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