risicare 0.9.2 → 0.11.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 (73) hide show
  1. package/CHANGELOG.md +254 -0
  2. package/README.md +194 -58
  3. package/dist/frameworks/instructor.cjs +383 -117
  4. package/dist/frameworks/instructor.cjs.map +1 -1
  5. package/dist/frameworks/instructor.js +383 -117
  6. package/dist/frameworks/instructor.js.map +1 -1
  7. package/dist/frameworks/langchain.cjs +396 -130
  8. package/dist/frameworks/langchain.cjs.map +1 -1
  9. package/dist/frameworks/langchain.js +396 -130
  10. package/dist/frameworks/langchain.js.map +1 -1
  11. package/dist/frameworks/langgraph.cjs +396 -130
  12. package/dist/frameworks/langgraph.cjs.map +1 -1
  13. package/dist/frameworks/langgraph.js +396 -130
  14. package/dist/frameworks/langgraph.js.map +1 -1
  15. package/dist/frameworks/llamaindex.cjs +396 -130
  16. package/dist/frameworks/llamaindex.cjs.map +1 -1
  17. package/dist/frameworks/llamaindex.js +396 -130
  18. package/dist/frameworks/llamaindex.js.map +1 -1
  19. package/dist/index.cjs +1136 -240
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +151 -26
  22. package/dist/index.d.ts +151 -26
  23. package/dist/index.js +1132 -240
  24. package/dist/index.js.map +1 -1
  25. package/dist/providers/anthropic/index.cjs +467 -137
  26. package/dist/providers/anthropic/index.cjs.map +1 -1
  27. package/dist/providers/anthropic/index.js +467 -137
  28. package/dist/providers/anthropic/index.js.map +1 -1
  29. package/dist/providers/bedrock/index.cjs +409 -128
  30. package/dist/providers/bedrock/index.cjs.map +1 -1
  31. package/dist/providers/bedrock/index.js +409 -128
  32. package/dist/providers/bedrock/index.js.map +1 -1
  33. package/dist/providers/cerebras/index.cjs +414 -133
  34. package/dist/providers/cerebras/index.cjs.map +1 -1
  35. package/dist/providers/cerebras/index.js +414 -133
  36. package/dist/providers/cerebras/index.js.map +1 -1
  37. package/dist/providers/cohere/index.cjs +414 -133
  38. package/dist/providers/cohere/index.cjs.map +1 -1
  39. package/dist/providers/cohere/index.js +414 -133
  40. package/dist/providers/cohere/index.js.map +1 -1
  41. package/dist/providers/google/index.cjs +414 -133
  42. package/dist/providers/google/index.cjs.map +1 -1
  43. package/dist/providers/google/index.js +414 -133
  44. package/dist/providers/google/index.js.map +1 -1
  45. package/dist/providers/groq/index.cjs +414 -133
  46. package/dist/providers/groq/index.cjs.map +1 -1
  47. package/dist/providers/groq/index.js +414 -133
  48. package/dist/providers/groq/index.js.map +1 -1
  49. package/dist/providers/huggingface/index.cjs +414 -133
  50. package/dist/providers/huggingface/index.cjs.map +1 -1
  51. package/dist/providers/huggingface/index.js +414 -133
  52. package/dist/providers/huggingface/index.js.map +1 -1
  53. package/dist/providers/mistral/index.cjs +414 -133
  54. package/dist/providers/mistral/index.cjs.map +1 -1
  55. package/dist/providers/mistral/index.js +414 -133
  56. package/dist/providers/mistral/index.js.map +1 -1
  57. package/dist/providers/ollama/index.cjs +414 -133
  58. package/dist/providers/ollama/index.cjs.map +1 -1
  59. package/dist/providers/ollama/index.js +414 -133
  60. package/dist/providers/ollama/index.js.map +1 -1
  61. package/dist/providers/openai/index.cjs +452 -135
  62. package/dist/providers/openai/index.cjs.map +1 -1
  63. package/dist/providers/openai/index.js +452 -135
  64. package/dist/providers/openai/index.js.map +1 -1
  65. package/dist/providers/together/index.cjs +414 -133
  66. package/dist/providers/together/index.cjs.map +1 -1
  67. package/dist/providers/together/index.js +414 -133
  68. package/dist/providers/together/index.js.map +1 -1
  69. package/dist/providers/vercel-ai/index.cjs +398 -132
  70. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  71. package/dist/providers/vercel-ai/index.js +398 -132
  72. package/dist/providers/vercel-ai/index.js.map +1 -1
  73. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -41,6 +41,7 @@ __export(src_exports, {
41
41
  SpanKind: () => SpanKind,
42
42
  SpanStatus: () => SpanStatus,
43
43
  WebhookVerificationError: () => WebhookVerificationError,
44
+ addTags: () => addTags,
44
45
  agent: () => agent,
45
46
  disable: () => disable,
46
47
  enable: () => enable,
@@ -72,6 +73,9 @@ __export(src_exports, {
72
73
  reportError: () => reportError,
73
74
  score: () => score,
74
75
  session: () => session,
76
+ setRelease: () => setRelease,
77
+ setSession: () => setSession,
78
+ setUser: () => setUser,
75
79
  shutdown: () => shutdown,
76
80
  shutdownFixRuntime: () => shutdownFixRuntime,
77
81
  suppressProviderInstrumentation: () => suppressProviderInstrumentation,
@@ -94,6 +98,35 @@ module.exports = __toCommonJS(src_exports);
94
98
  // src/client.ts
95
99
  var import_node_crypto3 = require("crypto");
96
100
 
101
+ // src/exporters/retry.ts
102
+ var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
103
+ var TOO_LARGE_STATUS = 413;
104
+ var RETRY_BACKOFF_BASE_S = 1;
105
+ var RETRY_BACKOFF_CAP_S = 30;
106
+ var DEFAULT_RETRY_HORIZON_S = 300;
107
+ var DEFAULT_SHUTDOWN_TIMEOUT_S = 10;
108
+ var RETRY_WARN_AFTER_ATTEMPTS = 3;
109
+ var jitter = { fraction: () => Math.random() };
110
+ function backoffDelayS(retryNumber, fraction) {
111
+ const exponent = Math.min(Math.max(retryNumber, 0), 62);
112
+ const ceiling = Math.min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** exponent);
113
+ return Math.min(Math.max(fraction, 0), 1) * ceiling;
114
+ }
115
+ var SECONDS = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
116
+ function parseRetryAfterS(value, nowMs = Date.now()) {
117
+ if (value === null || value === void 0) return null;
118
+ const text = String(value).trim();
119
+ if (text === "") return null;
120
+ if (SECONDS.test(text)) {
121
+ const seconds = Number(text);
122
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
123
+ }
124
+ if (!/[A-Za-z]/.test(text)) return null;
125
+ const when = Date.parse(text);
126
+ if (!Number.isFinite(when)) return null;
127
+ return Math.max(0, (when - nowMs) / 1e3);
128
+ }
129
+
97
130
  // src/globals.ts
98
131
  var import_node_async_hooks = require("async_hooks");
99
132
  var G = globalThis;
@@ -137,9 +170,9 @@ function setDebugFlag(enabled) {
137
170
  var PROVIDER_SPANS = /* @__PURE__ */ Symbol.for("risicare.providerSpans");
138
171
  function usableProviderSpanState(s) {
139
172
  if (!s || typeof s !== "object") return false;
140
- const { version, open, registry } = s;
173
+ const { version, open, registry: registry2 } = s;
141
174
  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");
175
+ return version === 1 && !!o && typeof o.add === "function" && typeof o.delete === "function" && typeof o[Symbol.iterator] === "function" && (registry2 === void 0 || typeof registry2.register === "function");
143
176
  }
144
177
  function getProviderSpanState() {
145
178
  const found = G[PROVIDER_SPANS];
@@ -367,7 +400,49 @@ var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
367
400
  "audio.transcript",
368
401
  "traceloop.entity.input",
369
402
  // OpenLLMetry
370
- "traceloop.entity.output"
403
+ "traceloop.entity.output",
404
+ // Gateway corpus v2 (R41): the content keys of more frameworks. The same 75
405
+ // keys as `CONTENT_KEYS_EXACT` in the gateway's `content_control.rs`.
406
+ "agent.backstory",
407
+ // OpenInference
408
+ "agent.goal",
409
+ "llm.available_functions",
410
+ "llm.tools",
411
+ "ai.prompt",
412
+ // Vercel AI SDK
413
+ "ai.prompt.messages",
414
+ "ai.prompt.tools",
415
+ "ai.response.files",
416
+ "ai.response.object",
417
+ "ai.response.reasoning",
418
+ "ai.response.text",
419
+ "ai.response.toolCalls",
420
+ "ai.result.object",
421
+ // the older Vercel names
422
+ "ai.result.text",
423
+ "ai.result.toolCalls",
424
+ "ai.toolCall.args",
425
+ "ai.toolCall.result",
426
+ "ai.value",
427
+ // the text of an embedding call
428
+ "ai.values",
429
+ "final_result",
430
+ // Pydantic AI
431
+ "model_request_parameters",
432
+ "pydantic_ai.all_messages",
433
+ "tool_arguments",
434
+ "tool_response",
435
+ "gcp.vertex.agent.data",
436
+ // Google ADK
437
+ "gcp.vertex.agent.llm_request",
438
+ "gcp.vertex.agent.llm_response",
439
+ "gcp.vertex.agent.tool_call_args",
440
+ "gcp.vertex.agent.tool_response",
441
+ "gen_ai.task.input",
442
+ // OpenLLMetry
443
+ "gen_ai.task.output",
444
+ "sk.available_functions"
445
+ // Semantic Kernel
371
446
  ]);
372
447
  var CONTENT_LAST_SEGMENT_IN_CONTEXT = /* @__PURE__ */ new Map([
373
448
  ["function_call_arguments_json", /* @__PURE__ */ new Set()],
@@ -375,7 +450,15 @@ var CONTENT_LAST_SEGMENT_IN_CONTEXT = /* @__PURE__ */ new Map([
375
450
  ["data", /* @__PURE__ */ new Set(["message_content"])],
376
451
  ["url", /* @__PURE__ */ new Set(["image"])],
377
452
  // `image.url` can hold base64 data
378
- ["metadata", /* @__PURE__ */ new Set(["document", "documents"])]
453
+ ["metadata", /* @__PURE__ */ new Set(["document", "documents"])],
454
+ // Gateway corpus v2: a list of tool definitions. The `description` of one tool
455
+ // on a tool span (`tool.description`) is not content; the descriptions in a list are.
456
+ ["description", /* @__PURE__ */ new Set(["definitions", "functions", "tools"])],
457
+ ["json_schema", /* @__PURE__ */ new Set(["tool", "tools"])],
458
+ ["parameters", /* @__PURE__ */ new Set(["definitions", "functions", "tool", "tools"])],
459
+ // Gateway corpus v2: the Mastra span I/O, `mastra.<span type>.input|output`.
460
+ ["input", /* @__PURE__ */ new Set(["mastra"])],
461
+ ["output", /* @__PURE__ */ new Set(["mastra"])]
379
462
  ]);
380
463
  var CONTENT_CONTAINER_SEGMENTS = /* @__PURE__ */ new Set([
381
464
  "message",
@@ -388,8 +471,23 @@ var CONTENT_CONTAINER_SEGMENTS = /* @__PURE__ */ new Set([
388
471
  "documents",
389
472
  "tool_call",
390
473
  "tool_calls",
391
- "function"
474
+ "function",
475
+ // Gateway corpus v2: LiteLLM `gen_ai.completion.{i}.function_call.arguments` and
476
+ // OpenInference `llm.prompts.{i}.prompt.text`.
477
+ "function_call",
478
+ "prompt",
479
+ "prompts"
480
+ ]);
481
+ var CONTENT_FIRST_SEGMENTS = /* @__PURE__ */ new Set(["crewai"]);
482
+ var CONTENT_EVENT_NAMES = /* @__PURE__ */ new Set([
483
+ "gen_ai.assistant.message",
484
+ "gen_ai.choice",
485
+ "gen_ai.system.message",
486
+ "gen_ai.tool.message",
487
+ "gen_ai.user.message"
392
488
  ]);
489
+ var CONTENT_EVENT_PREFIX = "gen_ai.content.";
490
+ var CONTENT_EVENT_KEEP_KEYS = /* @__PURE__ */ new Set(["gen_ai.provider.name", "gen_ai.system"]);
393
491
  var CONTENT_KEYS_KEEP_EXACT = /* @__PURE__ */ new Set([
394
492
  "gen_ai.response.content_type",
395
493
  "gen_ai.response.content_blocks",
@@ -407,10 +505,60 @@ var KEEP_LAST_SEGMENTS = /* @__PURE__ */ new Set([
407
505
  "index",
408
506
  "model",
409
507
  "finish_reason",
410
- "mime_type"
508
+ "mime_type",
509
+ // Gateway v2 at risicare-ingestion main (PR 94): a model name
510
+ // (`crewai.agent.llm`) and the crew process type are not content.
511
+ "llm",
512
+ "process"
411
513
  ]);
412
514
  var KEEP_LAST_SUFFIXES = ["_length", "_tokens", "_count"];
515
+ var CONTENT_IN_JSON_OBJECT = /* @__PURE__ */ new Map([
516
+ [
517
+ "llm.invocation_parameters",
518
+ /* @__PURE__ */ new Set([
519
+ "additionalinstructions",
520
+ // OpenAI assistants run
521
+ "chathistory",
522
+ // Cohere
523
+ "contents",
524
+ // Gemini
525
+ "documents",
526
+ // Cohere RAG
527
+ "functions",
528
+ "input",
529
+ "inputtext",
530
+ // Bedrock Titan
531
+ "instructions",
532
+ "message",
533
+ // Cohere
534
+ "messages",
535
+ "preamble",
536
+ // Cohere
537
+ "prediction",
538
+ // OpenAI predicted output
539
+ "prompt",
540
+ "system",
541
+ // Anthropic
542
+ "systeminstruction",
543
+ // Gemini
544
+ "texts",
545
+ // Cohere embed
546
+ "toolconfig",
547
+ // Gemini
548
+ "tools"
549
+ ])
550
+ ]
551
+ ]);
552
+ var VALUE_RULE_PREFIXES = new Set(
553
+ [...CONTENT_IN_JSON_OBJECT.keys()].flatMap((key) => {
554
+ const segments = key.split(".");
555
+ return segments.slice(1).map((_, i) => segments.slice(0, i + 1).join("."));
556
+ })
557
+ );
413
558
  var CONTENT_OMITTED_MARKER = "<risicare:content-omitted>";
559
+ function hasKeepLastSegment(last) {
560
+ return KEEP_LAST_SEGMENTS.has(last) || KEEP_LAST_SUFFIXES.some((x) => last.endsWith(x));
561
+ }
414
562
  function isContentKey(key) {
415
563
  if (CONTENT_KEYS_KEEP_EXACT.has(key)) return false;
416
564
  if (CONTENT_KEYS_EXACT.has(key) || key.endsWith("_content")) return true;
@@ -420,25 +568,220 @@ function isContentKey(key) {
420
568
  if (context && (context.size === 0 || segments.slice(0, -1).some((s) => context.has(s)))) {
421
569
  return true;
422
570
  }
423
- if (KEEP_LAST_SEGMENTS.has(last) || KEEP_LAST_SUFFIXES.some((x) => last.endsWith(x))) {
571
+ if (hasKeepLastSegment(last)) {
424
572
  return false;
425
573
  }
574
+ if (segments.length > 1 && CONTENT_FIRST_SEGMENTS.has(segments[0])) return true;
426
575
  if (last === "content") return true;
427
576
  if (last === "text" || last === "arguments") {
428
577
  return segments.slice(0, -1).some((s) => CONTENT_CONTAINER_SEGMENTS.has(s));
429
578
  }
430
579
  return false;
431
580
  }
432
- function stripAttributes(attrs) {
581
+ function isContentEvent(name) {
582
+ return CONTENT_EVENT_NAMES.has(name) || name.startsWith(CONTENT_EVENT_PREFIX);
583
+ }
584
+ function isContentEventAttribute(key) {
585
+ if (isContentKey(key)) return true;
586
+ const last = key.slice(key.lastIndexOf(".") + 1);
587
+ return !(CONTENT_KEYS_KEEP_EXACT.has(key) || CONTENT_EVENT_KEEP_KEYS.has(key) || hasKeepLastSegment(last));
588
+ }
589
+ function jsonObjectContentKeys(keyPath, key) {
590
+ for (const [ruleKey, keys] of CONTENT_IN_JSON_OBJECT) {
591
+ if (ruleKey === keyPath || ruleKey === key) return keys;
592
+ }
593
+ return void 0;
594
+ }
595
+ function isJsonObject(value) {
596
+ return typeof value === "object" && value !== null && !Array.isArray(value);
597
+ }
598
+ function flatValueRule(keyPath, key) {
599
+ for (const [ruleKey, keys] of CONTENT_IN_JSON_OBJECT) {
600
+ for (const k of [keyPath, key]) {
601
+ if (k.startsWith(`${ruleKey}.`)) return [k.slice(ruleKey.length + 1), keys];
602
+ }
603
+ }
604
+ return void 0;
605
+ }
606
+ function normalisedKey(key) {
607
+ return key.replace(/_/g, "").replace(/[A-Z]/g, (c) => c.toLowerCase());
608
+ }
609
+ function namesListedKey(key, keys) {
610
+ return key.split(".").some((part) => keys.has(normalisedKey(part)));
611
+ }
612
+ function isKeyRuleText(keyPath, key) {
613
+ return isContentKey(keyPath) || isContentKey(key);
614
+ }
615
+ function startsAsJson(text) {
616
+ return /^[ \t\n\r]*[{[]/.test(text);
617
+ }
618
+ function parseJson(text) {
619
+ return JSON.parse(text, (_key, value) => {
620
+ if (typeof value === "number" && !Number.isFinite(value)) {
621
+ throw new RangeError("not JSON: a number out of range");
622
+ }
623
+ return value;
624
+ });
625
+ }
626
+ function jsonCopy(value) {
627
+ return parseJson(
628
+ JSON.stringify(value, (_key, v) => {
629
+ if (typeof v === "number" && !Number.isFinite(v)) throw new RangeError("not JSON: a non-finite number");
630
+ return v;
631
+ })
632
+ );
633
+ }
634
+ function omitInJsonObject(value, keyPath, keys) {
635
+ try {
636
+ let parsed;
637
+ if (typeof value === "string") parsed = parseJson(value);
638
+ else if (typeof value === "object" && value !== null) parsed = jsonCopy(value);
639
+ if (!isJsonObject(parsed)) return [CONTENT_OMITTED_MARKER, 1];
640
+ let n = 0;
641
+ for (const k of Object.keys(parsed)) {
642
+ const [entry, count] = omitInParameterEntry(parsed[k], `${keyPath}.${k}`, k, keys);
643
+ parsed[k] = entry;
644
+ n += count;
645
+ }
646
+ return [typeof value === "string" ? JSON.stringify(parsed) : parsed, n];
647
+ } catch {
648
+ return [CONTENT_OMITTED_MARKER, 1];
649
+ }
650
+ }
651
+ function omitInParameterEntry(value, keyPath, key, keys) {
652
+ if (namesListedKey(key, keys) || isKeyRuleText(keyPath, key)) return [CONTENT_OMITTED_MARKER, 1];
653
+ return omitInParameter(value, keyPath, keys);
654
+ }
655
+ function omitInParameter(value, path, keys) {
433
656
  let n = 0;
434
- for (const k of Object.keys(attrs)) {
435
- if (isContentKey(k)) {
436
- attrs[k] = CONTENT_OMITTED_MARKER;
437
- n++;
657
+ if (Array.isArray(value)) {
658
+ value.forEach((item, i) => {
659
+ const [entry, count] = omitInParameter(item, `${path}.${i}`, keys);
660
+ value[i] = entry;
661
+ n += count;
662
+ });
663
+ } else if (isJsonObject(value)) {
664
+ for (const k of Object.keys(value)) {
665
+ const [entry, count] = omitInParameterEntry(value[k], `${path}.${k}`, k, keys);
666
+ value[k] = entry;
667
+ n += count;
668
+ }
669
+ } else if (typeof value === "string" && startsAsJson(value)) {
670
+ try {
671
+ const [tree, count] = omitInParameter(parseJson(value), path, keys);
672
+ return [count ? JSON.stringify(tree) : value, count];
673
+ } catch {
674
+ return [CONTENT_OMITTED_MARKER, 1];
675
+ }
676
+ }
677
+ return [value, n];
678
+ }
679
+ function omitFlat(value, keyPath, key, rest, keys) {
680
+ if (namesListedKey(rest, keys) || isKeyRuleText(keyPath, key)) return [CONTENT_OMITTED_MARKER, 1];
681
+ try {
682
+ if (typeof value === "object" && value !== null) {
683
+ const [tree, n] = omitInParameter(jsonCopy(value), keyPath, keys);
684
+ return n ? [tree, n] : [value, 0];
685
+ }
686
+ return omitInParameter(value, keyPath, keys);
687
+ } catch {
688
+ return [CONTENT_OMITTED_MARKER, 1];
689
+ }
690
+ }
691
+ function omitBelow(value, path) {
692
+ const text = typeof value === "string" ? value : value instanceof String ? value.valueOf() : void 0;
693
+ if (text !== void 0) {
694
+ let tree;
695
+ try {
696
+ tree = parseJson(text);
697
+ } catch {
698
+ return startsAsJson(text) ? [CONTENT_OMITTED_MARKER, 1] : [value, 0];
699
+ }
700
+ if (typeof tree !== "object" || tree === null) return [value, 0];
701
+ try {
702
+ const [n, found] = omitBelowParsed(tree, path);
703
+ return found ? [JSON.stringify(tree), n] : [value, 0];
704
+ } catch {
705
+ return [CONTENT_OMITTED_MARKER, 1];
438
706
  }
439
707
  }
708
+ if (typeof value !== "object" || value === null) return [value, 0];
709
+ try {
710
+ const tree = jsonCopy(value);
711
+ const [n, found] = omitBelowParsed(tree, path);
712
+ return found ? [tree, n] : [value, 0];
713
+ } catch {
714
+ return [CONTENT_OMITTED_MARKER, 1];
715
+ }
716
+ }
717
+ function omitBelowParsed(tree, path) {
718
+ let n = 0;
719
+ let found = false;
720
+ if (Array.isArray(tree)) {
721
+ tree.forEach((item, i) => {
722
+ const child = `${path}.${i}`;
723
+ if (!VALUE_RULE_PREFIXES.has(child)) return;
724
+ const [count, below] = omitBelowParsed(item, child);
725
+ n += count;
726
+ found ||= below;
727
+ });
728
+ } else if (isJsonObject(tree)) {
729
+ for (const k of Object.keys(tree)) {
730
+ const child = `${path}.${k}`;
731
+ const keys = jsonObjectContentKeys(child, k);
732
+ const flat = keys ? void 0 : flatValueRule(child, k);
733
+ if (keys) {
734
+ const [entry, count] = omitInJsonObject(tree[k], child, keys);
735
+ tree[k] = entry;
736
+ n += count;
737
+ found = true;
738
+ } else if (flat) {
739
+ const [entry, count] = omitFlat(tree[k], child, k, flat[0], flat[1]);
740
+ tree[k] = entry;
741
+ n += count;
742
+ found = true;
743
+ } else if (VALUE_RULE_PREFIXES.has(child)) {
744
+ const [count, below] = omitBelowParsed(tree[k], child);
745
+ n += count;
746
+ found ||= below;
747
+ }
748
+ }
749
+ }
750
+ return [n, found];
751
+ }
752
+ function reachesValueRule(key) {
753
+ return CONTENT_IN_JSON_OBJECT.has(key) || VALUE_RULE_PREFIXES.has(key) || flatValueRule(key, key) !== void 0;
754
+ }
755
+ function stripAttributes(attrs, rule = isContentKey) {
756
+ let n = 0;
757
+ for (const k of Object.keys(attrs)) {
758
+ const keys = rule === isContentKey ? jsonObjectContentKeys(k, k) : void 0;
759
+ const flat = rule === isContentKey && !keys ? flatValueRule(k, k) : void 0;
760
+ let result;
761
+ if (keys) result = omitInJsonObject(attrs[k], k, keys);
762
+ else if (flat) result = omitFlat(attrs[k], k, k, flat[0], flat[1]);
763
+ else if (rule(k)) result = [CONTENT_OMITTED_MARKER, 1];
764
+ else if (VALUE_RULE_PREFIXES.has(k)) result = omitBelow(attrs[k], k);
765
+ else continue;
766
+ attrs[k] = result[0];
767
+ n += result[1];
768
+ }
440
769
  return n;
441
770
  }
771
+ function stripOwned(holder, rule = isContentKey) {
772
+ const attrs = holder.attributes;
773
+ if (!attrs || typeof attrs !== "object" || !Object.keys(attrs).some((k) => rule(k) || reachesValueRule(k))) {
774
+ return 0;
775
+ }
776
+ const copy = { ...attrs };
777
+ try {
778
+ holder.attributes = copy;
779
+ } catch {
780
+ return stripAttributes(attrs, rule);
781
+ }
782
+ if (holder.attributes !== copy) return stripAttributes(attrs, rule);
783
+ return stripAttributes(copy, rule);
784
+ }
442
785
  function stripContent(span) {
443
786
  let stripped = 0;
444
787
  if (span.attributes && typeof span.attributes === "object") {
@@ -447,14 +790,15 @@ function stripContent(span) {
447
790
  if (Array.isArray(span.events)) {
448
791
  for (const event of span.events) {
449
792
  if (event?.attributes && typeof event.attributes === "object") {
450
- stripped += stripAttributes(event.attributes);
793
+ const messageEvent = typeof event.name === "string" && isContentEvent(event.name);
794
+ stripped += stripOwned(event, messageEvent ? isContentEventAttribute : isContentKey);
451
795
  }
452
796
  }
453
797
  }
454
798
  if (Array.isArray(span.links)) {
455
799
  for (const link of span.links) {
456
800
  if (link?.attributes && typeof link.attributes === "object") {
457
- stripped += stripAttributes(link.attributes);
801
+ stripped += stripOwned(link);
458
802
  }
459
803
  }
460
804
  }
@@ -511,6 +855,31 @@ function warnMaskSlow(spanCount, elapsedMs) {
511
855
  }
512
856
 
513
857
  // src/exporters/batch.ts
858
+ var DECIDED_FAILURES = /* @__PURE__ */ new Set([
859
+ "transport_refused",
860
+ "retry_exhausted",
861
+ "shutdown_residue"
862
+ ]);
863
+ var DECIDED_DROPS = /* @__PURE__ */ new Set([
864
+ "transport_refused",
865
+ "retry_exhausted",
866
+ "shutdown_residue",
867
+ "too_large"
868
+ ]);
869
+ function endMs(span) {
870
+ const end = span?.endTime;
871
+ if (typeof end !== "string") return null;
872
+ const ms = Date.parse(end);
873
+ return Number.isFinite(ms) ? ms : null;
874
+ }
875
+ function oldestEndMs(spans) {
876
+ let oldest = null;
877
+ for (const span of spans) {
878
+ const ms = endMs(span);
879
+ if (ms !== null && (oldest === null || ms < oldest)) oldest = ms;
880
+ }
881
+ return oldest;
882
+ }
514
883
  var DEADLINE = /* @__PURE__ */ Symbol("deadline");
515
884
  async function raceDeadline(p, ms) {
516
885
  let timer;
@@ -535,10 +904,11 @@ async function shutdownExporter(exporter, ms) {
535
904
  }
536
905
  }
537
906
  var SHUTDOWN_RESERVE_MS = 100;
538
- var SHUTDOWN_BUDGET_MS = 5e3;
907
+ var SHUTDOWN_BUDGET_MS = DEFAULT_SHUTDOWN_TIMEOUT_S * 1e3;
908
+ var FLUSH_BUDGET_MS = 5e3;
539
909
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
540
- function normalizeTimeoutMs(value) {
541
- if (typeof value !== "number" || !Number.isFinite(value)) return SHUTDOWN_BUDGET_MS;
910
+ function normalizeTimeoutMs(value, fallback = FLUSH_BUDGET_MS) {
911
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
542
912
  if (value < 0) return 0;
543
913
  return Math.min(value, MAX_TIMEOUT_MS);
544
914
  }
@@ -683,9 +1053,22 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
683
1053
  transport_refused: 0,
684
1054
  shutdown_residue: 0,
685
1055
  unacknowledged: 0,
686
- quota_exceeded: 0
1056
+ quota_exceeded: 0,
1057
+ retry_exhausted: 0,
1058
+ too_large: 0
687
1059
  };
688
1060
  exportedSpans = 0;
1061
+ /**
1062
+ * Export requests (W2-1c): for the SDK's HTTP exporter one for each HTTP request (each retry
1063
+ * and each half of a split counts), for another exporter one for each `export()` call.
1064
+ */
1065
+ attempts = 0;
1066
+ /**
1067
+ * Spans of a 413 split that `endRetries()` left unsent in the drain of `shutdown()`. They are
1068
+ * counted as `shutdown_residue` in their round; the residue WARNING adds them to its
1069
+ * in-export number.
1070
+ */
1071
+ _drainResidue = 0;
689
1072
  /**
690
1073
  * Spans that the backend acknowledged as REJECTED (the ack's `rejected`). They
691
1074
  * are not stored and are not retried. An exporter without an ack adds nothing.
@@ -798,8 +1181,9 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
798
1181
  * A second call, while the first runs or after it ended, returns the promise
799
1182
  * of the first one. It does not return before the first drain ends.
800
1183
  *
801
- * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
802
- * the values that are not a finite number.
1184
+ * @param timeoutMs - The budget (default `SHUTDOWN_BUDGET_MS`, 10,000 ms; the client passes
1185
+ * its `shutdownTimeoutS`). See `normalizeTimeoutMs` for the values that are not a finite
1186
+ * number.
803
1187
  */
804
1188
  shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
805
1189
  if (!this._started) return this._closing ?? Promise.resolve();
@@ -807,9 +1191,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
807
1191
  return this._closing;
808
1192
  }
809
1193
  async _shutdown(timeoutMs) {
810
- timeoutMs = normalizeTimeoutMs(timeoutMs);
1194
+ timeoutMs = normalizeTimeoutMs(timeoutMs, SHUTDOWN_BUDGET_MS);
811
1195
  this._started = false;
812
1196
  this._drainOpen = true;
1197
+ this._drainResidue = 0;
1198
+ for (const exporter of this._exporters) {
1199
+ try {
1200
+ exporter.endRetries?.();
1201
+ } catch (e) {
1202
+ debug(`Error ending the retries of ${exporter.name}: ${describeThrown(e)}`);
1203
+ }
1204
+ }
813
1205
  if (this._timer) {
814
1206
  clearInterval(this._timer);
815
1207
  this._timer = null;
@@ -848,17 +1240,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
848
1240
  }
849
1241
  }
850
1242
  }
851
- const residue = queued + inFlight;
1243
+ const drained = this._drainResidue;
1244
+ this._drainResidue = 0;
1245
+ const counted = queued + inFlight;
1246
+ const unfinished = inFlight + drained;
1247
+ const residue = counted + drained;
852
1248
  if (residue > 0) {
853
1249
  this._queue.length = 0;
854
- this._recordDropped("shutdown_residue", residue);
1250
+ if (counted > 0) this._recordDropped("shutdown_residue", counted);
855
1251
  if (this._quotaPaused()) {
856
1252
  warn(
857
- `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.`
1253
+ `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${unfinished} 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.`
858
1254
  );
859
1255
  } else {
860
1256
  warn(
861
- `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.`
1257
+ `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${unfinished} 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.`
862
1258
  );
863
1259
  }
864
1260
  }
@@ -882,8 +1278,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
882
1278
  _enqueue(span, exportAtBatchSize) {
883
1279
  if (this._queue.length >= this._maxQueueSize) {
884
1280
  if (this._quotaPaused()) {
885
- const oldest = this._queue.shift();
886
- if (oldest !== void 0) this._forgetRetry(oldest.spanId);
1281
+ const oldest2 = this._queue.shift();
1282
+ if (oldest2 !== void 0) this._forgetRetry(oldest2.spanId);
887
1283
  this._recordDropped("quota_exceeded");
888
1284
  for (const exporter of this._exporters) {
889
1285
  try {
@@ -894,9 +1290,16 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
894
1290
  this._queue.push(span);
895
1291
  return;
896
1292
  }
1293
+ const oldest = this._queue.shift();
1294
+ if (oldest !== void 0) {
1295
+ this._forgetRetry(oldest.spanId);
1296
+ this._queue.push(span);
1297
+ }
897
1298
  this._recordDropped("queue_full");
898
1299
  if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
899
- warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
1300
+ warn(
1301
+ `Span queue full (${this._maxQueueSize}): the oldest queued span is dropped and the new one is kept (reason=queue_full). ${this.droppedSpans} spans dropped so far.`
1302
+ );
900
1303
  }
901
1304
  return;
902
1305
  }
@@ -995,7 +1398,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
995
1398
  * conservative direction on purpose: a false negative costs a caller one
996
1399
  * more flush, a false positive is the defect being fixed.
997
1400
  */
998
- async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
1401
+ async flush(timeoutMs = FLUSH_BUDGET_MS) {
999
1402
  timeoutMs = normalizeTimeoutMs(timeoutMs);
1000
1403
  const deadline = Date.now() + timeoutMs;
1001
1404
  const mark = this._lossMark;
@@ -1015,6 +1418,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1015
1418
  while (this._queue.length > 0 || this._flushing) {
1016
1419
  const remaining = deadline - Date.now();
1017
1420
  if (remaining <= 0) return finish(false);
1421
+ if (!this._started && this._closing !== null) {
1422
+ const closed = await raceDeadline(this._closing.catch(() => void 0), remaining);
1423
+ if (closed === DEADLINE) return finish(false);
1424
+ const held = this._inFlight !== null && !this._inFlight.abandoned;
1425
+ return finish(this._queue.length === 0 && !held);
1426
+ }
1018
1427
  if (!this._flushing && this._queue.length > 0 && this._quotaPaused()) return finish(false);
1019
1428
  if (!this._flushing && this._queue.length > 0) {
1020
1429
  const outcome = await raceDeadline(this._exportBatch(), remaining);
@@ -1027,6 +1436,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1027
1436
  return finish(true);
1028
1437
  }
1029
1438
  getMetrics() {
1439
+ const ends = [];
1440
+ const head = endMs(this._queue[0]);
1441
+ if (head !== null) ends.push(head);
1442
+ const flight = this._inFlight;
1443
+ if (flight !== null && !flight.abandoned && flight.oldestEndMs !== null) ends.push(flight.oldestEndMs);
1444
+ const oldestPendingAgeS = ends.length > 0 ? Math.max(0, (Date.now() - Math.min(...ends)) / 1e3) : 0;
1030
1445
  return {
1031
1446
  exportedSpans: this.exportedSpans,
1032
1447
  rejectedSpans: this.rejectedSpans,
@@ -1036,6 +1451,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1036
1451
  // `droppedSpansByReason.quota_exceeded`, for a reader that wants one key.
1037
1452
  droppedQuota: this.droppedSpansByReason.quota_exceeded,
1038
1453
  failedExports: this.failedExports,
1454
+ /**
1455
+ * W2-1c: export requests (each retry and each half of a 413 split counts), added when the
1456
+ * export call ends: a batch that still retries is not in it yet.
1457
+ */
1458
+ attempts: this.attempts,
1459
+ /**
1460
+ * W2-1c: the age in seconds of the oldest span that is queued or in an export (its end
1461
+ * time to now). 0 when nothing is pending. It grows during an outage, up to the retry
1462
+ * horizon for the batch in an export.
1463
+ */
1464
+ oldestPendingAgeS,
1039
1465
  maskErrors: this.maskErrors,
1040
1466
  queueSize: this._queue.length,
1041
1467
  queueCapacity: this._maxQueueSize,
@@ -1062,6 +1488,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1062
1488
  n -= quota;
1063
1489
  if (n === 0) return;
1064
1490
  }
1491
+ for (const [reason, count] of Object.entries(ack.dropped ?? {})) {
1492
+ if (!DECIDED_DROPS.has(reason) || typeof count !== "number" || !Number.isInteger(count) || count <= 0) {
1493
+ continue;
1494
+ }
1495
+ const take = Math.min(count, n);
1496
+ if (take === 0) continue;
1497
+ this._recordDropped(reason, take);
1498
+ if (reason === "shutdown_residue") this._drainResidue += take;
1499
+ n -= take;
1500
+ }
1501
+ if (n === 0) return;
1065
1502
  const rejected = Math.min(ack.rejected, n);
1066
1503
  const accepted = Math.min(ack.accepted, n - rejected);
1067
1504
  const unacknowledged = n - accepted - rejected;
@@ -1089,13 +1526,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1089
1526
  return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : void 0;
1090
1527
  }
1091
1528
  /**
1092
- * The HTTP requests that the failed round for `batch` really sent (issue #57). `undefined`
1093
- * when the exporter that delivers does not state it, so that the WARNING keeps its "up to"
1094
- * text. NaN when the exporter has no record of the round.
1529
+ * The HTTP requests that `exporter`'s `export()` call for `batch` really sent (issue #57,
1530
+ * W2-1c). `undefined` when the exporter does not state it. NaN when it has no record of the
1531
+ * call, or the read threw.
1095
1532
  */
1096
- _requestsSent(batch) {
1097
- const exporter = this._soleDeliverer();
1098
- if (exporter === void 0 || typeof exporter.takeAttempts !== "function") return void 0;
1533
+ _takeAttempts(exporter, batch) {
1534
+ if (typeof exporter.takeAttempts !== "function") return void 0;
1099
1535
  try {
1100
1536
  const n = exporter.takeAttempts(batch);
1101
1537
  return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : Number.NaN;
@@ -1104,6 +1540,45 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1104
1540
  return Number.NaN;
1105
1541
  }
1106
1542
  }
1543
+ /**
1544
+ * The drop reason of `exporter`'s failed `export()` call for `batch` (W2-1c), or `null`: the
1545
+ * exporter does not classify its failure, and the batch gets the bounded re-queue.
1546
+ */
1547
+ _takeDropReason(exporter, batch) {
1548
+ if (typeof exporter.takeDropReason !== "function") return null;
1549
+ try {
1550
+ const reason = exporter.takeDropReason(batch);
1551
+ return typeof reason === "string" && DECIDED_FAILURES.has(reason) ? reason : null;
1552
+ } catch (e) {
1553
+ debug(`takeDropReason of ${exporter.name} failed: ${describeThrown(e)}`);
1554
+ return null;
1555
+ }
1556
+ }
1557
+ /**
1558
+ * A failed batch whose fate the exporter decided (`takeDropReason`, W2-1c).
1559
+ *
1560
+ * `transport_refused` and `retry_exhausted`: every span is dropped with that reason at once,
1561
+ * and COUNTED. A re-queue would only send it to the same answer, or past the retry horizon.
1562
+ * `shutdown_residue`: `endRetries()` ended the retries in the drain of `shutdown()`. The
1563
+ * batch goes back to the head of the queue, uncounted, and `shutdown()` counts it with the
1564
+ * queue in its one residue WARNING.
1565
+ */
1566
+ _dropDecided(batch, unserializable, reason) {
1567
+ const spans = batch.filter((span) => !unserializable.has(span));
1568
+ if (reason === "shutdown_residue") {
1569
+ this._queue.unshift(...spans);
1570
+ return;
1571
+ }
1572
+ for (const span of spans) this._forgetRetry(span.spanId);
1573
+ this._recordDropped(reason, spans.length);
1574
+ if (reason !== "transport_refused" || spans.length === 0) return;
1575
+ const now = Date.now();
1576
+ if (now - this._lastRefusalWarnAt <= REFUSAL_WARN_WINDOW_MS) return;
1577
+ this._lastRefusalWarnAt = now;
1578
+ warn(
1579
+ `${spans.length} span(s) DISCARDED (reason=transport_refused): the endpoint gave an answer that a retry cannot change, so the batch was sent once. ${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far in this process. This data is gone; check the apiKey and the endpoint.`
1580
+ );
1581
+ }
1107
1582
  /** End the retry tracking of one span (retry-map drain sites 1 and 2 of 3, and the queue drop). */
1108
1583
  _forgetRetry(spanId) {
1109
1584
  this._retryCounts.delete(spanId);
@@ -1141,7 +1616,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1141
1616
  }
1142
1617
  const batch = this._queue.splice(0, take);
1143
1618
  if (batch.length === 0) return 0 /* Empty */;
1144
- flight = { spans: batch, size: batch.length, abandoned: false };
1619
+ flight = { spans: batch, size: batch.length, abandoned: false, oldestEndMs: oldestEndMs(batch) };
1145
1620
  this._inFlight = flight;
1146
1621
  if (!this._traceContent) {
1147
1622
  const stripped = stripContentBatch(batch);
@@ -1158,12 +1633,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1158
1633
  let batchExported = false;
1159
1634
  const anyDelivers = this._exporters.some((e) => e.countsAsDelivery !== false);
1160
1635
  const unserializable = /* @__PURE__ */ new Set();
1636
+ let failReason = null;
1637
+ let failedDecider = false;
1638
+ const sole = this._soleDeliverer();
1639
+ let sent;
1161
1640
  for (const exporter of this._exporters) {
1162
1641
  const decides = !anyDelivers || exporter.countsAsDelivery !== false;
1163
1642
  try {
1164
1643
  const result = await exporter.export(batch);
1165
1644
  if (flight.abandoned) return 2 /* Failed */;
1166
1645
  if (!decides) continue;
1646
+ if (exporter.countsAsDelivery !== false) {
1647
+ const requests = this._takeAttempts(exporter, batch);
1648
+ this.attempts += requests !== void 0 && Number.isFinite(requests) ? requests : 1;
1649
+ if (exporter === sole) sent = requests;
1650
+ }
1167
1651
  for (const span of exporter.takeUnserializable?.(batch) ?? []) unserializable.add(span);
1168
1652
  if (result === "success" /* SUCCESS */) {
1169
1653
  const ack = exporter.takeAck?.(batch) ?? null;
@@ -1176,18 +1660,26 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1176
1660
  }
1177
1661
  } else {
1178
1662
  this.failedExports++;
1663
+ if (!failedDecider && exporter.countsAsDelivery !== false) {
1664
+ failedDecider = true;
1665
+ failReason = this._takeDropReason(exporter, batch);
1666
+ }
1179
1667
  }
1180
1668
  } catch (e) {
1181
1669
  if (flight.abandoned) return 2 /* Failed */;
1182
1670
  if (!decides) continue;
1671
+ if (exporter.countsAsDelivery !== false) this.attempts++;
1183
1672
  this.failedExports++;
1184
1673
  debug(`Export to ${exporter.name} failed: ${describeThrown(e)}`);
1185
1674
  }
1186
1675
  }
1187
1676
  if (unserializable.size > 0) this._recordDropped("unacknowledged", unserializable.size);
1677
+ if (!batchExported && failReason !== null) {
1678
+ this._dropDecided(batch, unserializable, failReason);
1679
+ return 2 /* Failed */;
1680
+ }
1188
1681
  if (!batchExported) {
1189
1682
  let dropped = 0;
1190
- const sent = this._requestsSent(batch);
1191
1683
  const droppedRequests = [];
1192
1684
  const retryable = batch.filter((span) => {
1193
1685
  if (unserializable.has(span)) return false;
@@ -1286,7 +1778,7 @@ function resolveConfig(config) {
1286
1778
  const environment = config?.environment || env.RISICARE_ENVIRONMENT || "development";
1287
1779
  const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
1288
1780
  const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
1289
- const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
1781
+ const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, true);
1290
1782
  const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
1291
1783
  const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
1292
1784
  const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
@@ -1303,6 +1795,12 @@ function resolveConfig(config) {
1303
1795
  const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
1304
1796
  const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
1305
1797
  const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
1798
+ const retryHorizonS = validateSeconds("retryHorizonS", config?.retryHorizonS, DEFAULT_RETRY_HORIZON_S);
1799
+ const shutdownTimeoutS = validateSeconds(
1800
+ "shutdownTimeoutS",
1801
+ config?.shutdownTimeoutS,
1802
+ DEFAULT_SHUTDOWN_TIMEOUT_S
1803
+ );
1306
1804
  let enabled;
1307
1805
  const tracingEnv = config?.enabled === void 0 ? tracingFromEnv(env.RISICARE_TRACING) : void 0;
1308
1806
  if (config?.enabled !== void 0) {
@@ -1327,6 +1825,8 @@ function resolveConfig(config) {
1327
1825
  batchSize,
1328
1826
  batchTimeoutMs,
1329
1827
  maxQueueSize,
1828
+ retryHorizonS,
1829
+ shutdownTimeoutS,
1330
1830
  debug: debug2,
1331
1831
  compress,
1332
1832
  fixRuntime,
@@ -1389,6 +1889,14 @@ function validateSampleRate(value) {
1389
1889
  );
1390
1890
  return 1;
1391
1891
  }
1892
+ function validateSeconds(name, value, defaultValue) {
1893
+ if (value === void 0) return defaultValue;
1894
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
1895
+ warn(
1896
+ `Risicare: ${name}=${String(value)} is not a finite number of seconds of 0 or more; using the default, ${defaultValue} s.`
1897
+ );
1898
+ return defaultValue;
1899
+ }
1392
1900
  function validatePositiveInt(name, value, defaultValue, min, max) {
1393
1901
  let n;
1394
1902
  if (typeof value === "number") {
@@ -1423,6 +1931,178 @@ function validatePositiveInt(name, value, defaultValue, min, max) {
1423
1931
  return Math.floor(n);
1424
1932
  }
1425
1933
 
1934
+ // src/context/storage.ts
1935
+ function storage() {
1936
+ return getContextStorage();
1937
+ }
1938
+ function getContext() {
1939
+ return storage().getStore() ?? {};
1940
+ }
1941
+ function hasContextScope() {
1942
+ return storage().getStore() !== void 0;
1943
+ }
1944
+ function runWithContext(overrides, fn) {
1945
+ const parent = getContext();
1946
+ const merged = { ...parent, ...overrides };
1947
+ return storage().run(merged, fn);
1948
+ }
1949
+ function getCurrentSession() {
1950
+ return getContext().session;
1951
+ }
1952
+ function getCurrentAgent() {
1953
+ return getContext().agent;
1954
+ }
1955
+ function getCurrentSpan() {
1956
+ return getContext().span;
1957
+ }
1958
+ function getCurrentPhase() {
1959
+ return getContext().phase;
1960
+ }
1961
+ function getCurrentSessionId() {
1962
+ return getContext().session?.sessionId;
1963
+ }
1964
+ function getCurrentAgentId() {
1965
+ return getContext().agent?.agentId;
1966
+ }
1967
+ function getCurrentTraceId() {
1968
+ return getContext().span?.traceId;
1969
+ }
1970
+ function getCurrentSpanId() {
1971
+ return getContext().span?.spanId;
1972
+ }
1973
+ function getCurrentContext() {
1974
+ const ctx = getContext();
1975
+ return {
1976
+ session: ctx.session ? {
1977
+ sessionId: ctx.session.sessionId,
1978
+ userId: ctx.session.userId,
1979
+ ...ctx.session.parentSessionId !== void 0 ? { parentSessionId: ctx.session.parentSessionId } : {},
1980
+ ...ctx.session.turnNumber !== void 0 ? { turnNumber: ctx.session.turnNumber } : {},
1981
+ ...ctx.session.metadata !== void 0 ? { metadata: ctx.session.metadata } : {}
1982
+ } : null,
1983
+ agent: ctx.agent ? {
1984
+ agentId: ctx.agent.agentId,
1985
+ agentName: ctx.agent.agentName,
1986
+ agentRole: ctx.agent.agentRole,
1987
+ agentType: ctx.agent.agentType,
1988
+ ...ctx.agent.parentAgentId !== void 0 ? { parentAgentId: ctx.agent.parentAgentId } : {},
1989
+ ...ctx.agent.version !== void 0 ? { version: ctx.agent.version } : {},
1990
+ ...ctx.agent.metadata !== void 0 ? { metadata: ctx.agent.metadata } : {}
1991
+ } : null,
1992
+ span: ctx.span ? { spanId: ctx.span.spanId, traceId: ctx.span.traceId } : null,
1993
+ phase: ctx.phase ?? null
1994
+ };
1995
+ }
1996
+
1997
+ // src/identity.ts
1998
+ var USER_ATTRIBUTE = "user.id";
1999
+ var SESSION_ATTRIBUTE = "session.id";
2000
+ var RELEASE_ATTRIBUTE = "risicare.release";
2001
+ var TAGS_ATTRIBUTE = "tag.tags";
2002
+ var MAX_TRACES = 1e4;
2003
+ var REGISTRY = /* @__PURE__ */ Symbol.for("risicare.identity");
2004
+ function registry() {
2005
+ const g = globalThis;
2006
+ let r = g[REGISTRY];
2007
+ if (r === void 0) {
2008
+ r = { traces: /* @__PURE__ */ new Map(), warned: /* @__PURE__ */ new Set() };
2009
+ g[REGISTRY] = r;
2010
+ }
2011
+ return r;
2012
+ }
2013
+ function warnOnce(helper, text) {
2014
+ const r = registry();
2015
+ if (r.warned.has(helper)) return;
2016
+ r.warned.add(helper);
2017
+ warn(`Risicare: ${helper}() ${text} Nothing was set.`);
2018
+ }
2019
+ function asText(helper, value) {
2020
+ let text;
2021
+ if (typeof value === "string") text = value.trim();
2022
+ else if (typeof value === "number" && Number.isInteger(value)) text = String(value);
2023
+ else {
2024
+ warnOnce(helper, `takes a non-empty string; it got ${value === null ? "null" : typeof value}.`);
2025
+ return null;
2026
+ }
2027
+ if (text === "") {
2028
+ warnOnce(helper, "takes a non-empty string; it got an empty one.");
2029
+ return null;
2030
+ }
2031
+ return text;
2032
+ }
2033
+ function mergeTags(old, add) {
2034
+ const merged = Array.isArray(old) ? old.filter((t) => typeof t === "string") : [];
2035
+ for (const tag of add) if (!merged.includes(tag)) merged.push(tag);
2036
+ return merged;
2037
+ }
2038
+ function set(helper, key, value) {
2039
+ const span = getCurrentSpan();
2040
+ const traceId = span?.traceId;
2041
+ if (span === void 0 || typeof traceId !== "string" || traceId === "") {
2042
+ warnOnce(
2043
+ helper,
2044
+ "was called outside a span, so there is no current trace. Call it inside a span (startSpan(), a decorated function), or use withSession() for a value that must apply before the first span."
2045
+ );
2046
+ return false;
2047
+ }
2048
+ const r = registry();
2049
+ const values = r.traces.get(traceId) ?? {};
2050
+ r.traces.delete(traceId);
2051
+ values[key] = key === TAGS_ATTRIBUTE ? mergeTags(values[key], value) : value;
2052
+ r.traces.set(traceId, values);
2053
+ while (r.traces.size > MAX_TRACES) {
2054
+ const oldest = r.traces.keys().next().value;
2055
+ r.traces.delete(oldest);
2056
+ }
2057
+ span.setAttribute(key, key === TAGS_ATTRIBUTE ? mergeTags(span.attributes[key], value) : value);
2058
+ return true;
2059
+ }
2060
+ function setUser(userId) {
2061
+ const text = asText("setUser", userId);
2062
+ return text !== null && set("setUser", USER_ATTRIBUTE, text);
2063
+ }
2064
+ function setSession(sessionId) {
2065
+ const text = asText("setSession", sessionId);
2066
+ return text !== null && set("setSession", SESSION_ATTRIBUTE, text);
2067
+ }
2068
+ function setRelease(version) {
2069
+ const text = asText("setRelease", version);
2070
+ return text !== null && set("setRelease", RELEASE_ATTRIBUTE, text);
2071
+ }
2072
+ function addTags(tags) {
2073
+ if (!Array.isArray(tags)) {
2074
+ warnOnce("addTags", `takes an array of strings; it got ${tags === null ? "null" : typeof tags}.`);
2075
+ return false;
2076
+ }
2077
+ const clean = [];
2078
+ for (const tag of tags) {
2079
+ const text = typeof tag === "string" ? tag.trim() : "";
2080
+ if (text === "") {
2081
+ warnOnce("addTags", "takes non-empty strings; it got another item, left out.");
2082
+ continue;
2083
+ }
2084
+ if (!clean.includes(text)) clean.push(text);
2085
+ }
2086
+ if (clean.length === 0) return false;
2087
+ return set("addTags", TAGS_ATTRIBUTE, clean);
2088
+ }
2089
+ function applyIdentity(span) {
2090
+ const r = registry();
2091
+ if (r.traces.size === 0) return;
2092
+ const values = r.traces.get(span.traceId);
2093
+ if (values === void 0) return;
2094
+ const attributes = span.attributes;
2095
+ for (const [key, value] of Object.entries(values)) {
2096
+ if (key === TAGS_ATTRIBUTE) {
2097
+ if (!(key in attributes) || Array.isArray(attributes[key])) {
2098
+ attributes[key] = mergeTags(attributes[key], value);
2099
+ }
2100
+ } else if (!(key in attributes)) {
2101
+ attributes[key] = value;
2102
+ }
2103
+ }
2104
+ }
2105
+
1426
2106
  // src/ids.ts
1427
2107
  var import_node_crypto = require("crypto");
1428
2108
  var HEX_REGEX_32 = /^[0-9a-f]{32}$/;
@@ -2247,69 +2927,6 @@ function classifyError(error) {
2247
2927
  return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : "";
2248
2928
  }
2249
2929
 
2250
- // src/context/storage.ts
2251
- function storage() {
2252
- return getContextStorage();
2253
- }
2254
- function getContext() {
2255
- return storage().getStore() ?? {};
2256
- }
2257
- function hasContextScope() {
2258
- return storage().getStore() !== void 0;
2259
- }
2260
- function runWithContext(overrides, fn) {
2261
- const parent = getContext();
2262
- const merged = { ...parent, ...overrides };
2263
- return storage().run(merged, fn);
2264
- }
2265
- function getCurrentSession() {
2266
- return getContext().session;
2267
- }
2268
- function getCurrentAgent() {
2269
- return getContext().agent;
2270
- }
2271
- function getCurrentSpan() {
2272
- return getContext().span;
2273
- }
2274
- function getCurrentPhase() {
2275
- return getContext().phase;
2276
- }
2277
- function getCurrentSessionId() {
2278
- return getContext().session?.sessionId;
2279
- }
2280
- function getCurrentAgentId() {
2281
- return getContext().agent?.agentId;
2282
- }
2283
- function getCurrentTraceId() {
2284
- return getContext().span?.traceId;
2285
- }
2286
- function getCurrentSpanId() {
2287
- return getContext().span?.spanId;
2288
- }
2289
- function getCurrentContext() {
2290
- const ctx = getContext();
2291
- return {
2292
- session: ctx.session ? {
2293
- sessionId: ctx.session.sessionId,
2294
- userId: ctx.session.userId,
2295
- ...ctx.session.parentSessionId !== void 0 ? { parentSessionId: ctx.session.parentSessionId } : {},
2296
- ...ctx.session.turnNumber !== void 0 ? { turnNumber: ctx.session.turnNumber } : {},
2297
- ...ctx.session.metadata !== void 0 ? { metadata: ctx.session.metadata } : {}
2298
- } : null,
2299
- agent: ctx.agent ? {
2300
- agentId: ctx.agent.agentId,
2301
- agentName: ctx.agent.agentName,
2302
- agentRole: ctx.agent.agentRole,
2303
- agentType: ctx.agent.agentType,
2304
- ...ctx.agent.parentAgentId !== void 0 ? { parentAgentId: ctx.agent.parentAgentId } : {},
2305
- ...ctx.agent.version !== void 0 ? { version: ctx.agent.version } : {},
2306
- ...ctx.agent.metadata !== void 0 ? { metadata: ctx.agent.metadata } : {}
2307
- } : null,
2308
- span: ctx.span ? { spanId: ctx.span.spanId, traceId: ctx.span.traceId } : null,
2309
- phase: ctx.phase ?? null
2310
- };
2311
- }
2312
-
2313
2930
  // src/tracer.ts
2314
2931
  function attachErrorCode(span, error) {
2315
2932
  try {
@@ -2330,7 +2947,11 @@ var Tracer = class {
2330
2947
  _serviceName;
2331
2948
  _serviceVersion;
2332
2949
  constructor(config) {
2333
- this._onSpanEnd = config.onSpanEnd;
2950
+ const onSpanEnd = config.onSpanEnd;
2951
+ this._onSpanEnd = (span) => {
2952
+ applyIdentity(span);
2953
+ onSpanEnd(span);
2954
+ };
2334
2955
  this._sampleRate = config.sampleRate ?? 1;
2335
2956
  this._enabled = config.enabled ?? true;
2336
2957
  this._traceContent = config.traceContent ?? false;
@@ -2491,7 +3112,7 @@ function markCancel(span, error) {
2491
3112
  }
2492
3113
 
2493
3114
  // src/version.ts
2494
- var SDK_VERSION = "0.9.2";
3115
+ var SDK_VERSION = "0.11.0";
2495
3116
 
2496
3117
  // src/exporters/quota.ts
2497
3118
  var QUOTA_REASON = "monthly_quota_exceeded";
@@ -2599,12 +3220,18 @@ var QuotaPause = class {
2599
3220
 
2600
3221
  // src/exporters/http.ts
2601
3222
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
2602
- var RETRY_AFTER_CEILING_MS = 1e4;
2603
- var REFUSAL_BACKOFF_BASE_MS = 1e3;
2604
- var REFUSAL_NO_HINT = -1;
2605
3223
  var MISROUTE_WARN_WINDOW_MS = 3e5;
2606
3224
  var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
2607
3225
  var FAILURE_WARN_WINDOW_MS = 3e5;
3226
+ var MAX_TIMER_MS = 2 ** 31 - 1;
3227
+ function validHorizonS(value) {
3228
+ if (value === void 0) return DEFAULT_RETRY_HORIZON_S;
3229
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
3230
+ warn(
3231
+ `Risicare: retryHorizonS=${String(value)} is not a finite number of 0 or more; using the default, ${DEFAULT_RETRY_HORIZON_S} s.`
3232
+ );
3233
+ return DEFAULT_RETRY_HORIZON_S;
3234
+ }
2608
3235
  var HttpExporter = class {
2609
3236
  name = "http";
2610
3237
  _endpoint;
@@ -2614,20 +3241,28 @@ var HttpExporter = class {
2614
3241
  _timeoutMs;
2615
3242
  _maxRetries;
2616
3243
  _compress;
3244
+ _retryHorizonS;
3245
+ /** Total HTTP requests that this exporter sent (each retry and each half of a split counts). */
3246
+ attempts = 0;
2617
3247
  // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
2618
- // a "30-second prod restart" scenario: with default 1s batch flush a
2619
- // 5-failure threshold opens the circuit ~5s into an outage and the 60s
2620
- // cooldown gives the gateway time to come back before the half-open
2621
- // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
3248
+ // a "30-second prod restart" scenario. Since W2-1c only answers that a retry
3249
+ // cannot change move it (see the block above).
2622
3250
  _consecutiveFailures = 0;
2623
3251
  _lastMisrouteWarnAt = -Infinity;
2624
3252
  _lastFailureWarnAt = -Infinity;
3253
+ _lastExhaustedWarnAt = -Infinity;
3254
+ /** "log once" (W2-1c): the WARNING for a `too_large` drop is written one time. */
3255
+ _tooLargeWarned = false;
2625
3256
  /**
2626
3257
  * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
2627
3258
  * 'unknown'). `null` after a success. A new kind in the same outage writes one more
2628
3259
  * WARNING, also inside the window.
2629
3260
  */
2630
3261
  _failureKind = null;
3262
+ /** `endRetries()` was called, and `shutdown()` has not run since. */
3263
+ _noWait = false;
3264
+ /** The wake-ups of the backoff waits in progress. `endRetries()` calls each one. */
3265
+ _waits = /* @__PURE__ */ new Set();
2631
3266
  /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
2632
3267
  _safeEndpoint;
2633
3268
  /** The endpoint holds userinfo. `fetch` refuses such a URL. */
@@ -2638,6 +3273,8 @@ var HttpExporter = class {
2638
3273
  _acks = /* @__PURE__ */ new WeakMap();
2639
3274
  /** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */
2640
3275
  _requests = /* @__PURE__ */ new WeakMap();
3276
+ /** The drop reason of each failed call, by its batch. Read once by `takeDropReason(spans)`. */
3277
+ _dropReasons = /* @__PURE__ */ new WeakMap();
2641
3278
  /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
2642
3279
  noteQuotaDrop(count = 1) {
2643
3280
  this._quota.addDrops(count);
@@ -2662,8 +3299,16 @@ var HttpExporter = class {
2662
3299
  this._projectId = options.projectId;
2663
3300
  this._environment = options.environment;
2664
3301
  this._timeoutMs = options.timeoutMs ?? 5e3;
2665
- this._maxRetries = options.maxRetries ?? 3;
3302
+ let maxRetries = options.maxRetries;
3303
+ if (maxRetries !== void 0 && !(Number.isInteger(maxRetries) && maxRetries >= 1)) {
3304
+ warn(
3305
+ `Risicare: maxRetries=${String(maxRetries)} is not a whole number of 1 or more; the exporter uses no count limit (the retry horizon is the limit).`
3306
+ );
3307
+ maxRetries = void 0;
3308
+ }
3309
+ this._maxRetries = maxRetries;
2666
3310
  this._compress = options.compress ?? false;
3311
+ this._retryHorizonS = validHorizonS(options.retryHorizonS);
2667
3312
  this._safeEndpoint = safeUrl(this._endpoint);
2668
3313
  this._endpointHasCredentials = hasCredentials(this._endpoint);
2669
3314
  }
@@ -2685,16 +3330,18 @@ var HttpExporter = class {
2685
3330
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
2686
3331
  return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
2687
3332
  }
2688
- /** The most requests that one `export()` call sends (`maxRetries`). */
3333
+ /**
3334
+ * The most attempts for one request body (`maxRetries`). `undefined` when no count is set:
3335
+ * the retry horizon is the limit.
3336
+ */
2689
3337
  get attemptsPerExport() {
2690
3338
  return this._maxRetries;
2691
3339
  }
2692
3340
  /**
2693
3341
  * Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears
2694
- * it. This is the number that was sent, not the most that the call may send
2695
- * (`attemptsPerExport`): a 401 or 403 stops the loop after one request, and an open circuit
2696
- * breaker sends none. Returns `null` when no call is on record for `spans`. The answer is
2697
- * kept per batch, as `takeAck` keeps the ack.
3342
+ * it. Each retry and each half of a 413 split counts one; a call that the open circuit
3343
+ * breaker or the quota pause stops sends none. Returns `null` when no call is on record for
3344
+ * `spans`. The answer is kept per batch, as `takeAck` keeps the ack.
2698
3345
  */
2699
3346
  takeAttempts(spans) {
2700
3347
  const n = this._requests.get(spans) ?? null;
@@ -2711,6 +3358,12 @@ var HttpExporter = class {
2711
3358
  this._acks.delete(spans);
2712
3359
  return ack;
2713
3360
  }
3361
+ /** Returns why the `export()` call for `spans` failed (W2-1c), and clears it. See `SpanExporter`. */
3362
+ takeDropReason(spans) {
3363
+ const reason = this._dropReasons.get(spans) ?? null;
3364
+ this._dropReasons.delete(spans);
3365
+ return reason;
3366
+ }
2714
3367
  /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
2715
3368
  takeUnserializable(spans) {
2716
3369
  const bad = this._unserializable.get(spans) ?? [];
@@ -2719,7 +3372,7 @@ var HttpExporter = class {
2719
3372
  }
2720
3373
  /**
2721
3374
  * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
2722
- * request, its retries and its backoff sleep. The batch processor calls it when
3375
+ * request, its retries and its backoff wait. The batch processor calls it when
2723
3376
  * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
2724
3377
  * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
2725
3378
  * logs no WARNING.
@@ -2729,24 +3382,39 @@ var HttpExporter = class {
2729
3382
  else for (const call of this._calls.values()) call.cancel.abort();
2730
3383
  }
2731
3384
  /**
2732
- * Send one batch. The limits are the request timeout and `maxRetries`.
3385
+ * End the retry waits of this exporter until its next `shutdown()`. The batch processor
3386
+ * calls it when `shutdown()` starts. A call that waits for a retry makes one more attempt
3387
+ * at once. An attempt that fails after this is not retried: the call fails with the drop
3388
+ * reason `shutdown_residue`. So a drain against a dead endpoint costs one attempt for each
3389
+ * batch, not the shutdown budget.
3390
+ */
3391
+ endRetries() {
3392
+ this._noWait = true;
3393
+ for (const wake of [...this._waits]) wake();
3394
+ }
3395
+ /**
3396
+ * Send one batch, with the W2-1c retry policy (see the block above the class).
3397
+ *
3398
+ * Resolves SUCCESS when the backend accounted for the batch: `takeAck` has the counts (and
3399
+ * the spans that a 413 split dropped, in `dropped`). Resolves FAILURE when no span was
3400
+ * accounted for: `takeDropReason` then says why, and the batch processor drops the batch
3401
+ * with that reason.
2733
3402
  *
2734
3403
  * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
2735
- * cuts a request that is already sent. A short flush budget that cut the request made a
2736
- * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
2737
- * the server stored the same spans again. Only `abort()` stops the call, and only
3404
+ * cuts a request that is already sent. Only `abort()` stops the call, and only
2738
3405
  * `shutdown()` calls it.
2739
3406
  */
2740
3407
  async export(spans) {
2741
3408
  if (spans.length === 0) return "success" /* SUCCESS */;
2742
3409
  const call = {
2743
3410
  cancel: new AbortController(),
2744
- refusalAfterMs: null,
3411
+ retryAfterS: null,
2745
3412
  misroute: null,
2746
3413
  noRetry: false,
2747
3414
  status: null,
2748
3415
  error: null,
2749
- attempts: 0
3416
+ attempts: 0,
3417
+ ack: null
2750
3418
  };
2751
3419
  this._calls.set(spans, call);
2752
3420
  try {
@@ -2783,83 +3451,236 @@ var HttpExporter = class {
2783
3451
  );
2784
3452
  }
2785
3453
  if (parts.length === 0) return "success" /* SUCCESS */;
2786
- const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
2787
- const now = Date.now();
2788
- let isHalfOpen = false;
2789
- if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
2790
- if (now < this._circuitOpenUntil) {
2791
- return "failure" /* FAILURE */;
3454
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold && Date.now() < this._circuitOpenUntil) {
3455
+ this._dropReasons.set(spans, "transport_refused");
3456
+ return "failure" /* FAILURE */;
3457
+ }
3458
+ const out = { delivered: [], dropped: {}, failed: [], cancelled: false };
3459
+ const start = performance.now();
3460
+ await this._deliver(parts, start, call, out, true);
3461
+ if (cancelled.aborted || out.cancelled) {
3462
+ this._acks.delete(spans);
3463
+ return "failure" /* FAILURE */;
3464
+ }
3465
+ return this._finish(spans, out, call.attempts);
3466
+ }
3467
+ /** The request body for `parts` (the serialized spans of one part of a batch). */
3468
+ _payload(parts) {
3469
+ return `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
3470
+ }
3471
+ /**
3472
+ * Send one part of a batch with the retry policy, and record its outcome in `out`.
3473
+ * `maySplit` is true only for the whole batch: a 413 splits it in two one time. A half
3474
+ * that gets 413 again is dropped as `too_large`.
3475
+ */
3476
+ async _deliver(parts, start, call, out, maySplit) {
3477
+ const n = parts.length;
3478
+ if (!maySplit && this._quota.paused()) {
3479
+ out.delivered.push({ n, ack: { accepted: 0, rejected: 0, quotaDropped: n } });
3480
+ return;
3481
+ }
3482
+ const result = await this._sendWithRetries(this._payload(parts), n, start, call);
3483
+ if (result.kind === "delivered") {
3484
+ out.delivered.push({ n, ack: result.ack });
3485
+ } else if (result.kind === "too_large") {
3486
+ if (maySplit && n > 1) {
3487
+ const mid = Math.ceil(n / 2);
3488
+ debug(`Ingest answered HTTP 413 for ${n} span(s): sending two halves of ${mid} and ${n - mid}`);
3489
+ await this._deliver(parts.slice(0, mid), start, call, out, false);
3490
+ if (!out.cancelled) await this._deliver(parts.slice(mid), start, call, out, false);
3491
+ } else {
3492
+ out.dropped.too_large = (out.dropped.too_large ?? 0) + n;
2792
3493
  }
2793
- isHalfOpen = true;
3494
+ } else if (result.kind === "cancelled") {
3495
+ out.cancelled = true;
3496
+ } else {
3497
+ out.failed.push({ n, reason: result.kind, answer: result.answer });
2794
3498
  }
2795
- const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
2796
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
2797
- call.refusalAfterMs = null;
3499
+ }
3500
+ /** Send one request body until it is delivered or the policy stops. */
3501
+ async _sendWithRetries(body, spansSent, start, call) {
3502
+ const cancelled = call.cancel.signal;
3503
+ let retryNumber = 0;
3504
+ let attemptsHere = 0;
3505
+ for (; ; ) {
3506
+ if (cancelled.aborted) return { kind: "cancelled" };
3507
+ call.retryAfterS = null;
2798
3508
  call.misroute = null;
2799
3509
  call.noRetry = false;
2800
3510
  call.status = null;
2801
3511
  call.error = null;
3512
+ call.ack = null;
2802
3513
  call.attempts++;
2803
- const result = await this._sendRequest(payload, parts.length, call, spans);
2804
- if (cancelled.aborted) {
2805
- this._acks.delete(spans);
2806
- return "failure" /* FAILURE */;
2807
- }
2808
- if (result === "success" /* SUCCESS */) {
2809
- this._consecutiveFailures = 0;
2810
- this._failureKind = null;
2811
- return result;
3514
+ attemptsHere++;
3515
+ this.attempts++;
3516
+ const result = await this._sendRequest(body, spansSent, call);
3517
+ if (cancelled.aborted) return { kind: "cancelled" };
3518
+ if (result === "success" /* SUCCESS */) return { kind: "delivered", ack: call.ack };
3519
+ if (call.status === TOO_LARGE_STATUS) return { kind: "too_large" };
3520
+ const answer = {
3521
+ status: call.status,
3522
+ error: call.error,
3523
+ misroute: call.misroute,
3524
+ zeroAck: call.noRetry,
3525
+ sent: spansSent
3526
+ };
3527
+ if (!this._retryable(call)) return { kind: "transport_refused", answer };
3528
+ if (attemptsHere === RETRY_WARN_AFTER_ATTEMPTS) this._warnOutage(answer, true);
3529
+ if (this._noWait) return { kind: "shutdown_residue", answer };
3530
+ if (this._maxRetries !== void 0 && attemptsHere >= this._maxRetries) {
3531
+ return { kind: "retry_exhausted", answer };
2812
3532
  }
2813
- if (call.misroute !== null || call.noRetry) break;
2814
- if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
2815
- if (attempt < maxAttempts - 1) {
2816
- const refusal = call.refusalAfterMs;
2817
- const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
2818
- await sleep(delay, cancelled);
2819
- if (cancelled.aborted) return "failure" /* FAILURE */;
3533
+ const remainingS = this._retryHorizonS - (performance.now() - start) / 1e3;
3534
+ if (remainingS <= 0) return { kind: "retry_exhausted", answer };
3535
+ const hint = call.retryAfterS;
3536
+ const waitS = hint !== null && hint > 0 ? hint : backoffDelayS(retryNumber, jitter.fraction());
3537
+ const delayS = Math.min(waitS, remainingS);
3538
+ retryNumber++;
3539
+ debug(
3540
+ `Ingest attempt ${attemptsHere} failed (${answer.status ?? answer.error ?? "unknown"}); next attempt in ${delayS.toFixed(2)} s (${Math.round(remainingS)} s of the horizon left)`
3541
+ );
3542
+ await this._retryWait(delayS * 1e3, cancelled);
3543
+ }
3544
+ }
3545
+ /** True when the answer of the last attempt of `call` can change on a retry. */
3546
+ _retryable(call) {
3547
+ if (call.misroute !== null || call.noRetry) return false;
3548
+ if (call.status !== null) return RETRY_STATUSES.has(call.status);
3549
+ if (this._endpointHasCredentials) return false;
3550
+ return call.error !== null;
3551
+ }
3552
+ /**
3553
+ * Wait `ms` before the next attempt. `abort()` and `endRetries()` end the wait at once. The
3554
+ * timer does not keep the process alive: when nothing else runs, `beforeExit` starts the
3555
+ * SDK's `shutdown()`, which ends the wait.
3556
+ */
3557
+ _retryWait(ms, signal) {
3558
+ return new Promise((resolve) => {
3559
+ if (signal.aborted || this._noWait || ms <= 0) return resolve();
3560
+ const done = () => {
3561
+ clearTimeout(timer);
3562
+ signal.removeEventListener("abort", done);
3563
+ this._waits.delete(done);
3564
+ resolve();
3565
+ };
3566
+ const timer = setTimeout(done, Math.min(ms, MAX_TIMER_MS));
3567
+ timer.unref?.();
3568
+ signal.addEventListener("abort", done, { once: true });
3569
+ this._waits.add(done);
3570
+ });
3571
+ }
3572
+ /** Turn the outcome of the parts of one batch into the result of `export()`. */
3573
+ _finish(spans, out, attempts) {
3574
+ const reasons = new Set(out.failed.map((f) => f.reason));
3575
+ if (out.delivered.length === 0 && Object.keys(out.dropped).length === 0 && reasons.size === 1) {
3576
+ const reason = out.failed[0].reason;
3577
+ const nFailed = out.failed.reduce((sum, f) => sum + f.n, 0);
3578
+ this._dropReasons.set(spans, reason);
3579
+ return this._fail(reason, out.failed[out.failed.length - 1].answer, nFailed, attempts);
3580
+ }
3581
+ let ack;
3582
+ if (out.delivered.length === 1 && Object.keys(out.dropped).length === 0 && out.failed.length === 0) {
3583
+ ack = out.delivered[0].ack;
3584
+ } else {
3585
+ let accepted = 0;
3586
+ let rejected = 0;
3587
+ let quotaDropped = 0;
3588
+ for (const part of out.delivered) {
3589
+ accepted += part.ack !== null ? part.ack.accepted : part.n;
3590
+ rejected += part.ack !== null ? part.ack.rejected : 0;
3591
+ quotaDropped += part.ack?.quotaDropped ?? 0;
2820
3592
  }
3593
+ const dropped = { ...out.dropped };
3594
+ for (const f of out.failed) dropped[f.reason] = (dropped[f.reason] ?? 0) + f.n;
3595
+ ack = { accepted, rejected };
3596
+ if (quotaDropped > 0) ack.quotaDropped = quotaDropped;
3597
+ if (Object.keys(dropped).length > 0) ack.dropped = dropped;
2821
3598
  }
2822
- if (call.refusalAfterMs !== null) {
2823
- warn(
2824
- `Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ${call.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.`
2825
- );
3599
+ if (ack !== null) this._acks.set(spans, ack);
3600
+ this._consecutiveFailures = 0;
3601
+ this._failureKind = null;
3602
+ const tooLarge = out.dropped.too_large ?? 0;
3603
+ if (tooLarge > 0) this._warnTooLarge(tooLarge);
3604
+ for (const f of out.failed) {
3605
+ if (f.reason === "retry_exhausted") this._warnExhausted(f.n, attempts, f.answer);
3606
+ }
3607
+ return "success" /* SUCCESS */;
3608
+ }
3609
+ /** End a call in which no span was accounted for. Always returns FAILURE. */
3610
+ _fail(reason, answer, nSpans, attempts) {
3611
+ if (reason === "shutdown_residue") {
3612
+ debug(`Export ended by shutdown after ${attempts} attempt(s)`);
2826
3613
  return "failure" /* FAILURE */;
2827
3614
  }
2828
- const misroute = call.misroute;
2829
- if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
2830
- this._lastMisrouteWarnAt = Date.now();
2831
- warn(
2832
- `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.`
2833
- );
3615
+ if (reason === "retry_exhausted") {
3616
+ if (answer.status === null || !CAPACITY_REFUSAL_STATUSES.has(answer.status)) this._stepBreaker();
3617
+ this._warnOutage(answer, true);
3618
+ this._warnExhausted(nSpans, attempts, answer);
3619
+ return "failure" /* FAILURE */;
2834
3620
  }
3621
+ this._stepBreaker();
3622
+ this._warnOutage(answer, false);
3623
+ return "failure" /* FAILURE */;
3624
+ }
3625
+ /** Count one failed call toward the circuit breaker. */
3626
+ _stepBreaker() {
2835
3627
  this._consecutiveFailures++;
2836
- if (misroute === null && !call.noRetry) {
2837
- const status = call.status;
2838
- const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
2839
- let write = false;
2840
- if (this._consecutiveFailures === 1 || this._failureKind === null) {
2841
- if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
2842
- this._lastFailureWarnAt = Date.now();
2843
- write = true;
2844
- }
2845
- this._failureKind = kind;
2846
- } else if (kind !== this._failureKind) {
2847
- this._failureKind = kind;
2848
- write = true;
2849
- }
2850
- if (write) this._warnOutage(kind, status, call.error);
2851
- }
2852
3628
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
2853
3629
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
2854
3630
  warn(
2855
3631
  `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
2856
3632
  );
2857
3633
  }
2858
- return "failure" /* FAILURE */;
2859
3634
  }
2860
- /** The outage WARNING for one kind of failure. */
2861
- _warnOutage(kind, status, error) {
3635
+ /**
3636
+ * The outage WARNING: at the first failure of an outage, and when its kind changes. At most
3637
+ * one in the window for the first failure; a misroute has its own WARNING, at most one in
3638
+ * the window. `retrying` is true for a retryable answer (written after
3639
+ * `RETRY_WARN_AFTER_ATTEMPTS` failed attempts of one batch, or when its retries end before
3640
+ * that), false for an answer that a retry cannot change (one attempt). The WARNING names the last HTTP status, or the error
3641
+ * code when there was no answer. It never names the key or the response body, and names
3642
+ * the API key as a cause only for a 401 or 403. An ack of 0 and 0 has its WARNING from
3643
+ * `checkAck`.
3644
+ */
3645
+ _warnOutage(answer, retrying) {
3646
+ if (answer.misroute !== null) {
3647
+ if (Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
3648
+ this._lastMisrouteWarnAt = Date.now();
3649
+ warn(
3650
+ `Risicare: spans are NOT reaching ${this._safeEndpoint}. It answered POST /v1/spans with ${answer.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.`
3651
+ );
3652
+ }
3653
+ return;
3654
+ }
3655
+ if (answer.zeroAck) return;
3656
+ const status = answer.status;
3657
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : answer.error !== null ? "none" : "unknown";
3658
+ let write = false;
3659
+ if (this._failureKind === null || !retrying && this._consecutiveFailures === 1) {
3660
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
3661
+ this._lastFailureWarnAt = Date.now();
3662
+ write = true;
3663
+ }
3664
+ this._failureKind = kind;
3665
+ } else if (kind !== this._failureKind) {
3666
+ this._failureKind = kind;
3667
+ write = true;
3668
+ }
3669
+ if (!write) return;
2862
3670
  const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
3671
+ if (retrying) {
3672
+ let limit = `${this._retryHorizonS} s from its first attempt (retryHorizonS)`;
3673
+ if (this._maxRetries !== void 0) limit = `${this._maxRetries} attempt(s) (maxRetries) or ${limit}`;
3674
+ const retryText = `The SDK sends each batch again with a growing wait, for up to ${limit}, and then drops it (reason=retry_exhausted).`;
3675
+ if (kind === "http") {
3676
+ warn(`${where}: it answered HTTP ${status}. ${retryText} Set debug: true to see each attempt.`);
3677
+ } else {
3678
+ warn(
3679
+ `${where}: no answer (${answer.error}). The endpoint cannot be reached, or it did not answer in time. ${retryText} Set debug: true to see each attempt.`
3680
+ );
3681
+ }
3682
+ return;
3683
+ }
2863
3684
  const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
2864
3685
  if (kind === "auth") {
2865
3686
  warn(
@@ -2867,15 +3688,11 @@ var HttpExporter = class {
2867
3688
  );
2868
3689
  } else if (kind === "http") {
2869
3690
  warn(
2870
- `${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.`
3691
+ `${where}: it answered HTTP ${status}. The server did not take the batch, and a retry cannot change that answer. Check the endpoint and the server. ${tail} Set debug: true to see each attempt.`
2871
3692
  );
2872
3693
  } else if (kind === "none" && this._endpointHasCredentials) {
2873
3694
  warn(
2874
- `${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}`
2875
- );
2876
- } else if (kind === "none") {
2877
- warn(
2878
- `${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.`
3695
+ `${where}: no answer (${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}`
2879
3696
  );
2880
3697
  } else {
2881
3698
  warn(
@@ -2883,33 +3700,38 @@ var HttpExporter = class {
2883
3700
  );
2884
3701
  }
2885
3702
  }
3703
+ /** The WARNING for spans dropped as `retry_exhausted`. At most one in the window. */
3704
+ _warnExhausted(nSpans, attempts, answer) {
3705
+ if (Date.now() - this._lastExhaustedWarnAt <= FAILURE_WARN_WINDOW_MS) return;
3706
+ this._lastExhaustedWarnAt = Date.now();
3707
+ const last = answer.status !== null ? `HTTP ${answer.status}` : `no answer (${answer.error})`;
3708
+ const capacity = answer.status !== null && CAPACITY_REFUSAL_STATUSES.has(answer.status) ? " (over capacity)" : "";
3709
+ const limit = this._maxRetries !== void 0 && attempts >= this._maxRetries ? `the maxRetries limit of ${this._maxRetries} attempt(s)` : `the retry horizon of ${this._retryHorizonS} s (retryHorizonS)`;
3710
+ warn(
3711
+ `Risicare: ${nSpans} span(s) DISCARDED (reason=retry_exhausted): ${this._safeEndpoint} did not take them in ${attempts} attempt(s), and ${limit} is used up. The last answer: ${last}${capacity}. A gateway outage that is longer than the retry horizon loses spans. To wait longer, raise retryHorizonS.`
3712
+ );
3713
+ }
3714
+ /** The WARNING for spans dropped as `too_large`. One time for each exporter. */
3715
+ _warnTooLarge(nSpans) {
3716
+ if (this._tooLargeWarned) return;
3717
+ this._tooLargeWarned = true;
3718
+ warn(
3719
+ `Risicare: ${nSpans} span(s) DISCARDED (reason=too_large): ${this._safeEndpoint} answered HTTP 413 (the request is too large) for a batch, and again for a half of it after one split. The SDK does not send these spans again. Make the span attributes smaller. This WARNING is written one time; droppedSpansByReason.too_large has the count.`
3720
+ );
3721
+ }
2886
3722
  /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
2887
3723
  _noteMisroute(call, answer) {
2888
3724
  call.misroute = this._scrub(answer, 300);
2889
3725
  debug(`Ingest misroute: ${call.misroute}`);
2890
3726
  return "failure" /* FAILURE */;
2891
3727
  }
2892
- /**
2893
- * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
2894
- *
2895
- * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
2896
- * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
2897
- * parse.
2898
- */
2899
- _noteRefusal(call, status, retryAfterRaw) {
2900
- if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
2901
- let delay = REFUSAL_NO_HINT;
2902
- if (retryAfterRaw) {
2903
- const secs = Number(retryAfterRaw);
2904
- if (Number.isFinite(secs) && secs >= 0) {
2905
- delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
2906
- }
2907
- }
2908
- call.refusalAfterMs = delay;
2909
- debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
2910
- return true;
3728
+ /** Record the `Retry-After` wait of a retryable answer for the retry loop. */
3729
+ _noteRetryAfter(call, status, retryAfterRaw) {
3730
+ if (!RETRY_STATUSES.has(status)) return;
3731
+ call.retryAfterS = parseRetryAfterS(retryAfterRaw);
3732
+ debug(`Ingest answered HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
2911
3733
  }
2912
- async _sendRequest(body, spansSent, call, spans) {
3734
+ async _sendRequest(body, spansSent, call) {
2913
3735
  const cancelled = call.cancel.signal;
2914
3736
  const timeoutMs = this._timeoutMs;
2915
3737
  const url = `${this._endpoint}/v1/spans`;
@@ -2977,14 +3799,15 @@ var HttpExporter = class {
2977
3799
  } else if (ack.result === "success" /* SUCCESS */) {
2978
3800
  this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
2979
3801
  }
2980
- if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
3802
+ if (ack.result === "success" /* SUCCESS */) call.ack = ack.counts;
2981
3803
  if (ack.final) call.noRetry = true;
2982
3804
  return ack.result;
2983
- } else if (response.status === 408 || response.status === 504) {
3805
+ }
3806
+ this._noteRetryAfter(call, response.status, response.headers?.get?.("Retry-After") ?? null);
3807
+ if (response.status === 408 || response.status === 504) {
2984
3808
  debug(`HTTP export timeout: ${response.status}`);
2985
3809
  return "timeout" /* TIMEOUT */;
2986
3810
  }
2987
- this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
2988
3811
  debug(`HTTP export failed: ${response.status}`);
2989
3812
  return "failure" /* FAILURE */;
2990
3813
  } catch (e) {
@@ -2998,20 +3821,9 @@ var HttpExporter = class {
2998
3821
  }
2999
3822
  }
3000
3823
  shutdown() {
3824
+ this._noWait = false;
3001
3825
  }
3002
3826
  };
3003
- function sleep(ms, signal) {
3004
- return new Promise((resolve) => {
3005
- if (signal?.aborted) return resolve();
3006
- const done = () => {
3007
- clearTimeout(timer);
3008
- signal?.removeEventListener("abort", done);
3009
- resolve();
3010
- };
3011
- const timer = setTimeout(done, ms);
3012
- signal?.addEventListener("abort", done, { once: true });
3013
- });
3014
- }
3015
3827
  function asCount(v) {
3016
3828
  return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
3017
3829
  }
@@ -3510,7 +4322,7 @@ var FixApplier = class {
3510
4322
  const initialDelayMs = cfg.initial_delay_ms ?? cfg.initialDelayMs ?? 1e3;
3511
4323
  const maxDelayMs = cfg.max_delay_ms ?? cfg.maxDelayMs ?? 3e4;
3512
4324
  const exponentialBase = cfg.exponential_base ?? cfg.exponentialBase ?? 2;
3513
- const jitter = cfg.jitter ?? true;
4325
+ const jitter2 = cfg.jitter ?? true;
3514
4326
  const retryOn = cfg.retry_on ?? cfg.retryOn ?? [];
3515
4327
  const result = emptyResult(fix, "retry");
3516
4328
  if (this._config.dryRun) {
@@ -3538,7 +4350,7 @@ var FixApplier = class {
3538
4350
  initialDelayMs * Math.pow(exponentialBase, attempt),
3539
4351
  maxDelayMs
3540
4352
  );
3541
- if (jitter) {
4353
+ if (jitter2) {
3542
4354
  delayMs *= 0.5 + Math.random();
3543
4355
  }
3544
4356
  debug(
@@ -4385,7 +5197,8 @@ var RisicareClient = class {
4385
5197
  apiKey: this.config.apiKey,
4386
5198
  projectId: this.config.projectId || void 0,
4387
5199
  environment: this.config.environment || void 0,
4388
- compress: this.config.compress
5200
+ compress: this.config.compress,
5201
+ retryHorizonS: this.config.retryHorizonS
4389
5202
  });
4390
5203
  }
4391
5204
  this.processor = new BatchSpanProcessor({
@@ -4476,7 +5289,8 @@ var RisicareClient = class {
4476
5289
  }
4477
5290
  this._shutdownHandlers = [];
4478
5291
  endOpenProviderSpans();
4479
- await this.processor.shutdown(timeoutMs);
5292
+ const budgetMs = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) ? timeoutMs : this.config.shutdownTimeoutS * 1e3;
5293
+ await this.processor.shutdown(budgetMs);
4480
5294
  _failWaitingScores(SCORE_DEADLINE_REASON);
4481
5295
  this.isShutdown = true;
4482
5296
  _finalMetrics = this.processor.getMetrics();
@@ -4553,7 +5367,7 @@ var RisicareClient = class {
4553
5367
  const othersAtSignal = process.listeners(signal).filter((l) => l !== handler).length;
4554
5368
  const backstop = setTimeout(
4555
5369
  () => process.exit(128 + signum),
4556
- SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
5370
+ this.config.shutdownTimeoutS * 1e3 + BACKSTOP_MARGIN_MS
4557
5371
  );
4558
5372
  backstop.unref();
4559
5373
  this.shutdown().catch(() => {
@@ -4587,7 +5401,10 @@ function init(config) {
4587
5401
  "environment",
4588
5402
  "serviceName",
4589
5403
  "serviceVersion",
4590
- "sampleRate"
5404
+ "sampleRate",
5405
+ // Capture is on by default (R9): a library's early init() must not
5406
+ // make the program's traceContent: false void in silence.
5407
+ "traceContent"
4591
5408
  ];
4592
5409
  for (const k of checkedKeys) {
4593
5410
  if (incoming[k] !== existing.config[k]) {
@@ -4694,10 +5511,14 @@ function getMetrics() {
4694
5511
  transport_refused: 0,
4695
5512
  shutdown_residue: 0,
4696
5513
  unacknowledged: 0,
4697
- quota_exceeded: 0
5514
+ quota_exceeded: 0,
5515
+ retry_exhausted: 0,
5516
+ too_large: 0
4698
5517
  },
4699
5518
  droppedQuota: 0,
4700
5519
  failedExports: 0,
5520
+ attempts: 0,
5521
+ oldestPendingAgeS: 0,
4701
5522
  queueSize: 0,
4702
5523
  queueCapacity: 0,
4703
5524
  queueUtilization: 0,
@@ -4759,40 +5580,111 @@ function refuseScore(message) {
4759
5580
  const client = getClient();
4760
5581
  if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;
4761
5582
  }
4762
- function score(traceId, name, value, options) {
5583
+ var SCORE_KINDS = ["annotation", "eval", "feedback", "outcome"];
5584
+ var SCORE_NAME_MAX_LEN = 128;
5585
+ var SCORE_STRING_VALUE_MAX_LEN = 256;
5586
+ var SCORE_SESSION_ID_MAX_LEN = 255;
5587
+ var SCORE_COMMENT_MAX_LEN = 4096;
5588
+ var _positionalScoreWarned = false;
5589
+ function warnPositionalScore() {
5590
+ if (_positionalScoreWarned) return;
5591
+ _positionalScoreWarned = true;
5592
+ warn(
5593
+ "Risicare: score(traceId, name, value) with positional arguments is deprecated; this call still sends the score. Use score({ name, value, traceId }). This WARNING is written one time."
5594
+ );
5595
+ }
5596
+ function scoreWireValue(value) {
5597
+ if (typeof value === "boolean") return value;
5598
+ if (typeof value === "number") {
5599
+ if (Number.isFinite(value)) return value;
5600
+ refuseScore(`score: a number value must be finite, not ${value}. The SDK does not send this score.`);
5601
+ return void 0;
5602
+ }
5603
+ if (typeof value === "string") {
5604
+ if (value.length >= 1 && value.length <= SCORE_STRING_VALUE_MAX_LEN) return value;
5605
+ refuseScore(
5606
+ `score: a string value must have 1 to ${SCORE_STRING_VALUE_MAX_LEN} characters, not ${value.length}. The SDK does not send this score.`
5607
+ );
5608
+ return void 0;
5609
+ }
5610
+ refuseScore(
5611
+ `score: the value must be a number, a string or a boolean, not ${value === null ? "null" : typeof value}. The SDK does not send this score.`
5612
+ );
5613
+ return void 0;
5614
+ }
5615
+ function score(first, legacyName, legacyValue, legacyOptions) {
4763
5616
  try {
4764
- const raw = value;
4765
- if (typeof raw === "boolean") value = raw ? 1 : 0;
4766
- if (typeof value !== "number") {
4767
- refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
5617
+ let opts;
5618
+ if (typeof first === "object" && first !== null && arguments.length === 1) {
5619
+ opts = first;
5620
+ } else {
5621
+ warnPositionalScore();
5622
+ opts = {
5623
+ traceId: first,
5624
+ name: legacyName,
5625
+ value: legacyValue,
5626
+ spanId: legacyOptions?.spanId,
5627
+ comment: legacyOptions?.comment
5628
+ };
5629
+ }
5630
+ const { name, traceId, spanId, sessionId } = opts;
5631
+ const kind = opts.kind ?? "annotation";
5632
+ if (typeof name !== "string" || given(name) === void 0) {
5633
+ refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
4768
5634
  return;
4769
5635
  }
4770
- if (!Number.isFinite(value) || value < 0 || value > 1) {
4771
- refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
5636
+ if (name.length > SCORE_NAME_MAX_LEN) {
5637
+ refuseScore(
5638
+ `score: name must be at most ${SCORE_NAME_MAX_LEN} characters, not ${name.length}. The SDK does not send this score.`
5639
+ );
4772
5640
  return;
4773
5641
  }
4774
- if (typeof traceId !== "string" || given(traceId) === void 0) {
5642
+ const value = scoreWireValue(opts.value);
5643
+ if (value === void 0) return;
5644
+ if (traceId !== void 0 && (typeof traceId !== "string" || given(traceId) === void 0)) {
4775
5645
  refuseScore("score: traceId must be a non-empty string. The SDK does not send this score.");
4776
5646
  return;
4777
5647
  }
4778
- if (typeof name !== "string" || given(name) === void 0) {
4779
- refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
5648
+ if (sessionId !== void 0 && (typeof sessionId !== "string" || given(sessionId) === void 0 || sessionId.length > SCORE_SESSION_ID_MAX_LEN)) {
5649
+ refuseScore(
5650
+ `score: sessionId must be a non-empty string of at most ${SCORE_SESSION_ID_MAX_LEN} characters. The SDK does not send this score.`
5651
+ );
5652
+ return;
5653
+ }
5654
+ if (traceId === void 0 && sessionId === void 0) {
5655
+ refuseScore("score: give traceId or sessionId (or both). The SDK does not send this score.");
5656
+ return;
5657
+ }
5658
+ if (spanId && traceId === void 0) {
5659
+ refuseScore("score: spanId needs traceId. The SDK does not send this score.");
5660
+ return;
5661
+ }
5662
+ if (typeof kind !== "string" || !SCORE_KINDS.includes(kind)) {
5663
+ refuseScore(`score: kind must be one of ${SCORE_KINDS.join(", ")}. The SDK does not send this score.`);
4780
5664
  return;
4781
5665
  }
4782
5666
  const client = getClient();
4783
5667
  if (!client?.enabled || !client.config.apiKey) return;
4784
5668
  const endpoint = client.config.apiEndpoint.replace(/\/+$/, "");
4785
5669
  const url = `${endpoint}/v1/scores`;
4786
- let comment = options?.comment;
5670
+ let comment = opts.comment;
4787
5671
  if (comment !== void 0 && client.config.mask) {
4788
5672
  comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
4789
5673
  }
5674
+ if (comment && comment.length > SCORE_COMMENT_MAX_LEN) {
5675
+ refuseScore(
5676
+ `score: comment must be at most ${SCORE_COMMENT_MAX_LEN} characters, not ${comment.length}. The SDK does not send this score.`
5677
+ );
5678
+ return;
5679
+ }
4790
5680
  const body = JSON.stringify({
4791
- trace_id: traceId,
4792
5681
  name,
4793
- score: value,
5682
+ value,
5683
+ kind,
4794
5684
  source: "sdk",
4795
- ...options?.spanId && { span_id: options.spanId },
5685
+ ...traceId !== void 0 && { trace_id: traceId },
5686
+ ...sessionId !== void 0 && { session_id: sessionId },
5687
+ ...spanId && { span_id: spanId },
4796
5688
  ...comment && { comment }
4797
5689
  });
4798
5690
  if (_scoresInFlight >= SCORE_MAX_IN_FLIGHT && _scoreWaiters.length >= SCORE_MAX_WAITING) {
@@ -6011,6 +6903,7 @@ function verifyWebhookSignature(payload, headers, secret, opts = {}) {
6011
6903
  SpanKind,
6012
6904
  SpanStatus,
6013
6905
  WebhookVerificationError,
6906
+ addTags,
6014
6907
  agent,
6015
6908
  disable,
6016
6909
  enable,
@@ -6042,6 +6935,9 @@ function verifyWebhookSignature(payload, headers, secret, opts = {}) {
6042
6935
  reportError,
6043
6936
  score,
6044
6937
  session,
6938
+ setRelease,
6939
+ setSession,
6940
+ setUser,
6045
6941
  shutdown,
6046
6942
  shutdownFixRuntime,
6047
6943
  suppressProviderInstrumentation,