|
| 1 | +import { randomUUID } from "node:crypto"; |
| 2 | +import { isRecord } from "@openclaw/normalization-core/record-coerce"; |
| 3 | +import type { ChatCompletionChunk } from "openai/resources/chat/completions.js"; |
| 4 | + |
| 5 | +type ChatCompletionToolCallDelta = ChatCompletionChunk.Choice.Delta.ToolCall; |
| 6 | +const MAX_BUFFERED_LEGACY_TOOL_CALL_ARGUMENT_BYTES = 256_000; |
| 7 | +const MAX_BUFFERED_LEGACY_FOLLOWING_DELTA_BYTES = 256_000; |
| 8 | +const MAX_BUFFERED_LEGACY_FOLLOWING_DELTAS = 1_024; |
| 9 | + |
| 10 | +type NormalizedOpenAICompletionsDelta = { |
| 11 | + delta: ChatCompletionChunk.Choice.Delta; |
| 12 | + toolCalls: ChatCompletionToolCallDelta[]; |
| 13 | +}; |
| 14 | + |
| 15 | +type OpenAICompletionsToolCallFinalizationOptions<TBlock extends object> = { |
| 16 | + allowSilentToolCallPromotion?: boolean; |
| 17 | + onConfirmedToolCall?: (block: TBlock, contentIndex: number) => void; |
| 18 | +}; |
| 19 | + |
| 20 | +/** Normalize the SDK's legacy single-function lane into its modern tool-call shape. */ |
| 21 | +export function createOpenAICompletionsToolCallDeltaNormalizer(): ( |
| 22 | + delta: ChatCompletionChunk.Choice.Delta, |
| 23 | + finishReason: ChatCompletionChunk.Choice["finish_reason"], |
| 24 | +) => NormalizedOpenAICompletionsDelta[] { |
| 25 | + let sawModernToolCall = false; |
| 26 | + let pendingLegacyArgumentBytes = 0; |
| 27 | + let pendingFollowingDeltaBytes = 0; |
| 28 | + let pendingLegacyToolCall: ChatCompletionToolCallDelta | undefined; |
| 29 | + const pendingFollowingDeltas: ChatCompletionChunk.Choice.Delta[] = []; |
| 30 | + |
| 31 | + const takePendingFollowingDeltas = (): NormalizedOpenAICompletionsDelta[] => { |
| 32 | + pendingFollowingDeltaBytes = 0; |
| 33 | + return pendingFollowingDeltas.splice(0).map((delta) => ({ delta, toolCalls: [] })); |
| 34 | + }; |
| 35 | + |
| 36 | + const bufferFollowingDelta = (delta: ChatCompletionChunk.Choice.Delta): void => { |
| 37 | + const nextDeltaBytes = Buffer.byteLength(JSON.stringify(delta), "utf8"); |
| 38 | + if ( |
| 39 | + pendingFollowingDeltaBytes + nextDeltaBytes > MAX_BUFFERED_LEGACY_FOLLOWING_DELTA_BYTES || |
| 40 | + pendingFollowingDeltas.length >= MAX_BUFFERED_LEGACY_FOLLOWING_DELTAS |
| 41 | + ) { |
| 42 | + throw new Error("Exceeded legacy tool-call content buffer limit"); |
| 43 | + } |
| 44 | + pendingFollowingDeltaBytes += nextDeltaBytes; |
| 45 | + pendingFollowingDeltas.push(delta); |
| 46 | + }; |
| 47 | + |
| 48 | + const withoutToolCalls = ( |
| 49 | + delta: ChatCompletionChunk.Choice.Delta, |
| 50 | + ): ChatCompletionChunk.Choice.Delta => { |
| 51 | + const ordinaryDelta = { ...delta }; |
| 52 | + delete ordinaryDelta.function_call; |
| 53 | + delete ordinaryDelta.tool_calls; |
| 54 | + return ordinaryDelta; |
| 55 | + }; |
| 56 | + |
| 57 | + const hasObservableContent = (value: unknown): boolean => { |
| 58 | + if (typeof value === "string") { |
| 59 | + return value.length > 0; |
| 60 | + } |
| 61 | + if (Array.isArray(value)) { |
| 62 | + return value.some(hasObservableContent); |
| 63 | + } |
| 64 | + if (isRecord(value)) { |
| 65 | + return Object.entries(value).some( |
| 66 | + ([field, nestedValue]) => |
| 67 | + field !== "type" && |
| 68 | + field !== "id" && |
| 69 | + field !== "index" && |
| 70 | + hasObservableContent(nestedValue), |
| 71 | + ); |
| 72 | + } |
| 73 | + return false; |
| 74 | + }; |
| 75 | + |
| 76 | + const hasOrdinaryContent = (delta: ChatCompletionChunk.Choice.Delta): boolean => |
| 77 | + Object.entries(delta).some(([field, value]) => field !== "role" && hasObservableContent(value)); |
| 78 | + |
| 79 | + return (delta, finishReason) => { |
| 80 | + const ordinaryDelta = withoutToolCalls(delta); |
| 81 | + if (delta.tool_calls && delta.tool_calls.length > 0) { |
| 82 | + const precedingDeltas = takePendingFollowingDeltas(); |
| 83 | + sawModernToolCall = true; |
| 84 | + pendingLegacyArgumentBytes = 0; |
| 85 | + pendingLegacyToolCall = undefined; |
| 86 | + return [...precedingDeltas, { delta: ordinaryDelta, toolCalls: delta.tool_calls }]; |
| 87 | + } |
| 88 | + |
| 89 | + const functionCall = delta.function_call; |
| 90 | + if (sawModernToolCall) { |
| 91 | + return [{ delta: ordinaryDelta, toolCalls: [] }]; |
| 92 | + } |
| 93 | + |
| 94 | + const hadPendingLegacyCall = pendingLegacyToolCall !== undefined; |
| 95 | + const leadingDeltas: NormalizedOpenAICompletionsDelta[] = []; |
| 96 | + if (hasOrdinaryContent(ordinaryDelta)) { |
| 97 | + if (hadPendingLegacyCall) { |
| 98 | + // Keep every lane behind its provisional call; publishing text early |
| 99 | + // permanently reverses the assistant's original tool/content order. |
| 100 | + bufferFollowingDelta(ordinaryDelta); |
| 101 | + } else { |
| 102 | + leadingDeltas.push({ delta: ordinaryDelta, toolCalls: [] }); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + if (functionCall && (functionCall.name || functionCall.arguments)) { |
| 107 | + // Legacy events are provisional until their terminal reason confirms no |
| 108 | + // modern call superseded them. Coalesce fragments so hostile empty/name |
| 109 | + // frames cannot create an unbounded queue or quadratic terminal parsing. |
| 110 | + const nextFunctionName = pendingLegacyToolCall?.function?.name |
| 111 | + ? undefined |
| 112 | + : functionCall.name; |
| 113 | + const nextArgumentBytes = |
| 114 | + Buffer.byteLength(functionCall.arguments ?? "", "utf8") + |
| 115 | + Buffer.byteLength(nextFunctionName ?? "", "utf8"); |
| 116 | + if ( |
| 117 | + pendingLegacyArgumentBytes + nextArgumentBytes > |
| 118 | + MAX_BUFFERED_LEGACY_TOOL_CALL_ARGUMENT_BYTES |
| 119 | + ) { |
| 120 | + throw new Error("Exceeded tool-call argument buffer limit"); |
| 121 | + } |
| 122 | + pendingLegacyArgumentBytes += nextArgumentBytes; |
| 123 | + pendingLegacyToolCall ??= { |
| 124 | + index: 0, |
| 125 | + id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}`, |
| 126 | + type: "function", |
| 127 | + function: {}, |
| 128 | + }; |
| 129 | + const pendingFunction = (pendingLegacyToolCall.function ??= {}); |
| 130 | + if (nextFunctionName) { |
| 131 | + pendingFunction.name = nextFunctionName; |
| 132 | + } |
| 133 | + if (functionCall.arguments) { |
| 134 | + pendingFunction.arguments = (pendingFunction.arguments ?? "") + functionCall.arguments; |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + if (!pendingLegacyToolCall) { |
| 139 | + return leadingDeltas.length > 0 ? leadingDeltas : [{ delta: ordinaryDelta, toolCalls: [] }]; |
| 140 | + } |
| 141 | + |
| 142 | + if (finishReason === "function_call") { |
| 143 | + const confirmedLegacyToolCall = pendingLegacyToolCall; |
| 144 | + pendingLegacyToolCall = undefined; |
| 145 | + pendingLegacyArgumentBytes = 0; |
| 146 | + return [ |
| 147 | + ...leadingDeltas, |
| 148 | + { delta: {}, toolCalls: [confirmedLegacyToolCall] }, |
| 149 | + ...takePendingFollowingDeltas(), |
| 150 | + ]; |
| 151 | + } |
| 152 | + |
| 153 | + if (finishReason) { |
| 154 | + pendingLegacyArgumentBytes = 0; |
| 155 | + pendingLegacyToolCall = undefined; |
| 156 | + return [...leadingDeltas, ...takePendingFollowingDeltas()]; |
| 157 | + } |
| 158 | + |
| 159 | + return leadingDeltas; |
| 160 | + }; |
| 161 | +} |
| 162 | + |
| 163 | +/** Publish only executable calls; streaming scratch state never belongs in replay. */ |
| 164 | +export function finalizeOpenAICompletionsToolCalls<TBlock extends object>( |
| 165 | + output: { content: TBlock[]; stopReason: string; errorMessage?: string }, |
| 166 | + options: OpenAICompletionsToolCallFinalizationOptions<TBlock> = {}, |
| 167 | +): void { |
| 168 | + const isToolCall = (block: TBlock) => (block as { type?: unknown }).type === "toolCall"; |
| 169 | + const hasToolCalls = output.content.some(isToolCall); |
| 170 | + |
| 171 | + if (output.stopReason === "toolUse" && !hasToolCalls) { |
| 172 | + output.stopReason = "stop"; |
| 173 | + } |
| 174 | + |
| 175 | + if ( |
| 176 | + output.stopReason === "stop" && |
| 177 | + hasToolCalls && |
| 178 | + options.allowSilentToolCallPromotion !== false && |
| 179 | + !output.content.some((block) => { |
| 180 | + const candidate = block as { type?: unknown; text?: unknown }; |
| 181 | + return ( |
| 182 | + candidate.type === "text" && |
| 183 | + typeof candidate.text === "string" && |
| 184 | + candidate.text.trim().length > 0 |
| 185 | + ); |
| 186 | + }) |
| 187 | + ) { |
| 188 | + output.stopReason = "toolUse"; |
| 189 | + } |
| 190 | + |
| 191 | + if (output.stopReason !== "toolUse") { |
| 192 | + if (hasToolCalls) { |
| 193 | + output.content = output.content.filter((block) => !isToolCall(block)); |
| 194 | + } |
| 195 | + return; |
| 196 | + } |
| 197 | + |
| 198 | + for (const block of output.content) { |
| 199 | + if (!isToolCall(block)) { |
| 200 | + continue; |
| 201 | + } |
| 202 | + const toolCall = block as { name?: unknown; arguments?: unknown; partialArgs?: unknown }; |
| 203 | + let completeArguments: unknown; |
| 204 | + try { |
| 205 | + completeArguments = |
| 206 | + typeof toolCall.partialArgs === "string" && toolCall.partialArgs.trim().length > 0 |
| 207 | + ? (JSON.parse(toolCall.partialArgs) as unknown) |
| 208 | + : undefined; |
| 209 | + } catch { |
| 210 | + completeArguments = undefined; |
| 211 | + } |
| 212 | + if ( |
| 213 | + typeof toolCall.name !== "string" || |
| 214 | + toolCall.name.trim().length === 0 || |
| 215 | + !isRecord(completeArguments) |
| 216 | + ) { |
| 217 | + output.stopReason = "error"; |
| 218 | + output.errorMessage = "Provider returned an incomplete or malformed tool call"; |
| 219 | + output.content = output.content.filter((candidate) => !isToolCall(candidate)); |
| 220 | + return; |
| 221 | + } |
| 222 | + toolCall.arguments = completeArguments; |
| 223 | + } |
| 224 | + |
| 225 | + for (let contentIndex = 0; contentIndex < output.content.length; contentIndex += 1) { |
| 226 | + const block = output.content[contentIndex]; |
| 227 | + if (!block || !isToolCall(block)) { |
| 228 | + continue; |
| 229 | + } |
| 230 | + delete (block as { partialArgs?: string }).partialArgs; |
| 231 | + delete (block as { streamIndex?: number }).streamIndex; |
| 232 | + options.onConfirmedToolCall?.(block, contentIndex); |
| 233 | + } |
| 234 | +} |
0 commit comments