risicare 0.8.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 (72) hide show
  1. package/README.md +80 -21
  2. package/dist/frameworks/instructor.cjs +1 -1
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +1 -1
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +1 -1
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.js +1 -1
  9. package/dist/frameworks/langchain.js.map +1 -1
  10. package/dist/frameworks/langgraph.cjs +1 -1
  11. package/dist/frameworks/langgraph.cjs.map +1 -1
  12. package/dist/frameworks/langgraph.js +1 -1
  13. package/dist/frameworks/langgraph.js.map +1 -1
  14. package/dist/frameworks/llamaindex.cjs +1 -1
  15. package/dist/frameworks/llamaindex.cjs.map +1 -1
  16. package/dist/frameworks/llamaindex.js +1 -1
  17. package/dist/frameworks/llamaindex.js.map +1 -1
  18. package/dist/index.cjs +131 -61
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +22 -8
  21. package/dist/index.d.ts +22 -8
  22. package/dist/index.js +131 -61
  23. package/dist/index.js.map +1 -1
  24. package/dist/providers/anthropic/index.cjs +1 -1
  25. package/dist/providers/anthropic/index.cjs.map +1 -1
  26. package/dist/providers/anthropic/index.js +1 -1
  27. package/dist/providers/anthropic/index.js.map +1 -1
  28. package/dist/providers/bedrock/index.cjs +1 -1
  29. package/dist/providers/bedrock/index.cjs.map +1 -1
  30. package/dist/providers/bedrock/index.js +1 -1
  31. package/dist/providers/bedrock/index.js.map +1 -1
  32. package/dist/providers/cerebras/index.cjs +1 -1
  33. package/dist/providers/cerebras/index.cjs.map +1 -1
  34. package/dist/providers/cerebras/index.js +1 -1
  35. package/dist/providers/cerebras/index.js.map +1 -1
  36. package/dist/providers/cohere/index.cjs +1 -1
  37. package/dist/providers/cohere/index.cjs.map +1 -1
  38. package/dist/providers/cohere/index.js +1 -1
  39. package/dist/providers/cohere/index.js.map +1 -1
  40. package/dist/providers/google/index.cjs +1 -1
  41. package/dist/providers/google/index.cjs.map +1 -1
  42. package/dist/providers/google/index.js +1 -1
  43. package/dist/providers/google/index.js.map +1 -1
  44. package/dist/providers/groq/index.cjs +1 -1
  45. package/dist/providers/groq/index.cjs.map +1 -1
  46. package/dist/providers/groq/index.js +1 -1
  47. package/dist/providers/groq/index.js.map +1 -1
  48. package/dist/providers/huggingface/index.cjs +1 -1
  49. package/dist/providers/huggingface/index.cjs.map +1 -1
  50. package/dist/providers/huggingface/index.js +1 -1
  51. package/dist/providers/huggingface/index.js.map +1 -1
  52. package/dist/providers/mistral/index.cjs +1 -1
  53. package/dist/providers/mistral/index.cjs.map +1 -1
  54. package/dist/providers/mistral/index.js +1 -1
  55. package/dist/providers/mistral/index.js.map +1 -1
  56. package/dist/providers/ollama/index.cjs +1 -1
  57. package/dist/providers/ollama/index.cjs.map +1 -1
  58. package/dist/providers/ollama/index.js +1 -1
  59. package/dist/providers/ollama/index.js.map +1 -1
  60. package/dist/providers/openai/index.cjs +1 -1
  61. package/dist/providers/openai/index.cjs.map +1 -1
  62. package/dist/providers/openai/index.js +1 -1
  63. package/dist/providers/openai/index.js.map +1 -1
  64. package/dist/providers/together/index.cjs +1 -1
  65. package/dist/providers/together/index.cjs.map +1 -1
  66. package/dist/providers/together/index.js +1 -1
  67. package/dist/providers/together/index.js.map +1 -1
  68. package/dist/providers/vercel-ai/index.cjs +1 -1
  69. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  70. package/dist/providers/vercel-ai/index.js +1 -1
  71. package/dist/providers/vercel-ai/index.js.map +1 -1
  72. package/package.json +1 -1
