risicare 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +26 -10
  2. package/dist/frameworks/instructor.cjs.map +1 -1
  3. package/dist/frameworks/instructor.js.map +1 -1
  4. package/dist/frameworks/langchain.cjs.map +1 -1
  5. package/dist/frameworks/langchain.js.map +1 -1
  6. package/dist/frameworks/langgraph.cjs.map +1 -1
  7. package/dist/frameworks/langgraph.js.map +1 -1
  8. package/dist/frameworks/llamaindex.cjs.map +1 -1
  9. package/dist/frameworks/llamaindex.js.map +1 -1
  10. package/dist/index.cjs +212 -8
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +162 -6
  13. package/dist/index.d.ts +162 -6
  14. package/dist/index.js +209 -8
  15. package/dist/index.js.map +1 -1
  16. package/dist/providers/anthropic/index.cjs.map +1 -1
  17. package/dist/providers/anthropic/index.js.map +1 -1
  18. package/dist/providers/bedrock/index.cjs.map +1 -1
  19. package/dist/providers/bedrock/index.js.map +1 -1
  20. package/dist/providers/cerebras/index.cjs.map +1 -1
  21. package/dist/providers/cerebras/index.js.map +1 -1
  22. package/dist/providers/cohere/index.cjs.map +1 -1
  23. package/dist/providers/cohere/index.js.map +1 -1
  24. package/dist/providers/google/index.cjs.map +1 -1
  25. package/dist/providers/google/index.js.map +1 -1
  26. package/dist/providers/groq/index.cjs.map +1 -1
  27. package/dist/providers/groq/index.js.map +1 -1
  28. package/dist/providers/huggingface/index.cjs.map +1 -1
  29. package/dist/providers/huggingface/index.js.map +1 -1
  30. package/dist/providers/mistral/index.cjs.map +1 -1
  31. package/dist/providers/mistral/index.js.map +1 -1
  32. package/dist/providers/ollama/index.cjs.map +1 -1
  33. package/dist/providers/ollama/index.js.map +1 -1
  34. package/dist/providers/openai/index.cjs +16 -1327
  35. package/dist/providers/openai/index.cjs.map +1 -1
  36. package/dist/providers/openai/index.js +16 -1343
  37. package/dist/providers/openai/index.js.map +1 -1
  38. package/dist/providers/together/index.cjs.map +1 -1
  39. package/dist/providers/together/index.js.map +1 -1
  40. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  41. package/dist/providers/vercel-ai/index.js.map +1 -1
  42. package/package.json +5 -4
