@happyvertical/ai 0.79.0 → 0.80.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT.md +1 -1
- package/dist/chunks/anthropic-DA8sdt12.js +438 -0
- package/dist/chunks/anthropic-DA8sdt12.js.map +1 -0
- package/dist/chunks/bedrock-DDiYFUw0.js +699 -0
- package/dist/chunks/bedrock-DDiYFUw0.js.map +1 -0
- package/dist/chunks/bifrost-fM9FpW_w.js +198 -0
- package/dist/chunks/bifrost-fM9FpW_w.js.map +1 -0
- package/dist/chunks/claude-cli-CnJh5KQT.js +498 -0
- package/dist/chunks/claude-cli-CnJh5KQT.js.map +1 -0
- package/dist/chunks/gateway-admin-CiKvHst7.js +283 -0
- package/dist/chunks/gateway-admin-CiKvHst7.js.map +1 -0
- package/dist/chunks/gemini-Bu7Fke7c.js +593 -0
- package/dist/chunks/gemini-Bu7Fke7c.js.map +1 -0
- package/dist/chunks/huggingface-B07_6wHW.js +295 -0
- package/dist/chunks/huggingface-B07_6wHW.js.map +1 -0
- package/dist/chunks/litellm-D_Oo9OQ_.js +185 -0
- package/dist/chunks/litellm-D_Oo9OQ_.js.map +1 -0
- package/dist/chunks/ollama-D4ksOTO8.js +626 -0
- package/dist/chunks/ollama-D4ksOTO8.js.map +1 -0
- package/dist/chunks/openai--F38QHiJ.js +691 -0
- package/dist/chunks/openai--F38QHiJ.js.map +1 -0
- package/dist/chunks/qwen-tts-DRRbOrhA.js +333 -0
- package/dist/chunks/qwen-tts-DRRbOrhA.js.map +1 -0
- package/dist/chunks/rate-limit-BwyPGXFW.js +199 -0
- package/dist/chunks/rate-limit-BwyPGXFW.js.map +1 -0
- package/dist/chunks/safety-CEnoJS6X.js +260 -0
- package/dist/chunks/safety-CEnoJS6X.js.map +1 -0
- package/dist/chunks/types-FHs-KbGL.js +117 -0
- package/dist/chunks/types-FHs-KbGL.js.map +1 -0
- package/dist/chunks/usage-C1Y1Nlg4.js +35 -0
- package/dist/chunks/usage-C1Y1Nlg4.js.map +1 -0
- package/dist/cli/claude-context.js +17 -17
- package/dist/cli/claude-context.js.map +1 -1
- package/dist/index.js +717 -23
- package/dist/index.js.map +1 -1
- package/metadata.json +1 -1
- package/package.json +5 -5
- package/dist/chunks/anthropic-2z-82zgr.js +0 -530
- package/dist/chunks/anthropic-2z-82zgr.js.map +0 -1
- package/dist/chunks/bedrock-Dc2eVPUD.js +0 -920
- package/dist/chunks/bedrock-Dc2eVPUD.js.map +0 -1
- package/dist/chunks/bifrost-CEnCsciy.js +0 -258
- package/dist/chunks/bifrost-CEnCsciy.js.map +0 -1
- package/dist/chunks/claude-cli-X1ONjE8K.js +0 -603
- package/dist/chunks/claude-cli-X1ONjE8K.js.map +0 -1
- package/dist/chunks/gateway-admin-BUhBzXZb.js +0 -359
- package/dist/chunks/gateway-admin-BUhBzXZb.js.map +0 -1
- package/dist/chunks/gemini-CS56gY0D.js +0 -768
- package/dist/chunks/gemini-CS56gY0D.js.map +0 -1
- package/dist/chunks/huggingface-wQSfO5xA.js +0 -411
- package/dist/chunks/huggingface-wQSfO5xA.js.map +0 -1
- package/dist/chunks/index-DCXO0nZA.js +0 -1293
- package/dist/chunks/index-DCXO0nZA.js.map +0 -1
- package/dist/chunks/litellm-BMFTYbWc.js +0 -245
- package/dist/chunks/litellm-BMFTYbWc.js.map +0 -1
- package/dist/chunks/ollama-DsGDrA-c.js +0 -962
- package/dist/chunks/ollama-DsGDrA-c.js.map +0 -1
- package/dist/chunks/openai-CJEo69jb.js +0 -882
- package/dist/chunks/openai-CJEo69jb.js.map +0 -1
- package/dist/chunks/qwen-tts-BLYZ6d9s.js +0 -365
- package/dist/chunks/qwen-tts-BLYZ6d9s.js.map +0 -1
- package/dist/chunks/usage-DMWiJ2oB.js +0 -21
- package/dist/chunks/usage-DMWiJ2oB.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-FHs-KbGL.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\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] 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 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 * 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` also uses `requestsPerMinute` and `maxConcurrent` from this\n * object for its local token bucket limiter.\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 * 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\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// 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":";;;;AA2FA,IAAa,oBAAoB;CAC/B;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;;;;;;;;;;AAssDA,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"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
//#region src/shared/providers/usage.ts
|
|
2
|
+
/**
|
|
3
|
+
* Emit a usage event to the `onUsage` callback configured on provider options.
|
|
4
|
+
*
|
|
5
|
+
* @param providerOptions - The provider's stored options (for `onUsage` and global `usageTags`).
|
|
6
|
+
* @param providerName - Provider identifier (e.g. `'openai'`).
|
|
7
|
+
* @param operation - The operation type that generated this usage.
|
|
8
|
+
* @param model - Model that was used.
|
|
9
|
+
* @param usage - Token usage breakdown, if available.
|
|
10
|
+
* @param startTime - `Date.now()` captured before the API call.
|
|
11
|
+
* @param callTags - Per-call `usageTags` from the method's options.
|
|
12
|
+
*/
|
|
13
|
+
function emitUsage(providerOptions, providerName, operation, model, usage, startTime, callTags) {
|
|
14
|
+
if (!providerOptions.onUsage) return;
|
|
15
|
+
const globalTags = providerOptions.usageTags;
|
|
16
|
+
const tags = globalTags || callTags ? {
|
|
17
|
+
...globalTags,
|
|
18
|
+
...callTags
|
|
19
|
+
} : void 0;
|
|
20
|
+
try {
|
|
21
|
+
providerOptions.onUsage({
|
|
22
|
+
provider: providerName,
|
|
23
|
+
model,
|
|
24
|
+
operation,
|
|
25
|
+
usage,
|
|
26
|
+
duration: Date.now() - startTime,
|
|
27
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
28
|
+
tags
|
|
29
|
+
});
|
|
30
|
+
} catch {}
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
export { emitUsage as t };
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=usage-C1Y1Nlg4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage-C1Y1Nlg4.js","names":[],"sources":["../../src/shared/providers/usage.ts"],"sourcesContent":["/**\n * Shared usage-event emission helper.\n *\n * Every provider delegates to this so the tag-merge + try/catch semantics\n * are defined in exactly one place.\n */\n\nimport type { BaseAIOptions, TokenUsage, UsageEvent } from '../types';\n\n/**\n * Emit a usage event to the `onUsage` callback configured on provider options.\n *\n * @param providerOptions - The provider's stored options (for `onUsage` and global `usageTags`).\n * @param providerName - Provider identifier (e.g. `'openai'`).\n * @param operation - The operation type that generated this usage.\n * @param model - Model that was used.\n * @param usage - Token usage breakdown, if available.\n * @param startTime - `Date.now()` captured before the API call.\n * @param callTags - Per-call `usageTags` from the method's options.\n */\nexport function emitUsage(\n providerOptions: BaseAIOptions,\n providerName: string,\n operation: UsageEvent['operation'],\n model: string,\n usage: TokenUsage | undefined,\n startTime: number,\n callTags?: Record<string, string>,\n): void {\n if (!providerOptions.onUsage) return;\n\n const globalTags = providerOptions.usageTags;\n const tags =\n globalTags || callTags ? { ...globalTags, ...callTags } : undefined;\n\n try {\n providerOptions.onUsage({\n provider: providerName,\n model,\n operation,\n usage,\n duration: Date.now() - startTime,\n timestamp: new Date(),\n tags,\n });\n } catch {\n // Silently swallow consumer errors\n }\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,SAAgB,UACd,iBACA,cACA,WACA,OACA,OACA,WACA,UACM;CACN,IAAI,CAAC,gBAAgB,SAAS;CAE9B,MAAM,aAAa,gBAAgB;CACnC,MAAM,OACJ,cAAc,WAAW;EAAE,GAAG;EAAY,GAAG;CAAS,IAAI,KAAA;CAE5D,IAAI;EACF,gBAAgB,QAAQ;GACtB,UAAU;GACV;GACA;GACA;GACA,UAAU,KAAK,IAAI,IAAI;GACvB,2BAAW,IAAI,KAAK;GACpB;EACF,CAAC;CACH,QAAQ,CAER;AACF"}
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { existsSync, mkdirSync
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
17
|
-
if (existsSync(metaSrc)) {
|
|
18
|
-
copyFileSync(metaSrc, join(targetDir, `have-${pkgName}.meta.json`));
|
|
19
|
-
}
|
|
5
|
+
//#region src/cli/claude-context.ts
|
|
6
|
+
/**
|
|
7
|
+
* CLI script to install agent context for @happyvertical/ai
|
|
8
|
+
* Run the published context installer binary for this package.
|
|
9
|
+
*/
|
|
10
|
+
var pkgRoot = join(dirname(fileURLToPath(import.meta.url)), "../..");
|
|
11
|
+
var targetDir = join(process.cwd(), ".claude");
|
|
12
|
+
if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
|
|
13
|
+
var pkgName = "ai";
|
|
14
|
+
var agentMdSrc = existsSync(join(pkgRoot, "AGENT.md")) ? join(pkgRoot, "AGENT.md") : join(pkgRoot, "CLAUDE.md");
|
|
15
|
+
var metaSrc = existsSync(join(pkgRoot, "metadata.json")) ? join(pkgRoot, "metadata.json") : join(pkgRoot, ".claude-meta.json");
|
|
16
|
+
if (existsSync(agentMdSrc)) copyFileSync(agentMdSrc, join(targetDir, `have-${pkgName}.md`));
|
|
17
|
+
if (existsSync(metaSrc)) copyFileSync(metaSrc, join(targetDir, `have-${pkgName}.meta.json`));
|
|
20
18
|
console.log(`✓ Installed @happyvertical/${pkgName} context to .claude/`);
|
|
21
|
-
//#
|
|
19
|
+
//#endregion
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=claude-context.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-context.js","sources":["../../src/cli/claude-context.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * CLI script to install agent context for @happyvertical/ai\n * Run the published context installer binary for this package.\n */\nimport { copyFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst Dirname = dirname(fileURLToPath(import.meta.url));\nconst pkgRoot = join(Dirname, '../..');\nconst targetDir = join(process.cwd(), '.claude');\n\nif (!existsSync(targetDir)) {\n mkdirSync(targetDir, { recursive: true });\n}\n\nconst pkgName = 'ai';\nconst agentMdSrc = existsSync(join(pkgRoot, 'AGENT.md'))\n ? join(pkgRoot, 'AGENT.md')\n : join(pkgRoot, 'CLAUDE.md');\nconst metaSrc = existsSync(join(pkgRoot, 'metadata.json'))\n ? join(pkgRoot, 'metadata.json')\n : join(pkgRoot, '.claude-meta.json');\n\nif (existsSync(agentMdSrc)) {\n copyFileSync(agentMdSrc, join(targetDir, `have-${pkgName}.md`));\n}\n\nif (existsSync(metaSrc)) {\n copyFileSync(metaSrc, join(targetDir, `have-${pkgName}.meta.json`));\n}\n\nconsole.log(`✓ Installed @happyvertical/${pkgName} context to .claude/`);\n"],"
|
|
1
|
+
{"version":3,"file":"claude-context.js","names":[],"sources":["../../src/cli/claude-context.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * CLI script to install agent context for @happyvertical/ai\n * Run the published context installer binary for this package.\n */\nimport { copyFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst Dirname = dirname(fileURLToPath(import.meta.url));\nconst pkgRoot = join(Dirname, '../..');\nconst targetDir = join(process.cwd(), '.claude');\n\nif (!existsSync(targetDir)) {\n mkdirSync(targetDir, { recursive: true });\n}\n\nconst pkgName = 'ai';\nconst agentMdSrc = existsSync(join(pkgRoot, 'AGENT.md'))\n ? join(pkgRoot, 'AGENT.md')\n : join(pkgRoot, 'CLAUDE.md');\nconst metaSrc = existsSync(join(pkgRoot, 'metadata.json'))\n ? join(pkgRoot, 'metadata.json')\n : join(pkgRoot, '.claude-meta.json');\n\nif (existsSync(agentMdSrc)) {\n copyFileSync(agentMdSrc, join(targetDir, `have-${pkgName}.md`));\n}\n\nif (existsSync(metaSrc)) {\n copyFileSync(metaSrc, join(targetDir, `have-${pkgName}.meta.json`));\n}\n\nconsole.log(`✓ Installed @happyvertical/${pkgName} context to .claude/`);\n"],"mappings":";;;;;;;;;AAUA,IAAM,UAAU,KADA,QAAQ,cAAc,OAAO,KAAK,GAAG,CAChC,GAAS,OAAO;AACrC,IAAM,YAAY,KAAK,QAAQ,IAAI,GAAG,SAAS;AAE/C,IAAI,CAAC,WAAW,SAAS,GACvB,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;AAG1C,IAAM,UAAU;AAChB,IAAM,aAAa,WAAW,KAAK,SAAS,UAAU,CAAC,IACnD,KAAK,SAAS,UAAU,IACxB,KAAK,SAAS,WAAW;AAC7B,IAAM,UAAU,WAAW,KAAK,SAAS,eAAe,CAAC,IACrD,KAAK,SAAS,eAAe,IAC7B,KAAK,SAAS,mBAAmB;AAErC,IAAI,WAAW,UAAU,GACvB,aAAa,YAAY,KAAK,WAAW,QAAQ,QAAQ,IAAI,CAAC;AAGhE,IAAI,WAAW,OAAO,GACpB,aAAa,SAAS,KAAK,WAAW,QAAQ,QAAQ,WAAW,CAAC;AAGpE,QAAQ,IAAI,8BAA8B,QAAQ,qBAAqB"}
|