risicare 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +346 -68
  2. package/dist/frameworks/instructor.cjs +790 -5
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +780 -5
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +790 -5
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.d.cts +3 -2
  9. package/dist/frameworks/langchain.d.ts +3 -2
  10. package/dist/frameworks/langchain.js +780 -5
  11. package/dist/frameworks/langchain.js.map +1 -1
  12. package/dist/frameworks/langgraph.cjs +790 -5
  13. package/dist/frameworks/langgraph.cjs.map +1 -1
  14. package/dist/frameworks/langgraph.js +780 -5
  15. package/dist/frameworks/langgraph.js.map +1 -1
  16. package/dist/frameworks/llamaindex.cjs +801 -5
  17. package/dist/frameworks/llamaindex.cjs.map +1 -1
  18. package/dist/frameworks/llamaindex.d.cts +3 -2
  19. package/dist/frameworks/llamaindex.d.ts +3 -2
  20. package/dist/frameworks/llamaindex.js +791 -5
  21. package/dist/frameworks/llamaindex.js.map +1 -1
  22. package/dist/index.cjs +1219 -212
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +250 -44
  25. package/dist/index.d.ts +250 -44
  26. package/dist/index.js +1219 -212
  27. package/dist/index.js.map +1 -1
  28. package/dist/providers/anthropic/index.cjs +1601 -36
  29. package/dist/providers/anthropic/index.cjs.map +1 -1
  30. package/dist/providers/anthropic/index.d.cts +3 -1
  31. package/dist/providers/anthropic/index.d.ts +3 -1
  32. package/dist/providers/anthropic/index.js +1591 -36
  33. package/dist/providers/anthropic/index.js.map +1 -1
  34. package/dist/providers/bedrock/index.cjs +850 -32
  35. package/dist/providers/bedrock/index.cjs.map +1 -1
  36. package/dist/providers/bedrock/index.js +840 -32
  37. package/dist/providers/bedrock/index.js.map +1 -1
  38. package/dist/providers/cerebras/index.cjs +1534 -30
  39. package/dist/providers/cerebras/index.cjs.map +1 -1
  40. package/dist/providers/cerebras/index.js +1524 -30
  41. package/dist/providers/cerebras/index.js.map +1 -1
  42. package/dist/providers/cohere/index.cjs +1557 -102
  43. package/dist/providers/cohere/index.cjs.map +1 -1
  44. package/dist/providers/cohere/index.js +1547 -102
  45. package/dist/providers/cohere/index.js.map +1 -1
  46. package/dist/providers/google/index.cjs +1562 -60
  47. package/dist/providers/google/index.cjs.map +1 -1
  48. package/dist/providers/google/index.js +1552 -60
  49. package/dist/providers/google/index.js.map +1 -1
  50. package/dist/providers/groq/index.cjs +1534 -30
  51. package/dist/providers/groq/index.cjs.map +1 -1
  52. package/dist/providers/groq/index.js +1524 -30
  53. package/dist/providers/groq/index.js.map +1 -1
  54. package/dist/providers/huggingface/index.cjs +1622 -25
  55. package/dist/providers/huggingface/index.cjs.map +1 -1
  56. package/dist/providers/huggingface/index.d.cts +0 -9
  57. package/dist/providers/huggingface/index.d.ts +0 -9
  58. package/dist/providers/huggingface/index.js +1612 -25
  59. package/dist/providers/huggingface/index.js.map +1 -1
  60. package/dist/providers/mistral/index.cjs +1535 -54
  61. package/dist/providers/mistral/index.cjs.map +1 -1
  62. package/dist/providers/mistral/index.js +1525 -54
  63. package/dist/providers/mistral/index.js.map +1 -1
  64. package/dist/providers/ollama/index.cjs +1559 -93
  65. package/dist/providers/ollama/index.cjs.map +1 -1
  66. package/dist/providers/ollama/index.js +1549 -93
  67. package/dist/providers/ollama/index.js.map +1 -1
  68. package/dist/providers/openai/index.cjs +1598 -61
  69. package/dist/providers/openai/index.cjs.map +1 -1
  70. package/dist/providers/openai/index.d.cts +6 -1
  71. package/dist/providers/openai/index.d.ts +6 -1
  72. package/dist/providers/openai/index.js +1588 -61
  73. package/dist/providers/openai/index.js.map +1 -1
  74. package/dist/providers/together/index.cjs +1534 -30
  75. package/dist/providers/together/index.cjs.map +1 -1
  76. package/dist/providers/together/index.js +1524 -30
  77. package/dist/providers/together/index.js.map +1 -1
  78. package/dist/providers/vercel-ai/index.cjs +1288 -17
  79. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  80. package/dist/providers/vercel-ai/index.d.cts +0 -6
  81. package/dist/providers/vercel-ai/index.d.ts +0 -6
  82. package/dist/providers/vercel-ai/index.js +1278 -17
  83. package/dist/providers/vercel-ai/index.js.map +1 -1
  84. package/package.json +1 -1
@@ -17,6 +17,29 @@ function getContextStorage() {
17
17
  function getDebug() {
18
18
  return G[PREFIX + "debug"] ?? false;
19
19
  }
20
+ var PROVIDER_SPANS = /* @__PURE__ */ Symbol.for("risicare.providerSpans");
21
+ function usableProviderSpanState(s) {
22
+ if (!s || typeof s !== "object") return false;
23
+ const { version, open, registry } = s;
24
+ const o = open;
25
+ return version === 1 && !!o && typeof o.add === "function" && typeof o.delete === "function" && typeof o[Symbol.iterator] === "function" && (registry === void 0 || typeof registry.register === "function");
26
+ }
27
+ function getProviderSpanState() {
28
+ const found = G[PROVIDER_SPANS];
29
+ if (found === void 0) {
30
+ const s = {
31
+ version: 1,
32
+ open: /* @__PURE__ */ new Set(),
33
+ registry: typeof FinalizationRegistry === "function" ? new FinalizationRegistry((o) => o.release()) : void 0
34
+ };
35
+ G[PROVIDER_SPANS] = s;
36
+ return s;
37
+ }
38
+ if (!usableProviderSpanState(found)) {
39
+ throw new TypeError("the shared provider span state is not version 1");
40
+ }
41
+ return found;
42
+ }
20
43
 
21
44
  // src/utils/log.ts
22
45
  function debug(msg) {
@@ -25,8 +48,80 @@ function debug(msg) {
25
48
  `);
26
49
  }
27
50
  }
51
+ function warn(msg) {
52
+ process.stderr.write(`[risicare] WARNING: ${msg}
53
+ `);
54
+ }
55
+
56
+ // src/utils/text.ts
57
+ function cutCodePoints(text, max) {
58
+ if (text.length <= max) return text;
59
+ let units = 0;
60
+ for (let points = 0; points < max && units < text.length; points++) {
61
+ units += text.codePointAt(units) > 65535 ? 2 : 1;
62
+ }
63
+ return text.slice(0, units);
64
+ }
65
+
66
+ // src/utils/scrub.ts
67
+ var KEY_MARKER = "[REDACTED-KEY]";
68
+ var CONTROL = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]", "g");
69
+ function escapeRegExp(text) {
70
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
71
+ }
72
+ function percentDecode(text) {
73
+ try {
74
+ return decodeURIComponent(text);
75
+ } catch {
76
+ return text.replace(/%([0-9A-Fa-f]{2})/g, (_m, hex) => String.fromCharCode(parseInt(hex, 16)));
77
+ }
78
+ }
79
+ function keyPattern(keys) {
80
+ const values = /* @__PURE__ */ new Set();
81
+ for (const k of [...keys, process.env.RISICARE_API_KEY]) if (k) values.add(k);
82
+ if (values.size === 0) return null;
83
+ const ordered = [...values].sort((a, b) => b.length - a.length);
84
+ return new RegExp(ordered.map(escapeRegExp).join("|"), "gi");
85
+ }
86
+ function scrubText(text, keys, limit = 200) {
87
+ let out;
88
+ try {
89
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
90
+ } catch {
91
+ out = typeof text;
92
+ }
93
+ const pattern = keyPattern(keys);
94
+ if (pattern !== null) {
95
+ if (out.includes("%")) {
96
+ const decoded = percentDecode(out);
97
+ pattern.lastIndex = 0;
98
+ if (decoded !== out && pattern.test(decoded)) out = decoded;
99
+ }
100
+ pattern.lastIndex = 0;
101
+ out = out.replace(pattern, KEY_MARKER);
102
+ }
103
+ return cutCodePoints(out.replace(CONTROL, " "), limit);
104
+ }
105
+ function safeUrl(url) {
106
+ try {
107
+ const u = new URL(url);
108
+ const path = u.pathname === "/" && !/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*\//i.test(url) ? "" : u.pathname;
109
+ return `${u.protocol}//${u.host}${path}`;
110
+ } catch {
111
+ return url.split("?")[0].split("#")[0].replace(/\/\/[^/@]*@/, "//");
112
+ }
113
+ }
114
+ function hasCredentials(url) {
115
+ try {
116
+ const u = new URL(url);
117
+ return u.username !== "" || u.password !== "";
118
+ } catch {
119
+ return false;
120
+ }
121
+ }
28
122
 
29
123
  // src/exporters/batch.ts
124
+ var MAX_TIMEOUT_MS = 2 ** 31 - 1;
30
125
  var MAX_BATCH_BYTES = 8 * 1024 * 1024;
31
126
  var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
32
127
 
@@ -103,14 +198,236 @@ var NOOP_SPAN = Object.freeze({
103
198
  }
104
199
  });
105
200
 