@@ -50,10 +50,6 @@ function debug(msg) {
50
50
  `);
51
51
  }
52
52
  }
53
- function warn(msg) {
54
- process.stderr.write(`[risicare] WARNING: ${msg}
55
- `);
56
- }
57
53
  var init_log = __esm({
58
54
  "src/utils/log.ts"() {
59
55
  "use strict";
@@ -61,1327 +57,6 @@ var init_log = __esm({
61
57
  }
62
58
  });
63
59
 
64
- // src/runtime/config.ts
65
- function resolveFixRuntimeConfig(config) {
66
- return {
67
- apiEndpoint: config.apiEndpoint,
68
- apiKey: config.apiKey,
69
- enabled: config.enabled ?? true,
70
- cacheEnabled: config.cacheEnabled ?? true,
71
- cacheTtlMs: config.cacheTtlMs ?? 3e5,
72
- cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
73
- autoRefresh: config.autoRefresh ?? true,
74
- refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
75
- dryRun: config.dryRun ?? false,
76
- abTestingEnabled: config.abTestingEnabled ?? true,
77
- timeoutMs: config.timeoutMs ?? 1e3,
78
- debug: config.debug ?? false
79
- };
80
- }
81
- function matchesError(fix, errorCode) {
82
- if (fix.errorCode === errorCode) {
83
- return true;
84
- }
85
- if (fix.errorCode.endsWith("*")) {
86
- const prefix = fix.errorCode.slice(0, -1);
87
- return errorCode.startsWith(prefix);
88
- }
89
- return false;
90
- }
91
- function shouldApply(fix, sessionHash) {
92
- if (fix.trafficPercentage >= 100) return true;
93
- if (fix.trafficPercentage <= 0) return false;
94
- const bucket = sessionHash % 100;
95
- return bucket < fix.trafficPercentage;
96
- }
97
- function activeFixFromApiResponse(item) {
98
- return {
99
- fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
100
- deploymentId: item.deployment_id ?? item.deploymentId ?? "",
101
- errorCode: item.error_code ?? item.errorCode ?? "",
102
- fixType: item.fix_type ?? item.fixType ?? "prompt",
103
- config: item.config ?? {},
104
- trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
105
- version: item.version ?? 1
106
- };
107
- }
108
- var init_config = __esm({
109
- "src/runtime/config.ts"() {
110
- "use strict";
111
- }
112
- });
113
-
114
- // src/runtime/cache.ts
115
- var FixCache;
116
- var init_cache = __esm({
117
- "src/runtime/cache.ts"() {
118
- "use strict";
119
- init_config();
120
- init_log();
121
- FixCache = class {
122
- _ttlMs;
123
- _maxEntries;
124
- _enabled;
125
- _cache;
126
- _stats;
127
- constructor(config) {
128
- this._enabled = config?.cacheEnabled ?? true;
129
- this._ttlMs = config?.cacheTtlMs ?? 3e5;
130
- this._maxEntries = config?.cacheMaxEntries ?? 1e3;
131
- this._cache = /* @__PURE__ */ new Map();
132
- this._stats = {
133
- hits: 0,
134
- misses: 0,
135
- evictions: 0,
136
- size: 0,
137
- lastRefresh: null
138
- };
139
- }
140
- /** Whether caching is enabled. */
141
- get enabled() {
142
- return this._enabled;
143
- }
144
- /**
145
- * Get a fix by error code.
146
- *
147
- * Checks exact match first, then scans for wildcard matches.
148
- * Expired entries are evicted on access.
149
- */
150
- get(errorCode) {
151
- try {
152
- if (!this._enabled) return null;
153
- const now = Date.now();
154
- const exactEntry = this._cache.get(errorCode);
155
- if (exactEntry) {
156
- if (exactEntry.expiresAt > now) {
157
- this._stats.hits++;
158
- return exactEntry.fix;
159
- }
160
- this._cache.delete(errorCode);
161
- this._stats.evictions++;
162
- }
163
- for (const [key, entry] of this._cache) {
164
- if (entry.expiresAt <= now) {
165
- this._cache.delete(key);
166
- this._stats.evictions++;
167
- continue;
168
- }
169
- if (matchesError(entry.fix, errorCode)) {
170
- this._stats.hits++;
171
- return entry.fix;
172
- }
173
- }
174
- this._stats.misses++;
175
- return null;
176
- } catch (e) {
177
- debug(`FixCache.get error: ${e}`);
178
- return null;
179
- }
180
- }
181
- /**
182
- * Add a single fix to the cache.
183
- *
184
- * Evicts the oldest entry if at capacity.
185
- */
186
- set(fix) {
187
- try {
188
- if (!this._enabled) return;
189
- if (this._cache.size >= this._maxEntries) {
190
- this._evictOldest();
191
- }
192
- const now = Date.now();
193
- this._cache.set(fix.errorCode, {
194
- fix,
195
- createdAt: now,
196
- expiresAt: now + this._ttlMs
197
- });
198
- this._stats.size = this._cache.size;
199
- } catch (e) {
200
- debug(`FixCache.set error: ${e}`);
201
- }
202
- }
203
- /**
204
- * Replace all cached fixes (bulk refresh).
205
- *
206
- * Clears the cache and populates with the given fixes.
207
- */
208
- setAll(fixes) {
209
- try {
210
- if (!this._enabled) return;
211
- this._cache.clear();
212
- const now = Date.now();
213
- for (const fix of fixes) {
214
- if (this._cache.size >= this._maxEntries) break;
215
- this._cache.set(fix.errorCode, {
216
- fix,
217
- createdAt: now,
218
- expiresAt: now + this._ttlMs
219
- });
220
- }
221
- this._stats.size = this._cache.size;
222
- this._stats.lastRefresh = now;
223
- } catch (e) {
224
- debug(`FixCache.setAll error: ${e}`);
225
- }
226
- }
227
- /**
228
- * Get all non-expired fixes.
229
- */
230
- getAll() {
231
- try {
232
- const now = Date.now();
233
- const valid = [];
234
- const expired = [];
235
- for (const [key, entry] of this._cache) {
236
- if (entry.expiresAt > now) {
237
- valid.push(entry.fix);
238
- } else {
239
- expired.push(key);
240
- }
241
- }
242
- for (const key of expired) {
243
- this._cache.delete(key);
244
- this._stats.evictions++;
245
- }
246
- this._stats.size = this._cache.size;
247
- return valid;
248
- } catch (e) {
249
- debug(`FixCache.getAll error: ${e}`);
250
- return [];
251
- }
252
- }
253
- /** Clear all cache entries. Returns the number of entries cleared. */
254
- clear() {
255
- const count = this._cache.size;
256
- this._cache.clear();
257
- this._stats.size = 0;
258
- return count;
259
- }
260
- /** Get cache statistics. */
261
- get stats() {
262
- this._stats.size = this._cache.size;
263
- return { ...this._stats };
264
- }
265
- /** Evict the oldest cache entry. */
266
- _evictOldest() {
267
- if (this._cache.size === 0) return;
268
- let oldestKey = null;
269
- let oldestTime = Infinity;
270
- for (const [key, entry] of this._cache) {
271
- if (entry.createdAt < oldestTime) {
272
- oldestTime = entry.createdAt;
273
- oldestKey = key;
274
- }
275
- }
276
- if (oldestKey !== null) {
277
- this._cache.delete(oldestKey);
278
- this._stats.evictions++;
279
- }
280
- }
281
- };
282
- }
283
- });
284
-
285
- // src/runtime/applier.ts
286
- function emptyResult(fix, fixType) {
287
- return {
288
- applied: false,
289
- fixId: fix.fixId,
290
- deploymentId: fix.deploymentId,
291
- fixType,
292
- modifications: {}
293
- };
294
- }
295
- var import_node_crypto2, MAX_FIX_CONTENT_LENGTH, FixApplier;
296
- var init_applier = __esm({
297
- "src/runtime/applier.ts"() {
298
- "use strict";
299
- import_node_crypto2 = require("crypto");
300
- init_config();
301
- init_log();
302
- MAX_FIX_CONTENT_LENGTH = 1e4;
303
- FixApplier = class {
304
- _config;
305
- _cache;
306
- _applicationLog = [];
307
- constructor(config, cache) {
308
- this._config = resolveFixRuntimeConfig(config);
309
- this._cache = cache;
310
- }
311
- // ═══════════════════════════════════════════════════════════════════════════
312
- // Fix Lookup
313
- // ═══════════════════════════════════════════════════════════════════════════
314
- /**
315
- * Get applicable fix for an error code.
316
- *
317
- * Considers A/B testing bucket if sessionId is provided. Uses
318
- * crypto.createHash('md5') for deterministic bucketing across restarts.
319
- */
320
- getFixForError(errorCode, sessionId) {
321
- try {
322
- const fix = this._cache.get(errorCode);
323
- if (!fix) return null;
324
- if (sessionId && this._config.abTestingEnabled) {
325
- const hashHex = (0, import_node_crypto2.createHash)("md5").update(sessionId).digest("hex").substring(0, 8);
326
- const sessionHash = parseInt(hashHex, 16);
327
- if (!shouldApply(fix, sessionHash)) {
328
- debug(`Fix ${fix.fixId} not applied (A/B control group)`);
329
- return null;
330
- }
331
- }
332
- return fix;
333
- } catch (e) {
334
- debug(`getFixForError error: ${e}`);
335
- return null;
336
- }
337
- }
338
- // ═══════════════════════════════════════════════════════════════════════════
339
- // 1. Prompt Fix
340
- // ═══════════════════════════════════════════════════════════════════════════
341
- /**
342
- * Apply a prompt fix to messages.
343
- *
344
- * Supports 4 modification types:
345
- * - prepend: Add content before first system message
346
- * - append: Add content after first system message
347
- * - replace: Regex replace across all messages
348
- * - few_shot: Insert user/assistant example pairs after system message
349
- */
350
- applyPromptFix(fix, messages) {
351
- try {
352
- const cfg = fix.config;
353
- const modificationType = cfg.modification_type ?? cfg.modificationType ?? "append";
354
- const target = cfg.target ?? "system";
355
- let content = cfg.content ?? "";
356
- if (content.length > MAX_FIX_CONTENT_LENGTH) {
357
- warn(
358
- `Fix ${fix.fixId} content truncated from ${content.length} to ${MAX_FIX_CONTENT_LENGTH} chars`
359
- );
360
- content = content.slice(0, MAX_FIX_CONTENT_LENGTH);
361
- }
362
- const result = emptyResult(fix, "prompt");
363
- if (this._config.dryRun) {
364
- result.modifications = {
365
- type: modificationType,
366
- target,
367
- contentPreview: content.slice(0, 100)
368
- };
369
- return { messages, result };
370
- }
371
- let modified = messages.map((m) => ({ ...m }));
372
- if (modificationType === "prepend") {
373
- modified = this._prependToTarget(modified, target, content);
374
- result.applied = true;
375
- result.modifications = { type: "prepend", target };
376
- } else if (modificationType === "append") {
377
- modified = this._appendToTarget(modified, target, content);
378
- result.applied = true;
379
- result.modifications = { type: "append", target };
380
- } else if (modificationType === "replace") {
381
- const pattern = cfg.pattern ?? "";
382
- if (pattern) {
383
- modified = this._replaceInMessages(modified, pattern, content);
384
- result.applied = true;
385
- result.modifications = { type: "replace", pattern };
386
- }
387
- } else if (modificationType === "few_shot") {
388
- const examples = cfg.examples ?? [];
389
- if (examples.length > 0) {
390
- modified = this._addFewShotExamples(modified, examples);
391
- result.applied = true;
392
- result.modifications = { type: "few_shot", count: examples.length };
393
- }
394
- }
395
- return { messages: modified, result };
396
- } catch (e) {
397
- debug(`applyPromptFix error: ${e}`);
398
- return {
399
- messages,
400
- result: {
401
- applied: false,
402
- fixId: fix.fixId,
403
- fixType: "prompt",
404
- modifications: {},
405
- error: String(e)
406
- }
407
- };
408
- }
409
- }
410
- // ═══════════════════════════════════════════════════════════════════════════
411
- // 2. Parameter Fix
412
- // ═══════════════════════════════════════════════════════════════════════════
413
- /**
414
- * Apply a parameter fix — merge config.parameters into params.
415
- */
416
- applyParameterFix(fix, params) {
417
- try {
418
- const newParams = fix.config.parameters ?? {};
419
- const result = emptyResult(fix, "parameter");
420
- if (this._config.dryRun) {
421
- result.modifications = { parameters: newParams };
422
- return { params, result };
423
- }
424
- const modified = { ...params, ...newParams };
425
- result.applied = true;
426
- result.modifications = { parameters: newParams };
427
- return { params: modified, result };
428
- } catch (e) {
429
- debug(`applyParameterFix error: ${e}`);
430
- return {
431
- params,
432
- result: {
433
- applied: false,
434
- fixId: fix.fixId,
435
- fixType: "parameter",
436
- modifications: {},
437
- error: String(e)
438
- }
439
- };
440
- }
441
- }
442
- // ═══════════════════════════════════════════════════════════════════════════
443
- // 3. Retry Fix (async — uses setTimeout for sleeping)
444
- // ═══════════════════════════════════════════════════════════════════════════
445
- /**
446
- * Apply a retry fix to an async operation.
447
- *
448
- * Retries with exponential backoff + jitter using
449
- * `await new Promise(r => setTimeout(r, delay))`.
450
- */
451
- async applyRetryFix(fix, operation) {
452
- const cfg = fix.config;
453
- const maxRetries = cfg.max_retries ?? cfg.maxRetries ?? 3;
454
- const initialDelayMs = cfg.initial_delay_ms ?? cfg.initialDelayMs ?? 1e3;
455
- const maxDelayMs = cfg.max_delay_ms ?? cfg.maxDelayMs ?? 3e4;
456
- const exponentialBase = cfg.exponential_base ?? cfg.exponentialBase ?? 2;
457
- const jitter = cfg.jitter ?? true;
458
- const retryOn = cfg.retry_on ?? cfg.retryOn ?? [];
459
- const result = emptyResult(fix, "retry");
460
- if (this._config.dryRun) {
461
- result.modifications = { maxRetries, initialDelayMs };
462
- const value = await operation();
463
- return { value, result };
464
- }
465
- let lastError = null;
466
- let attempts = 0;
467
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
468
- attempts++;
469
- try {
470
- const value = await operation();
471
- result.applied = true;
472
- result.modifications = { attempts };
473
- return { value, result };
474
- } catch (e) {
475
- lastError = e instanceof Error ? e : new Error(String(e));
476
- const errorType = lastError.constructor.name;
477
- if (retryOn.length > 0 && !retryOn.includes(errorType)) {
478
- throw lastError;
479
- }
480
- if (attempt < maxRetries) {
481
- let delayMs = Math.min(
482
- initialDelayMs * Math.pow(exponentialBase, attempt),
483
- maxDelayMs
484
- );
485
- if (jitter) {
486
- delayMs *= 0.5 + Math.random();
487
- }
488
- debug(
489
- `Retry ${attempt + 1}/${maxRetries} after ${Math.round(delayMs)}ms`
490
- );
491
- await new Promise((r) => setTimeout(r, delayMs));
492
- }
493
- }
494
- }
495
- result.applied = true;
496
- result.error = lastError?.message;
497
- result.modifications = { attempts, exhausted: true };
498
- throw lastError;
499
- }
500
- // ═══════════════════════════════════════════════════════════════════════════
501
- // 4. Fallback Fix
502
- // ═══════════════════════════════════════════════════════════════════════════
503
- /**
504
- * Apply a fallback fix.
505
- *
506
- * - 'model': Replace params.model with the fallback model
507
- * - 'default': Set params._fallbackResponse for the caller to use
508
- */
509
- applyFallbackFix(fix, params) {
510
- try {
511
- const cfg = fix.config;
512
- const fallbackType = cfg.fallback_type ?? cfg.fallbackType ?? "model";
513
- const fallbackConfig = cfg.fallback_config ?? cfg.fallbackConfig ?? {};
514
- const result = emptyResult(fix, "fallback");
515
- if (this._config.dryRun) {
516
- result.modifications = { fallbackType, fallbackConfig };
517
- return { params, result };
518
- }
519
- const modified = { ...params };
520
- if (fallbackType === "model") {
521
- const fallbackModel = fallbackConfig.model;
522
- if (fallbackModel) {
523
- modified.model = fallbackModel;
524
- result.applied = true;
525
- result.modifications = { model: fallbackModel };
526
- }
527
- } else if (fallbackType === "default") {
528
- const defaultResponse = fallbackConfig.response;
529
- if (defaultResponse !== void 0) {
530
- modified._fallbackResponse = defaultResponse;
531
- result.applied = true;
532
- result.modifications = { defaultResponse: true };
533
- }
534
- }
535
- return { params: modified, result };
536
- } catch (e) {
537
- debug(`applyFallbackFix error: ${e}`);
538
- return {
539
- params,
540
- result: {
541
- applied: false,
542
- fixId: fix.fixId,
543
- fixType: "fallback",
544
- modifications: {},
545
- error: String(e)
546
- }
547
- };
548
- }
549
- }
550
- // ═══════════════════════════════════════════════════════════════════════════
551
- // 5. Guard Fix
552
- // ═══════════════════════════════════════════════════════════════════════════
553
- /**
554
- * Apply a guard fix (validation).
555
- *
556
- * Guard types:
557
- * - content_filter: Regex-based blocked patterns
558
- * - format_check: JSON.parse() validity
559
- * - input_validation / output_validation: min/max length
560
- */
561
- applyGuardFix(fix, content, isInput = true) {
562
- try {
563
- const cfg = fix.config;
564
- const guardType = cfg.guard_type ?? cfg.guardType ?? "output_validation";
565
- const guardConfig = cfg.guard_config ?? cfg.guardConfig ?? {};
566
- const result = emptyResult(fix, "guard");
567
- if (isInput && guardType !== "input_validation" && guardType !== "content_filter") {
568
- return { content, passed: true, result };
569
- }
570
- if (!isInput && guardType !== "output_validation" && guardType !== "format_check") {
571
- return { content, passed: true, result };
572
- }
573
- if (this._config.dryRun) {
574
- result.modifications = { guardType };
575
- return { content, passed: true, result };
576
- }
577
- let passed = true;
578
- if (guardType === "content_filter") {
579
- const blockedPatterns = guardConfig.blocked_patterns ?? guardConfig.blockedPatterns ?? [];
580
- for (const pattern of blockedPatterns) {
581
- const regex = this._safeCompileRegex(pattern);
582
- if (regex && regex.test(content)) {
583
- passed = false;
584
- break;
585
- }
586
- }
587
- } else if (guardType === "format_check") {
588
- const requiredFormat = guardConfig.format;
589
- if (requiredFormat === "json") {
590
- try {
591
- JSON.parse(content);
592
- } catch {
593
- passed = false;
594
- }
595
- }
596
- } else if (guardType === "input_validation" || guardType === "output_validation") {
597
- const minLength = guardConfig.min_length ?? guardConfig.minLength ?? 0;
598
- const maxLength = guardConfig.max_length ?? guardConfig.maxLength ?? Infinity;
599
- if (content.length < minLength || content.length > maxLength) {
600
- passed = false;
601
- }
602
- }
603
- result.applied = true;
604
- result.modifications = { passed, guardType };
605
- return { content, passed, result };
606
- } catch (e) {
607
- debug(`applyGuardFix error: ${e}`);
608
- return {
609
- content,
610
- passed: true,
611
- result: {
612
- applied: false,
613
- fixId: fix.fixId,
614
- fixType: "guard",
615
- modifications: {},
616
- error: String(e)
617
- }
618
- };
619
- }
620
- }
621
- // ═══════════════════════════════════════════════════════════════════════════
622
- // Application Log
623
- // ═══════════════════════════════════════════════════════════════════════════
624
- /** Log a fix application result. */
625
- logApplication(result) {
626
- this._applicationLog.push(result);
627
- if (this._applicationLog.length > 1e3) {
628
- this._applicationLog = this._applicationLog.slice(-500);
629
- }
630
- }
631
- /** Get the application log. */
632
- getApplicationLog() {
633
- return [...this._applicationLog];
634
- }
635
- // ═══════════════════════════════════════════════════════════════════════════
636
- // Private Helpers
637
- // ═══════════════════════════════════════════════════════════════════════════
638
- /**
639
- * Safely compile a regex pattern from untrusted input.
640
- * Returns null if invalid or too long.
641
- */
642
- _safeCompileRegex(pattern, maxLength = 500) {
643
- if (!pattern || pattern.length > maxLength) return null;
644
- try {
645
- return new RegExp(pattern, "i");
646
- } catch {
647
- debug(`Invalid regex pattern (length=${pattern.length})`);
648
- return null;
649
- }
650
- }
651
- /** Prepend content to the first message matching the target role. */
652
- _prependToTarget(messages, target, content) {
653
- return messages.map((msg) => {
654
- if (msg.role === target) {
655
- return {
656
- ...msg,
657
- content: content + "\n\n" + (msg.content ?? "")
658
- };
659
- }
660
- return msg;
661
- });
662
- }
663
- /** Append content to the first message matching the target role. */
664
- _appendToTarget(messages, target, content) {
665
- return messages.map((msg) => {
666
- if (msg.role === target) {
667
- return {
668
- ...msg,
669
- content: (msg.content ?? "") + "\n\n" + content
670
- };
671
- }
672
- return msg;
673
- });
674
- }
675
- /** Regex replace across all messages. */
676
- _replaceInMessages(messages, pattern, replacement) {
677
- const regex = this._safeCompileRegex(pattern);
678
- if (!regex) {
679
- debug("Skipping invalid regex pattern in prompt fix");
680
- return messages;
681
- }
682
- return messages.map((msg) => {
683
- const msgContent = msg.content;
684
- if (typeof msgContent === "string") {
685
- return { ...msg, content: msgContent.replace(regex, replacement) };
686
- }
687
- return msg;
688
- });
689
- }
690
- /** Add few-shot examples after the first system message. */
691
- _addFewShotExamples(messages, examples) {
692
- const result = [];
693
- let systemFound = false;
694
- for (const msg of messages) {
695
- result.push(msg);
696
- if (msg.role === "system" && !systemFound) {
697
- systemFound = true;
698
- for (const example of examples) {
699
- if (example.user) {
700
- result.push({ role: "user", content: example.user });
701
- }
702
- if (example.assistant) {
703
- result.push({ role: "assistant", content: example.assistant });
704
- }
705
- }
706
- }
707
- }
708
- return result;
709
- }
710
- };
711
- }
712
- });
713
-
714
- // src/runtime/loader.ts
715
- var SDK_VERSION, FixLoader;
716
- var init_loader = __esm({
717
- "src/runtime/loader.ts"() {
718
- "use strict";
719
- init_config();
720
- init_config();
721
- init_log();
722
- SDK_VERSION = "0.1.3";
723
- FixLoader = class _FixLoader {
724
- _config;
725
- _cache;
726
- _refreshTimer = null;
727
- _lastLoadTime = null;
728
- _consecutiveFailures = 0;
729
- _circuitOpenUntil = 0;
730
- _onLoadCallbacks = [];
731
- // Circuit breaker settings
732
- static CIRCUIT_BREAKER_THRESHOLD = 3;
733
- static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
734
- constructor(config, cache) {
735
- this._config = resolveFixRuntimeConfig(config);
736
- this._cache = cache;
737
- }
738
- /** Timestamp of last successful load. */
739
- get lastLoadTime() {
740
- return this._lastLoadTime;
741
- }
742
- /**
743
- * Start the loader: perform initial load and start background refresh.
744
- *
745
- * Never throws — failures are logged and the runtime degrades gracefully.
746
- */
747
- start() {
748
- try {
749
- if (!this._config.enabled) {
750
- debug("Fix runtime disabled, skipping loader start");
751
- return;
752
- }
753
- if (!this._config.apiKey) {
754
- warn("No API key configured, fixes will not be loaded");
755
- return;
756
- }
757
- this.loadSync().catch((e) => {
758
- debug(`Initial fix load failed: ${e}`);
759
- });
760
- if (this._config.autoRefresh) {
761
- this._startRefreshInterval();
762
- }
763
- } catch (e) {
764
- debug(`FixLoader.start error: ${e}`);
765
- }
766
- }
767
- /** Stop the loader: clear the refresh interval. */
768
- stop() {
769
- try {
770
- if (this._refreshTimer !== null) {
771
- clearInterval(this._refreshTimer);
772
- this._refreshTimer = null;
773
- }
774
- } catch (e) {
775
- debug(`FixLoader.stop error: ${e}`);
776
- }
777
- }
778
- /**
779
- * Register a callback invoked after each successful load.
780
- */
781
- onLoad(callback) {
782
- this._onLoadCallbacks.push(callback);
783
- }
784
- /**
785
- * Load fixes from the API.
786
- *
787
- * Name kept as "loadSync" for parity with the Python SDK, but this
788
- * returns a Promise in JS (there's no synchronous fetch in Node.js).
789
- */
790
- async loadSync() {
791
- if (!this._config.apiKey) {
792
- return [];
793
- }
794
- const now = Date.now();
795
- if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
796
- debug("Fix loader circuit breaker open \u2014 skipping load");
797
- return this._cache.getAll();
798
- }
799
- try {
800
- const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
801
- const url = `${endpoint}/api/v1/fixes/active`;
802
- const controller = new AbortController();
803
- const timeoutId = setTimeout(
804
- () => controller.abort(),
805
- this._config.timeoutMs
806
- );
807
- const response = await fetch(url, {
808
- method: "GET",
809
- headers: {
810
- "Authorization": `Bearer ${this._config.apiKey}`,
811
- "Content-Type": "application/json",
812
- "X-Risicare-SDK-Version": SDK_VERSION
813
- },
814
- signal: controller.signal
815
- });
816
- clearTimeout(timeoutId);
817
- if (!response.ok) {
818
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
819
- }
820
- const data = await response.json();
821
- const fixes = this._parseResponse(data);
822
- this._onLoadSuccess(fixes);
823
- return fixes;
824
- } catch (e) {
825
- this._onLoadFailure(e);
826
- throw e;
827
- }
828
- }
829
- /** Get currently cached fixes without hitting the API. */
830
- getCached() {
831
- return this._cache.getAll();
832
- }
833
- // ─── Private ────────────────────────────────────────────────────────────
834
- _parseResponse(data) {
835
- const fixes = [];
836
- const items = data.fixes ?? data.data ?? [];
837
- if (!Array.isArray(items)) return fixes;
838
- for (const item of items) {
839
- try {
840
- if (item && typeof item === "object") {
841
- fixes.push(activeFixFromApiResponse(item));
842
- }
843
- } catch (e) {
844
- debug(`Failed to parse fix item: ${e}`);
845
- }
846
- }
847
- return fixes;
848
- }
849
- _onLoadSuccess(fixes) {
850
- this._lastLoadTime = Date.now();
851
- this._consecutiveFailures = 0;
852
- this._cache.setAll(fixes);
853
- for (const callback of this._onLoadCallbacks) {
854
- try {
855
- callback(fixes);
856
- } catch (e) {
857
- debug(`Load callback error: ${e}`);
858
- }
859
- }
860
- debug(`Loaded ${fixes.length} active fixes`);
861
- }
862
- _onLoadFailure(error) {
863
- this._consecutiveFailures++;
864
- if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
865
- this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
866
- warn(
867
- `Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
868
- );
869
- } else {
870
- debug(
871
- `Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
872
- );
873
- }
874
- }
875
- _startRefreshInterval() {
876
- const tick = () => {
877
- this.loadSync().catch((e) => {
878
- debug(`Background fix refresh failed: ${e}`);
879
- });
880
- };
881
- this._refreshTimer = setInterval(
882
- () => {
883
- if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
884
- return;
885
- }
886
- tick();
887
- },
888
- this._config.refreshIntervalMs
889
- );
890
- this._refreshTimer.unref();
891
- debug("Started fix refresh interval");
892
- }
893
- };
894
- }
895
- });
896
-
897
- // src/runtime/interceptors.ts
898
- function createInterceptContext(operationType, operationName, options) {
899
- return {
900
- operationType,
901
- operationName,
902
- sessionId: options?.sessionId,
903
- traceId: options?.traceId,
904
- errorCode: options?.errorCode,
905
- attempt: 1,
906
- appliedFixes: []
907
- };
908
- }
909
- function classifyError(error) {
910
- const errorType = error.constructor.name.toLowerCase();
911
- const errorMsg = error.message.toLowerCase();
912
- if (errorType.includes("timeout") || errorMsg.includes("timeout") || errorMsg.includes("aborted")) {
913
- return "TOOL.EXECUTION.TIMEOUT";
914
- }
915
- if (errorMsg.includes("rate") && errorMsg.includes("limit")) {
916
- return "TOOL.EXECUTION.RATE_LIMIT";
917
- }
918
- if (errorMsg.includes("429") || errorMsg.includes("too many requests")) {
919
- return "TOOL.EXECUTION.RATE_LIMIT";
920
- }
921
- if (errorType.includes("connection") || errorMsg.includes("connection") || errorMsg.includes("econnrefused") || errorMsg.includes("econnreset") || errorMsg.includes("fetch failed")) {
922
- return "TOOL.EXECUTION.CONNECTION_ERROR";
923
- }
924
- if (errorMsg.includes("auth") || errorMsg.includes("401") || errorMsg.includes("403") || errorMsg.includes("unauthorized") || errorMsg.includes("forbidden")) {
925
- return "TOOL.EXECUTION.AUTH_ERROR";
926
- }
927
- if (errorType.includes("syntaxerror") || errorType.includes("json") || errorMsg.includes("json") || errorMsg.includes("unexpected token")) {
928
- return "OUTPUT.FORMAT.JSON_INVALID";
929
- }
930
- return "TOOL.EXECUTION.FAILURE";
931
- }
932
- var DefaultFixInterceptor;
933
- var init_interceptors = __esm({
934
- "src/runtime/interceptors.ts"() {
935
- "use strict";
936
- init_config();
937
- init_log();
938
- DefaultFixInterceptor = class {
939
- _config;
940
- _cache;
941
- _applier;
942
- constructor(config, cache, applier) {
943
- this._config = resolveFixRuntimeConfig(config);
944
- this._cache = cache;
945
- this._applier = applier;
946
- }
947
- /**
948
- * Apply pre-call fixes.
949
- *
950
- * - If retrying after error: look up fix by error_code, apply
951
- * prompt/parameter/fallback fixes
952
- * - Runs input guard fixes on all message content
953
- */
954
- preCall(ctx, messages, params) {
955
- try {
956
- if (!this._config.enabled) {
957
- return { messages, params };
958
- }
959
- let modifiedMessages = messages;
960
- let modifiedParams = { ...params };
961
- if (ctx.errorCode) {
962
- const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
963
- if (fix) {
964
- debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
965
- if (fix.fixType === "prompt" && messages) {
966
- const msgRecords = messages;
967
- const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
968
- modifiedMessages = newMessages;
969
- ctx.appliedFixes.push(result);
970
- this._applier.logApplication(result);
971
- } else if (fix.fixType === "parameter") {
972
- const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
973
- modifiedParams = newParams;
974
- ctx.appliedFixes.push(result);
975
- this._applier.logApplication(result);
976
- } else if (fix.fixType === "fallback") {
977
- const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
978
- modifiedParams = newParams;
979
- ctx.appliedFixes.push(result);
980
- this._applier.logApplication(result);
981
- }
982
- }
983
- }
984
- if (modifiedMessages && this._config.enabled) {
985
- for (const msg of modifiedMessages) {
986
- const content = msg.content;
987
- if (typeof content === "string") {
988
- for (const fix of this._cache.getAll()) {
989
- if (fix.fixType === "guard") {
990
- const { result } = this._applier.applyGuardFix(
991
- fix,
992
- content,
993
- true
994
- );
995
- if (result.applied) {
996
- ctx.appliedFixes.push(result);
997
- this._applier.logApplication(result);
998
- }
999
- }
1000
- }
1001
- }
1002
- }
1003
- }
1004
- return { messages: modifiedMessages, params: modifiedParams };
1005
- } catch (e) {
1006
- debug(`DefaultFixInterceptor.preCall error: ${e}`);
1007
- return { messages, params };
1008
- }
1009
- }
1010
- /**
1011
- * Apply post-call fixes (output validation).
1012
- *
1013
- * Runs output guard fixes on response content.
1014
- */
1015
- postCall(ctx, response) {
1016
- try {
1017
- if (!this._config.enabled) {
1018
- return { response, shouldContinue: true };
1019
- }
1020
- for (const fix of this._cache.getAll()) {
1021
- if (fix.fixType !== "guard") continue;
1022
- const content = this._extractResponseContent(response);
1023
- if (!content) continue;
1024
- const { passed, result } = this._applier.applyGuardFix(
1025
- fix,
1026
- content,
1027
- false
1028
- );
1029
- if (result.applied) {
1030
- ctx.appliedFixes.push(result);
1031
- this._applier.logApplication(result);
1032
- }
1033
- if (!passed) {
1034
- warn(`Output guard failed for fix ${fix.fixId}`);
1035
- }
1036
- }
1037
- return { response, shouldContinue: true };
1038
- } catch (e) {
1039
- debug(`DefaultFixInterceptor.postCall error: ${e}`);
1040
- return { response, shouldContinue: true };
1041
- }
1042
- }
1043
- /**
1044
- * Handle errors and decide whether to retry.
1045
- *
1046
- * Classifies the error, looks up retry/fallback fixes, and returns
1047
- * whether the caller should retry.
1048
- */
1049
- onError(ctx, error) {
1050
- try {
1051
- if (!this._config.enabled) {
1052
- return { shouldRetry: false, modifiedParams: null };
1053
- }
1054
- const errorCode = classifyError(error);
1055
- ctx.errorCode = errorCode;
1056
- ctx.errorMessage = error.message;
1057
- const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
1058
- if (!fix) {
1059
- return { shouldRetry: false, modifiedParams: null };
1060
- }
1061
- if (fix.fixType === "retry") {
1062
- const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
1063
- if (ctx.attempt <= maxRetries) {
1064
- debug(
1065
- `Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
1066
- );
1067
- const result = {
1068
- applied: true,
1069
- fixId: fix.fixId,
1070
- deploymentId: fix.deploymentId,
1071
- fixType: "retry",
1072
- modifications: { attempt: ctx.attempt }
1073
- };
1074
- ctx.appliedFixes.push(result);
1075
- this._applier.logApplication(result);
1076
- return { shouldRetry: true, modifiedParams: null };
1077
- }
1078
- }
1079
- if (fix.fixType === "fallback") {
1080
- const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
1081
- if (result.applied) {
1082
- ctx.appliedFixes.push(result);
1083
- this._applier.logApplication(result);
1084
- return { shouldRetry: true, modifiedParams };
1085
- }
1086
- }
1087
- return { shouldRetry: false, modifiedParams: null };
1088
- } catch (e) {
1089
- debug(`DefaultFixInterceptor.onError error: ${e}`);
1090
- return { shouldRetry: false, modifiedParams: null };
1091
- }
1092
- }
1093
- // ─── Private ────────────────────────────────────────────────────────────
1094
- /** Extract text content from a response object. */
1095
- _extractResponseContent(response) {
1096
- if (typeof response === "string") return response;
1097
- if (response && typeof response === "object") {
1098
- const resp = response;
1099
- const choices = resp.choices;
1100
- if (Array.isArray(choices) && choices.length > 0) {
1101
- const first = choices[0];
1102
- const message = first?.message;
1103
- if (typeof message?.content === "string") {
1104
- return message.content;
1105
- }
1106
- }
1107
- const content = resp.content;
1108
- if (typeof content === "string") return content;
1109
- if (Array.isArray(content) && content.length > 0) {
1110
- const first = content[0];
1111
- if (typeof first?.text === "string") return first.text;
1112
- }
1113
- }
1114
- return null;
1115
- }
1116
- };
1117
- }
1118
- });
1119
-
1120
- // src/runtime/runtime.ts
1121
- var runtime_exports = {};
1122
- __export(runtime_exports, {
1123
- FixRuntime: () => FixRuntime,
1124
- getFixRuntime: () => getFixRuntime,
1125
- initFixRuntime: () => initFixRuntime,
1126
- setFixRuntime: () => setFixRuntime,
1127
- shutdownFixRuntime: () => shutdownFixRuntime
1128
- });
1129
- function getFixRuntime() {
1130
- return G2[RUNTIME_KEY];
1131
- }
1132
- function setFixRuntime(runtime) {
1133
- G2[RUNTIME_KEY] = runtime;
1134
- }
1135
- function initFixRuntime(config) {
1136
- try {
1137
- const existing = G2[RUNTIME_KEY];
1138
- if (existing) {
1139
- debug("Fix runtime already initialized");
1140
- return existing;
1141
- }
1142
- const runtime = new FixRuntime(config);
1143
- runtime.start();
1144
- G2[RUNTIME_KEY] = runtime;
1145
- return runtime;
1146
- } catch (e) {
1147
- warn(`initFixRuntime failed: ${e}`);
1148
- const fallback = new FixRuntime({ ...config, enabled: false });
1149
- G2[RUNTIME_KEY] = fallback;
1150
- return fallback;
1151
- }
1152
- }
1153
- function shutdownFixRuntime() {
1154
- try {
1155
- const runtime = G2[RUNTIME_KEY];
1156
- if (runtime) {
1157
- runtime.stop();
1158
- }
1159
- G2[RUNTIME_KEY] = void 0;
1160
- } catch (e) {
1161
- debug(`shutdownFixRuntime error: ${e}`);
1162
- G2[RUNTIME_KEY] = void 0;
1163
- }
1164
- }
1165
- var G2, RUNTIME_KEY, FixRuntime;
1166
- var init_runtime = __esm({
1167
- "src/runtime/runtime.ts"() {
1168
- "use strict";
1169
- init_cache();
1170
- init_config();
1171
- init_applier();
1172
- init_loader();
1173
- init_interceptors();
1174
- init_log();
1175
- G2 = globalThis;
1176
- RUNTIME_KEY = "__risicare_fix_runtime";
1177
- FixRuntime = class {
1178
- _config;
1179
- _cache;
1180
- _loader;
1181
- _applier;
1182
- _interceptor;
1183
- _started = false;
1184
- // Effectiveness tracking
1185
- _fixApplications = /* @__PURE__ */ new Map();
1186
- _fixSuccesses = /* @__PURE__ */ new Map();
1187
- constructor(config) {
1188
- this._config = resolveFixRuntimeConfig(config);
1189
- this._cache = new FixCache(this._config);
1190
- this._loader = new FixLoader(config, this._cache);
1191
- this._applier = new FixApplier(config, this._cache);
1192
- this._interceptor = new DefaultFixInterceptor(
1193
- config,
1194
- this._cache,
1195
- this._applier
1196
- );
1197
- }
1198
- // ─── Accessors ──────────────────────────────────────────────────────────
1199
- /** Runtime configuration (with defaults resolved). */
1200
- get config() {
1201
- return this._config;
1202
- }
1203
- /** Whether the runtime is enabled and started. */
1204
- get isEnabled() {
1205
- return this._config.enabled && this._started;
1206
- }
1207
- /** The fix cache. */
1208
- get cache() {
1209
- return this._cache;
1210
- }
1211
- /** The fix loader. */
1212
- get loader() {
1213
- return this._loader;
1214
- }
1215
- /** The fix applier. */
1216
- get applier() {
1217
- return this._applier;
1218
- }
1219
- /** The interceptor. */
1220
- get interceptor() {
1221
- return this._interceptor;
1222
- }
1223
- // ─── Lifecycle ──────────────────────────────────────────────────────────
1224
- /**
1225
- * Start the runtime.
1226
- *
1227
- * Triggers initial fix load and starts background refresh.
1228
- * Never throws — failures degrade gracefully.
1229
- */
1230
- start() {
1231
- try {
1232
- if (this._started) return;
1233
- if (!this._config.enabled) {
1234
- debug("Fix runtime disabled");
1235
- return;
1236
- }
1237
- debug("Starting fix runtime...");
1238
- this._loader.start();
1239
- this._started = true;
1240
- debug("Fix runtime started");
1241
- } catch (e) {
1242
- warn(`Fix runtime start failed: ${e}`);
1243
- }
1244
- }
1245
- /**
1246
- * Stop the runtime.
1247
- *
1248
- * Stops background refresh and clears the cache.
1249
- * Never throws.
1250
- */
1251
- stop() {
1252
- try {
1253
- if (!this._started) return;
1254
- debug("Stopping fix runtime...");
1255
- this._loader.stop();
1256
- this._cache.clear();
1257
- this._started = false;
1258
- debug("Fix runtime stopped");
1259
- } catch (e) {
1260
- debug(`Fix runtime stop error: ${e}`);
1261
- }
1262
- }
1263
- // ─── Intercept API ──────────────────────────────────────────────────────
1264
- /**
1265
- * Intercept a call: create context and run preCall fixes.
1266
- *
1267
- * Returns modified messages/params and the InterceptContext for
1268
- * use in subsequent interceptResponse / interceptError calls.
1269
- */
1270
- interceptCall(operationType, operationName, messages, params, options) {
1271
- const ctx = createInterceptContext(operationType, operationName, options);
1272
- try {
1273
- if (!this.isEnabled) {
1274
- return { messages, params, ctx };
1275
- }
1276
- const result = this._interceptor.preCall(ctx, messages, params);
1277
- return { messages: result.messages, params: result.params, ctx };
1278
- } catch (e) {
1279
- debug(`interceptCall error: ${e}`);
1280
- return { messages, params, ctx };
1281
- }
1282
- }
1283
- /**
1284
- * Intercept a response: run postCall fixes (output validation).
1285
- */
1286
- interceptResponse(ctx, response) {
1287
- try {
1288
- if (!this.isEnabled) {
1289
- return { response, shouldContinue: true };
1290
- }
1291
- const result = this._interceptor.postCall(ctx, response);
1292
- this._trackSuccess(ctx);
1293
- return result;
1294
- } catch (e) {
1295
- debug(`interceptResponse error: ${e}`);
1296
- return { response, shouldContinue: true };
1297
- }
1298
- }
1299
- /**
1300
- * Intercept an error: decide on retry/fallback.
1301
- */
1302
- interceptError(ctx, error) {
1303
- try {
1304
- if (!this.isEnabled) {
1305
- return { shouldRetry: false, modifiedParams: null };
1306
- }
1307
- ctx.attempt++;
1308
- const result = this._interceptor.onError(ctx, error);
1309
- if (!result.shouldRetry) {
1310
- this._trackFailure(ctx);
1311
- }
1312
- return result;
1313
- } catch (e) {
1314
- debug(`interceptError error: ${e}`);
1315
- return { shouldRetry: false, modifiedParams: null };
1316
- }
1317
- }
1318
- // ─── Direct Fix Access ──────────────────────────────────────────────────
1319
- /**
1320
- * Get applicable fix for an error code.
1321
- */
1322
- getFix(errorCode, sessionId) {
1323
- try {
1324
- if (!this.isEnabled) return null;
1325
- return this._applier.getFixForError(errorCode, sessionId);
1326
- } catch (e) {
1327
- debug(`getFix error: ${e}`);
1328
- return null;
1329
- }
1330
- }
1331
- /**
1332
- * Manually refresh fixes from the API.
1333
- */
1334
- async refreshFixes() {
1335
- try {
1336
- return await this._loader.loadSync();
1337
- } catch (e) {
1338
- debug(`refreshFixes error: ${e}`);
1339
- return [];
1340
- }
1341
- }
1342
- // ─── Effectiveness ──────────────────────────────────────────────────────
1343
- /** Get effectiveness statistics for all fixes. */
1344
- getEffectivenessStats() {
1345
- const stats = {};
1346
- for (const [fixId, applications] of this._fixApplications) {
1347
- const successes = this._fixSuccesses.get(fixId) ?? 0;
1348
- stats[fixId] = {
1349
- applications,
1350
- successes,
1351
- successRate: applications > 0 ? successes / applications : 0
1352
- };
1353
- }
1354
- return stats;
1355
- }
1356
- // ─── Private ────────────────────────────────────────────────────────────
1357
- _trackSuccess(ctx) {
1358
- for (const result of ctx.appliedFixes) {
1359
- if (result.applied && result.fixId) {
1360
- this._fixApplications.set(
1361
- result.fixId,
1362
- (this._fixApplications.get(result.fixId) ?? 0) + 1
1363
- );
1364
- this._fixSuccesses.set(
1365
- result.fixId,
1366
- (this._fixSuccesses.get(result.fixId) ?? 0) + 1
1367
- );
1368
- }
1369
- }
1370
- }
1371
- _trackFailure(ctx) {
1372
- for (const result of ctx.appliedFixes) {
1373
- if (result.applied && result.fixId) {
1374
- this._fixApplications.set(
1375
- result.fixId,
1376
- (this._fixApplications.get(result.fixId) ?? 0) + 1
1377
- );
1378
- }
1379
- }
1380
- }
1381
- };
1382
- }
1383
- });
1384
-
1385
60
  // src/providers/openai/index.ts
