risicare 0.8.0 → 0.9.1

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 +98 -21
  2. package/dist/frameworks/instructor.cjs +144 -2
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +144 -2
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +144 -2
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.js +144 -2
  9. package/dist/frameworks/langchain.js.map +1 -1
  10. package/dist/frameworks/langgraph.cjs +144 -2
  11. package/dist/frameworks/langgraph.cjs.map +1 -1
  12. package/dist/frameworks/langgraph.js +144 -2
  13. package/dist/frameworks/langgraph.js.map +1 -1
  14. package/dist/frameworks/llamaindex.cjs +144 -2
  15. package/dist/frameworks/llamaindex.cjs.map +1 -1
  16. package/dist/frameworks/llamaindex.js +144 -2
  17. package/dist/frameworks/llamaindex.js.map +1 -1
  18. package/dist/index.cjs +329 -67
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +29 -9
  21. package/dist/index.d.ts +29 -9
  22. package/dist/index.js +329 -67
  23. package/dist/index.js.map +1 -1
  24. package/dist/providers/anthropic/index.cjs +144 -2
  25. package/dist/providers/anthropic/index.cjs.map +1 -1
  26. package/dist/providers/anthropic/index.js +144 -2
  27. package/dist/providers/anthropic/index.js.map +1 -1
  28. package/dist/providers/bedrock/index.cjs +144 -2
  29. package/dist/providers/bedrock/index.cjs.map +1 -1
  30. package/dist/providers/bedrock/index.js +144 -2
  31. package/dist/providers/bedrock/index.js.map +1 -1
  32. package/dist/providers/cerebras/index.cjs +144 -2
  33. package/dist/providers/cerebras/index.cjs.map +1 -1
  34. package/dist/providers/cerebras/index.js +144 -2
  35. package/dist/providers/cerebras/index.js.map +1 -1
  36. package/dist/providers/cohere/index.cjs +144 -2
  37. package/dist/providers/cohere/index.cjs.map +1 -1
  38. package/dist/providers/cohere/index.js +144 -2
  39. package/dist/providers/cohere/index.js.map +1 -1
  40. package/dist/providers/google/index.cjs +144 -2
  41. package/dist/providers/google/index.cjs.map +1 -1
  42. package/dist/providers/google/index.js +144 -2
  43. package/dist/providers/google/index.js.map +1 -1
  44. package/dist/providers/groq/index.cjs +144 -2
  45. package/dist/providers/groq/index.cjs.map +1 -1
  46. package/dist/providers/groq/index.js +144 -2
  47. package/dist/providers/groq/index.js.map +1 -1
  48. package/dist/providers/huggingface/index.cjs +144 -2
  49. package/dist/providers/huggingface/index.cjs.map +1 -1
  50. package/dist/providers/huggingface/index.js +144 -2
  51. package/dist/providers/huggingface/index.js.map +1 -1
  52. package/dist/providers/mistral/index.cjs +144 -2
  53. package/dist/providers/mistral/index.cjs.map +1 -1
  54. package/dist/providers/mistral/index.js +144 -2
  55. package/dist/providers/mistral/index.js.map +1 -1
  56. package/dist/providers/ollama/index.cjs +144 -2
  57. package/dist/providers/ollama/index.cjs.map +1 -1
  58. package/dist/providers/ollama/index.js +144 -2
  59. package/dist/providers/ollama/index.js.map +1 -1
  60. package/dist/providers/openai/index.cjs +144 -2
  61. package/dist/providers/openai/index.cjs.map +1 -1
  62. package/dist/providers/openai/index.js +144 -2
  63. package/dist/providers/openai/index.js.map +1 -1
  64. package/dist/providers/together/index.cjs +144 -2
  65. package/dist/providers/together/index.cjs.map +1 -1
  66. package/dist/providers/together/index.js +144 -2
  67. package/dist/providers/together/index.js.map +1 -1
  68. package/dist/providers/vercel-ai/index.cjs +144 -2
  69. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  70. package/dist/providers/vercel-ai/index.js +144 -2
  71. package/dist/providers/vercel-ai/index.js.map +1 -1
  72. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -86,6 +86,10 @@ function warn(msg) {
86
86
  process.stderr.write(`[risicare] WARNING: ${msg}
87
87
  `);
88
88
  }
89
+ function info(msg) {
90
+ process.stderr.write(`[risicare] INFO: ${msg}
91
+ `);
92
+ }
89
93
 
90
94
  // src/utils/text.ts
