|
| 1 | +import type { TranslatorBudget } from "../lib/translator-budget"; |
| 2 | +import { |
| 3 | + customToolItemId, |
| 4 | + restoreRoutedCustomCalls, |
| 5 | + unwrapRoutedCustomToolArguments, |
| 6 | +} from "../responses/custom-tool-compat"; |
| 7 | +import { |
| 8 | + replaceSseDataPayload, |
| 9 | + sseDataPayload, |
| 10 | + type SseBlockRewrite, |
| 11 | +} from "./sse-payload-rewrite"; |
| 12 | + |
| 13 | +const FREEFORM_WRAP_PREFIX = '{"input":"'; |
| 14 | + |
| 15 | +function isPlainObject(value: unknown): value is Record<string, unknown> { |
| 16 | + return !!value && typeof value === "object" && !Array.isArray(value); |
| 17 | +} |
| 18 | + |
| 19 | +function partialCustomToolInput(argumentsText: string): string { |
| 20 | + if (!argumentsText.startsWith(FREEFORM_WRAP_PREFIX)) return argumentsText; |
| 21 | + const body = argumentsText.slice(FREEFORM_WRAP_PREFIX.length); |
| 22 | + let output = ""; |
| 23 | + for (let index = 0; index < body.length; index++) { |
| 24 | + const char = body[index]; |
| 25 | + if (char === '"') break; |
| 26 | + if (char !== "\\") { |
| 27 | + output += char; |
| 28 | + continue; |
| 29 | + } |
| 30 | + const escaped = body[index + 1]; |
| 31 | + if (escaped === undefined) break; |
| 32 | + index += 1; |
| 33 | + if (escaped === "n") output += "\n"; |
| 34 | + else if (escaped === "t") output += "\t"; |
| 35 | + else if (escaped === "r") output += "\r"; |
| 36 | + else if (escaped === "u") { |
| 37 | + const hex = body.slice(index + 1, index + 5); |
| 38 | + if (hex.length !== 4 || !/^[0-9a-fA-F]{4}$/.test(hex)) break; |
| 39 | + output += String.fromCharCode(Number.parseInt(hex, 16)); |
| 40 | + index += 4; |
| 41 | + } else output += escaped; |
| 42 | + } |
| 43 | + return output; |
| 44 | +} |
| 45 | + |
| 46 | +function replaceSseEventName(block: string, type: string): string { |
| 47 | + const newline = block.includes("\r\n") ? "\r\n" : "\n"; |
| 48 | + const lines = block.split(/\r?\n/); |
| 49 | + let replaced = false; |
| 50 | + const next = lines.map(line => { |
| 51 | + if (!replaced && line.startsWith("event:")) { |
| 52 | + replaced = true; |
| 53 | + return `event: ${type}`; |
| 54 | + } |
| 55 | + return line; |
| 56 | + }); |
| 57 | + return next.join(newline); |
| 58 | +} |
| 59 | + |
| 60 | +type OpenCustomCall = { |
| 61 | + argumentsText: string; |
| 62 | + emittedInput: string; |
| 63 | + retainedBytes: number; |
| 64 | +}; |
| 65 | + |
| 66 | +export function createRoutedCustomToolRestoreBlockRewrite( |
| 67 | + names: ReadonlySet<string>, |
| 68 | + budget?: TranslatorBudget, |
| 69 | +): SseBlockRewrite { |
| 70 | + const itemNames = new Map<string, string>(); |
| 71 | + const openCalls = new Map<string, OpenCustomCall>(); |
| 72 | + let disposed = false; |
| 73 | + |
| 74 | + const releaseCall = (itemId: string): void => { |
| 75 | + const open = openCalls.get(itemId); |
| 76 | + if (!open) return; |
| 77 | + if (open.retainedBytes > 0) { |
| 78 | + budget?.releaseRetained(open.retainedBytes, { kind: "retained_collectors" }); |
| 79 | + } |
| 80 | + openCalls.delete(itemId); |
| 81 | + }; |
| 82 | + |
| 83 | + const releaseAll = (): void => { |
| 84 | + if (disposed) return; |
| 85 | + disposed = true; |
| 86 | + for (const itemId of openCalls.keys()) releaseCall(itemId); |
| 87 | + itemNames.clear(); |
| 88 | + }; |
| 89 | + |
| 90 | + const rewrite: SseBlockRewrite = (block: string): readonly string[] => { |
| 91 | + const payload = sseDataPayload(block); |
| 92 | + if (payload === null || payload === "[DONE]") return [block]; |
| 93 | + let parsed: unknown; |
| 94 | + try { |
| 95 | + parsed = JSON.parse(payload); |
| 96 | + } catch { |
| 97 | + return [block]; |
| 98 | + } |
| 99 | + if (!isPlainObject(parsed)) return [block]; |
| 100 | + |
| 101 | + const type = typeof parsed.type === "string" ? parsed.type : ""; |
| 102 | + if ( |
| 103 | + (type === "response.output_item.added" || type === "response.output_item.done") |
| 104 | + && isPlainObject(parsed.item) |
| 105 | + && parsed.item.type === "function_call" |
| 106 | + && typeof parsed.item.name === "string" |
| 107 | + && names.has(parsed.item.name) |
| 108 | + ) { |
| 109 | + const upstreamItemId = typeof parsed.item.id === "string" ? parsed.item.id : undefined; |
| 110 | + if (upstreamItemId) { |
| 111 | + itemNames.set(upstreamItemId, parsed.item.name); |
| 112 | + if (type === "response.output_item.added") { |
| 113 | + openCalls.set(upstreamItemId, { argumentsText: "", emittedInput: "", retainedBytes: 0 }); |
| 114 | + } |
| 115 | + } |
| 116 | + const restored = restoreRoutedCustomCalls(parsed, names); |
| 117 | + if (type === "response.output_item.done" && upstreamItemId) releaseCall(upstreamItemId); |
| 118 | + return restored.changed |
| 119 | + ? [replaceSseDataPayload(block, JSON.stringify(restored.value))] |
| 120 | + : [block]; |
| 121 | + } |
| 122 | + |
| 123 | + const upstreamItemId = typeof parsed.item_id === "string" ? parsed.item_id : undefined; |
| 124 | + if ( |
| 125 | + type === "response.function_call_arguments.delta" |
| 126 | + && upstreamItemId |
| 127 | + && itemNames.has(upstreamItemId) |
| 128 | + ) { |
| 129 | + const open = openCalls.get(upstreamItemId) ?? { argumentsText: "", emittedInput: "", retainedBytes: 0 }; |
| 130 | + const delta = typeof parsed.delta === "string" ? parsed.delta : ""; |
| 131 | + const deltaBytes = Buffer.byteLength(delta, "utf8"); |
| 132 | + if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: "retained_collectors" }); |
| 133 | + open.argumentsText += delta; |
| 134 | + open.retainedBytes += deltaBytes; |
| 135 | + openCalls.set(upstreamItemId, open); |
| 136 | + if (FREEFORM_WRAP_PREFIX.startsWith(open.argumentsText)) return []; |
| 137 | + const fullInput = partialCustomToolInput(open.argumentsText); |
| 138 | + if (!fullInput.startsWith(open.emittedInput) || fullInput.length === open.emittedInput.length) return []; |
| 139 | + const inputDelta = fullInput.slice(open.emittedInput.length); |
| 140 | + open.emittedInput = fullInput; |
| 141 | + const nextType = "response.custom_tool_call_input.delta"; |
| 142 | + const next = { |
| 143 | + ...parsed, |
| 144 | + type: nextType, |
| 145 | + item_id: customToolItemId(upstreamItemId), |
| 146 | + delta: inputDelta, |
| 147 | + }; |
| 148 | + return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))]; |
| 149 | + } |
| 150 | + |
| 151 | + if ( |
| 152 | + type === "response.function_call_arguments.done" |
| 153 | + && upstreamItemId |
| 154 | + && itemNames.has(upstreamItemId) |
| 155 | + ) { |
| 156 | + const nextType = "response.custom_tool_call_input.done"; |
| 157 | + const source = typeof parsed.arguments === "string" |
| 158 | + ? parsed.arguments |
| 159 | + : openCalls.get(upstreamItemId)?.argumentsText ?? ""; |
| 160 | + const { arguments: _arguments, ...rest } = parsed; |
| 161 | + const next = { |
| 162 | + ...rest, |
| 163 | + type: nextType, |
| 164 | + item_id: customToolItemId(upstreamItemId), |
| 165 | + input: unwrapRoutedCustomToolArguments(source), |
| 166 | + }; |
| 167 | + return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))]; |
| 168 | + } |
| 169 | + |
| 170 | + const restored = restoreRoutedCustomCalls(parsed, names); |
| 171 | + const terminal = type === "response.completed" || type === "response.failed" || type === "response.incomplete"; |
| 172 | + if (terminal) releaseAll(); |
| 173 | + return restored.changed |
| 174 | + ? [replaceSseDataPayload(block, JSON.stringify(restored.value))] |
| 175 | + : [block]; |
| 176 | + }; |
| 177 | + rewrite.dispose = releaseAll; |
| 178 | + return rewrite; |
| 179 | +} |
0 commit comments