@codeworksh/aikit 0.13.0 → 0.14.0-canary.125.1.gb9ae8bf0
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/cli.mjs +3 -3
- package/{copilot-D9T1jbpu.mjs → copilot-BnraENbo.mjs} +2 -2
- package/{copilot-D9T1jbpu.mjs.map → copilot-BnraENbo.mjs.map} +1 -1
- package/{copilot-headers-I-AOoDed.mjs → copilot-headers-O7LmAz_U.mjs} +2 -2
- package/{copilot-headers-I-AOoDed.mjs.map → copilot-headers-O7LmAz_U.mjs.map} +1 -1
- package/github-copilot-BqLzvkGs.mjs +3 -0
- package/{github-copilot-CdkIxdQS.mjs → github-copilot-OdlbT7il.mjs} +3 -3
- package/{github-copilot-CdkIxdQS.mjs.map → github-copilot-OdlbT7il.mjs.map} +1 -1
- package/index.mjs +14 -8
- package/index.mjs.map +1 -1
- package/{model-av44O6GQ.mjs → model-Bngx_P1p.mjs} +2 -2
- package/{model-av44O6GQ.mjs.map → model-Bngx_P1p.mjs.map} +1 -1
- package/{model-BZZZAySN.mjs → model-DHV-hzpF.mjs} +1 -59
- package/{model-BZZZAySN.mjs.map → model-DHV-hzpF.mjs.map} +1 -1
- package/{modelgen-f3yv7FiK.mjs → modelgen-BE_GuJZG.mjs} +9 -5
- package/modelgen-BE_GuJZG.mjs.map +1 -0
- package/modelgen.mjs +2 -2
- package/oauth/github/copilot.mjs +1 -1
- package/openai-codex-CLv1E2ED.mjs +2 -0
- package/{openai-codex-DL0lqVuN.mjs → openai-codex-DOAYxBAw.mjs} +2 -2
- package/{openai-codex-DL0lqVuN.mjs.map → openai-codex-DOAYxBAw.mjs.map} +1 -1
- package/package.json +1 -1
- package/{registry-BULNTLAP.mjs → registry-7CCwBZxQ.mjs} +4 -4
- package/{registry-BULNTLAP.mjs.map → registry-7CCwBZxQ.mjs.map} +1 -1
- package/github-copilot-C75m0xwW.mjs +0 -3
- package/modelgen-f3yv7FiK.mjs.map +0 -1
- package/openai-codex-BGNrJzTb.mjs +0 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
2
|
import { a as FailureSchema } from "./schema-rXSoWhic.mjs";
|
|
3
|
-
import { a as KnownProviderEnumSchema, c as ThinkingLevel, o as ProviderInfo } from "./model-
|
|
3
|
+
import { a as KnownProviderEnumSchema, c as ThinkingLevel, o as ProviderInfo } from "./model-DHV-hzpF.mjs";
|
|
4
4
|
import Type$1 from "typebox";
|
|
5
5
|
import { uuidv7 } from "uuidv7";
|
|
6
6
|
import { APICallError } from "@ai-sdk/provider";
|
|
@@ -1614,4 +1614,4 @@ var ResponsesLanguageModel = class {
|
|
|
1614
1614
|
//#endregion
|
|
1615
1615
|
export { AssistantMessageSchema as a, message_exports as c, resolveToolGrammar as i, omitImages as l, clampPromptCacheKey as n, ToolCallSchema as o, shortHash as r, createAssistantMessage as s, ResponsesLanguageModel as t, transformMessages as u };
|
|
1616
1616
|
|
|
1617
|
-
//# sourceMappingURL=model-
|
|
1617
|
+
//# sourceMappingURL=model-Bngx_P1p.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-av44O6GQ.mjs","names":["Type","Model.KnownProviderEnumSchema","Model.ProviderInfo","Model.ThinkingLevel","Failure.FailureSchema","asRecord","asString"],"sources":["../../src/message/message.ts","../../src/providers/responses/tools.ts","../../src/utils/hash.ts","../../src/providers/responses/error.ts","../../src/providers/responses/prompt.ts","../../src/providers/responses/sse.ts","../../src/providers/responses/usage.ts","../../src/providers/responses/model.ts"],"sourcesContent":["import Type, { type Static, type TSchema } from \"typebox\";\nimport { uuidv7 } from \"uuidv7\";\nimport * as Failure from \"../llm/failure/schema.ts\";\nimport * as Model from \"../model/model.ts\";\n\nexport const TextContentSchema = Type.Object({\n\ttype: Type.Literal(\"text\"),\n\ttext: Type.String(),\n\ttextSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the message ID\n});\nexport type TextContent = Static<typeof TextContentSchema>;\n\nexport const ImageContentSchema = Type.Object({\n\ttype: Type.Literal(\"image\"),\n\tdata: Type.String(), // base64 encoded image data\n\tmimeType: Type.String(), // e.g., \"image/jpeg\", \"image/png\"\n});\nexport type ImageContent = Static<typeof ImageContentSchema>;\n\nexport const ThinkingContentSchema = Type.Object({\n\ttype: Type.Literal(\"thinking\"),\n\tthinking: Type.String(),\n\t// Provider-native replay data: an Anthropic signature, serialized OpenAI\n\t// reasoning metadata, or a serialized OpenAI Codex reasoning item.\n\tthinkingSignature: Type.Optional(Type.String()),\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted: Type.Optional(Type.Boolean()),\n});\nexport type ThinkingContent = Static<typeof ThinkingContentSchema>;\n\nexport const ToolCallBaseSchema = Type.Object({\n\ttype: Type.Literal(\"toolCall\"),\n\tcallID: Type.String(),\n\tname: Type.String(),\n\targuments: Type.Record(Type.String(), Type.Any()),\n\tthoughtSignature: Type.Optional(Type.String()), // Google-specific: opaque signature for reusing thought context\n\tnamespace: Type.Optional(Type.String()), // OpenAI Responses namespace for dynamically loaded tools\n\ttime: Type.Object({\n\t\tstart: Type.Number(), // Unix timestamp in milliseconds\n\t\tend: Type.Number(), // Unix timestamp in milliseconds, last known lifecycle update\n\t}),\n});\n\nexport const ToolSuccessResult = Type.Object({\n\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\tdetails: Type.Optional(Type.Any()),\n\tisError: Type.Literal(false),\n});\nexport const ToolErrorResult = Type.Object({\n\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\tdetails: Type.Optional(Type.Any()),\n\tisError: Type.Literal(true),\n});\nexport const ToolRunningPartial = Type.Object({\n\tcontent: Type.Optional(Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))),\n\tdetails: Type.Optional(Type.Any()),\n});\n\nexport const ToolStatusEnum = {\n\tpending: \"pending\",\n\trunning: \"running\",\n\tcompleted: \"completed\",\n\terror: \"error\",\n\tskipped: \"skipped\",\n\taborted: \"aborted\",\n} as const;\n\nexport const ToolRunningSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.running),\n\tpartial: Type.Optional(ToolRunningPartial),\n});\nexport const ToolCompletedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.completed),\n\tresult: ToolSuccessResult,\n});\nexport const ToolErrorSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.error),\n\tresult: ToolErrorResult,\n});\nexport const ToolSkippedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.skipped),\n\tresult: ToolErrorResult,\n});\nexport const ToolAbortedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.aborted),\n\tresult: ToolErrorResult,\n});\n\nexport const ToolCallPendingPartSchema = Type.Intersect([\n\tToolCallBaseSchema,\n\tType.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.pending),\n\t}),\n]);\nexport const ToolCallRunningPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolRunningSchema]));\nexport const ToolCallCompletedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));\nexport const ToolCallErrorPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolErrorSchema]));\nexport const ToolCallSkippedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));\nexport const ToolCallAbortedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));\nexport const ToolCallTerminalPartSchema = Type.Union([\n\tToolCallCompletedPartSchema,\n\tToolCallErrorPartSchema,\n\tToolCallSkippedPartSchema,\n\tToolCallAbortedPartSchema,\n]);\n\nexport const ToolCallInFlightSchema = Type.Object({\n\tcallID: Type.String(),\n\tname: Type.String(),\n\trawArgs: Type.Record(Type.String(), Type.Unknown()),\n\targs: Type.Optional(Type.Unknown()),\n});\nexport type ToolCallInFlight = Static<typeof ToolCallInFlightSchema>;\n\nexport const ToolCallSchema = Type.Union([\n\tToolCallPendingPartSchema,\n\tToolCallRunningPartSchema,\n\tToolCallTerminalPartSchema,\n]);\n\nexport type ToolCall = Static<typeof ToolCallSchema>;\nexport type ToolCallPendingPart = Static<typeof ToolCallPendingPartSchema>;\nexport type ToolCallRunningPart = Static<typeof ToolCallRunningPartSchema>;\nexport type ToolCallCompletedPart = Static<typeof ToolCallCompletedPartSchema>;\nexport type ToolCallErrorPart = Static<typeof ToolCallErrorPartSchema>;\nexport type ToolCallSkippedPart = Static<typeof ToolCallSkippedPartSchema>;\nexport type ToolCallAbortedPart = Static<typeof ToolCallAbortedPartSchema>;\nexport type ToolCallTerminalPart = Static<typeof ToolCallTerminalPartSchema>;\n\nexport const UsageSchema = Type.Object({\n\tinput: Type.Number(),\n\toutput: Type.Number(),\n\tcacheRead: Type.Number(),\n\tcacheWrite: Type.Number(),\n\t/** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */\n\tcacheWrite1h: Type.Optional(Type.Number()),\n\treasoning: Type.Optional(Type.Number()),\n\ttotalTokens: Type.Number(),\n\tcost: Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t\ttotal: Type.Number(),\n\t}),\n});\nexport type Usage = Static<typeof UsageSchema>;\n\nexport const StopReasonSchema = Type.Union([\n\tType.Literal(\"stop\"),\n\tType.Literal(\"length\"),\n\tType.Literal(\"toolUse\"),\n\tType.Literal(\"error\"),\n\tType.Literal(\"aborted\"),\n]);\nexport type StopReason = Static<typeof StopReasonSchema>;\n\nexport const UserMessageSchema = Type.Object({\n\tmessageId: Type.String(),\n\trole: Type.Literal(\"user\"),\n\ttime: Type.Object({\n\t\tcreated: Type.Number(),\n\t}),\n\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n});\nexport type UserMessage = Static<typeof UserMessageSchema>;\n\n/** Something aikit did on the caller's behalf while producing a message, such as a request retried in another shape. */\nexport const AssistantMessageDiagnosticSchema = Type.Object({\n\ttype: Type.String(),\n\ttimestamp: Type.Number(),\n\terror: Type.Optional(\n\t\tType.Object({\n\t\t\tname: Type.Optional(Type.String()),\n\t\t\tmessage: Type.String(),\n\t\t\tstack: Type.Optional(Type.String()),\n\t\t\tcode: Type.Optional(Type.Union([Type.String(), Type.Number()])),\n\t\t}),\n\t),\n\tdetails: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n});\nexport type AssistantMessageDiagnostic = Static<typeof AssistantMessageDiagnosticSchema>;\n\nexport const AssistantMessageSchema = Type.Object({\n\trole: Type.Literal(\"assistant\"),\n\tprotocol: Model.KnownProviderEnumSchema,\n\tprovider: Model.ProviderInfo,\n\tmodel: Type.String(),\n\t/** Thinking level the caller requested, before aikit fits it to the model. */\n\tthinkingLevel: Model.ThinkingLevel,\n\t/** Provider-native thinking value the request carried. Absent for budget-only or unmanaged reasoning. */\n\tproviderThinkingLevel: Type.Optional(Type.String()),\n\tusage: UsageSchema,\n\tstopReason: StopReasonSchema,\n\terrorMessage: Type.Optional(Type.String()),\n\t/**\n\t * Structured, provider-independent failure details for a failed request.\n\t * The schema is based on ai-sdk as the underlying provider wire protocol.\n\t * Depends on ai-sdk\n\t */\n\tfailure: Type.Optional(Failure.FailureSchema),\n\tdiagnostics: Type.Optional(Type.Array(AssistantMessageDiagnosticSchema)),\n\ttime: Type.Object({\n\t\tcreated: Type.Number(),\n\t\tcompleted: Type.Number(),\n\t}),\n\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema, ThinkingContentSchema, ToolCallSchema])),\n\tresponseId: Type.Optional(Type.String()), // Provider-specific response/message identifier when the upstream API exposes one\n\tresponseModel: Type.Optional(Type.String()), // Concrete routed model identifier when it differs from the requested model\n\tmessageId: Type.String(),\n});\nexport type AssistantMessage = Static<typeof AssistantMessageSchema>;\n\ntype UserMessageInit = Omit<UserMessage, \"messageId\"> & {\n\tmessageId?: string;\n};\n\ntype AssistantMessageInit = Omit<AssistantMessage, \"messageId\"> & {\n\tmessageId?: string;\n};\n\nexport function createMessageId(): string {\n\treturn uuidv7();\n}\n\nexport function createUserMessage(message: UserMessageInit): UserMessage {\n\tconst { messageId = createMessageId(), ...rest } = message;\n\treturn {\n\t\tmessageId,\n\t\t...rest,\n\t};\n}\n\nexport function createAssistantMessage(message: AssistantMessageInit): AssistantMessage {\n\tconst { messageId = createMessageId(), ...rest } = message;\n\treturn {\n\t\tmessageId,\n\t\t...rest,\n\t};\n}\n\nexport const GrammarVariantsSchema = Type.Partial(\n\tType.Object({\n\t\topenai_lark: Type.String(),\n\t\topenai_regex: Type.String(),\n\t}),\n);\nexport type GrammarVariants = Static<typeof GrammarVariantsSchema>;\n\nexport const ConstrainedSamplingSchema = Type.Union([\n\tType.Object({\n\t\ttype: Type.Literal(\"json_schema\"),\n\t\tstrict: Type.Union([Type.Literal(\"prefer\"), Type.Literal(\"require\")]),\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(\"grammar\"),\n\t\tvariants: GrammarVariantsSchema,\n\t}),\n]);\nexport type ConstrainedSampling = Static<typeof ConstrainedSamplingSchema>;\n\n/**\n * Generic tool definition with typed parameter schema.\n * Usage:\n *\n * const search = Message.defineTool({\n * name: \"search\",\n * description: \"Search documents\",\n * parameters: Type.Object({\n * query: Type.String(),\n * limit: Type.Optional(Type.Number()),\n * }),\n * });\n *\n * type SearchParams = Static<typeof search.parameters>;\n */\nexport const ToolSchema = Type.Object({\n\tname: Type.String(),\n\tdescription: Type.String(),\n\tparameters: Type.Unsafe<TSchema>({}),\n\tconstrainedSampling: Type.Optional(Type.Union([Type.Literal(false), ConstrainedSamplingSchema])),\n});\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n\t/** How the provider constrains generated tool-call arguments (strict JSON schema or grammar).\n\t * used by convert tool.\n\t * */\n\tconstrainedSampling?: false | ConstrainedSampling;\n}\nexport type ToolArguments<T extends Tool> = Static<T[\"parameters\"]>;\n\nexport function defineTool<TParameters extends TSchema>(tool: Tool<TParameters>): Tool<TParameters> {\n\treturn tool;\n}\n\nexport const ToolReferenceSchema = Type.Object({\n\tname: Type.String(),\n});\nexport type ToolReference = Static<typeof ToolReferenceSchema>;\n\n/**\n * A change to the system prompt and tool set at one point in the transcript.\n *\n * `Context.systemPrompt` and `Context.tools` hold the prompt and tools at the start of the\n * conversation; each system message changes them from its position on. Replaying them in\n * order yields the current prompt and tools. A redefinition is a removal plus an addition of\n * the same name.\n */\nexport const SystemMessageSchema = Type.Object({\n\tmessageId: Type.String(),\n\trole: Type.Literal(\"system\"),\n\ttime: Type.Object({\n\t\tcreated: Type.Number(),\n\t}),\n\t/** Instructions that apply from this point on, after the earlier ones. */\n\tcontent: Type.Optional(Type.String()),\n\t/**\n\t * Named prompt sections rendered after the content. A later message replaces a section by\n\t * name, and `null` removes it. Keep each section self-delimiting (a tag) so the model can\n\t * relate an update to the original, and avoid integer-like names, which JSON reorders.\n\t */\n\tsections: Type.Optional(Type.Record(Type.String(), Type.Union([Type.String(), Type.Null()]))),\n\t/** Complete definitions of tools that become available at this point. */\n\ttoolsAdded: Type.Optional(Type.Array(ToolSchema)),\n\t/** Tools that stop being available at this point. */\n\ttoolsRemoved: Type.Optional(Type.Array(ToolReferenceSchema)),\n\t/** Caller data kept with the message; never sent to a provider. */\n\tmetadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n});\nexport type SystemMessage = Static<typeof SystemMessageSchema>;\n\nexport const MessageSchema = Type.Union([SystemMessageSchema, UserMessageSchema, AssistantMessageSchema]);\nexport type Message = Static<typeof MessageSchema>;\n\ntype SystemMessageInit = Omit<SystemMessage, \"messageId\" | \"role\" | \"time\"> & {\n\tmessageId?: string;\n\ttime?: SystemMessage[\"time\"];\n};\n\nexport function createSystemMessage(message: SystemMessageInit): SystemMessage {\n\tconst { messageId = createMessageId(), time = { created: Date.now() }, ...rest } = message;\n\treturn { messageId, role: \"system\", time, ...rest };\n}\n\nexport const ContextSchema = Type.Object({\n\tsystemPrompt: Type.Optional(Type.String()),\n\tmessages: Type.Array(MessageSchema),\n\ttools: Type.Optional(Type.Array(ToolSchema)),\n\t/** Tools a later system message may add, for transports that must declare every tool up front. */\n\tdeferredTools: Type.Optional(Type.Array(ToolSchema)),\n});\nexport type Context = Static<typeof ContextSchema>;\n\nfunction isUnresolvedToolCall(toolCall: ToolCall): toolCall is ToolCallPendingPart | ToolCallRunningPart {\n\treturn toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;\n}\n\nfunction syntheticSkippedToolCall(toolCall: ToolCallPendingPart | ToolCallRunningPart): ToolCall {\n\tconst {\n\t\tstatus: _status,\n\t\tpartial: _partial,\n\t\t...base\n\t} = toolCall as (ToolCallPendingPart | ToolCallRunningPart) & {\n\t\tpartial?: unknown;\n\t};\n\n\treturn {\n\t\t...base,\n\t\tstatus: ToolStatusEnum.skipped,\n\t\tresult: {\n\t\t\tcontent: [{ type: \"text\", text: \"no result provided\" }],\n\t\t\tisError: true,\n\t\t},\n\t\ttime: {\n\t\t\t...toolCall.time,\n\t\t\tend: Math.max(toolCall.time.end, Date.now()),\n\t\t},\n\t};\n}\n\nconst USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\n\n// Consecutive images collapse into a single placeholder.\nexport function omitImages(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {\n\tconst result: TextContent[] = [];\n\tfor (const [index, block] of content.entries()) {\n\t\tif (block.type === \"text\") result.push(block);\n\t\telse if (content[index - 1]?.type !== \"image\") result.push({ type: \"text\", text: placeholder });\n\t}\n\treturn result;\n}\n\nfunction omitToolImages(toolCall: ToolCall): ToolCall {\n\tif (!(\"result\" in toolCall) || !toolCall.result.content.some((content) => content.type === \"image\")) return toolCall;\n\treturn {\n\t\t...toolCall,\n\t\tresult: { ...toolCall.result, content: omitImages(toolCall.result.content, TOOL_IMAGE_PLACEHOLDER) },\n\t} as ToolCall;\n}\n\nexport function transformMessages<TProtocol extends Model.KnownProviderEnum>(\n\tmessages: Message[],\n\tmodel: Model.TModel<TProtocol>,\n\tnormalizeToolCallId?: (id: string, model: Model.TModel<TProtocol>, source: AssistantMessage) => string,\n): Message[] {\n\tconst toolCallIDMap = new Map<string, string>();\n\tconst supportsImages = model.input.includes(\"image\");\n\n\tconst transformed: Message[] = [];\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"system\") {\n\t\t\ttransformed.push(msg);\n\t\t\tcontinue;\n\t\t}\n\t\tif (msg.role === \"user\") {\n\t\t\ttransformed.push(supportsImages ? msg : { ...msg, parts: omitImages(msg.parts, USER_IMAGE_PLACEHOLDER) });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tconst isSameModel =\n\t\t\tassistantMsg.provider.id === model.provider.id &&\n\t\t\tassistantMsg.protocol === model.protocol &&\n\t\t\tassistantMsg.model === model.id;\n\n\t\tconst transformedParts = assistantMsg.parts.flatMap((block) => {\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t// Signatures only verify on the model that made them, and readable thinking sent as\n\t\t\t\t// text makes the new model treat it as part of its visible reply.\n\t\t\t\tif (!isSameModel) return [];\n\t\t\t\t// Signed or redacted blocks replay even when empty (OpenAI encrypted reasoning).\n\t\t\t\tif (block.redacted || block.thinkingSignature) return block;\n\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\treturn block;\n\t\t\t}\n\n\t\t\tif (block.type === \"text\") {\n\t\t\t\tif (isSameModel) return block;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\ttext: block.text,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t}\n\n\t\t\t\tconst normalizedID = toolCallIDMap.get(block.callID);\n\t\t\t\tif (normalizedID && normalizedID !== block.callID) {\n\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: normalizedID };\n\t\t\t\t} else if (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\tconst nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);\n\t\t\t\t\tif (nextID !== toolCall.callID) {\n\t\t\t\t\t\ttoolCallIDMap.set(toolCall.callID, nextID);\n\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: nextID };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn normalizedToolCall;\n\t\t\t}\n\n\t\t\treturn block;\n\t\t});\n\t\tconst parts = transformedParts.map((block) => {\n\t\t\tif (block.type !== \"toolCall\") return block;\n\t\t\tconst toolCall = isUnresolvedToolCall(block) ? syntheticSkippedToolCall(block) : block;\n\t\t\treturn supportsImages ? toolCall : omitToolImages(toolCall);\n\t\t});\n\n\t\ttransformed.push({\n\t\t\t...assistantMsg,\n\t\t\tparts,\n\t\t});\n\t}\n\n\treturn transformed;\n}\n","import type {\n\tLanguageModelV3CallOptions,\n\tLanguageModelV3FunctionTool,\n\tLanguageModelV3ToolChoice,\n\tSharedV3Warning,\n} from \"@ai-sdk/provider\";\nimport type { TSchema } from \"typebox\";\nimport * as Message from \"../../message/message.ts\";\n\nexport type ResponsesTool =\n\t| {\n\t\t\ttype: \"function\";\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tparameters: Record<string, unknown>;\n\t\t\tstrict?: boolean | null;\n\t\t\tdefer_loading?: boolean;\n\t }\n\t| {\n\t\t\ttype: \"custom\";\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tformat: {\n\t\t\t\ttype: \"grammar\";\n\t\t\t\tsyntax: \"lark\" | \"regex\";\n\t\t\t\tdefinition: string;\n\t\t\t};\n\t\t\tdefer_loading?: boolean;\n\t };\n\nexport type ResponsesGrammarConstraint = {\n\ttype: \"grammar\";\n\tformat: \"lark\" | \"regex\";\n\tdefinition: string;\n\tinputProperty: string;\n};\n\nexport type GrammarInputBuffer = {\n\tinput: string;\n\tstarted: boolean;\n\tclosed: boolean;\n};\n\nexport function appendGrammarInputJsonDelta(\n\tbuffer: GrammarInputBuffer,\n\tinputProperty: string,\n\tnextInput: string,\n\tclose: boolean,\n): string | undefined {\n\tif (buffer.closed) {\n\t\tif (close && nextInput === buffer.input) return undefined;\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed after it was closed`);\n\t}\n\tif (!nextInput.startsWith(buffer.input)) {\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed non-monotonically`);\n\t}\n\n\tconst inputDelta = nextInput.slice(buffer.input.length);\n\tif (!close && inputDelta.length === 0) return undefined;\n\n\tlet delta = \"\";\n\tif (!buffer.started) {\n\t\tdelta += `{${JSON.stringify(inputProperty)}:\"`;\n\t\tbuffer.started = true;\n\t}\n\tdelta += JSON.stringify(inputDelta).slice(1, -1);\n\tbuffer.input = nextInput;\n\n\tif (close) {\n\t\tdelta += '\"}';\n\t\tbuffer.closed = true;\n\t}\n\treturn delta;\n}\n\ntype JsonSchemaObject = {\n\ttype?: unknown;\n\tproperties?: Record<string, { type?: unknown } | undefined>;\n\trequired?: unknown;\n};\n\nfunction inferGrammarInputProperty(parameters: TSchema): string {\n\tconst schema = parameters as JsonSchemaObject;\n\tif (schema.type !== \"object\") throw new Error(\"grammar constrained sampling requires an object parameter schema\");\n\tif (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== \"string\") {\n\t\tthrow new Error(\"grammar constrained sampling requires exactly one required string property\");\n\t}\n\tconst inputProperty = schema.required[0];\n\tif (!schema.properties?.[inputProperty]) {\n\t\tthrow new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);\n\t}\n\tif (schema.properties[inputProperty]?.type !== \"string\") {\n\t\tthrow new Error(`grammar constrained sampling property ${inputProperty} must have type string`);\n\t}\n\treturn inputProperty;\n}\n\nexport function resolveToolGrammar(\n\ttool: Message.Tool,\n\tcompat?: { supportsOpenAIGrammarTools?: boolean },\n): ResponsesGrammarConstraint | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config || config.type !== \"grammar\") return undefined;\n\tif (!(compat?.supportsOpenAIGrammarTools ?? false)) return undefined;\n\n\tconst lark = config.variants.openai_lark;\n\tconst regex = config.variants.openai_regex;\n\tconst hasLark = typeof lark === \"string\" && lark.trim().length > 0;\n\tconst hasRegex = typeof regex === \"string\" && regex.trim().length > 0;\n\tif (!hasLark && !hasRegex) {\n\t\tthrow new Error(\n\t\t\t`Tool \"${tool.name}\" cannot use grammar constrained sampling: no supported grammar variant was provided.`,\n\t\t);\n\t}\n\ttry {\n\t\treturn {\n\t\t\ttype: \"grammar\",\n\t\t\tformat: hasLark ? \"lark\" : \"regex\",\n\t\t\tdefinition: hasLark ? lark! : regex!,\n\t\t\tinputProperty: inferGrammarInputProperty(tool.parameters),\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`tool \"${tool.name}\" cannot use grammar constrained sampling: ${message}.`);\n\t}\n}\n\nexport type ResponsesToolChoice = \"auto\" | \"none\" | \"required\";\n\n/**\n * Tool changes declared at a system message's position, carried in its\n * `providerOptions[<provider>].toolChange`. `changes` declares tools in\n * `additional_tools` items; `additions` declares them as a synthetic tool search.\n */\nexport type ResponsesToolChange = {\n\tmode: \"changes\" | \"additions\";\n\ttools: LanguageModelV3FunctionTool[];\n\tremoved: string[];\n};\n\n/** A function tool carries its grammar in `providerOptions[<provider>].grammar`. */\nfunction toolGrammar(tool: LanguageModelV3FunctionTool, provider: string): ResponsesGrammarConstraint | undefined {\n\tconst metadata = tool.providerOptions?.[provider] as Record<string, unknown> | undefined;\n\tconst grammar = metadata?.grammar as ResponsesGrammarConstraint | undefined;\n\treturn grammar?.type === \"grammar\" ? grammar : undefined;\n}\n\nexport function toResponsesTool(tool: LanguageModelV3FunctionTool, provider: string): ResponsesTool {\n\tconst grammar = toolGrammar(tool, provider);\n\treturn grammar\n\t\t? {\n\t\t\t\ttype: \"custom\",\n\t\t\t\tname: tool.name,\n\t\t\t\t...(tool.description !== undefined && { description: tool.description }),\n\t\t\t\tformat: {\n\t\t\t\t\ttype: \"grammar\",\n\t\t\t\t\tsyntax: grammar.format,\n\t\t\t\t\tdefinition: grammar.definition,\n\t\t\t\t},\n\t\t\t}\n\t\t: {\n\t\t\t\ttype: \"function\",\n\t\t\t\tname: tool.name,\n\t\t\t\t...(tool.description !== undefined && { description: tool.description }),\n\t\t\t\tparameters: tool.inputSchema as Record<string, unknown>,\n\t\t\t\tstrict: tool.strict ?? null,\n\t\t\t};\n}\n\nexport function prepareResponsesTools({\n\tprovider,\n\ttools,\n\ttoolChoice,\n\tinPlaceToolNames,\n}: {\n\tprovider: string;\n\ttools: LanguageModelV3CallOptions[\"tools\"];\n\ttoolChoice: LanguageModelV3ToolChoice | undefined;\n\t/** Tools declared in place in the input; they stay out of the top-level list. */\n\tinPlaceToolNames?: ReadonlySet<string>;\n}): {\n\tresponsesTools: ResponsesTool[] | undefined;\n\tgrammarToolInputProperties: ReadonlyMap<string, string>;\n\ttoolChoiceValue: ResponsesToolChoice | undefined;\n\twarnings: SharedV3Warning[];\n} {\n\tconst warnings: SharedV3Warning[] = [];\n\tconst grammarToolInputProperties = new Map<string, string>();\n\n\tif (!tools || tools.length === 0) {\n\t\treturn {\n\t\t\tresponsesTools: undefined,\n\t\t\tgrammarToolInputProperties,\n\t\t\ttoolChoiceValue: undefined,\n\t\t\twarnings,\n\t\t};\n\t}\n\n\tconst responsesTools: ResponsesTool[] = [];\n\tfor (const tool of tools) {\n\t\tif (tool.type !== \"function\") {\n\t\t\twarnings.push({\n\t\t\t\ttype: \"unsupported\",\n\t\t\t\tfeature: `tool type ${tool.type}`,\n\t\t\t\tdetails: `Only function tools are supported; ignoring ${tool.name}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst grammar = toolGrammar(tool, provider);\n\t\tif (grammar) grammarToolInputProperties.set(tool.name, grammar.inputProperty);\n\t\tif (!inPlaceToolNames?.has(tool.name)) responsesTools.push(toResponsesTool(tool, provider));\n\t}\n\n\tlet toolChoiceValue: ResponsesToolChoice | undefined;\n\tswitch (toolChoice?.type) {\n\t\tcase undefined:\n\t\t\tbreak;\n\t\tcase \"auto\":\n\t\tcase \"none\":\n\t\tcase \"required\":\n\t\t\ttoolChoiceValue = toolChoice.type;\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\twarnings.push({\n\t\t\t\ttype: \"unsupported\",\n\t\t\t\tfeature: \"toolChoice tool name\",\n\t\t\t\tdetails: \"Forcing a specific tool is not supported; using 'required' instead.\",\n\t\t\t});\n\t\t\ttoolChoiceValue = \"required\";\n\t\t\tbreak;\n\t}\n\n\treturn {\n\t\tresponsesTools: responsesTools.length > 0 ? responsesTools : undefined,\n\t\tgrammarToolInputProperties,\n\t\ttoolChoiceValue,\n\t\twarnings,\n\t};\n}\n","/** Fast deterministic hash for shortening provider wire identifiers. */\nexport function shortHash(value: string): string {\n\tlet high = 0xdeadbeef;\n\tlet low = 0x41c6ce57;\n\tfor (let index = 0; index < value.length; index++) {\n\t\tconst character = value.charCodeAt(index);\n\t\thigh = Math.imul(high ^ character, 2654435761);\n\t\tlow = Math.imul(low ^ character, 1597334677);\n\t}\n\thigh = Math.imul(high ^ (high >>> 16), 2246822507) ^ Math.imul(low ^ (low >>> 13), 3266489909);\n\tlow = Math.imul(low ^ (low >>> 16), 2246822507) ^ Math.imul(high ^ (high >>> 13), 3266489909);\n\treturn (low >>> 0).toString(36) + (high >>> 0).toString(36);\n}\n","import { APICallError } from \"@ai-sdk/provider\";\n\ntype ResponsesError = {\n\tcode?: string;\n\ttype?: string;\n\tmessage?: string;\n\tplan_type?: string;\n\tresets_at?: number;\n};\n\ntype ResponsesErrorPayload = {\n\terror?: ResponsesError;\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n\nconst asString = (value: unknown): string | undefined =>\n\ttypeof value === \"string\" && value.trim() ? value.trim() : undefined;\n\nfunction normalizeErrorPayload(value: unknown): ResponsesErrorPayload {\n\tconst record = asRecord(value);\n\tconst nested = asRecord(record?.error);\n\tconst source = nested ?? record ?? {};\n\tconst code = asString(source.code);\n\tconst type = asString(source.type);\n\tconst message = asString(source.message);\n\tconst planType = asString(source.plan_type);\n\tconst error: ResponsesError = {\n\t\t...(code !== undefined && { code }),\n\t\t...(type !== undefined && { type }),\n\t\t...(message !== undefined && { message }),\n\t\t...(planType !== undefined && { plan_type: planType }),\n\t\t...(typeof source.resets_at === \"number\" && { resets_at: source.resets_at }),\n\t};\n\treturn { error };\n}\n\nfunction parseErrorPayload(body: string): ResponsesErrorPayload | undefined {\n\ttry {\n\t\treturn normalizeErrorPayload(JSON.parse(body) as unknown);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction errorIdentifiers(error: ResponsesError | undefined): string {\n\treturn `${error?.code ?? \"\"} ${error?.type ?? \"\"}`.toLowerCase();\n}\n\nfunction hasIdentifier(error: ResponsesError | undefined, identifiers: readonly string[]): boolean {\n\tconst value = errorIdentifiers(error);\n\treturn identifiers.some((identifier) => value.includes(identifier));\n}\n\nfunction isUsageLimitError(error: ResponsesError | undefined): boolean {\n\treturn hasIdentifier(error, [\"usage_limit_reached\", \"gousagelimiterror\", \"freeusagelimiterror\"]);\n}\n\nfunction isTerminalRateLimitError(body: string, payload = parseErrorPayload(body)): boolean {\n\treturn (\n\t\tisUsageLimitError(payload?.error) ||\n\t\thasIdentifier(payload?.error, [\"usage_not_included\", \"insufficient_quota\"]) ||\n\t\t/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|out of budget|quota exceeded|billing/i.test(\n\t\t\tbody,\n\t\t)\n\t);\n}\n\nfunction streamErrorStatus(error: ResponsesError | undefined): number {\n\tif (isUsageLimitError(error) || hasIdentifier(error, [\"usage_not_included\", \"insufficient_quota\", \"rate_limit\"])) {\n\t\treturn 429;\n\t}\n\tif (hasIdentifier(error, [\"server_is_overloaded\", \"slow_down\"])) return 503;\n\tif (\n\t\thasIdentifier(error, [\n\t\t\t\"context_length_exceeded\",\n\t\t\t\"invalid_prompt\",\n\t\t\t\"bio_policy\",\n\t\t\t\"cyber_policy\",\n\t\t\t\"misalignment_policy_violation\",\n\t\t])\n\t) {\n\t\treturn 400;\n\t}\n\treturn 500;\n}\n\nfunction retryAfterHeader(message: string | undefined): Record<string, string> {\n\tconst match = message?.match(/try again in\\s*(\\d+(?:\\.\\d+)?)\\s*(s|ms|seconds?)/i);\n\tif (!match) return {};\n\tconst value = Number(match[1]);\n\tif (!Number.isFinite(value)) return {};\n\treturn { \"retry-after\": String(match[2]?.toLowerCase() === \"ms\" ? value / 1_000 : value) };\n}\n\n/**\n * Turn a Responses error payload into a human-friendly message. Only terminal\n * ChatGPT plan exhaustion is rewritten; transient 429s retain backend detail.\n * `label` names the backend, e.g. \"OpenAI Codex\".\n */\nexport function responsesErrorMessage(label: string, body: string, statusText?: string): string {\n\tlet message = body || statusText || `${label} request failed`;\n\tconst payload = parseErrorPayload(body);\n\tconst error = payload?.error;\n\n\tif (isUsageLimitError(error)) {\n\t\tconst plan = error?.plan_type ? ` (${error.plan_type.toLowerCase()} plan)` : \"\";\n\t\tconst minutes = error?.resets_at\n\t\t\t? Math.max(0, Math.round((error.resets_at * 1000 - Date.now()) / 60000))\n\t\t\t: undefined;\n\t\tconst when = minutes === undefined ? \"\" : ` Try again in ~${minutes} min.`;\n\t\treturn `You have hit your ChatGPT usage limit${plan}.${when}`.trim();\n\t}\n\n\tif (error?.message) message = error.message;\n\treturn message;\n}\n\nexport async function createResponsesAPICallError(args: {\n\tlabel: string;\n\tresponse: Response;\n\turl: string;\n\trequestBodyValues: unknown;\n}): Promise<APICallError> {\n\tconst { response, url, requestBodyValues } = args;\n\tconst responseBody = await response.text().catch(() => \"\");\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\tconst data = parseErrorPayload(responseBody);\n\n\treturn new APICallError({\n\t\tmessage: responsesErrorMessage(args.label, responseBody, response.statusText),\n\t\turl,\n\t\trequestBodyValues,\n\t\tstatusCode: response.status,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\t...(data !== undefined && { data }),\n\t\tisRetryable:\n\t\t\tresponse.status === 408 ||\n\t\t\tresponse.status === 409 ||\n\t\t\t(response.status === 429 && !isTerminalRateLimitError(responseBody, data)) ||\n\t\t\tresponse.status >= 500,\n\t});\n}\n\n/** Map an error embedded in a successful SSE response to the same API error shape as HTTP failures. */\nexport function createResponsesStreamError(args: {\n\tlabel: string;\n\terror: unknown;\n\turl: string;\n\trequestBodyValues: unknown;\n\tresponseHeaders?: Record<string, string>;\n}): APICallError {\n\tconst { error: value, url, requestBodyValues } = args;\n\tconst data = normalizeErrorPayload(value);\n\tconst error = data.error;\n\tconst statusCode = streamErrorStatus(error);\n\tconst responseBody = JSON.stringify(data);\n\tconst responseHeaders = {\n\t\t...args.responseHeaders,\n\t\t...retryAfterHeader(error?.message),\n\t};\n\n\treturn new APICallError({\n\t\tmessage: responsesErrorMessage(args.label, responseBody),\n\t\turl,\n\t\trequestBodyValues,\n\t\tstatusCode,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\tdata,\n\t\tisRetryable:\n\t\t\tstatusCode >= 500 || (hasIdentifier(error, [\"rate_limit\"]) && !isTerminalRateLimitError(responseBody, data)),\n\t});\n}\n\n/** A transport failure used when an SSE response ends without a terminal Responses event. */\nexport function createResponsesPrematureCloseError(args: {\n\tlabel: string;\n\turl: string;\n\trequestBodyValues: unknown;\n\tresponseHeaders?: Record<string, string>;\n}): APICallError {\n\treturn new APICallError({\n\t\tmessage: `${args.label} stream closed before response.completed`,\n\t\turl: args.url,\n\t\trequestBodyValues: args.requestBodyValues,\n\t\t...(args.responseHeaders !== undefined && { responseHeaders: args.responseHeaders }),\n\t\tisRetryable: true,\n\t});\n}\n\n/**\n * A fetch that rejects never produced a response, but its body was still sent. Wrap\n * it the way AI SDK providers do, so it reads as a retryable transport failure that\n * carries the request. Aborts pass through untouched.\n */\nexport function responsesFetchError(error: unknown, url: string, requestBodyValues: unknown): unknown {\n\tif (error instanceof Error && (error.name === \"AbortError\" || error.name === \"TimeoutError\")) return error;\n\tconst cause = error instanceof Error && error.cause instanceof Error ? error.cause : error;\n\treturn new APICallError({\n\t\tmessage: `Cannot connect to API: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\tcause: error,\n\t\turl,\n\t\trequestBodyValues,\n\t\tisRetryable: true,\n\t});\n}\n","import type {\n\tLanguageModelV3FilePart,\n\tLanguageModelV3Prompt,\n\tLanguageModelV3ToolResultOutput,\n\tLanguageModelV4FilePart,\n\tLanguageModelV4Prompt,\n\tLanguageModelV4ToolResultOutput,\n} from \"@ai-sdk/provider\";\nimport { shortHash } from \"../../utils/hash.ts\";\nimport { toResponsesTool, type ResponsesTool, type ResponsesToolChange } from \"./tools.ts\";\n\n/**\n * OpenAI Responses API input item types this transport sends.\n */\nexport type ResponsesInputItem =\n\t| {\n\t\t\trole: \"user\";\n\t\t\tcontent: Array<\n\t\t\t\t{ type: \"input_text\"; text: string } | { type: \"input_image\"; image_url: string; detail?: string }\n\t\t\t>;\n\t }\n\t| {\n\t\t\ttype: \"message\";\n\t\t\trole: \"assistant\";\n\t\t\tid: string;\n\t\t\tcontent: Array<{ type: \"output_text\"; text: string; annotations: unknown[] }>;\n\t\t\tstatus: \"completed\";\n\t }\n\t| {\n\t\t\ttype: \"function_call\";\n\t\t\tid?: string;\n\t\t\tcall_id: string;\n\t\t\tname: string;\n\t\t\targuments: string;\n\t\t\tnamespace?: string;\n\t }\n\t| {\n\t\t\ttype: \"custom_tool_call\";\n\t\t\tid?: string;\n\t\t\tcall_id: string;\n\t\t\tname: string;\n\t\t\tinput: string;\n\t\t\tnamespace?: string;\n\t }\n\t| {\n\t\t\ttype: \"reasoning\";\n\t\t\tid: string;\n\t\t\t[key: string]: unknown;\n\t }\n\t| {\n\t\t\ttype: \"function_call_output\";\n\t\t\tcall_id: string;\n\t\t\toutput:\n\t\t\t\t| string\n\t\t\t\t| Array<{ type: \"input_text\"; text: string } | { type: \"input_image\"; image_url: string; detail: \"auto\" }>;\n\t }\n\t| {\n\t\t\ttype: \"custom_tool_call_output\";\n\t\t\tcall_id: string;\n\t\t\toutput: string;\n\t }\n\t| {\n\t\t\trole: \"developer\";\n\t\t\tcontent: string;\n\t }\n\t| {\n\t\t\ttype: \"additional_tools\";\n\t\t\trole: \"developer\";\n\t\t\ttools: ResponsesTool[];\n\t }\n\t| {\n\t\t\ttype: \"tool_search_call\";\n\t\t\tcall_id: string;\n\t\t\texecution: \"client\";\n\t\t\tstatus: \"completed\";\n\t\t\targuments: { query: string; limit: number };\n\t }\n\t| {\n\t\t\ttype: \"tool_search_output\";\n\t\t\tcall_id: string;\n\t\t\texecution: \"client\";\n\t\t\tstatus: \"completed\";\n\t\t\ttools: ResponsesTool[];\n\t };\n\nexport type ResponsesPrompt = {\n\t/** The system prompt, when it travels in the `instructions` field. */\n\tinstructions?: string;\n\tinput: ResponsesInputItem[];\n};\n\nconst DEFAULT_INSTRUCTIONS = \"You are a helpful assistant.\";\n\nexport type ResponsesPromptOptions = {\n\t/** The providerOptions key this transport reads, e.g. `openai-codex`. */\n\tprovider: string;\n\t/**\n\t * Where the leading system prompt goes: the `instructions` field (the Codex backend\n\t * requires one), or a developer message in place.\n\t */\n\tsystemPrompt: \"instructions\" | \"developer\";\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tsupportsImages?: boolean;\n};\n\n// Tool call ids round-trip through the AI SDK as `call_id|item_id` because the\n// Responses API needs both halves: `call_id` to pair function_call_output and\n// `id` for the function_call item itself.\nexport function splitToolCallId(toolCallId: string): { callId: string; itemId: string } {\n\tconst separator = toolCallId.indexOf(\"|\");\n\tif (separator === -1) return { callId: toolCallId, itemId: toolCallId };\n\treturn { callId: toolCallId.slice(0, separator), itemId: toolCallId.slice(separator + 1) };\n}\n\nexport function joinToolCallId(callId: string, itemId: string): string {\n\treturn `${callId}|${itemId}`;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) {\n\t\tbinary += String.fromCharCode(byte);\n\t}\n\treturn btoa(binary);\n}\n\nfunction imageUrlFromFilePart(part: LanguageModelV3FilePart | LanguageModelV4FilePart): string | undefined {\n\tconst data = part.data;\n\tif (data instanceof URL) return data.toString();\n\tif (typeof data === \"string\") {\n\t\tif (data.startsWith(\"data:\") || data.startsWith(\"http://\") || data.startsWith(\"https://\")) return data;\n\t\treturn `data:${part.mediaType};base64,${data}`;\n\t}\n\tif (data instanceof Uint8Array) {\n\t\treturn `data:${part.mediaType};base64,${uint8ArrayToBase64(data)}`;\n\t}\n\tif (\"type\" in data) {\n\t\tif (data.type === \"url\") return data.url.toString();\n\t\tif (data.type === \"data\") {\n\t\t\treturn typeof data.data === \"string\"\n\t\t\t\t? `data:${part.mediaType};base64,${data.data}`\n\t\t\t\t: `data:${part.mediaType};base64,${uint8ArrayToBase64(data.data)}`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction toolResultOutput(\n\toutput: LanguageModelV3ToolResultOutput | LanguageModelV4ToolResultOutput,\n\tsupportsImages: boolean,\n): Extract<ResponsesInputItem, { type: \"function_call_output\" }>[\"output\"] {\n\tswitch (output.type) {\n\t\tcase \"text\":\n\t\tcase \"error-text\":\n\t\t\treturn output.value || \"(no tool output)\";\n\t\tcase \"json\":\n\t\tcase \"error-json\":\n\t\t\treturn JSON.stringify(output.value);\n\t\tcase \"execution-denied\":\n\t\t\treturn output.reason ?? \"Tool execution denied\";\n\t\tcase \"content\": {\n\t\t\tconst text = output.value\n\t\t\t\t.filter((part): part is Extract<typeof part, { type: \"text\" }> => part.type === \"text\")\n\t\t\t\t.map((part) => part.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst images: Array<{ type: \"input_image\"; image_url: string; detail: \"auto\" }> = [];\n\t\t\tif (supportsImages) {\n\t\t\t\tfor (const part of output.value) {\n\t\t\t\t\tif (part.type === \"file-data\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\timages.push({\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\timage_url: `data:${part.mediaType};base64,${part.data}`,\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (part.type === \"file-url\") {\n\t\t\t\t\t\timages.push({ type: \"input_image\", image_url: part.url, detail: \"auto\" });\n\t\t\t\t\t} else if (part.type === \"file\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\tconst data = part.data;\n\t\t\t\t\t\tif (data.type === \"url\") {\n\t\t\t\t\t\t\timages.push({ type: \"input_image\", image_url: data.url.toString(), detail: \"auto\" });\n\t\t\t\t\t\t} else if (data.type === \"data\") {\n\t\t\t\t\t\t\tconst encoded = typeof data.data === \"string\" ? data.data : uint8ArrayToBase64(data.data);\n\t\t\t\t\t\t\timages.push({\n\t\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\t\timage_url: `data:${part.mediaType};base64,${encoded}`,\n\t\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (images.length === 0)\n\t\t\t\treturn text || (output.value.length > 0 ? \"(see attached image)\" : \"(no tool output)\");\n\t\t\treturn [...(text ? [{ type: \"input_text\" as const, text }] : []), ...images];\n\t\t}\n\t\tdefault:\n\t\t\treturn JSON.stringify(output);\n\t}\n}\n\nfunction customToolInput(input: unknown, toolName: string, inputProperty: string): string {\n\tif (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n\t\tthrow new Error(`custom tool \"${toolName}\" requires object input with string property \"${inputProperty}\".`);\n\t}\n\tconst value = (input as Record<string, unknown>)[inputProperty];\n\tif (typeof value !== \"string\") {\n\t\tthrow new Error(`custom tool \"${toolName}\" requires string input property \"${inputProperty}\".`);\n\t}\n\treturn value;\n}\n\nfunction customToolOutput(\n\toutput: LanguageModelV3ToolResultOutput | LanguageModelV4ToolResultOutput,\n\tsupportsImages: boolean,\n): string {\n\tconst value = toolResultOutput(output, supportsImages);\n\treturn typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\nfunction providerMetadata(\n\tproviderOptions: Record<string, unknown> | undefined,\n\tprovider: string,\n): Record<string, unknown> | undefined {\n\tconst metadata = providerOptions?.[provider];\n\treturn typeof metadata === \"object\" && metadata !== null && !Array.isArray(metadata)\n\t\t? (metadata as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction toolChange(\n\tproviderOptions: Record<string, unknown> | undefined,\n\tprovider: string,\n): ResponsesToolChange | undefined {\n\treturn providerMetadata(providerOptions, provider)?.toolChange as ResponsesToolChange | undefined;\n}\n\nfunction reasoningItem(\n\tproviderOptions: Record<string, unknown> | undefined,\n\tprovider: string,\n): Extract<ResponsesInputItem, { type: \"reasoning\" }> | undefined {\n\tconst value = providerMetadata(providerOptions, provider)?.reasoningItem;\n\tif (typeof value !== \"string\") return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n\t\tconst item = parsed as Record<string, unknown>;\n\t\treturn item.type === \"reasoning\" && typeof item.id === \"string\"\n\t\t\t? (item as Extract<ResponsesInputItem, { type: \"reasoning\" }>)\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Names of every tool declared in place by a system message's tool change. */\nexport function collectInPlaceToolNames(\n\tprompt: LanguageModelV3Prompt | LanguageModelV4Prompt,\n\tprovider: string,\n): Set<string> {\n\tconst names = new Set<string>();\n\tfor (const message of prompt) {\n\t\tif (message.role !== \"system\") continue;\n\t\tfor (const tool of toolChange(message.providerOptions, provider)?.tools ?? []) names.add(tool.name);\n\t}\n\treturn names;\n}\n\n/*\n * `additional_tools` items accumulate: a later item adds tools and replaces same-name\n * definitions from earlier ones, but cannot remove any. Without this notice, models read the\n * latest item as the complete tool set once a removal was announced, and restating the tools\n * that are still unavailable keeps smaller models from calling them after later loads.\n */\nfunction incrementalToolsNotice(unavailable: ReadonlySet<string>): string {\n\tconst notice =\n\t\t\"This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.\";\n\treturn unavailable.size > 0 ? `${notice}\\nStill unavailable: ${[...unavailable].join(\", \")}.` : notice;\n}\n\nfunction toolRemovalNotice(names: readonly string[]): string {\n\treturn `The following tools are no longer available. Do not call them:\\n${names.map((name) => `- ${name}`).join(\"\\n\")}`;\n}\n\n/**\n * Convert an AI SDK V3 prompt into the Responses request shape. The leading system\n * message goes where `options.systemPrompt` says, later ones (prompt updates and tool\n * changes) go in place, and everything else maps to `input` items.\n */\nexport function convertToResponsesPrompt(\n\tprompt: LanguageModelV3Prompt | LanguageModelV4Prompt,\n\toptions: ResponsesPromptOptions,\n): ResponsesPrompt {\n\tconst { provider } = options;\n\tlet instructions: string | undefined;\n\tconst input: ResponsesInputItem[] = [];\n\tlet syntheticMessageCounter = 0;\n\tlet toolChangeCounter = 0;\n\tlet declaredAdditionalTools = false;\n\t/** Tools announced as removed and not declared again since. */\n\tconst unavailableTools = new Set<string>();\n\n\t/** Declares the change's tools; returns the removal notice, which goes with the message's text. */\n\tconst appendToolChange = (change: ResponsesToolChange): string | undefined => {\n\t\tconst seed = toolChangeCounter++;\n\t\tconst tools = change.tools.map((tool) => toResponsesTool(tool, provider));\n\t\tfor (const tool of tools) unavailableTools.delete(tool.name);\n\t\tif (tools.length > 0 && change.mode === \"changes\") {\n\t\t\tif (declaredAdditionalTools) {\n\t\t\t\tinput.push({ role: \"developer\", content: incrementalToolsNotice(unavailableTools) });\n\t\t\t}\n\t\t\tdeclaredAdditionalTools = true;\n\t\t\tinput.push({ type: \"additional_tools\", role: \"developer\", tools });\n\t\t} else if (tools.length > 0) {\n\t\t\tconst names = tools.map((tool) => tool.name);\n\t\t\tconst callId = `cdwrk_aikit_tool_${shortHash(`${seed}:${names.join(\",\")}`)}`;\n\t\t\tinput.push({\n\t\t\t\ttype: \"tool_search_call\",\n\t\t\t\tcall_id: callId,\n\t\t\t\texecution: \"client\",\n\t\t\t\tstatus: \"completed\",\n\t\t\t\targuments: { query: names.join(\" \"), limit: names.length },\n\t\t\t});\n\t\t\tinput.push({\n\t\t\t\ttype: \"tool_search_output\",\n\t\t\t\tcall_id: callId,\n\t\t\t\texecution: \"client\",\n\t\t\t\tstatus: \"completed\",\n\t\t\t\ttools: tools.map((tool) => ({ ...tool, defer_loading: true })),\n\t\t\t});\n\t\t}\n\t\t// A redefinition is a removal plus an addition of the same name; only true removals are announced.\n\t\tconst added = new Set(tools.map((tool) => tool.name));\n\t\tconst removed = change.removed.filter((name) => !added.has(name));\n\t\tif (removed.length === 0) return;\n\t\t// Recorded after this change's additions, whose notice precedes this removal notice.\n\t\tfor (const name of removed) unavailableTools.add(name);\n\t\treturn toolRemovalNotice(removed);\n\t};\n\n\tfor (const message of prompt) {\n\t\tswitch (message.role) {\n\t\t\tcase \"system\": {\n\t\t\t\tconst change = toolChange(message.providerOptions, provider);\n\t\t\t\t// The first plain system message is the leading prompt; every later one is an update in place.\n\t\t\t\tif (!change && options.systemPrompt === \"instructions\" && instructions === undefined) {\n\t\t\t\t\tinstructions = message.content;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst removal = change ? appendToolChange(change) : undefined;\n\t\t\t\tconst text = [message.content, removal ?? \"\"].filter((part) => part.length > 0).join(\"\\n\\n\");\n\t\t\t\tif (text.length > 0) input.push({ role: \"developer\", content: text });\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"user\": {\n\t\t\t\tconst content: Extract<ResponsesInputItem, { role: \"user\" }>[\"content\"] = [];\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type === \"text\") {\n\t\t\t\t\t\tcontent.push({ type: \"input_text\", text: part.text });\n\t\t\t\t\t} else if (part.type === \"file\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\tconst imageUrl = imageUrlFromFilePart(part);\n\t\t\t\t\t\tif (imageUrl) content.push({ type: \"input_image\", image_url: imageUrl, detail: \"auto\" });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (content.length > 0) {\n\t\t\t\t\tinput.push({ role: \"user\", content });\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"assistant\": {\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type === \"reasoning\") {\n\t\t\t\t\t\tconst item = reasoningItem(part.providerOptions, provider);\n\t\t\t\t\t\tif (item) input.push(item);\n\t\t\t\t\t} else if (part.type === \"text\") {\n\t\t\t\t\t\tsyntheticMessageCounter++;\n\t\t\t\t\t\tconst messageId = providerMetadata(part.providerOptions, provider)?.messageId;\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\tid:\n\t\t\t\t\t\t\t\ttypeof messageId === \"string\" && messageId.length <= 64\n\t\t\t\t\t\t\t\t\t? messageId\n\t\t\t\t\t\t\t\t\t: `msg_cdwrk_aikit_${syntheticMessageCounter}`,\n\t\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: part.text, annotations: [] }],\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (part.type === \"tool-call\") {\n\t\t\t\t\t\tconst { callId, itemId } = splitToolCallId(part.toolCallId);\n\t\t\t\t\t\tconst metadata = providerMetadata(part.providerOptions, provider);\n\t\t\t\t\t\tconst namespace = metadata?.namespace;\n\t\t\t\t\t\tconst inputProperty = options.grammarToolInputProperties?.get(part.toolName);\n\t\t\t\t\t\tif (inputProperty) {\n\t\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\t\t...(metadata?.omitItemId === true || !itemId.startsWith(\"ctc_\") ? {} : { id: itemId }),\n\t\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\t\tname: part.toolName,\n\t\t\t\t\t\t\t\tinput: customToolInput(part.input, part.toolName, inputProperty),\n\t\t\t\t\t\t\t\t...(typeof namespace === \"string\" ? { namespace } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\t\t\t...(metadata?.omitItemId === true || !itemId.startsWith(\"fc_\") ? {} : { id: itemId }),\n\t\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\t\tname: part.toolName,\n\t\t\t\t\t\t\t\targuments: typeof part.input === \"string\" ? part.input : JSON.stringify(part.input ?? {}),\n\t\t\t\t\t\t\t\t...(typeof namespace === \"string\" ? { namespace } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool\": {\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type !== \"tool-result\") continue;\n\t\t\t\t\tconst { callId } = splitToolCallId(part.toolCallId);\n\t\t\t\t\tif (options.grammarToolInputProperties?.has(part.toolName)) {\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\toutput: customToolOutput(part.output, options.supportsImages ?? true),\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"function_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\toutput: toolResultOutput(part.output, options.supportsImages ?? true),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (options.systemPrompt === \"developer\") return { input };\n\treturn { instructions: instructions || DEFAULT_INSTRUCTIONS, input };\n}\n","import { EventSourceParserStream, type EventSourceMessage } from \"eventsource-parser/stream\";\n\n/** Parse standards-compliant event streams from a Responses endpoint. */\nexport function parseResponsesSSEStream(body: ReadableStream<Uint8Array>): ReadableStream<Record<string, unknown>> {\n\tconst decoder = new TextDecoder();\n\treturn body\n\t\t.pipeThrough(\n\t\t\tnew TransformStream<Uint8Array, string>({\n\t\t\t\ttransform(chunk, controller) {\n\t\t\t\t\tconst text = decoder.decode(chunk, { stream: true });\n\t\t\t\t\tif (text) controller.enqueue(text);\n\t\t\t\t},\n\t\t\t\tflush(controller) {\n\t\t\t\t\tconst text = decoder.decode();\n\t\t\t\t\tif (text) controller.enqueue(text);\n\t\t\t\t},\n\t\t\t}),\n\t\t)\n\t\t.pipeThrough(new EventSourceParserStream({ onError: \"terminate\" }))\n\t\t.pipeThrough(\n\t\t\tnew TransformStream<EventSourceMessage, Record<string, unknown>>({\n\t\t\t\ttransform(event, controller) {\n\t\t\t\t\tconst data = event.data.trim();\n\t\t\t\t\tif (!data || data === \"[DONE]\") return;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed: unknown = JSON.parse(data);\n\t\t\t\t\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\t\t\t\t\tthrow new TypeError(\"Responses SSE data must be a JSON object\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(parsed as Record<string, unknown>);\n\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\tcontroller.error(new Error(`invalid Responses SSE JSON: ${data.slice(0, 200)}`, { cause }));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n}\n","import type { JSONObject, LanguageModelV3FinishReason, LanguageModelV3Usage } from \"@ai-sdk/provider\";\n\nexport type ResponsesUsage = {\n\tinput_tokens?: number;\n\toutput_tokens?: number;\n\ttotal_tokens?: number;\n\tinput_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n\toutput_tokens_details?: { reasoning_tokens?: number };\n};\n\nexport function convertResponsesUsage(usage: ResponsesUsage | undefined): LanguageModelV3Usage {\n\tconst inputTotal = usage?.input_tokens;\n\tconst cachedTokens = usage?.input_tokens_details?.cached_tokens ?? 0;\n\tconst cacheWriteTokens = usage?.input_tokens_details?.cache_write_tokens ?? 0;\n\tconst outputTotal = usage?.output_tokens;\n\tconst reasoningTokens = usage?.output_tokens_details?.reasoning_tokens ?? 0;\n\n\treturn {\n\t\tinputTokens: {\n\t\t\ttotal: inputTotal,\n\t\t\tnoCache: inputTotal === undefined ? undefined : Math.max(inputTotal - cachedTokens - cacheWriteTokens, 0),\n\t\t\tcacheRead: inputTotal === undefined ? undefined : cachedTokens,\n\t\t\tcacheWrite: inputTotal === undefined ? undefined : cacheWriteTokens,\n\t\t},\n\t\toutputTokens: {\n\t\t\ttotal: outputTotal,\n\t\t\ttext: outputTotal === undefined ? undefined : outputTotal - reasoningTokens,\n\t\t\treasoning: outputTotal === undefined ? undefined : reasoningTokens,\n\t\t},\n\t\t...(usage ? { raw: usage as JSONObject } : {}),\n\t};\n}\n\nexport function mapResponsesFinishReason(\n\tstatus: string | undefined,\n\thasToolCalls: boolean,\n\tincompleteReason?: string,\n): LanguageModelV3FinishReason {\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn { unified: hasToolCalls ? \"tool-calls\" : \"stop\", raw: status };\n\t\tcase \"incomplete\":\n\t\t\treturn incompleteReason === \"max_output_tokens\"\n\t\t\t\t? { unified: \"length\", raw: `${status}.${incompleteReason}` }\n\t\t\t\t: { unified: \"error\", raw: incompleteReason ? `${status}.${incompleteReason}` : status };\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn { unified: \"error\", raw: status };\n\t\tcase undefined:\n\t\t\treturn { unified: \"other\", raw: undefined };\n\t\tdefault:\n\t\t\treturn { unified: \"stop\", raw: status };\n\t}\n}\n","import type * as NodeZlib from \"node:zlib\";\nimport type {\n\tLanguageModelV3,\n\tLanguageModelV3CallOptions,\n\tLanguageModelV3Content,\n\tLanguageModelV3FinishReason,\n\tLanguageModelV3GenerateResult,\n\tLanguageModelV3StreamPart,\n\tLanguageModelV3StreamResult,\n\tLanguageModelV3Usage,\n\tSharedV3Warning,\n} from \"@ai-sdk/provider\";\nimport {\n\tcreateResponsesAPICallError,\n\tresponsesFetchError,\n\tcreateResponsesPrematureCloseError,\n\tcreateResponsesStreamError,\n} from \"./error.ts\";\nimport { collectInPlaceToolNames, convertToResponsesPrompt, joinToolCallId } from \"./prompt.ts\";\nimport { parseResponsesSSEStream } from \"./sse.ts\";\nimport { appendGrammarInputJsonDelta, prepareResponsesTools, type GrammarInputBuffer } from \"./tools.ts\";\nimport { convertResponsesUsage, mapResponsesFinishReason, type ResponsesUsage } from \"./usage.ts\";\n\nexport const PROMPT_CACHE_KEY_MAX_LENGTH = 64;\nconst REQUEST_COMPRESSION_ZSTD_LEVEL = 3;\n// The Responses API rejects max_output_tokens below 16.\nconst MIN_OUTPUT_TOKENS = 16;\n\ntype ProcessWithBuiltinModule = typeof process & {\n\tgetBuiltinModule?: (id: \"node:zlib\") => typeof NodeZlib;\n};\n\nfunction compressRequest(body: string): Uint8Array | undefined {\n\tif (typeof process === \"undefined\" || !(process.versions?.node || process.versions?.bun)) return undefined;\n\tconst zlib = (process as ProcessWithBuiltinModule).getBuiltinModule?.(\"node:zlib\");\n\tif (!zlib || typeof zlib.zstdCompressSync !== \"function\") return undefined;\n\ttry {\n\t\tconst compressed = zlib.zstdCompressSync(body, {\n\t\t\tparams: { [zlib.constants.ZSTD_c_compressionLevel]: REQUEST_COMPRESSION_ZSTD_LEVEL },\n\t\t});\n\t\treturn new Uint8Array(compressed.buffer, compressed.byteOffset, compressed.byteLength);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function clampPromptCacheKey(key: string | undefined): string | undefined {\n\tif (key === undefined) return undefined;\n\tconst characters = Array.from(key);\n\treturn characters.length <= PROMPT_CACHE_KEY_MAX_LENGTH\n\t\t? key\n\t\t: characters.slice(0, PROMPT_CACHE_KEY_MAX_LENGTH).join(\"\");\n}\n\nexport type ResponsesServiceTier = \"auto\" | \"default\" | \"flex\" | \"scale\" | \"priority\";\n\nexport type ResponsesCompatibility = {\n\t/** Internal transport capability derived from the model's input modalities. */\n\tsupportsImages?: boolean;\n};\n\n/**\n * Per-call options, passed via `providerOptions[<provider>]`.\n */\nexport type ResponsesLanguageModelOptions = {\n\t/** Reasoning effort forwarded as `reasoning.effort`. */\n\treasoningEffort?: \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | (string & {});\n\t/** Reasoning summary verbosity; defaults to `auto` when an effort is set. */\n\treasoningSummary?: \"auto\" | \"concise\" | \"detailed\" | \"off\" | \"on\" | null;\n\t/** Output text verbosity; defaults to the backend's `request.textVerbosity`. */\n\ttextVerbosity?: \"low\" | \"medium\" | \"high\";\n\tserviceTier?: ResponsesServiceTier;\n\t/**\n\t * The string input property of each grammar tool the conversation declared, including tools\n\t * since removed, so their earlier calls replay as grammar calls. The current tools win.\n\t */\n\tgrammarToolInputProperties?: Record<string, string>;\n};\n\n/** How one Responses backend takes a request. */\nexport type ResponsesRequestProfile = {\n\t/** Where system prompt text goes: the `instructions` field, or a developer message in place. */\n\tsystemPrompt: \"instructions\" | \"developer\";\n\t/** Whether `max_output_tokens` is sent; the ChatGPT Codex backend rejects it. */\n\tmaxOutputTokens: boolean;\n\t/** Whether `reasoning.encrypted_content` is requested on every call or only with an effort. */\n\tencryptedReasoning: \"always\" | \"withEffort\";\n\t/** zstd-compress the body; a fetch that reads the JSON body needs it uncompressed. */\n\tcompress: boolean;\n\t/**\n\t * Whether `tool_choice: \"auto\"` and `parallel_tool_calls` go on every request, as the Codex\n\t * backend expects. Otherwise only a tool choice the call names is sent: some proxied models\n\t * (Grok on Copilot) reject either field on a request without tools.\n\t */\n\ttoolDefaults: boolean;\n\t/** `text.verbosity` when the call sets none. */\n\ttextVerbosity?: ResponsesLanguageModelOptions[\"textVerbosity\"];\n};\n\nexport type ResponsesLanguageModelConfig = {\n\t/** Provider name, and the providerOptions / providerMetadata key. */\n\tprovider: string;\n\t/** Backend name for error messages, e.g. \"OpenAI Codex\". */\n\tlabel: string;\n\turl: string;\n\theaders: () => PromiseLike<Record<string, string | undefined>> | Record<string, string | undefined>;\n\tfetch?: typeof globalThis.fetch;\n\tpromptCacheKey?: string;\n\tserviceTier?: ResponsesServiceTier;\n\tcompat?: ResponsesCompatibility;\n\trequest: ResponsesRequestProfile;\n};\n\ntype ResponsesEvent = Record<string, unknown>;\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as ResponsesEvent) : undefined;\n}\n\nfunction asString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction cleanHeaders(headers: Record<string, string | undefined>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value !== undefined) result[key] = value;\n\t}\n\treturn result;\n}\n\nexport class ResponsesLanguageModel implements LanguageModelV3 {\n\treadonly specificationVersion = \"v3\" as const;\n\treadonly modelId: string;\n\n\tprivate readonly config: ResponsesLanguageModelConfig;\n\n\tconstructor(modelId: string, config: ResponsesLanguageModelConfig) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t}\n\n\tget provider(): string {\n\t\treturn this.config.provider;\n\t}\n\n\tget supportedUrls(): Record<string, RegExp[]> {\n\t\treturn {};\n\t}\n\n\tprivate getArgs(options: LanguageModelV3CallOptions): {\n\t\targs: Record<string, unknown>;\n\t\twarnings: SharedV3Warning[];\n\t\tgrammarToolInputProperties: ReadonlyMap<string, string>;\n\t} {\n\t\tconst warnings: SharedV3Warning[] = [];\n\n\t\tif (options.topP != null) warnings.push({ type: \"unsupported\", feature: \"topP\" });\n\t\tif (options.topK != null) warnings.push({ type: \"unsupported\", feature: \"topK\" });\n\t\tif (options.presencePenalty != null) warnings.push({ type: \"unsupported\", feature: \"presencePenalty\" });\n\t\tif (options.frequencyPenalty != null) warnings.push({ type: \"unsupported\", feature: \"frequencyPenalty\" });\n\t\tif (options.seed != null) warnings.push({ type: \"unsupported\", feature: \"seed\" });\n\t\tif (options.stopSequences != null) warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n\t\tif (options.maxOutputTokens != null && !this.config.request.maxOutputTokens) {\n\t\t\twarnings.push({ type: \"unsupported\", feature: \"maxOutputTokens\" });\n\t\t}\n\t\tif (options.responseFormat?.type === \"json\" && options.responseFormat.schema === undefined) {\n\t\t\twarnings.push({ type: \"unsupported\", feature: \"responseFormat\" });\n\t\t}\n\n\t\tconst { provider, request } = this.config;\n\t\tconst callOptions = (options.providerOptions?.[provider] ?? {}) as ResponsesLanguageModelOptions;\n\t\tconst tools = prepareResponsesTools({\n\t\t\tprovider,\n\t\t\ttools: options.tools,\n\t\t\ttoolChoice: options.toolChoice,\n\t\t\tinPlaceToolNames: collectInPlaceToolNames(options.prompt, provider),\n\t\t});\n\t\tconst { instructions, input } = convertToResponsesPrompt(options.prompt, {\n\t\t\tprovider,\n\t\t\tsystemPrompt: request.systemPrompt,\n\t\t\tgrammarToolInputProperties: new Map([\n\t\t\t\t...Object.entries(callOptions.grammarToolInputProperties ?? {}),\n\t\t\t\t...tools.grammarToolInputProperties,\n\t\t\t]),\n\t\t\tsupportsImages: this.config.compat?.supportsImages ?? false,\n\t\t});\n\t\twarnings.push(...tools.warnings);\n\n\t\tconst verbosity = callOptions.textVerbosity ?? request.textVerbosity;\n\t\tconst text: Record<string, unknown> = verbosity ? { verbosity } : {};\n\t\tif (options.responseFormat?.type === \"json\" && options.responseFormat.schema !== undefined) {\n\t\t\ttext.format = {\n\t\t\t\ttype: \"json_schema\",\n\t\t\t\tstrict: true,\n\t\t\t\tschema: options.responseFormat.schema,\n\t\t\t\tname: options.responseFormat.name ?? \"output_schema\",\n\t\t\t};\n\t\t}\n\n\t\tconst args: Record<string, unknown> = {\n\t\t\tmodel: this.modelId,\n\t\t\t// Reasoning replays from encrypted content, so nothing is stored server-side.\n\t\t\tstore: false,\n\t\t\t...(instructions !== undefined && { instructions }),\n\t\t\tinput,\n\t\t\t...(request.toolDefaults\n\t\t\t\t? { tool_choice: tools.toolChoiceValue ?? \"auto\", parallel_tool_calls: true }\n\t\t\t\t: tools.toolChoiceValue !== undefined && { tool_choice: tools.toolChoiceValue }),\n\t\t\t...((request.encryptedReasoning === \"always\" || callOptions.reasoningEffort) && {\n\t\t\t\tinclude: [\"reasoning.encrypted_content\"],\n\t\t\t}),\n\t\t\t...(Object.keys(text).length > 0 && { text }),\n\t\t};\n\n\t\tif (tools.responsesTools) args.tools = tools.responsesTools;\n\t\tif (options.temperature != null) args.temperature = options.temperature;\n\t\tif (request.maxOutputTokens && options.maxOutputTokens != null) {\n\t\t\targs.max_output_tokens = Math.max(options.maxOutputTokens, MIN_OUTPUT_TOKENS);\n\t\t}\n\n\t\tconst promptCacheKey = clampPromptCacheKey(this.config.promptCacheKey);\n\t\tif (promptCacheKey) args.prompt_cache_key = promptCacheKey;\n\n\t\tconst serviceTier = callOptions.serviceTier ?? this.config.serviceTier;\n\t\tif (serviceTier) args.service_tier = serviceTier;\n\n\t\tif (callOptions.reasoningEffort) {\n\t\t\targs.reasoning = {\n\t\t\t\teffort: callOptions.reasoningEffort,\n\t\t\t\tsummary: callOptions.reasoningSummary ?? \"auto\",\n\t\t\t};\n\t\t}\n\n\t\treturn { args, warnings, grammarToolInputProperties: tools.grammarToolInputProperties };\n\t}\n\n\tasync doGenerate(options: LanguageModelV3CallOptions): Promise<LanguageModelV3GenerateResult> {\n\t\tconst { stream, request, response } = await this.doStream(options);\n\n\t\tconst content: LanguageModelV3Content[] = [];\n\t\tconst textBlocks = new Map<string, Extract<LanguageModelV3Content, { type: \"text\" }>>();\n\t\tconst reasoningBlocks = new Map<string, Extract<LanguageModelV3Content, { type: \"reasoning\" }>>();\n\t\tconst warnings: SharedV3Warning[] = [];\n\t\tlet finishReason: LanguageModelV3FinishReason = { unified: \"other\", raw: undefined };\n\t\tlet usage: LanguageModelV3Usage = convertResponsesUsage(undefined);\n\t\tlet responseId: string | undefined;\n\t\tlet responseModelId: string | undefined;\n\n\t\tconst reader = stream.getReader();\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\n\t\t\tswitch (value.type) {\n\t\t\t\tcase \"stream-start\":\n\t\t\t\t\twarnings.push(...value.warnings);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\tresponseId = value.id;\n\t\t\t\t\tresponseModelId = value.modelId;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"text-start\": {\n\t\t\t\t\tconst block = { type: \"text\" as const, text: \"\" };\n\t\t\t\t\ttextBlocks.set(value.id, block);\n\t\t\t\t\tcontent.push(block);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-delta\": {\n\t\t\t\t\tconst block = textBlocks.get(value.id);\n\t\t\t\t\tif (block) block.text += value.delta;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-end\": {\n\t\t\t\t\tconst block = textBlocks.get(value.id);\n\t\t\t\t\tif (block && value.providerMetadata !== undefined) block.providerMetadata = value.providerMetadata;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\tconst block = { type: \"reasoning\" as const, text: \"\" };\n\t\t\t\t\treasoningBlocks.set(value.id, block);\n\t\t\t\t\tcontent.push(block);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-delta\": {\n\t\t\t\t\tconst block = reasoningBlocks.get(value.id);\n\t\t\t\t\tif (block) block.text += value.delta;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-end\": {\n\t\t\t\t\tconst block = reasoningBlocks.get(value.id);\n\t\t\t\t\tif (block && value.providerMetadata !== undefined) block.providerMetadata = value.providerMetadata;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-call\":\n\t\t\t\t\tcontent.push(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tfinishReason = value.finishReason;\n\t\t\t\t\tusage = value.usage;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tthrow value.error instanceof Error ? value.error : new Error(String(value.error));\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: content.filter((part) =>\n\t\t\t\tpart.type === \"text\" || part.type === \"reasoning\"\n\t\t\t\t\t? part.text !== \"\" || part.providerMetadata !== undefined\n\t\t\t\t\t: true,\n\t\t\t),\n\t\t\tfinishReason,\n\t\t\tusage,\n\t\t\t...(request !== undefined && { request }),\n\t\t\tresponse: {\n\t\t\t\t...response,\n\t\t\t\t...(responseId !== undefined && { id: responseId }),\n\t\t\t\t...(responseModelId !== undefined && { modelId: responseModelId }),\n\t\t\t},\n\t\t\twarnings,\n\t\t};\n\t}\n\n\tasync doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {\n\t\tconst { args, warnings, grammarToolInputProperties } = this.getArgs(options);\n\t\tconst body = { ...args, stream: true };\n\t\tconst { url, label } = this.config;\n\n\t\tconst headers = cleanHeaders({\n\t\t\t...(await this.config.headers()),\n\t\t\t...options.headers,\n\t\t});\n\t\tconst bodyJson = JSON.stringify(body);\n\t\tconst compressedBody = this.config.request.compress ? compressRequest(bodyJson) : undefined;\n\t\tif (compressedBody) headers[\"content-encoding\"] = \"zstd\";\n\n\t\tconst fetchImpl = this.config.fetch ?? globalThis.fetch;\n\t\tconst response = await fetchImpl(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: compressedBody ?? bodyJson,\n\t\t\t...(options.abortSignal !== undefined && { signal: options.abortSignal }),\n\t\t}).catch((error: unknown) => {\n\t\t\tthrow responsesFetchError(error, url, body);\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow await createResponsesAPICallError({ label, response, url, requestBodyValues: body });\n\t\t}\n\t\tif (!response.body) {\n\t\t\tthrow new Error(`${label} response has no body`);\n\t\t}\n\n\t\tconst responseHeaders: Record<string, string> = {};\n\t\tresponse.headers.forEach((value, key) => {\n\t\t\tresponseHeaders[key] = value;\n\t\t});\n\n\t\treturn {\n\t\t\tstream: parseResponsesSSEStream(response.body).pipeThrough(\n\t\t\t\tthis.createTransformStream(warnings, options.includeRawChunks ?? false, grammarToolInputProperties, {\n\t\t\t\t\tlabel,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: body,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t}),\n\t\t\t),\n\t\t\trequest: { body },\n\t\t\tresponse: { headers: responseHeaders },\n\t\t};\n\t}\n\n\tprivate createTransformStream(\n\t\twarnings: SharedV3Warning[],\n\t\tincludeRawChunks: boolean,\n\t\tgrammarToolInputProperties: ReadonlyMap<string, string>,\n\t\trequest: {\n\t\t\tlabel: string;\n\t\t\turl: string;\n\t\t\trequestBodyValues: unknown;\n\t\t\tresponseHeaders: Record<string, string>;\n\t\t},\n\t): TransformStream<ResponsesEvent, LanguageModelV3StreamPart> {\n\t\tconst { provider } = this.config;\n\t\tlet finishReason: LanguageModelV3FinishReason = { unified: \"other\", raw: undefined };\n\t\tlet usage: ResponsesUsage | undefined;\n\t\tlet hasToolCalls = false;\n\t\tlet finished = false;\n\t\tlet servedServiceTier: string | undefined;\n\t\t/*\n\t\t * Items are tracked by `output_index`: Copilot sends a different item id on every\n\t\t * event of the same item. Tool parts use the composite `call_id|item_id` from the\n\t\t * item's first event so multi-turn replay can recover both halves.\n\t\t */\n\t\ttype Slot =\n\t\t\t| { kind: \"text\"; id: string }\n\t\t\t| { kind: \"reasoning\"; id: string }\n\t\t\t| { kind: \"function\"; toolCallId: string; toolName: string }\n\t\t\t| {\n\t\t\t\t\tkind: \"custom\";\n\t\t\t\t\ttoolCallId: string;\n\t\t\t\t\ttoolName: string;\n\t\t\t\t\tinputProperty: string;\n\t\t\t\t\tbuffer: GrammarInputBuffer;\n\t\t\t };\n\t\tconst slots = new Map<string, Slot>();\n\t\tconst slotKey = (event: ResponsesEvent, item?: ResponsesEvent): string | undefined =>\n\t\t\ttypeof event.output_index === \"number\"\n\t\t\t\t? `#${event.output_index}`\n\t\t\t\t: (asString(event.item_id) ?? asString(item?.id));\n\t\tconst finish = (controller: TransformStreamDefaultController<LanguageModelV3StreamPart>): void => {\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"finish\",\n\t\t\t\tfinishReason,\n\t\t\t\tusage: convertResponsesUsage(usage),\n\t\t\t\t// The tier the response was served at decides what it costs, and it is\n\t\t\t\t// not always the tier that was requested.\n\t\t\t\t...(servedServiceTier === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { providerMetadata: { [provider]: { serviceTier: servedServiceTier } } }),\n\t\t\t});\n\t\t};\n\t\tconst fail = (controller: TransformStreamDefaultController<LanguageModelV3StreamPart>, error: unknown): void => {\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\tcontroller.enqueue({ type: \"error\", error });\n\t\t\tcontroller.terminate();\n\t\t};\n\n\t\tconst startSlot = (\n\t\t\tkey: string,\n\t\t\titem: ResponsesEvent,\n\t\t\tcontroller: TransformStreamDefaultController<LanguageModelV3StreamPart>,\n\t\t): Slot | undefined => {\n\t\t\tconst itemType = asString(item.type);\n\t\t\tconst itemId = asString(item.id);\n\t\t\tif (!itemType || !itemId) return;\n\n\t\t\tlet slot: Slot | undefined;\n\t\t\tif (itemType === \"message\") {\n\t\t\t\tslot = { kind: \"text\", id: itemId };\n\t\t\t\tcontroller.enqueue({ type: \"text-start\", id: itemId });\n\t\t\t} else if (itemType === \"reasoning\") {\n\t\t\t\tslot = { kind: \"reasoning\", id: itemId };\n\t\t\t\tcontroller.enqueue({ type: \"reasoning-start\", id: itemId });\n\t\t\t} else if (itemType === \"function_call\") {\n\t\t\t\tconst toolName = asString(item.name) ?? \"\";\n\t\t\t\tslot = { kind: \"function\", toolCallId: joinToolCallId(asString(item.call_id) ?? itemId, itemId), toolName };\n\t\t\t\thasToolCalls = true;\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-start\", id: slot.toolCallId, toolName });\n\t\t\t} else if (itemType === \"custom_tool_call\") {\n\t\t\t\tconst toolName = asString(item.name) ?? \"\";\n\t\t\t\tslot = {\n\t\t\t\t\tkind: \"custom\",\n\t\t\t\t\ttoolCallId: joinToolCallId(asString(item.call_id) ?? itemId, itemId),\n\t\t\t\t\ttoolName,\n\t\t\t\t\tinputProperty: grammarToolInputProperties.get(toolName) ?? \"input\",\n\t\t\t\t\tbuffer: { input: \"\", started: false, closed: false },\n\t\t\t\t};\n\t\t\t\thasToolCalls = true;\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-start\", id: slot.toolCallId, toolName });\n\t\t\t}\n\t\t\tif (slot) slots.set(key, slot);\n\t\t\treturn slot;\n\t\t};\n\n\t\tconst endSlot = (\n\t\t\tkey: string,\n\t\t\titem: ResponsesEvent,\n\t\t\tcontroller: TransformStreamDefaultController<LanguageModelV3StreamPart>,\n\t\t) => {\n\t\t\tconst slot = slots.get(key) ?? startSlot(key, item, controller);\n\t\t\tif (!slot) return;\n\t\t\tslots.delete(key);\n\t\t\tconst namespace = asString(item.namespace);\n\t\t\tconst namespaceMetadata = namespace ? { providerMetadata: { [provider]: { namespace } } } : {};\n\n\t\t\tif (slot.kind === \"text\") {\n\t\t\t\tconst messageId = asString(item.id) ?? slot.id;\n\t\t\t\tcontroller.enqueue({ type: \"text-end\", id: slot.id, providerMetadata: { [provider]: { messageId } } });\n\t\t\t} else if (slot.kind === \"reasoning\") {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\tid: slot.id,\n\t\t\t\t\tproviderMetadata: { [provider]: { reasoningItem: JSON.stringify(item) } },\n\t\t\t\t});\n\t\t\t} else if (slot.kind === \"function\") {\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-end\", id: slot.toolCallId });\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\ttoolCallId: slot.toolCallId,\n\t\t\t\t\ttoolName: asString(item.name) ?? slot.toolName,\n\t\t\t\t\tinput: asString(item.arguments) ?? \"\",\n\t\t\t\t\t...namespaceMetadata,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst input = asString(item.input) ?? slot.buffer.input;\n\t\t\t\tconst delta = appendGrammarInputJsonDelta(slot.buffer, slot.inputProperty, input, true);\n\t\t\t\tif (delta) controller.enqueue({ type: \"tool-input-delta\", id: slot.toolCallId, delta });\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-end\", id: slot.toolCallId });\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\ttoolCallId: slot.toolCallId,\n\t\t\t\t\ttoolName: slot.toolName,\n\t\t\t\t\tinput: JSON.stringify({ [slot.inputProperty]: input }),\n\t\t\t\t\t...namespaceMetadata,\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\treturn new TransformStream<ResponsesEvent, LanguageModelV3StreamPart>({\n\t\t\tstart(controller) {\n\t\t\t\tcontroller.enqueue({ type: \"stream-start\", warnings });\n\t\t\t},\n\n\t\t\ttransform(event, controller) {\n\t\t\t\tif (includeRawChunks) {\n\t\t\t\t\tcontroller.enqueue({ type: \"raw\", rawValue: event });\n\t\t\t\t}\n\n\t\t\t\tconst type = asString(event.type);\n\t\t\t\tif (!type) return;\n\n\t\t\t\tswitch (type) {\n\t\t\t\t\tcase \"response.created\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tconst id = asString(response?.id);\n\t\t\t\t\t\tconst modelId = asString(response?.model);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"response-metadata\",\n\t\t\t\t\t\t\t...(id !== undefined && { id }),\n\t\t\t\t\t\t\t...(modelId !== undefined && { modelId }),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_item.added\": {\n\t\t\t\t\t\tconst item = asRecord(event.item);\n\t\t\t\t\t\tconst key = item ? slotKey(event, item) : undefined;\n\t\t\t\t\t\tif (item && key) startSlot(key, item, controller);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_text.delta\": {\n\t\t\t\t\t\tconst slot = slots.get(slotKey(event) ?? \"\");\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tif (slot?.kind === \"text\" && delta) controller.enqueue({ type: \"text-delta\", id: slot.id, delta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.reasoning_text.delta\":\n\t\t\t\t\tcase \"response.reasoning_summary_text.delta\": {\n\t\t\t\t\t\tconst slot = slots.get(slotKey(event) ?? \"\");\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tif (slot?.kind === \"reasoning\" && delta) {\n\t\t\t\t\t\t\tcontroller.enqueue({ type: \"reasoning-delta\", id: slot.id, delta });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.function_call_arguments.delta\": {\n\t\t\t\t\t\tconst slot = slots.get(slotKey(event) ?? \"\");\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tif (slot?.kind === \"function\" && delta) {\n\t\t\t\t\t\t\tcontroller.enqueue({ type: \"tool-input-delta\", id: slot.toolCallId, delta });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.custom_tool_call_input.delta\":\n\t\t\t\t\tcase \"response.custom_tool_call_input.done\": {\n\t\t\t\t\t\tconst slot = slots.get(slotKey(event) ?? \"\");\n\t\t\t\t\t\tif (slot?.kind !== \"custom\") break;\n\t\t\t\t\t\tconst done = type === \"response.custom_tool_call_input.done\";\n\t\t\t\t\t\tconst input = done ? asString(event.input) : slot.buffer.input + (asString(event.delta) ?? \"\");\n\t\t\t\t\t\tif (input === undefined) break;\n\t\t\t\t\t\tconst jsonDelta = appendGrammarInputJsonDelta(slot.buffer, slot.inputProperty, input, done);\n\t\t\t\t\t\tif (jsonDelta)\n\t\t\t\t\t\t\tcontroller.enqueue({ type: \"tool-input-delta\", id: slot.toolCallId, delta: jsonDelta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_item.done\": {\n\t\t\t\t\t\tconst item = asRecord(event.item);\n\t\t\t\t\t\tconst key = item ? slotKey(event, item) : undefined;\n\t\t\t\t\t\tif (item && key) endSlot(key, item, controller);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.completed\":\n\t\t\t\t\tcase \"response.incomplete\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tusage = (response?.usage as ResponsesUsage | undefined) ?? usage;\n\t\t\t\t\t\tservedServiceTier = asString(response?.service_tier) ?? servedServiceTier;\n\t\t\t\t\t\tconst status =\n\t\t\t\t\t\t\tasString(response?.status) ?? (type === \"response.incomplete\" ? \"incomplete\" : \"completed\");\n\t\t\t\t\t\tconst incompleteReason = asString(asRecord(response?.incomplete_details)?.reason);\n\t\t\t\t\t\tfinishReason = mapResponsesFinishReason(status, hasToolCalls, incompleteReason);\n\t\t\t\t\t\tfinish(controller);\n\t\t\t\t\t\tcontroller.terminate();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.failed\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tconst error = asRecord(response?.error);\n\t\t\t\t\t\tfinishReason = { unified: \"error\", raw: \"failed\" };\n\t\t\t\t\t\tfail(\n\t\t\t\t\t\t\tcontroller,\n\t\t\t\t\t\t\tcreateResponsesStreamError({\n\t\t\t\t\t\t\t\terror: error ?? { message: `${request.label} response failed` },\n\t\t\t\t\t\t\t\t...request,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tconst code = asString(event.code);\n\t\t\t\t\t\tfinishReason = { unified: \"error\", raw: code ?? \"error\" };\n\t\t\t\t\t\tfail(controller, createResponsesStreamError({ error: event, ...request }));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// Ignore lifecycle events we do not surface (content_part, in_progress, ...).\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tflush(controller) {\n\t\t\t\tif (!finished) {\n\t\t\t\t\tfinished = true;\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terror: createResponsesPrematureCloseError(request),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;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Y;IACjB,IAAI,CAAC,UAAU;KACd,WAAW;KACX,WAAW,QAAQ;MAClB,MAAM;MACN,OAAO,mCAAmC,OAAO;KAClD,CAAC;IACF;GACD;EACD,CAAC;CACF;AACD"}
|
|
1
|
+
{"version":3,"file":"model-Bngx_P1p.mjs","names":["Type","Model.KnownProviderEnumSchema","Model.ProviderInfo","Model.ThinkingLevel","Failure.FailureSchema","asRecord","asString"],"sources":["../../src/message/message.ts","../../src/providers/responses/tools.ts","../../src/utils/hash.ts","../../src/providers/responses/error.ts","../../src/providers/responses/prompt.ts","../../src/providers/responses/sse.ts","../../src/providers/responses/usage.ts","../../src/providers/responses/model.ts"],"sourcesContent":["import Type, { type Static, type TSchema } from \"typebox\";\nimport { uuidv7 } from \"uuidv7\";\nimport * as Failure from \"../llm/failure/schema.ts\";\nimport * as Model from \"../model/model.ts\";\n\nexport const TextContentSchema = Type.Object({\n\ttype: Type.Literal(\"text\"),\n\ttext: Type.String(),\n\ttextSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the message ID\n});\nexport type TextContent = Static<typeof TextContentSchema>;\n\nexport const ImageContentSchema = Type.Object({\n\ttype: Type.Literal(\"image\"),\n\tdata: Type.String(), // base64 encoded image data\n\tmimeType: Type.String(), // e.g., \"image/jpeg\", \"image/png\"\n});\nexport type ImageContent = Static<typeof ImageContentSchema>;\n\nexport const ThinkingContentSchema = Type.Object({\n\ttype: Type.Literal(\"thinking\"),\n\tthinking: Type.String(),\n\t// Provider-native replay data: an Anthropic signature, serialized OpenAI\n\t// reasoning metadata, or a serialized OpenAI Codex reasoning item.\n\tthinkingSignature: Type.Optional(Type.String()),\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted: Type.Optional(Type.Boolean()),\n});\nexport type ThinkingContent = Static<typeof ThinkingContentSchema>;\n\nexport const ToolCallBaseSchema = Type.Object({\n\ttype: Type.Literal(\"toolCall\"),\n\tcallID: Type.String(),\n\tname: Type.String(),\n\targuments: Type.Record(Type.String(), Type.Any()),\n\tthoughtSignature: Type.Optional(Type.String()), // Google-specific: opaque signature for reusing thought context\n\tnamespace: Type.Optional(Type.String()), // OpenAI Responses namespace for dynamically loaded tools\n\ttime: Type.Object({\n\t\tstart: Type.Number(), // Unix timestamp in milliseconds\n\t\tend: Type.Number(), // Unix timestamp in milliseconds, last known lifecycle update\n\t}),\n});\n\nexport const ToolSuccessResult = Type.Object({\n\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\tdetails: Type.Optional(Type.Any()),\n\tisError: Type.Literal(false),\n});\nexport const ToolErrorResult = Type.Object({\n\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\tdetails: Type.Optional(Type.Any()),\n\tisError: Type.Literal(true),\n});\nexport const ToolRunningPartial = Type.Object({\n\tcontent: Type.Optional(Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))),\n\tdetails: Type.Optional(Type.Any()),\n});\n\nexport const ToolStatusEnum = {\n\tpending: \"pending\",\n\trunning: \"running\",\n\tcompleted: \"completed\",\n\terror: \"error\",\n\tskipped: \"skipped\",\n\taborted: \"aborted\",\n} as const;\n\nexport const ToolRunningSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.running),\n\tpartial: Type.Optional(ToolRunningPartial),\n});\nexport const ToolCompletedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.completed),\n\tresult: ToolSuccessResult,\n});\nexport const ToolErrorSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.error),\n\tresult: ToolErrorResult,\n});\nexport const ToolSkippedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.skipped),\n\tresult: ToolErrorResult,\n});\nexport const ToolAbortedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.aborted),\n\tresult: ToolErrorResult,\n});\n\nexport const ToolCallPendingPartSchema = Type.Intersect([\n\tToolCallBaseSchema,\n\tType.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.pending),\n\t}),\n]);\nexport const ToolCallRunningPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolRunningSchema]));\nexport const ToolCallCompletedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));\nexport const ToolCallErrorPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolErrorSchema]));\nexport const ToolCallSkippedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));\nexport const ToolCallAbortedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));\nexport const ToolCallTerminalPartSchema = Type.Union([\n\tToolCallCompletedPartSchema,\n\tToolCallErrorPartSchema,\n\tToolCallSkippedPartSchema,\n\tToolCallAbortedPartSchema,\n]);\n\nexport const ToolCallInFlightSchema = Type.Object({\n\tcallID: Type.String(),\n\tname: Type.String(),\n\trawArgs: Type.Record(Type.String(), Type.Unknown()),\n\targs: Type.Optional(Type.Unknown()),\n});\nexport type ToolCallInFlight = Static<typeof ToolCallInFlightSchema>;\n\nexport const ToolCallSchema = Type.Union([\n\tToolCallPendingPartSchema,\n\tToolCallRunningPartSchema,\n\tToolCallTerminalPartSchema,\n]);\n\nexport type ToolCall = Static<typeof ToolCallSchema>;\nexport type ToolCallPendingPart = Static<typeof ToolCallPendingPartSchema>;\nexport type ToolCallRunningPart = Static<typeof ToolCallRunningPartSchema>;\nexport type ToolCallCompletedPart = Static<typeof ToolCallCompletedPartSchema>;\nexport type ToolCallErrorPart = Static<typeof ToolCallErrorPartSchema>;\nexport type ToolCallSkippedPart = Static<typeof ToolCallSkippedPartSchema>;\nexport type ToolCallAbortedPart = Static<typeof ToolCallAbortedPartSchema>;\nexport type ToolCallTerminalPart = Static<typeof ToolCallTerminalPartSchema>;\n\nexport const UsageSchema = Type.Object({\n\tinput: Type.Number(),\n\toutput: Type.Number(),\n\tcacheRead: Type.Number(),\n\tcacheWrite: Type.Number(),\n\t/** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */\n\tcacheWrite1h: Type.Optional(Type.Number()),\n\treasoning: Type.Optional(Type.Number()),\n\ttotalTokens: Type.Number(),\n\tcost: Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t\ttotal: Type.Number(),\n\t}),\n});\nexport type Usage = Static<typeof UsageSchema>;\n\nexport const StopReasonSchema = Type.Union([\n\tType.Literal(\"stop\"),\n\tType.Literal(\"length\"),\n\tType.Literal(\"toolUse\"),\n\tType.Literal(\"error\"),\n\tType.Literal(\"aborted\"),\n]);\nexport type StopReason = Static<typeof StopReasonSchema>;\n\nexport const UserMessageSchema = Type.Object({\n\tmessageId: Type.String(),\n\trole: Type.Literal(\"user\"),\n\ttime: Type.Object({\n\t\tcreated: Type.Number(),\n\t}),\n\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n});\nexport type UserMessage = Static<typeof UserMessageSchema>;\n\n/** Something aikit did on the caller's behalf while producing a message, such as a request retried in another shape. */\nexport const AssistantMessageDiagnosticSchema = Type.Object({\n\ttype: Type.String(),\n\ttimestamp: Type.Number(),\n\terror: Type.Optional(\n\t\tType.Object({\n\t\t\tname: Type.Optional(Type.String()),\n\t\t\tmessage: Type.String(),\n\t\t\tstack: Type.Optional(Type.String()),\n\t\t\tcode: Type.Optional(Type.Union([Type.String(), Type.Number()])),\n\t\t}),\n\t),\n\tdetails: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n});\nexport type AssistantMessageDiagnostic = Static<typeof AssistantMessageDiagnosticSchema>;\n\nexport const AssistantMessageSchema = Type.Object({\n\trole: Type.Literal(\"assistant\"),\n\tprotocol: Model.KnownProviderEnumSchema,\n\tprovider: Model.ProviderInfo,\n\tmodel: Type.String(),\n\t/** Thinking level the caller requested, before aikit fits it to the model. */\n\tthinkingLevel: Model.ThinkingLevel,\n\t/** Provider-native thinking value the request carried. Absent for budget-only or unmanaged reasoning. */\n\tproviderThinkingLevel: Type.Optional(Type.String()),\n\tusage: UsageSchema,\n\tstopReason: StopReasonSchema,\n\terrorMessage: Type.Optional(Type.String()),\n\t/**\n\t * Structured, provider-independent failure details for a failed request.\n\t * The schema is based on ai-sdk as the underlying provider wire protocol.\n\t * Depends on ai-sdk\n\t */\n\tfailure: Type.Optional(Failure.FailureSchema),\n\tdiagnostics: Type.Optional(Type.Array(AssistantMessageDiagnosticSchema)),\n\ttime: Type.Object({\n\t\tcreated: Type.Number(),\n\t\tcompleted: Type.Number(),\n\t}),\n\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema, ThinkingContentSchema, ToolCallSchema])),\n\tresponseId: Type.Optional(Type.String()), // Provider-specific response/message identifier when the upstream API exposes one\n\tresponseModel: Type.Optional(Type.String()), // Concrete routed model identifier when it differs from the requested model\n\tmessageId: Type.String(),\n});\nexport type AssistantMessage = Static<typeof AssistantMessageSchema>;\n\ntype UserMessageInit = Omit<UserMessage, \"messageId\"> & {\n\tmessageId?: string;\n};\n\ntype AssistantMessageInit = Omit<AssistantMessage, \"messageId\"> & {\n\tmessageId?: string;\n};\n\nexport function createMessageId(): string {\n\treturn uuidv7();\n}\n\nexport function createUserMessage(message: UserMessageInit): UserMessage {\n\tconst { messageId = createMessageId(), ...rest } = message;\n\treturn {\n\t\tmessageId,\n\t\t...rest,\n\t};\n}\n\nexport function createAssistantMessage(message: AssistantMessageInit): AssistantMessage {\n\tconst { messageId = createMessageId(), ...rest } = message;\n\treturn {\n\t\tmessageId,\n\t\t...rest,\n\t};\n}\n\nexport const GrammarVariantsSchema = Type.Partial(\n\tType.Object({\n\t\topenai_lark: Type.String(),\n\t\topenai_regex: Type.String(),\n\t}),\n);\nexport type GrammarVariants = Static<typeof GrammarVariantsSchema>;\n\nexport const ConstrainedSamplingSchema = Type.Union([\n\tType.Object({\n\t\ttype: Type.Literal(\"json_schema\"),\n\t\tstrict: Type.Union([Type.Literal(\"prefer\"), Type.Literal(\"require\")]),\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(\"grammar\"),\n\t\tvariants: GrammarVariantsSchema,\n\t}),\n]);\nexport type ConstrainedSampling = Static<typeof ConstrainedSamplingSchema>;\n\n/**\n * Generic tool definition with typed parameter schema.\n * Usage:\n *\n * const search = Message.defineTool({\n * name: \"search\",\n * description: \"Search documents\",\n * parameters: Type.Object({\n * query: Type.String(),\n * limit: Type.Optional(Type.Number()),\n * }),\n * });\n *\n * type SearchParams = Static<typeof search.parameters>;\n */\nexport const ToolSchema = Type.Object({\n\tname: Type.String(),\n\tdescription: Type.String(),\n\tparameters: Type.Unsafe<TSchema>({}),\n\tconstrainedSampling: Type.Optional(Type.Union([Type.Literal(false), ConstrainedSamplingSchema])),\n});\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n\t/** How the provider constrains generated tool-call arguments (strict JSON schema or grammar).\n\t * used by convert tool.\n\t * */\n\tconstrainedSampling?: false | ConstrainedSampling;\n}\nexport type ToolArguments<T extends Tool> = Static<T[\"parameters\"]>;\n\nexport function defineTool<TParameters extends TSchema>(tool: Tool<TParameters>): Tool<TParameters> {\n\treturn tool;\n}\n\nexport const ToolReferenceSchema = Type.Object({\n\tname: Type.String(),\n});\nexport type ToolReference = Static<typeof ToolReferenceSchema>;\n\n/**\n * A change to the system prompt and tool set at one point in the transcript.\n *\n * `Context.systemPrompt` and `Context.tools` hold the prompt and tools at the start of the\n * conversation; each system message changes them from its position on. Replaying them in\n * order yields the current prompt and tools. A redefinition is a removal plus an addition of\n * the same name.\n */\nexport const SystemMessageSchema = Type.Object({\n\tmessageId: Type.String(),\n\trole: Type.Literal(\"system\"),\n\ttime: Type.Object({\n\t\tcreated: Type.Number(),\n\t}),\n\t/** Instructions that apply from this point on, after the earlier ones. */\n\tcontent: Type.Optional(Type.String()),\n\t/**\n\t * Named prompt sections rendered after the content. A later message replaces a section by\n\t * name, and `null` removes it. Keep each section self-delimiting (a tag) so the model can\n\t * relate an update to the original, and avoid integer-like names, which JSON reorders.\n\t */\n\tsections: Type.Optional(Type.Record(Type.String(), Type.Union([Type.String(), Type.Null()]))),\n\t/** Complete definitions of tools that become available at this point. */\n\ttoolsAdded: Type.Optional(Type.Array(ToolSchema)),\n\t/** Tools that stop being available at this point. */\n\ttoolsRemoved: Type.Optional(Type.Array(ToolReferenceSchema)),\n\t/** Caller data kept with the message; never sent to a provider. */\n\tmetadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n});\nexport type SystemMessage = Static<typeof SystemMessageSchema>;\n\nexport const MessageSchema = Type.Union([SystemMessageSchema, UserMessageSchema, AssistantMessageSchema]);\nexport type Message = Static<typeof MessageSchema>;\n\ntype SystemMessageInit = Omit<SystemMessage, \"messageId\" | \"role\" | \"time\"> & {\n\tmessageId?: string;\n\ttime?: SystemMessage[\"time\"];\n};\n\nexport function createSystemMessage(message: SystemMessageInit): SystemMessage {\n\tconst { messageId = createMessageId(), time = { created: Date.now() }, ...rest } = message;\n\treturn { messageId, role: \"system\", time, ...rest };\n}\n\nexport const ContextSchema = Type.Object({\n\tsystemPrompt: Type.Optional(Type.String()),\n\tmessages: Type.Array(MessageSchema),\n\ttools: Type.Optional(Type.Array(ToolSchema)),\n\t/** Tools a later system message may add, for transports that must declare every tool up front. */\n\tdeferredTools: Type.Optional(Type.Array(ToolSchema)),\n});\nexport type Context = Static<typeof ContextSchema>;\n\nfunction isUnresolvedToolCall(toolCall: ToolCall): toolCall is ToolCallPendingPart | ToolCallRunningPart {\n\treturn toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;\n}\n\nfunction syntheticSkippedToolCall(toolCall: ToolCallPendingPart | ToolCallRunningPart): ToolCall {\n\tconst {\n\t\tstatus: _status,\n\t\tpartial: _partial,\n\t\t...base\n\t} = toolCall as (ToolCallPendingPart | ToolCallRunningPart) & {\n\t\tpartial?: unknown;\n\t};\n\n\treturn {\n\t\t...base,\n\t\tstatus: ToolStatusEnum.skipped,\n\t\tresult: {\n\t\t\tcontent: [{ type: \"text\", text: \"no result provided\" }],\n\t\t\tisError: true,\n\t\t},\n\t\ttime: {\n\t\t\t...toolCall.time,\n\t\t\tend: Math.max(toolCall.time.end, Date.now()),\n\t\t},\n\t};\n}\n\nconst USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\n\n// Consecutive images collapse into a single placeholder.\nexport function omitImages(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {\n\tconst result: TextContent[] = [];\n\tfor (const [index, block] of content.entries()) {\n\t\tif (block.type === \"text\") result.push(block);\n\t\telse if (content[index - 1]?.type !== \"image\") result.push({ type: \"text\", text: placeholder });\n\t}\n\treturn result;\n}\n\nfunction omitToolImages(toolCall: ToolCall): ToolCall {\n\tif (!(\"result\" in toolCall) || !toolCall.result.content.some((content) => content.type === \"image\")) return toolCall;\n\treturn {\n\t\t...toolCall,\n\t\tresult: { ...toolCall.result, content: omitImages(toolCall.result.content, TOOL_IMAGE_PLACEHOLDER) },\n\t} as ToolCall;\n}\n\nexport function transformMessages<TProtocol extends Model.KnownProviderEnum>(\n\tmessages: Message[],\n\tmodel: Model.TModel<TProtocol>,\n\tnormalizeToolCallId?: (id: string, model: Model.TModel<TProtocol>, source: AssistantMessage) => string,\n): Message[] {\n\tconst toolCallIDMap = new Map<string, string>();\n\tconst supportsImages = model.input.includes(\"image\");\n\n\tconst transformed: Message[] = [];\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"system\") {\n\t\t\ttransformed.push(msg);\n\t\t\tcontinue;\n\t\t}\n\t\tif (msg.role === \"user\") {\n\t\t\ttransformed.push(supportsImages ? msg : { ...msg, parts: omitImages(msg.parts, USER_IMAGE_PLACEHOLDER) });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tconst isSameModel =\n\t\t\tassistantMsg.provider.id === model.provider.id &&\n\t\t\tassistantMsg.protocol === model.protocol &&\n\t\t\tassistantMsg.model === model.id;\n\n\t\tconst transformedParts = assistantMsg.parts.flatMap((block) => {\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t// Signatures only verify on the model that made them, and readable thinking sent as\n\t\t\t\t// text makes the new model treat it as part of its visible reply.\n\t\t\t\tif (!isSameModel) return [];\n\t\t\t\t// Signed or redacted blocks replay even when empty (OpenAI encrypted reasoning).\n\t\t\t\tif (block.redacted || block.thinkingSignature) return block;\n\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\treturn block;\n\t\t\t}\n\n\t\t\tif (block.type === \"text\") {\n\t\t\t\tif (isSameModel) return block;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\ttext: block.text,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t}\n\n\t\t\t\tconst normalizedID = toolCallIDMap.get(block.callID);\n\t\t\t\tif (normalizedID && normalizedID !== block.callID) {\n\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: normalizedID };\n\t\t\t\t} else if (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\tconst nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);\n\t\t\t\t\tif (nextID !== toolCall.callID) {\n\t\t\t\t\t\ttoolCallIDMap.set(toolCall.callID, nextID);\n\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: nextID };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn normalizedToolCall;\n\t\t\t}\n\n\t\t\treturn block;\n\t\t});\n\t\tconst parts = transformedParts.map((block) => {\n\t\t\tif (block.type !== \"toolCall\") return block;\n\t\t\tconst toolCall = isUnresolvedToolCall(block) ? syntheticSkippedToolCall(block) : block;\n\t\t\treturn supportsImages ? toolCall : omitToolImages(toolCall);\n\t\t});\n\n\t\ttransformed.push({\n\t\t\t...assistantMsg,\n\t\t\tparts,\n\t\t});\n\t}\n\n\treturn transformed;\n}\n","import type {\n\tLanguageModelV3CallOptions,\n\tLanguageModelV3FunctionTool,\n\tLanguageModelV3ToolChoice,\n\tSharedV3Warning,\n} from \"@ai-sdk/provider\";\nimport type { TSchema } from \"typebox\";\nimport * as Message from \"../../message/message.ts\";\n\nexport type ResponsesTool =\n\t| {\n\t\t\ttype: \"function\";\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tparameters: Record<string, unknown>;\n\t\t\tstrict?: boolean | null;\n\t\t\tdefer_loading?: boolean;\n\t }\n\t| {\n\t\t\ttype: \"custom\";\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tformat: {\n\t\t\t\ttype: \"grammar\";\n\t\t\t\tsyntax: \"lark\" | \"regex\";\n\t\t\t\tdefinition: string;\n\t\t\t};\n\t\t\tdefer_loading?: boolean;\n\t };\n\nexport type ResponsesGrammarConstraint = {\n\ttype: \"grammar\";\n\tformat: \"lark\" | \"regex\";\n\tdefinition: string;\n\tinputProperty: string;\n};\n\nexport type GrammarInputBuffer = {\n\tinput: string;\n\tstarted: boolean;\n\tclosed: boolean;\n};\n\nexport function appendGrammarInputJsonDelta(\n\tbuffer: GrammarInputBuffer,\n\tinputProperty: string,\n\tnextInput: string,\n\tclose: boolean,\n): string | undefined {\n\tif (buffer.closed) {\n\t\tif (close && nextInput === buffer.input) return undefined;\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed after it was closed`);\n\t}\n\tif (!nextInput.startsWith(buffer.input)) {\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed non-monotonically`);\n\t}\n\n\tconst inputDelta = nextInput.slice(buffer.input.length);\n\tif (!close && inputDelta.length === 0) return undefined;\n\n\tlet delta = \"\";\n\tif (!buffer.started) {\n\t\tdelta += `{${JSON.stringify(inputProperty)}:\"`;\n\t\tbuffer.started = true;\n\t}\n\tdelta += JSON.stringify(inputDelta).slice(1, -1);\n\tbuffer.input = nextInput;\n\n\tif (close) {\n\t\tdelta += '\"}';\n\t\tbuffer.closed = true;\n\t}\n\treturn delta;\n}\n\ntype JsonSchemaObject = {\n\ttype?: unknown;\n\tproperties?: Record<string, { type?: unknown } | undefined>;\n\trequired?: unknown;\n};\n\nfunction inferGrammarInputProperty(parameters: TSchema): string {\n\tconst schema = parameters as JsonSchemaObject;\n\tif (schema.type !== \"object\") throw new Error(\"grammar constrained sampling requires an object parameter schema\");\n\tif (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== \"string\") {\n\t\tthrow new Error(\"grammar constrained sampling requires exactly one required string property\");\n\t}\n\tconst inputProperty = schema.required[0];\n\tif (!schema.properties?.[inputProperty]) {\n\t\tthrow new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);\n\t}\n\tif (schema.properties[inputProperty]?.type !== \"string\") {\n\t\tthrow new Error(`grammar constrained sampling property ${inputProperty} must have type string`);\n\t}\n\treturn inputProperty;\n}\n\nexport function resolveToolGrammar(\n\ttool: Message.Tool,\n\tcompat?: { supportsOpenAIGrammarTools?: boolean },\n): ResponsesGrammarConstraint | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config || config.type !== \"grammar\") return undefined;\n\tif (!(compat?.supportsOpenAIGrammarTools ?? false)) return undefined;\n\n\tconst lark = config.variants.openai_lark;\n\tconst regex = config.variants.openai_regex;\n\tconst hasLark = typeof lark === \"string\" && lark.trim().length > 0;\n\tconst hasRegex = typeof regex === \"string\" && regex.trim().length > 0;\n\tif (!hasLark && !hasRegex) {\n\t\tthrow new Error(\n\t\t\t`Tool \"${tool.name}\" cannot use grammar constrained sampling: no supported grammar variant was provided.`,\n\t\t);\n\t}\n\ttry {\n\t\treturn {\n\t\t\ttype: \"grammar\",\n\t\t\tformat: hasLark ? \"lark\" : \"regex\",\n\t\t\tdefinition: hasLark ? lark! : regex!,\n\t\t\tinputProperty: inferGrammarInputProperty(tool.parameters),\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`tool \"${tool.name}\" cannot use grammar constrained sampling: ${message}.`);\n\t}\n}\n\nexport type ResponsesToolChoice = \"auto\" | \"none\" | \"required\";\n\n/**\n * Tool changes declared at a system message's position, carried in its\n * `providerOptions[<provider>].toolChange`. `changes` declares tools in\n * `additional_tools` items; `additions` declares them as a synthetic tool search.\n */\nexport type ResponsesToolChange = {\n\tmode: \"changes\" | \"additions\";\n\ttools: LanguageModelV3FunctionTool[];\n\tremoved: string[];\n};\n\n/** A function tool carries its grammar in `providerOptions[<provider>].grammar`. */\nfunction toolGrammar(tool: LanguageModelV3FunctionTool, provider: string): ResponsesGrammarConstraint | undefined {\n\tconst metadata = tool.providerOptions?.[provider] as Record<string, unknown> | undefined;\n\tconst grammar = metadata?.grammar as ResponsesGrammarConstraint | undefined;\n\treturn grammar?.type === \"grammar\" ? grammar : undefined;\n}\n\nexport function toResponsesTool(tool: LanguageModelV3FunctionTool, provider: string): ResponsesTool {\n\tconst grammar = toolGrammar(tool, provider);\n\treturn grammar\n\t\t? {\n\t\t\t\ttype: \"custom\",\n\t\t\t\tname: tool.name,\n\t\t\t\t...(tool.description !== undefined && { description: tool.description }),\n\t\t\t\tformat: {\n\t\t\t\t\ttype: \"grammar\",\n\t\t\t\t\tsyntax: grammar.format,\n\t\t\t\t\tdefinition: grammar.definition,\n\t\t\t\t},\n\t\t\t}\n\t\t: {\n\t\t\t\ttype: \"function\",\n\t\t\t\tname: tool.name,\n\t\t\t\t...(tool.description !== undefined && { description: tool.description }),\n\t\t\t\tparameters: tool.inputSchema as Record<string, unknown>,\n\t\t\t\tstrict: tool.strict ?? null,\n\t\t\t};\n}\n\nexport function prepareResponsesTools({\n\tprovider,\n\ttools,\n\ttoolChoice,\n\tinPlaceToolNames,\n}: {\n\tprovider: string;\n\ttools: LanguageModelV3CallOptions[\"tools\"];\n\ttoolChoice: LanguageModelV3ToolChoice | undefined;\n\t/** Tools declared in place in the input; they stay out of the top-level list. */\n\tinPlaceToolNames?: ReadonlySet<string>;\n}): {\n\tresponsesTools: ResponsesTool[] | undefined;\n\tgrammarToolInputProperties: ReadonlyMap<string, string>;\n\ttoolChoiceValue: ResponsesToolChoice | undefined;\n\twarnings: SharedV3Warning[];\n} {\n\tconst warnings: SharedV3Warning[] = [];\n\tconst grammarToolInputProperties = new Map<string, string>();\n\n\tif (!tools || tools.length === 0) {\n\t\treturn {\n\t\t\tresponsesTools: undefined,\n\t\t\tgrammarToolInputProperties,\n\t\t\ttoolChoiceValue: undefined,\n\t\t\twarnings,\n\t\t};\n\t}\n\n\tconst responsesTools: ResponsesTool[] = [];\n\tfor (const tool of tools) {\n\t\tif (tool.type !== \"function\") {\n\t\t\twarnings.push({\n\t\t\t\ttype: \"unsupported\",\n\t\t\t\tfeature: `tool type ${tool.type}`,\n\t\t\t\tdetails: `Only function tools are supported; ignoring ${tool.name}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst grammar = toolGrammar(tool, provider);\n\t\tif (grammar) grammarToolInputProperties.set(tool.name, grammar.inputProperty);\n\t\tif (!inPlaceToolNames?.has(tool.name)) responsesTools.push(toResponsesTool(tool, provider));\n\t}\n\n\tlet toolChoiceValue: ResponsesToolChoice | undefined;\n\tswitch (toolChoice?.type) {\n\t\tcase undefined:\n\t\t\tbreak;\n\t\tcase \"auto\":\n\t\tcase \"none\":\n\t\tcase \"required\":\n\t\t\ttoolChoiceValue = toolChoice.type;\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\twarnings.push({\n\t\t\t\ttype: \"unsupported\",\n\t\t\t\tfeature: \"toolChoice tool name\",\n\t\t\t\tdetails: \"Forcing a specific tool is not supported; using 'required' instead.\",\n\t\t\t});\n\t\t\ttoolChoiceValue = \"required\";\n\t\t\tbreak;\n\t}\n\n\treturn {\n\t\tresponsesTools: responsesTools.length > 0 ? responsesTools : undefined,\n\t\tgrammarToolInputProperties,\n\t\ttoolChoiceValue,\n\t\twarnings,\n\t};\n}\n","/** Fast deterministic hash for shortening provider wire identifiers. */\nexport function shortHash(value: string): string {\n\tlet high = 0xdeadbeef;\n\tlet low = 0x41c6ce57;\n\tfor (let index = 0; index < value.length; index++) {\n\t\tconst character = value.charCodeAt(index);\n\t\thigh = Math.imul(high ^ character, 2654435761);\n\t\tlow = Math.imul(low ^ character, 1597334677);\n\t}\n\thigh = Math.imul(high ^ (high >>> 16), 2246822507) ^ Math.imul(low ^ (low >>> 13), 3266489909);\n\tlow = Math.imul(low ^ (low >>> 16), 2246822507) ^ Math.imul(high ^ (high >>> 13), 3266489909);\n\treturn (low >>> 0).toString(36) + (high >>> 0).toString(36);\n}\n","import { APICallError } from \"@ai-sdk/provider\";\n\ntype ResponsesError = {\n\tcode?: string;\n\ttype?: string;\n\tmessage?: string;\n\tplan_type?: string;\n\tresets_at?: number;\n};\n\ntype ResponsesErrorPayload = {\n\terror?: ResponsesError;\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n\nconst asString = (value: unknown): string | undefined =>\n\ttypeof value === \"string\" && value.trim() ? value.trim() : undefined;\n\nfunction normalizeErrorPayload(value: unknown): ResponsesErrorPayload {\n\tconst record = asRecord(value);\n\tconst nested = asRecord(record?.error);\n\tconst source = nested ?? record ?? {};\n\tconst code = asString(source.code);\n\tconst type = asString(source.type);\n\tconst message = asString(source.message);\n\tconst planType = asString(source.plan_type);\n\tconst error: ResponsesError = {\n\t\t...(code !== undefined && { code }),\n\t\t...(type !== undefined && { type }),\n\t\t...(message !== undefined && { message }),\n\t\t...(planType !== undefined && { plan_type: planType }),\n\t\t...(typeof source.resets_at === \"number\" && { resets_at: source.resets_at }),\n\t};\n\treturn { error };\n}\n\nfunction parseErrorPayload(body: string): ResponsesErrorPayload | undefined {\n\ttry {\n\t\treturn normalizeErrorPayload(JSON.parse(body) as unknown);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction errorIdentifiers(error: ResponsesError | undefined): string {\n\treturn `${error?.code ?? \"\"} ${error?.type ?? \"\"}`.toLowerCase();\n}\n\nfunction hasIdentifier(error: ResponsesError | undefined, identifiers: readonly string[]): boolean {\n\tconst value = errorIdentifiers(error);\n\treturn identifiers.some((identifier) => value.includes(identifier));\n}\n\nfunction isUsageLimitError(error: ResponsesError | undefined): boolean {\n\treturn hasIdentifier(error, [\"usage_limit_reached\", \"gousagelimiterror\", \"freeusagelimiterror\"]);\n}\n\nfunction isTerminalRateLimitError(body: string, payload = parseErrorPayload(body)): boolean {\n\treturn (\n\t\tisUsageLimitError(payload?.error) ||\n\t\thasIdentifier(payload?.error, [\"usage_not_included\", \"insufficient_quota\"]) ||\n\t\t/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|out of budget|quota exceeded|billing/i.test(\n\t\t\tbody,\n\t\t)\n\t);\n}\n\nfunction streamErrorStatus(error: ResponsesError | undefined): number {\n\tif (isUsageLimitError(error) || hasIdentifier(error, [\"usage_not_included\", \"insufficient_quota\", \"rate_limit\"])) {\n\t\treturn 429;\n\t}\n\tif (hasIdentifier(error, [\"server_is_overloaded\", \"slow_down\"])) return 503;\n\tif (\n\t\thasIdentifier(error, [\n\t\t\t\"context_length_exceeded\",\n\t\t\t\"invalid_prompt\",\n\t\t\t\"bio_policy\",\n\t\t\t\"cyber_policy\",\n\t\t\t\"misalignment_policy_violation\",\n\t\t])\n\t) {\n\t\treturn 400;\n\t}\n\treturn 500;\n}\n\nfunction retryAfterHeader(message: string | undefined): Record<string, string> {\n\tconst match = message?.match(/try again in\\s*(\\d+(?:\\.\\d+)?)\\s*(s|ms|seconds?)/i);\n\tif (!match) return {};\n\tconst value = Number(match[1]);\n\tif (!Number.isFinite(value)) return {};\n\treturn { \"retry-after\": String(match[2]?.toLowerCase() === \"ms\" ? value / 1_000 : value) };\n}\n\n/**\n * Turn a Responses error payload into a human-friendly message. Only terminal\n * ChatGPT plan exhaustion is rewritten; transient 429s retain backend detail.\n * `label` names the backend, e.g. \"OpenAI Codex\".\n */\nexport function responsesErrorMessage(label: string, body: string, statusText?: string): string {\n\tlet message = body || statusText || `${label} request failed`;\n\tconst payload = parseErrorPayload(body);\n\tconst error = payload?.error;\n\n\tif (isUsageLimitError(error)) {\n\t\tconst plan = error?.plan_type ? ` (${error.plan_type.toLowerCase()} plan)` : \"\";\n\t\tconst minutes = error?.resets_at\n\t\t\t? Math.max(0, Math.round((error.resets_at * 1000 - Date.now()) / 60000))\n\t\t\t: undefined;\n\t\tconst when = minutes === undefined ? \"\" : ` Try again in ~${minutes} min.`;\n\t\treturn `You have hit your ChatGPT usage limit${plan}.${when}`.trim();\n\t}\n\n\tif (error?.message) message = error.message;\n\treturn message;\n}\n\nexport async function createResponsesAPICallError(args: {\n\tlabel: string;\n\tresponse: Response;\n\turl: string;\n\trequestBodyValues: unknown;\n}): Promise<APICallError> {\n\tconst { response, url, requestBodyValues } = args;\n\tconst responseBody = await response.text().catch(() => \"\");\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\tconst data = parseErrorPayload(responseBody);\n\n\treturn new APICallError({\n\t\tmessage: responsesErrorMessage(args.label, responseBody, response.statusText),\n\t\turl,\n\t\trequestBodyValues,\n\t\tstatusCode: response.status,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\t...(data !== undefined && { data }),\n\t\tisRetryable:\n\t\t\tresponse.status === 408 ||\n\t\t\tresponse.status === 409 ||\n\t\t\t(response.status === 429 && !isTerminalRateLimitError(responseBody, data)) ||\n\t\t\tresponse.status >= 500,\n\t});\n}\n\n/** Map an error embedded in a successful SSE response to the same API error shape as HTTP failures. */\nexport function createResponsesStreamError(args: {\n\tlabel: string;\n\terror: unknown;\n\turl: string;\n\trequestBodyValues: unknown;\n\tresponseHeaders?: Record<string, string>;\n}): APICallError {\n\tconst { error: value, url, requestBodyValues } = args;\n\tconst data = normalizeErrorPayload(value);\n\tconst error = data.error;\n\tconst statusCode = streamErrorStatus(error);\n\tconst responseBody = JSON.stringify(data);\n\tconst responseHeaders = {\n\t\t...args.responseHeaders,\n\t\t...retryAfterHeader(error?.message),\n\t};\n\n\treturn new APICallError({\n\t\tmessage: responsesErrorMessage(args.label, responseBody),\n\t\turl,\n\t\trequestBodyValues,\n\t\tstatusCode,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\tdata,\n\t\tisRetryable:\n\t\t\tstatusCode >= 500 || (hasIdentifier(error, [\"rate_limit\"]) && !isTerminalRateLimitError(responseBody, data)),\n\t});\n}\n\n/** A transport failure used when an SSE response ends without a terminal Responses event. */\nexport function createResponsesPrematureCloseError(args: {\n\tlabel: string;\n\turl: string;\n\trequestBodyValues: unknown;\n\tresponseHeaders?: Record<string, string>;\n}): APICallError {\n\treturn new APICallError({\n\t\tmessage: `${args.label} stream closed before response.completed`,\n\t\turl: args.url,\n\t\trequestBodyValues: args.requestBodyValues,\n\t\t...(args.responseHeaders !== undefined && { responseHeaders: args.responseHeaders }),\n\t\tisRetryable: true,\n\t});\n}\n\n/**\n * A fetch that rejects never produced a response, but its body was still sent. Wrap\n * it the way AI SDK providers do, so it reads as a retryable transport failure that\n * carries the request. Aborts pass through untouched.\n */\nexport function responsesFetchError(error: unknown, url: string, requestBodyValues: unknown): unknown {\n\tif (error instanceof Error && (error.name === \"AbortError\" || error.name === \"TimeoutError\")) return error;\n\tconst cause = error instanceof Error && error.cause instanceof Error ? error.cause : error;\n\treturn new APICallError({\n\t\tmessage: `Cannot connect to API: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\tcause: error,\n\t\turl,\n\t\trequestBodyValues,\n\t\tisRetryable: true,\n\t});\n}\n","import type {\n\tLanguageModelV3FilePart,\n\tLanguageModelV3Prompt,\n\tLanguageModelV3ToolResultOutput,\n\tLanguageModelV4FilePart,\n\tLanguageModelV4Prompt,\n\tLanguageModelV4ToolResultOutput,\n} from \"@ai-sdk/provider\";\nimport { shortHash } from \"../../utils/hash.ts\";\nimport { toResponsesTool, type ResponsesTool, type ResponsesToolChange } from \"./tools.ts\";\n\n/**\n * OpenAI Responses API input item types this transport sends.\n */\nexport type ResponsesInputItem =\n\t| {\n\t\t\trole: \"user\";\n\t\t\tcontent: Array<\n\t\t\t\t{ type: \"input_text\"; text: string } | { type: \"input_image\"; image_url: string; detail?: string }\n\t\t\t>;\n\t }\n\t| {\n\t\t\ttype: \"message\";\n\t\t\trole: \"assistant\";\n\t\t\tid: string;\n\t\t\tcontent: Array<{ type: \"output_text\"; text: string; annotations: unknown[] }>;\n\t\t\tstatus: \"completed\";\n\t }\n\t| {\n\t\t\ttype: \"function_call\";\n\t\t\tid?: string;\n\t\t\tcall_id: string;\n\t\t\tname: string;\n\t\t\targuments: string;\n\t\t\tnamespace?: string;\n\t }\n\t| {\n\t\t\ttype: \"custom_tool_call\";\n\t\t\tid?: string;\n\t\t\tcall_id: string;\n\t\t\tname: string;\n\t\t\tinput: string;\n\t\t\tnamespace?: string;\n\t }\n\t| {\n\t\t\ttype: \"reasoning\";\n\t\t\tid: string;\n\t\t\t[key: string]: unknown;\n\t }\n\t| {\n\t\t\ttype: \"function_call_output\";\n\t\t\tcall_id: string;\n\t\t\toutput:\n\t\t\t\t| string\n\t\t\t\t| Array<{ type: \"input_text\"; text: string } | { type: \"input_image\"; image_url: string; detail: \"auto\" }>;\n\t }\n\t| {\n\t\t\ttype: \"custom_tool_call_output\";\n\t\t\tcall_id: string;\n\t\t\toutput: string;\n\t }\n\t| {\n\t\t\trole: \"developer\";\n\t\t\tcontent: string;\n\t }\n\t| {\n\t\t\ttype: \"additional_tools\";\n\t\t\trole: \"developer\";\n\t\t\ttools: ResponsesTool[];\n\t }\n\t| {\n\t\t\ttype: \"tool_search_call\";\n\t\t\tcall_id: string;\n\t\t\texecution: \"client\";\n\t\t\tstatus: \"completed\";\n\t\t\targuments: { query: string; limit: number };\n\t }\n\t| {\n\t\t\ttype: \"tool_search_output\";\n\t\t\tcall_id: string;\n\t\t\texecution: \"client\";\n\t\t\tstatus: \"completed\";\n\t\t\ttools: ResponsesTool[];\n\t };\n\nexport type ResponsesPrompt = {\n\t/** The system prompt, when it travels in the `instructions` field. */\n\tinstructions?: string;\n\tinput: ResponsesInputItem[];\n};\n\nconst DEFAULT_INSTRUCTIONS = \"You are a helpful assistant.\";\n\nexport type ResponsesPromptOptions = {\n\t/** The providerOptions key this transport reads, e.g. `openai-codex`. */\n\tprovider: string;\n\t/**\n\t * Where the leading system prompt goes: the `instructions` field (the Codex backend\n\t * requires one), or a developer message in place.\n\t */\n\tsystemPrompt: \"instructions\" | \"developer\";\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tsupportsImages?: boolean;\n};\n\n// Tool call ids round-trip through the AI SDK as `call_id|item_id` because the\n// Responses API needs both halves: `call_id` to pair function_call_output and\n// `id` for the function_call item itself.\nexport function splitToolCallId(toolCallId: string): { callId: string; itemId: string } {\n\tconst separator = toolCallId.indexOf(\"|\");\n\tif (separator === -1) return { callId: toolCallId, itemId: toolCallId };\n\treturn { callId: toolCallId.slice(0, separator), itemId: toolCallId.slice(separator + 1) };\n}\n\nexport function joinToolCallId(callId: string, itemId: string): string {\n\treturn `${callId}|${itemId}`;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) {\n\t\tbinary += String.fromCharCode(byte);\n\t}\n\treturn btoa(binary);\n}\n\nfunction imageUrlFromFilePart(part: LanguageModelV3FilePart | LanguageModelV4FilePart): string | undefined {\n\tconst data = part.data;\n\tif (data instanceof URL) return data.toString();\n\tif (typeof data === \"string\") {\n\t\tif (data.startsWith(\"data:\") || data.startsWith(\"http://\") || data.startsWith(\"https://\")) return data;\n\t\treturn `data:${part.mediaType};base64,${data}`;\n\t}\n\tif (data instanceof Uint8Array) {\n\t\treturn `data:${part.mediaType};base64,${uint8ArrayToBase64(data)}`;\n\t}\n\tif (\"type\" in data) {\n\t\tif (data.type === \"url\") return data.url.toString();\n\t\tif (data.type === \"data\") {\n\t\t\treturn typeof data.data === \"string\"\n\t\t\t\t? `data:${part.mediaType};base64,${data.data}`\n\t\t\t\t: `data:${part.mediaType};base64,${uint8ArrayToBase64(data.data)}`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction toolResultOutput(\n\toutput: LanguageModelV3ToolResultOutput | LanguageModelV4ToolResultOutput,\n\tsupportsImages: boolean,\n): Extract<ResponsesInputItem, { type: \"function_call_output\" }>[\"output\"] {\n\tswitch (output.type) {\n\t\tcase \"text\":\n\t\tcase \"error-text\":\n\t\t\treturn output.value || \"(no tool output)\";\n\t\tcase \"json\":\n\t\tcase \"error-json\":\n\t\t\treturn JSON.stringify(output.value);\n\t\tcase \"execution-denied\":\n\t\t\treturn output.reason ?? \"Tool execution denied\";\n\t\tcase \"content\": {\n\t\t\tconst text = output.value\n\t\t\t\t.filter((part): part is Extract<typeof part, { type: \"text\" }> => part.type === \"text\")\n\t\t\t\t.map((part) => part.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst images: Array<{ type: \"input_image\"; image_url: string; detail: \"auto\" }> = [];\n\t\t\tif (supportsImages) {\n\t\t\t\tfor (const part of output.value) {\n\t\t\t\t\tif (part.type === \"file-data\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\timages.push({\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\timage_url: `data:${part.mediaType};base64,${part.data}`,\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (part.type === \"file-url\") {\n\t\t\t\t\t\timages.push({ type: \"input_image\", image_url: part.url, detail: \"auto\" });\n\t\t\t\t\t} else if (part.type === \"file\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\tconst data = part.data;\n\t\t\t\t\t\tif (data.type === \"url\") {\n\t\t\t\t\t\t\timages.push({ type: \"input_image\", image_url: data.url.toString(), detail: \"auto\" });\n\t\t\t\t\t\t} else if (data.type === \"data\") {\n\t\t\t\t\t\t\tconst encoded = typeof data.data === \"string\" ? data.data : uint8ArrayToBase64(data.data);\n\t\t\t\t\t\t\timages.push({\n\t\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\t\timage_url: `data:${part.mediaType};base64,${encoded}`,\n\t\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (images.length === 0)\n\t\t\t\treturn text || (output.value.length > 0 ? \"(see attached image)\" : \"(no tool output)\");\n\t\t\treturn [...(text ? [{ type: \"input_text\" as const, text }] : []), ...images];\n\t\t}\n\t\tdefault:\n\t\t\treturn JSON.stringify(output);\n\t}\n}\n\nfunction customToolInput(input: unknown, toolName: string, inputProperty: string): string {\n\tif (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n\t\tthrow new Error(`custom tool \"${toolName}\" requires object input with string property \"${inputProperty}\".`);\n\t}\n\tconst value = (input as Record<string, unknown>)[inputProperty];\n\tif (typeof value !== \"string\") {\n\t\tthrow new Error(`custom tool \"${toolName}\" requires string input property \"${inputProperty}\".`);\n\t}\n\treturn value;\n}\n\nfunction customToolOutput(\n\toutput: LanguageModelV3ToolResultOutput | LanguageModelV4ToolResultOutput,\n\tsupportsImages: boolean,\n): string {\n\tconst value = toolResultOutput(output, supportsImages);\n\treturn typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\nfunction providerMetadata(\n\tproviderOptions: Record<string, unknown> | undefined,\n\tprovider: string,\n): Record<string, unknown> | undefined {\n\tconst metadata = providerOptions?.[provider];\n\treturn typeof metadata === \"object\" && metadata !== null && !Array.isArray(metadata)\n\t\t? (metadata as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction toolChange(\n\tproviderOptions: Record<string, unknown> | undefined,\n\tprovider: string,\n): ResponsesToolChange | undefined {\n\treturn providerMetadata(providerOptions, provider)?.toolChange as ResponsesToolChange | undefined;\n}\n\nfunction reasoningItem(\n\tproviderOptions: Record<string, unknown> | undefined,\n\tprovider: string,\n): Extract<ResponsesInputItem, { type: \"reasoning\" }> | undefined {\n\tconst value = providerMetadata(providerOptions, provider)?.reasoningItem;\n\tif (typeof value !== \"string\") return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n\t\tconst item = parsed as Record<string, unknown>;\n\t\treturn item.type === \"reasoning\" && typeof item.id === \"string\"\n\t\t\t? (item as Extract<ResponsesInputItem, { type: \"reasoning\" }>)\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Names of every tool declared in place by a system message's tool change. */\nexport function collectInPlaceToolNames(\n\tprompt: LanguageModelV3Prompt | LanguageModelV4Prompt,\n\tprovider: string,\n): Set<string> {\n\tconst names = new Set<string>();\n\tfor (const message of prompt) {\n\t\tif (message.role !== \"system\") continue;\n\t\tfor (const tool of toolChange(message.providerOptions, provider)?.tools ?? []) names.add(tool.name);\n\t}\n\treturn names;\n}\n\n/*\n * `additional_tools` items accumulate: a later item adds tools and replaces same-name\n * definitions from earlier ones, but cannot remove any. Without this notice, models read the\n * latest item as the complete tool set once a removal was announced, and restating the tools\n * that are still unavailable keeps smaller models from calling them after later loads.\n */\nfunction incrementalToolsNotice(unavailable: ReadonlySet<string>): string {\n\tconst notice =\n\t\t\"This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.\";\n\treturn unavailable.size > 0 ? `${notice}\\nStill unavailable: ${[...unavailable].join(\", \")}.` : notice;\n}\n\nfunction toolRemovalNotice(names: readonly string[]): string {\n\treturn `The following tools are no longer available. Do not call them:\\n${names.map((name) => `- ${name}`).join(\"\\n\")}`;\n}\n\n/**\n * Convert an AI SDK V3 prompt into the Responses request shape. The leading system\n * message goes where `options.systemPrompt` says, later ones (prompt updates and tool\n * changes) go in place, and everything else maps to `input` items.\n */\nexport function convertToResponsesPrompt(\n\tprompt: LanguageModelV3Prompt | LanguageModelV4Prompt,\n\toptions: ResponsesPromptOptions,\n): ResponsesPrompt {\n\tconst { provider } = options;\n\tlet instructions: string | undefined;\n\tconst input: ResponsesInputItem[] = [];\n\tlet syntheticMessageCounter = 0;\n\tlet toolChangeCounter = 0;\n\tlet declaredAdditionalTools = false;\n\t/** Tools announced as removed and not declared again since. */\n\tconst unavailableTools = new Set<string>();\n\n\t/** Declares the change's tools; returns the removal notice, which goes with the message's text. */\n\tconst appendToolChange = (change: ResponsesToolChange): string | undefined => {\n\t\tconst seed = toolChangeCounter++;\n\t\tconst tools = change.tools.map((tool) => toResponsesTool(tool, provider));\n\t\tfor (const tool of tools) unavailableTools.delete(tool.name);\n\t\tif (tools.length > 0 && change.mode === \"changes\") {\n\t\t\tif (declaredAdditionalTools) {\n\t\t\t\tinput.push({ role: \"developer\", content: incrementalToolsNotice(unavailableTools) });\n\t\t\t}\n\t\t\tdeclaredAdditionalTools = true;\n\t\t\tinput.push({ type: \"additional_tools\", role: \"developer\", tools });\n\t\t} else if (tools.length > 0) {\n\t\t\tconst names = tools.map((tool) => tool.name);\n\t\t\tconst callId = `cdwrk_aikit_tool_${shortHash(`${seed}:${names.join(\",\")}`)}`;\n\t\t\tinput.push({\n\t\t\t\ttype: \"tool_search_call\",\n\t\t\t\tcall_id: callId,\n\t\t\t\texecution: \"client\",\n\t\t\t\tstatus: \"completed\",\n\t\t\t\targuments: { query: names.join(\" \"), limit: names.length },\n\t\t\t});\n\t\t\tinput.push({\n\t\t\t\ttype: \"tool_search_output\",\n\t\t\t\tcall_id: callId,\n\t\t\t\texecution: \"client\",\n\t\t\t\tstatus: \"completed\",\n\t\t\t\ttools: tools.map((tool) => ({ ...tool, defer_loading: true })),\n\t\t\t});\n\t\t}\n\t\t// A redefinition is a removal plus an addition of the same name; only true removals are announced.\n\t\tconst added = new Set(tools.map((tool) => tool.name));\n\t\tconst removed = change.removed.filter((name) => !added.has(name));\n\t\tif (removed.length === 0) return;\n\t\t// Recorded after this change's additions, whose notice precedes this removal notice.\n\t\tfor (const name of removed) unavailableTools.add(name);\n\t\treturn toolRemovalNotice(removed);\n\t};\n\n\tfor (const message of prompt) {\n\t\tswitch (message.role) {\n\t\t\tcase \"system\": {\n\t\t\t\tconst change = toolChange(message.providerOptions, provider);\n\t\t\t\t// The first plain system message is the leading prompt; every later one is an update in place.\n\t\t\t\tif (!change && options.systemPrompt === \"instructions\" && instructions === undefined) {\n\t\t\t\t\tinstructions = message.content;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst removal = change ? appendToolChange(change) : undefined;\n\t\t\t\tconst text = [message.content, removal ?? \"\"].filter((part) => part.length > 0).join(\"\\n\\n\");\n\t\t\t\tif (text.length > 0) input.push({ role: \"developer\", content: text });\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"user\": {\n\t\t\t\tconst content: Extract<ResponsesInputItem, { role: \"user\" }>[\"content\"] = [];\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type === \"text\") {\n\t\t\t\t\t\tcontent.push({ type: \"input_text\", text: part.text });\n\t\t\t\t\t} else if (part.type === \"file\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\tconst imageUrl = imageUrlFromFilePart(part);\n\t\t\t\t\t\tif (imageUrl) content.push({ type: \"input_image\", image_url: imageUrl, detail: \"auto\" });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (content.length > 0) {\n\t\t\t\t\tinput.push({ role: \"user\", content });\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"assistant\": {\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type === \"reasoning\") {\n\t\t\t\t\t\tconst item = reasoningItem(part.providerOptions, provider);\n\t\t\t\t\t\tif (item) input.push(item);\n\t\t\t\t\t} else if (part.type === \"text\") {\n\t\t\t\t\t\tsyntheticMessageCounter++;\n\t\t\t\t\t\tconst messageId = providerMetadata(part.providerOptions, provider)?.messageId;\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\tid:\n\t\t\t\t\t\t\t\ttypeof messageId === \"string\" && messageId.length <= 64\n\t\t\t\t\t\t\t\t\t? messageId\n\t\t\t\t\t\t\t\t\t: `msg_cdwrk_aikit_${syntheticMessageCounter}`,\n\t\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: part.text, annotations: [] }],\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (part.type === \"tool-call\") {\n\t\t\t\t\t\tconst { callId, itemId } = splitToolCallId(part.toolCallId);\n\t\t\t\t\t\tconst metadata = providerMetadata(part.providerOptions, provider);\n\t\t\t\t\t\tconst namespace = metadata?.namespace;\n\t\t\t\t\t\tconst inputProperty = options.grammarToolInputProperties?.get(part.toolName);\n\t\t\t\t\t\tif (inputProperty) {\n\t\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\t\t...(metadata?.omitItemId === true || !itemId.startsWith(\"ctc_\") ? {} : { id: itemId }),\n\t\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\t\tname: part.toolName,\n\t\t\t\t\t\t\t\tinput: customToolInput(part.input, part.toolName, inputProperty),\n\t\t\t\t\t\t\t\t...(typeof namespace === \"string\" ? { namespace } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\t\t\t...(metadata?.omitItemId === true || !itemId.startsWith(\"fc_\") ? {} : { id: itemId }),\n\t\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\t\tname: part.toolName,\n\t\t\t\t\t\t\t\targuments: typeof part.input === \"string\" ? part.input : JSON.stringify(part.input ?? {}),\n\t\t\t\t\t\t\t\t...(typeof namespace === \"string\" ? { namespace } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool\": {\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type !== \"tool-result\") continue;\n\t\t\t\t\tconst { callId } = splitToolCallId(part.toolCallId);\n\t\t\t\t\tif (options.grammarToolInputProperties?.has(part.toolName)) {\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\toutput: customToolOutput(part.output, options.supportsImages ?? true),\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"function_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\toutput: toolResultOutput(part.output, options.supportsImages ?? true),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (options.systemPrompt === \"developer\") return { input };\n\treturn { instructions: instructions || DEFAULT_INSTRUCTIONS, input };\n}\n","import { EventSourceParserStream, type EventSourceMessage } from \"eventsource-parser/stream\";\n\n/** Parse standards-compliant event streams from a Responses endpoint. */\nexport function parseResponsesSSEStream(body: ReadableStream<Uint8Array>): ReadableStream<Record<string, unknown>> {\n\tconst decoder = new TextDecoder();\n\treturn body\n\t\t.pipeThrough(\n\t\t\tnew TransformStream<Uint8Array, string>({\n\t\t\t\ttransform(chunk, controller) {\n\t\t\t\t\tconst text = decoder.decode(chunk, { stream: true });\n\t\t\t\t\tif (text) controller.enqueue(text);\n\t\t\t\t},\n\t\t\t\tflush(controller) {\n\t\t\t\t\tconst text = decoder.decode();\n\t\t\t\t\tif (text) controller.enqueue(text);\n\t\t\t\t},\n\t\t\t}),\n\t\t)\n\t\t.pipeThrough(new EventSourceParserStream({ onError: \"terminate\" }))\n\t\t.pipeThrough(\n\t\t\tnew TransformStream<EventSourceMessage, Record<string, unknown>>({\n\t\t\t\ttransform(event, controller) {\n\t\t\t\t\tconst data = event.data.trim();\n\t\t\t\t\tif (!data || data === \"[DONE]\") return;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed: unknown = JSON.parse(data);\n\t\t\t\t\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\t\t\t\t\tthrow new TypeError(\"Responses SSE data must be a JSON object\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(parsed as Record<string, unknown>);\n\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\tcontroller.error(new Error(`invalid Responses SSE JSON: ${data.slice(0, 200)}`, { cause }));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n}\n","import type { JSONObject, LanguageModelV3FinishReason, LanguageModelV3Usage } from \"@ai-sdk/provider\";\n\nexport type ResponsesUsage = {\n\tinput_tokens?: number;\n\toutput_tokens?: number;\n\ttotal_tokens?: number;\n\tinput_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n\toutput_tokens_details?: { reasoning_tokens?: number };\n};\n\nexport function convertResponsesUsage(usage: ResponsesUsage | undefined): LanguageModelV3Usage {\n\tconst inputTotal = usage?.input_tokens;\n\tconst cachedTokens = usage?.input_tokens_details?.cached_tokens ?? 0;\n\tconst cacheWriteTokens = usage?.input_tokens_details?.cache_write_tokens ?? 0;\n\tconst outputTotal = usage?.output_tokens;\n\tconst reasoningTokens = usage?.output_tokens_details?.reasoning_tokens ?? 0;\n\n\treturn {\n\t\tinputTokens: {\n\t\t\ttotal: inputTotal,\n\t\t\tnoCache: inputTotal === undefined ? undefined : Math.max(inputTotal - cachedTokens - cacheWriteTokens, 0),\n\t\t\tcacheRead: inputTotal === undefined ? undefined : cachedTokens,\n\t\t\tcacheWrite: inputTotal === undefined ? undefined : cacheWriteTokens,\n\t\t},\n\t\toutputTokens: {\n\t\t\ttotal: outputTotal,\n\t\t\ttext: outputTotal === undefined ? undefined : outputTotal - reasoningTokens,\n\t\t\treasoning: outputTotal === undefined ? undefined : reasoningTokens,\n\t\t},\n\t\t...(usage ? { raw: usage as JSONObject } : {}),\n\t};\n}\n\nexport function mapResponsesFinishReason(\n\tstatus: string | undefined,\n\thasToolCalls: boolean,\n\tincompleteReason?: string,\n): LanguageModelV3FinishReason {\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn { unified: hasToolCalls ? \"tool-calls\" : \"stop\", raw: status };\n\t\tcase \"incomplete\":\n\t\t\treturn incompleteReason === \"max_output_tokens\"\n\t\t\t\t? { unified: \"length\", raw: `${status}.${incompleteReason}` }\n\t\t\t\t: { unified: \"error\", raw: incompleteReason ? `${status}.${incompleteReason}` : status };\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn { unified: \"error\", raw: status };\n\t\tcase undefined:\n\t\t\treturn { unified: \"other\", raw: undefined };\n\t\tdefault:\n\t\t\treturn { unified: \"stop\", raw: status };\n\t}\n}\n","import type * as NodeZlib from \"node:zlib\";\nimport type {\n\tLanguageModelV3,\n\tLanguageModelV3CallOptions,\n\tLanguageModelV3Content,\n\tLanguageModelV3FinishReason,\n\tLanguageModelV3GenerateResult,\n\tLanguageModelV3StreamPart,\n\tLanguageModelV3StreamResult,\n\tLanguageModelV3Usage,\n\tSharedV3Warning,\n} from \"@ai-sdk/provider\";\nimport {\n\tcreateResponsesAPICallError,\n\tresponsesFetchError,\n\tcreateResponsesPrematureCloseError,\n\tcreateResponsesStreamError,\n} from \"./error.ts\";\nimport { collectInPlaceToolNames, convertToResponsesPrompt, joinToolCallId } from \"./prompt.ts\";\nimport { parseResponsesSSEStream } from \"./sse.ts\";\nimport { appendGrammarInputJsonDelta, prepareResponsesTools, type GrammarInputBuffer } from \"./tools.ts\";\nimport { convertResponsesUsage, mapResponsesFinishReason, type ResponsesUsage } from \"./usage.ts\";\n\nexport const PROMPT_CACHE_KEY_MAX_LENGTH = 64;\nconst REQUEST_COMPRESSION_ZSTD_LEVEL = 3;\n// The Responses API rejects max_output_tokens below 16.\nconst MIN_OUTPUT_TOKENS = 16;\n\ntype ProcessWithBuiltinModule = typeof process & {\n\tgetBuiltinModule?: (id: \"node:zlib\") => typeof NodeZlib;\n};\n\nfunction compressRequest(body: string): Uint8Array | undefined {\n\tif (typeof process === \"undefined\" || !(process.versions?.node || process.versions?.bun)) return undefined;\n\tconst zlib = (process as ProcessWithBuiltinModule).getBuiltinModule?.(\"node:zlib\");\n\tif (!zlib || typeof zlib.zstdCompressSync !== \"function\") return undefined;\n\ttry {\n\t\tconst compressed = zlib.zstdCompressSync(body, {\n\t\t\tparams: { [zlib.constants.ZSTD_c_compressionLevel]: REQUEST_COMPRESSION_ZSTD_LEVEL },\n\t\t});\n\t\treturn new Uint8Array(compressed.buffer, compressed.byteOffset, compressed.byteLength);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function clampPromptCacheKey(key: string | undefined): string | undefined {\n\tif (key === undefined) return undefined;\n\tconst characters = Array.from(key);\n\treturn characters.length <= PROMPT_CACHE_KEY_MAX_LENGTH\n\t\t? key\n\t\t: characters.slice(0, PROMPT_CACHE_KEY_MAX_LENGTH).join(\"\");\n}\n\nexport type ResponsesServiceTier = \"auto\" | \"default\" | \"flex\" | \"scale\" | \"priority\";\n\nexport type ResponsesCompatibility = {\n\t/** Internal transport capability derived from the model's input modalities. */\n\tsupportsImages?: boolean;\n};\n\n/**\n * Per-call options, passed via `providerOptions[<provider>]`.\n */\nexport type ResponsesLanguageModelOptions = {\n\t/** Reasoning effort forwarded as `reasoning.effort`. */\n\treasoningEffort?: \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | (string & {});\n\t/** Reasoning summary verbosity; defaults to `auto` when an effort is set. */\n\treasoningSummary?: \"auto\" | \"concise\" | \"detailed\" | \"off\" | \"on\" | null;\n\t/** Output text verbosity; defaults to the backend's `request.textVerbosity`. */\n\ttextVerbosity?: \"low\" | \"medium\" | \"high\";\n\tserviceTier?: ResponsesServiceTier;\n\t/**\n\t * The string input property of each grammar tool the conversation declared, including tools\n\t * since removed, so their earlier calls replay as grammar calls. The current tools win.\n\t */\n\tgrammarToolInputProperties?: Record<string, string>;\n};\n\n/** How one Responses backend takes a request. */\nexport type ResponsesRequestProfile = {\n\t/** Where system prompt text goes: the `instructions` field, or a developer message in place. */\n\tsystemPrompt: \"instructions\" | \"developer\";\n\t/** Whether `max_output_tokens` is sent; the ChatGPT Codex backend rejects it. */\n\tmaxOutputTokens: boolean;\n\t/** Whether `reasoning.encrypted_content` is requested on every call or only with an effort. */\n\tencryptedReasoning: \"always\" | \"withEffort\";\n\t/** zstd-compress the body; a fetch that reads the JSON body needs it uncompressed. */\n\tcompress: boolean;\n\t/**\n\t * Whether `tool_choice: \"auto\"` and `parallel_tool_calls` go on every request, as the Codex\n\t * backend expects. Otherwise only a tool choice the call names is sent: some proxied models\n\t * (Grok on Copilot) reject either field on a request without tools.\n\t */\n\ttoolDefaults: boolean;\n\t/** `text.verbosity` when the call sets none. */\n\ttextVerbosity?: ResponsesLanguageModelOptions[\"textVerbosity\"];\n};\n\nexport type ResponsesLanguageModelConfig = {\n\t/** Provider name, and the providerOptions / providerMetadata key. */\n\tprovider: string;\n\t/** Backend name for error messages, e.g. \"OpenAI Codex\". */\n\tlabel: string;\n\turl: string;\n\theaders: () => PromiseLike<Record<string, string | undefined>> | Record<string, string | undefined>;\n\tfetch?: typeof globalThis.fetch;\n\tpromptCacheKey?: string;\n\tserviceTier?: ResponsesServiceTier;\n\tcompat?: ResponsesCompatibility;\n\trequest: ResponsesRequestProfile;\n};\n\ntype ResponsesEvent = Record<string, unknown>;\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as ResponsesEvent) : undefined;\n}\n\nfunction asString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction cleanHeaders(headers: Record<string, string | undefined>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value !== undefined) result[key] = value;\n\t}\n\treturn result;\n}\n\nexport class ResponsesLanguageModel implements LanguageModelV3 {\n\treadonly specificationVersion = \"v3\" as const;\n\treadonly modelId: string;\n\n\tprivate readonly config: ResponsesLanguageModelConfig;\n\n\tconstructor(modelId: string, config: ResponsesLanguageModelConfig) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t}\n\n\tget provider(): string {\n\t\treturn this.config.provider;\n\t}\n\n\tget supportedUrls(): Record<string, RegExp[]> {\n\t\treturn {};\n\t}\n\n\tprivate getArgs(options: LanguageModelV3CallOptions): {\n\t\targs: Record<string, unknown>;\n\t\twarnings: SharedV3Warning[];\n\t\tgrammarToolInputProperties: ReadonlyMap<string, string>;\n\t} {\n\t\tconst warnings: SharedV3Warning[] = [];\n\n\t\tif (options.topP != null) warnings.push({ type: \"unsupported\", feature: \"topP\" });\n\t\tif (options.topK != null) warnings.push({ type: \"unsupported\", feature: \"topK\" });\n\t\tif (options.presencePenalty != null) warnings.push({ type: \"unsupported\", feature: \"presencePenalty\" });\n\t\tif (options.frequencyPenalty != null) warnings.push({ type: \"unsupported\", feature: \"frequencyPenalty\" });\n\t\tif (options.seed != null) warnings.push({ type: \"unsupported\", feature: \"seed\" });\n\t\tif (options.stopSequences != null) warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n\t\tif (options.maxOutputTokens != null && !this.config.request.maxOutputTokens) {\n\t\t\twarnings.push({ type: \"unsupported\", feature: \"maxOutputTokens\" });\n\t\t}\n\t\tif (options.responseFormat?.type === \"json\" && options.responseFormat.schema === undefined) {\n\t\t\twarnings.push({ type: \"unsupported\", feature: \"responseFormat\" });\n\t\t}\n\n\t\tconst { provider, request } = this.config;\n\t\tconst callOptions = (options.providerOptions?.[provider] ?? {}) as ResponsesLanguageModelOptions;\n\t\tconst tools = prepareResponsesTools({\n\t\t\tprovider,\n\t\t\ttools: options.tools,\n\t\t\ttoolChoice: options.toolChoice,\n\t\t\tinPlaceToolNames: collectInPlaceToolNames(options.prompt, provider),\n\t\t});\n\t\tconst { instructions, input } = convertToResponsesPrompt(options.prompt, {\n\t\t\tprovider,\n\t\t\tsystemPrompt: request.systemPrompt,\n\t\t\tgrammarToolInputProperties: new Map([\n\t\t\t\t...Object.entries(callOptions.grammarToolInputProperties ?? {}),\n\t\t\t\t...tools.grammarToolInputProperties,\n\t\t\t]),\n\t\t\tsupportsImages: this.config.compat?.supportsImages ?? false,\n\t\t});\n\t\twarnings.push(...tools.warnings);\n\n\t\tconst verbosity = callOptions.textVerbosity ?? request.textVerbosity;\n\t\tconst text: Record<string, unknown> = verbosity ? { verbosity } : {};\n\t\tif (options.responseFormat?.type === \"json\" && options.responseFormat.schema !== undefined) {\n\t\t\ttext.format = {\n\t\t\t\ttype: \"json_schema\",\n\t\t\t\tstrict: true,\n\t\t\t\tschema: options.responseFormat.schema,\n\t\t\t\tname: options.responseFormat.name ?? \"output_schema\",\n\t\t\t};\n\t\t}\n\n\t\tconst args: Record<string, unknown> = {\n\t\t\tmodel: this.modelId,\n\t\t\t// Reasoning replays from encrypted content, so nothing is stored server-side.\n\t\t\tstore: false,\n\t\t\t...(instructions !== undefined && { instructions }),\n\t\t\tinput,\n\t\t\t...(request.toolDefaults\n\t\t\t\t? { tool_choice: tools.toolChoiceValue ?? \"auto\", parallel_tool_calls: true }\n\t\t\t\t: tools.toolChoiceValue !== undefined && { tool_choice: tools.toolChoiceValue }),\n\t\t\t...((request.encryptedReasoning === \"always\" || callOptions.reasoningEffort) && {\n\t\t\t\tinclude: [\"reasoning.encrypted_content\"],\n\t\t\t}),\n\t\t\t...(Object.keys(text).length > 0 && { text }),\n\t\t};\n\n\t\tif (tools.responsesTools) args.tools = tools.responsesTools;\n\t\tif (options.temperature != null) args.temperature = options.temperature;\n\t\tif (request.maxOutputTokens && options.maxOutputTokens != null) {\n\t\t\targs.max_output_tokens = Math.max(options.maxOutputTokens, MIN_OUTPUT_TOKENS);\n\t\t}\n\n\t\tconst promptCacheKey = clampPromptCacheKey(this.config.promptCacheKey);\n\t\tif (promptCacheKey) args.prompt_cache_key = promptCacheKey;\n\n\t\tconst serviceTier = callOptions.serviceTier ?? this.config.serviceTier;\n\t\tif (serviceTier) args.service_tier = serviceTier;\n\n\t\tif (callOptions.reasoningEffort) {\n\t\t\targs.reasoning = {\n\t\t\t\teffort: callOptions.reasoningEffort,\n\t\t\t\tsummary: callOptions.reasoningSummary ?? \"auto\",\n\t\t\t};\n\t\t}\n\n\t\treturn { args, warnings, grammarToolInputProperties: tools.grammarToolInputProperties };\n\t}\n\n\tasync doGenerate(options: LanguageModelV3CallOptions): Promise<LanguageModelV3GenerateResult> {\n\t\tconst { stream, request, response } = await this.doStream(options);\n\n\t\tconst content: LanguageModelV3Content[] = [];\n\t\tconst textBlocks = new Map<string, Extract<LanguageModelV3Content, { type: \"text\" }>>();\n\t\tconst reasoningBlocks = new Map<string, Extract<LanguageModelV3Content, { type: \"reasoning\" }>>();\n\t\tconst warnings: SharedV3Warning[] = [];\n\t\tlet finishReason: LanguageModelV3FinishReason = { unified: \"other\", raw: undefined };\n\t\tlet usage: LanguageModelV3Usage = convertResponsesUsage(undefined);\n\t\tlet responseId: string | undefined;\n\t\tlet responseModelId: string | undefined;\n\n\t\tconst reader = stream.getReader();\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\n\t\t\tswitch (value.type) {\n\t\t\t\tcase \"stream-start\":\n\t\t\t\t\twarnings.push(...value.warnings);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\tresponseId = value.id;\n\t\t\t\t\tresponseModelId = value.modelId;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"text-start\": {\n\t\t\t\t\tconst block = { type: \"text\" as const, text: \"\" };\n\t\t\t\t\ttextBlocks.set(value.id, block);\n\t\t\t\t\tcontent.push(block);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-delta\": {\n\t\t\t\t\tconst block = textBlocks.get(value.id);\n\t\t\t\t\tif (block) block.text += value.delta;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-end\": {\n\t\t\t\t\tconst block = textBlocks.get(value.id);\n\t\t\t\t\tif (block && value.providerMetadata !== undefined) block.providerMetadata = value.providerMetadata;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\tconst block = { type: \"reasoning\" as const, text: \"\" };\n\t\t\t\t\treasoningBlocks.set(value.id, block);\n\t\t\t\t\tcontent.push(block);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-delta\": {\n\t\t\t\t\tconst block = reasoningBlocks.get(value.id);\n\t\t\t\t\tif (block) block.text += value.delta;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-end\": {\n\t\t\t\t\tconst block = reasoningBlocks.get(value.id);\n\t\t\t\t\tif (block && value.providerMetadata !== undefined) block.providerMetadata = value.providerMetadata;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-call\":\n\t\t\t\t\tcontent.push(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tfinishReason = value.finishReason;\n\t\t\t\t\tusage = value.usage;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tthrow value.error instanceof Error ? value.error : new Error(String(value.error));\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: content.filter((part) =>\n\t\t\t\tpart.type === \"text\" || part.type === \"reasoning\"\n\t\t\t\t\t? part.text !== \"\" || part.providerMetadata !== undefined\n\t\t\t\t\t: true,\n\t\t\t),\n\t\t\tfinishReason,\n\t\t\tusage,\n\t\t\t...(request !== undefined && { request }),\n\t\t\tresponse: {\n\t\t\t\t...response,\n\t\t\t\t...(responseId !== undefined && { id: responseId }),\n\t\t\t\t...(responseModelId !== undefined && { modelId: responseModelId }),\n\t\t\t},\n\t\t\twarnings,\n\t\t};\n\t}\n\n\tasync doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {\n\t\tconst { args, warnings, grammarToolInputProperties } = this.getArgs(options);\n\t\tconst body = { ...args, stream: true };\n\t\tconst { url, label } = this.config;\n\n\t\tconst headers = cleanHeaders({\n\t\t\t...(await this.config.headers()),\n\t\t\t...options.headers,\n\t\t});\n\t\tconst bodyJson = JSON.stringify(body);\n\t\tconst compressedBody = this.config.request.compress ? compressRequest(bodyJson) : undefined;\n\t\tif (compressedBody) headers[\"content-encoding\"] = \"zstd\";\n\n\t\tconst fetchImpl = this.config.fetch ?? globalThis.fetch;\n\t\tconst response = await fetchImpl(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: compressedBody ?? bodyJson,\n\t\t\t...(options.abortSignal !== undefined && { signal: options.abortSignal }),\n\t\t}).catch((error: unknown) => {\n\t\t\tthrow responsesFetchError(error, url, body);\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow await createResponsesAPICallError({ label, response, url, requestBodyValues: body });\n\t\t}\n\t\tif (!response.body) {\n\t\t\tthrow new Error(`${label} response has no body`);\n\t\t}\n\n\t\tconst responseHeaders: Record<string, string> = {};\n\t\tresponse.headers.forEach((value, key) => {\n\t\t\tresponseHeaders[key] = value;\n\t\t});\n\n\t\treturn {\n\t\t\tstream: parseResponsesSSEStream(response.body).pipeThrough(\n\t\t\t\tthis.createTransformStream(warnings, options.includeRawChunks ?? false, grammarToolInputProperties, {\n\t\t\t\t\tlabel,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: body,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t}),\n\t\t\t),\n\t\t\trequest: { body },\n\t\t\tresponse: { headers: responseHeaders },\n\t\t};\n\t}\n\n\tprivate createTransformStream(\n\t\twarnings: SharedV3Warning[],\n\t\tincludeRawChunks: boolean,\n\t\tgrammarToolInputProperties: ReadonlyMap<string, string>,\n\t\trequest: {\n\t\t\tlabel: string;\n\t\t\turl: string;\n\t\t\trequestBodyValues: unknown;\n\t\t\tresponseHeaders: Record<string, string>;\n\t\t},\n\t): TransformStream<ResponsesEvent, LanguageModelV3StreamPart> {\n\t\tconst { provider } = this.config;\n\t\tlet finishReason: LanguageModelV3FinishReason = { unified: \"other\", raw: undefined };\n\t\tlet usage: ResponsesUsage | undefined;\n\t\tlet hasToolCalls = false;\n\t\tlet finished = false;\n\t\tlet servedServiceTier: string | undefined;\n\t\t/*\n\t\t * Items are tracked by `output_index`: Copilot sends a different item id on every\n\t\t * event of the same item. Tool parts use the composite `call_id|item_id` from the\n\t\t * item's first event so multi-turn replay can recover both halves.\n\t\t */\n\t\ttype Slot =\n\t\t\t| { kind: \"text\"; id: string }\n\t\t\t| { kind: \"reasoning\"; id: string }\n\t\t\t| { kind: \"function\"; toolCallId: string; toolName: string }\n\t\t\t| {\n\t\t\t\t\tkind: \"custom\";\n\t\t\t\t\ttoolCallId: string;\n\t\t\t\t\ttoolName: string;\n\t\t\t\t\tinputProperty: string;\n\t\t\t\t\tbuffer: GrammarInputBuffer;\n\t\t\t };\n\t\tconst slots = new Map<string, Slot>();\n\t\tconst slotKey = (event: ResponsesEvent, item?: ResponsesEvent): string | undefined =>\n\t\t\ttypeof event.output_index === \"number\"\n\t\t\t\t? `#${event.output_index}`\n\t\t\t\t: (asString(event.item_id) ?? asString(item?.id));\n\t\tconst finish = (controller: TransformStreamDefaultController<LanguageModelV3StreamPart>): void => {\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"finish\",\n\t\t\t\tfinishReason,\n\t\t\t\tusage: convertResponsesUsage(usage),\n\t\t\t\t// The tier the response was served at decides what it costs, and it is\n\t\t\t\t// not always the tier that was requested.\n\t\t\t\t...(servedServiceTier === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { providerMetadata: { [provider]: { serviceTier: servedServiceTier } } }),\n\t\t\t});\n\t\t};\n\t\tconst fail = (controller: TransformStreamDefaultController<LanguageModelV3StreamPart>, error: unknown): void => {\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\tcontroller.enqueue({ type: \"error\", error });\n\t\t\tcontroller.terminate();\n\t\t};\n\n\t\tconst startSlot = (\n\t\t\tkey: string,\n\t\t\titem: ResponsesEvent,\n\t\t\tcontroller: TransformStreamDefaultController<LanguageModelV3StreamPart>,\n\t\t): Slot | undefined => {\n\t\t\tconst itemType = asString(item.type);\n\t\t\tconst itemId = asString(item.id);\n\t\t\tif (!itemType || !itemId) return;\n\n\t\t\tlet slot: Slot | undefined;\n\t\t\tif (itemType === \"message\") {\n\t\t\t\tslot = { kind: \"text\", id: itemId };\n\t\t\t\tcontroller.enqueue({ type: \"text-start\", id: itemId });\n\t\t\t} else if (itemType === \"reasoning\") {\n\t\t\t\tslot = { kind: \"reasoning\", id: itemId };\n\t\t\t\tcontroller.enqueue({ type: \"reasoning-start\", id: itemId });\n\t\t\t} else if (itemType === \"function_call\") {\n\t\t\t\tconst toolName = asString(item.name) ?? \"\";\n\t\t\t\tslot = { kind: \"function\", toolCallId: joinToolCallId(asString(item.call_id) ?? itemId, itemId), toolName };\n\t\t\t\thasToolCalls = true;\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-start\", id: slot.toolCallId, toolName });\n\t\t\t} else if (itemType === \"custom_tool_call\") {\n\t\t\t\tconst toolName = asString(item.name) ?? \"\";\n\t\t\t\tslot = {\n\t\t\t\t\tkind: \"custom\",\n\t\t\t\t\ttoolCallId: joinToolCallId(asString(item.call_id) ?? itemId, itemId),\n\t\t\t\t\ttoolName,\n\t\t\t\t\tinputProperty: grammarToolInputProperties.get(toolName) ?? \"input\",\n\t\t\t\t\tbuffer: { input: \"\", started: false, closed: false },\n\t\t\t\t};\n\t\t\t\thasToolCalls = true;\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-start\", id: slot.toolCallId, toolName });\n\t\t\t}\n\t\t\tif (slot) slots.set(key, slot);\n\t\t\treturn slot;\n\t\t};\n\n\t\tconst endSlot = (\n\t\t\tkey: string,\n\t\t\titem: ResponsesEvent,\n\t\t\tcontroller: TransformStreamDefaultController<LanguageModelV3StreamPart>,\n\t\t) => {\n\t\t\tconst slot = slots.get(key) ?? startSlot(key, item, controller);\n\t\t\tif (!slot) return;\n\t\t\tslots.delete(key);\n\t\t\tconst namespace = asString(item.namespace);\n\t\t\tconst namespaceMetadata = namespace ? { providerMetadata: { [provider]: { namespace } } } : {};\n\n\t\t\tif (slot.kind === \"text\") {\n\t\t\t\tconst messageId = asString(item.id) ?? slot.id;\n\t\t\t\tcontroller.enqueue({ type: \"text-end\", id: slot.id, providerMetadata: { [provider]: { messageId } } });\n\t\t\t} else if (slot.kind === \"reasoning\") {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\tid: slot.id,\n\t\t\t\t\tproviderMetadata: { [provider]: { reasoningItem: JSON.stringify(item) } },\n\t\t\t\t});\n\t\t\t} else if (slot.kind === \"function\") {\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-end\", id: slot.toolCallId });\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\ttoolCallId: slot.toolCallId,\n\t\t\t\t\ttoolName: asString(item.name) ?? slot.toolName,\n\t\t\t\t\tinput: asString(item.arguments) ?? \"\",\n\t\t\t\t\t...namespaceMetadata,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst input = asString(item.input) ?? slot.buffer.input;\n\t\t\t\tconst delta = appendGrammarInputJsonDelta(slot.buffer, slot.inputProperty, input, true);\n\t\t\t\tif (delta) controller.enqueue({ type: \"tool-input-delta\", id: slot.toolCallId, delta });\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-end\", id: slot.toolCallId });\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\ttoolCallId: slot.toolCallId,\n\t\t\t\t\ttoolName: slot.toolName,\n\t\t\t\t\tinput: JSON.stringify({ [slot.inputProperty]: input }),\n\t\t\t\t\t...namespaceMetadata,\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\treturn new TransformStream<ResponsesEvent, LanguageModelV3StreamPart>({\n\t\t\tstart(controller) {\n\t\t\t\tcontroller.enqueue({ type: \"stream-start\", warnings });\n\t\t\t},\n\n\t\t\ttransform(event, controller) {\n\t\t\t\tif (includeRawChunks) {\n\t\t\t\t\tcontroller.enqueue({ type: \"raw\", rawValue: event });\n\t\t\t\t}\n\n\t\t\t\tconst type = asString(event.type);\n\t\t\t\tif (!type) return;\n\n\t\t\t\tswitch (type) {\n\t\t\t\t\tcase \"response.created\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tconst id = asString(response?.id);\n\t\t\t\t\t\tconst modelId = asString(response?.model);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"response-metadata\",\n\t\t\t\t\t\t\t...(id !== undefined && { id }),\n\t\t\t\t\t\t\t...(modelId !== undefined && { modelId }),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_item.added\": {\n\t\t\t\t\t\tconst item = asRecord(event.item);\n\t\t\t\t\t\tconst key = item ? slotKey(event, item) : undefined;\n\t\t\t\t\t\tif (item && key) startSlot(key, item, controller);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_text.delta\": {\n\t\t\t\t\t\tconst slot = slots.get(slotKey(event) ?? \"\");\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tif (slot?.kind === \"text\" && delta) controller.enqueue({ type: \"text-delta\", id: slot.id, delta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.reasoning_text.delta\":\n\t\t\t\t\tcase \"response.reasoning_summary_text.delta\": {\n\t\t\t\t\t\tconst slot = slots.get(slotKey(event) ?? \"\");\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tif (slot?.kind === \"reasoning\" && delta) {\n\t\t\t\t\t\t\tcontroller.enqueue({ type: \"reasoning-delta\", id: slot.id, delta });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.function_call_arguments.delta\": {\n\t\t\t\t\t\tconst slot = slots.get(slotKey(event) ?? \"\");\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tif (slot?.kind === \"function\" && delta) {\n\t\t\t\t\t\t\tcontroller.enqueue({ type: \"tool-input-delta\", id: slot.toolCallId, delta });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.custom_tool_call_input.delta\":\n\t\t\t\t\tcase \"response.custom_tool_call_input.done\": {\n\t\t\t\t\t\tconst slot = slots.get(slotKey(event) ?? \"\");\n\t\t\t\t\t\tif (slot?.kind !== \"custom\") break;\n\t\t\t\t\t\tconst done = type === \"response.custom_tool_call_input.done\";\n\t\t\t\t\t\tconst input = done ? asString(event.input) : slot.buffer.input + (asString(event.delta) ?? \"\");\n\t\t\t\t\t\tif (input === undefined) break;\n\t\t\t\t\t\tconst jsonDelta = appendGrammarInputJsonDelta(slot.buffer, slot.inputProperty, input, done);\n\t\t\t\t\t\tif (jsonDelta)\n\t\t\t\t\t\t\tcontroller.enqueue({ type: \"tool-input-delta\", id: slot.toolCallId, delta: jsonDelta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_item.done\": {\n\t\t\t\t\t\tconst item = asRecord(event.item);\n\t\t\t\t\t\tconst key = item ? slotKey(event, item) : undefined;\n\t\t\t\t\t\tif (item && key) endSlot(key, item, controller);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.completed\":\n\t\t\t\t\tcase \"response.incomplete\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tusage = (response?.usage as ResponsesUsage | undefined) ?? usage;\n\t\t\t\t\t\tservedServiceTier = asString(response?.service_tier) ?? servedServiceTier;\n\t\t\t\t\t\tconst status =\n\t\t\t\t\t\t\tasString(response?.status) ?? (type === \"response.incomplete\" ? \"incomplete\" : \"completed\");\n\t\t\t\t\t\tconst incompleteReason = asString(asRecord(response?.incomplete_details)?.reason);\n\t\t\t\t\t\tfinishReason = mapResponsesFinishReason(status, hasToolCalls, incompleteReason);\n\t\t\t\t\t\tfinish(controller);\n\t\t\t\t\t\tcontroller.terminate();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.failed\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tconst error = asRecord(response?.error);\n\t\t\t\t\t\tfinishReason = { unified: \"error\", raw: \"failed\" };\n\t\t\t\t\t\tfail(\n\t\t\t\t\t\t\tcontroller,\n\t\t\t\t\t\t\tcreateResponsesStreamError({\n\t\t\t\t\t\t\t\terror: error ?? { message: `${request.label} response failed` },\n\t\t\t\t\t\t\t\t...request,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tconst code = asString(event.code);\n\t\t\t\t\t\tfinishReason = { unified: \"error\", raw: code ?? \"error\" };\n\t\t\t\t\t\tfail(controller, createResponsesStreamError({ error: event, ...request }));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// Ignore lifecycle events we do not surface (content_part, in_progress, ...).\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tflush(controller) {\n\t\t\t\tif (!finished) {\n\t\t\t\t\tfinished = true;\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terror: createResponsesPrematureCloseError(request),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAa,oBAAoBA,OAAK,OAAO;CAC5C,MAAMA,OAAK,QAAQ,MAAM;CACzB,MAAMA,OAAK,OAAO;CAClB,eAAeA,OAAK,SAASA,OAAK,OAAO,CAAC;AAC3C,CAAC;AAGD,MAAa,qBAAqBA,OAAK,OAAO;CAC7C,MAAMA,OAAK,QAAQ,OAAO;CAC1B,MAAMA,OAAK,OAAO;CAClB,UAAUA,OAAK,OAAO;AACvB,CAAC;AAGD,MAAa,wBAAwBA,OAAK,OAAO;CAChD,MAAMA,OAAK,QAAQ,UAAU;CAC7B,UAAUA,OAAK,OAAO;CAGtB,mBAAmBA,OAAK,SAASA,OAAK,OAAO,CAAC;;;;CAI9C,UAAUA,OAAK,SAASA,OAAK,QAAQ,CAAC;AACvC,CAAC;AAGD,MAAa,qBAAqBA,OAAK,OAAO;CAC7C,MAAMA,OAAK,QAAQ,UAAU;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