@umituz/web-ai 0.0.0-stage → 1.0.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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -2
  3. package/dist/AIErrors-B2ogd1PB.d.ts +197 -0
  4. package/dist/AIErrors-C5EasV_c.d.cts +197 -0
  5. package/dist/ContentGeneration-B6iK2B33.d.cts +93 -0
  6. package/dist/ContentGeneration-B6iK2B33.d.ts +93 -0
  7. package/dist/ProviderConfig-DIFa9nmG.d.cts +108 -0
  8. package/dist/ProviderConfig-DIFa9nmG.d.ts +108 -0
  9. package/dist/cache-manager-Df9LLYGA.d.cts +31 -0
  10. package/dist/cache-manager-Df9LLYGA.d.ts +31 -0
  11. package/dist/chat/index.cjs +625 -0
  12. package/dist/chat/index.cjs.map +1 -0
  13. package/dist/chat/index.d.cts +25 -0
  14. package/dist/chat/index.d.ts +25 -0
  15. package/dist/chat/index.js +618 -0
  16. package/dist/chat/index.js.map +1 -0
  17. package/dist/chat.service-CL1qtYxe.d.cts +124 -0
  18. package/dist/chat.service-q05GnhEm.d.ts +124 -0
  19. package/dist/content/index.cjs +3976 -0
  20. package/dist/content/index.cjs.map +1 -0
  21. package/dist/content/index.d.cts +224 -0
  22. package/dist/content/index.d.ts +224 -0
  23. package/dist/content/index.js +3945 -0
  24. package/dist/content/index.js.map +1 -0
  25. package/dist/core/index.cjs +1137 -0
  26. package/dist/core/index.cjs.map +1 -0
  27. package/dist/core/index.d.cts +204 -0
  28. package/dist/core/index.d.ts +204 -0
  29. package/dist/core/index.js +1064 -0
  30. package/dist/core/index.js.map +1 -0
  31. package/dist/create-ai-DOI9jD3v.d.cts +251 -0
  32. package/dist/create-ai-DXEoke8-.d.ts +251 -0
  33. package/dist/hooks/index.cjs +5246 -0
  34. package/dist/hooks/index.cjs.map +1 -0
  35. package/dist/hooks/index.d.cts +210 -0
  36. package/dist/hooks/index.d.ts +210 -0
  37. package/dist/hooks/index.js +5235 -0
  38. package/dist/hooks/index.js.map +1 -0
  39. package/dist/index-DIHz8_OJ.d.ts +48 -0
  40. package/dist/index-DKHNcMbl.d.cts +48 -0
  41. package/dist/index-fXjxTR5W.d.cts +66 -0
  42. package/dist/index-fXjxTR5W.d.ts +66 -0
  43. package/dist/index.cjs +3309 -0
  44. package/dist/index.cjs.map +1 -0
  45. package/dist/index.d.cts +11 -0
  46. package/dist/index.d.ts +11 -0
  47. package/dist/index.js +3197 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/provider.factory-BxsfK4WW.d.cts +110 -0
  50. package/dist/provider.factory-DfDfk0dK.d.ts +110 -0
  51. package/dist/providers/index.cjs +2567 -0
  52. package/dist/providers/index.cjs.map +1 -0
  53. package/dist/providers/index.d.cts +332 -0
  54. package/dist/providers/index.d.ts +332 -0
  55. package/dist/providers/index.js +2533 -0
  56. package/dist/providers/index.js.map +1 -0
  57. package/dist/request-deduplicator.util-NDo0_n1y.d.cts +50 -0
  58. package/dist/request-deduplicator.util-NDo0_n1y.d.ts +50 -0
  59. package/dist/wizard/index.cjs +230 -0
  60. package/dist/wizard/index.cjs.map +1 -0
  61. package/dist/wizard/index.d.cts +86 -0
  62. package/dist/wizard/index.d.ts +86 -0
  63. package/dist/wizard/index.js +223 -0
  64. package/dist/wizard/index.js.map +1 -0
  65. package/package.json +114 -4
