@happyvertical/ai 0.86.3 → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +60 -2
  2. package/dist/chunks/{anthropic-DuYUnw8j.js → anthropic-ByuqC5mC.js} +4 -4
  3. package/dist/chunks/{anthropic-DuYUnw8j.js.map → anthropic-ByuqC5mC.js.map} +1 -1
  4. package/dist/chunks/{bedrock-ikQJAwWB.js → bedrock-BeVCmkrS.js} +3 -3
  5. package/dist/chunks/{bedrock-ikQJAwWB.js.map → bedrock-BeVCmkrS.js.map} +1 -1
  6. package/dist/chunks/{bifrost-CaYhelVL.js → bifrost-DvYZ3LNf.js} +4 -4
  7. package/dist/chunks/{bifrost-CaYhelVL.js.map → bifrost-DvYZ3LNf.js.map} +1 -1
  8. package/dist/chunks/{byteplus-modelark-B8l8sPXu.js → byteplus-modelark-DaF0U4n1.js} +4 -4
  9. package/dist/chunks/{byteplus-modelark-B8l8sPXu.js.map → byteplus-modelark-DaF0U4n1.js.map} +1 -1
  10. package/dist/chunks/{claude-cli-DeTKk9nu.js → claude-cli-BH_C62dV.js} +3 -3
  11. package/dist/chunks/{claude-cli-DeTKk9nu.js.map → claude-cli-BH_C62dV.js.map} +1 -1
  12. package/dist/chunks/{gateway-admin-DJXEDpUP.js → gateway-admin-B4RSBDmo.js} +2 -2
  13. package/dist/chunks/{gateway-admin-DJXEDpUP.js.map → gateway-admin-B4RSBDmo.js.map} +1 -1
  14. package/dist/chunks/{gemini-BT8fjXWz.js → gemini-GQdugon1.js} +4 -4
  15. package/dist/chunks/{gemini-BT8fjXWz.js.map → gemini-GQdugon1.js.map} +1 -1
  16. package/dist/chunks/{huggingface-CqzyxeLB.js → huggingface-DxPspM6Q.js} +3 -3
  17. package/dist/chunks/{huggingface-CqzyxeLB.js.map → huggingface-DxPspM6Q.js.map} +1 -1
  18. package/dist/chunks/{litellm-viqTuSY8.js → litellm-nOCNI7Vd.js} +4 -4
  19. package/dist/chunks/{litellm-viqTuSY8.js.map → litellm-nOCNI7Vd.js.map} +1 -1
  20. package/dist/chunks/{ollama-CdWqwZ05.js → ollama-BrB6bjnz.js} +3 -3
  21. package/dist/chunks/{ollama-CdWqwZ05.js.map → ollama-BrB6bjnz.js.map} +1 -1
  22. package/dist/chunks/{openai-BgrK3OfW.js → openai-BuwvBruA.js} +4 -4
  23. package/dist/chunks/{openai-BgrK3OfW.js.map → openai-BuwvBruA.js.map} +1 -1
  24. package/dist/chunks/{openai-compat-video-D_U7jo0d.js → openai-compat-video-DNE1Yvp6.js} +4 -4
  25. package/dist/chunks/{openai-compat-video-D_U7jo0d.js.map → openai-compat-video-DNE1Yvp6.js.map} +1 -1
  26. package/dist/chunks/{qwen-tts-BXjzY7DX.js → qwen-tts-CAh1upii.js} +2 -2
  27. package/dist/chunks/{qwen-tts-BXjzY7DX.js.map → qwen-tts-CAh1upii.js.map} +1 -1
  28. package/dist/chunks/{rate-limit-DgEhanDL.js → rate-limit-C2oPwLGI.js} +6 -5
  29. package/dist/chunks/rate-limit-C2oPwLGI.js.map +1 -0
  30. package/dist/chunks/{safety-C415clBm.js → safety-ClfpyKEN.js} +2 -2
  31. package/dist/chunks/{safety-C415clBm.js.map → safety-ClfpyKEN.js.map} +1 -1
  32. package/dist/chunks/seevio-Bbu_hTUF.js +451 -0
  33. package/dist/chunks/seevio-Bbu_hTUF.js.map +1 -0
  34. package/dist/chunks/{src-CU4qWJ2c.js → src-B091S0I4.js} +23 -16
  35. package/dist/chunks/src-B091S0I4.js.map +1 -0
  36. package/dist/chunks/{types-CINwUPDo.js → types-sSecpd_N.js} +3 -2
  37. package/dist/chunks/types-sSecpd_N.js.map +1 -0
  38. package/dist/index.js +3 -3
  39. package/dist/node/factory.d.ts +2 -1
  40. package/dist/node/factory.d.ts.map +1 -1
  41. package/dist/node.js +21 -6
  42. package/dist/node.js.map +1 -1
  43. package/dist/shared/factory.d.ts.map +1 -1
  44. package/dist/shared/providers/seevio.d.ts +48 -0
  45. package/dist/shared/providers/seevio.d.ts.map +1 -0
  46. package/dist/shared/rate-limit.d.ts.map +1 -1
  47. package/dist/shared/types.d.ts +61 -2
  48. package/dist/shared/types.d.ts.map +1 -1
  49. package/package.json +2 -2
  50. package/dist/chunks/rate-limit-DgEhanDL.js.map +0 -1
  51. package/dist/chunks/src-CU4qWJ2c.js.map +0 -1
  52. package/dist/chunks/types-CINwUPDo.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-B091S0I4.js","names":[],"sources":["../../src/shared/client.ts","../../src/shared/factory.ts","../../src/shared/message.ts","../../src/shared/thread.ts","../../src/index.ts"],"sourcesContent":["import { ApiError, ValidationError } from '@happyvertical/utils';\nimport OpenAI from 'openai';\n\nimport type { AIMessageOptions } from './message';\nimport type { AIProviderType, AIRateLimitOptions } from './types';\nimport { AI_PROVIDER_TYPES } from './types';\n\n/**\n * Common options for AI client configuration\n */\nexport interface AIClientOptions {\n /**\n * Type of AI client (e.g., 'openai')\n */\n type?: AIProviderType | string;\n\n /**\n * Response format for AI completions\n */\n responseFormat?: string;\n\n /**\n * API key for authentication\n */\n apiKey?: string;\n\n /**\n * Base URL for API requests\n */\n baseUrl?: string;\n\n /**\n * Admin API key for gateway providers that support provisioning.\n */\n adminApiKey?: string;\n\n /**\n * Admin base URL for gateway providers when it differs from `baseUrl`.\n */\n adminBaseUrl?: string;\n\n /**\n * Alias for adminBaseUrl.\n */\n adminUrl?: string;\n\n /**\n * Admin username for providers that use HTTP Basic auth.\n */\n adminUser?: string;\n\n /**\n * Admin username for providers that use HTTP Basic auth.\n */\n adminUsername?: string;\n\n /**\n * Admin password for providers that use HTTP Basic auth.\n */\n adminPassword?: string;\n\n /**\n * Custom admin headers for gateway providers.\n */\n adminHeaders?: Record<string, string>;\n\n /**\n * Optional shared pacing / retry configuration for getAI().\n */\n rateLimit?: AIRateLimitOptions;\n}\n\n/**\n * Interface defining required methods for AI clients\n */\nexport interface AIClientInterface {\n /**\n * Configuration options for this client\n */\n options: AIClientOptions;\n\n /**\n * Sends a message to the AI and gets a response\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to the AI response\n */\n message(text: string, options: AIMessageOptions): Promise<unknown>;\n\n /**\n * Gets a text completion from the AI\n *\n * @param text - Input text for completion\n * @param options - Completion options\n * @returns Promise resolving to the completion result\n */\n textCompletion(text: string, options: AIMessageOptions): Promise<unknown>;\n}\n\n/**\n * Type guard to check if options are for OpenAI client\n *\n * @param options - Options to check\n * @returns True if options are valid for OpenAI client\n */\nfunction isOpenAIClientOptions(\n options: AIClientOptions,\n): options is OpenAIClientOptions {\n return options.type === 'openai' && 'apiKey' in options && !!options.apiKey;\n}\n\n/**\n * Type guard to check if value is an AI client instance\n *\n * @param value - Value to check\n * @returns True if value is an AI client instance\n */\nfunction isAIClientInstance(value: any): value is AIClient {\n return value instanceof AIClient;\n}\n\n/**\n * Options for AI text completion requests\n */\nexport interface AITextCompletionOptions {\n /**\n * Model identifier to use\n */\n model?: string;\n\n /**\n * Timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Role of the message sender\n */\n role?: OpenAI.Chat.ChatCompletionRole;\n\n /**\n * Previous messages in the conversation\n */\n history?: OpenAI.Chat.ChatCompletionMessageParam[];\n\n /**\n * Name of the message sender\n */\n name?: string;\n\n /**\n * Penalty for token frequency\n */\n frequencyPenalty?: number;\n\n /**\n * Token bias adjustments\n */\n logitBias?: Record<string, number>;\n\n /**\n * Whether to return log probabilities\n */\n logprobs?: boolean;\n\n /**\n * Number of top log probabilities to return\n */\n topLogprobs?: number;\n\n /**\n * Maximum tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Number of completions to generate\n */\n n?: number;\n\n /**\n * Penalty for token presence\n */\n presencePenalty?: number;\n\n /**\n * Format for the response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n\n /**\n * Random seed for deterministic results\n */\n seed?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | Array<string>;\n\n /**\n * Whether to stream responses\n */\n stream?: boolean;\n\n /**\n * Sampling temperature\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topProbability?: number;\n\n /**\n * Available tools for the model\n */\n tools?: Array<any>; // todo: figure out generic solution - Array<OpenAI.Chat.ChatCompletionTool>;\n\n /**\n * Tool selection behavior\n */\n toolChoice?:\n | 'none'\n | 'auto'\n | { type: 'function'; function: { name: string } };\n\n /**\n * User identifier\n */\n user?: string;\n\n /**\n * Callback for handling streaming responses\n */\n onProgress?: (partialMessage: string) => void;\n}\n\n/**\n * Base class for AI clients\n * Provides a common interface for different AI service providers\n */\nexport class AIClient {\n /**\n * Configuration options for this client\n */\n public options: AIClientOptions;\n\n /**\n * Creates a new AIClient\n *\n * @param options - Client configuration options\n */\n constructor(options: AIClientOptions) {\n this.options = options;\n }\n\n /**\n * Sends a message to the AI\n * Base implementation returns a placeholder response\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to a placeholder response\n */\n public async message(\n _text: string,\n _options: AITextCompletionOptions = { role: 'user' },\n ) {\n return 'not a real ai message, this is the base class!';\n }\n\n /**\n * Factory method to create appropriate AI client based on options\n *\n * @param options - Client configuration options\n * @returns Promise resolving to an initialized AI client\n * @throws Error if client type is invalid\n */\n public static async create(\n options: AIClientOptions | AIClient,\n ): Promise<AIClient | OpenAIClient> {\n // If an AI client instance is passed, return it directly\n if (isAIClientInstance(options)) {\n return options;\n }\n\n // Cast to options since we know it's not an instance\n const clientOptions = options as AIClientOptions;\n\n if (isOpenAIClientOptions(clientOptions)) {\n return OpenAIClient.create(clientOptions);\n }\n\n // Delegate to modern factory for non-OpenAI providers\n const providedType = (clientOptions as any).type;\n if (providedType && providedType !== 'openai') {\n const { getAI } = await import('./factory.js');\n return (await getAI(clientOptions as any)) as any;\n }\n\n // Provide specific error messages for common issues\n if (providedType === 'openai') {\n throw new ValidationError(\n 'OpenAI API key is required but missing or empty',\n {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType,\n hint: 'Set OPENAI_API_KEY environment variable or pass apiKey in options',\n },\n );\n }\n\n throw new ValidationError('Invalid client type specified', {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType,\n });\n }\n\n /**\n * Gets a text completion from the AI\n * In base class, delegates to message method\n *\n * @param text - Input text for completion\n * @param options - Completion options\n * @returns Promise resolving to the completion result\n */\n public textCompletion(\n text: string,\n options: AITextCompletionOptions = {\n role: 'user',\n },\n ) {\n return this.message(text, options);\n }\n}\n\n/**\n * Creates an OpenAI client instance\n *\n * @param options - OpenAI configuration options\n * @returns Promise resolving to an OpenAI client\n */\nexport async function getOpenAI(options: {\n apiKey?: string;\n baseUrl?: string;\n}) {\n return new OpenAI({\n apiKey: options.apiKey,\n baseURL: options.baseUrl,\n });\n}\n\n/**\n * Options specific to OpenAI text completion requests\n */\nexport interface OpenAITextCompletionOptions {\n /**\n * Model identifier to use\n */\n model?: string;\n\n /**\n * Timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Role of the message sender\n */\n role?: OpenAI.Chat.ChatCompletionRole;\n\n /**\n * Previous messages in the conversation\n */\n history?: Array<OpenAI.Chat.ChatCompletionMessageParam>;\n\n /**\n * Name of the message sender\n */\n name?: string;\n\n /**\n * Penalty for token frequency\n */\n frequencyPenalty?: number;\n\n /**\n * Token bias adjustments\n */\n logitBias?: Record<string, number>;\n\n /**\n * Whether to return log probabilities\n */\n logprobs?: boolean;\n\n /**\n * Number of top log probabilities to return\n */\n topLogprobs?: number;\n\n /**\n * Maximum tokens to generate\n */\n maxTokens?: number;\n\n /**\n * Number of completions to generate\n */\n n?: number;\n\n /**\n * Penalty for token presence\n */\n presencePenalty?: number;\n\n /**\n * Format for the response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n\n /**\n * Random seed for deterministic results\n */\n seed?: number;\n\n /**\n * Sequences that stop generation\n */\n stop?: string | Array<string>;\n\n /**\n * Whether to stream responses\n */\n stream?: boolean;\n\n /**\n * Sampling temperature\n */\n temperature?: number;\n\n /**\n * Top-p sampling parameter\n */\n topProbability?: number;\n\n /**\n * Available tools for the model\n */\n tools?: Array<OpenAI.Chat.ChatCompletionTool>;\n\n /**\n * Tool selection behavior\n */\n toolChoice?:\n | 'none'\n | 'auto'\n | { type: 'function'; function: { name: string } };\n\n /**\n * User identifier\n */\n user?: string;\n\n /**\n * Callback for handling streaming responses\n */\n onProgress?: (partialMessage: string) => void;\n}\n\n/**\n * Configuration options specific to OpenAI client\n */\nexport interface OpenAIClientOptions extends AIClientOptions {\n /**\n * OpenAI API key\n */\n apiKey?: string;\n\n /**\n * OpenAI API base URL\n */\n baseUrl?: string;\n}\n\n/**\n * Client implementation for the OpenAI API\n */\nexport class OpenAIClient extends AIClient {\n /**\n * OpenAI client instance\n */\n protected openai!: OpenAI;\n\n /**\n * Configuration options for this client\n */\n public options: OpenAIClientOptions;\n\n /**\n * Creates a new OpenAIClient\n *\n * @param options - OpenAI client configuration options\n */\n constructor(options: OpenAIClientOptions) {\n super(options);\n this.options = options;\n }\n\n /**\n * Sends a message to OpenAI\n *\n * @param text - Message text\n * @param options - Message options\n * @returns Promise resolving to the OpenAI response\n */\n public async message(\n text: string,\n options: AIMessageOptions = { role: 'user' },\n ) {\n const response = await this.textCompletion(text, options);\n return response;\n }\n\n /**\n * Factory method to create and initialize an OpenAIClient\n *\n * @param options - OpenAI client configuration options\n * @returns Promise resolving to an initialized OpenAIClient\n */\n public static async create(\n options: OpenAIClientOptions,\n ): Promise<OpenAIClient> {\n const client = new OpenAIClient(options);\n await client.initialize();\n return client;\n }\n\n /**\n * Initializes the OpenAI client\n */\n protected async initialize() {\n this.openai = new OpenAI({\n apiKey: this.options.apiKey,\n baseURL: this.options.baseUrl,\n });\n }\n\n /**\n * Sends a text completion request to the OpenAI API\n *\n * @param message - The message to send\n * @param options - Configuration options for the completion request\n * @returns Promise resolving to the completion text\n * @throws Error if the OpenAI API response is invalid\n */\n public async textCompletion(\n message: string,\n options: OpenAITextCompletionOptions = {},\n ): Promise<string> {\n const {\n model = 'gpt-4o',\n role = 'user',\n history = [],\n name: _name,\n frequencyPenalty = 0,\n logitBias,\n logprobs = false,\n topLogprobs,\n maxTokens,\n n = 1,\n presencePenalty = 0,\n responseFormat,\n seed,\n stop,\n stream: _stream = false,\n temperature = 1,\n topProbability: topP = 1,\n tools,\n toolChoice,\n user,\n onProgress,\n } = options;\n\n const messages = [\n ...history,\n {\n role: role as OpenAI.Chat.ChatCompletionRole,\n content: message,\n } as OpenAI.Chat.ChatCompletionSystemMessageParam,\n ];\n\n if (onProgress) {\n const stream = await this.openai.chat.completions.create({\n model,\n messages,\n stream: true,\n frequency_penalty: frequencyPenalty,\n logit_bias: logitBias,\n logprobs,\n top_logprobs: topLogprobs,\n max_tokens: maxTokens,\n n,\n presence_penalty: presencePenalty,\n response_format: responseFormat,\n seed,\n stop,\n temperature,\n top_p: topP,\n tools,\n tool_choice: toolChoice,\n user,\n });\n\n let fullContent = '';\n for await (const chunk of stream) {\n const content = chunk.choices[0]?.delta?.content || '';\n fullContent += content;\n onProgress(content);\n }\n\n return fullContent;\n }\n const response = await this.openai.chat.completions.create({\n model,\n messages,\n frequency_penalty: frequencyPenalty,\n logit_bias: logitBias,\n logprobs,\n top_logprobs: topLogprobs,\n max_tokens: maxTokens,\n n,\n presence_penalty: presencePenalty,\n response_format: responseFormat,\n seed,\n stop,\n stream: false,\n temperature,\n top_p: topP,\n tools,\n tool_choice: toolChoice,\n user,\n });\n\n const choice = response.choices[0];\n if (!choice || !choice.message || !choice.message.content) {\n throw new ApiError('Invalid response from OpenAI API: Missing content', {\n model,\n responseId: response.id,\n choices: response.choices?.length || 0,\n hasChoice: !!choice,\n hasMessage: !!choice?.message,\n hasContent: !!choice?.message?.content,\n });\n }\n return choice.message.content;\n }\n}\n\n/**\n * Options for getting an AI client with type information\n */\ntype GetAIClientOptions = AIClientOptions & {\n type?: AIProviderType;\n};\n\n/**\n * Factory function to create and initialize an appropriate AI client\n * Delegates to the modern getAI() factory for all provider types\n *\n * @param options - Client configuration options\n * @returns Promise resolving to an initialized AI client\n * @throws Error if client type is invalid\n */\nexport async function getAIClient(\n options: GetAIClientOptions,\n): Promise<AIClient> {\n // Delegate to modern factory for all providers\n const { getAI } = await import('./factory.js');\n return (await getAI(options as any)) as any;\n}\n","/**\n * Universal factory functions for creating AI provider instances\n * Works in both browser and Node.js environments\n */\n\nimport { loadEnvConfig, ValidationError } from '@happyvertical/utils';\n\nimport type { AIClientOptions } from './client';\nimport { createRateLimitedAI } from './rate-limit';\nimport { createObservedAI, normalizeBaseAIOptions } from './safety';\nimport type {\n AIInterface,\n AIProviderType,\n AnthropicOptions,\n BedrockOptions,\n BifrostOptions,\n ByteplusModelArkOptions,\n ClaudeCliOptions,\n GeminiOptions,\n GetAIOptions,\n HuggingFaceOptions,\n LiteLLMOptions,\n OllamaOptions,\n OpenAICompatVideoOptions,\n OpenAIOptions,\n Qwen3TTSOptions,\n SeevioOptions,\n} from './types';\nimport { AI_PROVIDER_TYPES } from './types';\n\n/**\n * Type guards for provider options\n */\n\n/**\n * Checks if the options are for OpenAI provider\n * @param options - The AI provider options to check\n * @returns True if options are for OpenAI provider (including default case)\n */\nfunction isOpenAIOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OpenAIOptions {\n return !options.type || options.type === 'openai';\n}\n\n/**\n * Checks if the options are for LiteLLM provider\n * @param options - The AI provider options to check\n * @returns True if options are for LiteLLM provider\n */\nfunction isLiteLLMOptions(\n options: GetAIOptions | AIClientOptions,\n): options is LiteLLMOptions {\n return options.type === 'litellm';\n}\n\n/**\n * Checks if the options are for Bifrost provider\n * @param options - The AI provider options to check\n * @returns True if options are for Bifrost provider\n */\nfunction isBifrostOptions(\n options: GetAIOptions | AIClientOptions,\n): options is BifrostOptions {\n return options.type === 'bifrost';\n}\n\n/**\n * Checks if the options are for Ollama provider\n * @param options - The AI provider options to check\n * @returns True if options are for Ollama provider\n */\nfunction isOllamaOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OllamaOptions {\n return options.type === 'ollama';\n}\n\n/**\n * Checks if the options are for Google Gemini provider\n * @param options - The AI provider options to check\n * @returns True if options are for Gemini provider\n */\nfunction isGeminiOptions(\n options: GetAIOptions | AIClientOptions,\n): options is GeminiOptions {\n return options.type === 'gemini';\n}\n\n/**\n * Checks if the options are for Anthropic Claude provider\n * @param options - The AI provider options to check\n * @returns True if options are for Anthropic provider\n */\nfunction isAnthropicOptions(\n options: GetAIOptions | AIClientOptions,\n): options is AnthropicOptions {\n return options.type === 'anthropic';\n}\n\n/**\n * Checks if the options are for Hugging Face provider\n * @param options - The AI provider options to check\n * @returns True if options are for Hugging Face provider\n */\nfunction isHuggingFaceOptions(\n options: GetAIOptions | AIClientOptions,\n): options is HuggingFaceOptions {\n return options.type === 'huggingface';\n}\n\n/**\n * Checks if the options are for AWS Bedrock provider\n * @param options - The AI provider options to check\n * @returns True if options are for Bedrock provider\n */\nfunction isBedrockOptions(\n options: GetAIOptions | AIClientOptions,\n): options is BedrockOptions {\n return options.type === 'bedrock';\n}\n\n/**\n * Checks if the options are for Claude CLI provider\n * @param options - The AI provider options to check\n * @returns True if options are for Claude CLI provider\n */\nfunction isClaudeCliOptions(\n options: GetAIOptions | AIClientOptions,\n): options is ClaudeCliOptions {\n return options.type === 'claude-cli';\n}\n\n/**\n * Checks if the options are for Qwen3-TTS provider\n * @param options - The AI provider options to check\n * @returns True if options are for Qwen3-TTS provider\n */\nfunction isQwen3TTSOptions(\n options: GetAIOptions | AIClientOptions,\n): options is Qwen3TTSOptions {\n return options.type === 'qwen3-tts';\n}\n\n/**\n * Checks if the options are for the OpenAI-compatible video-generation provider\n * @param options - The AI provider options to check\n * @returns True if options are for the openai-compat-video provider\n */\nfunction isOpenAICompatVideoOptions(\n options: GetAIOptions | AIClientOptions,\n): options is OpenAICompatVideoOptions {\n return options.type === 'openai-compat-video';\n}\n\n/**\n * Checks if the options are for the BytePlus ModelArk (Seedance) provider\n * @param options - The AI provider options to check\n * @returns True if options are for the byteplus-modelark provider\n */\nfunction isByteplusModelArkOptions(\n options: GetAIOptions | AIClientOptions,\n): options is ByteplusModelArkOptions {\n return options.type === 'byteplus-modelark';\n}\n\n/** Checks if options select Seevio's native Seedance task API. */\nfunction isSeevioOptions(\n options: GetAIOptions | AIClientOptions,\n): options is SeevioOptions {\n return options.type === 'seevio';\n}\n\n/**\n * Creates an AI provider instance based on the provided options.\n * Universal version that works in both browser and Node.js environments.\n *\n * Supports environment variable configuration using the pattern:\n * - HAVE_AI_PROVIDER → provider type (string)\n * - HAVE_AI_MODEL → defaultModel (string)\n * - HAVE_AI_TIMEOUT → timeout (number)\n * - HAVE_AI_MAX_RETRIES → maxRetries (number)\n * - HAVE_AI_API_KEY → apiKey (string) - fallback if provider-specific key not set\n * - HAVE_AI_BASE_URL → baseUrl (string)\n *\n * User-provided options always take precedence over environment variables.\n *\n * Accepts both GetAIOptions (provider-specific options with literal types)\n * and AIClientOptions (legacy interface with generic string type) for\n * backward compatibility with existing code.\n *\n * @param options - Configuration options for the AI provider. Can be GetAIOptions or AIClientOptions.\n * @returns Promise resolving to an AI provider instance that implements the AIInterface\n * @throws {ValidationError} When the provider type is unsupported or invalid\n *\n * @example\n * ```typescript\n * // Create OpenAI client with explicit options\n * const openai = await getAI({\n * type: 'openai',\n * apiKey: process.env.OPENAI_API_KEY!,\n * defaultModel: 'gpt-4o'\n * });\n *\n * // Or use environment variables (HAVE_AI_PROVIDER=openai, HAVE_AI_API_KEY=sk-...)\n * const client = await getAI({});\n *\n * // Create Anthropic client\n * const anthropic = await getAI({\n * type: 'anthropic',\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * defaultModel: 'claude-3-5-sonnet-20241022'\n * });\n *\n * // Works with AIClientOptions (legacy interface)\n * const clientOptions: AIClientOptions = { type: 'openai', apiKey: '...' };\n * const legacy = await getAI(clientOptions);\n * ```\n */\nexport async function getAI(\n options: GetAIOptions | AIClientOptions = {},\n): Promise<AIInterface> {\n // Load environment variables with user options taking precedence\n options = loadEnvConfig(options as Record<string, any>, {\n packageName: 'ai',\n schema: {\n provider: 'string',\n type: 'string', // Alias for provider\n model: 'string',\n defaultModel: 'string',\n timeout: 'number',\n maxRetries: 'number',\n apiKey: 'string',\n baseUrl: 'string',\n adminApiKey: 'string',\n adminBaseUrl: 'string',\n adminUrl: 'string',\n adminUser: 'string',\n adminUsername: 'string',\n adminPassword: 'string',\n },\n }) as GetAIOptions;\n\n // Normalize 'provider' field to 'type' for consistency\n if ('provider' in options && !options.type) {\n (options as any).type = (options as any).provider;\n }\n\n // Normalize 'model' field to 'defaultModel' for consistency\n if ('model' in options && !options.defaultModel) {\n (options as any).defaultModel = (options as any).model;\n }\n\n options = normalizeBaseAIOptions(options as GetAIOptions);\n\n let client: AIInterface;\n\n if (isOpenAIOptions(options)) {\n const { OpenAIProvider } = await import('./providers/openai.js');\n client = new OpenAIProvider(options);\n } else if (isLiteLLMOptions(options)) {\n const { LiteLLMProvider } = await import('./providers/litellm.js');\n client = new LiteLLMProvider(options);\n } else if (isBifrostOptions(options)) {\n const { BifrostProvider } = await import('./providers/bifrost.js');\n client = new BifrostProvider(options);\n } else if (isOllamaOptions(options)) {\n const { OllamaProvider } = await import('./providers/ollama.js');\n client = new OllamaProvider(options);\n } else if (isGeminiOptions(options)) {\n const { GeminiProvider } = await import('./providers/gemini.js');\n client = new GeminiProvider(options);\n } else if (isAnthropicOptions(options)) {\n const { AnthropicProvider } = await import('./providers/anthropic.js');\n client = new AnthropicProvider(options);\n } else if (isHuggingFaceOptions(options)) {\n const { HuggingFaceProvider } = await import('./providers/huggingface.js');\n client = new HuggingFaceProvider(options);\n } else if (isBedrockOptions(options)) {\n const { BedrockProvider } = await import('./providers/bedrock.js');\n client = new BedrockProvider(options);\n } else if (isClaudeCliOptions(options)) {\n const { ClaudeCliProvider } = await import('./providers/claude-cli.js');\n client = new ClaudeCliProvider(options);\n } else if (isQwen3TTSOptions(options)) {\n const { Qwen3TTSProvider } = await import('./providers/qwen-tts.js');\n client = new Qwen3TTSProvider(options);\n } else if (isOpenAICompatVideoOptions(options)) {\n const { OpenAICompatVideoProvider } = await import(\n './providers/openai-compat-video.js'\n );\n client = new OpenAICompatVideoProvider(options);\n } else if (isByteplusModelArkOptions(options)) {\n const { ByteplusModelArkProvider } = await import(\n './providers/byteplus-modelark.js'\n );\n client = new ByteplusModelArkProvider(options);\n } else if (isSeevioOptions(options)) {\n const { SeevioProvider } = await import('./providers/seevio.js');\n client = new SeevioProvider(options);\n } else {\n throw new ValidationError('Unsupported AI provider type', {\n supportedTypes: [...AI_PROVIDER_TYPES],\n providedType: (options as any).type,\n });\n }\n\n return createObservedAI(createRateLimitedAI(client, options), options);\n}\n\n/**\n * Browser-compatible auto-detection of AI provider based on available credentials.\n * Does not rely on process.env, making it suitable for browser environments.\n *\n * @param options - Configuration options that may contain provider-specific credentials\n * @returns Promise resolving to an AI provider instance based on detected credentials\n * @throws {ValidationError} When no provider can be detected from the provided options\n *\n * @example\n * ```typescript\n * // Auto-detect OpenAI from apiKey\n * const client1 = await getAIAuto({\n * apiKey: 'sk-...', // Detected as OpenAI\n * defaultModel: 'gpt-4o'\n * });\n *\n * // Auto-detect Hugging Face from apiToken\n * const client2 = await getAIAuto({\n * apiToken: 'hf_...', // Detected as Hugging Face\n * model: 'microsoft/DialoGPT-medium'\n * });\n *\n * // Auto-detect AWS Bedrock from region and credentials\n * const client3 = await getAIAuto({\n * region: 'us-east-1',\n * credentials: {\n * accessKeyId: 'AKIA...',\n * secretAccessKey: 'xxx'\n * }\n * });\n * ```\n */\nexport async function getAIAuto(\n options: Record<string, any>,\n): Promise<AIInterface> {\n const baseUrl = String((options as any).baseUrl || '');\n const hasKeepAliveOption =\n 'keepAlive' in options && (options as any).keepAlive !== undefined;\n\n // Auto-detect provider based on available credentials\n if (\n /((?:localhost|127\\.0\\.0\\.1)(?::11434)?(?:\\/(?:api|v1))?|ollama(?:\\.com)?(?:\\/(?:api|v1))?)\\/?$/i.test(\n baseUrl,\n ) ||\n hasKeepAliveOption\n ) {\n return getAI({ ...options, type: 'ollama' } as OllamaOptions);\n }\n\n if (options.apiKey && !options.type) {\n // Default to OpenAI if apiKey is provided without explicit type\n return getAI({ ...options, type: 'openai' } as OpenAIOptions);\n }\n\n if (options.apiToken) {\n // Hugging Face uses apiToken\n return getAI({ ...options, type: 'huggingface' } as HuggingFaceOptions);\n }\n\n if (options.region && options.credentials) {\n // AWS Bedrock uses region and explicit credentials\n return getAI({ ...options, type: 'bedrock' } as BedrockOptions);\n }\n\n if (options.projectId || options.anthropicVersion) {\n // Try to detect based on provider-specific options\n if (options.anthropicVersion) {\n return getAI({ ...options, type: 'anthropic' } as AnthropicOptions);\n }\n if (options.projectId) {\n return getAI({ ...options, type: 'gemini' } as GeminiOptions);\n }\n }\n\n throw new ValidationError('Could not auto-detect AI provider from options', {\n hint: 'Please specify a \"type\" field in options or provide provider-specific credentials',\n supportedTypes: [...AI_PROVIDER_TYPES] as AIProviderType[],\n providedOptions: Object.keys(options),\n });\n}\n","import type { AIThread } from './thread';\n\n/**\n * Options for creating AI messages\n */\nexport interface AIMessageOptions {\n /**\n * Role of the message sender\n */\n role?: 'user' | 'assistant' | 'system';\n\n /**\n * Format for the AI response\n */\n responseFormat?: { type: 'text' | 'json_object' };\n}\n\n/**\n * Represents a message in an AI conversation\n */\nexport class AIMessage {\n /**\n * Original options used to create this message\n */\n protected options;\n\n /**\n * Name of the message sender\n */\n public name: string;\n\n /**\n * Content of the message\n */\n public content: string;\n\n /**\n * Role of the message sender in the conversation\n */\n public role: 'user' | 'assistant' | 'system';\n\n /**\n * Creates a new AI message\n *\n * @param options - Message configuration\n * @param options.role - Role of the message sender\n * @param options.content - Content of the message\n * @param options.name - Name of the message sender\n */\n constructor(options: {\n role: 'user' | 'assistant' | 'system';\n content: string;\n name: string;\n }) {\n this.options = options;\n this.role = options.role;\n this.content = options.content;\n this.name = options.name;\n }\n\n /**\n * Factory method to create a new AI message\n *\n * @param options - Message configuration\n * @param options.thread - Thread this message belongs to\n * @param options.role - Role of the message sender\n * @param options.content - Content of the message\n * @param options.name - Name of the message sender\n * @returns Promise resolving to a new AIMessage instance\n */\n static async create(options: {\n thread: AIThread;\n role: 'user' | 'assistant' | 'system';\n content: string;\n name: string;\n }) {\n return new AIMessage(options);\n }\n}\n","import type OpenAI from 'openai';\nimport { AIClient, type AIClientOptions } from './client';\nimport { AIMessage } from './message';\n\n/**\n * Options for creating an AI conversation thread\n */\nexport interface AIThreadOptions {\n /**\n * Options for the AI client to use in this thread\n */\n ai: AIClientOptions;\n}\n\n/**\n * Represents a conversation thread with an AI model\n * Manages messages, references, and conversation state\n */\nexport class AIThread {\n /**\n * AI client instance for this thread\n */\n protected ai!: AIClient;\n\n /**\n * Options used to configure this thread\n */\n protected options: AIThreadOptions;\n\n /**\n * Messages in this conversation thread\n */\n private messages: AIMessage[] = [];\n\n /**\n * Reference materials to include in the conversation context\n */\n private references: { [name: string]: string } = {};\n\n /**\n * Creates a new AI thread\n *\n * @param options - Thread configuration options\n */\n constructor(options: AIThreadOptions) {\n this.options = options;\n }\n\n /**\n * Factory method to create and initialize a new AI thread\n *\n * @param options - Thread configuration options\n * @returns Promise resolving to an initialized AIThread\n */\n static async create(options: AIThreadOptions) {\n const thread = new AIThread(options);\n await thread.initialize();\n return thread; // No need to add system message here, do it in addSystem\n }\n\n /**\n * Initializes the AI client for this thread\n */\n public async initialize() {\n this.ai = await AIClient.create(this.options.ai);\n }\n\n /**\n * Adds a system message to the conversation\n *\n * @param prompt - System message content\n * @returns Promise resolving to the created AIMessage\n */\n public async addSystem(prompt: string) {\n const message = await AIMessage.create({\n thread: this,\n role: 'system',\n name: 'system',\n content: prompt,\n });\n\n this.messages.push(message);\n return message;\n }\n\n /**\n * Adds a message to the conversation\n *\n * @param options - Message options\n * @param options.role - Role of the message sender\n * @param options.name - Optional name of the message sender\n * @param options.content - Content of the message\n * @returns Promise resolving to the created AIMessage\n */\n public async add(options: {\n role: 'user' | 'assistant' | 'system';\n name?: string;\n content: string;\n }) {\n const message = await AIMessage.create({\n thread: this,\n role: options.role,\n name: options.name || options.role, // Default name to role if not provided\n content: options.content,\n });\n\n this.messages.push(message);\n return message;\n }\n\n /**\n * Gets all messages in this thread\n *\n * @returns Array of AIMessage objects\n */\n public get(): AIMessage[] {\n return this.messages;\n }\n\n /**\n * Adds a reference to be included in the conversation context\n *\n * @param name - Name of the reference\n * @param body - Content of the reference\n */\n public addReference(name: string, body: string): void {\n this.references[name] = body;\n }\n\n /**\n * Assembles the conversation history for sending to the AI\n * Properly orders system message, references, and conversation messages\n *\n * @returns Array of message parameters formatted for the OpenAI API\n */\n public assembleHistory(): OpenAI.Chat.ChatCompletionMessageParam[] {\n const history: OpenAI.Chat.ChatCompletionMessageParam[] = [];\n\n // Add system message first\n const systemMessage = this.messages.find((m) => m.role === 'system');\n if (systemMessage) {\n history.push({\n role: systemMessage.role,\n content: systemMessage.content,\n });\n }\n\n // Add references as user messages (before other user/assistant messages)\n for (const name in this.references) {\n history.push({\n role: 'user',\n content: `Reference - ${name}:\\n${this.references[name]}`,\n });\n }\n\n // Add other messages\n this.messages\n .filter((m) => m.role !== 'system')\n .forEach((message) => {\n history.push({ role: message.role, content: message.content });\n });\n\n return history;\n }\n\n /**\n * Sends a prompt to the AI and gets a response\n *\n * @param prompt - Prompt message to send\n * @param options - Options for the AI response\n * @param options.responseFormat - Format for the AI to respond with\n * @returns Promise resolving to the AI response\n */\n public async do(\n prompt: string,\n options: {\n responseFormat?: 'html' | 'text' | 'json';\n } = {\n responseFormat: 'text',\n },\n ) {\n const { responseFormat } = options;\n const history = this.assembleHistory();\n\n // Get completion from AI with assembled history\n const response = await this.ai.textCompletion(prompt, {\n history,\n responseFormat: {\n type: responseFormat === 'json' ? 'json_object' : 'text',\n },\n });\n return response;\n }\n}\n","/**\n * @happyvertical/ai - A standardized interface for AI model interactions\n *\n * This package provides a unified interface for interacting with various AI models.\n * Supports multiple providers: OpenAI, LiteLLM, Ollama, Gemini, Anthropic,\n * Hugging Face, AWS Bedrock, Claude CLI, and Qwen3-TTS.\n *\n * Key components:\n * - getAI() - Factory function for creating AI provider instances\n * - AIInterface - Standardized interface for all AI providers\n * - Provider-specific implementations for each supported service\n */\n\n// Legacy exports for backward compatibility\nexport * from './shared/client';\nexport * from './shared/factory';\nexport { AIMessage as AIMessageClass } from './shared/message';\nexport {\n DEFAULT_AI_GENERATION_LIMITS,\n DEFAULT_AI_MAX_RETRIES,\n DEFAULT_AI_TIMEOUT_MS,\n} from './shared/safety';\nexport * from './shared/thread';\nexport * from './shared/types';\n\n/** @internal */\nexport const PACKAGE_VERSION_INITIALIZED = true;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0GA,SAAS,sBACP,SACgC;CAChC,OAAO,QAAQ,SAAS,YAAY,YAAY,WAAW,CAAC,CAAC,QAAQ;AACvE;;;;;;;AAQA,SAAS,mBAAmB,OAA+B;CACzD,OAAO,iBAAiB;AAC1B;;;;;AA4HA,IAAa,WAAb,MAAsB;;;;CAIpB;;;;;;CAOA,YAAY,SAA0B;EACpC,KAAK,UAAU;CACjB;;;;;;;;;CAUA,MAAa,QACX,OACA,WAAoC,EAAE,MAAM,OAAO,GACnD;EACA,OAAO;CACT;;;;;;;;CASA,aAAoB,OAClB,SACkC;EAElC,IAAI,mBAAmB,OAAO,GAC5B,OAAO;EAIT,MAAM,gBAAgB;EAEtB,IAAI,sBAAsB,aAAa,GACrC,OAAO,aAAa,OAAO,aAAa;EAI1C,MAAM,eAAgB,cAAsB;EAC5C,IAAI,gBAAgB,iBAAiB,UAAU;GAC7C,MAAM,EAAE,UAAU,MAAA,QAAA,QAAA,CAAA,CAAA,WAAA,eAAA;GAClB,OAAQ,MAAM,MAAM,aAAoB;EAC1C;EAGA,IAAI,iBAAiB,UACnB,MAAM,IAAI,gBACR,mDACA;GACE,gBAAgB,CAAC,GAAG,iBAAiB;GACrC;GACA,MAAM;EACR,CACF;EAGF,MAAM,IAAI,gBAAgB,iCAAiC;GACzD,gBAAgB,CAAC,GAAG,iBAAi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ClC,SAAS,YAAY;GACpB,QAAQ,KAAK;IAAE,MAAM,QAAQ;IAAM,SAAS,QAAQ;GAAQ,CAAC;EAC/D,CAAC;EAEH,OAAO;CACT;;;;;;;;;CAUA,MAAa,GACX,QACA,UAEI,EACF,gBAAgB,OAClB,GACA;EACA,MAAM,EAAE,mBAAmB;EAC3B,MAAM,UAAU,KAAK,gBAAgB;EASrC,OAAO,MANgB,KAAK,GAAG,eAAe,QAAQ;GACpD;GACA,gBAAgB,EACd,MAAM,mBAAmB,SAAS,gBAAgB,OACpD;EACF,CAAC;CAEH;AACF;;;;ACvKA,IAAa,8BAA8B"}
@@ -14,7 +14,8 @@ var AI_PROVIDER_TYPES = [
14
14
  "claude-cli",
15
15
  "qwen3-tts",
16
16
  "openai-compat-video",
17
- "byteplus-modelark"
17
+ "byteplus-modelark",
18
+ "seevio"
18
19
  ];
19
20
  /**
20
21
  * Extract text content from a message content field.
@@ -116,4 +117,4 @@ var ContentFilterError = class extends AIError {
116
117
  //#endregion
117
118
  export { ContextLengthError as a, extractTextContent as c, ContentFilterError as i, AI_PROVIDER_TYPES as n, ModelNotFoundError as o, AuthenticationError as r, RateLimitError as s, AIError as t };
118
119
 
119
- //# sourceMappingURL=types-CINwUPDo.js.map
120
+ //# sourceMappingURL=types-sSecpd_N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-sSecpd_N.js","names":[],"sources":["../../src/shared/types.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 */\nexport interface AIGenerationLimits {\n /** Maximum text tokens a single request may generate. */\n maxOutputTokens: 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 /** Request timeout in milliseconds. Overrides the provider default. */\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 | '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] 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 name?: string;\n\n /**\n * Optional tool calls\n */\n tool_calls?: Array<{\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n }>;\n}\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 * 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 * 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 * 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 * 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 * 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 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/**\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?: 'stop' | 'length' | 'tool_calls' | 'content_filter';\n\n /**\n * Tool calls made by the model\n */\n toolCalls?: Array<{\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n }>;\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 * 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 * 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 * 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/**\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\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/**\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 */\nexport class RateLimitError extends AIError {\n public retryAfter?: number;\n\n constructor(provider?: string, retryAfter?: number) {\n super(\n `Rate limit exceeded${retryAfter ? `, retry after ${retryAfter}s` : ''}`,\n 'RATE_LIMIT',\n provider,\n undefined,\n true,\n );\n this.name = 'RateLimitError';\n this.retryAfter = retryAfter;\n }\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 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"],"mappings":";;;;AA+FA,IAAa,oBAAoB;CAC/B;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;;;;;;;;;;AA64DA,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;;;;;;;AAQA,IAAa,iBAAb,cAAoC,QAAQ;CAC1C;CAEA,YAAY,UAAmB,YAAqB;EAClD,MACE,sBAAsB,aAAa,iBAAiB,WAAW,KAAK,MACpE,cACA,UACA,KAAA,GACA,IACF;EACA,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;;;;;;;AAQA,IAAa,qBAAb,cAAwC,QAAQ;CAC9C,YAAY,OAAe,UAAmB;EAC5C,MACE,oBAAoB,SACpB,mBACA,UACA,OACA,KACF;EACA,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAa,qBAAb,cAAwC,QAAQ;CAC9C,YAAY,UAAmB,OAAgB;EAC7C,MACE,wCACA,2BACA,UACA,OACA,KACF;EACA,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAa,qBAAb,cAAwC,QAAQ;CAC9C,YAAY,UAAmB,OAAgB;EAC7C,MACE,sCACA,oBACA,UACA,OACA,KACF;EACA,KAAK,OAAO;CACd;AACF"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as getAI, c as OpenAIClient, l as getAIClient, n as AIThread, o as getAIAuto, r as AIMessage, s as AIClient, t as PACKAGE_VERSION_INITIALIZED, u as getOpenAI } from "./chunks/src-CU4qWJ2c.js";
2
- import { a as ContextLengthError, c as extractTextContent, i as ContentFilterError, n as AI_PROVIDER_TYPES, o as ModelNotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./chunks/types-CINwUPDo.js";
3
- import { n as DEFAULT_AI_MAX_RETRIES, r as DEFAULT_AI_TIMEOUT_MS, t as DEFAULT_AI_GENERATION_LIMITS } from "./chunks/safety-C415clBm.js";
1
+ import { a as getAI, c as OpenAIClient, l as getAIClient, n as AIThread, o as getAIAuto, r as AIMessage, s as AIClient, t as PACKAGE_VERSION_INITIALIZED, u as getOpenAI } from "./chunks/src-B091S0I4.js";
2
+ import { a as ContextLengthError, c as extractTextContent, i as ContentFilterError, n as AI_PROVIDER_TYPES, o as ModelNotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./chunks/types-sSecpd_N.js";
3
+ import { n as DEFAULT_AI_MAX_RETRIES, r as DEFAULT_AI_TIMEOUT_MS, t as DEFAULT_AI_GENERATION_LIMITS } from "./chunks/safety-ClfpyKEN.js";
4
4
  export { AIClient, AIError, AIMessage as AIMessageClass, AIThread, AI_PROVIDER_TYPES, AuthenticationError, ContentFilterError, ContextLengthError, DEFAULT_AI_GENERATION_LIMITS, DEFAULT_AI_MAX_RETRIES, DEFAULT_AI_TIMEOUT_MS, ModelNotFoundError, OpenAIClient, PACKAGE_VERSION_INITIALIZED, RateLimitError, extractTextContent, getAI, getAIAuto, getAIClient, getOpenAI };
@@ -20,12 +20,13 @@ export { getAI } from '../shared/factory';
20
20
  * - AWS_* → AWS Bedrock credentials
21
21
  * - OPENAI_COMPAT_VIDEO_BASE_URL / OPENAI_COMPAT_VIDEO_API_KEY → openai-compat-video gateway config (checked last)
22
22
  * - MODELARK_API_KEY / ARK_API_KEY / MODELARK_BASE_URL → BytePlus ModelArk (Seedance) config (checked last)
23
+ * - SEEVIO_API_KEY / SEEVIO_BASE_URL → Seevio Seedance config (checked last)
23
24
  *
24
25
  * The two video-only provider types above are intentionally checked *after*
25
26
  * every general-purpose provider: they throw `NOT_IMPLEMENTED` for chat()
26
27
  * and everything else, so their env signals must never hijack a bare
27
28
  * `getAIAuto()` call away from a general-purpose provider. Prefer explicit
28
- * `type: 'byteplus-modelark'` / `type: 'openai-compat-video'` when you want
29
+ * `type: 'byteplus-modelark'` / `type: 'openai-compat-video'` / `type: 'seevio'` when you want
29
30
  * one of these on purpose.
30
31
  *
31
32
  * @param options - Configuration options that may contain provider-specific credentials
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src/node/factory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,KAAK,EACV,WAAW,EAaZ,MAAM,iBAAiB,CAAC;AAGzB;;GAEG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,SAAS,CAC7B,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAM,GAChC,OAAO,CAAC,WAAW,CAAC,CA6RtB"}
1
+ {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src/node/factory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,KAAK,EACV,WAAW,EAcZ,MAAM,iBAAiB,CAAC;AAGzB;;GAEG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAsB,SAAS,CAC7B,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAM,GAChC,OAAO,CAAC,WAAW,CAAC,CAmTtB"}
package/dist/node.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as getAI, c as OpenAIClient, l as getAIClient, n as AIThread, r as AIMessage, s as AIClient, t as PACKAGE_VERSION_INITIALIZED, u as getOpenAI } from "./chunks/src-CU4qWJ2c.js";
2
- import { a as ContextLengthError, c as extractTextContent, i as ContentFilterError, n as AI_PROVIDER_TYPES, o as ModelNotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./chunks/types-CINwUPDo.js";
3
- import { n as DEFAULT_AI_MAX_RETRIES, r as DEFAULT_AI_TIMEOUT_MS, t as DEFAULT_AI_GENERATION_LIMITS } from "./chunks/safety-C415clBm.js";
1
+ import { a as getAI, c as OpenAIClient, l as getAIClient, n as AIThread, r as AIMessage, s as AIClient, t as PACKAGE_VERSION_INITIALIZED, u as getOpenAI } from "./chunks/src-B091S0I4.js";
2
+ import { a as ContextLengthError, c as extractTextContent, i as ContentFilterError, n as AI_PROVIDER_TYPES, o as ModelNotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./chunks/types-sSecpd_N.js";
3
+ import { n as DEFAULT_AI_MAX_RETRIES, r as DEFAULT_AI_TIMEOUT_MS, t as DEFAULT_AI_GENERATION_LIMITS } from "./chunks/safety-ClfpyKEN.js";
4
4
  import { ValidationError, loadEnvConfig } from "@happyvertical/utils";
5
5
  //#region src/node/factory.ts
6
6
  /**
@@ -24,12 +24,13 @@ import { ValidationError, loadEnvConfig } from "@happyvertical/utils";
24
24
  * - AWS_* → AWS Bedrock credentials
25
25
  * - OPENAI_COMPAT_VIDEO_BASE_URL / OPENAI_COMPAT_VIDEO_API_KEY → openai-compat-video gateway config (checked last)
26
26
  * - MODELARK_API_KEY / ARK_API_KEY / MODELARK_BASE_URL → BytePlus ModelArk (Seedance) config (checked last)
27
+ * - SEEVIO_API_KEY / SEEVIO_BASE_URL → Seevio Seedance config (checked last)
27
28
  *
28
29
  * The two video-only provider types above are intentionally checked *after*
29
30
  * every general-purpose provider: they throw `NOT_IMPLEMENTED` for chat()
30
31
  * and everything else, so their env signals must never hijack a bare
31
32
  * `getAIAuto()` call away from a general-purpose provider. Prefer explicit
32
- * `type: 'byteplus-modelark'` / `type: 'openai-compat-video'` when you want
33
+ * `type: 'byteplus-modelark'` / `type: 'openai-compat-video'` / `type: 'seevio'` when you want
33
34
  * one of these on purpose.
34
35
  *
35
36
  * @param options - Configuration options that may contain provider-specific credentials
@@ -71,6 +72,11 @@ async function getAIAuto(options = {}) {
71
72
  apiKey: config.apiKey || process.env.OPENAI_COMPAT_VIDEO_API_KEY,
72
73
  baseUrl: config.baseUrl || process.env.OPENAI_COMPAT_VIDEO_BASE_URL
73
74
  });
75
+ if (config.type === "seevio") return getAI({
76
+ ...config,
77
+ apiKey: config.apiKey || process.env.SEEVIO_API_KEY,
78
+ baseUrl: config.baseUrl || process.env.SEEVIO_BASE_URL
79
+ });
74
80
  if (config.type === "bifrost") {
75
81
  const resolvedAdminUrl = callerAdminUrl || process.env.BIFROST_ADMIN_URL || process.env.BIFROST_ADMIN_BASE_URL;
76
82
  const resolvedAdminUser = callerAdminUser || process.env.BIFROST_ADMIN_USER || process.env.BIFROST_ADMIN_USERNAME;
@@ -89,7 +95,7 @@ async function getAIAuto(options = {}) {
89
95
  return getAI(config);
90
96
  }
91
97
  try {
92
- return await import("./chunks/src-CU4qWJ2c.js").then((n) => n.i).then((m) => m.getAIAuto(config));
98
+ return await import("./chunks/src-B091S0I4.js").then((n) => n.i).then((m) => m.getAIAuto(config));
93
99
  } catch (_error) {}
94
100
  const hasLiteLLMSignal = Boolean(process.env.LITELLM_BASE_URL || process.env.LITELLM_API_KEY);
95
101
  if (Boolean(process.env.BIFROST_BASE_URL) && !config.type) return getAI({
@@ -152,6 +158,7 @@ async function getAIAuto(options = {}) {
152
158
  }
153
159
  const hasModelArkSignal = Boolean(process.env.MODELARK_API_KEY || process.env.ARK_API_KEY || process.env.MODELARK_BASE_URL);
154
160
  const hasOpenAICompatVideoSignal = Boolean(process.env.OPENAI_COMPAT_VIDEO_BASE_URL);
161
+ const hasSeevioSignal = Boolean(process.env.SEEVIO_API_KEY || process.env.SEEVIO_BASE_URL);
155
162
  if (hasModelArkSignal && !config.type) return getAI({
156
163
  ...config,
157
164
  type: "byteplus-modelark",
@@ -164,6 +171,12 @@ async function getAIAuto(options = {}) {
164
171
  apiKey: config.apiKey || process.env.OPENAI_COMPAT_VIDEO_API_KEY,
165
172
  baseUrl: config.baseUrl || process.env.OPENAI_COMPAT_VIDEO_BASE_URL
166
173
  });
174
+ if (hasSeevioSignal && !config.type) return getAI({
175
+ ...config,
176
+ type: "seevio",
177
+ apiKey: config.apiKey || process.env.SEEVIO_API_KEY,
178
+ baseUrl: config.baseUrl || process.env.SEEVIO_BASE_URL
179
+ });
167
180
  throw new ValidationError("Could not auto-detect AI provider from options or environment", {
168
181
  hint: "Please specify a \"type\" field in options or provide provider-specific credentials/environment variables",
169
182
  supportedTypes: [...AI_PROVIDER_TYPES],
@@ -188,7 +201,9 @@ async function getAIAuto(options = {}) {
188
201
  "OPENAI_COMPAT_VIDEO_API_KEY",
189
202
  "MODELARK_API_KEY",
190
203
  "ARK_API_KEY",
191
- "MODELARK_BASE_URL"
204
+ "MODELARK_BASE_URL",
205
+ "SEEVIO_API_KEY",
206
+ "SEEVIO_BASE_URL"
192
207
  ]
193
208
  });
194
209
  }
package/dist/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":[],"sources":["../src/node/factory.ts"],"sourcesContent":["/**\n * Node.js-specific factory functions for creating AI provider instances\n * Includes support for environment variable detection\n */\n\nimport { loadEnvConfig, ValidationError } from '@happyvertical/utils';\nimport { getAI as getAIUniversal } from '../shared/factory';\n\nimport type {\n AIInterface,\n AIProviderType,\n AnthropicOptions,\n BedrockOptions,\n BifrostOptions,\n ByteplusModelArkOptions,\n GeminiOptions,\n GetAIOptions,\n HuggingFaceOptions,\n LiteLLMOptions,\n OllamaOptions,\n OpenAICompatVideoOptions,\n OpenAIOptions,\n} from '../shared/types';\nimport { AI_PROVIDER_TYPES } from '../shared/types';\n\n/**\n * Re-export the universal getAI function\n */\nexport { getAI } from '../shared/factory';\n\n/**\n * Node.js-enhanced auto-detection of AI provider based on available credentials\n * Includes support for environment variables\n *\n * Supports both HAVE_AI_* environment variables and provider-specific variables:\n * - HAVE_AI_PROVIDER / HAVE_AI_TYPE → provider type\n * - HAVE_AI_API_KEY → fallback API key\n * - LITELLM_BASE_URL / LITELLM_API_KEY / LITELLM_ADMIN_API_KEY → LiteLLM-specific gateway config\n * - BIFROST_BASE_URL / BIFROST_API_KEY / BIFROST_ADMIN_URL / BIFROST_ADMIN_USER / BIFROST_ADMIN_PASSWORD → Bifrost gateway config\n * - OLLAMA_HOST / OLLAMA_BASE_URL / OLLAMA_API_KEY → Ollama host/auth config\n * - OPENAI_API_KEY → OpenAI-specific key\n * - ANTHROPIC_API_KEY → Anthropic-specific key\n * - GEMINI_API_KEY / GOOGLE_API_KEY → Gemini-specific key\n * - HF_TOKEN → Hugging Face token\n * - AWS_* → AWS Bedrock credentials\n * - OPENAI_COMPAT_VIDEO_BASE_URL / OPENAI_COMPAT_VIDEO_API_KEY → openai-compat-video gateway config (checked last)\n * - MODELARK_API_KEY / ARK_API_KEY / MODELARK_BASE_URL → BytePlus ModelArk (Seedance) config (checked last)\n *\n * The two video-only provider types above are intentionally checked *after*\n * every general-purpose provider: they throw `NOT_IMPLEMENTED` for chat()\n * and everything else, so their env signals must never hijack a bare\n * `getAIAuto()` call away from a general-purpose provider. Prefer explicit\n * `type: 'byteplus-modelark'` / `type: 'openai-compat-video'` when you want\n * one of these on purpose.\n *\n * @param options - Configuration options that may contain provider-specific credentials\n * @returns Promise resolving to an AI provider instance\n * @throws ValidationError if no provider can be detected from the options\n */\nexport async function getAIAuto(\n options: Record<string, any> = {},\n): Promise<AIInterface> {\n // Load HAVE_AI_* environment variables first\n const config = loadEnvConfig(options, {\n packageName: 'ai',\n schema: {\n provider: 'string',\n type: 'string',\n model: 'string',\n defaultModel: 'string',\n timeout: 'number',\n maxRetries: 'number',\n apiKey: 'string',\n baseUrl: 'string',\n adminApiKey: 'string',\n adminBaseUrl: 'string',\n adminUrl: 'string',\n adminUser: 'string',\n adminUsername: 'string',\n adminPassword: 'string',\n },\n }) as GetAIOptions;\n\n // Normalize 'provider' field to 'type'\n if ('provider' in config && !config.type) {\n (config as any).type = (config as any).provider;\n }\n\n const adminConfig = config as {\n adminApiKey?: string;\n adminBaseUrl?: string;\n adminUrl?: string;\n adminUser?: string;\n adminUsername?: string;\n adminPassword?: string;\n };\n\n // Caller options always win over env: collapse alias pairs (adminUrl/adminBaseUrl\n // and adminUser/adminUsername) on the caller side first, so that an env override\n // for one alias cannot mask an explicit caller value supplied via the other.\n const callerAdminUrl = adminConfig.adminUrl || adminConfig.adminBaseUrl;\n const callerAdminUser = adminConfig.adminUser || adminConfig.adminUsername;\n\n // If type is specified (either from options or env vars), use getAI directly\n if (config.type) {\n if (config.type === 'byteplus-modelark') {\n return getAIUniversal({\n ...config,\n apiKey:\n config.apiKey ||\n process.env.MODELARK_API_KEY ||\n process.env.ARK_API_KEY,\n baseUrl: config.baseUrl || process.env.MODELARK_BASE_URL,\n } as ByteplusModelArkOptions);\n }\n\n if (config.type === 'openai-compat-video') {\n return getAIUniversal({\n ...config,\n apiKey: config.apiKey || process.env.OPENAI_COMPAT_VIDEO_API_KEY,\n baseUrl: config.baseUrl || process.env.OPENAI_COMPAT_VIDEO_BASE_URL,\n } as OpenAICompatVideoOptions);\n }\n\n if (config.type === 'bifrost') {\n const resolvedAdminUrl =\n callerAdminUrl ||\n process.env.BIFROST_ADMIN_URL ||\n process.env.BIFROST_ADMIN_BASE_URL;\n const resolvedAdminUser =\n callerAdminUser ||\n process.env.BIFROST_ADMIN_USER ||\n process.env.BIFROST_ADMIN_USERNAME;\n\n return getAIUniversal({\n ...config,\n baseUrl: config.baseUrl || process.env.BIFROST_BASE_URL,\n apiKey: config.apiKey || process.env.BIFROST_API_KEY,\n adminApiKey:\n adminConfig.adminApiKey || process.env.BIFROST_ADMIN_API_KEY,\n adminBaseUrl: resolvedAdminUrl,\n adminUrl: resolvedAdminUrl,\n adminUser: resolvedAdminUser,\n adminUsername: resolvedAdminUser,\n adminPassword:\n adminConfig.adminPassword || process.env.BIFROST_ADMIN_PASSWORD,\n } as BifrostOptions);\n }\n\n return getAIUniversal(config);\n }\n\n // First try universal detection with loaded config\n try {\n return await import('../shared/factory.js').then((m) =>\n m.getAIAuto(config),\n );\n } catch (_error) {\n // If universal detection fails, try Node.js-specific environment variables\n }\n\n // Auto-detect provider based on available credentials including environment variables\n const hasLiteLLMSignal = Boolean(\n process.env.LITELLM_BASE_URL || process.env.LITELLM_API_KEY,\n );\n const hasBifrostSignal = Boolean(process.env.BIFROST_BASE_URL);\n\n if (hasBifrostSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'bifrost',\n baseUrl: config.baseUrl || process.env.BIFROST_BASE_URL,\n apiKey: config.apiKey || process.env.BIFROST_API_KEY,\n adminApiKey: adminConfig.adminApiKey || process.env.BIFROST_ADMIN_API_KEY,\n adminBaseUrl:\n adminConfig.adminBaseUrl || process.env.BIFROST_ADMIN_BASE_URL,\n adminUrl: adminConfig.adminUrl || process.env.BIFROST_ADMIN_URL,\n adminUser:\n adminConfig.adminUser ||\n adminConfig.adminUsername ||\n process.env.BIFROST_ADMIN_USER ||\n process.env.BIFROST_ADMIN_USERNAME,\n adminPassword:\n adminConfig.adminPassword || process.env.BIFROST_ADMIN_PASSWORD,\n } as BifrostOptions);\n }\n\n if (hasLiteLLMSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'litellm',\n baseUrl: config.baseUrl || process.env.LITELLM_BASE_URL,\n apiKey: config.apiKey || process.env.LITELLM_API_KEY,\n adminApiKey: adminConfig.adminApiKey || process.env.LITELLM_ADMIN_API_KEY,\n adminBaseUrl:\n adminConfig.adminBaseUrl || process.env.LITELLM_ADMIN_BASE_URL,\n adminUrl: adminConfig.adminUrl || process.env.LITELLM_ADMIN_URL,\n } as LiteLLMOptions);\n }\n\n if (\n (process.env.OLLAMA_HOST ||\n process.env.OLLAMA_BASE_URL ||\n (process.env.OLLAMA_API_KEY && !process.env.OPENAI_API_KEY)) &&\n !config.type\n ) {\n return getAIUniversal({\n ...config,\n type: 'ollama',\n baseUrl:\n config.baseUrl ||\n process.env.OLLAMA_BASE_URL ||\n process.env.OLLAMA_HOST,\n apiKey: (config as any).apiKey || process.env.OLLAMA_API_KEY,\n } as OllamaOptions);\n }\n\n if ((config.apiKey || process.env.OPENAI_API_KEY) && !config.type) {\n // Default to OpenAI if apiKey is provided without explicit type\n return getAIUniversal({\n ...config,\n type: 'openai',\n apiKey: config.apiKey || process.env.OPENAI_API_KEY,\n } as OpenAIOptions);\n }\n\n if (process.env.ANTHROPIC_API_KEY) {\n return getAIUniversal({\n ...config,\n type: 'anthropic',\n apiKey: process.env.ANTHROPIC_API_KEY,\n } as AnthropicOptions);\n }\n\n if (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY) {\n return getAIUniversal({\n ...config,\n type: 'gemini',\n apiKey: process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY,\n } as GeminiOptions);\n }\n\n if ((config as any).apiToken || process.env.HF_TOKEN) {\n // Hugging Face uses apiToken or HF_TOKEN\n return getAIUniversal({\n ...config,\n type: 'huggingface',\n apiToken: (config as any).apiToken || process.env.HF_TOKEN,\n } as HuggingFaceOptions);\n }\n\n if (\n ((config as any).region || process.env.AWS_DEFAULT_REGION) &&\n ((config as any).credentials || process.env.AWS_ACCESS_KEY_ID)\n ) {\n // AWS Bedrock uses region and AWS credentials (explicit or from env)\n const bedrockOptions: BedrockOptions = {\n ...config,\n type: 'bedrock',\n region: (config as any).region || process.env.AWS_DEFAULT_REGION,\n };\n\n // Add credentials if available in environment\n if (\n !(config as any).credentials &&\n process.env.AWS_ACCESS_KEY_ID &&\n process.env.AWS_SECRET_ACCESS_KEY\n ) {\n bedrockOptions.credentials = {\n accessKeyId: process.env.AWS_ACCESS_KEY_ID,\n secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n };\n }\n\n return getAIUniversal(bedrockOptions);\n }\n\n // Video-only provider detection runs last, deliberately after every\n // general-purpose provider check above: these providers throw\n // NOT_IMPLEMENTED for chat() and every other non-video method, so a bare\n // getAIAuto() must never let a video-only credential (e.g. MODELARK_API_KEY\n // set alongside OPENAI_API_KEY for an unrelated pipeline step) hijack\n // selection away from a general-purpose provider. Explicit\n // `type: 'byteplus-modelark'` / `type: 'openai-compat-video'` selection is\n // the intended way to reach these providers; auto-detection is a\n // last-resort fallback for when nothing general-purpose matches.\n const hasModelArkSignal = Boolean(\n process.env.MODELARK_API_KEY ||\n process.env.ARK_API_KEY ||\n process.env.MODELARK_BASE_URL,\n );\n const hasOpenAICompatVideoSignal = Boolean(\n process.env.OPENAI_COMPAT_VIDEO_BASE_URL,\n );\n\n if (hasModelArkSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'byteplus-modelark',\n apiKey:\n config.apiKey ||\n process.env.MODELARK_API_KEY ||\n process.env.ARK_API_KEY,\n baseUrl: config.baseUrl || process.env.MODELARK_BASE_URL,\n } as ByteplusModelArkOptions);\n }\n\n if (hasOpenAICompatVideoSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'openai-compat-video',\n apiKey: config.apiKey || process.env.OPENAI_COMPAT_VIDEO_API_KEY,\n baseUrl: config.baseUrl || process.env.OPENAI_COMPAT_VIDEO_BASE_URL,\n } as OpenAICompatVideoOptions);\n }\n\n throw new ValidationError(\n 'Could not auto-detect AI provider from options or environment',\n {\n hint: 'Please specify a \"type\" field in options or provide provider-specific credentials/environment variables',\n supportedTypes: [...AI_PROVIDER_TYPES] as AIProviderType[],\n providedOptions: Object.keys(config),\n checkedEnvVars: [\n 'HAVE_AI_PROVIDER',\n 'HAVE_AI_TYPE',\n 'HAVE_AI_API_KEY',\n 'LITELLM_BASE_URL',\n 'LITELLM_API_KEY',\n 'OLLAMA_HOST',\n 'OLLAMA_BASE_URL',\n 'OLLAMA_API_KEY',\n 'OPENAI_API_KEY',\n 'ANTHROPIC_API_KEY',\n 'GEMINI_API_KEY',\n 'GOOGLE_API_KEY',\n 'HF_TOKEN',\n 'AWS_ACCESS_KEY_ID',\n 'AWS_DEFAULT_REGION',\n 'OPENAI_COMPAT_VIDEO_BASE_URL',\n 'OPENAI_COMPAT_VIDEO_API_KEY',\n 'MODELARK_API_KEY',\n 'ARK_API_KEY',\n 'MODELARK_BASE_URL',\n ],\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,eAAsB,UACpB,UAA+B,CAAC,GACV;CAEtB,MAAM,SAAS,cAAc,SAAS;EACpC,aAAa;EACb,QAAQ;GACN,UAAU;GACV,MAAM;GACN,OAAO;GACP,cAAc;GACd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;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF,CACF;AACF"}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../src/node/factory.ts"],"sourcesContent":["/**\n * Node.js-specific factory functions for creating AI provider instances\n * Includes support for environment variable detection\n */\n\nimport { loadEnvConfig, ValidationError } from '@happyvertical/utils';\nimport { getAI as getAIUniversal } from '../shared/factory';\n\nimport type {\n AIInterface,\n AIProviderType,\n AnthropicOptions,\n BedrockOptions,\n BifrostOptions,\n ByteplusModelArkOptions,\n GeminiOptions,\n GetAIOptions,\n HuggingFaceOptions,\n LiteLLMOptions,\n OllamaOptions,\n OpenAICompatVideoOptions,\n OpenAIOptions,\n SeevioOptions,\n} from '../shared/types';\nimport { AI_PROVIDER_TYPES } from '../shared/types';\n\n/**\n * Re-export the universal getAI function\n */\nexport { getAI } from '../shared/factory';\n\n/**\n * Node.js-enhanced auto-detection of AI provider based on available credentials\n * Includes support for environment variables\n *\n * Supports both HAVE_AI_* environment variables and provider-specific variables:\n * - HAVE_AI_PROVIDER / HAVE_AI_TYPE → provider type\n * - HAVE_AI_API_KEY → fallback API key\n * - LITELLM_BASE_URL / LITELLM_API_KEY / LITELLM_ADMIN_API_KEY → LiteLLM-specific gateway config\n * - BIFROST_BASE_URL / BIFROST_API_KEY / BIFROST_ADMIN_URL / BIFROST_ADMIN_USER / BIFROST_ADMIN_PASSWORD → Bifrost gateway config\n * - OLLAMA_HOST / OLLAMA_BASE_URL / OLLAMA_API_KEY → Ollama host/auth config\n * - OPENAI_API_KEY → OpenAI-specific key\n * - ANTHROPIC_API_KEY → Anthropic-specific key\n * - GEMINI_API_KEY / GOOGLE_API_KEY → Gemini-specific key\n * - HF_TOKEN → Hugging Face token\n * - AWS_* → AWS Bedrock credentials\n * - OPENAI_COMPAT_VIDEO_BASE_URL / OPENAI_COMPAT_VIDEO_API_KEY → openai-compat-video gateway config (checked last)\n * - MODELARK_API_KEY / ARK_API_KEY / MODELARK_BASE_URL → BytePlus ModelArk (Seedance) config (checked last)\n * - SEEVIO_API_KEY / SEEVIO_BASE_URL → Seevio Seedance config (checked last)\n *\n * The two video-only provider types above are intentionally checked *after*\n * every general-purpose provider: they throw `NOT_IMPLEMENTED` for chat()\n * and everything else, so their env signals must never hijack a bare\n * `getAIAuto()` call away from a general-purpose provider. Prefer explicit\n * `type: 'byteplus-modelark'` / `type: 'openai-compat-video'` / `type: 'seevio'` when you want\n * one of these on purpose.\n *\n * @param options - Configuration options that may contain provider-specific credentials\n * @returns Promise resolving to an AI provider instance\n * @throws ValidationError if no provider can be detected from the options\n */\nexport async function getAIAuto(\n options: Record<string, any> = {},\n): Promise<AIInterface> {\n // Load HAVE_AI_* environment variables first\n const config = loadEnvConfig(options, {\n packageName: 'ai',\n schema: {\n provider: 'string',\n type: 'string',\n model: 'string',\n defaultModel: 'string',\n timeout: 'number',\n maxRetries: 'number',\n apiKey: 'string',\n baseUrl: 'string',\n adminApiKey: 'string',\n adminBaseUrl: 'string',\n adminUrl: 'string',\n adminUser: 'string',\n adminUsername: 'string',\n adminPassword: 'string',\n },\n }) as GetAIOptions;\n\n // Normalize 'provider' field to 'type'\n if ('provider' in config && !config.type) {\n (config as any).type = (config as any).provider;\n }\n\n const adminConfig = config as {\n adminApiKey?: string;\n adminBaseUrl?: string;\n adminUrl?: string;\n adminUser?: string;\n adminUsername?: string;\n adminPassword?: string;\n };\n\n // Caller options always win over env: collapse alias pairs (adminUrl/adminBaseUrl\n // and adminUser/adminUsername) on the caller side first, so that an env override\n // for one alias cannot mask an explicit caller value supplied via the other.\n const callerAdminUrl = adminConfig.adminUrl || adminConfig.adminBaseUrl;\n const callerAdminUser = adminConfig.adminUser || adminConfig.adminUsername;\n\n // If type is specified (either from options or env vars), use getAI directly\n if (config.type) {\n if (config.type === 'byteplus-modelark') {\n return getAIUniversal({\n ...config,\n apiKey:\n config.apiKey ||\n process.env.MODELARK_API_KEY ||\n process.env.ARK_API_KEY,\n baseUrl: config.baseUrl || process.env.MODELARK_BASE_URL,\n } as ByteplusModelArkOptions);\n }\n\n if (config.type === 'openai-compat-video') {\n return getAIUniversal({\n ...config,\n apiKey: config.apiKey || process.env.OPENAI_COMPAT_VIDEO_API_KEY,\n baseUrl: config.baseUrl || process.env.OPENAI_COMPAT_VIDEO_BASE_URL,\n } as OpenAICompatVideoOptions);\n }\n\n if (config.type === 'seevio') {\n return getAIUniversal({\n ...config,\n apiKey: config.apiKey || process.env.SEEVIO_API_KEY,\n baseUrl: config.baseUrl || process.env.SEEVIO_BASE_URL,\n } as SeevioOptions);\n }\n\n if (config.type === 'bifrost') {\n const resolvedAdminUrl =\n callerAdminUrl ||\n process.env.BIFROST_ADMIN_URL ||\n process.env.BIFROST_ADMIN_BASE_URL;\n const resolvedAdminUser =\n callerAdminUser ||\n process.env.BIFROST_ADMIN_USER ||\n process.env.BIFROST_ADMIN_USERNAME;\n\n return getAIUniversal({\n ...config,\n baseUrl: config.baseUrl || process.env.BIFROST_BASE_URL,\n apiKey: config.apiKey || process.env.BIFROST_API_KEY,\n adminApiKey:\n adminConfig.adminApiKey || process.env.BIFROST_ADMIN_API_KEY,\n adminBaseUrl: resolvedAdminUrl,\n adminUrl: resolvedAdminUrl,\n adminUser: resolvedAdminUser,\n adminUsername: resolvedAdminUser,\n adminPassword:\n adminConfig.adminPassword || process.env.BIFROST_ADMIN_PASSWORD,\n } as BifrostOptions);\n }\n\n return getAIUniversal(config);\n }\n\n // First try universal detection with loaded config\n try {\n return await import('../shared/factory.js').then((m) =>\n m.getAIAuto(config),\n );\n } catch (_error) {\n // If universal detection fails, try Node.js-specific environment variables\n }\n\n // Auto-detect provider based on available credentials including environment variables\n const hasLiteLLMSignal = Boolean(\n process.env.LITELLM_BASE_URL || process.env.LITELLM_API_KEY,\n );\n const hasBifrostSignal = Boolean(process.env.BIFROST_BASE_URL);\n\n if (hasBifrostSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'bifrost',\n baseUrl: config.baseUrl || process.env.BIFROST_BASE_URL,\n apiKey: config.apiKey || process.env.BIFROST_API_KEY,\n adminApiKey: adminConfig.adminApiKey || process.env.BIFROST_ADMIN_API_KEY,\n adminBaseUrl:\n adminConfig.adminBaseUrl || process.env.BIFROST_ADMIN_BASE_URL,\n adminUrl: adminConfig.adminUrl || process.env.BIFROST_ADMIN_URL,\n adminUser:\n adminConfig.adminUser ||\n adminConfig.adminUsername ||\n process.env.BIFROST_ADMIN_USER ||\n process.env.BIFROST_ADMIN_USERNAME,\n adminPassword:\n adminConfig.adminPassword || process.env.BIFROST_ADMIN_PASSWORD,\n } as BifrostOptions);\n }\n\n if (hasLiteLLMSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'litellm',\n baseUrl: config.baseUrl || process.env.LITELLM_BASE_URL,\n apiKey: config.apiKey || process.env.LITELLM_API_KEY,\n adminApiKey: adminConfig.adminApiKey || process.env.LITELLM_ADMIN_API_KEY,\n adminBaseUrl:\n adminConfig.adminBaseUrl || process.env.LITELLM_ADMIN_BASE_URL,\n adminUrl: adminConfig.adminUrl || process.env.LITELLM_ADMIN_URL,\n } as LiteLLMOptions);\n }\n\n if (\n (process.env.OLLAMA_HOST ||\n process.env.OLLAMA_BASE_URL ||\n (process.env.OLLAMA_API_KEY && !process.env.OPENAI_API_KEY)) &&\n !config.type\n ) {\n return getAIUniversal({\n ...config,\n type: 'ollama',\n baseUrl:\n config.baseUrl ||\n process.env.OLLAMA_BASE_URL ||\n process.env.OLLAMA_HOST,\n apiKey: (config as any).apiKey || process.env.OLLAMA_API_KEY,\n } as OllamaOptions);\n }\n\n if ((config.apiKey || process.env.OPENAI_API_KEY) && !config.type) {\n // Default to OpenAI if apiKey is provided without explicit type\n return getAIUniversal({\n ...config,\n type: 'openai',\n apiKey: config.apiKey || process.env.OPENAI_API_KEY,\n } as OpenAIOptions);\n }\n\n if (process.env.ANTHROPIC_API_KEY) {\n return getAIUniversal({\n ...config,\n type: 'anthropic',\n apiKey: process.env.ANTHROPIC_API_KEY,\n } as AnthropicOptions);\n }\n\n if (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY) {\n return getAIUniversal({\n ...config,\n type: 'gemini',\n apiKey: process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY,\n } as GeminiOptions);\n }\n\n if ((config as any).apiToken || process.env.HF_TOKEN) {\n // Hugging Face uses apiToken or HF_TOKEN\n return getAIUniversal({\n ...config,\n type: 'huggingface',\n apiToken: (config as any).apiToken || process.env.HF_TOKEN,\n } as HuggingFaceOptions);\n }\n\n if (\n ((config as any).region || process.env.AWS_DEFAULT_REGION) &&\n ((config as any).credentials || process.env.AWS_ACCESS_KEY_ID)\n ) {\n // AWS Bedrock uses region and AWS credentials (explicit or from env)\n const bedrockOptions: BedrockOptions = {\n ...config,\n type: 'bedrock',\n region: (config as any).region || process.env.AWS_DEFAULT_REGION,\n };\n\n // Add credentials if available in environment\n if (\n !(config as any).credentials &&\n process.env.AWS_ACCESS_KEY_ID &&\n process.env.AWS_SECRET_ACCESS_KEY\n ) {\n bedrockOptions.credentials = {\n accessKeyId: process.env.AWS_ACCESS_KEY_ID,\n secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n };\n }\n\n return getAIUniversal(bedrockOptions);\n }\n\n // Video-only provider detection runs last, deliberately after every\n // general-purpose provider check above: these providers throw\n // NOT_IMPLEMENTED for chat() and every other non-video method, so a bare\n // getAIAuto() must never let a video-only credential (e.g. MODELARK_API_KEY\n // set alongside OPENAI_API_KEY for an unrelated pipeline step) hijack\n // selection away from a general-purpose provider. Explicit\n // `type: 'byteplus-modelark'` / `type: 'openai-compat-video'` selection is\n // the intended way to reach these providers; auto-detection is a\n // last-resort fallback for when nothing general-purpose matches.\n const hasModelArkSignal = Boolean(\n process.env.MODELARK_API_KEY ||\n process.env.ARK_API_KEY ||\n process.env.MODELARK_BASE_URL,\n );\n const hasOpenAICompatVideoSignal = Boolean(\n process.env.OPENAI_COMPAT_VIDEO_BASE_URL,\n );\n const hasSeevioSignal = Boolean(\n process.env.SEEVIO_API_KEY || process.env.SEEVIO_BASE_URL,\n );\n\n if (hasModelArkSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'byteplus-modelark',\n apiKey:\n config.apiKey ||\n process.env.MODELARK_API_KEY ||\n process.env.ARK_API_KEY,\n baseUrl: config.baseUrl || process.env.MODELARK_BASE_URL,\n } as ByteplusModelArkOptions);\n }\n\n if (hasOpenAICompatVideoSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'openai-compat-video',\n apiKey: config.apiKey || process.env.OPENAI_COMPAT_VIDEO_API_KEY,\n baseUrl: config.baseUrl || process.env.OPENAI_COMPAT_VIDEO_BASE_URL,\n } as OpenAICompatVideoOptions);\n }\n\n if (hasSeevioSignal && !config.type) {\n return getAIUniversal({\n ...config,\n type: 'seevio',\n apiKey: config.apiKey || process.env.SEEVIO_API_KEY,\n baseUrl: config.baseUrl || process.env.SEEVIO_BASE_URL,\n } as SeevioOptions);\n }\n\n throw new ValidationError(\n 'Could not auto-detect AI provider from options or environment',\n {\n hint: 'Please specify a \"type\" field in options or provide provider-specific credentials/environment variables',\n supportedTypes: [...AI_PROVIDER_TYPES] as AIProviderType[],\n providedOptions: Object.keys(config),\n checkedEnvVars: [\n 'HAVE_AI_PROVIDER',\n 'HAVE_AI_TYPE',\n 'HAVE_AI_API_KEY',\n 'LITELLM_BASE_URL',\n 'LITELLM_API_KEY',\n 'OLLAMA_HOST',\n 'OLLAMA_BASE_URL',\n 'OLLAMA_API_KEY',\n 'OPENAI_API_KEY',\n 'ANTHROPIC_API_KEY',\n 'GEMINI_API_KEY',\n 'GOOGLE_API_KEY',\n 'HF_TOKEN',\n 'AWS_ACCESS_KEY_ID',\n 'AWS_DEFAULT_REGION',\n 'OPENAI_COMPAT_VIDEO_BASE_URL',\n 'OPENAI_COMPAT_VIDEO_API_KEY',\n 'MODELARK_API_KEY',\n 'ARK_API_KEY',\n 'MODELARK_BASE_URL',\n 'SEEVIO_API_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OAAO,MAAe;EACpB,GAAG;EACH,MAAM;EACN,QACE,OAAO,UACP,QAAQ,IAAI,oBACZ,QAAQ,IAAI;EACd,SAAS,OAAO,WAAW,QAAQ,IAAI;CACzC,CAA4B;CAG9B,IAAI,8BAA8B,CAAC,OAAO,MACxC,OAAO,MAAe;EACpB,GAAG;EACH,MAAM;EACN,QAAQ,OAAO,UAAU,QAAQ,IAAI;EACrC,SAAS,OAAO,WAAW,QAAQ,IAAI;CACzC,CAA6B;CAG/B,IAAI,mBAAmB,CAAC,OAAO,MAC7B,OAAO,MAAe;EACpB,GAAG;EACH,MAAM;EACN,QAAQ,OAAO,UAAU,QAAQ,IAAI;EACrC,SAAS,OAAO,WAAW,QAAQ,IAAI;CACzC,CAAkB;CAGpB,MAAM,IAAI,gBACR,iEACA;EACE,MAAM;EACN,gBAAgB,CAAC,GAAG,iBAAiB;EACrC,iBAAiB,OAAO,KAAK,MAAM;EACnC,gBAAgB;GACd;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF,CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src/shared/factory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAGhD,OAAO,KAAK,EACV,WAAW,EAQX,YAAY,EAOb,MAAM,SAAS,CAAC;AA2IjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,wBAAsB,KAAK,CACzB,OAAO,GAAE,YAAY,GAAG,eAAoB,GAC3C,OAAO,CAAC,WAAW,CAAC,CAoFtB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAsB,SAAS,CAC7B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC3B,OAAO,CAAC,WAAW,CAAC,CA6CtB"}
1
+ {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src/shared/factory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAGhD,OAAO,KAAK,EACV,WAAW,EAQX,YAAY,EAQb,MAAM,SAAS,CAAC;AAkJjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,wBAAsB,KAAK,CACzB,OAAO,GAAE,YAAY,GAAG,eAAoB,GAC3C,OAAO,CAAC,WAAW,CAAC,CAuFtB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAsB,SAAS,CAC7B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC3B,OAAO,CAAC,WAAW,CAAC,CA6CtB"}
@@ -0,0 +1,48 @@
1
+ import { AICapabilities, AIInterface, AIMessage, AIModel, AIResponse, ChatOptions, CompletionOptions, EmbeddingOptions, EmbeddingResponse, ImageDescriptionOptions, ImageEmbeddingOptions, ImageGenerationOptions, ImageGenerationResponse, MessageOptions, SeevioOptions, TTSOptions, TTSResponse, VideoGenerationJob, VideoGenerationOptions, VideoGenerationResult, VideoGenerationStatusResult, Voice, VoiceCloneOptions, VoiceDesignOptions, VoiceListOptions } from '../types';
2
+ /** Native Seevio adapter for the pinned `seedance-2-5` model. */
3
+ export declare class SeevioProvider implements AIInterface {
4
+ private readonly options;
5
+ private readonly resultOrigins;
6
+ private readonly nextPollAt;
7
+ private readonly completedSnapshots;
8
+ /** Creates a Seevio task client using the documented HTTPS API root. */
9
+ constructor(options: SeevioOptions);
10
+ private request;
11
+ private rawRequest;
12
+ private assertReviewedResultUrl;
13
+ private downloadReviewedResult;
14
+ private mediaUrls;
15
+ private pollTask;
16
+ private completedSnapshot;
17
+ /** Submits one unambiguous, non-retried Seedance 2.5 task. */
18
+ submitVideoGenerationJob(options: VideoGenerationOptions): Promise<VideoGenerationJob>;
19
+ /** Returns a normalized task snapshot, enforcing Seevio's 10-second poll cadence. */
20
+ getVideoGenerationJob(handle: VideoGenerationJob): Promise<VideoGenerationStatusResult>;
21
+ /** Downloads a completed video while validating the initial URL and every redirect. */
22
+ fetchVideoGenerationResult(handle: VideoGenerationJob): Promise<VideoGenerationResult>;
23
+ /** Reports cancellation as unsupported because Seevio documents no cancellation endpoint. */
24
+ cancelVideoGenerationJob(_handle: VideoGenerationJob): Promise<void>;
25
+ /** Performs an unbilled random task-id probe; an authenticated 404 is valid access. */
26
+ validateVideoGenerationAccess(): Promise<boolean>;
27
+ private mapTask;
28
+ /** Lists the single intentional Seevio model selection. */
29
+ getModels(): Promise<AIModel[]>;
30
+ /** Reports Seevio's video-only capability surface. */
31
+ getCapabilities(): Promise<AICapabilities>;
32
+ private unsupported;
33
+ /** @inheritdoc */ chat(_messages: AIMessage[], _options?: ChatOptions): Promise<AIResponse>;
34
+ /** @inheritdoc */ complete(_prompt: string, _options?: CompletionOptions): Promise<AIResponse>;
35
+ /** @inheritdoc */ message(_text: string, _options?: MessageOptions): Promise<string>;
36
+ /** @inheritdoc */ embed(_text: string | string[], _options?: EmbeddingOptions): Promise<EmbeddingResponse>;
37
+ /** @inheritdoc */ embedImage(_image: string | Buffer, _options?: ImageEmbeddingOptions): Promise<EmbeddingResponse>;
38
+ /** @inheritdoc */ describeImage(_image: string | Buffer, _prompt?: string, _options?: ImageDescriptionOptions): Promise<string>;
39
+ /** @inheritdoc */ generateImage(_prompt: string, _options?: ImageGenerationOptions): Promise<ImageGenerationResponse>;
40
+ /** @inheritdoc */ stream(_messages: AIMessage[], _options?: ChatOptions): AsyncIterable<string>;
41
+ /** @inheritdoc */ countTokens(_text: string): Promise<number>;
42
+ /** @inheritdoc */ synthesizeSpeech(_text: string, _options?: TTSOptions): Promise<TTSResponse>;
43
+ /** @inheritdoc */ streamSpeech(_text: string, _options?: TTSOptions): AsyncIterable<Buffer>;
44
+ /** @inheritdoc */ cloneVoice(_options: VoiceCloneOptions): Promise<Voice>;
45
+ /** @inheritdoc */ designVoice(_options: VoiceDesignOptions): Promise<Voice>;
46
+ /** @inheritdoc */ getVoices(_options?: VoiceListOptions): Promise<Voice[]>;
47
+ }
48
+ //# sourceMappingURL=seevio.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seevio.d.ts","sourceRoot":"","sources":["../../../src/shared/providers/seevio.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,KAAK,EACV,cAAc,EACd,WAAW,EACX,SAAS,EACT,OAAO,EACP,UAAU,EACV,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,uBAAuB,EACvB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,cAAc,EACd,aAAa,EACb,UAAU,EACV,WAAW,EAEX,kBAAkB,EAClB,sBAAsB,EAEtB,qBAAqB,EACrB,2BAA2B,EAC3B,KAAK,EACL,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAuJlB,iEAAiE;AACjE,qBAAa,cAAe,YAAW,WAAW;IAChD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgB;IACxC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAc;IAC5C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA6B;IACxD,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAG/B;IAEJ,wEAAwE;gBAC5D,OAAO,EAAE,aAAa;YAKpB,OAAO;YAeP,UAAU;IAyGxB,OAAO,CAAC,uBAAuB;YAYjB,sBAAsB;IA+FpC,OAAO,CAAC,SAAS;YA6EH,QAAQ;IAyCtB,OAAO,CAAC,iBAAiB;IAUzB,8DAA8D;IACxD,wBAAwB,CAC5B,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,kBAAkB,CAAC;IA+G9B,qFAAqF;IAC/E,qBAAqB,CACzB,MAAM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