🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(tool): archive oversized tool results to VFS instead of truncating (#15074)
Inneic056760414f8
diff --git a/src/features/ChatInput/RuntimeConfig/ApprovalMode.tsx b/src/features/ChatInput/RuntimeConfig/ApprovalMode.tsxindex fb70a01b8ec..78e092710d5 100644--- a/src/features/ChatInput/RuntimeConfig/ApprovalMode.tsx+++ b/src/features/ChatInput/RuntimeConfig/ApprovalMode.tsx@@ -31,6 +31,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({line-height: 1.4;color: ${cssVar.colorText};`,+ trigger: css`+ overflow: hidden;+ border-radius: ${cssVar.borderRadius};+ `,}));const ModeItemLabel = memo<{ desc: string; icon: LucideIcon; title: string }>(@@ -128,10 +132,10 @@ const ModeSelector = memo(() => {<DropdownMenuitems={menuItems}open={dropdownOpen}- placement="bottomLeft"+ placement="bottomRight"onOpenChange={setDropdownOpen}>- <div>+ <div className={styles.trigger}>{dropdownOpen ? (button) : (diff --git a/src/features/Conversation/Markdown/plugins/LobeThinking/Render.tsx b/src/features/Conversation/Markdown/plugins/LobeThinking/Render.tsxindex 78e1627db56..0383f95c985 100644--- a/src/features/Conversation/Markdown/plugins/LobeThinking/Render.tsx+++ b/src/features/Conversation/Markdown/plugins/LobeThinking/Render.tsx@@ -5,14 +5,17 @@ import Thinking from '@/features/Conversation/components/Thinking';import { useUserStore } from '@/store/user';import { userGeneralSettingsSelectors } from '@/store/user/selectors';-import { dataSelectors, useConversationStore } from '../../../store';+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../../store';import { type MarkdownElementProps } from '../type';import { isTagClosed } from '../utils';const Render = memo<MarkdownElementProps>(({ children, id }) => {const [isGenerating] = useConversationStore((s) => {const message = dataSelectors.getDbMessageById(id)(s);- return [!isTagClosed(ARTIFACT_THINKING_TAG, message?.content)];+ return [+ !isTagClosed(ARTIFACT_THINKING_TAG, message?.content) &&+ messageStateSelectors.isMessageGenerating(id)(s),+ ];});const transitionMode = useUserStore(userGeneralSettingsSelectors.transitionMode);diff --git a/src/features/Conversation/Markdown/plugins/Thinking/Render.tsx b/src/features/Conversation/Markdown/plugins/Thinking/Render.tsxindex 2284e8f9ad8..7e34321d296 100644--- a/src/features/Conversation/Markdown/plugins/Thinking/Render.tsx+++ b/src/features/Conversation/Markdown/plugins/Thinking/Render.tsx@@ -4,7 +4,7 @@ import Thinking from '@/features/Conversation/components/Thinking';import { useUserStore } from '@/store/user';import { userGeneralSettingsSelectors } from '@/store/user/selectors';-import { dataSelectors, useConversationStore } from '../../../store';+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../../store';import { type MarkdownElementProps } from '../type';const isThinkingClosed = (input: string = '') => {@@ -17,7 +17,9 @@ const isThinkingClosed = (input: string = '') => {const Render = memo<MarkdownElementProps>(({ children, id }) => {const [isGenerating] = useConversationStore((s) => {const message = dataSelectors.getDbMessageById(id)(s);- return [!isThinkingClosed(message?.content)];+ return [+ !isThinkingClosed(message?.content) && messageStateSelectors.isMessageGenerating(id)(s),+ ];});const citations = useConversationStore((s) => {const message = dataSelectors.getDbMessageById(id)(s);diff --git a/src/features/Conversation/Messages/components/ContentLoading.tsx b/src/features/Conversation/Messages/components/ContentLoading.tsxindex 576af4a5acd..7c2d081a2ca 100644--- a/src/features/Conversation/Messages/components/ContentLoading.tsx+++ b/src/features/Conversation/Messages/components/ContentLoading.tsx@@ -62,6 +62,8 @@ const ContentLoading = memo<ContentLoadingProps>(({ id }) => {const showElapsedTime = elapsedSeconds >= ELAPSED_TIME_THRESHOLD / 1000;+ if (!runningOp) return null;+if (operationType && NO_NEED_SHOW_DOT_OP_TYPES.has(operationType)) return null;if (operationType === 'contextCompression') {diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex a42c807ec3c..e49e0dce8d2 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -64,6 +64,7 @@ import {type ToolExecutionResultResponse,type ToolExecutionService,} from '@/server/services/toolExecution';+import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';import { dispatchClientTool } from './dispatchClientTool';import { formatErrorEventData } from './formatErrorEventData';@@ -116,6 +117,40 @@ const getToolFailureKind = (result: ToolExecutionResultResponse): ToolFailureKinconst shouldRetryTool = (kind: ToolFailureKind | undefined, attempt: number, maxRetries: number) =>kind === 'retry' && attempt <= maxRetries;+const archiveRuntimeToolResult = async (+ result: ToolExecutionResultResponse,+ {+ agentId,+ identifier,+ limit,+ serverDB,+ toolCallId,+ topicId,+ userId,+ }: {+ agentId?: string | null;+ identifier?: string;+ limit?: number;+ serverDB: LobeChatDatabase;+ toolCallId?: string;+ topicId?: string | null;+ userId?: string;+ },+): Promise<ToolExecutionResultResponse> => {+ const archive = await archiveToolResultIfNeeded({+ agentId,+ content: result.content,+ identifier,+ limit,+ serverDB,+ toolCallId,+ topicId,+ userId,+ });++ return archive.content === result.content ? result : { ...result, content: archive.content };+};+// Builds a postProcessUrl callback that resolves S3 keys in file-backed fields// (imageList, videoList, fileList) to absolute URLs. Must be passed to every// messageModel.query() call whose output is later fed to the LLM — otherwise@@ -1698,6 +1733,7 @@ export const createRuntimeExecutors = (operationId,scope: state.metadata?.scope,serverDB: ctx.serverDB,+ skipResultTruncation: true,taskId: state.metadata?.taskId,threadId: state.metadata?.threadId,toolCallId: chatToolPayload.id,@@ -1715,7 +1751,15 @@ export const createRuntimeExecutors = ();}- const executionResult = execution.result;+ const executionResult = await archiveRuntimeToolResult(execution.result, {+ agentId: state.metadata?.agentId,+ identifier: chatToolPayload.identifier,+ limit: toolResultMaxLength,+ serverDB: ctx.serverDB,+ toolCallId: chatToolPayload.id,+ topicId: ctx.topicId ?? state.metadata?.topicId,+ userId: ctx.userId,+ });const executionTime = executionResult.executionTime;const isSuccess = executionResult.success;if (ctx.hookDispatcher) {@@ -2172,6 +2216,7 @@ export const createRuntimeExecutors = (operationId,scope: state.metadata?.scope,serverDB: ctx.serverDB,+ skipResultTruncation: true,taskId: state.metadata?.taskId,threadId: state.metadata?.threadId,toolCallId: chatToolPayload.id,@@ -2189,7 +2234,15 @@ export const createRuntimeExecutors = ();}- const executionResult = execution.result;+ const executionResult = await archiveRuntimeToolResult(execution.result, {+ agentId: state.metadata?.agentId,+ identifier: chatToolPayload.identifier,+ limit: batchAgentConfig?.chatConfig?.toolResultMaxLength,+ serverDB: ctx.serverDB,+ toolCallId: chatToolPayload.id,+ topicId: ctx.topicId ?? state.metadata?.topicId,+ userId: ctx.userId,+ });const executionTime = executionResult.executionTime;const isSuccess = executionResult.success;if (ctx.hookDispatcher) {diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex bd519c76ff6..a2488485bf3 100644--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -2922,6 +2922,7 @@ describe('RuntimeExecutors', () => {expect(mockToolExecutionService.executeTool).toHaveBeenCalledWith(expect.anything(),expect.objectContaining({+ skipResultTruncation: true,toolResultMaxLength: 5000,}),);diff --git a/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts b/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.tsindex 626c5561518..78265697303 100644--- a/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts@@ -85,6 +85,31 @@ describe('AgentDocument VFS Router Integration Tests', () => {);});+ it('reads ordinary document line ranges through readDocumentByPath loc', async () => {+ await agentDocumentModel.create(+ agentId,+ 'tool-result.md',+ ['line 0', 'line 1', 'line 2', 'line 3'].join('\n'),+ );++ const caller = agentDocumentRouter.createCaller(createTestContext(userId));+ const read = await caller.readDocumentByPath({+ agentId,+ loc: [2, 4],+ path: './tool-result.md',+ });++ expect(read).toEqual(+ expect.objectContaining({+ content: 'line 2\nline 3',+ lineCount: 2,+ loc: [2, 4],+ path: './tool-result.md',+ totalLineCount: 4,+ }),+ );+ });+it('stats mounted agent skills through unified ./lobe paths', async () => {const caller = agentDocumentRouter.createCaller(createTestContext(userId));diff --git a/src/server/routers/lambda/agentDocument.ts b/src/server/routers/lambda/agentDocument.tsindex 598cecf68bd..4361d3c632c 100644--- a/src/server/routers/lambda/agentDocument.ts+++ b/src/server/routers/lambda/agentDocument.ts@@ -76,6 +76,12 @@ const toolLoadRuleSchema = z.object({});const readFormatSchema = z.enum(['xml', 'markdown', 'both']).optional();+const readLocSchema = z+ .tuple([z.number().int().min(0), z.number().int().min(0)])+ .refine(([startLine, endLine]) => endLine >= startLine, {+ message: 'loc end line must be greater than or equal to start line',+ })+ .optional();const writeCreateModeSchema = z.enum(['always-new', 'if-missing', 'must-exist']).optional();const recursiveSchema = z.boolean().optional();const mountedSkillNamespaceSchema = z.literal('agent');@@ -426,16 +432,23 @@ export const agentDocumentRouter = router({.input(z.object({agentId: z.string(),+ loc: readLocSchema,path: z.string(),topicId: z.string().optional(),}),).query(async ({ ctx, input }) => {try {- return await ctx.agentDocumentVfsService.read(input.path, {- agentId: input.agentId,- topicId: input.topicId,- });+ return await ctx.agentDocumentVfsService.read(+ input.path,+ {+ agentId: input.agentId,+ topicId: input.topicId,+ },+ {+ loc: input.loc,+ },+ );} catch (error) {handleAgentDocumentVfsError(error);}diff --git a/src/server/routers/lambda/aiChat.ts b/src/server/routers/lambda/aiChat.tsindex d36b49c7faf..dc285c49bf3 100644--- a/src/server/routers/lambda/aiChat.ts+++ b/src/server/routers/lambda/aiChat.ts@@ -2,6 +2,7 @@ import type { CreateMessageParams, SendMessageServerResponse } from '@lobechat/timport { AiSendMessageServerSchema, RequestTrigger, StructureOutputSchema } from '@lobechat/types';import { createTimingHelpers, createTimingRequestId } from '@lobechat/utils';import debug from 'debug';+import { z } from 'zod';import { LOADING_FLAT } from '@/const/message';import { AgentModel } from '@/database/models/agent';@@ -14,6 +15,7 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { resolveContext } from '@/server/routers/lambda/_helpers/resolveContext';import { AiChatService } from '@/server/services/aiChat';import { FileService } from '@/server/services/file';+import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';const log = debug('lobe-lambda-router:ai-chat');const { createPrefixedTimingContext, logTiming, runTimedStage } = createTimingHelpers(@@ -330,4 +332,23 @@ export const aiChatRouter = router({userMessageId: messageId,} as SendMessageServerResponse;}),++ archiveToolResult: aiChatProcedure+ .input(+ z.object({+ agentId: z.string().nullish(),+ content: z.string(),+ identifier: z.string().optional(),+ limit: z.number().optional(),+ toolCallId: z.string(),+ topicId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return archiveToolResultIfNeeded({+ ...input,+ serverDB: ctx.serverDB,+ userId: ctx.userId,+ });+ }),});diff --git a/src/server/services/agentDocumentVfs/index.test.ts b/src/server/services/agentDocumentVfs/index.test.tsindex ea9c1c0dedc..d5ea94564e5 100644--- a/src/server/services/agentDocumentVfs/index.test.ts+++ b/src/server/services/agentDocumentVfs/index.test.ts@@ -190,6 +190,66 @@ describe('AgentDocumentVfsService', () => {);});+ it('reads an ordinary file line range with loc metadata', async () => {+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([+ {+ accessSelf: AgentAccess.READ | AgentAccess.LIST,+ content: ['line 0', 'line 1', 'line 2', 'line 3'].join('\n'),+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-1',+ fileType: 'agent/document',+ filename: 'SOUL.md',+ id: 'agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ },+ ]);++ const service = new AgentDocumentVfsService(db, userId);+ const result = await service.read('./SOUL.md', { agentId: 'agent-1' }, { loc: [1, 3] });++ expect(result).toEqual(+ expect.objectContaining({+ content: 'line 1\nline 2',+ lineCount: 2,+ loc: [1, 3],+ path: './SOUL.md',+ totalLineCount: 4,+ }),+ );+ });++ it('reads a mounted skill file line range with loc metadata', async () => {+ mockSkillMount.get.mockResolvedValue({+ content: ['# Skill', '', 'Use this skill.', 'Extra notes.'].join('\n'),+ contentType: 'text/markdown',+ name: 'SKILL.md',+ namespace: 'agent',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ readOnly: false,+ type: 'file',+ });++ const service = new AgentDocumentVfsService(db, userId);+ const result = await service.read(+ './lobe/skills/agent/skills/writer/SKILL.md',+ {+ agentId: 'agent-1',+ },+ { loc: [2, 4] },+ );++ expect(result).toEqual(+ expect.objectContaining({+ content: 'Use this skill.\nExtra notes.',+ contentType: 'text/markdown',+ lineCount: 2,+ loc: [2, 4],+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ totalLineCount: 4,+ }),+ );+ });+it('creates a new ordinary file through write when the path is missing', async () => {mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);diff --git a/src/server/services/agentDocumentVfs/index.ts b/src/server/services/agentDocumentVfs/index.tsindex 6e4f5190b1d..cd0421db4c9 100644--- a/src/server/services/agentDocumentVfs/index.ts+++ b/src/server/services/agentDocumentVfs/index.ts@@ -22,6 +22,7 @@ import type { SkillMountNode } from './mounts/skills/types';import type {AgentDocumentListOptions,AgentDocumentNode,+ AgentDocumentReadOptions,AgentDocumentReadResult,AgentDocumentStats,AgentDocumentTrashEntry,@@ -202,7 +203,11 @@ export class AgentDocumentVfsService {* Returns:* - File content payload*/- async read(path: string, ctx: AgentDocumentVfsContext): Promise<AgentDocumentReadResult> {+ async read(+ path: string,+ ctx: AgentDocumentVfsContext,+ options: AgentDocumentReadOptions = {},+ ): Promise<AgentDocumentReadResult> {const normalizedPath = normalizeAgentDocumentPath(path);if (isSkillPath(normalizedPath)) {@@ -217,7 +222,7 @@ export class AgentDocumentVfsService {}return {- content: node.content ?? '',+ ...sliceReadContent(node.content ?? '', options.loc),contentType: node.contentType,path: node.path,};@@ -234,7 +239,7 @@ export class AgentDocumentVfsService {}return {- content: node.content,+ ...sliceReadContent(node.content, options.loc),contentType: 'text/markdown',path: normalizedPath,};@@ -1198,6 +1203,28 @@ const assertNotSelfReferentialCopy = (}};+const sliceReadContent = (+ content: string,+ loc?: [number, number],+): Omit<AgentDocumentReadResult, 'contentType' | 'path'> => {+ const lines = content.split('\n');+ const totalLineCount = lines.length;+ const totalCharCount = content.length;+ const actualLoc: [number, number] = loc ?? [0, totalLineCount];+ const [startLine, endLine] = actualLoc;+ const selectedLines = lines.slice(startLine, endLine);+ const selectedContent = selectedLines.join('\n');++ return {+ charCount: selectedContent.length,+ content: selectedContent,+ lineCount: selectedLines.length,+ loc: actualLoc,+ totalCharCount,+ totalLineCount,+ };+};+const inferMountedSkillIdentity = (path: string) => {for (const namespace of ['agent'] as const) {const prefix = getUnifiedSkillNamespaceRootPath(namespace);diff --git a/src/server/services/agentDocumentVfs/types.ts b/src/server/services/agentDocumentVfs/types.tsindex b4caa96cc38..14a46f12a4e 100644--- a/src/server/services/agentDocumentVfs/types.ts+++ b/src/server/services/agentDocumentVfs/types.ts@@ -98,9 +98,27 @@ export interface AgentDocumentTrashEntry extends AgentDocumentStats {* - File content plus the resolved VFS path*/export interface AgentDocumentReadResult {+ charCount: number;content: string;contentType?: string;+ lineCount: number;+ loc: [number, number];path: string;+ totalCharCount: number;+ totalLineCount: number;+}++/**+ * Options accepted by VFS file reads.+ *+ * Use when:+ * - Reading a bounded line range from a large virtual file+ *+ * Expects:+ * - `loc` is zero-based and end-exclusive, matching `readLocalFile`+ */+export interface AgentDocumentReadOptions {+ loc?: [number, number];}/**diff --git a/src/server/services/toolExecution/__tests__/archiveToolResult.test.ts b/src/server/services/toolExecution/__tests__/archiveToolResult.test.tsnew file mode 100644index 00000000000..dd402409236--- /dev/null+++ b/src/server/services/toolExecution/__tests__/archiveToolResult.test.ts@@ -0,0 +1,160 @@+// @vitest-environment node+import type { LobeChatDatabase } from '@lobechat/database';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { TopicDocumentModel } from '@/database/models/topicDocument';+import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';++import { archiveToolResultIfNeeded } from '../archiveToolResult';++vi.mock('@/server/services/agentDocumentVfs', () => ({+ AgentDocumentVfsService: vi.fn(),+}));++vi.mock('@/database/models/topicDocument', () => ({+ TopicDocumentModel: vi.fn(),+}));++describe('archiveToolResultIfNeeded', () => {+ const db = {} as LobeChatDatabase;+ const mockVfsService = {+ mkdir: vi.fn(),+ write: vi.fn(),+ };+ const mockTopicDocumentModel = {+ associate: vi.fn(),+ isAssociated: vi.fn(),+ };++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(AgentDocumentVfsService).mockImplementation(() => mockVfsService as any);+ vi.mocked(TopicDocumentModel).mockImplementation(() => mockTopicDocumentModel as any);+ mockVfsService.mkdir.mockResolvedValue({});+ mockVfsService.write.mockResolvedValue({ documentId: 'document-1', id: 'agent-doc-1' });+ mockTopicDocumentModel.isAssociated.mockResolvedValue(false);+ mockTopicDocumentModel.associate.mockResolvedValue({+ documentId: 'document-1',+ topicId: 'topic-1',+ });+ });++ it('returns unchanged content when it is under the limit', async () => {+ const result = await archiveToolResultIfNeeded({+ agentId: 'agent-1',+ content: 'short result',+ limit: 100,+ serverDB: db,+ toolCallId: 'call_1',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(result).toEqual({ archived: false, content: 'short result' });+ expect(AgentDocumentVfsService).not.toHaveBeenCalled();+ });++ it('archives oversized content and returns a truncated pointer', async () => {+ const result = await archiveToolResultIfNeeded({+ agentId: 'agent-1',+ content: '0123456789',+ limit: 5,+ serverDB: db,+ toolCallId: 'call_1',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(mockVfsService.mkdir).toHaveBeenCalledWith(+ './.tool-results',+ { agentId: 'agent-1', topicId: 'topic-1' },+ { recursive: true },+ );+ expect(mockVfsService.write).toHaveBeenCalledWith(+ './.tool-results/topic-1_call_1.md',+ '0123456789',+ { agentId: 'agent-1', topicId: 'topic-1' },+ );+ expect(mockTopicDocumentModel.associate).toHaveBeenCalledWith({+ documentId: 'document-1',+ topicId: 'topic-1',+ });+ expect(result.archived).toBe(true);+ expect(result.archivePath).toBe('./.tool-results/topic-1_call_1.md');+ expect(result.content).toContain('01234');+ expect(result.content).toContain('./.tool-results/topic-1_call_1.md');+ expect(result.content).toContain('lobe-agent-documents');+ expect(result.content).toContain('readDocument');+ expect(result.content).toContain('agent-doc-1');+ });++ it('does not duplicate topic association when the archive document is already associated', async () => {+ mockTopicDocumentModel.isAssociated.mockResolvedValue(true);++ await archiveToolResultIfNeeded({+ agentId: 'agent-1',+ content: '0123456789',+ limit: 5,+ serverDB: db,+ toolCallId: 'call_1',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(mockTopicDocumentModel.associate).not.toHaveBeenCalled();+ });++ it('falls back to truncation without archive context', async () => {+ const result = await archiveToolResultIfNeeded({+ agentId: 'agent-1',+ content: '0123456789',+ limit: 5,+ toolCallId: 'call_1',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(result.archived).toBe(false);+ expect(result.archivePath).toBeUndefined();+ expect(result.content).toContain('01234');+ expect(result.content).toContain('Content truncated');+ expect(result.content).not.toContain('Archive failed');+ expect(AgentDocumentVfsService).not.toHaveBeenCalled();+ });++ it('bypasses archive entirely for lobe-agent-documents tool results', async () => {+ const result = await archiveToolResultIfNeeded({+ agentId: 'agent-1',+ content: 'x'.repeat(1000),+ identifier: 'lobe-agent-documents',+ limit: 5,+ serverDB: db,+ toolCallId: 'call_1',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(result.archived).toBe(false);+ expect(result.content).toBe('x'.repeat(1000));+ expect(AgentDocumentVfsService).not.toHaveBeenCalled();+ });++ it('keeps the tool result bounded when archive writing fails', async () => {+ mockVfsService.write.mockRejectedValue(new Error('write denied'));++ const result = await archiveToolResultIfNeeded({+ agentId: 'agent-1',+ content: '0123456789',+ limit: 5,+ serverDB: db,+ toolCallId: 'call_1',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(result.archived).toBe(false);+ expect(result.error).toBe('write denied');+ expect(result.content).toContain('01234');+ expect(result.content).toContain('Archive failed: write denied');+ });+});diff --git a/src/server/services/toolExecution/__tests__/index.test.ts b/src/server/services/toolExecution/__tests__/index.test.tsnew file mode 100644index 00000000000..c28378c5bcb--- /dev/null+++ b/src/server/services/toolExecution/__tests__/index.test.ts@@ -0,0 +1,66 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { ToolExecutionService } from '../index';++describe('ToolExecutionService', () => {+ it('can skip low-level result truncation for AgentRuntime archival', async () => {+ const builtinToolsExecutor = {+ execute: vi.fn().mockResolvedValue({+ content: '0123456789',+ success: true,+ }),+ };+ const service = new ToolExecutionService({+ builtinToolsExecutor: builtinToolsExecutor as any,+ mcpService: {} as any,+ });++ const result = await service.executeTool(+ {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'lobe-web-browsing',+ type: 'builtin',+ },+ {+ skipResultTruncation: true,+ toolManifestMap: {},+ toolResultMaxLength: 5,+ },+ );++ expect(result.content).toBe('0123456789');+ });++ it('keeps existing low-level truncation by default', async () => {+ const builtinToolsExecutor = {+ execute: vi.fn().mockResolvedValue({+ content: '0123456789',+ success: true,+ }),+ };+ const service = new ToolExecutionService({+ builtinToolsExecutor: builtinToolsExecutor as any,+ mcpService: {} as any,+ });++ const result = await service.executeTool(+ {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'lobe-web-browsing',+ type: 'builtin',+ },+ {+ toolManifestMap: {},+ toolResultMaxLength: 5,+ },+ );++ expect(result.content).toContain('01234');+ expect(result.content).toContain('Content truncated');+ });+});diff --git a/src/server/services/toolExecution/archiveToolResult.ts b/src/server/services/toolExecution/archiveToolResult.tsnew file mode 100644index 00000000000..340398bb7f8--- /dev/null+++ b/src/server/services/toolExecution/archiveToolResult.ts@@ -0,0 +1,99 @@+import type { LobeChatDatabase } from '@lobechat/database';++import { TopicDocumentModel } from '@/database/models/topicDocument';+import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';+import {+ ARCHIVE_BYPASS_IDENTIFIERS,+ DEFAULT_TOOL_RESULT_MAX_LENGTH,+ truncateToolResult,+} from '@/server/utils/truncateToolResult';++const TOOL_RESULTS_DIR = './.tool-results';++export interface ToolResultArchiveOutcome {+ archived: boolean;+ archivePath?: string;+ content: string;+ error?: string;+}++interface ArchiveToolResultParams {+ agentId?: string | null;+ content: string;+ identifier?: string;+ limit?: number;+ serverDB?: LobeChatDatabase;+ toolCallId?: string;+ topicId?: string | null;+ userId?: string;+}++const buildArchivePath = (topicId: string, toolCallId: string) =>+ `${TOOL_RESULTS_DIR}/${topicId}_${toolCallId}.md`;++const getErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : String(error || 'Unknown archive error');++export const archiveToolResultIfNeeded = async ({+ agentId,+ content,+ identifier,+ limit,+ serverDB,+ toolCallId,+ topicId,+ userId,+}: ArchiveToolResultParams): Promise<ToolResultArchiveOutcome> => {+ if (identifier && ARCHIVE_BYPASS_IDENTIFIERS.has(identifier)) {+ return { archived: false, content };+ }++ const maxLength = limit ?? DEFAULT_TOOL_RESULT_MAX_LENGTH;++ if (!content || content.length <= maxLength) {+ return { archived: false, content };+ }++ const truncatedContent = truncateToolResult(content, maxLength);++ if (!agentId || !topicId || !toolCallId || !serverDB || !userId) {+ return { archived: false, content: truncatedContent };+ }++ const archivePath = buildArchivePath(topicId, toolCallId);++ try {+ const vfsService = new AgentDocumentVfsService(serverDB, userId);+ await vfsService.mkdir(TOOL_RESULTS_DIR, { agentId, topicId }, { recursive: true });+ const stats = await vfsService.write(archivePath, content, { agentId, topicId });++ if (stats.documentId) {+ const topicDocumentModel = new TopicDocumentModel(serverDB, userId);+ const associated = await topicDocumentModel.isAssociated(stats.documentId, topicId);+ if (!associated) {+ await topicDocumentModel.associate({+ documentId: stats.documentId,+ topicId,+ });+ }+ }++ const agentDocumentIdHint =+ stats.id ?? '(call lobe-agent-documents.listDocuments with scope=currentTopic to look up)';++ return {+ archivePath,+ archived: true,+ content: `${truncatedContent}\nFull content archived to the agent-document VFS.\nPath: ${archivePath}\nAgent Document ID: ${agentDocumentIdHint}\nTo inspect specific sections, call the lobe-agent-documents tool with apiName=readDocument and id=<Agent Document ID above>. Do NOT activate cloud-sandbox or local-system file tools — this archive exists only inside the agent document tree.`,+ };+ } catch (error) {+ const message = getErrorMessage(error);++ return {+ archivePath,+ archived: false,+ content: `${truncatedContent}\n[Archive failed: ${message}. Full content was not persisted.]`,+ error: message,+ };+ }+};diff --git a/src/server/services/toolExecution/index.ts b/src/server/services/toolExecution/index.tsindex 299a962d2f0..0994ab80ef4 100644--- a/src/server/services/toolExecution/index.ts+++ b/src/server/services/toolExecution/index.ts@@ -95,7 +95,9 @@ export class ToolExecutionService {// Truncate result content to prevent context overflow// Use agent-specific config if provided, otherwise use default- const truncatedContent = truncateToolResult(data.content, context.toolResultMaxLength);+ const truncatedContent = context.skipResultTruncation+ ? data.content+ : truncateToolResult(data.content, context.toolResultMaxLength);// Log if content was truncatedif (truncatedContent !== data.content) {@@ -132,7 +134,7 @@ export class ToolExecutionService {const errorMessage = (error as Error).message;return {- content: truncateToolResult(errorMessage),+ content: context.skipResultTruncation ? errorMessage : truncateToolResult(errorMessage),error: normalizeExecutionError(error, errorMessage),executionTime,success: false,diff --git a/src/server/services/toolExecution/types.ts b/src/server/services/toolExecution/types.tsindex 5f1a6056744..339a2b4011b 100644--- a/src/server/services/toolExecution/types.ts+++ b/src/server/services/toolExecution/types.ts@@ -36,6 +36,8 @@ export interface ToolExecutionContext {scope?: string | null;/** Server database for LobeHub Skills execution */serverDB?: LobeChatDatabase;+ /** Skip low-level result truncation so the AgentRuntime boundary can archive full content first. */+ skipResultTruncation?: boolean;/** Task ID when executing within the Task system */taskId?: string;/** Current thread ID for thread-scoped conversations */diff --git a/src/server/utils/__tests__/truncateToolResult.test.ts b/src/server/utils/__tests__/truncateToolResult.test.tsindex 785f7530621..79b5b46b405 100644--- a/src/server/utils/__tests__/truncateToolResult.test.ts+++ b/src/server/utils/__tests__/truncateToolResult.test.ts@@ -14,7 +14,18 @@ const endsWithHighSurrogate = (value: string) => {};describe('truncateToolResult', () => {- it('should not split an emoji surrogate pair at the truncation boundary', () => {+ it('returns content unchanged when within the limit', () => {+ expect(truncateToolResult('hello', 100)).toBe('hello');+ });++ 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');+ });++ it('does not leave a lone high surrogate when the cutoff splits an emoji', () => {const content = `prefix ${'a'.repeat(10)}${validEmoji} suffix`;const limit = 'prefix '.length + 10 + 1;const result = truncateToolResult(content, limit);@@ -23,10 +34,10 @@ describe('truncateToolResult', () => {expect(result).toContain('[Content truncated:');expect(truncatedPortion).toBe(`prefix ${'a'.repeat(10)}`);expect(endsWithHighSurrogate(truncatedPortion)).toBe(false);- expect(JSON.stringify({ content: result })).not.toContain('\\ud83d');+ expect(JSON.stringify(result)).not.toContain('\\ud83d"');});- it('should keep a full emoji when the complete surrogate pair fits', () => {+ it('keeps a full emoji when the complete surrogate pair fits', () => {const content = `prefix ${'a'.repeat(10)}${validEmoji} suffix`;const limit = 'prefix '.length + 10 + validEmoji.length;const result = truncateToolResult(content, limit);@@ -35,19 +46,19 @@ describe('truncateToolResult', () => {expect(result).toContain('[Content truncated:');});- it('should never leave a lone high surrogate inside a ZWJ-composed emoji at any cutoff', () => {+ it('never leaves a lone high surrogate inside a ZWJ-composed emoji at any cutoff', () => {const content = `ab${familyEmoji}cd`;for (let cutoff = 1; cutoff < content.length; cutoff += 1) {const result = truncateToolResult(content, cutoff);const truncatedPortion = getTruncatedPortion(result);- expect(endsWithHighSurrogate(truncatedPortion)).toBe(false);+ expect(endsWithHighSurrogate(truncatedPortion), `cutoff=${cutoff}`).toBe(false);expect(() => JSON.parse(JSON.stringify(result))).not.toThrow();}});- it('should preserve state while truncating content safely', () => {+ it('preserves state while truncating content safely', () => {const result = truncateToolResultWithState({ content: `value ${'x'.repeat(4)}${validEmoji} tail`, state: { ok: true } },'value '.length + 4 + 1,diff --git a/src/server/utils/truncateToolResult.ts b/src/server/utils/truncateToolResult.tsindex 2703a8ad706..5e663c5662e 100644--- a/src/server/utils/truncateToolResult.ts+++ b/src/server/utils/truncateToolResult.ts@@ -9,6 +9,12 @@*/export const DEFAULT_TOOL_RESULT_MAX_LENGTH = 25_000;+/**+ * Tool identifiers whose results must never be truncated or archived,+ * because they are themselves the read surface for archived content.+ */+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@@ -25,8 +31,9 @@ export function truncateToolResult(content: string, maxLength?: number): string}// Avoid splitting a UTF-16 surrogate pair: if the cutoff lands right after a- // high surrogate, step back one code unit. Otherwise JSON.stringify emits a- // lone `\uD83D`-style escape, which DeepSeek rejects at the JSON parser layer.+ // 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) {diff --git a/src/services/toolResultArchive.ts b/src/services/toolResultArchive.tsnew file mode 100644index 00000000000..dc42eef2bc3--- /dev/null+++ b/src/services/toolResultArchive.ts@@ -0,0 +1,42 @@+import { lambdaClient } from '@/libs/trpc/client';+import { ARCHIVE_BYPASS_IDENTIFIERS, truncateToolResult } from '@/server/utils/truncateToolResult';++interface ArchiveParams {+ agentId?: string | null;+ content: string;+ identifier?: string;+ limit?: number;+ toolCallId?: string;+ topicId?: string | null;+}++export const archiveToolResultViaServer = async ({+ agentId,+ content,+ identifier,+ limit,+ toolCallId,+ topicId,+}: ArchiveParams): Promise<string> => {+ if (identifier && ARCHIVE_BYPASS_IDENTIFIERS.has(identifier)) {+ return content;+ }++ if (!content || !toolCallId || !topicId) {+ return truncateToolResult(content, limit);+ }++ try {+ const outcome = await lambdaClient.aiChat.archiveToolResult.mutate({+ agentId,+ content,+ identifier,+ limit,+ toolCallId,+ topicId,+ });+ return outcome.content;+ } catch {+ return truncateToolResult(content, limit);+ }+};diff --git a/src/store/chat/slices/plugin/actions/exector.ts b/src/store/chat/slices/plugin/actions/exector.tsindex 380aa1d9fe0..658959f9928 100644--- a/src/store/chat/slices/plugin/actions/exector.ts+++ b/src/store/chat/slices/plugin/actions/exector.ts@@ -1,5 +1,4 @@import { type MCPToolCallResult } from '@/libs/mcp';-import { truncateToolResult } from '@/server/utils/truncateToolResult';import { useToolStore } from '@/store/tool';import { type ChatToolPayload } from '@/types/message';import { safeParseJSON } from '@/utils/safeParseJSON';@@ -64,7 +63,7 @@ export const klavisExecutor: RemoteToolExecutor = async (p, _context) => {const toolResult = result.data;if (toolResult) {return {- content: truncateToolResult(toolResult.content),+ content: toolResult.content,error: toolResult.state?.isError ? toolResult.state : undefined,state: toolResult.state,success: toolResult.success,@@ -97,8 +96,7 @@ export const lobehubSkillExecutor: RemoteToolExecutor = async (p, context) => {}// Convert to MCPToolCallResult format- const rawContent = typeof result.data === 'string' ? result.data : JSON.stringify(result.data);- const content = truncateToolResult(rawContent);+ const content = typeof result.data === 'string' ? result.data : JSON.stringify(result.data);return {content,diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex 4a1b23b14d8..7470cccc247 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -2,9 +2,9 @@ import { type ChatToolPayload, type RuntimeStepContext } from '@lobechat/types';import debug from 'debug';import { type MCPToolCallResult } from '@/libs/mcp';-import { truncateToolResult } from '@/server/utils/truncateToolResult';import { mcpService } from '@/services/mcp';import { messageService } from '@/services/message';+import { archiveToolResultViaServer } from '@/services/toolResultArchive';import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation';import { type ChatStore } from '@/store/chat/store';import { useToolStore } from '@/store/tool';@@ -176,7 +176,14 @@ export class PluginTypesActionImpl {});// When error exists but content is empty, backfill error message into content- const content = result.content || result.error?.message || '';+ const rawContent = result.content || result.error?.message || '';+ const content = await archiveToolResultViaServer({+ agentId,+ content: rawContent,+ identifier: payload.identifier,+ toolCallId: payload.id,+ topicId,+ });// Use optimisticUpdateToolMessage to batch update content, state, error, metadataawait optimisticUpdateToolMessage(@@ -295,8 +302,15 @@ export class PluginTypesActionImpl {if (!data) return;- // Truncate content to prevent context overflow- const truncatedContent = truncateToolResult(data.content || (data.error as any)?.message || '');+ // Archive oversized content (or truncate if archive context unavailable)+ const rawContent = data.content || (data.error as any)?.message || '';+ const truncatedContent = await archiveToolResultViaServer({+ agentId: message?.agentId,+ content: rawContent,+ identifier: payload.identifier,+ toolCallId: payload.id,+ topicId: message?.topicId,+ });// operationId already declared above, reuse itconst context = operationId ? { operationId } : undefined;@@ -370,7 +384,14 @@ export class PluginTypesActionImpl {// If error occurred, exitif (!data) return;- const remoteContent = data.content || (data.error as any)?.message || '';+ const rawContent = data.content || (data.error as any)?.message || '';+ const remoteContent = await archiveToolResultViaServer({+ agentId: message?.agentId,+ content: rawContent,+ identifier: payload.identifier,+ toolCallId: payload.id,+ topicId: message?.topicId,+ });const context = operationId ? { operationId } : undefined;// Use optimisticUpdateToolMessage to update content and state/error in a single call