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
package/dist/index.js CHANGED
@@ -48,6 +48,29 @@ function getDebug() {
48
48
  function setDebugFlag(enabled) {
49
49
  G[PREFIX + "debug"] = enabled;
50
50
  }
51
+ var PROVIDER_SPANS = /* @__PURE__ */ Symbol.for("risicare.providerSpans");
52
+ function usableProviderSpanState(s) {
53
+ if (!s || typeof s !== "object") return false;
54
+ const { version, open, registry } = s;
55
+ const o = open;
56
+ return version === 1 && !!o && typeof o.add === "function" && typeof o.delete === "function" && typeof o[Symbol.iterator] === "function" && (registry === void 0 || typeof registry.register === "function");
57
+ }
58
+ function getProviderSpanState() {
59
+ const found = G[PROVIDER_SPANS];
60
+ if (found === void 0) {
61
+ const s = {
62
+ version: 1,
63
+ open: /* @__PURE__ */ new Set(),
64
+ registry: typeof FinalizationRegistry === "function" ? new FinalizationRegistry((o) => o.release()) : void 0
65
+ };
66
+ G[PROVIDER_SPANS] = s;
67
+ return s;
68
+ }
69
+ if (!usableProviderSpanState(found)) {
70
+ throw new TypeError("the shared provider span state is not version 1");
71
+ }
72
+ return found;
73
+ }
51
74
 
52
75
  // src/utils/log.ts
53
76
  function setDebug(enabled) {
@@ -64,6 +87,73 @@ function warn(msg) {
64
87
  `);
65
88
  }
66
89
 
90
+ // src/utils/text.ts
91
+ function cutCodePoints(text, max) {
92
+ if (text.length <= max) return text;
93
+ let units = 0;
94
+ for (let points = 0; points < max && units < text.length; points++) {
95
+ units += text.codePointAt(units) > 65535 ? 2 : 1;
96
+ }
97
+ return text.slice(0, units);
98
+ }
99
+
100
+ // src/utils/scrub.ts
101
+ var KEY_MARKER = "[REDACTED-KEY]";
102
+ var CONTROL = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]", "g");
103
+ function escapeRegExp(text) {
104
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
105
+ }
106
+ function percentDecode(text) {
107
+ try {
108
+ return decodeURIComponent(text);
109
+ } catch {
110
+ return text.replace(/%([0-9A-Fa-f]{2})/g, (_m, hex) => String.fromCharCode(parseInt(hex, 16)));
111
+ }
112
+ }
113
+ function keyPattern(keys) {
114
+ const values = /* @__PURE__ */ new Set();
115
+ for (const k of [...keys, process.env.RISICARE_API_KEY]) if (k) values.add(k);
116
+ if (values.size === 0) return null;
117
+ const ordered = [...values].sort((a, b) => b.length - a.length);
118
+ return new RegExp(ordered.map(escapeRegExp).join("|"), "gi");
119
+ }
120
+ function scrubText(text, keys, limit = 200) {
121
+ let out;
122
+ try {
123
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
124
+ } catch {
125
+ out = typeof text;
126
+ }
127
+ const pattern = keyPattern(keys);
128
+ if (pattern !== null) {
129
+ if (out.includes("%")) {
130
+ const decoded = percentDecode(out);
131
+ pattern.lastIndex = 0;
132
+ if (decoded !== out && pattern.test(decoded)) out = decoded;
133
+ }
134
+ pattern.lastIndex = 0;
135
+ out = out.replace(pattern, KEY_MARKER);
136
+ }
137
+ return cutCodePoints(out.replace(CONTROL, " "), limit);
138
+ }
139
+ function safeUrl(url) {
140
+ try {
141
+ const u = new URL(url);
142
+ const path = u.pathname === "/" && !/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*\//i.test(url) ? "" : u.pathname;
143
+ return `${u.protocol}//${u.host}${path}`;
144
+ } catch {
145
+ return url.split("?")[0].split("#")[0].replace(/\/\/[^/@]*@/, "//");
146
+ }
147
+ }
148
+ function hasCredentials(url) {
149
+ try {
150
+ const u = new URL(url);
151
+ return u.username !== "" || u.password !== "";
152
+ } catch {
153
+ return false;
154
+ }
155
+ }
156
+
67
157
  // src/masking.ts
68
158
  var MASK_ERROR_MARKER = "<risicare:mask-error>";
69
159
  var MASK_BUDGET_MS_PER_SPAN = 1;
@@ -143,6 +233,9 @@ var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
143
233
  "gen_ai.output.messages",
144
234
  "gen_ai.system_instructions",
145
235
  "gen_ai.tool.call.arguments",
236
+ // Corpus v2: the list of tool definitions of a request. The names,
237
+ // descriptions and schemas in it are text that the customer wrote.
238
+ "gen_ai.tool.definitions",
146
239
  "gen_ai.tool.call.result",
147
240
  "input.value",
148
241
  // OpenInference
@@ -306,7 +399,13 @@ function applyMaskBatch(spans, mask, onError) {
306
399
  }
307
400
  const elapsedMs = Date.now() - started;
308
401
  if (errors > 0 && firstKey !== void 0) {
309
- debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);
402
+ let detail;
403
+ try {
404
+ detail = String(firstError);
405
+ } catch {
406
+ detail = typeof firstError;
407
+ }
408
+ debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${detail}`);
310
409
  }
311
410
  return { errors, elapsedMs };
312
411
  }
@@ -322,8 +421,37 @@ function warnMaskSlow(spanCount, elapsedMs) {
322
421
  }
323
422
 
324
423
  // src/exporters/batch.ts
424
+ var DEADLINE = /* @__PURE__ */ Symbol("deadline");
425
+ async function raceDeadline(p, ms) {
426
+ let timer;
427
+ const deadline = new Promise((resolve) => {
428
+ timer = setTimeout(() => resolve(DEADLINE), Math.max(0, ms));
429
+ });
430
+ try {
431
+ return await Promise.race([p, deadline]);
432
+ } finally {
433
+ clearTimeout(timer);
434
+ }
435
+ }
436
+ function describeThrown(e) {
437
+ return scrubText(e, []);
438
+ }
439
+ async function shutdownExporter(exporter, ms) {
440
+ try {
441
+ const outcome = await raceDeadline(Promise.resolve().then(() => exporter.shutdown()), ms);
442
+ if (outcome === DEADLINE) debug(`${exporter.name}.shutdown() did not finish within ${ms} ms`);
443
+ } catch (e) {
444
+ debug(`Error shutting down ${exporter.name}: ${describeThrown(e)}`);
445
+ }
446
+ }
325
447
  var SHUTDOWN_RESERVE_MS = 100;
326
448
  var SHUTDOWN_BUDGET_MS = 5e3;
449
+ var MAX_TIMEOUT_MS = 2 ** 31 - 1;
450
+ function normalizeTimeoutMs(value) {
451
+ if (typeof value !== "number" || !Number.isFinite(value)) return SHUTDOWN_BUDGET_MS;
452
+ if (value < 0) return 0;
453
+ return Math.min(value, MAX_TIMEOUT_MS);
454
+ }
327
455
  var REFUSAL_WARN_WINDOW_MS = 3e5;
328
456
  var DEFAULT_BATCH_SIZE = 500;
329
457
  var MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24e3;
@@ -412,11 +540,18 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
412
540
  _timer = null;
413
541
  _started = false;
414
542
  _flushing = false;
543
+ _inFlight = null;
415
544
  _beforeExitHandler = null;
416
545
  // Retry tracking for failed batches (Audit #5)
417
546
  _retryCounts = /* @__PURE__ */ new Map();
418
547
  static MAX_RETRIES = 3;
419
548
  _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
549
+ _lastUnackWarnAt = Number.NEGATIVE_INFINITY;
550
+ /**
551
+ * The loss total (dropped + rejected) that the last finished `flush()` saw.
552
+ * A flush reports a loss that is new since then, one time.
553
+ */
554
+ _lossMark = 0;
420
555
  // ── Masking (see `../masking.ts`) ──────────────────────────────────────────
421
556
  _mask;
422
557
  // ── Content capture gate (see `../masking.ts`) ─────────────────────────────
@@ -438,9 +573,15 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
438
573
  droppedSpansByReason = {
439
574
  queue_full: 0,
440
575
  transport_refused: 0,
441
- shutdown_residue: 0
576
+ shutdown_residue: 0,
577
+ unacknowledged: 0
442
578
  };
443
579
  exportedSpans = 0;
580
+ /**
581
+ * Spans that the backend acknowledged as REJECTED (the ack's `rejected`). They
582
+ * are not stored and are not retried. An exporter without an ack adds nothing.
583
+ */
584
+ rejectedSpans = 0;
444
585
  /** Export ATTEMPTS, not a span count. */
445
586
  failedExports = 0;
446
587
  /**
@@ -525,13 +666,32 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
525
666
  * NO progress and abandons the queue exactly as before — measured at 900 of
526
667
  * 1,000. We await a tick instead, the shape `flush()` already models.
527
668
  *
528
- * Anything still queued when the loop stops is COUNTED as `shutdown_residue`
529
- * and announced with a WARNING. The warning is the primary signal, not the
530
- * counter: a counter incremented inside `shutdown()` is written to memory
531
- * about to be freed and has no reader (RULING §2 / §8.2).
669
+ * The deadline is a hard wall-clock bound. Each round is raced against the
670
+ * budget that remains. At the deadline, `shutdown()` stops the round in flight
671
+ * through the exporter's optional `abort()`. That stopped round changes no
672
+ * counter, does not move the circuit breaker and re-queues nothing. Through
673
+ * 0.7.1 the deadline was checked only between rounds, so one round against a
674
+ * silent server (3 attempts x 5 s) held a 5,000 ms shutdown for 15 s.
675
+ *
676
+ * Anything still queued when the loop stops, AND a batch whose export was
677
+ * stopped, is COUNTED as `shutdown_residue` and announced with ONE WARNING
678
+ * that gives both numbers. The server may have received the spans of the
679
+ * stopped export. The warning is the primary signal, not the counter: a
680
+ * counter incremented inside `shutdown()` is written to memory about to be
681
+ * freed and has no reader (RULING §2 / §8.2).
682
+ *
683
+ * Each exporter's own `shutdown()` gets the time that is left of the budget.
684
+ * An exporter that does not finish in that time is not awaited.
685
+ *
686
+ * Limit: the abort does not stop a TLS handshake that stalls. Measured, such a
687
+ * handshake kept the process alive about 10 s after `shutdown()` returned.
688
+ *
689
+ * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
690
+ * the values that are not a finite number.
532
691
  */
533
692
  async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
534
693
  if (!this._started) return;
694
+ timeoutMs = normalizeTimeoutMs(timeoutMs);
535
695
  this._started = false;
536
696
  if (this._timer) {
537
697
  clearInterval(this._timer);
@@ -542,10 +702,13 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
542
702
  this._beforeExitHandler = null;
543
703
  }
544
704
  const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);
545
- const drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);
705
+ const shutdownDeadline = Date.now() + timeoutMs;
706
+ const drainDeadline = shutdownDeadline - reserveMs;
546
707
  while (this._queue.length > 0 || this._flushing) {
547
- if (Date.now() >= drainDeadline) break;
548
- const outcome = await this._exportBatch();
708
+ const remaining = drainDeadline - Date.now();
709
+ if (remaining <= 0) break;
710
+ const outcome = await raceDeadline(this._exportBatch(), remaining);
711
+ if (outcome === DEADLINE) break;
549
712
  if (outcome === 3 /* Busy */) {
550
713
  await new Promise((r) => setTimeout(r, 1));
551
714
  continue;
@@ -554,20 +717,29 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
554
717
  break;
555
718
  }
556
719
  }
557
- const residue = this._queue.length;
720
+ const queued = this._queue.length;
721
+ const flight = this._inFlight;
722
+ const inFlight = flight !== null && !flight.abandoned ? flight.size : 0;
723
+ if (flight !== null && !flight.abandoned) {
724
+ flight.abandoned = true;
725
+ for (const exporter of this._exporters) {
726
+ try {
727
+ exporter.abort?.(flight.spans);
728
+ } catch (e) {
729
+ debug(`Error aborting ${exporter.name}: ${describeThrown(e)}`);
730
+ }
731
+ }
732
+ }
733
+ const residue = queued + inFlight;
558
734
  if (residue > 0) {
559
735
  this._queue.length = 0;
560
736
  this._recordDropped("shutdown_residue", residue);
561
737
  warn(
562
- `shutdown() gave up with ${residue} span(s) still queued (reason=shutdown_residue) \u2014 they were NOT delivered. The ${timeoutMs} ms shutdown budget expired or the transport stopped accepting. Raise the shutdown timeout, or your container's termination grace period, to lose less.`
738
+ `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${inFlight} in an export that shutdown() stopped. ` + (inFlight > 0 ? `The server may have received the ${inFlight} span(s) of the stopped export. ` : "") + `All ${residue} were not confirmed as delivered, and are counted as dropped. The ${timeoutMs} ms shutdown budget expired or the transport stopped accepting. Pass a larger timeout to shutdown(timeoutMs), or raise your container's termination grace period, to lose less.`
563
739
  );