1386
61
  var openai_exports = {};
1387
62
  __export(openai_exports, {
@@ -1634,15 +309,16 @@ function createChatCompletionProxy(originalCreate, provider) {
1634
309
  let params = args[0] ?? {};
1635
310
  let model = params.model ?? "unknown";
1636
311
  const isStream = !!params.stream;
312
+ let fixCtx;
1637
313
  try {
1638
- const { getFixRuntime: getFixRuntime2 } = (init_runtime(), __toCommonJS(runtime_exports));
1639
- const rt = getFixRuntime2();
314
+ const rt = globalThis["__risicare_fix_runtime"];
1640
315
  if (rt?.isEnabled) {
1641
316
  const result = rt.interceptCall("llm_call", model, params.messages ?? null, params);
1642
317
  if (result.messages) params = { ...params, messages: result.messages };
1643
318
  if (result.params) params = { ...params, ...result.params };
1644
319
  model = params.model ?? model;
1645
320
  args[0] = params;
321
+ fixCtx = result.ctx;
1646
322
  }
1647
323
  } catch {
1648
324
  }
@@ -1651,6 +327,19 @@ function createChatCompletionProxy(originalCreate, provider) {
1651
327
  (span) => {
1652
328
  span.setLlmFields({ provider, model });
1653
329
  enrichSpanFromRequest(span, params, provider);
330
+ try {
331
+ if (fixCtx) {
332
+ for (const result2 of fixCtx.appliedFixes) {
333
+ if (result2.applied && result2.fixId) {
334
+ span.setAttribute("risicare.fix.applied", result2.fixId);
335
+ span.setAttribute("risicare.fix.deployment_id", result2.deploymentId ?? "");
336
+ span.setAttribute("risicare.fix.error_code", fixCtx.errorCode ?? "");
337
+ break;
338
+ }
339
+ }
340
+ }
341
+ } catch {
342
+ }
1654
343
  const result = originalCreate.apply(this, args);
1655
344
  if (result && typeof result === "object" && typeof result.then === "function") {
1656
345
  return result.then((response) => {