risicare 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +346 -68
  2. package/dist/frameworks/instructor.cjs +790 -5
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +780 -5
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +790 -5
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.d.cts +3 -2
  9. package/dist/frameworks/langchain.d.ts +3 -2
  10. package/dist/frameworks/langchain.js +780 -5
  11. package/dist/frameworks/langchain.js.map +1 -1
  12. package/dist/frameworks/langgraph.cjs +790 -5
  13. package/dist/frameworks/langgraph.cjs.map +1 -1
  14. package/dist/frameworks/langgraph.js +780 -5
  15. package/dist/frameworks/langgraph.js.map +1 -1
  16. package/dist/frameworks/llamaindex.cjs +801 -5
  17. package/dist/frameworks/llamaindex.cjs.map +1 -1
  18. package/dist/frameworks/llamaindex.d.cts +3 -2
  19. package/dist/frameworks/llamaindex.d.ts +3 -2
  20. package/dist/frameworks/llamaindex.js +791 -5
  21. package/dist/frameworks/llamaindex.js.map +1 -1
  22. package/dist/index.cjs +1219 -212
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +250 -44
  25. package/dist/index.d.ts +250 -44
  26. package/dist/index.js +1219 -212
  27. package/dist/index.js.map +1 -1
  28. package/dist/providers/anthropic/index.cjs +1601 -36
  29. package/dist/providers/anthropic/index.cjs.map +1 -1
  30. package/dist/providers/anthropic/index.d.cts +3 -1
  31. package/dist/providers/anthropic/index.d.ts +3 -1
  32. package/dist/providers/anthropic/index.js +1591 -36
  33. package/dist/providers/anthropic/index.js.map +1 -1
  34. package/dist/providers/bedrock/index.cjs +850 -32
  35. package/dist/providers/bedrock/index.cjs.map +1 -1
  36. package/dist/providers/bedrock/index.js +840 -32
  37. package/dist/providers/bedrock/index.js.map +1 -1
  38. package/dist/providers/cerebras/index.cjs +1534 -30
  39. package/dist/providers/cerebras/index.cjs.map +1 -1
  40. package/dist/providers/cerebras/index.js +1524 -30
  41. package/dist/providers/cerebras/index.js.map +1 -1
  42. package/dist/providers/cohere/index.cjs +1557 -102
  43. package/dist/providers/cohere/index.cjs.map +1 -1
  44. package/dist/providers/cohere/index.js +1547 -102
  45. package/dist/providers/cohere/index.js.map +1 -1
  46. package/dist/providers/google/index.cjs +1562 -60
  47. package/dist/providers/google/index.cjs.map +1 -1
  48. package/dist/providers/google/index.js +1552 -60
  49. package/dist/providers/google/index.js.map +1 -1
  50. package/dist/providers/groq/index.cjs +1534 -30
  51. package/dist/providers/groq/index.cjs.map +1 -1
  52. package/dist/providers/groq/index.js +1524 -30
  53. package/dist/providers/groq/index.js.map +1 -1
  54. package/dist/providers/huggingface/index.cjs +1622 -25
  55. package/dist/providers/huggingface/index.cjs.map +1 -1
  56. package/dist/providers/huggingface/index.d.cts +0 -9
  57. package/dist/providers/huggingface/index.d.ts +0 -9
  58. package/dist/providers/huggingface/index.js +1612 -25
  59. package/dist/providers/huggingface/index.js.map +1 -1
  60. package/dist/providers/mistral/index.cjs +1535 -54
  61. package/dist/providers/mistral/index.cjs.map +1 -1
  62. package/dist/providers/mistral/index.js +1525 -54
  63. package/dist/providers/mistral/index.js.map +1 -1
  64. package/dist/providers/ollama/index.cjs +1559 -93
  65. package/dist/providers/ollama/index.cjs.map +1 -1
  66. package/dist/providers/ollama/index.js +1549 -93
  67. package/dist/providers/ollama/index.js.map +1 -1
  68. package/dist/providers/openai/index.cjs +1598 -61
  69. package/dist/providers/openai/index.cjs.map +1 -1
  70. package/dist/providers/openai/index.d.cts +6 -1
  71. package/dist/providers/openai/index.d.ts +6 -1
  72. package/dist/providers/openai/index.js +1588 -61
  73. package/dist/providers/openai/index.js.map +1 -1
  74. package/dist/providers/together/index.cjs +1534 -30
  75. package/dist/providers/together/index.cjs.map +1 -1
  76. package/dist/providers/together/index.js +1524 -30
  77. package/dist/providers/together/index.js.map +1 -1
  78. package/dist/providers/vercel-ai/index.cjs +1288 -17
  79. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  80. package/dist/providers/vercel-ai/index.d.cts +0 -6
  81. package/dist/providers/vercel-ai/index.d.ts +0 -6
  82. package/dist/providers/vercel-ai/index.js +1278 -17
  83. package/dist/providers/vercel-ai/index.js.map +1 -1
  84. package/package.json +1 -1
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,30 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
412
540
  _timer = null;
413
541
  _started = false;
414
542
  _flushing = false;
543
+ _inFlight = null;
544
+ /**
545
+ * The `shutdown()` that runs, or ran. A second `shutdown()` returns it, and a
546
+ * `flush()` that comes while it runs waits for it (inside its own deadline).
547
+ */
548
+ _closing = null;
549
+ /**
550
+ * True from the start of the drain of `shutdown()` until its loop ends and the
551
+ * residue is counted (no `await` between those two points). A span that ends
552
+ * in this time joins the drain. After it, the processor can take no span.
553
+ */
554
+ _drainOpen = false;
555
+ _lateSpanWarned = false;
415
556
  _beforeExitHandler = null;
416
557
  // Retry tracking for failed batches (Audit #5)
417
558
  _retryCounts = /* @__PURE__ */ new Map();
418
559
  static MAX_RETRIES = 3;
419
560
  _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
561
+ _lastUnackWarnAt = Number.NEGATIVE_INFINITY;
562
+ /**
563
+ * The loss total (dropped + rejected) that the last finished `flush()` saw.
564
+ * A flush reports a loss that is new since then, one time.
565
+ */
566
+ _lossMark = 0;
420
567
  // ── Masking (see `../masking.ts`) ──────────────────────────────────────────
421
568
  _mask;
422
569
  // ── Content capture gate (see `../masking.ts`) ─────────────────────────────
@@ -438,9 +585,15 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
438
585
  droppedSpansByReason = {
439
586
  queue_full: 0,
440
587
  transport_refused: 0,
441
- shutdown_residue: 0
588
+ shutdown_residue: 0,
589
+ unacknowledged: 0
442
590
  };
443
591
  exportedSpans = 0;
592
+ /**
593
+ * Spans that the backend acknowledged as REJECTED (the ack's `rejected`). They
594
+ * are not stored and are not retried. An exporter without an ack adds nothing.
595
+ */
596
+ rejectedSpans = 0;
444
597
  /** Export ATTEMPTS, not a span count. */
445
598
  failedExports = 0;
446
599
  /**
@@ -525,14 +678,41 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
525
678
  * NO progress and abandons the queue exactly as before — measured at 900 of
526
679
  * 1,000. We await a tick instead, the shape `flush()` already models.
527
680
  *
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).
681
+ * The deadline is a hard wall-clock bound. Each round is raced against the
682
+ * budget that remains. At the deadline, `shutdown()` stops the round in flight
683
+ * through the exporter's optional `abort()`. That stopped round changes no
684
+ * counter, does not move the circuit breaker and re-queues nothing. Through
685
+ * 0.7.1 the deadline was checked only between rounds, so one round against a
686
+ * silent server (3 attempts x 5 s) held a 5,000 ms shutdown for 15 s.
687
+ *
688
+ * Anything still queued when the loop stops, AND a batch whose export was
689
+ * stopped, is COUNTED as `shutdown_residue` and announced with ONE WARNING
690
+ * that gives both numbers. The server may have received the spans of the
691
+ * stopped export. The warning is the primary signal, not the counter: a
692
+ * counter incremented inside `shutdown()` is written to memory about to be
693
+ * freed and has no reader (RULING §2 / §8.2).
694
+ *
695
+ * Each exporter's own `shutdown()` gets the time that is left of the budget.
696
+ * An exporter that does not finish in that time is not awaited.
697
+ *
698
+ * Limit: the abort does not stop a TLS handshake that stalls. Measured, such a
699
+ * handshake kept the process alive about 10 s after `shutdown()` returned.
700
+ *
701
+ * A second call, while the first runs or after it ended, returns the promise
702
+ * of the first one. It does not return before the first drain ends.
703
+ *
704
+ * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
705
+ * the values that are not a finite number.
532
706
  */
533
- async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
534
- if (!this._started) return;
707
+ shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
708
+ if (!this._started) return this._closing ?? Promise.resolve();
709
+ this._closing = this._shutdown(timeoutMs);
710
+ return this._closing;
711
+ }
712
+ async _shutdown(timeoutMs) {
713
+ timeoutMs = normalizeTimeoutMs(timeoutMs);
535
714
  this._started = false;
715
+ this._drainOpen = true;
536
716
  if (this._timer) {
537
717
  clearInterval(this._timer);
538
718
  this._timer = null;
@@ -542,10 +722,13 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
542
722
  this._beforeExitHandler = null;
543
723
  }
544
724
  const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);
545
- const drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);
725
+ const shutdownDeadline = Date.now() + timeoutMs;
726
+ const drainDeadline = shutdownDeadline - reserveMs;
546
727
  while (this._queue.length > 0 || this._flushing) {
547
- if (Date.now() >= drainDeadline) break;
548
- const outcome = await this._exportBatch();
728
+ const remaining = drainDeadline - Date.now();
729
+ if (remaining <= 0) break;
730
+ const outcome = await raceDeadline(this._exportBatch(), remaining);
731
+ if (outcome === DEADLINE) break;
549
732
  if (outcome === 3 /* Busy */) {
550
733
  await new Promise((r) => setTimeout(r, 1));
551
734
  continue;
@@ -554,20 +737,30 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
554
737
  break;
555
738
  }
556
739
  }
557
- const residue = this._queue.length;
740
+ this._drainOpen = false;
741
+ const queued = this._queue.length;
742
+ const flight = this._inFlight;
743
+ const inFlight = flight !== null && !flight.abandoned ? flight.size : 0;
744
+ if (flight !== null && !flight.abandoned) {
745
+ flight.abandoned = true;
746
+ for (const exporter of this._exporters) {
747
+ try {
748
+ exporter.abort?.(flight.spans);
749
+ } catch (e) {
750
+ debug(`Error aborting ${exporter.name}: ${describeThrown(e)}`);
751
+ }
752
+ }
753
+ }
754
+ const residue = queued + inFlight;
558
755
  if (residue > 0) {
559
756
  this._queue.length = 0;
560
757
  this._recordDropped("shutdown_residue", residue);
561
758
  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.`
759
+ `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
760
  );
564
761
  }
565
762
  for (const exporter of this._exporters) {
566
- try {
567
- await exporter.shutdown();
568
- } catch (e) {
569
- debug(`Error shutting down ${exporter.name}: ${e}`);
570
- }
763
+ await shutdownExporter(exporter, Math.max(0, shutdownDeadline - Date.now()));
571
764
  }
572
765
  this._retryCounts.clear();
573
766
  debug(
@@ -575,7 +768,14 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
575
768
  );
576
769
  }
