UNPKG

openai

Version:

The official TypeScript library for the OpenAI API

1,040 lines • 46.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.responseEventRoutingFields = void 0; exports.hasRoutedOutputCallIdentity = hasRoutedOutputCallIdentity; exports.cloneValidatedResponse = cloneValidatedResponse; exports.validateResponseOutputItemIdentity = validateResponseOutputItemIdentity; exports.replaceResponseOutputItem = replaceResponseOutputItem; exports.createResponseContext = createResponseContext; exports.isResponseOutputEvent = isResponseOutputEvent; exports.accumulateWebSocketOutput = accumulateWebSocketOutput; exports.accumulateResponseWithContext = accumulateResponseWithContext; const error_1 = require("../../error.js"); const utils_1 = require("../utils.js"); const values_1 = require("../utils/values.js"); const canonical_output_text_1 = require("./canonical-output-text.js"); const responseOutputIdentityIndexes = new WeakMap(); function validateArrayIndex(collection, index, kind, allowAppend = false) { if (!Array.isArray(collection) || !Number.isSafeInteger(index) || index < 0 || index > collection.length || (index === collection.length ? !allowAppend || index in collection : !(0, utils_1.hasOwn)(collection, index))) { throw new error_1.OpenAIError(`missing ${kind} at index ${index}`); } } function validateArrayAppend(collection, index, kind) { if (index !== collection.length) { throw new error_1.OpenAIError(`missing ${kind} at index ${index}`); } validateArrayIndex(collection, index, kind, true); } function getOutput(snapshot, outputIndex) { validateArrayIndex(snapshot.output, outputIndex, 'output'); const output = snapshot.output[outputIndex]; if (!output) { throw new error_1.OpenAIError(`missing output at index ${outputIndex}`); } return output; } function hasRoutedOutputCallIdentity(output) { return (output.type === 'function_call' || output.type === 'custom_tool_call' || output.type === 'shell_call' || output.type === 'shell_call_output'); } function getOutputItemIdentityKeys(output, eventType) { // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate untrusted streamed item identifiers and discriminators before mutating the response snapshot. if (!(0, utils_1.hasOwn)(output, 'type') || typeof output.type !== 'string') { throw new error_1.OpenAIError(`expected an own output item type for ${eventType}`); } const optionalPlatformID = output.type === 'function_call' || output.type === 'custom_tool_call'; const identities = []; if ((0, utils_1.hasOwn)(output, 'id')) { // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate untrusted streamed item identifiers and discriminators before mutating the response snapshot. if (typeof output.id !== 'string' || (output.id.length === 0 && output.type !== 'computer_call')) { throw new error_1.OpenAIError(`expected a non-empty output item id for ${eventType}`); } identities.push(`id:${output.id}`); } else if (!optionalPlatformID) { throw new error_1.OpenAIError(`expected a non-empty output item id for ${eventType}`); } if (hasRoutedOutputCallIdentity(output)) { if (!(0, utils_1.hasOwn)(output, 'call_id') || // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate untrusted streamed call identifiers before mutating the response snapshot. typeof output.call_id !== 'string' || (output.call_id.length === 0 && output.type !== 'function_call')) { throw new error_1.OpenAIError(`expected a non-empty output item call_id for ${eventType}`); } identities.push(`call:${output.type}:${output.call_id}`); } return identities; } function assertOutputItemIdentitiesAvailable(identities, keys) { for (const key of keys) { if (identities.has(key)) { throw new error_1.OpenAIError(`duplicate output item identity '${key}'`); } } } function addOutputItemIdentities(identities, keys) { assertOutputItemIdentitiesAvailable(identities, keys); for (const key of keys) { identities.add(key); } } function createResponseOutputIdentityIndex(snapshot) { const identityIndex = { snapshot, output: snapshot.output, length: snapshot.output.length, identities: new Set(), }; for (let index = 0; index < snapshot.output.length; index += 1) { const output = getOutput(snapshot, index); addOutputItemIdentities(identityIndex.identities, getOutputItemIdentityKeys(output, 'response snapshot')); } return identityIndex; } function getResponseOutputIdentityIndex(context, snapshot) { const cached = responseOutputIdentityIndexes.get(context); if (cached && cached.snapshot === snapshot && cached.output === snapshot.output && cached.length === snapshot.output.length) { return cached; } const identityIndex = createResponseOutputIdentityIndex(snapshot); responseOutputIdentityIndexes.set(context, identityIndex); return identityIndex; } function cloneValidatedResponse(context, response) { const nextContext = (0, canonical_output_text_1.createCanonicalResponseContext)(); const snapshot = (0, canonical_output_text_1.cloneResponse)(nextContext, response); const identityIndex = createResponseOutputIdentityIndex(snapshot); context.canonicalSnapshot = nextContext.canonicalSnapshot; context.outputTextLengths = nextContext.outputTextLengths; context.outputTextIndex = nextContext.outputTextIndex; responseOutputIdentityIndexes.set(context, identityIndex); return snapshot; } const expectedOutputItemTypes = { 'response.output_text.delta': 'message', 'response.output_text.done': 'message', 'response.output_text.annotation.added': 'message', 'response.refusal.delta': 'message', 'response.refusal.done': 'message', 'response.function_call_arguments.delta': 'function_call', 'response.function_call_arguments.done': 'function_call', 'response.custom_tool_call_input.delta': 'custom_tool_call', 'response.custom_tool_call_input.done': 'custom_tool_call', 'response.mcp_call_arguments.delta': 'mcp_call', 'response.mcp_call_arguments.done': 'mcp_call', 'response.mcp_call.in_progress': 'mcp_call', 'response.mcp_call.completed': 'mcp_call', 'response.mcp_call.failed': 'mcp_call', 'response.shell_call_output_content.delta': 'shell_call_output', 'response.shell_call_output_content.done': 'shell_call_output', 'response.reasoning_text.delta': 'reasoning', 'response.reasoning_text.done': 'reasoning', 'response.reasoning_summary_part.added': 'reasoning', 'response.reasoning_summary_part.done': 'reasoning', 'response.reasoning_summary_text.delta': 'reasoning', 'response.reasoning_summary_text.done': 'reasoning', 'response.code_interpreter_call_code.delta': 'code_interpreter_call', 'response.code_interpreter_call_code.done': 'code_interpreter_call', 'response.code_interpreter_call.in_progress': 'code_interpreter_call', 'response.code_interpreter_call.interpreting': 'code_interpreter_call', 'response.code_interpreter_call.completed': 'code_interpreter_call', 'response.file_search_call.in_progress': 'file_search_call', 'response.file_search_call.searching': 'file_search_call', 'response.file_search_call.completed': 'file_search_call', 'response.web_search_call.in_progress': 'web_search_call', 'response.web_search_call.searching': 'web_search_call', 'response.web_search_call.completed': 'web_search_call', 'response.image_generation_call.in_progress': 'image_generation_call', 'response.image_generation_call.generating': 'image_generation_call', 'response.image_generation_call.completed': 'image_generation_call', 'response.image_generation_call.partial_image': 'image_generation_call', 'response.mcp_list_tools.in_progress': 'mcp_list_tools', 'response.mcp_list_tools.completed': 'mcp_list_tools', 'response.mcp_list_tools.failed': 'mcp_list_tools', 'response.compaction.compacting': 'compaction', }; function getExpectedOutputItemType(event) { if (event.type === 'response.content_part.added' || event.type === 'response.content_part.done') { return event.part.type === 'reasoning_text' ? 'reasoning' : 'message'; } return expectedOutputItemTypes[event.type]; } function validateResponseOutputItemIdentity(output, replacement, eventType) { getOutputItemIdentityKeys(output, eventType); getOutputItemIdentityKeys(replacement, eventType); if (!(0, utils_1.hasOwn)(replacement, 'type') || output.type !== replacement.type) { throw new error_1.OpenAIError(`expected output item type '${output.type}', got '${replacement.type}'`); } const outputID = (0, utils_1.hasOwn)(output, 'id') ? output.id : undefined; const replacementID = (0, utils_1.hasOwn)(replacement, 'id') ? replacement.id : undefined; const addsOptionalID = outputID === undefined && (output.type === 'function_call' || output.type === 'custom_tool_call'); if (outputID !== replacementID && !addsOptionalID) { throw new error_1.OpenAIError(`expected output item id '${outputID}', got '${replacementID}'`); } if (hasRoutedOutputCallIdentity(output) && hasRoutedOutputCallIdentity(replacement) && output.call_id !== replacement.call_id) { throw new error_1.OpenAIError(`expected output item call_id '${output.call_id}', got '${replacement.call_id}'`); } } function validateOutputItemIdentity(event, snapshot, rejectInvalidShellTargets) { if (event.type === 'response.output_item.done') { // Item identity is validated at the shared replacement owner before any update. return; } if (rejectInvalidShellTargets && (event.type === 'response.shell_call_command.added' || event.type === 'response.shell_call_command.delta' || event.type === 'response.shell_call_command.done')) { const output = getOutput(snapshot, event.output_index); if (!(0, utils_1.hasOwn)(output, 'type') || output.type !== 'shell_call') { throw new error_1.OpenAIError(`expected output item type 'shell_call', got '${output.type}'`); } return; } if (event.type !== 'response.content_part.added' && event.type !== 'response.content_part.done' && !(0, utils_1.hasOwn)(expectedOutputItemTypes, event.type)) { return; } // SAFETY: The event type was classified as item-scoped; the following checks validate its own item_id before use. const itemEvent = event; // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate untrusted streamed item identifiers and discriminators before mutating the response snapshot. if (!(0, utils_1.hasOwn)(event, 'item_id') || typeof itemEvent.item_id !== 'string' || itemEvent.item_id.length === 0) { throw new error_1.OpenAIError(`expected a non-empty item_id for ${event.type}`); } const output = getOutput(snapshot, itemEvent.output_index); const outputID = (0, utils_1.hasOwn)(output, 'id') ? output.id : undefined; if (outputID !== itemEvent.item_id) { throw new error_1.OpenAIError(`expected item_id '${outputID}', got '${itemEvent.item_id}'`); } const expectedType = getExpectedOutputItemType(itemEvent); if (output.type !== expectedType) { throw new error_1.OpenAIError(`expected output item type '${expectedType}', got '${output.type}'`); } } function getContent(content, contentIndex) { validateArrayIndex(content, contentIndex, 'content'); const part = content[contentIndex]; if (!part) { throw new error_1.OpenAIError(`missing content at index ${contentIndex}`); } return part; } function getShellOutputContent(snapshot, output, commandIndex) { const shellCall = snapshot.output.find((item) => item.type === 'shell_call' && item.call_id === output.call_id); if (shellCall) { validateArrayIndex(shellCall.action.commands, commandIndex, 'command'); } else { validateArrayIndex(output.output, commandIndex, 'content', true); } while (output.output.length <= commandIndex) { output.output.push({ stdout: '', stderr: '', outcome: { type: 'exit', exit_code: 0 }, }); } return getContent(output.output, commandIndex); } function createSupportedResponseEventTypes(eventTypes) { return new Set(eventTypes); } const supportedResponseEventTypes = createSupportedResponseEventTypes([ 'response.output_item.added', 'response.output_item.done', 'response.content_part.added', 'response.content_part.done', 'response.output_text.delta', 'response.output_text.done', 'response.output_text.annotation.added', 'response.refusal.delta', 'response.refusal.done', 'response.function_call_arguments.delta', 'response.function_call_arguments.done', 'response.custom_tool_call_input.delta', 'response.custom_tool_call_input.done', 'response.mcp_call_arguments.delta', 'response.mcp_call_arguments.done', 'response.shell_call_command.added', 'response.shell_call_command.done', 'response.shell_call_command.delta', 'response.shell_call_output_content.delta', 'response.shell_call_output_content.done', 'response.reasoning_text.delta', 'response.reasoning_text.done', 'response.reasoning_summary_part.added', 'response.reasoning_summary_part.done', 'response.reasoning_summary_text.delta', 'response.reasoning_summary_text.done', 'response.code_interpreter_call_code.delta', 'response.code_interpreter_call_code.done', 'response.code_interpreter_call.in_progress', 'response.code_interpreter_call.interpreting', 'response.code_interpreter_call.completed', 'response.file_search_call.in_progress', 'response.file_search_call.searching', 'response.file_search_call.completed', 'response.web_search_call.in_progress', 'response.web_search_call.searching', 'response.web_search_call.completed', 'response.image_generation_call.in_progress', 'response.image_generation_call.generating', 'response.image_generation_call.completed', 'response.mcp_call.in_progress', 'response.mcp_call.completed', 'response.mcp_call.failed', 'response.created', 'response.queued', 'response.in_progress', 'response.completed', 'response.failed', 'response.incomplete', 'response.audio.delta', 'response.audio.done', 'response.audio.transcript.delta', 'response.audio.transcript.done', 'response.compaction.compacting', 'response.image_generation_call.partial_image', 'response.mcp_list_tools.in_progress', 'response.mcp_list_tools.completed', 'response.mcp_list_tools.failed', 'keepalive', 'error', ]); function assertNever(_value) { throw new error_1.OpenAIError('Unhandled response stream event: unknown'); } exports.responseEventRoutingFields = [ 'item_id', 'output_index', 'content_index', 'annotation_index', 'command_index', 'summary_index', ]; function sanitizeResponseEvent(event) { let descriptor; try { descriptor = Object.getOwnPropertyDescriptor(event, 'type'); } catch { // SAFETY: assertNever always throws; the cast routes invalid runtime events through the existing unsupported-event error path. return assertNever(event); } const type = descriptor?.value; // SAFETY: The string is used only as a Set lookup key; membership performs the supported-event check. if ( // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate untrusted streamed item identifiers and discriminators before mutating the response snapshot. typeof type !== 'string' || !supportedResponseEventTypes.has(type)) { // SAFETY: assertNever always throws; the cast routes invalid runtime events through the existing unsupported-event error path. return assertNever(event); } const stableValues = new Map([['type', type]]); const itemScoped = type === 'response.output_item.added' || type === 'response.output_item.done' || type === 'response.content_part.added' || type === 'response.content_part.done' || type === 'response.shell_call_command.added' || type === 'response.shell_call_command.delta' || type === 'response.shell_call_command.done' || (0, utils_1.hasOwn)(expectedOutputItemTypes, type); if (itemScoped) { try { for (const field of exports.responseEventRoutingFields) { const routingDescriptor = Object.getOwnPropertyDescriptor(event, field); stableValues.set(field, routingDescriptor ? event[field] : undefined); } if (type === 'response.output_item.added' || type === 'response.output_item.done') { stableValues.set('item', structuredClone(event.item)); } else if (type === 'response.content_part.added' || type === 'response.content_part.done') { stableValues.set('part', structuredClone(event.part)); } } catch { // SAFETY: assertNever always throws; the cast routes invalid runtime events through the existing unsupported-event error path. return assertNever(event); } } return new Proxy(event, { get(target, property) { // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy forwarding must preserve arbitrary keys with the original target as accessor receiver. return stableValues.has(property) ? stableValues.get(property) : Reflect.get(target, property, target); }, }); } /** Replace one existing native item, preserving its routing identity and aggregate-text index. */ function replaceResponseOutputItem(context, snapshot, outputIndex, replacement, updateText = true) { const output = getOutput(snapshot, outputIndex); validateResponseOutputItemIdentity(output, replacement, 'response.output_item.done'); if (!(0, utils_1.hasOwn)(output, 'id') && (0, utils_1.hasOwn)(replacement, 'id')) { const { identities } = getResponseOutputIdentityIndex(context, snapshot); addOutputItemIdentities(identities, [`id:${replacement.id}`]); } if (!updateText) { snapshot.output[outputIndex] = replacement; return; } const previousText = (0, canonical_output_text_1.getOutputText)(context, output); if (output.type === 'message' || replacement.type === 'message') { (0, canonical_output_text_1.ensureCanonicalOutputText)(context, snapshot); } snapshot.output[outputIndex] = replacement; const nextText = (0, canonical_output_text_1.getOutputText)(context, replacement); if (context.canonicalSnapshot === snapshot) { context.outputTextIndex.update(outputIndex, nextText.length); } (0, canonical_output_text_1.updateOutputText)(context, snapshot, outputIndex, previousText, nextText); } function accumulateOutputItemEvent(event, snapshot, context) { switch (event.type) { case 'response.output_item.added': { validateArrayAppend(snapshot.output, event.output_index, 'output'); const identityIndex = getResponseOutputIdentityIndex(context, snapshot); const output = event.item; const identities = getOutputItemIdentityKeys(output, event.type); assertOutputItemIdentitiesAvailable(identityIndex.identities, identities); if (output.type === 'message') { (0, canonical_output_text_1.ensureCanonicalOutputText)(context, snapshot); } snapshot.output.push(output); addOutputItemIdentities(identityIndex.identities, identities); identityIndex.length = snapshot.output.length; const text = (0, canonical_output_text_1.getOutputText)(context, output); if (context.canonicalSnapshot === snapshot) { context.outputTextIndex.append(text.length); } if (text) { if (context.deferOutputText) { context.outputTextDirty = true; } else { snapshot.output_text += text; } } return true; } case 'response.output_item.done': { replaceResponseOutputItem(context, snapshot, event.output_index, event.item); return true; } default: { return false; } } } function accumulateContentPartAddedEvent(event, snapshot, context) { switch (event.type) { case 'response.content_part.added': { const output = getOutput(snapshot, event.output_index); const { type } = output; const { part } = event; if (type === 'message' && part.type !== 'reasoning_text') { validateArrayAppend(output.content, event.content_index, 'content'); const content = part; if (content.type === 'output_text') { (0, canonical_output_text_1.ensureCanonicalOutputText)(context, snapshot); } output.content.push(content); if (content.type === 'output_text') { (0, canonical_output_text_1.updateCachedOutputTextLength)(context, output, event.output_index, '', content.text); (0, canonical_output_text_1.updateOutputText)(context, snapshot, event.output_index, '', content.text, event.content_index); } } else if (type === 'reasoning' && part.type === 'reasoning_text') { const content = output.content ?? []; validateArrayAppend(content, event.content_index, 'content'); if (!output.content) { output.content = content; } content.push(part); } return true; } default: { return false; } } } function accumulateContentPartDoneEvent(event, snapshot, context) { switch (event.type) { case 'response.content_part.done': { const output = getOutput(snapshot, event.output_index); const { part } = event; if (output.type === 'message' && part.type !== 'reasoning_text') { const content = getContent(output.content, event.content_index); const previousText = content.type === 'output_text' ? content.text : ''; const replacement = part; if (content.type === 'output_text' || replacement.type === 'output_text') { (0, canonical_output_text_1.ensureCanonicalOutputText)(context, snapshot); } output.content[event.content_index] = replacement; const nextText = replacement.type === 'output_text' ? replacement.text : ''; (0, canonical_output_text_1.updateCachedOutputTextLength)(context, output, event.output_index, previousText, nextText); (0, canonical_output_text_1.updateOutputText)(context, snapshot, event.output_index, previousText, nextText, event.content_index); } else if (output.type === 'reasoning' && part.type === 'reasoning_text') { const { content } = output; if (!content) { throw new error_1.OpenAIError(`missing content at index ${event.content_index}`); } getContent(content, event.content_index); content[event.content_index] = part; } return true; } default: { return false; } } } // Streamed logprobs have a looser type than final output: bytes and even the // top token fields may be missing. Do not fabricate them in typed SSE snapshots. function isLogprobWithBytes(value) { return ((0, values_1.isObj)(value) && typeof value['token'] === 'string' && typeof value['logprob'] === 'number' && Array.isArray(value['bytes']) && // oxlint-disable-next-line anti-slop/no-runtime-typeof -- This boundary checks each byte against the generated final-output contract before exposing a typed SSE snapshot. value['bytes'].every((byte) => typeof byte === 'number')); } function isOutputLogprobs(value) { return (Array.isArray(value) && value.every((entry) => isLogprobWithBytes(entry) && 'top_logprobs' in entry && Array.isArray(entry.top_logprobs) && entry.top_logprobs.every(isLogprobWithBytes))); } function accumulateOutputLogprobs(content, event) { const logprobs = structuredClone(event.logprobs); if (!isOutputLogprobs(logprobs)) { return; } if (event.type === 'response.output_text.done') { if (logprobs.length > 0 || (Array.isArray(content.logprobs) && content.logprobs.length > 0)) { content.logprobs = logprobs; } } else if (logprobs.length > 0) { if (!Array.isArray(content.logprobs)) { content.logprobs = []; } for (const logprob of logprobs) { content.logprobs.push(logprob); } } } function accumulateOutputTextEvent(event, snapshot, context) { switch (event.type) { case 'response.output_text.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'message') { const content = getContent(output.content, event.content_index); if (content.type !== 'output_text') { throw new error_1.OpenAIError(`expected content to be 'output_text', got ${content.type}`); } accumulateOutputLogprobs(content, event); const previousText = content.text; (0, canonical_output_text_1.ensureCanonicalOutputText)(context, snapshot); content.text = previousText + event.delta; (0, canonical_output_text_1.updateCachedOutputTextLength)(context, output, event.output_index, previousText, content.text); if (event.output_index === snapshot.output.length - 1 && event.content_index === output.content.length - 1) { if (context.deferOutputText) { if (event.delta !== '') { context.outputTextDirty = true; } } else { snapshot.output_text += event.delta; } } else { (0, canonical_output_text_1.updateOutputText)(context, snapshot, event.output_index, previousText, content.text, event.content_index); } } return true; } case 'response.output_text.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'message') { const content = getContent(output.content, event.content_index); if (content.type !== 'output_text') { throw new error_1.OpenAIError(`expected content to be 'output_text', got ${content.type}`); } accumulateOutputLogprobs(content, event); const previousText = content.text; (0, canonical_output_text_1.ensureCanonicalOutputText)(context, snapshot); content.text = event.text; (0, canonical_output_text_1.updateCachedOutputTextLength)(context, output, event.output_index, previousText, event.text); (0, canonical_output_text_1.updateOutputText)(context, snapshot, event.output_index, previousText, event.text, event.content_index); } return true; } case 'response.output_text.annotation.added': { const output = getOutput(snapshot, event.output_index); if (output.type === 'message') { const content = getContent(output.content, event.content_index); if (content.type !== 'output_text') { throw new error_1.OpenAIError(`expected content to be 'output_text', got ${content.type}`); } validateArrayIndex(content.annotations, event.annotation_index, 'annotation', true); // SAFETY: The output_text discriminator and annotation index were checked; the annotation is cloned from the corresponding API event contract. content.annotations[event.annotation_index] = structuredClone(event.annotation); } return true; } default: { return false; } } } function accumulateRefusalAndArgumentsEvent(event, snapshot) { switch (event.type) { case 'response.refusal.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'message') { const content = getContent(output.content, event.content_index); if (content.type !== 'refusal') { throw new error_1.OpenAIError(`expected content to be 'refusal', got ${content.type}`); } content.refusal += event.delta; } return true; } case 'response.refusal.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'message') { const content = getContent(output.content, event.content_index); if (content.type !== 'refusal') { throw new error_1.OpenAIError(`expected content to be 'refusal', got ${content.type}`); } content.refusal = event.refusal; } return true; } case 'response.function_call_arguments.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'function_call') { output.arguments += event.delta; } return true; } case 'response.function_call_arguments.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'function_call') { output.arguments = event.arguments; } return true; } case 'response.custom_tool_call_input.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'custom_tool_call') { output.input += event.delta; } return true; } case 'response.custom_tool_call_input.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'custom_tool_call') { output.input = event.input; } return true; } case 'response.mcp_call_arguments.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'mcp_call') { output.arguments += event.delta; } return true; } case 'response.mcp_call_arguments.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'mcp_call') { output.arguments = event.arguments; } return true; } default: { return false; } } } function accumulateShellEvent(event, snapshot) { switch (event.type) { case 'response.shell_call_command.added': case 'response.shell_call_command.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'shell_call') { const allowAppend = event.type === 'response.shell_call_command.added'; validateArrayIndex(output.action.commands, event.command_index, 'command', allowAppend); output.action.commands[event.command_index] = event.command; } return true; } case 'response.shell_call_command.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'shell_call') { validateArrayIndex(output.action.commands, event.command_index, 'command'); output.action.commands[event.command_index] += event.delta; } return true; } case 'response.shell_call_output_content.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'shell_call_output') { const content = getShellOutputContent(snapshot, output, event.command_index); content.stdout += event.delta.stdout ?? ''; content.stderr += event.delta.stderr ?? ''; } return true; } case 'response.shell_call_output_content.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'shell_call_output') { const content = getContent(event.output, 0); getShellOutputContent(snapshot, output, event.command_index); output.output[event.command_index] = structuredClone(content); } return true; } default: { return false; } } } function accumulateReasoningEvent(event, snapshot) { switch (event.type) { case 'response.reasoning_text.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'reasoning') { if (!output.content) { throw new error_1.OpenAIError(`missing content at index ${event.content_index}`); } const content = getContent(output.content, event.content_index); if (content.type !== 'reasoning_text') { throw new error_1.OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); } content.text += event.delta; } return true; } case 'response.reasoning_text.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'reasoning') { if (!output.content) { throw new error_1.OpenAIError(`missing content at index ${event.content_index}`); } const content = getContent(output.content, event.content_index); if (content.type !== 'reasoning_text') { throw new error_1.OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); } content.text = event.text; } return true; } case 'response.reasoning_summary_part.added': { const output = getOutput(snapshot, event.output_index); if (output.type === 'reasoning') { validateArrayAppend(output.summary, event.summary_index, 'content'); output.summary.push(structuredClone(event.part)); } return true; } case 'response.reasoning_summary_part.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'reasoning') { getContent(output.summary, event.summary_index); output.summary[event.summary_index] = structuredClone(event.part); } return true; } case 'response.reasoning_summary_text.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'reasoning') { const part = getContent(output.summary, event.summary_index); part.text += event.delta; } return true; } case 'response.reasoning_summary_text.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'reasoning') { const part = getContent(output.summary, event.summary_index); part.text = event.text; } return true; } default: { return false; } } } function accumulateCodeInterpreterEvent(event, snapshot) { switch (event.type) { case 'response.code_interpreter_call_code.delta': { const output = getOutput(snapshot, event.output_index); if (output.type === 'code_interpreter_call') { output.code = (output.code ?? '') + event.delta; } return true; } case 'response.code_interpreter_call_code.done': { const output = getOutput(snapshot, event.output_index); if (output.type === 'code_interpreter_call') { output.code = event.code; } return true; } case 'response.code_interpreter_call.in_progress': { const output = getOutput(snapshot, event.output_index); if (output.type === 'code_interpreter_call') { output.status = 'in_progress'; } return true; } case 'response.code_interpreter_call.interpreting': { const output = getOutput(snapshot, event.output_index); if (output.type === 'code_interpreter_call') { output.status = 'interpreting'; } return true; } case 'response.code_interpreter_call.completed': { const output = getOutput(snapshot, event.output_index); if (output.type === 'code_interpreter_call') { output.status = 'completed'; } return true; } default: { return false; } } } function accumulateSearchStatusEvent(event, snapshot) { switch (event.type) { case 'response.file_search_call.in_progress': { const output = getOutput(snapshot, event.output_index); if (output.type === 'file_search_call') { output.status = 'in_progress'; } return true; } case 'response.file_search_call.searching': { const output = getOutput(snapshot, event.output_index); if (output.type === 'file_search_call') { output.status = 'searching'; } return true; } case 'response.file_search_call.completed': { const output = getOutput(snapshot, event.output_index); if (output.type === 'file_search_call') { output.status = 'completed'; } return true; } case 'response.web_search_call.in_progress': { const output = getOutput(snapshot, event.output_index); if (output.type === 'web_search_call') { output.status = 'in_progress'; } return true; } case 'response.web_search_call.searching': { const output = getOutput(snapshot, event.output_index); if (output.type === 'web_search_call') { output.status = 'searching'; } return true; } case 'response.web_search_call.completed': { const output = getOutput(snapshot, event.output_index); if (output.type === 'web_search_call') { output.status = 'completed'; } return true; } default: { return false; } } } function accumulateImageAndMcpStatusEvent(event, snapshot) { switch (event.type) { case 'response.image_generation_call.in_progress': { const output = getOutput(snapshot, event.output_index); if (output.type === 'image_generation_call') { output.status = 'in_progress'; } return true; } case 'response.image_generation_call.generating': { const output = getOutput(snapshot, event.output_index); if (output.type === 'image_generation_call') { output.status = 'generating'; } return true; } case 'response.image_generation_call.completed': { const output = getOutput(snapshot, event.output_index); if (output.type === 'image_generation_call') { output.status = 'completed'; } return true; } case 'response.mcp_call.in_progress': { const output = getOutput(snapshot, event.output_index); if (output.type === 'mcp_call') { output.status = 'in_progress'; } return true; } case 'response.mcp_call.completed': { const output = getOutput(snapshot, event.output_index); if (output.type === 'mcp_call') { output.status = 'completed'; } return true; } case 'response.mcp_call.failed': { const output = getOutput(snapshot, event.output_index); if (output.type === 'mcp_call') { output.status = 'failed'; } return true; } default: { return false; } } } function isResponseLifecycleEvent(event) { switch (event.type) { case 'response.created': case 'response.queued': case 'response.in_progress': case 'response.completed': case 'response.failed': case 'response.incomplete': { return true; } default: { return false; } } } function isIgnoredResponseEvent(event) { switch (event.type) { case 'response.audio.delta': case 'response.audio.done': case 'response.audio.transcript.delta': case 'response.audio.transcript.done': case 'response.compaction.compacting': case 'response.image_generation_call.partial_image': case 'response.mcp_list_tools.in_progress': case 'response.mcp_list_tools.completed': case 'response.mcp_list_tools.failed': case 'keepalive': case 'error': { return true; } default: { return false; } } } function createResponseContext() { return (0, canonical_output_text_1.createCanonicalResponseContext)(); } function accumulateResponseOutput(dispatchEvent, snapshot, context, rejectInvalidShellTargets) { validateOutputItemIdentity(dispatchEvent, snapshot, rejectInvalidShellTargets); if (accumulateOutputItemEvent(dispatchEvent, snapshot, context)) { return true; } if (accumulateContentPartAddedEvent(dispatchEvent, snapshot, context)) { return true; } if (accumulateContentPartDoneEvent(dispatchEvent, snapshot, context)) { return true; } if (accumulateOutputTextEvent(dispatchEvent, snapshot, context)) { return true; } if (accumulateRefusalAndArgumentsEvent(dispatchEvent, snapshot)) { return true; } if (accumulateShellEvent(dispatchEvent, snapshot)) { return true; } if (accumulateReasoningEvent(dispatchEvent, snapshot)) { return true; } if (accumulateCodeInterpreterEvent(dispatchEvent, snapshot)) { return true; } if (accumulateSearchStatusEvent(dispatchEvent, snapshot)) { return true; } if (accumulateImageAndMcpStatusEvent(dispatchEvent, snapshot)) { return true; } if (isIgnoredResponseEvent(dispatchEvent)) { return true; } return false; } /** Matches shared events that can change output. Validation still occurs before mutation. */ function isResponseOutputEvent(event) { // SAFETY: Membership of the existing SSE tag set is checked before using shared output validators. return (supportedResponseEventTypes.has(event.type) && !isResponseLifecycleEvent(event) && !isIgnoredResponseEvent(event)); } /** Applies the same strict output validation and mutations without requiring response metadata. */ function accumulateWebSocketOutput(event, snapshot, context) { const dispatchEvent = sanitizeResponseEvent(event); if (!accumulateResponseOutput(dispatchEvent, snapshot, context, true)) { throw new error_1.OpenAIError('Unsupported WebSocket output event'); } } function accumulateResponseWithContext(event, snapshot, context, rejectInvalidShellTargets = false, prepareSanitizedEvent) { let dispatchEvent = sanitizeResponseEvent(event); if (prepareSanitizedEvent && dispatchEvent.type !== 'keepalive') { const prepared = prepareSanitizedEvent(dispatchEvent); if (prepared === null) { if (!snapshot) { throw new error_1.OpenAIError('Cannot ignore a response event before response.created.'); } return snapshot; } dispatchEvent = prepared; } if (!snapshot) { if (dispatchEvent.type !== 'response.created') { throw new error_1.OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${dispatchEvent.type}`); } return cloneValidatedResponse(context, dispatchEvent.response); } if (accumulateResponseOutput(dispatchEvent, snapshot, context, rejectInvalidShellTargets)) { return snapshot; } if (isResponseLifecycleEvent(dispatchEvent)) { return cloneValidatedResponse(context, dispatchEvent.response); } return assertNever(dispatchEvent); } //# sourceMappingURL=response-accumulator.js.map