🤯 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(context-engine): pair tool results by position when providers reuse tool_call ids (#20114)
Arvin Xu3916ae426529
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.tsindex 98dd47c6fd7..5c02ecf5de0 100644--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts@@ -1123,6 +1123,78 @@ Document content here.});});+ describe('Provider-reused tool_call ids', () => {+ it('should send each step its own stored result when every step reuses `<tool>:0`', async () => {+ // Stored shape of a Kimi (zeabur / nvidia / moonshot) run: every step's+ // call id is `lobe-local-system____runCommand:0`, and every step succeeded.+ const reusedId = 'lobe-local-system____runCommand:0';+ const step = (n: number): UIChatMessage[] => [+ {+ content: '',+ createdAt: Date.now(),+ id: `assistant-${n}`,+ role: 'assistant',+ tools: [+ {+ apiName: 'runCommand',+ arguments: `{"command":"echo ok-${n}"}`,+ id: reusedId,+ identifier: 'lobe-local-system',+ type: 'builtin',+ },+ ],+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: `Command completed successfully.\n\nStdout: ok-${n}`,+ createdAt: Date.now(),+ id: `tool-${n}`,+ plugin: {+ apiName: 'runCommand',+ arguments: `{"command":"echo ok-${n}"}`,+ identifier: 'lobe-local-system',+ type: 'builtin',+ },+ role: 'tool',+ tool_call_id: reusedId,+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const engine = new MessagesEngine(+ createBasicParams({+ messages: [+ {+ content: 'run three commands',+ createdAt: Date.now(),+ id: 'user-1',+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ...step(1),+ ...step(2),+ ...step(3),+ ],+ }),+ );++ const result = await engine.process();+ const toolMessages = result.messages.filter((m) => m.role === 'tool');+ const callIds = result.messages+ .filter((m) => m.role === 'assistant')+ .flatMap((m) => (m as any).tool_calls.map((call: { id: string }) => call.id));++ expect(toolMessages.map((m) => m.content)).toEqual([+ 'Command completed successfully.\n\nStdout: ok-1',+ 'Command completed successfully.\n\nStdout: ok-2',+ 'Command completed successfully.\n\nStdout: ok-3',+ ]);+ expect(new Set(callIds).size).toBe(3);+ expect(toolMessages.map((m) => (m as any).tool_call_id)).toEqual(callIds);+ expect(result.metadata.toolMessageReorder?.removedInvalidTools).toBe(0);+ });+ });+describe('Page Selections', () => {it('should inject page selections to each user message that has them', async () => {const messages: UIChatMessage[] = [diff --git a/packages/context-engine/src/processors/ToolMessageReorder.ts b/packages/context-engine/src/processors/ToolMessageReorder.tsindex 1d740c0dfd6..0a15f3a69b4 100644--- a/packages/context-engine/src/processors/ToolMessageReorder.ts+++ b/packages/context-engine/src/processors/ToolMessageReorder.ts@@ -116,81 +116,140 @@ export class ToolMessageReorder extends BaseProcessor {/*** Reorder tool messages+ *+ * `tool_call_id` is provider-supplied and NOT unique across a conversation:+ * Kimi (via zeabur / nvidia / moonshot) numbers calls per response, so every+ * step calls `<tool>:0` (`<tool>_0` via giteeai), and OpenRouter DeepSeek+ * reuses `call_0`. Results are therefore paired with the call they answer by+ * position — the nearest preceding assistant that made that call — not by a+ * conversation-wide id map, which handed step 1's result to step 1 only and+ * replaced every later step's real result with `tool_result_missing`. Reused+ * ids are then made unique in the request, since strict providers reject a+ * conversation that repeats a tool call id.*/private reorderToolMessages(messages: any[]): {removedInvalidTools: number;reorderedMessages: any[];} {let removedInvalidTools = 0;- const validToolCallIds = new Set<string>();- const toolMessages = new Map<string, any>();+ // assistant message index → its tool calls with in-message duplicates removed+ const callsByAssistant = new Map<number, any[]>();+ // tool_call_id → indexes of the assistant messages that made that call+ const callersById = new Map<string, number[]>();- // 1. First collect all valid tool_call_ids from assistant messages- for (const message of messages) {+ // 1. Collect the tool calls of every assistant message+ for (const [index, message] of messages.entries()) {if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) continue;const seenToolCallIds = new Set<string>();+ const normalizedToolCalls = [];+for (const toolCall of message.tool_calls) {if (!toolCall?.id) continue;if (seenToolCallIds.has(toolCall.id)) continue;seenToolCallIds.add(toolCall.id);- validToolCallIds.add(toolCall.id);+ normalizedToolCalls.push(toolCall);++ const callers = callersById.get(toolCall.id) ?? [];+ callers.push(index);+ callersById.set(toolCall.id, callers);}++ callsByAssistant.set(index, normalizedToolCalls);}- // 2. Collect all valid tool messages- for (const message of messages) {+ // 2. Attach each tool message to the call it answers+ const resultKey = (assistantIndex: number, toolCallId: string) =>+ `${assistantIndex}:${toolCallId}`;+ const toolMessages = new Map<string, any>();++ for (const [index, message] of messages.entries()) {if (message.role !== 'tool') continue;+ const callers = message.tool_call_id ? callersById.get(message.tool_call_id) : undefined;+// Skip invalid tool messages- if (!message.tool_call_id || !validToolCallIds.has(message.tool_call_id)) {+ if (!callers) {removedInvalidTools++;continue;}- if (toolMessages.has(message.tool_call_id)) {- // Check if this tool message has already been added+ const isAnswered = (callerIndex: number) =>+ toolMessages.has(resultKey(callerIndex, message.tool_call_id));+ // A row's parentId names the assistant it answers when it is that raw+ // row; otherwise a result answers the nearest call before it, and once+ // that call has one this row is a duplicate. Only a result stored ahead+ // of every call (out-of-order rows) falls forward to the first+ // unanswered one.+ const linkedCaller = message.parentId+ ? callers.find((callerIndex) => messages[callerIndex].id === message.parentId)+ : undefined;+ const precedingCaller = callers.findLast((callerIndex) => callerIndex < index);+ const expectedCaller = linkedCaller ?? precedingCaller;+ const callerIndex =+ expectedCaller === undefined+ ? callers.find((callerIndex) => !isAnswered(callerIndex))+ : isAnswered(expectedCaller)+ ? undefined+ : expectedCaller;++ if (callerIndex === undefined) {+ // Duplicate of a result the call already hasremovedInvalidTools++;continue;}- toolMessages.set(message.tool_call_id, message);+ toolMessages.set(resultKey(callerIndex, message.tool_call_id), message);}// 3. Reorder messagesconst reorderedMessages: any[] = [];+ const emittedToolCallIds = new Set<string>();++ // Deterministic, so a request prefix stays byte-stable across steps+ const uniqueToolCallId = (toolCallId: string) => {+ if (!emittedToolCallIds.has(toolCallId)) return toolCallId;++ let occurrence = 2;+ let candidate = `${toolCallId}_${occurrence}`;+ while (callersById.has(candidate) || emittedToolCallIds.has(candidate)) {+ occurrence++;+ candidate = `${toolCallId}_${occurrence}`;+ }++ return candidate;+ };for (const [index, message] of messages.entries()) {if (message.role === 'tool') continue;- if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) {+ const normalizedToolCalls = callsByAssistant.get(index);++ if (!normalizedToolCalls) {reorderedMessages.push(message);continue;}- const seenToolCallIds = new Set<string>();- const normalizedToolCalls = [];+ const requestToolCalls = normalizedToolCalls.map((toolCall) => {+ const id = uniqueToolCallId(toolCall.id);+ emittedToolCallIds.add(id);- for (const toolCall of message.tool_calls) {- if (!toolCall?.id) continue;-- if (seenToolCallIds.has(toolCall.id)) continue;-- seenToolCallIds.add(toolCall.id);- normalizedToolCalls.push(toolCall);- }+ return id === toolCall.id ? toolCall : { ...toolCall, id };+ });reorderedMessages.push(- normalizedToolCalls.length === message.tool_calls.length+ requestToolCalls.length === message.tool_calls.length &&+ requestToolCalls.every((toolCall, i) => toolCall === message.tool_calls[i])? message- : { ...message, tool_calls: normalizedToolCalls },+ : { ...message, tool_calls: requestToolCalls },);// If assistant message with tool_calls, add corresponding tool messages- for (const toolCall of normalizedToolCalls) {- const matchedToolMessage = toolMessages.get(toolCall.id);+ for (const [i, toolCall] of normalizedToolCalls.entries()) {+ const requestToolCallId = requestToolCalls[i].id;+ const matchedToolMessage = toolMessages.get(resultKey(index, toolCall.id));if (matchedToolMessage) {const pluginErrorMessage =@@ -205,8 +264,8 @@ export class ToolMessageReorder extends BaseProcessor {content: hasUsableToolContent(matchedToolMessage.content, pluginErrorMessage)? matchedToolMessage.content: pluginErrorMessage || syntheticToolFailureContent('tool_result_unusable', toolName),+ tool_call_id: requestToolCallId,});- toolMessages.delete(toolCall.id);continue;}@@ -218,7 +277,7 @@ export class ToolMessageReorder extends BaseProcessor {content: syntheticToolFailureContent('tool_result_missing', toolCall.function?.name),...(toolCall.function?.name && { name: toolCall.function.name }),role: 'tool',- tool_call_id: toolCall.id,+ tool_call_id: requestToolCallId,});}}diff --git a/packages/context-engine/src/processors/__tests__/ToolMessageReorder.test.ts b/packages/context-engine/src/processors/__tests__/ToolMessageReorder.test.tsindex 3785c996f59..c2749da003a 100644--- a/packages/context-engine/src/processors/__tests__/ToolMessageReorder.test.ts+++ b/packages/context-engine/src/processors/__tests__/ToolMessageReorder.test.ts@@ -270,6 +270,145 @@ describe('ToolMessageReorder', () => {]);});+ describe('provider-reused tool_call ids across steps', () => {+ // Kimi (via zeabur / nvidia / moonshot) numbers tool calls per response, so+ // every step of a run calls `…runCommand:0`; OpenRouter DeepSeek does the+ // same with `call_0`. Each step's call and result are distinct.+ const RUN_COMMAND = 'lobe-local-system____runCommand';+ const REUSED_ID = `${RUN_COMMAND}:0`;++ const step = (n: number, result?: string) => [+ {+ id: `a${n}`,+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ function: { arguments: `{"command":"echo ${n}"}`, name: RUN_COMMAND },+ id: REUSED_ID,+ type: 'function',+ },+ ],+ },+ ...(result === undefined+ ? []+ : [{ id: `t${n}`, role: 'tool', content: result, tool_call_id: REUSED_ID }]),+ ];++ const toolResults = (messages: any[]) =>+ messages.filter((m) => m.role === 'tool').map((m) => m.content);++ it('should deliver every step its own real result instead of a synthetic tool_result_missing', async () => {+ const proc = new ToolMessageReorder();+ const ctx = createContext([+ { id: 'u1', role: 'user', content: 'run three commands' },+ ...step(1, 'Command completed successfully.\n\nStdout: ok-1'),+ ...step(2, 'Command completed successfully.\n\nStdout: ok-2'),+ ...step(3, 'Command completed successfully.\n\nStdout: ok-3'),+ ]);++ const result = await proc.process(ctx);++ expect(toolResults(result.messages)).toEqual([+ 'Command completed successfully.\n\nStdout: ok-1',+ 'Command completed successfully.\n\nStdout: ok-2',+ 'Command completed successfully.\n\nStdout: ok-3',+ ]);+ expect(result.messages.map((m) => m.id)).toEqual(['u1', 'a1', 't1', 'a2', 't2', 'a3', 't3']);+ expect(result.metadata.toolMessageReorder?.removedInvalidTools).toBe(0);+ });++ it('should give each reused id a unique, stable id in the request so strict providers accept it', async () => {+ const proc = new ToolMessageReorder();+ const ctx = createContext([...step(1, 'ok-1'), ...step(2, 'ok-2'), ...step(3, 'ok-3')]);++ const { messages } = await proc.process(ctx);++ const callIds = messages.filter((m) => m.role === 'assistant').map((m) => m.tool_calls[0].id);+ expect(callIds).toEqual([REUSED_ID, `${REUSED_ID}_2`, `${REUSED_ID}_3`]);+ // Each result follows the call it answers, under the same id.+ expect(messages.filter((m) => m.role === 'tool').map((m) => m.tool_call_id)).toEqual(callIds);+ // The stored rows are not mutated.+ expect(ctx.messages[2].tool_calls[0].id).toBe(REUSED_ID);+ expect(ctx.messages[3].tool_call_id).toBe(REUSED_ID);+ });++ it('should only mark the step whose result is really lost as tool_result_missing', async () => {+ const proc = new ToolMessageReorder();+ const ctx = createContext([...step(1, 'ok-1'), ...step(2), ...step(3, 'ok-3')]);++ const { messages } = await proc.process(ctx);++ expect(toolResults(messages)).toEqual([+ 'ok-1',+ syntheticToolFailureContent('tool_result_missing', RUN_COMMAND),+ 'ok-3',+ ]);+ });++ it('should drop a duplicate result instead of handing it to a later call with the same id', async () => {+ const proc = new ToolMessageReorder();+ const [a1, t1] = step(1, 'ok-1');+ const ctx = createContext([+ a1,+ t1,+ { id: 't1-dup', role: 'tool', content: 'ok-1-dup', tool_call_id: REUSED_ID },+ ...step(2, 'ok-2'),+ ]);++ const result = await proc.process(ctx);++ expect(toolResults(result.messages)).toEqual(['ok-1', 'ok-2']);+ expect(result.metadata.toolMessageReorder?.removedInvalidTools).toBe(1);+ });++ it('should follow parentId when displaced results share a reused id', async () => {+ const proc = new ToolMessageReorder();+ const [a1] = step(1);+ const [a2] = step(2);+ const ctx = createContext([+ a1,+ a2,+ { id: 't1', parentId: 'a1', role: 'tool', content: 'ok-1', tool_call_id: REUSED_ID },+ { id: 't2', parentId: 'a2', role: 'tool', content: 'ok-2', tool_call_id: REUSED_ID },+ ]);++ const result = await proc.process(ctx);++ expect(result.messages.map((m) => m.id)).toEqual(['a1', 't1', 'a2', 't2']);+ expect(toolResults(result.messages)).toEqual(['ok-1', 'ok-2']);+ expect(result.metadata.toolMessageReorder?.removedInvalidTools).toBe(0);+ });++ it('should not append a reused id suffix that collides with a real id', async () => {+ const proc = new ToolMessageReorder();+ const ctx = createContext([+ ...step(1, 'ok-1'),+ {+ id: 'a-real',+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ function: { arguments: '{}', name: RUN_COMMAND },+ id: `${REUSED_ID}_2`,+ type: 'function',+ },+ ],+ },+ { id: 't-real', role: 'tool', content: 'ok-real', tool_call_id: `${REUSED_ID}_2` },+ ...step(2, 'ok-2'),+ ]);++ const { messages } = await proc.process(ctx);++ const callIds = messages.filter((m) => m.role === 'assistant').map((m) => m.tool_calls[0].id);+ expect(new Set(callIds).size).toBe(3);+ expect(toolResults(messages)).toEqual(['ok-1', 'ok-real', 'ok-2']);+ expect(messages.filter((m) => m.role === 'tool').map((m) => m.tool_call_id)).toEqual(callIds);+ });+ });+it('should prefer a real error tool result over a synthetic fallback', async () => {const proc = new ToolMessageReorder();const ctx = createContext([diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.tsindex 185ec3d30e4..ddb94fc20b5 100644--- a/packages/conversation-flow/src/__tests__/parse.test.ts+++ b/packages/conversation-flow/src/__tests__/parse.test.ts@@ -163,6 +163,62 @@ describe('parse', () => {expect((currentGroup as any).children[0].tools[0].result_msg_id).toBe('tool-current-1');});+ it('should give each step its own result when a provider reuses one tool call id across the chain', () => {+ // Kimi via zeabur / nvidia / moonshot numbers tool calls per response, so+ // every step of one run stores `<tool>:0` — without `result_msg_id`.+ const reusedId = 'lobe-local-system____runCommand:0';+ const step = (n: number, parentId: string): Message[] => [+ {+ agentId: 'agent-1',+ content: '',+ createdAt: n * 2 - 1,+ id: `assistant-${n}`,+ parentId,+ role: 'assistant',+ tools: [+ {+ apiName: 'runCommand',+ arguments: `{"command":"echo ${n}"}`,+ id: reusedId,+ identifier: 'lobe-local-system',+ type: 'builtin',+ },+ ],+ updatedAt: n * 2 - 1,+ },+ {+ content: `Stdout: ok-${n}`,+ createdAt: n * 2,+ id: `tool-${n}`,+ parentId: `assistant-${n}`,+ role: 'tool',+ tool_call_id: reusedId,+ updatedAt: n * 2,+ },+ ];++ const result = parse([+ { content: 'run three commands', createdAt: 0, id: 'user-1', role: 'user', updatedAt: 0 },+ ...step(1, 'user-1'),+ ...step(2, 'tool-1'),+ ...step(3, 'tool-2'),+ ]);++ const group = result.flatList.find((message) => message.id === 'assistant-1') as any;++ expect(group?.role).toBe('assistantGroup');+ expect(+ group.children.map((child: any) => ({+ content: child.tools[0].result?.content,+ resultId: child.tools[0].result_msg_id,+ })),+ ).toEqual([+ { content: 'Stdout: ok-1', resultId: 'tool-1' },+ { content: 'Stdout: ok-2', resultId: 'tool-2' },+ { content: 'Stdout: ok-3', resultId: 'tool-3' },+ ]);+ });+it('should keep sibling assistant continuations before later user turns under another tool result', () => {const time = (seconds: number) =>new Date(`2026-01-01T00:00:${String(seconds).padStart(2, '0')}.000Z`).getTime();diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.tsindex b9f38bdbd6b..6ddd074c499 100644--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts@@ -1025,18 +1025,43 @@ export class FlatListBuilder {// Create tool map for lookupconst toolMap = new Map<string, Message>();+ const toolMessagesById = new Map<string, Message>();+ // `${parentId}:${tool_call_id}` → first result that assistant received+ const toolMapByCaller = new Map<string, Message>();allToolMessages.forEach((tm) => {+ toolMessagesById.set(tm.id, tm);if (tm.tool_call_id) {toolMap.set(tm.tool_call_id, tm);++ const callerKey = `${tm.parentId}:${tm.tool_call_id}`;+ if (tm.parentId && !toolMapByCaller.has(callerKey)) toolMapByCaller.set(callerKey, tm);}});+ const chainAssistantIds = new Set(assistantChain.map((assistant) => assistant.id));++ // `tool_call_id` is provider-supplied and not unique across a chain: Kimi+ // (via zeabur / nvidia / moonshot) stores `<tool>:0` on every step. Pair a+ // call with the result its own assistant produced first; the id-only map+ // is a fallback that must never hand one step another step's result.+ const findToolResult = (assistant: Message, toolCallId: string, resultMsgId?: string) => {+ const explicit = resultMsgId ? toolMessagesById.get(resultMsgId) : undefined;+ if (explicit) return explicit;++ const own = toolMapByCaller.get(`${assistant.id}:${toolCallId}`);+ if (own) return own;++ const fallback = toolMap.get(toolCallId);+ if (fallback?.parentId && chainAssistantIds.has(fallback.parentId)) return undefined;++ return fallback;+ };// Process each assistant in the chainfor (const assistant of assistantChain) {// Build toolsWithResults for this assistantconst toolsWithResults: ChatToolPayloadWithResult[] =assistant.tools?.map((tool) => {- const toolMsg = toolMap.get(tool.id);+ const toolMsg = findToolResult(assistant, tool.id, tool.result_msg_id);if (toolMsg) {const result: any = {content: toolMsg.content || '',diff --git a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.tsindex a89f1837381..2654a48f1db 100644--- a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts+++ b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts@@ -11,9 +11,10 @@ vi.mock('node:fs/promises', () => ({const spawnMock = vi.hoisted(() => vi.fn());-vi.mock('node:child_process', () => ({- spawn: spawnMock,-}));+vi.mock('node:child_process', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return { ...actual, spawn: spawnMock };+});class RpcChild extends EventEmitter {stderr = new EventEmitter();