π€― 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
β‘οΈ perf(tools): project readFile, and stop shipping a tool body nobody opens (#19704)
Arvin Xu8e9ad839b805
diff --git a/apps/cli/src/utils/agentStream.test.ts b/apps/cli/src/utils/agentStream.test.tsindex 432335cbb3e..485ba25c5fc 100644--- a/apps/cli/src/utils/agentStream.test.ts+++ b/apps/cli/src/utils/agentStream.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { streamAgentEvents, streamAgentEventsViaWebSocket } from './agentStream';+import { replayAgentEvents, streamAgentEvents, streamAgentEventsViaWebSocket } from './agentStream';vi.mock('./logger', () => ({log: {@@ -638,3 +638,37 @@ describe('streamAgentEventsViaWebSocket', () => {expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Agent finished'));});});++describe('renderEvent tool_end', () => {+ const toolEnd = (result: Record<string, unknown>) =>+ [+ {+ data: {+ executionTime: 120,+ isSuccess: true,+ payload: { toolCalling: { apiName: 'search', id: 'tc-1', identifier: 'web' } },+ result,+ },+ type: 'tool_end',+ },+ ] as any;++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('prints the result body under --verbose', async () => {+ const { log } = await import('./logger');+ replayAgentEvents(toolEnd({ content: 'the body' }), { verbose: true });++ expect(log.toolResult).toHaveBeenCalledWith('tc-1', true, 'the body');+ });++ it('falls back to the timing when the transport dropped the body', async () => {+ const { log } = await import('./logger');+ // The gateway WS projects `tool_end` β the body arrives with the message.+ replayAgentEvents(toolEnd({ success: true }), { verbose: true });++ expect(log.toolResult).toHaveBeenCalledWith('tc-1', true, ' 120ms');+ });+});diff --git a/apps/cli/src/utils/agentStream.ts b/apps/cli/src/utils/agentStream.tsindex f32bc93dda1..109c3dbb8a3 100644--- a/apps/cli/src/utils/agentStream.ts+++ b/apps/cli/src/utils/agentStream.ts@@ -382,7 +382,12 @@ function renderEvent(event: AgentStreamEvent, ctx: RenderContext, options: Streaconst success = event.data?.isSuccess !== false;const time = event.data?.executionTime;const timeSuffix = time ? ` ${time}ms` : '';- log.toolResult(id, success, options.verbose ? event.data?.result?.content : timeSuffix);+ // Some transports drop the result body before it reaches us (the gateway+ // WS projects `tool_end` for tools whose body no consumer reads β it+ // arrives with the message instead). Fall back to the timing so+ // `--verbose` never prints `undefined`.+ const body = options.verbose ? event.data?.result?.content : undefined;+ log.toolResult(id, success, body ?? timeSuffix);break;}diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.tsindex 684ed8b0ffa..b1effe1f282 100644--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -1,4 +1,5 @@import type { ToolExecuteData } from '@lobechat/agent-gateway-client';+import { projectToolEndResult } from '@lobechat/tool-view-model';import type { ChatMessageError } from '@lobechat/types';import debug from 'debug';import urlJoin from 'url-join';@@ -23,6 +24,21 @@ import type { IStreamEventManager, PublishAgentRuntimeEndParams } from './types'const log = debug('lobe-server:agent-runtime:gateway-notifier');+/**+ * Reduce an event to what the gateway wire actually needs.+ *+ * Today that means `tool_end`: the body of a tool result reaches the screen+ * through the read path, which already projects it, so shipping the raw body+ * here is a second copy of the largest payload on the connection. See+ * `projectToolEndResult` for what survives and why.+ *+ * This is the transport seam on purpose. The shared stream-manager chokepoint+ * would also catch the Responses API and the CLI's `--verbose`, both of which+ * print the body.+ */+const projectGatewayEventData = (data: unknown, eventType: unknown): unknown =>+ eventType === 'tool_end' ? projectToolEndResult(data) : data;+const POST_TIMEOUT = 5000; // 5s per requestconst MAX_INFLIGHT = 20; // bounded concurrency@@ -402,7 +418,13 @@ export class GatewayStreamNotifier implements IStreamEventManager {const sanitizedEvent =event.data === undefined? event- : { ...event, data: sanitizeGatewayEventData(event.data, redaction, event.type) };+ : {+ ...event,+ data: projectGatewayEventData(+ sanitizeGatewayEventData(event.data, redaction, event.type),+ event.type,+ ),+ };const pushes: Promise<void>[] = [this.httpPost('/api/operations/push-event', {event: sanitizedEvent,diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.tsindex 2d58bd5cc19..024a666ebee 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts@@ -113,6 +113,59 @@ describe('GatewayStreamNotifier', () => {},);+ it('projects the tool_end result onto the wire without touching the inner copy', async () => {+ const result = {+ content: 'THE WHOLE PAGE'.repeat(500),+ state: {+ results: [{ crawler: 'naive', data: { content: 'x'.repeat(5000) }, url: 'https://a' }],+ },+ success: true,+ };+ const data = {+ executionTime: 42,+ isSuccess: true,+ payload: {+ parentMessageId: 'msg-1',+ toolCalling: { apiName: 'crawlSinglePage', identifier: 'lobe-web-browsing' },+ },+ result,+ };++ await notifier.publishStreamEvent('op-1', { data, stepIndex: 1, type: 'tool_end' });++ const pushed = JSON.parse(mockFetch.mock.calls[0][1].body).event.data;+ expect(pushed.result).not.toHaveProperty('content');+ expect(pushed.result.success).toBe(true);+ expect(pushed.isSuccess).toBe(true);+ expect(pushed.executionTime).toBe(42);+ expect(pushed.result.state.results[0].data.content.length).toBeLessThan(5000);+ // In-process consumers (Responses API, recorded steps) keep the real body.+ expect(inner.calls.publishStreamEvent[0][1].data.result).toBe(result);+ expect(data.result.content).toBe(result.content);+ });++ it('keeps a shell result body, whose renderer-side hook parses it', async () => {+ const data = {+ isSuccess: true,+ payload: { toolCalling: { apiName: 'runCommand', identifier: 'lobe-local-system' } },+ result: { content: 'Switched to branch feat/x', state: { exitCode: 0 }, success: true },+ };++ await notifier.publishStreamEvent('op-1', { data, stepIndex: 1, type: 'tool_end' });++ const pushed = JSON.parse(mockFetch.mock.calls[0][1].body).event.data;+ expect(pushed.result.content).toBe('Switched to branch feat/x');+ expect(pushed.result.state.exitCode).toBe(0);+ });++ it('leaves other event types carrying their result body', async () => {+ const data = { result: { content: 'kept' } };++ await notifier.publishStreamEvent('op-1', { data, stepIndex: 1, type: 'step_start' });++ expect(JSON.parse(mockFetch.mock.calls[0][1].body).event.data.result.content).toBe('kept');+ });+it('forwards opted-in step state without bypassing visitor redaction', async () => {const finalState = {host: { includeFinalState: true },diff --git a/packages/agent-gateway-client/PROTOCOL_V2.md b/packages/agent-gateway-client/PROTOCOL_V2.mdindex afd06946e03..b8c4d64661b 100644--- a/packages/agent-gateway-client/PROTOCOL_V2.md+++ b/packages/agent-gateway-client/PROTOCOL_V2.md@@ -33,6 +33,24 @@ omit reconstructible message history and tool-set fields; share-visitor redactioalways takes precedence. Internal state persistence and local done events areunaffected. This option does not change terminal message-patch reconciliation.+### 0.2 Projected `tool_end` results++`tool_end` announces that a tool finished; it is not how the result reaches the+screen. That arrives with the message, through a read path that already projects+it, so the event carries a second copy of the largest payload on the connection.++The gateway push runs `result.state` through the same per-tool projectors the read+path uses, keeping mid-run and settled renders identical, and drops `result.content`+for the tools vouched for by the `eventBodyUnused` allowlist in+`@lobechat/tool-view-model`. The allowlist exists because several renderer-side+`onAfterCall` hooks parse the body for invisible side effects β a shell result tells+the topic which branch it switched to and which PR it opened β so shell and worktree+tools keep their body, and any tool not on the list is unchanged.++This is applied in `GatewayStreamNotifier`, the WS transport seam. In-process+consumers β the OpenAI-compatible Responses endpoint, recorded step events β install+their own stream manager, never reach this path, and keep the real body.+### 0.1 Native runtime message reconciliationFor the server-owned native agent harness, protocol v2 avoids repeating the completediff --git a/packages/tool-view-model/src/index.ts b/packages/tool-view-model/src/index.tsindex dd6023a5b75..42bc0091ad2 100644--- a/packages/tool-view-model/src/index.ts+++ b/packages/tool-view-model/src/index.ts@@ -1,3 +1,4 @@export { type ProjectorResolver, projectToolViewModels } from './project';+export { projectToolEndResult, type ToolEventResult } from './projectToolEvent';export { getToolProjector, listProjectedTools } from './registry';export type { ToolProjection, ToolProjector, ToolProjectorInput } from './types';diff --git a/packages/tool-view-model/src/project.test.ts b/packages/tool-view-model/src/project.test.tsindex fde8710aecd..17a6eb88a17 100644--- a/packages/tool-view-model/src/project.test.ts+++ b/packages/tool-view-model/src/project.test.ts@@ -143,6 +143,7 @@ describe('registry', () => {'claude-code/Bash','codex/command_execution','lobe-agent-documents/readDocument',+ 'lobe-local-system/readFile','lobe-local-system/runCommand','lobe-web-browsing/crawlMultiPages','lobe-web-browsing/crawlSinglePage',diff --git a/packages/tool-view-model/src/projectToolEvent.test.ts b/packages/tool-view-model/src/projectToolEvent.test.tsnew file mode 100644index 00000000000..22ca070097c--- /dev/null+++ b/packages/tool-view-model/src/projectToolEvent.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from 'vitest';++import { projectToolEndResult } from './projectToolEvent';++const toolEndData = (+ result: Record<string, unknown>,+ identifier = 'lobe-web-browsing',+ apiName = 'crawlSinglePage',+) => ({+ executionTime: 12,+ isSuccess: true,+ payload: { parentMessageId: 'msg-1', toolCalling: { apiName, identifier } },+ phase: 'tool_execution',+ result,+});++describe('projectToolEndResult', () => {+ it('drops the body of a tool no hook reads', () => {+ const projected = projectToolEndResult(+ toolEndData({ content: 'RAW BODY', success: true }),+ ) as any;++ expect('content' in projected.result).toBe(false);+ expect(projected.result.success).toBe(true);+ });++ it('keeps the fields the executor hooks and the Work refresh read', () => {+ const projected = projectToolEndResult(+ toolEndData({ content: 'RAW BODY', success: false, workRegistration: { type: 'skill' } }),+ ) as any;++ expect(projected.result.workRegistration).toEqual({ type: 'skill' });+ expect(projected.result.success).toBe(false);+ expect(projected.isSuccess).toBe(true);+ expect(projected.executionTime).toBe(12);+ expect(projected.payload).toEqual({+ parentMessageId: 'msg-1',+ toolCalling: { apiName: 'crawlSinglePage', identifier: 'lobe-web-browsing' },+ });+ });++ it('projects the state through the same projector the read path uses', () => {+ const projected = projectToolEndResult(+ toolEndData({+ content: 'RAW BODY',+ state: { results: [{ crawler: 'naive', data: { content: 'x'.repeat(5000) }, url: 'u' }] },+ success: true,+ }),+ ) as any;++ const [entry] = projected.result.state.results;+ expect(entry.data.content.length).toBeLessThan(5000);+ expect(entry.data.length).toBe(5000);+ });++ // The renderer-side hooks parse a shell result's body to learn the branch a+ // run switched to and the PR it opened. Dropping it loses the topic binding.+ it.each([+ ['lobe-local-system', 'runCommand'],+ ['claude-code', 'Bash'],+ ['codex', 'command_execution'],+ ['opencode', 'bash'],+ ['pi', 'bash'],+ ['claude-code', 'EnterWorktree'],+ ])('keeps the body of %s/%s, whose hook parses it', (identifier, apiName) => {+ const projected = projectToolEndResult(+ toolEndData(+ { content: 'Switched to branch feat/x', state: { exitCode: 0 }, success: true },+ identifier,+ apiName,+ ),+ ) as any;++ expect(projected.result.content).toBe('Switched to branch feat/x');+ expect(projected.result.state.exitCode).toBe(0);+ });++ // A tool can shed its body without having a projector: the body reaching the+ // screen is the read path's business, and only the hooks matter here.+ it.each([+ ['lobe-agent-documents', 'listDocuments'],+ ['lobe-user-memory', 'searchUserMemory'],+ ])('drops the body of %s/%s while leaving its unprojected state', (identifier, apiName) => {+ const state = { items: [{ id: 'a' }] };+ const projected = projectToolEndResult(+ toolEndData({ content: 'RAW BODY', state, success: true }, identifier, apiName),+ ) as any;++ expect('content' in projected.result).toBe(false);+ expect(projected.result.state).toBe(state);+ });++ it('keeps the body of a tool with no projector β nothing has vouched for it', () => {+ const data = toolEndData({ content: 'RAW BODY', state: { anything: 1 } }, 'some-mcp-plugin');++ expect(projectToolEndResult(data)).toBe(data);+ });++ it('leaves data it does not recognize alone', () => {+ expect(projectToolEndResult(undefined)).toBeUndefined();+ expect(projectToolEndResult({ result: 'not-an-object' })).toEqual({ result: 'not-an-object' });++ const bodiless = { payload: {}, result: { success: true } };+ expect(projectToolEndResult(bodiless)).toBe(bodiless);+ });+});diff --git a/packages/tool-view-model/src/projectToolEvent.ts b/packages/tool-view-model/src/projectToolEvent.tsnew file mode 100644index 00000000000..0fe65d936db--- /dev/null+++ b/packages/tool-view-model/src/projectToolEvent.ts@@ -0,0 +1,67 @@+import { getToolProjector, isToolEventBodyUnused } from './registry';++/** The `result` a `tool_end` event carries: the same two halves, different keys. */+export interface ToolEventResult {+ [key: string]: unknown;+ content?: unknown;+ state?: unknown;+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === 'object' && !Array.isArray(value);++/**+ * Reduce the `result` on a `tool_end` before it goes over the WebSocket.+ *+ * `tool_end` announces that a tool finished; it is not how the result reaches+ * the screen β that arrives with the message, through the read path, which+ * already projects it. So the event is carrying a second copy of the largest+ * payload on the connection, and on this wire it drives only two things: an+ * executor's `onAfterCall` hook, and whether a Work view needs refreshing.+ *+ * `state` goes through the same projector the read path uses, so a tool looks+ * the same mid-run as it does once settled. No hook among the projected tools+ * reads `result.state` beyond `runCommand`'s exit code, which the projector+ * keeps.+ *+ * The body goes only for the tools {@link isToolEventBodyUnused} vouches for.+ * Shell and worktree tools keep theirs β their hooks parse it.+ *+ * Applied on the gateway push only. The OpenAI-compatible Responses endpoint+ * installs its own stream manager and never reaches this path, so its+ * `function_call_output` keeps the real output.+ */+export const projectToolEndResult = (data: unknown): unknown => {+ if (!isRecord(data)) return data;++ const result = data.result;+ if (!isRecord(result)) return data;++ const toolCalling = isRecord(data.payload) ? data.payload.toolCalling : undefined;+ const rawIdentifier = isRecord(toolCalling) ? toolCalling.identifier : undefined;+ const rawApiName = isRecord(toolCalling) ? toolCalling.apiName : undefined;+ const identifier = typeof rawIdentifier === 'string' ? rawIdentifier : undefined;+ const apiName = typeof rawApiName === 'string' ? rawApiName : undefined;++ const projector = getToolProjector(identifier, apiName);+ const dropBody = 'content' in result && isToolEventBodyUnused(identifier, apiName);++ let projectedState: unknown = result.state;+ if (projector && isRecord(result.state)) {+ const projection = projector({+ apiName: apiName ?? '',+ content: typeof result.content === 'string' ? result.content : '',+ identifier: identifier ?? '',+ pluginState: result.state,+ });+ if (projection?.pluginState !== undefined) projectedState = projection.pluginState;+ }++ if (!dropBody && projectedState === result.state) return data;++ const { content: _content, ...rest } = result as ToolEventResult;+ const projected: ToolEventResult = dropBody ? rest : { ...result };+ if (projectedState !== result.state) projected.state = projectedState;++ return { ...data, result: projected };+};diff --git a/packages/tool-view-model/src/projectors/projectors.test.ts b/packages/tool-view-model/src/projectors/projectors.test.tsindex 639ef6746a7..c82b138f61e 100644--- a/packages/tool-view-model/src/projectors/projectors.test.ts+++ b/packages/tool-view-model/src/projectors/projectors.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import { readDocumentProjector } from './agentDocuments';import { runCommandProjector } from './localSystem';+import { readFileProjector } from './readFile';import { crawlProjector } from './webBrowsing';const input = (partial: Record<string, unknown> = {}) => ({@@ -195,3 +196,52 @@ describe('readDocumentProjector', () => {});});});++describe('readFileProjector', () => {+ const fileState = (over: Record<string, unknown> = {}) => ({+ content: 'x'.repeat(8000),+ fileType: 'ts',+ images: [{ url: 'https://cdn.test/a.png' }],+ loc: [0, 200],+ path: '/repo/src/index.ts',+ ...over,+ });++ it('drops both copies of the file and keeps what the card reads', () => {+ const result = readFileProjector(+ input({ content: 'File: /repo/src/index.ts\n...', pluginState: fileState() }),+ );++ expect(result?.content).toBeNull();+ expect(result?.pluginState).toEqual({+ charCount: 8000,+ fileType: 'ts',+ images: [{ url: 'https://cdn.test/a.png' }],+ loc: [0, 200],+ path: '/repo/src/index.ts',+ });+ expect(result?.storedPayloadNeededBy).toBe('render');+ });++ it('pins charCount, which the card otherwise derives from the dropped body', () => {+ const result = readFileProjector(input({ pluginState: fileState({ charCount: 12_345 }) }));++ expect((result?.pluginState as any).charCount).toBe(12_345);+ });++ it('keeps images, which vision models read as image_url parts', () => {+ const result = readFileProjector(input({ pluginState: fileState() }));++ expect((result?.pluginState as any).images).toEqual([{ url: 'https://cdn.test/a.png' }]);+ });++ it('still drops the duplicated body when state carries no file text', () => {+ const result = readFileProjector(input({ content: 'body', pluginState: { path: '/a' } }));++ expect(result).toEqual({ content: null, storedPayloadNeededBy: 'render' });+ });++ it('declines when there is nothing to drop', () => {+ expect(readFileProjector(input({ content: '', pluginState: { path: '/a' } }))).toBeUndefined();+ });+});diff --git a/packages/tool-view-model/src/projectors/readFile.ts b/packages/tool-view-model/src/projectors/readFile.tsnew file mode 100644index 00000000000..817ef0e7a9c--- /dev/null+++ b/packages/tool-view-model/src/projectors/readFile.ts@@ -0,0 +1,40 @@+import type { ToolProjector } from '../types';++const isRecord = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === 'object' && !Array.isArray(value);++/**+ * `readFile` β the largest single tool in production, and another one storing+ * its payload twice: the message body and `state.content` both hold the file.+ *+ * The card reads `state.content` (`buildReadFileState` falls back to the message+ * body only for the opencode / pi variants), and it mounts with the row's+ * expansion, so both copies go and the card hydrates on open.+ *+ * `charCount` is pinned first: the card computes it from the body when state+ * doesn't carry it, so without this every file would report zero characters.+ *+ * Everything else stays, `images` above all β those are turned into `image_url`+ * parts for vision-capable models, so they are MODEL-facing, not decoration.+ */+export const readFileProjector: ToolProjector = ({ content, pluginState }) => {+ if (!isRecord(pluginState)) {+ return content ? { content: null, storedPayloadNeededBy: 'render' } : undefined;+ }++ const body = pluginState.content;+ if (typeof body !== 'string') {+ return content ? { content: null, storedPayloadNeededBy: 'render' } : undefined;+ }++ const { content: _body, ...rest } = pluginState;++ return {+ content: null,+ pluginState: {+ ...rest,+ charCount: typeof pluginState.charCount === 'number' ? pluginState.charCount : body.length,+ },+ storedPayloadNeededBy: 'render',+ };+};diff --git a/packages/tool-view-model/src/registry.ts b/packages/tool-view-model/src/registry.tsindex a9e73ed6154..687fd092161 100644--- a/packages/tool-view-model/src/registry.ts+++ b/packages/tool-view-model/src/registry.ts@@ -1,5 +1,6 @@import { readDocumentProjector } from './projectors/agentDocuments';import { runCommandProjector } from './projectors/localSystem';+import { readFileProjector } from './projectors/readFile';import { crawlProjector } from './projectors/webBrowsing';import type { ToolProjector } from './types';@@ -31,6 +32,7 @@ const toolProjectors: Record<string, Record<string, ToolProjector>> = {readDocument: readDocumentProjector,},'lobe-local-system': {+ readFile: readFileProjector,runCommand: runCommandProjector,},'lobe-web-browsing': {@@ -45,6 +47,40 @@ const toolProjectors: Record<string, Record<string, ToolProjector>> = {},};+/**+ * Tools whose result BODY no `tool_end` consumer reads, so the gateway can drop+ * it from the event (the body still reaches the screen with the message).+ *+ * An allowlist, not a denylist, because getting this wrong is silent. Several+ * renderer-side `onAfterCall` hooks parse the body for side effects the user+ * never sees them do β every heterogeneous CLI's shell tool and its worktree+ * enter/exit feed `recordGitCommandEffects` / `recordWorktreeEnter`, and+ * `lobe-local-system/runCommand` does the same for native runs, which is how a+ * topic learns the branch it switched to and the PR it opened. Dropping the+ * body there would lose that binding with nothing on screen to show for it.+ *+ * So a tool earns a place here only after its hooks are checked. Anything+ * absent keeps shipping its body, exactly as before.+ */+const eventBodyUnused: ReadonlySet<string> = new Set([+ // `lobe-agent-documents`' hook only fires for list-mutating APIs and reads+ // `result.success`; a read is neither.+ 'lobe-agent-documents/listDocuments',+ 'lobe-agent-documents/readDocument',+ // `lobe-local-system`'s hook is scoped to `runCommand`.+ 'lobe-local-system/readFile',+ // `lobe-user-memory` and `lobe-web-browsing` register no hook at all.+ 'lobe-user-memory/searchUserMemory',+ 'lobe-web-browsing/crawlMultiPages',+ 'lobe-web-browsing/crawlSinglePage',+]);++/** Whether a `tool_end` for this tool can travel without its result body. */+export const isToolEventBodyUnused = (+ identifier?: string | null,+ apiName?: string | null,+): boolean => !!identifier && !!apiName && eventBodyUnused.has(`${identifier}/${apiName}`);+export const getToolProjector = (identifier?: string | null,apiName?: string | null,