@codeworksh/aikit 0.13.0 → 0.14.0-canary.129.1.g84dd6b36

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/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["Type","Message.AssistantMessageSchema","Message.ToolCallSchema","Model.getModel","Model.getModels","Model.getProviders","Model.registry","Model.modelsAreEqual","Type","Model.KnownProviderEnumSchema","stream","Transcript.renderSystemPromptUpdate","Type","Model.ThinkingBudgets","Type","Model.APIMethodEnumSchema","Model.ActiveThinkingLevel","Model.optionsKey","Protocol.ProtocolAuthError","Model.thinkingTokenBudgetField","Model.optionsKey","Model.clampThinkingLevel","partialParse","Message.createAssistantMessage","Message.omitImages","Model.optionsKey","Transcript.getCurrentTools","Transcript.getDeclaredTools","Transcript.resolveTranscriptPrompt","Message.transformMessages","Transcript.resolveTranscriptTools","Transcript.renderSystemPromptUpdate","Pricing.cacheWrite1hTokens","Model.optionsKey","Thinking.isAnthropicMessagesModel","Thinking.reasoningProviderOptions","Thinking.providerThinkingLevel","Pricing.serviceTierCostMultiplier","Pricing.servedServiceTier","stream","Thinking.resolvePlan","Pricing.requestedServiceTier","Failure.strictToolLimitMessage","Failure.normalize","Protocol.stream","Protocol.complete","Protocol.resolveProtocolProvider"],"sources":["../../src/event/event.ts","../../src/llm.ts","../../src/llm/protocol.ts","../../src/llm/runtime.ts","../../src/message/transcript.ts","../../src/utils/estimate.ts","../../src/llm/shared.ts","../../src/llm/options.ts","../../src/utils/eventstream.ts","../../src/utils/helpers.ts","../../src/llm/pricing.ts","../../src/llm/provider.ts","../../src/llm/thinking.ts","../../src/utils/jsonparse.ts","../../src/utils/sanitize.ts","../../src/llm/strict.ts","../../src/llm/transform.ts","../../src/llm/stream.ts","../../src/llm/index.ts","../../src/llm/register.ts","../../src/stream.ts","../../src/utils/validation.ts"],"sourcesContent":["import Type, { type Static } from \"typebox\";\nimport * as Message from \"../message/message.ts\";\n\n// TODO @sanchitrk:\n// for delta events we can have metadata KV that a provider can use for internal state\n// similar to index what anthropic does\nexport const LLMMessageEventType = {\n\tstart: \"start\",\n\n\ttextStart: \"text.start\",\n\ttextDelta: \"text.delta\",\n\ttextEnd: \"text.end\",\n\n\tthinkingStart: \"thinking.start\",\n\tthinkingDelta: \"thinking.delta\",\n\tthinkingEnd: \"thinking.end\",\n\n\ttoolcallStart: \"toolcall.start\",\n\ttoolcallDelta: \"toolcall.delta\",\n\ttoolcallEnd: \"toolcall.end\",\n\ttoolcallFinal: \"toolcall.final\",\n\n\tdone: \"done\",\n\terror: \"error\",\n} as const;\nexport type LLMMessageEventType = (typeof LLMMessageEventType)[keyof typeof LLMMessageEventType];\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Streams should emit `start` before partial updates, then terminate with either:\n * - `done` carrying the final successful AssistantMessage, or\n * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n * and errorMessage.\n */\nexport const LLMMessageEventSchema = Type.Union([\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.start),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textEnd),\n\t\tpartIndex: Type.Number(),\n\t\tcontent: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingEnd),\n\t\tpartIndex: Type.Number(),\n\t\tcontent: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallEnd),\n\t\tpartIndex: Type.Number(),\n\t\ttoolCall: Message.ToolCallSchema,\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallFinal),\n\t\tpartIndex: Type.Number(),\n\t\ttoolCall: Message.ToolCallSchema,\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.done),\n\t\treason: Type.Union([Type.Literal(\"stop\"), Type.Literal(\"length\"), Type.Literal(\"toolUse\")]),\n\t\tmessage: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.error),\n\t\treason: Type.Union([Type.Literal(\"aborted\"), Type.Literal(\"error\")]),\n\t\terror: Message.AssistantMessageSchema,\n\t}),\n]);\nexport type LLMMessageEvent = Static<typeof LLMMessageEventSchema>;\n\n// export const AgentEventType = {\n// \t// Agent lifecycle\n// \tagentStart: \"agent.start\",\n// \tagentEnd: \"agent.end\",\n// \t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n// \tturnStart: \"turn.start\",\n// \tturnEnd: \"turn.end\",\n// \t// Message lifecycle - emitted for user, assistant message and corresponding parts\n// \tmessageStart: \"message.start\",\n\n// \tmessagePartStart: \"message.part.start\",\n// \tmessagePartUpdate: \"message.part.update\",\n// \tmessagePartEnd: \"message.part.end\",\n\n// \tmessageUpdate: \"message.update\",\n// \tmessageEnd: \"message.end\",\n// \t// Tool execution lifecycle\n// \ttoolExecutionStart: \"tool.execution.start\",\n// \ttoolExecutionUpdate: \"tool.execution.update\",\n// \ttoolExecutionEnd: \"tool.execution.end\",\n// } as const;\n// export type AgentEventType = (typeof AgentEventType)[keyof typeof AgentEventType];\n\n//\n// message parts\n// const UserMessagePart = Type.Union([Message.TextContentSchema, Message.ImageContentSchema]);\n// const AssistantMessagePart = Type.Union([\n// \tMessage.TextContentSchema,\n// \tMessage.ImageContentSchema,\n// \tMessage.ThinkingContentSchema,\n// \tMessage.ToolCallSchema,\n// ]);\n\n//\n// user message part\n// part start\n// const UserMessagePartStart = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartStart),\n// \tmessage: Message.UserMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: UserMessagePart,\n// });\n// part end\n// const UserMessagePartEnd = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartEnd),\n// \tmessage: Message.UserMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: UserMessagePart,\n// });\n\n//\n// assistant message part\n// part start\n// const AssistantMessagePartStart = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartStart),\n// \tmessage: Message.AssistantMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: AssistantMessagePart,\n// });\n// part update llm\n// const AssistantMessagePartLLMUpdate = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartUpdate),\n// \tmessage: Message.AssistantMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: AssistantMessagePart,\n// \tsource: Type.Literal(\"llm\"),\n// });\n// part update tool\n// const AssistantMessagePartToolUpdate = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartUpdate),\n// \tmessage: Message.AssistantMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: AssistantMessagePart,\n// \tsource: Type.Literal(\"tool\"),\n// });\n// part end\n// const AssistantMessagePartEnd = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartEnd),\n// \tmessage: Message.AssistantMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: AssistantMessagePart,\n// });\n\n//\n// tool exection\n// const ToolExecutionStartSchema = Type.Object({\n// \ttype: Type.Literal(AgentEventType.toolExecutionStart),\n// \tmessageId: Type.String(),\n// \tpartIndex: Type.Number(),\n// \ttoolCall: Message.ToolCallPendingPartSchema,\n// });\n// export type ToolExecutionStart = Static<typeof ToolExecutionStartSchema>;\n\n// const ToolExecutionUpdateSchema = Type.Object({\n// \ttype: Type.Literal(AgentEventType.toolExecutionUpdate),\n// \tmessageId: Type.String(),\n// \tpartIndex: Type.Number(),\n// \ttoolCall: Message.ToolCallRunningPartSchema,\n// });\n// export type ToolExecutionUpdate = Static<typeof ToolExecutionUpdateSchema>;\n\n// const ToolExecutionEndSchema = Type.Object({\n// \ttype: Type.Literal(AgentEventType.toolExecutionEnd),\n// \tmessageId: Type.String(),\n// \tpartIndex: Type.Number(),\n// \ttoolCall: Message.ToolCallTerminalPartSchema,\n// });\n// export type ToolExecutionEnd = Static<typeof ToolExecutionEndSchema>;\n\n/**\n * Events emitted by the Agent lifecycle\n * These events provide fine-grained lifecycle information for messages, turns, and tool execution.\n */\n// export const AgentEventSchema = Type.Union([\n// \t//\n// \t// Agent lifecycle\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.agentStart),\n// \t}),\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.agentEnd),\n// \t\tmessages: Type.Array(Message.MessageSchema),\n// \t}),\n// \t//\n// \t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.turnStart),\n// \t}),\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.turnEnd),\n// \t\tmessage: Message.AssistantMessageSchema,\n// \t}),\n// \t//\n// \t// Message lifecycle - emitted for user, assistant and corresponding parts\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.messageStart),\n// \t\tmessage: Message.MessageSchema,\n// \t}),\n// \t// user message parts lifecycle\n// \tType.Union([UserMessagePartStart, UserMessagePartEnd]),\n// \t//\n// \t// assistant message parts lifecycle\n// \tType.Union([\n// \t\tAssistantMessagePartStart,\n// \t\tAssistantMessagePartLLMUpdate,\n// \t\tAssistantMessagePartToolUpdate,\n// \t\tAssistantMessagePartEnd,\n// \t]),\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.messageUpdate),\n// \t\tmessage: Message.MessageSchema,\n// \t}),\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.messageEnd),\n// \t\tmessage: Message.MessageSchema,\n// \t}),\n// \t//\n// \t// Tool execution lifecycle\n// \tToolExecutionStartSchema,\n// \tToolExecutionUpdateSchema,\n// \tToolExecutionEndSchema,\n// ]);\n// export type AgentEvent = Static<typeof AgentEventSchema>;\n","import * as Model from \"./model/model.ts\";\n\ntype LLM = {\n\t<TProvider extends string, TProtocol extends Model.KnownProviderEnum = Model.ProviderToProtocol<TProvider>>(\n\t\tprovider: TProvider,\n\t\tmodel: string,\n\t\toverrides?: Partial<Model.Info> & { protocol?: TProtocol },\n\t): Promise<Model.TModel<TProtocol> | undefined>;\n\tmodel: typeof Model.getModel;\n\tmodels: typeof Model.getModels;\n\tproviders: typeof Model.getProviders;\n\tregistry: typeof Model.registry;\n\tmodelsAreEqual: typeof Model.modelsAreEqual;\n};\n\nconst llmImpl = async <\n\tTProvider extends string,\n\tTProtocol extends Model.KnownProviderEnum = Model.ProviderToProtocol<TProvider>,\n>(\n\tprovider: TProvider,\n\tmodel: string,\n\toverrides?: Partial<Model.Info> & { protocol?: TProtocol },\n): Promise<Model.TModel<TProtocol> | undefined> => Model.getModel(provider, model, overrides as any);\n\nexport const llm = Object.assign(llmImpl, {\n\tmodel: Model.getModel,\n\tmodels: Model.getModels,\n\tproviders: Model.getProviders,\n\tregistry: Model.registry,\n\tmodelsAreEqual: Model.modelsAreEqual,\n}) as LLM;\n","import type { Static, TSchema } from \"typebox\";\nimport Type from \"typebox\";\nimport type * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { NamedError } from \"../utils/error.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/eventstream.ts\";\nimport type {\n\tAnthropicOptions,\n\tGitHubCopilotOptions,\n\tGoogleOptions,\n\tGoogleVertexAnthropicOptions,\n\tGoogleVertexOptions,\n\tOpenAICodexOptions,\n\tOpenAICompatibleOptions,\n\tOpenAIOptions,\n\tOpenRouterOptions,\n\tXaiOptions,\n} from \"./options.ts\";\nimport type { SharedOptions, ThinkingBudgets } from \"./shared.ts\";\nexport const ProviderProtocolNotFoundError = NamedError.create(\n\t\"ProviderProtocolNotFoundError\",\n\tType.Object({\n\t\tprotocol: Model.KnownProviderEnumSchema,\n\t}),\n);\nexport type ProviderProtocolNotFoundError = InstanceType<typeof ProviderProtocolNotFoundError>;\n\nexport const ProtocolMismatchError = NamedError.create(\n\t\"ProtocolMismatchError\",\n\tType.Object({\n\t\tactual: Model.KnownProviderEnumSchema,\n\t\texpected: Model.KnownProviderEnumSchema,\n\t}),\n);\nexport type ProtocolMismatchError = InstanceType<typeof ProtocolMismatchError>;\n\nexport const ProtocolAuthError = NamedError.create(\n\t\"ProtocolAuthError\",\n\tType.Object({\n\t\tmessage: Type.String(),\n\t\tprotocol: Type.String(),\n\t}),\n);\nexport type ProtocolAuthError = InstanceType<typeof ProtocolAuthError>;\n\nexport type CommonOptions = SharedOptions & {\n\treasoning?: Model.ActiveThinkingLevel;\n\tthinkingBudgets?: ThinkingBudgets;\n};\nexport interface OptionsByProtocol {\n\t[Model.KnownProviderEnum.openai]: OpenAIOptions;\n\t[Model.KnownProviderEnum.anthropic]: AnthropicOptions;\n\t[Model.KnownProviderEnum.google]: GoogleOptions;\n\t[Model.KnownProviderEnum.googleVertex]: GoogleVertexOptions;\n\t[Model.KnownProviderEnum.googleVertexAnthropic]: GoogleVertexAnthropicOptions;\n\t[Model.KnownProviderEnum.openaiCompatible]: OpenAICompatibleOptions;\n\t[Model.KnownProviderEnum.openaiCodex]: OpenAICodexOptions;\n\t[Model.KnownProviderEnum.githubCopilot]: GitHubCopilotOptions;\n\t[Model.KnownProviderEnum.openrouter]: OpenRouterOptions;\n\t[Model.KnownProviderEnum.xai]: XaiOptions;\n}\nexport type ProtocolWithOptions = keyof OptionsByProtocol & Model.KnownProviderEnum;\nexport type OptionsFor<TProtocol extends ProtocolWithOptions> = OptionsByProtocol[TProtocol];\n\nexport type StreamFunction<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> = (model: Model.TModel<TProtocol>, context: Message.Context, options?: Static<S>) => AssistantMessageEventStream;\n\nexport type ProtocolStreamFunction<S extends TSchema = TSchema> = (\n\tmodel: Model.Info,\n\tcontext: Message.Context,\n\toptions?: Static<S>,\n) => AssistantMessageEventStream;\n\nexport interface Protocol<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> {\n\tprotocol: TProtocol;\n\tstream: StreamFunction<TProtocol, S>;\n}\n\nexport interface RegisteredProtocol<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> {\n\tprotocol: TProtocol;\n\tstream: ProtocolStreamFunction<S>;\n}\n\ntype AnyRegisteredProtocol = RegisteredProtocol<Model.KnownProviderEnum, TSchema>;\n\ntype RegistryEntry = {\n\tprovider: AnyRegisteredProtocol;\n\tsourceId?: string;\n};\n\nconst protocolRegistry = new Map<Model.KnownProviderEnum, RegistryEntry>();\n\nfunction wrapStream<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\tprotocol: TProtocol,\n\tstream: StreamFunction<TProtocol, S>,\n): ProtocolStreamFunction<S> {\n\treturn (model, context, options) => {\n\t\tif (model.protocol !== protocol) {\n\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\tactual: model.protocol,\n\t\t\t\texpected: protocol,\n\t\t\t});\n\t\t}\n\n\t\treturn stream(model as Model.TModel<TProtocol>, context, options);\n\t};\n}\n\nexport function registerProtocolProvider<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\tprovider: Protocol<TProtocol, S>,\n\tsourceId?: string,\n): void {\n\tconst registered: RegisteredProtocol<TProtocol, S> = {\n\t\tprotocol: provider.protocol,\n\t\tstream: wrapStream(provider.protocol, provider.stream),\n\t};\n\n\tprotocolRegistry.set(provider.protocol, {\n\t\tprovider: registered as AnyRegisteredProtocol,\n\t\t...(sourceId !== undefined && { sourceId }),\n\t});\n}\n\nexport function getProtocolProvider(protocol: Model.KnownProviderEnum): AnyRegisteredProtocol | undefined {\n\treturn protocolRegistry.get(protocol)?.provider;\n}\n\nexport function resolveProtocolProvider(model: Model.Info): AnyRegisteredProtocol {\n\tconst provider = getProtocolProvider(model.protocol);\n\tif (!provider) {\n\t\tthrow new ProviderProtocolNotFoundError({\n\t\t\tprotocol: model.protocol,\n\t\t});\n\t}\n\n\treturn provider;\n}\n\nexport function getProtocolProviders(): AnyRegisteredProtocol[] {\n\treturn Array.from(protocolRegistry.values(), (entry) => entry.provider);\n}\n\nexport function stream<TProtocol extends ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: OptionsFor<TProtocol>,\n): AssistantMessageEventStream {\n\tconst provider = resolveProtocolProvider(model);\n\treturn provider.stream(model, context, options);\n}\n\nexport async function complete<TProtocol extends ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: OptionsFor<TProtocol>,\n): Promise<Message.AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function unregisterProtocolProviders(sourceId: string): void {\n\tfor (const [protocol, entry] of protocolRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tprotocolRegistry.delete(protocol);\n\t\t}\n\t}\n}\n\nexport function clearProtocolProviders(): void {\n\tprotocolRegistry.clear();\n}\n","/** Where a provider's API key may come from: its catalog `key` and `env` variable names. */\nexport type ApiKeyProvider = {\n\tenv?: string[];\n\tkey?: string;\n};\n\nexport function mergeHeaders(\n\t...headerSources: (Record<string, string | null> | undefined)[]\n): Record<string, string | null> {\n\tconst merged: Record<string, string | null> = {};\n\tfor (const headers of headerSources) {\n\t\tif (headers) {\n\t\t\tObject.assign(merged, headers);\n\t\t}\n\t}\n\treturn merged;\n}\n\n/** The provider's API key from the environment, checking its `key` then each `env` name. */\nexport function getEnvApiKey(provider: ApiKeyProvider): string | undefined {\n\tif (typeof process === \"undefined\") return;\n\n\tconst candidates = [provider.key, ...(provider.env ?? [])].filter((name): name is string => Boolean(name));\n\tfor (const name of candidates) {\n\t\tconst value = process.env[name];\n\t\tif (value) return value;\n\t}\n}\n\nexport function formatThrownError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.stack || error.message || error.name;\n\t}\n\tif (typeof error === \"string\") {\n\t\treturn error;\n\t}\n\ttry {\n\t\treturn JSON.stringify(error);\n\t} catch {\n\t\treturn String(error);\n\t}\n}\n","/*\n * @file Prompt and tool state carried by a transcript.\n *\n * `Context.systemPrompt` and `Context.tools` are the prompt and tool set at the start of the\n * conversation. Each system message changes them from its position on, so replaying them in\n * order yields the prompt and tools in effect now. Providers either send those changes in\n * place, which keeps the cached prefix, or fold them into the leading prompt and the\n * top-level tool list.\n */\n\nimport type { Context, Message, SystemMessage, Tool, ToolReference } from \"./message.ts\";\n\ntype Transcript = Pick<Context, \"systemPrompt\" | \"tools\" | \"messages\">;\n\ntype PromptChange = Pick<SystemMessage, \"content\" | \"sections\">;\n\nfunction isSystemMessage(message: Message): message is SystemMessage {\n\treturn message.role === \"system\";\n}\n\n/** Render a system message as a complete prompt: its content followed by its sections. */\nexport function renderSystemPrompt(message: PromptChange): string {\n\tconst parts = [message.content ?? \"\"];\n\tfor (const text of Object.values(message.sections ?? {})) {\n\t\tif (text !== null) parts.push(text);\n\t}\n\treturn parts.filter((part) => part.length > 0).join(\"\\n\\n\");\n}\n\n/**\n * Render a later system message sent in place. Section changes are framed by name so the\n * model can relate them to the leading prompt.\n */\nexport function renderSystemPromptUpdate(message: PromptChange): string {\n\tconst parts: string[] = [];\n\tif (message.content) parts.push(message.content);\n\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\tparts.push(\n\t\t\tvalue === null\n\t\t\t\t? `Removed system prompt section \"${name}\".`\n\t\t\t\t: `Updated system prompt section \"${name}\":\\n\\n${value}`,\n\t\t);\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n\n/**\n * The sections after every transcript change in order: replaced by name, removed by `null`, and\n * a removed section added again goes last.\n */\nexport function getCurrentSections(messages: readonly Message[]): Record<string, string> {\n\tconst sections = new Map<string, string>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\t\tif (value === null) sections.delete(name);\n\t\t\telse sections.set(name, value);\n\t\t}\n\t}\n\treturn Object.fromEntries(sections);\n}\n\n/**\n * The patch that brings `previous` sections to `current`, `null` removing one; `undefined` when\n * they match.\n */\nexport function diffSections(\n\tprevious: Readonly<Record<string, string>>,\n\tcurrent: Readonly<Record<string, string>>,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) if (previous[name] !== text) patch[name] = text;\n\tfor (const name of Object.keys(previous)) if (!Object.hasOwn(current, name)) patch[name] = null;\n\treturn Object.keys(patch).length === 0 ? undefined : patch;\n}\n\n/** The prompt after every transcript change in order: content accumulates, sections as {@link getCurrentSections}. */\nexport function getCurrentSystemPrompt(context: Pick<Context, \"systemPrompt\" | \"messages\">): string {\n\tconst content: string[] = [context.systemPrompt ?? \"\"];\n\tfor (const message of context.messages) if (isSystemMessage(message)) content.push(message.content ?? \"\");\n\treturn renderSystemPrompt({\n\t\tcontent: content.filter((part) => part.length > 0).join(\"\\n\\n\"),\n\t\tsections: getCurrentSections(context.messages),\n\t});\n}\n\nexport interface TranscriptPrompt {\n\t/** The prompt sent at the head of the request. */\n\tsystemPrompt: string;\n\t/**\n\t * Number of leading transcript system messages whose prompt changes `systemPrompt` already\n\t * holds. Every later system message sends its changes in place.\n\t */\n\tfoldedSystemMessages: number;\n}\n\n/**\n * Split the prompt between the head of the request and in-place updates.\n *\n * In place, `Context.systemPrompt` leads; without one (and without initial tools), a leading\n * system message is the prompt. Every other system message is an update. Otherwise the head\n * holds the current prompt and no update is sent, which costs the cached prefix on a change.\n */\nexport function resolveTranscriptPrompt(context: Transcript, inPlace: boolean): TranscriptPrompt {\n\tconst systemMessages = context.messages.filter(isSystemMessage);\n\tif (!inPlace) {\n\t\treturn { systemPrompt: getCurrentSystemPrompt(context), foldedSystemMessages: systemMessages.length };\n\t}\n\tconst first = context.messages[0];\n\tif (!context.systemPrompt && (context.tools ?? []).length === 0 && first && isSystemMessage(first)) {\n\t\treturn { systemPrompt: renderSystemPrompt(first), foldedSystemMessages: 1 };\n\t}\n\treturn { systemPrompt: context.systemPrompt ?? \"\", foldedSystemMessages: 0 };\n}\n\n/** The tool changes in order, led by `Context.tools` as the initial declaration. */\nfunction toolDeclarations(context: Transcript): Pick<SystemMessage, \"toolsAdded\" | \"toolsRemoved\">[] {\n\treturn [{ toolsAdded: context.tools ?? [] }, ...context.messages.filter(isSystemMessage)];\n}\n\nfunction replay(declarations: ReadonlyArray<Pick<SystemMessage, \"toolsAdded\" | \"toolsRemoved\">>): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const declaration of declarations) {\n\t\tfor (const tool of declaration.toolsRemoved ?? []) tools.delete(tool.name);\n\t\tfor (const tool of declaration.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/** The tools available after applying every transcript change in order. */\nexport function getCurrentTools(context: Transcript): Tool[] {\n\treturn replay(toolDeclarations(context));\n}\n\n/**\n * Every tool the transcript ever declared, the latest definition of each name winning. Removals\n * are ignored: a removed tool's earlier calls still replay in the form it was called in.\n */\nexport function getDeclaredTools(context: Transcript): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const declaration of toolDeclarations(context)) {\n\t\tfor (const tool of declaration.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/** Strip a tool to what the model sees, for comparison and persistence. */\nexport function toToolDeclaration(tool: Tool): Tool {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: JSON.parse(JSON.stringify(tool.parameters)) as Tool[\"parameters\"],\n\t\t...(tool.constrainedSampling === undefined ? {} : { constrainedSampling: tool.constrainedSampling }),\n\t};\n}\n\n/**\n * Whether two tools declare the same interface to the model. The JSON round trip in\n * {@link toToolDeclaration} drops typebox symbol keys and `undefined` fields and fixes the key\n * order, so comparing the serialized declarations is exact.\n */\nexport function declarationsEqual(left: Tool, right: Tool): boolean {\n\treturn JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));\n}\n\nexport interface ToolStateChanges {\n\ttoolsAdded: Tool[];\n\ttoolsRemoved: ToolReference[];\n}\n\n/** Compare two complete tool states. A changed definition is a removal followed by an addition. */\nexport function getToolStateChanges(previous: readonly Tool[], current: readonly Tool[]): ToolStateChanges {\n\tconst previousTools = new Map(previous.map((tool) => [tool.name, tool]));\n\tconst currentTools = new Map(current.map((tool) => [tool.name, tool]));\n\treturn {\n\t\ttoolsAdded: current\n\t\t\t.filter((tool) => {\n\t\t\t\tconst previousTool = previousTools.get(tool.name);\n\t\t\t\treturn previousTool === undefined || !declarationsEqual(previousTool, tool);\n\t\t\t})\n\t\t\t.map(toToolDeclaration),\n\t\ttoolsRemoved: previous\n\t\t\t.filter((tool) => {\n\t\t\t\tconst currentTool = currentTools.get(tool.name);\n\t\t\t\treturn currentTool === undefined || !declarationsEqual(tool, currentTool);\n\t\t\t})\n\t\t\t.map((tool) => ({ name: tool.name })),\n\t};\n}\n\n/** Index of the last declaration with a removal or same-name redeclaration, or -1. */\nfunction lastNonAdditiveChange(declarations: ReadonlyArray<Pick<SystemMessage, \"toolsAdded\" | \"toolsRemoved\">>) {\n\t// A name declared before counts as a redeclaration even after its removal: a removed tool\n\t// declared again later is not reliably picked up again.\n\tconst declared = new Set<string>();\n\tlet last = -1;\n\tfor (const [index, declaration] of declarations.entries()) {\n\t\tif ((declaration.toolsRemoved?.length ?? 0) > 0) last = index;\n\t\tfor (const tool of declaration.toolsAdded ?? []) {\n\t\t\tif (declared.has(tool.name)) last = index;\n\t\t\tdeclared.add(tool.name);\n\t\t}\n\t}\n\treturn last;\n}\n\n/**\n * How a transport can express tool changes after the first request.\n *\n * - `\"none\"`: only the top-level tool list exists; it always holds the current tools.\n * - `\"additions\"`: tools can be added at a later message, but not removed or redefined.\n * - `\"changes\"`: every tool, including the initial ones, is declared in place, and a later\n * declaration under the same name replaces the earlier one. Removals are not expressible on\n * the wire, so the transport announces them as text and the removed tools stay declared.\n */\nexport type TranscriptToolSupport = \"none\" | \"additions\" | \"changes\";\n\nexport interface TranscriptTools {\n\t/** Tools sent in the top-level request field. */\n\trequestTools: Tool[];\n\t/** Whether `Context.tools` is declared in place at the head of the input instead of top-level. */\n\tinitialToolsInPlace: boolean;\n\t/**\n\t * Number of leading transcript system messages whose changes `requestTools` already holds.\n\t * Every later system message declares its changes in place.\n\t */\n\tfoldedSystemMessages: number;\n}\n\n/**\n * Split tool declarations between the top-level request field and in-place changes.\n *\n * With `\"changes\"`, the top-level list stays empty and every declaration, including\n * `Context.tools`, goes in place: an in-place declaration can replace an earlier in-place one,\n * but not a top-level one. With `\"additions\"`, a removal or redefinition cannot be expressed in\n * place, so the top-level list becomes the tool state after the last such change; later\n * additions stay in place, and the cached prefix is invalidated once per removal instead of on\n * every later addition. With `\"none\"`, the top-level list is the current tool set.\n */\nexport function resolveTranscriptTools(context: Transcript, support: TranscriptToolSupport): TranscriptTools {\n\tconst declarations = toolDeclarations(context);\n\tconst transcriptMessages = declarations.length - 1;\n\tif (support === \"none\") {\n\t\treturn {\n\t\t\trequestTools: replay(declarations),\n\t\t\tinitialToolsInPlace: false,\n\t\t\tfoldedSystemMessages: transcriptMessages,\n\t\t};\n\t}\n\tif (support === \"changes\") return { requestTools: [], initialToolsInPlace: true, foldedSystemMessages: 0 };\n\tconst folded = Math.max(1, lastNonAdditiveChange(declarations) + 1);\n\treturn {\n\t\trequestTools: replay(declarations.slice(0, folded)),\n\t\tinitialToolsInPlace: false,\n\t\tfoldedSystemMessages: folded - 1,\n\t};\n}\n","/*\n * @file Cheap, provider-independent estimate of how much context a request carries.\n *\n * Used to size a response ceiling before the request goes out, so a long session\n * asks for an answer that still fits rather than taking a provider overflow error.\n * The estimate is deliberately coarse: where a real token count already exists --\n * the usage reported by the last assistant turn -- it is trusted, and only the\n * messages appended after it are estimated.\n */\n\nimport type * as Message from \"../message/message.ts\";\nimport * as Transcript from \"../message/transcript.ts\";\n\n/** Rough characters-per-token ratio across the tokenizers in use. */\nconst CHARS_PER_TOKEN = 4;\n/** A base64 image costs far more than its own text length; this is a flat stand-in. */\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nexport interface ContextUsageEstimate {\n\t/** Estimated total context tokens. */\n\ttokens: number;\n\t/** Tokens reported by the most recent applicable assistant usage block. */\n\tusageTokens: number;\n\t/** Estimated tokens after the most recent applicable assistant usage block. */\n\ttrailingTokens: number;\n\t/** Index of the applicable message that provided usage, or null when none exists. */\n\tlastUsageIndex: number | null;\n}\n\nexport function calculateContextTokens(usage: Message.Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\treturn JSON.stringify(value) ?? \"undefined\";\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nexport function estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\nfunction contentChars(content: ReadonlyArray<Message.TextContent | Message.ImageContent>): number {\n\tlet chars = 0;\n\tfor (const block of content) chars += block.type === \"text\" ? block.text.length : ESTIMATED_IMAGE_CHARS;\n\treturn chars;\n}\n\nexport function estimateContentTokens(content: ReadonlyArray<Message.TextContent | Message.ImageContent>): number {\n\treturn Math.ceil(contentChars(content) / CHARS_PER_TOKEN);\n}\n\n/**\n * A tool call costs its name, its arguments, and -- unlike providers that carry\n * results in their own messages -- the result it already holds.\n */\nfunction toolCallChars(part: Message.ToolCall): number {\n\treturn part.name.length + safeJsonStringify(part.arguments).length + toolResultChars(part);\n}\n\nfunction toolResultChars(part: Message.ToolCall): number {\n\treturn \"result\" in part && part.result ? contentChars(part.result.content) : 0;\n}\n\nexport function estimateMessageTokens(message: Message.Message): number {\n\tif (message.role === \"system\") {\n\t\treturn estimateTextTokens(Transcript.renderSystemPromptUpdate(message)) + estimateToolsTokens(message.toolsAdded);\n\t}\n\tif (message.role === \"user\") return estimateContentTokens(message.parts);\n\n\tlet chars = 0;\n\tfor (const part of message.parts) {\n\t\tswitch (part.type) {\n\t\t\tcase \"text\":\n\t\t\t\tchars += part.text.length;\n\t\t\t\tbreak;\n\t\t\tcase \"image\":\n\t\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t\t\tbreak;\n\t\t\tcase \"thinking\":\n\t\t\t\tchars += part.thinking.length;\n\t\t\t\tbreak;\n\t\t\tcase \"toolCall\":\n\t\t\t\tchars += toolCallChars(part);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn Math.ceil(chars / CHARS_PER_TOKEN);\n}\n\nfunction lastAssistantUsage(\n\tmessages: ReadonlyArray<Message.Message>,\n): { usage: Message.Usage; index: number } | undefined {\n\tlet latestPrefixTime = Number.NEGATIVE_INFINITY;\n\tlet found: { usage: Message.Usage; index: number } | undefined;\n\n\tfor (let i = 0; i < messages.length; i++) {\n\t\tconst message = messages[i]!;\n\t\tif (message.role === \"assistant\") {\n\t\t\t/*\n\t\t\t * A newer prefix message was inserted after this response (a compaction\n\t\t\t * summary, say), so its usage no longer describes the current prefix.\n\t\t\t */\n\t\t\tconst appliesToPrefix = message.time.created >= latestPrefixTime;\n\t\t\tif (\n\t\t\t\tappliesToPrefix &&\n\t\t\t\tmessage.stopReason !== \"aborted\" &&\n\t\t\t\tmessage.stopReason !== \"error\" &&\n\t\t\t\tcalculateContextTokens(message.usage) > 0\n\t\t\t) {\n\t\t\t\tfound = { usage: message.usage, index: i };\n\t\t\t}\n\t\t}\n\t\tlatestPrefixTime = Math.max(latestPrefixTime, message.time.created);\n\t}\n\n\treturn found;\n}\n\nfunction estimateMessages(messages: ReadonlyArray<Message.Message>): ContextUsageEstimate {\n\tconst usage = lastAssistantUsage(messages);\n\tif (usage) {\n\t\tconst usageTokens = calculateContextTokens(usage.usage);\n\t\t// Tool results are attached to the assistant turn after its usage was\n\t\t// reported, not sent as separate messages. Only its output is counted.\n\t\tconst latest = messages[usage.index] as Message.AssistantMessage;\n\t\tlet resultChars = 0;\n\t\tfor (const part of latest.parts) {\n\t\t\tif (part.type === \"toolCall\") resultChars += toolResultChars(part);\n\t\t}\n\t\tlet trailingTokens = Math.ceil(resultChars / CHARS_PER_TOKEN);\n\t\tfor (let i = usage.index + 1; i < messages.length; i++) trailingTokens += estimateMessageTokens(messages[i]!);\n\t\treturn { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usage.index };\n\t}\n\n\tlet tokens = 0;\n\tfor (const message of messages) tokens += estimateMessageTokens(message);\n\treturn { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };\n}\n\nfunction estimateToolsTokens(tools: ReadonlyArray<Message.Tool> | undefined): number {\n\tif (!tools || tools.length === 0) return 0;\n\treturn estimateTextTokens(safeJsonStringify(tools));\n}\n\nexport function estimateContextTokens(context: Message.Context): ContextUsageEstimate {\n\tconst estimate = estimateMessages(context.messages);\n\n\t/*\n\t * Reported usage already includes the system prompt and the tools that were\n\t * live at the time. Prompt and tool changes since arrive as system messages\n\t * after it, which the trailing estimate already counts.\n\t */\n\tif (estimate.lastUsageIndex !== null) return estimate;\n\n\tconst prefixTokens =\n\t\t(context.systemPrompt ? estimateTextTokens(context.systemPrompt) : 0) + estimateToolsTokens(context.tools);\n\n\treturn {\n\t\ttokens: estimate.tokens + prefixTokens,\n\t\tusageTokens: estimate.usageTokens,\n\t\ttrailingTokens: estimate.trailingTokens + prefixTokens,\n\t\tlastUsageIndex: estimate.lastUsageIndex,\n\t};\n}\n","import { Type, type Static } from \"typebox\";\nimport type * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { estimateContextTokens } from \"../utils/estimate.ts\";\n\nexport const CacheRetention = Type.Union([Type.Literal(\"none\"), Type.Literal(\"short\"), Type.Literal(\"long\")]);\nexport type CacheRetention = Static<typeof CacheRetention>;\n\nexport const GenerationOptions = Type.Object({\n\tmaxTokens: Type.Optional(Type.Number()),\n\ttemperature: Type.Optional(Type.Number()),\n\tcacheRetention: Type.Optional(CacheRetention),\n});\n\nexport const HelperOptions = Type.Object({\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tsessionId: Type.Optional(Type.String()),\n\tapiKey: Type.Optional(Type.String()),\n\ttimeoutMs: Type.Optional(Type.Number()),\n\t/** Abort a stream that goes this long without a chunk, so a dead connection fails instead of waiting out `timeoutMs`. */\n\tidleTimeoutMs: Type.Optional(Type.Number()),\n\tmaxRetries: Type.Optional(Type.Number()),\n\tsignal: Type.Optional(Type.Unsafe<AbortSignal>({})),\n\tonPayload: Type.Optional(\n\t\tType.Unsafe<(payload: unknown, model: Model.TModel<Model.KnownProviderEnum>) => Promise<unknown>>({}),\n\t),\n\tmetadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n});\n\nexport const ThinkingBudgets = Model.ThinkingBudgets;\nexport type ThinkingBudgets = Model.ThinkingBudgets;\n\nexport const SharedOptions = Type.Evaluate(Type.Intersect([GenerationOptions, HelperOptions]));\nexport type SharedOptions = Static<typeof SharedOptions>;\n\n/** Headroom left for the prompt when sizing a response against the context window. */\nconst CONTEXT_SAFETY_TOKENS = 4096;\n// The smallest ceiling OpenAI accepts (`max_output_tokens` >= 16). Below it an\n// overflowing prompt fails as an invalid parameter instead of a context overflow.\nconst MIN_MAX_TOKENS = 16;\n\n/**\n * The model's own ceiling, unless the caller named a smaller one.\n *\n * No heuristic cap here: a catalog whose `maxTokens` spans the whole context\n * window is handled by {@link clampMaxTokensToContext}, which knows what the\n * prompt actually costs and does not have to guess.\n */\nexport function applyDefaultMaxTokens<TOptions extends SharedOptions = SharedOptions>(\n\tmodel: Model.TModel<Model.KnownProviderEnum>,\n\toptions?: TOptions,\n): TOptions & Pick<SharedOptions, \"maxTokens\"> {\n\treturn {\n\t\t...options,\n\t\tmaxTokens: options?.maxTokens ?? (model.maxTokens > 0 ? model.maxTokens : undefined),\n\t} as TOptions & Pick<SharedOptions, \"maxTokens\">;\n}\n\n/**\n * Shrink a response ceiling to what is left of the context window.\n *\n * Without this a long session asks for an answer that cannot fit and takes a\n * provider overflow error instead of a shorter answer.\n */\nexport function clampMaxTokensToContext(\n\tmodel: Model.TModel<Model.KnownProviderEnum>,\n\tcontext: Message.Context,\n\tmaxTokens: number,\n): number {\n\tif (model.contextWindow <= 0) return Math.max(MIN_MAX_TOKENS, maxTokens);\n\tconst available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;\n\treturn Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));\n}\n\n/** Tokens always left for the answer when a thinking budget shares the response ceiling. */\nexport const MIN_ANSWER_TOKENS = 1024;\n\n/**\n * Default thinking budget per level, in tokens.\n *\n * Absolute rather than a fraction of `model.maxTokens`: a fraction turns one\n * \"medium\" setting into wildly different budgets across models, and a budget is\n * a property of how hard the task is, not of how large the model's ceiling is.\n */\nexport const DEFAULT_THINKING_BUDGETS = {\n\tminimal: 1024,\n\tlow: 2048,\n\tmedium: 8192,\n\thigh: 16384,\n} as const;\n\ntype BaseThinkingLevel = keyof typeof DEFAULT_THINKING_BUDGETS;\n\n/** `xhigh` and `max` fall back to `high`'s budget unless one is configured for them. */\nfunction baseThinkingLevel(level: Model.ActiveThinkingLevel): BaseThinkingLevel {\n\treturn level === \"xhigh\" || level === \"max\" ? \"high\" : level;\n}\n\nexport function thinkingBudgetForLevel(level: Model.ActiveThinkingLevel, budgets?: ThinkingBudgets): number {\n\tconst base = baseThinkingLevel(level);\n\treturn budgets?.[level] ?? budgets?.[base] ?? DEFAULT_THINKING_BUDGETS[base];\n}\n\n/** Cap a thinking budget so at least {@link MIN_ANSWER_TOKENS} remain under a shared response ceiling. */\nexport function clampThinkingBudgetToAnswerRoom(thinkingBudget: number, ceiling: number): number {\n\treturn Math.min(thinkingBudget, Math.max(0, ceiling - MIN_ANSWER_TOKENS));\n}\n\n/**\n * Fit a thinking budget and an answer inside one response ceiling.\n *\n * The caller's `maxTokens` is the room they want for the *answer*, so thinking is\n * added on top and the total is clamped to the model's ceiling. When even that\n * does not fit, the budget gives way -- never the answer.\n */\nexport function adjustMaxTokensForThinking(\n\t// Undefined means no explicit caller cap. Use the model cap and fit thinking inside it.\n\tbaseMaxTokens: number | undefined,\n\tmodelMaxTokens: number,\n\tlevel: Model.ActiveThinkingLevel,\n\tbudgets?: ThinkingBudgets,\n): { maxTokens: number; thinkingBudget: number } {\n\tlet thinkingBudget = thinkingBudgetForLevel(level, budgets);\n\tconst maxTokens =\n\t\tbaseMaxTokens === undefined ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);\n\n\tif (maxTokens <= thinkingBudget) {\n\t\tthinkingBudget = clampThinkingBudgetToAnswerRoom(thinkingBudget, maxTokens);\n\t}\n\n\treturn { maxTokens, thinkingBudget };\n}\n","import type { AnthropicLanguageModelOptions, AnthropicProviderSettings } from \"@ai-sdk/anthropic\";\nimport type { GoogleGenerativeAIProviderSettings, GoogleLanguageModelOptions } from \"@ai-sdk/google\";\nimport type { GoogleVertexProviderSettings } from \"@ai-sdk/google-vertex\";\nimport type { GoogleVertexAnthropicProviderSettings } from \"@ai-sdk/google-vertex/anthropic\";\nimport type {\n\tOpenAILanguageModelChatOptions,\n\tOpenAILanguageModelCompletionOptions,\n\tOpenAILanguageModelResponsesOptions,\n\tOpenAIProviderSettings,\n} from \"@ai-sdk/openai\";\nimport type {\n\tOpenAICompatibleLanguageModelChatOptions,\n\tOpenAICompatibleLanguageModelCompletionOptions,\n\tOpenAICompatibleProviderSettings,\n} from \"@ai-sdk/openai-compatible\";\nimport type { XaiLanguageModelResponsesOptions, XaiProviderSettings } from \"@ai-sdk/xai\";\nimport type { OpenRouterProviderOptions, OpenRouterProviderSettings } from \"@openrouter/ai-sdk-provider\";\nimport { Type, type Static } from \"typebox\";\nimport * as Model from \"../model/model.ts\";\nimport type { GitHubCopilotProviderSettings } from \"../providers/github-copilot/index.ts\";\nimport type { OpenAICodexProviderSettings } from \"../providers/openai-codex/index.ts\";\nimport type { ResponsesLanguageModelOptions } from \"../providers/responses/model.ts\";\nimport type * as Protocol from \"./protocol.ts\";\nimport { SharedOptions, ThinkingBudgets } from \"./shared.ts\";\n\nexport const Options = Type.Evaluate(\n\tType.Intersect([\n\t\tSharedOptions,\n\t\tType.Object({\n\t\t\tbaseURL: Type.Optional(Type.String()),\n\t\t\tmethod: Type.Optional(Model.APIMethodEnumSchema),\n\t\t\tmodelId: Type.Optional(Type.String()),\n\t\t\treasoning: Type.Optional(Model.ActiveThinkingLevel),\n\t\t\tthinkingBudgets: Type.Optional(ThinkingBudgets),\n\t\t\ttoolChoice: Type.Optional(Type.Any()),\n\t\t\tactiveTools: Type.Optional(Type.Array(Type.String())),\n\t\t\tfactoryOptions: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\t\t\tproviderOptions: Type.Optional(Type.Record(Type.String(), Type.Record(Type.String(), Type.Unknown()))),\n\t\t}),\n\t]),\n);\n\nexport type ProviderOptionBag = Record<string, Record<string, unknown> | undefined>;\n\n/** Caller options as the transport sees them, after protocol-level fields are merged in. */\nexport type RuntimeOptions = Options & Protocol.CommonOptions;\n\nexport type AISDKOptions<\n\tTFactoryOptions,\n\tTProviderOptions extends ProviderOptionBag = ProviderOptionBag,\n> = Protocol.CommonOptions & {\n\tbaseURL?: string;\n\tmethod?: Model.APIMethodEnum;\n\tmodelId?: string;\n\ttoolChoice?: unknown;\n\tactiveTools?: string[];\n\tfactoryOptions?: Partial<TFactoryOptions> & Record<string, unknown>;\n\tproviderOptions?: TProviderOptions & ProviderOptionBag;\n};\n\ntype OpenAILanguageOptions =\n\t| OpenAILanguageModelResponsesOptions\n\t| OpenAILanguageModelChatOptions\n\t| OpenAILanguageModelCompletionOptions;\ntype OpenAICompatibleLanguageOptions =\n\t| OpenAICompatibleLanguageModelChatOptions\n\t| OpenAICompatibleLanguageModelCompletionOptions;\n// xAI serves only the Responses API.\ntype XaiLanguageOptions = XaiLanguageModelResponsesOptions;\ntype GitHubCopilotLanguageOptions =\n\t| AnthropicLanguageModelOptions\n\t| ResponsesLanguageModelOptions\n\t| OpenAICompatibleLanguageModelChatOptions;\n\nexport type OpenAIOptions = AISDKOptions<OpenAIProviderSettings, { openai?: OpenAILanguageOptions }>;\nexport type AnthropicOptions = AISDKOptions<AnthropicProviderSettings, { anthropic?: AnthropicLanguageModelOptions }>;\nexport type GoogleOptions = AISDKOptions<GoogleGenerativeAIProviderSettings, { google?: GoogleLanguageModelOptions }>;\nexport type GoogleVertexOptions = AISDKOptions<GoogleVertexProviderSettings>;\nexport type GoogleVertexAnthropicOptions = AISDKOptions<GoogleVertexAnthropicProviderSettings>;\nexport type OpenAICompatibleOptions = AISDKOptions<\n\tOpenAICompatibleProviderSettings,\n\t{ \"openai-compatible\"?: OpenAICompatibleLanguageOptions }\n>;\nexport type OpenAICodexOptions = AISDKOptions<\n\tOpenAICodexProviderSettings,\n\t{ \"openai-codex\"?: ResponsesLanguageModelOptions }\n>;\nexport type GitHubCopilotOptions = AISDKOptions<\n\tGitHubCopilotProviderSettings,\n\t{ \"github-copilot\"?: GitHubCopilotLanguageOptions }\n>;\nexport type OpenRouterOptions = AISDKOptions<OpenRouterProviderSettings, { openrouter?: OpenRouterProviderOptions }>;\nexport type XaiOptions = AISDKOptions<XaiProviderSettings, { xai?: XaiLanguageOptions }>;\n\nexport type Options = Static<typeof Options>;\n","/**\n * @description Defines the Generic event stream class for async iteration.\n */\n\nimport type * as Event from \"../event/event.ts\";\nimport type * as Message from \"../message/message.ts\";\n\n// Implements the async iterator pattern\n// LLM output are streams of events for consuming\n// This class helps with that by acting like buffer data structure to manage the streams\n// for producer and consumer\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue: T[] = [];\n\tprivate waiting: ((value: IteratorResult<T>) => void)[] = [];\n\tprivate done = false;\n\tprivate readonly finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\tprivate readonly isComplete: (event: T) => boolean;\n\tprivate readonly extractResult: (event: T) => R;\n\n\tconstructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R) {\n\t\tthis.isComplete = isComplete;\n\t\tthis.extractResult = extractResult;\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.shift();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.push(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.shift()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.shift()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<Event.LLMMessageEvent, Message.AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n","import Type, { type TUnsafe } from \"typebox\";\n\n/**\n * `T` with every `undefined`-valued key turned into an optional key.\n */\ntype Compact<T> = {\n\t[K in keyof T as undefined extends T[K] ? never : K]: T[K];\n} & {\n\t[K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined>;\n};\n\n/**\n * Drops keys whose value is `undefined`.\n *\n * Under `exactOptionalPropertyTypes` an explicit `undefined` is not assignable to an optional\n * property, so a literal built from optional inputs has to omit the key rather than pass it\n * through. Only worth reaching for when a literal forwards many optional values at once — for a\n * handful of keys a conditional spread reads better.\n */\nexport function compact<T extends object>(value: T): Compact<T> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, entry] of Object.entries(value)) {\n\t\tif (entry !== undefined) result[key] = entry;\n\t}\n\treturn result as Compact<T>;\n}\n\n/**\n * Creates a string enum schema compatible with Google's API and other providers\n * that don't support anyOf/const patterns.\n *\n * @example\n * const OperationSchema = StringEnum([\"add\", \"subtract\", \"multiply\", \"divide\"], {\n * description: \"The operation to perform\"\n * });\n *\n * type Operation = Static<typeof OperationSchema>; // \"add\" | \"subtract\" | \"multiply\" | \"divide\"\n */\nexport function StringEnum<T extends readonly string[]>(\n\tvalues: T,\n\toptions?: { description?: string; default?: T[number] },\n): TUnsafe<T[number]> {\n\treturn Type.Unsafe<T[number]>({\n\t\ttype: \"string\",\n\t\tenum: values as any,\n\t\t...(options?.description && { description: options.description }),\n\t\t...(options?.default && { default: options.default }),\n\t});\n}\n","/*\n * @file What a turn actually costs, as opposed to what it was asked to cost.\n *\n * Two pricing inputs are only knowable once the provider answers: the service\n * tier a request was *served* at, which may differ from the one requested, and\n * the retention split of Anthropic cache writes, which are billed at different\n * rates. Both arrive as provider metadata, so both are read here rather than in\n * the transport.\n */\n\nimport * as Model from \"../model/model.ts\";\n\n/** Protocols that price a request by the OpenAI service tier it was served at. */\nconst SERVICE_TIER_KEYS = new Set([\"openai\", \"openai-codex\"]);\n\nfunction asString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction bag(value: unknown, key: string): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null) return undefined;\n\tconst nested = (value as Record<string, unknown>)[key];\n\treturn typeof nested === \"object\" && nested !== null ? (nested as Record<string, unknown>) : undefined;\n}\n\n/** The tier the request asked for, before the provider says which one it used. */\nexport function requestedServiceTier(\n\tmodel: Model.Info,\n\toptions: { readonly factoryOptions?: Record<string, unknown> },\n\tproviderOptions: Record<string, Record<string, unknown> | undefined>,\n): string | undefined {\n\tconst key = Model.optionsKey(model);\n\tif (!SERVICE_TIER_KEYS.has(key)) return undefined;\n\treturn asString(\n\t\tproviderOptions[key]?.serviceTier ?? options.factoryOptions?.serviceTier ?? model.options?.serviceTier,\n\t);\n}\n\n/**\n * The tier the response was actually served at, which is what gets billed.\n *\n * A `\"default\"` response to an explicit flex or priority request still bills at\n * the requested tier: the Codex backend reports the fallback it used, not the\n * rate it charged.\n */\nexport function servedServiceTier(\n\tmodel: Model.Info,\n\trequested: string | undefined,\n\tproviderMetadata: unknown,\n): string | undefined {\n\tconst key = Model.optionsKey(model);\n\tif (!SERVICE_TIER_KEYS.has(key)) return undefined;\n\tconst served = asString(bag(providerMetadata, key)?.serviceTier);\n\tif (key === \"openai-codex\" && served === \"default\" && (requested === \"flex\" || requested === \"priority\")) {\n\t\treturn requested;\n\t}\n\treturn served ?? requested;\n}\n\nexport function serviceTierCostMultiplier(model: Model.Info, serviceTier: string | undefined): number {\n\treturn serviceTier === undefined ? 1 : (model.cost.serviceTierMultipliers?.[serviceTier] ?? 1);\n}\n\n/**\n * Tokens Anthropic wrote with 1h retention, out of the total cache write.\n *\n * The AI SDK does not model the split, but it passes Anthropic's raw usage object\n * through untouched, so read it from there.\n */\nexport function cacheWrite1hTokens(providerMetadata: unknown): number | undefined {\n\tfor (const key of [\"anthropic\", \"google-vertex-anthropic\"]) {\n\t\tconst creation = bag(bag(bag(providerMetadata, key), \"usage\"), \"cache_creation\");\n\t\tconst tokens = creation?.ephemeral_1h_input_tokens;\n\t\tif (typeof tokens === \"number\") return tokens;\n\t}\n\treturn undefined;\n}\n\nexport * as Pricing from \"./pricing.ts\";\n","import type { LanguageModel } from \"ai\";\nimport * as Model from \"../model/model.ts\";\nimport type { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { loadProviderFactory, packageForModel, resolveLanguageModel } from \"./registry.ts\";\nimport { getEnvApiKey, mergeHeaders } from \"./runtime.ts\";\n\nfunction cleanHeaders(headers: Record<string, string | null>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value !== null) result[key] = value;\n\t}\n\treturn result;\n}\n\nfunction resolveBaseURL(model: Model.Info, options: Options): string | undefined {\n\treturn (options.baseURL ?? model.api?.url ?? model.baseUrl) || undefined;\n}\n\n/**\n * Inject a thinking-token budget the AI SDK has no field for.\n *\n * `@ai-sdk/openai-compatible` validates provider options against a closed schema,\n * so an endpoint-specific budget field cannot travel that way. `transformRequestBody`\n * is the SDK's own hook for exactly this: the last edit before the body is sent.\n */\nexport function thinkingTokenBudgetTransform(\n\tfield: string,\n\tbudget: number,\n\texisting: unknown,\n): (body: Record<string, unknown>) => Record<string, unknown> {\n\tconst chain =\n\t\ttypeof existing === \"function\"\n\t\t\t? (existing as (body: Record<string, unknown>) => Record<string, unknown>)\n\t\t\t: undefined;\n\treturn (body) => {\n\t\tconst transformed = chain ? chain(body) : body;\n\t\treturn { ...transformed, [field]: budget };\n\t};\n}\n\nexport async function resolveAISDKLanguageModel(\n\tmodel: Model.Info,\n\toptions: Options,\n\tthinkingTokenBudget?: number,\n): Promise<LanguageModel> {\n\tconst npm = packageForModel(model);\n\tconst createProvider = await loadProviderFactory(npm);\n\tconst apiKey = options.apiKey ?? getEnvApiKey(model.provider);\n\tconst headers = cleanHeaders(mergeHeaders(model.headers, options.headers));\n\tconst baseURL = resolveBaseURL(model, options);\n\n\tconst factoryOptions: Record<string, unknown> = {\n\t\t...model.options,\n\t\t...options.factoryOptions,\n\t};\n\n\tif (apiKey) factoryOptions.apiKey = apiKey;\n\tif (Object.keys(headers).length > 0) factoryOptions.headers = headers;\n\tif (baseURL) factoryOptions.baseURL = baseURL;\n\n\tif (npm === \"@ai-sdk/openai-compatible\") {\n\t\tif (!baseURL) {\n\t\t\tthrow new Protocol.ProtocolAuthError({\n\t\t\t\tprotocol: model.protocol,\n\t\t\t\tmessage: \"AI SDK openai-compatible transport requires model.baseUrl, model.api.url, or options.baseURL\",\n\t\t\t});\n\t\t}\n\t\tfactoryOptions.name ??= model.provider.id;\n\t\tfactoryOptions.includeUsage ??= true;\n\n\t\tconst budgetField = Model.thinkingTokenBudgetField(model);\n\t\tif (budgetField && thinkingTokenBudget !== undefined && thinkingTokenBudget > 0) {\n\t\t\tfactoryOptions.transformRequestBody = thinkingTokenBudgetTransform(\n\t\t\t\tbudgetField,\n\t\t\t\tthinkingTokenBudget,\n\t\t\t\tfactoryOptions.transformRequestBody,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst cacheDisabled =\n\t\toptions.cacheRetention === \"none\" ||\n\t\t(typeof process !== \"undefined\" && process.env.CODEWORK_CACHE_RETENTION === \"none\");\n\t// Our own Responses model (Codex, Copilot `/responses`) reads image support from compat.\n\tconst responsesCompat = () => ({\n\t\t...model.compat,\n\t\tsupportsImages: model.input.includes(\"image\"),\n\t\t...(typeof factoryOptions.compat === \"object\" && factoryOptions.compat !== null ? factoryOptions.compat : {}),\n\t});\n\n\tif (npm === \"@codeworksh/ai-sdk-openai-codex\") {\n\t\t// Codex uses the session id for the session-id header and prompt cache key.\n\t\tif (options.sessionId && !cacheDisabled) factoryOptions.sessionId ??= options.sessionId;\n\t\tfactoryOptions.compat = responsesCompat();\n\t}\n\n\tif (npm === \"@codeworksh/ai-sdk-github-copilot\") {\n\t\t// Copilot uses the session id for X-Interaction-Id request grouping, and as the\n\t\t// Responses prompt cache key.\n\t\tif (options.sessionId) factoryOptions.sessionId ??= options.sessionId;\n\t\tif (options.sessionId && !cacheDisabled) factoryOptions.promptCacheKey ??= options.sessionId;\n\t\tfactoryOptions.compat = responsesCompat();\n\n\t\tconst budgetField = Model.thinkingTokenBudgetField(model);\n\t\tif (budgetField && thinkingTokenBudget !== undefined && thinkingTokenBudget > 0) {\n\t\t\tfactoryOptions.transformRequestBody = thinkingTokenBudgetTransform(\n\t\t\t\tbudgetField,\n\t\t\t\tthinkingTokenBudget,\n\t\t\t\tfactoryOptions.transformRequestBody,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst provider = createProvider(factoryOptions);\n\treturn resolveLanguageModel(provider, model, options.method);\n}\n","/*\n * @file How a thinking level becomes a budget, a ceiling, and provider options.\n *\n * Every provider spells reasoning differently -- an effort string, a token budget,\n * a level -- but they all draw from the same two numbers, and those two numbers\n * are decided together because the budget and the answer share one ceiling.\n */\n\nimport * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport type { ProviderOptionBag, RuntimeOptions } from \"./options.ts\";\nimport {\n\tadjustMaxTokensForThinking,\n\tclampMaxTokensToContext,\n\tclampThinkingBudgetToAnswerRoom,\n\tthinkingBudgetForLevel,\n} from \"./shared.ts\";\n\n/**\n * The thinking budget and response ceiling for one request, resolved together.\n *\n * A budget and the answer share `model.maxTokens`, so neither can be decided\n * alone. `maxTokens` is what the request should ask for; `budget` is what fits\n * inside it once the answer keeps its floor.\n */\nexport interface Plan {\n\treadonly level: Model.ThinkingLevel;\n\t/** Fitted tokens, or Google's -1 sentinel for provider-managed dynamic thinking. */\n\treadonly budget: number;\n\treadonly maxTokens: number | undefined;\n\t/** The caller configured a budget for this level, rather than inheriting a default. */\n\treadonly explicit: boolean;\n}\n\n/** Anthropic rejects an enabled thinking block whose budget is under 1024 tokens. */\nconst ANTHROPIC_MIN_THINKING_BUDGET = 1024;\n\n/**\n * The smallest budget this model will accept, for providers that take one at all.\n *\n * Adaptive models are exempt: they are sent an effort level and no budget, so\n * there is no floor to fall under.\n */\n/** Whether the model talks Anthropic Messages — directly, or via Copilot's `/v1/messages` route. */\nexport function isAnthropicMessagesModel(model: Model.Info): boolean {\n\tconst key = Model.optionsKey(model);\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") return true;\n\treturn key === \"github-copilot\" && model.api?.method === Model.APIMethodEnum.messages;\n}\n\nfunction minimumThinkingBudget(model: Model.Info): number {\n\tif (!isAnthropicMessagesModel(model)) return 0;\n\treturn model.compat?.forceAdaptiveThinking ? 0 : ANTHROPIC_MIN_THINKING_BUDGET;\n}\n\nexport function resolvePlan(model: Model.Info, context: Message.Context, options: RuntimeOptions): Plan {\n\tconst clampToContext = (maxTokens: number | undefined) =>\n\t\tmaxTokens === undefined ? undefined : clampMaxTokensToContext(model, context, maxTokens);\n\n\tconst requested = options.reasoning;\n\tconst level = requested ? Model.clampThinkingLevel(model, requested) : \"off\";\n\tif (level === \"off\") return { level, budget: 0, maxTokens: clampToContext(options.maxTokens), explicit: false };\n\n\tconst budgets = { ...model.thinkingBudgets, ...options.thinkingBudgets };\n\tconst explicit = options.thinkingBudgets?.[level] !== undefined;\n\tconst key = Model.optionsKey(model);\n\tconst usesGoogleBudget = (key === \"google\" || key === \"google-vertex\") && !model.compat?.supportsThinkingLevel;\n\tconst requestedBudget = thinkingBudgetForLevel(level, budgets);\n\n\t// A catalog entry without a ceiling gives the fit nothing to work against.\n\tif (model.maxTokens <= 0) {\n\t\treturn { level, budget: requestedBudget, maxTokens: clampToContext(options.maxTokens), explicit };\n\t}\n\n\t// Google's -1 is a dynamic-thinking sentinel, not a negative token count.\n\tconst dynamic = usesGoogleBudget && requestedBudget === -1;\n\tconst adjusted = adjustMaxTokensForThinking(options.maxTokens, model.maxTokens, level, {\n\t\t[level]: dynamic ? 0 : requestedBudget,\n\t});\n\tconst maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);\n\n\t/*\n\t * Preserve an explicit small answer allowance when it fits, and apply the\n\t * 1024-token reserve only when context pressure reduces it, rather than always:\n\t * aikit deliberately permits small answers.\n\t */\n\tconst budget =\n\t\tmaxTokens < adjusted.maxTokens\n\t\t\t? clampThinkingBudgetToAnswerRoom(adjusted.thinkingBudget, maxTokens)\n\t\t\t: adjusted.thinkingBudget;\n\n\t/*\n\t * A budget below the provider's own floor is not a smaller amount of thinking,\n\t * it is an invalid request. When the room has gone -- a nearly full window is\n\t * the way there -- the turn goes out without thinking rather than not at all.\n\t */\n\tif (budget < minimumThinkingBudget(model)) {\n\t\treturn { level: \"off\", budget: 0, maxTokens, explicit };\n\t}\n\n\treturn { level, budget: dynamic ? -1 : budget, maxTokens, explicit };\n}\n\ntype GoogleThinkingLevel = \"minimal\" | \"low\" | \"medium\" | \"high\";\n\nfunction googleThinkingLevel(mapped: string): GoogleThinkingLevel {\n\treturn mapped === \"xhigh\" || mapped === \"max\" ? \"high\" : (mapped as GoogleThinkingLevel);\n}\n\n/**\n * Turn thinking off, in the provider's own words.\n *\n * Several models reason by default, so declining to *ask* for thinking is not the\n * same as asking for none: the caller ends up paying output tokens for reasoning\n * they never requested.\n *\n * OpenRouter is deliberately left alone. It fronts hundreds of third-party\n * endpoints whose support varies per endpoint -- several reject the request\n * outright with \"reasoning is mandatory for this endpoint and cannot be disabled\"\n * -- so its reasoning stays pass-through.\n */\nexport function disabledProviderOptions(model: Model.Info): ProviderOptionBag {\n\t// A model that cannot reason has nothing to switch off.\n\tif (!model.reasoning) return {};\n\n\tconst key = Model.optionsKey(model);\n\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\t// `null` means this model cannot disable thinking and rejects the request. It\n\t\t// reasons at the API's default effort regardless, so name that effort on the\n\t\t// wire and the response records the level the model really ran at.\n\t\tif (model.thinkingLevelMap?.off === null) return { [key]: { effort: ANTHROPIC_DEFAULT_EFFORT } };\n\t\treturn { [key]: { thinking: { type: \"disabled\" } } };\n\t}\n\n\tif (key === \"github-copilot\") {\n\t\t// Copilot accepts `thinking: {type:\"disabled\"}` on the Messages route, except for a\n\t\t// Claude that cannot disable thinking: it rejects the request, so the field is left\n\t\t// out and Copilot's default applies. On Responses only the models mapped to an off\n\t\t// effort take one, and the chat route has no reasoning control at all.\n\t\tconst off = model.thinkingLevelMap?.off;\n\t\tif (model.api?.method === Model.APIMethodEnum.messages) {\n\t\t\treturn off === null ? {} : { [key]: { thinking: { type: \"disabled\" } } };\n\t\t}\n\t\tif (model.api?.method === Model.APIMethodEnum.responses && typeof off === \"string\") {\n\t\t\treturn { [key]: { reasoningEffort: off } };\n\t\t}\n\t\treturn {};\n\t}\n\n\tif (key === \"google\" || key === \"google-vertex\") {\n\t\tif (model.thinkingLevelMap?.off === null) return {};\n\t\treturn { [key]: { thinkingConfig: googleDisabledThinkingConfig(model) } };\n\t}\n\n\tif (key === \"openai\" || key === \"xai\" || key === \"openai-codex\") {\n\t\tconst off = model.thinkingLevelMap?.off;\n\t\t// `null` means this model cannot disable reasoning; sending an effort it\n\t\t// does not accept would fail the request outright.\n\t\tif (off === null) return {};\n\t\treturn { [key]: { reasoningEffort: off ?? \"none\" } };\n\t}\n\n\treturn {};\n}\n\n/**\n * Gemini 3 Pro cannot disable thinking, and Gemini 3 Flash and Gemma 4 cannot\n * fully disable it either. For those, ask for the lowest level and leave\n * `includeThoughts` off so the thinking stays hidden. Gemini 2.x takes a zero budget.\n */\nfunction googleDisabledThinkingConfig(model: Model.Info): Record<string, unknown> {\n\tif (model.compat?.supportsThinkingLevel) return { thinkingLevel: model.thinkingLevelMap?.off ?? \"minimal\" };\n\treturn { thinkingBudget: 0 };\n}\n\ntype AnthropicEffort = \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n// TODO(sanchitrk): should we go lower here like low or medium?\n/** The effort Anthropic applies when a request names none. */\nconst ANTHROPIC_DEFAULT_EFFORT: AnthropicEffort = \"high\";\n\n/**\n * The effort level an adaptive Claude model reasons at.\n *\n * A model's own `thinkingLevelMap` wins where it has an opinion -- that is where\n * per-model support for `xhigh` and `max` is recorded -- and the rest collapse onto\n * the three levels every adaptive model accepts.\n */\nfunction anthropicEffort(model: Model.Info, level: Model.ActiveThinkingLevel): AnthropicEffort {\n\tconst mapped = model.thinkingLevelMap?.[level];\n\tif (typeof mapped === \"string\") return mapped as AnthropicEffort;\n\n\tswitch (level) {\n\t\tcase \"minimal\":\n\t\tcase \"low\":\n\t\t\treturn \"low\";\n\t\tcase \"medium\":\n\t\t\treturn \"medium\";\n\t\tcase \"xhigh\":\n\t\t\treturn \"xhigh\";\n\t\tcase \"max\":\n\t\t\treturn \"max\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\nexport function reasoningProviderOptions(model: Model.Info, plan: Plan): ProviderOptionBag {\n\tconst level = plan.level;\n\tif (level === \"off\") return disabledProviderOptions(model);\n\n\tconst mapped = model.thinkingLevelMap?.[level] ?? level;\n\tif (!mapped) return {};\n\n\tconst key = Model.optionsKey(model);\n\tconst budget = plan.budget;\n\n\tif (key === \"openai\" || key === \"xai\" || key === \"openai-codex\") {\n\t\treturn { [key]: { reasoningEffort: mapped } };\n\t}\n\n\tif (key === \"github-copilot\") {\n\t\tconst method = model.api?.method;\n\t\tif (method === Model.APIMethodEnum.responses) {\n\t\t\treturn { [key]: { reasoningEffort: mapped } };\n\t\t}\n\t\tif (method === Model.APIMethodEnum.messages) {\n\t\t\tif (model.compat?.forceAdaptiveThinking) {\n\t\t\t\treturn {\n\t\t\t\t\t[key]: {\n\t\t\t\t\t\tthinking: { type: \"adaptive\", display: \"summarized\" },\n\t\t\t\t\t\teffort: anthropicEffort(model, level),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t[key]: {\n\t\t\t\t\tthinking: {\n\t\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t\tbudgetTokens: budget,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\t// The chat route has no generic reasoning control; catalog models carry\n\t\t// `compat.supportsThinkingTokenBudget` when they take a budget field.\n\t\treturn {};\n\t}\n\n\tif (key === \"openrouter\") {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\treasoning: {\n\t\t\t\t\teffort: mapped === \"off\" ? \"none\" : mapped,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (key === \"google\" || key === \"google-vertex\") {\n\t\tconst thinkingLevel = googleThinkingLevel(mapped);\n\t\t// Gemini 3 and Gemma 4 take a level; earlier families take a token budget.\n\t\tif (model.compat?.supportsThinkingLevel) {\n\t\t\treturn { [key]: { thinkingConfig: { thinkingLevel, includeThoughts: true } } };\n\t\t}\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinkingConfig: {\n\t\t\t\t\tincludeThoughts: true,\n\t\t\t\t\tthinkingBudget: budget,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\t// Newer Claude models size their own thinking from an effort level. Handing\n\t\t// them a fixed budget pins every turn to one depth instead.\n\t\tif (model.compat?.forceAdaptiveThinking) {\n\t\t\treturn {\n\t\t\t\t[key]: {\n\t\t\t\t\tthinking: { type: \"adaptive\", display: \"summarized\" },\n\t\t\t\t\teffort: anthropicEffort(model, level),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinking: {\n\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t// Already fitted under `plan.maxTokens` with the answer floor reserved.\n\t\t\t\t\t// Re-clamping here would reserve that floor a second time.\n\t\t\t\t\tbudgetTokens: budget,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {};\n}\n\n/**\n * The provider-native thinking value a request carried, read off the exact body the\n * adapter sent. Adapters drop efforts they believe a model rejects, so the options\n * aikit hands them can say more than the wire did.\n */\nexport function providerThinkingLevel(body: unknown): string | undefined {\n\tconst value =\n\t\tfield(body, \"reasoning\", \"effort\") ??\n\t\tfield(body, \"reasoning_effort\") ??\n\t\tfield(body, \"generationConfig\", \"thinkingConfig\", \"thinkingLevel\") ??\n\t\t// An effort sent alongside disabled thinking only shapes the answer; it is not a thinking level.\n\t\t(field(body, \"thinking\", \"type\") === \"disabled\" ? undefined : field(body, \"output_config\", \"effort\"));\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction field(value: unknown, ...keys: string[]): unknown {\n\treturn keys.reduce<unknown>(\n\t\t(at, key) => (typeof at === \"object\" && at !== null ? (at as Record<string, unknown>)[key] : undefined),\n\t\tvalue,\n\t);\n}\n\nexport * as Thinking from \"./thinking.ts\";\n","/**\n * @description Helper function to parse partial jsons during LLM streaming.\n */\n\nimport { parse as partialParse } from \"partial-json\";\n\n/**\n * Attempts to parse potentially incomplete JSON during streaming.\n * Always returns a valid object, even if the JSON is incomplete.\n *\n * @param partialJson The partial JSON string from streaming\n * @returns Parsed object or empty object if parsing fails\n */\nexport function parseStreamingJson<T = any>(partialJson: string | undefined): T {\n\tif (!partialJson || partialJson.trim() === \"\") {\n\t\treturn {} as T;\n\t}\n\n\t// Try standard parsing first (fastest for complete JSON)\n\ttry {\n\t\treturn JSON.parse(partialJson) as T;\n\t} catch {\n\t\tconst repaired = repairInvalidJsonStringContent(partialJson);\n\t\tif (repaired !== partialJson) {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(repaired) as T;\n\t\t\t} catch {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = partialParse(repaired);\n\t\t\t\t\treturn (result ?? {}) as T;\n\t\t\t\t} catch {\n\t\t\t\t\t// Fall through to the original partial parser.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Try partial-json for incomplete JSON\n\t\ttry {\n\t\t\tconst result = partialParse(partialJson);\n\t\t\treturn (result ?? {}) as T;\n\t\t} catch {\n\t\t\t// If all parsing fails, return empty object\n\t\t\treturn {} as T;\n\t\t}\n\t}\n}\n\nfunction repairInvalidJsonStringContent(input: string): string {\n\tlet output = \"\";\n\tlet inString = false;\n\tlet escaping = false;\n\n\tfor (const char of input) {\n\t\tif (!inString) {\n\t\t\toutput += char;\n\t\t\tif (char === '\"') inString = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (escaping) {\n\t\t\tif (`\"\\\\/bfnrtu`.includes(char)) {\n\t\t\t\toutput += `\\\\${char}`;\n\t\t\t} else {\n\t\t\t\toutput += `\\\\\\\\${char}`;\n\t\t\t}\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"\\\\\") {\n\t\t\tescaping = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tinString = false;\n\t\t\toutput += char;\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (char) {\n\t\t\tcase \"\\b\":\n\t\t\t\toutput += \"\\\\b\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\f\":\n\t\t\t\toutput += \"\\\\f\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\n\":\n\t\t\t\toutput += \"\\\\n\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\r\":\n\t\t\t\toutput += \"\\\\r\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\t\":\n\t\t\t\toutput += \"\\\\t\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput += char;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (escaping) output += \"\\\\\\\\\";\n\treturn output;\n}\n","/**\n * Removes unpaired Unicode surrogate characters from a string.\n *\n * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF,\n * or vice versa) cause JSON serialization errors in many API providers.\n *\n * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired\n * surrogates and will NOT be affected by this function.\n *\n * @param text - The text to sanitize\n * @returns The sanitized text with unpaired surrogates removed\n *\n * @example\n * // Valid emoji (properly paired surrogates) are preserved\n * sanitizeSurrogates(\"Hello 🙈 World\") // => \"Hello 🙈 World\"\n *\n * // Unpaired high surrogate is removed\n * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low\n * sanitizeSurrogates(`Text ${unpaired} here`) // => \"Text here\"\n */\nexport function sanitizeSurrogates(text: string): string {\n\t// Replace unpaired high surrogates (0xD800-0xDBFF not followed by low surrogate)\n\t// Replace unpaired low surrogates (0xDC00-0xDFFF not preceded by high surrogate)\n\treturn text.replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, \"\");\n}\n","import type * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\n\ntype JsonSchemaObject = Record<string, unknown> & {\n\tproperties?: Record<string, unknown>;\n\trequired?: unknown;\n};\n\nclass UnsupportedStrictSchemaError extends Error {}\n\n/** True when a provider's strict mode rejects this schema keyword with this value. */\ntype UnsupportedKeyword = (key: string, value: unknown) => boolean;\n\nconst UNSUPPORTED_KEYWORDS = [\n\t\"$ref\",\n\t\"$defs\",\n\t\"definitions\",\n\t\"allOf\",\n\t\"oneOf\",\n\t\"patternProperties\",\n\t\"dependentSchemas\",\n\t\"dependencies\",\n\t\"unevaluatedProperties\",\n\t\"propertyNames\",\n\t\"contains\",\n\t\"prefixItems\",\n\t\"not\",\n\t\"if\",\n\t\"then\",\n\t\"else\",\n] as const;\n\n// Anthropic strict tool use rejects these with a 400 for the whole request.\n// https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations\nconst ANTHROPIC_UNSUPPORTED_KEYWORDS = new Set([\n\t\"minimum\",\n\t\"maximum\",\n\t\"exclusiveMinimum\",\n\t\"exclusiveMaximum\",\n\t\"multipleOf\",\n\t\"maxItems\",\n\t\"uniqueItems\",\n\t\"minContains\",\n\t\"maxContains\",\n\t\"minProperties\",\n\t\"maxProperties\",\n]);\nconst ANTHROPIC_STRING_FORMATS = new Set([\n\t\"date-time\",\n\t\"time\",\n\t\"date\",\n\t\"duration\",\n\t\"email\",\n\t\"hostname\",\n\t\"uri\",\n\t\"ipv4\",\n\t\"ipv6\",\n\t\"uuid\",\n]);\n\nconst isAnthropicUnsupportedKeyword: UnsupportedKeyword = (key, value) => {\n\tif (ANTHROPIC_UNSUPPORTED_KEYWORDS.has(key)) return true;\n\tif (key === \"minItems\") return value !== 0 && value !== 1;\n\tif (key === \"format\") return typeof value !== \"string\" || !ANTHROPIC_STRING_FORMATS.has(value);\n\treturn false;\n};\n\nfunction isJsonSchemaObject(value: unknown): value is JsonSchemaObject {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNullSchema(schema: unknown): boolean {\n\treturn isJsonSchemaObject(schema) && schema.type === \"null\";\n}\n\n/** `X` of an `anyOf: [X, null]` schema. */\nexport function nullableVariant(schema: unknown): unknown {\n\tif (!isJsonSchemaObject(schema) || !Array.isArray(schema.anyOf)) return;\n\tconst variants = schema.anyOf.filter((variant) => !isNullSchema(variant));\n\treturn variants.length === 1 ? variants[0] : undefined;\n}\n\nfunction isStructuredSchema(schema: unknown): boolean {\n\tif (!isJsonSchemaObject(schema)) return false;\n\tconst types = typeof schema.type === \"string\" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];\n\treturn (\n\t\ttypes.includes(\"object\") ||\n\t\ttypes.includes(\"array\") ||\n\t\tschema.properties !== undefined ||\n\t\tschema.items !== undefined\n\t);\n}\n\nconst CONSTRAINING_KEYWORDS = [\n\t\"type\",\n\t\"const\",\n\t\"enum\",\n\t\"anyOf\",\n\t\"allOf\",\n\t\"oneOf\",\n\t\"not\",\n\t\"$ref\",\n\t\"properties\",\n\t\"items\",\n];\n\nexport function schemaAllowsNull(schema: unknown): boolean {\n\tif (schema === true) return true;\n\tif (!isJsonSchemaObject(schema)) return false;\n\tif (CONSTRAINING_KEYWORDS.every((key) => schema[key] === undefined)) return true;\n\tif (schema.type === \"null\" || (Array.isArray(schema.type) && schema.type.includes(\"null\"))) return true;\n\tif (schema.const === null || (Array.isArray(schema.enum) && schema.enum.includes(null))) return true;\n\treturn Array.isArray(schema.anyOf) && schema.anyOf.some((variant) => schemaAllowsNull(variant));\n}\n\nfunction makeNodeStrict(schema: unknown, isUnsupportedKeyword?: UnsupportedKeyword): void {\n\tif (!isJsonSchemaObject(schema)) throw new UnsupportedStrictSchemaError(\"boolean schemas are unsupported\");\n\tfor (const key of UNSUPPORTED_KEYWORDS) {\n\t\tif (schema[key] !== undefined) throw new UnsupportedStrictSchemaError(`${key} schemas are unsupported`);\n\t}\n\tif (isUnsupportedKeyword) {\n\t\tfor (const [key, value] of Object.entries(schema)) {\n\t\t\tif (isUnsupportedKeyword(key, value)) {\n\t\t\t\tthrow new UnsupportedStrictSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (schema.anyOf !== undefined) {\n\t\tif (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) {\n\t\t\tthrow new UnsupportedStrictSchemaError(\"anyOf must contain at least one schema\");\n\t\t}\n\t\t// `[X, null]` is the nullable shape this transform itself emits; only real unions of structures are rejected.\n\t\tconst nullable = nullableVariant(schema) !== undefined;\n\t\tfor (const variant of schema.anyOf) {\n\t\t\tif (!nullable && isStructuredSchema(variant)) {\n\t\t\t\tthrow new UnsupportedStrictSchemaError(\"object and array unions are unsupported\");\n\t\t\t}\n\t\t\tmakeNodeStrict(variant, isUnsupportedKeyword);\n\t\t}\n\t}\n\n\tif (schema.items !== undefined) {\n\t\tif (Array.isArray(schema.items)) throw new UnsupportedStrictSchemaError(\"tuple schemas are unsupported\");\n\t\tmakeNodeStrict(schema.items, isUnsupportedKeyword);\n\t}\n\n\tconst isObjectSchema = schema.type === \"object\";\n\tif (schema.properties !== undefined && !isObjectSchema) {\n\t\tthrow new UnsupportedStrictSchemaError(\"properties require type object\");\n\t}\n\tif (!isObjectSchema) return;\n\t// Effect Schema emits `additionalProperties: true` for every struct; excess keys are dropped on decode, so\n\t// closing the object loses nothing. Only schema-valued additionalProperties carries meaning.\n\tif (schema.additionalProperties !== undefined && typeof schema.additionalProperties !== \"boolean\") {\n\t\tthrow new UnsupportedStrictSchemaError(\"schema-valued additionalProperties is unsupported\");\n\t}\n\tif (schema.properties !== undefined && !isJsonSchemaObject(schema.properties)) {\n\t\tthrow new UnsupportedStrictSchemaError(\"object properties must be a schema map\");\n\t}\n\tif (\n\t\tschema.required !== undefined &&\n\t\t(!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== \"string\"))\n\t) {\n\t\tthrow new UnsupportedStrictSchemaError(\"object required must be a string array\");\n\t}\n\n\tconst properties = schema.properties ?? {};\n\tconst propertyNames = Object.keys(properties);\n\tconst required = new Set(Array.isArray(schema.required) ? schema.required : []);\n\tif ([...required].some((key) => !propertyNames.includes(key))) {\n\t\tthrow new UnsupportedStrictSchemaError(\"required contains an unknown property\");\n\t}\n\tfor (const [key, property] of Object.entries(properties)) {\n\t\tmakeNodeStrict(property, isUnsupportedKeyword);\n\t\tif (!required.has(key) && !schemaAllowsNull(property)) {\n\t\t\tproperties[key] = { anyOf: [property, { type: \"null\" }] };\n\t\t}\n\t}\n\tschema.required = propertyNames;\n\tschema.additionalProperties = false;\n}\n\n/**\n * Convert a tool's parameter schema to the subset strict constrained sampling accepts: every object closed and\n * every property required, with formerly optional properties made nullable. Callers strip those nulls again\n * before validation (see `normalizeOptionalNulls`).\n */\nfunction makeStrictJsonSchema(schema: unknown, isUnsupportedKeyword?: UnsupportedKeyword): Record<string, unknown> {\n\tconst cloned: unknown = structuredClone(schema);\n\tif (!isJsonSchemaObject(cloned) || cloned.type !== \"object\") {\n\t\tthrow new UnsupportedStrictSchemaError(\"root schema must have type object\");\n\t}\n\tmakeNodeStrict(cloned, isUnsupportedKeyword);\n\treturn cloned;\n}\n\n/**\n * The strict parameter schema to send for a JSON-schema constrained tool, or `undefined` to send it non-strict.\n * A `\"prefer\"` tool whose schema the model's strict mode cannot express falls back to non-strict; a `\"require\"`\n * tool throws instead. `preferNonStrict` sends every `\"prefer\"` tool non-strict.\n */\nexport function resolveStrictParameters(\n\ttool: Message.Tool,\n\tmodel?: Pick<Model.Info, \"protocol\" | \"compat\">,\n\tpreferNonStrict = false,\n): Record<string, unknown> | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config || config.type !== \"json_schema\") return;\n\tif (preferNonStrict && config.strict === \"prefer\") return;\n\n\tif (model?.compat?.supportsStrictMode ?? true) {\n\t\tconst isAnthropic =\n\t\t\tmodel?.protocol === Model.KnownProviderEnum.anthropic ||\n\t\t\tmodel?.protocol === Model.KnownProviderEnum.googleVertexAnthropic;\n\t\ttry {\n\t\t\treturn makeStrictJsonSchema(tool.parameters, isAnthropic ? isAnthropicUnsupportedKeyword : undefined);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof UnsupportedStrictSchemaError)) throw error;\n\t\t\tif (config.strict !== \"require\") return;\n\t\t\tthrow new Error(`tool \"${tool.name}\" requires JSON-schema constrained sampling, but ${error.message}.`);\n\t\t}\n\t}\n\tif (config.strict === \"require\") {\n\t\tthrow new Error(\n\t\t\t`tool \"${tool.name}\" requires JSON-schema constrained sampling, but strict tools are unsupported.`,\n\t\t);\n\t}\n}\n","import {\n\tjsonSchema,\n\ttype AssistantModelMessage,\n\ttype FinishReason,\n\ttype LanguageModelUsage,\n\ttype ModelMessage,\n\ttype TextStreamPart,\n\ttype ToolModelMessage,\n\ttype ToolSet,\n\ttype UserModelMessage,\n} from \"ai\";\nimport type { LanguageModelV3FunctionTool, SharedV3ProviderOptions } from \"@ai-sdk/provider\";\nimport * as Message from \"../message/message.ts\";\nimport * as Transcript from \"../message/transcript.ts\";\nimport { Pricing } from \"./pricing.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { resolveToolGrammar, type ResponsesToolChange } from \"../providers/responses/tools.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/jsonparse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize.ts\";\nimport { packageForModel, resolveMethod } from \"./registry.ts\";\nimport { resolveStrictParameters } from \"./strict.ts\";\nimport { isAnthropicMessagesModel } from \"./thinking.ts\";\n\ntype ToolCallPart = Extract<Message.AssistantMessage[\"parts\"][number], { type: \"toolCall\" }>;\ntype TerminalToolCall = Exclude<ToolCallPart, Message.ToolCallPendingPart | Message.ToolCallRunningPart>;\n\nexport function createAssistantMessage(\n\tmodel: Model.Info,\n\tthinkingLevel: Model.ThinkingLevel,\n): Message.AssistantMessage {\n\treturn Message.createAssistantMessage({\n\t\trole: \"assistant\",\n\t\tparts: [],\n\t\tprotocol: model.protocol,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tthinkingLevel,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\ttime: {\n\t\t\tcreated: Date.now(),\n\t\t\tcompleted: Date.now(),\n\t\t},\n\t});\n}\n\nfunction userContent(parts: Message.UserMessage[\"parts\"]): ModelMessage[] {\n\tconst content: Exclude<UserModelMessage[\"content\"], string> = [];\n\tfor (const part of parts) {\n\t\tif (part.type === \"text\") {\n\t\t\tconst text = sanitizeSurrogates(part.text);\n\t\t\tif (text.trim().length > 0) {\n\t\t\t\tcontent.push({ type: \"text\", text });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcontent.push({ type: \"file\", data: part.data, mediaType: part.mimeType });\n\t}\n\n\tif (content.length === 0) return [];\n\treturn [{ role: \"user\", content }];\n}\n\nfunction sanitizeValue(value: unknown): unknown {\n\tif (typeof value === \"string\") return sanitizeSurrogates(value);\n\tif (Array.isArray(value)) return value.map((item) => sanitizeValue(item));\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, item] of Object.entries(value)) {\n\t\t\tresult[key] = sanitizeValue(item);\n\t\t}\n\t\treturn result;\n\t}\n\treturn value;\n}\n\nfunction sanitizeRecord(value: Record<string, unknown>): Record<string, unknown> {\n\treturn sanitizeValue(value) as Record<string, unknown>;\n}\n\nconst ERROR_TOOL_IMAGE_PLACEHOLDER = \"(image attached after the tool results)\";\nconst MOVED_TOOL_IMAGE_PLACEHOLDER = \"(see attached image)\";\nconst CHAT_TOOL_IMAGES_CAPTION = \"Attached image(s) from tool result:\";\nconst GEMINI_TOOL_IMAGES_CAPTION = \"Tool result image:\";\n\n/**\n * Where a tool result's images go when the wire cannot carry them inside the result. Each case\n * sends them in a user message after the turn's tool results:\n * - `anthropicError`: Anthropic rejects images in error tool results.\n * - `chat`: Chat Completions adapters serialize tool result images as JSON text.\n * - `gemini`: before Gemini 3 (and for non-Gemini models), an image-only result loses its function response.\n */\ntype MovedImages = \"anthropicError\" | \"chat\" | \"gemini\";\n\nconst COPILOT = \"@codeworksh/ai-sdk-github-copilot\";\n\nexport function isAnthropicWire(model: Model.Info, method: Model.APIMethodEnum): boolean {\n\tif (packageForModel(model) === COPILOT) return method === Model.APIMethodEnum.messages;\n\treturn isAnthropicMessagesModel(model);\n}\n\n/** Whether the model runs on our own Responses transport: Codex, and Copilot's `/responses`. */\nexport function isOwnResponses(model: Model.Info, methodOverride?: Model.APIMethodEnum): boolean {\n\tif (model.protocol === Model.KnownProviderEnum.openaiCodex) return true;\n\treturn (\n\t\tmodel.protocol === Model.KnownProviderEnum.githubCopilot &&\n\t\tresolveMethod(model, methodOverride) === Model.APIMethodEnum.responses\n\t);\n}\n\nfunction isChatCompletions(model: Model.Info, method: Model.APIMethodEnum): boolean {\n\tconst npm = packageForModel(model);\n\t// The compatible adapter falls back to its chat model for every other method.\n\tif (npm === \"@ai-sdk/openai-compatible\") return true;\n\tif (npm === COPILOT) return method !== Model.APIMethodEnum.responses && method !== Model.APIMethodEnum.messages;\n\treturn npm === \"@ai-sdk/openai\" && method === Model.APIMethodEnum.chat;\n}\n\n/** The Google adapter's own split: anything but Gemini 3 and later gets the legacy function response. */\nfunction isLegacyGoogleToolResults(model: Model.Info): boolean {\n\tif (model.protocol !== Model.KnownProviderEnum.google && model.protocol !== Model.KnownProviderEnum.googleVertex) {\n\t\treturn false;\n\t}\n\tconst id = model.api?.id ?? model.id;\n\tconst gemini = /(^|[/.])gemini-/i.test(id);\n\tconst legacy =\n\t\t/(^|[/.])gemini-[12](?:[.-]|$)/i.test(id) ||\n\t\t/(^|[/.])gemini-pro(?:-vision)?$/i.test(id) ||\n\t\t/(^|[/.])gemini-robotics-er-1\\.5(?:[.-]|$)/i.test(id);\n\treturn !gemini || legacy;\n}\n\nfunction movedImages(\n\ttoolCall: TerminalToolCall,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum,\n): MovedImages | undefined {\n\tif (!toolCall.result.content.some((content) => content.type === \"image\")) return;\n\tif (isAnthropicWire(model, method)) return toolCall.result.isError ? \"anthropicError\" : undefined;\n\tif (isChatCompletions(model, method)) return \"chat\";\n\tif (isLegacyGoogleToolResults(model)) return \"gemini\";\n}\n\nfunction toolResultOutput(toolCall: TerminalToolCall, moved: MovedImages | undefined) {\n\tconst content =\n\t\tmoved === \"anthropicError\"\n\t\t\t? Message.omitImages(toolCall.result.content, ERROR_TOOL_IMAGE_PLACEHOLDER)\n\t\t\t: moved\n\t\t\t\t? toolCall.result.content.filter((content) => content.type === \"text\")\n\t\t\t\t: toolCall.result.content;\n\tconst joined = content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => sanitizeSurrogates(content.text))\n\t\t.join(\"\\n\");\n\tconst text =\n\t\tmoved && moved !== \"anthropicError\" && joined.trim().length === 0 ? MOVED_TOOL_IMAGE_PLACEHOLDER : joined;\n\tconst images = content.filter((content) => content.type === \"image\");\n\n\t// The AI SDK's content output has no error flag, so other providers keep the images and lose\n\t// the flag: Google drops its `error` key, OpenAI-family wires have no flag to lose.\n\tif (toolCall.result.isError && images.length === 0) {\n\t\treturn {\n\t\t\ttype: \"error-text\" as const,\n\t\t\tvalue: text || \"tool returned an error\",\n\t\t};\n\t}\n\n\tif (images.length === 0) {\n\t\treturn {\n\t\t\ttype: \"text\" as const,\n\t\t\tvalue: text,\n\t\t};\n\t}\n\n\treturn {\n\t\ttype: \"content\" as const,\n\t\tvalue: [\n\t\t\t...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n\t\t\t...images.map((image) => ({\n\t\t\t\ttype: \"file\" as const,\n\t\t\t\tdata: { type: \"data\" as const, data: image.data },\n\t\t\t\tmediaType: image.mimeType,\n\t\t\t})),\n\t\t],\n\t};\n}\n\nfunction normalizeOpenAICodexIdPart(value: string): string {\n\treturn value\n\t\t.replace(/[^a-zA-Z0-9_-]/g, \"_\")\n\t\t.slice(0, 64)\n\t\t.replace(/_+$/, \"\");\n}\n\nexport function normalizeOpenAICodexToolCallId(\n\tid: string,\n\tmodel: Model.Info,\n\tsource: Message.AssistantMessage,\n): string {\n\tif (!id.includes(\"|\")) return normalizeOpenAICodexIdPart(id);\n\tconst [callId, itemId = \"\"] = id.split(\"|\");\n\tconst normalizedCallId = normalizeOpenAICodexIdPart(callId ?? \"\");\n\tconst isForeignToolCall = source.provider.id !== model.provider.id || source.protocol !== model.protocol;\n\tlet normalizedItemId = isForeignToolCall ? `fc_${shortHash(itemId)}` : normalizeOpenAICodexIdPart(itemId);\n\tif (!normalizedItemId.startsWith(\"fc_\") && !normalizedItemId.startsWith(\"ctc_\")) {\n\t\tnormalizedItemId = normalizeOpenAICodexIdPart(`fc_${normalizedItemId}`);\n\t}\n\treturn `${normalizedCallId}|${normalizedItemId}`;\n}\n\n/**\n * OpenAI (`call_id`, at most 64 characters), Anthropic (`^[a-zA-Z0-9_-]+$`) and\n * OpenRouter upstreams take a foreign tool call ID verbatim, so a Codex\n * `call|item` ID keeps only its unique call half.\n */\nexport function normalizeForeignToolCallId(id: string): string {\n\tif (/^[a-zA-Z0-9_-]{1,64}$/.test(id)) return id;\n\treturn normalizeOpenAICodexIdPart(id.split(\"|\")[0] ?? id);\n}\n\nfunction toolCallIdNormalizer(model: Model.Info, method: Model.APIMethodEnum) {\n\tif (isOwnResponses(model, method)) return normalizeOpenAICodexToolCallId;\n\tswitch (model.protocol) {\n\t\tcase Model.KnownProviderEnum.openaiCodex:\n\t\t\treturn normalizeOpenAICodexToolCallId;\n\t\tcase Model.KnownProviderEnum.openai:\n\t\tcase Model.KnownProviderEnum.anthropic:\n\t\tcase Model.KnownProviderEnum.googleVertexAnthropic:\n\t\tcase Model.KnownProviderEnum.openrouter:\n\t\t\treturn normalizeForeignToolCallId;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\ntype OpenAIReasoningMetadata = {\n\titemId: string;\n\treasoningEncryptedContent?: string | null;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function encodeOpenAIReasoningSignature(providerMetadata: unknown): string | undefined {\n\tif (!isRecord(providerMetadata)) return;\n\tconst metadata = providerMetadata.openai;\n\tif (!isRecord(metadata) || typeof metadata.itemId !== \"string\") return;\n\n\tconst signature: OpenAIReasoningMetadata = { itemId: metadata.itemId };\n\tif (typeof metadata.reasoningEncryptedContent === \"string\" || metadata.reasoningEncryptedContent === null) {\n\t\tsignature.reasoningEncryptedContent = metadata.reasoningEncryptedContent;\n\t}\n\treturn JSON.stringify(signature);\n}\n\nfunction decodeOpenAIReasoningSignature(signature: string): OpenAIReasoningMetadata | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(signature);\n\t\tif (isRecord(parsed) && typeof parsed.itemId === \"string\") {\n\t\t\treturn {\n\t\t\t\titemId: parsed.itemId,\n\t\t\t\t...(typeof parsed.reasoningEncryptedContent === \"string\" || parsed.reasoningEncryptedContent === null\n\t\t\t\t\t? { reasoningEncryptedContent: parsed.reasoningEncryptedContent }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t} catch {\n\t\treturn;\n\t}\n}\n\n/**\n * The reasoning item our Responses transport replays from a thinking signature. Copilot\n * messages from before it ran on that transport carry `{ itemId, reasoningEncryptedContent }`\n * instead of the item; those replay when they hold encrypted content.\n */\nfunction responsesReasoningItem(signature: string): string | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(signature);\n\t\tif (!isRecord(parsed)) return;\n\t\tif (parsed.type === \"reasoning\" && typeof parsed.id === \"string\") return signature;\n\t\tconst legacy = decodeOpenAIReasoningSignature(signature);\n\t\tif (!legacy || typeof legacy.reasoningEncryptedContent !== \"string\") return;\n\t\treturn JSON.stringify({\n\t\t\ttype: \"reasoning\",\n\t\t\tid: legacy.itemId,\n\t\t\tencrypted_content: legacy.reasoningEncryptedContent,\n\t\t\tsummary: [],\n\t\t});\n\t} catch {\n\t\treturn;\n\t}\n}\n\nexport function googleThoughtSignature(metadata: unknown): string | undefined {\n\tif (!isRecord(metadata)) return;\n\tfor (const key of [\"google\", \"google-vertex\"]) {\n\t\tconst provider = metadata[key];\n\t\tif (isRecord(provider) && typeof provider.thoughtSignature === \"string\") return provider.thoughtSignature;\n\t}\n}\n\nfunction assistantMessages(\n\tmessage: Message.AssistantMessage,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum,\n): ModelMessage[] {\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") return [];\n\n\tconst assistantContent: Exclude<AssistantModelMessage[\"content\"], string> = [];\n\tconst toolResults: ToolModelMessage[\"content\"] = [];\n\tconst movedImageContent: Exclude<UserModelMessage[\"content\"], string> = [];\n\t// Replay metadata for our own Responses transport, only from a message it produced.\n\tconst responsesKey =\n\t\tisOwnResponses(model, method) && message.protocol === model.protocol && message.provider.id === model.provider.id\n\t\t\t? Model.optionsKey(model)\n\t\t\t: undefined;\n\tconst googleReplay =\n\t\t(model.protocol === \"google\" || model.protocol === \"google-vertex\") &&\n\t\tmessage.protocol === model.protocol &&\n\t\tmessage.provider.id === model.provider.id &&\n\t\tmessage.model === model.id;\n\tconst googleOptions = (signature: string | undefined) =>\n\t\tgoogleReplay && signature ? { [Model.optionsKey(model)]: { thoughtSignature: signature } } : undefined;\n\n\tfor (const part of message.parts) {\n\t\tconst google = googleOptions(\n\t\t\tpart.type === \"text\"\n\t\t\t\t? part.textSignature\n\t\t\t\t: part.type === \"thinking\"\n\t\t\t\t\t? part.thinkingSignature\n\t\t\t\t\t: part.type === \"toolCall\"\n\t\t\t\t\t\t? part.thoughtSignature\n\t\t\t\t\t\t: undefined,\n\t\t);\n\t\tif (part.type === \"text\") {\n\t\t\tconst text = sanitizeSurrogates(part.text);\n\t\t\tif (text.trim().length === 0) continue;\n\t\t\tassistantContent.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext,\n\t\t\t\t...(google ? { providerOptions: google } : {}),\n\t\t\t\t...(part.textSignature && responsesKey\n\t\t\t\t\t? { providerOptions: { [responsesKey]: { messageId: part.textSignature } } }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.type === \"thinking\") {\n\t\t\tconst thinking = sanitizeSurrogates(part.thinking);\n\t\t\tif (thinking.trim().length === 0 && !part.thinkingSignature) continue;\n\n\t\t\tif (responsesKey) {\n\t\t\t\t// Only a signed reasoning item replays; unsigned thinking is dropped.\n\t\t\t\tconst reasoningItem = part.thinkingSignature ? responsesReasoningItem(part.thinkingSignature) : undefined;\n\t\t\t\tif (!reasoningItem) continue;\n\t\t\t\tassistantContent.push({\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttext: thinking,\n\t\t\t\t\tproviderOptions: { [responsesKey]: { reasoningItem } },\n\t\t\t\t} as (typeof assistantContent)[number]);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (message.protocol === Model.KnownProviderEnum.githubCopilot) {\n\t\t\t\t/*\n\t\t\t\t * Copilot Messages models carry Anthropic signatures, and the chat endpoint\n\t\t\t\t * cannot replay thinking at all. Thinking that cannot be replayed natively\n\t\t\t\t * survives as plain text instead of going out unsigned.\n\t\t\t\t */\n\t\t\t\tconst openai = part.thinkingSignature ? decodeOpenAIReasoningSignature(part.thinkingSignature) : undefined;\n\t\t\t\tif (method === Model.APIMethodEnum.messages && part.thinkingSignature && !openai) {\n\t\t\t\t\tassistantContent.push({\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: thinking,\n\t\t\t\t\t\tproviderOptions: { anthropic: { signature: part.thinkingSignature } },\n\t\t\t\t\t} as (typeof assistantContent)[number]);\n\t\t\t\t} else if (thinking.trim().length > 0) {\n\t\t\t\t\tassistantContent.push({ type: \"text\", text: thinking });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst reasoning: Record<string, unknown> = { type: \"reasoning\", text: thinking };\n\t\t\t// OpenAI Responses only accepts native reasoning items with encoded metadata.\n\t\t\tif (message.protocol === Model.KnownProviderEnum.openai) {\n\t\t\t\tif (!part.thinkingSignature) continue;\n\t\t\t\tconst openai = decodeOpenAIReasoningSignature(part.thinkingSignature);\n\t\t\t\tif (!openai) continue;\n\t\t\t\treasoning.providerOptions = { openai };\n\t\t\t} else if (google) {\n\t\t\t\treasoning.providerOptions = google;\n\t\t\t} else if (part.thinkingSignature && message.protocol !== \"google\" && message.protocol !== \"google-vertex\") {\n\t\t\t\treasoning.providerOptions = { anthropic: { signature: part.thinkingSignature } };\n\t\t\t}\n\t\t\tassistantContent.push(reasoning as (typeof assistantContent)[number]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.type !== \"toolCall\") continue;\n\n\t\tconst responsesToolMetadata: { namespace?: string; omitItemId?: boolean } = {};\n\t\tif (responsesKey && part.namespace) responsesToolMetadata.namespace = part.namespace;\n\t\tif (responsesKey && message.model !== model.id) responsesToolMetadata.omitItemId = true;\n\t\tassistantContent.push({\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: part.callID,\n\t\t\ttoolName: part.name,\n\t\t\tinput: sanitizeRecord(part.arguments ?? {}),\n\t\t\t...(google ? { providerOptions: google } : {}),\n\t\t\t...(responsesKey && Object.keys(responsesToolMetadata).length > 0\n\t\t\t\t? { providerOptions: { [responsesKey]: responsesToolMetadata } }\n\t\t\t\t: {}),\n\t\t});\n\n\t\tconst terminal = part.status === \"pending\" || part.status === \"running\" ? undefined : part;\n\t\tconst moved = terminal ? movedImages(terminal, model, method) : undefined;\n\t\ttoolResults.push({\n\t\t\ttype: \"tool-result\",\n\t\t\ttoolCallId: part.callID,\n\t\t\ttoolName: part.name,\n\t\t\toutput: terminal\n\t\t\t\t? toolResultOutput(terminal, moved)\n\t\t\t\t: {\n\t\t\t\t\t\ttype: \"error-text\",\n\t\t\t\t\t\tvalue: \"no result provided\",\n\t\t\t\t\t},\n\t\t});\n\t\tif (terminal && moved) {\n\t\t\tconst caption =\n\t\t\t\tmoved === \"anthropicError\"\n\t\t\t\t\t? `Images from the error result of tool call ${part.callID} (${part.name}):`\n\t\t\t\t\t: moved === \"gemini\"\n\t\t\t\t\t\t? GEMINI_TOOL_IMAGES_CAPTION\n\t\t\t\t\t\t: movedImageContent.length === 0\n\t\t\t\t\t\t\t? CHAT_TOOL_IMAGES_CAPTION\n\t\t\t\t\t\t\t: undefined;\n\t\t\tmovedImageContent.push(\n\t\t\t\t...(caption === undefined ? [] : [{ type: \"text\" as const, text: caption }]),\n\t\t\t\t...terminal.result.content.flatMap((content) =>\n\t\t\t\t\tcontent.type === \"image\"\n\t\t\t\t\t\t? [{ type: \"file\" as const, data: content.data, mediaType: content.mimeType }]\n\t\t\t\t\t\t: [],\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\tconst result: ModelMessage[] = [];\n\tif (assistantContent.length > 0) {\n\t\tresult.push({ role: \"assistant\", content: assistantContent });\n\t}\n\tif (toolResults.length > 0) {\n\t\tresult.push({ role: \"tool\", content: toolResults });\n\t}\n\t// @ai-sdk/anthropic merges this into the tool results' user message, after the tool_result blocks.\n\tif (movedImageContent.length > 0) {\n\t\tresult.push({ role: \"user\", content: movedImageContent });\n\t}\n\treturn result;\n}\n\n/**\n * How the model's transport expresses tool changes after the first request. Only our own\n * Responses transport can declare tools in place; the AI SDK adapters take the current tool\n * set top-level. A request limited to some tools (`activeTools`) takes them top-level too,\n * since only that list is filtered.\n */\nexport function transcriptToolSupport(\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum | undefined,\n\trestricted = false,\n): Transcript.TranscriptToolSupport {\n\tif (restricted || !isOwnResponses(model, method)) return \"none\";\n\tif (supportsMidConvoSystemMessages(model, method) && model.compat?.supportsAdditionalTools) return \"changes\";\n\treturn model.compat?.supportsToolSearch ? \"additions\" : \"none\";\n}\n\n/**\n * Whether prompt changes go in place as system messages. Our own Responses transport and the\n * AI SDK's OpenAI Responses and Anthropic Messages adapters keep them where they stand; Chat\n * Completions takes the current prompt as the leading system prompt.\n */\nexport function supportsMidConvoSystemMessages(model: Model.Info, method: Model.APIMethodEnum | undefined): boolean {\n\tif (model.compat?.supportsMidConvoSystemMessages !== true) return false;\n\treturn isOwnResponses(model, method) || !isChatCompletions(model, resolveMethod(model, method));\n}\n\n/**\n * Anthropic with tool changes in place: every tool the thread can reach is declared up front, the\n * ones beyond its initial set deferred, and later changes name them by reference. Adding a tool\n * to the top-level list costs the cached prefix; referencing a deferred one does not.\n */\nfunction anthropicToolReferences(model: Model.Info, method: Model.APIMethodEnum, restricted: boolean): boolean {\n\treturn (\n\t\t!restricted &&\n\t\tisAnthropicWire(model, method) &&\n\t\tsupportsMidConvoSystemMessages(model, method) &&\n\t\tmodel.compat?.supportsAdditionalTools === true\n\t);\n}\n\n/** Messages before the first reply: on Anthropic their system messages join the leading prompt and tools. */\nfunction beforeFirstReply(messages: readonly Message.Message[]): Message.Message[] {\n\tconst reply = messages.findIndex((message) => message.role === \"assistant\");\n\treturn reply === -1 ? [...messages] : messages.slice(0, reply);\n}\n\n/**\n * The tools the request declares top-level, and which of them are deferred. Usually every tool\n * callable now. With Anthropic tool references, the initial set, then the deferred catalog and\n * every other tool the transcript declared, deferred, in an order that holds across requests.\n */\nexport function requestTools(\n\tcontext: Message.Context,\n\tmodel: Model.Info,\n\tmethodOverride?: Model.APIMethodEnum,\n\tactiveTools?: readonly string[],\n): { tools: Message.Tool[]; deferred: ReadonlySet<string> } {\n\tif (!anthropicToolReferences(model, resolveMethod(model, methodOverride), activeTools !== undefined)) {\n\t\treturn { tools: Transcript.getCurrentTools(context), deferred: new Set() };\n\t}\n\tconst initial = Transcript.getCurrentTools({ ...context, messages: beforeFirstReply(context.messages) });\n\tconst latest = new Map(Transcript.getDeclaredTools(context).map((tool) => [tool.name, tool]));\n\tconst tools = new Map(initial.map((tool) => [tool.name, tool]));\n\tconst deferred = new Set<string>();\n\tfor (const tool of [...(context.deferredTools ?? []), ...latest.values()]) {\n\t\tif (tools.has(tool.name)) continue;\n\t\ttools.set(tool.name, latest.get(tool.name) ?? tool);\n\t\tdeferred.add(tool.name);\n\t}\n\treturn { tools: [...tools.values()], deferred };\n}\n\n/** A later system message's tool changes as Anthropic tool references; a redefinition needs no removal. */\nfunction toolReferences(message: Message.SystemMessage) {\n\tconst added = new Set((message.toolsAdded ?? []).map((tool) => tool.name));\n\treturn [\n\t\t...(message.toolsRemoved ?? [])\n\t\t\t.filter((tool) => !added.has(tool.name))\n\t\t\t.map((tool) => ({ type: \"tool_removal\" as const, toolName: tool.name })),\n\t\t...[...added].map((name) => ({ type: \"tool_addition\" as const, toolName: name })),\n\t];\n}\n\n/**\n * The prompt the AI SDK adapters take as `system`: the leading one when changes go in place,\n * else the current one, every change folded in.\n */\nexport function leadingSystemPrompt(\n\tcontext: Message.Context,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum | undefined,\n): string | undefined {\n\treturn (\n\t\tTranscript.resolveTranscriptPrompt(context, supportsMidConvoSystemMessages(model, method)).systemPrompt ||\n\t\tundefined\n\t);\n}\n\n/** A tool as the language model receives it, for declaring it inside the prompt. */\nfunction functionTool(tool: Message.Tool, model: Model.Info, method: Model.APIMethodEnum): LanguageModelV3FunctionTool {\n\tconst { inputSchema, strict, providerOptions } = toolWire(tool, model, method);\n\treturn {\n\t\ttype: \"function\",\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: JSON.parse(JSON.stringify(inputSchema)) as LanguageModelV3FunctionTool[\"inputSchema\"],\n\t\t...(strict ? { strict } : {}),\n\t\t...(providerOptions ? { providerOptions } : {}),\n\t};\n}\n\n/** A system message sent in place: the prompt update `content`, then the tool change, if any. */\nfunction systemChangeMessage(\n\tcontent: string,\n\ttoolsAdded: readonly Message.Tool[],\n\ttoolsRemoved: readonly Message.ToolReference[],\n\tsupport: Transcript.TranscriptToolSupport,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum,\n): ModelMessage | undefined {\n\tif (toolsAdded.length === 0 && toolsRemoved.length === 0) {\n\t\treturn content.length > 0 ? { role: \"system\", content: sanitizeSurrogates(content) } : undefined;\n\t}\n\tconst toolChange: ResponsesToolChange = {\n\t\tmode: support === \"changes\" ? \"changes\" : \"additions\",\n\t\ttools: toolsAdded.map((tool) => functionTool(tool, model, method)),\n\t\tremoved: toolsRemoved.map((tool) => tool.name),\n\t};\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: sanitizeSurrogates(content),\n\t\t// Function tools are plain JSON once their schema went through `functionTool`.\n\t\tproviderOptions: { [Model.optionsKey(model)]: { toolChange } } as unknown as SharedV3ProviderOptions,\n\t};\n}\n\nexport function convertMessages(\n\tcontext: Message.Context,\n\tmodel: Model.Info,\n\tmethodOverride?: Model.APIMethodEnum,\n\tactiveTools?: readonly string[],\n): ModelMessage[] {\n\tconst method = resolveMethod(model, methodOverride);\n\tconst messages: ModelMessage[] = [];\n\tconst transformedMessages = Message.transformMessages(context.messages, model, toolCallIdNormalizer(model, method));\n\tconst support = transcriptToolSupport(model, method, activeTools !== undefined);\n\tconst transcript = Transcript.resolveTranscriptTools(context, support);\n\tconst prompt = Transcript.resolveTranscriptPrompt(context, supportsMidConvoSystemMessages(model, method));\n\n\tif (transcript.initialToolsInPlace) {\n\t\tconst head = systemChangeMessage(\"\", context.tools ?? [], [], support, model, method);\n\t\tif (head) messages.push(head);\n\t}\n\t// Our Responses transport takes the leading prompt in place, after the initial tool declaration.\n\tif (isOwnResponses(model, method) && prompt.systemPrompt) {\n\t\tmessages.push({ role: \"system\", content: sanitizeSurrogates(prompt.systemPrompt) });\n\t}\n\n\t// Every system message goes as an update, the first declaration too: a section a model read\n\t// whole does not yield to a later update of it, one it read as an update does. On Anthropic,\n\t// one before the first reply joins the leading prompt, where it caches: a trailing system\n\t// message's cache entry is never read once a reply follows it. Anthropic takes a later one\n\t// only after a user message, and never between a tool call and its result: each is held for\n\t// the next assistant message, or the end.\n\tconst anthropic = isAnthropicWire(model, method);\n\tconst references = anthropicToolReferences(model, method, activeTools !== undefined);\n\tconst leading: ModelMessage[] = [];\n\tconst held: ModelMessage[] = [];\n\tlet replied = false;\n\tlet systemIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"system\") {\n\t\t\tconst index = systemIndex++;\n\t\t\tconst update = index < prompt.foldedSystemMessages ? \"\" : Transcript.renderSystemPromptUpdate(msg);\n\t\t\t// The tools of one before the first reply belong to the initial set.\n\t\t\tconst toolChanges = references && replied ? toolReferences(msg) : [];\n\t\t\tif (toolChanges.length > 0) {\n\t\t\t\theld.push({\n\t\t\t\t\trole: \"system\",\n\t\t\t\t\tcontent: sanitizeSurrogates(update),\n\t\t\t\t\tproviderOptions: { [Model.optionsKey(model)]: { toolChanges } },\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst folded = index < transcript.foldedSystemMessages;\n\t\t\tconst change = systemChangeMessage(\n\t\t\t\tupdate,\n\t\t\t\tfolded ? [] : (msg.toolsAdded ?? []),\n\t\t\t\tfolded ? [] : (msg.toolsRemoved ?? []),\n\t\t\t\tsupport,\n\t\t\t\tmodel,\n\t\t\t\tmethod,\n\t\t\t);\n\t\t\tif (change) (!anthropic ? messages : replied ? held : leading).push(change);\n\t\t\tcontinue;\n\t\t}\n\t\tif (msg.role === \"user\") {\n\t\t\tmessages.push(...userContent(msg.parts));\n\t\t\tcontinue;\n\t\t}\n\t\tconst converted = assistantMessages(msg, model, method);\n\t\tif (converted.length > 0) {\n\t\t\treplied = true;\n\t\t\tmessages.push(...held.splice(0));\n\t\t}\n\t\tmessages.push(...converted);\n\t}\n\n\treturn [...leading, ...messages, ...held];\n}\n\n/**\n * The string input property of every grammar tool the transcript declared, for our Responses\n * transport: earlier calls to a tool since removed or redefined still replay as grammar calls.\n */\nexport function grammarToolInputProperties(\n\tcontext: Message.Context,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum | undefined,\n): Record<string, string> | undefined {\n\tif (!isOwnResponses(model, method)) return;\n\tconst properties: Record<string, string> = {};\n\tfor (const tool of Transcript.getDeclaredTools(context)) {\n\t\tconst grammar = resolveToolGrammar(tool, model.compat);\n\t\tif (grammar) properties[tool.name] = grammar.inputProperty;\n\t}\n\treturn Object.keys(properties).length > 0 ? properties : undefined;\n}\n\n/** The parameter schema, strict flag and grammar a tool goes out with on this model. */\nfunction toolWire(tool: Message.Tool, model?: Model.Info, method?: Model.APIMethodEnum, preferNonStrict = false) {\n\tconst strictParameters = resolveStrictParameters(tool, model, preferNonStrict);\n\tconst grammarConstraint =\n\t\tmodel && isOwnResponses(model, method) ? resolveToolGrammar(tool, model.compat) : undefined;\n\treturn {\n\t\tinputSchema: strictParameters ?? tool.parameters,\n\t\tstrict: strictParameters ? true : undefined,\n\t\tproviderOptions:\n\t\t\tmodel && grammarConstraint ? { [Model.optionsKey(model)]: { grammar: grammarConstraint } } : undefined,\n\t};\n}\n\nexport function convertTools(\n\ttools?: Message.Tool[],\n\tmodel?: Model.Info,\n\tmethod?: Model.APIMethodEnum,\n\tdeferred: ReadonlySet<string> = new Set(),\n\tpreferNonStrict = false,\n): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tconst { inputSchema, strict, providerOptions } = toolWire(tool, model, method, preferNonStrict);\n\t\tconst key = model && deferred.has(tool.name) ? Model.optionsKey(model) : undefined;\n\t\tconst options =\n\t\t\tkey === undefined\n\t\t\t\t? providerOptions\n\t\t\t\t: { ...providerOptions, [key]: { ...providerOptions?.[key], deferLoading: true } };\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(inputSchema as any),\n\t\t\t...(strict ? { strict } : {}),\n\t\t\t...(options ? { providerOptions: options } : {}),\n\t\t};\n\t}\n\treturn result;\n}\n\nexport function mapFinishReason(reason: FinishReason | undefined): Message.StopReason {\n\tswitch (reason) {\n\t\tcase \"length\":\n\t\t\treturn \"length\";\n\t\tcase \"tool-calls\":\n\t\t\treturn \"toolUse\";\n\t\tcase \"content-filter\":\n\t\tcase \"error\":\n\t\tcase \"other\":\n\t\t\treturn \"error\";\n\t\tcase \"stop\":\n\t\tdefault:\n\t\t\treturn \"stop\";\n\t}\n}\n\nexport function mapUsage(\n\tusage: LanguageModelUsage | undefined,\n\tmodel: Model.Info,\n\tcostMultiplier = 1,\n\tproviderMetadata?: unknown,\n): Message.AssistantMessage[\"usage\"] {\n\tconst cacheRead = usage?.inputTokenDetails.cacheReadTokens ?? 0;\n\tconst cacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;\n\tconst cacheWrite1h = Pricing.cacheWrite1hTokens(providerMetadata);\n\tconst input =\n\t\tusage?.inputTokenDetails?.noCacheTokens ?? Math.max((usage?.inputTokens ?? 0) - cacheRead - cacheWrite, 0);\n\tconst output = usage?.outputTokens ?? 0;\n\tconst totalTokens = usage?.totalTokens ?? input + cacheRead + cacheWrite + output;\n\tconst result: Message.AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\t...(cacheWrite1h === undefined ? {} : { cacheWrite1h }),\n\t\t...(usage?.outputTokenDetails?.reasoningTokens !== undefined\n\t\t\t? { reasoning: usage.outputTokenDetails.reasoningTokens }\n\t\t\t: {}),\n\t\ttotalTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tModel.calculateCost(model, result);\n\tif (costMultiplier !== 1) {\n\t\tresult.cost.input *= costMultiplier;\n\t\tresult.cost.output *= costMultiplier;\n\t\tresult.cost.cacheRead *= costMultiplier;\n\t\tresult.cost.cacheWrite *= costMultiplier;\n\t\tresult.cost.total = result.cost.input + result.cost.output + result.cost.cacheRead + result.cost.cacheWrite;\n\t}\n\treturn result;\n}\n\nexport type StreamingToolCallBlock = Message.ToolCallPendingPart & {\n\tpartialJson?: string;\n};\n\nexport function toolCallFromPart(\n\tpart: Extract<TextStreamPart<ToolSet>, { type: \"tool-call\" }>,\n): StreamingToolCallBlock {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tcallID: part.toolCallId,\n\t\tname: part.toolName,\n\t\targuments: typeof part.input === \"object\" && part.input !== null ? (part.input as Record<string, unknown>) : {},\n\t\tstatus: \"pending\",\n\t\ttime: {\n\t\t\tstart: Date.now(),\n\t\t\tend: Date.now(),\n\t\t},\n\t};\n}\n\nexport function updateToolCallFromInput(block: StreamingToolCallBlock, partialJson: string): void {\n\tblock.partialJson = partialJson;\n\tblock.arguments = parseStreamingJson<Record<string, unknown>>(partialJson);\n\tblock.time.end = Date.now();\n}\n","import { APICallError } from \"@ai-sdk/provider\";\nimport { RetryError, streamText, type TextStreamPart, type ToolSet } from \"ai\";\nimport * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { AssistantMessageEventStream } from \"../utils/eventstream.ts\";\nimport { compact } from \"../utils/helpers.ts\";\nimport * as Failure from \"./failure.ts\";\nimport { Options, type ProviderOptionBag, type RuntimeOptions } from \"./options.ts\";\nimport * as Pricing from \"./pricing.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { resolveAISDKLanguageModel } from \"./provider.ts\";\nimport { resolveMethod } from \"./registry.ts\";\nimport { formatThrownError } from \"./runtime.ts\";\nimport { applyDefaultMaxTokens } from \"./shared.ts\";\nimport * as Thinking from \"./thinking.ts\";\nimport {\n\tgoogleThoughtSignature,\n\tconvertMessages,\n\tisAnthropicWire,\n\tisOwnResponses,\n\tconvertTools,\n\trequestTools,\n\tcreateAssistantMessage,\n\tencodeOpenAIReasoningSignature,\n\tgrammarToolInputProperties,\n\tleadingSystemPrompt,\n\tmapFinishReason,\n\tmapUsage,\n\ttoolCallFromPart,\n\tupdateToolCallFromInput,\n\ttype StreamingToolCallBlock,\n} from \"./transform.ts\";\n\ntype TextBlock = Message.TextContent & { streamId?: string };\ntype ThinkingBlock = Message.ThinkingContent & { streamId?: string };\n\ntype StreamBlock = TextBlock | ThinkingBlock | StreamingToolCallBlock;\n\nfunction mergeProviderOptions(...sources: Array<ProviderOptionBag | undefined>): ProviderOptionBag {\n\tconst result: ProviderOptionBag = {};\n\tfor (const source of sources) {\n\t\tif (!source) continue;\n\t\tfor (const [key, value] of Object.entries(source)) {\n\t\t\tif (!value) continue;\n\t\t\tresult[key] = {\n\t\t\t\t...result[key],\n\t\t\t\t...value,\n\t\t\t};\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction configuredCacheRetention(options: RuntimeOptions): \"none\" | \"short\" | \"long\" | undefined {\n\tif (options.cacheRetention) return options.cacheRetention;\n\tconst env = process.env.CODEWORK_CACHE_RETENTION;\n\tif (env === \"none\" || env === \"short\" || env === \"long\") return env;\n}\n\nfunction cacheProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\tconst retention = configuredCacheRetention(options);\n\tconst key = Model.optionsKey(model);\n\n\tif (retention === \"none\") return {};\n\n\tif (key === \"openai\") {\n\t\tconst openai: Record<string, unknown> = {};\n\t\tif (options.sessionId) openai.promptCacheKey = options.sessionId;\n\t\tif (retention === \"short\") openai.promptCacheRetention = \"in_memory\";\n\t\tif (retention === \"long\") openai.promptCacheRetention = \"24h\";\n\t\treturn Object.keys(openai).length > 0 ? { [key]: openai } : {};\n\t}\n\n\tif (Thinking.isAnthropicMessagesModel(model) && retention) {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tcacheControl: {\n\t\t\t\t\ttype: \"ephemeral\",\n\t\t\t\t\t...(retention === \"long\" ? { ttl: \"1h\" } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {};\n}\n\nfunction resolveProviderOptions(\n\tmodel: Model.Info,\n\tcontext: Message.Context,\n\toptions: RuntimeOptions,\n\tplan: Thinking.Plan,\n): ProviderOptionBag {\n\tconst grammars = grammarToolInputProperties(context, model, options.method);\n\treturn mergeProviderOptions(\n\t\tmodel.providerOptions as ProviderOptionBag | undefined,\n\t\tcacheProviderOptions(model, options),\n\t\tThinking.reasoningProviderOptions(model, plan),\n\t\tgrammars === undefined ? undefined : { [Model.optionsKey(model)]: { grammarToolInputProperties: grammars } },\n\t\toptions.providerOptions as ProviderOptionBag | undefined,\n\t);\n}\n\nfunction partIndex(output: Message.AssistantMessage, block: StreamBlock): number {\n\treturn output.parts.indexOf(block as Message.AssistantMessage[\"parts\"][number]);\n}\n\n/** Metadata our Responses transport attaches under the model's provider key. */\nfunction responsesMetadata(value: unknown, model: Model.Info): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst metadata = (value as Record<string, unknown>)[Model.optionsKey(model)];\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 ensureTextBlock(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): TextBlock {\n\tconst existing = output.parts.find((part) => part.type === \"text\" && (part as TextBlock).streamId === id) as\n\t\t| TextBlock\n\t\t| undefined;\n\tif (existing) return existing;\n\n\tconst block: TextBlock = { type: \"text\", text: \"\", streamId: id };\n\toutput.parts.push(block);\n\tstream.push({ type: \"text.start\", partIndex: partIndex(output, block), partial: output });\n\treturn block;\n}\n\nfunction ensureThinkingBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n): ThinkingBlock {\n\tconst existing = output.parts.find((part) => part.type === \"thinking\" && (part as ThinkingBlock).streamId === id) as\n\t\t| ThinkingBlock\n\t\t| undefined;\n\tif (existing) return existing;\n\n\tconst block: ThinkingBlock = { type: \"thinking\", thinking: \"\", streamId: id };\n\toutput.parts.push(block);\n\tstream.push({ type: \"thinking.start\", partIndex: partIndex(output, block), partial: output });\n\treturn block;\n}\n\nfunction ensureToolCallBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tname: string,\n\tstream: AssistantMessageEventStream,\n\temitStart: boolean,\n): StreamingToolCallBlock {\n\tconst existing = output.parts.find((part) => part.type === \"toolCall\" && part.callID === id) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tif (existing) {\n\t\tif (!existing.name && name) existing.name = name;\n\t\treturn existing;\n\t}\n\n\tconst block: StreamingToolCallBlock = {\n\t\ttype: \"toolCall\",\n\t\tcallID: id,\n\t\tname,\n\t\targuments: {},\n\t\tstatus: \"pending\",\n\t\ttime: {\n\t\t\tstart: Date.now(),\n\t\t\tend: Date.now(),\n\t\t},\n\t};\n\toutput.parts.push(block);\n\tif (emitStart) {\n\t\tstream.push({ type: \"toolcall.start\", partIndex: partIndex(output, block), partial: output });\n\t}\n\treturn block;\n}\n\nfunction finishTextBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n\ttextSignature?: string,\n): void {\n\tconst block = output.parts.find((part) => part.type === \"text\" && (part as TextBlock).streamId === id) as\n\t\t| TextBlock\n\t\t| undefined;\n\tif (!block) return;\n\tif (textSignature) block.textSignature = textSignature;\n\tconst index = partIndex(output, block);\n\tdelete (block as { streamId?: string }).streamId;\n\tstream.push({ type: \"text.end\", partIndex: index, content: block.text, partial: output });\n}\n\nfunction finishThinkingBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n\tthinkingSignature?: string,\n): void {\n\tconst block = output.parts.find((part) => part.type === \"thinking\" && (part as ThinkingBlock).streamId === id) as\n\t\t| ThinkingBlock\n\t\t| undefined;\n\tif (!block) return;\n\tif (thinkingSignature) block.thinkingSignature = thinkingSignature;\n\tconst index = partIndex(output, block);\n\tdelete (block as { streamId?: string }).streamId;\n\tstream.push({ type: \"thinking.end\", partIndex: index, content: block.thinking, partial: output });\n}\n\nfunction finishToolInput(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): void {\n\tconst block = output.parts.find((part) => part.type === \"toolCall\" && part.callID === id) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tif (!block) return;\n\tconst index = partIndex(output, block);\n\tdelete block.partialJson;\n\tstream.push({ type: \"toolcall.end\", partIndex: index, toolCall: block, partial: output });\n}\n\nfunction finalizeToolCall(\n\toutput: Message.AssistantMessage,\n\tpart: Extract<TextStreamPart<ToolSet>, { type: \"tool-call\" }>,\n\tmodel: Model.Info,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst existing = output.parts.find((item) => item.type === \"toolCall\" && item.callID === part.toolCallId) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tconst block = existing ?? toolCallFromPart(part);\n\tblock.callID = part.toolCallId;\n\tblock.name = part.toolName;\n\tblock.arguments =\n\t\ttypeof part.input === \"object\" && part.input !== null ? (part.input as Record<string, unknown>) : {};\n\tconst namespace = responsesMetadata(part.providerMetadata, model)?.namespace;\n\tconst thoughtSignature = googleThoughtSignature(part.providerMetadata);\n\tif (thoughtSignature) block.thoughtSignature = thoughtSignature;\n\tif (typeof namespace === \"string\") block.namespace = namespace;\n\tblock.time.end = Date.now();\n\tdelete block.partialJson;\n\n\tif (!existing) {\n\t\toutput.parts.push(block);\n\t}\n\n\tconst index = partIndex(output, block);\n\tstream.push({ type: \"toolcall.final\", partIndex: index, toolCall: block, partial: output });\n}\n\n/**\n * Pricing inputs that are only complete once the provider answers.\n *\n * The requested tier is known upfront; the tier actually served and the cache-write\n * breakdown arrive with the terminal usage, and both change what the turn costs.\n */\ninterface Pricing {\n\treadonly requestedServiceTier: string | undefined;\n\tproviderMetadata?: unknown;\n}\n\nfunction handlePart(\n\tpart: TextStreamPart<ToolSet>,\n\toutput: Message.AssistantMessage,\n\tmodel: Model.Info,\n\tstream: AssistantMessageEventStream,\n\tpricing: Pricing,\n): void {\n\tswitch (part.type) {\n\t\tcase \"text-start\":\n\t\t\tensureTextBlock(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"text-delta\": {\n\t\t\tconst block = ensureTextBlock(output, part.id, stream);\n\t\t\tconst signature = googleThoughtSignature(part.providerMetadata);\n\t\t\tif (signature) block.textSignature = signature;\n\t\t\tblock.text += part.text;\n\t\t\tstream.push({ type: \"text.delta\", partIndex: partIndex(output, block), delta: part.text, partial: output });\n\t\t\tbreak;\n\t\t}\n\t\tcase \"text-end\": {\n\t\t\tconst messageId = responsesMetadata(part.providerMetadata, model)?.messageId;\n\t\t\tfinishTextBlock(output, part.id, stream, typeof messageId === \"string\" ? messageId : undefined);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reasoning-start\":\n\t\t\tensureThinkingBlock(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"reasoning-delta\": {\n\t\t\tconst block = ensureThinkingBlock(output, part.id, stream);\n\t\t\tblock.thinking += part.text;\n\t\t\t// Capture the provider thinking signature for faithful multi-turn replay.\n\t\t\t// @ai-sdk/anthropic emits it as a reasoning-delta with empty text and providerMetadata.\n\t\t\tconst sig =\n\t\t\t\t(part.providerMetadata?.anthropic as Record<string, unknown> | undefined)?.signature ??\n\t\t\t\t(part.providerMetadata?.[\"google-vertex-anthropic\"] as Record<string, unknown> | undefined)?.signature ??\n\t\t\t\tgoogleThoughtSignature(part.providerMetadata);\n\t\t\tif (typeof sig === \"string\") block.thinkingSignature = sig;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking.delta\",\n\t\t\t\tpartIndex: partIndex(output, block),\n\t\t\t\tdelta: part.text,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reasoning-end\": {\n\t\t\tconst reasoningItem = responsesMetadata(part.providerMetadata, model)?.reasoningItem;\n\t\t\tconst openAISignature = encodeOpenAIReasoningSignature(part.providerMetadata);\n\t\t\tfinishThinkingBlock(\n\t\t\t\toutput,\n\t\t\t\tpart.id,\n\t\t\t\tstream,\n\t\t\t\ttypeof reasoningItem === \"string\" ? reasoningItem : openAISignature,\n\t\t\t);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-input-start\":\n\t\t\tensureToolCallBlock(output, part.id, part.toolName, stream, true);\n\t\t\tbreak;\n\t\tcase \"tool-input-delta\": {\n\t\t\tconst block = ensureToolCallBlock(output, part.id, \"\", stream, true);\n\t\t\tconst partialJson = (block.partialJson ?? \"\") + part.delta;\n\t\t\tupdateToolCallFromInput(block, partialJson);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall.delta\",\n\t\t\t\tpartIndex: partIndex(output, block),\n\t\t\t\tdelta: part.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-input-end\":\n\t\t\tfinishToolInput(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"tool-call\":\n\t\t\tfinalizeToolCall(output, part, model, stream);\n\t\t\tbreak;\n\t\tcase \"start-step\":\n\t\t\tstampProviderThinkingLevel(output, part.request.body);\n\t\t\tbreak;\n\t\tcase \"finish-step\":\n\t\t\toutput.responseId ||= part.response.id;\n\t\t\tif (part.response.modelId && part.response.modelId !== model.id)\n\t\t\t\toutput.responseModel ||= part.response.modelId;\n\t\t\tpricing.providerMetadata = part.providerMetadata ?? pricing.providerMetadata;\n\t\t\toutput.usage = mapUsage(part.usage, model, resolvePricing(model, pricing), pricing.providerMetadata);\n\t\t\toutput.stopReason = mapFinishReason(part.finishReason);\n\t\t\tbreak;\n\t\tcase \"finish\":\n\t\t\toutput.usage = mapUsage(part.totalUsage, model, resolvePricing(model, pricing), pricing.providerMetadata);\n\t\t\toutput.stopReason = mapFinishReason(part.finishReason);\n\t\t\tbreak;\n\t\tcase \"abort\":\n\t\t\toutput.stopReason = \"aborted\";\n\t\t\tif (part.reason !== undefined) output.errorMessage = part.reason;\n\t\t\tbreak;\n\t\tcase \"error\":\n\t\t\tthrow part.error instanceof Error ? part.error : new Error(formatThrownError(part.error));\n\t}\n}\n\nfunction stampProviderThinkingLevel(output: Message.AssistantMessage, body: unknown): void {\n\tconst level = Thinking.providerThinkingLevel(body);\n\tif (level !== undefined) output.providerThinkingLevel = level;\n}\n\n/** A request the provider refused never streams a `start-step`; its body travels on the error. */\nfunction rejectedRequestBody(error: unknown): unknown {\n\tif (RetryError.isInstance(error)) return rejectedRequestBody(error.lastError);\n\treturn APICallError.isInstance(error) ? error.requestBodyValues : undefined;\n}\n\nfunction resolvePricing(model: Model.Info, pricing: Pricing): number {\n\treturn Pricing.serviceTierCostMultiplier(\n\t\tmodel,\n\t\tPricing.servedServiceTier(model, pricing.requestedServiceTier, pricing.providerMetadata),\n\t);\n}\n\n/**\n * The response ceiling to send, already fitted around the thinking budget by\n * {@link Thinking.resolvePlan}.\n *\n * `plan.maxTokens` is the whole response -- thinking and answer together, which is\n * what Anthropic's own `max_tokens` means. But `@ai-sdk/anthropic` treats\n * `maxOutputTokens` as the answer alone and adds the budget back on before sending\n * (`baseArgs.max_tokens = maxTokens + thinkingBudget`). Handing it the total there\n * would ask for the budget twice, so it gets the answer room and reconstructs the\n * total itself.\n *\n * That only applies when a budget is actually sent. An adaptive model is given an\n * effort level and no budget, so the SDK adds nothing and the total goes through\n * unchanged -- subtracting there would quietly under-ask by the whole budget.\n */\nexport function resolveMaxOutputTokens(model: Model.Info, plan: Thinking.Plan): number | undefined {\n\tconst key = Model.optionsKey(model);\n\t// The ChatGPT Codex backend rejects max_output_tokens, so never send it.\n\tif (key === \"openai-codex\") return undefined;\n\tif (plan.maxTokens === undefined) return undefined;\n\n\tconst sendsBudget = Thinking.isAnthropicMessagesModel(model) && !model.compat?.forceAdaptiveThinking;\n\treturn sendsBudget ? plan.maxTokens - plan.budget : plan.maxTokens;\n}\n\n/** A bare number is a total ceiling only; the idle timeout has to be spelled per chunk. */\nfunction resolveTimeout(options: RuntimeOptions): Parameters<typeof streamText<ToolSet>>[0][\"timeout\"] {\n\tconst { timeoutMs, idleTimeoutMs } = options;\n\tif (timeoutMs === undefined && idleTimeoutMs === undefined) return undefined;\n\treturn compact({ totalMs: timeoutMs, firstChunkMs: idleTimeoutMs, chunkMs: idleTimeoutMs });\n}\n\nexport const stream: Protocol.StreamFunction<Model.KnownProviderEnum, typeof Options> = (model, context, options) => {\n\tconst stream = new AssistantMessageEventStream();\n\tconst runtimeOptions = applyDefaultMaxTokens(model, (options ?? {}) as RuntimeOptions);\n\n\tvoid (async () => {\n\t\tconst output = createAssistantMessage(model, runtimeOptions.reasoning ?? \"off\");\n\t\ttry {\n\t\t\tconst plan = Thinking.resolvePlan(model, context, runtimeOptions);\n\t\t\tconst languageModel = await resolveAISDKLanguageModel(model, runtimeOptions, plan.budget);\n\t\t\t// Every tool callable now, so calls to tools declared in place still parse.\n\t\t\tconst declared = requestTools(context, model, runtimeOptions.method, runtimeOptions.activeTools);\n\t\t\tconst messages = convertMessages(context, model, runtimeOptions.method, runtimeOptions.activeTools);\n\t\t\tconst providerOptions = resolveProviderOptions(model, context, runtimeOptions, plan) as Parameters<\n\t\t\t\ttypeof streamText<ToolSet>\n\t\t\t>[0][\"providerOptions\"];\n\t\t\tconst pricing: Pricing = {\n\t\t\t\trequestedServiceTier: Pricing.requestedServiceTier(\n\t\t\t\t\tmodel,\n\t\t\t\t\truntimeOptions,\n\t\t\t\t\tproviderOptions as ProviderOptionBag,\n\t\t\t\t),\n\t\t\t};\n\n\t\t\tconst buildParams = async (preferNonStrict: boolean) => {\n\t\t\t\tconst tools = convertTools(\n\t\t\t\t\tdeclared.tools,\n\t\t\t\t\tmodel,\n\t\t\t\t\truntimeOptions.method,\n\t\t\t\t\tdeclared.deferred,\n\t\t\t\t\tpreferNonStrict,\n\t\t\t\t);\n\t\t\t\tconst sentPreferStrict =\n\t\t\t\t\tdeclared.tools?.some(\n\t\t\t\t\t\t(tool) =>\n\t\t\t\t\t\t\ttool.constrainedSampling &&\n\t\t\t\t\t\t\ttool.constrainedSampling.type === \"json_schema\" &&\n\t\t\t\t\t\t\ttool.constrainedSampling.strict === \"prefer\" &&\n\t\t\t\t\t\t\ttools?.[tool.name]?.strict === true,\n\t\t\t\t\t) ?? false;\n\t\t\t\tconst activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = compact({\n\t\t\t\t\tmodel: languageModel,\n\t\t\t\t\t// Our own Responses transport receives the system prompt among the messages.\n\t\t\t\t\tsystem: isOwnResponses(model, runtimeOptions.method)\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: leadingSystemPrompt(context, model, runtimeOptions.method),\n\t\t\t\t\tmessages,\n\t\t\t\t\t// Prompt and tool changes sent in place travel as system messages.\n\t\t\t\t\tallowSystemInMessages: messages.some((message) => message.role === \"system\") || undefined,\n\t\t\t\t\ttools,\n\t\t\t\t\ttoolChoice: runtimeOptions.toolChoice as Parameters<typeof streamText<ToolSet>>[0][\"toolChoice\"],\n\t\t\t\t\tactiveTools,\n\t\t\t\t\tmaxOutputTokens: resolveMaxOutputTokens(model, plan),\n\t\t\t\t\ttemperature: model.compat?.supportsTemperature === false ? undefined : runtimeOptions.temperature,\n\t\t\t\t\tproviderOptions,\n\t\t\t\t\t// The exact body is where `providerThinkingLevel` is read from.\n\t\t\t\t\tinclude: { requestBody: true },\n\t\t\t\t\tabortSignal: runtimeOptions.signal,\n\t\t\t\t\ttimeout: resolveTimeout(runtimeOptions),\n\t\t\t\t\tmaxRetries: runtimeOptions.maxRetries,\n\t\t\t\t\theaders: runtimeOptions.headers,\n\t\t\t\t\t// Aikit owns error normalization and emits one terminal error event.\n\t\t\t\t\t// AI SDK's default callback logs the raw exception (including request\n\t\t\t\t\t// payloads) before that event can reach an SDK or CLI consumer.\n\t\t\t\t\tonError: () => {},\n\t\t\t\t});\n\n\t\t\t\tconst payload = await runtimeOptions.onPayload?.(params, model);\n\t\t\t\tif (payload !== undefined) {\n\t\t\t\t\tparams = payload as Parameters<typeof streamText<ToolSet>>[0];\n\t\t\t\t}\n\t\t\t\treturn { params, sentPreferStrict };\n\t\t\t};\n\n\t\t\tlet preferNonStrict = false;\n\t\t\tlet built = await buildParams(preferNonStrict);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tfor (;;) {\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const part of streamText(built.params).fullStream) {\n\t\t\t\t\t\thandlePart(part, output, model, stream, pricing);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Claude refuses the whole request when strict tools exceed its limits, and `prefer` tools\n\t\t\t\t\t// can go non-strict instead. Only a request refused before anything streamed is retried, once.\n\t\t\t\t\tconst limitMessage = Failure.strictToolLimitMessage(error);\n\t\t\t\t\tif (\n\t\t\t\t\t\tpreferNonStrict ||\n\t\t\t\t\t\truntimeOptions.signal?.aborted ||\n\t\t\t\t\t\toutput.parts.length > 0 ||\n\t\t\t\t\t\t!built.sentPreferStrict ||\n\t\t\t\t\t\t!isAnthropicWire(model, resolveMethod(model, runtimeOptions.method)) ||\n\t\t\t\t\t\tlimitMessage === undefined\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\t(output.diagnostics ??= []).push({\n\t\t\t\t\t\ttype: \"strictToolsFallback\",\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\terror: { message: limitMessage },\n\t\t\t\t\t\tdetails: { reason: \"strictToolLimits\" },\n\t\t\t\t\t});\n\t\t\t\t\tpreferNonStrict = true;\n\t\t\t\t\tbuilt = await buildParams(preferNonStrict);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (runtimeOptions.signal?.aborted || output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"provider returned an error stop reason\");\n\t\t\t}\n\n\t\t\toutput.time.completed = Date.now();\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.parts) {\n\t\t\t\tdelete (block as TextBlock).streamId;\n\t\t\t\tdelete (block as ThinkingBlock).streamId;\n\t\t\t\tdelete (block as StreamingToolCallBlock).partialJson;\n\t\t\t}\n\t\t\toutput.time.completed = Date.now();\n\t\t\t// Only the caller's signal means \"stop\". An abort from inside the SDK, such as its\n\t\t\t// `timeoutMs` timer, is a failure the caller did not ask for.\n\t\t\tstampProviderThinkingLevel(output, rejectedRequestBody(error));\n\t\t\toutput.stopReason = runtimeOptions.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tif (output.stopReason === \"aborted\") {\n\t\t\t\toutput.errorMessage = formatThrownError(error);\n\t\t\t} else {\n\t\t\t\toutput.failure = Failure.normalize(error);\n\t\t\t\toutput.errorMessage = output.failure.message;\n\t\t\t}\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n","import * as Model from \"../model/model.ts\";\nimport { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { stream } from \"./stream.ts\";\n\nexport { Options } from \"./options.ts\";\nexport * from \"./registry.ts\";\nexport { stream } from \"./stream.ts\";\nexport * from \"./transform.ts\";\n\nexport function createAISDKProtocol(\n\tprotocol: Model.KnownProviderEnum,\n): Protocol.Protocol<Model.KnownProviderEnum, typeof Options> {\n\treturn {\n\t\tprotocol,\n\t\tstream,\n\t};\n}\n\nexport function registerAISDKProtocols(): void {\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.anthropic));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.google));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertex));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertexAnthropic));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openai));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCompatible));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCodex));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.githubCopilot));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openrouter));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.xai));\n}\n","import { registerAISDKProtocols } from \"./index.ts\";\n\nregisterAISDKProtocols();\n","import \"./llm/register.ts\";\n\nimport type * as Message from \"./message/message.ts\";\nimport type * as Model from \"./model/model.ts\";\nimport * as Protocol from \"./llm/protocol.ts\";\nimport type { AssistantMessageEventStream } from \"./utils/eventstream.ts\";\n\n/**\n * Stream assistant responses for a model and context.\n *\n * Example:\n *\n * ```ts\n * const s = stream(model, context, {\n * apiKey: process.env.ANTHROPIC_API_KEY,\n * });\n *\n * for await (const event of s) {\n * if (event.type === \"text.delta\") {\n * process.stdout.write(event.delta);\n * }\n * }\n *\n * const message = await s.result();\n * ```\n *\n * This export also includes convenience helpers:\n *\n * ```ts\n * const message = await stream.complete(model, context, options);\n * ```\n */\ntype StreamCallable = {\n\t<TProtocol extends Protocol.ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: Protocol.OptionsFor<TProtocol>,\n\t): AssistantMessageEventStream;\n\tcomplete: typeof Protocol.complete;\n\tresolveProtocolProvider: typeof Protocol.resolveProtocolProvider;\n};\n\nconst streamImpl = <TProtocol extends Protocol.ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: Protocol.OptionsFor<TProtocol>,\n): AssistantMessageEventStream => Protocol.stream(model, context, options);\n\n/**\n * Start a streaming assistant response for a model/context pair.\n *\n * This is the main streaming entrypoint.\n * Attached helpers:\n *\n * - `stream.complete(...)` resolves the final assistant message without manually iterating events.\n * - `stream.resolveProtocolProvider(...)` exposes protocol resolution for advanced integrations.\n */\nexport const stream = Object.assign(streamImpl, {\n\tcomplete: Protocol.complete,\n\tresolveProtocolProvider: Protocol.resolveProtocolProvider,\n}) as StreamCallable;\n\n/** Resolve a streamed response directly to the final assistant message. */\nexport const complete = Protocol.complete;\n","/**\n * @description Validation powered by TypeBox's built-in schema compiler.\n */\n\nimport type { Static, TSchema } from \"typebox\";\nimport Schema from \"typebox/schema\";\nimport Value from \"typebox/value\";\n\nimport { nullableVariant, schemaAllowsNull } from \"../llm/strict.ts\";\nimport type * as Message from \"../message/message.ts\";\n\nconst validators = new WeakMap<TSchema, ReturnType<typeof Schema.Compile>>();\n\nfunction getValidator<T extends TSchema>(schema: T): ReturnType<typeof Schema.Compile<T>> {\n\tconst existing = validators.get(schema) as ReturnType<typeof Schema.Compile<T>> | undefined;\n\tif (existing) return existing;\n\n\tconst validator = Schema.Compile(schema);\n\tvalidators.set(schema, validator);\n\treturn validator;\n}\n\nfunction errorPath(error: { instancePath?: string; params?: Record<string, unknown> }): string {\n\tif (error.instancePath) return error.instancePath.substring(1);\n\n\tconst requiredProperties = error.params?.requiredProperties;\n\tif (Array.isArray(requiredProperties)) return requiredProperties.join(\", \");\n\n\treturn \"root\";\n}\n\ntype JsonSchemaObject = {\n\tproperties?: Record<string, JsonSchemaObject>;\n\trequired?: string[];\n\titems?: JsonSchemaObject | JsonSchemaObject[];\n\t$ref?: unknown;\n};\n\n/**\n * Drop `null` from optional properties whose schema does not accept null, in place. Strict constrained sampling\n * makes every property required and nullable, so the model answers an omitted optional argument with `null`.\n */\nexport function normalizeOptionalNulls(value: unknown, schema: unknown): void {\n\tconst variant = nullableVariant(schema);\n\tif (variant !== undefined) return normalizeOptionalNulls(value, variant);\n\tconst node = schema as JsonSchemaObject;\n\tif (Array.isArray(value)) {\n\t\tif (Array.isArray(node.items)) {\n\t\t\tfor (const [index, item] of value.entries()) {\n\t\t\t\tif (node.items[index]) normalizeOptionalNulls(item, node.items[index]);\n\t\t\t}\n\t\t} else if (node.items) {\n\t\t\tfor (const item of value) normalizeOptionalNulls(item, node.items);\n\t\t}\n\t\treturn;\n\t}\n\tif (typeof value !== \"object\" || value === null || !node.properties) return;\n\n\tconst object = value as Record<string, unknown>;\n\tconst required = new Set(node.required ?? []);\n\tfor (const [key, property] of Object.entries(node.properties)) {\n\t\tif (!(key in object)) continue;\n\t\tif (\n\t\t\tobject[key] === null &&\n\t\t\t!required.has(key) &&\n\t\t\ttypeof property.$ref !== \"string\" &&\n\t\t\t!schemaAllowsNull(property)\n\t\t) {\n\t\t\tdelete object[key];\n\t\t} else {\n\t\t\tnormalizeOptionalNulls(object[key], property);\n\t\t}\n\t}\n}\n\n/**\n * Validates an arbitrary value against a TypeBox schema and returns the coerced value.\n */\nexport function validateSchema<T extends TSchema>(schema: T, value: unknown, label: string): Static<T> {\n\tconst validator = getValidator(schema);\n\tconst input = Value.Convert(schema, structuredClone(value));\n\n\ttry {\n\t\treturn validator.Parse(input);\n\t} catch {\n\t\tconst [_result, validationErrors] = validator.Errors(input);\n\t\tconst errors =\n\t\t\tvalidationErrors\n\t\t\t\t.map((err) => {\n\t\t\t\t\treturn ` - ${errorPath(err)}: ${err.message}`;\n\t\t\t\t})\n\t\t\t\t.join(\"\\n\") || \"Unknown Validation Error\";\n\n\t\tthrow new Error(\n\t\t\t[\n\t\t\t\t`Validation Failed For ${label}`,\n\t\t\t\t`${errors}\\n`,\n\t\t\t\t\"Received Value:\",\n\t\t\t\t`${JSON.stringify(value, null, 2)}\\n`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n}\n\n/**\n * Finds a tool by name and validates the tool call arguments against its TypeBox schema\n */\nexport function validateToolCall<T extends Message.Tool>(\n\ttools: T[],\n\ttoolExecution: Message.ToolCallInFlight,\n): Message.ToolArguments<T> {\n\tconst tool = tools.find((t) => t.name === toolExecution.name);\n\tif (!tool) {\n\t\tthrow new Error(`tool \"${toolExecution.name}\" not found`);\n\t}\n\treturn validateToolArguments(tool, toolExecution);\n}\n\n/**\n * Validates tool call arguments against the tool's TypeBox schema\n */\nexport function validateToolArguments<T extends Message.Tool>(\n\ttool: T,\n\ttoolExecution: Message.ToolCallInFlight,\n): Message.ToolArguments<T> {\n\tconst args = structuredClone(toolExecution.rawArgs);\n\tnormalizeOptionalNulls(args, tool.parameters);\n\treturn validateSchema(tool.parameters, args, `Tool \"${toolExecution.name}\"`) as Message.ToolArguments<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAMA,MAAa,sBAAsB;CAClC,OAAO;CAEP,WAAW;CACX,WAAW;CACX,SAAS;CAET,eAAe;CACf,eAAe;CACf,aAAa;CAEb,eAAe;CACf,eAAe;CACf,aAAa;CACb,eAAe;CAEf,MAAM;CACN,OAAO;AACR;;;;;;;;;AAWA,MAAa,wBAAwBA,OAAK,MAAM;CAC/CA,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,KAAK;EAC5C,SAASC;CACV,CAAC;CACDD,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,SAAS;EAChD,WAAWA,OAAK,OAAO;EACvB,SAASC;CACV,CAAC;CACDD,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,SAAS;EAChD,WAAWA,OAAK,OAAO;EACvB,OAAOA,OAAK,OAAO;EACnB,SAASC;CACV,CAAC;CACDD,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,OAAO;EAC9C,WAAWA,OAAK,OAAO;EACvB,SAASA,OAAK,OAAO;EACrB,SAASC;CACV,CAAC;CACDD,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,aAAa;EACpD,WAAWA,OAAK,OAAO;EACvB,SAASC;CACV,CAAC;CACDD,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,aAAa;EACpD,WAAWA,OAAK,OAAO;EACvB,OAAOA,OAAK,OAAO;EACnB,SAASC;CACV,CAAC;CACDD,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,WAAW;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AAgB,sBACf,MACA,eAC2B;CAC3B,MAAM,OAAO,gBAAgB,cAAc,OAAO;CAClD,uBAAuB,MAAM,KAAK,UAAU;CAC5C,OAAO,eAAe,KAAK,YAAY,MAAM,SAAS,cAAc,KAAK,EAAE;AAC5E"}
1
+ {"version":3,"file":"index.mjs","names":["Type","Message.AssistantMessageSchema","Message.ToolCallSchema","Model.getModel","Model.getModels","Model.getProviders","Model.registry","Model.modelsAreEqual","Type","Model.KnownProviderEnumSchema","stream","Transcript.renderSystemPromptUpdate","Type","Model.ThinkingBudgets","Type","Model.APIMethodEnumSchema","Model.ActiveThinkingLevel","Model.optionsKey","Protocol.ProtocolAuthError","Model.thinkingTokenBudgetField","Model.optionsKey","Model.clampThinkingLevel","partialParse","Message.createAssistantMessage","Message.omitImages","Model.optionsKey","Transcript.getCurrentTools","Transcript.getDeclaredTools","Transcript.resolveTranscriptPrompt","Message.transformMessages","Transcript.resolveTranscriptTools","Transcript.renderSystemPromptUpdate","Pricing.cacheWrite1hTokens","Model.optionsKey","Thinking.isAnthropicMessagesModel","Thinking.reasoningProviderOptions","Thinking.providerThinkingLevel","Pricing.serviceTierCostMultiplier","Pricing.servedServiceTier","stream","Thinking.resolvePlan","Pricing.requestedServiceTier","Failure.strictToolLimitMessage","Failure.normalize","Protocol.stream","Protocol.complete","Protocol.resolveProtocolProvider"],"sources":["../../src/event/event.ts","../../src/llm.ts","../../src/llm/protocol.ts","../../src/llm/runtime.ts","../../src/message/transcript.ts","../../src/utils/estimate.ts","../../src/llm/shared.ts","../../src/llm/options.ts","../../src/utils/eventstream.ts","../../src/utils/helpers.ts","../../src/llm/pricing.ts","../../src/llm/provider.ts","../../src/llm/thinking.ts","../../src/utils/jsonparse.ts","../../src/utils/sanitize.ts","../../src/llm/strict.ts","../../src/llm/transform.ts","../../src/llm/stream.ts","../../src/llm/index.ts","../../src/llm/register.ts","../../src/stream.ts","../../src/utils/validation.ts"],"sourcesContent":["import Type, { type Static } from \"typebox\";\nimport * as Message from \"../message/message.ts\";\n\n// TODO @sanchitrk:\n// for delta events we can have metadata KV that a provider can use for internal state\n// similar to index what anthropic does\nexport const LLMMessageEventType = {\n\tstart: \"start\",\n\n\ttextStart: \"text.start\",\n\ttextDelta: \"text.delta\",\n\ttextEnd: \"text.end\",\n\n\tthinkingStart: \"thinking.start\",\n\tthinkingDelta: \"thinking.delta\",\n\tthinkingEnd: \"thinking.end\",\n\n\ttoolcallStart: \"toolcall.start\",\n\ttoolcallDelta: \"toolcall.delta\",\n\ttoolcallEnd: \"toolcall.end\",\n\ttoolcallFinal: \"toolcall.final\",\n\n\tdone: \"done\",\n\terror: \"error\",\n} as const;\nexport type LLMMessageEventType = (typeof LLMMessageEventType)[keyof typeof LLMMessageEventType];\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Streams should emit `start` before partial updates, then terminate with either:\n * - `done` carrying the final successful AssistantMessage, or\n * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n * and errorMessage.\n */\nexport const LLMMessageEventSchema = Type.Union([\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.start),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textEnd),\n\t\tpartIndex: Type.Number(),\n\t\tcontent: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingEnd),\n\t\tpartIndex: Type.Number(),\n\t\tcontent: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallEnd),\n\t\tpartIndex: Type.Number(),\n\t\ttoolCall: Message.ToolCallSchema,\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallFinal),\n\t\tpartIndex: Type.Number(),\n\t\ttoolCall: Message.ToolCallSchema,\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.done),\n\t\treason: Type.Union([Type.Literal(\"stop\"), Type.Literal(\"length\"), Type.Literal(\"toolUse\")]),\n\t\tmessage: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.error),\n\t\treason: Type.Union([Type.Literal(\"aborted\"), Type.Literal(\"error\")]),\n\t\terror: Message.AssistantMessageSchema,\n\t}),\n]);\nexport type LLMMessageEvent = Static<typeof LLMMessageEventSchema>;\n\n// export const AgentEventType = {\n// \t// Agent lifecycle\n// \tagentStart: \"agent.start\",\n// \tagentEnd: \"agent.end\",\n// \t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n// \tturnStart: \"turn.start\",\n// \tturnEnd: \"turn.end\",\n// \t// Message lifecycle - emitted for user, assistant message and corresponding parts\n// \tmessageStart: \"message.start\",\n\n// \tmessagePartStart: \"message.part.start\",\n// \tmessagePartUpdate: \"message.part.update\",\n// \tmessagePartEnd: \"message.part.end\",\n\n// \tmessageUpdate: \"message.update\",\n// \tmessageEnd: \"message.end\",\n// \t// Tool execution lifecycle\n// \ttoolExecutionStart: \"tool.execution.start\",\n// \ttoolExecutionUpdate: \"tool.execution.update\",\n// \ttoolExecutionEnd: \"tool.execution.end\",\n// } as const;\n// export type AgentEventType = (typeof AgentEventType)[keyof typeof AgentEventType];\n\n//\n// message parts\n// const UserMessagePart = Type.Union([Message.TextContentSchema, Message.ImageContentSchema]);\n// const AssistantMessagePart = Type.Union([\n// \tMessage.TextContentSchema,\n// \tMessage.ImageContentSchema,\n// \tMessage.ThinkingContentSchema,\n// \tMessage.ToolCallSchema,\n// ]);\n\n//\n// user message part\n// part start\n// const UserMessagePartStart = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartStart),\n// \tmessage: Message.UserMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: UserMessagePart,\n// });\n// part end\n// const UserMessagePartEnd = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartEnd),\n// \tmessage: Message.UserMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: UserMessagePart,\n// });\n\n//\n// assistant message part\n// part start\n// const AssistantMessagePartStart = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartStart),\n// \tmessage: Message.AssistantMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: AssistantMessagePart,\n// });\n// part update llm\n// const AssistantMessagePartLLMUpdate = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartUpdate),\n// \tmessage: Message.AssistantMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: AssistantMessagePart,\n// \tsource: Type.Literal(\"llm\"),\n// });\n// part update tool\n// const AssistantMessagePartToolUpdate = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartUpdate),\n// \tmessage: Message.AssistantMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: AssistantMessagePart,\n// \tsource: Type.Literal(\"tool\"),\n// });\n// part end\n// const AssistantMessagePartEnd = Type.Object({\n// \ttype: Type.Literal(AgentEventType.messagePartEnd),\n// \tmessage: Message.AssistantMessageSchema,\n// \tpartIndex: Type.Number(),\n// \tpart: AssistantMessagePart,\n// });\n\n//\n// tool exection\n// const ToolExecutionStartSchema = Type.Object({\n// \ttype: Type.Literal(AgentEventType.toolExecutionStart),\n// \tmessageId: Type.String(),\n// \tpartIndex: Type.Number(),\n// \ttoolCall: Message.ToolCallPendingPartSchema,\n// });\n// export type ToolExecutionStart = Static<typeof ToolExecutionStartSchema>;\n\n// const ToolExecutionUpdateSchema = Type.Object({\n// \ttype: Type.Literal(AgentEventType.toolExecutionUpdate),\n// \tmessageId: Type.String(),\n// \tpartIndex: Type.Number(),\n// \ttoolCall: Message.ToolCallRunningPartSchema,\n// });\n// export type ToolExecutionUpdate = Static<typeof ToolExecutionUpdateSchema>;\n\n// const ToolExecutionEndSchema = Type.Object({\n// \ttype: Type.Literal(AgentEventType.toolExecutionEnd),\n// \tmessageId: Type.String(),\n// \tpartIndex: Type.Number(),\n// \ttoolCall: Message.ToolCallTerminalPartSchema,\n// });\n// export type ToolExecutionEnd = Static<typeof ToolExecutionEndSchema>;\n\n/**\n * Events emitted by the Agent lifecycle\n * These events provide fine-grained lifecycle information for messages, turns, and tool execution.\n */\n// export const AgentEventSchema = Type.Union([\n// \t//\n// \t// Agent lifecycle\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.agentStart),\n// \t}),\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.agentEnd),\n// \t\tmessages: Type.Array(Message.MessageSchema),\n// \t}),\n// \t//\n// \t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.turnStart),\n// \t}),\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.turnEnd),\n// \t\tmessage: Message.AssistantMessageSchema,\n// \t}),\n// \t//\n// \t// Message lifecycle - emitted for user, assistant and corresponding parts\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.messageStart),\n// \t\tmessage: Message.MessageSchema,\n// \t}),\n// \t// user message parts lifecycle\n// \tType.Union([UserMessagePartStart, UserMessagePartEnd]),\n// \t//\n// \t// assistant message parts lifecycle\n// \tType.Union([\n// \t\tAssistantMessagePartStart,\n// \t\tAssistantMessagePartLLMUpdate,\n// \t\tAssistantMessagePartToolUpdate,\n// \t\tAssistantMessagePartEnd,\n// \t]),\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.messageUpdate),\n// \t\tmessage: Message.MessageSchema,\n// \t}),\n// \tType.Object({\n// \t\ttype: Type.Literal(AgentEventType.messageEnd),\n// \t\tmessage: Message.MessageSchema,\n// \t}),\n// \t//\n// \t// Tool execution lifecycle\n// \tToolExecutionStartSchema,\n// \tToolExecutionUpdateSchema,\n// \tToolExecutionEndSchema,\n// ]);\n// export type AgentEvent = Static<typeof AgentEventSchema>;\n","import * as Model from \"./model/model.ts\";\n\ntype LLM = {\n\t<TProvider extends string, TProtocol extends Model.KnownProviderEnum = Model.ProviderToProtocol<TProvider>>(\n\t\tprovider: TProvider,\n\t\tmodel: string,\n\t\toverrides?: Partial<Model.Info> & { protocol?: TProtocol },\n\t): Promise<Model.TModel<TProtocol> | undefined>;\n\tmodel: typeof Model.getModel;\n\tmodels: typeof Model.getModels;\n\tproviders: typeof Model.getProviders;\n\tregistry: typeof Model.registry;\n\tmodelsAreEqual: typeof Model.modelsAreEqual;\n};\n\nconst llmImpl = async <\n\tTProvider extends string,\n\tTProtocol extends Model.KnownProviderEnum = Model.ProviderToProtocol<TProvider>,\n>(\n\tprovider: TProvider,\n\tmodel: string,\n\toverrides?: Partial<Model.Info> & { protocol?: TProtocol },\n): Promise<Model.TModel<TProtocol> | undefined> => Model.getModel(provider, model, overrides as any);\n\nexport const llm = Object.assign(llmImpl, {\n\tmodel: Model.getModel,\n\tmodels: Model.getModels,\n\tproviders: Model.getProviders,\n\tregistry: Model.registry,\n\tmodelsAreEqual: Model.modelsAreEqual,\n}) as LLM;\n","import type { Static, TSchema } from \"typebox\";\nimport Type from \"typebox\";\nimport type * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { NamedError } from \"../utils/error.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/eventstream.ts\";\nimport type {\n\tAnthropicOptions,\n\tGitHubCopilotOptions,\n\tGoogleOptions,\n\tGoogleVertexAnthropicOptions,\n\tGoogleVertexOptions,\n\tOpenAICodexOptions,\n\tOpenAICompatibleOptions,\n\tOpenAIOptions,\n\tOpenRouterOptions,\n\tXaiOptions,\n} from \"./options.ts\";\nimport type { SharedOptions, ThinkingBudgets } from \"./shared.ts\";\nexport const ProviderProtocolNotFoundError = NamedError.create(\n\t\"ProviderProtocolNotFoundError\",\n\tType.Object({\n\t\tprotocol: Model.KnownProviderEnumSchema,\n\t}),\n);\nexport type ProviderProtocolNotFoundError = InstanceType<typeof ProviderProtocolNotFoundError>;\n\nexport const ProtocolMismatchError = NamedError.create(\n\t\"ProtocolMismatchError\",\n\tType.Object({\n\t\tactual: Model.KnownProviderEnumSchema,\n\t\texpected: Model.KnownProviderEnumSchema,\n\t}),\n);\nexport type ProtocolMismatchError = InstanceType<typeof ProtocolMismatchError>;\n\nexport const ProtocolAuthError = NamedError.create(\n\t\"ProtocolAuthError\",\n\tType.Object({\n\t\tmessage: Type.String(),\n\t\tprotocol: Type.String(),\n\t}),\n);\nexport type ProtocolAuthError = InstanceType<typeof ProtocolAuthError>;\n\nexport type CommonOptions = SharedOptions & {\n\treasoning?: Model.ActiveThinkingLevel;\n\tthinkingBudgets?: ThinkingBudgets;\n};\nexport interface OptionsByProtocol {\n\t[Model.KnownProviderEnum.openai]: OpenAIOptions;\n\t[Model.KnownProviderEnum.anthropic]: AnthropicOptions;\n\t[Model.KnownProviderEnum.google]: GoogleOptions;\n\t[Model.KnownProviderEnum.googleVertex]: GoogleVertexOptions;\n\t[Model.KnownProviderEnum.googleVertexAnthropic]: GoogleVertexAnthropicOptions;\n\t[Model.KnownProviderEnum.openaiCompatible]: OpenAICompatibleOptions;\n\t[Model.KnownProviderEnum.openaiCodex]: OpenAICodexOptions;\n\t[Model.KnownProviderEnum.githubCopilot]: GitHubCopilotOptions;\n\t[Model.KnownProviderEnum.openrouter]: OpenRouterOptions;\n\t[Model.KnownProviderEnum.xai]: XaiOptions;\n}\nexport type ProtocolWithOptions = keyof OptionsByProtocol & Model.KnownProviderEnum;\nexport type OptionsFor<TProtocol extends ProtocolWithOptions> = OptionsByProtocol[TProtocol];\n\nexport type StreamFunction<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> = (model: Model.TModel<TProtocol>, context: Message.Context, options?: Static<S>) => AssistantMessageEventStream;\n\nexport type ProtocolStreamFunction<S extends TSchema = TSchema> = (\n\tmodel: Model.Info,\n\tcontext: Message.Context,\n\toptions?: Static<S>,\n) => AssistantMessageEventStream;\n\nexport interface Protocol<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> {\n\tprotocol: TProtocol;\n\tstream: StreamFunction<TProtocol, S>;\n}\n\nexport interface RegisteredProtocol<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> {\n\tprotocol: TProtocol;\n\tstream: ProtocolStreamFunction<S>;\n}\n\ntype AnyRegisteredProtocol = RegisteredProtocol<Model.KnownProviderEnum, TSchema>;\n\ntype RegistryEntry = {\n\tprovider: AnyRegisteredProtocol;\n\tsourceId?: string;\n};\n\nconst protocolRegistry = new Map<Model.KnownProviderEnum, RegistryEntry>();\n\nfunction wrapStream<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\tprotocol: TProtocol,\n\tstream: StreamFunction<TProtocol, S>,\n): ProtocolStreamFunction<S> {\n\treturn (model, context, options) => {\n\t\tif (model.protocol !== protocol) {\n\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\tactual: model.protocol,\n\t\t\t\texpected: protocol,\n\t\t\t});\n\t\t}\n\n\t\treturn stream(model as Model.TModel<TProtocol>, context, options);\n\t};\n}\n\nexport function registerProtocolProvider<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\tprovider: Protocol<TProtocol, S>,\n\tsourceId?: string,\n): void {\n\tconst registered: RegisteredProtocol<TProtocol, S> = {\n\t\tprotocol: provider.protocol,\n\t\tstream: wrapStream(provider.protocol, provider.stream),\n\t};\n\n\tprotocolRegistry.set(provider.protocol, {\n\t\tprovider: registered as AnyRegisteredProtocol,\n\t\t...(sourceId !== undefined && { sourceId }),\n\t});\n}\n\nexport function getProtocolProvider(protocol: Model.KnownProviderEnum): AnyRegisteredProtocol | undefined {\n\treturn protocolRegistry.get(protocol)?.provider;\n}\n\nexport function resolveProtocolProvider(model: Model.Info): AnyRegisteredProtocol {\n\tconst provider = getProtocolProvider(model.protocol);\n\tif (!provider) {\n\t\tthrow new ProviderProtocolNotFoundError({\n\t\t\tprotocol: model.protocol,\n\t\t});\n\t}\n\n\treturn provider;\n}\n\nexport function getProtocolProviders(): AnyRegisteredProtocol[] {\n\treturn Array.from(protocolRegistry.values(), (entry) => entry.provider);\n}\n\nexport function stream<TProtocol extends ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: OptionsFor<TProtocol>,\n): AssistantMessageEventStream {\n\tconst provider = resolveProtocolProvider(model);\n\treturn provider.stream(model, context, options);\n}\n\nexport async function complete<TProtocol extends ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: OptionsFor<TProtocol>,\n): Promise<Message.AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function unregisterProtocolProviders(sourceId: string): void {\n\tfor (const [protocol, entry] of protocolRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tprotocolRegistry.delete(protocol);\n\t\t}\n\t}\n}\n\nexport function clearProtocolProviders(): void {\n\tprotocolRegistry.clear();\n}\n","/** Where a provider's API key may come from: its catalog `key` and `env` variable names. */\nexport type ApiKeyProvider = {\n\tenv?: string[];\n\tkey?: string;\n};\n\nexport function mergeHeaders(\n\t...headerSources: (Record<string, string | null> | undefined)[]\n): Record<string, string | null> {\n\tconst merged: Record<string, string | null> = {};\n\tfor (const headers of headerSources) {\n\t\tif (headers) {\n\t\t\tObject.assign(merged, headers);\n\t\t}\n\t}\n\treturn merged;\n}\n\n/** The provider's API key from the environment, checking its `key` then each `env` name. */\nexport function getEnvApiKey(provider: ApiKeyProvider): string | undefined {\n\tif (typeof process === \"undefined\") return;\n\n\tconst candidates = [provider.key, ...(provider.env ?? [])].filter((name): name is string => Boolean(name));\n\tfor (const name of candidates) {\n\t\tconst value = process.env[name];\n\t\tif (value) return value;\n\t}\n}\n\nexport function formatThrownError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.stack || error.message || error.name;\n\t}\n\tif (typeof error === \"string\") {\n\t\treturn error;\n\t}\n\ttry {\n\t\treturn JSON.stringify(error);\n\t} catch {\n\t\treturn String(error);\n\t}\n}\n","/*\n * @file Prompt and tool state carried by a transcript.\n *\n * `Context.systemPrompt` and `Context.tools` are the prompt and tool set at the start of the\n * conversation. Each system message changes them from its position on, so replaying them in\n * order yields the prompt and tools in effect now. Providers either send those changes in\n * place, which keeps the cached prefix, or fold them into the leading prompt and the\n * top-level tool list.\n */\n\nimport type { Context, Message, SystemMessage, Tool, ToolReference } from \"./message.ts\";\n\ntype Transcript = Pick<Context, \"systemPrompt\" | \"tools\" | \"messages\">;\n\ntype PromptChange = Pick<SystemMessage, \"content\" | \"sections\">;\n\nfunction isSystemMessage(message: Message): message is SystemMessage {\n\treturn message.role === \"system\";\n}\n\n/** Render a system message as a complete prompt: its content followed by its sections. */\nexport function renderSystemPrompt(message: PromptChange): string {\n\tconst parts = [message.content ?? \"\"];\n\tfor (const text of Object.values(message.sections ?? {})) {\n\t\tif (text !== null) parts.push(text);\n\t}\n\treturn parts.filter((part) => part.length > 0).join(\"\\n\\n\");\n}\n\n/**\n * Render a later system message sent in place. Section changes are framed by name so the\n * model can relate them to the leading prompt.\n */\nexport function renderSystemPromptUpdate(message: PromptChange): string {\n\tconst parts: string[] = [];\n\tif (message.content) parts.push(message.content);\n\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\tparts.push(\n\t\t\tvalue === null\n\t\t\t\t? `Removed system prompt section \"${name}\".`\n\t\t\t\t: `Updated system prompt section \"${name}\":\\n\\n${value}`,\n\t\t);\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n\n/**\n * The sections after every transcript change in order: replaced by name, removed by `null`, and\n * a removed section added again goes last.\n */\nexport function getCurrentSections(messages: readonly Message[]): Record<string, string> {\n\tconst sections = new Map<string, string>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\t\tif (value === null) sections.delete(name);\n\t\t\telse sections.set(name, value);\n\t\t}\n\t}\n\treturn Object.fromEntries(sections);\n}\n\n/**\n * The patch that brings `previous` sections to `current`, `null` removing one; `undefined` when\n * they match.\n */\nexport function diffSections(\n\tprevious: Readonly<Record<string, string>>,\n\tcurrent: Readonly<Record<string, string>>,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) if (previous[name] !== text) patch[name] = text;\n\tfor (const name of Object.keys(previous)) if (!Object.hasOwn(current, name)) patch[name] = null;\n\treturn Object.keys(patch).length === 0 ? undefined : patch;\n}\n\n/** The prompt after every transcript change in order: content accumulates, sections as {@link getCurrentSections}. */\nexport function getCurrentSystemPrompt(context: Pick<Context, \"systemPrompt\" | \"messages\">): string {\n\tconst content: string[] = [context.systemPrompt ?? \"\"];\n\tfor (const message of context.messages) if (isSystemMessage(message)) content.push(message.content ?? \"\");\n\treturn renderSystemPrompt({\n\t\tcontent: content.filter((part) => part.length > 0).join(\"\\n\\n\"),\n\t\tsections: getCurrentSections(context.messages),\n\t});\n}\n\nexport interface TranscriptPrompt {\n\t/** The prompt sent at the head of the request. */\n\tsystemPrompt: string;\n\t/**\n\t * Number of leading transcript system messages whose prompt changes `systemPrompt` already\n\t * holds. Every later system message sends its changes in place.\n\t */\n\tfoldedSystemMessages: number;\n}\n\n/**\n * Split the prompt between the head of the request and in-place updates.\n *\n * In place, `Context.systemPrompt` leads; without one (and without initial tools), a leading\n * system message is the prompt. Every other system message is an update. Otherwise the head\n * holds the current prompt and no update is sent, which costs the cached prefix on a change.\n */\nexport function resolveTranscriptPrompt(context: Transcript, inPlace: boolean): TranscriptPrompt {\n\tconst systemMessages = context.messages.filter(isSystemMessage);\n\tif (!inPlace) {\n\t\treturn { systemPrompt: getCurrentSystemPrompt(context), foldedSystemMessages: systemMessages.length };\n\t}\n\tconst first = context.messages[0];\n\tif (!context.systemPrompt && (context.tools ?? []).length === 0 && first && isSystemMessage(first)) {\n\t\treturn { systemPrompt: renderSystemPrompt(first), foldedSystemMessages: 1 };\n\t}\n\treturn { systemPrompt: context.systemPrompt ?? \"\", foldedSystemMessages: 0 };\n}\n\n/** The tool changes in order, led by `Context.tools` as the initial declaration. */\nfunction toolDeclarations(context: Transcript): Pick<SystemMessage, \"toolsAdded\" | \"toolsRemoved\">[] {\n\treturn [{ toolsAdded: context.tools ?? [] }, ...context.messages.filter(isSystemMessage)];\n}\n\nfunction replay(declarations: ReadonlyArray<Pick<SystemMessage, \"toolsAdded\" | \"toolsRemoved\">>): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const declaration of declarations) {\n\t\tfor (const tool of declaration.toolsRemoved ?? []) tools.delete(tool.name);\n\t\tfor (const tool of declaration.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/** The tools available after applying every transcript change in order. */\nexport function getCurrentTools(context: Transcript): Tool[] {\n\treturn replay(toolDeclarations(context));\n}\n\n/**\n * Every tool the transcript ever declared, the latest definition of each name winning. Removals\n * are ignored: a removed tool's earlier calls still replay in the form it was called in.\n */\nexport function getDeclaredTools(context: Transcript): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const declaration of toolDeclarations(context)) {\n\t\tfor (const tool of declaration.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/** Strip a tool to what the model sees, for comparison and persistence. */\nexport function toToolDeclaration(tool: Tool): Tool {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: JSON.parse(JSON.stringify(tool.parameters)) as Tool[\"parameters\"],\n\t\t...(tool.constrainedSampling === undefined ? {} : { constrainedSampling: tool.constrainedSampling }),\n\t};\n}\n\n/**\n * Whether two tools declare the same interface to the model. The JSON round trip in\n * {@link toToolDeclaration} drops typebox symbol keys and `undefined` fields and fixes the key\n * order, so comparing the serialized declarations is exact.\n */\nexport function declarationsEqual(left: Tool, right: Tool): boolean {\n\treturn JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));\n}\n\nexport interface ToolStateChanges {\n\ttoolsAdded: Tool[];\n\ttoolsRemoved: ToolReference[];\n}\n\n/** Compare two complete tool states. A changed definition is a removal followed by an addition. */\nexport function getToolStateChanges(previous: readonly Tool[], current: readonly Tool[]): ToolStateChanges {\n\tconst previousTools = new Map(previous.map((tool) => [tool.name, tool]));\n\tconst currentTools = new Map(current.map((tool) => [tool.name, tool]));\n\treturn {\n\t\ttoolsAdded: current\n\t\t\t.filter((tool) => {\n\t\t\t\tconst previousTool = previousTools.get(tool.name);\n\t\t\t\treturn previousTool === undefined || !declarationsEqual(previousTool, tool);\n\t\t\t})\n\t\t\t.map(toToolDeclaration),\n\t\ttoolsRemoved: previous\n\t\t\t.filter((tool) => {\n\t\t\t\tconst currentTool = currentTools.get(tool.name);\n\t\t\t\treturn currentTool === undefined || !declarationsEqual(tool, currentTool);\n\t\t\t})\n\t\t\t.map((tool) => ({ name: tool.name })),\n\t};\n}\n\n/** Index of the last declaration with a removal or same-name redeclaration, or -1. */\nfunction lastNonAdditiveChange(declarations: ReadonlyArray<Pick<SystemMessage, \"toolsAdded\" | \"toolsRemoved\">>) {\n\t// A name declared before counts as a redeclaration even after its removal: a removed tool\n\t// declared again later is not reliably picked up again.\n\tconst declared = new Set<string>();\n\tlet last = -1;\n\tfor (const [index, declaration] of declarations.entries()) {\n\t\tif ((declaration.toolsRemoved?.length ?? 0) > 0) last = index;\n\t\tfor (const tool of declaration.toolsAdded ?? []) {\n\t\t\tif (declared.has(tool.name)) last = index;\n\t\t\tdeclared.add(tool.name);\n\t\t}\n\t}\n\treturn last;\n}\n\n/**\n * How a transport can express tool changes after the first request.\n *\n * - `\"none\"`: only the top-level tool list exists; it always holds the current tools.\n * - `\"additions\"`: tools can be added at a later message, but not removed or redefined.\n * - `\"changes\"`: every tool, including the initial ones, is declared in place, and a later\n * declaration under the same name replaces the earlier one. Removals are not expressible on\n * the wire, so the transport announces them as text and the removed tools stay declared.\n */\nexport type TranscriptToolSupport = \"none\" | \"additions\" | \"changes\";\n\nexport interface TranscriptTools {\n\t/** Tools sent in the top-level request field. */\n\trequestTools: Tool[];\n\t/** Whether `Context.tools` is declared in place at the head of the input instead of top-level. */\n\tinitialToolsInPlace: boolean;\n\t/**\n\t * Number of leading transcript system messages whose changes `requestTools` already holds.\n\t * Every later system message declares its changes in place.\n\t */\n\tfoldedSystemMessages: number;\n}\n\n/**\n * Split tool declarations between the top-level request field and in-place changes.\n *\n * With `\"changes\"`, the top-level list stays empty and every declaration, including\n * `Context.tools`, goes in place: an in-place declaration can replace an earlier in-place one,\n * but not a top-level one. With `\"additions\"`, a removal or redefinition cannot be expressed in\n * place, so the top-level list becomes the tool state after the last such change; later\n * additions stay in place, and the cached prefix is invalidated once per removal instead of on\n * every later addition. With `\"none\"`, the top-level list is the current tool set.\n */\nexport function resolveTranscriptTools(context: Transcript, support: TranscriptToolSupport): TranscriptTools {\n\tconst declarations = toolDeclarations(context);\n\tconst transcriptMessages = declarations.length - 1;\n\tif (support === \"none\") {\n\t\treturn {\n\t\t\trequestTools: replay(declarations),\n\t\t\tinitialToolsInPlace: false,\n\t\t\tfoldedSystemMessages: transcriptMessages,\n\t\t};\n\t}\n\tif (support === \"changes\") return { requestTools: [], initialToolsInPlace: true, foldedSystemMessages: 0 };\n\tconst folded = Math.max(1, lastNonAdditiveChange(declarations) + 1);\n\treturn {\n\t\trequestTools: replay(declarations.slice(0, folded)),\n\t\tinitialToolsInPlace: false,\n\t\tfoldedSystemMessages: folded - 1,\n\t};\n}\n","/*\n * @file Cheap, provider-independent estimate of how much context a request carries.\n *\n * Used to size a response ceiling before the request goes out, so a long session\n * asks for an answer that still fits rather than taking a provider overflow error.\n * The estimate is deliberately coarse: where a real token count already exists --\n * the usage reported by the last assistant turn -- it is trusted, and only the\n * messages appended after it are estimated.\n */\n\nimport type * as Message from \"../message/message.ts\";\nimport * as Transcript from \"../message/transcript.ts\";\n\n/** Rough characters-per-token ratio across the tokenizers in use. */\nconst CHARS_PER_TOKEN = 4;\n/** A base64 image costs far more than its own text length; this is a flat stand-in. */\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nexport interface ContextUsageEstimate {\n\t/** Estimated total context tokens. */\n\ttokens: number;\n\t/** Tokens reported by the most recent applicable assistant usage block. */\n\tusageTokens: number;\n\t/** Estimated tokens after the most recent applicable assistant usage block. */\n\ttrailingTokens: number;\n\t/** Index of the applicable message that provided usage, or null when none exists. */\n\tlastUsageIndex: number | null;\n}\n\nexport function calculateContextTokens(usage: Message.Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\treturn JSON.stringify(value) ?? \"undefined\";\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nexport function estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\nfunction contentChars(content: ReadonlyArray<Message.TextContent | Message.ImageContent>): number {\n\tlet chars = 0;\n\tfor (const block of content) chars += block.type === \"text\" ? block.text.length : ESTIMATED_IMAGE_CHARS;\n\treturn chars;\n}\n\nexport function estimateContentTokens(content: ReadonlyArray<Message.TextContent | Message.ImageContent>): number {\n\treturn Math.ceil(contentChars(content) / CHARS_PER_TOKEN);\n}\n\n/**\n * A tool call costs its name, its arguments, and -- unlike providers that carry\n * results in their own messages -- the result it already holds.\n */\nfunction toolCallChars(part: Message.ToolCall): number {\n\treturn part.name.length + safeJsonStringify(part.arguments).length + toolResultChars(part);\n}\n\nfunction toolResultChars(part: Message.ToolCall): number {\n\treturn \"result\" in part && part.result ? contentChars(part.result.content) : 0;\n}\n\nexport function estimateMessageTokens(message: Message.Message): number {\n\tif (message.role === \"system\") {\n\t\treturn estimateTextTokens(Transcript.renderSystemPromptUpdate(message)) + estimateToolsTokens(message.toolsAdded);\n\t}\n\tif (message.role === \"user\") return estimateContentTokens(message.parts);\n\n\tlet chars = 0;\n\tfor (const part of message.parts) {\n\t\tswitch (part.type) {\n\t\t\tcase \"text\":\n\t\t\t\tchars += part.text.length;\n\t\t\t\tbreak;\n\t\t\tcase \"image\":\n\t\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t\t\tbreak;\n\t\t\tcase \"thinking\":\n\t\t\t\tchars += part.thinking.length;\n\t\t\t\tbreak;\n\t\t\tcase \"toolCall\":\n\t\t\t\tchars += toolCallChars(part);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn Math.ceil(chars / CHARS_PER_TOKEN);\n}\n\nfunction lastAssistantUsage(\n\tmessages: ReadonlyArray<Message.Message>,\n): { usage: Message.Usage; index: number } | undefined {\n\tlet latestPrefixTime = Number.NEGATIVE_INFINITY;\n\tlet found: { usage: Message.Usage; index: number } | undefined;\n\n\tfor (let i = 0; i < messages.length; i++) {\n\t\tconst message = messages[i]!;\n\t\tif (message.role === \"assistant\") {\n\t\t\t/*\n\t\t\t * A newer prefix message was inserted after this response (a compaction\n\t\t\t * summary, say), so its usage no longer describes the current prefix.\n\t\t\t */\n\t\t\tconst appliesToPrefix = message.time.created >= latestPrefixTime;\n\t\t\tif (\n\t\t\t\tappliesToPrefix &&\n\t\t\t\tmessage.stopReason !== \"aborted\" &&\n\t\t\t\tmessage.stopReason !== \"error\" &&\n\t\t\t\tcalculateContextTokens(message.usage) > 0\n\t\t\t) {\n\t\t\t\tfound = { usage: message.usage, index: i };\n\t\t\t}\n\t\t}\n\t\tlatestPrefixTime = Math.max(latestPrefixTime, message.time.created);\n\t}\n\n\treturn found;\n}\n\nfunction estimateMessages(messages: ReadonlyArray<Message.Message>): ContextUsageEstimate {\n\tconst usage = lastAssistantUsage(messages);\n\tif (usage) {\n\t\tconst usageTokens = calculateContextTokens(usage.usage);\n\t\t// Tool results are attached to the assistant turn after its usage was\n\t\t// reported, not sent as separate messages. Only its output is counted.\n\t\tconst latest = messages[usage.index] as Message.AssistantMessage;\n\t\tlet resultChars = 0;\n\t\tfor (const part of latest.parts) {\n\t\t\tif (part.type === \"toolCall\") resultChars += toolResultChars(part);\n\t\t}\n\t\tlet trailingTokens = Math.ceil(resultChars / CHARS_PER_TOKEN);\n\t\tfor (let i = usage.index + 1; i < messages.length; i++) trailingTokens += estimateMessageTokens(messages[i]!);\n\t\treturn { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usage.index };\n\t}\n\n\tlet tokens = 0;\n\tfor (const message of messages) tokens += estimateMessageTokens(message);\n\treturn { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };\n}\n\nfunction estimateToolsTokens(tools: ReadonlyArray<Message.Tool> | undefined): number {\n\tif (!tools || tools.length === 0) return 0;\n\treturn estimateTextTokens(safeJsonStringify(tools));\n}\n\nexport function estimateContextTokens(context: Message.Context): ContextUsageEstimate {\n\tconst estimate = estimateMessages(context.messages);\n\n\t/*\n\t * Reported usage already includes the system prompt and the tools that were\n\t * live at the time. Prompt and tool changes since arrive as system messages\n\t * after it, which the trailing estimate already counts.\n\t */\n\tif (estimate.lastUsageIndex !== null) return estimate;\n\n\tconst prefixTokens =\n\t\t(context.systemPrompt ? estimateTextTokens(context.systemPrompt) : 0) + estimateToolsTokens(context.tools);\n\n\treturn {\n\t\ttokens: estimate.tokens + prefixTokens,\n\t\tusageTokens: estimate.usageTokens,\n\t\ttrailingTokens: estimate.trailingTokens + prefixTokens,\n\t\tlastUsageIndex: estimate.lastUsageIndex,\n\t};\n}\n","import { Type, type Static } from \"typebox\";\nimport type * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { estimateContextTokens } from \"../utils/estimate.ts\";\n\nexport const CacheRetention = Type.Union([Type.Literal(\"none\"), Type.Literal(\"short\"), Type.Literal(\"long\")]);\nexport type CacheRetention = Static<typeof CacheRetention>;\n\nexport const GenerationOptions = Type.Object({\n\tmaxTokens: Type.Optional(Type.Number()),\n\ttemperature: Type.Optional(Type.Number()),\n\tcacheRetention: Type.Optional(CacheRetention),\n});\n\nexport const HelperOptions = Type.Object({\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tsessionId: Type.Optional(Type.String()),\n\tapiKey: Type.Optional(Type.String()),\n\ttimeoutMs: Type.Optional(Type.Number()),\n\t/** Abort a stream that goes this long without a chunk, so a dead connection fails instead of waiting out `timeoutMs`. */\n\tidleTimeoutMs: Type.Optional(Type.Number()),\n\tmaxRetries: Type.Optional(Type.Number()),\n\tsignal: Type.Optional(Type.Unsafe<AbortSignal>({})),\n\tonPayload: Type.Optional(\n\t\tType.Unsafe<(payload: unknown, model: Model.TModel<Model.KnownProviderEnum>) => Promise<unknown>>({}),\n\t),\n\tmetadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n});\n\nexport const ThinkingBudgets = Model.ThinkingBudgets;\nexport type ThinkingBudgets = Model.ThinkingBudgets;\n\nexport const SharedOptions = Type.Evaluate(Type.Intersect([GenerationOptions, HelperOptions]));\nexport type SharedOptions = Static<typeof SharedOptions>;\n\n/** Headroom left for the prompt when sizing a response against the context window. */\nconst CONTEXT_SAFETY_TOKENS = 4096;\n// OpenRouter counts the input with its own tokenizer and rejects input + max_tokens above the\n// window before routing. It counted prose up to 12% above the provider's count.\nconst CONTEXT_SAFETY_RATIO = 0.15;\n// The 15% margin is kept only while it leaves at least this much output. Otherwise (a nearly full\n// large window, or any small window such as a 32k local model) only the fixed margin is kept, and\n// output is capped at this size so an OpenRouter overcount still fits for a while before compaction.\nconst MIN_OUTPUT_WITH_RATIO_MARGIN = 32768;\n// The smallest ceiling OpenAI accepts (`max_output_tokens` >= 16). Below it an\n// overflowing prompt fails as an invalid parameter instead of a context overflow.\nconst MIN_MAX_TOKENS = 16;\n\n/**\n * The model's own ceiling, unless the caller named a smaller one.\n *\n * No heuristic cap here: a catalog whose `maxTokens` spans the whole context\n * window is handled by {@link clampMaxTokensToContext}, which knows what the\n * prompt actually costs and does not have to guess.\n */\nexport function applyDefaultMaxTokens<TOptions extends SharedOptions = SharedOptions>(\n\tmodel: Model.TModel<Model.KnownProviderEnum>,\n\toptions?: TOptions,\n): TOptions & Pick<SharedOptions, \"maxTokens\"> {\n\treturn {\n\t\t...options,\n\t\tmaxTokens: options?.maxTokens ?? (model.maxTokens > 0 ? model.maxTokens : undefined),\n\t} as TOptions & Pick<SharedOptions, \"maxTokens\">;\n}\n\n/**\n * Shrink a response ceiling to what is left of the context window.\n *\n * Without this a long session asks for an answer that cannot fit and takes a\n * provider overflow error instead of a shorter answer. The margin leaves room\n * for the input being counted higher than estimated.\n */\nexport function clampMaxTokensToContext(\n\tmodel: Model.TModel<Model.KnownProviderEnum>,\n\tcontext: Message.Context,\n\tmaxTokens: number,\n): number {\n\tif (model.contextWindow <= 0) return Math.max(MIN_MAX_TOKENS, maxTokens);\n\tconst input = estimateContextTokens(context).tokens;\n\tconst margin = Math.max(CONTEXT_SAFETY_TOKENS, Math.ceil(input * CONTEXT_SAFETY_RATIO));\n\tlet room = model.contextWindow - input - margin;\n\tif (room < MIN_OUTPUT_WITH_RATIO_MARGIN) {\n\t\troom = Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN, model.contextWindow - input - CONTEXT_SAFETY_TOKENS);\n\t}\n\treturn Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, room));\n}\n\n/** Tokens always left for the answer when a thinking budget shares the response ceiling. */\nexport const MIN_ANSWER_TOKENS = 1024;\n\n/**\n * Default thinking budget per level, in tokens.\n *\n * Absolute rather than a fraction of `model.maxTokens`: a fraction turns one\n * \"medium\" setting into wildly different budgets across models, and a budget is\n * a property of how hard the task is, not of how large the model's ceiling is.\n */\nexport const DEFAULT_THINKING_BUDGETS = {\n\tminimal: 1024,\n\tlow: 2048,\n\tmedium: 8192,\n\thigh: 16384,\n} as const;\n\ntype BaseThinkingLevel = keyof typeof DEFAULT_THINKING_BUDGETS;\n\n/** `xhigh` and `max` fall back to `high`'s budget unless one is configured for them. */\nfunction baseThinkingLevel(level: Model.ActiveThinkingLevel): BaseThinkingLevel {\n\treturn level === \"xhigh\" || level === \"max\" ? \"high\" : level;\n}\n\nexport function thinkingBudgetForLevel(level: Model.ActiveThinkingLevel, budgets?: ThinkingBudgets): number {\n\tconst base = baseThinkingLevel(level);\n\treturn budgets?.[level] ?? budgets?.[base] ?? DEFAULT_THINKING_BUDGETS[base];\n}\n\n/** Cap a thinking budget so at least {@link MIN_ANSWER_TOKENS} remain under a shared response ceiling. */\nexport function clampThinkingBudgetToAnswerRoom(thinkingBudget: number, ceiling: number): number {\n\treturn Math.min(thinkingBudget, Math.max(0, ceiling - MIN_ANSWER_TOKENS));\n}\n\n/**\n * Fit a thinking budget and an answer inside one response ceiling.\n *\n * The caller's `maxTokens` is the room they want for the *answer*, so thinking is\n * added on top and the total is clamped to the model's ceiling. When even that\n * does not fit, the budget gives way -- never the answer.\n */\nexport function adjustMaxTokensForThinking(\n\t// Undefined means no explicit caller cap. Use the model cap and fit thinking inside it.\n\tbaseMaxTokens: number | undefined,\n\tmodelMaxTokens: number,\n\tlevel: Model.ActiveThinkingLevel,\n\tbudgets?: ThinkingBudgets,\n): { maxTokens: number; thinkingBudget: number } {\n\tlet thinkingBudget = thinkingBudgetForLevel(level, budgets);\n\tconst maxTokens =\n\t\tbaseMaxTokens === undefined ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);\n\n\tif (maxTokens <= thinkingBudget) {\n\t\tthinkingBudget = clampThinkingBudgetToAnswerRoom(thinkingBudget, maxTokens);\n\t}\n\n\treturn { maxTokens, thinkingBudget };\n}\n","import type { AnthropicLanguageModelOptions, AnthropicProviderSettings } from \"@ai-sdk/anthropic\";\nimport type { GoogleGenerativeAIProviderSettings, GoogleLanguageModelOptions } from \"@ai-sdk/google\";\nimport type { GoogleVertexProviderSettings } from \"@ai-sdk/google-vertex\";\nimport type { GoogleVertexAnthropicProviderSettings } from \"@ai-sdk/google-vertex/anthropic\";\nimport type {\n\tOpenAILanguageModelChatOptions,\n\tOpenAILanguageModelCompletionOptions,\n\tOpenAILanguageModelResponsesOptions,\n\tOpenAIProviderSettings,\n} from \"@ai-sdk/openai\";\nimport type {\n\tOpenAICompatibleLanguageModelChatOptions,\n\tOpenAICompatibleLanguageModelCompletionOptions,\n\tOpenAICompatibleProviderSettings,\n} from \"@ai-sdk/openai-compatible\";\nimport type { XaiLanguageModelResponsesOptions, XaiProviderSettings } from \"@ai-sdk/xai\";\nimport type { OpenRouterProviderOptions, OpenRouterProviderSettings } from \"@openrouter/ai-sdk-provider\";\nimport { Type, type Static } from \"typebox\";\nimport * as Model from \"../model/model.ts\";\nimport type { GitHubCopilotProviderSettings } from \"../providers/github-copilot/index.ts\";\nimport type { OpenAICodexProviderSettings } from \"../providers/openai-codex/index.ts\";\nimport type { ResponsesLanguageModelOptions } from \"../providers/responses/model.ts\";\nimport type * as Protocol from \"./protocol.ts\";\nimport { SharedOptions, ThinkingBudgets } from \"./shared.ts\";\n\nexport const Options = Type.Evaluate(\n\tType.Intersect([\n\t\tSharedOptions,\n\t\tType.Object({\n\t\t\tbaseURL: Type.Optional(Type.String()),\n\t\t\tmethod: Type.Optional(Model.APIMethodEnumSchema),\n\t\t\tmodelId: Type.Optional(Type.String()),\n\t\t\treasoning: Type.Optional(Model.ActiveThinkingLevel),\n\t\t\tthinkingBudgets: Type.Optional(ThinkingBudgets),\n\t\t\ttoolChoice: Type.Optional(Type.Any()),\n\t\t\tactiveTools: Type.Optional(Type.Array(Type.String())),\n\t\t\tfactoryOptions: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\t\t\tproviderOptions: Type.Optional(Type.Record(Type.String(), Type.Record(Type.String(), Type.Unknown()))),\n\t\t}),\n\t]),\n);\n\nexport type ProviderOptionBag = Record<string, Record<string, unknown> | undefined>;\n\n/** Caller options as the transport sees them, after protocol-level fields are merged in. */\nexport type RuntimeOptions = Options & Protocol.CommonOptions;\n\nexport type AISDKOptions<\n\tTFactoryOptions,\n\tTProviderOptions extends ProviderOptionBag = ProviderOptionBag,\n> = Protocol.CommonOptions & {\n\tbaseURL?: string;\n\tmethod?: Model.APIMethodEnum;\n\tmodelId?: string;\n\ttoolChoice?: unknown;\n\tactiveTools?: string[];\n\tfactoryOptions?: Partial<TFactoryOptions> & Record<string, unknown>;\n\tproviderOptions?: TProviderOptions & ProviderOptionBag;\n};\n\ntype OpenAILanguageOptions =\n\t| OpenAILanguageModelResponsesOptions\n\t| OpenAILanguageModelChatOptions\n\t| OpenAILanguageModelCompletionOptions;\ntype OpenAICompatibleLanguageOptions =\n\t| OpenAICompatibleLanguageModelChatOptions\n\t| OpenAICompatibleLanguageModelCompletionOptions;\n// xAI serves only the Responses API.\ntype XaiLanguageOptions = XaiLanguageModelResponsesOptions;\ntype GitHubCopilotLanguageOptions =\n\t| AnthropicLanguageModelOptions\n\t| ResponsesLanguageModelOptions\n\t| OpenAICompatibleLanguageModelChatOptions;\n\nexport type OpenAIOptions = AISDKOptions<OpenAIProviderSettings, { openai?: OpenAILanguageOptions }>;\nexport type AnthropicOptions = AISDKOptions<AnthropicProviderSettings, { anthropic?: AnthropicLanguageModelOptions }>;\nexport type GoogleOptions = AISDKOptions<GoogleGenerativeAIProviderSettings, { google?: GoogleLanguageModelOptions }>;\nexport type GoogleVertexOptions = AISDKOptions<GoogleVertexProviderSettings>;\nexport type GoogleVertexAnthropicOptions = AISDKOptions<GoogleVertexAnthropicProviderSettings>;\nexport type OpenAICompatibleOptions = AISDKOptions<\n\tOpenAICompatibleProviderSettings,\n\t{ \"openai-compatible\"?: OpenAICompatibleLanguageOptions }\n>;\nexport type OpenAICodexOptions = AISDKOptions<\n\tOpenAICodexProviderSettings,\n\t{ \"openai-codex\"?: ResponsesLanguageModelOptions }\n>;\nexport type GitHubCopilotOptions = AISDKOptions<\n\tGitHubCopilotProviderSettings,\n\t{ \"github-copilot\"?: GitHubCopilotLanguageOptions }\n>;\nexport type OpenRouterOptions = AISDKOptions<OpenRouterProviderSettings, { openrouter?: OpenRouterProviderOptions }>;\nexport type XaiOptions = AISDKOptions<XaiProviderSettings, { xai?: XaiLanguageOptions }>;\n\nexport type Options = Static<typeof Options>;\n","/**\n * @description Defines the Generic event stream class for async iteration.\n */\n\nimport type * as Event from \"../event/event.ts\";\nimport type * as Message from \"../message/message.ts\";\n\n// Implements the async iterator pattern\n// LLM output are streams of events for consuming\n// This class helps with that by acting like buffer data structure to manage the streams\n// for producer and consumer\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue: T[] = [];\n\tprivate waiting: ((value: IteratorResult<T>) => void)[] = [];\n\tprivate done = false;\n\tprivate readonly finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\tprivate readonly isComplete: (event: T) => boolean;\n\tprivate readonly extractResult: (event: T) => R;\n\n\tconstructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R) {\n\t\tthis.isComplete = isComplete;\n\t\tthis.extractResult = extractResult;\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.shift();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.push(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.shift()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.shift()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<Event.LLMMessageEvent, Message.AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n","import Type, { type TUnsafe } from \"typebox\";\n\n/**\n * `T` with every `undefined`-valued key turned into an optional key.\n */\ntype Compact<T> = {\n\t[K in keyof T as undefined extends T[K] ? never : K]: T[K];\n} & {\n\t[K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined>;\n};\n\n/**\n * Drops keys whose value is `undefined`.\n *\n * Under `exactOptionalPropertyTypes` an explicit `undefined` is not assignable to an optional\n * property, so a literal built from optional inputs has to omit the key rather than pass it\n * through. Only worth reaching for when a literal forwards many optional values at once — for a\n * handful of keys a conditional spread reads better.\n */\nexport function compact<T extends object>(value: T): Compact<T> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, entry] of Object.entries(value)) {\n\t\tif (entry !== undefined) result[key] = entry;\n\t}\n\treturn result as Compact<T>;\n}\n\n/**\n * Creates a string enum schema compatible with Google's API and other providers\n * that don't support anyOf/const patterns.\n *\n * @example\n * const OperationSchema = StringEnum([\"add\", \"subtract\", \"multiply\", \"divide\"], {\n * description: \"The operation to perform\"\n * });\n *\n * type Operation = Static<typeof OperationSchema>; // \"add\" | \"subtract\" | \"multiply\" | \"divide\"\n */\nexport function StringEnum<T extends readonly string[]>(\n\tvalues: T,\n\toptions?: { description?: string; default?: T[number] },\n): TUnsafe<T[number]> {\n\treturn Type.Unsafe<T[number]>({\n\t\ttype: \"string\",\n\t\tenum: values as any,\n\t\t...(options?.description && { description: options.description }),\n\t\t...(options?.default && { default: options.default }),\n\t});\n}\n","/*\n * @file What a turn actually costs, as opposed to what it was asked to cost.\n *\n * Two pricing inputs are only knowable once the provider answers: the service\n * tier a request was *served* at, which may differ from the one requested, and\n * the retention split of Anthropic cache writes, which are billed at different\n * rates. Both arrive as provider metadata, so both are read here rather than in\n * the transport.\n */\n\nimport * as Model from \"../model/model.ts\";\n\n/** Protocols that price a request by the OpenAI service tier it was served at. */\nconst SERVICE_TIER_KEYS = new Set([\"openai\", \"openai-codex\"]);\n\nfunction asString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction bag(value: unknown, key: string): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null) return undefined;\n\tconst nested = (value as Record<string, unknown>)[key];\n\treturn typeof nested === \"object\" && nested !== null ? (nested as Record<string, unknown>) : undefined;\n}\n\n/** The tier the request asked for, before the provider says which one it used. */\nexport function requestedServiceTier(\n\tmodel: Model.Info,\n\toptions: { readonly factoryOptions?: Record<string, unknown> },\n\tproviderOptions: Record<string, Record<string, unknown> | undefined>,\n): string | undefined {\n\tconst key = Model.optionsKey(model);\n\tif (!SERVICE_TIER_KEYS.has(key)) return undefined;\n\treturn asString(\n\t\tproviderOptions[key]?.serviceTier ?? options.factoryOptions?.serviceTier ?? model.options?.serviceTier,\n\t);\n}\n\n/**\n * The tier the response was actually served at, which is what gets billed.\n *\n * A `\"default\"` response to an explicit flex or priority request still bills at\n * the requested tier: the Codex backend reports the fallback it used, not the\n * rate it charged.\n */\nexport function servedServiceTier(\n\tmodel: Model.Info,\n\trequested: string | undefined,\n\tproviderMetadata: unknown,\n): string | undefined {\n\tconst key = Model.optionsKey(model);\n\tif (!SERVICE_TIER_KEYS.has(key)) return undefined;\n\tconst served = asString(bag(providerMetadata, key)?.serviceTier);\n\tif (key === \"openai-codex\" && served === \"default\" && (requested === \"flex\" || requested === \"priority\")) {\n\t\treturn requested;\n\t}\n\treturn served ?? requested;\n}\n\nexport function serviceTierCostMultiplier(model: Model.Info, serviceTier: string | undefined): number {\n\treturn serviceTier === undefined ? 1 : (model.cost.serviceTierMultipliers?.[serviceTier] ?? 1);\n}\n\n/**\n * Tokens Anthropic wrote with 1h retention, out of the total cache write.\n *\n * The AI SDK does not model the split, but it passes Anthropic's raw usage object\n * through untouched, so read it from there.\n */\nexport function cacheWrite1hTokens(providerMetadata: unknown): number | undefined {\n\tfor (const key of [\"anthropic\", \"google-vertex-anthropic\"]) {\n\t\tconst creation = bag(bag(bag(providerMetadata, key), \"usage\"), \"cache_creation\");\n\t\tconst tokens = creation?.ephemeral_1h_input_tokens;\n\t\tif (typeof tokens === \"number\") return tokens;\n\t}\n\treturn undefined;\n}\n\nexport * as Pricing from \"./pricing.ts\";\n","import type { LanguageModel } from \"ai\";\nimport * as Model from \"../model/model.ts\";\nimport type { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { loadProviderFactory, packageForModel, resolveLanguageModel } from \"./registry.ts\";\nimport { getEnvApiKey, mergeHeaders } from \"./runtime.ts\";\n\nfunction cleanHeaders(headers: Record<string, string | null>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value !== null) result[key] = value;\n\t}\n\treturn result;\n}\n\nfunction resolveBaseURL(model: Model.Info, options: Options): string | undefined {\n\treturn (options.baseURL ?? model.api?.url ?? model.baseUrl) || undefined;\n}\n\n/**\n * Inject a thinking-token budget the AI SDK has no field for.\n *\n * `@ai-sdk/openai-compatible` validates provider options against a closed schema,\n * so an endpoint-specific budget field cannot travel that way. `transformRequestBody`\n * is the SDK's own hook for exactly this: the last edit before the body is sent.\n */\nexport function thinkingTokenBudgetTransform(\n\tfield: string,\n\tbudget: number,\n\texisting: unknown,\n): (body: Record<string, unknown>) => Record<string, unknown> {\n\tconst chain =\n\t\ttypeof existing === \"function\"\n\t\t\t? (existing as (body: Record<string, unknown>) => Record<string, unknown>)\n\t\t\t: undefined;\n\treturn (body) => {\n\t\tconst transformed = chain ? chain(body) : body;\n\t\treturn { ...transformed, [field]: budget };\n\t};\n}\n\nexport async function resolveAISDKLanguageModel(\n\tmodel: Model.Info,\n\toptions: Options,\n\tthinkingTokenBudget?: number,\n): Promise<LanguageModel> {\n\tconst npm = packageForModel(model);\n\tconst createProvider = await loadProviderFactory(npm);\n\tconst apiKey = options.apiKey ?? getEnvApiKey(model.provider);\n\tconst headers = cleanHeaders(mergeHeaders(model.headers, options.headers));\n\tconst baseURL = resolveBaseURL(model, options);\n\n\tconst factoryOptions: Record<string, unknown> = {\n\t\t...model.options,\n\t\t...options.factoryOptions,\n\t};\n\n\tif (apiKey) factoryOptions.apiKey = apiKey;\n\tif (Object.keys(headers).length > 0) factoryOptions.headers = headers;\n\tif (baseURL) factoryOptions.baseURL = baseURL;\n\n\tif (npm === \"@ai-sdk/openai-compatible\") {\n\t\tif (!baseURL) {\n\t\t\tthrow new Protocol.ProtocolAuthError({\n\t\t\t\tprotocol: model.protocol,\n\t\t\t\tmessage: \"AI SDK openai-compatible transport requires model.baseUrl, model.api.url, or options.baseURL\",\n\t\t\t});\n\t\t}\n\t\tfactoryOptions.name ??= model.provider.id;\n\t\tfactoryOptions.includeUsage ??= true;\n\n\t\tconst budgetField = Model.thinkingTokenBudgetField(model);\n\t\tif (budgetField && thinkingTokenBudget !== undefined && thinkingTokenBudget > 0) {\n\t\t\tfactoryOptions.transformRequestBody = thinkingTokenBudgetTransform(\n\t\t\t\tbudgetField,\n\t\t\t\tthinkingTokenBudget,\n\t\t\t\tfactoryOptions.transformRequestBody,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst cacheDisabled =\n\t\toptions.cacheRetention === \"none\" ||\n\t\t(typeof process !== \"undefined\" && process.env.CODEWORK_CACHE_RETENTION === \"none\");\n\t// Our own Responses model (Codex, Copilot `/responses`) reads image support from compat.\n\tconst responsesCompat = () => ({\n\t\t...model.compat,\n\t\tsupportsImages: model.input.includes(\"image\"),\n\t\t...(typeof factoryOptions.compat === \"object\" && factoryOptions.compat !== null ? factoryOptions.compat : {}),\n\t});\n\n\tif (npm === \"@codeworksh/ai-sdk-openai-codex\") {\n\t\t// Codex uses the session id for the session-id header and prompt cache key.\n\t\tif (options.sessionId && !cacheDisabled) factoryOptions.sessionId ??= options.sessionId;\n\t\tfactoryOptions.compat = responsesCompat();\n\t}\n\n\tif (npm === \"@codeworksh/ai-sdk-github-copilot\") {\n\t\t// Copilot uses the session id for X-Interaction-Id request grouping, and as the\n\t\t// Responses prompt cache key.\n\t\tif (options.sessionId) factoryOptions.sessionId ??= options.sessionId;\n\t\tif (options.sessionId && !cacheDisabled) factoryOptions.promptCacheKey ??= options.sessionId;\n\t\tfactoryOptions.compat = responsesCompat();\n\n\t\tconst budgetField = Model.thinkingTokenBudgetField(model);\n\t\tif (budgetField && thinkingTokenBudget !== undefined && thinkingTokenBudget > 0) {\n\t\t\tfactoryOptions.transformRequestBody = thinkingTokenBudgetTransform(\n\t\t\t\tbudgetField,\n\t\t\t\tthinkingTokenBudget,\n\t\t\t\tfactoryOptions.transformRequestBody,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst provider = createProvider(factoryOptions);\n\treturn resolveLanguageModel(provider, model, options.method);\n}\n","/*\n * @file How a thinking level becomes a budget, a ceiling, and provider options.\n *\n * Every provider spells reasoning differently -- an effort string, a token budget,\n * a level -- but they all draw from the same two numbers, and those two numbers\n * are decided together because the budget and the answer share one ceiling.\n */\n\nimport * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport type { ProviderOptionBag, RuntimeOptions } from \"./options.ts\";\nimport {\n\tadjustMaxTokensForThinking,\n\tclampMaxTokensToContext,\n\tclampThinkingBudgetToAnswerRoom,\n\tthinkingBudgetForLevel,\n} from \"./shared.ts\";\n\n/**\n * The thinking budget and response ceiling for one request, resolved together.\n *\n * A budget and the answer share `model.maxTokens`, so neither can be decided\n * alone. `maxTokens` is what the request should ask for; `budget` is what fits\n * inside it once the answer keeps its floor.\n */\nexport interface Plan {\n\treadonly level: Model.ThinkingLevel;\n\t/** Fitted tokens, or Google's -1 sentinel for provider-managed dynamic thinking. */\n\treadonly budget: number;\n\treadonly maxTokens: number | undefined;\n\t/** The caller configured a budget for this level, rather than inheriting a default. */\n\treadonly explicit: boolean;\n}\n\n/** Anthropic rejects an enabled thinking block whose budget is under 1024 tokens. */\nconst ANTHROPIC_MIN_THINKING_BUDGET = 1024;\n\n/**\n * The smallest budget this model will accept, for providers that take one at all.\n *\n * Adaptive models are exempt: they are sent an effort level and no budget, so\n * there is no floor to fall under.\n */\n/** Whether the model talks Anthropic Messages — directly, or via Copilot's `/v1/messages` route. */\nexport function isAnthropicMessagesModel(model: Model.Info): boolean {\n\tconst key = Model.optionsKey(model);\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") return true;\n\treturn key === \"github-copilot\" && model.api?.method === Model.APIMethodEnum.messages;\n}\n\nfunction minimumThinkingBudget(model: Model.Info): number {\n\tif (!isAnthropicMessagesModel(model)) return 0;\n\treturn model.compat?.forceAdaptiveThinking ? 0 : ANTHROPIC_MIN_THINKING_BUDGET;\n}\n\nexport function resolvePlan(model: Model.Info, context: Message.Context, options: RuntimeOptions): Plan {\n\tconst clampToContext = (maxTokens: number | undefined) =>\n\t\tmaxTokens === undefined ? undefined : clampMaxTokensToContext(model, context, maxTokens);\n\n\tconst requested = options.reasoning;\n\tconst level = requested ? Model.clampThinkingLevel(model, requested) : \"off\";\n\tif (level === \"off\") return { level, budget: 0, maxTokens: clampToContext(options.maxTokens), explicit: false };\n\n\tconst budgets = { ...model.thinkingBudgets, ...options.thinkingBudgets };\n\tconst explicit = options.thinkingBudgets?.[level] !== undefined;\n\tconst key = Model.optionsKey(model);\n\tconst usesGoogleBudget = (key === \"google\" || key === \"google-vertex\") && !model.compat?.supportsThinkingLevel;\n\tconst requestedBudget = thinkingBudgetForLevel(level, budgets);\n\n\t// A catalog entry without a ceiling gives the fit nothing to work against.\n\tif (model.maxTokens <= 0) {\n\t\treturn { level, budget: requestedBudget, maxTokens: clampToContext(options.maxTokens), explicit };\n\t}\n\n\t// Google's -1 is a dynamic-thinking sentinel, not a negative token count.\n\tconst dynamic = usesGoogleBudget && requestedBudget === -1;\n\tconst adjusted = adjustMaxTokensForThinking(options.maxTokens, model.maxTokens, level, {\n\t\t[level]: dynamic ? 0 : requestedBudget,\n\t});\n\tconst maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);\n\n\t/*\n\t * Preserve an explicit small answer allowance when it fits, and apply the\n\t * 1024-token reserve only when context pressure reduces it, rather than always:\n\t * aikit deliberately permits small answers.\n\t */\n\tconst budget =\n\t\tmaxTokens < adjusted.maxTokens\n\t\t\t? clampThinkingBudgetToAnswerRoom(adjusted.thinkingBudget, maxTokens)\n\t\t\t: adjusted.thinkingBudget;\n\n\t/*\n\t * A budget below the provider's own floor is not a smaller amount of thinking,\n\t * it is an invalid request. When the room has gone -- a nearly full window is\n\t * the way there -- the turn goes out without thinking rather than not at all.\n\t */\n\tif (budget < minimumThinkingBudget(model)) {\n\t\treturn { level: \"off\", budget: 0, maxTokens, explicit };\n\t}\n\n\treturn { level, budget: dynamic ? -1 : budget, maxTokens, explicit };\n}\n\ntype GoogleThinkingLevel = \"minimal\" | \"low\" | \"medium\" | \"high\";\n\nfunction googleThinkingLevel(mapped: string): GoogleThinkingLevel {\n\treturn mapped === \"xhigh\" || mapped === \"max\" ? \"high\" : (mapped as GoogleThinkingLevel);\n}\n\n/**\n * Turn thinking off, in the provider's own words.\n *\n * Several models reason by default, so declining to *ask* for thinking is not the\n * same as asking for none: the caller ends up paying output tokens for reasoning\n * they never requested.\n *\n * OpenRouter is deliberately left alone. It fronts hundreds of third-party\n * endpoints whose support varies per endpoint -- several reject the request\n * outright with \"reasoning is mandatory for this endpoint and cannot be disabled\"\n * -- so its reasoning stays pass-through.\n */\nexport function disabledProviderOptions(model: Model.Info): ProviderOptionBag {\n\t// A model that cannot reason has nothing to switch off.\n\tif (!model.reasoning) return {};\n\n\tconst key = Model.optionsKey(model);\n\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\t// `null` means this model cannot disable thinking and rejects the request. It\n\t\t// reasons at the API's default effort regardless, so name that effort on the\n\t\t// wire and the response records the level the model really ran at.\n\t\tif (model.thinkingLevelMap?.off === null) return { [key]: { effort: ANTHROPIC_DEFAULT_EFFORT } };\n\t\treturn { [key]: { thinking: { type: \"disabled\" } } };\n\t}\n\n\tif (key === \"github-copilot\") {\n\t\t// Copilot accepts `thinking: {type:\"disabled\"}` on the Messages route, except for a\n\t\t// Claude that cannot disable thinking: it rejects the request, so the field is left\n\t\t// out and Copilot's default applies. On Responses only the models mapped to an off\n\t\t// effort take one, and the chat route has no reasoning control at all.\n\t\tconst off = model.thinkingLevelMap?.off;\n\t\tif (model.api?.method === Model.APIMethodEnum.messages) {\n\t\t\treturn off === null ? {} : { [key]: { thinking: { type: \"disabled\" } } };\n\t\t}\n\t\tif (model.api?.method === Model.APIMethodEnum.responses && typeof off === \"string\") {\n\t\t\treturn { [key]: { reasoningEffort: off } };\n\t\t}\n\t\treturn {};\n\t}\n\n\tif (key === \"google\" || key === \"google-vertex\") {\n\t\tif (model.thinkingLevelMap?.off === null) return {};\n\t\treturn { [key]: { thinkingConfig: googleDisabledThinkingConfig(model) } };\n\t}\n\n\tif (key === \"openai\" || key === \"xai\" || key === \"openai-codex\") {\n\t\tconst off = model.thinkingLevelMap?.off;\n\t\t// `null` means this model cannot disable reasoning; sending an effort it\n\t\t// does not accept would fail the request outright.\n\t\tif (off === null) return {};\n\t\treturn { [key]: { reasoningEffort: off ?? \"none\" } };\n\t}\n\n\treturn {};\n}\n\n/**\n * Gemini 3 Pro cannot disable thinking, and Gemini 3 Flash and Gemma 4 cannot\n * fully disable it either. For those, ask for the lowest level and leave\n * `includeThoughts` off so the thinking stays hidden. Gemini 2.x takes a zero budget.\n */\nfunction googleDisabledThinkingConfig(model: Model.Info): Record<string, unknown> {\n\tif (model.compat?.supportsThinkingLevel) return { thinkingLevel: model.thinkingLevelMap?.off ?? \"minimal\" };\n\treturn { thinkingBudget: 0 };\n}\n\ntype AnthropicEffort = \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n// TODO(sanchitrk): should we go lower here like low or medium?\n/** The effort Anthropic applies when a request names none. */\nconst ANTHROPIC_DEFAULT_EFFORT: AnthropicEffort = \"high\";\n\n/**\n * The effort level an adaptive Claude model reasons at.\n *\n * A model's own `thinkingLevelMap` wins where it has an opinion -- that is where\n * per-model support for `xhigh` and `max` is recorded -- and the rest collapse onto\n * the three levels every adaptive model accepts.\n */\nfunction anthropicEffort(model: Model.Info, level: Model.ActiveThinkingLevel): AnthropicEffort {\n\tconst mapped = model.thinkingLevelMap?.[level];\n\tif (typeof mapped === \"string\") return mapped as AnthropicEffort;\n\n\tswitch (level) {\n\t\tcase \"minimal\":\n\t\tcase \"low\":\n\t\t\treturn \"low\";\n\t\tcase \"medium\":\n\t\t\treturn \"medium\";\n\t\tcase \"xhigh\":\n\t\t\treturn \"xhigh\";\n\t\tcase \"max\":\n\t\t\treturn \"max\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\nexport function reasoningProviderOptions(model: Model.Info, plan: Plan): ProviderOptionBag {\n\tconst level = plan.level;\n\tif (level === \"off\") return disabledProviderOptions(model);\n\n\tconst mapped = model.thinkingLevelMap?.[level] ?? level;\n\tif (!mapped) return {};\n\n\tconst key = Model.optionsKey(model);\n\tconst budget = plan.budget;\n\n\tif (key === \"openai\" || key === \"xai\" || key === \"openai-codex\") {\n\t\treturn { [key]: { reasoningEffort: mapped } };\n\t}\n\n\tif (key === \"github-copilot\") {\n\t\tconst method = model.api?.method;\n\t\tif (method === Model.APIMethodEnum.responses) {\n\t\t\treturn { [key]: { reasoningEffort: mapped } };\n\t\t}\n\t\tif (method === Model.APIMethodEnum.messages) {\n\t\t\tif (model.compat?.forceAdaptiveThinking) {\n\t\t\t\treturn {\n\t\t\t\t\t[key]: {\n\t\t\t\t\t\tthinking: { type: \"adaptive\", display: \"summarized\" },\n\t\t\t\t\t\teffort: anthropicEffort(model, level),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t[key]: {\n\t\t\t\t\tthinking: {\n\t\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t\tbudgetTokens: budget,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\t// The chat route has no generic reasoning control; catalog models carry\n\t\t// `compat.supportsThinkingTokenBudget` when they take a budget field.\n\t\treturn {};\n\t}\n\n\tif (key === \"openrouter\") {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\treasoning: {\n\t\t\t\t\teffort: mapped === \"off\" ? \"none\" : mapped,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (key === \"google\" || key === \"google-vertex\") {\n\t\tconst thinkingLevel = googleThinkingLevel(mapped);\n\t\t// Gemini 3 and Gemma 4 take a level; earlier families take a token budget.\n\t\tif (model.compat?.supportsThinkingLevel) {\n\t\t\treturn { [key]: { thinkingConfig: { thinkingLevel, includeThoughts: true } } };\n\t\t}\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinkingConfig: {\n\t\t\t\t\tincludeThoughts: true,\n\t\t\t\t\tthinkingBudget: budget,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\t// Newer Claude models size their own thinking from an effort level. Handing\n\t\t// them a fixed budget pins every turn to one depth instead.\n\t\tif (model.compat?.forceAdaptiveThinking) {\n\t\t\treturn {\n\t\t\t\t[key]: {\n\t\t\t\t\tthinking: { type: \"adaptive\", display: \"summarized\" },\n\t\t\t\t\teffort: anthropicEffort(model, level),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinking: {\n\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t// Already fitted under `plan.maxTokens` with the answer floor reserved.\n\t\t\t\t\t// Re-clamping here would reserve that floor a second time.\n\t\t\t\t\tbudgetTokens: budget,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {};\n}\n\n/**\n * The provider-native thinking value a request carried, read off the exact body the\n * adapter sent. Adapters drop efforts they believe a model rejects, so the options\n * aikit hands them can say more than the wire did.\n */\nexport function providerThinkingLevel(body: unknown): string | undefined {\n\tconst value =\n\t\tfield(body, \"reasoning\", \"effort\") ??\n\t\tfield(body, \"reasoning_effort\") ??\n\t\tfield(body, \"generationConfig\", \"thinkingConfig\", \"thinkingLevel\") ??\n\t\t// An effort sent alongside disabled thinking only shapes the answer; it is not a thinking level.\n\t\t(field(body, \"thinking\", \"type\") === \"disabled\" ? undefined : field(body, \"output_config\", \"effort\"));\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction field(value: unknown, ...keys: string[]): unknown {\n\treturn keys.reduce<unknown>(\n\t\t(at, key) => (typeof at === \"object\" && at !== null ? (at as Record<string, unknown>)[key] : undefined),\n\t\tvalue,\n\t);\n}\n\nexport * as Thinking from \"./thinking.ts\";\n","/**\n * @description Helper function to parse partial jsons during LLM streaming.\n */\n\nimport { parse as partialParse } from \"partial-json\";\n\n/**\n * Attempts to parse potentially incomplete JSON during streaming.\n * Always returns a valid object, even if the JSON is incomplete.\n *\n * @param partialJson The partial JSON string from streaming\n * @returns Parsed object or empty object if parsing fails\n */\nexport function parseStreamingJson<T = any>(partialJson: string | undefined): T {\n\tif (!partialJson || partialJson.trim() === \"\") {\n\t\treturn {} as T;\n\t}\n\n\t// Try standard parsing first (fastest for complete JSON)\n\ttry {\n\t\treturn JSON.parse(partialJson) as T;\n\t} catch {\n\t\tconst repaired = repairInvalidJsonStringContent(partialJson);\n\t\tif (repaired !== partialJson) {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(repaired) as T;\n\t\t\t} catch {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = partialParse(repaired);\n\t\t\t\t\treturn (result ?? {}) as T;\n\t\t\t\t} catch {\n\t\t\t\t\t// Fall through to the original partial parser.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Try partial-json for incomplete JSON\n\t\ttry {\n\t\t\tconst result = partialParse(partialJson);\n\t\t\treturn (result ?? {}) as T;\n\t\t} catch {\n\t\t\t// If all parsing fails, return empty object\n\t\t\treturn {} as T;\n\t\t}\n\t}\n}\n\nfunction repairInvalidJsonStringContent(input: string): string {\n\tlet output = \"\";\n\tlet inString = false;\n\tlet escaping = false;\n\n\tfor (const char of input) {\n\t\tif (!inString) {\n\t\t\toutput += char;\n\t\t\tif (char === '\"') inString = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (escaping) {\n\t\t\tif (`\"\\\\/bfnrtu`.includes(char)) {\n\t\t\t\toutput += `\\\\${char}`;\n\t\t\t} else {\n\t\t\t\toutput += `\\\\\\\\${char}`;\n\t\t\t}\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"\\\\\") {\n\t\t\tescaping = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tinString = false;\n\t\t\toutput += char;\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (char) {\n\t\t\tcase \"\\b\":\n\t\t\t\toutput += \"\\\\b\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\f\":\n\t\t\t\toutput += \"\\\\f\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\n\":\n\t\t\t\toutput += \"\\\\n\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\r\":\n\t\t\t\toutput += \"\\\\r\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\t\":\n\t\t\t\toutput += \"\\\\t\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput += char;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (escaping) output += \"\\\\\\\\\";\n\treturn output;\n}\n","/**\n * Removes unpaired Unicode surrogate characters from a string.\n *\n * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF,\n * or vice versa) cause JSON serialization errors in many API providers.\n *\n * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired\n * surrogates and will NOT be affected by this function.\n *\n * @param text - The text to sanitize\n * @returns The sanitized text with unpaired surrogates removed\n *\n * @example\n * // Valid emoji (properly paired surrogates) are preserved\n * sanitizeSurrogates(\"Hello 🙈 World\") // => \"Hello 🙈 World\"\n *\n * // Unpaired high surrogate is removed\n * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low\n * sanitizeSurrogates(`Text ${unpaired} here`) // => \"Text here\"\n */\nexport function sanitizeSurrogates(text: string): string {\n\t// Replace unpaired high surrogates (0xD800-0xDBFF not followed by low surrogate)\n\t// Replace unpaired low surrogates (0xDC00-0xDFFF not preceded by high surrogate)\n\treturn text.replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, \"\");\n}\n","import type * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\n\ntype JsonSchemaObject = Record<string, unknown> & {\n\tproperties?: Record<string, unknown>;\n\trequired?: unknown;\n};\n\nclass UnsupportedStrictSchemaError extends Error {}\n\n/** True when a provider's strict mode rejects this schema keyword with this value. */\ntype UnsupportedKeyword = (key: string, value: unknown) => boolean;\n\nconst UNSUPPORTED_KEYWORDS = [\n\t\"$ref\",\n\t\"$defs\",\n\t\"definitions\",\n\t\"allOf\",\n\t\"oneOf\",\n\t\"patternProperties\",\n\t\"dependentSchemas\",\n\t\"dependencies\",\n\t\"unevaluatedProperties\",\n\t\"propertyNames\",\n\t\"contains\",\n\t\"prefixItems\",\n\t\"not\",\n\t\"if\",\n\t\"then\",\n\t\"else\",\n] as const;\n\n// Anthropic strict tool use rejects these with a 400 for the whole request.\n// https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations\nconst ANTHROPIC_UNSUPPORTED_KEYWORDS = new Set([\n\t\"minimum\",\n\t\"maximum\",\n\t\"exclusiveMinimum\",\n\t\"exclusiveMaximum\",\n\t\"multipleOf\",\n\t\"maxItems\",\n\t\"uniqueItems\",\n\t\"minContains\",\n\t\"maxContains\",\n\t\"minProperties\",\n\t\"maxProperties\",\n]);\nconst ANTHROPIC_STRING_FORMATS = new Set([\n\t\"date-time\",\n\t\"time\",\n\t\"date\",\n\t\"duration\",\n\t\"email\",\n\t\"hostname\",\n\t\"uri\",\n\t\"ipv4\",\n\t\"ipv6\",\n\t\"uuid\",\n]);\n\nconst isAnthropicUnsupportedKeyword: UnsupportedKeyword = (key, value) => {\n\tif (ANTHROPIC_UNSUPPORTED_KEYWORDS.has(key)) return true;\n\tif (key === \"minItems\") return value !== 0 && value !== 1;\n\tif (key === \"format\") return typeof value !== \"string\" || !ANTHROPIC_STRING_FORMATS.has(value);\n\treturn false;\n};\n\nfunction isJsonSchemaObject(value: unknown): value is JsonSchemaObject {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNullSchema(schema: unknown): boolean {\n\treturn isJsonSchemaObject(schema) && schema.type === \"null\";\n}\n\n/** `X` of an `anyOf: [X, null]` schema. */\nexport function nullableVariant(schema: unknown): unknown {\n\tif (!isJsonSchemaObject(schema) || !Array.isArray(schema.anyOf)) return;\n\tconst variants = schema.anyOf.filter((variant) => !isNullSchema(variant));\n\treturn variants.length === 1 ? variants[0] : undefined;\n}\n\nfunction isStructuredSchema(schema: unknown): boolean {\n\tif (!isJsonSchemaObject(schema)) return false;\n\tconst types = typeof schema.type === \"string\" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];\n\treturn (\n\t\ttypes.includes(\"object\") ||\n\t\ttypes.includes(\"array\") ||\n\t\tschema.properties !== undefined ||\n\t\tschema.items !== undefined\n\t);\n}\n\nconst CONSTRAINING_KEYWORDS = [\n\t\"type\",\n\t\"const\",\n\t\"enum\",\n\t\"anyOf\",\n\t\"allOf\",\n\t\"oneOf\",\n\t\"not\",\n\t\"$ref\",\n\t\"properties\",\n\t\"items\",\n];\n\nexport function schemaAllowsNull(schema: unknown): boolean {\n\tif (schema === true) return true;\n\tif (!isJsonSchemaObject(schema)) return false;\n\tif (CONSTRAINING_KEYWORDS.every((key) => schema[key] === undefined)) return true;\n\tif (schema.type === \"null\" || (Array.isArray(schema.type) && schema.type.includes(\"null\"))) return true;\n\tif (schema.const === null || (Array.isArray(schema.enum) && schema.enum.includes(null))) return true;\n\treturn Array.isArray(schema.anyOf) && schema.anyOf.some((variant) => schemaAllowsNull(variant));\n}\n\nfunction makeNodeStrict(schema: unknown, isUnsupportedKeyword?: UnsupportedKeyword): void {\n\tif (!isJsonSchemaObject(schema)) throw new UnsupportedStrictSchemaError(\"boolean schemas are unsupported\");\n\tfor (const key of UNSUPPORTED_KEYWORDS) {\n\t\tif (schema[key] !== undefined) throw new UnsupportedStrictSchemaError(`${key} schemas are unsupported`);\n\t}\n\tif (isUnsupportedKeyword) {\n\t\tfor (const [key, value] of Object.entries(schema)) {\n\t\t\tif (isUnsupportedKeyword(key, value)) {\n\t\t\t\tthrow new UnsupportedStrictSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (schema.anyOf !== undefined) {\n\t\tif (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) {\n\t\t\tthrow new UnsupportedStrictSchemaError(\"anyOf must contain at least one schema\");\n\t\t}\n\t\t// `[X, null]` is the nullable shape this transform itself emits; only real unions of structures are rejected.\n\t\tconst nullable = nullableVariant(schema) !== undefined;\n\t\tfor (const variant of schema.anyOf) {\n\t\t\tif (!nullable && isStructuredSchema(variant)) {\n\t\t\t\tthrow new UnsupportedStrictSchemaError(\"object and array unions are unsupported\");\n\t\t\t}\n\t\t\tmakeNodeStrict(variant, isUnsupportedKeyword);\n\t\t}\n\t}\n\n\tif (schema.items !== undefined) {\n\t\tif (Array.isArray(schema.items)) throw new UnsupportedStrictSchemaError(\"tuple schemas are unsupported\");\n\t\tmakeNodeStrict(schema.items, isUnsupportedKeyword);\n\t}\n\n\tconst isObjectSchema = schema.type === \"object\";\n\tif (schema.properties !== undefined && !isObjectSchema) {\n\t\tthrow new UnsupportedStrictSchemaError(\"properties require type object\");\n\t}\n\tif (!isObjectSchema) return;\n\t// Effect Schema emits `additionalProperties: true` for every struct; excess keys are dropped on decode, so\n\t// closing the object loses nothing. Only schema-valued additionalProperties carries meaning.\n\tif (schema.additionalProperties !== undefined && typeof schema.additionalProperties !== \"boolean\") {\n\t\tthrow new UnsupportedStrictSchemaError(\"schema-valued additionalProperties is unsupported\");\n\t}\n\tif (schema.properties !== undefined && !isJsonSchemaObject(schema.properties)) {\n\t\tthrow new UnsupportedStrictSchemaError(\"object properties must be a schema map\");\n\t}\n\tif (\n\t\tschema.required !== undefined &&\n\t\t(!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== \"string\"))\n\t) {\n\t\tthrow new UnsupportedStrictSchemaError(\"object required must be a string array\");\n\t}\n\n\tconst properties = schema.properties ?? {};\n\tconst propertyNames = Object.keys(properties);\n\tconst required = new Set(Array.isArray(schema.required) ? schema.required : []);\n\tif ([...required].some((key) => !propertyNames.includes(key))) {\n\t\tthrow new UnsupportedStrictSchemaError(\"required contains an unknown property\");\n\t}\n\tfor (const [key, property] of Object.entries(properties)) {\n\t\tmakeNodeStrict(property, isUnsupportedKeyword);\n\t\tif (!required.has(key) && !schemaAllowsNull(property)) {\n\t\t\tproperties[key] = { anyOf: [property, { type: \"null\" }] };\n\t\t}\n\t}\n\tschema.required = propertyNames;\n\tschema.additionalProperties = false;\n}\n\n/**\n * Convert a tool's parameter schema to the subset strict constrained sampling accepts: every object closed and\n * every property required, with formerly optional properties made nullable. Callers strip those nulls again\n * before validation (see `normalizeOptionalNulls`).\n */\nfunction makeStrictJsonSchema(schema: unknown, isUnsupportedKeyword?: UnsupportedKeyword): Record<string, unknown> {\n\tconst cloned: unknown = structuredClone(schema);\n\tif (!isJsonSchemaObject(cloned) || cloned.type !== \"object\") {\n\t\tthrow new UnsupportedStrictSchemaError(\"root schema must have type object\");\n\t}\n\tmakeNodeStrict(cloned, isUnsupportedKeyword);\n\treturn cloned;\n}\n\n/**\n * The strict parameter schema to send for a JSON-schema constrained tool, or `undefined` to send it non-strict.\n * A `\"prefer\"` tool whose schema the model's strict mode cannot express falls back to non-strict; a `\"require\"`\n * tool throws instead. `preferNonStrict` sends every `\"prefer\"` tool non-strict.\n */\nexport function resolveStrictParameters(\n\ttool: Message.Tool,\n\tmodel?: Pick<Model.Info, \"protocol\" | \"compat\">,\n\tpreferNonStrict = false,\n): Record<string, unknown> | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config || config.type !== \"json_schema\") return;\n\tif (preferNonStrict && config.strict === \"prefer\") return;\n\n\tif (model?.compat?.supportsStrictMode ?? true) {\n\t\tconst isAnthropic =\n\t\t\tmodel?.protocol === Model.KnownProviderEnum.anthropic ||\n\t\t\tmodel?.protocol === Model.KnownProviderEnum.googleVertexAnthropic;\n\t\ttry {\n\t\t\treturn makeStrictJsonSchema(tool.parameters, isAnthropic ? isAnthropicUnsupportedKeyword : undefined);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof UnsupportedStrictSchemaError)) throw error;\n\t\t\tif (config.strict !== \"require\") return;\n\t\t\tthrow new Error(`tool \"${tool.name}\" requires JSON-schema constrained sampling, but ${error.message}.`);\n\t\t}\n\t}\n\tif (config.strict === \"require\") {\n\t\tthrow new Error(\n\t\t\t`tool \"${tool.name}\" requires JSON-schema constrained sampling, but strict tools are unsupported.`,\n\t\t);\n\t}\n}\n","import {\n\tjsonSchema,\n\ttype AssistantModelMessage,\n\ttype FinishReason,\n\ttype LanguageModelUsage,\n\ttype ModelMessage,\n\ttype TextStreamPart,\n\ttype ToolModelMessage,\n\ttype ToolSet,\n\ttype UserModelMessage,\n} from \"ai\";\nimport type { LanguageModelV3FunctionTool, SharedV3ProviderOptions } from \"@ai-sdk/provider\";\nimport * as Message from \"../message/message.ts\";\nimport * as Transcript from \"../message/transcript.ts\";\nimport { Pricing } from \"./pricing.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { resolveToolGrammar, type ResponsesToolChange } from \"../providers/responses/tools.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/jsonparse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize.ts\";\nimport { packageForModel, resolveMethod } from \"./registry.ts\";\nimport { resolveStrictParameters } from \"./strict.ts\";\nimport { isAnthropicMessagesModel } from \"./thinking.ts\";\n\ntype ToolCallPart = Extract<Message.AssistantMessage[\"parts\"][number], { type: \"toolCall\" }>;\ntype TerminalToolCall = Exclude<ToolCallPart, Message.ToolCallPendingPart | Message.ToolCallRunningPart>;\n\nexport function createAssistantMessage(\n\tmodel: Model.Info,\n\tthinkingLevel: Model.ThinkingLevel,\n): Message.AssistantMessage {\n\treturn Message.createAssistantMessage({\n\t\trole: \"assistant\",\n\t\tparts: [],\n\t\tprotocol: model.protocol,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tthinkingLevel,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\ttime: {\n\t\t\tcreated: Date.now(),\n\t\t\tcompleted: Date.now(),\n\t\t},\n\t});\n}\n\nfunction userContent(parts: Message.UserMessage[\"parts\"]): ModelMessage[] {\n\tconst content: Exclude<UserModelMessage[\"content\"], string> = [];\n\tfor (const part of parts) {\n\t\tif (part.type === \"text\") {\n\t\t\tconst text = sanitizeSurrogates(part.text);\n\t\t\tif (text.trim().length > 0) {\n\t\t\t\tcontent.push({ type: \"text\", text });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcontent.push({ type: \"file\", data: part.data, mediaType: part.mimeType });\n\t}\n\n\tif (content.length === 0) return [];\n\treturn [{ role: \"user\", content }];\n}\n\nfunction sanitizeValue(value: unknown): unknown {\n\tif (typeof value === \"string\") return sanitizeSurrogates(value);\n\tif (Array.isArray(value)) return value.map((item) => sanitizeValue(item));\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, item] of Object.entries(value)) {\n\t\t\tresult[key] = sanitizeValue(item);\n\t\t}\n\t\treturn result;\n\t}\n\treturn value;\n}\n\nfunction sanitizeRecord(value: Record<string, unknown>): Record<string, unknown> {\n\treturn sanitizeValue(value) as Record<string, unknown>;\n}\n\nconst ERROR_TOOL_IMAGE_PLACEHOLDER = \"(image attached after the tool results)\";\nconst MOVED_TOOL_IMAGE_PLACEHOLDER = \"(see attached image)\";\nconst CHAT_TOOL_IMAGES_CAPTION = \"Attached image(s) from tool result:\";\nconst GEMINI_TOOL_IMAGES_CAPTION = \"Tool result image:\";\n\n/**\n * Where a tool result's images go when the wire cannot carry them inside the result. Each case\n * sends them in a user message after the turn's tool results:\n * - `anthropicError`: Anthropic rejects images in error tool results.\n * - `chat`: Chat Completions adapters serialize tool result images as JSON text.\n * - `gemini`: before Gemini 3 (and for non-Gemini models), an image-only result loses its function response.\n */\ntype MovedImages = \"anthropicError\" | \"chat\" | \"gemini\";\n\nconst COPILOT = \"@codeworksh/ai-sdk-github-copilot\";\n\nexport function isAnthropicWire(model: Model.Info, method: Model.APIMethodEnum): boolean {\n\tif (packageForModel(model) === COPILOT) return method === Model.APIMethodEnum.messages;\n\treturn isAnthropicMessagesModel(model);\n}\n\n/** Whether the model runs on our own Responses transport: Codex, and Copilot's `/responses`. */\nexport function isOwnResponses(model: Model.Info, methodOverride?: Model.APIMethodEnum): boolean {\n\tif (model.protocol === Model.KnownProviderEnum.openaiCodex) return true;\n\treturn (\n\t\tmodel.protocol === Model.KnownProviderEnum.githubCopilot &&\n\t\tresolveMethod(model, methodOverride) === Model.APIMethodEnum.responses\n\t);\n}\n\nfunction isChatCompletions(model: Model.Info, method: Model.APIMethodEnum): boolean {\n\tconst npm = packageForModel(model);\n\t// The compatible adapter falls back to its chat model for every other method.\n\tif (npm === \"@ai-sdk/openai-compatible\") return true;\n\tif (npm === COPILOT) return method !== Model.APIMethodEnum.responses && method !== Model.APIMethodEnum.messages;\n\treturn npm === \"@ai-sdk/openai\" && method === Model.APIMethodEnum.chat;\n}\n\n/** The Google adapter's own split: anything but Gemini 3 and later gets the legacy function response. */\nfunction isLegacyGoogleToolResults(model: Model.Info): boolean {\n\tif (model.protocol !== Model.KnownProviderEnum.google && model.protocol !== Model.KnownProviderEnum.googleVertex) {\n\t\treturn false;\n\t}\n\tconst id = model.api?.id ?? model.id;\n\tconst gemini = /(^|[/.])gemini-/i.test(id);\n\tconst legacy =\n\t\t/(^|[/.])gemini-[12](?:[.-]|$)/i.test(id) ||\n\t\t/(^|[/.])gemini-pro(?:-vision)?$/i.test(id) ||\n\t\t/(^|[/.])gemini-robotics-er-1\\.5(?:[.-]|$)/i.test(id);\n\treturn !gemini || legacy;\n}\n\nfunction movedImages(\n\ttoolCall: TerminalToolCall,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum,\n): MovedImages | undefined {\n\tif (!toolCall.result.content.some((content) => content.type === \"image\")) return;\n\tif (isAnthropicWire(model, method)) return toolCall.result.isError ? \"anthropicError\" : undefined;\n\tif (isChatCompletions(model, method)) return \"chat\";\n\tif (isLegacyGoogleToolResults(model)) return \"gemini\";\n}\n\nfunction toolResultOutput(toolCall: TerminalToolCall, moved: MovedImages | undefined) {\n\tconst content =\n\t\tmoved === \"anthropicError\"\n\t\t\t? Message.omitImages(toolCall.result.content, ERROR_TOOL_IMAGE_PLACEHOLDER)\n\t\t\t: moved\n\t\t\t\t? toolCall.result.content.filter((content) => content.type === \"text\")\n\t\t\t\t: toolCall.result.content;\n\tconst joined = content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => sanitizeSurrogates(content.text))\n\t\t.join(\"\\n\");\n\tconst text =\n\t\tmoved && moved !== \"anthropicError\" && joined.trim().length === 0 ? MOVED_TOOL_IMAGE_PLACEHOLDER : joined;\n\tconst images = content.filter((content) => content.type === \"image\");\n\n\t// The AI SDK's content output has no error flag, so other providers keep the images and lose\n\t// the flag: Google drops its `error` key, OpenAI-family wires have no flag to lose.\n\tif (toolCall.result.isError && images.length === 0) {\n\t\treturn {\n\t\t\ttype: \"error-text\" as const,\n\t\t\tvalue: text || \"tool returned an error\",\n\t\t};\n\t}\n\n\tif (images.length === 0) {\n\t\treturn {\n\t\t\ttype: \"text\" as const,\n\t\t\tvalue: text,\n\t\t};\n\t}\n\n\treturn {\n\t\ttype: \"content\" as const,\n\t\tvalue: [\n\t\t\t...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n\t\t\t...images.map((image) => ({\n\t\t\t\ttype: \"file\" as const,\n\t\t\t\tdata: { type: \"data\" as const, data: image.data },\n\t\t\t\tmediaType: image.mimeType,\n\t\t\t})),\n\t\t],\n\t};\n}\n\nfunction normalizeOpenAICodexIdPart(value: string): string {\n\treturn value\n\t\t.replace(/[^a-zA-Z0-9_-]/g, \"_\")\n\t\t.slice(0, 64)\n\t\t.replace(/_+$/, \"\");\n}\n\nexport function normalizeOpenAICodexToolCallId(\n\tid: string,\n\tmodel: Model.Info,\n\tsource: Message.AssistantMessage,\n): string {\n\tif (!id.includes(\"|\")) return normalizeOpenAICodexIdPart(id);\n\tconst [callId, itemId = \"\"] = id.split(\"|\");\n\tconst normalizedCallId = normalizeOpenAICodexIdPart(callId ?? \"\");\n\tconst isForeignToolCall = source.provider.id !== model.provider.id || source.protocol !== model.protocol;\n\tlet normalizedItemId = isForeignToolCall ? `fc_${shortHash(itemId)}` : normalizeOpenAICodexIdPart(itemId);\n\tif (!normalizedItemId.startsWith(\"fc_\") && !normalizedItemId.startsWith(\"ctc_\")) {\n\t\tnormalizedItemId = normalizeOpenAICodexIdPart(`fc_${normalizedItemId}`);\n\t}\n\treturn `${normalizedCallId}|${normalizedItemId}`;\n}\n\n/**\n * OpenAI (`call_id`, at most 64 characters), Anthropic (`^[a-zA-Z0-9_-]+$`) and\n * OpenRouter upstreams take a foreign tool call ID verbatim, so a Codex\n * `call|item` ID keeps only its unique call half.\n */\nexport function normalizeForeignToolCallId(id: string): string {\n\tif (/^[a-zA-Z0-9_-]{1,64}$/.test(id)) return id;\n\treturn normalizeOpenAICodexIdPart(id.split(\"|\")[0] ?? id);\n}\n\nfunction toolCallIdNormalizer(model: Model.Info, method: Model.APIMethodEnum) {\n\tif (isOwnResponses(model, method)) return normalizeOpenAICodexToolCallId;\n\tswitch (model.protocol) {\n\t\tcase Model.KnownProviderEnum.openaiCodex:\n\t\t\treturn normalizeOpenAICodexToolCallId;\n\t\tcase Model.KnownProviderEnum.openai:\n\t\tcase Model.KnownProviderEnum.anthropic:\n\t\tcase Model.KnownProviderEnum.googleVertexAnthropic:\n\t\tcase Model.KnownProviderEnum.openrouter:\n\t\t\treturn normalizeForeignToolCallId;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\ntype OpenAIReasoningMetadata = {\n\titemId: string;\n\treasoningEncryptedContent?: string | null;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function encodeOpenAIReasoningSignature(providerMetadata: unknown): string | undefined {\n\tif (!isRecord(providerMetadata)) return;\n\tconst metadata = providerMetadata.openai;\n\tif (!isRecord(metadata) || typeof metadata.itemId !== \"string\") return;\n\n\tconst signature: OpenAIReasoningMetadata = { itemId: metadata.itemId };\n\tif (typeof metadata.reasoningEncryptedContent === \"string\" || metadata.reasoningEncryptedContent === null) {\n\t\tsignature.reasoningEncryptedContent = metadata.reasoningEncryptedContent;\n\t}\n\treturn JSON.stringify(signature);\n}\n\nfunction decodeOpenAIReasoningSignature(signature: string): OpenAIReasoningMetadata | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(signature);\n\t\tif (isRecord(parsed) && typeof parsed.itemId === \"string\") {\n\t\t\treturn {\n\t\t\t\titemId: parsed.itemId,\n\t\t\t\t...(typeof parsed.reasoningEncryptedContent === \"string\" || parsed.reasoningEncryptedContent === null\n\t\t\t\t\t? { reasoningEncryptedContent: parsed.reasoningEncryptedContent }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t} catch {\n\t\treturn;\n\t}\n}\n\n/**\n * The reasoning item our Responses transport replays from a thinking signature. Copilot\n * messages from before it ran on that transport carry `{ itemId, reasoningEncryptedContent }`\n * instead of the item; those replay when they hold encrypted content.\n */\nfunction responsesReasoningItem(signature: string): string | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(signature);\n\t\tif (!isRecord(parsed)) return;\n\t\tif (parsed.type === \"reasoning\" && typeof parsed.id === \"string\") return signature;\n\t\tconst legacy = decodeOpenAIReasoningSignature(signature);\n\t\tif (!legacy || typeof legacy.reasoningEncryptedContent !== \"string\") return;\n\t\treturn JSON.stringify({\n\t\t\ttype: \"reasoning\",\n\t\t\tid: legacy.itemId,\n\t\t\tencrypted_content: legacy.reasoningEncryptedContent,\n\t\t\tsummary: [],\n\t\t});\n\t} catch {\n\t\treturn;\n\t}\n}\n\nexport function googleThoughtSignature(metadata: unknown): string | undefined {\n\tif (!isRecord(metadata)) return;\n\tfor (const key of [\"google\", \"google-vertex\"]) {\n\t\tconst provider = metadata[key];\n\t\tif (isRecord(provider) && typeof provider.thoughtSignature === \"string\") return provider.thoughtSignature;\n\t}\n}\n\nfunction assistantMessages(\n\tmessage: Message.AssistantMessage,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum,\n): ModelMessage[] {\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") return [];\n\n\tconst assistantContent: Exclude<AssistantModelMessage[\"content\"], string> = [];\n\tconst toolResults: ToolModelMessage[\"content\"] = [];\n\tconst movedImageContent: Exclude<UserModelMessage[\"content\"], string> = [];\n\t// Replay metadata for our own Responses transport, only from a message it produced.\n\tconst responsesKey =\n\t\tisOwnResponses(model, method) && message.protocol === model.protocol && message.provider.id === model.provider.id\n\t\t\t? Model.optionsKey(model)\n\t\t\t: undefined;\n\tconst googleReplay =\n\t\t(model.protocol === \"google\" || model.protocol === \"google-vertex\") &&\n\t\tmessage.protocol === model.protocol &&\n\t\tmessage.provider.id === model.provider.id &&\n\t\tmessage.model === model.id;\n\tconst googleOptions = (signature: string | undefined) =>\n\t\tgoogleReplay && signature ? { [Model.optionsKey(model)]: { thoughtSignature: signature } } : undefined;\n\n\tfor (const part of message.parts) {\n\t\tconst google = googleOptions(\n\t\t\tpart.type === \"text\"\n\t\t\t\t? part.textSignature\n\t\t\t\t: part.type === \"thinking\"\n\t\t\t\t\t? part.thinkingSignature\n\t\t\t\t\t: part.type === \"toolCall\"\n\t\t\t\t\t\t? part.thoughtSignature\n\t\t\t\t\t\t: undefined,\n\t\t);\n\t\tif (part.type === \"text\") {\n\t\t\tconst text = sanitizeSurrogates(part.text);\n\t\t\tif (text.trim().length === 0) continue;\n\t\t\tassistantContent.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext,\n\t\t\t\t...(google ? { providerOptions: google } : {}),\n\t\t\t\t...(part.textSignature && responsesKey\n\t\t\t\t\t? { providerOptions: { [responsesKey]: { messageId: part.textSignature } } }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.type === \"thinking\") {\n\t\t\tconst thinking = sanitizeSurrogates(part.thinking);\n\t\t\tif (thinking.trim().length === 0 && !part.thinkingSignature) continue;\n\n\t\t\tif (responsesKey) {\n\t\t\t\t// Only a signed reasoning item replays; unsigned thinking is dropped.\n\t\t\t\tconst reasoningItem = part.thinkingSignature ? responsesReasoningItem(part.thinkingSignature) : undefined;\n\t\t\t\tif (!reasoningItem) continue;\n\t\t\t\tassistantContent.push({\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttext: thinking,\n\t\t\t\t\tproviderOptions: { [responsesKey]: { reasoningItem } },\n\t\t\t\t} as (typeof assistantContent)[number]);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (message.protocol === Model.KnownProviderEnum.githubCopilot) {\n\t\t\t\t/*\n\t\t\t\t * Copilot Messages models carry Anthropic signatures, and the chat endpoint\n\t\t\t\t * cannot replay thinking at all. Thinking that cannot be replayed natively\n\t\t\t\t * survives as plain text instead of going out unsigned.\n\t\t\t\t */\n\t\t\t\tconst openai = part.thinkingSignature ? decodeOpenAIReasoningSignature(part.thinkingSignature) : undefined;\n\t\t\t\tif (method === Model.APIMethodEnum.messages && part.thinkingSignature && !openai) {\n\t\t\t\t\tassistantContent.push({\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: thinking,\n\t\t\t\t\t\tproviderOptions: { anthropic: { signature: part.thinkingSignature } },\n\t\t\t\t\t} as (typeof assistantContent)[number]);\n\t\t\t\t} else if (thinking.trim().length > 0) {\n\t\t\t\t\tassistantContent.push({ type: \"text\", text: thinking });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst reasoning: Record<string, unknown> = { type: \"reasoning\", text: thinking };\n\t\t\t// OpenAI Responses only accepts native reasoning items with encoded metadata.\n\t\t\tif (message.protocol === Model.KnownProviderEnum.openai) {\n\t\t\t\tif (!part.thinkingSignature) continue;\n\t\t\t\tconst openai = decodeOpenAIReasoningSignature(part.thinkingSignature);\n\t\t\t\tif (!openai) continue;\n\t\t\t\treasoning.providerOptions = { openai };\n\t\t\t} else if (google) {\n\t\t\t\treasoning.providerOptions = google;\n\t\t\t} else if (part.thinkingSignature && message.protocol !== \"google\" && message.protocol !== \"google-vertex\") {\n\t\t\t\treasoning.providerOptions = { anthropic: { signature: part.thinkingSignature } };\n\t\t\t}\n\t\t\tassistantContent.push(reasoning as (typeof assistantContent)[number]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.type !== \"toolCall\") continue;\n\n\t\tconst responsesToolMetadata: { namespace?: string; omitItemId?: boolean } = {};\n\t\tif (responsesKey && part.namespace) responsesToolMetadata.namespace = part.namespace;\n\t\tif (responsesKey && message.model !== model.id) responsesToolMetadata.omitItemId = true;\n\t\tassistantContent.push({\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: part.callID,\n\t\t\ttoolName: part.name,\n\t\t\tinput: sanitizeRecord(part.arguments ?? {}),\n\t\t\t...(google ? { providerOptions: google } : {}),\n\t\t\t...(responsesKey && Object.keys(responsesToolMetadata).length > 0\n\t\t\t\t? { providerOptions: { [responsesKey]: responsesToolMetadata } }\n\t\t\t\t: {}),\n\t\t});\n\n\t\tconst terminal = part.status === \"pending\" || part.status === \"running\" ? undefined : part;\n\t\tconst moved = terminal ? movedImages(terminal, model, method) : undefined;\n\t\ttoolResults.push({\n\t\t\ttype: \"tool-result\",\n\t\t\ttoolCallId: part.callID,\n\t\t\ttoolName: part.name,\n\t\t\toutput: terminal\n\t\t\t\t? toolResultOutput(terminal, moved)\n\t\t\t\t: {\n\t\t\t\t\t\ttype: \"error-text\",\n\t\t\t\t\t\tvalue: \"no result provided\",\n\t\t\t\t\t},\n\t\t});\n\t\tif (terminal && moved) {\n\t\t\tconst caption =\n\t\t\t\tmoved === \"anthropicError\"\n\t\t\t\t\t? `Images from the error result of tool call ${part.callID} (${part.name}):`\n\t\t\t\t\t: moved === \"gemini\"\n\t\t\t\t\t\t? GEMINI_TOOL_IMAGES_CAPTION\n\t\t\t\t\t\t: movedImageContent.length === 0\n\t\t\t\t\t\t\t? CHAT_TOOL_IMAGES_CAPTION\n\t\t\t\t\t\t\t: undefined;\n\t\t\tmovedImageContent.push(\n\t\t\t\t...(caption === undefined ? [] : [{ type: \"text\" as const, text: caption }]),\n\t\t\t\t...terminal.result.content.flatMap((content) =>\n\t\t\t\t\tcontent.type === \"image\"\n\t\t\t\t\t\t? [{ type: \"file\" as const, data: content.data, mediaType: content.mimeType }]\n\t\t\t\t\t\t: [],\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\tconst result: ModelMessage[] = [];\n\tif (assistantContent.length > 0) {\n\t\tresult.push({ role: \"assistant\", content: assistantContent });\n\t}\n\tif (toolResults.length > 0) {\n\t\tresult.push({ role: \"tool\", content: toolResults });\n\t}\n\t// @ai-sdk/anthropic merges this into the tool results' user message, after the tool_result blocks.\n\tif (movedImageContent.length > 0) {\n\t\tresult.push({ role: \"user\", content: movedImageContent });\n\t}\n\treturn result;\n}\n\n/**\n * How the model's transport expresses tool changes after the first request. Only our own\n * Responses transport can declare tools in place; the AI SDK adapters take the current tool\n * set top-level. A request limited to some tools (`activeTools`) takes them top-level too,\n * since only that list is filtered.\n */\nexport function transcriptToolSupport(\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum | undefined,\n\trestricted = false,\n): Transcript.TranscriptToolSupport {\n\tif (restricted || !isOwnResponses(model, method)) return \"none\";\n\tif (supportsMidConvoSystemMessages(model, method) && model.compat?.supportsAdditionalTools) return \"changes\";\n\treturn model.compat?.supportsToolSearch ? \"additions\" : \"none\";\n}\n\n/**\n * Whether prompt changes go in place as system messages. Our own Responses transport and the\n * AI SDK's OpenAI Responses and Anthropic Messages adapters keep them where they stand; Chat\n * Completions takes the current prompt as the leading system prompt.\n */\nexport function supportsMidConvoSystemMessages(model: Model.Info, method: Model.APIMethodEnum | undefined): boolean {\n\tif (model.compat?.supportsMidConvoSystemMessages !== true) return false;\n\treturn isOwnResponses(model, method) || !isChatCompletions(model, resolveMethod(model, method));\n}\n\n/**\n * Anthropic with tool changes in place: every tool the thread can reach is declared up front, the\n * ones beyond its initial set deferred, and later changes name them by reference. Adding a tool\n * to the top-level list costs the cached prefix; referencing a deferred one does not.\n */\nfunction anthropicToolReferences(model: Model.Info, method: Model.APIMethodEnum, restricted: boolean): boolean {\n\treturn (\n\t\t!restricted &&\n\t\tisAnthropicWire(model, method) &&\n\t\tsupportsMidConvoSystemMessages(model, method) &&\n\t\tmodel.compat?.supportsAdditionalTools === true\n\t);\n}\n\n/** Messages before the first reply: on Anthropic their system messages join the leading prompt and tools. */\nfunction beforeFirstReply(messages: readonly Message.Message[]): Message.Message[] {\n\tconst reply = messages.findIndex((message) => message.role === \"assistant\");\n\treturn reply === -1 ? [...messages] : messages.slice(0, reply);\n}\n\n/**\n * The tools the request declares top-level, and which of them are deferred. Usually every tool\n * callable now. With Anthropic tool references, the initial set, then the deferred catalog and\n * every other tool the transcript declared, deferred, in an order that holds across requests.\n */\nexport function requestTools(\n\tcontext: Message.Context,\n\tmodel: Model.Info,\n\tmethodOverride?: Model.APIMethodEnum,\n\tactiveTools?: readonly string[],\n): { tools: Message.Tool[]; deferred: ReadonlySet<string> } {\n\tif (!anthropicToolReferences(model, resolveMethod(model, methodOverride), activeTools !== undefined)) {\n\t\treturn { tools: Transcript.getCurrentTools(context), deferred: new Set() };\n\t}\n\tconst initial = Transcript.getCurrentTools({ ...context, messages: beforeFirstReply(context.messages) });\n\tconst latest = new Map(Transcript.getDeclaredTools(context).map((tool) => [tool.name, tool]));\n\tconst tools = new Map(initial.map((tool) => [tool.name, tool]));\n\tconst deferred = new Set<string>();\n\tfor (const tool of [...(context.deferredTools ?? []), ...latest.values()]) {\n\t\tif (tools.has(tool.name)) continue;\n\t\ttools.set(tool.name, latest.get(tool.name) ?? tool);\n\t\tdeferred.add(tool.name);\n\t}\n\treturn { tools: [...tools.values()], deferred };\n}\n\n/** A later system message's tool changes as Anthropic tool references; a redefinition needs no removal. */\nfunction toolReferences(message: Message.SystemMessage) {\n\tconst added = new Set((message.toolsAdded ?? []).map((tool) => tool.name));\n\treturn [\n\t\t...(message.toolsRemoved ?? [])\n\t\t\t.filter((tool) => !added.has(tool.name))\n\t\t\t.map((tool) => ({ type: \"tool_removal\" as const, toolName: tool.name })),\n\t\t...[...added].map((name) => ({ type: \"tool_addition\" as const, toolName: name })),\n\t];\n}\n\n/**\n * The prompt the AI SDK adapters take as `system`: the leading one when changes go in place,\n * else the current one, every change folded in.\n */\nexport function leadingSystemPrompt(\n\tcontext: Message.Context,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum | undefined,\n): string | undefined {\n\treturn (\n\t\tTranscript.resolveTranscriptPrompt(context, supportsMidConvoSystemMessages(model, method)).systemPrompt ||\n\t\tundefined\n\t);\n}\n\n/** A tool as the language model receives it, for declaring it inside the prompt. */\nfunction functionTool(tool: Message.Tool, model: Model.Info, method: Model.APIMethodEnum): LanguageModelV3FunctionTool {\n\tconst { inputSchema, strict, providerOptions } = toolWire(tool, model, method);\n\treturn {\n\t\ttype: \"function\",\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: JSON.parse(JSON.stringify(inputSchema)) as LanguageModelV3FunctionTool[\"inputSchema\"],\n\t\t...(strict ? { strict } : {}),\n\t\t...(providerOptions ? { providerOptions } : {}),\n\t};\n}\n\n/** A system message sent in place: the prompt update `content`, then the tool change, if any. */\nfunction systemChangeMessage(\n\tcontent: string,\n\ttoolsAdded: readonly Message.Tool[],\n\ttoolsRemoved: readonly Message.ToolReference[],\n\tsupport: Transcript.TranscriptToolSupport,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum,\n): ModelMessage | undefined {\n\tif (toolsAdded.length === 0 && toolsRemoved.length === 0) {\n\t\treturn content.length > 0 ? { role: \"system\", content: sanitizeSurrogates(content) } : undefined;\n\t}\n\tconst toolChange: ResponsesToolChange = {\n\t\tmode: support === \"changes\" ? \"changes\" : \"additions\",\n\t\ttools: toolsAdded.map((tool) => functionTool(tool, model, method)),\n\t\tremoved: toolsRemoved.map((tool) => tool.name),\n\t};\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: sanitizeSurrogates(content),\n\t\t// Function tools are plain JSON once their schema went through `functionTool`.\n\t\tproviderOptions: { [Model.optionsKey(model)]: { toolChange } } as unknown as SharedV3ProviderOptions,\n\t};\n}\n\nexport function convertMessages(\n\tcontext: Message.Context,\n\tmodel: Model.Info,\n\tmethodOverride?: Model.APIMethodEnum,\n\tactiveTools?: readonly string[],\n): ModelMessage[] {\n\tconst method = resolveMethod(model, methodOverride);\n\tconst messages: ModelMessage[] = [];\n\tconst transformedMessages = Message.transformMessages(context.messages, model, toolCallIdNormalizer(model, method));\n\tconst support = transcriptToolSupport(model, method, activeTools !== undefined);\n\tconst transcript = Transcript.resolveTranscriptTools(context, support);\n\tconst prompt = Transcript.resolveTranscriptPrompt(context, supportsMidConvoSystemMessages(model, method));\n\n\tif (transcript.initialToolsInPlace) {\n\t\tconst head = systemChangeMessage(\"\", context.tools ?? [], [], support, model, method);\n\t\tif (head) messages.push(head);\n\t}\n\t// Our Responses transport takes the leading prompt in place, after the initial tool declaration.\n\tif (isOwnResponses(model, method) && prompt.systemPrompt) {\n\t\tmessages.push({ role: \"system\", content: sanitizeSurrogates(prompt.systemPrompt) });\n\t}\n\n\t// Every system message goes as an update, the first declaration too: a section a model read\n\t// whole does not yield to a later update of it, one it read as an update does. On Anthropic,\n\t// one before the first reply joins the leading prompt, where it caches: a trailing system\n\t// message's cache entry is never read once a reply follows it. Anthropic takes a later one\n\t// only after a user message, and never between a tool call and its result: each is held for\n\t// the next assistant message, or the end.\n\tconst anthropic = isAnthropicWire(model, method);\n\tconst references = anthropicToolReferences(model, method, activeTools !== undefined);\n\tconst leading: ModelMessage[] = [];\n\tconst held: ModelMessage[] = [];\n\tlet replied = false;\n\tlet systemIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"system\") {\n\t\t\tconst index = systemIndex++;\n\t\t\tconst update = index < prompt.foldedSystemMessages ? \"\" : Transcript.renderSystemPromptUpdate(msg);\n\t\t\t// The tools of one before the first reply belong to the initial set.\n\t\t\tconst toolChanges = references && replied ? toolReferences(msg) : [];\n\t\t\tif (toolChanges.length > 0) {\n\t\t\t\theld.push({\n\t\t\t\t\trole: \"system\",\n\t\t\t\t\tcontent: sanitizeSurrogates(update),\n\t\t\t\t\tproviderOptions: { [Model.optionsKey(model)]: { toolChanges } },\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst folded = index < transcript.foldedSystemMessages;\n\t\t\tconst change = systemChangeMessage(\n\t\t\t\tupdate,\n\t\t\t\tfolded ? [] : (msg.toolsAdded ?? []),\n\t\t\t\tfolded ? [] : (msg.toolsRemoved ?? []),\n\t\t\t\tsupport,\n\t\t\t\tmodel,\n\t\t\t\tmethod,\n\t\t\t);\n\t\t\tif (change) (!anthropic ? messages : replied ? held : leading).push(change);\n\t\t\tcontinue;\n\t\t}\n\t\tif (msg.role === \"user\") {\n\t\t\tmessages.push(...userContent(msg.parts));\n\t\t\tcontinue;\n\t\t}\n\t\tconst converted = assistantMessages(msg, model, method);\n\t\tif (converted.length > 0) {\n\t\t\treplied = true;\n\t\t\tmessages.push(...held.splice(0));\n\t\t}\n\t\tmessages.push(...converted);\n\t}\n\n\treturn [...leading, ...messages, ...held];\n}\n\n/**\n * The string input property of every grammar tool the transcript declared, for our Responses\n * transport: earlier calls to a tool since removed or redefined still replay as grammar calls.\n */\nexport function grammarToolInputProperties(\n\tcontext: Message.Context,\n\tmodel: Model.Info,\n\tmethod: Model.APIMethodEnum | undefined,\n): Record<string, string> | undefined {\n\tif (!isOwnResponses(model, method)) return;\n\tconst properties: Record<string, string> = {};\n\tfor (const tool of Transcript.getDeclaredTools(context)) {\n\t\tconst grammar = resolveToolGrammar(tool, model.compat);\n\t\tif (grammar) properties[tool.name] = grammar.inputProperty;\n\t}\n\treturn Object.keys(properties).length > 0 ? properties : undefined;\n}\n\n/** The parameter schema, strict flag and grammar a tool goes out with on this model. */\nfunction toolWire(tool: Message.Tool, model?: Model.Info, method?: Model.APIMethodEnum, preferNonStrict = false) {\n\tconst strictParameters = resolveStrictParameters(tool, model, preferNonStrict);\n\tconst grammarConstraint =\n\t\tmodel && isOwnResponses(model, method) ? resolveToolGrammar(tool, model.compat) : undefined;\n\treturn {\n\t\tinputSchema: strictParameters ?? tool.parameters,\n\t\tstrict: strictParameters ? true : undefined,\n\t\tproviderOptions:\n\t\t\tmodel && grammarConstraint ? { [Model.optionsKey(model)]: { grammar: grammarConstraint } } : undefined,\n\t};\n}\n\nexport function convertTools(\n\ttools?: Message.Tool[],\n\tmodel?: Model.Info,\n\tmethod?: Model.APIMethodEnum,\n\tdeferred: ReadonlySet<string> = new Set(),\n\tpreferNonStrict = false,\n): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tconst { inputSchema, strict, providerOptions } = toolWire(tool, model, method, preferNonStrict);\n\t\tconst key = model && deferred.has(tool.name) ? Model.optionsKey(model) : undefined;\n\t\tconst options =\n\t\t\tkey === undefined\n\t\t\t\t? providerOptions\n\t\t\t\t: { ...providerOptions, [key]: { ...providerOptions?.[key], deferLoading: true } };\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(inputSchema as any),\n\t\t\t...(strict ? { strict } : {}),\n\t\t\t...(options ? { providerOptions: options } : {}),\n\t\t};\n\t}\n\treturn result;\n}\n\nexport function mapFinishReason(reason: FinishReason | undefined): Message.StopReason {\n\tswitch (reason) {\n\t\tcase \"length\":\n\t\t\treturn \"length\";\n\t\tcase \"tool-calls\":\n\t\t\treturn \"toolUse\";\n\t\tcase \"content-filter\":\n\t\tcase \"error\":\n\t\tcase \"other\":\n\t\t\treturn \"error\";\n\t\tcase \"stop\":\n\t\tdefault:\n\t\t\treturn \"stop\";\n\t}\n}\n\nexport function mapUsage(\n\tusage: LanguageModelUsage | undefined,\n\tmodel: Model.Info,\n\tcostMultiplier = 1,\n\tproviderMetadata?: unknown,\n): Message.AssistantMessage[\"usage\"] {\n\tconst cacheRead = usage?.inputTokenDetails.cacheReadTokens ?? 0;\n\tconst cacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;\n\tconst cacheWrite1h = Pricing.cacheWrite1hTokens(providerMetadata);\n\tconst input =\n\t\tusage?.inputTokenDetails?.noCacheTokens ?? Math.max((usage?.inputTokens ?? 0) - cacheRead - cacheWrite, 0);\n\tconst output = usage?.outputTokens ?? 0;\n\tconst totalTokens = usage?.totalTokens ?? input + cacheRead + cacheWrite + output;\n\tconst result: Message.AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\t...(cacheWrite1h === undefined ? {} : { cacheWrite1h }),\n\t\t...(usage?.outputTokenDetails?.reasoningTokens !== undefined\n\t\t\t? { reasoning: usage.outputTokenDetails.reasoningTokens }\n\t\t\t: {}),\n\t\ttotalTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tModel.calculateCost(model, result);\n\tif (costMultiplier !== 1) {\n\t\tresult.cost.input *= costMultiplier;\n\t\tresult.cost.output *= costMultiplier;\n\t\tresult.cost.cacheRead *= costMultiplier;\n\t\tresult.cost.cacheWrite *= costMultiplier;\n\t\tresult.cost.total = result.cost.input + result.cost.output + result.cost.cacheRead + result.cost.cacheWrite;\n\t}\n\treturn result;\n}\n\nexport type StreamingToolCallBlock = Message.ToolCallPendingPart & {\n\tpartialJson?: string;\n};\n\nexport function toolCallFromPart(\n\tpart: Extract<TextStreamPart<ToolSet>, { type: \"tool-call\" }>,\n): StreamingToolCallBlock {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tcallID: part.toolCallId,\n\t\tname: part.toolName,\n\t\targuments: typeof part.input === \"object\" && part.input !== null ? (part.input as Record<string, unknown>) : {},\n\t\tstatus: \"pending\",\n\t\ttime: {\n\t\t\tstart: Date.now(),\n\t\t\tend: Date.now(),\n\t\t},\n\t};\n}\n\nexport function updateToolCallFromInput(block: StreamingToolCallBlock, partialJson: string): void {\n\tblock.partialJson = partialJson;\n\tblock.arguments = parseStreamingJson<Record<string, unknown>>(partialJson);\n\tblock.time.end = Date.now();\n}\n","import { APICallError } from \"@ai-sdk/provider\";\nimport { RetryError, streamText, type TextStreamPart, type ToolSet } from \"ai\";\nimport * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { AssistantMessageEventStream } from \"../utils/eventstream.ts\";\nimport { compact } from \"../utils/helpers.ts\";\nimport * as Failure from \"./failure.ts\";\nimport { Options, type ProviderOptionBag, type RuntimeOptions } from \"./options.ts\";\nimport * as Pricing from \"./pricing.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { resolveAISDKLanguageModel } from \"./provider.ts\";\nimport { resolveMethod } from \"./registry.ts\";\nimport { formatThrownError } from \"./runtime.ts\";\nimport { applyDefaultMaxTokens } from \"./shared.ts\";\nimport * as Thinking from \"./thinking.ts\";\nimport {\n\tgoogleThoughtSignature,\n\tconvertMessages,\n\tisAnthropicWire,\n\tisOwnResponses,\n\tconvertTools,\n\trequestTools,\n\tcreateAssistantMessage,\n\tencodeOpenAIReasoningSignature,\n\tgrammarToolInputProperties,\n\tleadingSystemPrompt,\n\tmapFinishReason,\n\tmapUsage,\n\ttoolCallFromPart,\n\tupdateToolCallFromInput,\n\ttype StreamingToolCallBlock,\n} from \"./transform.ts\";\n\ntype TextBlock = Message.TextContent & { streamId?: string };\ntype ThinkingBlock = Message.ThinkingContent & { streamId?: string };\n\ntype StreamBlock = TextBlock | ThinkingBlock | StreamingToolCallBlock;\n\nfunction mergeProviderOptions(...sources: Array<ProviderOptionBag | undefined>): ProviderOptionBag {\n\tconst result: ProviderOptionBag = {};\n\tfor (const source of sources) {\n\t\tif (!source) continue;\n\t\tfor (const [key, value] of Object.entries(source)) {\n\t\t\tif (!value) continue;\n\t\t\tresult[key] = {\n\t\t\t\t...result[key],\n\t\t\t\t...value,\n\t\t\t};\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction configuredCacheRetention(options: RuntimeOptions): \"none\" | \"short\" | \"long\" | undefined {\n\tif (options.cacheRetention) return options.cacheRetention;\n\tconst env = process.env.CODEWORK_CACHE_RETENTION;\n\tif (env === \"none\" || env === \"short\" || env === \"long\") return env;\n}\n\nfunction cacheProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\tconst retention = configuredCacheRetention(options);\n\tconst key = Model.optionsKey(model);\n\n\tif (retention === \"none\") return {};\n\n\tif (key === \"openai\") {\n\t\tconst openai: Record<string, unknown> = {};\n\t\tif (options.sessionId) openai.promptCacheKey = options.sessionId;\n\t\tif (retention === \"short\") openai.promptCacheRetention = \"in_memory\";\n\t\tif (retention === \"long\") openai.promptCacheRetention = \"24h\";\n\t\treturn Object.keys(openai).length > 0 ? { [key]: openai } : {};\n\t}\n\n\tif (Thinking.isAnthropicMessagesModel(model) && retention) {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tcacheControl: {\n\t\t\t\t\ttype: \"ephemeral\",\n\t\t\t\t\t...(retention === \"long\" ? { ttl: \"1h\" } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {};\n}\n\nfunction resolveProviderOptions(\n\tmodel: Model.Info,\n\tcontext: Message.Context,\n\toptions: RuntimeOptions,\n\tplan: Thinking.Plan,\n): ProviderOptionBag {\n\tconst grammars = grammarToolInputProperties(context, model, options.method);\n\treturn mergeProviderOptions(\n\t\tmodel.providerOptions as ProviderOptionBag | undefined,\n\t\tcacheProviderOptions(model, options),\n\t\tThinking.reasoningProviderOptions(model, plan),\n\t\tgrammars === undefined ? undefined : { [Model.optionsKey(model)]: { grammarToolInputProperties: grammars } },\n\t\toptions.providerOptions as ProviderOptionBag | undefined,\n\t);\n}\n\nfunction partIndex(output: Message.AssistantMessage, block: StreamBlock): number {\n\treturn output.parts.indexOf(block as Message.AssistantMessage[\"parts\"][number]);\n}\n\n/** Metadata our Responses transport attaches under the model's provider key. */\nfunction responsesMetadata(value: unknown, model: Model.Info): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst metadata = (value as Record<string, unknown>)[Model.optionsKey(model)];\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 ensureTextBlock(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): TextBlock {\n\tconst existing = output.parts.find((part) => part.type === \"text\" && (part as TextBlock).streamId === id) as\n\t\t| TextBlock\n\t\t| undefined;\n\tif (existing) return existing;\n\n\tconst block: TextBlock = { type: \"text\", text: \"\", streamId: id };\n\toutput.parts.push(block);\n\tstream.push({ type: \"text.start\", partIndex: partIndex(output, block), partial: output });\n\treturn block;\n}\n\nfunction ensureThinkingBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n): ThinkingBlock {\n\tconst existing = output.parts.find((part) => part.type === \"thinking\" && (part as ThinkingBlock).streamId === id) as\n\t\t| ThinkingBlock\n\t\t| undefined;\n\tif (existing) return existing;\n\n\tconst block: ThinkingBlock = { type: \"thinking\", thinking: \"\", streamId: id };\n\toutput.parts.push(block);\n\tstream.push({ type: \"thinking.start\", partIndex: partIndex(output, block), partial: output });\n\treturn block;\n}\n\nfunction ensureToolCallBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tname: string,\n\tstream: AssistantMessageEventStream,\n\temitStart: boolean,\n): StreamingToolCallBlock {\n\tconst existing = output.parts.find((part) => part.type === \"toolCall\" && part.callID === id) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tif (existing) {\n\t\tif (!existing.name && name) existing.name = name;\n\t\treturn existing;\n\t}\n\n\tconst block: StreamingToolCallBlock = {\n\t\ttype: \"toolCall\",\n\t\tcallID: id,\n\t\tname,\n\t\targuments: {},\n\t\tstatus: \"pending\",\n\t\ttime: {\n\t\t\tstart: Date.now(),\n\t\t\tend: Date.now(),\n\t\t},\n\t};\n\toutput.parts.push(block);\n\tif (emitStart) {\n\t\tstream.push({ type: \"toolcall.start\", partIndex: partIndex(output, block), partial: output });\n\t}\n\treturn block;\n}\n\nfunction finishTextBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n\ttextSignature?: string,\n): void {\n\tconst block = output.parts.find((part) => part.type === \"text\" && (part as TextBlock).streamId === id) as\n\t\t| TextBlock\n\t\t| undefined;\n\tif (!block) return;\n\tif (textSignature) block.textSignature = textSignature;\n\tconst index = partIndex(output, block);\n\tdelete (block as { streamId?: string }).streamId;\n\tstream.push({ type: \"text.end\", partIndex: index, content: block.text, partial: output });\n}\n\nfunction finishThinkingBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n\tthinkingSignature?: string,\n): void {\n\tconst block = output.parts.find((part) => part.type === \"thinking\" && (part as ThinkingBlock).streamId === id) as\n\t\t| ThinkingBlock\n\t\t| undefined;\n\tif (!block) return;\n\tif (thinkingSignature) block.thinkingSignature = thinkingSignature;\n\tconst index = partIndex(output, block);\n\tdelete (block as { streamId?: string }).streamId;\n\tstream.push({ type: \"thinking.end\", partIndex: index, content: block.thinking, partial: output });\n}\n\nfunction finishToolInput(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): void {\n\tconst block = output.parts.find((part) => part.type === \"toolCall\" && part.callID === id) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tif (!block) return;\n\tconst index = partIndex(output, block);\n\tdelete block.partialJson;\n\tstream.push({ type: \"toolcall.end\", partIndex: index, toolCall: block, partial: output });\n}\n\nfunction finalizeToolCall(\n\toutput: Message.AssistantMessage,\n\tpart: Extract<TextStreamPart<ToolSet>, { type: \"tool-call\" }>,\n\tmodel: Model.Info,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst existing = output.parts.find((item) => item.type === \"toolCall\" && item.callID === part.toolCallId) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tconst block = existing ?? toolCallFromPart(part);\n\tblock.callID = part.toolCallId;\n\tblock.name = part.toolName;\n\tblock.arguments =\n\t\ttypeof part.input === \"object\" && part.input !== null ? (part.input as Record<string, unknown>) : {};\n\tconst namespace = responsesMetadata(part.providerMetadata, model)?.namespace;\n\tconst thoughtSignature = googleThoughtSignature(part.providerMetadata);\n\tif (thoughtSignature) block.thoughtSignature = thoughtSignature;\n\tif (typeof namespace === \"string\") block.namespace = namespace;\n\tblock.time.end = Date.now();\n\tdelete block.partialJson;\n\n\tif (!existing) {\n\t\toutput.parts.push(block);\n\t}\n\n\tconst index = partIndex(output, block);\n\tstream.push({ type: \"toolcall.final\", partIndex: index, toolCall: block, partial: output });\n}\n\n/**\n * Pricing inputs that are only complete once the provider answers.\n *\n * The requested tier is known upfront; the tier actually served and the cache-write\n * breakdown arrive with the terminal usage, and both change what the turn costs.\n */\ninterface Pricing {\n\treadonly requestedServiceTier: string | undefined;\n\tproviderMetadata?: unknown;\n}\n\nfunction handlePart(\n\tpart: TextStreamPart<ToolSet>,\n\toutput: Message.AssistantMessage,\n\tmodel: Model.Info,\n\tstream: AssistantMessageEventStream,\n\tpricing: Pricing,\n): void {\n\tswitch (part.type) {\n\t\tcase \"text-start\":\n\t\t\tensureTextBlock(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"text-delta\": {\n\t\t\tconst block = ensureTextBlock(output, part.id, stream);\n\t\t\tconst signature = googleThoughtSignature(part.providerMetadata);\n\t\t\tif (signature) block.textSignature = signature;\n\t\t\tblock.text += part.text;\n\t\t\tstream.push({ type: \"text.delta\", partIndex: partIndex(output, block), delta: part.text, partial: output });\n\t\t\tbreak;\n\t\t}\n\t\tcase \"text-end\": {\n\t\t\tconst messageId = responsesMetadata(part.providerMetadata, model)?.messageId;\n\t\t\tfinishTextBlock(output, part.id, stream, typeof messageId === \"string\" ? messageId : undefined);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reasoning-start\":\n\t\t\tensureThinkingBlock(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"reasoning-delta\": {\n\t\t\tconst block = ensureThinkingBlock(output, part.id, stream);\n\t\t\tblock.thinking += part.text;\n\t\t\t// Capture the provider thinking signature for faithful multi-turn replay.\n\t\t\t// @ai-sdk/anthropic emits it as a reasoning-delta with empty text and providerMetadata.\n\t\t\tconst sig =\n\t\t\t\t(part.providerMetadata?.anthropic as Record<string, unknown> | undefined)?.signature ??\n\t\t\t\t(part.providerMetadata?.[\"google-vertex-anthropic\"] as Record<string, unknown> | undefined)?.signature ??\n\t\t\t\tgoogleThoughtSignature(part.providerMetadata);\n\t\t\tif (typeof sig === \"string\") block.thinkingSignature = sig;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking.delta\",\n\t\t\t\tpartIndex: partIndex(output, block),\n\t\t\t\tdelta: part.text,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reasoning-end\": {\n\t\t\tconst reasoningItem = responsesMetadata(part.providerMetadata, model)?.reasoningItem;\n\t\t\tconst openAISignature = encodeOpenAIReasoningSignature(part.providerMetadata);\n\t\t\tfinishThinkingBlock(\n\t\t\t\toutput,\n\t\t\t\tpart.id,\n\t\t\t\tstream,\n\t\t\t\ttypeof reasoningItem === \"string\" ? reasoningItem : openAISignature,\n\t\t\t);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-input-start\":\n\t\t\tensureToolCallBlock(output, part.id, part.toolName, stream, true);\n\t\t\tbreak;\n\t\tcase \"tool-input-delta\": {\n\t\t\tconst block = ensureToolCallBlock(output, part.id, \"\", stream, true);\n\t\t\tconst partialJson = (block.partialJson ?? \"\") + part.delta;\n\t\t\tupdateToolCallFromInput(block, partialJson);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall.delta\",\n\t\t\t\tpartIndex: partIndex(output, block),\n\t\t\t\tdelta: part.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-input-end\":\n\t\t\tfinishToolInput(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"tool-call\":\n\t\t\tfinalizeToolCall(output, part, model, stream);\n\t\t\tbreak;\n\t\tcase \"start-step\":\n\t\t\tstampProviderThinkingLevel(output, part.request.body);\n\t\t\tbreak;\n\t\tcase \"finish-step\":\n\t\t\toutput.responseId ||= part.response.id;\n\t\t\tif (part.response.modelId && part.response.modelId !== model.id)\n\t\t\t\toutput.responseModel ||= part.response.modelId;\n\t\t\tpricing.providerMetadata = part.providerMetadata ?? pricing.providerMetadata;\n\t\t\toutput.usage = mapUsage(part.usage, model, resolvePricing(model, pricing), pricing.providerMetadata);\n\t\t\toutput.stopReason = mapFinishReason(part.finishReason);\n\t\t\tbreak;\n\t\tcase \"finish\":\n\t\t\toutput.usage = mapUsage(part.totalUsage, model, resolvePricing(model, pricing), pricing.providerMetadata);\n\t\t\toutput.stopReason = mapFinishReason(part.finishReason);\n\t\t\tbreak;\n\t\tcase \"abort\":\n\t\t\toutput.stopReason = \"aborted\";\n\t\t\tif (part.reason !== undefined) output.errorMessage = part.reason;\n\t\t\tbreak;\n\t\tcase \"error\":\n\t\t\tthrow part.error instanceof Error ? part.error : new Error(formatThrownError(part.error));\n\t}\n}\n\nfunction stampProviderThinkingLevel(output: Message.AssistantMessage, body: unknown): void {\n\tconst level = Thinking.providerThinkingLevel(body);\n\tif (level !== undefined) output.providerThinkingLevel = level;\n}\n\n/** A request the provider refused never streams a `start-step`; its body travels on the error. */\nfunction rejectedRequestBody(error: unknown): unknown {\n\tif (RetryError.isInstance(error)) return rejectedRequestBody(error.lastError);\n\treturn APICallError.isInstance(error) ? error.requestBodyValues : undefined;\n}\n\nfunction resolvePricing(model: Model.Info, pricing: Pricing): number {\n\treturn Pricing.serviceTierCostMultiplier(\n\t\tmodel,\n\t\tPricing.servedServiceTier(model, pricing.requestedServiceTier, pricing.providerMetadata),\n\t);\n}\n\n/**\n * The response ceiling to send, already fitted around the thinking budget by\n * {@link Thinking.resolvePlan}.\n *\n * `plan.maxTokens` is the whole response -- thinking and answer together, which is\n * what Anthropic's own `max_tokens` means. But `@ai-sdk/anthropic` treats\n * `maxOutputTokens` as the answer alone and adds the budget back on before sending\n * (`baseArgs.max_tokens = maxTokens + thinkingBudget`). Handing it the total there\n * would ask for the budget twice, so it gets the answer room and reconstructs the\n * total itself.\n *\n * That only applies when a budget is actually sent. An adaptive model is given an\n * effort level and no budget, so the SDK adds nothing and the total goes through\n * unchanged -- subtracting there would quietly under-ask by the whole budget.\n */\nexport function resolveMaxOutputTokens(model: Model.Info, plan: Thinking.Plan): number | undefined {\n\tconst key = Model.optionsKey(model);\n\t// The ChatGPT Codex backend rejects max_output_tokens, so never send it.\n\tif (key === \"openai-codex\") return undefined;\n\tif (plan.maxTokens === undefined) return undefined;\n\n\tconst sendsBudget = Thinking.isAnthropicMessagesModel(model) && !model.compat?.forceAdaptiveThinking;\n\treturn sendsBudget ? plan.maxTokens - plan.budget : plan.maxTokens;\n}\n\n/** A bare number is a total ceiling only; the idle timeout has to be spelled per chunk. */\nfunction resolveTimeout(options: RuntimeOptions): Parameters<typeof streamText<ToolSet>>[0][\"timeout\"] {\n\tconst { timeoutMs, idleTimeoutMs } = options;\n\tif (timeoutMs === undefined && idleTimeoutMs === undefined) return undefined;\n\treturn compact({ totalMs: timeoutMs, firstChunkMs: idleTimeoutMs, chunkMs: idleTimeoutMs });\n}\n\nexport const stream: Protocol.StreamFunction<Model.KnownProviderEnum, typeof Options> = (model, context, options) => {\n\tconst stream = new AssistantMessageEventStream();\n\tconst runtimeOptions = applyDefaultMaxTokens(model, (options ?? {}) as RuntimeOptions);\n\n\tvoid (async () => {\n\t\tconst output = createAssistantMessage(model, runtimeOptions.reasoning ?? \"off\");\n\t\ttry {\n\t\t\tconst plan = Thinking.resolvePlan(model, context, runtimeOptions);\n\t\t\tconst languageModel = await resolveAISDKLanguageModel(model, runtimeOptions, plan.budget);\n\t\t\t// Every tool callable now, so calls to tools declared in place still parse.\n\t\t\tconst declared = requestTools(context, model, runtimeOptions.method, runtimeOptions.activeTools);\n\t\t\tconst messages = convertMessages(context, model, runtimeOptions.method, runtimeOptions.activeTools);\n\t\t\tconst providerOptions = resolveProviderOptions(model, context, runtimeOptions, plan) as Parameters<\n\t\t\t\ttypeof streamText<ToolSet>\n\t\t\t>[0][\"providerOptions\"];\n\t\t\tconst pricing: Pricing = {\n\t\t\t\trequestedServiceTier: Pricing.requestedServiceTier(\n\t\t\t\t\tmodel,\n\t\t\t\t\truntimeOptions,\n\t\t\t\t\tproviderOptions as ProviderOptionBag,\n\t\t\t\t),\n\t\t\t};\n\n\t\t\tconst buildParams = async (preferNonStrict: boolean) => {\n\t\t\t\tconst tools = convertTools(\n\t\t\t\t\tdeclared.tools,\n\t\t\t\t\tmodel,\n\t\t\t\t\truntimeOptions.method,\n\t\t\t\t\tdeclared.deferred,\n\t\t\t\t\tpreferNonStrict,\n\t\t\t\t);\n\t\t\t\tconst sentPreferStrict =\n\t\t\t\t\tdeclared.tools?.some(\n\t\t\t\t\t\t(tool) =>\n\t\t\t\t\t\t\ttool.constrainedSampling &&\n\t\t\t\t\t\t\ttool.constrainedSampling.type === \"json_schema\" &&\n\t\t\t\t\t\t\ttool.constrainedSampling.strict === \"prefer\" &&\n\t\t\t\t\t\t\ttools?.[tool.name]?.strict === true,\n\t\t\t\t\t) ?? false;\n\t\t\t\tconst activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = compact({\n\t\t\t\t\tmodel: languageModel,\n\t\t\t\t\t// Our own Responses transport receives the system prompt among the messages.\n\t\t\t\t\tsystem: isOwnResponses(model, runtimeOptions.method)\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: leadingSystemPrompt(context, model, runtimeOptions.method),\n\t\t\t\t\tmessages,\n\t\t\t\t\t// Prompt and tool changes sent in place travel as system messages.\n\t\t\t\t\tallowSystemInMessages: messages.some((message) => message.role === \"system\") || undefined,\n\t\t\t\t\ttools,\n\t\t\t\t\ttoolChoice: runtimeOptions.toolChoice as Parameters<typeof streamText<ToolSet>>[0][\"toolChoice\"],\n\t\t\t\t\tactiveTools,\n\t\t\t\t\tmaxOutputTokens: resolveMaxOutputTokens(model, plan),\n\t\t\t\t\ttemperature: model.compat?.supportsTemperature === false ? undefined : runtimeOptions.temperature,\n\t\t\t\t\tproviderOptions,\n\t\t\t\t\t// The exact body is where `providerThinkingLevel` is read from.\n\t\t\t\t\tinclude: { requestBody: true },\n\t\t\t\t\tabortSignal: runtimeOptions.signal,\n\t\t\t\t\ttimeout: resolveTimeout(runtimeOptions),\n\t\t\t\t\tmaxRetries: runtimeOptions.maxRetries,\n\t\t\t\t\theaders: runtimeOptions.headers,\n\t\t\t\t\t// Aikit owns error normalization and emits one terminal error event.\n\t\t\t\t\t// AI SDK's default callback logs the raw exception (including request\n\t\t\t\t\t// payloads) before that event can reach an SDK or CLI consumer.\n\t\t\t\t\tonError: () => {},\n\t\t\t\t});\n\n\t\t\t\tconst payload = await runtimeOptions.onPayload?.(params, model);\n\t\t\t\tif (payload !== undefined) {\n\t\t\t\t\tparams = payload as Parameters<typeof streamText<ToolSet>>[0];\n\t\t\t\t}\n\t\t\t\treturn { params, sentPreferStrict };\n\t\t\t};\n\n\t\t\tlet preferNonStrict = false;\n\t\t\tlet built = await buildParams(preferNonStrict);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tfor (;;) {\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const part of streamText(built.params).fullStream) {\n\t\t\t\t\t\thandlePart(part, output, model, stream, pricing);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Claude refuses the whole request when strict tools exceed its limits, and `prefer` tools\n\t\t\t\t\t// can go non-strict instead. Only a request refused before anything streamed is retried, once.\n\t\t\t\t\tconst limitMessage = Failure.strictToolLimitMessage(error);\n\t\t\t\t\tif (\n\t\t\t\t\t\tpreferNonStrict ||\n\t\t\t\t\t\truntimeOptions.signal?.aborted ||\n\t\t\t\t\t\toutput.parts.length > 0 ||\n\t\t\t\t\t\t!built.sentPreferStrict ||\n\t\t\t\t\t\t!isAnthropicWire(model, resolveMethod(model, runtimeOptions.method)) ||\n\t\t\t\t\t\tlimitMessage === undefined\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\t(output.diagnostics ??= []).push({\n\t\t\t\t\t\ttype: \"strictToolsFallback\",\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\terror: { message: limitMessage },\n\t\t\t\t\t\tdetails: { reason: \"strictToolLimits\" },\n\t\t\t\t\t});\n\t\t\t\t\tpreferNonStrict = true;\n\t\t\t\t\tbuilt = await buildParams(preferNonStrict);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (runtimeOptions.signal?.aborted || output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"provider returned an error stop reason\");\n\t\t\t}\n\n\t\t\toutput.time.completed = Date.now();\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.parts) {\n\t\t\t\tdelete (block as TextBlock).streamId;\n\t\t\t\tdelete (block as ThinkingBlock).streamId;\n\t\t\t\tdelete (block as StreamingToolCallBlock).partialJson;\n\t\t\t}\n\t\t\toutput.time.completed = Date.now();\n\t\t\t// Only the caller's signal means \"stop\". An abort from inside the SDK, such as its\n\t\t\t// `timeoutMs` timer, is a failure the caller did not ask for.\n\t\t\tstampProviderThinkingLevel(output, rejectedRequestBody(error));\n\t\t\toutput.stopReason = runtimeOptions.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tif (output.stopReason === \"aborted\") {\n\t\t\t\toutput.errorMessage = formatThrownError(error);\n\t\t\t} else {\n\t\t\t\toutput.failure = Failure.normalize(error);\n\t\t\t\toutput.errorMessage = output.failure.message;\n\t\t\t}\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n","import * as Model from \"../model/model.ts\";\nimport { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { stream } from \"./stream.ts\";\n\nexport { Options } from \"./options.ts\";\nexport * from \"./registry.ts\";\nexport { stream } from \"./stream.ts\";\nexport * from \"./transform.ts\";\n\nexport function createAISDKProtocol(\n\tprotocol: Model.KnownProviderEnum,\n): Protocol.Protocol<Model.KnownProviderEnum, typeof Options> {\n\treturn {\n\t\tprotocol,\n\t\tstream,\n\t};\n}\n\nexport function registerAISDKProtocols(): void {\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.anthropic));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.google));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertex));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertexAnthropic));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openai));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCompatible));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCodex));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.githubCopilot));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openrouter));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.xai));\n}\n","import { registerAISDKProtocols } from \"./index.ts\";\n\nregisterAISDKProtocols();\n","import \"./llm/register.ts\";\n\nimport type * as Message from \"./message/message.ts\";\nimport type * as Model from \"./model/model.ts\";\nimport * as Protocol from \"./llm/protocol.ts\";\nimport type { AssistantMessageEventStream } from \"./utils/eventstream.ts\";\n\n/**\n * Stream assistant responses for a model and context.\n *\n * Example:\n *\n * ```ts\n * const s = stream(model, context, {\n * apiKey: process.env.ANTHROPIC_API_KEY,\n * });\n *\n * for await (const event of s) {\n * if (event.type === \"text.delta\") {\n * process.stdout.write(event.delta);\n * }\n * }\n *\n * const message = await s.result();\n * ```\n *\n * This export also includes convenience helpers:\n *\n * ```ts\n * const message = await stream.complete(model, context, options);\n * ```\n */\ntype StreamCallable = {\n\t<TProtocol extends Protocol.ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: Protocol.OptionsFor<TProtocol>,\n\t): AssistantMessageEventStream;\n\tcomplete: typeof Protocol.complete;\n\tresolveProtocolProvider: typeof Protocol.resolveProtocolProvider;\n};\n\nconst streamImpl = <TProtocol extends Protocol.ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: Protocol.OptionsFor<TProtocol>,\n): AssistantMessageEventStream => Protocol.stream(model, context, options);\n\n/**\n * Start a streaming assistant response for a model/context pair.\n *\n * This is the main streaming entrypoint.\n * Attached helpers:\n *\n * - `stream.complete(...)` resolves the final assistant message without manually iterating events.\n * - `stream.resolveProtocolProvider(...)` exposes protocol resolution for advanced integrations.\n */\nexport const stream = Object.assign(streamImpl, {\n\tcomplete: Protocol.complete,\n\tresolveProtocolProvider: Protocol.resolveProtocolProvider,\n}) as StreamCallable;\n\n/** Resolve a streamed response directly to the final assistant message. */\nexport const complete = Protocol.complete;\n","/**\n * @description Validation powered by TypeBox's built-in schema compiler.\n */\n\nimport type { Static, TSchema } from \"typebox\";\nimport Schema from \"typebox/schema\";\nimport Value from \"typebox/value\";\n\nimport { nullableVariant, schemaAllowsNull } from \"../llm/strict.ts\";\nimport type * as Message from \"../message/message.ts\";\n\nconst validators = new WeakMap<TSchema, ReturnType<typeof Schema.Compile>>();\n\nfunction getValidator<T extends TSchema>(schema: T): ReturnType<typeof Schema.Compile<T>> {\n\tconst existing = validators.get(schema) as ReturnType<typeof Schema.Compile<T>> | undefined;\n\tif (existing) return existing;\n\n\tconst validator = Schema.Compile(schema);\n\tvalidators.set(schema, validator);\n\treturn validator;\n}\n\nfunction errorPath(error: { instancePath?: string; params?: Record<string, unknown> }): string {\n\tif (error.instancePath) return error.instancePath.substring(1);\n\n\tconst requiredProperties = error.params?.requiredProperties;\n\tif (Array.isArray(requiredProperties)) return requiredProperties.join(\", \");\n\n\treturn \"root\";\n}\n\ntype JsonSchemaObject = {\n\tproperties?: Record<string, JsonSchemaObject>;\n\trequired?: string[];\n\titems?: JsonSchemaObject | JsonSchemaObject[];\n\t$ref?: unknown;\n};\n\n/**\n * Drop `null` from optional properties whose schema does not accept null, in place. Strict constrained sampling\n * makes every property required and nullable, so the model answers an omitted optional argument with `null`.\n */\nexport function normalizeOptionalNulls(value: unknown, schema: unknown): void {\n\tconst variant = nullableVariant(schema);\n\tif (variant !== undefined) return normalizeOptionalNulls(value, variant);\n\tconst node = schema as JsonSchemaObject;\n\tif (Array.isArray(value)) {\n\t\tif (Array.isArray(node.items)) {\n\t\t\tfor (const [index, item] of value.entries()) {\n\t\t\t\tif (node.items[index]) normalizeOptionalNulls(item, node.items[index]);\n\t\t\t}\n\t\t} else if (node.items) {\n\t\t\tfor (const item of value) normalizeOptionalNulls(item, node.items);\n\t\t}\n\t\treturn;\n\t}\n\tif (typeof value !== \"object\" || value === null || !node.properties) return;\n\n\tconst object = value as Record<string, unknown>;\n\tconst required = new Set(node.required ?? []);\n\tfor (const [key, property] of Object.entries(node.properties)) {\n\t\tif (!(key in object)) continue;\n\t\tif (\n\t\t\tobject[key] === null &&\n\t\t\t!required.has(key) &&\n\t\t\ttypeof property.$ref !== \"string\" &&\n\t\t\t!schemaAllowsNull(property)\n\t\t) {\n\t\t\tdelete object[key];\n\t\t} else {\n\t\t\tnormalizeOptionalNulls(object[key], property);\n\t\t}\n\t}\n}\n\n/**\n * Validates an arbitrary value against a TypeBox schema and returns the coerced value.\n */\nexport function validateSchema<T extends TSchema>(schema: T, value: unknown, label: string): Static<T> {\n\tconst validator = getValidator(schema);\n\tconst input = Value.Convert(schema, structuredClone(value));\n\n\ttry {\n\t\treturn validator.Parse(input);\n\t} catch {\n\t\tconst [_result, validationErrors] = validator.Errors(input);\n\t\tconst errors =\n\t\t\tvalidationErrors\n\t\t\t\t.map((err) => {\n\t\t\t\t\treturn ` - ${errorPath(err)}: ${err.message}`;\n\t\t\t\t})\n\t\t\t\t.join(\"\\n\") || \"Unknown Validation Error\";\n\n\t\tthrow new Error(\n\t\t\t[\n\t\t\t\t`Validation Failed For ${label}`,\n\t\t\t\t`${errors}\\n`,\n\t\t\t\t\"Received Value:\",\n\t\t\t\t`${JSON.stringify(value, null, 2)}\\n`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n}\n\n/**\n * Finds a tool by name and validates the tool call arguments against its TypeBox schema\n */\nexport function validateToolCall<T extends Message.Tool>(\n\ttools: T[],\n\ttoolExecution: Message.ToolCallInFlight,\n): Message.ToolArguments<T> {\n\tconst tool = tools.find((t) => t.name === toolExecution.name);\n\tif (!tool) {\n\t\tthrow new Error(`tool \"${toolExecution.name}\" not found`);\n\t}\n\treturn validateToolArguments(tool, toolExecution);\n}\n\n/**\n * Validates tool call arguments against the tool's TypeBox schema\n */\nexport function validateToolArguments<T extends Message.Tool>(\n\ttool: T,\n\ttoolExecution: Message.ToolCallInFlight,\n): Message.ToolArguments<T> {\n\tconst args = structuredClone(toolExecution.rawArgs);\n\tnormalizeOptionalNulls(args, tool.parameters);\n\treturn validateSchema(tool.parameters, args, `Tool \"${toolExecution.name}\"`) as Message.ToolArguments<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAMA,MAAa,sBAAsB;CAClC,OAAO;CAEP,WAAW;CACX,WAAW;CACX,SAAS;CAET,eAAe;CACf,eAAe;CACf,aAAa;CAEb,eAAe;CACf,eAAe;CACf,aAAa;CACb,eAAe;CAEf,MAAM;CACN,OAAO;AACR;;;;;;;;;AAWA,MAAa,wBAAwBA,OAAK,MAAM;CAC/CA,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,KAAK;EAC5C,SAASC;CACV,CAAC;CACDD,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,SAAS;EAChD,WAAWA,OAAK,OAAO;EACvB,SAASC;CACV,CAAC;CACDD,OAAK,OAAO;EACX,MAAMA,OAAK,QAAQ,oBAAoB,SAAS;EAChD,WAA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