package/dist/index.d.cts CHANGED
@@ -301,7 +301,11 @@ interface RisicareConfig {
301
301
  serviceName?: string;
302
302
  /** Service version */
303
303
  serviceVersion?: string;
304
- /** Whether tracing is enabled (default: true if apiKey provided) */
304
+ /**
305
+ * Whether tracing is enabled (default: true if apiKey provided).
306
+ * With no API key tracing is always off, also with `enabled: true`,
307
+ * `RISICARE_TRACING=true` or `enable()`: the SDK sends nothing without a key.
308
+ */
305
309
  enabled?: boolean;
306
310
  /**
307
311
  * Whether prompt/completion content may leave the process.
@@ -511,9 +515,15 @@ declare function shutdown(timeoutMs?: number): Promise<void>;
511
515
  * - a span was discarded since the previous flush returned (F-SDKCB-001 §6);
512
516
  * - the backend rejected a span since the previous flush returned, or its ack
513
517
  * did not account for a span;
514
- * - it is called after a `shutdown()` that left spans undelivered
515
- * (`shutdown_residue`).
516
- * An uninitialised SDK returns `true`: it was handed nothing, and it lost nothing.
518
+ * - a `shutdown()` left spans undelivered (`shutdown_residue`) since the previous
519
+ * flush returned. That loss is reported once, as every other loss.
520
+ * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at
521
+ * SIGTERM / SIGINT, or one that nobody awaited) waits for it inside its own
522
+ * deadline, and then answers from the final tally with the same rule. So does a
523
+ * `flush()` after `shutdown()`. Through 0.8.0 both answered from the empty queue.
524
+ * Not active means not true: `flush()` returns `false` before `init()`, with tracing
525
+ * off (`enabled: false`, `RISICARE_TRACING=false`), and with no API key. Through
526
+ * 0.8.0 it returned `true` in those cases: nothing was queued.
517
527
  *
518
528
  * `flush()` never stops a request that is already sent. At the deadline it stops
519
529
  * waiting; the export in flight continues and ends by its own rules.
@@ -541,7 +551,9 @@ declare function enable(): void;
541
551
  */
542
552
  declare function disable(): void;
543
553
  /**
544
- * Check whether tracing is currently enabled.
554
+ * Check whether tracing is currently enabled. False before `init()`, with no API
555
+ * key (also with `RISICARE_TRACING=true`, `enabled: true` or `enable()`), with
556
+ * tracing off, and after `shutdown()` or the SDK's own drain at SIGTERM / SIGINT.
545
557
  */
546
558
  declare function isEnabled(): boolean;
547
559
  /**
@@ -660,9 +672,11 @@ declare function reportError(error: unknown, options?: {
660
672
  * the score name and the status or the error code. Later failures in the next
661
673
  * 10 s are counted, and the next WARNING gives their number. Root `flush()`
662
674
  * waits for pending scores inside its deadline, and returns `false` when a
663
- * score failed since the previous `flush()` returned. An out-of-range value, or an empty `traceId`
664
- * or `name`, writes one WARNING, and the SDK does not send the score. `true`
665
- * and `false` count as 1 and 0.
675
+ * score failed since the previous `flush()` returned. An out-of-range value, a
676
+ * value that is not a number, or an empty `traceId` or `name` writes one WARNING,
677
+ * and the SDK does not send the score. It counts as a failed score, so the next
678
+ * `flush()` is false (not when the SDK is not active: then nothing is counted).
679
+ * `true` and `false` count as 1 and 0.
666
680
  *
667
681
  * If a `mask` is configured on `init()`, `options.comment` is passed to it under
668
682
  * the key `score.comment` before the request is built. `traceId`, `spanId` and
package/dist/index.d.ts CHANGED
@@ -301,7 +301,11 @@ interface RisicareConfig {
301
301
  serviceName?: string;
302
302
  /** Service version */
303
303
  serviceVersion?: string;
304
- /** Whether tracing is enabled (default: true if apiKey provided) */
304
+ /**
305
+ * Whether tracing is enabled (default: true if apiKey provided).
306
+ * With no API key tracing is always off, also with `enabled: true`,
307
+ * `RISICARE_TRACING=true` or `enable()`: the SDK sends nothing without a key.
308
+ */
305
309
  enabled?: boolean;
306
310
  /**
307
311
  * Whether prompt/completion content may leave the process.
@@ -511,9 +515,15 @@ declare function shutdown(timeoutMs?: number): Promise<void>;
511
515
  * - a span was discarded since the previous flush returned (F-SDKCB-001 §6);
512
516
  * - the backend rejected a span since the previous flush returned, or its ack
513
517
  * did not account for a span;
514
- * - it is called after a `shutdown()` that left spans undelivered
515
- * (`shutdown_residue`).
516
- * An uninitialised SDK returns `true`: it was handed nothing, and it lost nothing.
518
+ * - a `shutdown()` left spans undelivered (`shutdown_residue`) since the previous
519
+ * flush returned. That loss is reported once, as every other loss.
520
+ * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at
521
+ * SIGTERM / SIGINT, or one that nobody awaited) waits for it inside its own
522
+ * deadline, and then answers from the final tally with the same rule. So does a
523
+ * `flush()` after `shutdown()`. Through 0.8.0 both answered from the empty queue.
524
+ * Not active means not true: `flush()` returns `false` before `init()`, with tracing
525
+ * off (`enabled: false`, `RISICARE_TRACING=false`), and with no API key. Through
526
+ * 0.8.0 it returned `true` in those cases: nothing was queued.
517
527
  *
518
528
  * `flush()` never stops a request that is already sent. At the deadline it stops
519
529
  * waiting; the export in flight continues and ends by its own rules.
@@ -541,7 +551,9 @@ declare function enable(): void;
541
551
  */
542
552
  declare function disable(): void;
543
553
  /**
544
- * Check whether tracing is currently enabled.
554
+ * Check whether tracing is currently enabled. False before `init()`, with no API
555
+ * key (also with `RISICARE_TRACING=true`, `enabled: true` or `enable()`), with
556
+ * tracing off, and after `shutdown()` or the SDK's own drain at SIGTERM / SIGINT.
545
557
  */
546
558
  declare function isEnabled(): boolean;
547
559
  /**
@@ -660,9 +672,11 @@ declare function reportError(error: unknown, options?: {
660
672
  * the score name and the status or the error code. Later failures in the next
661
673
  * 10 s are counted, and the next WARNING gives their number. Root `flush()`
662
674
  * waits for pending scores inside its deadline, and returns `false` when a
663
- * score failed since the previous `flush()` returned. An out-of-range value, or an empty `traceId`
664
- * or `name`, writes one WARNING, and the SDK does not send the score. `true`
665
- * and `false` count as 1 and 0.
675
+ * score failed since the previous `flush()` returned. An out-of-range value, a
676
+ * value that is not a number, or an empty `traceId` or `name` writes one WARNING,
677
+ * and the SDK does not send the score. It counts as a failed score, so the next
678
+ * `flush()` is false (not when the SDK is not active: then nothing is counted).
679
+ * `true` and `false` count as 1 and 0.
666
680
  *
667
681
  * If a `mask` is configured on `init()`, `options.comment` is passed to it under
668
682
  * the key `score.comment` before the request is built. `traceId`, `spanId` and
package/dist/index.js CHANGED
@@ -541,6 +541,18 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
541
541
  _started = false;
542
542
  _flushing = false;
543
543
  _inFlight = null;
544
+ /**
545
+ * The `shutdown()` that runs, or ran. A second `shutdown()` returns it, and a
546
+ * `flush()` that comes while it runs waits for it (inside its own deadline).
547
+ */
548
+ _closing = null;
549
+ /**
550
+ * True from the start of the drain of `shutdown()` until its loop ends and the
551
+ * residue is counted (no `await` between those two points). A span that ends
552
+ * in this time joins the drain. After it, the processor can take no span.
553
+ */
554
+ _drainOpen = false;
555
+ _lateSpanWarned = false;
544
556
  _beforeExitHandler = null;
545
557
  // Retry tracking for failed batches (Audit #5)
546
558
  _retryCounts = /* @__PURE__ */ new Map();
@@ -686,13 +698,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
686
698
  * Limit: the abort does not stop a TLS handshake that stalls. Measured, such a
687
699
  * handshake kept the process alive about 10 s after `shutdown()` returned.
688
700
  *
701
+ * A second call, while the first runs or after it ended, returns the promise
702
+ * of the first one. It does not return before the first drain ends.
703
+ *
689
704
  * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
690
705
  * the values that are not a finite number.
691
706
  */
692
- async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
693
- if (!this._started) return;
707
+ shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
708
+ if (!this._started) return this._closing ?? Promise.resolve();
709
+ this._closing = this._shutdown(timeoutMs);
710
+ return this._closing;
711
+ }
712
+ async _shutdown(timeoutMs) {
694
713
  timeoutMs = normalizeTimeoutMs(timeoutMs);
695
714
  this._started = false;
715
+ this._drainOpen = true;
696
716
  if (this._timer) {
697
717
  clearInterval(this._timer);
698
718
  this._timer = null;
@@ -717,6 +737,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
717
737
  break;
718
738
  }
719
739
  }