577
770
  onSpanEnd(span) {
578
- if (!this._started) return;
771
+ if (!this._started) {
772
+ if (this._drainOpen) this._enqueue(span, false);
773
+ else if (this._closing !== null) this._lateSpan();
774
+ return;
775
+ }
776
+ this._enqueue(span, true);
777
+ }
778
+ _enqueue(span, exportAtBatchSize) {
579
779
  if (this._queue.length >= this._maxQueueSize) {
580
780
  this._recordDropped("queue_full");
581
781
  if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
@@ -584,14 +784,24 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
584
784
  return;
585
785
  }
586
786
  this._queue.push(span);
587
- if (this._queue.length >= this._batchSize) {
787
+ if (exportAtBatchSize && this._queue.length >= this._batchSize) {
588
788
  void this._exportBatch();
589
789
  }
590
790
  }
791
+ /** A span that ended after the drain ended: counted, with one WARNING for the first. */
792
+ _lateSpan() {
793
+ this._recordDropped("shutdown_residue");
794
+ if (this._lateSpanWarned) return;
795
+ this._lateSpanWarned = true;
796
+ warn(
797
+ "a span ended after shutdown() had stopped taking spans (reason=shutdown_residue). It was not delivered, and it is counted as dropped. Later spans of this kind are counted without a WARNING."
798
+ );
799
+ }
591
800
  /**
592
801
  * Flush pending spans.
593
802
  *
594
- * @returns `true` only if everything queued at entry was DELIVERED.
803
+ * @returns `true` only if everything queued at entry was DELIVERED and no
804
+ * span was lost since the previous flush returned.
595
805
  *
596
806
  * RULING §6. This used to answer a different question — "is the queue
597
807
  * empty?" — and those two diverge in exactly one case: when spans left the
@@ -600,35 +810,91 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
600
810
  * everything right; silence lets them discover the problem, a false
601
811
  * affirmative forecloses it.
602
812
  *
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.
813
+ * A LOSS IS REPORTED BY THE NEXT `flush()`, ONE TIME (design section 0,
814
+ * third revision). Returns `true` only when, at the moment it returns, the
815
+ * queue is empty, no batch is in flight, and no span was discarded or
816
+ * rejected since the previous `flush()` returned (or since start, for the
817
+ * first call). Through 0.7.1 only a loss during the call counted: a script
818
+ * whose spans the batch timer had discarded against a 401 sink got `true`
819
+ * with nothing delivered. A failure that a retry repairs does not make it
820
+ * `false`.
821
+ *
822
+ * Mechanics: the processor keeps a loss mark, the loss total (dropped +
823
+ * rejected) that the last finished flush saw. A flush compares the total
824
+ * with the mark it read at its start, then raises the mark to the total
825
+ * (never lowers it). Two flushes that overlap both answer `false` for one
826
+ * loss. The flush after that answers `true` when nothing new was lost.
827
+ *
828
+ * Returns `false` in these cases:
829
+ * (a) the deadline expires with spans still queued or in flight, or while a
830
+ * `shutdown()` that it waits for still runs;
831
+ * (b) a span was discarded since the previous flush returned: queue full,
832
+ * breaker refusal, retry exhaustion, spans that `shutdown()` left
833
+ * (`shutdown_residue`), or an ack that did not account for it or a span
834
+ * that could not be serialized (`unacknowledged`);
835
+ * (c) the backend rejected a span since the previous flush returned.
836
+ *
837
+ * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at
838
+ * SIGTERM or SIGINT, or a `shutdown()` that nobody awaited) waits for that
839
+ * shutdown, inside its OWN deadline, and then answers from the final tally with
840
+ * the same loss mark. After `shutdown()` it answers from the final tally in the
841
+ * same way. Through 0.8.0 both answered from the empty queue: true in 0 ms,
842
+ * with the batch in flight, and true after a rejection or a `transport_refused`
843
+ * drop. A loss that `shutdown()` counts (also `shutdown_residue`) makes ONE
844
+ * `flush()` false, as every other loss does.
845
+ *
846
+ * The deadline is a hard wall-clock bound on the WAIT. At the deadline
847
+ * `flush()` returns `false`. Through 0.7.1 the deadline was checked only
848
+ * between rounds.
849
+ *
850
+ * ⚠ `flush()` never stops a request that is already sent. The export round in
851
+ * flight continues and ends by its own rules: its request timeout, its
852
+ * retries, the circuit breaker. A short flush budget therefore costs no retry,
853
+ * moves no breaker and sends nothing twice. Its result still counts.
854
+ *
855
+ * Limit: that round can keep the process alive after `flush()` returns
856
+ * `false`, until its own timeouts end. Measured on a silent server: 22 s. To
857
+ * end a process within a bound, call `await shutdown(timeoutMs)`: it stops
858
+ * the round in flight.
607
859
  *
608
860
  * ⚠ (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
861
+ * that arrived during the call also answers `false`. That is the
610
862
  * conservative direction on purpose: a false negative costs a caller one
611
863
  * more flush, a false positive is the defect being fixed.
612
864
  */
613
865
  async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
866
+ timeoutMs = normalizeTimeoutMs(timeoutMs);
867
+ const deadline = Date.now() + timeoutMs;
868
+ const mark = this._lossMark;
869
+ const finish = (settled) => {
870
+ const lost = this.droppedSpans + this.rejectedSpans;
871
+ this._lossMark = Math.max(this._lossMark, lost);
872
+ return settled && lost === mark;
873
+ };
614
874
  if (!this._started) {
615
- return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
875
+ if (this._closing !== null) {
876
+ const closed = await raceDeadline(this._closing.catch(() => void 0), timeoutMs);
877
+ if (closed === DEADLINE) return finish(false);
878
+ }
879
+ const held = this._inFlight !== null && !this._inFlight.abandoned;
880
+ return finish(this._queue.length === 0 && !held);
616
881
  }
617
- const start = Date.now();
618
- const discardedAtEntry = this.droppedSpans;
619
882
  while (this._queue.length > 0 || this._flushing) {
883
+ const remaining = deadline - Date.now();
884
+ if (remaining <= 0) return finish(false);
620
885
  if (!this._flushing && this._queue.length > 0) {
621
- await this._exportBatch();
886
+ const outcome = await raceDeadline(this._exportBatch(), remaining);
887
+ if (outcome === DEADLINE) return finish(false);
622
888
  } else {
623
889
  await new Promise((r) => setTimeout(r, 1));
624
890
  }
625
- if (Date.now() - start > timeoutMs) return false;
626
891
  }
627
- return this.droppedSpans === discardedAtEntry;
892
+ return finish(true);
628
893
  }
629
894
  getMetrics() {
630
895
  return {
631
896
  exportedSpans: this.exportedSpans,
897
+ rejectedSpans: this.rejectedSpans,
632
898
  droppedSpans: this.droppedSpans,
633
899
  droppedSpansByReason: { ...this.droppedSpansByReason },
634
900
  failedExports: this.failedExports,
@@ -638,10 +904,56 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
638
904
  queueUtilization: this._queue.length / this._maxQueueSize
639
905
  };
640
906
  }
