mirascope 2.0.0-alpha.0
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/README.md +397 -0
- package/dist/bun.cjs +447 -0
- package/dist/bun.cjs.map +1 -0
- package/dist/bun.d.cts +53 -0
- package/dist/bun.d.ts +53 -0
- package/dist/bun.js +94 -0
- package/dist/bun.js.map +1 -0
- package/dist/chunk-2R5IW35Y.js +116 -0
- package/dist/chunk-2R5IW35Y.js.map +1 -0
- package/dist/chunk-A6ZCB7BU.js +6826 -0
- package/dist/chunk-A6ZCB7BU.js.map +1 -0
- package/dist/chunk-NSBPE2FW.js +15 -0
- package/dist/chunk-NSBPE2FW.js.map +1 -0
- package/dist/chunk-RMNCGJYW.js +49 -0
- package/dist/chunk-RMNCGJYW.js.map +1 -0
- package/dist/chunk-U4MFJ4DP.js +358 -0
- package/dist/chunk-U4MFJ4DP.js.map +1 -0
- package/dist/index.cjs +7705 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +4859 -0
- package/dist/index.d.ts +4859 -0
- package/dist/index.js +324 -0
- package/dist/index.js.map +1 -0
- package/dist/model-T6IQ7UUA.js +4 -0
- package/dist/model-T6IQ7UUA.js.map +1 -0
- package/dist/tool-schema-Dh-RLHhC.d.cts +45 -0
- package/dist/tool-schema-Dh-RLHhC.d.ts +45 -0
- package/dist/transform/index.cjs +525 -0
- package/dist/transform/index.cjs.map +1 -0
- package/dist/transform/index.d.cts +89 -0
- package/dist/transform/index.d.ts +89 -0
- package/dist/transform/index.js +6 -0
- package/dist/transform/index.js.map +1 -0
- package/dist/transform/plugins/esbuild.cjs +472 -0
- package/dist/transform/plugins/esbuild.cjs.map +1 -0
- package/dist/transform/plugins/esbuild.d.cts +46 -0
- package/dist/transform/plugins/esbuild.d.ts +46 -0
- package/dist/transform/plugins/esbuild.js +5 -0
- package/dist/transform/plugins/esbuild.js.map +1 -0
- package/dist/transform/plugins/vite.cjs +405 -0
- package/dist/transform/plugins/vite.cjs.map +1 -0
- package/dist/transform/plugins/vite.d.cts +50 -0
- package/dist/transform/plugins/vite.d.ts +50 -0
- package/dist/transform/plugins/vite.js +5 -0
- package/dist/transform/plugins/vite.js.map +1 -0
- package/package.json +127 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/llm/exceptions.ts","../src/llm/messages/message.ts","../src/llm/messages/utils.ts","../src/llm/messages/index.ts","../src/llm/providers/base/base-provider.ts","../src/llm/providers/base/param-handler.ts","../src/llm/providers/base/index.ts","../src/llm/providers/anthropic/model-id.ts","../src/llm/providers/_utils.ts","../src/llm/responses/finish-reason.ts","../src/llm/responses/usage.ts","../src/llm/tools/tools.ts","../src/llm/content/tool-output.ts","../src/llm/formatting/types.ts","../src/llm/formatting/output-parser.ts","../src/llm/formatting/format.ts","../src/llm/formatting/index.ts","../src/llm/tools/define-tool.ts","../src/llm/tools/provider-tool.ts","../src/llm/tools/toolkit.ts","../src/llm/tools/web-search-tool.ts","../src/llm/tools/index.ts","../src/llm/providers/anthropic/_utils.ts","../src/llm/providers/anthropic/beta-decode.ts","../src/llm/content/audio.ts","../src/llm/content/document.ts","../src/llm/content/image.ts","../src/llm/content/text.ts","../src/llm/content/thought.ts","../src/llm/content/tool-call.ts","../src/llm/content/index.ts","../src/llm/responses/chunks.ts","../src/llm/providers/anthropic/beta-decode-stream.ts","../src/llm/responses/utils.ts","../src/llm/providers/google/model-id.ts","../src/llm/providers/google/_utils.ts","../src/llm/providers/google/decode-stream.ts","../src/llm/responses/base-response.ts","../src/llm/responses/context-response.ts","../src/llm/responses/streams.ts","../src/llm/responses/base-stream-response.ts","../src/llm/responses/context-stream-response.ts","../src/llm/responses/stream-response.ts","../src/llm/providers/google/provider.ts","../src/llm/providers/google/index.ts","../src/llm/providers/mirascope/_utils.ts","../src/llm/providers/mirascope/provider.ts","../src/llm/providers/mirascope/index.ts","../src/llm/providers/openai/_utils/errors.ts","../src/llm/providers/openai/model-id.ts","../src/llm/providers/openai/model-info.ts","../src/llm/providers/openai/completions/_utils.ts","../src/llm/providers/openai/completions/decode-stream.ts","../src/llm/providers/openai/completions/base-provider.ts","../src/llm/providers/ollama/provider.ts","../src/llm/providers/ollama/index.ts","../src/llm/providers/openai/completions/provider.ts","../src/llm/providers/openai/responses/_utils.ts","../src/llm/providers/openai/responses/decode-stream.ts","../src/llm/providers/openai/responses/provider.ts","../src/llm/providers/openai/provider.ts","../src/llm/providers/together/provider.ts","../src/llm/providers/together/index.ts","../src/llm/providers/registry.ts","../src/llm/models/model.ts","../src/llm/responses/root-response.ts","../src/llm/responses/response.ts","../src/llm/responses/index.ts","../src/llm/providers/anthropic/beta-provider.ts","../src/llm/providers/anthropic/decode-stream.ts","../src/llm/providers/anthropic/provider.ts","../src/llm/providers/anthropic/index.ts","../src/llm/index.ts","../src/llm/providers/provider-id.ts","../src/llm/providers/index.ts","../src/llm/context/context.ts","../src/llm/models/index.ts","../src/llm/models/model-context.ts","../src/llm/prompts/prompt.ts","../src/llm/calls/call.ts"],"names":["init_utils","tool","callable","execute","init_tools","blocks","system","Anthropic","uint8ArrayToBase64","parsePartialJson","modelName","init_model_id","encodeImage","processContentParts","THINKING_LEVEL_TO_BUDGET_MULTIPLIER","encodeToolSchema","encodeTools","encodeMessages","buildRequestParams","DEFAULT_MAX_TOKENS","decodeResponse","decodeContent","decodeUsage","GoogleFinishReason","ApiError","GoogleThinkingLevel","UNKNOWN_TOOL_ID","decodeFinishReason","model","GoogleGenAI","init_provider","OpenAI","encodeAudio","createDecodeState","decodeStreamEvent","decodeStream","init_decode_stream","init_base_provider","API_KEY_ENV_VAR","encodeToolOutputs","encodeUserMessage","encodeAssistantMessage","DEFAULT_BASE_URL","decodeStopReason"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IASa,gBAqBA,aAAA,EA+BA,QAAA,EAeA,mBAAA,EASA,eAAA,EASA,iBASA,aAAA,EASA,cAAA,EASA,WAAA,EASA,eAAA,EASA,cA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AAO,cAAc,MAAA,CAAO,QAAA,CAAS,YAAY,CAAA,EAAG,KAAK,IAAI,CAAA;AAAA,IAC/D,CAAA,MAAO;AAEL,MAAA,MAAM,IAAA,GAAO,QAAA;AACb,MAAA,MAAM,aAAA,GAAgB,MAAA;AAMtB,MAAA,OAAO,aAAA,CAAc,MAAA,CAAO,QAAA,CAAS,YAAY,GAAG,IAAI,CAAA;AAAA,IAC1D;AAAA,EACF,CAAA;AAEA,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,MAAA,CAAO,QAAA,EAAU;AAAA,IAC1C,YAAA;AAAA,IACA,IAAA,EAAM,QAAA;AAAA,IACN,MAAA,EAAQ,UAAA;AAAA,IACR,KAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACD,CAAA;AAED,EAAA,MAAA,CAAO,cAAA,CAAe,aAAa,OAAA,EAAS;AAAA,IAC1C,GAAA,EAAK,MAAM,QAAA,CAAS,YAAY,CAAA;AAAA,IAChC,UAAA,EAAY;AAAA,GACb,CAAA;AAED,EAAA,OAAO,WAAA;AACT;AAmGO,SAAS,WACd,IAAA,EAC8D;AAE9D,EAAA,IAAI,SAAS,MAAA,EAAW;AACtB,IAAA,QAAQ,CACN,WAAA,KACuB;AACvB,MAAA,OAAO,WAAW,WAAW,CAAA;AAAA,IAC/B,CAAA;AAAA,EACF;AAEA,EAAA,OAAO,WAAW,IAAI,CAAA;AACxB;;;APjXA,cAAA,EAAA","file":"index.cjs","sourcesContent":["/**\n * Mirascope LLM exception hierarchy for unified error handling across providers.\n */\n\nimport type { ModelId, ProviderId } from \"@/llm/providers\";\n\n/**\n * Base exception for all Mirascope LLM errors.\n */\nexport class MirascopeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}\n\n/**\n * Options for constructing a ProviderError.\n */\nexport interface ProviderErrorOptions {\n provider: ProviderId;\n originalException?: Error | null;\n}\n\n/**\n * Base class for errors that originate from a provider SDK.\n *\n * This wraps exceptions from provider libraries (OpenAI, Anthropic, etc.)\n * and provides a unified interface for error handling.\n */\nexport class ProviderError extends MirascopeError {\n /**\n * The provider that raised this error.\n */\n readonly provider: ProviderId;\n\n /**\n * The original exception from the provider SDK, if available.\n */\n readonly originalException: Error | null;\n\n constructor(message: string, options: ProviderErrorOptions) {\n super(message);\n this.provider = options.provider;\n this.originalException = options.originalException ?? null;\n if (this.originalException !== null) {\n this.cause = this.originalException;\n }\n }\n}\n\n/**\n * Options for constructing an APIError.\n */\nexport interface APIErrorOptions extends ProviderErrorOptions {\n statusCode?: number | null;\n}\n\n/**\n * Base class for HTTP-level API errors.\n */\nexport class APIError extends ProviderError {\n /**\n * The HTTP status code, if available.\n */\n readonly statusCode: number | null;\n\n constructor(message: string, options: APIErrorOptions) {\n super(message, options);\n this.statusCode = options.statusCode ?? null;\n }\n}\n\n/**\n * Raised for authentication failures (401, invalid API keys).\n */\nexport class AuthenticationError extends APIError {\n constructor(message: string, options: APIErrorOptions) {\n super(message, { ...options, statusCode: options.statusCode ?? 401 });\n }\n}\n\n/**\n * Raised for permission/authorization failures (403).\n */\nexport class PermissionError extends APIError {\n constructor(message: string, options: APIErrorOptions) {\n super(message, { ...options, statusCode: options.statusCode ?? 403 });\n }\n}\n\n/**\n * Raised for malformed requests (400, 422).\n */\nexport class BadRequestError extends APIError {\n constructor(message: string, options: APIErrorOptions) {\n super(message, { ...options, statusCode: options.statusCode ?? 400 });\n }\n}\n\n/**\n * Raised when requested resource is not found (404).\n */\nexport class NotFoundError extends APIError {\n constructor(message: string, options: APIErrorOptions) {\n super(message, { ...options, statusCode: options.statusCode ?? 404 });\n }\n}\n\n/**\n * Raised when rate limits are exceeded (429).\n */\nexport class RateLimitError extends APIError {\n constructor(message: string, options: APIErrorOptions) {\n super(message, { ...options, statusCode: options.statusCode ?? 429 });\n }\n}\n\n/**\n * Raised for server-side errors (500+).\n */\nexport class ServerError extends APIError {\n constructor(message: string, options: APIErrorOptions) {\n super(message, { ...options, statusCode: options.statusCode ?? 500 });\n }\n}\n\n/**\n * Raised when unable to connect to the API (network issues, timeouts).\n */\nexport class ConnectionError extends ProviderError {\n constructor(message: string, options: ProviderErrorOptions) {\n super(message, options);\n }\n}\n\n/**\n * Raised when requests timeout or deadline exceeded.\n */\nexport class TimeoutError extends ProviderError {\n constructor(message: string, options: ProviderErrorOptions) {\n super(message, options);\n }\n}\n\n/**\n * Raised when API response fails validation.\n *\n * This wraps the APIResponseValidationErrors that OpenAI and Anthropic both return.\n */\nexport class ResponseValidationError extends ProviderError {\n constructor(message: string, options: ProviderErrorOptions) {\n super(message, options);\n }\n}\n\n/**\n * Base class for errors that occur during tool execution.\n */\nexport class ToolError extends MirascopeError {}\n\n/**\n * Raised if an uncaught exception is thrown while executing a tool.\n */\nexport class ToolExecutionError extends ToolError {\n /**\n * The exception that was thrown while executing the tool.\n */\n readonly toolException: Error;\n\n constructor(toolException: Error | string) {\n let exception: Error;\n let message: string;\n\n if (typeof toolException === \"string\") {\n // Support string for snapshot reconstruction\n message = toolException;\n exception = new Error(message);\n } else {\n message = toolException.message;\n exception = toolException;\n }\n\n super(message);\n this.toolException = exception;\n this.cause = exception;\n }\n}\n\n/**\n * Raised if a tool call does not match any registered tool.\n */\nexport class ToolNotFoundError extends ToolError {\n /**\n * The name of the tool that was not found.\n */\n readonly toolName: string;\n\n constructor(toolName: string) {\n super(`Tool '${toolName}' not found in registered tools`);\n this.toolName = toolName;\n }\n}\n\n/**\n * Raised when response.parse() fails to parse the response content.\n *\n * This wraps errors from JSON extraction, JSON parsing, Pydantic validation,\n * or custom OutputParser functions.\n */\nexport class ParseError extends MirascopeError {\n /**\n * The original exception that caused the parse failure.\n */\n readonly originalException: Error;\n\n constructor(message: string, originalException: Error) {\n super(message);\n this.originalException = originalException;\n this.cause = originalException;\n }\n\n /**\n * Generate a message suitable for retrying with the LLM.\n *\n * Returns a user-friendly message describing what went wrong,\n * suitable for including in a retry prompt.\n */\n retryMessage(): string {\n const original = this.originalException;\n\n // Check for JSON syntax errors\n if (original instanceof SyntaxError && original.message.includes(\"JSON\")) {\n return (\n \"Your response could not be parsed because no valid JSON object \" +\n \"was found. Please ensure your response contains a JSON object \" +\n \"with opening '{' and closing '}' braces.\"\n );\n }\n\n // Default message for other errors\n return (\n `Your response could not be parsed: ${original.message}\\n\\n` +\n \"Please ensure your response matches the expected format.\"\n );\n }\n}\n\n/**\n * Raised if a Mirascope feature is unsupported by chosen provider.\n *\n * If compatibility is model-specific, then `modelId` should be specified.\n * If the feature is not supported by the provider at all, then it may be `null`.\n */\nexport class FeatureNotSupportedError extends MirascopeError {\n /**\n * The provider that does not support this feature.\n */\n readonly providerId: ProviderId;\n\n /**\n * The model that does not support this feature, if model-specific.\n */\n readonly modelId: ModelId | null;\n\n /**\n * The name of the unsupported feature.\n */\n readonly feature: string;\n\n constructor(\n feature: string,\n providerId: ProviderId,\n modelId: ModelId | null = null,\n message: string | null = null,\n ) {\n const defaultMessage =\n message ??\n `Feature '${feature}' is not supported by provider '${providerId}'${\n modelId !== null ? ` for model '${modelId}'` : \"\"\n }`;\n super(defaultMessage);\n this.feature = feature;\n this.providerId = providerId;\n this.modelId = modelId;\n }\n}\n\n/**\n * Raised when no provider is registered for a given model_id.\n */\nexport class NoRegisteredProviderError extends MirascopeError {\n /**\n * The model ID that has no registered provider.\n */\n readonly modelId: string;\n\n constructor(modelId: string) {\n const message =\n `No provider registered for model '${modelId}'. ` +\n `Use llm.registerProvider() to register a provider for this model.`;\n super(message);\n this.modelId = modelId;\n }\n}\n\n/**\n * Raised when no API key is available for a provider.\n *\n * This error is raised during auto-registration when the required API key\n * environment variable is not set. If a Mirascope fallback is available,\n * the error message will suggest using MIRASCOPE_API_KEY as an alternative.\n */\nexport class MissingAPIKeyError extends MirascopeError {\n /**\n * The provider that requires an API key.\n */\n readonly providerId: string;\n\n /**\n * The environment variable that should contain the API key.\n */\n readonly envVar: string;\n\n constructor(\n providerId: string,\n envVar: string,\n hasMirascopeFallback: boolean = false,\n ) {\n let message: string;\n if (hasMirascopeFallback) {\n message =\n `No API key found for ${providerId}. Either:\\n` +\n ` 1. Set ${envVar} environment variable, or\\n` +\n ` 2. Set MIRASCOPE_API_KEY for cross-provider support ` +\n `via Mirascope Router\\n` +\n ` (Learn more: https://mirascope.com/docs/router)`;\n } else {\n message =\n `No API key found for ${providerId}. ` +\n `Set the ${envVar} environment variable.`;\n }\n super(message);\n this.providerId = providerId;\n this.envVar = envVar;\n }\n}\n","/**\n * The `Message` types and utility constructors.\n */\n\nimport type { AssistantContentPart, UserContentPart } from \"@/llm/content\";\nimport type { Text } from \"@/llm/content/text\";\nimport type { ModelId, ProviderId } from \"@/llm/providers\";\nimport type { Jsonable } from \"@/llm/types\";\n\n/**\n * A system message that sets context and instructions for the conversation.\n */\nexport type SystemMessage = {\n /** The role of this message. Always \"system\". */\n readonly role: \"system\";\n\n /** The content of this SystemMessage. */\n readonly content: Text;\n};\n\n/**\n * A user message containing input from the user.\n */\nexport type UserMessage = {\n /** The role of this message. Always \"user\". */\n readonly role: \"user\";\n\n /** The content of the user message. */\n readonly content: readonly UserContentPart[];\n\n /** A name identifying the creator of this message. */\n readonly name: string | null;\n};\n\n/**\n * An assistant message containing the model's response.\n */\nexport type AssistantMessage = {\n /** The role of this message. Always \"assistant\". */\n readonly role: \"assistant\";\n\n /** The content of the assistant message. */\n readonly content: readonly AssistantContentPart[];\n\n /** A name identifying the creator of this message. */\n readonly name: string | null;\n\n /** The LLM provider that generated this assistant message, if available. */\n readonly providerId: ProviderId | null;\n\n /** The model identifier of the LLM that generated this assistant message, if available. */\n readonly modelId: ModelId | null;\n\n /** The provider-specific model identifier (e.g. \"gpt-5:responses\"), if available. */\n readonly providerModelName: string | null;\n\n /**\n * The provider-specific raw representation of this assistant message, if available.\n *\n * If raw_content is truthy, then it may be used for provider-specific behavior when\n * resuming an LLM interaction that included this assistant message. For example, we can\n * reuse the provider-specific raw encoding rather than re-encoding the message from it's\n * Mirascope content representation. This may also take advantage of server-side provider\n * context, e.g. identifiers of reasoning context tokens that the provider generated.\n *\n * If present, the content should be encoded as JSON-serializable data, and in a format\n * that matches representation the provider expects representing the Mirascope data.\n *\n * Raw content is not required, as the Mirascope content can also be used to generate\n * a valid input to the provider (potentially without taking advantage of provider-specific\n * reasoning caches, etc). In that case raw content should be left empty.\n */\n readonly rawMessage: Jsonable | null;\n};\n\n/**\n * A message in an LLM interaction.\n *\n * Messages have a role (system, user, or assistant) and content that is a sequence\n * of content parts. The content can include text, images, audio, documents, and\n * tool interactions.\n *\n * For most use cases, prefer the convenience functions `system()`, `user()`, and\n * `assistant()` instead of directly creating `Message` objects.\n *\n * @example\n * ```typescript\n * import { messages } from 'mirascope/llm';\n *\n * const msgs = [\n * messages.system(\"You are a helpful assistant.\"),\n * messages.user(\"Hello, how are you?\"),\n * ];\n * ```\n */\nexport type Message = SystemMessage | UserMessage | AssistantMessage;\n\n/**\n * Type alias for content that can fit into a `UserMessage`.\n */\nexport type UserContent =\n | string\n | UserContentPart\n | readonly (string | UserContentPart)[];\n\n/**\n * Type alias for content that can fit into an `AssistantMessage`.\n */\nexport type AssistantContent =\n | string\n | AssistantContentPart\n | readonly (string | AssistantContentPart)[];\n\n/**\n * Type alias for content that can fit into a `SystemMessage`.\n */\nexport type SystemContent = string | Text;\n\n/**\n * Creates a system message.\n *\n * @param content - The content of the message, which must be a string or Text content.\n * @returns A SystemMessage.\n */\nexport function system(content: SystemContent): SystemMessage {\n const promotedContent: Text =\n typeof content === \"string\" ? { type: \"text\", text: content } : content;\n return {\n role: \"system\",\n content: promotedContent,\n };\n}\n\n/**\n * Creates a user message.\n *\n * @param content - The content of the message, which can be a string or any UserContent,\n * or a sequence of such user content pieces.\n * @param options - Optional parameters.\n * @param options.name - Optional name to identify a specific user in multi-party conversations.\n * @returns A UserMessage.\n */\nexport function user(\n content: UserContent,\n options?: { name?: string | null },\n): UserMessage {\n const contentArray: readonly (string | UserContentPart)[] =\n typeof content === \"string\" || !Array.isArray(content)\n ? [content as string | UserContentPart]\n : content;\n\n const promotedContent: readonly UserContentPart[] = contentArray.map((part) =>\n typeof part === \"string\" ? { type: \"text\" as const, text: part } : part,\n );\n\n return {\n role: \"user\",\n content: promotedContent,\n name: options?.name ?? null,\n };\n}\n\n/**\n * Creates an assistant message.\n *\n * @param content - The content of the message, which can be a string or any AssistantContent,\n * or a sequence of assistant content pieces.\n * @param options - Required and optional parameters.\n * @param options.modelId - Optional id of the model that produced this message.\n * @param options.providerId - Optional identifier of the provider that produced this message.\n * @param options.providerModelName - Optional provider-specific model name.\n * @param options.rawMessage - Optional Jsonable object with provider-specific raw data.\n * @param options.name - Optional name to identify a specific assistant in multi-party conversations.\n * @returns An AssistantMessage.\n */\nexport function assistant(\n content: AssistantContent,\n options: {\n modelId: ModelId | null;\n providerId: ProviderId | null;\n providerModelName?: string | null;\n rawMessage?: Jsonable | null;\n name?: string | null;\n },\n): AssistantMessage {\n const contentArray: readonly (string | AssistantContentPart)[] =\n typeof content === \"string\" || !Array.isArray(content)\n ? [content as string | AssistantContentPart]\n : content;\n\n const promotedContent: readonly AssistantContentPart[] = contentArray.map(\n (part) =>\n typeof part === \"string\" ? { type: \"text\" as const, text: part } : part,\n );\n\n return {\n role: \"assistant\",\n content: promotedContent,\n name: options.name ?? null,\n providerId: options.providerId,\n modelId: options.modelId,\n providerModelName: options.providerModelName ?? null,\n rawMessage: options.rawMessage ?? null,\n };\n}\n","/**\n * Utility functions for message handling.\n */\n\nimport type { Message, UserContent } from \"@/llm/messages/message\";\n\nimport { user } from \"@/llm/messages/message\";\n\n/**\n * Type guard that checks if the content is a sequence of Messages.\n *\n * @param content - Either user content or a sequence of messages.\n * @returns True if content is a sequence of Messages, false otherwise.\n * @throws Error if an empty array is provided.\n */\nexport function isMessages(\n content: UserContent | readonly Message[],\n): content is readonly Message[] {\n if (Array.isArray(content)) {\n if (content.length === 0) {\n throw new Error(\"Empty array may not be used as message content\");\n }\n const first: unknown = content[0];\n return (\n typeof first === \"object\" &&\n first !== null &&\n \"role\" in first &&\n typeof (first as { role: unknown }).role === \"string\" &&\n ((first as { role: string }).role === \"system\" ||\n (first as { role: string }).role === \"user\" ||\n (first as { role: string }).role === \"assistant\")\n );\n }\n return false;\n}\n\n/**\n * Promote a prompt result to a list of messages.\n *\n * If the result is already a list of Messages, returns it as-is.\n * If the result is str/UserContentPart/Sequence of content parts, wraps it in a user message.\n *\n * @param content - Either user content or a sequence of messages.\n * @returns A sequence of Messages.\n */\nexport function promoteToMessages(\n content: UserContent | readonly Message[],\n): readonly Message[] {\n if (isMessages(content)) {\n return content;\n }\n return [user(content)];\n}\n","/**\n * The messages module for LLM interactions.\n *\n * This module defines the message types used in LLM interactions. Messages are represented\n * as a unified `Message` type with different roles (system, user, assistant) and flexible\n * content arrays that can include text, images, audio, documents, and tool interactions.\n */\n\nexport type {\n AssistantContent,\n AssistantMessage,\n Message,\n SystemContent,\n SystemMessage,\n UserContent,\n UserMessage,\n} from \"@/llm/messages/message\";\n\nexport { assistant, system, user } from \"@/llm/messages/message\";\n\nexport { isMessages, promoteToMessages } from \"@/llm/messages/utils\";\n","/**\n * Base abstract interface for provider clients.\n */\n\nimport type { Context } from \"@/llm/context\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { Message, UserContent } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { ProviderId } from \"@/llm/providers/provider-id\";\nimport type { StreamResponseChunk } from \"@/llm/responses/chunks\";\nimport type { RootResponse } from \"@/llm/responses/root-response\";\nimport type {\n Tools,\n ContextTools,\n BaseTool,\n AnyContextTool,\n} from \"@/llm/tools\";\n\nimport {\n APIError,\n ProviderError,\n type APIErrorOptions,\n type ProviderErrorOptions,\n} from \"@/llm/exceptions\";\nimport { user } from \"@/llm/messages\";\nimport { Response } from \"@/llm/responses\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport { StreamResponse } from \"@/llm/responses/stream-response\";\n\n/**\n * A Mirascope error class constructor.\n */\nexport type MirascopeErrorClass =\n | (new (message: string, options: ProviderErrorOptions) => ProviderError)\n | (new (message: string, options: APIErrorOptions) => APIError);\n\n/**\n * Mapping from provider SDK exception types to Mirascope error classes.\n */\nexport type ProviderErrorMap = Array<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [new (...args: any[]) => Error, MirascopeErrorClass]\n>;\n\n/**\n * Base abstract provider for LLM interactions.\n *\n * This class defines the interface for provider implementations.\n * Each provider (Anthropic, OpenAI, etc.) extends this class.\n */\nexport abstract class BaseProvider {\n /**\n * Provider identifier (e.g., \"anthropic\", \"openai\").\n */\n abstract readonly id: ProviderId;\n\n /**\n * Mapping from provider SDK exceptions to Mirascope error types.\n */\n protected abstract readonly errorMap: ProviderErrorMap;\n\n /**\n * Generate a Response by calling this provider's LLM.\n *\n * This method wraps the provider-specific implementation with error handling,\n * converting provider SDK exceptions to Mirascope error types.\n */\n async call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<Response> {\n try {\n return await this._call(args);\n } catch (e) {\n throw this.wrapError(e);\n }\n }\n\n /**\n * Provider-specific implementation of call().\n *\n * Subclasses implement this method to handle the actual API call.\n */\n protected abstract _call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<Response>;\n\n /**\n * Generate a StreamResponse by calling this provider's LLM with streaming.\n *\n * This method wraps the provider-specific implementation with error handling,\n * converting provider SDK exceptions to Mirascope error types. It also wraps\n * the chunk iterator to catch errors during iteration (not just initial call).\n */\n async stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<StreamResponse> {\n let response: StreamResponse;\n try {\n response = await this._stream(args);\n } catch (e) {\n throw this.wrapError(e);\n }\n\n // Wrap the iterator to catch errors during iteration\n response.wrapChunkIterator((iterator) =>\n this._wrapIteratorErrors(iterator),\n );\n\n return response;\n }\n\n /**\n * Wrap an async iterator to catch errors during iteration.\n * Converts provider SDK exceptions to Mirascope error types.\n */\n private async *_wrapIteratorErrors(\n iterator: AsyncIterator<StreamResponseChunk>,\n ): AsyncGenerator<StreamResponseChunk> {\n try {\n let result = await iterator.next();\n while (!result.done) {\n yield result.value;\n result = await iterator.next();\n }\n } catch (e) {\n throw this.wrapError(e);\n }\n }\n\n /**\n * Provider-specific implementation of stream().\n *\n * Subclasses implement this method to handle the actual streaming API call.\n */\n protected abstract _stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<StreamResponse>;\n\n /**\n * Generate a ContextResponse by calling this provider's LLM with context.\n *\n * This method accepts a context for dependency injection, enabling context-aware\n * tools and prompts.\n *\n * @template DepsT - The type of dependencies in the context.\n */\n async contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n try {\n return await this._contextCall(args);\n } catch (e) {\n throw this.wrapError(e);\n }\n }\n\n /**\n * Provider-specific implementation of contextCall().\n *\n * Subclasses implement this method to handle the actual API call with context.\n * Currently functionally equivalent to _call() since context-aware tools are\n * not yet implemented. When context-aware tools are added, this method will\n * handle passing context to tools during execution.\n */\n protected abstract _contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextResponse<DepsT>>;\n\n /**\n * Generate a ContextStreamResponse by calling this provider's LLM with context and streaming.\n *\n * This method accepts a context for dependency injection, enabling context-aware\n * tools and prompts.\n *\n * @template DepsT - The type of dependencies in the context.\n */\n async contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n let response: ContextStreamResponse<DepsT>;\n try {\n response = await this._contextStream(args);\n } catch (e) {\n throw this.wrapError(e);\n }\n\n // Wrap the iterator to catch errors during iteration\n response.wrapChunkIterator((iterator) =>\n this._wrapIteratorErrors(iterator),\n );\n\n return response;\n }\n\n /**\n * Provider-specific implementation of contextStream().\n *\n * Subclasses implement this method to handle the actual streaming API call with context.\n * Currently functionally equivalent to _stream() since context-aware tools are\n * not yet implemented. When context-aware tools are added, this method will\n * handle passing context to tools during execution.\n */\n protected abstract _contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>>;\n\n // ===== Resume Methods =====\n\n /**\n * Generate a new Response by extending a previous response's messages with additional user content.\n *\n * Uses the previous response's tools and output format. The default implementation\n * appends a user message and delegates to call().\n *\n * @param args.modelId - The model ID to use.\n * @param args.response - The previous response to extend.\n * @param args.content - The new user content to append.\n * @param args.params - Optional parameters for the request.\n * @returns A new Response containing the extended conversation.\n */\n async resume(args: {\n modelId: string;\n response: RootResponse;\n content: UserContent;\n params?: Params;\n }): Promise<Response> {\n const messages = [...args.response.messages, user(args.content)];\n const tools = (args.response as { toolkit?: { tools: BaseTool[] } }).toolkit\n ?.tools;\n const format = args.response.format;\n return this.call({\n modelId: args.modelId,\n messages,\n params: args.params,\n tools,\n format,\n });\n }\n\n /**\n * Generate a new StreamResponse by extending a previous response's messages with additional user content.\n *\n * Uses the previous response's tools and output format. The default implementation\n * appends a user message and delegates to stream().\n *\n * @param args.modelId - The model ID to use.\n * @param args.response - The previous response to extend.\n * @param args.content - The new user content to append.\n * @param args.params - Optional parameters for the request.\n * @returns A new StreamResponse for consuming the extended conversation.\n */\n async resumeStream(args: {\n modelId: string;\n response: RootResponse;\n content: UserContent;\n params?: Params;\n }): Promise<StreamResponse> {\n const messages = [...args.response.messages, user(args.content)];\n const tools = (args.response as { toolkit?: { tools: BaseTool[] } }).toolkit\n ?.tools;\n const format = args.response.format;\n return this.stream({\n modelId: args.modelId,\n messages,\n tools,\n format,\n params: args.params,\n });\n }\n\n /**\n * Generate a new ContextResponse by extending a previous response's messages with additional user content.\n *\n * Uses the previous response's tools and output format. The default implementation\n * appends a user message and delegates to contextCall().\n *\n * @template DepsT - The type of dependencies in the context.\n * @param args.ctx - The context containing dependencies for tools.\n * @param args.modelId - The model ID to use.\n * @param args.response - The previous response to extend.\n * @param args.content - The new user content to append.\n * @param args.params - Optional parameters for the request.\n * @returns A new ContextResponse containing the extended conversation.\n */\n async contextResume<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n response: RootResponse;\n content: UserContent;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n const messages = [...args.response.messages, user(args.content)];\n const tools = (\n args.response as { toolkit?: { tools: AnyContextTool<DepsT>[] } }\n ).toolkit?.tools;\n const format = args.response.format;\n return this.contextCall({\n ctx: args.ctx,\n modelId: args.modelId,\n messages,\n tools,\n format,\n params: args.params,\n });\n }\n\n /**\n * Generate a new ContextStreamResponse by extending a previous response's messages with additional user content.\n *\n * Uses the previous response's tools and output format. The default implementation\n * appends a user message and delegates to contextStream().\n *\n * @template DepsT - The type of dependencies in the context.\n * @param args.ctx - The context containing dependencies for tools.\n * @param args.modelId - The model ID to use.\n * @param args.response - The previous response to extend.\n * @param args.content - The new user content to append.\n * @param args.params - Optional parameters for the request.\n * @returns A new ContextStreamResponse for consuming the extended conversation.\n */\n async contextResumeStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n response: RootResponse;\n content: UserContent;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n const messages = [...args.response.messages, user(args.content)];\n const tools = (\n args.response as { toolkit?: { tools: AnyContextTool<DepsT>[] } }\n ).toolkit?.tools;\n const format = args.response.format;\n return this.contextStream({\n ctx: args.ctx,\n modelId: args.modelId,\n messages,\n tools,\n format,\n params: args.params,\n });\n }\n\n /**\n * Wrap a provider SDK exception in the appropriate Mirascope error type.\n */\n protected wrapError(e: unknown): Error {\n if (!(e instanceof Error)) {\n return new Error(String(e));\n }\n\n // Walk through error map to find matching error type\n for (const [ErrorClass, MirascopeErrorClass] of this.errorMap) {\n if (e instanceof ErrorClass) {\n const statusCode = this.getErrorStatus(e);\n\n // Check if this is an APIError subclass (has statusCode)\n if (MirascopeErrorClass.prototype instanceof APIError) {\n return new (MirascopeErrorClass as new (\n message: string,\n options: APIErrorOptions,\n ) => APIError)(e.message, {\n provider: this.id,\n statusCode,\n originalException: e,\n });\n }\n\n return new MirascopeErrorClass(e.message, {\n provider: this.id,\n originalException: e,\n });\n }\n }\n\n // Not in error map - return as-is\n return e;\n }\n\n /**\n * Extract HTTP status code from provider-specific exception.\n *\n * Different SDKs store status codes differently (e.g., .status_code vs .code).\n * Each provider implements this to handle their SDK's convention.\n *\n * @param e - The exception to extract status code from.\n * @returns The HTTP status code if available, undefined otherwise.\n */\n protected abstract getErrorStatus(e: Error): number | undefined;\n}\n\n/**\n * Type alias for any provider instance.\n * Equivalent to Python's `Provider = BaseProvider[Any]`.\n */\nexport type Provider = BaseProvider;\n","/**\n * Reusable utility for handling LLM parameters with strict checking.\n *\n * Ensures all provided params are explicitly handled, preventing silent\n * misconfiguration.\n */\n\nimport type { Params } from \"@/llm/models\";\nimport type { ProviderId } from \"@/llm/providers/provider-id\";\n\nimport { FeatureNotSupportedError } from \"@/llm/exceptions\";\n\n/**\n * Helper for safely accessing and tracking params.\n *\n * Tracks which params have been accessed and ensures all provided params\n * are handled before completing. This prevents silently ignoring user\n * configuration.\n *\n * @example\n * ```typescript\n * // Use the static `with()` method for automatic checking:\n * const result = ParamHandler.with(params, 'anthropic', modelId, (p) => {\n * return {\n * max_tokens: p.getOrDefault('maxTokens', 4096),\n * temperature: p.get('temperature'),\n * };\n * }); // checkAllHandled() called automatically\n * ```\n */\nexport class ParamHandler {\n /**\n * Execute a callback with param handling, automatically checking all params\n * were handled when done.\n *\n * This is the preferred way to use ParamHandler - it ensures checkAllHandled()\n * is always called.\n */\n static with<T>(\n params: Params,\n providerId: ProviderId,\n modelId: string,\n fn: (handler: ParamHandler) => T,\n ): T {\n const handler = new ParamHandler(params, providerId, modelId);\n const result = fn(handler);\n handler.checkAllHandled();\n return result;\n }\n private readonly params: Params;\n private readonly handled: Set<string> = new Set();\n private readonly providerId: ProviderId;\n private readonly modelId: string;\n\n constructor(params: Params, providerId: ProviderId, modelId: string) {\n this.params = params;\n this.providerId = providerId;\n this.modelId = modelId;\n }\n\n /**\n * Get a param value, marking it as handled.\n */\n get<K extends keyof Params>(key: K): Params[K] {\n this.handled.add(key as string);\n return this.params[key];\n }\n\n /**\n * Get a param value with a default, marking it as handled.\n */\n getOrDefault<K extends keyof Params, D>(\n key: K,\n defaultValue: D,\n ): NonNullable<Params[K]> | D {\n this.handled.add(key as string);\n const value = this.params[key];\n return value !== undefined ? value : defaultValue;\n }\n\n /**\n * Check if a param is set (not undefined), marking it as handled.\n */\n has<K extends keyof Params>(key: K): boolean {\n this.handled.add(key as string);\n return this.params[key] !== undefined;\n }\n\n /**\n * Mark a param as not yet implemented - logs a warning if set.\n *\n * Use this for features that are planned but not yet supported.\n */\n warnNotImplemented<K extends keyof Params>(\n key: K,\n featureName: string,\n ): void {\n this.handled.add(key as string);\n const value = this.params[key];\n if (value !== undefined && value !== null) {\n console.warn(\n `[mirascope] Warning: ${featureName} is not yet implemented for ${this.providerId} provider. ` +\n `The '${key as string}' parameter will be ignored.`,\n );\n }\n }\n\n /**\n * Mark a param as unsupported by this provider - logs a warning if set.\n *\n * Use this for features the provider fundamentally doesn't support.\n * The param will be ignored but the call will proceed.\n */\n warnUnsupported<K extends keyof Params>(key: K, message?: string): void {\n this.handled.add(key as string);\n if (this.params[key] !== undefined) {\n console.warn(\n `[mirascope] Warning: ${message ?? `${this.providerId} does not support the '${key as string}' parameter`}. ` +\n `The '${key as string}' parameter will be ignored.`,\n );\n }\n }\n\n /**\n * Verify all provided params were handled.\n *\n * Call this after processing all params. Throws if any param was\n * provided but not explicitly handled.\n */\n checkAllHandled(): void {\n for (const key of Object.keys(this.params)) {\n if (!this.handled.has(key)) {\n throw new FeatureNotSupportedError(\n `unknown param: ${key}`,\n this.providerId,\n this.modelId,\n `Unknown parameter '${key}' is not supported by ${this.providerId}`,\n );\n }\n }\n }\n}\n","/**\n * Base provider types and utilities.\n */\n\nexport { BaseProvider } from \"@/llm/providers/base/base-provider\";\nexport type {\n MirascopeErrorClass,\n Provider,\n ProviderErrorMap,\n} from \"@/llm/providers/base/base-provider\";\n\nexport { ParamHandler } from \"@/llm/providers/base/param-handler\";\n","/**\n * Anthropic registered LLM models.\n */\n\nimport type { AnthropicKnownModels } from \"@/llm/providers/anthropic/model-info\";\n\n/**\n * The Anthropic model IDs registered with Mirascope.\n */\nexport type AnthropicModelId = AnthropicKnownModels | (string & {});\n\n/**\n * Extract the Anthropic model name from the ModelId.\n *\n * @param modelId - Full model ID (e.g. \"anthropic/claude-sonnet-4-5\" or \"anthropic-beta/claude-sonnet-4-5\")\n * @returns Provider-specific model ID (e.g. \"claude-sonnet-4-5\")\n */\nexport function modelName(modelId: AnthropicModelId): string {\n return modelId.replace(/^anthropic-beta\\//, \"\").replace(/^anthropic\\//, \"\");\n}\n","/**\n * Shared utilities for provider implementations.\n */\n\nimport type { Params } from \"@/llm/models\";\n\n/**\n * Extract includeThoughts setting from params.\n *\n * @param params - The params object\n * @returns Whether to include thoughts in the response (defaults to false)\n */\nexport function getIncludeThoughts(params: Params = {}): boolean {\n return params.thinking?.includeThoughts ?? false;\n}\n","/**\n * Finish reason indicating why the model stopped generating.\n */\n\n/**\n * Possible reasons why generation stopped.\n */\nexport const FinishReason = {\n /** Model ran out of tokens. */\n MAX_TOKENS: \"max_tokens\",\n /** Model refused to generate. */\n REFUSAL: \"refusal\",\n /** Context length exceeded. */\n CONTEXT_LENGTH_EXCEEDED: \"context_length_exceeded\",\n} as const;\n\n/**\n * Type representing a finish reason value.\n */\nexport type FinishReason = (typeof FinishReason)[keyof typeof FinishReason];\n","/**\n * Token usage tracking for LLM responses.\n */\n\n/**\n * Token usage statistics for a response.\n */\nexport interface Usage {\n /**\n * Total input tokens (includes cache tokens).\n */\n readonly inputTokens: number;\n\n /**\n * Total output tokens (includes reasoning tokens).\n */\n readonly outputTokens: number;\n\n /**\n * Tokens read from cache.\n */\n readonly cacheReadTokens: number;\n\n /**\n * Tokens written to cache.\n */\n readonly cacheWriteTokens: number;\n\n /**\n * Tokens used for thinking/reasoning.\n */\n readonly reasoningTokens: number;\n\n /**\n * Provider-specific raw usage object.\n */\n readonly raw: unknown;\n}\n\n/**\n * Create a Usage object with default values.\n */\nexport function createUsage(options: Partial<Usage> = {}): Usage {\n return {\n inputTokens: options.inputTokens ?? 0,\n outputTokens: options.outputTokens ?? 0,\n cacheReadTokens: options.cacheReadTokens ?? 0,\n cacheWriteTokens: options.cacheWriteTokens ?? 0,\n reasoningTokens: options.reasoningTokens ?? 0,\n raw: options.raw ?? null,\n };\n}\n\n/**\n * Calculate total tokens from usage.\n */\nexport function totalTokens(usage: Usage): number {\n return usage.inputTokens + usage.outputTokens;\n}\n","/**\n * Tool type definitions for LLM function calling.\n *\n * Provides interfaces for tools that can be called by LLMs,\n * including base types for toolkit storage and callable types\n * for direct invocation.\n */\n\nimport type { ToolCall } from \"@/llm/content/tool-call\";\nimport type { ToolOutput } from \"@/llm/content/tool-output\";\nimport type { Context } from \"@/llm/context\";\nimport type { ProviderTool } from \"@/llm/tools/provider-tool\";\nimport type { ToolSchema } from \"@/llm/tools/tool-schema\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\n/**\n * Duck-typed Zod schema interface for optional Zod support.\n *\n * This allows accepting Zod schemas without requiring Zod as a dependency.\n * We detect Zod schemas at runtime by checking for these properties.\n *\n * Compatible with both Zod 3 (description in _def.description) and\n * Zod 4 (description may be at schema.description or _def.description).\n */\nexport interface ZodLike {\n /** Internal Zod definition - structure varies by version */\n // Using 'object' instead of Record<string, unknown> for Zod 4 compatibility\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly _def: any;\n /** Description may be at top level in Zod 4 */\n readonly description?: string;\n /** Output type for type inference (Zod internal) */\n readonly _output?: unknown;\n safeParse(data: unknown): {\n success: boolean;\n data?: unknown;\n error?: unknown;\n };\n}\n\n/**\n * Infer the output type from a Zod-like schema.\n *\n * Uses Zod's internal `_output` property for type inference.\n * This allows TypeScript to infer tool argument types from Zod schemas.\n *\n * @template Z - The Zod schema type.\n */\nexport type InferZod<Z extends ZodLike> = Z extends { _output: infer T }\n ? T & Record<string, unknown>\n : Record<string, unknown>;\n\n/**\n * Type discriminator for regular tools.\n * Used at runtime to distinguish from context tools.\n */\nexport const TOOL_TYPE = \"tool\" as const;\n\n/**\n * Type discriminator for context tools.\n * Used at runtime to distinguish from regular tools.\n */\nexport const CONTEXT_TOOL_TYPE = \"context_tool\" as const;\n\n/**\n * Base interface for tools without the callable signature.\n *\n * This is used by Toolkit to store tools without variance issues.\n * The callable signature in Tool<T> causes contravariance problems\n * when storing tools with different argument types in a collection.\n */\nexport interface BaseTool extends ToolSchema {\n /**\n * Type discriminator - always 'tool' for regular tools.\n * Used at runtime to distinguish from context tools.\n */\n readonly __toolType: typeof TOOL_TYPE;\n\n /**\n * Execute the tool from a ToolCall.\n *\n * @param toolCall - The tool call from the LLM.\n * @returns A ToolOutput with the result or error.\n */\n execute(toolCall: ToolCall): Promise<ToolOutput<Jsonable>>;\n\n /**\n * The Zod validator used for this tool, if any.\n * Present when tool was created with `validator` option.\n */\n readonly validator: ZodLike | undefined;\n}\n\n/**\n * A defined tool that can be called by an LLM.\n *\n * Tools extend ToolSchema (a tool IS a schema) and are callable.\n * Calling a tool directly executes it with the provided arguments.\n *\n * @template T - The type of arguments the tool accepts.\n */\nexport interface Tool<\n T extends Record<string, unknown> = Record<string, unknown>,\n> extends BaseTool {\n /**\n * Call the tool directly with arguments.\n * This is equivalent to Python's `tool.__call__(*args, **kwargs)`.\n *\n * @param args - The arguments to pass to the tool.\n * @returns The tool result.\n */\n (args: T): Promise<Jsonable>;\n}\n\n/**\n * Base interface for context tools without the callable signature.\n *\n * This is used by ContextToolkit to store tools without variance issues.\n *\n * @template DepsT - The type of dependencies in the context.\n */\nexport interface BaseContextTool<DepsT = unknown> extends ToolSchema {\n /**\n * Type discriminator - always 'context_tool' for context tools.\n * Used at runtime to distinguish from regular tools.\n */\n readonly __toolType: typeof CONTEXT_TOOL_TYPE;\n\n /**\n * Execute the tool from a ToolCall with context.\n *\n * @param ctx - The context containing dependencies.\n * @param toolCall - The tool call from the LLM.\n * @returns A ToolOutput with the result or error.\n */\n execute(\n ctx: Context<DepsT>,\n toolCall: ToolCall,\n ): Promise<ToolOutput<Jsonable>>;\n\n /**\n * The Zod validator used for this tool, if any.\n * Present when tool was created with `validator` option.\n */\n readonly validator: ZodLike | undefined;\n}\n\n/**\n * A defined context tool with dependency injection.\n *\n * Context tools extend ToolSchema and are callable with a context argument.\n *\n * @template T - The type of arguments the tool accepts.\n * @template DepsT - The type of dependencies in the context.\n */\nexport interface ContextTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n DepsT = unknown,\n> extends BaseContextTool<DepsT> {\n /**\n * Call the tool directly with context and arguments.\n * This is equivalent to Python's `tool.__call__(ctx, *args, **kwargs)`.\n *\n * @param ctx - The context containing dependencies.\n * @param args - The arguments to pass to the tool.\n * @returns The tool result.\n */\n (ctx: Context<DepsT>, args: T): Promise<Jsonable>;\n}\n\n/**\n * Union type for any tool (regular or context).\n */\nexport type AnyTool = Tool | ContextTool;\n\n/**\n * Union type for tools that can be used in context paths.\n *\n * Context paths accept BOTH regular tools AND context tools,\n * matching Python's `ContextTools[DepsT] = Tool | ContextTool[DepsT]`.\n *\n * @template DepsT - The type of dependencies in the context.\n */\nexport type AnyContextTool<DepsT = unknown> = BaseTool | BaseContextTool<DepsT>;\n\n/**\n * Type alias for any tool schema.\n *\n * This is used as a type bound in generic toolkit storage.\n * Matches Python's `AnyToolSchema = ToolSchema[AnyToolFn]`.\n */\nexport type AnyToolSchema = BaseTool | BaseContextTool;\n\n// =============================================================================\n// Array Type Aliases (matching Python's Sequence types)\n// =============================================================================\n\n/**\n * Type alias for an array of regular tools.\n * Matches Python's `Tools = Sequence[Tool | ProviderTool]`.\n */\nexport type Tools = readonly (BaseTool | ProviderTool)[];\n\n/**\n * Type alias for an array of tools usable in context paths.\n * Accepts both regular tools AND context tools, plus provider tools.\n * Matches Python's `ContextTools[DepsT] = Sequence[Tool | ContextTool[DepsT] | ProviderTool]`.\n *\n * @template DepsT - The type of dependencies in the context.\n */\nexport type ContextTools<DepsT = unknown> = readonly (\n | AnyContextTool<DepsT>\n | ProviderTool\n)[];\n\n// =============================================================================\n// Tool Function Types\n// =============================================================================\n\nexport type ToolFn<\n T extends Record<string, unknown> = Record<string, unknown>,\n R extends Jsonable = Jsonable,\n> = (args: T) => Promise<R> | R;\n\nexport type ContextToolFn<\n T extends Record<string, unknown> = Record<string, unknown>,\n DepsT = unknown,\n R extends Jsonable = Jsonable,\n> = (ctx: Context<DepsT>, args: T) => Promise<R> | R;\n\nexport type AnyToolFn = ToolFn | ContextToolFn;\n\n// =============================================================================\n// Type Guards\n// =============================================================================\n\n/**\n * Type guard to check if a tool is a context tool.\n *\n * @param tool - The tool to check.\n * @returns True if the tool is a context tool.\n */\nexport function isContextTool<DepsT = unknown>(\n tool: AnyContextTool<DepsT>,\n): tool is BaseContextTool<DepsT> {\n return tool.__toolType === CONTEXT_TOOL_TYPE;\n}\n","import type { Jsonable } from \"@/llm/types/jsonable\";\n\n/**\n * Tool output content representing the result of a tool call.\n *\n * Contains the result of executing a tool, or an error if the tool failed.\n * The generic type T allows for typed results when the tool output type is known.\n */\nexport type ToolOutput<T extends Jsonable = Jsonable> = {\n readonly type: \"tool_output\";\n\n /** The ID of the tool call that this output is for. */\n readonly id: string;\n\n /** The name of the tool that created this output. */\n readonly name: string;\n\n /**\n * The result of calling the tool.\n *\n * If the tool executed successfully, this will be the tool output.\n * If the tool errored, this will be the error message, as a string.\n */\n readonly result: T | string;\n\n /** The error from calling the tool, if any. */\n readonly error: Error | null;\n};\n\n/**\n * Factory methods for creating ToolOutput instances.\n */\nexport const ToolOutput = {\n /**\n * Create a ToolOutput with explicit parameters.\n */\n create: <T extends Jsonable>(\n id: string,\n name: string,\n result: T | string,\n error: Error | null = null,\n ): ToolOutput<T> => ({\n type: \"tool_output\",\n id,\n name,\n result,\n error,\n }),\n\n /**\n * Create a successful ToolOutput.\n */\n success: <T extends Jsonable>(\n id: string,\n name: string,\n result: T,\n ): ToolOutput<T> => ({\n type: \"tool_output\",\n id,\n name,\n result,\n error: null,\n }),\n\n /**\n * Create a failed ToolOutput.\n */\n failure: (id: string, name: string, error: Error): ToolOutput => ({\n type: \"tool_output\",\n id,\n name,\n result: error.message,\n error,\n }),\n};\n","/**\n * Formatting types for structured LLM outputs.\n *\n * Provides types for defining structured output formats that LLMs\n * should follow when generating responses.\n */\n\nimport type { ToolParameterSchema, ZodLike } from \"@/llm/tools\";\n\n/**\n * Formatting mode determines how the structured output is requested from the LLM.\n *\n * - `strict`: Use provider's strict structured output mode (requires provider support)\n * - `json`: Use JSON mode with schema instructions in system prompt\n * - `tool`: Use tool calling with a format tool to get structured output\n * - `parser`: Use custom OutputParser for non-JSON formats\n */\nexport type FormattingMode = \"strict\" | \"json\" | \"tool\" | \"parser\";\n\n/**\n * User-facing format specification.\n *\n * Can be one of:\n * - A TypeScript interface/type (transformer injects __schema)\n * - A Zod schema (used for both schema and validation)\n * - { schema: T, validator: ZodSchema } for explicit control\n * - Format (from defineFormat)\n * - OutputParser (from defineOutputParser)\n *\n * @template T - The type of the formatted output.\n */\nexport interface FormatSpec<T = unknown> {\n /**\n * The schema marker for the TypeScript type.\n * The compile-time transformer uses this to determine which type to extract schema from.\n */\n schema?: T;\n\n /**\n * Optional Zod schema for runtime validation.\n * When provided, parsed output will be validated against this schema.\n */\n validator?: ZodLike;\n\n /**\n * Internal: JSON schema injected by the compile-time transformer.\n * Users should not set this directly.\n */\n __schema?: ToolParameterSchema;\n}\n\n/**\n * Check if a value is a Zod-like schema.\n *\n * @param value - The value to check.\n * @returns True if the value has Zod-like properties.\n */\nexport function isZodSchema(value: unknown): value is ZodLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"_def\" in value &&\n typeof (value as ZodLike).safeParse === \"function\"\n );\n}\n\n/**\n * Check if a value is a FormatSpec object.\n *\n * @param value - The value to check.\n * @returns True if the value is a FormatSpec object.\n */\nexport function isFormatSpec(value: unknown): value is FormatSpec {\n if (typeof value !== \"object\" || value === null) return false;\n\n // FormatSpec has optional schema, validator, or __schema\n const obj = value as Record<string, unknown>;\n return (\n \"__schema\" in obj ||\n \"validator\" in obj ||\n (\"schema\" in obj && !(\"__formatType\" in obj))\n );\n}\n\n// Import Format and OutputParser types for ExtractFormatType\n// These are imported lazily to avoid circular dependencies\nimport type { Format } from \"@/llm/formatting/format\";\nimport type { OutputParser } from \"@/llm/formatting/output-parser\";\n\n/**\n * Any format input that can be provided to defineCall/definePrompt.\n * Used for constraining format type parameters.\n *\n * @template F - The output type of the format. Defaults to unknown.\n */\nexport type FormatInput<F = unknown> =\n | Format<F>\n | FormatSpec<F>\n | OutputParser<F>\n | ZodLike\n | null\n | undefined;\n\n/**\n * Union of all possible format input types (non-generic version).\n * Used for type narrowing in resolveFormat.\n */\nexport type AnyFormatInput =\n | Format<unknown>\n | FormatSpec<unknown>\n | OutputParser<unknown>\n | ZodLike\n | null\n | undefined;\n\n/**\n * Extract the format output type from a format input.\n *\n * This utility type enables automatic type inference when using formats\n * with defineCall and definePrompt, eliminating the need to specify the\n * format type parameter explicitly.\n *\n * @template F - The format input type.\n * @returns The extracted output type, or `unknown` if not determinable.\n *\n * @example\n * ```typescript\n * // ExtractFormatType<Format<Book>> = Book\n * // ExtractFormatType<OutputParser<Recipe>> = Recipe\n * // ExtractFormatType<typeof BookSchema> = z.infer<typeof BookSchema>\n * // ExtractFormatType<null> = unknown\n * ```\n */\nexport type ExtractFormatType<F> =\n // Format<F> -> F\n F extends Format<infer F>\n ? F\n : // OutputParser<F> -> F\n F extends OutputParser<infer F>\n ? F\n : // FormatSpec<F> -> F\n F extends FormatSpec<infer F>\n ? F\n : // Zod schema - infer from _output type (used by z.infer)\n F extends { _output: infer O }\n ? O\n : // null/undefined -> unknown\n F extends null | undefined\n ? unknown\n : // Fallback\n unknown;\n","/**\n * Output parser for custom format parsing.\n *\n * Provides OutputParser type and defineOutputParser function for creating\n * custom parsers for non-JSON formats like XML, YAML, CSV, or any custom\n * text structure.\n */\n\nimport type { AnyResponse } from \"@/llm/responses/root-response\";\nexport type { AnyResponse };\n\n/**\n * Type discriminator symbol for OutputParser.\n * Used at runtime to distinguish OutputParsers from other format types.\n */\nexport const OUTPUT_PARSER_TYPE = Symbol(\"OUTPUT_PARSER_TYPE\");\n\n/**\n * Represents a custom output parser for non-JSON formats.\n *\n * OutputParser wraps a parsing function and stores formatting instructions.\n * Unlike structured outputs (JSON schema, tools, strict mode), OutputParser\n * works with raw text responses and custom parsing logic.\n *\n * @template T - The type of the parsed output.\n *\n * @example\n * ```typescript\n * const xmlParser = defineOutputParser({\n * formattingInstructions: 'Return XML: <book><title>...</title></book>',\n * parser: (response) => {\n * const text = response.text();\n * // Parse XML and return Book\n * return { title: '...', author: '...' };\n * },\n * });\n *\n * const response = await model.call('Recommend a book', { format: xmlParser });\n * const book = response.parse(); // Returns parsed Book\n * ```\n */\nexport interface OutputParser<T = unknown> {\n /**\n * Type discriminator for runtime identification.\n */\n readonly __outputParserType: typeof OUTPUT_PARSER_TYPE;\n\n /**\n * The name of the output parser (derived from parser function name).\n */\n readonly name: string;\n\n /**\n * Instructions for the LLM on how to format its output.\n * These are added to the system prompt.\n */\n readonly formattingInstructions: string;\n\n /**\n * Parse the response using the wrapped function.\n *\n * @param response - The response from the LLM call.\n * @returns The parsed output of type T.\n */\n (response: AnyResponse): T;\n}\n\n/**\n * Arguments for defining an output parser.\n *\n * @template T - The type of the parsed output.\n */\nexport interface OutputParserArgs<T> {\n /**\n * Instructions for the LLM on how to format the output.\n * These will be added to the system prompt.\n */\n formattingInstructions: string;\n\n /**\n * The parsing function that takes a Response and returns the parsed output.\n *\n * @param response - The response from the LLM call.\n * @returns The parsed output of type T.\n */\n parser: (response: AnyResponse) => T;\n}\n\n/**\n * Create an output parser for custom format parsing.\n *\n * Use this function to create custom parsers for non-JSON formats like\n * XML, YAML, CSV, or any custom text structure. The parser function\n * receives the full Response object and returns the parsed output.\n *\n * @template T - The type of the parsed output.\n * @param args - The output parser arguments.\n * @returns An OutputParser instance.\n *\n * @example XML parsing\n * ```typescript\n * interface Book {\n * title: string;\n * author: string;\n * }\n *\n * const bookXmlParser = defineOutputParser<Book>({\n * formattingInstructions: `\n * Return the book information in this XML structure:\n * <book>\n * <title>Book Title</title>\n * <author>Author Name</author>\n * </book>\n * `,\n * parser: (response) => {\n * const text = response.text();\n * // Parse XML (example using regex, use proper parser in production)\n * const titleMatch = text.match(/<title>([^<]+)<\\/title>/);\n * const authorMatch = text.match(/<author>([^<]+)<\\/author>/);\n * return {\n * title: titleMatch?.[1] ?? '',\n * author: authorMatch?.[1] ?? '',\n * };\n * },\n * });\n *\n * const response = await model.call('Recommend a fantasy book', {\n * format: bookXmlParser,\n * });\n * const book = response.parse(); // Type: Book\n * ```\n *\n * @example CSV parsing\n * ```typescript\n * interface Book {\n * title: string;\n * author: string;\n * rating: number;\n * }\n *\n * const booksCsvParser = defineOutputParser<Book[]>({\n * formattingInstructions: `\n * Return book information as CSV format with header:\n * title,author,rating\n * Book 1,Author 1,5\n * Book 2,Author 2,4\n * `,\n * parser: (response) => {\n * const text = response.text();\n * const lines = text.trim().split('\\n').slice(1); // Skip header\n * return lines.map((line) => {\n * const [title, author, rating] = line.split(',').map((s) => s.trim());\n * return { title, author, rating: parseInt(rating, 10) };\n * });\n * },\n * });\n * ```\n */\nexport function defineOutputParser<T>(\n args: OutputParserArgs<T>,\n): OutputParser<T> {\n const { formattingInstructions, parser } = args;\n\n // Create the callable function\n const outputParser = ((response: AnyResponse): T => {\n return parser(response);\n }) as OutputParser<T>;\n\n // Add OutputParser properties\n Object.defineProperty(outputParser, \"__outputParserType\", {\n value: OUTPUT_PARSER_TYPE,\n enumerable: false,\n writable: false,\n });\n Object.defineProperty(outputParser, \"name\", {\n /* v8 ignore next */ // Fallback name rarely needed with named functions\n value: parser.name || \"outputParser\",\n enumerable: true,\n writable: false,\n });\n Object.defineProperty(outputParser, \"formattingInstructions\", {\n value: formattingInstructions,\n enumerable: true,\n writable: false,\n });\n\n return outputParser;\n}\n\n/**\n * Check if an object is an OutputParser.\n *\n * This is a type guard function that narrows the type of `obj` to\n * `OutputParser<unknown>` when it returns true.\n *\n * @param obj - The object to check.\n * @returns True if the object is an OutputParser, false otherwise.\n */\nexport function isOutputParser(obj: unknown): obj is OutputParser<unknown> {\n return (\n typeof obj === \"function\" &&\n \"__outputParserType\" in obj &&\n (obj as OutputParser).__outputParserType === OUTPUT_PARSER_TYPE\n );\n}\n","/**\n * Format class and utilities for structured LLM outputs.\n *\n * Provides the Format interface and functions for creating and resolving\n * structured output formats.\n */\n\nimport type { ToolParameterSchema, ToolSchema, ZodLike } from \"@/llm/tools\";\n\nimport {\n isOutputParser,\n type OutputParser,\n} from \"@/llm/formatting/output-parser\";\nimport {\n isFormatSpec,\n isZodSchema,\n type FormattingMode,\n type FormatSpec,\n} from \"@/llm/formatting/types\";\n\n/**\n * Reserved tool name for formatted output tools.\n * This is used internally to convert formatted output tool calls to textual output.\n */\nexport const FORMAT_TOOL_NAME = \"__mirascope_formatted_output_tool__\";\n\n/**\n * System prompt instructions for tool mode formatting.\n */\nexport const TOOL_MODE_INSTRUCTIONS = `Always respond to the user's query using the ${FORMAT_TOOL_NAME} tool for structured output.`;\n\n/**\n * System prompt instructions for JSON mode formatting.\n * The {json_schema} placeholder will be replaced with the actual schema.\n */\nexport const JSON_MODE_INSTRUCTIONS =\n \"Respond only with valid JSON that matches this exact schema:\\n{json_schema}\";\n\n/**\n * Type discriminator symbol for Format.\n */\nexport const FORMAT_TYPE = Symbol(\"FORMAT_TYPE\");\n\n/**\n * Represents a resolved structured output format.\n *\n * A Format contains all metadata needed to describe a structured output type\n * to the LLM, including the JSON schema, formatting mode, and optional validator.\n *\n * Format objects are created by `defineFormat` or `resolveFormat` and are used\n * internally by providers to configure structured output requests.\n *\n * @template T - The type of the formatted output.\n */\nexport interface Format<T = unknown> {\n /**\n * Type discriminator for runtime identification.\n */\n readonly __formatType: typeof FORMAT_TYPE;\n\n /**\n * The name of the format (derived from the type name).\n */\n readonly name: string;\n\n /**\n * A description of the format, if available.\n */\n readonly description: string | null;\n\n /**\n * JSON schema representation of the structured output format.\n */\n readonly schema: ToolParameterSchema;\n\n /**\n * The formatting mode determining how the LLM is configured.\n */\n readonly mode: FormattingMode;\n\n /**\n * Optional Zod schema for runtime validation.\n */\n readonly validator: ZodLike | null;\n\n /**\n * Optional OutputParser for custom parsing.\n * When set, indicates this format uses custom parsing instead of JSON.\n */\n readonly outputParser: OutputParser<T> | null;\n\n /**\n * The formatting instructions to add to the system prompt.\n */\n readonly formattingInstructions: string | null;\n\n /**\n * Create a ToolSchema for this format.\n * Used when mode is 'tool' to generate a tool for structured output.\n */\n createToolSchema(): ToolSchema;\n}\n\n/**\n * Check if an object is a Format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a Format.\n */\nexport function isFormat(obj: unknown): obj is Format<unknown> {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"__formatType\" in obj &&\n (obj as Format).__formatType === FORMAT_TYPE\n );\n}\n\n/**\n * Options for defineFormat when using TypeScript interfaces.\n *\n * The `__schema` field is injected by the compile-time transformer based on\n * the generic type parameter T.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- T is for type inference\nexport interface DefineFormatOptions<T = unknown> {\n /**\n * The formatting mode to use.\n */\n mode: FormattingMode;\n\n /**\n * Optional Zod schema for runtime validation.\n */\n validator?: ZodLike;\n\n /**\n * Internal: JSON schema injected by compile-time transformer.\n * Do not set this manually - it is populated automatically when using\n * the Mirascope transformer with TypeScript interfaces.\n */\n __schema?: ToolParameterSchema;\n}\n\n/**\n * Create a Format with explicit mode control.\n *\n * Use this to create structured output formats for LLM responses. The format\n * can be derived from a Zod schema (via `validator`) or a TypeScript interface\n * (via the compile-time transformer which injects `__schema`).\n *\n * @template T - The type of the formatted output.\n * @param options - The format options including mode and optional validator.\n * @returns A Format object.\n *\n * @example With Zod schema\n * ```typescript\n * const BookSchema = z.object({ title: z.string(), author: z.string() });\n * const bookFormat = defineFormat<Book>({ mode: 'tool', validator: BookSchema });\n * const response = await model.call('Recommend a book', { format: bookFormat });\n * const book = response.parse(); // Typed as Book\n * ```\n *\n * @example With TypeScript interface (requires transformer)\n * ```typescript\n * interface Book { title: string; author: string; }\n *\n * // Transformer injects __schema at compile time\n * const bookFormat = defineFormat<Book>({ mode: 'json' });\n * ```\n */\nexport function defineFormat<T>(options: DefineFormatOptions<T>): Format<T> {\n const { mode, validator, __schema } = options;\n\n // If we have a validator, extract schema from it\n if (validator) {\n return createFormatFromZod<T>(validator, mode);\n }\n\n // Must have __schema (injected by transformer) at this point\n if (!__schema) {\n throw new Error(\n \"Format specification is missing schema. \" +\n \"Provide a Zod schema via the `validator` option, \" +\n \"or use the Mirascope TypeScript transformer with a type parameter.\",\n );\n }\n\n return createFormatFromSchema<T>(__schema, null, mode);\n}\n\n/**\n * Resolve any format input to internal Format representation.\n *\n * This function handles all possible format inputs and converts them to\n * a Format object. It's used internally by providers to normalize format\n * specifications.\n *\n * @template T - The type of the formatted output.\n * @param formatArg - The format specification (can be Format, FormatSpec, ZodLike, OutputParser, or null).\n * @param defaultMode - The default mode to use when not explicitly specified.\n * @returns A Format object or null.\n */\nexport function resolveFormat<T>(\n formatArg:\n | Format<T>\n | FormatSpec<T>\n | ZodLike\n | OutputParser<T>\n | null\n | undefined,\n defaultMode: FormattingMode,\n): Format<T> | null {\n // Handle null/undefined\n if (formatArg === null || formatArg === undefined) {\n return null;\n }\n\n // Handle Format (pass through)\n if (isFormat(formatArg)) {\n return formatArg;\n }\n\n // Handle OutputParser\n if (isOutputParser(formatArg)) {\n return createFormatFromOutputParser<T>(formatArg);\n }\n\n // Handle Zod schema\n if (isZodSchema(formatArg)) {\n return createFormatFromZod<T>(formatArg, defaultMode);\n }\n\n // Handle FormatSpec\n if (isFormatSpec(formatArg)) {\n const spec = formatArg;\n\n // If we have a validator that's a Zod schema, use it for schema if __schema missing\n if (spec.validator && !spec.__schema) {\n return createFormatFromZod<T>(spec.validator, defaultMode);\n }\n\n // Must have __schema\n if (!spec.__schema) {\n throw new Error(\n \"Format specification is missing __schema. \" +\n \"Either use the Mirascope TypeScript transformer, provide a Zod schema, \" +\n \"or provide __schema explicitly.\",\n );\n }\n\n return createFormatFromSchema<T>(\n spec.__schema,\n spec.validator ?? null,\n defaultMode,\n );\n }\n\n // Unknown format type - shouldn't happen with proper types\n throw new Error(`Unknown format type: ${typeof formatArg}`);\n}\n\n// =============================================================================\n// Internal helper functions\n// =============================================================================\n\n/**\n * Create a Format from a Zod schema.\n */\nfunction createFormatFromZod<T>(\n zodSchema: ZodLike,\n mode: FormattingMode,\n): Format<T> {\n // Extract JSON schema from Zod\n // Note: In production, we'd use zod-to-json-schema or similar\n // For now, we assume the transformer or runtime handles this\n const schema = extractSchemaFromZod(zodSchema);\n const name = extractNameFromZod(zodSchema);\n // Zod 4: description at top level, Zod 3: in _def.description\n const def = zodSchema._def as { description?: string };\n const description = zodSchema.description ?? def.description ?? null;\n\n return createFormat<T>({\n name,\n description,\n schema,\n mode,\n validator: zodSchema,\n outputParser: null,\n });\n}\n\n/**\n * Create a Format from a ToolParameterSchema.\n */\nfunction createFormatFromSchema<T>(\n schema: ToolParameterSchema,\n validator: ZodLike | null,\n mode: FormattingMode,\n): Format<T> {\n // Extract name from schema title or use default\n const name =\n ((schema as unknown as Record<string, unknown>).title as\n | string\n | undefined) ?? \"FormattedOutput\";\n\n return createFormat<T>({\n name,\n description: null,\n schema,\n mode,\n validator,\n outputParser: null,\n });\n}\n\n/**\n * Create a Format from an OutputParser.\n */\nfunction createFormatFromOutputParser<T>(parser: OutputParser<T>): Format<T> {\n // OutputParser has empty schema - it uses custom parsing\n const emptySchema: ToolParameterSchema = {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: false,\n };\n\n return createFormat<T>({\n name: parser.name,\n description: null,\n schema: emptySchema,\n mode: \"parser\",\n validator: null,\n outputParser: parser,\n });\n}\n\n/**\n * Internal Format creation options.\n */\ninterface CreateFormatOptions<T> {\n name: string;\n description: string | null;\n schema: ToolParameterSchema;\n mode: FormattingMode;\n validator: ZodLike | null;\n outputParser: OutputParser<T> | null;\n}\n\n/**\n * Create a Format object with all properties.\n */\nfunction createFormat<T>(options: CreateFormatOptions<T>): Format<T> {\n const { name, description, schema, mode, validator, outputParser } = options;\n\n // Compute formatting instructions based on mode\n let formattingInstructions: string | null;\n if (outputParser) {\n formattingInstructions = outputParser.formattingInstructions;\n } else if (mode === \"tool\") {\n formattingInstructions = TOOL_MODE_INSTRUCTIONS;\n } else if (mode === \"json\") {\n const jsonSchema = JSON.stringify(schema, null, 2);\n formattingInstructions = JSON_MODE_INSTRUCTIONS.replace(\n \"{json_schema}\",\n jsonSchema,\n );\n } else {\n // strict mode - let provider handle instructions\n formattingInstructions = null;\n }\n\n return {\n __formatType: FORMAT_TYPE,\n name,\n description,\n schema,\n mode,\n validator,\n outputParser,\n formattingInstructions,\n createToolSchema(): ToolSchema {\n const toolDescription = `Use this tool to extract data in ${name} format for a final response.${\n description ? \"\\n\" + description : \"\"\n }`;\n\n // Get all property keys as required\n /* v8 ignore next */ // properties always exists in valid JSON schemas\n const properties = schema.properties ?? {};\n const required = Object.keys(properties);\n\n // Build parameters object - include $defs if present\n const parameters: ToolParameterSchema = {\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n ...(schema.$defs && { $defs: schema.$defs }),\n };\n\n return {\n name: FORMAT_TOOL_NAME,\n description: toolDescription,\n parameters,\n strict: undefined, // Provider determines strict mode\n };\n },\n };\n}\n\n/**\n * Extract JSON schema from a Zod schema.\n *\n * Supports both Zod 3 and Zod 4:\n * - Zod 4: Uses toJSONSchema() method if available\n * - Zod 3: Manually extracts from _def structure\n */\nexport function extractSchemaFromZod(zodSchema: ZodLike): ToolParameterSchema {\n const schemaAny = zodSchema as unknown as Record<string, unknown>;\n\n // Zod 4: Use toJSONSchema() if available (preferred method)\n if (typeof schemaAny.toJSONSchema === \"function\") {\n try {\n const jsonSchema = (schemaAny.toJSONSchema as () => unknown)() as Record<\n string,\n unknown\n >;\n // Ensure additionalProperties is false for strict matching\n // Note: ?? fallbacks are for edge cases where toJSONSchema returns incomplete data\n const properties =\n /* v8 ignore next */\n (jsonSchema.properties as ToolParameterSchema[\"properties\"]) ?? {};\n const required =\n /* v8 ignore next */\n (jsonSchema.required as ToolParameterSchema[\"required\"]) ?? [];\n const $defs = jsonSchema.$defs as ToolParameterSchema[\"$defs\"];\n\n // Include $defs if present (for nested schemas)\n /* v8 ignore start */\n if ($defs) {\n return {\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n $defs,\n } as const satisfies ToolParameterSchema;\n }\n /* v8 ignore end */\n return {\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n } as const satisfies ToolParameterSchema;\n } catch /* v8 ignore start */ {\n // Fall through to manual extraction\n } /* v8 ignore end */\n }\n\n // Zod 3/4 fallback: Manually extract from _def\n if (typeof schemaAny._def === \"object\" && schemaAny._def !== null) {\n const def = schemaAny._def as Record<string, unknown>;\n\n // Zod 3: typeName is 'ZodObject', shape is a function\n if (def.typeName === \"ZodObject\" && typeof def.shape === \"function\") {\n return extractSchemaFromZod3(def);\n }\n\n /* v8 ignore start */\n // Zod 4: type is 'object', shape is a getter (object)\n if (def.type === \"object\" && typeof def.shape === \"object\") {\n return extractSchemaFromZod4(def);\n }\n /* v8 ignore end */\n }\n\n // Fallback: return empty schema\n // The transformer should inject proper schema at compile time\n /* v8 ignore start */\n return {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: false,\n };\n /* v8 ignore end */\n}\n\n/**\n * Extract schema from Zod 3 definition.\n */\nfunction extractSchemaFromZod3(\n def: Record<string, unknown>,\n): ToolParameterSchema {\n const shape = (def.shape as () => Record<string, ZodLike>)();\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, fieldSchema] of Object.entries(shape)) {\n properties[key] = extractFieldSchema(fieldSchema);\n // Check if field is optional\n const fieldDef = fieldSchema._def as Record<string, unknown>;\n if (fieldDef.typeName !== \"ZodOptional\") {\n required.push(key);\n }\n }\n\n return {\n type: \"object\",\n properties: properties as Record<\n string,\n { type?: string; description?: string }\n >,\n required,\n additionalProperties: false,\n };\n}\n\n/**\n * Extract schema from Zod 4 definition.\n * This is a fallback when toJSONSchema() is not available.\n */\n/* v8 ignore start */\nfunction extractSchemaFromZod4(\n def: Record<string, unknown>,\n): ToolParameterSchema {\n const shape = def.shape as Record<string, ZodLike>;\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, fieldSchema] of Object.entries(shape)) {\n properties[key] = extractFieldSchemaZod4(fieldSchema);\n // Check if field is optional (Zod 4 uses isOptional method)\n const schemaAny = fieldSchema as unknown as {\n isOptional?: () => boolean;\n _def?: { type?: string };\n };\n const isOptional =\n typeof schemaAny.isOptional === \"function\"\n ? schemaAny.isOptional()\n : schemaAny._def?.type === \"optional\";\n if (!isOptional) {\n required.push(key);\n }\n }\n\n return {\n type: \"object\",\n properties: properties as Record<\n string,\n { type?: string; description?: string }\n >,\n required,\n additionalProperties: false,\n };\n}\n/* v8 ignore end */\n\n/**\n * Extract JSON schema for a single Zod 3 field.\n */\nfunction extractFieldSchema(zodField: ZodLike): {\n type?: string;\n description?: string;\n} {\n const def = zodField._def as Record<string, unknown>;\n const description = def.description as string | undefined;\n\n // Handle wrapped types (optional, nullable, etc.)\n if (def.innerType && typeof def.innerType === \"object\") {\n const inner = extractFieldSchema(def.innerType as ZodLike);\n /* v8 ignore next */ // description ?? inner.description - both branches tested\n return { ...inner, description: description ?? inner.description };\n }\n\n // Map Zod types to JSON Schema types\n const typeMapping: Record<string, string> = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBoolean: \"boolean\",\n ZodArray: \"array\",\n ZodObject: \"object\",\n };\n\n const typeName = def.typeName as string;\n const type = typeMapping[typeName];\n\n return {\n ...(type && { type }),\n /* v8 ignore next */ // description is usually undefined for simple fields\n ...(description && { description }),\n };\n}\n\n/**\n * Extract JSON schema for a single Zod 4 field.\n * This is a fallback when toJSONSchema() is not available.\n */\n/* v8 ignore start */\nfunction extractFieldSchemaZod4(zodField: ZodLike): {\n type?: string;\n description?: string;\n items?: { type?: string };\n} {\n const def = zodField._def as Record<string, unknown>;\n const fieldAny = zodField as unknown as { description?: string };\n // Zod 4: description at top level, Zod 3: in _def.description\n const description =\n fieldAny.description ?? (def.description as string | undefined);\n\n // Handle wrapped types (optional, nullable, etc.)\n if (def.innerType && typeof def.innerType === \"object\") {\n const inner = extractFieldSchemaZod4(def.innerType as ZodLike);\n return { ...inner, description: description ?? inner.description };\n }\n\n // Zod 4 uses _def.type directly as a string\n const zodType = def.type as string | undefined;\n\n // Map Zod 4 types to JSON Schema types\n const typeMapping: Record<string, string> = {\n string: \"string\",\n number: \"number\",\n boolean: \"boolean\",\n array: \"array\",\n object: \"object\",\n int: \"integer\",\n };\n\n const type = zodType ? typeMapping[zodType] : undefined;\n\n // Handle array items\n if (zodType === \"array\" && def.element) {\n const itemSchema = extractFieldSchemaZod4(def.element as ZodLike);\n return {\n type: \"array\",\n items: itemSchema,\n ...(description && { description }),\n };\n }\n\n return {\n ...(type && { type }),\n ...(description && { description }),\n };\n}\n/* v8 ignore end */\n\n/**\n * Extract a name from a Zod schema.\n */\nfunction extractNameFromZod(zodSchema: ZodLike): string {\n // Try to get description as name (Zod 4: top level, Zod 3: _def.description)\n const def = zodSchema._def as { description?: string };\n const description = zodSchema.description ?? def.description;\n if (description) {\n // Use first word of description as name\n const firstWord = description.split(/\\s+/)[0];\n if (firstWord && firstWord.length < 30) {\n return firstWord;\n }\n }\n\n return \"FormattedOutput\";\n}\n","/**\n * Response formatting interfaces for structuring LLM outputs.\n *\n * This module provides a way to define structured output formats for LLM responses.\n * Use `defineFormat` to create formats with explicit mode control, or pass\n * format specs directly to call/stream methods.\n *\n * The `defineOutputParser` function can be used to create custom parsers for\n * non-JSON formats like XML, YAML, CSV, or any custom text structure.\n */\n\n// Types\nexport type {\n FormattingMode,\n FormatSpec,\n FormatInput,\n AnyFormatInput,\n ExtractFormatType,\n} from \"@/llm/formatting/types\";\nexport { isZodSchema, isFormatSpec } from \"@/llm/formatting/types\";\n\n// Partial type\nexport type { DeepPartial } from \"@/llm/formatting/partial\";\n\n// OutputParser\nexport type {\n OutputParser,\n OutputParserArgs,\n AnyResponse,\n} from \"@/llm/formatting/output-parser\";\nexport {\n defineOutputParser,\n isOutputParser,\n OUTPUT_PARSER_TYPE,\n} from \"@/llm/formatting/output-parser\";\n\n// Format\nexport type { Format, DefineFormatOptions } from \"@/llm/formatting/format\";\nexport {\n defineFormat,\n resolveFormat,\n isFormat,\n extractSchemaFromZod,\n FORMAT_TYPE,\n FORMAT_TOOL_NAME,\n TOOL_MODE_INSTRUCTIONS,\n JSON_MODE_INSTRUCTIONS,\n} from \"@/llm/formatting/format\";\n","/**\n * Tool definition functions for creating LLM-callable tools.\n *\n * Provides `defineTool()` and `defineContextTool()` for creating tools\n * with type-safe argument inference.\n *\n * Two patterns are supported:\n * 1. **Zod-native**: Use `validator` option with a Zod schema (no transformer needed)\n * 2. **Transformer-based**: Use generic type parameter (requires transformer for schema injection)\n */\n\nimport type { ToolCall } from \"@/llm/content/tool-call\";\nimport type { Context } from \"@/llm/context\";\nimport type { ToolParameterSchema } from \"@/llm/tools/tool-schema\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport { ToolOutput } from \"@/llm/content/tool-output\";\nimport { ToolExecutionError } from \"@/llm/exceptions\";\nimport { extractSchemaFromZod } from \"@/llm/formatting\";\nimport {\n TOOL_TYPE,\n CONTEXT_TOOL_TYPE,\n type ZodLike,\n type InferZod,\n type Tool,\n type ContextTool,\n} from \"@/llm/tools/tools\";\n\n/**\n * Check if a value is a Zod-like schema.\n */\nexport function isZodLike(value: unknown): value is ZodLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"_def\" in value &&\n typeof (value as ZodLike).safeParse === \"function\"\n );\n}\n\n// =============================================================================\n// Zod-Native Tool Args (No Transformer Required)\n// =============================================================================\n\n/**\n * Arguments for defining a tool using a Zod schema.\n *\n * This pattern does NOT require the compile-time transformer.\n * The schema is extracted from the Zod validator at runtime.\n *\n * @template Z - The Zod schema type.\n */\nexport interface ZodToolArgs<Z extends ZodLike> {\n /** The name of the tool. */\n name: string;\n\n /** A description of what the tool does. */\n description: string;\n\n /**\n * Whether to use strict mode for the tool schema.\n * When true, providers that support it will enforce strict schema validation.\n */\n strict?: boolean;\n\n /**\n * Zod schema for both schema generation AND runtime validation.\n * Use `.describe()` on fields to add descriptions.\n */\n validator: Z;\n\n /** The tool implementation function. */\n tool: (args: InferZod<Z>) => Jsonable | Promise<Jsonable>;\n}\n\n/**\n * Arguments for defining a context tool using a Zod schema.\n *\n * This pattern does NOT require the compile-time transformer.\n *\n * @template Z - The Zod schema type.\n * @template DepsT - The type of dependencies in the context.\n */\nexport interface ZodContextToolArgs<Z extends ZodLike, DepsT = unknown> {\n /** The name of the tool. */\n name: string;\n\n /** A description of what the tool does. */\n description: string;\n\n /**\n * Whether to use strict mode for the tool schema.\n * When true, providers that support it will enforce strict schema validation.\n */\n strict?: boolean;\n\n /**\n * Zod schema for both schema generation AND runtime validation.\n * Use `.describe()` on fields to add descriptions.\n */\n validator: Z;\n\n /** The tool implementation function with context. */\n tool: (\n ctx: Context<DepsT>,\n args: InferZod<Z>,\n ) => Jsonable | Promise<Jsonable>;\n}\n\n// =============================================================================\n// Transformer-Based Tool Args\n// =============================================================================\n\n/**\n * Arguments for defining a tool using the compile-time transformer.\n *\n * @template T - The type of arguments the tool accepts.\n */\nexport interface ToolArgs<T extends Record<string, unknown>> {\n /** The name of the tool. */\n name: string;\n\n /** A description of what the tool does. */\n description: string;\n\n /**\n * Whether to use strict mode for the tool schema.\n * When true, providers that support it will enforce strict schema validation.\n */\n strict?: boolean;\n\n /** The tool implementation function. */\n tool: (args: T) => Jsonable | Promise<Jsonable>;\n\n /**\n * Internal: JSON schema injected by the compile-time transformer.\n * Users should not set this directly - it's populated automatically.\n */\n __schema?: ToolParameterSchema;\n}\n\n/**\n * Arguments for defining a context tool using the compile-time transformer.\n *\n * @template T - The type of arguments the tool accepts.\n * @template DepsT - The type of dependencies in the context.\n */\nexport interface ContextToolArgs<\n T extends Record<string, unknown>,\n DepsT = unknown,\n> {\n /** The name of the tool. */\n name: string;\n\n /** A description of what the tool does. */\n description: string;\n\n /**\n * Whether to use strict mode for the tool schema.\n * When true, providers that support it will enforce strict schema validation.\n */\n strict?: boolean;\n\n /** The tool implementation function with context. */\n tool: (ctx: Context<DepsT>, args: T) => Jsonable | Promise<Jsonable>;\n\n /**\n * Internal: JSON schema injected by the compile-time transformer.\n * Users should not set this directly - it's populated automatically.\n */\n __schema?: ToolParameterSchema;\n}\n\n// =============================================================================\n// Type Guards\n// =============================================================================\n\n/**\n * Check if args have a validator (Zod-native path).\n */\nfunction hasValidator<Z extends ZodLike>(\n args: ZodToolArgs<Z> | ToolArgs<Record<string, unknown>>,\n): args is ZodToolArgs<Z> {\n return \"validator\" in args && isZodLike(args.validator);\n}\n\n/**\n * Check if context tool args have a validator (Zod-native path).\n */\nfunction hasContextValidator<Z extends ZodLike, DepsT>(\n args:\n | ZodContextToolArgs<Z, DepsT>\n | ContextToolArgs<Record<string, unknown>, DepsT>,\n): args is ZodContextToolArgs<Z, DepsT> {\n return \"validator\" in args && isZodLike(args.validator);\n}\n\n// =============================================================================\n// Validation Helper\n// =============================================================================\n\n/**\n * Validate arguments against a Zod validator.\n *\n * @param args - The arguments to validate.\n * @param validator - The Zod validator.\n * @returns The validated arguments (potentially transformed by Zod).\n * @throws Error if validation fails.\n */\nfunction validateWithZod<T>(args: T, validator: ZodLike): T {\n const result = validator.safeParse(args);\n if (!result.success) {\n throw new Error(`Validation failed: ${JSON.stringify(result.error)}`);\n }\n return result.data as T;\n}\n\n// =============================================================================\n// defineTool Function\n// =============================================================================\n\n/**\n * Define a tool using a Zod schema (no transformer needed).\n *\n * @template Z - The Zod schema type.\n * @param args - The tool definition arguments with validator.\n * @returns A Tool instance with args inferred from the Zod schema.\n *\n * @example\n * ```typescript\n * import { z } from 'zod';\n *\n * const getWeather = defineTool({\n * name: 'get_weather',\n * description: 'Get weather for a city',\n * validator: z.object({\n * city: z.string().describe('The city name'),\n * }),\n * tool: ({ city }) => ({ temp: 72, city }),\n * });\n * ```\n */\nexport function defineTool<Z extends ZodLike>(\n args: ZodToolArgs<Z>,\n): Tool<InferZod<Z>>;\n\n/**\n * Define a tool using the compile-time transformer.\n *\n * @template T - The type of arguments the tool accepts.\n * @param args - The tool definition arguments.\n * @returns A Tool instance.\n *\n * @example\n * ```typescript\n * interface WeatherArgs {\n * // JSDoc comments become field descriptions via transformer\n * city: string;\n * }\n *\n * const getWeather = defineTool<WeatherArgs>({\n * name: 'get_weather',\n * description: 'Get weather for a city',\n * tool: ({ city }) => ({ temp: 72, city }),\n * });\n * ```\n */\nexport function defineTool<T extends Record<string, unknown>>(\n args: ToolArgs<T>,\n): Tool<T>;\n\n/**\n * Implementation of defineTool.\n */\nexport function defineTool<\n T extends Record<string, unknown>,\n Z extends ZodLike = ZodLike,\n>(args: ZodToolArgs<Z> | ToolArgs<T>): Tool<T> | Tool<InferZod<Z>> {\n const { name, description, strict } = args;\n\n // Determine which path to use\n if (\n hasValidator<Z>(args as ZodToolArgs<Z> | ToolArgs<Record<string, unknown>>)\n ) {\n // Zod-native path\n const { validator, tool } = args as ZodToolArgs<Z>;\n const parameters = extractSchemaFromZod(validator);\n\n const callable = async (toolArgs: InferZod<Z>): Promise<Jsonable> => {\n const validatedArgs = validateWithZod(toolArgs, validator);\n const result = tool(validatedArgs);\n return result instanceof Promise ? result : Promise.resolve(result);\n };\n\n const execute = async (\n toolCall: ToolCall,\n ): Promise<ToolOutput<Jsonable>> => {\n try {\n const parsedArgs = JSON.parse(toolCall.args) as InferZod<Z>;\n const result = await callable(parsedArgs);\n return ToolOutput.success(toolCall.id, name, result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return ToolOutput.failure(\n toolCall.id,\n name,\n new ToolExecutionError(err),\n );\n }\n };\n\n Object.defineProperty(callable, \"name\", { value: name, writable: false });\n return Object.assign(callable, {\n __toolType: TOOL_TYPE,\n description,\n parameters,\n strict,\n execute,\n validator,\n }) as Tool<InferZod<Z>>;\n }\n\n // Transformer-based path\n const { tool, __schema } = args as ToolArgs<T>;\n\n // Schema is required from transformer\n // Coverage ignored: When using the Mirascope transformer, __schema is always\n // injected at compile time. This error path is defensive for non-transformed usage.\n /* v8 ignore start */\n if (!__schema) {\n throw new Error(\n `Tool '${name}' is missing __schema. ` +\n \"Either use the Mirascope TypeScript transformer, \" +\n \"or use the Zod-native pattern with a 'validator' option.\",\n );\n }\n /* v8 ignore end */\n\n const callable = async (toolArgs: T): Promise<Jsonable> => {\n const result = tool(toolArgs);\n return result instanceof Promise ? result : Promise.resolve(result);\n };\n\n const execute = async (toolCall: ToolCall): Promise<ToolOutput<Jsonable>> => {\n try {\n const parsedArgs = JSON.parse(toolCall.args) as T;\n const result = await callable(parsedArgs);\n return ToolOutput.success(toolCall.id, name, result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return ToolOutput.failure(toolCall.id, name, new ToolExecutionError(err));\n }\n };\n\n Object.defineProperty(callable, \"name\", { value: name, writable: false });\n return Object.assign(callable, {\n __toolType: TOOL_TYPE,\n description,\n parameters: __schema,\n strict,\n execute,\n validator: undefined,\n }) as Tool<T>;\n}\n\n// =============================================================================\n// defineContextTool Function\n// =============================================================================\n\n/**\n * Define a context tool using a Zod schema (no transformer needed).\n *\n * @template Z - The Zod schema type.\n * @template DepsT - The type of dependencies in the context.\n * @param args - The tool definition arguments with validator.\n * @returns A ContextTool instance with args inferred from the Zod schema.\n *\n * @example\n * ```typescript\n * import { z } from 'zod';\n *\n * const searchDatabase = defineContextTool({\n * name: 'search_database',\n * description: 'Search the database',\n * validator: z.object({\n * query: z.string().describe('The search query'),\n * }),\n * tool: (ctx, { query }) => ctx.deps.db.search(query),\n * });\n * ```\n */\nexport function defineContextTool<Z extends ZodLike, DepsT = unknown>(\n args: ZodContextToolArgs<Z, DepsT>,\n): ContextTool<InferZod<Z>, DepsT>;\n\n/**\n * Define a context tool using the compile-time transformer.\n *\n * @template T - The type of arguments the tool accepts.\n * @template DepsT - The type of dependencies in the context.\n * @param args - The tool definition arguments.\n * @returns A ContextTool instance.\n *\n * @example\n * ```typescript\n * interface MyDeps {\n * db: Database;\n * }\n *\n * interface SearchArgs {\n * query: string;\n * }\n *\n * const searchDatabase = defineContextTool<SearchArgs, MyDeps>({\n * name: 'search_database',\n * description: 'Search the database',\n * tool: (ctx, { query }) => ctx.deps.db.search(query),\n * });\n * ```\n */\nexport function defineContextTool<\n T extends Record<string, unknown>,\n DepsT = unknown,\n>(args: ContextToolArgs<T, DepsT>): ContextTool<T, DepsT>;\n\n/**\n * Implementation of defineContextTool.\n */\nexport function defineContextTool<\n T extends Record<string, unknown>,\n DepsT = unknown,\n Z extends ZodLike = ZodLike,\n>(\n args: ZodContextToolArgs<Z, DepsT> | ContextToolArgs<T, DepsT>,\n): ContextTool<T, DepsT> | ContextTool<InferZod<Z>, DepsT> {\n const { name, description, strict } = args;\n\n // Determine which path to use\n if (\n hasContextValidator<Z, DepsT>(\n args as\n | ZodContextToolArgs<Z, DepsT>\n | ContextToolArgs<Record<string, unknown>, DepsT>,\n )\n ) {\n // Zod-native path\n const { validator, tool } = args as ZodContextToolArgs<Z, DepsT>;\n const parameters = extractSchemaFromZod(validator);\n\n const callable = async (\n ctx: Context<DepsT>,\n toolArgs: InferZod<Z>,\n ): Promise<Jsonable> => {\n const validatedArgs = validateWithZod(toolArgs, validator);\n const result = tool(ctx, validatedArgs);\n return result instanceof Promise ? result : Promise.resolve(result);\n };\n\n const execute = async (\n ctx: Context<DepsT>,\n toolCall: ToolCall,\n ): Promise<ToolOutput<Jsonable>> => {\n try {\n const parsedArgs = JSON.parse(toolCall.args) as InferZod<Z>;\n const result = await callable(ctx, parsedArgs);\n return ToolOutput.success(toolCall.id, name, result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return ToolOutput.failure(\n toolCall.id,\n name,\n new ToolExecutionError(err),\n );\n }\n };\n\n Object.defineProperty(callable, \"name\", { value: name, writable: false });\n return Object.assign(callable, {\n __toolType: CONTEXT_TOOL_TYPE,\n description,\n parameters,\n strict,\n execute,\n validator,\n }) as ContextTool<InferZod<Z>, DepsT>;\n }\n\n // Transformer-based path\n const { tool, __schema } = args as ContextToolArgs<T, DepsT>;\n\n // Schema is required from transformer\n // Coverage ignored: When using the Mirascope transformer, __schema is always\n // injected at compile time. This error path is defensive for non-transformed usage.\n /* v8 ignore start */\n if (!__schema) {\n throw new Error(\n `Tool '${name}' is missing __schema. ` +\n \"Either use the Mirascope TypeScript transformer, \" +\n \"or use the Zod-native pattern with a 'validator' option.\",\n );\n }\n /* v8 ignore end */\n\n const callable = async (\n ctx: Context<DepsT>,\n toolArgs: T,\n ): Promise<Jsonable> => {\n const result = tool(ctx, toolArgs);\n return result instanceof Promise ? result : Promise.resolve(result);\n };\n\n const execute = async (\n ctx: Context<DepsT>,\n toolCall: ToolCall,\n ): Promise<ToolOutput<Jsonable>> => {\n try {\n const parsedArgs = JSON.parse(toolCall.args) as T;\n const result = await callable(ctx, parsedArgs);\n return ToolOutput.success(toolCall.id, name, result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return ToolOutput.failure(toolCall.id, name, new ToolExecutionError(err));\n }\n };\n\n Object.defineProperty(callable, \"name\", { value: name, writable: false });\n return Object.assign(callable, {\n __toolType: CONTEXT_TOOL_TYPE,\n description,\n parameters: __schema,\n strict,\n execute,\n validator: undefined,\n }) as ContextTool<T, DepsT>;\n}\n","/**\n * Base class for provider-native tools.\n *\n * Unlike regular tools which define functions that you execute locally,\n * provider tools are capabilities built into the provider's API.\n * The provider handles execution entirely server-side.\n */\nexport class ProviderTool {\n readonly name: string;\n\n constructor(name: string) {\n this.name = name;\n }\n}\n\n/**\n * Type guard to check if a value is a ProviderTool.\n */\nexport function isProviderTool(value: unknown): value is ProviderTool {\n return value instanceof ProviderTool;\n}\n","/**\n * Toolkit class for managing collections of tools.\n *\n * Provides a unified interface for executing tool calls against\n * a collection of registered tools.\n */\n\nimport type { ToolCall } from \"@/llm/content/tool-call\";\nimport type { Context } from \"@/llm/context\";\nimport type { ToolSchema } from \"@/llm/tools/tool-schema\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport { ToolOutput } from \"@/llm/content/tool-output\";\nimport { ToolNotFoundError } from \"@/llm/exceptions\";\nimport { ProviderTool, isProviderTool } from \"@/llm/tools/provider-tool\";\nimport {\n isContextTool,\n type BaseTool,\n type AnyContextTool,\n type Tools,\n type ContextTools,\n} from \"@/llm/tools/tools\";\n\n/**\n * Base interface that all toolkit types implement.\n *\n * This provides a unified interface for accessing tool schemas and looking\n * up tools by name. Matches Python's `BaseToolkit[ToolSchemaT]` pattern.\n *\n * @template T - The type of tools stored in this toolkit.\n */\nexport interface BaseToolkit<T extends ToolSchema = ToolSchema> {\n /**\n * Get all tools in the toolkit (including provider tools).\n */\n readonly tools: readonly (T | ProviderTool)[];\n\n /**\n * Get the schemas for all tools in the toolkit.\n * Does NOT include provider tools (they have no schema).\n */\n readonly schemas: readonly ToolSchema[];\n\n /**\n * Get the provider tools in the toolkit.\n */\n readonly providerTools: readonly ProviderTool[];\n\n /**\n * Get a tool by name.\n *\n * @param name - The name of the tool.\n * @returns The tool, or undefined if not found.\n */\n get(name: string): T | undefined;\n\n /**\n * Check if a tool with the given name exists.\n *\n * @param name - The name of the tool.\n * @returns True if the tool exists.\n */\n has(name: string): boolean;\n}\n\n// =============================================================================\n// Type Aliases for Tool Inputs (matching Python's types.py)\n// =============================================================================\n\n/**\n * Type alias for any tools input: either a sequence or a toolkit.\n *\n * This accepts either an array of tools or a pre-built Toolkit,\n * matching Python's `Tools = Sequence[Tool] | Toolkit` pattern.\n */\nexport type AnyTools = Tools | Toolkit;\n\n/**\n * Type alias for any context tools input: either a sequence or a toolkit.\n *\n * This accepts either an array of tools or a pre-built ContextToolkit,\n * matching Python's `ContextTools[DepsT] = Sequence[...] | ContextToolkit[DepsT]` pattern.\n *\n * @template DepsT - The type of dependencies in the context.\n */\nexport type AnyContextTools<DepsT = unknown> =\n | ContextTools<DepsT>\n | ContextToolkit<DepsT>;\n\n/**\n * A toolkit for managing and executing regular tools.\n *\n * Implements BaseToolkit<BaseTool> for type-safe tool access.\n *\n * @example\n * ```typescript\n * const toolkit = new Toolkit([getWeather, searchWeb]);\n *\n * // Execute a tool call from the LLM\n * const output = await toolkit.execute(toolCall);\n * ```\n */\nexport class Toolkit implements BaseToolkit<BaseTool> {\n private readonly toolMap: Map<string, BaseTool>;\n private readonly providerToolMap: Map<string, ProviderTool>;\n private readonly _tools: readonly (BaseTool | ProviderTool)[];\n\n /**\n * Create a new Toolkit with the given tools.\n *\n * @param tools - The tools to include in the toolkit, or null/undefined for empty.\n * @throws Error if multiple tools have the same name.\n */\n constructor(tools: readonly (BaseTool | ProviderTool)[] | null | undefined) {\n this.toolMap = new Map();\n this.providerToolMap = new Map();\n this._tools = tools ?? [];\n\n for (const tool of this._tools) {\n if (isProviderTool(tool)) {\n if (this.providerToolMap.has(tool.name)) {\n throw new Error(`Multiple provider tools with name: ${tool.name}`);\n }\n this.providerToolMap.set(tool.name, tool);\n } else {\n const baseTool = tool as BaseTool;\n if (this.toolMap.has(baseTool.name)) {\n throw new Error(`Multiple tools with name: ${baseTool.name}`);\n }\n this.toolMap.set(baseTool.name, baseTool);\n }\n }\n }\n\n /**\n * Get all tools in the toolkit (including provider tools).\n */\n get tools(): readonly (BaseTool | ProviderTool)[] {\n return this._tools;\n }\n\n /**\n * Get the schemas for all tools in the toolkit.\n * Does NOT include provider tools (they have no schema).\n */\n get schemas(): readonly ToolSchema[] {\n return Array.from(this.toolMap.values());\n }\n\n /**\n * Get the provider tools in the toolkit.\n */\n get providerTools(): readonly ProviderTool[] {\n return Array.from(this.providerToolMap.values());\n }\n\n /**\n * Get a tool by name.\n *\n * @param name - The name of the tool.\n * @returns The tool, or undefined if not found.\n */\n get(name: string): BaseTool | undefined {\n return this.toolMap.get(name);\n }\n\n /**\n * Check if a tool with the given name exists.\n *\n * @param name - The name of the tool.\n * @returns True if the tool exists.\n */\n has(name: string): boolean {\n return this.toolMap.has(name);\n }\n\n /**\n * Execute a tool call.\n *\n * Finds the tool matching the call's name and executes it.\n * Returns a ToolOutput with the result or error.\n *\n * @param toolCall - The tool call from the LLM.\n * @returns A ToolOutput with the result or error.\n */\n async execute(toolCall: ToolCall): Promise<ToolOutput<Jsonable>> {\n const tool = this.toolMap.get(toolCall.name);\n\n if (!tool) {\n const error = new ToolNotFoundError(toolCall.name);\n return ToolOutput.failure(toolCall.id, toolCall.name, error);\n }\n\n return tool.execute(toolCall);\n }\n}\n\n/**\n * A toolkit for managing and executing context tools.\n *\n * This toolkit supports BOTH regular tools (BaseTool) AND context tools\n * (BaseContextTool), matching Python's `ContextToolkit[DepsT]` pattern.\n * Regular tools are executed without context; context tools receive the\n * context for dependency injection.\n *\n * Implements BaseToolkit<AnyContextTool<DepsT>> for type-safe tool access.\n *\n * @template DepsT - The type of dependencies in the context.\n *\n * @example\n * ```typescript\n * interface MyDeps { db: Database; }\n *\n * // Can mix regular and context tools\n * const toolkit = new ContextToolkit<MyDeps>([\n * regularTool, // BaseTool - no context needed\n * searchDatabase, // BaseContextTool<MyDeps> - receives context\n * ]);\n *\n * // Execute with context - polymorphic dispatch handles both types\n * const ctx = createContext<MyDeps>({ db: myDatabase });\n * const output = await toolkit.execute(ctx, toolCall);\n * ```\n */\nexport class ContextToolkit<DepsT = unknown> implements BaseToolkit<\n AnyContextTool<DepsT>\n> {\n private readonly toolMap: Map<string, AnyContextTool<DepsT>>;\n private readonly providerToolMap: Map<string, ProviderTool>;\n private readonly _tools: readonly (AnyContextTool<DepsT> | ProviderTool)[];\n\n /**\n * Create a new ContextToolkit with the given tools.\n *\n * Accepts regular tools (BaseTool), context tools (BaseContextTool), and provider tools.\n *\n * @param tools - The tools to include in the toolkit, or null/undefined for empty.\n * @throws Error if multiple tools have the same name.\n */\n constructor(\n tools: readonly (AnyContextTool<DepsT> | ProviderTool)[] | null | undefined,\n ) {\n this.toolMap = new Map();\n this.providerToolMap = new Map();\n this._tools = tools ?? [];\n\n for (const tool of this._tools) {\n if (isProviderTool(tool)) {\n if (this.providerToolMap.has(tool.name)) {\n throw new Error(`Multiple provider tools with name: ${tool.name}`);\n }\n this.providerToolMap.set(tool.name, tool);\n } else {\n const contextTool = tool as AnyContextTool<DepsT>;\n if (this.toolMap.has(contextTool.name)) {\n throw new Error(`Multiple tools with name: ${contextTool.name}`);\n }\n this.toolMap.set(contextTool.name, contextTool);\n }\n }\n }\n\n /**\n * Get all tools in the toolkit (including provider tools).\n */\n get tools(): readonly (AnyContextTool<DepsT> | ProviderTool)[] {\n return this._tools;\n }\n\n /**\n * Get the schemas for all tools in the toolkit.\n * Does NOT include provider tools (they have no schema).\n */\n get schemas(): readonly ToolSchema[] {\n return Array.from(this.toolMap.values());\n }\n\n /**\n * Get the provider tools in the toolkit.\n */\n get providerTools(): readonly ProviderTool[] {\n return Array.from(this.providerToolMap.values());\n }\n\n /**\n * Get a tool by name.\n *\n * @param name - The name of the tool.\n * @returns The tool, or undefined if not found.\n */\n get(name: string): AnyContextTool<DepsT> | undefined {\n return this.toolMap.get(name);\n }\n\n /**\n * Check if a tool with the given name exists.\n *\n * @param name - The name of the tool.\n * @returns True if the tool exists.\n */\n has(name: string): boolean {\n return this.toolMap.has(name);\n }\n\n /**\n * Execute a tool call with context.\n *\n * Uses polymorphic dispatch to handle both regular tools and context tools:\n * - Regular tools (BaseTool) are executed without context\n * - Context tools (BaseContextTool) receive the context for dependency injection\n *\n * @param ctx - The context containing dependencies.\n * @param toolCall - The tool call from the LLM.\n * @returns A ToolOutput with the result or error.\n */\n async execute(\n ctx: Context<DepsT>,\n toolCall: ToolCall,\n ): Promise<ToolOutput<Jsonable>> {\n const tool = this.toolMap.get(toolCall.name);\n\n if (!tool) {\n const error = new ToolNotFoundError(toolCall.name);\n return ToolOutput.failure(toolCall.id, toolCall.name, error);\n }\n\n // Polymorphic dispatch based on tool type\n if (isContextTool<DepsT>(tool)) {\n // Context tool - pass context for dependency injection\n return tool.execute(ctx, toolCall);\n } else {\n // Regular tool - execute without context\n return tool.execute(toolCall);\n }\n }\n\n /**\n * Execute multiple tool calls in parallel with context.\n *\n * @param ctx - The context containing dependencies.\n * @param toolCalls - The tool calls to execute.\n * @returns An array of ToolOutputs in the same order as the input.\n */\n async executeAll(\n ctx: Context<DepsT>,\n toolCalls: readonly ToolCall[],\n ): Promise<ToolOutput<Jsonable>[]> {\n return Promise.all(toolCalls.map((call) => this.execute(ctx, call)));\n }\n}\n\n// =============================================================================\n// Factory Functions (for direct construction)\n// =============================================================================\n\n/**\n * Create a toolkit from an array of tools.\n *\n * This is a convenience function for creating Toolkit instances.\n *\n * @param tools - The tools to include in the toolkit.\n * @returns A new Toolkit instance.\n */\nexport function createToolkit(\n tools: readonly (BaseTool | ProviderTool)[],\n): Toolkit {\n return new Toolkit(tools);\n}\n\n/**\n * Create a context toolkit from an array of tools.\n *\n * This is a convenience function for creating ContextToolkit instances.\n * Accepts regular tools (BaseTool), context tools (BaseContextTool), and provider tools.\n *\n * @template DepsT - The type of dependencies in the context.\n * @param tools - The tools to include in the toolkit.\n * @returns A new ContextToolkit instance.\n */\nexport function createContextToolkit<DepsT = unknown>(\n tools: readonly (AnyContextTool<DepsT> | ProviderTool)[],\n): ContextToolkit<DepsT> {\n return new ContextToolkit(tools);\n}\n\n// =============================================================================\n// Normalization Functions (matching Python's types.py)\n// =============================================================================\n\n/**\n * Normalize tools input to a Toolkit.\n *\n * Handles multiple input types:\n * - null/undefined → empty Toolkit\n * - Toolkit → passthrough (returns as-is)\n * - array → wraps in new Toolkit\n *\n * Matches Python's `normalize_tools()` function.\n *\n * @param tools - A sequence of Tools, a Toolkit, or null/undefined.\n * @returns A Toolkit containing the tools (or an empty Toolkit if null/undefined).\n */\nexport function normalizeTools(tools: AnyTools | null | undefined): Toolkit {\n if (tools == null) {\n return new Toolkit(null);\n }\n if (tools instanceof Toolkit) {\n return tools;\n }\n return new Toolkit(tools);\n}\n\n/**\n * Normalize context tools input to a ContextToolkit.\n *\n * Handles multiple input types:\n * - null/undefined → empty ContextToolkit\n * - ContextToolkit → passthrough (returns as-is)\n * - array → wraps in new ContextToolkit\n *\n * Matches Python's `normalize_context_tools()` function.\n *\n * @template DepsT - The type of dependencies in the context.\n * @param tools - A sequence of Tools/ContextTools, a ContextToolkit, or null/undefined.\n * @returns A ContextToolkit containing the tools (or an empty ContextToolkit if null/undefined).\n */\nexport function normalizeContextTools<DepsT = unknown>(\n tools: AnyContextTools<DepsT> | null | undefined,\n): ContextToolkit<DepsT> {\n if (tools == null) {\n return new ContextToolkit<DepsT>(null);\n }\n if (tools instanceof ContextToolkit) {\n return tools;\n }\n return new ContextToolkit<DepsT>(tools);\n}\n","/**\n * Web search tool for provider-native web search capabilities.\n */\n\nimport { ProviderTool } from \"./provider-tool\";\n\n/**\n * Web search tool that allows the model to search the internet.\n *\n * This is a provider tool - the search is executed server-side by the provider,\n * not by your code. The model decides when to search based on the prompt,\n * and the provider returns search results with citations.\n *\n * Supported providers include Anthropic, Google, and OpenAI (when using the Responses API).\n *\n * @example\n * ```typescript\n * import { defineCall, WebSearchTool } from '@anthropic-ai/mirascope';\n *\n * const searchWeb = defineCall({\n * model: 'anthropic/claude-sonnet-4-5',\n * tools: [new WebSearchTool()],\n * }, () => 'Search the web for: Who won the 2024 Super Bowl?');\n *\n * const response = await searchWeb();\n * console.log(response.text()); // Response includes citations from web search\n * ```\n */\nexport class WebSearchTool extends ProviderTool {\n constructor() {\n super(\"web_search\");\n }\n}\n\n/**\n * Type guard to check if a value is a WebSearchTool.\n */\nexport function isWebSearchTool(value: unknown): value is WebSearchTool {\n return value instanceof WebSearchTool;\n}\n","/**\n * Tools module for LLM function calling.\n *\n * Provides utilities for defining tools that LLMs can call,\n * including schema generation, validation, and execution.\n */\n\n// Schema types and constants\nexport { FORMAT_TOOL_NAME } from \"@/llm/tools/tool-schema\";\nexport type {\n JsonSchemaProperty,\n ToolParameterSchema,\n ToolSchema,\n} from \"@/llm/tools/tool-schema\";\n\n// Tools\nexport { TOOL_TYPE, CONTEXT_TOOL_TYPE, isContextTool } from \"@/llm/tools/tools\";\nexport type {\n ZodLike,\n InferZod,\n BaseTool,\n BaseContextTool,\n Tool,\n ContextTool,\n AnyTool,\n AnyContextTool,\n AnyToolSchema,\n Tools,\n ContextTools,\n ToolFn,\n ContextToolFn,\n AnyToolFn,\n} from \"@/llm/tools/tools\";\n\n// Tool definition\nexport {\n defineTool,\n defineContextTool,\n isZodLike,\n} from \"@/llm/tools/define-tool\";\nexport type {\n ToolArgs,\n ContextToolArgs,\n ZodToolArgs,\n ZodContextToolArgs,\n} from \"@/llm/tools/define-tool\";\n\n// Toolkit\nexport type {\n BaseToolkit,\n AnyTools,\n AnyContextTools,\n} from \"@/llm/tools/toolkit\";\nexport {\n Toolkit,\n ContextToolkit,\n createToolkit,\n createContextToolkit,\n normalizeTools,\n normalizeContextTools,\n} from \"@/llm/tools/toolkit\";\n\n// Provider tools\nexport { ProviderTool, isProviderTool } from \"@/llm/tools/provider-tool\";\nexport { WebSearchTool, isWebSearchTool } from \"@/llm/tools/web-search-tool\";\n","/**\n * Anthropic-specific utilities for encoding requests and decoding responses.\n */\n\nimport type {\n Base64ImageSource as AnthropicBase64ImageSource,\n ContentBlock,\n ImageBlockParam,\n Message as AnthropicMessage,\n MessageCreateParamsNonStreaming,\n URLImageSource as AnthropicURLImageSource,\n} from \"@anthropic-ai/sdk/resources/messages\";\n\nimport Anthropic from \"@anthropic-ai/sdk\";\n\nimport type {\n AssistantContentPart,\n Image,\n ImageMimeType,\n Text,\n Thought,\n ToolCall,\n UserContentPart,\n} from \"@/llm/content\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { AssistantMessage, Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { ThinkingLevel } from \"@/llm/models/thinking-config\";\nimport type { AnthropicModelId } from \"@/llm/providers/anthropic/model-id\";\nimport type { Usage } from \"@/llm/responses/usage\";\nimport type { ToolSchema, Tools } from \"@/llm/tools\";\n\nimport {\n APIError,\n AuthenticationError,\n BadRequestError,\n ConnectionError,\n FeatureNotSupportedError,\n NotFoundError,\n PermissionError,\n RateLimitError,\n ServerError,\n} from \"@/llm/exceptions\";\nimport { modelName } from \"@/llm/providers/anthropic/model-id\";\nimport { ParamHandler, type ProviderErrorMap } from \"@/llm/providers/base\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\nimport { createUsage } from \"@/llm/responses/usage\";\nimport { ProviderTool, isProviderTool, isWebSearchTool } from \"@/llm/tools\";\n\n/**\n * Default max tokens for Anthropic requests.\n */\nconst DEFAULT_MAX_TOKENS = 4096;\n\n/**\n * Supported Anthropic image MIME types.\n */\ntype AnthropicImageMimeType =\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\";\n\n/**\n * Convert an ImageMimeType to Anthropic-supported media type.\n *\n * @throws FeatureNotSupportedError for unsupported formats (HEIC, HEIF)\n */\nfunction toAnthropicImageMimeType(\n mimeType: ImageMimeType,\n): AnthropicImageMimeType {\n if (\n mimeType === \"image/jpeg\" ||\n mimeType === \"image/png\" ||\n mimeType === \"image/gif\" ||\n mimeType === \"image/webp\"\n ) {\n return mimeType;\n }\n throw new FeatureNotSupportedError(\n `image format: ${mimeType}`,\n \"anthropic\",\n null,\n `Anthropic does not support ${mimeType}. Supported formats: JPEG, PNG, GIF, WebP.`,\n );\n}\n\n/**\n * Encode an Image content part to Anthropic's ImageBlockParam format.\n */\nfunction encodeImage(image: Image): ImageBlockParam {\n if (image.source.type === \"base64_image_source\") {\n const source: AnthropicBase64ImageSource = {\n type: \"base64\",\n media_type: toAnthropicImageMimeType(image.source.mimeType),\n data: image.source.data,\n };\n return { type: \"image\", source };\n } else {\n const source: AnthropicURLImageSource = {\n type: \"url\",\n url: image.source.url,\n };\n return { type: \"image\", source };\n }\n}\n\n/**\n * Thinking level to budget multiplier mapping.\n * The multiplier is applied to max_tokens to compute the thinking budget.\n */\nconst THINKING_LEVEL_TO_BUDGET_MULTIPLIER: Record<\n Exclude<ThinkingLevel, \"none\" | \"default\">,\n number\n> = {\n minimal: 0, // Will become 1024 (minimum allowed)\n low: 0.2,\n medium: 0.4,\n high: 0.6,\n max: 0.8,\n};\n\n/**\n * Compute Anthropic token budget from ThinkingConfig level.\n *\n * @param level - The thinking level from ThinkingConfig\n * @param maxTokens - The max_tokens value for the request\n * @returns Token budget (0 to disable, -1 for provider default, positive for budget)\n */\nexport function computeThinkingBudget(\n level: ThinkingLevel,\n maxTokens: number,\n): number {\n if (level === \"none\") {\n return 0; // Disabled\n }\n if (level === \"default\") {\n return -1; // Use provider default (don't set thinking param)\n }\n\n const multiplier = THINKING_LEVEL_TO_BUDGET_MULTIPLIER[level];\n const budget = Math.floor(multiplier * maxTokens);\n return Math.max(1024, budget); // Minimum 1024 tokens\n}\n\n/**\n * Error mapping from Anthropic SDK exceptions to Mirascope error types.\n * Note: More specific error classes must come before their parent classes\n * since the error map is checked with instanceof in order.\n */\nexport const ANTHROPIC_ERROR_MAP: ProviderErrorMap = [\n [Anthropic.AuthenticationError, AuthenticationError],\n [Anthropic.PermissionDeniedError, PermissionError],\n [Anthropic.BadRequestError, BadRequestError],\n [Anthropic.NotFoundError, NotFoundError],\n [Anthropic.RateLimitError, RateLimitError],\n [Anthropic.InternalServerError, ServerError],\n [Anthropic.APIConnectionError, ConnectionError],\n [Anthropic.APIError, APIError],\n];\n\n// ============================================================================\n// Content Part Processing\n// ============================================================================\n\n/**\n * Cacheable content types that can have cache_control applied.\n */\nconst CACHEABLE_CONTENT_TYPES = new Set([\n \"text\",\n \"image\",\n \"tool_output\",\n \"tool_call\",\n]);\n\n/**\n * Process content parts from either user or assistant messages.\n * Converts to Anthropic's ContentBlockParam format.\n *\n * @param content - The content parts to process\n * @param addCacheControl - Whether to add cache_control to the last cacheable content block\n */\nfunction processContentParts(\n content: readonly (UserContentPart | AssistantContentPart)[],\n addCacheControl: boolean = false,\n): Anthropic.Messages.ContentBlockParam[] {\n const blocks: Anthropic.Messages.ContentBlockParam[] = [];\n\n // Find the last cacheable content index if we need to add cache control\n let lastCacheableIndex = -1;\n if (addCacheControl) {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i]!;\n if (CACHEABLE_CONTENT_TYPES.has(part.type)) {\n // Skip empty text\n if (part.type === \"text\" && !part.text) {\n continue;\n }\n lastCacheableIndex = i;\n break;\n }\n }\n }\n\n for (let i = 0; i < content.length; i++) {\n const part = content[i]!;\n const shouldAddCache = addCacheControl && i === lastCacheableIndex;\n\n switch (part.type) {\n case \"text\":\n blocks.push({\n type: \"text\",\n text: part.text,\n ...(shouldAddCache && { cache_control: { type: \"ephemeral\" } }),\n });\n break;\n\n case \"image\":\n blocks.push({\n ...encodeImage(part),\n ...(shouldAddCache && { cache_control: { type: \"ephemeral\" } }),\n });\n break;\n\n case \"audio\":\n throw new FeatureNotSupportedError(\n \"audio input\",\n \"anthropic\",\n null,\n \"Anthropic does not support audio inputs.\",\n );\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n case \"tool_call\":\n blocks.push({\n type: \"tool_use\",\n id: part.id,\n name: part.name,\n input: JSON.parse(part.args) as Record<string, unknown>,\n ...(shouldAddCache && { cache_control: { type: \"ephemeral\" } }),\n });\n break;\n\n case \"tool_output\":\n blocks.push({\n type: \"tool_result\",\n tool_use_id: part.id,\n content:\n typeof part.result === \"string\"\n ? part.result\n : JSON.stringify(part.result),\n is_error: part.error !== null,\n ...(shouldAddCache && { cache_control: { type: \"ephemeral\" } }),\n });\n break;\n /* v8 ignore stop */\n\n /* v8 ignore start - content types not yet implemented */\n case \"document\":\n throw new FeatureNotSupportedError(\n \"document content encoding\",\n \"anthropic\",\n null,\n \"Document content is not yet implemented\",\n );\n\n case \"thought\":\n throw new FeatureNotSupportedError(\n \"thought encoding\",\n \"anthropic\",\n null,\n \"Thought content is not yet implemented\",\n );\n /* v8 ignore stop */\n }\n }\n\n return blocks;\n}\n\n// ============================================================================\n// Content Simplification\n// ============================================================================\n\n/**\n * Simplify content to string if only a single text part without cache_control.\n * Anthropic accepts string for simple messages, but not when cache_control is present.\n */\nfunction simplifyContent(\n blocks: Anthropic.Messages.ContentBlockParam[],\n): string | Anthropic.Messages.ContentBlockParam[] {\n if (\n blocks.length === 1 &&\n blocks[0] &&\n blocks[0].type === \"text\" &&\n !(\"cache_control\" in blocks[0] && blocks[0].cache_control)\n ) {\n return blocks[0].text;\n }\n return blocks;\n}\n\n// ============================================================================\n// Message Encoding\n// ============================================================================\n\n/**\n * Encode a single user or assistant message.\n *\n * @param message - The message to encode\n * @param modelId - The model ID for the request\n * @param expectedProviderModelName - The expected provider model name\n * @param addCacheControl - Whether to add cache_control to the last content block\n */\nfunction encodeMessage(\n message: Message,\n modelId: AnthropicModelId,\n expectedProviderModelName: string,\n addCacheControl: boolean,\n): Anthropic.Messages.MessageParam | null {\n /* v8 ignore next 3 - defensive check: system messages filtered in encodeMessages */\n if (message.role === \"system\") {\n return null; // System messages are handled separately\n }\n\n if (message.role === \"user\") {\n const blocks = processContentParts(message.content, addCacheControl);\n return {\n role: \"user\",\n content: simplifyContent(blocks),\n };\n }\n\n // assistant message\n // Check if we can reuse the raw message (from same provider/model)\n // Can only reuse if not adding cache control\n if (\n !addCacheControl &&\n message.providerId === \"anthropic\" &&\n message.modelId === modelId &&\n message.providerModelName === expectedProviderModelName &&\n message.rawMessage &&\n typeof message.rawMessage === \"object\" &&\n \"role\" in message.rawMessage &&\n \"content\" in message.rawMessage\n ) {\n // Reuse the serialized message directly\n return message.rawMessage as unknown as Anthropic.Messages.MessageParam;\n }\n\n // Otherwise, encode from content parts\n const blocks = processContentParts(message.content, addCacheControl);\n return {\n role: \"assistant\",\n content: simplifyContent(blocks),\n };\n}\n\n/**\n * Encode Mirascope messages to Anthropic API format.\n *\n * If the conversation contains assistant messages (indicating multi-turn),\n * adds cache_control to the last content block of the last message.\n *\n * @param messages - The messages to encode\n * @param modelId - The model ID for the request (used to check if raw message can be reused)\n */\nexport function encodeMessages(\n messages: readonly Message[],\n modelId: AnthropicModelId,\n): {\n system: string | undefined;\n messages: MessageCreateParamsNonStreaming[\"messages\"];\n} {\n let system: string | undefined;\n const anthropicMessages: MessageCreateParamsNonStreaming[\"messages\"] = [];\n const expectedProviderModelName = modelName(modelId);\n\n // Extract system message\n const nonSystemMessages: Message[] = [];\n for (const message of messages) {\n if (message.role === \"system\") {\n system = message.content.text;\n } else {\n nonSystemMessages.push(message);\n }\n }\n\n // Detect multi-turn conversations by checking for assistant messages\n const hasAssistantMessage = nonSystemMessages.some(\n (msg) => msg.role === \"assistant\",\n );\n\n // Encode messages, adding cache_control to the last message if multi-turn\n for (let i = 0; i < nonSystemMessages.length; i++) {\n const message = nonSystemMessages[i]!;\n const isLast = i === nonSystemMessages.length - 1;\n const addCacheControl = hasAssistantMessage && isLast;\n\n const encoded = encodeMessage(\n message,\n modelId,\n expectedProviderModelName,\n addCacheControl,\n );\n if (encoded) {\n anthropicMessages.push(encoded);\n }\n }\n\n return { system, messages: anthropicMessages };\n}\n\n// ============================================================================\n// Tool Encoding\n// ============================================================================\n\n/* v8 ignore start - tool encoding will be tested via e2e */\n/**\n * Convert a ToolSchema to Anthropic's Tool format.\n */\nexport function encodeToolSchema(tool: ToolSchema): Anthropic.Messages.Tool {\n return {\n name: tool.name,\n description: tool.description,\n input_schema: {\n type: \"object\",\n properties: tool.parameters.properties as Record<\n string,\n Anthropic.Messages.Tool.InputSchema\n >,\n required: tool.parameters.required as string[],\n },\n };\n}\n\n/**\n * Encode an array of tool schemas to Anthropic's format.\n */\nexport function encodeTools(\n tools: readonly ToolSchema[],\n): Anthropic.Messages.Tool[] {\n return tools.map(encodeToolSchema);\n}\n/* v8 ignore stop */\n\n/**\n * Build the request parameters for the Anthropic API.\n *\n * This function performs strict param checking - any unhandled params will\n * cause an error to ensure we don't silently ignore user configuration.\n *\n * @param modelId - The model ID to use\n * @param messages - The messages to send\n * @param tools - Optional tools to make available to the model\n * @param format - Optional format for structured output\n * @param params - Optional parameters (temperature, maxTokens, etc.)\n */\nexport function buildRequestParams(\n modelId: AnthropicModelId,\n messages: readonly Message[],\n tools?: Tools,\n format?: Format | null,\n params: Params = {},\n): MessageCreateParamsNonStreaming {\n const { system, messages: anthropicMessages } = encodeMessages(\n messages,\n modelId,\n );\n\n return ParamHandler.with(params, \"anthropic\", modelId, (p) => {\n const maxTokens = p.getOrDefault(\"maxTokens\", DEFAULT_MAX_TOKENS);\n const requestParams: MessageCreateParamsNonStreaming = {\n model: modelName(modelId),\n messages: anthropicMessages,\n max_tokens: maxTokens,\n };\n\n // Start with the system prompt from messages\n let systemPrompt = system;\n\n // Collect tools from both explicit tools and format tool\n const allTools: Anthropic.Messages.ToolUnion[] = [];\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (tools !== undefined && tools.length > 0) {\n // Separate regular tools from provider tools\n const regularTools: ToolSchema[] = [];\n for (const tool of tools) {\n // Check for provider tools first (WebSearchTool extends ProviderTool)\n if (isProviderTool(tool)) {\n if (isWebSearchTool(tool)) {\n // Anthropic's web search tool\n allTools.push({\n type: \"web_search_20250305\",\n name: \"web_search\",\n });\n } else {\n // Cast needed because TS narrows to never after WebSearchTool check\n const unsupportedTool = tool as ProviderTool;\n throw new FeatureNotSupportedError(\n `Provider tool ${unsupportedTool.name}`,\n \"anthropic\",\n modelId,\n `Provider tool '${unsupportedTool.name}' is not supported by Anthropic`,\n );\n }\n } else {\n // Regular tool (BaseTool extends ToolSchema)\n regularTools.push(tool as ToolSchema);\n }\n }\n if (regularTools.length > 0) {\n allTools.push(...encodeTools(regularTools));\n }\n }\n /* v8 ignore stop */\n\n // Handle format-based tool and instructions\n /* v8 ignore start - format encoding will be tested via e2e */\n if (format) {\n // Check mode support\n if (format.mode === \"strict\") {\n throw new FeatureNotSupportedError(\n \"formatting_mode:strict\",\n \"anthropic\",\n modelId,\n \"Anthropic standard API does not support strict mode formatting. Use beta API or tool mode.\",\n );\n }\n\n // Add format tool if mode is 'tool'\n if (format.mode === \"tool\") {\n const formatToolSchema = format.createToolSchema();\n allTools.push(encodeToolSchema(formatToolSchema));\n\n // Set tool_choice based on whether we have other tools\n if (tools && tools.length > 0) {\n // When we have other tools, use 'any' to require a tool call\n requestParams.tool_choice = { type: \"any\" };\n } else {\n // When only format tool, force that specific tool\n requestParams.tool_choice = {\n type: \"tool\",\n name: formatToolSchema.name,\n disable_parallel_tool_use: true,\n };\n }\n }\n\n // Add formatting instructions to system prompt\n if (format.formattingInstructions) {\n if (systemPrompt) {\n systemPrompt = `${systemPrompt}\\n\\n${format.formattingInstructions}`;\n } else {\n systemPrompt = format.formattingInstructions;\n }\n }\n }\n /* v8 ignore stop */\n\n // Set system prompt if we have one (with cache control for prompt caching)\n if (systemPrompt) {\n requestParams.system = [\n {\n type: \"text\",\n text: systemPrompt,\n cache_control: { type: \"ephemeral\" },\n },\n ];\n }\n\n // Set tools if we have any (with cache control on the last tool)\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (allTools.length > 0) {\n // Add cache control to the last tool for prompt caching\n const lastTool = allTools[allTools.length - 1]!;\n (\n lastTool as Anthropic.Messages.Tool & { cache_control?: object }\n ).cache_control = { type: \"ephemeral\" };\n requestParams.tools = allTools;\n }\n /* v8 ignore stop */\n\n const temperature = p.get(\"temperature\");\n const topP = p.get(\"topP\");\n\n // Anthropic doesn't allow both temperature and topP together\n if (temperature !== undefined && topP !== undefined) {\n throw new FeatureNotSupportedError(\n \"temperature + topP\",\n \"anthropic\",\n modelId,\n \"Anthropic does not allow both temperature and top_p to be specified together\",\n );\n }\n\n if (temperature !== undefined) {\n requestParams.temperature = temperature;\n }\n\n if (topP !== undefined) {\n requestParams.top_p = topP;\n }\n\n const topK = p.get(\"topK\");\n if (topK !== undefined) {\n requestParams.top_k = topK;\n }\n\n const stopSequences = p.get(\"stopSequences\");\n if (stopSequences !== undefined) {\n requestParams.stop_sequences = stopSequences;\n }\n\n // Anthropic doesn't support seed\n p.warnUnsupported(\"seed\", \"Anthropic does not support the seed parameter\");\n\n const thinkingConfig = p.get(\"thinking\");\n if (thinkingConfig) {\n const budget = computeThinkingBudget(thinkingConfig.level, maxTokens);\n if (budget === 0) {\n requestParams.thinking = { type: \"disabled\" };\n } else if (budget > 0) {\n requestParams.thinking = { type: \"enabled\", budget_tokens: budget };\n }\n // If budget === -1, don't set thinking (use provider default)\n }\n\n return requestParams;\n });\n}\n\n/**\n * Serialize content blocks for storage in rawMessage.\n *\n * This mirrors Python's `part.model_dump()` pattern for round-tripping.\n */\nfunction serializeContentBlocks(\n content: ContentBlock[],\n): Record<string, unknown>[] {\n return content.map((block) => {\n // Copy all non-undefined properties from the block\n const serialized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(block)) {\n if (value !== undefined) {\n serialized[key] = value;\n }\n }\n return serialized;\n });\n}\n\n/**\n * Decode Anthropic response to Mirascope types.\n *\n * @param response - The raw Anthropic API response\n * @param modelId - The model ID used for the request\n * @param includeThoughts - Whether to include thinking blocks in the response (default: false)\n */\nexport function decodeResponse(\n response: AnthropicMessage,\n modelId: AnthropicModelId,\n includeThoughts: boolean = false,\n): {\n assistantMessage: AssistantMessage;\n finishReason: FinishReason | null;\n usage: Usage | null;\n} {\n const content = decodeContent(response.content, includeThoughts);\n\n // Store serialized message for round-tripping in resume operations.\n // This format matches what Anthropic expects as MessageParam.\n const serializedRawMessage = {\n role: response.role,\n content: serializeContentBlocks(response.content),\n };\n\n const assistantMessage: AssistantMessage = {\n role: \"assistant\",\n content,\n name: null,\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n rawMessage:\n serializedRawMessage as unknown as AssistantMessage[\"rawMessage\"],\n };\n\n const finishReason = decodeStopReason(response.stop_reason);\n const usage = decodeUsage(response.usage);\n\n return { assistantMessage, finishReason, usage };\n}\n\nfunction decodeContent(\n content: ContentBlock[],\n includeThoughts: boolean,\n): AssistantContentPart[] {\n const parts: AssistantContentPart[] = [];\n\n for (const block of content) {\n if (block.type === \"text\") {\n const text: Text = { type: \"text\", text: block.text };\n parts.push(text);\n } else if (block.type === \"thinking\") {\n if (includeThoughts) {\n const thought: Thought = { type: \"thought\", thought: block.thinking };\n parts.push(thought);\n }\n /* v8 ignore start - redacted_thinking can't be reliably triggered in tests */\n } else if (block.type === \"redacted_thinking\") {\n // Skip redacted thinking blocks - they contain encrypted thinking\n // that cannot be decoded\n continue;\n /* v8 ignore stop */\n /* v8 ignore start - tool decoding will be tested via e2e */\n } else if (block.type === \"tool_use\") {\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: block.id,\n name: block.name,\n args: JSON.stringify(block.input),\n };\n parts.push(toolCall);\n /* v8 ignore stop */\n /* v8 ignore start - defensive unknown block handling */\n } else {\n // Unknown block type - be strict so we know what we're missing\n throw new FeatureNotSupportedError(\n `unknown block type: ${block.type}`,\n \"anthropic\",\n null,\n `Unknown content block type '${block.type}' in response is not yet implemented`,\n );\n }\n /* v8 ignore stop */\n }\n\n return parts;\n}\n\nfunction decodeStopReason(\n stopReason: AnthropicMessage[\"stop_reason\"],\n): FinishReason | null {\n switch (stopReason) {\n case \"max_tokens\":\n return FinishReason.MAX_TOKENS;\n case \"end_turn\":\n case \"stop_sequence\":\n case \"tool_use\":\n return null; // Normal completion\n /* v8 ignore next 2 - defensive default case */\n default:\n return null;\n }\n}\n\nexport function decodeUsage(usage: AnthropicMessage[\"usage\"]): Usage {\n return createUsage({\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n /* v8 ignore next 2 - cache tokens only present with caching enabled, will add tests later */\n cacheReadTokens: usage.cache_read_input_tokens ?? 0,\n cacheWriteTokens: usage.cache_creation_input_tokens ?? 0,\n raw: usage,\n });\n}\n","/**\n * Beta Anthropic response decoding utilities.\n *\n * Handles BetaMessage type which has additional stop reasons and content types\n * compared to the standard Message type.\n */\n\nimport type {\n BetaContentBlock,\n BetaMessage,\n BetaStopReason,\n BetaUsage,\n} from \"@anthropic-ai/sdk/resources/beta/messages/messages\";\n\nimport type { AssistantContentPart, Text, Thought } from \"@/llm/content\";\nimport type { AssistantMessage } from \"@/llm/messages\";\nimport type { AnthropicModelId } from \"@/llm/providers/anthropic/model-id\";\nimport type { Usage } from \"@/llm/responses/usage\";\n\nimport { FeatureNotSupportedError } from \"@/llm/exceptions\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\nimport { createUsage } from \"@/llm/responses/usage\";\n\n/**\n * Decode Beta Anthropic response to Mirascope types.\n *\n * Similar to standard decodeResponse but handles BetaMessage type\n * which has additional stop reasons (refusal, etc.) and content types.\n *\n * @param response - The raw BetaMessage from Anthropic API\n * @param modelId - The model ID used for the request\n * @param includeThoughts - Whether to include thinking blocks in the response (default: false)\n */\nexport function betaDecodeResponse(\n response: BetaMessage,\n modelId: AnthropicModelId,\n includeThoughts: boolean = false,\n): {\n assistantMessage: AssistantMessage;\n finishReason: FinishReason | null;\n usage: Usage | null;\n} {\n const content = betaDecodeContent(response.content, includeThoughts);\n\n const assistantMessage: AssistantMessage = {\n role: \"assistant\",\n content,\n name: null,\n // Note: providerId is 'anthropic' (not 'anthropic-beta') to match Python SDK\n providerId: \"anthropic\",\n modelId,\n providerModelName: response.model,\n rawMessage: response as unknown as AssistantMessage[\"rawMessage\"],\n };\n\n const finishReason = betaDecodeStopReason(response.stop_reason);\n const usage = betaDecodeUsage(response.usage);\n\n return { assistantMessage, finishReason, usage };\n}\n\n/**\n * Decode beta content blocks to Mirascope content parts.\n *\n * @param content - The content blocks from the beta response\n * @param includeThoughts - Whether to include thinking blocks\n */\nfunction betaDecodeContent(\n content: BetaContentBlock[],\n includeThoughts: boolean,\n): AssistantContentPart[] {\n const parts: AssistantContentPart[] = [];\n\n for (const block of content) {\n if (block.type === \"text\") {\n const text: Text = { type: \"text\", text: block.text };\n parts.push(text);\n } else if (block.type === \"thinking\") {\n if (includeThoughts) {\n const thought: Thought = { type: \"thought\", thought: block.thinking };\n parts.push(thought);\n }\n } else if (block.type === \"redacted_thinking\") {\n // Skip redacted thinking blocks - they contain encrypted thinking\n // that cannot be decoded\n continue;\n /* v8 ignore start - content types not yet implemented */\n } else if (block.type === \"tool_use\") {\n throw new FeatureNotSupportedError(\n \"tool use decoding\",\n \"anthropic\",\n null,\n \"Tool use blocks in responses are not yet implemented\",\n );\n } else {\n // Unknown block type - be strict so we know what we're missing\n throw new FeatureNotSupportedError(\n `unknown block type: ${block.type}`,\n \"anthropic\",\n null,\n `Unknown content block type '${block.type}' in beta response is not yet implemented`,\n );\n }\n /* v8 ignore stop */\n }\n\n return parts;\n}\n\n/**\n * Decode beta stop reason to Mirascope FinishReason.\n *\n * Beta API has additional stop reasons compared to standard:\n * - 'refusal': Model refused to generate content\n * - 'pause_turn': Conversation paused (not yet supported)\n * - 'model_context_window_exceeded': Context too long (not yet supported)\n */\nfunction betaDecodeStopReason(\n stopReason: BetaStopReason | null,\n): FinishReason | null {\n switch (stopReason) {\n case \"max_tokens\":\n return FinishReason.MAX_TOKENS;\n case \"refusal\":\n return FinishReason.REFUSAL;\n case \"end_turn\":\n case \"stop_sequence\":\n case \"tool_use\":\n case \"pause_turn\":\n return null; // Normal completion\n /* v8 ignore next 2 - defensive default case */\n default:\n return null;\n }\n}\n\n/**\n * Decode beta usage to Mirascope Usage.\n *\n * Beta usage has additional fields (cache_creation, server_tool_use)\n * but we only use the common fields for now.\n */\nfunction betaDecodeUsage(usage: BetaUsage): Usage {\n return createUsage({\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n cacheReadTokens: usage.cache_read_input_tokens ?? 0,\n cacheWriteTokens: usage.cache_creation_input_tokens ?? 0,\n raw: usage,\n });\n}\n","/**\n * Supported audio MIME types.\n */\nexport type AudioMimeType =\n | \"audio/wav\"\n | \"audio/mp3\"\n | \"audio/aiff\"\n | \"audio/aac\"\n | \"audio/ogg\"\n | \"audio/flac\";\n\n/**\n * Audio data encoded as base64.\n */\nexport type Base64AudioSource = {\n readonly type: \"base64_audio_source\";\n\n /** The audio data, as a base64 encoded string. */\n readonly data: string;\n\n /** The mime type of the audio (e.g. audio/mp3). */\n readonly mimeType: AudioMimeType;\n};\n\n/**\n * Audio content for a message.\n *\n * Audio can be included in user messages for multimodal models that support it.\n */\nexport type Audio = {\n readonly type: \"audio\";\n\n readonly source: Base64AudioSource;\n};\n\n/** Maximum audio size in bytes (25MB) */\nexport const MAX_AUDIO_SIZE = 25 * 1024 * 1024;\n\n/**\n * Infer the MIME type of audio from its magic bytes.\n *\n * @throws Error if the audio type cannot be determined\n */\nexport function inferAudioType(data: Uint8Array): AudioMimeType {\n if (data.length < 12) {\n throw new Error(\n \"Audio data too small to determine type (minimum 12 bytes)\",\n );\n }\n\n // WAV: starts with RIFF....WAVE\n if (\n data[0] === 0x52 &&\n data[1] === 0x49 &&\n data[2] === 0x46 &&\n data[3] === 0x46 &&\n data[8] === 0x57 &&\n data[9] === 0x41 &&\n data[10] === 0x56 &&\n data[11] === 0x45\n ) {\n return \"audio/wav\";\n }\n\n // MP3: starts with ID3 or 0xFF 0xFB (frame sync)\n if (\n (data[0] === 0x49 && data[1] === 0x44 && data[2] === 0x33) ||\n (data[0] === 0xff &&\n (data[1] === 0xfb ||\n data[1] === 0xfa ||\n data[1] === 0xf3 ||\n data[1] === 0xf2))\n ) {\n return \"audio/mp3\";\n }\n\n // AIFF: starts with FORM....AIFF\n if (\n data[0] === 0x46 &&\n data[1] === 0x4f &&\n data[2] === 0x52 &&\n data[3] === 0x4d &&\n data[8] === 0x41 &&\n data[9] === 0x49 &&\n data[10] === 0x46 &&\n data[11] === 0x46\n ) {\n return \"audio/aiff\";\n }\n\n // OGG: starts with OggS\n if (\n data[0] === 0x4f &&\n data[1] === 0x67 &&\n data[2] === 0x67 &&\n data[3] === 0x53\n ) {\n return \"audio/ogg\";\n }\n\n // FLAC: starts with fLaC\n if (\n data[0] === 0x66 &&\n data[1] === 0x4c &&\n data[2] === 0x61 &&\n data[3] === 0x43\n ) {\n return \"audio/flac\";\n }\n\n // AAC: starts with ADTS sync word 0xFFF (first 12 bits)\n // Safe to use ! - we validated length >= 12 above\n if (data[0] === 0xff && (data[1]! & 0xf0) === 0xf0) {\n return \"audio/aac\";\n }\n\n throw new Error(\"Unsupported audio type\");\n}\n\n/**\n * Convert a Uint8Array to a base64 string.\n */\nfunction uint8ArrayToBase64(data: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]!);\n }\n return btoa(binary);\n}\n\n/**\n * Factory methods for creating Audio instances.\n */\nexport const Audio = {\n /**\n * Download audio from a URL and encode as base64.\n *\n * @throws Error if download fails or audio exceeds maxSize\n */\n download: async (url: string, maxSize = MAX_AUDIO_SIZE): Promise<Audio> => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(\n `Failed to download audio: ${response.status} ${response.statusText}`,\n );\n }\n const buffer = await response.arrayBuffer();\n return Audio.fromBytes(new Uint8Array(buffer), maxSize);\n },\n\n /**\n * Create Audio from raw bytes.\n *\n * @throws Error if data exceeds maxSize or type cannot be inferred\n */\n fromBytes: (data: Uint8Array, maxSize = MAX_AUDIO_SIZE): Audio => {\n if (data.length > maxSize) {\n throw new Error(\n `Audio size (${data.length} bytes) exceeds maximum (${maxSize} bytes)`,\n );\n }\n const mimeType = inferAudioType(data);\n const base64 = uint8ArrayToBase64(data);\n return {\n type: \"audio\",\n source: { type: \"base64_audio_source\", data: base64, mimeType },\n };\n },\n};\n","/**\n * MIME types for text-based documents.\n */\nexport type DocumentTextMimeType =\n | \"application/json\"\n | \"text/plain\"\n | \"application/x-javascript\"\n | \"text/javascript\"\n | \"application/x-python\"\n | \"text/x-python\"\n | \"text/html\"\n | \"text/css\"\n | \"text/xml\"\n | \"text/rtf\";\n\n/**\n * MIME types for binary documents (base64 encoded).\n */\nexport type DocumentBase64MimeType = \"application/pdf\";\n\n/**\n * Document data encoded as base64 (for binary formats like PDF).\n */\nexport type Base64DocumentSource = {\n readonly type: \"base64_document_source\";\n\n /** The document data, as a base64 encoded string. */\n readonly data: string;\n\n /** The media type of the document (e.g. application/pdf). */\n readonly mediaType: DocumentBase64MimeType;\n};\n\n/**\n * Document data as plain text.\n */\nexport type TextDocumentSource = {\n readonly type: \"text_document_source\";\n\n /** The document data, as plain text. */\n readonly data: string;\n\n /** The media type of the document (e.g. text/plain, text/csv). */\n readonly mediaType: DocumentTextMimeType;\n};\n\n/**\n * Document referenced by URL.\n */\nexport type URLDocumentSource = {\n readonly type: \"url_document_source\";\n\n /** The url of the document (e.g. https://example.com/paper.pdf). */\n readonly url: string;\n};\n\n/**\n * Document content for a message.\n *\n * Documents can be included in user messages for models that support them.\n * Supports text documents (JSON, plain text, code) and binary documents (PDF).\n */\nexport type Document = {\n readonly type: \"document\";\n\n readonly source:\n | Base64DocumentSource\n | TextDocumentSource\n | URLDocumentSource;\n};\n\n/**\n * Factory methods for creating Document instances.\n *\n * Note: These are stubs that throw NotImplementedError.\n * Full implementation is deferred to a later phase.\n */\nexport const Document = {\n /**\n * Create a Document from a URL reference.\n *\n * @throws Error (not implemented)\n */\n fromUrl: (_url: string, _options?: { download?: boolean }): Document => {\n throw new Error(\"Document.fromUrl is not yet implemented\");\n },\n\n /**\n * Create a Document from raw bytes.\n *\n * @throws Error (not implemented)\n */\n fromBytes: (\n _data: Uint8Array,\n _options?: { mimeType?: DocumentTextMimeType | DocumentBase64MimeType },\n ): Document => {\n throw new Error(\"Document.fromBytes is not yet implemented\");\n },\n};\n","/**\n * Supported image MIME types.\n */\nexport type ImageMimeType =\n | \"image/png\"\n | \"image/jpeg\"\n | \"image/webp\"\n | \"image/gif\"\n | \"image/heic\"\n | \"image/heif\";\n\n/**\n * Image data encoded as base64.\n */\nexport type Base64ImageSource = {\n readonly type: \"base64_image_source\";\n\n /** The image data, as a base64 encoded string. */\n readonly data: string;\n\n /** The mime type of the image (e.g. image/png). */\n readonly mimeType: ImageMimeType;\n};\n\n/**\n * Image referenced by URL.\n */\nexport type URLImageSource = {\n readonly type: \"url_image_source\";\n\n /** The url of the image (e.g. https://example.com/image.png). */\n readonly url: string;\n};\n\n/**\n * Image content for a message.\n *\n * Images can be included in user messages for multimodal models.\n * The source can be either base64-encoded data or a URL reference.\n */\nexport type Image = {\n readonly type: \"image\";\n\n readonly source: Base64ImageSource | URLImageSource;\n};\n\n/** Maximum image size in bytes (20MB) */\nexport const MAX_IMAGE_SIZE = 20 * 1024 * 1024;\n\n/**\n * Infer the MIME type of an image from its magic bytes.\n *\n * @throws Error if the image type cannot be determined\n */\nexport function inferImageType(data: Uint8Array): ImageMimeType {\n if (data.length < 12) {\n throw new Error(\n \"Image data too small to determine type (minimum 12 bytes)\",\n );\n }\n\n // JPEG: starts with 0xFF 0xD8 0xFF\n if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {\n return \"image/jpeg\";\n }\n\n // PNG: starts with 0x89 PNG\\r\\n\\x1a\\n\n if (\n data[0] === 0x89 &&\n data[1] === 0x50 &&\n data[2] === 0x4e &&\n data[3] === 0x47 &&\n data[4] === 0x0d &&\n data[5] === 0x0a &&\n data[6] === 0x1a &&\n data[7] === 0x0a\n ) {\n return \"image/png\";\n }\n\n // GIF: starts with GIF87a or GIF89a\n if (\n data[0] === 0x47 &&\n data[1] === 0x49 &&\n data[2] === 0x46 &&\n data[3] === 0x38 &&\n (data[4] === 0x37 || data[4] === 0x39) &&\n data[5] === 0x61\n ) {\n return \"image/gif\";\n }\n\n // WebP: starts with RIFF....WEBP\n if (\n data[0] === 0x52 &&\n data[1] === 0x49 &&\n data[2] === 0x46 &&\n data[3] === 0x46 &&\n data[8] === 0x57 &&\n data[9] === 0x45 &&\n data[10] === 0x42 &&\n data[11] === 0x50\n ) {\n return \"image/webp\";\n }\n\n // HEIC/HEIF: check ftyp box at offset 4\n if (\n data[4] === 0x66 &&\n data[5] === 0x74 &&\n data[6] === 0x79 &&\n data[7] === 0x70\n ) {\n // Check subtype at offset 8-11 (safe - we validated length >= 12)\n const subtype = String.fromCharCode(\n data[8]!,\n data[9]!,\n data[10]!,\n data[11]!,\n );\n if (subtype === \"heic\" || subtype === \"heix\") {\n return \"image/heic\";\n }\n if ([\"mif1\", \"msf1\", \"hevc\", \"hevx\"].includes(subtype)) {\n return \"image/heif\";\n }\n }\n\n throw new Error(\"Unsupported image type\");\n}\n\n/**\n * Convert a Uint8Array to a base64 string.\n */\nexport function uint8ArrayToBase64(data: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]!);\n }\n return btoa(binary);\n}\n\n/**\n * Factory methods for creating Image instances.\n */\nexport const Image = {\n /**\n * Create an Image from a URL reference (no download).\n */\n fromUrl: (url: string): Image => ({\n type: \"image\",\n source: { type: \"url_image_source\", url },\n }),\n\n /**\n * Download an image from a URL and encode as base64.\n *\n * @throws Error if download fails or image exceeds maxSize\n */\n download: async (url: string, maxSize = MAX_IMAGE_SIZE): Promise<Image> => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(\n `Failed to download image: ${response.status} ${response.statusText}`,\n );\n }\n const buffer = await response.arrayBuffer();\n return Image.fromBytes(new Uint8Array(buffer), maxSize);\n },\n\n /**\n * Create an Image from raw bytes.\n *\n * @throws Error if data exceeds maxSize or type cannot be inferred\n */\n fromBytes: (data: Uint8Array, maxSize = MAX_IMAGE_SIZE): Image => {\n if (data.length > maxSize) {\n throw new Error(\n `Image size (${data.length} bytes) exceeds maximum (${maxSize} bytes)`,\n );\n }\n const mimeType = inferImageType(data);\n const base64 = uint8ArrayToBase64(data);\n return {\n type: \"image\",\n source: { type: \"base64_image_source\", data: base64, mimeType },\n };\n },\n};\n","/**\n * Text content for a message.\n *\n * Represents plain text content in a message. This is the most common\n * content type for both user and assistant messages.\n */\nexport type Text = {\n readonly type: \"text\";\n\n /** The text content. */\n readonly text: string;\n};\n\n/**\n * Signals the start of a text content block in the stream.\n */\nexport type TextStartChunk = {\n readonly type: \"text_start_chunk\";\n readonly contentType: \"text\";\n};\n\n/**\n * Contains incremental text content.\n */\nexport type TextChunk = {\n readonly type: \"text_chunk\";\n readonly contentType: \"text\";\n /** The incremental text added in this chunk. */\n readonly delta: string;\n};\n\n/**\n * Signals the end of a text content block in the stream.\n */\nexport type TextEndChunk = {\n readonly type: \"text_end_chunk\";\n readonly contentType: \"text\";\n};\n\n/** Create a TextStartChunk */\nexport function textStart(): TextStartChunk {\n return { type: \"text_start_chunk\", contentType: \"text\" };\n}\n\n/** Create a TextChunk */\nexport function textChunk(delta: string): TextChunk {\n return { type: \"text_chunk\", contentType: \"text\", delta };\n}\n\n/** Create a TextEndChunk */\nexport function textEnd(): TextEndChunk {\n return { type: \"text_end_chunk\", contentType: \"text\" };\n}\n","/**\n * Thought content from an assistant's extended thinking.\n *\n * Represents the reasoning or thinking process of an assistant model\n * that supports extended thinking (e.g., Claude with thinking enabled).\n */\nexport type Thought = {\n readonly type: \"thought\";\n\n /** The thoughts or reasoning of the assistant. */\n readonly thought: string;\n};\n\n/**\n * Signals the start of a thought content block in the stream.\n */\nexport type ThoughtStartChunk = {\n readonly type: \"thought_start_chunk\";\n readonly contentType: \"thought\";\n};\n\n/**\n * Contains incremental thought content.\n */\nexport type ThoughtChunk = {\n readonly type: \"thought_chunk\";\n readonly contentType: \"thought\";\n /** The incremental thought text added in this chunk. */\n readonly delta: string;\n};\n\n/**\n * Signals the end of a thought content block in the stream.\n */\nexport type ThoughtEndChunk = {\n readonly type: \"thought_end_chunk\";\n readonly contentType: \"thought\";\n};\n\n/** Create a ThoughtStartChunk */\nexport function thoughtStart(): ThoughtStartChunk {\n return { type: \"thought_start_chunk\", contentType: \"thought\" };\n}\n\n/** Create a ThoughtChunk */\nexport function thoughtChunk(delta: string): ThoughtChunk {\n return { type: \"thought_chunk\", contentType: \"thought\", delta };\n}\n\n/** Create a ThoughtEndChunk */\nexport function thoughtEnd(): ThoughtEndChunk {\n return { type: \"thought_end_chunk\", contentType: \"thought\" };\n}\n","/**\n * Tool call content from an assistant message.\n *\n * Represents a request from the assistant to call a tool/function.\n * The args field contains the stringified JSON arguments.\n */\nexport type ToolCall = {\n readonly type: \"tool_call\";\n\n /** A unique identifier for this tool call. */\n readonly id: string;\n\n /** The name of the tool to call. */\n readonly name: string;\n\n /** The arguments to pass to the tool, stored as stringified JSON. */\n readonly args: string;\n};\n\n/**\n * Signals the start of a tool call in the stream.\n */\nexport type ToolCallStartChunk = {\n readonly type: \"tool_call_start_chunk\";\n readonly contentType: \"tool_call\";\n /** Unique identifier for this tool call. */\n readonly id: string;\n /** The name of the tool to call. */\n readonly name: string;\n};\n\n/**\n * Contains incremental tool call arguments (JSON).\n */\nexport type ToolCallChunk = {\n readonly type: \"tool_call_chunk\";\n readonly contentType: \"tool_call\";\n /** Unique identifier for this tool call. */\n readonly id: string;\n /** The incremental JSON args added in this chunk. */\n readonly delta: string;\n};\n\n/**\n * Signals the end of a tool call in the stream.\n */\nexport type ToolCallEndChunk = {\n readonly type: \"tool_call_end_chunk\";\n readonly contentType: \"tool_call\";\n /** Unique identifier for this tool call. */\n readonly id: string;\n};\n\n/** Create a ToolCallStartChunk */\nexport function toolCallStart(id: string, name: string): ToolCallStartChunk {\n return { type: \"tool_call_start_chunk\", contentType: \"tool_call\", id, name };\n}\n\n/** Create a ToolCallChunk */\nexport function toolCallChunk(id: string, delta: string): ToolCallChunk {\n return { type: \"tool_call_chunk\", contentType: \"tool_call\", id, delta };\n}\n\n/** Create a ToolCallEndChunk */\nexport function toolCallEnd(id: string): ToolCallEndChunk {\n return { type: \"tool_call_end_chunk\", contentType: \"tool_call\", id };\n}\n","import type { Audio } from \"@/llm/content/audio\";\nimport type { Document } from \"@/llm/content/document\";\nimport type { Image } from \"@/llm/content/image\";\nimport type { Text } from \"@/llm/content/text\";\nimport type {\n TextChunk,\n TextEndChunk,\n TextStartChunk,\n} from \"@/llm/content/text\";\nimport type { Thought } from \"@/llm/content/thought\";\nimport type {\n ThoughtChunk,\n ThoughtEndChunk,\n ThoughtStartChunk,\n} from \"@/llm/content/thought\";\nimport type { ToolCall } from \"@/llm/content/tool-call\";\nimport type {\n ToolCallChunk,\n ToolCallEndChunk,\n ToolCallStartChunk,\n} from \"@/llm/content/tool-call\";\nimport type { ToolOutput } from \"@/llm/content/tool-output\";\n\n/**\n * All content types that can appear in messages.\n */\nexport type ContentPart =\n | Text\n | Image\n | Audio\n | Document\n | ToolOutput\n | ToolCall\n | Thought;\n\n/**\n * Content types that can appear in user messages.\n */\nexport type UserContentPart = Text | Image | Audio | Document | ToolOutput;\n\n/**\n * Content types that can appear in assistant messages.\n */\nexport type AssistantContentPart = Text | ToolCall | Thought;\n\n/**\n * Chunks of assistant content that may be streamed as generated by the LLM.\n */\nexport type AssistantContentChunk =\n | TextStartChunk\n | TextChunk\n | TextEndChunk\n | ThoughtStartChunk\n | ThoughtChunk\n | ThoughtEndChunk\n | ToolCallStartChunk\n | ToolCallChunk\n | ToolCallEndChunk;\n\n/**\n * Individual content type exports\n */\nexport type { Text } from \"@/llm/content/text\";\nexport type { Thought } from \"@/llm/content/thought\";\nexport type { ToolCall } from \"@/llm/content/tool-call\";\nexport {\n Audio,\n type AudioMimeType,\n type Base64AudioSource,\n} from \"@/llm/content/audio\";\nexport {\n Document,\n type Base64DocumentSource,\n type DocumentBase64MimeType,\n type DocumentTextMimeType,\n type TextDocumentSource,\n type URLDocumentSource,\n} from \"@/llm/content/document\";\nexport {\n Image,\n type Base64ImageSource,\n type ImageMimeType,\n type URLImageSource,\n} from \"@/llm/content/image\";\nexport { ToolOutput } from \"@/llm/content/tool-output\";\n\n/**\n * Text chunk exports\n */\nexport type {\n TextStartChunk,\n TextChunk,\n TextEndChunk,\n} from \"@/llm/content/text\";\nexport { textStart, textChunk, textEnd } from \"@/llm/content/text\";\n\n/**\n * Thought chunk exports\n */\nexport type {\n ThoughtStartChunk,\n ThoughtChunk,\n ThoughtEndChunk,\n} from \"@/llm/content/thought\";\nexport { thoughtStart, thoughtChunk, thoughtEnd } from \"@/llm/content/thought\";\n\n/**\n * ToolCall chunk exports\n */\nexport type {\n ToolCallStartChunk,\n ToolCallChunk,\n ToolCallEndChunk,\n} from \"@/llm/content/tool-call\";\nexport {\n toolCallStart,\n toolCallChunk,\n toolCallEnd,\n} from \"@/llm/content/tool-call\";\n","/**\n * Streaming metadata chunk types for provider-agnostic streaming responses.\n *\n * Content-specific chunks (Text, Thought, ToolCall) are defined in content/.\n * This file only contains metadata chunks.\n */\n\nimport type { AssistantContentChunk } from \"@/llm/content\";\nimport type { FinishReason } from \"@/llm/responses/finish-reason\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\n// ============================================================================\n// Metadata Chunks\n// ============================================================================\n\n/**\n * Contains the finish reason when the stream completes.\n */\nexport interface FinishReasonChunk {\n readonly type: \"finish_reason_chunk\";\n /** The reason the stream finished */\n readonly finishReason: FinishReason;\n}\n\n/**\n * Contains incremental token usage information.\n */\nexport interface UsageDeltaChunk {\n readonly type: \"usage_delta_chunk\";\n /** Delta in input tokens */\n readonly inputTokens: number;\n /** Delta in output tokens */\n readonly outputTokens: number;\n /** Delta in cache read tokens */\n readonly cacheReadTokens: number;\n /** Delta in cache write tokens */\n readonly cacheWriteTokens: number;\n /** Delta in reasoning/thinking tokens */\n readonly reasoningTokens: number;\n}\n\n/**\n * Contains a raw stream event from the underlying provider.\n */\nexport interface RawStreamEventChunk {\n readonly type: \"raw_stream_event_chunk\";\n /** The raw stream event from the underlying provider */\n readonly rawStreamEvent: unknown;\n}\n\n/**\n * Contains provider-specific raw message content.\n */\nexport interface RawMessageChunk {\n readonly type: \"raw_message_chunk\";\n /** Provider-specific raw content */\n readonly rawMessage: Jsonable;\n}\n\n// ============================================================================\n// Type Aliases\n// ============================================================================\n\n/**\n * All possible chunk types in a streaming response.\n */\nexport type StreamResponseChunk =\n | AssistantContentChunk\n | FinishReasonChunk\n | UsageDeltaChunk\n | RawStreamEventChunk\n | RawMessageChunk;\n\n/**\n * Async iterator type for streaming chunks.\n */\nexport type AsyncChunkIterator = AsyncIterator<StreamResponseChunk>;\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/** Create a FinishReasonChunk */\nexport function finishReasonChunk(\n finishReason: FinishReason,\n): FinishReasonChunk {\n return { type: \"finish_reason_chunk\", finishReason };\n}\n\n/** Create a UsageDeltaChunk */\n/* v8 ignore start - optional fields default to 0 */\nexport function usageDeltaChunk(usage: {\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n}): UsageDeltaChunk {\n return {\n type: \"usage_delta_chunk\",\n inputTokens: usage.inputTokens ?? 0,\n outputTokens: usage.outputTokens ?? 0,\n cacheReadTokens: usage.cacheReadTokens ?? 0,\n cacheWriteTokens: usage.cacheWriteTokens ?? 0,\n reasoningTokens: usage.reasoningTokens ?? 0,\n };\n}\n/* v8 ignore stop */\n\n/** Create a RawStreamEventChunk */\nexport function rawStreamEventChunk(\n rawStreamEvent: unknown,\n): RawStreamEventChunk {\n return { type: \"raw_stream_event_chunk\", rawStreamEvent };\n}\n\n/** Create a RawMessageChunk */\nexport function rawMessageChunk(rawMessage: Jsonable): RawMessageChunk {\n return { type: \"raw_message_chunk\", rawMessage };\n}\n","/**\n * Anthropic Beta stream decoding utilities.\n *\n * Converts Anthropic Beta MessageStreamEvent to Mirascope StreamResponseChunk.\n * The Beta API supports thinking blocks which are decoded as thought chunks.\n *\n * Note: This module is only used when shouldUseBeta() returns true, which requires\n * strict mode features that are not yet implemented. The code is marked with v8 ignore\n * to avoid coverage requirements for feature-gated code.\n */\n\n/* v8 ignore start - beta streaming is feature-gated behind shouldUseBeta() */\n\nimport type { BetaRawMessageStreamEvent } from \"@anthropic-ai/sdk/resources/beta/messages/messages\";\n\nimport type { StreamResponseChunk } from \"@/llm/responses/chunks\";\n\nimport {\n textStart,\n textChunk,\n textEnd,\n thoughtStart,\n thoughtChunk,\n thoughtEnd,\n} from \"@/llm/content\";\nimport {\n finishReasonChunk,\n usageDeltaChunk,\n rawStreamEventChunk,\n} from \"@/llm/responses/chunks\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\n\n/**\n * State tracking for stream decoding.\n */\ninterface DecodeState {\n /** Index of current content block being streamed */\n currentBlockIndex: number;\n /** Type of current content block */\n currentBlockType: \"text\" | \"thinking\" | null;\n /** Whether to include thoughts in output */\n includeThoughts: boolean;\n}\n\n/**\n * Create a new decode state for a fresh stream.\n */\nexport function createBetaDecodeState(includeThoughts: boolean): DecodeState {\n return {\n currentBlockIndex: -1,\n currentBlockType: null,\n includeThoughts,\n };\n}\n\n/**\n * Decode an Anthropic Beta MessageStreamEvent to Mirascope chunks.\n *\n * @param event - The Anthropic Beta stream event\n * @param state - Mutable state tracking current block\n * @returns Array of Mirascope chunks (may be empty or multiple)\n */\nexport function decodeBetaStreamEvent(\n event: BetaRawMessageStreamEvent,\n state: DecodeState,\n): StreamResponseChunk[] {\n const chunks: StreamResponseChunk[] = [];\n\n // Always emit raw event chunk for debugging/passthrough\n chunks.push(rawStreamEventChunk(event));\n\n switch (event.type) {\n case \"message_start\":\n // Note: We don't emit rawMessageChunk here because event.message contains\n // fields like 'model' and 'id' that aren't valid in resume requests.\n // For streaming, we let rawMessage remain null - the encodeMessages function\n // will encode from content parts instead.\n // Emit initial usage if available\n if (event.message.usage) {\n chunks.push(\n usageDeltaChunk({\n inputTokens: event.message.usage.input_tokens,\n outputTokens: event.message.usage.output_tokens,\n }),\n );\n }\n break;\n\n case \"content_block_start\":\n state.currentBlockIndex = event.index;\n if (event.content_block.type === \"text\") {\n state.currentBlockType = \"text\";\n chunks.push(textStart());\n // If there's initial text, emit it\n if (event.content_block.text) {\n chunks.push(textChunk(event.content_block.text));\n }\n } else if (event.content_block.type === \"thinking\") {\n state.currentBlockType = \"thinking\";\n // Only emit thought chunks if includeThoughts is true\n if (state.includeThoughts) {\n chunks.push(thoughtStart());\n // If there's initial thinking text, emit it\n if (event.content_block.thinking) {\n chunks.push(thoughtChunk(event.content_block.thinking));\n }\n }\n }\n // Note: tool_use and redacted_thinking blocks not yet fully supported\n break;\n\n case \"content_block_delta\":\n if (event.delta.type === \"text_delta\") {\n chunks.push(textChunk(event.delta.text));\n } else if (event.delta.type === \"thinking_delta\") {\n // Only emit thought chunks if includeThoughts is true\n if (state.includeThoughts) {\n chunks.push(thoughtChunk(event.delta.thinking));\n }\n }\n // Note: input_json_delta for tools not yet supported\n break;\n\n case \"content_block_stop\":\n if (state.currentBlockType === \"text\") {\n chunks.push(textEnd());\n } else if (\n state.currentBlockType === \"thinking\" &&\n state.includeThoughts\n ) {\n chunks.push(thoughtEnd());\n }\n state.currentBlockType = null;\n break;\n\n case \"message_delta\":\n // Handle finish reason\n if (event.delta.stop_reason) {\n const finishReason = decodeBetaStopReason(event.delta.stop_reason);\n if (finishReason) {\n chunks.push(finishReasonChunk(finishReason));\n }\n }\n // Handle output token usage delta\n if (event.usage) {\n chunks.push(\n usageDeltaChunk({\n outputTokens: event.usage.output_tokens,\n }),\n );\n }\n break;\n\n case \"message_stop\":\n // Stream complete - no additional chunks needed\n break;\n }\n\n return chunks;\n}\n\n/**\n * Convert Anthropic Beta stop reason to Mirascope FinishReason.\n */\nfunction decodeBetaStopReason(\n stopReason:\n | \"end_turn\"\n | \"max_tokens\"\n | \"stop_sequence\"\n | \"tool_use\"\n | \"refusal\"\n | \"pause_turn\"\n | \"model_context_window_exceeded\"\n | null,\n): FinishReason | null {\n switch (stopReason) {\n case \"max_tokens\":\n case \"model_context_window_exceeded\":\n return FinishReason.MAX_TOKENS;\n case \"refusal\":\n return FinishReason.REFUSAL;\n case \"end_turn\":\n case \"stop_sequence\":\n case \"tool_use\":\n case \"pause_turn\":\n return null; // Normal completion\n default:\n return null;\n }\n}\n\n/**\n * Create an async iterator that decodes Anthropic Beta stream events to Mirascope chunks.\n *\n * @param stream - The Anthropic Beta message stream\n * @param includeThoughts - Whether to include thinking blocks as thought chunks\n * @returns Async iterator of Mirascope chunks\n */\nexport async function* decodeBetaStream(\n stream: AsyncIterable<BetaRawMessageStreamEvent>,\n includeThoughts: boolean,\n): AsyncGenerator<StreamResponseChunk> {\n const state = createBetaDecodeState(includeThoughts);\n\n for await (const event of stream) {\n const chunks = decodeBetaStreamEvent(event, state);\n for (const chunk of chunks) {\n yield chunk;\n }\n }\n}\n\n/* v8 ignore stop */\n","/**\n * Utilities for parsing LLM responses.\n *\n * Provides functions for extracting and parsing JSON from LLM text responses,\n * including support for partial JSON parsing during streaming.\n */\n\nimport { parse as parsePartialJson } from \"partial-json\";\n\nimport type { ZodLike } from \"@/llm/tools\";\n\n/**\n * Strip preamble text before JSON content.\n *\n * Handles common patterns like:\n * - \"Sure thing! Here's the JSON:\\n{...\"\n * - \"```json\\n{...\"\n * - Plain text followed by JSON\n *\n * @param text - The text that may contain a JSON preamble.\n * @returns The text starting from the first '{', or null if no '{' found.\n */\nfunction stripJsonPreamble(text: string): string | null {\n // Handle markdown code blocks\n const codeBlockStart = text.indexOf(\"```json\");\n if (codeBlockStart > -1) {\n // Skip past the ```json marker\n text = text.slice(codeBlockStart + 7);\n // Also handle closing ``` if present\n const codeBlockEnd = text.indexOf(\"```\");\n if (codeBlockEnd > -1) {\n text = text.slice(0, codeBlockEnd);\n }\n }\n\n // Find the start of the JSON object\n const jsonStart = text.indexOf(\"{\");\n if (jsonStart === -1) {\n return null;\n }\n\n return text.slice(jsonStart);\n}\n\n/**\n * Extract the serialized JSON string from text that may contain extra content.\n *\n * This function handles cases where the LLM includes explanatory text before\n * or after the JSON object. It finds the complete JSON object by matching\n * opening and closing braces.\n *\n * @param text - The text containing JSON, possibly with extra content.\n * @returns The extracted JSON string.\n * @throws SyntaxError if no valid JSON object is found.\n *\n * @example\n * ```typescript\n * const text = 'Here is the book:\\n{\"title\": \"1984\", \"author\": \"Orwell\"}\\nHope this helps!';\n * const json = extractSerializedJson(text);\n * // json = '{\"title\": \"1984\", \"author\": \"Orwell\"}'\n * ```\n */\nexport function extractSerializedJson(text: string): string {\n const stripped = stripJsonPreamble(text);\n if (!stripped) {\n throw new SyntaxError(\"No JSON object found in response: missing '{'\");\n }\n\n // Find matching closing brace\n let braceCount = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = 0; i < stripped.length; i++) {\n const char = stripped[i];\n\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\") {\n escaped = true;\n continue;\n }\n\n if (char === '\"' && !escaped) {\n inString = !inString;\n continue;\n }\n\n if (!inString) {\n if (char === \"{\") {\n braceCount++;\n } else if (char === \"}\") {\n braceCount--;\n if (braceCount === 0) {\n return stripped.slice(0, i + 1);\n }\n }\n }\n }\n\n throw new SyntaxError(\"No JSON object found in response: missing '}'\");\n}\n\n/**\n * Parse potentially incomplete JSON into a partial object.\n *\n * This function uses the `partial-json` library to handle incomplete JSON\n * that may arrive during streaming. It gracefully handles:\n * - Unclosed braces/brackets\n * - Incomplete strings\n * - Trailing content\n *\n * @template T - The expected type of the parsed output.\n * @param jsonText - The potentially incomplete JSON text.\n * @param validator - Optional Zod schema for validation (best effort).\n * @returns The parsed partial object, or null if parsing fails.\n *\n * @example\n * ```typescript\n * // During streaming, we might receive:\n * const partial1 = parsePartial('{\"title\": \"19'); // { title: \"19\" }\n * const partial2 = parsePartial('{\"title\": \"1984\", \"au'); // { title: \"1984\" }\n * const partial3 = parsePartial('{\"title\": \"1984\", \"author\": \"Orwell\"}'); // Complete\n * ```\n */\nexport function parsePartial<T>(\n jsonText: string,\n validator?: ZodLike,\n): T | null {\n const stripped = stripJsonPreamble(jsonText);\n if (!stripped) {\n return null;\n }\n\n try {\n // Use partial-json library for robust partial parsing\n // The library returns `any`, so we cast to `unknown` for type safety\n const parsed: unknown = parsePartialJson(stripped);\n\n // If no validator, return parsed directly\n if (!validator) {\n return parsed as T;\n }\n\n // Try to validate with Zod\n // For partial parsing, we use safeParse and accept whatever succeeds\n // since the data may be incomplete\n const result = validator.safeParse(parsed);\n if (result.success) {\n return result.data as T;\n }\n\n // If validation fails on partial data, still return the parsed value\n // This is expected during streaming when not all fields are present yet\n return parsed as T;\n /* v8 ignore start -- defensive: partial-json library is designed to not throw */\n } catch {\n // Parsing failed - likely JSON is too incomplete\n return null;\n }\n /* v8 ignore stop */\n}\n","/**\n * Google registered LLM models.\n */\n\nimport type { GoogleKnownModels } from \"@/llm/providers/google/model-info\";\n\n/**\n * The Google model IDs registered with Mirascope.\n */\nexport type GoogleModelId = GoogleKnownModels | (string & {});\n\n/**\n * Extract the Google model name from the ModelId.\n *\n * @param modelId - Full model ID (e.g. \"google/gemini-2.5-flash\")\n * @returns Provider-specific model ID (e.g. \"gemini-2.5-flash\")\n */\nexport function modelName(modelId: GoogleModelId): string {\n return modelId.replace(/^google\\//, \"\");\n}\n","/**\n * Google-specific utilities for encoding requests and decoding responses.\n */\n\nimport type {\n Blob as GoogleBlob,\n Content,\n ContentUnion,\n GenerateContentConfig,\n GenerateContentParameters,\n GenerateContentResponse,\n Part,\n ThinkingConfig as GoogleThinkingConfig,\n FinishReason as GoogleFinishReasonType,\n} from \"@google/genai\";\n\nimport {\n ApiError,\n FinishReason as GoogleFinishReason,\n ThinkingLevel as GoogleThinkingLevel,\n} from \"@google/genai\";\n\nimport type {\n AssistantContentPart,\n Audio,\n Image,\n Text,\n Thought,\n ToolCall,\n UserContentPart,\n} from \"@/llm/content\";\nimport type { AssistantMessage, Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type {\n ThinkingConfig,\n ThinkingLevel,\n} from \"@/llm/models/thinking-config\";\nimport type { GoogleModelId } from \"@/llm/providers/google/model-id\";\nimport type { Usage } from \"@/llm/responses/usage\";\nimport type { ToolSchema, Tools } from \"@/llm/tools\";\n\nimport {\n APIError,\n AuthenticationError,\n BadRequestError,\n FeatureNotSupportedError,\n NotFoundError,\n PermissionError,\n RateLimitError,\n ServerError,\n} from \"@/llm/exceptions\";\nimport { ParamHandler, type ProviderErrorMap } from \"@/llm/providers/base\";\nimport { modelName } from \"@/llm/providers/google/model-id\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\nimport { createUsage } from \"@/llm/responses/usage\";\nimport { ProviderTool, isProviderTool, isWebSearchTool } from \"@/llm/tools\";\n\n/**\n * Default tool ID for Google function calls when no ID is provided.\n * Google doesn't always provide tool IDs, so we use this as a fallback.\n */\nconst UNKNOWN_TOOL_ID = \"google_unknown_tool_id\";\n\n/**\n * Error mapping from Google SDK exceptions to Mirascope error types.\n * Google SDK uses a single ApiError class with status codes.\n */\nexport const GOOGLE_ERROR_MAP: ProviderErrorMap = [[ApiError, APIError]];\n\n/**\n * Map Google error status codes to specific Mirascope error types.\n *\n * @param status - HTTP status code from the Google API error\n * @returns The appropriate Mirascope error class for this status code\n */\nexport function mapGoogleErrorByStatus(status: number): typeof APIError {\n switch (status) {\n case 401:\n return AuthenticationError;\n case 403:\n return PermissionError;\n case 404:\n return NotFoundError;\n case 429:\n return RateLimitError;\n case 400:\n case 422:\n return BadRequestError;\n default:\n if (status >= 500) {\n return ServerError;\n }\n return APIError;\n }\n}\n\n// ============================================================================\n// Content Part Processing\n// ============================================================================\n\n/**\n * Encode an Image content part to Google's Part format.\n * Google requires inline data (base64), not URL references.\n *\n * @throws FeatureNotSupportedError if the image uses a URL source\n */\nfunction encodeImage(image: Image): Part {\n if (image.source.type === \"url_image_source\") {\n throw new FeatureNotSupportedError(\n \"url_image_source\",\n \"google\",\n null,\n \"Google does not support URL-referenced images. Try `Image.download(...)` instead.\",\n );\n }\n const inlineData: GoogleBlob = {\n data: image.source.data,\n mimeType: image.source.mimeType,\n };\n return { inlineData };\n}\n\n/**\n * Encode an Audio content part to Google's Part format.\n */\nfunction encodeAudio(audio: Audio): Part {\n const inlineData: GoogleBlob = {\n data: audio.source.data,\n mimeType: audio.source.mimeType,\n };\n return { inlineData };\n}\n\n/**\n * Process content parts from either user or assistant messages.\n * Converts to Google's Part format.\n */\nfunction processContentParts(\n content: readonly (UserContentPart | AssistantContentPart)[],\n): Part[] {\n const parts: Part[] = [];\n\n for (const part of content) {\n switch (part.type) {\n case \"text\":\n parts.push({ text: part.text });\n break;\n\n case \"image\":\n parts.push(encodeImage(part));\n break;\n\n case \"audio\":\n parts.push(encodeAudio(part));\n break;\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n case \"tool_call\":\n parts.push({\n functionCall: {\n name: part.name,\n args: JSON.parse(part.args) as Record<string, unknown>,\n },\n });\n break;\n\n case \"tool_output\": {\n // Google expects the result to be an object\n const response =\n typeof part.result === \"string\"\n ? { result: part.result }\n : (part.result as Record<string, unknown>);\n parts.push({\n functionResponse: {\n name: part.name,\n response,\n },\n });\n break;\n }\n /* v8 ignore stop */\n\n /* v8 ignore start - content types not yet implemented */\n case \"document\":\n throw new FeatureNotSupportedError(\n \"document content encoding\",\n \"google\",\n null,\n \"Document content is not yet implemented\",\n );\n\n case \"thought\":\n throw new FeatureNotSupportedError(\n \"thought encoding\",\n \"google\",\n null,\n \"Thought content is not yet implemented\",\n );\n /* v8 ignore stop */\n }\n }\n\n return parts;\n}\n\n// ============================================================================\n// Message Encoding\n// ============================================================================\n\n/**\n * Default max tokens for Google requests.\n */\nconst DEFAULT_MAX_TOKENS = 8192;\n\n/**\n * Thinking level to budget multiplier for Gemini 2.5 models.\n */\nconst THINKING_LEVEL_TO_BUDGET_MULTIPLIER: Record<\n Exclude<ThinkingLevel, \"none\" | \"default\">,\n number\n> = {\n minimal: 0.1,\n low: 0.2,\n medium: 0.4,\n high: 0.6,\n max: 0.8,\n};\n\n/**\n * Thinking level mapping for Gemini 3 Pro (only LOW or HIGH supported).\n */\nconst THINKING_LEVEL_FOR_GEMINI_3_PRO: Record<\n ThinkingLevel,\n GoogleThinkingLevel\n> = {\n default: GoogleThinkingLevel.THINKING_LEVEL_UNSPECIFIED,\n none: GoogleThinkingLevel.LOW,\n minimal: GoogleThinkingLevel.LOW,\n low: GoogleThinkingLevel.LOW,\n medium: GoogleThinkingLevel.HIGH,\n high: GoogleThinkingLevel.HIGH,\n max: GoogleThinkingLevel.HIGH,\n};\n\n/**\n * Thinking level mapping for Gemini 3 Flash (MINIMAL, LOW, MEDIUM, HIGH supported).\n */\nconst THINKING_LEVEL_FOR_GEMINI_3_FLASH: Record<\n ThinkingLevel,\n GoogleThinkingLevel\n> = {\n default: GoogleThinkingLevel.THINKING_LEVEL_UNSPECIFIED,\n none: GoogleThinkingLevel.MINIMAL,\n minimal: GoogleThinkingLevel.MINIMAL,\n low: GoogleThinkingLevel.LOW,\n medium: GoogleThinkingLevel.MEDIUM,\n high: GoogleThinkingLevel.HIGH,\n max: GoogleThinkingLevel.HIGH,\n};\n\n/**\n * Compute Google thinking configuration based on model version.\n *\n * @param thinkingConfig - The ThinkingConfig from params\n * @param maxTokens - Max output tokens (used to compute budget for 2.5 models)\n * @param modelId - The Google model ID to determine version\n * @returns GoogleThinkingConfig with appropriate settings for the model\n */\nexport function computeGoogleThinkingConfig(\n thinkingConfig: ThinkingConfig,\n maxTokens: number,\n modelId: GoogleModelId,\n): GoogleThinkingConfig {\n const level = thinkingConfig.level;\n const result: GoogleThinkingConfig = {};\n\n // Set includeThoughts if specified\n if (thinkingConfig.includeThoughts !== undefined) {\n result.includeThoughts = thinkingConfig.includeThoughts;\n }\n\n // Determine thinking config based on model\n if (\n modelId.includes(\"gemini-3-flash\") ||\n modelId.includes(\"gemini-3.0-flash\")\n ) {\n result.thinkingLevel = THINKING_LEVEL_FOR_GEMINI_3_FLASH[level];\n } else if (\n modelId.includes(\"gemini-3-pro\") ||\n modelId.includes(\"gemini-3.0-pro\")\n ) {\n result.thinkingLevel = THINKING_LEVEL_FOR_GEMINI_3_PRO[level];\n } else {\n // Gemini 2.5 and earlier use thinking_budget\n if (level === \"default\") {\n result.thinkingBudget = -1; // Dynamic/automatic budget\n } else if (level === \"none\") {\n result.thinkingBudget = 0; // Disable thinking\n } else {\n const multiplier = THINKING_LEVEL_TO_BUDGET_MULTIPLIER[level];\n result.thinkingBudget = Math.floor(multiplier * maxTokens);\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Tool Encoding\n// ============================================================================\n\n/* v8 ignore start - tool encoding will be tested via e2e */\n/**\n * Convert a ToolSchema to Google's FunctionDeclaration format.\n */\nexport function encodeToolSchema(tool: ToolSchema): {\n name: string;\n description: string;\n parametersJsonSchema: unknown;\n} {\n return {\n name: tool.name,\n description: tool.description,\n // Use parametersJsonSchema for raw JSON schema compatibility\n parametersJsonSchema: {\n type: \"object\",\n properties: tool.parameters.properties,\n required: tool.parameters.required,\n },\n };\n}\n\n/**\n * Encode an array of tool schemas to Google's format.\n * Google wraps all function declarations in a single Tool object.\n */\nexport function encodeTools(\n tools: readonly ToolSchema[],\n): NonNullable<GenerateContentConfig[\"tools\"]> {\n return [\n {\n functionDeclarations: tools.map(encodeToolSchema),\n },\n ];\n}\n/* v8 ignore stop */\n\n/**\n * Encode Mirascope messages to Google API format.\n *\n * Converts the unified Mirascope message format to Google's Content array format.\n * System messages are extracted separately as Google uses `systemInstruction`.\n * Assistant messages are mapped to the 'model' role.\n *\n * @param messages - The messages to encode\n * @param modelId - The model ID for the request (used to check if raw message can be reused)\n */\nexport function encodeMessages(\n messages: readonly Message[],\n modelId: GoogleModelId,\n): {\n systemInstruction: ContentUnion | undefined;\n contents: Content[];\n} {\n let systemInstruction: ContentUnion | undefined;\n const contents: Content[] = [];\n const expectedProviderModelName = modelName(modelId);\n\n for (const message of messages) {\n if (message.role === \"system\") {\n systemInstruction = message.content.text;\n } else if (message.role === \"user\") {\n contents.push({\n role: \"user\",\n parts: processContentParts(message.content),\n });\n } else if (message.role === \"assistant\") {\n // Check if we can reuse the raw message (from same provider/model)\n if (\n message.providerId === \"google\" &&\n message.modelId === modelId &&\n message.providerModelName === expectedProviderModelName &&\n message.rawMessage &&\n typeof message.rawMessage === \"object\" &&\n \"role\" in message.rawMessage &&\n \"parts\" in message.rawMessage\n ) {\n // Reuse the serialized content directly\n contents.push(message.rawMessage as Content);\n } else {\n // Otherwise, encode from content parts\n contents.push({\n role: \"model\",\n parts: processContentParts(message.content),\n });\n }\n }\n }\n\n return { systemInstruction, contents };\n}\n\n/**\n * Build the request parameters for the Google API.\n *\n * This function performs strict param checking - any unhandled params will\n * cause an error to ensure we don't silently ignore user configuration.\n *\n * @param modelId - The model ID to use\n * @param messages - The messages to send\n * @param params - Optional parameters (temperature, maxTokens, etc.)\n * @param tools - Optional tools to make available to the model\n */\nexport function buildRequestParams(\n modelId: GoogleModelId,\n messages: readonly Message[],\n tools?: Tools,\n params: Params = {},\n): GenerateContentParameters {\n const { systemInstruction, contents } = encodeMessages(messages, modelId);\n\n return ParamHandler.with(params, \"google\", modelId, (p) => {\n const maxTokens = p.getOrDefault(\"maxTokens\", DEFAULT_MAX_TOKENS);\n const config: GenerateContentConfig = {\n maxOutputTokens: maxTokens,\n };\n\n if (systemInstruction) {\n config.systemInstruction = systemInstruction;\n }\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (tools !== undefined && tools.length > 0) {\n // Separate regular tools from provider tools\n const regularTools: ToolSchema[] = [];\n let hasWebSearch = false;\n\n for (const tool of tools) {\n // Check for provider tools first (WebSearchTool extends ProviderTool)\n if (isProviderTool(tool)) {\n if (isWebSearchTool(tool)) {\n hasWebSearch = true;\n } else {\n // Cast needed because TS narrows to never after WebSearchTool check\n const unsupportedTool = tool as ProviderTool;\n throw new FeatureNotSupportedError(\n `Provider tool ${unsupportedTool.name}`,\n \"google\",\n modelId,\n `Provider tool '${unsupportedTool.name}' is not supported by Google`,\n );\n }\n } else {\n // Regular tool (BaseTool extends ToolSchema)\n regularTools.push(tool as ToolSchema);\n }\n }\n\n const googleTools: NonNullable<GenerateContentConfig[\"tools\"]> = [];\n\n if (regularTools.length > 0) {\n googleTools.push(...encodeTools(regularTools));\n }\n\n if (hasWebSearch) {\n googleTools.push({ googleSearch: {} });\n }\n\n if (googleTools.length > 0) {\n config.tools = googleTools;\n }\n }\n /* v8 ignore stop */\n\n const temperature = p.get(\"temperature\");\n if (temperature !== undefined) {\n config.temperature = temperature;\n }\n\n const topP = p.get(\"topP\");\n if (topP !== undefined) {\n config.topP = topP;\n }\n\n const topK = p.get(\"topK\");\n if (topK !== undefined) {\n config.topK = topK;\n }\n\n const stopSequences = p.get(\"stopSequences\");\n if (stopSequences !== undefined) {\n config.stopSequences = stopSequences;\n }\n\n const seed = p.get(\"seed\");\n if (seed !== undefined) {\n config.seed = seed;\n }\n\n const thinkingConfig = p.get(\"thinking\");\n if (thinkingConfig) {\n config.thinkingConfig = computeGoogleThinkingConfig(\n thinkingConfig,\n maxTokens,\n modelId,\n );\n }\n\n return {\n model: modelName(modelId),\n contents,\n config,\n };\n });\n}\n\n/**\n * Serialize a Content object for storage in rawMessage.\n *\n * This mirrors Python's `content.model_dump()` pattern for round-tripping.\n */\nfunction serializeContent(\n content: Content | undefined,\n): Record<string, unknown> {\n /* v8 ignore start - defensive fallback for missing content */\n if (!content) {\n return { role: \"model\", parts: [] };\n }\n /* v8 ignore stop */\n // Copy all non-undefined properties\n const serialized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(content)) {\n if (value !== undefined) {\n serialized[key] = value;\n }\n }\n return serialized;\n}\n\n/**\n * Decode Google API response to Mirascope types.\n *\n * Extracts the assistant message content, finish reason, and usage information\n * from the Google GenerateContentResponse.\n *\n * @param response - Raw response from Google's generateContent API\n * @param modelId - The model ID used for the request\n * @param includeThoughts - Whether to include thinking blocks in the response (default: false)\n * @returns Decoded assistant message, finish reason, and usage information\n */\nexport function decodeResponse(\n response: GenerateContentResponse,\n modelId: GoogleModelId,\n includeThoughts: boolean = false,\n): {\n assistantMessage: AssistantMessage;\n finishReason: FinishReason | null;\n usage: Usage | null;\n} {\n const candidate = response.candidates?.[0];\n /* v8 ignore next - defensive fallback for missing parts */\n const content = candidate?.content?.parts ?? [];\n const decodedContent = decodeContent(content, includeThoughts);\n\n // Store serialized candidate content for round-tripping in resume operations.\n // This format matches what Google expects as Content.\n const serializedRawMessage = serializeContent(candidate?.content);\n\n const assistantMessage: AssistantMessage = {\n role: \"assistant\",\n content: decodedContent,\n name: null,\n providerId: \"google\",\n modelId,\n providerModelName: modelName(modelId),\n rawMessage:\n serializedRawMessage as unknown as AssistantMessage[\"rawMessage\"],\n };\n\n const finishReason = decodeFinishReason(candidate?.finishReason);\n const usage = decodeUsage(response);\n\n return { assistantMessage, finishReason, usage };\n}\n\n/**\n * Decode Google response parts to Mirascope content format.\n *\n * @param parts - Array of Google Part objects from the response\n * @param includeThoughts - Whether to include thought parts\n * @returns Array of Mirascope AssistantContentPart objects\n * @throws FeatureNotSupportedError for unsupported part types (function_call)\n */\nfunction decodeContent(\n parts: Part[],\n includeThoughts: boolean,\n): AssistantContentPart[] {\n const content: AssistantContentPart[] = [];\n\n for (const part of parts) {\n if (part.thought && part.text !== undefined) {\n if (includeThoughts) {\n const thought: Thought = { type: \"thought\", thought: part.text };\n content.push(thought);\n }\n } else if (part.text !== undefined) {\n const text: Text = { type: \"text\", text: part.text };\n content.push(text);\n /* v8 ignore start - tool decoding will be tested via e2e */\n } else if (part.functionCall) {\n // Google doesn't always provide IDs for function calls\n const name = part.functionCall.name ?? \"\";\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: part.functionCall.id ?? UNKNOWN_TOOL_ID,\n name,\n args: JSON.stringify(part.functionCall.args ?? {}),\n };\n content.push(toolCall);\n /* v8 ignore stop */\n /* v8 ignore start - defensive unknown part handling */\n } else {\n // Unknown part type - be strict so we know what we're missing\n const partKeys = Object.keys(part).filter(\n (k) => part[k as keyof Part] !== undefined,\n );\n throw new FeatureNotSupportedError(\n `unknown part type: ${partKeys.join(\", \")}`,\n \"google\",\n null,\n `Unknown content part in response is not yet implemented`,\n );\n }\n /* v8 ignore stop */\n }\n\n return content;\n}\n\n/**\n * Convert Google finish reason to Mirascope FinishReason.\n *\n * Maps Google's finish reasons to the unified Mirascope format:\n * - MAX_TOKENS → FinishReason.MAX_TOKENS\n * - SAFETY, RECITATION, BLOCKLIST, etc. → FinishReason.REFUSAL\n * - STOP or undefined → null (normal completion)\n *\n * @param finishReason - Google finish reason from the response candidate\n * @returns Mirascope FinishReason or null for normal completion\n */\nfunction decodeFinishReason(\n finishReason: GoogleFinishReasonType | undefined,\n): FinishReason | null {\n switch (finishReason) {\n case GoogleFinishReason.MAX_TOKENS:\n return FinishReason.MAX_TOKENS;\n /* v8 ignore next 6 - refusal reasons can't be reliably triggered in e2e tests */\n case GoogleFinishReason.SAFETY:\n case GoogleFinishReason.RECITATION:\n case GoogleFinishReason.BLOCKLIST:\n case GoogleFinishReason.PROHIBITED_CONTENT:\n case GoogleFinishReason.SPII:\n return FinishReason.REFUSAL;\n case GoogleFinishReason.STOP:\n case undefined:\n return null; // Normal completion\n /* v8 ignore next 2 - defensive default case */\n default:\n return null;\n }\n}\n\n/**\n * Extract usage information from the Google response.\n *\n * Maps Google's usage metadata to the unified Mirascope Usage format:\n * - promptTokenCount → inputTokens\n * - candidatesTokenCount + thoughtsTokenCount → outputTokens\n * - cachedContentTokenCount → cacheReadTokens\n * - thoughtsTokenCount → reasoningTokens\n *\n * @param response - Raw Google API response\n * @returns Mirascope Usage object or null if no metadata available\n */\nfunction decodeUsage(response: GenerateContentResponse): Usage | null {\n const metadata = response.usageMetadata;\n /* v8 ignore next 3 - defensive null check */\n if (!metadata) {\n return null;\n }\n\n /* v8 ignore start - token counts always present in practice, fallbacks are defensive */\n return createUsage({\n inputTokens: metadata.promptTokenCount ?? 0,\n outputTokens:\n (metadata.candidatesTokenCount ?? 0) + (metadata.thoughtsTokenCount ?? 0),\n cacheReadTokens: metadata.cachedContentTokenCount ?? 0,\n reasoningTokens: metadata.thoughtsTokenCount ?? 0,\n raw: metadata,\n });\n /* v8 ignore stop */\n}\n","/**\n * Google stream decoding utilities.\n *\n * Converts Google GenerateContentResponse chunks to Mirascope StreamResponseChunk.\n * Google streaming returns complete parts in each chunk, not deltas.\n */\n\nimport type {\n GenerateContentResponse,\n FinishReason as GoogleFinishReasonType,\n} from \"@google/genai\";\n\nimport { FinishReason as GoogleFinishReason } from \"@google/genai\";\n\nimport type { StreamResponseChunk } from \"@/llm/responses/chunks\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport {\n textStart,\n textChunk,\n textEnd,\n thoughtStart,\n thoughtChunk,\n thoughtEnd,\n toolCallStart,\n toolCallChunk,\n toolCallEnd,\n} from \"@/llm/content\";\nimport {\n finishReasonChunk,\n usageDeltaChunk,\n rawStreamEventChunk,\n rawMessageChunk,\n} from \"@/llm/responses/chunks\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\n\n/**\n * Default tool ID for Google function calls when no ID is provided.\n * Google doesn't always provide tool IDs, so we use this as a fallback.\n */\nconst UNKNOWN_TOOL_ID = \"google_unknown_tool_id\";\n\n/**\n * State tracking for stream decoding.\n */\ninterface DecodeState {\n /** Whether we're in a text block */\n inTextBlock: boolean;\n /** Whether we're in a thought block */\n inThoughtBlock: boolean;\n /** Whether to include thoughts in output */\n includeThoughts: boolean;\n}\n\n/**\n * Create a new decode state for a fresh stream.\n */\nexport function createDecodeState(includeThoughts: boolean): DecodeState {\n return {\n inTextBlock: false,\n inThoughtBlock: false,\n includeThoughts,\n };\n}\n\n/**\n * Decode a Google GenerateContentResponse to Mirascope chunks.\n *\n * Unlike Anthropic which streams character-by-character deltas,\n * Google streams complete parts. We still emit start/chunk/end\n * to maintain a consistent interface.\n *\n * @param response - The Google stream response chunk\n * @param state - Mutable state tracking current blocks\n * @returns Array of Mirascope chunks\n */\nexport function decodeStreamEvent(\n response: GenerateContentResponse,\n state: DecodeState,\n): StreamResponseChunk[] {\n const chunks: StreamResponseChunk[] = [];\n\n // Always emit raw event chunk\n chunks.push(rawStreamEventChunk(response));\n\n // Emit raw message chunk\n chunks.push(rawMessageChunk(response as unknown as Jsonable));\n\n const candidate = response.candidates?.[0];\n const parts = candidate?.content?.parts ?? [];\n\n for (const part of parts) {\n if (part.thought && part.text !== undefined) {\n if (state.includeThoughts) {\n // Emit thought start if not already in a thought block\n if (!state.inThoughtBlock) {\n // Close any open text block first\n /* v8 ignore start - edge case when thoughts follow text */\n if (state.inTextBlock) {\n chunks.push(textEnd());\n state.inTextBlock = false;\n }\n /* v8 ignore stop */\n chunks.push(thoughtStart());\n state.inThoughtBlock = true;\n }\n chunks.push(thoughtChunk(part.text));\n }\n } else if (part.text !== undefined) {\n if (!state.inTextBlock) {\n // Close any open thought block first\n if (state.inThoughtBlock) {\n chunks.push(thoughtEnd());\n state.inThoughtBlock = false;\n }\n chunks.push(textStart());\n state.inTextBlock = true;\n }\n chunks.push(textChunk(part.text));\n } else if (part.functionCall) {\n const functionCall = part.functionCall;\n const toolId = functionCall.id ?? UNKNOWN_TOOL_ID;\n const toolName = functionCall.name;\n\n /* v8 ignore start - defensive check for malformed Google API response */\n if (!toolName) {\n throw new Error(\"Required name missing on Google function call\");\n }\n /* v8 ignore stop */\n\n // Close any open blocks before emitting tool call\n /* v8 ignore start - Google doesn't send text and function calls together */\n if (state.inTextBlock) {\n chunks.push(textEnd());\n state.inTextBlock = false;\n }\n /* v8 ignore stop */\n /* v8 ignore start - edge case when thought block open at function call */\n if (state.inThoughtBlock) {\n chunks.push(thoughtEnd());\n state.inThoughtBlock = false;\n }\n /* v8 ignore stop */\n\n // Google sends complete function calls, so we emit start/chunk/end together\n chunks.push(toolCallStart(toolId, toolName));\n chunks.push(\n toolCallChunk(\n toolId,\n /* v8 ignore next 1 - empty args branch */\n functionCall.args ? JSON.stringify(functionCall.args) : \"{}\",\n ),\n );\n chunks.push(toolCallEnd(toolId));\n }\n }\n\n if (candidate?.finishReason) {\n // Close any open blocks\n if (state.inTextBlock) {\n chunks.push(textEnd());\n state.inTextBlock = false;\n }\n /* v8 ignore start - edge case when thought block open at finish */\n if (state.inThoughtBlock) {\n chunks.push(thoughtEnd());\n state.inThoughtBlock = false;\n }\n /* v8 ignore stop */\n\n const finishReason = decodeFinishReason(candidate.finishReason);\n if (finishReason) {\n chunks.push(finishReasonChunk(finishReason));\n }\n }\n\n const usage = response.usageMetadata;\n if (usage) {\n chunks.push(\n usageDeltaChunk({\n inputTokens: usage.promptTokenCount ?? /* v8 ignore next 1 */ 0,\n outputTokens:\n (usage.candidatesTokenCount ?? /* v8 ignore next 1 */ 0) +\n (usage.thoughtsTokenCount ?? /* v8 ignore next 1 */ 0),\n cacheReadTokens:\n usage.cachedContentTokenCount ?? /* v8 ignore next 1 */ 0,\n reasoningTokens: usage.thoughtsTokenCount ?? /* v8 ignore next 1 */ 0,\n }),\n );\n }\n\n return chunks;\n}\n\n/**\n * Convert Google finish reason to Mirascope FinishReason.\n */\nfunction decodeFinishReason(\n finishReason: GoogleFinishReasonType | undefined,\n): FinishReason | null {\n switch (finishReason) {\n case GoogleFinishReason.MAX_TOKENS:\n return FinishReason.MAX_TOKENS;\n /* v8 ignore start - refusal cases are rare and hard to trigger reliably */\n case GoogleFinishReason.SAFETY:\n case GoogleFinishReason.RECITATION:\n case GoogleFinishReason.BLOCKLIST:\n case GoogleFinishReason.PROHIBITED_CONTENT:\n case GoogleFinishReason.SPII:\n return FinishReason.REFUSAL;\n /* v8 ignore end */\n case GoogleFinishReason.STOP:\n case undefined:\n return null; // Normal completion\n /* v8 ignore start - exhaustive switch default */\n default:\n return null;\n /* v8 ignore end */\n }\n}\n\n/**\n * Create an async iterator that decodes Google stream responses to Mirascope chunks.\n *\n * @param stream - The Google content stream\n * @param includeThoughts - Whether to include thinking as thought chunks\n * @returns Async iterator of Mirascope chunks\n */\nexport async function* decodeStream(\n stream: AsyncIterable<GenerateContentResponse>,\n includeThoughts: boolean,\n): AsyncGenerator<StreamResponseChunk> {\n const state = createDecodeState(includeThoughts);\n\n for await (const response of stream) {\n const chunks = decodeStreamEvent(response, state);\n for (const chunk of chunks) {\n yield chunk;\n }\n }\n}\n","/**\n * Shared base of Response implementations.\n */\n\nimport type {\n AssistantContentPart,\n Text,\n Thought,\n ToolCall,\n} from \"@/llm/content\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { AssistantMessage, Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { ModelId, ProviderId } from \"@/llm/providers\";\nimport type { FinishReason } from \"@/llm/responses/finish-reason\";\nimport type { Usage } from \"@/llm/responses/usage\";\nimport type { BaseToolkit } from \"@/llm/tools\";\n\nimport { FORMAT_TOOL_NAME } from \"@/llm/formatting\";\nimport { RootResponse } from \"@/llm/responses/root-response\";\n\n/**\n * Initialization options for creating a BaseResponse.\n */\nexport interface BaseResponseInit {\n /**\n * The raw response from the LLM provider.\n */\n raw: unknown;\n\n /**\n * The provider that generated this response.\n */\n providerId: ProviderId;\n\n /**\n * The model ID that generated this response.\n */\n modelId: ModelId;\n\n /**\n * Provider-specific model name (may include additional info like API mode).\n */\n providerModelName: string;\n\n /**\n * The parameters used to generate this response.\n */\n params: Params;\n\n /**\n * The toolkit containing all tools available for this response.\n * Can be a Toolkit or ContextToolkit.\n */\n toolkit: BaseToolkit;\n\n /**\n * The Format describing the structured response format, if any.\n */\n format?: Format | null;\n\n /**\n * The input messages (before the assistant response).\n */\n inputMessages: readonly Message[];\n\n /**\n * The assistant message containing the response content.\n */\n assistantMessage: AssistantMessage;\n\n /**\n * The reason generation stopped, if not normal completion.\n */\n finishReason: FinishReason | null;\n\n /**\n * Token usage statistics, if available.\n */\n usage: Usage | null;\n}\n\n/**\n * Base response class with constructor logic.\n *\n * This class processes the assistant message content, organizing it by type\n * (text, tool calls, thoughts) for easy access.\n *\n * @template F - The type of the formatted output when using structured outputs.\n */\nexport class BaseResponse<F = unknown> extends RootResponse<F> {\n readonly raw: unknown;\n readonly providerId: ProviderId;\n readonly modelId: ModelId;\n readonly providerModelName: string;\n readonly params: Params;\n readonly messages: readonly Message[];\n readonly content: readonly AssistantContentPart[];\n readonly texts: readonly Text[];\n readonly toolCalls: readonly ToolCall[];\n readonly thoughts: readonly Thought[];\n readonly finishReason: FinishReason | null;\n readonly usage: Usage | null;\n readonly format: Format | null;\n readonly toolkit: BaseToolkit;\n\n constructor(init: BaseResponseInit) {\n super();\n\n this.raw = init.raw;\n this.providerId = init.providerId;\n this.modelId = init.modelId;\n this.providerModelName = init.providerModelName;\n this.params = init.params;\n this.finishReason = init.finishReason;\n this.usage = init.usage;\n this.format = init.format ?? null;\n\n // Process content from assistant message, organizing by type\n // FORMAT_TOOL calls are transformed to text content for parse() access\n const texts: Text[] = [];\n const toolCalls: ToolCall[] = [];\n const thoughts: Thought[] = [];\n const content: AssistantContentPart[] = [];\n\n for (const part of init.assistantMessage.content) {\n if (part.type === \"text\") {\n texts.push(part);\n content.push(part);\n /* v8 ignore start - tool_call and thought content not yet implemented */\n } else if (part.type === \"tool_call\") {\n // Transform FORMAT_TOOL calls to text content\n // The tool call args contain the JSON structured output\n if (part.name.startsWith(FORMAT_TOOL_NAME)) {\n const textPart: Text = { type: \"text\", text: part.args };\n texts.push(textPart);\n content.push(textPart);\n } else {\n toolCalls.push(part);\n content.push(part);\n }\n } else if (part.type === \"thought\") {\n thoughts.push(part);\n content.push(part);\n }\n /* v8 ignore stop */\n }\n\n this.texts = texts;\n this.toolCalls = toolCalls;\n this.thoughts = thoughts;\n this.content = content;\n\n // Build full message history\n this.messages = [...init.inputMessages, init.assistantMessage];\n\n // Store the toolkit directly (conversion from tools happens in child classes)\n this.toolkit = init.toolkit;\n }\n}\n","/**\n * ContextResponse class for context-based LLM calls.\n *\n * Extends BaseResponse with context-aware functionality including:\n * - executeTools(): Execute tool calls with context dependency injection\n * - resume(): Continue the conversation with additional user content\n */\n\nimport type { ToolOutput } from \"@/llm/content/tool-output\";\nimport type { Context } from \"@/llm/context\";\nimport type { UserContent } from \"@/llm/messages\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport {\n BaseResponse,\n type BaseResponseInit,\n} from \"@/llm/responses/base-response\";\nimport { ContextToolkit, type ContextTools } from \"@/llm/tools\";\n\n/**\n * Initialization options for creating a ContextResponse.\n *\n * Accepts `tools` as either a ContextToolkit or a list of tools, which gets\n * converted to a ContextToolkit before passing to BaseResponse.\n *\n * Supports both regular tools (BaseTool) and context tools (BaseContextTool),\n * matching Python's `ContextTools[DepsT]` pattern.\n *\n * @template DepsT - The type of dependencies in the context.\n */\nexport interface ContextResponseInit<DepsT = unknown> extends Omit<\n BaseResponseInit,\n \"toolkit\"\n> {\n /**\n * The tools available for this response.\n * Can be a ContextToolkit instance or an array of tools.\n * Accepts both regular tools and context tools.\n */\n tools?: ContextTools<DepsT> | ContextToolkit<DepsT>;\n}\n\n/**\n * The response generated by an LLM from a context call.\n *\n * This class provides context-aware functionality on top of the standard response:\n * - `executeTools()`: Execute all tool calls with context dependency injection\n * - `resume()`: Continue the conversation with additional user content\n *\n * @template DepsT - The type of dependencies in the context.\n * @template F - The type of the formatted output when using structured outputs.\n *\n * @example\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await myPrompt(model, ctx);\n * console.log(response.text());\n *\n * // Continue the conversation\n * const followUp = await response.resume(ctx, 'Tell me more');\n * ```\n */\nexport class ContextResponse<\n DepsT = unknown,\n F = unknown,\n> extends BaseResponse<F> {\n /**\n * The context toolkit containing tools that can receive context.\n */\n readonly contextToolkit: ContextToolkit<DepsT>;\n\n constructor(init: ContextResponseInit<DepsT>) {\n // Convert tools to context toolkit (matching Python's pattern)\n const contextToolkit =\n init.tools instanceof ContextToolkit\n ? init.tools\n : new ContextToolkit(init.tools ?? []);\n\n // Pass an empty toolkit to base since context responses use contextToolkit\n super({ ...init, toolkit: contextToolkit });\n\n this.contextToolkit = contextToolkit;\n }\n\n /**\n * Execute all tool calls in this response using the registered context tools.\n *\n * @param ctx - The context containing dependencies to pass to tools.\n * @returns An array of ToolOutput objects, one for each tool call.\n *\n * @example\n * ```typescript\n * const response = await myPrompt(model, ctx, [searchTool]);\n * if (response.toolCalls.length > 0) {\n * const outputs = await response.executeTools(ctx);\n * const followUp = await response.resume(ctx, outputs);\n * }\n * ```\n */\n async executeTools(ctx: Context<DepsT>): Promise<ToolOutput<Jsonable>[]> {\n return this.contextToolkit.executeAll(ctx, this.toolCalls);\n }\n\n /**\n * Generate a new ContextResponse using this response's messages with additional user content.\n *\n * Uses this response's tools and format type. Also uses this response's provider,\n * model, and params.\n *\n * @param ctx - A Context with the required deps type.\n * @param content - The new user message content to append to the message history.\n * @returns A new ContextResponse instance generated from the extended message history.\n *\n * @example\n * ```typescript\n * const response = await myPrompt(model, ctx);\n * console.log(response.text());\n *\n * // Continue the conversation\n * const followUp = await response.resume(ctx, 'Tell me more about that');\n * console.log(followUp.text());\n * ```\n */\n async resume(\n ctx: Context<DepsT>,\n content: UserContent,\n ): Promise<ContextResponse<DepsT, F>> {\n const model = await this.model;\n return model.contextResume(ctx, this, content) as Promise<\n ContextResponse<DepsT, F>\n >;\n }\n}\n","/**\n * Stream classes for streaming assistant content parts.\n *\n * Each stream wraps a chunk iterator and provides:\n * - Async iteration via [Symbol.asyncIterator]() yielding delta strings\n * - collect() to consume remaining chunks and return the final content object\n * - Partial accumulation properties to track content as it arrives\n */\n\nimport type {\n Text,\n TextChunk,\n Thought,\n ThoughtChunk,\n ToolCall,\n ToolCallChunk,\n} from \"@/llm/content\";\n\n/**\n * Stream for text content.\n *\n * Wraps a TextChunk iterator and yields text delta strings.\n * Accumulates text in partialText as chunks are consumed.\n */\nexport class TextStream {\n readonly type = \"text_stream\" as const;\n readonly contentType = \"text\" as const;\n\n /** The accumulated text content as chunks are received. */\n partialText: string = \"\";\n\n private _chunkIterator: AsyncIterator<TextChunk>;\n\n constructor(chunkIterator: AsyncIterator<TextChunk>) {\n this._chunkIterator = chunkIterator;\n }\n\n /**\n * Iterate over text deltas as they are received.\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<string> {\n let result = await this._chunkIterator.next();\n while (!result.done) {\n const delta = result.value.delta;\n this.partialText += delta;\n yield delta;\n result = await this._chunkIterator.next();\n }\n }\n\n /**\n * Collect all chunks and return the final Text content.\n */\n async collect(): Promise<Text> {\n for await (const _ of this) {\n // Just consume\n }\n return { type: \"text\", text: this.partialText };\n }\n}\n\n/**\n * Stream for thought/reasoning content.\n *\n * Wraps a ThoughtChunk iterator and yields thought delta strings.\n * Accumulates thought in partialThought as chunks are consumed.\n */\nexport class ThoughtStream {\n readonly type = \"thought_stream\" as const;\n readonly contentType = \"thought\" as const;\n\n /** The accumulated thought content as chunks are received. */\n partialThought: string = \"\";\n\n private _chunkIterator: AsyncIterator<ThoughtChunk>;\n\n constructor(chunkIterator: AsyncIterator<ThoughtChunk>) {\n this._chunkIterator = chunkIterator;\n }\n\n /**\n * Iterate over thought deltas as they are received.\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<string> {\n let result = await this._chunkIterator.next();\n while (!result.done) {\n const delta = result.value.delta;\n this.partialThought += delta;\n yield delta;\n result = await this._chunkIterator.next();\n }\n }\n\n /**\n * Collect all chunks and return the final Thought content.\n */\n async collect(): Promise<Thought> {\n for await (const _ of this) {\n // Just consume\n }\n return { type: \"thought\", thought: this.partialThought };\n }\n}\n\n/**\n * Stream for tool call content.\n *\n * Wraps a ToolCallChunk iterator and yields argument delta strings.\n * Accumulates args in partialArgs as chunks are consumed.\n */\nexport class ToolCallStream {\n readonly type = \"tool_call_stream\" as const;\n readonly contentType = \"tool_call\" as const;\n\n /** A unique identifier for this tool call. */\n readonly toolId: string;\n\n /** The name of the tool being called. */\n readonly toolName: string;\n\n /** The accumulated tool arguments as chunks are received. */\n partialArgs: string = \"\";\n\n private _chunkIterator: AsyncIterator<ToolCallChunk>;\n\n constructor(\n toolId: string,\n toolName: string,\n chunkIterator: AsyncIterator<ToolCallChunk>,\n ) {\n this.toolId = toolId;\n this.toolName = toolName;\n this._chunkIterator = chunkIterator;\n }\n\n /**\n * Iterate over tool call argument deltas as they are received.\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<string> {\n let result = await this._chunkIterator.next();\n while (!result.done) {\n const delta = result.value.delta;\n this.partialArgs += delta;\n yield delta;\n result = await this._chunkIterator.next();\n }\n }\n\n /**\n * Collect all chunks and return the final ToolCall content.\n */\n async collect(): Promise<ToolCall> {\n for await (const _ of this) {\n // Just consume\n }\n return {\n type: \"tool_call\",\n id: this.toolId,\n name: this.toolName,\n args: this.partialArgs,\n };\n }\n}\n\n/**\n * A stream for any assistant content type.\n */\nexport type Stream = TextStream | ThoughtStream | ToolCallStream;\n","/**\n * BaseStreamResponse class for handling streaming LLM responses.\n *\n * Extends RootResponse to provide the standard response interface while adding\n * streaming-specific methods:\n * - chunkStream(): Raw chunks as async iterator (with caching for replay)\n * - textStream(): Text deltas only\n * - thoughtStream(): Thought deltas only\n * - structuredStream(): Partial parsed objects for structured output streaming\n *\n * Accumulates content as chunks arrive, with final state accessible via\n * the standard RootResponse interface (text(), content, finishReason, usage, etc.).\n *\n * This base class contains all streaming logic but no resume methods.\n * StreamResponse and ContextStreamResponse extend this class and add their\n * own resume methods with appropriate signatures.\n */\n\nimport type {\n AssistantContentChunk,\n AssistantContentPart,\n Text,\n TextChunk,\n Thought,\n ThoughtChunk,\n ToolCall,\n ToolCallChunk,\n} from \"@/llm/content\";\nimport type { DeepPartial, Format } from \"@/llm/formatting\";\nimport type { AssistantMessage, Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { ModelId, ProviderId } from \"@/llm/providers\";\nimport type { StreamResponseChunk } from \"@/llm/responses/chunks\";\nimport type { FinishReason } from \"@/llm/responses/finish-reason\";\nimport type { Usage } from \"@/llm/responses/usage\";\nimport type { BaseToolkit } from \"@/llm/tools\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport { FORMAT_TOOL_NAME } from \"@/llm/formatting\";\nimport { RootResponse } from \"@/llm/responses/root-response\";\nimport {\n TextStream,\n ThoughtStream,\n ToolCallStream,\n type Stream,\n} from \"@/llm/responses/streams\";\nimport { createUsage } from \"@/llm/responses/usage\";\n\n/**\n * Arguments for constructing a BaseStreamResponse.\n */\nexport interface BaseStreamResponseInit {\n /** The provider ID (e.g., 'anthropic', 'openai') */\n providerId: ProviderId;\n\n /** The model ID (e.g., 'anthropic/claude-sonnet-4-20250514') */\n modelId: ModelId;\n\n /** The provider's model name from the response */\n providerModelName: string;\n\n /** Parameters used for the request */\n params: Params;\n\n /** The toolkit containing all tools available for this response */\n toolkit: BaseToolkit;\n\n /** The Format describing the structured response format, if any */\n format?: Format | null;\n\n /** Input messages sent in the request */\n inputMessages: readonly Message[];\n\n /** Async iterator of streaming chunks from the provider */\n chunkIterator: AsyncIterator<StreamResponseChunk>;\n}\n\n/**\n * Base streaming response that consumes chunks from an async iterator.\n *\n * Extends RootResponse to provide the standard response interface. Chunks are\n * processed lazily and cached for replay. Content is accumulated as chunks\n * arrive, with text/thought objects mutated in place for efficiency.\n *\n * This class contains all streaming logic but no resume methods. Subclasses\n * (StreamResponse, ContextStreamResponse) add their own resume methods.\n *\n * @template F - The type of the formatted output when using structured outputs.\n */\nexport class BaseStreamResponse<F = unknown> extends RootResponse<F> {\n // ===== RootResponse Implementation =====\n\n /** Raw stream events from provider */\n get raw(): readonly unknown[] {\n return this._rawStreamEvents;\n }\n\n readonly providerId: ProviderId;\n readonly modelId: ModelId;\n readonly providerModelName: string;\n readonly params: Params;\n readonly toolkit: BaseToolkit;\n readonly format: Format | null;\n\n /** Input messages sent in the request */\n readonly inputMessages: readonly Message[];\n\n get messages(): readonly Message[] {\n return [...this.inputMessages, this.assistantMessage];\n }\n\n get content(): readonly AssistantContentPart[] {\n return this._content;\n }\n\n get texts(): readonly Text[] {\n return this._texts;\n }\n\n get toolCalls(): readonly ToolCall[] {\n return this._toolCalls;\n }\n\n get thoughts(): readonly Thought[] {\n return this._thoughts;\n }\n\n get finishReason(): FinishReason | null {\n return this._finishReason;\n }\n\n get usage(): Usage | null {\n return this._usage;\n }\n\n // ===== Streaming-Specific Properties =====\n\n /** Cached chunks for replay */\n private readonly _chunks: AssistantContentChunk[] = [];\n /** Accumulated content parts */\n private readonly _content: AssistantContentPart[] = [];\n /** Accumulated text parts */\n private readonly _texts: Text[] = [];\n /** Accumulated thought parts */\n private readonly _thoughts: Thought[] = [];\n /** Accumulated tool calls */\n private readonly _toolCalls: ToolCall[] = [];\n /** Raw stream events from provider */\n private readonly _rawStreamEvents: unknown[] = [];\n\n /** The chunk iterator from the provider */\n private _chunkIterator: AsyncIterator<StreamResponseChunk>;\n /** Current content block being built (Text or Thought) */\n private _currentContent:\n | (Text & { text: string })\n | (Thought & { thought: string })\n | null = null;\n /** In-progress tool calls tracked by ID (for interleaved streaming) */\n private readonly _currentToolCalls = new Map<\n string,\n ToolCall & { args: string }\n >();\n /** Whether the iterator has been fully consumed */\n private _consumed = false;\n /** Whether we're currently processing a FORMAT_TOOL call (transforming to text) */\n private _processingFormatTool = false;\n\n /** Finish reason once stream is complete */\n private _finishReason: FinishReason | null = null;\n /** Accumulated usage statistics */\n private _usage: Usage | null = null;\n /** Raw message from provider */\n private _rawMessage: Jsonable = null;\n\n constructor(args: BaseStreamResponseInit) {\n super();\n this.providerId = args.providerId;\n this.modelId = args.modelId;\n this.providerModelName = args.providerModelName;\n this.params = args.params;\n this.toolkit = args.toolkit;\n this.format = args.format ?? null;\n this.inputMessages = args.inputMessages;\n this._chunkIterator = args.chunkIterator;\n }\n\n // ===== Streaming-Specific Methods =====\n\n /**\n * Get the cached chunks.\n */\n get chunks(): readonly AssistantContentChunk[] {\n return this._chunks;\n }\n\n /**\n * Whether the stream has been fully consumed.\n */\n get consumed(): boolean {\n return this._consumed;\n }\n\n /**\n * Get the accumulated thought content.\n * Joins all thought parts with the specified separator.\n */\n thought(separator = \"\\n\"): string {\n return this._thoughts.map((t) => t.thought).join(separator);\n }\n\n /**\n * Build the assistant message from accumulated content.\n */\n get assistantMessage(): AssistantMessage {\n return {\n role: \"assistant\",\n content: [...this._content],\n name: null,\n providerId: this.providerId,\n modelId: this.modelId,\n providerModelName: this.providerModelName,\n rawMessage: this._rawMessage,\n };\n }\n\n /**\n * Stream content chunks with caching for replay.\n *\n * First yields any cached chunks, then continues consuming from the iterator.\n * All chunks are cached so subsequent calls can replay from the beginning.\n */\n async *chunkStream(): AsyncGenerator<AssistantContentChunk> {\n // First, yield all cached chunks (replay mechanism)\n for (const chunk of this._chunks) {\n yield chunk;\n }\n\n // If stream is already fully consumed, stop\n if (this._consumed) {\n return;\n }\n\n // Consume fresh chunks from the iterator\n let result = await this._chunkIterator.next();\n while (!result.done) {\n const chunk = result.value;\n const contentChunk = this._processChunk(chunk);\n if (contentChunk) {\n yield contentChunk;\n }\n result = await this._chunkIterator.next();\n }\n\n // Mark stream as fully consumed\n this._consumed = true;\n }\n\n /**\n * Stream only text deltas.\n *\n * Yields the text string from each TextChunk, filtering out other chunk types.\n */\n async *textStream(): AsyncGenerator<string> {\n for await (const chunk of this.chunkStream()) {\n if (chunk.type === \"text_chunk\") {\n yield chunk.delta;\n }\n }\n }\n\n /**\n * Stream only thought deltas.\n *\n * Yields the thought string from each ThoughtChunk, filtering out other chunk types.\n */\n async *thoughtStream(): AsyncGenerator<string> {\n for await (const chunk of this.chunkStream()) {\n if (chunk.type === \"thought_chunk\") {\n yield chunk.delta;\n }\n }\n }\n\n /**\n * Stream partial parsed objects as they arrive during structured output streaming.\n *\n * This method drives the stream forward, parsing the accumulated text content\n * as partial JSON after each text chunk arrives. The yielded objects may have\n * missing or incomplete fields early in the stream, gradually becoming complete.\n *\n * @yields DeepPartial<F> - Partial objects with fields populated as they arrive.\n * @throws Error if format was not specified or uses OutputParser.\n *\n * @example\n * ```typescript\n * interface Book { title: string; author: string; }\n *\n * const stream = await model.stream<Book>('Recommend a book', {\n * format: BookSchema\n * });\n *\n * for await (const partial of stream.structuredStream()) {\n * console.log(partial.title); // May be undefined initially\n * console.log(partial.author); // Populated as it arrives\n * }\n *\n * // After stream completes, get the final validated result\n * const book = stream.parse();\n * ```\n */\n async *structuredStream(): AsyncGenerator<DeepPartial<F>> {\n if (!this.format) {\n throw new Error(\"structuredStream() requires format parameter\");\n }\n if (this.format.outputParser) {\n throw new Error(\"structuredStream() is not supported for OutputParser\");\n }\n\n for await (const chunk of this.chunkStream()) {\n if (chunk.type === \"text_chunk\") {\n const partial = this.parse({ partial: true });\n if (partial !== null) {\n yield partial as DeepPartial<F>;\n }\n }\n }\n }\n\n /**\n * Consume the entire stream without processing chunks.\n * Useful when you just want the final accumulated state.\n */\n async consume(): Promise<void> {\n for await (const _ of this.chunkStream()) {\n // Just consume\n }\n }\n\n /**\n * Returns an async iterator that yields streams for each content part in the response.\n *\n * Each content part in the response will correspond to one stream, which will yield\n * chunks of content as they come in from the underlying LLM.\n *\n * Fully iterating through this iterator will fully consume the underlying stream,\n * updating the Response with all collected content.\n *\n * As content is consumed, it is cached on the StreamResponse. If a new iterator\n * is constructed via calling `streams()`, it will start by replaying the cached\n * content from the response, and (if there is still more content to consume from\n * the LLM), it will proceed to consume it once it has iterated through all the\n * cached chunks.\n */\n async *streams(): AsyncGenerator<Stream> {\n const chunkIter = this.chunkStream();\n\n // Use manual iteration to avoid closing the iterator on early return.\n // Using for-await-of would call iter.return() when the inner generator\n // returns, which would close chunkIter and prevent _consumed from being set.\n let result = await chunkIter.next();\n while (!result.done) {\n const startChunk = result.value;\n\n // At the start of this loop, we always expect to find a start chunk. Then,\n // before proceeding, we will collect from the stream we create (in case the\n // user did not exhaust it), which ensures we will be expecting a start chunk\n // again on the next iteration\n let stream: Stream;\n\n switch (startChunk.type) {\n case \"text_start_chunk\": {\n const textStreamIterator = async function* (\n iter: AsyncGenerator<AssistantContentChunk>,\n ): AsyncGenerator<TextChunk> {\n // Use manual iteration to avoid closing the outer iterator\n let innerResult = await iter.next();\n while (!innerResult.done) {\n const chunk = innerResult.value;\n if (chunk.type === \"text_chunk\") {\n yield chunk;\n innerResult = await iter.next();\n } else {\n return; // Stream finished\n }\n }\n };\n stream = new TextStream(textStreamIterator(chunkIter));\n yield stream;\n break;\n }\n\n case \"thought_start_chunk\": {\n const thoughtStreamIterator = async function* (\n iter: AsyncGenerator<AssistantContentChunk>,\n ): AsyncGenerator<ThoughtChunk> {\n // Use manual iteration to avoid closing the outer iterator\n let innerResult = await iter.next();\n while (!innerResult.done) {\n const chunk = innerResult.value;\n if (chunk.type === \"thought_chunk\") {\n yield chunk;\n innerResult = await iter.next();\n } else {\n return; // Stream finished\n }\n }\n };\n stream = new ThoughtStream(thoughtStreamIterator(chunkIter));\n yield stream;\n break;\n }\n\n case \"tool_call_start_chunk\": {\n const toolId = startChunk.id;\n const toolName = startChunk.name;\n\n const toolCallStreamIterator = async function* (\n iter: AsyncGenerator<AssistantContentChunk>,\n ): AsyncGenerator<ToolCallChunk> {\n // Use manual iteration to avoid closing the outer iterator\n let innerResult = await iter.next();\n while (!innerResult.done) {\n const chunk = innerResult.value;\n if (chunk.type === \"tool_call_chunk\") {\n yield chunk;\n innerResult = await iter.next();\n } else {\n return; // Stream finished\n }\n }\n };\n stream = new ToolCallStream(\n toolId,\n toolName,\n toolCallStreamIterator(chunkIter),\n );\n yield stream;\n break;\n }\n\n default:\n throw new Error(`Expected start chunk, got: ${startChunk.type}`);\n }\n\n // Before continuing to the next stream, make sure the last stream is consumed\n // (If the user did not do so when we yielded it)\n await stream.collect();\n\n result = await chunkIter.next();\n }\n }\n\n /**\n * Replace the chunk iterator with a wrapped version.\n * Used internally by providers to wrap errors during iteration.\n * @internal\n */\n wrapChunkIterator(\n wrapper: (\n iterator: AsyncIterator<StreamResponseChunk>,\n ) => AsyncIterator<StreamResponseChunk>,\n ): void {\n this._chunkIterator = wrapper(this._chunkIterator);\n }\n\n // ===== Private Helpers =====\n\n /**\n * Transform FORMAT_TOOL chunks to text chunks.\n *\n * When the format uses tool mode, the LLM generates tool calls to the\n * FORMAT_TOOL. These chunks are transformed to text chunks so that the\n * structured output appears as text content for parse() to consume.\n *\n * @param chunk - The original chunk from the provider.\n * @returns The transformed chunk (tool_call → text) or the original chunk.\n */\n private _transformFormatToolChunk(\n chunk: StreamResponseChunk,\n ): StreamResponseChunk {\n // Handle tool_call_start_chunk: Transform FORMAT_TOOL start to text_start\n if (\n chunk.type === \"tool_call_start_chunk\" &&\n chunk.name.startsWith(FORMAT_TOOL_NAME)\n ) {\n this._processingFormatTool = true;\n return { type: \"text_start_chunk\", contentType: \"text\" };\n }\n\n // Handle tool_call_chunk: Transform FORMAT_TOOL chunk to text_chunk\n if (this._processingFormatTool && chunk.type === \"tool_call_chunk\") {\n return { type: \"text_chunk\", contentType: \"text\", delta: chunk.delta };\n }\n\n // Handle tool_call_end_chunk: Transform FORMAT_TOOL end to text_end\n if (this._processingFormatTool && chunk.type === \"tool_call_end_chunk\") {\n this._processingFormatTool = false;\n return { type: \"text_end_chunk\", contentType: \"text\" };\n }\n\n return chunk;\n }\n\n /**\n * Process a single chunk, handling metadata and content accumulation.\n * Returns the content chunk if it should be yielded, null otherwise.\n */\n private _processChunk(\n chunk: StreamResponseChunk,\n ): AssistantContentChunk | null {\n // Transform FORMAT_TOOL chunks to text chunks\n const transformedChunk = this._transformFormatToolChunk(chunk);\n\n switch (transformedChunk.type) {\n // Metadata chunks - handle internally, don't yield\n case \"raw_stream_event_chunk\":\n this._rawStreamEvents.push(transformedChunk.rawStreamEvent);\n return null;\n\n case \"raw_message_chunk\":\n this._rawMessage = transformedChunk.rawMessage;\n return null;\n\n case \"finish_reason_chunk\":\n this._finishReason = transformedChunk.finishReason;\n return null;\n\n case \"usage_delta_chunk\":\n this._accumulateUsage(transformedChunk);\n return null;\n\n case \"text_start_chunk\":\n case \"text_chunk\":\n case \"text_end_chunk\":\n return this._handleTextChunk(transformedChunk);\n\n case \"thought_start_chunk\":\n case \"thought_chunk\":\n case \"thought_end_chunk\":\n return this._handleThoughtChunk(transformedChunk);\n\n case \"tool_call_start_chunk\":\n case \"tool_call_chunk\":\n case \"tool_call_end_chunk\":\n return this._handleToolCallChunk(transformedChunk);\n }\n }\n\n /**\n * Handle text chunks, accumulating content.\n */\n private _handleTextChunk(\n chunk:\n | { type: \"text_start_chunk\"; contentType: \"text\" }\n | { type: \"text_chunk\"; contentType: \"text\"; delta: string }\n | { type: \"text_end_chunk\"; contentType: \"text\" },\n ): AssistantContentChunk {\n if (chunk.type === \"text_start_chunk\") {\n // Create new Text object and add to content immediately\n const text: Text & { text: string } = { type: \"text\", text: \"\" };\n this._currentContent = text;\n this._content.push(text);\n this._texts.push(text);\n } else if (chunk.type === \"text_chunk\") {\n // Mutate the existing Text object in place\n if (this._currentContent && \"text\" in this._currentContent) {\n this._currentContent.text += chunk.delta;\n }\n } else if (chunk.type === \"text_end_chunk\") {\n // Mark text as complete\n this._currentContent = null;\n }\n\n // Cache and return the chunk\n this._chunks.push(chunk);\n return chunk;\n }\n\n /**\n * Handle thought chunks, accumulating content.\n */\n private _handleThoughtChunk(\n chunk:\n | { type: \"thought_start_chunk\"; contentType: \"thought\" }\n | { type: \"thought_chunk\"; contentType: \"thought\"; delta: string }\n | { type: \"thought_end_chunk\"; contentType: \"thought\" },\n ): AssistantContentChunk {\n if (chunk.type === \"thought_start_chunk\") {\n // Create new Thought object and add to content immediately\n const thought: Thought & { thought: string } = {\n type: \"thought\",\n thought: \"\",\n };\n this._currentContent = thought;\n this._content.push(thought);\n this._thoughts.push(thought);\n } else if (chunk.type === \"thought_chunk\") {\n // Mutate the existing Thought object in place\n if (this._currentContent && \"thought\" in this._currentContent) {\n this._currentContent.thought += chunk.delta;\n }\n } else if (chunk.type === \"thought_end_chunk\") {\n // Mark thought as complete\n this._currentContent = null;\n }\n\n // Cache and return the chunk\n this._chunks.push(chunk);\n return chunk;\n }\n\n /**\n * Handle tool call chunks, accumulating content.\n *\n * Unlike text/thought which are added immediately to content,\n * tool calls are only added once the end chunk is received.\n * Multiple tool calls can be in progress simultaneously (interleaved).\n */\n private _handleToolCallChunk(\n chunk:\n | {\n type: \"tool_call_start_chunk\";\n contentType: \"tool_call\";\n id: string;\n name: string;\n }\n | {\n type: \"tool_call_chunk\";\n contentType: \"tool_call\";\n id: string;\n delta: string;\n }\n | { type: \"tool_call_end_chunk\"; contentType: \"tool_call\"; id: string },\n ): AssistantContentChunk {\n if (chunk.type === \"tool_call_start_chunk\") {\n // Create new ToolCall and track by ID\n if (this._currentToolCalls.has(chunk.id)) {\n throw new Error(\n `Received tool_call_start_chunk with duplicate id: ${chunk.id}`,\n );\n }\n const toolCall: ToolCall & { args: string } = {\n type: \"tool_call\",\n id: chunk.id,\n name: chunk.name,\n args: \"\",\n };\n this._currentToolCalls.set(chunk.id, toolCall);\n } else if (chunk.type === \"tool_call_chunk\") {\n // Append delta to existing tool call's args\n const toolCall = this._currentToolCalls.get(chunk.id);\n if (!toolCall) {\n throw new Error(\n `Received tool_call_chunk for unknown tool call ID: ${chunk.id}`,\n );\n }\n toolCall.args += chunk.delta;\n } else if (chunk.type === \"tool_call_end_chunk\") {\n // Finalize tool call and add to content\n const toolCall = this._currentToolCalls.get(chunk.id);\n if (!toolCall) {\n throw new Error(\n `Received tool_call_end_chunk for unknown tool call ID: ${chunk.id}`,\n );\n }\n // Default empty args to empty object (matches Python behavior)\n if (!toolCall.args) {\n toolCall.args = \"{}\";\n }\n this._content.push(toolCall);\n this._toolCalls.push(toolCall);\n this._currentToolCalls.delete(chunk.id);\n }\n\n // Cache and return the chunk\n this._chunks.push(chunk);\n return chunk;\n }\n\n /**\n * Accumulate usage statistics from a usage delta chunk.\n */\n private _accumulateUsage(chunk: {\n type: \"usage_delta_chunk\";\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n reasoningTokens: number;\n }): void {\n if (this._usage === null) {\n this._usage = createUsage({\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n reasoningTokens: 0,\n raw: null,\n });\n }\n\n // Accumulate token counts\n // Note: Usage is frozen by createUsage, so we need to create a new one\n this._usage = createUsage({\n inputTokens: this._usage.inputTokens + chunk.inputTokens,\n outputTokens: this._usage.outputTokens + chunk.outputTokens,\n cacheReadTokens: this._usage.cacheReadTokens + chunk.cacheReadTokens,\n cacheWriteTokens: this._usage.cacheWriteTokens + chunk.cacheWriteTokens,\n reasoningTokens: this._usage.reasoningTokens + chunk.reasoningTokens,\n raw: this._usage.raw,\n });\n }\n}\n","/**\n * ContextStreamResponse class for context-based streaming LLM calls.\n *\n * Extends BaseStreamResponse with context-aware functionality including:\n * - executeTools(): Execute tool calls with context dependency injection\n * - resume(): Continue the conversation with additional user content\n */\n\nimport type { ToolOutput } from \"@/llm/content/tool-output\";\nimport type { Context } from \"@/llm/context\";\nimport type { UserContent } from \"@/llm/messages\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport {\n BaseStreamResponse,\n type BaseStreamResponseInit,\n} from \"@/llm/responses/base-stream-response\";\nimport { ContextToolkit, type ContextTools } from \"@/llm/tools\";\n\n/**\n * Arguments for constructing a ContextStreamResponse.\n *\n * Accepts `tools` as either a ContextToolkit or a list of tools, which gets\n * converted to a ContextToolkit before passing to BaseStreamResponse.\n *\n * Supports both regular tools (BaseTool) and context tools (BaseContextTool),\n * matching Python's `ContextTools[DepsT]` pattern.\n *\n * @template DepsT - The type of dependencies in the context.\n */\nexport interface ContextStreamResponseInit<DepsT = unknown> extends Omit<\n BaseStreamResponseInit,\n \"toolkit\"\n> {\n /**\n * The tools available for this response.\n * Can be a ContextToolkit instance or an array of tools.\n * Accepts both regular tools and context tools.\n */\n tools?: ContextTools<DepsT> | ContextToolkit<DepsT>;\n}\n\n/**\n * A streaming response from a context-based LLM call.\n *\n * This class provides context-aware functionality on top of the standard streaming response:\n * - `executeTools()`: Execute all tool calls with context dependency injection\n * - `resume()`: Continue the conversation with additional user content\n *\n * @template DepsT - The type of dependencies in the context.\n * @template F - The type of the formatted output when using structured outputs.\n *\n * @example\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await myPrompt.stream(model, ctx);\n *\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n *\n * // Continue the conversation\n * const followUp = await response.resume(ctx, 'Tell me more');\n * ```\n */\nexport class ContextStreamResponse<\n DepsT = unknown,\n F = unknown,\n> extends BaseStreamResponse<F> {\n /**\n * The context toolkit containing tools that can receive context.\n */\n readonly contextToolkit: ContextToolkit<DepsT>;\n\n constructor(args: ContextStreamResponseInit<DepsT>) {\n // Convert tools to context toolkit (matching Python's pattern)\n const contextToolkit =\n args.tools instanceof ContextToolkit\n ? args.tools\n : new ContextToolkit(args.tools ?? []);\n\n super({ ...args, toolkit: contextToolkit });\n\n this.contextToolkit = contextToolkit;\n }\n\n // ===== Tool Execution =====\n\n /**\n * Execute all tool calls in this response using the registered context tools.\n *\n * Note: The stream must be consumed before calling executeTools() to ensure\n * all tool calls have been received.\n *\n * @param ctx - The context containing dependencies to pass to tools.\n * @returns An array of ToolOutput objects, one for each tool call.\n *\n * @example\n * ```typescript\n * const response = await myPrompt.stream(model, ctx, [searchTool]);\n *\n * // Consume the stream first\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n *\n * // Then execute tools\n * if (response.toolCalls.length > 0) {\n * const outputs = await response.executeTools(ctx);\n * const followUp = await response.resume(ctx, outputs);\n * }\n * ```\n */\n async executeTools(ctx: Context<DepsT>): Promise<ToolOutput<Jsonable>[]> {\n return this.contextToolkit.executeAll(ctx, this.toolCalls);\n }\n\n // ===== Resume Methods =====\n\n /**\n * Generate a new ContextStreamResponse using this response's messages with additional user content.\n *\n * Uses this response's tools and format type. Also uses this response's provider,\n * model, and params.\n *\n * Note: The stream must be consumed before calling resume() to ensure\n * the assistant message is complete.\n *\n * @param ctx - A Context with the required deps type.\n * @param content - The new user message content to append to the message history.\n * @returns A new ContextStreamResponse instance generated from the extended message history.\n *\n * @example\n * ```typescript\n * const response = await myPrompt.stream(model, ctx);\n *\n * // Consume the stream first\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n *\n * // Then resume with streaming\n * const followUp = await response.resume(ctx, 'Tell me more about that');\n * for await (const text of followUp.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n async resume(\n ctx: Context<DepsT>,\n content: UserContent,\n ): Promise<ContextStreamResponse<DepsT, F>> {\n const model = await this.model;\n return model.contextResumeStream(ctx, this, content) as Promise<\n ContextStreamResponse<DepsT, F>\n >;\n }\n}\n","/**\n * StreamResponse class for handling streaming LLM responses.\n *\n * Extends BaseStreamResponse with resume methods for continuing conversations.\n */\n\nimport type { ToolOutput } from \"@/llm/content/tool-output\";\nimport type { UserContent } from \"@/llm/messages\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport {\n BaseStreamResponse,\n type BaseStreamResponseInit,\n} from \"@/llm/responses/base-stream-response\";\nimport { Toolkit, type Tools } from \"@/llm/tools\";\n\n/**\n * Arguments for constructing a StreamResponse.\n *\n * Accepts `tools` as either a Toolkit or a list of tools, which gets\n * converted to a Toolkit before passing to BaseStreamResponse.\n */\nexport interface StreamResponseInit extends Omit<\n BaseStreamResponseInit,\n \"toolkit\"\n> {\n /**\n * The tools available for this response.\n * Can be a Toolkit instance or an array of tools.\n */\n tools?: Tools | Toolkit;\n}\n\n/**\n * Streaming response that consumes chunks from an async iterator.\n *\n * Extends BaseStreamResponse to provide the standard streaming interface,\n * adding resume methods for continuing conversations.\n *\n * @template F - The type of the formatted output when using structured outputs.\n *\n * @example\n * ```typescript\n * const response = await model.stream('Hello!');\n *\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n *\n * // Continue the conversation\n * const followUp = await response.resume('Tell me more');\n * ```\n *\n * @example With structured output\n * ```typescript\n * interface Book { title: string; author: string; }\n * const response = await model.stream<Book>('Recommend a book', { format: BookSchema });\n * for await (const partial of response.structuredStream()) {\n * console.log(partial.title); // Typed as DeepPartial<Book>\n * }\n * ```\n */\nexport class StreamResponse<F = unknown> extends BaseStreamResponse<F> {\n /**\n * Override base toolkit with correct type for execute() support.\n */\n declare readonly toolkit: Toolkit;\n\n constructor(args: StreamResponseInit) {\n // Convert tools to toolkit (matching Python's pattern)\n const toolkit =\n args.tools instanceof Toolkit\n ? args.tools\n : new Toolkit(args.tools ?? []);\n\n super({ ...args, toolkit });\n }\n\n // ===== Tool Execution =====\n\n /**\n * Execute all tool calls in this response using the registered tools.\n *\n * Note: The stream must be consumed before calling executeTools() to ensure\n * all tool calls have been received.\n *\n * @returns An array of ToolOutput objects, one for each tool call.\n *\n * @example\n * ```typescript\n * const response = await model.stream('What is the weather?', [weatherTool]);\n *\n * // Consume the stream first\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n *\n * // Then execute tools\n * if (response.toolCalls.length > 0) {\n * const outputs = await response.executeTools();\n * const followUp = await response.resume(outputs);\n * }\n * ```\n */\n async executeTools(): Promise<ToolOutput<Jsonable>[]> {\n return Promise.all(\n this.toolCalls.map((call) => this.toolkit.execute(call)),\n );\n }\n\n // ===== Resume Methods =====\n\n /**\n * Generate a new StreamResponse using this response's messages with additional user content.\n *\n * Uses this response's tools and format type. Also uses this response's provider,\n * model, and params.\n *\n * Note: The stream must be consumed before calling resume() to ensure\n * the assistant message is complete.\n *\n * @param content - The new user message content to append to the message history.\n * @returns A new StreamResponse instance generated from the extended message history.\n *\n * @example\n * ```typescript\n * const response = await model.stream('Hello!');\n *\n * // Consume the stream first\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n *\n * // Then resume with streaming\n * const followUp = await response.resume('Tell me more about that');\n * for await (const text of followUp.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n async resume(content: UserContent): Promise<StreamResponse<F>> {\n const model = await this.model;\n return model.resumeStream(this, content) as Promise<StreamResponse<F>>;\n }\n}\n","/**\n * Google provider implementation.\n */\n\nimport { GoogleGenAI, ApiError } from \"@google/genai\";\n\nimport type { Context } from \"@/llm/context\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { GoogleModelId } from \"@/llm/providers/google/model-id\";\nimport type { Tools, ContextTools } from \"@/llm/tools\";\n\nimport { getIncludeThoughts } from \"@/llm/providers/_utils\";\nimport { BaseProvider } from \"@/llm/providers/base\";\nimport {\n GOOGLE_ERROR_MAP,\n buildRequestParams,\n decodeResponse,\n mapGoogleErrorByStatus,\n} from \"@/llm/providers/google/_utils\";\nimport { decodeStream } from \"@/llm/providers/google/decode-stream\";\nimport { modelName } from \"@/llm/providers/google/model-id\";\nimport { Response } from \"@/llm/responses\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport { StreamResponse } from \"@/llm/responses/stream-response\";\n\n/**\n * Provider for the Google Gemini API.\n *\n * @example\n * ```typescript\n * const provider = new GoogleProvider();\n * const response = await provider.call({\n * modelId: 'gemini-2.0-flash',\n * messages: [user('Hello!')],\n * });\n * console.log(response.text());\n * ```\n */\nexport class GoogleProvider extends BaseProvider {\n readonly id = \"google\" as const;\n protected readonly errorMap = GOOGLE_ERROR_MAP;\n\n private readonly client: GoogleGenAI;\n\n /**\n * Create a new Google provider instance.\n *\n * @param init - Configuration options\n * @param init.apiKey - Google API key (defaults to GOOGLE_API_KEY env var)\n * @param init.baseURL - Optional custom base URL for the API\n */\n constructor(init: { apiKey?: string; baseURL?: string } = {}) {\n super();\n this.client = new GoogleGenAI({\n apiKey: init.apiKey,\n httpOptions: init.baseURL\n ? {\n baseUrl: init.baseURL,\n headers: { Authorization: `Bearer ${init.apiKey}` },\n }\n : undefined,\n });\n }\n\n /**\n * Execute a call to the Google Gemini API.\n *\n * @param args - Call arguments\n * @param args.modelId - The Google model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns Response object containing the API response\n */\n protected async _call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<Response> {\n const modelId = args.modelId as GoogleModelId;\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.params,\n );\n\n const googleResponse =\n await this.client.models.generateContent(requestParams);\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const { assistantMessage, finishReason, usage } = decodeResponse(\n googleResponse,\n modelId,\n includeThoughts,\n );\n\n return new Response({\n raw: googleResponse,\n providerId: \"google\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a streaming call to the Google Gemini API.\n *\n * @param args - Call arguments\n * @param args.modelId - The Google model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns StreamResponse object for streaming consumption\n */\n protected async _stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<StreamResponse> {\n const modelId = args.modelId as GoogleModelId;\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.params,\n );\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const stream =\n await this.client.models.generateContentStream(requestParams);\n\n const chunkIterator = decodeStream(stream, includeThoughts);\n\n return new StreamResponse({\n providerId: \"google\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n chunkIterator,\n });\n }\n\n /**\n * Execute a context-aware call to the Google Gemini API.\n *\n * NOTE: This implementation intentionally duplicates _call() rather than delegating.\n * When context-aware tools are implemented, this method will diverge to handle\n * passing context to tools during execution. We keep them separate now to make\n * that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The Google model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns ContextResponse object containing the API response\n */\n protected async _contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n const modelId = args.modelId as GoogleModelId;\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.params,\n );\n\n const googleResponse =\n await this.client.models.generateContent(requestParams);\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const { assistantMessage, finishReason, usage } = decodeResponse(\n googleResponse,\n modelId,\n includeThoughts,\n );\n\n return new ContextResponse({\n raw: googleResponse,\n providerId: \"google\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a context-aware streaming call to the Google Gemini API.\n *\n * NOTE: This implementation intentionally duplicates _stream() rather than delegating.\n * When context-aware tools are implemented, this method will diverge to handle\n * passing context to tools during execution. We keep them separate now to make\n * that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The Google model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns ContextStreamResponse object for streaming consumption\n */\n protected async _contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n const modelId = args.modelId as GoogleModelId;\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.params,\n );\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const stream =\n await this.client.models.generateContentStream(requestParams);\n\n const chunkIterator = decodeStream(stream, includeThoughts);\n\n return new ContextStreamResponse({\n providerId: \"google\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n chunkIterator,\n });\n }\n\n /**\n * Extract the HTTP status code from a Google API error.\n *\n * @param e - The error to extract the status from\n * @returns The HTTP status code or undefined if not available\n */\n /* v8 ignore next 4 - only used by base class wrapError which we override */\n protected getErrorStatus(e: Error): number | undefined {\n // Google SDK uses 'status' property\n return (e as InstanceType<typeof ApiError>).status;\n }\n\n /**\n * Wrap an error with provider-specific error handling.\n *\n * Maps Google ApiError instances to specific Mirascope error types\n * based on the HTTP status code.\n *\n * @param e - The error to wrap\n * @returns A Mirascope error instance\n */\n protected override wrapError(e: unknown): Error {\n if (e instanceof ApiError) {\n const ErrorClass = mapGoogleErrorByStatus(e.status);\n return new ErrorClass(e.message, {\n provider: this.id,\n statusCode: e.status,\n originalException: e,\n });\n }\n return super.wrapError(e);\n }\n}\n","/**\n * Google provider implementation.\n */\n\nexport type { GoogleModelId } from \"@/llm/providers/google/model-id\";\nexport { modelName } from \"@/llm/providers/google/model-id\";\nexport type { GoogleKnownModels } from \"@/llm/providers/google/model-info\";\nexport {\n GOOGLE_KNOWN_MODELS,\n MODELS_WITHOUT_STRUCTURED_OUTPUT_AND_TOOLS_SUPPORT,\n} from \"@/llm/providers/google/model-info\";\nexport { GoogleProvider } from \"@/llm/providers/google/provider\";\n","import type { BaseProvider } from \"@/llm/providers/base\";\nimport type { ProviderId } from \"@/llm/providers/provider-id\";\n\nimport { getProviderSingleton } from \"@/llm/providers/registry\";\n\nconst DEFAULT_ROUTER_BASE_URL = \"https://mirascope.com/router/v2\";\n\nexport function getDefaultRouterBaseUrl(): string {\n return process.env.MIRASCOPE_ROUTER_BASE_URL ?? DEFAULT_ROUTER_BASE_URL;\n}\n\nexport function extractModelScope(modelId: string): string | null {\n if (!modelId.includes(\"/\")) {\n return null;\n }\n return modelId.split(\"/\")[0]!;\n}\n\nconst SUPPORTED_PROVIDERS: ProviderId[] = [\"anthropic\", \"google\", \"openai\"];\n\nexport function createUnderlyingProvider(\n modelScope: string,\n apiKey: string,\n routerBaseUrl: string,\n): BaseProvider {\n if (!SUPPORTED_PROVIDERS.includes(modelScope as ProviderId)) {\n throw new Error(\n `Unsupported provider: ${modelScope}. ` +\n `Mirascope Router currently supports: ${SUPPORTED_PROVIDERS.join(\", \")}`,\n );\n }\n\n let baseURL = `${routerBaseUrl}/${modelScope}`;\n if (modelScope === \"openai\") {\n baseURL = `${baseURL}/v1`;\n }\n\n // Use the shared provider singleton cache from registry\n // This ensures proper cleanup via resetProviderRegistry()\n return getProviderSingleton(modelScope as ProviderId, { apiKey, baseURL });\n}\n","import type { Context } from \"@/llm/context\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { ProviderId } from \"@/llm/providers/provider-id\";\nimport type { Tools, ContextTools } from \"@/llm/tools\";\n\nimport { BaseProvider, type ProviderErrorMap } from \"@/llm/providers/base\";\nimport {\n extractModelScope,\n getDefaultRouterBaseUrl,\n createUnderlyingProvider,\n} from \"@/llm/providers/mirascope/_utils\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport { Response } from \"@/llm/responses/response\";\nimport { StreamResponse } from \"@/llm/responses/stream-response\";\n\nexport interface MirascopeProviderInit {\n apiKey?: string;\n baseURL?: string;\n}\n\nexport class MirascopeProvider extends BaseProvider {\n readonly id: ProviderId = \"mirascope\";\n protected readonly errorMap: ProviderErrorMap = [];\n\n private readonly apiKey: string;\n private readonly routerBaseUrl: string;\n\n constructor(init?: MirascopeProviderInit) {\n super();\n const apiKey = init?.apiKey ?? process.env.MIRASCOPE_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"Mirascope API key not found. \" +\n \"Set MIRASCOPE_API_KEY environment variable or pass apiKey parameter.\",\n );\n }\n this.apiKey = apiKey;\n this.routerBaseUrl = init?.baseURL ?? getDefaultRouterBaseUrl();\n }\n\n private getUnderlyingProvider(modelId: string): BaseProvider {\n const modelScope = extractModelScope(modelId);\n if (!modelScope) {\n throw new Error(\n `Invalid model ID format: ${modelId}. ` +\n `Expected format 'scope/model-name' (e.g., 'openai/gpt-4')`,\n );\n }\n return createUnderlyingProvider(\n modelScope,\n this.apiKey,\n this.routerBaseUrl,\n );\n }\n\n protected async _call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<Response> {\n const provider = this.getUnderlyingProvider(args.modelId);\n return provider.call(args);\n }\n\n protected async _stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<StreamResponse> {\n const provider = this.getUnderlyingProvider(args.modelId);\n return provider.stream(args);\n }\n\n protected async _contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n const provider = this.getUnderlyingProvider(args.modelId);\n return provider.contextCall(args);\n }\n\n protected async _contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n const provider = this.getUnderlyingProvider(args.modelId);\n return provider.contextStream(args);\n }\n\n /* v8 ignore next 3 - unreachable: errors handled by underlying providers */\n protected getErrorStatus(_e: Error): number | undefined {\n return undefined;\n }\n}\n","export {\n MirascopeProvider,\n type MirascopeProviderInit,\n} from \"@/llm/providers/mirascope/provider\";\n","/**\n * OpenAI error mapping from SDK exceptions to Mirascope error types.\n */\n\nimport OpenAI from \"openai\";\n\nimport type { ProviderErrorMap } from \"@/llm/providers/base\";\n\nimport {\n APIError,\n AuthenticationError,\n BadRequestError,\n ConnectionError,\n NotFoundError,\n PermissionError,\n RateLimitError,\n ServerError,\n TimeoutError,\n} from \"@/llm/exceptions\";\n\n/**\n * Error mapping from OpenAI SDK exceptions to Mirascope error types.\n * Note: More specific error classes must come before their parent classes\n * since the error map is checked with instanceof in order.\n */\nexport const OPENAI_ERROR_MAP: ProviderErrorMap = [\n [OpenAI.AuthenticationError, AuthenticationError],\n [OpenAI.PermissionDeniedError, PermissionError],\n [OpenAI.NotFoundError, NotFoundError],\n [OpenAI.BadRequestError, BadRequestError],\n [OpenAI.UnprocessableEntityError, BadRequestError],\n [OpenAI.ConflictError, BadRequestError],\n [OpenAI.RateLimitError, RateLimitError],\n [OpenAI.InternalServerError, ServerError],\n [OpenAI.APIConnectionTimeoutError, TimeoutError],\n [OpenAI.APIConnectionError, ConnectionError],\n [OpenAI.APIError, APIError],\n];\n","/**\n * OpenAI model IDs and related utilities.\n */\n\nimport type { OpenAIKnownModels } from \"@/llm/providers/openai/model-info\";\n\n/**\n * The OpenAI model IDs registered with Mirascope.\n */\nexport type OpenAIModelId = OpenAIKnownModels | (string & {});\n\n/**\n * API mode for OpenAI requests.\n */\nexport type ApiMode = \"responses\" | \"completions\";\n\n/**\n * Extract the OpenAI model name from the ModelId.\n *\n * @param modelId - Full model ID (e.g. \"openai/gpt-4o\" or \"openai/gpt-4o:responses\")\n * @param apiMode - API mode to append as suffix (\"responses\" or \"completions\").\n * If null, no suffix will be added (just the base model name).\n * @returns Provider-specific model ID with API suffix (e.g. \"gpt-4o:responses\")\n */\nexport function modelName(\n modelId: OpenAIModelId,\n apiMode: ApiMode | null,\n): string {\n const modelPart = modelId.replace(/^openai\\//, \"\");\n const baseName = modelPart\n .replace(/:responses$/, \"\")\n .replace(/:completions$/, \"\");\n\n if (apiMode === null) {\n return baseName;\n }\n return `${baseName}:${apiMode}`;\n}\n","/**\n * OpenAI model information.\n *\n * This file is auto-generated by typescript/scripts/codegen/openai.ts\n * Do not edit manually - run `bun run codegen` to update.\n */\n\n/**\n * Array of all known OpenAI model IDs.\n * This is the source of truth - the type and Set are derived from it.\n */\nconst OPENAI_KNOWN_MODELS_ARRAY = [\n \"openai/chatgpt-4o-latest\",\n \"openai/chatgpt-4o-latest:completions\",\n \"openai/chatgpt-4o-latest:responses\",\n \"openai/codex-mini-latest\",\n \"openai/codex-mini-latest:responses\",\n \"openai/gpt-3.5-turbo\",\n \"openai/gpt-3.5-turbo:completions\",\n \"openai/gpt-3.5-turbo:responses\",\n \"openai/gpt-3.5-turbo-0125\",\n \"openai/gpt-3.5-turbo-0125:completions\",\n \"openai/gpt-3.5-turbo-0125:responses\",\n \"openai/gpt-3.5-turbo-1106\",\n \"openai/gpt-3.5-turbo-1106:completions\",\n \"openai/gpt-3.5-turbo-1106:responses\",\n \"openai/gpt-3.5-turbo-16k\",\n \"openai/gpt-3.5-turbo-16k:completions\",\n \"openai/gpt-4\",\n \"openai/gpt-4:completions\",\n \"openai/gpt-4:responses\",\n \"openai/gpt-4-0125-preview\",\n \"openai/gpt-4-0125-preview:completions\",\n \"openai/gpt-4-0125-preview:responses\",\n \"openai/gpt-4-0613\",\n \"openai/gpt-4-0613:completions\",\n \"openai/gpt-4-0613:responses\",\n \"openai/gpt-4-1106-preview\",\n \"openai/gpt-4-1106-preview:completions\",\n \"openai/gpt-4-1106-preview:responses\",\n \"openai/gpt-4-turbo\",\n \"openai/gpt-4-turbo:completions\",\n \"openai/gpt-4-turbo:responses\",\n \"openai/gpt-4-turbo-2024-04-09\",\n \"openai/gpt-4-turbo-2024-04-09:completions\",\n \"openai/gpt-4-turbo-2024-04-09:responses\",\n \"openai/gpt-4-turbo-preview\",\n \"openai/gpt-4-turbo-preview:completions\",\n \"openai/gpt-4-turbo-preview:responses\",\n \"openai/gpt-4.1\",\n \"openai/gpt-4.1:completions\",\n \"openai/gpt-4.1:responses\",\n \"openai/gpt-4.1-2025-04-14\",\n \"openai/gpt-4.1-2025-04-14:completions\",\n \"openai/gpt-4.1-2025-04-14:responses\",\n \"openai/gpt-4.1-mini\",\n \"openai/gpt-4.1-mini:completions\",\n \"openai/gpt-4.1-mini:responses\",\n \"openai/gpt-4.1-mini-2025-04-14\",\n \"openai/gpt-4.1-mini-2025-04-14:completions\",\n \"openai/gpt-4.1-mini-2025-04-14:responses\",\n \"openai/gpt-4.1-nano\",\n \"openai/gpt-4.1-nano:completions\",\n \"openai/gpt-4.1-nano:responses\",\n \"openai/gpt-4.1-nano-2025-04-14\",\n \"openai/gpt-4.1-nano-2025-04-14:completions\",\n \"openai/gpt-4.1-nano-2025-04-14:responses\",\n \"openai/gpt-4o\",\n \"openai/gpt-4o:completions\",\n \"openai/gpt-4o:responses\",\n \"openai/gpt-4o-2024-05-13\",\n \"openai/gpt-4o-2024-05-13:completions\",\n \"openai/gpt-4o-2024-05-13:responses\",\n \"openai/gpt-4o-2024-08-06\",\n \"openai/gpt-4o-2024-08-06:completions\",\n \"openai/gpt-4o-2024-08-06:responses\",\n \"openai/gpt-4o-2024-11-20\",\n \"openai/gpt-4o-2024-11-20:completions\",\n \"openai/gpt-4o-2024-11-20:responses\",\n \"openai/gpt-4o-mini\",\n \"openai/gpt-4o-mini:completions\",\n \"openai/gpt-4o-mini:responses\",\n \"openai/gpt-4o-mini-2024-07-18\",\n \"openai/gpt-4o-mini-2024-07-18:completions\",\n \"openai/gpt-4o-mini-2024-07-18:responses\",\n \"openai/gpt-4o-mini-search-preview\",\n \"openai/gpt-4o-mini-search-preview:completions\",\n \"openai/gpt-4o-mini-search-preview-2025-03-11\",\n \"openai/gpt-4o-mini-search-preview-2025-03-11:completions\",\n \"openai/gpt-4o-search-preview\",\n \"openai/gpt-4o-search-preview:completions\",\n \"openai/gpt-4o-search-preview-2025-03-11\",\n \"openai/gpt-4o-search-preview-2025-03-11:completions\",\n \"openai/gpt-5\",\n \"openai/gpt-5:completions\",\n \"openai/gpt-5:responses\",\n \"openai/gpt-5-2025-08-07\",\n \"openai/gpt-5-2025-08-07:completions\",\n \"openai/gpt-5-2025-08-07:responses\",\n \"openai/gpt-5-chat-latest\",\n \"openai/gpt-5-chat-latest:completions\",\n \"openai/gpt-5-chat-latest:responses\",\n \"openai/gpt-5-codex\",\n \"openai/gpt-5-codex:responses\",\n \"openai/gpt-5-mini\",\n \"openai/gpt-5-mini:completions\",\n \"openai/gpt-5-mini:responses\",\n \"openai/gpt-5-mini-2025-08-07\",\n \"openai/gpt-5-mini-2025-08-07:completions\",\n \"openai/gpt-5-mini-2025-08-07:responses\",\n \"openai/gpt-5-nano\",\n \"openai/gpt-5-nano:completions\",\n \"openai/gpt-5-nano:responses\",\n \"openai/gpt-5-nano-2025-08-07\",\n \"openai/gpt-5-nano-2025-08-07:completions\",\n \"openai/gpt-5-nano-2025-08-07:responses\",\n \"openai/gpt-5-pro\",\n \"openai/gpt-5-pro:responses\",\n \"openai/gpt-5-pro-2025-10-06\",\n \"openai/gpt-5-pro-2025-10-06:responses\",\n \"openai/gpt-5-search-api\",\n \"openai/gpt-5-search-api:completions\",\n \"openai/gpt-5-search-api-2025-10-14\",\n \"openai/gpt-5-search-api-2025-10-14:completions\",\n \"openai/gpt-5.1\",\n \"openai/gpt-5.1:responses\",\n \"openai/gpt-5.1-2025-11-13\",\n \"openai/gpt-5.1-2025-11-13:responses\",\n \"openai/gpt-5.1-chat-latest\",\n \"openai/gpt-5.1-chat-latest:completions\",\n \"openai/gpt-5.1-chat-latest:responses\",\n \"openai/gpt-5.1-codex\",\n \"openai/gpt-5.1-codex:responses\",\n \"openai/gpt-5.1-codex-max\",\n \"openai/gpt-5.1-codex-max:responses\",\n \"openai/gpt-5.1-codex-mini\",\n \"openai/gpt-5.1-codex-mini:responses\",\n \"openai/gpt-5.2\",\n \"openai/gpt-5.2:completions\",\n \"openai/gpt-5.2:responses\",\n \"openai/gpt-5.2-2025-12-11\",\n \"openai/gpt-5.2-2025-12-11:completions\",\n \"openai/gpt-5.2-2025-12-11:responses\",\n \"openai/gpt-5.2-chat-latest\",\n \"openai/gpt-5.2-chat-latest:completions\",\n \"openai/gpt-5.2-chat-latest:responses\",\n \"openai/gpt-5.2-pro\",\n \"openai/gpt-5.2-pro:responses\",\n \"openai/gpt-5.2-pro-2025-12-11\",\n \"openai/gpt-5.2-pro-2025-12-11:responses\",\n \"openai/o1\",\n \"openai/o1:completions\",\n \"openai/o1:responses\",\n \"openai/o1-2024-12-17\",\n \"openai/o1-2024-12-17:completions\",\n \"openai/o1-2024-12-17:responses\",\n \"openai/o1-pro\",\n \"openai/o1-pro:responses\",\n \"openai/o1-pro-2025-03-19\",\n \"openai/o1-pro-2025-03-19:responses\",\n \"openai/o3\",\n \"openai/o3:completions\",\n \"openai/o3:responses\",\n \"openai/o3-2025-04-16\",\n \"openai/o3-2025-04-16:completions\",\n \"openai/o3-2025-04-16:responses\",\n \"openai/o3-mini\",\n \"openai/o3-mini:completions\",\n \"openai/o3-mini:responses\",\n \"openai/o3-mini-2025-01-31\",\n \"openai/o3-mini-2025-01-31:completions\",\n \"openai/o3-mini-2025-01-31:responses\",\n \"openai/o3-pro\",\n \"openai/o3-pro:responses\",\n \"openai/o3-pro-2025-06-10\",\n \"openai/o3-pro-2025-06-10:responses\",\n \"openai/o4-mini\",\n \"openai/o4-mini:completions\",\n \"openai/o4-mini:responses\",\n \"openai/o4-mini-2025-04-16\",\n \"openai/o4-mini-2025-04-16:completions\",\n \"openai/o4-mini-2025-04-16:responses\",\n] as const;\n\n/**\n * Valid OpenAI model IDs including API-specific variants.\n */\nexport type OpenAIKnownModels = (typeof OPENAI_KNOWN_MODELS_ARRAY)[number];\n\n/**\n * Set of all known OpenAI model IDs.\n */\nexport const OPENAI_KNOWN_MODELS: ReadonlySet<string> = new Set(\n OPENAI_KNOWN_MODELS_ARRAY,\n);\n\n/**\n * Models that do not support audio inputs.\n *\n * Models not in this set are assumed to support audio (optimistic default).\n */\nexport const MODELS_WITHOUT_AUDIO_SUPPORT: ReadonlySet<string> = new Set([\n \"chatgpt-4o-latest\",\n \"gpt-3.5-turbo\",\n \"gpt-3.5-turbo-0125\",\n \"gpt-3.5-turbo-1106\",\n \"gpt-3.5-turbo-16k\",\n \"gpt-4\",\n \"gpt-4-0125-preview\",\n \"gpt-4-0613\",\n \"gpt-4-1106-preview\",\n \"gpt-4-turbo\",\n \"gpt-4-turbo-2024-04-09\",\n \"gpt-4-turbo-preview\",\n \"gpt-4.1\",\n \"gpt-4.1-2025-04-14\",\n \"gpt-4.1-mini\",\n \"gpt-4.1-mini-2025-04-14\",\n \"gpt-4.1-nano\",\n \"gpt-4.1-nano-2025-04-14\",\n \"gpt-4o\",\n \"gpt-4o-2024-05-13\",\n \"gpt-4o-2024-08-06\",\n \"gpt-4o-2024-11-20\",\n \"gpt-4o-mini\",\n \"gpt-4o-mini-2024-07-18\",\n \"gpt-4o-mini-search-preview\",\n \"gpt-4o-mini-search-preview-2025-03-11\",\n \"gpt-4o-search-preview\",\n \"gpt-4o-search-preview-2025-03-11\",\n \"gpt-5\",\n \"gpt-5-2025-08-07\",\n \"gpt-5-chat-latest\",\n \"gpt-5-mini\",\n \"gpt-5-mini-2025-08-07\",\n \"gpt-5-nano\",\n \"gpt-5-nano-2025-08-07\",\n \"gpt-5-search-api\",\n \"gpt-5-search-api-2025-10-14\",\n \"gpt-5.1-chat-latest\",\n \"gpt-5.2\",\n \"gpt-5.2-2025-12-11\",\n \"gpt-5.2-chat-latest\",\n \"o1\",\n \"o1-2024-12-17\",\n \"o3\",\n \"o3-2025-04-16\",\n \"o3-mini\",\n \"o3-mini-2025-01-31\",\n \"o4-mini\",\n \"o4-mini-2025-04-16\",\n]);\n\n/**\n * Models that do not support the reasoning parameter.\n *\n * Models not in this set are assumed to support reasoning (optimistic default).\n */\nexport const NON_REASONING_MODELS: ReadonlySet<string> = new Set([\n \"chatgpt-4o-latest\",\n \"gpt-3.5-turbo\",\n \"gpt-3.5-turbo-0125\",\n \"gpt-3.5-turbo-1106\",\n \"gpt-4\",\n \"gpt-4-0125-preview\",\n \"gpt-4-0613\",\n \"gpt-4-1106-preview\",\n \"gpt-4-turbo\",\n \"gpt-4-turbo-2024-04-09\",\n \"gpt-4-turbo-preview\",\n \"gpt-4.1\",\n \"gpt-4.1-2025-04-14\",\n \"gpt-4.1-mini\",\n \"gpt-4.1-mini-2025-04-14\",\n \"gpt-4.1-nano\",\n \"gpt-4.1-nano-2025-04-14\",\n \"gpt-4o\",\n \"gpt-4o-2024-05-13\",\n \"gpt-4o-2024-08-06\",\n \"gpt-4o-2024-11-20\",\n \"gpt-4o-mini\",\n \"gpt-4o-mini-2024-07-18\",\n \"gpt-5-chat-latest\",\n]);\n\n/**\n * Models that do not support JSON schema (structured outputs).\n *\n * Models not in this set are assumed to support JSON schema (optimistic default).\n */\nexport const MODELS_WITHOUT_JSON_SCHEMA_SUPPORT: ReadonlySet<string> = new Set([\n \"chatgpt-4o-latest\",\n \"gpt-3.5-turbo\",\n \"gpt-3.5-turbo-0125\",\n \"gpt-3.5-turbo-1106\",\n \"gpt-3.5-turbo-16k\",\n \"gpt-4\",\n \"gpt-4-0125-preview\",\n \"gpt-4-0613\",\n \"gpt-4-1106-preview\",\n \"gpt-4-turbo\",\n \"gpt-4-turbo-2024-04-09\",\n \"gpt-4-turbo-preview\",\n \"gpt-4o-2024-05-13\",\n]);\n\n/**\n * Models that do not support JSON object mode.\n *\n * Models not in this set are assumed to support JSON object mode (optimistic default).\n */\nexport const MODELS_WITHOUT_JSON_OBJECT_SUPPORT: ReadonlySet<string> = new Set([\n \"gpt-4\",\n \"gpt-4-0613\",\n \"gpt-4o-mini-search-preview\",\n \"gpt-4o-mini-search-preview-2025-03-11\",\n \"gpt-4o-search-preview\",\n \"gpt-4o-search-preview-2025-03-11\",\n \"gpt-5-search-api\",\n \"gpt-5-search-api-2025-10-14\",\n]);\n","/**\n * OpenAI Completions API utilities for encoding requests and decoding responses.\n */\n\nimport type {\n ChatCompletion,\n ChatCompletionAssistantMessageParam,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPartText,\n ChatCompletionCreateParamsNonStreaming,\n ChatCompletionMessageParam,\n ChatCompletionToolMessageParam,\n} from \"openai/resources/chat/completions\";\n\nimport type {\n AssistantContentPart,\n Audio,\n AudioMimeType,\n Image,\n Text,\n ToolCall,\n} from \"@/llm/content\";\nimport type { AssistantMessage, Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { OpenAIModelId } from \"@/llm/providers/openai/model-id\";\nimport type { Usage } from \"@/llm/responses/usage\";\nimport type { ToolSchema, Tools } from \"@/llm/tools\";\n\nimport { FeatureNotSupportedError } from \"@/llm/exceptions\";\nimport { ParamHandler } from \"@/llm/providers/base\";\nimport { modelName } from \"@/llm/providers/openai/model-id\";\nimport { MODELS_WITHOUT_AUDIO_SUPPORT } from \"@/llm/providers/openai/model-info\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\nimport { createUsage } from \"@/llm/responses/usage\";\nimport { isProviderTool } from \"@/llm/tools\";\n\n// ============================================================================\n// Content Part Encoding\n// ============================================================================\n\n/**\n * Content part types for user messages.\n */\ntype UserContentPartOpenAI =\n | ChatCompletionContentPartText\n | ChatCompletionContentPartImage\n | ChatCompletionContentPartInputAudio;\n\n/**\n * Encode an Image content part to OpenAI's format.\n * OpenAI accepts either a URL or a base64 data URI.\n */\nfunction encodeImage(image: Image): ChatCompletionContentPartImage {\n let url: string;\n if (image.source.type === \"url_image_source\") {\n url = image.source.url;\n } else {\n url = `data:${image.source.mimeType};base64,${image.source.data}`;\n }\n return {\n type: \"image_url\",\n image_url: { url, detail: \"auto\" },\n };\n}\n\n/**\n * OpenAI-supported audio formats for input.\n */\ntype OpenAIAudioFormat = \"wav\" | \"mp3\";\n\n/**\n * Extract the audio format from a MIME type.\n *\n * @throws FeatureNotSupportedError if the format is not supported by OpenAI\n */\nfunction toOpenAIAudioFormat(mimeType: AudioMimeType): OpenAIAudioFormat {\n const format = mimeType.split(\"/\")[1];\n if (format === \"wav\" || format === \"mp3\") {\n return format;\n }\n throw new FeatureNotSupportedError(\n `audio format: ${mimeType}`,\n \"openai\",\n null,\n `OpenAI only supports 'wav' and 'mp3' audio formats, got '${format}'.`,\n );\n}\n\n/**\n * Encode an Audio content part to OpenAI's format.\n *\n * @throws FeatureNotSupportedError if the model doesn't support audio or format is unsupported\n */\nfunction encodeAudio(\n audio: Audio,\n modelId: OpenAIModelId | undefined,\n): ChatCompletionContentPartInputAudio {\n // Check if model supports audio\n if (modelId) {\n const baseModelName = modelName(modelId, null);\n if (MODELS_WITHOUT_AUDIO_SUPPORT.has(baseModelName)) {\n throw new FeatureNotSupportedError(\n \"audio input\",\n \"openai\",\n modelId,\n `Model '${modelId}' does not support audio inputs.`,\n );\n }\n }\n\n const format = toOpenAIAudioFormat(audio.source.mimeType);\n return {\n type: \"input_audio\",\n input_audio: {\n data: audio.source.data,\n format,\n },\n };\n}\n\n// ============================================================================\n// Tool Encoding\n// ============================================================================\n\n/* v8 ignore start - tool encoding will be tested via e2e */\n/**\n * Convert a ToolSchema to OpenAI's ChatCompletionTool format.\n */\nexport function encodeToolSchema(\n tool: ToolSchema,\n): ChatCompletionCreateParamsNonStreaming[\"tools\"] extends\n | (infer T)[]\n | undefined\n ? T\n : never {\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\",\n properties: tool.parameters.properties,\n required: tool.parameters.required,\n },\n strict: tool.strict,\n },\n };\n}\n\n/**\n * Encode an array of tool schemas to OpenAI's format.\n */\nexport function encodeTools(\n tools: readonly ToolSchema[],\n): NonNullable<ChatCompletionCreateParamsNonStreaming[\"tools\"]> {\n return tools.map(encodeToolSchema);\n}\n/* v8 ignore stop */\n\n// ============================================================================\n// Message Encoding\n// ============================================================================\n\n/**\n * Encode Mirascope messages to OpenAI Chat Completions API format.\n *\n * @param messages - The messages to encode\n * @param encodeThoughtsAsText - Whether to encode thoughts as text in assistant messages\n * @param modelId - The model ID (used for checking audio support and raw message reuse)\n */\nexport function encodeMessages(\n messages: readonly Message[],\n encodeThoughtsAsText: boolean = false,\n modelId?: OpenAIModelId,\n): ChatCompletionMessageParam[] {\n const openaiMessages: ChatCompletionMessageParam[] = [];\n const expectedProviderModelName = modelId\n ? modelName(modelId, \"completions\")\n : null;\n\n for (const message of messages) {\n if (message.role === \"system\") {\n openaiMessages.push({\n role: \"system\",\n content: message.content.text,\n });\n } else if (message.role === \"user\") {\n /* v8 ignore start - tool encoding will be tested via e2e */\n // First add any tool output messages (OpenAI uses separate \"tool\" role)\n const toolMessages = encodeToolOutputs(message);\n openaiMessages.push(...toolMessages);\n /* v8 ignore stop */\n\n // Then add the user message if it has non-tool content\n const userMessage = encodeUserMessage(message, modelId);\n if (userMessage) {\n openaiMessages.push(userMessage);\n }\n } else if (message.role === \"assistant\") {\n // Check if we can reuse the raw message (from same provider/model)\n if (\n message.providerId === \"openai\" &&\n expectedProviderModelName &&\n message.providerModelName === expectedProviderModelName &&\n message.rawMessage &&\n typeof message.rawMessage === \"object\" &&\n \"role\" in message.rawMessage &&\n !encodeThoughtsAsText\n ) {\n // Reuse the serialized message directly\n openaiMessages.push(\n message.rawMessage as unknown as ChatCompletionAssistantMessageParam,\n );\n } else {\n // Otherwise, encode from content parts\n openaiMessages.push(\n encodeAssistantMessage(message, encodeThoughtsAsText),\n );\n }\n }\n }\n\n return openaiMessages;\n}\n\n/**\n * Encode a Mirascope user message to OpenAI format.\n *\n * Iterates over content parts and builds the appropriate content structure.\n * Single text part is simplified to string, multiple parts become an array.\n * Returns null if the message only contains tool outputs (which are handled separately).\n */\nfunction encodeUserMessage(\n message: Extract<Message, { role: \"user\" }>,\n modelId?: OpenAIModelId,\n): ChatCompletionMessageParam | null {\n const contentParts: UserContentPartOpenAI[] = [];\n\n for (const part of message.content) {\n switch (part.type) {\n case \"text\":\n contentParts.push({ type: \"text\", text: part.text });\n break;\n\n case \"image\":\n contentParts.push(encodeImage(part));\n break;\n\n case \"audio\":\n contentParts.push(encodeAudio(part, modelId));\n break;\n\n /* v8 ignore start - content types not yet implemented */\n case \"document\":\n throw new FeatureNotSupportedError(\n \"document content encoding\",\n \"openai\",\n null,\n \"Document content is not yet implemented\",\n );\n /* v8 ignore stop */\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n case \"tool_output\":\n // tool_output is handled separately in encodeMessages\n // by creating tool role messages\n break;\n /* v8 ignore stop */\n }\n }\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n // If no content parts (only tool_outputs), return null\n if (contentParts.length === 0) {\n return null;\n }\n /* v8 ignore stop */\n\n // Simplify to string if only a single text part\n let content: string | UserContentPartOpenAI[] = contentParts;\n if (contentParts.length === 1 && contentParts[0]?.type === \"text\") {\n content = contentParts[0].text;\n }\n\n return {\n role: \"user\",\n content,\n ...(message.name && { name: message.name }),\n };\n}\n\n/* v8 ignore start - tool encoding will be tested via e2e */\n/**\n * Extract tool outputs from a user message and encode as tool role messages.\n */\nfunction encodeToolOutputs(\n message: Extract<Message, { role: \"user\" }>,\n): ChatCompletionToolMessageParam[] {\n const toolMessages: ChatCompletionToolMessageParam[] = [];\n\n for (const part of message.content) {\n if (part.type === \"tool_output\") {\n toolMessages.push({\n role: \"tool\",\n tool_call_id: part.id,\n content:\n typeof part.result === \"string\"\n ? part.result\n : JSON.stringify(part.result),\n });\n }\n }\n\n return toolMessages;\n}\n/* v8 ignore stop */\n\n/**\n * Encode a Mirascope assistant message to OpenAI format.\n *\n * Iterates over content parts and builds text content.\n * Single text part is simplified to string, multiple parts become an array.\n * Tool calls are encoded as a separate array on the message.\n */\nfunction encodeAssistantMessage(\n message: AssistantMessage,\n encodeThoughtsAsText: boolean,\n): ChatCompletionAssistantMessageParam {\n const textParts: ChatCompletionContentPartText[] = [];\n const toolCalls: ChatCompletionAssistantMessageParam[\"tool_calls\"] = [];\n\n for (const part of message.content) {\n switch (part.type) {\n case \"text\":\n textParts.push({ type: \"text\", text: part.text });\n break;\n\n case \"thought\":\n // Encode thoughts as text when requested, otherwise drop\n if (encodeThoughtsAsText) {\n textParts.push({\n type: \"text\",\n text: \"**Thinking:** \" + part.thought,\n });\n }\n break;\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n case \"tool_call\": {\n toolCalls.push({\n id: part.id,\n type: \"function\",\n function: {\n name: part.name,\n arguments: part.args,\n },\n });\n break;\n }\n /* v8 ignore stop */\n }\n }\n\n // Simplify to string if single text part, otherwise keep as list\n // Empty content becomes null\n let content: string | ChatCompletionContentPartText[] | null = null;\n if (textParts.length === 1) {\n content = textParts[0]!.text;\n } else if (textParts.length > 1) {\n content = textParts;\n }\n\n const result: ChatCompletionAssistantMessageParam = {\n role: \"assistant\",\n content,\n ...(message.name && { name: message.name }),\n };\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (toolCalls.length > 0) {\n result.tool_calls = toolCalls;\n }\n /* v8 ignore stop */\n\n return result;\n}\n\n/**\n * Build the request parameters for the OpenAI Chat Completions API.\n *\n * This function performs strict param checking - any unhandled params will\n * cause an error to ensure we don't silently ignore user configuration.\n *\n * @param modelId - The model ID to use\n * @param messages - The messages to send\n * @param tools - Optional tools to make available to the model\n * @param params - Optional parameters (temperature, maxTokens, etc.)\n */\nexport function buildRequestParams(\n modelId: OpenAIModelId,\n messages: readonly Message[],\n tools?: Tools,\n params: Params = {},\n): ChatCompletionCreateParamsNonStreaming {\n return ParamHandler.with(params, \"openai\", modelId, (p) => {\n const thinkingConfig = p.get(\"thinking\");\n const encodeThoughtsAsText = thinkingConfig?.encodeThoughtsAsText ?? false;\n\n const openaiMessages = encodeMessages(\n messages,\n encodeThoughtsAsText,\n modelId,\n );\n\n const requestParams: ChatCompletionCreateParamsNonStreaming = {\n model: modelName(modelId, null),\n messages: openaiMessages,\n };\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (tools !== undefined && tools.length > 0) {\n // Filter out provider tools (not supported by Completions API)\n const regularTools: ToolSchema[] = [];\n for (const tool of tools) {\n if (isProviderTool(tool)) {\n throw new FeatureNotSupportedError(\n `Provider tool ${tool.name}`,\n \"openai:completions\",\n modelId,\n `Provider tool '${tool.name}' is not supported by OpenAI Completions API. Try using the Responses API instead (append ':responses' to your model ID).`,\n );\n }\n regularTools.push(tool);\n }\n if (regularTools.length > 0) {\n requestParams.tools = encodeTools(regularTools);\n }\n }\n /* v8 ignore stop */\n\n const maxTokens = p.get(\"maxTokens\");\n if (maxTokens !== undefined) {\n // max_completion_tokens is the preferred parameter (max_tokens is deprecated)\n requestParams.max_completion_tokens = maxTokens;\n }\n\n const temperature = p.get(\"temperature\");\n if (temperature !== undefined) {\n requestParams.temperature = temperature;\n }\n\n const topP = p.get(\"topP\");\n if (topP !== undefined) {\n requestParams.top_p = topP;\n }\n\n const seed = p.get(\"seed\");\n if (seed !== undefined) {\n requestParams.seed = seed;\n }\n\n const stopSequences = p.get(\"stopSequences\");\n if (stopSequences !== undefined) {\n requestParams.stop = stopSequences;\n }\n\n // OpenAI doesn't support topK\n p.warnUnsupported(\"topK\", \"OpenAI does not support the top_k parameter\");\n\n return requestParams;\n });\n}\n\n/**\n * Serialize a message object for storage in rawMessage.\n *\n * This mirrors Python's `message.model_dump(exclude_none=True)` pattern.\n */\nfunction serializeMessage(\n message: ChatCompletion.Choice[\"message\"],\n): Record<string, unknown> {\n const serialized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(message)) {\n if (value !== undefined && value !== null) {\n serialized[key] = value;\n }\n }\n return serialized;\n}\n\n/**\n * Decode OpenAI Chat Completions response to Mirascope types.\n */\nexport function decodeResponse(\n response: ChatCompletion,\n modelId: OpenAIModelId,\n): {\n assistantMessage: AssistantMessage;\n finishReason: FinishReason | null;\n usage: Usage | null;\n} {\n const choice = response.choices[0];\n /* v8 ignore start - defensive check for empty choices */\n if (!choice) {\n throw new Error(\"No choices in response\");\n }\n /* v8 ignore stop */\n\n const content = decodeContent(choice.message);\n\n // Store serialized message for round-tripping in resume operations.\n // This format matches what OpenAI expects as ChatCompletionAssistantMessageParam.\n const serializedRawMessage = serializeMessage(choice.message);\n\n const assistantMessage: AssistantMessage = {\n role: \"assistant\",\n content,\n name: null,\n providerId: \"openai\",\n modelId,\n providerModelName: modelName(modelId, \"completions\"),\n rawMessage:\n serializedRawMessage as unknown as AssistantMessage[\"rawMessage\"],\n };\n\n const finishReason = decodeFinishReason(choice.finish_reason);\n\n /* v8 ignore next - usage is always present in API responses */\n const usage = response.usage ? decodeUsage(response.usage) : null;\n\n return { assistantMessage, finishReason, usage };\n}\n\nfunction decodeContent(\n message: ChatCompletion.Choice[\"message\"],\n): AssistantContentPart[] {\n const parts: AssistantContentPart[] = [];\n\n // Handle text content\n if (message.content) {\n const text: Text = { type: \"text\", text: message.content };\n parts.push(text);\n }\n\n // Handle refusal as text (OpenAI returns refusal as separate field)\n /* v8 ignore start - refusals are difficult to trigger reliably */\n if (message.refusal) {\n const text: Text = { type: \"text\", text: message.refusal };\n parts.push(text);\n }\n /* v8 ignore end */\n\n /* v8 ignore start - tool decoding will be tested via e2e */\n // Handle tool calls\n if (message.tool_calls && message.tool_calls.length > 0) {\n for (const tc of message.tool_calls) {\n // Only handle function type tool calls\n if (tc.type === \"function\") {\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n };\n parts.push(toolCall);\n }\n }\n }\n /* v8 ignore stop */\n\n return parts;\n}\n\nfunction decodeFinishReason(\n finishReason: ChatCompletion.Choice[\"finish_reason\"],\n): FinishReason | null {\n switch (finishReason) {\n case \"length\":\n return FinishReason.MAX_TOKENS;\n /* v8 ignore start - refusals are difficult to trigger reliably */\n case \"content_filter\":\n return FinishReason.REFUSAL;\n /* v8 ignore end */\n case \"stop\":\n case \"tool_calls\":\n case \"function_call\":\n return null; // Normal completion\n /* v8 ignore next 2 - defensive default case */\n default:\n return null;\n }\n}\n\nfunction decodeUsage(usage: NonNullable<ChatCompletion[\"usage\"]>): Usage {\n return createUsage({\n inputTokens: usage.prompt_tokens,\n outputTokens: usage.completion_tokens,\n cacheReadTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,\n reasoningTokens: usage.completion_tokens_details?.reasoning_tokens ?? 0,\n raw: usage,\n });\n}\n","/**\n * OpenAI Completions stream decoding utilities.\n *\n * Converts OpenAI ChatCompletionChunk to Mirascope StreamResponseChunk.\n * The Chat Completions API does not support native reasoning/thinking.\n */\n\nimport type { ChatCompletionChunk } from \"openai/resources/chat/completions\";\n\nimport type { StreamResponseChunk } from \"@/llm/responses/chunks\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport {\n textStart,\n textChunk,\n textEnd,\n toolCallStart,\n toolCallChunk,\n toolCallEnd,\n} from \"@/llm/content\";\nimport {\n finishReasonChunk,\n usageDeltaChunk,\n rawStreamEventChunk,\n rawMessageChunk,\n} from \"@/llm/responses/chunks\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\n\n/**\n * State tracking for stream decoding.\n * Matches Python SDK's _OpenAIChunkProcessor state.\n */\ninterface DecodeState {\n /** Current content type being streamed */\n currentContentType: \"text\" | \"tool_call\" | null;\n /** Index of the current tool call being streamed */\n currentToolIndex: number | null;\n /** ID of the current tool call being streamed */\n currentToolId: string | null;\n /** Whether a refusal was encountered */\n refusalEncountered: boolean;\n}\n\n/**\n * Create a new decode state for a fresh stream.\n */\nexport function createDecodeState(): DecodeState {\n return {\n currentContentType: null,\n currentToolIndex: null,\n currentToolId: null,\n refusalEncountered: false,\n };\n}\n\n/**\n * Decode an OpenAI ChatCompletionChunk to Mirascope chunks.\n *\n * @param chunk - The OpenAI stream chunk\n * @param state - Mutable state tracking current block\n * @returns Array of Mirascope chunks (may be empty or multiple)\n */\nexport function decodeStreamEvent(\n chunk: ChatCompletionChunk,\n state: DecodeState,\n): StreamResponseChunk[] {\n const chunks: StreamResponseChunk[] = [];\n\n // Always emit raw event chunk for debugging/passthrough\n chunks.push(rawStreamEventChunk(chunk));\n\n // Emit raw message chunk\n chunks.push(rawMessageChunk(chunk as unknown as Jsonable));\n\n // Handle usage (typically in the last chunk when stream_options.include_usage is true)\n if (chunk.usage) {\n chunks.push(\n usageDeltaChunk({\n inputTokens: chunk.usage.prompt_tokens,\n outputTokens: chunk.usage.completion_tokens,\n /* v8 ignore start - optional details may not be present */\n cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens ?? 0,\n reasoningTokens:\n chunk.usage.completion_tokens_details?.reasoning_tokens ?? 0,\n /* v8 ignore stop */\n }),\n );\n }\n\n const choice = chunk.choices[0];\n if (!choice) {\n return chunks;\n }\n\n const delta = choice.delta;\n\n // Handle text content (including refusal as text)\n const content = delta?.content ?? delta?.refusal;\n /* v8 ignore start - refusal is a rare edge case */\n if (delta?.refusal) {\n state.refusalEncountered = true;\n }\n /* v8 ignore stop */\n if (content !== undefined && content !== null) {\n if (state.currentContentType === null) {\n chunks.push(textStart());\n state.currentContentType = \"text\";\n }\n chunks.push(textChunk(content));\n }\n\n // Handle tool calls\n if (delta?.tool_calls) {\n /* v8 ignore start - rare to have text and tool calls in same chunk */\n if (state.currentContentType === \"text\") {\n chunks.push(textEnd());\n }\n /* v8 ignore stop */\n state.currentContentType = \"tool_call\";\n\n for (const toolCallDelta of delta.tool_calls) {\n const index = toolCallDelta.index;\n\n // Check for out-of-order tool call data\n /* v8 ignore start - defensive check for malformed streams */\n if (state.currentToolIndex !== null && state.currentToolIndex > index) {\n throw new Error(\n `Received tool data for already-finished tool at index ${index}`,\n );\n }\n /* v8 ignore stop */\n\n // If we're moving to a new tool (higher index), close the previous one\n if (state.currentToolIndex !== null && state.currentToolIndex < index) {\n /* v8 ignore start - defensive check */\n if (state.currentToolId === null) {\n throw new Error(\"No current_tool_id for ToolCallEndChunk\");\n }\n /* v8 ignore stop */\n chunks.push(toolCallEnd(state.currentToolId));\n state.currentToolIndex = null;\n }\n\n // Start a new tool call if we don't have one at this index\n if (state.currentToolIndex === null) {\n const name = toolCallDelta.function?.name;\n const toolId = toolCallDelta.id;\n /* v8 ignore start - defensive check for malformed streams */\n if (!name) {\n throw new Error(`Missing name for tool call at index ${index}`);\n }\n if (!toolId) {\n throw new Error(`Missing id for tool call at index ${index}`);\n }\n /* v8 ignore stop */\n\n state.currentToolIndex = index;\n state.currentToolId = toolId;\n chunks.push(toolCallStart(toolId, name));\n }\n\n // Emit tool call argument chunk if present\n if (toolCallDelta.function?.arguments) {\n /* v8 ignore start - defensive check */\n if (state.currentToolId === null) {\n throw new Error(\"No current_tool_id for ToolCallChunk\");\n }\n /* v8 ignore stop */\n chunks.push(\n toolCallChunk(state.currentToolId, toolCallDelta.function.arguments),\n );\n }\n }\n }\n\n // Handle finish reason\n if (choice.finish_reason) {\n if (state.currentContentType === \"text\") {\n chunks.push(textEnd());\n } else if (state.currentContentType === \"tool_call\") {\n /* v8 ignore start - defensive check */\n if (state.currentToolId === null) {\n throw new Error(\"No current_tool_id for ToolCallEndChunk\");\n }\n /* v8 ignore stop */\n chunks.push(toolCallEnd(state.currentToolId));\n /* v8 ignore start - defensive check for unknown content types */\n } else if (state.currentContentType !== null) {\n throw new Error(\"Unexpected content type\");\n }\n /* v8 ignore stop */\n\n // Emit finish reason if applicable\n /* v8 ignore next 2 - refusal is a rare edge case */\n const finishReason = state.refusalEncountered\n ? FinishReason.REFUSAL\n : decodeFinishReason(choice.finish_reason);\n if (finishReason !== null) {\n chunks.push(finishReasonChunk(finishReason));\n }\n }\n\n return chunks;\n}\n\n/**\n * Convert OpenAI finish reason to Mirascope FinishReason.\n */\nfunction decodeFinishReason(\n finishReason: ChatCompletionChunk.Choice[\"finish_reason\"],\n): FinishReason | null {\n switch (finishReason) {\n case \"length\":\n return FinishReason.MAX_TOKENS;\n /* v8 ignore start - content_filter is a rare edge case */\n case \"content_filter\":\n return FinishReason.REFUSAL;\n /* v8 ignore stop */\n case \"stop\":\n case \"tool_calls\":\n case \"function_call\":\n return null; // Normal completion\n /* v8 ignore start - exhaustive switch default */\n default:\n return null;\n /* v8 ignore stop */\n }\n}\n\n/**\n * Create an async iterator that decodes OpenAI stream chunks to Mirascope chunks.\n *\n * @param stream - The OpenAI completion stream\n * @returns Async iterator of Mirascope chunks\n */\nexport async function* decodeStream(\n stream: AsyncIterable<ChatCompletionChunk>,\n): AsyncGenerator<StreamResponseChunk> {\n const state = createDecodeState();\n\n for await (const chunk of stream) {\n const chunks = decodeStreamEvent(chunk, state);\n for (const c of chunks) {\n yield c;\n }\n }\n}\n","/**\n * Base class for OpenAI Completions-compatible providers.\n *\n * This base class contains all the logic for calling OpenAI-compatible APIs.\n * Subclasses (OpenAICompletionsProvider, OllamaProvider, etc.) extend this\n * and provide their specific configuration.\n */\n\nimport OpenAI from \"openai\";\n\nimport type { Context } from \"@/llm/context\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { Tools, ContextTools } from \"@/llm/tools\";\n\nimport { BaseProvider } from \"@/llm/providers/base\";\nimport { OPENAI_ERROR_MAP } from \"@/llm/providers/openai/_utils/errors\";\nimport {\n buildRequestParams,\n decodeResponse,\n} from \"@/llm/providers/openai/completions/_utils\";\nimport { decodeStream } from \"@/llm/providers/openai/completions/decode-stream\";\nimport { Response } from \"@/llm/responses\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport { StreamResponse } from \"@/llm/responses/stream-response\";\n\n/**\n * Configuration for initializing an OpenAI-compatible provider.\n */\nexport interface BaseOpenAICompletionsProviderInit {\n apiKey?: string;\n baseURL?: string;\n}\n\n/**\n * Internal configuration passed from subclass to base class.\n */\ninterface BaseOpenAICompletionsProviderConfig {\n /** The provider identifier */\n id: string;\n /** Resolved API key */\n apiKey: string | undefined;\n /** Resolved base URL */\n baseURL: string | undefined;\n}\n\n/**\n * Base class for providers that use OpenAI Completions-compatible APIs.\n *\n * Subclasses must:\n * - Set `id` as a readonly property\n * - Override `resolveConfig()` to provide API key and base URL resolution\n * - Optionally override `modelName()` to extract model name from model ID\n * - Optionally override `providerModelName()` for Response tracking\n */\nexport abstract class BaseOpenAICompletionsProvider extends BaseProvider {\n abstract readonly id: string;\n protected readonly errorMap = OPENAI_ERROR_MAP;\n protected readonly client: OpenAI;\n\n constructor(config: BaseOpenAICompletionsProviderConfig) {\n super();\n\n // If base URL is set but no API key, use placeholder\n let effectiveApiKey = config.apiKey;\n /* v8 ignore start - tested via E2E with custom base URLs */\n if (config.baseURL !== undefined && !effectiveApiKey) {\n effectiveApiKey = \"not-needed\";\n }\n /* v8 ignore stop */\n\n this.client = new OpenAI({\n apiKey: effectiveApiKey,\n baseURL: config.baseURL,\n });\n }\n\n /**\n * Extract the model name to send to the API.\n * Override in subclasses to strip provider-specific prefixes.\n */\n protected modelName(modelId: string): string {\n return modelId;\n }\n\n /**\n * Get the model name for tracking in Response.\n * Override in subclasses for custom tracking names.\n */\n /* v8 ignore start - default used by subclasses, tested via E2E */\n protected providerModelName(modelId: string): string {\n return this.modelName(modelId);\n }\n /* v8 ignore stop */\n\n /**\n * Execute a call to the OpenAI-compatible API.\n */\n protected async _call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<Response> {\n const apiModelName = this.modelName(args.modelId);\n const requestParams = buildRequestParams(\n apiModelName,\n args.messages,\n args.tools,\n args.params,\n );\n\n const openaiResponse =\n await this.client.chat.completions.create(requestParams);\n\n const { assistantMessage, finishReason, usage } = decodeResponse(\n openaiResponse,\n apiModelName,\n );\n\n return new Response({\n raw: openaiResponse,\n providerId: this.id,\n modelId: args.modelId,\n providerModelName: this.providerModelName(args.modelId),\n params: args.params ?? {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a streaming call to the OpenAI-compatible API.\n */\n protected async _stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<StreamResponse> {\n const apiModelName = this.modelName(args.modelId);\n const requestParams = buildRequestParams(\n apiModelName,\n args.messages,\n args.tools,\n args.params,\n );\n\n const stream = await this.client.chat.completions.create({\n ...requestParams,\n stream: true,\n stream_options: { include_usage: true },\n });\n\n const chunkIterator = decodeStream(stream);\n\n return new StreamResponse({\n providerId: this.id,\n modelId: args.modelId,\n providerModelName: this.providerModelName(args.modelId),\n params: args.params ?? /* v8 ignore next */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n chunkIterator,\n });\n }\n\n /**\n * Execute a context-aware call to the OpenAI-compatible API.\n */\n protected async _contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n const apiModelName = this.modelName(args.modelId);\n const requestParams = buildRequestParams(\n apiModelName,\n args.messages,\n args.tools,\n args.params,\n );\n\n const openaiResponse =\n await this.client.chat.completions.create(requestParams);\n\n const { assistantMessage, finishReason, usage } = decodeResponse(\n openaiResponse,\n apiModelName,\n );\n\n return new ContextResponse({\n raw: openaiResponse,\n providerId: this.id,\n modelId: args.modelId,\n providerModelName: this.providerModelName(args.modelId),\n params: args.params ?? /* v8 ignore next */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a context-aware streaming call to the OpenAI-compatible API.\n */\n protected async _contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n const apiModelName = this.modelName(args.modelId);\n const requestParams = buildRequestParams(\n apiModelName,\n args.messages,\n args.tools,\n args.params,\n );\n\n const stream = await this.client.chat.completions.create({\n ...requestParams,\n stream: true,\n stream_options: { include_usage: true },\n });\n\n const chunkIterator = decodeStream(stream);\n\n return new ContextStreamResponse({\n providerId: this.id,\n modelId: args.modelId,\n providerModelName: this.providerModelName(args.modelId),\n params: args.params ?? /* v8 ignore next */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n chunkIterator,\n });\n }\n\n /**\n * Extract the HTTP status code from an OpenAI API error.\n */\n protected getErrorStatus(e: Error): number | undefined {\n return (e as InstanceType<typeof OpenAI.APIError>).status;\n }\n}\n","/**\n * Ollama provider implementation.\n *\n * Ollama provides an OpenAI-compatible API for local LLM inference.\n */\n\nimport { BaseOpenAICompletionsProvider } from \"@/llm/providers/openai/completions/base-provider\";\n\nconst DEFAULT_BASE_URL = \"http://localhost:11434/v1/\";\nconst API_KEY_ENV_VAR = \"OLLAMA_API_KEY\";\n\nexport interface OllamaProviderInit {\n apiKey?: string;\n baseURL?: string;\n}\n\n/**\n * Provider for Ollama's OpenAI-compatible API.\n *\n * Inherits from BaseOpenAICompletionsProvider with Ollama-specific configuration:\n * - Uses Ollama's local API endpoint (default: http://localhost:11434/v1/)\n * - API key is not required (Ollama ignores API keys)\n * - Supports OLLAMA_BASE_URL environment variable\n *\n * @example\n * ```typescript\n * const provider = new OllamaProvider();\n * const response = await provider.call({\n * modelId: 'ollama/llama2',\n * messages: [user('Hello!')],\n * });\n * console.log(response.text());\n * ```\n */\nexport class OllamaProvider extends BaseOpenAICompletionsProvider {\n readonly id = \"ollama\" as const;\n\n /**\n * Create a new Ollama provider instance.\n *\n * @param init - Configuration options\n * @param init.apiKey - API key (defaults to OLLAMA_API_KEY env var, or 'ollama' if not set)\n * @param init.baseURL - Base URL (defaults to OLLAMA_BASE_URL env var, or 'http://localhost:11434/v1/')\n */\n constructor(init: OllamaProviderInit = {}) {\n const resolvedApiKey =\n init.apiKey ?? process.env[API_KEY_ENV_VAR] ?? \"ollama\";\n const resolvedBaseUrl =\n init.baseURL ?? process.env.OLLAMA_BASE_URL ?? DEFAULT_BASE_URL;\n\n super({\n id: \"ollama\",\n apiKey: resolvedApiKey,\n baseURL: resolvedBaseUrl,\n });\n }\n\n /**\n * Strip 'ollama/' prefix from model ID for Ollama API.\n */\n protected override modelName(modelId: string): string {\n return modelId.startsWith(\"ollama/\") ? modelId.slice(7) : modelId;\n }\n}\n","export { OllamaProvider, type OllamaProviderInit } from \"./provider\";\n","/**\n * OpenAI Completions provider implementation.\n */\n\nimport {\n BaseOpenAICompletionsProvider,\n type BaseOpenAICompletionsProviderInit,\n} from \"@/llm/providers/openai/completions/base-provider\";\nimport { modelName } from \"@/llm/providers/openai/model-id\";\n\nconst API_KEY_ENV_VAR = \"OPENAI_API_KEY\";\n\n/**\n * Provider for the OpenAI Chat Completions API.\n *\n * This provider uses the Chat Completions API (not the Responses API).\n * For the routing provider that selects between APIs, use `OpenAIProvider`.\n *\n * @example\n * ```typescript\n * const provider = new OpenAICompletionsProvider();\n * const response = await provider.call({\n * modelId: 'openai/gpt-4o',\n * messages: [user('Hello!')],\n * });\n * console.log(response.text());\n * ```\n */\nexport class OpenAICompletionsProvider extends BaseOpenAICompletionsProvider {\n readonly id = \"openai\" as const;\n\n constructor(init: BaseOpenAICompletionsProviderInit = {}) {\n const resolvedApiKey = init.apiKey ?? process.env[API_KEY_ENV_VAR];\n super({\n id: \"openai\",\n apiKey: resolvedApiKey,\n baseURL: init.baseURL,\n });\n }\n\n /**\n * Get the model name for tracking in Response.\n *\n * Returns the model name with :completions suffix for tracking which API was used.\n */\n protected override providerModelName(modelId: string): string {\n return modelName(modelId, \"completions\");\n }\n}\n","/**\n * OpenAI Responses API utilities for encoding requests and decoding responses.\n */\n\nimport type OpenAI from \"openai\";\nimport type {\n Response as OpenAIResponse,\n ResponseCreateParamsNonStreaming,\n FunctionTool,\n ResponseFunctionToolCall,\n ResponseInputContent,\n ResponseInputImage,\n ResponseInputItem,\n ResponseOutputItem,\n} from \"openai/resources/responses/responses\";\nimport type { Reasoning, ReasoningEffort } from \"openai/resources/shared\";\n\nimport type {\n AssistantContentPart,\n Image,\n Text,\n Thought,\n ToolCall,\n} from \"@/llm/content\";\nimport type { AssistantMessage, Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { ThinkingLevel } from \"@/llm/models/thinking-config\";\nimport type { OpenAIModelId } from \"@/llm/providers/openai/model-id\";\nimport type { Usage } from \"@/llm/responses/usage\";\nimport type { ToolSchema, Tools } from \"@/llm/tools\";\n\nimport { FeatureNotSupportedError } from \"@/llm/exceptions\";\nimport { ParamHandler } from \"@/llm/providers/base\";\nimport { modelName } from \"@/llm/providers/openai/model-id\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\nimport { createUsage } from \"@/llm/responses/usage\";\nimport { ProviderTool, isProviderTool, isWebSearchTool } from \"@/llm/tools\";\n\n/**\n * Maps ThinkingLevel to OpenAI ReasoningEffort.\n */\nconst THINKING_LEVEL_TO_EFFORT: Record<ThinkingLevel, ReasoningEffort> = {\n default: \"medium\",\n none: \"none\",\n minimal: \"minimal\",\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n max: \"xhigh\",\n};\n\n/**\n * Compute OpenAI Reasoning config from ThinkingConfig.\n *\n * @param level - The thinking level\n * @param includeThoughts - Whether to include reasoning summary\n * @returns OpenAI Reasoning configuration\n */\nexport function computeReasoning(\n level: ThinkingLevel,\n includeThoughts: boolean,\n): Reasoning {\n const reasoning: Reasoning = {\n /* v8 ignore next - all ThinkingLevel values are covered in the map */\n effort: THINKING_LEVEL_TO_EFFORT[level] ?? \"medium\",\n };\n\n if (includeThoughts) {\n reasoning.summary = \"auto\";\n }\n\n return reasoning;\n}\n\n/**\n * Simple message type for easy input (user, assistant, developer roles).\n */\ntype EasyInputMessage = OpenAI.Responses.EasyInputMessage;\n\n// ============================================================================\n// Content Part Encoding\n// ============================================================================\n\n/**\n * Encode an Image to the Responses API format.\n */\nfunction encodeImage(image: Image): ResponseInputImage {\n let imageUrl: string;\n if (image.source.type === \"url_image_source\") {\n imageUrl = image.source.url;\n } else {\n imageUrl = `data:${image.source.mimeType};base64,${image.source.data}`;\n }\n return { type: \"input_image\", image_url: imageUrl, detail: \"auto\" };\n}\n\n// ============================================================================\n// Tool Encoding\n// ============================================================================\n\n/* v8 ignore start - tool encoding will be tested via e2e */\n/**\n * Encode a tool schema to OpenAI Responses API tool format.\n */\nexport function encodeToolSchema(tool: ToolSchema): FunctionTool {\n return {\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\",\n properties: tool.parameters.properties as Record<string, unknown>,\n required: tool.parameters.required as string[] | undefined,\n },\n strict: tool.strict ?? null,\n };\n}\n\n/**\n * Encode multiple tool schemas for OpenAI Responses API.\n */\nexport function encodeTools(tools: readonly ToolSchema[]): FunctionTool[] {\n return tools.map(encodeToolSchema);\n}\n/* v8 ignore stop */\n\n// ============================================================================\n// Message Encoding\n// ============================================================================\n\n/**\n * Encode Mirascope messages to OpenAI Responses API format.\n *\n * Key differences from Completions API:\n * - System messages use role: 'developer' (not 'system')\n * - Uses EasyInputMessageParam for simple message format\n * - Returns flat array of input items (not nested messages)\n * - Assistant messages with multiple text parts are encoded as separate messages\n * - Tool outputs are encoded as function_call_output items\n *\n * @param messages - The messages to encode\n * @param modelId - The model ID for the request (used to check if raw message can be reused)\n */\nexport function encodeMessages(\n messages: readonly Message[],\n modelId: OpenAIModelId,\n): ResponseInputItem[] {\n const inputItems: ResponseInputItem[] = [];\n const expectedProviderModelName = modelName(modelId, \"responses\");\n\n for (const message of messages) {\n if (message.role === \"system\") {\n inputItems.push({\n role: \"developer\",\n content: message.content.text,\n });\n } else if (message.role === \"user\") {\n // Check for tool outputs first\n const toolOutputs = encodeToolOutputs(message);\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (toolOutputs.length > 0) {\n inputItems.push(...toolOutputs);\n }\n /* v8 ignore stop */\n // Then encode any non-tool content as a user message\n const userMessage = encodeUserMessage(message);\n if (userMessage !== null) {\n inputItems.push(userMessage);\n }\n } else if (message.role === \"assistant\") {\n // Check if we can reuse the raw message (from same provider/model)\n if (\n message.providerId === \"openai\" &&\n message.providerModelName === expectedProviderModelName &&\n message.rawMessage &&\n Array.isArray(message.rawMessage)\n ) {\n // Reuse serialized output items directly\n inputItems.push(\n ...(message.rawMessage as unknown as ResponseInputItem[]),\n );\n } else {\n // Otherwise, encode from content parts\n inputItems.push(...encodeAssistantMessage(message));\n }\n }\n }\n\n return inputItems;\n}\n\n/* v8 ignore start - tool encoding will be tested via e2e */\n/**\n * Encode tool outputs from a user message to function_call_output items.\n */\nfunction encodeToolOutputs(\n message: Extract<Message, { role: \"user\" }>,\n): ResponseInputItem.FunctionCallOutput[] {\n const outputs: ResponseInputItem.FunctionCallOutput[] = [];\n\n for (const part of message.content) {\n if (part.type === \"tool_output\") {\n outputs.push({\n type: \"function_call_output\",\n call_id: part.id,\n output:\n typeof part.result === \"string\"\n ? part.result\n : JSON.stringify(part.result),\n });\n }\n }\n\n return outputs;\n}\n/* v8 ignore stop */\n\n/**\n * Encode a Mirascope user message to OpenAI Responses API format.\n *\n * - Single text part: string content (simplified)\n * - Multiple parts or non-text content: array of content items\n * - Returns null if message contains only tool outputs (handled separately)\n */\nfunction encodeUserMessage(\n message: Extract<Message, { role: \"user\" }>,\n): EasyInputMessage | null {\n const contentItems: ResponseInputContent[] = [];\n\n for (const part of message.content) {\n switch (part.type) {\n case \"text\":\n contentItems.push({ type: \"input_text\", text: part.text });\n break;\n\n case \"image\":\n contentItems.push(encodeImage(part));\n break;\n\n case \"audio\":\n throw new FeatureNotSupportedError(\n \"audio input\",\n \"openai\",\n null,\n 'OpenAI Responses API does not support audio inputs. Try appending \":completions\" to your model ID instead.',\n );\n\n /* v8 ignore start - content types not yet fully implemented */\n case \"document\":\n throw new FeatureNotSupportedError(\n \"document content encoding\",\n \"openai\",\n null,\n \"Document content is not yet implemented\",\n );\n\n case \"tool_output\":\n // Tool outputs in Responses API are handled separately as function_call_output items\n // Skip here - they're processed in encodeMessages\n break;\n /* v8 ignore stop */\n }\n }\n\n // No content (only tool outputs) - return null\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (contentItems.length === 0) {\n return null;\n }\n /* v8 ignore stop */\n\n // Single text part: simplify to string\n if (contentItems.length === 1 && contentItems[0]?.type === \"input_text\") {\n return {\n role: \"user\",\n content: contentItems[0].text,\n };\n }\n\n // Multiple parts or non-text content: use array format\n return {\n role: \"user\",\n content: contentItems,\n };\n}\n\n/**\n * Encode a Mirascope assistant message to OpenAI Responses API format.\n *\n * Note: OpenAI does not provide any way to encode multiple pieces of assistant-generated\n * text as adjacent content within the same Message. Rather than generating fake fields,\n * we encode each text part as a separate EasyInputMessage.\n *\n * @returns Array of input items (text messages and function calls)\n */\nfunction encodeAssistantMessage(\n message: AssistantMessage,\n): ResponseInputItem[] {\n const result: ResponseInputItem[] = [];\n\n for (const part of message.content) {\n if (part.type === \"text\") {\n result.push({\n role: \"assistant\",\n content: part.text,\n });\n }\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (part.type === \"tool_call\") {\n const toolCallItem: ResponseFunctionToolCall = {\n type: \"function_call\",\n id: part.id,\n call_id: part.id, // Used to match with function_call_output\n name: part.name,\n arguments: part.args,\n status: \"completed\", // Required for model to recognize tool was executed\n };\n result.push(toolCallItem);\n }\n /* v8 ignore stop */\n // Note: thought encoding is not yet implemented\n }\n\n return result;\n}\n\n/**\n * Build the request parameters for the OpenAI Responses API.\n *\n * This function performs strict param checking - any unhandled params will\n * cause an error to ensure we don't silently ignore user configuration.\n *\n * @param modelId - The model ID to use\n * @param messages - The messages to send\n * @param tools - Optional tools to make available to the model\n * @param params - Optional parameters (temperature, maxTokens, etc.)\n */\nexport function buildRequestParams(\n modelId: OpenAIModelId,\n messages: readonly Message[],\n tools?: Tools,\n params: Params = {},\n): ResponseCreateParamsNonStreaming {\n const inputItems = encodeMessages(messages, modelId);\n\n return ParamHandler.with(params, \"openai\", modelId, (p) => {\n const requestParams: ResponseCreateParamsNonStreaming = {\n model: modelName(modelId, null),\n input: inputItems,\n };\n\n /* v8 ignore start - tool encoding will be tested via e2e */\n if (tools && tools.length > 0) {\n // Separate regular tools from provider tools\n const regularTools: ToolSchema[] = [];\n const allTools: ResponseCreateParamsNonStreaming[\"tools\"] = [];\n\n for (const tool of tools) {\n // Check for provider tools first (WebSearchTool extends ProviderTool)\n if (isProviderTool(tool)) {\n if (isWebSearchTool(tool)) {\n // OpenAI Responses API web search tool\n allTools.push({ type: \"web_search\" });\n } else {\n // Cast needed because TS narrows to never after WebSearchTool check\n const unsupportedTool = tool as ProviderTool;\n throw new FeatureNotSupportedError(\n `Provider tool ${unsupportedTool.name}`,\n \"openai:responses\",\n modelId,\n `Provider tool '${unsupportedTool.name}' is not supported by OpenAI Responses API`,\n );\n }\n } else {\n // Regular tool (BaseTool extends ToolSchema)\n regularTools.push(tool as ToolSchema);\n }\n }\n\n if (regularTools.length > 0) {\n allTools.push(...encodeTools(regularTools));\n }\n\n if (allTools.length > 0) {\n requestParams.tools = allTools;\n }\n }\n /* v8 ignore stop */\n\n const maxTokens = p.get(\"maxTokens\");\n if (maxTokens !== undefined) {\n requestParams.max_output_tokens = maxTokens;\n }\n\n const temperature = p.get(\"temperature\");\n if (temperature !== undefined) {\n requestParams.temperature = temperature;\n }\n\n const topP = p.get(\"topP\");\n if (topP !== undefined) {\n requestParams.top_p = topP;\n }\n\n // OpenAI Responses API doesn't support these params\n p.warnUnsupported(\"topK\", \"OpenAI does not support the top_k parameter\");\n p.warnUnsupported(\n \"seed\",\n \"OpenAI Responses API does not support the seed parameter\",\n );\n p.warnUnsupported(\n \"stopSequences\",\n \"OpenAI Responses API does not support stop sequences\",\n );\n\n const thinkingConfig = p.get(\"thinking\");\n if (thinkingConfig) {\n const includeThoughts = thinkingConfig.includeThoughts ?? false;\n requestParams.reasoning = computeReasoning(\n thinkingConfig.level,\n includeThoughts,\n );\n }\n\n return requestParams;\n });\n}\n\n/**\n * Decode OpenAI Responses API response to Mirascope types.\n *\n * @param response - The raw OpenAI Responses API response\n * @param modelId - The model ID used for the request\n * @param includeThoughts - Whether to include reasoning blocks in the response (default: false)\n */\nexport function decodeResponse(\n response: OpenAIResponse,\n modelId: OpenAIModelId,\n includeThoughts: boolean = false,\n): {\n assistantMessage: AssistantMessage;\n finishReason: FinishReason | null;\n usage: Usage | null;\n} {\n const content = decodeContent(response.output, includeThoughts);\n const finishReason = decodeFinishReason(response);\n\n // Store serialized output items for round-tripping in resume operations.\n // This allows sending the exact output back as input when resuming.\n const serializedOutput = response.output.map(serializeOutputItem);\n\n const assistantMessage: AssistantMessage = {\n role: \"assistant\",\n content,\n name: null,\n providerId: \"openai\",\n modelId,\n providerModelName: modelName(modelId, \"responses\"),\n rawMessage: serializedOutput as unknown as AssistantMessage[\"rawMessage\"],\n };\n\n /* v8 ignore next - usage is always present in API responses */\n const usage = response.usage ? decodeUsage(response.usage) : null;\n\n return { assistantMessage, finishReason, usage };\n}\n\n/**\n * Decode output items from the Responses API to Mirascope content format.\n *\n * @param output - The output items from the response\n * @param includeThoughts - Whether to include reasoning blocks as thoughts\n */\nfunction decodeContent(\n output: OpenAIResponse[\"output\"],\n includeThoughts: boolean,\n): AssistantContentPart[] {\n const parts: AssistantContentPart[] = [];\n\n for (const item of output) {\n if (item.type === \"message\") {\n for (const contentPart of item.content) {\n if (contentPart.type === \"output_text\") {\n const text: Text = { type: \"text\", text: contentPart.text };\n parts.push(text);\n /* v8 ignore start - refusals are difficult to trigger reliably */\n } else if (contentPart.type === \"refusal\") {\n const text: Text = { type: \"text\", text: contentPart.refusal };\n parts.push(text);\n }\n /* v8 ignore stop */\n }\n /* v8 ignore start - tool decoding will be tested via e2e */\n } else if (item.type === \"function_call\") {\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: item.call_id,\n name: item.name,\n args: item.arguments,\n };\n parts.push(toolCall);\n /* v8 ignore stop */\n } else if (item.type === \"reasoning\") {\n if (includeThoughts) {\n // Extract thoughts from summary (preferred) or content\n /* v8 ignore next - summary is always defined per types, but defensive coding */\n for (const summaryPart of item.summary ?? []) {\n if (summaryPart.type === \"summary_text\") {\n const thought: Thought = {\n type: \"thought\",\n thought: summaryPart.text,\n };\n parts.push(thought);\n }\n }\n /* v8 ignore start - reasoning_text content is rare, likely only in open-source models */\n if (item.content) {\n for (const contentPart of item.content) {\n if (contentPart.type === \"reasoning_text\") {\n const thought: Thought = {\n type: \"thought\",\n thought: contentPart.text,\n };\n parts.push(thought);\n }\n }\n }\n /* v8 ignore stop */\n }\n }\n }\n\n return parts;\n}\n\n/**\n * Decode finish reason from the Responses API.\n *\n * The Responses API uses `incomplete_details.reason` instead of `finish_reason`.\n */\nfunction decodeFinishReason(response: OpenAIResponse): FinishReason | null {\n // Check for refusal in output content\n for (const item of response.output) {\n if (item.type === \"message\") {\n for (const contentPart of item.content) {\n /* v8 ignore start - refusals are difficult to trigger reliably */\n if (contentPart.type === \"refusal\") {\n return FinishReason.REFUSAL;\n }\n /* v8 ignore end */\n }\n }\n }\n\n // Check incomplete_details for finish reason\n if (response.incomplete_details) {\n const reason = response.incomplete_details.reason;\n if (reason === \"max_output_tokens\") {\n return FinishReason.MAX_TOKENS;\n }\n /* v8 ignore start - refusals are difficult to trigger reliably */\n if (reason === \"content_filter\") {\n return FinishReason.REFUSAL;\n }\n /* v8 ignore stop */\n }\n\n return null; // Normal completion\n}\n\n/**\n * Decode usage information from the Responses API.\n */\nfunction decodeUsage(usage: NonNullable<OpenAIResponse[\"usage\"]>): Usage {\n return createUsage({\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n cacheReadTokens: usage.input_tokens_details?.cached_tokens ?? 0,\n reasoningTokens: usage.output_tokens_details?.reasoning_tokens ?? 0,\n raw: usage,\n });\n}\n\n/**\n * Serialize an output item for storage in rawMessage.\n *\n * This is used for round-tripping assistant messages through the API.\n * The serialized items can be sent directly back as input items when\n * resuming a conversation.\n */\nfunction serializeOutputItem(\n item: ResponseOutputItem,\n): Record<string, unknown> {\n // Copy all non-undefined properties from the item\n const serialized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(item)) {\n if (value !== undefined) {\n serialized[key] = value;\n }\n }\n return serialized;\n}\n","/**\n * OpenAI Responses stream decoding utilities.\n *\n * Converts OpenAI Responses API streaming events to Mirascope StreamResponseChunk.\n * The Responses API supports reasoning/thinking through summary text.\n */\n\nimport type {\n ResponseStreamEvent,\n ResponseTextDeltaEvent,\n ResponseCompletedEvent,\n ResponseIncompleteEvent,\n} from \"openai/resources/responses/responses\";\n\nimport type { StreamResponseChunk } from \"@/llm/responses/chunks\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport {\n textStart,\n textChunk,\n textEnd,\n thoughtStart,\n thoughtChunk,\n thoughtEnd,\n toolCallStart,\n toolCallChunk,\n toolCallEnd,\n} from \"@/llm/content\";\nimport {\n finishReasonChunk,\n usageDeltaChunk,\n rawStreamEventChunk,\n rawMessageChunk,\n} from \"@/llm/responses/chunks\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\n\n/**\n * State tracking for stream decoding.\n */\ninterface DecodeState {\n /** Whether we're in a text block */\n inTextBlock: boolean;\n /** Whether we're in a thought block */\n inThoughtBlock: boolean;\n /** ID of current tool call being streamed */\n currentToolCallId: string | null;\n /** Whether to include thoughts in output */\n includeThoughts: boolean;\n}\n\n/**\n * Create a new decode state for a fresh stream.\n */\nexport function createDecodeState(includeThoughts: boolean): DecodeState {\n return {\n inTextBlock: false,\n inThoughtBlock: false,\n currentToolCallId: null,\n includeThoughts,\n };\n}\n\n/**\n * Decode an OpenAI Responses API stream event to Mirascope chunks.\n *\n * @param event - The OpenAI Responses stream event\n * @param state - Mutable state tracking current block\n * @returns Array of Mirascope chunks (may be empty or multiple)\n */\nexport function decodeStreamEvent(\n event: ResponseStreamEvent,\n state: DecodeState,\n): StreamResponseChunk[] {\n const chunks: StreamResponseChunk[] = [];\n\n // Always emit raw event chunk for debugging/passthrough\n chunks.push(rawStreamEventChunk(event));\n\n switch (event.type) {\n case \"response.created\":\n // Emit raw message chunk with initial response data\n chunks.push(rawMessageChunk(event.response as unknown as Jsonable));\n break;\n\n case \"response.output_text.delta\":\n handleTextDelta(event, state, chunks);\n break;\n\n case \"response.output_text.done\":\n if (state.inTextBlock) {\n chunks.push(textEnd());\n state.inTextBlock = false;\n }\n break;\n\n case \"response.reasoning_summary_text.delta\":\n if (state.includeThoughts) {\n handleThoughtDelta(event, state, chunks);\n }\n break;\n\n case \"response.reasoning_summary_text.done\":\n if (state.inThoughtBlock && state.includeThoughts) {\n chunks.push(thoughtEnd());\n state.inThoughtBlock = false;\n }\n break;\n\n /* v8 ignore start - OpenAI Responses API not in tools test providers */\n case \"response.output_item.added\":\n if (event.item.type === \"function_call\") {\n state.currentToolCallId = event.item.call_id;\n chunks.push(toolCallStart(event.item.call_id, event.item.name));\n }\n break;\n\n case \"response.function_call_arguments.delta\":\n if (state.currentToolCallId) {\n chunks.push(toolCallChunk(state.currentToolCallId, event.delta));\n }\n break;\n\n case \"response.function_call_arguments.done\":\n if (state.currentToolCallId) {\n chunks.push(toolCallEnd(state.currentToolCallId));\n state.currentToolCallId = null;\n }\n break;\n /* v8 ignore stop */\n\n case \"response.completed\":\n case \"response.incomplete\":\n // Close any open blocks\n /* v8 ignore start - blocks typically closed before completion event */\n if (state.inTextBlock) {\n chunks.push(textEnd());\n state.inTextBlock = false;\n }\n if (state.inThoughtBlock) {\n chunks.push(thoughtEnd());\n state.inThoughtBlock = false;\n }\n /* v8 ignore stop */\n\n handleCompleted(event, chunks);\n break;\n\n // Handle other events we might want to process\n /* v8 ignore start - refusal events are rare edge cases */\n case \"response.refusal.delta\":\n // Treat refusal as text\n handleRefusalDelta(event, state, chunks);\n break;\n\n case \"response.refusal.done\":\n // Close text block and emit refusal finish reason\n if (state.inTextBlock) {\n chunks.push(textEnd());\n state.inTextBlock = false;\n }\n chunks.push(finishReasonChunk(FinishReason.REFUSAL));\n break;\n /* v8 ignore stop */\n\n // Other events don't produce content chunks\n default:\n break;\n }\n\n return chunks;\n}\n\n/**\n * Handle text delta event.\n */\nfunction handleTextDelta(\n event: ResponseTextDeltaEvent,\n state: DecodeState,\n chunks: StreamResponseChunk[],\n): void {\n if (!state.inTextBlock) {\n // Close thought block if transitioning from thoughts to text\n /* v8 ignore start - edge case when thoughts precede text */\n if (state.inThoughtBlock) {\n chunks.push(thoughtEnd());\n state.inThoughtBlock = false;\n }\n /* v8 ignore stop */\n chunks.push(textStart());\n state.inTextBlock = true;\n }\n chunks.push(textChunk(event.delta));\n}\n\n/**\n * Handle reasoning summary delta event (thoughts).\n */\nfunction handleThoughtDelta(\n event: { type: \"response.reasoning_summary_text.delta\"; delta: string },\n state: DecodeState,\n chunks: StreamResponseChunk[],\n): void {\n if (!state.inThoughtBlock) {\n // Close text block if transitioning from text to thoughts\n /* v8 ignore start - edge case when text precedes thoughts */\n if (state.inTextBlock) {\n chunks.push(textEnd());\n state.inTextBlock = false;\n }\n /* v8 ignore stop */\n chunks.push(thoughtStart());\n state.inThoughtBlock = true;\n }\n chunks.push(thoughtChunk(event.delta));\n}\n\n/**\n * Handle refusal delta event.\n */\n/* v8 ignore start - refusal events are rare edge cases */\nfunction handleRefusalDelta(\n event: { type: \"response.refusal.delta\"; delta: string },\n state: DecodeState,\n chunks: StreamResponseChunk[],\n): void {\n // Treat refusal as text content\n if (!state.inTextBlock) {\n chunks.push(textStart());\n state.inTextBlock = true;\n }\n chunks.push(textChunk(event.delta));\n}\n/* v8 ignore stop */\n\n/**\n * Handle response.completed or response.incomplete event for finish reason and usage.\n */\nfunction handleCompleted(\n event: ResponseCompletedEvent | ResponseIncompleteEvent,\n chunks: StreamResponseChunk[],\n): void {\n const response = event.response;\n\n // Check for finish reason from incomplete_details\n /* v8 ignore start - incomplete_details only present when stream is incomplete */\n if (response.incomplete_details) {\n const reason = response.incomplete_details.reason;\n if (reason === \"max_output_tokens\") {\n chunks.push(finishReasonChunk(FinishReason.MAX_TOKENS));\n } else if (reason === \"content_filter\") {\n chunks.push(finishReasonChunk(FinishReason.REFUSAL));\n }\n }\n /* v8 ignore stop */\n\n // Emit usage if available\n if (response.usage) {\n chunks.push(\n usageDeltaChunk({\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n cacheReadTokens:\n /* v8 ignore next 1 */\n response.usage.input_tokens_details?.cached_tokens ?? 0,\n reasoningTokens:\n /* v8 ignore next 1 */\n response.usage.output_tokens_details?.reasoning_tokens ?? 0,\n }),\n );\n }\n}\n\n/**\n * Create an async iterator that decodes OpenAI Responses stream events to Mirascope chunks.\n *\n * @param stream - The OpenAI Responses stream\n * @param includeThoughts - Whether to include reasoning blocks as thought chunks\n * @returns Async iterator of Mirascope chunks\n */\nexport async function* decodeStream(\n stream: AsyncIterable<ResponseStreamEvent>,\n includeThoughts: boolean,\n): AsyncGenerator<StreamResponseChunk> {\n const state = createDecodeState(includeThoughts);\n\n for await (const event of stream) {\n const chunks = decodeStreamEvent(event, state);\n for (const chunk of chunks) {\n yield chunk;\n }\n }\n}\n","/**\n * OpenAI Responses provider implementation.\n */\n\nimport OpenAI from \"openai\";\n\nimport type { Context } from \"@/llm/context\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { OpenAIModelId } from \"@/llm/providers/openai/model-id\";\nimport type { Tools, ContextTools } from \"@/llm/tools\";\n\nimport { getIncludeThoughts } from \"@/llm/providers/_utils\";\nimport { BaseProvider } from \"@/llm/providers/base\";\nimport { OPENAI_ERROR_MAP } from \"@/llm/providers/openai/_utils/errors\";\nimport { modelName } from \"@/llm/providers/openai/model-id\";\nimport {\n buildRequestParams,\n decodeResponse,\n} from \"@/llm/providers/openai/responses/_utils\";\nimport { decodeStream } from \"@/llm/providers/openai/responses/decode-stream\";\nimport { Response } from \"@/llm/responses\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport { StreamResponse } from \"@/llm/responses/stream-response\";\n\n/**\n * Provider for the OpenAI Responses API.\n *\n * This provider uses the Responses API (not the Chat Completions API).\n * For the routing provider that selects between APIs, use `OpenAIProvider`.\n *\n * @example\n * ```typescript\n * const provider = new OpenAIResponsesProvider();\n * const response = await provider.call({\n * modelId: 'openai/gpt-4o:responses',\n * messages: [user('Hello!')],\n * });\n * console.log(response.text());\n * ```\n */\nexport class OpenAIResponsesProvider extends BaseProvider {\n readonly id = \"openai\" as const;\n protected readonly errorMap = OPENAI_ERROR_MAP;\n\n private readonly client: OpenAI;\n\n /**\n * Create a new OpenAI Responses provider instance.\n *\n * @param init - Configuration options\n * @param init.apiKey - OpenAI API key (defaults to OPENAI_API_KEY env var)\n * @param init.baseURL - Optional custom base URL for the API\n */\n constructor(init: { apiKey?: string; baseURL?: string } = {}) {\n super();\n this.client = new OpenAI({\n apiKey: init.apiKey,\n baseURL: init.baseURL,\n });\n }\n\n /**\n * Execute a call to the OpenAI Responses API.\n *\n * @param args - Call arguments\n * @param args.modelId - The OpenAI model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns Response object containing the API response\n */\n protected async _call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<Response> {\n const modelIdTyped = args.modelId as OpenAIModelId;\n const requestParams = buildRequestParams(\n modelIdTyped,\n args.messages,\n args.tools,\n args.params,\n );\n\n const openaiResponse = await this.client.responses.create(requestParams);\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const { assistantMessage, finishReason, usage } = decodeResponse(\n openaiResponse,\n modelIdTyped,\n includeThoughts,\n );\n\n return new Response({\n raw: openaiResponse,\n providerId: \"openai\",\n modelId: modelIdTyped,\n providerModelName: modelName(modelIdTyped, \"responses\"),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a streaming call to the OpenAI Responses API.\n *\n * @param args - Call arguments\n * @param args.modelId - The OpenAI model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns StreamResponse object for streaming consumption\n */\n protected async _stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<StreamResponse> {\n const modelIdTyped = args.modelId as OpenAIModelId;\n const requestParams = buildRequestParams(\n modelIdTyped,\n args.messages,\n args.tools,\n args.params,\n );\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const stream = await this.client.responses.create({\n ...requestParams,\n stream: true,\n });\n\n const chunkIterator = decodeStream(stream, includeThoughts);\n\n return new StreamResponse({\n providerId: \"openai\",\n modelId: modelIdTyped,\n providerModelName: modelName(modelIdTyped, \"responses\"),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n chunkIterator,\n });\n }\n\n /**\n * Execute a context-aware call to the OpenAI Responses API.\n *\n * NOTE: This implementation intentionally duplicates _call() rather than delegating.\n * When context-aware tools are implemented, this method will diverge to handle\n * passing context to tools during execution. We keep them separate now to make\n * that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The OpenAI model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns ContextResponse object containing the API response\n */\n protected async _contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n const modelIdTyped = args.modelId as OpenAIModelId;\n const requestParams = buildRequestParams(\n modelIdTyped,\n args.messages,\n args.tools,\n args.params,\n );\n\n const openaiResponse = await this.client.responses.create(requestParams);\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const { assistantMessage, finishReason, usage } = decodeResponse(\n openaiResponse,\n modelIdTyped,\n includeThoughts,\n );\n\n return new ContextResponse({\n raw: openaiResponse,\n providerId: \"openai\",\n modelId: modelIdTyped,\n providerModelName: modelName(modelIdTyped, \"responses\"),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a context-aware streaming call to the OpenAI Responses API.\n *\n * NOTE: This implementation intentionally duplicates _stream() rather than delegating.\n * When context-aware tools are implemented, this method will diverge to handle\n * passing context to tools during execution. We keep them separate now to make\n * that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The OpenAI model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns ContextStreamResponse object for streaming consumption\n */\n protected async _contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n const modelIdTyped = args.modelId as OpenAIModelId;\n const requestParams = buildRequestParams(\n modelIdTyped,\n args.messages,\n args.tools,\n args.params,\n );\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const stream = await this.client.responses.create({\n ...requestParams,\n stream: true,\n });\n\n const chunkIterator = decodeStream(stream, includeThoughts);\n\n return new ContextStreamResponse({\n providerId: \"openai\",\n modelId: modelIdTyped,\n providerModelName: modelName(modelIdTyped, \"responses\"),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format,\n inputMessages: args.messages,\n chunkIterator,\n });\n }\n\n /**\n * Extract the HTTP status code from an OpenAI API error.\n *\n * @param e - The error to extract the status from\n * @returns The HTTP status code or undefined if not available\n */\n protected getErrorStatus(e: Error): number | undefined {\n // OpenAI SDK uses 'status' property\n return (e as InstanceType<typeof OpenAI.APIError>).status;\n }\n}\n","/**\n * OpenAI provider implementation with routing between Completions and Responses APIs.\n */\n\nimport OpenAI from \"openai\";\n\nimport type { Context } from \"@/llm/context\";\nimport type { Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { ApiMode, OpenAIModelId } from \"@/llm/providers/openai/model-id\";\nimport type { ContextResponse } from \"@/llm/responses/context-response\";\nimport type { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport type { Tools, ContextTools } from \"@/llm/tools\";\n\nimport { BaseProvider } from \"@/llm/providers/base\";\nimport { OPENAI_ERROR_MAP } from \"@/llm/providers/openai/_utils/errors\";\nimport { OpenAICompletionsProvider } from \"@/llm/providers/openai/completions/provider\";\nimport { OPENAI_KNOWN_MODELS } from \"@/llm/providers/openai/model-info\";\nimport { OpenAIResponsesProvider } from \"@/llm/providers/openai/responses/provider\";\nimport { Response } from \"@/llm/responses\";\nimport { StreamResponse } from \"@/llm/responses/stream-response\";\n\n/**\n * Check if messages contain any audio content.\n *\n * Audio content requires the Completions API since Responses API doesn't support it yet.\n */\nfunction hasAudioContent(messages: readonly Message[]): boolean {\n for (const message of messages) {\n if (message.role === \"system\") {\n continue;\n }\n for (const part of message.content) {\n if (part.type === \"audio\") {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Choose between 'responses' or 'completions' API based on model ID and messages.\n *\n * If the user manually specified an API mode (by appending it as a suffix to the model\n * ID), then we use it.\n *\n * Otherwise, we prefer the Responses API where supported (because it has better\n * reasoning support and better prompt caching). However we will use the Completions API\n * if the messages contain any audio content, as audio content is not yet supported in\n * the Responses API.\n *\n * @param modelId - The model identifier\n * @param messages - The messages to send to the LLM\n * @returns Either \"responses\" or \"completions\" depending on the model and message content\n */\nexport function chooseApiMode(\n modelId: OpenAIModelId,\n messages: readonly Message[],\n): ApiMode {\n // Check explicit suffix\n if (modelId.endsWith(\":completions\")) {\n return \"completions\";\n }\n if (modelId.endsWith(\":responses\")) {\n return \"responses\";\n }\n\n // Audio content requires completions API\n if (hasAudioContent(messages)) {\n return \"completions\";\n }\n\n // Prefer responses API when we know it is available\n if (OPENAI_KNOWN_MODELS.has(`${modelId}:responses`)) {\n return \"responses\";\n }\n\n // If we know from testing that the completions API is available, and\n // (implied by above) that responses wasn't, then we should use completions\n if (OPENAI_KNOWN_MODELS.has(`${modelId}:completions`)) {\n return \"completions\";\n }\n\n // If we don't have either :responses or :completions in the known models, it's\n // likely that this is a new model we haven't tested. We default to responses API for\n // openai/ models (on the assumption that they are new models and OpenAI prefers\n // the responses API) but completions for other models (on the assumption that they\n // are other models routing through the OpenAI completions API)\n if (modelId.startsWith(\"openai/\")) {\n return \"responses\";\n }\n\n return \"completions\";\n}\n\n/**\n * Provider for the OpenAI API with intelligent routing between Completions and Responses APIs.\n *\n * This provider automatically selects the appropriate API based on the model ID and messages:\n * - Model IDs ending with `:completions` force the Chat Completions API\n * - Model IDs ending with `:responses` force the Responses API\n * - Messages with audio content use the Completions API (Responses doesn't support audio)\n * - Known models prefer the Responses API when available\n * - Unknown openai/ models default to Responses API\n * - Other unknown models default to Completions API (for OpenAI-compatible providers)\n *\n * @example\n * ```typescript\n * const provider = new OpenAIProvider();\n *\n * // Smart routing: uses Responses API for known models\n * const response = await provider.call({\n * modelId: 'openai/gpt-4o',\n * messages: [user('Hello!')],\n * });\n *\n * // Explicitly force Completions API\n * const response2 = await provider.call({\n * modelId: 'openai/gpt-4o:completions',\n * messages: [user('Hello!')],\n * });\n * ```\n */\nexport class OpenAIProvider extends BaseProvider {\n readonly id = \"openai\" as const;\n protected readonly errorMap = OPENAI_ERROR_MAP;\n\n private readonly completionsProvider: OpenAICompletionsProvider;\n private readonly responsesProvider: OpenAIResponsesProvider;\n\n /**\n * Create a new OpenAI provider instance.\n *\n * @param init - Configuration options\n * @param init.apiKey - OpenAI API key (defaults to OPENAI_API_KEY env var)\n * @param init.baseURL - Optional custom base URL for the API\n */\n constructor(init: { apiKey?: string; baseURL?: string } = {}) {\n super();\n this.completionsProvider = new OpenAICompletionsProvider(init);\n this.responsesProvider = new OpenAIResponsesProvider(init);\n }\n\n /**\n * Execute a call to the OpenAI API, routing to the appropriate API based on model ID.\n *\n * @param args - Call arguments\n * @param args.modelId - The OpenAI model ID to use (optionally with :completions or :responses suffix)\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.params - Optional additional parameters\n * @returns Response object containing the API response\n */\n protected async _call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n params?: Params;\n }): Promise<Response> {\n const modelId = args.modelId as OpenAIModelId;\n const apiMode = chooseApiMode(modelId, args.messages);\n\n if (apiMode === \"responses\") {\n // Delegate to the responses provider\n return this.responsesProvider.call({\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n params: args.params,\n });\n }\n\n // Delegate to the completions provider\n return this.completionsProvider.call({\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n params: args.params,\n });\n }\n\n /**\n * Execute a streaming call to the OpenAI API, routing to the appropriate API based on model ID.\n *\n * @param args - Call arguments\n * @param args.modelId - The OpenAI model ID to use (optionally with :completions or :responses suffix)\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.params - Optional additional parameters\n * @returns StreamResponse object for streaming consumption\n */\n protected async _stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n params?: Params;\n }): Promise<StreamResponse> {\n const modelId = args.modelId as OpenAIModelId;\n const apiMode = chooseApiMode(modelId, args.messages);\n\n if (apiMode === \"responses\") {\n return this.responsesProvider.stream({\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n params: args.params,\n });\n }\n\n return this.completionsProvider.stream({\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n params: args.params,\n });\n }\n\n /**\n * Execute a context-aware call to the OpenAI API, routing to the appropriate API.\n *\n * NOTE: This implementation intentionally duplicates _call() routing logic rather\n * than delegating. When context-aware tools are implemented, this method will\n * diverge to handle passing context to tools during execution. We keep them\n * separate now to make that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The OpenAI model ID to use (optionally with :completions or :responses suffix)\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.params - Optional additional parameters\n * @returns ContextResponse object containing the API response\n */\n protected async _contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n const modelId = args.modelId as OpenAIModelId;\n const apiMode = chooseApiMode(modelId, args.messages);\n\n if (apiMode === \"responses\") {\n // Delegate to the responses provider's context call\n return this.responsesProvider.contextCall({\n ctx: args.ctx,\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n params: args.params,\n });\n }\n\n // Delegate to the completions provider's context call\n return this.completionsProvider.contextCall({\n ctx: args.ctx,\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n params: args.params,\n });\n }\n\n /**\n * Execute a context-aware streaming call to the OpenAI API, routing to the appropriate API.\n *\n * NOTE: This implementation intentionally duplicates _stream() routing logic rather\n * than delegating. When context-aware tools are implemented, this method will\n * diverge to handle passing context to tools during execution. We keep them\n * separate now to make that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The OpenAI model ID to use (optionally with :completions or :responses suffix)\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.params - Optional additional parameters\n * @returns ContextStreamResponse object for streaming consumption\n */\n protected async _contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n const modelId = args.modelId as OpenAIModelId;\n const apiMode = chooseApiMode(modelId, args.messages);\n\n if (apiMode === \"responses\") {\n return this.responsesProvider.contextStream({\n ctx: args.ctx,\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n params: args.params,\n });\n }\n\n return this.completionsProvider.contextStream({\n ctx: args.ctx,\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n params: args.params,\n });\n }\n\n /**\n * Extract the HTTP status code from an OpenAI API error.\n *\n * @param e - The error to extract the status from\n * @returns The HTTP status code or undefined if not available\n */\n /* v8 ignore start - error handling delegated to completions provider */\n protected getErrorStatus(e: Error): number | undefined {\n // OpenAI SDK uses 'status' property\n return (e as InstanceType<typeof OpenAI.APIError>).status;\n }\n /* v8 ignore stop */\n}\n","/**\n * Together AI provider implementation.\n *\n * Together AI provides an OpenAI-compatible API for hosted LLM inference.\n */\n\nimport { BaseOpenAICompletionsProvider } from \"@/llm/providers/openai/completions/base-provider\";\n\nconst DEFAULT_BASE_URL = \"https://api.together.xyz/v1\";\nconst API_KEY_ENV_VAR = \"TOGETHER_API_KEY\";\n\nexport interface TogetherProviderInit {\n apiKey?: string;\n baseURL?: string;\n}\n\n/**\n * Provider for Together AI's OpenAI-compatible API.\n *\n * Inherits from BaseOpenAICompletionsProvider with Together-specific configuration:\n * - Uses Together AI's API endpoint (https://api.together.xyz/v1)\n * - Requires TOGETHER_API_KEY environment variable\n *\n * @example\n * ```typescript\n * import { registerProvider } from '@mirascope/core/llm';\n *\n * // Register for meta-llama models\n * registerProvider('together', 'meta-llama/');\n *\n * // Now you can use meta-llama models directly\n * const call = defineCall({\n * model: 'meta-llama/Llama-3.3-70B-Instruct-Turbo',\n * fn: () => [user('Hello!')],\n * });\n * ```\n */\nexport class TogetherProvider extends BaseOpenAICompletionsProvider {\n readonly id = \"together\" as const;\n\n /**\n * Create a new Together AI provider instance.\n *\n * @param init - Configuration options\n * @param init.apiKey - API key (defaults to TOGETHER_API_KEY env var)\n * @param init.baseURL - Base URL (defaults to 'https://api.together.xyz/v1')\n */\n constructor(init: TogetherProviderInit = {}) {\n const resolvedApiKey = init.apiKey ?? process.env[API_KEY_ENV_VAR];\n const resolvedBaseUrl = init.baseURL ?? DEFAULT_BASE_URL;\n\n super({\n id: \"together\",\n apiKey: resolvedApiKey,\n baseURL: resolvedBaseUrl,\n });\n }\n}\n","export {\n TogetherProvider,\n type TogetherProviderInit,\n} from \"@/llm/providers/together/provider\";\n","/**\n * Provider registry for managing provider instances.\n *\n * Provides automatic provider resolution based on model ID prefixes.\n */\n\nimport type { BaseProvider } from \"@/llm/providers/base\";\nimport type { ProviderId } from \"@/llm/providers/provider-id\";\n\nimport {\n MissingAPIKeyError,\n NoRegisteredProviderError,\n} from \"@/llm/exceptions\";\nimport { AnthropicProvider } from \"@/llm/providers/anthropic\";\nimport { GoogleProvider } from \"@/llm/providers/google\";\nimport { MirascopeProvider } from \"@/llm/providers/mirascope\";\nimport { OllamaProvider } from \"@/llm/providers/ollama\";\nimport { OpenAIProvider } from \"@/llm/providers/openai/provider\";\nimport { TogetherProvider } from \"@/llm/providers/together\";\n\n/**\n * Global registry mapping scopes to providers.\n * Scopes are matched by prefix (longest match wins).\n */\nconst PROVIDER_REGISTRY: Map<string, BaseProvider> = new Map();\n\n/**\n * Reset the provider registry, clearing all registered providers.\n * Primarily useful for testing.\n */\nexport function resetProviderRegistry(): void {\n PROVIDER_REGISTRY.clear();\n providerCache.clear();\n}\n\n/**\n * Configuration for a provider in the auto-registration fallback chain.\n */\ninterface ProviderDefault {\n providerId: ProviderId;\n apiKeyEnvVar: string | null;\n}\n\n/**\n * Default auto-registration scopes with fallback chains.\n */\nconst DEFAULT_AUTO_REGISTER_SCOPES: Record<string, ProviderDefault[]> = {\n \"anthropic/\": [\n { providerId: \"anthropic\", apiKeyEnvVar: \"ANTHROPIC_API_KEY\" },\n ],\n \"google/\": [{ providerId: \"google\", apiKeyEnvVar: \"GOOGLE_API_KEY\" }],\n \"mirascope/\": [\n { providerId: \"mirascope\", apiKeyEnvVar: \"MIRASCOPE_API_KEY\" },\n ],\n \"ollama/\": [{ providerId: \"ollama\", apiKeyEnvVar: null }],\n \"openai/\": [{ providerId: \"openai\", apiKeyEnvVar: \"OPENAI_API_KEY\" }],\n \"together/\": [{ providerId: \"together\", apiKeyEnvVar: \"TOGETHER_API_KEY\" }],\n};\n\n/**\n * Check if an API key is available for a provider default.\n */\nfunction hasApiKey(defaultConfig: ProviderDefault): boolean {\n /* v8 ignore start - no current providers without API key requirement */\n if (defaultConfig.apiKeyEnvVar === null) {\n return true; // Provider doesn't require API key\n }\n /* v8 ignore stop */\n return process.env[defaultConfig.apiKeyEnvVar] !== undefined;\n}\n\n/**\n * Cache for provider singletons.\n */\nconst providerCache: Map<string, BaseProvider> = new Map();\n\n/**\n * Create a cached provider instance for the specified provider ID.\n * Uses a cache keyed by providerId + apiKey + baseURL for reuse.\n */\nexport function getProviderSingleton(\n providerId: ProviderId,\n options?: { apiKey?: string; baseURL?: string },\n): BaseProvider {\n const cacheKey = `${providerId}:${options?.apiKey ?? \"\"}:${options?.baseURL ?? \"\"}`;\n const cached = providerCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n let provider: BaseProvider;\n switch (providerId) {\n case \"anthropic\":\n provider = new AnthropicProvider({\n apiKey: options?.apiKey,\n baseURL: options?.baseURL,\n });\n break;\n case \"google\":\n provider = new GoogleProvider({\n apiKey: options?.apiKey,\n baseURL: options?.baseURL,\n });\n break;\n case \"mirascope\":\n provider = new MirascopeProvider({\n apiKey: options?.apiKey,\n baseURL: options?.baseURL,\n });\n break;\n case \"ollama\":\n provider = new OllamaProvider({\n apiKey: options?.apiKey,\n baseURL: options?.baseURL,\n });\n break;\n case \"openai\":\n provider = new OpenAIProvider({\n apiKey: options?.apiKey,\n baseURL: options?.baseURL,\n });\n break;\n case \"together\":\n provider = new TogetherProvider({\n apiKey: options?.apiKey,\n baseURL: options?.baseURL,\n });\n break;\n default:\n throw new Error(`Unknown provider: '${providerId}'`);\n }\n\n providerCache.set(cacheKey, provider);\n return provider;\n}\n\n/**\n * Register a provider with scope(s) in the global registry.\n *\n * Scopes use prefix matching on model IDs:\n * - \"anthropic/\" matches \"anthropic/*\"\n * - \"anthropic/claude-sonnet-4\" matches \"anthropic/claude-sonnet-4*\"\n *\n * When multiple scopes match a model_id, the longest match wins.\n *\n * @example\n * ```typescript\n * // Register with default scope\n * registerProvider('anthropic', { apiKey: 'key' });\n *\n * // Register for specific models\n * registerProvider('anthropic', { scope: 'anthropic/claude-sonnet-4' });\n *\n * // Register a custom instance\n * const custom = new AnthropicProvider({ apiKey: 'team-key' });\n * registerProvider(custom, { scope: 'anthropic/claude-sonnet-4' });\n * ```\n */\nexport function registerProvider(\n provider: ProviderId | BaseProvider,\n options?: {\n scope?: string | string[];\n apiKey?: string;\n baseURL?: string;\n },\n): BaseProvider {\n let providerInstance: BaseProvider;\n\n if (typeof provider === \"string\") {\n providerInstance = getProviderSingleton(provider, {\n apiKey: options?.apiKey,\n baseURL: options?.baseURL,\n });\n } else {\n providerInstance = provider;\n }\n\n // Determine scopes to register\n let scopes: string[];\n if (options?.scope) {\n scopes = Array.isArray(options.scope) ? options.scope : [options.scope];\n } else {\n // Use default scope based on provider ID\n scopes = [`${providerInstance.id}/`];\n }\n\n for (const scope of scopes) {\n PROVIDER_REGISTRY.set(scope, providerInstance);\n }\n\n return providerInstance;\n}\n\n/**\n * Get the provider for a model ID based on the registry.\n *\n * Uses longest prefix matching to find the most specific provider for the model.\n * If no explicit registration is found, checks for auto-registration defaults\n * and automatically registers the provider on first use.\n *\n * @param modelId - The full model ID (e.g., \"anthropic/claude-sonnet-4-20250514\").\n * @returns The provider instance registered for this model.\n * @throws NoRegisteredProviderError if no provider scope matches the model ID.\n * @throws MissingAPIKeyError if no provider has its API key set.\n *\n * @example\n * ```typescript\n * // Auto-registration on first use:\n * const provider = getProviderForModel('anthropic/claude-sonnet-4-20250514');\n * // Automatically loads and registers AnthropicProvider for \"anthropic/\"\n * ```\n */\nexport function getProviderForModel(modelId: string): BaseProvider {\n // Try explicit registry first (longest match wins)\n const matchingScopes = [...PROVIDER_REGISTRY.keys()].filter((scope) =>\n modelId.startsWith(scope),\n );\n\n if (matchingScopes.length > 0) {\n /* v8 ignore next 3 - reduce comparison for multiple scope matches, only Anthropic implemented */\n const bestScope = matchingScopes.reduce((a, b) =>\n a.length > b.length ? a : b,\n );\n return PROVIDER_REGISTRY.get(bestScope)!;\n }\n\n // Fall back to auto-registration\n const matchingDefaults = Object.keys(DEFAULT_AUTO_REGISTER_SCOPES).filter(\n (scope) => modelId.startsWith(scope),\n );\n\n if (matchingDefaults.length > 0) {\n /* v8 ignore next 3 - reduce only runs with multiple scope matches, only Anthropic implemented */\n const bestScope = matchingDefaults.reduce((a, b) =>\n a.length > b.length ? a : b,\n );\n const fallbackChain = DEFAULT_AUTO_REGISTER_SCOPES[bestScope]!;\n\n // Try each provider in the fallback chain\n for (const defaultConfig of fallbackChain) {\n if (hasApiKey(defaultConfig)) {\n const provider = getProviderSingleton(defaultConfig.providerId);\n // Register for just this scope\n PROVIDER_REGISTRY.set(bestScope, provider);\n return provider;\n }\n }\n\n // No provider in chain has API key - raise helpful error\n const primary = fallbackChain[0]!;\n throw new MissingAPIKeyError(\n primary.providerId,\n /* v8 ignore next - apiKeyEnvVar always defined for current providers */\n primary.apiKeyEnvVar ?? \"\",\n false,\n );\n }\n\n // No matching scope at all\n throw new NoRegisteredProviderError(modelId);\n}\n","/**\n * The Model class - unified interface for LLM calls.\n */\n\nimport type { Context } from \"@/llm/context\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { Message, UserContent } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models/params\";\nimport type { BaseProvider } from \"@/llm/providers/base\";\nimport type { ModelId } from \"@/llm/providers/model-id\";\nimport type { ProviderId } from \"@/llm/providers/provider-id\";\nimport type { Response } from \"@/llm/responses\";\nimport type { ContextResponse } from \"@/llm/responses/context-response\";\nimport type { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport type { RootResponse } from \"@/llm/responses/root-response\";\nimport type { StreamResponse } from \"@/llm/responses/stream-response\";\nimport type { Tools, ContextTools } from \"@/llm/tools\";\n\nimport { promoteToMessages } from \"@/llm/messages\";\nimport { getProviderForModel } from \"@/llm/providers/registry\";\n\n/**\n * The unified LLM interface that delegates to provider-specific clients.\n *\n * This class provides a consistent interface for interacting with language models\n * from various providers. It handles the common operations like generating responses\n * by delegating to the appropriate provider methods.\n *\n * @example\n * ```typescript\n * import { Model } from 'mirascope/llm';\n *\n * const model = new Model('anthropic/claude-sonnet-4-20250514');\n * const response = await model.call('Hello!');\n * console.log(response.text());\n * ```\n *\n * @example With parameters\n * ```typescript\n * const model = new Model('anthropic/claude-sonnet-4-20250514', {\n * temperature: 0.7,\n * maxTokens: 1000,\n * });\n * const response = await model.call('Write a haiku about coding.');\n * ```\n */\nexport class Model {\n /**\n * The model ID being used (e.g., \"anthropic/claude-sonnet-4-20250514\").\n */\n readonly modelId: ModelId;\n\n /**\n * The default parameters for the model (temperature, maxTokens, etc.).\n */\n readonly params: Params;\n\n /**\n * Initialize the Model with a model ID and optional parameters.\n *\n * @param modelId - The model ID in \"provider/model-name\" format.\n * @param params - Optional parameters for the model.\n * @throws Error if the model ID format is invalid.\n */\n constructor(modelId: ModelId, params: Params = {}) {\n if (!modelId.includes(\"/\")) {\n throw new Error(\n `Invalid model_id format. Expected format: 'provider/model-name' ` +\n `(e.g., 'anthropic/claude-sonnet-4-20250514'). Got: '${modelId}'`,\n );\n }\n this.modelId = modelId;\n this.params = params;\n }\n\n /**\n * The provider being used (e.g., an AnthropicProvider).\n *\n * This property dynamically looks up the provider from the registry based on\n * the current modelId. This allows provider overrides via registerProvider()\n * to take effect even after the model instance is created.\n *\n * @throws NoRegisteredProviderError if no provider is available for the modelId.\n */\n get provider(): BaseProvider {\n return getProviderForModel(this.modelId);\n }\n\n /**\n * The string ID of the provider being used (e.g., \"anthropic\").\n *\n * @throws NoRegisteredProviderError if no provider is available for the modelId.\n */\n get providerId(): ProviderId {\n return this.provider.id;\n }\n\n /**\n * Generate a Response by calling this model's LLM provider.\n *\n * @param content - Content to send to the LLM. Can be a string (converted to user\n * message), UserContent, a sequence of UserContent, or a sequence of Messages\n * for full control.\n * @param options - Optional configuration for the call.\n * @param options.tools - Optional tools to make available to the model.\n * @param options.format - Optional format for structured output.\n * @returns A Response object containing the LLM-generated content.\n *\n * @example Simple string input\n * ```typescript\n * const response = await model.call('What is the capital of France?');\n * console.log(response.text());\n * ```\n *\n * @example With message array\n * ```typescript\n * import { system, user } from 'mirascope/llm/messages';\n *\n * const response = await model.call([\n * system('You are a helpful assistant.'),\n * user('What is the capital of France?'),\n * ]);\n * ```\n *\n * @example With structured output format\n * ```typescript\n * import { defineFormat } from 'mirascope/llm';\n *\n * interface Book { title: string; author: string; }\n * const bookFormat = defineFormat<Book>({ mode: 'tool' });\n *\n * const response = await model.call('Recommend a book', { format: bookFormat });\n * const book = response.parse<Book>();\n * ```\n */\n async call(\n content: UserContent | readonly Message[],\n options?: { tools?: Tools; format?: Format | null },\n ): Promise<Response> {\n const messages = promoteToMessages(content);\n return this.provider.call({\n modelId: this.modelId,\n messages,\n tools: options?.tools,\n format: options?.format,\n params: this.params,\n });\n }\n\n /**\n * Generate a streaming Response by calling this model's LLM provider.\n *\n * @param content - Content to send to the LLM. Can be a string (converted to user\n * message), UserContent, a sequence of UserContent, or a sequence of Messages\n * for full control.\n * @param options - Optional configuration for the stream.\n * @param options.tools - Optional tools to make available to the model.\n * @param options.format - Optional format for structured output.\n * @returns A StreamResponse object for consuming the streamed content.\n *\n * @example Simple string input\n * ```typescript\n * const response = await model.stream('What is the capital of France?');\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n *\n * @example With message array\n * ```typescript\n * import { system, user } from 'mirascope/llm/messages';\n *\n * const response = await model.stream([\n * system('You are a helpful assistant.'),\n * user('What is the capital of France?'),\n * ]);\n *\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n *\n * // After consuming the stream, get the full text\n * console.log(response.text());\n * ```\n *\n * @example With structured streaming\n * ```typescript\n * import { defineFormat } from 'mirascope/llm';\n *\n * interface Book { title: string; author: string; }\n * const bookFormat = defineFormat<Book>({ mode: 'tool' });\n *\n * const response = await model.stream('Recommend a book', { format: bookFormat });\n * for await (const partial of response.structuredStream<Book>()) {\n * console.log('Partial:', partial);\n * }\n * const book = response.parse<Book>();\n * ```\n */\n async stream(\n content: UserContent | readonly Message[],\n options?: { tools?: Tools; format?: Format | null },\n ): Promise<StreamResponse> {\n const messages = promoteToMessages(content);\n return this.provider.stream({\n modelId: this.modelId,\n messages,\n tools: options?.tools,\n format: options?.format,\n params: this.params,\n });\n }\n\n /**\n * Generate a ContextResponse by calling this model's LLM provider with context.\n *\n * This method accepts a context for dependency injection, enabling context-aware\n * tools and prompts.\n *\n * @template DepsT - The type of dependencies in the context.\n * @param ctx - The context containing dependencies for tools.\n * @param content - Content to send to the LLM.\n * @param options - Optional configuration for the call.\n * @param options.tools - Optional tools to make available to the model.\n * @param options.format - Optional format for structured output.\n * @returns A ContextResponse object containing the LLM-generated content.\n *\n * @example\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await model.contextCall(ctx, 'Hello!');\n * console.log(response.text());\n * ```\n */\n async contextCall<DepsT>(\n ctx: Context<DepsT>,\n content: UserContent | readonly Message[],\n options?: { tools?: ContextTools<DepsT>; format?: Format | null },\n ): Promise<ContextResponse<DepsT>> {\n const messages = promoteToMessages(content);\n return this.provider.contextCall({\n ctx,\n modelId: this.modelId,\n messages,\n tools: options?.tools,\n format: options?.format,\n params: this.params,\n });\n }\n\n /**\n * Generate a streaming ContextStreamResponse by calling this model's LLM provider with context.\n *\n * This method accepts a context for dependency injection, enabling context-aware\n * tools and prompts.\n *\n * @template DepsT - The type of dependencies in the context.\n * @param ctx - The context containing dependencies for tools.\n * @param content - Content to send to the LLM.\n * @param options - Optional configuration for the stream.\n * @param options.tools - Optional tools to make available to the model.\n * @param options.format - Optional format for structured output.\n * @returns A ContextStreamResponse object for consuming the streamed content.\n *\n * @example\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await model.contextStream(ctx, 'Hello!');\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n async contextStream<DepsT>(\n ctx: Context<DepsT>,\n content: UserContent | readonly Message[],\n options?: { tools?: ContextTools<DepsT>; format?: Format | null },\n ): Promise<ContextStreamResponse<DepsT>> {\n const messages = promoteToMessages(content);\n return this.provider.contextStream({\n ctx,\n modelId: this.modelId,\n messages,\n tools: options?.tools,\n format: options?.format,\n params: this.params,\n });\n }\n\n // ===== Resume Methods =====\n\n /**\n * Generate a new Response by extending a previous response's messages with additional user content.\n *\n * Uses the previous response's tools and output format, and this model's params.\n *\n * @param response - Previous response to extend.\n * @param content - Additional user content to append.\n * @returns A new Response object containing the extended conversation.\n *\n * @example\n * ```typescript\n * const response = await model.call('Hello!');\n * const followUp = await model.resume(response, 'Tell me more');\n * console.log(followUp.text());\n * ```\n */\n async resume(\n response: RootResponse,\n content: UserContent,\n ): Promise<Response> {\n return this.provider.resume({\n modelId: this.modelId,\n response,\n content,\n params: this.params,\n });\n }\n\n /**\n * Generate a new StreamResponse by extending a previous response's messages with additional user content.\n *\n * Uses the previous response's tools and output format, and this model's params.\n *\n * @param response - Previous response to extend.\n * @param content - Additional user content to append.\n * @returns A new StreamResponse object for consuming the streamed content.\n *\n * @example\n * ```typescript\n * const response = await model.call('Hello!');\n * const followUp = await model.resumeStream(response, 'Tell me more');\n * for await (const text of followUp.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n async resumeStream(\n response: RootResponse,\n content: UserContent,\n ): Promise<StreamResponse> {\n return this.provider.resumeStream({\n modelId: this.modelId,\n response,\n content,\n params: this.params,\n });\n }\n\n /**\n * Generate a new ContextResponse by extending a previous response's messages with additional user content.\n *\n * Uses the previous response's tools and output format, and this model's params.\n *\n * @template DepsT - The type of dependencies in the context.\n * @param ctx - The context containing dependencies for tools.\n * @param response - Previous response to extend.\n * @param content - Additional user content to append.\n * @returns A new ContextResponse object containing the extended conversation.\n *\n * @example\n * ```typescript\n * const response = await model.contextCall(ctx, 'Hello!');\n * const followUp = await model.contextResume(ctx, response, 'Tell me more');\n * console.log(followUp.text());\n * ```\n */\n async contextResume<DepsT>(\n ctx: Context<DepsT>,\n response: RootResponse,\n content: UserContent,\n ): Promise<ContextResponse<DepsT>> {\n return this.provider.contextResume({\n ctx,\n modelId: this.modelId,\n response,\n content,\n params: this.params,\n });\n }\n\n /**\n * Generate a new ContextStreamResponse by extending a previous response's messages with additional user content.\n *\n * Uses the previous response's tools and output format, and this model's params.\n *\n * @template DepsT - The type of dependencies in the context.\n * @param ctx - The context containing dependencies for tools.\n * @param response - Previous response to extend.\n * @param content - Additional user content to append.\n * @returns A new ContextStreamResponse object for consuming the streamed content.\n *\n * @example\n * ```typescript\n * const response = await model.contextStream(ctx, 'Hello!');\n * await response.consume();\n * const followUp = await model.contextResumeStream(ctx, response, 'Tell me more');\n * for await (const text of followUp.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n async contextResumeStream<DepsT>(\n ctx: Context<DepsT>,\n response: RootResponse,\n content: UserContent,\n ): Promise<ContextStreamResponse<DepsT>> {\n return this.provider.contextResumeStream({\n ctx,\n modelId: this.modelId,\n response,\n content,\n params: this.params,\n });\n }\n}\n\n/**\n * Helper for creating a Model instance.\n *\n * This is just an alias for the Model constructor, added for convenience.\n *\n * @param modelId - A model ID string (e.g., \"anthropic/claude-sonnet-4-20250514\").\n * @param params - Optional parameters to configure the model.\n * @returns A Model instance.\n *\n * @example\n * ```typescript\n * import { model } from 'mirascope/llm';\n *\n * const m = model('anthropic/claude-sonnet-4-20250514');\n * const response = await m.call('Hello!');\n * ```\n */\nexport function model(modelId: ModelId, params: Params = {}): Model {\n return new Model(modelId, params);\n}\n","/**\n * Base interface for all LLM responses.\n */\n\nimport type {\n AssistantContentPart,\n Text,\n Thought,\n ToolCall,\n} from \"@/llm/content\";\nimport type { DeepPartial, Format } from \"@/llm/formatting\";\nimport type { Message } from \"@/llm/messages\";\nimport type { Model, Params } from \"@/llm/models\";\nimport type { ModelId, ProviderId } from \"@/llm/providers\";\nimport type { FinishReason } from \"@/llm/responses/finish-reason\";\nimport type { Usage } from \"@/llm/responses/usage\";\n\nimport { ParseError } from \"@/llm/exceptions\";\nimport { extractSerializedJson, parsePartial } from \"@/llm/responses/utils\";\n\n/**\n * Type alias for RootResponse with any format type.\n * Useful for functions that accept any response type.\n */\nexport type AnyResponse = RootResponse<unknown>;\n\n/**\n * Base class for LLM responses.\n *\n * This abstract class defines the core interface that all response types must implement.\n * It provides the common properties and methods shared across all response variants.\n *\n * @template F - The type of the formatted output when using structured outputs.\n */\nexport abstract class RootResponse<F = unknown> {\n /**\n * The raw response from the LLM.\n */\n abstract readonly raw: unknown;\n\n /**\n * The provider that generated this response.\n */\n abstract readonly providerId: ProviderId;\n\n /**\n * The model ID that generated this response.\n */\n abstract readonly modelId: ModelId;\n\n /**\n * Provider-specific model name (may include additional info like API mode).\n */\n abstract readonly providerModelName: string;\n\n /**\n * The parameters used to generate this response.\n */\n abstract readonly params: Params;\n\n /**\n * The message history, including the most recent assistant message.\n */\n abstract readonly messages: readonly Message[];\n\n /**\n * The content generated by the LLM.\n */\n abstract readonly content: readonly AssistantContentPart[];\n\n /**\n * The text content in the generated response, if any.\n */\n abstract readonly texts: readonly Text[];\n\n /**\n * The tools the LLM wants called on its behalf, if any.\n */\n abstract readonly toolCalls: readonly ToolCall[];\n\n /**\n * The readable thoughts from the model's thinking process, if any.\n *\n * The thoughts may be direct output from the model thinking process, or may be a\n * generated summary. (This depends on the provider; newer models tend to summarize.)\n */\n abstract readonly thoughts: readonly Thought[];\n\n /**\n * The reason why the LLM finished generating a response, if set.\n *\n * `finishReason` is only set if the response did not finish generating normally,\n * e.g. `FinishReason.MAX_TOKENS` if the model ran out of tokens before completing.\n * When the response generates normally, `response.finishReason` will be `null`.\n */\n abstract readonly finishReason: FinishReason | null;\n\n /**\n * Token usage statistics for this response, if available.\n */\n abstract readonly usage: Usage | null;\n\n /**\n * The Format describing the structured response format, if available.\n *\n * When a format is specified in the call, this contains the resolved Format\n * with schema and validator information used for parsing.\n */\n abstract readonly format: Format | null;\n\n /**\n * Return all text content from this response as a single string.\n *\n * Joins the text from all `Text` parts in the response content using the\n * specified separator.\n *\n * @param sep - The separator to use when joining multiple text parts.\n * Defaults to newline (\"\\n\").\n * @returns A string containing all text content joined by the separator.\n * Returns an empty string if the response contains no text parts.\n *\n * @example\n * ```typescript\n * response.text() // Join with newlines (default): \"Hello\\nWorld\"\n * response.text(\" \") // Join with spaces: \"Hello World\"\n * response.text(\"\") // Concatenate directly: \"HelloWorld\"\n * ```\n */\n text(sep: string = \"\\n\"): string {\n return this.texts.map((t) => t.text).join(sep);\n }\n\n /**\n * Return a string representation of all response content.\n *\n * The response content will be represented in a way that emphasizes clarity and\n * readability, but may not include all metadata (like thinking signatures or tool\n * call ids), and thus cannot be used to reconstruct the response.\n *\n * @example\n * ```\n * **Thinking:**\n * The user is asking a math problem. I should use the calculator tool.\n *\n * **ToolCall (calculator):** {\"operation\": \"mult\", \"a\": 1337, \"b\": 4242}\n *\n * I am going to use the calculator and answer your question for you!\n * ```\n */\n pretty(): string {\n const parts: string[] = [];\n\n for (const part of this.content) {\n if (part.type === \"text\") {\n parts.push(part.text);\n } else if (part.type === \"tool_call\") {\n parts.push(`**ToolCall (${part.name}):** ${part.args}`);\n } else if (part.type === \"thought\") {\n const indented = part.thought\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n parts.push(`**Thinking:**\\n${indented}`);\n }\n }\n\n return parts.join(\"\\n\\n\");\n }\n\n /**\n * A Model with parameters matching this response.\n *\n * Creates a new Model instance with the same model ID and parameters that\n * were used to generate this response. This is useful for resuming\n * conversations or making follow-up calls with consistent settings.\n *\n * Uses dynamic import to avoid circular dependencies.\n *\n * @returns A Promise resolving to a Model instance configured with this response's model ID and params.\n *\n * @example\n * ```typescript\n * const response = await model.call('Hello!');\n * const sameModel = await response.model;\n * const followUp = await sameModel.call('Tell me more');\n * ```\n */\n get model(): Promise<Model> {\n return (async () => {\n const { Model: ModelClass } = await import(\"@/llm/models/model\");\n return new ModelClass(this.modelId, this.params);\n })();\n }\n\n /**\n * Parse the response with partial parsing enabled (for streaming).\n *\n * Use this during streaming to parse incomplete JSON as it arrives.\n * Returns a DeepPartial version where all fields are optional.\n *\n * @returns The partially parsed response with optional fields.\n *\n * @example\n * ```typescript\n * for await (const chunk of streamResponse.chunkStream()) {\n * const partial = streamResponse.parse({ partial: true });\n * // partial.title may be undefined initially\n * }\n * ```\n */\n parse(options: { partial: true }): DeepPartial<F>;\n\n /**\n * Parse the response according to the response format.\n *\n * If a format was specified in the call, parses the response content\n * according to that format. For JSON-based formats, extracts and parses\n * the JSON. For OutputParser formats, calls the custom parser.\n *\n * When a format is specified, returns the parsed value of type F.\n * When no format is specified (F = unknown), returns null at runtime.\n *\n * @returns The parsed response.\n * @throws ParseError if parsing fails.\n *\n * @example\n * ```typescript\n * interface Book { title: string; author: string; }\n *\n * const response = await model.call<Book>('Recommend a book', {\n * format: BookSchema\n * });\n *\n * const book = response.parse(); // Type: Book\n * console.log(book.title);\n * ```\n */\n parse(options?: { partial?: false }): F;\n\n // Implementation\n parse(options?: { partial?: boolean }): F | DeepPartial<F> | null {\n // No format specified - return null\n if (!this.format) {\n return null;\n }\n\n // Handle OutputParser\n if (this.format.outputParser) {\n if (options?.partial) {\n throw new Error(\n \"parse({ partial: true }) is not supported with OutputParser\",\n );\n }\n try {\n return this.format.outputParser(this) as F;\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n throw new ParseError(`OutputParser failed: ${error.message}`, error);\n }\n }\n\n // Get text content\n const textContent = this.text(\"\");\n\n // Partial parsing for streaming\n if (options?.partial) {\n return parsePartial<DeepPartial<F>>(\n textContent,\n this.format.validator ?? undefined,\n );\n }\n\n // Full parsing\n try {\n const jsonText = extractSerializedJson(textContent);\n const parsed = JSON.parse(jsonText) as F;\n\n // Validate with Zod if validator provided\n if (this.format.validator) {\n const result = this.format.validator.safeParse(parsed);\n if (!result.success) {\n throw new Error(`Validation failed: ${JSON.stringify(result.error)}`);\n }\n return result.data as F;\n }\n\n return parsed;\n } catch (e) {\n /* v8 ignore next -- defensive: JSON.parse always throws Error */\n const error = e instanceof Error ? e : new Error(String(e));\n throw new ParseError(`Failed to parse response: ${error.message}`, error);\n }\n }\n}\n","/**\n * Response class for LLM calls.\n */\n\nimport type { ToolOutput } from \"@/llm/content/tool-output\";\nimport type { UserContent } from \"@/llm/messages\";\nimport type { Jsonable } from \"@/llm/types/jsonable\";\n\nimport {\n BaseResponse,\n type BaseResponseInit,\n} from \"@/llm/responses/base-response\";\nimport { Toolkit, type Tools } from \"@/llm/tools\";\n\n/**\n * Initialization options for creating a Response.\n *\n * Accepts `tools` as either a Toolkit or a list of tools, which gets\n * converted to a Toolkit before passing to BaseResponse.\n */\nexport interface ResponseInit extends Omit<BaseResponseInit, \"toolkit\"> {\n /**\n * The tools available for this response.\n * Can be a Toolkit instance or an array of tools.\n */\n tools?: Tools | Toolkit;\n}\n\n/**\n * The response generated by an LLM.\n *\n * This is the primary response class for non-streaming LLM calls. Since TypeScript\n * IO is always async, this single class handles all async response scenarios.\n *\n * @template F - The type of the formatted output when using structured outputs.\n *\n * @example\n * ```typescript\n * const response = await model.call([user(\"Hello!\")]);\n * console.log(response.text());\n * ```\n *\n * @example With structured output\n * ```typescript\n * interface Book { title: string; author: string; }\n * const response = await model.call<Book>('Recommend a book', { format: BookSchema });\n * const book = response.parse(); // Type: Book | DeepPartial<Book> | null\n * ```\n */\nexport class Response<F = unknown> extends BaseResponse<F> {\n /**\n * Override base toolkit with correct type for execute() support.\n */\n declare readonly toolkit: Toolkit;\n\n constructor(init: ResponseInit) {\n // Convert tools to toolkit (matching Python's pattern)\n const toolkit =\n init.tools instanceof Toolkit\n ? init.tools\n : new Toolkit(init.tools ?? []);\n\n super({ ...init, toolkit });\n }\n\n /**\n * Execute all tool calls in this response using the registered tools.\n *\n * @returns An array of ToolOutput objects, one for each tool call.\n *\n * @example\n * ```typescript\n * const response = await model.call('What is the weather?', [weatherTool]);\n * if (response.toolCalls.length > 0) {\n * const outputs = await response.executeTools();\n * const followUp = await response.resume(outputs);\n * }\n * ```\n */\n async executeTools(): Promise<ToolOutput<Jsonable>[]> {\n return Promise.all(\n this.toolCalls.map((call) => this.toolkit.execute(call)),\n );\n }\n\n /**\n * Generate a new Response using this response's messages with additional user content.\n *\n * Uses this response's tools and format type. Also uses this response's provider,\n * model, and params.\n *\n * @param content - The new user message content to append to the message history.\n * @returns A new Response instance generated from the extended message history.\n *\n * @example\n * ```typescript\n * const response = await model.call('Hello!');\n * console.log(response.text());\n *\n * // Continue the conversation\n * const followUp = await response.resume('Tell me more about that');\n * console.log(followUp.text());\n * ```\n */\n async resume(content: UserContent): Promise<Response<F>> {\n const model = await this.model;\n return model.resume(this, content) as Promise<Response<F>>;\n }\n}\n","/**\n * Response types and utilities for LLM calls.\n */\n\nexport { FinishReason } from \"@/llm/responses/finish-reason\";\nexport type { FinishReason as FinishReasonType } from \"@/llm/responses/finish-reason\";\n\nexport { createUsage, totalTokens } from \"@/llm/responses/usage\";\nexport type { Usage } from \"@/llm/responses/usage\";\n\nexport { RootResponse } from \"@/llm/responses/root-response\";\nexport type { AnyResponse } from \"@/llm/responses/root-response\";\n\nexport { BaseResponse } from \"@/llm/responses/base-response\";\nexport type { BaseResponseInit } from \"@/llm/responses/base-response\";\n\nexport { Response } from \"@/llm/responses/response\";\nexport type { ResponseInit } from \"@/llm/responses/response\";\n\nexport { ContextResponse } from \"@/llm/responses/context-response\";\nexport type { ContextResponseInit } from \"@/llm/responses/context-response\";\n\nexport { BaseStreamResponse } from \"@/llm/responses/base-stream-response\";\nexport type { BaseStreamResponseInit } from \"@/llm/responses/base-stream-response\";\n\nexport { StreamResponse } from \"@/llm/responses/stream-response\";\nexport type { StreamResponseInit } from \"@/llm/responses/stream-response\";\n\nexport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nexport type { ContextStreamResponseInit } from \"@/llm/responses/context-stream-response\";\n\nexport {\n TextStream,\n ThoughtStream,\n ToolCallStream,\n} from \"@/llm/responses/streams\";\nexport type { Stream } from \"@/llm/responses/streams\";\n\nexport { extractSerializedJson, parsePartial } from \"@/llm/responses/utils\";\n\n// Metadata streaming chunk types (content chunks are in content/)\nexport {\n finishReasonChunk,\n usageDeltaChunk,\n rawStreamEventChunk,\n rawMessageChunk,\n} from \"@/llm/responses/chunks\";\n\nexport type {\n FinishReasonChunk,\n UsageDeltaChunk,\n RawStreamEventChunk,\n RawMessageChunk,\n StreamResponseChunk,\n AsyncChunkIterator,\n} from \"@/llm/responses/chunks\";\n","/**\n * Beta Anthropic provider implementation.\n *\n * Uses the beta API (client.beta.messages.create()) which supports\n * additional features like extended thinking and structured outputs.\n */\n\nimport Anthropic from \"@anthropic-ai/sdk\";\n\nimport type { Context } from \"@/llm/context\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { AnthropicModelId } from \"@/llm/providers/anthropic/model-id\";\nimport type { Tools, ContextTools } from \"@/llm/tools\";\n\nimport { getIncludeThoughts } from \"@/llm/providers/_utils\";\nimport {\n ANTHROPIC_ERROR_MAP,\n buildRequestParams,\n} from \"@/llm/providers/anthropic/_utils\";\nimport { betaDecodeResponse } from \"@/llm/providers/anthropic/beta-decode\";\nimport { decodeBetaStream } from \"@/llm/providers/anthropic/beta-decode-stream\";\nimport { modelName } from \"@/llm/providers/anthropic/model-id\";\nimport { BaseProvider } from \"@/llm/providers/base\";\nimport { Response } from \"@/llm/responses\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport { StreamResponse } from \"@/llm/responses/stream-response\";\n\n/**\n * Provider for the Anthropic Beta API.\n *\n * This provider uses the beta messages API which supports additional features\n * like extended thinking and structured outputs. Users opt-in by using the\n * `anthropic-beta/` prefix in their model ID.\n *\n * @example\n * ```typescript\n * const provider = new AnthropicBetaProvider();\n * const response = await provider.call({\n * modelId: 'claude-sonnet-4-20250514',\n * messages: [user('Hello!')],\n * });\n * console.log(response.text());\n * ```\n */\nexport class AnthropicBetaProvider extends BaseProvider {\n readonly id = \"anthropic-beta\" as const;\n protected readonly errorMap = ANTHROPIC_ERROR_MAP;\n\n private readonly client: Anthropic;\n\n /**\n * Create a new Anthropic Beta provider instance.\n *\n * @param init - Configuration options\n * @param init.apiKey - Anthropic API key (defaults to ANTHROPIC_API_KEY env var)\n * @param init.baseURL - Optional custom base URL for the API\n */\n constructor(init: { apiKey?: string; baseURL?: string } = {}) {\n super();\n this.client = new Anthropic({\n apiKey: init.apiKey,\n baseURL: init.baseURL,\n });\n }\n\n /**\n * Execute a call to the Anthropic Beta API.\n *\n * @param args - Call arguments\n * @param args.modelId - The Anthropic model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns Response object containing the API response\n */\n protected async _call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<Response> {\n const modelId = args.modelId as AnthropicModelId;\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.format,\n args.params,\n );\n\n // Use beta API instead of standard\n const betaResponse = await this.client.beta.messages.create(requestParams);\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const { assistantMessage, finishReason, usage } = betaDecodeResponse(\n betaResponse,\n modelId,\n includeThoughts,\n );\n\n return new Response({\n raw: betaResponse,\n // Note: providerId is 'anthropic' (not 'anthropic-beta') to match Python SDK\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n format: args.format ?? null,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a streaming call to the Anthropic Beta API.\n *\n * @param args - Call arguments\n * @param args.modelId - The Anthropic model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns StreamResponse object for streaming consumption\n */\n /* v8 ignore start - beta streaming is feature-gated behind shouldUseBeta() */\n protected _stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<StreamResponse> {\n const modelId = args.modelId as AnthropicModelId;\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.format,\n args.params,\n );\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const stream = this.client.beta.messages.stream(requestParams);\n\n const chunkIterator = decodeBetaStream(stream, includeThoughts);\n\n return Promise.resolve(\n new StreamResponse({\n // Note: providerId is 'anthropic' (not 'anthropic-beta')\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format ?? null,\n inputMessages: args.messages,\n chunkIterator,\n }),\n );\n }\n /* v8 ignore stop */\n\n /**\n * Execute a context-aware call to the Anthropic Beta API.\n *\n * NOTE: This implementation intentionally duplicates _call() rather than delegating.\n * When context-aware tools are implemented, this method will diverge to handle\n * passing context to tools during execution. We keep them separate now to make\n * that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The Anthropic model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns ContextResponse object containing the API response\n */\n /* v8 ignore start - beta context call is feature-gated behind shouldUseBeta() */\n protected async _contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n const modelId = args.modelId as AnthropicModelId;\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.format,\n args.params,\n );\n\n // Use beta API instead of standard\n const betaResponse = await this.client.beta.messages.create(requestParams);\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const { assistantMessage, finishReason, usage } = betaDecodeResponse(\n betaResponse,\n modelId,\n includeThoughts,\n );\n\n return new ContextResponse({\n raw: betaResponse,\n // Note: providerId is 'anthropic' (not 'anthropic-beta') to match Python SDK\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n format: args.format ?? null,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n /* v8 ignore stop */\n\n /**\n * Execute a context-aware streaming call to the Anthropic Beta API.\n *\n * NOTE: This implementation intentionally duplicates _stream() rather than delegating.\n * When context-aware tools are implemented, this method will diverge to handle\n * passing context to tools during execution. We keep them separate now to make\n * that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The Anthropic model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns ContextStreamResponse object for streaming consumption\n */\n /* v8 ignore start - beta context stream is feature-gated behind shouldUseBeta() */\n protected _contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n const modelId = args.modelId as AnthropicModelId;\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.format,\n args.params,\n );\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const stream = this.client.beta.messages.stream(requestParams);\n\n const chunkIterator = decodeBetaStream(stream, includeThoughts);\n\n return Promise.resolve(\n new ContextStreamResponse({\n // Note: providerId is 'anthropic' (not 'anthropic-beta')\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format ?? null,\n inputMessages: args.messages,\n chunkIterator,\n }),\n );\n }\n /* v8 ignore stop */\n\n /**\n * Extract the HTTP status code from an Anthropic API error.\n *\n * @param e - The error to extract the status from\n * @returns The HTTP status code or undefined if not available\n */\n protected getErrorStatus(e: Error): number | undefined {\n // Anthropic SDK uses 'status' property\n return (e as InstanceType<typeof Anthropic.APIError>).status;\n }\n}\n","/**\n * Anthropic stream decoding utilities.\n *\n * Converts Anthropic MessageStreamEvent to Mirascope StreamResponseChunk.\n * The standard Anthropic API supports thinking blocks when extended thinking is enabled.\n */\n\nimport type { MessageStreamEvent } from \"@anthropic-ai/sdk/resources/messages\";\n\nimport type { StreamResponseChunk } from \"@/llm/responses/chunks\";\n\nimport {\n textStart,\n textChunk,\n textEnd,\n thoughtStart,\n thoughtChunk,\n thoughtEnd,\n toolCallStart,\n toolCallChunk,\n toolCallEnd,\n} from \"@/llm/content\";\nimport {\n finishReasonChunk,\n usageDeltaChunk,\n rawStreamEventChunk,\n} from \"@/llm/responses/chunks\";\nimport { FinishReason } from \"@/llm/responses/finish-reason\";\n\n/**\n * State tracking for stream decoding.\n */\ninterface DecodeState {\n /** Index of current content block being streamed */\n currentBlockIndex: number;\n /** Type of current content block */\n currentBlockType: \"text\" | \"thinking\" | \"tool_use\" | null;\n /** ID of current tool call (when currentBlockType is 'tool_use') */\n currentToolId: string | null;\n /** Whether to include thoughts in output */\n includeThoughts: boolean;\n}\n\n/**\n * Create a new decode state for a fresh stream.\n */\nexport function createDecodeState(includeThoughts: boolean): DecodeState {\n return {\n currentBlockIndex: -1,\n currentBlockType: null,\n currentToolId: null,\n includeThoughts,\n };\n}\n\n/**\n * Decode an Anthropic MessageStreamEvent to Mirascope chunks.\n *\n * @param event - The Anthropic stream event\n * @param state - Mutable state tracking current block\n * @returns Array of Mirascope chunks (may be empty or multiple)\n */\nexport function decodeStreamEvent(\n event: MessageStreamEvent,\n state: DecodeState,\n): StreamResponseChunk[] {\n const chunks: StreamResponseChunk[] = [];\n\n // Always emit raw event chunk for debugging/passthrough\n chunks.push(rawStreamEventChunk(event));\n\n switch (event.type) {\n case \"message_start\":\n // Note: We don't emit rawMessageChunk here because event.message contains\n // fields like 'model' and 'id' that aren't valid in resume requests.\n // For streaming, we let rawMessage remain null - the encodeMessages function\n // will encode from content parts instead.\n // Emit initial usage if available\n if (event.message.usage) {\n chunks.push(\n usageDeltaChunk({\n inputTokens: event.message.usage.input_tokens,\n outputTokens: event.message.usage.output_tokens,\n }),\n );\n }\n break;\n\n case \"content_block_start\":\n state.currentBlockIndex = event.index;\n if (event.content_block.type === \"text\") {\n state.currentBlockType = \"text\";\n chunks.push(textStart());\n // If there's initial text, emit it\n /* v8 ignore start - initial text in start event is rare */\n if (event.content_block.text) {\n chunks.push(textChunk(event.content_block.text));\n }\n /* v8 ignore stop */\n } else if (event.content_block.type === \"thinking\") {\n state.currentBlockType = \"thinking\";\n if (state.includeThoughts) {\n chunks.push(thoughtStart());\n // If there's initial thinking text, emit it\n /* v8 ignore start - initial thinking in start event is rare */\n if (event.content_block.thinking) {\n chunks.push(thoughtChunk(event.content_block.thinking));\n }\n /* v8 ignore stop */\n }\n } else if (event.content_block.type === \"tool_use\") {\n state.currentBlockType = \"tool_use\";\n state.currentToolId = event.content_block.id;\n chunks.push(\n toolCallStart(event.content_block.id, event.content_block.name),\n );\n }\n // Note: redacted_thinking blocks not yet supported\n break;\n\n case \"content_block_delta\":\n if (event.delta.type === \"text_delta\") {\n chunks.push(textChunk(event.delta.text));\n } else if (event.delta.type === \"thinking_delta\") {\n if (state.includeThoughts) {\n chunks.push(thoughtChunk(event.delta.thinking));\n }\n } else if (event.delta.type === \"input_json_delta\") {\n if (state.currentToolId) {\n chunks.push(\n toolCallChunk(state.currentToolId, event.delta.partial_json),\n );\n }\n }\n break;\n\n case \"content_block_stop\":\n if (state.currentBlockType === \"text\") {\n chunks.push(textEnd());\n } else if (\n state.currentBlockType === \"thinking\" &&\n state.includeThoughts\n ) {\n chunks.push(thoughtEnd());\n } else if (state.currentBlockType === \"tool_use\" && state.currentToolId) {\n chunks.push(toolCallEnd(state.currentToolId));\n state.currentToolId = null;\n }\n state.currentBlockType = null;\n break;\n\n case \"message_delta\":\n if (event.delta.stop_reason) {\n const finishReason = decodeStopReason(event.delta.stop_reason);\n if (finishReason) {\n chunks.push(finishReasonChunk(finishReason));\n }\n }\n if (event.usage) {\n chunks.push(\n usageDeltaChunk({\n outputTokens: event.usage.output_tokens,\n }),\n );\n }\n break;\n\n case \"message_stop\":\n // Stream complete - no additional chunks needed\n break;\n }\n\n return chunks;\n}\n\n/**\n * Convert Anthropic stop reason to Mirascope FinishReason.\n */\nfunction decodeStopReason(\n stopReason:\n | \"end_turn\"\n | \"max_tokens\"\n | \"stop_sequence\"\n | \"tool_use\"\n | \"refusal\"\n | \"pause_turn\"\n | null,\n): FinishReason | null {\n switch (stopReason) {\n case \"max_tokens\":\n return FinishReason.MAX_TOKENS;\n /* v8 ignore next 2 - refusal is rare and hard to trigger reliably */\n case \"refusal\":\n return FinishReason.REFUSAL;\n case \"end_turn\":\n case \"stop_sequence\":\n case \"tool_use\":\n case \"pause_turn\":\n return null; // Normal completion\n /* v8 ignore start - exhaustive switch default */\n default:\n return null;\n /* v8 ignore stop */\n }\n}\n\n/**\n * Create an async iterator that decodes Anthropic stream events to Mirascope chunks.\n *\n * @param stream - The Anthropic message stream\n * @param includeThoughts - Whether to include thinking blocks as thought chunks\n * @returns Async iterator of Mirascope chunks\n */\nexport async function* decodeStream(\n stream: AsyncIterable<MessageStreamEvent>,\n includeThoughts: boolean,\n): AsyncGenerator<StreamResponseChunk> {\n const state = createDecodeState(includeThoughts);\n\n for await (const event of stream) {\n const chunks = decodeStreamEvent(event, state);\n for (const chunk of chunks) {\n yield chunk;\n }\n }\n}\n","/**\n * Anthropic provider implementation with routing between standard and beta APIs.\n */\n\nimport Anthropic from \"@anthropic-ai/sdk\";\n\nimport type { Context } from \"@/llm/context\";\nimport type { Format } from \"@/llm/formatting\";\nimport type { Message } from \"@/llm/messages\";\nimport type { Params } from \"@/llm/models\";\nimport type { AnthropicModelId } from \"@/llm/providers/anthropic/model-id\";\nimport type { Tools, ContextTools } from \"@/llm/tools\";\n\nimport { getIncludeThoughts } from \"@/llm/providers/_utils\";\nimport {\n ANTHROPIC_ERROR_MAP,\n buildRequestParams,\n decodeResponse,\n} from \"@/llm/providers/anthropic/_utils\";\nimport { AnthropicBetaProvider } from \"@/llm/providers/anthropic/beta-provider\";\nimport { decodeStream } from \"@/llm/providers/anthropic/decode-stream\";\nimport { modelName } from \"@/llm/providers/anthropic/model-id\";\nimport { BaseProvider } from \"@/llm/providers/base\";\nimport { Response } from \"@/llm/responses\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport { StreamResponse } from \"@/llm/responses/stream-response\";\n\n/**\n * Determine whether to use the beta API based on format mode or strict tools.\n *\n * Routes to beta when:\n * - Format mode is \"strict\" (TODO: not yet supported in TypeScript SDK)\n * - Any tools have strict=True (TODO: not yet supported in TypeScript SDK)\n *\n * @param _modelId - The model identifier (unused until strict mode is implemented)\n * @param _params - The request parameters (unused until strict mode is implemented)\n * @returns Whether to use the beta API\n */\nfunction shouldUseBeta(_modelId: AnthropicModelId, _params?: Params): boolean {\n // TODO: Implement when strict mode format and tools are supported\n // Will check:\n // 1. If format resolves to strict mode\n // 2. If any tools have strict=true\n // 3. If model supports strict structured outputs (not in MODELS_WITHOUT_STRICT_STRUCTURED_OUTPUTS)\n return false;\n}\n\n/**\n * Provider for the Anthropic API with intelligent routing between standard and beta APIs.\n *\n * This provider automatically selects the appropriate API based on the request:\n * - Standard API (`client.messages.create()`) for regular requests\n * - Beta API (`client.beta.messages.create()`) for requests requiring strict mode\n *\n * Currently, routing always uses the standard API. Beta API routing will be enabled\n * when strict mode format and tools support is added to the TypeScript SDK.\n *\n * @example\n * ```typescript\n * const provider = new AnthropicProvider();\n * const response = await provider.call({\n * modelId: 'anthropic/claude-sonnet-4-20250514',\n * messages: [user('Hello!')],\n * });\n * console.log(response.text());\n * ```\n */\nexport class AnthropicProvider extends BaseProvider {\n readonly id = \"anthropic\" as const;\n protected readonly errorMap = ANTHROPIC_ERROR_MAP;\n\n private readonly client: Anthropic;\n private readonly betaProvider: AnthropicBetaProvider;\n\n /**\n * Create a new Anthropic provider instance.\n *\n * @param init - Configuration options\n * @param init.apiKey - Anthropic API key (defaults to ANTHROPIC_API_KEY env var)\n * @param init.baseURL - Optional custom base URL for the API\n */\n constructor(init: { apiKey?: string; baseURL?: string } = {}) {\n super();\n this.client = new Anthropic({\n apiKey: init.apiKey,\n baseURL: init.baseURL,\n });\n this.betaProvider = new AnthropicBetaProvider(init);\n }\n\n /**\n * Execute a call to the Anthropic API, routing to beta API if needed.\n *\n * @param args - Call arguments\n * @param args.modelId - The Anthropic model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns Response object containing the API response\n */\n protected async _call(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<Response> {\n const modelId = args.modelId as AnthropicModelId;\n\n // Route to beta provider for strict mode\n /* v8 ignore start - beta routing not yet implemented */\n if (shouldUseBeta(modelId, args.params)) {\n return this.betaProvider.call({\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n format: args.format,\n params: args.params,\n });\n }\n /* v8 ignore stop */\n\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.format,\n args.params,\n );\n\n const anthropicResponse = await this.client.messages.create(requestParams);\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const { assistantMessage, finishReason, usage } = decodeResponse(\n anthropicResponse,\n modelId,\n includeThoughts,\n );\n\n return new Response({\n raw: anthropicResponse,\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format ?? null,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a streaming call to the Anthropic API, routing to beta API if needed.\n *\n * @param args - Call arguments\n * @param args.modelId - The Anthropic model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns StreamResponse object for streaming consumption\n */\n protected async _stream(args: {\n modelId: string;\n messages: readonly Message[];\n tools?: Tools;\n format?: Format | null;\n params?: Params;\n }): Promise<StreamResponse> {\n const modelId = args.modelId as AnthropicModelId;\n\n // Route to beta provider for strict mode\n /* v8 ignore start - beta routing not yet implemented */\n if (shouldUseBeta(modelId, args.params)) {\n return this.betaProvider.stream({\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n format: args.format,\n params: args.params,\n });\n }\n /* v8 ignore stop */\n\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.format,\n args.params,\n );\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const stream = this.client.messages.stream(requestParams);\n\n const chunkIterator = decodeStream(stream, includeThoughts);\n\n return new StreamResponse({\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format ?? null,\n inputMessages: args.messages,\n chunkIterator,\n });\n }\n\n /**\n * Execute a context-aware call to the Anthropic API.\n *\n * NOTE: This implementation intentionally duplicates _call() rather than delegating.\n * When context-aware tools are implemented, this method will diverge to handle\n * passing context to tools during execution. We keep them separate now to make\n * that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The Anthropic model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns ContextResponse object containing the API response\n */\n protected async _contextCall<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextResponse<DepsT>> {\n const modelId = args.modelId as AnthropicModelId;\n\n // Route to beta provider for strict mode\n /* v8 ignore start - beta routing not yet implemented */\n if (shouldUseBeta(modelId, args.params)) {\n return this.betaProvider.contextCall({\n ctx: args.ctx,\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n format: args.format,\n params: args.params,\n });\n }\n /* v8 ignore stop */\n\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.format,\n args.params,\n );\n\n const anthropicResponse = await this.client.messages.create(requestParams);\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const { assistantMessage, finishReason, usage } = decodeResponse(\n anthropicResponse,\n modelId,\n includeThoughts,\n );\n\n return new ContextResponse({\n raw: anthropicResponse,\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format ?? null,\n inputMessages: args.messages,\n assistantMessage,\n finishReason,\n usage,\n });\n }\n\n /**\n * Execute a context-aware streaming call to the Anthropic API.\n *\n * NOTE: This implementation intentionally duplicates _stream() rather than delegating.\n * When context-aware tools are implemented, this method will diverge to handle\n * passing context to tools during execution. We keep them separate now to make\n * that future change clearer.\n *\n * @param args - Call arguments including context and model\n * @param args.modelId - The Anthropic model ID to use\n * @param args.messages - Array of messages to send\n * @param args.tools - Optional tools to make available to the model\n * @param args.format - Optional format for structured output\n * @param args.params - Optional additional parameters\n * @returns ContextStreamResponse object for streaming consumption\n */\n protected async _contextStream<DepsT>(args: {\n ctx: Context<DepsT>;\n modelId: string;\n messages: readonly Message[];\n tools?: ContextTools<DepsT>;\n format?: Format | null;\n params?: Params;\n }): Promise<ContextStreamResponse<DepsT>> {\n const modelId = args.modelId as AnthropicModelId;\n\n // Route to beta provider for strict mode\n /* v8 ignore start - beta routing not yet implemented */\n if (shouldUseBeta(modelId, args.params)) {\n return this.betaProvider.contextStream({\n ctx: args.ctx,\n modelId: args.modelId,\n messages: args.messages,\n tools: args.tools,\n format: args.format,\n params: args.params,\n });\n }\n /* v8 ignore stop */\n\n const requestParams = buildRequestParams(\n modelId,\n args.messages,\n args.tools,\n args.format,\n args.params,\n );\n\n const includeThoughts = getIncludeThoughts(args.params);\n\n const stream = this.client.messages.stream(requestParams);\n\n const chunkIterator = decodeStream(stream, includeThoughts);\n\n return new ContextStreamResponse({\n providerId: \"anthropic\",\n modelId,\n providerModelName: modelName(modelId),\n params: args.params ?? /* v8 ignore next 1 */ {},\n tools: args.tools,\n format: args.format ?? null,\n inputMessages: args.messages,\n chunkIterator,\n });\n }\n\n /**\n * Extract the HTTP status code from an Anthropic API error.\n *\n * @param e - The error to extract the status from\n * @returns The HTTP status code or undefined if not available\n */\n protected getErrorStatus(e: Error): number | undefined {\n // Anthropic SDK uses 'status' property\n return (e as InstanceType<typeof Anthropic.APIError>).status;\n }\n}\n","/**\n * Anthropic provider implementation.\n *\n * The AnthropicProvider handles routing between standard and beta APIs internally.\n * AnthropicBetaProvider is not exported as it's an internal implementation detail.\n */\n\nexport type { AnthropicModelId } from \"@/llm/providers/anthropic/model-id\";\nexport { modelName } from \"@/llm/providers/anthropic/model-id\";\nexport type { AnthropicKnownModels } from \"@/llm/providers/anthropic/model-info\";\nexport {\n ANTHROPIC_KNOWN_MODELS,\n MODELS_WITHOUT_STRICT_STRUCTURED_OUTPUTS,\n} from \"@/llm/providers/anthropic/model-info\";\n\nexport { AnthropicProvider } from \"@/llm/providers/anthropic/provider\";\n","export type { Jsonable } from \"@/llm/types\";\n\nexport type {\n AnthropicModelId,\n GoogleModelId,\n OpenAIModelId,\n ApiMode,\n KnownProviderId,\n ModelId,\n Provider,\n ProviderId,\n} from \"@/llm/providers\";\nexport { KNOWN_PROVIDER_IDS } from \"@/llm/providers\";\n\nexport {\n type Context,\n createContext,\n isContext,\n CONTEXT_MARKER,\n} from \"@/llm/context\";\n\nexport type {\n AssistantContentPart,\n AssistantContentChunk,\n ContentPart,\n UserContentPart,\n} from \"@/llm/content\";\n\nexport type { Text, Thought, ToolCall } from \"@/llm/content\";\n\n// Content chunk types (from content module, like Python)\nexport type {\n TextStartChunk,\n TextChunk,\n TextEndChunk,\n ThoughtStartChunk,\n ThoughtChunk,\n ThoughtEndChunk,\n ToolCallStartChunk,\n ToolCallChunk,\n ToolCallEndChunk,\n} from \"@/llm/content\";\n\n// Content chunk factory functions\nexport {\n textStart,\n textChunk,\n textEnd,\n thoughtStart,\n thoughtChunk,\n thoughtEnd,\n toolCallStart,\n toolCallChunk,\n toolCallEnd,\n} from \"@/llm/content\";\n\nexport {\n Audio,\n type AudioMimeType,\n type Base64AudioSource,\n} from \"@/llm/content\";\n\nexport {\n Document,\n type Base64DocumentSource,\n type DocumentBase64MimeType,\n type DocumentTextMimeType,\n type TextDocumentSource,\n type URLDocumentSource,\n} from \"@/llm/content\";\n\nexport {\n Image,\n type Base64ImageSource,\n type ImageMimeType,\n type URLImageSource,\n} from \"@/llm/content\";\n\nexport { ToolOutput } from \"@/llm/content\";\n\nexport {\n defineTool,\n defineContextTool,\n isZodLike,\n isContextTool,\n Toolkit,\n ContextToolkit,\n createToolkit,\n createContextToolkit,\n TOOL_TYPE,\n CONTEXT_TOOL_TYPE,\n ProviderTool,\n isProviderTool,\n WebSearchTool,\n isWebSearchTool,\n} from \"@/llm/tools\";\n\nexport type {\n JsonSchemaProperty,\n ToolParameterSchema,\n ToolSchema,\n ZodLike,\n InferZod,\n ToolArgs,\n ContextToolArgs,\n ZodToolArgs,\n ZodContextToolArgs,\n BaseTool,\n BaseContextTool,\n Tool,\n ContextTool,\n AnyTool,\n AnyContextTool,\n Tools,\n ContextTools,\n ToolFn,\n ContextToolFn,\n AnyToolFn,\n} from \"@/llm/tools\";\n\nexport type {\n AssistantContent,\n AssistantMessage,\n Message,\n SystemContent,\n SystemMessage,\n UserContent,\n UserMessage,\n} from \"@/llm/messages\";\n\nimport * as messages from \"@/llm/messages\";\nexport { messages };\n\nexport {\n MirascopeError,\n ProviderError,\n APIError,\n AuthenticationError,\n PermissionError,\n BadRequestError,\n NotFoundError,\n RateLimitError,\n ServerError,\n ConnectionError,\n TimeoutError,\n ResponseValidationError,\n ToolError,\n ToolExecutionError,\n ToolNotFoundError,\n ParseError,\n FeatureNotSupportedError,\n NoRegisteredProviderError,\n MissingAPIKeyError,\n} from \"@/llm/exceptions\";\n\nexport type { Params, ThinkingConfig, ThinkingLevel } from \"@/llm/models\";\n\nexport {\n defineFormat,\n defineOutputParser,\n isFormat,\n isOutputParser,\n resolveFormat,\n FORMAT_TOOL_NAME,\n TOOL_MODE_INSTRUCTIONS,\n JSON_MODE_INSTRUCTIONS,\n} from \"@/llm/formatting\";\n\nexport type {\n Format,\n FormatSpec,\n FormattingMode,\n OutputParser,\n OutputParserArgs,\n DeepPartial,\n} from \"@/llm/formatting\";\nexport {\n Model,\n model,\n modelFromContext,\n useModel,\n withModel,\n} from \"@/llm/models\";\n\nexport {\n definePrompt,\n type MessageTemplate,\n type Prompt,\n type PromptArgs,\n type TemplateFunc,\n // Context-aware types (unified API)\n type ContextMessageTemplate,\n type ContextPrompt,\n type ContextPromptArgs,\n type ContextTemplateFunc,\n // Type utilities\n type ExtractDeps,\n type ExtractVars,\n type UnifiedPrompt,\n} from \"@/llm/prompts\";\n\nexport {\n defineCall,\n type Call,\n type CallArgs,\n // Context-aware types (unified API)\n type ContextCall,\n type ContextCallArgs,\n // Type utilities\n type UnifiedCall,\n} from \"@/llm/calls\";\n\nexport {\n getProviderForModel,\n registerProvider,\n resetProviderRegistry,\n} from \"@/llm/providers\";\n\nexport {\n FinishReason,\n RootResponse,\n BaseResponse,\n Response,\n ContextResponse,\n StreamResponse,\n ContextStreamResponse,\n createUsage,\n totalTokens,\n} from \"@/llm/responses\";\nexport type { AnyResponse } from \"@/llm/responses\";\nexport type {\n FinishReasonType,\n Usage,\n BaseResponseInit,\n ResponseInit,\n ContextResponseInit,\n StreamResponseInit,\n ContextStreamResponseInit,\n // Metadata streaming chunk types (content chunks exported from content above)\n FinishReasonChunk,\n UsageDeltaChunk,\n RawStreamEventChunk,\n RawMessageChunk,\n StreamResponseChunk,\n AsyncChunkIterator,\n} from \"@/llm/responses\";\n","/**\n * Identifiers for all registered providers.\n */\n\n/**\n * Array of known provider IDs for runtime checks.\n */\nexport const KNOWN_PROVIDER_IDS = [\n \"anthropic\",\n \"google\",\n \"mirascope\",\n \"ollama\",\n \"openai\",\n \"together\",\n] as const;\n\n/**\n * Known provider identifiers.\n */\nexport type KnownProviderId = (typeof KNOWN_PROVIDER_IDS)[number];\n\n/**\n * Provider identifier.\n *\n * Can be a known provider or any custom string for extensibility.\n */\nexport type ProviderId = KnownProviderId | (string & {});\n","/**\n * Interfaces for LLM providers.\n */\n\nexport type { AnthropicModelId } from \"@/llm/providers/anthropic\";\nexport type { GoogleModelId } from \"@/llm/providers/google\";\nexport type { OpenAIModelId, ApiMode } from \"@/llm/providers/openai\";\nexport type { ModelId } from \"@/llm/providers/model-id\";\nexport type { KnownProviderId, ProviderId } from \"@/llm/providers/provider-id\";\nexport { KNOWN_PROVIDER_IDS } from \"@/llm/providers/provider-id\";\n\n// Base provider\nexport { BaseProvider } from \"@/llm/providers/base\";\nexport type { Provider, ProviderErrorMap } from \"@/llm/providers/base\";\n\nexport { AnthropicProvider } from \"@/llm/providers/anthropic\";\n\n// Google provider\nexport { GoogleProvider } from \"@/llm/providers/google\";\n\n// Mirascope provider\nexport { MirascopeProvider } from \"@/llm/providers/mirascope\";\n\n// Ollama provider\nexport { OllamaProvider } from \"@/llm/providers/ollama\";\n\n// Together provider\nexport { TogetherProvider } from \"@/llm/providers/together\";\n\n// OpenAI provider\nexport {\n OpenAIProvider,\n OpenAICompletionsProvider,\n} from \"@/llm/providers/openai\";\n\n// Provider registry\nexport {\n getProviderForModel,\n getProviderSingleton,\n registerProvider,\n resetProviderRegistry,\n} from \"@/llm/providers/registry\";\n","/**\n * Context for LLM calls with dependency injection.\n *\n * Context allows you to pass dependencies (like database connections, user info,\n * configuration, etc.) through to your prompts and tools in a type-safe way.\n */\n\n/**\n * Symbol marker used to identify Context objects at runtime.\n * This enables reliable detection of Context instances in unified call/prompt functions.\n */\nexport const CONTEXT_MARKER = Symbol(\"mirascope.Context\");\n\n/**\n * Context for LLM calls with dependency injection.\n *\n * @template DepsT - The type of dependencies contained in the context.\n *\n * @example\n * ```typescript\n * interface MyDeps {\n * userId: string;\n * db: Database;\n * }\n *\n * const ctx = createContext<MyDeps>({ userId: '123', db: myDb });\n * const response = await myPrompt(model, ctx, { greeting: 'Hello' });\n * ```\n */\nexport interface Context<DepsT> {\n /**\n * Marker property for runtime Context detection.\n * @internal\n */\n readonly [CONTEXT_MARKER]: true;\n\n /**\n * The dependencies available in this context.\n */\n readonly deps: DepsT;\n}\n\n/**\n * Type guard to check if a value is a Context object.\n *\n * @param value - The value to check.\n * @returns True if the value is a Context, false otherwise.\n *\n * @example\n * ```typescript\n * const maybeCtx = getArgument();\n * if (isContext(maybeCtx)) {\n * console.log(maybeCtx.deps); // TypeScript knows this is a Context\n * }\n * ```\n */\nexport function isContext(value: unknown): value is Context<unknown> {\n return value !== null && typeof value === \"object\" && CONTEXT_MARKER in value;\n}\n\n/**\n * Create a context with the given dependencies.\n *\n * @template DepsT - The type of dependencies.\n * @param deps - The dependencies to include in the context.\n * @returns A Context containing the provided dependencies.\n *\n * @example\n * ```typescript\n * interface MyDeps {\n * userId: string;\n * db: Database;\n * }\n *\n * const ctx = createContext<MyDeps>({ userId: '123', db: myDb });\n * ```\n */\nexport function createContext<DepsT>(deps: DepsT): Context<DepsT> {\n return { [CONTEXT_MARKER]: true as const, deps };\n}\n","/**\n * Model types and utilities.\n */\n\nexport type {\n ThinkingConfig,\n ThinkingLevel,\n} from \"@/llm/models/thinking-config\";\nexport type { Params } from \"@/llm/models/params\";\nexport { Model, model } from \"@/llm/models/model\";\nexport {\n modelFromContext,\n useModel,\n withModel,\n} from \"@/llm/models/model-context\";\n","/**\n * Model context management for runtime model switching.\n *\n * This module provides a way to set a model context that overrides\n * the default model in `defineCall` and `definePrompt`, similar to\n * Python's `with llm.model(...):` context manager.\n *\n * ## Cross-Platform Implementation\n *\n * - **Node.js**: Uses native `AsyncLocalStorage` from `async_hooks` for proper\n * async context propagation. This handles concurrent async operations correctly.\n *\n * - **Browser**: Uses a stack-based fallback. This works correctly for:\n * - Synchronous code\n * - Sequential async/await chains\n * - Nested `withModel` calls (as long as they are sequential)\n *\n * ## Browser Limitations\n *\n * The browser fallback has a known limitation with **concurrent** async operations:\n *\n * ```typescript\n * // WARNING: In browsers, this may have unexpected behavior:\n * await Promise.all([\n * llm.withModel(modelA, async () => { await call(); }), // May see modelB!\n * llm.withModel(modelB, async () => { await call(); }), // May see modelA!\n * ]);\n * ```\n *\n * This is because the browser lacks a native async context mechanism. The stack\n * can become interleaved when multiple async operations run concurrently.\n *\n * ## Future: TC39 AsyncContext Proposal\n *\n * The TC39 \"Async Context\" proposal (https://github.com/tc39/proposal-async-context)\n * aims to bring `AsyncLocalStorage`-like functionality to all JavaScript environments.\n * Once this proposal is standardized and widely supported, we can update the browser\n * implementation to use native async context, eliminating the concurrent operation\n * limitation.\n *\n * @see https://github.com/tc39/proposal-async-context\n *\n * @example\n * ```typescript\n * const call = llm.defineCall({\n * model: llm.model(\"openai/gpt-4o\"),\n * template: () => \"Hello\"\n * });\n *\n * // Without context - uses default model\n * await call();\n *\n * // With context - overrides default\n * await llm.withModel(llm.model(\"anthropic/claude-sonnet-4-0\"), async () => {\n * await call(); // Uses Claude\n * });\n * ```\n */\n\nimport type { Params } from \"@/llm/models/params\";\nimport type { ModelId } from \"@/llm/providers/model-id\";\n\nimport { Model } from \"@/llm/models/model\";\n\n/**\n * Cross-platform context storage interface.\n * Abstracts over Node.js AsyncLocalStorage and browser fallback.\n * @internal Exported for testing purposes only\n */\nexport interface ContextStorage<T> {\n get(): T | undefined;\n run<R>(value: T, fn: () => R): R;\n}\n\n/**\n * Node.js implementation using AsyncLocalStorage.\n * Provides proper async context propagation across async/await boundaries.\n */\nfunction createNodeStorage<T>(): ContextStorage<T> {\n // Dynamic require to avoid issues in browser bundlers\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { AsyncLocalStorage } = require(\"node:async_hooks\") as {\n AsyncLocalStorage: new <T>() => {\n getStore(): T | undefined;\n run<R>(store: T, callback: () => R): R;\n };\n };\n const storage = new AsyncLocalStorage<T>();\n return {\n get: () => storage.getStore(),\n run: <R>(value: T, fn: () => R): R => storage.run(value, fn),\n };\n}\n\n/**\n * Browser fallback using a stack.\n *\n * **Limitations**: This implementation works correctly for sequential async operations\n * but does NOT properly isolate concurrent async operations. When multiple `withModel`\n * calls run in parallel via `Promise.all`, their contexts may become interleaved.\n *\n * This is a fundamental limitation of any JavaScript-based solution without native\n * async context support. The TC39 AsyncContext proposal will solve this when available.\n *\n * @see https://github.com/tc39/proposal-async-context\n * @internal Exported for testing purposes only\n */\nexport function createBrowserStorage<T>(): ContextStorage<T> {\n const stack: T[] = [];\n return {\n get: () => stack[stack.length - 1],\n run: <R>(value: T, fn: () => R): R => {\n stack.push(value);\n try {\n const result = fn();\n // Handle promises to ensure cleanup after async completion\n if (result instanceof Promise) {\n return result.finally(() => {\n stack.pop();\n }) as R;\n }\n stack.pop();\n return result;\n } catch (e) {\n stack.pop();\n throw e;\n }\n },\n };\n}\n\n/**\n * Auto-detect environment and create appropriate storage.\n * @internal Exported for testing purposes only\n */\nexport function createStorage<T>(): ContextStorage<T> {\n try {\n return createNodeStorage<T>();\n /* v8 ignore start - browser fallback only hit when AsyncLocalStorage unavailable */\n } catch {\n // This branch is only hit in browser environments where AsyncLocalStorage\n // is unavailable. Since tests run in Node.js, this is tested indirectly\n // through createBrowserStorage tests.\n return createBrowserStorage<T>();\n }\n /* v8 ignore stop */\n}\n\n// Initialize the model storage\nconst modelStorage = createStorage<Model>();\n\n/**\n * Get the model currently set via context, if any.\n *\n * @returns The current context model, or undefined if none is set.\n *\n * @example\n * ```typescript\n * await llm.withModel(llm.model(\"anthropic/claude-sonnet-4-0\"), async () => {\n * const model = llm.modelFromContext();\n * console.log(model?.modelId); // \"anthropic/claude-sonnet-4-0\"\n * });\n *\n * const outsideModel = llm.modelFromContext(); // undefined\n * ```\n */\nexport function modelFromContext(): Model | undefined {\n return modelStorage.get();\n}\n\n/**\n * Execute a function with a model set in context.\n *\n * All calls to `defineCall` and `definePrompt` within the callback\n * will use the context model instead of their default model.\n *\n * @param model - The model to set in context (Model instance or model ID string).\n * @param paramsOrFn - Either params object (if using string model ID) or the function to execute.\n * @param fn - The function to execute (if params were provided).\n * @returns The return value of the function.\n *\n * @example With Model instance\n * ```typescript\n * const response = await llm.withModel(llm.model(\"openai/gpt-4o\"), async () => {\n * return await call();\n * });\n * ```\n *\n * @example With model ID string\n * ```typescript\n * const response = await llm.withModel(\"openai/gpt-4o\", async () => {\n * return await call();\n * });\n * ```\n *\n * @example With model ID and params\n * ```typescript\n * const response = await llm.withModel(\"anthropic/claude-sonnet-4-0\", { temperature: 0.9 }, async () => {\n * return await call();\n * });\n * ```\n *\n * @example Nested contexts\n * ```typescript\n * await llm.withModel(\"anthropic/claude-sonnet-4-0\", async () => {\n * const model1 = llm.modelFromContext(); // Claude\n *\n * await llm.withModel(\"openai/gpt-4o\", async () => {\n * const model2 = llm.modelFromContext(); // GPT-4o\n * });\n *\n * const model3 = llm.modelFromContext(); // Claude (restored)\n * });\n * ```\n */\nexport function withModel<T>(model: Model, fn: () => T): T;\nexport function withModel<T>(modelId: ModelId, fn: () => T): T;\nexport function withModel<T>(modelId: ModelId, params: Params, fn: () => T): T;\nexport function withModel<T>(\n modelOrId: Model | ModelId,\n paramsOrFn: Params | (() => T),\n fn?: () => T,\n): T {\n let resolvedModel: Model;\n let resolvedFn: () => T;\n\n if (typeof modelOrId === \"string\") {\n // String model ID\n if (typeof paramsOrFn === \"function\") {\n // withModel(modelId, fn)\n resolvedModel = new Model(modelOrId);\n resolvedFn = paramsOrFn;\n } else {\n // withModel(modelId, params, fn)\n resolvedModel = new Model(modelOrId, paramsOrFn);\n resolvedFn = fn!;\n }\n } else {\n // Model instance\n resolvedModel = modelOrId;\n resolvedFn = paramsOrFn as () => T;\n }\n\n return modelStorage.run(resolvedModel, resolvedFn);\n}\n\n/**\n * Get the model from context if available, otherwise use the provided model.\n *\n * This function implements the fallback pattern:\n * 1. If a model is set in context, return it (context takes precedence)\n * 2. Otherwise, if a Model instance is provided, return it\n * 3. Otherwise, if a string model ID is provided, create a new Model\n *\n * @param modelOrId - A Model instance or model ID string.\n * @param params - Optional parameters when creating a new Model from string ID.\n * @returns The resolved Model instance.\n *\n * @example\n * ```typescript\n * // Outside context - returns the provided model\n * const model1 = llm.useModel(\"openai/gpt-4o\"); // Creates new Model\n *\n * // Inside context - returns context model\n * await llm.withModel(llm.model(\"anthropic/claude-sonnet-4-0\"), async () => {\n * const model2 = llm.useModel(\"openai/gpt-4o\"); // Returns Claude model\n * });\n * ```\n */\nexport function useModel(model: Model | ModelId, params?: Params): Model {\n const contextModel = modelFromContext();\n if (contextModel !== undefined) {\n return contextModel;\n }\n if (typeof model === \"string\") {\n return new Model(model, params);\n }\n return model;\n}\n","/**\n * Prompt definition and creation utilities.\n *\n * This module provides a unified `definePrompt` function that automatically\n * detects whether a prompt is context-aware based on the template type parameter.\n * If T includes `ctx: Context<DepsT>`, a ContextPrompt is returned; otherwise\n * a regular Prompt is returned.\n */\n\nimport type { Message, UserContent } from \"@/llm/messages\";\nimport type { ModelId } from \"@/llm/providers/model-id\";\nimport type { Response } from \"@/llm/responses\";\nimport type { StreamResponse } from \"@/llm/responses/stream-response\";\nimport type { ContextTools, Tools, ZodLike } from \"@/llm/tools\";\nimport type { NoVars } from \"@/llm/types\";\n\nimport { type Context, isContext } from \"@/llm/context\";\nimport {\n resolveFormat,\n type AnyFormatInput,\n type ExtractFormatType,\n type FormatInput,\n type Format,\n type FormatSpec,\n type OutputParser,\n} from \"@/llm/formatting\";\nimport { promoteToMessages } from \"@/llm/messages\";\nimport { Model, useModel } from \"@/llm/models\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\n\n// ============================================================================\n// Type Utilities for Context Detection\n// ============================================================================\n\n/**\n * Extract DepsT from T if T has a `ctx: Context<DepsT>` property.\n * Returns `never` if T doesn't have a context property.\n */\nexport type ExtractDeps<T> = T extends { ctx: Context<infer D> } ? D : never;\n\n/**\n * Extract the variables type from T by removing the `ctx` property.\n */\nexport type ExtractVars<T> = Omit<T, \"ctx\">;\n\n// ============================================================================\n// Template Types\n// ============================================================================\n\n/**\n * A template function that generates message content from variables.\n *\n * @template T - The type of variables the template accepts.\n */\nexport type MessageTemplate<T> = (vars: T) => UserContent | readonly Message[];\n\n/**\n * Template function type - either takes no args or takes vars of type T.\n */\nexport type TemplateFunc<T> =\n | (() => UserContent | readonly Message[])\n | ((vars: T) => UserContent | readonly Message[]);\n\n/**\n * The combined context and variables object passed to context template functions.\n *\n * @template T - The type of variables the template accepts.\n * @template DepsT - The type of dependencies in the context.\n */\nexport type ContextMessageTemplate<T, DepsT> = { ctx: Context<DepsT> } & T;\n\n/**\n * Context template function type - takes an object with ctx and vars.\n *\n * @template T - The type of variables the template accepts.\n * @template DepsT - The type of dependencies in the context.\n */\nexport type ContextTemplateFunc<T, DepsT> = (\n args: ContextMessageTemplate<T, DepsT>,\n) => UserContent | readonly Message[];\n\n// ============================================================================\n// Prompt Args Types\n// ============================================================================\n\n/**\n * Arguments for defining a prompt.\n *\n * @template T - The type of variables the template accepts. Defaults to NoVars.\n * @template F - The format input type. The output type F is derived via ExtractFormatType<F>.\n */\nexport interface PromptArgs<T = NoVars, F extends AnyFormatInput = undefined> {\n /** Optional tools to make available to the model. */\n tools?: Tools;\n /**\n * Optional format specification for structured output.\n * Can be a Zod schema, Format, FormatSpec, or OutputParser.\n * The output type is automatically inferred from this format.\n */\n format?: F;\n /** A function that generates message content (optionally from variables). */\n template: TemplateFunc<T>;\n}\n\n/**\n * Arguments for defining a context-aware prompt.\n * Used when T includes `ctx: Context<DepsT>`.\n *\n * @template T - The full template parameter type including ctx.\n * @template F - The format input type.\n */\nexport interface ContextPromptArgs<\n T = NoVars,\n F extends AnyFormatInput = undefined,\n> {\n /** Optional tools to make available to the model. */\n tools?: ExtractDeps<T> extends never ? Tools : ContextTools<ExtractDeps<T>>;\n /**\n * Optional format specification for structured output.\n * Can be a Zod schema, Format, FormatSpec, or OutputParser.\n */\n format?: F;\n /** A function that generates message content from context (and optionally variables). */\n template: TemplateFunc<T>;\n}\n\n// ============================================================================\n// Prompt Interface (Non-Context)\n// ============================================================================\n\n/**\n * A prompt that can be called with a model to generate a response.\n *\n * Created by `definePrompt()`. The prompt is callable and also has a\n * `messages()` method for getting the raw messages without calling the LLM.\n *\n * @template T - The type of variables the prompt accepts. Defaults to empty object.\n * @template F - The format input type. The output type F is derived via ExtractFormatType<F>.\n *\n * @example With variables\n * ```typescript\n * const recommendBook = definePrompt<{ genre: string }>({\n * template: ({ genre }) => `Recommend a ${genre} book`,\n * });\n *\n * const response = await recommendBook(model, { genre: 'fantasy' });\n * const messages = recommendBook.messages({ genre: 'fantasy' });\n * ```\n *\n * @example Without variables\n * ```typescript\n * const sayHello = definePrompt({\n * template: () => 'Hello!',\n * });\n * const response = await sayHello(model);\n * ```\n */\nexport interface Prompt<T = NoVars, F extends AnyFormatInput = undefined> {\n /**\n * Call the prompt with a model and variables to generate a response.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n (\n model: Model | ModelId,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<Response<ExtractFormatType<F>>>;\n\n /**\n * Call the prompt with a model and variables to generate a response.\n * This is the method form of the callable interface.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n call(\n model: Model | ModelId,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<Response<ExtractFormatType<F>>>;\n\n /**\n * Stream the prompt with a model and variables to generate a streaming response.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the streaming LLM response.\n *\n * @example\n * ```typescript\n * const response = await prompt.stream(model, { genre: 'fantasy' });\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n stream(\n model: Model | ModelId,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<StreamResponse<ExtractFormatType<F>>>;\n\n /**\n * Get the messages for this prompt without calling the LLM.\n *\n * @param vars - The variables to pass to the template.\n * @returns The messages that would be sent to the LLM.\n */\n messages(...args: keyof T extends never ? [] : [vars: T]): readonly Message[];\n\n /**\n * The tools available to this prompt.\n */\n readonly tools: Tools | undefined;\n\n /**\n * The format specification for structured output, if any.\n */\n readonly format: FormatInput<ExtractFormatType<F>>;\n\n /**\n * The underlying template function.\n */\n readonly template: TemplateFunc<T>;\n}\n\n// ============================================================================\n// Context Prompt Interface\n// ============================================================================\n\n/**\n * A context-aware prompt that can be called with a model and context to generate a response.\n *\n * Created by `definePrompt()` when the template type includes `ctx: Context<DepsT>`.\n * The prompt is callable and also has a `messages()` method for getting the raw messages.\n *\n * @template T - The type of variables the prompt accepts. Defaults to empty object.\n * @template DepsT - The type of dependencies in the context.\n * @template F - The format input type. The output type is derived via ExtractFormatType<F>.\n *\n * @example With variables\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = definePrompt<{ ctx: Context<MyDeps>; greeting: string }>({\n * template: ({ ctx, greeting }) => `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(model, ctx, { greeting: 'Hello' });\n * const messages = greetUser.messages(ctx, { greeting: 'Hello' });\n * ```\n *\n * @example Without variables\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const sayHello = definePrompt<{ ctx: Context<MyDeps> }>({\n * template: ({ ctx }) => `Hello, user ${ctx.deps.userId}!`,\n * });\n *\n * const response = await sayHello(model, ctx);\n * ```\n */\nexport interface ContextPrompt<\n T = NoVars,\n DepsT = unknown,\n F extends AnyFormatInput = undefined,\n> {\n /**\n * Call the prompt with a model, context, and variables to generate a response.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n (\n model: Model | ModelId,\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Call the prompt with a model, context, and variables to generate a response.\n * This is the method form of the callable interface.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n call(\n model: Model | ModelId,\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Stream the prompt with a model, context, and variables to generate a streaming response.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the streaming LLM response.\n *\n * @example\n * ```typescript\n * const response = await prompt.stream(model, ctx, { greeting: 'Hello' });\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n stream(\n model: Model | ModelId,\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextStreamResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Get the messages for this prompt without calling the LLM.\n *\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns The messages that would be sent to the LLM.\n */\n messages(\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): readonly Message[];\n\n /**\n * The tools available to this prompt.\n */\n readonly tools: ContextTools<DepsT> | undefined;\n\n /**\n * The format specification for structured output, if any.\n */\n readonly format:\n | Format<ExtractFormatType<F>>\n | FormatSpec<ExtractFormatType<F>>\n | ZodLike\n | OutputParser<ExtractFormatType<F>>\n | null\n | undefined;\n\n /**\n * The underlying template function.\n */\n readonly template: ContextTemplateFunc<T, DepsT>;\n}\n\n// ============================================================================\n// Unified Prompt Type\n// ============================================================================\n\n/**\n * Unified prompt type that returns either Prompt or ContextPrompt\n * based on whether T includes `ctx: Context<DepsT>`.\n */\nexport type UnifiedPrompt<T, F extends AnyFormatInput = undefined> =\n ExtractDeps<T> extends never\n ? Prompt<T, F>\n : ContextPrompt<ExtractVars<T>, ExtractDeps<T>, F>;\n\n// ============================================================================\n// definePrompt Function Overloads\n// ============================================================================\n\n/**\n * Define a prompt that automatically detects context from the template type.\n *\n * When T includes `ctx: Context<DepsT>`, returns a ContextPrompt.\n * Otherwise returns a regular Prompt.\n *\n * @template T - The type of the template parameter (including ctx if context-aware).\n * @template F - The format input type. The output type is derived via ExtractFormatType<F>.\n * @param args - The prompt arguments including the template.\n * @returns A callable prompt (context-aware if T includes ctx).\n *\n * @example Prompt without variables\n * ```typescript\n * const sayHello = definePrompt({\n * template: () => 'Hello!',\n * });\n * const response = await sayHello(model);\n * ```\n *\n * @example Regular prompt with variables\n * ```typescript\n * const recommendBook = definePrompt<{ genre: string }>({\n * template: ({ genre }) => `Recommend a ${genre} book`,\n * });\n * const response = await recommendBook(model, { genre: 'fantasy' });\n * ```\n *\n * @example Context-aware prompt\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = definePrompt<{ ctx: Context<MyDeps>; greeting: string }>({\n * template: ({ ctx, greeting }) => `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(model, ctx, { greeting: 'Hello' });\n * ```\n */\nexport function definePrompt<\n T extends Record<string, unknown> = NoVars,\n F extends AnyFormatInput = undefined,\n>(args: PromptArgs<T, F> | ContextPromptArgs<T, F>): UnifiedPrompt<T, F>;\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n// Implementation\nexport function definePrompt<T, F extends AnyFormatInput>({\n tools,\n format,\n template,\n}: PromptArgs<T, F> | ContextPromptArgs<T, F>): UnifiedPrompt<T, F> {\n // Resolve format at definition time (uses 'tool' as default mode)\n const resolvedFormat = resolveFormat(format, \"tool\");\n\n // Create messages function that handles both context and non-context cases\n const messagesImpl = (...args: unknown[]): readonly Message[] => {\n const firstArg = args[0];\n\n // Check if first argument is a Context\n if (isContext(firstArg)) {\n // Context case: first arg is ctx, second is vars\n const ctx = firstArg;\n const vars = args[1] as ExtractVars<T> | undefined;\n const templateArgs = { ctx, ...vars } as T;\n const content =\n template.length === 0\n ? (template as () => UserContent | readonly Message[])()\n : (template as (args: T) => UserContent | readonly Message[])(\n templateArgs,\n );\n return promoteToMessages(content);\n } else {\n // Non-context case: first arg is vars (or undefined)\n const vars = firstArg as T | undefined;\n const content =\n template.length === 0\n ? (template as () => UserContent | readonly Message[])()\n : (template as (vars: T) => UserContent | readonly Message[])(\n vars as T,\n );\n return promoteToMessages(content);\n }\n };\n\n // Create call function\n const callImpl = async (\n ...args: unknown[]\n ): Promise<\n | Response<ExtractFormatType<F>>\n | ContextResponse<unknown, ExtractFormatType<F>>\n > => {\n const modelArg = args[0] as Model | ModelId;\n const secondArg = args[1];\n\n if (isContext(secondArg)) {\n // Context case: call(model, ctx, vars?)\n const ctx = secondArg;\n const vars = args[2] as ExtractVars<T> | undefined;\n const msgs = messagesImpl(ctx, vars);\n return useModel(modelArg).contextCall(ctx, msgs, {\n tools: tools as ContextTools<unknown>,\n format: resolvedFormat,\n }) as Promise<ContextResponse<unknown, ExtractFormatType<F>>>;\n } else {\n // Non-context case: call(model, vars?)\n const vars = secondArg as T | undefined;\n const msgs = messagesImpl(vars);\n return useModel(modelArg).call(msgs, {\n tools: tools as Tools,\n format: resolvedFormat,\n }) as Promise<Response<ExtractFormatType<F>>>;\n }\n };\n\n // Create callable wrapper\n const callable = async (\n ...args: unknown[]\n ): Promise<\n | Response<ExtractFormatType<F>>\n | ContextResponse<unknown, ExtractFormatType<F>>\n > => {\n return callImpl(...args);\n };\n\n // Create stream function\n const streamImpl = async (\n ...args: unknown[]\n ): Promise<\n | StreamResponse<ExtractFormatType<F>>\n | ContextStreamResponse<unknown, ExtractFormatType<F>>\n > => {\n const modelArg = args[0] as Model | ModelId;\n const secondArg = args[1];\n\n if (isContext(secondArg)) {\n // Context case: stream(model, ctx, vars?)\n const ctx = secondArg;\n const vars = args[2] as ExtractVars<T> | undefined;\n const msgs = messagesImpl(ctx, vars);\n return useModel(modelArg).contextStream(ctx, msgs, {\n tools: tools as ContextTools<unknown>,\n format: resolvedFormat,\n }) as Promise<ContextStreamResponse<unknown, ExtractFormatType<F>>>;\n } else {\n // Non-context case: stream(model, vars?)\n const vars = secondArg as T | undefined;\n const msgs = messagesImpl(vars);\n return useModel(modelArg).stream(msgs, {\n tools: tools as Tools,\n format: resolvedFormat,\n }) as Promise<StreamResponse<ExtractFormatType<F>>>;\n }\n };\n\n return Object.assign(callable, {\n call: callImpl,\n stream: streamImpl,\n messages: messagesImpl,\n tools,\n format,\n template,\n }) as UnifiedPrompt<T, F>;\n}\n","/**\n * Call definition and creation utilities.\n *\n * A Call is a Prompt with a bundled Model - it can be invoked directly\n * without passing a model argument.\n *\n * This module provides a unified `defineCall` function that automatically\n * detects whether a call is context-aware based on the template type parameter.\n * If T includes `ctx: Context<DepsT>`, a ContextCall is returned; otherwise\n * a regular Call is returned.\n */\n\nimport type {\n AnyFormatInput,\n ExtractFormatType,\n FormatInput,\n Format,\n FormatSpec,\n OutputParser,\n} from \"@/llm/formatting\";\nimport type { Params } from \"@/llm/models/params\";\nimport type { ModelId } from \"@/llm/providers/model-id\";\nimport type { Response } from \"@/llm/responses\";\nimport type { ContextResponse } from \"@/llm/responses/context-response\";\nimport type { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport type { StreamResponse } from \"@/llm/responses/stream-response\";\nimport type { ContextTools, Tools, ZodLike } from \"@/llm/tools\";\nimport type { NoVars } from \"@/llm/types\";\n\nimport { type Context, isContext } from \"@/llm/context\";\nimport { Model, useModel } from \"@/llm/models\";\nimport {\n definePrompt,\n type ContextPrompt,\n type ContextTemplateFunc,\n type ExtractDeps,\n type ExtractVars,\n type Prompt,\n type PromptArgs,\n type TemplateFunc,\n} from \"@/llm/prompts\";\n\n// ============================================================================\n// Call Args Types\n// ============================================================================\n\n/**\n * Arguments for defining a call.\n *\n * @template T - The type of variables the template accepts. Defaults to NoVars.\n * @template F - The format input type. The output type F is derived via ExtractFormatType<F>.\n */\nexport interface CallArgs<\n T = NoVars,\n F extends AnyFormatInput = undefined,\n> extends Params {\n /** The model to use, either a Model instance or model ID string. */\n model: Model | ModelId;\n /** Optional tools to make available to the model. */\n tools?: Tools;\n /**\n * Optional format specification for structured output.\n * Can be a Zod schema, Format, FormatSpec, or OutputParser.\n * The output type is automatically inferred from this format.\n */\n format?: F;\n /** A function that generates message content (optionally from variables). */\n template: TemplateFunc<T>;\n}\n\n/**\n * Arguments for defining a context-aware call.\n * Used when T includes `ctx: Context<DepsT>`.\n *\n * @template T - The full template parameter type including ctx.\n * @template F - The format input type.\n */\nexport interface ContextCallArgs<\n T = NoVars,\n F extends AnyFormatInput = undefined,\n> extends Params {\n /** The model to use, either a Model instance or model ID string. */\n model: Model | ModelId;\n /** Optional tools to make available to the model. */\n tools?: ExtractDeps<T> extends never ? Tools : ContextTools<ExtractDeps<T>>;\n /**\n * Optional format specification for structured output.\n * Can be a Zod schema, Format, FormatSpec, or OutputParser.\n */\n format?: F;\n /** A function that generates message content from context (and optionally variables). */\n template: TemplateFunc<T>;\n}\n\n// ============================================================================\n// Call Interface (Non-Context)\n// ============================================================================\n\n/**\n * A call that can be invoked directly to generate a response.\n *\n * Created by `defineCall()`. Unlike a `Prompt`, a `Call` has a model bundled in,\n * so it can be invoked without passing a model argument.\n *\n * @template T - The type of variables the call accepts. Defaults to empty object.\n * @template F - The format input type. The output type F is derived via ExtractFormatType<F>.\n *\n * @example With variables\n * ```typescript\n * const recommendBook = defineCall<{ genre: string }>({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ genre }) => `Recommend a ${genre} book`,\n * });\n *\n * const response = await recommendBook({ genre: 'fantasy' });\n * ```\n *\n * @example Without variables\n * ```typescript\n * const sayHello = defineCall({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: () => 'Hello!',\n * });\n * const response = await sayHello();\n * ```\n */\nexport interface Call<T = NoVars, F extends AnyFormatInput = undefined> {\n /**\n * Call directly to generate a response (model is bundled).\n *\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n (\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<Response<ExtractFormatType<F>>>;\n\n /**\n * Call directly to generate a response (model is bundled).\n * This is the method form of the callable interface.\n *\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n call(\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<Response<ExtractFormatType<F>>>;\n\n /**\n * Stream directly to generate a streaming response (model is bundled).\n *\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the streaming LLM response.\n *\n * @example\n * ```typescript\n * const response = await call.stream({ genre: 'fantasy' });\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n stream(\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<StreamResponse<ExtractFormatType<F>>>;\n\n /**\n * The model used for generating responses.\n * Returns the context model if one is set via `withModel`, otherwise returns `defaultModel`.\n */\n readonly model: Model;\n\n /**\n * The default model configured when defining this call.\n * Use `model` to get the effective model (which respects context).\n */\n readonly defaultModel: Model;\n\n /**\n * The tools available to this call.\n */\n readonly tools: Tools | undefined;\n\n /**\n * The format specification for structured output, if any.\n */\n readonly format: FormatInput<ExtractFormatType<F>>;\n\n /**\n * The underlying prompt.\n */\n readonly prompt: Prompt<T, F>;\n\n /**\n * The underlying template function.\n */\n readonly template: TemplateFunc<T>;\n}\n\n// ============================================================================\n// Context Call Interface\n// ============================================================================\n\n/**\n * A context-aware call that can be invoked directly with a context to generate a response.\n *\n * Created by `defineCall()` when the template type includes `ctx: Context<DepsT>`.\n * Unlike a `ContextPrompt`, a `ContextCall` has a model bundled in, so it can be\n * invoked without passing a model argument.\n *\n * @template T - The type of variables the call accepts. Defaults to empty object.\n * @template DepsT - The type of dependencies in the context.\n * @template F - The format input type. The output type is derived via ExtractFormatType<F>.\n *\n * @example With variables\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = defineCall<{ ctx: Context<MyDeps>; greeting: string }>({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ ctx, greeting }) => `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(ctx, { greeting: 'Hello' });\n * ```\n *\n * @example Without variables\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const sayHello = defineCall<{ ctx: Context<MyDeps> }>({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ ctx }) => `Hello, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await sayHello(ctx);\n * ```\n */\nexport interface ContextCall<\n T = NoVars,\n DepsT = unknown,\n F extends AnyFormatInput = undefined,\n> {\n /**\n * Call directly with context to generate a response (model is bundled).\n *\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n (\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Call directly with context to generate a response (model is bundled).\n * This is the method form of the callable interface.\n *\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n call(\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Stream directly with context to generate a streaming response (model is bundled).\n *\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the streaming LLM response.\n *\n * @example\n * ```typescript\n * const response = await call.stream(ctx, { greeting: 'Hello' });\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n stream(\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextStreamResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * The model used for generating responses.\n * Returns the context model if one is set via `withModel`, otherwise returns `defaultModel`.\n */\n readonly model: Model;\n\n /**\n * The default model configured when defining this call.\n * Use `model` to get the effective model (which respects context).\n */\n readonly defaultModel: Model;\n\n /**\n * The tools available to this call.\n */\n readonly tools: ContextTools<DepsT> | undefined;\n\n /**\n * The format specification for structured output, if any.\n */\n readonly format:\n | Format<ExtractFormatType<F>>\n | FormatSpec<ExtractFormatType<F>>\n | ZodLike\n | OutputParser<ExtractFormatType<F>>\n | null\n | undefined;\n\n /**\n * The underlying context prompt.\n */\n readonly prompt: ContextPrompt<T, DepsT, F>;\n\n /**\n * The underlying template function.\n */\n readonly template: ContextTemplateFunc<T, DepsT>;\n}\n\n// ============================================================================\n// Unified Call Type\n// ============================================================================\n\n/**\n * Unified call type that returns either Call or ContextCall\n * based on whether T includes `ctx: Context<DepsT>`.\n */\nexport type UnifiedCall<T, F extends AnyFormatInput = undefined> =\n ExtractDeps<T> extends never\n ? Call<T, F>\n : ContextCall<ExtractVars<T>, ExtractDeps<T>, F>;\n\n/**\n * A builder function returned when defineCall is called with only a type parameter.\n * Allows specifying the variables type explicitly while inferring the format type.\n *\n * @template T - The type of variables the call accepts (may include ctx for context calls).\n */\nexport interface CallBuilder<T extends Record<string, unknown>> {\n <F extends AnyFormatInput = undefined>(\n args: CallArgs<T, F> | ContextCallArgs<T, F>,\n ): UnifiedCall<T, F>;\n}\n\n// ============================================================================\n// Core Implementation\n// ============================================================================\n\n// Core implementation - separated to avoid overload matching issues with curried calls\nfunction createCall<T, F extends AnyFormatInput>({\n model,\n tools,\n format,\n template,\n ...params\n}: CallArgs<T, F> | ContextCallArgs<T, F>): UnifiedCall<T, F> {\n if (typeof model !== \"string\" && Object.keys(params).length > 0) {\n throw new Error(\n \"Cannot pass params when model is a Model instance. Use new Model(id, params) instead.\",\n );\n }\n\n // Resolve the default model at definition time (bakes in params)\n const defaultModel: Model =\n typeof model === \"string\" ? new Model(model, params) : model;\n\n // Create the unified prompt (it handles both context and non-context cases)\n const prompt = definePrompt({ tools, format, template } as PromptArgs<\n T & Record<string, unknown>,\n F\n >);\n\n // Create call function that handles both context and non-context cases\n // We use type assertions here because the unified prompt handles runtime detection\n const callImpl = async (\n ...args: unknown[]\n ): Promise<\n | Response<ExtractFormatType<F>>\n | ContextResponse<unknown, ExtractFormatType<F>>\n > => {\n const firstArg = args[0];\n\n if (isContext(firstArg)) {\n // Context case: call(ctx, vars?)\n const ctx = firstArg;\n const vars = args[1] as ExtractVars<T> | undefined;\n // Use the prompt's internal implementation which handles both cases\n const contextPrompt = prompt as unknown as {\n call(\n model: Model,\n ctx: Context<unknown>,\n vars?: ExtractVars<T>,\n ): Promise<ContextResponse<unknown, ExtractFormatType<F>>>;\n };\n return contextPrompt.call(useModel(defaultModel), ctx, vars);\n } else {\n // Non-context case: call(vars?)\n const vars = firstArg as T | undefined;\n const regularPrompt = prompt as unknown as {\n call(model: Model, vars?: T): Promise<Response<ExtractFormatType<F>>>;\n };\n return regularPrompt.call(useModel(defaultModel), vars);\n }\n };\n\n // Create callable wrapper\n const callable = async (\n ...args: unknown[]\n ): Promise<\n | Response<ExtractFormatType<F>>\n | ContextResponse<unknown, ExtractFormatType<F>>\n > => {\n return callImpl(...args);\n };\n\n // Create stream function\n const streamImpl = async (\n ...args: unknown[]\n ): Promise<\n | StreamResponse<ExtractFormatType<F>>\n | ContextStreamResponse<unknown, ExtractFormatType<F>>\n > => {\n const firstArg = args[0];\n\n if (isContext(firstArg)) {\n // Context case: stream(ctx, vars?)\n const ctx = firstArg;\n const vars = args[1] as ExtractVars<T> | undefined;\n const contextPrompt = prompt as unknown as {\n stream(\n model: Model,\n ctx: Context<unknown>,\n vars?: ExtractVars<T>,\n ): Promise<ContextStreamResponse<unknown, ExtractFormatType<F>>>;\n };\n return contextPrompt.stream(useModel(defaultModel), ctx, vars);\n } else {\n // Non-context case: stream(vars?)\n const vars = firstArg as T | undefined;\n const regularPrompt = prompt as unknown as {\n stream(\n model: Model,\n vars?: T,\n ): Promise<StreamResponse<ExtractFormatType<F>>>;\n };\n return regularPrompt.stream(useModel(defaultModel), vars);\n }\n };\n\n const definedCall = Object.assign(callable, {\n defaultModel,\n call: callImpl,\n stream: streamImpl,\n tools,\n format,\n prompt,\n template,\n });\n\n Object.defineProperty(definedCall, \"model\", {\n get: () => useModel(defaultModel),\n enumerable: true,\n });\n\n return definedCall as unknown as UnifiedCall<T, F>;\n}\n\n// ============================================================================\n// defineCall Function Overloads\n// ============================================================================\n\n/**\n * Define a call with explicit variables type, returning a builder that infers format.\n *\n * This overload enables specifying the variables type upfront while still allowing\n * the format type to be inferred from the `format` property.\n *\n * @template T - The type of variables the template accepts (may include ctx for context calls).\n * @returns A builder function that accepts call arguments and infers the format type.\n *\n * @example With explicit variables and inferred format\n * ```typescript\n * const recommendBook = defineCall<{ genre: string }>()({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * format: defineFormat<Book>({ mode: 'tool' }),\n * template: ({ genre }) => `Recommend a ${genre} book`,\n * });\n *\n * const response = await recommendBook({ genre: 'fantasy' });\n * const book = response.parse(); // Typed as Book\n * ```\n *\n * @example Context-aware call with explicit type\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = defineCall<{ ctx: Context<MyDeps>; greeting: string }>()({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ ctx, greeting }) => `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(ctx, { greeting: 'Hello' });\n * ```\n */\nexport function defineCall<T extends Record<string, unknown>>(): CallBuilder<T>;\n\n/**\n * Define a call that automatically detects context from the template type.\n *\n * When T includes `ctx: Context<DepsT>`, returns a ContextCall.\n * Otherwise returns a regular Call.\n *\n * Both the variables type and format type are inferred from the arguments.\n * Type the template parameter to enable variables inference.\n *\n * @template T - The type of variables the template accepts (may include ctx for context calls).\n * @template F - The format input type (inferred from format property).\n * @param args - The call arguments including model, template, and optional parameters.\n * @returns A callable that can be invoked directly with variables (and context if T includes ctx).\n *\n * @example Call without variables\n * ```typescript\n * const sayHello = defineCall({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: () => 'Hello!',\n * });\n * const response = await sayHello();\n * ```\n *\n * @example Regular call with variables\n * ```typescript\n * const recommendBook = defineCall({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * format: defineFormat<Book>({ mode: 'tool' }),\n * template: ({ genre }: { genre: string }) => `Recommend a ${genre} book`,\n * });\n * const response = await recommendBook({ genre: 'fantasy' });\n * ```\n *\n * @example Context-aware call\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = defineCall({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ ctx, greeting }: { ctx: Context<MyDeps>; greeting: string }) =>\n * `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(ctx, { greeting: 'Hello' });\n * ```\n */\nexport function defineCall<\n T extends Record<string, unknown> = NoVars,\n F extends AnyFormatInput = undefined,\n>(args: CallArgs<T, F> | ContextCallArgs<T, F>): UnifiedCall<T, F>;\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n// Implementation\nexport function defineCall<T, F extends AnyFormatInput>(\n args?: CallArgs<T, F> | ContextCallArgs<T, F>,\n): UnifiedCall<T, F> | CallBuilder<T & Record<string, unknown>> {\n // If no args provided, return a builder function for curried usage\n if (args === undefined) {\n return (<F2 extends AnyFormatInput = undefined>(\n builderArgs: CallArgs<T, F2> | ContextCallArgs<T, F2>,\n ): UnifiedCall<T, F2> => {\n return createCall(builderArgs);\n }) as CallBuilder<T & Record<string, unknown>>;\n }\n\n return createCall(args);\n}\n"]}
|