201
+ // src/runtime/config.ts
202
+ function resolveFixRuntimeConfig(config) {
203
+ return {
204
+ apiEndpoint: config.apiEndpoint,
205
+ apiKey: config.apiKey,
206
+ enabled: config.enabled ?? true,
207
+ cacheEnabled: config.cacheEnabled ?? true,
208
+ cacheTtlMs: config.cacheTtlMs ?? 3e5,
209
+ cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
210
+ autoRefresh: config.autoRefresh ?? true,
211
+ refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
212
+ dryRun: config.dryRun ?? false,
213
+ abTestingEnabled: config.abTestingEnabled ?? true,
214
+ timeoutMs: config.timeoutMs ?? 1e3,
215
+ debug: config.debug ?? false
216
+ };
217
+ }
218
+ function activeFixFromApiResponse(item) {
219
+ return {
220
+ fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
221
+ deploymentId: item.deployment_id ?? item.deploymentId ?? "",
222
+ errorCode: item.error_code ?? item.errorCode ?? "",
223
+ fixType: item.fix_type ?? item.fixType ?? "prompt",
224
+ config: item.config ?? {},
225
+ trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
226
+ version: item.version ?? 1
227
+ };
228
+ }
229
+
106
230
  // src/runtime/taxonomy.generated.ts
