π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent-runtime): strip heavy fields off finalState in stream events (#15190)
Arvin Xu506b96af6477
diff --git a/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts b/src/server/modules/AgentRuntime/GatewayStreamNotifier.tsindex 85fe2657017..1ed868b2d31 100644--- a/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -6,6 +6,7 @@ import {getDefaultReasonDetail,type StreamChunkData,type StreamEvent,+ stripFinalStateInEventData,} from './StreamEventManager';import type { IStreamEventManager, PublishAgentRuntimeEndParams } from './types';@@ -147,7 +148,18 @@ export class GatewayStreamNotifier implements IStreamEventManager {// βββ Gateway HTTP helpers βββprivate pushEvent(operationId: string, event: Record<string, unknown>) {- this.httpPost('/api/operations/push-event', { event, operationId }).catch(() => {});+ // Mirror the Redis publisher's chokepoint β strip+ // `finalState.messages` + tool-set fields off the gateway WS push+ // payload too. The gateway forwards events verbatim to clients, and+ // downstream consumers don't read these fields, so carrying them+ // would re-introduce the same multi-megabyte serialization that+ // crashed the xadd path.+ const sanitizedEvent =+ event.data === undefined ? event : { ...event, data: stripFinalStateInEventData(event.data) };+ this.httpPost('/api/operations/push-event', {+ event: sanitizedEvent,+ operationId,+ }).catch(() => {});}/**diff --git a/src/server/modules/AgentRuntime/InMemoryStreamEventManager.ts b/src/server/modules/AgentRuntime/InMemoryStreamEventManager.tsindex 199d9e8aed8..bb0ced16537 100644--- a/src/server/modules/AgentRuntime/InMemoryStreamEventManager.ts+++ b/src/server/modules/AgentRuntime/InMemoryStreamEventManager.ts@@ -1,6 +1,10 @@import debug from 'debug';-import { type StreamChunkData, type StreamEvent } from './StreamEventManager';+import {+ type StreamChunkData,+ type StreamEvent,+ stripFinalStateInEventData,+} from './StreamEventManager';import { type IStreamEventManager, type PublishAgentRuntimeEndParams } from './types';const log = debug('lobe-server:agent-runtime:in-memory-stream-event-manager');@@ -41,6 +45,11 @@ export class InMemoryStreamEventManager implements IStreamEventManager {const eventData: StreamEvent = {...event,+ // Mirror the Redis-backed manager's chokepoint strip so in-memory+ // event shape stays identical to the production wire format β+ // tests run against this manager and would otherwise mask+ // regressions in the strip behaviour.+ data: stripFinalStateInEventData(event.data),id: eventId,operationId,timestamp: Date.now(),@@ -105,6 +114,7 @@ export class InMemoryStreamEventManager implements IStreamEventManager {reasonDetail,uiMessages,}: PublishAgentRuntimeEndParams): Promise<string> {+ // Strip happens centrally inside `publishStreamEvent`.return this.publishStreamEvent(operationId, {data: {finalState,diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 081da76d153..108e0791456 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -2778,7 +2778,9 @@ export const createRuntimeExecutors = (}}- // Publish execution complete event+ // Publish execution complete event. `finalState.messages` + tool-set+ // fields are stripped centrally inside `publishStreamEvent` so this+ // call site stays unaware.await streamManager.publishStreamEvent(operationId, {data: {finalState: { ...state, status: 'done' },@@ -3087,7 +3089,8 @@ export const createRuntimeExecutors = (newState.lastModified = new Date().toISOString();newState.status = 'done';- // Publish completion event+ // Publish completion event. finalState stripped centrally inside+ // `publishStreamEvent`.await streamManager.publishStreamEvent(operationId, {data: {finalState: newState,diff --git a/src/server/modules/AgentRuntime/StreamEventManager.ts b/src/server/modules/AgentRuntime/StreamEventManager.tsindex 4cdd07a696d..18c6ab413b8 100644--- a/src/server/modules/AgentRuntime/StreamEventManager.ts+++ b/src/server/modules/AgentRuntime/StreamEventManager.ts@@ -40,6 +40,61 @@ export const getDefaultReasonDetail = (finalState: any, reason?: string): stringreturn 'Agent runtime completed successfully';};+/**+ * Drop reconstructible / heavy fields from an `AgentState` before+ * serializing it into a Redis stream event. `messages` is the size+ * driver β long topics with `compressedGroup` envelopes can push a+ * single `xadd` past Upstash's 10 MB request limit, manifesting on+ * the gateway as a misleading watchdog "Operation idle" timeout.+ *+ * The dropped fields are all reconstructible:+ *+ * - `messages` β canonical copy lives in the DB (UIChatMessage rows)+ * and the runtime in-memory state; in-process consumers that need+ * it (e.g. `execSubAgentTask.onComplete`) receive the full state+ * via the local `HookContext` channel, not via the stream.+ * - `operationToolSet`, `toolManifestMap`, `toolSourceMap`, `tools`+ * β operation-level snapshot; back-compat copies of one struct.+ *+ * Mirrors the `done`-event strip in `OperationTraceRecorder.appendStep`;+ * keep the two lists in sync if either set changes.+ */+const stripStateForStream = <T extends Record<string, any>>(+ state: T | undefined,+): T | undefined => {+ if (!state) return state;+ const {+ messages: _messages,+ operationToolSet: _operationToolSet,+ toolManifestMap: _toolManifestMap,+ toolSourceMap: _toolSourceMap,+ tools: _tools,+ ...rest+ } = state;+ return rest as T;+};++/**+ * Chokepoint helper applied inside every stream-event publish site.+ * If the event `data` carries a `finalState`, strip `messages` + the+ * tool-set group off it (see `stripStateForStream` for the rationale).+ *+ * Centralizing the strip here means new callers β including direct+ * `publishStreamEvent` users (e.g. `RuntimeExecutors`, the per-step+ * publish in `AgentRuntimeService.executeStep`) β get the size+ * protection automatically, with no per-site bookkeeping.+ *+ * Returns the original reference when no stripping is needed so the+ * common path stays allocation-free.+ */+export const stripFinalStateInEventData = (data: unknown): unknown => {+ if (!data || typeof data !== 'object') return data;+ const record = data as Record<string, unknown>;+ const finalState = record.finalState;+ if (!finalState || typeof finalState !== 'object') return data;+ return { ...record, finalState: stripStateForStream(finalState as Record<string, any>) };+};+/*** Server-side stream event shape. Wire-compatible with `AgentStreamEvent` in* `@lobechat/agent-gateway-client` (the type union is the single source of@@ -103,6 +158,11 @@ export class StreamEventManager {const eventData: StreamEvent = {...event,+ // Chokepoint strip β every event passing through here gets its+ // `data.finalState` trimmed (messages + tool-set fields) before+ // serialization so a single xadd can't blow past Upstash's 10 MB+ // request limit on long topics.+ data: stripFinalStateInEventData(event.data),operationId,timestamp: Date.now(),};@@ -191,6 +251,10 @@ export class StreamEventManager {reasonDetail,uiMessages,}: PublishAgentRuntimeEndParams): Promise<string> {+ // `finalState.messages` + tool-set fields are stripped centrally+ // inside `publishStreamEvent`; callers stay dumb. `reasonDetail`+ // derivation below uses the un-stripped in-process `finalState`+ // so the error message remains available.return this.publishStreamEvent(operationId, {data: {finalState,diff --git a/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.tsindex d46ccf938b0..167c7042e90 100644--- a/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.ts@@ -1,6 +1,10 @@import { describe, expect, it, vi } from 'vitest';-import { getDefaultReasonDetail, StreamEventManager } from '../StreamEventManager';+import {+ getDefaultReasonDetail,+ StreamEventManager,+ stripFinalStateInEventData,+} from '../StreamEventManager';// Mock Redis clientconst mockRedis = {@@ -237,6 +241,100 @@ describe('StreamEventManager', () => {expect.any(String),);});++ // Heavy reconstructible fields (notably `messages` with+ // compressedGroup envelopes) must be stripped before xadd so a+ // single event can't blow past Upstash's 10 MB request limit.+ it('strips messages + tool-set fields from finalState before xadd', async () => {+ const operationId = 'test-operation-id';+ const messages = [+ { content: 'msg', role: 'user' },+ { content: 'reply', role: 'assistant' },+ ];+ const finalState = {+ cost: { total: 42 },+ error: { message: 'boom', type: 'BoomError' },+ messages,+ operationToolSet: { enabledToolIds: ['x'] },+ status: 'error',+ stepCount: 4,+ toolManifestMap: { x: { name: 'x' } },+ toolSourceMap: { x: 'plugin' },+ tools: [{ name: 'x' }],+ usage: { llm: { tokens: { total: 100 } } },+ };++ mockRedis.xadd.mockResolvedValue('event-id-strip');++ await streamManager.publishAgentRuntimeEnd({+ finalState,+ operationId,+ reason: 'error',+ stepIndex: 4,+ });++ const dataArg = mockRedis.xadd.mock.calls[0]?.find(+ (a: any) => typeof a === 'string' && a.startsWith('{'),+ );+ const parsed = JSON.parse(dataArg);++ // Stripped: heavy / reconstructible fields gone+ expect(parsed.finalState.messages).toBeUndefined();+ expect(parsed.finalState.operationToolSet).toBeUndefined();+ expect(parsed.finalState.toolManifestMap).toBeUndefined();+ expect(parsed.finalState.toolSourceMap).toBeUndefined();+ expect(parsed.finalState.tools).toBeUndefined();++ // Preserved: lightweight observability fields downstream consumers use+ expect(parsed.finalState.status).toBe('error');+ expect(parsed.finalState.cost).toEqual({ total: 42 });+ expect(parsed.finalState.error).toEqual({ message: 'boom', type: 'BoomError' });+ expect(parsed.finalState.stepCount).toBe(4);+ expect(parsed.finalState.usage).toEqual({ llm: { tokens: { total: 100 } } });++ // reasonDetail derivation runs against the un-stripped in-process+ // finalState passed as a param, so the error message survives.+ expect(parsed.reasonDetail).toBe('boom');+ });+ });++ describe('stripFinalStateInEventData', () => {+ it('returns data unchanged when finalState is absent', () => {+ const data = { phase: 'execution_complete', reason: 'done' };+ expect(stripFinalStateInEventData(data)).toBe(data);+ });++ it('returns data unchanged when finalState is falsy', () => {+ const data = { finalState: null, reason: 'done' };+ expect(stripFinalStateInEventData(data)).toBe(data);+ });++ it('strips reconstructible fields off finalState while preserving others', () => {+ const result = stripFinalStateInEventData({+ finalState: {+ cost: { total: 1 },+ messages: [{ role: 'user' }],+ operationToolSet: {},+ status: 'done',+ toolManifestMap: {},+ toolSourceMap: {},+ tools: [],+ },+ reason: 'done',+ });++ expect(result).toEqual({+ finalState: { cost: { total: 1 }, status: 'done' },+ reason: 'done',+ });+ });++ it('handles non-object data defensively', () => {+ expect(stripFinalStateInEventData(undefined)).toBeUndefined();+ expect(stripFinalStateInEventData(null)).toBeNull();+ expect(stripFinalStateInEventData('chunk')).toBe('chunk');+ expect(stripFinalStateInEventData(123)).toBe(123);+ });});describe('getDefaultReasonDetail', () => {