564
740
  }
565
741
  for (const exporter of this._exporters) {
566
- try {
567
- await exporter.shutdown();
568
- } catch (e) {
569
- debug(`Error shutting down ${exporter.name}: ${e}`);
570
- }
742
+ await shutdownExporter(exporter, Math.max(0, shutdownDeadline - Date.now()));
571
743
  }
572
744
  this._retryCounts.clear();
573
745
  debug(
@@ -591,7 +763,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
591
763
  /**
592
764
  * Flush pending spans.
593
765
  *
594
- * @returns `true` only if everything queued at entry was DELIVERED.
766
+ * @returns `true` only if everything queued at entry was DELIVERED and no
767
+ * span was lost since the previous flush returned.
595
768
  *
596
769
  * RULING §6. This used to answer a different question — "is the queue
597
770
  * empty?" — and those two diverge in exactly one case: when spans left the
@@ -600,35 +773,76 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
600
773
  * everything right; silence lets them discover the problem, a false
601
774
  * affirmative forecloses it.
602
775
  *
603
- * Returns `false` when (a) the deadline expires with spans still queued,
604
- * (b) any span was discarded during the window — breaker refusal or retry
605
- * exhaustion — or (c) it is called after `shutdown()` and the shutdown
606
- * residue was non-zero.
776
+ * A LOSS IS REPORTED BY THE NEXT `flush()`, ONE TIME (design section 0,
777
+ * third revision). Returns `true` only when, at the moment it returns, the
778
+ * queue is empty, no batch is in flight, and no span was discarded or
779
+ * rejected since the previous `flush()` returned (or since start, for the
780
+ * first call). Through 0.7.1 only a loss during the call counted: a script
781
+ * whose spans the batch timer had discarded against a 401 sink got `true`
782
+ * with nothing delivered. A failure that a retry repairs does not make it
783
+ * `false`.
784
+ *
785
+ * Mechanics: the processor keeps a loss mark, the loss total (dropped +
786
+ * rejected) that the last finished flush saw. A flush compares the total
787
+ * with the mark it read at its start, then raises the mark to the total
788
+ * (never lowers it). Two flushes that overlap both answer `false` for one
789
+ * loss. The flush after that answers `true` when nothing new was lost.
790
+ *
791
+ * Returns `false` in these cases:
792
+ * (a) the deadline expires with spans still queued or in flight;
793
+ * (b) a span was discarded since the previous flush returned: queue full,
794
+ * breaker refusal, retry exhaustion, or an ack that did not account
795
+ * for it or a span that could not be serialized (`unacknowledged`);
796
+ * (c) the backend rejected a span since the previous flush returned;
797
+ * (d) it is called after `shutdown()`, and the shutdown residue was not 0.
798
+ *
799
+ * The deadline is a hard wall-clock bound on the WAIT. At the deadline
800
+ * `flush()` returns `false`. Through 0.7.1 the deadline was checked only
801
+ * between rounds.
802
+ *
803
+ * ⚠ `flush()` never stops a request that is already sent. The export round in
804
+ * flight continues and ends by its own rules: its request timeout, its
805
+ * retries, the circuit breaker. A short flush budget therefore costs no retry,
806
+ * moves no breaker and sends nothing twice. Its result still counts.
807
+ *
808
+ * Limit: that round can keep the process alive after `flush()` returns
809
+ * `false`, until its own timeouts end. Measured on a silent server: 22 s. To
810
+ * end a process within a bound, call `await shutdown(timeoutMs)`: it stops
811
+ * the round in flight.
607
812
  *
608
813
  * ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span
609
- * that arrived DURING the window also answers `false`. That is the
814
+ * that arrived during the call also answers `false`. That is the
610
815
  * conservative direction on purpose: a false negative costs a caller one
611
816
  * more flush, a false positive is the defect being fixed.
612
817
  */
613
818
  async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
819
+ timeoutMs = normalizeTimeoutMs(timeoutMs);
614
820
  if (!this._started) {
615
821
  return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
616
822
  }
617
- const start = Date.now();
618
- const discardedAtEntry = this.droppedSpans;
823
+ const deadline = Date.now() + timeoutMs;
824
+ const mark = this._lossMark;
825
+ const finish = (settled) => {
826
+ const lost = this.droppedSpans + this.rejectedSpans;
827
+ this._lossMark = Math.max(this._lossMark, lost);
828
+ return settled && lost === mark;
829
+ };
619
830
  while (this._queue.length > 0 || this._flushing) {
831
+ const remaining = deadline - Date.now();
832
+ if (remaining <= 0) return finish(false);
620
833
  if (!this._flushing && this._queue.length > 0) {
621
- await this._exportBatch();
834
+ const outcome = await raceDeadline(this._exportBatch(), remaining);
835
+ if (outcome === DEADLINE) return finish(false);
622
836
  } else {
623
837
  await new Promise((r) => setTimeout(r, 1));
624
838
  }
625
- if (Date.now() - start > timeoutMs) return false;
626
839
  }
627
- return this.droppedSpans === discardedAtEntry;
840
+ return finish(true);
628
841
  }
629
842
  getMetrics() {
630
843
  return {
631
844
  exportedSpans: this.exportedSpans,
845
+ rejectedSpans: this.rejectedSpans,
632
846
  droppedSpans: this.droppedSpans,
633
847
  droppedSpansByReason: { ...this.droppedSpansByReason },
634
848
  failedExports: this.failedExports,
@@ -638,10 +852,56 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
638
852
  queueUtilization: this._queue.length / this._maxQueueSize
639
853
  };
640
854
  }