91
95
  function cutCodePoints(text, max) {
@@ -541,6 +545,18 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
541
545
  _started = false;
542
546
  _flushing = false;
543
547
  _inFlight = null;
548
+ /**
549
+ * The `shutdown()` that runs, or ran. A second `shutdown()` returns it, and a
550
+ * `flush()` that comes while it runs waits for it (inside its own deadline).
551
+ */
552
+ _closing = null;
553
+ /**
554
+ * True from the start of the drain of `shutdown()` until its loop ends and the
555
+ * residue is counted (no `await` between those two points). A span that ends
556
+ * in this time joins the drain. After it, the processor can take no span.
557
+ */
558
+ _drainOpen = false;
559
+ _lateSpanWarned = false;
544
560
  _beforeExitHandler = null;
545
561
  // Retry tracking for failed batches (Audit #5)
546
562
  _retryCounts = /* @__PURE__ */ new Map();
@@ -574,7 +590,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
574
590
  queue_full: 0,
575
591
  transport_refused: 0,
576
592
  shutdown_residue: 0,
577
- unacknowledged: 0
593
+ unacknowledged: 0,
594
+ quota_exceeded: 0
578
595
  };
579
596
  exportedSpans = 0;
580
597
  /**
@@ -686,13 +703,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
686
703
  * Limit: the abort does not stop a TLS handshake that stalls. Measured, such a
687
704
  * handshake kept the process alive about 10 s after `shutdown()` returned.
688
705
  *
706
+ * A second call, while the first runs or after it ended, returns the promise
707
+ * of the first one. It does not return before the first drain ends.
708
+ *
689
709
  * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
690
710
  * the values that are not a finite number.
691
711
  */
692
- async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
693
- if (!this._started) return;
712
+ shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
713
+ if (!this._started) return this._closing ?? Promise.resolve();
714
+ this._closing = this._shutdown(timeoutMs);
715
+ return this._closing;
716
+ }
717
+ async _shutdown(timeoutMs) {
694
718
  timeoutMs = normalizeTimeoutMs(timeoutMs);
695
719
  this._started = false;
720
+ this._drainOpen = true;
696
721
  if (this._timer) {
697
722
  clearInterval(this._timer);
698
723
  this._timer = null;
@@ -717,6 +742,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
717
742
  break;
718
743
  }
719
744
  }
745
+ this._drainOpen = false;
720
746
  const queued = this._queue.length;
721
747
  const flight = this._inFlight;
722
748
  const inFlight = flight !== null && !flight.abandoned ? flight.size : 0;
@@ -734,9 +760,15 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
734
760
  if (residue > 0) {
735
761
  this._queue.length = 0;
736
762
  this._recordDropped("shutdown_residue", residue);
737
- warn(
738
- `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${inFlight} in an export that shutdown() stopped. ` + (inFlight > 0 ? `The server may have received the ${inFlight} span(s) of the stopped export. ` : "") + `All ${residue} were not confirmed as delivered, and are counted as dropped. The ${timeoutMs} ms shutdown budget expired or the transport stopped accepting. Pass a larger timeout to shutdown(timeoutMs), or raise your container's termination grace period, to lose less.`
739
- );
763
+ if (this._quotaPaused()) {
764
+ warn(
765
+ `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${inFlight} in an export that shutdown() stopped. The monthly event quota is used up and export is paused until the next probe, so these spans could not be sent. A longer shutdown timeout does not help. Upgrade the plan or wait for the quota to reset.`
766
+ );
767
+ } else {
768
+ warn(
769
+ `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.`
770
+ );
771
+ }
740
772
  }
741
773
  for (const exporter of this._exporters) {
742
774
  await shutdownExporter(exporter, Math.max(0, shutdownDeadline - Date.now()));
@@ -747,8 +779,28 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
747
779
  );
748
780
  }
