π€― 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): route context engine payload out of the events stream (#15151)
Arvin Xu538195dfb46f
diff --git a/.agents/skills/agent-tracing/SKILL.md b/.agents/skills/agent-tracing/SKILL.mdindex ea0b3ed4b18..f1d092deae8 100644--- a/.agents/skills/agent-tracing/SKILL.md+++ b/.agents/skills/agent-tracing/SKILL.md@@ -14,7 +14,7 @@ In `NODE_ENV=development`, `AgentRuntimeService.executeStep()` automatically rec**Data flow**: executeStep loop -> build `StepPresentationData` -> write partial snapshot to disk -> on completion, finalize to `.agent-tracing/{timestamp}_{traceId}.json`-**Context engine capture**: In `RuntimeExecutors.ts`, the `call_llm` executor emits a `context_engine_result` event after `serverMessagesEngine()` processes messages. This event carries the full `contextEngineInput` (DB messages, systemRole, model, knowledge, tools, userMemory, etc.) and the processed `output` messages (the final LLM payload).+**Context engine capture**: In `RuntimeExecutors.ts`, the `call_llm` executor calls `ctx.tracingContextEngine(input, output)` after `serverMessagesEngine()` processes messages. `AgentRuntimeService.executeStep` buffers the call per step and forwards it to `OperationTraceRecorder.appendStep` as the typed `contextEngine` field. CE flows through this side channel rather than the `events` array so its heavy payload (agentDocuments, systemRole, β¦) never enters the Redis state pipeline (LOBE-9110).## Package Location@@ -199,9 +199,10 @@ interface StepSnapshot {messages?: any[]; // DB messages before stepcontext?: { phase: string; payload?: unknown; stepContext?: unknown };events?: Array<{ type: string; [key: string]: unknown }>;- // context_engine_result event contains:- // input: full contextEngineInput (messages, systemRole, model, knowledge, tools, userMemory, ...)- // output: processed messages array (final LLM payload)+ contextEngine?: {+ input?: unknown; // contextEngineInput minus messages + toolsConfig (reconstructible from baseline)+ output?: unknown; // processed messages array (final LLM payload)+ };}```@@ -216,5 +217,5 @@ When using `--messages`, the output shows three sections (if context engine data## Integration Points- **Recording**: `src/server/services/agentRuntime/AgentRuntimeService.ts` β in the `executeStep()` method, after building `stepPresentationData`, writes partial snapshot in dev mode-- **Context engine event**: `src/server/modules/AgentRuntime/RuntimeExecutors.ts` β in `call_llm` executor, after `serverMessagesEngine()` returns, emits `context_engine_result` event+- **Context engine capture**: `src/server/modules/AgentRuntime/RuntimeExecutors.ts` β in `call_llm` executor, after `serverMessagesEngine()` returns, calls `ctx.tracingContextEngine(input, output)`. `AgentRuntimeService.executeStep` buffers it per step and passes it to `traceRecorder.appendStep` as the typed `contextEngine` field (kept off the `events` array to stay out of Redis state).- **Store**: `FileSnapshotStore` reads/writes to `.agent-tracing/` relative to `process.cwd()`diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex f66d48ced18..fbfb14bc163 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -272,6 +272,14 @@ export interface RuntimeExecutorContext {streamManager: IStreamEventManager;toolExecutionService: ToolExecutionService;topicId?: string;+ /**+ * Trace-pipeline sink for context engine input/output. Wired by+ * AgentRuntimeService so the trace recorder can pick CE data up+ * out-of-band, keeping the heavy CE payload (agentDocuments, systemRole, β¦)+ * out of the `events` array and therefore out of the Redis state pipeline.+ * See LOBE-9110.+ */+ tracingContextEngine?: (input: unknown, output: unknown) => void;userId?: string;userTimezone?: string;}@@ -714,7 +722,7 @@ export const createRuntimeExecutors = (processedMessages = await serverMessagesEngine(contextEngineInput);- // Emit context engine event for tracing+ // Hand context engine input/output to the trace sink out-of-band.// Omit large/redundant fields to reduce snapshot size:// - input.messages: reconstructible from step's messagesBaseline + messagesDelta// - input.toolsConfig: static per operation, ~47KB of manifests repeated every call_llm step@@ -724,14 +732,10 @@ export const createRuntimeExecutors = (toolsConfig: _toolsConfig,...contextEngineInputLite} = contextEngineInput;- events.push({- input: {- ...contextEngineInputLite,- toolCount: _toolsConfig?.tools?.length ?? 0,- },- output: processedMessages,- type: 'context_engine_result',- } as any);+ ctx.tracingContextEngine?.(+ { ...contextEngineInputLite, toolCount: _toolsConfig?.tools?.length ?? 0 },+ processedMessages,+ );} else {processedMessages = llmPayload.messages;}diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex 68dbf95cdbe..765f151586a 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -622,6 +622,14 @@ export class AgentRuntimeService {log('[%s] beforeStep hook dispatch error: %O', operationId, hookError);}+ // Per-step buffer for context engine input/output. Populated by the+ // `tracingContextEngine` callback passed into the executor context;+ // consumed by traceRecorder.appendStep below. Routing CE this way keeps+ // its heavy payload (agentDocuments, systemRole, β¦) out of+ // `stepResult.events` and therefore out of the Redis state pipeline.+ // See LOBE-9110.+ let contextEnginePayload: { input: unknown; output: unknown } | undefined;+// Create Agent and Runtime instances// Use agentState.metadata which contains the full app context (topicId, agentId, etc.)// operationMetadata only contains basic fields (agentConfig, modelRuntimeConfig, userId)@@ -629,6 +637,9 @@ export class AgentRuntimeService {metadata: agentState?.metadata,operationId,stepIndex,+ tracingContextEngine: (input, output) => {+ contextEnginePayload = { input, output };+ },});// Handle human intervention@@ -800,6 +811,7 @@ export class AgentRuntimeService {afterStepSignalEvents,agentState,beforeStepSignalEvents,+ contextEngine: contextEnginePayload,currentContext,externalRetryCount,presentation: stepPresentationData,@@ -1337,10 +1349,12 @@ export class AgentRuntimeService {metadata,operationId,stepIndex,+ tracingContextEngine,}: {metadata?: any;operationId: string;stepIndex: number;+ tracingContextEngine?: (input: unknown, output: unknown) => void;}) {const contextWindowTokens =metadata?.modelRuntimeConfig?.model && metadata?.modelRuntimeConfig?.provider@@ -1386,6 +1400,7 @@ export class AgentRuntimeService {streamManager: this.streamManager,toolExecutionService: this.toolExecutionService,topicId: metadata?.topicId,+ tracingContextEngine,userId: metadata?.userId,};diff --git a/src/server/services/agentRuntime/OperationTraceRecorder.ts b/src/server/services/agentRuntime/OperationTraceRecorder.tsindex 14614d5a4c2..d8e2394b3dc 100644--- a/src/server/services/agentRuntime/OperationTraceRecorder.ts+++ b/src/server/services/agentRuntime/OperationTraceRecorder.ts@@ -15,6 +15,13 @@ export interface AppendStepParams {*/agentState: any;beforeStepSignalEvents: SignalEvent[];+ /**+ * Context engine input/output captured for this step. Delivered via+ * `RuntimeExecutorContext.tracingContextEngine` rather than through the+ * `events` array, so CE payloads (agentDocuments, systemRole, β¦) stay out+ * of the Redis state pipeline. See LOBE-9110.+ */+ contextEngine?: { input?: unknown; output?: unknown };currentContext?: { payload?: unknown; phase?: string; stepContext?: unknown };externalRetryCount: number;presentation: StepPresentationData;@@ -220,6 +227,7 @@ export class OperationTraceRecorder {agentState,afterStepSignalEvents,beforeStepSignalEvents,+ contextEngine: ceInput,currentContext,externalRetryCount,presentation,@@ -237,21 +245,20 @@ export class OperationTraceRecorder {const isBaseline = stepIndex === 0 || isCompression;const messagesDelta = afterMessages.slice(prevMessages.length);- // Extract context_engine_result into contextEngine (dedicated typed field).- // CE data is structural state, not a streaming event β it lives separately- // from events and uses the same delta pattern as messagesBaseline/messagesDelta.- const rawEvents = (stepResult.events as any[]) ?? [];- const ceEvent = rawEvents.find((e: any) => e.type === 'context_engine_result') as any;- const contextEngine: StepSnapshot['contextEngine'] = ceEvent- ? { input: ceEvent.input, output: ceEvent.output }+ // CE data is structural state, not a streaming event β delivered via the+ // typed `contextEngine` field on AppendStepParams (sourced from+ // RuntimeExecutorContext.tracingContextEngine). Uses the same delta+ // pattern as messagesBaseline/messagesDelta.+ const contextEngine: StepSnapshot['contextEngine'] = ceInput+ ? { input: ceInput.input, output: ceInput.output }: undefined;// Strip heavy/redundant data from events before persisting to snapshot.- // context_engine_result is excluded β stored in contextEngine instead.+ const rawEvents = (stepResult.events as any[]) ?? [];const snapshotEvents = [...beforeStepSignalEvents,...rawEvents- .filter((e) => e.type !== 'llm_stream' && e.type !== 'context_engine_result')+ .filter((e) => e.type !== 'llm_stream').map((e) => {if (e.type === 'done' && e.finalState) {// Remove reconstructible fields from finalState:diff --git a/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.tsindex 47048e81350..756d816d84d 100644--- a/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts+++ b/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts@@ -358,26 +358,29 @@ describe('OperationTraceRecorder', () => {recorder = new OperationTraceRecorder(store as any);});- const buildCeEvent = (overrides: Record<string, unknown> = {}) => ({+ const buildCe = (overrides: { input?: unknown; output?: unknown } = {}) => ({input: { messages: ['hello'] },output: { tokens: 42 },- type: 'context_engine_result',...overrides,});- const appendStepWithCe = (ceEvent: Record<string, unknown>, prevStepsInStore: any[]) => {+ const appendStepWithCe = (+ ce: { input?: unknown; output?: unknown },+ prevStepsInStore: any[],+ ) => {store.loadPartial.mockResolvedValue({ startedAt: 1, steps: prevStepsInStore });return recorder.appendStep('op-ce', {afterStepSignalEvents: [],agentState: { messages: [] },beforeStepSignalEvents: [],+ contextEngine: ce,currentContext: { phase: 'user_input' },externalRetryCount: 0,presentation: buildPresentation(),startedAt: 1000,stepIndex: prevStepsInStore.length,stepResult: {- events: [ceEvent],+ events: [],newState: { activatedStepTools: [], messages: [] },},});@@ -388,8 +391,8 @@ describe('OperationTraceRecorder', () => {return saved.steps.find((s: any) => s.stepIndex === newStepIndex);};- it('extracts CE event into contextEngine, not in events', async () => {- await appendStepWithCe(buildCeEvent(), []);+ it('routes CE input/output into contextEngine, never into events', async () => {+ await appendStepWithCe(buildCe(), []);const step = getSavedStep(0);// CE data lives in contextEngine, not events@@ -398,7 +401,7 @@ describe('OperationTraceRecorder', () => {});it('keeps both input and output on the first step (no previous CE to compare against)', async () => {- await appendStepWithCe(buildCeEvent(), []);+ await appendStepWithCe(buildCe(), []);const step = getSavedStep(0);expect(step.contextEngine.input).toEqual({ messages: ['hello'] });@@ -411,7 +414,7 @@ describe('OperationTraceRecorder', () => {stepIndex: 0,stepType: 'call_llm',};- await appendStepWithCe(buildCeEvent(), [prevStep]);+ await appendStepWithCe(buildCe(), [prevStep]);const step = getSavedStep(1);expect(step.contextEngine.input).toBeUndefined();@@ -424,10 +427,9 @@ describe('OperationTraceRecorder', () => {stepIndex: 0,stepType: 'call_llm',};- await appendStepWithCe(- buildCeEvent({ input: { messages: ['hello'] }, output: { tokens: 99 } }),- [prevStep],- );+ await appendStepWithCe(buildCe({ input: { messages: ['hello'] }, output: { tokens: 99 } }), [+ prevStep,+ ]);const step = getSavedStep(1);expect(step.contextEngine.input).toBeUndefined();@@ -440,10 +442,9 @@ describe('OperationTraceRecorder', () => {stepIndex: 0,stepType: 'call_llm',};- await appendStepWithCe(- buildCeEvent({ input: { messages: ['world'] }, output: { tokens: 42 } }),- [prevStep],- );+ await appendStepWithCe(buildCe({ input: { messages: ['world'] }, output: { tokens: 42 } }), [+ prevStep,+ ]);const step = getSavedStep(1);expect(step.contextEngine.input).toEqual({ messages: ['world'] });@@ -456,10 +457,9 @@ describe('OperationTraceRecorder', () => {stepIndex: 0,stepType: 'call_llm',};- await appendStepWithCe(- buildCeEvent({ input: { messages: ['new'] }, output: { tokens: 20 } }),- [prevStep],- );+ await appendStepWithCe(buildCe({ input: { messages: ['new'] }, output: { tokens: 20 } }), [+ prevStep,+ ]);const step = getSavedStep(1);expect(step.contextEngine.input).toEqual({ messages: ['new'] });@@ -476,7 +476,7 @@ describe('OperationTraceRecorder', () => {// step 1 has no contextEngine β dedup must skip it and walk back to step 0{ stepIndex: 1, stepType: 'call_tool' },];- await appendStepWithCe(buildCeEvent(), prevSteps);+ await appendStepWithCe(buildCe(), prevSteps);const step = getSavedStep(2);expect(step.contextEngine.input).toBeUndefined();@@ -492,7 +492,7 @@ describe('OperationTraceRecorder', () => {{ contextEngine: { output: { tokens: 42 } }, stepIndex: 1, stepType: 'call_llm' },];await appendStepWithCe(- buildCeEvent({ input: { messages: ['hello'] }, output: { tokens: 42 } }),+ buildCe({ input: { messages: ['hello'] }, output: { tokens: 42 } }),prevSteps,);@@ -501,7 +501,7 @@ describe('OperationTraceRecorder', () => {expect(step.contextEngine.output).toBeUndefined();});- it('sets contextEngine to undefined when the step has no context_engine_result event', async () => {+ it('sets contextEngine to undefined when no CE was recorded for the step', async () => {const prevStep = {contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },stepIndex: 0,