@happyvertical/ai 0.85.4 → 0.86.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 (84) hide show
  1. package/README.md +87 -1
  2. package/dist/chunks/{anthropic-DA8sdt12.js → anthropic-DuYUnw8j.js} +20 -4
  3. package/dist/chunks/anthropic-DuYUnw8j.js.map +1 -0
  4. package/dist/chunks/{bedrock-DDiYFUw0.js → bedrock-ikQJAwWB.js} +19 -3
  5. package/dist/chunks/bedrock-ikQJAwWB.js.map +1 -0
  6. package/dist/chunks/{bifrost-fM9FpW_w.js → bifrost-CaYhelVL.js} +5 -4
  7. package/dist/chunks/bifrost-CaYhelVL.js.map +1 -0
  8. package/dist/chunks/byteplus-modelark-B8l8sPXu.js +473 -0
  9. package/dist/chunks/byteplus-modelark-B8l8sPXu.js.map +1 -0
  10. package/dist/chunks/{claude-cli-CnJh5KQT.js → claude-cli-DeTKk9nu.js} +19 -3
  11. package/dist/chunks/claude-cli-DeTKk9nu.js.map +1 -0
  12. package/dist/chunks/{gateway-admin-CiKvHst7.js → gateway-admin-DJXEDpUP.js} +2 -2
  13. package/dist/chunks/{gateway-admin-CiKvHst7.js.map → gateway-admin-DJXEDpUP.js.map} +1 -1
  14. package/dist/chunks/{gemini-Bu7Fke7c.js → gemini-BT8fjXWz.js} +294 -11
  15. package/dist/chunks/gemini-BT8fjXWz.js.map +1 -0
  16. package/dist/chunks/{huggingface-B07_6wHW.js → huggingface-CqzyxeLB.js} +19 -3
  17. package/dist/chunks/huggingface-CqzyxeLB.js.map +1 -0
  18. package/dist/chunks/{litellm-D_Oo9OQ_.js → litellm-viqTuSY8.js} +5 -4
  19. package/dist/chunks/litellm-viqTuSY8.js.map +1 -0
  20. package/dist/chunks/{ollama-D4ksOTO8.js → ollama-CdWqwZ05.js} +19 -3
  21. package/dist/chunks/ollama-CdWqwZ05.js.map +1 -0
  22. package/dist/chunks/{openai--F38QHiJ.js → openai-BgrK3OfW.js} +20 -4
  23. package/dist/chunks/openai-BgrK3OfW.js.map +1 -0
  24. package/dist/chunks/openai-compat-video-D_U7jo0d.js +369 -0
  25. package/dist/chunks/openai-compat-video-D_U7jo0d.js.map +1 -0
  26. package/dist/chunks/{qwen-tts-DRRbOrhA.js → qwen-tts-BXjzY7DX.js} +21 -4
  27. package/dist/chunks/qwen-tts-BXjzY7DX.js.map +1 -0
  28. package/dist/chunks/{rate-limit-BwyPGXFW.js → rate-limit-DgEhanDL.js} +4 -3
  29. package/dist/chunks/rate-limit-DgEhanDL.js.map +1 -0
  30. package/dist/chunks/{safety-CEnoJS6X.js → safety-C415clBm.js} +25 -7
  31. package/dist/chunks/safety-C415clBm.js.map +1 -0
  32. package/dist/chunks/src-CU4qWJ2c.js +740 -0
  33. package/dist/chunks/src-CU4qWJ2c.js.map +1 -0
  34. package/dist/chunks/{types-FHs-KbGL.js → types-CINwUPDo.js} +4 -2
  35. package/dist/chunks/types-CINwUPDo.js.map +1 -0
  36. package/dist/index.js +3 -717
  37. package/dist/node/factory.d.ts +9 -0
  38. package/dist/node/factory.d.ts.map +1 -1
  39. package/dist/node.d.ts +29 -0
  40. package/dist/node.d.ts.map +1 -0
  41. package/dist/node.js +198 -0
  42. package/dist/node.js.map +1 -0
  43. package/dist/shared/factory.d.ts.map +1 -1
  44. package/dist/shared/providers/anthropic.d.ts +6 -1
  45. package/dist/shared/providers/anthropic.d.ts.map +1 -1
  46. package/dist/shared/providers/bedrock.d.ts +6 -1
  47. package/dist/shared/providers/bedrock.d.ts.map +1 -1
  48. package/dist/shared/providers/bifrost.d.ts.map +1 -1
  49. package/dist/shared/providers/byteplus-modelark.d.ts +91 -0
  50. package/dist/shared/providers/byteplus-modelark.d.ts.map +1 -0
  51. package/dist/shared/providers/claude-cli.d.ts +6 -1
  52. package/dist/shared/providers/claude-cli.d.ts.map +1 -1
  53. package/dist/shared/providers/gemini.d.ts +115 -2
  54. package/dist/shared/providers/gemini.d.ts.map +1 -1
  55. package/dist/shared/providers/huggingface.d.ts +6 -1
  56. package/dist/shared/providers/huggingface.d.ts.map +1 -1
  57. package/dist/shared/providers/litellm.d.ts.map +1 -1
  58. package/dist/shared/providers/ollama.d.ts +6 -1
  59. package/dist/shared/providers/ollama.d.ts.map +1 -1
  60. package/dist/shared/providers/openai-compat-video.d.ts +98 -0
  61. package/dist/shared/providers/openai-compat-video.d.ts.map +1 -0
  62. package/dist/shared/providers/openai.d.ts +6 -1
  63. package/dist/shared/providers/openai.d.ts.map +1 -1
  64. package/dist/shared/providers/qwen-tts.d.ts +6 -1
  65. package/dist/shared/providers/qwen-tts.d.ts.map +1 -1
  66. package/dist/shared/rate-limit.d.ts.map +1 -1
  67. package/dist/shared/safety.d.ts.map +1 -1
  68. package/dist/shared/types.d.ts +343 -5
  69. package/dist/shared/types.d.ts.map +1 -1
  70. package/package.json +7 -3
  71. package/dist/chunks/anthropic-DA8sdt12.js.map +0 -1
  72. package/dist/chunks/bedrock-DDiYFUw0.js.map +0 -1
  73. package/dist/chunks/bifrost-fM9FpW_w.js.map +0 -1
  74. package/dist/chunks/claude-cli-CnJh5KQT.js.map +0 -1
  75. package/dist/chunks/gemini-Bu7Fke7c.js.map +0 -1
  76. package/dist/chunks/huggingface-B07_6wHW.js.map +0 -1
  77. package/dist/chunks/litellm-D_Oo9OQ_.js.map +0 -1
  78. package/dist/chunks/ollama-D4ksOTO8.js.map +0 -1
  79. package/dist/chunks/openai--F38QHiJ.js.map +0 -1
  80. package/dist/chunks/qwen-tts-DRRbOrhA.js.map +0 -1
  81. package/dist/chunks/rate-limit-BwyPGXFW.js.map +0 -1
  82. package/dist/chunks/safety-CEnoJS6X.js.map +0 -1
  83. package/dist/chunks/types-FHs-KbGL.js.map +0 -1
  84. package/dist/index.js.map +0 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @happyvertical/ai
2
2
 
3
- Unified interface for AI model interactions across multiple providers. Supports OpenAI, LiteLLM, Bifrost, Ollama, Anthropic Claude, Google Gemini, AWS Bedrock, Hugging Face, Claude CLI, and Qwen3-TTS with a consistent API for chat, completions, embeddings, streaming, function calling, image operations, text-to-speech, and gateway admin provisioning where available.
3
+ Unified interface for AI model interactions across multiple providers. Supports OpenAI, LiteLLM, Bifrost, Ollama, Anthropic Claude, Google Gemini, AWS Bedrock, Hugging Face, Claude CLI, Qwen3-TTS, and video-generation providers (Gemini Veo, BytePlus ModelArk/Seedance, OpenAI-compatible `/v1/videos` gateways) with a consistent API for chat, completions, embeddings, streaming, function calling, image operations, asynchronous video generation, text-to-speech, and gateway admin provisioning where available.
4
4
 
5
5
  ## Installation
6
6
 
@@ -99,8 +99,87 @@ const cli = await getAI({ type: 'claude-cli', defaultModel: 'sonnet' });
99
99
 
100
100
  // Qwen3-TTS (text-to-speech only)
101
101
  const tts = await getAI({ type: 'qwen3-tts', endpoint: 'http://localhost:8880' });
