1
import type {2
Api,3
AssistantMessage,4
ImageContent,5
Message,6
Model,7
TextContent,8
ToolCall,9
ToolResultMessage,10
} from "../types.ts";12
const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";13
const NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";14
const ERROR_TOOL_IMAGE_PLACEHOLDER = "(image attached after the tool results)";16
/** An error tool result split into a text-only result and the images to send after the tool results. */17
export interface SplitErrorToolResult {18
/** The result content with each run of images replaced by a note. */19
content: TextContent[];20
/** Text naming the tool call, to send before `images`. */21
caption: string;22
images: ImageContent[];23
}25
/**26
* Split the images out of an error tool result, for APIs that reject images in error results27
* (Anthropic, and Claude on Bedrock). Send the returned content as the tool result and the caption and28
* images after all tool results of the turn, in the same user message. Returns undefined for results29
* that need no split (#10794).30
*/31
export function splitErrorToolResultImages(msg: ToolResultMessage): SplitErrorToolResult | undefined {32
if (!msg.isError) return undefined;33
const images = msg.content.filter((block): block is ImageContent => block.type === "image");34
if (images.length === 0) return undefined;35
return {36
content: replaceImagesWithPlaceholder(msg.content, ERROR_TOOL_IMAGE_PLACEHOLDER),37
caption: `Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,38
images,39
};40
}42
function replaceImagesWithPlaceholder(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {43
const result: TextContent[] = [];44
let previousWasPlaceholder = false;46
for (const block of content) {47
if (block.type === "image") {48
if (!previousWasPlaceholder) {49
result.push({ type: "text", text: placeholder });50
}51
previousWasPlaceholder = true;52
continue;53
}55
result.push(block);56
previousWasPlaceholder = block.text === placeholder;57
}59
return result;60
}62
function downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {63
if (model.input.includes("image")) {64
return messages;65
}67
return messages.map((msg) => {68
if (msg.role === "user" && Array.isArray(msg.content)) {69
return {70
...msg,71
content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER),72
};73
}75
if (msg.role === "toolResult") {76
return {77
...msg,78
content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER),79
};80
}82
return msg;83
});84
}86
/**87
* Normalize tool call ID for cross-provider compatibility.88
* OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.89
* Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).90
*/91
export function transformMessages<TApi extends Api>(92
messages: Message[],93
model: Model<TApi>,94
normalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,95
): Message[] {96
// Build a map of original tool call IDs to normalized IDs97
const toolCallIdMap = new Map<string, string>();98
// Normalize null/undefined content from untyped callers (custom tools, hand-built99
// histories, old session files) so downstream code can rely on the type contract.100
const normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));101
const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);103
// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)104
const transformed = imageAwareMessages.map((msg) => {105
// System and user messages pass through unchanged106
if (msg.role === "system" || msg.role === "user") {107
return msg;108
}110
// Handle toolResult messages - normalize toolCallId if we have a mapping111
if (msg.role === "toolResult") {112
const normalizedId = toolCallIdMap.get(msg.toolCallId);113
if (normalizedId && normalizedId !== msg.toolCallId) {114
return { ...msg, toolCallId: normalizedId };115
}116
return msg;117
}119
// Assistant messages need transformation check120
if (msg.role === "assistant") {121
const assistantMsg = msg as AssistantMessage;122
const isSameModel =123
assistantMsg.provider === model.provider &&124
assistantMsg.api === model.api &&125
assistantMsg.model === model.id;127
const transformedContent = assistantMsg.content.flatMap((block) => {128
if (block.type === "thinking") {129
// Thinking from another model is dropped. Signatures and encrypted reasoning are130
// only valid for the model that produced them, and sending readable thinking as131
// plain text makes the new model treat it as part of the visible reply.132
if (!isSameModel) return [];133
// Keep redacted and signed blocks even if the thinking text is empty134
// (OpenAI encrypted reasoning); they are needed for replay.135
if (block.redacted || block.thinkingSignature) return block;136
if (!block.thinking || block.thinking.trim() === "") return [];137
return block;138
}140
if (block.type === "text") {141
if (isSameModel) return block;142
return {143
type: "text" as const,144
text: block.text,145
};146
}148
if (block.type === "toolCall") {149
const toolCall = block as ToolCall;150
let normalizedToolCall: ToolCall = toolCall;152
if (!isSameModel && toolCall.thoughtSignature) {153
normalizedToolCall = { ...toolCall };154
delete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;155
}157
if (!isSameModel && normalizeToolCallId) {158
const normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);159
if (normalizedId !== toolCall.id) {160
toolCallIdMap.set(toolCall.id, normalizedId);161
normalizedToolCall = { ...normalizedToolCall, id: normalizedId };162
}163
}165
return normalizedToolCall;166
}168
return block;169
});171
return {172
...assistantMsg,173
content: transformedContent,174
};175
}176
return msg;177
});179
// Second pass: insert synthetic empty tool results for orphaned tool calls180
// This preserves thinking signatures and satisfies API requirements181
const result: Message[] = [];182
let pendingToolCalls: ToolCall[] = [];183
let existingToolResultIds = new Set<string>();184
// System messages are transparent to tool-call accounting: one that lands between a tool185
// call and its results is held back and emitted after the results (synthetic ones186
// included), so it never causes a duplicate result for a call that is answered later.187
const heldSystemMessages: Message[] = [];188
const closePendingToolCalls = () => {189
if (pendingToolCalls.length > 0) {190
for (const tc of pendingToolCalls) {191
if (!existingToolResultIds.has(tc.id)) {192
result.push({193
role: "toolResult",194
toolCallId: tc.id,195
toolName: tc.name,196
content: [{ type: "text", text: "No result provided" }],197
isError: true,198
timestamp: Date.now(),199
} as ToolResultMessage);200
}201
}202
pendingToolCalls = [];203
existingToolResultIds = new Set();204
}205
result.push(...heldSystemMessages);206
heldSystemMessages.length = 0;207
};209
for (let i = 0; i < transformed.length; i++) {210
const msg = transformed[i];212
if (msg.role === "assistant") {213
// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now214
closePendingToolCalls();216
// Skip errored/aborted assistant messages entirely.217
// These are incomplete turns that shouldn't be replayed:218
// - May have partial content (reasoning without message, incomplete tool calls)219
// - Replaying them can cause API errors (e.g., OpenAI "reasoning without following item")220
// - The model should retry from the last valid state221
const assistantMsg = msg as AssistantMessage;222
if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {223
continue;224
}226
// Track tool calls from this assistant message227
const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall") as ToolCall[];228
if (toolCalls.length > 0) {229
pendingToolCalls = toolCalls;230
existingToolResultIds = new Set();231
}233
result.push(msg);234
} else if (msg.role === "toolResult") {235
existingToolResultIds.add(msg.toolCallId);236
result.push(msg);237
} else if (msg.role === "system") {238
if (pendingToolCalls.length > 0) {239
heldSystemMessages.push(msg);240
} else {241
result.push(msg);242
}243
} else if (msg.role === "user") {244
// A new user turn interrupts tool flow - insert synthetic results for orphaned calls245
closePendingToolCalls();246
result.push(msg);247
} else {248
result.push(msg);249
}250
}252
// If the conversation ends with unresolved tool calls, synthesize results now.253
closePendingToolCalls();255
return result;256
}