749
781
  onSpanEnd(span) {
750
- if (!this._started) return;
782
+ if (!this._started) {
783
+ if (this._drainOpen) this._enqueue(span, false);
784
+ else if (this._closing !== null) this._lateSpan();
785
+ return;
786
+ }
787
+ this._enqueue(span, true);
788
+ }
789
+ _enqueue(span, exportAtBatchSize) {
751
790
  if (this._queue.length >= this._maxQueueSize) {
791
+ if (this._quotaPaused()) {
792
+ const oldest = this._queue.shift();
793
+ if (oldest !== void 0) this._retryCounts.delete(oldest.spanId);
794
+ this._recordDropped("quota_exceeded");
795
+ for (const exporter of this._exporters) {
796
+ try {
797
+ exporter.noteQuotaDrop?.(1);
798
+ } catch {
799
+ }
800
+ }
801
+ this._queue.push(span);
802
+ return;
803
+ }
752
804
  this._recordDropped("queue_full");
753
805
  if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
754
806
  warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
@@ -756,10 +808,35 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
756
808
  return;
757
809
  }
758
810
  this._queue.push(span);
759
- if (this._queue.length >= this._batchSize) {
811
+ if (exportAtBatchSize && this._queue.length >= this._batchSize) {
760
812
  void this._exportBatch();
761
813
  }
762
814
  }
815
+ /**
816
+ * True when every exporter that delivers is paused for the monthly quota (S-1). An exporter
817
+ * says so with `quotaPaused()`. A custom exporter has none: not paused.
818
+ */
819
+ _quotaPaused() {
820
+ const deciders = this._exporters.filter((e) => e.countsAsDelivery !== false);
821
+ if (deciders.length === 0) return false;
822
+ for (const exporter of deciders) {
823
+ try {
824
+ if (exporter.quotaPaused?.() !== true) return false;
825
+ } catch {
826
+ return false;
827
+ }
828
+ }
829
+ return true;
830
+ }
831
+ /** A span that ended after the drain ended: counted, with one WARNING for the first. */
832
+ _lateSpan() {
833
+ this._recordDropped("shutdown_residue");
834
+ if (this._lateSpanWarned) return;
835
+ this._lateSpanWarned = true;
836
+ warn(
837
+ "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."
838
+ );
839
+ }
763
840
  /**
764
841
  * Flush pending spans.
765
842
  *
@@ -789,12 +866,22 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
789
866
  * loss. The flush after that answers `true` when nothing new was lost.
790
867
  *
791
868
  * Returns `false` in these cases:
792
- * (a) the deadline expires with spans still queued or in flight;
869
+ * (a) the deadline expires with spans still queued or in flight, or while a
870
+ * `shutdown()` that it waits for still runs;
793
871
  * (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.
872
+ * breaker refusal, retry exhaustion, spans that `shutdown()` left
873
+ * (`shutdown_residue`), or an ack that did not account for it or a span
874
+ * that could not be serialized (`unacknowledged`);
875
+ * (c) the backend rejected a span since the previous flush returned.
876
+ *
877
+ * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at
878
+ * SIGTERM or SIGINT, or a `shutdown()` that nobody awaited) waits for that
879
+ * shutdown, inside its OWN deadline, and then answers from the final tally with
880
+ * the same loss mark. After `shutdown()` it answers from the final tally in the
881
+ * same way. Through 0.8.0 both answered from the empty queue: true in 0 ms,
882
+ * with the batch in flight, and true after a rejection or a `transport_refused`
883
+ * drop. A loss that `shutdown()` counts (also `shutdown_residue`) makes ONE
884
+ * `flush()` false, as every other loss does.
798
885
  *
799
886
  * The deadline is a hard wall-clock bound on the WAIT. At the deadline
800
887
  * `flush()` returns `false`. Through 0.7.1 the deadline was checked only
@@ -817,9 +904,6 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
817
904
  */
818
905
  async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
819
906
  timeoutMs = normalizeTimeoutMs(timeoutMs);
820
- if (!this._started) {
821
- return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
822
- }
823
907
  const deadline = Date.now() + timeoutMs;
824
908
  const mark = this._lossMark;
825
909
  const finish = (settled) => {
@@ -827,12 +911,22 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
827
911
  this._lossMark = Math.max(this._lossMark, lost);
828
912
  return settled && lost === mark;
829
913
  };
914
+ if (!this._started) {
915
+ if (this._closing !== null) {
916
+ const closed = await raceDeadline(this._closing.catch(() => void 0), timeoutMs);
917
+ if (closed === DEADLINE) return finish(false);
918
+ }
919
+ const held = this._inFlight !== null && !this._inFlight.abandoned;
920
+ return finish(this._queue.length === 0 && !held);
921
+ }
830
922
  while (this._queue.length > 0 || this._flushing) {
831
923
  const remaining = deadline - Date.now();
832
924
  if (remaining <= 0) return finish(false);
925
+ if (!this._flushing && this._queue.length > 0 && this._quotaPaused()) return finish(false);
833
926
  if (!this._flushing && this._queue.length > 0) {
834
927
  const outcome = await raceDeadline(this._exportBatch(), remaining);
835
928
  if (outcome === DEADLINE) return finish(false);
929
+ if (outcome === 4 /* Paused */) await new Promise((r) => setTimeout(r, 20));
836
930
  } else {
837
931
  await new Promise((r) => setTimeout(r, 1));
838
932
  }
@@ -845,6 +939,9 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
845
939
  rejectedSpans: this.rejectedSpans,
846
940
  droppedSpans: this.droppedSpans,
847
941
  droppedSpansByReason: { ...this.droppedSpansByReason },
942
+ // Spans dropped because the monthly event quota is used up (S-1). The same number as
943
+ // `droppedSpansByReason.quota_exceeded`, for a reader that wants one key.
944
+ droppedQuota: this.droppedSpansByReason.quota_exceeded,
848
945
  failedExports: this.failedExports,
849
946
  maskErrors: this.maskErrors,
850
947
  queueSize: this._queue.length,
@@ -866,6 +963,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
866
963
  this.exportedSpans += n;
867
964
  return;
868
965
  }
966
+ const quota = Math.min(Math.max(ack.quotaDropped ?? 0, 0), n);
967
+ if (quota > 0) {
968
+ this._recordDropped("quota_exceeded", quota);
969
+ n -= quota;
970
+ if (n === 0) return;
971
+ }
869
972
  const rejected = Math.min(ack.rejected, n);
870
973
  const accepted = Math.min(ack.accepted, n - rejected);
871
974
  const unacknowledged = n - accepted - rejected;
@@ -900,6 +1003,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
900
1003
  async _exportBatch() {
901
1004
  if (this._flushing) return 3 /* Busy */;
902
1005
  if (this._queue.length === 0) return 0 /* Empty */;
1006
+ if (this._quotaPaused()) return 4 /* Paused */;
903
1007
  this._flushing = true;
904
1008
  let flight = null;
905
1009
  try {
@@ -1031,7 +1135,7 @@ function resolveEndpoints(endpointOption, apiEndpointOption, envEndpoint, envApi
1031
1135
  }
1032
1136
  function resolveConfig(config) {
1033
1137
  const env = process.env;
1034
- const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
1138
+ const apiKey = keyText(config?.apiKey) || keyText(env.RISICARE_API_KEY) || void 0;
1035
1139
  const { endpoint, apiEndpoint } = resolveEndpoints(
1036
1140
  config?.endpoint,
1037
1141
  config?.apiEndpoint,
@@ -1073,6 +1177,7 @@ function resolveConfig(config) {
1073
1177
  } else {
1074
1178
  enabled = !!apiKey;
1075
1179
  }
1180
+ if (!apiKey) enabled = false;
1076
1181
  return hideKeyFromInspect({
1077
1182
  apiKey: apiKey ?? "",
1078
1183
  endpoint,
@@ -1123,6 +1228,14 @@ function tracingFromEnv(value) {
1123
1228
  );
1124
1229
  return false;
1125
1230
  }
1231
+ function keyText(value) {
1232
+ return typeof value === "string" ? value.trim() : "";
1233
+ }
1234
+ function tracingTurnedOff(config) {
1235
+ if (config?.enabled !== void 0) return config.enabled === false;
1236
+ const v = (process.env.RISICARE_TRACING ?? "").trim().toLowerCase();
1237
+ return v !== "" && !TRACING_ON.has(v);
1238
+ }
1126
1239
  function parseNumericEnv(value, defaultValue) {
1127
1240
  if (value === void 0) return defaultValue;
1128
1241
  const n = Number(value);
@@ -2243,7 +2356,111 @@ function markCancel(span, error) {
2243
2356
  }
2244
2357
 
2245
2358
  // src/version.ts
2246
- var SDK_VERSION = "0.8.0";
2359
+ var SDK_VERSION = "0.9.1";
2360
+
2361
+ // src/exporters/quota.ts
2362
+ var QUOTA_REASON = "monthly_quota_exceeded";
2363
+ var QUOTA_HEADER = "X-Risicare-Quota";
2364
+ var QUOTA_HEADER_VALUE = "exceeded";
2365
+ var DEFAULT_RETRY_AFTER_S = 300;
2366
+ var MIN_RETRY_AFTER_S = 1;
2367
+ var MAX_RETRY_AFTER_S = 3600;
2368
+ var QUOTA_WARN_WINDOW_MS = 36e5;
2369
+ var MAX_RESETS_AT_CHARS = 40;
2370
+ function asPositiveCount(v) {
2371
+ if (typeof v === "number") return Number.isFinite(v) && v > 0;
2372
+ if (typeof v === "string" && /^[0-9]+$/.test(v)) return Number(v) > 0;
2373
+ return false;
2374
+ }
2375
+ function boundedRetryAfter(value) {
2376
+ let n;
2377
+ if (typeof value === "number") n = value;
2378
+ else if (typeof value === "string" && value.trim() !== "") n = Number(value);
2379
+ else return DEFAULT_RETRY_AFTER_S;
2380
+ if (!Number.isFinite(n)) return DEFAULT_RETRY_AFTER_S;
2381
+ return Math.min(Math.max(n, MIN_RETRY_AFTER_S), MAX_RETRY_AFTER_S);
2382
+ }
2383
+ function boundedResetsAt(value) {
2384
+ if (typeof value !== "string" || value.length === 0) return null;
2385
+ const cut = value.slice(0, MAX_RESETS_AT_CHARS);
2386
+ return /^[ -~]*$/.test(cut) ? cut : null;
2387
+ }
2388
+ function headerSaysExceeded(headers) {
2389
+ try {
2390
+ const value = headers?.get?.(QUOTA_HEADER);
2391
+ return typeof value === "string" && value.trim().toLowerCase() === QUOTA_HEADER_VALUE;
2392
+ } catch {
2393
+ return false;
2394
+ }
2395
+ }
2396
+ function parseJsonDiscard(payload, headers) {
2397
+ const body = payload !== null && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
2398
+ const stored = (asPositiveCount(body.accepted) || asPositiveCount(body.spansAccepted)) === true;
2399
+ if (body.reason === QUOTA_REASON || headerSaysExceeded(headers) && !stored) {
2400
+ return {
2401
+ retryAfterS: boundedRetryAfter(body.retryAfterSeconds),
2402
+ resetsAt: boundedResetsAt(body.resetsAt)
2403
+ };
2404
+ }
2405
+ return null;
2406
+ }
2407
+ var EPISODE_END_ACCEPTS = 3;
2408
+ var QuotaPause = class {
2409
+ constructor(now = () => performance.now()) {
2410
+ this.now = now;
2411
+ }
2412
+ _until = -Infinity;
2413
+ _inEpisode = false;
2414
+ _accepts = 0;
2415
+ _lastWarn = -Infinity;
2416
+ _lastInfo = -Infinity;
2417
+ /**
2418
+ * Spans dropped since the last WARNING: the full queue's (`addDrops`) and the batches that a
2419
+ * probe lost while the WARNING was held back. The WARNING carries the number.
2420
+ */
2421
+ _drops = 0;
2422
+ addDrops(count) {
2423
+ this._drops += count;
2424
+ }
2425
+ paused() {
2426
+ return this.now() < this._until;
2427
+ }
2428
+ remainingS() {
2429
+ return Math.max(0, (this._until - this.now()) / 1e3);
2430
+ }
2431
+ enter(discard, where, dropped) {
2432
+ const t = this.now();
2433
+ this._until = t + discard.retryAfterS * 1e3;
2434
+ this._inEpisode = true;
2435
+ this._accepts = 0;
2436
+ if (t - this._lastWarn >= QUOTA_WARN_WINDOW_MS) {
2437
+ this._lastWarn = t;
2438
+ const since = this._drops;
2439
+ this._drops = 0;
2440
+ warn(
2441
+ `Risicare: the monthly event quota is used up (monthly_quota_exceeded). ${where} discarded ${dropped} span(s) and will discard new ones until the quota resets (resetsAt=${discard.resetsAt ?? "unknown"}) or the plan changes. The SDK pauses export and sends one batch again in ${Math.round(discard.retryAfterS)} s. Spans that end in the meantime wait in the queue. When it is full the oldest spans are dropped (the most recent are kept) and counted as quota_exceeded in droppedSpansByReason; a batch that is discarded again is dropped and counted the same way. This is not an error and the SDK does not retry the batch. At most one such WARNING an hour.` + (since > 0 ? ` Spans dropped for the quota since the last WARNING: ${since}.` : "")
2442
+ );
2443
+ } else {
2444
+ this._drops += dropped;
2445
+ debug(`Quota discard again: ${dropped} span(s); paused for ${Math.round(discard.retryAfterS)} s`);
2446
+ }
2447
+ }
2448
+ accepted(where) {
2449
+ if (!this._inEpisode) return;
2450
+ this._accepts++;
2451
+ if (this._accepts < EPISODE_END_ACCEPTS) return;
2452
+ this._inEpisode = false;
2453
+ this._accepts = 0;
2454
+ this._until = -Infinity;
2455
+ const t = this.now();
2456
+ if (t - this._lastInfo >= QUOTA_WARN_WINDOW_MS) {
2457
+ this._lastInfo = t;
2458
+ info(`Risicare: ${where} accepts spans again; the export pause for the quota has ended.`);
2459
+ } else {
2460
+ debug("Quota pause ended (INFO already written this hour)");
2461
+ }
2462
+ }
2463
+ };
2247
2464
 
2248
2465
  // src/exporters/http.ts
2249
2466
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
@@ -2284,8 +2501,21 @@ var HttpExporter = class {
2284
2501
  _calls = /* @__PURE__ */ new Map();
2285
2502
  /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */
2286
2503
  _acks = /* @__PURE__ */ new WeakMap();
2504
+ /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
2505
+ noteQuotaDrop(count = 1) {
2506
+ this._quota.addDrops(count);
2507
+ }
2508
+ /** True while the exporter is paused for the monthly event quota (S-1). */
2509
+ quotaPaused() {
2510
+ return this._quota.paused();
2511
+ }
2287
2512
  /** The spans of each finished call that could not be serialized, by its batch. */
2288
2513
  _unserializable = /* @__PURE__ */ new WeakMap();
2514
+ /**
2515
+ * S-1: the paused state after a monthly-quota discard (see `quota.ts`). A discard is not a
2516
+ * failure: it does not touch the circuit breaker.
2517
+ */
2518
+ _quota = new QuotaPause();
2289
2519
  _circuitOpenUntil = 0;
2290
2520
  _circuitBreakerThreshold = 5;
2291
2521
  _circuitBreakerCooldownMs = 6e4;
@@ -2377,6 +2607,13 @@ var HttpExporter = class {
2377
2607
  }
2378
2608
  async _export(spans, call) {
2379
2609
  const cancelled = call.cancel.signal;
2610
+ if (this._quota.paused()) {
2611
+ debug(
2612
+ `Export skipped: monthly quota pause, ${Math.round(this._quota.remainingS())} s left; ${spans.length} span(s) dropped`
2613
+ );
2614
+ this._acks.set(spans, { accepted: 0, rejected: 0, quotaDropped: spans.length });
2615
+ return "success" /* SUCCESS */;
2616
+ }
2380
2617
  const parts = [];
2381
2618
  const bad = [];
2382
2619
  let errorClass = "";
@@ -2585,6 +2822,11 @@ var HttpExporter = class {
2585
2822
  `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
2586
2823
  );
2587
2824
  }
2825
+ if (ack.quota !== void 0) {
2826
+ this._quota.enter(ack.quota, `The ingest endpoint ${this._safeEndpoint}`, spansSent);
2827
+ } else if (ack.result === "success" /* SUCCESS */) {
2828
+ this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
2829
+ }
2588
2830
  if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
2589
2831
  if (ack.final) call.noRetry = true;
2590
2832
  return ack.result;
@@ -2651,7 +2893,16 @@ async function checkAck(response, spansSent, scrub) {
2651
2893
  try {
2652
2894
  payload = await response.json();
2653
2895
  } catch {
2654
- return null;
2896
+ payload = void 0;
2897
+ }
2898
+ const discard = parseJsonDiscard(payload, response.headers);
2899
+ if (discard !== null) {
2900
+ return {
2901
+ result: "success" /* SUCCESS */,
2902
+ counts: { accepted: 0, rejected: 0, quotaDropped: spansSent },
2903
+ final: false,
2904
+ quota: discard
2905
+ };
2655
2906
  }
2656
2907
  if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
2657
2908
  return null;
@@ -2681,27 +2932,6 @@ async function checkAck(response, spansSent, scrub) {
2681
2932
  return { result: "success" /* SUCCESS */, counts, final: false };
2682
2933
  }
2683
2934
 
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
2935
  // src/utils/stream-proxy.ts
2706
2936
  function endOpenProviderSpans() {
2707
2937
  let open;
@@ -3894,6 +4124,8 @@ var TERMINATING_SIGNALS = [
3894
4124
  ];
3895
4125
  var BACKSTOP_MARGIN_MS = 500;
3896
4126
  var _finalMetrics;
4127
+ var _finalProcessor;
4128
+ var _finalActive = false;
3897
4129
  var SCORE_TIMEOUT_MS = 2e3;
3898
4130
  var _pendingScores = /* @__PURE__ */ new Set();
3899
4131
  var _failedScores = 0;
@@ -3974,6 +4206,13 @@ var RisicareClient = class {
3974
4206
  * this flag `getMetrics()` would keep reporting `"running"` over a processor
3975
4207
  * that has already been torn down. */
3976
4208
  isShutdown = false;
4209
+ /**
4210
+ * Tracing was on at `init()` or since `enable()`. A client that never was
4211
+ * (no key, or tracing off) accepted nothing, and delivered nothing: its
4212
+ * `flush()` is false. `disable()` does not clear it: spans that were accepted
4213
+ * before keep their answer.
4214
+ */
4215
+ _activated = false;
3977
4216
  _shutdownPromise;
3978
4217
  _shutdownHandlers = [];
3979
4218
  constructor(config) {
@@ -3984,16 +4223,13 @@ var RisicareClient = class {
3984
4223
  'the API key does not look like a Risicare key: it should start with "rsk-", "rski_" or "rsks_". Tracing continues with this key.'
3985
4224
  );
3986
4225
  }
3987
- const tracingSetExplicitly = config?.enabled !== void 0 || (process.env.RISICARE_TRACING ?? "").trim() !== "";
3988
- if (!this.config.apiKey && !this.config.enabled && !tracingSetExplicitly) {
4226
+ if (!this.config.apiKey && !tracingTurnedOff(config)) {
3989
4227
  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."
4228
+ "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
4229
  );
3992
4230
  }
3993
4231
  let exporter;
3994
- if (this.config.debug && !this.config.apiKey) {
3995
- exporter = new ConsoleExporter();
3996
- } else if (this.config.apiKey) {
4232
+ if (this.config.apiKey) {
3997
4233
  exporter = new HttpExporter({
3998
4234
  endpoint: this.config.endpoint,
3999
4235
  apiKey: this.config.apiKey,
@@ -4001,16 +4237,6 @@ var RisicareClient = class {
4001
4237
  environment: this.config.environment || void 0,
4002
4238
  compress: this.config.compress
4003
4239
  });
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
4240
  }
4015
4241
  this.processor = new BatchSpanProcessor({
4016
4242
  exporters: exporter ? [exporter] : [],
@@ -4041,6 +4267,7 @@ var RisicareClient = class {
4041
4267
  serviceName: this.config.serviceName,
4042
4268
  serviceVersion: this.config.serviceVersion
4043
4269
  });
4270
+ this._activated = this.tracer.enabled;
4044
4271
  this.processor.start();
4045
4272
  if (this.config.apiKey && this.config.enabled && this.config.fixRuntime) {
4046
4273
  try {
@@ -4079,7 +4306,12 @@ var RisicareClient = class {
4079
4306
  return this.tracer.enabled;
4080
4307
  }
4081
4308
  set enabled(value) {
4309
+ if (value && !this.config.apiKey) {
4310
+ debug("enable() ignored: no API key is configured, so tracing stays off");
4311
+ return;
4312
+ }
4082
4313
  this.tracer.enabled = value;
4314
+ if (value) this._activated = true;
4083
4315
  }
4084
4316
  // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)
4085
4317
  async shutdown(timeoutMs) {
@@ -4098,6 +4330,8 @@ var RisicareClient = class {
4098
4330
  _failWaitingScores(SCORE_DEADLINE_REASON);
4099
4331
  this.isShutdown = true;
4100
4332
  _finalMetrics = this.processor.getMetrics();
4333
+ _finalProcessor = this.processor;
4334
+ _finalActive = this._activated;
4101
4335
  }
4102
4336
  /**
4103
4337
  * Flush pending spans.
@@ -4111,6 +4345,7 @@ var RisicareClient = class {
4111
4345
  * *discarded*.
4112
4346
  */
4113
4347
  async flush(timeoutMs) {
4348
+ if (!this._activated) return false;
4114
4349
  return this.processor.flush(timeoutMs);
4115
4350
  }
4116
4351
  /**
@@ -4137,6 +4372,19 @@ var RisicareClient = class {
4137
4372
  * * **A prior listener exists.** The application took ownership before the
4138
4373
  * SDK loaded. We drain and RETURN; termination was never ours to decide,
4139
4374
  * and forcing it would cut off the app's own graceful shutdown.
4375
+ * * **A listener that the application adds after `init()`.** Node calls ours
4376
+ * first. The question is asked when OUR listener starts, at signal time:
4377
+ * is there another listener for this signal? If there is, it owns
4378
+ * termination as well: when the drain ends we do not raise the signal
4379
+ * again, and we do not arm the fail-safe exit. Its listener runs once and
4380
+ * decides the exit, in the same way as when it was registered before
4381
+ * `init()`. Through 0.8.0 the re-raise ran it a second time, and the
4382
+ * fail-safe ended the process with code 143, 100 ms later.
4383
+ * * **A listener that the application adds DURING the drain.** There was none
4384
+ * at signal time, so the 0.8.0 rule holds: after the drain we raise the
4385
+ * signal again, and that listener runs on it, and the process ends (fail-safe
4386
+ * after 100 ms if it does not). A count taken after the drain would have
4387
+ * counted that listener, and nothing would have run or ended the process.
4140
4388
  *
4141
4389
  * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
4142
4390
  * carries no termination the SDK could displace — the loop has already
@@ -4152,6 +4400,7 @@ var RisicareClient = class {
4152
4400
  for (const [signal, signum] of TERMINATING_SIGNALS) {
4153
4401
  const weDisplacedDefault = process.listenerCount(signal) === 0;
4154
4402
  const handler = () => {
4403
+ const othersAtSignal = process.listeners(signal).filter((l) => l !== handler).length;
4155
4404
  const backstop = setTimeout(
4156
4405
  () => process.exit(128 + signum),
4157
4406
  SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
@@ -4161,6 +4410,7 @@ var RisicareClient = class {
4161
4410
  }).finally(() => {
4162
4411
  clearTimeout(backstop);
4163
4412
  if (!weDisplacedDefault) return;
4413
+ if (othersAtSignal > 0) return;
4164
4414
  try {
4165
4415
  process.kill(process.pid, signal);
4166
4416
  } catch {
@@ -4209,6 +4459,8 @@ function init(config) {
4209
4459
  return;
4210
4460
  }
4211
4461
  _finalMetrics = void 0;
4462
+ _finalProcessor = void 0;
4463
+ _finalActive = false;
4212
4464
  _resetScoreFailures();
4213
4465
  const client = new RisicareClient(config);
4214
4466
  setClient(client);
@@ -4231,10 +4483,12 @@ async function flush(timeoutMs) {
4231
4483
  const scoreMark = _failedScoresFlushMark;
4232
4484
  const client = getClient();
4233
4485
  let spansOk;
4234
- if (!client) {
4235
- spansOk = (_finalMetrics?.droppedSpansByReason.shutdown_residue ?? 0) === 0;
4236
- } else {
4486
+ if (client) {
4237
4487
  spansOk = await client.flush(timeoutMs);
4488
+ } else if (_finalProcessor) {
4489
+ spansOk = _finalActive && await _finalProcessor.flush(timeoutMs);
4490
+ } else {
4491
+ spansOk = false;
4238
4492
  }
4239
4493
  const scoresDone = await _waitForPendingScores(deadline - Date.now());
4240
4494
  if (!scoresDone) _failWaitingScores(SCORE_DEADLINE_REASON);
@@ -4253,7 +4507,7 @@ function disable() {
4253
4507
  }
4254
4508
  function isEnabled() {
4255
4509
  const client = getClient();
4256
- return client?.enabled ?? false;
4510
+ return client !== void 0 && !client.isShutdown && client.enabled;
4257
4511
  }
4258
4512
  function getTracer2() {
4259
4513
  return getTracer();
@@ -4272,10 +4526,11 @@ function getMetrics() {
4272
4526
  };
4273
4527
  }
4274
4528
  if (_finalMetrics) {
4529
+ const tally = _finalProcessor?.getMetrics() ?? _finalMetrics;
4275
4530
  return {
4276
- ..._finalMetrics,
4531
+ ...tally,
4277
4532
  failedScores: _failedScores,
4278
- droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
4533
+ droppedSpansByReason: { ...tally.droppedSpansByReason },
4279
4534
  sdkState: "shutdown"
4280
4535
  };
4281
4536
  }
@@ -4288,8 +4543,10 @@ function getMetrics() {
4288
4543
  queue_full: 0,
4289
4544
  transport_refused: 0,
4290
4545
  shutdown_residue: 0,
4291
- unacknowledged: 0
4546
+ unacknowledged: 0,
4547
+ quota_exceeded: 0
4292
4548
  },
4549
+ droppedQuota: 0,
4293
4550
  failedExports: 0,
4294
4551
  queueSize: 0,
4295
4552
  queueCapacity: 0,
@@ -4347,24 +4604,29 @@ function reportError(error, options) {
4347
4604
  debug("reportError failed");
4348
4605
  }
4349
4606
  }
4607
+ function refuseScore(message) {
4608
+ warn(message);
4609
+ const client = getClient();
4610
+ if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;
4611
+ }
4350
4612
  function score(traceId, name, value, options) {
4351
4613
  try {
4352
4614
  const raw = value;
4353
4615
  if (typeof raw === "boolean") value = raw ? 1 : 0;
4354
4616
  if (typeof value !== "number") {
4355
- warn(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4617
+ refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4356
4618
  return;
4357
4619
  }
4358
4620
  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.`);
4621
+ refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
4360
4622
  return;
4361
4623
  }
4362
4624
  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.");
4625
+ refuseScore("score: traceId must be a non-empty string. The SDK does not send this score.");
4364
4626
  return;
4365
4627
  }
4366
4628
  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.");
4629
+ refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
4368
4630
  return;
4369
4631
  }
4370
4632
  const client = getClient();