102
+
103
+ // BytePlus ModelArk / Seedance (video generation only)
104
+ const modelark = await getAI({
105
+ type: 'byteplus-modelark',
106
+ apiKey: process.env.MODELARK_API_KEY!, // or ARK_API_KEY
107
+ });
108
+
109
+ // OpenAI-compatible /v1/videos gateway (video generation only)
110
+ const video = await getAI({
111
+ type: 'openai-compat-video',
112
+ baseUrl: process.env.OPENAI_COMPAT_VIDEO_BASE_URL || 'https://llm.happyvertical.com/v1',
113
+ apiKey: process.env.OPENAI_COMPAT_VIDEO_API_KEY!,
114
+ });
115
+ ```
116
+
117
+ ## Video Generation
118
+
119
+ Video generation is asynchronous: `submitVideoGenerationJob` returns a JSON-serializable
120
+ handle immediately, and the render itself runs as a provider-side job that you poll with
121
+ `getVideoGenerationJob`. Persist the handle (it has no closures or client instances) to
122
+ resume polling after a restart, and always call `cancelVideoGenerationJob` on abort so you
123
+ are not billed for orphaned renders.
124
+
125
+ ```typescript
126
+ const ai = await getAI({ type: 'gemini', apiKey: process.env.GEMINI_API_KEY! });
127
+
128
+ const job = await ai.submitVideoGenerationJob({
129
+ prompt: 'A drone shot flying over a coastal cliff at sunrise',
130
+ durationSeconds: 8,
131
+ resolution: '1080p',
132
+ aspectRatio: '16:9',
133
+ });
134
+
135
+ // Persist `job` (plain JSON) and resume polling later, even after a process restart.
136
+ let status = await ai.getVideoGenerationJob(job);
137
+ while (status.status === 'queued' || status.status === 'running') {
138
+ await new Promise((resolve) => setTimeout(resolve, 5000));
139
+ status = await ai.getVideoGenerationJob(job);
140
+ }
141
+
142
+ if (status.status === 'succeeded') {
143
+ const result = await ai.fetchVideoGenerationResult(job);
144
+ if (result.data) fs.writeFileSync('output.mp4', result.data);
145
+ }
146
+
147
+ // On abort/step cancellation (best-effort — see below):
148
+ await ai.cancelVideoGenerationJob(job).catch((error) => {
149
+ console.warn('Could not cancel video job', job.jobId, error);
150
+ });
102
151
  ```
103
152
 
153
+ Supported providers: `gemini` (Veo, via `@google/genai` long-running operations),
154
+ `byteplus-modelark` (Seedance, raw-HTTP ModelArk task API), and `openai-compat-video`
155
+ (thin adapter over a `/v1/videos`-shaped REST surface — LiteLLM's Veo passthrough,
156
+ Sora-shaped gateways). Providers without video support throw `NOT_IMPLEMENTED`, and
157
+ `ai.getCapabilities()` reports `videoGeneration: false` for them.
158
+
159
+ **Cancellation is best-effort, not a guarantee.** Gemini has no cancel endpoint for
160
+ video-generation operations at all and always throws; ModelArk can only cancel a task
161
+ that hasn't started rendering yet (`queued`) and rejects cancellation of a `running`
162
+ one. Callers must catch and tolerate a `cancelVideoGenerationJob` failure rather than
163
+ treating it as fatal.
164
+
165
+ `byteplus-modelark` locally throttles `submitVideoGenerationJob` to approximate
166
+ Seedance's documented account limits (QPS 2, small burst / 3 concurrent
167
+ *submissions* — pass `rateLimit: { requestsPerMinute, maxConcurrent }` to override the
168
+ defaults). This limiter is shared across provider instances constructed with the same
169
+ `apiKey`, since a fresh instance is often constructed per pipeline step. It bounds
170
+ concurrent submit HTTP requests, not the lifetime of the render tasks those
171
+ submissions create — ModelArk doesn't expose a way to observe when a task actually
172
+ finishes rendering, so task-lifetime concurrency isn't tracked. `submitVideoGenerationJob`
173
+ is also registered with the shared [rate-limit pacing wrapper](#opt-in-rate-limit-pacing),
174
+ so `rateLimit.enabled` works the same way it does for `chat`.
175
+
176
+ Every provider exposes a cheap `validateVideoGenerationAccess()` auth-shaped check
177
+ (a low-cost call — the exact shape is provider-specific: a model/task list for
178
+ Gemini/ModelArk, a single-resource probe for `openai-compat-video` since LiteLLM's
179
+ list route requires a parameter this generic adapter can't supply). It is not free —
180
+ callers on a hot path must cache the result themselves rather than calling it on every
181
+ iteration.
182
+
104
183
  ## Gateway Admin
105
184
 
106
185
  Gateway providers that support provisioning expose `ai.admin`.
@@ -300,6 +379,8 @@ for (const site of sites) {
300
379
  - `GEMINI_API_KEY`, `GOOGLE_API_KEY`
301
380
  - `HF_TOKEN`
302
381
  - `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`
382
+ - `MODELARK_API_KEY` / `ARK_API_KEY`, `MODELARK_BASE_URL`
383
+ - `OPENAI_COMPAT_VIDEO_BASE_URL`, `OPENAI_COMPAT_VIDEO_API_KEY`
303
384
 
304
385
  ## API Overview
305
386
 
@@ -322,6 +403,11 @@ All providers implement `AIInterface`:
322
403
  | `embedImage(image, options?)` | Image embeddings (Gemini and Bedrock native, OpenAI and Ollama via describe-then-embed) |
323
404
  | `describeImage(image, prompt?, options?)` | Image description via vision models |
324
405
  | `generateImage(prompt, options?)` | Image generation (DALL-E, Imagen, Titan Image Generator, Ollama-compatible image models) |
406
+ | `submitVideoGenerationJob(options)` | Submit an async video-generation job, returning a serializable handle |
407
+ | `getVideoGenerationJob(handle)` | Poll job status (`queued`\|`running`\|`succeeded`\|`failed`\|`cancelled`) |
408
+ | `fetchVideoGenerationResult(handle)` | Fetch the generated video once the job has succeeded |
409
+ | `cancelVideoGenerationJob(handle)` | Cancel an in-flight video-generation job |
410
+ | `validateVideoGenerationAccess()` | Cheap auth-shaped check for video-generation access (cache the result) |
325
411
  | `countTokens(text)` | Token count estimation |
326
412
  | `getModels()` | List available models |
327
413
  | `getCapabilities()` | Query provider capabilities |
@@ -1,6 +1,6 @@
1
- import { a as ContextLengthError, c as extractTextContent, o as ModelNotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./types-FHs-KbGL.js";
2
- import { n as extractRetryAfterSeconds } from "./rate-limit-BwyPGXFW.js";
3
- import { a as normalizeBaseAIOptions, c as prepareRequestControls, o as normalizeChatOptions } from "./safety-CEnoJS6X.js";
1
+ import { a as ContextLengthError, c as extractTextContent, o as ModelNotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./types-CINwUPDo.js";
2
+ import { n as extractRetryAfterSeconds } from "./rate-limit-DgEhanDL.js";
3
+ import { a as normalizeBaseAIOptions, c as prepareRequestControls, o as normalizeChatOptions } from "./safety-C415clBm.js";
4
4
  import { t as emitUsage } from "./usage-C1Y1Nlg4.js";
5
5
  //#region src/shared/providers/anthropic.ts
6
6
  /**
@@ -355,6 +355,7 @@ var AnthropicProvider = class {
355
355
  fineTuning: false,
356
356
  imageEmbeddings: false,
357
357
  imageGeneration: false,
358
+ videoGeneration: false,
358
359
  tts: false,
359
360
  voiceCloning: false,
360
361
  voiceDesign: false,
@@ -368,6 +369,21 @@ var AnthropicProvider = class {
368
369
  ]
369
370
  };
370
371
  }
372
+ async submitVideoGenerationJob(_options) {
373
+ throw new AIError("Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "anthropic");
374
+ }
375
+ async getVideoGenerationJob(_handle) {
376
+ throw new AIError("Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "anthropic");
377
+ }
378
+ async fetchVideoGenerationResult(_handle) {
379
+ throw new AIError("Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "anthropic");
380
+ }
381
+ async cancelVideoGenerationJob(_handle) {
382
+ throw new AIError("Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "anthropic");
383
+ }
384
+ async validateVideoGenerationAccess() {
385
+ throw new AIError("Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "anthropic");
386
+ }
371
387
  async synthesizeSpeech(_text, _options) {
372
388
  throw new AIError("TTS is not supported by Anthropic provider. Use Qwen3-TTS provider.", "NOT_IMPLEMENTED", "anthropic");
373
389
  }
@@ -435,4 +451,4 @@ var AnthropicProvider = class {
435
451
  //#endregion
436
452
  export { AnthropicProvider };
437
453
 
438
- //# sourceMappingURL=anthropic-DA8sdt12.js.map
454
+ //# sourceMappingURL=anthropic-DuYUnw8j.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-DuYUnw8j.js","names":[],"sources":["../../src/shared/providers/anthropic.ts"],"sourcesContent":["/**\n * Anthropic Claude provider implementation\n *\n * Provides a standardized interface for interacting with Anthropic's Claude models,\n * including chat completions, streaming responses, and vision capabilities.\n * Note: Claude models do not support embeddings - use OpenAI or another provider for that.\n */\n\nimport { extractRetryAfterSeconds } from '../rate-limit';\nimport {\n normalizeBaseAIOptions,\n normalizeChatOptions,\n type PreparedRequestControls,\n prepareRequestControls,\n} from '../safety';\nimport type {\n AICapabilities,\n AIInterface,\n AIMessage,\n AIModel,\n AIResponse,\n AnthropicOptions,\n ChatOptions,\n CompletionOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n MessageOptions,\n TokenUsage,\n TTSOptions,\n TTSResponse,\n VideoGenerationJob,\n VideoGenerationOptions,\n VideoGenerationResult,\n VideoGenerationStatusResult,\n Voice,\n VoiceCloneOptions,\n VoiceDesignOptions,\n VoiceListOptions,\n} from '../types';\nimport {\n AIError,\n AuthenticationError,\n ContextLengthError,\n extractTextContent,\n ModelNotFoundError,\n RateLimitError,\n} from '../types';\nimport { emitUsage } from './usage';\n\n// Note: This implementation will require @anthropic-ai/sdk package\n// For now, this is a placeholder that defines the interface\n\n/**\n * Anthropic Claude provider implementation that handles all interactions with Anthropic's API.\n * Supports Claude models, streaming, vision capabilities, and function calling.\n * Does not support embeddings (use OpenAI or another provider for embeddings).\n */\nexport class AnthropicProvider implements AIInterface {\n private options: AnthropicOptions;\n private client: any; // Will be Anthropic instance from @anthropic-ai/sdk\n\n /**\n * Creates a new Anthropic provider instance\n * @param options - Configuration options for the Anthropic provider\n */\n constructor(options: AnthropicOptions) {\n this.options = normalizeBaseAIOptions({\n defaultModel: 'claude-3-5-sonnet-20241022',\n anthropicVersion: '2023-06-01',\n ...options,\n });\n\n // Initialize Anthropic client\n this.initializeClientSync();\n }\n\n private initializeClientSync() {\n try {\n // Dynamic import in constructor - this will work if the package is installed\n import('@anthropic-ai/sdk')\n .then(({ Anthropic }) => {\n this.client = new Anthropic({\n apiKey: this.options.apiKey,\n baseURL: this.options.baseUrl,\n timeout: this.options.timeout,\n maxRetries: this.options.maxRetries,\n defaultHeaders: {\n 'anthropic-version': this.options.anthropicVersion,\n ...this.options.headers,\n },\n });\n })\n .catch(() => {\n // Client will be null and we'll handle it in methods\n });\n } catch (_error) {\n // Client will be null and we'll handle it in methods\n }\n }\n\n /**\n * Ensures the Anthropic client is initialized by dynamically importing the SDK\n * @throws {AIError} When the Anthropic SDK cannot be loaded\n * @private\n */\n private async ensureClient() {\n if (!this.client) {\n try {\n const { Anthropic } = await import('@anthropic-ai/sdk');\n this.client = new Anthropic({\n apiKey: this.options.apiKey,\n baseURL: this.options.baseUrl,\n timeout: this.options.timeout,\n maxRetries: this.options.maxRetries,\n defaultHeaders: {\n 'anthropic-version': this.options.anthropicVersion,\n ...this.options.headers,\n },\n });\n } catch (_error) {\n throw new AIError(\n 'Failed to initialize Anthropic client. Make sure @anthropic-ai/sdk is installed.',\n 'INITIALIZATION_ERROR',\n 'anthropic',\n );\n }\n }\n }\n\n /**\n * Generate a chat completion using Claude models\n * @param messages - Array of conversation messages\n * @param options - Optional configuration for the chat completion\n * @returns Promise resolving to the AI response with content and metadata\n * @throws {AIError} When the API request fails or SDK is not available\n *\n * @example\n * ```typescript\n * const response = await provider.chat([\n * { role: 'system', content: 'You are a helpful assistant.' },\n * { role: 'user', content: 'Explain quantum computing' }\n * ], {\n * model: 'claude-3-5-sonnet-20241022',\n * maxTokens: 1000\n * });\n * ```\n */\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const { system, anthropicMessages } =\n this.mapMessagesToAnthropic(messages);\n\n const model = options.model || this.options.defaultModel;\n options = normalizeChatOptions(this.options, options, 'anthropic', model);\n controls = prepareRequestControls(this.options, options);\n\n // Build request parameters\n const requestParams: Record<string, any> = {\n model,\n messages: anthropicMessages,\n max_tokens: options.maxTokens,\n temperature: options.temperature,\n top_p: options.topP,\n stop_sequences: Array.isArray(options.stop)\n ? options.stop\n : options.stop\n ? [options.stop]\n : undefined,\n system: system || undefined,\n tools:\n options.tools && options.tools.length > 0\n ? options.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description || '',\n input_schema: tool.function.parameters || { type: 'object' },\n }))\n : undefined,\n tool_choice: this.mapToolChoice(options.toolChoice),\n stream: false,\n };\n if ((options.reasoning?.maxTokens || 0) > 0) {\n requestParams.thinking = {\n type: 'enabled',\n budget_tokens: options.reasoning?.maxTokens,\n };\n }\n\n // Add response format if specified\n if (options.responseFormat?.type === 'json_object') {\n const jsonInstruction =\n '\\n\\nIMPORTANT: You must respond with valid JSON only. Do not include any explanatory text outside the JSON object.';\n requestParams.system = requestParams.system\n ? requestParams.system + jsonInstruction\n : jsonInstruction.trim();\n }\n\n const response = await this.client.messages.create(requestParams, {\n signal: controls.signal,\n timeout: controls.timeout,\n });\n\n // Extract text content and tool calls from response\n const textContent = response.content\n .filter((block: any) => block.type === 'text')\n .map((block: any) => block.text)\n .join('');\n\n const toolCalls = response.content\n .filter((block: any) => block.type === 'tool_use')\n .map((block: any) => ({\n id: block.id,\n type: 'function' as const,\n function: {\n name: block.name,\n arguments: JSON.stringify(block.input),\n },\n }));\n\n const usage: TokenUsage = {\n promptTokens: response.usage.input_tokens,\n completionTokens: response.usage.output_tokens,\n totalTokens: response.usage.input_tokens + response.usage.output_tokens,\n };\n emitUsage(\n this.options,\n 'anthropic',\n 'chat',\n response.model || model,\n usage,\n startTime,\n options.usageTags,\n );\n\n return {\n content: textContent,\n model: response.model,\n finishReason: this.mapFinishReason(response.stop_reason),\n usage,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n };\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'anthropic',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'anthropic',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n async complete(\n prompt: string,\n options: CompletionOptions = {},\n ): Promise<AIResponse> {\n return this.chat([{ role: 'user', content: prompt }], {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n n: options.n,\n stop: options.stop,\n stream: options.stream,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n });\n }\n\n /**\n * Simple message interface for single-turn interactions with optional history\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 usage\n * const response = await provider.message('Hello!');\n *\n * // With history\n * const response = await provider.message('What was my question?', {\n * history: [\n * { role: 'user', content: 'What is 2+2?' },\n * { role: 'assistant', content: '4' }\n * ]\n * });\n * ```\n */\n async message(text: string, options: MessageOptions = {}): Promise<string> {\n // Build messages array from history + current message\n const messages: AIMessage[] = [\n ...(options.history || []),\n { role: options.role || 'user', content: text },\n ];\n\n const response = await this.chat(messages, {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n stop: options.stop,\n stream: options.stream,\n frequencyPenalty: options.frequencyPenalty,\n presencePenalty: options.presencePenalty,\n responseFormat: options.responseFormat,\n seed: options.seed,\n tools: options.tools,\n toolChoice: options.toolChoice,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n });\n\n return response.content;\n }\n\n async embed(\n _text: string | string[],\n _options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n // Anthropic Claude doesn't provide embeddings API\n throw new AIError(\n 'Anthropic Claude does not support embeddings. Use OpenAI or another provider for embeddings.',\n 'NOT_SUPPORTED',\n 'anthropic',\n );\n }\n\n async embedImage(\n _image: string | Buffer,\n _options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n throw new AIError(\n 'Anthropic Claude does not support image embeddings. Use OpenAI or Gemini.',\n 'NOT_SUPPORTED',\n 'anthropic',\n );\n }\n\n async describeImage(\n _image: string | Buffer,\n _prompt?: string,\n _options: ImageDescriptionOptions = {},\n ): Promise<string> {\n // Note: Claude does support vision, but we're keeping this as a stub for now\n // A full implementation could use the chat API with image content\n throw new AIError(\n 'Image description is not yet implemented for Anthropic. Use OpenAI or Gemini.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n async generateImage(\n _prompt: string,\n _options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n throw new AIError(\n 'Anthropic Claude does not support image generation. Use OpenAI or Gemini.',\n 'NOT_SUPPORTED',\n 'anthropic',\n );\n }\n\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const { system, anthropicMessages } =\n this.mapMessagesToAnthropic(messages);\n\n const model = options.model || this.options.defaultModel;\n options = normalizeChatOptions(this.options, options, 'anthropic', model);\n controls = prepareRequestControls(this.options, options);\n\n const requestParams: Record<string, any> = {\n model,\n messages: anthropicMessages,\n max_tokens: options.maxTokens,\n temperature: options.temperature,\n top_p: options.topP,\n stop_sequences: Array.isArray(options.stop)\n ? options.stop\n : options.stop\n ? [options.stop]\n : undefined,\n system: system || undefined,\n stream: true,\n };\n if ((options.reasoning?.maxTokens || 0) > 0) {\n requestParams.thinking = {\n type: 'enabled',\n budget_tokens: options.reasoning?.maxTokens,\n };\n }\n const stream = await this.client.messages.create(requestParams, {\n signal: controls.signal,\n timeout: controls.timeout,\n });\n\n for await (const chunk of stream) {\n if (\n chunk.type === 'content_block_delta' &&\n chunk.delta.type === 'text_delta'\n ) {\n if (options.onProgress) {\n options.onProgress(chunk.delta.text);\n }\n yield chunk.delta.text;\n }\n }\n\n emitUsage(\n this.options,\n 'anthropic',\n 'stream',\n model!,\n undefined,\n startTime,\n options.usageTags,\n );\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'anthropic',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'anthropic',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n async countTokens(text: string): Promise<number> {\n // Anthropic doesn't provide a direct token counting API\n // This is an approximation - Claude uses a different tokenizer than OpenAI\n return Math.ceil(text.length / 3.5); // Slightly different ratio for Claude\n }\n\n async getModels(): Promise<AIModel[]> {\n // Return static list of known Claude models\n return [\n {\n id: 'claude-3-5-sonnet-20241022',\n name: 'Claude 3.5 Sonnet',\n description: 'Most intelligent Claude model with balanced performance',\n contextLength: 200000,\n capabilities: ['text', 'chat', 'vision', 'functions'],\n supportsFunctions: true,\n supportsVision: true,\n },\n {\n id: 'claude-3-5-haiku-20241022',\n name: 'Claude 3.5 Haiku',\n description: 'Fastest Claude model for simple tasks',\n contextLength: 200000,\n capabilities: ['text', 'chat', 'vision'],\n supportsFunctions: true,\n supportsVision: true,\n },\n {\n id: 'claude-3-opus-20240229',\n name: 'Claude 3 Opus',\n description: 'Most powerful Claude model for complex tasks',\n contextLength: 200000,\n capabilities: ['text', 'chat', 'vision', 'functions'],\n supportsFunctions: true,\n supportsVision: true,\n },\n {\n id: 'claude-3-sonnet-20240229',\n name: 'Claude 3 Sonnet',\n description: 'Balanced Claude model for most tasks',\n contextLength: 200000,\n capabilities: ['text', 'chat', 'vision'],\n supportsFunctions: true,\n supportsVision: true,\n },\n {\n id: 'claude-3-haiku-20240307',\n name: 'Claude 3 Haiku',\n description: 'Fast Claude model for simple tasks',\n contextLength: 200000,\n capabilities: ['text', 'chat', 'vision'],\n supportsFunctions: false,\n supportsVision: true,\n },\n ];\n }\n\n async getCapabilities(): Promise<AICapabilities> {\n return {\n chat: true,\n completion: true,\n embeddings: false, // Claude doesn't support embeddings\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: false,\n imageEmbeddings: false,\n imageGeneration: false,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 200000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'streaming',\n 'functions',\n 'vision',\n ],\n };\n }\n\n // ============================================================================\n // Video Generation Methods (Not supported - use gemini, byteplus-modelark,\n // or openai-compat-video provider)\n // ============================================================================\n\n async submitVideoGenerationJob(\n _options: VideoGenerationOptions,\n ): Promise<VideoGenerationJob> {\n throw new AIError(\n 'Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n async getVideoGenerationJob(\n _handle: VideoGenerationJob,\n ): Promise<VideoGenerationStatusResult> {\n throw new AIError(\n 'Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n async fetchVideoGenerationResult(\n _handle: VideoGenerationJob,\n ): Promise<VideoGenerationResult> {\n throw new AIError(\n 'Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n async cancelVideoGenerationJob(_handle: VideoGenerationJob): Promise<void> {\n throw new AIError(\n 'Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n async validateVideoGenerationAccess(): Promise<boolean> {\n throw new AIError(\n 'Video generation is not supported by Anthropic provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n // ============================================================================\n // TTS Methods (Not supported - use Qwen3-TTS provider)\n // ============================================================================\n\n async synthesizeSpeech(\n _text: string,\n _options?: TTSOptions,\n ): Promise<TTSResponse> {\n throw new AIError(\n 'TTS is not supported by Anthropic provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n streamSpeech(_text: string, _options?: TTSOptions): AsyncIterable<Buffer> {\n const error = new AIError(\n 'TTS streaming is not supported by Anthropic provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n return {\n [Symbol.asyncIterator]: () => ({\n next: () => Promise.reject(error),\n }),\n };\n }\n\n async cloneVoice(_options: VoiceCloneOptions): Promise<Voice> {\n throw new AIError(\n 'Voice cloning is not supported by Anthropic provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n async designVoice(_options: VoiceDesignOptions): Promise<Voice> {\n throw new AIError(\n 'Voice design is not supported by Anthropic provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n async getVoices(_options?: VoiceListOptions): Promise<Voice[]> {\n throw new AIError(\n 'Voice listing is not supported by Anthropic provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'anthropic',\n );\n }\n\n private mapMessagesToAnthropic(messages: AIMessage[]): {\n system?: string;\n anthropicMessages: Array<{ role: 'user' | 'assistant'; content: string }>;\n } {\n // Anthropic handles system messages separately\n let system: string | undefined;\n const anthropicMessages: Array<{\n role: 'user' | 'assistant';\n content: string;\n }> = [];\n\n for (const message of messages) {\n const textContent = extractTextContent(message.content);\n if (message.role === 'system') {\n // Combine multiple system messages\n system = system ? `${system}\\n\\n${textContent}` : textContent;\n } else {\n anthropicMessages.push({\n role: message.role === 'assistant' ? 'assistant' : 'user',\n content: textContent,\n });\n }\n }\n\n return { system, anthropicMessages };\n }\n\n private mapToolChoice(\n toolChoice?:\n | 'auto'\n | 'none'\n | { type: 'function'; function: { name: string } },\n ): any {\n if (!toolChoice || toolChoice === 'auto') {\n return { type: 'auto' };\n }\n\n if (toolChoice === 'none') {\n return undefined; // Anthropic doesn't have explicit 'none', just omit tools\n }\n\n if (typeof toolChoice === 'object' && toolChoice.type === 'function') {\n return {\n type: 'tool',\n name: toolChoice.function.name,\n };\n }\n\n return { type: 'auto' };\n }\n\n private mapFinishReason(reason: string | null): AIResponse['finishReason'] {\n switch (reason) {\n case 'end_turn':\n return 'stop';\n case 'max_tokens':\n return 'length';\n case 'stop_sequence':\n return 'stop';\n case 'tool_use':\n return 'tool_calls';\n default:\n return 'stop';\n }\n }\n\n private mapError(error: unknown): AIError {\n if (error instanceof AIError) {\n return error;\n }\n\n // Map common HTTP status codes from Anthropic API\n if (typeof error === 'object' && error !== null && 'status' in error) {\n const apiError = error as { status: number; message?: string };\n switch (apiError.status) {\n case 401:\n return new AuthenticationError('anthropic');\n case 429:\n return new RateLimitError(\n 'anthropic',\n extractRetryAfterSeconds(error),\n );\n case 404:\n return new ModelNotFoundError(\n apiError.message || 'Model not found',\n 'anthropic',\n );\n case 413:\n return new ContextLengthError('anthropic');\n }\n }\n\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown Anthropic error occurred';\n return new AIError(errorMessage, 'UNKNOWN_ERROR', 'anthropic');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6DA,IAAa,oBAAb,MAAsD;CACpD;CACA;;;;;CAMA,YAAY,SAA2B;EACrC,KAAK,UAAU,uBAAuB;GACpC,cAAc;GACd,kBAAkB;GAClB,GAAG;EACL,CAAC;EAGD,KAAK,qBAAqB;CAC5B;CAEA,uBAA+B;EAC7B,IAAI;GAEF,OAAO,oBAAoB,CACxB,MAAM,EAAE,gBAAgB;IACvB,KAAK,SAAS,IAAI,UAAU;KAC1B,QAAQ,KAAK,QAAQ;KACrB,SAAS,KAAK,QAAQ;KACtB,SAAS,KAAK,QAAQ;KACtB,YAAY,KAAK,QAAQ;KACzB,gBAAgB;MACd,qBAAqB,KAAK,QAAQ;MAClC,GAAG,KAAK,QAAQ;KAClB;IACF,CAAC;GACH,CAAC,CAAC,CACD,YAAY,CAEb,CAAC;EACL,SAAS,QAAQ,CAEjB;CACF;;;;;;CAOA,MAAc,eAAe;EAC3B,IAAI,CAAC,KAAK,QACR,IAAI;GACF,MAAM,EAAE,cAAc,MAAM,OAAO;GACnC,KAAK,SAAS,IAAI,UAAU;IAC1B,QAAQ,KAAK,QAAQ;IACrB,SAAS,KAAK,QAAQ;IACtB,SAAS,KAAK,QAAQ;IACtB,YAAY,KAAK,QAAQ;IACzB,gBAAgB;KACd,qBAAqB,KAAK,QAAQ;KAClC,GAAG,KAAK,QAAQ;IAClB;GACF,CAAC;EACH,SAAS,QAAQ;GACf,MAAM,IAAI,QACR,oFACA,wBACA,WACF;EACF;CAEJ;;;;;;;;;;;;;;;;;;;CAoBA,MAAM,KACJ,UACA,UAAuB,CAAC,GACH;EACrB,MAAM,YAAY,KAAK,IAAI;EAC3B,IAAI;EACJ,IAAI;GACF,MAAM,KAAK,aAAa;GAExB,MAAM,EAAE,QAAQ,sBACd,KAAK,uBA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NotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./types-FHs-KbGL.js";
2
- import { a as normalizeBaseAIOptions, c as prepareRequestControls, o as normalizeChatOptions, s as normalizeImageGenerationOptions } from "./safety-CEnoJS6X.js";
1
+ import { a as ContextLengthError, c as extractTextContent, o as ModelNotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./types-CINwUPDo.js";
2
+ import { a as normalizeBaseAIOptions, c as prepareRequestControls, o as normalizeChatOptions, s as normalizeImageGenerationOptions } from "./safety-C415clBm.js";
3
3
  import { t as emitUsage } from "./usage-C1Y1Nlg4.js";
4
4
  //#region src/shared/providers/bedrock.ts
5
5
  /**
@@ -406,6 +406,7 @@ var BedrockProvider = class {
406
406
  fineTuning: true,
407
407
  imageEmbeddings: true,
408
408
  imageGeneration: true,
409
+ videoGeneration: false,
409
410
  tts: false,
410
411
  voiceCloning: false,
411
412
  voiceDesign: false,
@@ -422,6 +423,21 @@ var BedrockProvider = class {
422
423
  ]
423
424
  };
424
425
  }
426
+ async submitVideoGenerationJob(_options) {
427
+ throw new AIError("Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "bedrock");
428
+ }
429
+ async getVideoGenerationJob(_handle) {
430
+ throw new AIError("Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "bedrock");
431
+ }
432
+ async fetchVideoGenerationResult(_handle) {
433
+ throw new AIError("Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "bedrock");
434
+ }
435
+ async cancelVideoGenerationJob(_handle) {
436
+ throw new AIError("Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "bedrock");
437
+ }
438
+ async validateVideoGenerationAccess() {
439
+ throw new AIError("Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.", "NOT_IMPLEMENTED", "bedrock");
440
+ }
425
441
  async synthesizeSpeech(_text, _options) {
426
442
  throw new AIError("TTS is not supported by Bedrock provider. Use Qwen3-TTS provider.", "NOT_IMPLEMENTED", "bedrock");
427
443
  }
@@ -696,4 +712,4 @@ var BedrockProvider = class {
696
712
  //#endregion
697
713
  export { BedrockProvider };
698
714
 
699
- //# sourceMappingURL=bedrock-DDiYFUw0.js.map
715
+ //# sourceMappingURL=bedrock-ikQJAwWB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bedrock-ikQJAwWB.js","names":[],"sources":["../../src/shared/providers/bedrock.ts"],"sourcesContent":["/**\n * AWS Bedrock provider implementation\n */\n\nimport {\n normalizeBaseAIOptions,\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n type PreparedRequestControls,\n prepareRequestControls,\n} from '../safety';\nimport type {\n AICapabilities,\n AIInterface,\n AIMessage,\n AIModel,\n AIResponse,\n BedrockOptions,\n ChatOptions,\n CompletionOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n MessageOptions,\n TokenUsage,\n TTSOptions,\n TTSResponse,\n VideoGenerationJob,\n VideoGenerationOptions,\n VideoGenerationResult,\n VideoGenerationStatusResult,\n Voice,\n VoiceCloneOptions,\n VoiceDesignOptions,\n VoiceListOptions,\n} from '../types';\nimport {\n AIError,\n AuthenticationError,\n ContextLengthError,\n extractTextContent,\n ModelNotFoundError,\n RateLimitError,\n} from '../types';\nimport { emitUsage } from './usage';\n\nconst BEDROCK_DEFAULT_CHAT_MODEL = 'anthropic.claude-3-5-sonnet-20241022-v2:0';\nconst BEDROCK_TEXT_EMBEDDING_MODEL = 'amazon.titan-embed-text-v2:0';\nconst BEDROCK_IMAGE_EMBEDDING_MODEL = 'amazon.titan-embed-image-v1';\nconst BEDROCK_IMAGE_GENERATION_MODEL = 'amazon.titan-image-generator-v2:0';\n\nexport class BedrockProvider implements AIInterface {\n private options: BedrockOptions;\n private client: any; // Will be BedrockRuntimeClient instance from @aws-sdk/client-bedrock-runtime\n\n constructor(options: BedrockOptions) {\n this.options = normalizeBaseAIOptions({\n defaultModel: BEDROCK_DEFAULT_CHAT_MODEL,\n ...options,\n });\n\n // Initialize AWS Bedrock client\n this.initializeClientSync();\n }\n\n private initializeClientSync() {\n try {\n // Dynamic import in constructor - this will work if the package is installed\n import('@aws-sdk/client-bedrock-runtime')\n .then(({ BedrockRuntimeClient }) => {\n this.client = new BedrockRuntimeClient({\n region: this.options.region,\n credentials: this.options.credentials,\n endpoint: this.options.endpoint,\n maxAttempts: (this.options.maxRetries || 0) + 1,\n });\n })\n .catch(() => {\n // Client will be null and we'll handle it in methods\n });\n } catch (_error) {\n // Client will be null and we'll handle it in methods\n }\n }\n\n private async ensureClient() {\n if (!this.client) {\n try {\n const { BedrockRuntimeClient } = await import(\n '@aws-sdk/client-bedrock-runtime'\n );\n this.client = new BedrockRuntimeClient({\n region: this.options.region,\n credentials: this.options.credentials,\n endpoint: this.options.endpoint,\n maxAttempts: (this.options.maxRetries || 0) + 1,\n });\n } catch (_error) {\n throw new AIError(\n 'Failed to initialize Bedrock client. Make sure @aws-sdk/client-bedrock-runtime is installed.',\n 'INITIALIZATION_ERROR',\n 'bedrock',\n );\n }\n }\n }\n\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const modelId = options.model || this.options.defaultModel;\n options = normalizeChatOptions(this.options, options, 'bedrock', modelId);\n controls = prepareRequestControls(this.options, options);\n const response = this.mapConverseResponse(\n await this.client.converse(\n await this.buildConverseRequest(\n messages,\n options,\n modelId!,\n controls.signal,\n ),\n { abortSignal: controls.signal },\n ),\n modelId!,\n );\n\n emitUsage(\n this.options,\n 'bedrock',\n 'chat',\n response.model || modelId || 'unknown',\n response.usage,\n startTime,\n options.usageTags,\n );\n return response;\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'bedrock',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'bedrock',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n async complete(\n prompt: string,\n options: CompletionOptions = {},\n ): Promise<AIResponse> {\n return this.chat([{ role: 'user', content: prompt }], {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n n: options.n,\n stop: options.stop,\n stream: options.stream,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n });\n }\n\n /**\n * Simple message interface for single-turn interactions with optional history\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 async message(text: string, options: MessageOptions = {}): Promise<string> {\n // Build messages array from history + current message\n const messages: AIMessage[] = [\n ...(options.history || []),\n { role: options.role || 'user', content: text },\n ];\n\n const response = await this.chat(messages, {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n stop: options.stop,\n stream: options.stream,\n frequencyPenalty: options.frequencyPenalty,\n presencePenalty: options.presencePenalty,\n responseFormat: options.responseFormat,\n seed: options.seed,\n tools: options.tools,\n toolChoice: options.toolChoice,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n });\n\n return response.content;\n }\n\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n const startTime = Date.now();\n try {\n await this.ensureClient();\n\n const model = options.model || BEDROCK_TEXT_EMBEDDING_MODEL;\n const inputs = Array.isArray(text) ? text : [text];\n const embeddings: number[][] = [];\n let totalTokens = 0;\n\n for (const inputText of inputs) {\n const response = await this.client.invokeModel({\n modelId: model,\n contentType: 'application/json',\n accept: 'application/json',\n body: JSON.stringify({\n inputText,\n ...(options.dimensions && { dimensions: options.dimensions }),\n normalize: true,\n }),\n });\n\n const payload = await this.parseInvokeModelBody(response.body);\n const embedding = this.extractEmbeddingVector(payload);\n if (embedding) {\n embeddings.push(embedding);\n }\n\n totalTokens +=\n payload.inputTextTokenCount ||\n payload.inputTokenCount ||\n payload.tokenCount ||\n 0;\n }\n\n const usage: TokenUsage | undefined =\n totalTokens > 0\n ? {\n promptTokens: totalTokens,\n completionTokens: 0,\n totalTokens,\n }\n : undefined;\n\n emitUsage(\n this.options,\n 'bedrock',\n 'embed',\n model,\n usage,\n startTime,\n options.usageTags,\n );\n\n return {\n embeddings,\n model,\n usage,\n };\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n const startTime = Date.now();\n try {\n await this.ensureClient();\n\n const model = options.model || BEDROCK_IMAGE_EMBEDDING_MODEL;\n const response = await this.client.invokeModel({\n modelId: model,\n contentType: 'application/json',\n accept: 'application/json',\n body: JSON.stringify({\n inputImage: await this.imageToBase64(image),\n ...(options.dimensions && {\n embeddingConfig: {\n outputEmbeddingLength: options.dimensions,\n },\n }),\n }),\n });\n\n const payload = await this.parseInvokeModelBody(response.body);\n const embedding = this.extractEmbeddingVector(payload);\n\n emitUsage(\n this.options,\n 'bedrock',\n 'embedImage',\n model,\n undefined,\n startTime,\n );\n\n return {\n embeddings: embedding ? [embedding] : [],\n model,\n };\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n const imageUrl = await this.imageToDataUrl(image, options.signal);\n const response = await this.chat(\n [\n {\n role: 'user',\n content: [\n {\n type: 'text',\n text:\n prompt ||\n 'Describe this image for a search index. Include objects, mood, lighting, and any visible text.',\n },\n {\n type: 'image_url',\n image_url: { url: imageUrl },\n },\n ],\n },\n ],\n {\n model: options.model || this.options.defaultModel,\n maxTokens: options.maxTokens ?? 500,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n },\n );\n\n return response.content;\n }\n\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const model = options.model || BEDROCK_IMAGE_GENERATION_MODEL;\n options = normalizeImageGenerationOptions(\n this.options,\n options,\n 'bedrock',\n model,\n );\n controls = prepareRequestControls(this.options, options);\n const size = this.resolveImageSize(options);\n const response = await this.client.invokeModel(\n {\n modelId: model,\n contentType: 'application/json',\n accept: 'application/json',\n body: JSON.stringify({\n taskType: 'TEXT_IMAGE',\n textToImageParams: {\n text: prompt,\n ...(options.imageInput && {\n conditionImage: await this.imageToBase64(\n options.imageInput,\n controls.signal,\n ),\n }),\n },\n imageGenerationConfig: {\n numberOfImages: options.n,\n quality: this.mapImageQuality(options.quality),\n ...size,\n },\n }),\n },\n { abortSignal: controls.signal },\n );\n\n const payload = await this.parseInvokeModelBody(response.body);\n if (payload.error) {\n throw new AIError(payload.error, 'API_ERROR', 'bedrock');\n }\n\n const images = (payload.images || []).map((encoded: string) => {\n const mimeType = 'image/png';\n if (options.outputFormat === 'base64') {\n return { data: encoded, mimeType };\n }\n if (options.outputFormat === 'url') {\n return { data: `data:${mimeType};base64,${encoded}`, mimeType };\n }\n return {\n data: Buffer.from(encoded, 'base64'),\n mimeType,\n };\n });\n\n return {\n images,\n model,\n };\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'bedrock',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'bedrock',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const modelId = options.model || this.options.defaultModel;\n options = normalizeChatOptions(this.options, options, 'bedrock', modelId);\n controls = prepareRequestControls(this.options, options);\n const response = await this.client.converseStream(\n await this.buildConverseRequest(\n messages,\n options,\n modelId!,\n controls.signal,\n ),\n { abortSignal: controls.signal },\n );\n\n let usage: TokenUsage | undefined;\n\n for await (const event of response.stream || []) {\n const text = event.contentBlockDelta?.delta?.text;\n if (text) {\n if (options.onProgress) {\n options.onProgress(text);\n }\n yield text;\n }\n\n if (event.metadata?.usage) {\n usage = {\n promptTokens: event.metadata.usage.inputTokens || 0,\n completionTokens: event.metadata.usage.outputTokens || 0,\n totalTokens: event.metadata.usage.totalTokens || 0,\n };\n }\n }\n\n emitUsage(\n this.options,\n 'bedrock',\n 'stream',\n modelId || 'unknown',\n usage,\n startTime,\n options.usageTags,\n );\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'bedrock',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'bedrock',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n async countTokens(text: string): Promise<number> {\n try {\n await this.ensureClient();\n\n const modelId = this.options.defaultModel || BEDROCK_DEFAULT_CHAT_MODEL;\n const response = await this.client.countTokens({\n modelId,\n input: {\n converse: {\n messages: [\n {\n role: 'user',\n content: [{ text }],\n },\n ],\n },\n },\n });\n\n return response.inputTokens || Math.ceil(text.length / 4);\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n async getModels(): Promise<AIModel[]> {\n // Return static list of popular Bedrock models\n return [\n // Anthropic Claude models\n {\n id: 'anthropic.claude-3-5-sonnet-20241022-v2:0',\n name: 'Claude 3.5 Sonnet v2',\n description: 'Latest Claude 3.5 Sonnet model on Bedrock',\n contextLength: 200000,\n capabilities: ['text', 'chat', 'vision', 'functions'],\n supportsFunctions: true,\n supportsVision: true,\n },\n {\n id: 'anthropic.claude-3-opus-20240229-v1:0',\n name: 'Claude 3 Opus',\n description: 'Most powerful Claude model on Bedrock',\n contextLength: 200000,\n capabilities: ['text', 'chat', 'vision'],\n supportsFunctions: false,\n supportsVision: true,\n },\n // Amazon Titan models\n {\n id: 'amazon.titan-text-premier-v1:0',\n name: 'Titan Text Premier',\n description: 'Premier Amazon Titan text model',\n contextLength: 32000,\n capabilities: ['text', 'chat'],\n supportsFunctions: false,\n supportsVision: false,\n },\n {\n id: 'amazon.titan-embed-text-v1',\n name: 'Titan Embeddings Text',\n description: 'Amazon Titan text embeddings model',\n contextLength: 8192,\n capabilities: ['embeddings'],\n supportsFunctions: false,\n supportsVision: false,\n },\n {\n id: BEDROCK_TEXT_EMBEDDING_MODEL,\n name: 'Titan Embeddings Text V2',\n description: 'Amazon Titan text embeddings v2 model',\n contextLength: 8192,\n capabilities: ['embeddings'],\n supportsFunctions: false,\n supportsVision: false,\n },\n {\n id: BEDROCK_IMAGE_EMBEDDING_MODEL,\n name: 'Titan Multimodal Embeddings G1',\n description:\n 'Amazon Titan multimodal embeddings model for image similarity',\n contextLength: 256,\n capabilities: ['embeddings', 'image_embedding'],\n supportsFunctions: false,\n supportsVision: false,\n },\n {\n id: BEDROCK_IMAGE_GENERATION_MODEL,\n name: 'Titan Image Generator V2',\n description: 'Amazon Titan image generation model',\n contextLength: 0,\n capabilities: ['image_generation'],\n supportsFunctions: false,\n supportsVision: false,\n },\n // Cohere models\n {\n id: 'cohere.command-r-plus-v1:0',\n name: 'Command R+',\n description: 'Cohere Command R+ model with advanced capabilities',\n contextLength: 128000,\n capabilities: ['text', 'chat', 'functions'],\n supportsFunctions: true,\n supportsVision: false,\n },\n // Meta Llama models\n {\n id: 'meta.llama3-1-405b-instruct-v1:0',\n name: 'Llama 3.1 405B Instruct',\n description: 'Meta Llama 3.1 405B instruction-tuned model',\n contextLength: 128000,\n capabilities: ['text', 'chat'],\n supportsFunctions: false,\n supportsVision: false,\n },\n ];\n }\n\n async getCapabilities(): Promise<AICapabilities> {\n return {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true, // Some models support function calling\n vision: true, // Some models support vision\n fineTuning: true, // Via Bedrock fine-tuning\n imageEmbeddings: true,\n imageGeneration: true,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 200000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n };\n }\n\n // ============================================================================\n // Video Generation Methods (Not supported - use gemini, byteplus-modelark,\n // or openai-compat-video provider)\n // ============================================================================\n\n async submitVideoGenerationJob(\n _options: VideoGenerationOptions,\n ): Promise<VideoGenerationJob> {\n throw new AIError(\n 'Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n async getVideoGenerationJob(\n _handle: VideoGenerationJob,\n ): Promise<VideoGenerationStatusResult> {\n throw new AIError(\n 'Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n async fetchVideoGenerationResult(\n _handle: VideoGenerationJob,\n ): Promise<VideoGenerationResult> {\n throw new AIError(\n 'Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n async cancelVideoGenerationJob(_handle: VideoGenerationJob): Promise<void> {\n throw new AIError(\n 'Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n async validateVideoGenerationAccess(): Promise<boolean> {\n throw new AIError(\n 'Video generation is not supported by Bedrock provider. Use gemini, byteplus-modelark, or openai-compat-video provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n // ============================================================================\n // TTS Methods (Not supported - use Qwen3-TTS provider)\n // ============================================================================\n\n async synthesizeSpeech(\n _text: string,\n _options?: TTSOptions,\n ): Promise<TTSResponse> {\n throw new AIError(\n 'TTS is not supported by Bedrock provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n streamSpeech(_text: string, _options?: TTSOptions): AsyncIterable<Buffer> {\n const error = new AIError(\n 'TTS streaming is not supported by Bedrock provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n return {\n [Symbol.asyncIterator]: () => ({\n next: () => Promise.reject(error),\n }),\n };\n }\n\n async cloneVoice(_options: VoiceCloneOptions): Promise<Voice> {\n throw new AIError(\n 'Voice cloning is not supported by Bedrock provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n async designVoice(_options: VoiceDesignOptions): Promise<Voice> {\n throw new AIError(\n 'Voice design is not supported by Bedrock provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n async getVoices(_options?: VoiceListOptions): Promise<Voice[]> {\n throw new AIError(\n 'Voice listing is not supported by Bedrock provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'bedrock',\n );\n }\n\n private async buildConverseRequest(\n messages: AIMessage[],\n options: ChatOptions,\n modelId: string,\n signal?: AbortSignal,\n ): Promise<Record<string, any>> {\n const { system, bedrockMessages } = await this.mapMessagesToBedrock(\n messages,\n signal,\n );\n const systemPrompt =\n options.responseFormat?.type === 'json_object'\n ? [\n system,\n 'Respond with valid JSON only. Do not include explanatory text outside the JSON object.',\n ]\n .filter(Boolean)\n .join('\\n\\n')\n : system;\n\n const inferenceConfig = Object.fromEntries(\n Object.entries({\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n stopSequences: Array.isArray(options.stop)\n ? options.stop\n : options.stop\n ? [options.stop]\n : undefined,\n }).filter(([, value]) => value !== undefined),\n );\n\n const request: Record<string, any> = {\n modelId,\n messages: bedrockMessages,\n ...(Object.keys(inferenceConfig).length > 0 && { inferenceConfig }),\n ...(systemPrompt && { system: [{ text: systemPrompt }] }),\n };\n if ((options.reasoning?.maxTokens || 0) > 0) {\n request.additionalModelRequestFields = {\n thinking: {\n type: 'enabled',\n budget_tokens: options.reasoning?.maxTokens,\n },\n };\n }\n\n const toolConfig = this.mapToolConfig(options);\n if (toolConfig) {\n request.toolConfig = toolConfig;\n }\n\n return request;\n }\n\n private async mapMessagesToBedrock(\n messages: AIMessage[],\n signal?: AbortSignal,\n ): Promise<{\n system?: string;\n bedrockMessages: Array<{ role: 'user' | 'assistant'; content: any[] }>;\n }> {\n let system: string | undefined;\n const bedrockMessages: Array<{\n role: 'user' | 'assistant';\n content: any[];\n }> = [];\n\n for (const message of messages) {\n const textContent = extractTextContent(message.content);\n if (message.role === 'system') {\n system = system ? `${system}\\n\\n${textContent}` : textContent;\n continue;\n }\n\n const content: any[] = [];\n if (typeof message.content === 'string') {\n content.push({ text: message.content });\n } else {\n for (const part of message.content) {\n if (part.type === 'text') {\n content.push({ text: part.text });\n continue;\n }\n\n const image = await this.imageUrlToBedrockImage(\n part.image_url.url,\n signal,\n );\n content.push({ image });\n }\n }\n\n if (message.role === 'assistant' && message.tool_calls) {\n for (const toolCall of message.tool_calls) {\n content.push({\n toolUse: {\n toolUseId: toolCall.id,\n name: toolCall.function.name,\n input: this.safeJsonParse(toolCall.function.arguments),\n },\n });\n }\n }\n\n if (content.length === 0 && textContent) {\n content.push({ text: textContent });\n }\n\n bedrockMessages.push({\n role: message.role === 'assistant' ? 'assistant' : 'user',\n content,\n });\n }\n\n return { system, bedrockMessages };\n }\n\n private mapConverseResponse(response: any, modelId: string): AIResponse {\n const contentBlocks = response.output?.message?.content || [];\n const textContent = contentBlocks\n .filter((block: any) => typeof block.text === 'string')\n .map((block: any) => block.text)\n .join('');\n\n const toolCalls = contentBlocks\n .filter((block: any) => block.toolUse)\n .map((block: any) => ({\n id: block.toolUse.toolUseId,\n type: 'function' as const,\n function: {\n name: block.toolUse.name,\n arguments: JSON.stringify(block.toolUse.input || {}),\n },\n }));\n\n const usage =\n response.usage &&\n ({\n promptTokens: response.usage.inputTokens || 0,\n completionTokens: response.usage.outputTokens || 0,\n totalTokens: response.usage.totalTokens || 0,\n } satisfies TokenUsage);\n\n return {\n content: textContent,\n model: modelId,\n finishReason: this.mapBedrockFinishReason(response.stopReason),\n usage,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n };\n }\n\n private mapBedrockFinishReason(\n reason: string | null | undefined,\n ): AIResponse['finishReason'] {\n switch (reason) {\n case 'end_turn':\n return 'stop';\n case 'max_tokens':\n return 'length';\n case 'stop_sequence':\n return 'stop';\n case 'tool_use':\n return 'tool_calls';\n default:\n return 'stop';\n }\n }\n\n private mapToolConfig(options: ChatOptions): Record<string, any> | undefined {\n if (!options.tools || options.tools.length === 0) {\n return undefined;\n }\n\n if (options.toolChoice === 'none') {\n return undefined;\n }\n\n return {\n tools: options.tools.map((tool) => ({\n toolSpec: {\n name: tool.function.name,\n description: tool.function.description || '',\n inputSchema: {\n json: tool.function.parameters || { type: 'object' },\n },\n },\n })),\n ...(options.toolChoice && {\n toolChoice: this.mapToolChoice(options.toolChoice),\n }),\n };\n }\n\n private mapToolChoice(\n toolChoice?:\n | 'auto'\n | 'none'\n | { type: 'function'; function: { name: string } },\n ): Record<string, any> | undefined {\n if (!toolChoice || toolChoice === 'auto') {\n return { auto: {} };\n }\n\n if (toolChoice === 'none') {\n return undefined;\n }\n\n return {\n tool: {\n name: toolChoice.function.name,\n },\n };\n }\n\n private async parseInvokeModelBody(body: unknown): Promise<any> {\n const bytes =\n typeof (body as any)?.transformToByteArray === 'function'\n ? await (body as any).transformToByteArray()\n : body instanceof Uint8Array\n ? body\n : Buffer.isBuffer(body)\n ? body\n : new Uint8Array(body as ArrayBuffer);\n return JSON.parse(new TextDecoder().decode(bytes));\n }\n\n private extractEmbeddingVector(payload: any): number[] | undefined {\n if (Array.isArray(payload.embedding)) {\n return payload.embedding;\n }\n\n if (Array.isArray(payload.embeddings?.[0])) {\n return payload.embeddings[0];\n }\n\n if (Array.isArray(payload.embeddingsByType?.float)) {\n return payload.embeddingsByType.float;\n }\n\n if (Array.isArray(payload.vector)) {\n return payload.vector;\n }\n\n return undefined;\n }\n\n private async imageUrlToBedrockImage(\n imageUrl: string,\n signal?: AbortSignal,\n ): Promise<any> {\n const { bytes, mimeType } = await this.imageToBytes(imageUrl, signal);\n return {\n format: this.mimeTypeToBedrockImageFormat(mimeType),\n source: { bytes },\n };\n }\n\n private async imageToDataUrl(\n image: string | Buffer,\n signal?: AbortSignal,\n ): Promise<string> {\n if (Buffer.isBuffer(image)) {\n return `data:image/png;base64,${image.toString('base64')}`;\n }\n if (image.startsWith('data:')) {\n return image;\n }\n\n const { bytes, mimeType } = await this.imageToBytes(image, signal);\n return `data:${mimeType};base64,${Buffer.from(bytes).toString('base64')}`;\n }\n\n private async imageToBase64(\n image: string | Buffer,\n signal?: AbortSignal,\n ): Promise<string> {\n if (Buffer.isBuffer(image)) {\n return image.toString('base64');\n }\n if (image.startsWith('data:')) {\n const match = image.match(/^data:([^;]+);base64,(.+)$/);\n if (!match) {\n throw new AIError(\n 'Invalid base64 data URL format',\n 'INVALID_INPUT',\n 'bedrock',\n );\n }\n return match[2];\n }\n\n const { bytes } = await this.imageToBytes(image, signal);\n return Buffer.from(bytes).toString('base64');\n }\n\n private async imageToBytes(\n image: string,\n signal?: AbortSignal,\n ): Promise<{ bytes: Uint8Array; mimeType: string }> {\n if (image.startsWith('data:')) {\n const match = image.match(/^data:([^;]+);base64,(.+)$/);\n if (!match) {\n throw new AIError(\n 'Invalid base64 data URL format',\n 'INVALID_INPUT',\n 'bedrock',\n );\n }\n\n return {\n bytes: Uint8Array.from(Buffer.from(match[2], 'base64')),\n mimeType: match[1],\n };\n }\n\n const response = await fetch(image, { signal });\n if (!response.ok) {\n throw new AIError(\n `Failed to fetch image: ${response.status} ${response.statusText}`,\n 'IMAGE_FETCH_ERROR',\n 'bedrock',\n );\n }\n\n const arrayBuffer = await response.arrayBuffer();\n return {\n bytes: new Uint8Array(arrayBuffer),\n mimeType: response.headers.get('content-type') || 'image/png',\n };\n }\n\n private mimeTypeToBedrockImageFormat(mimeType: string): string {\n if (mimeType.includes('png')) return 'png';\n if (mimeType.includes('jpeg') || mimeType.includes('jpg')) return 'jpeg';\n if (mimeType.includes('gif')) return 'gif';\n if (mimeType.includes('webp')) return 'webp';\n\n throw new AIError(\n `Unsupported image format for Bedrock: ${mimeType}`,\n 'INVALID_INPUT',\n 'bedrock',\n );\n }\n\n private resolveImageSize(options: ImageGenerationOptions): {\n width: number;\n height: number;\n } {\n if (options.size) {\n const [width, height] = options.size.split('x').map(Number);\n if (Number.isFinite(width) && Number.isFinite(height)) {\n return { width, height };\n }\n }\n\n const aspectRatioSizes: Record<string, { width: number; height: number }> =\n {\n '1:1': { width: 1024, height: 1024 },\n '2:3': { width: 768, height: 1152 },\n '3:2': { width: 1152, height: 768 },\n '3:5': { width: 768, height: 1280 },\n '5:3': { width: 1280, height: 768 },\n '7:9': { width: 896, height: 1152 },\n '9:7': { width: 1152, height: 896 },\n '6:11': { width: 768, height: 1408 },\n '11:6': { width: 1408, height: 768 },\n '5:11': { width: 640, height: 1408 },\n '11:5': { width: 1408, height: 640 },\n '9:5': { width: 1152, height: 640 },\n '16:9': { width: 1173, height: 640 },\n };\n\n return (\n aspectRatioSizes[options.aspectRatio || ''] || {\n width: 1024,\n height: 1024,\n }\n );\n }\n\n private mapImageQuality(quality?: string): string {\n if (!quality || quality === 'standard') {\n return 'standard';\n }\n\n if (quality === 'hd') {\n return 'premium';\n }\n\n return quality;\n }\n\n private safeJsonParse(input: string): any {\n try {\n return JSON.parse(input);\n } catch {\n return { rawArguments: input };\n }\n }\n\n private mapError(error: unknown): AIError {\n if (error instanceof AIError) {\n return error;\n }\n\n // Map common AWS error codes\n if (typeof error === 'object' && error !== null) {\n const awsError = error as { name?: string; message?: string };\n\n if (awsError.name === 'AccessDeniedException') {\n return new AuthenticationError('bedrock');\n }\n\n if (awsError.name === 'ThrottlingException') {\n return new RateLimitError('bedrock');\n }\n\n if (awsError.name === 'ResourceNotFoundException') {\n return new ModelNotFoundError(\n awsError.message || 'Model not found',\n 'bedrock',\n );\n }\n\n if (\n awsError.name === 'ValidationException' &&\n awsError.message?.includes('input is too long')\n ) {\n return new ContextLengthError('bedrock');\n }\n }\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown Bedrock error occurred';\n return new AIError(errorMessage, 'UNKNOWN_ERROR', 'bedrock');\n }\n}\n"],"mappings":";;;;;;;AAiDA,IAAM,6BAA6B;AACnC,IAAM,+BAA+B;AACrC,IAAM,gCAAgC;AACtC,IAAM,iCAAiC;AAEvC,IAAa,kBAAb,MAAoD;CAClD;CACA;CAEA,YAAY,SAAyB;EACnC,KAAK,UAAU,uBAAuB;GACpC,cAAc;GACd,GAAG;EACL,CAAC;EAGD,KAAK,qBAAqB;CAC5B;CAEA,uBAA+B;EAC7B,IAAI;GAEF,OAAO,kCAAkC,CACtC,MAAM,EAAE,2BAA2B;IAClC,KAAK,SAAS,IAAI,qBAAqB;KACrC,QAAQ,KAAK,QAAQ;KACrB,aAAa,KAAK,QAAQ;KAC1B,UAAU,KAAK,QAAQ;KACvB,cAAc,KAAK,QAAQ,cAAc,KAAK;IAChD,CAAC;GACH,CAAC,CAAC,CACD,YAAY,CAEb,CAAC;EACL,SAAS,QAAQ,CAEjB;CACF;CAEA,MAAc,eAAe;EAC3B,IAAI,CAAC,KAAK,QACR,IAAI;GACF,MAAM,EAAE,yBAAyB,MAAM,OACrC;GAEF,KAAK,SAAS,IA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QAAQ;IAAE,OAAO;IAAM,QAAQ;GAAI;GACnC,OAAO;IAAE,OAAO;IAAM,QAAQ;GAAI;GAClC,QAAQ;IAAE,OAAO;IAAM,QAAQ;GAAI;EAIrC,EAAiB,QAAQ,eAAe,OAAO;GAC7C,OAAO;GACP,QAAQ;EACV;CAEJ;CAEA,gBAAwB,SAA0B;EAChD,IAAI,CAAC,WAAW,YAAY,YAC1B,OAAO;EAGT,IAAI,YAAY,MACd,OAAO;EAGT,OAAO;CACT;CAEA,cAAsB,OAAoB;EACxC,IAAI;GACF,OAAO,KAAK,MAAM,KAAK;EACzB,QAAQ;GACN,OAAO,EAAE,cAAc,MAAM;EAC/B;CACF;CAEA,SAAiB,OAAyB;EACxC,IAAI,iBAAiB,SACnB,OAAO;EAIT,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;GAC/C,MAAM,WAAW;GAEjB,IAAI,SAAS,SAAS,yBACpB,OAAO,IAAI,oBAAoB,SAAS;GAG1C,IAAI,SAAS,SAAS,uBACpB,OAAO,IAAI,eAAe,SAAS;GAGrC,IAAI,SAAS,SAAS,6BACpB,OAAO,IAAI,mBACT,SAAS,WAAW,mBACpB,SACF;GAGF,IACE,SAAS,SAAS,yBAClB,SAAS,SAAS,SAAS,mBAAmB,GAE9C,OAAO,IAAI,mBAAmB,SAAS;EAE3C;EAIA,OAAO,IAAI,QADT,iBAAiB,QAAQ,MAAM,UAAU,kCACV,iBAAiB,SAAS;CAC7D;AACF"}
@@ -1,6 +1,6 @@
1
- import { o as normalizeChatOptions, s as normalizeImageGenerationOptions } from "./safety-CEnoJS6X.js";
2
- import { i as resolveGatewayAdminBaseUrl, r as normalizeGatewayBaseUrl, t as BifrostAdmin } from "./gateway-admin-CiKvHst7.js";
3
- import { OpenAIProvider } from "./openai--F38QHiJ.js";
1
+ import { o as normalizeChatOptions, s as normalizeImageGenerationOptions } from "./safety-C415clBm.js";
2
+ import { i as resolveGatewayAdminBaseUrl, r as normalizeGatewayBaseUrl, t as BifrostAdmin } from "./gateway-admin-DJXEDpUP.js";
3
+ import { OpenAIProvider } from "./openai-BgrK3OfW.js";
4
4
  import { ValidationError } from "@happyvertical/utils";
5
5
  //#region src/shared/providers/bifrost.ts
6
6
  var BIFROST_CAPABILITIES = {
@@ -13,6 +13,7 @@ var BIFROST_CAPABILITIES = {
13
13
  fineTuning: false,
14
14
  imageEmbeddings: true,
15
15
  imageGeneration: true,
16
+ videoGeneration: false,
16
17
  tts: false,
17
18
  voiceCloning: false,
18
19
  voiceDesign: false,
@@ -195,4 +196,4 @@ var BifrostProvider = class extends OpenAIProvider {
195
196
  //#endregion
196
197
  export { BifrostProvider };
197
198
 
198
- //# sourceMappingURL=bifrost-fM9FpW_w.js.map
199
+ //# sourceMappingURL=bifrost-CaYhelVL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bifrost-CaYhelVL.js","names":[],"sources":["../../src/shared/providers/bifrost.ts"],"sourcesContent":["import { ValidationError } from '@happyvertical/utils';\n\nimport {\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n} from '../safety';\nimport type {\n AICapabilities,\n AIMessage,\n AIModel,\n AIResponse,\n BifrostOptions,\n ChatOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n} from '../types';\nimport {\n BifrostAdmin,\n normalizeGatewayBaseUrl,\n resolveGatewayAdminBaseUrl,\n} from './gateway-admin';\nimport { type OpenAICompatibleProfile, OpenAIProvider } from './openai';\n\nconst BIFROST_CAPABILITIES: AICapabilities = {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: false,\n imageEmbeddings: true,\n imageGeneration: true,\n videoGeneration: false,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 128000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n};\n\nfunction isEmbeddingModel(modelId: string): boolean {\n return /embed/i.test(modelId);\n}\n\nfunction isImageEmbeddingModel(modelId: string): boolean {\n return /titan-embed-image|multimodalembedding|image[-_]?embed|clip/i.test(\n modelId,\n );\n}\n\nfunction isImageGenerationModel(modelId: string): boolean {\n return /gpt-image|dall-e|imagen|stable[-_ ]diffusion|sdxl|flux|titan-image|image-generator/i.test(\n modelId,\n );\n}\n\nfunction isFilteredBifrostModel(modelId: string): boolean {\n return /moderation|transcrib|whisper|speech|tts|rerank/i.test(modelId);\n}\n\nfunction inferBifrostContextLength(modelId: string): number {\n if (isEmbeddingModel(modelId)) return 8192;\n if (/gemini-1\\.5|gemini-2\\.0|gemini-2\\.5|gemini-3/i.test(modelId)) {\n return 1000000;\n }\n if (/claude/i.test(modelId)) return 200000;\n if (/gpt-4o|gpt-4\\.1|o1|o3|o4|llama|mistral|qwen|deepseek/i.test(modelId)) {\n return 128000;\n }\n return 32768;\n}\n\nfunction inferBifrostFunctions(modelId: string): boolean {\n if (isEmbeddingModel(modelId)) return false;\n return /gpt|claude|gemini|command|llama|mistral|qwen|deepseek|o1|o3|o4/i.test(\n modelId,\n );\n}\n\nfunction inferBifrostVision(modelId: string): boolean {\n return /gpt-4o|gpt-4\\.1|vision|claude-3|gemini|pixtral|llava|qwen.*vl|vl-/i.test(\n modelId,\n );\n}\n\nfunction inferBifrostCapabilities(modelId: string): string[] {\n if (isImageGenerationModel(modelId)) {\n return ['image_generation'];\n }\n\n if (isImageEmbeddingModel(modelId)) {\n return ['embeddings', 'image_embedding'];\n }\n\n if (isEmbeddingModel(modelId)) {\n return ['embeddings'];\n }\n\n const capabilities = ['text', 'chat'];\n\n if (inferBifrostFunctions(modelId)) {\n capabilities.push('functions');\n }\n\n if (inferBifrostVision(modelId)) {\n capabilities.push('vision');\n }\n\n return capabilities;\n}\n\nfunction ensureBifrostOptions(options: BifrostOptions): BifrostOptions {\n if (!options.baseUrl?.trim()) {\n throw new ValidationError('Bifrost baseUrl is required', {\n provider: 'bifrost',\n hint: 'Pass baseUrl like http://localhost:8080, http://localhost:8080/openai, or http://localhost:8080/v1 and optionally adminBaseUrl for governance endpoints',\n });\n }\n\n const baseUrl = normalizeGatewayBaseUrl(options.baseUrl);\n const inferenceBaseUrl = /\\/(?:openai|v1|pydanticai\\/v1)$/.test(baseUrl)\n ? baseUrl\n : `${baseUrl}/openai`;\n const headers = options.apiKey\n ? {\n ...options.headers,\n 'x-bf-vk': options.apiKey,\n 'x-api-key': options.apiKey,\n }\n : options.headers;\n\n return {\n ...options,\n baseUrl: inferenceBaseUrl,\n headers,\n };\n}\n\nconst BIFROST_PROFILE: OpenAICompatibleProfile = {\n providerLabel: 'Bifrost',\n providerName: 'bifrost',\n defaultModel: 'openai/gpt-4o-mini',\n capabilities: BIFROST_CAPABILITIES,\n describeModel: (modelId) => `Bifrost model: ${modelId}`,\n getContextLength: inferBifrostContextLength,\n getModelCapabilities: inferBifrostCapabilities,\n shouldIncludeModel: (modelId) => !isFilteredBifrostModel(modelId),\n supportsFunctions: inferBifrostFunctions,\n supportsVision: inferBifrostVision,\n};\n\ntype BifrostResolvedCapability =\n | 'chat'\n | 'vision'\n | 'embeddings'\n | 'image_generation';\n\nfunction supportsCapability(\n model: AIModel,\n capability: BifrostResolvedCapability,\n): boolean {\n if (capability === 'vision') {\n return (\n model.capabilities.includes('vision') || model.supportsVision === true\n );\n }\n\n if (capability === 'embeddings') {\n return model.capabilities.includes('embeddings');\n }\n\n if (capability === 'image_generation') {\n return model.capabilities.includes('image_generation');\n }\n\n return model.capabilities.includes('chat');\n}\n\n/**\n * Bifrost provider implementation.\n *\n * Bifrost exposes OpenAI-compatible inference and governance admin APIs. This\n * provider reuses the OpenAI-compatible transport for inference and exposes\n * `admin` for tenant project and virtual-key provisioning.\n */\nexport class BifrostProvider extends OpenAIProvider {\n readonly admin: BifrostAdmin;\n private readonly configuredDefaultModel?: string;\n private readonly resolvedModelCache = new Map<\n BifrostResolvedCapability,\n Promise<string>\n >();\n\n constructor(options: BifrostOptions) {\n const normalized = ensureBifrostOptions(options);\n super(normalized, BIFROST_PROFILE);\n const adminKey = normalized.adminApiKey || normalized.apiKey;\n const adminUsername = normalized.adminUser || normalized.adminUsername;\n this.admin = new BifrostAdmin({\n provider: 'bifrost',\n baseUrl: resolveGatewayAdminBaseUrl(\n normalized.baseUrl,\n normalized.adminUrl || normalized.adminBaseUrl,\n 'bifrost',\n ),\n apiKey: adminKey,\n username: adminUsername,\n password: normalized.adminPassword,\n headers:\n adminKey && !(adminUsername && normalized.adminPassword)\n ? {\n ...normalized.adminHeaders,\n 'x-bf-vk': adminKey,\n 'x-api-key': adminKey,\n }\n : normalized.adminHeaders,\n timeout: normalized.timeout,\n });\n this.configuredDefaultModel = normalized.defaultModel;\n }\n\n private async resolveModel(\n capability: BifrostResolvedCapability,\n explicitModel?: string,\n ): Promise<string> {\n if (explicitModel) {\n return explicitModel;\n }\n\n if (\n this.configuredDefaultModel &&\n (capability === 'chat' || capability === 'vision')\n ) {\n return this.configuredDefaultModel;\n }\n\n const cached = this.resolvedModelCache.get(capability);\n if (cached) {\n return cached;\n }\n\n const pending = this.selectModel(capability).catch((error) => {\n this.resolvedModelCache.delete(capability);\n throw error;\n });\n this.resolvedModelCache.set(capability, pending);\n return pending;\n }\n\n private async selectModel(\n capability: BifrostResolvedCapability,\n ): Promise<string> {\n const models = await super.getModels();\n const model = models.find((candidate) =>\n supportsCapability(candidate, capability),\n );\n\n if (!model) {\n throw new ValidationError(\n `No ${capability} model is available from the Bifrost gateway`,\n {\n provider: 'bifrost',\n capability,\n hint: 'Pass defaultModel explicitly or ensure the gateway returns a compatible model for this key',\n },\n );\n }\n\n return model.id;\n }\n\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n return super.chat(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n yield* super.stream(messages, {\n ...safe,\n model: await this.resolveModel('chat', safe.model),\n });\n }\n\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n const safe = normalizeChatOptions(\n this.options,\n options,\n 'bifrost',\n options.model || this.options.defaultModel,\n );\n return super.describeImage(image, prompt, {\n ...safe,\n model: await this.resolveModel('vision', safe.model),\n });\n }\n\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embed(text, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n return super.embedImage(image, {\n ...options,\n model: await this.resolveModel('embeddings', options.model),\n });\n }\n\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n const safe = normalizeImageGenerationOptions(\n this.options,\n options,\n 'bifrost',\n options.model,\n );\n return super.generateImage(prompt, {\n ...safe,\n model: await this.resolveModel('image_generation', safe.model),\n });\n }\n}\n"],"mappings":";;;;;AA2BA,IAAM,uBAAuC;CAC3C,MAAM;CACN,YAAY;CACZ,YAAY;CACZ,WAAW;CACX,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,KAAK;CACL,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,qBAAqB;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;AAEA,SAAS,iBAAiB,SAA0B;CAClD,OAAO,SAAS,KAAK,OAAO;AAC9B;AAEA,SAAS,sBAAsB,SAA0B;CACvD,OAAO,8DAA8D,KACnE,OACF;AACF;AAEA,SAAS,uBA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