@happyvertical/ai 0.102.1 → 0.102.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/AGENT.md +1 -1
  2. package/README.md +123 -2
  3. package/dist/chunks/{anthropic-6ZDF32jo.js → anthropic-CxOrttgj.js} +3 -4
  4. package/dist/chunks/{anthropic-6ZDF32jo.js.map → anthropic-CxOrttgj.js.map} +1 -1
  5. package/dist/chunks/{bedrock-BQi3Z9jR.js → bedrock-B0cNEXFa.js} +3 -4
  6. package/dist/chunks/{bedrock-BQi3Z9jR.js.map → bedrock-B0cNEXFa.js.map} +1 -1
  7. package/dist/chunks/{bifrost-DsI2I4ka.js → bifrost-CyO3-hBv.js} +4 -4
  8. package/dist/chunks/{bifrost-DsI2I4ka.js.map → bifrost-CyO3-hBv.js.map} +1 -1
  9. package/dist/chunks/{byteplus-modelark-Dq8AgCQD.js → byteplus-modelark-DZ0YL2vl.js} +3 -4
  10. package/dist/chunks/{byteplus-modelark-Dq8AgCQD.js.map → byteplus-modelark-DZ0YL2vl.js.map} +1 -1
  11. package/dist/chunks/{claude-cli-DIFxvG3c.js → claude-cli-CtBp-Uk-.js} +3 -4
  12. package/dist/chunks/{claude-cli-DIFxvG3c.js.map → claude-cli-CtBp-Uk-.js.map} +1 -1
  13. package/dist/chunks/{continuation-D0NisZA1.js → continuation-7o7400bp.js} +3 -3
  14. package/dist/chunks/continuation-7o7400bp.js.map +1 -0
  15. package/dist/chunks/{gateway-audio-models-Dn7Wrc6P.js → gateway-audio-models-BSZGgjd8.js} +2 -2
  16. package/dist/chunks/{gateway-audio-models-Dn7Wrc6P.js.map → gateway-audio-models-BSZGgjd8.js.map} +1 -1
  17. package/dist/chunks/{gemini-BLFwWN90.js → gemini-DUk4ssth.js} +3 -4
  18. package/dist/chunks/{gemini-BLFwWN90.js.map → gemini-DUk4ssth.js.map} +1 -1
  19. package/dist/chunks/{huggingface-BuRwlABZ.js → huggingface-C41BZOoI.js} +3 -4
  20. package/dist/chunks/{huggingface-BuRwlABZ.js.map → huggingface-C41BZOoI.js.map} +1 -1
  21. package/dist/chunks/{litellm-CpfCT6jN.js → litellm-BLR5cs8B.js} +4 -4
  22. package/dist/chunks/{litellm-CpfCT6jN.js.map → litellm-BLR5cs8B.js.map} +1 -1
  23. package/dist/chunks/{ollama-CnrskTUg.js → ollama--y88p8Bz.js} +4 -5
  24. package/dist/chunks/{ollama-CnrskTUg.js.map → ollama--y88p8Bz.js.map} +1 -1
  25. package/dist/chunks/{openai-compat-video-CJIDdkUO.js → openai-compat-video-erarPEz-.js} +3 -4
  26. package/dist/chunks/{openai-compat-video-CJIDdkUO.js.map → openai-compat-video-erarPEz-.js.map} +1 -1
  27. package/dist/chunks/{qwen-tts-PzEkWcEb.js → qwen-tts-C9w7teY6.js} +2 -2
  28. package/dist/chunks/{qwen-tts-PzEkWcEb.js.map → qwen-tts-C9w7teY6.js.map} +1 -1
  29. package/dist/chunks/{rate-limit-BzWfHA0e.js → rate-limit-Bln_w0rH.js} +3 -280
  30. package/dist/chunks/rate-limit-Bln_w0rH.js.map +1 -0
  31. package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
  32. package/dist/chunks/{seevio-D2y5Io7C.js → seevio-CosohVa0.js} +3 -4
  33. package/dist/chunks/{seevio-D2y5Io7C.js.map → seevio-CosohVa0.js.map} +1 -1
  34. package/dist/chunks/{src-CLT6r1W0.js → src-DDEz_uOe.js} +25 -30
  35. package/dist/chunks/{src-CLT6r1W0.js.map → src-DDEz_uOe.js.map} +1 -1
  36. package/dist/chunks/{typesafe-CVUqQ8N1.js → typesafe-BNM-QAJ2.js} +3 -4
  37. package/dist/chunks/{typesafe-CVUqQ8N1.js.map → typesafe-BNM-QAJ2.js.map} +1 -1
  38. package/dist/chunks/usage-BaQKo8bc.js +484 -0
  39. package/dist/chunks/usage-BaQKo8bc.js.map +1 -0
  40. package/dist/chunks/webllm-CWgY5nnP.js +584 -0
  41. package/dist/chunks/webllm-CWgY5nnP.js.map +1 -0
  42. package/dist/index.js +3 -4
  43. package/dist/local.d.ts +33 -0
  44. package/dist/local.d.ts.map +1 -0
  45. package/dist/local.js +3 -0
  46. package/dist/node.js +4 -5
  47. package/dist/node.js.map +1 -1
  48. package/dist/shared/continuation.d.ts +1 -1
  49. package/dist/shared/continuation.d.ts.map +1 -1
  50. package/dist/shared/factory.d.ts.map +1 -1
  51. package/dist/shared/providers/webllm-shim.d.ts +9 -0
  52. package/dist/shared/providers/webllm-shim.d.ts.map +1 -0
  53. package/dist/shared/providers/webllm.d.ts +115 -0
  54. package/dist/shared/providers/webllm.d.ts.map +1 -0
  55. package/dist/shared/types.d.ts +73 -2
  56. package/dist/shared/types.d.ts.map +1 -1
  57. package/metadata.json +1 -0
  58. package/package.json +15 -2
  59. package/dist/chunks/continuation-D0NisZA1.js.map +0 -1
  60. package/dist/chunks/rate-limit-BzWfHA0e.js.map +0 -1
  61. package/dist/chunks/types-DB5W6_F-.js +0 -153
  62. package/dist/chunks/types-DB5W6_F-.js.map +0 -1
  63. package/dist/chunks/usage-C1Y1Nlg4.js +0 -35
  64. package/dist/chunks/usage-C1Y1Nlg4.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-BaQKo8bc.js","names":[],"sources":["../../src/shared/types.ts","../../src/shared/safety.ts","../../src/shared/providers/usage.ts"],"sourcesContent":["/**\n * Core types and interfaces for the AI library\n */\n\n/**\n * Thinking level options for Gemini 3 models\n * Controls the amount of internal reasoning the model performs\n */\nexport type GeminiThinkingLevel = 'minimal' | 'low' | 'medium' | 'high';\n\n/**\n * Cost and output limits applied to every generative request.\n *\n * Provider instances merge partial overrides with the exported safe defaults.\n */\n/** Why a generation stopped, normalised across providers. */\nexport type AIFinishReason =\n | 'stop'\n | 'length'\n | 'tool_calls'\n | 'content_filter';\n\n/**\n * Automatic continuation when a reply stops on its output limit. `true`\n * allows up to 3 extra requests; pass `{ maxContinuations }` to change that.\n * Never applies to tool calls or JSON output.\n */\nexport type ContinueOnLengthOption =\n | boolean\n | {\n /** Extra requests allowed after the first (default 3). */\n maxContinuations?: number;\n };\n\nexport interface AIGenerationLimits {\n /**\n * Hard ceiling on text tokens a single request may generate. Defaults to a\n * high value (131072) so explicit caller `maxTokens` is bounded by the model\n * rather than by this package; set it to enforce a deployment-wide cap.\n */\n maxOutputTokens: number;\n\n /**\n * Output tokens used when the caller passes no `maxTokens` (default 4096,\n * never above `maxOutputTokens`).\n */\n defaultOutputTokens?: number;\n\n /** Maximum reasoning/thinking tokens a single request may generate. */\n maxReasoningTokens: number;\n\n /** Maximum images a single image-generation request may produce. */\n maxImagesPerRequest: number;\n\n /** Behavior when a request exceeds one of the configured limits. */\n onExceeded: 'error' | 'clamp';\n}\n\n/** Provider-neutral reasoning controls for a single generation request. */\nexport interface AIReasoningOptions {\n effort?: 'none' | GeminiThinkingLevel;\n maxTokens?: number;\n includeThoughts?: boolean;\n}\n\n/** Request-scoped cancellation, timeout, and reasoning controls. */\nexport interface AIRequestControls {\n /** Caller cancellation signal. Provider timeouts are composed with this signal. */\n signal?: AbortSignal;\n\n /**\n * Request timeout in milliseconds. Overrides the provider default. With\n * `rateLimit` pacing it covers the whole call, including time queued for the\n * rate-limit key and retry waits.\n */\n timeout?: number;\n\n /** Provider-neutral reasoning controls. */\n reasoning?: AIReasoningOptions;\n\n /** Sanitized dimensions attached to lifecycle and usage events. */\n usageTags?: Record<string, string>;\n}\n\n/** Operations reported through {@link AIRequestEvent}. */\nexport type AIRequestOperation =\n | 'decide'\n | 'chat'\n | 'complete'\n | 'message'\n | 'embed'\n | 'embedImage'\n | 'describeImage'\n | 'generateImage'\n | 'stream'\n | 'submitVideoGenerationJob'\n | 'getVideoGenerationJob'\n | 'fetchVideoGenerationResult'\n | 'cancelVideoGenerationJob';\n\n/** Terminal lifecycle state for a provider request. */\nexport type AIRequestStatus =\n | 'succeeded'\n | 'failed'\n | 'timed_out'\n | 'aborted'\n | 'rejected';\n\n/**\n * Prompt-free request lifecycle event.\n *\n * This intentionally excludes request and response content and credentials.\n */\nexport interface AIRequestEvent {\n provider: string;\n model: string;\n operation: AIRequestOperation;\n status: AIRequestStatus;\n attempts: number;\n requestedMaxOutputTokens?: number;\n effectiveMaxOutputTokens?: number;\n duration: number;\n errorCode?: string;\n tags?: Record<string, string>;\n}\n\n/**\n * Supported AI provider types\n */\nexport const AI_PROVIDER_TYPES = [\n 'openai',\n 'litellm',\n 'bifrost',\n 'ollama',\n 'gemini',\n 'anthropic',\n 'huggingface',\n 'bedrock',\n 'claude-cli',\n 'qwen3-tts',\n 'openai-compat-video',\n 'byteplus-modelark',\n 'seevio',\n 'typesafe',\n 'webllm',\n] as const;\n\n/**\n * Supported AI provider type union\n */\nexport type AIProviderType = (typeof AI_PROVIDER_TYPES)[number];\n\n/**\n * Text content part for multimodal messages\n */\nexport interface TextContentPart {\n type: 'text';\n text: string;\n}\n\n/**\n * Image content part for vision-capable models\n */\nexport interface ImageContentPart {\n type: 'image_url';\n image_url: {\n /** Image URL (http/https) or base64 data URL */\n url: string;\n /** Image detail level for processing */\n detail?: 'auto' | 'low' | 'high';\n };\n}\n\n/**\n * Union type for all content parts in multimodal messages\n */\nexport type ContentPart = TextContentPart | ImageContentPart;\n\n/**\n * Extract text content from a message content field.\n *\n * Handles both simple string content and multimodal content arrays,\n * extracting only the text parts and concatenating them.\n *\n * @param content - The message content (string or ContentPart array)\n * @returns The extracted text content\n */\nexport function extractTextContent(content: string | ContentPart[]): string {\n if (typeof content === 'string') {\n return content;\n }\n // Extract text from content parts\n return content\n .filter((part): part is TextContentPart => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n}\n\n/**\n * AI message structure for chat interactions\n *\n * Supports both simple string content and multimodal content arrays\n * for vision-capable models.\n *\n * @example Simple text message\n * ```typescript\n * const message: AIMessage = {\n * role: 'user',\n * content: 'Hello, how are you?'\n * };\n * ```\n *\n * @example Multimodal message with image\n * ```typescript\n * const message: AIMessage = {\n * role: 'user',\n * content: [\n * { type: 'text', text: 'What is in this image?' },\n * { type: 'image_url', image_url: { url: 'data:image/png;base64,...' } }\n * ]\n * };\n * ```\n */\nexport interface AIMessage {\n /**\n * Role of the message sender\n */\n role: 'system' | 'user' | 'assistant' | 'function' | 'tool';\n\n /**\n * Content of the message.\n *\n * Can be a simple string for text-only messages, or an array of content parts\n * for multimodal messages (e.g., text + images for vision models).\n */\n content: string | ContentPart[];\n\n /**\n * Optional name for the message sender.\n *\n * On `role: 'tool'` messages this is the name of the function that\n * produced the result. It is optional: providers that need it (Gemini,\n * Ollama) resolve it from the matching assistant `tool_calls` entry via\n * `tool_call_id` when it is omitted.\n */\n name?: string;\n\n /**\n * Tool calls requested by the model (assistant messages only).\n *\n * Pass `AIResponse.toolCalls` back here unchanged when continuing a tool\n * loop so every provider can replay the call with its original id.\n */\n tool_calls?: AIToolCall[];\n\n /**\n * Id of the tool call this message answers (`role: 'tool'` messages only).\n *\n * Required by OpenAI-compatible APIs (`tool_call_id`), Anthropic\n * (`tool_use_id`) and Bedrock (`toolUseId`) to pair a tool result with\n * the assistant tool call that requested it.\n */\n tool_call_id?: string;\n}\n\n/**\n * A function call requested by the model.\n *\n * Returned in `AIResponse.toolCalls` and replayed in `AIMessage.tool_calls`.\n */\nexport interface AIToolCall {\n /**\n * Call id, echoed back as `AIMessage.tool_call_id` on the tool result\n */\n id: string;\n type: 'function';\n function: {\n name: string;\n /**\n * JSON-encoded call arguments\n */\n arguments: string;\n };\n /**\n * Opaque provider signature that must be replayed with the call.\n *\n * Set by Gemini (thought signatures, required by Gemini 3 function\n * calling). Other providers ignore it.\n */\n thoughtSignature?: string;\n /**\n * Anthropic extended-thinking blocks that opened the assistant turn which\n * requested this call, with their signatures, in their original order.\n *\n * Set on the first tool call of a response when extended thinking is\n * enabled. Anthropic requires a replayed assistant `tool_use` turn to start\n * with its thinking blocks while thinking is enabled, so replay\n * `response.toolCalls` unchanged (and persist this field if you store\n * the conversation). Other providers ignore it.\n */\n thinkingBlocks?: AIThinkingBlock[];\n}\n\n/**\n * An Anthropic extended-thinking content block, kept opaque for replay.\n */\nexport type AIThinkingBlock =\n | { type: 'thinking'; thinking: string; signature: string }\n | { type: 'redacted_thinking'; data: string };\n\n/**\n * Options for chat completion requests\n */\nexport interface ChatOptions extends AIRequestControls {\n /**\n * Model to use for completion\n */\n model?: string;\n\n /**\n * Maximum number of tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Sampling temperature (0-2)\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topP?: number;\n\n /**\n * Number of completions to generate\n */\n n?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | string[];\n\n /**\n * Whether to stream the response\n */\n stream?: boolean;\n\n /**\n * Penalty for frequency of tokens\n */\n frequencyPenalty?: number;\n\n /**\n * Penalty for presence of tokens\n */\n presencePenalty?: number;\n\n /**\n * User identifier for monitoring\n */\n user?: string;\n\n /**\n * Available tools/functions\n */\n tools?: AITool[];\n\n /**\n * Tool choice behavior\n */\n toolChoice?:\n | 'auto'\n | 'none'\n | { type: 'function'; function: { name: string } };\n\n /**\n * Response format specification\n */\n responseFormat?: { type: 'text' | 'json_object' };\n\n /**\n * JSON Schema the reply must satisfy, as an object or a serialized string.\n * Implies JSON output. Honored only by providers that constrain decoding\n * with a grammar (`webllm`), where the model cannot emit a value outside\n * the schema (e.g. an enum); other providers ignore it, so still validate.\n */\n responseSchema?: Record<string, unknown> | string;\n\n /**\n * Random seed for deterministic results\n */\n seed?: number;\n\n /**\n * Callback for streaming responses\n */\n onProgress?: (chunk: string) => void;\n\n /**\n * Called by streaming adapters when the reply ends, with the normalised\n * finish reason. Used for continuation; also useful to detect truncation.\n */\n onFinishReason?: (reason: AIFinishReason) => void;\n\n /**\n * Continue a reply that stopped on its output limit and return the stitched\n * text. Off by default; ignored for tools and JSON output. Each part is a\n * separate request bounded by the output ceiling.\n */\n continueOnLength?: ContinueOnLengthOption;\n\n /**\n * Thinking level for providers that expose reasoning controls.\n * Gemini 3 models use named levels:\n * - 'minimal': No thinking for most queries (Gemini 3 Flash only)\n * - 'low': Minimizes latency and cost, good for simple tasks\n * - 'medium': Balanced thinking for most tasks (Gemini 3 Flash only)\n * - 'high': Maximizes reasoning depth (default for Gemini 3)\n *\n * Ollama also accepts `false` to explicitly disable visible/internal thinking\n * for models that support it.\n * @deprecated Use `reasoning.effort` and `reasoning.maxTokens` instead.\n */\n thinkingLevel?: GeminiThinkingLevel | false;\n\n /**\n * Whether to include the model's internal thoughts in the response\n * Only applicable for Gemini 3 models with thinking enabled\n * @deprecated Use `reasoning.includeThoughts` instead.\n */\n includeThoughts?: boolean;\n\n /**\n * Custom tags to attach to the usage event for this call.\n * Merged over any global `usageTags` from provider options.\n */\n usageTags?: Record<string, string>;\n}\n\n/**\n * Options for text completion requests (non-chat models)\n */\nexport interface CompletionOptions extends AIRequestControls {\n /**\n * Model to use for completion\n */\n model?: string;\n\n /**\n * Maximum number of tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Sampling temperature\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topP?: number;\n\n /**\n * Number of completions to generate\n */\n n?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | string[];\n\n /**\n * Whether to stream the response\n */\n stream?: boolean;\n\n /**\n * Callback for streaming responses\n */\n onProgress?: (chunk: string) => void;\n\n /**\n * Continue a reply that stopped on its output limit and return the stitched\n * text. Off by default; ignored for tools and JSON output. Each part is a\n * separate request bounded by the output ceiling.\n */\n continueOnLength?: ContinueOnLengthOption;\n\n /**\n * Custom tags to attach to the usage event for this call.\n * Merged over any global `usageTags` from provider options.\n */\n usageTags?: Record<string, string>;\n}\n\n/**\n * Options for embedding generation\n */\nexport interface EmbeddingOptions {\n /**\n * Model to use for embeddings\n */\n model?: string;\n\n /**\n * User identifier for monitoring\n */\n user?: string;\n\n /**\n * Encoding format for embeddings\n */\n encodingFormat?: 'float' | 'base64';\n\n /**\n * Number of dimensions for the embedding\n */\n dimensions?: number;\n\n /**\n * Custom tags to attach to the usage event for this call.\n * Merged over any global `usageTags` from provider options.\n */\n usageTags?: Record<string, string>;\n}\n\n/**\n * Options for image embedding generation\n */\nexport interface ImageEmbeddingOptions {\n /**\n * Model to use for image embeddings\n * - Gemini: 'multimodalembedding@001' or similar\n * - OpenAI: Uses describe-then-embed with text-embedding-3-small\n */\n model?: string;\n\n /**\n * Number of dimensions for the embedding output\n */\n dimensions?: number;\n\n /**\n * User identifier for monitoring\n */\n user?: string;\n}\n\n/**\n * Options for image description generation\n */\nexport interface ImageDescriptionOptions extends AIRequestControls {\n /**\n * Model to use for image description\n * - OpenAI: defaults to 'gpt-4o'\n * - Gemini: defaults to 'gemini-2.5-flash'\n */\n model?: string;\n\n /**\n * Maximum tokens for the description\n */\n maxTokens?: number;\n\n /**\n * Detail level for image processing (OpenAI-specific)\n */\n detail?: 'auto' | 'low' | 'high';\n}\n\n/**\n * Options for image generation\n */\nexport interface ImageGenerationOptions extends AIRequestControls {\n /**\n * Model to use for image generation\n * - OpenAI: 'dall-e-3' (default), 'dall-e-2'\n * - Gemini: 'imagen-3.0-generate-002' (default)\n */\n model?: string;\n\n /**\n * Input image for image-to-image workflows\n * Can be a URL (http/https), base64 data URL, or Buffer\n */\n imageInput?: string | Buffer;\n\n /**\n * Aspect ratio for the generated image\n * e.g., \"16:9\", \"1:1\", \"4:3\", \"3:4\", \"9:16\"\n */\n aspectRatio?: string;\n\n /**\n * Output format for the generated image\n * - 'buffer': Returns raw image bytes (default)\n * - 'base64': Returns base64-encoded string\n * - 'url': Returns temporary URL (provider-dependent, may expire)\n */\n outputFormat?: 'buffer' | 'base64' | 'url';\n\n /**\n * Number of images to generate (provider-dependent)\n * - DALL-E 3: Only 1 supported\n * - Imagen 3: 1-4 supported\n */\n n?: number;\n\n /**\n * Image style (OpenAI DALL-E 3 specific)\n */\n style?: 'vivid' | 'natural';\n\n /**\n * Quality setting\n * - OpenAI: 'standard' | 'hd'\n */\n quality?: string;\n\n /**\n * Size specification (for providers that use fixed sizes)\n * - OpenAI DALL-E 3: '1024x1024' | '1792x1024' | '1024x1792'\n */\n size?: string;\n}\n\n/**\n * Response from image generation\n */\nexport interface ImageGenerationResponse {\n /**\n * Generated image(s) - format depends on outputFormat option\n */\n images: Array<{\n /**\n * Image data - Buffer for 'buffer' format, string for 'base64' or 'url'\n */\n data: Buffer | string;\n /**\n * MIME type of the image (e.g., 'image/png', 'image/jpeg')\n */\n mimeType: string;\n /**\n * Revised prompt (if provider modified the original)\n */\n revisedPrompt?: string;\n }>;\n\n /**\n * Model used for generation\n */\n model?: string;\n}\n\n/**\n * Options for simple message requests (convenience method)\n * This provides a simpler interface than chat() for single-turn interactions\n */\nexport interface MessageOptions extends AIRequestControls {\n /**\n * Model to use for completion\n */\n model?: string;\n\n /**\n * Role of the message sender (default: 'user')\n */\n role?: 'user' | 'assistant' | 'system';\n\n /**\n * Conversation history (previous messages)\n */\n history?: AIMessage[];\n\n /**\n * Maximum number of tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Sampling temperature (0-2)\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topP?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | string[];\n\n /**\n * Whether to stream the response\n */\n stream?: boolean;\n\n /**\n * Penalty for frequency of tokens\n */\n frequencyPenalty?: number;\n\n /**\n * Penalty for presence of tokens\n */\n presencePenalty?: number;\n\n /**\n * Response format specification\n */\n responseFormat?: { type: 'text' | 'json_object' };\n\n /**\n * JSON Schema the reply must satisfy, as an object or a serialized string.\n * Implies JSON output. Honored only by providers that constrain decoding\n * with a grammar (`webllm`), where the model cannot emit a value outside\n * the schema (e.g. an enum); other providers ignore it, so still validate.\n */\n responseSchema?: Record<string, unknown> | string;\n\n /**\n * Random seed for deterministic results\n */\n seed?: number;\n\n /**\n * Available tools/functions\n */\n tools?: AITool[];\n\n /**\n * Tool choice behavior\n */\n toolChoice?:\n | 'auto'\n | 'none'\n | { type: 'function'; function: { name: string } };\n\n /**\n * Callback for streaming responses\n */\n onProgress?: (chunk: string) => void;\n\n /**\n * Continue a reply that stopped on its output limit and return the stitched\n * text. Off by default; ignored for tools and JSON output. Each part is a\n * separate request bounded by the output ceiling.\n */\n continueOnLength?: ContinueOnLengthOption;\n\n /**\n * Custom tags to attach to the usage event for this call.\n * Merged over any global `usageTags` from provider options.\n */\n usageTags?: Record<string, string>;\n}\n\n/**\n * Tool/function definition for AI models\n */\nexport interface AITool {\n /**\n * Type of tool\n */\n type: 'function';\n\n /**\n * Function definition\n */\n function: {\n /**\n * Function name\n */\n name: string;\n\n /**\n * Function description\n */\n description?: string;\n\n /**\n * JSON schema for function parameters\n */\n parameters?: Record<string, any>;\n };\n}\n\n/**\n * Model information structure\n */\nexport interface AIModel {\n /**\n * Model identifier\n */\n id: string;\n\n /**\n * Human-readable model name\n */\n name: string;\n\n /**\n * Model description\n */\n description?: string;\n\n /**\n * Maximum context length in tokens\n */\n contextLength: number;\n\n /**\n * Supported capabilities\n */\n capabilities: string[];\n\n /**\n * Whether the model supports function calling\n */\n supportsFunctions: boolean;\n\n /**\n * Whether the model supports vision/multimodal input\n */\n supportsVision: boolean;\n\n /**\n * Cost per input token (if available)\n */\n inputCostPer1k?: number;\n\n /**\n * Cost per output token (if available)\n */\n outputCostPer1k?: number;\n}\n\n/**\n * Budget configuration for AI gateway admin operations.\n *\n * Providers translate this to their native field names:\n * - Bifrost: `budget.max_limit` / `budget.reset_duration`\n * - LiteLLM: `max_budget` / `budget_duration`\n */\nexport interface AIAdminBudget {\n /**\n * Maximum spend in USD.\n */\n maxLimit?: number;\n\n /**\n * Reset duration such as `1h`, `1d`, `30d`, or `1M`.\n */\n resetDuration?: string;\n\n /**\n * Bifrost only: reset at calendar boundaries for day/week/month/year periods.\n */\n calendarAligned?: boolean;\n}\n\n/**\n * Rate-limit configuration for AI gateway admin operations.\n */\nexport interface AIAdminRateLimit {\n /**\n * Provider-agnostic token limit.\n *\n * Bifrost maps this to `token_max_limit`; LiteLLM maps it to `tpm_limit`.\n */\n tokenMaxLimit?: number;\n\n /**\n * Bifrost token reset duration such as `1h`.\n */\n tokenResetDuration?: string;\n\n /**\n * Provider-agnostic request limit.\n *\n * Bifrost maps this to `request_max_limit`; LiteLLM maps it to `rpm_limit`.\n */\n requestMaxLimit?: number;\n\n /**\n * Bifrost request reset duration such as `1m`.\n */\n requestResetDuration?: string;\n\n /**\n * LiteLLM tokens-per-minute limit. Overrides `tokenMaxLimit` for LiteLLM.\n */\n tpmLimit?: number;\n\n /**\n * LiteLLM requests-per-minute limit. Overrides `requestMaxLimit` for LiteLLM.\n */\n rpmLimit?: number;\n}\n\n/**\n * Bifrost virtual-key routing configuration.\n */\nexport interface AIAdminProviderConfig {\n /**\n * Provider identifier such as `openai` or `anthropic`.\n */\n provider: string;\n\n /**\n * Routing weight for this provider.\n */\n weight?: number;\n\n /**\n * Models this virtual key may use for the provider.\n */\n allowedModels?: string[];\n\n /**\n * Bifrost provider key IDs that this virtual key may use.\n */\n keyIds?: string[];\n}\n\n/**\n * Options for creating a gateway-scoped project.\n *\n * In Bifrost, projects are implemented as governance teams, optionally attached\n * to a customer via `tenantId`. In LiteLLM, projects are implemented as teams.\n */\nexport interface CreateAIProjectOptions {\n /**\n * Stable project ID. LiteLLM requires one; if omitted, a slug is derived from\n * the tenant and project name. Bifrost generates its own team ID.\n */\n id?: string;\n\n /**\n * Human-readable project name.\n */\n name: string;\n\n /**\n * Tenant/customer identifier to attach the project to where supported.\n */\n tenantId?: string;\n\n /**\n * Human-readable description. Stored in metadata for providers that support it.\n */\n description?: string;\n\n /**\n * Models the project may access.\n */\n models?: string[];\n\n /**\n * Shared project budget.\n */\n budget?: AIAdminBudget;\n\n /**\n * Shared project rate limits.\n */\n rateLimit?: AIAdminRateLimit;\n\n /**\n * Provider-specific metadata.\n */\n metadata?: Record<string, unknown>;\n\n /**\n * Whether the project should be blocked on creation where supported.\n */\n isBlocked?: boolean;\n\n /**\n * Provider-specific request body overrides.\n */\n raw?: Record<string, unknown>;\n}\n\n/**\n * Gateway project descriptor returned by admin providers.\n */\nexport interface AIAdminProject {\n /**\n * Provider project ID.\n */\n id: string;\n\n /**\n * Human-readable project name.\n */\n name: string;\n\n /**\n * Tenant/customer identifier where available.\n */\n tenantId?: string;\n\n /**\n * Provider budget ID where available.\n */\n budgetId?: string;\n\n /**\n * Admin provider that created this project.\n */\n provider: string;\n\n /**\n * Raw provider response.\n */\n raw?: unknown;\n}\n\n/**\n * Options for creating a gateway virtual key.\n */\nexport interface CreateAIVirtualKeyOptions {\n /**\n * Human-readable key name or alias.\n */\n name: string;\n\n /**\n * Human-readable key description.\n */\n description?: string;\n\n /**\n * Project/team ID to attach the key to.\n */\n projectId?: string;\n\n /**\n * Tenant/customer ID to attach the key to when no project is supplied, or to\n * record in LiteLLM metadata.\n */\n tenantId?: string;\n\n /**\n * Optional end-user ID associated with the key.\n */\n userId?: string;\n\n /**\n * Models this key may access.\n */\n models?: string[];\n\n /**\n * Bifrost provider routing configuration.\n */\n providerConfigs?: AIAdminProviderConfig[];\n\n /**\n * Key-level budget.\n */\n budget?: AIAdminBudget;\n\n /**\n * Key-level rate limits.\n */\n rateLimit?: AIAdminRateLimit;\n\n /**\n * Key duration such as `30d`, `1h`, or `permanent` where supported.\n */\n duration?: string;\n\n /**\n * Provider-specific metadata.\n */\n metadata?: Record<string, unknown>;\n\n /**\n * Bifrost provider API key IDs this virtual key may use. Use `[\"*\"]` to allow\n * all configured provider keys.\n */\n keyIds?: string[];\n\n /**\n * Whether the key should be active on creation.\n */\n isActive?: boolean;\n\n /**\n * LiteLLM model aliases for this key.\n */\n aliases?: Record<string, string>;\n\n /**\n * LiteLLM key-specific config.\n */\n config?: Record<string, unknown>;\n\n /**\n * LiteLLM key-specific permissions.\n */\n permissions?: Record<string, unknown>;\n\n /**\n * Provider-specific request body overrides.\n */\n raw?: Record<string, unknown>;\n}\n\n/**\n * Gateway virtual key descriptor returned by admin providers.\n */\nexport interface AIVirtualKey {\n /**\n * Provider key ID, when returned separately from the key value.\n */\n id?: string;\n\n /**\n * Human-readable key name or alias.\n */\n name?: string;\n\n /**\n * Newly generated key value. Some provider list/detail responses may only\n * expose a masked value.\n */\n key?: string;\n\n /**\n * Masked key value or key name, when provided.\n */\n maskedKey?: string;\n\n /**\n * Attached project/team ID.\n */\n projectId?: string;\n\n /**\n * Attached tenant/customer ID.\n */\n tenantId?: string;\n\n /**\n * Expiration timestamp where supported.\n */\n expiresAt?: string;\n\n /**\n * Admin provider that created this key.\n */\n provider: string;\n\n /**\n * Raw provider response.\n */\n raw?: unknown;\n}\n\n/**\n * Admin operations exposed by gateway providers that support provisioning.\n */\nexport interface AIAdminInterface {\n /**\n * Create a project/team for a tenant.\n */\n createProject(options: CreateAIProjectOptions): Promise<AIAdminProject>;\n\n /**\n * Create a virtual key, optionally attached to a project or tenant.\n */\n createVirtualKey(options: CreateAIVirtualKeyOptions): Promise<AIVirtualKey>;\n}\n\n/**\n * AI provider capabilities\n */\nexport interface AICapabilities {\n /**\n * Whether the provider supports typed, prompt-free decisions.\n *\n * Optional to preserve source compatibility for existing capability literals.\n */\n decisions?: boolean;\n /**\n * Whether the provider supports chat completions\n */\n chat: boolean;\n\n /**\n * Whether the provider supports text completions\n */\n completion: boolean;\n\n /**\n * Whether the provider supports embeddings\n */\n embeddings: boolean;\n\n /**\n * Whether the provider supports streaming\n */\n streaming: boolean;\n\n /**\n * Whether the provider supports function calling\n */\n functions: boolean;\n\n /**\n * Whether the provider supports vision/multimodal\n */\n vision: boolean;\n\n /**\n * Whether the provider supports fine-tuning\n */\n fineTuning: boolean;\n\n /**\n * Whether the provider supports image embeddings\n */\n imageEmbeddings: boolean;\n\n /**\n * Whether the provider supports image generation\n */\n imageGeneration: boolean;\n\n /**\n * Whether the provider supports asynchronous video-generation jobs\n * (submitVideoGenerationJob / getVideoGenerationJob / fetchVideoGenerationResult / cancelVideoGenerationJob)\n */\n videoGeneration: boolean;\n\n /**\n * Whether the provider supports text-to-speech synthesis\n */\n tts: boolean;\n\n /**\n * Whether the provider supports voice cloning from samples\n */\n voiceCloning: boolean;\n\n /**\n * Whether the provider supports voice design via description\n */\n voiceDesign: boolean;\n\n /**\n * Maximum context length supported\n */\n maxContextLength: number;\n\n /**\n * Supported operations\n */\n supportedOperations: string[];\n}\n\n/**\n * Token usage information\n */\nexport interface TokenUsage {\n /**\n * Number of prompt tokens\n */\n promptTokens: number;\n\n /**\n * Number of completion tokens\n */\n completionTokens: number;\n\n /**\n * Total tokens used\n */\n totalTokens: number;\n}\n\n/** JSON-compatible data evaluated by a decision provider. */\nexport type DecisionValue =\n | string\n | number\n | boolean\n | null\n | DecisionValue[]\n | { [key: string]: DecisionValue };\n\n/** A boolean predicate, expressed without provider-specific terminology. */\nexport interface PredicateDecisionQuestion {\n type: 'predicate';\n instructions: DecisionValue;\n criteria?: { true?: DecisionValue; false?: DecisionValue };\n}\n\n/** A selection from named, unordered labels. */\nexport interface ChoiceDecisionQuestion {\n type: 'choice';\n instructions: DecisionValue;\n criteria: Record<string, DecisionValue | null>;\n}\n\n/** A position on an ordered rubric. */\nexport interface ScoreDecisionQuestion {\n type: 'score';\n instructions: DecisionValue;\n criteria: DecisionValue[];\n}\n\nexport type DecisionQuestion =\n | PredicateDecisionQuestion\n | ChoiceDecisionQuestion\n | ScoreDecisionQuestion;\n\n/** A typed batch of independent questions evaluated against one state. */\nexport interface DecisionRequest {\n state: DecisionValue;\n questions: Record<string, DecisionQuestion>;\n}\n\n/** Request controls for a decision operation. Generation controls do not apply. */\nexport interface DecisionOptions extends AIRequestControls {\n model?: string;\n}\n\nexport interface PredicateDecisionAnswer {\n type: 'predicate';\n /** Probability that the predicate is true, bounded from zero through one. */\n probability: number;\n}\n\nexport interface ChoiceDecisionAnswer {\n type: 'choice';\n choice: string;\n probabilities: Record<string, number>;\n confidence: number;\n}\n\nexport interface ScoreDecisionAnswer {\n type: 'score';\n score: number;\n probabilities: Record<string, number>;\n confidence: number;\n /** Ordered rubric descriptions corresponding to probability keys 0..n-1. */\n levels: DecisionValue[];\n}\n\nexport type DecisionAnswer =\n | PredicateDecisionAnswer\n | ChoiceDecisionAnswer\n | ScoreDecisionAnswer;\n\nexport interface DecisionResult {\n /** Actual model returned by the provider. */\n model: string;\n usage?: TokenUsage;\n /** Provider/model provenance. Probabilities are not cross-provider calibrated. */\n provenance: { provider: string; model: string };\n answers: Record<string, DecisionAnswer>;\n}\n\n/**\n * Usage event emitted via the `onUsage` callback after each API call.\n * Provides token usage, timing, and context for tracking and analytics.\n *\n * @example\n * ```typescript\n * const ai = await getAI({\n * type: 'openai',\n * apiKey: '...',\n * onUsage: (event) => {\n * console.log(`[${event.provider}/${event.model}] ${event.operation}: ${event.usage?.totalTokens} tokens in ${event.duration}ms`);\n * },\n * });\n * ```\n */\nexport interface UsageEvent {\n /** Provider that handled the request (e.g. 'openai', 'anthropic', 'gemini') */\n provider: string;\n\n /** Model that was used (e.g. 'gpt-4o', 'claude-3-5-sonnet-20241022') */\n model: string;\n\n /** Operation type that generated this usage */\n operation: AIRequestOperation;\n\n /** Token usage breakdown, if available from the provider */\n usage?: TokenUsage;\n\n /** Wall-clock duration of the API call in milliseconds */\n duration: number;\n\n /** Timestamp when the call completed */\n timestamp: Date;\n\n /** Custom tags from global `usageTags` and per-call `usageTags`, merged */\n tags?: Record<string, string>;\n}\n\n/**\n * AI response structure\n */\nexport interface AIResponse {\n /**\n * Generated content\n */\n content: string;\n\n /**\n * Token usage information\n */\n usage?: TokenUsage;\n\n /**\n * Model used for generation\n */\n model?: string;\n\n /**\n * Finish reason\n */\n finishReason?: AIFinishReason;\n\n /**\n * Tool calls made by the model\n */\n toolCalls?: AIToolCall[];\n\n /**\n * True when the reply ended on the output limit (after any continuations).\n */\n truncated?: boolean;\n\n /**\n * Number of provider requests stitched into this reply. Set when\n * continuation ran.\n */\n parts?: number;\n}\n\n/**\n * Embedding response structure\n */\nexport interface EmbeddingResponse {\n /**\n * Generated embeddings\n */\n embeddings: number[][];\n\n /**\n * Token usage information\n */\n usage?: TokenUsage;\n\n /**\n * Model used for embeddings\n */\n model?: string;\n}\n\n/**\n * Core AI interface that all providers must implement\n */\nexport interface AIInterface {\n /**\n * Optional admin surface for gateway providers that support provisioning.\n */\n admin?: AIAdminInterface;\n\n /**\n * Evaluate provider-neutral, typed questions without using text generation.\n * Optional so third-party implementations remain source compatible.\n */\n decide?(\n request: DecisionRequest,\n options?: DecisionOptions,\n ): Promise<DecisionResult>;\n\n /**\n * Generate a chat completion from a sequence of messages.\n *\n * @param messages - Conversation messages (system, user, assistant, tool roles)\n * @param options - Chat options including model, temperature, tools, etc.\n * @returns Promise resolving to the model's response with content and usage info\n * @throws {AIError} When the request fails\n * @throws {AuthenticationError} When credentials are invalid\n * @throws {RateLimitError} When the provider's rate limit is exceeded\n */\n chat(messages: AIMessage[], options?: ChatOptions): Promise<AIResponse>;\n\n /**\n * Generate a text completion from a prompt string (non-chat interface).\n *\n * @param prompt - The text prompt to complete\n * @param options - Completion options including model, temperature, etc.\n * @returns Promise resolving to the model's response\n * @throws {AIError} When the request fails\n */\n complete(prompt: string, options?: CompletionOptions): Promise<AIResponse>;\n\n /**\n * Simple message interface for single-turn interactions\n *\n * This is a convenience method that wraps chat() for simpler use cases.\n * It accepts a text string and optional configuration, returning just\n * the response content as a string.\n *\n * Supports conversation history via the `history` option for multi-turn\n * conversations while maintaining a simple API.\n *\n * @param text - The message text to send\n * @param options - Configuration options including history, model, etc.\n * @returns Promise resolving to the response content string\n *\n * @example\n * ```typescript\n * // Simple single-turn usage\n * const response = await ai.message('Hello, how are you?');\n *\n * // With options\n * const response = await ai.message('Analyze this data', {\n * model: 'gpt-4o',\n * responseFormat: { type: 'json_object' },\n * maxTokens: 1000\n * });\n *\n * // With conversation history\n * const response = await ai.message('What did I ask before?', {\n * history: [\n * { role: 'user', content: 'Hello' },\n * { role: 'assistant', content: 'Hi there!' }\n * ]\n * });\n * ```\n */\n message(text: string, options?: MessageOptions): Promise<string>;\n\n /**\n * Generate vector embeddings for one or more text inputs.\n *\n * @param text - A single string or array of strings to embed\n * @param options - Embedding options including model and dimensions\n * @returns Promise resolving to embedding vectors and usage info\n * @throws {AIError} When embeddings are not supported by this provider or request fails\n */\n embed(\n text: string | string[],\n options?: EmbeddingOptions,\n ): Promise<EmbeddingResponse>;\n\n /**\n * Generate embeddings for an image\n *\n * Implementation varies by provider:\n * - Gemini: Uses native multimodal embeddings\n * - OpenAI: Uses describe-then-embed pattern (describeImage → embed)\n * - Others: Throws NOT_IMPLEMENTED\n *\n * @param image - Image as URL, base64 data URL, or Buffer\n * @param options - Optional configuration for image embeddings\n * @returns Promise resolving to embeddings response\n * @throws {AIError} When embeddings are not supported or request fails\n *\n * @example\n * ```typescript\n * // From URL\n * const embedding = await ai.embedImage('https://example.com/image.jpg');\n *\n * // From Buffer\n * const buffer = fs.readFileSync('image.png');\n * const embedding = await ai.embedImage(buffer);\n *\n * // With options\n * const embedding = await ai.embedImage(imageUrl, { dimensions: 768 });\n * ```\n */\n embedImage(\n image: string | Buffer,\n options?: ImageEmbeddingOptions,\n ): Promise<EmbeddingResponse>;\n\n /**\n * Generate a text description of an image\n *\n * @param image - Image as URL, base64 data URL, or Buffer\n * @param prompt - Custom prompt for description (optional)\n * @param options - Optional configuration\n * @returns Promise resolving to the description string\n * @throws {AIError} When vision is not supported or request fails\n *\n * @example\n * ```typescript\n * // Default description for search indexing\n * const description = await ai.describeImage('https://example.com/image.jpg');\n *\n * // Custom prompt\n * const description = await ai.describeImage(imageBuffer, 'What product is shown?');\n *\n * // With options\n * const description = await ai.describeImage(imageUrl, undefined, {\n * model: 'gpt-4o',\n * maxTokens: 500,\n * detail: 'high'\n * });\n * ```\n */\n describeImage(\n image: string | Buffer,\n prompt?: string,\n options?: ImageDescriptionOptions,\n ): Promise<string>;\n\n /**\n * Generate an image from a text prompt\n *\n * @param prompt - Text description of the image to generate\n * @param options - Optional configuration for image generation\n * @returns Promise resolving to generated image(s)\n * @throws {AIError} When image generation is not supported or request fails\n *\n * @example\n * ```typescript\n * // Basic generation (returns Buffer by default)\n * const result = await ai.generateImage('A sunset over mountains');\n * fs.writeFileSync('image.png', result.images[0].data);\n *\n * // With options\n * const result = await ai.generateImage('A cat wearing a hat', {\n * outputFormat: 'base64',\n * size: '1024x1024',\n * style: 'vivid'\n * });\n * ```\n */\n generateImage(\n prompt: string,\n options?: ImageGenerationOptions,\n ): Promise<ImageGenerationResponse>;\n\n // ============================================================================\n // Video Generation Methods (async job abstraction)\n // ============================================================================\n\n /**\n * Submit an asynchronous video-generation job.\n *\n * Returns a JSON-serializable handle rather than the finished video: video\n * generation runs as a long-lived provider-side job, so callers persist the\n * handle and poll {@link AIInterface.getVideoGenerationJob} (optionally\n * across process restarts) until the job completes.\n *\n * @param options - Prompt, reference media, and generation parameters\n * @returns Promise resolving to a serializable job handle\n * @throws {AIError} When video generation is not supported or the request fails\n *\n * @example\n * ```typescript\n * const job = await ai.submitVideoGenerationJob({\n * prompt: 'A drone shot flying over a coastal cliff at sunrise',\n * durationSeconds: 8,\n * resolution: '1080p',\n * });\n * // Persist `job` (it is plain JSON) and resume polling later, even after a restart.\n * ```\n */\n submitVideoGenerationJob(\n options: VideoGenerationOptions,\n ): Promise<VideoGenerationJob>;\n\n /**\n * Check the status of a previously submitted video-generation job.\n *\n * @param handle - The job handle returned by {@link AIInterface.submitVideoGenerationJob}\n * @returns Promise resolving to the current status, and the result once succeeded\n * @throws {AIError} When video generation is not supported or the status check fails\n *\n * @example\n * ```typescript\n * const status = await ai.getVideoGenerationJob(job);\n * if (status.status === 'succeeded') {\n * console.log(status.result?.url);\n * }\n * ```\n */\n getVideoGenerationJob(\n handle: VideoGenerationJob,\n ): Promise<VideoGenerationStatusResult>;\n\n /**\n * Fetch the result of a completed video-generation job.\n *\n * @param handle - The job handle returned by {@link AIInterface.submitVideoGenerationJob}\n * @returns Promise resolving to the generated video's location/bytes and metadata\n * @throws {AIError} When video generation is not supported, the job has not\n * succeeded yet, or the request fails\n *\n * @example\n * ```typescript\n * const result = await ai.fetchVideoGenerationResult(job);\n * if (result.data) fs.writeFileSync('output.mp4', result.data);\n * ```\n */\n fetchVideoGenerationResult(\n handle: VideoGenerationJob,\n ): Promise<VideoGenerationResult>;\n\n /**\n * Cancel an in-flight video-generation job.\n *\n * **Cancellation is best-effort across every provider, not a guarantee.**\n * Consumers should call this on step abort or lease loss so they are not\n * billed for orphaned renders, but must be prepared for it to fail and\n * tolerate that failure rather than treating it as fatal:\n * - Some providers have no cancel endpoint at all for video-generation\n * jobs (e.g. Gemini/Veo) and always throw.\n * - Some providers can only cancel a job that hasn't started rendering\n * yet (e.g. ModelArk/Seedance can cancel a `queued` task but rejects\n * cancellation of a `running` one).\n * - Some gateway-shaped providers may not implement cancellation at all,\n * depending on the backend they proxy to.\n *\n * In every failure case, implementations throw {@link AIError} describing\n * why rather than silently succeeding.\n *\n * @param handle - The job handle returned by {@link AIInterface.submitVideoGenerationJob}\n * @throws {AIError} When video generation is not supported, or cancellation\n * is unsupported/rejected by the provider (best-effort — callers must\n * tolerate this)\n *\n * @example\n * ```typescript\n * controller.signal.addEventListener('abort', () => {\n * ai.cancelVideoGenerationJob(job).catch((error) => {\n * // Best-effort: log and move on, don't treat this as fatal.\n * console.warn('Could not cancel video job', job.jobId, error);\n * });\n * });\n * ```\n */\n cancelVideoGenerationJob(handle: VideoGenerationJob): Promise<void>;\n\n /**\n * Perform a cheap, auth-shaped call to confirm video-generation access is\n * configured correctly (e.g. a list-shaped API call), without submitting a\n * billed generation job.\n *\n * This is intentionally minimal, not free: providers without a dedicated\n * health endpoint reuse a low-cost listing call. Callers on a hot path\n * (e.g. a capability check per task) must cache the result themselves\n * rather than calling this on every iteration.\n *\n * @returns Promise resolving to true when access looks valid\n * @throws {AIError} When video generation is not supported or credentials are invalid\n */\n validateVideoGenerationAccess(): Promise<boolean>;\n\n /**\n * Stream a chat completion, yielding text chunks as they arrive.\n *\n * @param messages - Conversation messages\n * @param options - Chat options including model, temperature, etc.\n * @returns Async iterable of string chunks\n * @throws {AIError} When the request fails\n */\n stream(messages: AIMessage[], options?: ChatOptions): AsyncIterable<string>;\n\n /**\n * Estimate or calculate the token count for a text string.\n *\n * @param text - The text to tokenize\n * @returns Promise resolving to the token count\n */\n countTokens(text: string): Promise<number>;\n\n /**\n * List models available from this provider.\n *\n * @returns Promise resolving to an array of model descriptors\n */\n getModels(): Promise<AIModel[]>;\n\n /**\n * Query the capabilities supported by this provider (chat, embeddings, vision, TTS, etc.).\n *\n * @returns Promise resolving to a capabilities descriptor\n */\n getCapabilities(): Promise<AICapabilities>;\n\n // ============================================================================\n // Text-to-Speech Methods\n // ============================================================================\n\n /**\n * Synthesize speech from text\n *\n * @param text - The text to synthesize into speech\n * @param options - Optional configuration for TTS synthesis\n * @returns Promise resolving to audio data with metadata\n * @throws {AIError} When TTS is not supported or request fails\n *\n * @example\n * ```typescript\n * // Basic synthesis\n * const result = await ai.synthesizeSpeech('Hello, world!');\n * fs.writeFileSync('speech.wav', result.audio);\n *\n * // With options\n * const result = await ai.synthesizeSpeech('News broadcast text', {\n * voice: 'news-anchor-1',\n * speed: 1.1,\n * includeWordTimings: true\n * });\n * console.log(`Duration: ${result.duration}s`);\n * ```\n */\n synthesizeSpeech(text: string, options?: TTSOptions): Promise<TTSResponse>;\n\n /**\n * Stream speech synthesis for real-time playback\n *\n * @param text - The text to synthesize into speech\n * @param options - Optional configuration for TTS synthesis\n * @returns AsyncIterable of audio chunks\n * @throws {AIError} When TTS streaming is not supported or request fails\n *\n * @example\n * ```typescript\n * const chunks: Buffer[] = [];\n * for await (const chunk of ai.streamSpeech('Long text...')) {\n * chunks.push(chunk);\n * // Or stream directly to audio output\n * }\n * ```\n */\n streamSpeech(text: string, options?: TTSOptions): AsyncIterable<Buffer>;\n\n /**\n * Clone a voice from an audio sample\n *\n * Creates a new voice profile from a 3+ second audio sample.\n * The cloned voice can be used in subsequent synthesizeSpeech calls.\n *\n * @param options - Voice cloning configuration including audio sample\n * @returns Promise resolving to the cloned voice profile\n * @throws {AIError} When voice cloning is not supported or request fails\n *\n * @example\n * ```typescript\n * const sample = fs.readFileSync('voice-sample.wav');\n * const voice = await ai.cloneVoice({\n * sampleAudio: sample,\n * name: 'News Anchor Voice',\n * language: 'en-US'\n * });\n *\n * // Use the cloned voice\n * const speech = await ai.synthesizeSpeech('Breaking news...', {\n * voice: voice.id\n * });\n * ```\n */\n cloneVoice(options: VoiceCloneOptions): Promise<Voice>;\n\n /**\n * Design a voice using natural language description\n *\n * Creates a new voice profile from a text description of the desired voice.\n * The designed voice can be used in subsequent synthesizeSpeech calls.\n *\n * @param options - Voice design configuration including description\n * @returns Promise resolving to the designed voice profile\n * @throws {AIError} When voice design is not supported or request fails\n *\n * @example\n * ```typescript\n * const voice = await ai.designVoice({\n * description: 'warm female voice, slight British accent, professional news anchor',\n * language: 'en-US',\n * gender: 'female'\n * });\n *\n * // Use the designed voice\n * const speech = await ai.synthesizeSpeech('Good evening...', {\n * voice: voice.id\n * });\n * ```\n */\n designVoice(options: VoiceDesignOptions): Promise<Voice>;\n\n /**\n * List available voices for TTS synthesis\n *\n * @param options - Optional filters for the voice list\n * @returns Promise resolving to array of available voices\n * @throws {AIError} When TTS is not supported or request fails\n *\n * @example\n * ```typescript\n * // List all voices\n * const voices = await ai.getVoices();\n *\n * // Filter by language\n * const englishVoices = await ai.getVoices({ language: 'en' });\n *\n * // Include cloned voices\n * const allVoices = await ai.getVoices({ includeCloned: true });\n * ```\n */\n getVoices(options?: VoiceListOptions): Promise<Voice[]>;\n}\n\n/**\n * Shared rate-limit configuration for AI providers.\n *\n * The pacing wrapper activates only when one of the pacing fields\n * (`enabled`, `key`, `cooldownMs`, `initialDelayMs`, `maxAttempts`) is set.\n *\n * `qwen3-tts` and `byteplus-modelark` also use `requestsPerMinute` and\n * `maxConcurrent` from this object for their local token bucket limiters.\n */\nexport interface AIRateLimitOptions {\n /**\n * Enable shared in-process request pacing for this client.\n */\n enabled?: boolean;\n\n /**\n * Shared budget key used to coordinate pacing across multiple clients.\n * If omitted, a provider-scoped key is derived from the configured credentials.\n */\n key?: string;\n\n /**\n * Minimum delay in milliseconds between successful calls sharing the same key.\n */\n cooldownMs?: number;\n\n /**\n * Fallback delay in milliseconds before retrying a rate-limited call when\n * the provider does not return a `Retry-After` hint.\n */\n initialDelayMs?: number;\n\n /**\n * Maximum attempts for retryable rate-limit failures, including the first call.\n */\n maxAttempts?: number;\n\n /**\n * Longest provider reset wait (ms) still retried in-process. A rate limit\n * that resets further away is not retried and its `RateLimitError` has\n * `retryable: false`. Defaults to 60000.\n */\n maxRetryDelayMs?: number;\n\n /**\n * Qwen3-TTS only: maximum requests per minute for its local token bucket.\n */\n requestsPerMinute?: number;\n\n /**\n * Qwen3-TTS only: maximum concurrent requests allowed by its local limiter.\n */\n maxConcurrent?: number;\n}\n\n/**\n * Base configuration options for all providers\n */\nexport interface BaseAIOptions {\n /**\n * API timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n\n /**\n * Per-request generation guardrails. Partial overrides are merged with the\n * package defaults; raising a ceiling must therefore be deliberate.\n */\n generationLimits?: Partial<AIGenerationLimits>;\n\n /**\n * Client-wide default for continuing replies that stop on the output limit\n * (see {@link ContinueOnLengthOption}). A per-call `continueOnLength` wins.\n */\n continueOnLength?: ContinueOnLengthOption;\n\n /**\n * Custom headers\n */\n headers?: Record<string, string>;\n\n /**\n * Default model to use\n */\n defaultModel?: string;\n\n /**\n * Callback invoked after each API call with usage details.\n * Use this to track token consumption, costs, and performance across providers.\n *\n * Errors thrown inside this callback are silently caught and will not\n * affect the API call result.\n *\n * @param event - Usage event with provider, model, operation, tokens, and timing\n */\n onUsage?: (event: UsageEvent) => void;\n\n /**\n * Callback invoked once for every terminal request outcome, including local\n * limit rejection and timeout. Prompt and response content are never emitted.\n */\n onRequest?: (event: AIRequestEvent) => void;\n\n /**\n * Global tags to include in every usage event.\n * Per-call `usageTags` on `ChatOptions` / `EmbeddingOptions` / etc.\n * will be merged on top of these.\n */\n usageTags?: Record<string, string>;\n\n /**\n * Optional shared pacing / retry configuration.\n */\n rateLimit?: AIRateLimitOptions;\n}\n\n/**\n * OpenAI provider options\n */\nexport interface OpenAIOptions extends BaseAIOptions {\n type?: 'openai';\n apiKey?: string;\n baseUrl?: string;\n organization?: string;\n}\n\n/**\n * LiteLLM provider options\n *\n * LiteLLM exposes an OpenAI-compatible API surface and requires a custom\n * base URL such as `https://llm.happyvertical.com/v1`.\n */\nexport interface LiteLLMOptions extends BaseAIOptions {\n type: 'litellm';\n apiKey?: string;\n baseUrl?: string;\n organization?: string;\n adminApiKey?: string;\n adminBaseUrl?: string;\n adminUrl?: string;\n adminHeaders?: Record<string, string>;\n}\n\n/**\n * Bifrost provider options.\n *\n * Bifrost exposes OpenAI-compatible inference through endpoints such as\n * `/openai` and `/v1`, plus governance admin endpoints at `/api/governance/*`.\n */\nexport interface BifrostOptions extends BaseAIOptions {\n type: 'bifrost';\n apiKey?: string;\n baseUrl?: string;\n organization?: string;\n /**\n * Optional virtual key for admin routes. Bifrost OSS admin APIs typically use\n * username/password Basic auth instead; use `adminUser` / `adminPassword`\n * when governance auth is enabled without enterprise bearer-token support.\n */\n adminApiKey?: string;\n /**\n * Admin API root. Alias: `adminUrl`.\n */\n adminBaseUrl?: string;\n /**\n * Admin API root. Kept as a friendly alias for env vars such as\n * `BIFROST_ADMIN_URL`.\n */\n adminUrl?: string;\n /**\n * Bifrost admin username for HTTP Basic auth.\n */\n adminUser?: string;\n /**\n * Bifrost admin username for HTTP Basic auth.\n */\n adminUsername?: string;\n /**\n * Bifrost admin password for HTTP Basic auth.\n */\n adminPassword?: string;\n adminHeaders?: Record<string, string>;\n}\n\n/**\n * Ollama provider options\n *\n * Ollama defaults to the local host at `http://localhost:11434` and can also\n * target remote hosts such as `https://ollama.com/api` when paired with an\n * API key.\n */\nexport interface OllamaOptions extends BaseAIOptions {\n type: 'ollama';\n apiKey?: string;\n baseUrl?: string;\n /**\n * Default keep-alive duration for model requests, for example `5m` or `0`.\n */\n keepAlive?: string | number;\n}\n\n/**\n * Gemini provider options\n */\nexport interface GeminiOptions extends BaseAIOptions {\n type: 'gemini';\n apiKey?: string;\n baseUrl?: string;\n projectId?: string;\n location?: string;\n /**\n * Thinking level for Gemini 3 models (gemini-3-flash-preview, gemini-3-pro)\n * Controls internal reasoning depth:\n * - 'minimal': No thinking for most queries (Gemini 3 Flash only)\n * - 'low': Minimizes latency and cost, good for simple tasks\n * - 'medium': Balanced thinking for most tasks (Gemini 3 Flash only)\n * - 'high': Maximizes reasoning depth (default for Gemini 3)\n *\n * Note: Only works with Gemini 3 models. Gemini 2.5 uses thinkingBudget instead.\n *\n * @deprecated Use request-level `reasoning` controls instead. This alias is\n * normalized through `generationLimits.maxReasoningTokens`.\n */\n thinkingLevel?: GeminiThinkingLevel;\n}\n\n/**\n * Anthropic provider options\n */\nexport interface AnthropicOptions extends BaseAIOptions {\n type: 'anthropic';\n apiKey?: string;\n baseUrl?: string;\n anthropicVersion?: string;\n}\n\n/**\n * Hugging Face provider options\n */\nexport interface HuggingFaceOptions extends BaseAIOptions {\n type: 'huggingface';\n apiToken?: string;\n endpoint?: string;\n model?: string;\n useCache?: boolean;\n waitForModel?: boolean;\n}\n\n/**\n * AWS Bedrock provider options\n */\nexport interface BedrockOptions extends BaseAIOptions {\n type: 'bedrock';\n region?: string;\n credentials?: {\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n };\n endpoint?: string;\n}\n\n/**\n * Claude CLI provider options\n * Uses the local Claude Code CLI instead of API keys\n */\nexport interface ClaudeCliOptions extends BaseAIOptions {\n type: 'claude-cli';\n /**\n * Optional custom path to claude binary\n * If not specified, will search in PATH\n */\n cliPath?: string;\n}\n\n/**\n * Qwen3-TTS provider options\n * Uses Qwen3-TTS for text-to-speech synthesis\n *\n * TTS is co-located with ComfyUI for GPU sharing efficiency.\n */\nexport interface Qwen3TTSOptions extends BaseAIOptions {\n type: 'qwen3-tts';\n\n /**\n * TTS service endpoint URL\n * e.g., 'http://localhost:8880' or 'http://qwen-tts:8000'\n */\n endpoint?: string;\n\n /**\n * Default model variant\n * - 'qwen3-tts-1.7b': Higher quality (4.54GB VRAM)\n * - 'qwen3-tts-0.6b': Faster, lower VRAM (2.52GB)\n */\n defaultModel?: 'qwen3-tts-1.7b' | 'qwen3-tts-0.6b';\n\n /**\n * Default voice ID to use for synthesis\n */\n defaultVoice?: string;\n\n /**\n * Default language for synthesis\n */\n defaultLanguage?: string;\n\n /**\n * Rate limiting configuration for the local TTS adapter.\n * Reuses `BaseAIOptions.rateLimit` and reads `requestsPerMinute` / `maxConcurrent`.\n */\n rateLimit?: AIRateLimitOptions;\n}\n\n/**\n * OpenAI-compatible video-generation provider options.\n *\n * Thin adapter over a `/v1/videos`-shaped REST surface (create / retrieve /\n * cancel / download content), the shape used by LiteLLM's video passthrough\n * and Sora-shaped gateways. Only video-generation methods are implemented;\n * chat, embeddings, and other operations throw `NOT_IMPLEMENTED` — use the\n * `openai` or `litellm` provider types for those against the same gateway.\n */\nexport interface OpenAICompatVideoOptions extends BaseAIOptions {\n type: 'openai-compat-video';\n apiKey?: string;\n /**\n * Base URL for the gateway's OpenAI-compatible API root, e.g.\n * `https://llm.happyvertical.com/v1`. Required (directly or via the\n * `OPENAI_COMPAT_VIDEO_BASE_URL` environment variable).\n */\n baseUrl?: string;\n}\n\n/**\n * BytePlus ModelArk (Seedance) video-generation provider options.\n *\n * Raw-HTTP provider following the `qwen3-tts` precedent: no vendor SDK, just\n * the ModelArk video-generation task API (create task / poll / fetch).\n */\nexport interface ByteplusModelArkOptions extends BaseAIOptions {\n type: 'byteplus-modelark';\n /**\n * ModelArk API key. Falls back to `MODELARK_API_KEY` or the\n * BytePlus-documented `ARK_API_KEY` environment variable.\n */\n apiKey?: string;\n /**\n * ModelArk API root. Defaults to\n * `https://ark.ap-southeast.bytepluses.com/api/v3`.\n */\n baseUrl?: string;\n /**\n * Rate limiting configuration for the local submit-time limiter, shared\n * across provider instances constructed with the same `apiKey` (or the\n * same explicit `rateLimit.key`). Reads `requestsPerMinute` /\n * `maxConcurrent`. Defaults approximate the documented Seedance account\n * limits of QPS 2 / 3 concurrent *submissions* — `maxConcurrent` bounds\n * concurrent submit HTTP requests, not the lifetime of the render tasks\n * they create, which this package has no way to observe.\n */\n rateLimit?: AIRateLimitOptions;\n}\n\n/**\n * Seevio Seedance video-generation provider options.\n *\n * This provider is intentionally distinct from BytePlus ModelArk: Seevio\n * exposes its own asynchronous task API and credit-reservation semantics.\n */\nexport interface SeevioOptions extends BaseAIOptions {\n /** Selects Seevio's native asynchronous video API. */\n type: 'seevio';\n /** API key. Falls back to `SEEVIO_API_KEY` in the Node factory. */\n apiKey?: string;\n /** API root. Defaults to `https://api.seevio.ai`. */\n baseUrl?: string;\n /**\n * Reviewed HTTPS origins that may serve generated videos. Defaults to the\n * official `https://cdn.seevio.ai` origin. Redirect targets are checked\n * against this same allow-list before bytes are downloaded.\n */\n resultUrlOrigins?: string[];\n /** Maximum generated-video download size in bytes. Defaults to 200 MiB. */\n maxResultBytes?: number;\n}\n\n/** TypeSafe System One decision provider. `defaultModel` selects a Jev model. */\nexport interface TypeSafeOptions extends BaseAIOptions {\n type: 'typesafe';\n apiKey?: string;\n /** Defaults to https://api.typesafe.ai/v1. */\n baseUrl?: string;\n}\n\n/** Subset of a WebLLM `InitProgressReport` surfaced to model-load callbacks. */\nexport interface WebLLMLoadProgress {\n /** Fraction complete, 0 to 1. */\n progress: number;\n /** Human-readable status, e.g. the shard being fetched. */\n text: string;\n /** Seconds since loading started. */\n timeElapsed: number;\n}\n\n/**\n * Structural view of a WebLLM engine (`MLCEngine`, `WebWorkerMLCEngine`,\n * `ServiceWorkerMLCEngine`). Declared here so consumers need not have\n * `@mlc-ai/web-llm` installed to typecheck against this package.\n */\nexport interface WebLLMEngineLike {\n chat: {\n completions: {\n create(request: Record<string, any>): Promise<any>;\n };\n };\n interruptGenerate(): void | Promise<void>;\n unload?(): Promise<void>;\n}\n\n/**\n * In-browser provider backed by WebLLM (WebGPU). Needs the optional peer\n * dependency `@mlc-ai/web-llm`; no server and no API key. `defaultModel`\n * selects a WebLLM model id (default `Llama-3.2-1B-Instruct-q4f16_1-MLC`).\n */\nexport interface WebLLMOptions extends BaseAIOptions {\n type: 'webllm';\n /** Alias for `defaultModel`. */\n model?: string;\n /**\n * A pre-created engine, or a factory for one, e.g. `CreateWebWorkerMLCEngine`\n * so inference stays off the UI thread. When set, the provider never loads\n * or caches an engine itself and skips the WebGPU check.\n */\n engine?: WebLLMEngineLike | (() => Promise<WebLLMEngineLike>);\n /** Reports model download and compile progress while the engine loads. */\n onLoadProgress?: (report: WebLLMLoadProgress) => void;\n /** WebLLM `AppConfig` (custom `model_list`, cache backend). Defaults to the prebuilt list. */\n appConfig?: Record<string, any>;\n}\n\n/**\n * Union type for all provider options\n */\nexport type GetAIOptions =\n | OpenAIOptions\n | LiteLLMOptions\n | BifrostOptions\n | OllamaOptions\n | GeminiOptions\n | AnthropicOptions\n | HuggingFaceOptions\n | BedrockOptions\n | ClaudeCliOptions\n | Qwen3TTSOptions\n | OpenAICompatVideoOptions\n | ByteplusModelArkOptions\n | SeevioOptions\n | TypeSafeOptions\n | WebLLMOptions;\n\n/**\n * Base error class for all AI operations.\n * Provider-specific errors are mapped to subclasses for structured error handling.\n *\n * @param message - Human-readable error description\n * @param code - Machine-readable error code (e.g., 'AUTH_ERROR', 'RATE_LIMIT')\n * @param provider - Provider that raised the error (e.g., 'openai', 'anthropic')\n * @param model - Model involved in the error, if applicable\n */\nexport class AIError extends Error {\n constructor(\n message: string,\n public code: string,\n public provider?: string,\n public model?: string,\n public retryable: boolean = false,\n ) {\n super(message);\n this.name = 'AIError';\n }\n}\n\n/**\n * Thrown when API key or credentials are invalid or missing.\n *\n * @param provider - Provider that rejected authentication\n */\nexport class AuthenticationError extends AIError {\n constructor(provider?: string) {\n super('Authentication failed', 'AUTH_ERROR', provider, undefined, false);\n this.name = 'AuthenticationError';\n }\n}\n\n/** What a provider said about a rate limit, as kept on {@link RateLimitError}. */\nexport interface RateLimitErrorDetails {\n /**\n * The provider's own reason text, for example\n * `token limit exceeded (277867/250000, resets every 1h)`.\n */\n reason?: string;\n /**\n * Milliseconds until the limit resets, when the provider said so: a\n * `Retry-After` header, a reset header, or text such as \"try again in 20s\".\n */\n retryAfterMs?: number;\n /**\n * Length of the limit window the provider named without saying when it\n * resets (\"resets every 1h\"); the limit lifts within this time.\n */\n limitWindowMs?: number;\n /** Model the request was for, when known. */\n model?: string;\n /** The provider error this was mapped from. */\n cause?: unknown;\n /**\n * Longest wait still worth retrying soon. When the reset is further away\n * (`retryAfterMs`, else `limitWindowMs`), `retryable` is false. Defaults to\n * {@link DEFAULT_RATE_LIMIT_MAX_RETRY_DELAY_MS}; `rateLimit.maxRetryDelayMs`\n * overrides it for paced clients.\n */\n maxRetryDelayMs?: number;\n}\n\n/**\n * Default for {@link RateLimitErrorDetails.maxRetryDelayMs}: a rate limit that\n * resets more than a minute away is not worth retrying in-process.\n */\nexport const DEFAULT_RATE_LIMIT_MAX_RETRY_DELAY_MS = 60_000;\n\n/**\n * Whether a rate limit that lifts after `waitMs` is worth retrying soon, given\n * the longest acceptable wait. An unknown wait counts as retryable.\n */\nexport function isRateLimitRetryableSoon(\n waitMs: number | undefined,\n maxRetryDelayMs: number = DEFAULT_RATE_LIMIT_MAX_RETRY_DELAY_MS,\n): boolean {\n return waitMs === undefined || waitMs <= maxRetryDelayMs;\n}\n\nconst MAX_RATE_LIMIT_REASON_LENGTH = 500;\n\n/**\n * Thrown when the provider's rate limit has been exceeded.\n *\n * @param provider - Provider that enforced the rate limit\n * @param retryAfter - Seconds to wait before retrying, if provided by the API\n * @param details - The provider's reason text and reset hints\n */\nexport class RateLimitError extends AIError {\n /**\n * False when the limit resets further away than the longest wait worth\n * retrying soon (see {@link RateLimitErrorDetails.maxRetryDelayMs}).\n */\n declare retryable: boolean;\n /** Seconds until the limit resets, when the provider said so. */\n public retryAfter?: number;\n /** Milliseconds until the limit resets, when the provider said so. */\n public retryAfterMs?: number;\n /** Length of a limit window named without a reset time (see details). */\n public limitWindowMs?: number;\n /** The provider's own reason text, when it sent one. */\n public reason?: string;\n\n constructor(\n provider?: string,\n retryAfter?: number,\n details: RateLimitErrorDetails = {},\n ) {\n const retryAfterMs = finiteNonNegative(\n details.retryAfterMs ??\n (retryAfter !== undefined ? retryAfter * 1000 : undefined),\n );\n const seconds =\n finiteNonNegative(retryAfter) ??\n (retryAfterMs !== undefined ? Math.ceil(retryAfterMs / 1000) : undefined);\n const reason = details.reason\n ?.replace(/\\s+/g, ' ')\n .trim()\n .slice(0, MAX_RATE_LIMIT_REASON_LENGTH);\n super(\n `Rate limit exceeded${reason ? `: ${reason}` : ''}${seconds ? `, retry after ${seconds}s` : ''}`,\n 'RATE_LIMIT',\n provider,\n details.model,\n true,\n );\n this.name = 'RateLimitError';\n this.retryAfter = seconds;\n this.retryAfterMs = retryAfterMs;\n this.limitWindowMs = finiteNonNegative(details.limitWindowMs);\n // A limit that lifts far away is not worth retrying soon: job runners\n // should reschedule after `retryAfterMs` (or `limitWindowMs`) instead.\n this.retryable = isRateLimitRetryableSoon(\n this.retryAfterMs ?? this.limitWindowMs,\n details.maxRetryDelayMs,\n );\n this.reason = reason || undefined;\n if (details.cause !== undefined) this.cause = details.cause;\n }\n}\n\nfunction finiteNonNegative(value: number | undefined): number | undefined {\n return typeof value === 'number' && Number.isFinite(value)\n ? Math.max(0, value)\n : undefined;\n}\n\n/**\n * Thrown when the requested model does not exist or is not available.\n *\n * @param model - The model identifier that was not found\n * @param provider - Provider that was queried\n */\nexport class ModelNotFoundError extends AIError {\n constructor(model: string, provider?: string) {\n super(\n `Model not found: ${model}`,\n 'MODEL_NOT_FOUND',\n provider,\n model,\n false,\n );\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Thrown when the input exceeds the model's maximum context window.\n *\n * @param provider - Provider that reported the error\n * @param model - Model whose context limit was exceeded\n */\nexport class ContextLengthError extends AIError {\n constructor(provider?: string, model?: string) {\n super(\n 'Input exceeds maximum context length',\n 'CONTEXT_LENGTH_EXCEEDED',\n provider,\n model,\n false,\n );\n this.name = 'ContextLengthError';\n }\n}\n\n/**\n * Thrown by the `webllm` provider when the browser exposes no WebGPU\n * (`navigator.gpu` is absent). Catch it to show a fallback.\n */\nexport class WebGPUUnavailableError extends AIError {\n constructor(provider = 'webllm', detail?: string) {\n super(\n detail ??\n 'WebGPU is not available in this environment (navigator.gpu is missing); on-device inference cannot run.',\n 'WEBGPU_UNAVAILABLE',\n provider,\n undefined,\n false,\n );\n this.name = 'WebGPUUnavailableError';\n }\n}\n\n/**\n * Thrown by the `webllm` provider when the optional peer dependency\n * `@mlc-ai/web-llm` cannot be imported.\n */\nexport class WebLLMPeerMissingError extends AIError {\n constructor(cause?: unknown) {\n super(\n 'The webllm provider needs the optional peer dependency @mlc-ai/web-llm. Install it with `pnpm add @mlc-ai/web-llm` (or the npm/yarn equivalent).',\n 'WEBLLM_PEER_MISSING',\n 'webllm',\n undefined,\n false,\n );\n this.name = 'WebLLMPeerMissingError';\n if (cause !== undefined) this.cause = cause;\n }\n}\n\n/**\n * Thrown when content is blocked by the provider's safety/content filters.\n *\n * @param provider - Provider that filtered the content\n * @param model - Model that triggered the filter\n */\nexport class ContentFilterError extends AIError {\n constructor(provider?: string, model?: string) {\n super(\n 'Content filtered by safety systems',\n 'CONTENT_FILTERED',\n provider,\n model,\n false,\n );\n this.name = 'ContentFilterError';\n }\n}\n\n// ============================================================================\n// Video Generation Types\n// ============================================================================\n\n/**\n * Lifecycle status of an asynchronous video-generation job.\n */\nexport type VideoGenerationStatus =\n | 'queued'\n | 'running'\n | 'succeeded'\n | 'failed'\n | 'cancelled';\n\n/**\n * A reference image supplied to guide video generation (image-to-video,\n * first/last frame, subject/style conditioning).\n */\nexport interface VideoGenerationReferenceImage {\n /**\n * Image as a URL, base64 data URL, or raw bytes.\n */\n image: string | Buffer;\n\n /**\n * MIME type of `image`, required when `image` is a Buffer.\n */\n mimeType?: string;\n\n /**\n * Provider-specific reference role, e.g. `'first_frame'`, `'last_frame'`,\n * `'reference_image'`, `'style'`, or `'asset'`. Providers that don't\n * recognize a role fall back to their default reference behavior.\n */\n role?: string;\n}\n\n/** A URL-based image, video, or audio asset used to guide video generation. */\nexport interface VideoGenerationReferenceMedia {\n /** Media category understood by providers that support multimodal references. */\n type: 'image' | 'video' | 'audio';\n /** Public URL the provider can retrieve. */\n url: string;\n /** Optional media MIME type retained for provider-specific validation. */\n mimeType?: string;\n /** Optional playback duration used by providers with media-duration limits. */\n durationSeconds?: number;\n}\n\n/**\n * Options for submitting an asynchronous video-generation job.\n */\nexport interface VideoGenerationOptions extends AIRequestControls {\n /**\n * Model to use for video generation (provider-specific id).\n */\n model?: string;\n\n /**\n * Text description of the desired video. Optional for providers that\n * support pure image-to-video generation from `referenceImages` alone.\n */\n prompt?: string;\n\n /**\n * Explicit statement of what should NOT appear in the generated video.\n * Support varies by provider; unsupported providers ignore this field.\n */\n negativePrompt?: string;\n\n /**\n * Reference image(s) for image-to-video or style/subject conditioning.\n */\n referenceImages?: VideoGenerationReferenceImage[];\n\n /**\n * Provider-neutral URL-based image, video, and audio reference assets.\n * Existing `referenceImages` remains supported for providers that accept\n * bytes or data URLs; providers such as Seevio that retrieve public assets\n * directly require HTTPS URLs here.\n */\n referenceMedia?: VideoGenerationReferenceMedia[];\n\n /**\n * Duration of the generated clip in seconds.\n */\n durationSeconds?: number;\n\n /**\n * Resolution label such as `'720p'` or `'1080p'` (provider-dependent).\n */\n resolution?: string;\n\n /**\n * Aspect ratio such as `'16:9'`, `'9:16'`, or `'1:1'`.\n */\n aspectRatio?: string;\n\n /** Whether a provider that supports native audio should generate it. */\n generateAudio?: boolean;\n\n /** Whether a provider that supports it should return a final-frame URL. */\n returnLastFrame?: boolean;\n\n /**\n * Frames per second for the generated video. Support varies by provider.\n */\n fps?: number;\n\n /**\n * Random seed for deterministic generation where supported.\n */\n seed?: number;\n\n /**\n * Custom tags to attach to the usage event emitted for this job.\n * Merged over any global `usageTags` from provider options.\n */\n usageTags?: Record<string, string>;\n}\n\n/**\n * Serializable handle for an in-flight or completed video-generation job.\n *\n * Consumers persist this (e.g. as JSON in a database checkpoint) so they can\n * resume polling after a process restart. Every field is plain\n * JSON-serializable data — no closures, streams, or provider client\n * instances — so the handle round-trips through `JSON.stringify` /\n * `JSON.parse` unchanged.\n *\n * `jobId` and `provider` are the load-bearing fields every provider needs to\n * resume polling; `raw` may carry provider-specific resume context (e.g.\n * which auth mode a job was submitted under) that is opaque to callers but\n * required for a provider to correctly service the resumed request.\n * Consumers must persist and pass back the **whole** handle verbatim —\n * reconstructing a handle from just `jobId` (dropping `raw`) is not\n * guaranteed to work.\n */\nexport interface VideoGenerationJob {\n /**\n * Provider-assigned job or operation identifier.\n */\n jobId: string;\n\n /**\n * Provider that created the job (e.g. `'gemini'`, `'byteplus-modelark'`).\n */\n provider: string;\n\n /**\n * Model used for the job.\n */\n model: string;\n\n /**\n * ISO-8601 timestamp for when the job was submitted.\n */\n createdAt: string;\n\n /**\n * Provider-specific data needed to resume polling (e.g. an operation\n * resource name shape, or routing hints). Opaque to callers; always\n * JSON-serializable.\n */\n raw?: Record<string, unknown>;\n}\n\n/**\n * Result of a completed video-generation job.\n */\nexport interface VideoGenerationResult {\n /**\n * Temporary or permanent URL to the generated video, when the provider\n * returns a downloadable link instead of inline bytes.\n */\n url?: string;\n\n /**\n * Raw generated video bytes, when the provider returns inline data\n * instead of (or in addition to) a URL.\n */\n data?: Buffer;\n\n /**\n * MIME type of the generated video (e.g. `'video/mp4'`).\n */\n mimeType: string;\n\n /**\n * Duration of the generated video in seconds, where reported.\n */\n durationSeconds?: number;\n\n /**\n * Width of the generated video in pixels, where reported.\n */\n width?: number;\n\n /**\n * Height of the generated video in pixels, where reported.\n */\n height?: number;\n\n /** Time at which a temporary result URL expires, when the provider reports it. */\n expiresAt?: string;\n\n /** Optional URL for a returned final frame, when requested and supported. */\n lastFrameUrl?: string;\n}\n\n/** Provider-neutral credit reservation and settlement metadata for a video job. */\nexport interface VideoGenerationBillingMetadata {\n /** Credits reserved or settled for the task, when the provider reports them. */\n credits?: number;\n /** Normalized reservation lifecycle state. */\n status?: 'reserved' | 'charged' | 'refunded' | 'refund_failed';\n /** An unrecognized provider billing state retained for diagnostics. */\n rawStatus?: string;\n}\n\n/**\n * Status snapshot for a video-generation job, as returned by\n * {@link AIInterface.getVideoGenerationJob}.\n */\nexport interface VideoGenerationStatusResult {\n /**\n * Current lifecycle status of the job.\n */\n status: VideoGenerationStatus;\n\n /**\n * Provider-reported progress percentage (0-100), where available.\n */\n progress?: number;\n\n /**\n * Human-readable error message, populated when `status` is `'failed'`.\n */\n error?: string;\n\n /**\n * The provider's raw, unrecognized status string. Only set when the\n * provider reported a status value this package doesn't have an explicit\n * mapping for. Providers must never invent a terminal state (`'failed'`\n * or `'succeeded'`) for a status they don't understand — an unrecognized\n * value is mapped to `'running'` with the original string preserved here,\n * so a mid-render status a provider adds later (e.g. a new gateway\n * synonym for \"processing\") never gets misread as a failure that would\n * cause a caller to resubmit and double-bill.\n */\n rawStatus?: string;\n\n /**\n * Populated once `status` is `'succeeded'`. For providers whose status\n * endpoint returns the payload inline, this is equivalent to calling\n * {@link AIInterface.fetchVideoGenerationResult} with the same handle.\n * Providers whose result requires a separate download (e.g. large binary\n * content behind its own endpoint) may populate metadata here (mimeType,\n * durationSeconds, width, height) while leaving `url`/`data` unset until\n * `fetchVideoGenerationResult` is called explicitly.\n */\n result?: VideoGenerationResult;\n\n /** Provider-reported credit reservation or settlement metadata. */\n billing?: VideoGenerationBillingMetadata;\n}\n\n// ============================================================================\n// Text-to-Speech (TTS) Types\n// ============================================================================\n\n/**\n * Options for text-to-speech synthesis\n */\nexport interface TTSOptions {\n /**\n * TTS model to use (e.g., 'qwen3-tts-1.7b', 'qwen3-tts-0.6b')\n */\n model?: string;\n\n /**\n * Voice ID or profile reference to use for synthesis\n */\n voice?: string;\n\n /**\n * ISO language code (e.g., 'en-US', 'zh-CN')\n * Supported: Chinese, English, Japanese, Korean, German, French, Russian, Portuguese, Spanish, Italian\n */\n language?: string;\n\n /**\n * Speech rate multiplier (0.5 - 2.0, default: 1.0)\n */\n speed?: number;\n\n /**\n * Pitch adjustment in semitones (-20 to 20, default: 0)\n */\n pitch?: number;\n\n /**\n * Output audio format\n */\n outputFormat?: 'wav' | 'mp3' | 'ogg';\n\n /**\n * Whether to stream the audio output\n */\n stream?: boolean;\n\n /**\n * Whether to include word-level timing information for lip-sync\n */\n includeWordTimings?: boolean;\n}\n\n/**\n * Options for voice cloning from audio samples\n */\nexport interface VoiceCloneOptions {\n /**\n * Model to use for voice cloning\n */\n model?: string;\n\n /**\n * Audio sample for cloning (3+ seconds recommended)\n * Can be a Buffer or base64-encoded string\n */\n sampleAudio: Buffer | string;\n\n /**\n * MIME type of the sample audio (e.g., 'audio/wav', 'audio/mp3')\n */\n sampleMimeType?: string;\n\n /**\n * Name for the cloned voice profile\n */\n name?: string;\n\n /**\n * Description of the voice\n */\n description?: string;\n\n /**\n * Language of the voice sample\n */\n language?: string;\n}\n\n/**\n * Options for voice design via natural language description\n */\nexport interface VoiceDesignOptions {\n /**\n * Model to use for voice design\n */\n model?: string;\n\n /**\n * Natural language description of the desired voice\n * e.g., \"warm female voice with slight British accent, professional news anchor tone\"\n */\n description: string;\n\n /**\n * Primary language for the voice\n */\n language?: string;\n\n /**\n * Target gender for the voice\n */\n gender?: 'male' | 'female' | 'neutral';\n}\n\n/**\n * Word timing information for lip-sync alignment\n */\nexport interface WordTiming {\n /**\n * The word or phoneme\n */\n word: string;\n\n /**\n * Start time in seconds\n */\n start: number;\n\n /**\n * End time in seconds\n */\n end: number;\n}\n\n/**\n * Response from text-to-speech synthesis\n */\nexport interface TTSResponse {\n /**\n * Generated audio data\n */\n audio: Buffer;\n\n /**\n * MIME type of the audio (e.g., 'audio/wav', 'audio/mp3')\n */\n mimeType: string;\n\n /**\n * Duration of the audio in seconds\n */\n duration: number;\n\n /**\n * Word-level timing information for lip-sync (if requested)\n */\n wordTimings?: WordTiming[];\n\n /**\n * Model used for generation\n */\n model?: string;\n\n /**\n * Sample rate in Hz (e.g., 22050, 44100)\n */\n sampleRate?: number;\n}\n\n/**\n * Voice profile information\n */\nexport interface Voice {\n /**\n * Unique identifier for the voice\n */\n id: string;\n\n /**\n * Human-readable name for the voice\n */\n name: string;\n\n /**\n * Primary language of the voice (ISO code)\n */\n language: string;\n\n /**\n * Gender of the voice\n */\n gender?: 'male' | 'female' | 'neutral';\n\n /**\n * Description of the voice characteristics\n */\n description?: string;\n\n /**\n * Whether this is a cloned voice\n */\n isCloned?: boolean;\n\n /**\n * Whether this was designed via natural language\n */\n isDesigned?: boolean;\n\n /**\n * URL to a sample of this voice (if available)\n */\n sampleUrl?: string;\n\n /**\n * Provider-specific voice data/embedding\n */\n voiceData?: Record<string, any>;\n}\n\n/**\n * Options for listing available voices\n */\nexport interface VoiceListOptions {\n /**\n * Filter by language\n */\n language?: string;\n\n /**\n * Filter by gender\n */\n gender?: 'male' | 'female' | 'neutral';\n\n /**\n * Include cloned voices\n */\n includeCloned?: boolean;\n\n /**\n * Include designed voices\n */\n includeDesigned?: boolean;\n}\n","import type {\n AIGenerationLimits,\n AIInterface,\n AIReasoningOptions,\n AIRequestControls,\n AIRequestEvent,\n AIRequestOperation,\n AIRequestStatus,\n BaseAIOptions,\n ChatOptions,\n ImageGenerationOptions,\n} from './types';\nimport { AIError } from './types';\n\nexport const DEFAULT_AI_TIMEOUT_MS = 120_000;\nexport const DEFAULT_AI_MAX_RETRIES = 0;\n\nexport const DEFAULT_AI_GENERATION_LIMITS: Readonly<AIGenerationLimits> =\n Object.freeze({\n // Hard ceiling: a deployment-set value is enforced; the default sits above\n // every current model's documented output limit so an explicit caller\n // request is only bounded by the model/provider.\n maxOutputTokens: 131_072,\n // Used only when the caller does not pass maxTokens (spend guardrail).\n defaultOutputTokens: 4096,\n maxReasoningTokens: 1024,\n maxImagesPerRequest: 1,\n onExceeded: 'error',\n });\n\nexport interface NormalizedBaseAIOptions extends BaseAIOptions {\n timeout: number;\n maxRetries: number;\n generationLimits: AIGenerationLimits;\n}\n\nexport interface PreparedRequestControls {\n signal: AbortSignal;\n timeout: number;\n cleanup(): void;\n didTimeout(): boolean;\n}\n\nfunction positiveInteger(\n value: number | undefined,\n fallback: number,\n field: string,\n): number {\n if (value === undefined) return fallback;\n if (!Number.isFinite(value) || value <= 0) {\n throw new AIError(\n `${field} must be a positive finite number`,\n 'AI_LIMIT_INVALID',\n );\n }\n return Math.trunc(value);\n}\n\nexport function normalizeBaseAIOptions<T extends BaseAIOptions>(\n options: T,\n): T & NormalizedBaseAIOptions {\n const configuredLimits = options.generationLimits || {};\n const generationLimits: AIGenerationLimits = {\n maxOutputTokens: positiveInteger(\n configuredLimits.maxOutputTokens,\n DEFAULT_AI_GENERATION_LIMITS.maxOutputTokens,\n 'generationLimits.maxOutputTokens',\n ),\n defaultOutputTokens: Math.min(\n positiveInteger(\n configuredLimits.defaultOutputTokens,\n DEFAULT_AI_GENERATION_LIMITS.defaultOutputTokens as number,\n 'generationLimits.defaultOutputTokens',\n ),\n positiveInteger(\n configuredLimits.maxOutputTokens,\n DEFAULT_AI_GENERATION_LIMITS.maxOutputTokens,\n 'generationLimits.maxOutputTokens',\n ),\n ),\n maxReasoningTokens: positiveInteger(\n configuredLimits.maxReasoningTokens,\n DEFAULT_AI_GENERATION_LIMITS.maxReasoningTokens,\n 'generationLimits.maxReasoningTokens',\n ),\n maxImagesPerRequest: positiveInteger(\n configuredLimits.maxImagesPerRequest,\n DEFAULT_AI_GENERATION_LIMITS.maxImagesPerRequest,\n 'generationLimits.maxImagesPerRequest',\n ),\n onExceeded:\n configuredLimits.onExceeded || DEFAULT_AI_GENERATION_LIMITS.onExceeded,\n };\n\n if (!['error', 'clamp'].includes(generationLimits.onExceeded)) {\n throw new AIError(\n 'generationLimits.onExceeded must be \"error\" or \"clamp\"',\n 'AI_LIMIT_INVALID',\n );\n }\n\n return {\n ...options,\n timeout: positiveInteger(options.timeout, DEFAULT_AI_TIMEOUT_MS, 'timeout'),\n maxRetries: (() => {\n if (options.maxRetries === undefined) return DEFAULT_AI_MAX_RETRIES;\n if (!Number.isFinite(options.maxRetries) || options.maxRetries < 0) {\n throw new AIError(\n 'maxRetries must be a non-negative finite number',\n 'AI_LIMIT_INVALID',\n );\n }\n return Math.trunc(options.maxRetries);\n })(),\n generationLimits,\n };\n}\n\nfunction reasoningTokensForEffort(\n effort: AIReasoningOptions['effort'] | false | undefined,\n): number | undefined {\n switch (effort) {\n case false:\n case 'none':\n return 0;\n case 'minimal':\n return 1024;\n case 'low':\n return 2048;\n case 'medium':\n return 4096;\n case 'high':\n return 8192;\n default:\n return undefined;\n }\n}\n\nfunction enforceLimit(\n requested: number,\n limit: number,\n behavior: AIGenerationLimits['onExceeded'],\n label: string,\n provider?: string,\n model?: string,\n): number {\n if (!Number.isFinite(requested) || requested < 0) {\n throw new AIError(\n `${label} must be a non-negative finite number`,\n 'AI_LIMIT_INVALID',\n provider,\n model,\n );\n }\n const normalized = Math.trunc(requested);\n if (normalized <= limit) return normalized;\n if (behavior === 'clamp') return limit;\n throw new AIError(\n `${label} ${normalized} exceeds configured ceiling ${limit}`,\n 'AI_LIMIT_EXCEEDED',\n provider,\n model,\n );\n}\n\nexport function normalizeChatOptions<\n T extends AIRequestControls & {\n maxTokens?: number;\n thinkingLevel?: ChatOptions['thinkingLevel'];\n includeThoughts?: boolean;\n },\n>(\n providerOptions: BaseAIOptions,\n options: T,\n provider?: string,\n model?: string,\n): T & { maxTokens: number; reasoning: AIReasoningOptions } {\n const normalizedProvider = normalizeBaseAIOptions(providerOptions);\n const limits = normalizedProvider.generationLimits;\n const requestedOutput =\n options.maxTokens ?? limits.defaultOutputTokens ?? limits.maxOutputTokens;\n const legacyEffort =\n options.thinkingLevel ??\n (\n providerOptions as BaseAIOptions & {\n thinkingLevel?: ChatOptions['thinkingLevel'];\n }\n ).thinkingLevel;\n const reasoningWasRequested =\n options.reasoning !== undefined ||\n legacyEffort !== undefined ||\n options.includeThoughts === true;\n const requestedReasoning = reasoningWasRequested\n ? (options.reasoning?.maxTokens ??\n reasoningTokensForEffort(options.reasoning?.effort ?? legacyEffort) ??\n limits.maxReasoningTokens)\n : 0;\n\n return {\n ...options,\n maxTokens: enforceLimit(\n requestedOutput,\n limits.maxOutputTokens,\n limits.onExceeded,\n 'maxTokens',\n provider,\n model,\n ),\n reasoning: {\n ...options.reasoning,\n maxTokens: enforceLimit(\n requestedReasoning,\n limits.maxReasoningTokens,\n limits.onExceeded,\n 'reasoning.maxTokens',\n provider,\n model,\n ),\n includeThoughts:\n options.reasoning?.includeThoughts ?? options.includeThoughts,\n },\n };\n}\n\nexport function normalizeImageGenerationOptions<\n T extends ImageGenerationOptions,\n>(\n providerOptions: BaseAIOptions,\n options: T,\n provider?: string,\n model?: string,\n): T & { n: number } {\n const normalizedProvider = normalizeBaseAIOptions(providerOptions);\n const limits = normalizedProvider.generationLimits;\n return {\n ...options,\n n: enforceLimit(\n options.n ?? 1,\n limits.maxImagesPerRequest,\n limits.onExceeded,\n 'n',\n provider,\n model,\n ),\n };\n}\n\nexport function prepareRequestControls(\n providerOptions: BaseAIOptions,\n requestOptions: AIRequestControls = {},\n): PreparedRequestControls {\n const normalized = normalizeBaseAIOptions(providerOptions);\n const timeout = positiveInteger(\n requestOptions.timeout,\n normalized.timeout,\n 'timeout',\n );\n const controller = new AbortController();\n let timedOut = false;\n\n const abortFromCaller = () => controller.abort(requestOptions.signal?.reason);\n if (requestOptions.signal?.aborted) {\n abortFromCaller();\n } else {\n requestOptions.signal?.addEventListener('abort', abortFromCaller, {\n once: true,\n });\n }\n\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort(new Error(`AI request timed out after ${timeout}ms`));\n }, timeout);\n\n return {\n signal: controller.signal,\n timeout,\n didTimeout: () => timedOut,\n cleanup: () => {\n clearTimeout(timer);\n requestOptions.signal?.removeEventListener('abort', abortFromCaller);\n },\n };\n}\n\nfunction mergeTags(\n providerOptions: BaseAIOptions,\n callTags?: Record<string, string>,\n): Record<string, string> | undefined {\n return providerOptions.usageTags || callTags\n ? { ...providerOptions.usageTags, ...callTags }\n : undefined;\n}\n\nexport function emitRequestEvent(\n providerOptions: BaseAIOptions,\n event: Omit<AIRequestEvent, 'tags'> & {\n tags?: Record<string, string>;\n },\n): void {\n if (!providerOptions.onRequest) return;\n try {\n providerOptions.onRequest({\n ...event,\n tags: mergeTags(providerOptions, event.tags),\n });\n } catch {\n // Consumer telemetry must never affect an AI request.\n }\n}\n\nexport function classifyRequestFailure(\n error: unknown,\n didTimeout = false,\n): { status: AIRequestStatus; errorCode?: string } {\n const code = error instanceof AIError ? error.code : undefined;\n if (code === 'AI_LIMIT_EXCEEDED' || code === 'AI_LIMIT_INVALID') {\n return { status: 'rejected', errorCode: code };\n }\n if (\n didTimeout ||\n code === 'AI_TIMEOUT' ||\n code === 'TIMEOUT' ||\n code === 'REQUEST_TIMEOUT'\n ) {\n return { status: 'timed_out', errorCode: code || 'AI_TIMEOUT' };\n }\n if (error instanceof Error && error.name === 'AbortError') {\n return { status: 'aborted', errorCode: 'ABORTED' };\n }\n if (code === 'AI_ABORTED' || code === 'REQUEST_ABORTED') {\n return { status: 'aborted', errorCode: code };\n }\n return {\n status: 'failed',\n errorCode: code || (error instanceof Error ? error.name : undefined),\n };\n}\n\nexport function requestEventBase(options: {\n providerOptions: BaseAIOptions;\n provider: string;\n model: string;\n operation: AIRequestOperation;\n callOptions?: { maxTokens?: number; usageTags?: Record<string, string> };\n effectiveMaxOutputTokens?: number;\n}): Omit<AIRequestEvent, 'status' | 'duration'> & {\n tags?: Record<string, string>;\n} {\n const normalized = normalizeBaseAIOptions(options.providerOptions);\n return {\n provider: options.provider,\n model: options.model,\n operation: options.operation,\n attempts: normalized.maxRetries + 1,\n requestedMaxOutputTokens:\n options.operation === 'decide'\n ? undefined\n : options.callOptions?.maxTokens,\n effectiveMaxOutputTokens:\n options.operation === 'decide' ||\n options.operation === 'generateImage' ||\n VIDEO_GENERATION_OPERATIONS.has(options.operation)\n ? undefined\n : (options.effectiveMaxOutputTokens ??\n Math.min(\n options.callOptions?.maxTokens ??\n normalized.generationLimits.defaultOutputTokens ??\n normalized.generationLimits.maxOutputTokens,\n normalized.generationLimits.maxOutputTokens,\n )),\n tags: options.callOptions?.usageTags,\n };\n}\n\nconst OBSERVED_OPERATIONS = new Set<AIRequestOperation>([\n 'decide',\n 'chat',\n 'complete',\n 'message',\n 'describeImage',\n 'generateImage',\n 'stream',\n 'submitVideoGenerationJob',\n 'getVideoGenerationJob',\n 'fetchVideoGenerationResult',\n 'cancelVideoGenerationJob',\n]);\n\n/**\n * `getVideoGenerationJob` / `fetchVideoGenerationResult` /\n * `cancelVideoGenerationJob` take a `VideoGenerationJob` handle as their\n * first (and only) argument rather than a chat-shaped `options` object as\n * the second argument. The handle still carries a `model` field, so\n * `callOptionsFor` reads it from the same position as `submitVideoGenerationJob`'s\n * `options` (index 0) rather than index 1.\n */\nconst VIDEO_HANDLE_OPERATIONS = new Set<AIRequestOperation>([\n 'getVideoGenerationJob',\n 'fetchVideoGenerationResult',\n 'cancelVideoGenerationJob',\n]);\n\nconst VIDEO_GENERATION_OPERATIONS = new Set<AIRequestOperation>([\n 'submitVideoGenerationJob',\n ...VIDEO_HANDLE_OPERATIONS,\n]);\n\nfunction callOptionsFor(\n operation: AIRequestOperation,\n args: unknown[],\n):\n | (AIRequestControls & {\n model?: string;\n maxTokens?: number;\n usageTags?: Record<string, string>;\n })\n | undefined {\n const index =\n operation === 'decide'\n ? 1\n : operation === 'describeImage'\n ? 2\n : operation === 'submitVideoGenerationJob' ||\n VIDEO_HANDLE_OPERATIONS.has(operation)\n ? 0\n : 1;\n const value = args[index];\n return value && typeof value === 'object'\n ? (value as AIRequestControls & {\n model?: string;\n maxTokens?: number;\n usageTags?: Record<string, string>;\n })\n : undefined;\n}\n\nfunction providerName(options: BaseAIOptions): string {\n const configured = (options as BaseAIOptions & { type?: string }).type;\n return configured || 'openai';\n}\n\nfunction effectiveOutputTokens(\n operation: AIRequestOperation,\n providerOptions: BaseAIOptions,\n callOptions:\n | (AIRequestControls & {\n model?: string;\n maxTokens?: number;\n n?: number;\n })\n | undefined,\n): number | undefined {\n if (\n operation === 'decide' ||\n operation === 'generateImage' ||\n VIDEO_GENERATION_OPERATIONS.has(operation)\n ) {\n // maxTokens/reasoning concepts don't apply to video-generation jobs;\n // avoid attaching a misleading chat-shaped token ceiling to the event.\n if (operation === 'generateImage') {\n normalizeImageGenerationOptions(\n providerOptions,\n callOptions || {},\n providerName(providerOptions),\n callOptions?.model,\n );\n }\n return undefined;\n }\n\n return normalizeChatOptions(\n providerOptions,\n callOptions || {},\n providerName(providerOptions),\n callOptions?.model || providerOptions.defaultModel,\n ).maxTokens;\n}\n\n/**\n * Wrap a public provider instance with prompt-free lifecycle observation.\n * Provider adapters still enforce limits internally so direct construction is\n * protected; this wrapper adds one terminal event to the public getAI() path.\n */\nexport function createObservedAI<T extends AIInterface>(\n client: T,\n providerOptions: BaseAIOptions,\n): T {\n if (!providerOptions.onRequest) return client;\n\n return new Proxy(client, {\n get(target, property, receiver) {\n const value = Reflect.get(target, property, receiver);\n if (\n typeof property !== 'string' ||\n typeof value !== 'function' ||\n !OBSERVED_OPERATIONS.has(property as AIRequestOperation)\n ) {\n return typeof value === 'function' ? value.bind(target) : value;\n }\n\n const operation = property as AIRequestOperation;\n if (operation === 'stream') {\n return async function* (...args: unknown[]) {\n const startedAt = Date.now();\n const callOptions = callOptionsFor(operation, args);\n let base: ReturnType<typeof requestEventBase> | undefined;\n try {\n base = requestEventBase({\n providerOptions,\n provider: providerName(providerOptions),\n model:\n callOptions?.model || providerOptions.defaultModel || 'unknown',\n operation,\n callOptions,\n effectiveMaxOutputTokens: effectiveOutputTokens(\n operation,\n providerOptions,\n callOptions,\n ),\n });\n const iterable = Reflect.apply(\n value,\n target,\n args,\n ) as AsyncIterable<string>;\n for await (const chunk of iterable) yield chunk;\n emitRequestEvent(providerOptions, {\n ...base,\n status: 'succeeded',\n duration: Date.now() - startedAt,\n });\n } catch (error) {\n const failure = classifyRequestFailure(error);\n base ||= requestEventBase({\n providerOptions,\n provider: providerName(providerOptions),\n model:\n callOptions?.model || providerOptions.defaultModel || 'unknown',\n operation,\n callOptions,\n });\n emitRequestEvent(providerOptions, {\n ...base,\n ...failure,\n duration: Date.now() - startedAt,\n });\n throw error;\n }\n };\n }\n\n return async (...args: unknown[]) => {\n const startedAt = Date.now();\n const callOptions = callOptionsFor(operation, args);\n let base: ReturnType<typeof requestEventBase> | undefined;\n try {\n base = requestEventBase({\n providerOptions,\n provider: providerName(providerOptions),\n model:\n callOptions?.model || providerOptions.defaultModel || 'unknown',\n operation,\n callOptions,\n effectiveMaxOutputTokens: effectiveOutputTokens(\n operation,\n providerOptions,\n callOptions,\n ),\n });\n const result = await Reflect.apply(value, target, args);\n emitRequestEvent(providerOptions, {\n ...base,\n status: 'succeeded',\n duration: Date.now() - startedAt,\n });\n return result;\n } catch (error) {\n const failure = classifyRequestFailure(error);\n base ||= requestEventBase({\n providerOptions,\n provider: providerName(providerOptions),\n model:\n callOptions?.model || providerOptions.defaultModel || 'unknown',\n operation,\n callOptions,\n });\n emitRequestEvent(providerOptions, {\n ...base,\n ...failure,\n duration: Date.now() - startedAt,\n });\n throw error;\n }\n };\n },\n });\n}\n","/**\n * Shared usage-event emission helper.\n *\n * Every provider delegates to this so the tag-merge + try/catch semantics\n * are defined in exactly one place.\n */\n\nimport type { BaseAIOptions, TokenUsage, UsageEvent } from '../types';\n\n/**\n * Emit a usage event to the `onUsage` callback configured on provider options.\n *\n * @param providerOptions - The provider's stored options (for `onUsage` and global `usageTags`).\n * @param providerName - Provider identifier (e.g. `'openai'`).\n * @param operation - The operation type that generated this usage.\n * @param model - Model that was used.\n * @param usage - Token usage breakdown, if available.\n * @param startTime - `Date.now()` captured before the API call.\n * @param callTags - Per-call `usageTags` from the method's options.\n */\nexport function emitUsage(\n providerOptions: BaseAIOptions,\n providerName: string,\n operation: UsageEvent['operation'],\n model: string,\n usage: TokenUsage | undefined,\n startTime: number,\n callTags?: Record<string, string>,\n): void {\n if (!providerOptions.onUsage) return;\n\n const globalTags = providerOptions.usageTags;\n const tags =\n globalTags || callTags ? { ...globalTags, ...callTags } : undefined;\n\n try {\n providerOptions.onUsage({\n provider: providerName,\n model,\n operation,\n usage,\n duration: Date.now() - startTime,\n timestamp: new Date(),\n tags,\n });\n } catch {\n // Silently swallow consumer errors\n }\n}\n"],"mappings":";;;;AAiIA,IAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;AA0CA,SAAgB,mBAAmB,SAAyC;CAC1E,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,OAAO,QACJ,QAAQ,SAAkC,KAAK,SAAS,MAAM,CAAC,CAC/D,KAAK,SAAS,KAAK,IAAI,CAAC,CACxB,KAAK,IAAI;AACd;;;;;;;;;;AAypEA,IAAa,UAAb,cAA6B,MAAM;CAGxB;CACA;CACA;CACA;CALT,YACE,SACA,MACA,UACA,OACA,YAA4B,OAC5B;EACA,MAAM,OAAO;EALN,KAAA,OAAA;EACA,KAAA,WAAA;EACA,KAAA,QAAA;EACA,KAAA,YAAA;EAGP,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,sBAAb,cAAyC,QAAQ;CAC/C,YAAY,UAAmB;EAC7B,MAAM,yBAAyB,cAAc,UAAU,KAAA,GAAW,KAAK;EACvE,KAAK,OAAO;CACd;AACF;;;;;AAoCA,IAAa,wCAAwC;;;;;AAMrD,SAAgB,yBACd,QACA,kBAA0B,uCACjB;CACT,OAAO,WAAW,KAAA,KAAa,UAAU;AAC3C;AAEA,IAAM,+BAA+B;;;;;;;;AASrC,IAAa,iBAAb,cAAoC,QAAQ;;CAO1C;;CAEA;;CAEA;;CAEA;CAEA,YACE,UACA,YACA,UAAiC,CAAC,GAClC;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