740
+ this._drainOpen = false;
720
741
  const queued = this._queue.length;
721
742
  const flight = this._inFlight;
722
743
  const inFlight = flight !== null && !flight.abandoned ? flight.size : 0;
@@ -747,7 +768,14 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
747
768
  );
748
769
  }
749
770
  onSpanEnd(span) {
750
- if (!this._started) return;
771
+ if (!this._started) {
772
+ if (this._drainOpen) this._enqueue(span, false);
773
+ else if (this._closing !== null) this._lateSpan();
774
+ return;
775
+ }
776
+ this._enqueue(span, true);
777
+ }
778
+ _enqueue(span, exportAtBatchSize) {
751
779
  if (this._queue.length >= this._maxQueueSize) {
752
780
  this._recordDropped("queue_full");
753
781
  if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
@@ -756,10 +784,19 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
756
784
  return;
757
785
  }
758
786
  this._queue.push(span);
759
- if (this._queue.length >= this._batchSize) {
787
+ if (exportAtBatchSize && this._queue.length >= this._batchSize) {
760
788
  void this._exportBatch();
761
789
  }
762
790
  }
791
+ /** A span that ended after the drain ended: counted, with one WARNING for the first. */
792
+ _lateSpan() {
793
+ this._recordDropped("shutdown_residue");
794
+ if (this._lateSpanWarned) return;
795
+ this._lateSpanWarned = true;
796
+ warn(
797
+ "a span ended after shutdown() had stopped taking spans (reason=shutdown_residue). It was not delivered, and it is counted as dropped. Later spans of this kind are counted without a WARNING."
798
+ );
799
+ }
763
800
  /**
764
801
  * Flush pending spans.
765
802
  *
@@ -789,12 +826,22 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
789
826
  * loss. The flush after that answers `true` when nothing new was lost.
790
827
  *
791
828
  * Returns `false` in these cases:
792
- * (a) the deadline expires with spans still queued or in flight;
829
+ * (a) the deadline expires with spans still queued or in flight, or while a
830
+ * `shutdown()` that it waits for still runs;
793
831
  * (b) a span was discarded since the previous flush returned: queue full,
794
- * breaker refusal, retry exhaustion, or an ack that did not account
795
- * for it or a span that could not be serialized (`unacknowledged`);
796
- * (c) the backend rejected a span since the previous flush returned;
797
- * (d) it is called after `shutdown()`, and the shutdown residue was not 0.
832
+ * breaker refusal, retry exhaustion, spans that `shutdown()` left
833
+ * (`shutdown_residue`), or an ack that did not account for it or a span
834
+ * that could not be serialized (`unacknowledged`);
835
+ * (c) the backend rejected a span since the previous flush returned.
836
+ *
837
+ * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at
838
+ * SIGTERM or SIGINT, or a `shutdown()` that nobody awaited) waits for that
839
+ * shutdown, inside its OWN deadline, and then answers from the final tally with
840
+ * the same loss mark. After `shutdown()` it answers from the final tally in the
841
+ * same way. Through 0.8.0 both answered from the empty queue: true in 0 ms,
842
+ * with the batch in flight, and true after a rejection or a `transport_refused`
843
+ * drop. A loss that `shutdown()` counts (also `shutdown_residue`) makes ONE
844
+ * `flush()` false, as every other loss does.
798
845
  *
799
846
  * The deadline is a hard wall-clock bound on the WAIT. At the deadline
800
847
  * `flush()` returns `false`. Through 0.7.1 the deadline was checked only
@@ -817,9 +864,6 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
817
864
  */
818
865
  async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
819
866
  timeoutMs = normalizeTimeoutMs(timeoutMs);
820
- if (!this._started) {
821
- return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
822
- }
823
867
  const deadline = Date.now() + timeoutMs;
824
868
  const mark = this._lossMark;
825
869
  const finish = (settled) => {
@@ -827,6 +871,14 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
827
871
  this._lossMark = Math.max(this._lossMark, lost);
828
872
  return settled && lost === mark;
829
873
  };
874
+ if (!this._started) {
875
+ if (this._closing !== null) {
876
+ const closed = await raceDeadline(this._closing.catch(() => void 0), timeoutMs);
877
+ if (closed === DEADLINE) return finish(false);
878
+ }
879
+ const held = this._inFlight !== null && !this._inFlight.abandoned;
880
+ return finish(this._queue.length === 0 && !held);
881
+ }
830
882
  while (this._queue.length > 0 || this._flushing) {
831
883
  const remaining = deadline - Date.now();
832
884
  if (remaining <= 0) return finish(false);
@@ -1031,7 +1083,7 @@ function resolveEndpoints(endpointOption, apiEndpointOption, envEndpoint, envApi
1031
1083
  }
1032
1084
  function resolveConfig(config) {
1033
1085
  const env = process.env;
1034
- const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
1086
+ const apiKey = keyText(config?.apiKey) || keyText(env.RISICARE_API_KEY) || void 0;
1035
1087
  const { endpoint, apiEndpoint } = resolveEndpoints(
1036
1088
  config?.endpoint,
1037
1089
  config?.apiEndpoint,
@@ -1073,6 +1125,7 @@ function resolveConfig(config) {
1073
1125
  } else {
1074
1126
  enabled = !!apiKey;
1075
1127
  }
1128
+ if (!apiKey) enabled = false;
1076
1129
  return hideKeyFromInspect({
1077
1130
  apiKey: apiKey ?? "",
1078
1131
  endpoint,
@@ -1123,6 +1176,14 @@ function tracingFromEnv(value) {
1123
1176
  );
1124
1177
  return false;
1125
1178
  }
1179
+ function keyText(value) {
1180
+ return typeof value === "string" ? value.trim() : "";
1181
+ }
1182
+ function tracingTurnedOff(config) {
1183
+ if (config?.enabled !== void 0) return config.enabled === false;
1184
+ const v = (process.env.RISICARE_TRACING ?? "").trim().toLowerCase();
1185
+ return v !== "" && !TRACING_ON.has(v);
1186
+ }
1126
1187
  function parseNumericEnv(value, defaultValue) {
1127
1188
  if (value === void 0) return defaultValue;
1128
1189
  const n = Number(value);
@@ -2243,7 +2304,7 @@ function markCancel(span, error) {
2243
2304
  }
2244
2305
 
2245
2306
  // src/version.ts
2246
- var SDK_VERSION = "0.8.0";
2307
+ var SDK_VERSION = "0.9.0";
2247
2308
 
2248
2309
  // src/exporters/http.ts
2249
2310
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
@@ -2681,27 +2742,6 @@ async function checkAck(response, spansSent, scrub) {
2681
2742
  return { result: "success" /* SUCCESS */, counts, final: false };
2682
2743
  }
2683
2744
 
2684
- // src/exporters/console.ts
2685
- var ConsoleExporter = class {
2686
- name = "console";
2687
- /**
2688
- * It only shows spans locally, so its success is not a delivery. When another
2689
- * exporter is present, the batch processor ignores this exporter's result.
2690
- */
2691
- countsAsDelivery = false;
2692
- export(spans) {
2693
- for (const span of spans) {
2694
- const payload = span.toPayload();
2695
- const line = JSON.stringify(payload);
2696
- process.stderr.write(`[risicare] ${line}
2697
- `);
2698
- }
2699
- return "success" /* SUCCESS */;
2700
- }
2701
- shutdown() {
2702
- }
2703
- };
2704
-
2705
2745
  // src/utils/stream-proxy.ts
2706
2746
  function endOpenProviderSpans() {
2707
2747
  let open;
@@ -3894,6 +3934,8 @@ var TERMINATING_SIGNALS = [
3894
3934
  ];
3895
3935
  var BACKSTOP_MARGIN_MS = 500;
3896
3936
  var _finalMetrics;
3937
+ var _finalProcessor;
3938
+ var _finalActive = false;
3897
3939
  var SCORE_TIMEOUT_MS = 2e3;
3898
3940
  var _pendingScores = /* @__PURE__ */ new Set();
3899
3941
  var _failedScores = 0;
@@ -3974,6 +4016,13 @@ var RisicareClient = class {
3974
4016
  * this flag `getMetrics()` would keep reporting `"running"` over a processor
3975
4017
  * that has already been torn down. */
3976
4018
  isShutdown = false;
4019
+ /**
4020
+ * Tracing was on at `init()` or since `enable()`. A client that never was
4021
+ * (no key, or tracing off) accepted nothing, and delivered nothing: its
4022
+ * `flush()` is false. `disable()` does not clear it: spans that were accepted
4023
+ * before keep their answer.
4024
+ */
4025
+ _activated = false;
3977
4026
  _shutdownPromise;
3978
4027
  _shutdownHandlers = [];
3979
4028
  constructor(config) {
@@ -3984,16 +4033,13 @@ var RisicareClient = class {
3984
4033
  'the API key does not look like a Risicare key: it should start with "rsk-", "rski_" or "rsks_". Tracing continues with this key.'
3985
4034
  );
3986
4035
  }
3987
- const tracingSetExplicitly = config?.enabled !== void 0 || (process.env.RISICARE_TRACING ?? "").trim() !== "";
3988
- if (!this.config.apiKey && !this.config.enabled && !tracingSetExplicitly) {
4036
+ if (!this.config.apiKey && !tracingTurnedOff(config)) {
3989
4037
  warn(
3990
- "Risicare found no API key. Tracing is off and the SDK sends no span. Pass apiKey to init() or set RISICARE_API_KEY."
4038
+ "Risicare found no API key. Nothing is sent to Risicare: tracing is off, no span is created, and flush() returns false. Set the RISICARE_API_KEY environment variable, or pass apiKey to init()."
3991
4039
  );
3992
4040
  }
3993
4041
  let exporter;
3994
- if (this.config.debug && !this.config.apiKey) {
3995
- exporter = new ConsoleExporter();
3996
- } else if (this.config.apiKey) {
4042
+ if (this.config.apiKey) {
3997
4043
  exporter = new HttpExporter({
3998
4044
  endpoint: this.config.endpoint,
3999
4045
  apiKey: this.config.apiKey,
@@ -4001,16 +4047,6 @@ var RisicareClient = class {
4001
4047
  environment: this.config.environment || void 0,
4002
4048
  compress: this.config.compress
4003
4049
  });
4004
- } else {
4005
- exporter = void 0;
4006
- if (this.config.enabled) {
4007
- try {
4008
- console.warn(
4009
- `[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.`
4010
- );
4011
- } catch {
4012
- }
4013
- }
4014
4050
  }
4015
4051
  this.processor = new BatchSpanProcessor({
4016
4052
  exporters: exporter ? [exporter] : [],
@@ -4041,6 +4077,7 @@ var RisicareClient = class {
4041
4077
  serviceName: this.config.serviceName,
4042
4078
  serviceVersion: this.config.serviceVersion
4043
4079
  });
4080
+ this._activated = this.tracer.enabled;
4044
4081
  this.processor.start();
4045
4082
  if (this.config.apiKey && this.config.enabled && this.config.fixRuntime) {
4046
4083
  try {
@@ -4079,7 +4116,12 @@ var RisicareClient = class {
4079
4116
  return this.tracer.enabled;
4080
4117
  }
4081
4118
  set enabled(value) {
4119
+ if (value && !this.config.apiKey) {
4120
+ debug("enable() ignored: no API key is configured, so tracing stays off");
4121
+ return;
4122
+ }
4082
4123
  this.tracer.enabled = value;
4124
+ if (value) this._activated = true;
4083
4125
  }
4084
4126
  // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)
4085
4127
  async shutdown(timeoutMs) {
@@ -4098,6 +4140,8 @@ var RisicareClient = class {
4098
4140
  _failWaitingScores(SCORE_DEADLINE_REASON);
4099
4141
  this.isShutdown = true;
4100
4142
  _finalMetrics = this.processor.getMetrics();
4143
+ _finalProcessor = this.processor;
4144
+ _finalActive = this._activated;
4101
4145
  }
4102
4146
  /**
4103
4147
  * Flush pending spans.
@@ -4111,6 +4155,7 @@ var RisicareClient = class {
4111
4155
  * *discarded*.
4112
4156
  */
4113
4157
  async flush(timeoutMs) {
4158
+ if (!this._activated) return false;
4114
4159
  return this.processor.flush(timeoutMs);
4115
4160
  }
4116
4161
  /**
@@ -4137,6 +4182,19 @@ var RisicareClient = class {
4137
4182
  * * **A prior listener exists.** The application took ownership before the
4138
4183
  * SDK loaded. We drain and RETURN; termination was never ours to decide,
4139
4184
  * and forcing it would cut off the app's own graceful shutdown.
4185
+ * * **A listener that the application adds after `init()`.** Node calls ours
4186
+ * first. The question is asked when OUR listener starts, at signal time:
4187
+ * is there another listener for this signal? If there is, it owns
4188
+ * termination as well: when the drain ends we do not raise the signal
4189
+ * again, and we do not arm the fail-safe exit. Its listener runs once and
4190
+ * decides the exit, in the same way as when it was registered before
4191
+ * `init()`. Through 0.8.0 the re-raise ran it a second time, and the
4192
+ * fail-safe ended the process with code 143, 100 ms later.
4193
+ * * **A listener that the application adds DURING the drain.** There was none
4194
+ * at signal time, so the 0.8.0 rule holds: after the drain we raise the
4195
+ * signal again, and that listener runs on it, and the process ends (fail-safe
4196
+ * after 100 ms if it does not). A count taken after the drain would have
4197
+ * counted that listener, and nothing would have run or ended the process.
4140
4198
  *
4141
4199
  * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
4142
4200
  * carries no termination the SDK could displace — the loop has already
@@ -4152,6 +4210,7 @@ var RisicareClient = class {
4152
4210
  for (const [signal, signum] of TERMINATING_SIGNALS) {
4153
4211
  const weDisplacedDefault = process.listenerCount(signal) === 0;
4154
4212
  const handler = () => {
4213
+ const othersAtSignal = process.listeners(signal).filter((l) => l !== handler).length;
4155
4214
  const backstop = setTimeout(
4156
4215
  () => process.exit(128 + signum),
4157
4216
  SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
@@ -4161,6 +4220,7 @@ var RisicareClient = class {
4161
4220
  }).finally(() => {
4162
4221
  clearTimeout(backstop);
4163
4222
  if (!weDisplacedDefault) return;
4223
+ if (othersAtSignal > 0) return;
4164
4224
  try {
4165
4225
  process.kill(process.pid, signal);
4166
4226
  } catch {
@@ -4209,6 +4269,8 @@ function init(config) {
4209
4269
  return;
4210
4270
  }
4211
4271
  _finalMetrics = void 0;
4272
+ _finalProcessor = void 0;
4273
+ _finalActive = false;
4212
4274
  _resetScoreFailures();
4213
4275
  const client = new RisicareClient(config);
4214
4276
  setClient(client);
@@ -4231,10 +4293,12 @@ async function flush(timeoutMs) {
4231
4293
  const scoreMark = _failedScoresFlushMark;
4232
4294
  const client = getClient();
4233
4295
  let spansOk;
4234
- if (!client) {
4235
- spansOk = (_finalMetrics?.droppedSpansByReason.shutdown_residue ?? 0) === 0;
4236
- } else {
4296
+ if (client) {
4237
4297
  spansOk = await client.flush(timeoutMs);
4298
+ } else if (_finalProcessor) {
4299
+ spansOk = _finalActive && await _finalProcessor.flush(timeoutMs);
4300
+ } else {
4301
+ spansOk = false;
4238
4302
  }
4239
4303
  const scoresDone = await _waitForPendingScores(deadline - Date.now());
4240
4304
  if (!scoresDone) _failWaitingScores(SCORE_DEADLINE_REASON);
@@ -4253,7 +4317,7 @@ function disable() {
4253
4317
  }
4254
4318
  function isEnabled() {
4255
4319
  const client = getClient();
4256
- return client?.enabled ?? false;
4320
+ return client !== void 0 && !client.isShutdown && client.enabled;
4257
4321
  }
4258
4322
  function getTracer2() {
4259
4323
  return getTracer();
@@ -4272,10 +4336,11 @@ function getMetrics() {
4272
4336
  };
4273
4337
  }
4274
4338
  if (_finalMetrics) {
4339
+ const tally = _finalProcessor?.getMetrics() ?? _finalMetrics;
4275
4340
  return {
4276
- ..._finalMetrics,
4341
+ ...tally,
4277
4342
  failedScores: _failedScores,
4278
- droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
4343
+ droppedSpansByReason: { ...tally.droppedSpansByReason },
4279
4344
  sdkState: "shutdown"
4280
4345
  };
4281
4346
  }
@@ -4347,24 +4412,29 @@ function reportError(error, options) {
4347
4412
  debug("reportError failed");
4348
4413
  }
4349
4414
  }
4415
+ function refuseScore(message) {
4416
+ warn(message);
4417
+ const client = getClient();
4418
+ if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;
4419
+ }
4350
4420
  function score(traceId, name, value, options) {
4351
4421
  try {
4352
4422
  const raw = value;
4353
4423
  if (typeof raw === "boolean") value = raw ? 1 : 0;
4354
4424
  if (typeof value !== "number") {
4355
- warn(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4425
+ refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4356
4426
  return;
4357
4427
  }
4358
4428
  if (!Number.isFinite(value) || value < 0 || value > 1) {
4359
- warn(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
4429
+ refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
4360
4430
  return;
4361
4431
  }
4362
4432
  if (typeof traceId !== "string" || given(traceId) === void 0) {
4363
- warn("score: traceId must be a non-empty string. The SDK does not send this score.");
4433
+ refuseScore("score: traceId must be a non-empty string. The SDK does not send this score.");
4364
4434
  return;
4365
4435
  }
4366
4436
  if (typeof name !== "string" || given(name) === void 0) {
4367
- warn("score: name must be a non-empty string. The SDK does not send this score.");
4437
+ refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
4368
4438
  return;
4369
4439
  }
4370
4440
  const client = getClient();