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