@tanstack/openai-base 0.10.16 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/adapters/chat-completions-text.d.ts +4 -2
- package/dist/esm/adapters/chat-completions-text.js +29 -4
- package/dist/esm/adapters/chat-completions-text.js.map +1 -1
- package/dist/esm/adapters/responses-text.d.ts +18 -6
- package/dist/esm/adapters/responses-text.js +261 -16
- package/dist/esm/adapters/responses-text.js.map +1 -1
- package/dist/esm/adapters/responses-user-tools.d.ts +42 -0
- package/dist/esm/adapters/responses-user-tools.js +241 -0
- package/dist/esm/adapters/responses-user-tools.js.map +1 -0
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/usage.d.ts +2 -2
- package/dist/esm/usage.js +5 -3
- package/dist/esm/usage.js.map +1 -1
- package/dist/esm/utils/schema-converter.d.ts +22 -0
- package/dist/esm/utils/schema-converter.js +41 -8
- package/dist/esm/utils/schema-converter.js.map +1 -1
- package/package.json +4 -3
- package/src/adapters/chat-completions-text.ts +74 -5
- package/src/adapters/responses-text.ts +468 -37
- package/src/adapters/responses-user-tools.ts +355 -0
- package/src/index.ts +2 -0
- package/src/usage.ts +16 -5
- package/src/utils/schema-converter.ts +72 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses-text.js","names":[],"sources":["../../../src/adapters/responses-text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport {\n toRunErrorPayload,\n toRunErrorRawEvent,\n} from '@tanstack/ai/adapter-internals'\nimport { generateId } from '@tanstack/ai-utils'\nimport { extractRequestOptions } from '../utils/request-options'\nimport { makeStructuredOutputCompatibleWithMap } from '../utils/schema-converter'\nimport { createToolInputNormalizer } from '../utils/tool-input-normalizer'\nimport type { StructuredOutputCompatibility } from '../utils/schema-converter'\nimport { buildResponsesUsage } from '../usage'\nimport { convertToolsToResponsesFormat } from './responses-tool-converter'\nimport type OpenAI from 'openai'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type {\n Response,\n ResponseCreateParams,\n ResponseFunctionCallOutputItem,\n ResponseInput,\n ResponseInputContent,\n ResponseStreamEvent,\n} from 'openai/resources/responses/responses'\nimport type {\n ContentPart,\n DefaultMessageMetadataByModality,\n Modality,\n ModelMessage,\n AdapterYieldChunk,\n TextOptions,\n} from '@tanstack/ai'\n\n// Base64 encoding of the '%PDF' file header — every PDF payload starts with\n// these bytes, so inline document data must begin with this prefix.\nconst PDF_BASE64_MAGIC = 'JVBERi'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction packResponsesReasoningSignature(\n id: string | undefined,\n encryptedContent: string | undefined,\n): string | undefined {\n if (!id && !encryptedContent) return undefined\n return JSON.stringify({\n ...(id ? { id } : {}),\n ...(encryptedContent ? { encrypted_content: encryptedContent } : {}),\n })\n}\n\nfunction unpackResponsesReasoningSignature(\n signature: string,\n): { id?: string; encrypted_content?: string } | undefined {\n try {\n const parsed: unknown = JSON.parse(signature)\n if (!isRecord(parsed)) return undefined\n const id = typeof parsed.id === 'string' ? parsed.id : undefined\n const encrypted_content =\n typeof parsed.encrypted_content === 'string'\n ? parsed.encrypted_content\n : undefined\n if (!id && !encrypted_content) return undefined\n return {\n ...(id ? { id } : {}),\n ...(encrypted_content ? { encrypted_content } : {}),\n }\n } catch {\n return undefined\n }\n}\n\nfunction readReasoningItem(\n item: unknown,\n): { id?: string; encrypted_content?: string } | undefined {\n if (!isRecord(item) || item.type !== 'reasoning') return undefined\n const id = typeof item.id === 'string' ? item.id : undefined\n const encrypted_content =\n typeof item.encrypted_content === 'string'\n ? item.encrypted_content\n : undefined\n if (!id && !encrypted_content) return undefined\n return {\n ...(id ? { id } : {}),\n ...(encrypted_content ? { encrypted_content } : {}),\n }\n}\n\n/**\n * Provider-specific metadata that preserves the Responses API output item ID.\n *\n * Responses function calls have two identifiers: `call_id` correlates the\n * function output with the call, while `id` identifies the output item itself.\n * TanStack AI uses `call_id` as the canonical tool-call ID and carries the\n * item ID here so stateless follow-up requests can replay both values.\n */\nexport interface OpenAIResponsesToolCallMetadata {\n itemId: string\n}\n\ninterface StreamedFunctionCallMetadata {\n callId: string\n index: number\n name: string\n started: boolean\n ended?: boolean\n pendingArguments?: string | undefined\n}\n\n/**\n * The pre-2025-07 spec name for `response.reasoning_text.delta`. Removed from\n * the openai SDK, but OpenAI-compatible providers frozen on the older spec\n * (e.g. Amazon Bedrock's Mantle endpoint serving Gemma) still emit it.\n */\ninterface LegacyReasoningDeltaEvent {\n type: 'response.reasoning.delta'\n delta?: unknown\n}\n\n/**\n * Shared implementation of the OpenAI Responses API. Holds the stream-event\n * accumulator + AG-UI lifecycle and calls the OpenAI SDK directly. Subclasses\n * (today: ai-openai) construct an OpenAI client with their provider-specific\n * `baseURL` / headers and pass it in.\n */\nexport abstract class OpenAIBaseResponsesTextAdapter<\n TModel extends string,\n TProviderOptions extends Record<string, unknown> = Record<string, unknown>,\n TInputModalities extends ReadonlyArray<Modality> = ReadonlyArray<Modality>,\n TMessageMetadata extends DefaultMessageMetadataByModality =\n DefaultMessageMetadataByModality,\n TToolCapabilities extends ReadonlyArray<string> = ReadonlyArray<string>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n TMessageMetadata,\n TToolCapabilities,\n OpenAIResponsesToolCallMetadata\n> {\n override readonly kind = 'text' as const\n readonly name: string\n protected client: OpenAI\n\n constructor(model: TModel, name: string, client: OpenAI) {\n super({}, model)\n this.name = name\n this.client = client\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n // Key streamed state by output item ID because argument deltas reference\n // `item_id`. The state separately retains `call_id`, which is the public\n // tool-call ID and the correlation key for function_call_output.\n const toolCallMetadata = new Map<string, StreamedFunctionCallMetadata>()\n\n // AG-UI lifecycle tracking. Honor a caller-supplied `runId` (as `threadId`\n // already does) so the emitted RUN_STARTED matches the id the caller keys\n // durability by — e.g. a summarize run threading the client's runId through\n // for mid-run reload resumability. Falls back to a generated id.\n const aguiState = {\n runId: options.runId ?? generateId(this.name),\n threadId: options.threadId ?? generateId(this.name),\n messageId: generateId(this.name),\n hasEmittedRunStarted: false,\n }\n\n try {\n // mapOptionsToRequest can throw on caller-side validation failures\n // (empty user content, unsupported parts, webSearchTool() rejection in\n // the OpenRouter override). Keep it inside the try so those failures\n // surface as RUN_ERROR events instead of iterator throws.\n const requestParams = this.mapOptionsToRequest(options)\n options.logger.request(\n `activity=chat provider=${this.name} model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n { provider: this.name, model: this.model },\n )\n const response = await this.client.responses.create(\n {\n ...requestParams,\n stream: true,\n },\n extractRequestOptions(options.request),\n )\n\n yield* this.processStreamChunks(\n response,\n toolCallMetadata,\n options,\n aguiState,\n )\n } catch (error: unknown) {\n // Narrow before logging: raw SDK errors can carry request metadata\n // (including auth headers) which we must never surface to user loggers.\n const errorPayload = toRunErrorPayload(\n error,\n `${this.name}.chatStream failed`,\n )\n const rawEvent = toRunErrorRawEvent(error)\n\n // Emit RUN_STARTED if not yet emitted\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: options.model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n // Emit AG-UI RUN_ERROR. Conditional `code` spread keeps the wire\n // shape spec-compliant under `exactOptionalPropertyTypes`: AG-UI's\n // `RunErrorEvent.code` is `string?` (absent vs explicit `undefined`\n // matter), so we omit the key when there's no code.\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: errorPayload.message,\n code: errorPayload.code,\n // Forward the provider's structured error body when present (see\n // toRunErrorRawEvent); omitted otherwise.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: errorPayload.message,\n code: errorPayload.code,\n },\n }\n\n options.logger.errors(`${this.name}.chatStream fatal`, {\n error: errorPayload,\n source: `${this.name}.chatStream`,\n })\n }\n }\n\n /**\n * Generate structured output using the provider's native JSON Schema response format.\n * Uses stream: false to get the complete response in one call.\n *\n * OpenAI-compatible Responses APIs have strict requirements for structured output:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for all objects\n *\n * The outputSchema is already JSON Schema (converted in the ai layer).\n * We apply provider-specific transformations for structured output compatibility.\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const requestParams = this.mapOptionsToRequest(chatOptions)\n\n // Apply provider-specific transformations for structured output compatibility\n const jsonSchema = this.makeStructuredOutputCompatible(\n outputSchema,\n outputSchema.required,\n )\n\n try {\n // Strip streaming-only fields a subclass override of mapOptionsToRequest\n // might have returned (parallel to chat-completions's structuredOutput\n // cleanup) — sending stream_options to a non-streaming call is a 4xx.\n const {\n stream: _stream,\n stream_options: _streamOptions,\n ...cleanParams\n } = requestParams as Record<string, unknown>\n void _stream\n void _streamOptions\n chatOptions.logger.request(\n `activity=structuredOutput provider=${this.name} model=${this.model} messages=${chatOptions.messages.length}`,\n { provider: this.name, model: this.model },\n )\n const response = await this.client.responses.create(\n {\n ...(cleanParams as Omit<ResponseCreateParams, 'stream'>),\n stream: false,\n // Configure structured output via text.format\n text: {\n format: {\n type: 'json_schema',\n name: 'structured_output',\n schema: jsonSchema,\n strict: true,\n },\n },\n },\n extractRequestOptions(chatOptions.request),\n )\n\n // Extract text content from the response. `stream: false` narrows the\n // SDK return type to `Response`, but the explicit annotation makes\n // that contract local rather than relying on inference through the\n // overloaded `client.responses.create` signature.\n const rawText = this.extractTextFromResponse(response satisfies Response)\n\n // Fail loud on empty content rather than letting it cascade into a\n // confusing \"Failed to parse JSON. Content: \" error — the root cause\n // (the model returned no text content for the structured request) is\n // then visible in logs. Mirrors the chat-completions sibling.\n if (rawText.length === 0) {\n throw new Error(\n `${this.name}.structuredOutput: response contained no content`,\n )\n }\n\n // Parse the JSON response\n let parsed: unknown\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to parse structured output as JSON. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n\n // Provider-specific post-parse shaping (default passthrough). Null-widening\n // from strict mode is undone by the engine, not here.\n const transformed = this.transformStructuredOutput(parsed)\n\n // Surface usage so non-stream structured paths (and\n // fallbackStructuredOutputStream) can forward tokens to middleware.\n const usage = buildResponsesUsage(response.usage)\n return {\n data: transformed,\n rawText,\n ...(usage && { usage }),\n }\n } catch (error: unknown) {\n // Narrow before logging: raw SDK errors can carry request metadata\n // (including auth headers) which we must never surface to user loggers.\n chatOptions.logger.errors(`${this.name}.structuredOutput fatal`, {\n error: toRunErrorPayload(error, `${this.name}.structuredOutput failed`),\n source: `${this.name}.structuredOutput`,\n })\n throw error\n }\n }\n\n /**\n * Stream structured output via the Responses API: single request with\n * `text.format: json_schema` + `stream: true`. Consumes Responses-API\n * events (`response.output_text.delta`, `response.reasoning_text.delta`,\n * `response.reasoning_summary_text.delta`, the legacy\n * `response.reasoning.delta`, `response.refusal.delta`,\n * `response.completed`, `response.failed`) and re-emits the standard AG-UI\n * lifecycle ending with `CUSTOM 'structured-output.complete'`.\n *\n * Tools are stripped (structured output is mutually exclusive with tool\n * calls in this path). Reasoning text is accumulated and surfaced both as\n * REASONING_* lifecycle events during the stream and on the terminal\n * CUSTOM event's `value.reasoning`.\n */\n async *structuredOutputStream(\n options: StructuredOutputOptions<TProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const { chatOptions, outputSchema } = options\n const requestParams = this.mapOptionsToRequest(chatOptions)\n\n const jsonSchema = this.makeStructuredOutputCompatible(\n outputSchema,\n outputSchema.required,\n )\n\n const aguiState = {\n runId: generateId(this.name),\n threadId: chatOptions.threadId ?? generateId(this.name),\n messageId: generateId(this.name),\n hasEmittedRunStarted: false,\n }\n\n let accumulatedContent = ''\n let accumulatedReasoning = ''\n let hasEmittedTextMessageStart = false\n let reasoningMessageId: string | undefined\n let stepId: string | undefined\n let hasClosedReasoning = false\n let model: string = chatOptions.model\n let usage: OpenAI.Responses.Response['usage'] | undefined\n\n const closeReasoning = function* (this: {\n name: string\n }): Generator<AdapterYieldChunk> {\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n if (stepId) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n content: accumulatedReasoning,\n }\n }\n reasoningMessageId = undefined\n stepId = undefined\n hasClosedReasoning = false\n }\n }.bind(this)\n\n const openReasoning = function* (this: {\n name: string\n }): Generator<AdapterYieldChunk> {\n if (reasoningMessageId) return\n reasoningMessageId = generateId(this.name)\n stepId = generateId(this.name)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n stepType: 'thinking',\n }\n }.bind(this)\n\n try {\n const { tools: _tools, ...cleanParams } = requestParams\n void _tools\n\n chatOptions.logger.request(\n `activity=structuredOutputStream provider=${this.name} model=${this.model} messages=${chatOptions.messages.length}`,\n { provider: this.name, model: this.model },\n )\n\n const stream: AsyncIterable<\n ResponseStreamEvent | LegacyReasoningDeltaEvent\n > = await this.client.responses.create(\n {\n ...cleanParams,\n stream: true,\n text: {\n format: {\n type: 'json_schema',\n name: 'structured_output',\n schema: jsonSchema,\n strict: true,\n },\n },\n },\n extractRequestOptions(chatOptions.request),\n )\n\n for await (const chunk of stream) {\n chatOptions.logger.provider(\n `provider=${this.name} type=${chunk.type}`,\n { provider: this.name, type: chunk.type },\n )\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model,\n timestamp: Date.now(),\n parentRunId: chatOptions.parentRunId,\n }\n }\n\n if (\n chunk.type === 'response.created' ||\n chunk.type === 'response.in_progress'\n ) {\n const responseModel = (chunk as { response?: { model?: string } })\n .response?.model\n if (responseModel) model = responseModel\n continue\n }\n\n if (chunk.type === 'response.refusal.delta') {\n const delta =\n typeof (chunk as { delta?: unknown }).delta === 'string'\n ? (chunk as { delta: string }).delta\n : ''\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message: `Model refused: ${delta}`,\n code: 'refusal',\n error: { message: `Model refused: ${delta}`, code: 'refusal' },\n }\n return\n }\n\n if (\n chunk.type === 'response.reasoning_text.delta' ||\n chunk.type === 'response.reasoning_summary_text.delta' ||\n chunk.type === 'response.reasoning.delta'\n ) {\n const raw = (chunk as { delta?: unknown }).delta\n const reasoningDelta = Array.isArray(raw)\n ? raw.join('')\n : typeof raw === 'string'\n ? raw\n : ''\n if (!reasoningDelta) continue\n yield* openReasoning()\n // openReasoning() guarantees reasoningMessageId is set on first call;\n // TS can't see through the generator side-effect.\n if (!reasoningMessageId) continue\n accumulatedReasoning += reasoningDelta\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: reasoningDelta,\n model,\n timestamp: Date.now(),\n }\n continue\n }\n\n if (chunk.type === 'response.output_text.delta') {\n const raw = (chunk as { delta?: unknown }).delta\n const textDelta = Array.isArray(raw)\n ? raw.join('')\n : typeof raw === 'string'\n ? raw\n : ''\n if (!textDelta) continue\n\n yield* closeReasoning()\n\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n accumulatedContent += textDelta\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: aguiState.messageId,\n model,\n timestamp: Date.now(),\n delta: textDelta,\n content: accumulatedContent,\n }\n continue\n }\n\n if (chunk.type === 'response.completed') {\n const response = chunk.response\n if (response.usage) usage = response.usage\n if (response.model) model = response.model\n continue\n }\n\n if (chunk.type === 'response.failed') {\n const response = (\n chunk as {\n response?: { error?: { message?: string; code?: string } }\n }\n ).response\n const message =\n response?.error?.message || 'Responses API stream failed'\n const code = response?.error?.code\n // Conditional `code` spread keeps the wire shape spec-compliant\n // under `exactOptionalPropertyTypes` (see chatStream catch).\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message,\n ...(code !== undefined && { code }),\n error: { message, ...(code !== undefined && { code }) },\n }\n return\n }\n }\n\n yield* closeReasoning()\n\n if (hasEmittedTextMessageStart) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: aguiState.messageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n if (accumulatedContent.length === 0) {\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message: `${this.name}.structuredOutputStream: response contained no content`,\n code: 'empty-response',\n error: {\n message: `${this.name}.structuredOutputStream: response contained no content`,\n code: 'empty-response',\n },\n }\n return\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(accumulatedContent)\n } catch {\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message: `Failed to parse structured output as JSON. Content: ${accumulatedContent.slice(0, 200)}${accumulatedContent.length > 200 ? '...' : ''}`,\n code: 'parse-error',\n error: {\n message: 'Failed to parse structured output as JSON',\n code: 'parse-error',\n },\n }\n return\n }\n\n // Route through the same hook as the non-streaming path (default\n // passthrough). Engine un-widens nulls; the streaming path must not strip\n // them blindly either.\n const transformed = this.transformStructuredOutput(parsed)\n\n yield {\n type: EventType.CUSTOM,\n name: 'structured-output.complete',\n value: {\n object: transformed,\n raw: accumulatedContent,\n ...(accumulatedReasoning ? { reasoning: accumulatedReasoning } : {}),\n },\n model,\n timestamp: Date.now(),\n }\n\n yield {\n type: EventType.RUN_FINISHED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n ...(usage && {\n usage: buildResponsesUsage(usage),\n }),\n }\n } catch (error: unknown) {\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model,\n timestamp: Date.now(),\n parentRunId: chatOptions.parentRunId,\n }\n }\n\n const isAbort = this.isAbortError(error)\n const errorPayload = toRunErrorPayload(\n error,\n `${this.name}.structuredOutputStream failed`,\n )\n\n // Conditional `code` spread keeps the wire shape spec-compliant under\n // `exactOptionalPropertyTypes` (see chatStream catch).\n const resolvedCode = isAbort ? 'aborted' : errorPayload.code\n const rawEvent = isAbort ? undefined : toRunErrorRawEvent(error)\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message: errorPayload.message,\n ...(resolvedCode !== undefined && { code: resolvedCode }),\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: errorPayload.message,\n ...(resolvedCode !== undefined && { code: resolvedCode }),\n },\n }\n\n chatOptions.logger.errors(`${this.name}.structuredOutputStream fatal`, {\n error: errorPayload,\n source: `${this.name}.structuredOutputStream`,\n })\n }\n }\n\n /**\n * Cross-SDK abort detection for `structuredOutputStream`. Mirrors the\n * Chat Completions base; subclasses with proprietary error types override.\n */\n protected isAbortError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false\n const e = error as { name?: unknown; code?: unknown }\n return (\n e.name === 'APIUserAbortError' ||\n e.name === 'AbortError' ||\n e.code === 'ERR_CANCELED'\n )\n }\n\n /**\n * Strict conversion plus the inverse null-widening map for this request.\n * Override this when schema conversion changes, so tool-input undo matches\n * the wire schema.\n */\n protected makeStructuredOutputCompatibleWithMap(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n ): StructuredOutputCompatibility {\n return makeStructuredOutputCompatibleWithMap(schema, originalRequired)\n }\n\n /**\n * Applies provider-specific transformations for structured output compatibility.\n * Override `makeStructuredOutputCompatibleWithMap` when you need the inverse map\n * to match the wire schema.\n */\n protected makeStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n ): Record<string, any> {\n return this.makeStructuredOutputCompatibleWithMap(schema, originalRequired)\n .schema\n }\n\n /**\n * Final shaping pass applied to parsed structured-output JSON before it is\n * returned to the caller. Default is a passthrough.\n *\n * Provider `null`s are no longer stripped here: strict-mode null-widening is\n * now undone precisely by the engine (`undoNullWidening`, driven by the\n * schema's null-widening map) the moment the result is captured, so a blind\n * `transformNullsToUndefined` at the adapter would only destroy genuine\n * `.nullable()` nulls. Subclasses may still override to remap or reshape the\n * provider's structured output.\n */\n protected transformStructuredOutput(parsed: unknown): unknown {\n return parsed\n }\n\n /**\n * Extract text content from a non-streaming Responses API response.\n * Override this in subclasses for provider-specific response shapes.\n */\n protected extractTextFromResponse(response: Response): string {\n let textContent = ''\n let refusal: string | undefined\n let sawMessageItem = false\n const observedItemTypes = new Set<string>()\n\n for (const item of response.output) {\n observedItemTypes.add(item.type)\n if (item.type === 'message') {\n sawMessageItem = true\n for (const part of item.content) {\n // Cast off the discriminated union before the type discrimination\n // so future SDK variants (e.g. `output_audio`, `output_image`) hit\n // the explicit error path rather than being misreported as refusals\n // when they get added to the union. Mirrors the streaming side's\n // handleContentPart.\n const partType = (part as { type: string }).type\n if (partType === 'output_text') {\n textContent += (part as { text?: string }).text ?? ''\n } else if (partType === 'refusal') {\n const refusalText = (part as { refusal?: string }).refusal\n refusal = refusalText || refusal || 'Refused without explanation'\n } else {\n throw new Error(\n `${this.name}.extractTextFromResponse: unsupported message content part type \"${partType}\"`,\n )\n }\n }\n }\n }\n\n // Surface refusals as an explicit error so callers don't see a generic\n // \"Failed to parse structured output as JSON. Content: \" when the model\n // refused for safety / content-policy reasons.\n if (!textContent && refusal !== undefined) {\n const err = new Error(`Model refused to respond: ${refusal}`)\n ;(err as Error & { code?: string }).code = 'refusal'\n throw err\n }\n\n // Response had items but none carried message text (e.g. only\n // function_call or reasoning items). Surface that explicitly so a\n // downstream structured-output caller doesn't see a misleading\n // \"Failed to parse JSON. Content: \" from an empty string.\n if (!textContent && response.output.length > 0 && !sawMessageItem) {\n throw new Error(\n `${this.name}.extractTextFromResponse: response.output contained items of type(s) [${[...observedItemTypes].sort().join(', ')}] but no message text — the model returned a non-text response`,\n )\n }\n\n return textContent\n }\n\n /**\n * Processes streamed chunks from the Responses API and yields AG-UI events.\n * Override this in subclasses to handle provider-specific stream behavior.\n *\n * Handles the following event types:\n * - response.created / response.incomplete / response.failed\n * - response.output_text.delta\n * - response.reasoning_text.delta\n * - response.reasoning.delta (the legacy type used before response.reasoning_text.delta)\n * - response.reasoning_summary_text.delta\n * - response.content_part.added / response.content_part.done\n * - response.output_item.added\n * - response.function_call_arguments.delta / response.function_call_arguments.done\n * - response.completed\n * - error\n */\n protected async *processStreamChunks(\n stream: AsyncIterable<ResponseStreamEvent | LegacyReasoningDeltaEvent>,\n toolCallMetadata: Map<string, StreamedFunctionCallMetadata>,\n options: TextOptions<TProviderOptions>,\n aguiState: {\n runId: string\n threadId: string\n messageId: string\n hasEmittedRunStarted: boolean\n },\n ): AsyncIterable<AdapterYieldChunk> {\n const normalizeToolInput = createToolInputNormalizer(\n options.tools,\n (schema, required) =>\n this.makeStructuredOutputCompatibleWithMap(schema, required),\n )\n let accumulatedContent = ''\n let accumulatedReasoning = ''\n\n // Track if we've been streaming deltas to avoid duplicating content from done events\n let hasStreamedContentDeltas = false\n let hasStreamedReasoningDeltas = false\n\n // Preserve response metadata across events\n let model: string = options.model\n\n // AG-UI lifecycle tracking\n let stepId: string | null = null\n let hasEmittedTextMessageStart = false\n let reasoningMessageId: string | undefined\n let reasoningItemId: string | undefined\n let reasoningEncryptedContent: string | undefined\n let closedReasoningStepId: string | undefined\n let hasClosedReasoning = false\n // Track whether we've emitted a terminal RUN_FINISHED so the\n // end-of-stream fallback below knows to synthesise one when the upstream\n // cuts off without a response.completed event.\n let runFinishedEmitted = false\n\n const adapterName = this.name\n const emitModel = () => model || options.model\n\n const openReasoning = function* (): Generator<AdapterYieldChunk> {\n if (reasoningMessageId) return\n reasoningMessageId = generateId(adapterName)\n stepId = generateId(adapterName)\n const timestamp = Date.now()\n const currentModel = emitModel()\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model: currentModel,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model: currentModel,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model: currentModel,\n timestamp,\n stepType: 'thinking',\n }\n }\n\n const captureReasoningItem = (item: unknown) => {\n const parsed = readReasoningItem(item)\n if (!parsed) return\n if (parsed.id) reasoningItemId = parsed.id\n if (parsed.encrypted_content) {\n reasoningEncryptedContent = parsed.encrypted_content\n }\n }\n\n const closeReasoning = function* (): Generator<AdapterYieldChunk> {\n if (!reasoningMessageId || hasClosedReasoning) return\n hasClosedReasoning = true\n const timestamp = Date.now()\n const currentModel = emitModel()\n const signature = packResponsesReasoningSignature(\n reasoningItemId,\n reasoningEncryptedContent,\n )\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model: currentModel,\n timestamp,\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model: currentModel,\n timestamp,\n }\n if (stepId) {\n closedReasoningStepId = stepId\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model: currentModel,\n timestamp,\n content: accumulatedReasoning,\n ...(signature ? { signature } : {}),\n }\n }\n reasoningMessageId = undefined\n reasoningItemId = undefined\n reasoningEncryptedContent = undefined\n stepId = null\n hasClosedReasoning = false\n accumulatedReasoning = ''\n }\n\n const emitReasoningDelta = function* (\n text: string,\n ): Generator<AdapterYieldChunk> {\n if (!text) return\n yield* openReasoning()\n if (!reasoningMessageId) return\n accumulatedReasoning += text\n hasStreamedReasoningDeltas = true\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: text,\n model: emitModel(),\n timestamp: Date.now(),\n }\n }\n\n try {\n for await (const chunk of stream) {\n options.logger.provider(`provider=${this.name} type=${chunk.type}`, {\n provider: this.name,\n type: chunk.type,\n })\n\n // Emit RUN_STARTED on first chunk\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: model || options.model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n const handleContentPart = (contentPart: {\n type: string\n text?: string\n refusal?: string\n }): AdapterYieldChunk => {\n if (contentPart.type === 'output_text') {\n accumulatedContent += contentPart.text || ''\n return {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n delta: contentPart.text || '',\n content: accumulatedContent,\n }\n }\n\n // Either a real refusal or an unknown content_part type. Surface\n // the part type in the error so unknown parts are debuggable\n // instead of being misreported as \"Unknown refusal\".\n const isRefusal = contentPart.type === 'refusal'\n const message = isRefusal\n ? contentPart.refusal || 'Refused without explanation'\n : `Unsupported response content_part type: ${contentPart.type}`\n const code = isRefusal ? 'refusal' : contentPart.type\n return {\n type: EventType.RUN_ERROR,\n model: model || options.model,\n timestamp: Date.now(),\n message,\n code,\n error: { message, code },\n }\n }\n\n // Capture model metadata from any of these events (created starts\n // the run; failed/incomplete signal terminal failure).\n if (\n chunk.type === 'response.created' ||\n chunk.type === 'response.incomplete' ||\n chunk.type === 'response.failed'\n ) {\n model = chunk.response.model\n }\n\n // response.created marks the start of a fresh run — safe to reset\n // the per-run accumulators here.\n if (chunk.type === 'response.created') {\n hasStreamedContentDeltas = false\n hasStreamedReasoningDeltas = false\n hasEmittedTextMessageStart = false\n reasoningMessageId = undefined\n hasClosedReasoning = false\n stepId = null\n accumulatedContent = ''\n accumulatedReasoning = ''\n }\n\n // response.failed and response.incomplete are TERMINAL events for\n // the current response. Close any open AG-UI message lifecycle FIRST\n // so consumers tracking start/end pairs don't see an unbalanced\n // TEXT_MESSAGE_START. Then surface the error and mark the run as\n // finished so the post-loop synthetic terminal block doesn't emit\n // a duplicate RUN_FINISHED on top of RUN_ERROR.\n if (\n chunk.type === 'response.failed' ||\n chunk.type === 'response.incomplete'\n ) {\n yield* closeReasoning()\n if (hasEmittedTextMessageStart) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: aguiState.messageId,\n model: chunk.response.model,\n timestamp: Date.now(),\n }\n hasEmittedTextMessageStart = false\n }\n // Coalesce error + incomplete_details into a single RUN_ERROR\n // payload — emitting two distinct events for one terminal upstream\n // event would force consumers to handle a non-existent ordering.\n const errorMessage =\n chunk.response.error?.message ||\n chunk.response.incomplete_details?.reason ||\n (chunk.type === 'response.failed'\n ? 'Response failed'\n : 'Response ended incomplete')\n const errorCode =\n chunk.response.error?.code ??\n (chunk.response.incomplete_details ? 'incomplete' : undefined) ??\n undefined\n // Always emit RUN_ERROR for terminal failure events, even when the\n // upstream omitted both `error` and `incomplete_details`. Skipping\n // emission on a `response.incomplete` with no detail would let the\n // post-loop synthetic block silently coerce the run to a clean\n // `RUN_FINISHED { finishReason: 'stop' }` — masking the failure.\n yield {\n type: EventType.RUN_ERROR,\n model: chunk.response.model,\n timestamp: Date.now(),\n message: errorMessage,\n ...(errorCode !== undefined && { code: errorCode }),\n error: {\n message: errorMessage,\n ...(errorCode !== undefined && { code: errorCode }),\n },\n }\n // RUN_ERROR is the terminal event for this run; stop processing\n // any further chunks the iterator might still deliver.\n runFinishedEmitted = true\n return\n }\n\n // Handle output text deltas (token-by-token streaming)\n // response.output_text.delta provides incremental text updates\n if (chunk.type === 'response.output_text.delta' && chunk.delta) {\n // Delta can be an array of strings or a single string\n const textDelta = Array.isArray(chunk.delta)\n ? chunk.delta.join('')\n : typeof chunk.delta === 'string'\n ? chunk.delta\n : ''\n\n if (textDelta) {\n yield* closeReasoning()\n // Emit TEXT_MESSAGE_START on first text content\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n accumulatedContent += textDelta\n hasStreamedContentDeltas = true\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n delta: textDelta,\n content: accumulatedContent,\n }\n }\n }\n\n // Handle reasoning deltas (token-by-token thinking/reasoning streaming)\n // response.reasoning_text.delta provides incremental reasoning updates\n if (\n (chunk.type === 'response.reasoning_text.delta' ||\n chunk.type === 'response.reasoning.delta') &&\n chunk.delta\n ) {\n const reasoningDelta = Array.isArray(chunk.delta)\n ? chunk.delta.join('')\n : typeof chunk.delta === 'string'\n ? chunk.delta\n : ''\n yield* emitReasoningDelta(reasoningDelta)\n }\n\n // Handle reasoning summary deltas (when using reasoning.summary option)\n if (\n chunk.type === 'response.reasoning_summary_text.delta' &&\n chunk.delta\n ) {\n const summaryDelta =\n typeof chunk.delta === 'string' ? chunk.delta : ''\n yield* emitReasoningDelta(summaryDelta)\n }\n\n // handle content_part added events for text, reasoning and refusals\n if (chunk.type === 'response.content_part.added') {\n const contentPart = chunk.part\n // The Responses API can announce a text part with an empty\n // placeholder before putting the actual text only on the completed\n // response. An empty placeholder is not streamed content and must\n // not suppress the completion backstop below.\n if (\n (contentPart.type === 'output_text' ||\n contentPart.type === 'reasoning_text') &&\n !contentPart.text\n ) {\n continue\n }\n if (contentPart.type === 'reasoning_text') {\n yield* emitReasoningDelta(contentPart.text || '')\n continue\n }\n if (\n contentPart.type === 'output_text' &&\n !hasEmittedTextMessageStart\n ) {\n yield* closeReasoning()\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n // Mark whichever stream we just emitted into so a subsequent\n // `content_part.done` doesn't duplicate the same text. Without\n // this flag, an `added` event carrying the full text followed by\n // a matching `done` event would emit TEXT_MESSAGE_CONTENT twice.\n if (contentPart.type === 'output_text') {\n hasStreamedContentDeltas = true\n }\n const partChunk = handleContentPart(contentPart)\n yield partChunk\n // handleContentPart returns RUN_ERROR for refusals / unknown\n // content_part types — those are terminal events. Don't keep\n // processing more chunks (and don't let the post-loop synthetic\n // block emit a second terminal event).\n if (partChunk.type === 'RUN_ERROR') {\n runFinishedEmitted = true\n return\n }\n }\n\n if (chunk.type === 'response.content_part.done') {\n const contentPart = chunk.part\n\n // Skip emitting chunks for content parts that we've already streamed via deltas\n // The done event is just a completion marker, not new content\n if (contentPart.type === 'output_text' && hasStreamedContentDeltas) {\n // Content already accumulated from deltas, skip\n continue\n }\n if (\n contentPart.type === 'reasoning_text' &&\n hasStreamedReasoningDeltas\n ) {\n // Reasoning already accumulated from deltas, skip\n continue\n }\n\n // Upstreams that emit `content_part.done` without any preceding\n // deltas (or `content_part.added`) still need a START event before\n // CONTENT — otherwise consumers tracking start/end pairs see content\n // without a start and never see an end. Emit the lifecycle opener\n // for whichever stream this content_part belongs to before yielding\n // the CONTENT chunk; the post-loop block emits the matching END.\n if (contentPart.type === 'reasoning_text') {\n yield* emitReasoningDelta(contentPart.text || '')\n continue\n }\n if (\n contentPart.type === 'output_text' &&\n !hasEmittedTextMessageStart\n ) {\n yield* closeReasoning()\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n // Only emit if we haven't been streaming deltas (e.g., for non-streaming responses)\n const doneChunk = handleContentPart(contentPart)\n yield doneChunk\n if (doneChunk.type === 'RUN_ERROR') {\n runFinishedEmitted = true\n return\n }\n }\n\n // handle output_item.added to capture function call metadata (name)\n if (chunk.type === 'response.output_item.added') {\n const item = chunk.item\n if (item.type === 'reasoning') {\n captureReasoningItem(item)\n yield* openReasoning()\n }\n if (item.type === 'function_call' && item.id) {\n // Track the item as soon as we see it so subsequent arg deltas\n // aren't logged as orphans, but only emit TOOL_CALL_START when\n // both id AND name are populated. Emitting START with an empty\n // name would propagate into TOOL_CALL_END (which reads the same\n // metadata) and route the tool call to whatever name happens to\n // match `''` downstream — a silent misroute.\n let metadata = toolCallMetadata.get(item.id)\n if (!metadata) {\n metadata = {\n callId: item.call_id || item.id,\n index: chunk.output_index,\n name: item.name || '',\n started: false,\n }\n toolCallMetadata.set(item.id, metadata)\n } else {\n if (item.call_id) metadata.callId = item.call_id\n if (!metadata.name && item.name) {\n // A later output_item.added for the same id finally carries\n // the name. Update so the gated emission below can fire.\n metadata.name = item.name\n }\n }\n if (!metadata.started && metadata.name) {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: metadata.callId,\n toolCallName: metadata.name,\n toolName: metadata.name,\n parentMessageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n index: chunk.output_index,\n metadata: {\n itemId: item.id,\n } satisfies OpenAIResponsesToolCallMetadata,\n }\n metadata.started = true\n }\n }\n }\n\n // Handle function call arguments delta (streaming). Drop the\n // previously-emitted `args` field — it had inverted polarity\n // (populated only when metadata was MISSING, i.e. when the\n // matching TOOL_CALL_START hadn't fired) and the chat-completions\n // adapter never emitted it, so it leaked partial deltas as\n // pseudo-args only on the orphan path. Consumers should accumulate\n // `delta` themselves.\n //\n // Guard with `metadata?.started`: the matching TOOL_CALL_START fires\n // from `output_item.added`, and emitting TOOL_CALL_ARGS before that\n // would violate the AG-UI lifecycle (ARGS without START). The .done\n // handler below applies the same guard.\n if (\n chunk.type === 'response.function_call_arguments.delta' &&\n chunk.delta\n ) {\n const metadata = toolCallMetadata.get(chunk.item_id)\n if (!metadata?.started) {\n options.logger.errors(\n `${this.name}.processStreamChunks orphan function_call_arguments.delta`,\n {\n source: `${this.name}.processStreamChunks`,\n // No metadata yet, so the `call_id` is unknown here — only the\n // output item id the delta referenced.\n itemId: chunk.item_id,\n rawDelta: chunk.delta,\n },\n )\n continue\n }\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: metadata.callId,\n model: model || options.model,\n timestamp: Date.now(),\n delta: chunk.delta,\n }\n }\n\n if (chunk.type === 'response.function_call_arguments.done') {\n const { item_id } = chunk\n\n // Get the function name from metadata (captured in output_item.added)\n const metadata = toolCallMetadata.get(item_id)\n // If the matching START was never emitted (the upstream sent an\n // `output_item.added` without a name and no later event has filled\n // it in yet), defer END until `output_item.done` or\n // `response.completed` can backfill the name. We stash the raw\n // arguments so the late emission has them. Emitting END without\n // START would produce an unbalanced AG-UI lifecycle event\n // downstream consumers can't pair.\n if (!metadata?.started) {\n if (metadata) {\n metadata.pendingArguments = chunk.arguments\n }\n options.logger.errors(\n `${this.name}.processStreamChunks deferring function_call_arguments.done — TOOL_CALL_START not yet emitted (waiting for name)`,\n {\n source: `${this.name}.processStreamChunks`,\n ...(metadata && { toolCallId: metadata.callId }),\n itemId: item_id,\n rawArguments: chunk.arguments,\n },\n )\n continue\n }\n // The output_item.done backstop may have already emitted END (when\n // it arrived before args.done with a populated item.arguments).\n // Skip so we never produce a duplicate close for the same id.\n if (metadata.ended) continue\n const name = metadata.name || ''\n metadata.ended = true\n\n // Parse arguments. Surface parse failures via the logger so a\n // model emitting malformed JSON is debuggable instead of silently\n // invoking the tool with {}.\n let parsedInput: unknown = {}\n if (chunk.arguments) {\n try {\n const parsed = JSON.parse(chunk.arguments)\n parsedInput = normalizeToolInput(\n name,\n parsed && typeof parsed === 'object' ? parsed : {},\n )\n } catch (parseError) {\n options.logger.errors(\n `${this.name}.processStreamChunks tool-args JSON parse failed`,\n {\n error: toRunErrorPayload(\n parseError,\n `tool ${name} (${metadata.callId}) returned malformed JSON arguments`,\n ),\n source: `${this.name}.processStreamChunks`,\n toolCallId: metadata.callId,\n itemId: item_id,\n toolName: name,\n rawArguments: chunk.arguments,\n },\n )\n parsedInput = {}\n }\n }\n\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: metadata.callId,\n toolCallName: name,\n toolName: name,\n model: model || options.model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n }\n\n // `output_item.done` is the last point at which a function_call's\n // name is guaranteed to be on the wire — it carries the fully-formed\n // ResponseFunctionToolCall. Use it as a backstop to recover any\n // tool call whose name was missing from `output_item.added` (and\n // whose START + END therefore never fired).\n if (chunk.type === 'response.output_item.done') {\n const item = chunk.item\n if (item.type === 'reasoning') {\n captureReasoningItem(item)\n yield* openReasoning()\n }\n if (item.type === 'function_call' && item.id) {\n const metadata = toolCallMetadata.get(item.id) ?? {\n callId: item.call_id || item.id,\n index: chunk.output_index,\n name: item.name || '',\n started: false,\n }\n if (!toolCallMetadata.has(item.id)) {\n toolCallMetadata.set(item.id, metadata)\n } else {\n if (item.call_id) metadata.callId = item.call_id\n if (!metadata.name && item.name) metadata.name = item.name\n }\n // Emit gated START if we now have a name and never started.\n if (!metadata.started && metadata.name) {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: metadata.callId,\n toolCallName: metadata.name,\n toolName: metadata.name,\n parentMessageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n index: metadata.index,\n metadata: {\n itemId: item.id,\n } satisfies OpenAIResponsesToolCallMetadata,\n }\n metadata.started = true\n }\n // Emit END if we have args (either from a previously-deferred\n // args.done OR from item.arguments) and haven't already ended.\n const rawArgs =\n typeof item.arguments === 'string' && item.arguments.length > 0\n ? item.arguments\n : metadata.pendingArguments\n if (metadata.started && !metadata.ended && rawArgs !== undefined) {\n const name = metadata.name || ''\n let parsedInput: unknown = {}\n if (rawArgs) {\n try {\n const parsed = JSON.parse(rawArgs)\n parsedInput = normalizeToolInput(\n name,\n parsed && typeof parsed === 'object' ? parsed : {},\n )\n } catch (parseError) {\n options.logger.errors(\n `${this.name}.processStreamChunks tool-args JSON parse failed (output_item.done backfill)`,\n {\n error: toRunErrorPayload(\n parseError,\n `tool ${name} (${metadata.callId}) returned malformed JSON arguments`,\n ),\n source: `${this.name}.processStreamChunks`,\n toolCallId: metadata.callId,\n itemId: item.id,\n toolName: name,\n rawArguments: rawArgs,\n },\n )\n parsedInput = {}\n }\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: metadata.callId,\n toolCallName: name,\n toolName: name,\n model: model || options.model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n metadata.ended = true\n metadata.pendingArguments = undefined\n }\n }\n }\n\n if (chunk.type === 'response.completed') {\n // Some Responses API streams, notably reasoning-model responses,\n // can omit text deltas and carry the successful final text only in\n // response.completed.output. Recover that text so consumers never\n // observe an empty result for a successful response.\n const completedText = chunk.response.output\n .flatMap((item) => (item.type === 'message' ? item.content : []))\n .filter((part) => part.type === 'output_text')\n .map((part) => part.text)\n .join('')\n\n if (accumulatedContent.length === 0 && completedText.length > 0) {\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n accumulatedContent = completedText\n hasStreamedContentDeltas = true\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n delta: completedText,\n content: accumulatedContent,\n }\n }\n\n if (Array.isArray(chunk.response.output)) {\n for (const item of chunk.response.output) {\n captureReasoningItem(item)\n }\n }\n // output_text already closed the streamed reasoning item. A second\n // openReasoning() would emit an empty thinking part. Attach the\n // completed item's id/blob to that step instead. Open only when\n // this turn never started reasoning (encrypted-only output).\n if (\n !reasoningMessageId &&\n (reasoningItemId || reasoningEncryptedContent)\n ) {\n const signature = packResponsesReasoningSignature(\n reasoningItemId,\n reasoningEncryptedContent,\n )\n if (closedReasoningStepId && signature) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: closedReasoningStepId,\n stepId: closedReasoningStepId,\n model: emitModel(),\n timestamp: Date.now(),\n content: '',\n signature,\n }\n } else if (!closedReasoningStepId) {\n yield* openReasoning()\n }\n }\n\n // Final backstop for function_call lifecycle: if a function_call\n // appears in `response.output[]` but was never matched by an\n // output_item.added/done with a name, recover the missing START\n // (and END if args were pending). Without this, a tool call could\n // be silently dropped from the AG-UI stream while `hasFunctionCalls`\n // below still routes the run's finishReason to 'tool_calls' —\n // leaving consumers waiting for tool results they never saw start.\n for (const item of chunk.response.output) {\n if (item.type !== 'function_call' || !item.id) continue\n const metadata = toolCallMetadata.get(item.id) ?? {\n callId: item.call_id || item.id,\n index: 0,\n name: item.name || '',\n started: false,\n }\n if (!toolCallMetadata.has(item.id)) {\n toolCallMetadata.set(item.id, metadata)\n } else {\n if (item.call_id) metadata.callId = item.call_id\n if (!metadata.name && item.name) metadata.name = item.name\n }\n if (!metadata.started && metadata.name) {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: metadata.callId,\n toolCallName: metadata.name,\n toolName: metadata.name,\n parentMessageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n index: metadata.index,\n metadata: {\n itemId: item.id,\n } satisfies OpenAIResponsesToolCallMetadata,\n }\n metadata.started = true\n }\n const rawArgs =\n typeof item.arguments === 'string' && item.arguments.length > 0\n ? item.arguments\n : metadata.pendingArguments\n if (metadata.started && !metadata.ended) {\n const name = metadata.name || ''\n let parsedInput: unknown = {}\n if (rawArgs) {\n try {\n const parsed = JSON.parse(rawArgs)\n parsedInput = normalizeToolInput(\n name,\n parsed && typeof parsed === 'object' ? parsed : {},\n )\n } catch (parseError) {\n options.logger.errors(\n `${this.name}.processStreamChunks tool-args JSON parse failed (response.completed backfill)`,\n {\n error: toRunErrorPayload(\n parseError,\n `tool ${name} (${metadata.callId}) returned malformed JSON arguments`,\n ),\n source: `${this.name}.processStreamChunks`,\n toolCallId: metadata.callId,\n itemId: item.id,\n toolName: name,\n rawArguments: rawArgs,\n },\n )\n parsedInput = {}\n }\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: metadata.callId,\n toolCallName: name,\n toolName: name,\n model: model || options.model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n metadata.ended = true\n metadata.pendingArguments = undefined\n }\n }\n\n yield* closeReasoning()\n // Emit TEXT_MESSAGE_END if we had text content\n if (hasEmittedTextMessageStart) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n }\n hasEmittedTextMessageStart = false\n }\n\n // Determine finish reason. Function-call output → tool_calls.\n // Otherwise surface incomplete_details.reason when present so\n // callers can distinguish length-limit / content-filter cutoffs\n // from a clean stop, mirroring the chat-completions adapter.\n // The Responses API's incomplete_details.reason ('max_output_tokens'\n // | 'content_filter') maps to the AG-UI finishReason vocabulary:\n // max_output_tokens → 'length', content_filter → 'content_filter'.\n const hasFunctionCalls = chunk.response.output.some(\n (item: unknown) =>\n (item as { type: string }).type === 'function_call',\n )\n const incompleteReason = chunk.response.incomplete_details?.reason\n const finishReason:\n | 'tool_calls'\n | 'length'\n | 'content_filter'\n | 'stop' = hasFunctionCalls\n ? 'tool_calls'\n : incompleteReason === 'max_output_tokens'\n ? 'length'\n : incompleteReason === 'content_filter'\n ? 'content_filter'\n : 'stop'\n\n yield {\n type: EventType.RUN_FINISHED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: model || options.model,\n timestamp: Date.now(),\n // Omit usage entirely when the provider reported none rather than\n // emitting fabricated zeros (also satisfies exactOptionalPropertyTypes).\n ...(chunk.response.usage && {\n usage: buildResponsesUsage(chunk.response.usage),\n }),\n finishReason,\n }\n runFinishedEmitted = true\n }\n\n if (chunk.type === 'error') {\n // Conditional `code` spread keeps the wire shape spec-compliant\n // under `exactOptionalPropertyTypes` (see chatStream catch).\n const code = chunk.code ?? undefined\n yield {\n type: EventType.RUN_ERROR,\n model: model || options.model,\n timestamp: Date.now(),\n message: chunk.message,\n ...(code !== undefined && { code }),\n error: {\n message: chunk.message,\n ...(code !== undefined && { code }),\n },\n }\n // RUN_ERROR is terminal — don't let the synthetic RUN_FINISHED\n // block fire after a top-level stream error event, and stop\n // processing further chunks so no in-flight lifecycle events\n // (TEXT_MESSAGE_CONTENT, TOOL_CALL_*) leak past the terminal\n // error. Mirrors the `response.failed` / `response.incomplete`\n // branches above which return after their RUN_ERROR emission.\n runFinishedEmitted = true\n return\n }\n }\n\n // Synthetic terminal RUN_FINISHED if the stream ended without a\n // response.completed event (e.g. truncated upstream connection). This\n // mirrors the chat-completions adapter's behavior so consumers always\n // see a terminal event for every started run.\n if (!runFinishedEmitted && aguiState.hasEmittedRunStarted) {\n yield* closeReasoning()\n if (hasEmittedTextMessageStart) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n }\n }\n // Omit `usage` entirely (vs `usage: undefined`) — the synthetic\n // RUN_FINISHED for truncated streams has no usage data, and AG-UI's\n // `RunFinishedEvent.usage` is optional without `| undefined` under\n // `exactOptionalPropertyTypes`.\n yield {\n type: EventType.RUN_FINISHED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: model || options.model,\n timestamp: Date.now(),\n finishReason: toolCallMetadata.size > 0 ? 'tool_calls' : 'stop',\n }\n }\n } catch (error: unknown) {\n // Narrow before logging: raw SDK errors can carry request metadata\n // (including auth headers) which we must never surface to user loggers.\n const errorPayload = toRunErrorPayload(\n error,\n `${this.name}.processStreamChunks failed`,\n )\n const rawEvent = toRunErrorRawEvent(error)\n options.logger.errors(`${this.name}.processStreamChunks fatal`, {\n error: errorPayload,\n source: `${this.name}.processStreamChunks`,\n })\n // Emit AG-UI RUN_ERROR with conditional `code` spread (see chatStream\n // catch for the rationale). `rawEvent` carries the provider's structured\n // error body when present.\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: errorPayload.message,\n ...(errorPayload.code !== undefined && { code: errorPayload.code }),\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: errorPayload.message,\n ...(errorPayload.code !== undefined && { code: errorPayload.code }),\n },\n }\n }\n }\n\n /**\n * Maps common TextOptions to Responses API request format.\n * Override this in subclasses to add provider-specific options.\n */\n protected mapOptionsToRequest(\n options: TextOptions<TProviderOptions>,\n ): Omit<ResponseCreateParams, 'stream'> {\n const input = this.convertMessagesToInput(options.messages)\n\n const tools = options.tools\n ? convertToolsToResponsesFormat(\n options.tools,\n this.makeStructuredOutputCompatible.bind(this),\n )\n : undefined\n\n const modelOptions = options.modelOptions\n\n // Native combined mode (issue #605): when the engine threads\n // `outputSchema` through TextOptions, the adapter declared\n // `supportsCombinedToolsAndSchema` and the schema is already JSON Schema\n // (pre-converted at the activity boundary). Wire it into `text.format`\n // alongside any `tools` — the Responses API supports both together and\n // emits the schema-constrained text on the natural final turn.\n const combinedSchema = options.outputSchema as\n | Record<string, unknown>\n | undefined\n const textFormat = combinedSchema\n ? {\n text: {\n format: {\n type: 'json_schema' as const,\n name: 'structured_output',\n schema: this.makeStructuredOutputCompatible(\n combinedSchema,\n Array.isArray(combinedSchema.required)\n ? (combinedSchema.required as Array<string>)\n : undefined,\n ),\n strict: true,\n },\n },\n }\n : undefined\n\n // `modelOptions` is the sole sampling surface: `temperature`, `top_p`, and\n // `max_output_tokens` live there (typed via OpenAISamplingOptions) and are\n // spread first. Engine-managed fields (`model`, `metadata`, `instructions`,\n // `input`, `tools`, `textFormat`) are layered on top afterward so they\n // always win over any same-named key a caller happened to put in\n // `modelOptions`.\n return {\n ...modelOptions,\n model: options.model,\n ...(options.metadata !== undefined && { metadata: options.metadata }),\n ...(() => {\n const prompts = normalizeSystemPrompts(options.systemPrompts)\n if (prompts.length === 0) return {}\n return { instructions: prompts.map((p) => p.content).join('\\n') }\n })(),\n input,\n // Conditional spread: `tools: undefined` would clobber any\n // modelOptions.tools the caller set above.\n ...(tools && tools.length > 0 && { tools }),\n ...(textFormat ?? {}),\n }\n }\n\n /**\n * The OpenAI Responses API supports `tools` and `text.format: json_schema`\n * together in a single streaming request (per issue #605). Subclasses\n * that route to providers without this capability should override.\n */\n supportsCombinedToolsAndSchema(): boolean {\n return true\n }\n\n /**\n * Converts ModelMessage[] to Responses API ResponseInput format.\n * Override this in subclasses for provider-specific message format quirks.\n *\n * Key differences from Chat Completions:\n * - Tool results use `function_call_output` type (not `tool` role)\n * - Assistant tool calls are `function_call` objects (not nested in `tool_calls`)\n * - User content uses `input_text`, `input_image`, `input_file` types\n * - System prompts go in `instructions`, not as messages\n */\n protected convertMessagesToInput(\n messages: Array<ModelMessage>,\n ): ResponseInput {\n const result: ResponseInput = []\n\n for (const message of messages) {\n // Handle tool messages - convert to FunctionToolCallOutput\n if (message.role === 'tool') {\n const toolContent = message.content\n const output: string | Array<ResponseFunctionCallOutputItem> =\n Array.isArray(toolContent)\n ? toolContent.map((part) => this.convertContentPartToInput(part))\n : typeof toolContent === 'string'\n ? toolContent\n : JSON.stringify(toolContent)\n result.push({\n type: 'function_call_output',\n call_id: message.toolCallId || '',\n output,\n })\n continue\n }\n\n // Handle assistant messages\n if (message.role === 'assistant') {\n if (message.thinking) {\n for (const thinking of message.thinking) {\n if (!thinking.signature) continue\n const packed = unpackResponsesReasoningSignature(thinking.signature)\n if (!packed?.id) continue\n result.push({\n type: 'reasoning',\n id: packed.id,\n ...(packed.encrypted_content\n ? { encrypted_content: packed.encrypted_content }\n : {}),\n summary: thinking.content\n ? [{ type: 'summary_text', text: thinking.content }]\n : [],\n })\n }\n }\n\n // If the assistant message has tool calls, add them as FunctionToolCall objects\n // Responses API expects arguments as a string (JSON string)\n if (message.toolCalls && message.toolCalls.length > 0) {\n for (const toolCall of message.toolCalls) {\n // Keep arguments as string for Responses API\n const argumentsString =\n typeof toolCall.function.arguments === 'string'\n ? toolCall.function.arguments\n : JSON.stringify(toolCall.function.arguments)\n const itemId = (\n toolCall.metadata as OpenAIResponsesToolCallMetadata | undefined\n )?.itemId\n\n result.push({\n type: 'function_call',\n call_id: toolCall.id,\n ...(itemId && { id: itemId }),\n name: toolCall.function.name,\n arguments: argumentsString,\n })\n }\n }\n\n // Add the assistant's text message if there is content\n if (message.content) {\n const contentStr = this.extractTextContent(message.content)\n if (contentStr) {\n result.push({\n type: 'message',\n role: 'assistant',\n content: contentStr,\n })\n }\n }\n\n continue\n }\n\n // Handle user messages (default case) — support multimodal content\n const contentParts = this.normalizeContent(message.content)\n const inputContent: Array<ResponseInputContent> = []\n\n for (const part of contentParts) {\n inputContent.push(this.convertContentPartToInput(part))\n }\n\n if (inputContent.length === 0) {\n // Fail loud rather than silently sending an empty user message —\n // mirrors the chat-completions adapter, where a paid-but-empty\n // request would mask the real intent (caller passed `null` content\n // or a normalize step dropped everything).\n throw new Error(\n `User message for ${this.name} has no content parts. ` +\n `Empty user messages would produce a paid request with no input; ` +\n `provide at least one text/image/audio/document part or omit the message.`,\n )\n }\n\n result.push({\n type: 'message',\n role: 'user',\n content: inputContent,\n })\n }\n\n return result\n }\n\n /**\n * Converts a ContentPart to Responses API input content item.\n * Handles text, image, audio, and document (PDF) content parts.\n * Override this in subclasses for additional content types or provider-specific metadata.\n */\n protected convertContentPartToInput(part: ContentPart): ResponseInputContent {\n switch (part.type) {\n case 'text':\n return {\n type: 'input_text',\n text: part.content,\n }\n case 'image': {\n const imageMetadata = part.metadata as\n | { detail?: 'auto' | 'low' | 'high' }\n | undefined\n if (part.source.type === 'url') {\n return {\n type: 'input_image',\n image_url: part.source.value,\n detail: imageMetadata?.detail || 'auto',\n }\n }\n // For base64 data, construct a data URI using the mimeType from\n // source. Default to a generic octet-stream MIME if the source\n // didn't supply one — letting `undefined` interpolate would produce\n // an invalid URI like \"data:undefined;base64,...\".\n const imageValue = part.source.value\n const imageMime = part.source.mimeType || 'application/octet-stream'\n const imageUrl = imageValue.startsWith('data:')\n ? imageValue\n : `data:${imageMime};base64,${imageValue}`\n return {\n type: 'input_image',\n image_url: imageUrl,\n detail: imageMetadata?.detail || 'auto',\n }\n }\n case 'audio': {\n if (part.source.type === 'url') {\n return {\n type: 'input_file',\n file_url: part.source.value,\n }\n }\n // Wrap raw base64 in a data URL — `input_file` rejects bare base64\n // payloads (matches the image branch above).\n // Default the MIME if missing so we never interpolate `undefined`.\n const audioValue = part.source.value\n const audioMime = part.source.mimeType || 'application/octet-stream'\n const audioFileData = audioValue.startsWith('data:')\n ? audioValue\n : `data:${audioMime};base64,${audioValue}`\n return {\n type: 'input_file',\n file_data: audioFileData,\n }\n }\n\n case 'document': {\n const documentMetadata = part.metadata as\n | { filename?: string; detail?: 'auto' | 'low' | 'high' }\n | undefined\n // Spread `detail` only when provided so the API applies its own\n // default ('auto'). The Responses API accepts 'auto' | 'low' | 'high',\n // but the pinned OpenAI SDK's `ResponseInputFile.detail` type still\n // lists only 'low' | 'high' — cast so 'auto' (a valid API value) can\n // pass through without a type error.\n const documentDetail =\n documentMetadata?.detail !== undefined\n ? { detail: documentMetadata.detail as 'low' | 'high' }\n : {}\n if (part.source.type === 'url') {\n // The Responses API fetches the PDF itself; filename and MIME\n // type are inferred from the response.\n return {\n type: 'input_file',\n file_url: part.source.value,\n ...documentDetail,\n }\n }\n // This adapter supports only PDF documents; anything else is\n // rejected. MIME types are case-insensitive and can carry\n // ;parameters (RFC 2045), so the type is normalized before comparing.\n const documentValue = part.source.value\n const documentMime = (\n (part.source.mimeType || 'application/pdf').split(';')[0] ?? ''\n )\n .trim()\n .toLowerCase()\n if (documentMime !== 'application/pdf') {\n throw new Error(\n `${this.name} document parts only support application/pdf ` +\n `(received ${documentMime})`,\n )\n }\n // A pre-wrapped data URL carries its own media type — validate it too.\n if (\n documentValue.startsWith('data:') &&\n !/^data:application\\/pdf[;,]/i.test(documentValue)\n ) {\n throw new Error(\n `${this.name} document parts only support application/pdf ` +\n `(received data URL with non-PDF media type)`,\n )\n }\n // Sniff the payload so a non-PDF labeled (or unlabeled) as PDF is\n // caught locally instead of by an opaque provider 400. Only base64\n // payloads are checked; a rare `data:` URL without `;base64` is left\n // to the server.\n const documentBase64 = documentValue.startsWith('data:')\n ? /;base64,/i.test(documentValue)\n ? documentValue.slice(documentValue.indexOf(',') + 1)\n : ''\n : documentValue\n if (documentBase64 && !documentBase64.startsWith(PDF_BASE64_MAGIC)) {\n throw new Error(\n `${this.name} document parts only support application/pdf ` +\n `(inline data does not start with the %PDF header)`,\n )\n }\n // Wrap raw base64 in a data URL — `input_file` rejects bare base64\n // payloads (matches the image and audio branches above).\n const documentFileData = documentValue.startsWith('data:')\n ? documentValue\n : `data:${documentMime};base64,${documentValue}`\n return {\n type: 'input_file',\n // The Responses API requires a filename alongside PDF `file_data`.\n filename: documentMetadata?.filename || 'document.pdf',\n file_data: documentFileData,\n ...documentDetail,\n }\n }\n\n case 'video':\n default:\n // OpenAI Responses API doesn't accept native video parts on this\n // path — surface as explicit unsupported error so callers see the\n // same message regardless of which content type leaked through.\n throw new Error(`Unsupported content part type: ${part.type}`)\n }\n }\n\n /**\n * Normalizes message content to an array of ContentPart.\n * Handles backward compatibility with string content.\n */\n protected normalizeContent(\n content: string | null | undefined | Array<ContentPart>,\n ): Array<ContentPart> {\n if (content === null || content === undefined) {\n return []\n }\n if (typeof content === 'string') {\n return [{ type: 'text', content: content }]\n }\n return content\n }\n\n /**\n * Extracts text content from a content value that may be string, null, or ContentPart array.\n */\n protected extractTextContent(\n content: string | null | undefined | Array<ContentPart>,\n ): string {\n if (content === null || content === undefined) {\n return ''\n }\n if (typeof content === 'string') {\n return content\n }\n // It's an array of ContentPart\n return content\n .filter((p) => p.type === 'text')\n .map((p) => p.content)\n .join('')\n }\n}\n"],"mappings":";;;;;;;;;;AAqCA,IAAM,mBAAmB;AAEzB,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,gCACP,IACA,kBACoB;CACpB,IAAI,CAAC,MAAM,CAAC,kBAAkB,OAAO,KAAA;CACrC,OAAO,KAAK,UAAU;EACpB,GAAI,KAAK,EAAE,GAAG,IAAI,CAAC;EACnB,GAAI,mBAAmB,EAAE,mBAAmB,iBAAiB,IAAI,CAAC;CACpE,CAAC;AACH;AAEA,SAAS,kCACP,WACyD;CACzD,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,SAAS;EAC5C,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO,KAAA;EAC9B,MAAM,KAAK,OAAO,OAAO,OAAO,WAAW,OAAO,KAAK,KAAA;EACvD,MAAM,oBACJ,OAAO,OAAO,sBAAsB,WAChC,OAAO,oBACP,KAAA;EACN,IAAI,CAAC,MAAM,CAAC,mBAAmB,OAAO,KAAA;EACtC,OAAO;GACL,GAAI,KAAK,EAAE,GAAG,IAAI,CAAC;GACnB,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;EACnD;CACF,QAAQ;EACN;CACF;AACF;AAEA,SAAS,kBACP,MACyD;CACzD,IAAI,CAAC,SAAS,IAAI,KAAK,KAAK,SAAS,aAAa,OAAO,KAAA;CACzD,MAAM,KAAK,OAAO,KAAK,OAAO,WAAW,KAAK,KAAK,KAAA;CACnD,MAAM,oBACJ,OAAO,KAAK,sBAAsB,WAC9B,KAAK,oBACL,KAAA;CACN,IAAI,CAAC,MAAM,CAAC,mBAAmB,OAAO,KAAA;CACtC,OAAO;EACL,GAAI,KAAK,EAAE,GAAG,IAAI,CAAC;EACnB,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;C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iB,mBACnB,MAAM,IAAI,MACR,GAAG,KAAK,KAAK,yDACE,aAAa,EAC9B;IAGF,IACE,cAAc,WAAW,OAAO,KAChC,CAAC,8BAA8B,KAAK,aAAa,GAEjD,MAAM,IAAI,MACR,GAAG,KAAK,KAAK,yFAEf;IAMF,MAAM,iBAAiB,cAAc,WAAW,OAAO,IACnD,YAAY,KAAK,aAAa,IAC5B,cAAc,MAAM,cAAc,QAAQ,GAAG,IAAI,CAAC,IAClD,KACF;IACJ,IAAI,kBAAkB,CAAC,eAAe,WAAW,gBAAgB,GAC/D,MAAM,IAAI,MACR,GAAG,KAAK,KAAK,+FAEf;IAIF,MAAM,mBAAmB,cAAc,WAAW,OAAO,IACrD,gBACA,QAAQ,aAAa,UAAU;IACnC,OAAO;KACL,MAAM;KAEN,UAAU,kBAAkB,YAAY;KACxC,WAAW;KACX,GAAG;IACL;GACF;GAGA,SAIE,MAAM,IAAI,MAAM,kCAAkC,KAAK,MAAM;EACjE;CACF;;;;;CAMA,iBACE,SACoB;EACpB,IAAI,YAAY,QAAQ,YAAY,KAAA,GAClC,OAAO,CAAC;EAEV,IAAI,OAAO,YAAY,UACrB,OAAO,CAAC;GAAE,MAAM;GAAiB;EAAQ,CAAC;EAE5C,OAAO;CACT;;;;CAKA,mBACE,SACQ;EACR,IAAI,YAAY,QAAQ,YAAY,KAAA,GAClC,OAAO;EAET,IAAI,OAAO,YAAY,UACrB,OAAO;EAGT,OAAO,QACJ,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,CAChC,KAAK,MAAM,EAAE,OAAO,CAAC,CACrB,KAAK,EAAE;CACZ;AACF"}
|
|
1
|
+
{"version":3,"file":"responses-text.js","names":[],"sources":["../../../src/adapters/responses-text.ts"],"sourcesContent":["import {\n EventType,\n fileReferenceFor,\n isFileSource,\n normalizeSystemPrompts,\n unsupportedFileSourceError,\n} from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport {\n toRunErrorPayload,\n toRunErrorRawEvent,\n} from '@tanstack/ai/adapter-internals'\nimport { generateId } from '@tanstack/ai-utils'\nimport { extractRequestOptions } from '../utils/request-options'\nimport {\n makeStructuredOutputCompatibleWithMap,\n warnStrictFallback,\n} from '../utils/schema-converter'\nimport { createToolInputNormalizer } from '../utils/tool-input-normalizer'\nimport type {\n OpenAIBaseTextAdapterOptions,\n StructuredOutputCompatibility,\n} from '../utils/schema-converter'\nimport { buildResponsesUsage } from '../usage'\nimport { convertToolsToResponsesFormat } from './responses-tool-converter'\nimport {\n hostedShellCallIds,\n readUserExecutedCall,\n userToolRequestItem,\n userToolResultItem,\n} from './responses-user-tools'\nimport type { OpenAIUserToolName } from './responses-user-tools'\nimport type OpenAI from 'openai'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type {\n Response,\n ResponseCreateParams,\n ResponseFunctionCallOutputItem,\n ResponseFunctionWebSearch,\n ResponseInput,\n ResponseInputContent,\n ResponseOutputMessage,\n ResponseOutputText,\n ResponseStreamEvent,\n} from 'openai/resources/responses/responses'\nimport type {\n ContentPart,\n DefaultMessageMetadataByModality,\n Modality,\n ModelMessage,\n AdapterYieldChunk,\n ProviderExecutedToolMetadata,\n ProviderExecutedToolSource,\n TextOptions,\n} from '@tanstack/ai'\n\n// Base64 encoding of the '%PDF' file header — every PDF payload starts with\n// these bytes, so inline document data must begin with this prefix.\nconst PDF_BASE64_MAGIC = 'JVBERi'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction readURLCitation(\n value: unknown,\n): ResponseOutputText.URLCitation | undefined {\n if (!isRecord(value) || value.type !== 'url_citation') return undefined\n if (\n typeof value.url !== 'string' ||\n typeof value.title !== 'string' ||\n typeof value.start_index !== 'number' ||\n typeof value.end_index !== 'number'\n ) {\n return undefined\n }\n return {\n type: 'url_citation',\n url: value.url,\n title: value.title,\n start_index: value.start_index,\n end_index: value.end_index,\n }\n}\n\nfunction readWebSearchCall(\n value: unknown,\n): ResponseFunctionWebSearch | undefined {\n if (!isRecord(value) || value.type !== 'web_search_call') return undefined\n if (\n typeof value.id !== 'string' ||\n typeof value.status !== 'string' ||\n !isRecord(value.action) ||\n typeof value.action.type !== 'string'\n ) {\n return undefined\n }\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- the runtime guard above validates the stable fields while the SDK union preserves provider-specific action fields\n return value as unknown as ResponseFunctionWebSearch\n}\n\nfunction collectWebSearchSources(\n item: ResponseFunctionWebSearch,\n citations: ReadonlyArray<ResponseOutputText.URLCitation>,\n): Array<ProviderExecutedToolSource> {\n const sources = new Map<string, ProviderExecutedToolSource>()\n const add = (url: unknown, title?: unknown) => {\n if (typeof url !== 'string' || url.length === 0) return\n const existing = sources.get(url)\n if (existing) {\n if (!existing.title && typeof title === 'string' && title.length > 0) {\n existing.title = title\n }\n return\n }\n sources.set(url, {\n url,\n ...(typeof title === 'string' && title.length > 0 ? { title } : {}),\n })\n }\n\n if (item.action.type === 'search') {\n for (const source of item.action.sources ?? []) {\n add(source.url)\n }\n }\n for (const citation of citations) {\n add(citation.url, citation.title)\n }\n\n return [...sources.values()]\n}\n\nfunction packResponsesReasoningSignature(\n id: string | undefined,\n encryptedContent: string | undefined,\n): string | undefined {\n if (!id && !encryptedContent) return undefined\n return JSON.stringify({\n ...(id ? { id } : {}),\n ...(encryptedContent ? { encrypted_content: encryptedContent } : {}),\n })\n}\n\nfunction unpackResponsesReasoningSignature(\n signature: string,\n): { id?: string; encrypted_content?: string } | undefined {\n try {\n const parsed: unknown = JSON.parse(signature)\n if (!isRecord(parsed)) return undefined\n const id = typeof parsed.id === 'string' ? parsed.id : undefined\n const encrypted_content =\n typeof parsed.encrypted_content === 'string'\n ? parsed.encrypted_content\n : undefined\n if (!id && !encrypted_content) return undefined\n return {\n ...(id ? { id } : {}),\n ...(encrypted_content ? { encrypted_content } : {}),\n }\n } catch {\n return undefined\n }\n}\n\nfunction readReasoningItem(\n item: unknown,\n): { id?: string; encrypted_content?: string } | undefined {\n if (!isRecord(item) || item.type !== 'reasoning') return undefined\n const id = typeof item.id === 'string' ? item.id : undefined\n const encrypted_content =\n typeof item.encrypted_content === 'string'\n ? item.encrypted_content\n : undefined\n if (!id && !encrypted_content) return undefined\n return {\n ...(id ? { id } : {}),\n ...(encrypted_content ? { encrypted_content } : {}),\n }\n}\n\n/**\n * Provider-specific metadata that preserves the Responses API output item ID.\n *\n * Responses function calls have two identifiers: `call_id` correlates the\n * function output with the call, while `id` identifies the output item itself.\n * TanStack AI uses `call_id` as the canonical tool-call ID and carries the\n * item ID here so stateless follow-up requests can replay both values.\n */\nexport interface OpenAIResponsesToolCallMetadata extends ProviderExecutedToolMetadata {\n itemId?: string\n /** Set for shell, local_shell, and apply_patch calls the app must run. */\n openaiUserTool?: OpenAIUserToolName\n /** Shell `action.max_output_length`, echoed on `shell_call_output`. */\n maxOutputLength?: number | null\n openai?: {\n webSearchCall: ResponseFunctionWebSearch\n urlCitations: Array<ResponseOutputText.URLCitation>\n assistantMessage?: ResponseOutputMessage\n }\n}\n\ninterface StreamedFunctionCallMetadata {\n callId: string\n index: number\n name: string\n started: boolean\n ended?: boolean\n pendingArguments?: string | undefined\n}\n\n/**\n * The pre-2025-07 spec name for `response.reasoning_text.delta`. Removed from\n * the openai SDK, but OpenAI-compatible providers frozen on the older spec\n * (e.g. Amazon Bedrock's Mantle endpoint serving Gemma) still emit it.\n */\ninterface LegacyReasoningDeltaEvent {\n type: 'response.reasoning.delta'\n delta?: unknown\n}\n\n/**\n * Shared implementation of the OpenAI Responses API. Holds the stream-event\n * accumulator + AG-UI lifecycle and calls the OpenAI SDK directly. Subclasses\n * (today: ai-openai) construct an OpenAI client with their provider-specific\n * `baseURL` / headers and pass it in.\n */\nexport abstract class OpenAIBaseResponsesTextAdapter<\n TModel extends string,\n TProviderOptions extends Record<string, unknown> = Record<string, unknown>,\n TInputModalities extends ReadonlyArray<Modality> = ReadonlyArray<Modality>,\n TMessageMetadata extends DefaultMessageMetadataByModality =\n DefaultMessageMetadataByModality,\n TToolCapabilities extends ReadonlyArray<string> = ReadonlyArray<string>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n TMessageMetadata,\n TToolCapabilities,\n OpenAIResponsesToolCallMetadata\n> {\n override readonly kind = 'text' as const\n readonly name: string\n protected client: OpenAI\n\n /** See {@link OpenAIBaseTextAdapterOptions.strictFallbackWarning}. */\n protected readonly strictFallbackWarning: boolean\n\n constructor(\n model: TModel,\n name: string,\n client: OpenAI,\n options: OpenAIBaseTextAdapterOptions = {},\n ) {\n super({}, model)\n this.name = name\n this.client = client\n this.strictFallbackWarning = options.strictFallbackWarning ?? true\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n // Key streamed state by output item ID because argument deltas reference\n // `item_id`. The state separately retains `call_id`, which is the public\n // tool-call ID and the correlation key for function_call_output.\n const toolCallMetadata = new Map<string, StreamedFunctionCallMetadata>()\n\n // AG-UI lifecycle tracking. Honor a caller-supplied `runId` (as `threadId`\n // already does) so the emitted RUN_STARTED matches the id the caller keys\n // durability by — e.g. a summarize run threading the client's runId through\n // for mid-run reload resumability. Falls back to a generated id.\n const aguiState = {\n runId: options.runId ?? generateId(this.name),\n threadId: options.threadId ?? generateId(this.name),\n messageId: generateId(this.name),\n hasEmittedRunStarted: false,\n }\n\n try {\n // mapOptionsToRequest can throw on caller-side validation failures\n // (empty user content, unsupported parts, webSearchTool() rejection in\n // the OpenRouter override). Keep it inside the try so those failures\n // surface as RUN_ERROR events instead of iterator throws.\n const requestParams = this.mapOptionsToRequest(options)\n options.logger.request(\n `activity=chat provider=${this.name} model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n { provider: this.name, model: this.model },\n )\n const response = await this.client.responses.create(\n {\n ...requestParams,\n stream: true,\n },\n extractRequestOptions(options.request),\n )\n\n yield* this.processStreamChunks(\n response,\n toolCallMetadata,\n options,\n aguiState,\n )\n } catch (error: unknown) {\n // Narrow before logging: raw SDK errors can carry request metadata\n // (including auth headers) which we must never surface to user loggers.\n const errorPayload = toRunErrorPayload(\n error,\n `${this.name}.chatStream failed`,\n )\n const rawEvent = toRunErrorRawEvent(error)\n\n // Emit RUN_STARTED if not yet emitted\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: options.model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n // Emit AG-UI RUN_ERROR. Conditional `code` spread keeps the wire\n // shape spec-compliant under `exactOptionalPropertyTypes`: AG-UI's\n // `RunErrorEvent.code` is `string?` (absent vs explicit `undefined`\n // matter), so we omit the key when there's no code.\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: errorPayload.message,\n code: errorPayload.code,\n // Forward the provider's structured error body when present (see\n // toRunErrorRawEvent); omitted otherwise.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: errorPayload.message,\n code: errorPayload.code,\n },\n }\n\n options.logger.errors(`${this.name}.chatStream fatal`, {\n error: errorPayload,\n source: `${this.name}.chatStream`,\n })\n }\n }\n\n /**\n * Generate structured output using the provider's native JSON Schema response format.\n * Uses stream: false to get the complete response in one call.\n *\n * OpenAI-compatible Responses APIs have strict requirements for structured output:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for all objects\n *\n * The outputSchema is already JSON Schema (converted in the ai layer).\n * We apply provider-specific transformations for structured output compatibility.\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const requestParams = this.mapOptionsToRequest(chatOptions)\n\n // Apply provider-specific transformations for structured output compatibility\n const jsonSchema = this.makeStructuredOutputCompatible(\n outputSchema,\n outputSchema.required,\n )\n\n try {\n // Strip streaming-only fields a subclass override of mapOptionsToRequest\n // might have returned (parallel to chat-completions's structuredOutput\n // cleanup) — sending stream_options to a non-streaming call is a 4xx.\n const {\n stream: _stream,\n stream_options: _streamOptions,\n ...cleanParams\n } = requestParams as Record<string, unknown>\n void _stream\n void _streamOptions\n chatOptions.logger.request(\n `activity=structuredOutput provider=${this.name} model=${this.model} messages=${chatOptions.messages.length}`,\n { provider: this.name, model: this.model },\n )\n const response = await this.client.responses.create(\n {\n ...(cleanParams as Omit<ResponseCreateParams, 'stream'>),\n stream: false,\n // Configure structured output via text.format\n text: {\n format: {\n type: 'json_schema',\n name: 'structured_output',\n schema: jsonSchema,\n strict: true,\n },\n },\n },\n extractRequestOptions(chatOptions.request),\n )\n\n // Extract text content from the response. `stream: false` narrows the\n // SDK return type to `Response`, but the explicit annotation makes\n // that contract local rather than relying on inference through the\n // overloaded `client.responses.create` signature.\n const rawText = this.extractTextFromResponse(response satisfies Response)\n\n // Fail loud on empty content rather than letting it cascade into a\n // confusing \"Failed to parse JSON. Content: \" error — the root cause\n // (the model returned no text content for the structured request) is\n // then visible in logs. Mirrors the chat-completions sibling.\n if (rawText.length === 0) {\n throw new Error(\n `${this.name}.structuredOutput: response contained no content`,\n )\n }\n\n // Parse the JSON response\n let parsed: unknown\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to parse structured output as JSON. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n\n // Provider-specific post-parse shaping (default passthrough). Null-widening\n // from strict mode is undone by the engine, not here.\n const transformed = this.transformStructuredOutput(parsed)\n\n // Surface usage so non-stream structured paths (and\n // fallbackStructuredOutputStream) can forward tokens to middleware.\n const usage = buildResponsesUsage(response.usage)\n return {\n data: transformed,\n rawText,\n ...(usage && { usage }),\n }\n } catch (error: unknown) {\n // Narrow before logging: raw SDK errors can carry request metadata\n // (including auth headers) which we must never surface to user loggers.\n chatOptions.logger.errors(`${this.name}.structuredOutput fatal`, {\n error: toRunErrorPayload(error, `${this.name}.structuredOutput failed`),\n source: `${this.name}.structuredOutput`,\n })\n throw error\n }\n }\n\n /**\n * Stream structured output via the Responses API: single request with\n * `text.format: json_schema` + `stream: true`. Consumes Responses-API\n * events (`response.output_text.delta`, `response.reasoning_text.delta`,\n * `response.reasoning_summary_text.delta`, the legacy\n * `response.reasoning.delta`, `response.refusal.delta`,\n * `response.completed`, `response.failed`) and re-emits the standard AG-UI\n * lifecycle ending with `CUSTOM 'structured-output.complete'`.\n *\n * Tools are stripped (structured output is mutually exclusive with tool\n * calls in this path). Reasoning text is accumulated and surfaced both as\n * REASONING_* lifecycle events during the stream and on the terminal\n * CUSTOM event's `value.reasoning`.\n */\n async *structuredOutputStream(\n options: StructuredOutputOptions<TProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const { chatOptions, outputSchema } = options\n const requestParams = this.mapOptionsToRequest(chatOptions)\n\n const jsonSchema = this.makeStructuredOutputCompatible(\n outputSchema,\n outputSchema.required,\n )\n\n const aguiState = {\n runId: generateId(this.name),\n threadId: chatOptions.threadId ?? generateId(this.name),\n messageId: generateId(this.name),\n hasEmittedRunStarted: false,\n }\n\n let accumulatedContent = ''\n let accumulatedReasoning = ''\n let hasEmittedTextMessageStart = false\n let reasoningMessageId: string | undefined\n let stepId: string | undefined\n let hasClosedReasoning = false\n let model: string = chatOptions.model\n let usage: OpenAI.Responses.Response['usage'] | undefined\n let responseCompleted = false\n\n const closeReasoning = function* (this: {\n name: string\n }): Generator<AdapterYieldChunk> {\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n if (stepId) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n content: accumulatedReasoning,\n }\n }\n reasoningMessageId = undefined\n stepId = undefined\n hasClosedReasoning = false\n }\n }.bind(this)\n\n const openReasoning = function* (this: {\n name: string\n }): Generator<AdapterYieldChunk> {\n if (reasoningMessageId) return\n reasoningMessageId = generateId(this.name)\n stepId = generateId(this.name)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n stepType: 'thinking',\n }\n }.bind(this)\n\n try {\n const { tools: _tools, ...cleanParams } = requestParams\n void _tools\n\n chatOptions.logger.request(\n `activity=structuredOutputStream provider=${this.name} model=${this.model} messages=${chatOptions.messages.length}`,\n { provider: this.name, model: this.model },\n )\n\n const stream: AsyncIterable<\n ResponseStreamEvent | LegacyReasoningDeltaEvent\n > = await this.client.responses.create(\n {\n ...cleanParams,\n stream: true,\n text: {\n format: {\n type: 'json_schema',\n name: 'structured_output',\n schema: jsonSchema,\n strict: true,\n },\n },\n },\n extractRequestOptions(chatOptions.request),\n )\n\n for await (const chunk of stream) {\n chatOptions.logger.provider(\n `provider=${this.name} type=${chunk.type}`,\n { provider: this.name, type: chunk.type },\n )\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model,\n timestamp: Date.now(),\n parentRunId: chatOptions.parentRunId,\n }\n }\n\n if (\n chunk.type === 'response.created' ||\n chunk.type === 'response.in_progress'\n ) {\n const responseModel = (chunk as { response?: { model?: string } })\n .response?.model\n if (responseModel) model = responseModel\n continue\n }\n\n if (chunk.type === 'response.refusal.delta') {\n const delta =\n typeof (chunk as { delta?: unknown }).delta === 'string'\n ? (chunk as { delta: string }).delta\n : ''\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message: `Model refused: ${delta}`,\n code: 'refusal',\n error: { message: `Model refused: ${delta}`, code: 'refusal' },\n }\n return\n }\n\n if (\n chunk.type === 'response.reasoning_text.delta' ||\n chunk.type === 'response.reasoning_summary_text.delta' ||\n chunk.type === 'response.reasoning.delta'\n ) {\n const raw = (chunk as { delta?: unknown }).delta\n const reasoningDelta = Array.isArray(raw)\n ? raw.join('')\n : typeof raw === 'string'\n ? raw\n : ''\n if (!reasoningDelta) continue\n yield* openReasoning()\n // openReasoning() guarantees reasoningMessageId is set on first call;\n // TS can't see through the generator side-effect.\n if (!reasoningMessageId) continue\n accumulatedReasoning += reasoningDelta\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: reasoningDelta,\n model,\n timestamp: Date.now(),\n }\n continue\n }\n\n if (chunk.type === 'response.output_text.delta') {\n const raw = (chunk as { delta?: unknown }).delta\n const textDelta = Array.isArray(raw)\n ? raw.join('')\n : typeof raw === 'string'\n ? raw\n : ''\n if (!textDelta) continue\n\n yield* closeReasoning()\n\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n accumulatedContent += textDelta\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: aguiState.messageId,\n model,\n timestamp: Date.now(),\n delta: textDelta,\n content: accumulatedContent,\n }\n continue\n }\n\n if (chunk.type === 'response.completed') {\n responseCompleted = true\n const response = chunk.response\n if (response.usage) usage = response.usage\n if (response.model) model = response.model\n // Terminal event: do not wait for the HTTP body to close (#1445).\n break\n }\n\n if (chunk.type === 'response.failed') {\n const response = (\n chunk as {\n response?: { error?: { message?: string; code?: string } }\n }\n ).response\n const message =\n response?.error?.message || 'Responses API stream failed'\n const code = response?.error?.code\n // Conditional `code` spread keeps the wire shape spec-compliant\n // under `exactOptionalPropertyTypes` (see chatStream catch).\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message,\n ...(code !== undefined && { code }),\n error: { message, ...(code !== undefined && { code }) },\n }\n return\n }\n }\n\n yield* closeReasoning()\n\n if (hasEmittedTextMessageStart) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: aguiState.messageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n if (!responseCompleted) {\n const message = 'Response stream ended before response.completed'\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message,\n code: 'incomplete-stream',\n error: { message, code: 'incomplete-stream' },\n }\n return\n }\n\n if (accumulatedContent.length === 0) {\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message: `${this.name}.structuredOutputStream: response contained no content`,\n code: 'empty-response',\n error: {\n message: `${this.name}.structuredOutputStream: response contained no content`,\n code: 'empty-response',\n },\n }\n return\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(accumulatedContent)\n } catch {\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message: `Failed to parse structured output as JSON. Content: ${accumulatedContent.slice(0, 200)}${accumulatedContent.length > 200 ? '...' : ''}`,\n code: 'parse-error',\n error: {\n message: 'Failed to parse structured output as JSON',\n code: 'parse-error',\n },\n }\n return\n }\n\n // Route through the same hook as the non-streaming path (default\n // passthrough). Engine un-widens nulls; the streaming path must not strip\n // them blindly either.\n const transformed = this.transformStructuredOutput(parsed)\n\n yield {\n type: EventType.CUSTOM,\n name: 'structured-output.complete',\n value: {\n object: transformed,\n raw: accumulatedContent,\n ...(accumulatedReasoning ? { reasoning: accumulatedReasoning } : {}),\n },\n model,\n timestamp: Date.now(),\n }\n\n yield {\n type: EventType.RUN_FINISHED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n ...(usage && {\n usage: buildResponsesUsage(usage),\n }),\n }\n } catch (error: unknown) {\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model,\n timestamp: Date.now(),\n parentRunId: chatOptions.parentRunId,\n }\n }\n\n const isAbort = this.isAbortError(error)\n const errorPayload = toRunErrorPayload(\n error,\n `${this.name}.structuredOutputStream failed`,\n )\n\n // Conditional `code` spread keeps the wire shape spec-compliant under\n // `exactOptionalPropertyTypes` (see chatStream catch).\n const resolvedCode = isAbort ? 'aborted' : errorPayload.code\n const rawEvent = isAbort ? undefined : toRunErrorRawEvent(error)\n yield {\n type: EventType.RUN_ERROR,\n runId: aguiState.runId,\n model,\n timestamp: Date.now(),\n message: errorPayload.message,\n ...(resolvedCode !== undefined && { code: resolvedCode }),\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: errorPayload.message,\n ...(resolvedCode !== undefined && { code: resolvedCode }),\n },\n }\n\n chatOptions.logger.errors(`${this.name}.structuredOutputStream fatal`, {\n error: errorPayload,\n source: `${this.name}.structuredOutputStream`,\n })\n }\n }\n\n /**\n * Cross-SDK abort detection for `structuredOutputStream`. Mirrors the\n * Chat Completions base; subclasses with proprietary error types override.\n */\n protected isAbortError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false\n const e = error as { name?: unknown; code?: unknown }\n return (\n e.name === 'APIUserAbortError' ||\n e.name === 'AbortError' ||\n e.code === 'ERR_CANCELED'\n )\n }\n\n /**\n * Strict conversion plus the inverse null-widening map for this request.\n * Override this when schema conversion changes, so tool-input undo matches\n * the wire schema.\n */\n protected makeStructuredOutputCompatibleWithMap(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n ): StructuredOutputCompatibility {\n return makeStructuredOutputCompatibleWithMap(schema, originalRequired)\n }\n\n /**\n * Applies provider-specific transformations for structured output compatibility.\n * Override `makeStructuredOutputCompatibleWithMap` when you need the inverse map\n * to match the wire schema.\n */\n protected makeStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n ): Record<string, any> {\n return this.makeStructuredOutputCompatibleWithMap(schema, originalRequired)\n .schema\n }\n\n /**\n * Final shaping pass applied to parsed structured-output JSON before it is\n * returned to the caller. Default is a passthrough.\n *\n * Provider `null`s are no longer stripped here: strict-mode null-widening is\n * now undone precisely by the engine (`undoNullWidening`, driven by the\n * schema's null-widening map) the moment the result is captured, so a blind\n * `transformNullsToUndefined` at the adapter would only destroy genuine\n * `.nullable()` nulls. Subclasses may still override to remap or reshape the\n * provider's structured output.\n */\n protected transformStructuredOutput(parsed: unknown): unknown {\n return parsed\n }\n\n /**\n * Extract text content from a non-streaming Responses API response.\n * Override this in subclasses for provider-specific response shapes.\n */\n protected extractTextFromResponse(response: Response): string {\n let textContent = ''\n let refusal: string | undefined\n let sawMessageItem = false\n const observedItemTypes = new Set<string>()\n\n for (const item of response.output) {\n observedItemTypes.add(item.type)\n if (item.type === 'message') {\n sawMessageItem = true\n for (const part of item.content) {\n // Cast off the discriminated union before the type discrimination\n // so future SDK variants (e.g. `output_audio`, `output_image`) hit\n // the explicit error path rather than being misreported as refusals\n // when they get added to the union. Mirrors the streaming side's\n // handleContentPart.\n const partType = (part as { type: string }).type\n if (partType === 'output_text') {\n textContent += (part as { text?: string }).text ?? ''\n } else if (partType === 'refusal') {\n const refusalText = (part as { refusal?: string }).refusal\n refusal = refusalText || refusal || 'Refused without explanation'\n } else {\n throw new Error(\n `${this.name}.extractTextFromResponse: unsupported message content part type \"${partType}\"`,\n )\n }\n }\n }\n }\n\n // Surface refusals as an explicit error so callers don't see a generic\n // \"Failed to parse structured output as JSON. Content: \" when the model\n // refused for safety / content-policy reasons.\n if (!textContent && refusal !== undefined) {\n const err = new Error(`Model refused to respond: ${refusal}`)\n ;(err as Error & { code?: string }).code = 'refusal'\n throw err\n }\n\n // Response had items but none carried message text (e.g. only\n // function_call or reasoning items). Surface that explicitly so a\n // downstream structured-output caller doesn't see a misleading\n // \"Failed to parse JSON. Content: \" from an empty string.\n if (!textContent && response.output.length > 0 && !sawMessageItem) {\n throw new Error(\n `${this.name}.extractTextFromResponse: response.output contained items of type(s) [${[...observedItemTypes].sort().join(', ')}] but no message text — the model returned a non-text response`,\n )\n }\n\n return textContent\n }\n\n /**\n * Processes streamed chunks from the Responses API and yields AG-UI events.\n * Override this in subclasses to handle provider-specific stream behavior.\n *\n * Handles the following event types:\n * - response.created / response.incomplete / response.failed\n * - response.output_text.delta\n * - response.reasoning_text.delta\n * - response.reasoning.delta (the legacy type used before response.reasoning_text.delta)\n * - response.reasoning_summary_text.delta\n * - response.content_part.added / response.content_part.done\n * - response.output_item.added\n * - response.function_call_arguments.delta / response.function_call_arguments.done\n * - response.completed\n * - error\n */\n protected async *processStreamChunks(\n stream: AsyncIterable<ResponseStreamEvent | LegacyReasoningDeltaEvent>,\n toolCallMetadata: Map<string, StreamedFunctionCallMetadata>,\n options: TextOptions<TProviderOptions>,\n aguiState: {\n runId: string\n threadId: string\n messageId: string\n hasEmittedRunStarted: boolean\n },\n ): AsyncIterable<AdapterYieldChunk> {\n const normalizeToolInput = createToolInputNormalizer(\n options.tools,\n (schema, required) =>\n this.makeStructuredOutputCompatibleWithMap(schema, required),\n )\n let accumulatedContent = ''\n let accumulatedReasoning = ''\n\n // Track if we've been streaming deltas to avoid duplicating content from done events\n let hasStreamedContentDeltas = false\n let hasStreamedReasoningDeltas = false\n\n // Preserve response metadata across events\n let model: string = options.model\n\n // AG-UI lifecycle tracking\n let stepId: string | null = null\n let hasEmittedTextMessageStart = false\n let reasoningMessageId: string | undefined\n let reasoningItemId: string | undefined\n let reasoningEncryptedContent: string | undefined\n let closedReasoningStepId: string | undefined\n let hasClosedReasoning = false\n // Track whether we've emitted a terminal RUN_FINISHED so the\n // end-of-stream fallback below knows to synthesise one when the upstream\n // cuts off without a response.completed event.\n let runFinishedEmitted = false\n\n const providerWebSearchCalls = new Map<\n string,\n {\n item: ResponseFunctionWebSearch\n index: number\n started: boolean\n }\n >()\n const webSearchCitations: Array<ResponseOutputText.URLCitation> = []\n\n const adapterName = this.name\n const emitModel = () => model || options.model\n\n const recordProviderWebSearchCall = (value: unknown, index: number) => {\n const item = readWebSearchCall(value)\n if (!item) return\n const existing = providerWebSearchCalls.get(item.id)\n if (existing) {\n existing.item = item\n existing.index = index\n } else {\n providerWebSearchCalls.set(item.id, {\n item,\n index,\n started: false,\n })\n }\n }\n\n const emitProviderWebSearchCalls = function* (\n assistantMessage?: ResponseOutputMessage,\n completedOnly = false,\n ): Generator<AdapterYieldChunk> {\n for (const entry of providerWebSearchCalls.values()) {\n if (\n entry.started ||\n (completedOnly && entry.item.status !== 'completed')\n ) {\n continue\n }\n\n // Citations belong to the whole response. Give a call only the\n // citations whose URL is in its own action.sources.\n // ponytail: exact URL match; normalize URLs if the two ever differ.\n const callUrls = new Set(\n entry.item.action.type === 'search'\n ? (entry.item.action.sources ?? []).map((source) => source.url)\n : [],\n )\n const citations = webSearchCitations.filter((citation) =>\n callUrls.has(citation.url),\n )\n const metadata: OpenAIResponsesToolCallMetadata = {\n itemId: entry.item.id,\n providerExecuted: true,\n sources: collectWebSearchSources(entry.item, citations),\n openai: {\n webSearchCall: entry.item,\n urlCitations: citations,\n ...(assistantMessage ? { assistantMessage } : {}),\n },\n }\n\n entry.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: entry.item.id,\n toolCallName: 'web_search',\n toolName: 'web_search',\n parentMessageId: aguiState.messageId,\n model: emitModel(),\n timestamp: Date.now(),\n index: entry.index,\n metadata,\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: entry.item.id,\n toolCallName: 'web_search',\n toolName: 'web_search',\n model: emitModel(),\n timestamp: Date.now(),\n input: entry.item.action,\n }\n }\n }\n\n const openReasoning = function* (): Generator<AdapterYieldChunk> {\n if (reasoningMessageId) return\n reasoningMessageId = generateId(adapterName)\n stepId = generateId(adapterName)\n const timestamp = Date.now()\n const currentModel = emitModel()\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model: currentModel,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model: currentModel,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model: currentModel,\n timestamp,\n stepType: 'thinking',\n }\n }\n\n const captureReasoningItem = (item: unknown) => {\n const parsed = readReasoningItem(item)\n if (!parsed) return\n if (parsed.id) reasoningItemId = parsed.id\n if (parsed.encrypted_content) {\n reasoningEncryptedContent = parsed.encrypted_content\n }\n }\n\n const closeReasoning = function* (): Generator<AdapterYieldChunk> {\n if (!reasoningMessageId || hasClosedReasoning) return\n hasClosedReasoning = true\n const timestamp = Date.now()\n const currentModel = emitModel()\n const signature = packResponsesReasoningSignature(\n reasoningItemId,\n reasoningEncryptedContent,\n )\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model: currentModel,\n timestamp,\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model: currentModel,\n timestamp,\n }\n if (stepId) {\n closedReasoningStepId = stepId\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model: currentModel,\n timestamp,\n content: accumulatedReasoning,\n ...(signature ? { signature } : {}),\n }\n }\n reasoningMessageId = undefined\n reasoningItemId = undefined\n reasoningEncryptedContent = undefined\n stepId = null\n hasClosedReasoning = false\n accumulatedReasoning = ''\n }\n\n const userToolChunks = (\n item: unknown,\n outputIndex: number,\n bareShell: boolean,\n ): Array<AdapterYieldChunk> => {\n const call = readUserExecutedCall(item, { bareShell })\n if (!call || toolCallMetadata.get(call.callId)?.ended) return []\n const tracked = toolCallMetadata.get(call.callId) ?? {\n callId: call.callId,\n index: outputIndex,\n name: call.name,\n started: false,\n }\n toolCallMetadata.set(call.callId, tracked)\n tracked.started = true\n tracked.ended = true\n tracked.name = call.name\n const timestamp = Date.now()\n const modelName = model || options.model\n const metadata: OpenAIResponsesToolCallMetadata = {\n openaiUserTool: call.name,\n ...(call.itemId ? { itemId: call.itemId } : {}),\n ...(call.maxOutputLength !== undefined\n ? { maxOutputLength: call.maxOutputLength }\n : {}),\n }\n return [\n {\n type: EventType.TOOL_CALL_START,\n toolCallId: call.callId,\n toolCallName: call.name,\n toolName: call.name,\n parentMessageId: aguiState.messageId,\n model: modelName,\n timestamp,\n index: outputIndex,\n metadata,\n },\n {\n type: EventType.TOOL_CALL_END,\n toolCallId: call.callId,\n toolCallName: call.name,\n toolName: call.name,\n model: modelName,\n timestamp,\n input: call.input,\n },\n ]\n }\n\n const emitReasoningDelta = function* (\n text: string,\n ): Generator<AdapterYieldChunk> {\n if (!text) return\n yield* openReasoning()\n if (!reasoningMessageId) return\n accumulatedReasoning += text\n hasStreamedReasoningDeltas = true\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: text,\n model: emitModel(),\n timestamp: Date.now(),\n }\n }\n\n try {\n for await (const chunk of stream) {\n options.logger.provider(`provider=${this.name} type=${chunk.type}`, {\n provider: this.name,\n type: chunk.type,\n })\n\n // Emit RUN_STARTED on first chunk\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: model || options.model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n const handleContentPart = (contentPart: {\n type: string\n text?: string\n refusal?: string\n }): AdapterYieldChunk => {\n if (contentPart.type === 'output_text') {\n accumulatedContent += contentPart.text || ''\n return {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n delta: contentPart.text || '',\n content: accumulatedContent,\n }\n }\n\n // Either a real refusal or an unknown content_part type. Surface\n // the part type in the error so unknown parts are debuggable\n // instead of being misreported as \"Unknown refusal\".\n const isRefusal = contentPart.type === 'refusal'\n const message = isRefusal\n ? contentPart.refusal || 'Refused without explanation'\n : `Unsupported response content_part type: ${contentPart.type}`\n const code = isRefusal ? 'refusal' : contentPart.type\n return {\n type: EventType.RUN_ERROR,\n model: model || options.model,\n timestamp: Date.now(),\n message,\n code,\n error: { message, code },\n }\n }\n\n // Capture model metadata from any of these events (created starts\n // the run; failed/incomplete signal terminal failure).\n if (\n chunk.type === 'response.created' ||\n chunk.type === 'response.incomplete' ||\n chunk.type === 'response.failed'\n ) {\n model = chunk.response.model\n }\n\n // response.created marks the start of a fresh run — safe to reset\n // the per-run accumulators here.\n if (chunk.type === 'response.created') {\n hasStreamedContentDeltas = false\n hasStreamedReasoningDeltas = false\n hasEmittedTextMessageStart = false\n reasoningMessageId = undefined\n hasClosedReasoning = false\n stepId = null\n accumulatedContent = ''\n accumulatedReasoning = ''\n }\n\n // response.failed and response.incomplete are TERMINAL events for\n // the current response. Close any open AG-UI message lifecycle FIRST\n // so consumers tracking start/end pairs don't see an unbalanced\n // TEXT_MESSAGE_START. Then surface the error and mark the run as\n // finished so the post-loop synthetic terminal block doesn't emit\n // a duplicate RUN_FINISHED on top of RUN_ERROR.\n if (\n chunk.type === 'response.failed' ||\n chunk.type === 'response.incomplete'\n ) {\n if (chunk.type === 'response.incomplete') {\n for (const [index, item] of (\n chunk.response.output ?? []\n ).entries()) {\n recordProviderWebSearchCall(item, index)\n }\n yield* emitProviderWebSearchCalls(undefined, true)\n }\n yield* closeReasoning()\n if (hasEmittedTextMessageStart) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: aguiState.messageId,\n model: chunk.response.model,\n timestamp: Date.now(),\n }\n hasEmittedTextMessageStart = false\n }\n // Coalesce error + incomplete_details into a single RUN_ERROR\n // payload — emitting two distinct events for one terminal upstream\n // event would force consumers to handle a non-existent ordering.\n const errorMessage =\n chunk.response.error?.message ||\n chunk.response.incomplete_details?.reason ||\n (chunk.type === 'response.failed'\n ? 'Response failed'\n : 'Response ended incomplete')\n const errorCode =\n chunk.response.error?.code ??\n (chunk.response.incomplete_details ? 'incomplete' : undefined) ??\n undefined\n // Always emit RUN_ERROR for terminal failure events, even when the\n // upstream omitted both `error` and `incomplete_details`. Skipping\n // emission on a `response.incomplete` with no detail would let the\n // post-loop synthetic block silently coerce the run to a clean\n // `RUN_FINISHED { finishReason: 'stop' }` — masking the failure.\n yield {\n type: EventType.RUN_ERROR,\n model: chunk.response.model,\n timestamp: Date.now(),\n message: errorMessage,\n ...(errorCode !== undefined && { code: errorCode }),\n error: {\n message: errorMessage,\n ...(errorCode !== undefined && { code: errorCode }),\n },\n }\n // RUN_ERROR is the terminal event for this run; stop processing\n // any further chunks the iterator might still deliver.\n runFinishedEmitted = true\n return\n }\n\n // Handle output text deltas (token-by-token streaming)\n // response.output_text.delta provides incremental text updates\n if (chunk.type === 'response.output_text.delta' && chunk.delta) {\n // Delta can be an array of strings or a single string\n const textDelta = Array.isArray(chunk.delta)\n ? chunk.delta.join('')\n : typeof chunk.delta === 'string'\n ? chunk.delta\n : ''\n\n if (textDelta) {\n yield* closeReasoning()\n // Emit TEXT_MESSAGE_START on first text content\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n accumulatedContent += textDelta\n hasStreamedContentDeltas = true\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n delta: textDelta,\n content: accumulatedContent,\n }\n }\n }\n\n // Handle reasoning deltas (token-by-token thinking/reasoning streaming)\n // response.reasoning_text.delta provides incremental reasoning updates\n if (\n (chunk.type === 'response.reasoning_text.delta' ||\n chunk.type === 'response.reasoning.delta') &&\n chunk.delta\n ) {\n const reasoningDelta = Array.isArray(chunk.delta)\n ? chunk.delta.join('')\n : typeof chunk.delta === 'string'\n ? chunk.delta\n : ''\n yield* emitReasoningDelta(reasoningDelta)\n }\n\n // Handle reasoning summary deltas (when using reasoning.summary option)\n if (\n chunk.type === 'response.reasoning_summary_text.delta' &&\n chunk.delta\n ) {\n const summaryDelta =\n typeof chunk.delta === 'string' ? chunk.delta : ''\n yield* emitReasoningDelta(summaryDelta)\n }\n\n // handle content_part added events for text, reasoning and refusals\n if (chunk.type === 'response.content_part.added') {\n const contentPart = chunk.part\n // The Responses API can announce a text part with an empty\n // placeholder before putting the actual text only on the completed\n // response. An empty placeholder is not streamed content and must\n // not suppress the completion backstop below.\n if (\n (contentPart.type === 'output_text' ||\n contentPart.type === 'reasoning_text') &&\n !contentPart.text\n ) {\n continue\n }\n if (contentPart.type === 'reasoning_text') {\n yield* emitReasoningDelta(contentPart.text || '')\n continue\n }\n if (\n contentPart.type === 'output_text' &&\n !hasEmittedTextMessageStart\n ) {\n yield* closeReasoning()\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n // Mark whichever stream we just emitted into so a subsequent\n // `content_part.done` doesn't duplicate the same text. Without\n // this flag, an `added` event carrying the full text followed by\n // a matching `done` event would emit TEXT_MESSAGE_CONTENT twice.\n if (contentPart.type === 'output_text') {\n hasStreamedContentDeltas = true\n }\n const partChunk = handleContentPart(contentPart)\n yield partChunk\n // handleContentPart returns RUN_ERROR for refusals / unknown\n // content_part types — those are terminal events. Don't keep\n // processing more chunks (and don't let the post-loop synthetic\n // block emit a second terminal event).\n if (partChunk.type === 'RUN_ERROR') {\n runFinishedEmitted = true\n return\n }\n }\n\n if (chunk.type === 'response.content_part.done') {\n const contentPart = chunk.part\n\n // Skip emitting chunks for content parts that we've already streamed via deltas\n // The done event is just a completion marker, not new content\n if (contentPart.type === 'output_text' && hasStreamedContentDeltas) {\n // Content already accumulated from deltas, skip\n continue\n }\n if (\n contentPart.type === 'reasoning_text' &&\n hasStreamedReasoningDeltas\n ) {\n // Reasoning already accumulated from deltas, skip\n continue\n }\n\n // Upstreams that emit `content_part.done` without any preceding\n // deltas (or `content_part.added`) still need a START event before\n // CONTENT — otherwise consumers tracking start/end pairs see content\n // without a start and never see an end. Emit the lifecycle opener\n // for whichever stream this content_part belongs to before yielding\n // the CONTENT chunk; the post-loop block emits the matching END.\n if (contentPart.type === 'reasoning_text') {\n yield* emitReasoningDelta(contentPart.text || '')\n continue\n }\n if (\n contentPart.type === 'output_text' &&\n !hasEmittedTextMessageStart\n ) {\n yield* closeReasoning()\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n // Only emit if we haven't been streaming deltas (e.g., for non-streaming responses)\n const doneChunk = handleContentPart(contentPart)\n yield doneChunk\n if (doneChunk.type === 'RUN_ERROR') {\n runFinishedEmitted = true\n return\n }\n }\n\n // handle output_item.added to capture function call metadata (name)\n if (chunk.type === 'response.output_item.added') {\n const item = chunk.item\n if (item.type === 'web_search_call') {\n recordProviderWebSearchCall(item, chunk.output_index)\n }\n if (item.type === 'reasoning') {\n captureReasoningItem(item)\n yield* openReasoning()\n }\n if (item.type === 'function_call' && item.id) {\n // Track the item as soon as we see it so subsequent arg deltas\n // aren't logged as orphans, but only emit TOOL_CALL_START when\n // both id AND name are populated. Emitting START with an empty\n // name would propagate into TOOL_CALL_END (which reads the same\n // metadata) and route the tool call to whatever name happens to\n // match `''` downstream — a silent misroute.\n let metadata = toolCallMetadata.get(item.id)\n if (!metadata) {\n metadata = {\n callId: item.call_id || item.id,\n index: chunk.output_index,\n name: item.name || '',\n started: false,\n }\n toolCallMetadata.set(item.id, metadata)\n } else {\n if (item.call_id) metadata.callId = item.call_id\n if (!metadata.name && item.name) {\n // A later output_item.added for the same id finally carries\n // the name. Update so the gated emission below can fire.\n metadata.name = item.name\n }\n }\n if (!metadata.started && metadata.name) {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: metadata.callId,\n toolCallName: metadata.name,\n toolName: metadata.name,\n parentMessageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n index: chunk.output_index,\n metadata: {\n itemId: item.id,\n } satisfies OpenAIResponsesToolCallMetadata,\n }\n metadata.started = true\n }\n }\n yield* userToolChunks(item, chunk.output_index, false)\n }\n\n // Handle function call arguments delta (streaming). Drop the\n // previously-emitted `args` field — it had inverted polarity\n // (populated only when metadata was MISSING, i.e. when the\n // matching TOOL_CALL_START hadn't fired) and the chat-completions\n // adapter never emitted it, so it leaked partial deltas as\n // pseudo-args only on the orphan path. Consumers should accumulate\n // `delta` themselves.\n //\n // Guard with `metadata?.started`: the matching TOOL_CALL_START fires\n // from `output_item.added`, and emitting TOOL_CALL_ARGS before that\n // would violate the AG-UI lifecycle (ARGS without START). The .done\n // handler below applies the same guard.\n if (\n chunk.type === 'response.function_call_arguments.delta' &&\n chunk.delta\n ) {\n const metadata = toolCallMetadata.get(chunk.item_id)\n if (!metadata?.started) {\n options.logger.errors(\n `${this.name}.processStreamChunks orphan function_call_arguments.delta`,\n {\n source: `${this.name}.processStreamChunks`,\n // No metadata yet, so the `call_id` is unknown here — only the\n // output item id the delta referenced.\n itemId: chunk.item_id,\n rawDelta: chunk.delta,\n },\n )\n continue\n }\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: metadata.callId,\n model: model || options.model,\n timestamp: Date.now(),\n delta: chunk.delta,\n }\n }\n\n if (chunk.type === 'response.function_call_arguments.done') {\n const { item_id } = chunk\n\n // Get the function name from metadata (captured in output_item.added)\n const metadata = toolCallMetadata.get(item_id)\n // If the matching START was never emitted (the upstream sent an\n // `output_item.added` without a name and no later event has filled\n // it in yet), defer END until `output_item.done` or\n // `response.completed` can backfill the name. We stash the raw\n // arguments so the late emission has them. Emitting END without\n // START would produce an unbalanced AG-UI lifecycle event\n // downstream consumers can't pair.\n if (!metadata?.started) {\n if (metadata) {\n metadata.pendingArguments = chunk.arguments\n }\n options.logger.errors(\n `${this.name}.processStreamChunks deferring function_call_arguments.done — TOOL_CALL_START not yet emitted (waiting for name)`,\n {\n source: `${this.name}.processStreamChunks`,\n ...(metadata && { toolCallId: metadata.callId }),\n itemId: item_id,\n rawArguments: chunk.arguments,\n },\n )\n continue\n }\n // The output_item.done backstop may have already emitted END (when\n // it arrived before args.done with a populated item.arguments).\n // Skip so we never produce a duplicate close for the same id.\n if (metadata.ended) continue\n const name = metadata.name || ''\n metadata.ended = true\n\n // Parse arguments. Surface parse failures via the logger so a\n // model emitting malformed JSON is debuggable instead of silently\n // invoking the tool with {}.\n let parsedInput: unknown = {}\n if (chunk.arguments) {\n try {\n const parsed = JSON.parse(chunk.arguments)\n parsedInput = normalizeToolInput(\n name,\n parsed && typeof parsed === 'object' ? parsed : {},\n )\n } catch (parseError) {\n options.logger.errors(\n `${this.name}.processStreamChunks tool-args JSON parse failed`,\n {\n error: toRunErrorPayload(\n parseError,\n `tool ${name} (${metadata.callId}) returned malformed JSON arguments`,\n ),\n source: `${this.name}.processStreamChunks`,\n toolCallId: metadata.callId,\n itemId: item_id,\n toolName: name,\n rawArguments: chunk.arguments,\n },\n )\n parsedInput = {}\n }\n }\n\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: metadata.callId,\n toolCallName: name,\n toolName: name,\n model: model || options.model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n }\n\n // `output_item.done` is the last point at which a function_call's\n // name is guaranteed to be on the wire — it carries the fully-formed\n // ResponseFunctionToolCall. Use it as a backstop to recover any\n // tool call whose name was missing from `output_item.added` (and\n // whose START + END therefore never fired).\n if (chunk.type === 'response.output_item.done') {\n const item = chunk.item\n if (item.type === 'web_search_call') {\n recordProviderWebSearchCall(item, chunk.output_index)\n }\n if (item.type === 'reasoning') {\n captureReasoningItem(item)\n yield* openReasoning()\n }\n if (item.type === 'function_call' && item.id) {\n const metadata = toolCallMetadata.get(item.id) ?? {\n callId: item.call_id || item.id,\n index: chunk.output_index,\n name: item.name || '',\n started: false,\n }\n if (!toolCallMetadata.has(item.id)) {\n toolCallMetadata.set(item.id, metadata)\n } else {\n if (item.call_id) metadata.callId = item.call_id\n if (!metadata.name && item.name) metadata.name = item.name\n }\n // Emit gated START if we now have a name and never started.\n if (!metadata.started && metadata.name) {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: metadata.callId,\n toolCallName: metadata.name,\n toolName: metadata.name,\n parentMessageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n index: metadata.index,\n metadata: {\n itemId: item.id,\n } satisfies OpenAIResponsesToolCallMetadata,\n }\n metadata.started = true\n }\n // Emit END if we have args (either from a previously-deferred\n // args.done OR from item.arguments) and haven't already ended.\n const rawArgs =\n typeof item.arguments === 'string' && item.arguments.length > 0\n ? item.arguments\n : metadata.pendingArguments\n if (metadata.started && !metadata.ended && rawArgs !== undefined) {\n const name = metadata.name || ''\n let parsedInput: unknown = {}\n if (rawArgs) {\n try {\n const parsed = JSON.parse(rawArgs)\n parsedInput = normalizeToolInput(\n name,\n parsed && typeof parsed === 'object' ? parsed : {},\n )\n } catch (parseError) {\n options.logger.errors(\n `${this.name}.processStreamChunks tool-args JSON parse failed (output_item.done backfill)`,\n {\n error: toRunErrorPayload(\n parseError,\n `tool ${name} (${metadata.callId}) returned malformed JSON arguments`,\n ),\n source: `${this.name}.processStreamChunks`,\n toolCallId: metadata.callId,\n itemId: item.id,\n toolName: name,\n rawArguments: rawArgs,\n },\n )\n parsedInput = {}\n }\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: metadata.callId,\n toolCallName: name,\n toolName: name,\n model: model || options.model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n metadata.ended = true\n metadata.pendingArguments = undefined\n }\n }\n yield* userToolChunks(item, chunk.output_index, false)\n }\n\n if (chunk.type === 'response.output_text.annotation.added') {\n const citation = readURLCitation(chunk.annotation)\n if (citation) webSearchCitations.push(citation)\n }\n\n if (chunk.type === 'response.completed') {\n const responseOutput = Array.isArray(chunk.response.output)\n ? chunk.response.output\n : []\n const assistantMessage = responseOutput.find(\n (item): item is ResponseOutputMessage => item.type === 'message',\n )\n for (const [index, item] of responseOutput.entries()) {\n if (item.type === 'web_search_call') {\n recordProviderWebSearchCall(item, index)\n }\n }\n\n // Some Responses API streams, notably reasoning-model responses,\n // can omit text deltas and carry the successful final text only in\n // response.completed.output. Recover that text so consumers never\n // observe an empty result for a successful response.\n const completedText = responseOutput\n .flatMap((item) => (item.type === 'message' ? item.content : []))\n .filter((part) => part.type === 'output_text')\n .map((part) => part.text)\n .join('')\n\n if (accumulatedContent.length === 0 && completedText.length > 0) {\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n accumulatedContent = completedText\n hasStreamedContentDeltas = true\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n delta: completedText,\n content: accumulatedContent,\n }\n }\n\n for (const item of responseOutput) {\n captureReasoningItem(item)\n }\n // output_text already closed the streamed reasoning item. A second\n // openReasoning() would emit an empty thinking part. Attach the\n // completed item's id/blob to that step instead. Open only when\n // this turn never started reasoning (encrypted-only output).\n if (\n !reasoningMessageId &&\n (reasoningItemId || reasoningEncryptedContent)\n ) {\n const signature = packResponsesReasoningSignature(\n reasoningItemId,\n reasoningEncryptedContent,\n )\n if (closedReasoningStepId && signature) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: closedReasoningStepId,\n stepId: closedReasoningStepId,\n model: emitModel(),\n timestamp: Date.now(),\n content: '',\n signature,\n }\n } else if (!closedReasoningStepId) {\n yield* openReasoning()\n }\n }\n\n // Final backstop for function_call lifecycle: if a function_call\n // appears in `response.output[]` but was never matched by an\n // output_item.added/done with a name, recover the missing START\n // (and END if args were pending). Without this, a tool call could\n // be silently dropped from the AG-UI stream while `hasFunctionCalls`\n // below still routes the run's finishReason to 'tool_calls' —\n // leaving consumers waiting for tool results they never saw start.\n for (const [outputIndex, item] of responseOutput.entries()) {\n if (item.type !== 'function_call' || !item.id) continue\n const metadata = toolCallMetadata.get(item.id) ?? {\n callId: item.call_id || item.id,\n index: outputIndex,\n name: item.name || '',\n started: false,\n }\n if (!toolCallMetadata.has(item.id)) {\n toolCallMetadata.set(item.id, metadata)\n } else {\n if (item.call_id) metadata.callId = item.call_id\n if (!metadata.name && item.name) metadata.name = item.name\n }\n if (!metadata.started && metadata.name) {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: metadata.callId,\n toolCallName: metadata.name,\n toolName: metadata.name,\n parentMessageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n index: metadata.index,\n metadata: {\n itemId: item.id,\n } satisfies OpenAIResponsesToolCallMetadata,\n }\n metadata.started = true\n }\n const rawArgs =\n typeof item.arguments === 'string' && item.arguments.length > 0\n ? item.arguments\n : metadata.pendingArguments\n if (metadata.started && !metadata.ended) {\n const name = metadata.name || ''\n let parsedInput: unknown = {}\n if (rawArgs) {\n try {\n const parsed = JSON.parse(rawArgs)\n parsedInput = normalizeToolInput(\n name,\n parsed && typeof parsed === 'object' ? parsed : {},\n )\n } catch (parseError) {\n options.logger.errors(\n `${this.name}.processStreamChunks tool-args JSON parse failed (response.completed backfill)`,\n {\n error: toRunErrorPayload(\n parseError,\n `tool ${name} (${metadata.callId}) returned malformed JSON arguments`,\n ),\n source: `${this.name}.processStreamChunks`,\n toolCallId: metadata.callId,\n itemId: item.id,\n toolName: name,\n rawArguments: rawArgs,\n },\n )\n parsedInput = {}\n }\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: metadata.callId,\n toolCallName: name,\n toolName: name,\n model: model || options.model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n metadata.ended = true\n metadata.pendingArguments = undefined\n }\n }\n\n yield* emitProviderWebSearchCalls(assistantMessage)\n\n const shellOutputs = hostedShellCallIds(responseOutput)\n for (const [outputIndex, item] of responseOutput.entries()) {\n if (\n isRecord(item) &&\n item.type === 'shell_call' &&\n typeof item.call_id === 'string' &&\n shellOutputs.has(item.call_id)\n ) {\n continue\n }\n yield* userToolChunks(item, outputIndex, true)\n }\n\n yield* closeReasoning()\n // Emit TEXT_MESSAGE_END if we had text content\n if (hasEmittedTextMessageStart) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n }\n hasEmittedTextMessageStart = false\n }\n\n // Determine finish reason. Function-call output → tool_calls.\n // Otherwise surface incomplete_details.reason when present so\n // callers can distinguish length-limit / content-filter cutoffs\n // from a clean stop, mirroring the chat-completions adapter.\n // The Responses API's incomplete_details.reason ('max_output_tokens'\n // | 'content_filter') maps to the AG-UI finishReason vocabulary:\n // max_output_tokens → 'length', content_filter → 'content_filter'.\n const hasFunctionCalls = responseOutput.some((item) => {\n if (!isRecord(item)) return false\n if (item.type === 'function_call') return true\n if (\n item.type === 'shell_call' &&\n typeof item.call_id === 'string' &&\n shellOutputs.has(item.call_id)\n ) {\n return false\n }\n return readUserExecutedCall(item, { bareShell: true }) !== null\n })\n const incompleteReason = chunk.response.incomplete_details?.reason\n const finishReason:\n | 'tool_calls'\n | 'length'\n | 'content_filter'\n | 'stop' = hasFunctionCalls\n ? 'tool_calls'\n : incompleteReason === 'max_output_tokens'\n ? 'length'\n : incompleteReason === 'content_filter'\n ? 'content_filter'\n : 'stop'\n\n yield {\n type: EventType.RUN_FINISHED,\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: model || options.model,\n timestamp: Date.now(),\n // Omit usage entirely when the provider reported none rather than\n // emitting fabricated zeros (also satisfies exactOptionalPropertyTypes).\n ...(chunk.response.usage && {\n usage: buildResponsesUsage(chunk.response.usage),\n }),\n finishReason,\n }\n runFinishedEmitted = true\n // Terminal event: do not wait for the HTTP body to close (#1445).\n return\n }\n\n if (chunk.type === 'error') {\n // Conditional `code` spread keeps the wire shape spec-compliant\n // under `exactOptionalPropertyTypes` (see chatStream catch).\n const code = chunk.code ?? undefined\n yield {\n type: EventType.RUN_ERROR,\n model: model || options.model,\n timestamp: Date.now(),\n message: chunk.message,\n ...(code !== undefined && { code }),\n error: {\n message: chunk.message,\n ...(code !== undefined && { code }),\n },\n }\n // RUN_ERROR is terminal — don't let the synthetic RUN_FINISHED\n // block fire after a top-level stream error event, and stop\n // processing further chunks so no in-flight lifecycle events\n // (TEXT_MESSAGE_CONTENT, TOOL_CALL_*) leak past the terminal\n // error. Mirrors the `response.failed` / `response.incomplete`\n // branches above which return after their RUN_ERROR emission.\n runFinishedEmitted = true\n return\n }\n }\n\n // The stream ended without a terminal event (e.g. a truncated\n // connection). Completion was never confirmed, so this is not a\n // successful stop (#1447). The partial text was already emitted.\n if (!runFinishedEmitted && aguiState.hasEmittedRunStarted) {\n yield* emitProviderWebSearchCalls(undefined, true)\n yield* closeReasoning()\n if (hasEmittedTextMessageStart) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: aguiState.messageId,\n model: model || options.model,\n timestamp: Date.now(),\n }\n }\n const message = 'Response stream ended before response.completed'\n yield {\n type: EventType.RUN_ERROR,\n model: model || options.model,\n timestamp: Date.now(),\n message,\n code: 'incomplete-stream',\n error: { message, code: 'incomplete-stream' },\n }\n }\n } catch (error: unknown) {\n // Narrow before logging: raw SDK errors can carry request metadata\n // (including auth headers) which we must never surface to user loggers.\n const errorPayload = toRunErrorPayload(\n error,\n `${this.name}.processStreamChunks failed`,\n )\n const rawEvent = toRunErrorRawEvent(error)\n options.logger.errors(`${this.name}.processStreamChunks fatal`, {\n error: errorPayload,\n source: `${this.name}.processStreamChunks`,\n })\n // Emit AG-UI RUN_ERROR with conditional `code` spread (see chatStream\n // catch for the rationale). `rawEvent` carries the provider's structured\n // error body when present.\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: errorPayload.message,\n ...(errorPayload.code !== undefined && { code: errorPayload.code }),\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: errorPayload.message,\n ...(errorPayload.code !== undefined && { code: errorPayload.code }),\n },\n }\n }\n }\n\n /**\n * Maps common TextOptions to Responses API request format.\n * Override this in subclasses to add provider-specific options.\n */\n protected mapOptionsToRequest(\n options: TextOptions<TProviderOptions>,\n ): Omit<ResponseCreateParams, 'stream'> {\n const input = this.convertMessagesToInput(options.messages)\n\n if (this.strictFallbackWarning) {\n warnStrictFallback(options.tools, options.logger)\n }\n const tools = options.tools\n ? convertToolsToResponsesFormat(\n options.tools,\n this.makeStructuredOutputCompatible.bind(this),\n )\n : undefined\n\n const modelOptions = options.modelOptions\n\n // Native combined mode (issue #605): when the engine threads\n // `outputSchema` through TextOptions, the adapter declared\n // `supportsCombinedToolsAndSchema` and the schema is already JSON Schema\n // (pre-converted at the activity boundary). Wire it into `text.format`\n // alongside any `tools` — the Responses API supports both together and\n // emits the schema-constrained text on the natural final turn.\n const combinedSchema = options.outputSchema as\n | Record<string, unknown>\n | undefined\n const textFormat = combinedSchema\n ? {\n text: {\n format: {\n type: 'json_schema' as const,\n name: 'structured_output',\n schema: this.makeStructuredOutputCompatible(\n combinedSchema,\n Array.isArray(combinedSchema.required)\n ? (combinedSchema.required as Array<string>)\n : undefined,\n ),\n strict: true,\n },\n },\n }\n : undefined\n\n // `modelOptions` is the sole sampling surface: `temperature`, `top_p`, and\n // `max_output_tokens` live there (typed via OpenAISamplingOptions) and are\n // spread first. Engine-managed fields (`model`, `metadata`, `instructions`,\n // `input`, `tools`, `textFormat`) are layered on top afterward so they\n // always win over any same-named key a caller happened to put in\n // `modelOptions`.\n return {\n ...modelOptions,\n model: options.model,\n ...(options.metadata !== undefined && { metadata: options.metadata }),\n ...(() => {\n const prompts = normalizeSystemPrompts(options.systemPrompts)\n if (prompts.length === 0) return {}\n return { instructions: prompts.map((p) => p.content).join('\\n') }\n })(),\n input,\n // Conditional spread: `tools: undefined` would clobber any\n // modelOptions.tools the caller set above.\n ...(tools && tools.length > 0 && { tools }),\n ...(textFormat ?? {}),\n }\n }\n\n /**\n * The OpenAI Responses API supports `tools` and `text.format: json_schema`\n * together in a single streaming request (per issue #605). Subclasses\n * that route to providers without this capability should override.\n */\n supportsCombinedToolsAndSchema(): boolean {\n return true\n }\n\n /**\n * Converts ModelMessage[] to Responses API ResponseInput format.\n * Override this in subclasses for provider-specific message format quirks.\n *\n * Key differences from Chat Completions:\n * - Tool results use `function_call_output` type (not `tool` role)\n * - Assistant tool calls are `function_call` objects (not nested in `tool_calls`)\n * - User content uses `input_text`, `input_image`, `input_file` types\n * - System prompts go in `instructions`, not as messages\n */\n protected convertMessagesToInput(\n messages: Array<ModelMessage>,\n ): ResponseInput {\n const result: ResponseInput = []\n // A reasoning item id may only appear once in `input`; replaying the same\n // id twice fails with \"Duplicate item found with id rs_...\". Providers have\n // been observed minting one id for two separate reasoning items, and a\n // stored transcript can end up carrying it on two assistant messages.\n const seenReasoningIds = new Set<string>()\n const userToolCalls = new Map<\n string,\n {\n id: string\n function: { name: string; arguments: string }\n metadata?: unknown\n }\n >()\n\n for (const message of messages) {\n // Handle tool messages - convert to FunctionToolCallOutput\n if (message.role === 'tool') {\n const owner = message.toolCallId\n ? userToolCalls.get(message.toolCallId)\n : undefined\n const userOutput = owner\n ? userToolResultItem(owner, message.content)\n : null\n if (userOutput) {\n result.push(userOutput)\n continue\n }\n const toolContent = message.content\n const output: string | Array<ResponseFunctionCallOutputItem> =\n Array.isArray(toolContent)\n ? toolContent.map((part) => this.convertContentPartToInput(part))\n : typeof toolContent === 'string'\n ? toolContent\n : JSON.stringify(toolContent)\n result.push({\n type: 'function_call_output',\n call_id: message.toolCallId || '',\n output,\n })\n continue\n }\n\n // Handle assistant messages\n if (message.role === 'assistant') {\n // Every reasoning item this message could contribute, and how many of\n // them actually made it into `input` after de-duplication. Both counts\n // are needed below to decide whether the function calls can still be\n // paired with their reasoning.\n let reasoningCandidates = 0\n let emittedReasoning = 0\n if (message.thinking) {\n for (const thinking of message.thinking) {\n if (!thinking.signature) continue\n const packed = unpackResponsesReasoningSignature(thinking.signature)\n if (!packed?.id) continue\n reasoningCandidates++\n if (seenReasoningIds.has(packed.id)) continue\n seenReasoningIds.add(packed.id)\n emittedReasoning++\n result.push({\n type: 'reasoning',\n id: packed.id,\n ...(packed.encrypted_content\n ? { encrypted_content: packed.encrypted_content }\n : {}),\n summary: thinking.content\n ? [{ type: 'summary_text', text: thinking.content }]\n : [],\n })\n }\n }\n\n // The Responses API requires a persisted `function_call` item to sit\n // directly after the reasoning item that produced it. A ModelMessage\n // stores reasoning and tool calls as two flat arrays, so their original\n // interleaving is gone: a message holding two or more reasoning items\n // replays as reasoning A, reasoning B, call A, call B, and the request\n // is rejected with \"Item 'fc_...' of type 'function_call' was provided\n // without its required 'reasoning' item: 'rs_...'\". The same happens\n // when this message's reasoning was dropped above as a duplicate.\n //\n // Sending the calls without their item id makes them fresh items that\n // the API does not try to pair, which replays correctly. `call_id` is\n // untouched, so the matching `function_call_output` still resolves.\n // One reasoning item (or none at all) always lands adjacent to its\n // calls, so those keep their ids and their prompt-cache hits. If any\n // reasoning was dropped as a duplicate, a call may belong to it, so\n // the ids go too.\n const canPairReasoning =\n reasoningCandidates === 0 ||\n (reasoningCandidates === 1 && emittedReasoning === 1)\n\n // If the assistant message has tool calls, add them as FunctionToolCall objects\n // Responses API expects arguments as a string (JSON string)\n let rawAssistantMessage: ResponseOutputMessage | undefined\n if (message.toolCalls && message.toolCalls.length > 0) {\n for (const toolCall of message.toolCalls) {\n const metadata = toolCall.metadata as\n | OpenAIResponsesToolCallMetadata\n | undefined\n if (metadata?.providerExecuted) {\n const webSearchCall = metadata.openai?.webSearchCall\n // The raw ws_/msg_ items carry ids that must pair with their\n // reasoning item, the same as function calls above. When they\n // cannot pair, skip them and send the plain message with no id.\n if (webSearchCall && canPairReasoning) {\n result.push(webSearchCall)\n rawAssistantMessage ??= metadata.openai?.assistantMessage\n }\n continue\n }\n\n // Keep arguments as string for Responses API\n const argumentsString =\n typeof toolCall.function.arguments === 'string'\n ? toolCall.function.arguments\n : JSON.stringify(toolCall.function.arguments)\n const replayCall = {\n id: toolCall.id,\n function: {\n name: toolCall.function.name,\n arguments: argumentsString,\n },\n ...(toolCall.metadata !== undefined\n ? { metadata: toolCall.metadata }\n : {}),\n }\n const userItem = userToolRequestItem(replayCall)\n if (userItem) {\n userToolCalls.set(toolCall.id, replayCall)\n result.push(userItem)\n continue\n }\n const itemId = metadata?.itemId\n\n result.push({\n type: 'function_call',\n call_id: toolCall.id,\n ...(itemId && canPairReasoning && { id: itemId }),\n name: toolCall.function.name,\n arguments: argumentsString,\n })\n }\n }\n\n if (rawAssistantMessage) {\n result.push(rawAssistantMessage)\n } else if (message.content) {\n // Add the assistant's text message if there is content\n const contentStr = this.extractTextContent(message.content)\n if (contentStr) {\n result.push({\n type: 'message',\n role: 'assistant',\n content: contentStr,\n })\n }\n }\n\n continue\n }\n\n // Handle user messages (default case) — support multimodal content\n const contentParts = this.normalizeContent(message.content)\n const inputContent: Array<ResponseInputContent> = []\n\n for (const part of contentParts) {\n inputContent.push(this.convertContentPartToInput(part))\n }\n\n if (inputContent.length === 0) {\n // Fail loud rather than silently sending an empty user message —\n // mirrors the chat-completions adapter, where a paid-but-empty\n // request would mask the real intent (caller passed `null` content\n // or a normalize step dropped everything).\n throw new Error(\n `User message for ${this.name} has no content parts. ` +\n `Empty user messages would produce a paid request with no input; ` +\n `provide at least one text/image/audio/document part or omit the message.`,\n )\n }\n\n result.push({\n type: 'message',\n role: 'user',\n content: inputContent,\n })\n }\n\n return result\n }\n\n /**\n * Converts a ContentPart to Responses API input content item.\n * Handles text, image, audio, and document (PDF) content parts.\n * Override this in subclasses for additional content types or provider-specific metadata.\n */\n protected convertContentPartToInput(part: ContentPart): ResponseInputContent {\n switch (part.type) {\n case 'text':\n return {\n type: 'input_text',\n text: part.content,\n }\n case 'image': {\n const imageMetadata = part.metadata as\n | { detail?: 'auto' | 'low' | 'high' }\n | undefined\n if (isFileSource(part.source)) {\n if (this.supportsFileSources !== true) {\n throw unsupportedFileSourceError(this.name)\n }\n return {\n type: 'input_image',\n file_id: fileReferenceFor(part.source, this.name),\n detail: imageMetadata?.detail || 'auto',\n }\n }\n if (part.source.type === 'url') {\n return {\n type: 'input_image',\n image_url: part.source.value,\n detail: imageMetadata?.detail || 'auto',\n }\n }\n // For base64 data, construct a data URI using the mimeType from\n // source. Default to a generic octet-stream MIME if the source\n // didn't supply one — letting `undefined` interpolate would produce\n // an invalid URI like \"data:undefined;base64,...\".\n const imageValue = part.source.value\n const imageMime = part.source.mimeType || 'application/octet-stream'\n const imageUrl = imageValue.startsWith('data:')\n ? imageValue\n : `data:${imageMime};base64,${imageValue}`\n return {\n type: 'input_image',\n image_url: imageUrl,\n detail: imageMetadata?.detail || 'auto',\n }\n }\n case 'audio': {\n if (isFileSource(part.source)) {\n if (this.supportsFileSources !== true) {\n throw unsupportedFileSourceError(this.name)\n }\n return {\n type: 'input_file',\n file_id: fileReferenceFor(part.source, this.name),\n }\n }\n if (part.source.type === 'url') {\n return {\n type: 'input_file',\n file_url: part.source.value,\n }\n }\n // Wrap raw base64 in a data URL — `input_file` rejects bare base64\n // payloads (matches the image branch above).\n // Default the MIME if missing so we never interpolate `undefined`.\n const audioValue = part.source.value\n const audioMime = part.source.mimeType || 'application/octet-stream'\n const audioFileData = audioValue.startsWith('data:')\n ? audioValue\n : `data:${audioMime};base64,${audioValue}`\n return {\n type: 'input_file',\n file_data: audioFileData,\n }\n }\n\n case 'document': {\n const documentMetadata = part.metadata as\n | { filename?: string; detail?: 'auto' | 'low' | 'high' }\n | undefined\n // Spread `detail` only when provided so the API applies its own\n // default ('auto'). The Responses API accepts 'auto' | 'low' | 'high',\n // but the pinned OpenAI SDK's `ResponseInputFile.detail` type still\n // lists only 'low' | 'high' — cast so 'auto' (a valid API value) can\n // pass through without a type error.\n const documentDetail =\n documentMetadata?.detail !== undefined\n ? { detail: documentMetadata.detail as 'low' | 'high' }\n : {}\n if (isFileSource(part.source)) {\n if (this.supportsFileSources !== true) {\n throw unsupportedFileSourceError(this.name)\n }\n return {\n type: 'input_file',\n file_id: fileReferenceFor(part.source, this.name),\n ...documentDetail,\n }\n }\n if (part.source.type === 'url') {\n // The Responses API fetches the PDF itself; filename and MIME\n // type are inferred from the response.\n return {\n type: 'input_file',\n file_url: part.source.value,\n ...documentDetail,\n }\n }\n // This adapter supports only PDF documents; anything else is\n // rejected. MIME types are case-insensitive and can carry\n // ;parameters (RFC 2045), so the type is normalized before comparing.\n const documentValue = part.source.value\n const documentMime = (\n (part.source.mimeType || 'application/pdf').split(';')[0] ?? ''\n )\n .trim()\n .toLowerCase()\n if (documentMime !== 'application/pdf') {\n throw new Error(\n `${this.name} document parts only support application/pdf ` +\n `(received ${documentMime})`,\n )\n }\n // A pre-wrapped data URL carries its own media type — validate it too.\n if (\n documentValue.startsWith('data:') &&\n !/^data:application\\/pdf[;,]/i.test(documentValue)\n ) {\n throw new Error(\n `${this.name} document parts only support application/pdf ` +\n `(received data URL with non-PDF media type)`,\n )\n }\n // Sniff the payload so a non-PDF labeled (or unlabeled) as PDF is\n // caught locally instead of by an opaque provider 400. Only base64\n // payloads are checked; a rare `data:` URL without `;base64` is left\n // to the server.\n const documentBase64 = documentValue.startsWith('data:')\n ? /;base64,/i.test(documentValue)\n ? documentValue.slice(documentValue.indexOf(',') + 1)\n : ''\n : documentValue\n if (documentBase64 && !documentBase64.startsWith(PDF_BASE64_MAGIC)) {\n throw new Error(\n `${this.name} document parts only support application/pdf ` +\n `(inline data does not start with the %PDF header)`,\n )\n }\n // Wrap raw base64 in a data URL — `input_file` rejects bare base64\n // payloads (matches the image and audio branches above).\n const documentFileData = documentValue.startsWith('data:')\n ? documentValue\n : `data:${documentMime};base64,${documentValue}`\n return {\n type: 'input_file',\n // The Responses API requires a filename alongside PDF `file_data`.\n filename: documentMetadata?.filename || 'document.pdf',\n file_data: documentFileData,\n ...documentDetail,\n }\n }\n case 'video':\n default:\n // OpenAI Responses API doesn't accept native video parts on this\n // path — surface as explicit unsupported error so callers see the\n // same message regardless of which content type leaked through.\n throw new Error(`Unsupported content part type: ${part.type}`)\n }\n }\n\n /**\n * Normalizes message content to an array of ContentPart.\n * Handles backward compatibility with string content.\n */\n protected normalizeContent(\n content: string | null | undefined | Array<ContentPart>,\n ): Array<ContentPart> {\n if (content === null || content === undefined) {\n return []\n }\n if (typeof content === 'string') {\n return [{ type: 'text', content: content }]\n }\n return content\n }\n\n /**\n * Extracts text content from a content value that may be string, null, or ContentPart array.\n */\n protected extractTextContent(\n content: string | null | undefined | Array<ContentPart>,\n ): string {\n if (content === null || content === undefined) {\n return ''\n }\n if (typeof content === 'string') {\n return content\n }\n // It's an array of ContentPart\n return content\n .filter((p) => p.type === 'text')\n .map((p) => p.content)\n .join('')\n }\n}\n"],"mappings":";;;;;;;;;;;AA6DA,IAAM,mBAAmB;AAEzB,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,gBACP,OAC4C;CAC5C,IAAI,CAAC,SAAS,KAAK,KAAK,MAAM,SAAS,gBAAgB,OAAO,KAAA;CAC9D,IACE,OAAO,MAAM,QAAQ,YACrB,OAAO,MAAM,UAAU,YACvB,OAAO,MAAM,gBAAgB,YAC7B,OAAO,MAAM,cAAc,UAE3B;CAEF,OAAO;EACL,MAAM;EACN,KAAK,MAAM;EACX,OAAO,MAAM;EACb,aAAa,MAAM;EACnB,WAAW,MAAM;CACnB;AACF;AAEA,SAAS,kBACP,OACuC;CACvC,IAAI,CAAC,SAAS,KAAK,KAAK,MAAM,SAAS,mBAAmB,OAAO,KAAA;CACjE,IACE,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,YACxB,CAAC,SAAS,MAAM,MAAM,KACtB,OAAO,MAAM,OAAO,SAAS,UAE7B;CAGF,O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