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.cjs CHANGED
@@ -134,6 +134,29 @@ function getDebug() {
134
134
  function setDebugFlag(enabled) {
135
135
  G[PREFIX + "debug"] = enabled;
136
136
  }
137
+ var PROVIDER_SPANS = /* @__PURE__ */ Symbol.for("risicare.providerSpans");
138
+ function usableProviderSpanState(s) {
139
+ if (!s || typeof s !== "object") return false;
140
+ const { version, open, registry } = s;
141
+ const o = open;
142
+ return version === 1 && !!o && typeof o.add === "function" && typeof o.delete === "function" && typeof o[Symbol.iterator] === "function" && (registry === void 0 || typeof registry.register === "function");
143
+ }
144
+ function getProviderSpanState() {
145
+ const found = G[PROVIDER_SPANS];
146
+ if (found === void 0) {
147
+ const s = {
148
+ version: 1,
149
+ open: /* @__PURE__ */ new Set(),
150
+ registry: typeof FinalizationRegistry === "function" ? new FinalizationRegistry((o) => o.release()) : void 0
151
+ };
152
+ G[PROVIDER_SPANS] = s;
153
+ return s;
154
+ }
155
+ if (!usableProviderSpanState(found)) {
156
+ throw new TypeError("the shared provider span state is not version 1");
157
+ }
158
+ return found;
159
+ }
137
160
 
138
161
  // src/utils/log.ts
139
162
  function setDebug(enabled) {
@@ -150,6 +173,73 @@ function warn(msg) {
150
173
  `);
151
174
  }
152
175
 
176
+ // src/utils/text.ts
177
+ function cutCodePoints(text, max) {
178
+ if (text.length <= max) return text;
179
+ let units = 0;
180
+ for (let points = 0; points < max && units < text.length; points++) {
181
+ units += text.codePointAt(units) > 65535 ? 2 : 1;
182
+ }
183
+ return text.slice(0, units);
184
+ }
185
+
186
+ // src/utils/scrub.ts
187
+ var KEY_MARKER = "[REDACTED-KEY]";
188
+ var CONTROL = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]", "g");
189
+ function escapeRegExp(text) {
190
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
191
+ }
192
+ function percentDecode(text) {
193
+ try {
194
+ return decodeURIComponent(text);
195
+ } catch {
196
+ return text.replace(/%([0-9A-Fa-f]{2})/g, (_m, hex) => String.fromCharCode(parseInt(hex, 16)));
197
+ }
198
+ }
199
+ function keyPattern(keys) {
200
+ const values = /* @__PURE__ */ new Set();
201
+ for (const k of [...keys, process.env.RISICARE_API_KEY]) if (k) values.add(k);
202
+ if (values.size === 0) return null;
203
+ const ordered = [...values].sort((a, b) => b.length - a.length);
204
+ return new RegExp(ordered.map(escapeRegExp).join("|"), "gi");
205
+ }
206
+ function scrubText(text, keys, limit = 200) {
207
+ let out;
208
+ try {
209
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
210
+ } catch {
211
+ out = typeof text;
212
+ }
213
+ const pattern = keyPattern(keys);
214
+ if (pattern !== null) {
215
+ if (out.includes("%")) {
216
+ const decoded = percentDecode(out);
217
+ pattern.lastIndex = 0;
218
+ if (decoded !== out && pattern.test(decoded)) out = decoded;
219
+ }
220
+ pattern.lastIndex = 0;
221
+ out = out.replace(pattern, KEY_MARKER);
222
+ }
223
+ return cutCodePoints(out.replace(CONTROL, " "), limit);
224
+ }
225
+ function safeUrl(url) {
226
+ try {
227
+ const u = new URL(url);
228
+ const path = u.pathname === "/" && !/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*\//i.test(url) ? "" : u.pathname;
229
+ return `${u.protocol}//${u.host}${path}`;
230
+ } catch {
231
+ return url.split("?")[0].split("#")[0].replace(/\/\/[^/@]*@/, "//");
232
+ }
233
+ }
234
+ function hasCredentials(url) {
235
+ try {
236
+ const u = new URL(url);
237
+ return u.username !== "" || u.password !== "";
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
153
243
  // src/masking.ts
154
244
  var MASK_ERROR_MARKER = "<risicare:mask-error>";
155
245
  var MASK_BUDGET_MS_PER_SPAN = 1;
@@ -229,6 +319,9 @@ var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
229
319
  "gen_ai.output.messages",
230
320
  "gen_ai.system_instructions",
231
321
  "gen_ai.tool.call.arguments",
322
+ // Corpus v2: the list of tool definitions of a request. The names,
323
+ // descriptions and schemas in it are text that the customer wrote.
324
+ "gen_ai.tool.definitions",
232
325
  "gen_ai.tool.call.result",
233
326
  "input.value",
234
327
  // OpenInference
@@ -392,7 +485,13 @@ function applyMaskBatch(spans, mask, onError) {
392
485
  }
393
486
  const elapsedMs = Date.now() - started;
394
487
  if (errors > 0 && firstKey !== void 0) {
395
- debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);
488
+ let detail;
489
+ try {
490
+ detail = String(firstError);
491
+ } catch {
492
+ detail = typeof firstError;
493
+ }
494
+ debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${detail}`);
396
495
  }
397
496
  return { errors, elapsedMs };
398
497
  }
@@ -408,8 +507,37 @@ function warnMaskSlow(spanCount, elapsedMs) {
408
507
  }
409
508
 
410
509
  // src/exporters/batch.ts
510
+ var DEADLINE = /* @__PURE__ */ Symbol("deadline");
511
+ async function raceDeadline(p, ms) {
512
+ let timer;
513
+ const deadline = new Promise((resolve) => {
514
+ timer = setTimeout(() => resolve(DEADLINE), Math.max(0, ms));
515
+ });
516
+ try {
517
+ return await Promise.race([p, deadline]);
518
+ } finally {
519
+ clearTimeout(timer);
520
+ }
521
+ }
522
+ function describeThrown(e) {
523
+ return scrubText(e, []);
524
+ }
525
+ async function shutdownExporter(exporter, ms) {
526
+ try {
527
+ const outcome = await raceDeadline(Promise.resolve().then(() => exporter.shutdown()), ms);
528
+ if (outcome === DEADLINE) debug(`${exporter.name}.shutdown() did not finish within ${ms} ms`);
529
+ } catch (e) {
530
+ debug(`Error shutting down ${exporter.name}: ${describeThrown(e)}`);
531
+ }
532
+ }
411
533
  var SHUTDOWN_RESERVE_MS = 100;
412
534
  var SHUTDOWN_BUDGET_MS = 5e3;
535
+ var MAX_TIMEOUT_MS = 2 ** 31 - 1;
536
+ function normalizeTimeoutMs(value) {
537
+ if (typeof value !== "number" || !Number.isFinite(value)) return SHUTDOWN_BUDGET_MS;
538
+ if (value < 0) return 0;
539
+ return Math.min(value, MAX_TIMEOUT_MS);
540
+ }
413
541
  var REFUSAL_WARN_WINDOW_MS = 3e5;
414
542
  var DEFAULT_BATCH_SIZE = 500;
415
543
  var MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24e3;
@@ -498,11 +626,30 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
498
626
  _timer = null;
499
627
  _started = false;
500
628
  _flushing = false;
629
+ _inFlight = null;
630
+ /**
631
+ * The `shutdown()` that runs, or ran. A second `shutdown()` returns it, and a
632
+ * `flush()` that comes while it runs waits for it (inside its own deadline).
633
+ */
634
+ _closing = null;
635
+ /**
636
+ * True from the start of the drain of `shutdown()` until its loop ends and the
637
+ * residue is counted (no `await` between those two points). A span that ends
638
+ * in this time joins the drain. After it, the processor can take no span.
639
+ */
640
+ _drainOpen = false;
641
+ _lateSpanWarned = false;
501
642
  _beforeExitHandler = null;
502
643
  // Retry tracking for failed batches (Audit #5)
503
644
  _retryCounts = /* @__PURE__ */ new Map();
504
645
  static MAX_RETRIES = 3;
505
646
  _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
647
+ _lastUnackWarnAt = Number.NEGATIVE_INFINITY;
648
+ /**
649
+ * The loss total (dropped + rejected) that the last finished `flush()` saw.
650
+ * A flush reports a loss that is new since then, one time.
651
+ */
652
+ _lossMark = 0;
506
653
  // ── Masking (see `../masking.ts`) ──────────────────────────────────────────
507
654
  _mask;
508
655
  // ── Content capture gate (see `../masking.ts`) ─────────────────────────────
@@ -524,9 +671,15 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
524
671
  droppedSpansByReason = {
525
672
  queue_full: 0,
526
673
  transport_refused: 0,
527
- shutdown_residue: 0
674
+ shutdown_residue: 0,
675
+ unacknowledged: 0
528
676
  };
529
677
  exportedSpans = 0;
678
+ /**
679
+ * Spans that the backend acknowledged as REJECTED (the ack's `rejected`). They
680
+ * are not stored and are not retried. An exporter without an ack adds nothing.
681
+ */
682
+ rejectedSpans = 0;
530
683
  /** Export ATTEMPTS, not a span count. */
531
684
  failedExports = 0;
532
685
  /**
@@ -611,14 +764,41 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
611
764
  * NO progress and abandons the queue exactly as before — measured at 900 of
612
765
  * 1,000. We await a tick instead, the shape `flush()` already models.
613
766
  *
614
- * Anything still queued when the loop stops is COUNTED as `shutdown_residue`
615
- * and announced with a WARNING. The warning is the primary signal, not the
616
- * counter: a counter incremented inside `shutdown()` is written to memory
617
- * about to be freed and has no reader (RULING §2 / §8.2).
767
+ * The deadline is a hard wall-clock bound. Each round is raced against the
768
+ * budget that remains. At the deadline, `shutdown()` stops the round in flight
769
+ * through the exporter's optional `abort()`. That stopped round changes no
770
+ * counter, does not move the circuit breaker and re-queues nothing. Through
771
+ * 0.7.1 the deadline was checked only between rounds, so one round against a
772
+ * silent server (3 attempts x 5 s) held a 5,000 ms shutdown for 15 s.
773
+ *
774
+ * Anything still queued when the loop stops, AND a batch whose export was
775
+ * stopped, is COUNTED as `shutdown_residue` and announced with ONE WARNING
776
+ * that gives both numbers. The server may have received the spans of the
777
+ * stopped export. The warning is the primary signal, not the counter: a
778
+ * counter incremented inside `shutdown()` is written to memory about to be
779
+ * freed and has no reader (RULING §2 / §8.2).
780
+ *
781
+ * Each exporter's own `shutdown()` gets the time that is left of the budget.
782
+ * An exporter that does not finish in that time is not awaited.
783
+ *
784
+ * Limit: the abort does not stop a TLS handshake that stalls. Measured, such a
785
+ * handshake kept the process alive about 10 s after `shutdown()` returned.
786
+ *
787
+ * A second call, while the first runs or after it ended, returns the promise
788
+ * of the first one. It does not return before the first drain ends.
789
+ *
790
+ * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
791
+ * the values that are not a finite number.
618
792
  */
619
- async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
620
- if (!this._started) return;
793
+ shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
794
+ if (!this._started) return this._closing ?? Promise.resolve();
795
+ this._closing = this._shutdown(timeoutMs);
796
+ return this._closing;
797
+ }
798
+ async _shutdown(timeoutMs) {
799
+ timeoutMs = normalizeTimeoutMs(timeoutMs);
621
800
  this._started = false;
801
+ this._drainOpen = true;
622
802
  if (this._timer) {
623
803
  clearInterval(this._timer);
624
804
  this._timer = null;
@@ -628,10 +808,13 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
628
808
  this._beforeExitHandler = null;
629
809
  }
630
810
  const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);
631
- const drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);
811
+ const shutdownDeadline = Date.now() + timeoutMs;
812
+ const drainDeadline = shutdownDeadline - reserveMs;
632
813
  while (this._queue.length > 0 || this._flushing) {
633
- if (Date.now() >= drainDeadline) break;
634
- const outcome = await this._exportBatch();
814
+ const remaining = drainDeadline - Date.now();
815
+ if (remaining <= 0) break;
816
+ const outcome = await raceDeadline(this._exportBatch(), remaining);
817
+ if (outcome === DEADLINE) break;
635
818
  if (outcome === 3 /* Busy */) {
636
819
  await new Promise((r) => setTimeout(r, 1));
637
820
  continue;
@@ -640,20 +823,30 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
640
823
  break;
641
824
  }
642
825
  }
643
- const residue = this._queue.length;
826
+ this._drainOpen = false;
827
+ const queued = this._queue.length;
828
+ const flight = this._inFlight;
829
+ const inFlight = flight !== null && !flight.abandoned ? flight.size : 0;
830
+ if (flight !== null && !flight.abandoned) {
831
+ flight.abandoned = true;
832
+ for (const exporter of this._exporters) {
833
+ try {
834
+ exporter.abort?.(flight.spans);
835
+ } catch (e) {
836
+ debug(`Error aborting ${exporter.name}: ${describeThrown(e)}`);
837
+ }
838
+ }
839
+ }
840
+ const residue = queued + inFlight;
644
841
  if (residue > 0) {
645
842
  this._queue.length = 0;
646
843
  this._recordDropped("shutdown_residue", residue);
647
844
  warn(
648
- `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.`
845
+ `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.`
649
846
  );
650
847
  }
651
848
  for (const exporter of this._exporters) {
652
- try {
653
- await exporter.shutdown();
654
- } catch (e) {
655
- debug(`Error shutting down ${exporter.name}: ${e}`);
656
- }
849
+ await shutdownExporter(exporter, Math.max(0, shutdownDeadline - Date.now()));
657
850
  }
658
851
  this._retryCounts.clear();
659
852
  debug(
@@ -661,7 +854,14 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
661
854
  );
662
855
  }
663
856
  onSpanEnd(span) {
664
- if (!this._started) return;
857
+ if (!this._started) {
858
+ if (this._drainOpen) this._enqueue(span, false);
859
+ else if (this._closing !== null) this._lateSpan();
860
+ return;
861
+ }
862
+ this._enqueue(span, true);
863
+ }
864
+ _enqueue(span, exportAtBatchSize) {
665
865
  if (this._queue.length >= this._maxQueueSize) {
666
866
  this._recordDropped("queue_full");
667
867
  if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
@@ -670,14 +870,24 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
670
870
  return;
671
871
  }
672
872
  this._queue.push(span);
673
- if (this._queue.length >= this._batchSize) {
873
+ if (exportAtBatchSize && this._queue.length >= this._batchSize) {
674
874
  void this._exportBatch();
675
875
  }
676
876
  }
877
+ /** A span that ended after the drain ended: counted, with one WARNING for the first. */
878
+ _lateSpan() {
879
+ this._recordDropped("shutdown_residue");
880
+ if (this._lateSpanWarned) return;
881
+ this._lateSpanWarned = true;
882
+ warn(
883
+ "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."
884
+ );
885
+ }
677
886
  /**
678
887
  * Flush pending spans.
679
888
  *
680
- * @returns `true` only if everything queued at entry was DELIVERED.
889
+ * @returns `true` only if everything queued at entry was DELIVERED and no
890
+ * span was lost since the previous flush returned.
681
891
  *
682
892
  * RULING §6. This used to answer a different question — "is the queue
683
893
  * empty?" — and those two diverge in exactly one case: when spans left the
@@ -686,35 +896,91 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
686
896
  * everything right; silence lets them discover the problem, a false
687
897
  * affirmative forecloses it.
688
898
  *
689
- * Returns `false` when (a) the deadline expires with spans still queued,
690
- * (b) any span was discarded during the window — breaker refusal or retry
691
- * exhaustion — or (c) it is called after `shutdown()` and the shutdown
692
- * residue was non-zero.
899
+ * A LOSS IS REPORTED BY THE NEXT `flush()`, ONE TIME (design section 0,
900
+ * third revision). Returns `true` only when, at the moment it returns, the
901
+ * queue is empty, no batch is in flight, and no span was discarded or
902
+ * rejected since the previous `flush()` returned (or since start, for the
903
+ * first call). Through 0.7.1 only a loss during the call counted: a script
904
+ * whose spans the batch timer had discarded against a 401 sink got `true`
905
+ * with nothing delivered. A failure that a retry repairs does not make it
906
+ * `false`.
907
+ *
908
+ * Mechanics: the processor keeps a loss mark, the loss total (dropped +
909
+ * rejected) that the last finished flush saw. A flush compares the total
910
+ * with the mark it read at its start, then raises the mark to the total
911
+ * (never lowers it). Two flushes that overlap both answer `false` for one
912
+ * loss. The flush after that answers `true` when nothing new was lost.
913
+ *
914
+ * Returns `false` in these cases:
915
+ * (a) the deadline expires with spans still queued or in flight, or while a
916
+ * `shutdown()` that it waits for still runs;
917
+ * (b) a span was discarded since the previous flush returned: queue full,
918
+ * breaker refusal, retry exhaustion, spans that `shutdown()` left
919
+ * (`shutdown_residue`), or an ack that did not account for it or a span
920
+ * that could not be serialized (`unacknowledged`);
921
+ * (c) the backend rejected a span since the previous flush returned.
922
+ *
923
+ * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at
924
+ * SIGTERM or SIGINT, or a `shutdown()` that nobody awaited) waits for that
925
+ * shutdown, inside its OWN deadline, and then answers from the final tally with
926
+ * the same loss mark. After `shutdown()` it answers from the final tally in the
927
+ * same way. Through 0.8.0 both answered from the empty queue: true in 0 ms,
928
+ * with the batch in flight, and true after a rejection or a `transport_refused`
929
+ * drop. A loss that `shutdown()` counts (also `shutdown_residue`) makes ONE
930
+ * `flush()` false, as every other loss does.
931
+ *
932
+ * The deadline is a hard wall-clock bound on the WAIT. At the deadline
933
+ * `flush()` returns `false`. Through 0.7.1 the deadline was checked only
934
+ * between rounds.
935
+ *
936
+ * ⚠ `flush()` never stops a request that is already sent. The export round in
937
+ * flight continues and ends by its own rules: its request timeout, its
938
+ * retries, the circuit breaker. A short flush budget therefore costs no retry,
939
+ * moves no breaker and sends nothing twice. Its result still counts.
940
+ *
941
+ * Limit: that round can keep the process alive after `flush()` returns
942
+ * `false`, until its own timeouts end. Measured on a silent server: 22 s. To
943
+ * end a process within a bound, call `await shutdown(timeoutMs)`: it stops
944
+ * the round in flight.
693
945
  *
694
946
  * ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span
695
- * that arrived DURING the window also answers `false`. That is the
947
+ * that arrived during the call also answers `false`. That is the
696
948
  * conservative direction on purpose: a false negative costs a caller one
697
949
  * more flush, a false positive is the defect being fixed.
698
950
  */
699
951
  async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
952
+ timeoutMs = normalizeTimeoutMs(timeoutMs);
953
+ const deadline = Date.now() + timeoutMs;
954
+ const mark = this._lossMark;
955
+ const finish = (settled) => {
956
+ const lost = this.droppedSpans + this.rejectedSpans;
957
+ this._lossMark = Math.max(this._lossMark, lost);
958
+ return settled && lost === mark;
959
+ };
700
960
  if (!this._started) {
701
- return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
961
+ if (this._closing !== null) {
962
+ const closed = await raceDeadline(this._closing.catch(() => void 0), timeoutMs);
963
+ if (closed === DEADLINE) return finish(false);
964
+ }
965
+ const held = this._inFlight !== null && !this._inFlight.abandoned;
966
+ return finish(this._queue.length === 0 && !held);
702
967
  }
703
- const start = Date.now();
704
- const discardedAtEntry = this.droppedSpans;
705
968
  while (this._queue.length > 0 || this._flushing) {
969
+ const remaining = deadline - Date.now();
970
+ if (remaining <= 0) return finish(false);
706
971
  if (!this._flushing && this._queue.length > 0) {
707
- await this._exportBatch();
972
+ const outcome = await raceDeadline(this._exportBatch(), remaining);
973
+ if (outcome === DEADLINE) return finish(false);
708
974
  } else {
709
975
  await new Promise((r) => setTimeout(r, 1));
710
976
  }
711
- if (Date.now() - start > timeoutMs) return false;
712
977
  }
713
- return this.droppedSpans === discardedAtEntry;
978
+ return finish(true);
714
979
  }
715
980
  getMetrics() {
716
981
  return {
717
982
  exportedSpans: this.exportedSpans,
983
+ rejectedSpans: this.rejectedSpans,
718
984
  droppedSpans: this.droppedSpans,
719
985
  droppedSpansByReason: { ...this.droppedSpansByReason },
720
986
  failedExports: this.failedExports,
@@ -724,10 +990,56 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
724
990
  queueUtilization: this._queue.length / this._maxQueueSize
725
991
  };
726
992
  }
993
+ /**
994
+ * Count a delivered batch of `n` spans from the exporter's ack.
995
+ *
996
+ * The ack is not trusted. With r = min(rejected, n), a = min(accepted, n - r)
997
+ * and u = n - a - r: `exportedSpans` rises by a, `rejectedSpans` by r, and the
998
+ * u spans that no ack accounts for are dropped as `unacknowledged`, with one
999
+ * rate-limited WARNING. Without an ack (console, custom exporter), the whole
1000
+ * batch counts as exported, as before. Python twin: the same clamp.
1001
+ */
1002
+ _countDelivered(n, ack) {
1003
+ if (ack === null) {
1004
+ this.exportedSpans += n;
1005
+ return;
1006
+ }
1007
+ const rejected = Math.min(ack.rejected, n);
1008
+ const accepted = Math.min(ack.accepted, n - rejected);
1009
+ const unacknowledged = n - accepted - rejected;
1010
+ this.exportedSpans += accepted;
1011
+ this.rejectedSpans += rejected;
1012
+ if (unacknowledged > 0) {
1013
+ this._recordDropped("unacknowledged", unacknowledged);
1014
+ const now = Date.now();
1015
+ if (now - this._lastUnackWarnAt > REFUSAL_WARN_WINDOW_MS) {
1016
+ this._lastUnackWarnAt = now;
1017
+ warn(
1018
+ `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.`
1019
+ );
1020
+ }
1021
+ }
1022
+ }
1023
+ /** The requests in one export round, when every exporter that delivers states it. */
1024
+ _requestsPerRound() {
1025
+ const delivering = this._exporters.filter((e) => e.countsAsDelivery !== false);
1026
+ if (delivering.length !== 1) return void 0;
1027
+ const n = delivering[0].attemptsPerExport;
1028
+ return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : void 0;
1029
+ }
1030
+ /**
1031
+ * One export round.
1032
+ *
1033
+ * Which results decide delivery: an exporter that only shows spans locally
1034
+ * (`countsAsDelivery === false`, the console exporter) decides only when no
1035
+ * other kind of exporter is present. Among the exporters that deliver, ANY
1036
+ * success counts the batch as delivered, once.
1037
+ */
727
1038
  async _exportBatch() {
728
1039
  if (this._flushing) return 3 /* Busy */;
729
1040
  if (this._queue.length === 0) return 0 /* Empty */;
730
1041
  this._flushing = true;
1042
+ let flight = null;
731
1043
  try {
732
1044
  let take = 0;
733
1045
  let pairs = 0;
@@ -746,6 +1058,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
746
1058
  }
747
1059
  const batch = this._queue.splice(0, take);
748
1060
  if (batch.length === 0) return 0 /* Empty */;
1061
+ flight = { spans: batch, size: batch.length, abandoned: false };
1062
+ this._inFlight = flight;
749
1063
  if (!this._traceContent) {
750
1064
  const stripped = stripContentBatch(batch);
751
1065
  if (stripped > 0) {
@@ -759,12 +1073,19 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
759
1073
  }
760
1074
  debug(`Exporting batch of ${batch.length} spans`);
761
1075
  let batchExported = false;
1076
+ const anyDelivers = this._exporters.some((e) => e.countsAsDelivery !== false);
1077
+ const unserializable = /* @__PURE__ */ new Set();
762
1078
  for (const exporter of this._exporters) {
1079
+ const decides = !anyDelivers || exporter.countsAsDelivery !== false;
763
1080
  try {
764
1081
  const result = await exporter.export(batch);
1082
+ if (flight.abandoned) return 2 /* Failed */;
1083
+ if (!decides) continue;
1084
+ for (const span of exporter.takeUnserializable?.(batch) ?? []) unserializable.add(span);
765
1085
  if (result === "success" /* SUCCESS */) {
1086
+ const ack = exporter.takeAck?.(batch) ?? null;
766
1087
  if (!batchExported) {
767
- this.exportedSpans += batch.length;
1088
+ this._countDelivered(batch.length - unserializable.size, ack);
768
1089
  batchExported = true;
769
1090
  for (const span of batch) {
770
1091
  this._retryCounts.delete(span.spanId);
@@ -774,13 +1095,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
774
1095
  this.failedExports++;
775
1096
  }
776
1097
  } catch (e) {
1098
+ if (flight.abandoned) return 2 /* Failed */;
1099
+ if (!decides) continue;
777
1100
  this.failedExports++;
778
- debug(`Export to ${exporter.name} failed: ${e}`);
1101
+ debug(`Export to ${exporter.name} failed: ${describeThrown(e)}`);
779
1102
  }
780
1103
  }
1104
+ if (unserializable.size > 0) this._recordDropped("unacknowledged", unserializable.size);
781
1105
  if (!batchExported) {
782
1106
  let dropped = 0;
783
1107
  const retryable = batch.filter((span) => {
1108
+ if (unserializable.has(span)) return false;
784
1109
  const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
785
1110
  if (count > _BatchSpanProcessor.MAX_RETRIES) {
786
1111
  this._retryCounts.delete(span.spanId);
@@ -799,14 +1124,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
799
1124
  const now = Date.now();
800
1125
  if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {
801
1126
  this._lastRefusalWarnAt = now;
1127
+ const rounds = _BatchSpanProcessor.MAX_RETRIES + 1;
1128
+ const perRound = this._requestsPerRound();
802
1129
  warn(
803
- `${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.`
1130
+ `${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.`
804
1131
  );
805
1132
  }
806
1133
  }
807
1134
  }
808
1135
  return batchExported ? 1 /* Delivered */ : 2 /* Failed */;
809
1136
  } finally {
1137
+ if (this._inFlight === flight) this._inFlight = null;
810
1138
  this._flushing = false;
811
1139
  }
812
1140
  }
@@ -815,18 +1143,46 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
815
1143
  // src/config.ts
816
1144
  var DEFAULT_ENDPOINT = "https://ingest.risicare.ai";
817
1145
  var DEFAULT_API_ENDPOINT = "https://api.risicare.ai";
1146
+ var ASCII_WS_EDGES = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
1147
+ function given(value) {
1148
+ if (typeof value !== "string") return void 0;
1149
+ const trimmed = value.replace(ASCII_WS_EDGES, "");
1150
+ return trimmed === "" ? void 0 : trimmed;
1151
+ }
1152
+ var DEFAULT_INGEST_PATTERN = /^https:\/\/ingest\.risicare\.ai(?::443)?\/*$/i;
1153
+ function isDefaultIngest(value) {
1154
+ return DEFAULT_INGEST_PATTERN.test(value);
1155
+ }
1156
+ function resolveEndpoints(endpointOption, apiEndpointOption, envEndpoint, envApiEndpoint) {
1157
+ const e = given(endpointOption);
1158
+ const a = given(apiEndpointOption);
1159
+ const ee = given(envEndpoint);
1160
+ const ea = given(envApiEndpoint);
1161
+ const endpoint = e ?? ee ?? DEFAULT_ENDPOINT;
1162
+ let apiEndpoint;
1163
+ if (a !== void 0) apiEndpoint = a;
1164
+ else if (e !== void 0 && !isDefaultIngest(e)) apiEndpoint = e;
1165
+ else if (ea !== void 0) apiEndpoint = ea;
1166
+ else if (e === void 0 && ee !== void 0 && !isDefaultIngest(ee)) apiEndpoint = ee;
1167
+ else apiEndpoint = DEFAULT_API_ENDPOINT;
1168
+ return { endpoint, apiEndpoint };
1169
+ }
818
1170
  function resolveConfig(config) {
819
1171
  const env = process.env;
820
- const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
821
- const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;
822
- const apiEndpoint = config?.apiEndpoint ?? env.RISICARE_API_ENDPOINT ?? config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_API_ENDPOINT;
1172
+ const apiKey = keyText(config?.apiKey) || keyText(env.RISICARE_API_KEY) || void 0;
1173
+ const { endpoint, apiEndpoint } = resolveEndpoints(
1174
+ config?.endpoint,
1175
+ config?.apiEndpoint,
1176
+ env.RISICARE_ENDPOINT,
1177
+ env.RISICARE_API_ENDPOINT
1178
+ );
823
1179
  const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;
824
1180
  if (config?.projectId || env.RISICARE_PROJECT_ID) {
825
1181
  console.warn(
826
1182
  "[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."
827
1183
  );
828
1184
  }
829
- const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
1185
+ const environment = config?.environment || env.RISICARE_ENVIRONMENT || "development";
830
1186
  const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
831
1187
  const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
832
1188
  const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
@@ -847,14 +1203,16 @@ function resolveConfig(config) {
847
1203
  const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
848
1204
  const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
849
1205
  let enabled;
1206
+ const tracingEnv = config?.enabled === void 0 ? tracingFromEnv(env.RISICARE_TRACING) : void 0;
850
1207
  if (config?.enabled !== void 0) {
851
1208
  enabled = config.enabled;
852
- } else if (env.RISICARE_TRACING !== void 0) {
853
- enabled = parseBool(env.RISICARE_TRACING, false);
1209
+ } else if (tracingEnv !== void 0) {
1210
+ enabled = tracingEnv;
854
1211
  } else {
855
1212
  enabled = !!apiKey;
856
1213
  }
857
- return {
1214
+ if (!apiKey) enabled = false;
1215
+ return hideKeyFromInspect({
858
1216
  apiKey: apiKey ?? "",
859
1217
  endpoint,
860
1218
  apiEndpoint,
@@ -874,13 +1232,44 @@ function resolveConfig(config) {
874
1232
  metadata: config?.metadata ?? {},
875
1233
  // No env fallback — see the field's note on RisicareConfig.
876
1234
  mask: config?.mask
877
- };
1235
+ });
1236
+ }
1237
+ function hideKeyFromInspect(config) {
1238
+ Object.defineProperty(config, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
1239
+ enumerable: false,
1240
+ value(_depth, options, inspect) {
1241
+ const { apiKey, ...rest } = this;
1242
+ return `RisicareConfig ${inspect({ ...rest, apiKey: apiKey ? "<redacted>" : "" }, options)}`;
1243
+ }
1244
+ });
1245
+ return config;
878
1246
  }
879
1247
  function parseBool(value, defaultValue) {
880
1248
  if (value === void 0) return defaultValue;
881
1249
  const lower = value.toLowerCase();
882
1250
  return lower === "true" || lower === "1" || lower === "yes";
883
1251
  }
1252
+ var TRACING_ON = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
1253
+ var TRACING_OFF = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
1254
+ function tracingFromEnv(value) {
1255
+ if (value === void 0) return void 0;
1256
+ const v = value.trim().toLowerCase();
1257
+ if (v === "") return void 0;
1258
+ if (TRACING_ON.has(v)) return true;
1259
+ if (TRACING_OFF.has(v)) return false;
1260
+ warn(
1261
+ `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.`
1262
+ );
1263
+ return false;
1264
+ }
1265
+ function keyText(value) {
1266
+ return typeof value === "string" ? value.trim() : "";
1267
+ }
1268
+ function tracingTurnedOff(config) {
1269
+ if (config?.enabled !== void 0) return config.enabled === false;
1270
+ const v = (process.env.RISICARE_TRACING ?? "").trim().toLowerCase();
1271
+ return v !== "" && !TRACING_ON.has(v);
1272
+ }
884
1273
  function parseNumericEnv(value, defaultValue) {
885
1274
  if (value === void 0) return defaultValue;
886
1275
  const n = Number(value);
@@ -1486,12 +1875,31 @@ var CANONICAL_ERROR_CODES = /* @__PURE__ */ new Set([
1486
1875
  "TOOL.RESULT.UNEXPECTED_FORMAT",
1487
1876
  "TOOL.RESULT.UNPARSEABLE"
1488
1877
  ]);
1878
+ var CORE_RULES = [
1879
+ { re: new RegExp("json", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" },
1880
+ { re: new RegExp("encoding", "u"), code: "PERCEPTION.INPUT.ENCODING" },
1881
+ { re: new RegExp("injection", "u"), code: "PERCEPTION.INPUT.INJECTION" },
1882
+ { re: new RegExp("malformed", "u"), code: "PERCEPTION.INPUT.MALFORMED" },
1883
+ { re: new RegExp("hallucin", "u"), code: "REASONING.HALLUCINATION.FACTUAL" },
1884
+ { re: new RegExp("contradict", "u"), code: "REASONING.LOGIC.CONTRADICTION" },
1885
+ { re: new RegExp("timeout", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
1886
+ { re: new RegExp("rate[^\\n]?limit", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1887
+ { re: new RegExp("permission", "u"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
1888
+ { re: new RegExp("context[^\\n]+overflow", "u"), code: "MEMORY.CONTEXT_WINDOW.EXCEEDED" },
1889
+ { re: new RegExp("state[^\\n]+corrupt", "u"), code: "MEMORY.STATE.CORRUPTED" },
1890
+ { re: new RegExp("pii", "u"), code: "OUTPUT.SAFETY.PII_LEAK" },
1891
+ { re: new RegExp("deadlock", "u"), code: "COORDINATION.WORKFLOW.DEADLOCK" },
1892
+ { re: new RegExp("undeliverable", "u"), code: "COMMUNICATION.DELIVERY.UNDELIVERABLE" },
1893
+ { re: new RegExp("crash", "u"), code: "ORCHESTRATION.LIFECYCLE.CRASHED" },
1894
+ { re: new RegExp("quorum", "u"), code: "CONSENSUS.AGREEMENT.QUORUM_FAILED" },
1895
+ { re: new RegExp("quota[^\\n]+exceed", "u"), code: "RESOURCES.QUOTA.EXCEEDED" }
1896
+ ];
1489
1897
  var SUPPLEMENTAL_RULES = [
1490
- { re: new RegExp("timeout|timedout|aborted", "i"), code: "TOOL.EXECUTION.TIMEOUT" },
1491
- { re: new RegExp("rate.?limit|\\b429\\b|too many requests", "i"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1492
- { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "i"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
1493
- { re: new RegExp("\\bauth|unauthorized|forbidden|permission|\\b401\\b|\\b403\\b", "i"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
1494
- { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "i"), code: "PERCEPTION.PARSING.JSON_INVALID" }
1898
+ { re: new RegExp("timeout|timedout|aborted", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
1899
+ { re: new RegExp("rate[^\\n]?limit|(?<![\\p{L}\\p{N}_])429(?![\\p{L}\\p{N}_])|too many requests", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1900
+ { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "u"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
1901
+ { 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" },
1902
+ { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" }
1495
1903
  ];
1496
1904
  var GENERIC_FALLBACK = "TOOL.EXECUTION.CRASHED";
1497
1905
 
@@ -1508,6 +1916,16 @@ var GuardRejectedError = class extends Error {
1508
1916
  this.phase = phase;
1509
1917
  }
1510
1918
  };
1919
+ function guardText(message) {
1920
+ if (!message || typeof message !== "object") return null;
1921
+ const content = message.content;
1922
+ if (typeof content === "string") return content === "" ? null : content;
1923
+ if (Array.isArray(content)) {
1924
+ const texts = content.filter((p) => !!p && typeof p === "object" && p.type === "text" && typeof p.text === "string").map((p) => p.text);
1925
+ if (texts.length > 0) return texts.join("\n");
1926
+ }
1927
+ return null;
1928
+ }
1511
1929
  function createInterceptContext(operationType, operationName, options) {
1512
1930
  return {
1513
1931
  operationType,
@@ -1567,8 +1985,8 @@ var DefaultFixInterceptor = class {
1567
1985
  }
1568
1986
  if (modifiedMessages && this._config.enabled) {
1569
1987
  for (const msg of modifiedMessages) {
1570
- const content = msg.content;
1571
- if (typeof content === "string") {
1988
+ const content = guardText(msg);
1989
+ if (content !== null) {
1572
1990
  for (const fix of this._cache.getAll()) {
1573
1991
  if (fix.fixType === "guard") {
1574
1992
  const { passed, result } = this._applier.applyGuardFix(
@@ -1713,7 +2131,13 @@ var DefaultFixInterceptor = class {
1713
2131
  }
1714
2132
  };
1715
2133
  function classifyError(error) {
1716
- const haystack = `${error?.constructor?.name ?? "Error"} ${error?.message ?? ""}`;
2134
+ const message = String(error?.message ?? "").toLowerCase();
2135
+ for (const rule of CORE_RULES) {
2136
+ if (rule.re.test(message)) {
2137
+ return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
2138
+ }
2139
+ }
2140
+ const haystack = `${error?.constructor?.name ?? "Error"} ${String(error?.message ?? "")}`.toLowerCase();
1717
2141
  for (const rule of SUPPLEMENTAL_RULES) {
1718
2142
  if (rule.re.test(haystack)) {
1719
2143
  return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
@@ -1729,6 +2153,9 @@ function storage() {
1729
2153
  function getContext() {
1730
2154
  return storage().getStore() ?? {};
1731
2155
  }
2156
+ function hasContextScope() {
2157
+ return storage().getStore() !== void 0;
2158
+ }
1732
2159
  function runWithContext(overrides, fn) {
1733
2160
  const parent = getContext();
1734
2161
  const merged = { ...parent, ...overrides };
@@ -1785,7 +2212,8 @@ function getCurrentContext() {
1785
2212
  // src/tracer.ts
1786
2213
  function attachErrorCode(span, error) {
1787
2214
  try {
1788
- const err = error instanceof Error ? error : new Error(String(error));
2215
+ const ownMessage = error !== null && typeof error === "object" ? error.message : void 0;
2216
+ const err = error instanceof Error ? error : new Error(typeof ownMessage === "string" ? ownMessage : String(error));
1789
2217
  const code = classifyError(err);
1790
2218
  if (code) {
1791
2219
  span.setAttribute("error.code", code);
@@ -1887,6 +2315,7 @@ var Tracer = class {
1887
2315
  (error) => {
1888
2316
  span.recordException(error instanceof Error ? error : String(error));
1889
2317
  attachErrorCode(span, error);
2318
+ markCancel(span, error);
1890
2319
  span.end();
1891
2320
  throw error;
1892
2321
  }
@@ -1897,6 +2326,7 @@ var Tracer = class {
1897
2326
  } catch (error) {
1898
2327
  span.recordException(error instanceof Error ? error : String(error));
1899
2328
  attachErrorCode(span, error);
2329
+ markCancel(span, error);
1900
2330
  span.end();
1901
2331
  throw error;
1902
2332
  }
@@ -1916,7 +2346,7 @@ var Tracer = class {
1916
2346
  const session2 = getCurrentSession();
1917
2347
  const agent2 = getCurrentAgent();
1918
2348
  const phase = getCurrentPhase();
1919
- const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();
2349
+ const traceId = opts.traceId ?? parentSpan?.traceId ?? getContext()._rootTraceId ?? generateTraceId();
1920
2350
  if (!parentSpan) {
1921
2351
  if (getContext()._traceSampled === false) {
1922
2352
  return NOOP_SPAN;
@@ -1952,9 +2382,15 @@ var Tracer = class {
1952
2382
  );
1953
2383
  }
1954
2384
  };
2385
+ function markCancel(span, error) {
2386
+ if (error instanceof Error && error.name === "AbortError") {
2387
+ span.setAttribute("risicare.cancelled", true);
2388
+ span.setAttribute("risicare.cancel_type", "AbortError");
2389
+ }
2390
+ }
1955
2391
 
1956
2392
  // src/version.ts
1957
- var SDK_VERSION = "0.7.0";
2393
+ var SDK_VERSION = "0.9.0";
1958
2394
 
1959
2395
  // src/exporters/http.ts
1960
2396
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
@@ -1962,6 +2398,8 @@ var RETRY_AFTER_CEILING_MS = 1e4;
1962
2398
  var REFUSAL_BACKOFF_BASE_MS = 1e3;
1963
2399
  var REFUSAL_NO_HINT = -1;
1964
2400
  var MISROUTE_WARN_WINDOW_MS = 3e5;
2401
+ var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
2402
+ var FAILURE_WARN_WINDOW_MS = 3e5;
1965
2403
  var HttpExporter = class {
1966
2404
  name = "http";
1967
2405
  _endpoint;
@@ -1977,21 +2415,24 @@ var HttpExporter = class {
1977
2415
  // cooldown gives the gateway time to come back before the half-open
1978
2416
  // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
1979
2417
  _consecutiveFailures = 0;
2418
+ _lastMisrouteWarnAt = -Infinity;
2419
+ _lastFailureWarnAt = -Infinity;
1980
2420
  /**
1981
- * F-SDK503-001. Set by `_sendRequest` when a response is a CAPACITY REFUSAL, read by the
1982
- * retry loop and the breaker. `null` = not a refusal; `REFUSAL_NO_HINT` = refused with no
1983
- * `Retry-After`; otherwise the honoured delay in ms.
1984
- *
1985
- * ⚠ Node has ONE thread and `export()` is `async`, so two concurrent exports interleave on
1986
- * this field at every `await`. It is written immediately after the awaited `fetch` resolves
1987
- * and read on the very next statement, with no `await` between — so the value cannot be
1988
- * clobbered mid-decision. The Python twin carries the same per-call state on `self` for the
1989
- * same reason (its `_send_request` signature is pin-locked).
2421
+ * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
2422
+ * 'unknown'). `null` after a success. A new kind in the same outage writes one more
2423
+ * WARNING, also inside the window.
1990
2424
  */
1991
- _lastRefusalAfterMs = null;
1992
- /** Set by `_sendRequest` on a MISROUTE: a short description of the answer. `null` = none. */
1993
- _lastMisroute = null;
1994
- _lastMisrouteWarnAt = -Infinity;
2425
+ _failureKind = null;
2426
+ /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
2427
+ _safeEndpoint;
2428
+ /** The endpoint holds userinfo. `fetch` refuses such a URL. */
2429
+ _endpointHasCredentials;
2430
+ /** The calls in progress, by their batch, so that `abort(spans)` stops the right one. */
2431
+ _calls = /* @__PURE__ */ new Map();
2432
+ /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */
2433
+ _acks = /* @__PURE__ */ new WeakMap();
2434
+ /** The spans of each finished call that could not be serialized, by its batch. */
2435
+ _unserializable = /* @__PURE__ */ new WeakMap();
1995
2436
  _circuitOpenUntil = 0;
1996
2437
  _circuitBreakerThreshold = 5;
1997
2438
  _circuitBreakerCooldownMs = 6e4;
@@ -2003,9 +2444,105 @@ var HttpExporter = class {
2003
2444
  this._timeoutMs = options.timeoutMs ?? 5e3;
2004
2445
  this._maxRetries = options.maxRetries ?? 3;
2005
2446
  this._compress = options.compress ?? false;
2447
+ this._safeEndpoint = safeUrl(this._endpoint);
2448
+ this._endpointHasCredentials = hasCredentials(this._endpoint);
2449
+ }
2450
+ /**
2451
+ * Network or error text for a log line: the endpoint as `safeUrl` gives it, and no
2452
+ * form of the API key (`utils/scrub.ts`).
2453
+ */
2454
+ _scrub(text, limit = 200) {
2455
+ let out;
2456
+ try {
2457
+ out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
2458
+ } catch {
2459
+ out = typeof text;
2460
+ }
2461
+ if (this._safeEndpoint !== this._endpoint) out = out.split(this._endpoint).join(this._safeEndpoint);
2462
+ return scrubText(out, [this._apiKey], limit);
2463
+ }
2464
+ /** Hide the key from `util.inspect` and `console.log` of the exporter. */
2465
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
2466
+ return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
2467
+ }
2468
+ /** The most requests that one `export()` call sends (`maxRetries`). */
2469
+ get attemptsPerExport() {
2470
+ return this._maxRetries;
2471
+ }
2472
+ /**
2473
+ * Returns the counts of the ack that the `export()` call for `spans` received, and clears
2474
+ * them. The answer is kept per batch, not on the instance: two processors that share this
2475
+ * exporter cannot read each other's ack across an `await`.
2476
+ */
2477
+ takeAck(spans) {
2478
+ const ack = this._acks.get(spans) ?? null;
2479
+ this._acks.delete(spans);
2480
+ return ack;
2481
+ }
2482
+ /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
2483
+ takeUnserializable(spans) {
2484
+ const bad = this._unserializable.get(spans) ?? [];
2485
+ this._unserializable.delete(spans);
2486
+ return bad;
2006
2487
  }
2488
+ /**
2489
+ * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
2490
+ * request, its retries and its backoff sleep. The batch processor calls it when
2491
+ * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
2492
+ * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
2493
+ * logs no WARNING.
2494
+ */
2495
+ abort(spans) {
2496
+ if (spans !== void 0) this._calls.get(spans)?.cancel.abort();
2497
+ else for (const call of this._calls.values()) call.cancel.abort();
2498
+ }
2499
+ /**
2500
+ * Send one batch. The limits are the request timeout and `maxRetries`.
2501
+ *
2502
+ * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
2503
+ * cuts a request that is already sent. A short flush budget that cut the request made a
2504
+ * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
2505
+ * the server stored the same spans again. Only `abort()` stops the call, and only
2506
+ * `shutdown()` calls it.
2507
+ */
2007
2508
  async export(spans) {
2008
2509
  if (spans.length === 0) return "success" /* SUCCESS */;
2510
+ const call = {
2511
+ cancel: new AbortController(),
2512
+ refusalAfterMs: null,
2513
+ misroute: null,
2514
+ noRetry: false,
2515
+ status: null,
2516
+ error: null
2517
+ };
2518
+ this._calls.set(spans, call);
2519
+ try {
2520
+ return await this._export(spans, call);
2521
+ } finally {
2522
+ this._calls.delete(spans);
2523
+ }
2524
+ }
2525
+ async _export(spans, call) {
2526
+ const cancelled = call.cancel.signal;
2527
+ const parts = [];
2528
+ const bad = [];
2529
+ let errorClass = "";
2530
+ for (const span of spans) {
2531
+ try {
2532
+ parts.push(JSON.stringify(span.toPayload()));
2533
+ } catch (e) {
2534
+ bad.push(span);
2535
+ errorClass ||= e instanceof Error ? e.name : typeof e;
2536
+ }
2537
+ }
2538
+ if (bad.length > 0) {
2539
+ this._unserializable.set(spans, bad);
2540
+ warn(
2541
+ `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).`
2542
+ );
2543
+ }
2544
+ if (parts.length === 0) return "success" /* SUCCESS */;
2545
+ const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
2009
2546
  const now = Date.now();
2010
2547
  let isHalfOpen = false;
2011
2548
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
@@ -2014,44 +2551,64 @@ var HttpExporter = class {
2014
2551
  }
2015
2552
  isHalfOpen = true;
2016
2553
  }
2017
- const body = {
2018
- spans: spans.map((s) => s.toPayload())
2019
- };
2020
- if (this._projectId) body.projectId = this._projectId;
2021
- if (this._environment) body.environment = this._environment;
2022
2554
  const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
2555
+ let attempts = 0;
2023
2556
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
2024
- this._lastRefusalAfterMs = null;
2025
- this._lastMisroute = null;
2026
- const result = await this._sendRequest(body);
2557
+ call.refusalAfterMs = null;
2558
+ call.misroute = null;
2559
+ call.noRetry = false;
2560
+ call.status = null;
2561
+ call.error = null;
2562
+ attempts++;
2563
+ const result = await this._sendRequest(payload, parts.length, call, spans);
2564
+ if (cancelled.aborted) {
2565
+ this._acks.delete(spans);
2566
+ return "failure" /* FAILURE */;
2567
+ }
2027
2568
  if (result === "success" /* SUCCESS */) {
2028
2569
  this._consecutiveFailures = 0;
2570
+ this._failureKind = null;
2029
2571
  return result;
2030
2572
  }
2031
- if (this._lastMisroute !== null) break;
2573
+ if (call.misroute !== null || call.noRetry) break;
2574
+ if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
2032
2575
  if (attempt < maxAttempts - 1) {
2033
- const refusal = this._lastRefusalAfterMs;
2576
+ const refusal = call.refusalAfterMs;
2034
2577
  const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
2035
- await sleep(delay);
2578
+ await sleep(delay, cancelled);
2579
+ if (cancelled.aborted) return "failure" /* FAILURE */;
2036
2580
  }
2037
2581
  }
2038
- const refusedForCapacity = this._lastRefusalAfterMs !== null;
2039
- this._lastRefusalAfterMs = null;
2040
- if (refusedForCapacity) {
2582
+ if (call.refusalAfterMs !== null) {
2041
2583
  warn(
2042
- `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.`
2584
+ `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.`
2043
2585
  );
2044
2586
  return "failure" /* FAILURE */;
2045
2587
  }
2046
- const misroute = this._lastMisroute;
2047
- this._lastMisroute = null;
2588
+ const misroute = call.misroute;
2048
2589
  if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
2049
2590
  this._lastMisrouteWarnAt = Date.now();
2050
2591
  warn(
2051
- `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.`
2592
+ `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.`
2052
2593
  );
2053
2594
  }
2054
2595
  this._consecutiveFailures++;
2596
+ if (misroute === null && !call.noRetry) {
2597
+ const status = call.status;
2598
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
2599
+ let write = false;
2600
+ if (this._consecutiveFailures === 1 || this._failureKind === null) {
2601
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
2602
+ this._lastFailureWarnAt = Date.now();
2603
+ write = true;
2604
+ }
2605
+ this._failureKind = kind;
2606
+ } else if (kind !== this._failureKind) {
2607
+ this._failureKind = kind;
2608
+ write = true;
2609
+ }
2610
+ if (write) this._warnOutage(kind, status, call.error);
2611
+ }
2055
2612
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
2056
2613
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
2057
2614
  warn(
@@ -2060,10 +2617,36 @@ var HttpExporter = class {
2060
2617
  }
2061
2618
  return "failure" /* FAILURE */;
2062
2619
  }
2620
+ /** The outage WARNING for one kind of failure. */
2621
+ _warnOutage(kind, status, error) {
2622
+ const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
2623
+ const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
2624
+ if (kind === "auth") {
2625
+ warn(
2626
+ `${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}`
2627
+ );
2628
+ } else if (kind === "http") {
2629
+ warn(
2630
+ `${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.`
2631
+ );
2632
+ } else if (kind === "none" && this._endpointHasCredentials) {
2633
+ warn(
2634
+ `${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}`
2635
+ );
2636
+ } else if (kind === "none") {
2637
+ warn(
2638
+ `${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.`
2639
+ );
2640
+ } else {
2641
+ warn(
2642
+ `${where}: the export failed. Common causes: an invalid apiKey or an unreachable endpoint. ${tail} Set debug: true to see each attempt.`
2643
+ );
2644
+ }
2645
+ }
2063
2646
  /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
2064
- _noteMisroute(answer) {
2065
- this._lastMisroute = answer.slice(0, 300);
2066
- debug(`Ingest misroute: ${this._lastMisroute}`);
2647
+ _noteMisroute(call, answer) {
2648
+ call.misroute = this._scrub(answer, 300);
2649
+ debug(`Ingest misroute: ${call.misroute}`);
2067
2650
  return "failure" /* FAILURE */;
2068
2651
  }
2069
2652
  /**
@@ -2073,7 +2656,7 @@ var HttpExporter = class {
2073
2656
  * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
2074
2657
  * parse.
2075
2658
  */
2076
- _noteRefusal(status, retryAfterRaw) {
2659
+ _noteRefusal(call, status, retryAfterRaw) {
2077
2660
  if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
2078
2661
  let delay = REFUSAL_NO_HINT;
2079
2662
  if (retryAfterRaw) {
@@ -2082,11 +2665,13 @@ var HttpExporter = class {
2082
2665
  delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
2083
2666
  }
2084
2667
  }
2085
- this._lastRefusalAfterMs = delay;
2086
- debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);
2668
+ call.refusalAfterMs = delay;
2669
+ debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
2087
2670
  return true;
2088
2671
  }
2089
- async _sendRequest(body) {
2672
+ async _sendRequest(body, spansSent, call, spans) {
2673
+ const cancelled = call.cancel.signal;
2674
+ const timeoutMs = this._timeoutMs;
2090
2675
  const url = `${this._endpoint}/v1/spans`;
2091
2676
  const headers = {
2092
2677
  "Content-Type": "application/json",
@@ -2101,19 +2686,22 @@ var HttpExporter = class {
2101
2686
  if (this._apiKey) {
2102
2687
  headers["Authorization"] = `Bearer ${this._apiKey}`;
2103
2688
  }
2104
- let payload = JSON.stringify(body);
2689
+ let payload = body;
2105
2690
  if (this._compress && payload.length > 1024) {
2106
2691
  try {
2107
2692
  const { gzipSync } = await import("zlib");
2108
2693
  payload = gzipSync(Buffer.from(payload));
2109
2694
  headers["Content-Encoding"] = "gzip";
2110
2695
  } catch (e) {
2111
- debug(`Gzip compression failed, sending uncompressed: ${e}`);
2696
+ debug(`Gzip compression failed, sending uncompressed: ${this._scrub(e)}`);
2112
2697
  }
2113
2698
  }
2699
+ const controller = new AbortController();
2700
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
2701
+ const onCancel = () => controller.abort();
2702
+ cancelled.addEventListener("abort", onCancel, { once: true });
2703
+ if (cancelled.aborted) controller.abort();
2114
2704
  try {
2115
- const controller = new AbortController();
2116
- const timeoutId = setTimeout(() => controller.abort(), this._timeoutMs);
2117
2705
  const response = await fetch(url, {
2118
2706
  method: "POST",
2119
2707
  headers,
@@ -2123,40 +2711,89 @@ var HttpExporter = class {
2123
2711
  // the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.
2124
2712
  redirect: "manual"
2125
2713
  });
2126
- clearTimeout(timeoutId);
2714
+ call.status = response.status;
2127
2715
  const redirected = response.type === "opaqueredirect";
2128
2716
  if (redirected || response.status >= 300 && response.status < 400) {
2129
2717
  const location = response.headers?.get?.("Location");
2130
- const target = location ? location.slice(0, 200) : "no Location header";
2131
- return this._noteMisroute(`HTTP ${response.status || "3xx"}, a redirect to ${target}`);
2718
+ const target = location ? this._scrub(location, 1e3) : "no Location header";
2719
+ return this._noteMisroute(call, `HTTP ${response.status || "3xx"}, a redirect to ${target}`);
2132
2720
  }
2133
2721
  if (response.status >= 200 && response.status < 300) {
2134
- const ack = await checkAck(response);
2135
- return ack === null ? this._noteMisroute(
2136
- `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
2137
- ) : ack;
2722
+ const ack = await checkAck(response, spansSent, (t) => this._scrub(t, 1e3));
2723
+ if (ack === null) {
2724
+ if (controller.signal.aborted) {
2725
+ call.status = null;
2726
+ call.error = `timeout after ${timeoutMs} ms`;
2727
+ debug(`HTTP export timeout: the ack body did not arrive within ${timeoutMs} ms`);
2728
+ return "timeout" /* TIMEOUT */;
2729
+ }
2730
+ return this._noteMisroute(
2731
+ call,
2732
+ `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
2733
+ );
2734
+ }
2735
+ if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
2736
+ if (ack.final) call.noRetry = true;
2737
+ return ack.result;
2138
2738
  } else if (response.status === 408 || response.status === 504) {
2139
2739
  debug(`HTTP export timeout: ${response.status}`);
2140
2740
  return "timeout" /* TIMEOUT */;
2141
2741
  }
2142
- this._noteRefusal(response.status, response.headers.get("Retry-After"));
2742
+ this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
2143
2743
  debug(`HTTP export failed: ${response.status}`);
2144
2744
  return "failure" /* FAILURE */;
2145
2745
  } catch (e) {
2146
- debug(`HTTP export error: ${e}`);
2746
+ const cause = e instanceof Error ? e.cause : void 0;
2747
+ call.error = controller.signal.aborted ? `timeout after ${timeoutMs} ms` : typeof cause?.code === "string" ? cause.code : e instanceof Error ? e.name : "Error";
2748
+ debug(`HTTP export error: ${this._scrub(e)}`);
2147
2749
  return "failure" /* FAILURE */;
2750
+ } finally {
2751
+ clearTimeout(timeoutId);
2752
+ cancelled.removeEventListener("abort", onCancel);
2148
2753
  }
2149
2754
  }
2150
2755
  shutdown() {
2151
2756
  }
2152
2757
  };
2153
- function sleep(ms) {
2154
- return new Promise((resolve) => setTimeout(resolve, ms));
2758
+ function sleep(ms, signal) {
2759
+ return new Promise((resolve) => {
2760
+ if (signal?.aborted) return resolve();
2761
+ const done = () => {
2762
+ clearTimeout(timer);
2763
+ signal?.removeEventListener("abort", done);
2764
+ resolve();
2765
+ };
2766
+ const timer = setTimeout(done, ms);
2767
+ signal?.addEventListener("abort", done, { once: true });
2768
+ });
2155
2769
  }
2156
2770
  function asCount(v) {
2157
2771
  return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
2158
2772
  }
2159
- async function checkAck(response) {
2773
+ var MAX_ACK_REASONS = 3;
2774
+ var MAX_ACK_REASON_CHARS = 200;
2775
+ function oneLine(text) {
2776
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ");
2777
+ }
2778
+ function ackReasons(body) {
2779
+ const reasons = [];
2780
+ const errors = body.errors;
2781
+ if (Array.isArray(errors)) {
2782
+ for (const entry of errors) {
2783
+ const text = entry?.error;
2784
+ if (typeof text !== "string" || text.length === 0) continue;
2785
+ const cut = oneLine(text).slice(0, MAX_ACK_REASON_CHARS);
2786
+ if (!reasons.includes(cut)) reasons.push(cut);
2787
+ if (reasons.length === MAX_ACK_REASONS) break;
2788
+ }
2789
+ }
2790
+ if (reasons.length === 0) {
2791
+ const message = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || "";
2792
+ if (message) reasons.push(oneLine(message).slice(0, MAX_ACK_REASON_CHARS));
2793
+ }
2794
+ return reasons.length === 0 ? "No reason was returned." : `Reasons: ${reasons.join("; ")}`;
2795
+ }
2796
+ async function checkAck(response, spansSent, scrub) {
2160
2797
  let payload;
2161
2798
  try {
2162
2799
  payload = await response.json();
@@ -2170,37 +2807,37 @@ async function checkAck(response) {
2170
2807
  const accepted = asCount(body.accepted);
2171
2808
  const rejected = asCount(body.rejected);
2172
2809
  if (accepted === void 0 || rejected === void 0) return null;
2173
- if (rejected === 0) return "success" /* SUCCESS */;
2174
- const errors = body.errors;
2175
- 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.";
2810
+ const counts = { accepted, rejected };
2811
+ if (accepted === 0 && rejected === 0 && spansSent > 0) {
2812
+ warn(
2813
+ `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.`
2814
+ );
2815
+ return { result: "failure" /* FAILURE */, counts, final: true };
2816
+ }
2817
+ if (rejected === 0) return { result: "success" /* SUCCESS */, counts, final: false };
2176
2818
  const total = accepted + rejected;
2177
2819
  if (accepted === 0) {
2178
2820
  warn(
2179
- `Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. ${detail}`
2821
+ `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))}`
2180
2822
  );
2181
- return "failure" /* FAILURE */;
2823
+ return { result: "success" /* SUCCESS */, counts, final: false };
2182
2824
  }
2183
2825
  warn(
2184
- `Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ${accepted} were stored. Those ${rejected} are permanently lost and are NOT retried. ${detail}`
2826
+ `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))}`
2185
2827
  );
2186
- return "success" /* SUCCESS */;
2828
+ return { result: "success" /* SUCCESS */, counts, final: false };
2187
2829
  }
2188
2830
 
2189
- // src/exporters/console.ts
2190
- var ConsoleExporter = class {
2191
- name = "console";
2192
- export(spans) {
2193
- for (const span of spans) {
2194
- const payload = span.toPayload();
2195
- const line = JSON.stringify(payload);
2196
- process.stderr.write(`[risicare] ${line}
2197
- `);
2198
- }
2199
- return "success" /* SUCCESS */;
2200
- }
2201
- shutdown() {
2831
+ // src/utils/stream-proxy.ts
2832
+ function endOpenProviderSpans() {
2833
+ let open;
2834
+ try {
2835
+ open = [...getProviderSpanState().open];
2836
+ } catch {
2837
+ return;
2202
2838
  }
2203
- };
2839
+ for (const o of open) o.end("shutdown");
2840
+ }
2204
2841
 
2205
2842
  // src/runtime/cache.ts
2206
2843
  var FixCache = class {
@@ -2377,6 +3014,94 @@ function emptyResult(fix, fixType) {
2377
3014
  modifications: {}
2378
3015
  };
2379
3016
  }
3017
+ var SAME_ESCAPES = "bBdDsSwWfnrtv";
3018
+ var SAME_ESCAPES_IN_CLASS = "bdDsSwWfnrtv";
3019
+ var LEADING_INLINE_FLAGS = /^\(\?([ims]+)\)/;
3020
+ var PY_NAMED_GROUP = /^\(\?P<([A-Za-z_][A-Za-z0-9_]*)>/;
3021
+ var PY_NAMED_BACKREF = /^\(\?P=([A-Za-z_][A-Za-z0-9_]*)\)/;
3022
+ var JS_NAMED_GROUP = /^\(\?<([A-Za-z_][A-Za-z0-9_]*)>/;
3023
+ function translatePythonPattern(pattern) {
3024
+ let flags = "i";
3025
+ let rest = pattern;
3026
+ const m = LEADING_INLINE_FLAGS.exec(rest);
3027
+ if (m) {
3028
+ for (const f of m[1]) if (!flags.includes(f)) flags += f;
3029
+ rest = rest.slice(m[0].length);
3030
+ }
3031
+ const names = /* @__PURE__ */ new Set();
3032
+ const addName = (name) => {
3033
+ if (names.has(name)) throw new Error("a group name occurs two times");
3034
+ names.add(name);
3035
+ };
3036
+ let source = "";
3037
+ let inClass = false;
3038
+ for (let i = 0; i < rest.length; i++) {
3039
+ const c = rest[i];
3040
+ if (c === "\\" && i + 1 < rest.length) {
3041
+ const next = rest[i + 1];
3042
+ if (/[A-Za-z]/.test(next)) {
3043
+ if (!inClass && next === "A") {
3044
+ source += "(?<![\\s\\S])";
3045
+ i++;
3046
+ continue;
3047
+ }
3048
+ if (!inClass && next === "Z") {
3049
+ source += "(?![\\s\\S])";
3050
+ i++;
3051
+ continue;
3052
+ }
3053
+ if (next === "x" || next === "u") {
3054
+ const n = next === "x" ? 2 : 4;
3055
+ const hex = rest.slice(i + 2, i + 2 + n);
3056
+ if (!new RegExp(`^[0-9A-Fa-f]{${n}}$`).test(hex)) throw new Error("short hex escape");
3057
+ source += c + next + hex;
3058
+ i += 1 + n;
3059
+ continue;
3060
+ }
3061
+ if (!(inClass ? SAME_ESCAPES_IN_CLASS : SAME_ESCAPES).includes(next)) {
3062
+ throw new Error("an escape that Python and JavaScript read differently");
3063
+ }
3064
+ }
3065
+ source += c + next;
3066
+ i++;
3067
+ continue;
3068
+ }
3069
+ if (inClass) {
3070
+ if (c === "]") inClass = false;
3071
+ source += c;
3072
+ continue;
3073
+ }
3074
+ if (c === "[") {
3075
+ inClass = true;
3076
+ source += c;
3077
+ continue;
3078
+ }
3079
+ const tail = rest.slice(i);
3080
+ let g;
3081
+ if ((g = PY_NAMED_GROUP.exec(tail)) || (g = JS_NAMED_GROUP.exec(tail))) {
3082
+ addName(g[1]);
3083
+ source += `(?<${g[1]}>`;
3084
+ i += g[0].length - 1;
3085
+ continue;
3086
+ }
3087
+ if (g = PY_NAMED_BACKREF.exec(tail)) {
3088
+ source += `\\k<${g[1]}>`;
3089
+ i += g[0].length - 1;
3090
+ continue;
3091
+ }
3092
+ source += c;
3093
+ }
3094
+ return { source, flags };
3095
+ }
3096
+ var warnedGuardPatterns = /* @__PURE__ */ new Set();
3097
+ function warnUnusablePattern(fixId, index) {
3098
+ const key = `${fixId ?? "unknown"}\0${index}`;
3099
+ if (warnedGuardPatterns.has(key)) return;
3100
+ warnedGuardPatterns.add(key);
3101
+ warn(
3102
+ 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.`
3103
+ );
3104
+ }
2380
3105
  var FixApplier = class {
2381
3106
  _config;
2382
3107
  _cache;
@@ -2634,6 +3359,26 @@ var FixApplier = class {
2634
3359
  * - content_filter: Regex-based blocked patterns
2635
3360
  * - format_check: JSON.parse() validity
2636
3361
  * - input_validation / output_validation: min/max length
3362
+ *
3363
+ * `content_filter` searches the content for each entry of `blocked_patterns`
3364
+ * (case-insensitive, after `translatePythonPattern`). It fails CLOSED: when
3365
+ * `blocked_patterns` is not a list, or an entry is empty, is not a string,
3366
+ * is longer than 500 characters or cannot be used, the guard does not pass.
3367
+ * One WARNING names the fix id and the pattern index, once for each pair in
3368
+ * the process. The reason names the pattern index, never the pattern or the
3369
+ * content.
3370
+ *
3371
+ * Limits:
3372
+ * - The interceptor runs only on the OpenAI chat patch (input guards) and on
3373
+ * `interceptCall` / `interceptResponse`. It does not run when a framework
3374
+ * integration suppresses provider instrumentation.
3375
+ * - Each SDK uses its own regular-expression engine. These constructs can
3376
+ * give a different result in JavaScript and Python: `$` before a final
3377
+ * newline, Unicode case folding, `\d` and `\w` on non-ASCII text,
3378
+ * `\N{...}` and `\U........` (JavaScript fails closed), and a `]` first
3379
+ * in a class.
3380
+ * - A pattern has no time bound. A pattern with nested repeats can take a
3381
+ * very long time on a long input.
2637
3382
  */
2638
3383
  applyGuardFix(fix, content, isInput = true) {
2639
3384
  try {
@@ -2654,13 +3399,25 @@ var FixApplier = class {
2654
3399
  let passed = true;
2655
3400
  let reason;
2656
3401
  if (guardType === "content_filter") {
2657
- const blockedPatterns = guardConfig.blocked_patterns ?? guardConfig.blockedPatterns ?? [];
2658
- for (const pattern of blockedPatterns) {
2659
- const regex = this._safeCompileRegex(pattern);
2660
- if (regex && regex.test(content)) {
2661
- passed = false;
2662
- reason = `blocked pattern matched: ${pattern.slice(0, 80)}`;
2663
- break;
3402
+ const blockedPatterns = "blocked_patterns" in guardConfig ? guardConfig.blocked_patterns : "blockedPatterns" in guardConfig ? guardConfig.blockedPatterns : [];
3403
+ if (!Array.isArray(blockedPatterns)) {
3404
+ warnUnusablePattern(fix.fixId, -1);
3405
+ passed = false;
3406
+ reason = "blocked_patterns is not a list";
3407
+ } else {
3408
+ for (let index = 0; index < blockedPatterns.length; index++) {
3409
+ const regex = this._safeCompileRegex(blockedPatterns[index]);
3410
+ if (!regex) {
3411
+ warnUnusablePattern(fix.fixId, index);
3412
+ passed = false;
3413
+ reason = `blocked pattern ${index} is not usable`;
3414
+ break;
3415
+ }
3416
+ if (regex.test(content)) {
3417
+ passed = false;
3418
+ reason = `blocked pattern matched (pattern ${index})`;
3419
+ break;
3420
+ }
2664
3421
  }
2665
3422
  }
2666
3423
  } else if (guardType === "format_check") {
@@ -2721,11 +3478,17 @@ var FixApplier = class {
2721
3478
  /**
2722
3479
  * Safely compile a regex pattern from untrusted input.
2723
3480
  * Returns null if invalid or too long.
3481
+ *
3482
+ * F-029: the fix patterns are written for Python `re`. Before it compiles
3483
+ * the pattern, this function translates the Python forms that have an exact
3484
+ * JavaScript equivalent (see `translatePythonPattern`). The `i` flag is
3485
+ * always on, as in the Python applier.
2724
3486
  */
2725
3487
  _safeCompileRegex(pattern, maxLength = 500) {
2726
- if (!pattern || pattern.length > maxLength) return null;
3488
+ if (typeof pattern !== "string" || !pattern || pattern.length > maxLength) return null;
2727
3489
  try {
2728
- return new RegExp(pattern, "i");
3490
+ const { source, flags } = translatePythonPattern(pattern);
3491
+ return new RegExp(source, flags);
2729
3492
  } catch {
2730
3493
  debug(`Invalid regex pattern (length=${pattern.length})`);
2731
3494
  return null;
@@ -2801,6 +3564,8 @@ var FixLoader = class _FixLoader {
2801
3564
  _consecutiveFailures = 0;
2802
3565
  _circuitOpenUntil = 0;
2803
3566
  _onLoadCallbacks = [];
3567
+ // The HTTP status of the last load that got a non-2xx answer; null otherwise.
3568
+ _lastStatus = null;
2804
3569
  // Circuit breaker settings
2805
3570
  static CIRCUIT_BREAKER_THRESHOLD = 3;
2806
3571
  static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
@@ -2808,6 +3573,43 @@ var FixLoader = class _FixLoader {
2808
3573
  this._config = resolveFixRuntimeConfig(config);
2809
3574
  this._cache = cache;
2810
3575
  }
3576
+ /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */
3577
+ _scrub(error) {
3578
+ let out;
3579
+ try {
3580
+ out = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
3581
+ } catch {
3582
+ out = typeof error;
3583
+ }
3584
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
3585
+ if (endpoint && safeUrl(endpoint) !== endpoint) out = out.split(endpoint).join(safeUrl(endpoint));
3586
+ return scrubText(out, [this._config.apiKey]);
3587
+ }
3588
+ /**
3589
+ * The WARNING for a failed first load: the request URL with no userinfo, no
3590
+ * query and no key, the HTTP status or the error class, and that tracing is
3591
+ * not affected. Never the error text: it can echo the URL with its query.
3592
+ */
3593
+ _firstLoadWarning(error) {
3594
+ let cause;
3595
+ if (this._lastStatus !== null) {
3596
+ cause = `HTTP ${this._lastStatus}`;
3597
+ } else {
3598
+ cause = error instanceof Error ? error.name : typeof error;
3599
+ const code = error?.cause?.code;
3600
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code)) cause += ` (${code})`;
3601
+ }
3602
+ const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
3603
+ return scrubText(
3604
+ `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.`,
3605
+ [this._config.apiKey],
3606
+ 500
3607
+ );
3608
+ }
3609
+ /** Hide the key from `util.inspect` and `console.log` of the loader. */
3610
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
3611
+ return "FixLoader {}";
3612
+ }
2811
3613
  /** Timestamp of last successful load. */
2812
3614
  get lastLoadTime() {
2813
3615
  return this._lastLoadTime;
@@ -2828,13 +3630,13 @@ var FixLoader = class _FixLoader {
2828
3630
  return;
2829
3631
  }
2830
3632
  this.loadSync().catch((e) => {
2831
- debug(`Initial fix load failed: ${e}`);
3633
+ warn(this._firstLoadWarning(e));
2832
3634
  });
2833
3635
  if (this._config.autoRefresh) {
2834
3636
  this._startRefreshInterval();
2835
3637
  }
2836
3638
  } catch (e) {
2837
- debug(`FixLoader.start error: ${e}`);
3639
+ debug(`FixLoader.start error: ${this._scrub(e)}`);
2838
3640
  }
2839
3641
  }
2840
3642
  /** Stop the loader: clear the refresh interval. */
@@ -2845,7 +3647,7 @@ var FixLoader = class _FixLoader {
2845
3647
  this._refreshTimer = null;
2846
3648
  }
2847
3649
  } catch (e) {
2848
- debug(`FixLoader.stop error: ${e}`);
3650
+ debug(`FixLoader.stop error: ${this._scrub(e)}`);
2849
3651
  }
2850
3652
  }
2851
3653
  /**
@@ -2869,6 +3671,7 @@ var FixLoader = class _FixLoader {
2869
3671
  debug("Fix loader circuit breaker open \u2014 skipping load");
2870
3672
  return this._cache.getAll();
2871
3673
  }
3674
+ this._lastStatus = null;
2872
3675
  try {
2873
3676
  const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
2874
3677
  const url = `${endpoint}/v1/fixes/active`;
@@ -2888,6 +3691,7 @@ var FixLoader = class _FixLoader {
2888
3691
  });
2889
3692
  clearTimeout(timeoutId);
2890
3693
  if (!response.ok) {
3694
+ this._lastStatus = response.status;
2891
3695
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
2892
3696
  }
2893
3697
  const data = await response.json();
@@ -2914,7 +3718,7 @@ var FixLoader = class _FixLoader {
2914
3718
  fixes.push(activeFixFromApiResponse(item));
2915
3719
  }
2916
3720
  } catch (e) {
2917
- debug(`Failed to parse fix item: ${e}`);
3721
+ debug(`Failed to parse fix item: ${this._scrub(e)}`);
2918
3722
  }
2919
3723
  }
2920
3724
  return fixes;
@@ -2927,7 +3731,7 @@ var FixLoader = class _FixLoader {
2927
3731
  try {
2928
3732
  callback(fixes);
2929
3733
  } catch (e) {
2930
- debug(`Load callback error: ${e}`);
3734
+ debug(`Load callback error: ${this._scrub(e)}`);
2931
3735
  }
2932
3736
  }
2933
3737
  debug(`Loaded ${fixes.length} active fixes`);
@@ -2941,14 +3745,14 @@ var FixLoader = class _FixLoader {
2941
3745
  );
2942
3746
  } else {
2943
3747
  debug(
2944
- `Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
3748
+ `Fix load failed (attempt ${this._consecutiveFailures}): ${this._scrub(error)}`
2945
3749
  );
2946
3750
  }
2947
3751
  }
2948
3752
  _startRefreshInterval() {
2949
3753
  const tick = () => {
2950
3754
  this.loadSync().catch((e) => {
2951
- debug(`Background fix refresh failed: ${e}`);
3755
+ debug(`Background fix refresh failed: ${this._scrub(e)}`);
2952
3756
  });
2953
3757
  };
2954
3758
  this._refreshTimer = setInterval(
@@ -3216,6 +4020,80 @@ var TERMINATING_SIGNALS = [
3216
4020
  ];
3217
4021
  var BACKSTOP_MARGIN_MS = 500;
3218
4022
  var _finalMetrics;
4023
+ var _finalProcessor;
4024
+ var _finalActive = false;
4025
+ var SCORE_TIMEOUT_MS = 2e3;
4026
+ var _pendingScores = /* @__PURE__ */ new Set();
4027
+ var _failedScores = 0;
4028
+ var _failedScoresFlushMark = 0;
4029
+ var SCORE_MAX_IN_FLIGHT = 50;
4030
+ var SCORE_MAX_WAITING = 1e3;
4031
+ var SCORE_CAP_REASON = `not sent: ${SCORE_MAX_WAITING} scores wait for a free slot`;
4032
+ var SCORE_DEADLINE_REASON = "not sent before the deadline";
4033
+ var _scoresInFlight = 0;
4034
+ var _scoreWaiters = [];
4035
+ function _startWaitingScores() {
4036
+ while (_scoresInFlight < SCORE_MAX_IN_FLIGHT && _scoreWaiters.length > 0) {
4037
+ _scoreWaiters.shift().start();
4038
+ }
4039
+ }
4040
+ function _failWaitingScores(reason) {
4041
+ for (const waiter of _scoreWaiters.splice(0)) waiter.fail(reason);
4042
+ }
4043
+ var _scoreWarnWindowMs = 1e4;
4044
+ var SCORE_NAME_MAX = 200;
4045
+ var _scoreWarnedAt;
4046
+ var _scoreHeld = 0;
4047
+ var _scoreHeldReason = "";
4048
+ function _resetScoreFailures() {
4049
+ _failedScores = 0;
4050
+ _failedScoresFlushMark = 0;
4051
+ _scoreWarnedAt = void 0;
4052
+ _scoreHeld = 0;
4053
+ _scoreHeldReason = "";
4054
+ }
4055
+ function _heldText() {
4056
+ return ` ${_scoreHeld} more scores failed after the last warning. The last reason: ${_scoreHeldReason}.`;
4057
+ }
4058
+ function _scoreFailed(name, reason) {
4059
+ _failedScores += 1;
4060
+ const now = Date.now();
4061
+ if (_scoreWarnedAt !== void 0 && now - _scoreWarnedAt < _scoreWarnWindowMs) {
4062
+ _scoreHeld += 1;
4063
+ _scoreHeldReason = reason;
4064
+ return;
4065
+ }
4066
+ let message = `score ${JSON.stringify(name.slice(0, SCORE_NAME_MAX))} failed: ${reason}.`;
4067
+ if (_scoreHeld > 0) message += _heldText();
4068
+ _scoreWarnedAt = now;
4069
+ _scoreHeld = 0;
4070
+ _scoreHeldReason = "";
4071
+ warn(message);
4072
+ }
4073
+ function _warnHeldScores() {
4074
+ if (_scoreHeld === 0) return;
4075
+ const message = _heldText().trimStart();
4076
+ _scoreWarnedAt = Date.now();
4077
+ _scoreHeld = 0;
4078
+ _scoreHeldReason = "";
4079
+ warn(message);
4080
+ }
4081
+ async function _waitForPendingScores(timeoutMs) {
4082
+ if (_pendingScores.size === 0) return true;
4083
+ let timer;
4084
+ const expired = new Promise((resolve) => {
4085
+ timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
4086
+ });
4087
+ const settled = (async () => {
4088
+ while (_pendingScores.size > 0) await Promise.all([..._pendingScores]);
4089
+ return true;
4090
+ })();
4091
+ try {
4092
+ return await Promise.race([settled, expired]);
4093
+ } finally {
4094
+ clearTimeout(timer);
4095
+ }
4096
+ }
3219
4097
  var RisicareClient = class {
3220
4098
  config;
3221
4099
  processor;
@@ -3224,17 +4102,30 @@ var RisicareClient = class {
3224
4102
  * this flag `getMetrics()` would keep reporting `"running"` over a processor
3225
4103
  * that has already been torn down. */
3226
4104
  isShutdown = false;
4105
+ /**
4106
+ * Tracing was on at `init()` or since `enable()`. A client that never was
4107
+ * (no key, or tracing off) accepted nothing, and delivered nothing: its
4108
+ * `flush()` is false. `disable()` does not clear it: spans that were accepted
4109
+ * before keep their answer.
4110
+ */
4111
+ _activated = false;
3227
4112
  _shutdownPromise;
3228
4113
  _shutdownHandlers = [];
3229
4114
  constructor(config) {
3230
4115
  this.config = resolveConfig(config);
3231
- if (this.config.apiKey && !this.config.apiKey.startsWith("rsk-")) {
3232
- debug('Warning: API key should start with "rsk-". Got: ' + this.config.apiKey.slice(0, 4) + "...");
4116
+ const hasKnownPrefix = this.config.apiKey?.startsWith("rsk-") || this.config.apiKey?.startsWith("rski_") || this.config.apiKey?.startsWith("rsks_");
4117
+ if (this.config.apiKey && !hasKnownPrefix) {
4118
+ warn(
4119
+ 'the API key does not look like a Risicare key: it should start with "rsk-", "rski_" or "rsks_". Tracing continues with this key.'
4120
+ );
4121
+ }
4122
+ if (!this.config.apiKey && !tracingTurnedOff(config)) {
4123
+ warn(
4124
+ "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()."
4125
+ );
3233
4126
  }
3234
4127
  let exporter;
3235
- if (this.config.debug && !this.config.apiKey) {
3236
- exporter = new ConsoleExporter();
3237
- } else if (this.config.apiKey) {
4128
+ if (this.config.apiKey) {
3238
4129
  exporter = new HttpExporter({
3239
4130
  endpoint: this.config.endpoint,
3240
4131
  apiKey: this.config.apiKey,
@@ -3242,16 +4133,6 @@ var RisicareClient = class {
3242
4133
  environment: this.config.environment || void 0,
3243
4134
  compress: this.config.compress
3244
4135
  });
3245
- } else {
3246
- exporter = void 0;
3247
- if (this.config.enabled) {
3248
- try {
3249
- console.warn(
3250
- `[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.`
3251
- );
3252
- } catch {
3253
- }
3254
- }
3255
4136
  }
3256
4137
  this.processor = new BatchSpanProcessor({
3257
4138
  exporters: exporter ? [exporter] : [],
@@ -3282,6 +4163,7 @@ var RisicareClient = class {
3282
4163
  serviceName: this.config.serviceName,
3283
4164
  serviceVersion: this.config.serviceVersion
3284
4165
  });
4166
+ this._activated = this.tracer.enabled;
3285
4167
  this.processor.start();
3286
4168
  if (this.config.apiKey && this.config.enabled && this.config.fixRuntime) {
3287
4169
  try {
@@ -3293,21 +4175,23 @@ var RisicareClient = class {
3293
4175
  });
3294
4176
  } catch (e) {
3295
4177
  const errName = e instanceof Error ? e.name : "Error";
3296
- const errMsg = e instanceof Error ? e.message : String(e);
4178
+ const errMsg = scrubText(e instanceof Error ? e.message : String(e), [this.config.apiKey]);
3297
4179
  try {
3298
4180
  console.warn(
3299
- `[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.`
4181
+ `[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.`
3300
4182
  );
3301
4183
  } catch {
3302
4184
  }
3303
4185
  if (this.config.debug) {
3304
- debug(`FixRuntime init traceback: ${e instanceof Error && e.stack ? e.stack : String(e)}`);
4186
+ debug(
4187
+ `FixRuntime init traceback: ${scrubText(e instanceof Error && e.stack ? e.stack : String(e), [this.config.apiKey], 2e3)}`
4188
+ );
3305
4189
  }
3306
4190
  }
3307
4191
  }
3308
4192
  this._registerShutdownHooks();
3309
4193
  setDebug(this.config.debug);
3310
- debug(`Initialized: enabled=${this.config.enabled}, endpoint=${this.config.endpoint}`);
4194
+ debug(`Initialized: enabled=${this.config.enabled}, endpoint=${safeUrl(this.config.endpoint)}`);
3311
4195
  if (!this.config.fixRuntime) {
3312
4196
  debug(
3313
4197
  "FixRuntime is off: nothing polls /fixes/active and no fix is applied. Opt in with fixRuntime: true or RISICARE_FIX_RUNTIME=true."
@@ -3318,23 +4202,32 @@ var RisicareClient = class {
3318
4202
  return this.tracer.enabled;
3319
4203
  }
3320
4204
  set enabled(value) {
4205
+ if (value && !this.config.apiKey) {
4206
+ debug("enable() ignored: no API key is configured, so tracing stays off");
4207
+ return;
4208
+ }
3321
4209
  this.tracer.enabled = value;
4210
+ if (value) this._activated = true;
3322
4211
  }
3323
4212
  // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)
3324
- async shutdown() {
4213
+ async shutdown(timeoutMs) {
3325
4214
  if (this._shutdownPromise) return this._shutdownPromise;
3326
- this._shutdownPromise = this._doShutdown();
4215
+ this._shutdownPromise = this._doShutdown(timeoutMs);
3327
4216
  return this._shutdownPromise;
3328
4217
  }
3329
- async _doShutdown() {
4218
+ async _doShutdown(timeoutMs) {
3330
4219
  debug("Shutting down...");
3331
4220
  for (const { signal, handler } of this._shutdownHandlers) {
3332
4221
  process.removeListener(signal, handler);
3333
4222
  }
3334
4223
  this._shutdownHandlers = [];
3335
- await this.processor.shutdown();
4224
+ endOpenProviderSpans();
4225
+ await this.processor.shutdown(timeoutMs);
4226
+ _failWaitingScores(SCORE_DEADLINE_REASON);
3336
4227
  this.isShutdown = true;
3337
4228
  _finalMetrics = this.processor.getMetrics();
4229
+ _finalProcessor = this.processor;
4230
+ _finalActive = this._activated;
3338
4231
  }
3339
4232
  /**
3340
4233
  * Flush pending spans.
@@ -3347,8 +4240,9 @@ var RisicareClient = class {
3347
4240
  * false one — both leave the customer unable to tell *drained* from
3348
4241
  * *discarded*.
3349
4242
  */
3350
- async flush() {
3351
- return this.processor.flush();
4243
+ async flush(timeoutMs) {
4244
+ if (!this._activated) return false;
4245
+ return this.processor.flush(timeoutMs);
3352
4246
  }
3353
4247
  /**
3354
4248
  * SDK-RELEASE-RULING.md §3 — who decides whether the process dies.
@@ -3374,6 +4268,19 @@ var RisicareClient = class {
3374
4268
  * * **A prior listener exists.** The application took ownership before the
3375
4269
  * SDK loaded. We drain and RETURN; termination was never ours to decide,
3376
4270
  * and forcing it would cut off the app's own graceful shutdown.
4271
+ * * **A listener that the application adds after `init()`.** Node calls ours
4272
+ * first. The question is asked when OUR listener starts, at signal time:
4273
+ * is there another listener for this signal? If there is, it owns
4274
+ * termination as well: when the drain ends we do not raise the signal
4275
+ * again, and we do not arm the fail-safe exit. Its listener runs once and
4276
+ * decides the exit, in the same way as when it was registered before
4277
+ * `init()`. Through 0.8.0 the re-raise ran it a second time, and the
4278
+ * fail-safe ended the process with code 143, 100 ms later.
4279
+ * * **A listener that the application adds DURING the drain.** There was none
4280
+ * at signal time, so the 0.8.0 rule holds: after the drain we raise the
4281
+ * signal again, and that listener runs on it, and the process ends (fail-safe
4282
+ * after 100 ms if it does not). A count taken after the drain would have
4283
+ * counted that listener, and nothing would have run or ended the process.
3377
4284
  *
3378
4285
  * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
3379
4286
  * carries no termination the SDK could displace — the loop has already
@@ -3389,6 +4296,7 @@ var RisicareClient = class {
3389
4296
  for (const [signal, signum] of TERMINATING_SIGNALS) {
3390
4297
  const weDisplacedDefault = process.listenerCount(signal) === 0;
3391
4298
  const handler = () => {
4299
+ const othersAtSignal = process.listeners(signal).filter((l) => l !== handler).length;
3392
4300
  const backstop = setTimeout(
3393
4301
  () => process.exit(128 + signum),
3394
4302
  SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
@@ -3398,6 +4306,7 @@ var RisicareClient = class {
3398
4306
  }).finally(() => {
3399
4307
  clearTimeout(backstop);
3400
4308
  if (!weDisplacedDefault) return;
4309
+ if (othersAtSignal > 0) return;
3401
4310
  try {
3402
4311
  process.kill(process.pid, signal);
3403
4312
  } catch {
@@ -3446,25 +4355,43 @@ function init(config) {
3446
4355
  return;
3447
4356
  }
3448
4357
  _finalMetrics = void 0;
4358
+ _finalProcessor = void 0;
4359
+ _finalActive = false;
4360
+ _resetScoreFailures();
3449
4361
  const client = new RisicareClient(config);
3450
4362
  setClient(client);
3451
4363
  setTracer(client.tracer);
3452
4364
  }
3453
- async function shutdown() {
4365
+ async function shutdown(timeoutMs) {
3454
4366
  try {
3455
4367
  shutdownFixRuntime();
3456
4368
  } catch {
3457
4369
  }
3458
4370
  const client = getClient();
3459
4371
  if (!client) return;
3460
- await client.shutdown();
4372
+ await client.shutdown(timeoutMs);
3461
4373
  setClient(void 0);
3462
4374
  setTracer(void 0);
3463
4375
  }
3464
- async function flush() {
4376
+ async function flush(timeoutMs) {
4377
+ const budgetMs = normalizeTimeoutMs(timeoutMs);
4378
+ const deadline = Date.now() + budgetMs;
4379
+ const scoreMark = _failedScoresFlushMark;
3465
4380
  const client = getClient();
3466
- if (!client) return true;
3467
- return client.flush();
4381
+ let spansOk;
4382
+ if (client) {
4383
+ spansOk = await client.flush(timeoutMs);
4384
+ } else if (_finalProcessor) {
4385
+ spansOk = _finalActive && await _finalProcessor.flush(timeoutMs);
4386
+ } else {
4387
+ spansOk = false;
4388
+ }
4389
+ const scoresDone = await _waitForPendingScores(deadline - Date.now());
4390
+ if (!scoresDone) _failWaitingScores(SCORE_DEADLINE_REASON);
4391
+ _warnHeldScores();
4392
+ const failedNow = _failedScores;
4393
+ if (failedNow > _failedScoresFlushMark) _failedScoresFlushMark = failedNow;
4394
+ return spansOk && scoresDone && failedNow <= scoreMark;
3468
4395
  }
3469
4396
  function enable() {
3470
4397
  const client = getClient();
@@ -3476,7 +4403,7 @@ function disable() {
3476
4403
  }
3477
4404
  function isEnabled() {
3478
4405
  const client = getClient();
3479
- return client?.enabled ?? false;
4406
+ return client !== void 0 && !client.isShutdown && client.enabled;
3480
4407
  }
3481
4408
  function getTracer2() {
3482
4409
  return getTracer();
@@ -3488,22 +4415,31 @@ function getTraceContent() {
3488
4415
  function getMetrics() {
3489
4416
  const client = getClient();
3490
4417
  if (client && !client.isShutdown) {
3491
- return { ...client.processor.getMetrics(), sdkState: "running" };
4418
+ return {
4419
+ ...client.processor.getMetrics(),
4420
+ failedScores: _failedScores,
4421
+ sdkState: "running"
4422
+ };
3492
4423
  }
3493
4424
  if (_finalMetrics) {
4425
+ const tally = _finalProcessor?.getMetrics() ?? _finalMetrics;
3494
4426
  return {
3495
- ..._finalMetrics,
3496
- droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
4427
+ ...tally,
4428
+ failedScores: _failedScores,
4429
+ droppedSpansByReason: { ...tally.droppedSpansByReason },
3497
4430
  sdkState: "shutdown"
3498
4431
  };
3499
4432
  }
3500
4433
  return {
3501
4434
  exportedSpans: 0,
4435
+ rejectedSpans: 0,
4436
+ failedScores: _failedScores,
3502
4437
  droppedSpans: 0,
3503
4438
  droppedSpansByReason: {
3504
4439
  queue_full: 0,
3505
4440
  transport_refused: 0,
3506
- shutdown_residue: 0
4441
+ shutdown_residue: 0,
4442
+ unacknowledged: 0
3507
4443
  },
3508
4444
  failedExports: 0,
3509
4445
  queueSize: 0,
@@ -3548,8 +4484,8 @@ function reportError(error, options) {
3548
4484
  span.setStatus("error" /* ERROR */, err.message);
3549
4485
  span.setAttribute("error", true);
3550
4486
  span.setAttribute("error.type", err.constructor.name);
3551
- span.setAttribute("error.message", err.message.slice(0, 2e3));
3552
- if (err.stack) span.setAttribute("error.stack", err.stack.slice(0, 4e3));
4487
+ span.setAttribute("error.message", cutCodePoints(err.message, 2e3));
4488
+ if (err.stack) span.setAttribute("error.stack", cutCodePoints(err.stack, 4e3));
3553
4489
  span.setAttribute("risicare.reported_error", true);
3554
4490
  attachErrorCode(span, err);
3555
4491
  if (options?.attributes) {
@@ -3562,14 +4498,29 @@ function reportError(error, options) {
3562
4498
  debug("reportError failed");
3563
4499
  }
3564
4500
  }
4501
+ function refuseScore(message) {
4502
+ warn(message);
4503
+ const client = getClient();
4504
+ if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;
4505
+ }
3565
4506
  function score(traceId, name, value, options) {
3566
4507
  try {
3567
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {
3568
- debug(`score: value must be in [0.0, 1.0], got ${value}. Score not sent.`);
4508
+ const raw = value;
4509
+ if (typeof raw === "boolean") value = raw ? 1 : 0;
4510
+ if (typeof value !== "number") {
4511
+ refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4512
+ return;
4513
+ }
4514
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
4515
+ refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
4516
+ return;
4517
+ }
4518
+ if (typeof traceId !== "string" || given(traceId) === void 0) {
4519
+ refuseScore("score: traceId must be a non-empty string. The SDK does not send this score.");
3569
4520
  return;
3570
4521
  }
3571
- if (!traceId || !name) {
3572
- debug("score: traceId and name are required");
4522
+ if (typeof name !== "string" || given(name) === void 0) {
4523
+ refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
3573
4524
  return;
3574
4525
  }
3575
4526
  const client = getClient();
@@ -3588,21 +4539,71 @@ function score(traceId, name, value, options) {
3588
4539
  ...options?.spanId && { span_id: options.spanId },
3589
4540
  ...comment && { comment }
3590
4541
  });
3591
- fetch(url, {
3592
- method: "POST",
3593
- headers: {
3594
- "Content-Type": "application/json",
3595
- "Authorization": `Bearer ${client.config.apiKey}`,
3596
- // F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI
3597
- // server under /v1/, which `main.py::audit_logging_middleware` audits
3598
- // into `audit_logs.user_agent`; ingest reaches the Rust gateway, which
3599
- // discards it. This is the one client-identity visible with no gateway
3600
- // change.
3601
- "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
3602
- "X-Risicare-SDK-Version": SDK_VERSION
3603
- },
3604
- body
3605
- }).catch((err) => debug(`score: send failed: ${err}`));
4542
+ if (_scoresInFlight >= SCORE_MAX_IN_FLIGHT && _scoreWaiters.length >= SCORE_MAX_WAITING) {
4543
+ _scoreFailed(name, SCORE_CAP_REASON);
4544
+ return;
4545
+ }
4546
+ let settle;
4547
+ const request = new Promise((resolve) => settle = resolve);
4548
+ const send = async () => {
4549
+ const controller = new AbortController();
4550
+ const timer = setTimeout(() => controller.abort(), SCORE_TIMEOUT_MS);
4551
+ try {
4552
+ const response = await fetch(url, {
4553
+ method: "POST",
4554
+ headers: {
4555
+ "Content-Type": "application/json",
4556
+ "Authorization": `Bearer ${client.config.apiKey}`,
4557
+ // F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI
4558
+ // server under /v1/, which `main.py::audit_logging_middleware` audits
4559
+ // into `audit_logs.user_agent`; ingest reaches the Rust gateway, which
4560
+ // discards it. This is the one client-identity visible with no gateway
4561
+ // change.
4562
+ "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
4563
+ "X-Risicare-SDK-Version": SDK_VERSION
4564
+ },
4565
+ body,
4566
+ // Never follow: a redirect is a misroute, not a route. Through 0.7.1
4567
+ // fetch followed a 307 and re-POSTed the score to the login page.
4568
+ redirect: "manual",
4569
+ signal: controller.signal
4570
+ });
4571
+ if (response.type === "opaqueredirect" || response.status >= 300) {
4572
+ _scoreFailed(name, `HTTP ${response.status || "3xx"}`);
4573
+ }
4574
+ try {
4575
+ await response.body?.cancel();
4576
+ } catch {
4577
+ }
4578
+ } catch (err) {
4579
+ const cause = err instanceof Error ? err.cause : void 0;
4580
+ const code = typeof cause?.code === "string" ? cause.code : void 0;
4581
+ const reason = controller.signal.aborted ? `no answer within ${SCORE_TIMEOUT_MS} ms` : code ?? (err instanceof Error ? err.name : "Error");
4582
+ _scoreFailed(name, reason);
4583
+ } finally {
4584
+ clearTimeout(timer);
4585
+ _scoresInFlight--;
4586
+ settle();
4587
+ _startWaitingScores();
4588
+ }
4589
+ };
4590
+ const start = () => {
4591
+ _scoresInFlight++;
4592
+ void send();
4593
+ };
4594
+ if (_scoresInFlight < SCORE_MAX_IN_FLIGHT) {
4595
+ start();
4596
+ } else {
4597
+ _scoreWaiters.push({
4598
+ start,
4599
+ fail: (reason) => {
4600
+ _scoreFailed(name, reason);
4601
+ settle();
4602
+ }
4603
+ });
4604
+ }
4605
+ _pendingScores.add(request);
4606
+ void request.finally(() => _pendingScores.delete(request));
3606
4607
  } catch {
3607
4608
  debug("score failed");
3608
4609
  }
@@ -3631,9 +4632,9 @@ var LIFECYCLE_STATUS = "risicare.lifecycle.status";
3631
4632
  var STATUS_MESSAGE_MAX = 500;
3632
4633
  function excSummary(error) {
3633
4634
  if (error instanceof Error) {
3634
- return `${error.constructor.name}: ${error.message}`.slice(0, STATUS_MESSAGE_MAX);
4635
+ return cutCodePoints(`${error.constructor.name}: ${error.message}`, STATUS_MESSAGE_MAX);
3635
4636
  }
3636
- return String(error).slice(0, STATUS_MESSAGE_MAX);
4637
+ return cutCodePoints(String(error), STATUS_MESSAGE_MAX);
3637
4638
  }
3638
4639
  function stampEndMarker(span, entity, error) {
3639
4640
  try {
@@ -3720,9 +4721,10 @@ function withSessionEndMarker(body) {
3720
4721
 
3721
4722
  // src/decorators/agent.ts
3722
4723
  function _wrapAgent(options, fn) {
3723
- const spanName = `agent:${options.name ?? "agent"}`;
3724
- const agentId = options.agentId ?? generateAgentId(options.name ?? "agent");
3725
- const boundOptions = { ...options, agentId };
4724
+ const agentName = options.name ?? (fn.name.replace(/^(bound )+/, "") || "agent");
4725
+ const spanName = `agent:${agentName}`;
4726
+ const agentId = options.agentId ?? generateAgentId(agentName);
4727
+ const boundOptions = { ...options, name: agentName, agentId };
3726
4728
  return (...args) => {
3727
4729
  const tracer = getTracer2();
3728
4730
  if (!tracer) {
@@ -3775,6 +4777,10 @@ function withPhase(phase, fn) {
3775
4777
  }
3776
4778
 
3777
4779
  // src/decorators/phase.ts
4780
+ function bareName(phase, fn) {
4781
+ const fnName = typeof fn === "function" ? fn.name.replace(/^(bound )+/, "") : "";
4782
+ return fnName ? `${phase}:${fnName}` : `phase:${phase}`;
4783
+ }
3778
4784
  function phaseWrapper(phase, kind, name, fn) {
3779
4785
  return (...args) => {
3780
4786
  const tracer = getTracer2();
@@ -3790,22 +4796,22 @@ function phaseWrapper(phase, kind, name, fn) {
3790
4796
  };
3791
4797
  }
3792
4798
  function traceThink(fnOrName, maybeFn) {
3793
- const name = typeof fnOrName === "string" ? fnOrName : `phase:think`;
4799
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("think", fnOrName);
3794
4800
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3795
4801
  return phaseWrapper("think" /* THINK */, "think" /* THINK */, name, fn);
3796
4802
  }
3797
4803
  function traceDecide(fnOrName, maybeFn) {
3798
- const name = typeof fnOrName === "string" ? fnOrName : `phase:decide`;
4804
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("decide", fnOrName);
3799
4805
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3800
4806
  return phaseWrapper("decide" /* DECIDE */, "decide" /* DECIDE */, name, fn);
3801
4807
  }
3802
4808
  function traceAct(fnOrName, maybeFn) {
3803
- const name = typeof fnOrName === "string" ? fnOrName : `phase:act`;
4809
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("act", fnOrName);
3804
4810
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3805
4811
  return phaseWrapper("act" /* ACT */, "tool_call" /* TOOL_CALL */, name, fn);
3806
4812
  }
3807
4813
  function traceObserve(fnOrName, maybeFn) {
3808
- const name = typeof fnOrName === "string" ? fnOrName : `phase:observe`;
4814
+ const name = typeof fnOrName === "string" ? fnOrName : bareName("observe", fnOrName);
3809
4815
  const fn = typeof fnOrName === "function" ? fnOrName : maybeFn;
3810
4816
  return phaseWrapper("observe" /* OBSERVE */, "observe" /* OBSERVE */, name, fn);
3811
4817
  }
@@ -3894,7 +4900,7 @@ function getTraceContext() {
3894
4900
  traceId = ctx._rootTraceId;
3895
4901
  } else {
3896
4902
  traceId = generateTraceId();
3897
- if (ctx.session || ctx.agent) {
4903
+ if (hasContextScope()) {
3898
4904
  ctx._rootTraceId = traceId;
3899
4905
  }
3900
4906
  }
@@ -3931,7 +4937,8 @@ function extractTraceContext(headers) {
3931
4937
  const result = {};
3932
4938
  const normalizedHeaders = {};
3933
4939
  for (const [key, value] of Object.entries(headers)) {
3934
- normalizedHeaders[key.toLowerCase()] = value;
4940
+ const first = Array.isArray(value) ? value[0] : value;
4941
+ if (typeof first === "string") normalizedHeaders[key.toLowerCase()] = first;
3935
4942
  }
3936
4943
  const traceparent = normalizedHeaders[TRACEPARENT_HEADER] ?? "";
3937
4944
  if (traceparent) {