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