@codeworksh/aikit 0.10.0 → 0.11.0-dev.20261012155220

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.
Files changed (34) hide show
  1. package/cli.mjs +3 -3
  2. package/{copilot-bFammM5T.mjs → copilot-JLgwmznn.mjs} +2 -2
  3. package/{copilot-bFammM5T.mjs.map → copilot-JLgwmznn.mjs.map} +1 -1
  4. package/{copilot-headers-01-kLz8g.mjs → copilot-headers-BvQ3FFn-.mjs} +2 -2
  5. package/{copilot-headers-01-kLz8g.mjs.map → copilot-headers-BvQ3FFn-.mjs.map} +1 -1
  6. package/{failure-CN0horoO.mjs → failure-DFQNKc-O.mjs} +23 -6
  7. package/failure-DFQNKc-O.mjs.map +1 -0
  8. package/{github-copilot-eDhLBMfL.mjs → github-copilot-C7oJ2Tfp.mjs} +2 -2
  9. package/{github-copilot-eDhLBMfL.mjs.map → github-copilot-C7oJ2Tfp.mjs.map} +1 -1
  10. package/github-copilot-CLJx-bcP.mjs +3 -0
  11. package/index.d.mts +46 -6
  12. package/index.mjs +238 -16
  13. package/index.mjs.map +1 -1
  14. package/llm/failure.mjs +1 -1
  15. package/{model-Czo0SKj0.mjs → model-D-FoGzVN.mjs} +5 -3
  16. package/model-D-FoGzVN.mjs.map +1 -0
  17. package/{model-yhqJA3dm.d.mts → model-DCfjY0fS.d.mts} +2 -2
  18. package/{modelgen-BHm-jA64.mjs → modelgen-D6UBM1fq.mjs} +5 -5
  19. package/modelgen-D6UBM1fq.mjs.map +1 -0
  20. package/modelgen.d.mts +1 -1
  21. package/modelgen.mjs +1 -1
  22. package/oauth/github/copilot.mjs +1 -1
  23. package/openai-codex-CIBVNhQx.mjs +2 -0
  24. package/{openai-codex-MpxV35tx.mjs → openai-codex-Dj0oh0UV.mjs} +26 -15
  25. package/openai-codex-Dj0oh0UV.mjs.map +1 -0
  26. package/package.json +1 -1
  27. package/{registry-CZtcfRPL.mjs → registry-CfGgGfSs.mjs} +4 -4
  28. package/{registry-CZtcfRPL.mjs.map → registry-CfGgGfSs.mjs.map} +1 -1
  29. package/failure-CN0horoO.mjs.map +0 -1
  30. package/github-copilot-gMaBI_-X.mjs +0 -3
  31. package/model-Czo0SKj0.mjs.map +0 -1
  32. package/modelgen-BHm-jA64.mjs.map +0 -1
  33. package/openai-codex-CvdfMYoU.mjs +0 -2
  34. package/openai-codex-MpxV35tx.mjs.map +0 -1
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","Type","Model.ThinkingBudgets","Type","Model.APIMethodEnumSchema","Model.ActiveThinkingLevel","Model.optionsKey","Protocol.ProtocolAuthError","Model.thinkingTokenBudgetField","Model.optionsKey","Model.clampThinkingLevel","partialParse","Message.createAssistantMessage","Model.optionsKey","Message.transformMessages","Message.resolveJsonSchemaConstraint","Pricing.cacheWrite1hTokens","Model.optionsKey","Thinking.isAnthropicMessagesModel","Thinking.reasoningProviderOptions","Pricing.serviceTierCostMultiplier","Pricing.servedServiceTier","stream","Thinking.resolvePlan","Pricing.requestedServiceTier","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/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/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 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\";\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 === \"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// Unlike Pi's separate tool-result messages, our results are attached to\n\t\t// the assistant turn after its usage was reported. Only its output is counted.\n\t\tconst latest = messages[usage.index]!;\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\n/** Tools discovered by execution of the given assistant turn or later turns. */\nfunction toolNamesAddedAfter(messages: ReadonlyArray<Message.Message>, index: number): Set<string> {\n\tconst names = new Set<string>();\n\tfor (let i = index; i < messages.length; i++) {\n\t\tconst message = messages[i]!;\n\t\tif (message.role !== \"assistant\") continue;\n\t\tfor (const part of message.parts) {\n\t\t\tif (part.type !== \"toolCall\") continue;\n\t\t\tfor (const name of part.addedToolNames ?? []) names.add(name);\n\t\t}\n\t}\n\treturn names;\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, so only what arrived since is added on top.\n\t */\n\tif (estimate.lastUsageIndex !== null) {\n\t\tconst added = toolNamesAddedAfter(context.messages, estimate.lastUsageIndex);\n\t\tconst addedTokens = estimateToolsTokens(context.tools?.filter((tool) => added.has(tool.name)));\n\t\treturn {\n\t\t\ttokens: estimate.tokens + addedTokens,\n\t\t\tusageTokens: estimate.usageTokens,\n\t\t\ttrailingTokens: estimate.trailingTokens + addedTokens,\n\t\t\tlastUsageIndex: estimate.lastUsageIndex,\n\t\t};\n\t}\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\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 { XaiLanguageModelChatOptions, 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 { OpenAICodexLanguageModelOptions, OpenAICodexProviderSettings } from \"../providers/openai-codex/index.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;\ntype XaiLanguageOptions = XaiLanguageModelResponsesOptions | XaiLanguageModelChatOptions;\ntype GitHubCopilotLanguageOptions =\n\t| AnthropicLanguageModelOptions\n\t| OpenAILanguageModelResponsesOptions\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\"?: OpenAICodexLanguageModelOptions }\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\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\tconst cacheDisabled =\n\t\t\toptions.cacheRetention === \"none\" ||\n\t\t\t(typeof process !== \"undefined\" && process.env.CODEWORK_CACHE_RETENTION === \"none\");\n\t\tif (options.sessionId && !cacheDisabled) factoryOptions.sessionId ??= options.sessionId;\n\t\tfactoryOptions.compat = {\n\t\t\t...model.compat,\n\t\t\tsupportsImages: model.input.includes(\"image\"),\n\t\t\t...(typeof factoryOptions.compat === \"object\" && factoryOptions.compat !== null ? factoryOptions.compat : {}),\n\t\t};\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.\n\t\tif (options.sessionId) factoryOptions.sessionId ??= options.sessionId;\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 when context pressure reduces it. Pi's Anthropic wrapper\n\t * applies this reserve unconditionally; 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.\n\t\tif (model.thinkingLevelMap?.off === null) return {};\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; on\n\t\t// Responses it rejects `reasoningEffort: \"none\"`, and the chat route has no\n\t\t// reasoning control at all.\n\t\tif (model.api?.method === Model.APIMethodEnum.messages) {\n\t\t\treturn { [key]: { thinking: { type: \"disabled\" } } };\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/**\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\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 {\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 * as Message from \"../message/message.ts\";\nimport { Pricing } from \"./pricing.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { resolveOpenAICodexToolConstraint } from \"../providers/openai-codex/codex-tools.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/jsonparse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize.ts\";\n\ntype ToolCallPart = Extract<Message.AssistantMessage[\"parts\"][number], { type: \"toolCall\" }>;\ntype TerminalToolCall = Exclude<ToolCallPart, Message.ToolCallPendingPart | Message.ToolCallRunningPart>;\n\nexport function createAssistantMessage(model: Model.Info): 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\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\nfunction toolResultOutput(toolCall: TerminalToolCall) {\n\tconst text = toolCall.result.content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => sanitizeSurrogates(content.text))\n\t\t.join(\"\\n\");\n\tconst images = toolCall.result.content.filter((content) => content.type === \"image\");\n\n\tif (toolCall.result.isError) {\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) {\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\t// Copilot's Responses adapter is named \"github-copilot\", so its reasoning\n\t// metadata lands under that key rather than \"openai\".\n\tconst metadata = providerMetadata.openai ?? providerMetadata[\"github-copilot\"];\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\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(message: Message.AssistantMessage, model: Model.Info): 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 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 && message.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t\t? { providerOptions: { \"openai-codex\": { 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 (message.protocol === Model.KnownProviderEnum.githubCopilot) {\n\t\t\t\t/*\n\t\t\t\t * Copilot signs reasoning differently per endpoint family: Responses\n\t\t\t\t * models round-trip encoded item metadata, Messages models carry\n\t\t\t\t * Anthropic signatures, and the chat endpoint cannot replay thinking\n\t\t\t\t * at all. A signature from the wrong family is foreign material, so\n\t\t\t\t * the text survives as plain text instead of going out unsigned.\n\t\t\t\t */\n\t\t\t\tconst method = model.api?.method;\n\t\t\t\tconst openai = part.thinkingSignature ? decodeOpenAIReasoningSignature(part.thinkingSignature) : undefined;\n\t\t\t\tif (method === Model.APIMethodEnum.responses && 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: { \"github-copilot\": openai },\n\t\t\t\t\t} as (typeof assistantContent)[number]);\n\t\t\t\t} else if (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 =\n\t\t\t\t\tmessage.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t\t\t? { \"openai-codex\": { reasoningItem: part.thinkingSignature } }\n\t\t\t\t\t\t: { 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 codexToolMetadata: { namespace?: string; omitItemId?: boolean } = {};\n\t\tif (part.namespace && message.protocol === Model.KnownProviderEnum.openaiCodex) {\n\t\t\tcodexToolMetadata.namespace = part.namespace;\n\t\t}\n\t\tif (\n\t\t\tmodel.protocol === Model.KnownProviderEnum.openaiCodex &&\n\t\t\tmessage.protocol === model.protocol &&\n\t\t\tmessage.provider.id === model.provider.id &&\n\t\t\tmessage.model !== model.id\n\t\t) {\n\t\t\tcodexToolMetadata.omitItemId = true;\n\t\t}\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...(Object.keys(codexToolMetadata).length > 0\n\t\t\t\t? { providerOptions: { \"openai-codex\": codexToolMetadata } }\n\t\t\t\t: {}),\n\t\t});\n\n\t\tconst terminal = part.status === \"pending\" || part.status === \"running\" ? undefined : part;\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\t...(terminal?.addedToolNames?.length\n\t\t\t\t? { providerOptions: { \"openai-codex\": { addedToolNames: terminal.addedToolNames } } }\n\t\t\t\t: {}),\n\t\t\toutput: terminal\n\t\t\t\t? toolResultOutput(terminal)\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}\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\treturn result;\n}\n\nexport function convertMessages(context: Message.Context, model: Model.Info): ModelMessage[] {\n\tconst messages: ModelMessage[] = [];\n\tconst transformedMessages = Message.transformMessages(context.messages, model, toolCallIdNormalizer(model));\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tmessages.push(...userContent(msg.parts));\n\t\t\tcontinue;\n\t\t}\n\t\tmessages.push(...assistantMessages(msg, model));\n\t}\n\n\treturn messages;\n}\n\nexport function convertTools(tools?: Message.Tool[], model?: Model.Info): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tconst jsonSchemaConstraint = Message.resolveJsonSchemaConstraint(tool, model?.compat);\n\t\tconst grammarConstraint =\n\t\t\tmodel?.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t? resolveOpenAICodexToolConstraint(tool, model.compat)\n\t\t\t\t: undefined;\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(tool.parameters as any),\n\t\t\t...(jsonSchemaConstraint ? { strict: true } : {}),\n\t\t\t...(grammarConstraint?.type === \"grammar\"\n\t\t\t\t? { providerOptions: { \"openai-codex\": { grammar: grammarConstraint } } }\n\t\t\t\t: {}),\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 { 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 { formatThrownError } from \"./runtime.ts\";\nimport { applyDefaultMaxTokens } from \"./shared.ts\";\nimport * as Thinking from \"./thinking.ts\";\nimport {\n\tgoogleThoughtSignature,\n\tconvertMessages,\n\tconvertTools,\n\tcreateAssistantMessage,\n\tencodeOpenAIReasoningSignature,\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(model: Model.Info, options: RuntimeOptions, plan: Thinking.Plan): ProviderOptionBag {\n\treturn mergeProviderOptions(\n\t\tmodel.providerOptions as ProviderOptionBag | undefined,\n\t\tcacheProviderOptions(model, options),\n\t\tThinking.reasoningProviderOptions(model, plan),\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\nfunction openAICodexMetadata(value: unknown): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst metadata = (value as Record<string, unknown>)[\"openai-codex\"];\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\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 = openAICodexMetadata(part.providerMetadata)?.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 = openAICodexMetadata(part.providerMetadata)?.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 = openAICodexMetadata(part.providerMetadata)?.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, stream);\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 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\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);\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\tconst tools = convertTools(context.tools, model);\n\t\t\tconst messages = convertMessages(context, model);\n\t\t\tconst providerOptions = resolveProviderOptions(model, 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\t\t\tconst activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = compact({\n\t\t\t\tmodel: languageModel,\n\t\t\t\tsystem: context.systemPrompt,\n\t\t\t\tmessages,\n\t\t\t\ttools,\n\t\t\t\ttoolChoice: runtimeOptions.toolChoice as Parameters<typeof streamText<ToolSet>>[0][\"toolChoice\"],\n\t\t\t\tactiveTools,\n\t\t\t\tmaxOutputTokens: resolveMaxOutputTokens(model, plan),\n\t\t\t\ttemperature: runtimeOptions.temperature,\n\t\t\t\tproviderOptions,\n\t\t\t\tabortSignal: runtimeOptions.signal,\n\t\t\t\ttimeout: runtimeOptions.timeoutMs,\n\t\t\t\tmaxRetries: runtimeOptions.maxRetries,\n\t\t\t\theaders: runtimeOptions.headers,\n\t\t\t\t// Aikit owns error normalization and emits one terminal error event.\n\t\t\t\t// AI SDK's default callback logs the raw exception (including request\n\t\t\t\t// payloads) before that event can reach an SDK or CLI consumer.\n\t\t\t\tonError: () => {},\n\t\t\t});\n\n\t\t\tconst payload = await runtimeOptions.onPayload?.(params, model);\n\t\t\tif (payload !== undefined) {\n\t\t\t\tparams = payload as Parameters<typeof streamText<ToolSet>>[0];\n\t\t\t}\n\n\t\t\tconst result = streamText(params);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tfor await (const part of result.fullStream) {\n\t\t\t\thandlePart(part, output, model, stream, pricing);\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\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 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\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\treturn validateSchema(\n\t\ttool.parameters,\n\t\ttoolExecution.rawArgs,\n\t\t`Tool \"${toolExecution.name}\"`,\n\t) 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;EAClD,WAAWA,OAAK,OAAO;EACvB,SAASA,OAAK,OAAO;EACrB,SAASC;CACV,CA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AAE;EACnC,CAAC,CAAC,KAAK,IAAI,CACZ;CACD;AACD;;;;AAKA,SAAgB,iBACf,OACA,eAC2B;CAC3B,MAAM,OAAO,MAAM,MAAM,MAAM,EAAE,SAAS,cAAc,IAAI;CAC5D,IAAI,CAAC,MACJ,MAAM,IAAI,MAAM,SAAS,cAAc,KAAK,YAAY;CAEzD,OAAO,sBAAsB,MAAM,aAAa;AACjD;;;;AAKA,SAAgB,sBACf,MACA,eAC2B;CAC3B,OAAO,eACN,KAAK,YACL,cAAc,SACd,SAAS,cAAc,KAAK,EAC7B;AACD"}
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","Type","Model.ThinkingBudgets","Type","Model.APIMethodEnumSchema","Model.ActiveThinkingLevel","Model.optionsKey","Protocol.ProtocolAuthError","Model.thinkingTokenBudgetField","Model.optionsKey","Model.clampThinkingLevel","partialParse","Message.createAssistantMessage","Model.optionsKey","Message.transformMessages","Pricing.cacheWrite1hTokens","Model.optionsKey","Thinking.isAnthropicMessagesModel","Thinking.reasoningProviderOptions","Thinking.providerThinkingLevel","Pricing.serviceTierCostMultiplier","Pricing.servedServiceTier","stream","Thinking.resolvePlan","Pricing.requestedServiceTier","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/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 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\";\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 === \"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// Unlike Pi's separate tool-result messages, our results are attached to\n\t\t// the assistant turn after its usage was reported. Only its output is counted.\n\t\tconst latest = messages[usage.index]!;\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\n/** Tools discovered by execution of the given assistant turn or later turns. */\nfunction toolNamesAddedAfter(messages: ReadonlyArray<Message.Message>, index: number): Set<string> {\n\tconst names = new Set<string>();\n\tfor (let i = index; i < messages.length; i++) {\n\t\tconst message = messages[i]!;\n\t\tif (message.role !== \"assistant\") continue;\n\t\tfor (const part of message.parts) {\n\t\t\tif (part.type !== \"toolCall\") continue;\n\t\t\tfor (const name of part.addedToolNames ?? []) names.add(name);\n\t\t}\n\t}\n\treturn names;\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, so only what arrived since is added on top.\n\t */\n\tif (estimate.lastUsageIndex !== null) {\n\t\tconst added = toolNamesAddedAfter(context.messages, estimate.lastUsageIndex);\n\t\tconst addedTokens = estimateToolsTokens(context.tools?.filter((tool) => added.has(tool.name)));\n\t\treturn {\n\t\t\ttokens: estimate.tokens + addedTokens,\n\t\t\tusageTokens: estimate.usageTokens,\n\t\t\ttrailingTokens: estimate.trailingTokens + addedTokens,\n\t\t\tlastUsageIndex: estimate.lastUsageIndex,\n\t\t};\n\t}\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 { XaiLanguageModelChatOptions, 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 { OpenAICodexLanguageModelOptions, OpenAICodexProviderSettings } from \"../providers/openai-codex/index.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;\ntype XaiLanguageOptions = XaiLanguageModelResponsesOptions | XaiLanguageModelChatOptions;\ntype GitHubCopilotLanguageOptions =\n\t| AnthropicLanguageModelOptions\n\t| OpenAILanguageModelResponsesOptions\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\"?: OpenAICodexLanguageModelOptions }\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\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\tconst cacheDisabled =\n\t\t\toptions.cacheRetention === \"none\" ||\n\t\t\t(typeof process !== \"undefined\" && process.env.CODEWORK_CACHE_RETENTION === \"none\");\n\t\tif (options.sessionId && !cacheDisabled) factoryOptions.sessionId ??= options.sessionId;\n\t\tfactoryOptions.compat = {\n\t\t\t...model.compat,\n\t\t\tsupportsImages: model.input.includes(\"image\"),\n\t\t\t...(typeof factoryOptions.compat === \"object\" && factoryOptions.compat !== null ? factoryOptions.compat : {}),\n\t\t};\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.\n\t\tif (options.sessionId) factoryOptions.sessionId ??= options.sessionId;\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 when context pressure reduces it. Pi's Anthropic wrapper\n\t * applies this reserve unconditionally; 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; on\n\t\t// Responses it rejects `reasoningEffort: \"none\"`, and the chat route has no\n\t\t// reasoning control at all.\n\t\tif (model.api?.method === Model.APIMethodEnum.messages) {\n\t\t\treturn { [key]: { thinking: { type: \"disabled\" } } };\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.\n */\nexport function resolveStrictParameters(\n\ttool: Message.Tool,\n\tmodel?: Pick<Model.Info, \"protocol\" | \"compat\">,\n): Record<string, unknown> | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config || config.type !== \"json_schema\") 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 * as Message from \"../message/message.ts\";\nimport { Pricing } from \"./pricing.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { resolveOpenAICodexToolConstraint } from \"../providers/openai-codex/codex-tools.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/jsonparse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize.ts\";\nimport { resolveStrictParameters } from \"./strict.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\nfunction toolResultOutput(toolCall: TerminalToolCall) {\n\tconst text = toolCall.result.content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => sanitizeSurrogates(content.text))\n\t\t.join(\"\\n\");\n\tconst images = toolCall.result.content.filter((content) => content.type === \"image\");\n\n\tif (toolCall.result.isError) {\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) {\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\t// Copilot's Responses adapter is named \"github-copilot\", so its reasoning\n\t// metadata lands under that key rather than \"openai\".\n\tconst metadata = providerMetadata.openai ?? providerMetadata[\"github-copilot\"];\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\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(message: Message.AssistantMessage, model: Model.Info): 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 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 && message.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t\t? { providerOptions: { \"openai-codex\": { 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 (message.protocol === Model.KnownProviderEnum.githubCopilot) {\n\t\t\t\t/*\n\t\t\t\t * Copilot signs reasoning differently per endpoint family: Responses\n\t\t\t\t * models round-trip encoded item metadata, Messages models carry\n\t\t\t\t * Anthropic signatures, and the chat endpoint cannot replay thinking\n\t\t\t\t * at all. A signature from the wrong family is foreign material, so\n\t\t\t\t * the text survives as plain text instead of going out unsigned.\n\t\t\t\t */\n\t\t\t\tconst method = model.api?.method;\n\t\t\t\tconst openai = part.thinkingSignature ? decodeOpenAIReasoningSignature(part.thinkingSignature) : undefined;\n\t\t\t\tif (method === Model.APIMethodEnum.responses && 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: { \"github-copilot\": openai },\n\t\t\t\t\t} as (typeof assistantContent)[number]);\n\t\t\t\t} else if (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 =\n\t\t\t\t\tmessage.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t\t\t? { \"openai-codex\": { reasoningItem: part.thinkingSignature } }\n\t\t\t\t\t\t: { 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 codexToolMetadata: { namespace?: string; omitItemId?: boolean } = {};\n\t\tif (part.namespace && message.protocol === Model.KnownProviderEnum.openaiCodex) {\n\t\t\tcodexToolMetadata.namespace = part.namespace;\n\t\t}\n\t\tif (\n\t\t\tmodel.protocol === Model.KnownProviderEnum.openaiCodex &&\n\t\t\tmessage.protocol === model.protocol &&\n\t\t\tmessage.provider.id === model.provider.id &&\n\t\t\tmessage.model !== model.id\n\t\t) {\n\t\t\tcodexToolMetadata.omitItemId = true;\n\t\t}\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...(Object.keys(codexToolMetadata).length > 0\n\t\t\t\t? { providerOptions: { \"openai-codex\": codexToolMetadata } }\n\t\t\t\t: {}),\n\t\t});\n\n\t\tconst terminal = part.status === \"pending\" || part.status === \"running\" ? undefined : part;\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\t...(terminal?.addedToolNames?.length\n\t\t\t\t? { providerOptions: { \"openai-codex\": { addedToolNames: terminal.addedToolNames } } }\n\t\t\t\t: {}),\n\t\t\toutput: terminal\n\t\t\t\t? toolResultOutput(terminal)\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}\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\treturn result;\n}\n\nexport function convertMessages(context: Message.Context, model: Model.Info): ModelMessage[] {\n\tconst messages: ModelMessage[] = [];\n\tconst transformedMessages = Message.transformMessages(context.messages, model, toolCallIdNormalizer(model));\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tmessages.push(...userContent(msg.parts));\n\t\t\tcontinue;\n\t\t}\n\t\tmessages.push(...assistantMessages(msg, model));\n\t}\n\n\treturn messages;\n}\n\nexport function convertTools(tools?: Message.Tool[], model?: Model.Info): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tconst strictParameters = resolveStrictParameters(tool, model);\n\t\tconst grammarConstraint =\n\t\t\tmodel?.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t? resolveOpenAICodexToolConstraint(tool, model.compat)\n\t\t\t\t: undefined;\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(strictParameters ?? (tool.parameters as any)),\n\t\t\t...(strictParameters ? { strict: true } : {}),\n\t\t\t...(grammarConstraint ? { providerOptions: { \"openai-codex\": { grammar: grammarConstraint } } } : {}),\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 { formatThrownError } from \"./runtime.ts\";\nimport { applyDefaultMaxTokens } from \"./shared.ts\";\nimport * as Thinking from \"./thinking.ts\";\nimport {\n\tgoogleThoughtSignature,\n\tconvertMessages,\n\tconvertTools,\n\tcreateAssistantMessage,\n\tencodeOpenAIReasoningSignature,\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(model: Model.Info, options: RuntimeOptions, plan: Thinking.Plan): ProviderOptionBag {\n\treturn mergeProviderOptions(\n\t\tmodel.providerOptions as ProviderOptionBag | undefined,\n\t\tcacheProviderOptions(model, options),\n\t\tThinking.reasoningProviderOptions(model, plan),\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\nfunction openAICodexMetadata(value: unknown): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst metadata = (value as Record<string, unknown>)[\"openai-codex\"];\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\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 = openAICodexMetadata(part.providerMetadata)?.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 = openAICodexMetadata(part.providerMetadata)?.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 = openAICodexMetadata(part.providerMetadata)?.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, 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\tconst tools = convertTools(context.tools, model);\n\t\t\tconst messages = convertMessages(context, model);\n\t\t\tconst providerOptions = resolveProviderOptions(model, 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\t\t\tconst activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = compact({\n\t\t\t\tmodel: languageModel,\n\t\t\t\tsystem: context.systemPrompt,\n\t\t\t\tmessages,\n\t\t\t\ttools,\n\t\t\t\ttoolChoice: runtimeOptions.toolChoice as Parameters<typeof streamText<ToolSet>>[0][\"toolChoice\"],\n\t\t\t\tactiveTools,\n\t\t\t\tmaxOutputTokens: resolveMaxOutputTokens(model, plan),\n\t\t\t\ttemperature: runtimeOptions.temperature,\n\t\t\t\tproviderOptions,\n\t\t\t\t// The exact body is where `providerThinkingLevel` is read from.\n\t\t\t\tinclude: { requestBody: true },\n\t\t\t\tabortSignal: runtimeOptions.signal,\n\t\t\t\ttimeout: resolveTimeout(runtimeOptions),\n\t\t\t\tmaxRetries: runtimeOptions.maxRetries,\n\t\t\t\theaders: runtimeOptions.headers,\n\t\t\t\t// Aikit owns error normalization and emits one terminal error event.\n\t\t\t\t// AI SDK's default callback logs the raw exception (including request\n\t\t\t\t// payloads) before that event can reach an SDK or CLI consumer.\n\t\t\t\tonError: () => {},\n\t\t\t});\n\n\t\t\tconst payload = await runtimeOptions.onPayload?.(params, model);\n\t\t\tif (payload !== undefined) {\n\t\t\t\tparams = payload as Parameters<typeof streamText<ToolSet>>[0];\n\t\t\t}\n\n\t\t\tconst result = streamText(params);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tfor await (const part of result.fullStream) {\n\t\t\t\thandlePart(part, output, model, stream, pricing);\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,OAA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