@codeworksh/aikit 0.3.1 → 0.4.1-dev.20260530133305

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["partialParse","createClient","buildSyntheticToolResult","convertMessages","convertTools","mapStopReason","buildParams","anthropicProvider","openAICompletionsProvider"],"sources":["../../src/provider/provider.ts","../../src/model/catalog.ts","../../src/model/transform.ts","../../src/model/model.ts","../../src/provider/stream.ts","../../src/utils/eventstream.ts","../../src/utils/validation.ts","../../src/agent/loop.ts","../../src/agent.ts","../../src/message/message.ts","../../src/utils/jsonparse.ts","../../src/utils/sanitize.ts","../../src/provider/providers/utils.ts","../../src/provider/providers/anthropic/index.ts","../../src/provider/providers/github/github.ts","../../src/provider/providers/openai/completions.ts","../../src/provider/register.ts","../../src/agent/agent.ts","../../src/agent/codemode/codemode.ts","../../src/llm.ts","../../src/stream.ts"],"sourcesContent":["import { type Static, Type } from \"@sinclair/typebox\";\n\nexport namespace Provider {\n\texport const KnownProviderEnum = {\n\t\tanthropic: \"anthropic\",\n\t\topenai: \"openai\",\n\t\tgithubCopilot: \"github-copilot\",\n\t\topenrouter: \"openrouter\",\n\t\tgroq: \"groq\",\n\t\txai: \"xai\",\n\t\tcerebras: \"cerebras\",\n\t\tzai: \"zai\",\n\t\topencode: \"opencode\",\n\t} as const;\n\texport const KnownProviderSchema = Type.Union([\n\t\tType.Literal(KnownProviderEnum.anthropic),\n\t\tType.Literal(KnownProviderEnum.openai),\n\t\tType.Literal(KnownProviderEnum.githubCopilot),\n\t\tType.Literal(KnownProviderEnum.openrouter),\n\t\tType.Literal(KnownProviderEnum.groq),\n\t\tType.Literal(KnownProviderEnum.xai),\n\t\tType.Literal(KnownProviderEnum.cerebras),\n\t\tType.Literal(KnownProviderEnum.zai),\n\t\tType.Literal(KnownProviderEnum.opencode),\n\t]);\n\texport type KnownProvider = Static<typeof KnownProviderSchema>;\n\n\texport const Info = Type.Object({\n\t\tid: KnownProviderSchema,\n\t\tname: Type.String(),\n\t\tenv: Type.Array(Type.String()),\n\t\tkey: Type.Optional(Type.String()),\n\t\toptions: Type.Optional(Type.Record(Type.String(), Type.Any())),\n\t});\n\texport type Info = Static<typeof Info>;\n\n\texport const ReasoningEffortMapSchema = Type.Object({\n\t\tminimal: Type.Optional(Type.String()),\n\t\tlow: Type.Optional(Type.String()),\n\t\tmedium: Type.Optional(Type.String()),\n\t\thigh: Type.Optional(Type.String()),\n\t\txhigh: Type.Optional(Type.String()),\n\t});\n\texport type ReasoningEffortMap = Static<typeof ReasoningEffortMapSchema>;\n\texport type StrictReasoningEffortMap = {\n\t\t[K in keyof ReasoningEffortMap]-?: NonNullable<ReasoningEffortMap[K]>;\n\t};\n\n\texport const OpenRouterRoutingSchema = Type.Object({\n\t\tonly: Type.Optional(Type.Array(Type.String())),\n\t\torder: Type.Optional(Type.Array(Type.String())),\n\t});\n\texport type OpenRouterRouting = Static<typeof OpenRouterRoutingSchema>;\n\n\texport const VercelGatewayRoutingSchema = Type.Object({\n\t\tonly: Type.Optional(Type.Array(Type.String())),\n\t\torder: Type.Optional(Type.Array(Type.String())),\n\t});\n\texport type VercelGatewayRouting = Static<typeof VercelGatewayRoutingSchema>;\n}\n","import { Filesystem, lazy } from \"@codeworksh/utils\";\n\nexport namespace ModelCatalog {\n\texport interface ModelsDevModel {\n\t\tid: string;\n\t\tname: string;\n\t\tfamily: string;\n\t\tattachment: boolean;\n\t\treasoning?: boolean;\n\t\ttool_call?: boolean;\n\t\ttemperature?: boolean;\n\t\tknowledge?: string | boolean;\n\t\trelease_date: string;\n\t\tlast_updated: string;\n\t\tmodalities: {\n\t\t\tinput?: string[];\n\t\t\toutput: string[];\n\t\t};\n\t\topen_weights: boolean;\n\t\tbaseUrl?: string;\n\t\theaders?: Record<string, string>;\n\t\tcost?: {\n\t\t\tinput?: number;\n\t\t\toutput?: number;\n\t\t\tcache_read?: number;\n\t\t\tcache_write?: number;\n\t\t};\n\t\tlimit?: {\n\t\t\tcontext?: number;\n\t\t\toutput?: number;\n\t\t};\n\t}\n\texport interface ModelsDevProvider {\n\t\tid: string;\n\t\tenv: string[];\n\t\tnpm?: string;\n\t\tapi: string;\n\t\tbaseUrl?: string;\n\t\tname: string;\n\t\tdoc?: string;\n\t\tkey?: string;\n\t\theaders?: Record<string, string>;\n\t\tmodels: Record<string, ModelsDevModel>;\n\t}\n\t// Doesn't represent the full spec from models.dev.\n\t// Represents the provider entries on a best-effort basis.\n\texport type ModelsDevCatalog = Record<string, ModelsDevProvider>;\n\ttype LazyModelsDevCatalog = ReturnType<typeof lazy<Promise<ModelsDevCatalog>>>;\n\n\tfunction modelsDevURL(): string {\n\t\treturn process.env.OPENCODE_MODELS_URL || \"https://models.dev\";\n\t}\n\n\tfunction modelsDevPath(): string | undefined {\n\t\treturn process.env.CODEWORK_AIKIT_MODELS_PATH;\n\t}\n\n\texport const modelsDevData: LazyModelsDevCatalog = lazy(async () => {\n\t\tconst path = modelsDevPath();\n\t\tif (path) {\n\t\t\tconst result = await Filesystem.readJson<ModelsDevCatalog>(path).catch(() => undefined);\n\t\t\tif (result) return result;\n\t\t}\n\n\t\tconst json = await fetch(`${modelsDevURL()}/api.json`).then((x) => x.text());\n\t\treturn JSON.parse(json) as ModelsDevCatalog;\n\t});\n\n\texport async function get(): Promise<ModelsDevCatalog> {\n\t\treturn modelsDevData();\n\t}\n\n\texport async function refresh(): Promise<void> {\n\t\tconst result = await fetch(`${modelsDevURL()}/api.json`, {\n\t\t\tsignal: AbortSignal.timeout(10 * 1000),\n\t\t}).catch(() => undefined);\n\t\tif (!result?.ok) return;\n\n\t\tconst json = await result.text();\n\t\tconst path = modelsDevPath();\n\t\tif (path) {\n\t\t\tawait Filesystem.write(path, json);\n\t\t}\n\t\tmodelsDevData.reset();\n\t}\n\n\tvoid ModelCatalog.refresh();\n\tsetInterval(\n\t\tasync () => {\n\t\t\tawait ModelCatalog.refresh();\n\t\t},\n\t\t60 * 1000 * 60,\n\t).unref();\n}\n","import { Provider } from \"../provider/provider\";\nimport type { ModelCatalog } from \"./catalog\";\nimport { Model } from \"./model\";\n\nfunction defaultBaseUrl(providerId: Provider.KnownProvider): string | undefined {\n\tswitch (providerId) {\n\t\tcase Provider.KnownProviderEnum.openai:\n\t\t\treturn \"https://api.openai.com/v1\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction resolveDefaultProtocol(providerId: Provider.KnownProvider): Model.KnownProtocol {\n\tswitch (providerId) {\n\t\tcase Provider.KnownProviderEnum.anthropic:\n\t\t\treturn Model.KnownProtocolEnum.anthropicMessages;\n\t\tcase Provider.KnownProviderEnum.openai:\n\t\t\treturn Model.KnownProtocolEnum.openaiResponses;\n\t\tdefault:\n\t\t\treturn Model.KnownProtocolEnum.openaiCompletions;\n\t}\n}\n\nexport function applyModification(\n\tproviderId: Provider.KnownProvider,\n\tprovider: ModelCatalog.ModelsDevProvider,\n\tmodel: ModelCatalog.ModelsDevModel,\n): Model.Info {\n\tconst baseUrl = model.baseUrl ?? provider.baseUrl ?? provider.api ?? defaultBaseUrl(providerId);\n\tconst normalized: Model.Info = {\n\t\tid: model.id,\n\t\tname: model.name,\n\t\tprovider: Model.toProviderInfo(providerId, provider),\n\t\tbaseUrl,\n\t\treasoning: Boolean(model.reasoning),\n\t\tinput: Model.normalizeInput(model.modalities.input),\n\t\tcost: {\n\t\t\tinput: model.cost?.input ?? 0,\n\t\t\toutput: model.cost?.output ?? 0,\n\t\t\tcacheRead: model.cost?.cache_read ?? 0,\n\t\t\tcacheWrite: model.cost?.cache_write ?? 0,\n\t\t},\n\t\tcontextWindow: model.limit?.context ?? 0,\n\t\tmaxTokens: model.limit?.output ?? 0,\n\t\theaders: model.headers ?? provider.headers,\n\t\tprotocol: resolveDefaultProtocol(providerId),\n\t};\n\t//\n\t// add support for multiple known protocols\n\tif (providerId === Provider.KnownProviderEnum.openai) {\n\t\tnormalized.supportedProtocols = {\n\t\t\topenaiCompletions: Model.KnownProtocolEnum.openaiCompletions,\n\t\t};\n\t\treturn normalized;\n\t} else {\n\t\treturn normalized;\n\t}\n}\n","import { lazy } from \"@codeworksh/utils\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport { keys, mapValues, pick, pipe } from \"remeda\";\nimport { Provider } from \"../provider/provider\";\nimport { ModelCatalog } from \"./catalog\";\nimport { applyModification } from \"./transform\";\n\nexport namespace Model {\n\texport const KnownProtocolEnum = {\n\t\tanthropicMessages: \"anthropic-messages\",\n\t\topenaiCompletions: \"openai-completions\",\n\t\topenaiResponses: \"openai-responses\",\n\t} as const;\n\texport const KnownProtocolSchema = Type.Union([\n\t\tType.Literal(KnownProtocolEnum.anthropicMessages),\n\t\tType.Literal(KnownProtocolEnum.openaiCompletions),\n\t\tType.Literal(KnownProtocolEnum.openaiResponses),\n\t]);\n\texport type KnownProtocol = Static<typeof KnownProtocolSchema>;\n\n\tconst InputSchema = Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]));\n\tconst CostSchema = Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t});\n\tconst HeadersSchema = Type.Optional(Type.Record(Type.String(), Type.String()));\n\n\texport const SupportedProtocolsSchema = Type.Object({\n\t\tanthropicMessages: Type.Optional(Type.Literal(KnownProtocolEnum.anthropicMessages)),\n\t\topenaiCompletions: Type.Optional(Type.Literal(KnownProtocolEnum.openaiCompletions)),\n\t\topenaiResponses: Type.Optional(Type.Literal(KnownProtocolEnum.openaiResponses)),\n\t});\n\t//\n\t// reprsents common base schema for a model\n\texport const BaseSchema = Type.Object({\n\t\tid: Type.String(),\n\t\tname: Type.String(),\n\t\tprovider: Provider.Info,\n\t\tbaseUrl: Type.String(),\n\t\treasoning: Type.Boolean(),\n\t\tinput: InputSchema,\n\t\tcost: CostSchema,\n\t\tcontextWindow: Type.Number(),\n\t\tmaxTokens: Type.Number(),\n\t\theaders: HeadersSchema,\n\t\tsupportedProtocols: Type.Optional(Type.Partial(SupportedProtocolsSchema)), // optionally supported protocols\n\t});\n\n\t/**\n\t * Compatibility settings for OpenAI-compatible completions APIs.\n\t * Use this to override URL-based auto-detection for custom providers.\n\t */\n\texport const OpenAICompletionsCompatSchema = Type.Object({\n\t\tsupportsStore: Type.Optional(Type.Boolean()),\n\t\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\t\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\t\treasoningEffortMap: Type.Optional(Provider.ReasoningEffortMapSchema),\n\t\tsupportsUsageInStreaming: Type.Optional(Type.Boolean()),\n\t\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n\t\trequiresToolResultName: Type.Optional(Type.Boolean()),\n\t\trequiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),\n\t\trequiresThinkingAsText: Type.Optional(Type.Boolean()),\n\t\tthinkingFormat: Type.Optional(\n\t\t\tType.Union([\n\t\t\t\tType.Literal(\"openai\"),\n\t\t\t\tType.Literal(\"openrouter\"),\n\t\t\t\tType.Literal(\"zai\"),\n\t\t\t\tType.Literal(\"qwen\"),\n\t\t\t\tType.Literal(\"qwen-chat-template\"),\n\t\t\t]),\n\t\t),\n\t\topenRouterRouting: Type.Optional(Provider.OpenRouterRoutingSchema),\n\t\tvercelGatewayRouting: Type.Optional(Provider.VercelGatewayRoutingSchema),\n\t\tzaiToolStream: Type.Optional(Type.Boolean()),\n\t\tsupportsStrictMode: Type.Optional(Type.Boolean()),\n\t});\n\texport type OpenAICompletionsCompat = Static<typeof OpenAICompletionsCompatSchema>;\n\n\t/** Compatibility settings for OpenAI Responses APIs. */\n\texport const OpenAIResponsesCompatSchema = Type.Object({});\n\texport type OpenAIResponsesCompat = Static<typeof OpenAIResponsesCompatSchema>;\n\n\texport const OpenAICompatSchema = Type.Union([OpenAICompletionsCompatSchema, OpenAIResponsesCompatSchema]);\n\n\texport const AnthropicSchema = Type.Composite([\n\t\tBaseSchema,\n\t\tType.Object({\n\t\t\tprotocol: Type.Literal(KnownProtocolEnum.anthropicMessages),\n\t\t}),\n\t]);\n\n\texport const OpenAICompletionsSchema = Type.Composite([\n\t\tBaseSchema,\n\t\tType.Object({\n\t\t\tprotocol: Type.Literal(KnownProtocolEnum.openaiCompletions),\n\t\t\tcompat: Type.Optional(OpenAICompletionsCompatSchema),\n\t\t}),\n\t]);\n\texport const OpenAIResponsesSchema = Type.Composite([\n\t\tBaseSchema,\n\t\tType.Object({\n\t\t\tprotocol: Type.Literal(KnownProtocolEnum.openaiResponses),\n\t\t\tcompat: Type.Optional(OpenAIResponsesCompatSchema),\n\t\t}),\n\t]);\n\n\texport const Info = Type.Union([AnthropicSchema, OpenAICompletionsSchema, OpenAIResponsesSchema]);\n\texport type Info = Static<typeof Info>;\n\texport type TModel<TProtocol extends KnownProtocol> = Extract<Info, { protocol: TProtocol }>;\n\tconst BUILTINS = keys(Provider.KnownProviderEnum) as Provider.KnownProvider[];\n\n\texport function calculateCost(\n\t\tmodel: Info,\n\t\tusage: {\n\t\t\tinput: number;\n\t\t\toutput: number;\n\t\t\tcacheRead: number;\n\t\t\tcacheWrite: number;\n\t\t\tcost: {\n\t\t\t\tinput: number;\n\t\t\t\toutput: number;\n\t\t\t\tcacheRead: number;\n\t\t\t\tcacheWrite: number;\n\t\t\t\ttotal: number;\n\t\t\t};\n\t\t},\n\t): void {\n\t\tusage.cost.input = (usage.input / 1_000_000) * model.cost.input;\n\t\tusage.cost.output = (usage.output / 1_000_000) * model.cost.output;\n\t\tusage.cost.cacheRead = (usage.cacheRead / 1_000_000) * model.cost.cacheRead;\n\t\tusage.cost.cacheWrite = (usage.cacheWrite / 1_000_000) * model.cost.cacheWrite;\n\t\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n\t}\n\n\texport type BuiltInModels = Partial<Record<Provider.KnownProvider, Record<string, Info>>>;\n\n\texport function normalizeInput(input?: string[]): Array<\"text\" | \"image\"> {\n\t\tconst normalized = new Set<\"text\" | \"image\">();\n\t\tfor (const modality of input ?? [\"text\"]) {\n\t\t\tif (modality === \"text\" || modality === \"image\") {\n\t\t\t\tnormalized.add(modality);\n\t\t\t}\n\t\t}\n\t\tif (normalized.size === 0) normalized.add(\"text\");\n\t\treturn [...normalized];\n\t}\n\n\texport function toProviderInfo(\n\t\tproviderId: Provider.KnownProvider,\n\t\tprovider: ModelCatalog.ModelsDevProvider,\n\t): Provider.Info {\n\t\treturn {\n\t\t\tid: providerId,\n\t\t\tname: provider.name,\n\t\t\tenv: provider.env,\n\t\t\tkey: provider.key,\n\t\t\toptions: provider.headers,\n\t\t};\n\t}\n\n\tfunction toModelValue(\n\t\tproviderId: Provider.KnownProvider,\n\t\tprovider: ModelCatalog.ModelsDevProvider,\n\t\tmodel: ModelCatalog.ModelsDevModel,\n\t): Info {\n\t\treturn applyModification(providerId, provider, model);\n\t}\n\n\texport async function getBuiltInModels(): Promise<BuiltInModels> {\n\t\tconst catalog = await ModelCatalog.get();\n\t\treturn pipe(\n\t\t\tcatalog,\n\t\t\tpick(BUILTINS),\n\t\t\tmapValues((provider, providerId) =>\n\t\t\t\tmapValues(provider.models, (model) => toModelValue(providerId as Provider.KnownProvider, provider, model)),\n\t\t\t),\n\t\t) as BuiltInModels;\n\t}\n\n\texport const registry = lazy(async () => {\n\t\tconst registry: Map<Provider.KnownProvider, Map<string, Info>> = new Map();\n\t\tconst models = await getBuiltInModels();\n\t\tfor (const [provider, value] of Object.entries(models) as Array<[Provider.KnownProvider, Record<string, Info>]>) {\n\t\t\tconst providerModels = new Map<string, Info>();\n\t\t\tfor (const [id, model] of Object.entries(value)) {\n\t\t\t\tproviderModels.set(id, model);\n\t\t\t}\n\t\t\tregistry.set(provider, providerModels);\n\t\t}\n\t\treturn registry;\n\t});\n\n\texport async function getModel<TProvider extends Provider.KnownProvider, TModel extends Info[\"id\"]>(\n\t\tprovider: TProvider,\n\t\tmodel: TModel,\n\t\toverrides?: Partial<Info>,\n\t) {\n\t\tconst data = await registry();\n\t\tconst providerModels = data.get(provider);\n\t\tconst result = providerModels?.get(model);\n\t\tif (result && overrides) {\n\t\t\treturn { ...result, ...overrides };\n\t\t}\n\t\treturn result;\n\t}\n\n\texport async function getProviders(): Promise<Provider.KnownProvider[]> {\n\t\tconst data = await registry();\n\t\treturn Array.from(data.keys());\n\t}\n\n\texport async function getModels<TProvider extends Provider.KnownProvider>(provider: TProvider): Promise<Info[]> {\n\t\tconst data = await registry();\n\t\tconst models = data.get(provider);\n\t\treturn models ? Array.from(models.values()) : [];\n\t}\n\n\tfunction isGpt5OrLater(modelID: string): boolean {\n\t\tconst match = /^gpt-(\\d+)/.exec(modelID);\n\t\tif (!match) {\n\t\t\treturn false;\n\t\t}\n\t\treturn Number(match[1]) >= 5;\n\t}\n\n\t/**\n\t * Check if a model supports xhigh thinking level.\n\t * Currently only certain OpenAI Codex models support this.\n\t */\n\texport function supportsXhigh(model: Info): boolean {\n\t\treturn isGpt5OrLater(model.id);\n\t}\n\n\t/**\n\t * Check if two models are equal by comparing both their id and provider id.\n\t * Returns false if either model is null or undefined.\n\t */\n\texport function modelsAreEqual(a: Info | null | undefined, b: Info | null | undefined): boolean {\n\t\tif (!a || !b) return false;\n\t\treturn a.id === b.id && a.provider.id === b.provider.id;\n\t}\n}\n","import { NamedError } from \"@codeworksh/utils\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport type { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport type { AssistantMessageEventStream } from \"../utils/eventstream\";\n\nexport namespace Stream {\n\texport const ProtocolProviderNotFoundError = NamedError.create(\n\t\t\"ProtocolProviderNotFoundError\",\n\t\tType.Object({\n\t\t\tprotocol: Model.KnownProtocolSchema,\n\t\t}),\n\t);\n\texport type ProtocolProviderNotFoundError = InstanceType<typeof ProtocolProviderNotFoundError>;\n\n\texport const ProtocolMismatchError = NamedError.create(\n\t\t\"ProtocolMismatchError\",\n\t\tType.Object({\n\t\t\tactual: Model.KnownProtocolSchema,\n\t\t\texpected: Model.KnownProtocolSchema,\n\t\t}),\n\t);\n\texport type ProtocolMismatchError = InstanceType<typeof ProtocolMismatchError>;\n\n\texport const ThinkingLevelEnum = {\n\t\toff: \"off\",\n\t\tminimal: \"minimal\",\n\t\tlow: \"low\",\n\t\tmedium: \"medium\",\n\t\thigh: \"high\",\n\t\txhigh: \"xhigh\",\n\t} as const;\n\texport const ThinkingLevelSchema = Type.Union([\n\t\tType.Literal(ThinkingLevelEnum.off),\n\t\tType.Literal(ThinkingLevelEnum.minimal),\n\t\tType.Literal(ThinkingLevelEnum.low),\n\t\tType.Literal(ThinkingLevelEnum.medium),\n\t\tType.Literal(ThinkingLevelEnum.high),\n\t\tType.Literal(ThinkingLevelEnum.xhigh),\n\t]);\n\texport type ThinkingLevel = Static<typeof ThinkingLevelSchema>;\n\n\texport const ThinkingBudgetsSchema = Type.Object({\n\t\toff: Type.Optional(Type.Number()),\n\t\tminimal: Type.Optional(Type.Number()),\n\t\tlow: Type.Optional(Type.Number()),\n\t\tmedium: Type.Optional(Type.Number()),\n\t\thigh: Type.Optional(Type.Number()),\n\t});\n\texport type ThinkingBudgets = Static<typeof ThinkingBudgetsSchema>;\n\n\texport const CacheRetentionSchema = Type.Union([Type.Literal(\"none\"), Type.Literal(\"short\"), Type.Literal(\"long\")]);\n\texport type CacheRetention = Static<typeof CacheRetentionSchema>;\n\n\texport const TransportSchema = Type.Union([Type.Literal(\"sse\"), Type.Literal(\"websocket\"), Type.Literal(\"auto\")]);\n\texport type Transport = Static<typeof TransportSchema>;\n\n\texport const OptionsSchema = Type.Object({\n\t\ttemperature: Type.Optional(Type.Number()),\n\t\tmaxTokens: Type.Optional(Type.Number()),\n\t\tsignal: Type.Optional(Type.Unsafe<AbortSignal>()),\n\t\tapiKey: Type.Optional(Type.String()),\n\t\ttransport: Type.Optional(TransportSchema),\n\t\tcacheRetention: Type.Optional(CacheRetentionSchema),\n\t\tsessionId: Type.Optional(Type.String()),\n\t\tonPayload: Type.Optional(Type.Unsafe<(payload: unknown, model: Model.TModel<Model.KnownProtocol>) => unknown>()),\n\t\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\t\tmaxRetryDelayMs: Type.Optional(Type.Number()),\n\t\tmetadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\t});\n\texport type Options = Static<typeof OptionsSchema>;\n\texport type ProviderOptions = Options & Record<string, unknown>;\n\n\texport const SimpleOptionsSchema = Type.Composite([\n\t\tOptionsSchema,\n\t\tType.Object({\n\t\t\treasoning: Type.Optional(ThinkingLevelSchema),\n\t\t\tthinkingBudgets: Type.Optional(ThinkingBudgetsSchema),\n\t\t}),\n\t]);\n\texport type SimpleOptions = Static<typeof SimpleOptionsSchema>;\n\n\t// Contract:\n\t// - Must return an AssistantMessageEventStream.\n\t// - Once invoked, request/model/runtime failures should be encoded in the\n\t// returned stream, not thrown.\n\t// - Error termination must produce an AssistantMessage with stopReason\n\t// \"error\" or \"aborted\" and errorMessage, emitted via the stream protocol.\n\texport type StreamFunction<\n\t\tTProtocol extends Model.KnownProtocol = Model.KnownProtocol,\n\t\tTOptions extends Options = Options,\n\t> = (model: Model.TModel<TProtocol>, context: Message.Context, options?: TOptions) => AssistantMessageEventStream;\n\n\texport function buildBaseOptions(model: Model.Info, options?: SimpleOptions, apiKey?: string): Options {\n\t\treturn {\n\t\t\ttemperature: options?.temperature,\n\t\t\tmaxTokens: options?.maxTokens || Math.min(model.maxTokens, 32000),\n\t\t\tsignal: options?.signal,\n\t\t\tapiKey: apiKey || options?.apiKey,\n\t\t\ttransport: options?.transport,\n\t\t\tcacheRetention: options?.cacheRetention,\n\t\t\tsessionId: options?.sessionId,\n\t\t\theaders: options?.headers,\n\t\t\tonPayload: options?.onPayload,\n\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\tmetadata: options?.metadata,\n\t\t};\n\t}\n\n\texport function clampReasoning(effort: ThinkingLevel | undefined): Exclude<ThinkingLevel, \"xhigh\"> | undefined {\n\t\treturn effort === ThinkingLevelEnum.xhigh ? ThinkingLevelEnum.high : effort;\n\t}\n\n\texport function adjustMaxTokensForThinking(\n\t\tbaseMaxTokens: number,\n\t\tmodelMaxTokens: number,\n\t\treasoningLevel: ThinkingLevel,\n\t\tcustomBudgets?: ThinkingBudgets,\n\t): { maxTokens: number; thinkingBudget: number } {\n\t\tconst defaultBudgets: ThinkingBudgets = {\n\t\t\tminimal: 1024,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 16384,\n\t\t};\n\t\tconst budgets = { ...defaultBudgets, ...customBudgets };\n\t\tconst minOutputTokens = 1024;\n\t\tconst level = clampReasoning(reasoningLevel)!;\n\t\tlet thinkingBudget = budgets[level]!;\n\t\tconst maxTokens = Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);\n\n\t\tif (maxTokens <= thinkingBudget) {\n\t\t\tthinkingBudget = Math.max(0, maxTokens - minOutputTokens);\n\t\t}\n\n\t\treturn { maxTokens, thinkingBudget };\n\t}\n\n\texport type ProtocolStreamFunction = (\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: Options,\n\t) => AssistantMessageEventStream;\n\n\texport type ProtocolStreamSimpleFunction = (\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: SimpleOptions,\n\t) => AssistantMessageEventStream;\n\n\texport interface ProtocolProvider<\n\t\tTProtocol extends Model.KnownProtocol = Model.KnownProtocol,\n\t\tTOptions extends Options = Options,\n\t> {\n\t\tprotocol: TProtocol;\n\t\tstream: StreamFunction<TProtocol, TOptions>;\n\t\tstreamSimple: StreamFunction<TProtocol, SimpleOptions>;\n\t}\n\n\ttype RegisteredProtocolProvider = {\n\t\tprovider: ProtocolProvider<Model.KnownProtocol, Options>;\n\t\tsourceId?: string;\n\t};\n\n\tconst protocolProviderRegistry = new Map<Model.KnownProtocol, RegisteredProtocolProvider>();\n\n\tfunction wrapStream<TProtocol extends Model.KnownProtocol, TOptions extends Options>(\n\t\tprotocol: TProtocol,\n\t\tstream: StreamFunction<TProtocol, TOptions>,\n\t): ProtocolStreamFunction {\n\t\treturn (model, context, options) => {\n\t\t\tif (model.protocol !== protocol) {\n\t\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\t\tactual: model.protocol,\n\t\t\t\t\texpected: protocol,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn stream(model as Model.TModel<TProtocol>, context, options as TOptions);\n\t\t};\n\t}\n\n\tfunction wrapStreamSimple<TProtocol extends Model.KnownProtocol>(\n\t\tprotocol: TProtocol,\n\t\tstreamSimple: StreamFunction<TProtocol, SimpleOptions>,\n\t): ProtocolStreamSimpleFunction {\n\t\treturn (model, context, options) => {\n\t\t\tif (model.protocol !== protocol) {\n\t\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\t\tactual: model.protocol,\n\t\t\t\t\texpected: protocol,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn streamSimple(model as Model.TModel<TProtocol>, context, options);\n\t\t};\n\t}\n\n\texport function registerProtocolProvider<TProtocol extends Model.KnownProtocol, TOptions extends Options>(\n\t\tprovider: ProtocolProvider<TProtocol, TOptions>,\n\t\tsourceId?: string,\n\t): void {\n\t\tprotocolProviderRegistry.set(provider.protocol, {\n\t\t\tprovider: {\n\t\t\t\tprotocol: provider.protocol,\n\t\t\t\tstream: wrapStream(provider.protocol, provider.stream),\n\t\t\t\tstreamSimple: wrapStreamSimple(provider.protocol, provider.streamSimple),\n\t\t\t},\n\t\t\tsourceId,\n\t\t});\n\t}\n\n\texport function getProtocolProvider(\n\t\tprotocol: Model.KnownProtocol,\n\t): ProtocolProvider<Model.KnownProtocol, Options> | undefined {\n\t\treturn protocolProviderRegistry.get(protocol)?.provider;\n\t}\n\n\texport function resolveProtocolProvider(model: Model.Info): ProtocolProvider<Model.KnownProtocol, Options> {\n\t\tconst provider = getProtocolProvider(model.protocol);\n\t\tif (!provider) {\n\t\t\tthrow new ProtocolProviderNotFoundError({\n\t\t\t\tprotocol: model.protocol,\n\t\t\t});\n\t\t}\n\t\treturn provider;\n\t}\n\n\texport function stream(model: Model.Info, context: Message.Context, options?: Options): AssistantMessageEventStream {\n\t\tconst provider = resolveProtocolProvider(model);\n\t\treturn provider.stream(model, context, options);\n\t}\n\n\texport async function complete(\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: Options,\n\t): Promise<Message.AssistantMessage> {\n\t\tconst s = stream(model, context, options);\n\t\treturn s.result();\n\t}\n\n\texport function streamSimple(\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: SimpleOptions,\n\t): AssistantMessageEventStream {\n\t\tconst provider = resolveProtocolProvider(model);\n\t\treturn provider.streamSimple(model, context, options);\n\t}\n\n\texport async function completeSimple(\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: SimpleOptions,\n\t): Promise<Message.AssistantMessage> {\n\t\tconst s = streamSimple(model, context, options);\n\t\treturn s.result();\n\t}\n\n\texport function getApiProviders(): ProtocolProvider<Model.KnownProtocol, Options>[] {\n\t\treturn Array.from(protocolProviderRegistry.values(), (entry) => entry.provider);\n\t}\n\n\texport function unregisterProtocolProviders(sourceId: string): void {\n\t\tfor (const [api, entry] of protocolProviderRegistry.entries()) {\n\t\t\tif (entry.sourceId === sourceId) {\n\t\t\t\tprotocolProviderRegistry.delete(api);\n\t\t\t}\n\t\t}\n\t}\n\n\texport function clearProtocolProviders(): void {\n\t\tprotocolProviderRegistry.clear();\n\t}\n}\n","/**\n * @description Defines the Generic event stream class for async iteration.\n */\n\nimport type { Event } from \"../event/event\";\nimport type { Message } from \"../message/message\";\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\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\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","/**\n * @description Validation powered by ajv, TypeBox natively doesn't provide data validation.\n */\n\nimport type { Static, TSchema } from \"@sinclair/typebox\";\nimport Ajv from \"ajv\";\nimport addFormats from \"ajv-formats\";\n\nimport type { Agent } from \"../agent/agent\";\nimport type { Message } from \"../message/message\";\n\n// Create singleton AJV instance with formats\nconst ajv = new Ajv({\n\tallErrors: true,\n\tstrict: false,\n\tcoerceTypes: true,\n});\naddFormats(ajv);\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 validate = ajv.compile(schema);\n\tconst input = structuredClone(value);\n\n\tif (validate(input)) {\n\t\treturn input as Static<T>;\n\t}\n\n\tconst errors =\n\t\tvalidate.errors\n\t\t\t?.map((err) => {\n\t\t\t\tconst path = err.instancePath ? err.instancePath.substring(1) : err.params?.missingProperty || \"root\";\n\t\t\t\treturn ` - ${path}: ${err.message}`;\n\t\t\t})\n\t\t\t.join(\"\\n\") || \"Unknown Validation Error\";\n\n\tthrow new Error(\n\t\t[`Validation Failed For ${label}`, `${errors}\\n`, \"Received Value:\", `${JSON.stringify(value, null, 2)}\\n`].join(\n\t\t\t\"\\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: Agent.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: Agent.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","import { NamedError } from \"@codeworksh/utils\";\nimport { type TSchema, Type } from \"@sinclair/typebox\";\nimport type { Event } from \"../event/event\";\nimport type { Message } from \"../message/message\";\nimport type { Model } from \"../model/model\";\nimport type { Provider } from \"../provider/provider\";\nimport { Stream } from \"../provider/stream\";\nimport { EventStream } from \"../utils/eventstream\";\nimport { validateToolArguments } from \"../utils/validation\";\nimport type { Agent } from \"./agent\";\n\nexport namespace Loop {\n\t/** Stream function used by the core agent loop\n\t *\n\t * Contract:\n\t * - Must not throw or return a rejected promise for request/model/runtime (LLM) failures.\n\t * - Must return an AssistantMessageEventStream see: packages/aikit/src/utils/eventstream.ts\n\t * - Failures must be encoded in the returned stream via protocol events and a\n\t * final Message.AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n\t */\n\texport type StreamFn = (\n\t\t...args: Parameters<typeof Stream.streamSimple>\n\t) => ReturnType<typeof Stream.streamSimple> | Promise<ReturnType<typeof Stream.streamSimple>>;\n\n\t/**\n\t * Configuration for how tool calls from a single assistant message are executed.\n\t *\n\t * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n\t * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n\t * Final tool results are still emitted in assistant source order.\n\t */\n\texport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n\t/** Context passed to `beforeToolExecution`. */\n\texport interface BeforeToolExecutionContext {\n\t\t/** The current context at the time the tool call is prepared */\n\t\tcontext: Agent.AgentContext;\n\t\t/** The assistant message that requested the tool call. */\n\t\tassistantMessage: Message.AssistantMessage;\n\t\t/** The validated in-flight tool call with validated arguments */\n\t\ttoolCall: Agent.ToolCallInFlight;\n\t}\n\n\t/** Context passed to `afterToolExecution`. */\n\texport interface AfterToolExecutionContext {\n\t\t/** Current agent context at the time the tool call is finalized. */\n\t\tcontext: Agent.AgentContext;\n\t\t/** The assistant message that requested the tool call. */\n\t\tassistantMessage: Message.AssistantMessage;\n\t\t/** The validated in-flight tool call with validated arguments */\n\t\ttoolCall: Agent.ToolCallInFlight;\n\t\t/** The executed tool result before any `afterToolExecution` overrides are applied. */\n\t\tresult: Agent.ToolTerminalResult<unknown>;\n\t}\n\n\t/**\n\t * Result returned from `beforeToolExecution`.\n\t *\n\t * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n\t * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n\t */\n\texport interface BeforeToolCallResult {\n\t\tblock?: boolean;\n\t\treason?: string;\n\t\tdetails?: unknown;\n\t}\n\n\t/** Configuration for the agent loop. */\n\texport interface Config extends Stream.SimpleOptions {\n\t\tmodel: Model.Info;\n\t\tconvertToLlm: (messages: Message.Message[]) => Message.Message[] | Promise<Message.Message[]>;\n\t\t/**\n\t\t * Optional transform applied to the context before `convertToLlm`.\n\t\t *\n\t\t * Use this for operations that work at the AgentMessage level:\n\t\t * - Context window management (pruning old messages)\n\t\t * - Injecting context from external sources\n\t\t *\n\t\t * @example\n\t\t * ```typescript\n\t\t * transformContext: async (messages) => {\n\t\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t\t * return pruneOldMessages(messages);\n\t\t * }\n\t\t * return messages;\n\t\t * }\n\t\t * ```\n\t\t */\n\t\ttransformContext?: (messages: Message.Message[], signal?: AbortSignal) => Promise<Message.Message[]>;\n\t\t/**\n\t\t * Resolves an API key dynamically for each LLM call.\n\t\t *\n\t\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t\t * during long-running tool execution phases.\n\t\t */\n\t\tgetApiKey?: (provider: Provider.Info) => Promise<string | undefined> | string | undefined;\n\t\t/**\n\t\t * Returns steering messages to inject into the conversation mid-run.\n\t\t *\n\t\t * Called after each tool execution to check for user interruptions.\n\t\t * If messages are returned, remaining tool calls are skipped and\n\t\t * these messages are added to the context before the next LLM call.\n\t\t *\n\t\t * Use this for \"steering\" the agent while it's working.\n\t\t */\n\t\tgetSteeringMessages?: () => Promise<Message.UserMessage[]>;\n\t\t/**\n\t\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t\t *\n\t\t * Called when the agent has no more tool calls and no steering messages.\n\t\t * If messages are returned, they're added to the context and the agent\n\t\t * continues with another turn.\n\t\t *\n\t\t * Use this for follow-up messages that should wait until the agent finishes.\n\t\t */\n\t\tgetFollowUpMessages?: () => Promise<Message.UserMessage[]>;\n\n\t\t/**\n\t\t * Tool execution mode.\n\t\t * - \"sequential\": execute tool calls one by one\n\t\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently\n\t\t *\n\t\t * Default: \"parallel\"\n\t\t */\n\t\ttoolExecution?: ToolExecutionMode;\n\n\t\t/**\n\t\t * Called before a tool is executed, after arguments have been validated.\n\t\t *\n\t\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t\t */\n\t\tbeforeToolExecution?: (\n\t\t\tcontext: BeforeToolExecutionContext,\n\t\t\tsignal?: AbortSignal,\n\t\t) => Promise<BeforeToolCallResult | undefined>;\n\n\t\t/**\n\t\t * Called after a tool finishes executing, before final tool events are emitted.\n\t\t *\n\t\t * Any omitted fields keep their original values. No deep merge is performed.\n\t\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t\t */\n\t\tafterToolExecution?: (\n\t\t\tcontext: AfterToolExecutionContext,\n\t\t\tsignal?: AbortSignal,\n\t\t) => Promise<Agent.ToolTerminalResult<unknown> | undefined>;\n\t}\n\n\tfunction createAgentStream(): EventStream<Event.AgentEvent, Message.Message[]> {\n\t\treturn new EventStream<Event.AgentEvent, Message.Message[]>(\n\t\t\t(event: Event.AgentEvent) => event.type === \"agent.end\",\n\t\t\t(event: Event.AgentEvent) => (event.type === \"agent.end\" ? event.messages : []),\n\t\t);\n\t}\n\n\ttype AgentEventSink = (event: Event.AgentEvent) => Promise<void> | void;\n\n\ttype AssistantPart = Message.AssistantMessage[\"parts\"][number];\n\n\ttype ToolCallPart = Message.ToolCallPendingPart & { partIndex: number }; // runtime toolcall pending part\n\n\ttype RuntimeAgentTool = {\n\t\tname: string;\n\t\tparameters: TSchema;\n\t\texecute: (\n\t\t\tcallID: string,\n\t\t\tparams: unknown,\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?: Agent.ToolUpdateCallback<unknown>,\n\t\t) => Promise<Agent.ToolTerminalResult<unknown>>;\n\t};\n\n\ttype ToolCallPrepared =\n\t\t| {\n\t\t\t\terror: {\n\t\t\t\t\tkind: \"error\" | \"blocked\";\n\t\t\t\t\tmessage: string;\n\t\t\t\t\tdetails?: unknown;\n\t\t\t\t};\n\t\t\t\trunnable: Agent.ToolCallInFlight;\n\t\t }\n\t\t| {\n\t\t\t\terror?: never;\n\t\t\t\trunnable: Agent.ToolCallInFlight;\n\t\t\t\ttool: RuntimeAgentTool;\n\t\t };\n\n\ttype ToolCallRunnable = {\n\t\ttoolCall: ToolCallPart;\n\t\trunnable: Agent.ToolCallInFlight;\n\t\ttool: RuntimeAgentTool;\n\t};\n\n\ttype ToolCallExecutionResult =\n\t\t| { result: Agent.ToolTerminalResult<unknown>; error?: never }\n\t\t| { result?: never; error: { message: string; details?: unknown } };\n\n\texport const AgentContextError = NamedError.create(\n\t\t\"AgentContextError\",\n\t\tType.Object({\n\t\t\tmessage: Type.String(),\n\t\t}),\n\t);\n\texport type AgentContextError = InstanceType<typeof AgentContextError>;\n\n\tfunction snapshotAssistantMessage(message: Message.AssistantMessage): Message.AssistantMessage {\n\t\treturn structuredClone(message);\n\t}\n\n\tfunction snapshotAssistantPartEvent(\n\t\tmessage: Message.AssistantMessage,\n\t\tpartIndex: number,\n\t): { message: Message.AssistantMessage; part: AssistantPart } {\n\t\tconst snapshot = snapshotAssistantMessage(message);\n\t\tconst part = snapshot.parts[partIndex];\n\t\tif (!part) {\n\t\t\tthrow new Error(`Assistant message part at index ${partIndex} was not found`);\n\t\t}\n\t\treturn { message: snapshot, part };\n\t}\n\n\tasync function emitEvent(emit: AgentEventSink, event: Event.AgentEvent): Promise<void> {\n\t\tawait emit(event);\n\t}\n\n\tasync function streamAssistantResponse(\n\t\tconfig: Config,\n\t\tcontext: Agent.AgentContext,\n\t\temit: AgentEventSink,\n\t\tstreamFn?: StreamFn,\n\t\tsignal?: AbortSignal,\n\t): Promise<Message.AssistantMessage> {\n\t\t// FIXME @sanchitrk:\n\t\t// Have something like a pipeline with Message.Message[] transformation\n\t\t// caller will inject transfomers[](async functions) that is then invoked in order\n\n\t\t// Apply context transform if configured (Message.Message[] → Message.Message[])\n\t\tlet messages = context.messages;\n\t\tif (config.transformContext) {\n\t\t\tmessages = await config.transformContext(messages, signal);\n\t\t}\n\n\t\t// Convert to LLM-compatible messages (Message.Message[] → Message.Message[])\n\t\tconst llmMessages = await config.convertToLlm(messages);\n\n\t\t// Build LLM context, subset of Agent.AgentContext\n\t\tconst llmContext: Agent.AgentContext = {\n\t\t\tsystemPrompt: context.systemPrompt,\n\t\t\tmessages: llmMessages,\n\t\t\ttools: context.tools,\n\t\t};\n\t\tconst streamFunction = streamFn || Stream.streamSimple;\n\t\t// Resolve API key (important for expiring tokens)\n\t\t// TODO @sanchitrk:\n\t\t// improve passing of credentials (key/oauth), provider also has resolve api key,\n\t\t// for now its dummy implementation.\n\t\tconst resolvedApiKey =\n\t\t\t(config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;\n\n\t\tconst events = await streamFunction(config.model, llmContext, {\n\t\t\t...config,\n\t\t\tapiKey: resolvedApiKey,\n\t\t\tsignal,\n\t\t});\n\n\t\tlet partialMessage: Message.AssistantMessage | null = null;\n\t\tlet started = false;\n\n\t\tconst ensureMessageStarted = async (message: Message.AssistantMessage): Promise<void> => {\n\t\t\tif (started) return;\n\t\t\tstarted = true;\n\t\t\tawait emitEvent(emit, { type: \"message.start\", message: snapshotAssistantMessage(message) });\n\t\t};\n\n\t\tconst emitMessageUpdate = async (message: Message.AssistantMessage): Promise<void> => {\n\t\t\tawait emitEvent(emit, { type: \"message.update\", message: snapshotAssistantMessage(message) });\n\t\t};\n\n\t\tconst emitPartStart = async (message: Message.AssistantMessage, partIndex: number): Promise<void> => {\n\t\t\tconst snapshot = snapshotAssistantPartEvent(message, partIndex);\n\t\t\tawait emitEvent(emit, { type: \"message.part.start\", partIndex, ...snapshot });\n\t\t};\n\n\t\tconst emitPartUpdate = async (message: Message.AssistantMessage, partIndex: number): Promise<void> => {\n\t\t\tconst snapshot = snapshotAssistantPartEvent(message, partIndex);\n\t\t\tawait emitEvent(emit, { type: \"message.part.update\", partIndex, ...snapshot, source: \"llm\" });\n\t\t};\n\n\t\tconst emitPartEnd = async (message: Message.AssistantMessage, partIndex: number): Promise<void> => {\n\t\t\tconst snapshot = snapshotAssistantPartEvent(message, partIndex);\n\t\t\tawait emitEvent(emit, { type: \"message.part.end\", partIndex, ...snapshot });\n\t\t};\n\n\t\t// NOTE: Do not mutate context directly\n\t\t// once all the events are done return message\n\t\t// mutate partialMessage and corresponding parts as required\n\t\t// return the final built message from llm events\n\t\tfor await (const event of events) {\n\t\t\tswitch (event.type) {\n\t\t\t\tcase \"start\": {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tawait ensureMessageStarted(partialMessage);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text.start\":\n\t\t\t\tcase \"thinking.start\":\n\t\t\t\tcase \"toolcall.start\": {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tawait ensureMessageStarted(partialMessage);\n\t\t\t\t\tawait emitPartStart(partialMessage, event.partIndex);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text.delta\":\n\t\t\t\tcase \"thinking.delta\":\n\t\t\t\tcase \"toolcall.delta\": {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tawait ensureMessageStarted(partialMessage);\n\t\t\t\t\tawait emitPartUpdate(partialMessage, event.partIndex);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text.end\":\n\t\t\t\tcase \"thinking.end\":\n\t\t\t\tcase \"toolcall.end\": {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tawait ensureMessageStarted(partialMessage);\n\t\t\t\t\tawait emitPartEnd(partialMessage, event.partIndex);\n\t\t\t\t\tawait emitMessageUpdate(partialMessage);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"done\": {\n\t\t\t\t\tawait ensureMessageStarted(event.message);\n\t\t\t\t\tawait emitEvent(emit, { type: \"message.end\", message: snapshotAssistantMessage(event.message) });\n\t\t\t\t\treturn event.message;\n\t\t\t\t}\n\t\t\t\tcase \"error\": {\n\t\t\t\t\tawait ensureMessageStarted(event.error);\n\t\t\t\t\tawait emitEvent(emit, { type: \"message.end\", message: snapshotAssistantMessage(event.error) });\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst finalMessage = await events.result();\n\t\tawait ensureMessageStarted(finalMessage);\n\t\tawait emitEvent(emit, { type: \"message.end\", message: snapshotAssistantMessage(finalMessage) });\n\t\treturn finalMessage;\n\t}\n\n\tasync function executeToolCalls(\n\t\tconfig: Config,\n\t\tcurrentContext: Agent.AgentContext,\n\t\tmessage: Message.AssistantMessage,\n\t\ttoolCalls: ToolCallPart[],\n\t\temit: AgentEventSink,\n\t\tsignal?: AbortSignal,\n\t): Promise<void> {\n\t\tif (config.toolExecution === \"sequential\")\n\t\t\treturn executeToolCallsSequential(config, currentContext, message, toolCalls, emit, signal);\n\t\treturn executeToolCallsParallel(config, currentContext, message, toolCalls, emit, signal);\n\t}\n\n\tasync function executeToolCallsSequential(\n\t\tconfig: Config,\n\t\tcurrentContext: Agent.AgentContext,\n\t\tmessage: Message.AssistantMessage,\n\t\ttoolCalls: ToolCallPart[],\n\t\temit: AgentEventSink,\n\t\tsignal?: AbortSignal,\n\t): Promise<void> {\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tconst toolCallInFlight: Agent.ToolCallInFlight = {\n\t\t\t\tcallID: toolCall.callID,\n\t\t\t\tname: toolCall.name,\n\t\t\t\trawArgs: toolCall.arguments,\n\t\t\t};\n\t\t\tawait emitEvent(emit, {\n\t\t\t\ttype: \"tool.execution.start\",\n\t\t\t\t...toolCallInFlight,\n\t\t\t});\n\t\t\t//\n\t\t\t// Prepares the tool call for execution.\n\t\t\t// Invokes a pre-execution callback with the current context, allowing\n\t\t\t// the callback to either continue or block (short-circuiting the execution).\n\t\t\t// Mutates `message.parts` in-place to update the pending tool call with its result.\n\t\t\tconst prepared = await prepareToolCall(config, currentContext, message, toolCallInFlight, signal);\n\t\t\tif (prepared.error) {\n\t\t\t\tconst error: Agent.ToolErrorResult<unknown> = {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\tresult: {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: prepared.error.message }],\n\t\t\t\t\t\tdetails: prepared.error.details,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tawait emitToolCallTerminalResult(toolCall, prepared.runnable, message, emit, error);\n\t\t\t} else {\n\t\t\t\tconst runnable: ToolCallRunnable = {\n\t\t\t\t\ttoolCall,\n\t\t\t\t\trunnable: prepared.runnable,\n\t\t\t\t\ttool: prepared.tool,\n\t\t\t\t};\n\t\t\t\tconst executed = await executeRunnableToolCall(runnable, message, emit, signal);\n\t\t\t\tif (executed.error) {\n\t\t\t\t\t// tool call invocation failed with error\n\t\t\t\t\t// create tool error result\n\t\t\t\t\tconst error: Agent.ToolErrorResult<unknown> = {\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: executed.error.message }],\n\t\t\t\t\t\t\tdetails: executed.error.details,\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t\tawait emitToolCallTerminalResult(runnable.toolCall, runnable.runnable, message, emit, error);\n\t\t\t\t} else {\n\t\t\t\t\t// finalize results from tool invocation\n\t\t\t\t\t// invokes after tool exection callback\n\t\t\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tcurrentContext,\n\t\t\t\t\t\trunnable.toolCall,\n\t\t\t\t\t\trunnable.runnable,\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\temit,\n\t\t\t\t\t\texecuted.result,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tasync function executeToolCallsParallel(\n\t\tconfig: Config,\n\t\tcurrentContext: Agent.AgentContext,\n\t\tmessage: Message.AssistantMessage,\n\t\ttoolCalls: ToolCallPart[],\n\t\temit: AgentEventSink,\n\t\tsignal?: AbortSignal,\n\t): Promise<void> {\n\t\tconst runnables: ToolCallRunnable[] = [];\n\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tconst toolCallInFlight: Agent.ToolCallInFlight = {\n\t\t\t\tcallID: toolCall.callID,\n\t\t\t\tname: toolCall.name,\n\t\t\t\trawArgs: toolCall.arguments,\n\t\t\t};\n\t\t\tawait emitEvent(emit, {\n\t\t\t\ttype: \"tool.execution.start\",\n\t\t\t\t...toolCallInFlight,\n\t\t\t});\n\t\t\t//\n\t\t\t// Prepares the tool call for execution.\n\t\t\t// Invokes a pre-execution callback with the current context, allowing\n\t\t\t// the callback to either continue or block (short-circuiting the execution).\n\t\t\t// Mutates `message.parts` in-place to update the pending tool call with its result.\n\t\t\tconst prepared = await prepareToolCall(config, currentContext, message, toolCallInFlight, signal);\n\t\t\tif (prepared.error) {\n\t\t\t\tconst error: Agent.ToolErrorResult<unknown> = {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\tresult: {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: prepared.error.message }],\n\t\t\t\t\t\tdetails: prepared.error.details,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tawait emitToolCallTerminalResult(toolCall, prepared.runnable, message, emit, error);\n\t\t\t} else {\n\t\t\t\trunnables.push({\n\t\t\t\t\ttoolCall,\n\t\t\t\t\trunnable: prepared.runnable,\n\t\t\t\t\ttool: prepared.tool,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst runningExecutions = runnables.map((runnable) => ({\n\t\t\trunnable,\n\t\t\texecution: executeRunnableToolCall(runnable, message, emit, signal),\n\t\t}));\n\n\t\tfor (const running of runningExecutions) {\n\t\t\tconst executed = await running.execution;\n\t\t\tconst { runnable } = running;\n\t\t\tif (executed.error) {\n\t\t\t\t// tool call invocation failed with error\n\t\t\t\t// create tool error result\n\t\t\t\tconst error: Agent.ToolErrorResult<unknown> = {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\tresult: {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: executed.error.message }],\n\t\t\t\t\t\tdetails: executed.error.details,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tawait emitToolCallTerminalResult(runnable.toolCall, runnable.runnable, message, emit, error);\n\t\t\t} else {\n\t\t\t\t// finalize results from tool invocation\n\t\t\t\t// invokes after tool exection callback\n\t\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\t\tconfig,\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\trunnable.toolCall,\n\t\t\t\t\trunnable.runnable,\n\t\t\t\t\tmessage,\n\t\t\t\t\temit,\n\t\t\t\t\texecuted.result,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync function prepareToolCall(\n\t\tconfig: Config,\n\t\tcurrentContext: Agent.AgentContext,\n\t\tassistantMessage: Message.AssistantMessage,\n\t\ttoolCallInFlight: Agent.ToolCallInFlight,\n\t\tsignal?: AbortSignal,\n\t): Promise<ToolCallPrepared> {\n\t\tconst tool = currentContext.tools?.find((t) => t.name === toolCallInFlight.name);\n\t\tif (!tool) {\n\t\t\treturn {\n\t\t\t\terror: {\n\t\t\t\t\tkind: \"error\",\n\t\t\t\t\tmessage: `Tool ${toolCallInFlight.name} Not Found`,\n\t\t\t\t},\n\t\t\t\trunnable: toolCallInFlight,\n\t\t\t};\n\t\t}\n\n\t\ttry {\n\t\t\t//\n\t\t\t// first validate toolcall args, before invoking callback\n\t\t\t// appends validated args\n\t\t\ttoolCallInFlight.args = validateToolArguments(tool, toolCallInFlight);\n\t\t\tif (config.beforeToolExecution) {\n\t\t\t\tconst beforeResult = await config.beforeToolExecution(\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall: toolCallInFlight,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t\tif (beforeResult?.block) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tkind: \"blocked\",\n\t\t\t\t\t\t\tmessage: beforeResult?.reason || \"Tool Execution was Blocked\",\n\t\t\t\t\t\t\tdetails: beforeResult?.details,\n\t\t\t\t\t\t},\n\t\t\t\t\t\trunnable: toolCallInFlight,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trunnable: toolCallInFlight,\n\t\t\t\ttool: tool as RuntimeAgentTool,\n\t\t\t};\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\terror: {\n\t\t\t\t\tkind: \"error\",\n\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t},\n\t\t\t\trunnable: toolCallInFlight,\n\t\t\t};\n\t\t}\n\t}\n\n\tasync function executeRunnableToolCall(\n\t\ttoolCallRunnable: ToolCallRunnable,\n\t\tmessage: Message.AssistantMessage,\n\t\temit: AgentEventSink,\n\t\tsignal?: AbortSignal,\n\t): Promise<ToolCallExecutionResult> {\n\t\tconst { toolCall, runnable, tool } = toolCallRunnable;\n\t\tconst { partIndex, ...pendingPart } = toolCall;\n\t\ttry {\n\t\t\tconst result = await tool.execute(runnable.callID, runnable.args, signal, async (result) => {\n\t\t\t\tconst runningResult: Agent.ToolRunningResult<unknown> = {\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\tpartial: result.partial,\n\t\t\t\t};\n\t\t\t\tconst toolExecutionUpdate: Event.ToolExecutionUpdate = {\n\t\t\t\t\ttype: \"tool.execution.update\",\n\t\t\t\t\t...runnable,\n\t\t\t\t\t...runningResult,\n\t\t\t\t};\n\t\t\t\tawait emitEvent(emit, { ...toolExecutionUpdate });\n\n\t\t\t\tconst runningPart: Message.ToolCallRunningPart = {\n\t\t\t\t\t...pendingPart,\n\t\t\t\t\t...runningResult,\n\t\t\t\t};\n\n\t\t\t\tmessage.parts[partIndex] = runningPart; // in-place mutate; add error part\n\n\t\t\t\tawait emitEvent(emit, {\n\t\t\t\t\ttype: \"message.part.update\",\n\t\t\t\t\tmessage,\n\t\t\t\t\tpartIndex,\n\t\t\t\t\tpart: runningPart,\n\t\t\t\t\tsource: \"tool\",\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tresult,\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\treturn {\n\t\t\t\terror: {\n\t\t\t\t\tmessage,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\tasync function emitToolCallTerminalResult(\n\t\ttoolCall: ToolCallPart,\n\t\trunnable: Agent.ToolCallInFlight,\n\t\tmessage: Message.AssistantMessage,\n\t\temit: AgentEventSink,\n\t\tresult: Agent.ToolTerminalResult<unknown>,\n\t): Promise<void> {\n\t\tconst { partIndex, ...pendingPart } = toolCall;\n\t\tconst { time } = pendingPart;\n\t\tconst toolExecutionEnd: Event.ToolExecutionEnd = {\n\t\t\ttype: \"tool.execution.end\",\n\t\t\t...runnable,\n\t\t\t...result,\n\t\t};\n\t\tawait emitEvent(emit, { ...toolExecutionEnd });\n\n\t\tconst part: Message.ToolCallErrorPart | Message.ToolCallCompletedPart = {\n\t\t\t...pendingPart,\n\t\t\t...result,\n\t\t\ttime: {\n\t\t\t\tstart: time.start,\n\t\t\t\tend: Date.now(),\n\t\t\t},\n\t\t};\n\n\t\tmessage.parts[partIndex] = part; // in-place mutate; add error part\n\n\t\tawait emitEvent(emit, { type: \"message.part.start\", message: message, partIndex: partIndex, part: part });\n\t\tawait emitEvent(emit, { type: \"message.part.end\", message: message, partIndex: partIndex, part: part });\n\t\tawait emitEvent(emit, { type: \"message.update\", message: message });\n\t}\n\n\tasync function finalizeExecutedToolCall(\n\t\tconfig: Config,\n\t\tcurrentContext: Agent.AgentContext,\n\t\ttoolCall: ToolCallPart,\n\t\trunnable: Agent.ToolCallInFlight,\n\t\tmessage: Message.AssistantMessage,\n\t\temit: AgentEventSink,\n\t\tresult: Agent.ToolTerminalResult<unknown>,\n\t\tsignal?: AbortSignal,\n\t): Promise<void> {\n\t\tif (config.afterToolExecution) {\n\t\t\tconst afterResult = await config.afterToolExecution(\n\t\t\t\t{\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\tassistantMessage: message,\n\t\t\t\t\ttoolCall: runnable,\n\t\t\t\t\tresult,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (afterResult) {\n\t\t\t\tawait emitToolCallTerminalResult(toolCall, runnable, message, emit, afterResult);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tawait emitToolCallTerminalResult(toolCall, runnable, message, emit, result);\n\t}\n\n\t/**\n\t * Main core loop shared by run and runContinue.\n\t */\n\tasync function runLoop(\n\t\tconfig: Config,\n\t\tcurrentContext: Agent.AgentContext,\n\t\tnewMessages: Message.Message[],\n\t\temit: AgentEventSink,\n\t\tstreamFn?: StreamFn,\n\t\tsignal?: AbortSignal,\n\t): Promise<void> {\n\t\t// initial `turn.start` is already emitted\n\t\t// avoiding duplicate `turn.start` emits\n\t\tlet firstTurn = true;\n\t\t// Check for steering messages at start (user may have submitted while waiting)\n\t\tlet pendingMessages: Message.UserMessage[] = (await config.getSteeringMessages?.()) || [];\n\n\t\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\t\twhile (true) {\n\t\t\tlet hasMoreToolCalls = true;\n\n\t\t\t// Inner loop: process tool calls and steering messages\n\t\t\t// Note: turn.start for full tool calls / pending messages.\n\t\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\t\t// flip firstTurn, so next iterations starts emitting `turn.start` event\n\t\t\t\tif (!firstTurn) {\n\t\t\t\t\tawait emitEvent(emit, { type: \"turn.start\" });\n\t\t\t\t} else {\n\t\t\t\t\tfirstTurn = false;\n\t\t\t\t}\n\n\t\t\t\t// Process pending messages (inject before next assistant response)\n\t\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\t\tawait emitEvent(emit, { type: \"message.start\", message: message });\n\t\t\t\t\t\tfor (const [partIndex, part] of message.parts.entries()) {\n\t\t\t\t\t\t\tawait emitEvent(emit, { type: \"message.part.start\", message: message, partIndex, part });\n\t\t\t\t\t\t\tawait emitEvent(emit, { type: \"message.part.end\", message: message, partIndex, part });\n\t\t\t\t\t\t\tawait emitEvent(emit, { type: \"message.update\", message: message });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait emitEvent(emit, { type: \"message.end\", message: message });\n\t\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\t\tnewMessages.push(message);\n\t\t\t\t\t}\n\t\t\t\t\tpendingMessages = [];\n\t\t\t\t}\n\n\t\t\t\t// Run llm and emit assistant response\n\t\t\t\tconst message: Message.AssistantMessage = await streamAssistantResponse(\n\t\t\t\t\tconfig,\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\temit,\n\t\t\t\t\tstreamFn,\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\n\t\t\t\t// terminal state\n\t\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\t\tcurrentContext.messages.push(message); // append the terminal message into the context\n\t\t\t\t\tnewMessages.push(message); // append the terminal message\n\n\t\t\t\t\tawait emitEvent(emit, { type: \"turn.end\", message });\n\t\t\t\t\tawait emitEvent(emit, { type: \"agent.end\", messages: newMessages });\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// check for pending tool calls\n\t\t\t\t// use partIndex for in-place mutation for tool call result parts in message.parts\n\t\t\t\tconst toolCalls: ToolCallPart[] = message.parts\n\t\t\t\t\t.map((part, index) => ({ ...part, partIndex: index }))\n\t\t\t\t\t.filter((part) => part.type === \"toolCall\" && part.status === \"pending\");\n\n\t\t\t\thasMoreToolCalls = toolCalls.length > 0;\n\t\t\t\tif (hasMoreToolCalls) {\n\t\t\t\t\tawait executeToolCalls(config, currentContext, message, toolCalls, emit, signal);\n\t\t\t\t}\n\n\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\tnewMessages.push(message);\n\n\t\t\t\tawait emitEvent(emit, { type: \"turn.end\", message });\n\n\t\t\t\t//\n\t\t\t\t// check for steering messages while turn loop was working.\n\t\t\t\tpendingMessages = (await config.getSteeringMessages?.()) || [];\n\t\t\t}\n\n\t\t\t// Agent would stop here. Check for follow-up messages.\n\t\t\tconst followUpMessages = (await config.getFollowUpMessages?.()) || [];\n\t\t\tif (followUpMessages.length > 0) {\n\t\t\t\t// Set as pending so inner loop processes them\n\t\t\t\tpendingMessages = followUpMessages;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// No more messages, exit\n\t\t\tbreak;\n\t\t}\n\n\t\tawait emitEvent(emit, { type: \"agent.end\", messages: newMessages });\n\t}\n\n\texport async function runAgentLoop(\n\t\tconfig: Config,\n\t\tcontext: Agent.AgentContext,\n\t\tprompts: Message.UserMessage[],\n\t\temit: AgentEventSink,\n\t\tstreamFn?: StreamFn,\n\t\tsignal?: AbortSignal,\n\t) {\n\t\t/**\n\t\t * maintain 2 arrays to represent state, `context` the actual full state sent to the LLM,\n\t\t * `newMessages` for intermediate current loop state.\n\t\t * think of newMessages as subset of context.messages for the running current loop.\n\t\t * they do move at the same speed staring with initial user prompts.\n\t\t * */\n\t\tconst newMessages: Message.Message[] = [...prompts];\n\t\tconst currentContext: Agent.AgentContext = {\n\t\t\t...context,\n\t\t\tmessages: [...context.messages, ...prompts],\n\t\t};\n\n\t\tawait emitEvent(emit, { type: \"agent.start\" });\n\t\tawait emitEvent(emit, { type: \"turn.start\" });\n\t\tfor (const prompt of prompts) {\n\t\t\tawait emitEvent(emit, { type: \"message.start\", message: prompt });\n\t\t\tfor (const [partIndex, part] of prompt.parts.entries()) {\n\t\t\t\tawait emitEvent(emit, { type: \"message.part.start\", message: prompt, partIndex, part });\n\t\t\t\tawait emitEvent(emit, { type: \"message.part.end\", message: prompt, partIndex, part });\n\t\t\t}\n\t\t\tawait emitEvent(emit, { type: \"message.end\", message: prompt });\n\t\t}\n\n\t\tawait runLoop(config, currentContext, newMessages, emit, streamFn, signal);\n\t\treturn newMessages;\n\t}\n\n\t/**\n\t * **Important:** The last message in context must not be `assistant` message, convert\n\t * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n\t * This cannot be validated here since `convertToLlm` is only called once per turn.\n\t */\n\texport async function runAgentLoopContinue(\n\t\tconfig: Config,\n\t\tcontext: Agent.AgentContext,\n\t\temit: AgentEventSink,\n\t\tstreamFn?: StreamFn,\n\t\tsignal?: AbortSignal,\n\t) {\n\t\tif (context.messages.length === 0) {\n\t\t\tthrow new AgentContextError({ message: \"connot continue: no messages in context\" });\n\t\t}\n\t\tif (context.messages[context.messages.length - 1]?.role === \"assistant\") {\n\t\t\tthrow new AgentContextError({ message: \"cannot continue from message role: assistant\" });\n\t\t}\n\n\t\tconst newMessages: Message.Message[] = [];\n\t\tconst currentContext: Agent.AgentContext = { ...context };\n\n\t\tawait emitEvent(emit, { type: \"agent.start\" });\n\t\tawait emitEvent(emit, { type: \"turn.start\" });\n\n\t\tawait runLoop(config, currentContext, newMessages, emit, streamFn, signal);\n\t\treturn newMessages;\n\t}\n\n\t/**\n\t * Start an agent loop with a new prompt message.\n\t * The prompt is added to the context and events are emitted for it.\n\t */\n\texport function run(\n\t\tconfig: Config,\n\t\tcontext: Agent.AgentContext,\n\t\tprompts: Message.UserMessage[],\n\t\tstreamFn?: StreamFn,\n\t\tsignal?: AbortSignal,\n\t): EventStream<Event.AgentEvent, Message.Message[]> {\n\t\tconst stream = createAgentStream();\n\n\t\tvoid runAgentLoop(\n\t\t\tconfig,\n\t\t\tcontext,\n\t\t\tprompts,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tstreamFn,\n\t\t\tsignal,\n\t\t).then((messages) => {\n\t\t\tstream.end(messages);\n\t\t});\n\n\t\treturn stream;\n\t}\n\n\t/**\n\t * Continue an agent loop from the current context without adding a new message.\n\t * Used for retries - context already has user message or tool results.\n\t */\n\texport function runContinue(\n\t\tconfig: Config,\n\t\tcontext: Agent.AgentContext,\n\t\tstreamFn?: StreamFn,\n\t\tsignal?: AbortSignal,\n\t): EventStream<Event.AgentEvent, Message.Message[]> {\n\t\tconst stream = createAgentStream();\n\n\t\tvoid runAgentLoopContinue(\n\t\t\tconfig,\n\t\t\tcontext,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tstreamFn,\n\t\t\tsignal,\n\t\t).then((messages) => {\n\t\t\tstream.end(messages);\n\t\t});\n\n\t\treturn stream;\n\t}\n}\n","import { Loop } from \"./agent/loop\";\n\ntype AgentFacade = {\n\tloop: typeof Loop.run;\n\tloopContinue: typeof Loop.runContinue;\n};\n\nexport const agent = {\n\tloop: Loop.run,\n\tloopContinue: Loop.runContinue,\n} as AgentFacade;\n","import { type Static, type TSchema, Type } from \"@sinclair/typebox\";\nimport { uuidv7 } from \"uuidv7\";\nimport { Model } from \"../model/model\";\nimport { Provider } from \"../provider/provider\";\n\nexport namespace Message {\n\texport const TextContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"text\"),\n\t\ttext: Type.String(),\n\t\ttextSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the message ID\n\t});\n\texport type TextContent = Static<typeof TextContentSchema>;\n\n\texport const ImageContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"image\"),\n\t\tdata: Type.String(), // base64 encoded image data\n\t\tmimeType: Type.String(), // e.g., \"image/jpeg\", \"image/png\"\n\t});\n\texport type ImageContent = Static<typeof ImageContentSchema>;\n\n\texport const ThinkingContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"thinking\"),\n\t\tthinking: Type.String(),\n\t\tthinkingSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the reasoning item ID\n\t\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t\t * to the API for multi-turn continuity. */\n\t\tredacted: Type.Optional(Type.Boolean()),\n\t});\n\texport type ThinkingContent = Static<typeof ThinkingContentSchema>;\n\n\texport const ToolCallBaseSchema = Type.Object({\n\t\ttype: Type.Literal(\"toolCall\"),\n\t\tcallID: Type.String(),\n\t\tname: Type.String(),\n\t\targuments: Type.Record(Type.String(), Type.Any()),\n\t\tthoughtSignature: Type.Optional(Type.String()), // Google-specific: opaque signature for reusing thought context\n\t\ttime: Type.Object({\n\t\t\tstart: Type.Number(), // Unix timestamp in milliseconds\n\t\t\tend: Type.Number(), // Unix timestamp in milliseconds, last known lifecycle update\n\t\t}),\n\t});\n\n\texport const ToolSuccessResult = Type.Object({\n\t\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t\tdetails: Type.Optional(Type.Any()),\n\t\tisError: Type.Literal(false),\n\t});\n\texport const ToolErrorResult = Type.Object({\n\t\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t\tdetails: Type.Optional(Type.Any()),\n\t\tisError: Type.Literal(true),\n\t});\n\texport const ToolRunningPartial = Type.Object({\n\t\tcontent: Type.Optional(Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))),\n\t\tdetails: Type.Optional(Type.Any()),\n\t});\n\n\texport const ToolStatusEnum = {\n\t\tpending: \"pending\",\n\t\trunning: \"running\",\n\t\tcompleted: \"completed\",\n\t\terror: \"error\",\n\t\tskipped: \"skipped\",\n\t\taborted: \"aborted\",\n\t} as const;\n\n\texport const ToolRunningSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.running),\n\t\tpartial: Type.Optional(ToolRunningPartial),\n\t});\n\texport const ToolCompletedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.completed),\n\t\tresult: ToolSuccessResult,\n\t});\n\texport const ToolErrorSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.error),\n\t\tresult: ToolErrorResult,\n\t});\n\texport const ToolSkippedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.skipped),\n\t\tresult: ToolErrorResult,\n\t});\n\texport const ToolAbortedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.aborted),\n\t\tresult: ToolErrorResult,\n\t});\n\n\tconst ToolCallPendingPart = Type.Intersect([\n\t\tToolCallBaseSchema,\n\t\tType.Object({\n\t\t\tstatus: Type.Literal(ToolStatusEnum.pending),\n\t\t}),\n\t]);\n\tconst ToolCallRunningPart = Type.Composite([ToolCallBaseSchema, ToolRunningSchema]);\n\tconst ToolCallCompletedPart = Type.Composite([ToolCallBaseSchema, ToolCompletedSchema]);\n\tconst ToolCallErrorPart = Type.Composite([ToolCallBaseSchema, ToolErrorSchema]);\n\tconst ToolCallSkippedPart = Type.Composite([ToolCallBaseSchema, ToolSkippedSchema]);\n\tconst ToolCallAbortedPart = Type.Composite([ToolCallBaseSchema, ToolAbortedSchema]);\n\n\texport const ToolCallSchema = Type.Union([\n\t\tToolCallPendingPart,\n\t\tToolCallRunningPart,\n\t\tToolCallCompletedPart,\n\t\tToolCallErrorPart,\n\t\tToolCallSkippedPart,\n\t\tToolCallAbortedPart,\n\t]);\n\n\texport type ToolCall = Static<typeof ToolCallSchema>;\n\texport type ToolCallPendingPart = Static<typeof ToolCallPendingPart>;\n\texport type ToolCallRunningPart = Static<typeof ToolCallRunningPart>;\n\texport type ToolCallCompletedPart = Static<typeof ToolCallCompletedPart>;\n\texport type ToolCallErrorPart = Static<typeof ToolCallErrorPart>;\n\n\texport const UsageSchema = Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t\ttotalTokens: Type.Number(),\n\t\tcost: Type.Object({\n\t\t\tinput: Type.Number(),\n\t\t\toutput: Type.Number(),\n\t\t\tcacheRead: Type.Number(),\n\t\t\tcacheWrite: Type.Number(),\n\t\t\ttotal: Type.Number(),\n\t\t}),\n\t});\n\texport type Usage = Static<typeof UsageSchema>;\n\n\texport const StopReasonSchema = Type.Union([\n\t\tType.Literal(\"stop\"),\n\t\tType.Literal(\"length\"),\n\t\tType.Literal(\"toolUse\"),\n\t\tType.Literal(\"error\"),\n\t\tType.Literal(\"aborted\"),\n\t]);\n\texport type StopReason = Static<typeof StopReasonSchema>;\n\n\texport const UserMessageSchema = Type.Object({\n\t\tmessageId: Type.String(),\n\t\trole: Type.Literal(\"user\"),\n\t\ttime: Type.Object({\n\t\t\tcreated: Type.Number(),\n\t\t}),\n\t\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t});\n\texport type UserMessage = Static<typeof UserMessageSchema>;\n\n\texport const AssistantMessageSchema = Type.Object({\n\t\trole: Type.Literal(\"assistant\"),\n\t\tprotocol: Model.KnownProtocolSchema,\n\t\tprovider: Provider.Info,\n\t\tmodel: Type.String(),\n\t\tusage: UsageSchema,\n\t\tstopReason: StopReasonSchema,\n\t\terrorMessage: Type.Optional(Type.String()),\n\t\ttime: Type.Object({\n\t\t\tcreated: Type.Number(),\n\t\t\tcompleted: Type.Number(),\n\t\t}),\n\t\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema, ThinkingContentSchema, ToolCallSchema])),\n\t\tresponseId: Type.Optional(Type.String()), // Provider-specific response/message identifier when the upstream API exposes one\n\t\tmessageId: Type.String(),\n\t});\n\texport type AssistantMessage = Static<typeof AssistantMessageSchema>;\n\n\texport const MessageSchema = Type.Union([UserMessageSchema, AssistantMessageSchema]);\n\texport type Message = Static<typeof MessageSchema>;\n\n\ttype UserMessageInit = Omit<UserMessage, \"messageId\"> & {\n\t\tmessageId?: string;\n\t};\n\n\ttype AssistantMessageInit = Omit<AssistantMessage, \"messageId\"> & {\n\t\tmessageId?: string;\n\t};\n\n\texport function createMessageId(): string {\n\t\treturn uuidv7();\n\t}\n\n\texport function createUserMessage(message: UserMessageInit): UserMessage {\n\t\tconst { messageId = createMessageId(), ...rest } = message;\n\t\treturn {\n\t\t\tmessageId,\n\t\t\t...rest,\n\t\t};\n\t}\n\n\texport function createAssistantMessage(message: AssistantMessageInit): AssistantMessage {\n\t\tconst { messageId = createMessageId(), ...rest } = message;\n\t\treturn {\n\t\t\tmessageId,\n\t\t\t...rest,\n\t\t};\n\t}\n\n\t/**\n\t * Generic tool definition with typed parameter schema.\n\t * Usage:\n\t *\n\t * const search = Message.defineTool({\n\t * name: \"search\",\n\t * description: \"Search documents\",\n\t * parameters: Type.Object({\n\t * query: Type.String(),\n\t * limit: Type.Optional(Type.Number()),\n\t * }),\n\t * });\n\t *\n\t * type SearchParams = Static<typeof search.parameters>;\n\t */\n\texport const ToolSchema = Type.Object({\n\t\tname: Type.String(),\n\t\tdescription: Type.String(),\n\t\tparameters: Type.Unsafe<TSchema>(),\n\t});\n\texport interface Tool<TParameters extends TSchema = TSchema> {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: TParameters;\n\t}\n\texport type ToolArguments<T extends Tool> = Static<T[\"parameters\"]>;\n\n\texport function defineTool<TParameters extends TSchema>(tool: Tool<TParameters>): Tool<TParameters> {\n\t\treturn tool;\n\t}\n\n\texport const ContextSchema = Type.Object({\n\t\tsystemPrompt: Type.Optional(Type.String()),\n\t\tmessages: Type.Array(MessageSchema),\n\t\ttools: Type.Optional(Type.Array(ToolSchema)),\n\t});\n\texport type Context = Static<typeof ContextSchema>;\n\n\texport function transformMessages<TProtocol extends Model.KnownProtocol>(\n\t\tmessages: Message[],\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tnormalizeToolCallId?: (id: string, model: Model.TModel<TProtocol>, source: AssistantMessage) => string,\n\t): Message[] {\n\t\tconst toolCallIDMap = new Map<string, string>();\n\n\t\tconst transformed: Message[] = [];\n\t\tfor (const msg of messages) {\n\t\t\tif (msg.role === \"user\") {\n\t\t\t\ttransformed.push(msg);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider.id === model.provider.id &&\n\t\t\t\tassistantMsg.protocol === model.protocol &&\n\t\t\t\tassistantMsg.model === model.id;\n\n\t\t\tconst parts = assistantMsg.parts.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (isSameModel && block.thinkingSignature) return block;\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst normalizedID = toolCallIDMap.get(block.callID);\n\t\t\t\t\tif (normalizedID && normalizedID !== block.callID) {\n\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: normalizedID };\n\t\t\t\t\t} else if (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);\n\t\t\t\t\t\tif (nextID !== toolCall.callID) {\n\t\t\t\t\t\t\ttoolCallIDMap.set(toolCall.callID, nextID);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: nextID };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\ttransformed.push({\n\t\t\t\t...assistantMsg,\n\t\t\t\tparts,\n\t\t\t});\n\t\t}\n\n\t\treturn transformed;\n\t}\n}\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\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","/**\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 { Provider } from \"../provider\";\n\n// TODO @sanchitrk:\n// implement based for multiple providers\nexport function getEnvApiKey(_provider: Provider.Info): string | undefined {\n\treturn undefined;\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n\tContentBlockParam,\n\tMessageCreateParamsStreaming,\n\tMessageParam,\n} from \"@anthropic-ai/sdk/resources/messages.js\";\nimport { Message } from \"../../../message/message\";\nimport { Model } from \"../../../model/model\";\nimport { AssistantMessageEventStream } from \"../../../utils/eventstream\";\nimport { parseStreamingJson } from \"../../../utils/jsonparse\";\nimport { sanitizeSurrogates } from \"../../../utils/sanitize\";\nimport { Stream } from \"../../stream\";\nimport { getEnvApiKey } from \"../utils\";\n\nexport interface AnthropicOptions extends Stream.Options {\n\tthinkingEnabled?: boolean;\n\tthinkingBudgetTokens?: number;\n\tinterleavedThinking?: boolean;\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\tclient?: Anthropic;\n}\n\nfunction resolveCacheRetention(cacheRetention?: Stream.CacheRetention): Stream.CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.CODEWORK_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCacheControl(\n\tbaseUrl: string,\n\tcacheRetention?: Stream.CacheRetention,\n): {\n\tretention: Stream.CacheRetention;\n\tcacheControl?: { type: \"ephemeral\"; ttl?: \"1h\" };\n} {\n\tconst retention = resolveCacheRetention(cacheRetention);\n\tif (retention === \"none\") {\n\t\treturn { retention };\n\t}\n\tconst ttl = retention === \"long\" && baseUrl.includes(\"api.anthropic.com\") ? \"1h\" : undefined;\n\treturn {\n\t\tretention,\n\t\tcacheControl: { type: \"ephemeral\", ...(ttl && { ttl }) },\n\t};\n}\n\nconst claudeCodeVersion = \"2.1.2\";\nconst claudeCodeTools = [\n\t\"Read\",\n\t\"Write\",\n\t\"Edit\",\n\t\"Bash\",\n\t\"Grep\",\n\t\"Glob\",\n\t\"AskUserQuestion\",\n\t\"EnterPlanMode\",\n\t\"ExitPlanMode\",\n\t\"KillShell\",\n\t\"NotebookEdit\",\n\t\"Skill\",\n\t\"Task\",\n\t\"TaskOutput\",\n\t\"TodoWrite\",\n\t\"WebFetch\",\n\t\"WebSearch\",\n];\nconst ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));\n\nconst toClaudeCodeName = (name: string) => ccToolLookup.get(name.toLowerCase()) ?? name;\nconst fromClaudeCodeName = (name: string, tools?: Message.Tool[]) => {\n\tif (tools && tools.length > 0) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tconst matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);\n\t\tif (matchedTool) return matchedTool.name;\n\t}\n\treturn name;\n};\n\nfunction convertContentBlocks(content: (Message.TextContent | Message.ImageContent)[]):\n\t| string\n\t| Array<\n\t\t\t| { type: \"text\"; text: string }\n\t\t\t| {\n\t\t\t\t\ttype: \"image\";\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: \"base64\";\n\t\t\t\t\t\tmedia_type: \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\";\n\t\t\t\t\t\tdata: string;\n\t\t\t\t\t};\n\t\t\t }\n\t > {\n\tconst hasImages = content.some((c) => c.type === \"image\");\n\tif (!hasImages) {\n\t\treturn sanitizeSurrogates(content.map((c) => (c as Message.TextContent).text).join(\"\\n\"));\n\t}\n\n\tconst blocks = content.map((block) => {\n\t\tif (block.type === \"text\") {\n\t\t\treturn {\n\t\t\t\ttype: \"text\" as const,\n\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\ttype: \"image\" as const,\n\t\t\tsource: {\n\t\t\t\ttype: \"base64\" as const,\n\t\t\t\tmedia_type: block.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n\t\t\t\tdata: block.data,\n\t\t\t},\n\t\t};\n\t});\n\n\tif (!blocks.some((b) => b.type === \"text\")) {\n\t\tblocks.unshift({\n\t\t\ttype: \"text\" as const,\n\t\t\ttext: \"(see attached image)\",\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nfunction mergeHeaders(...headerSources: (Record<string, string> | undefined)[]): Record<string, string> {\n\tconst merged: Record<string, string> = {};\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\nfunction isOAuthToken(apiKey: string): boolean {\n\treturn apiKey.includes(\"sk-ant-oat\");\n}\n\nfunction createClient(\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.anthropicMessages>,\n\tapiKey: string,\n\tinterleavedThinking: boolean,\n\toptionsHeaders?: Record<string, string>,\n): { client: Anthropic; isOAuthToken: boolean } {\n\tconst betaFeatures = [\"fine-grained-tool-streaming-2025-05-14\"];\n\tif (interleavedThinking) {\n\t\tbetaFeatures.push(\"interleaved-thinking-2025-05-14\");\n\t}\n\n\tconst oauthToken = isOAuthToken(apiKey);\n\tif (oauthToken) {\n\t\tconst defaultHeaders = mergeHeaders(\n\t\t\t{\n\t\t\t\taccept: \"application/json\",\n\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\"anthropic-beta\": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(\",\")}`,\n\t\t\t\t\"user-agent\": `claude-cli/${claudeCodeVersion} (external, cli)`,\n\t\t\t\t\"x-app\": \"cli\",\n\t\t\t},\n\t\t\tmodel.headers,\n\t\t\toptionsHeaders,\n\t\t);\n\n\t\treturn {\n\t\t\tclient: new Anthropic({\n\t\t\t\tapiKey: null,\n\t\t\t\tauthToken: apiKey,\n\t\t\t\tbaseURL: model.baseUrl,\n\t\t\t\tdefaultHeaders,\n\t\t\t\tdangerouslyAllowBrowser: true,\n\t\t\t}),\n\t\t\tisOAuthToken: true,\n\t\t};\n\t}\n\n\tconst defaultHeaders = mergeHeaders(\n\t\t{\n\t\t\taccept: \"application/json\",\n\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\"anthropic-beta\": betaFeatures.join(\",\"),\n\t\t},\n\t\tmodel.headers,\n\t\toptionsHeaders,\n\t);\n\n\treturn {\n\t\tclient: new Anthropic({\n\t\t\tapiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tdefaultHeaders,\n\t\t}),\n\t\tisOAuthToken: false,\n\t};\n}\n\nfunction normalizeToolCallId(id: string): string {\n\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 64);\n}\n\nfunction assertReplayableAssistant(message: Message.AssistantMessage): void {\n\tlet sawToolCall = false;\n\tlet sawNonTerminalToolCall = false;\n\tlet sawTerminalToolCall = false;\n\n\tfor (const part of message.parts) {\n\t\tif (part.type === \"image\") {\n\t\t\tthrow new Error(\"Anthropic replay does not support assistant image parts\");\n\t\t}\n\n\t\tif (part.type === \"toolCall\") {\n\t\t\tsawToolCall = true;\n\t\t\tif (part.status === \"pending\" || part.status === \"running\") {\n\t\t\t\tsawNonTerminalToolCall = true;\n\t\t\t} else {\n\t\t\t\tsawTerminalToolCall = true;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (sawToolCall) {\n\t\t\tthrow new Error(\"Assistant parts after a toolCall are not replayable for Anthropic\");\n\t\t}\n\t}\n\n\tif (sawToolCall && message.stopReason !== \"toolUse\") {\n\t\tthrow new Error(\"Assistant message with tool calls must have stopReason 'toolUse'\");\n\t}\n\n\tif (!sawToolCall && message.stopReason === \"toolUse\") {\n\t\tthrow new Error(\"Assistant message with stopReason 'toolUse' must contain at least one toolCall\");\n\t}\n\n\tif (sawTerminalToolCall && sawNonTerminalToolCall) {\n\t\tthrow new Error(\"Assistant message cannot mix terminal and non-terminal toolCall states\");\n\t}\n}\n\nfunction buildSyntheticToolResult(\n\tblock: Extract<Message.ToolCall, { status: \"pending\" | \"running\" }>,\n): ContentBlockParam {\n\treturn {\n\t\ttype: \"tool_result\",\n\t\ttool_use_id: block.callID,\n\t\tcontent: convertContentBlocks([\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: [\"<result>\", \"No Result Provided\", \"</result>\"].join(\"\\n\"),\n\t\t\t},\n\t\t]),\n\t\tis_error: true,\n\t};\n}\n\nfunction convertMessages(\n\tmessages: Message.Message[],\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.anthropicMessages>,\n\tisOAuthToken: boolean,\n\tcacheControl?: { type: \"ephemeral\"; ttl?: \"1h\" },\n): MessageParam[] {\n\tconst params: MessageParam[] = [];\n\tconst transformedMessages = Message.transformMessages(messages, model, normalizeToolCallId);\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst blocks: ContentBlockParam[] = msg.parts.map((item) => {\n\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\t\tmedia_type: item.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t});\n\t\t\tlet filteredBlocks = !model.input.includes(\"image\") ? blocks.filter((b) => b.type !== \"image\") : blocks;\n\t\t\tfilteredBlocks = filteredBlocks.filter((b) => (b.type === \"text\" ? b.text.trim().length > 0 : true));\n\t\t\tif (filteredBlocks.length === 0) continue;\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: filteredBlocks,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (msg.stopReason === \"error\" || msg.stopReason === \"aborted\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tassertReplayableAssistant(msg);\n\n\t\tconst assistantBlocks: ContentBlockParam[] = [];\n\t\tconst toolResults: ContentBlockParam[] = [];\n\n\t\tfor (const block of msg.parts) {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\tif (block.text.trim().length === 0) continue;\n\t\t\t\tassistantBlocks.push({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t});\n\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\tif (block.thinking.trim().length === 0) continue;\n\t\t\t\tif (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) {\n\t\t\t\t\tassistantBlocks.push({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tassistantBlocks.push({\n\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\tthinking: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\tsignature: block.thinkingSignature,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\tassistantBlocks.push({\n\t\t\t\t\ttype: \"tool_use\",\n\t\t\t\t\tid: block.callID,\n\t\t\t\t\tname: isOAuthToken ? toClaudeCodeName(block.name) : block.name,\n\t\t\t\t\tinput: block.arguments ?? {},\n\t\t\t\t});\n\n\t\t\t\tif (block.status === \"pending\" || block.status === \"running\") {\n\t\t\t\t\ttoolResults.push(buildSyntheticToolResult(block));\n\t\t\t\t} else {\n\t\t\t\t\ttoolResults.push({\n\t\t\t\t\t\ttype: \"tool_result\",\n\t\t\t\t\t\ttool_use_id: block.callID,\n\t\t\t\t\t\tcontent: convertContentBlocks(block.result.content),\n\t\t\t\t\t\tis_error: block.result.isError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (assistantBlocks.length > 0) {\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: assistantBlocks,\n\t\t\t});\n\t\t}\n\n\t\tif (toolResults.length > 0) {\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: toolResults,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (cacheControl && params.length > 0) {\n\t\tconst lastMessage = params[params.length - 1]!;\n\t\tif (lastMessage.role === \"user\") {\n\t\t\tif (Array.isArray(lastMessage.content)) {\n\t\t\t\tconst lastBlock = lastMessage.content[lastMessage.content.length - 1];\n\t\t\t\tif (\n\t\t\t\t\tlastBlock &&\n\t\t\t\t\t(lastBlock.type === \"text\" || lastBlock.type === \"image\" || lastBlock.type === \"tool_result\")\n\t\t\t\t) {\n\t\t\t\t\t(lastBlock as { cache_control?: { type: \"ephemeral\"; ttl?: \"1h\" } }).cache_control = cacheControl;\n\t\t\t\t}\n\t\t\t} else if (typeof lastMessage.content === \"string\") {\n\t\t\t\tlastMessage.content = [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: lastMessage.content,\n\t\t\t\t\t\tcache_control: cacheControl,\n\t\t\t\t\t},\n\t\t\t\t] as any;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction convertTools(tools: Message.Tool[], isOAuthToken: boolean): Anthropic.Messages.Tool[] {\n\tif (!tools) return [];\n\n\treturn tools.map((tool) => {\n\t\tconst jsonSchema = tool.parameters as any; // TypeBox already generates JSON Schema\n\n\t\treturn {\n\t\t\tname: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tinput_schema: {\n\t\t\t\ttype: \"object\" as const,\n\t\t\t\tproperties: jsonSchema.properties || {},\n\t\t\t\trequired: jsonSchema.required || [],\n\t\t\t},\n\t\t};\n\t});\n}\n\ntype AnthropicStopReason = Anthropic.Messages.StopReason | \"sensitive\";\n\nfunction mapStopReason(reason: AnthropicStopReason): Message.StopReason {\n\tswitch (reason) {\n\t\tcase \"end_turn\":\n\t\t\treturn \"stop\";\n\t\tcase \"max_tokens\":\n\t\t\treturn \"length\";\n\t\tcase \"tool_use\":\n\t\t\treturn \"toolUse\";\n\t\tcase \"pause_turn\":\n\t\tcase \"stop_sequence\":\n\t\t\treturn \"stop\";\n\t\tcase \"refusal\":\n\t\tcase \"sensitive\":\n\t\t\treturn \"error\";\n\t\tdefault:\n\t\t\tthrow new Error(\"Unhandled Anthropic stop reason\");\n\t}\n}\n\nfunction buildParams(\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.anthropicMessages>,\n\tcontext: Message.Context,\n\tisOAuthToken: boolean,\n\toptions?: AnthropicOptions,\n): MessageCreateParamsStreaming {\n\tconst { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention);\n\tconst params: MessageCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages: convertMessages(context.messages, model, isOAuthToken, cacheControl),\n\t\tmax_tokens: options?.maxTokens || (model.maxTokens / 3) | 0,\n\t\tstream: true,\n\t};\n\n\tif (isOAuthToken) {\n\t\tparams.system = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: \"You are Claude Code, Anthropic's official CLI for Claude.\",\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t},\n\t\t];\n\t\tif (context.systemPrompt) {\n\t\t\tparams.system.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: sanitizeSurrogates(context.systemPrompt),\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t});\n\t\t}\n\t} else if (context.systemPrompt) {\n\t\tparams.system = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: sanitizeSurrogates(context.systemPrompt),\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t},\n\t\t];\n\t}\n\n\tif (options?.temperature !== undefined && !options?.thinkingEnabled) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tif (context.tools) {\n\t\tparams.tools = convertTools(context.tools, isOAuthToken);\n\t}\n\n\tif (options?.thinkingEnabled && model.reasoning) {\n\t\tparams.thinking = {\n\t\t\ttype: \"enabled\",\n\t\t\tbudget_tokens: options.thinkingBudgetTokens || 1024,\n\t\t};\n\t}\n\n\tif (options?.metadata) {\n\t\tconst userId = options.metadata.user_id;\n\t\tif (typeof userId === \"string\") {\n\t\t\tparams.metadata = { user_id: userId };\n\t\t}\n\t}\n\n\tif (options?.toolChoice) {\n\t\tparams.tool_choice = typeof options.toolChoice === \"string\" ? { type: options.toolChoice } : options.toolChoice;\n\t}\n\n\treturn params;\n}\n\ntype Block = (Message.ThinkingContent | Message.TextContent | (Message.ToolCall & { partialJson: string })) & {\n\tindex: number;\n};\n\nexport const streamAnthropic: Stream.StreamFunction<\n\ttypeof Model.KnownProtocolEnum.anthropicMessages,\n\tAnthropicOptions\n> = (\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.anthropicMessages>,\n\tcontext: Message.Context,\n\toptions?: AnthropicOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\tvoid (async () => {\n\t\tconst output = Message.createAssistantMessage({\n\t\t\trole: \"assistant\",\n\t\t\tparts: [],\n\t\t\tprotocol: model.protocol,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttime: {\n\t\t\t\tcreated: Date.now(),\n\t\t\t\tcompleted: Date.now(),\n\t\t\t},\n\t\t});\n\n\t\ttry {\n\t\t\tlet client: Anthropic;\n\t\t\tlet isOAuthToken: boolean;\n\n\t\t\tif (options?.client) {\n\t\t\t\tclient = options.client;\n\t\t\t\tisOAuthToken = false;\n\t\t\t} else {\n\t\t\t\tconst apiKey = options?.apiKey ?? getEnvApiKey(model.provider);\n\t\t\t\tif (!apiKey) {\n\t\t\t\t\tthrow new Error(`No API key for provider: ${model.provider.id}`);\n\t\t\t\t}\n\n\t\t\t\tconst created = createClient(model, apiKey, options?.interleavedThinking ?? true, options?.headers);\n\t\t\t\tclient = created.client;\n\t\t\t\tisOAuthToken = created.isOAuthToken;\n\t\t\t}\n\n\t\t\tlet params = buildParams(model, context, isOAuthToken, options);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as MessageCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst anthropicStream = client.messages.stream({ ...params, stream: true }, { signal: options?.signal });\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tconst blocks = output.parts as Block[];\n\n\t\t\tfor await (const event of anthropicStream) {\n\t\t\t\tif (event.type === \"message_start\") {\n\t\t\t\t\toutput.responseId = event.message.id;\n\t\t\t\t\t// Capture initial token usage from message_start event\n\t\t\t\t\t// This ensures we have input token counts even if the stream is aborted early\n\t\t\t\t\toutput.usage.input = event.message.usage.input_tokens || 0;\n\t\t\t\t\toutput.usage.output = event.message.usage.output_tokens || 0;\n\t\t\t\t\toutput.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;\n\t\t\t\t\toutput.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;\n\t\t\t\t\t// Anthropic doesn't provide total_tokens, compute from components\n\t\t\t\t\toutput.usage.totalTokens =\n\t\t\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\t\t\tModel.calculateCost(model, output.usage);\n\t\t\t\t} else if (event.type === \"content_block_start\") {\n\t\t\t\t\tif (event.content_block.type === \"text\") {\n\t\t\t\t\t\tconst block: Block = { type: \"text\", text: \"\", index: event.index };\n\t\t\t\t\t\toutput.parts.push(block); // push the block to parts\n\t\t\t\t\t\t// `contentIndex` points to the index of the block within parts\n\t\t\t\t\t\t// Useful for replaying message and corresponding parts based on stream.\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text.start\",\n\t\t\t\t\t\t\tpartIndex: output.parts.length - 1,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (event.content_block.type === \"thinking\") {\n\t\t\t\t\t\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: \"\",\n\t\t\t\t\t\t\tthinkingSignature: \"\",\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.parts.push(block);\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"thinking.start\",\n\t\t\t\t\t\t\tpartIndex: output.parts.length - 1,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (event.content_block.type === \"redacted_thinking\") {\n\t\t\t\t\t\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: \"[Reasoning redacted]\",\n\t\t\t\t\t\t\tthinkingSignature: event.content_block.data,\n\t\t\t\t\t\t\tredacted: true,\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.parts.push(block);\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"thinking.start\",\n\t\t\t\t\t\t\tpartIndex: output.parts.length - 1,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (event.content_block.type === \"tool_use\") {\n\t\t\t\t\t\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tcallID: event.content_block.id,\n\t\t\t\t\t\t\tname: isOAuthToken\n\t\t\t\t\t\t\t\t? fromClaudeCodeName(event.content_block.name, context.tools)\n\t\t\t\t\t\t\t\t: event.content_block.name,\n\t\t\t\t\t\t\targuments: (event.content_block.input as Record<string, any>) ?? {},\n\t\t\t\t\t\t\tpartialJson: \"\",\n\t\t\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t\t\ttime: {\n\t\t\t\t\t\t\t\tstart: Date.now(),\n\t\t\t\t\t\t\t\tend: Date.now(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.parts.push(block);\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"toolcall.start\",\n\t\t\t\t\t\t\tpartIndex: output.parts.length - 1,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_delta\") {\n\t\t\t\t\t// *_delta updates existing block part\n\t\t\t\t\t// filtered based on event identifier `event.index` (not to confuse with array indices)\n\t\t\t\t\t// index persisted on block(part) with `index`\n\t\t\t\t\tconst partIndex = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\tconst block = blocks[partIndex];\n\t\t\t\t\tif (!block) continue; // block doesn't exist for delta, move on\n\n\t\t\t\t\tif (event.delta.type === \"text_delta\" && block.type === \"text\") {\n\t\t\t\t\t\tblock.text += event.delta.text; // mutates block, implicitly mutating block in output.parts\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text.delta\",\n\t\t\t\t\t\t\tpartIndex: partIndex,\n\t\t\t\t\t\t\tdelta: event.delta.text,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (event.delta.type === \"thinking_delta\" && block.type === \"thinking\") {\n\t\t\t\t\t\tblock.thinking += event.delta.thinking;\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"thinking.delta\",\n\t\t\t\t\t\t\tpartIndex: partIndex,\n\t\t\t\t\t\t\tdelta: event.delta.thinking,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (event.delta.type === \"input_json_delta\" && block.type === \"toolCall\") {\n\t\t\t\t\t\tblock.partialJson += event.delta.partial_json;\n\t\t\t\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"toolcall.delta\",\n\t\t\t\t\t\t\tpartIndex: partIndex,\n\t\t\t\t\t\t\tdelta: event.delta.partial_json,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (event.delta.type === \"signature_delta\" && block.type === \"thinking\") {\n\t\t\t\t\t\tblock.thinkingSignature = block.thinkingSignature || \"\";\n\t\t\t\t\t\tblock.thinkingSignature += event.delta.signature;\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_stop\") {\n\t\t\t\t\tconst partIndex = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\tconst block = blocks[partIndex];\n\t\t\t\t\tif (block) {\n\t\t\t\t\t\tdelete (block as any).index; // clear block index; used for internal loop state\n\t\t\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"text.end\",\n\t\t\t\t\t\t\t\tpartIndex: partIndex,\n\t\t\t\t\t\t\t\tcontent: block.text,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking.end\",\n\t\t\t\t\t\t\t\tpartIndex: partIndex,\n\t\t\t\t\t\t\t\tcontent: block.thinking,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\t\t\t\t\tdelete (block as any).partialJson; // clear partialJson; used for internal loop state\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall.end\",\n\t\t\t\t\t\t\t\tpartIndex: partIndex,\n\t\t\t\t\t\t\t\ttoolCall: block,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"message_delta\") {\n\t\t\t\t\tif (event.delta.stop_reason) {\n\t\t\t\t\t\toutput.stopReason = mapStopReason(event.delta.stop_reason);\n\t\t\t\t\t}\n\t\t\t\t\t// Only update usage fields if present (not null).\n\t\t\t\t\t// Preserves input_tokens from message_start when proxies omit it in message_delta.\n\t\t\t\t\tif (event.usage.input_tokens != null) {\n\t\t\t\t\t\toutput.usage.input = event.usage.input_tokens;\n\t\t\t\t\t}\n\t\t\t\t\tif (event.usage.output_tokens != null) {\n\t\t\t\t\t\toutput.usage.output = event.usage.output_tokens;\n\t\t\t\t\t}\n\t\t\t\t\tif (event.usage.cache_read_input_tokens != null) {\n\t\t\t\t\t\toutput.usage.cacheRead = event.usage.cache_read_input_tokens;\n\t\t\t\t\t}\n\t\t\t\t\tif (event.usage.cache_creation_input_tokens != null) {\n\t\t\t\t\t\toutput.usage.cacheWrite = event.usage.cache_creation_input_tokens;\n\t\t\t\t\t}\n\t\t\t\t\t// Anthropic doesn't provide total_tokens, compute from components\n\t\t\t\t\toutput.usage.totalTokens =\n\t\t\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\t\t\tModel.calculateCost(model, output.usage);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\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) delete (block as { index?: number }).index;\n\t\t\toutput.time.completed = Date.now();\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\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\nexport const streamSimpleAnthropic: Stream.StreamFunction<\n\ttypeof Model.KnownProtocolEnum.anthropicMessages,\n\tStream.SimpleOptions\n> = (\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.anthropicMessages>,\n\tcontext: Message.Context,\n\toptions?: Stream.SimpleOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider.id}`);\n\t}\n\n\tconst base = Stream.buildBaseOptions(model, options, apiKey);\n\tif (!options?.reasoning) {\n\t\treturn streamAnthropic(model, context, {\n\t\t\t...base,\n\t\t\tthinkingEnabled: false,\n\t\t} satisfies AnthropicOptions);\n\t}\n\n\tconst adjusted = Stream.adjustMaxTokensForThinking(\n\t\tbase.maxTokens || 0,\n\t\tmodel.maxTokens,\n\t\toptions.reasoning,\n\t\toptions.thinkingBudgets,\n\t);\n\n\treturn streamAnthropic(model, context, {\n\t\t...base,\n\t\tmaxTokens: adjusted.maxTokens,\n\t\tthinkingEnabled: true,\n\t\tthinkingBudgetTokens: adjusted.thinkingBudget,\n\t} satisfies AnthropicOptions);\n};\n\nconst anthropicProtocolProvider: Stream.ProtocolProvider<\n\ttypeof Model.KnownProtocolEnum.anthropicMessages,\n\tAnthropicOptions\n> = {\n\tprotocol: Model.KnownProtocolEnum.anthropicMessages,\n\tstream: streamAnthropic,\n\tstreamSimple: streamSimpleAnthropic,\n};\n\nexport default anthropicProtocolProvider;\n","import type { Message } from \"../../../message/message\";\n\n// Copilot expects X-Initiator to indicate whether the request is user-initiated\n// or agent-initiated (e.g. follow-up after assistant/tool messages).\nexport function inferCopilotInitiator(messages: Message.Message[]): \"user\" | \"agent\" {\n\tconst last = messages[messages.length - 1];\n\treturn last && last.role !== \"user\" ? \"agent\" : \"user\";\n}\n\n// Copilot requires Copilot-Vision-Request header when sending images\nexport function hasCopilotVisionInput(messages: Message.Message[]): boolean {\n\treturn messages.some((msg) => {\n\t\tif (msg.role === \"user\") {\n\t\t\treturn msg.parts.some((c) => c.type === \"image\");\n\t\t}\n\t\treturn false;\n\t});\n}\n\nexport function buildCopilotDynamicHeaders(params: {\n\tmessages: Message.Message[];\n\thasImages: boolean;\n}): Record<string, string> {\n\tconst headers: Record<string, string> = {\n\t\t\"X-Initiator\": inferCopilotInitiator(params.messages),\n\t\t\"Openai-Intent\": \"conversation-edits\",\n\t};\n\n\tif (params.hasImages) {\n\t\theaders[\"Copilot-Vision-Request\"] = \"true\";\n\t}\n\n\treturn headers;\n}\n","import OpenAI from \"openai\";\nimport type {\n\tChatCompletionAssistantMessageParam,\n\tChatCompletionContentPart,\n\tChatCompletionContentPartImage,\n\tChatCompletionContentPartText,\n\tChatCompletionMessageParam,\n\tChatCompletionToolMessageParam,\n} from \"openai/resources/chat/completions.js\";\nimport { Message } from \"../../../message/message\";\nimport { Model } from \"../../../model/model\";\nimport { AssistantMessageEventStream } from \"../../../utils/eventstream\";\nimport { parseStreamingJson } from \"../../../utils/jsonparse\";\nimport { sanitizeSurrogates } from \"../../../utils/sanitize\";\nimport { Provider } from \"../../provider\";\nimport { Stream } from \"../../stream\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"../github/github\";\nimport { getEnvApiKey } from \"../utils\";\n\ntype OpenAIReasoningEffort = keyof Provider.StrictReasoningEffortMap;\n\ntype StreamingToolCallBlock = Message.ToolCall & {\n\tindex?: number;\n\tpartialArgs?: string;\n\tstreamIndex?: number;\n};\n\ntype StreamingBlock =\n\t| (Message.TextContent & { index?: number })\n\t| (Message.ThinkingContent & { index?: number })\n\t| StreamingToolCallBlock;\n\nfunction hasToolHistory(messages: Message.Message[]): boolean {\n\tfor (const msg of messages) {\n\t\tif (msg.role !== \"assistant\") continue;\n\t\tif (msg.parts.some((block) => block.type === \"toolCall\")) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction buildSyntheticToolResult(\n\tblock: Extract<Message.ToolCall, { status: \"pending\" | \"running\" }>,\n\tcompat: Required<Model.OpenAICompletionsCompat>,\n): ChatCompletionToolMessageParam {\n\tconst message: ChatCompletionToolMessageParam = {\n\t\trole: \"tool\",\n\t\tcontent: [\"<result>\", \"No Result Provided\", \"</result>\"].join(\"\\n\"),\n\t\ttool_call_id: block.callID,\n\t};\n\tif (compat.requiresToolResultName) {\n\t\t(message as ChatCompletionToolMessageParam & { name?: string }).name = block.name;\n\t}\n\treturn message;\n}\n\nexport interface OpenAICompletionsOptions extends Stream.Options {\n\ttoolChoice?: \"auto\" | \"none\" | \"required\" | { type: \"function\"; function: { name: string } };\n\treasoningEffort?: OpenAIReasoningEffort;\n}\n\nfunction resolveBaseUrl(model: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>): string {\n\treturn model.baseUrl || (model.provider.id === Provider.KnownProviderEnum.openai ? \"https://api.openai.com/v1\" : \"\");\n}\n\nexport const streamOpenAICompletions: Stream.StreamFunction<\n\ttypeof Model.KnownProtocolEnum.openaiCompletions,\n\tOpenAICompletionsOptions\n> = (\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n\tcontext: Message.Context,\n\toptions?: OpenAICompletionsOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\tvoid (async () => {\n\t\tconst output = Message.createAssistantMessage({\n\t\t\trole: \"assistant\",\n\t\t\tparts: [],\n\t\t\tprotocol: model.protocol,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttime: {\n\t\t\t\tcreated: Date.now(),\n\t\t\t\tcompleted: Date.now(),\n\t\t\t},\n\t\t});\n\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\t\t\tconst client = createClient(model, context, apiKey, options?.headers);\n\t\t\tlet params = buildParams(model, context, options);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;\n\t\t\t}\n\n\t\t\tconst openaiStream = await client.chat.completions.create(params, { signal: options?.signal });\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tlet currentBlock: Exclude<StreamingBlock, StreamingToolCallBlock> | null = null;\n\t\t\tconst blocks = output.parts as StreamingBlock[];\n\t\t\tconst activeToolCalls = new Map<number, StreamingToolCallBlock>();\n\t\t\tconst finishCurrentBlock = (block?: StreamingBlock | null) => {\n\t\t\t\tif (block) {\n\t\t\t\t\tconst partIndex = block.index ?? blocks.indexOf(block);\n\t\t\t\t\tdelete block.index;\n\n\t\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text.end\",\n\t\t\t\t\t\t\tpartIndex,\n\t\t\t\t\t\t\tcontent: block.text,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"thinking.end\",\n\t\t\t\t\t\t\tpartIndex,\n\t\t\t\t\t\t\tcontent: block.thinking,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\t\tif (block.streamIndex !== undefined) {\n\t\t\t\t\t\t\tactiveToolCalls.delete(block.streamIndex);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblock.arguments = parseStreamingJson<Record<string, unknown>>(block.partialArgs);\n\t\t\t\t\t\tdelete block.partialArgs;\n\t\t\t\t\t\tdelete block.streamIndex;\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"toolcall.end\",\n\t\t\t\t\t\t\tpartIndex,\n\t\t\t\t\t\t\ttoolCall: block,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst flushActiveToolCalls = () => {\n\t\t\t\tfor (const toolBlock of [...activeToolCalls.values()].sort((a, b) => (a.index ?? 0) - (b.index ?? 0))) {\n\t\t\t\t\tfinishCurrentBlock(toolBlock);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tfor await (const chunk of openaiStream) {\n\t\t\t\tif (!chunk || typeof chunk !== \"object\") continue;\n\n\t\t\t\t// OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier,\n\t\t\t\t// and each chunk in a streamed completion carries the same id.\n\t\t\t\toutput.responseId ||= chunk.id;\n\t\t\t\tif (chunk.usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage(chunk.usage, model);\n\t\t\t\t}\n\n\t\t\t\tconst choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined;\n\t\t\t\tif (!choice) continue;\n\n\t\t\t\t// fallback: some providers (e.g., Moonshot) return usage\n\t\t\t\t// in choice.usage instead of the standard chunk.usage\n\t\t\t\tconst choiceWithUsage = choice as unknown as {\n\t\t\t\t\tusage?: Parameters<typeof parseChunkUsage>[0];\n\t\t\t\t};\n\t\t\t\tif (!chunk.usage && choiceWithUsage.usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage(choiceWithUsage.usage, model);\n\t\t\t\t}\n\n\t\t\t\tif (choice.finish_reason) {\n\t\t\t\t\tconst finishReasonResult = mapStopReason(choice.finish_reason);\n\t\t\t\t\toutput.stopReason = finishReasonResult.stopReason;\n\t\t\t\t\tif (finishReasonResult.errorMessage) {\n\t\t\t\t\t\toutput.errorMessage = finishReasonResult.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!choice.delta) continue;\n\n\t\t\t\tif (\n\t\t\t\t\tchoice.delta.content !== null &&\n\t\t\t\t\tchoice.delta.content !== undefined &&\n\t\t\t\t\tchoice.delta.content.length > 0\n\t\t\t\t) {\n\t\t\t\t\tif (activeToolCalls.size > 0) {\n\t\t\t\t\t\tflushActiveToolCalls();\n\t\t\t\t\t}\n\t\t\t\t\tif (!currentBlock || currentBlock.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\", index: output.parts.length };\n\t\t\t\t\t\toutput.parts.push(currentBlock);\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text.start\",\n\t\t\t\t\t\t\tpartIndex: currentBlock.index!,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\tcurrentBlock.text += choice.delta.content;\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text.delta\",\n\t\t\t\t\t\t\tpartIndex: currentBlock.index!,\n\t\t\t\t\t\t\tdelta: choice.delta.content,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// some endpoints return reasoning in reasoning_content (llama.cpp),\n\t\t\t\t// or reasoning (other openai compatible endpoints)\n\t\t\t\t// Use the first non-empty reasoning field to avoid duplication\n\t\t\t\t// (e.g., chutes.ai returns both reasoning_content and reasoning with same content)\n\t\t\t\tconst reasoningFields = [\"reasoning_content\", \"reasoning\", \"reasoning_text\"] as const;\n\t\t\t\tlet foundReasoningField: (typeof reasoningFields)[number] | null = null;\n\t\t\t\tfor (const field of reasoningFields) {\n\t\t\t\t\tconst value = (choice.delta as Record<string, unknown>)[field];\n\t\t\t\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\t\t\t\tfoundReasoningField = field;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (foundReasoningField) {\n\t\t\t\t\tif (activeToolCalls.size > 0) {\n\t\t\t\t\t\tflushActiveToolCalls();\n\t\t\t\t\t}\n\t\t\t\t\tif (!currentBlock || currentBlock.type !== \"thinking\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = {\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: \"\",\n\t\t\t\t\t\t\tthinkingSignature: foundReasoningField,\n\t\t\t\t\t\t\tindex: output.parts.length,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.parts.push(currentBlock);\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"thinking.start\",\n\t\t\t\t\t\t\tpartIndex: currentBlock.index!,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tif (currentBlock.type === \"thinking\") {\n\t\t\t\t\t\tconst delta = (choice.delta as Record<string, unknown>)[foundReasoningField];\n\t\t\t\t\t\tif (typeof delta === \"string\") {\n\t\t\t\t\t\t\tcurrentBlock.thinking += delta;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking.delta\",\n\t\t\t\t\t\t\t\tpartIndex: currentBlock.index!,\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (choice.delta.tool_calls) {\n\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = null;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const toolCall of choice.delta.tool_calls) {\n\t\t\t\t\t\tconst streamIndex = toolCall.index ?? activeToolCalls.size;\n\t\t\t\t\t\tlet toolBlock = activeToolCalls.get(streamIndex);\n\t\t\t\t\t\tif (!toolBlock) {\n\t\t\t\t\t\t\ttoolBlock = {\n\t\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\t\tcallID: toolCall.id || \"\",\n\t\t\t\t\t\t\t\tname: toolCall.function?.name || \"\",\n\t\t\t\t\t\t\t\targuments: {},\n\t\t\t\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t\t\t\t\tindex: output.parts.length,\n\t\t\t\t\t\t\t\tstreamIndex,\n\t\t\t\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t\t\t\ttime: {\n\t\t\t\t\t\t\t\t\tstart: Date.now(),\n\t\t\t\t\t\t\t\t\tend: Date.now(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tactiveToolCalls.set(streamIndex, toolBlock);\n\t\t\t\t\t\t\toutput.parts.push(toolBlock);\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall.start\",\n\t\t\t\t\t\t\t\tpartIndex: toolBlock.index!,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (toolCall.id) toolBlock.callID = toolCall.id;\n\t\t\t\t\t\tif (toolCall.function?.name) toolBlock.name = toolCall.function.name;\n\n\t\t\t\t\t\tlet delta = \"\";\n\t\t\t\t\t\tif (toolCall.function?.arguments) {\n\t\t\t\t\t\t\tdelta = toolCall.function.arguments;\n\t\t\t\t\t\t\ttoolBlock.partialArgs = (toolBlock.partialArgs || \"\") + delta;\n\t\t\t\t\t\t\ttoolBlock.arguments = parseStreamingJson<Record<string, unknown>>(toolBlock.partialArgs);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttoolBlock.time.end = Date.now();\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"toolcall.delta\",\n\t\t\t\t\t\t\tpartIndex: toolBlock.index!,\n\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst reasoningDetails = (choice.delta as { reasoning_details?: Array<Record<string, unknown>> })\n\t\t\t\t\t.reasoning_details;\n\t\t\t\tif (reasoningDetails && Array.isArray(reasoningDetails)) {\n\t\t\t\t\tfor (const detail of reasoningDetails) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tdetail.type === \"reasoning.encrypted\" &&\n\t\t\t\t\t\t\ttypeof detail.id === \"string\" &&\n\t\t\t\t\t\t\tdetail.data !== undefined\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst matchingToolCall = output.parts.find(\n\t\t\t\t\t\t\t\t(block) => block.type === \"toolCall\" && block.callID === detail.id,\n\t\t\t\t\t\t\t) as Message.ToolCall | undefined;\n\t\t\t\t\t\t\tif (matchingToolCall) {\n\t\t\t\t\t\t\t\tmatchingToolCall.thoughtSignature = JSON.stringify(detail);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\tflushActiveToolCalls();\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(\"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 StreamingBlock).index;\n\t\t\t\tdelete (block as StreamingToolCallBlock).partialArgs;\n\t\t\t\tdelete (block as StreamingToolCallBlock).streamIndex;\n\t\t\t}\n\t\t\toutput.time.completed = Date.now();\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tconst rawMetadata = (error as { error?: { metadata?: { raw?: string } } })?.error?.metadata?.raw;\n\t\t\tif (rawMetadata) output.errorMessage += `\\n${rawMetadata}`;\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\nexport const streamSimpleOpenAICompletions: Stream.StreamFunction<\n\ttypeof Model.KnownProtocolEnum.openaiCompletions,\n\tStream.SimpleOptions\n> = (\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n\tcontext: Message.Context,\n\toptions?: Stream.SimpleOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider.id}`);\n\t}\n\n\tconst base = Stream.buildBaseOptions(model, options, apiKey);\n\tconst simpleReasoning = Model.supportsXhigh(model) ? options?.reasoning : Stream.clampReasoning(options?.reasoning);\n\tconst reasoningEffort: OpenAIReasoningEffort | undefined =\n\t\tsimpleReasoning && simpleReasoning !== Stream.ThinkingLevelEnum.off ? simpleReasoning : undefined;\n\tconst toolChoice = (options as OpenAICompletionsOptions | undefined)?.toolChoice;\n\n\treturn streamOpenAICompletions(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t\ttoolChoice,\n\t} satisfies OpenAICompletionsOptions);\n};\n\nfunction buildParams(\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n\tcontext: Message.Context,\n\toptions?: OpenAICompletionsOptions,\n) {\n\tconst compat = getCompat(model);\n\tconst messages = convertMessages(model, context, compat);\n\tmaybeAddOpenRouterAnthropicCacheControl(model, messages);\n\t//\n\t// resolve URL\n\t// ideally this is last resort\n\tconst baseUrl = resolveBaseUrl(model);\n\n\tconst params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages,\n\t\tstream: true,\n\t};\n\n\tif (compat.supportsUsageInStreaming !== false) {\n\t\t(params as typeof params & { stream_options?: { include_usage: boolean } }).stream_options = {\n\t\t\tinclude_usage: true,\n\t\t};\n\t}\n\n\tif (compat.supportsStore) {\n\t\tparams.store = false;\n\t}\n\n\tif (options?.maxTokens) {\n\t\tif (compat.maxTokensField === \"max_tokens\") {\n\t\t\t(params as typeof params & { max_tokens?: number }).max_tokens = options.maxTokens;\n\t\t} else {\n\t\t\tparams.max_completion_tokens = options.maxTokens;\n\t\t}\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tif (context.tools) {\n\t\tparams.tools = convertTools(context.tools, compat);\n\t\tif (compat.zaiToolStream) {\n\t\t\t(params as typeof params & { tool_stream?: boolean }).tool_stream = true;\n\t\t}\n\t} else if (hasToolHistory(context.messages)) {\n\t\tparams.tools = [];\n\t}\n\n\tif (options?.toolChoice) {\n\t\tparams.tool_choice = options.toolChoice;\n\t}\n\n\tif ((compat.thinkingFormat === \"zai\" || compat.thinkingFormat === \"qwen\") && model.reasoning) {\n\t\t(params as typeof params & { enable_thinking?: boolean }).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen-chat-template\" && model.reasoning) {\n\t\t(params as typeof params & { chat_template_kwargs?: { enable_thinking: boolean } }).chat_template_kwargs = {\n\t\t\tenable_thinking: !!options?.reasoningEffort,\n\t\t};\n\t} else if (compat.thinkingFormat === \"openrouter\" && model.reasoning) {\n\t\tconst openRouterParams = params as typeof params & { reasoning?: { effort?: string } };\n\t\tif (options?.reasoningEffort) {\n\t\t\topenRouterParams.reasoning = {\n\t\t\t\teffort: mapReasoningEffort(options.reasoningEffort, compat.reasoningEffortMap),\n\t\t\t};\n\t\t} else {\n\t\t\topenRouterParams.reasoning = { effort: \"none\" };\n\t\t}\n\t} else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\t(params as { reasoning_effort?: string }).reasoning_effort = mapReasoningEffort(\n\t\t\toptions.reasoningEffort,\n\t\t\tcompat.reasoningEffortMap,\n\t\t);\n\t}\n\n\tif (baseUrl.includes(\"openrouter.ai\") && model.compat?.openRouterRouting) {\n\t\t(params as typeof params & { provider?: Provider.OpenRouterRouting }).provider = model.compat.openRouterRouting;\n\t}\n\n\tif (baseUrl.includes(\"ai-gateway.vercel.sh\") && model.compat?.vercelGatewayRouting) {\n\t\tconst routing = model.compat.vercelGatewayRouting;\n\t\tif (routing.only || routing.order) {\n\t\t\tconst gatewayOptions: Record<string, string[]> = {};\n\t\t\tif (routing.only) gatewayOptions.only = routing.only;\n\t\t\tif (routing.order) gatewayOptions.order = routing.order;\n\t\t\t(\n\t\t\t\tparams as typeof params & {\n\t\t\t\t\tproviderOptions?: { gateway: Record<string, string[]> };\n\t\t\t\t}\n\t\t\t).providerOptions = { gateway: gatewayOptions };\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction createClient(\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n\tcontext: Message.Context,\n\tapiKey?: string,\n\toptsHeaders?: Record<string, string>,\n) {\n\tconst baseUrl = resolveBaseUrl(model);\n\tif (!apiKey) {\n\t\tif (!process.env.OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI API key is required. set OPENAI_API_KEY environment variable or pass it as an argument\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.OPENAI_API_KEY;\n\t}\n\n\tconst headers = { ...model.headers };\n\tif (model.provider.id === Provider.KnownProviderEnum.githubCopilot) {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (optsHeaders) {\n\t\tObject.assign(headers, optsHeaders);\n\t}\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t});\n}\n\nfunction mapReasoningEffort(\n\teffort: NonNullable<OpenAICompletionsOptions[\"reasoningEffort\"]>,\n\treasoningEffortMap: Partial<Record<OpenAIReasoningEffort, string>>,\n): string {\n\treturn reasoningEffortMap[effort] ?? effort;\n}\n\nfunction maybeAddOpenRouterAnthropicCacheControl(\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n\tmessages: ChatCompletionMessageParam[],\n): void {\n\tif (model.provider.id !== Provider.KnownProviderEnum.openrouter || !model.id.startsWith(\"anthropic/\")) return;\n\n\t// Anthropic-style caching requires cache_control on a text part. Add a breakpoint\n\t// on the last user/assistant message (walking backwards until we find text content).\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst msg = messages[i];\n\t\tif (!msg) continue;\n\t\tif (msg.role !== \"user\" && msg.role !== \"assistant\") continue;\n\n\t\tconst content = msg.content;\n\t\tif (typeof content === \"string\") {\n\t\t\tmsg.content = [\n\t\t\t\tObject.assign({ type: \"text\" as const, text: content }, { cache_control: { type: \"ephemeral\" } }),\n\t\t\t];\n\t\t\treturn;\n\t\t}\n\n\t\tif (!Array.isArray(content)) continue;\n\n\t\tfor (let j = content.length - 1; j >= 0; j--) {\n\t\t\tconst part = content[j];\n\t\t\tif (part?.type === \"text\") {\n\t\t\t\tObject.assign(part, { cache_control: { type: \"ephemeral\" } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function convertMessages(\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n\tcontext: Message.Context,\n\tcompat: Required<Model.OpenAICompletionsCompat>,\n): ChatCompletionMessageParam[] {\n\tconst params: ChatCompletionMessageParam[] = [];\n\n\tconst normalizeToolCallId = (id: string): string => {\n\t\t// handle pipe-separated IDs from OpenAI Responses API\n\t\t// format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =)\n\t\t// these come from providers like github-copilot, openai-codex, opencode\n\t\t// extract just the call_id part and normalize it\n\t\tif (id.includes(\"|\")) {\n\t\t\tconst callID = id.split(\"|\")[0] ?? id;\n\t\t\t// sanitize to allowed chars and truncate to 40 chars (OpenAI limit)\n\t\t\treturn callID.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 40);\n\t\t}\n\n\t\tif (model.provider.id === Provider.KnownProviderEnum.openai) {\n\t\t\treturn id.length > 40 ? id.slice(0, 40) : id;\n\t\t}\n\t\treturn id;\n\t};\n\n\tconst transformedMessages = Message.transformMessages(context.messages, model, normalizeToolCallId);\n\n\tif (context.systemPrompt) {\n\t\tconst useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;\n\t\tconst role = useDeveloperRole ? \"developer\" : \"system\";\n\t\tparams.push({\n\t\t\trole,\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tlet lastRole: \"user\" | \"assistant\" | \"tool\" | null = null;\n\n\tfor (const msg of transformedMessages) {\n\t\t// some providers don't allow user messages directly after tool results\n\t\t// insert a synthetic assistant message to bridge the gap\n\t\tif (compat.requiresAssistantAfterToolResult && lastRole === \"tool\" && msg.role === \"user\") {\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t});\n\t\t\tlastRole = \"assistant\";\n\t\t}\n\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content: ChatCompletionContentPart[] = msg.parts.flatMap((item): ChatCompletionContentPart[] => {\n\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\tconst text = sanitizeSurrogates(item.text);\n\t\t\t\t\tif (text.trim().length === 0) return [];\n\t\t\t\t\treturn [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartText,\n\t\t\t\t\t];\n\t\t\t\t}\n\n\t\t\t\tif (!model.input.includes(\"image\")) return [];\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\turl: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t} satisfies ChatCompletionContentPartImage,\n\t\t\t\t];\n\t\t\t});\n\n\t\t\tif (content.length === 0) continue;\n\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent,\n\t\t\t});\n\t\t\tlastRole = \"user\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst assistantMsg: ChatCompletionAssistantMessageParam = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: compat.requiresAssistantAfterToolResult ? \"\" : null,\n\t\t};\n\n\t\tconst textBlocks = msg.parts.filter((block) => block.type === \"text\") as Message.TextContent[];\n\t\tconst textSegments = textBlocks\n\t\t\t.map((block) => sanitizeSurrogates(block.text))\n\t\t\t.filter((text) => text.trim().length > 0);\n\n\t\tconst thinkingBlocks = msg.parts.filter((block) => block.type === \"thinking\") as Message.ThinkingContent[];\n\t\tconst nonEmptyThinkingBlocks = thinkingBlocks.filter((block) => block.thinking.trim().length > 0);\n\n\t\tif (compat.requiresThinkingAsText && nonEmptyThinkingBlocks.length > 0) {\n\t\t\ttextSegments.unshift(...nonEmptyThinkingBlocks.map((block) => sanitizeSurrogates(block.thinking)));\n\t\t} else if (nonEmptyThinkingBlocks.length > 0) {\n\t\t\tconst signature = nonEmptyThinkingBlocks[0]?.thinkingSignature;\n\t\t\tif (signature && signature.length > 0) {\n\t\t\t\t(assistantMsg as ChatCompletionAssistantMessageParam & Record<string, string>)[signature] =\n\t\t\t\t\tnonEmptyThinkingBlocks.map((block) => sanitizeSurrogates(block.thinking)).join(\"\\n\");\n\t\t\t}\n\t\t}\n\n\t\tif (textSegments.length > 0) {\n\t\t\tassistantMsg.content = textSegments.join(\"\");\n\t\t}\n\n\t\tconst toolCalls = msg.parts.filter((block) => block.type === \"toolCall\") as Message.ToolCall[];\n\t\tif (toolCalls.length > 0) {\n\t\t\tassistantMsg.tool_calls = toolCalls.map((toolCall) => ({\n\t\t\t\tid: toolCall.callID,\n\t\t\t\ttype: \"function\" as const,\n\t\t\t\tfunction: {\n\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t},\n\t\t\t}));\n\n\t\t\tconst reasoningDetails = toolCalls\n\t\t\t\t.filter((toolCall) => toolCall.thoughtSignature)\n\t\t\t\t.map((toolCall) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn JSON.parse(toolCall.thoughtSignature!);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.filter(Boolean);\n\n\t\t\tif (reasoningDetails.length > 0) {\n\t\t\t\t(\n\t\t\t\t\tassistantMsg as ChatCompletionAssistantMessageParam & { reasoning_details?: unknown[] }\n\t\t\t\t).reasoning_details = reasoningDetails;\n\t\t\t}\n\t\t}\n\n\t\tconst assistantContent = assistantMsg.content;\n\t\tconst hasAssistantContent =\n\t\t\tassistantContent !== null &&\n\t\t\tassistantContent !== undefined &&\n\t\t\t(typeof assistantContent === \"string\" ? assistantContent.length > 0 : assistantContent.length > 0);\n\t\tif (!hasAssistantContent && !assistantMsg.tool_calls) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tparams.push(assistantMsg);\n\t\tlastRole = \"assistant\";\n\n\t\tconst imageBlocks: Array<{ type: \"image_url\"; image_url: { url: string } }> = [];\n\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tif (toolCall.status === \"pending\" || toolCall.status === \"running\") {\n\t\t\t\tparams.push(buildSyntheticToolResult(toolCall, compat));\n\t\t\t\tlastRole = \"tool\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst textResult = toolCall.result.content\n\t\t\t\t.filter((content) => content.type === \"text\")\n\t\t\t\t.map((content) => content.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst hasImages = toolCall.result.content.some((content) => content.type === \"image\");\n\n\t\t\tconst toolResultMsg: ChatCompletionToolMessageParam = {\n\t\t\t\trole: \"tool\",\n\t\t\t\tcontent: sanitizeSurrogates(textResult.length > 0 ? textResult : \"(see attached image)\"),\n\t\t\t\ttool_call_id: toolCall.callID,\n\t\t\t};\n\t\t\tif (compat.requiresToolResultName) {\n\t\t\t\t(toolResultMsg as ChatCompletionToolMessageParam & { name?: string }).name = toolCall.name;\n\t\t\t}\n\t\t\tparams.push(toolResultMsg);\n\t\t\tlastRole = \"tool\";\n\n\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\tfor (const block of toolCall.result.content) {\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\timageBlocks.push({\n\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\turl: `data:${block.mimeType};base64,${block.data}`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (imageBlocks.length > 0) {\n\t\t\tif (compat.requiresAssistantAfterToolResult) {\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Attached image(s) from tool result:\",\n\t\t\t\t\t},\n\t\t\t\t\t...imageBlocks,\n\t\t\t\t],\n\t\t\t});\n\t\t\tlastRole = \"user\";\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction convertTools(\n\ttools: Message.Tool[],\n\tcompat: Required<Model.OpenAICompletionsCompat>,\n): OpenAI.Chat.Completions.ChatCompletionTool[] {\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters as Record<string, unknown>,\n\t\t\t...(compat.supportsStrictMode !== false && { strict: false }),\n\t\t},\n\t}));\n}\n\nfunction parseChunkUsage(\n\trawUsage: {\n\t\tprompt_tokens?: number;\n\t\tcompletion_tokens?: number;\n\t\tprompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n\t\tcompletion_tokens_details?: { reasoning_tokens?: number };\n\t},\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n): Message.AssistantMessage[\"usage\"] {\n\tconst promptTokens = rawUsage.prompt_tokens || 0;\n\tconst reportedCachedTokens = rawUsage.prompt_tokens_details?.cached_tokens || 0;\n\tconst cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;\n\tconst reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens || 0;\n\n\tconst cacheReadTokens =\n\t\tcacheWriteTokens > 0 ? Math.max(0, reportedCachedTokens - cacheWriteTokens) : reportedCachedTokens;\n\n\tconst input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);\n\tconst outputTokens = (rawUsage.completion_tokens || 0) + reasoningTokens;\n\tconst usage: Message.AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput: outputTokens,\n\t\tcacheRead: cacheReadTokens,\n\t\tcacheWrite: cacheWriteTokens,\n\t\ttotalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tModel.calculateCost(model, usage);\n\treturn usage;\n}\n\nfunction mapStopReason(reason: string | null): {\n\tstopReason: Message.StopReason;\n\terrorMessage?: string;\n} {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\tcase \"end\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"function_call\":\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"content_filter\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: content_filter\" };\n\t\tcase \"network_error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: network_error\" };\n\t\tdefault:\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: `Provider finish_reason: ${reason}`,\n\t\t\t};\n\t}\n}\n\nfunction detectCompat(\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n): Required<Model.OpenAICompletionsCompat> {\n\tconst provider = model.provider.id;\n\tconst baseUrl = resolveBaseUrl(model);\n\n\tconst isZai = provider === \"zai\" || baseUrl.includes(\"api.z.ai\");\n\tconst isNonStandard =\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tbaseUrl.includes(\"deepseek.com\") ||\n\t\tisZai ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\");\n\n\tconst useMaxTokens = baseUrl.includes(\"chutes.ai\");\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isGroq = provider === \"groq\" || baseUrl.includes(\"groq.com\");\n\n\tconst reasoningEffortMap: Partial<Record<OpenAIReasoningEffort, string>> =\n\t\tisGroq && model.id === \"qwen/qwen3-32b\"\n\t\t\t? {\n\t\t\t\t\tminimal: \"default\",\n\t\t\t\t\tlow: \"default\",\n\t\t\t\t\tmedium: \"default\",\n\t\t\t\t\thigh: \"default\",\n\t\t\t\t\txhigh: \"default\",\n\t\t\t\t}\n\t\t\t: {};\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: !isNonStandard,\n\t\tsupportsReasoningEffort: !isGrok && !isZai,\n\t\treasoningEffortMap,\n\t\tsupportsUsageInStreaming: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\tthinkingFormat: isZai\n\t\t\t? \"zai\"\n\t\t\t: provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\")\n\t\t\t\t? \"openrouter\"\n\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: true,\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Uses explicit model.compat if provided, otherwise auto-detects from provider/URL.\n */\nfunction getCompat(\n\tmodel: Model.TModel<typeof Model.KnownProtocolEnum.openaiCompletions>,\n): Required<Model.OpenAICompletionsCompat> {\n\tconst detected = detectCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\treasoningEffortMap: model.compat.reasoningEffortMap ?? detected.reasoningEffortMap,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? {},\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t};\n}\n\nconst openAICompletionsProtocolProvider: Stream.ProtocolProvider<\n\ttypeof Model.KnownProtocolEnum.openaiCompletions,\n\tOpenAICompletionsOptions\n> = {\n\tprotocol: Model.KnownProtocolEnum.openaiCompletions,\n\tstream: streamOpenAICompletions,\n\tstreamSimple: streamSimpleOpenAICompletions,\n};\n\nexport default openAICompletionsProtocolProvider;\n","import anthropicProvider from \"./providers/anthropic/index\";\nimport openAICompletionsProvider from \"./providers/openai/completions\";\nimport { Stream } from \"./stream\";\n\nStream.registerProtocolProvider(anthropicProvider, \"providers/anthropic/index.ts\");\nStream.registerProtocolProvider(openAICompletionsProvider, \"providers/openai/completions.ts\");\n","import { NamedError } from \"@codeworksh/utils\";\nimport { type Static, type TSchema, Type } from \"@sinclair/typebox\";\nimport type { Event } from \"../event/event\";\nimport { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport type { Provider } from \"../provider/provider\";\nimport \"../provider/register\";\nimport { Stream } from \"../provider/stream\";\nimport { Loop } from \"./loop\";\n\nexport namespace Agent {\n\texport const ToolTerminalResultSchema = Type.Union([Message.ToolCompletedSchema, Message.ToolErrorSchema]);\n\texport const ToolResultSchema = Type.Union([\n\t\tMessage.ToolRunningSchema,\n\t\tMessage.ToolCompletedSchema,\n\t\tMessage.ToolErrorSchema,\n\t]);\n\n\texport type ToolRunningResult<T> = Omit<Static<typeof Message.ToolRunningSchema>, \"partial\"> & {\n\t\tpartial?: Omit<Static<typeof Message.ToolRunningPartial>, \"details\"> & {\n\t\t\tdetails?: T;\n\t\t};\n\t};\n\texport type ToolCompletedResult<T> = Omit<Static<typeof Message.ToolCompletedSchema>, \"result\"> & {\n\t\tresult: Omit<Static<typeof Message.ToolSuccessResult>, \"details\"> & {\n\t\t\tdetails?: T;\n\t\t};\n\t};\n\texport type ToolErrorResult<T> = Omit<Static<typeof Message.ToolErrorSchema>, \"result\"> & {\n\t\tresult: Omit<Static<typeof Message.ToolErrorResult>, \"details\"> & {\n\t\t\tdetails?: T;\n\t\t};\n\t};\n\texport type ToolTerminalResult<TCompleted = unknown, TError = unknown> =\n\t\t| ToolCompletedResult<TCompleted>\n\t\t| ToolErrorResult<TError>;\n\ttype InferSchema<T extends TSchema | undefined> = T extends TSchema ? Static<T> : unknown;\n\n\t// callback for tool execution updates.\n\t// consumers can narrow on status if needed\n\t// type inference:\n\t// U - update\n\texport type ToolUpdateCallback<U = unknown> = (result: ToolRunningResult<U>) => Promise<void> | void;\n\n\texport interface AgentTool<\n\t\tTParameters extends TSchema = TSchema,\n\t\tTOutput extends TSchema | undefined = undefined,\n\t\tTUpdate = unknown,\n\t\tTError extends TSchema | undefined = undefined,\n\t> extends Message.Tool<TParameters> {\n\t\t// A human-readable label for the tool for display\n\t\tlabel: string;\n\t\toutputSchema?: TOutput;\n\t\terrorSchema?: TError;\n\t\texecute: (\n\t\t\tcallID: string,\n\t\t\tparams: Static<TParameters>,\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?: ToolUpdateCallback<TUpdate>,\n\t\t) => Promise<ToolTerminalResult<InferSchema<TOutput>, InferSchema<TError>>>;\n\t}\n\n\texport function defineTool<\n\t\tTParameters extends TSchema,\n\t\tTOutput extends TSchema | undefined = undefined,\n\t\tTUpdate = unknown,\n\t\tTError extends TSchema | undefined = undefined,\n\t>(tool: AgentTool<TParameters, TOutput, TUpdate, TError>): AgentTool<TParameters, TOutput, TUpdate, TError> {\n\t\treturn tool;\n\t}\n\n\texport type AnyAgentTool = AgentTool<any, any, any, any>;\n\n\texport interface State {\n\t\tname: string;\n\t\tsystemPrompt: string;\n\t\tmodel: Model.Info;\n\t\tthinkingLevel: Stream.ThinkingLevel;\n\t\ttools: AnyAgentTool[];\n\t\tmessages: Message.Message[];\n\t\tisStreaming: boolean;\n\t\tstreamMessage: Message.Message | null;\n\t\tpendingToolCalls: Set<string>;\n\t\terror?: string;\n\t}\n\n\t// AgentContext is like Message.Context but uses AgentTool\n\t// TODO: @sanchitrk: rename this to Context; Agent.Context\n\texport interface AgentContext {\n\t\tsystemPrompt: string;\n\t\tmessages: Message.Message[];\n\t\ttools?: AnyAgentTool[];\n\t}\n\n\texport const ToolCallInFlightSchema = Type.Object({\n\t\tcallID: Type.String(),\n\t\tname: Type.String(),\n\t\trawArgs: Type.Record(Type.String(), Type.Unknown()),\n\t\targs: Type.Optional(Type.Unknown()), // post validation\n\t});\n\texport type ToolCallInFlight = Static<typeof ToolCallInFlightSchema>;\n\n\texport const ModelNotFoundErr = NamedError.create(\n\t\t\"ModelNotFoundErr\",\n\t\tType.Object({\n\t\t\tmessage: Type.String(),\n\t\t\tprovider: Type.String(),\n\t\t\tmodel: Type.String(),\n\t\t}),\n\t);\n\n\texport const ModelNotConfiguredErr = NamedError.create(\n\t\t\"ModelNotConfiguredErr\",\n\t\tType.Object({\n\t\t\tmessage: Type.String(),\n\t\t}),\n\t);\n\n\texport interface AgentOptions {\n\t\tinitialState?: Partial<State>;\n\t\tconvertToLlm?: (messages: Message.Message[]) => Message.Message[] | Promise<Message.Message[]>;\n\t\t/**\n\t\t * Optional transform applied to the context before `convertToLlm`.\n\t\t *\n\t\t * Use this for operations that work at the AgentMessage level:\n\t\t * - Context window management (pruning old messages)\n\t\t * - Injecting context from external sources\n\t\t *\n\t\t * @example\n\t\t * ```typescript\n\t\t * transformContext: async (messages) => {\n\t\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t\t * return pruneOldMessages(messages);\n\t\t * }\n\t\t * return messages;\n\t\t * }\n\t\t * ```\n\t\t */\n\t\ttransformContext?: (messages: Message.Message[], signal?: AbortSignal) => Promise<Message.Message[]>;\n\t\t/**\n\t\t * Steering mode: \"all\" = send all steering messages at once, \"one-at-a-time\" = one per turn\n\t\t */\n\t\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\n\t\t/**\n\t\t * Follow-up mode: \"all\" = send all follow-up messages at once, \"one-at-a-time\" = one per turn\n\t\t */\n\t\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\t\t/**\n\t\t * Custom stream function (for proxy backends, etc.). Default uses streamSimple.\n\t\t */\n\t\tstreamFn?: Loop.StreamFn;\n\t\t/**\n\t\t * Optional session identifier forwarded to LLM providers.\n\t\t * Used by providers that support session-based caching (e.g., OpenAI Codex).\n\t\t */\n\t\tsessionId?: string;\n\t\t/**\n\t\t * Resolves an API key dynamically for each LLM call.\n\t\t * Useful for expiring tokens (e.g., GitHub Copilot OAuth).\n\t\t */\n\t\tgetApiKey?: (provider: Provider.Info) => Promise<string | undefined> | string | undefined;\n\t\t/**\n\t\t * Inspect or replace provider payloads before they are sent.\n\t\t */\n\t\tonPayload?: Stream.SimpleOptions[\"onPayload\"];\n\t\t/**\n\t\t * Custom token budgets for thinking levels (token-based providers only).\n\t\t */\n\t\tthinkingBudgets?: Stream.ThinkingBudgets;\n\t\t/**\n\t\t * Preferred transport for providers that support multiple transports.\n\t\t */\n\t\ttransport?: Stream.Transport;\n\t\t/**\n\t\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t\t * If the server's requested delay exceeds this value, the request fails immediately,\n\t\t * allowing higher-level retry logic to handle it with user visibility.\n\t\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t\t */\n\t\tmaxRetryDelayMs?: number;\n\t\t/** Tool execution mode. Default: \"parallel\" */\n\t\ttoolExecution?: Loop.ToolExecutionMode;\n\t\t/** Called before a tool is executed, after arguments have been validated. */\n\t\tbeforeToolExecution?: (\n\t\t\tcontext: Loop.BeforeToolExecutionContext,\n\t\t\tsignal?: AbortSignal,\n\t\t) => Promise<Loop.BeforeToolCallResult | undefined>;\n\t\t/** Called after a tool finishes executing, before final tool events are emitted. */\n\t\tafterToolExecution?: (\n\t\t\tcontext: Loop.AfterToolExecutionContext,\n\t\t\tsignal?: AbortSignal,\n\t\t) => Promise<Agent.ToolTerminalResult<unknown> | undefined>;\n\t}\n\n\texport const AgentInStreamingErr = NamedError.create(\n\t\t\"AgentInStreamingErr\",\n\t\tType.Object({\n\t\t\tmessage: Type.String(),\n\t\t\tname: Type.String(),\n\t\t}),\n\t);\n\n\texport class Instance {\n\t\tprivate _state: State;\n\n\t\tprivate listeners = new Set<(e: Event.AgentEvent) => void>();\n\t\tprivate abortController?: AbortController;\n\n\t\tprivate convertToLlm: (messages: Message.Message[]) => Message.Message[] | Promise<Message.Message[]>;\n\t\tprivate transformContext?: (messages: Message.Message[], signal?: AbortSignal) => Promise<Message.Message[]>;\n\n\t\tprivate steeringQueue: Message.UserMessage[] = [];\n\t\tprivate followUpQueue: Message.UserMessage[] = [];\n\t\tprivate steeringMode: \"all\" | \"one-at-a-time\";\n\t\tprivate followUpMode: \"all\" | \"one-at-a-time\";\n\n\t\tpublic streamFn: Loop.StreamFn;\n\n\t\tprivate _sessionId?: string;\n\t\tpublic getApiKey?: (provider: Provider.Info) => Promise<string | undefined> | string | undefined;\n\n\t\tprivate _onPayload?: Stream.SimpleOptions[\"onPayload\"];\n\n\t\tprivate runningPrompt?: Promise<void>;\n\t\tprivate resolveRunningPrompt?: () => void;\n\t\tprivate _thinkingBudgets?: Stream.ThinkingBudgets;\n\t\tprivate _transport: Stream.Transport;\n\t\tprivate _maxRetryDelayMs?: number;\n\t\tprivate _toolExecution: Loop.ToolExecutionMode;\n\n\t\tprivate _beforeToolExecution?: (\n\t\t\tcontext: Loop.BeforeToolExecutionContext,\n\t\t\tsignal?: AbortSignal,\n\t\t) => Promise<Loop.BeforeToolCallResult | undefined>;\n\t\tprivate _afterToolExecution?: (\n\t\t\tcontext: Loop.AfterToolExecutionContext,\n\t\t\tsignal?: AbortSignal,\n\t\t) => Promise<Agent.ToolTerminalResult<unknown> | undefined>;\n\n\t\tconstructor(name: string, model: Model.Info, opts: AgentOptions = {}) {\n\t\t\tthis._state = {\n\t\t\t\tsystemPrompt: \"\",\n\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\ttools: [],\n\t\t\t\tmessages: [],\n\t\t\t\tisStreaming: false,\n\t\t\t\tstreamMessage: null,\n\t\t\t\tpendingToolCalls: new Set<string>(),\n\t\t\t\terror: undefined,\n\t\t\t\t...opts.initialState,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t};\n\t\t\t/**\n\t\t\t * Transformation logic to prepare messages for the LLM.\n\t\t\t * * @remarks\n\t\t\t * Currently just forwards messages as-is. Modify this logic when\n\t\t\t * specific formatting or filtering is required.\n\t\t\t * A good example is using user message parts with custom content\n\t\t\t * * @default\n\t\t\t * forwards messages as is.\n\t\t\t */\n\t\t\tthis.convertToLlm = opts.convertToLlm || ((messages: Message.Message[]) => messages);\n\t\t\tthis.transformContext = opts.transformContext;\n\n\t\t\tthis.steeringMode = opts.steeringMode || \"one-at-a-time\";\n\t\t\tthis.followUpMode = opts.followUpMode || \"one-at-a-time\";\n\n\t\t\tthis.streamFn = opts.streamFn || Stream.streamSimple;\n\t\t\tthis._sessionId = opts.sessionId;\n\n\t\t\tthis.getApiKey = opts.getApiKey;\n\t\t\tthis._onPayload = opts.onPayload;\n\n\t\t\tthis._thinkingBudgets = opts.thinkingBudgets;\n\t\t\tthis._transport = opts.transport ?? \"sse\";\n\t\t\tthis._maxRetryDelayMs = opts.maxRetryDelayMs;\n\n\t\t\tthis._toolExecution = opts.toolExecution ?? \"parallel\";\n\t\t\tthis._beforeToolExecution = opts.beforeToolExecution;\n\t\t\tthis._afterToolExecution = opts.afterToolExecution;\n\t\t}\n\n\t\t/**\n\t\t * Get the current session ID used for provider caching.\n\t\t */\n\t\tget sessionId(): string | undefined {\n\t\t\treturn this._sessionId;\n\t\t}\n\n\t\t/**\n\t\t * Set the session ID for provider caching.\n\t\t * Call this when switching sessions (new session, branch, resume, etc).\n\t\t */\n\t\tset sessionId(value: string | undefined) {\n\t\t\tthis._sessionId = value;\n\t\t}\n\t\t/**\n\t\t * Get the current thinking budgets.\n\t\t */\n\t\tget thinkingBudgets(): Stream.ThinkingBudgets | undefined {\n\t\t\treturn this._thinkingBudgets;\n\t\t}\n\t\t/**\n\t\t * Set custom thinking budgets for token-based providers.\n\t\t */\n\t\tset thinkingBudgets(value: Stream.ThinkingBudgets | undefined) {\n\t\t\tthis._thinkingBudgets = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the current preferred transport.\n\t\t */\n\t\tget transport(): Stream.Transport {\n\t\t\treturn this._transport;\n\t\t}\n\t\t/**\n\t\t * Set the preferred transport.\n\t\t */\n\t\tsetTransport(value: Stream.Transport) {\n\t\t\tthis._transport = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the current max retry delay in milliseconds.\n\t\t */\n\t\tget maxRetryDelayMs(): number | undefined {\n\t\t\treturn this._maxRetryDelayMs;\n\t\t}\n\n\t\t/**\n\t\t * Set the maximum delay to wait for server-requested retries.\n\t\t * Set to 0 to disable the cap.\n\t\t */\n\t\tset maxRetryDelayMs(value: number | undefined) {\n\t\t\tthis._maxRetryDelayMs = value;\n\t\t}\n\n\t\tget toolExecution(): Loop.ToolExecutionMode {\n\t\t\treturn this._toolExecution;\n\t\t}\n\n\t\tsetToolExecution(value: Loop.ToolExecutionMode) {\n\t\t\tthis._toolExecution = value;\n\t\t}\n\n\t\tsetBeforeToolExecution(\n\t\t\tvalue:\n\t\t\t\t| ((\n\t\t\t\t\t\tcontext: Loop.BeforeToolExecutionContext,\n\t\t\t\t\t\tsignal?: AbortSignal,\n\t\t\t\t ) => Promise<Loop.BeforeToolCallResult | undefined>)\n\t\t\t\t| undefined,\n\t\t) {\n\t\t\tthis._beforeToolExecution = value;\n\t\t}\n\n\t\tsetAfterToolExecution(\n\t\t\tvalue:\n\t\t\t\t| ((\n\t\t\t\t\t\tcontext: Loop.AfterToolExecutionContext,\n\t\t\t\t\t\tsignal?: AbortSignal,\n\t\t\t\t ) => Promise<Agent.ToolTerminalResult<unknown> | undefined>)\n\t\t\t\t| undefined,\n\t\t) {\n\t\t\tthis._afterToolExecution = value;\n\t\t}\n\n\t\tget state(): State {\n\t\t\treturn this._state;\n\t\t}\n\n\t\tsubscribe(fn: (e: Event.AgentEvent) => void): () => void {\n\t\t\tthis.listeners.add(fn);\n\t\t\treturn () => this.listeners.delete(fn);\n\t\t}\n\n\t\t// State mutators\n\t\tsetSystemPrompt(v: string) {\n\t\t\tthis._state.systemPrompt = v;\n\t\t}\n\t\tsetModel(m: Model.Info) {\n\t\t\tthis._state.model = m;\n\t\t}\n\t\tsetThinkingLevel(l: Stream.ThinkingLevel) {\n\t\t\tthis._state.thinkingLevel = l;\n\t\t}\n\t\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\") {\n\t\t\tthis.steeringMode = mode;\n\t\t}\n\n\t\tgetSteeringMode(): \"all\" | \"one-at-a-time\" {\n\t\t\treturn this.steeringMode;\n\t\t}\n\n\t\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\") {\n\t\t\tthis.followUpMode = mode;\n\t\t}\n\n\t\tgetFollowUpMode(): \"all\" | \"one-at-a-time\" {\n\t\t\treturn this.followUpMode;\n\t\t}\n\n\t\tsetTools(t: AgentTool<any>[]) {\n\t\t\tthis._state.tools = t;\n\t\t}\n\n\t\treplaceMessages(ms: Message.Message[]) {\n\t\t\tthis._state.messages = ms.slice();\n\t\t}\n\n\t\tappendMessage(m: Message.Message) {\n\t\t\tthis._state.messages = [...this._state.messages, m];\n\t\t}\n\n\t\tprivate findMessageIndexById(messageId: string): number {\n\t\t\treturn this._state.messages.findIndex((message) => message.messageId === messageId);\n\t\t}\n\n\t\tprivate replaceMessageById(message: Message.Message): boolean {\n\t\t\tconst messageIndex = this.findMessageIndexById(message.messageId);\n\t\t\tif (messageIndex === -1) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tconst messages = this._state.messages.slice();\n\t\t\tmessages[messageIndex] = message;\n\t\t\tthis._state.messages = messages;\n\t\t\treturn true;\n\t\t}\n\n\t\tprivate upsertMessage(message: Message.Message): void {\n\t\t\tif (this.replaceMessageById(message)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.appendMessage(message);\n\t\t}\n\n\t\tprivate patchStoredAssistantPart(\n\t\t\tmessageId: string,\n\t\t\tpartIndex: number,\n\t\t\tpart: Message.AssistantMessage[\"parts\"][number],\n\t\t): boolean {\n\t\t\tconst messageIndex = this.findMessageIndexById(messageId);\n\t\t\tif (messageIndex === -1) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tconst messages = this._state.messages.slice();\n\t\t\tconst existing = messages[messageIndex];\n\t\t\tif (!existing || existing.role !== \"assistant\") {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tconst nextParts = existing.parts.slice();\n\t\t\tnextParts[partIndex] = part;\n\t\t\tmessages[messageIndex] = {\n\t\t\t\t...existing,\n\t\t\t\tparts: nextParts,\n\t\t\t};\n\t\t\tthis._state.messages = messages;\n\t\t\treturn true;\n\t\t}\n\n\t\t/**\n\t\t * Queue a steering message while the agent is running.\n\t\t * Delivered after the current assistant turn finishes executing its tool calls,\n\t\t * before the next LLM call.\n\t\t */\n\t\tsteer(m: Message.UserMessage) {\n\t\t\tthis.steeringQueue.push(m);\n\t\t}\n\n\t\t/**\n\t\t * Queue a follow-up message to be processed after the agent finishes.\n\t\t * Delivered only when agent has no more tool calls or steering messages.\n\t\t */\n\t\tfollowUp(m: Message.UserMessage) {\n\t\t\tthis.followUpQueue.push(m);\n\t\t}\n\n\t\tclearSteeringQueue() {\n\t\t\tthis.steeringQueue = [];\n\t\t}\n\n\t\tclearFollowUpQueue() {\n\t\t\tthis.followUpQueue = [];\n\t\t}\n\n\t\tclearAllQueues() {\n\t\t\tthis.steeringQueue = [];\n\t\t\tthis.followUpQueue = [];\n\t\t}\n\n\t\thasQueuedMessages(): boolean {\n\t\t\treturn this.steeringQueue.length > 0 || this.followUpQueue.length > 0;\n\t\t}\n\n\t\tprivate dequeueSteeringMessages(): Message.UserMessage[] {\n\t\t\tif (this.steeringMode === \"one-at-a-time\") {\n\t\t\t\tif (this.steeringQueue.length > 0) {\n\t\t\t\t\tconst first = this.steeringQueue[0]!;\n\t\t\t\t\tthis.steeringQueue = this.steeringQueue.slice(1);\n\t\t\t\t\treturn [first];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t}\n\n\t\t\tconst steering = this.steeringQueue.slice();\n\t\t\tthis.steeringQueue = [];\n\t\t\treturn steering;\n\t\t}\n\n\t\tprivate dequeueFollowUpMessages(): Message.UserMessage[] {\n\t\t\tif (this.followUpMode === \"one-at-a-time\") {\n\t\t\t\tif (this.followUpQueue.length > 0) {\n\t\t\t\t\tconst first = this.followUpQueue[0]!;\n\t\t\t\t\tthis.followUpQueue = this.followUpQueue.slice(1);\n\t\t\t\t\treturn [first];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t}\n\n\t\t\tconst followUp = this.followUpQueue.slice();\n\t\t\tthis.followUpQueue = [];\n\t\t\treturn followUp;\n\t\t}\n\n\t\tclearMessages() {\n\t\t\tthis._state.messages = [];\n\t\t}\n\n\t\tabort() {\n\t\t\tthis.abortController?.abort();\n\t\t}\n\n\t\twaitForIdle(): Promise<void> {\n\t\t\treturn this.runningPrompt ?? Promise.resolve();\n\t\t}\n\n\t\treset() {\n\t\t\tthis._state.messages = [];\n\t\t\tthis._state.isStreaming = false;\n\t\t\tthis._state.streamMessage = null;\n\t\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\t\tthis._state.error = undefined;\n\t\t\tthis.steeringQueue = [];\n\t\t\tthis.followUpQueue = [];\n\t\t}\n\n\t\tgetName(): string {\n\t\t\treturn this._state.name;\n\t\t}\n\n\t\tprivate ensureIdle() {\n\t\t\tif (this._state.isStreaming) {\n\t\t\t\tthrow new AgentInStreamingErr({\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"agent is already processing a prompt. Use steer() or followup() to queue messages, or wait for completion.\",\n\t\t\t\t\tname: this._state.name,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tprivate async _runLoop(messages?: Message.UserMessage[], opts?: { skipInitialSteeringPoll?: boolean }) {\n\t\t\tconst model = this._state.model;\n\t\t\tif (!model)\n\t\t\t\tthrow new ModelNotConfiguredErr({\n\t\t\t\t\tmessage: \"no model configured yet\",\n\t\t\t\t});\n\n\t\t\tthis.runningPrompt = new Promise<void>((resolve) => {\n\t\t\t\tthis.resolveRunningPrompt = resolve;\n\t\t\t});\n\n\t\t\tthis.abortController = new AbortController();\n\t\t\tthis._state.isStreaming = true;\n\t\t\tthis._state.streamMessage = null;\n\t\t\tthis._state.error = undefined;\n\n\t\t\tconst reasoning = this.state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel;\n\n\t\t\tconst context: Agent.AgentContext = {\n\t\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\t\tmessages: this._state.messages.slice(),\n\t\t\t\ttools: this._state.tools,\n\t\t\t};\n\n\t\t\tlet skipInitialSteeringPoll = opts?.skipInitialSteeringPoll === true;\n\n\t\t\tconst config: Loop.Config = {\n\t\t\t\tmodel,\n\t\t\t\treasoning,\n\t\t\t\tsessionId: this._sessionId,\n\t\t\t\tonPayload: this._onPayload,\n\t\t\t\ttransport: this._transport,\n\t\t\t\tthinkingBudgets: this._thinkingBudgets,\n\t\t\t\tmaxRetryDelayMs: this._maxRetryDelayMs,\n\t\t\t\ttoolExecution: this._toolExecution,\n\t\t\t\tbeforeToolExecution: this._beforeToolExecution,\n\t\t\t\tafterToolExecution: this._afterToolExecution,\n\t\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\t\ttransformContext: this.transformContext,\n\t\t\t\tgetApiKey: this.getApiKey,\n\t\t\t\tgetSteeringMessages: async () => {\n\t\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\t\treturn [];\n\t\t\t\t\t}\n\t\t\t\t\treturn this.dequeueSteeringMessages();\n\t\t\t\t},\n\t\t\t\tgetFollowUpMessages: async () => this.dequeueFollowUpMessages(),\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tif (messages) {\n\t\t\t\t\tawait Loop.runAgentLoop(\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tasync (e) => this._processLoopEvent(e),\n\t\t\t\t\t\tthis.streamFn,\n\t\t\t\t\t\tthis.abortController.signal,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tawait Loop.runAgentLoopContinue(\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\tasync (e) => this._processLoopEvent(e),\n\t\t\t\t\t\tthis.streamFn,\n\t\t\t\t\t\tthis.abortController.signal,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err: any) {\n\t\t\t\tconst message = Message.createAssistantMessage({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tprotocol: model.protocol,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.id,\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t\tstopReason: this.abortController.signal.aborted ? \"aborted\" : \"error\",\n\t\t\t\t\terrorMessage: err?.message || String(err),\n\t\t\t\t\ttime: {\n\t\t\t\t\t\tcreated: Date.now(),\n\t\t\t\t\t\tcompleted: Date.now(),\n\t\t\t\t\t},\n\t\t\t\t\tparts: [],\n\t\t\t\t});\n\n\t\t\t\tthis.appendMessage(message);\n\t\t\t\tthis._state.error = err?.message || String(err);\n\t\t\t\tthis.emit({ type: \"agent.end\", messages: [message] });\n\t\t\t} finally {\n\t\t\t\tthis._state.isStreaming = false;\n\t\t\t\tthis._state.streamMessage = null;\n\t\t\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\t\t\tthis.abortController = undefined;\n\t\t\t\tthis.resolveRunningPrompt?.();\n\t\t\t\tthis.runningPrompt = undefined;\n\t\t\t\tthis.resolveRunningPrompt = undefined;\n\t\t\t}\n\t\t}\n\n\t\tasync loop(messages: Message.UserMessage[]): Promise<void> {\n\t\t\tthis.ensureIdle();\n\t\t\tawait this._runLoop(messages);\n\t\t}\n\n\t\tasync loopContinue(): Promise<void> {\n\t\t\tthis.ensureIdle();\n\t\t\tawait this._runLoop();\n\t\t}\n\n\t\tasync prompt(messages: Message.TextContent[], images?: Message.ImageContent[]): Promise<void> {\n\t\t\tthis.ensureIdle();\n\t\t\tconst model = this._state.model;\n\t\t\tif (!model)\n\t\t\t\tthrow new ModelNotConfiguredErr({\n\t\t\t\t\tmessage: \"no model configured yet.\",\n\t\t\t\t});\n\n\t\t\tconst message = Message.createUserMessage({\n\t\t\t\trole: \"user\",\n\t\t\t\ttime: {\n\t\t\t\t\tcreated: Date.now(),\n\t\t\t\t},\n\t\t\t\tparts: [...messages, ...(images ?? [])],\n\t\t\t});\n\n\t\t\tawait this.loop([message]);\n\t\t}\n\n\t\tprivate _processLoopEvent(event: Event.AgentEvent): void {\n\t\t\tswitch (event.type) {\n\t\t\t\tcase \"message.start\": {\n\t\t\t\t\tthis._state.streamMessage = event.message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"message.part.start\":\n\t\t\t\tcase \"message.part.update\":\n\t\t\t\tcase \"message.part.end\": {\n\t\t\t\t\tthis._state.streamMessage = event.message;\n\t\t\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\t\t\tthis.patchStoredAssistantPart(event.message.messageId, event.partIndex, event.part);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"message.update\":\n\t\t\t\t\tthis._state.streamMessage = event.message;\n\t\t\t\t\tthis.replaceMessageById(event.message);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"message.end\":\n\t\t\t\t\tthis._state.streamMessage = null;\n\t\t\t\t\tthis.upsertMessage(event.message);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool.execution.start\": {\n\t\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\t\tpendingToolCalls.add(event.callID);\n\t\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool.execution.end\": {\n\t\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\t\tpendingToolCalls.delete(event.callID);\n\t\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"turn.end\":\n\t\t\t\t\tif (event.message.role === \"assistant\" && event.message.parts.length > 0) {\n\t\t\t\t\t\tthis._state.error = event.message.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"agent.end\":\n\t\t\t\t\tthis._state.isStreaming = false;\n\t\t\t\t\tthis._state.streamMessage = null;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tthis.emit(event);\n\t\t}\n\n\t\tprivate emit(e: Event.AgentEvent) {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tlistener(e);\n\t\t\t}\n\t\t}\n\t}\n\n\texport async function create<TProvider extends Provider.KnownProvider, TModel extends Model.Info[\"id\"]>(\n\t\toptions: AgentOptions & {\n\t\t\tprovider: TProvider;\n\t\t\tmodel: TModel;\n\t\t\tname?: string;\n\t\t},\n\t): Promise<Instance>;\n\texport async function create(options: AgentOptions & { model: Model.Info; name?: string }): Promise<Instance>;\n\texport async function create(\n\t\toptions:\n\t\t\t| (AgentOptions & { model: Model.Info; name?: string })\n\t\t\t| (AgentOptions & {\n\t\t\t\t\tprovider: Provider.KnownProvider;\n\t\t\t\t\tmodel: Model.Info[\"id\"];\n\t\t\t\t\tname?: string;\n\t\t\t }),\n\t): Promise<Instance> {\n\t\tlet resolvedModel: Model.Info;\n\t\tif (\"provider\" in options) {\n\t\t\tconst result = await Model.getModel(options.provider, options.model);\n\t\t\tif (!result) {\n\t\t\t\tthrow new ModelNotFoundErr({\n\t\t\t\t\tmessage: \"model not found or not configured yet\",\n\t\t\t\t\tprovider: options.provider,\n\t\t\t\t\tmodel: options.model,\n\t\t\t\t});\n\t\t\t}\n\t\t\tresolvedModel = result;\n\t\t} else {\n\t\t\tresolvedModel = options.model;\n\t\t}\n\n\t\treturn new Instance(options.name ?? \"main\", resolvedModel, options);\n\t}\n}\n","import { NamedError } from \"@codeworksh/utils\";\nimport { type Static, type TSchema, Type, TypeGuard } from \"@sinclair/typebox\";\nimport { transform } from \"esbuild\";\nimport { capitalize } from \"remeda\";\nimport { validateSchema } from \"../../utils/validation\";\nimport { Agent } from \"../agent\";\n\nexport namespace CodeMode {\n\texport const ToolDefinitionErr = NamedError.create(\n\t\t\"ToolDefinitionErr\",\n\t\tType.Object({\n\t\t\tmessage: Type.String(),\n\t\t}),\n\t);\n\n\tconst toolFnPrefix = process.env.CODEWORK_CODEMODE_FN_PREFIX ?? \"external_\";\n\n\texport const SandboxExecutionInputSchema = Type.Object({\n\t\ttypescriptCode: Type.String({\n\t\t\tdescription: \"TypeScript code to execute in the sandbox.\",\n\t\t}),\n\t});\n\texport type SandboxExecutionInput = Static<typeof SandboxExecutionInputSchema>;\n\n\texport const SandboxExecutionOutputSchema = Type.Object({\n\t\tresult: Type.Optional(Type.Unknown()),\n\t\tlogs: Type.Optional(Type.Array(Type.String())),\n\t});\n\texport type SandboxExecutionOutput = Static<typeof SandboxExecutionOutputSchema>;\n\n\texport const SandboxExecutionErrorSchema = Type.Object({\n\t\tmessage: Type.String(),\n\t\tname: Type.Optional(Type.String()),\n\t\tstack: Type.Optional(Type.String()),\n\t\tline: Type.Optional(Type.Number()),\n\t\tlogs: Type.Optional(Type.Array(Type.String())),\n\t});\n\texport type SandboxExecutionError = Static<typeof SandboxExecutionErrorSchema>;\n\n\texport interface NormalizedError {\n\t\tmessage: string;\n\t\tname?: string;\n\t\tstack?: string;\n\t\tline?: number;\n\t}\n\n\texport interface ExecutionResult<T = unknown> {\n\t\tsuccess: boolean;\n\t\tvalue?: T;\n\t\tlogs?: string[];\n\t\terror?: NormalizedError;\n\t}\n\n\texport interface Context {\n\t\texecute: <T = unknown>(code: string) => Promise<ExecutionResult<T>>;\n\t\tdispose: () => Promise<void>;\n\t}\n\n\texport interface DriverContextConfig {\n\t\tbindings: Record<string, ToolBinding>;\n\t\ttimeout?: number;\n\t\tmemoryLimit?: number;\n\t\tsignal?: AbortSignal;\n\t}\n\n\texport interface Driver {\n\t\tcreateContext: (config: DriverContextConfig) => Promise<Context>;\n\t}\n\n\texport interface ToolConfig {\n\t\t/**\n\t\t * Driver for sandbox code execution\n\t\t */\n\t\tdriver: Driver;\n\t\t/**\n\t\t * Tools to expose for functions in sandbox\n\t\t */\n\t\ttools: Agent.AnyAgentTool[];\n\t\t/**\n\t\t * Execution timeout in milliseconds (default: 30000)\n\t\t */\n\t\ttimeout?: number;\n\t\t/**\n\t\t * Memory limit in MB for sandbox (default: 128)\n\t\t */\n\t\tmemoryLimit?: number;\n\t\t/**\n\t\t * Tool function prefix.\n\t\t * @default env.CODEWORK_CODEMODE_FN_PREFIX ?? \"external_\"\n\t\t */\n\t\tfnPrefix?: string;\n\t}\n\n\texport interface ToolBinding {\n\t\tname: string;\n\t\tdescription: string;\n\t\tinputSchema: TSchema;\n\t\toutputSchema?: TSchema;\n\t\terrorSchema?: TSchema;\n\t\texecute: (callID: string, params: unknown, signal?: AbortSignal) => Promise<unknown>;\n\t}\n\n\t/**\n\t * Options for type stub generation\n\t */\n\texport interface TypeGeneratorOptions {\n\t\t/**\n\t\t * Include JSDoc comments with descriptions\n\t\t * @default true\n\t\t */\n\t\tincludeDescriptions?: boolean;\n\t}\n\n\tfunction withMessageInStack(message: string, stack: string | undefined): string | undefined {\n\t\tif (!stack) return undefined;\n\t\treturn stack.includes(message) ? stack : `${message}\\n${stack}`;\n\t}\n\n\tfunction normalizeExecutionError(error: unknown): NormalizedError {\n\t\tif (error instanceof Error) {\n\t\t\treturn {\n\t\t\t\tname: error.name,\n\t\t\t\tmessage: error.message,\n\t\t\t\tstack: withMessageInStack(error.message, error.stack),\n\t\t\t\tline: parseErrorLine(error.stack),\n\t\t\t};\n\t\t}\n\n\t\tif (typeof error === \"object\" && error !== null) {\n\t\t\tconst candidate = error as Record<string, unknown>;\n\t\t\treturn {\n\t\t\t\tname: typeof candidate.name === \"string\" ? candidate.name : undefined,\n\t\t\t\tmessage:\n\t\t\t\t\ttypeof candidate.message === \"string\"\n\t\t\t\t\t\t? candidate.message\n\t\t\t\t\t\t: JSON.stringify(candidate) || \"Unknown execution error\",\n\t\t\t\tstack:\n\t\t\t\t\ttypeof candidate.stack === \"string\"\n\t\t\t\t\t\t? withMessageInStack(\n\t\t\t\t\t\t\t\ttypeof candidate.message === \"string\"\n\t\t\t\t\t\t\t\t\t? candidate.message\n\t\t\t\t\t\t\t\t\t: JSON.stringify(candidate) || \"Unknown execution error\",\n\t\t\t\t\t\t\t\tcandidate.stack,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined,\n\t\t\t\tline: typeof candidate.line === \"number\" ? candidate.line : parseErrorLine(candidate.stack),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tname: \"Error\",\n\t\t\tmessage: String(error),\n\t\t};\n\t}\n\n\tfunction parseErrorLine(stack: unknown): number | undefined {\n\t\tif (typeof stack !== \"string\") return undefined;\n\t\tconst lineMatch = stack.match(/:(\\d+)(?::\\d+)?\\)?$/m);\n\t\treturn lineMatch ? Number(lineMatch[1]) : undefined;\n\t}\n\n\tfunction serializeForContent(value: unknown): string {\n\t\treturn JSON.stringify(\n\t\t\tvalue,\n\t\t\t(_key, currentValue) => (typeof currentValue === \"bigint\" ? currentValue.toString() : currentValue),\n\t\t\t2,\n\t\t);\n\t}\n\n\tfunction toolContentToText(result: { content: Array<{ type: string; text?: string }> }): string {\n\t\tconst parts = result.content\n\t\t\t.filter((part) => part.type === \"text\" && typeof part.text === \"string\")\n\t\t\t.map((part) => part.text);\n\t\treturn parts.join(\"\\n\").trim();\n\t}\n\n\tfunction unwrapToolResult(tool: Agent.AnyAgentTool, result: Agent.ToolTerminalResult<unknown, unknown>): unknown {\n\t\tif (result.status === \"completed\") {\n\t\t\tif (tool.outputSchema) {\n\t\t\t\treturn validateSchema(tool.outputSchema, result.result.details, `Tool \"${tool.name}\" output`);\n\t\t\t}\n\t\t\treturn result.result.details;\n\t\t}\n\n\t\tif (tool.errorSchema && result.result.details !== undefined) {\n\t\t\tvalidateSchema(tool.errorSchema, result.result.details, `Tool \"${tool.name}\" error`);\n\t\t}\n\n\t\tconst message = toolContentToText(result.result) || `Tool \"${tool.name}\" failed`;\n\t\tconst error = new Error(message);\n\t\tif (result.result.details !== undefined) {\n\t\t\t(error as Error & { cause?: unknown }).cause = result.result.details;\n\t\t}\n\t\tthrow error;\n\t}\n\n\tfunction toolToBinding(tool: Agent.AnyAgentTool, prefix: string = \"\"): ToolBinding {\n\t\tconst inputSchema = TypeGuard.IsSchema(tool.parameters) ? tool.parameters : Type.Object({});\n\t\tconst outputSchema = TypeGuard.IsSchema(tool.outputSchema) ? tool.outputSchema : undefined;\n\t\tconst errorSchema = TypeGuard.IsSchema(tool.errorSchema) ? tool.errorSchema : undefined;\n\n\t\tif (!(\"execute\" in tool) || typeof tool.execute !== \"function\") {\n\t\t\tthrow new ToolDefinitionErr({\n\t\t\t\tmessage: `tool \"${tool.name}\" does not have an execute function. code mode requires tools with implementation`,\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\tname: `${prefix}${tool.name}`,\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema,\n\t\t\toutputSchema,\n\t\t\terrorSchema,\n\t\t\texecute: async (callID: string, params: unknown, signal?: AbortSignal) => {\n\t\t\t\tconst validatedParams = validateSchema(inputSchema, params, `Tool \"${tool.name}\" input`);\n\t\t\t\tconst terminalResult = await tool.execute(callID, validatedParams, signal);\n\t\t\t\treturn unwrapToolResult(tool, terminalResult);\n\t\t\t},\n\t\t};\n\t}\n\n\tfunction toolsForBinding(tools: Agent.AnyAgentTool[], prefix: string): Record<string, ToolBinding> {\n\t\tconst bindings: Record<string, ToolBinding> = {};\n\n\t\tfor (const tool of tools) {\n\t\t\tconst name = `${prefix}${tool.name}`;\n\t\t\tbindings[name] = toolToBinding(tool, prefix);\n\t\t}\n\n\t\treturn bindings;\n\t}\n\n\tfunction indent(value: string, depth: number = 1): string {\n\t\tconst prefix = \"\\t\".repeat(depth);\n\t\treturn value\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => `${prefix}${line}`)\n\t\t\t.join(\"\\n\");\n\t}\n\n\tfunction toPropertyKey(name: string): string {\n\t\treturn /^[$A-Z_a-z][$\\w]*$/i.test(name) ? name : JSON.stringify(name);\n\t}\n\n\tfunction schemaToTypeScript(schema: TSchema): string {\n\t\tif (TypeGuard.IsAny(schema)) return \"any\";\n\t\tif (TypeGuard.IsUnknown(schema)) return \"unknown\";\n\t\tif (TypeGuard.IsString(schema)) return \"string\";\n\t\tif (TypeGuard.IsNumber(schema) || TypeGuard.IsInteger(schema)) return \"number\";\n\t\tif (TypeGuard.IsBoolean(schema)) return \"boolean\";\n\t\tif (TypeGuard.IsNull(schema)) return \"null\";\n\t\tif (TypeGuard.IsUndefined(schema) || TypeGuard.IsVoid(schema)) return \"undefined\";\n\t\tif (TypeGuard.IsLiteral(schema)) return JSON.stringify(schema.const);\n\n\t\tif (TypeGuard.IsArray(schema)) {\n\t\t\treturn `Array<${schemaToTypeScript(schema.items)}>`;\n\t\t}\n\n\t\tif (TypeGuard.IsTuple(schema)) {\n\t\t\tconst items = schema.items ?? [];\n\t\t\treturn `[${items.map((item) => schemaToTypeScript(item)).join(\", \")}]`;\n\t\t}\n\n\t\tif (TypeGuard.IsUnion(schema)) {\n\t\t\treturn schema.anyOf.map((item) => schemaToTypeScript(item)).join(\" | \");\n\t\t}\n\n\t\tif (TypeGuard.IsIntersect(schema)) {\n\t\t\treturn schema.allOf.map((item) => schemaToTypeScript(item)).join(\" & \");\n\t\t}\n\n\t\tif (TypeGuard.IsRecord(schema)) {\n\t\t\tconst valueSchema =\n\t\t\t\tObject.values(schema.patternProperties ?? {}).find(TypeGuard.IsSchema) ??\n\t\t\t\t(schema.additionalProperties && TypeGuard.IsSchema(schema.additionalProperties)\n\t\t\t\t\t? schema.additionalProperties\n\t\t\t\t\t: Type.Unknown());\n\t\t\treturn `Record<string, ${schemaToTypeScript(valueSchema)}>`;\n\t\t}\n\n\t\tif (TypeGuard.IsObject(schema)) {\n\t\t\tconst required = new Set(schema.required ?? []);\n\t\t\tconst properties = Object.entries(schema.properties ?? {}).map(([key, value]) => {\n\t\t\t\tconst optional = required.has(key) ? \"\" : \"?\";\n\t\t\t\treturn `${toPropertyKey(key)}${optional}: ${schemaToTypeScript(value)};`;\n\t\t\t});\n\n\t\t\tif (schema.additionalProperties === true) {\n\t\t\t\tproperties.push(\"[key: string]: unknown;\");\n\t\t\t} else if (schema.additionalProperties && TypeGuard.IsSchema(schema.additionalProperties)) {\n\t\t\t\tproperties.push(`[key: string]: ${schemaToTypeScript(schema.additionalProperties)};`);\n\t\t\t}\n\n\t\t\tif (properties.length === 0) return \"{}\";\n\n\t\t\treturn `{\\n${indent(properties.join(\"\\n\"))}\\n}`;\n\t\t}\n\n\t\treturn \"unknown\";\n\t}\n\n\t/**\n\t * Generate TypeScript type stubs for all tool bindings.\n\t *\n\t * These stubs are included in the LLM system prompt so it knows the exact\n\t * type signatures of available tools.\n\t */\n\texport function generateTypeStubs(\n\t\tbindings: Record<string, ToolBinding>,\n\t\toptions: TypeGeneratorOptions = {},\n\t): string {\n\t\tconst { includeDescriptions = true } = options;\n\t\tconst declarations: string[] = [];\n\n\t\tfor (const [name, binding] of Object.entries(bindings)) {\n\t\t\tconst inputTypeName = `${capitalize(name)}Input`;\n\t\t\tconst outputTypeName = `${capitalize(name)}Output`;\n\n\t\t\tdeclarations.push(`type ${inputTypeName} = ${schemaToTypeScript(binding.inputSchema)};`);\n\n\t\t\tlet outputTypeRef = \"unknown\";\n\t\t\tif (binding.outputSchema !== undefined) {\n\t\t\t\tdeclarations.push(`type ${outputTypeName} = ${schemaToTypeScript(binding.outputSchema)};`);\n\t\t\t\toutputTypeRef = outputTypeName;\n\t\t\t}\n\n\t\t\tconst description = includeDescriptions && binding.description ? `/** ${binding.description} */\\n` : \"\";\n\t\t\tdeclarations.push(\n\t\t\t\t`${description}declare function ${name}(input: ${inputTypeName}): Promise<${outputTypeRef}>;`,\n\t\t\t);\n\t\t}\n\n\t\treturn declarations.join(\"\\n\\n\");\n\t}\n\n\tfunction buildExampleSnippet(): string[] {\n\t\treturn [\n\t\t\t\"```typescript\",\n\t\t\t\"const numbers = [12, 24, 36];\",\n\t\t\t\"const total = numbers.reduce((sum, value) => sum + value, 0);\",\n\t\t\t\"\",\n\t\t\t\"return {\",\n\t\t\t\" count: numbers.length,\",\n\t\t\t\" average: total / numbers.length,\",\n\t\t\t\"};\",\n\t\t\t\"```\",\n\t\t];\n\t}\n\n\texport function generateSystemPrompt(config: ToolConfig): string {\n\t\tconst fnPrefix = config.fnPrefix ?? toolFnPrefix;\n\t\tconst bindings = toolsForBinding(config.tools, fnPrefix);\n\t\tconst typeStubs = generateTypeStubs(bindings);\n\t\tconst functionDocs =\n\t\t\tObject.entries(bindings)\n\t\t\t\t.map(([name, binding]) => `- \\`${name}(input)\\`: ${binding.description}`)\n\t\t\t\t.join(\"\\n\") || \"- No external APIs available for this run.\";\n\n\t\treturn [\n\t\t\t\"## Code Execution Tool\",\n\t\t\t\"\",\n\t\t\t\"You have access to `sandbox_execute_typescript` which runs TypeScript code in a sandboxed environment.\",\n\t\t\t\"\",\n\t\t\t\"### When to Use\",\n\t\t\t\"\",\n\t\t\t\"Use `sandbox_execute_typescript` when you need to:\",\n\t\t\t\"- Process data with loops, conditionals, or complex logic\",\n\t\t\t\"- Make multiple tool calls in parallel with `Promise.all(...)`\",\n\t\t\t\"- Transform, filter, or aggregate data\",\n\t\t\t\"- Perform calculations or data analysis\",\n\t\t\t\"\",\n\t\t\t\"For simple operations, prefer calling tools directly.\",\n\t\t\t\"\",\n\t\t\t\"### Available External APIs\",\n\t\t\t\"\",\n\t\t\t\"Inside your TypeScript code, you can call these async functions:\",\n\t\t\t\"\",\n\t\t\tfunctionDocs,\n\t\t\t\"\",\n\t\t\t\"### Type Definitions\",\n\t\t\t\"\",\n\t\t\t\"```typescript\",\n\t\t\ttypeStubs,\n\t\t\t\"```\",\n\t\t\t\"\",\n\t\t\t\"### Example\",\n\t\t\t\"\",\n\t\t\t...buildExampleSnippet(),\n\t\t\t\"\",\n\t\t\t\"### Important Notes\",\n\t\t\t\"\",\n\t\t\t\"- All\" + `\\`${fnPrefix}\\`*` + \"calls are async, so always use `await`\",\n\t\t\t\"- Return a value to pass results back to you\",\n\t\t\t\"- Use `console.log()` for debugging (logs are captured)\",\n\t\t\t\"- The sandbox is isolated - no network access or file system\",\n\t\t\t\"- Each execution is isolated and does not share state with previous runs\",\n\t\t\t\"\",\n\t\t].join(\"\\n\");\n\t}\n\n\tasync function transpileTypeScript(typescriptCode: string): Promise<string> {\n\t\tconst wrappedSource = [\n\t\t\t\"(async () => {\",\n\t\t\t\"\\tconst __codemodeNormalizeError = (error: unknown) => {\",\n\t\t\t\"\\t\\tif (error instanceof Error) return { name: error.name, message: error.message, stack: error.stack };\",\n\t\t\t\"\\t\\tif (typeof error === 'object' && error !== null) {\",\n\t\t\t\"\\t\\t\\tconst candidate = error as { name?: unknown; message?: unknown; stack?: unknown };\",\n\t\t\t\"\\t\\t\\treturn {\",\n\t\t\t\"\\t\\t\\t\\tname: typeof candidate.name === 'string' ? candidate.name : 'Error',\",\n\t\t\t\"\\t\\t\\t\\tmessage:\",\n\t\t\t\"\\t\\t\\t\\t\\ttypeof candidate.message === 'string'\",\n\t\t\t\"\\t\\t\\t\\t\\t\\t? candidate.message\",\n\t\t\t\"\\t\\t\\t\\t\\t\\t: JSON.stringify(candidate) || 'Unknown execution error',\",\n\t\t\t\"\\t\\t\\t\\tstack: typeof candidate.stack === 'string' ? candidate.stack : undefined,\",\n\t\t\t\"\\t\\t\\t};\",\n\t\t\t\"\\t\\t}\",\n\t\t\t\"\\t\\treturn { name: 'Error', message: String(error) };\",\n\t\t\t\"\\t};\",\n\t\t\t\"\\ttry {\",\n\t\t\ttypescriptCode,\n\t\t\t\"\\t} catch (error) {\",\n\t\t\t\"\\t\\tthrow __codemodeNormalizeError(error);\",\n\t\t\t\"\\t}\",\n\t\t\t\"})()\",\n\t\t].join(\"\\n\");\n\t\tconst transformed = await transform(wrappedSource, {\n\t\t\tloader: \"ts\",\n\t\t\ttarget: \"es2022\",\n\t\t\tsourcefile: \"script.ts\",\n\t\t\tminify: false,\n\t\t\tkeepNames: false,\n\t\t});\n\t\treturn transformed.code;\n\t}\n\n\tfunction buildToolDescription(tools: Agent.AnyAgentTool[], fnPrefix = toolFnPrefix): string {\n\t\tconst externalFunctions = tools.map((tool) => `${fnPrefix}${tool.name}`).join(\"\\n\");\n\n\t\treturn [\n\t\t\t\"Execute TypeScript code in a secure sandbox environment. \",\n\t\t\t\"The code can use these external API functions:\",\n\t\t\t\"<functions>\",\n\t\t\t` ${externalFunctions}`,\n\t\t\t\"</functions>\",\n\t\t\t`All ${fnPrefix}* calls are async and must be awaited. `,\n\t\t\t\"Return a value to pass results back. Use console.log() for debugging.\",\n\t\t].join(\"\\n\");\n\t}\n\n\texport function createCodeModeTool(\n\t\tconfig: ToolConfig,\n\t): Agent.AgentTool<\n\t\ttypeof SandboxExecutionInputSchema,\n\t\ttypeof SandboxExecutionOutputSchema,\n\t\tunknown,\n\t\ttypeof SandboxExecutionErrorSchema\n\t> {\n\t\tif (config.tools.length === 0) {\n\t\t\tthrow new ToolDefinitionErr({ message: \"at least one tool must be provided to `createCodeModeTool`\" });\n\t\t}\n\n\t\tconst tool = Agent.defineTool({\n\t\t\tname: \"sandbox_execute_typescript\",\n\t\t\tlabel: \"Sandbox TypeScript\",\n\t\t\tdescription: buildToolDescription(config.tools, config.fnPrefix),\n\t\t\tparameters: SandboxExecutionInputSchema,\n\t\t\toutputSchema: SandboxExecutionOutputSchema,\n\t\t\terrorSchema: SandboxExecutionErrorSchema,\n\t\t\tasync execute(_callID, params, signal, onUpdate) {\n\t\t\t\tconst bindings = toolsForBinding(config.tools, config.fnPrefix ?? toolFnPrefix);\n\t\t\t\tlet context: Context | undefined;\n\n\t\t\t\ttry {\n\t\t\t\t\tawait onUpdate?.({\n\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t\tpartial: {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"Transpiling TypeScript for sandbox execution\" }],\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\tconst javascriptCode = await transpileTypeScript(params.typescriptCode);\n\n\t\t\t\t\tawait onUpdate?.({\n\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t\tpartial: {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"Executing code in sandbox runtime\" }],\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\tcontext = await config.driver.createContext({\n\t\t\t\t\t\tbindings,\n\t\t\t\t\t\ttimeout: config.timeout,\n\t\t\t\t\t\tmemoryLimit: config.memoryLimit,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst executionResult = await context.execute(javascriptCode);\n\t\t\t\t\tif (executionResult.success) {\n\t\t\t\t\t\tconst details: SandboxExecutionOutput = {\n\t\t\t\t\t\t\tresult: executionResult.value,\n\t\t\t\t\t\t\t...(executionResult.logs && executionResult.logs.length > 0 ? { logs: executionResult.logs } : {}),\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: serializeForContent(details) }],\n\t\t\t\t\t\t\t\tdetails,\n\t\t\t\t\t\t\t\tisError: false,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tconst details: SandboxExecutionError = {\n\t\t\t\t\t\tmessage: executionResult.error?.message || \"sandbox execution failed\",\n\t\t\t\t\t\t...(executionResult.error?.name ? { name: executionResult.error.name } : {}),\n\t\t\t\t\t\t...(executionResult.error?.stack ? { stack: executionResult.error.stack } : {}),\n\t\t\t\t\t\t...(executionResult.error?.line != null ? { line: executionResult.error.line } : {}),\n\t\t\t\t\t\t...(executionResult.logs && executionResult.logs.length > 0 ? { logs: executionResult.logs } : {}),\n\t\t\t\t\t};\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: serializeForContent(details) }],\n\t\t\t\t\t\t\tdetails,\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst normalizedError = normalizeExecutionError(error);\n\t\t\t\t\tconst details: SandboxExecutionError = {\n\t\t\t\t\t\tmessage: normalizedError.message,\n\t\t\t\t\t\t...(normalizedError.name ? { name: normalizedError.name } : {}),\n\t\t\t\t\t\t...(normalizedError.stack ? { stack: normalizedError.stack } : {}),\n\t\t\t\t\t\t...(normalizedError.line != null ? { line: normalizedError.line } : {}),\n\t\t\t\t\t};\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: serializeForContent(details) }],\n\t\t\t\t\t\t\tdetails,\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t} finally {\n\t\t\t\t\tawait context?.dispose();\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t\treturn tool;\n\t}\n\n\texport async function create(config: ToolConfig) {\n\t\treturn {\n\t\t\ttool: createCodeModeTool(config),\n\t\t\tsystemPrompt: generateSystemPrompt(config),\n\t\t};\n\t}\n}\n","import { Model } from \"./model/model\";\nimport type { Provider } from \"./provider/provider\";\n\ntype LLM = {\n\t<TProvider extends Provider.KnownProvider, TModel extends Model.Info[\"id\"]>(\n\t\tprovider: TProvider,\n\t\tmodel: TModel,\n\t\toverrides?: Partial<Model.Info>,\n\t): Promise<Model.Info | undefined>;\n\tmodel: typeof Model.getModel;\n\tmodels: typeof Model.getModels;\n\tproviders: typeof Model.getProviders;\n\tregistry: typeof Model.registry;\n\tsupportsXhigh: typeof Model.supportsXhigh;\n\tmodelsAreEqual: typeof Model.modelsAreEqual;\n};\n\nconst llmImpl = async <TProvider extends Provider.KnownProvider, TModel extends Model.Info[\"id\"]>(\n\tprovider: TProvider,\n\tmodel: TModel,\n\toverrides?: Partial<Model.Info>,\n): Promise<Model.Info | undefined> => Model.getModel(provider, model, overrides);\n\nexport const llm = Object.assign(llmImpl, {\n\tmodel: Model.getModel,\n\tmodels: Model.getModels,\n\tproviders: Model.getProviders,\n\tregistry: Model.registry,\n\tsupportsXhigh: Model.supportsXhigh,\n\tmodelsAreEqual: Model.modelsAreEqual,\n}) as LLM;\n","import \"./provider/register\";\n\nimport type { Message } from \"./message/message\";\nimport type { Model } from \"./model/model\";\nimport { Stream } from \"./provider/stream\";\nimport type { AssistantMessageEventStream } from \"./utils/eventstream\";\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 * const simple = stream.simple(model, context, options);\n * const simpleMessage = await stream.completeSimple(model, context, options);\n * ```\n */\ntype StreamCallable = {\n\t(model: Model.Info, context: Message.Context, options?: Stream.Options): AssistantMessageEventStream;\n\tcomplete: typeof Stream.complete;\n\tsimple: typeof Stream.streamSimple;\n\tcompleteSimple: typeof Stream.completeSimple;\n\tresolveProtocolProvider: typeof Stream.resolveProtocolProvider;\n};\n\nconst streamImpl = (\n\tmodel: Model.Info,\n\tcontext: Message.Context,\n\toptions?: Stream.Options,\n): AssistantMessageEventStream => Stream.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.simple(...)` uses `Stream.SimpleOptions` for higher-level reasoning controls.\n * - `stream.completeSimple(...)` is the non-streaming counterpart to `stream.simple(...)`.\n * - `stream.resolveProtocolProvider(...)` exposes protocol resolution for advanced integrations.\n */\nexport const stream = Object.assign(streamImpl, {\n\tcomplete: Stream.complete,\n\tsimple: Stream.streamSimple,\n\tcompleteSimple: Stream.completeSimple,\n\tresolveProtocolProvider: Stream.resolveProtocolProvider,\n}) as StreamCallable;\n\n/** Resolve a streamed response directly to the final assistant message. */\nexport const complete = Stream.complete;\n/** Start a stream using the simplified options surface. */\nexport const streamSimple = Stream.streamSimple;\n/** Resolve a simplified stream request directly to the final assistant message. */\nexport const completeSimple = Stream.completeSimple;\n"],"mappings":";;;;;;;;;;;AAEO,IAAA;;CACC,MAAM,oBAAA,UAAA,oBAAoB;EAChC,WAAW;EACX,QAAQ;EACR,eAAe;EACf,YAAY;EACZ,MAAM;EACN,KAAK;EACL,UAAU;EACV,KAAK;EACL,UAAU;EACV;CACM,MAAM,sBAAA,UAAA,sBAAsB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oB,QAAQ;QAAE,CAAC;OAC/D;OACA,SAAS;OACT;MACD;cACQ;AACT,WAAM,SAAS,SAAS;;;GAG1B,CAAC;;;CAII,eAAe,OAAO,QAAoB;AAChD,SAAO;GACN,MAAM,mBAAmB,OAAO;GAChC,cAAc,qBAAqB,OAAO;GAC1C;;;+BAEF;;;AC/hBD,MAAM,UAAU,OACf,UACA,OACA,cACqC,MAAM,SAAS,UAAU,OAAO,UAAU;AAEhF,MAAa,MAAM,OAAO,OAAO,SAAS;CACzC,OAAO,MAAM;CACb,QAAQ,MAAM;CACd,WAAW,MAAM;CACjB,UAAU,MAAM;CAChB,eAAe,MAAM;CACrB,gBAAgB,MAAM;CACtB,CAAC;;;ACYF,MAAM,cACL,OACA,SACA,YACiC,OAAO,OAAO,OAAO,SAAS,QAAQ;;;;;;;;;;;;AAaxE,MAAa,SAAS,OAAO,OAAO,YAAY;CAC/C,UAAU,OAAO;CACjB,QAAQ,OAAO;CACf,gBAAgB,OAAO;CACvB,yBAAyB,OAAO;CAChC,CAAC;AAGsB,OAAO;AAEH,OAAO;AAEL,OAAO"}
1
+ {"version":3,"file":"index.mjs","names":["Type","Type","Type","Type","Type","partialParse","stream"],"sources":["../../src/message/message.ts","../../src/event/event.ts","../../src/llm.ts","../../src/llm/protocol.ts","../../src/llm/shared.ts","../../src/llm/options.ts","../../src/utils/eventstream.ts","../../src/llm/runtime.ts","../../src/llm/provider.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, type TSchema } from \"typebox\";\nimport { uuidv7 } from \"uuidv7\";\nimport { Model } from \"../model/model\";\n\nexport namespace Message {\n\texport const TextContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"text\"),\n\t\ttext: Type.String(),\n\t\ttextSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the message ID\n\t});\n\texport type TextContent = Static<typeof TextContentSchema>;\n\n\texport const ImageContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"image\"),\n\t\tdata: Type.String(), // base64 encoded image data\n\t\tmimeType: Type.String(), // e.g., \"image/jpeg\", \"image/png\"\n\t});\n\texport type ImageContent = Static<typeof ImageContentSchema>;\n\n\texport const ThinkingContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"thinking\"),\n\t\tthinking: Type.String(),\n\t\tthinkingSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the reasoning item ID\n\t\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t\t * to the API for multi-turn continuity. */\n\t\tredacted: Type.Optional(Type.Boolean()),\n\t});\n\texport type ThinkingContent = Static<typeof ThinkingContentSchema>;\n\n\texport const ToolCallBaseSchema = Type.Object({\n\t\ttype: Type.Literal(\"toolCall\"),\n\t\tcallID: Type.String(),\n\t\tname: Type.String(),\n\t\targuments: Type.Record(Type.String(), Type.Any()),\n\t\tthoughtSignature: Type.Optional(Type.String()), // Google-specific: opaque signature for reusing thought context\n\t\ttime: Type.Object({\n\t\t\tstart: Type.Number(), // Unix timestamp in milliseconds\n\t\t\tend: Type.Number(), // Unix timestamp in milliseconds, last known lifecycle update\n\t\t}),\n\t});\n\n\texport const ToolSuccessResult = Type.Object({\n\t\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t\tdetails: Type.Optional(Type.Any()),\n\t\tisError: Type.Literal(false),\n\t});\n\texport const ToolErrorResult = Type.Object({\n\t\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t\tdetails: Type.Optional(Type.Any()),\n\t\tisError: Type.Literal(true),\n\t});\n\texport const ToolRunningPartial = Type.Object({\n\t\tcontent: Type.Optional(Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))),\n\t\tdetails: Type.Optional(Type.Any()),\n\t});\n\n\texport const ToolStatusEnum = {\n\t\tpending: \"pending\",\n\t\trunning: \"running\",\n\t\tcompleted: \"completed\",\n\t\terror: \"error\",\n\t\tskipped: \"skipped\",\n\t\taborted: \"aborted\",\n\t} as const;\n\n\texport const ToolRunningSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.running),\n\t\tpartial: Type.Optional(ToolRunningPartial),\n\t});\n\texport const ToolCompletedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.completed),\n\t\tresult: ToolSuccessResult,\n\t});\n\texport const ToolErrorSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.error),\n\t\tresult: ToolErrorResult,\n\t});\n\texport const ToolSkippedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.skipped),\n\t\tresult: ToolErrorResult,\n\t});\n\texport const ToolAbortedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.aborted),\n\t\tresult: ToolErrorResult,\n\t});\n\n\tconst ToolCallPendingPart = Type.Intersect([\n\t\tToolCallBaseSchema,\n\t\tType.Object({\n\t\t\tstatus: Type.Literal(ToolStatusEnum.pending),\n\t\t}),\n\t]);\n\tconst ToolCallRunningPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolRunningSchema]));\n\tconst ToolCallCompletedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));\n\tconst ToolCallErrorPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolErrorSchema]));\n\tconst ToolCallSkippedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));\n\tconst ToolCallAbortedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));\n\n\texport const ToolCallInFlightSchema = Type.Object({\n\t\tcallID: Type.String(),\n\t\tname: Type.String(),\n\t\trawArgs: Type.Record(Type.String(), Type.Unknown()),\n\t\targs: Type.Optional(Type.Unknown()),\n\t});\n\texport type ToolCallInFlight = Static<typeof ToolCallInFlightSchema>;\n\n\texport const ToolCallSchema = Type.Union([\n\t\tToolCallPendingPart,\n\t\tToolCallRunningPart,\n\t\tToolCallCompletedPart,\n\t\tToolCallErrorPart,\n\t\tToolCallSkippedPart,\n\t\tToolCallAbortedPart,\n\t]);\n\n\texport type ToolCall = Static<typeof ToolCallSchema>;\n\texport type ToolCallPendingPart = Static<typeof ToolCallPendingPart>;\n\texport type ToolCallRunningPart = Static<typeof ToolCallRunningPart>;\n\texport type ToolCallCompletedPart = Static<typeof ToolCallCompletedPart>;\n\texport type ToolCallErrorPart = Static<typeof ToolCallErrorPart>;\n\n\texport const UsageSchema = Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t\ttotalTokens: Type.Number(),\n\t\tcost: Type.Object({\n\t\t\tinput: Type.Number(),\n\t\t\toutput: Type.Number(),\n\t\t\tcacheRead: Type.Number(),\n\t\t\tcacheWrite: Type.Number(),\n\t\t\ttotal: Type.Number(),\n\t\t}),\n\t});\n\texport type Usage = Static<typeof UsageSchema>;\n\n\texport const StopReasonSchema = Type.Union([\n\t\tType.Literal(\"stop\"),\n\t\tType.Literal(\"length\"),\n\t\tType.Literal(\"toolUse\"),\n\t\tType.Literal(\"error\"),\n\t\tType.Literal(\"aborted\"),\n\t]);\n\texport type StopReason = Static<typeof StopReasonSchema>;\n\n\texport const UserMessageSchema = Type.Object({\n\t\tmessageId: Type.String(),\n\t\trole: Type.Literal(\"user\"),\n\t\ttime: Type.Object({\n\t\t\tcreated: Type.Number(),\n\t\t}),\n\t\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t});\n\texport type UserMessage = Static<typeof UserMessageSchema>;\n\n\texport const AssistantMessageSchema = Type.Object({\n\t\trole: Type.Literal(\"assistant\"),\n\t\tprotocol: Model.KnownProviderEnumSchema,\n\t\tprovider: Model.ProviderInfo,\n\t\tmodel: Type.String(),\n\t\tusage: UsageSchema,\n\t\tstopReason: StopReasonSchema,\n\t\terrorMessage: Type.Optional(Type.String()),\n\t\ttime: Type.Object({\n\t\t\tcreated: Type.Number(),\n\t\t\tcompleted: Type.Number(),\n\t\t}),\n\t\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema, ThinkingContentSchema, ToolCallSchema])),\n\t\tresponseId: Type.Optional(Type.String()), // Provider-specific response/message identifier when the upstream API exposes one\n\t\tresponseModel: Type.Optional(Type.String()), // Concrete routed model identifier when it differs from the requested model\n\t\tmessageId: Type.String(),\n\t});\n\texport type AssistantMessage = Static<typeof AssistantMessageSchema>;\n\n\texport const MessageSchema = Type.Union([UserMessageSchema, AssistantMessageSchema]);\n\texport type Message = Static<typeof MessageSchema>;\n\n\ttype UserMessageInit = Omit<UserMessage, \"messageId\"> & {\n\t\tmessageId?: string;\n\t};\n\n\ttype AssistantMessageInit = Omit<AssistantMessage, \"messageId\"> & {\n\t\tmessageId?: string;\n\t};\n\n\texport function createMessageId(): string {\n\t\treturn uuidv7();\n\t}\n\n\texport function createUserMessage(message: UserMessageInit): UserMessage {\n\t\tconst { messageId = createMessageId(), ...rest } = message;\n\t\treturn {\n\t\t\tmessageId,\n\t\t\t...rest,\n\t\t};\n\t}\n\n\texport function createAssistantMessage(message: AssistantMessageInit): AssistantMessage {\n\t\tconst { messageId = createMessageId(), ...rest } = message;\n\t\treturn {\n\t\t\tmessageId,\n\t\t\t...rest,\n\t\t};\n\t}\n\n\t/**\n\t * Generic tool definition with typed parameter schema.\n\t * Usage:\n\t *\n\t * const search = Message.defineTool({\n\t * name: \"search\",\n\t * description: \"Search documents\",\n\t * parameters: Type.Object({\n\t * query: Type.String(),\n\t * limit: Type.Optional(Type.Number()),\n\t * }),\n\t * });\n\t *\n\t * type SearchParams = Static<typeof search.parameters>;\n\t */\n\texport const ToolSchema = Type.Object({\n\t\tname: Type.String(),\n\t\tdescription: Type.String(),\n\t\tparameters: Type.Unsafe<TSchema>({}),\n\t});\n\texport interface Tool<TParameters extends TSchema = TSchema> {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: TParameters;\n\t}\n\texport type ToolArguments<T extends Tool> = Static<T[\"parameters\"]>;\n\n\texport function defineTool<TParameters extends TSchema>(tool: Tool<TParameters>): Tool<TParameters> {\n\t\treturn tool;\n\t}\n\n\texport const ContextSchema = Type.Object({\n\t\tsystemPrompt: Type.Optional(Type.String()),\n\t\tmessages: Type.Array(MessageSchema),\n\t\ttools: Type.Optional(Type.Array(ToolSchema)),\n\t});\n\texport type Context = Static<typeof ContextSchema>;\n\n\tfunction isUnresolvedToolCall(toolCall: ToolCall): toolCall is ToolCallPendingPart | ToolCallRunningPart {\n\t\treturn toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;\n\t}\n\n\tfunction syntheticSkippedToolCall(toolCall: ToolCallPendingPart | ToolCallRunningPart): ToolCall {\n\t\tconst {\n\t\t\tstatus: _status,\n\t\t\tpartial: _partial,\n\t\t\t...base\n\t\t} = toolCall as (ToolCallPendingPart | ToolCallRunningPart) & {\n\t\t\tpartial?: unknown;\n\t\t};\n\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: ToolStatusEnum.skipped,\n\t\t\tresult: {\n\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\tisError: true,\n\t\t\t},\n\t\t\ttime: {\n\t\t\t\t...toolCall.time,\n\t\t\t\tend: Math.max(toolCall.time.end, Date.now()),\n\t\t\t},\n\t\t};\n\t}\n\n\texport function transformMessages<TProtocol extends Model.KnownProviderEnum>(\n\t\tmessages: Message[],\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tnormalizeToolCallId?: (id: string, model: Model.TModel<TProtocol>, source: AssistantMessage) => string,\n\t): Message[] {\n\t\tconst toolCallIDMap = new Map<string, string>();\n\n\t\tconst transformed: Message[] = [];\n\t\tfor (const msg of messages) {\n\t\t\tif (msg.role === \"user\") {\n\t\t\t\ttransformed.push(msg);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider.id === model.provider.id &&\n\t\t\t\tassistantMsg.protocol === model.protocol &&\n\t\t\t\tassistantMsg.model === model.id;\n\n\t\t\tconst transformedParts = assistantMsg.parts.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (isSameModel && block.thinkingSignature) return block;\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst normalizedID = toolCallIDMap.get(block.callID);\n\t\t\t\t\tif (normalizedID && normalizedID !== block.callID) {\n\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: normalizedID };\n\t\t\t\t\t} else if (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);\n\t\t\t\t\t\tif (nextID !== toolCall.callID) {\n\t\t\t\t\t\t\ttoolCallIDMap.set(toolCall.callID, nextID);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: nextID };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\t\t\tconst parts = transformedParts.map((block) => {\n\t\t\t\tif (block.type === \"toolCall\" && isUnresolvedToolCall(block)) {\n\t\t\t\t\treturn syntheticSkippedToolCall(block);\n\t\t\t\t}\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\ttransformed.push({\n\t\t\t\t...assistantMsg,\n\t\t\t\tparts,\n\t\t\t});\n\t\t}\n\n\t\treturn transformed;\n\t}\n}\n","import Type, { type Static } from \"typebox\";\nimport { Message } from \"../message/message\";\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 namespace Event {\n\texport const LLMMessageEventType = {\n\t\tstart: \"start\",\n\n\t\ttextStart: \"text.start\",\n\t\ttextDelta: \"text.delta\",\n\t\ttextEnd: \"text.end\",\n\n\t\tthinkingStart: \"thinking.start\",\n\t\tthinkingDelta: \"thinking.delta\",\n\t\tthinkingEnd: \"thinking.end\",\n\n\t\ttoolcallStart: \"toolcall.start\",\n\t\ttoolcallDelta: \"toolcall.delta\",\n\t\ttoolcallEnd: \"toolcall.end\",\n\t\ttoolcallFinal: \"toolcall.final\",\n\n\t\tdone: \"done\",\n\t\terror: \"error\",\n\t} as const;\n\texport type LLMMessageEventType = (typeof LLMMessageEventType)[keyof typeof LLMMessageEventType];\n\n\t/**\n\t * Event protocol for AssistantMessageEventStream.\n\t *\n\t * Streams should emit `start` before partial updates, then terminate with either:\n\t * - `done` carrying the final successful AssistantMessage, or\n\t * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n\t * and errorMessage.\n\t */\n\texport const LLMMessageEventSchema = Type.Union([\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.start),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tcontent: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tcontent: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\ttoolCall: Message.ToolCallSchema,\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallFinal),\n\t\t\tpartIndex: Type.Number(),\n\t\t\ttoolCall: Message.ToolCallSchema,\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.done),\n\t\t\treason: Type.Union([Type.Literal(\"stop\"), Type.Literal(\"length\"), Type.Literal(\"toolUse\")]),\n\t\t\tmessage: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.error),\n\t\t\treason: Type.Union([Type.Literal(\"aborted\"), Type.Literal(\"error\")]),\n\t\t\terror: Message.AssistantMessageSchema,\n\t\t}),\n\t]);\n\texport type LLMMessageEvent = Static<typeof LLMMessageEventSchema>;\n\n\texport const AgentEventType = {\n\t\t// Agent lifecycle\n\t\tagentStart: \"agent.start\",\n\t\tagentEnd: \"agent.end\",\n\t\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t\tturnStart: \"turn.start\",\n\t\tturnEnd: \"turn.end\",\n\t\t// Message lifecycle - emitted for user, assistant message and corresponding parts\n\t\tmessageStart: \"message.start\",\n\n\t\tmessagePartStart: \"message.part.start\",\n\t\tmessagePartUpdate: \"message.part.update\",\n\t\tmessagePartEnd: \"message.part.end\",\n\n\t\tmessageUpdate: \"message.update\",\n\t\tmessageEnd: \"message.end\",\n\t\t// Tool execution lifecycle\n\t\ttoolExecutionStart: \"tool.execution.start\",\n\t\ttoolExecutionUpdate: \"tool.execution.update\",\n\t\ttoolExecutionEnd: \"tool.execution.end\",\n\t} as const;\n\texport type AgentEventType = (typeof AgentEventType)[keyof typeof AgentEventType];\n\n\t//\n\t// message parts\n\tconst UserMessagePart = Type.Union([Message.TextContentSchema, Message.ImageContentSchema]);\n\tconst AssistantMessagePart = Type.Union([\n\t\tMessage.TextContentSchema,\n\t\tMessage.ImageContentSchema,\n\t\tMessage.ThinkingContentSchema,\n\t\tMessage.ToolCallSchema,\n\t]);\n\n\t//\n\t// user message part\n\t// part start\n\tconst UserMessagePartStart = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartStart),\n\t\tmessage: Message.UserMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: UserMessagePart,\n\t});\n\t// part end\n\tconst UserMessagePartEnd = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\t\tmessage: Message.UserMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: UserMessagePart,\n\t});\n\n\t//\n\t// assistant message part\n\t// part start\n\tconst AssistantMessagePartStart = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartStart),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t});\n\t// part update llm\n\tconst AssistantMessagePartLLMUpdate = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t\tsource: Type.Literal(\"llm\"),\n\t});\n\t// part update tool\n\tconst AssistantMessagePartToolUpdate = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t\tsource: Type.Literal(\"tool\"),\n\t});\n\t// part end\n\tconst AssistantMessagePartEnd = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t});\n\n\t//\n\t// tool exection\n\tconst ToolExecutionStartSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionStart),\n\t\t\t}),\n\t\t]),\n\t);\n\texport type ToolExecutionStart = Static<typeof ToolExecutionStartSchema>;\n\n\tconst ToolExecutionUpdateSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionUpdate),\n\t\t\t}),\n\t\t\tMessage.ToolRunningSchema,\n\t\t]),\n\t);\n\texport type ToolExecutionUpdate = Static<typeof ToolExecutionUpdateSchema>;\n\n\tconst ToolExecutionEndSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionEnd),\n\t\t\t}),\n\t\t\tType.Union([Message.ToolCompletedSchema, Message.ToolErrorSchema]),\n\t\t]),\n\t);\n\texport type ToolExecutionEnd = Static<typeof ToolExecutionEndSchema>;\n\n\t/**\n\t * Events emitted by the Agent lifecycle\n\t * These events provide fine-grained lifecycle information for messages, turns, and tool execution.\n\t */\n\texport const AgentEventSchema = Type.Union([\n\t\t//\n\t\t// Agent lifecycle\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.agentStart),\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.agentEnd),\n\t\t\tmessages: Type.Array(Message.MessageSchema),\n\t\t}),\n\t\t//\n\t\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.turnStart),\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.turnEnd),\n\t\t\tmessage: Message.AssistantMessageSchema,\n\t\t}),\n\t\t//\n\t\t// Message lifecycle - emitted for user, assistant and corresponding parts\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageStart),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\t// user message parts lifecycle\n\t\tType.Union([UserMessagePartStart, UserMessagePartEnd]),\n\t\t//\n\t\t// assistant message parts lifecycle\n\t\tType.Union([\n\t\t\tAssistantMessagePartStart,\n\t\t\tAssistantMessagePartLLMUpdate,\n\t\t\tAssistantMessagePartToolUpdate,\n\t\t\tAssistantMessagePartEnd,\n\t\t]),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageUpdate),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageEnd),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\t//\n\t\t// Tool execution lifecycle\n\t\tToolExecutionStartSchema,\n\t\tToolExecutionUpdateSchema,\n\t\tToolExecutionEndSchema,\n\t]);\n\texport type AgentEvent = Static<typeof AgentEventSchema>;\n}\n","import { Model } from \"./model/model\";\n\ntype LLM = {\n\t<TProvider extends string, TModel extends Model.Info[\"id\"]>(\n\t\tprovider: TProvider,\n\t\tmodel: TModel,\n\t\toverrides?: Partial<Model.Info>,\n\t): Promise<Model.Info | 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 <TProvider extends string, TModel extends Model.Info[\"id\"]>(\n\tprovider: TProvider,\n\tmodel: TModel,\n\toverrides?: Partial<Model.Info>,\n): Promise<Model.Info | undefined> => Model.getModel(provider, model, overrides);\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 { NamedError } from \"@codeworksh/utils\";\nimport type { Static, TSchema } from \"typebox\";\nimport Type from \"typebox\";\nimport type { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport type { AssistantMessageEventStream } from \"../utils/eventstream\";\nimport type { SharedOptions, ThinkingBudgets } from \"./shared\";\n\nexport namespace Protocol {\n\texport const ProviderProtocolNotFoundError = NamedError.create(\n\t\t\"ProviderProtocolNotFoundError\",\n\t\tType.Object({\n\t\t\tprotocol: Model.KnownProviderEnumSchema,\n\t\t}),\n\t);\n\texport type ProviderProtocolNotFoundError = InstanceType<typeof ProviderProtocolNotFoundError>;\n\n\texport const ProtocolMismatchError = NamedError.create(\n\t\t\"ProtocolMismatchError\",\n\t\tType.Object({\n\t\t\tactual: Model.KnownProviderEnumSchema,\n\t\t\texpected: Model.KnownProviderEnumSchema,\n\t\t}),\n\t);\n\texport type ProtocolMismatchError = InstanceType<typeof ProtocolMismatchError>;\n\n\texport const ProtocolAuthError = NamedError.create(\n\t\t\"ProtocolAuthError\",\n\t\tType.Object({\n\t\t\tmessage: Type.String(),\n\t\t\tprotocol: Type.String(),\n\t\t}),\n\t);\n\texport type ProtocolAuthError = InstanceType<typeof ProtocolAuthError>;\n\n\texport type CommonOptions = SharedOptions & {\n\t\treasoning?: Model.ActiveThinkingLevel;\n\t\tthinkingBudgets?: ThinkingBudgets;\n\t};\n\texport interface OptionsByProtocol {}\n\texport type ProtocolWithOptions = keyof OptionsByProtocol & Model.KnownProviderEnum;\n\texport type OptionsFor<TProtocol extends ProtocolWithOptions> = OptionsByProtocol[TProtocol];\n\n\texport type StreamFunction<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> = (model: Model.TModel<TProtocol>, context: Message.Context, options?: Static<S>) => AssistantMessageEventStream;\n\n\texport type ProtocolStreamFunction<S extends TSchema = TSchema> = (\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: Static<S>,\n\t) => AssistantMessageEventStream;\n\n\texport interface Protocol<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> {\n\t\tprotocol: TProtocol;\n\t\tstream: StreamFunction<TProtocol, S>;\n\t}\n\n\texport interface RegisteredProtocol<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> {\n\t\tprotocol: TProtocol;\n\t\tstream: ProtocolStreamFunction<S>;\n\t}\n\n\ttype AnyRegisteredProtocol = RegisteredProtocol<Model.KnownProviderEnum, TSchema>;\n\n\ttype RegistryEntry = {\n\t\tprovider: AnyRegisteredProtocol;\n\t\tsourceId?: string;\n\t};\n\n\tconst protocolRegistry = new Map<Model.KnownProviderEnum, RegistryEntry>();\n\n\tfunction wrapStream<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\t\tprotocol: TProtocol,\n\t\tstream: StreamFunction<TProtocol, S>,\n\t): ProtocolStreamFunction<S> {\n\t\treturn (model, context, options) => {\n\t\t\tif (model.protocol !== protocol) {\n\t\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\t\tactual: model.protocol,\n\t\t\t\t\texpected: protocol,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn stream(model as Model.TModel<TProtocol>, context, options);\n\t\t};\n\t}\n\n\texport function registerProtocolProvider<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\t\tprovider: Protocol<TProtocol, S>,\n\t\tsourceId?: string,\n\t): void {\n\t\tconst registered: RegisteredProtocol<TProtocol, S> = {\n\t\t\tprotocol: provider.protocol,\n\t\t\tstream: wrapStream(provider.protocol, provider.stream),\n\t\t};\n\n\t\tprotocolRegistry.set(provider.protocol, {\n\t\t\tprovider: registered as AnyRegisteredProtocol,\n\t\t\tsourceId,\n\t\t});\n\t}\n\n\texport function getProtocolProvider(protocol: Model.KnownProviderEnum): AnyRegisteredProtocol | undefined {\n\t\treturn protocolRegistry.get(protocol)?.provider;\n\t}\n\n\texport function resolveProtocolProvider(model: Model.Info): AnyRegisteredProtocol {\n\t\tconst provider = getProtocolProvider(model.protocol);\n\t\tif (!provider) {\n\t\t\tthrow new ProviderProtocolNotFoundError({\n\t\t\t\tprotocol: model.protocol,\n\t\t\t});\n\t\t}\n\n\t\treturn provider;\n\t}\n\n\texport function getProtocolProviders(): AnyRegisteredProtocol[] {\n\t\treturn Array.from(protocolRegistry.values(), (entry) => entry.provider);\n\t}\n\n\texport function stream<TProtocol extends ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: OptionsFor<TProtocol>,\n\t): AssistantMessageEventStream {\n\t\tconst provider = resolveProtocolProvider(model);\n\t\treturn provider.stream(model, context, options);\n\t}\n\n\texport async function complete<TProtocol extends ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: OptionsFor<TProtocol>,\n\t): Promise<Message.AssistantMessage> {\n\t\tconst s = stream(model, context, options);\n\t\treturn s.result();\n\t}\n\n\texport function unregisterProtocolProviders(sourceId: string): void {\n\t\tfor (const [protocol, entry] of protocolRegistry.entries()) {\n\t\t\tif (entry.sourceId === sourceId) {\n\t\t\t\tprotocolRegistry.delete(protocol);\n\t\t\t}\n\t\t}\n\t}\n\n\texport function clearProtocolProviders(): void {\n\t\tprotocolRegistry.clear();\n\t}\n}\n","import { Type, type Static } from \"typebox\";\nimport { type Model } from \"../model/model\";\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 = Type.Object({\n\tminimal: Type.Optional(Type.Number()),\n\tlow: Type.Optional(Type.Number()),\n\tmedium: Type.Optional(Type.Number()),\n\thigh: Type.Optional(Type.Number()),\n\txhigh: Type.Optional(Type.Number()),\n});\nexport type ThinkingBudgets = Static<typeof ThinkingBudgets>;\n\nexport const SharedOptions = Type.Evaluate(Type.Intersect([GenerationOptions, HelperOptions]));\nexport type SharedOptions = Static<typeof SharedOptions>;\n\nconst DEFAULT_MAX_OUTPUT_TOKENS = 32000;\nconst CONTEXT_WINDOW_OUTPUT_TOLERANCE = 1024;\n\nexport function applyDefaultMaxTokens<TOptions extends SharedOptions = SharedOptions>(\n\tmodel: Model.TModel<Model.KnownProviderEnum>,\n\toptions?: TOptions,\n): TOptions & Pick<SharedOptions, \"maxTokens\"> {\n\tconst defaultMaxTokens =\n\t\tmodel.maxTokens > 0\n\t\t\t? model.maxTokens >= model.contextWindow - CONTEXT_WINDOW_OUTPUT_TOLERANCE\n\t\t\t\t? Math.min(model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS)\n\t\t\t\t: model.maxTokens\n\t\t\t: undefined;\n\n\treturn {\n\t\t...options,\n\t\tmaxTokens: options?.maxTokens ?? defaultMaxTokens,\n\t} as TOptions & Pick<SharedOptions, \"maxTokens\">;\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 { Model } from \"../model/model\";\nimport type { Protocol } from \"./protocol\";\nimport { SharedOptions, ThinkingBudgets } from \"./shared\";\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\ntype ProviderOptionBag = Record<string, Record<string, unknown> | undefined>;\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;\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 OpenRouterOptions = AISDKOptions<OpenRouterProviderSettings, { openrouter?: OpenRouterProviderOptions }>;\nexport type XaiOptions = AISDKOptions<XaiProviderSettings, { xai?: XaiLanguageOptions }>;\n\nexport type Options = Static<typeof Options>;\n\ndeclare module \"./protocol\" {\n\texport namespace Protocol {\n\t\t// Used for type inference\n\t\t// eslint-disable-next-line no-unused-vars -- declaration merging registers AI SDK protocol options.\n\t\tinterface OptionsByProtocol {\n\t\t\t[Model.KnownProviderEnum.openai]: OpenAIOptions;\n\t\t\t[Model.KnownProviderEnum.anthropic]: AnthropicOptions;\n\t\t\t[Model.KnownProviderEnum.google]: GoogleOptions;\n\t\t\t[Model.KnownProviderEnum.googleVertex]: GoogleVertexOptions;\n\t\t\t[Model.KnownProviderEnum.googleVertexAnthropic]: GoogleVertexAnthropicOptions;\n\t\t\t[Model.KnownProviderEnum.openaiCompatible]: OpenAICompatibleOptions;\n\t\t\t[Model.KnownProviderEnum.openrouter]: OpenRouterOptions;\n\t\t\t[Model.KnownProviderEnum.xai]: XaiOptions;\n\t\t}\n\t}\n}\n","/**\n * @description Defines the Generic event stream class for async iteration.\n */\n\nimport type { Event } from \"../event/event\";\nimport type { Message } from \"../message/message\";\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\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\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","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\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","import type { LanguageModel } from \"ai\";\nimport { Model } from \"../model/model\";\nimport type { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { loadProviderFactory, packageForModel, resolveLanguageModel } from \"./registry\";\nimport { getEnvApiKey, mergeHeaders } from \"./runtime\";\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\nexport async function resolveAISDKLanguageModel(model: Model.Info, options: Options): 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\t}\n\n\tconst provider = createProvider(factoryOptions);\n\treturn resolveLanguageModel(provider, model, options.method);\n}\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 { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport { parseStreamingJson } from \"../utils/jsonparse\";\nimport { sanitizeSurrogates } from \"../utils/sanitize\";\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\"], supportsImages: boolean): 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\tif (supportsImages) {\n\t\t\tcontent.push({ type: \"image\", image: part.data, mediaType: part.mimeType });\n\t\t}\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: \"image-data\" as const,\n\t\t\t\tdata: image.data,\n\t\t\t\tmediaType: image.mimeType,\n\t\t\t})),\n\t\t],\n\t};\n}\n\nfunction assistantMessages(message: Message.AssistantMessage): ModelMessage[] {\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") return [];\n\n\tconst assistantContent: Exclude<AssistantModelMessage[\"content\"], string> = [];\n\tconst toolResults: ToolModelMessage[\"content\"] = [];\n\n\tfor (const part of message.parts) {\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({ type: \"text\", text });\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) continue;\n\t\t\tconst reasoning: Record<string, unknown> = { type: \"reasoning\", text: thinking };\n\t\t\t// Include the provider signature for faithful replay (e.g. Anthropic extended thinking).\n\t\t\tif (part.thinkingSignature) {\n\t\t\t\treasoning.providerOptions = {\n\t\t\t\t\tanthropic: { signature: part.thinkingSignature },\n\t\t\t\t};\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\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});\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\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);\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tmessages.push(...userContent(msg.parts, model.input.includes(\"image\")));\n\t\t\tcontinue;\n\t\t}\n\t\tmessages.push(...assistantMessages(msg));\n\t}\n\n\treturn messages;\n}\n\nexport function convertTools(tools?: Message.Tool[]): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(tool.parameters as any),\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(usage: LanguageModelUsage | undefined, model: Model.Info): Message.AssistantMessage[\"usage\"] {\n\tconst cacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? usage?.cachedInputTokens ?? 0;\n\tconst cacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;\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\ttotalTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tModel.calculateCost(model, result);\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 { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport { AssistantMessageEventStream } from \"../utils/eventstream\";\nimport { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { resolveAISDKLanguageModel } from \"./provider\";\nimport { formatThrownError } from \"./runtime\";\nimport { applyDefaultMaxTokens } from \"./shared\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tcreateAssistantMessage,\n\tmapFinishReason,\n\tmapUsage,\n\ttoolCallFromPart,\n\tupdateToolCallFromInput,\n\ttype StreamingToolCallBlock,\n} from \"./transform\";\n\ntype TextBlock = Message.TextContent & { streamId?: string };\ntype ThinkingBlock = Message.ThinkingContent & { streamId?: string };\n\ntype StreamBlock = TextBlock | ThinkingBlock | StreamingToolCallBlock;\ntype RuntimeOptions = Options & Protocol.CommonOptions;\ntype ProviderOptionBag = Record<string, Record<string, unknown> | undefined>;\n\nfunction providerOptionsKey(model: Model.Info): string {\n\treturn model.providerOptionsKey ?? model.protocol;\n}\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 = providerOptionsKey(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 ((key === \"anthropic\" || key === \"google-vertex-anthropic\") && 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\n// Default thinking budgets as a fraction of model.maxTokens, per level.\nconst DEFAULT_THINKING_BUDGET_FRACTIONS: Record<Model.ActiveThinkingLevel, number> = {\n\tminimal: 0.05,\n\tlow: 0.1,\n\tmedium: 0.25,\n\thigh: 0.5,\n\txhigh: 0.8,\n};\n\nconst MIN_THINKING_BUDGET = 1024;\n\nfunction resolveThinkingBudget(\n\tmodel: Model.Info,\n\toptions: RuntimeOptions,\n\tlevel: Model.ActiveThinkingLevel,\n): number | undefined {\n\t// Explicit budget from caller takes priority.\n\tconst explicit = options.thinkingBudgets?.[level];\n\tif (explicit !== undefined) return explicit;\n\n\t// Compute a sensible default so @ai-sdk/anthropic does not warn.\n\tconst key = providerOptionsKey(model);\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\tconst fraction = DEFAULT_THINKING_BUDGET_FRACTIONS[level];\n\t\treturn Math.max(Math.floor(model.maxTokens * fraction), MIN_THINKING_BUDGET);\n\t}\n\n\treturn undefined;\n}\n\nfunction reasoningProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\tconst requestedLevel = options.reasoning;\n\tif (!requestedLevel) return {};\n\n\tconst level = Model.clampThinkingLevel(model, requestedLevel);\n\tif (level === \"off\") return {};\n\n\tconst mapped = model.thinkingLevelMap?.[level] ?? level;\n\tif (!mapped) return {};\n\n\tconst key = providerOptionsKey(model);\n\tconst budget = resolveThinkingBudget(model, options, level);\n\n\tif (key === \"openai\" || key === \"xai\") {\n\t\treturn { [key]: { reasoningEffort: mapped } };\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 = mapped === \"xhigh\" ? \"high\" : mapped;\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinkingConfig: {\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\tincludeThoughts: true,\n\t\t\t\t\t...(budget !== undefined ? { thinkingBudget: 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\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinking: {\n\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\tbudgetTokens: budget ?? MIN_THINKING_BUDGET,\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): ProviderOptionBag {\n\treturn mergeProviderOptions(\n\t\tmodel.providerOptions as ProviderOptionBag | undefined,\n\t\tcacheProviderOptions(model, options),\n\t\treasoningProviderOptions(model, options),\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 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(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): 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\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(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): 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\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\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\nfunction handlePart(\n\tpart: TextStreamPart<ToolSet>,\n\toutput: Message.AssistantMessage,\n\tmodel: Model.Info,\n\tstream: AssistantMessageEventStream,\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\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\tfinishTextBlock(output, part.id, stream);\n\t\t\tbreak;\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\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\tfinishThinkingBlock(output, part.id, stream);\n\t\t\tbreak;\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\toutput.usage = mapUsage(part.usage, model);\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);\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\toutput.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\n/**\n * Resolve maxOutputTokens so that (maxOutputTokens + thinkingBudget) does not exceed model.maxTokens.\n * Without this adjustment @ai-sdk/anthropic logs a warning and silently caps the value.\n */\nfunction resolveMaxOutputTokens(\n\tmodel: Model.Info,\n\toptions: RuntimeOptions,\n\tproviderOptions: Record<string, unknown> | undefined,\n): number | undefined {\n\tconst maxTokens = options.maxTokens;\n\tif (maxTokens === undefined) return undefined;\n\n\tconst key = providerOptionsKey(model);\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\tconst thinkingConfig = providerOptions?.[key] as Record<string, unknown> | undefined;\n\t\tconst thinking = thinkingConfig?.thinking as { budgetTokens?: number } | undefined;\n\t\tconst budgetTokens = thinking?.budgetTokens ?? 0;\n\t\tif (budgetTokens > 0 && maxTokens + budgetTokens > model.maxTokens) {\n\t\t\treturn Math.max(model.maxTokens - budgetTokens, 1);\n\t\t}\n\t}\n\n\treturn 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 languageModel = await resolveAISDKLanguageModel(model, runtimeOptions);\n\t\t\tconst tools = convertTools(context.tools);\n\t\t\tconst messages = convertMessages(context, model);\n\t\t\tconst providerOptions = resolveProviderOptions(model, runtimeOptions) as Parameters<\n\t\t\t\ttypeof streamText<ToolSet>\n\t\t\t>[0][\"providerOptions\"];\n\t\t\tconst activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = {\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, runtimeOptions, providerOptions),\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};\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);\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\toutput.stopReason = runtimeOptions.signal?.aborted || output.stopReason === \"aborted\" ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatThrownError(error);\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 { Model } from \"../model/model\";\nimport { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { stream } from \"./stream\";\n\nexport { Options } from \"./options\";\nexport * from \"./registry\";\nexport { stream } from \"./stream\";\nexport * from \"./transform\";\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.openrouter));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.xai));\n}\n","import { registerAISDKProtocols } from \"./index\";\n\nregisterAISDKProtocols();\n","import \"./llm/register\";\n\nimport type { Message } from \"./message/message\";\nimport type { Model } from \"./model/model\";\nimport { Protocol } from \"./llm/protocol\";\nimport type { AssistantMessageEventStream } from \"./utils/eventstream\";\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 { Message } from \"../message/message\";\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":";;;;;;;;AAIO,IAAA;;CACC,MAAM,oBAAA,SAAA,oBAAoBA,OAAK,OAAO;EAC5C,MAAMA,OAAK,QAAQ,OAAO;EAC1B,MAAMA,OAAK,QAAQ;EACnB,eAAeA,OAAK,SAASA,OAAK,QAAQ,CAAC;EAC3C,CAAC;CAGK,MAAM,qBAAA,SAAA,qBAAqBA,OAAK,OAAO;EAC7C,MAAMA,OAAK,QAAQ,QAAQ;EAC3B,MAAMA,OAAK,QAAQ;EACnB,UAAUA,OAAK,QAAQ;EACvB,CAAC;CAGK,MAAM,wBAAA,SAAA,wBAAwBA,OAAK,OAAO;EAChD,MAAMA,OAAK,QAAQ,WAAW;EAC9B,UAAUA,OAAK,QAAQ;EACvB,mBAAmBA,OAAK,SAASA,OAAK,QAAQ,CAAC;EAI/C,UAAUA,OAAK,SAASA,OAAK,SAAS,CAAC;EACvC,CAAC;CAGK,MAAM,qBAAA,SAAA,qBAAqBA,OAAK,OAAO;EAC7C,MAAMA,OAAK,QAAQ,WAAW;EAC9B,QAAQA,OAAK,QAAQ;EACrB,MAAMA,OAAK,QAAQ;EACnB,WAAWA,OAAK,OAAOA,OAAK,QAAQ,EAAEA,OAAK,KAAK,CAAC;EACjD,kBAAkBA,OAAK,SAASA,OAAK,QAAQ,CAAC;EAC9C,MAAMA,OAAK,OAAO;GACjB,OAAOA,OAAK,QAAQ;GACpB,KAAKA,OAAK,QAAQ;GAClB,CAAC;EACF,CAAC;CAEK,MAAM,oBAAA,SA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