231
+ var CANONICAL_ERROR_CODES = /* @__PURE__ */ new Set([
232
+ "COMMUNICATION.CONTENT.AMBIGUOUS",
233
+ "COMMUNICATION.CONTENT.CORRUPTED",
234
+ "COMMUNICATION.CONTENT.INCOMPATIBLE",
235
+ "COMMUNICATION.CONTENT.MALFORMED",
236
+ "COMMUNICATION.CONTENT.TOO_LARGE",
237
+ "COMMUNICATION.DELIVERY.DELAYED",
238
+ "COMMUNICATION.DELIVERY.DUPLICATED",
239
+ "COMMUNICATION.DELIVERY.EXPIRED",
240
+ "COMMUNICATION.DELIVERY.OUT_OF_ORDER",
241
+ "COMMUNICATION.DELIVERY.UNDELIVERABLE",
242
+ "COMMUNICATION.ROUTING.BROADCAST_STORM",
243
+ "COMMUNICATION.ROUTING.LOOP",
244
+ "COMMUNICATION.ROUTING.NO_ROUTE",
245
+ "COMMUNICATION.ROUTING.PARTITION",
246
+ "COMMUNICATION.ROUTING.WRONG_ROUTE",
247
+ "CONSENSUS.AGREEMENT.INCONSISTENT",
248
+ "CONSENSUS.AGREEMENT.QUORUM_FAILED",
249
+ "CONSENSUS.AGREEMENT.REJECTED",
250
+ "CONSENSUS.AGREEMENT.STALE_VOTE",
251
+ "CONSENSUS.AGREEMENT.TIMEOUT",
252
+ "CONSENSUS.CONFLICT.BIAS",
253
+ "CONSENSUS.CONFLICT.CASCADING",
254
+ "CONSENSUS.CONFLICT.DEADLOCK",
255
+ "CONSENSUS.CONFLICT.RESOLUTION_REJECTED",
256
+ "CONSENSUS.CONFLICT.UNRESOLVED",
257
+ "CONSENSUS.VOTING.ABSTENTION_FLOOD",
258
+ "CONSENSUS.VOTING.COERCED_VOTE",
259
+ "CONSENSUS.VOTING.DUPLICATE_VOTE",
260
+ "CONSENSUS.VOTING.INVALID_VOTE",
261
+ "CONSENSUS.VOTING.SPLIT_VOTE",
262
+ "COORDINATION.HANDOFF.DELAYED",
263
+ "COORDINATION.HANDOFF.DUPLICATED",
264
+ "COORDINATION.HANDOFF.INCOMPLETE",
265
+ "COORDINATION.HANDOFF.LOST",
266
+ "COORDINATION.HANDOFF.WRONG_RECIPIENT",
267
+ "COORDINATION.SYNCHRONIZATION.CLOCK_SKEW",
268
+ "COORDINATION.SYNCHRONIZATION.OUT_OF_ORDER",
269
+ "COORDINATION.SYNCHRONIZATION.RACE_CONDITION",
270
+ "COORDINATION.SYNCHRONIZATION.SPLIT_BRAIN",
271
+ "COORDINATION.SYNCHRONIZATION.VERSION_MISMATCH",
272
+ "COORDINATION.WORKFLOW.CYCLE",
273
+ "COORDINATION.WORKFLOW.DEADLOCK",
274
+ "COORDINATION.WORKFLOW.LIVELOCK",
275
+ "COORDINATION.WORKFLOW.ORPHANED",
276
+ "COORDINATION.WORKFLOW.STARVATION",
277
+ "MEMORY.CONTEXT_WINDOW.DROPPED",
278
+ "MEMORY.CONTEXT_WINDOW.EXCEEDED",
279
+ "MEMORY.CONTEXT_WINDOW.FRAGMENTED",
280
+ "MEMORY.CONTEXT_WINDOW.PRIORITY_ERROR",
281
+ "MEMORY.RETRIEVAL.INCOMPLETE",
282
+ "MEMORY.RETRIEVAL.NOT_FOUND",
283
+ "MEMORY.RETRIEVAL.OUTDATED",
284
+ "MEMORY.RETRIEVAL.TOO_MANY",
285
+ "MEMORY.RETRIEVAL.WRONG_MATCH",
286
+ "MEMORY.STATE.CORRUPTED",
287
+ "MEMORY.STATE.INCONSISTENT",
288
+ "MEMORY.STATE.LOST",
289
+ "MEMORY.STATE.OVERFLOW",
290
+ "MEMORY.STATE.STALE",
291
+ "ORCHESTRATION.DELEGATION.CAPABILITY_MISMATCH",
292
+ "ORCHESTRATION.DELEGATION.CIRCULAR_DELEGATION",
293
+ "ORCHESTRATION.DELEGATION.EXCESSIVE_DEPTH",
294
+ "ORCHESTRATION.DELEGATION.NO_AVAILABLE_AGENT",
295
+ "ORCHESTRATION.DELEGATION.OVERLOADED_AGENT",
296
+ "ORCHESTRATION.LIFECYCLE.CLEANUP_FAILED",
297
+ "ORCHESTRATION.LIFECYCLE.CRASHED",
298
+ "ORCHESTRATION.LIFECYCLE.HUNG",
299
+ "ORCHESTRATION.LIFECYCLE.SPAWN_FAILED",
300
+ "ORCHESTRATION.LIFECYCLE.ZOMBIE",
301
+ "ORCHESTRATION.SCALING.OVERLOADED",
302
+ "ORCHESTRATION.SCALING.QUOTA_EXCEEDED",
303
+ "ORCHESTRATION.SCALING.SCALE_DOWN_FAILED",
304
+ "ORCHESTRATION.SCALING.SCALE_UP_FAILED",
305
+ "ORCHESTRATION.SCALING.UNDERUTILIZED",
306
+ "OUTPUT.FORMAT.ENCODING",
307
+ "OUTPUT.FORMAT.INVALID_JSON",
308
+ "OUTPUT.FORMAT.MALFORMED",
309
+ "OUTPUT.FORMAT.SCHEMA_VIOLATION",
310
+ "OUTPUT.FORMAT.TRUNCATED",
311
+ "OUTPUT.QUALITY.INCOMPLETE",
312
+ "OUTPUT.QUALITY.IRRELEVANT",
313
+ "OUTPUT.QUALITY.REPETITIVE",
314
+ "OUTPUT.QUALITY.UNCLEAR",
315
+ "OUTPUT.QUALITY.VERBOSE",
316
+ "OUTPUT.SAFETY.BIAS",
317
+ "OUTPUT.SAFETY.COPYRIGHT",
318
+ "OUTPUT.SAFETY.HARMFUL_CONTENT",
319
+ "OUTPUT.SAFETY.PII_LEAK",
320
+ "OUTPUT.SAFETY.POLICY_VIOLATION",
321
+ "PERCEPTION.CONTEXT.CONFLICTING",
322
+ "PERCEPTION.CONTEXT.IRRELEVANT",
323
+ "PERCEPTION.CONTEXT.MISSING",
324
+ "PERCEPTION.CONTEXT.OVERFLOW",
325
+ "PERCEPTION.CONTEXT.STALE",
326
+ "PERCEPTION.INPUT.ENCODING",
327
+ "PERCEPTION.INPUT.INJECTION",
328
+ "PERCEPTION.INPUT.MALFORMED",
329
+ "PERCEPTION.INPUT.SCHEMA_MISMATCH",
330
+ "PERCEPTION.INPUT.TRUNCATED",
331
+ "PERCEPTION.PARSING.DATE_FORMAT",
332
+ "PERCEPTION.PARSING.JSON_INVALID",
333
+ "PERCEPTION.PARSING.NUMBER_FORMAT",
334
+ "PERCEPTION.PARSING.REFERENCE_BROKEN",
335
+ "PERCEPTION.PARSING.XML_INVALID",
336
+ "REASONING.DECISION.BIASED",
337
+ "REASONING.DECISION.INDECISIVE",
338
+ "REASONING.DECISION.OSCILLATING",
339
+ "REASONING.DECISION.OVERCONFIDENT",
340
+ "REASONING.DECISION.PREMATURE",
341
+ "REASONING.HALLUCINATION.CAPABILITY",
342
+ "REASONING.HALLUCINATION.CITATION",
343
+ "REASONING.HALLUCINATION.ENTITY",
344
+ "REASONING.HALLUCINATION.FACTUAL",
345
+ "REASONING.HALLUCINATION.TEMPORAL",
346
+ "REASONING.LOGIC.CIRCULAR",
347
+ "REASONING.LOGIC.CONTRADICTION",
348
+ "REASONING.LOGIC.INCOMPLETE",
349
+ "REASONING.LOGIC.INVALID_INFERENCE",
350
+ "REASONING.LOGIC.MISSING_PREMISE",
351
+ "REASONING.PLANNING.INCOMPLETE",
352
+ "REASONING.PLANNING.INFEASIBLE",
353
+ "REASONING.PLANNING.SCOPE_CREEP",
354
+ "REASONING.PLANNING.SUBOPTIMAL",
355
+ "REASONING.PLANNING.UNSAFE",
356
+ "RESOURCES.ACCESS.DENIED",
357
+ "RESOURCES.ACCESS.EXPIRED",
358
+ "RESOURCES.ACCESS.LOCKED",
359
+ "RESOURCES.ACCESS.NOT_FOUND",
360
+ "RESOURCES.ACCESS.REVOKED",
361
+ "RESOURCES.CONTENTION.DEADLOCK",
362
+ "RESOURCES.CONTENTION.OVERFLOW",
363
+ "RESOURCES.CONTENTION.PRIORITY_INVERSION",
364
+ "RESOURCES.CONTENTION.STARVATION",
365
+ "RESOURCES.CONTENTION.THRASHING",
366
+ "RESOURCES.QUOTA.ALLOCATION_FAILED",
367
+ "RESOURCES.QUOTA.EXCEEDED",
368
+ "RESOURCES.QUOTA.LEAK",
369
+ "RESOURCES.QUOTA.STALE",
370
+ "RESOURCES.QUOTA.UNFAIR_DISTRIBUTION",
371
+ "TOOL.EXECUTION.CRASHED",
372
+ "TOOL.EXECUTION.DEPENDENCY_FAILED",
373
+ "TOOL.EXECUTION.RATE_LIMITED",
374
+ "TOOL.EXECUTION.RESOURCE_EXHAUSTED",
375
+ "TOOL.EXECUTION.TIMEOUT",
376
+ "TOOL.INVOCATION.INVALID_ARGS",
377
+ "TOOL.INVOCATION.MISSING_REQUIRED",
378
+ "TOOL.INVOCATION.NOT_FOUND",
379
+ "TOOL.INVOCATION.PERMISSION_DENIED",
380
+ "TOOL.INVOCATION.TYPE_MISMATCH",
381
+ "TOOL.RESULT.EMPTY",
382
+ "TOOL.RESULT.ERROR_IN_RESULT",
383
+ "TOOL.RESULT.PARTIAL",
384
+ "TOOL.RESULT.UNEXPECTED_FORMAT",
385
+ "TOOL.RESULT.UNPARSEABLE"
386
+ ]);
387
+ var CORE_RULES = [
388
+ { re: new RegExp("json", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" },
389
+ { re: new RegExp("encoding", "u"), code: "PERCEPTION.INPUT.ENCODING" },
390
+ { re: new RegExp("injection", "u"), code: "PERCEPTION.INPUT.INJECTION" },
391
+ { re: new RegExp("malformed", "u"), code: "PERCEPTION.INPUT.MALFORMED" },
392
+ { re: new RegExp("hallucin", "u"), code: "REASONING.HALLUCINATION.FACTUAL" },
393
+ { re: new RegExp("contradict", "u"), code: "REASONING.LOGIC.CONTRADICTION" },
394
+ { re: new RegExp("timeout", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
395
+ { re: new RegExp("rate[^\\n]?limit", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
396
+ { re: new RegExp("permission", "u"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
397
+ { re: new RegExp("context[^\\n]+overflow", "u"), code: "MEMORY.CONTEXT_WINDOW.EXCEEDED" },
398
+ { re: new RegExp("state[^\\n]+corrupt", "u"), code: "MEMORY.STATE.CORRUPTED" },
399
+ { re: new RegExp("pii", "u"), code: "OUTPUT.SAFETY.PII_LEAK" },
400
+ { re: new RegExp("deadlock", "u"), code: "COORDINATION.WORKFLOW.DEADLOCK" },
401
+ { re: new RegExp("undeliverable", "u"), code: "COMMUNICATION.DELIVERY.UNDELIVERABLE" },
402
+ { re: new RegExp("crash", "u"), code: "ORCHESTRATION.LIFECYCLE.CRASHED" },
403
+ { re: new RegExp("quorum", "u"), code: "CONSENSUS.AGREEMENT.QUORUM_FAILED" },
404
+ { re: new RegExp("quota[^\\n]+exceed", "u"), code: "RESOURCES.QUOTA.EXCEEDED" }
405
+ ];
107
406
  var SUPPLEMENTAL_RULES = [
108
- { re: new RegExp("timeout|timedout|aborted", "i"), code: "TOOL.EXECUTION.TIMEOUT" },
109
- { re: new RegExp("rate.?limit|\\b429\\b|too many requests", "i"), code: "TOOL.EXECUTION.RATE_LIMITED" },
110
- { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "i"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
111
- { re: new RegExp("\\bauth|unauthorized|forbidden|permission|\\b401\\b|\\b403\\b", "i"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
112
- { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "i"), code: "PERCEPTION.PARSING.JSON_INVALID" }
407
+ { re: new RegExp("timeout|timedout|aborted", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
408
+ { re: new RegExp("rate[^\\n]?limit|(?<![\\p{L}\\p{N}_])429(?![\\p{L}\\p{N}_])|too many requests", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
409
+ { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "u"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
410
+ { re: new RegExp("(?<![\\p{L}\\p{N}_])auth|unauthorized|forbidden|permission|(?<![\\p{L}\\p{N}_])401(?![\\p{L}\\p{N}_])|(?<![\\p{L}\\p{N}_])403(?![\\p{L}\\p{N}_])", "u"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
411
+ { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" }
113
412
  ];
413
+ var GENERIC_FALLBACK = "TOOL.EXECUTION.CRASHED";
414
+
415
+ // src/runtime/interceptors.ts
416
+ function classifyError(error) {
417
+ const message = String(error?.message ?? "").toLowerCase();
418
+ for (const rule of CORE_RULES) {
419
+ if (rule.re.test(message)) {
420
+ return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
421
+ }
422
+ }
423
+ const haystack = `${error?.constructor?.name ?? "Error"} ${String(error?.message ?? "")}`.toLowerCase();
424
+ for (const rule of SUPPLEMENTAL_RULES) {
425
+ if (rule.re.test(haystack)) {
426
+ return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
427
+ }
428
+ }
429
+ return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : "";
430
+ }
114
431
 
115
432
  // src/context/storage.ts
116
433
  function storage() {
@@ -119,11 +436,1176 @@ function storage() {
119
436
  function getContext() {
120
437
  return storage().getStore() ?? {};
121
438
  }
439
+ function runWithContext(overrides, fn) {
440
+ const parent = getContext();
441
+ const merged = { ...parent, ...overrides };
442
+ return storage().run(merged, fn);
443
+ }
444
+
445
+ // src/tracer.ts
446
+ function attachErrorCode(span, error) {
447
+ try {
448
+ const ownMessage = error !== null && typeof error === "object" ? error.message : void 0;
449
+ const err = error instanceof Error ? error : new Error(typeof ownMessage === "string" ? ownMessage : String(error));
450
+ const code = classifyError(err);
451
+ if (code) {
452
+ span.setAttribute("error.code", code);
453
+ }
454
+ } catch {
455
+ }
456
+ }
457
+
458
+ // src/version.ts
459
+ var SDK_VERSION = "0.9.0";
460
+
461
+ // src/exporters/http.ts
462
+ var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
463
+ var RETRY_AFTER_CEILING_MS = 1e4;
464
+ var REFUSAL_BACKOFF_BASE_MS = 1e3;
465
+ var REFUSAL_NO_HINT = -1;
466
+ var MISROUTE_WARN_WINDOW_MS = 3e5;
467
+ var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
468
+ var FAILURE_WARN_WINDOW_MS = 3e5;
469
+ var HttpExporter = class {
470
+ name = "http";
471
+ _endpoint;
472
+ _apiKey;
473
+ _projectId;
474
+ _environment;
475
+ _timeoutMs;
476
+ _maxRetries;
477
+ _compress;
478
+ // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
479
+ // a "30-second prod restart" scenario: with default 1s batch flush a
480
+ // 5-failure threshold opens the circuit ~5s into an outage and the 60s
481
+ // cooldown gives the gateway time to come back before the half-open
482
+ // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
483
+ _consecutiveFailures = 0;
484
+ _lastMisrouteWarnAt = -Infinity;
485
+ _lastFailureWarnAt = -Infinity;
486
+ /**
487
+ * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
488
+ * 'unknown'). `null` after a success. A new kind in the same outage writes one more
489
+ * WARNING, also inside the window.
490
+ */
491
+ _failureKind = null;
492
+ /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
493
+ _safeEndpoint;
494
+ /** The endpoint holds userinfo. `fetch` refuses such a URL. */
495
+ _endpointHasCredentials;
496
+ /** The calls in progress, by their batch, so that `abort(spans)` stops the right one. */
497
+ _calls = /* @__PURE__ */ new Map();
498
+ /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */
499
+ _acks = /* @__PURE__ */ new WeakMap();
500
+ /** The spans of each finished call that could not be serialized, by its batch. */
501
+ _unserializable = /* @__PURE__ */ new WeakMap();
502
+ _circuitOpenUntil = 0;
503
+ _circuitBreakerThreshold = 5;
504
+ _circuitBreakerCooldownMs = 6e4;
505
+ constructor(options) {
506
+ this._endpoint = options.endpoint.replace(/\/+$/, "");
507
+ this._apiKey = options.apiKey;
508
+ this._projectId = options.projectId;
509
+ this._environment = options.environment;
510
+ this._timeoutMs = options.timeoutMs ?? 5e3;
511
+ this._maxRetries = options.maxRetries ?? 3;
512
+ this._compress = options.compress ?? false;
513
+ this._safeEndpoint = safeUrl(this._endpoint);
514
+ this._endpointHasCredentials = hasCredentials(this._endpoint);
515
+ }
516
+ /**
517
+ * Network or error text for a log line: the endpoint as `safeUrl` gives it, and no
518
+ * form of the API key (`utils/scrub.ts`).
519
+ */
520
+ _scrub(text, limit = 200) {
521
+ let out;
522
+ try {
523
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
524
+ } catch {
525
+ out = typeof text;
526
+ }
527
+ if (this._safeEndpoint !== this._endpoint) out = out.split(this._endpoint).join(this._safeEndpoint);
528
+ return scrubText(out, [this._apiKey], limit);
529
+ }
530
+ /** Hide the key from `util.inspect` and `console.log` of the exporter. */
531
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
532
+ return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
533
+ }
534
+ /** The most requests that one `export()` call sends (`maxRetries`). */
535
+ get attemptsPerExport() {
536
+ return this._maxRetries;
537
+ }
538
+ /**
539
+ * Returns the counts of the ack that the `export()` call for `spans` received, and clears
540
+ * them. The answer is kept per batch, not on the instance: two processors that share this
541
+ * exporter cannot read each other's ack across an `await`.
542
+ */
543
+ takeAck(spans) {
544
+ const ack = this._acks.get(spans) ?? null;
545
+ this._acks.delete(spans);
546
+ return ack;
547
+ }
548
+ /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
549
+ takeUnserializable(spans) {
550
+ const bad = this._unserializable.get(spans) ?? [];
551
+ this._unserializable.delete(spans);
552
+ return bad;
553
+ }
554
+ /**
555
+ * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
556
+ * request, its retries and its backoff sleep. The batch processor calls it when
557
+ * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
558
+ * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
559
+ * logs no WARNING.
560
+ */
561
+ abort(spans) {
562
+ if (spans !== void 0) this._calls.get(spans)?.cancel.abort();
563
+ else for (const call of this._calls.values()) call.cancel.abort();
564
+ }
565
+ /**
566
+ * Send one batch. The limits are the request timeout and `maxRetries`.
567
+ *
568
+ * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
569
+ * cuts a request that is already sent. A short flush budget that cut the request made a
570
+ * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
571
+ * the server stored the same spans again. Only `abort()` stops the call, and only
572
+ * `shutdown()` calls it.
573
+ */
574
+ async export(spans) {
575
+ if (spans.length === 0) return "success" /* SUCCESS */;
576
+ const call = {
577
+ cancel: new AbortController(),
578
+ refusalAfterMs: null,
579
+ misroute: null,
580
+ noRetry: false,
581
+ status: null,
582
+ error: null
583
+ };
584
+ this._calls.set(spans, call);
585
+ try {
586
+ return await this._export(spans, call);
587
+ } finally {
588
+ this._calls.delete(spans);
589
+ }
590
+ }
591
+ async _export(spans, call) {
592
+ const cancelled = call.cancel.signal;
593
+ const parts = [];
594
+ const bad = [];
595
+ let errorClass = "";
596
+ for (const span of spans) {
597
+ try {
598
+ parts.push(JSON.stringify(span.toPayload()));
599
+ } catch (e) {
600
+ bad.push(span);
601
+ errorClass ||= e instanceof Error ? e.name : typeof e;
602
+ }
603
+ }
604
+ if (bad.length > 0) {
605
+ this._unserializable.set(spans, bad);
606
+ warn(
607
+ `Risicare: ${bad.length} of ${spans.length} span(s) in this batch could not be serialized (${errorClass}), for example an attribute with a BigInt or a circular reference. They are not sent and are counted as dropped (reason=unacknowledged).`
608
+ );
609
+ }
610
+ if (parts.length === 0) return "success" /* SUCCESS */;
611
+ const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
612
+ const now = Date.now();
613
+ let isHalfOpen = false;
614
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
615
+ if (now < this._circuitOpenUntil) {
616
+ return "failure" /* FAILURE */;
617
+ }
618
+ isHalfOpen = true;
619
+ }
620
+ const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
621
+ let attempts = 0;
622
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
623
+ call.refusalAfterMs = null;
624
+ call.misroute = null;
625
+ call.noRetry = false;
626
+ call.status = null;
627
+ call.error = null;
628
+ attempts++;
629
+ const result = await this._sendRequest(payload, parts.length, call, spans);
630
+ if (cancelled.aborted) {
631
+ this._acks.delete(spans);
632
+ return "failure" /* FAILURE */;
633
+ }
634
+ if (result === "success" /* SUCCESS */) {
635
+ this._consecutiveFailures = 0;
636
+ this._failureKind = null;
637
+ return result;
638
+ }
639
+ if (call.misroute !== null || call.noRetry) break;
640
+ if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
641
+ if (attempt < maxAttempts - 1) {
642
+ const refusal = call.refusalAfterMs;
643
+ const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
644
+ await sleep(delay, cancelled);
645
+ if (cancelled.aborted) return "failure" /* FAILURE */;
646
+ }
647
+ }
648
+ if (call.refusalAfterMs !== null) {
649
+ warn(
650
+ `Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ${attempts} attempt(s). This is a healthy server shedding load, not an outage. This export of the batch failed; the circuit breaker does not count it. Reduce batch size or export rate if it persists.`
651
+ );
652
+ return "failure" /* FAILURE */;
653
+ }
654
+ const misroute = call.misroute;
655
+ if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
656
+ this._lastMisrouteWarnAt = Date.now();
657
+ warn(
658
+ `Risicare: spans are NOT reaching ${this._safeEndpoint}. It answered POST /v1/spans with ${misroute}. That is not the Risicare ingest gateway, so the endpoint is probably wrong (for example the dashboard URL instead of the ingest gateway URL). The SDK does not follow redirects, and this batch is counted as NOT delivered. Set endpoint or RISICARE_ENDPOINT to the ingest gateway URL.`
659
+ );
660
+ }
661
+ this._consecutiveFailures++;
662
+ if (misroute === null && !call.noRetry) {
663
+ const status = call.status;
664
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
665
+ let write = false;
666
+ if (this._consecutiveFailures === 1 || this._failureKind === null) {
667
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
668
+ this._lastFailureWarnAt = Date.now();
669
+ write = true;
670
+ }
671
+ this._failureKind = kind;
672
+ } else if (kind !== this._failureKind) {
673
+ this._failureKind = kind;
674
+ write = true;
675
+ }
676
+ if (write) this._warnOutage(kind, status, call.error);
677
+ }
678
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
679
+ this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
680
+ warn(
681
+ `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
682
+ );
683
+ }
684
+ return "failure" /* FAILURE */;
685
+ }
686
+ /** The outage WARNING for one kind of failure. */
687
+ _warnOutage(kind, status, error) {
688
+ const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
689
+ const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
690
+ if (kind === "auth") {
691
+ warn(
692
+ `${where}: it answered HTTP ${status}. The endpoint refused the API key. Check the apiKey (or RISICARE_API_KEY) and the project it belongs to. ${tail}`
693
+ );
694
+ } else if (kind === "http") {
695
+ warn(
696
+ `${where}: it answered HTTP ${status}. The server did not take the batch. Check the endpoint and the server. ${tail} Set debug: true to see each attempt.`
697
+ );
698
+ } else if (kind === "none" && this._endpointHasCredentials) {
699
+ warn(
700
+ `${where}: no answer (${error}). The endpoint URL holds credentials (a user name or a password before the host), and fetch does not send a request to such a URL. Remove the credentials from the endpoint URL. ${tail}`
701
+ );
702
+ } else if (kind === "none") {
703
+ warn(
704
+ `${where}: no answer (${error}). The endpoint cannot be reached, or it did not answer in time. Check the endpoint and the network. ${tail} Set debug: true to see each attempt.`
705
+ );
706
+ } else {
707
+ warn(
708
+ `${where}: the export failed. Common causes: an invalid apiKey or an unreachable endpoint. ${tail} Set debug: true to see each attempt.`
709
+ );
710
+ }
711
+ }
712
+ /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
713
+ _noteMisroute(call, answer) {
714
+ call.misroute = this._scrub(answer, 300);
715
+ debug(`Ingest misroute: ${call.misroute}`);
716
+ return "failure" /* FAILURE */;
717
+ }
718
+ /**
719
+ * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
720
+ *
721
+ * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
722
+ * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
723
+ * parse.
724
+ */
725
+ _noteRefusal(call, status, retryAfterRaw) {
726
+ if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
727
+ let delay = REFUSAL_NO_HINT;
728
+ if (retryAfterRaw) {
729
+ const secs = Number(retryAfterRaw);
730
+ if (Number.isFinite(secs) && secs >= 0) {
731
+ delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
732
+ }
733
+ }
734
+ call.refusalAfterMs = delay;
735
+ debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
736
+ return true;
737
+ }
738
+ async _sendRequest(body, spansSent, call, spans) {
739
+ const cancelled = call.cancel.signal;
740
+ const timeoutMs = this._timeoutMs;
741
+ const url = `${this._endpoint}/v1/spans`;
742
+ const headers = {
743
+ "Content-Type": "application/json",
744
+ "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
745
+ // F-SDKVER-001 parity. Python's ingest exporter has always sent
746
+ // `X-Risicare-SDK-Version`; JS sent only a User-Agent, so the two SDKs
747
+ // disagreed about how a client identifies itself. A parser-free header is
748
+ // strictly easier for the gateway to consume than picking a version out of
749
+ // a UA string.
750
+ "X-Risicare-SDK-Version": SDK_VERSION
751
+ };
752
+ if (this._apiKey) {
753
+ headers["Authorization"] = `Bearer ${this._apiKey}`;
754
+ }
755
+ let payload = body;
756
+ if (this._compress && payload.length > 1024) {
757
+ try {
758
+ const { gzipSync } = await import("zlib");
759
+ payload = gzipSync(Buffer.from(payload));
760
+ headers["Content-Encoding"] = "gzip";
761
+ } catch (e) {
762
+ debug(`Gzip compression failed, sending uncompressed: ${this._scrub(e)}`);
763
+ }
764
+ }
765
+ const controller = new AbortController();
766
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
767
+ const onCancel = () => controller.abort();
768
+ cancelled.addEventListener("abort", onCancel, { once: true });
769
+ if (cancelled.aborted) controller.abort();
770
+ try {
771
+ const response = await fetch(url, {
772
+ method: "POST",
773
+ headers,
774
+ body: payload,
775
+ signal: controller.signal,
776
+ // Never follow: a redirect is a misroute (see MISROUTE_WARN_WINDOW_MS). Node returns
777
+ // the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.
778
+ redirect: "manual"
779
+ });
780
+ call.status = response.status;
781
+ const redirected = response.type === "opaqueredirect";
782
+ if (redirected || response.status >= 300 && response.status < 400) {
783
+ const location = response.headers?.get?.("Location");
784
+ const target = location ? this._scrub(location, 1e3) : "no Location header";
785
+ return this._noteMisroute(call, `HTTP ${response.status || "3xx"}, a redirect to ${target}`);
786
+ }
787
+ if (response.status >= 200 && response.status < 300) {
788
+ const ack = await checkAck(response, spansSent, (t) => this._scrub(t, 1e3));
789
+ if (ack === null) {
790
+ if (controller.signal.aborted) {
791
+ call.status = null;
792
+ call.error = `timeout after ${timeoutMs} ms`;
793
+ debug(`HTTP export timeout: the ack body did not arrive within ${timeoutMs} ms`);
794
+ return "timeout" /* TIMEOUT */;
795
+ }
796
+ return this._noteMisroute(
797
+ call,
798
+ `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
799
+ );
800
+ }
801
+ if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
802
+ if (ack.final) call.noRetry = true;
803
+ return ack.result;
804
+ } else if (response.status === 408 || response.status === 504) {
805
+ debug(`HTTP export timeout: ${response.status}`);
806
+ return "timeout" /* TIMEOUT */;
807
+ }
808
+ this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
809
+ debug(`HTTP export failed: ${response.status}`);
810
+ return "failure" /* FAILURE */;
811
+ } catch (e) {
812
+ const cause = e instanceof Error ? e.cause : void 0;
813
+ call.error = controller.signal.aborted ? `timeout after ${timeoutMs} ms` : typeof cause?.code === "string" ? cause.code : e instanceof Error ? e.name : "Error";
814
+ debug(`HTTP export error: ${this._scrub(e)}`);
815
+ return "failure" /* FAILURE */;
816
+ } finally {
817
+ clearTimeout(timeoutId);
818
+ cancelled.removeEventListener("abort", onCancel);
819
+ }
820
+ }
821
+ shutdown() {
822
+ }
823
+ };
824
+ function sleep(ms, signal) {
825
+ return new Promise((resolve) => {
826
+ if (signal?.aborted) return resolve();
827
+ const done = () => {
828
+ clearTimeout(timer);
829
+ signal?.removeEventListener("abort", done);
830
+ resolve();
831
+ };
832
+ const timer = setTimeout(done, ms);
833
+ signal?.addEventListener("abort", done, { once: true });
834
+ });
835
+ }
836
+ function asCount(v) {
837
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
838
+ }
839
+ var MAX_ACK_REASONS = 3;
840
+ var MAX_ACK_REASON_CHARS = 200;
841
+ function oneLine(text) {
842
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ");
843
+ }
844
+ function ackReasons(body) {
845
+ const reasons = [];
846
+ const errors = body.errors;
847
+ if (Array.isArray(errors)) {
848
+ for (const entry of errors) {
849
+ const text = entry?.error;
850
+ if (typeof text !== "string" || text.length === 0) continue;
851
+ const cut = oneLine(text).slice(0, MAX_ACK_REASON_CHARS);
852
+ if (!reasons.includes(cut)) reasons.push(cut);
853
+ if (reasons.length === MAX_ACK_REASONS) break;
854
+ }
855
+ }
856
+ if (reasons.length === 0) {
857
+ const message = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || "";
858
+ if (message) reasons.push(oneLine(message).slice(0, MAX_ACK_REASON_CHARS));
859
+ }
860
+ return reasons.length === 0 ? "No reason was returned." : `Reasons: ${reasons.join("; ")}`;
861
+ }
862
+ async function checkAck(response, spansSent, scrub) {
863
+ let payload;
864
+ try {
865
+ payload = await response.json();
866
+ } catch {
867
+ return null;
868
+ }
869
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
870
+ return null;
871
+ }
872
+ const body = payload;
873
+ const accepted = asCount(body.accepted);
874
+ const rejected = asCount(body.rejected);
875
+ if (accepted === void 0 || rejected === void 0) return null;
876
+ const counts = { accepted, rejected };
877
+ if (accepted === 0 && rejected === 0 && spansSent > 0) {
878
+ warn(
879
+ `Risicare: the backend acknowledged 0 of ${spansSent} span(s): its ack counts no span as accepted or rejected. This batch is counted as NOT delivered.`
880
+ );
881
+ return { result: "failure" /* FAILURE */, counts, final: true };
882
+ }
883
+ if (rejected === 0) return { result: "success" /* SUCCESS */, counts, final: false };
884
+ const total = accepted + rejected;
885
+ if (accepted === 0) {
886
+ warn(
887
+ `Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. Rejected spans are permanently lost and are NOT retried. ${scrub(ackReasons(body))}`
888
+ );
889
+ return { result: "success" /* SUCCESS */, counts, final: false };
890
+ }
891
+ warn(
892
+ `Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ${accepted} were stored. Those ${rejected} are permanently lost and are NOT retried. ${scrub(ackReasons(body))}`
893
+ );
894
+ return { result: "success" /* SUCCESS */, counts, final: false };
895
+ }
896
+
897
+ // src/utils/read-safely.ts
898
+ var logged = /* @__PURE__ */ new Set();
899
+ var LOGGED_MAX = 1e3;
900
+ function className(error) {
901
+ if (error !== null && typeof error === "object") {
902
+ const name = error.constructor?.name;
903
+ if (typeof name === "string" && name) return name;
904
+ }
905
+ return typeof error;
906
+ }
907
+ function responseReadFailed(provider, site, error, span) {
908
+ try {
909
+ const cls = className(error);
910
+ span?.setAttribute("risicare.observer_error", cls);
911
+ if (!getDebug()) return;
912
+ const key = `${provider}\0${site}\0${cls}`;
913
+ if (logged.has(key) || logged.size >= LOGGED_MAX) return;
914
+ logged.add(key);
915
+ debug(`could not read the ${provider} response in ${site} (${cls}); the span keeps fewer facts`);
916
+ } catch {
917
+ }
918
+ }
919
+ function readResponseSafely(provider, site, span, read) {
920
+ try {
921
+ read();
922
+ } catch (error) {
923
+ responseReadFailed(provider, site, error, span);
924
+ }
925
+ }
926
+
927
+ // src/utils/stream-proxy.ts
928
+ var HANDOFF = /* @__PURE__ */ new Set(["tee", "toReadableStream", "getReader", "pipeTo", "pipeThrough"]);
929
+ function isAbortError(e) {
930
+ return e instanceof Error && e.name === "AbortError";
931
+ }
932
+ var CallObservation = class {
933
+ constructor(span, opts) {
934
+ this.span = span;
935
+ this.opts = opts;
936
+ this.state = getProviderSpanState();
937
+ this.state.open.add(this);
938
+ }
939
+ ended = false;
940
+ streamSeen = false;
941
+ chunks = 0;
942
+ /** Calls of `next()` that have not settled. */
943
+ pending = 0;
944
+ /** The provider's abort signal fired; what the stream does next decides. */
945
+ abortSeen = false;
946
+ /** Subscriptions on the promise (`then`, `await`) that have not settled. */
947
+ subscriptions = 0;
948
+ /** Removes the abort listener from the provider's signal. */
949
+ unlisten;
950
+ /** Held objects (promise, stream, iterators) that nobody collected yet. */
951
+ live = 0;
952
+ /** True when the registry holds at least one object of this call. */
953
+ held = false;
954
+ /** The shared state (globals.ts); read once, so that `end()` cannot throw on it. */
955
+ state;
956
+ hold(obj) {
957
+ const registry = this.state.registry;
958
+ if (!registry) return;
959
+ this.live++;
960
+ this.held = true;
961
+ registry.register(obj, this);
962
+ }
963
+ /** Nobody can reach one of the held objects any more. */
964
+ release() {
965
+ this.live--;
966
+ this.endIfUnreachable();
967
+ }
968
+ /**
969
+ * THE one check after a counter goes down. The span ends as `garbage` only
970
+ * when nobody can reach ANY held object, no `next()` waits and no
971
+ * subscription on the promise waits for the provider: an `await` keeps the
972
+ * request, not our Proxy, so a call in flight must not end here. Every path
973
+ * that lowers a counter calls this AFTER it records its facts. A `next()`
974
+ * that settled with a chunk after the last proxy was collected left the
975
+ * span open until `shutdown()` when only `release()` checked (PR #49,
976
+ * second review: 2,000 of 2,000 spans open).
977
+ */
978
+ endIfUnreachable() {
979
+ if (this.held && this.live <= 0 && this.pending <= 0 && this.subscriptions <= 0) this.end("garbage");
980
+ }
981
+ /** A subscription on the promise (`then`, `withResponse`, `asResponse`) starts. */
982
+ subscribed() {
983
+ this.subscriptions++;
984
+ }
985
+ /** A subscription settled. Call it after the value or the error is recorded. */
986
+ unsubscribed() {
987
+ this.subscriptions--;
988
+ this.endIfUnreachable();
989
+ }
990
+ /** A `next()` starts. */
991
+ nextCalled() {
992
+ this.pending++;
993
+ }
994
+ chunk(value) {
995
+ if (this.ended) return;
996
+ this.chunks++;
997
+ const onChunk = this.opts.onChunk;
998
+ if (onChunk) readResponseSafely(this.opts.provider, "stream chunk", this.span, () => onChunk(value));
999
+ }
1000
+ value(value) {
1001
+ const onValue = this.opts.onValue;
1002
+ if (onValue && !this.ended) readResponseSafely(this.opts.provider, "response", this.span, () => onValue(value));
1003
+ this.end("response");
1004
+ }
1005
+ /**
1006
+ * The provider's abort signal fired. That alone does not end the span: a
1007
+ * provider may go on (Cohere's `controller.abort()` does not stop its
1008
+ * stream). What the stream does next decides: an `AbortError`, or the end
1009
+ * with no chunk after the abort, is an abort; a chunk after it means the
1010
+ * abort did nothing.
1011
+ */
1012
+ abortRequested() {
1013
+ this.abortSeen = true;
1014
+ }
1015
+ /** A `next()` settled with `r`. */
1016
+ settled(r) {
1017
+ this.pending--;
1018
+ if (r && r.done) this.end(this.abortSeen ? "abort" : "done");
1019
+ else {
1020
+ this.abortSeen = false;
1021
+ this.chunk(r?.value);
1022
+ }
1023
+ this.endIfUnreachable();
1024
+ }
1025
+ /** A `next()` failed (it threw, or its promise rejected). */
1026
+ failed(e) {
1027
+ this.pending--;
1028
+ this.end(isAbortError(e) ? "abort" : "error", e);
1029
+ this.endIfUnreachable();
1030
+ }
1031
+ end(reason, error) {
1032
+ if (this.ended) return;
1033
+ this.ended = true;
1034
+ try {
1035
+ this.state.open.delete(this);
1036
+ } catch (e) {
1037
+ responseReadFailed(this.opts.provider, "provider span state", e, this.span);
1038
+ }
1039
+ if (this.unlisten) {
1040
+ const unlisten = this.unlisten;
1041
+ this.unlisten = void 0;
1042
+ readResponseSafely(this.opts.provider, "stream abort signal", this.span, unlisten);
1043
+ }
1044
+ if ((reason === "garbage" || reason === "shutdown") && this.abortSeen) reason = "abort";
1045
+ try {
1046
+ const span = this.span;
1047
+ const isStream = this.streamSeen || this.opts.stream === true;
1048
+ if (isStream) {
1049
+ const beforeEnd = this.opts.beforeEnd;
1050
+ if (beforeEnd && this.streamSeen) readResponseSafely(this.opts.provider, "stream end", span, beforeEnd);
1051
+ span.setAttribute("stream.chunk_count", this.chunks);
1052
+ }
1053
+ if (reason !== "response" && (isStream || reason === "garbage" || reason === "shutdown" || reason === "handoff")) {
1054
+ span.setAttribute("stream.end_reason", reason);
1055
+ }
1056
+ const aborted = reason === "abort" || isAbortError(error);
1057
+ if (error !== void 0) {
1058
+ span.recordException(error instanceof Error ? error : String(error));
1059
+ attachErrorCode(span, error);
1060
+ } else if (aborted) {
1061
+ span.setStatus("error" /* ERROR */, "AbortError: the stream was aborted");
1062
+ }
1063
+ if (aborted) {
1064
+ span.setAttribute("risicare.cancelled", true);
1065
+ span.setAttribute("risicare.cancel_type", "AbortError");
1066
+ }
1067
+ span.end();
1068
+ } catch (e) {
1069
+ responseReadFailed(this.opts.provider, "span end", e, this.span);
1070
+ }
1071
+ }
1072
+ };
1073
+ function notObserved(provider, span, error) {
1074
+ responseReadFailed(provider, "the provider span state; this call is not observed", error, span);
1075
+ }
1076
+ function endQuietly(span) {
1077
+ try {
1078
+ span.end();
1079
+ } catch {
1080
+ }
1081
+ }
1082
+ function listenForAbort(signal, obs) {
1083
+ if (signal.aborted) {
1084
+ obs.abortRequested();
1085
+ return;
1086
+ }
1087
+ const onAbort = () => obs.abortRequested();
1088
+ signal.addEventListener("abort", onAbort, { once: true });
1089
+ obs.unlisten = () => signal.removeEventListener("abort", onAbort);
1090
+ }
1091
+ function abortSignalOf(stream) {
1092
+ const s = stream;
1093
+ return usableSignal(s.controller?.signal ?? s.abortController?.signal);
1094
+ }
1095
+ function usableSignal(signal) {
1096
+ return signal && typeof signal.addEventListener === "function" ? signal : void 0;
1097
+ }
1098
+ function frozenOwn(target, prop) {
1099
+ const d = Object.getOwnPropertyDescriptor(target, prop);
1100
+ return !!d && d.configurable === false && "value" in d && d.writable === false;
1101
+ }
1102
+ function forwarder(target) {
1103
+ const bound = /* @__PURE__ */ new Map();
1104
+ return (prop) => {
1105
+ const v = Reflect.get(target, prop, target);
1106
+ if (typeof v !== "function" || prop === "constructor" || Object.prototype.hasOwnProperty.call(target, prop)) return v;
1107
+ let b = bound.get(v);
1108
+ if (!b) {
1109
+ b = v.bind(target);
1110
+ bound.set(v, b);
1111
+ }
1112
+ return b;
1113
+ };
1114
+ }
1115
+ function iteratorMethod(src, prop, obs) {
1116
+ const fn = Reflect.get(src, prop, src);
1117
+ if (typeof fn !== "function") return void 0;
1118
+ if (prop === "next") {
1119
+ return (...a) => {
1120
+ obs.nextCalled();
1121
+ let p;
1122
+ try {
1123
+ p = Reflect.apply(fn, src, a);
1124
+ } catch (e) {
1125
+ obs.failed(e);
1126
+ throw e;
1127
+ }
1128
+ return Promise.resolve(p).then(
1129
+ (r) => {
1130
+ obs.settled(r);
1131
+ return r;
1132
+ },
1133
+ (e) => {
1134
+ obs.failed(e);
1135
+ throw e;
1136
+ }
1137
+ );
1138
+ };
1139
+ }
1140
+ if (prop === "return") {
1141
+ return (...a) => {
1142
+ obs.end("return");
1143
+ return Reflect.apply(fn, src, a);
1144
+ };
1145
+ }
1146
+ return (...a) => {
1147
+ obs.end("error", a[0]);
1148
+ return Reflect.apply(fn, src, a);
1149
+ };
1150
+ }
1151
+ function traceIterator(it, obs) {
1152
+ const forward = forwarder(it);
1153
+ const proxy = new Proxy(it, {
1154
+ get(target, prop) {
1155
+ if ((prop === "next" || prop === "return" || prop === "throw") && !frozenOwn(target, prop)) {
1156
+ return iteratorMethod(target, prop, obs);
1157
+ }
1158
+ if (prop === Symbol.asyncIterator && !frozenOwn(target, prop)) {
1159
+ const own = Reflect.get(target, prop, target);
1160
+ return typeof own === "function" ? () => proxy : own;
1161
+ }
1162
+ return forward(prop);
1163
+ }
1164
+ });
1165
+ obs.hold(proxy);
1166
+ return proxy;
1167
+ }
1168
+ function traceStream(stream, obs) {
1169
+ obs.streamSeen = true;
1170
+ let signal;
1171
+ readResponseSafely(obs.opts.provider, "stream abort signal", obs.span, () => {
1172
+ const own = obs.opts.abortSignal;
1173
+ signal = own ? usableSignal(own()) : abortSignalOf(stream);
1174
+ });
1175
+ if (signal) listenForAbort(signal, obs);
1176
+ const forward = forwarder(stream);
1177
+ const proxy = new Proxy(stream, {
1178
+ get(target, prop) {
1179
+ if (frozenOwn(target, prop)) return Reflect.get(target, prop, target);
1180
+ if (prop === Symbol.asyncIterator) {
1181
+ const fn = Reflect.get(target, prop, target);
1182
+ if (typeof fn !== "function") return fn;
1183
+ return (...a) => {
1184
+ const it = Reflect.apply(fn, target, a);
1185
+ return it === target ? proxy : traceIterator(it, obs);
1186
+ };
1187
+ }
1188
+ if (prop === "next" || prop === "return" || prop === "throw") {
1189
+ return iteratorMethod(target, prop, obs);
1190
+ }
1191
+ if (prop === "values") {
1192
+ const fn = Reflect.get(target, prop, target);
1193
+ if (typeof fn !== "function") return fn;
1194
+ return (...a) => traceIterator(Reflect.apply(fn, target, a), obs);
1195
+ }
1196
+ if (prop === "cancel") {
1197
+ const fn = Reflect.get(target, prop, target);
1198
+ if (typeof fn !== "function") return fn;
1199
+ return (...a) => {
1200
+ const r = Reflect.apply(fn, target, a);
1201
+ Promise.resolve(r).then(
1202
+ () => obs.end("abort"),
1203
+ () => {
1204
+ }
1205
+ );
1206
+ return r;
1207
+ };
1208
+ }
1209
+ if (HANDOFF.has(prop)) {
1210
+ const fn = Reflect.get(target, prop, target);
1211
+ if (typeof fn !== "function") return fn;
1212
+ return (...a) => {
1213
+ obs.end("handoff");
1214
+ return Reflect.apply(fn, target, a);
1215
+ };
1216
+ }
1217
+ return forward(prop);
1218
+ }
1219
+ });
1220
+ obs.hold(proxy);
1221
+ return proxy;
1222
+ }
1223
+ function isAsyncIterable(v) {
1224
+ return !!v && (typeof v === "object" || typeof v === "function") && typeof v[Symbol.asyncIterator] === "function";
1225
+ }
1226
+ function mapper(obs) {
1227
+ let done = false;
1228
+ let mapped;
1229
+ return (v) => {
1230
+ if (done) return mapped;
1231
+ done = true;
1232
+ mapped = v;
1233
+ try {
1234
+ const trace = (s) => isAsyncIterable(s) ? traceStream(s, obs) : s;
1235
+ if (obs.opts.wrapValue) {
1236
+ mapped = obs.opts.wrapValue(v, trace, (q, onValue) => traceSidePromise(q, obs, onValue));
1237
+ if (mapped === v) obs.value(v);
1238
+ else if (mapped && (typeof mapped === "object" || typeof mapped === "function")) obs.hold(mapped);
1239
+ } else if (isAsyncIterable(v)) mapped = traceStream(v, obs);
1240
+ else obs.value(v);
1241
+ } catch (e) {
1242
+ responseReadFailed(obs.opts.provider, "stream proxy", e, obs.span);
1243
+ mapped = v;
1244
+ obs.end("response");
1245
+ }
1246
+ return mapped;
1247
+ };
1248
+ }
1249
+ function traceSidePromise(promise, obs, onValue) {
1250
+ return tracePromise(
1251
+ promise,
1252
+ obs,
1253
+ (v) => {
1254
+ if (!obs.streamSeen && !obs.ended) {
1255
+ readResponseSafely(obs.opts.provider, "response", obs.span, () => onValue(v));
1256
+ obs.end("done");
1257
+ }
1258
+ return v;
1259
+ },
1260
+ (e) => {
1261
+ if (!obs.streamSeen) obs.end("error", e);
1262
+ }
1263
+ );
1264
+ }
1265
+ function tracePromise(promise, obs, map = mapper(obs), fail = (e) => obs.end("error", e)) {
1266
+ const forward = forwarder(promise);
1267
+ const t = promise;
1268
+ const then = (f, r) => {
1269
+ obs.subscribed();
1270
+ let observed;
1271
+ try {
1272
+ observed = t.then(
1273
+ (v) => {
1274
+ const m = map(v);
1275
+ obs.unsubscribed();
1276
+ return m;
1277
+ },
1278
+ (e) => {
1279
+ fail(e);
1280
+ obs.unsubscribed();
1281
+ throw e;
1282
+ }
1283
+ );
1284
+ } catch (e) {
1285
+ fail(e);
1286
+ obs.unsubscribed();
1287
+ throw e;
1288
+ }
1289
+ return observed.then(
1290
+ typeof f === "function" ? f : void 0,
1291
+ typeof r === "function" ? r : void 0
1292
+ );
1293
+ };
1294
+ const proxy = new Proxy(promise, {
1295
+ get(target, prop) {
1296
+ if (frozenOwn(target, prop)) return Reflect.get(target, prop, target);
1297
+ if (prop === "then") return then;
1298
+ if (prop === "catch") return (r) => then(void 0, r);
1299
+ if (prop === "finally") {
1300
+ return (f) => typeof f !== "function" ? then() : then(
1301
+ (v) => Promise.resolve(f()).then(() => v),
1302
+ (e) => Promise.resolve(f()).then(() => {
1303
+ throw e;
1304
+ })
1305
+ );
1306
+ }
1307
+ if (prop === "withResponse" || prop === "withRawResponse") {
1308
+ const fn = Reflect.get(target, prop, target);
1309
+ if (typeof fn !== "function") return fn;
1310
+ return (...a) => {
1311
+ obs.subscribed();
1312
+ return Reflect.apply(fn, target, a).then(
1313
+ (o) => {
1314
+ let out = o;
1315
+ if (o && typeof o === "object" && "data" in o) {
1316
+ try {
1317
+ out = { ...o, data: map(o.data) };
1318
+ } catch (e) {
1319
+ responseReadFailed(obs.opts.provider, "withResponse", e, obs.span);
1320
+ }
1321
+ }
1322
+ obs.unsubscribed();
1323
+ return out;
1324
+ },
1325
+ (e) => {
1326
+ obs.end("error", e);
1327
+ obs.unsubscribed();
1328
+ throw e;
1329
+ }
1330
+ );
1331
+ };
1332
+ }
1333
+ if (prop === "asResponse") {
1334
+ const fn = Reflect.get(target, prop, target);
1335
+ if (typeof fn !== "function") return fn;
1336
+ return (...a) => {
1337
+ const p = Reflect.apply(fn, target, a);
1338
+ obs.subscribed();
1339
+ Promise.resolve(p).then(
1340
+ () => {
1341
+ obs.end("handoff");
1342
+ obs.unsubscribed();
1343
+ },
1344
+ (e) => {
1345
+ obs.end("error", e);
1346
+ obs.unsubscribed();
1347
+ }
1348
+ );
1349
+ return p;
1350
+ };
1351
+ }
1352
+ return forward(prop);
1353
+ }
1354
+ });
1355
+ obs.hold(proxy);
1356
+ return proxy;
1357
+ }
1358
+ function observeProviderCall(span, opts, call) {
1359
+ let obs;
1360
+ try {
1361
+ obs = new CallObservation(span, opts);
1362
+ } catch (e) {
1363
+ notObserved(opts.provider, span, e);
1364
+ try {
1365
+ return runWithContext({ span }, call);
1366
+ } finally {
1367
+ endQuietly(span);
1368
+ }
1369
+ }
1370
+ let result;
1371
+ try {
1372
+ result = runWithContext({ span }, call);
1373
+ } catch (e) {
1374
+ obs.end("error", e);
1375
+ throw e;
1376
+ }
1377
+ try {
1378
+ if (result && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
1379
+ return tracePromise(result, obs);
1380
+ }
1381
+ return mapper(obs)(result);
1382
+ } catch (e) {
1383
+ responseReadFailed(opts.provider, "stream proxy", e, span);
1384
+ obs.end("response");
1385
+ return result;
1386
+ }
1387
+ }
122
1388
 
123
1389
  // src/runtime/applier.ts
124
1390
  import { createHash } from "crypto";
125
1391
 
1392
+ // src/runtime/loader.ts
1393
+ var FixLoader = class _FixLoader {
1394
+ _config;
1395
+ _cache;
1396
+ _refreshTimer = null;
1397
+ _lastLoadTime = null;
1398
+ _consecutiveFailures = 0;
1399
+ _circuitOpenUntil = 0;
1400
+ _onLoadCallbacks = [];
1401
+ // The HTTP status of the last load that got a non-2xx answer; null otherwise.
1402
+ _lastStatus = null;
1403
+ // Circuit breaker settings
1404
+ static CIRCUIT_BREAKER_THRESHOLD = 3;
1405
+ static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
1406
+ constructor(config, cache) {
1407
+ this._config = resolveFixRuntimeConfig(config);
1408
+ this._cache = cache;
1409
+ }
1410
+ /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */
1411
+ _scrub(error) {
1412
+ let out;
1413
+ try {
1414
+ out = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1415
+ } catch {
1416
+ out = typeof error;
1417
+ }
1418
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
1419
+ if (endpoint && safeUrl(endpoint) !== endpoint) out = out.split(endpoint).join(safeUrl(endpoint));
1420
+ return scrubText(out, [this._config.apiKey]);
1421
+ }
1422
+ /**
1423
+ * The WARNING for a failed first load: the request URL with no userinfo, no
1424
+ * query and no key, the HTTP status or the error class, and that tracing is
1425
+ * not affected. Never the error text: it can echo the URL with its query.
1426
+ */
1427
+ _firstLoadWarning(error) {
1428
+ let cause;
1429
+ if (this._lastStatus !== null) {
1430
+ cause = `HTTP ${this._lastStatus}`;
1431
+ } else {
1432
+ cause = error instanceof Error ? error.name : typeof error;
1433
+ const code = error?.cause?.code;
1434
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code)) cause += ` (${code})`;
1435
+ }
1436
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
1437
+ return scrubText(
1438
+ `The first load of the fixes from ${safeUrl(endpoint)}/v1/fixes/active failed (${cause}). No fix is applied until a later load succeeds. Tracing is not affected.`,
1439
+ [this._config.apiKey],
1440
+ 500
1441
+ );
1442
+ }
1443
+ /** Hide the key from `util.inspect` and `console.log` of the loader. */
1444
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1445
+ return "FixLoader {}";
1446
+ }
1447
+ /** Timestamp of last successful load. */
1448
+ get lastLoadTime() {
1449
+ return this._lastLoadTime;
1450
+ }
1451
+ /**
1452
+ * Start the loader: perform initial load and start background refresh.
1453
+ *
1454
+ * Never throws — failures are logged and the runtime degrades gracefully.
1455
+ */
1456
+ start() {
1457
+ try {
1458
+ if (!this._config.enabled) {
1459
+ debug("Fix runtime disabled, skipping loader start");
1460
+ return;
1461
+ }
1462
+ if (!this._config.apiKey) {
1463
+ warn("No API key configured, fixes will not be loaded");
1464
+ return;
1465
+ }
1466
+ this.loadSync().catch((e) => {
1467
+ warn(this._firstLoadWarning(e));
1468
+ });
1469
+ if (this._config.autoRefresh) {
1470
+ this._startRefreshInterval();
1471
+ }
1472
+ } catch (e) {
1473
+ debug(`FixLoader.start error: ${this._scrub(e)}`);
1474
+ }
1475
+ }
1476
+ /** Stop the loader: clear the refresh interval. */
1477
+ stop() {
1478
+ try {
1479
+ if (this._refreshTimer !== null) {
1480
+ clearInterval(this._refreshTimer);
1481
+ this._refreshTimer = null;
1482
+ }
1483
+ } catch (e) {
1484
+ debug(`FixLoader.stop error: ${this._scrub(e)}`);
1485
+ }
1486
+ }
1487
+ /**
1488
+ * Register a callback invoked after each successful load.
1489
+ */
1490
+ onLoad(callback) {
1491
+ this._onLoadCallbacks.push(callback);
1492
+ }
1493
+ /**
1494
+ * Load fixes from the API.
1495
+ *
1496
+ * Name kept as "loadSync" for parity with the Python SDK, but this
1497
+ * returns a Promise in JS (there's no synchronous fetch in Node.js).
1498
+ */
1499
+ async loadSync() {
1500
+ if (!this._config.apiKey) {
1501
+ return [];
1502
+ }
1503
+ const now = Date.now();
1504
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
1505
+ debug("Fix loader circuit breaker open \u2014 skipping load");
1506
+ return this._cache.getAll();
1507
+ }
1508
+ this._lastStatus = null;
1509
+ try {
1510
+ const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
1511
+ const url = `${endpoint}/v1/fixes/active`;
1512
+ const controller = new AbortController();
1513
+ const timeoutId = setTimeout(
1514
+ () => controller.abort(),
1515
+ this._config.timeoutMs
1516
+ );
1517
+ const response = await fetch(url, {
1518
+ method: "GET",
1519
+ headers: {
1520
+ "Authorization": `Bearer ${this._config.apiKey}`,
1521
+ "Content-Type": "application/json",
1522
+ "X-Risicare-SDK-Version": SDK_VERSION
1523
+ },
1524
+ signal: controller.signal
1525
+ });
1526
+ clearTimeout(timeoutId);
1527
+ if (!response.ok) {
1528
+ this._lastStatus = response.status;
1529
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1530
+ }
1531
+ const data = await response.json();
1532
+ const fixes = this._parseResponse(data);
1533
+ this._onLoadSuccess(fixes);
1534
+ return fixes;
1535
+ } catch (e) {
1536
+ this._onLoadFailure(e);
1537
+ throw e;
1538
+ }
1539
+ }
1540
+ /** Get currently cached fixes without hitting the API. */
1541
+ getCached() {
1542
+ return this._cache.getAll();
1543
+ }
1544
+ // ─── Private ────────────────────────────────────────────────────────────
1545
+ _parseResponse(data) {
1546
+ const fixes = [];
1547
+ const items = data.fixes ?? data.data ?? [];
1548
+ if (!Array.isArray(items)) return fixes;
1549
+ for (const item of items) {
1550
+ try {
1551
+ if (item && typeof item === "object") {
1552
+ fixes.push(activeFixFromApiResponse(item));
1553
+ }
1554
+ } catch (e) {
1555
+ debug(`Failed to parse fix item: ${this._scrub(e)}`);
1556
+ }
1557
+ }
1558
+ return fixes;
1559
+ }
1560
+ _onLoadSuccess(fixes) {
1561
+ this._lastLoadTime = Date.now();
1562
+ this._consecutiveFailures = 0;
1563
+ this._cache.setAll(fixes);
1564
+ for (const callback of this._onLoadCallbacks) {
1565
+ try {
1566
+ callback(fixes);
1567
+ } catch (e) {
1568
+ debug(`Load callback error: ${this._scrub(e)}`);
1569
+ }
1570
+ }
1571
+ debug(`Loaded ${fixes.length} active fixes`);
1572
+ }
1573
+ _onLoadFailure(error) {
1574
+ this._consecutiveFailures++;
1575
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
1576
+ this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
1577
+ warn(
1578
+ `Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
1579
+ );
1580
+ } else {
1581
+ debug(
1582
+ `Fix load failed (attempt ${this._consecutiveFailures}): ${this._scrub(error)}`
1583
+ );
1584
+ }
1585
+ }
1586
+ _startRefreshInterval() {
1587
+ const tick = () => {
1588
+ this.loadSync().catch((e) => {
1589
+ debug(`Background fix refresh failed: ${this._scrub(e)}`);
1590
+ });
1591
+ };
1592
+ this._refreshTimer = setInterval(
1593
+ () => {
1594
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
1595
+ return;
1596
+ }
1597
+ tick();
1598
+ },
1599
+ this._config.refreshIntervalMs
1600
+ );
1601
+ this._refreshTimer.unref();
1602
+ debug("Started fix refresh interval");
1603
+ }
1604
+ };
1605
+
126
1606
  // src/client.ts
1607
+ var SCORE_MAX_WAITING = 1e3;
1608
+ var SCORE_CAP_REASON = `not sent: ${SCORE_MAX_WAITING} scores wait for a free slot`;
127
1609
  function requireTracer() {
128
1610
  const tracer = getTracer();
129
1611
  if (!tracer) {
@@ -181,6 +1663,23 @@ function calculateCost(model, promptTokens, completionTokens) {
181
1663
  return inputCost + outputCost;
182
1664
  }
183
1665
 
1666
+ // src/utils/token-usage.ts
1667
+ function tokenCount(value) {
1668
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
1669
+ }
1670
+ function recordTokenUsage(span, counts, model) {
1671
+ const promptTokens = tokenCount(counts.prompt);
1672
+ const completionTokens = tokenCount(counts.completion);
1673
+ const bothKnown = promptTokens !== void 0 && completionTokens !== void 0;
1674
+ const totalTokens = tokenCount(counts.total) ?? (bothKnown ? promptTokens + completionTokens : void 0);
1675
+ const costUsd = model && bothKnown ? calculateCost(model, promptTokens, completionTokens) : void 0;
1676
+ span.setLlmFields({ promptTokens, completionTokens, totalTokens, costUsd });
1677
+ if (promptTokens !== void 0) span.setAttribute("gen_ai.usage.prompt_tokens", promptTokens);
1678
+ if (completionTokens !== void 0) span.setAttribute("gen_ai.usage.completion_tokens", completionTokens);
1679
+ if (totalTokens !== void 0) span.setAttribute("gen_ai.usage.total_tokens", totalTokens);
1680
+ if (costUsd !== void 0) span.setAttribute("llm.cost.total_usd", costUsd);
1681
+ }
1682
+
184
1683
  // src/utils/assert-client.ts
185
1684
  function assertClient(patcherName, client) {
186
1685
  if (client === null || client === void 0) {
@@ -224,20 +1723,7 @@ function enrichFromResponse(span, response) {
224
1723
  }
225
1724
  if (response.id) span.setAttribute("gen_ai.response.id", response.id);
226
1725
  if (usage) {
227
- const promptTokens = usage.prompt_tokens ?? usage.promptTokens ?? 0;
228
- const completionTokens = usage.completion_tokens ?? usage.completionTokens ?? 0;
229
- const totalTokens = usage.total_tokens ?? usage.totalTokens ?? promptTokens + completionTokens;
230
- const cost = model ?? span.llmModel ? calculateCost(model ?? span.llmModel ?? "", promptTokens, completionTokens) : void 0;
231
- span.setLlmFields({
232
- promptTokens,
233
- completionTokens,
234
- totalTokens,
235
- costUsd: cost
236
- });
237
- span.setAttribute("gen_ai.usage.prompt_tokens", promptTokens);
238
- span.setAttribute("gen_ai.usage.completion_tokens", completionTokens);
239
- span.setAttribute("gen_ai.usage.total_tokens", totalTokens);
240
- if (cost !== void 0) span.setAttribute("llm.cost.total_usd", cost);
1726
+ recordTokenUsage(span, { prompt: usage.prompt_tokens ?? usage.promptTokens, completion: usage.completion_tokens ?? usage.completionTokens, total: usage.total_tokens ?? usage.totalTokens }, model ?? span.llmModel);
241
1727
  }
242
1728
  const choices = response.choices;
243
1729
  if (choices?.[0]?.finishReason ?? choices?.[0]?.finish_reason) {
@@ -245,7 +1731,8 @@ function enrichFromResponse(span, response) {
245
1731
  choices[0].finishReason ?? choices[0].finish_reason
246
1732
  ]);
247
1733
  }
248
- } catch {
1734
+ } catch (error) {
1735
+ responseReadFailed("mistral", "enrichFromResponse", error, span);
249
1736
  }
250
1737
  }
251
1738
  function createCompleteProxy(original) {
@@ -270,7 +1757,7 @@ function createCompleteProxy(original) {
270
1757
  const result = original.apply(this, args);
271
1758
  if (result && typeof result.then === "function") {
272
1759
  return result.then((response) => {
273
- if (response) enrichFromResponse(span, response);
1760
+ if (response) readResponseSafely("mistral", "enrichFromResponse", span, () => enrichFromResponse(span, response));
274
1761
  return response;
275
1762
  });
276
1763
  }
@@ -300,40 +1787,24 @@ function createStreamProxy(original) {
300
1787
  });
301
1788
  span.setLlmFields({ provider: "mistral", model });
302
1789
  enrichSpanFromRequest(span, params);
303
- const resultPromise = original.apply(this, args);
304
- if (resultPromise && typeof resultPromise.then === "function") {
305
- return resultPromise.then((stream) => {
306
- if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
307
- span.end();
308
- return stream;
1790
+ let lastUsage;
1791
+ return observeProviderCall(
1792
+ span,
1793
+ {
1794
+ provider: "mistral",
1795
+ stream: true,
1796
+ // Mistral sends usage in the final chunk's data.
1797
+ onChunk: (chunk) => {
1798
+ const c = chunk;
1799
+ const data = c?.data ?? c;
1800
+ if (data?.usage) lastUsage = data.usage;
1801
+ },
1802
+ beforeEnd: () => {
1803
+ if (lastUsage) enrichFromResponse(span, { usage: lastUsage, model });
309
1804
  }
310
- let chunkCount = 0;
311
- let lastUsage;
312
- return {
313
- async *[Symbol.asyncIterator]() {
314
- try {
315
- for await (const chunk of stream) {
316
- chunkCount++;
317
- const data = chunk.data ?? chunk;
318
- if (data.usage) lastUsage = data.usage;
319
- yield chunk;
320
- }
321
- } catch (error) {
322
- span.recordException(error instanceof Error ? error : String(error));
323
- throw error;
324
- } finally {
325
- if (lastUsage) {
326
- enrichFromResponse(span, { usage: lastUsage, model });
327
- }
328
- span.setAttribute("stream.chunk_count", chunkCount);
329
- span.end();
330
- }
331
- }
332
- };
333
- });
334
- }
335
- span.end();
336
- return resultPromise;
1805
+ },
1806
+ () => original.apply(this, args)
1807
+ );
337
1808
  };
338
1809
  }
339
1810
  function patchMistral(client) {