risicare 0.7.0 → 0.8.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 +282 -63
  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 +1113 -176
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +234 -42
  25. package/dist/index.d.ts +234 -42
  26. package/dist/index.js +1113 -176
  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
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/frameworks/langgraph.ts
@@ -51,8 +61,80 @@ function debug(msg) {
51
61
  `);
52
62
  }
53
63
  }
64
+ function warn(msg) {
65
+ process.stderr.write(`[risicare] WARNING: ${msg}
66
+ `);
67
+ }
68
+
69
+ // src/utils/text.ts
70
+ function cutCodePoints(text, max) {
71
+ if (text.length <= max) return text;
72
+ let units = 0;
73
+ for (let points = 0; points < max && units < text.length; points++) {
74
+ units += text.codePointAt(units) > 65535 ? 2 : 1;
75
+ }
76
+ return text.slice(0, units);
77
+ }
78
+
79
+ // src/utils/scrub.ts
80
+ var KEY_MARKER = "[REDACTED-KEY]";
81
+ var CONTROL = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]", "g");
82
+ function escapeRegExp(text) {
83
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
84
+ }
85
+ function percentDecode(text) {
86
+ try {
87
+ return decodeURIComponent(text);
88
+ } catch {
89
+ return text.replace(/%([0-9A-Fa-f]{2})/g, (_m, hex) => String.fromCharCode(parseInt(hex, 16)));
90
+ }
91
+ }
92
+ function keyPattern(keys) {
93
+ const values = /* @__PURE__ */ new Set();
94
+ for (const k of [...keys, process.env.RISICARE_API_KEY]) if (k) values.add(k);
95
+ if (values.size === 0) return null;
96
+ const ordered = [...values].sort((a, b) => b.length - a.length);
97
+ return new RegExp(ordered.map(escapeRegExp).join("|"), "gi");
98
+ }
99
+ function scrubText(text, keys, limit = 200) {
100
+ let out;
101
+ try {
102
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
103
+ } catch {
104
+ out = typeof text;
105
+ }
106
+ const pattern = keyPattern(keys);
107
+ if (pattern !== null) {
108
+ if (out.includes("%")) {
109
+ const decoded = percentDecode(out);
110
+ pattern.lastIndex = 0;
111
+ if (decoded !== out && pattern.test(decoded)) out = decoded;
112
+ }
113
+ pattern.lastIndex = 0;
114
+ out = out.replace(pattern, KEY_MARKER);
115
+ }
116
+ return cutCodePoints(out.replace(CONTROL, " "), limit);
117
+ }
118
+ function safeUrl(url) {
119
+ try {
120
+ const u = new URL(url);
121
+ const path = u.pathname === "/" && !/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*\//i.test(url) ? "" : u.pathname;
122
+ return `${u.protocol}//${u.host}${path}`;
123
+ } catch {
124
+ return url.split("?")[0].split("#")[0].replace(/\/\/[^/@]*@/, "//");
125
+ }
126
+ }
127
+ function hasCredentials(url) {
128
+ try {
129
+ const u = new URL(url);
130
+ return u.username !== "" || u.password !== "";
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
54
135
 
55
136
  // src/exporters/batch.ts
137
+ var MAX_TIMEOUT_MS = 2 ** 31 - 1;
56
138
  var MAX_BATCH_BYTES = 8 * 1024 * 1024;
57
139
  var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
58
140
 
@@ -129,13 +211,61 @@ var NOOP_SPAN = Object.freeze({
129
211
  }
130
212
  });
131
213
 
214
+ // src/runtime/config.ts
215
+ function resolveFixRuntimeConfig(config) {
216
+ return {
217
+ apiEndpoint: config.apiEndpoint,
218
+ apiKey: config.apiKey,
219
+ enabled: config.enabled ?? true,
220
+ cacheEnabled: config.cacheEnabled ?? true,
221
+ cacheTtlMs: config.cacheTtlMs ?? 3e5,
222
+ cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
223
+ autoRefresh: config.autoRefresh ?? true,
224
+ refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
225
+ dryRun: config.dryRun ?? false,
226
+ abTestingEnabled: config.abTestingEnabled ?? true,
227
+ timeoutMs: config.timeoutMs ?? 1e3,
228
+ debug: config.debug ?? false
229
+ };
230
+ }
231
+ function activeFixFromApiResponse(item) {
232
+ return {
233
+ fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
234
+ deploymentId: item.deployment_id ?? item.deploymentId ?? "",
235
+ errorCode: item.error_code ?? item.errorCode ?? "",
236
+ fixType: item.fix_type ?? item.fixType ?? "prompt",
237
+ config: item.config ?? {},
238
+ trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
239
+ version: item.version ?? 1
240
+ };
241
+ }
242
+
132
243
  // src/runtime/taxonomy.generated.ts
244
+ var CORE_RULES = [
245
+ { re: new RegExp("json", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" },
246
+ { re: new RegExp("encoding", "u"), code: "PERCEPTION.INPUT.ENCODING" },
247
+ { re: new RegExp("injection", "u"), code: "PERCEPTION.INPUT.INJECTION" },
248
+ { re: new RegExp("malformed", "u"), code: "PERCEPTION.INPUT.MALFORMED" },
249
+ { re: new RegExp("hallucin", "u"), code: "REASONING.HALLUCINATION.FACTUAL" },
250
+ { re: new RegExp("contradict", "u"), code: "REASONING.LOGIC.CONTRADICTION" },
251
+ { re: new RegExp("timeout", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
252
+ { re: new RegExp("rate[^\\n]?limit", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
253
+ { re: new RegExp("permission", "u"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
254
+ { re: new RegExp("context[^\\n]+overflow", "u"), code: "MEMORY.CONTEXT_WINDOW.EXCEEDED" },
255
+ { re: new RegExp("state[^\\n]+corrupt", "u"), code: "MEMORY.STATE.CORRUPTED" },
256
+ { re: new RegExp("pii", "u"), code: "OUTPUT.SAFETY.PII_LEAK" },
257
+ { re: new RegExp("deadlock", "u"), code: "COORDINATION.WORKFLOW.DEADLOCK" },
258
+ { re: new RegExp("undeliverable", "u"), code: "COMMUNICATION.DELIVERY.UNDELIVERABLE" },
259
+ { re: new RegExp("crash", "u"), code: "ORCHESTRATION.LIFECYCLE.CRASHED" },
260
+ { re: new RegExp("quorum", "u"), code: "CONSENSUS.AGREEMENT.QUORUM_FAILED" },
261
+ { re: new RegExp("quota[^\\n]+exceed", "u"), code: "RESOURCES.QUOTA.EXCEEDED" }
262
+ ];
133
263
  var SUPPLEMENTAL_RULES = [
134
- { re: new RegExp("timeout|timedout|aborted", "i"), code: "TOOL.EXECUTION.TIMEOUT" },
135
- { re: new RegExp("rate.?limit|\\b429\\b|too many requests", "i"), code: "TOOL.EXECUTION.RATE_LIMITED" },
136
- { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "i"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
137
- { re: new RegExp("\\bauth|unauthorized|forbidden|permission|\\b401\\b|\\b403\\b", "i"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
138
- { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "i"), code: "PERCEPTION.PARSING.JSON_INVALID" }
264
+ { re: new RegExp("timeout|timedout|aborted", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
265
+ { re: new RegExp("rate[^\\n]?limit|(?<![\\p{L}\\p{N}_])429(?![\\p{L}\\p{N}_])|too many requests", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
266
+ { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "u"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
267
+ { 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" },
268
+ { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" }
139
269
  ];
140
270
 
141
271
  // src/context/storage.ts
@@ -151,10 +281,665 @@ function runWithContext(overrides, fn) {
151
281
  return storage().run(merged, fn);
152
282
  }
153
283
 
284
+ // src/version.ts
285
+ var SDK_VERSION = "0.8.0";
286
+
287
+ // src/exporters/http.ts
288
+ var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
289
+ var RETRY_AFTER_CEILING_MS = 1e4;
290
+ var REFUSAL_BACKOFF_BASE_MS = 1e3;
291
+ var REFUSAL_NO_HINT = -1;
292
+ var MISROUTE_WARN_WINDOW_MS = 3e5;
293
+ var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
294
+ var FAILURE_WARN_WINDOW_MS = 3e5;
295
+ var HttpExporter = class {
296
+ name = "http";
297
+ _endpoint;
298
+ _apiKey;
299
+ _projectId;
300
+ _environment;
301
+ _timeoutMs;
302
+ _maxRetries;
303
+ _compress;
304
+ // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
305
+ // a "30-second prod restart" scenario: with default 1s batch flush a
306
+ // 5-failure threshold opens the circuit ~5s into an outage and the 60s
307
+ // cooldown gives the gateway time to come back before the half-open
308
+ // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
309
+ _consecutiveFailures = 0;
310
+ _lastMisrouteWarnAt = -Infinity;
311
+ _lastFailureWarnAt = -Infinity;
312
+ /**
313
+ * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
314
+ * 'unknown'). `null` after a success. A new kind in the same outage writes one more
315
+ * WARNING, also inside the window.
316
+ */
317
+ _failureKind = null;
318
+ /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
319
+ _safeEndpoint;
320
+ /** The endpoint holds userinfo. `fetch` refuses such a URL. */
321
+ _endpointHasCredentials;
322
+ /** The calls in progress, by their batch, so that `abort(spans)` stops the right one. */
323
+ _calls = /* @__PURE__ */ new Map();
324
+ /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */
325
+ _acks = /* @__PURE__ */ new WeakMap();
326
+ /** The spans of each finished call that could not be serialized, by its batch. */
327
+ _unserializable = /* @__PURE__ */ new WeakMap();
328
+ _circuitOpenUntil = 0;
329
+ _circuitBreakerThreshold = 5;
330
+ _circuitBreakerCooldownMs = 6e4;
331
+ constructor(options) {
332
+ this._endpoint = options.endpoint.replace(/\/+$/, "");
333
+ this._apiKey = options.apiKey;
334
+ this._projectId = options.projectId;
335
+ this._environment = options.environment;
336
+ this._timeoutMs = options.timeoutMs ?? 5e3;
337
+ this._maxRetries = options.maxRetries ?? 3;
338
+ this._compress = options.compress ?? false;
339
+ this._safeEndpoint = safeUrl(this._endpoint);
340
+ this._endpointHasCredentials = hasCredentials(this._endpoint);
341
+ }
342
+ /**
343
+ * Network or error text for a log line: the endpoint as `safeUrl` gives it, and no
344
+ * form of the API key (`utils/scrub.ts`).
345
+ */
346
+ _scrub(text, limit = 200) {
347
+ let out;
348
+ try {
349
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
350
+ } catch {
351
+ out = typeof text;
352
+ }
353
+ if (this._safeEndpoint !== this._endpoint) out = out.split(this._endpoint).join(this._safeEndpoint);
354
+ return scrubText(out, [this._apiKey], limit);
355
+ }
356
+ /** Hide the key from `util.inspect` and `console.log` of the exporter. */
357
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
358
+ return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
359
+ }
360
+ /** The most requests that one `export()` call sends (`maxRetries`). */
361
+ get attemptsPerExport() {
362
+ return this._maxRetries;
363
+ }
364
+ /**
365
+ * Returns the counts of the ack that the `export()` call for `spans` received, and clears
366
+ * them. The answer is kept per batch, not on the instance: two processors that share this
367
+ * exporter cannot read each other's ack across an `await`.
368
+ */
369
+ takeAck(spans) {
370
+ const ack = this._acks.get(spans) ?? null;
371
+ this._acks.delete(spans);
372
+ return ack;
373
+ }
374
+ /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
375
+ takeUnserializable(spans) {
376
+ const bad = this._unserializable.get(spans) ?? [];
377
+ this._unserializable.delete(spans);
378
+ return bad;
379
+ }
380
+ /**
381
+ * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
382
+ * request, its retries and its backoff sleep. The batch processor calls it when
383
+ * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
384
+ * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
385
+ * logs no WARNING.
386
+ */
387
+ abort(spans) {
388
+ if (spans !== void 0) this._calls.get(spans)?.cancel.abort();
389
+ else for (const call of this._calls.values()) call.cancel.abort();
390
+ }
391
+ /**
392
+ * Send one batch. The limits are the request timeout and `maxRetries`.
393
+ *
394
+ * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
395
+ * cuts a request that is already sent. A short flush budget that cut the request made a
396
+ * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
397
+ * the server stored the same spans again. Only `abort()` stops the call, and only
398
+ * `shutdown()` calls it.
399
+ */
400
+ async export(spans) {
401
+ if (spans.length === 0) return "success" /* SUCCESS */;
402
+ const call = {
403
+ cancel: new AbortController(),
404
+ refusalAfterMs: null,
405
+ misroute: null,
406
+ noRetry: false,
407
+ status: null,
408
+ error: null
409
+ };
410
+ this._calls.set(spans, call);
411
+ try {
412
+ return await this._export(spans, call);
413
+ } finally {
414
+ this._calls.delete(spans);
415
+ }
416
+ }
417
+ async _export(spans, call) {
418
+ const cancelled = call.cancel.signal;
419
+ const parts = [];
420
+ const bad = [];
421
+ let errorClass = "";
422
+ for (const span of spans) {
423
+ try {
424
+ parts.push(JSON.stringify(span.toPayload()));
425
+ } catch (e) {
426
+ bad.push(span);
427
+ errorClass ||= e instanceof Error ? e.name : typeof e;
428
+ }
429
+ }
430
+ if (bad.length > 0) {
431
+ this._unserializable.set(spans, bad);
432
+ warn(
433
+ `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).`
434
+ );
435
+ }
436
+ if (parts.length === 0) return "success" /* SUCCESS */;
437
+ const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
438
+ const now = Date.now();
439
+ let isHalfOpen = false;
440
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
441
+ if (now < this._circuitOpenUntil) {
442
+ return "failure" /* FAILURE */;
443
+ }
444
+ isHalfOpen = true;
445
+ }
446
+ const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
447
+ let attempts = 0;
448
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
449
+ call.refusalAfterMs = null;
450
+ call.misroute = null;
451
+ call.noRetry = false;
452
+ call.status = null;
453
+ call.error = null;
454
+ attempts++;
455
+ const result = await this._sendRequest(payload, parts.length, call, spans);
456
+ if (cancelled.aborted) {
457
+ this._acks.delete(spans);
458
+ return "failure" /* FAILURE */;
459
+ }
460
+ if (result === "success" /* SUCCESS */) {
461
+ this._consecutiveFailures = 0;
462
+ this._failureKind = null;
463
+ return result;
464
+ }
465
+ if (call.misroute !== null || call.noRetry) break;
466
+ if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
467
+ if (attempt < maxAttempts - 1) {
468
+ const refusal = call.refusalAfterMs;
469
+ const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
470
+ await sleep(delay, cancelled);
471
+ if (cancelled.aborted) return "failure" /* FAILURE */;
472
+ }
473
+ }
474
+ if (call.refusalAfterMs !== null) {
475
+ warn(
476
+ `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.`
477
+ );
478
+ return "failure" /* FAILURE */;
479
+ }
480
+ const misroute = call.misroute;
481
+ if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
482
+ this._lastMisrouteWarnAt = Date.now();
483
+ warn(
484
+ `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.`
485
+ );
486
+ }
487
+ this._consecutiveFailures++;
488
+ if (misroute === null && !call.noRetry) {
489
+ const status = call.status;
490
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
491
+ let write = false;
492
+ if (this._consecutiveFailures === 1 || this._failureKind === null) {
493
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
494
+ this._lastFailureWarnAt = Date.now();
495
+ write = true;
496
+ }
497
+ this._failureKind = kind;
498
+ } else if (kind !== this._failureKind) {
499
+ this._failureKind = kind;
500
+ write = true;
501
+ }
502
+ if (write) this._warnOutage(kind, status, call.error);
503
+ }
504
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
505
+ this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
506
+ warn(
507
+ `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
508
+ );
509
+ }
510
+ return "failure" /* FAILURE */;
511
+ }
512
+ /** The outage WARNING for one kind of failure. */
513
+ _warnOutage(kind, status, error) {
514
+ const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
515
+ const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
516
+ if (kind === "auth") {
517
+ warn(
518
+ `${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}`
519
+ );
520
+ } else if (kind === "http") {
521
+ warn(
522
+ `${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.`
523
+ );
524
+ } else if (kind === "none" && this._endpointHasCredentials) {
525
+ warn(
526
+ `${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}`
527
+ );
528
+ } else if (kind === "none") {
529
+ warn(
530
+ `${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.`
531
+ );
532
+ } else {
533
+ warn(
534
+ `${where}: the export failed. Common causes: an invalid apiKey or an unreachable endpoint. ${tail} Set debug: true to see each attempt.`
535
+ );
536
+ }
537
+ }
538
+ /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
539
+ _noteMisroute(call, answer) {
540
+ call.misroute = this._scrub(answer, 300);
541
+ debug(`Ingest misroute: ${call.misroute}`);
542
+ return "failure" /* FAILURE */;
543
+ }
544
+ /**
545
+ * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
546
+ *
547
+ * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
548
+ * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
549
+ * parse.
550
+ */
551
+ _noteRefusal(call, status, retryAfterRaw) {
552
+ if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
553
+ let delay = REFUSAL_NO_HINT;
554
+ if (retryAfterRaw) {
555
+ const secs = Number(retryAfterRaw);
556
+ if (Number.isFinite(secs) && secs >= 0) {
557
+ delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
558
+ }
559
+ }
560
+ call.refusalAfterMs = delay;
561
+ debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
562
+ return true;
563
+ }
564
+ async _sendRequest(body, spansSent, call, spans) {
565
+ const cancelled = call.cancel.signal;
566
+ const timeoutMs = this._timeoutMs;
567
+ const url = `${this._endpoint}/v1/spans`;
568
+ const headers = {
569
+ "Content-Type": "application/json",
570
+ "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
571
+ // F-SDKVER-001 parity. Python's ingest exporter has always sent
572
+ // `X-Risicare-SDK-Version`; JS sent only a User-Agent, so the two SDKs
573
+ // disagreed about how a client identifies itself. A parser-free header is
574
+ // strictly easier for the gateway to consume than picking a version out of
575
+ // a UA string.
576
+ "X-Risicare-SDK-Version": SDK_VERSION
577
+ };
578
+ if (this._apiKey) {
579
+ headers["Authorization"] = `Bearer ${this._apiKey}`;
580
+ }
581
+ let payload = body;
582
+ if (this._compress && payload.length > 1024) {
583
+ try {
584
+ const { gzipSync } = await import("zlib");
585
+ payload = gzipSync(Buffer.from(payload));
586
+ headers["Content-Encoding"] = "gzip";
587
+ } catch (e) {
588
+ debug(`Gzip compression failed, sending uncompressed: ${this._scrub(e)}`);
589
+ }
590
+ }
591
+ const controller = new AbortController();
592
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
593
+ const onCancel = () => controller.abort();
594
+ cancelled.addEventListener("abort", onCancel, { once: true });
595
+ if (cancelled.aborted) controller.abort();
596
+ try {
597
+ const response = await fetch(url, {
598
+ method: "POST",
599
+ headers,
600
+ body: payload,
601
+ signal: controller.signal,
602
+ // Never follow: a redirect is a misroute (see MISROUTE_WARN_WINDOW_MS). Node returns
603
+ // the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.
604
+ redirect: "manual"
605
+ });
606
+ call.status = response.status;
607
+ const redirected = response.type === "opaqueredirect";
608
+ if (redirected || response.status >= 300 && response.status < 400) {
609
+ const location = response.headers?.get?.("Location");
610
+ const target = location ? this._scrub(location, 1e3) : "no Location header";
611
+ return this._noteMisroute(call, `HTTP ${response.status || "3xx"}, a redirect to ${target}`);
612
+ }
613
+ if (response.status >= 200 && response.status < 300) {
614
+ const ack = await checkAck(response, spansSent, (t) => this._scrub(t, 1e3));
615
+ if (ack === null) {
616
+ if (controller.signal.aborted) {
617
+ call.status = null;
618
+ call.error = `timeout after ${timeoutMs} ms`;
619
+ debug(`HTTP export timeout: the ack body did not arrive within ${timeoutMs} ms`);
620
+ return "timeout" /* TIMEOUT */;
621
+ }
622
+ return this._noteMisroute(
623
+ call,
624
+ `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
625
+ );
626
+ }
627
+ if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
628
+ if (ack.final) call.noRetry = true;
629
+ return ack.result;
630
+ } else if (response.status === 408 || response.status === 504) {
631
+ debug(`HTTP export timeout: ${response.status}`);
632
+ return "timeout" /* TIMEOUT */;
633
+ }
634
+ this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
635
+ debug(`HTTP export failed: ${response.status}`);
636
+ return "failure" /* FAILURE */;
637
+ } catch (e) {
638
+ const cause = e instanceof Error ? e.cause : void 0;
639
+ call.error = controller.signal.aborted ? `timeout after ${timeoutMs} ms` : typeof cause?.code === "string" ? cause.code : e instanceof Error ? e.name : "Error";
640
+ debug(`HTTP export error: ${this._scrub(e)}`);
641
+ return "failure" /* FAILURE */;
642
+ } finally {
643
+ clearTimeout(timeoutId);
644
+ cancelled.removeEventListener("abort", onCancel);
645
+ }
646
+ }
647
+ shutdown() {
648
+ }
649
+ };
650
+ function sleep(ms, signal) {
651
+ return new Promise((resolve) => {
652
+ if (signal?.aborted) return resolve();
653
+ const done = () => {
654
+ clearTimeout(timer);
655
+ signal?.removeEventListener("abort", done);
656
+ resolve();
657
+ };
658
+ const timer = setTimeout(done, ms);
659
+ signal?.addEventListener("abort", done, { once: true });
660
+ });
661
+ }
662
+ function asCount(v) {
663
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
664
+ }
665
+ var MAX_ACK_REASONS = 3;
666
+ var MAX_ACK_REASON_CHARS = 200;
667
+ function oneLine(text) {
668
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ");
669
+ }
670
+ function ackReasons(body) {
671
+ const reasons = [];
672
+ const errors = body.errors;
673
+ if (Array.isArray(errors)) {
674
+ for (const entry of errors) {
675
+ const text = entry?.error;
676
+ if (typeof text !== "string" || text.length === 0) continue;
677
+ const cut = oneLine(text).slice(0, MAX_ACK_REASON_CHARS);
678
+ if (!reasons.includes(cut)) reasons.push(cut);
679
+ if (reasons.length === MAX_ACK_REASONS) break;
680
+ }
681
+ }
682
+ if (reasons.length === 0) {
683
+ const message = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || "";
684
+ if (message) reasons.push(oneLine(message).slice(0, MAX_ACK_REASON_CHARS));
685
+ }
686
+ return reasons.length === 0 ? "No reason was returned." : `Reasons: ${reasons.join("; ")}`;
687
+ }
688
+ async function checkAck(response, spansSent, scrub) {
689
+ let payload;
690
+ try {
691
+ payload = await response.json();
692
+ } catch {
693
+ return null;
694
+ }
695
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
696
+ return null;
697
+ }
698
+ const body = payload;
699
+ const accepted = asCount(body.accepted);
700
+ const rejected = asCount(body.rejected);
701
+ if (accepted === void 0 || rejected === void 0) return null;
702
+ const counts = { accepted, rejected };
703
+ if (accepted === 0 && rejected === 0 && spansSent > 0) {
704
+ warn(
705
+ `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.`
706
+ );
707
+ return { result: "failure" /* FAILURE */, counts, final: true };
708
+ }
709
+ if (rejected === 0) return { result: "success" /* SUCCESS */, counts, final: false };
710
+ const total = accepted + rejected;
711
+ if (accepted === 0) {
712
+ warn(
713
+ `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))}`
714
+ );
715
+ return { result: "success" /* SUCCESS */, counts, final: false };
716
+ }
717
+ warn(
718
+ `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))}`
719
+ );
720
+ return { result: "success" /* SUCCESS */, counts, final: false };
721
+ }
722
+
154
723
  // src/runtime/applier.ts
155
724
  var import_node_crypto2 = require("crypto");
156
725
 
726
+ // src/runtime/loader.ts
727
+ var FixLoader = class _FixLoader {
728
+ _config;
729
+ _cache;
730
+ _refreshTimer = null;
731
+ _lastLoadTime = null;
732
+ _consecutiveFailures = 0;
733
+ _circuitOpenUntil = 0;
734
+ _onLoadCallbacks = [];
735
+ // The HTTP status of the last load that got a non-2xx answer; null otherwise.
736
+ _lastStatus = null;
737
+ // Circuit breaker settings
738
+ static CIRCUIT_BREAKER_THRESHOLD = 3;
739
+ static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
740
+ constructor(config, cache) {
741
+ this._config = resolveFixRuntimeConfig(config);
742
+ this._cache = cache;
743
+ }
744
+ /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */
745
+ _scrub(error) {
746
+ let out;
747
+ try {
748
+ out = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
749
+ } catch {
750
+ out = typeof error;
751
+ }
752
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
753
+ if (endpoint && safeUrl(endpoint) !== endpoint) out = out.split(endpoint).join(safeUrl(endpoint));
754
+ return scrubText(out, [this._config.apiKey]);
755
+ }
756
+ /**
757
+ * The WARNING for a failed first load: the request URL with no userinfo, no
758
+ * query and no key, the HTTP status or the error class, and that tracing is
759
+ * not affected. Never the error text: it can echo the URL with its query.
760
+ */
761
+ _firstLoadWarning(error) {
762
+ let cause;
763
+ if (this._lastStatus !== null) {
764
+ cause = `HTTP ${this._lastStatus}`;
765
+ } else {
766
+ cause = error instanceof Error ? error.name : typeof error;
767
+ const code = error?.cause?.code;
768
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code)) cause += ` (${code})`;
769
+ }
770
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
771
+ return scrubText(
772
+ `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.`,
773
+ [this._config.apiKey],
774
+ 500
775
+ );
776
+ }
777
+ /** Hide the key from `util.inspect` and `console.log` of the loader. */
778
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
779
+ return "FixLoader {}";
780
+ }
781
+ /** Timestamp of last successful load. */
782
+ get lastLoadTime() {
783
+ return this._lastLoadTime;
784
+ }
785
+ /**
786
+ * Start the loader: perform initial load and start background refresh.
787
+ *
788
+ * Never throws — failures are logged and the runtime degrades gracefully.
789
+ */
790
+ start() {
791
+ try {
792
+ if (!this._config.enabled) {
793
+ debug("Fix runtime disabled, skipping loader start");
794
+ return;
795
+ }
796
+ if (!this._config.apiKey) {
797
+ warn("No API key configured, fixes will not be loaded");
798
+ return;
799
+ }
800
+ this.loadSync().catch((e) => {
801
+ warn(this._firstLoadWarning(e));
802
+ });
803
+ if (this._config.autoRefresh) {
804
+ this._startRefreshInterval();
805
+ }
806
+ } catch (e) {
807
+ debug(`FixLoader.start error: ${this._scrub(e)}`);
808
+ }
809
+ }
810
+ /** Stop the loader: clear the refresh interval. */
811
+ stop() {
812
+ try {
813
+ if (this._refreshTimer !== null) {
814
+ clearInterval(this._refreshTimer);
815
+ this._refreshTimer = null;
816
+ }
817
+ } catch (e) {
818
+ debug(`FixLoader.stop error: ${this._scrub(e)}`);
819
+ }
820
+ }
821
+ /**
822
+ * Register a callback invoked after each successful load.
823
+ */
824
+ onLoad(callback) {
825
+ this._onLoadCallbacks.push(callback);
826
+ }
827
+ /**
828
+ * Load fixes from the API.
829
+ *
830
+ * Name kept as "loadSync" for parity with the Python SDK, but this
831
+ * returns a Promise in JS (there's no synchronous fetch in Node.js).
832
+ */
833
+ async loadSync() {
834
+ if (!this._config.apiKey) {
835
+ return [];
836
+ }
837
+ const now = Date.now();
838
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
839
+ debug("Fix loader circuit breaker open \u2014 skipping load");
840
+ return this._cache.getAll();
841
+ }
842
+ this._lastStatus = null;
843
+ try {
844
+ const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
845
+ const url = `${endpoint}/v1/fixes/active`;
846
+ const controller = new AbortController();
847
+ const timeoutId = setTimeout(
848
+ () => controller.abort(),
849
+ this._config.timeoutMs
850
+ );
851
+ const response = await fetch(url, {
852
+ method: "GET",
853
+ headers: {
854
+ "Authorization": `Bearer ${this._config.apiKey}`,
855
+ "Content-Type": "application/json",
856
+ "X-Risicare-SDK-Version": SDK_VERSION
857
+ },
858
+ signal: controller.signal
859
+ });
860
+ clearTimeout(timeoutId);
861
+ if (!response.ok) {
862
+ this._lastStatus = response.status;
863
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
864
+ }
865
+ const data = await response.json();
866
+ const fixes = this._parseResponse(data);
867
+ this._onLoadSuccess(fixes);
868
+ return fixes;
869
+ } catch (e) {
870
+ this._onLoadFailure(e);
871
+ throw e;
872
+ }
873
+ }
874
+ /** Get currently cached fixes without hitting the API. */
875
+ getCached() {
876
+ return this._cache.getAll();
877
+ }
878
+ // ─── Private ────────────────────────────────────────────────────────────
879
+ _parseResponse(data) {
880
+ const fixes = [];
881
+ const items = data.fixes ?? data.data ?? [];
882
+ if (!Array.isArray(items)) return fixes;
883
+ for (const item of items) {
884
+ try {
885
+ if (item && typeof item === "object") {
886
+ fixes.push(activeFixFromApiResponse(item));
887
+ }
888
+ } catch (e) {
889
+ debug(`Failed to parse fix item: ${this._scrub(e)}`);
890
+ }
891
+ }
892
+ return fixes;
893
+ }
894
+ _onLoadSuccess(fixes) {
895
+ this._lastLoadTime = Date.now();
896
+ this._consecutiveFailures = 0;
897
+ this._cache.setAll(fixes);
898
+ for (const callback of this._onLoadCallbacks) {
899
+ try {
900
+ callback(fixes);
901
+ } catch (e) {
902
+ debug(`Load callback error: ${this._scrub(e)}`);
903
+ }
904
+ }
905
+ debug(`Loaded ${fixes.length} active fixes`);
906
+ }
907
+ _onLoadFailure(error) {
908
+ this._consecutiveFailures++;
909
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
910
+ this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
911
+ warn(
912
+ `Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
913
+ );
914
+ } else {
915
+ debug(
916
+ `Fix load failed (attempt ${this._consecutiveFailures}): ${this._scrub(error)}`
917
+ );
918
+ }
919
+ }
920
+ _startRefreshInterval() {
921
+ const tick = () => {
922
+ this.loadSync().catch((e) => {
923
+ debug(`Background fix refresh failed: ${this._scrub(e)}`);
924
+ });
925
+ };
926
+ this._refreshTimer = setInterval(
927
+ () => {
928
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
929
+ return;
930
+ }
931
+ tick();
932
+ },
933
+ this._config.refreshIntervalMs
934
+ );
935
+ this._refreshTimer.unref();
936
+ debug("Started fix refresh interval");
937
+ }
938
+ };
939
+
157
940
  // src/client.ts
941
+ var SCORE_MAX_WAITING = 1e3;
942
+ var SCORE_CAP_REASON = `not sent: ${SCORE_MAX_WAITING} scores wait for a free slot`;
158
943
  function getTracer2() {
159
944
  return getTracer();
160
945
  }