907
+ /**
908
+ * Count a delivered batch of `n` spans from the exporter's ack.
909
+ *
910
+ * The ack is not trusted. With r = min(rejected, n), a = min(accepted, n - r)
911
+ * and u = n - a - r: `exportedSpans` rises by a, `rejectedSpans` by r, and the
912
+ * u spans that no ack accounts for are dropped as `unacknowledged`, with one
913
+ * rate-limited WARNING. Without an ack (console, custom exporter), the whole
914
+ * batch counts as exported, as before. Python twin: the same clamp.
915
+ */
916
+ _countDelivered(n, ack) {
917
+ if (ack === null) {
918
+ this.exportedSpans += n;
919
+ return;
920
+ }
921
+ const rejected = Math.min(ack.rejected, n);
922
+ const accepted = Math.min(ack.accepted, n - rejected);
923
+ const unacknowledged = n - accepted - rejected;
924
+ this.exportedSpans += accepted;
925
+ this.rejectedSpans += rejected;
926
+ if (unacknowledged > 0) {
927
+ this._recordDropped("unacknowledged", unacknowledged);
928
+ const now = Date.now();
929
+ if (now - this._lastUnackWarnAt > REFUSAL_WARN_WINDOW_MS) {
930
+ this._lastUnackWarnAt = now;
931
+ warn(
932
+ `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.`
933
+ );
934
+ }
935
+ }
936
+ }
937
+ /** The requests in one export round, when every exporter that delivers states it. */
938
+ _requestsPerRound() {
939
+ const delivering = this._exporters.filter((e) => e.countsAsDelivery !== false);
940
+ if (delivering.length !== 1) return void 0;
941
+ const n = delivering[0].attemptsPerExport;
942
+ return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : void 0;
943
+ }
944
+ /**
945
+ * One export round.
946
+ *
947
+ * Which results decide delivery: an exporter that only shows spans locally
948
+ * (`countsAsDelivery === false`, the console exporter) decides only when no
949
+ * other kind of exporter is present. Among the exporters that deliver, ANY
950
+ * success counts the batch as delivered, once.
951
+ */
641
952
  async _exportBatch() {
642
953
  if (this._flushing) return 3 /* Busy */;
643
954
  if (this._queue.length === 0) return 0 /* Empty */;
644
955
  this._flushing = true;
956
+ let flight = null;
645
957
  try {
646
958
  let take = 0;
647
959
  let pairs = 0;
@@ -660,6 +972,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
660
972
  }
661
973
  const batch = this._queue.splice(0, take);
662
974
  if (batch.length === 0) return 0 /* Empty */;
975
+ flight = { spans: batch, size: batch.length, abandoned: false };
976
+ this._inFlight = flight;
663
977
  if (!this._traceContent) {
664
978
  const stripped = stripContentBatch(batch);
665
979
  if (stripped > 0) {
@@ -673,12 +987,19 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
673
987
  }
674
988
  debug(`Exporting batch of ${batch.length} spans`);
675
989
  let batchExported = false;
990
+ const anyDelivers = this._exporters.some((e) => e.countsAsDelivery !== false);
991
+ const unserializable = /* @__PURE__ */ new Set();
676
992
  for (const exporter of this._exporters) {
993
+ const decides = !anyDelivers || exporter.countsAsDelivery !== false;
677
994
  try {
678
995
  const result = await exporter.export(batch);
996
+ if (flight.abandoned) return 2 /* Failed */;
997
+ if (!decides) continue;
998
+ for (const span of exporter.takeUnserializable?.(batch) ?? []) unserializable.add(span);
679
999
  if (result === "success" /* SUCCESS */) {
1000
+ const ack = exporter.takeAck?.(batch) ?? null;
680
1001
  if (!batchExported) {
681
- this.exportedSpans += batch.length;
1002
+ this._countDelivered(batch.length - unserializable.size, ack);
682
1003
  batchExported = true;
683
1004
  for (const span of batch) {
684
1005
  this._retryCounts.delete(span.spanId);
@@ -688,13 +1009,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
688
1009
  this.failedExports++;
689
1010
  }
690
1011
  } catch (e) {
1012
+ if (flight.abandoned) return 2 /* Failed */;
1013
+ if (!decides) continue;
691
1014
  this.failedExports++;
692
- debug(`Export to ${exporter.name} failed: ${e}`);
1015
+ debug(`Export to ${exporter.name} failed: ${describeThrown(e)}`);
693
1016
  }
694
1017
  }
1018
+ if (unserializable.size > 0) this._recordDropped("unacknowledged", unserializable.size);
695
1019
  if (!batchExported) {
696
1020
  let dropped = 0;
697
1021
  const retryable = batch.filter((span) => {
1022
+ if (unserializable.has(span)) return false;
698
1023
  const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
699
1024
  if (count > _BatchSpanProcessor.MAX_RETRIES) {
700
1025
  this._retryCounts.delete(span.spanId);
@@ -713,14 +1038,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
713
1038
  const now = Date.now();
714
1039
  if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {
715
1040
  this._lastRefusalWarnAt = now;
1041
+ const rounds = _BatchSpanProcessor.MAX_RETRIES + 1;
1042
+ const perRound = this._requestsPerRound();
716
1043
  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.`
1044
+ `${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
1045
  );
719
1046
  }
720
1047
  }
721
1048
  }
722
1049
  return batchExported ? 1 /* Delivered */ : 2 /* Failed */;
723
1050
  } finally {
1051
+ if (this._inFlight === flight) this._inFlight = null;
724
1052
  this._flushing = false;
725
1053
  }
726
1054
  }
@@ -729,18 +1057,46 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
729
1057
  // src/config.ts
730
1058
  var DEFAULT_ENDPOINT = "https://ingest.risicare.ai";
731
1059
  var DEFAULT_API_ENDPOINT = "https://api.risicare.ai";
1060
+ var ASCII_WS_EDGES = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
1061
+ function given(value) {
1062
+ if (typeof value !== "string") return void 0;
1063
+ const trimmed = value.replace(ASCII_WS_EDGES, "");
1064
+ return trimmed === "" ? void 0 : trimmed;
1065
+ }
1066
+ var DEFAULT_INGEST_PATTERN = /^https:\/\/ingest\.risicare\.ai(?::443)?\/*$/i;
1067
+ function isDefaultIngest(value) {
1068
+ return DEFAULT_INGEST_PATTERN.test(value);
1069
+ }
1070
+ function resolveEndpoints(endpointOption, apiEndpointOption, envEndpoint, envApiEndpoint) {
1071
+ const e = given(endpointOption);
1072
+ const a = given(apiEndpointOption);
1073
+ const ee = given(envEndpoint);
1074
+ const ea = given(envApiEndpoint);
1075
+ const endpoint = e ?? ee ?? DEFAULT_ENDPOINT;
1076
+ let apiEndpoint;
1077
+ if (a !== void 0) apiEndpoint = a;
1078
+ else if (e !== void 0 && !isDefaultIngest(e)) apiEndpoint = e;
1079
+ else if (ea !== void 0) apiEndpoint = ea;
1080
+ else if (e === void 0 && ee !== void 0 && !isDefaultIngest(ee)) apiEndpoint = ee;
1081
+ else apiEndpoint = DEFAULT_API_ENDPOINT;
1082
+ return { endpoint, apiEndpoint };
1083
+ }
732
1084
  function resolveConfig(config) {
733
1085
  const env = process.env;
734
- 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;
1086
+ const apiKey = keyText(config?.apiKey) || keyText(env.RISICARE_API_KEY) || void 0;
1087
+ const { endpoint, apiEndpoint } = resolveEndpoints(
1088
+ config?.endpoint,
1089
+ config?.apiEndpoint,
1090
+ env.RISICARE_ENDPOINT,
1091
+ env.RISICARE_API_ENDPOINT
1092
+ );
737
1093
  const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;
738
1094
  if (config?.projectId || env.RISICARE_PROJECT_ID) {
739
1095
  console.warn(
740
1096
  "[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
1097
  );
742
1098
  }
743
- const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
1099
+ const environment = config?.environment || env.RISICARE_ENVIRONMENT || "development";
744
1100
  const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
745
1101
  const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
746
1102
  const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
@@ -761,14 +1117,16 @@ function resolveConfig(config) {
761
1117
  const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
762
1118
  const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
763
1119
  let enabled;
1120
+ const tracingEnv = config?.enabled === void 0 ? tracingFromEnv(env.RISICARE_TRACING) : void 0;
764
1121
  if (config?.enabled !== void 0) {
765
1122
  enabled = config.enabled;
766
- } else if (env.RISICARE_TRACING !== void 0) {
767
- enabled = parseBool(env.RISICARE_TRACING, false);
1123
+ } else if (tracingEnv !== void 0) {
1124
+ enabled = tracingEnv;
768
1125
  } else {
769
1126
  enabled = !!apiKey;
770
1127
  }
771
- return {
1128
+ if (!apiKey) enabled = false;
1129
+ return hideKeyFromInspect({
772
1130
  apiKey: apiKey ?? "",
773
1131
  endpoint,
774
1132
  apiEndpoint,
@@ -788,13 +1146,44 @@ function resolveConfig(config) {
788
1146
  metadata: config?.metadata ?? {},
789
1147
  // No env fallback — see the field's note on RisicareConfig.
790
1148
  mask: config?.mask
791
- };
1149
+ });
1150
+ }
1151
+ function hideKeyFromInspect(config) {
1152
+ Object.defineProperty(config, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
1153
+ enumerable: false,
1154
+ value(_depth, options, inspect) {
1155
+ const { apiKey, ...rest } = this;
1156
+ return `RisicareConfig ${inspect({ ...rest, apiKey: apiKey ? "<redacted>" : "" }, options)}`;
1157
+ }
1158
+ });
1159
+ return config;
792
1160
  }
793
1161
  function parseBool(value, defaultValue) {
794
1162
  if (value === void 0) return defaultValue;
795
1163
  const lower = value.toLowerCase();
796
1164
  return lower === "true" || lower === "1" || lower === "yes";
797
1165
  }
1166
+ var TRACING_ON = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
1167
+ var TRACING_OFF = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
1168
+ function tracingFromEnv(value) {
1169
+ if (value === void 0) return void 0;
1170
+ const v = value.trim().toLowerCase();
1171
+ if (v === "") return void 0;
1172
+ if (TRACING_ON.has(v)) return true;
1173
+ if (TRACING_OFF.has(v)) return false;
1174
+ warn(
1175
+ `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.`
1176
+ );
1177
+ return false;
1178
+ }
1179
+ function keyText(value) {
1180
+ return typeof value === "string" ? value.trim() : "";
1181
+ }
1182
+ function tracingTurnedOff(config) {
1183
+ if (config?.enabled !== void 0) return config.enabled === false;
1184
+ const v = (process.env.RISICARE_TRACING ?? "").trim().toLowerCase();
1185
+ return v !== "" && !TRACING_ON.has(v);
1186
+ }
798
1187
  function parseNumericEnv(value, defaultValue) {
799
1188
  if (value === void 0) return defaultValue;
800
1189
  const n = Number(value);
@@ -1400,12 +1789,31 @@ var CANONICAL_ERROR_CODES = /* @__PURE__ */ new Set([
1400
1789
  "TOOL.RESULT.UNEXPECTED_FORMAT",
1401
1790
  "TOOL.RESULT.UNPARSEABLE"
1402
1791
  ]);
1792
+ var CORE_RULES = [
1793
+ { re: new RegExp("json", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" },
1794
+ { re: new RegExp("encoding", "u"), code: "PERCEPTION.INPUT.ENCODING" },
1795
+ { re: new RegExp("injection", "u"), code: "PERCEPTION.INPUT.INJECTION" },
1796
+ { re: new RegExp("malformed", "u"), code: "PERCEPTION.INPUT.MALFORMED" },
1797
+ { re: new RegExp("hallucin", "u"), code: "REASONING.HALLUCINATION.FACTUAL" },
1798
+ { re: new RegExp("contradict", "u"), code: "REASONING.LOGIC.CONTRADICTION" },
1799
+ { re: new RegExp("timeout", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
1800
+ { re: new RegExp("rate[^\\n]?limit", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1801
+ { re: new RegExp("permission", "u"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
1802
+ { re: new RegExp("context[^\\n]+overflow", "u"), code: "MEMORY.CONTEXT_WINDOW.EXCEEDED" },
1803
+ { re: new RegExp("state[^\\n]+corrupt", "u"), code: "MEMORY.STATE.CORRUPTED" },
1804
+ { re: new RegExp("pii", "u"), code: "OUTPUT.SAFETY.PII_LEAK" },
1805
+ { re: new RegExp("deadlock", "u"), code: "COORDINATION.WORKFLOW.DEADLOCK" },
1806
+ { re: new RegExp("undeliverable", "u"), code: "COMMUNICATION.DELIVERY.UNDELIVERABLE" },
1807
+ { re: new RegExp("crash", "u"), code: "ORCHESTRATION.LIFECYCLE.CRASHED" },
1808
+ { re: new RegExp("quorum", "u"), code: "CONSENSUS.AGREEMENT.QUORUM_FAILED" },
1809
+ { re: new RegExp("quota[^\\n]+exceed", "u"), code: "RESOURCES.QUOTA.EXCEEDED" }
1810
+ ];
1403
1811
  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" }
1812
+ { re: new RegExp("timeout|timedout|aborted", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
1813
+ { re: new RegExp("rate[^\\n]?limit|(?<![\\p{L}\\p{N}_])429(?![\\p{L}\\p{N}_])|too many requests", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1814
+ { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "u"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
1815
+ { 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" },
1816
+ { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" }
1409
1817
  ];
1410
1818
  var GENERIC_FALLBACK = "TOOL.EXECUTION.CRASHED";
1411
1819
 
@@ -1422,6 +1830,16 @@ var GuardRejectedError = class extends Error {
1422
1830
  this.phase = phase;
1423
1831
  }
1424
1832
  };
1833
+ function guardText(message) {
1834
+ if (!message || typeof message !== "object") return null;
1835
+ const content = message.content;
1836
+ if (typeof content === "string") return content === "" ? null : content;
1837
+ if (Array.isArray(content)) {
1838
+ const texts = content.filter((p) => !!p && typeof p === "object" && p.type === "text" && typeof p.text === "string").map((p) => p.text);
1839
+ if (texts.length > 0) return texts.join("\n");
1840
+ }
1841
+ return null;
1842
+ }
1425
1843
  function createInterceptContext(operationType, operationName, options) {
1426
1844
  return {
1427
1845
  operationType,
@@ -1481,8 +1899,8 @@ var DefaultFixInterceptor = class {
1481
1899
  }
1482
1900
  if (modifiedMessages && this._config.enabled) {
1483
1901
  for (const msg of modifiedMessages) {
1484
- const content = msg.content;
1485
- if (typeof content === "string") {
1902
+ const content = guardText(msg);
1903
+ if (content !== null) {
1486
1904
  for (const fix of this._cache.getAll()) {
1487
1905
  if (fix.fixType === "guard") {
1488
1906
  const { passed, result } = this._applier.applyGuardFix(
@@ -1627,7 +2045,13 @@ var DefaultFixInterceptor = class {
1627
2045
  }
1628
2046
  };
1629
2047
  function classifyError(error) {
1630
- const haystack = `${error?.constructor?.name ?? "Error"} ${error?.message ?? ""}`;
2048
+ const message = String(error?.message ?? "").toLowerCase();
2049
+ for (const rule of CORE_RULES) {
2050
+ if (rule.re.test(message)) {
2051
+ return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
2052
+ }
2053
+ }
2054
+ const haystack = `${error?.constructor?.name ?? "Error"} ${String(error?.message ?? "")}`.toLowerCase();
1631
2055
  for (const rule of SUPPLEMENTAL_RULES) {
1632
2056
  if (rule.re.test(haystack)) {
1633
2057
  return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
@@ -1643,6 +2067,9 @@ function storage() {
1643
2067
  function getContext() {
1644
2068
  return storage().getStore() ?? {};
1645
2069
  }
2070
+ function hasContextScope() {
2071
+ return storage().getStore() !== void 0;
2072
+ }
1646
2073
  function runWithContext(overrides, fn) {
1647
2074
  const parent = getContext();
1648
2075
  const merged = { ...parent, ...overrides };
@@ -1699,7 +2126,8 @@ function getCurrentContext() {
1699
2126
  // src/tracer.ts
1700
2127
  function attachErrorCode(span, error) {
1701
2128
  try {
1702
- const err = error instanceof Error ? error : new Error(String(error));
2129
+ const ownMessage = error !== null && typeof error === "object" ? error.message : void 0;
2130
+ const err = error instanceof Error ? error : new Error(typeof ownMessage === "string" ? ownMessage : String(error));
1703
2131
  const code = classifyError(err);
1704
2132
  if (code) {
1705
2133
  span.setAttribute("error.code", code);
@@ -1801,6 +2229,7 @@ var Tracer = class {
1801
2229
  (error) => {
1802
2230
  span.recordException(error instanceof Error ? error : String(error));
1803
2231
  attachErrorCode(span, error);
2232
+ markCancel(span, error);
1804
2233
  span.end();
1805
2234
  throw error;
1806
2235
  }
@@ -1811,6 +2240,7 @@ var Tracer = class {
1811
2240
  } catch (error) {
1812
2241
  span.recordException(error instanceof Error ? error : String(error));
1813
2242
  attachErrorCode(span, error);
2243
+ markCancel(span, error);
1814
2244
  span.end();
1815
2245
  throw error;
1816
2246
  }
@@ -1830,7 +2260,7 @@ var Tracer = class {
1830
2260
  const session2 = getCurrentSession();
1831
2261
  const agent2 = getCurrentAgent();
1832
2262
  const phase = getCurrentPhase();
1833
- const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();
2263
+ const traceId = opts.traceId ?? parentSpan?.traceId ?? getContext()._rootTraceId ?? generateTraceId();
1834
2264
  if (!parentSpan) {
1835
2265
  if (getContext()._traceSampled === false) {
1836
2266
  return NOOP_SPAN;
@@ -1866,9 +2296,15 @@ var Tracer = class {
1866
2296
  );
1867
2297
  }
1868
2298
  };
2299
+ function markCancel(span, error) {
2300
+ if (error instanceof Error && error.name === "AbortError") {
2301
+ span.setAttribute("risicare.cancelled", true);
2302
+ span.setAttribute("risicare.cancel_type", "AbortError");
2303
+ }
2304
+ }
1869
2305
 
1870
2306
  // src/version.ts
1871
- var SDK_VERSION = "0.7.0";
2307
+ var SDK_VERSION = "0.9.0";
1872
2308
 
1873
2309
  // src/exporters/http.ts
1874
2310
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
@@ -1876,6 +2312,8 @@ var RETRY_AFTER_CEILING_MS = 1e4;
1876
2312
  var REFUSAL_BACKOFF_BASE_MS = 1e3;
1877
2313
  var REFUSAL_NO_HINT = -1;
1878
2314
  var MISROUTE_WARN_WINDOW_MS = 3e5;
2315
+ var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
2316
+ var FAILURE_WARN_WINDOW_MS = 3e5;
1879
2317
  var HttpExporter = class {
1880
2318
  name = "http";
1881
2319
  _endpoint;
@@ -1891,21 +2329,24 @@ var HttpExporter = class {
1891
2329
  // cooldown gives the gateway time to come back before the half-open
1892
2330
  // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
1893
2331
  _consecutiveFailures = 0;
2332
+ _lastMisrouteWarnAt = -Infinity;
2333
+ _lastFailureWarnAt = -Infinity;
1894
2334
  /**
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).
2335
+ * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
2336
+ * 'unknown'). `null` after a success. A new kind in the same outage writes one more
2337
+ * WARNING, also inside the window.
1904
2338
  */
1905
- _lastRefusalAfterMs = null;
1906
- /** Set by `_sendRequest` on a MISROUTE: a short description of the answer. `null` = none. */
1907
- _lastMisroute = null;
1908
- _lastMisrouteWarnAt = -Infinity;
2339
+ _failureKind = null;
2340
+ /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
2341
+ _safeEndpoint;
2342
+ /** The endpoint holds userinfo. `fetch` refuses such a URL. */
2343
+ _endpointHasCredentials;
2344
+ /** The calls in progress, by their batch, so that `abort(spans)` stops the right one. */
2345
+ _calls = /* @__PURE__ */ new Map();
2346
+ /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */
2347
+ _acks = /* @__PURE__ */ new WeakMap();
2348
+ /** The spans of each finished call that could not be serialized, by its batch. */
2349
+ _unserializable = /* @__PURE__ */ new WeakMap();
1909
2350
  _circuitOpenUntil = 0;
1910
2351
  _circuitBreakerThreshold = 5;
1911
2352
  _circuitBreakerCooldownMs = 6e4;
@@ -1917,9 +2358,105 @@ var HttpExporter = class {
1917
2358
  this._timeoutMs = options.timeoutMs ?? 5e3;
1918
2359
  this._maxRetries = options.maxRetries ?? 3;
1919
2360
  this._compress = options.compress ?? false;
2361
+ this._safeEndpoint = safeUrl(this._endpoint);
2362
+ this._endpointHasCredentials = hasCredentials(this._endpoint);
2363
+ }
2364
+ /**
2365
+ * Network or error text for a log line: the endpoint as `safeUrl` gives it, and no
2366
+ * form of the API key (`utils/scrub.ts`).
2367
+ */
2368
+ _scrub(text, limit = 200) {
2369
+ let out;
2370
+ try {
2371
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
2372
+ } catch {
2373
+ out = typeof text;
2374
+ }
2375
+ if (this._safeEndpoint !== this._endpoint) out = out.split(this._endpoint).join(this._safeEndpoint);
2376
+ return scrubText(out, [this._apiKey], limit);
2377
+ }
2378
+ /** Hide the key from `util.inspect` and `console.log` of the exporter. */
2379
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
2380
+ return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
2381
+ }
2382
+ /** The most requests that one `export()` call sends (`maxRetries`). */
2383
+ get attemptsPerExport() {
2384
+ return this._maxRetries;
2385
+ }
2386
+ /**
2387
+ * Returns the counts of the ack that the `export()` call for `spans` received, and clears
2388
+ * them. The answer is kept per batch, not on the instance: two processors that share this
2389
+ * exporter cannot read each other's ack across an `await`.
2390
+ */
2391
+ takeAck(spans) {
2392
+ const ack = this._acks.get(spans) ?? null;
2393
+ this._acks.delete(spans);
2394
+ return ack;
2395
+ }
2396
+ /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
2397
+ takeUnserializable(spans) {
2398
+ const bad = this._unserializable.get(spans) ?? [];
2399
+ this._unserializable.delete(spans);
2400
+ return bad;
1920
2401
  }
2402
+ /**
2403
+ * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
2404
+ * request, its retries and its backoff sleep. The batch processor calls it when
2405
+ * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
2406
+ * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
2407
+ * logs no WARNING.
2408
+ */
2409
+ abort(spans) {
2410
+ if (spans !== void 0) this._calls.get(spans)?.cancel.abort();
2411
+ else for (const call of this._calls.values()) call.cancel.abort();
2412
+ }
2413
+ /**
2414
+ * Send one batch. The limits are the request timeout and `maxRetries`.
2415
+ *
2416
+ * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
2417
+ * cuts a request that is already sent. A short flush budget that cut the request made a
2418
+ * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
2419
+ * the server stored the same spans again. Only `abort()` stops the call, and only
2420
+ * `shutdown()` calls it.
2421
+ */
1921
2422
  async export(spans) {
1922
2423
  if (spans.length === 0) return "success" /* SUCCESS */;
2424
+ const call = {
2425
+ cancel: new AbortController(),
2426
+ refusalAfterMs: null,
2427
+ misroute: null,
2428
+ noRetry: false,
2429
+ status: null,
2430
+ error: null
2431
+ };
2432
+ this._calls.set(spans, call);
2433
+ try {
2434
+ return await this._export(spans, call);
2435
+ } finally {
2436
+ this._calls.delete(spans);
2437
+ }
2438
+ }
2439
+ async _export(spans, call) {
2440
+ const cancelled = call.cancel.signal;
2441
+ const parts = [];
2442
+ const bad = [];
2443
+ let errorClass = "";
2444
+ for (const span of spans) {
2445
+ try {
2446
+ parts.push(JSON.stringify(span.toPayload()));
2447
+ } catch (e) {
2448
+ bad.push(span);
2449
+ errorClass ||= e instanceof Error ? e.name : typeof e;
2450
+ }
2451
+ }
2452
+ if (bad.length > 0) {
2453
+ this._unserializable.set(spans, bad);
2454
+ warn(
2455
+ `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).`
2456
+ );
2457
+ }
2458
+ if (parts.length === 0) return "success" /* SUCCESS */;
2459
+ const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
1923
2460
  const now = Date.now();
1924
2461
  let isHalfOpen = false;
1925
2462
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
@@ -1928,44 +2465,64 @@ var HttpExporter = class {
1928
2465
  }
1929
2466
  isHalfOpen = true;
1930
2467
  }
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
2468
  const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
2469
+ let attempts = 0;
1937
2470
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1938
- this._lastRefusalAfterMs = null;
1939
- this._lastMisroute = null;
1940
- const result = await this._sendRequest(body);
2471
+ call.refusalAfterMs = null;
2472
+ call.misroute = null;
2473
+ call.noRetry = false;
2474
+ call.status = null;
2475
+ call.error = null;
2476
+ attempts++;
2477
+ const result = await this._sendRequest(payload, parts.length, call, spans);
2478
+ if (cancelled.aborted) {
2479
+ this._acks.delete(spans);
2480
+ return "failure" /* FAILURE */;
2481
+ }
1941
2482
  if (result === "success" /* SUCCESS */) {
1942
2483
  this._consecutiveFailures = 0;
2484
+ this._failureKind = null;
1943
2485
  return result;
1944
2486
  }
1945
- if (this._lastMisroute !== null) break;
2487
+ if (call.misroute !== null || call.noRetry) break;
2488
+ if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
1946
2489
  if (attempt < maxAttempts - 1) {
1947
- const refusal = this._lastRefusalAfterMs;
2490
+ const refusal = call.refusalAfterMs;
1948
2491
  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);
2492
+ await sleep(delay, cancelled);
2493
+ if (cancelled.aborted) return "failure" /* FAILURE */;
1950
2494
  }
1951
2495
  }
1952
- const refusedForCapacity = this._lastRefusalAfterMs !== null;
1953
- this._lastRefusalAfterMs = null;
1954
- if (refusedForCapacity) {
2496
+ if (call.refusalAfterMs !== null) {
1955
2497
  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.`
2498
+ `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
2499
  );
1958
2500
  return "failure" /* FAILURE */;
1959
2501
  }
1960
- const misroute = this._lastMisroute;
1961
- this._lastMisroute = null;
2502
+ const misroute = call.misroute;
1962
2503
  if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
1963
2504
  this._lastMisrouteWarnAt = Date.now();
1964
2505
  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.`
2506
+ `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
2507
  );
1967
2508
  }
1968
2509
  this._consecutiveFailures++;
2510
+ if (misroute === null && !call.noRetry) {
2511
+ const status = call.status;
2512
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
2513
+ let write = false;
2514
+ if (this._consecutiveFailures === 1 || this._failureKind === null) {
2515
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
2516
+ this._lastFailureWarnAt = Date.now();
2517
+ write = true;
2518
+ }
2519
+ this._failureKind = kind;
2520
+ } else if (kind !== this._failureKind) {
2521
+ this._failureKind = kind;
2522
+ write = true;
2523
+ }
2524
+ if (write) this._warnOutage(kind, status, call.error);
2525
+ }
1969
2526
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
1970
2527
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
1971
2528
  warn(
@@ -1974,10 +2531,36 @@ var HttpExporter = class {
1974
2531
  }
1975
2532
  return "failure" /* FAILURE */;
1976
2533
  }
2534
+ /** The outage WARNING for one kind of failure. */
2535
+ _warnOutage(kind, status, error) {
2536
+ const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
2537
+ const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
2538
+ if (kind === "auth") {
2539
+ warn(
2540
+ `${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}`
2541
+ );
2542
+ } else if (kind === "http") {
2543
+ warn(
2544
+ `${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.`
2545
+ );
2546
+ } else if (kind === "none" && this._endpointHasCredentials) {
2547
+ warn(
2548
+ `${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}`
2549
+ );
2550
+ } else if (kind === "none") {
2551
+ warn(
2552
+ `${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.`
2553
+ );
2554
+ } else {
2555
+ warn(
2556
+ `${where}: the export failed. Common causes: an invalid apiKey or an unreachable endpoint. ${tail} Set debug: true to see each attempt.`
2557
+ );
2558
+ }
2559
+ }
1977
2560
  /** 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}`);
2561
+ _noteMisroute(call, answer) {
2562
+ call.misroute = this._scrub(answer, 300);
2563
+ debug(`Ingest misroute: ${call.misroute}`);
1981
2564
  return "failure" /* FAILURE */;
1982
2565
  }
1983
2566
  /**
@@ -1987,7 +2570,7 @@ var HttpExporter = class {
1987
2570
  * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
1988
2571
  * parse.
1989
2572
  */
1990
- _noteRefusal(status, retryAfterRaw) {
2573
+ _noteRefusal(call, status, retryAfterRaw) {
1991
2574
  if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
1992
2575
  let delay = REFUSAL_NO_HINT;
1993
2576
  if (retryAfterRaw) {
@@ -1996,11 +2579,13 @@ var HttpExporter = class {
1996
2579
  delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
1997
2580
  }
1998
2581
  }
1999
- this._lastRefusalAfterMs = delay;
2000
- debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);
2582
+ call.refusalAfterMs = delay;
2583
+ debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
2001
2584
  return true;
2002
2585
  }
2003
- async _sendRequest(body) {
2586
+ async _sendRequest(body, spansSent, call, spans) {
2587
+ const cancelled = call.cancel.signal;
2588
+ const timeoutMs = this._timeoutMs;
2004
2589
  const url = `${this._endpoint}/v1/spans`;
2005
2590
  const headers = {
2006
2591
  "Content-Type": "application/json",
@@ -2015,19 +2600,22 @@ var HttpExporter = class {
2015
2600
  if (this._apiKey) {
2016
2601
  headers["Authorization"] = `Bearer ${this._apiKey}`;
2017
2602
  }
2018
- let payload = JSON.stringify(body);
2603
+ let payload = body;
2019
2604
  if (this._compress && payload.length > 1024) {
2020
2605
  try {
2021
2606
  const { gzipSync } = await import("zlib");
2022
2607
  payload = gzipSync(Buffer.from(payload));
2023
2608
  headers["Content-Encoding"] = "gzip";
2024
2609
  } catch (e) {
2025
- debug(`Gzip compression failed, sending uncompressed: ${e}`);
2610
+ debug(`Gzip compression failed, sending uncompressed: ${this._scrub(e)}`);
2026
2611
  }
2027
2612
  }
2613
+ const controller = new AbortController();
2614
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
2615
+ const onCancel = () => controller.abort();
2616
+ cancelled.addEventListener("abort", onCancel, { once: true });
2617
+ if (cancelled.aborted) controller.abort();
2028
2618
  try {
2029
- const controller = new AbortController();
2030
- const timeoutId = setTimeout(() => controller.abort(), this._timeoutMs);
2031
2619
  const response = await fetch(url, {
2032
2620
  method: "POST",
2033
2621
  headers,
@@ -2037,40 +2625,89 @@ var HttpExporter = class {
2037
2625
  // the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.
2038
2626
  redirect: "manual"
2039
2627
  });
2040
- clearTimeout(timeoutId);
2628
+ call.status = response.status;
2041
2629
  const redirected = response.type === "opaqueredirect";
2042
2630
  if (redirected || response.status >= 300 && response.status < 400) {
2043
2631
  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}`);
2632
+ const target = location ? this._scrub(location, 1e3) : "no Location header";
2633
+ return this._noteMisroute(call, `HTTP ${response.status || "3xx"}, a redirect to ${target}`);
2046
2634
  }
2047
2635
  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;
2636
+ const ack = await checkAck(response, spansSent, (t) => this._scrub(t, 1e3));
2637
+ if (ack === null) {
2638
+ if (controller.signal.aborted) {
2639
+ call.status = null;
2640
+ call.error = `timeout after ${timeoutMs} ms`;
2641
+ debug(`HTTP export timeout: the ack body did not arrive within ${timeoutMs} ms`);
2642
+ return "timeout" /* TIMEOUT */;
2643
+ }
2644
+ return this._noteMisroute(
2645
+ call,
2646
+ `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
2647
+ );
2648
+ }
2649
+ if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
2650
+ if (ack.final) call.noRetry = true;
2651
+ return ack.result;
2052
2652
  } else if (response.status === 408 || response.status === 504) {
2053
2653
  debug(`HTTP export timeout: ${response.status}`);
2054
2654
  return "timeout" /* TIMEOUT */;
2055
2655
  }
2056
- this._noteRefusal(response.status, response.headers.get("Retry-After"));
2656
+ this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
2057
2657
  debug(`HTTP export failed: ${response.status}`);
2058
2658
  return "failure" /* FAILURE */;
2059
2659
  } catch (e) {
2060
- debug(`HTTP export error: ${e}`);
2660
+ const cause = e instanceof Error ? e.cause : void 0;
2661
+ call.error = controller.signal.aborted ? `timeout after ${timeoutMs} ms` : typeof cause?.code === "string" ? cause.code : e instanceof Error ? e.name : "Error";
2662
+ debug(`HTTP export error: ${this._scrub(e)}`);
2061
2663
  return "failure" /* FAILURE */;
2664
+ } finally {
2665
+ clearTimeout(timeoutId);
2666
+ cancelled.removeEventListener("abort", onCancel);
2062
2667
  }
2063
2668
  }
2064
2669
  shutdown() {
2065
2670
  }
2066
2671
  };
2067
- function sleep(ms) {
2068
- return new Promise((resolve) => setTimeout(resolve, ms));
2672
+ function sleep(ms, signal) {
2673
+ return new Promise((resolve) => {
2674
+ if (signal?.aborted) return resolve();
2675
+ const done = () => {
2676
+ clearTimeout(timer);
2677
+ signal?.removeEventListener("abort", done);
2678
+ resolve();
2679
+ };
2680
+ const timer = setTimeout(done, ms);
2681
+ signal?.addEventListener("abort", done, { once: true });
2682
+ });
2069
2683
  }
2070
2684
  function asCount(v) {
2071
2685
  return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
2072
2686
  }
2073
- async function checkAck(response) {
2687
+ var MAX_ACK_REASONS = 3;
2688
+ var MAX_ACK_REASON_CHARS = 200;
2689
+ function oneLine(text) {
2690
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ");
2691
+ }
2692
+ function ackReasons(body) {
2693
+ const reasons = [];
2694
+ const errors = body.errors;
2695
+ if (Array.isArray(errors)) {
2696
+ for (const entry of errors) {
2697
+ const text = entry?.error;
2698
+ if (typeof text !== "string" || text.length === 0) continue;
2699
+ const cut = oneLine(text).slice(0, MAX_ACK_REASON_CHARS);
2700
+ if (!reasons.includes(cut)) reasons.push(cut);
2701
+ if (reasons.length === MAX_ACK_REASONS) break;
2702
+ }
2703
+ }
2704
+ if (reasons.length === 0) {
2705
+ const message = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || "";
2706
+ if (message) reasons.push(oneLine(message).slice(0, MAX_ACK_REASON_CHARS));
2707
+ }
2708
+ return reasons.length === 0 ? "No reason was returned." : `Reasons: ${reasons.join("; ")}`;
2709
+ }
2710
+ async function checkAck(response, spansSent, scrub) {
2074
2711
  let payload;
2075
2712
  try {
2076
2713
  payload = await response.json();
@@ -2084,37 +2721,37 @@ async function checkAck(response) {
2084
2721
  const accepted = asCount(body.accepted);
2085
2722
  const rejected = asCount(body.rejected);
2086
2723
  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.";
2724
+ const counts = { accepted, rejected };
2725
+ if (accepted === 0 && rejected === 0 && spansSent > 0) {
2726
+ warn(
2727
+ `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.`
2728
+ );
2729
+ return { result: "failure" /* FAILURE */, counts, final: true };
2730
+ }
2731
+ if (rejected === 0) return { result: "success" /* SUCCESS */, counts, final: false };
2090
2732
  const total = accepted + rejected;
2091
2733
  if (accepted === 0) {
2092
2734
  warn(
2093
- `Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. ${detail}`
2735
+ `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
2736
  );
2095
- return "failure" /* FAILURE */;
2737
+ return { result: "success" /* SUCCESS */, counts, final: false };
2096
2738
  }
2097
2739
  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}`
2740
+ `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
2741
  );
2100
- return "success" /* SUCCESS */;
2742
+ return { result: "success" /* SUCCESS */, counts, final: false };
2101
2743
  }
2102
2744
 
2103
- // src/exporters/console.ts
2104
- var ConsoleExporter = class {
2105
- name = "console";
2106
- export(spans) {
2107
- for (const span of spans) {
2108
- const payload = span.toPayload();
2109
- const line = JSON.stringify(payload);
2110
- process.stderr.write(`[risicare] ${line}
2111
- `);
2112
- }
2113
- return "success" /* SUCCESS */;
2114
- }
2115
- shutdown() {
2745
+ // src/utils/stream-proxy.ts
2746
+ function endOpenProviderSpans() {
2747
+ let open;
2748
+ try {
2749
+ open = [...getProviderSpanState().open];
2750
+ } catch {
2751
+ return;
2116
2752
  }
2117
- };
2753
+ for (const o of open) o.end("shutdown");
2754
+ }
2118
2755
 
2119
2756
  // src/runtime/cache.ts
2120
2757
  var FixCache = class {
@@ -2291,6 +2928,94 @@ function emptyResult(fix, fixType) {
2291
2928
  modifications: {}
2292
2929
  };
2293
2930
  }
2931
+ var SAME_ESCAPES = "bBdDsSwWfnrtv";
2932
+ var SAME_ESCAPES_IN_CLASS = "bdDsSwWfnrtv";
2933
+ var LEADING_INLINE_FLAGS = /^\(\?([ims]+)\)/;
2934
+ var PY_NAMED_GROUP = /^\(\?P<([A-Za-z_][A-Za-z0-9_]*)>/;
2935
+ var PY_NAMED_BACKREF = /^\(\?P=([A-Za-z_][A-Za-z0-9_]*)\)/;
2936
+ var JS_NAMED_GROUP = /^\(\?<([A-Za-z_][A-Za-z0-9_]*)>/;
2937
+ function translatePythonPattern(pattern) {
2938
+ let flags = "i";
2939
+ let rest = pattern;
2940
+ const m = LEADING_INLINE_FLAGS.exec(rest);
2941
+ if (m) {
2942
+ for (const f of m[1]) if (!flags.includes(f)) flags += f;
2943
+ rest = rest.slice(m[0].length);
2944
+ }
2945
+ const names = /* @__PURE__ */ new Set();
2946
+ const addName = (name) => {
2947
+ if (names.has(name)) throw new Error("a group name occurs two times");
2948
+ names.add(name);
2949
+ };
2950
+ let source = "";
2951
+ let inClass = false;
2952
+ for (let i = 0; i < rest.length; i++) {
2953
+ const c = rest[i];
2954
+ if (c === "\\" && i + 1 < rest.length) {
2955
+ const next = rest[i + 1];
2956
+ if (/[A-Za-z]/.test(next)) {
2957
+ if (!inClass && next === "A") {
2958
+ source += "(?<![\\s\\S])";
2959
+ i++;
2960
+ continue;
2961
+ }
2962
+ if (!inClass && next === "Z") {
2963
+ source += "(?![\\s\\S])";
2964
+ i++;
2965
+ continue;
2966
+ }
2967
+ if (next === "x" || next === "u") {
2968
+ const n = next === "x" ? 2 : 4;
2969
+ const hex = rest.slice(i + 2, i + 2 + n);
2970
+ if (!new RegExp(`^[0-9A-Fa-f]{${n}}$`).test(hex)) throw new Error("short hex escape");
2971
+ source += c + next + hex;
2972
+ i += 1 + n;
2973
+ continue;
2974
+ }
2975
+ if (!(inClass ? SAME_ESCAPES_IN_CLASS : SAME_ESCAPES).includes(next)) {
2976
+ throw new Error("an escape that Python and JavaScript read differently");
2977
+ }
2978
+ }
2979
+ source += c + next;
2980
+ i++;
2981
+ continue;
2982
+ }
2983
+ if (inClass) {
2984
+ if (c === "]") inClass = false;
2985
+ source += c;
2986
+ continue;
2987
+ }
2988
+ if (c === "[") {
2989
+ inClass = true;
2990
+ source += c;
2991
+ continue;
2992
+ }
2993
+ const tail = rest.slice(i);
2994
+ let g;
2995
+ if ((g = PY_NAMED_GROUP.exec(tail)) || (g = JS_NAMED_GROUP.exec(tail))) {
2996
+ addName(g[1]);
2997
+ source += `(?<${g[1]}>`;
2998
+ i += g[0].length - 1;
2999
+ continue;
3000
+ }
3001
+ if (g = PY_NAMED_BACKREF.exec(tail)) {
3002
+ source += `\\k<${g[1]}>`;
3003
+ i += g[0].length - 1;
3004
+ continue;
3005
+ }
3006
+ source += c;
3007
+ }
3008
+ return { source, flags };
3009
+ }
3010
+ var warnedGuardPatterns = /* @__PURE__ */ new Set();
3011
+ function warnUnusablePattern(fixId, index) {
3012
+ const key = `${fixId ?? "unknown"}\0${index}`;
3013
+ if (warnedGuardPatterns.has(key)) return;
3014
+ warnedGuardPatterns.add(key);
3015
+ warn(
3016
+ 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.`
3017
+ );
3018
+ }
2294
3019
  var FixApplier = class {
2295
3020
  _config;
2296
3021
  _cache;
@@ -2548,6 +3273,26 @@ var FixApplier = class {
2548
3273
  * - content_filter: Regex-based blocked patterns
2549
3274
  * - format_check: JSON.parse() validity
2550
3275
  * - input_validation / output_validation: min/max length
3276
+ *
3277
+ * `content_filter` searches the content for each entry of `blocked_patterns`
3278
+ * (case-insensitive, after `translatePythonPattern`). It fails CLOSED: when
3279
+ * `blocked_patterns` is not a list, or an entry is empty, is not a string,
3280
+ * is longer than 500 characters or cannot be used, the guard does not pass.
3281
+ * One WARNING names the fix id and the pattern index, once for each pair in
3282
+ * the process. The reason names the pattern index, never the pattern or the
3283
+ * content.
3284
+ *
3285
+ * Limits:
3286
+ * - The interceptor runs only on the OpenAI chat patch (input guards) and on
3287
+ * `interceptCall` / `interceptResponse`. It does not run when a framework
3288
+ * integration suppresses provider instrumentation.
3289
+ * - Each SDK uses its own regular-expression engine. These constructs can
3290
+ * give a different result in JavaScript and Python: `$` before a final
3291
+ * newline, Unicode case folding, `\d` and `\w` on non-ASCII text,
3292
+ * `\N{...}` and `\U........` (JavaScript fails closed), and a `]` first
3293
+ * in a class.
3294
+ * - A pattern has no time bound. A pattern with nested repeats can take a
3295
+ * very long time on a long input.
2551
3296
  */
2552
3297
  applyGuardFix(fix, content, isInput = true) {
2553
3298
  try {
@@ -2568,13 +3313,25 @@ var FixApplier = class {
2568
3313
  let passed = true;
2569
3314
  let reason;
2570
3315
  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;
3316
+ const blockedPatterns = "blocked_patterns" in guardConfig ? guardConfig.blocked_patterns : "blockedPatterns" in guardConfig ? guardConfig.blockedPatterns : [];
3317
+ if (!Array.isArray(blockedPatterns)) {
3318
+ warnUnusablePattern(fix.fixId, -1);
3319
+ passed = false;
3320
+ reason = "blocked_patterns is not a list";
3321
+ } else {
3322
+ for (let index = 0; index < blockedPatterns.length; index++) {
3323
+ const regex = this._safeCompileRegex(blockedPatterns[index]);
3324
+ if (!regex) {
3325
+ warnUnusablePattern(fix.fixId, index);
3326
+ passed = false;
3327
+ reason = `blocked pattern ${index} is not usable`;
3328
+ break;
3329
+ }
3330
+ if (regex.test(content)) {
3331
+ passed = false;
3332
+ reason = `blocked pattern matched (pattern ${index})`;
3333
+ break;
3334
+ }
2578
3335
  }
2579
3336
  }
2580
3337
  } else if (guardType === "format_check") {
@@ -2635,11 +3392,17 @@ var FixApplier = class {
2635
3392
  /**
2636
3393
  * Safely compile a regex pattern from untrusted input.
2637
3394
  * Returns null if invalid or too long.
3395
+ *
3396
+ * F-029: the fix patterns are written for Python `re`. Before it compiles
3397
+ * the pattern, this function translates the Python forms that have an exact
3398
+ * JavaScript equivalent (see `translatePythonPattern`). The `i` flag is
3399
+ * always on, as in the Python applier.
2638
3400
  */
2639
3401
  _safeCompileRegex(pattern, maxLength = 500) {
2640
- if (!pattern || pattern.length > maxLength) return null;
3402
+ if (typeof pattern !== "string" || !pattern || pattern.length > maxLength) return null;
2641
3403
  try {
2642
- return new RegExp(pattern, "i");
3404
+ const { source, flags } = translatePythonPattern(pattern);
3405
+ return new RegExp(source, flags);
2643
3406
  } catch {
2644
3407
  debug(`Invalid regex pattern (length=${pattern.length})`);
2645
3408
  return null;
@@ -2715,6 +3478,8 @@ var FixLoader = class _FixLoader {
2715
3478
  _consecutiveFailures = 0;
2716
3479
  _circuitOpenUntil = 0;
2717
3480
  _onLoadCallbacks = [];
3481
+ // The HTTP status of the last load that got a non-2xx answer; null otherwise.
3482
+ _lastStatus = null;
2718
3483
  // Circuit breaker settings
2719
3484
  static CIRCUIT_BREAKER_THRESHOLD = 3;
2720
3485
  static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
@@ -2722,6 +3487,43 @@ var FixLoader = class _FixLoader {
2722
3487
  this._config = resolveFixRuntimeConfig(config);
2723
3488
  this._cache = cache;
2724
3489
  }
3490
+ /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */
3491
+ _scrub(error) {
3492
+ let out;
3493
+ try {
3494
+ out = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
3495
+ } catch {
3496
+ out = typeof error;
3497
+ }
3498
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
3499
+ if (endpoint && safeUrl(endpoint) !== endpoint) out = out.split(endpoint).join(safeUrl(endpoint));
3500
+ return scrubText(out, [this._config.apiKey]);
3501
+ }
3502
+ /**
3503
+ * The WARNING for a failed first load: the request URL with no userinfo, no
3504
+ * query and no key, the HTTP status or the error class, and that tracing is
3505
+ * not affected. Never the error text: it can echo the URL with its query.
3506
+ */
3507
+ _firstLoadWarning(error) {
3508
+ let cause;
3509
+ if (this._lastStatus !== null) {
3510
+ cause = `HTTP ${this._lastStatus}`;
3511
+ } else {
3512
+ cause = error instanceof Error ? error.name : typeof error;
3513
+ const code = error?.cause?.code;
3514
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code)) cause += ` (${code})`;
3515
+ }
3516
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
3517
+ return scrubText(
3518
+ `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.`,
3519
+ [this._config.apiKey],
3520
+ 500
3521
+ );
3522
+ }
3523
+ /** Hide the key from `util.inspect` and `console.log` of the loader. */
3524
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
3525
+ return "FixLoader {}";
3526
+ }
2725
3527
  /** Timestamp of last successful load. */
2726
3528
  get lastLoadTime() {
2727
3529
  return this._lastLoadTime;
@@ -2742,13 +3544,13 @@ var FixLoader = class _FixLoader {
2742
3544
  return;
2743
3545
  }
2744
3546
  this.loadSync().catch((e) => {
2745
- debug(`Initial fix load failed: ${e}`);
3547
+ warn(this._firstLoadWarning(e));
2746
3548
  });
2747
3549
  if (this._config.autoRefresh) {
2748
3550
  this._startRefreshInterval();
2749
3551
  }
2750
3552
  } catch (e) {
2751
- debug(`FixLoader.start error: ${e}`);
3553
+ debug(`FixLoader.start error: ${this._scrub(e)}`);
2752
3554
  }
2753
3555
  }
2754
3556
  /** Stop the loader: clear the refresh interval. */
@@ -2759,7 +3561,7 @@ var FixLoader = class _FixLoader {
2759
3561
  this._refreshTimer = null;
2760
3562
  }
2761
3563
  } catch (e) {
2762
- debug(`FixLoader.stop error: ${e}`);
3564
+ debug(`FixLoader.stop error: ${this._scrub(e)}`);
2763
3565
  }
2764
3566
  }
2765
3567
  /**
@@ -2783,6 +3585,7 @@ var FixLoader = class _FixLoader {
2783
3585
  debug("Fix loader circuit breaker open \u2014 skipping load");
2784
3586
  return this._cache.getAll();
2785
3587
  }
3588
+ this._lastStatus = null;
2786
3589
  try {
2787
3590
  const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
2788
3591
  const url = `${endpoint}/v1/fixes/active`;
@@ -2802,6 +3605,7 @@ var FixLoader = class _FixLoader {
2802
3605
  });
2803
3606
  clearTimeout(timeoutId);
2804
3607
  if (!response.ok) {
3608
+ this._lastStatus = response.status;
2805
3609
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
2806
3610
  }
2807
3611
  const data = await response.json();
@@ -2828,7 +3632,7 @@ var FixLoader = class _FixLoader {
2828
3632
  fixes.push(activeFixFromApiResponse(item));
2829
3633
  }
2830
3634
  } catch (e) {
2831
- debug(`Failed to parse fix item: ${e}`);
3635
+ debug(`Failed to parse fix item: ${this._scrub(e)}`);
2832
3636
  }
2833
3637
  }
2834
3638
  return fixes;
@@ -2841,7 +3645,7 @@ var FixLoader = class _FixLoader {
2841
3645
  try {
2842
3646
  callback(fixes);
2843
3647
  } catch (e) {
2844
- debug(`Load callback error: ${e}`);
3648
+ debug(`Load callback error: ${this._scrub(e)}`);
2845
3649
  }
2846
3650
  }
2847
3651
  debug(`Loaded ${fixes.length} active fixes`);
@@ -2855,14 +3659,14 @@ var FixLoader = class _FixLoader {
2855
3659
  );
2856
3660
  } else {
2857
3661
  debug(
2858
- `Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
3662
+ `Fix load failed (attempt ${this._consecutiveFailures}): ${this._scrub(error)}`
2859
3663
  );
2860
3664
  }
2861
3665
  }
2862
3666
  _startRefreshInterval() {
2863
3667
  const tick = () => {
2864
3668
  this.loadSync().catch((e) => {
2865
- debug(`Background fix refresh failed: ${e}`);
3669
+ debug(`Background fix refresh failed: ${this._scrub(e)}`);
2866
3670
  });
2867
3671
  };
2868
3672
  this._refreshTimer = setInterval(
@@ -3130,6 +3934,80 @@ var TERMINATING_SIGNALS = [
3130
3934
  ];
3131
3935
  var BACKSTOP_MARGIN_MS = 500;
3132
3936
  var _finalMetrics;
3937
+ var _finalProcessor;
3938
+ var _finalActive = false;
3939
+ var SCORE_TIMEOUT_MS = 2e3;
3940
+ var _pendingScores = /* @__PURE__ */ new Set();
3941
+ var _failedScores = 0;
3942
+ var _failedScoresFlushMark = 0;
3943
+ var SCORE_MAX_IN_FLIGHT = 50;
3944
+ var SCORE_MAX_WAITING = 1e3;
3945
+ var SCORE_CAP_REASON = `not sent: ${SCORE_MAX_WAITING} scores wait for a free slot`;
3946
+ var SCORE_DEADLINE_REASON = "not sent before the deadline";
3947
+ var _scoresInFlight = 0;
3948
+ var _scoreWaiters = [];
3949
+ function _startWaitingScores() {
3950
+ while (_scoresInFlight < SCORE_MAX_IN_FLIGHT && _scoreWaiters.length > 0) {
3951
+ _scoreWaiters.shift().start();
3952
+ }
3953
+ }
3954
+ function _failWaitingScores(reason) {
3955
+ for (const waiter of _scoreWaiters.splice(0)) waiter.fail(reason);
3956
+ }
3957
+ var _scoreWarnWindowMs = 1e4;
3958
+ var SCORE_NAME_MAX = 200;
3959
+ var _scoreWarnedAt;
3960
+ var _scoreHeld = 0;
3961
+ var _scoreHeldReason = "";
3962
+ function _resetScoreFailures() {
3963
+ _failedScores = 0;
3964
+ _failedScoresFlushMark = 0;
3965
+ _scoreWarnedAt = void 0;
3966
+ _scoreHeld = 0;
3967
+ _scoreHeldReason = "";
3968
+ }
3969
+ function _heldText() {
3970
+ return ` ${_scoreHeld} more scores failed after the last warning. The last reason: ${_scoreHeldReason}.`;
3971
+ }
3972
+ function _scoreFailed(name, reason) {
3973
+ _failedScores += 1;
3974
+ const now = Date.now();
3975
+ if (_scoreWarnedAt !== void 0 && now - _scoreWarnedAt < _scoreWarnWindowMs) {
3976
+ _scoreHeld += 1;
3977
+ _scoreHeldReason = reason;
3978
+ return;
3979
+ }
3980
+ let message = `score ${JSON.stringify(name.slice(0, SCORE_NAME_MAX))} failed: ${reason}.`;
3981
+ if (_scoreHeld > 0) message += _heldText();
3982
+ _scoreWarnedAt = now;
3983
+ _scoreHeld = 0;
3984
+ _scoreHeldReason = "";
3985
+ warn(message);
3986
+ }
3987
+ function _warnHeldScores() {
3988
+ if (_scoreHeld === 0) return;
3989
+ const message = _heldText().trimStart();
3990
+ _scoreWarnedAt = Date.now();
3991
+ _scoreHeld = 0;
3992
+ _scoreHeldReason = "";
3993
+ warn(message);
3994
+ }
3995
+ async function _waitForPendingScores(timeoutMs) {
3996
+ if (_pendingScores.size === 0) return true;
3997
+ let timer;
3998
+ const expired = new Promise((resolve) => {
3999
+ timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
4000
+ });
4001
+ const settled = (async () => {
4002
+ while (_pendingScores.size > 0) await Promise.all([..._pendingScores]);
4003
+ return true;
4004
+ })();
4005
+ try {
4006
+ return await Promise.race([settled, expired]);
4007
+ } finally {
4008
+ clearTimeout(timer);
4009
+ }
4010
+ }
3133
4011
  var RisicareClient = class {
3134
4012
  config;
3135
4013
  processor;
@@ -3138,17 +4016,30 @@ var RisicareClient = class {
3138
4016
  * this flag `getMetrics()` would keep reporting `"running"` over a processor
3139
4017
  * that has already been torn down. */
3140
4018
  isShutdown = false;
4019
+ /**
4020
+ * Tracing was on at `init()` or since `enable()`. A client that never was
4021
+ * (no key, or tracing off) accepted nothing, and delivered nothing: its
4022
+ * `flush()` is false. `disable()` does not clear it: spans that were accepted
4023
+ * before keep their answer.
4024
+ */
4025
+ _activated = false;
3141
4026
  _shutdownPromise;
3142
4027
  _shutdownHandlers = [];
3143
4028
  constructor(config) {
3144
4029
  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) + "...");
4030
+ const hasKnownPrefix = this.config.apiKey?.startsWith("rsk-") || this.config.apiKey?.startsWith("rski_") || this.config.apiKey?.startsWith("rsks_");
4031
+ if (this.config.apiKey && !hasKnownPrefix) {
4032
+ warn(
4033
+ 'the API key does not look like a Risicare key: it should start with "rsk-", "rski_" or "rsks_". Tracing continues with this key.'
4034
+ );
4035
+ }
4036
+ if (!this.config.apiKey && !tracingTurnedOff(config)) {
4037
+ warn(
4038
+ "Risicare found no API key. Nothing is sent to Risicare: tracing is off, no span is created, and flush() returns false. Set the RISICARE_API_KEY environment variable, or pass apiKey to init()."
4039
+ );
3147
4040
  }
3148
4041
  let exporter;
3149
- if (this.config.debug && !this.config.apiKey) {
3150
- exporter = new ConsoleExporter();
3151
- } else if (this.config.apiKey) {
4042
+ if (this.config.apiKey) {
3152
4043
  exporter = new HttpExporter({
3153
4044
  endpoint: this.config.endpoint,
3154
4045
  apiKey: this.config.apiKey,
@@ -3156,16 +4047,6 @@ var RisicareClient = class {
3156
4047
  environment: this.config.environment || void 0,
3157
4048
  compress: this.config.compress
3158
4049
  });
3159
- } else {
3160
- exporter = void 0;
3161
- if (this.config.enabled) {
3162
- try {
3163
- console.warn(
3164
- `[risicare] tracing is enabled but NO API key is configured \u2014 spans are created and then DROPPED, not sent to ${this.config.endpoint}. Pass apiKey to init() (or set the RISICARE_API_KEY env var). Span data is NOT written to the console: it would be unredacted. Pass debug:true if you want console output for local development.`
3165
- );
3166
- } catch {
3167
- }
3168
- }
3169
4050
  }
3170
4051
  this.processor = new BatchSpanProcessor({
3171
4052
  exporters: exporter ? [exporter] : [],
@@ -3196,6 +4077,7 @@ var RisicareClient = class {
3196
4077
  serviceName: this.config.serviceName,
3197
4078
  serviceVersion: this.config.serviceVersion
3198
4079
  });
4080
+ this._activated = this.tracer.enabled;
3199
4081
  this.processor.start();
3200
4082
  if (this.config.apiKey && this.config.enabled && this.config.fixRuntime) {
3201
4083
  try {
@@ -3207,21 +4089,23 @@ var RisicareClient = class {
3207
4089
  });
3208
4090
  } catch (e) {
3209
4091
  const errName = e instanceof Error ? e.name : "Error";
3210
- const errMsg = e instanceof Error ? e.message : String(e);
4092
+ const errMsg = scrubText(e instanceof Error ? e.message : String(e), [this.config.apiKey]);
3211
4093
  try {
3212
4094
  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.`
4095
+ `[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
4096
  );
3215
4097
  } catch {
3216
4098
  }
3217
4099
  if (this.config.debug) {
3218
- debug(`FixRuntime init traceback: ${e instanceof Error && e.stack ? e.stack : String(e)}`);
4100
+ debug(
4101
+ `FixRuntime init traceback: ${scrubText(e instanceof Error && e.stack ? e.stack : String(e), [this.config.apiKey], 2e3)}`
4102
+ );
3219
4103
  }
3220
4104
  }
3221
4105
  }
3222
4106
  this._registerShutdownHooks();
3223
4107
  setDebug(this.config.debug);
3224
- debug(`Initialized: enabled=${this.config.enabled}, endpoint=${this.config.endpoint}`);
4108
+ debug(`Initialized: enabled=${this.config.enabled}, endpoint=${safeUrl(this.config.endpoint)}`);
3225
4109
  if (!this.config.fixRuntime) {
3226
4110
  debug(
3227
4111
  "FixRuntime is off: nothing polls /fixes/active and no fix is applied. Opt in with fixRuntime: true or RISICARE_FIX_RUNTIME=true."
@@ -3232,23 +4116,32 @@ var RisicareClient = class {
3232
4116
  return this.tracer.enabled;
3233
4117
  }
3234
4118
  set enabled(value) {
4119
+ if (value && !this.config.apiKey) {
4120
+ debug("enable() ignored: no API key is configured, so tracing stays off");
4121
+ return;
4122
+ }
3235
4123
  this.tracer.enabled = value;
4124
+ if (value) this._activated = true;
3236
4125
  }
3237
4126
  // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)
3238
- async shutdown() {
4127
+ async shutdown(timeoutMs) {
3239
4128
  if (this._shutdownPromise) return this._shutdownPromise;
3240
- this._shutdownPromise = this._doShutdown();
4129
+ this._shutdownPromise = this._doShutdown(timeoutMs);
3241
4130
  return this._shutdownPromise;
3242
4131
  }
3243
- async _doShutdown() {
4132
+ async _doShutdown(timeoutMs) {
3244
4133
  debug("Shutting down...");
3245
4134
  for (const { signal, handler } of this._shutdownHandlers) {
3246
4135
  process.removeListener(signal, handler);
3247
4136
  }
3248
4137
  this._shutdownHandlers = [];
3249
- await this.processor.shutdown();
4138
+ endOpenProviderSpans();
4139
+ await this.processor.shutdown(timeoutMs);
4140
+ _failWaitingScores(SCORE_DEADLINE_REASON);
3250
4141
  this.isShutdown = true;
3251
4142
  _finalMetrics = this.processor.getMetrics();
4143
+ _finalProcessor = this.processor;
4144
+ _finalActive = this._activated;
3252
4145
  }
3253
4146
  /**
3254
4147
  * Flush pending spans.
@@ -3261,8 +4154,9 @@ var RisicareClient = class {
3261
4154
  * false one — both leave the customer unable to tell *drained* from
3262
4155
  * *discarded*.
3263
4156
  */
3264
- async flush() {
3265
- return this.processor.flush();
4157
+ async flush(timeoutMs) {
4158
+ if (!this._activated) return false;
4159
+ return this.processor.flush(timeoutMs);
3266
4160
  }
3267
4161
  /**
3268
4162
  * SDK-RELEASE-RULING.md §3 — who decides whether the process dies.
@@ -3288,6 +4182,19 @@ var RisicareClient = class {
3288
4182
  * * **A prior listener exists.** The application took ownership before the
3289
4183
  * SDK loaded. We drain and RETURN; termination was never ours to decide,
3290
4184
  * and forcing it would cut off the app's own graceful shutdown.
4185
+ * * **A listener that the application adds after `init()`.** Node calls ours
4186
+ * first. The question is asked when OUR listener starts, at signal time:
4187
+ * is there another listener for this signal? If there is, it owns
4188
+ * termination as well: when the drain ends we do not raise the signal
4189
+ * again, and we do not arm the fail-safe exit. Its listener runs once and
4190
+ * decides the exit, in the same way as when it was registered before
4191
+ * `init()`. Through 0.8.0 the re-raise ran it a second time, and the
4192
+ * fail-safe ended the process with code 143, 100 ms later.
4193
+ * * **A listener that the application adds DURING the drain.** There was none
4194
+ * at signal time, so the 0.8.0 rule holds: after the drain we raise the
4195
+ * signal again, and that listener runs on it, and the process ends (fail-safe
4196
+ * after 100 ms if it does not). A count taken after the drain would have
4197
+ * counted that listener, and nothing would have run or ended the process.
3291
4198
  *
3292
4199
  * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
3293
4200
  * carries no termination the SDK could displace — the loop has already
@@ -3303,6 +4210,7 @@ var RisicareClient = class {
3303
4210
  for (const [signal, signum] of TERMINATING_SIGNALS) {
3304
4211
  const weDisplacedDefault = process.listenerCount(signal) === 0;
3305
4212
  const handler = () => {
4213
+ const othersAtSignal = process.listeners(signal).filter((l) => l !== handler).length;
3306
4214
  const backstop = setTimeout(
3307
4215
  () => process.exit(128 + signum),
3308
4216
  SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
@@ -3312,6 +4220,7 @@ var RisicareClient = class {
3312
4220
  }).finally(() => {
3313
4221
  clearTimeout(backstop);
3314
4222
  if (!weDisplacedDefault) return;
4223
+ if (othersAtSignal > 0) return;
3315
4224
  try {
3316
4225
  process.kill(process.pid, signal);
3317
4226
  } catch {
@@ -3360,25 +4269,43 @@ function init(config) {
3360
4269
  return;
3361
4270
  }
3362
4271
  _finalMetrics = void 0;
4272
+ _finalProcessor = void 0;
4273
+ _finalActive = false;
4274
+ _resetScoreFailures();
3363
4275
  const client = new RisicareClient(config);
3364
4276
  setClient(client);
3365
4277
  setTracer(client.tracer);
3366
4278
  }
3367
- async function shutdown() {
4279
+ async function shutdown(timeoutMs) {
3368
4280
  try {
3369
4281
  shutdownFixRuntime();
3370
4282
  } catch {
3371
4283
  }
3372
4284
  const client = getClient();
3373
4285
  if (!client) return;
3374
- await client.shutdown();
4286
+ await client.shutdown(timeoutMs);
3375
4287
  setClient(void 0);
3376
4288
  setTracer(void 0);
3377
4289
  }
3378
- async function flush() {
4290
+ async function flush(timeoutMs) {
4291
+ const budgetMs = normalizeTimeoutMs(timeoutMs);
4292
+ const deadline = Date.now() + budgetMs;
4293
+ const scoreMark = _failedScoresFlushMark;
3379
4294
  const client = getClient();
3380
- if (!client) return true;
3381
- return client.flush();
4295
+ let spansOk;
4296
+ if (client) {
4297
+ spansOk = await client.flush(timeoutMs);
4298
+ } else if (_finalProcessor) {
4299
+ spansOk = _finalActive && await _finalProcessor.flush(timeoutMs);
4300
+ } else {
4301
+ spansOk = false;
4302
+ }
4303
+ const scoresDone = await _waitForPendingScores(deadline - Date.now());
4304
+ if (!scoresDone) _failWaitingScores(SCORE_DEADLINE_REASON);
4305
+ _warnHeldScores();
4306
+ const failedNow = _failedScores;
4307
+ if (failedNow > _failedScoresFlushMark) _failedScoresFlushMark = failedNow;
4308
+ return spansOk && scoresDone && failedNow <= scoreMark;
3382
4309
  }
3383
4310
  function enable() {
3384
4311
  const client = getClient();
@@ -3390,7 +4317,7 @@ function disable() {
3390
4317
  }
3391
4318
  function isEnabled() {
3392
4319
  const client = getClient();
3393
- return client?.enabled ?? false;
4320
+ return client !== void 0 && !client.isShutdown && client.enabled;
3394
4321
  }
3395
4322
  function getTracer2() {
3396
4323
  return getTracer();
@@ -3402,22 +4329,31 @@ function getTraceContent() {
3402
4329
  function getMetrics() {
3403
4330
  const client = getClient();
3404
4331
  if (client && !client.isShutdown) {
3405
- return { ...client.processor.getMetrics(), sdkState: "running" };
4332
+ return {
4333
+ ...client.processor.getMetrics(),
4334
+ failedScores: _failedScores,
4335
+ sdkState: "running"
4336
+ };
3406
4337
  }
3407
4338
  if (_finalMetrics) {
4339
+ const tally = _finalProcessor?.getMetrics() ?? _finalMetrics;
3408
4340
  return {
3409
- ..._finalMetrics,
3410
- droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
4341
+ ...tally,
4342
+ failedScores: _failedScores,
4343
+ droppedSpansByReason: { ...tally.droppedSpansByReason },
3411
4344
  sdkState: "shutdown"
3412
4345
  };
3413
4346
  }
3414
4347
  return {
3415
4348
  exportedSpans: 0,
4349
+ rejectedSpans: 0,
4350
+ failedScores: _failedScores,
3416
4351
  droppedSpans: 0,
3417
4352
  droppedSpansByReason: {
3418
4353
  queue_full: 0,
3419
4354
  transport_refused: 0,
3420
- shutdown_residue: 0
4355
+ shutdown_residue: 0,
4356
+ unacknowledged: 0
3421
4357
  },
3422
4358
  failedExports: 0,
3423
4359
  queueSize: 0,
@@ -3462,8 +4398,8 @@ function reportError(error, options) {
3462
4398
  span.setStatus("error" /* ERROR */, err.message);
3463
4399
  span.setAttribute("error", true);
3464
4400
  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));
4401
+ span.setAttribute("error.message", cutCodePoints(err.message, 2e3));
4402
+ if (err.stack) span.setAttribute("error.stack", cutCodePoints(err.stack, 4e3));
3467
4403
  span.setAttribute("risicare.reported_error", true);
3468
4404
  attachErrorCode(span, err);
3469
4405
  if (options?.attributes) {
@@ -3476,14 +4412,29 @@ function reportError(error, options) {
3476
4412
  debug("reportError failed");
3477
4413
  }
3478
4414
  }
4415
+ function refuseScore(message) {
4416
+ warn(message);
4417
+ const client = getClient();
4418
+ if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;
4419
+ }
3479
4420
  function score(traceId, name, value, options) {
3480
4421
  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.`);
4422
+ const raw = value;
4423
+ if (typeof raw === "boolean") value = raw ? 1 : 0;
4424
+ if (typeof value !== "number") {
4425
+ refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4426
+ return;
4427
+ }
4428
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
4429
+ refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
4430
+ return;
4431
+ }
4432
+ if (typeof traceId !== "string" || given(traceId) === void 0) {
4433
+ refuseScore("score: traceId must be a non-empty string. The SDK does not send this score.");
3483
4434
  return;
3484
4435
  }
3485
- if (!traceId || !name) {
3486
- debug("score: traceId and name are required");
4436
+ if (typeof name !== "string" || given(name) === void 0) {
4437
+ refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
3487
4438
  return;
3488
4439
  }
3489
4440
  const client = getClient();
@@ -3502,21 +4453,71 @@ function score(traceId, name, value, options) {
3502
4453
  ...options?.spanId && { span_id: options.spanId },
3503
4454
  ...comment && { comment }
3504
4455
  });
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}`));
4456
+ if (_scoresInFlight >= SCORE_MAX_IN_FLIGHT && _scoreWaiters.length >= SCORE_MAX_WAITING) {
4457
+ _scoreFailed(name, SCORE_CAP_REASON);
4458
+ return;
4459
+ }
4460
+ let settle;
4461
+ const request = new Promise((resolve) => settle = resolve);
4462
+ const send = async () => {
4463
+ const controller = new AbortController();
4464
+ const timer = setTimeout(() => controller.abort(), SCORE_TIMEOUT_MS);
4465
+ try {
4466
+ const response = await fetch(url, {
4467
+ method: "POST",
4468
+ headers: {
4469
+ "Content-Type": "application/json",
4470
+ "Authorization": `Bearer ${client.config.apiKey}`,
4471
+ // F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI
4472
+ // server under /v1/, which `main.py::audit_logging_middleware` audits
4473
+ // into `audit_logs.user_agent`; ingest reaches the Rust gateway, which
4474
+ // discards it. This is the one client-identity visible with no gateway
4475
+ // change.
4476
+ "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
4477
+ "X-Risicare-SDK-Version": SDK_VERSION
4478
+ },
4479
+ body,
4480
+ // Never follow: a redirect is a misroute, not a route. Through 0.7.1
4481
+ // fetch followed a 307 and re-POSTed the score to the login page.
4482
+ redirect: "manual",
4483
+ signal: controller.signal
4484
+ });
4485
+ if (response.type === "opaqueredirect" || response.status >= 300) {
4486
+ _scoreFailed(name, `HTTP ${response.status || "3xx"}`);
4487
+ }
4488
+ try {
4489
+ await response.body?.cancel();
4490
+ } catch {
4491
+ }
4492
+ } catch (err) {
4493
+ const cause = err instanceof Error ? err.cause : void 0;
4494
+ const code = typeof cause?.code === "string" ? cause.code : void 0;
4495
+ const reason = controller.signal.aborted ? `no answer within ${SCORE_TIMEOUT_MS} ms` : code ?? (err instanceof Error ? err.name : "Error");
4496
+ _scoreFailed(name, reason);
4497
+ } finally {
4498
+ clearTimeout(timer);
4499
+ _scoresInFlight--;
4500
+ settle();
4501
+ _startWaitingScores();
4502
+ }
4503
+ };
4504
+ const start = () => {
4505
+ _scoresInFlight++;
4506
+ void send();
4507
+ };
4508
+ if (_scoresInFlight < SCORE_MAX_IN_FLIGHT) {
4509
+ start();
4510
+ } else {
4511
+ _scoreWaiters.push({
4512
+ start,
4513
+ fail: (reason) => {
4514
+ _scoreFailed(name, reason);
4515
+ settle();
4516
+ }
4517
+ });
4518
+ }
4519
+ _pendingScores.add(request);
4520
+ void request.finally(() => _pendingScores.delete(request));
3520
4521
  } catch {
3521
4522
  debug("score failed");
3522
4523
  }
@@ -3545,9 +4546,9 @@ var LIFECYCLE_STATUS = "risicare.lifecycle.status";
3545
4546
  var STATUS_MESSAGE_MAX = 500;
3546
4547
  function excSummary(error) {
3547
4548
  if (error instanceof Error) {
3548
- return `${error.constructor.name}: ${error.message}`.slice(0, STATUS_MESSAGE_MAX);
4549
+ return cutCodePoints(`${error.constructor.name}: ${error.message}`, STATUS_MESSAGE_MAX);
3549
4550
  }
3550
- return String(error).slice(0, STATUS_MESSAGE_MAX);
4551
+ return cutCodePoints(String(error), STATUS_MESSAGE_MAX);
3551
4552
  }
3552
4553
  function stampEndMarker(span, entity, error) {
3553
4554
  try {
@@ -3634,9 +4635,10 @@ function withSessionEndMarker(body) {
3634
4635
 
3635
4636
  // src/decorators/agent.ts
3636
4637
  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 };
4638
+ const agentName = options.name ?? (fn.name.replace(/^(bound )+/, "") || "agent");
4639
+ const spanName = `agent:${agentName}`;
4640
+ const agentId = options.agentId ?? generateAgentId(agentName);
4641
+ const boundOptions = { ...options, name: agentName, agentId };
3640
4642
  return (...args) => {
3641
4643
  const tracer = getTracer2();
3642
4644
  if (!tracer) {
@@ -3689,6 +4691,10 @@ function withPhase(phase, fn) {
3689
4691
  }
3690
4692
 
3691
4693
  // src/decorators/phase.ts
4694
+ function bareName(phase, fn) {
4695
+ const fnName = typeof fn === "function" ? fn.name.replace(/^(bound )+/, "") : "";
4696
+ return fnName ? `${phase}:${fnName}` : `phase:${phase}`;
4697
+ }
3692
4698
  function phaseWrapper(phase, kind, name, fn) {
3693
4699
  return (...args) => {
3694
4700
  const tracer = getTracer2();
@@ -3704,22 +4710,22 @@ function phaseWrapper(phase, kind, name, fn) {
3704
4710
  };
3705
4711
  }
3706
4712
  function traceThink(fnOrName, maybeFn) {
3707
- const name = typeof fnOrName === "string" ? fnOrName : `phase:think`;
4713
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("think", fnOrName);
3708
4714
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3709
4715
  return phaseWrapper("think" /* THINK */, "think" /* THINK */, name, fn);
3710
4716
  }
3711
4717
  function traceDecide(fnOrName, maybeFn) {
3712
- const name = typeof fnOrName === "string" ? fnOrName : `phase:decide`;
4718
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("decide", fnOrName);
3713
4719
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3714
4720
  return phaseWrapper("decide" /* DECIDE */, "decide" /* DECIDE */, name, fn);
3715
4721
  }
3716
4722
  function traceAct(fnOrName, maybeFn) {
3717
- const name = typeof fnOrName === "string" ? fnOrName : `phase:act`;
4723
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("act", fnOrName);
3718
4724
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3719
4725
  return phaseWrapper("act" /* ACT */, "tool_call" /* TOOL_CALL */, name, fn);
3720
4726
  }
3721
4727
  function traceObserve(fnOrName, maybeFn) {
3722
- const name = typeof fnOrName === "string" ? fnOrName : `phase:observe`;
4728
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("observe", fnOrName);
3723
4729
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3724
4730
  return phaseWrapper("observe" /* OBSERVE */, "observe" /* OBSERVE */, name, fn);
3725
4731
  }
@@ -3808,7 +4814,7 @@ function getTraceContext() {
3808
4814
  traceId = ctx._rootTraceId;
3809
4815
  } else {
3810
4816
  traceId = generateTraceId();
3811
- if (ctx.session || ctx.agent) {
4817
+ if (hasContextScope()) {
3812
4818
  ctx._rootTraceId = traceId;
3813
4819
  }
3814
4820
  }
@@ -3845,7 +4851,8 @@ function extractTraceContext(headers) {
3845
4851
  const result = {};
3846
4852
  const normalizedHeaders = {};
3847
4853
  for (const [key, value] of Object.entries(headers)) {
3848
- normalizedHeaders[key.toLowerCase()] = value;
4854
+ const first = Array.isArray(value) ? value[0] : value;
4855
+ if (typeof first === "string") normalizedHeaders[key.toLowerCase()] = first;
3849
4856
  }
3850
4857
  const traceparent = normalizedHeaders[TRACEPARENT_HEADER] ?? "";
3851
4858
  if (traceparent) {