855
+ /**
856
+ * Count a delivered batch of `n` spans from the exporter's ack.
857
+ *
858
+ * The ack is not trusted. With r = min(rejected, n), a = min(accepted, n - r)
859
+ * and u = n - a - r: `exportedSpans` rises by a, `rejectedSpans` by r, and the
860
+ * u spans that no ack accounts for are dropped as `unacknowledged`, with one
861
+ * rate-limited WARNING. Without an ack (console, custom exporter), the whole
862
+ * batch counts as exported, as before. Python twin: the same clamp.
863
+ */
864
+ _countDelivered(n, ack) {
865
+ if (ack === null) {
866
+ this.exportedSpans += n;
867
+ return;
868
+ }
869
+ const rejected = Math.min(ack.rejected, n);
870
+ const accepted = Math.min(ack.accepted, n - rejected);
871
+ const unacknowledged = n - accepted - rejected;
872
+ this.exportedSpans += accepted;
873
+ this.rejectedSpans += rejected;
874
+ if (unacknowledged > 0) {
875
+ this._recordDropped("unacknowledged", unacknowledged);
876
+ const now = Date.now();
877
+ if (now - this._lastUnackWarnAt > REFUSAL_WARN_WINDOW_MS) {
878
+ this._lastUnackWarnAt = now;
879
+ warn(
880
+ `Risicare: the backend's ack accounts for ${accepted + rejected} of ${n} span(s) in this batch. The other ${unacknowledged} are counted as dropped (reason=unacknowledged): they may not be stored. ${this.droppedSpansByReason.unacknowledged} span(s) counted this way so far in this process.`
881
+ );
882
+ }
883
+ }
884
+ }
885
+ /** The requests in one export round, when every exporter that delivers states it. */
886
+ _requestsPerRound() {
887
+ const delivering = this._exporters.filter((e) => e.countsAsDelivery !== false);
888
+ if (delivering.length !== 1) return void 0;
889
+ const n = delivering[0].attemptsPerExport;
890
+ return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : void 0;
891
+ }
892
+ /**
893
+ * One export round.
894
+ *
895
+ * Which results decide delivery: an exporter that only shows spans locally
896
+ * (`countsAsDelivery === false`, the console exporter) decides only when no
897
+ * other kind of exporter is present. Among the exporters that deliver, ANY
898
+ * success counts the batch as delivered, once.
899
+ */
641
900
  async _exportBatch() {
642
901
  if (this._flushing) return 3 /* Busy */;
643
902
  if (this._queue.length === 0) return 0 /* Empty */;
644
903
  this._flushing = true;
904
+ let flight = null;
645
905
  try {
646
906
  let take = 0;
647
907
  let pairs = 0;
@@ -660,6 +920,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
660
920
  }
661
921
  const batch = this._queue.splice(0, take);
662
922
  if (batch.length === 0) return 0 /* Empty */;
923
+ flight = { spans: batch, size: batch.length, abandoned: false };
924
+ this._inFlight = flight;
663
925
  if (!this._traceContent) {
664
926
  const stripped = stripContentBatch(batch);
665
927
  if (stripped > 0) {
@@ -673,12 +935,19 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
673
935
  }
674
936
  debug(`Exporting batch of ${batch.length} spans`);
675
937
  let batchExported = false;
938
+ const anyDelivers = this._exporters.some((e) => e.countsAsDelivery !== false);
939
+ const unserializable = /* @__PURE__ */ new Set();
676
940
  for (const exporter of this._exporters) {
941
+ const decides = !anyDelivers || exporter.countsAsDelivery !== false;
677
942
  try {
678
943
  const result = await exporter.export(batch);
944
+ if (flight.abandoned) return 2 /* Failed */;
945
+ if (!decides) continue;
946
+ for (const span of exporter.takeUnserializable?.(batch) ?? []) unserializable.add(span);
679
947
  if (result === "success" /* SUCCESS */) {
948
+ const ack = exporter.takeAck?.(batch) ?? null;
680
949
  if (!batchExported) {
681
- this.exportedSpans += batch.length;
950
+ this._countDelivered(batch.length - unserializable.size, ack);
682
951
  batchExported = true;
683
952
  for (const span of batch) {
684
953
  this._retryCounts.delete(span.spanId);
@@ -688,13 +957,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
688
957
  this.failedExports++;
689
958
  }
690
959
  } catch (e) {
960
+ if (flight.abandoned) return 2 /* Failed */;
961
+ if (!decides) continue;
691
962
  this.failedExports++;
692
- debug(`Export to ${exporter.name} failed: ${e}`);
963
+ debug(`Export to ${exporter.name} failed: ${describeThrown(e)}`);
693
964
  }
694
965
  }
966
+ if (unserializable.size > 0) this._recordDropped("unacknowledged", unserializable.size);
695
967
  if (!batchExported) {
696
968
  let dropped = 0;
697
969
  const retryable = batch.filter((span) => {
970
+ if (unserializable.has(span)) return false;
698
971
  const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
699
972
  if (count > _BatchSpanProcessor.MAX_RETRIES) {
700
973
  this._retryCounts.delete(span.spanId);
@@ -713,14 +986,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
713
986
  const now = Date.now();
714
987
  if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {
715
988
  this._lastRefusalWarnAt = now;
989
+ const rounds = _BatchSpanProcessor.MAX_RETRIES + 1;
990
+ const perRound = this._requestsPerRound();
716
991
  warn(
717
- `${dropped} span(s) DISCARDED (reason=transport_refused) after ${_BatchSpanProcessor.MAX_RETRIES} failed export attempts each \u2014 the endpoint is not accepting spans and the retry budget is spent. ${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far in this process. This data is gone; check the apiKey and the endpoint.`
992
+ `${dropped} span(s) DISCARDED (reason=transport_refused) after ${rounds} failed export rounds each` + (perRound !== void 0 ? ` (up to ${rounds * perRound} HTTP requests: ${perRound} in each round)` : "") + ` \u2014 the endpoint is not accepting spans and the retry budget is spent. ${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far in this process. This data is gone; check the apiKey and the endpoint.`
718
993
  );
719
994
  }
720
995
  }
721
996
  }
722
997
  return batchExported ? 1 /* Delivered */ : 2 /* Failed */;
723
998
  } finally {
999
+ if (this._inFlight === flight) this._inFlight = null;
724
1000
  this._flushing = false;
725
1001
  }
726
1002
  }
@@ -729,18 +1005,46 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
729
1005
  // src/config.ts
730
1006
  var DEFAULT_ENDPOINT = "https://ingest.risicare.ai";
731
1007
  var DEFAULT_API_ENDPOINT = "https://api.risicare.ai";
1008
+ var ASCII_WS_EDGES = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
1009
+ function given(value) {
1010
+ if (typeof value !== "string") return void 0;
1011
+ const trimmed = value.replace(ASCII_WS_EDGES, "");
1012
+ return trimmed === "" ? void 0 : trimmed;
1013
+ }
1014
+ var DEFAULT_INGEST_PATTERN = /^https:\/\/ingest\.risicare\.ai(?::443)?\/*$/i;
1015
+ function isDefaultIngest(value) {
1016
+ return DEFAULT_INGEST_PATTERN.test(value);
1017
+ }
1018
+ function resolveEndpoints(endpointOption, apiEndpointOption, envEndpoint, envApiEndpoint) {
1019
+ const e = given(endpointOption);
1020
+ const a = given(apiEndpointOption);
1021
+ const ee = given(envEndpoint);
1022
+ const ea = given(envApiEndpoint);
1023
+ const endpoint = e ?? ee ?? DEFAULT_ENDPOINT;
1024
+ let apiEndpoint;
1025
+ if (a !== void 0) apiEndpoint = a;
1026
+ else if (e !== void 0 && !isDefaultIngest(e)) apiEndpoint = e;
1027
+ else if (ea !== void 0) apiEndpoint = ea;
1028
+ else if (e === void 0 && ee !== void 0 && !isDefaultIngest(ee)) apiEndpoint = ee;
1029
+ else apiEndpoint = DEFAULT_API_ENDPOINT;
1030
+ return { endpoint, apiEndpoint };
1031
+ }
732
1032
  function resolveConfig(config) {
733
1033
  const env = process.env;
734
1034
  const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
735
- const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;
736
- const apiEndpoint = config?.apiEndpoint ?? env.RISICARE_API_ENDPOINT ?? config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_API_ENDPOINT;
1035
+ const { endpoint, apiEndpoint } = resolveEndpoints(
1036
+ config?.endpoint,
1037
+ config?.apiEndpoint,
1038
+ env.RISICARE_ENDPOINT,
1039
+ env.RISICARE_API_ENDPOINT
1040
+ );
737
1041
  const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;
738
1042
  if (config?.projectId || env.RISICARE_PROJECT_ID) {
739
1043
  console.warn(
740
1044
  "[risicare] projectId is deprecated and ignored by the gateway. Your API key determines the project. Use serviceName and environment for within-project organization. projectId will be removed in v1.0."
741
1045
  );
742
1046
  }
743
- const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
1047
+ const environment = config?.environment || env.RISICARE_ENVIRONMENT || "development";
744
1048
  const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
745
1049
  const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
746
1050
  const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
@@ -761,14 +1065,15 @@ function resolveConfig(config) {
761
1065
  const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
762
1066
  const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
763
1067
  let enabled;
1068
+ const tracingEnv = config?.enabled === void 0 ? tracingFromEnv(env.RISICARE_TRACING) : void 0;
764
1069
  if (config?.enabled !== void 0) {
765
1070
  enabled = config.enabled;
766
- } else if (env.RISICARE_TRACING !== void 0) {
767
- enabled = parseBool(env.RISICARE_TRACING, false);
1071
+ } else if (tracingEnv !== void 0) {
1072
+ enabled = tracingEnv;
768
1073
  } else {
769
1074
  enabled = !!apiKey;
770
1075
  }
771
- return {
1076
+ return hideKeyFromInspect({
772
1077
  apiKey: apiKey ?? "",
773
1078
  endpoint,
774
1079
  apiEndpoint,
@@ -788,13 +1093,36 @@ function resolveConfig(config) {
788
1093
  metadata: config?.metadata ?? {},
789
1094
  // No env fallback — see the field's note on RisicareConfig.
790
1095
  mask: config?.mask
791
- };
1096
+ });
1097
+ }
1098
+ function hideKeyFromInspect(config) {
1099
+ Object.defineProperty(config, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
1100
+ enumerable: false,
1101
+ value(_depth, options, inspect) {
1102
+ const { apiKey, ...rest } = this;
1103
+ return `RisicareConfig ${inspect({ ...rest, apiKey: apiKey ? "<redacted>" : "" }, options)}`;
1104
+ }
1105
+ });
1106
+ return config;
792
1107
  }
793
1108
  function parseBool(value, defaultValue) {
794
1109
  if (value === void 0) return defaultValue;
795
1110
  const lower = value.toLowerCase();
796
1111
  return lower === "true" || lower === "1" || lower === "yes";
797
1112
  }
1113
+ var TRACING_ON = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
1114
+ var TRACING_OFF = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
1115
+ function tracingFromEnv(value) {
1116
+ if (value === void 0) return void 0;
1117
+ const v = value.trim().toLowerCase();
1118
+ if (v === "") return void 0;
1119
+ if (TRACING_ON.has(v)) return true;
1120
+ if (TRACING_OFF.has(v)) return false;
1121
+ warn(
1122
+ `RISICARE_TRACING=${JSON.stringify(value.slice(0, 40))} is not a recognised value, so tracing is OFF. Use one of: true, 1, yes, on (tracing on) or false, 0, no, off (tracing off). Leave it unset or empty to use the default.`
1123
+ );
1124
+ return false;
1125
+ }
798
1126
  function parseNumericEnv(value, defaultValue) {
799
1127
  if (value === void 0) return defaultValue;
800
1128
  const n = Number(value);
@@ -1400,12 +1728,31 @@ var CANONICAL_ERROR_CODES = /* @__PURE__ */ new Set([
1400
1728
  "TOOL.RESULT.UNEXPECTED_FORMAT",
1401
1729
  "TOOL.RESULT.UNPARSEABLE"
1402
1730
  ]);
1731
+ var CORE_RULES = [
1732
+ { re: new RegExp("json", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" },
1733
+ { re: new RegExp("encoding", "u"), code: "PERCEPTION.INPUT.ENCODING" },
1734
+ { re: new RegExp("injection", "u"), code: "PERCEPTION.INPUT.INJECTION" },
1735
+ { re: new RegExp("malformed", "u"), code: "PERCEPTION.INPUT.MALFORMED" },
1736
+ { re: new RegExp("hallucin", "u"), code: "REASONING.HALLUCINATION.FACTUAL" },
1737
+ { re: new RegExp("contradict", "u"), code: "REASONING.LOGIC.CONTRADICTION" },
1738
+ { re: new RegExp("timeout", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
1739
+ { re: new RegExp("rate[^\\n]?limit", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1740
+ { re: new RegExp("permission", "u"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
1741
+ { re: new RegExp("context[^\\n]+overflow", "u"), code: "MEMORY.CONTEXT_WINDOW.EXCEEDED" },
1742
+ { re: new RegExp("state[^\\n]+corrupt", "u"), code: "MEMORY.STATE.CORRUPTED" },
1743
+ { re: new RegExp("pii", "u"), code: "OUTPUT.SAFETY.PII_LEAK" },
1744
+ { re: new RegExp("deadlock", "u"), code: "COORDINATION.WORKFLOW.DEADLOCK" },
1745
+ { re: new RegExp("undeliverable", "u"), code: "COMMUNICATION.DELIVERY.UNDELIVERABLE" },
1746
+ { re: new RegExp("crash", "u"), code: "ORCHESTRATION.LIFECYCLE.CRASHED" },
1747
+ { re: new RegExp("quorum", "u"), code: "CONSENSUS.AGREEMENT.QUORUM_FAILED" },
1748
+ { re: new RegExp("quota[^\\n]+exceed", "u"), code: "RESOURCES.QUOTA.EXCEEDED" }
1749
+ ];
1403
1750
  var SUPPLEMENTAL_RULES = [
1404
- { re: new RegExp("timeout|timedout|aborted", "i"), code: "TOOL.EXECUTION.TIMEOUT" },
1405
- { re: new RegExp("rate.?limit|\\b429\\b|too many requests", "i"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1406
- { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "i"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
1407
- { re: new RegExp("\\bauth|unauthorized|forbidden|permission|\\b401\\b|\\b403\\b", "i"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
1408
- { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "i"), code: "PERCEPTION.PARSING.JSON_INVALID" }
1751
+ { re: new RegExp("timeout|timedout|aborted", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
1752
+ { re: new RegExp("rate[^\\n]?limit|(?<![\\p{L}\\p{N}_])429(?![\\p{L}\\p{N}_])|too many requests", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1753
+ { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "u"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
1754
+ { 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" },
1755
+ { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" }
1409
1756
  ];
1410
1757
  var GENERIC_FALLBACK = "TOOL.EXECUTION.CRASHED";
1411
1758
 
@@ -1422,6 +1769,16 @@ var GuardRejectedError = class extends Error {
1422
1769
  this.phase = phase;
1423
1770
  }
1424
1771
  };
1772
+ function guardText(message) {
1773
+ if (!message || typeof message !== "object") return null;
1774
+ const content = message.content;
1775
+ if (typeof content === "string") return content === "" ? null : content;
1776
+ if (Array.isArray(content)) {
1777
+ const texts = content.filter((p) => !!p && typeof p === "object" && p.type === "text" && typeof p.text === "string").map((p) => p.text);
1778
+ if (texts.length > 0) return texts.join("\n");
1779
+ }
1780
+ return null;
1781
+ }
1425
1782
  function createInterceptContext(operationType, operationName, options) {
1426
1783
  return {
1427
1784
  operationType,
@@ -1481,8 +1838,8 @@ var DefaultFixInterceptor = class {
1481
1838
  }
1482
1839
  if (modifiedMessages && this._config.enabled) {
1483
1840
  for (const msg of modifiedMessages) {
1484
- const content = msg.content;
1485
- if (typeof content === "string") {
1841
+ const content = guardText(msg);
1842
+ if (content !== null) {
1486
1843
  for (const fix of this._cache.getAll()) {
1487
1844
  if (fix.fixType === "guard") {
1488
1845
  const { passed, result } = this._applier.applyGuardFix(
@@ -1627,7 +1984,13 @@ var DefaultFixInterceptor = class {
1627
1984
  }
1628
1985
  };
1629
1986
  function classifyError(error) {
1630
- const haystack = `${error?.constructor?.name ?? "Error"} ${error?.message ?? ""}`;
1987
+ const message = String(error?.message ?? "").toLowerCase();
1988
+ for (const rule of CORE_RULES) {
1989
+ if (rule.re.test(message)) {
1990
+ return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
1991
+ }
1992
+ }
1993
+ const haystack = `${error?.constructor?.name ?? "Error"} ${String(error?.message ?? "")}`.toLowerCase();
1631
1994
  for (const rule of SUPPLEMENTAL_RULES) {
1632
1995
  if (rule.re.test(haystack)) {
1633
1996
  return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
@@ -1643,6 +2006,9 @@ function storage() {
1643
2006
  function getContext() {
1644
2007
  return storage().getStore() ?? {};
1645
2008
  }
2009
+ function hasContextScope() {
2010
+ return storage().getStore() !== void 0;
2011
+ }
1646
2012
  function runWithContext(overrides, fn) {
1647
2013
  const parent = getContext();
1648
2014
  const merged = { ...parent, ...overrides };
@@ -1699,7 +2065,8 @@ function getCurrentContext() {
1699
2065
  // src/tracer.ts
1700
2066
  function attachErrorCode(span, error) {
1701
2067
  try {
1702
- const err = error instanceof Error ? error : new Error(String(error));
2068
+ const ownMessage = error !== null && typeof error === "object" ? error.message : void 0;
2069
+ const err = error instanceof Error ? error : new Error(typeof ownMessage === "string" ? ownMessage : String(error));
1703
2070
  const code = classifyError(err);
1704
2071
  if (code) {
1705
2072
  span.setAttribute("error.code", code);
@@ -1801,6 +2168,7 @@ var Tracer = class {
1801
2168
  (error) => {
1802
2169
  span.recordException(error instanceof Error ? error : String(error));
1803
2170
  attachErrorCode(span, error);
2171
+ markCancel(span, error);
1804
2172
  span.end();
1805
2173
  throw error;
1806
2174
  }
@@ -1811,6 +2179,7 @@ var Tracer = class {
1811
2179
  } catch (error) {
1812
2180
  span.recordException(error instanceof Error ? error : String(error));
1813
2181
  attachErrorCode(span, error);
2182
+ markCancel(span, error);
1814
2183
  span.end();
1815
2184
  throw error;
1816
2185
  }
@@ -1830,7 +2199,7 @@ var Tracer = class {
1830
2199
  const session2 = getCurrentSession();
1831
2200
  const agent2 = getCurrentAgent();
1832
2201
  const phase = getCurrentPhase();
1833
- const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();
2202
+ const traceId = opts.traceId ?? parentSpan?.traceId ?? getContext()._rootTraceId ?? generateTraceId();
1834
2203
  if (!parentSpan) {
1835
2204
  if (getContext()._traceSampled === false) {
1836
2205
  return NOOP_SPAN;
@@ -1866,9 +2235,15 @@ var Tracer = class {
1866
2235
  );
1867
2236
  }
1868
2237
  };
2238
+ function markCancel(span, error) {
2239
+ if (error instanceof Error && error.name === "AbortError") {
2240
+ span.setAttribute("risicare.cancelled", true);
2241
+ span.setAttribute("risicare.cancel_type", "AbortError");
2242
+ }
2243
+ }
1869
2244
 
1870
2245
  // src/version.ts
1871
- var SDK_VERSION = "0.7.0";
2246
+ var SDK_VERSION = "0.8.0";
1872
2247
 
1873
2248
  // src/exporters/http.ts
1874
2249
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
@@ -1876,6 +2251,8 @@ var RETRY_AFTER_CEILING_MS = 1e4;
1876
2251
  var REFUSAL_BACKOFF_BASE_MS = 1e3;
1877
2252
  var REFUSAL_NO_HINT = -1;
1878
2253
  var MISROUTE_WARN_WINDOW_MS = 3e5;
2254
+ var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
2255
+ var FAILURE_WARN_WINDOW_MS = 3e5;
1879
2256
  var HttpExporter = class {
1880
2257
  name = "http";
1881
2258
  _endpoint;
@@ -1891,21 +2268,24 @@ var HttpExporter = class {
1891
2268
  // cooldown gives the gateway time to come back before the half-open
1892
2269
  // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
1893
2270
  _consecutiveFailures = 0;
2271
+ _lastMisrouteWarnAt = -Infinity;
2272
+ _lastFailureWarnAt = -Infinity;
1894
2273
  /**
1895
- * F-SDK503-001. Set by `_sendRequest` when a response is a CAPACITY REFUSAL, read by the
1896
- * retry loop and the breaker. `null` = not a refusal; `REFUSAL_NO_HINT` = refused with no
1897
- * `Retry-After`; otherwise the honoured delay in ms.
1898
- *
1899
- * ⚠ Node has ONE thread and `export()` is `async`, so two concurrent exports interleave on
1900
- * this field at every `await`. It is written immediately after the awaited `fetch` resolves
1901
- * and read on the very next statement, with no `await` between — so the value cannot be
1902
- * clobbered mid-decision. The Python twin carries the same per-call state on `self` for the
1903
- * same reason (its `_send_request` signature is pin-locked).
2274
+ * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
2275
+ * 'unknown'). `null` after a success. A new kind in the same outage writes one more
2276
+ * WARNING, also inside the window.
1904
2277
  */
1905
- _lastRefusalAfterMs = null;
1906
- /** Set by `_sendRequest` on a MISROUTE: a short description of the answer. `null` = none. */
1907
- _lastMisroute = null;
1908
- _lastMisrouteWarnAt = -Infinity;
2278
+ _failureKind = null;
2279
+ /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
2280
+ _safeEndpoint;
2281
+ /** The endpoint holds userinfo. `fetch` refuses such a URL. */
2282
+ _endpointHasCredentials;
2283
+ /** The calls in progress, by their batch, so that `abort(spans)` stops the right one. */
2284
+ _calls = /* @__PURE__ */ new Map();
2285
+ /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */
2286
+ _acks = /* @__PURE__ */ new WeakMap();
2287
+ /** The spans of each finished call that could not be serialized, by its batch. */
2288
+ _unserializable = /* @__PURE__ */ new WeakMap();
1909
2289
  _circuitOpenUntil = 0;
1910
2290
  _circuitBreakerThreshold = 5;
1911
2291
  _circuitBreakerCooldownMs = 6e4;
@@ -1917,9 +2297,105 @@ var HttpExporter = class {
1917
2297
  this._timeoutMs = options.timeoutMs ?? 5e3;
1918
2298
  this._maxRetries = options.maxRetries ?? 3;
1919
2299
  this._compress = options.compress ?? false;
2300
+ this._safeEndpoint = safeUrl(this._endpoint);
2301
+ this._endpointHasCredentials = hasCredentials(this._endpoint);
2302
+ }
2303
+ /**
2304
+ * Network or error text for a log line: the endpoint as `safeUrl` gives it, and no
2305
+ * form of the API key (`utils/scrub.ts`).
2306
+ */
2307
+ _scrub(text, limit = 200) {
2308
+ let out;
2309
+ try {
2310
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
2311
+ } catch {
2312
+ out = typeof text;
2313
+ }
2314
+ if (this._safeEndpoint !== this._endpoint) out = out.split(this._endpoint).join(this._safeEndpoint);
2315
+ return scrubText(out, [this._apiKey], limit);
2316
+ }
2317
+ /** Hide the key from `util.inspect` and `console.log` of the exporter. */
2318
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
2319
+ return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
2320
+ }
2321
+ /** The most requests that one `export()` call sends (`maxRetries`). */
2322
+ get attemptsPerExport() {
2323
+ return this._maxRetries;
1920
2324
  }
2325
+ /**
2326
+ * Returns the counts of the ack that the `export()` call for `spans` received, and clears
2327
+ * them. The answer is kept per batch, not on the instance: two processors that share this
2328
+ * exporter cannot read each other's ack across an `await`.
2329
+ */
2330
+ takeAck(spans) {
2331
+ const ack = this._acks.get(spans) ?? null;
2332
+ this._acks.delete(spans);
2333
+ return ack;
2334
+ }
2335
+ /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
2336
+ takeUnserializable(spans) {
2337
+ const bad = this._unserializable.get(spans) ?? [];
2338
+ this._unserializable.delete(spans);
2339
+ return bad;
2340
+ }
2341
+ /**
2342
+ * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
2343
+ * request, its retries and its backoff sleep. The batch processor calls it when
2344
+ * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
2345
+ * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
2346
+ * logs no WARNING.
2347
+ */
2348
+ abort(spans) {
2349
+ if (spans !== void 0) this._calls.get(spans)?.cancel.abort();
2350
+ else for (const call of this._calls.values()) call.cancel.abort();
2351
+ }
2352
+ /**
2353
+ * Send one batch. The limits are the request timeout and `maxRetries`.
2354
+ *
2355
+ * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
2356
+ * cuts a request that is already sent. A short flush budget that cut the request made a
2357
+ * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
2358
+ * the server stored the same spans again. Only `abort()` stops the call, and only
2359
+ * `shutdown()` calls it.
2360
+ */
1921
2361
  async export(spans) {
1922
2362
  if (spans.length === 0) return "success" /* SUCCESS */;
2363
+ const call = {
2364
+ cancel: new AbortController(),
2365
+ refusalAfterMs: null,
2366
+ misroute: null,
2367
+ noRetry: false,
2368
+ status: null,
2369
+ error: null
2370
+ };
2371
+ this._calls.set(spans, call);
2372
+ try {
2373
+ return await this._export(spans, call);
2374
+ } finally {
2375
+ this._calls.delete(spans);
2376
+ }
2377
+ }
2378
+ async _export(spans, call) {
2379
+ const cancelled = call.cancel.signal;
2380
+ const parts = [];
2381
+ const bad = [];
2382
+ let errorClass = "";
2383
+ for (const span of spans) {
2384
+ try {
2385
+ parts.push(JSON.stringify(span.toPayload()));
2386
+ } catch (e) {
2387
+ bad.push(span);
2388
+ errorClass ||= e instanceof Error ? e.name : typeof e;
2389
+ }
2390
+ }
2391
+ if (bad.length > 0) {
2392
+ this._unserializable.set(spans, bad);
2393
+ warn(
2394
+ `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).`
2395
+ );
2396
+ }
2397
+ if (parts.length === 0) return "success" /* SUCCESS */;
2398
+ const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
1923
2399
  const now = Date.now();
1924
2400
  let isHalfOpen = false;
1925
2401
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
@@ -1928,44 +2404,64 @@ var HttpExporter = class {
1928
2404
  }
1929
2405
  isHalfOpen = true;
1930
2406
  }
1931
- const body = {
1932
- spans: spans.map((s) => s.toPayload())
1933
- };
1934
- if (this._projectId) body.projectId = this._projectId;
1935
- if (this._environment) body.environment = this._environment;
1936
2407
  const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
2408
+ let attempts = 0;
1937
2409
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1938
- this._lastRefusalAfterMs = null;
1939
- this._lastMisroute = null;
1940
- const result = await this._sendRequest(body);
2410
+ call.refusalAfterMs = null;
2411
+ call.misroute = null;
2412
+ call.noRetry = false;
2413
+ call.status = null;
2414
+ call.error = null;
2415
+ attempts++;
2416
+ const result = await this._sendRequest(payload, parts.length, call, spans);
2417
+ if (cancelled.aborted) {
2418
+ this._acks.delete(spans);
2419
+ return "failure" /* FAILURE */;
2420
+ }
1941
2421
  if (result === "success" /* SUCCESS */) {
1942
2422
  this._consecutiveFailures = 0;
2423
+ this._failureKind = null;
1943
2424
  return result;
1944
2425
  }
1945
- if (this._lastMisroute !== null) break;
2426
+ if (call.misroute !== null || call.noRetry) break;
2427
+ if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
1946
2428
  if (attempt < maxAttempts - 1) {
1947
- const refusal = this._lastRefusalAfterMs;
2429
+ const refusal = call.refusalAfterMs;
1948
2430
  const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
1949
- await sleep(delay);
2431
+ await sleep(delay, cancelled);
2432
+ if (cancelled.aborted) return "failure" /* FAILURE */;
1950
2433
  }
1951
2434
  }
1952
- const refusedForCapacity = this._lastRefusalAfterMs !== null;
1953
- this._lastRefusalAfterMs = null;
1954
- if (refusedForCapacity) {
2435
+ if (call.refusalAfterMs !== null) {
1955
2436
  warn(
1956
- `Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ${maxAttempts} attempt(s). This is a healthy server shedding load, not an outage \u2014 the batch is dropped but the exporter keeps sending. Reduce batch size or export rate if it persists.`
2437
+ `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.`
1957
2438
  );
1958
2439
  return "failure" /* FAILURE */;
1959
2440
  }
1960
- const misroute = this._lastMisroute;
1961
- this._lastMisroute = null;
2441
+ const misroute = call.misroute;
1962
2442
  if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
1963
2443
  this._lastMisrouteWarnAt = Date.now();
1964
2444
  warn(
1965
- `Risicare: spans are NOT reaching ${this._endpoint}. 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.`
2445
+ `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.`
1966
2446
  );
1967
2447
  }
1968
2448
  this._consecutiveFailures++;
2449
+ if (misroute === null && !call.noRetry) {
2450
+ const status = call.status;
2451
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
2452
+ let write = false;
2453
+ if (this._consecutiveFailures === 1 || this._failureKind === null) {
2454
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
2455
+ this._lastFailureWarnAt = Date.now();
2456
+ write = true;
2457
+ }
2458
+ this._failureKind = kind;
2459
+ } else if (kind !== this._failureKind) {
2460
+ this._failureKind = kind;
2461
+ write = true;
2462
+ }
2463
+ if (write) this._warnOutage(kind, status, call.error);
2464
+ }
1969
2465
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
1970
2466
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
1971
2467
  warn(
@@ -1974,10 +2470,36 @@ var HttpExporter = class {
1974
2470
  }
1975
2471
  return "failure" /* FAILURE */;
1976
2472
  }
2473
+ /** The outage WARNING for one kind of failure. */
2474
+ _warnOutage(kind, status, error) {
2475
+ const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
2476
+ const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
2477
+ if (kind === "auth") {
2478
+ warn(
2479
+ `${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}`
2480
+ );
2481
+ } else if (kind === "http") {
2482
+ warn(
2483
+ `${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.`
2484
+ );
2485
+ } else if (kind === "none" && this._endpointHasCredentials) {
2486
+ warn(
2487
+ `${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}`
2488
+ );
2489
+ } else if (kind === "none") {
2490
+ warn(
2491
+ `${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.`
2492
+ );
2493
+ } else {
2494
+ warn(
2495
+ `${where}: the export failed. Common causes: an invalid apiKey or an unreachable endpoint. ${tail} Set debug: true to see each attempt.`
2496
+ );
2497
+ }
2498
+ }
1977
2499
  /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
1978
- _noteMisroute(answer) {
1979
- this._lastMisroute = answer.slice(0, 300);
1980
- debug(`Ingest misroute: ${this._lastMisroute}`);
2500
+ _noteMisroute(call, answer) {
2501
+ call.misroute = this._scrub(answer, 300);
2502
+ debug(`Ingest misroute: ${call.misroute}`);
1981
2503
  return "failure" /* FAILURE */;
1982
2504
  }
1983
2505
  /**
@@ -1987,7 +2509,7 @@ var HttpExporter = class {
1987
2509
  * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
1988
2510
  * parse.
1989
2511
  */
1990
- _noteRefusal(status, retryAfterRaw) {
2512
+ _noteRefusal(call, status, retryAfterRaw) {
1991
2513
  if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
1992
2514
  let delay = REFUSAL_NO_HINT;
1993
2515
  if (retryAfterRaw) {
@@ -1996,11 +2518,13 @@ var HttpExporter = class {
1996
2518
  delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
1997
2519
  }
1998
2520
  }
1999
- this._lastRefusalAfterMs = delay;
2000
- debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);
2521
+ call.refusalAfterMs = delay;
2522
+ debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
2001
2523
  return true;
2002
2524
  }
2003
- async _sendRequest(body) {
2525
+ async _sendRequest(body, spansSent, call, spans) {
2526
+ const cancelled = call.cancel.signal;
2527
+ const timeoutMs = this._timeoutMs;
2004
2528
  const url = `${this._endpoint}/v1/spans`;
2005
2529
  const headers = {
2006
2530
  "Content-Type": "application/json",
@@ -2015,19 +2539,22 @@ var HttpExporter = class {
2015
2539
  if (this._apiKey) {
2016
2540
  headers["Authorization"] = `Bearer ${this._apiKey}`;
2017
2541
  }
2018
- let payload = JSON.stringify(body);
2542
+ let payload = body;
2019
2543
  if (this._compress && payload.length > 1024) {
2020
2544
  try {
2021
2545
  const { gzipSync } = await import("zlib");
2022
2546
  payload = gzipSync(Buffer.from(payload));
2023
2547
  headers["Content-Encoding"] = "gzip";
2024
2548
  } catch (e) {
2025
- debug(`Gzip compression failed, sending uncompressed: ${e}`);
2549
+ debug(`Gzip compression failed, sending uncompressed: ${this._scrub(e)}`);
2026
2550
  }
2027
2551
  }
2552
+ const controller = new AbortController();
2553
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
2554
+ const onCancel = () => controller.abort();
2555
+ cancelled.addEventListener("abort", onCancel, { once: true });
2556
+ if (cancelled.aborted) controller.abort();
2028
2557
  try {
2029
- const controller = new AbortController();
2030
- const timeoutId = setTimeout(() => controller.abort(), this._timeoutMs);
2031
2558
  const response = await fetch(url, {
2032
2559
  method: "POST",
2033
2560
  headers,
@@ -2037,40 +2564,89 @@ var HttpExporter = class {
2037
2564
  // the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.
2038
2565
  redirect: "manual"
2039
2566
  });
2040
- clearTimeout(timeoutId);
2567
+ call.status = response.status;
2041
2568
  const redirected = response.type === "opaqueredirect";
2042
2569
  if (redirected || response.status >= 300 && response.status < 400) {
2043
2570
  const location = response.headers?.get?.("Location");
2044
- const target = location ? location.slice(0, 200) : "no Location header";
2045
- return this._noteMisroute(`HTTP ${response.status || "3xx"}, a redirect to ${target}`);
2571
+ const target = location ? this._scrub(location, 1e3) : "no Location header";
2572
+ return this._noteMisroute(call, `HTTP ${response.status || "3xx"}, a redirect to ${target}`);
2046
2573
  }
2047
2574
  if (response.status >= 200 && response.status < 300) {
2048
- const ack = await checkAck(response);
2049
- return ack === null ? this._noteMisroute(
2050
- `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
2051
- ) : ack;
2575
+ const ack = await checkAck(response, spansSent, (t) => this._scrub(t, 1e3));
2576
+ if (ack === null) {
2577
+ if (controller.signal.aborted) {
2578
+ call.status = null;
2579
+ call.error = `timeout after ${timeoutMs} ms`;
2580
+ debug(`HTTP export timeout: the ack body did not arrive within ${timeoutMs} ms`);
2581
+ return "timeout" /* TIMEOUT */;
2582
+ }
2583
+ return this._noteMisroute(
2584
+ call,
2585
+ `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
2586
+ );
2587
+ }
2588
+ if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
2589
+ if (ack.final) call.noRetry = true;
2590
+ return ack.result;
2052
2591
  } else if (response.status === 408 || response.status === 504) {
2053
2592
  debug(`HTTP export timeout: ${response.status}`);
2054
2593
  return "timeout" /* TIMEOUT */;
2055
2594
  }
2056
- this._noteRefusal(response.status, response.headers.get("Retry-After"));
2595
+ this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
2057
2596
  debug(`HTTP export failed: ${response.status}`);
2058
2597
  return "failure" /* FAILURE */;
2059
2598
  } catch (e) {
2060
- debug(`HTTP export error: ${e}`);
2599
+ const cause = e instanceof Error ? e.cause : void 0;
2600
+ call.error = controller.signal.aborted ? `timeout after ${timeoutMs} ms` : typeof cause?.code === "string" ? cause.code : e instanceof Error ? e.name : "Error";
2601
+ debug(`HTTP export error: ${this._scrub(e)}`);
2061
2602
  return "failure" /* FAILURE */;
2603
+ } finally {
2604
+ clearTimeout(timeoutId);
2605
+ cancelled.removeEventListener("abort", onCancel);
2062
2606
  }
2063
2607
  }
2064
2608
  shutdown() {
2065
2609
  }
2066
2610
  };
2067
- function sleep(ms) {
2068
- return new Promise((resolve) => setTimeout(resolve, ms));
2611
+ function sleep(ms, signal) {
2612
+ return new Promise((resolve) => {
2613
+ if (signal?.aborted) return resolve();
2614
+ const done = () => {
2615
+ clearTimeout(timer);
2616
+ signal?.removeEventListener("abort", done);
2617
+ resolve();
2618
+ };
2619
+ const timer = setTimeout(done, ms);
2620
+ signal?.addEventListener("abort", done, { once: true });
2621
+ });
2069
2622
  }
2070
2623
  function asCount(v) {
2071
2624
  return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
2072
2625
  }
2073
- async function checkAck(response) {
2626
+ var MAX_ACK_REASONS = 3;
2627
+ var MAX_ACK_REASON_CHARS = 200;
2628
+ function oneLine(text) {
2629
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ");
2630
+ }
2631
+ function ackReasons(body) {
2632
+ const reasons = [];
2633
+ const errors = body.errors;
2634
+ if (Array.isArray(errors)) {
2635
+ for (const entry of errors) {
2636
+ const text = entry?.error;
2637
+ if (typeof text !== "string" || text.length === 0) continue;
2638
+ const cut = oneLine(text).slice(0, MAX_ACK_REASON_CHARS);
2639
+ if (!reasons.includes(cut)) reasons.push(cut);
2640
+ if (reasons.length === MAX_ACK_REASONS) break;
2641
+ }
2642
+ }
2643
+ if (reasons.length === 0) {
2644
+ const message = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || "";
2645
+ if (message) reasons.push(oneLine(message).slice(0, MAX_ACK_REASON_CHARS));
2646
+ }
2647
+ return reasons.length === 0 ? "No reason was returned." : `Reasons: ${reasons.join("; ")}`;
2648
+ }
2649
+ async function checkAck(response, spansSent, scrub) {
2074
2650
  let payload;
2075
2651
  try {
2076
2652
  payload = await response.json();
@@ -2084,25 +2660,35 @@ async function checkAck(response) {
2084
2660
  const accepted = asCount(body.accepted);
2085
2661
  const rejected = asCount(body.rejected);
2086
2662
  if (accepted === void 0 || rejected === void 0) return null;
2087
- if (rejected === 0) return "success" /* SUCCESS */;
2088
- const errors = body.errors;
2089
- const detail = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || (Array.isArray(errors) && errors.length > 0 ? JSON.stringify(errors[0]) : "") || "No reason was returned.";
2663
+ const counts = { accepted, rejected };
2664
+ if (accepted === 0 && rejected === 0 && spansSent > 0) {
2665
+ warn(
2666
+ `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.`
2667
+ );
2668
+ return { result: "failure" /* FAILURE */, counts, final: true };
2669
+ }
2670
+ if (rejected === 0) return { result: "success" /* SUCCESS */, counts, final: false };
2090
2671
  const total = accepted + rejected;
2091
2672
  if (accepted === 0) {
2092
2673
  warn(
2093
- `Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. ${detail}`
2674
+ `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))}`
2094
2675
  );
2095
- return "failure" /* FAILURE */;
2676
+ return { result: "success" /* SUCCESS */, counts, final: false };
2096
2677
  }
2097
2678
  warn(
2098
- `Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ${accepted} were stored. Those ${rejected} are permanently lost and are NOT retried. ${detail}`
2679
+ `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))}`
2099
2680
  );
2100
- return "success" /* SUCCESS */;
2681
+ return { result: "success" /* SUCCESS */, counts, final: false };
2101
2682
  }
2102
2683
 
2103
2684
  // src/exporters/console.ts
2104
2685
  var ConsoleExporter = class {
2105
2686
  name = "console";
2687
+ /**
2688
+ * It only shows spans locally, so its success is not a delivery. When another
2689
+ * exporter is present, the batch processor ignores this exporter's result.
2690
+ */
2691
+ countsAsDelivery = false;
2106
2692
  export(spans) {
2107
2693
  for (const span of spans) {
2108
2694
  const payload = span.toPayload();
@@ -2116,6 +2702,17 @@ var ConsoleExporter = class {
2116
2702
  }
2117
2703
  };
2118
2704
 
2705
+ // src/utils/stream-proxy.ts
2706
+ function endOpenProviderSpans() {
2707
+ let open;
2708
+ try {
2709
+ open = [...getProviderSpanState().open];
2710
+ } catch {
2711
+ return;
2712
+ }
2713
+ for (const o of open) o.end("shutdown");
2714
+ }
2715
+
2119
2716
  // src/runtime/cache.ts
2120
2717
  var FixCache = class {
2121
2718
  _ttlMs;
@@ -2291,6 +2888,94 @@ function emptyResult(fix, fixType) {
2291
2888
  modifications: {}
2292
2889
  };
2293
2890
  }
2891
+ var SAME_ESCAPES = "bBdDsSwWfnrtv";
2892
+ var SAME_ESCAPES_IN_CLASS = "bdDsSwWfnrtv";
2893
+ var LEADING_INLINE_FLAGS = /^\(\?([ims]+)\)/;
2894
+ var PY_NAMED_GROUP = /^\(\?P<([A-Za-z_][A-Za-z0-9_]*)>/;
2895
+ var PY_NAMED_BACKREF = /^\(\?P=([A-Za-z_][A-Za-z0-9_]*)\)/;
2896
+ var JS_NAMED_GROUP = /^\(\?<([A-Za-z_][A-Za-z0-9_]*)>/;
2897
+ function translatePythonPattern(pattern) {
2898
+ let flags = "i";
2899
+ let rest = pattern;
2900
+ const m = LEADING_INLINE_FLAGS.exec(rest);
2901
+ if (m) {
2902
+ for (const f of m[1]) if (!flags.includes(f)) flags += f;
2903
+ rest = rest.slice(m[0].length);
2904
+ }
2905
+ const names = /* @__PURE__ */ new Set();
2906
+ const addName = (name) => {
2907
+ if (names.has(name)) throw new Error("a group name occurs two times");
2908
+ names.add(name);
2909
+ };
2910
+ let source = "";
2911
+ let inClass = false;
2912
+ for (let i = 0; i < rest.length; i++) {
2913
+ const c = rest[i];
2914
+ if (c === "\\" && i + 1 < rest.length) {
2915
+ const next = rest[i + 1];
2916
+ if (/[A-Za-z]/.test(next)) {
2917
+ if (!inClass && next === "A") {
2918
+ source += "(?<![\\s\\S])";
2919
+ i++;
2920
+ continue;
2921
+ }
2922
+ if (!inClass && next === "Z") {
2923
+ source += "(?![\\s\\S])";
2924
+ i++;
2925
+ continue;
2926
+ }
2927
+ if (next === "x" || next === "u") {
2928
+ const n = next === "x" ? 2 : 4;
2929
+ const hex = rest.slice(i + 2, i + 2 + n);
2930
+ if (!new RegExp(`^[0-9A-Fa-f]{${n}}$`).test(hex)) throw new Error("short hex escape");
2931
+ source += c + next + hex;
2932
+ i += 1 + n;
2933
+ continue;
2934
+ }
2935
+ if (!(inClass ? SAME_ESCAPES_IN_CLASS : SAME_ESCAPES).includes(next)) {
2936
+ throw new Error("an escape that Python and JavaScript read differently");
2937
+ }
2938
+ }
2939
+ source += c + next;
2940
+ i++;
2941
+ continue;
2942
+ }
2943
+ if (inClass) {
2944
+ if (c === "]") inClass = false;
2945
+ source += c;
2946
+ continue;
2947
+ }
2948
+ if (c === "[") {
2949
+ inClass = true;
2950
+ source += c;
2951
+ continue;
2952
+ }
2953
+ const tail = rest.slice(i);
2954
+ let g;
2955
+ if ((g = PY_NAMED_GROUP.exec(tail)) || (g = JS_NAMED_GROUP.exec(tail))) {
2956
+ addName(g[1]);
2957
+ source += `(?<${g[1]}>`;
2958
+ i += g[0].length - 1;
2959
+ continue;
2960
+ }
2961
+ if (g = PY_NAMED_BACKREF.exec(tail)) {
2962
+ source += `\\k<${g[1]}>`;
2963
+ i += g[0].length - 1;
2964
+ continue;
2965
+ }
2966
+ source += c;
2967
+ }
2968
+ return { source, flags };
2969
+ }
2970
+ var warnedGuardPatterns = /* @__PURE__ */ new Set();
2971
+ function warnUnusablePattern(fixId, index) {
2972
+ const key = `${fixId ?? "unknown"}\0${index}`;
2973
+ if (warnedGuardPatterns.has(key)) return;
2974
+ warnedGuardPatterns.add(key);
2975
+ warn(
2976
+ index < 0 ? `Guard fix ${fixId ?? "unknown"}: blocked_patterns is not a list. The guard rejects every call.` : `Guard fix ${fixId ?? "unknown"}: blocked pattern ${index} is not usable (empty, not a string, longer than 500 characters, or it does not compile). The guard rejects every call.`
2977
+ );
2978
+ }
2294
2979
  var FixApplier = class {
2295
2980
  _config;
2296
2981
  _cache;
@@ -2548,6 +3233,26 @@ var FixApplier = class {
2548
3233
  * - content_filter: Regex-based blocked patterns
2549
3234
  * - format_check: JSON.parse() validity
2550
3235
  * - input_validation / output_validation: min/max length
3236
+ *
3237
+ * `content_filter` searches the content for each entry of `blocked_patterns`
3238
+ * (case-insensitive, after `translatePythonPattern`). It fails CLOSED: when
3239
+ * `blocked_patterns` is not a list, or an entry is empty, is not a string,
3240
+ * is longer than 500 characters or cannot be used, the guard does not pass.
3241
+ * One WARNING names the fix id and the pattern index, once for each pair in
3242
+ * the process. The reason names the pattern index, never the pattern or the
3243
+ * content.
3244
+ *
3245
+ * Limits:
3246
+ * - The interceptor runs only on the OpenAI chat patch (input guards) and on
3247
+ * `interceptCall` / `interceptResponse`. It does not run when a framework
3248
+ * integration suppresses provider instrumentation.
3249
+ * - Each SDK uses its own regular-expression engine. These constructs can
3250
+ * give a different result in JavaScript and Python: `$` before a final
3251
+ * newline, Unicode case folding, `\d` and `\w` on non-ASCII text,
3252
+ * `\N{...}` and `\U........` (JavaScript fails closed), and a `]` first
3253
+ * in a class.
3254
+ * - A pattern has no time bound. A pattern with nested repeats can take a
3255
+ * very long time on a long input.
2551
3256
  */
2552
3257
  applyGuardFix(fix, content, isInput = true) {
2553
3258
  try {
@@ -2568,13 +3273,25 @@ var FixApplier = class {
2568
3273
  let passed = true;
2569
3274
  let reason;
2570
3275
  if (guardType === "content_filter") {
2571
- const blockedPatterns = guardConfig.blocked_patterns ?? guardConfig.blockedPatterns ?? [];
2572
- for (const pattern of blockedPatterns) {
2573
- const regex = this._safeCompileRegex(pattern);
2574
- if (regex && regex.test(content)) {
2575
- passed = false;
2576
- reason = `blocked pattern matched: ${pattern.slice(0, 80)}`;
2577
- break;
3276
+ const blockedPatterns = "blocked_patterns" in guardConfig ? guardConfig.blocked_patterns : "blockedPatterns" in guardConfig ? guardConfig.blockedPatterns : [];
3277
+ if (!Array.isArray(blockedPatterns)) {
3278
+ warnUnusablePattern(fix.fixId, -1);
3279
+ passed = false;
3280
+ reason = "blocked_patterns is not a list";
3281
+ } else {
3282
+ for (let index = 0; index < blockedPatterns.length; index++) {
3283
+ const regex = this._safeCompileRegex(blockedPatterns[index]);
3284
+ if (!regex) {
3285
+ warnUnusablePattern(fix.fixId, index);
3286
+ passed = false;
3287
+ reason = `blocked pattern ${index} is not usable`;
3288
+ break;
3289
+ }
3290
+ if (regex.test(content)) {
3291
+ passed = false;
3292
+ reason = `blocked pattern matched (pattern ${index})`;
3293
+ break;
3294
+ }
2578
3295
  }
2579
3296
  }
2580
3297
  } else if (guardType === "format_check") {
@@ -2635,11 +3352,17 @@ var FixApplier = class {
2635
3352
  /**
2636
3353
  * Safely compile a regex pattern from untrusted input.
2637
3354
  * Returns null if invalid or too long.
3355
+ *
3356
+ * F-029: the fix patterns are written for Python `re`. Before it compiles
3357
+ * the pattern, this function translates the Python forms that have an exact
3358
+ * JavaScript equivalent (see `translatePythonPattern`). The `i` flag is
3359
+ * always on, as in the Python applier.
2638
3360
  */
2639
3361
  _safeCompileRegex(pattern, maxLength = 500) {
2640
- if (!pattern || pattern.length > maxLength) return null;
3362
+ if (typeof pattern !== "string" || !pattern || pattern.length > maxLength) return null;
2641
3363
  try {
2642
- return new RegExp(pattern, "i");
3364
+ const { source, flags } = translatePythonPattern(pattern);
3365
+ return new RegExp(source, flags);
2643
3366
  } catch {
2644
3367
  debug(`Invalid regex pattern (length=${pattern.length})`);
2645
3368
  return null;
@@ -2715,6 +3438,8 @@ var FixLoader = class _FixLoader {
2715
3438
  _consecutiveFailures = 0;
2716
3439
  _circuitOpenUntil = 0;
2717
3440
  _onLoadCallbacks = [];
3441
+ // The HTTP status of the last load that got a non-2xx answer; null otherwise.
3442
+ _lastStatus = null;
2718
3443
  // Circuit breaker settings
2719
3444
  static CIRCUIT_BREAKER_THRESHOLD = 3;
2720
3445
  static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
@@ -2722,6 +3447,43 @@ var FixLoader = class _FixLoader {
2722
3447
  this._config = resolveFixRuntimeConfig(config);
2723
3448
  this._cache = cache;
2724
3449
  }
3450
+ /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */
3451
+ _scrub(error) {
3452
+ let out;
3453
+ try {
3454
+ out = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
3455
+ } catch {
3456
+ out = typeof error;
3457
+ }
3458
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
3459
+ if (endpoint && safeUrl(endpoint) !== endpoint) out = out.split(endpoint).join(safeUrl(endpoint));
3460
+ return scrubText(out, [this._config.apiKey]);
3461
+ }
3462
+ /**
3463
+ * The WARNING for a failed first load: the request URL with no userinfo, no
3464
+ * query and no key, the HTTP status or the error class, and that tracing is
3465
+ * not affected. Never the error text: it can echo the URL with its query.
3466
+ */
3467
+ _firstLoadWarning(error) {
3468
+ let cause;
3469
+ if (this._lastStatus !== null) {
3470
+ cause = `HTTP ${this._lastStatus}`;
3471
+ } else {
3472
+ cause = error instanceof Error ? error.name : typeof error;
3473
+ const code = error?.cause?.code;
3474
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code)) cause += ` (${code})`;
3475
+ }
3476
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
3477
+ return scrubText(
3478
+ `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.`,
3479
+ [this._config.apiKey],
3480
+ 500
3481
+ );
3482
+ }
3483
+ /** Hide the key from `util.inspect` and `console.log` of the loader. */
3484
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
3485
+ return "FixLoader {}";
3486
+ }
2725
3487
  /** Timestamp of last successful load. */
2726
3488
  get lastLoadTime() {
2727
3489
  return this._lastLoadTime;
@@ -2742,13 +3504,13 @@ var FixLoader = class _FixLoader {
2742
3504
  return;
2743
3505
  }
2744
3506
  this.loadSync().catch((e) => {
2745
- debug(`Initial fix load failed: ${e}`);
3507
+ warn(this._firstLoadWarning(e));
2746
3508
  });
2747
3509
  if (this._config.autoRefresh) {
2748
3510
  this._startRefreshInterval();
2749
3511
  }
2750
3512
  } catch (e) {
2751
- debug(`FixLoader.start error: ${e}`);
3513
+ debug(`FixLoader.start error: ${this._scrub(e)}`);
2752
3514
  }
2753
3515
  }
2754
3516
  /** Stop the loader: clear the refresh interval. */
@@ -2759,7 +3521,7 @@ var FixLoader = class _FixLoader {
2759
3521
  this._refreshTimer = null;
2760
3522
  }
2761
3523
  } catch (e) {
2762
- debug(`FixLoader.stop error: ${e}`);
3524
+ debug(`FixLoader.stop error: ${this._scrub(e)}`);
2763
3525
  }
2764
3526
  }
2765
3527
  /**
@@ -2783,6 +3545,7 @@ var FixLoader = class _FixLoader {
2783
3545
  debug("Fix loader circuit breaker open \u2014 skipping load");
2784
3546
  return this._cache.getAll();
2785
3547
  }
3548
+ this._lastStatus = null;
2786
3549
  try {
2787
3550
  const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
2788
3551
  const url = `${endpoint}/v1/fixes/active`;
@@ -2802,6 +3565,7 @@ var FixLoader = class _FixLoader {
2802
3565
  });
2803
3566
  clearTimeout(timeoutId);
2804
3567
  if (!response.ok) {
3568
+ this._lastStatus = response.status;
2805
3569
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
2806
3570
  }
2807
3571
  const data = await response.json();
@@ -2828,7 +3592,7 @@ var FixLoader = class _FixLoader {
2828
3592
  fixes.push(activeFixFromApiResponse(item));
2829
3593
  }
2830
3594
  } catch (e) {
2831
- debug(`Failed to parse fix item: ${e}`);
3595
+ debug(`Failed to parse fix item: ${this._scrub(e)}`);
2832
3596
  }
2833
3597
  }
2834
3598
  return fixes;
@@ -2841,7 +3605,7 @@ var FixLoader = class _FixLoader {
2841
3605
  try {
2842
3606
  callback(fixes);
2843
3607
  } catch (e) {
2844
- debug(`Load callback error: ${e}`);
3608
+ debug(`Load callback error: ${this._scrub(e)}`);
2845
3609
  }
2846
3610
  }
2847
3611
  debug(`Loaded ${fixes.length} active fixes`);
@@ -2855,14 +3619,14 @@ var FixLoader = class _FixLoader {
2855
3619
  );
2856
3620
  } else {
2857
3621
  debug(
2858
- `Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
3622
+ `Fix load failed (attempt ${this._consecutiveFailures}): ${this._scrub(error)}`
2859
3623
  );
2860
3624
  }
2861
3625
  }
2862
3626
  _startRefreshInterval() {
2863
3627
  const tick = () => {
2864
3628
  this.loadSync().catch((e) => {
2865
- debug(`Background fix refresh failed: ${e}`);
3629
+ debug(`Background fix refresh failed: ${this._scrub(e)}`);
2866
3630
  });
2867
3631
  };
2868
3632
  this._refreshTimer = setInterval(
@@ -3130,6 +3894,78 @@ var TERMINATING_SIGNALS = [
3130
3894
  ];
3131
3895
  var BACKSTOP_MARGIN_MS = 500;
3132
3896
  var _finalMetrics;
3897
+ var SCORE_TIMEOUT_MS = 2e3;
3898
+ var _pendingScores = /* @__PURE__ */ new Set();
3899
+ var _failedScores = 0;
3900
+ var _failedScoresFlushMark = 0;
3901
+ var SCORE_MAX_IN_FLIGHT = 50;
3902
+ var SCORE_MAX_WAITING = 1e3;
3903
+ var SCORE_CAP_REASON = `not sent: ${SCORE_MAX_WAITING} scores wait for a free slot`;
3904
+ var SCORE_DEADLINE_REASON = "not sent before the deadline";
3905
+ var _scoresInFlight = 0;
3906
+ var _scoreWaiters = [];
3907
+ function _startWaitingScores() {
3908
+ while (_scoresInFlight < SCORE_MAX_IN_FLIGHT && _scoreWaiters.length > 0) {
3909
+ _scoreWaiters.shift().start();
3910
+ }
3911
+ }
3912
+ function _failWaitingScores(reason) {
3913
+ for (const waiter of _scoreWaiters.splice(0)) waiter.fail(reason);
3914
+ }
3915
+ var _scoreWarnWindowMs = 1e4;
3916
+ var SCORE_NAME_MAX = 200;
3917
+ var _scoreWarnedAt;
3918
+ var _scoreHeld = 0;
3919
+ var _scoreHeldReason = "";
3920
+ function _resetScoreFailures() {
3921
+ _failedScores = 0;
3922
+ _failedScoresFlushMark = 0;
3923
+ _scoreWarnedAt = void 0;
3924
+ _scoreHeld = 0;
3925
+ _scoreHeldReason = "";
3926
+ }
3927
+ function _heldText() {
3928
+ return ` ${_scoreHeld} more scores failed after the last warning. The last reason: ${_scoreHeldReason}.`;
3929
+ }
3930
+ function _scoreFailed(name, reason) {
3931
+ _failedScores += 1;
3932
+ const now = Date.now();
3933
+ if (_scoreWarnedAt !== void 0 && now - _scoreWarnedAt < _scoreWarnWindowMs) {
3934
+ _scoreHeld += 1;
3935
+ _scoreHeldReason = reason;
3936
+ return;
3937
+ }
3938
+ let message = `score ${JSON.stringify(name.slice(0, SCORE_NAME_MAX))} failed: ${reason}.`;
3939
+ if (_scoreHeld > 0) message += _heldText();
3940
+ _scoreWarnedAt = now;
3941
+ _scoreHeld = 0;
3942
+ _scoreHeldReason = "";
3943
+ warn(message);
3944
+ }
3945
+ function _warnHeldScores() {
3946
+ if (_scoreHeld === 0) return;
3947
+ const message = _heldText().trimStart();
3948
+ _scoreWarnedAt = Date.now();
3949
+ _scoreHeld = 0;
3950
+ _scoreHeldReason = "";
3951
+ warn(message);
3952
+ }
3953
+ async function _waitForPendingScores(timeoutMs) {
3954
+ if (_pendingScores.size === 0) return true;
3955
+ let timer;
3956
+ const expired = new Promise((resolve) => {
3957
+ timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
3958
+ });
3959
+ const settled = (async () => {
3960
+ while (_pendingScores.size > 0) await Promise.all([..._pendingScores]);
3961
+ return true;
3962
+ })();
3963
+ try {
3964
+ return await Promise.race([settled, expired]);
3965
+ } finally {
3966
+ clearTimeout(timer);
3967
+ }
3968
+ }
3133
3969
  var RisicareClient = class {
3134
3970
  config;
3135
3971
  processor;
@@ -3142,8 +3978,17 @@ var RisicareClient = class {
3142
3978
  _shutdownHandlers = [];
3143
3979
  constructor(config) {
3144
3980
  this.config = resolveConfig(config);
3145
- if (this.config.apiKey && !this.config.apiKey.startsWith("rsk-")) {
3146
- debug('Warning: API key should start with "rsk-". Got: ' + this.config.apiKey.slice(0, 4) + "...");
3981
+ const hasKnownPrefix = this.config.apiKey?.startsWith("rsk-") || this.config.apiKey?.startsWith("rski_") || this.config.apiKey?.startsWith("rsks_");
3982
+ if (this.config.apiKey && !hasKnownPrefix) {
3983
+ warn(
3984
+ 'the API key does not look like a Risicare key: it should start with "rsk-", "rski_" or "rsks_". Tracing continues with this key.'
3985
+ );
3986
+ }
3987
+ const tracingSetExplicitly = config?.enabled !== void 0 || (process.env.RISICARE_TRACING ?? "").trim() !== "";
3988
+ if (!this.config.apiKey && !this.config.enabled && !tracingSetExplicitly) {
3989
+ warn(
3990
+ "Risicare found no API key. Tracing is off and the SDK sends no span. Pass apiKey to init() or set RISICARE_API_KEY."
3991
+ );
3147
3992
  }
3148
3993
  let exporter;
3149
3994
  if (this.config.debug && !this.config.apiKey) {
@@ -3207,21 +4052,23 @@ var RisicareClient = class {
3207
4052
  });
3208
4053
  } catch (e) {
3209
4054
  const errName = e instanceof Error ? e.name : "Error";
3210
- const errMsg = e instanceof Error ? e.message : String(e);
4055
+ const errMsg = scrubText(e instanceof Error ? e.message : String(e), [this.config.apiKey]);
3211
4056
  try {
3212
4057
  console.warn(
3213
- `[risicare] FixRuntime initialization failed \u2014 auto-fix is OFFLINE for this process. endpoint=${this.config.endpoint} error=${errName}: ${errMsg}. Tracing + reporting still work; only fix application is disabled. Pass debug:true in init() options for the full traceback.`
4058
+ `[risicare] FixRuntime initialization failed \u2014 auto-fix is OFFLINE for this process. apiEndpoint=${safeUrl(this.config.apiEndpoint)} error=${errName}: ${errMsg}. Tracing + reporting still work; only fix application is disabled. Pass debug:true in init() options for the full traceback.`
3214
4059
  );
3215
4060
  } catch {
3216
4061
  }
3217
4062
  if (this.config.debug) {
3218
- debug(`FixRuntime init traceback: ${e instanceof Error && e.stack ? e.stack : String(e)}`);
4063
+ debug(
4064
+ `FixRuntime init traceback: ${scrubText(e instanceof Error && e.stack ? e.stack : String(e), [this.config.apiKey], 2e3)}`
4065
+ );
3219
4066
  }
3220
4067
  }
3221
4068
  }
3222
4069
  this._registerShutdownHooks();
3223
4070
  setDebug(this.config.debug);
3224
- debug(`Initialized: enabled=${this.config.enabled}, endpoint=${this.config.endpoint}`);
4071
+ debug(`Initialized: enabled=${this.config.enabled}, endpoint=${safeUrl(this.config.endpoint)}`);
3225
4072
  if (!this.config.fixRuntime) {
3226
4073
  debug(
3227
4074
  "FixRuntime is off: nothing polls /fixes/active and no fix is applied. Opt in with fixRuntime: true or RISICARE_FIX_RUNTIME=true."
@@ -3235,18 +4082,20 @@ var RisicareClient = class {
3235
4082
  this.tracer.enabled = value;
3236
4083
  }
3237
4084
  // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)
3238
- async shutdown() {
4085
+ async shutdown(timeoutMs) {
3239
4086
  if (this._shutdownPromise) return this._shutdownPromise;
3240
- this._shutdownPromise = this._doShutdown();
4087
+ this._shutdownPromise = this._doShutdown(timeoutMs);
3241
4088
  return this._shutdownPromise;
3242
4089
  }
3243
- async _doShutdown() {
4090
+ async _doShutdown(timeoutMs) {
3244
4091
  debug("Shutting down...");
3245
4092
  for (const { signal, handler } of this._shutdownHandlers) {
3246
4093
  process.removeListener(signal, handler);
3247
4094
  }
3248
4095
  this._shutdownHandlers = [];
3249
- await this.processor.shutdown();
4096
+ endOpenProviderSpans();
4097
+ await this.processor.shutdown(timeoutMs);
4098
+ _failWaitingScores(SCORE_DEADLINE_REASON);
3250
4099
  this.isShutdown = true;
3251
4100
  _finalMetrics = this.processor.getMetrics();
3252
4101
  }
@@ -3261,8 +4110,8 @@ var RisicareClient = class {
3261
4110
  * false one — both leave the customer unable to tell *drained* from
3262
4111
  * *discarded*.
3263
4112
  */
3264
- async flush() {
3265
- return this.processor.flush();
4113
+ async flush(timeoutMs) {
4114
+ return this.processor.flush(timeoutMs);
3266
4115
  }
3267
4116
  /**
3268
4117
  * SDK-RELEASE-RULING.md §3 — who decides whether the process dies.
@@ -3360,25 +4209,39 @@ function init(config) {
3360
4209
  return;
3361
4210
  }
3362
4211
  _finalMetrics = void 0;
4212
+ _resetScoreFailures();
3363
4213
  const client = new RisicareClient(config);
3364
4214
  setClient(client);
3365
4215
  setTracer(client.tracer);
3366
4216
  }
3367
- async function shutdown() {
4217
+ async function shutdown(timeoutMs) {
3368
4218
  try {
3369
4219
  shutdownFixRuntime();
3370
4220
  } catch {
3371
4221
  }
3372
4222
  const client = getClient();
3373
4223
  if (!client) return;
3374
- await client.shutdown();
4224
+ await client.shutdown(timeoutMs);
3375
4225
  setClient(void 0);
3376
4226
  setTracer(void 0);
3377
4227
  }
3378
- async function flush() {
4228
+ async function flush(timeoutMs) {
4229
+ const budgetMs = normalizeTimeoutMs(timeoutMs);
4230
+ const deadline = Date.now() + budgetMs;
4231
+ const scoreMark = _failedScoresFlushMark;
3379
4232
  const client = getClient();
3380
- if (!client) return true;
3381
- return client.flush();
4233
+ let spansOk;
4234
+ if (!client) {
4235
+ spansOk = (_finalMetrics?.droppedSpansByReason.shutdown_residue ?? 0) === 0;
4236
+ } else {
4237
+ spansOk = await client.flush(timeoutMs);
4238
+ }
4239
+ const scoresDone = await _waitForPendingScores(deadline - Date.now());
4240
+ if (!scoresDone) _failWaitingScores(SCORE_DEADLINE_REASON);
4241
+ _warnHeldScores();
4242
+ const failedNow = _failedScores;
4243
+ if (failedNow > _failedScoresFlushMark) _failedScoresFlushMark = failedNow;
4244
+ return spansOk && scoresDone && failedNow <= scoreMark;
3382
4245
  }
3383
4246
  function enable() {
3384
4247
  const client = getClient();
@@ -3402,22 +4265,30 @@ function getTraceContent() {
3402
4265
  function getMetrics() {
3403
4266
  const client = getClient();
3404
4267
  if (client && !client.isShutdown) {
3405
- return { ...client.processor.getMetrics(), sdkState: "running" };
4268
+ return {
4269
+ ...client.processor.getMetrics(),
4270
+ failedScores: _failedScores,
4271
+ sdkState: "running"
4272
+ };
3406
4273
  }
3407
4274
  if (_finalMetrics) {
3408
4275
  return {
3409
4276
  ..._finalMetrics,
4277
+ failedScores: _failedScores,
3410
4278
  droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
3411
4279
  sdkState: "shutdown"
3412
4280
  };
3413
4281
  }
3414
4282
  return {
3415
4283
  exportedSpans: 0,
4284
+ rejectedSpans: 0,
4285
+ failedScores: _failedScores,
3416
4286
  droppedSpans: 0,
3417
4287
  droppedSpansByReason: {
3418
4288
  queue_full: 0,
3419
4289
  transport_refused: 0,
3420
- shutdown_residue: 0
4290
+ shutdown_residue: 0,
4291
+ unacknowledged: 0
3421
4292
  },
3422
4293
  failedExports: 0,
3423
4294
  queueSize: 0,
@@ -3462,8 +4333,8 @@ function reportError(error, options) {
3462
4333
  span.setStatus("error" /* ERROR */, err.message);
3463
4334
  span.setAttribute("error", true);
3464
4335
  span.setAttribute("error.type", err.constructor.name);
3465
- span.setAttribute("error.message", err.message.slice(0, 2e3));
3466
- if (err.stack) span.setAttribute("error.stack", err.stack.slice(0, 4e3));
4336
+ span.setAttribute("error.message", cutCodePoints(err.message, 2e3));
4337
+ if (err.stack) span.setAttribute("error.stack", cutCodePoints(err.stack, 4e3));
3467
4338
  span.setAttribute("risicare.reported_error", true);
3468
4339
  attachErrorCode(span, err);
3469
4340
  if (options?.attributes) {
@@ -3478,12 +4349,22 @@ function reportError(error, options) {
3478
4349
  }
3479
4350
  function score(traceId, name, value, options) {
3480
4351
  try {
3481
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {
3482
- debug(`score: value must be in [0.0, 1.0], got ${value}. Score not sent.`);
4352
+ const raw = value;
4353
+ if (typeof raw === "boolean") value = raw ? 1 : 0;
4354
+ if (typeof value !== "number") {
4355
+ warn(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4356
+ return;
4357
+ }
4358
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
4359
+ warn(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
3483
4360
  return;
3484
4361
  }
3485
- if (!traceId || !name) {
3486
- debug("score: traceId and name are required");
4362
+ if (typeof traceId !== "string" || given(traceId) === void 0) {
4363
+ warn("score: traceId must be a non-empty string. The SDK does not send this score.");
4364
+ return;
4365
+ }
4366
+ if (typeof name !== "string" || given(name) === void 0) {
4367
+ warn("score: name must be a non-empty string. The SDK does not send this score.");
3487
4368
  return;
3488
4369
  }
3489
4370
  const client = getClient();
@@ -3502,21 +4383,71 @@ function score(traceId, name, value, options) {
3502
4383
  ...options?.spanId && { span_id: options.spanId },
3503
4384
  ...comment && { comment }
3504
4385
  });
3505
- fetch(url, {
3506
- method: "POST",
3507
- headers: {
3508
- "Content-Type": "application/json",
3509
- "Authorization": `Bearer ${client.config.apiKey}`,
3510
- // F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI
3511
- // server under /v1/, which `main.py::audit_logging_middleware` audits
3512
- // into `audit_logs.user_agent`; ingest reaches the Rust gateway, which
3513
- // discards it. This is the one client-identity visible with no gateway
3514
- // change.
3515
- "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
3516
- "X-Risicare-SDK-Version": SDK_VERSION
3517
- },
3518
- body
3519
- }).catch((err) => debug(`score: send failed: ${err}`));
4386
+ if (_scoresInFlight >= SCORE_MAX_IN_FLIGHT && _scoreWaiters.length >= SCORE_MAX_WAITING) {
4387
+ _scoreFailed(name, SCORE_CAP_REASON);
4388
+ return;
4389
+ }
4390
+ let settle;
4391
+ const request = new Promise((resolve) => settle = resolve);
4392
+ const send = async () => {
4393
+ const controller = new AbortController();
4394
+ const timer = setTimeout(() => controller.abort(), SCORE_TIMEOUT_MS);
4395
+ try {
4396
+ const response = await fetch(url, {
4397
+ method: "POST",
4398
+ headers: {
4399
+ "Content-Type": "application/json",
4400
+ "Authorization": `Bearer ${client.config.apiKey}`,
4401
+ // F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI
4402
+ // server under /v1/, which `main.py::audit_logging_middleware` audits
4403
+ // into `audit_logs.user_agent`; ingest reaches the Rust gateway, which
4404
+ // discards it. This is the one client-identity visible with no gateway
4405
+ // change.
4406
+ "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
4407
+ "X-Risicare-SDK-Version": SDK_VERSION
4408
+ },
4409
+ body,
4410
+ // Never follow: a redirect is a misroute, not a route. Through 0.7.1
4411
+ // fetch followed a 307 and re-POSTed the score to the login page.
4412
+ redirect: "manual",
4413
+ signal: controller.signal
4414
+ });
4415
+ if (response.type === "opaqueredirect" || response.status >= 300) {
4416
+ _scoreFailed(name, `HTTP ${response.status || "3xx"}`);
4417
+ }
4418
+ try {
4419
+ await response.body?.cancel();
4420
+ } catch {
4421
+ }
4422
+ } catch (err) {
4423
+ const cause = err instanceof Error ? err.cause : void 0;
4424
+ const code = typeof cause?.code === "string" ? cause.code : void 0;
4425
+ const reason = controller.signal.aborted ? `no answer within ${SCORE_TIMEOUT_MS} ms` : code ?? (err instanceof Error ? err.name : "Error");
4426
+ _scoreFailed(name, reason);
4427
+ } finally {
4428
+ clearTimeout(timer);
4429
+ _scoresInFlight--;
4430
+ settle();
4431
+ _startWaitingScores();
4432
+ }
4433
+ };
4434
+ const start = () => {
4435
+ _scoresInFlight++;
4436
+ void send();
4437
+ };
4438
+ if (_scoresInFlight < SCORE_MAX_IN_FLIGHT) {
4439
+ start();
4440
+ } else {
4441
+ _scoreWaiters.push({
4442
+ start,
4443
+ fail: (reason) => {
4444
+ _scoreFailed(name, reason);
4445
+ settle();
4446
+ }
4447
+ });
4448
+ }
4449
+ _pendingScores.add(request);
4450
+ void request.finally(() => _pendingScores.delete(request));
3520
4451
  } catch {
3521
4452
  debug("score failed");
3522
4453
  }
@@ -3545,9 +4476,9 @@ var LIFECYCLE_STATUS = "risicare.lifecycle.status";
3545
4476
  var STATUS_MESSAGE_MAX = 500;
3546
4477
  function excSummary(error) {
3547
4478
  if (error instanceof Error) {
3548
- return `${error.constructor.name}: ${error.message}`.slice(0, STATUS_MESSAGE_MAX);
4479
+ return cutCodePoints(`${error.constructor.name}: ${error.message}`, STATUS_MESSAGE_MAX);
3549
4480
  }
3550
- return String(error).slice(0, STATUS_MESSAGE_MAX);
4481
+ return cutCodePoints(String(error), STATUS_MESSAGE_MAX);
3551
4482
  }
3552
4483
  function stampEndMarker(span, entity, error) {
3553
4484
  try {
@@ -3634,9 +4565,10 @@ function withSessionEndMarker(body) {
3634
4565
 
3635
4566
  // src/decorators/agent.ts
3636
4567
  function _wrapAgent(options, fn) {
3637
- const spanName = `agent:${options.name ?? "agent"}`;
3638
- const agentId = options.agentId ?? generateAgentId(options.name ?? "agent");
3639
- const boundOptions = { ...options, agentId };
4568
+ const agentName = options.name ?? (fn.name.replace(/^(bound )+/, "") || "agent");
4569
+ const spanName = `agent:${agentName}`;
4570
+ const agentId = options.agentId ?? generateAgentId(agentName);
4571
+ const boundOptions = { ...options, name: agentName, agentId };
3640
4572
  return (...args) => {
3641
4573
  const tracer = getTracer2();
3642
4574
  if (!tracer) {
@@ -3689,6 +4621,10 @@ function withPhase(phase, fn) {
3689
4621
  }
3690
4622
 
3691
4623
  // src/decorators/phase.ts
4624
+ function bareName(phase, fn) {
4625
+ const fnName = typeof fn === "function" ? fn.name.replace(/^(bound )+/, "") : "";
4626
+ return fnName ? `${phase}:${fnName}` : `phase:${phase}`;
4627
+ }
3692
4628
  function phaseWrapper(phase, kind, name, fn) {
3693
4629
  return (...args) => {
3694
4630
  const tracer = getTracer2();
@@ -3704,22 +4640,22 @@ function phaseWrapper(phase, kind, name, fn) {
3704
4640
  };
3705
4641
  }
3706
4642
  function traceThink(fnOrName, maybeFn) {
3707
- const name = typeof fnOrName === "string" ? fnOrName : `phase:think`;
4643
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("think", fnOrName);
3708
4644
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3709
4645
  return phaseWrapper("think" /* THINK */, "think" /* THINK */, name, fn);
3710
4646
  }
3711
4647
  function traceDecide(fnOrName, maybeFn) {
3712
- const name = typeof fnOrName === "string" ? fnOrName : `phase:decide`;
4648
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("decide", fnOrName);
3713
4649
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3714
4650
  return phaseWrapper("decide" /* DECIDE */, "decide" /* DECIDE */, name, fn);
3715
4651
  }
3716
4652
  function traceAct(fnOrName, maybeFn) {
3717
- const name = typeof fnOrName === "string" ? fnOrName : `phase:act`;
4653
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("act", fnOrName);
3718
4654
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3719
4655
  return phaseWrapper("act" /* ACT */, "tool_call" /* TOOL_CALL */, name, fn);
3720
4656
  }
3721
4657
  function traceObserve(fnOrName, maybeFn) {
3722
- const name = typeof fnOrName === "string" ? fnOrName : `phase:observe`;
4658
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("observe", fnOrName);
3723
4659
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3724
4660
  return phaseWrapper("observe" /* OBSERVE */, "observe" /* OBSERVE */, name, fn);
3725
4661
  }
@@ -3808,7 +4744,7 @@ function getTraceContext() {
3808
4744
  traceId = ctx._rootTraceId;
3809
4745
  } else {
3810
4746
  traceId = generateTraceId();
3811
- if (ctx.session || ctx.agent) {
4747
+ if (hasContextScope()) {
3812
4748
  ctx._rootTraceId = traceId;
3813
4749
  }
3814
4750
  }
@@ -3845,7 +4781,8 @@ function extractTraceContext(headers) {
3845
4781
  const result = {};
3846
4782
  const normalizedHeaders = {};
3847
4783
  for (const [key, value] of Object.entries(headers)) {
3848
- normalizedHeaders[key.toLowerCase()] = value;
4784
+ const first = Array.isArray(value) ? value[0] : value;
4785
+ if (typeof first === "string") normalizedHeaders[key.toLowerCase()] = first;
3849
4786
  }
3850
4787
  const traceparent = normalizedHeaders[TRACEPARENT_HEADER] ?? "";
3851
4788
  if (traceparent) {