@@ -0,0 +1,2533 @@
1
+ // src/providers/base/provider.types.ts
2
+ function isTextProvider(provider) {
3
+ return provider.capabilities.includes("text");
4
+ }
5
+ function isMediaProvider(provider) {
6
+ return provider.capabilities.includes("image") || provider.capabilities.includes("video");
7
+ }
8
+
9
+ // src/core/errors/ai-error-types.ts
10
+ var AIErrorType = /* @__PURE__ */ ((AIErrorType2) => {
11
+ AIErrorType2["INVALID_API_KEY"] = "INVALID_API_KEY";
12
+ AIErrorType2["MISSING_CONFIG"] = "MISSING_CONFIG";
13
+ AIErrorType2["NETWORK_ERROR"] = "NETWORK_ERROR";
14
+ AIErrorType2["ABORT_ERROR"] = "ABORT_ERROR";
15
+ AIErrorType2["RATE_LIMIT_ERROR"] = "RATE_LIMIT_ERROR";
16
+ AIErrorType2["SERVER_ERROR"] = "SERVER_ERROR";
17
+ AIErrorType2["CLIENT_ERROR"] = "CLIENT_ERROR";
18
+ AIErrorType2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
19
+ return AIErrorType2;
20
+ })(AIErrorType || {});
21
+
22
+ // src/core/errors/ai-error.ts
23
+ var KNOWN_ERROR_TYPES = new Set(Object.values(AIErrorType));
24
+ function mapCodeToType(code) {
25
+ switch (code) {
26
+ case "VALIDATION_ERROR":
27
+ case "CLIENT_ERROR":
28
+ return "CLIENT_ERROR" /* CLIENT_ERROR */;
29
+ case "INVALID_API_KEY":
30
+ return "INVALID_API_KEY" /* INVALID_API_KEY */;
31
+ case "MISSING_CONFIG":
32
+ case "PROVIDER_UNAVAILABLE":
33
+ return "MISSING_CONFIG" /* MISSING_CONFIG */;
34
+ case "PROVIDER_QUOTA_EXHAUSTED":
35
+ case "RATE_LIMIT_ERROR":
36
+ return "RATE_LIMIT_ERROR" /* RATE_LIMIT_ERROR */;
37
+ case "NETWORK_ERROR":
38
+ case "TIMEOUT":
39
+ return "NETWORK_ERROR" /* NETWORK_ERROR */;
40
+ case "ABORT_ERROR":
41
+ case "ABORTED":
42
+ return "ABORT_ERROR" /* ABORT_ERROR */;
43
+ case "SERVER_ERROR":
44
+ case "PROVIDER_ERROR":
45
+ case "NO_RESULT":
46
+ return "SERVER_ERROR" /* SERVER_ERROR */;
47
+ default:
48
+ return "UNKNOWN_ERROR" /* UNKNOWN_ERROR */;
49
+ }
50
+ }
51
+ function mapMessageToCode(message, fallback = "UNKNOWN") {
52
+ const lower = message.toLowerCase();
53
+ if (lower.includes("validation")) return "VALIDATION_ERROR";
54
+ if (lower.includes("quota")) return "PROVIDER_QUOTA_EXHAUSTED";
55
+ if (lower.includes("unavailable")) return "PROVIDER_UNAVAILABLE";
56
+ if (lower.includes("timeout") || lower.includes("aborted")) {
57
+ return lower.includes("aborted") ? "ABORTED" : "TIMEOUT";
58
+ }
59
+ if (lower.includes("parse") || lower.includes("json")) return "PARSE_ERROR";
60
+ if (lower.includes("no result")) return "NO_RESULT";
61
+ if (lower.includes("network") || lower.includes("fetch")) return "NETWORK_ERROR";
62
+ return fallback;
63
+ }
64
+ var AIError = class _AIError extends Error {
65
+ type;
66
+ code;
67
+ cause;
68
+ metadata;
69
+ constructor(typeOrMessage, messageOrCode, cause, metadata = {}) {
70
+ let effectiveType;
71
+ let effectiveMessage;
72
+ let effectiveCode;
73
+ if (KNOWN_ERROR_TYPES.has(typeOrMessage)) {
74
+ effectiveType = typeOrMessage;
75
+ effectiveMessage = messageOrCode ?? "";
76
+ effectiveCode = effectiveType;
77
+ } else {
78
+ effectiveMessage = typeOrMessage;
79
+ effectiveCode = messageOrCode ?? "UNKNOWN";
80
+ effectiveType = mapCodeToType(effectiveCode);
81
+ }
82
+ super(effectiveMessage);
83
+ this.name = "AIError";
84
+ this.type = effectiveType;
85
+ this.code = effectiveCode;
86
+ this.cause = cause;
87
+ this.metadata = metadata;
88
+ }
89
+ static from(error, fallbackCode = "UNKNOWN") {
90
+ if (error instanceof _AIError) return error;
91
+ if (error instanceof Error) {
92
+ const code = mapMessageToCode(error.message, fallbackCode);
93
+ return new _AIError(error.message, code, error);
94
+ }
95
+ return new _AIError(String(error), fallbackCode, error);
96
+ }
97
+ toString() {
98
+ const statusPart = typeof this.metadata.status === "number" ? ` (HTTP ${this.metadata.status})` : "";
99
+ return `${this.name} [${this.type}]: ${this.message}${statusPart}`;
100
+ }
101
+ toJSON() {
102
+ return {
103
+ name: this.name,
104
+ type: this.type,
105
+ code: this.code,
106
+ message: this.message,
107
+ metadata: this.metadata
108
+ };
109
+ }
110
+ };
111
+
112
+ // src/content/domain/limits/ProviderTimingConfig.ts
113
+ var ProviderTimingConfig = {
114
+ DEFAULT_TIMEOUT_MS: 3e4,
115
+ DEFAULT_RETRY_ATTEMPTS: 3,
116
+ FAL_TIMEOUT_MS: 12e4,
117
+ FAL_RETRY_ATTEMPTS: 2,
118
+ GEMINI_TIMEOUT_MS: 6e4,
119
+ GEMINI_RETRY_ATTEMPTS: 3,
120
+ HEALTH_CHECK_TTL_MS: 5 * 60 * 1e3,
121
+ RETRY_BACKOFF_BASE_MS: 1e3
122
+ };
123
+
124
+ // src/content/domain/calculations/RetryBackoffDelay.ts
125
+ function calculateRetryBackoffDelayMs(attemptIndex) {
126
+ return ProviderTimingConfig.RETRY_BACKOFF_BASE_MS * Math.pow(2, attemptIndex);
127
+ }
128
+
129
+ // src/providers/base/base.provider.ts
130
+ var BaseProvider = class {
131
+ config;
132
+ constructor(config) {
133
+ this.config = config;
134
+ }
135
+ async healthCheck() {
136
+ if (!this.config.apiKey) {
137
+ return "unavailable";
138
+ }
139
+ return "healthy";
140
+ }
141
+ async estimateCost(_request) {
142
+ return 0;
143
+ }
144
+ async fetchWithTimeout(url, options, timeout) {
145
+ const effectiveTimeout = timeout ?? this.config.timeout ?? ProviderTimingConfig.DEFAULT_TIMEOUT_MS;
146
+ const controller = new AbortController();
147
+ const timeoutId = setTimeout(() => controller.abort(), effectiveTimeout);
148
+ try {
149
+ const response = await fetch(url, {
150
+ ...options,
151
+ signal: controller.signal
152
+ });
153
+ clearTimeout(timeoutId);
154
+ return response;
155
+ } catch (error) {
156
+ clearTimeout(timeoutId);
157
+ throw error;
158
+ }
159
+ }
160
+ async withRetry(fn, maxAttempts) {
161
+ const attempts = maxAttempts ?? this.config.retryAttempts ?? ProviderTimingConfig.DEFAULT_RETRY_ATTEMPTS;
162
+ let lastError;
163
+ for (let i = 0; i < attempts; i++) {
164
+ try {
165
+ return await fn();
166
+ } catch (error) {
167
+ lastError = error;
168
+ if (i < attempts - 1) {
169
+ await new Promise((resolve) => setTimeout(resolve, calculateRetryBackoffDelayMs(i)));
170
+ }
171
+ }
172
+ }
173
+ throw lastError || new Error("Retry attempts exhausted");
174
+ }
175
+ };
176
+ var ProviderError = class extends AIError {
177
+ constructor(message, providerId, originalError) {
178
+ super(message, "PROVIDER_ERROR", originalError);
179
+ this.providerId = providerId;
180
+ this.name = "ProviderError";
181
+ }
182
+ providerId;
183
+ };
184
+
185
+ // src/core/errors/error-classifier.ts
186
+ var DEFAULT_RETRYABLE_TYPES = /* @__PURE__ */ new Set([
187
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
188
+ "RATE_LIMIT_ERROR" /* RATE_LIMIT_ERROR */,
189
+ "SERVER_ERROR" /* SERVER_ERROR */
190
+ ]);
191
+ var DEFAULT_AUTH_TYPES = /* @__PURE__ */ new Set([
192
+ "INVALID_API_KEY" /* INVALID_API_KEY */
193
+ ]);
194
+ var DEFAULT_ERROR_CLASSIFICATION_RULE = {
195
+ retryable: DEFAULT_RETRYABLE_TYPES,
196
+ auth: DEFAULT_AUTH_TYPES
197
+ };
198
+ function isRetryableErrorType(type, rule = DEFAULT_ERROR_CLASSIFICATION_RULE) {
199
+ return rule.retryable.has(type);
200
+ }
201
+
202
+ // src/core/errors/http-status-classifier.ts
203
+ var DEFAULT_HTTP_STATUS_RULE = {
204
+ unauthorizedStatuses: /* @__PURE__ */ new Set([401, 403]),
205
+ rateLimitedStatus: 429,
206
+ serverErrorThreshold: 500,
207
+ clientErrorThreshold: 400
208
+ };
209
+ function classifyHttpStatus(status, rule = DEFAULT_HTTP_STATUS_RULE) {
210
+ if (rule.unauthorizedStatuses.has(status)) return "INVALID_API_KEY" /* INVALID_API_KEY */;
211
+ if (status === rule.rateLimitedStatus) return "RATE_LIMIT_ERROR" /* RATE_LIMIT_ERROR */;
212
+ if (status >= rule.serverErrorThreshold) return "SERVER_ERROR" /* SERVER_ERROR */;
213
+ if (status >= rule.clientErrorThreshold) return "CLIENT_ERROR" /* CLIENT_ERROR */;
214
+ return "UNKNOWN_ERROR" /* UNKNOWN_ERROR */;
215
+ }
216
+
217
+ // src/core/errors/response-error-message-extractor.ts
218
+ function extractErrorMessageFromJsonBody(body) {
219
+ if (!body || typeof body !== "object") return null;
220
+ const candidate = body;
221
+ const message = candidate.error?.message ?? candidate.message;
222
+ if (typeof message === "string" && message.length > 0) return message;
223
+ return null;
224
+ }
225
+ function buildHttpStatusFallback(status, statusText) {
226
+ const trimmedStatusText = statusText.trim();
227
+ if (trimmedStatusText.length > 0) {
228
+ return `HTTP ${status}: ${trimmedStatusText}`;
229
+ }
230
+ return `HTTP ${status}`;
231
+ }
232
+ async function extractErrorMessageFromResponse(response) {
233
+ const body = await response.json().catch(() => null);
234
+ const fromBody = extractErrorMessageFromJsonBody(body);
235
+ if (fromBody) return fromBody;
236
+ return buildHttpStatusFallback(response.status, response.statusText);
237
+ }
238
+
239
+ // src/providers/factory/provider.factory.ts
240
+ var ProviderFactory = class {
241
+ providers = /* @__PURE__ */ new Map();
242
+ healthCache = /* @__PURE__ */ new Map();
243
+ priority;
244
+ fallbackEnabled;
245
+ defaultTier;
246
+ constructor(config = {}) {
247
+ this.priority = config.priority ?? [];
248
+ this.fallbackEnabled = config.fallbackEnabled ?? true;
249
+ this.defaultTier = config.defaultTier ?? "balanced";
250
+ }
251
+ register(provider) {
252
+ this.providers.set(provider.id, provider);
253
+ }
254
+ getProvider(id) {
255
+ return this.providers.get(id);
256
+ }
257
+ getAllProviders() {
258
+ return Array.from(this.providers.values());
259
+ }
260
+ getByCapability(capability) {
261
+ return this.getAllProviders().filter(
262
+ (provider) => provider.capabilities.includes(capability)
263
+ );
264
+ }
265
+ getTextProviders() {
266
+ return this.getAllProviders().filter(isTextProvider);
267
+ }
268
+ hasTextProvider() {
269
+ return this.getByCapability("text").length > 0;
270
+ }
271
+ /* ---------- neutral text surface ---------- */
272
+ /**
273
+ * Single-chat entry point: resolves a healthy text provider by priority,
274
+ * injects the default tier when the request names neither model nor tier,
275
+ * and walks the fallback chain on failure. Providers map tiers onto their
276
+ * own models, so switching Groq→Anthropic is a config change.
277
+ */
278
+ async chat(request) {
279
+ const effective = request.model || request.tier ? request : { ...request, tier: this.defaultTier };
280
+ return this.executeWithFallback(
281
+ "text",
282
+ (provider) => provider.generate(effective)
283
+ );
284
+ }
285
+ async chatStream(request, callbacks) {
286
+ const effective = request.model || request.tier ? request : { ...request, tier: this.defaultTier };
287
+ let lastError;
288
+ const attemptCallbacks = {
289
+ onChunk: callbacks.onChunk,
290
+ onComplete: callbacks.onComplete
291
+ };
292
+ const providers = this.getByCapability("text");
293
+ if (providers.length === 0) {
294
+ throw this.noProviderError("text");
295
+ }
296
+ const ordered = this.orderByPriority(providers);
297
+ for (const provider of ordered) {
298
+ if (!this.isProviderHealthy(provider.id)) continue;
299
+ try {
300
+ return await provider.stream(effective, attemptCallbacks);
301
+ } catch (error) {
302
+ lastError = error;
303
+ this.markDegraded(provider.id);
304
+ if (!this.fallbackEnabled) {
305
+ callbacks.onError?.(error instanceof Error ? error : new Error(String(error)));
306
+ throw error;
307
+ }
308
+ }
309
+ }
310
+ const failure = new AIError(
311
+ "SERVER_ERROR" /* SERVER_ERROR */,
312
+ `All providers failed for capability 'text'`,
313
+ lastError instanceof Error ? lastError : void 0
314
+ );
315
+ callbacks.onError?.(lastError instanceof Error ? lastError : failure);
316
+ throw failure;
317
+ }
318
+ /** AsyncGenerator adapter over chatStream — A's familiar consumption shape. */
319
+ async *streamText(request) {
320
+ const queue = [];
321
+ let wake = null;
322
+ let finished = false;
323
+ let failure;
324
+ const controller = new AbortController();
325
+ const onAbort = () => controller.abort();
326
+ request.signal?.addEventListener("abort", onAbort);
327
+ const effectiveRequest = { ...request, signal: controller.signal };
328
+ const notify = () => {
329
+ const resolve = wake;
330
+ wake = null;
331
+ resolve?.();
332
+ };
333
+ const completion = this.chatStream(effectiveRequest, {
334
+ onChunk: (chunk) => {
335
+ queue.push(chunk);
336
+ notify();
337
+ }
338
+ }).then(
339
+ () => {
340
+ finished = true;
341
+ notify();
342
+ },
343
+ (error) => {
344
+ failure = error;
345
+ finished = true;
346
+ notify();
347
+ }
348
+ );
349
+ try {
350
+ while (!finished || queue.length > 0) {
351
+ if (queue.length === 0 && !finished) {
352
+ await new Promise((resolve) => {
353
+ wake = resolve;
354
+ });
355
+ }
356
+ while (queue.length > 0) {
357
+ yield queue.shift();
358
+ }
359
+ if (failure) throw failure;
360
+ }
361
+ await completion;
362
+ } finally {
363
+ controller.abort();
364
+ request.signal?.removeEventListener("abort", onAbort);
365
+ }
366
+ }
367
+ async generateJson(request) {
368
+ const effective = request.model || request.tier ? request : { ...request, tier: this.defaultTier };
369
+ return this.executeWithFallback(
370
+ "text",
371
+ (provider) => provider.generateStructured(effective)
372
+ );
373
+ }
374
+ /* ---------- content-layer string facade (ITextGenerator) ---------- */
375
+ async generateText(prompt, options = {}) {
376
+ const result = await this.chat({
377
+ messages: [{ role: "user", content: prompt }],
378
+ model: options.model,
379
+ maxTokens: options.maxTokens,
380
+ temperature: options.temperature,
381
+ topP: options.topP
382
+ });
383
+ return result.text;
384
+ }
385
+ generateTextStream(prompt, options = {}) {
386
+ return this.streamText({
387
+ messages: [{ role: "user", content: prompt }],
388
+ model: options.model,
389
+ maxTokens: options.maxTokens,
390
+ temperature: options.temperature,
391
+ topP: options.topP
392
+ });
393
+ }
394
+ /* ---------- media surface ---------- */
395
+ async generateImage(request) {
396
+ return this.executeWithFallback(
397
+ "image",
398
+ (provider) => provider.generateImage(request)
399
+ );
400
+ }
401
+ async generateVideo(request) {
402
+ return this.executeWithFallback(
403
+ "video",
404
+ (provider) => provider.generateVideo(request)
405
+ );
406
+ }
407
+ async imageToVideo(request) {
408
+ return this.executeWithFallback(
409
+ "video",
410
+ (provider) => provider.imageToVideo(request)
411
+ );
412
+ }
413
+ async videoToVideo(request) {
414
+ return this.executeWithFallback(
415
+ "video",
416
+ (provider) => provider.videoToVideo(request)
417
+ );
418
+ }
419
+ /* ---------- health ---------- */
420
+ async checkProviderHealth(providerId, forceRefresh = false) {
421
+ const provider = this.providers.get(providerId);
422
+ if (!provider) {
423
+ return "unavailable";
424
+ }
425
+ const cached = this.healthCache.get(providerId);
426
+ const now = Date.now();
427
+ const ttl = ProviderTimingConfig.HEALTH_CHECK_TTL_MS;
428
+ if (!forceRefresh && cached && now - cached.timestamp < ttl) {
429
+ return cached.health;
430
+ }
431
+ try {
432
+ const health = await provider.healthCheck();
433
+ this.healthCache.set(providerId, { health, timestamp: now });
434
+ return health;
435
+ } catch {
436
+ this.healthCache.set(providerId, { health: "unavailable", timestamp: now });
437
+ return "unavailable";
438
+ }
439
+ }
440
+ isProviderHealthy(providerId) {
441
+ const cached = this.healthCache.get(providerId);
442
+ if (!cached) {
443
+ return true;
444
+ }
445
+ return cached.health === "healthy" || cached.health === "degraded";
446
+ }
447
+ async refreshAllHealth() {
448
+ await Promise.all(
449
+ Array.from(this.providers.keys()).map((id) => this.checkProviderHealth(id))
450
+ );
451
+ }
452
+ /* ---------- internals ---------- */
453
+ async executeWithFallback(capability, fn) {
454
+ const providers = this.getByCapability(capability);
455
+ if (providers.length === 0) {
456
+ throw this.noProviderError(capability);
457
+ }
458
+ let lastError;
459
+ for (const provider of this.orderByPriority(providers)) {
460
+ if (!this.isProviderHealthy(provider.id)) {
461
+ continue;
462
+ }
463
+ try {
464
+ return await fn(provider);
465
+ } catch (error) {
466
+ lastError = error;
467
+ this.markDegraded(provider.id);
468
+ if (!this.fallbackEnabled) {
469
+ throw error;
470
+ }
471
+ }
472
+ }
473
+ throw new AIError(
474
+ "SERVER_ERROR" /* SERVER_ERROR */,
475
+ `All providers failed for capability '${capability}'`,
476
+ lastError instanceof Error ? lastError : void 0
477
+ );
478
+ }
479
+ orderByPriority(providers) {
480
+ if (this.priority.length === 0) {
481
+ return providers;
482
+ }
483
+ const ordered = [];
484
+ for (const providerId of this.priority) {
485
+ const provider = providers.find((p) => p.id === providerId);
486
+ if (provider) ordered.push(provider);
487
+ }
488
+ for (const provider of providers) {
489
+ if (!this.priority.includes(provider.id)) {
490
+ ordered.push(provider);
491
+ }
492
+ }
493
+ return ordered;
494
+ }
495
+ markDegraded(providerId) {
496
+ const cached = this.healthCache.get(providerId);
497
+ if (cached) {
498
+ this.healthCache.set(providerId, { health: "degraded", timestamp: cached.timestamp });
499
+ }
500
+ }
501
+ noProviderError(capability) {
502
+ return new AIError(
503
+ "MISSING_CONFIG" /* MISSING_CONFIG */,
504
+ `No provider registered for capability '${capability}' \u2014 create one with createAI() and include its config block`
505
+ );
506
+ }
507
+ };
508
+
509
+ // src/core/constants/protocol.constants.ts
510
+ var SSE_PREFIX = "data: ";
511
+ var SSE_DONE_MARKER = "[DONE]";
512
+ var JSON_CODE_BLOCK_PATTERN = /```(?:json)?\s*\n?([\s\S]*?)\n?```/;
513
+ var JSON_OBJECT_PATTERN = /\{[\s\S]*\}/;
514
+ var JSON_ARRAY_PATTERN = /\[[\s\S]*\]/;
515
+
516
+ // src/core/parsers/sse-lines.ts
517
+ function isSseDataLine(line) {
518
+ return line.startsWith(SSE_PREFIX) || line.startsWith("data:");
519
+ }
520
+ function extractSseDataPayload(line) {
521
+ if (line.startsWith(SSE_PREFIX)) {
522
+ return line.slice(SSE_PREFIX.length);
523
+ }
524
+ if (line.startsWith("data:")) {
525
+ return line.slice(5);
526
+ }
527
+ return line;
528
+ }
529
+ function isSseDoneMarker(payload) {
530
+ return payload === SSE_DONE_MARKER;
531
+ }
532
+
533
+ // src/core/parsers/json-content-extractor.ts
534
+ function extractJsonFromCodeFence(content) {
535
+ const match = content.match(JSON_CODE_BLOCK_PATTERN);
536
+ if (match && match[1]) return match[1].trim();
537
+ return null;
538
+ }
539
+ function extractJsonObject(content) {
540
+ const match = content.match(JSON_OBJECT_PATTERN);
541
+ if (match && match[0]) return match[0];
542
+ return null;
543
+ }
544
+ function extractJsonArray(content) {
545
+ const match = content.match(JSON_ARRAY_PATTERN);
546
+ if (match && match[0]) return match[0];
547
+ return null;
548
+ }
549
+ function repairCommonJsonDefects(text) {
550
+ return text.replace(/(:\s*-?\d+(?:\.\d+)?)\s*"/g, "$1").replace(/(:\s*"[^"]*")"/g, "$1");
551
+ }
552
+ function extractJsonCandidate(content) {
553
+ const fromFence = extractJsonFromCodeFence(content);
554
+ if (fromFence) return fromFence;
555
+ const objectIndex = content.indexOf("{");
556
+ const arrayIndex = content.indexOf("[");
557
+ if (objectIndex !== -1 && (arrayIndex === -1 || objectIndex < arrayIndex)) {
558
+ const obj = extractJsonObject(content);
559
+ if (obj) return obj;
560
+ } else if (arrayIndex !== -1) {
561
+ const arr = extractJsonArray(content);
562
+ if (arr) return arr;
563
+ }
564
+ return content.trim();
565
+ }
566
+
567
+ // src/core/parsers/json-response.parser.ts
568
+ var JsonResponseParser = class {
569
+ parse(rawContent) {
570
+ const candidate = extractJsonCandidate(rawContent);
571
+ try {
572
+ return JSON.parse(candidate);
573
+ } catch {
574
+ try {
575
+ return JSON.parse(repairCommonJsonDefects(candidate));
576
+ } catch (error) {
577
+ throw new AIError(
578
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
579
+ "Failed to parse structured response as JSON",
580
+ error instanceof Error ? error : void 0,
581
+ { rawContent }
582
+ );
583
+ }
584
+ }
585
+ }
586
+ };
587
+
588
+ // src/core/parsers/structured-prompt.builder.ts
589
+ var StructuredPromptBuilder = class _StructuredPromptBuilder {
590
+ schema;
591
+ request;
592
+ constructor(request) {
593
+ this.request = request;
594
+ }
595
+ static for(request) {
596
+ return new _StructuredPromptBuilder(request);
597
+ }
598
+ withSchema(schema) {
599
+ this.schema = schema;
600
+ return this;
601
+ }
602
+ build() {
603
+ const schemaSection = this.schema ? `Expected JSON schema:
604
+ ${JSON.stringify(this.schema, null, 2)}
605
+
606
+ ` : "";
607
+ return "Please generate a JSON response for the following request.\n\n" + schemaSection + `Request:
608
+ ${this.request}
609
+
610
+ Respond only with valid JSON, formatted as:
611
+ \`\`\`json
612
+ {...}
613
+ \`\`\``;
614
+ }
615
+ };
616
+
617
+ // src/core/tiers/index.ts
618
+ function resolveModel(tiers, tier, providerId) {
619
+ const model = tiers[tier] ?? tiers.balanced;
620
+ if (!model) {
621
+ throw new Error(
622
+ `${providerId} has no model configured for tier "${tier}" \u2014 pass an explicit model or configure the tier map`
623
+ );
624
+ }
625
+ return model;
626
+ }
627
+ function mergeTierOverrides(defaults, overrides) {
628
+ if (!overrides) return defaults;
629
+ return { ...defaults, ...overrides };
630
+ }
631
+
632
+ // src/providers/anthropic/anthropic.constants.ts
633
+ var ANTHROPIC_MODELS = {
634
+ OPUS_5_5: "claude-opus-5-5",
635
+ SONNET_5_5: "claude-sonnet-5-5",
636
+ HAIKU_5_5: "claude-haiku-5-5"
637
+ };
638
+ var ANTHROPIC_TIERS = {
639
+ fast: ANTHROPIC_MODELS.HAIKU_5_5,
640
+ balanced: ANTHROPIC_MODELS.SONNET_5_5,
641
+ powerful: ANTHROPIC_MODELS.OPUS_5_5
642
+ };
643
+ var ANTHROPIC_API_VERSION = "2026-10-21";
644
+ var ANTHROPIC_DEFAULT_MAX_TOKENS = 16e3;
645
+ var ANTHROPIC_BASE_URL = "https://api.anthropic.com";
646
+ var ANTHROPIC_MESSAGES_PATH = "/v1/messages";
647
+ var ANTHROPIC_MODELS_PATH = "/v1/models";
648
+ var ANTHROPIC_TIMEOUTS = {
649
+ DEFAULT: 6e4,
650
+ STREAMING: 12e4
651
+ };
652
+ var ANTHROPIC_HEADERS = {
653
+ CONTENT_TYPE: "Content-Type",
654
+ APPLICATION_JSON: "application/json",
655
+ API_KEY: "x-api-key",
656
+ VERSION: "anthropic-version"
657
+ };
658
+ var ANTHROPIC_DEFAULT_EFFORT = {
659
+ [ANTHROPIC_MODELS.OPUS_5_5]: "medium",
660
+ [ANTHROPIC_MODELS.SONNET_5_5]: "high",
661
+ [ANTHROPIC_MODELS.HAIKU_5_5]: "medium"
662
+ };
663
+
664
+ // src/providers/anthropic/anthropic-http.transport.ts
665
+ var AnthropicHttpTransport = class {
666
+ constructor(config) {
667
+ this.config = config;
668
+ }
669
+ config;
670
+ async postMessages(request, options = {}) {
671
+ const url = `${this.baseUrl()}${ANTHROPIC_MESSAGES_PATH}`;
672
+ const timeout = this.config.timeoutMs ?? ANTHROPIC_TIMEOUTS.DEFAULT;
673
+ const controller = new AbortController();
674
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
675
+ const onExternalAbort = () => controller.abort();
676
+ options.signal?.addEventListener("abort", onExternalAbort);
677
+ try {
678
+ const response = await fetch(url, {
679
+ method: "POST",
680
+ headers: this.buildHeaders(),
681
+ body: JSON.stringify({ ...request, stream: false }),
682
+ signal: controller.signal
683
+ });
684
+ if (!response.ok) await this.throwFromErrorResponse(response);
685
+ return await response.json();
686
+ } catch (error) {
687
+ throw this.normalizeError(error);
688
+ } finally {
689
+ clearTimeout(timeoutId);
690
+ options.signal?.removeEventListener("abort", onExternalAbort);
691
+ }
692
+ }
693
+ async streamMessages(request, options = {}) {
694
+ const url = `${this.baseUrl()}${ANTHROPIC_MESSAGES_PATH}`;
695
+ const timeout = this.config.timeoutMs ?? ANTHROPIC_TIMEOUTS.STREAMING;
696
+ const controller = new AbortController();
697
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
698
+ const onExternalAbort = () => controller.abort();
699
+ options.signal?.addEventListener("abort", onExternalAbort);
700
+ try {
701
+ const response = await fetch(url, {
702
+ method: "POST",
703
+ headers: this.buildHeaders(),
704
+ body: JSON.stringify({ ...request, stream: true }),
705
+ signal: controller.signal
706
+ });
707
+ if (!response.ok) await this.throwFromErrorResponse(response);
708
+ if (!response.body) {
709
+ throw new AIError("NETWORK_ERROR" /* NETWORK_ERROR */, "Response body is null");
710
+ }
711
+ return response.body;
712
+ } catch (error) {
713
+ options.signal?.removeEventListener("abort", onExternalAbort);
714
+ throw this.normalizeError(error);
715
+ } finally {
716
+ clearTimeout(timeoutId);
717
+ }
718
+ }
719
+ async listModels() {
720
+ const url = `${this.baseUrl()}${ANTHROPIC_MODELS_PATH}`;
721
+ return fetch(url, {
722
+ method: "GET",
723
+ headers: this.buildHeaders()
724
+ });
725
+ }
726
+ baseUrl() {
727
+ return this.config.baseUrl ?? ANTHROPIC_BASE_URL;
728
+ }
729
+ buildHeaders() {
730
+ return {
731
+ [ANTHROPIC_HEADERS.CONTENT_TYPE]: ANTHROPIC_HEADERS.APPLICATION_JSON,
732
+ [ANTHROPIC_HEADERS.API_KEY]: this.config.apiKey,
733
+ [ANTHROPIC_HEADERS.VERSION]: ANTHROPIC_API_VERSION
734
+ };
735
+ }
736
+ async throwFromErrorResponse(response) {
737
+ const errorMessage = await extractErrorMessageFromResponse(response);
738
+ const metadata = {
739
+ status: response.status,
740
+ url: response.url
741
+ };
742
+ throw new AIError(
743
+ classifyHttpStatus(response.status),
744
+ errorMessage,
745
+ void 0,
746
+ metadata
747
+ );
748
+ }
749
+ normalizeError(error) {
750
+ if (error instanceof AIError) return error;
751
+ if (error instanceof Error) {
752
+ if (error.name === "AbortError") {
753
+ return new AIError(
754
+ "ABORT_ERROR" /* ABORT_ERROR */,
755
+ "Request was aborted by the client",
756
+ error
757
+ );
758
+ }
759
+ if (error.name === "TypeError" && error.message.toLowerCase().includes("network")) {
760
+ return new AIError(
761
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
762
+ "Network error: Unable to connect to the AI service",
763
+ error
764
+ );
765
+ }
766
+ }
767
+ return new AIError(
768
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
769
+ error instanceof Error ? error.message : "Unknown error occurred",
770
+ error instanceof Error ? error : void 0
771
+ );
772
+ }
773
+ };
774
+
775
+ // src/providers/anthropic/anthropic-request.builder.ts
776
+ var AnthropicRequestBuilder = class _AnthropicRequestBuilder {
777
+ model;
778
+ messages = [];
779
+ systemPrompt;
780
+ maxTokens = ANTHROPIC_DEFAULT_MAX_TOKENS;
781
+ effort;
782
+ stopSequences;
783
+ streamEnabled = false;
784
+ constructor(model) {
785
+ this.model = model;
786
+ }
787
+ static for(model) {
788
+ return new _AnthropicRequestBuilder(model);
789
+ }
790
+ withRequest(request) {
791
+ this.messages = toAnthropicMessages(request.messages);
792
+ this.systemPrompt = request.systemPrompt;
793
+ if (request.maxTokens !== void 0) this.maxTokens = request.maxTokens;
794
+ if (request.stopSequences !== void 0 && request.stopSequences.length > 0) {
795
+ this.stopSequences = [...request.stopSequences];
796
+ }
797
+ return this;
798
+ }
799
+ withEffort(effort) {
800
+ this.effort = effort;
801
+ return this;
802
+ }
803
+ withStream(stream) {
804
+ this.streamEnabled = stream;
805
+ return this;
806
+ }
807
+ withSystemPromptOverride(systemPrompt) {
808
+ this.systemPrompt = systemPrompt;
809
+ return this;
810
+ }
811
+ withMessagesOverride(messages) {
812
+ this.messages = messages;
813
+ return this;
814
+ }
815
+ build() {
816
+ const request = {
817
+ model: this.model,
818
+ messages: this.messages,
819
+ max_tokens: this.maxTokens,
820
+ output_config: {
821
+ effort: this.effort ?? defaultEffortForModel(this.model)
822
+ }
823
+ };
824
+ if (this.systemPrompt !== void 0 && this.systemPrompt.length > 0) {
825
+ request.system = this.systemPrompt;
826
+ }
827
+ if (this.stopSequences !== void 0) {
828
+ request.stop_sequences = this.stopSequences;
829
+ }
830
+ if (this.streamEnabled) {
831
+ request.stream = true;
832
+ }
833
+ return request;
834
+ }
835
+ };
836
+ function toAnthropicMessages(messages) {
837
+ return messages.filter((message) => message.role !== "system" && message.content.length > 0).map((message) => ({
838
+ role: message.role,
839
+ content: message.content
840
+ }));
841
+ }
842
+ function defaultEffortForModel(model) {
843
+ return ANTHROPIC_DEFAULT_EFFORT[model] ?? "medium";
844
+ }
845
+
846
+ // src/providers/anthropic/anthropic-stream.parser.ts
847
+ function mapAnthropicStopReason(reason) {
848
+ if (reason === "end_turn") return "stop";
849
+ if (reason === "stop_sequence") return "stop";
850
+ if (reason === "max_tokens") return "length";
851
+ if (reason === "refusal") return "refusal";
852
+ return void 0;
853
+ }
854
+ async function consumeAnthropicStream(stream, callbacks) {
855
+ const reader = stream.getReader();
856
+ const decoder = new TextDecoder();
857
+ const chunks = [];
858
+ let buffer = "";
859
+ let model = null;
860
+ let inputTokens;
861
+ let outputTokens;
862
+ let finishReason;
863
+ const consumeLine = (rawLine) => {
864
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
865
+ const trimmed = line.trim();
866
+ if (trimmed.length === 0 || !isSseDataLine(trimmed)) return;
867
+ const payload = extractSseDataPayload(trimmed);
868
+ let event;
869
+ try {
870
+ event = JSON.parse(payload);
871
+ } catch {
872
+ return;
873
+ }
874
+ switch (event.type) {
875
+ case "message_start":
876
+ model = event.message.model;
877
+ if (event.message.usage?.input_tokens !== void 0) {
878
+ inputTokens = event.message.usage.input_tokens;
879
+ }
880
+ break;
881
+ case "content_block_delta":
882
+ if (typeof event.delta.text === "string" && event.delta.text.length > 0) {
883
+ chunks.push(event.delta.text);
884
+ callbacks.onChunk?.(event.delta.text);
885
+ }
886
+ break;
887
+ case "message_delta":
888
+ if (event.delta?.stop_reason !== void 0 && event.delta.stop_reason !== null) {
889
+ finishReason = mapAnthropicStopReason(event.delta.stop_reason);
890
+ }
891
+ if (event.usage?.output_tokens !== void 0) {
892
+ outputTokens = event.usage.output_tokens;
893
+ }
894
+ break;
895
+ case "message_stop":
896
+ break;
897
+ case "error": {
898
+ const errType = event.error.type;
899
+ const mappedType = errType === "rate_limit_error" ? "RATE_LIMIT_ERROR" /* RATE_LIMIT_ERROR */ : errType === "authentication_error" ? "INVALID_API_KEY" /* INVALID_API_KEY */ : errType === "invalid_request_error" ? "CLIENT_ERROR" /* CLIENT_ERROR */ : "SERVER_ERROR" /* SERVER_ERROR */;
900
+ throw new AIError(
901
+ mappedType,
902
+ event.error.message || "Anthropic stream failed mid-flight"
903
+ );
904
+ }
905
+ }
906
+ };
907
+ try {
908
+ while (true) {
909
+ const { done, value } = await reader.read();
910
+ if (done) break;
911
+ buffer += decoder.decode(value, { stream: true });
912
+ const lines = buffer.split("\n");
913
+ buffer = lines.pop() ?? "";
914
+ for (const line of lines) consumeLine(line);
915
+ }
916
+ buffer += decoder.decode();
917
+ if (buffer.length > 0) consumeLine(buffer);
918
+ } catch (error) {
919
+ if (error instanceof AIError) throw error;
920
+ throw new AIError(
921
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
922
+ "Stream was interrupted",
923
+ error instanceof Error ? error : void 0
924
+ );
925
+ } finally {
926
+ reader.releaseLock();
927
+ }
928
+ return {
929
+ text: chunks.join(""),
930
+ model,
931
+ inputTokens,
932
+ outputTokens,
933
+ finishReason
934
+ };
935
+ }
936
+
937
+ // src/providers/anthropic/anthropic.provider.ts
938
+ var REFUSAL_FALLBACK_TEXT = "I'm not able to help with that request. Could you rephrase or ask something else?";
939
+ var AnthropicProvider = class {
940
+ constructor(config) {
941
+ this.config = config;
942
+ this.transport = new AnthropicHttpTransport(config);
943
+ this.tiers = mergeTierOverrides(ANTHROPIC_TIERS, config.models);
944
+ }
945
+ config;
946
+ id = "anthropic";
947
+ name = "Anthropic";
948
+ capabilities = ["text"];
949
+ transport;
950
+ tiers;
951
+ jsonParser = new JsonResponseParser();
952
+ resolveModel(tier) {
953
+ return resolveModel(this.tiers, tier, this.id);
954
+ }
955
+ async healthCheck() {
956
+ if (!this.config.apiKey) return "unavailable";
957
+ try {
958
+ const response = await this.transport.listModels();
959
+ if (response.ok) return "healthy";
960
+ if (response.status === 401 || response.status === 403) return "unavailable";
961
+ return "degraded";
962
+ } catch {
963
+ return "unavailable";
964
+ }
965
+ }
966
+ async estimateCost() {
967
+ return 0;
968
+ }
969
+ async generate(request) {
970
+ const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
971
+ const wireRequest = new AnthropicRequestBuilder(model).withRequest(request).withEffort(this.config.effort).build();
972
+ const response = await this.transport.postMessages(wireRequest, {
973
+ signal: request.signal
974
+ });
975
+ return this.toGenerationResult(response, model);
976
+ }
977
+ async generateStructured(request) {
978
+ const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
979
+ const messages = [...request.messages];
980
+ const lastUserIndex = findLastIndex(messages, (m) => m.role === "user");
981
+ if (lastUserIndex === -1) {
982
+ throw new AIError(
983
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
984
+ "generateStructured requires at least one user message"
985
+ );
986
+ }
987
+ const structuredPrompt = new StructuredPromptBuilder(
988
+ messages[lastUserIndex].content
989
+ ).withSchema(request.schema).build();
990
+ messages[lastUserIndex] = { role: "user", content: structuredPrompt };
991
+ const wireRequest = new AnthropicRequestBuilder(model).withRequest({ ...request, messages }).withEffort(this.config.effort).build();
992
+ const response = await this.transport.postMessages(wireRequest, {
993
+ signal: request.signal
994
+ });
995
+ const result = this.toGenerationResult(response, model);
996
+ return { value: this.jsonParser.parse(result.text), result };
997
+ }
998
+ async stream(request, callbacks) {
999
+ const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
1000
+ const wireRequest = new AnthropicRequestBuilder(model).withRequest(request).withEffort(this.config.effort).withStream(true).build();
1001
+ const streamBody = await this.transport.streamMessages(wireRequest, {
1002
+ signal: request.signal
1003
+ });
1004
+ try {
1005
+ const outcome = await consumeAnthropicStream(streamBody, callbacks);
1006
+ const text = outcome.text.length > 0 ? outcome.text : refusalTextFor(outcome.finishReason);
1007
+ const result = {
1008
+ text,
1009
+ usage: {
1010
+ inputTokens: outcome.inputTokens ?? 0,
1011
+ outputTokens: outcome.outputTokens ?? 0
1012
+ },
1013
+ model: outcome.model ?? model,
1014
+ providerId: this.id,
1015
+ finishReason: outcome.finishReason
1016
+ };
1017
+ callbacks.onComplete?.(result);
1018
+ return result;
1019
+ } catch (error) {
1020
+ callbacks.onError?.(error instanceof Error ? error : new Error(String(error)));
1021
+ throw error;
1022
+ }
1023
+ }
1024
+ toGenerationResult(response, fallbackModel) {
1025
+ const text = extractText(response.content);
1026
+ const finishReason = mapAnthropicStopReason(response.stop_reason);
1027
+ if (text.length === 0) {
1028
+ if (finishReason === "refusal") {
1029
+ return {
1030
+ text: REFUSAL_FALLBACK_TEXT,
1031
+ usage: mapAnthropicUsage(response.usage),
1032
+ model: response.model || fallbackModel,
1033
+ providerId: this.id,
1034
+ finishReason
1035
+ };
1036
+ }
1037
+ throw new AIError(
1038
+ "SERVER_ERROR" /* SERVER_ERROR */,
1039
+ "No content generated from Anthropic API",
1040
+ void 0,
1041
+ { model: response.model || fallbackModel, stopReason: response.stop_reason ?? void 0 }
1042
+ );
1043
+ }
1044
+ return {
1045
+ text,
1046
+ usage: mapAnthropicUsage(response.usage),
1047
+ model: response.model || fallbackModel,
1048
+ providerId: this.id,
1049
+ finishReason
1050
+ };
1051
+ }
1052
+ };
1053
+ function extractText(blocks) {
1054
+ return blocks.filter((block) => block.type === "text").map((block) => block.text).join("");
1055
+ }
1056
+ function refusalTextFor(finishReason) {
1057
+ return finishReason === "refusal" ? REFUSAL_FALLBACK_TEXT : "";
1058
+ }
1059
+ function mapAnthropicUsage(usage) {
1060
+ if (!usage) return void 0;
1061
+ return {
1062
+ inputTokens: usage.input_tokens,
1063
+ outputTokens: usage.output_tokens
1064
+ };
1065
+ }
1066
+ function findLastIndex(items, predicate) {
1067
+ for (let i = items.length - 1; i >= 0; i--) {
1068
+ if (predicate(items[i])) return i;
1069
+ }
1070
+ return -1;
1071
+ }
1072
+
1073
+ // src/core/calculations/lru-key-selector.ts
1074
+ function selectLeastRecentlyUsedKey(entries) {
1075
+ let oldestKey = null;
1076
+ let oldestAccess = Number.POSITIVE_INFINITY;
1077
+ for (const [key, entry] of entries.entries()) {
1078
+ if (entry.lastAccess < oldestAccess) {
1079
+ oldestAccess = entry.lastAccess;
1080
+ oldestKey = key;
1081
+ }
1082
+ }
1083
+ return oldestKey;
1084
+ }
1085
+
1086
+ // src/core/calculations/cache-hit-rate.ts
1087
+ function calculateCacheHitRate(entries) {
1088
+ if (entries.length === 0) return 0;
1089
+ const totalAccess = entries.reduce((sum, e) => sum + e.accessCount, 0);
1090
+ return totalAccess / entries.length;
1091
+ }
1092
+
1093
+ // src/core/utils/cache-key-builder.ts
1094
+ function buildCacheKey(params) {
1095
+ const sortedKeys = Object.keys(params).sort();
1096
+ const sortedParams = {};
1097
+ for (const key of sortedKeys) {
1098
+ sortedParams[key] = params[key];
1099
+ }
1100
+ return JSON.stringify(sortedParams);
1101
+ }
1102
+
1103
+ // src/core/utils/cache-manager.ts
1104
+ var DEFAULT_CACHE_MAX_SIZE = 100;
1105
+ var DEFAULT_CACHE_TTL_MS = 3e5;
1106
+ var CacheManager = class {
1107
+ cache = /* @__PURE__ */ new Map();
1108
+ maxSize;
1109
+ ttl;
1110
+ constructor(options = {}) {
1111
+ this.maxSize = options.maxSize ?? DEFAULT_CACHE_MAX_SIZE;
1112
+ this.ttl = options.ttl ?? DEFAULT_CACHE_TTL_MS;
1113
+ }
1114
+ get(key) {
1115
+ const entry = this.cache.get(key);
1116
+ if (!entry) return null;
1117
+ if (this.isExpired(entry)) {
1118
+ this.cache.delete(key);
1119
+ return null;
1120
+ }
1121
+ entry.accessCount += 1;
1122
+ entry.lastAccess = Date.now();
1123
+ return entry.value;
1124
+ }
1125
+ set(key, value) {
1126
+ if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
1127
+ const lruKey = selectLeastRecentlyUsedKey(this.cache);
1128
+ if (lruKey !== null) this.cache.delete(lruKey);
1129
+ }
1130
+ this.cache.set(key, {
1131
+ value,
1132
+ timestamp: Date.now(),
1133
+ accessCount: 1,
1134
+ lastAccess: Date.now()
1135
+ });
1136
+ }
1137
+ has(key) {
1138
+ const entry = this.cache.get(key);
1139
+ return entry !== void 0 && !this.isExpired(entry);
1140
+ }
1141
+ delete(key) {
1142
+ return this.cache.delete(key);
1143
+ }
1144
+ clear() {
1145
+ this.cache.clear();
1146
+ }
1147
+ generateKey(params) {
1148
+ return buildCacheKey(params);
1149
+ }
1150
+ getStats() {
1151
+ const now = Date.now();
1152
+ const entries = Array.from(this.cache.entries()).map(([key, entry]) => ({
1153
+ key,
1154
+ accessCount: entry.accessCount,
1155
+ ageMs: now - entry.timestamp
1156
+ }));
1157
+ const hitRate = calculateCacheHitRate(
1158
+ Array.from(this.cache.values()).map((e) => ({ accessCount: e.accessCount }))
1159
+ );
1160
+ return {
1161
+ size: this.cache.size,
1162
+ maxSize: this.maxSize,
1163
+ hitRate,
1164
+ entries
1165
+ };
1166
+ }
1167
+ isExpired(entry) {
1168
+ return Date.now() - entry.timestamp > this.ttl;
1169
+ }
1170
+ };
1171
+ new CacheManager();
1172
+
1173
+ // src/core/calculations/exponential-backoff.ts
1174
+ function calculateExponentialBackoff(params) {
1175
+ const {
1176
+ attempt,
1177
+ initialDelay,
1178
+ maxDelay,
1179
+ backoffMultiplier,
1180
+ jitterFactor,
1181
+ random = Math.random
1182
+ } = params;
1183
+ const base = initialDelay * Math.pow(backoffMultiplier, Math.max(0, attempt - 1));
1184
+ const capped = Math.min(base, maxDelay);
1185
+ const jitterMultiplier = random() * 2 - 1;
1186
+ const jitter = capped * jitterFactor * jitterMultiplier;
1187
+ return Math.max(0, capped + jitter);
1188
+ }
1189
+
1190
+ // src/core/constants/identifier.constants.ts
1191
+ var QUEUE_PRIORITY_USER_REQUEST = 10;
1192
+ var DEFAULT_RETRY_MAX_ATTEMPTS = 3;
1193
+ var DEFAULT_RETRY_INITIAL_DELAY_MS = 1e3;
1194
+ var DEFAULT_RETRY_MAX_DELAY_MS = 1e4;
1195
+ var DEFAULT_RETRY_BACKOFF_MULTIPLIER = 2;
1196
+ var DEFAULT_RETRY_JITTER_FACTOR = 0.1;
1197
+
1198
+ // src/core/utils/retry.ts
1199
+ var RETRYABLE_MESSAGE_KEYWORDS = [
1200
+ "network",
1201
+ "timeout",
1202
+ "econnrefused",
1203
+ "enotfound",
1204
+ "etimedout"
1205
+ ];
1206
+ var RetryManager = class {
1207
+ defaults;
1208
+ constructor() {
1209
+ this.defaults = {
1210
+ maxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,
1211
+ initialDelay: DEFAULT_RETRY_INITIAL_DELAY_MS,
1212
+ maxDelay: DEFAULT_RETRY_MAX_DELAY_MS,
1213
+ backoffMultiplier: DEFAULT_RETRY_BACKOFF_MULTIPLIER,
1214
+ jitterFactor: DEFAULT_RETRY_JITTER_FACTOR
1215
+ };
1216
+ }
1217
+ async execute(fn, options = {}) {
1218
+ const maxAttempts = options.maxAttempts ?? this.defaults.maxAttempts;
1219
+ let lastError;
1220
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1221
+ try {
1222
+ return await fn();
1223
+ } catch (error) {
1224
+ lastError = error instanceof Error ? error : new Error(String(error));
1225
+ if (attempt >= maxAttempts || !this.shouldRetry(lastError, options)) {
1226
+ throw lastError;
1227
+ }
1228
+ const delay = calculateExponentialBackoff({
1229
+ attempt,
1230
+ initialDelay: options.initialDelay ?? this.defaults.initialDelay,
1231
+ maxDelay: options.maxDelay ?? this.defaults.maxDelay,
1232
+ backoffMultiplier: options.backoffMultiplier ?? this.defaults.backoffMultiplier,
1233
+ jitterFactor: options.jitterFactor ?? this.defaults.jitterFactor
1234
+ });
1235
+ await this.delay(delay);
1236
+ }
1237
+ }
1238
+ throw lastError ?? new Error("Retry loop exited without result");
1239
+ }
1240
+ shouldRetry(error, options) {
1241
+ if (options.shouldRetry) return options.shouldRetry(error);
1242
+ if (error instanceof AIError) {
1243
+ return isRetryableErrorType(error.type, DEFAULT_ERROR_CLASSIFICATION_RULE);
1244
+ }
1245
+ const lower = error.message.toLowerCase();
1246
+ return RETRYABLE_MESSAGE_KEYWORDS.some((kw) => lower.includes(kw));
1247
+ }
1248
+ delay(ms) {
1249
+ return new Promise((resolve) => setTimeout(resolve, ms));
1250
+ }
1251
+ };
1252
+
1253
+ // src/core/utils/request-queue.util.ts
1254
+ var DEFAULT_MAX_CONCURRENT = 3;
1255
+ var DEFAULT_PRIORITY = 0;
1256
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
1257
+ var RequestQueue = class {
1258
+ queue = [];
1259
+ activeRequests = /* @__PURE__ */ new Set();
1260
+ maxConcurrent;
1261
+ defaultPriority;
1262
+ requestTimeout;
1263
+ requestIdCounter = 0;
1264
+ constructor(options = {}) {
1265
+ this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;
1266
+ this.defaultPriority = options.defaultPriority ?? DEFAULT_PRIORITY;
1267
+ this.requestTimeout = options.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT_MS;
1268
+ }
1269
+ add(requestFn, priority) {
1270
+ return new Promise((resolve, reject) => {
1271
+ const id = `req-${++this.requestIdCounter}`;
1272
+ const queuedRequest = {
1273
+ id,
1274
+ priority: priority ?? this.defaultPriority,
1275
+ requestFn,
1276
+ resolve,
1277
+ reject,
1278
+ timestamp: Date.now()
1279
+ };
1280
+ this.queue.push(queuedRequest);
1281
+ this.sortQueue();
1282
+ this.process();
1283
+ });
1284
+ }
1285
+ cancelAll() {
1286
+ for (const request of this.queue) {
1287
+ request.reject(new Error("Request was cancelled"));
1288
+ }
1289
+ this.queue = [];
1290
+ }
1291
+ sortQueue() {
1292
+ this.queue.sort((a, b) => {
1293
+ if (a.priority !== b.priority) {
1294
+ return b.priority - a.priority;
1295
+ }
1296
+ return a.timestamp - b.timestamp;
1297
+ });
1298
+ }
1299
+ process() {
1300
+ while (this.queue.length > 0 && this.activeRequests.size < this.maxConcurrent) {
1301
+ const request = this.queue.shift();
1302
+ if (!request) break;
1303
+ this.executeRequest(request);
1304
+ }
1305
+ }
1306
+ executeRequest(request) {
1307
+ this.activeRequests.add(request.id);
1308
+ const timeoutId = setTimeout(() => {
1309
+ this.activeRequests.delete(request.id);
1310
+ request.reject(new Error(`Request ${request.id} timed out`));
1311
+ this.process();
1312
+ }, this.requestTimeout);
1313
+ request.requestFn().then((result) => {
1314
+ clearTimeout(timeoutId);
1315
+ request.resolve(result);
1316
+ }).catch((error) => {
1317
+ clearTimeout(timeoutId);
1318
+ request.reject(error);
1319
+ }).finally(() => {
1320
+ this.activeRequests.delete(request.id);
1321
+ this.process();
1322
+ });
1323
+ }
1324
+ };
1325
+ new RequestQueue();
1326
+
1327
+ // src/core/utils/request-deduplicator.util.ts
1328
+ var DEFAULT_DEDUPE_TTL_MS = 3e4;
1329
+ var RequestDeduplicator = class {
1330
+ pendingRequests = /* @__PURE__ */ new Map();
1331
+ ttl;
1332
+ constructor(ttl = DEFAULT_DEDUPE_TTL_MS) {
1333
+ this.ttl = ttl;
1334
+ }
1335
+ execute(key, requestFn) {
1336
+ this.cleanup();
1337
+ const existing = this.pendingRequests.get(key);
1338
+ if (existing) {
1339
+ return existing.promise;
1340
+ }
1341
+ const promise = requestFn();
1342
+ this.pendingRequests.set(key, {
1343
+ promise,
1344
+ timestamp: Date.now()
1345
+ });
1346
+ promise.catch(() => void 0).then(() => {
1347
+ this.pendingRequests.delete(key);
1348
+ });
1349
+ return promise;
1350
+ }
1351
+ cancelAll() {
1352
+ this.pendingRequests.clear();
1353
+ }
1354
+ cleanup() {
1355
+ const now = Date.now();
1356
+ for (const [key, request] of this.pendingRequests.entries()) {
1357
+ if (now - request.timestamp > this.ttl) {
1358
+ this.pendingRequests.delete(key);
1359
+ }
1360
+ }
1361
+ }
1362
+ };
1363
+
1364
+ // src/providers/groq/groq.constants.ts
1365
+ var GROQ_MODELS = {
1366
+ LLAMA_3_1_8B_INSTANT: "llama-3.1-8b-instant",
1367
+ LLAMA_3_3_70B_VERSATILE: "llama-3.3-70b-versatile",
1368
+ LLAMA_3_1_70B_VERSATILE: "llama-3.1-70b-versatile",
1369
+ GPT_OSS_20B: "openai/gpt-oss-20b",
1370
+ GPT_OSS_120B: "openai/gpt-oss-120b",
1371
+ MIXTRAL_8X7B: "mixtral-8x7b-32768",
1372
+ GEMMA_2_9B: "gemma2-9b-it",
1373
+ LLAMA_4_SCOUT_17B: "meta-llama/llama-4-scout-17b-16e-instruct",
1374
+ KIMI_K2_INSTRUCT: "moonshotai/kimi-k2-instruct",
1375
+ QWEN3_32B: "qwen/qwen3-32b"
1376
+ };
1377
+ var GROQ_TIERS = {
1378
+ fast: GROQ_MODELS.LLAMA_3_1_8B_INSTANT,
1379
+ balanced: GROQ_MODELS.LLAMA_3_3_70B_VERSATILE,
1380
+ powerful: GROQ_MODELS.GPT_OSS_120B
1381
+ };
1382
+ var DEFAULT_GENERATION_CONFIG = {
1383
+ temperature: 0.7,
1384
+ maxTokens: 1024,
1385
+ topP: 1
1386
+ };
1387
+ var GROQ_BASE_URL = "https://api.groq.com/openai/v1";
1388
+ var CHAT_COMPLETIONS_PATH = "/chat/completions";
1389
+ var GROQ_TIMEOUTS = {
1390
+ DEFAULT: 3e4,
1391
+ STREAMING: 6e4
1392
+ };
1393
+ var HTTP_HEADERS = {
1394
+ CONTENT_TYPE: "Content-Type",
1395
+ APPLICATION_JSON: "application/json",
1396
+ AUTHORIZATION: "Authorization",
1397
+ BEARER_PREFIX: "Bearer "
1398
+ };
1399
+
1400
+ // src/providers/groq/groq-request.builder.ts
1401
+ var GroqChatRequestBuilder = class _GroqChatRequestBuilder {
1402
+ model;
1403
+ messages = [];
1404
+ generationConfig = {};
1405
+ streamEnabled = false;
1406
+ jsonResponse = false;
1407
+ constructor(model) {
1408
+ this.model = model;
1409
+ }
1410
+ static for(model) {
1411
+ return new _GroqChatRequestBuilder(model);
1412
+ }
1413
+ withMessages(messages) {
1414
+ this.messages = [...messages];
1415
+ return this;
1416
+ }
1417
+ withConfig(config) {
1418
+ this.generationConfig = config ? { ...config } : {};
1419
+ return this;
1420
+ }
1421
+ withStream(stream) {
1422
+ this.streamEnabled = stream;
1423
+ return this;
1424
+ }
1425
+ withJsonResponse(enabled) {
1426
+ this.jsonResponse = enabled;
1427
+ return this;
1428
+ }
1429
+ build() {
1430
+ const cfg = this.generationConfig;
1431
+ const request = {
1432
+ model: this.model,
1433
+ messages: this.messages,
1434
+ temperature: cfg.temperature ?? DEFAULT_GENERATION_CONFIG.temperature,
1435
+ max_tokens: cfg.maxTokens ?? DEFAULT_GENERATION_CONFIG.maxTokens,
1436
+ top_p: cfg.topP ?? DEFAULT_GENERATION_CONFIG.topP
1437
+ };
1438
+ if (cfg.n !== void 0) request.n = cfg.n;
1439
+ if (cfg.stop !== void 0) request.stop = cfg.stop;
1440
+ if (cfg.frequencyPenalty !== void 0) request.frequency_penalty = cfg.frequencyPenalty;
1441
+ if (cfg.presencePenalty !== void 0) request.presence_penalty = cfg.presencePenalty;
1442
+ if (cfg.reasoningEffort !== void 0) request.reasoning_effort = cfg.reasoningEffort;
1443
+ if (this.jsonResponse) {
1444
+ request.response_format = { type: "json_object" };
1445
+ }
1446
+ if (this.streamEnabled) request.stream = true;
1447
+ return request;
1448
+ }
1449
+ };
1450
+
1451
+ // src/providers/groq/groq-http-transport.ts
1452
+ var GroqHttpTransport = class {
1453
+ constructor(config) {
1454
+ this.config = config;
1455
+ }
1456
+ config;
1457
+ pendingAbortControllers = /* @__PURE__ */ new Set();
1458
+ cancelPendingRequests() {
1459
+ for (const controller of this.pendingAbortControllers) {
1460
+ controller.abort();
1461
+ }
1462
+ this.pendingAbortControllers.clear();
1463
+ }
1464
+ async postChatCompletion(request) {
1465
+ return this.request(CHAT_COMPLETIONS_PATH, {
1466
+ ...request,
1467
+ stream: false
1468
+ });
1469
+ }
1470
+ async streamChatCompletion(request, options = {}) {
1471
+ const url = `${this.baseUrl()}${CHAT_COMPLETIONS_PATH}`;
1472
+ const timeout = this.config.timeoutMs ?? GROQ_TIMEOUTS.STREAMING;
1473
+ const controller = new AbortController();
1474
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1475
+ const onExternalAbort = () => controller.abort();
1476
+ options.signal?.addEventListener("abort", onExternalAbort);
1477
+ this.pendingAbortControllers.add(controller);
1478
+ try {
1479
+ const response = await fetch(url, {
1480
+ method: "POST",
1481
+ headers: this.buildHeaders(),
1482
+ body: JSON.stringify({ ...request, stream: true }),
1483
+ signal: controller.signal
1484
+ });
1485
+ if (!response.ok) await this.throwFromErrorResponse(response);
1486
+ if (!response.body) {
1487
+ throw new AIError("NETWORK_ERROR" /* NETWORK_ERROR */, "Response body is null");
1488
+ }
1489
+ return response.body;
1490
+ } catch (error) {
1491
+ options.signal?.removeEventListener("abort", onExternalAbort);
1492
+ throw this.normalizeError(error);
1493
+ } finally {
1494
+ clearTimeout(timeoutId);
1495
+ this.pendingAbortControllers.delete(controller);
1496
+ }
1497
+ }
1498
+ baseUrl() {
1499
+ return this.config.baseUrl ?? GROQ_BASE_URL;
1500
+ }
1501
+ async request(endpoint, body) {
1502
+ const url = `${this.baseUrl()}${endpoint}`;
1503
+ const timeout = this.config.timeoutMs ?? GROQ_TIMEOUTS.DEFAULT;
1504
+ const controller = new AbortController();
1505
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1506
+ this.pendingAbortControllers.add(controller);
1507
+ try {
1508
+ const response = await fetch(url, {
1509
+ method: "POST",
1510
+ headers: this.buildHeaders(),
1511
+ body: JSON.stringify(body),
1512
+ signal: controller.signal
1513
+ });
1514
+ if (!response.ok) await this.throwFromErrorResponse(response);
1515
+ return await response.json();
1516
+ } catch (error) {
1517
+ throw this.normalizeError(error);
1518
+ } finally {
1519
+ clearTimeout(timeoutId);
1520
+ this.pendingAbortControllers.delete(controller);
1521
+ }
1522
+ }
1523
+ buildHeaders() {
1524
+ return {
1525
+ [HTTP_HEADERS.CONTENT_TYPE]: HTTP_HEADERS.APPLICATION_JSON,
1526
+ [HTTP_HEADERS.AUTHORIZATION]: `${HTTP_HEADERS.BEARER_PREFIX}${this.config.apiKey}`
1527
+ };
1528
+ }
1529
+ async throwFromErrorResponse(response) {
1530
+ const errorMessage = await extractErrorMessageFromResponse(response);
1531
+ const metadata = {
1532
+ status: response.status,
1533
+ url: response.url
1534
+ };
1535
+ throw new AIError(
1536
+ classifyHttpStatus(response.status),
1537
+ errorMessage,
1538
+ void 0,
1539
+ metadata
1540
+ );
1541
+ }
1542
+ normalizeError(error) {
1543
+ if (error instanceof AIError) return error;
1544
+ if (error instanceof Error) {
1545
+ if (error.name === "AbortError") {
1546
+ return new AIError(
1547
+ "ABORT_ERROR" /* ABORT_ERROR */,
1548
+ "Request was aborted by the client",
1549
+ error
1550
+ );
1551
+ }
1552
+ if (error.name === "TypeError" && error.message.toLowerCase().includes("network")) {
1553
+ return new AIError(
1554
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1555
+ "Network error: Unable to connect to the AI service",
1556
+ error
1557
+ );
1558
+ }
1559
+ }
1560
+ return new AIError(
1561
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
1562
+ error instanceof Error ? error.message : "Unknown error occurred",
1563
+ error instanceof Error ? error : void 0
1564
+ );
1565
+ }
1566
+ };
1567
+
1568
+ // src/core/executor/retry-executor.strategy.ts
1569
+ var RetryExecutor = class {
1570
+ constructor(retryManager2, options) {
1571
+ this.retryManager = retryManager2;
1572
+ this.options = options;
1573
+ }
1574
+ retryManager;
1575
+ options;
1576
+ execute(fn, ...args) {
1577
+ return this.retryManager.execute(() => fn(...args), this.options);
1578
+ }
1579
+ };
1580
+
1581
+ // src/core/executor/queue-executor.strategy.ts
1582
+ var QueueExecutor = class {
1583
+ constructor(queue, priority) {
1584
+ this.queue = queue;
1585
+ this.priority = priority;
1586
+ }
1587
+ queue;
1588
+ priority;
1589
+ execute(fn, ...args) {
1590
+ return this.queue.add(() => fn(...args), this.priority);
1591
+ }
1592
+ };
1593
+
1594
+ // src/core/executor/dedupe-executor.strategy.ts
1595
+ var DedupeExecutor = class {
1596
+ constructor(deduplicator, options) {
1597
+ this.deduplicator = deduplicator;
1598
+ this.options = options;
1599
+ }
1600
+ deduplicator;
1601
+ options;
1602
+ execute(fn, ...args) {
1603
+ const key = this.options.generateKey(...args);
1604
+ return this.deduplicator.execute(key, () => fn(...args));
1605
+ }
1606
+ };
1607
+
1608
+ // src/core/executor/composite-executor.strategy.ts
1609
+ var CompositeExecutor = class {
1610
+ executors;
1611
+ constructor(executors) {
1612
+ this.executors = executors;
1613
+ }
1614
+ execute(fn, ...args) {
1615
+ const composed = this.compress(fn);
1616
+ return composed(...args);
1617
+ }
1618
+ compress(fn) {
1619
+ return this.executors.reduceRight(
1620
+ (innerFn, executor) => (...a) => executor.execute(innerFn, ...a),
1621
+ fn
1622
+ );
1623
+ }
1624
+ };
1625
+
1626
+ // src/providers/groq/groq-http-client.ts
1627
+ var GroqHttpClient = class {
1628
+ transport;
1629
+ executor;
1630
+ constructor(config, deps = {}) {
1631
+ this.transport = deps.transport ?? new GroqHttpTransport(config);
1632
+ const retryManager2 = deps.retryManager ?? new RetryManager();
1633
+ const queue = deps.queue ?? new RequestQueue();
1634
+ const deduplicator = deps.deduplicator ?? new RequestDeduplicator();
1635
+ this.executor = new CompositeExecutor([
1636
+ new DedupeExecutor(deduplicator, {
1637
+ generateKey: (request) => deduplicatorKey(request, config.apiKey)
1638
+ }),
1639
+ new RetryExecutor(retryManager2),
1640
+ new QueueExecutor(queue, QUEUE_PRIORITY_USER_REQUEST)
1641
+ ]);
1642
+ }
1643
+ cancelPendingRequests() {
1644
+ this.transport.cancelPendingRequests();
1645
+ }
1646
+ postChatCompletion(request) {
1647
+ return this.executor.execute(
1648
+ (req) => this.transport.postChatCompletion(req),
1649
+ request
1650
+ );
1651
+ }
1652
+ streamChatCompletion(request, options) {
1653
+ return this.transport.streamChatCompletion(request, options);
1654
+ }
1655
+ };
1656
+ function deduplicatorKey(request, apiKey) {
1657
+ const { model, messages, stream: _stream, ...rest } = request;
1658
+ const stable = JSON.stringify({
1659
+ apiKey,
1660
+ model,
1661
+ messages: messages.map((m) => ({ role: m.role, content: m.content })),
1662
+ ...rest
1663
+ });
1664
+ return stable;
1665
+ }
1666
+
1667
+ // src/providers/groq/groq-sse.ts
1668
+ function extractContentFromSsePayload(payload) {
1669
+ try {
1670
+ const parsed = JSON.parse(payload);
1671
+ const delta = parsed.choices?.[0]?.delta?.content;
1672
+ return typeof delta === "string" && delta.length > 0 ? delta : null;
1673
+ } catch {
1674
+ return null;
1675
+ }
1676
+ }
1677
+ function mapGroqFinishReason(reason) {
1678
+ if (reason === "stop") return "stop";
1679
+ if (reason === "length") return "length";
1680
+ if (reason === "content_filter") return "content_filter";
1681
+ return void 0;
1682
+ }
1683
+ function mapGroqUsage(usage) {
1684
+ if (!usage) return void 0;
1685
+ return {
1686
+ inputTokens: usage.prompt_tokens,
1687
+ outputTokens: usage.completion_tokens,
1688
+ totalTokens: usage.total_tokens
1689
+ };
1690
+ }
1691
+ async function consumeGroqStream(stream, callbacks) {
1692
+ const reader = stream.getReader();
1693
+ const decoder = new TextDecoder();
1694
+ const chunks = [];
1695
+ let buffer = "";
1696
+ let model = null;
1697
+ let finishReason;
1698
+ let usage;
1699
+ const consumeLine = (rawLine) => {
1700
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1701
+ const trimmed = line.trim();
1702
+ if (trimmed.length === 0 || !isSseDataLine(trimmed)) return;
1703
+ const payload = extractSseDataPayload(trimmed);
1704
+ if (isSseDoneMarker(payload)) return;
1705
+ let chunk;
1706
+ try {
1707
+ chunk = JSON.parse(payload);
1708
+ } catch {
1709
+ return;
1710
+ }
1711
+ const errorBody = chunk.error;
1712
+ if (errorBody) {
1713
+ throw new AIError(
1714
+ errorBody.message?.toLowerCase().includes("rate limit") ? "RATE_LIMIT_ERROR" /* RATE_LIMIT_ERROR */ : "SERVER_ERROR" /* SERVER_ERROR */,
1715
+ errorBody.message || "Groq stream failed mid-flight"
1716
+ );
1717
+ }
1718
+ if (chunk.model) model = chunk.model;
1719
+ const choice = chunk.choices?.[0];
1720
+ const delta = choice?.delta?.content;
1721
+ if (typeof delta === "string" && delta.length > 0) {
1722
+ chunks.push(delta);
1723
+ callbacks.onChunk?.(delta);
1724
+ }
1725
+ if (choice?.finish_reason) {
1726
+ finishReason = mapGroqFinishReason(choice.finish_reason);
1727
+ }
1728
+ const tailUsage = chunk.x_groq?.usage;
1729
+ if (tailUsage) {
1730
+ usage = mapGroqUsage(tailUsage);
1731
+ }
1732
+ };
1733
+ try {
1734
+ while (true) {
1735
+ const { done, value } = await reader.read();
1736
+ if (done) break;
1737
+ buffer += decoder.decode(value, { stream: true });
1738
+ const lines = buffer.split("\n");
1739
+ buffer = lines.pop() ?? "";
1740
+ for (const line of lines) consumeLine(line);
1741
+ }
1742
+ buffer += decoder.decode();
1743
+ if (buffer.length > 0) consumeLine(buffer);
1744
+ } catch (error) {
1745
+ if (error instanceof AIError) throw error;
1746
+ throw new AIError(
1747
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1748
+ "Stream was interrupted",
1749
+ error instanceof Error ? error : void 0
1750
+ );
1751
+ } finally {
1752
+ reader.releaseLock();
1753
+ }
1754
+ return { text: chunks.join(""), model, finishReason, usage };
1755
+ }
1756
+
1757
+ // src/providers/groq/groq.provider.ts
1758
+ var CACHE_LAYOUT_VERSION = 2;
1759
+ var STRUCTURED_TEMPERATURE = 0.1;
1760
+ var GroqProvider = class {
1761
+ constructor(config) {
1762
+ this.config = config;
1763
+ this.client = new GroqHttpClient(config);
1764
+ this.tiers = mergeTierOverrides(GROQ_TIERS, config.models);
1765
+ }
1766
+ config;
1767
+ id = "groq";
1768
+ name = "Groq";
1769
+ capabilities = ["text"];
1770
+ client;
1771
+ tiers;
1772
+ cache = new CacheManager();
1773
+ jsonParser = new JsonResponseParser();
1774
+ resolveModel(tier) {
1775
+ return resolveModel(this.tiers, tier, this.id);
1776
+ }
1777
+ async healthCheck() {
1778
+ return this.config.apiKey ? "healthy" : "unavailable";
1779
+ }
1780
+ async estimateCost() {
1781
+ return 0;
1782
+ }
1783
+ async generate(request) {
1784
+ const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
1785
+ const cacheKey = this.cache.generateKey({
1786
+ v: CACHE_LAYOUT_VERSION,
1787
+ provider: this.id,
1788
+ op: "generate",
1789
+ model,
1790
+ messages: request.messages,
1791
+ systemPrompt: request.systemPrompt ?? null,
1792
+ temperature: request.temperature ?? null,
1793
+ maxTokens: request.maxTokens ?? null,
1794
+ topP: request.topP ?? null
1795
+ });
1796
+ const cached = this.cache.get(cacheKey);
1797
+ if (cached) return cached;
1798
+ const response = await this.client.postChatCompletion(
1799
+ this.buildWireRequest(model, request)
1800
+ );
1801
+ const choice = response.choices?.[0];
1802
+ const text = choice?.message?.content ?? "";
1803
+ if (text.length === 0) {
1804
+ throw new AIError(
1805
+ "SERVER_ERROR" /* SERVER_ERROR */,
1806
+ "No content generated from Groq API",
1807
+ void 0,
1808
+ { model }
1809
+ );
1810
+ }
1811
+ const result = {
1812
+ text,
1813
+ usage: mapGroqUsage(response.usage),
1814
+ model: response.model || model,
1815
+ providerId: this.id,
1816
+ finishReason: mapGroqFinishReason(choice?.finish_reason)
1817
+ };
1818
+ this.cache.set(cacheKey, result);
1819
+ return result;
1820
+ }
1821
+ async generateStructured(request) {
1822
+ const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
1823
+ const messages = toGroqMessages(request.messages, request.systemPrompt);
1824
+ const lastUserIndex = findLastIndex2(messages, (m) => m.role === "user");
1825
+ if (lastUserIndex === -1) {
1826
+ throw new AIError(
1827
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
1828
+ "generateStructured requires at least one user message"
1829
+ );
1830
+ }
1831
+ const structuredPrompt = new StructuredPromptBuilder(
1832
+ messages[lastUserIndex].content
1833
+ ).withSchema(request.schema).build();
1834
+ messages[lastUserIndex] = { role: "user", content: structuredPrompt };
1835
+ const wireRequest = GroqChatRequestBuilder.for(model).withMessages(messages).withConfig(this.generationConfig(request, STRUCTURED_TEMPERATURE)).withJsonResponse(true).build();
1836
+ const response = await this.client.postChatCompletion(wireRequest);
1837
+ const choice = response.choices?.[0];
1838
+ const text = choice?.message?.content ?? "";
1839
+ if (text.length === 0) {
1840
+ throw new AIError(
1841
+ "SERVER_ERROR" /* SERVER_ERROR */,
1842
+ "No content generated from Groq API",
1843
+ void 0,
1844
+ { model }
1845
+ );
1846
+ }
1847
+ return {
1848
+ value: this.jsonParser.parse(text),
1849
+ result: {
1850
+ text,
1851
+ usage: mapGroqUsage(response.usage),
1852
+ model: response.model || model,
1853
+ providerId: this.id,
1854
+ finishReason: mapGroqFinishReason(choice?.finish_reason)
1855
+ }
1856
+ };
1857
+ }
1858
+ async stream(request, callbacks) {
1859
+ const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
1860
+ const streamBody = await this.client.streamChatCompletion(
1861
+ this.buildWireRequest(model, request),
1862
+ { signal: request.signal }
1863
+ );
1864
+ try {
1865
+ const outcome = await consumeGroqStream(streamBody, callbacks);
1866
+ if (outcome.text.length === 0) {
1867
+ throw new AIError(
1868
+ "SERVER_ERROR" /* SERVER_ERROR */,
1869
+ "No content generated from Groq API",
1870
+ void 0,
1871
+ { model }
1872
+ );
1873
+ }
1874
+ const result = {
1875
+ text: outcome.text,
1876
+ usage: outcome.usage,
1877
+ model: outcome.model ?? model,
1878
+ providerId: this.id,
1879
+ finishReason: outcome.finishReason
1880
+ };
1881
+ callbacks.onComplete?.(result);
1882
+ return result;
1883
+ } catch (error) {
1884
+ callbacks.onError?.(error instanceof Error ? error : new Error(String(error)));
1885
+ throw error;
1886
+ }
1887
+ }
1888
+ getCacheStats() {
1889
+ return this.cache.getStats();
1890
+ }
1891
+ clearCache() {
1892
+ this.cache.clear();
1893
+ }
1894
+ cancelPendingRequests() {
1895
+ this.client.cancelPendingRequests();
1896
+ }
1897
+ buildWireRequest(model, request) {
1898
+ return GroqChatRequestBuilder.for(model).withMessages(toGroqMessages(request.messages, request.systemPrompt)).withConfig(this.generationConfig(request)).build();
1899
+ }
1900
+ generationConfig(request, temperatureOverride) {
1901
+ return {
1902
+ ...request.temperature !== void 0 ? { temperature: request.temperature } : {},
1903
+ ...temperatureOverride !== void 0 ? { temperature: temperatureOverride } : {},
1904
+ ...request.maxTokens !== void 0 ? { maxTokens: request.maxTokens } : {},
1905
+ ...request.topP !== void 0 ? { topP: request.topP } : {},
1906
+ ...request.stopSequences !== void 0 && request.stopSequences.length > 0 ? { stop: [...request.stopSequences] } : {}
1907
+ };
1908
+ }
1909
+ };
1910
+ function toGroqMessages(messages, systemPrompt) {
1911
+ const wire = [];
1912
+ if (systemPrompt && systemPrompt.length > 0) {
1913
+ wire.push({ role: "system", content: systemPrompt });
1914
+ }
1915
+ for (const message of messages) {
1916
+ if (message.role === "system") {
1917
+ wire.push({ role: "system", content: message.content });
1918
+ continue;
1919
+ }
1920
+ wire.push({ role: message.role, content: message.content });
1921
+ }
1922
+ return wire;
1923
+ }
1924
+ function findLastIndex2(items, predicate) {
1925
+ for (let i = items.length - 1; i >= 0; i--) {
1926
+ if (predicate(items[i])) return i;
1927
+ }
1928
+ return -1;
1929
+ }
1930
+
1931
+ // src/content/domain/predicates/ProviderCostEstimator.ts
1932
+ var FAL_FIXED_COST = 1;
1933
+ var GEMINI_IMAGE_COST = 0.02;
1934
+ var GEMINI_TEXT_PER_1K_CHARS_COST = 1e-4;
1935
+ function estimateFalGenerationCost(_request) {
1936
+ return FAL_FIXED_COST;
1937
+ }
1938
+ function estimateGeminiGenerationCost(request) {
1939
+ if (request.type === "image") return GEMINI_IMAGE_COST;
1940
+ return GEMINI_TEXT_PER_1K_CHARS_COST;
1941
+ }
1942
+
1943
+ // src/content/domain/limits/ModelDefaults.ts
1944
+ var ModelDefaults = {
1945
+ FAL_IMAGE: "fal-ai/flux/schnell",
1946
+ FAL_VIDEO: "fal-ai/hunyuan-video/1",
1947
+ FAL_IMAGE_TO_VIDEO: "fal-ai/fast-animatediff/image-to-video",
1948
+ GEMINI_TEXT: "gemini-2.0-flash",
1949
+ GEMINI_IMAGE: "imagen-4.0-generate-001"};
1950
+
1951
+ // src/providers/gemini/gemini.provider.ts
1952
+ var GEMINI_TIERS = {
1953
+ fast: "gemini-2.0-flash-lite",
1954
+ balanced: ModelDefaults.GEMINI_TEXT,
1955
+ powerful: "gemini-2.5-pro"
1956
+ };
1957
+ var GeminiProvider = class extends BaseProvider {
1958
+ id = "gemini";
1959
+ name = "Google Gemini";
1960
+ capabilities = ["text", "image"];
1961
+ models;
1962
+ tiers;
1963
+ jsonParser = new JsonResponseParser();
1964
+ constructor(config) {
1965
+ super({
1966
+ apiKey: config.apiKey,
1967
+ baseUrl: config.baseUrl || "https://generativelanguage.googleapis.com/v1beta",
1968
+ timeout: config.timeout || ProviderTimingConfig.GEMINI_TIMEOUT_MS,
1969
+ retryAttempts: config.retryAttempts || ProviderTimingConfig.GEMINI_RETRY_ATTEMPTS
1970
+ });
1971
+ this.models = {
1972
+ text: ModelDefaults.GEMINI_TEXT,
1973
+ image: ModelDefaults.GEMINI_IMAGE
1974
+ };
1975
+ if (config.models) {
1976
+ this.models = { ...this.models, ...config.models };
1977
+ }
1978
+ this.tiers = mergeTierOverrides(
1979
+ GEMINI_TIERS,
1980
+ config.models ? { balanced: config.models.text } : void 0
1981
+ );
1982
+ }
1983
+ resolveModel(tier) {
1984
+ return resolveModel(this.tiers, tier, this.id);
1985
+ }
1986
+ async healthCheck() {
1987
+ try {
1988
+ if (!this.config.apiKey) {
1989
+ return "unavailable";
1990
+ }
1991
+ const response = await this.fetchWithTimeout(
1992
+ `${this.config.baseUrl}/models`,
1993
+ {
1994
+ method: "GET",
1995
+ headers: this.authHeaders()
1996
+ }
1997
+ );
1998
+ if (response.ok) return "healthy";
1999
+ if (response.status === 401 || response.status === 403) return "unavailable";
2000
+ return "degraded";
2001
+ } catch {
2002
+ return "unavailable";
2003
+ }
2004
+ }
2005
+ async estimateCost(request) {
2006
+ return estimateGeminiGenerationCost(request);
2007
+ }
2008
+ async generate(request) {
2009
+ try {
2010
+ const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
2011
+ const systemMessages = request.messages.filter((m) => m.role === "system");
2012
+ const systemPrompt = request.systemPrompt && request.systemPrompt.length > 0 ? request.systemPrompt : systemMessages.length > 0 ? systemMessages.map((m) => m.content).join("\n") : void 0;
2013
+ const response = await this.withRetry(async () => {
2014
+ return await this.fetchWithTimeout(
2015
+ `${this.config.baseUrl}/models/${model}:generateContent`,
2016
+ {
2017
+ method: "POST",
2018
+ headers: this.authHeaders(),
2019
+ body: JSON.stringify({
2020
+ systemInstruction: systemPrompt && systemPrompt.length > 0 ? { parts: [{ text: systemPrompt }] } : void 0,
2021
+ contents: toGeminiContents(request.messages),
2022
+ generationConfig: {
2023
+ temperature: request.temperature ?? 0.7,
2024
+ maxOutputTokens: request.maxTokens ?? 2048,
2025
+ topP: request.topP ?? 0.9
2026
+ }
2027
+ })
2028
+ }
2029
+ );
2030
+ });
2031
+ if (!response.ok) {
2032
+ const message = await extractErrorMessageFromResponse(response);
2033
+ throw new AIError(
2034
+ classifyHttpStatus(response.status),
2035
+ `Gemini API error (${response.status}): ${message}`,
2036
+ void 0,
2037
+ { status: response.status, model }
2038
+ );
2039
+ }
2040
+ const data = await response.json();
2041
+ const text = data.candidates?.[0]?.content?.parts?.map((part) => part.text ?? "").join("") ?? "";
2042
+ if (text.length === 0) {
2043
+ throw new AIError("SERVER_ERROR" /* SERVER_ERROR */, "No content generated from Gemini API", void 0, { model });
2044
+ }
2045
+ return {
2046
+ text,
2047
+ usage: data.usageMetadata ? {
2048
+ inputTokens: data.usageMetadata.promptTokenCount,
2049
+ outputTokens: data.usageMetadata.candidatesTokenCount,
2050
+ totalTokens: data.usageMetadata.totalTokenCount
2051
+ } : void 0,
2052
+ model,
2053
+ providerId: this.id,
2054
+ finishReason: mapGeminiFinishReason(data.candidates?.[0]?.finishReason)
2055
+ };
2056
+ } catch (error) {
2057
+ if (error instanceof AIError) throw error;
2058
+ throw new AIError(
2059
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
2060
+ `Gemini text generation failed: ${error instanceof Error ? error.message : "Unknown error"}`,
2061
+ error instanceof Error ? error : void 0
2062
+ );
2063
+ }
2064
+ }
2065
+ async generateStructured(request) {
2066
+ const messages = [...request.messages];
2067
+ const lastUserIndex = findLastIndex3(messages, (m) => m.role === "user");
2068
+ if (lastUserIndex === -1) {
2069
+ throw new AIError(
2070
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
2071
+ "generateStructured requires at least one user message"
2072
+ );
2073
+ }
2074
+ messages[lastUserIndex] = {
2075
+ role: "user",
2076
+ content: new StructuredPromptBuilder(messages[lastUserIndex].content).withSchema(request.schema).build()
2077
+ };
2078
+ const result = await this.generate({ ...request, messages, temperature: 0.1 });
2079
+ return { value: this.jsonParser.parse(result.text), result };
2080
+ }
2081
+ async stream(request, callbacks) {
2082
+ const result = await this.generate(request);
2083
+ callbacks.onChunk?.(result.text);
2084
+ callbacks.onComplete?.(result);
2085
+ return result;
2086
+ }
2087
+ async generateImage(request) {
2088
+ try {
2089
+ const response = await this.withRetry(async () => {
2090
+ return await this.fetchWithTimeout(
2091
+ `${this.config.baseUrl}/models/${this.models.image}:generateContent`,
2092
+ {
2093
+ method: "POST",
2094
+ headers: this.authHeaders(),
2095
+ body: JSON.stringify({
2096
+ contents: [{
2097
+ parts: [{
2098
+ text: this.buildImagePrompt(request)
2099
+ }]
2100
+ }]
2101
+ })
2102
+ }
2103
+ );
2104
+ });
2105
+ if (!response.ok) {
2106
+ const message = await extractErrorMessageFromResponse(response);
2107
+ throw new AIError(
2108
+ classifyHttpStatus(response.status),
2109
+ `Gemini image generation error (${response.status}): ${message}`,
2110
+ void 0,
2111
+ { status: response.status }
2112
+ );
2113
+ }
2114
+ const data = await response.json();
2115
+ const imageData = data.candidates?.[0]?.content?.parts?.[0]?.inlineData;
2116
+ if (!imageData) {
2117
+ throw new AIError("SERVER_ERROR" /* SERVER_ERROR */, "No image data in Gemini response");
2118
+ }
2119
+ const url = `data:${imageData.mimeType};base64,${imageData.data}`;
2120
+ return {
2121
+ id: Date.now().toString(),
2122
+ type: "image",
2123
+ url,
2124
+ metadata: {
2125
+ provider: "gemini",
2126
+ model: this.models.image,
2127
+ mimeType: imageData.mimeType
2128
+ },
2129
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2130
+ };
2131
+ } catch (error) {
2132
+ throw new Error(`Gemini image generation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
2133
+ }
2134
+ }
2135
+ async generateVideo(_request) {
2136
+ throw new Error("Gemini provider does not support video generation");
2137
+ }
2138
+ async imageToVideo(_request) {
2139
+ throw new Error("Gemini provider does not support image-to-video conversion");
2140
+ }
2141
+ async videoToVideo(_request) {
2142
+ throw new Error("Gemini provider does not support video-to-video conversion");
2143
+ }
2144
+ authHeaders() {
2145
+ return {
2146
+ "Content-Type": "application/json",
2147
+ "x-goog-api-key": this.config.apiKey
2148
+ };
2149
+ }
2150
+ buildImagePrompt(request) {
2151
+ let prompt = request.prompt;
2152
+ if (request.style) {
2153
+ const styles = {
2154
+ realistic: "photorealistic, highly detailed, 8k resolution",
2155
+ cartoon: "cartoon style, colorful, animated",
2156
+ abstract: "abstract art, modern, artistic",
2157
+ minimalist: "minimalist, clean, simple",
2158
+ vintage: "vintage style, retro, classic"
2159
+ };
2160
+ prompt += `, ${styles[request.style]}`;
2161
+ }
2162
+ if (request.quality === "ultra") {
2163
+ prompt += ", ultra high quality, masterpiece";
2164
+ }
2165
+ return prompt;
2166
+ }
2167
+ };
2168
+ function toGeminiContents(messages) {
2169
+ return messages.filter((message) => message.role !== "system" && message.content.length > 0).map((message) => ({
2170
+ role: message.role === "assistant" ? "model" : "user",
2171
+ parts: [{ text: message.content }]
2172
+ }));
2173
+ }
2174
+ function mapGeminiFinishReason(reason) {
2175
+ if (reason === "STOP") return "stop";
2176
+ if (reason === "MAX_TOKENS") return "length";
2177
+ if (reason === "SAFETY" || reason === "PROHIBITED_CONTENT") return "content_filter";
2178
+ return void 0;
2179
+ }
2180
+ function findLastIndex3(items, predicate) {
2181
+ for (let i = items.length - 1; i >= 0; i--) {
2182
+ if (predicate(items[i])) return i;
2183
+ }
2184
+ return -1;
2185
+ }
2186
+ function createGeminiProvider(config) {
2187
+ return new GeminiProvider(config);
2188
+ }
2189
+
2190
+ // src/content/domain/predicates/FalImageRenderingOptions.ts
2191
+ var FAL_FORMAT_TO_IMAGE_SIZE = {
2192
+ square: "square_hd",
2193
+ landscape: "landscape_16_9",
2194
+ portrait: "portrait_9_16",
2195
+ story: "portrait_9_16",
2196
+ banner: "landscape_16_9"
2197
+ };
2198
+ var FAL_DEFAULT_IMAGE_SIZE = "square_hd";
2199
+ var FAL_QUALITY_TO_STEPS = {
2200
+ standard: 4,
2201
+ high: 6,
2202
+ ultra: 8
2203
+ };
2204
+ var FAL_DEFAULT_QUALITY_STEPS = 6;
2205
+ function resolveFalImageSize(format) {
2206
+ if (!format) return FAL_DEFAULT_IMAGE_SIZE;
2207
+ return FAL_FORMAT_TO_IMAGE_SIZE[format] ?? FAL_DEFAULT_IMAGE_SIZE;
2208
+ }
2209
+ function resolveFalInferenceSteps(quality) {
2210
+ if (!quality) return FAL_DEFAULT_QUALITY_STEPS;
2211
+ return FAL_QUALITY_TO_STEPS[quality] ?? FAL_DEFAULT_QUALITY_STEPS;
2212
+ }
2213
+
2214
+ // src/providers/fal/fal.provider.ts
2215
+ var FalProvider = class extends BaseProvider {
2216
+ id = "fal";
2217
+ name = "FAL";
2218
+ capabilities = ["image", "video"];
2219
+ models;
2220
+ constructor(config) {
2221
+ super({
2222
+ apiKey: config.apiKey,
2223
+ baseUrl: config.baseUrl || "https://queue.fal.run",
2224
+ timeout: config.timeout || ProviderTimingConfig.FAL_TIMEOUT_MS,
2225
+ retryAttempts: config.retryAttempts || ProviderTimingConfig.FAL_RETRY_ATTEMPTS
2226
+ });
2227
+ this.models = {
2228
+ image: ModelDefaults.FAL_IMAGE,
2229
+ video: ModelDefaults.FAL_VIDEO,
2230
+ imageToVideo: ModelDefaults.FAL_IMAGE_TO_VIDEO
2231
+ };
2232
+ if (config.models) {
2233
+ this.models = { ...this.models, ...config.models };
2234
+ }
2235
+ }
2236
+ async healthCheck() {
2237
+ try {
2238
+ if (!this.config.apiKey) {
2239
+ return "unavailable";
2240
+ }
2241
+ const response = await this.fetchWithTimeout(
2242
+ `${this.config.baseUrl}/fal-ai/flux/schnell/status`,
2243
+ {
2244
+ method: "HEAD",
2245
+ headers: {
2246
+ "Authorization": `Key ${this.config.apiKey}`
2247
+ }
2248
+ }
2249
+ );
2250
+ return response.ok ? "healthy" : "degraded";
2251
+ } catch {
2252
+ return "unavailable";
2253
+ }
2254
+ }
2255
+ async estimateCost(request) {
2256
+ return estimateFalGenerationCost();
2257
+ }
2258
+ async generateImage(request) {
2259
+ try {
2260
+ const response = await this.withRetry(async () => {
2261
+ return await this.fetchWithTimeout(
2262
+ `${this.config.baseUrl}/${this.models.image}`,
2263
+ {
2264
+ method: "POST",
2265
+ headers: {
2266
+ "Authorization": `Key ${this.config.apiKey}`,
2267
+ "Content-Type": "application/json"
2268
+ },
2269
+ body: JSON.stringify({
2270
+ prompt: request.prompt,
2271
+ image_size: resolveFalImageSize(request.format),
2272
+ num_inference_steps: resolveFalInferenceSteps(request.quality),
2273
+ num_images: request.quantity || 1
2274
+ })
2275
+ }
2276
+ );
2277
+ });
2278
+ if (!response.ok) {
2279
+ throw new Error(`FAL API error: ${response.statusText}`);
2280
+ }
2281
+ const data = await response.json();
2282
+ if (data.error) {
2283
+ throw new Error(data.error);
2284
+ }
2285
+ return {
2286
+ id: Date.now().toString(),
2287
+ type: "image",
2288
+ url: data.images?.[0]?.url,
2289
+ metadata: {
2290
+ provider: "fal",
2291
+ model: this.models.image
2292
+ },
2293
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2294
+ };
2295
+ } catch (error) {
2296
+ throw new Error(`FAL image generation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
2297
+ }
2298
+ }
2299
+ async generateVideo(request) {
2300
+ try {
2301
+ const response = await this.withRetry(async () => {
2302
+ return await this.fetchWithTimeout(
2303
+ `${this.config.baseUrl}/${this.models.video}`,
2304
+ {
2305
+ method: "POST",
2306
+ headers: {
2307
+ "Authorization": `Key ${this.config.apiKey}`,
2308
+ "Content-Type": "application/json"
2309
+ },
2310
+ body: JSON.stringify({
2311
+ prompt: request.prompt,
2312
+ aspect_ratio: request.aspectRatio || "16:9"
2313
+ })
2314
+ }
2315
+ );
2316
+ });
2317
+ if (!response.ok) {
2318
+ throw new Error(`FAL API error: ${response.statusText}`);
2319
+ }
2320
+ const data = await response.json();
2321
+ if (data.error) {
2322
+ throw new Error(data.error);
2323
+ }
2324
+ return {
2325
+ id: Date.now().toString(),
2326
+ type: "video",
2327
+ url: data.video?.url,
2328
+ metadata: {
2329
+ provider: "fal",
2330
+ model: this.models.video
2331
+ },
2332
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2333
+ };
2334
+ } catch (error) {
2335
+ throw new Error(`FAL video generation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
2336
+ }
2337
+ }
2338
+ async imageToVideo(request) {
2339
+ try {
2340
+ const response = await this.withRetry(async () => {
2341
+ return await this.fetchWithTimeout(
2342
+ `${this.config.baseUrl}/${this.models.imageToVideo}`,
2343
+ {
2344
+ method: "POST",
2345
+ headers: {
2346
+ "Authorization": `Key ${this.config.apiKey}`,
2347
+ "Content-Type": "application/json"
2348
+ },
2349
+ body: JSON.stringify({
2350
+ image_url: request.imageUrl,
2351
+ motion: request.motion || "medium",
2352
+ prompt: request.prompt
2353
+ })
2354
+ }
2355
+ );
2356
+ });
2357
+ if (!response.ok) {
2358
+ throw new Error(`FAL API error: ${response.statusText}`);
2359
+ }
2360
+ const data = await response.json();
2361
+ if (data.error) {
2362
+ throw new Error(data.error);
2363
+ }
2364
+ return {
2365
+ id: Date.now().toString(),
2366
+ type: "video",
2367
+ url: data.video?.url,
2368
+ metadata: {
2369
+ provider: "fal",
2370
+ model: this.models.imageToVideo
2371
+ },
2372
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2373
+ };
2374
+ } catch (error) {
2375
+ throw new Error(`FAL image-to-video failed: ${error instanceof Error ? error.message : "Unknown error"}`);
2376
+ }
2377
+ }
2378
+ async videoToVideo(_request) {
2379
+ throw new Error("FAL provider does not support video-to-video conversion");
2380
+ }
2381
+ };
2382
+ function createFalProvider(config) {
2383
+ return new FalProvider(config);
2384
+ }
2385
+
2386
+ // src/providers/pruna/pruna-generate.ts
2387
+ var prunaCorePromise = null;
2388
+ async function loadPrunaCore() {
2389
+ if (!prunaCorePromise) {
2390
+ const specifier = "@umituz/pruna-provider/core";
2391
+ prunaCorePromise = import(specifier);
2392
+ }
2393
+ return prunaCorePromise;
2394
+ }
2395
+ async function* generateWithPruna(request, apiKey, signal, onProgress) {
2396
+ const prunaCore = await loadPrunaCore();
2397
+ if (prunaCore.generateWithPruna) {
2398
+ yield* prunaCore.generateWithPruna(request, apiKey, signal, onProgress);
2399
+ return;
2400
+ }
2401
+ if (!prunaCore.submitPrediction || !prunaCore.pollForResult) {
2402
+ throw new Error("@umituz/pruna-provider/core does not export required functions");
2403
+ }
2404
+ const modelId = request.model || (request.image ? "p-image-edit" : "p-image");
2405
+ const prediction = await prunaCore.submitPrediction(modelId, request, apiKey, signal, onProgress);
2406
+ if (prediction.output && typeof prediction.output === "object" && "url" in prediction.output) {
2407
+ yield {
2408
+ stage: "predicting",
2409
+ result: { url: prediction.output.url, model: modelId }
2410
+ };
2411
+ return;
2412
+ }
2413
+ const pollUrl = prediction.status_url || prediction.generation_url;
2414
+ if (!pollUrl) {
2415
+ throw new Error("Pruna prediction response missing polling URL");
2416
+ }
2417
+ const resultUrl = await prunaCore.pollForResult(pollUrl, apiKey, 60, 2e3, signal, onProgress);
2418
+ yield { stage: "polling", result: { url: resultUrl, model: modelId } };
2419
+ }
2420
+
2421
+ // src/providers/pruna/pruna.provider.ts
2422
+ var PrunaProvider = class {
2423
+ constructor(config) {
2424
+ this.config = config;
2425
+ }
2426
+ config;
2427
+ id = "pruna";
2428
+ name = "Pruna AI";
2429
+ capabilities = ["image", "video"];
2430
+ async healthCheck() {
2431
+ return this.config.apiKey ? "healthy" : "unavailable";
2432
+ }
2433
+ async estimateCost(_request) {
2434
+ return 1;
2435
+ }
2436
+ async generateImage(request) {
2437
+ let finalUrl;
2438
+ const model = this.config.models?.textToImage;
2439
+ for await (const stage of generateWithPruna(
2440
+ { prompt: request.prompt, model, quality: request.quality },
2441
+ this.config.apiKey
2442
+ )) {
2443
+ if (stage.error) throw stage.error;
2444
+ if (stage.result?.url) finalUrl = stage.result.url;
2445
+ }
2446
+ if (!finalUrl) {
2447
+ throw new AIError("SERVER_ERROR" /* SERVER_ERROR */, "No image generated by Pruna AI");
2448
+ }
2449
+ return {
2450
+ id: Date.now().toString(),
2451
+ type: "image",
2452
+ url: finalUrl,
2453
+ metadata: { provider: this.id, model: model ?? "p-image" },
2454
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2455
+ };
2456
+ }
2457
+ async generateVideo(request) {
2458
+ let finalUrl;
2459
+ const model = this.config.models?.textToVideo;
2460
+ for await (const stage of generateWithPruna(
2461
+ { prompt: request.prompt, model, duration: request.duration, aspectRatio: request.aspectRatio },
2462
+ this.config.apiKey
2463
+ )) {
2464
+ if (stage.error) throw stage.error;
2465
+ if (stage.result?.url) finalUrl = stage.result.url;
2466
+ }
2467
+ if (!finalUrl) {
2468
+ throw new AIError("SERVER_ERROR" /* SERVER_ERROR */, "No video generated by Pruna AI");
2469
+ }
2470
+ return {
2471
+ id: Date.now().toString(),
2472
+ type: "video",
2473
+ url: finalUrl,
2474
+ metadata: { provider: this.id, model: model ?? "p-video" },
2475
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2476
+ };
2477
+ }
2478
+ async imageToVideo(request) {
2479
+ let finalUrl;
2480
+ for await (const stage of generateWithPruna(
2481
+ { image: request.imageUrl, prompt: request.prompt, duration: request.duration, motion: request.motion },
2482
+ this.config.apiKey
2483
+ )) {
2484
+ if (stage.error) throw stage.error;
2485
+ if (stage.result?.url) finalUrl = stage.result.url;
2486
+ }
2487
+ if (!finalUrl) {
2488
+ throw new AIError("SERVER_ERROR" /* SERVER_ERROR */, "No video generated from image by Pruna AI");
2489
+ }
2490
+ return {
2491
+ id: Date.now().toString(),
2492
+ type: "video",
2493
+ url: finalUrl,
2494
+ metadata: { provider: this.id, model: "p-image-to-video" },
2495
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2496
+ };
2497
+ }
2498
+ async videoToVideo(_request) {
2499
+ throw new AIError("CLIENT_ERROR" /* CLIENT_ERROR */, "Pruna AI provider does not support video-to-video conversion");
2500
+ }
2501
+ };
2502
+ function createPrunaProvider(config) {
2503
+ return new PrunaProvider(config);
2504
+ }
2505
+
2506
+ // src/providers/factory/create-ai.ts
2507
+ function createAI(config = {}) {
2508
+ const factory = new ProviderFactory({
2509
+ priority: config.priority,
2510
+ fallbackEnabled: config.fallbackEnabled,
2511
+ defaultTier: config.defaultTier
2512
+ });
2513
+ if (config.anthropic?.apiKey) {
2514
+ factory.register(new AnthropicProvider(config.anthropic));
2515
+ }
2516
+ if (config.groq?.apiKey) {
2517
+ factory.register(new GroqProvider(config.groq));
2518
+ }
2519
+ if (config.gemini?.apiKey) {
2520
+ factory.register(new GeminiProvider({ ...config.gemini, enabled: true }));
2521
+ }
2522
+ if (config.fal?.apiKey) {
2523
+ factory.register(new FalProvider({ ...config.fal, enabled: true }));
2524
+ }
2525
+ if (config.pruna?.apiKey) {
2526
+ factory.register(new PrunaProvider({ ...config.pruna, enabled: true }));
2527
+ }
2528
+ return factory;
2529
+ }
2530
+
2531
+ export { ANTHROPIC_API_VERSION, ANTHROPIC_DEFAULT_MAX_TOKENS, ANTHROPIC_MODELS, ANTHROPIC_TIERS, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, BaseProvider, FalProvider, GEMINI_TIERS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GroqChatRequestBuilder, GroqHttpClient, GroqHttpTransport, GroqProvider, ProviderError, ProviderFactory, PrunaProvider, consumeAnthropicStream, consumeGroqStream, createAI, createFalProvider, createGeminiProvider, createPrunaProvider, defaultEffortForModel, extractContentFromSsePayload, generateWithPruna, isMediaProvider, isTextProvider, mapAnthropicStopReason, toGroqMessages };
2532
+ //# sourceMappingURL=index.js.map
2533
+ //# sourceMappingURL=index.js.map