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: handle oversized documents with one pageable truncation contract (#20004)

YuTengjingf1c5847ff162
diff --git a/.agents/skills/deep-review/references/dimensions/compatibility.md b/.agents/skills/deep-review/references/dimensions/compatibility.md
index b780371e7a2..83d11a60087 100644
--- a/.agents/skills/deep-review/references/dimensions/compatibility.md
+++ b/.agents/skills/deep-review/references/dimensions/compatibility.md
@@ -19,6 +19,7 @@ The same change must work across every surface this product ships to. Authors (a
| Deployment | Vercel (serverless: no local fs persistence, execution time limits) vs Docker (long-lived process) |
| Edition | open-source self-hosted (business slots return safe no-op defaults) vs cloud (commercial overrides active) |
| Tenancy | personal context (`workspaceId === null`) vs workspace context (workspace-scoped data, permissions, member sharing) |
+| Tool mode | agent / chat / custom (pinned tools) / exclusive-tool or goal turns / legacy client tool engine / share visitor |
## Quick checklist
@@ -32,6 +33,7 @@ The same change must work across every surface this product ships to. Authors (a
- Workspace-blind logic: new data reads/writes, permission checks, or list scoping that silently assume the personal context — must respect the active workspace scope (`useActiveWorkspaceId` / `workspaceSlug`) or be explicitly personal-only by design
- Cloud-only assumption: logic that only works when a business slot has its cloud override — must still function against the slot's open-source no-op default (feature hidden or gracefully degraded, not broken)
- Renamed backend route paths (`src/app/(backend)/webapi/...`) or auth surfaces (`src/app/spa-auth/...`, `src/routes/auth/...`), or changed `@lobechat/business-*` exports — downstream deployments override/extend these paths; flag so they can adapt
+- Prompt text that promises a tool ("call readX to continue", "use tool Y") decided apart from the final tool set — the tool may be missing in custom mode, exclusive-tool / goal turns, the legacy client tool engine, share-visitor allowlists, or models without function calling. Gate the promise on the final enabled tool ids that reach the model (e.g. `toolsConfig.tools` in `MessagesEngine`), not on the signal that enabled the tool, and require tests for both the tool-present and tool-absent prompt
- Dependency major bumps (`next`, `drizzle-orm`, ...) — downstream lockstep required; call out in the PR description
## Rule sources (deep mode: read before reviewing)
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 8dedd092f8a..b702f4b950c 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -29,6 +29,8 @@ import {
type LocalFilePreviewResult,
type LocalFilePreviewUrlParams,
type LocalFilePreviewUrlResult,
+ type LocalFileStats,
+ type LocalFileStatsParams,
type LocalMoveFilesResultItem,
type LocalReadFileParams,
type LocalReadFileResult,
@@ -70,6 +72,7 @@ import {
writeLocalFile,
} from '@lobechat/local-file-shell/file';
import type { FileResult, SearchOptions } from '@lobechat/local-file-shell/types';
+import { isUtf16Buffer, sniffBinaryBuffer } from '@lobechat/utils/isBinaryContent';
import { resolveMimeType } from '@lobechat/utils/mimeType';
import { dialog, shell } from 'electron';
@@ -151,6 +154,12 @@ const resolvePathWithScope = (inputPath: string, scope: string): string =>
const isWithinSafePathPrefixes = (targetPath: string, prefixes: readonly string[]): boolean =>
prefixes.some((prefix) => targetPath === prefix || targetPath.startsWith(`${prefix}${path.sep}`));
+/** Bytes sampled to decide whether a file is text before counting its lines. */
+const LOCAL_FILE_SNIFF_BYTES = 8 * 1024;
+
+/** Files above this size skip line counting so inserting a reference stays fast. */
+const LOCAL_FILE_LINE_COUNT_MAX_BYTES = 256 * 1024 * 1024;
+
const resolveNearestExistingRealPath = async (targetPath: string): Promise<string | undefined> => {
let currentPath = targetPath;
@@ -436,6 +445,55 @@ export default class LocalFileCtr extends ControllerModule {
return hash.digest('hex');
}
+ /**
+ * Size, MIME type, and line count of a local file, attached to `<localFile>` references so the
+ * model knows whether to read the file whole or in windows. Lines are counted by streaming, so
+ * memory stays flat; binary files, UTF-16 files and files above
+ * {@link LOCAL_FILE_LINE_COUNT_MAX_BYTES} skip it. UTF-16 is skipped because counting `0x0a` bytes
+ * also counts code units such as U+0A00-U+0AFF, so the number would be wrong rather than missing.
+ */
+ @IpcMethod()
+ async getLocalFileStats({ path: filePath }: LocalFileStatsParams): Promise<LocalFileStats> {
+ const fileStat = await stat(filePath);
+ if (!fileStat.isFile()) return { size: fileStat.size };
+
+ let head: Buffer | undefined;
+ let lineCount: number | undefined;
+ let lastByte: number | undefined;
+
+ for await (const chunk of createReadStream(filePath)) {
+ const buffer = chunk as Buffer;
+ if (!head) {
+ head = buffer.subarray(0, LOCAL_FILE_SNIFF_BYTES);
+ if (
+ sniffBinaryBuffer(head).isBinary ||
+ isUtf16Buffer(head) ||
+ fileStat.size > LOCAL_FILE_LINE_COUNT_MAX_BYTES
+ ) {
+ break;
+ }
+ lineCount = 0;
+ }
+ for (
+ let index = buffer.indexOf(0x0a);
+ index !== -1;
+ index = buffer.indexOf(0x0a, index + 1)
+ ) {
+ lineCount! += 1;
+ }
+ lastByte = buffer.at(-1);
+ }
+
+ // A final line without a trailing newline still counts as a line.
+ if (lineCount !== undefined && lastByte !== undefined && lastByte !== 0x0a) lineCount += 1;
+
+ const mimeType = await resolveMimeType(filePath, head ?? new Uint8Array()).catch(
+ () => undefined,
+ );
+
+ return { lineCount, mimeType: mimeType || undefined, size: fileStat.size };
+ }
+
@IpcMethod()
async readFile(params: LocalReadFileParams): Promise<LocalReadFileResult> {
logger.debug('Starting to read file:', {
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.getLocalFileStats.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.getLocalFileStats.test.ts
new file mode 100644
index 00000000000..ac2a2d6541a
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.getLocalFileStats.test.ts
@@ -0,0 +1,87 @@
+import fs from 'node:fs';
+import { mkdir, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type App } from '@/core/App';
+
+import LocalFileCtr from '../LocalFileCtr';
+
+vi.mock('electron', () => ({
+ dialog: { showOpenDialog: vi.fn(), showSaveDialog: vi.fn() },
+ ipcMain: { handle: vi.fn() },
+ shell: { openPath: vi.fn() },
+}));
+
+vi.mock('execa', () => ({ execa: vi.fn() }));
+vi.mock('@/utils/net-fetch', () => ({ netFetch: vi.fn() }));
+vi.mock('@/utils/file-system', () => ({ makeSureDirExist: vi.fn() }));
+
+const mockApp = {
+ appStoragePath: '/mock/app/storage',
+ getService: vi.fn(),
+ toolDetectorManager: { getBestTool: vi.fn(() => null) },
+} as unknown as App;
+
+describe('LocalFileCtr — getLocalFileStats', () => {
+ const tmpDir = path.join(os.tmpdir(), 'localfilectr-stats-test-' + process.pid);
+
+ beforeEach(async () => {
+ await mkdir(tmpDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { force: true, recursive: true });
+ });
+
+ it('reports size and line count for a text file', async () => {
+ const filePath = path.join(tmpDir, 'data.csv');
+ const content = Array.from({ length: 200_000 }, (_, index) => `row,${index}`).join('\n');
+ await writeFile(filePath, content);
+
+ const stats = await new LocalFileCtr(mockApp).getLocalFileStats({ path: filePath });
+
+ expect(stats).toMatchObject({ lineCount: 200_000, size: Buffer.byteLength(content) });
+ });
+
+ it('does not count an extra line after a trailing newline', async () => {
+ const filePath = path.join(tmpDir, 'notes.txt');
+ await writeFile(filePath, 'a\nb\n');
+
+ const stats = await new LocalFileCtr(mockApp).getLocalFileStats({ path: filePath });
+
+ expect(stats.lineCount).toBe(2);
+ });
+
+ it('skips line counting for binary files', async () => {
+ const filePath = path.join(tmpDir, 'blob.bin');
+ await writeFile(filePath, Buffer.from([0x00, 0x0a, 0x01, 0x0a, 0x00]));
+
+ const stats = await new LocalFileCtr(mockApp).getLocalFileStats({ path: filePath });
+
+ expect(stats.lineCount).toBeUndefined();
+ expect(stats.size).toBe(5);
+ });
+
+ it('skips line counting for UTF-16 files', async () => {
+ const filePath = path.join(tmpDir, 'export.csv');
+ const content = Buffer.concat([
+ Buffer.from([0xff, 0xfe]),
+ Buffer.from('a,b\nc,d\n', 'utf16le'),
+ ]);
+ await writeFile(filePath, content);
+
+ const stats = await new LocalFileCtr(mockApp).getLocalFileStats({ path: filePath });
+
+ expect(stats.lineCount).toBeUndefined();
+ expect(stats.size).toBe(content.length);
+ });
+
+ it('rejects when the file does not exist', async () => {
+ await expect(
+ new LocalFileCtr(mockApp).getLocalFileStats({ path: path.join(tmpDir, 'missing') }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 7e8d106e800..0d07118a0cf 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -5,7 +5,8 @@ import type {
ToolTransport,
ToolWorkRegistration,
} from '@lobechat/agent-runtime';
-import { executeToolWithRetry } from '@lobechat/agent-runtime';
+import { executeToolWithRetry, selectOperationToolSet } from '@lobechat/agent-runtime';
+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import {
buildExecuteToolAttributes,
@@ -119,6 +120,10 @@ export class ServerToolTransport implements ToolTransport {
const { operationId, serverDB, stepIndex, streamManager, toolExecutionService, userId } =
this.ctx;
const operationLogId = `${operationId}:${stepIndex}`;
+ const enabledToolIds = [
+ ...selectOperationToolSet(context.state).enabledToolIds,
+ ...(context.state.activatedStepTools ?? []).map((activation) => activation.id),
+ ];
const executeToolSpan = agentRuntimeTracer.startSpan(executeToolSpanName(context.toolName), {
attributes: buildExecuteToolAttributes({
operationId,
@@ -268,6 +273,7 @@ export class ServerToolTransport implements ToolTransport {
taskId: context.state.origin?.taskId,
threadId: context.state.origin?.threadId,
toolCallId: chatToolPayload.id,
+ enabledToolIds,
toolManifestMap: context.effectiveManifestMap,
toolMessageId: context.toolMessageId,
toolResultMaxLength: context.toolResultMaxLength,
@@ -305,6 +311,7 @@ export class ServerToolTransport implements ToolTransport {
};
const executionResult = await archiveRuntimeToolResult(resultWithExecutionTime, {
agentId: context.state.origin?.agentId,
+ canReadArchive: enabledToolIds.includes(AgentDocumentsIdentifier),
identifier: chatToolPayload.identifier,
limit: context.toolResultMaxLength,
serverDB,
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
index eb08a560100..f9e038b105c 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
@@ -146,11 +146,19 @@ export const buildServerCallLlmContext = async ({
knowledge: {
fileContents: agentConfig.files
?.filter((file: { enabled?: boolean | null }) => file.enabled === true)
- .map((file: { content?: string | null; id?: string; name?: string }) => ({
- content: file.content ?? '',
- fileId: file.id ?? '',
- filename: file.name ?? '',
- })),
+ .map(
+ (file: {
+ content?: string | null;
+ id?: string;
+ name?: string;
+ originalCharCount?: number;
+ }) => ({
+ content: file.content ?? '',
+ fileId: file.id ?? '',
+ filename: file.name ?? '',
+ originalChars: file.originalCharCount,
+ }),
+ ),
knowledgeBases: agentConfig.knowledgeBases
?.filter((knowledgeBase: { enabled?: boolean | null }) => knowledgeBase.enabled === true)
.map((knowledgeBase: { id?: string; name?: string }) => ({
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index f3b3be4369a..f818f52cd10 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -58,6 +58,7 @@ export const archiveRuntimeToolResult = async (
result: ToolExecutionResultResponse,
{
agentId,
+ canReadArchive,
identifier,
limit,
serverDB,
@@ -67,6 +68,7 @@ export const archiveRuntimeToolResult = async (
workspaceId,
}: {
agentId?: string | null;
+ canReadArchive?: boolean;
identifier?: string;
limit?: number;
serverDB: LobeChatDatabase;
@@ -78,6 +80,7 @@ export const archiveRuntimeToolResult = async (
): Promise<ToolExecutionResultResponse> => {
const archive = await archiveToolResultIfNeeded({
agentId,
+ canReadArchive,
content: result.content,
identifier,
limit,
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
index 852ef3bc05d..32322fbdb40 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
@@ -111,6 +111,7 @@ export const createServerAgentToolsEngine = (
executionPlan,
globalMemoryEnabled = false,
hasEnabledKnowledgeBases = false,
+ hasOversizedFiles = false,
isBotConversation = false,
isGroupSupervisor = false,
manifestContext,
@@ -158,6 +159,7 @@ export const createServerAgentToolsEngine = (
disabledPluginIds,
executionTarget,
hasEnabledKnowledgeBases,
+ hasOversizedFiles,
isBotConversation,
isGroupSupervisor,
// Local tools reach a machine only through an online, auto-activated
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts
index dbe263a0315..f66307dd358 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts
@@ -120,6 +120,8 @@ export interface ServerCreateAgentToolsEngineParams {
globalMemoryEnabled?: boolean;
/** Whether agent has enabled knowledge bases */
hasEnabledKnowledgeBases?: boolean;
+ /** Whether an attached or agent-assigned file is previewed because it is too long to inline */
+ hasOversizedFiles?: boolean;
/** Whether the request originates from a bot conversation (auto-enables message tool) */
isBotConversation?: boolean;
/**
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index 9dd86d6ddbe..ea2350417cf 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -24,6 +24,7 @@ import {
resolveDiscoveryPool,
resolveInvocationToolIds,
} from '@lobechat/mecha';
+import { FILE_INLINE_MAX_CHARS, isOversizedFileContent } from '@lobechat/prompts';
import type {
ChatTopicBotContext,
FrozenCredentialFacts,
@@ -45,6 +46,7 @@ import { AiProviderModel } from '@/database/models/aiProvider';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { ConnectorModel } from '@/database/models/connector';
import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import type { MessageModel } from '@/database/models/message';
import type { PluginModel } from '@/database/models/plugin';
@@ -506,6 +508,31 @@ export const discoverTools = async (
return fileRecords.map((file) => file.fileType || '');
}
+ /**
+ * Whether this turn sends any file as a truncated preview (see `previewLongFileContent`):
+ * an enabled agent file, or a parsed attachment of this turn or topic, over the inline limit.
+ * Enables the attachments tool in the modes whose rules include it (agent / chat). The preview
+ * only names `readAttachment` when the final tool set carries it (see `MessagesEngine`), so
+ * custom / exclusive tool turns and share visitors fall back to a plain preview.
+ */
+ async function readHasOversizedFiles(): Promise<boolean> {
+ const hasOversizedAgentFile = agentConfig.files?.some(
+ (file: { content?: string | null; enabled?: boolean | null; originalCharCount?: number }) =>
+ file.enabled === true &&
+ isOversizedFileContent(file.content?.length ?? 0, file.originalCharCount),
+ );
+ if (hasOversizedAgentFile) return true;
+ if (!topicId && !attachedFileIds?.length) return false;
+
+ return traceDiscoveryStage('oversized_files', () =>
+ new DocumentModel(deps.db, deps.userId, deps.workspaceId).hasFileDocumentsOverChars({
+ fileIds: attachedFileIds,
+ minChars: FILE_INLINE_MAX_CHARS,
+ topicId,
+ }),
+ );
+ }
+
// Every other read this send needs, started together. They hit different
// backends — Postgres rows, the Market's live skill discovery, the device
// gateway — and none of them feeds another, so the user waits for the slowest
@@ -524,6 +551,7 @@ export const discoverTools = async (
).catch(() => false), // non-critical
),
attachedFileTypes: started(readAttachedFileTypes()),
+ oversizedFiles: started(readHasOversizedFiles().catch(() => false)), // non-critical
composioManifests: started(
traceDiscoveryStage('composio', () =>
deps.composioService.getComposioManifests(resolvedAgentId),
@@ -777,6 +805,7 @@ export const discoverTools = async (
false;
hasAgentDocuments = await toolReads.agentDocuments;
+ const hasOversizedFiles = await toolReads.oversizedFiles;
log('execAgent: isBotConversation=%s', isBotConversation);
@@ -1050,6 +1079,7 @@ export const discoverTools = async (
executionPlan,
globalMemoryEnabled,
hasEnabledKnowledgeBases,
+ hasOversizedFiles,
isBotConversation,
isGroupSupervisor,
modelAbilities,
diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.ts
index f43ecd3978b..ad80cc874f5 100644
--- a/apps/server/src/services/document/__tests__/index.test.ts
+++ b/apps/server/src/services/document/__tests__/index.test.ts
@@ -12,7 +12,7 @@ import { EditLockService } from '../../editLock';
import { FileService } from '../../file';
import { publishResourceEvent } from '../../resourceEvents';
import { DocumentHistoryService } from '../history';
-import { DocumentService } from '../index';
+import { capParsedFileDocument, DocumentService, PARSED_FILE_CONTENT_MAX_CHARS } from '../index';
vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));
vi.mock('@/database/models/document');
@@ -1836,6 +1836,34 @@ describe('DocumentService', () => {
expect(result).toEqual({ id: 'doc-1', title: 'My Doc' });
});
+ it('strips page tags before capping an oversized PDF', async () => {
+ const page = 'x'.repeat(1000);
+ const pageCount = Math.ceil(PARSED_FILE_CONTENT_MAX_CHARS / page.length) + 2;
+ const content = Array.from(
+ { length: pageCount },
+ (_, index) => `<page number="${index + 1}">${page}</page>`,
+ ).join('');
+ vi.mocked(loadFile).mockResolvedValue({
+ content,
+ fileType: 'pdf',
+ metadata: {},
+ pages: undefined,
+ totalCharCount: content.length,
+ totalLineCount: 1,
+ } as any);
+ mockDocumentModel.create.mockResolvedValue({ id: 'doc-1' });
+
+ await service.parseDocument('file-1');
+
+ const created = mockDocumentModel.create.mock.calls[0][0];
+ expect(created.content).toHaveLength(PARSED_FILE_CONTENT_MAX_CHARS);
+ expect(created.content).not.toContain('<page');
+ expect(created.metadata).toMatchObject({
+ originalCharCount: page.length * pageCount,
+ truncated: true,
+ });
+ });
+
it('should use filename as title when metadata has no title', async () => {
vi.mocked(loadFile).mockResolvedValue({
content: 'Content',
@@ -1904,6 +1932,29 @@ describe('DocumentService', () => {
});
});
+ it('should cap oversized parsed text before storing it', async () => {
+ vi.mocked(loadFile).mockResolvedValue({
+ content: 'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS + 10),
+ fileType: 'txt',
+ metadata: {},
+ pages: [{ content: 'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS + 10) }],
+ totalCharCount: PARSED_FILE_CONTENT_MAX_CHARS + 10,
+ totalLineCount: 1,
+ } as any);
+ mockDocumentModel.create.mockResolvedValue({ id: 'doc-1' });
+
+ await service.parseFile('file-1');
+
+ const created = mockDocumentModel.create.mock.calls.at(-1)![0];
+ expect(created.content).toHaveLength(PARSED_FILE_CONTENT_MAX_CHARS);
+ expect(created.totalCharCount).toBe(PARSED_FILE_CONTENT_MAX_CHARS);
+ expect(created.pages).toBeUndefined();
+ expect(created.metadata).toMatchObject({
+ originalCharCount: PARSED_FILE_CONTENT_MAX_CHARS + 10,
+ truncated: true,
+ });
+ });
+
it('should parse a file and create document record with pages', async () => {
vi.mocked(loadFile).mockResolvedValue({
content: 'Full file content',
@@ -2129,3 +2180,72 @@ describe('DocumentService', () => {
});
});
});
+
+describe('capParsedFileDocument', () => {
+ const fileDocument = (content: string, fileType = 'txt') =>
+ ({
+ content,
+ fileType,
+ filename: 'big.txt',
+ metadata: { source: 'big.txt' },
+ pages: [{ charCount: content.length, lineCount: 1, metadata: {}, pageContent: content }],
+ totalCharCount: content.length,
+ totalLineCount: 1,
+ }) as unknown as Parameters<typeof capParsedFileDocument>[0];
+
+ it('keeps parsed text within the limit untouched', () => {
+ const input = fileDocument('hello');
+
+ expect(capParsedFileDocument(input)).toBe(input);
+ });
+
+ it('does not split a surrogate pair at the cap', () => {
+ const content = `${'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 1)}🐛`;
+ const result = capParsedFileDocument(fileDocument(content));
+
+ expect(result.content).toBe('a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 1));
+ });
+
+ it('closes a PDF page cut by the cap without exceeding it', () => {
+ const page = (n: number, body: string) => `<page pageNumber="${n}">\n${body}\n</page>\n`;
+ const content = page(1, 'first') + page(2, 'b'.repeat(PARSED_FILE_CONTENT_MAX_CHARS));
+ const result = capParsedFileDocument(fileDocument(content, 'pdf'));
+
+ expect(result.content.startsWith(page(1, 'first'))).toBe(true);
+ expect(result.content.endsWith('b\n</page>')).toBe(true);
+ expect(result.content.length).toBeLessThanOrEqual(PARSED_FILE_CONTENT_MAX_CHARS);
+ expect(result.content.match(/<page /g)).toHaveLength(2);
+ expect(result.content.match(/<\/page>/g)).toHaveLength(2);
+ });
+
+ it('drops a page opening tag cut by the cap', () => {
+ const first = `<page pageNumber="1">\n${'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 40)}\n</page>\n`;
+ const result = capParsedFileDocument(
+ fileDocument(`${first}<page pageNumber="2">\nsecond\n</page>`, 'pdf'),
+ );
+
+ expect(result.content).toBe(first.trimEnd());
+ });
+
+ it('leaves a literal page tag in non-PDF text untouched', () => {
+ const content = `<page title="example">\n${'c'.repeat(PARSED_FILE_CONTENT_MAX_CHARS)}`;
+ const result = capParsedFileDocument(fileDocument(content));
+
+ expect(result.content).toBe(content.slice(0, PARSED_FILE_CONTENT_MAX_CHARS));
+ });
+
+ it('truncates oversized parsed text and drops the duplicated pages', () => {
+ const originalLength = PARSED_FILE_CONTENT_MAX_CHARS + 10;
+ const result = capParsedFileDocument(fileDocument(`${'a\n'.repeat(originalLength / 2)}`));
+
+ expect(result.content).toHaveLength(PARSED_FILE_CONTENT_MAX_CHARS);
+ expect(result.pages).toBeUndefined();
+ expect(result.totalCharCount).toBe(PARSED_FILE_CONTENT_MAX_CHARS);
+ expect(result.totalLineCount).toBe(PARSED_FILE_CONTENT_MAX_CHARS / 2 + 1);
+ expect(result.metadata).toMatchObject({
+ originalCharCount: originalLength,
+ source: 'big.txt',
+ truncated: true,
+ });
+ });
+});
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index 6af56a5fd81..d6e5fe23359 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -5,6 +5,7 @@ import { type LobeChatDatabase } from '@lobechat/database';
import { type DocumentItem } from '@lobechat/database/schemas';
import { documents, files } from '@lobechat/database/schemas';
import { loadFile, UnsupportedFileTypeError } from '@lobechat/file-loaders';
+import { sliceHead } from '@lobechat/prompts/textWindow';
import type { DocumentAccessScope, FileAccessScope } from '@lobechat/types';
import {
ordinaryDocumentAccessScope,
@@ -45,6 +46,61 @@ import type {
const log = debug('lobe-chat:service:document');
+/**
+ * Upper bound, in characters, of parsed file text stored in `documents.content`.
+ *
+ * Parsing raw CSV exports, logs, or sparse spreadsheets can yield 100+ MiB of text. Rows that large
+ * slow every read of the document, overflow the model context when attached, and cannot be synced
+ * to full-text search. The original file stays in storage for tools that process it directly.
+ */
+export const PARSED_FILE_CONTENT_MAX_CHARS = 5_000_000;
+
+type ParsedFileDocument = Awaited<ReturnType<typeof loadFile>>;
+
+const PAGE_CLOSE_TAG = '\n</page>';
+
+/**
+ * PDF loaders wrap each page in `<page ...>...</page>`. A cut inside a page leaves an opening tag
+ * with no closing tag (or a half-written tag at the tail), which previews and `readAttachment`
+ * would expose as malformed markup. Close the cut page, or drop a half-written opening tag, while
+ * staying within the cap. Page tags are kept rather than stripped so page numbers survive.
+ */
+const closeCutPage = (content: string): string => {
+ const open = content.lastIndexOf('<page');
+ if (open === -1 || open < content.lastIndexOf('</page>')) return content;
+
+ const openEnd = content.indexOf('>', open);
+ if (openEnd === -1) return content.slice(0, open).trimEnd();
+
+ const bodyEnd = Math.max(openEnd + 1, content.length - PAGE_CLOSE_TAG.length);
+ const body = content.slice(0, bodyEnd).replace(/<\/?(?:p(?:a(?:ge?)?)?)?$/, '');
+ return `${body}${PAGE_CLOSE_TAG}`;
+};
+
+/**
+ * Truncates oversized parsed text before it is stored. `pages` repeats the full text, so it is
+ * dropped for truncated documents; `metadata` records the original length.
+ */
+export const capParsedFileDocument = (fileDocument: ParsedFileDocument): ParsedFileDocument => {
+ if (fileDocument.content.length <= PARSED_FILE_CONTENT_MAX_CHARS) return fileDocument;
+
+ const head = sliceHead(fileDocument.content, PARSED_FILE_CONTENT_MAX_CHARS);
+ // Only the PDF loader emits page wrappers; other text may contain a literal `<page` to keep.
+ const content = fileDocument.fileType === 'pdf' ? closeCutPage(head) : head;
+ return {
+ ...fileDocument,
+ content,
+ metadata: {
+ ...fileDocument.metadata,
+ originalCharCount: fileDocument.content.length,
+ truncated: true,
+ },
+ pages: undefined,
+ totalCharCount: content.length,
+ totalLineCount: content.split('\n').length,
+ };
+};
+
const normalizeParseFileError = (error: unknown) => {
if (error instanceof UnsupportedFileTypeError) {
return new TRPCError({
@@ -813,8 +869,17 @@ export class DocumentService {
log(`${logPrefix} Starting to parse file as document, path: ${filePath}`);
try {
- // Use loadFile to load file content
- const fileDocument = await loadFile(filePath);
+ const loaded = await loadFile(filePath);
+ // Strip <page> wrappers before capping: a cut inside a page would leave an opening tag with
+ // no closing tag, which the strip regex can no longer match.
+ const fileDocument = capParsedFileDocument(
+ loaded.content.includes('<page')
+ ? {
+ ...loaded,
+ content: loaded.content.replaceAll(/<page[^>]*>([\S\s]*?)<\/page>/g, '$1').trim(),
+ }
+ : loaded,
+ );
log(`${logPrefix} File parsed successfully %O`, {
fileType: fileDocument.fileType,
@@ -827,11 +892,7 @@ export class DocumentService {
file.name.replace(/\.(pdf|docx?|md|markdown)$/i, '') ||
'Untitled';
- // Clean up content - remove <page> tags if present
- let cleanContent = fileDocument.content;
- if (cleanContent.includes('<page')) {
- cleanContent = cleanContent.replaceAll(/<page[^>]*>([\S\s]*?)<\/page>/g, '$1').trim();
- }
+ const cleanContent = fileDocument.content;
const document = await this.documentModel.create({
content: cleanContent,
@@ -885,7 +946,7 @@ export class DocumentService {
try {
// Use loadFile to load file content
- const fileDocument = await loadFile(filePath);
+ const fileDocument = capParsedFileDocument(await loadFile(filePath));
log(`${logPrefix} File parsed successfully %O`, {
fileType: fileDocument.fileType,
diff --git a/apps/server/src/services/file/resolveAttachments.test.ts b/apps/server/src/services/file/resolveAttachments.test.ts
index 156e9e324ea..82cd0002fa7 100644
--- a/apps/server/src/services/file/resolveAttachments.test.ts
+++ b/apps/server/src/services/file/resolveAttachments.test.ts
@@ -125,4 +125,25 @@ describe('resolveAttachmentMetadata', () => {
expect.objectContaining({ content: 'Visitor report', id: 'file-visitor-pdf' }),
]);
});
+
+ it('reports the original size of text that was cut at parse time', async () => {
+ mocks.findByIds.mockResolvedValue([
+ { fileType: 'text/csv', id: 'file-big', name: 'big.csv', size: 42, url: 'files/big.csv' },
+ ]);
+ mocks.getFullFileUrl.mockResolvedValue('https://storage.example.com/files/big.csv');
+ mocks.parseFile.mockResolvedValue({
+ content: 'head',
+ metadata: { originalCharCount: 9_000_000, truncated: true },
+ });
+
+ const result = await resolveAttachmentsByFileIds({
+ db: {} as LobeChatDatabase,
+ fileIds: ['file-big'],
+ userId: 'user-1',
+ });
+
+ expect(result.fileList).toEqual([
+ expect.objectContaining({ content: 'head', id: 'file-big', originalCharCount: 9_000_000 }),
+ ]);
+ });
});
diff --git a/apps/server/src/services/file/resolveAttachments.ts b/apps/server/src/services/file/resolveAttachments.ts
index 1f24328fe98..eef7ecf3856 100644
--- a/apps/server/src/services/file/resolveAttachments.ts
+++ b/apps/server/src/services/file/resolveAttachments.ts
@@ -11,6 +11,7 @@ import { readAudioDurationMs } from '@lobechat/utils/audio';
import debug from 'debug';
import { FileModel } from '@/database/models/file';
+import { readOriginalCharCount } from '@/database/utils/parsedDocument';
import { DocumentService } from '@/server/services/document';
import { FileService, getFileProxyUrl } from '@/server/services/file';
@@ -114,14 +115,16 @@ export const resolveAttachmentsByFileIds = async ({
return { file, fileType, id, resolvedUrl };
}
let content: string | undefined;
+ let originalCharCount: number | undefined;
let parseError: unknown;
try {
const document = await documentService.parseFile(file.id, fileAccessScope);
content = document.content ?? undefined;
+ originalCharCount = readOriginalCharCount(document.metadata);
} catch (error) {
parseError = error;
}
- return { content, file, fileType, id, parseError, resolvedUrl };
+ return { content, file, fileType, id, originalCharCount, parseError, resolvedUrl };
}),
);
@@ -160,6 +163,7 @@ export const resolveAttachmentsByFileIds = async ({
fileType: fileType || 'application/octet-stream',
id: file.id,
name: file.name || 'file',
+ originalCharCount: entry.originalCharCount,
size: file.size ?? 0,
url: resolvedUrl,
});
diff --git a/apps/server/src/services/knowledgeBase/index.ts b/apps/server/src/services/knowledgeBase/index.ts
index dc13bd05dde..2c656ac8701 100644
--- a/apps/server/src/services/knowledgeBase/index.ts
+++ b/apps/server/src/services/knowledgeBase/index.ts
@@ -14,6 +14,7 @@ import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import type { FtsSearchKnowledgeBaseDocumentHit } from '@/database/repositories/ftsSearch';
import { knowledgeBaseFiles } from '@/database/schemas';
+import { readOriginalCharCount } from '@/database/utils/parsedDocument';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { getServerDefaultFilesConfig } from '@/server/globalConfig';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
@@ -26,6 +27,8 @@ export interface FileContentResult {
fileId: string;
filename: string;
metadata?: Record<string, any> | null;
+ /** Original character count when the stored text was cut at parse time. */
+ originalCharCount?: number;
preview?: string;
totalCharCount?: number;
totalLineCount?: number;
@@ -248,6 +251,7 @@ export class KnowledgeBaseSearchService {
fileId: id,
filename: doc.title || doc.filename || 'Untitled',
metadata: doc.metadata,
+ originalCharCount: readOriginalCharCount(doc.metadata),
preview: lines.slice(0, 5).join('\n'),
totalCharCount: content.length,
totalLineCount: lines.length,
@@ -288,6 +292,7 @@ export class KnowledgeBaseSearchService {
fileId: id,
filename: file.name,
metadata: document.metadata,
+ originalCharCount: readOriginalCharCount(document.metadata),
preview: lines.slice(0, 5).join('\n'),
totalCharCount: content.length,
totalLineCount: lines.length,
diff --git a/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts b/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts
index da1df64f400..2a01364a2e3 100644
--- a/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts
@@ -194,13 +194,43 @@ describe('archiveToolResultIfNeeded', () => {
expect(mockTopicDocumentModel.associate).not.toHaveBeenCalled();
});
+ it('ends a multi-line archive preview with the readDocument call for the next window', async () => {
+ const content = 'line 1\nline 2\nline 3';
+ mockVfsService.read.mockResolvedValue({ content });
+
+ const result = await archive({ content, limit: 14 });
+
+ expect(result.content).toContain(
+ 'line 1\nline 2\n[Showing lines 1-2 of 3 lines, 20 characters. To continue, call lobe-agent-documents readDocument with id="agent-doc-1", format="markdown" and offset=3.]',
+ );
+ });
+
+ it('tells the model to re-read a cut line that fits the readDocument budget', async () => {
+ const result = await archive();
+
+ expect(result.content).toContain(
+ 'Line 1 is 10 characters long and was cut at 5. To read it in full and continue, call lobe-agent-documents readDocument with id="agent-doc-1", format="markdown" and offset=1.',
+ );
+ });
+
+ it('truncates without archiving or naming readDocument when the run cannot call it', async () => {
+ const result = await archive({ canReadArchive: false });
+
+ expect(result.archived).toBe(false);
+ expect(result.content).toContain('01234');
+ expect(result.content).not.toContain('readDocument');
+ expect(result.content).not.toContain('lobe-agent-documents');
+ expect(db.transaction).not.toHaveBeenCalled();
+ expect(AgentDocumentVfsService).not.toHaveBeenCalled();
+ });
+
it('falls back to truncation without archive context', async () => {
const result = await archive({ serverDB: undefined });
expect(result.archived).toBe(false);
expect(result.archivePath).toBeUndefined();
expect(result.content).toContain('01234');
- expect(result.content).toContain('Content truncated');
+ expect(result.content).toContain('[Showing lines 1-1 of 1 lines');
expect(result.content).not.toContain('Archive failed');
expect(AgentDocumentVfsService).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index a1571774168..32edc6cc7c1 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -316,7 +316,7 @@ describe('ToolExecutionService', () => {
);
expect(result.content).toContain('01234');
- expect(result.content).toContain('Content truncated');
+ expect(result.content).toContain('[Showing lines 1-');
});
/**
@@ -352,7 +352,7 @@ describe('ToolExecutionService', () => {
const message = (result.error as { message: string }).message;
expect(message.length).toBeLessThan(5000);
expect(message).toContain('Command failed with exit code 1');
- expect(message).toContain('Content truncated');
+ expect(message).toContain('[Showing lines 1-');
// The archival opt-out covers the LLM-facing content, never the error.
expect(result.content).toBe(runawayOutput);
});
diff --git a/apps/server/src/services/toolExecution/archiveToolResult.ts b/apps/server/src/services/toolExecution/archiveToolResult.ts
index 000a9990189..769ac8fde78 100644
--- a/apps/server/src/services/toolExecution/archiveToolResult.ts
+++ b/apps/server/src/services/toolExecution/archiveToolResult.ts
@@ -1,6 +1,12 @@
import { createHash } from 'node:crypto';
+import { MAX_READ_DOCUMENT_CONTENT_CHARS } from '@lobechat/builtin-tool-agent-documents';
import type { LobeChatDatabase } from '@lobechat/database';
+import {
+ appendTextWindowNotice,
+ formatTextWindowNotice,
+ type TextWindow,
+} from '@lobechat/prompts/textWindow';
import debug from 'debug';
import { sql } from 'drizzle-orm';
@@ -9,7 +15,7 @@ import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';
import {
ARCHIVE_BYPASS_IDENTIFIERS,
DEFAULT_TOOL_RESULT_MAX_LENGTH,
- truncateToolResult,
+ sliceToolResult,
} from '@/server/utils/truncateToolResult';
import { TOOL_RESULTS_DIR_NAME } from './constants';
@@ -35,6 +41,12 @@ export interface ToolResultArchiveOutcome {
interface ArchiveToolResultParams {
agentId?: string | null;
+ /**
+ * Whether the run can call `lobe-agent-documents` readDocument, the only way to page an archive.
+ * When false, nothing is persisted and the model gets the truncated window with a notice that
+ * names no tool. Defaults to true for callers that cannot resolve the run's tool set.
+ */
+ canReadArchive?: boolean;
content: string;
identifier?: string;
limit?: number;
@@ -79,20 +91,31 @@ const hashArchiveContent = (content: string) =>
const getErrorMessage = (error: unknown) =>
error instanceof Error ? error.message : String(error || 'Unknown archive error');
+/**
+ * The model sees the leading window of the result plus the shared notice, whose continuation
+ * pages the archive through `readDocument` with the same line numbers.
+ */
const buildArchivedContent = (
- truncatedContent: string,
+ window: TextWindow,
archivePath: string,
agentDocumentId?: string,
) => {
+ const documentId = agentDocumentId ?? '<Agent Document ID>';
+ const notice = formatTextWindowNotice(window, {
+ continueFrom: (line) =>
+ `call lobe-agent-documents readDocument with id="${documentId}", format="markdown" and offset=${line}`,
+ continueMaxChars: MAX_READ_DOCUMENT_CONTENT_CHARS,
+ });
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.`;
+ return `${window.content}\n${notice}\nFull content archived to the agent-document VFS.\nPath: ${archivePath}\nAgent Document ID: ${agentDocumentIdHint}\nRead it with the lobe-agent-documents tool: apiName=readDocument, id=<Agent Document ID above>, format="markdown", and offset/limit to page by line. Do NOT activate cloud-sandbox or local-system file tools — this archive exists only inside the agent document tree.`;
};
export const archiveToolResultIfNeeded = async ({
agentId,
+ canReadArchive = true,
content,
identifier,
limit,
@@ -112,9 +135,10 @@ export const archiveToolResultIfNeeded = async ({
return { archived: false, content };
}
- const truncatedContent = truncateToolResult(content, maxLength);
+ const window = sliceToolResult(content, maxLength);
+ const truncatedContent = appendTextWindowNotice(window);
- if (!agentId || !topicId || !toolCallId || !serverDB || !userId) {
+ if (!canReadArchive || !agentId || !topicId || !toolCallId || !serverDB || !userId) {
return { archived: false, content: truncatedContent };
}
@@ -211,7 +235,7 @@ export const archiveToolResultIfNeeded = async ({
return {
archivePath: handle.archivePath,
archived: true,
- content: buildArchivedContent(truncatedContent, handle.archivePath, handle.agentDocumentId),
+ content: buildArchivedContent(window, handle.archivePath, handle.agentDocumentId),
};
} catch (error) {
const message = getErrorMessage(error);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/attachments.ts b/apps/server/src/services/toolExecution/serverRuntimes/attachments.ts
new file mode 100644
index 00000000000..5c1e74f7d68
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/attachments.ts
@@ -0,0 +1,31 @@
+import { AttachmentsIdentifier } from '@lobechat/builtin-tool-attachments';
+import { AttachmentsExecutionRuntime } from '@lobechat/builtin-tool-attachments/executionRuntime';
+
+import { KnowledgeBaseSearchService } from '@/server/services/knowledgeBase';
+
+import { type ServerRuntimeRegistration } from './types';
+
+/**
+ * Reads files through the same user/workspace/agent-visibility scope as `readKnowledge`, so an
+ * attachment preview can be paged without enabling the knowledge-base tool.
+ */
+export const attachmentsRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ const { userId, serverDB, agentVisibility, workspaceId } = context;
+ if (!userId || !serverDB) {
+ throw new Error('userId and serverDB are required for attachment reads');
+ }
+
+ const searchService = new KnowledgeBaseSearchService(
+ serverDB,
+ userId,
+ workspaceId,
+ agentVisibility,
+ );
+
+ return new AttachmentsExecutionRuntime({
+ getFileContents: (fileIds) => searchService.getFileContents(fileIds),
+ });
+ },
+ identifier: AttachmentsIdentifier,
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
index fcbe4a73b0c..d5b2ef17d7f 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
@@ -17,6 +17,7 @@ import { agentSignalFeedbackIntentRuntime } from './agentSignalFeedbackIntent';
import { agentSignalReflectionRuntime } from './agentSignalReflection';
import { agentSignalReviewRuntime } from './agentSignalReview';
import { agentSignalSkillManagementRuntime } from './agentSignalSkillManagement';
+import { attachmentsRuntime } from './attachments';
import { auvRuntime } from './auv';
import { briefRuntime } from './brief';
import { browserRuntime } from './browser';
@@ -95,6 +96,7 @@ registerRuntimes([
imageGenerationRuntime,
videoGenerationRuntime,
knowledgeBaseRuntime,
+ attachmentsRuntime,
webOnboardingRuntime,
lobeAgentRuntime,
selfFeedbackIntentRuntime,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts b/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts
index 7407256c6cb..a69a8602a13 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts
@@ -1,3 +1,4 @@
+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { WebBrowsingExecutionRuntime } from '@lobechat/builtin-tool-web-browsing/executionRuntime';
@@ -20,6 +21,7 @@ export const webBrowsingRuntime: ServerRuntimeRegistration = {
userId && serverDB ? await getUserChannelPreferences(serverDB, userId) : undefined;
return new WebBrowsingExecutionRuntime({
+ canReadSavedDocuments: !!context.enabledToolIds?.includes(AgentDocumentsIdentifier),
documentService: canSaveDocuments
? {
associateDocument: async (documentId) => {
@@ -29,7 +31,7 @@ export const webBrowsingRuntime: ServerRuntimeRegistration = {
context.workspaceId,
agentVisibility,
);
- await service.associateDocument(agentId, documentId);
+ return service.associateDocument(agentId, documentId);
},
createDocument: async (params) => {
// Same service the client trpc procedure uses — dedupe by URL,
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index c0fbf5bedd0..0bac8a7bff1 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -234,6 +234,11 @@ export interface ToolExecutionContext {
* a group chat turn; only GroupAgentBuilder tool methods read this.
*/
editingGroupId?: string;
+ /**
+ * Tool ids offered to the model in this run (operation tool set plus step activations). Lets a
+ * runtime name a follow-up tool in its result only when the model can actually call it.
+ */
+ enabledToolIds?: string[];
/**
* Legacy agent invocation callback forwarded from RuntimeExecutorContext.
* Kept for tool runtimes that still dispatch through exec_sub_agent style
diff --git a/apps/server/src/utils/__tests__/truncateToolResult.test.ts b/apps/server/src/utils/__tests__/truncateToolResult.test.ts
index 79b5b46b405..880d31c16ef 100644
--- a/apps/server/src/utils/__tests__/truncateToolResult.test.ts
+++ b/apps/server/src/utils/__tests__/truncateToolResult.test.ts
@@ -6,7 +6,7 @@ import { truncateToolResult, truncateToolResultWithState } from '../truncateTool
const validEmoji = '\uD83D\uDC1B';
const familyEmoji = '\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC67\u200D\uD83D\uDC66';
-const getTruncatedPortion = (value: string) => value.split('\n\n[Content truncated')[0];
+const getTruncatedPortion = (value: string) => value.split('\n[Showing lines')[0];
const endsWithHighSurrogate = (value: string) => {
const lastCharCode = value.charCodeAt(value.length - 1);
@@ -21,8 +21,17 @@ describe('truncateToolResult', () => {
it('truncates and appends a notice when over the limit', () => {
const result = truncateToolResult('0123456789', 5);
- expect(result.startsWith('01234')).toBe(true);
- expect(result).toContain('Content truncated');
+ expect(result).toBe(
+ '01234\n[Showing lines 1-1 of 1 lines, 10 characters. Line 1 is 10 characters long and was cut at 5; the rest of that line cannot be paged.]',
+ );
+ });
+
+ it('keeps whole leading lines and reports the lines left out', () => {
+ const result = truncateToolResult('line 1\nline 2\nline 3', 14);
+
+ expect(result).toBe(
+ 'line 1\nline 2\n[Showing lines 1-2 of 3 lines, 20 characters. Lines 3-3 were left out.]',
+ );
});
it('does not leave a lone high surrogate when the cutoff splits an emoji', () => {
@@ -31,7 +40,7 @@ describe('truncateToolResult', () => {
const result = truncateToolResult(content, limit);
const truncatedPortion = getTruncatedPortion(result);
- expect(result).toContain('[Content truncated:');
+ expect(result).toContain('was cut at');
expect(truncatedPortion).toBe(`prefix ${'a'.repeat(10)}`);
expect(endsWithHighSurrogate(truncatedPortion)).toBe(false);
expect(JSON.stringify(result)).not.toContain('\\ud83d"');
@@ -43,7 +52,7 @@ describe('truncateToolResult', () => {
const result = truncateToolResult(content, limit);
expect(result).toContain(validEmoji);
- expect(result).toContain('[Content truncated:');
+ expect(result).toContain('[Showing lines 1-1 of 1 lines');
});
it('never leaves a lone high surrogate inside a ZWJ-composed emoji at any cutoff', () => {
diff --git a/apps/server/src/utils/truncateToolResult.ts b/apps/server/src/utils/truncateToolResult.ts
index 5e663c5662e..0aabdf90f59 100644
--- a/apps/server/src/utils/truncateToolResult.ts
+++ b/apps/server/src/utils/truncateToolResult.ts
@@ -1,3 +1,9 @@
+import {
+ appendTextWindowNotice,
+ sliceTextWindow,
+ type TextWindow,
+} from '@lobechat/prompts/textWindow';
+
/**
* Shared utility for truncating tool execution results
* Used by both frontend tRPC routers and backend tool execution service
@@ -16,8 +22,15 @@ export const DEFAULT_TOOL_RESULT_MAX_LENGTH = 25_000;
export const ARCHIVE_BYPASS_IDENTIFIERS = new Set<string>(['lobe-agent-documents']);
/**
- * Truncate tool result content if it exceeds the maximum length
- * Adds a truncation notice to inform the LLM that content was cut off
+ * The leading window of an oversized tool result: whole lines up to `maxLength` characters, using
+ * the shared text-window contract so archived results can be paged with the same line numbers.
+ */
+export const sliceToolResult = (content: string, maxLength?: number): TextWindow =>
+ sliceTextWindow(content, { maxChars: maxLength ?? DEFAULT_TOOL_RESULT_MAX_LENGTH });
+
+/**
+ * Truncate tool result content if it exceeds the maximum length.
+ * Keeps whole leading lines and appends the shared notice with the shown range and total size.
*
* @param content - The tool result content to truncate
* @param maxLength - Maximum allowed length (uses default if not provided)
@@ -30,23 +43,7 @@ export function truncateToolResult(content: string, maxLength?: number): string
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 as "unexpected end of hex escape".
- let cutoff = limit;
- const lastCharCode = content.charCodeAt(cutoff - 1);
- if (lastCharCode >= 0xd8_00 && lastCharCode <= 0xdb_ff) {
- cutoff -= 1;
- }
-
- const truncated = content.slice(0, cutoff);
- const remainingChars = content.length - cutoff;
-
- // Add truncation notice
- const notice = `\n\n[Content truncated: ${remainingChars.toLocaleString()} characters omitted to prevent context overflow. Original length: ${content.length.toLocaleString()} characters]`;
-
- return truncated + notice;
+ return appendTextWindowNotice(sliceToolResult(content, limit));
}
/**
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4dae8a507a3..58e2d86a225 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2185,6 +2185,7 @@
"upload.clientMode.disabled": "The current model does not support visual recognition and file analysis. Please switch models to use this feature.",
"upload.clientMode.fileNotSupported": "File uploads are not supported in browser mode; only images are allowed.",
"upload.clientMode.visionNotSupported": "The current model does not support visual recognition. Please switch to a different model to use this feature.",
+ "upload.localPathReference": "Large files are referenced by their local path instead of uploaded, so the agent reads the original file directly.",
"upload.preview.prepareTasks": "Preparing chunks...",
"upload.preview.status.cancelled": "Upload cancelled",
"upload.preview.status.error": "Upload failed",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index abf54fd158d..ffdfe1dc240 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -180,6 +180,8 @@
"builtins.lobe-agent.todos.completedStep": "Completed",
"builtins.lobe-agent.todos.currentStep": "Current step",
"builtins.lobe-agent.todos.todos": "Todos",
+ "builtins.lobe-attachments.apiName.readAttachment": "Read attachment",
+ "builtins.lobe-attachments.title": "Attachments",
"builtins.lobe-browser.apiName.click": "Clicked element",
"builtins.lobe-browser.apiName.fill": "Filled input",
"builtins.lobe-browser.apiName.navigate": "Opened page",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 3de234a9aa8..bd7311e1d01 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1540,6 +1540,8 @@
"tools.builtins.lobe-artifacts.description": "Generate and preview interactive UI components and visualizations",
"tools.builtins.lobe-artifacts.readme": "Generate and live-preview interactive UI components, data visualizations, charts, SVG graphics, and web applications. Create rich visual content that users can interact with directly.",
"tools.builtins.lobe-artifacts.title": "Artifacts",
+ "tools.builtins.lobe-attachments.description": "Page through attached files that were too long to include in full",
+ "tools.builtins.lobe-attachments.title": "Attachments",
"tools.builtins.lobe-brief.description": "Report progress, deliver results, and request user decisions",
"tools.builtins.lobe-brief.title": "Brief Tools",
"tools.builtins.lobe-calculator.description": "Perform mathematical calculations, solve equations, and work with symbolic expressions",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index e4b5a0978ce..63a99b61556 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2185,6 +2185,7 @@
"upload.clientMode.disabled": "当前模型不支持视觉识别和文件分析。请切换模型后使用",
"upload.clientMode.fileNotSupported": "浏览器模式暂不支持上传文件。仅支持图片",
"upload.clientMode.visionNotSupported": "当前模型不支持视觉识别。请切换模型后使用",
+ "upload.localPathReference": "大文件改为引用本地路径,不再上传,助手会直接读取原文件。",
"upload.preview.prepareTasks": "正在准备分块…",
"upload.preview.status.cancelled": "已取消上传",
"upload.preview.status.error": "上传失败",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index ed1e9626fd3..ad12b2f9ba1 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -180,6 +180,8 @@
"builtins.lobe-agent.todos.completedStep": "已完成",
"builtins.lobe-agent.todos.currentStep": "当前步骤",
"builtins.lobe-agent.todos.todos": "待办",
+ "builtins.lobe-attachments.apiName.readAttachment": "读取附件",
+ "builtins.lobe-attachments.title": "附件",
"builtins.lobe-browser.apiName.click": "点击了元素",
"builtins.lobe-browser.apiName.fill": "填写了输入框",
"builtins.lobe-browser.apiName.navigate": "打开了页面",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index d5d098dcb13..1c4449fc4b4 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1540,6 +1540,8 @@
"tools.builtins.lobe-artifacts.description": "生成并预览交互式 UI 组件和可视化内容",
"tools.builtins.lobe-artifacts.readme": "生成并实时预览交互式 UI 组件、数据可视化、图表、SVG 图形和 Web 应用。创建用户可直接交互的丰富可视化内容。",
"tools.builtins.lobe-artifacts.title": "Artifacts",
+ "tools.builtins.lobe-attachments.description": "分段读取因过长未完整发送的附件",
+ "tools.builtins.lobe-attachments.title": "附件",
"tools.builtins.lobe-brief.description": "汇报进度、交付结果,并请求用户决策",
"tools.builtins.lobe-brief.title": "简报工具",
"tools.builtins.lobe-calculator.description": "执行数学计算、解方程,并处理符号表达式",
diff --git a/package.json b/package.json
index 44cea2ce9af..1e2e9edad88 100644
--- a/package.json
+++ b/package.json
@@ -240,6 +240,7 @@
"@lobechat/builtin-tool-agent-documents": "workspace:*",
"@lobechat/builtin-tool-agent-management": "workspace:*",
"@lobechat/builtin-tool-agent-signal": "workspace:*",
+ "@lobechat/builtin-tool-attachments": "workspace:*",
"@lobechat/builtin-tool-auv": "workspace:*",
"@lobechat/builtin-tool-brief": "workspace:*",
"@lobechat/builtin-tool-browser": "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 4e54dfcd093..e2cb398e374 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
@@ -260,7 +260,9 @@ describe('AgentDocumentsExecutionRuntime', () => {
// 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');
+ expect(result.content).toContain(
+ 'Line 1 is 500000 characters long and was cut at 200000; the rest of that line cannot be paged.',
+ );
// Inspector still receives the untruncated document via state.
expect(result.state).toMatchObject({ content: hugeMarkdown, xml: hugeXml });
});
@@ -300,6 +302,30 @@ describe('AgentDocumentsExecutionRuntime', () => {
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');
+ expect(result.content).toContain('was cut at 199999');
+ });
+
+ it('pages a long document by line with the exact call for the next window', async () => {
+ const markdown = Array.from({ length: 10 }, (_, i) => `line ${i + 1}`).join('\n');
+ const readDocument = vi.fn().mockResolvedValue({
+ content: markdown,
+ id: 'agent-doc-1',
+ litexml: '',
+ title: 'Archive',
+ });
+ const runtime = createRuntime({ readDocument });
+
+ const result = await runtime.readDocument(
+ { format: 'markdown', id: 'agent-doc-1', limit: 3, offset: 4 },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result.content).toBe(
+ 'line 4\nline 5\nline 6\n[Showing lines 4-6 of 10 lines, 70 characters. To continue, call readDocument again with id="agent-doc-1", format="markdown" and offset=7.]',
+ );
+ // Paging arguments stay in the runtime; the service only receives the lookup.
+ expect(readDocument).toHaveBeenCalledWith(
+ expect.not.objectContaining({ limit: expect.anything() }),
+ );
});
});
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index abe97e7f9a6..1e310e62e9c 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -7,6 +7,7 @@ import {
formatReplaceDocumentResult,
formatUpdateLoadRuleResult,
} from '@lobechat/prompts';
+import { appendTextWindowNotice, sliceTextWindow } from '@lobechat/prompts/textWindow';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
import type {
@@ -20,6 +21,7 @@ import type {
ReplaceDocumentContentArgs,
UpdateLoadRuleArgs,
} from '../types';
+import { MAX_READ_DOCUMENT_CONTENT_CHARS } from '../types';
interface AgentDocumentRecord {
content?: string;
@@ -85,18 +87,6 @@ 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 {
@@ -277,45 +267,35 @@ export class AgentDocumentsExecutionRuntime {
}
/**
- * 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.
+ * Returns one window of a field using the shared text-window contract. A field within the cap
+ * and read without `offset`/`limit` is returned whole, exactly as before; otherwise the window
+ * ends with the range, total size and the exact readDocument call for the next window.
*/
- 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 windowReadContent(content: string, args: ReadDocumentArgs, format: string) {
+ const paged = args.offset !== undefined || args.limit !== undefined;
+ if (!paged && content.length <= MAX_READ_DOCUMENT_CONTENT_CHARS) return content;
+
+ const window = sliceTextWindow(content, {
+ maxChars: MAX_READ_DOCUMENT_CONTENT_CHARS,
+ maxLines: args.limit,
+ offset: args.offset,
+ });
+
+ return appendTextWindowNotice(window, {
+ continueFrom: (line) =>
+ `call readDocument again with id="${args.id}", format="${format}" and offset=${line}`,
+ });
}
- private formatDocumentReadContent(
- doc: AgentDocumentRecord,
- format: 'xml' | 'markdown' | 'both' = 'xml',
- ) {
- const markdown = this.capReadContent(doc.content || '');
- const xml = this.capReadContent(doc.litexml || '');
+ private formatDocumentReadContent(doc: AgentDocumentRecord, args: ReadDocumentArgs) {
+ const format = args.format ?? 'xml';
+ const markdown = () => this.windowReadContent(doc.content || '', args, format);
+ const xml = () => this.windowReadContent(doc.litexml || '', args, format);
- if (format === 'markdown') return markdown;
- if (format === 'both') return JSON.stringify({ markdown, xml });
+ if (format === 'markdown') return markdown();
+ if (format === 'both') return JSON.stringify({ markdown: markdown(), xml: xml() });
- return xml || markdown;
+ return doc.litexml ? xml() : markdown();
}
async listDocuments(
@@ -436,13 +416,12 @@ export class AgentDocumentsExecutionRuntime {
};
}
- const doc = await this.service.readDocument({ ...args, agentId });
+ const { limit: _limit, offset: _offset, ...readArgs } = args;
+ const doc = await this.service.readDocument({ ...readArgs, agentId });
if (!doc) return { content: `Document not found: ${args.id}`, success: false };
- const format = args.format ?? 'xml';
-
return {
- content: this.formatDocumentReadContent(doc, format),
+ content: this.formatDocumentReadContent(doc, args),
state: { content: doc.content, id: doc.id, title: doc.title, xml: doc.litexml },
success: true,
};
diff --git a/packages/builtin-tool-agent-documents/src/index.ts b/packages/builtin-tool-agent-documents/src/index.ts
index 1e08c9a5a07..54b9cb976c3 100644
--- a/packages/builtin-tool-agent-documents/src/index.ts
+++ b/packages/builtin-tool-agent-documents/src/index.ts
@@ -12,6 +12,7 @@ export {
type CreateDocumentState,
type ListDocumentsArgs,
type ListDocumentsState,
+ MAX_READ_DOCUMENT_CONTENT_CHARS,
type ModifyDocumentNodesArgs,
type ModifyDocumentNodesState,
type ModifyDocumentOperation,
diff --git a/packages/builtin-tool-agent-documents/src/manifest.ts b/packages/builtin-tool-agent-documents/src/manifest.ts
index 03f46924e05..b5a440a585f 100644
--- a/packages/builtin-tool-agent-documents/src/manifest.ts
+++ b/packages/builtin-tool-agent-documents/src/manifest.ts
@@ -51,7 +51,7 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
},
{
description:
- 'Read an existing agent document by ID. Prefer XML format before node-level edits because XML includes stable node IDs.',
+ 'Read an existing agent document by ID. Prefer XML format before node-level edits because XML includes stable node IDs. Long documents are returned one window at a time; a partial read ends with the offset to continue from.',
name: AgentDocumentsApiName.readDocument,
parameters: {
properties: {
@@ -66,6 +66,16 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
description: AGENT_DOCUMENT_ID_DESCRIPTION,
type: 'string',
},
+ limit: {
+ description:
+ 'Maximum number of lines to return. Omit to read as much as fits in one response.',
+ type: 'integer',
+ },
+ offset: {
+ description:
+ '1-based line to start reading from. Use the offset given at the end of a partial read to continue.',
+ type: 'integer',
+ },
},
required: ['id'],
type: 'object',
diff --git a/packages/builtin-tool-agent-documents/src/types.ts b/packages/builtin-tool-agent-documents/src/types.ts
index e93ab4ad2b2..e03d0baf5be 100644
--- a/packages/builtin-tool-agent-documents/src/types.ts
+++ b/packages/builtin-tool-agent-documents/src/types.ts
@@ -1,5 +1,17 @@
export const AgentDocumentsIdentifier = 'lobe-agent-documents';
+/**
+ * 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.
+ */
+export const MAX_READ_DOCUMENT_CONTENT_CHARS = 200_000;
+
export const AgentDocumentsApiName = {
createDocument: 'createDocument',
copyDocument: 'copyDocument',
@@ -46,6 +58,10 @@ export interface CreateDocumentState {
export interface ReadDocumentArgs {
format?: 'xml' | 'markdown' | 'both';
id: string;
+ /** Maximum number of lines to return. */
+ limit?: number;
+ /** 1-based line to start reading from. */
+ offset?: number;
}
export interface ReadDocumentState {
diff --git a/packages/builtin-tool-attachments/package.json b/packages/builtin-tool-attachments/package.json
new file mode 100644
index 00000000000..ddca256214b
--- /dev/null
+++ b/packages/builtin-tool-attachments/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@lobechat/builtin-tool-attachments",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts",
+ "./executor": "./src/executor/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/prompts": "workspace:*"
+ },
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ }
+}
diff --git a/packages/builtin-tool-attachments/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-attachments/src/ExecutionRuntime/index.test.ts
new file mode 100644
index 00000000000..1bcf47b6419
--- /dev/null
+++ b/packages/builtin-tool-attachments/src/ExecutionRuntime/index.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { AttachmentsExecutionRuntime } from './index';
+
+const lines = (count: number) => Array.from({ length: count }, (_, i) => `row ${i + 1}`).join('\n');
+
+describe('AttachmentsExecutionRuntime.readAttachment', () => {
+ it('returns one window and names the readAttachment call for the next one', async () => {
+ const getFileContents = vi
+ .fn()
+ .mockResolvedValue([{ content: lines(1000), fileId: 'file_1', filename: 'sales.csv' }]);
+ const runtime = new AttachmentsExecutionRuntime({ getFileContents });
+
+ const result = await runtime.readAttachment({ fileId: 'file_1', limit: '10', offset: 401 });
+
+ expect(getFileContents).toHaveBeenCalledWith(['file_1'], undefined);
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('lines="401-410" total_lines="1000"');
+ expect(result.content).toContain('row 401\n');
+ expect(result.content).toContain(
+ 'To continue, call readAttachment with fileId="file_1" and offset=411.',
+ );
+ expect(result.state).toMatchObject({ endLine: 410, startLine: 401, truncated: true });
+ });
+
+ it('reports a stored text cut at parse time', async () => {
+ const runtime = new AttachmentsExecutionRuntime({
+ getFileContents: vi
+ .fn()
+ .mockResolvedValue([
+ { content: 'head', fileId: 'file_1', filename: 'big.txt', originalCharCount: 9000 },
+ ]),
+ });
+
+ const result = await runtime.readAttachment({ fileId: 'file_1' });
+
+ expect(result.content).toContain('original_chars="9000"');
+ expect(result.content).toContain('The stored text is incomplete');
+ });
+
+ it('fails without leaking content when the file cannot be read', async () => {
+ const runtime = new AttachmentsExecutionRuntime({
+ getFileContents: vi
+ .fn()
+ .mockResolvedValue([
+ { content: '', error: 'File not found', fileId: 'file_x', filename: '' },
+ ]),
+ });
+
+ const result = await runtime.readAttachment({ fileId: 'file_x' });
+
+ expect(result).toMatchObject({
+ content: '<file id="file_x" error="File not found" />',
+ success: false,
+ });
+ });
+
+ it('requires a fileId', async () => {
+ const getFileContents = vi.fn();
+ const runtime = new AttachmentsExecutionRuntime({ getFileContents });
+
+ expect(await runtime.readAttachment({ fileId: '' })).toMatchObject({ success: false });
+ expect(getFileContents).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/builtin-tool-attachments/src/ExecutionRuntime/index.ts b/packages/builtin-tool-attachments/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..7105243f2c2
--- /dev/null
+++ b/packages/builtin-tool-attachments/src/ExecutionRuntime/index.ts
@@ -0,0 +1,79 @@
+import { readAttachmentContinuation } from '@lobechat/prompts';
+import {
+ formatTextWindowAttributes,
+ formatTextWindowNotice,
+ sliceReadWindow,
+} from '@lobechat/prompts/textWindow';
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import type { ReadAttachmentArgs, ReadAttachmentState } from '../types';
+
+export interface AttachmentContent {
+ content: string;
+ error?: string;
+ fileId: string;
+ filename: string;
+ /** Original character count when the stored text was cut at parse time. */
+ originalCharCount?: number;
+}
+
+export interface AttachmentsRuntimeService {
+ /** Resolves parsed text for files the caller may read; ownership is enforced by the host. */
+ getFileContents: (fileIds: string[], signal?: AbortSignal) => Promise<AttachmentContent[]>;
+}
+
+export class AttachmentsExecutionRuntime {
+ private service: AttachmentsRuntimeService;
+
+ constructor(service: AttachmentsRuntimeService) {
+ this.service = service;
+ }
+
+ async readAttachment(
+ args: ReadAttachmentArgs,
+ options?: { signal?: AbortSignal },
+ ): Promise<BuiltinServerRuntimeOutput> {
+ const { fileId, limit, offset } = args;
+ if (!fileId) return { content: 'Error: fileId is required', success: false };
+
+ try {
+ const [file] = await this.service.getFileContents([fileId], options?.signal);
+ if (!file || file.error) {
+ const error = file?.error ?? 'File not found';
+ const state: ReadAttachmentState = { error, fileId };
+ return { content: `<file id="${fileId}" error="${error}" />`, state, success: false };
+ }
+
+ const window = sliceReadWindow(file.content, { limit, offset });
+ const noticeOptions = {
+ continueFrom: readAttachmentContinuation(fileId),
+ originalChars: file.originalCharCount,
+ };
+ const notice = formatTextWindowNotice(window, noticeOptions);
+
+ const state: ReadAttachmentState = {
+ endLine: window.endLine,
+ fileId,
+ filename: file.filename,
+ startLine: window.startLine,
+ totalCharCount: window.totalChars,
+ totalLineCount: window.totalLines,
+ truncated: window.truncated,
+ };
+
+ return {
+ content: `<file id="${fileId}" name="${file.filename}"${formatTextWindowAttributes(window, noticeOptions)}>
+${window.content}${notice ? `\n${notice}` : ''}
+</file>`,
+ state,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `Error reading attachment: ${(e as Error).message}`,
+ error: e,
+ success: false,
+ };
+ }
+ }
+}
diff --git a/packages/builtin-tool-attachments/src/executor/index.ts b/packages/builtin-tool-attachments/src/executor/index.ts
new file mode 100644
index 00000000000..a783fb364e6
--- /dev/null
+++ b/packages/builtin-tool-attachments/src/executor/index.ts
@@ -0,0 +1,36 @@
+import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
+import { BaseExecutor } from '@lobechat/types';
+
+import type { AttachmentsExecutionRuntime } from '../ExecutionRuntime';
+import type { ReadAttachmentArgs } from '../types';
+import { AttachmentsApiName, AttachmentsIdentifier } from '../types';
+
+export class AttachmentsExecutor extends BaseExecutor<typeof AttachmentsApiName> {
+ readonly identifier = AttachmentsIdentifier;
+ protected readonly apiEnum = AttachmentsApiName;
+ private runtime: AttachmentsExecutionRuntime;
+
+ constructor(runtime: AttachmentsExecutionRuntime) {
+ super();
+ this.runtime = runtime;
+ }
+
+ readAttachment = async (
+ params: ReadAttachmentArgs,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { content, error, state, success } = await this.runtime.readAttachment(params, {
+ signal: ctx.signal,
+ });
+ if (success) return { content, state, success };
+
+ return {
+ content,
+ error: error
+ ? { body: error, message: (error as Error).message ?? content, type: 'PluginServerError' }
+ : undefined,
+ state,
+ success: false,
+ };
+ };
+}
diff --git a/packages/builtin-tool-attachments/src/index.ts b/packages/builtin-tool-attachments/src/index.ts
new file mode 100644
index 00000000000..b3aa21bdae9
--- /dev/null
+++ b/packages/builtin-tool-attachments/src/index.ts
@@ -0,0 +1,8 @@
+export { AttachmentsManifest } from './manifest';
+export {
+ AttachmentsApiName,
+ type AttachmentsApiNameType,
+ AttachmentsIdentifier,
+ type ReadAttachmentArgs,
+ type ReadAttachmentState,
+} from './types';
diff --git a/packages/builtin-tool-attachments/src/manifest.ts b/packages/builtin-tool-attachments/src/manifest.ts
new file mode 100644
index 00000000000..86808d0b59f
--- /dev/null
+++ b/packages/builtin-tool-attachments/src/manifest.ts
@@ -0,0 +1,49 @@
+import { MAX_READ_WINDOW_LINES } from '@lobechat/prompts/textWindow';
+import { type BuiltinToolManifest } from '@lobechat/types';
+
+import { AttachmentsApiName, AttachmentsIdentifier } from './types';
+
+/**
+ * Read-only paging over the parsed text of a file the user attached (or an agent file) that was
+ * sent to the model as a preview. Deliberately separate from `lobe-knowledge-base`: enabling that
+ * whole tool for one oversized attachment also exposed knowledge-base search and write/delete APIs.
+ */
+export const AttachmentsManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ 'Read the next window of an attached file that was shown only as a preview. Use the fileId from the <file> tag and the offset named in its notice. Returns whole lines, bounded to about 10k characters per call; when truncated="true", call again with the suggested offset.',
+ name: AttachmentsApiName.readAttachment,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ fileId: {
+ description: 'The id attribute of the <file> tag to read.',
+ type: 'string',
+ },
+ limit: {
+ description: `Maximum number of lines to return (1-${MAX_READ_WINDOW_LINES}). Defaults to 400.`,
+ maximum: MAX_READ_WINDOW_LINES,
+ minimum: 1,
+ type: 'integer',
+ },
+ offset: {
+ description: '1-based line number to start reading from. Defaults to 1.',
+ minimum: 1,
+ type: 'integer',
+ },
+ },
+ required: ['fileId'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: AttachmentsIdentifier,
+ meta: {
+ avatar: '📎',
+ description: 'Page through attached files that were too long to include in full',
+ title: 'Attachments',
+ },
+ systemRole: '',
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-attachments/src/types.ts b/packages/builtin-tool-attachments/src/types.ts
new file mode 100644
index 00000000000..d843f9f46cf
--- /dev/null
+++ b/packages/builtin-tool-attachments/src/types.ts
@@ -0,0 +1,25 @@
+export const AttachmentsIdentifier = 'lobe-attachments';
+
+export const AttachmentsApiName = {
+ readAttachment: 'readAttachment',
+} as const;
+
+export type AttachmentsApiNameType = (typeof AttachmentsApiName)[keyof typeof AttachmentsApiName];
+
+export interface ReadAttachmentArgs {
+ fileId: string;
+ /** Some providers send numeric arguments as strings. */
+ limit?: number | string;
+ offset?: number | string;
+}
+
+export interface ReadAttachmentState {
+ endLine?: number;
+ error?: string;
+ fileId: string;
+ filename?: string;
+ startLine?: number;
+ totalCharCount?: number;
+ totalLineCount?: number;
+ truncated?: boolean;
+}
diff --git a/packages/builtin-tool-attachments/vitest.config.mts b/packages/builtin-tool-attachments/vitest.config.mts
new file mode 100644
index 00000000000..52f86e133c7
--- /dev/null
+++ b/packages/builtin-tool-attachments/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',
+ },
+});
diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
index f27a96d8cf1..85bf1c20c9d 100644
--- a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
@@ -1,4 +1,5 @@
import { formatSearchResults, promptFileContents, promptNoSearchResults } from '@lobechat/prompts';
+import { sliceReadWindow } from '@lobechat/prompts/textWindow';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
import type {
@@ -25,13 +26,14 @@ import type {
ViewKnowledgeBaseArgs,
ViewKnowledgeBaseState,
} from '../types';
-import { sliceReadWindow } from './readWindow';
interface FileContentResult {
content: string;
error?: string;
fileId: string;
filename: string;
+ /** Original character count when the stored text was cut at parse time. */
+ originalCharCount?: number;
preview?: string;
totalCharCount?: number;
totalLineCount?: number;
@@ -344,14 +346,8 @@ export class KnowledgeBaseExecutionRuntime {
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,
- },
+ originalChars: file.originalCharCount,
+ range: window,
}
: {
content: file.content,
@@ -372,8 +368,8 @@ export class KnowledgeBaseExecutionRuntime {
// 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,
+ totalCharCount: file.totalCharCount ?? window?.totalChars,
+ totalLineCount: file.totalLineCount ?? window?.totalLines,
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.ts
index 9814350bb0d..5d653f09735 100644
--- a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readKnowledge.test.ts
+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readKnowledge.test.ts
@@ -5,7 +5,9 @@ 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 createRuntime = (
+ files: Record<string, { content: string; error?: string; originalCharCount?: number }>,
+) => {
const ragService = {
getFileContents: vi.fn(async (ids: string[]) =>
ids.map((id) => {
@@ -16,6 +18,7 @@ const createRuntime = (files: Record<string, { content: string; error?: string }
error: file.error,
fileId: id,
filename: `${id}.md`,
+ originalCharCount: file.originalCharCount,
preview: lines.slice(0, 5).join('\n'),
totalCharCount: file.content.length,
totalLineCount: lines.length,
@@ -39,10 +42,14 @@ describe('KnowledgeBaseExecutionRuntime.readKnowledge', () => {
expect(result.success).toBe(true);
expect(result.content).toContain(
- '<file id="big" name="big.md" lines="1-400" totalLines="1000"',
+ '<file id="big" name="big.md" lines="1-400" total_lines="1000"',
+ );
+ expect(result.content).toContain(
+ 'To continue, call readKnowledge with fileIds=["big"] and offset=401.',
+ );
+ expect(result.content).toContain(
+ '<file id="small" name="small.md" lines="1-1" total_lines="1"',
);
- 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;
@@ -63,12 +70,23 @@ describe('KnowledgeBaseExecutionRuntime.readKnowledge', () => {
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');
+ expect(result.content).toContain('fileIds=["big"] and offset=404.');
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('tells the model the stored text is incomplete on a file cut at parse time', async () => {
+ const { runtime } = createRuntime({
+ capped: { content: buildLines('L', 3), originalCharCount: 9_000_000 },
+ });
+
+ const result = await runtime.readKnowledge({ fileIds: ['capped'] });
+
+ expect(result.content).toContain('original_chars="9000000"');
+ expect(result.content).toContain('The stored text is incomplete');
+ });
+
it('keeps error files as errors without a window', async () => {
const { runtime } = createRuntime({
missing: { content: '', error: 'Document not found' },
diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.ts
deleted file mode 100644
index 2daefb152ae..00000000000
--- a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- * 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-web-browsing/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
index a2399d39372..6b730e4051a 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
@@ -132,4 +132,65 @@ describe('WebBrowsingExecutionRuntime', () => {
);
});
});
+
+ describe('crawlMultiPages', () => {
+ const longPage = Array.from({ length: 5000 }, (_, i) => `paragraph ${i + 1}`).join('\n');
+ const createSearchService = () => ({
+ crawlPages: vi.fn().mockResolvedValue({
+ results: [
+ {
+ data: { content: longPage, title: 'Long', url: 'https://example.com/long' },
+ originalUrl: 'https://example.com/long',
+ },
+ ],
+ }),
+ webSearch: vi.fn(),
+ });
+
+ it('pages a long crawled page through its saved agent document', async () => {
+ const runtime = new WebBrowsingExecutionRuntime({
+ canReadSavedDocuments: true,
+ documentService: {
+ associateDocument: vi.fn().mockResolvedValue({ id: 'agent-doc-1' }),
+ createDocument: vi.fn().mockResolvedValue({ id: 'docs-1' }),
+ },
+ searchService: createSearchService() as any,
+ });
+
+ const result = await runtime.crawlMultiPages({ urls: ['https://example.com/long'] });
+
+ expect(result.content).not.toContain('paragraph 5000');
+ expect(result.content).toMatch(
+ /\[Showing lines 1-\d+ of 5000 lines, \d+ characters\. To continue, call lobe-agent-documents readDocument with id="agent-doc-1", format="markdown" and offset=\d+\.\]/,
+ );
+ });
+
+ it('does not name readDocument when the run cannot call it', async () => {
+ // Chat mode, or a custom tool set with browsing alone, has no lobe-agent-documents.
+ const createDocument = vi.fn().mockResolvedValue({ id: 'docs-1' });
+ const runtime = new WebBrowsingExecutionRuntime({
+ documentService: {
+ associateDocument: vi.fn().mockResolvedValue({ id: 'agent-doc-1' }),
+ createDocument,
+ },
+ searchService: createSearchService() as any,
+ });
+
+ const result = await runtime.crawlMultiPages({ urls: ['https://example.com/long'] });
+
+ expect(createDocument).toHaveBeenCalled();
+ expect(result.content).toMatch(/Lines \d+-5000 were left out\./);
+ expect(result.content).not.toContain('readDocument');
+ });
+
+ it('reports what was left out when the page was not saved', async () => {
+ const runtime = new WebBrowsingExecutionRuntime({
+ searchService: createSearchService() as any,
+ });
+
+ const result = await runtime.crawlMultiPages({ urls: ['https://example.com/long'] });
+
+ expect(result.content).toMatch(/Lines \d+-5000 were left out\./);
+ });
+ });
});
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
index 21f560fc293..a5d3085d5eb 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
@@ -1,4 +1,5 @@
import { crawlResultsPrompt, searchResultsPrompt } from '@lobechat/prompts';
+import { appendTextWindowNotice, sliceTextWindow } from '@lobechat/prompts/textWindow';
import type {
BuiltinServerRuntimeOutput,
CrawlMultiPagesQuery,
@@ -12,7 +13,8 @@ import type { CrawlSuccessResult } from '@lobechat/web-crawler';
import { CRAWL_CONTENT_LIMITED_COUNT, SEARCH_ITEM_LIMITED_COUNT } from '../const';
export interface WebBrowsingDocumentService {
- associateDocument: (documentId: string) => Promise<void>;
+ /** Returns the agent document binding when one was created, so its id can be handed to the model. */
+ associateDocument: (documentId: string) => Promise<{ id?: string } | void>;
createDocument: (params: {
content: string;
description?: string;
@@ -23,6 +25,12 @@ export interface WebBrowsingDocumentService {
export interface WebBrowsingRuntimeOptions {
agentId?: string;
+ /**
+ * Whether `lobe-agent-documents` is in this run's final tool set. A truncated page only names
+ * `readDocument` on its saved copy when the model can actually call it; chat mode or a custom
+ * tool set with browsing alone still saves the page but reports what was left out instead.
+ */
+ canReadSavedDocuments?: boolean;
documentService?: WebBrowsingDocumentService;
searchService: SearchServiceImpl;
topicId?: string;
@@ -30,6 +38,7 @@ export interface WebBrowsingRuntimeOptions {
export class WebBrowsingExecutionRuntime {
private agentId?: string;
+ private canReadSavedDocuments: boolean;
private documentService?: WebBrowsingDocumentService;
private searchService: SearchServiceImpl;
private topicId?: string;
@@ -37,6 +46,7 @@ export class WebBrowsingExecutionRuntime {
constructor(options: WebBrowsingRuntimeOptions) {
this.searchService = options.searchService;
this.documentService = options.documentService;
+ this.canReadSavedDocuments = options.canReadSavedDocuments ?? false;
this.agentId = options.agentId;
this.topicId = options.topicId;
}
@@ -90,7 +100,9 @@ export class WebBrowsingExecutionRuntime {
const { results } = response;
- // Save crawled pages as documents and associate with agent
+ // Save crawled pages as documents and associate with agent. The agent document id lets a
+ // truncated page point the model at the full saved copy.
+ const savedDocumentIds = new Map<string, string>();
if (this.documentService) {
await Promise.all(
results.map(async (item) => {
@@ -107,7 +119,8 @@ export class WebBrowsingExecutionRuntime {
url: pageData.url,
});
- await this.documentService!.associateDocument(doc.id);
+ const binding = await this.documentService!.associateDocument(doc.id);
+ if (binding?.id) savedDocumentIds.set(pageData.url, binding.id);
} catch (error) {
console.error('[WebBrowsing] Failed to save crawl result to agent document:', error);
}
@@ -115,17 +128,29 @@ export class WebBrowsingExecutionRuntime {
);
}
- const content = results.map((item) =>
- 'errorMessage' in item.data
- ? // keep the failing url attached so the model knows which page to give up on
- { ...item.data, url: item.data.url ?? item.originalUrl }
- : {
- ...item.data,
- // if crawl too many content
- // slice the top 10000 char
- content: item.data.content?.slice(0, CRAWL_CONTENT_LIMITED_COUNT),
- },
- );
+ const content = results.map((item) => {
+ // keep the failing url attached so the model knows which page to give up on
+ if ('errorMessage' in item.data)
+ return { ...item.data, url: item.data.url ?? item.originalUrl };
+
+ const pageData = item.data as CrawlSuccessResult;
+ if (!pageData.content || pageData.content.length <= CRAWL_CONTENT_LIMITED_COUNT) {
+ return pageData;
+ }
+
+ const savedId = this.canReadSavedDocuments ? savedDocumentIds.get(pageData.url) : undefined;
+ const window = sliceTextWindow(pageData.content, { maxChars: CRAWL_CONTENT_LIMITED_COUNT });
+
+ return {
+ ...pageData,
+ content: appendTextWindowNotice(window, {
+ continueFrom: savedId
+ ? (line) =>
+ `call lobe-agent-documents readDocument with id="${savedId}", format="markdown" and offset=${line}`
+ : undefined,
+ }),
+ };
+ });
const xmlContent = crawlResultsPrompt(content as any);
return {
diff --git a/packages/builtin-tool-web-browsing/src/const.ts b/packages/builtin-tool-web-browsing/src/const.ts
index 72727fc5c5c..2aca20a0cc2 100644
--- a/packages/builtin-tool-web-browsing/src/const.ts
+++ b/packages/builtin-tool-web-browsing/src/const.ts
@@ -43,6 +43,7 @@ export const ENGINE_ICON_MAP: Record<string, string> = {
'youtube': 'https://icons.duckduckgo.com/ip3/youtube.com.ico',
};
+/** Characters of a crawled page returned to the model; longer pages end with the shared window notice. */
export const CRAWL_CONTENT_LIMITED_COUNT = 25_000;
export const SEARCH_ITEM_LIMITED_COUNT = 30;
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index 45749b0b7e2..7a06b7bd6e6 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -27,6 +27,7 @@
"@lobechat/builtin-tool-agent-documents": "workspace:*",
"@lobechat/builtin-tool-agent-management": "workspace:*",
"@lobechat/builtin-tool-agent-signal": "workspace:*",
+ "@lobechat/builtin-tool-attachments": "workspace:*",
"@lobechat/builtin-tool-auv": "workspace:*",
"@lobechat/builtin-tool-brief": "workspace:*",
"@lobechat/builtin-tool-browser": "workspace:*",
diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.ts
index d3f66c834fd..d3971fa4a6f 100644
--- a/packages/builtin-tools/src/identifiers.ts
+++ b/packages/builtin-tools/src/identifiers.ts
@@ -9,6 +9,7 @@ import {
agentSignalReviewManifest,
agentSignalSkillManagementManifest,
} from '@lobechat/builtin-tool-agent-signal';
+import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';
@@ -39,6 +40,7 @@ export const builtinToolIdentifiers: string[] = [
AgentBuilderManifest.identifier,
AgentDocumentsManifest.identifier,
AgentManagementManifest.identifier,
+ AttachmentsManifest.identifier,
AuvManifest.identifier,
CalculatorManifest.identifier,
CloudSandboxManifest.identifier,
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 34f26477feb..a1542caf619 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -15,6 +15,7 @@ import {
agentSignalReviewManifest,
agentSignalSkillManagementManifest,
} from '@lobechat/builtin-tool-agent-signal';
+import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { BriefManifest } from '@lobechat/builtin-tool-brief';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
@@ -63,6 +64,7 @@ export const defaultToolIds = [
SkillStoreManifest.identifier,
WebBrowsingManifest.identifier,
KnowledgeBaseManifest.identifier,
+ AttachmentsManifest.identifier,
MemoryManifest.identifier,
LocalSystemManifest.identifier,
BrowserManifest.identifier,
@@ -126,6 +128,7 @@ export const manualModeExcludeToolIds = [
* `allowExplicitActivation` so the activator can't smuggle other tools in.
*/
export const chatModeAllowedToolIds = [
+ AttachmentsManifest.identifier,
KnowledgeBaseManifest.identifier,
MemoryManifest.identifier,
WebBrowsingManifest.identifier,
@@ -169,6 +172,7 @@ export const groupSupervisorToolIds = [GroupManagementManifest.identifier];
* `src/helpers/toolEngineering/index.ts`.
*/
export const runtimeManagedToolIds = [
+ AttachmentsManifest.identifier,
BrowserManifest.identifier,
CloudSandboxManifest.identifier,
KnowledgeBaseManifest.identifier,
@@ -429,6 +433,13 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
manifest: KnowledgeBaseManifest,
type: 'builtin',
},
+ {
+ discoverable: false,
+ hidden: true,
+ identifier: AttachmentsManifest.identifier,
+ manifest: AttachmentsManifest,
+ type: 'builtin',
+ },
{
// Opt-in image generation: chat mode no longer auto-injects it, so the
// Tools popover must expose a pin/disable control.
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 313c27030aa..8779ea9566e 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -83,6 +83,9 @@ import type { MessagesEngineParams, MessagesEngineResult } from './types';
const log = debug('context-engine:MessagesEngine');
+/** `AttachmentsIdentifier` from `@lobechat/builtin-tool-attachments`, inlined to avoid a package cycle */
+const ATTACHMENTS_TOOL_ID = 'lobe-attachments';
+
/**
* MessagesEngine - High-level message processing engine
*
@@ -248,6 +251,9 @@ export class MessagesEngine {
// documentation is confirmed to be injected into the system prompt for this
// request.
const canUseFC = capabilities?.isCanUseFC || (() => true);
+ // Oversized file previews may only promise `readAttachment` when the model is actually sent that
+ // tool; custom / exclusive tool modes, share visitors and clients without it get a plain preview.
+ const canReadAttachment = toolIds.includes(ATTACHMENTS_TOOL_ID) && !!canUseFC(model, provider);
const injectedActivatedSkills =
isAgentMode && (skillsConfig?.enabledSkills?.length ?? 0) > 0
? selectActivatedSkills(skillsConfig?.enabledSkills)
@@ -393,6 +399,7 @@ export class MessagesEngine {
new PlanInjector({ enabled: !!isPlanEnabled, plan: planTodo?.plan }),
// Knowledge (agent files + knowledge bases)
new KnowledgeInjector({
+ canReadAttachment,
fileContents: knowledge?.fileContents,
knowledgeBases: knowledge?.knowledgeBases,
}),
@@ -600,6 +607,7 @@ export class MessagesEngine {
new ReactionFeedbackProcessor({ enabled: true }),
// Message content processing (image encoding, multimodal)
new MessageContentProcessor({
+ canReadAttachment,
fileContext: fileContext || { enabled: true, includeFileUrl: true },
isCanUseAudio: capabilities?.isCanUseAudio || (() => false),
isCanUseVideo: capabilities?.isCanUseVideo || (() => false),
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
index 384c90d0b24..98dd47c6fd7 100644
--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -682,6 +682,79 @@ describe('MessagesEngine', () => {
expect(content[0].text).toContain('url="https://files.example.com/test.txt"');
});
+
+ describe('oversized attachment previews', () => {
+ const oversizedParams = (overrides?: Partial<MessagesEngineParams>) =>
+ createBasicParams({
+ knowledge: {
+ fileContents: [
+ { content: 'agent,row\n'.repeat(20_000), fileId: 'agent-file', filename: 'a.csv' },
+ ],
+ },
+ messages: [
+ {
+ content: 'Summarize this',
+ createdAt: Date.now(),
+ fileList: [
+ {
+ content: 'row,value\n'.repeat(20_000),
+ fileType: 'text/csv',
+ id: 'big-file',
+ name: 'big.csv',
+ size: 200_000,
+ url: 'https://files.example.com/big.csv',
+ },
+ ],
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ],
+ ...overrides,
+ });
+
+ const userText = async (params: MessagesEngineParams) => {
+ const result = await new MessagesEngine(params).process();
+ return result.messages
+ .filter((message) => message.role === 'user')
+ .flatMap((message) =>
+ typeof message.content === 'string'
+ ? [message.content]
+ : (message.content as any[]).map((part) => part.text ?? ''),
+ )
+ .join('\n');
+ };
+
+ it('names readAttachment when the final tool set carries it', async () => {
+ const text = await userText(
+ oversizedParams({ toolsConfig: { tools: ['lobe-attachments'] } }),
+ );
+
+ expect(text).toContain('call readAttachment with fileId="big-file" and offset=401');
+ expect(text).toContain('call readAttachment with fileId="agent-file" and offset=401');
+ });
+
+ it('does not promise readAttachment when the tool is not enabled', async () => {
+ // Custom / exclusive tool modes, share visitors and legacy clients never enable it.
+ const text = await userText(
+ oversizedParams({ toolsConfig: { tools: ['lobe-web-browsing'] } }),
+ );
+
+ expect(text).toContain('no tool to read the rest is available here');
+ expect(text).not.toContain('readAttachment');
+ });
+
+ it('does not promise readAttachment when the model cannot call tools', async () => {
+ const text = await userText(
+ oversizedParams({
+ capabilities: { isCanUseFC: () => false },
+ toolsConfig: { tools: ['lobe-attachments'] },
+ }),
+ );
+
+ expect(text).not.toContain('readAttachment');
+ });
+ });
});
describe('tools config', () => {
diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.ts
index ffdb40b2ee5..8c04db1d195 100644
--- a/packages/context-engine/src/processors/MessageContent.ts
+++ b/packages/context-engine/src/processors/MessageContent.ts
@@ -83,6 +83,8 @@ export interface FileContextConfig {
}
export interface MessageContentConfig {
+ /** Whether `readAttachment` is in the request's tool set, so oversized file previews can name it */
+ canReadAttachment?: boolean;
/** File context configuration */
fileContext?: FileContextConfig;
/** Function to check if audio input is supported */
@@ -265,6 +267,7 @@ export class MessageContentProcessor extends BaseProcessor {
// Call sites can still disable them for environments such as desktop local files.
addUrl: this.config.fileContext.includeFileUrl ?? true,
audioList: message.audioList || [],
+ canReadAttachment: this.config.canReadAttachment,
fileList: message.fileList,
imageList: message.imageList || [],
messageId: message.id,
diff --git a/packages/context-engine/src/providers/KnowledgeInjector.ts b/packages/context-engine/src/providers/KnowledgeInjector.ts
index 0c3ddc1e8a8..4232faff200 100644
--- a/packages/context-engine/src/providers/KnowledgeInjector.ts
+++ b/packages/context-engine/src/providers/KnowledgeInjector.ts
@@ -16,6 +16,8 @@ declare module '../types' {
const log = debug('context-engine:provider:KnowledgeInjector');
export interface KnowledgeInjectorConfig {
+ /** Whether `readAttachment` is in the request's tool set, so oversized file previews can name it */
+ canReadAttachment?: boolean;
/** File contents to inject */
fileContents?: FileContent[];
/** Knowledge bases to inject */
@@ -42,7 +44,11 @@ export class KnowledgeInjector extends BaseFirstUserContentProvider {
const knowledgeBases = this.config.knowledgeBases || [];
// Generate unified knowledge prompt
- const formattedContent = promptAgentKnowledge({ fileContents, knowledgeBases });
+ const formattedContent = promptAgentKnowledge({
+ canReadAttachment: this.config.canReadAttachment,
+ fileContents,
+ knowledgeBases,
+ });
if (!formattedContent) {
log('No knowledge to inject');
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index adc030a98ff..7b42f8981ac 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -139,6 +139,61 @@ describe('AgentModel', () => {
expect(result!.files[0].enabled).toBe(true);
});
+ it('should report the original size of a document cut at parse time', async () => {
+ const agentId = 'test-agent-with-cut-doc';
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ await serverDB.insert(agentsFiles).values({ agentId, fileId: '1', userId, enabled: true });
+ await serverDB.insert(documents).values({
+ content: 'Kept head',
+ fileId: '1',
+ fileType: 'application/pdf',
+ id: 'doc-cut',
+ metadata: { originalCharCount: 9_000_000, truncated: true },
+ source: 'document.pdf',
+ sourceType: 'file',
+ totalCharCount: 9,
+ totalLineCount: 1,
+ userId,
+ });
+
+ const result = await agentModel.getAgentConfigById(agentId);
+
+ expect(result!.files[0].originalCharCount).toBe(9_000_000);
+ });
+
+ it('should pick the oldest document when a file owns several', async () => {
+ const agentId = 'test-agent-with-two-docs';
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ await serverDB.insert(agentsFiles).values({ agentId, fileId: '1', userId, enabled: true });
+ const doc = {
+ fileId: '1',
+ fileType: 'text/plain',
+ source: 'notes.txt',
+ sourceType: 'file',
+ totalCharCount: 10,
+ totalLineCount: 1,
+ userId,
+ } as const;
+ // Inserted newest first: without an explicit order, a first-wins read would take the newer copy.
+ await serverDB.insert(documents).values({
+ ...doc,
+ content: 'page-editor copy',
+ createdAt: new Date('2026-02-01'),
+ id: 'doc-new',
+ });
+ await serverDB.insert(documents).values({
+ ...doc,
+ content: 'parse cache',
+ createdAt: new Date('2026-01-01'),
+ id: 'doc-old',
+ });
+
+ const result = await agentModel.getAgentConfigById(agentId);
+
+ // Same document `DocumentModel.findByFileId` returns, which `readAttachment` pages through.
+ expect(result!.files[0].content).toBe('parse cache');
+ });
+
it('should not include content for disabled files', async () => {
const agentId = 'test-agent-disabled-file';
await serverDB.insert(agents).values({ id: agentId, userId });
diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.ts
index d886e81934b..e0342b9b6cf 100644
--- a/packages/database/src/models/__tests__/document.test.ts
+++ b/packages/database/src/models/__tests__/document.test.ts
@@ -9,6 +9,9 @@ import {
documentHistories,
documents,
files,
+ messages,
+ messagesFiles,
+ topics,
users,
workspaces,
} from '../../schemas';
@@ -695,6 +698,81 @@ describe('DocumentModel', () => {
});
});
+ describe('hasFileDocumentsOverChars', () => {
+ const attachToTopic = async (fileId: string) => {
+ await serverDB.insert(topics).values({ id: 'tpc_large', userId });
+ await serverDB.insert(messages).values({
+ id: 'msg_large',
+ role: 'user',
+ topicId: 'tpc_large',
+ userId,
+ });
+ await serverDB.insert(messagesFiles).values({ fileId, messageId: 'msg_large', userId });
+ };
+
+ it('detects an oversized document among the given files', async () => {
+ const { file } = await createTestDocument(documentModel, fileModel, 'x'.repeat(20));
+
+ await expect(
+ documentModel.hasFileDocumentsOverChars({ fileIds: [file.id], minChars: 10 }),
+ ).resolves.toBe(true);
+ await expect(
+ documentModel.hasFileDocumentsOverChars({ fileIds: [file.id], minChars: 20 }),
+ ).resolves.toBe(false);
+ });
+
+ it('detects an oversized document attached earlier in the topic', async () => {
+ const { file } = await createTestDocument(documentModel, fileModel, 'x'.repeat(20));
+ await attachToTopic(file.id);
+
+ await expect(
+ documentModel.hasFileDocumentsOverChars({ minChars: 10, topicId: 'tpc_large' }),
+ ).resolves.toBe(true);
+ await expect(
+ documentModel.hasFileDocumentsOverChars({ minChars: 10, topicId: 'tpc_other' }),
+ ).resolves.toBe(false);
+ });
+
+ it('detects a short document whose stored text was cut at parse time', async () => {
+ const { documentId, file } = await createTestDocument(
+ documentModel,
+ fileModel,
+ 'x'.repeat(5),
+ );
+ await documentModel.update(documentId, { metadata: { originalCharCount: 50 } });
+
+ // Below the size threshold, but prompts still preview it because the text is incomplete.
+ await expect(
+ documentModel.hasFileDocumentsOverChars({ fileIds: [file.id], minChars: 10 }),
+ ).resolves.toBe(true);
+ });
+
+ it('ignores malformed originalCharCount metadata instead of failing', async () => {
+ const { documentId, file } = await createTestDocument(
+ documentModel,
+ fileModel,
+ 'x'.repeat(5),
+ );
+
+ for (const originalCharCount of ['not-a-number', '1e30', 1.5, { n: 1 }]) {
+ await documentModel.update(documentId, { metadata: { originalCharCount } });
+
+ await expect(
+ documentModel.hasFileDocumentsOverChars({ fileIds: [file.id], minChars: 10 }),
+ ).resolves.toBe(false);
+ }
+ });
+
+ it('ignores other users documents and returns false without inputs', async () => {
+ const { file } = await createTestDocument(documentModel, fileModel, 'x'.repeat(20));
+
+ await expect(
+ documentModel2.hasFileDocumentsOverChars({ fileIds: [file.id], minChars: 10 }),
+ ).resolves.toBe(false);
+ await expect(documentModel.hasFileDocumentsOverChars({ minChars: 10 })).resolves.toBe(false);
+ });
+ });
+
describe('findByFileId', () => {
it('should find document by fileId', async () => {
const { documentId, file } = await createTestDocument(
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.ts
index 2307ccad612..263702bb70a 100644
--- a/packages/database/src/models/__tests__/messages/message.query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts
@@ -2417,6 +2417,148 @@ describe('MessageModel Query Tests', () => {
expect(result[0].fileList).toHaveLength(1);
expect(result[0].fileList![0].id).toBe(fileId);
expect(result[0].fileList![0].content).toBe('This is the document content for testing');
+ expect(result[0].fileList![0].originalCharCount).toBeUndefined();
+ });
+
+ it('should report the original size of document text cut at parse time', async () => {
+ const fileId = uuid();
+
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values({ id: 'session1', userId });
+ await trx.insert(files).values({
+ fileType: 'text/csv',
+ id: fileId,
+ name: 'big.csv',
+ size: 5000,
+ url: 'big.csv',
+ userId,
+ });
+ await trx.insert(documents).values({
+ content: 'stored head',
+ fileId,
+ fileType: 'text/csv',
+ metadata: { originalCharCount: 9_000_000, truncated: true },
+ source: 'big.csv',
+ sourceType: 'file',
+ totalCharCount: 11,
+ totalLineCount: 1,
+ userId,
+ });
+
+ const messageId = uuid();
+ await trx.insert(messages).values({
+ content: 'Message with a capped document',
+ id: messageId,
+ role: 'user',
+ sessionId: 'session1',
+ userId,
+ });
+ await trx.insert(messagesFiles).values({ fileId, messageId, userId });
+ });
+
+ const result = await messageModel.query({ sessionId: 'session1' });
+
+ expect(result[0].fileList![0]).toMatchObject({
+ content: 'stored head',
+ originalCharCount: 9_000_000,
+ });
+ });
+
+ it('should treat malformed originalCharCount metadata as absent', async () => {
+ const fileId = uuid();
+
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values({ id: 'session1', userId });
+ await trx.insert(files).values({
+ fileType: 'text/plain',
+ id: fileId,
+ name: 'note.txt',
+ size: 10,
+ url: 'note.txt',
+ userId,
+ });
+ await trx.insert(documents).values({
+ content: 'note',
+ fileId,
+ fileType: 'text/plain',
+ metadata: { originalCharCount: 'not-a-number' },
+ source: 'note.txt',
+ sourceType: 'file',
+ totalCharCount: 4,
+ totalLineCount: 1,
+ userId,
+ });
+
+ const messageId = uuid();
+ await trx.insert(messages).values({
+ content: 'Message with odd metadata',
+ id: messageId,
+ role: 'user',
+ sessionId: 'session1',
+ userId,
+ });
+ await trx.insert(messagesFiles).values({ fileId, messageId, userId });
+ });
+
+ const result = await messageModel.query({ sessionId: 'session1' });
+
+ expect(result[0].fileList![0].content).toBe('note');
+ expect(result[0].fileList![0].originalCharCount).toBeUndefined();
+ });
+
+ it('should pick the oldest document when a file owns several', async () => {
+ const fileId = uuid();
+ const messageId = uuid();
+ const doc = {
+ fileId,
+ fileType: 'text/plain',
+ source: 'notes.txt',
+ sourceType: 'file',
+ totalLineCount: 1,
+ userId,
+ } as const;
+
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values({ id: 'session1', userId });
+ await trx.insert(files).values({
+ fileType: 'text/plain',
+ id: fileId,
+ name: 'notes.txt',
+ size: 100,
+ url: 'notes.txt',
+ userId,
+ });
+ // Inserted newest first: without an explicit order, a first-wins read would take the newer copy.
+ await trx.insert(documents).values({
+ ...doc,
+ content: 'page-editor copy',
+ createdAt: new Date('2026-02-01'),
+ totalCharCount: 16,
+ });
+ await trx.insert(documents).values({
+ ...doc,
+ content: 'parse cache',
+ createdAt: new Date('2026-01-01'),
+ totalCharCount: 11,
+ });
+
+ await trx.insert(messages).values({
+ content: 'Message with a twice-parsed file',
+ id: messageId,
+ role: 'user',
+ sessionId: 'session1',
+ userId,
+ });
+ await trx.insert(messagesFiles).values({ fileId, messageId, userId });
+ });
+
+ const result = await messageModel.query({ sessionId: 'session1' });
+
+ // Same document `DocumentModel.findByFileId` returns, which `readAttachment` pages through.
+ expect(result[0].fileList![0].content).toBe('parse cache');
+
+ const [byId] = await messageModel.queryByIds([messageId]);
+ expect(byId.fileList![0].content).toBe('parse cache');
});
});
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index c372bfa421c..07f3a47ed67 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -85,6 +85,7 @@ import { rehomeAgentQuotaBindingsForRecipient } from '../utils/agentQuotaBinding
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { resolveGroupMembershipType } from '../utils/groupMembership';
import { normalizeInboxAgentMeta } from '../utils/inboxAgent';
+import { readOriginalCharCount } from '../utils/parsedDocument';
import { sanitizeAgentApiConfig } from '../utils/sanitizeAgentApiConfig';
import { notShareVisitorTopic } from '../utils/shareVisitor';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
@@ -784,19 +785,30 @@ export class AgentModel {
.filter((f) => f.enabled)
.map((f) => f.id)
.filter((id) => id !== undefined);
- let files: Array<(typeof knowledge.files)[number] & { content?: string | null }> =
- knowledge.files;
+ let files: Array<
+ (typeof knowledge.files)[number] & { content?: string | null; originalCharCount?: number }
+ > = knowledge.files;
if (enabledFileIds.length > 0) {
const documentsData = await this.db.query.documents.findMany({
+ // A file can own several documents; take the oldest, like `DocumentModel.findByFileId`
+ // (which `readAttachment` pages through), so the preview and its continuation agree.
+ orderBy: [asc(documents.createdAt), asc(documents.id)],
where: and(this.documentsOwnership(), inArray(documents.fileId, enabledFileIds)),
});
- const documentMap = new Map(documentsData.map((doc) => [doc.fileId, doc.content]));
- files = knowledge.files.map((file) => ({
- ...file,
- content: file.enabled && file.id ? documentMap.get(file.id) : undefined,
- }));
+ const documentMap = new Map<string | null, (typeof documentsData)[number]>();
+ for (const doc of documentsData) {
+ if (!documentMap.has(doc.fileId)) documentMap.set(doc.fileId, doc);
+ }
+ files = knowledge.files.map((file) => {
+ const document = file.enabled && file.id ? documentMap.get(file.id) : undefined;
+ return {
+ ...file,
+ content: document?.content,
+ originalCharCount: readOriginalCharCount(document?.metadata),
+ };
+ });
}
return { ...normalizedAgent, ...knowledge, files };
diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.ts
index 1f6e8370123..fbf790ec472 100644
--- a/packages/database/src/models/document.ts
+++ b/packages/database/src/models/document.ts
@@ -5,7 +5,20 @@ import {
ordinaryFileAccessScope,
stripAgentShareDocumentProvenance,
} from '@lobechat/types';
-import { and, asc, count, desc, eq, inArray, isNull, ne, notInArray, or, sum } from 'drizzle-orm';
+import {
+ and,
+ asc,
+ count,
+ desc,
+ eq,
+ gt,
+ inArray,
+ isNull,
+ ne,
+ notInArray,
+ or,
+ sum,
+} from 'drizzle-orm';
import type { DocumentItem, NewDocument } from '../schemas';
import {
@@ -16,6 +29,8 @@ import {
documents,
files,
knowledgeBaseFiles,
+ messages,
+ messagesFiles,
nextDocumentUpdatedAt,
works,
} from '../schemas';
@@ -25,6 +40,7 @@ import {
fileReferenceMatchesAccessScope,
notAgentShareFileReference,
} from '../utils/fileVisibility';
+import { documentOriginalCharCount } from '../utils/originalCharCount';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
export interface QueryDocumentParams {
@@ -289,6 +305,55 @@ export class DocumentModel {
.where(and(this.readScope(), inArray(documents.id, ids)));
};
+ /**
+ * Whether a parsed document that prompts preview instead of inline exists for the given files or
+ * for any file attached to a message in `topicId`: longer than `minChars`, or cut at parse time
+ * (`metadata.originalCharCount` above the stored length). Mirrors `isOversizedFileContent` in
+ * `@lobechat/prompts`, so the run gets a tool that can read those previews in windows.
+ */
+ hasFileDocumentsOverChars = async ({
+ fileIds = [],
+ minChars,
+ topicId,
+ }: {
+ fileIds?: string[];
+ minChars: number;
+ topicId?: string | null;
+ }): Promise<boolean> => {
+ const fileConditions = [];
+ if (fileIds.length > 0) fileConditions.push(inArray(documents.fileId, fileIds));
+ if (topicId) {
+ fileConditions.push(
+ inArray(
+ documents.fileId,
+ this.db
+ .select({ fileId: messagesFiles.fileId })
+ .from(messagesFiles)
+ .innerJoin(messages, eq(messages.id, messagesFiles.messageId))
+ .where(eq(messages.topicId, topicId)),
+ ),
+ );
+ }
+ if (fileConditions.length === 0) return false;
+
+ const [row] = await this.db
+ .select({ id: documents.id })
+ .from(documents)
+ .where(
+ and(
+ this.ownership(),
+ or(
+ gt(documents.totalCharCount, minChars),
+ gt(documentOriginalCharCount(), documents.totalCharCount),
+ ),
+ or(...fileConditions),
+ ),
+ )
+ .limit(1);
+
+ return !!row;
+ };
+
findByFileId = async (fileId: string, accessScope: FileAccessScope = ordinaryFileAccessScope) => {
const [document] = await this.db
.select()
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index f02836439b5..eaa3575c205 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -98,12 +98,48 @@ import { notCopiedTranscript } from '../utils/copiedTranscript';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { idGenerator } from '../utils/idGenerator';
import { inJsonStringArray } from '../utils/inJsonStringArray';
+import { documentOriginalCharCount } from '../utils/originalCharCount';
import { searchableMessage } from '../utils/searchableMessage';
import { notShareVisitorMessage, notShareVisitorTopicRef } from '../utils/shareVisitor';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { recomputeTopicUsage } from './topicUsage';
import { WorkModel } from './work';
+/**
+ * Parsed-document columns attached to chat file items. `originalCharCount` is only set when the
+ * stored text was cut at parse time; prompts use it to tell the model the text is incomplete.
+ * Selected as a scalar so the rest of `metadata` never leaves the database.
+ */
+const fileDocumentColumns = {
+ content: documents.content,
+ fileId: documents.fileId,
+ originalCharCount: documentOriginalCharCount().mapWith(Number),
+};
+
+/**
+ * A file can own more than one document (`parseDocument` writes a page-editor copy next to the parse
+ * cache). Every reader picks the oldest, matching `DocumentModel.findByFileId`, so a preview and the
+ * `readAttachment` pages that continue it come from the same text.
+ */
+const fileDocumentsOrder = [asc(documents.createdAt), asc(documents.id)];
+
+type FileDocumentsMap = Record<string, { content: string; originalCharCount?: number }>;
+
+const toFileDocumentsMap = (
+ rows: { content: string | null; fileId: string | null; originalCharCount: number | null }[],
+): FileDocumentsMap =>
+ rows.reduce<FileDocumentsMap>((acc, doc) => {
+ // Rows arrive oldest first (see `fileDocumentsOrder`); keep the first so the prompt shows the
+ // same document `DocumentModel.findByFileId` — and therefore `readAttachment` — pages through.
+ if (doc.fileId && !(doc.fileId in acc)) {
+ acc[doc.fileId] = {
+ content: doc.content as string,
+ originalCharCount: doc.originalCharCount ?? undefined,
+ };
+ }
+ return acc;
+ }, {});
+
const createChatImageItem = ({
id,
metadata,
@@ -316,7 +352,7 @@ interface ActiveBranchSnapshot {
}
interface MessageFileRelations {
- documentsMap: Record<string, string>;
+ documentsMap: FileDocumentsMap;
relatedFileList: MessageRelatedFile[];
}
@@ -1672,7 +1708,8 @@ export class MessageModel {
name === null
? { fileType: '', id, inaccessible: true, name: '', size: 0, url: '' }
: {
- content: documentsMap[id],
+ content: documentsMap[id]?.content,
+ originalCharCount: documentsMap[id]?.originalCharCount,
fileType: fileType!,
id,
name,
@@ -1890,22 +1927,14 @@ export class MessageModel {
'db.message.queryWithWhere.documents.select',
() =>
this.db
- .select({
- content: documents.content,
- fileId: documents.fileId,
- })
+ .select(fileDocumentColumns)
.from(documents)
- .where(inArray(documents.fileId, fileIds)),
+ .where(inArray(documents.fileId, fileIds))
+ .orderBy(...fileDocumentsOrder),
{ fileCount: fileIds.length },
);
- const documentsMap = documentsList.reduce(
- (acc, doc) => {
- if (doc.fileId) acc[doc.fileId] = doc.content as string;
- return acc;
- },
- {} as Record<string, string>,
- );
+ const documentsMap = toFileDocumentsMap(documentsList);
return { documentsMap, relatedFileList };
};
@@ -2279,24 +2308,16 @@ export class MessageModel {
.map((file) => file.id)
.filter(Boolean);
- let documentsMap: Record<string, string> = {};
+ let documentsMap: FileDocumentsMap = {};
if (fileIds.length > 0) {
const documentsList = await this.db
- .select({
- content: documents.content,
- fileId: documents.fileId,
- })
+ .select(fileDocumentColumns)
.from(documents)
- .where(inArray(documents.fileId, fileIds));
+ .where(inArray(documents.fileId, fileIds))
+ .orderBy(...fileDocumentsOrder);
- documentsMap = documentsList.reduce(
- (acc, doc) => {
- if (doc.fileId) acc[doc.fileId] = doc.content as string;
- return acc;
- },
- {} as Record<string, string>,
- );
+ documentsMap = toFileDocumentsMap(documentsList);
}
const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));
@@ -2377,7 +2398,8 @@ export class MessageModel {
name === null
? { fileType: '', id, inaccessible: true, name: '', size: 0, url: '' }
: {
- content: documentsMap[id],
+ content: documentsMap[id]?.content,
+ originalCharCount: documentsMap[id]?.originalCharCount,
fileType: fileType!,
id,
name,
diff --git a/packages/database/src/utils/originalCharCount.ts b/packages/database/src/utils/originalCharCount.ts
new file mode 100644
index 00000000000..78dc9993c82
--- /dev/null
+++ b/packages/database/src/utils/originalCharCount.ts
@@ -0,0 +1,19 @@
+import type { SQL } from 'drizzle-orm';
+import { sql } from 'drizzle-orm';
+
+import { documents } from '../schemas';
+
+/**
+ * `documents.metadata.originalCharCount` as bigint, or NULL when absent or malformed.
+ *
+ * Document metadata is client-writable (`z.record(z.string(), z.any())`), so a plain `::bigint`
+ * cast would raise on a non-numeric value and fail the whole statement — one bad row would break
+ * message loading for its topic. Only a JSON number made of 1–18 digits is cast, which also keeps
+ * it within bigint range.
+ */
+export const documentOriginalCharCount = (): SQL<number | null> =>
+ sql<number | null>`CASE
+ WHEN jsonb_typeof(${documents.metadata} -> 'originalCharCount') = 'number'
+ AND (${documents.metadata} ->> 'originalCharCount') ~ '^[0-9]{1,18}$'
+ THEN (${documents.metadata} ->> 'originalCharCount')::bigint
+ END`;
diff --git a/packages/database/src/utils/parsedDocument.ts b/packages/database/src/utils/parsedDocument.ts
new file mode 100644
index 00000000000..e11ac0415c0
--- /dev/null
+++ b/packages/database/src/utils/parsedDocument.ts
@@ -0,0 +1,10 @@
+/**
+ * Character count of the original parsed text, recorded in document `metadata` when the stored
+ * `content` was cut at parse time. `undefined` for documents stored in full.
+ */
+export const readOriginalCharCount = (
+ metadata: Record<string, unknown> | null | undefined,
+): number | undefined => {
+ const value = metadata?.originalCharCount;
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+};
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 5a6b28c0299..e95ae53e7f8 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -92,6 +92,20 @@ export interface HashLocalFileParams {
path: string;
}
+export interface LocalFileStatsParams {
+ path: string;
+}
+
+/** Basic facts about a local file, so a model can plan how to read it before opening it. */
+export interface LocalFileStats {
+ /** Number of lines; omitted for binary files and files too large to scan. */
+ lineCount?: number;
+ /** Detected MIME type, when it can be determined. */
+ mimeType?: string;
+ /** Size in bytes. */
+ size: number;
+}
+
export interface LocalReadFileParams {
/** Working directory a relative `path` resolves against. See {@link ListLocalFileParams.cwd}. */
cwd?: string;
diff --git a/packages/file-loaders/src/loaders/excel/__snapshots__/index.test.ts.snap b/packages/file-loaders/src/loaders/excel/__snapshots__/index.test.ts.snap
index c024836b5cf..a9a9685835b 100644
--- a/packages/file-loaders/src/loaders/excel/__snapshots__/index.test.ts.snap
+++ b/packages/file-loaders/src/loaders/excel/__snapshots__/index.test.ts.snap
@@ -2,52 +2,52 @@
exports[`ExcelLoader > should aggregate content correctly (joining sheets) > aggregated_content 1`] = `
"<sheet name="表1" index="0">
-| __EMPTY | 类别 A | 类别 B | __EMPTY_1 | __EMPTY_2 |
-| --- | --- | --- | --- | --- |
-| 项目 1 | 5 | 7 | | |
-| 项目 2 | 10 | 8 | | |
-| 项目 3 | 9 | 15 | | |
-| 项目 4 | 7 | 12 | | |
-| 项目 5 | 16 | 21 | | |
+| __EMPTY | 类别 A | 类别 B |
+| --- | --- | --- |
+| 项目 1 | 5 | 7 |
+| 项目 2 | 10 | 8 |
+| 项目 3 | 9 | 15 |
+| 项目 4 | 7 | 12 |
+| 项目 5 | 16 | 21 |
</sheet>
<sheet name="表2 - 表格 2" index="1">
-| __EMPTY | 类别 A | 类别 B | __EMPTY_1 | __EMPTY_2 |
-| --- | --- | --- | --- | --- |
-| 项目 1 | 5 | 7 | | |
-| 项目 2 | 10 | 8 | | |
-| 项目 3 | 9 | 15 | | |
-| 项目 4 | 7 | 12 | | |
-| 项目 5 | 16 | 21 | | |
+| __EMPTY | 类别 A | 类别 B |
+| --- | --- | --- |
+| 项目 1 | 5 | 7 |
+| 项目 2 | 10 | 8 |
+| 项目 3 | 9 | 15 |
+| 项目 4 | 7 | 12 |
+| 项目 5 | 16 | 21 |
</sheet>"
`;
exports[`ExcelLoader > should handle Excel file with only headers > only_header_pages 1`] = `
[
{
- "charCount": 124,
+ "charCount": 82,
"lineCount": 3,
"metadata": {
"sheetName": "表1",
},
- "pageContent": "| 表格 1 | __EMPTY | __EMPTY_1 | __EMPTY_2 | __EMPTY_3 |
-| --- | --- | --- | --- | --- |
-| header1 | header2 | header3 | | |",
+ "pageContent": "| 表格 1 | __EMPTY | __EMPTY_1 |
+| --- | --- | --- |
+| header1 | header2 | header3 |",
},
{
- "charCount": 231,
+ "charCount": 159,
"lineCount": 8,
"metadata": {
"sheetName": "表2 - 表格 2",
},
- "pageContent": "| 表格 2 | __EMPTY | __EMPTY_1 | __EMPTY_2 | __EMPTY_3 |
-| --- | --- | --- | --- | --- |
-| | 类别 A | 类别 B | | |
-| 项目 1 | 5 | 7 | | |
-| 项目 2 | 10 | 8 | | |
-| 项目 3 | 9 | 15 | | |
-| 项目 4 | 7 | 12 | | |
-| 项目 5 | 16 | 21 | | |",
+ "pageContent": "| 表格 2 | __EMPTY | __EMPTY_1 |
+| --- | --- | --- |
+| | 类别 A | 类别 B |
+| 项目 1 | 5 | 7 |
+| 项目 2 | 10 | 8 |
+| 项目 3 | 9 | 15 |
+| 项目 4 | 7 | 12 |
+| 项目 5 | 16 | 21 |",
},
]
`;
@@ -55,32 +55,32 @@ exports[`ExcelLoader > should handle Excel file with only headers > only_header_
exports[`ExcelLoader > should load pages correctly from an Excel file (one page per sheet) 1`] = `
[
{
- "charCount": 201,
+ "charCount": 135,
"lineCount": 7,
"metadata": {
"sheetName": "表1",
},
- "pageContent": "| __EMPTY | 类别 A | 类别 B | __EMPTY_1 | __EMPTY_2 |
-| --- | --- | --- | --- | --- |
-| 项目 1 | 5 | 7 | | |
-| 项目 2 | 10 | 8 | | |
-| 项目 3 | 9 | 15 | | |
-| 项目 4 | 7 | 12 | | |
-| 项目 5 | 16 | 21 | | |",
+ "pageContent": "| __EMPTY | 类别 A | 类别 B |
+| --- | --- | --- |
+| 项目 1 | 5 | 7 |
+| 项目 2 | 10 | 8 |
+| 项目 3 | 9 | 15 |
+| 项目 4 | 7 | 12 |
+| 项目 5 | 16 | 21 |",
},
{
- "charCount": 201,
+ "charCount": 135,
"lineCount": 7,
"metadata": {
"sheetName": "表2 - 表格 2",
},
- "pageContent": "| __EMPTY | 类别 A | 类别 B | __EMPTY_1 | __EMPTY_2 |
-| --- | --- | --- | --- | --- |
-| 项目 1 | 5 | 7 | | |
-| 项目 2 | 10 | 8 | | |
-| 项目 3 | 9 | 15 | | |
-| 项目 4 | 7 | 12 | | |
-| 项目 5 | 16 | 21 | | |",
+ "pageContent": "| __EMPTY | 类别 A | 类别 B |
+| --- | --- | --- |
+| 项目 1 | 5 | 7 |
+| 项目 2 | 10 | 8 |
+| 项目 3 | 9 | 15 |
+| 项目 4 | 7 | 12 |
+| 项目 5 | 16 | 21 |",
},
]
`;
diff --git a/packages/file-loaders/src/loaders/excel/index.test.ts b/packages/file-loaders/src/loaders/excel/index.test.ts
index 0c951062304..de8e91e5359 100644
--- a/packages/file-loaders/src/loaders/excel/index.test.ts
+++ b/packages/file-loaders/src/loaders/excel/index.test.ts
@@ -1,6 +1,9 @@
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
import path from 'node:path';
import { beforeEach, describe, expect, it } from 'vitest';
+import * as xlsx from 'xlsx';
import type { FileLoaderInterface } from '../../types';
import { ExcelLoader } from './index';
@@ -53,4 +56,27 @@ describe('ExcelLoader', () => {
expect(pages[0].pageContent).toBeTruthy(); // Should contain header content
expect(pages).toMatchSnapshot('only_header_pages');
});
+
+ it('drops blank columns and rows from a sheet whose used range is stretched', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'excel-loader-'));
+ try {
+ const worksheet = xlsx.utils.aoa_to_sheet([['name', 'value'], ['a', 1], [], ['b', 2]]);
+ // Simulate formatting that stretches the used range far beyond the real data
+ worksheet['!ref'] = 'A1:ZZ2000';
+ const workbook = xlsx.utils.book_new();
+ xlsx.utils.book_append_sheet(workbook, worksheet, 'Sparse');
+ const filePath = path.join(dir, 'sparse.xlsx');
+ await writeFile(filePath, xlsx.write(workbook, { bookType: 'xlsx', type: 'buffer' }));
+
+ const pages = await loader.loadPages(filePath);
+
+ expect(pages[0].pageContent).toContain(
+ '| name | value |\n| --- | --- |\n| a | 1 |\n| b | 2 |',
+ );
+ expect(pages[0].pageContent).not.toContain('__EMPTY');
+ expect(pages[0].pageContent.length).toBeLessThan(500);
+ } finally {
+ await rm(dir, { force: true, recursive: true });
+ }
+ });
});
diff --git a/packages/file-loaders/src/loaders/excel/index.ts b/packages/file-loaders/src/loaders/excel/index.ts
index fa730fd4e86..820d469875b 100644
--- a/packages/file-loaders/src/loaders/excel/index.ts
+++ b/packages/file-loaders/src/loaders/excel/index.ts
@@ -19,8 +19,19 @@ function sheetToMarkdownTable(jsonData: Record<string, any>[]): string {
return '*Sheet is empty or contains no data.*';
}
- // Ensure all rows have the same keys based on the first row, handle potentially sparse data
- const headers = Object.keys(jsonData[0] || {});
+ const toCell = (value: unknown) =>
+ // Handle null/undefined and escape pipe characters within cells
+ value === null || value === undefined ? '' : String(value).replaceAll('|', '\\|').trim();
+
+ /**
+ * Keep only columns that hold a value in some row, and rows with at least one value.
+ * Formatting or stray edits can stretch a sheet's used range across thousands of blank columns
+ * and rows (the headers show up as `__EMPTY_n`); rendering every blank cell turned a 200 KB
+ * workbook into 60+ MB of `| | |` text.
+ */
+ const headers = Object.keys(jsonData[0] || {}).filter(
+ (header) => !header.startsWith('__EMPTY') || jsonData.some((row) => toCell(row[header]) !== ''),
+ );
log('Sheet headers:', headers);
if (headers.length === 0) {
log('Sheet has no headers, returning placeholder message');
@@ -32,16 +43,9 @@ function sheetToMarkdownTable(jsonData: Record<string, any>[]): string {
log('Building data rows for Markdown table');
const dataRows = jsonData
- .map((row) => {
- const cells = headers.map((header) => {
- const value = row[header];
- // Handle null/undefined and escape pipe characters within cells
- const cellContent =
- value === null || value === undefined ? '' : String(value).replaceAll('|', '\\|');
- return cellContent.trim(); // Trim whitespace from cells
- });
- return `| ${cells.join(' | ')} |`;
- })
+ .map((row) => headers.map((header) => toCell(row[header])))
+ .filter((cells) => cells.some((cell) => cell !== ''))
+ .map((cells) => `| ${cells.join(' | ')} |`)
.join('\n');
const result = `${headerRow}\n${separatorRow}\n${dataRows}`;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 1e29e5f10c8..53193fc1af3 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2494,6 +2494,8 @@ export default {
'File uploads are not supported in browser mode; only images are allowed.',
'upload.clientMode.visionNotSupported':
'The current model does not support visual recognition. Please switch to a different model to use this feature.',
+ 'upload.localPathReference':
+ 'Large files are referenced by their local path instead of uploaded, so the agent reads the original file directly.',
'upload.preview.prepareTasks': 'Preparing chunks...',
'upload.preview.status.cancelled': 'Upload cancelled',
'upload.preview.status.error': 'Upload failed',
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 724ff6741e2..c0e795324cb 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -1,4 +1,6 @@
export default {
+ 'builtins.lobe-attachments.apiName.readAttachment': 'Read attachment',
+ 'builtins.lobe-attachments.title': 'Attachments',
'builtins.lobe-goal-supervisor.apiName.inspectGoal': 'Inspect goal',
'builtins.lobe-goal-supervisor.apiName.inspectTask': 'Inspect interrupted task',
'builtins.lobe-goal-supervisor.apiName.readArtifact': 'Read goal artifact',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 09bd58875fe..3d0b874b724 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1778,6 +1778,9 @@ When I am ___, I need ___
'tab.uploadZip': 'Upload Zip',
'tab.uploadZip.desc': 'Upload a local .zip or .skill file',
'tab.usage': 'Usage',
+ 'tools.builtins.lobe-attachments.description':
+ 'Page through attached files that were too long to include in full',
+ 'tools.builtins.lobe-attachments.title': 'Attachments',
'workspace.create.descPlaceholder': 'Describe what this workspace is for (optional)',
'workspace.create.namePlaceholder': 'e.g. Acme Team',
'workspace.create.submit': 'Create workspace',
diff --git a/packages/mecha/package.json b/packages/mecha/package.json
index 32b9d018d06..8ecd902fcd1 100644
--- a/packages/mecha/package.json
+++ b/packages/mecha/package.json
@@ -17,6 +17,7 @@
"@lobechat/builtin-skills": "workspace:*",
"@lobechat/builtin-tool-agent-builder": "workspace:*",
"@lobechat/builtin-tool-agent-management": "workspace:*",
+ "@lobechat/builtin-tool-attachments": "workspace:*",
"@lobechat/builtin-tool-auv": "workspace:*",
"@lobechat/builtin-tool-browser": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
diff --git a/packages/mecha/src/toolSet/resolveToolRules.test.ts b/packages/mecha/src/toolSet/resolveToolRules.test.ts
index 4a543a0a8ab..fd359ca0625 100644
--- a/packages/mecha/src/toolSet/resolveToolRules.test.ts
+++ b/packages/mecha/src/toolSet/resolveToolRules.test.ts
@@ -30,6 +30,19 @@ describe('resolveToolRules', () => {
expect(resolveToolRules(request({ model: { canUseFC: false } })).toolMode).toBe('agent');
});
+ it('enables only the attachments tool when an oversized file is previewed', () => {
+ expect(resolveToolRules(request()).rules['lobe-attachments']).toBe(false);
+
+ const { rules } = resolveToolRules(request({ hasOversizedFiles: true }));
+ expect(rules['lobe-attachments']).toBe(true);
+ expect(rules['lobe-knowledge-base']).toBe(false);
+
+ const chatMode = resolveToolRules(
+ request({ agent: { chatConfig: { enableAgentMode: false } }, hasOversizedFiles: true }),
+ );
+ expect(chatMode.rules['lobe-attachments']).toBe(true);
+ });
+
it('chat mode is a strict whitelist with no activator and no always-on tools', () => {
const resolved = resolveToolRules(
request({
diff --git a/packages/mecha/src/toolSet/resolveToolRules.ts b/packages/mecha/src/toolSet/resolveToolRules.ts
index fef9b8d7c43..6c8b7b83a9a 100644
--- a/packages/mecha/src/toolSet/resolveToolRules.ts
+++ b/packages/mecha/src/toolSet/resolveToolRules.ts
@@ -1,3 +1,4 @@
+import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
@@ -57,6 +58,10 @@ export const resolveToolRules = (request: ToolRuleRequest): ResolvedToolRules =>
const searchMode = agent.chatConfig?.searchMode ?? 'auto';
const isSearchEnabled = request.useApplicationBuiltinSearchTool ?? searchMode !== 'off';
const kbEnabled = request.hasEnabledKnowledgeBases ?? false;
+ // Oversized attachments are sent as previews that can be paged with `readAttachment`; only that
+ // read-only tool is enabled, not the knowledge-base tool with its search and write APIs. The
+ // preview names it only when it survives into the final tool set (see `MessagesEngine`).
+ const attachmentsEnabled = request.hasOversizedFiles ?? false;
const memoryEnabled = request.memoryEnabled ?? false;
// Image generation is never auto-injected: the user opts in by pinning the
// tool, and a model with native image output never gets the fallback.
@@ -74,6 +79,7 @@ export const resolveToolRules = (request: ToolRuleRequest): ResolvedToolRules =>
// Chat mode: a strict outer whitelist. No always-on tools, no runtime
// injection, no activator — each entry still passes its own gate.
const chatModeRules = {
+ [AttachmentsManifest.identifier]: attachmentsEnabled,
[ImageGenerationManifest.identifier]: imageGenerationEnabled,
[VideoGenerationManifest.identifier]: videoGenerationEnabled,
[KnowledgeBaseManifest.identifier]: kbEnabled,
@@ -90,6 +96,7 @@ export const resolveToolRules = (request: ToolRuleRequest): ResolvedToolRules =>
// System rules may override the user's selection for specific tools.
// Auto mode lets the model pick the sandbox or the routed device per
// call, so the dedicated sandbox tool is offered there too.
+ [AttachmentsManifest.identifier]: attachmentsEnabled,
[CloudSandboxManifest.identifier]: runtimeMode === 'cloud' || executionTarget === 'auto',
[KnowledgeBaseManifest.identifier]: kbEnabled,
[LocalSystemManifest.identifier]: localToolsEnabled,
diff --git a/packages/mecha/src/toolSet/types.ts b/packages/mecha/src/toolSet/types.ts
index 78d487292db..b3ef8f3c08a 100644
--- a/packages/mecha/src/toolSet/types.ts
+++ b/packages/mecha/src/toolSet/types.ts
@@ -50,6 +50,11 @@ export interface ToolRuleRequest {
/** The run's effective execution target, resolved by the host. */
executionTarget: DeviceExecutionTarget;
hasEnabledKnowledgeBases?: boolean;
+ /**
+ * An attached or agent-assigned file is too long to inline and is sent as a preview; the
+ * attachments tool is enabled so the model can read the rest with `readAttachment`.
+ */
+ hasOversizedFiles?: boolean;
isBotConversation?: boolean;
/** Verified against the persisted roster, never a client claim. */
isGroupSupervisor?: boolean;
diff --git a/packages/prompts/package.json b/packages/prompts/package.json
index 75e3af87860..95f4f98b754 100644
--- a/packages/prompts/package.json
+++ b/packages/prompts/package.json
@@ -4,7 +4,8 @@
"private": true,
"exports": {
".": "./src/index.ts",
- "./fileSystem": "./src/prompts/fileSystem/index.ts"
+ "./fileSystem": "./src/prompts/fileSystem/index.ts",
+ "./textWindow": "./src/textWindow/index.ts"
},
"main": "./src/index.ts",
"scripts": {
diff --git a/packages/prompts/src/index.ts b/packages/prompts/src/index.ts
index 6217ca7b9b1..075a6bad52e 100644
--- a/packages/prompts/src/index.ts
+++ b/packages/prompts/src/index.ts
@@ -4,3 +4,4 @@ export * from './chains/goalExplore';
export * from './chains/goalSupervisor';
export * from './contexts';
export * from './prompts';
+export * from './textWindow';
diff --git a/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts b/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts
index 1cf6066128e..4aa070604ca 100644
--- a/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts
@@ -52,9 +52,9 @@ describe('formatFileContent', () => {
totalLines: 2545,
});
expect(result).toMatchInlineSnapshot(`
- "(lines 1-1000 of 2545)
- 1 line 1
- 2 line 2"
+ "1 line 1
+ 2 line 2
+ [Showing lines 1-1000 of 2545 lines. Lines 1001-2545 were left out.]"
`);
});
@@ -108,7 +108,7 @@ describe('formatFileContent', () => {
lineRange: [0, 2],
totalLines: 3,
});
- expect(result).toBe('(lines 1-2 of 3)\n1 a\n2 ');
+ expect(result).toBe('1 a\n2 \n[Showing lines 1-2 of 3 lines. Lines 3-3 were left out.]');
});
it('should cap the output after adding line numbers', () => {
diff --git a/packages/prompts/src/prompts/fileSystem/formatFileContent.ts b/packages/prompts/src/prompts/fileSystem/formatFileContent.ts
index 8a87f62f706..35d0ef5f539 100644
--- a/packages/prompts/src/prompts/fileSystem/formatFileContent.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatFileContent.ts
@@ -1,5 +1,12 @@
+import { formatTextWindowNotice, type TextWindowNoticeOptions } from '../../textWindow';
+
export interface FormatFileContentParams {
content: string;
+ /**
+ * Builds the call that reads the next window from a 1-based line. The read tools differ in
+ * argument shape (`loc` vs `startLine`), so each caller supplies its own.
+ */
+ continueFrom?: TextWindowNoticeOptions['continueFrom'];
/**
* 1-based line number of the first content line. When set, every line is
* prefixed with its line number (right-aligned, space-separated) so the
@@ -7,6 +14,7 @@ export interface FormatFileContentParams {
*/
firstLineNumber?: number;
lineRange?: [number, number];
+ totalChars?: number;
totalLines?: number;
/**
* The service cut the content at its character cap, so the window's tail
@@ -50,7 +58,9 @@ const numberLines = (
export const formatFileContent = ({
content,
+ continueFrom,
lineRange,
+ totalChars,
totalLines,
firstLineNumber,
truncated,
@@ -72,9 +82,9 @@ export const formatFileContent = ({
capped = true;
}
- // Only a window that stops before EOF gets a marker — that's the one piece
- // of information the numbered lines can't convey (how much is left). A
- // capped payload never claims the full window.
+ // Only a window that stops before EOF gets the shared window notice — how
+ // much is left and how to read it is the one piece of information the
+ // numbered lines can't convey. A capped payload never claims the full window.
if (
truncated ||
capped ||
@@ -86,8 +96,17 @@ export const formatFileContent = ({
return body;
}
- const start = firstLineNumber ?? lineRange[0];
- const marker = `(lines ${start}-${start + (end - lineRange[0]) - 1} of ${totalLines})`;
+ const startLine = firstLineNumber ?? lineRange[0];
+ const notice = formatTextWindowNotice(
+ {
+ endLine: startLine + (end - lineRange[0]) - 1,
+ startLine,
+ totalChars,
+ totalLines,
+ truncated: true,
+ },
+ { continueFrom },
+ );
- return `${marker}\n${body}`;
+ return `${body}\n${notice}`;
};
diff --git a/packages/prompts/src/prompts/fileSystem/formatGrepResults.test.ts b/packages/prompts/src/prompts/fileSystem/formatGrepResults.test.ts
index 16f130c4d32..f7f23393999 100644
--- a/packages/prompts/src/prompts/fileSystem/formatGrepResults.test.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatGrepResults.test.ts
@@ -63,7 +63,7 @@ describe('formatGrepResults', () => {
match18
match19
match20
- ... and 5 more"
+ [Showing 20 of 25 locations. To see the rest, narrow the search with a more specific pattern, path or glob.]"
`);
});
@@ -79,7 +79,7 @@ describe('formatGrepResults', () => {
match1
match2
match3
- ... and 2 more"
+ [Showing 3 of 5 locations. To see the rest, narrow the search with a more specific pattern, path or glob.]"
`);
});
});
diff --git a/packages/prompts/src/prompts/fileSystem/formatGrepResults.ts b/packages/prompts/src/prompts/fileSystem/formatGrepResults.ts
index ac49935817e..57a86da0dba 100644
--- a/packages/prompts/src/prompts/fileSystem/formatGrepResults.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatGrepResults.ts
@@ -29,8 +29,12 @@ export const formatGrepResults = ({
return ` ${parts.join('')}`;
})
.join('\n');
+ // Say how to reach the hidden matches instead of only counting them; the grep tool has no
+ // offset, so the way forward is a narrower search.
const moreInfo =
- matches.length > maxDisplay ? `\n ... and ${matches.length - maxDisplay} more` : '';
+ matches.length > maxDisplay
+ ? `\n[Showing ${maxDisplay} of ${matches.length} locations. To see the rest, narrow the search with a more specific pattern, path or glob.]`
+ : '';
return `${message}:\n${matchList}${moreInfo}`;
};
diff --git a/packages/prompts/src/prompts/files/file.ts b/packages/prompts/src/prompts/files/file.ts
index 8d7d4bfeaa6..2a942f6fd05 100644
--- a/packages/prompts/src/prompts/files/file.ts
+++ b/packages/prompts/src/prompts/files/file.ts
@@ -1,18 +1,105 @@
import type { ChatFileItem } from '@lobechat/types';
-const filePrompt = (item: ChatFileItem, addUrl: boolean) => {
- const content = item.content || '';
+import {
+ formatTextWindowAttributes,
+ formatTextWindowNotice,
+ MAX_READ_WINDOW_CHARS,
+ sliceTextWindow,
+} from '../../textWindow';
+
+/**
+ * Attachments whose extracted text exceeds this many characters are previewed instead of inlined.
+ *
+ * Parsed spreadsheets, CSV exports, and logs can reach 100+ MiB of text. Inlining them overflows
+ * every model's context window, and because history re-injects attachments on each turn, the
+ * whole topic keeps failing afterwards. Context compression cannot help: the latest user message
+ * is always kept intact.
+ */
+export const FILE_INLINE_MAX_CHARS = 100_000;
+
+/** Leading characters kept as a preview when an attachment exceeds `FILE_INLINE_MAX_CHARS`. */
+export const FILE_PREVIEW_CHARS = 4000;
+
+/** The exact `readAttachment` call that continues reading `fileId` from a 1-based line. */
+export const readAttachmentContinuation = (fileId: string) => (line: number) =>
+ `call readAttachment with fileId="${fileId}" and offset=${line}`;
+
+export interface PreviewLongFileContentOptions {
+ /**
+ * Whether `readAttachment` is in the tool set sent with this request. Only then does the preview
+ * name it as the way to continue; otherwise (custom tool modes, share visitors, clients without
+ * the tool) the model would be told to call a tool it does not have.
+ */
+ canReadAttachment?: boolean;
+ /** File id the model passes to `readAttachment` to page through the rest. */
+ fileId: string;
+ /** Original character count when the stored text was cut at parse time. */
+ originalChars?: number;
+}
+
+/**
+ * Whether a file's text is sent as a preview instead of inlined: it exceeds
+ * `FILE_INLINE_MAX_CHARS`, or the stored text is shorter than the original. The database query
+ * tool discovery uses to enable `readAttachment` mirrors this predicate.
+ */
+export const isOversizedFileContent = (contentLength: number, originalChars?: number) =>
+ contentLength > FILE_INLINE_MAX_CHARS ||
+ (originalChars !== undefined && originalChars > contentLength);
+
+/**
+ * Inline a file's text, or replace it with a preview when it exceeds `FILE_INLINE_MAX_CHARS` or
+ * its stored text is known to be incomplete. The preview uses the shared text-window contract:
+ * attributes report the window and full size, and — when `readAttachment` is available — the
+ * notice names the exact call for the next window.
+ */
+export const previewLongFileContent = (
+ content: string,
+ { canReadAttachment = false, fileId, originalChars }: PreviewLongFileContentOptions,
+) => {
+ if (!isOversizedFileContent(content.length, originalChars)) {
+ return { attributes: '', body: content };
+ }
+
+ const window = sliceTextWindow(content, { maxChars: FILE_PREVIEW_CHARS });
+ const options = canReadAttachment
+ ? {
+ continueFrom: readAttachmentContinuation(fileId),
+ continueMaxChars: MAX_READ_WINDOW_CHARS,
+ originalChars,
+ }
+ : { originalChars };
+ const notice = formatTextWindowNotice(window, options);
+ const preamble = canReadAttachment
+ ? '[This is a preview, not the complete file. Do not ask the user to paste the rest.]'
+ : '[This is a preview, not the complete file, and no tool to read the rest is available here. Answer from the preview, and tell the user when the answer depends on the omitted part.]';
+
+ return {
+ attributes: formatTextWindowAttributes(window, options),
+ body: `${window.content}\n${preamble}${notice ? `\n${notice}` : ''}`,
+ };
+};
+
+const filePrompt = (item: ChatFileItem, addUrl: boolean, canReadAttachment: boolean) => {
+ const { attributes, body } = previewLongFileContent(item.content || '', {
+ canReadAttachment,
+ fileId: item.id,
+ originalChars: item.originalCharCount,
+ });
return addUrl
- ? `<file id="${item.id}" name="${item.name}" type="${item.fileType}" size="${item.size}" url="${item.url}">${content}</file>`
- : `<file id="${item.id}" name="${item.name}" type="${item.fileType}" size="${item.size}">${content}</file>`;
+ ? `<file id="${item.id}" name="${item.name}" type="${item.fileType}" size="${item.size}" url="${item.url}"${attributes}>${body}</file>`
+ : `<file id="${item.id}" name="${item.name}" type="${item.fileType}" size="${item.size}"${attributes}>${body}</file>`;
};
-export const filePrompts = (fileList: ChatFileItem[], addUrl: boolean) => {
+export const filePrompts = (
+ fileList: ChatFileItem[],
+ addUrl: boolean,
+ canReadAttachment = false,
+) => {
if (fileList.length === 0) return '';
const prompt = `<files>
<files_docstring>here are user upload files you can refer to</files_docstring>
-${fileList.map((item) => filePrompt(item, addUrl)).join('\n')}
+${fileList.map((item) => filePrompt(item, addUrl, canReadAttachment)).join('\n')}
</files>`;
return prompt.trim();
diff --git a/packages/prompts/src/prompts/files/index.test.ts b/packages/prompts/src/prompts/files/index.test.ts
index 65522e707fc..0de752d432b 100644
--- a/packages/prompts/src/prompts/files/index.test.ts
+++ b/packages/prompts/src/prompts/files/index.test.ts
@@ -2,6 +2,7 @@ import { createMediaFileRef } from '@lobechat/const/mediaRef';
import type { ChatAudioItem, ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
+import { FILE_INLINE_MAX_CHARS, FILE_PREVIEW_CHARS } from './file';
import { filesPrompts } from './index';
describe('filesPrompts', () => {
@@ -383,4 +384,83 @@ describe('filesPrompts', () => {
expect(result).toEqual('');
});
});
+
+ describe('large attachments', () => {
+ it('inlines content up to the limit unchanged', () => {
+ const content = 'a'.repeat(FILE_INLINE_MAX_CHARS);
+ const result = filesPrompts({ addUrl: false, fileList: [{ ...mockFile, content }] });
+
+ expect(result).toContain(`size="1024">${content}</file>`);
+ expect(result).not.toContain('truncated="true"');
+ });
+
+ it('replaces oversized content with a marked preview', () => {
+ const content = `${'a'.repeat(FILE_PREVIEW_CHARS)}${'b'.repeat(FILE_INLINE_MAX_CHARS)}`;
+ const result = filesPrompts({ addUrl: true, fileList: [{ ...mockFile, content }] });
+
+ expect(result).toContain(
+ `url="https://example.com/test.pdf" lines="1-1" total_lines="1" total_chars="${content.length}" truncated="true">${'a'.repeat(FILE_PREVIEW_CHARS)}\n[This is a preview, not the complete file`,
+ );
+ expect(result).toContain(
+ `Line 1 is ${content.length} characters long and was cut at ${FILE_PREVIEW_CHARS}`,
+ );
+ expect(result).not.toContain('bbbb');
+ });
+
+ it('previews whole lines and names the readAttachment call for the next window', () => {
+ const content = 'row,value\n'.repeat(FILE_INLINE_MAX_CHARS / 10 + 1);
+ const result = filesPrompts({
+ addUrl: false,
+ canReadAttachment: true,
+ fileList: [{ ...mockFile, content }],
+ });
+
+ expect(result).toContain(`lines="1-400" total_lines="${FILE_INLINE_MAX_CHARS / 10 + 2}"`);
+ expect(result).toContain(
+ `To continue, call readAttachment with fileId="${mockFile.id}" and offset=401.`,
+ );
+ });
+
+ it('does not promise readAttachment when the request does not carry the tool', () => {
+ const content = 'row,value\n'.repeat(FILE_INLINE_MAX_CHARS / 10 + 1);
+ const result = filesPrompts({ addUrl: false, fileList: [{ ...mockFile, content }] });
+
+ expect(result).toContain(`lines="1-400" total_lines="${FILE_INLINE_MAX_CHARS / 10 + 2}"`);
+ expect(result).toContain('no tool to read the rest is available here');
+ expect(result).toContain(`Lines 401-${FILE_INLINE_MAX_CHARS / 10 + 2} were left out.`);
+ expect(result).not.toContain('readAttachment');
+ });
+
+ it('re-reads a long first line in full when readAttachment can hold it', () => {
+ // One line longer than the preview but within one readAttachment window.
+ const content = `${'a'.repeat(6000)}\n${'row,value\n'.repeat(FILE_INLINE_MAX_CHARS / 10)}`;
+ const result = filesPrompts({
+ addUrl: false,
+ canReadAttachment: true,
+ fileList: [{ ...mockFile, content }],
+ });
+
+ expect(result).toContain(
+ `Line 1 is 6000 characters long and was cut at ${FILE_PREVIEW_CHARS}. To read it in full and continue, call readAttachment with fileId="${mockFile.id}" and offset=1.`,
+ );
+ expect(result).not.toContain('cannot be paged');
+ });
+
+ it('marks stored text that was cut at parse time even when it is short', () => {
+ const result = filesPrompts({
+ addUrl: false,
+ fileList: [{ ...mockFile, content: 'head', originalCharCount: 9_000_000 }],
+ });
+
+ expect(result).toContain('truncated="true" original_chars="9000000"');
+ expect(result).toContain('only the first 4 of the original 9000000 characters were kept');
+ });
+
+ it('counts lines of oversized content', () => {
+ const content = 'line\n'.repeat(FILE_INLINE_MAX_CHARS / 5 + 1);
+ const result = filesPrompts({ addUrl: false, fileList: [{ ...mockFile, content }] });
+
+ expect(result).toContain(`total_lines="${FILE_INLINE_MAX_CHARS / 5 + 2}"`);
+ });
+ });
});
diff --git a/packages/prompts/src/prompts/files/index.ts b/packages/prompts/src/prompts/files/index.ts
index 146b12a66cc..595374e9ab1 100644
--- a/packages/prompts/src/prompts/files/index.ts
+++ b/packages/prompts/src/prompts/files/index.ts
@@ -5,6 +5,13 @@ import { filePrompts } from './file';
import { imagesPrompts } from './image';
import { videosPrompts } from './video';
+export {
+ FILE_INLINE_MAX_CHARS,
+ FILE_PREVIEW_CHARS,
+ isOversizedFileContent,
+ previewLongFileContent,
+ readAttachmentContinuation,
+} from './file';
export type { KnowledgeBaseInfo, PromptKnowledgeOptions } from './knowledgeBase';
export { promptAgentKnowledge } from './knowledgeBase';
@@ -14,9 +21,12 @@ export const filesPrompts = ({
videoList,
audioList,
addUrl = true,
+ canReadAttachment = false,
messageId,
}: {
addUrl?: boolean;
+ /** Whether `readAttachment` is in the request's tool set; see `PreviewLongFileContentOptions`. */
+ canReadAttachment?: boolean;
audioList?: ChatAudioItem[];
fileList?: ChatFileItem[];
imageList?: ChatImageItem[];
@@ -32,7 +42,7 @@ export const filesPrompts = ({
const contentParts = [
hasImages ? imagesPrompts(imageList!, addUrl, messageId) : '',
- hasFiles ? filePrompts(fileList!, addUrl) : '',
+ hasFiles ? filePrompts(fileList!, addUrl, canReadAttachment) : '',
hasVideos ? videosPrompts(videoList!, addUrl, messageId) : '',
hasAudios ? audiosPrompts(audioList!, addUrl, messageId) : '',
].filter(Boolean);
diff --git a/packages/prompts/src/prompts/files/knowledgeBase.test.ts b/packages/prompts/src/prompts/files/knowledgeBase.test.ts
index b029d555bf1..69850f45892 100644
--- a/packages/prompts/src/prompts/files/knowledgeBase.test.ts
+++ b/packages/prompts/src/prompts/files/knowledgeBase.test.ts
@@ -1,10 +1,35 @@
import { describe, expect, it } from 'vitest';
import type { FileContent } from '../knowledgeBaseQA';
+import { FILE_INLINE_MAX_CHARS, FILE_PREVIEW_CHARS } from './file';
import type { KnowledgeBaseInfo } from './knowledgeBase';
import { promptAgentKnowledge } from './knowledgeBase';
describe('promptAgentKnowledge', () => {
+ it('should preview oversized agent files instead of inlining them', () => {
+ const content = `${'a'.repeat(FILE_PREVIEW_CHARS)}\n${'b'.repeat(FILE_INLINE_MAX_CHARS)}`;
+ const result = promptAgentKnowledge({
+ canReadAttachment: true,
+ fileContents: [{ content, fileId: 'file1', filename: 'big.csv' }],
+ });
+
+ expect(result).toContain(
+ `<file id="file1" name="big.csv" lines="1-1" total_lines="2" total_chars="${content.length}" truncated="true">`,
+ );
+ expect(result).toContain('To continue, call readAttachment with fileId="file1" and offset=2.');
+ expect(result).not.toContain('bbbb');
+ });
+
+ it('should not promise readAttachment for oversized agent files without the tool', () => {
+ const content = `${'a'.repeat(FILE_PREVIEW_CHARS)}\n${'b'.repeat(FILE_INLINE_MAX_CHARS)}`;
+ const result = promptAgentKnowledge({
+ fileContents: [{ content, fileId: 'file1', filename: 'big.csv' }],
+ });
+
+ expect(result).toContain('Lines 2-2 were left out.');
+ expect(result).not.toContain('readAttachment');
+ });
+
it('should return empty string when no files and no knowledge bases', () => {
const result = promptAgentKnowledge({});
expect(result).toBe('');
diff --git a/packages/prompts/src/prompts/files/knowledgeBase.ts b/packages/prompts/src/prompts/files/knowledgeBase.ts
index f4a83b1a52e..5d80b3adf0a 100644
--- a/packages/prompts/src/prompts/files/knowledgeBase.ts
+++ b/packages/prompts/src/prompts/files/knowledgeBase.ts
@@ -1,4 +1,5 @@
import type { FileContent } from '../knowledgeBaseQA';
+import { previewLongFileContent } from './file';
export interface KnowledgeBaseInfo {
description?: string | null;
@@ -7,6 +8,8 @@ export interface KnowledgeBaseInfo {
}
export interface PromptKnowledgeOptions {
+ /** Whether `readAttachment` is in the request's tool set; see `PreviewLongFileContentOptions`. */
+ canReadAttachment?: boolean;
/** File contents to inject */
fileContents?: FileContent[];
/** Knowledge bases to include */
@@ -16,13 +19,19 @@ export interface PromptKnowledgeOptions {
/**
* Formats a single file content with XML tags
*/
-const formatFileContent = (file: FileContent): string => {
+const formatFileContent = (file: FileContent, canReadAttachment: boolean): string => {
if (file.error) {
return `<file id="${file.fileId}" name="${file.filename}" error="${file.error}" />`;
}
- return `<file id="${file.fileId}" name="${file.filename}">
-${file.content}
+ // Agent files are re-sent on every turn, so oversized ones get the same preview as attachments.
+ const { attributes, body } = previewLongFileContent(file.content, {
+ canReadAttachment,
+ fileId: file.fileId,
+ originalChars: file.originalChars,
+ });
+ return `<file id="${file.fileId}" name="${file.filename}"${attributes}>
+${body}
</file>`;
};
@@ -30,6 +39,7 @@ ${file.content}
* Format agent knowledge (files + knowledge bases) as unified XML prompt
*/
export const promptAgentKnowledge = ({
+ canReadAttachment = false,
fileContents = [],
knowledgeBases = [],
}: PromptKnowledgeOptions) => {
@@ -60,7 +70,9 @@ export const promptAgentKnowledge = ({
// Add files section
if (hasFiles) {
- const filesXml = fileContents.map((file) => formatFileContent(file)).join('\n');
+ const filesXml = fileContents
+ .map((file) => formatFileContent(file, canReadAttachment))
+ .join('\n');
contentParts.push(`<files totalCount="${fileContents.length}">
${filesXml}
</files>`);
diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap
index 076191901df..30411b6db84 100644
--- a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap
+++ b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap
@@ -77,12 +77,12 @@ Another successfully loaded file with more content.
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">
+<file id="file-paged" name="long.md" lines="1-2" total_lines="800" total_chars="30334" truncated="true">
line 1
line 2
-[Showing lines 1-2 of 800. Call readKnowledge again with offset=3 to continue.]
+[Showing lines 1-2 of 800 lines, 30334 characters. To continue, call readKnowledge with fileIds=["file-paged"] and offset=3.]
</file>
-<file id="file-complete" name="short.md" lines="1-1" totalLines="1" totalChars="9" truncated="false">
+<file id="file-complete" name="short.md" lines="1-1" total_lines="1" total_chars="9" truncated="false">
tail line
</file>
</knowledge_base_files>"
diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts
index 1334841d087..a5e622a9053 100644
--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts
+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts
@@ -125,15 +125,15 @@ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
range: {
endLine: 0,
startLine: 900,
- totalCharCount: 100,
- totalLineCount: 800,
+ totalChars: 100,
+ totalLines: 800,
truncated: false,
},
},
]);
expect(result).toContain('lines="900-0"');
- expect(result).toContain('offset 900 is past the end of this 800-line file');
+ expect(result).toContain('Line 900 is past the end of this text (800 lines, 100 characters)');
});
it('should explain a line that was cut to fit the per-call cap', () => {
@@ -146,15 +146,17 @@ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
cutLine: { keptChars: 10, line: 1, totalChars: 30_000 },
endLine: 1,
startLine: 1,
- totalCharCount: 30_002,
- totalLineCount: 2,
+ totalChars: 30_002,
+ totalLines: 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');
+ expect(result).toContain(
+ 'To continue with the next line, call readKnowledge with fileIds=["file-cut"] and offset=2.',
+ );
});
it('should render a paged window with range attributes and a continue notice', () => {
@@ -166,8 +168,8 @@ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
range: {
endLine: 2,
startLine: 1,
- totalCharCount: 30_334,
- totalLineCount: 800,
+ totalChars: 30_334,
+ totalLines: 800,
truncated: true,
},
},
@@ -178,8 +180,8 @@ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
range: {
endLine: 1,
startLine: 1,
- totalCharCount: 9,
- totalLineCount: 1,
+ totalChars: 9,
+ totalLines: 1,
truncated: false,
},
},
@@ -187,8 +189,33 @@ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
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');
+ expect(result).toContain('lines="1-2" total_lines="800" total_chars="30334" truncated="true"');
+ expect(result).toContain(
+ '[Showing lines 1-2 of 800 lines, 30334 characters. To continue, call readKnowledge with fileIds=["file-paged"] and offset=3.]',
+ );
+ expect(result).not.toContain('offset=2');
+ });
+
+ it('should say the stored text is incomplete when the original file was longer', () => {
+ const result = promptFileContents([
+ {
+ content: 'last line',
+ fileId: 'file-capped',
+ filename: 'huge.csv',
+ originalChars: 9_000_000,
+ range: {
+ endLine: 80,
+ startLine: 80,
+ totalChars: 5_000_000,
+ totalLines: 80,
+ truncated: false,
+ },
+ },
+ ]);
+
+ expect(result).toContain('truncated="true" original_chars="9000000"');
+ expect(result).toContain(
+ 'only the first 5000000 of the original 9000000 characters were kept, ending at line 80',
+ );
});
});
diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts
index 0fe7e6be388..6ee4dc91202 100644
--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts
+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts
@@ -1,51 +1,32 @@
+import {
+ formatTextWindowAttributes,
+ formatTextWindowNotice,
+ type TextWindowRange,
+} from '../../textWindow';
+
/**
* 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 type FileContentRange = TextWindowRange;
export interface FileContent {
content: string;
error?: string;
fileId: string;
filename: string;
+ /**
+ * Character count of the original file when its stored text was cut at parse time, so the
+ * model learns the text it pages through is not the whole file.
+ */
+ originalChars?: number;
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.]`;
-};
+/** The exact readKnowledge call that continues reading `fileId` from a 1-based line. */
+export const readKnowledgeContinuation = (fileId: string) => (line: number) =>
+ `call readKnowledge with fileIds=["${fileId}"] and offset=${line}`;
/**
* Formats a single file content with XML tags
@@ -55,8 +36,13 @@ const formatFileContent = (file: FileContent): string => {
return `<file id="${file.fileId}" name="${file.filename}" error="${file.error}" />`;
}
- const rangeAttributes = file.range ? formatRangeAttributes(file.range) : '';
- const rangeNotice = file.range ? formatRangeNotice(file.range) : '';
+ const options = {
+ continueFrom: readKnowledgeContinuation(file.fileId),
+ originalChars: file.originalChars,
+ };
+ const rangeAttributes = file.range ? formatTextWindowAttributes(file.range, options) : '';
+ const notice = file.range ? formatTextWindowNotice(file.range, options) : '';
+ const rangeNotice = notice ? `\n${notice}` : '';
return `<file id="${file.fileId}" name="${file.filename}"${rangeAttributes}>
${file.content}${rangeNotice}
diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/index.ts b/packages/prompts/src/prompts/knowledgeBaseQA/index.ts
index 390bd92c5c7..562d8b432b7 100644
--- a/packages/prompts/src/prompts/knowledgeBaseQA/index.ts
+++ b/packages/prompts/src/prompts/knowledgeBaseQA/index.ts
@@ -5,7 +5,7 @@ import { knowledgePrompts } from './knowledge';
import { userQueryPrompt } from './userQuery';
export type { FileContent, FileContentRange } from './formatFileContents';
-export { promptFileContents } from './formatFileContents';
+export { promptFileContents, readKnowledgeContinuation } from './formatFileContents';
export { promptNoSearchResults } from './formatNoSearchResults';
export type { FileSearchResult, FileSearchResultChunk } from './formatSearchResults';
export { formatSearchResults } from './formatSearchResults';
diff --git a/packages/prompts/src/textWindow/index.test.ts b/packages/prompts/src/textWindow/index.test.ts
new file mode 100644
index 00000000000..59adc444270
--- /dev/null
+++ b/packages/prompts/src/textWindow/index.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ appendTextWindowNotice,
+ countLines,
+ formatTextWindowAttributes,
+ formatTextWindowNotice,
+ sliceHead,
+ sliceTextWindow,
+} from './index';
+
+const continueFrom = (line: number) => `call read with offset=${line}`;
+
+describe('sliceHead', () => {
+ it('does not split a surrogate pair', () => {
+ const emoji = '🐛';
+ expect(sliceHead(`ab${emoji}`, 3)).toBe('ab');
+ expect(sliceHead(`ab${emoji}`, 4)).toBe(`ab${emoji}`);
+ });
+});
+
+describe('countLines', () => {
+ it('counts newline-separated lines', () => {
+ expect(countLines('')).toBe(1);
+ expect(countLines('a\nb\n')).toBe(3);
+ });
+});
+
+describe('sliceTextWindow', () => {
+ it('returns the whole text when it fits', () => {
+ expect(sliceTextWindow('a\nb')).toEqual({
+ content: 'a\nb',
+ endLine: 2,
+ startLine: 1,
+ totalChars: 3,
+ totalLines: 2,
+ truncated: false,
+ });
+ });
+
+ it('stops at whole lines when the character budget is hit', () => {
+ const window = sliceTextWindow('aaaa\nbbbb\ncccc', { maxChars: 10 });
+
+ expect(window.content).toBe('aaaa\nbbbb');
+ expect(window.endLine).toBe(2);
+ expect(window.truncated).toBe(true);
+ });
+
+ it('fills the remaining budget with the head of a line that can never fit', () => {
+ const window = sliceTextWindow(`short\n${'x'.repeat(100)}\nnext`, { maxChars: 20 });
+
+ expect(window.content).toBe(`short\n${'x'.repeat(14)}`);
+ expect(window.endLine).toBe(2);
+ expect(window.cutLine).toEqual({ keptChars: 14, line: 2, totalChars: 100 });
+ });
+
+ it('leaves a line that fits a later window for that window', () => {
+ const window = sliceTextWindow(`short\n${'x'.repeat(18)}`, { maxChars: 20 });
+
+ expect(window.content).toBe('short');
+ expect(window.cutLine).toBeUndefined();
+ });
+});
+
+describe('formatTextWindowNotice', () => {
+ it('is empty for a complete window', () => {
+ expect(formatTextWindowNotice(sliceTextWindow('a\nb'), { continueFrom })).toBe('');
+ });
+
+ it('reports the range, total size and the next call', () => {
+ const window = sliceTextWindow('a\nb\nc', { maxLines: 2 });
+
+ expect(formatTextWindowNotice(window, { continueFrom })).toBe(
+ '[Showing lines 1-2 of 3 lines, 5 characters. To continue, call read with offset=3.]',
+ );
+ });
+
+ it('says what was left out when the text cannot be paged', () => {
+ const window = sliceTextWindow('a\nb\nc', { maxLines: 1 });
+
+ expect(formatTextWindowNotice(window)).toBe(
+ '[Showing lines 1-1 of 3 lines, 5 characters. Lines 2-3 were left out.]',
+ );
+ });
+
+ it('explains a cut line and continues after it', () => {
+ const window = sliceTextWindow(`${'x'.repeat(30)}\nb`, { maxChars: 10 });
+
+ expect(formatTextWindowNotice(window, { continueFrom })).toBe(
+ '[Showing lines 1-1 of 2 lines, 32 characters. Line 1 is 30 characters long and was cut at 10; the rest of that line cannot be paged. To continue with the next line, call read with offset=2.]',
+ );
+ });
+
+ it('re-reads a cut line in full when the continuation budget holds it', () => {
+ const window = sliceTextWindow(`${'x'.repeat(30)}\nb`, { maxChars: 10 });
+
+ expect(formatTextWindowNotice(window, { continueFrom, continueMaxChars: 30 })).toBe(
+ '[Showing lines 1-1 of 2 lines, 32 characters. Line 1 is 30 characters long and was cut at 10. To read it in full and continue, call read with offset=1.]',
+ );
+ // A line the continuation cannot hold either is still skipped, or paging would stall on it.
+ expect(formatTextWindowNotice(window, { continueFrom, continueMaxChars: 29 })).toContain(
+ 'the rest of that line cannot be paged. To continue with the next line, call read with offset=2.',
+ );
+ });
+
+ it('reports an offset past the end', () => {
+ const window = sliceTextWindow('a\nb', { offset: 5 });
+
+ expect(formatTextWindowNotice(window, { continueFrom })).toContain(
+ 'Line 5 is past the end of this text (2 lines, 3 characters)',
+ );
+ });
+
+ it('says the stored text is incomplete when the original was longer', () => {
+ const window = sliceTextWindow('a\nb');
+ const notice = formatTextWindowNotice(window, { continueFrom, originalChars: 9000 });
+
+ expect(notice).toContain('only the first 3 of the original 9000 characters were kept');
+ expect(notice).toContain('ending at line 2');
+ expect(formatTextWindowNotice(window, { originalChars: 3 })).toBe('');
+ });
+});
+
+describe('formatTextWindowAttributes', () => {
+ it('describes the window and the original size', () => {
+ const window = sliceTextWindow('a\nb\nc', { maxLines: 2 });
+
+ expect(formatTextWindowAttributes(window)).toBe(
+ ' lines="1-2" total_lines="3" total_chars="5" truncated="true"',
+ );
+ expect(formatTextWindowAttributes(sliceTextWindow('a'), { originalChars: 50 })).toBe(
+ ' lines="1-1" total_lines="1" total_chars="1" truncated="true" original_chars="50"',
+ );
+ });
+});
+
+describe('appendTextWindowNotice', () => {
+ it('returns content alone when nothing was left out', () => {
+ expect(appendTextWindowNotice(sliceTextWindow('abc'))).toBe('abc');
+ });
+});
diff --git a/packages/prompts/src/textWindow/index.ts b/packages/prompts/src/textWindow/index.ts
new file mode 100644
index 00000000000..1e21953ee7d
--- /dev/null
+++ b/packages/prompts/src/textWindow/index.ts
@@ -0,0 +1,280 @@
+/**
+ * One truncation contract for every place that shows the model part of a long text: attachment
+ * previews, knowledge-file reads, agent-document reads, archived tool results, crawled pages and
+ * local file reads.
+ *
+ * Borrowed from how Claude Code, Codex, opencode and pi handle long reads:
+ * - cut on line boundaries, bounded by both a line count and a character budget;
+ * - always tell the model the full size and the exact range it received;
+ * - end with the exact call that reads the next window, so the model can load progressively
+ * instead of guessing or asking the user to paste the rest;
+ * - say so explicitly when the stored text is itself shorter than the original, because paging can
+ * never reach content that was not stored.
+ */
+
+export interface TextWindowOptions {
+ /** Maximum characters of `content`. Defaults to unbounded. */
+ maxChars?: number;
+ /** Maximum number of lines. Defaults to unbounded. */
+ maxLines?: number | string;
+ /** 1-based line to start from. Defaults to 1. */
+ offset?: number | string;
+}
+
+/** Position of a window inside the full text. Shared by every notice and attribute formatter. */
+export interface TextWindowRange {
+ /**
+ * Set when a line longer than the character budget was cut to fit. Line-based paging cannot
+ * reach the rest of that line, so notices say so instead of promising more.
+ */
+ cutLine?: { keptChars: number; line: number; totalChars: number };
+ /** 1-based, inclusive. `0` when the window is empty. */
+ endLine: number;
+ /** 1-based, inclusive. */
+ startLine: number;
+ /** Omitted by callers that only know the line count (e.g. a remote file read). */
+ totalChars?: number;
+ totalLines: number;
+ /** True when content after the window exists: later lines, or the rest of a cut line. */
+ truncated: boolean;
+}
+
+export interface TextWindow extends TextWindowRange {
+ content: string;
+ totalChars: number;
+}
+
+export interface TextWindowNoticeOptions {
+ /**
+ * Builds the instruction that reads from a given 1-based line, e.g.
+ * `(line) => \`call readKnowledge again with offset=${line}\``. Omit it when the text cannot be
+ * paged; the notice then only reports what was left out.
+ */
+ continueFrom?: (line: number) => string;
+ /**
+ * Character budget of the call `continueFrom` names, when it is larger than the budget that cut
+ * this window (a 4k attachment preview continued by a 10k `readAttachment`). A cut line that fits
+ * this budget can be re-read whole from its own line, so the notice points there instead of
+ * skipping it.
+ */
+ continueMaxChars?: number;
+ /**
+ * Character count of the original text when the stored text was cut before it was stored (for
+ * example a parsed file above the parse-time cap). Ignored unless larger than `totalChars`.
+ */
+ originalChars?: number;
+}
+
+const toInteger = (value: number | string | undefined, fallback: number, min: 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.max(min, Math.floor(parsed));
+};
+
+/**
+ * Returns at most `maxChars` leading characters without splitting a UTF-16 surrogate pair.
+ * A lone high surrogate serializes to a `\uD83D`-style escape that some providers (DeepSeek,
+ * Anthropic) reject as "unexpected end of hex escape".
+ */
+export const sliceHead = (text: string, maxChars: number): string => {
+ if (text.length <= maxChars) return text;
+
+ let cutoff = Math.max(0, maxChars);
+ const lastCharCode = text.charCodeAt(cutoff - 1);
+ if (lastCharCode >= 0xd8_00 && lastCharCode <= 0xdb_ff) cutoff -= 1;
+
+ return text.slice(0, cutoff);
+};
+
+export const countLines = (text: string): number => {
+ let lines = 1;
+ for (let index = text.indexOf('\n'); index !== -1; index = text.indexOf('\n', index + 1)) {
+ lines += 1;
+ }
+ return lines;
+};
+
+/**
+ * Cuts a window of whole lines out of `text`, starting at `offset`, bounded by `maxLines` and
+ * `maxChars` (whichever is hit first).
+ *
+ * A line longer than `maxChars` can never be returned whole, so it is cut to the remaining budget
+ * and reported as `cutLine`; the next window starts after it so paging cannot stall.
+ */
+export const sliceTextWindow = (text: string, options: TextWindowOptions = {}): TextWindow => {
+ const lines = text.split('\n');
+ const totalLines = lines.length;
+ const totalChars = text.length;
+
+ const maxLines = toInteger(options.maxLines, Number.MAX_SAFE_INTEGER, 1);
+ const maxChars = toInteger(options.maxChars, Number.MAX_SAFE_INTEGER, 1);
+ const startLine = toInteger(options.offset, 1, 1);
+
+ if (startLine > totalLines) {
+ return { content: '', endLine: 0, startLine, totalChars, totalLines, truncated: false };
+ }
+
+ const selected: string[] = [];
+ let charCount = 0;
+ let cutLine: TextWindow['cutLine'];
+
+ for (let index = startLine - 1; index < totalLines && selected.length < maxLines; index++) {
+ const line = lines[index];
+ const separator = selected.length > 0 ? 1 : 0;
+ const nextCount = charCount + separator + line.length;
+
+ if (nextCount <= maxChars) {
+ selected.push(line);
+ charCount = nextCount;
+ continue;
+ }
+
+ // Lines that fit a later window whole are left for it. Lines longer than the whole budget
+ // never fit, so fill the remaining budget with their head instead of wasting it.
+ const remaining = maxChars - charCount - separator;
+ if (line.length > maxChars && remaining > 0) {
+ const kept = sliceHead(line, remaining);
+ selected.push(kept);
+ cutLine = { keptChars: kept.length, line: index + 1, totalChars: line.length };
+ }
+ break;
+ }
+
+ const endLine = startLine + selected.length - 1;
+
+ return {
+ content: selected.join('\n'),
+ cutLine,
+ endLine,
+ startLine,
+ totalChars,
+ totalLines,
+ truncated: endLine < totalLines || cutLine !== undefined,
+ };
+};
+
+/** Default number of lines a paged read tool returns when the model passes no `limit`. */
+export const DEFAULT_READ_WINDOW_LINES = 400;
+
+/** Upper bound on a paged read's `limit`, so a model cannot opt back into whole-file reads. */
+export const MAX_READ_WINDOW_LINES = 2000;
+
+/**
+ * Hard cap on characters a paged read returns per file per call, applied on top of the line
+ * limit. Two files at this cap stay under the 25k tool-result archive threshold.
+ */
+export const MAX_READ_WINDOW_CHARS = 10_000;
+
+export interface ReadWindowOptions {
+ /** Maximum number of lines to return; defaults to {@link DEFAULT_READ_WINDOW_LINES}. */
+ limit?: number | string;
+ /** Maximum characters to return; defaults to {@link MAX_READ_WINDOW_CHARS}. */
+ maxChars?: number;
+ /** 1-based line number to start from; defaults to 1. */
+ offset?: number | string;
+}
+
+/**
+ * The window a paged read tool (`readKnowledge`, `readAttachment`) returns for one call: the
+ * model-supplied `limit` is clamped to {@link MAX_READ_WINDOW_LINES}, and the character budget
+ * defaults to {@link MAX_READ_WINDOW_CHARS}.
+ */
+export const sliceReadWindow = (content: string, options: ReadWindowOptions = {}): TextWindow =>
+ sliceTextWindow(content, {
+ maxChars: options.maxChars ?? MAX_READ_WINDOW_CHARS,
+ maxLines: Math.min(
+ MAX_READ_WINDOW_LINES,
+ toInteger(options.limit, DEFAULT_READ_WINDOW_LINES, 1),
+ ),
+ offset: options.offset,
+ });
+
+const hasStoredCut = (range: TextWindowRange, originalChars?: number) =>
+ originalChars !== undefined && range.totalChars !== undefined && originalChars > range.totalChars;
+
+/**
+ * XML attributes describing a window, shared by every `<file>` style tag the model sees:
+ * ` lines="a-b" total_lines="N" total_chars="C" truncated="…"`, plus `original_chars` when the
+ * stored text is shorter than the original.
+ */
+export const formatTextWindowAttributes = (
+ range: TextWindowRange,
+ { originalChars }: Pick<TextWindowNoticeOptions, 'originalChars'> = {},
+): string => {
+ const attributes = [
+ `lines="${range.startLine}-${range.endLine}"`,
+ `total_lines="${range.totalLines}"`,
+ ];
+ if (range.totalChars !== undefined) attributes.push(`total_chars="${range.totalChars}"`);
+ attributes.push(`truncated="${range.truncated || hasStoredCut(range, originalChars)}"`);
+ if (hasStoredCut(range, originalChars)) attributes.push(`original_chars="${originalChars}"`);
+
+ return ` ${attributes.join(' ')}`;
+};
+
+const withStoredCutNotice = (parts: string[], range: TextWindowRange, originalChars?: number) => {
+ if (hasStoredCut(range, originalChars)) {
+ parts.push(
+ `[The stored text is incomplete: only the first ${range.totalChars} of the original ${originalChars} characters were kept, ending at line ${range.totalLines}. Paging cannot go past that point. If the task needs the rest (for example aggregating a whole table), process the original file in a code sandbox or at its local path when available.]`,
+ );
+ }
+
+ return parts.join('\n');
+};
+
+/**
+ * The model-facing notice for a window. Empty when the window is the complete text.
+ *
+ * Every notice states the range and total size, then the exact call for the next window.
+ */
+export const formatTextWindowNotice = (
+ range: TextWindowRange,
+ { continueFrom, continueMaxChars, originalChars }: TextWindowNoticeOptions = {},
+): string => {
+ const parts: string[] = [];
+ const size =
+ range.totalChars === undefined
+ ? `${range.totalLines} lines`
+ : `${range.totalLines} lines, ${range.totalChars} characters`;
+
+ if (range.endLine === 0) {
+ parts.push(
+ `[Line ${range.startLine} is past the end of this text (${size}); nothing was returned. The text is not empty.]`,
+ );
+ } else if (range.cutLine) {
+ const { keptChars, line, totalChars } = range.cutLine;
+ if (continueFrom && continueMaxChars !== undefined && totalChars <= continueMaxChars) {
+ parts.push(
+ `[Showing lines ${range.startLine}-${line} of ${size}. Line ${line} is ${totalChars} characters long and was cut at ${keptChars}. To read it in full and continue, ${continueFrom(line)}.]`,
+ );
+ return withStoredCutNotice(parts, range, originalChars);
+ }
+ const next =
+ line < range.totalLines
+ ? continueFrom
+ ? ` To continue with the next line, ${continueFrom(line + 1)}.`
+ : ` Lines ${line + 1}-${range.totalLines} were left out.`
+ : '';
+ parts.push(
+ `[Showing lines ${range.startLine}-${line} of ${size}. Line ${line} is ${totalChars} characters long and was cut at ${keptChars}; the rest of that line cannot be paged.${next}]`,
+ );
+ } else if (range.truncated) {
+ const next = continueFrom
+ ? ` To continue, ${continueFrom(range.endLine + 1)}.`
+ : ` Lines ${range.endLine + 1}-${range.totalLines} were left out.`;
+ parts.push(`[Showing lines ${range.startLine}-${range.endLine} of ${size}.${next}]`);
+ }
+
+ return withStoredCutNotice(parts, range, originalChars);
+};
+
+/** `content` followed by its notice on a new line, or `content` alone when nothing was left out. */
+export const appendTextWindowNotice = (
+ window: TextWindow,
+ options: TextWindowNoticeOptions = {},
+): string => {
+ const notice = formatTextWindowNotice(window, options);
+ return notice ? `${window.content}\n${notice}` : window.content;
+};
diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.test.ts b/packages/prompts/src/textWindow/readWindow.test.ts
similarity index 80%
rename from packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.test.ts
rename to packages/prompts/src/textWindow/readWindow.test.ts
index f5cd673d17d..fdb37c652e9 100644
--- a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.test.ts
+++ b/packages/prompts/src/textWindow/readWindow.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'vitest';
import {
- DEFAULT_READ_KNOWLEDGE_LINE_LIMIT,
- MAX_READ_KNOWLEDGE_CHARS_PER_FILE,
- MAX_READ_KNOWLEDGE_LINE_LIMIT,
+ DEFAULT_READ_WINDOW_LINES,
+ MAX_READ_WINDOW_CHARS,
+ MAX_READ_WINDOW_LINES,
sliceReadWindow,
-} from './readWindow';
+} from './index';
const buildLines = (count: number, width = 5) =>
Array.from({ length: count }, (_, i) => `${i + 1}`.padStart(width, 'L')).join('\n');
@@ -19,20 +19,20 @@ describe('sliceReadWindow', () => {
content,
endLine: 3,
startLine: 1,
- totalCharCount: 5,
- totalLineCount: 3,
+ totalChars: 5,
+ totalLines: 3,
truncated: false,
});
});
it('caps at the default line limit and flags truncation', () => {
- const content = buildLines(DEFAULT_READ_KNOWLEDGE_LINE_LIMIT + 10);
+ const content = buildLines(DEFAULT_READ_WINDOW_LINES + 10);
const window = sliceReadWindow(content);
expect(window.startLine).toBe(1);
- expect(window.endLine).toBe(DEFAULT_READ_KNOWLEDGE_LINE_LIMIT);
+ expect(window.endLine).toBe(DEFAULT_READ_WINDOW_LINES);
expect(window.truncated).toBe(true);
- expect(window.content.split('\n')).toHaveLength(DEFAULT_READ_KNOWLEDGE_LINE_LIMIT);
+ expect(window.content.split('\n')).toHaveLength(DEFAULT_READ_WINDOW_LINES);
});
it('pages from a 1-based offset with an explicit limit', () => {
@@ -57,7 +57,7 @@ describe('sliceReadWindow', () => {
expect(window.startLine).toBe(5);
expect(window.endLine).toBe(0);
expect(window.truncated).toBe(false);
- expect(window.totalLineCount).toBe(2);
+ expect(window.totalLines).toBe(2);
});
it('stops before exceeding the per-file character cap', () => {
@@ -65,7 +65,7 @@ describe('sliceReadWindow', () => {
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.content.length).toBeLessThanOrEqual(MAX_READ_WINDOW_CHARS);
expect(window.endLine).toBe(2);
expect(window.truncated).toBe(true);
@@ -78,12 +78,12 @@ describe('sliceReadWindow', () => {
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.content).toBe('a'.repeat(MAX_READ_WINDOW_CHARS));
+ expect(window.content.length).toBe(MAX_READ_WINDOW_CHARS);
expect(window.endLine).toBe(1);
expect(window.truncated).toBe(true);
expect(window.cutLine).toEqual({
- keptChars: MAX_READ_KNOWLEDGE_CHARS_PER_FILE,
+ keptChars: MAX_READ_WINDOW_CHARS,
line: 1,
totalChars: 30_000,
});
@@ -97,7 +97,7 @@ describe('sliceReadWindow', () => {
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.content.length).toBe(MAX_READ_WINDOW_CHARS);
expect(window.truncated).toBe(true);
expect(window.cutLine?.totalChars).toBe(20_000);
});
@@ -117,10 +117,10 @@ describe('sliceReadWindow', () => {
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), {
+ sliceReadWindow(buildLines(MAX_READ_WINDOW_LINES + 5), {
limit: 999_999,
maxChars: Number.MAX_SAFE_INTEGER,
}).endLine,
- ).toBe(MAX_READ_KNOWLEDGE_LINE_LIMIT);
+ ).toBe(MAX_READ_WINDOW_LINES);
});
});
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index f2c6007e42c..87e2922588a 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -164,7 +164,7 @@ export abstract class ComputerRuntime {
};
// Number every returned line (1-based gutter) and, when the window
- // stops before EOF, prefix a `(lines 1-1000 of 2545)` marker. Rendering
+ // stops before EOF, append the shared window notice with the next call. Rendering
// only the caller-supplied args here meant a default-window read looked
// identical to a full read, and the model had to burn extra turns
// discovering the file was truncated.
@@ -188,10 +188,24 @@ export abstract class ComputerRuntime {
// returned line's 1-based number is loc[0] + 1 or startLine.
const firstLineNumber = hasLoc ? r.loc[0] + 1 : (args.startLine ?? 1);
+ // Name the next call in the argument shape this tool takes: local reads
+ // page with a 0-based end-exclusive `loc` of the same span; cloud sandbox
+ // reads with 1-based `startLine`/`endLine`.
+ const span = lineRange ? Math.max(lineRange[1] - lineRange[0], 1) : undefined;
+ const continueFrom = hasLoc
+ ? (line: number) =>
+ `call readFile again with path="${args.path}" and loc=[${line - 1}, ${line - 1 + span!}]`
+ : (line: number) =>
+ args.endLine === undefined
+ ? `call readFile again with path="${args.path}" and startLine=${line}`
+ : `call readFile again with path="${args.path}", startLine=${line} and endLine=${line + span! - 1}`;
+
const content = formatFileContent({
content: fileContent,
+ continueFrom,
firstLineNumber,
lineRange,
+ totalChars: r.totalCharCount,
totalLines: r.totalLineCount ?? r.totalLines,
// When the service cut the content at its char cap, the window's tail
// was never delivered — a "(lines 1-1000 of N)" marker would claim
diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
index d2117df503a..9823011743b 100644
--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
@@ -296,7 +296,9 @@ describe('LocalSystemExecutionRuntime.readFile', () => {
const output = await runtime.readFile({ path: '/tmp/big.txt' });
- expect(output.content).toBe('(lines 1-200 of 2545)\n1 first 200 lines…');
+ expect(output.content).toBe(
+ '1 first 200 lines…\n[Showing lines 1-200 of 2545 lines, 148370 characters. To continue, call readFile again with path="/tmp/big.txt" and loc=[200, 400].]',
+ );
});
it('omits the window marker when the window reaches the end of the file', async () => {
@@ -385,7 +387,9 @@ describe('LocalSystemExecutionRuntime.readFile', () => {
const output = await runtime.readFile({ endLine: 200, path: '/tmp/big.txt', startLine: 1 });
- expect(output.content).toContain('(lines 1-200 of 2545)');
+ expect(output.content).toContain(
+ '[Showing lines 1-200 of 2545 lines, 148370 characters. To continue, call readFile again with path="/tmp/big.txt", startLine=201 and endLine=400.]',
+ );
expect(output.content).toContain('1 some lines');
});
@@ -406,7 +410,9 @@ describe('LocalSystemExecutionRuntime.readFile', () => {
const output = await runtime.readFile({ endLine: 200, path: '/tmp/big.txt' });
- expect(output.content).toContain('(lines 1-200 of 2545)');
+ expect(output.content).toContain(
+ '[Showing lines 1-200 of 2545 lines, 148370 characters. To continue, call readFile again with path="/tmp/big.txt", startLine=201 and endLine=400.]',
+ );
expect(output.content).toContain('1 some lines');
});
diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.ts
index 95a892559d4..1287c3ca6a6 100644
--- a/packages/types/src/files/index.ts
+++ b/packages/types/src/files/index.ts
@@ -69,6 +69,8 @@ export interface FileItem {
enabled?: boolean;
id: string;
name: string;
+ /** Original character count when the parsed `content` was cut at parse time. */
+ originalCharCount?: number;
size: number;
source?: FileSource | null;
type: string;
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 72550c26153..ff903ca4705 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -50,6 +50,12 @@ export interface ChatFileItem {
*/
inaccessible?: boolean;
name: string;
+ /**
+ * Character count of the original parsed text when the stored `content` was cut at parse time
+ * (see `metadata.originalCharCount` on the document). Lets prompts tell the model the text is
+ * incomplete instead of leaving it to guess from the file size.
+ */
+ originalCharCount?: number;
size: number;
url: string;
}
diff --git a/packages/utils/src/isBinaryContent.ts b/packages/utils/src/isBinaryContent.ts
index bae349d0c77..d8fbcde5e8d 100644
--- a/packages/utils/src/isBinaryContent.ts
+++ b/packages/utils/src/isBinaryContent.ts
@@ -16,6 +16,10 @@ const hasUtf8Bom = (buf: Uint8Array): boolean =>
const hasUtf16Bom = (buf: Uint8Array): boolean =>
buf.length >= 2 && ((buf[0] === 0xff && buf[1] === 0xfe) || (buf[0] === 0xfe && buf[1] === 0xff));
+/** Whether sampled bytes are UTF-16 text, with or without a BOM. */
+export const isUtf16Buffer = (buf: Uint8Array): boolean =>
+ hasUtf16Bom(buf) || detectUtf16NoBom(buf) !== null;
+
/**
* Heuristically determine if a buffer looks like binary data.
*
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index f568cbebd0a..d1db3e153c7 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -46,6 +46,7 @@ import { labPreferSelectors, settingsSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
import { useEffectiveModel } from '../../hooks/useEffectiveModel';
+import { useLargeFileLocalPath } from '../../hooks/useLargeFileLocalPath';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import { insertGoalTag } from '../../InputEditor/ActionTag/goalTag';
import { useChatInputStore } from '../../store';
@@ -316,6 +317,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
const isMemoryEnabled = useMemoryEnabled(agentId);
const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);
const editor = useChatInputStore((s) => s.editor);
+ const routeLargeFilesToLocalPaths = useLargeFileLocalPath(agentId, editor);
const { canUploadImage, canUploadVideo, canUploadAudio } = useMediaUploadAbility(
model,
provider,
@@ -482,7 +484,8 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
onFiles={async (files) => {
close();
editor?.focus();
- await upload(files, agentId);
+ const filesToUpload = routeLargeFilesToLocalPaths(files);
+ if (filesToUpload.length > 0) await upload(filesToUpload, agentId);
}}
>
<div className={cx(hotArea)}>{t('upload.action.fileOrImageUpload')}</div>
@@ -748,6 +751,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
skillMarketFooter,
skillMarketHeader,
upload,
+ routeLargeFilesToLocalPaths,
close,
]);
diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsx
index 6e3f85ddddf..7851180ffbf 100644
--- a/src/features/ChatInput/ActionBar/Upload/index.tsx
+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx
@@ -16,6 +16,7 @@ import { preferenceSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import { useEffectiveModel } from '../../hooks/useEffectiveModel';
+import { useLargeFileLocalPath } from '../../hooks/useLargeFileLocalPath';
import { useChatInputStore } from '../../store';
import { type ActionDropdownMenuItems } from '../components/ActionDropdown';
import { ChatInputAction } from '../components/ChatInputAction';
@@ -42,6 +43,7 @@ const FileUpload = memo(() => {
const agentId = useAgentId();
const { model, provider } = useEffectiveModel(agentId);
+ const routeLargeFilesToLocalPaths = useLargeFileLocalPath(agentId, editor);
const { canUploadImage, canUploadVideo, canUploadAudio } = useMediaUploadAbility(
model,
@@ -134,7 +136,8 @@ const FileUpload = memo(() => {
onFiles={async (files) => {
setDropdownOpen(false);
editor?.focus();
- await upload(files, agentId);
+ const filesToUpload = routeLargeFilesToLocalPaths(files);
+ if (filesToUpload.length > 0) await upload(filesToUpload, agentId);
}}
>
<div className={cx(hotArea)}>{t('upload.action.fileUpload')}</div>
@@ -173,7 +176,8 @@ const FileUpload = memo(() => {
onFiles={async (files) => {
setDropdownOpen(false);
editor?.focus();
- await upload(files, agentId);
+ const filesToUpload = routeLargeFilesToLocalPaths(files);
+ if (filesToUpload.length > 0) await upload(filesToUpload, agentId);
}}
>
<div className={cx(hotArea)}>{t('upload.action.folderUpload')}</div>
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagNode.ts b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagNode.ts
index f9377f46922..f4bd564b027 100644
--- a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagNode.ts
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagNode.ts
@@ -1,4 +1,5 @@
import { addClassNamesToElement } from '@lexical/utils';
+import type { LocalFileStats } from '@lobechat/electron-client-ipc';
import { getKernelFromEditor } from '@lobehub/editor';
import type { HeadlessRenderableNode, HeadlessRenderContext } from '@lobehub/editor/renderer';
import {
@@ -19,8 +20,11 @@ import { LocalFile } from '@/features/LocalFile';
export type SerializedLocalFileTagNode = Spread<
{
isDirectory: boolean;
+ lineCount?: number;
+ mimeType?: string;
name: string;
path: string;
+ size?: number;
},
SerializedLexicalNode
>;
@@ -36,13 +40,16 @@ export class LocalFileTagNode extends DecoratorNode<any> implements HeadlessRend
__name: string;
__path: string;
__isDirectory: boolean;
+ __stats: Partial<LocalFileStats>;
static getType(): string {
return 'local-file-tag';
}
static clone(node: LocalFileTagNode): LocalFileTagNode {
- return new LocalFileTagNode(node.__name, node.__path, node.__isDirectory, node.__key);
+ const clone = new LocalFileTagNode(node.__name, node.__path, node.__isDirectory, node.__key);
+ clone.__stats = node.__stats;
+ return clone;
}
static importJSON(serializedNode: SerializedLocalFileTagNode): LocalFileTagNode {
@@ -50,6 +57,11 @@ export class LocalFileTagNode extends DecoratorNode<any> implements HeadlessRend
serializedNode.name,
serializedNode.path,
serializedNode.isDirectory,
+ {
+ lineCount: serializedNode.lineCount,
+ mimeType: serializedNode.mimeType,
+ size: serializedNode.size,
+ },
).updateFromJSON(serializedNode);
}
@@ -62,6 +74,7 @@ export class LocalFileTagNode extends DecoratorNode<any> implements HeadlessRend
this.__name = name;
this.__path = path;
this.__isDirectory = isDirectory;
+ this.__stats = {};
}
get name(): string {
@@ -76,6 +89,17 @@ export class LocalFileTagNode extends DecoratorNode<any> implements HeadlessRend
return this.__isDirectory;
}
+ /** Size, line count, and MIME type, filled in asynchronously after insertion when available. */
+ get stats(): Partial<LocalFileStats> {
+ return this.__stats;
+ }
+
+ setStats(stats: Partial<LocalFileStats>): this {
+ const writable = this.getWritable();
+ writable.__stats = stats;
+ return writable;
+ }
+
exportDOM(): DOMExportOutput {
return { element: document.createElement('span') };
}
@@ -102,8 +126,11 @@ export class LocalFileTagNode extends DecoratorNode<any> implements HeadlessRend
return {
...super.exportJSON(),
isDirectory: this.__isDirectory,
+ lineCount: this.__stats.lineCount,
+ mimeType: this.__stats.mimeType,
name: this.__name,
path: this.__path,
+ size: this.__stats.size,
};
}
@@ -135,8 +162,11 @@ export function $createLocalFileTagNode(
name: string,
path: string,
isDirectory = false,
+ stats: Partial<LocalFileStats> = {},
): LocalFileTagNode {
- return $applyNodeReplacement(new LocalFileTagNode(name, path, isDirectory));
+ const node = new LocalFileTagNode(name, path, isDirectory);
+ node.__stats = stats;
+ return $applyNodeReplacement(node);
}
export function $isLocalFileTagNode(
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.test.ts b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.test.ts
new file mode 100644
index 00000000000..00d97273e15
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.test.ts
@@ -0,0 +1,77 @@
+import type { IEditor } from '@lobehub/editor';
+import { CommonPlugin, Kernel, LitexmlPlugin, MarkdownPlugin, moment } from '@lobehub/editor';
+import { describe, expect, it, vi } from 'vitest';
+
+import { INSERT_LOCAL_FILE_TAG_COMMAND, LocalFileTagPlugin } from './LocalFileTagPlugin';
+
+vi.mock('@/features/LocalFile', () => ({ LocalFile: () => null }));
+
+const createEditor = (resolveFileStats?: (path: string) => Promise<any>) => {
+ const editor = new Kernel() as unknown as IEditor;
+ editor.registerPlugins([CommonPlugin, MarkdownPlugin, LitexmlPlugin]);
+ editor.registerPlugin(LocalFileTagPlugin, { decorator: () => null, resolveFileStats });
+ editor.initNodeEditor();
+ return editor;
+};
+
+const insertTag = async (editor: IEditor, payload: { isDirectory?: boolean; path: string }) => {
+ editor.dispatchCommand(INSERT_LOCAL_FILE_TAG_COMMAND, { name: 'sales.csv', ...payload });
+ await moment();
+};
+
+describe('LocalFileTagPlugin', () => {
+ it('writes file stats into the serialized reference', async () => {
+ const resolveFileStats = vi
+ .fn()
+ .mockResolvedValue({ lineCount: 812_345, mimeType: 'text/csv', size: 52_428_800 });
+ const editor = createEditor(resolveFileStats);
+
+ await insertTag(editor, { path: '/Users/me/sales.csv' });
+
+ expect(resolveFileStats).toHaveBeenCalledWith('/Users/me/sales.csv');
+ await vi.waitFor(() =>
+ expect(editor.getDocument('markdown')).toContain(
+ '<localFile name="sales.csv" path="/Users/me/sales.csv" size="52428800" lines="812345" type="text/csv" />',
+ ),
+ );
+ });
+
+ it('keeps the plain reference when stats cannot be resolved', async () => {
+ const editor = createEditor(vi.fn().mockRejectedValue(new Error('ENOENT')));
+
+ await insertTag(editor, { path: '/remote/sales.csv' });
+
+ expect(editor.getDocument('markdown')).toContain(
+ '<localFile name="sales.csv" path="/remote/sales.csv" />',
+ );
+ });
+
+ it('does not look up stats for directories', async () => {
+ const resolveFileStats = vi.fn();
+ const editor = createEditor(resolveFileStats);
+
+ await insertTag(editor, { isDirectory: true, path: '/Users/me/data' });
+
+ expect(resolveFileStats).not.toHaveBeenCalled();
+ });
+
+ it('limits concurrent stats lookups', async () => {
+ let running = 0;
+ let peak = 0;
+ const resolveFileStats = vi.fn(async () => {
+ running += 1;
+ peak = Math.max(peak, running);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ running -= 1;
+ return { size: 1 };
+ });
+ const editor = createEditor(resolveFileStats);
+
+ for (let index = 0; index < 6; index++) {
+ await insertTag(editor, { path: `/Users/me/file-${index}.csv` });
+ }
+
+ await vi.waitFor(() => expect(resolveFileStats).toHaveBeenCalledTimes(6));
+ expect(peak).toBeLessThanOrEqual(2);
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.ts b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.ts
index f1e5828aeb3..26705a39f34 100644
--- a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.ts
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.ts
@@ -1,4 +1,5 @@
import { $wrapNodeInElement } from '@lexical/utils';
+import type { LocalFileStats } from '@lobechat/electron-client-ipc';
import { escapeXmlAttr } from '@lobechat/prompts';
import {
type getKernelFromEditor,
@@ -8,6 +9,7 @@ import {
import {
$createParagraphNode,
$createTextNode,
+ $getNodeByKey,
$insertNodes,
$isRootOrShadowRoot,
COMMAND_PRIORITY_HIGH,
@@ -36,9 +38,36 @@ type IEditorKernel = ReturnType<typeof getKernelFromEditor>;
export interface LocalFileTagPluginOptions {
decorator: (node: LocalFileTagNode, editor: LexicalEditor) => any;
+ /**
+ * Looks up size, line count, and MIME type for an inserted file reference. The result is
+ * written into the tag so the model can plan how to read the file before opening it.
+ */
+ resolveFileStats?: (path: string) => Promise<LocalFileStats>;
theme?: { localFileTag?: string };
}
+/**
+ * Serialized `<localFile>` attributes carrying file stats. `size` is in bytes; `lines` is omitted
+ * for binary files.
+ */
+const localFileStatsAttributes = (stats: Partial<LocalFileStats>): Record<string, string> => ({
+ ...(stats.size === undefined ? {} : { size: String(stats.size) }),
+ ...(stats.lineCount === undefined ? {} : { lines: String(stats.lineCount) }),
+ ...(stats.mimeType ? { type: stats.mimeType } : {}),
+});
+
+/**
+ * Stats lookups stream the whole file on the desktop main process to count lines, so dropping a
+ * folder with hundreds of files must not start hundreds of full-file reads at once.
+ */
+const FILE_STATS_CONCURRENCY = 2;
+
+const readNumberAttribute = (value: string | null | undefined) => {
+ if (!value) return undefined;
+ const number = Number(value);
+ return Number.isFinite(number) ? number : undefined;
+};
+
/**
* Owns the `local-file-tag` node: its decorator, its `<localFile … />`
* markdown writer, and its insert command. Because this plugin is registered
@@ -53,6 +82,8 @@ export class LocalFileTagPlugin {
config?: LocalFileTagPluginOptions;
private kernel: IEditorKernel;
+ private pendingFileStats: (() => Promise<void>)[] = [];
+ private runningFileStats = 0;
constructor(kernel: IEditorKernel, config?: LocalFileTagPluginOptions) {
this.kernel = kernel;
@@ -83,7 +114,10 @@ export class LocalFileTagPlugin {
const name = escapeXmlAttr(node.name);
const path = escapeXmlAttr(node.path);
const isDirectory = node.isDirectory ? ' isDirectory' : '';
- ctx.appendLine(`<localFile name="${name}" path="${path}"${isDirectory} />`);
+ const stats = Object.entries(localFileStatsAttributes(node.stats))
+ .map(([key, value]) => ` ${key}="${escapeXmlAttr(value)}"`)
+ .join('');
+ ctx.appendLine(`<localFile name="${name}" path="${path}"${stats}${isDirectory} />`);
}
});
}
@@ -99,6 +133,8 @@ export class LocalFileTagPlugin {
if ($isRootOrShadowRoot(node.getParentOrThrow())) {
$wrapNodeInElement(node, $createParagraphNode).selectEnd();
}
+ // Commands can run inside a deferred update, so start the lookup once the key exists.
+ if (!payload.isDirectory) this.fillFileStats(editor, node.getKey(), payload.path);
});
return true;
},
@@ -106,6 +142,38 @@ export class LocalFileTagPlugin {
);
}
+ /**
+ * Stats are filled in after insertion so the tag appears immediately; a message sent before the
+ * lookup finishes (or on a path this machine cannot read) keeps the plain name/path reference.
+ */
+ private fillFileStats(editor: LexicalEditor, nodeKey: string, path: string): void {
+ const resolveFileStats = this.config?.resolveFileStats;
+ if (!resolveFileStats || !path) return;
+
+ this.pendingFileStats.push(() =>
+ resolveFileStats(path)
+ .then((stats) => {
+ editor.update(() => {
+ const node = $getNodeByKey(nodeKey);
+ if ($isLocalFileTagNode(node)) node.setStats(stats);
+ });
+ })
+ .catch(() => {}),
+ );
+ this.drainFileStats();
+ }
+
+ private drainFileStats(): void {
+ while (this.runningFileStats < FILE_STATS_CONCURRENCY && this.pendingFileStats.length > 0) {
+ const task = this.pendingFileStats.shift()!;
+ this.runningFileStats += 1;
+ void task().finally(() => {
+ this.runningFileStats -= 1;
+ this.drainFileStats();
+ });
+ }
+ }
+
private registerLiteXml(): void {
const xmlService = this.kernel.requireService(ILitexmlService);
@@ -115,6 +183,7 @@ export class LocalFileTagPlugin {
...(node.isDirectory ? { isDirectory: 'true' } : {}),
name: node.name,
path: node.path,
+ ...localFileStatsAttributes(node.stats),
});
}
return false;
@@ -125,8 +194,11 @@ export class LocalFileTagPlugin {
isDirectory:
xmlElement.hasAttribute?.('isDirectory') ||
xmlElement.getAttribute('isDirectory') === 'true',
+ lineCount: readNumberAttribute(xmlElement.getAttribute('lines')),
+ mimeType: xmlElement.getAttribute('type') || undefined,
name: xmlElement.getAttribute('name') || '',
path: xmlElement.getAttribute('path') || '',
+ size: readNumberAttribute(xmlElement.getAttribute('size')),
type: LocalFileTagNode.getType(),
version: 1,
} satisfies SerializedLocalFileTagNode;
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/ReactLocalFileTagPlugin.tsx b/src/features/ChatInput/InputEditor/LocalFileTag/ReactLocalFileTagPlugin.tsx
index 0053ed4f950..ac8b8bd762b 100644
--- a/src/features/ChatInput/InputEditor/LocalFileTag/ReactLocalFileTagPlugin.tsx
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/ReactLocalFileTagPlugin.tsx
@@ -1,6 +1,9 @@
+import { isDesktop } from '@lobechat/const';
import { useLexicalComposerContext } from '@lobehub/editor';
import { type FC, useLayoutEffect } from 'react';
+import { localFileService } from '@/services/electron/localFileService';
+
import { LocalFileTag } from './LocalFileTag';
import { LocalFileTagPlugin } from './LocalFileTagPlugin';
@@ -22,6 +25,10 @@ const ReactLocalFileTagPlugin: FC = () => {
/>
);
},
+ // Only the desktop app can stat a path on this machine; elsewhere tags keep name/path only.
+ resolveFileStats: isDesktop
+ ? (path) => localFileService.getLocalFileStats({ path })
+ : undefined,
});
}, [editor]);
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
index 891c2dd01e7..a6dc45ddda2 100644
--- a/src/features/ChatInput/InputEditor/index.test.tsx
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -200,6 +200,9 @@ vi.mock('@/store/user/selectors', () => ({
}));
vi.mock('../hooks/useAgentId', () => ({ useAgentId: () => 'agent-id' }));
+vi.mock('../hooks/useLargeFileLocalPath', () => ({
+ useLargeFileLocalPath: () => (files: File[]) => files,
+}));
vi.mock('../store', () => {
const editor = {
dispatchCommand: vi.fn(),
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index 6bee3719fa0..ac02f4666f5 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -42,6 +42,7 @@ import { useChatInputDraft } from '../hooks/useChatInputDraft';
import { useChatInputHistory } from '../hooks/useChatInputHistory';
import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
import { useEffectiveModel } from '../hooks/useEffectiveModel';
+import { useLargeFileLocalPath } from '../hooks/useLargeFileLocalPath';
import { useChatInputStore, useStoreApi } from '../store';
import {
INSERT_ACTION_TAG_COMMAND,
@@ -232,9 +233,14 @@ const InputEditor = memo<{
!heterogeneousName &&
categories.some((category) => category.id === 'agent');
const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
+ const routeLargeFilesToLocalPaths = useLargeFileLocalPath(agentId, editor);
+ const handlePasteFiles = useCallback(
+ (files: File[]) => handleUploadFiles(routeLargeFilesToLocalPaths(files)),
+ [handleUploadFiles, routeLargeFilesToLocalPaths],
+ );
// Listen to editor's paste event for file uploads
- usePasteFile(editor, handleUploadFiles);
+ usePasteFile(editor, handlePasteFiles);
useEffect(() => {
const fn = (e: BeforeUnloadEvent) => {
diff --git a/src/features/ChatInput/hooks/useLargeFileLocalPath.test.ts b/src/features/ChatInput/hooks/useLargeFileLocalPath.test.ts
new file mode 100644
index 00000000000..f606a5d6f61
--- /dev/null
+++ b/src/features/ChatInput/hooks/useLargeFileLocalPath.test.ts
@@ -0,0 +1,84 @@
+import type { IEditor } from '@lobehub/editor';
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ LOCAL_PATH_REFERENCE_MIN_FILE_SIZE,
+ partitionLargeFilesAsLocalPaths,
+ useLargeFileLocalPath,
+} from './useLargeFileLocalPath';
+
+const { insertLocalPathTagsMock, toastInfoMock } = vi.hoisted(() => ({
+ insertLocalPathTagsMock: vi.fn(),
+ toastInfoMock: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({ toast: { info: toastInfoMock } }));
+vi.mock('@/features/ChatInput/InputEditor/insertLocalFileTags', () => ({
+ insertLocalPathTags: insertLocalPathTagsMock,
+}));
+vi.mock('@/features/Conversation/useLocalPathReference', () => ({
+ useLocalPathReference: () => ({ enableLocalPathReference: true }),
+}));
+vi.mock('@/utils/electron/localFilePath', () => ({
+ getElectronLocalFilePath: (file: File) => `/Users/me/${file.name}`,
+}));
+vi.mock('./useTopicId', () => ({ useTopicId: () => 'topic-1' }));
+
+const createFile = (name: string, type: string, size: number) => {
+ const file = new File(['x'], name, { type });
+ Object.defineProperty(file, 'size', { value: size });
+ return file;
+};
+
+const resolvePath = (file: File) => `/Users/me/${file.name}`;
+
+describe('partitionLargeFilesAsLocalPaths', () => {
+ it('references large non-media files by local path', () => {
+ const large = createFile('data.csv', 'text/csv', LOCAL_PATH_REFERENCE_MIN_FILE_SIZE + 1);
+
+ expect(partitionLargeFilesAsLocalPaths([large], resolvePath)).toEqual({
+ files: [],
+ localPaths: [{ isDirectory: false, name: 'data.csv', path: '/Users/me/data.csv' }],
+ });
+ });
+
+ it('keeps uploading small files and media of any size', () => {
+ const small = createFile('notes.txt', 'text/plain', LOCAL_PATH_REFERENCE_MIN_FILE_SIZE);
+ const image = createFile('photo.png', 'image/png', LOCAL_PATH_REFERENCE_MIN_FILE_SIZE * 10);
+ const video = createFile('clip.mp4', 'video/mp4', LOCAL_PATH_REFERENCE_MIN_FILE_SIZE * 10);
+
+ expect(partitionLargeFilesAsLocalPaths([small, image, video], resolvePath)).toEqual({
+ files: [small, image, video],
+ localPaths: [],
+ });
+ });
+
+ it('falls back to upload when no local path resolves', () => {
+ const pasted = createFile('export.json', '', LOCAL_PATH_REFERENCE_MIN_FILE_SIZE * 2);
+
+ expect(partitionLargeFilesAsLocalPaths([pasted], () => null)).toEqual({
+ files: [pasted],
+ localPaths: [],
+ });
+ });
+});
+
+describe('useLargeFileLocalPath', () => {
+ it('inserts path tags and tells the user once per burst of picked files', () => {
+ const editor = {} as IEditor;
+ const { result } = renderHook(() => useLargeFileLocalPath('agent-1', editor));
+ const large = (name: string) =>
+ createFile(name, 'text/csv', LOCAL_PATH_REFERENCE_MIN_FILE_SIZE + 1);
+ const small = createFile('notes.txt', 'text/plain', 10);
+
+ expect(result.current([large('a.csv'), small])).toEqual([small]);
+ expect(result.current([large('b.csv')])).toEqual([]);
+
+ expect(insertLocalPathTagsMock).toHaveBeenCalledTimes(2);
+ expect(insertLocalPathTagsMock).toHaveBeenLastCalledWith(editor, [
+ { isDirectory: false, name: 'b.csv', path: '/Users/me/b.csv' },
+ ]);
+ expect(toastInfoMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/ChatInput/hooks/useLargeFileLocalPath.ts b/src/features/ChatInput/hooks/useLargeFileLocalPath.ts
new file mode 100644
index 00000000000..2457e6842d9
--- /dev/null
+++ b/src/features/ChatInput/hooks/useLargeFileLocalPath.ts
@@ -0,0 +1,94 @@
+'use client';
+
+import type { IEditor } from '@lobehub/editor';
+import { toast } from '@lobehub/ui/base-ui';
+import { useCallback, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { DroppedLocalPath } from '@/components/DragUploadZone';
+import { insertLocalPathTags } from '@/features/ChatInput/InputEditor/insertLocalFileTags';
+import { useLocalPathReference } from '@/features/Conversation/useLocalPathReference';
+import { getElectronLocalFilePath } from '@/utils/electron/localFilePath';
+
+import { useTopicId } from './useTopicId';
+
+/**
+ * Non-media files above this size are referenced by local path instead of uploaded when the run
+ * can read this machine's filesystem.
+ *
+ * Uploading parses the whole file into text that is inlined into the prompt; large spreadsheets,
+ * CSV exports, and logs overflow the context window that way. Local tools can page, grep, or
+ * script over the original file instead.
+ */
+export const LOCAL_PATH_REFERENCE_MIN_FILE_SIZE = 1024 * 1024;
+
+/** Folder picks call the router once per file; show the notice at most once per burst. */
+const NOTICE_THROTTLE_MS = 3000;
+
+const isMediaFile = (file: File) =>
+ file.type.startsWith('image') || file.type.startsWith('video') || file.type.startsWith('audio');
+
+export interface PartitionedLargeLocalFiles {
+ files: File[];
+ localPaths: DroppedLocalPath[];
+}
+
+/**
+ * Split picked or pasted files into large non-media files that resolve to a local path and files
+ * that should still be uploaded. Media keeps uploading so vision/audio models receive it directly.
+ */
+export const partitionLargeFilesAsLocalPaths = (
+ files: File[],
+ resolvePath: (file: File) => string | null = getElectronLocalFilePath,
+): PartitionedLargeLocalFiles => {
+ const result: PartitionedLargeLocalFiles = { files: [], localPaths: [] };
+
+ for (const file of files) {
+ const path =
+ !isMediaFile(file) && file.size > LOCAL_PATH_REFERENCE_MIN_FILE_SIZE
+ ? resolvePath(file)
+ : null;
+ if (path) {
+ result.localPaths.push({ isDirectory: false, name: file.name, path });
+ } else {
+ result.files.push(file);
+ }
+ }
+
+ return result;
+};
+
+/**
+ * Routes large picked/pasted files (including files inside a picked folder) to `<localFile>`
+ * references in the given editor on desktop and returns the files that still need uploading.
+ * Outside desktop local execution it returns the input unchanged.
+ *
+ * Only large non-media files are rerouted here, while drag-and-drop
+ * (`partitionDroppedItemsAsLocalPaths` in `useLocalDragUpload`) intentionally references every
+ * dropped file and folder: dragging from the file manager expresses "work on this local file",
+ * whereas the picker and paste are the upload entry points and keep uploading anything that fits.
+ */
+export const useLargeFileLocalPath = (agentId: string, editor: IEditor | undefined) => {
+ const { t } = useTranslation('chat');
+ const topicId = useTopicId();
+ const { enableLocalPathReference } = useLocalPathReference(agentId, topicId);
+ const lastNoticeAt = useRef(0);
+
+ return useCallback(
+ (files: File[]): File[] => {
+ if (!enableLocalPathReference || !editor) return files;
+
+ const partitioned = partitionLargeFilesAsLocalPaths(files);
+ if (partitioned.localPaths.length > 0) {
+ insertLocalPathTags(editor, partitioned.localPaths);
+ // Tell the user why the file shows up as a path chip instead of an upload card.
+ if (Date.now() - lastNoticeAt.current > NOTICE_THROTTLE_MS) {
+ lastNoticeAt.current = Date.now();
+ toast.info(t('upload.localPathReference'));
+ }
+ }
+ return partitioned.files;
+ },
+ [editor, enableLocalPathReference, t],
+ );
+};
diff --git a/src/features/Conversation/useLocalPathReference.test.ts b/src/features/Conversation/useLocalPathReference.test.ts
new file mode 100644
index 00000000000..23428a61955
--- /dev/null
+++ b/src/features/Conversation/useLocalPathReference.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import { canReadLocalFileReferences } from './useLocalPathReference';
+
+const base = {
+ isHeterogeneous: false,
+ isLocalSystemEnabled: true,
+ pinnedPluginIds: [] as string[],
+ toolMode: 'agent' as const,
+};
+
+describe('canReadLocalFileReferences', () => {
+ it('allows local references in agent mode with local system enabled', () => {
+ expect(canReadLocalFileReferences(base)).toBe(true);
+ });
+
+ it('keeps uploading in chat mode, which never offers lobe-local-system', () => {
+ expect(canReadLocalFileReferences({ ...base, toolMode: 'chat' })).toBe(false);
+ });
+
+ it('allows custom mode only when lobe-local-system is pinned', () => {
+ expect(canReadLocalFileReferences({ ...base, toolMode: 'custom' })).toBe(false);
+ expect(
+ canReadLocalFileReferences({
+ ...base,
+ pinnedPluginIds: ['lobe-local-system'],
+ toolMode: 'custom',
+ }),
+ ).toBe(true);
+ });
+
+ it('requires local system for builtin agents but not for heterogeneous agents', () => {
+ expect(canReadLocalFileReferences({ ...base, isLocalSystemEnabled: false })).toBe(false);
+ expect(
+ canReadLocalFileReferences({
+ ...base,
+ isHeterogeneous: true,
+ isLocalSystemEnabled: false,
+ toolMode: 'chat',
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/src/features/Conversation/useLocalPathReference.ts b/src/features/Conversation/useLocalPathReference.ts
index f43bd1ba844..4324f10f595 100644
--- a/src/features/Conversation/useLocalPathReference.ts
+++ b/src/features/Conversation/useLocalPathReference.ts
@@ -1,3 +1,4 @@
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
import { isDesktop } from '@lobechat/const';
import { useCallback } from 'react';
@@ -14,6 +15,29 @@ import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selec
import { useChatStore } from '@/store/chat';
import { useElectronStore } from '@/store/electron';
+/**
+ * Whether a run of this agent is offered a tool that reads local files. Heterogeneous agents bring
+ * their own. Otherwise `lobe-local-system` must survive the tool mode: chat mode never includes it
+ * and custom mode only when pinned, so a `<localFile>` tag there would replace an upload with a
+ * path the model cannot open.
+ */
+export const canReadLocalFileReferences = ({
+ isHeterogeneous,
+ isLocalSystemEnabled,
+ pinnedPluginIds,
+ toolMode,
+}: {
+ isHeterogeneous: boolean;
+ isLocalSystemEnabled: boolean;
+ pinnedPluginIds: string[];
+ toolMode: 'agent' | 'chat' | 'custom';
+}) => {
+ if (isHeterogeneous) return true;
+ if (!isLocalSystemEnabled) return false;
+ if (toolMode === 'agent') return true;
+ return toolMode === 'custom' && pinnedPluginIds.includes(LocalSystemIdentifier);
+};
+
/**
* Whether a drag-dropped local path should become a `<localFile>` reference for
* this agent's next run, plus the insert handler for the drop zone.
@@ -30,6 +54,8 @@ export const useLocalPathReference = (agentId: string, topicId?: string | null)
const isLocalSystemEnabled = useAgentStore(
chatConfigByIdSelectors.isLocalSystemEnabledById(agentId),
);
+ const toolMode = useAgentStore(chatConfigByIdSelectors.getToolModeById(agentId));
+ const pinnedPluginIds = useAgentStore(agentByIdSelectors.getAgentPluginsById(agentId));
const workingDirectory = useEffectiveWorkingDirectory(agentId, { topicId });
const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
@@ -41,7 +67,12 @@ export const useLocalPathReference = (agentId: string, topicId?: string | null)
const enableLocalPathReference =
isDesktop &&
!!workingDirectory &&
- (isHeterogeneous || isLocalSystemEnabled) &&
+ canReadLocalFileReferences({
+ isHeterogeneous,
+ isLocalSystemEnabled,
+ pinnedPluginIds,
+ toolMode,
+ }) &&
canExecutionTargetReadLocalPaths(executionTarget, agencyConfig, currentDeviceId);
const handleLocalPaths = useCallback((paths: DroppedLocalPath[]) => {
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 558a02f6baa..40ebdf62e9f 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -192,7 +192,12 @@ export const contextEngineering = async ({
const fileContents = agentFiles
.filter((file) => file.enabled && file.content)
- .map((file) => ({ content: file.content!, fileId: file.id, filename: file.name }));
+ .map((file) => ({
+ content: file.content!,
+ fileId: file.id,
+ filename: file.name,
+ originalChars: file.originalCharCount,
+ }));
const knowledgeBases = agentKnowledgeBases
.filter((kb) => kb.enabled)
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 86a797e38e1..7f1445e63d5 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -23,6 +23,8 @@ import {
type ListProjectSkillsResult,
type LocalFileItem,
type LocalFilePreviewUrlParams,
+ type LocalFileStats,
+ type LocalFileStatsParams,
type LocalMoveFilesResultItem,
type LocalReadFileParams,
type LocalReadFileResult,
@@ -207,6 +209,10 @@ class LocalFileService {
return ensureElectronIpc().localSystem.hashLocalFile(params);
}
+ async getLocalFileStats(params: LocalFileStatsParams): Promise<LocalFileStats> {
+ return ensureElectronIpc().localSystem.getLocalFileStats(params);
+ }
+
async readLocalFiles(params: LocalReadFilesParams): Promise<LocalReadFileResult[]> {
return ensureElectronIpc().localSystem.readFiles(params);
}
diff --git a/src/services/toolResultArchive.test.ts b/src/services/toolResultArchive.test.ts
new file mode 100644
index 00000000000..a25f9181809
--- /dev/null
+++ b/src/services/toolResultArchive.test.ts
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { archiveToolResultViaServer } from './toolResultArchive';
+
+const { mutate, getChatConfigById } = vi.hoisted(() => ({
+ getChatConfigById: vi.fn(),
+ mutate: vi.fn(),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { aiChat: { archiveToolResult: { mutate } } },
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ chatConfigByIdSelectors: { getChatConfigById },
+}));
+
+vi.mock('@/store/agent/store', () => ({ getAgentStoreState: () => ({}) }));
+
+describe('archiveToolResultViaServer', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mutate.mockResolvedValue({ content: 'archived' });
+ });
+
+ it("sends the agent's configured tool-result limit", async () => {
+ getChatConfigById.mockReturnValue(() => ({ toolResultMaxLength: 80_000 }));
+
+ await archiveToolResultViaServer({
+ agentId: 'agent-1',
+ content: 'result',
+ toolCallId: 'call-1',
+ topicId: 'topic-1',
+ });
+
+ expect(getChatConfigById).toHaveBeenCalledWith('agent-1');
+ expect(mutate).toHaveBeenCalledWith(expect.objectContaining({ limit: 80_000 }));
+ });
+
+ it('prefers an explicit limit over the agent config', async () => {
+ getChatConfigById.mockReturnValue(() => ({ toolResultMaxLength: 80_000 }));
+
+ await archiveToolResultViaServer({
+ agentId: 'agent-1',
+ content: 'result',
+ limit: 1000,
+ toolCallId: 'call-1',
+ topicId: 'topic-1',
+ });
+
+ expect(mutate).toHaveBeenCalledWith(expect.objectContaining({ limit: 1000 }));
+ });
+
+ it('applies the agent limit when truncating locally', async () => {
+ getChatConfigById.mockReturnValue(() => ({ toolResultMaxLength: 1000 }));
+
+ const result = await archiveToolResultViaServer({
+ agentId: 'agent-1',
+ content: 'x\n'.repeat(5000),
+ });
+
+ expect(mutate).not.toHaveBeenCalled();
+ expect(result.length).toBeLessThan(2000);
+ });
+});
diff --git a/src/services/toolResultArchive.ts b/src/services/toolResultArchive.ts
index dc42eef2bc3..f75b97e1733 100644
--- a/src/services/toolResultArchive.ts
+++ b/src/services/toolResultArchive.ts
@@ -1,5 +1,16 @@
import { lambdaClient } from '@/libs/trpc/client';
import { ARCHIVE_BYPASS_IDENTIFIERS, truncateToolResult } from '@/server/utils/truncateToolResult';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { getAgentStoreState } from '@/store/agent/store';
+
+/**
+ * The agent's configured tool-result limit. The server runtime reads it from the agent config;
+ * without this the client path always fell back to the 25k default.
+ */
+const resolveAgentResultLimit = (agentId?: string | null) =>
+ agentId
+ ? chatConfigByIdSelectors.getChatConfigById(agentId)(getAgentStoreState()).toolResultMaxLength
+ : undefined;
interface ArchiveParams {
agentId?: string | null;
@@ -22,8 +33,10 @@ export const archiveToolResultViaServer = async ({
return content;
}
+ const effectiveLimit = limit ?? resolveAgentResultLimit(agentId);
+
if (!content || !toolCallId || !topicId) {
- return truncateToolResult(content, limit);
+ return truncateToolResult(content, effectiveLimit);
}
try {
@@ -31,12 +44,12 @@ export const archiveToolResultViaServer = async ({
agentId,
content,
identifier,
- limit,
+ limit: effectiveLimit,
toolCallId,
topicId,
});
return outcome.content;
} catch {
- return truncateToolResult(content, limit);
+ return truncateToolResult(content, effectiveLimit);
}
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/localSystemToolSnapshots.ts b/src/store/chat/slices/agentRun/actions/transports/client/localSystemToolSnapshots.ts
index fd7d42f4f5f..b037ed73cf8 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/localSystemToolSnapshots.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/localSystemToolSnapshots.ts
@@ -34,10 +34,14 @@ const createReadSnapshot = async (
try {
const result = await localFileService.readLocalFile(args);
+ const span = Math.max(result.loc[1] - result.loc[0], 1);
const content = formatFileContent({
content: result.content,
+ continueFrom: (line) =>
+ `call readFile with path="${reference.path}" and loc=[${line - 1}, ${line - 1 + span}]`,
firstLineNumber: result.loc[0] + 1,
lineRange: result.loc,
+ totalChars: result.totalCharCount,
totalLines: result.totalLineCount,
truncated: result.truncated,
});
diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.ts
index e5eafae5d44..5d3fb580224 100644
--- a/src/store/tool/slices/builtin/executors/catalog.ts
+++ b/src/store/tool/slices/builtin/executors/catalog.ts
@@ -33,6 +33,7 @@ import {
} from './heteroCli';
import { activatorExecutor } from './lobe-activator';
import { agentDocumentsExecutor } from './lobe-agent-documents';
+import { attachmentsExecutor } from './lobe-attachments';
import { messageExecutor } from './lobe-message';
import { notebookExecutor } from './lobe-notebook';
import { pageAgentExecutor } from './lobe-page-agent';
@@ -63,6 +64,7 @@ export const builtinToolExecutors = [
agentBuilderExecutor,
agentDocumentsExecutor,
agentManagementExecutor,
+ attachmentsExecutor,
auvExecutor,
calculatorExecutor,
cloudSandboxExecutor,
diff --git a/src/store/tool/slices/builtin/executors/lobe-attachments.ts b/src/store/tool/slices/builtin/executors/lobe-attachments.ts
new file mode 100644
index 00000000000..2e83574c471
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/lobe-attachments.ts
@@ -0,0 +1,10 @@
+import { AttachmentsExecutionRuntime } from '@lobechat/builtin-tool-attachments/executionRuntime';
+import { AttachmentsExecutor } from '@lobechat/builtin-tool-attachments/executor';
+
+import { ragService } from '@/services/rag';
+
+export const attachmentsExecutor = new AttachmentsExecutor(
+ new AttachmentsExecutionRuntime({
+ getFileContents: (fileIds, signal) => ragService.getFileContents(fileIds, signal),
+ }),
+);
diff --git a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts b/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts
index 59cc8608ec5..8bf6c09a540 100644
--- a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts
@@ -25,7 +25,7 @@ const searchRuntime = new WebBrowsingExecutionRuntime({ searchService });
const createDocumentService = (ctx: BuiltinToolContext): WebBrowsingDocumentService => ({
associateDocument: async (documentId) => {
if (!ctx.agentId) return;
- await agentDocumentService.associateDocument({ agentId: ctx.agentId, documentId });
+ return agentDocumentService.associateDocument({ agentId: ctx.agentId, documentId });
},
createDocument: async ({ content, description, title, url }) =>
webBrowsingService.upsertCrawledDocument({