import type { AgentMessage } from "@mariozechner/pi-agent-core"; type ToolCallLike = { id: string; name?: string; }; function extractToolCallsFromAssistant( msg: Extract, ): ToolCallLike[] { const content = msg.content; if (!Array.isArray(content)) return []; const toolCalls: ToolCallLike[] = []; for (const block of content) { if (!block || typeof block !== "object") continue; const rec = block as { type?: unknown; id?: unknown; name?: unknown }; if (typeof rec.id !== "string" || !rec.id) continue; if (rec.type === "toolCall" || rec.type === "toolUse" || rec.type === "functionCall") { toolCalls.push({ id: rec.id, name: typeof rec.name === "string" ? rec.name : undefined, }); } } return toolCalls; } function extractToolResultId(msg: Extract): string | null { const toolCallId = (msg as { toolCallId?: unknown }).toolCallId; if (typeof toolCallId === "string" && toolCallId) return toolCallId; const toolUseId = (msg as { toolUseId?: unknown }).toolUseId; if (typeof toolUseId === "string" && toolUseId) return toolUseId; return null; } function makeMissingToolResult(params: { toolCallId: string; toolName?: string; }): Extract { return { role: "toolResult", toolCallId: params.toolCallId, toolName: params.toolName ?? "unknown", content: [ { type: "text", text: "[openclaw] missing tool result in session history; inserted synthetic error result for transcript repair.", }, ], isError: true, timestamp: Date.now(), } as Extract; } export { makeMissingToolResult }; export function sanitizeToolUseResultPairing(messages: AgentMessage[]): AgentMessage[] { return repairToolUseResultPairing(messages).messages; } export type ToolUseRepairReport = { messages: AgentMessage[]; added: Array>; droppedDuplicateCount: number; droppedOrphanCount: number; moved: boolean; }; export function repairToolUseResultPairing(messages: AgentMessage[]): ToolUseRepairReport { // Anthropic (and Cloud Code Assist) reject transcripts where assistant tool calls are not // immediately followed by matching tool results. Session files can end up with results // displaced (e.g. after user turns) or duplicated. Repair by: // - moving matching toolResult messages directly after their assistant toolCall turn // - inserting synthetic error toolResults for missing ids // - dropping duplicate toolResults for the same id (anywhere in the transcript) // - deduplicating tool_use IDs in assistant messages (Anthropic requires unique IDs) const out: AgentMessage[] = []; const added: Array> = []; const seenToolResultIds = new Set(); const seenToolUseIds = new Set(); let droppedDuplicateCount = 0; let droppedOrphanCount = 0; let moved = false; let changed = false; const pushToolResult = (msg: Extract) => { const id = extractToolResultId(msg); if (id && seenToolResultIds.has(id)) { droppedDuplicateCount += 1; changed = true; return; } if (id) seenToolResultIds.add(id); out.push(msg); }; // Deduplicate tool_use IDs in assistant messages by generating unique IDs for collisions const deduplicateToolUseId = (id: string): string => { if (!seenToolUseIds.has(id)) { seenToolUseIds.add(id); return id; } // Generate a unique ID by appending a counter let counter = 2; let newId = `${id}_${counter}`; while (seenToolUseIds.has(newId)) { counter += 1; newId = `${id}_${counter}`; } seenToolUseIds.add(newId); return newId; }; for (let i = 0; i < messages.length; i += 1) { const msg = messages[i] as AgentMessage; if (!msg || typeof msg !== "object") { out.push(msg); continue; } const role = (msg as { role?: unknown }).role; if (role !== "assistant") { // Tool results must only appear directly after the matching assistant tool call turn. // Any "free-floating" toolResult entries in session history can make strict providers // (Anthropic-compatible APIs, MiniMax, Cloud Code Assist) reject the entire request. if (role !== "toolResult") { out.push(msg); } else { droppedOrphanCount += 1; changed = true; } continue; } const assistant = msg as Extract; const toolCalls = extractToolCallsFromAssistant(assistant); if (toolCalls.length === 0) { out.push(msg); continue; } // Check for duplicate tool_use IDs and remap them if necessary const idRemapping = new Map(); let assistantNeedsRewrite = false; for (const call of toolCalls) { const newId = deduplicateToolUseId(call.id); if (newId !== call.id) { idRemapping.set(call.id, newId); assistantNeedsRewrite = true; changed = true; } } // Rewrite assistant message if any tool_use IDs were deduplicated let processedAssistant = assistant; if (assistantNeedsRewrite && Array.isArray(assistant.content)) { const newContent = assistant.content.map((block) => { if (!block || typeof block !== "object") return block; const rec = block as { type?: unknown; id?: unknown }; if ( (rec.type === "toolCall" || rec.type === "toolUse" || rec.type === "functionCall") && typeof rec.id === "string" && idRemapping.has(rec.id) ) { return { ...(block as unknown as Record), id: idRemapping.get(rec.id) }; } return block; }); processedAssistant = { ...assistant, content: newContent as typeof assistant.content }; } // Update toolCalls with remapped IDs for matching const effectiveToolCalls = toolCalls.map((call) => ({ ...call, id: idRemapping.get(call.id) ?? call.id, originalId: call.id, })); const toolCallIds = new Set(effectiveToolCalls.map((t) => t.originalId)); const spanResultsById = new Map>(); const remainder: AgentMessage[] = []; let j = i + 1; for (; j < messages.length; j += 1) { const next = messages[j] as AgentMessage; if (!next || typeof next !== "object") { remainder.push(next); continue; } const nextRole = (next as { role?: unknown }).role; if (nextRole === "assistant") break; if (nextRole === "toolResult") { const toolResult = next as Extract; const id = extractToolResultId(toolResult); if (id && toolCallIds.has(id)) { if (seenToolResultIds.has(id)) { droppedDuplicateCount += 1; changed = true; continue; } if (!spanResultsById.has(id)) { spanResultsById.set(id, toolResult); } continue; } } // Drop tool results that don't match the current assistant tool calls. if (nextRole !== "toolResult") { remainder.push(next); } else { droppedOrphanCount += 1; changed = true; } } out.push(processedAssistant); if (spanResultsById.size > 0 && remainder.length > 0) { moved = true; changed = true; } for (const call of effectiveToolCalls) { const existing = spanResultsById.get(call.originalId); if (existing) { // Remap toolResult ID if the tool_use ID was deduplicated const remappedId = idRemapping.get(call.originalId); if (remappedId) { const remappedResult = { ...existing, toolCallId: remappedId, } as Extract; pushToolResult(remappedResult); } else { pushToolResult(existing); } } else { const missing = makeMissingToolResult({ toolCallId: call.id, toolName: call.name, }); added.push(missing); changed = true; pushToolResult(missing); } } for (const rem of remainder) { if (!rem || typeof rem !== "object") { out.push(rem); continue; } out.push(rem); } i = j - 1; } const changedOrMoved = changed || moved; return { messages: changedOrMoved ? out : messages, added, droppedDuplicateCount, droppedOrphanCount, moved: changedOrMoved, }; }