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.js CHANGED
@@ -8,6 +8,35 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
8
  // src/client.ts
9
9
  import { createHash as createHash2 } from "crypto";
10
10
 
11
+ // src/exporters/retry.ts
12
+ var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
13
+ var TOO_LARGE_STATUS = 413;
14
+ var RETRY_BACKOFF_BASE_S = 1;
15
+ var RETRY_BACKOFF_CAP_S = 30;
16
+ var DEFAULT_RETRY_HORIZON_S = 300;
17
+ var DEFAULT_SHUTDOWN_TIMEOUT_S = 10;
18
+ var RETRY_WARN_AFTER_ATTEMPTS = 3;
19
+ var jitter = { fraction: () => Math.random() };
20
+ function backoffDelayS(retryNumber, fraction) {
21
+ const exponent = Math.min(Math.max(retryNumber, 0), 62);
22
+ const ceiling = Math.min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** exponent);
23
+ return Math.min(Math.max(fraction, 0), 1) * ceiling;
24
+ }
25
+ var SECONDS = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
26
+ function parseRetryAfterS(value, nowMs = Date.now()) {
27
+ if (value === null || value === void 0) return null;
28
+ const text = String(value).trim();
29
+ if (text === "") return null;
30
+ if (SECONDS.test(text)) {
31
+ const seconds = Number(text);
32
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
33
+ }
34
+ if (!/[A-Za-z]/.test(text)) return null;
35
+ const when = Date.parse(text);
36
+ if (!Number.isFinite(when)) return null;
37
+ return Math.max(0, (when - nowMs) / 1e3);
38
+ }
39
+
11
40
  // src/globals.ts
12
41
  import { AsyncLocalStorage } from "async_hooks";
13
42
  var G = globalThis;
@@ -51,9 +80,9 @@ function setDebugFlag(enabled) {
51
80
  var PROVIDER_SPANS = /* @__PURE__ */ Symbol.for("risicare.providerSpans");
52
81
  function usableProviderSpanState(s) {
53
82
  if (!s || typeof s !== "object") return false;
54
- const { version, open, registry } = s;
83
+ const { version, open, registry: registry2 } = s;
55
84
  const o = open;
56
- return version === 1 && !!o && typeof o.add === "function" && typeof o.delete === "function" && typeof o[Symbol.iterator] === "function" && (registry === void 0 || typeof registry.register === "function");
85
+ return version === 1 && !!o && typeof o.add === "function" && typeof o.delete === "function" && typeof o[Symbol.iterator] === "function" && (registry2 === void 0 || typeof registry2.register === "function");
57
86
  }
58
87
  function getProviderSpanState() {
59
88
  const found = G[PROVIDER_SPANS];
@@ -281,7 +310,49 @@ var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
281
310
  "audio.transcript",
282
311
  "traceloop.entity.input",
283
312
  // OpenLLMetry
284
- "traceloop.entity.output"
313
+ "traceloop.entity.output",
314
+ // Gateway corpus v2 (R41): the content keys of more frameworks. The same 75
315
+ // keys as `CONTENT_KEYS_EXACT` in the gateway's `content_control.rs`.
316
+ "agent.backstory",
317
+ // OpenInference
318
+ "agent.goal",
319
+ "llm.available_functions",
320
+ "llm.tools",
321
+ "ai.prompt",
322
+ // Vercel AI SDK
323
+ "ai.prompt.messages",
324
+ "ai.prompt.tools",
325
+ "ai.response.files",
326
+ "ai.response.object",
327
+ "ai.response.reasoning",
328
+ "ai.response.text",
329
+ "ai.response.toolCalls",
330
+ "ai.result.object",
331
+ // the older Vercel names
332
+ "ai.result.text",
333
+ "ai.result.toolCalls",
334
+ "ai.toolCall.args",
335
+ "ai.toolCall.result",
336
+ "ai.value",
337
+ // the text of an embedding call
338
+ "ai.values",
339
+ "final_result",
340
+ // Pydantic AI
341
+ "model_request_parameters",
342
+ "pydantic_ai.all_messages",
343
+ "tool_arguments",
344
+ "tool_response",
345
+ "gcp.vertex.agent.data",
346
+ // Google ADK
347
+ "gcp.vertex.agent.llm_request",
348
+ "gcp.vertex.agent.llm_response",
349
+ "gcp.vertex.agent.tool_call_args",
350
+ "gcp.vertex.agent.tool_response",
351
+ "gen_ai.task.input",
352
+ // OpenLLMetry
353
+ "gen_ai.task.output",
354
+ "sk.available_functions"
355
+ // Semantic Kernel
285
356
  ]);
286
357
  var CONTENT_LAST_SEGMENT_IN_CONTEXT = /* @__PURE__ */ new Map([
287
358
  ["function_call_arguments_json", /* @__PURE__ */ new Set()],
@@ -289,7 +360,15 @@ var CONTENT_LAST_SEGMENT_IN_CONTEXT = /* @__PURE__ */ new Map([
289
360
  ["data", /* @__PURE__ */ new Set(["message_content"])],
290
361
  ["url", /* @__PURE__ */ new Set(["image"])],
291
362
  // `image.url` can hold base64 data
292
- ["metadata", /* @__PURE__ */ new Set(["document", "documents"])]
363
+ ["metadata", /* @__PURE__ */ new Set(["document", "documents"])],
364
+ // Gateway corpus v2: a list of tool definitions. The `description` of one tool
365
+ // on a tool span (`tool.description`) is not content; the descriptions in a list are.
366
+ ["description", /* @__PURE__ */ new Set(["definitions", "functions", "tools"])],
367
+ ["json_schema", /* @__PURE__ */ new Set(["tool", "tools"])],
368
+ ["parameters", /* @__PURE__ */ new Set(["definitions", "functions", "tool", "tools"])],
369
+ // Gateway corpus v2: the Mastra span I/O, `mastra.<span type>.input|output`.
370
+ ["input", /* @__PURE__ */ new Set(["mastra"])],
371
+ ["output", /* @__PURE__ */ new Set(["mastra"])]
293
372
  ]);
294
373
  var CONTENT_CONTAINER_SEGMENTS = /* @__PURE__ */ new Set([
295
374
  "message",
@@ -302,8 +381,23 @@ var CONTENT_CONTAINER_SEGMENTS = /* @__PURE__ */ new Set([
302
381
  "documents",
303
382
  "tool_call",
304
383
  "tool_calls",
305
- "function"
384
+ "function",
385
+ // Gateway corpus v2: LiteLLM `gen_ai.completion.{i}.function_call.arguments` and
386
+ // OpenInference `llm.prompts.{i}.prompt.text`.
387
+ "function_call",
388
+ "prompt",
389
+ "prompts"
390
+ ]);
391
+ var CONTENT_FIRST_SEGMENTS = /* @__PURE__ */ new Set(["crewai"]);
392
+ var CONTENT_EVENT_NAMES = /* @__PURE__ */ new Set([
393
+ "gen_ai.assistant.message",
394
+ "gen_ai.choice",
395
+ "gen_ai.system.message",
396
+ "gen_ai.tool.message",
397
+ "gen_ai.user.message"
306
398
  ]);
399
+ var CONTENT_EVENT_PREFIX = "gen_ai.content.";
400
+ var CONTENT_EVENT_KEEP_KEYS = /* @__PURE__ */ new Set(["gen_ai.provider.name", "gen_ai.system"]);
307
401
  var CONTENT_KEYS_KEEP_EXACT = /* @__PURE__ */ new Set([
308
402
  "gen_ai.response.content_type",
309
403
  "gen_ai.response.content_blocks",
@@ -321,10 +415,60 @@ var KEEP_LAST_SEGMENTS = /* @__PURE__ */ new Set([
321
415
  "index",
322
416
  "model",
323
417
  "finish_reason",
324
- "mime_type"
418
+ "mime_type",
419
+ // Gateway v2 at risicare-ingestion main (PR 94): a model name
420
+ // (`crewai.agent.llm`) and the crew process type are not content.
421
+ "llm",
422
+ "process"
325
423
  ]);
326
424
  var KEEP_LAST_SUFFIXES = ["_length", "_tokens", "_count"];
425
+ var CONTENT_IN_JSON_OBJECT = /* @__PURE__ */ new Map([
426
+ [
427
+ "llm.invocation_parameters",
428
+ /* @__PURE__ */ new Set([
429
+ "additionalinstructions",
430
+ // OpenAI assistants run
431
+ "chathistory",
432
+ // Cohere
433
+ "contents",
434
+ // Gemini
435
+ "documents",
436
+ // Cohere RAG
437
+ "functions",
438
+ "input",
439
+ "inputtext",
440
+ // Bedrock Titan
441
+ "instructions",
442
+ "message",
443
+ // Cohere
444
+ "messages",
445
+ "preamble",
446
+ // Cohere
447
+ "prediction",
448
+ // OpenAI predicted output
449
+ "prompt",
450
+ "system",
451
+ // Anthropic
452
+ "systeminstruction",
453
+ // Gemini
454
+ "texts",
455
+ // Cohere embed
456
+ "toolconfig",
457
+ // Gemini
458
+ "tools"
459
+ ])
460
+ ]
461
+ ]);
462
+ var VALUE_RULE_PREFIXES = new Set(
463
+ [...CONTENT_IN_JSON_OBJECT.keys()].flatMap((key) => {
464
+ const segments = key.split(".");
465
+ return segments.slice(1).map((_, i) => segments.slice(0, i + 1).join("."));
466
+ })
467
+ );
327
468
  var CONTENT_OMITTED_MARKER = "<risicare:content-omitted>";
469
+ function hasKeepLastSegment(last) {
470
+ return KEEP_LAST_SEGMENTS.has(last) || KEEP_LAST_SUFFIXES.some((x) => last.endsWith(x));
471
+ }
328
472
  function isContentKey(key) {
329
473
  if (CONTENT_KEYS_KEEP_EXACT.has(key)) return false;
330
474
  if (CONTENT_KEYS_EXACT.has(key) || key.endsWith("_content")) return true;
@@ -334,25 +478,220 @@ function isContentKey(key) {
334
478
  if (context && (context.size === 0 || segments.slice(0, -1).some((s) => context.has(s)))) {
335
479
  return true;
336
480
  }
337
- if (KEEP_LAST_SEGMENTS.has(last) || KEEP_LAST_SUFFIXES.some((x) => last.endsWith(x))) {
481
+ if (hasKeepLastSegment(last)) {
338
482
  return false;
339
483
  }
484
+ if (segments.length > 1 && CONTENT_FIRST_SEGMENTS.has(segments[0])) return true;
340
485
  if (last === "content") return true;
341
486
  if (last === "text" || last === "arguments") {
342
487
  return segments.slice(0, -1).some((s) => CONTENT_CONTAINER_SEGMENTS.has(s));
343
488
  }
344
489
  return false;
345
490
  }
346
- function stripAttributes(attrs) {
491
+ function isContentEvent(name) {
492
+ return CONTENT_EVENT_NAMES.has(name) || name.startsWith(CONTENT_EVENT_PREFIX);
493
+ }
494
+ function isContentEventAttribute(key) {
495
+ if (isContentKey(key)) return true;
496
+ const last = key.slice(key.lastIndexOf(".") + 1);
497
+ return !(CONTENT_KEYS_KEEP_EXACT.has(key) || CONTENT_EVENT_KEEP_KEYS.has(key) || hasKeepLastSegment(last));
498
+ }
499
+ function jsonObjectContentKeys(keyPath, key) {
500
+ for (const [ruleKey, keys] of CONTENT_IN_JSON_OBJECT) {
501
+ if (ruleKey === keyPath || ruleKey === key) return keys;
502
+ }
503
+ return void 0;
504
+ }
505
+ function isJsonObject(value) {
506
+ return typeof value === "object" && value !== null && !Array.isArray(value);
507
+ }
508
+ function flatValueRule(keyPath, key) {
509
+ for (const [ruleKey, keys] of CONTENT_IN_JSON_OBJECT) {
510
+ for (const k of [keyPath, key]) {
511
+ if (k.startsWith(`${ruleKey}.`)) return [k.slice(ruleKey.length + 1), keys];
512
+ }
513
+ }
514
+ return void 0;
515
+ }
516
+ function normalisedKey(key) {
517
+ return key.replace(/_/g, "").replace(/[A-Z]/g, (c) => c.toLowerCase());
518
+ }
519
+ function namesListedKey(key, keys) {
520
+ return key.split(".").some((part) => keys.has(normalisedKey(part)));
521
+ }
522
+ function isKeyRuleText(keyPath, key) {
523
+ return isContentKey(keyPath) || isContentKey(key);
524
+ }
525
+ function startsAsJson(text) {
526
+ return /^[ \t\n\r]*[{[]/.test(text);
527
+ }
528
+ function parseJson(text) {
529
+ return JSON.parse(text, (_key, value) => {
530
+ if (typeof value === "number" && !Number.isFinite(value)) {
531
+ throw new RangeError("not JSON: a number out of range");
532
+ }
533
+ return value;
534
+ });
535
+ }
536
+ function jsonCopy(value) {
537
+ return parseJson(
538
+ JSON.stringify(value, (_key, v) => {
539
+ if (typeof v === "number" && !Number.isFinite(v)) throw new RangeError("not JSON: a non-finite number");
540
+ return v;
541
+ })
542
+ );
543
+ }
544
+ function omitInJsonObject(value, keyPath, keys) {
545
+ try {
546
+ let parsed;
547
+ if (typeof value === "string") parsed = parseJson(value);
548
+ else if (typeof value === "object" && value !== null) parsed = jsonCopy(value);
549
+ if (!isJsonObject(parsed)) return [CONTENT_OMITTED_MARKER, 1];
550
+ let n = 0;
551
+ for (const k of Object.keys(parsed)) {
552
+ const [entry, count] = omitInParameterEntry(parsed[k], `${keyPath}.${k}`, k, keys);
553
+ parsed[k] = entry;
554
+ n += count;
555
+ }
556
+ return [typeof value === "string" ? JSON.stringify(parsed) : parsed, n];
557
+ } catch {
558
+ return [CONTENT_OMITTED_MARKER, 1];
559
+ }
560
+ }
561
+ function omitInParameterEntry(value, keyPath, key, keys) {
562
+ if (namesListedKey(key, keys) || isKeyRuleText(keyPath, key)) return [CONTENT_OMITTED_MARKER, 1];
563
+ return omitInParameter(value, keyPath, keys);
564
+ }
565
+ function omitInParameter(value, path, keys) {
347
566
  let n = 0;
348
- for (const k of Object.keys(attrs)) {
349
- if (isContentKey(k)) {
350
- attrs[k] = CONTENT_OMITTED_MARKER;
351
- n++;
567
+ if (Array.isArray(value)) {
568
+ value.forEach((item, i) => {
569
+ const [entry, count] = omitInParameter(item, `${path}.${i}`, keys);
570
+ value[i] = entry;
571
+ n += count;
572
+ });
573
+ } else if (isJsonObject(value)) {
574
+ for (const k of Object.keys(value)) {
575
+ const [entry, count] = omitInParameterEntry(value[k], `${path}.${k}`, k, keys);
576
+ value[k] = entry;
577
+ n += count;
578
+ }
579
+ } else if (typeof value === "string" && startsAsJson(value)) {
580
+ try {
581
+ const [tree, count] = omitInParameter(parseJson(value), path, keys);
582
+ return [count ? JSON.stringify(tree) : value, count];
583
+ } catch {
584
+ return [CONTENT_OMITTED_MARKER, 1];
585
+ }
586
+ }
587
+ return [value, n];
588
+ }
589
+ function omitFlat(value, keyPath, key, rest, keys) {
590
+ if (namesListedKey(rest, keys) || isKeyRuleText(keyPath, key)) return [CONTENT_OMITTED_MARKER, 1];
591
+ try {
592
+ if (typeof value === "object" && value !== null) {
593
+ const [tree, n] = omitInParameter(jsonCopy(value), keyPath, keys);
594
+ return n ? [tree, n] : [value, 0];
595
+ }
596
+ return omitInParameter(value, keyPath, keys);
597
+ } catch {
598
+ return [CONTENT_OMITTED_MARKER, 1];
599
+ }
600
+ }
601
+ function omitBelow(value, path) {
602
+ const text = typeof value === "string" ? value : value instanceof String ? value.valueOf() : void 0;
603
+ if (text !== void 0) {
604
+ let tree;
605
+ try {
606
+ tree = parseJson(text);
607
+ } catch {
608
+ return startsAsJson(text) ? [CONTENT_OMITTED_MARKER, 1] : [value, 0];
609
+ }
610
+ if (typeof tree !== "object" || tree === null) return [value, 0];
611
+ try {
612
+ const [n, found] = omitBelowParsed(tree, path);
613
+ return found ? [JSON.stringify(tree), n] : [value, 0];
614
+ } catch {
615
+ return [CONTENT_OMITTED_MARKER, 1];
352
616
  }
353
617
  }
618
+ if (typeof value !== "object" || value === null) return [value, 0];
619
+ try {
620
+ const tree = jsonCopy(value);
621
+ const [n, found] = omitBelowParsed(tree, path);
622
+ return found ? [tree, n] : [value, 0];
623
+ } catch {
624
+ return [CONTENT_OMITTED_MARKER, 1];
625
+ }
626
+ }
627
+ function omitBelowParsed(tree, path) {
628
+ let n = 0;
629
+ let found = false;
630
+ if (Array.isArray(tree)) {
631
+ tree.forEach((item, i) => {
632
+ const child = `${path}.${i}`;
633
+ if (!VALUE_RULE_PREFIXES.has(child)) return;
634
+ const [count, below] = omitBelowParsed(item, child);
635
+ n += count;
636
+ found ||= below;
637
+ });
638
+ } else if (isJsonObject(tree)) {
639
+ for (const k of Object.keys(tree)) {
640
+ const child = `${path}.${k}`;
641
+ const keys = jsonObjectContentKeys(child, k);
642
+ const flat = keys ? void 0 : flatValueRule(child, k);
643
+ if (keys) {
644
+ const [entry, count] = omitInJsonObject(tree[k], child, keys);
645
+ tree[k] = entry;
646
+ n += count;
647
+ found = true;
648
+ } else if (flat) {
649
+ const [entry, count] = omitFlat(tree[k], child, k, flat[0], flat[1]);
650
+ tree[k] = entry;
651
+ n += count;
652
+ found = true;
653
+ } else if (VALUE_RULE_PREFIXES.has(child)) {
654
+ const [count, below] = omitBelowParsed(tree[k], child);
655
+ n += count;
656
+ found ||= below;
657
+ }
658
+ }
659
+ }
660
+ return [n, found];
661
+ }
662
+ function reachesValueRule(key) {
663
+ return CONTENT_IN_JSON_OBJECT.has(key) || VALUE_RULE_PREFIXES.has(key) || flatValueRule(key, key) !== void 0;
664
+ }
665
+ function stripAttributes(attrs, rule = isContentKey) {
666
+ let n = 0;
667
+ for (const k of Object.keys(attrs)) {
668
+ const keys = rule === isContentKey ? jsonObjectContentKeys(k, k) : void 0;
669
+ const flat = rule === isContentKey && !keys ? flatValueRule(k, k) : void 0;
670
+ let result;
671
+ if (keys) result = omitInJsonObject(attrs[k], k, keys);
672
+ else if (flat) result = omitFlat(attrs[k], k, k, flat[0], flat[1]);
673
+ else if (rule(k)) result = [CONTENT_OMITTED_MARKER, 1];
674
+ else if (VALUE_RULE_PREFIXES.has(k)) result = omitBelow(attrs[k], k);
675
+ else continue;
676
+ attrs[k] = result[0];
677
+ n += result[1];
678
+ }
354
679
  return n;
355
680
  }
681
+ function stripOwned(holder, rule = isContentKey) {
682
+ const attrs = holder.attributes;
683
+ if (!attrs || typeof attrs !== "object" || !Object.keys(attrs).some((k) => rule(k) || reachesValueRule(k))) {
684
+ return 0;
685
+ }
686
+ const copy = { ...attrs };
687
+ try {
688
+ holder.attributes = copy;
689
+ } catch {
690
+ return stripAttributes(attrs, rule);
691
+ }
692
+ if (holder.attributes !== copy) return stripAttributes(attrs, rule);
693
+ return stripAttributes(copy, rule);
694
+ }
356
695
  function stripContent(span) {
357
696
  let stripped = 0;
358
697
  if (span.attributes && typeof span.attributes === "object") {
@@ -361,14 +700,15 @@ function stripContent(span) {
361
700
  if (Array.isArray(span.events)) {
362
701
  for (const event of span.events) {
363
702
  if (event?.attributes && typeof event.attributes === "object") {
364
- stripped += stripAttributes(event.attributes);
703
+ const messageEvent = typeof event.name === "string" && isContentEvent(event.name);
704
+ stripped += stripOwned(event, messageEvent ? isContentEventAttribute : isContentKey);
365
705
  }
366
706
  }
367
707
  }
368
708
  if (Array.isArray(span.links)) {
369
709
  for (const link of span.links) {
370
710
  if (link?.attributes && typeof link.attributes === "object") {
371
- stripped += stripAttributes(link.attributes);
711
+ stripped += stripOwned(link);
372
712
  }
373
713
  }
374
714
  }
@@ -425,6 +765,31 @@ function warnMaskSlow(spanCount, elapsedMs) {
425
765
  }
426
766
 
427
767
  // src/exporters/batch.ts
768
+ var DECIDED_FAILURES = /* @__PURE__ */ new Set([
769
+ "transport_refused",
770
+ "retry_exhausted",
771
+ "shutdown_residue"
772
+ ]);
773
+ var DECIDED_DROPS = /* @__PURE__ */ new Set([
774
+ "transport_refused",
775
+ "retry_exhausted",
776
+ "shutdown_residue",
777
+ "too_large"
778
+ ]);
779
+ function endMs(span) {
780
+ const end = span?.endTime;
781
+ if (typeof end !== "string") return null;
782
+ const ms = Date.parse(end);
783
+ return Number.isFinite(ms) ? ms : null;
784
+ }
785
+ function oldestEndMs(spans) {
786
+ let oldest = null;
787
+ for (const span of spans) {
788
+ const ms = endMs(span);
789
+ if (ms !== null && (oldest === null || ms < oldest)) oldest = ms;
790
+ }
791
+ return oldest;
792
+ }
428
793
  var DEADLINE = /* @__PURE__ */ Symbol("deadline");
429
794
  async function raceDeadline(p, ms) {
430
795
  let timer;
@@ -449,10 +814,11 @@ async function shutdownExporter(exporter, ms) {
449
814
  }
450
815
  }
451
816
  var SHUTDOWN_RESERVE_MS = 100;
452
- var SHUTDOWN_BUDGET_MS = 5e3;
817
+ var SHUTDOWN_BUDGET_MS = DEFAULT_SHUTDOWN_TIMEOUT_S * 1e3;
818
+ var FLUSH_BUDGET_MS = 5e3;
453
819
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
454
- function normalizeTimeoutMs(value) {
455
- if (typeof value !== "number" || !Number.isFinite(value)) return SHUTDOWN_BUDGET_MS;
820
+ function normalizeTimeoutMs(value, fallback = FLUSH_BUDGET_MS) {
821
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
456
822
  if (value < 0) return 0;
457
823
  return Math.min(value, MAX_TIMEOUT_MS);
458
824
  }
@@ -597,9 +963,22 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
597
963
  transport_refused: 0,
598
964
  shutdown_residue: 0,
599
965
  unacknowledged: 0,
600
- quota_exceeded: 0
966
+ quota_exceeded: 0,
967
+ retry_exhausted: 0,
968
+ too_large: 0
601
969
  };
602
970
  exportedSpans = 0;
971
+ /**
972
+ * Export requests (W2-1c): for the SDK's HTTP exporter one for each HTTP request (each retry
973
+ * and each half of a split counts), for another exporter one for each `export()` call.
974
+ */
975
+ attempts = 0;
976
+ /**
977
+ * Spans of a 413 split that `endRetries()` left unsent in the drain of `shutdown()`. They are
978
+ * counted as `shutdown_residue` in their round; the residue WARNING adds them to its
979
+ * in-export number.
980
+ */
981
+ _drainResidue = 0;
603
982
  /**
604
983
  * Spans that the backend acknowledged as REJECTED (the ack's `rejected`). They
605
984
  * are not stored and are not retried. An exporter without an ack adds nothing.
@@ -712,8 +1091,9 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
712
1091
  * A second call, while the first runs or after it ended, returns the promise
713
1092
  * of the first one. It does not return before the first drain ends.
714
1093
  *
715
- * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
716
- * the values that are not a finite number.
1094
+ * @param timeoutMs - The budget (default `SHUTDOWN_BUDGET_MS`, 10,000 ms; the client passes
1095
+ * its `shutdownTimeoutS`). See `normalizeTimeoutMs` for the values that are not a finite
1096
+ * number.
717
1097
  */
718
1098
  shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
719
1099
  if (!this._started) return this._closing ?? Promise.resolve();
@@ -721,9 +1101,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
721
1101
  return this._closing;
722
1102
  }
723
1103
  async _shutdown(timeoutMs) {
724
- timeoutMs = normalizeTimeoutMs(timeoutMs);
1104
+ timeoutMs = normalizeTimeoutMs(timeoutMs, SHUTDOWN_BUDGET_MS);
725
1105
  this._started = false;
726
1106
  this._drainOpen = true;
1107
+ this._drainResidue = 0;
1108
+ for (const exporter of this._exporters) {
1109
+ try {
1110
+ exporter.endRetries?.();
1111
+ } catch (e) {
1112
+ debug(`Error ending the retries of ${exporter.name}: ${describeThrown(e)}`);
1113
+ }
1114
+ }
727
1115
  if (this._timer) {
728
1116
  clearInterval(this._timer);
729
1117
  this._timer = null;
@@ -762,17 +1150,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
762
1150
  }
763
1151
  }
764
1152
  }
765
- const residue = queued + inFlight;
1153
+ const drained = this._drainResidue;
1154
+ this._drainResidue = 0;
1155
+ const counted = queued + inFlight;
1156
+ const unfinished = inFlight + drained;
1157
+ const residue = counted + drained;
766
1158
  if (residue > 0) {
767
1159
  this._queue.length = 0;
768
- this._recordDropped("shutdown_residue", residue);
1160
+ if (counted > 0) this._recordDropped("shutdown_residue", counted);
769
1161
  if (this._quotaPaused()) {
770
1162
  warn(
771
- `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.`
1163
+ `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.`
772
1164
  );
773
1165
  } else {
774
1166
  warn(
775
- `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.`
1167
+ `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.`
776
1168
  );
777
1169
  }
778
1170
  }
@@ -796,8 +1188,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
796
1188
  _enqueue(span, exportAtBatchSize) {
797
1189
  if (this._queue.length >= this._maxQueueSize) {
798
1190
  if (this._quotaPaused()) {
799
- const oldest = this._queue.shift();
800
- if (oldest !== void 0) this._forgetRetry(oldest.spanId);
1191
+ const oldest2 = this._queue.shift();
1192
+ if (oldest2 !== void 0) this._forgetRetry(oldest2.spanId);
801
1193
  this._recordDropped("quota_exceeded");
802
1194
  for (const exporter of this._exporters) {
803
1195
  try {
@@ -808,9 +1200,16 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
808
1200
  this._queue.push(span);
809
1201
  return;
810
1202
  }
1203
+ const oldest = this._queue.shift();
1204
+ if (oldest !== void 0) {
1205
+ this._forgetRetry(oldest.spanId);
1206
+ this._queue.push(span);
1207
+ }
811
1208
  this._recordDropped("queue_full");
812
1209
  if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
813
- warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
1210
+ warn(
1211
+ `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.`
1212
+ );
814
1213
  }
815
1214
  return;
816
1215
  }
@@ -909,7 +1308,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
909
1308
  * conservative direction on purpose: a false negative costs a caller one
910
1309
  * more flush, a false positive is the defect being fixed.
911
1310
  */
912
- async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
1311
+ async flush(timeoutMs = FLUSH_BUDGET_MS) {
913
1312
  timeoutMs = normalizeTimeoutMs(timeoutMs);
914
1313
  const deadline = Date.now() + timeoutMs;
915
1314
  const mark = this._lossMark;
@@ -929,6 +1328,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
929
1328
  while (this._queue.length > 0 || this._flushing) {
930
1329
  const remaining = deadline - Date.now();
931
1330
  if (remaining <= 0) return finish(false);
1331
+ if (!this._started && this._closing !== null) {
1332
+ const closed = await raceDeadline(this._closing.catch(() => void 0), remaining);
1333
+ if (closed === DEADLINE) return finish(false);
1334
+ const held = this._inFlight !== null && !this._inFlight.abandoned;
1335
+ return finish(this._queue.length === 0 && !held);
1336
+ }
932
1337
  if (!this._flushing && this._queue.length > 0 && this._quotaPaused()) return finish(false);
933
1338
  if (!this._flushing && this._queue.length > 0) {
934
1339
  const outcome = await raceDeadline(this._exportBatch(), remaining);
@@ -941,6 +1346,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
941
1346
  return finish(true);
942
1347
  }
943
1348
  getMetrics() {
1349
+ const ends = [];
1350
+ const head = endMs(this._queue[0]);
1351
+ if (head !== null) ends.push(head);
1352
+ const flight = this._inFlight;
1353
+ if (flight !== null && !flight.abandoned && flight.oldestEndMs !== null) ends.push(flight.oldestEndMs);
1354
+ const oldestPendingAgeS = ends.length > 0 ? Math.max(0, (Date.now() - Math.min(...ends)) / 1e3) : 0;
944
1355
  return {
945
1356
  exportedSpans: this.exportedSpans,
946
1357
  rejectedSpans: this.rejectedSpans,
@@ -950,6 +1361,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
950
1361
  // `droppedSpansByReason.quota_exceeded`, for a reader that wants one key.
951
1362
  droppedQuota: this.droppedSpansByReason.quota_exceeded,
952
1363
  failedExports: this.failedExports,
1364
+ /**
1365
+ * W2-1c: export requests (each retry and each half of a 413 split counts), added when the
1366
+ * export call ends: a batch that still retries is not in it yet.
1367
+ */
1368
+ attempts: this.attempts,
1369
+ /**
1370
+ * W2-1c: the age in seconds of the oldest span that is queued or in an export (its end
1371
+ * time to now). 0 when nothing is pending. It grows during an outage, up to the retry
1372
+ * horizon for the batch in an export.
1373
+ */
1374
+ oldestPendingAgeS,
953
1375
  maskErrors: this.maskErrors,
954
1376
  queueSize: this._queue.length,
955
1377
  queueCapacity: this._maxQueueSize,
@@ -976,6 +1398,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
976
1398
  n -= quota;
977
1399
  if (n === 0) return;
978
1400
  }
1401
+ for (const [reason, count] of Object.entries(ack.dropped ?? {})) {
1402
+ if (!DECIDED_DROPS.has(reason) || typeof count !== "number" || !Number.isInteger(count) || count <= 0) {
1403
+ continue;
1404
+ }
1405
+ const take = Math.min(count, n);
1406
+ if (take === 0) continue;
1407
+ this._recordDropped(reason, take);
1408
+ if (reason === "shutdown_residue") this._drainResidue += take;
1409
+ n -= take;
1410
+ }
1411
+ if (n === 0) return;
979
1412
  const rejected = Math.min(ack.rejected, n);
980
1413
  const accepted = Math.min(ack.accepted, n - rejected);
981
1414
  const unacknowledged = n - accepted - rejected;
@@ -1003,13 +1436,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1003
1436
  return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : void 0;
1004
1437
  }
1005
1438
  /**
1006
- * The HTTP requests that the failed round for `batch` really sent (issue #57). `undefined`
1007
- * when the exporter that delivers does not state it, so that the WARNING keeps its "up to"
1008
- * text. NaN when the exporter has no record of the round.
1439
+ * The HTTP requests that `exporter`'s `export()` call for `batch` really sent (issue #57,
1440
+ * W2-1c). `undefined` when the exporter does not state it. NaN when it has no record of the
1441
+ * call, or the read threw.
1009
1442
  */
1010
- _requestsSent(batch) {
1011
- const exporter = this._soleDeliverer();
1012
- if (exporter === void 0 || typeof exporter.takeAttempts !== "function") return void 0;
1443
+ _takeAttempts(exporter, batch) {
1444
+ if (typeof exporter.takeAttempts !== "function") return void 0;
1013
1445
  try {
1014
1446
  const n = exporter.takeAttempts(batch);
1015
1447
  return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : Number.NaN;
@@ -1018,6 +1450,45 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1018
1450
  return Number.NaN;
1019
1451
  }
1020
1452
  }
1453
+ /**
1454
+ * The drop reason of `exporter`'s failed `export()` call for `batch` (W2-1c), or `null`: the
1455
+ * exporter does not classify its failure, and the batch gets the bounded re-queue.
1456
+ */
1457
+ _takeDropReason(exporter, batch) {
1458
+ if (typeof exporter.takeDropReason !== "function") return null;
1459
+ try {
1460
+ const reason = exporter.takeDropReason(batch);
1461
+ return typeof reason === "string" && DECIDED_FAILURES.has(reason) ? reason : null;
1462
+ } catch (e) {
1463
+ debug(`takeDropReason of ${exporter.name} failed: ${describeThrown(e)}`);
1464
+ return null;
1465
+ }
1466
+ }
1467
+ /**
1468
+ * A failed batch whose fate the exporter decided (`takeDropReason`, W2-1c).
1469
+ *
1470
+ * `transport_refused` and `retry_exhausted`: every span is dropped with that reason at once,
1471
+ * and COUNTED. A re-queue would only send it to the same answer, or past the retry horizon.
1472
+ * `shutdown_residue`: `endRetries()` ended the retries in the drain of `shutdown()`. The
1473
+ * batch goes back to the head of the queue, uncounted, and `shutdown()` counts it with the
1474
+ * queue in its one residue WARNING.
1475
+ */
1476
+ _dropDecided(batch, unserializable, reason) {
1477
+ const spans = batch.filter((span) => !unserializable.has(span));
1478
+ if (reason === "shutdown_residue") {
1479
+ this._queue.unshift(...spans);
1480
+ return;
1481
+ }
1482
+ for (const span of spans) this._forgetRetry(span.spanId);
1483
+ this._recordDropped(reason, spans.length);
1484
+ if (reason !== "transport_refused" || spans.length === 0) return;
1485
+ const now = Date.now();
1486
+ if (now - this._lastRefusalWarnAt <= REFUSAL_WARN_WINDOW_MS) return;
1487
+ this._lastRefusalWarnAt = now;
1488
+ warn(
1489
+ `${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.`
1490
+ );
1491
+ }
1021
1492
  /** End the retry tracking of one span (retry-map drain sites 1 and 2 of 3, and the queue drop). */
1022
1493
  _forgetRetry(spanId) {
1023
1494
  this._retryCounts.delete(spanId);
@@ -1055,7 +1526,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1055
1526
  }
1056
1527
  const batch = this._queue.splice(0, take);
1057
1528
  if (batch.length === 0) return 0 /* Empty */;
1058
- flight = { spans: batch, size: batch.length, abandoned: false };
1529
+ flight = { spans: batch, size: batch.length, abandoned: false, oldestEndMs: oldestEndMs(batch) };
1059
1530
  this._inFlight = flight;
1060
1531
  if (!this._traceContent) {
1061
1532
  const stripped = stripContentBatch(batch);
@@ -1072,12 +1543,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1072
1543
  let batchExported = false;
1073
1544
  const anyDelivers = this._exporters.some((e) => e.countsAsDelivery !== false);
1074
1545
  const unserializable = /* @__PURE__ */ new Set();
1546
+ let failReason = null;
1547
+ let failedDecider = false;
1548
+ const sole = this._soleDeliverer();
1549
+ let sent;
1075
1550
  for (const exporter of this._exporters) {
1076
1551
  const decides = !anyDelivers || exporter.countsAsDelivery !== false;
1077
1552
  try {
1078
1553
  const result = await exporter.export(batch);
1079
1554
  if (flight.abandoned) return 2 /* Failed */;
1080
1555
  if (!decides) continue;
1556
+ if (exporter.countsAsDelivery !== false) {
1557
+ const requests = this._takeAttempts(exporter, batch);
1558
+ this.attempts += requests !== void 0 && Number.isFinite(requests) ? requests : 1;
1559
+ if (exporter === sole) sent = requests;
1560
+ }
1081
1561
  for (const span of exporter.takeUnserializable?.(batch) ?? []) unserializable.add(span);
1082
1562
  if (result === "success" /* SUCCESS */) {
1083
1563
  const ack = exporter.takeAck?.(batch) ?? null;
@@ -1090,18 +1570,26 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1090
1570
  }
1091
1571
  } else {
1092
1572
  this.failedExports++;
1573
+ if (!failedDecider && exporter.countsAsDelivery !== false) {
1574
+ failedDecider = true;
1575
+ failReason = this._takeDropReason(exporter, batch);
1576
+ }
1093
1577
  }
1094
1578
  } catch (e) {
1095
1579
  if (flight.abandoned) return 2 /* Failed */;
1096
1580
  if (!decides) continue;
1581
+ if (exporter.countsAsDelivery !== false) this.attempts++;
1097
1582
  this.failedExports++;
1098
1583
  debug(`Export to ${exporter.name} failed: ${describeThrown(e)}`);
1099
1584
  }
1100
1585
  }
1101
1586
  if (unserializable.size > 0) this._recordDropped("unacknowledged", unserializable.size);
1587
+ if (!batchExported && failReason !== null) {
1588
+ this._dropDecided(batch, unserializable, failReason);
1589
+ return 2 /* Failed */;
1590
+ }
1102
1591
  if (!batchExported) {
1103
1592
  let dropped = 0;
1104
- const sent = this._requestsSent(batch);
1105
1593
  const droppedRequests = [];
1106
1594
  const retryable = batch.filter((span) => {
1107
1595
  if (unserializable.has(span)) return false;
@@ -1200,7 +1688,7 @@ function resolveConfig(config) {
1200
1688
  const environment = config?.environment || env.RISICARE_ENVIRONMENT || "development";
1201
1689
  const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
1202
1690
  const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
1203
- const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
1691
+ const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, true);
1204
1692
  const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
1205
1693
  const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
1206
1694
  const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
@@ -1217,6 +1705,12 @@ function resolveConfig(config) {
1217
1705
  const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
1218
1706
  const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
1219
1707
  const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
1708
+ const retryHorizonS = validateSeconds("retryHorizonS", config?.retryHorizonS, DEFAULT_RETRY_HORIZON_S);
1709
+ const shutdownTimeoutS = validateSeconds(
1710
+ "shutdownTimeoutS",
1711
+ config?.shutdownTimeoutS,
1712
+ DEFAULT_SHUTDOWN_TIMEOUT_S
1713
+ );
1220
1714
  let enabled;
1221
1715
  const tracingEnv = config?.enabled === void 0 ? tracingFromEnv(env.RISICARE_TRACING) : void 0;
1222
1716
  if (config?.enabled !== void 0) {
@@ -1241,6 +1735,8 @@ function resolveConfig(config) {
1241
1735
  batchSize,
1242
1736
  batchTimeoutMs,
1243
1737
  maxQueueSize,
1738
+ retryHorizonS,
1739
+ shutdownTimeoutS,
1244
1740
  debug: debug2,
1245
1741
  compress,
1246
1742
  fixRuntime,
@@ -1303,6 +1799,14 @@ function validateSampleRate(value) {
1303
1799
  );
1304
1800
  return 1;
1305
1801
  }
1802
+ function validateSeconds(name, value, defaultValue) {
1803
+ if (value === void 0) return defaultValue;
1804
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
1805
+ warn(
1806
+ `Risicare: ${name}=${String(value)} is not a finite number of seconds of 0 or more; using the default, ${defaultValue} s.`
1807
+ );
1808
+ return defaultValue;
1809
+ }
1306
1810
  function validatePositiveInt(name, value, defaultValue, min, max) {
1307
1811
  let n;
1308
1812
  if (typeof value === "number") {
@@ -1337,6 +1841,178 @@ function validatePositiveInt(name, value, defaultValue, min, max) {
1337
1841
  return Math.floor(n);
1338
1842
  }
1339
1843
 
1844
+ // src/context/storage.ts
1845
+ function storage() {
1846
+ return getContextStorage();
1847
+ }
1848
+ function getContext() {
1849
+ return storage().getStore() ?? {};
1850
+ }
1851
+ function hasContextScope() {
1852
+ return storage().getStore() !== void 0;
1853
+ }
1854
+ function runWithContext(overrides, fn) {
1855
+ const parent = getContext();
1856
+ const merged = { ...parent, ...overrides };
1857
+ return storage().run(merged, fn);
1858
+ }
1859
+ function getCurrentSession() {
1860
+ return getContext().session;
1861
+ }
1862
+ function getCurrentAgent() {
1863
+ return getContext().agent;
1864
+ }
1865
+ function getCurrentSpan() {
1866
+ return getContext().span;
1867
+ }
1868
+ function getCurrentPhase() {
1869
+ return getContext().phase;
1870
+ }
1871
+ function getCurrentSessionId() {
1872
+ return getContext().session?.sessionId;
1873
+ }
1874
+ function getCurrentAgentId() {
1875
+ return getContext().agent?.agentId;
1876
+ }
1877
+ function getCurrentTraceId() {
1878
+ return getContext().span?.traceId;
1879
+ }
1880
+ function getCurrentSpanId() {
1881
+ return getContext().span?.spanId;
1882
+ }
1883
+ function getCurrentContext() {
1884
+ const ctx = getContext();
1885
+ return {
1886
+ session: ctx.session ? {
1887
+ sessionId: ctx.session.sessionId,
1888
+ userId: ctx.session.userId,
1889
+ ...ctx.session.parentSessionId !== void 0 ? { parentSessionId: ctx.session.parentSessionId } : {},
1890
+ ...ctx.session.turnNumber !== void 0 ? { turnNumber: ctx.session.turnNumber } : {},
1891
+ ...ctx.session.metadata !== void 0 ? { metadata: ctx.session.metadata } : {}
1892
+ } : null,
1893
+ agent: ctx.agent ? {
1894
+ agentId: ctx.agent.agentId,
1895
+ agentName: ctx.agent.agentName,
1896
+ agentRole: ctx.agent.agentRole,
1897
+ agentType: ctx.agent.agentType,
1898
+ ...ctx.agent.parentAgentId !== void 0 ? { parentAgentId: ctx.agent.parentAgentId } : {},
1899
+ ...ctx.agent.version !== void 0 ? { version: ctx.agent.version } : {},
1900
+ ...ctx.agent.metadata !== void 0 ? { metadata: ctx.agent.metadata } : {}
1901
+ } : null,
1902
+ span: ctx.span ? { spanId: ctx.span.spanId, traceId: ctx.span.traceId } : null,
1903
+ phase: ctx.phase ?? null
1904
+ };
1905
+ }
1906
+
1907
+ // src/identity.ts
1908
+ var USER_ATTRIBUTE = "user.id";
1909
+ var SESSION_ATTRIBUTE = "session.id";
1910
+ var RELEASE_ATTRIBUTE = "risicare.release";
1911
+ var TAGS_ATTRIBUTE = "tag.tags";
1912
+ var MAX_TRACES = 1e4;
1913
+ var REGISTRY = /* @__PURE__ */ Symbol.for("risicare.identity");
1914
+ function registry() {
1915
+ const g = globalThis;
1916
+ let r = g[REGISTRY];
1917
+ if (r === void 0) {
1918
+ r = { traces: /* @__PURE__ */ new Map(), warned: /* @__PURE__ */ new Set() };
1919
+ g[REGISTRY] = r;
1920
+ }
1921
+ return r;
1922
+ }
1923
+ function warnOnce(helper, text) {
1924
+ const r = registry();
1925
+ if (r.warned.has(helper)) return;
1926
+ r.warned.add(helper);
1927
+ warn(`Risicare: ${helper}() ${text} Nothing was set.`);
1928
+ }
1929
+ function asText(helper, value) {
1930
+ let text;
1931
+ if (typeof value === "string") text = value.trim();
1932
+ else if (typeof value === "number" && Number.isInteger(value)) text = String(value);
1933
+ else {
1934
+ warnOnce(helper, `takes a non-empty string; it got ${value === null ? "null" : typeof value}.`);
1935
+ return null;
1936
+ }
1937
+ if (text === "") {
1938
+ warnOnce(helper, "takes a non-empty string; it got an empty one.");
1939
+ return null;
1940
+ }
1941
+ return text;
1942
+ }
1943
+ function mergeTags(old, add) {
1944
+ const merged = Array.isArray(old) ? old.filter((t) => typeof t === "string") : [];
1945
+ for (const tag of add) if (!merged.includes(tag)) merged.push(tag);
1946
+ return merged;
1947
+ }
1948
+ function set(helper, key, value) {
1949
+ const span = getCurrentSpan();
1950
+ const traceId = span?.traceId;
1951
+ if (span === void 0 || typeof traceId !== "string" || traceId === "") {
1952
+ warnOnce(
1953
+ helper,
1954
+ "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."
1955
+ );
1956
+ return false;
1957
+ }
1958
+ const r = registry();
1959
+ const values = r.traces.get(traceId) ?? {};
1960
+ r.traces.delete(traceId);
1961
+ values[key] = key === TAGS_ATTRIBUTE ? mergeTags(values[key], value) : value;
1962
+ r.traces.set(traceId, values);
1963
+ while (r.traces.size > MAX_TRACES) {
1964
+ const oldest = r.traces.keys().next().value;
1965
+ r.traces.delete(oldest);
1966
+ }
1967
+ span.setAttribute(key, key === TAGS_ATTRIBUTE ? mergeTags(span.attributes[key], value) : value);
1968
+ return true;
1969
+ }
1970
+ function setUser(userId) {
1971
+ const text = asText("setUser", userId);
1972
+ return text !== null && set("setUser", USER_ATTRIBUTE, text);
1973
+ }
1974
+ function setSession(sessionId) {
1975
+ const text = asText("setSession", sessionId);
1976
+ return text !== null && set("setSession", SESSION_ATTRIBUTE, text);
1977
+ }
1978
+ function setRelease(version) {
1979
+ const text = asText("setRelease", version);
1980
+ return text !== null && set("setRelease", RELEASE_ATTRIBUTE, text);
1981
+ }
1982
+ function addTags(tags) {
1983
+ if (!Array.isArray(tags)) {
1984
+ warnOnce("addTags", `takes an array of strings; it got ${tags === null ? "null" : typeof tags}.`);
1985
+ return false;
1986
+ }
1987
+ const clean = [];
1988
+ for (const tag of tags) {
1989
+ const text = typeof tag === "string" ? tag.trim() : "";
1990
+ if (text === "") {
1991
+ warnOnce("addTags", "takes non-empty strings; it got another item, left out.");
1992
+ continue;
1993
+ }
1994
+ if (!clean.includes(text)) clean.push(text);
1995
+ }
1996
+ if (clean.length === 0) return false;
1997
+ return set("addTags", TAGS_ATTRIBUTE, clean);
1998
+ }
1999
+ function applyIdentity(span) {
2000
+ const r = registry();
2001
+ if (r.traces.size === 0) return;
2002
+ const values = r.traces.get(span.traceId);
2003
+ if (values === void 0) return;
2004
+ const attributes = span.attributes;
2005
+ for (const [key, value] of Object.entries(values)) {
2006
+ if (key === TAGS_ATTRIBUTE) {
2007
+ if (!(key in attributes) || Array.isArray(attributes[key])) {
2008
+ attributes[key] = mergeTags(attributes[key], value);
2009
+ }
2010
+ } else if (!(key in attributes)) {
2011
+ attributes[key] = value;
2012
+ }
2013
+ }
2014
+ }
2015
+
1340
2016
  // src/ids.ts
1341
2017
  import { randomBytes } from "crypto";
1342
2018
  var HEX_REGEX_32 = /^[0-9a-f]{32}$/;
@@ -2161,69 +2837,6 @@ function classifyError(error) {
2161
2837
  return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : "";
2162
2838
  }
2163
2839
 
2164
- // src/context/storage.ts
2165
- function storage() {
2166
- return getContextStorage();
2167
- }
2168
- function getContext() {
2169
- return storage().getStore() ?? {};
2170
- }
2171
- function hasContextScope() {
2172
- return storage().getStore() !== void 0;
2173
- }
2174
- function runWithContext(overrides, fn) {
2175
- const parent = getContext();
2176
- const merged = { ...parent, ...overrides };
2177
- return storage().run(merged, fn);
2178
- }
2179
- function getCurrentSession() {
2180
- return getContext().session;
2181
- }
2182
- function getCurrentAgent() {
2183
- return getContext().agent;
2184
- }
2185
- function getCurrentSpan() {
2186
- return getContext().span;
2187
- }
2188
- function getCurrentPhase() {
2189
- return getContext().phase;
2190
- }
2191
- function getCurrentSessionId() {
2192
- return getContext().session?.sessionId;
2193
- }
2194
- function getCurrentAgentId() {
2195
- return getContext().agent?.agentId;
2196
- }
2197
- function getCurrentTraceId() {
2198
- return getContext().span?.traceId;
2199
- }
2200
- function getCurrentSpanId() {
2201
- return getContext().span?.spanId;
2202
- }
2203
- function getCurrentContext() {
2204
- const ctx = getContext();
2205
- return {
2206
- session: ctx.session ? {
2207
- sessionId: ctx.session.sessionId,
2208
- userId: ctx.session.userId,
2209
- ...ctx.session.parentSessionId !== void 0 ? { parentSessionId: ctx.session.parentSessionId } : {},
2210
- ...ctx.session.turnNumber !== void 0 ? { turnNumber: ctx.session.turnNumber } : {},
2211
- ...ctx.session.metadata !== void 0 ? { metadata: ctx.session.metadata } : {}
2212
- } : null,
2213
- agent: ctx.agent ? {
2214
- agentId: ctx.agent.agentId,
2215
- agentName: ctx.agent.agentName,
2216
- agentRole: ctx.agent.agentRole,
2217
- agentType: ctx.agent.agentType,
2218
- ...ctx.agent.parentAgentId !== void 0 ? { parentAgentId: ctx.agent.parentAgentId } : {},
2219
- ...ctx.agent.version !== void 0 ? { version: ctx.agent.version } : {},
2220
- ...ctx.agent.metadata !== void 0 ? { metadata: ctx.agent.metadata } : {}
2221
- } : null,
2222
- span: ctx.span ? { spanId: ctx.span.spanId, traceId: ctx.span.traceId } : null,
2223
- phase: ctx.phase ?? null
2224
- };
2225
- }
2226
-
2227
2840
  // src/tracer.ts
2228
2841
  function attachErrorCode(span, error) {
2229
2842
  try {
@@ -2244,7 +2857,11 @@ var Tracer = class {
2244
2857
  _serviceName;
2245
2858
  _serviceVersion;
2246
2859
  constructor(config) {
2247
- this._onSpanEnd = config.onSpanEnd;
2860
+ const onSpanEnd = config.onSpanEnd;
2861
+ this._onSpanEnd = (span) => {
2862
+ applyIdentity(span);
2863
+ onSpanEnd(span);
2864
+ };
2248
2865
  this._sampleRate = config.sampleRate ?? 1;
2249
2866
  this._enabled = config.enabled ?? true;
2250
2867
  this._traceContent = config.traceContent ?? false;
@@ -2405,7 +3022,7 @@ function markCancel(span, error) {
2405
3022
  }
2406
3023
 
2407
3024
  // src/version.ts
2408
- var SDK_VERSION = "0.9.2";
3025
+ var SDK_VERSION = "0.11.0";
2409
3026
 
2410
3027
  // src/exporters/quota.ts
2411
3028
  var QUOTA_REASON = "monthly_quota_exceeded";
@@ -2513,12 +3130,18 @@ var QuotaPause = class {
2513
3130
 
2514
3131
  // src/exporters/http.ts
2515
3132
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
2516
- var RETRY_AFTER_CEILING_MS = 1e4;
2517
- var REFUSAL_BACKOFF_BASE_MS = 1e3;
2518
- var REFUSAL_NO_HINT = -1;
2519
3133
  var MISROUTE_WARN_WINDOW_MS = 3e5;
2520
3134
  var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
2521
3135
  var FAILURE_WARN_WINDOW_MS = 3e5;
3136
+ var MAX_TIMER_MS = 2 ** 31 - 1;
3137
+ function validHorizonS(value) {
3138
+ if (value === void 0) return DEFAULT_RETRY_HORIZON_S;
3139
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
3140
+ warn(
3141
+ `Risicare: retryHorizonS=${String(value)} is not a finite number of 0 or more; using the default, ${DEFAULT_RETRY_HORIZON_S} s.`
3142
+ );
3143
+ return DEFAULT_RETRY_HORIZON_S;
3144
+ }
2522
3145
  var HttpExporter = class {
2523
3146
  name = "http";
2524
3147
  _endpoint;
@@ -2528,20 +3151,28 @@ var HttpExporter = class {
2528
3151
  _timeoutMs;
2529
3152
  _maxRetries;
2530
3153
  _compress;
3154
+ _retryHorizonS;
3155
+ /** Total HTTP requests that this exporter sent (each retry and each half of a split counts). */
3156
+ attempts = 0;
2531
3157
  // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
2532
- // a "30-second prod restart" scenario: with default 1s batch flush a
2533
- // 5-failure threshold opens the circuit ~5s into an outage and the 60s
2534
- // cooldown gives the gateway time to come back before the half-open
2535
- // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
3158
+ // a "30-second prod restart" scenario. Since W2-1c only answers that a retry
3159
+ // cannot change move it (see the block above).
2536
3160
  _consecutiveFailures = 0;
2537
3161
  _lastMisrouteWarnAt = -Infinity;
2538
3162
  _lastFailureWarnAt = -Infinity;
3163
+ _lastExhaustedWarnAt = -Infinity;
3164
+ /** "log once" (W2-1c): the WARNING for a `too_large` drop is written one time. */
3165
+ _tooLargeWarned = false;
2539
3166
  /**
2540
3167
  * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
2541
3168
  * 'unknown'). `null` after a success. A new kind in the same outage writes one more
2542
3169
  * WARNING, also inside the window.
2543
3170
  */
2544
3171
  _failureKind = null;
3172
+ /** `endRetries()` was called, and `shutdown()` has not run since. */
3173
+ _noWait = false;
3174
+ /** The wake-ups of the backoff waits in progress. `endRetries()` calls each one. */
3175
+ _waits = /* @__PURE__ */ new Set();
2545
3176
  /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
2546
3177
  _safeEndpoint;
2547
3178
  /** The endpoint holds userinfo. `fetch` refuses such a URL. */
@@ -2552,6 +3183,8 @@ var HttpExporter = class {
2552
3183
  _acks = /* @__PURE__ */ new WeakMap();
2553
3184
  /** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */
2554
3185
  _requests = /* @__PURE__ */ new WeakMap();
3186
+ /** The drop reason of each failed call, by its batch. Read once by `takeDropReason(spans)`. */
3187
+ _dropReasons = /* @__PURE__ */ new WeakMap();
2555
3188
  /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
2556
3189
  noteQuotaDrop(count = 1) {
2557
3190
  this._quota.addDrops(count);
@@ -2576,8 +3209,16 @@ var HttpExporter = class {
2576
3209
  this._projectId = options.projectId;
2577
3210
  this._environment = options.environment;
2578
3211
  this._timeoutMs = options.timeoutMs ?? 5e3;
2579
- this._maxRetries = options.maxRetries ?? 3;
3212
+ let maxRetries = options.maxRetries;
3213
+ if (maxRetries !== void 0 && !(Number.isInteger(maxRetries) && maxRetries >= 1)) {
3214
+ warn(
3215
+ `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).`
3216
+ );
3217
+ maxRetries = void 0;
3218
+ }
3219
+ this._maxRetries = maxRetries;
2580
3220
  this._compress = options.compress ?? false;
3221
+ this._retryHorizonS = validHorizonS(options.retryHorizonS);
2581
3222
  this._safeEndpoint = safeUrl(this._endpoint);
2582
3223
  this._endpointHasCredentials = hasCredentials(this._endpoint);
2583
3224
  }
@@ -2599,16 +3240,18 @@ var HttpExporter = class {
2599
3240
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
2600
3241
  return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
2601
3242
  }
2602
- /** The most requests that one `export()` call sends (`maxRetries`). */
3243
+ /**
3244
+ * The most attempts for one request body (`maxRetries`). `undefined` when no count is set:
3245
+ * the retry horizon is the limit.
3246
+ */
2603
3247
  get attemptsPerExport() {
2604
3248
  return this._maxRetries;
2605
3249
  }
2606
3250
  /**
2607
3251
  * Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears
2608
- * it. This is the number that was sent, not the most that the call may send
2609
- * (`attemptsPerExport`): a 401 or 403 stops the loop after one request, and an open circuit
2610
- * breaker sends none. Returns `null` when no call is on record for `spans`. The answer is
2611
- * kept per batch, as `takeAck` keeps the ack.
3252
+ * it. Each retry and each half of a 413 split counts one; a call that the open circuit
3253
+ * breaker or the quota pause stops sends none. Returns `null` when no call is on record for
3254
+ * `spans`. The answer is kept per batch, as `takeAck` keeps the ack.
2612
3255
  */
2613
3256
  takeAttempts(spans) {
2614
3257
  const n = this._requests.get(spans) ?? null;
@@ -2625,6 +3268,12 @@ var HttpExporter = class {
2625
3268
  this._acks.delete(spans);
2626
3269
  return ack;
2627
3270
  }
3271
+ /** Returns why the `export()` call for `spans` failed (W2-1c), and clears it. See `SpanExporter`. */
3272
+ takeDropReason(spans) {
3273
+ const reason = this._dropReasons.get(spans) ?? null;
3274
+ this._dropReasons.delete(spans);
3275
+ return reason;
3276
+ }
2628
3277
  /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
2629
3278
  takeUnserializable(spans) {
2630
3279
  const bad = this._unserializable.get(spans) ?? [];
@@ -2633,7 +3282,7 @@ var HttpExporter = class {
2633
3282
  }
2634
3283
  /**
2635
3284
  * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
2636
- * request, its retries and its backoff sleep. The batch processor calls it when
3285
+ * request, its retries and its backoff wait. The batch processor calls it when
2637
3286
  * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
2638
3287
  * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
2639
3288
  * logs no WARNING.
@@ -2643,24 +3292,39 @@ var HttpExporter = class {
2643
3292
  else for (const call of this._calls.values()) call.cancel.abort();
2644
3293
  }
2645
3294
  /**
2646
- * Send one batch. The limits are the request timeout and `maxRetries`.
3295
+ * End the retry waits of this exporter until its next `shutdown()`. The batch processor
3296
+ * calls it when `shutdown()` starts. A call that waits for a retry makes one more attempt
3297
+ * at once. An attempt that fails after this is not retried: the call fails with the drop
3298
+ * reason `shutdown_residue`. So a drain against a dead endpoint costs one attempt for each
3299
+ * batch, not the shutdown budget.
3300
+ */
3301
+ endRetries() {
3302
+ this._noWait = true;
3303
+ for (const wake of [...this._waits]) wake();
3304
+ }
3305
+ /**
3306
+ * Send one batch, with the W2-1c retry policy (see the block above the class).
3307
+ *
3308
+ * Resolves SUCCESS when the backend accounted for the batch: `takeAck` has the counts (and
3309
+ * the spans that a 413 split dropped, in `dropped`). Resolves FAILURE when no span was
3310
+ * accounted for: `takeDropReason` then says why, and the batch processor drops the batch
3311
+ * with that reason.
2647
3312
  *
2648
3313
  * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
2649
- * cuts a request that is already sent. A short flush budget that cut the request made a
2650
- * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
2651
- * the server stored the same spans again. Only `abort()` stops the call, and only
3314
+ * cuts a request that is already sent. Only `abort()` stops the call, and only
2652
3315
  * `shutdown()` calls it.
2653
3316
  */
2654
3317
  async export(spans) {
2655
3318
  if (spans.length === 0) return "success" /* SUCCESS */;
2656
3319
  const call = {
2657
3320
  cancel: new AbortController(),
2658
- refusalAfterMs: null,
3321
+ retryAfterS: null,
2659
3322
  misroute: null,
2660
3323
  noRetry: false,
2661
3324
  status: null,
2662
3325
  error: null,
2663
- attempts: 0
3326
+ attempts: 0,
3327
+ ack: null
2664
3328
  };
2665
3329
  this._calls.set(spans, call);
2666
3330
  try {
@@ -2697,83 +3361,236 @@ var HttpExporter = class {
2697
3361
  );
2698
3362
  }
2699
3363
  if (parts.length === 0) return "success" /* SUCCESS */;
2700
- const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
2701
- const now = Date.now();
2702
- let isHalfOpen = false;
2703
- if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
2704
- if (now < this._circuitOpenUntil) {
2705
- return "failure" /* FAILURE */;
3364
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold && Date.now() < this._circuitOpenUntil) {
3365
+ this._dropReasons.set(spans, "transport_refused");
3366
+ return "failure" /* FAILURE */;
3367
+ }
3368
+ const out = { delivered: [], dropped: {}, failed: [], cancelled: false };
3369
+ const start = performance.now();
3370
+ await this._deliver(parts, start, call, out, true);
3371
+ if (cancelled.aborted || out.cancelled) {
3372
+ this._acks.delete(spans);
3373
+ return "failure" /* FAILURE */;
3374
+ }
3375
+ return this._finish(spans, out, call.attempts);
3376
+ }
3377
+ /** The request body for `parts` (the serialized spans of one part of a batch). */
3378
+ _payload(parts) {
3379
+ return `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
3380
+ }
3381
+ /**
3382
+ * Send one part of a batch with the retry policy, and record its outcome in `out`.
3383
+ * `maySplit` is true only for the whole batch: a 413 splits it in two one time. A half
3384
+ * that gets 413 again is dropped as `too_large`.
3385
+ */
3386
+ async _deliver(parts, start, call, out, maySplit) {
3387
+ const n = parts.length;
3388
+ if (!maySplit && this._quota.paused()) {
3389
+ out.delivered.push({ n, ack: { accepted: 0, rejected: 0, quotaDropped: n } });
3390
+ return;
3391
+ }
3392
+ const result = await this._sendWithRetries(this._payload(parts), n, start, call);
3393
+ if (result.kind === "delivered") {
3394
+ out.delivered.push({ n, ack: result.ack });
3395
+ } else if (result.kind === "too_large") {
3396
+ if (maySplit && n > 1) {
3397
+ const mid = Math.ceil(n / 2);
3398
+ debug(`Ingest answered HTTP 413 for ${n} span(s): sending two halves of ${mid} and ${n - mid}`);
3399
+ await this._deliver(parts.slice(0, mid), start, call, out, false);
3400
+ if (!out.cancelled) await this._deliver(parts.slice(mid), start, call, out, false);
3401
+ } else {
3402
+ out.dropped.too_large = (out.dropped.too_large ?? 0) + n;
2706
3403
  }
2707
- isHalfOpen = true;
3404
+ } else if (result.kind === "cancelled") {
3405
+ out.cancelled = true;
3406
+ } else {
3407
+ out.failed.push({ n, reason: result.kind, answer: result.answer });
2708
3408
  }
2709
- const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
2710
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
2711
- call.refusalAfterMs = null;
3409
+ }
3410
+ /** Send one request body until it is delivered or the policy stops. */
3411
+ async _sendWithRetries(body, spansSent, start, call) {
3412
+ const cancelled = call.cancel.signal;
3413
+ let retryNumber = 0;
3414
+ let attemptsHere = 0;
3415
+ for (; ; ) {
3416
+ if (cancelled.aborted) return { kind: "cancelled" };
3417
+ call.retryAfterS = null;
2712
3418
  call.misroute = null;
2713
3419
  call.noRetry = false;
2714
3420
  call.status = null;
2715
3421
  call.error = null;
3422
+ call.ack = null;
2716
3423
  call.attempts++;
2717
- const result = await this._sendRequest(payload, parts.length, call, spans);
2718
- if (cancelled.aborted) {
2719
- this._acks.delete(spans);
2720
- return "failure" /* FAILURE */;
2721
- }
2722
- if (result === "success" /* SUCCESS */) {
2723
- this._consecutiveFailures = 0;
2724
- this._failureKind = null;
2725
- return result;
3424
+ attemptsHere++;
3425
+ this.attempts++;
3426
+ const result = await this._sendRequest(body, spansSent, call);
3427
+ if (cancelled.aborted) return { kind: "cancelled" };
3428
+ if (result === "success" /* SUCCESS */) return { kind: "delivered", ack: call.ack };
3429
+ if (call.status === TOO_LARGE_STATUS) return { kind: "too_large" };
3430
+ const answer = {
3431
+ status: call.status,
3432
+ error: call.error,
3433
+ misroute: call.misroute,
3434
+ zeroAck: call.noRetry,
3435
+ sent: spansSent
3436
+ };
3437
+ if (!this._retryable(call)) return { kind: "transport_refused", answer };
3438
+ if (attemptsHere === RETRY_WARN_AFTER_ATTEMPTS) this._warnOutage(answer, true);
3439
+ if (this._noWait) return { kind: "shutdown_residue", answer };
3440
+ if (this._maxRetries !== void 0 && attemptsHere >= this._maxRetries) {
3441
+ return { kind: "retry_exhausted", answer };
2726
3442
  }
2727
- if (call.misroute !== null || call.noRetry) break;
2728
- if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
2729
- if (attempt < maxAttempts - 1) {
2730
- const refusal = call.refusalAfterMs;
2731
- const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
2732
- await sleep(delay, cancelled);
2733
- if (cancelled.aborted) return "failure" /* FAILURE */;
3443
+ const remainingS = this._retryHorizonS - (performance.now() - start) / 1e3;
3444
+ if (remainingS <= 0) return { kind: "retry_exhausted", answer };
3445
+ const hint = call.retryAfterS;
3446
+ const waitS = hint !== null && hint > 0 ? hint : backoffDelayS(retryNumber, jitter.fraction());
3447
+ const delayS = Math.min(waitS, remainingS);
3448
+ retryNumber++;
3449
+ debug(
3450
+ `Ingest attempt ${attemptsHere} failed (${answer.status ?? answer.error ?? "unknown"}); next attempt in ${delayS.toFixed(2)} s (${Math.round(remainingS)} s of the horizon left)`
3451
+ );
3452
+ await this._retryWait(delayS * 1e3, cancelled);
3453
+ }
3454
+ }
3455
+ /** True when the answer of the last attempt of `call` can change on a retry. */
3456
+ _retryable(call) {
3457
+ if (call.misroute !== null || call.noRetry) return false;
3458
+ if (call.status !== null) return RETRY_STATUSES.has(call.status);
3459
+ if (this._endpointHasCredentials) return false;
3460
+ return call.error !== null;
3461
+ }
3462
+ /**
3463
+ * Wait `ms` before the next attempt. `abort()` and `endRetries()` end the wait at once. The
3464
+ * timer does not keep the process alive: when nothing else runs, `beforeExit` starts the
3465
+ * SDK's `shutdown()`, which ends the wait.
3466
+ */
3467
+ _retryWait(ms, signal) {
3468
+ return new Promise((resolve) => {
3469
+ if (signal.aborted || this._noWait || ms <= 0) return resolve();
3470
+ const done = () => {
3471
+ clearTimeout(timer);
3472
+ signal.removeEventListener("abort", done);
3473
+ this._waits.delete(done);
3474
+ resolve();
3475
+ };
3476
+ const timer = setTimeout(done, Math.min(ms, MAX_TIMER_MS));
3477
+ timer.unref?.();
3478
+ signal.addEventListener("abort", done, { once: true });
3479
+ this._waits.add(done);
3480
+ });
3481
+ }
3482
+ /** Turn the outcome of the parts of one batch into the result of `export()`. */
3483
+ _finish(spans, out, attempts) {
3484
+ const reasons = new Set(out.failed.map((f) => f.reason));
3485
+ if (out.delivered.length === 0 && Object.keys(out.dropped).length === 0 && reasons.size === 1) {
3486
+ const reason = out.failed[0].reason;
3487
+ const nFailed = out.failed.reduce((sum, f) => sum + f.n, 0);
3488
+ this._dropReasons.set(spans, reason);
3489
+ return this._fail(reason, out.failed[out.failed.length - 1].answer, nFailed, attempts);
3490
+ }
3491
+ let ack;
3492
+ if (out.delivered.length === 1 && Object.keys(out.dropped).length === 0 && out.failed.length === 0) {
3493
+ ack = out.delivered[0].ack;
3494
+ } else {
3495
+ let accepted = 0;
3496
+ let rejected = 0;
3497
+ let quotaDropped = 0;
3498
+ for (const part of out.delivered) {
3499
+ accepted += part.ack !== null ? part.ack.accepted : part.n;
3500
+ rejected += part.ack !== null ? part.ack.rejected : 0;
3501
+ quotaDropped += part.ack?.quotaDropped ?? 0;
2734
3502
  }
3503
+ const dropped = { ...out.dropped };
3504
+ for (const f of out.failed) dropped[f.reason] = (dropped[f.reason] ?? 0) + f.n;
3505
+ ack = { accepted, rejected };
3506
+ if (quotaDropped > 0) ack.quotaDropped = quotaDropped;
3507
+ if (Object.keys(dropped).length > 0) ack.dropped = dropped;
2735
3508
  }
2736
- if (call.refusalAfterMs !== null) {
2737
- warn(
2738
- `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.`
2739
- );
3509
+ if (ack !== null) this._acks.set(spans, ack);
3510
+ this._consecutiveFailures = 0;
3511
+ this._failureKind = null;
3512
+ const tooLarge = out.dropped.too_large ?? 0;
3513
+ if (tooLarge > 0) this._warnTooLarge(tooLarge);
3514
+ for (const f of out.failed) {
3515
+ if (f.reason === "retry_exhausted") this._warnExhausted(f.n, attempts, f.answer);
3516
+ }
3517
+ return "success" /* SUCCESS */;
3518
+ }
3519
+ /** End a call in which no span was accounted for. Always returns FAILURE. */
3520
+ _fail(reason, answer, nSpans, attempts) {
3521
+ if (reason === "shutdown_residue") {
3522
+ debug(`Export ended by shutdown after ${attempts} attempt(s)`);
2740
3523
  return "failure" /* FAILURE */;
2741
3524
  }
2742
- const misroute = call.misroute;
2743
- if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
2744
- this._lastMisrouteWarnAt = Date.now();
2745
- warn(
2746
- `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.`
2747
- );
3525
+ if (reason === "retry_exhausted") {
3526
+ if (answer.status === null || !CAPACITY_REFUSAL_STATUSES.has(answer.status)) this._stepBreaker();
3527
+ this._warnOutage(answer, true);
3528
+ this._warnExhausted(nSpans, attempts, answer);
3529
+ return "failure" /* FAILURE */;
2748
3530
  }
3531
+ this._stepBreaker();
3532
+ this._warnOutage(answer, false);
3533
+ return "failure" /* FAILURE */;
3534
+ }
3535
+ /** Count one failed call toward the circuit breaker. */
3536
+ _stepBreaker() {
2749
3537
  this._consecutiveFailures++;
2750
- if (misroute === null && !call.noRetry) {
2751
- const status = call.status;
2752
- const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
2753
- let write = false;
2754
- if (this._consecutiveFailures === 1 || this._failureKind === null) {
2755
- if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
2756
- this._lastFailureWarnAt = Date.now();
2757
- write = true;
2758
- }
2759
- this._failureKind = kind;
2760
- } else if (kind !== this._failureKind) {
2761
- this._failureKind = kind;
2762
- write = true;
2763
- }
2764
- if (write) this._warnOutage(kind, status, call.error);
2765
- }
2766
3538
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
2767
3539
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
2768
3540
  warn(
2769
3541
  `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
2770
3542
  );
2771
3543
  }
2772
- return "failure" /* FAILURE */;
2773
3544
  }
2774
- /** The outage WARNING for one kind of failure. */
2775
- _warnOutage(kind, status, error) {
3545
+ /**
3546
+ * The outage WARNING: at the first failure of an outage, and when its kind changes. At most
3547
+ * one in the window for the first failure; a misroute has its own WARNING, at most one in
3548
+ * the window. `retrying` is true for a retryable answer (written after
3549
+ * `RETRY_WARN_AFTER_ATTEMPTS` failed attempts of one batch, or when its retries end before
3550
+ * that), false for an answer that a retry cannot change (one attempt). The WARNING names the last HTTP status, or the error
3551
+ * code when there was no answer. It never names the key or the response body, and names
3552
+ * the API key as a cause only for a 401 or 403. An ack of 0 and 0 has its WARNING from
3553
+ * `checkAck`.
3554
+ */
3555
+ _warnOutage(answer, retrying) {
3556
+ if (answer.misroute !== null) {
3557
+ if (Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
3558
+ this._lastMisrouteWarnAt = Date.now();
3559
+ warn(
3560
+ `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.`
3561
+ );
3562
+ }
3563
+ return;
3564
+ }
3565
+ if (answer.zeroAck) return;
3566
+ const status = answer.status;
3567
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : answer.error !== null ? "none" : "unknown";
3568
+ let write = false;
3569
+ if (this._failureKind === null || !retrying && this._consecutiveFailures === 1) {
3570
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
3571
+ this._lastFailureWarnAt = Date.now();
3572
+ write = true;
3573
+ }
3574
+ this._failureKind = kind;
3575
+ } else if (kind !== this._failureKind) {
3576
+ this._failureKind = kind;
3577
+ write = true;
3578
+ }
3579
+ if (!write) return;
2776
3580
  const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
3581
+ if (retrying) {
3582
+ let limit = `${this._retryHorizonS} s from its first attempt (retryHorizonS)`;
3583
+ if (this._maxRetries !== void 0) limit = `${this._maxRetries} attempt(s) (maxRetries) or ${limit}`;
3584
+ const retryText = `The SDK sends each batch again with a growing wait, for up to ${limit}, and then drops it (reason=retry_exhausted).`;
3585
+ if (kind === "http") {
3586
+ warn(`${where}: it answered HTTP ${status}. ${retryText} Set debug: true to see each attempt.`);
3587
+ } else {
3588
+ warn(
3589
+ `${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.`
3590
+ );
3591
+ }
3592
+ return;
3593
+ }
2777
3594
  const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
2778
3595
  if (kind === "auth") {
2779
3596
  warn(
@@ -2781,15 +3598,11 @@ var HttpExporter = class {
2781
3598
  );
2782
3599
  } else if (kind === "http") {
2783
3600
  warn(
2784
- `${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.`
3601
+ `${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.`
2785
3602
  );
2786
3603
  } else if (kind === "none" && this._endpointHasCredentials) {
2787
3604
  warn(
2788
- `${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}`
2789
- );
2790
- } else if (kind === "none") {
2791
- warn(
2792
- `${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.`
3605
+ `${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}`
2793
3606
  );
2794
3607
  } else {
2795
3608
  warn(
@@ -2797,33 +3610,38 @@ var HttpExporter = class {
2797
3610
  );
2798
3611
  }
2799
3612
  }
3613
+ /** The WARNING for spans dropped as `retry_exhausted`. At most one in the window. */
3614
+ _warnExhausted(nSpans, attempts, answer) {
3615
+ if (Date.now() - this._lastExhaustedWarnAt <= FAILURE_WARN_WINDOW_MS) return;
3616
+ this._lastExhaustedWarnAt = Date.now();
3617
+ const last = answer.status !== null ? `HTTP ${answer.status}` : `no answer (${answer.error})`;
3618
+ const capacity = answer.status !== null && CAPACITY_REFUSAL_STATUSES.has(answer.status) ? " (over capacity)" : "";
3619
+ 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)`;
3620
+ warn(
3621
+ `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.`
3622
+ );
3623
+ }
3624
+ /** The WARNING for spans dropped as `too_large`. One time for each exporter. */
3625
+ _warnTooLarge(nSpans) {
3626
+ if (this._tooLargeWarned) return;
3627
+ this._tooLargeWarned = true;
3628
+ warn(
3629
+ `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.`
3630
+ );
3631
+ }
2800
3632
  /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
2801
3633
  _noteMisroute(call, answer) {
2802
3634
  call.misroute = this._scrub(answer, 300);
2803
3635
  debug(`Ingest misroute: ${call.misroute}`);
2804
3636
  return "failure" /* FAILURE */;
2805
3637
  }
2806
- /**
2807
- * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
2808
- *
2809
- * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
2810
- * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
2811
- * parse.
2812
- */
2813
- _noteRefusal(call, status, retryAfterRaw) {
2814
- if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
2815
- let delay = REFUSAL_NO_HINT;
2816
- if (retryAfterRaw) {
2817
- const secs = Number(retryAfterRaw);
2818
- if (Number.isFinite(secs) && secs >= 0) {
2819
- delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
2820
- }
2821
- }
2822
- call.refusalAfterMs = delay;
2823
- debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
2824
- return true;
3638
+ /** Record the `Retry-After` wait of a retryable answer for the retry loop. */
3639
+ _noteRetryAfter(call, status, retryAfterRaw) {
3640
+ if (!RETRY_STATUSES.has(status)) return;
3641
+ call.retryAfterS = parseRetryAfterS(retryAfterRaw);
3642
+ debug(`Ingest answered HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
2825
3643
  }
2826
- async _sendRequest(body, spansSent, call, spans) {
3644
+ async _sendRequest(body, spansSent, call) {
2827
3645
  const cancelled = call.cancel.signal;
2828
3646
  const timeoutMs = this._timeoutMs;
2829
3647
  const url = `${this._endpoint}/v1/spans`;
@@ -2891,14 +3709,15 @@ var HttpExporter = class {
2891
3709
  } else if (ack.result === "success" /* SUCCESS */) {
2892
3710
  this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
2893
3711
  }
2894
- if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
3712
+ if (ack.result === "success" /* SUCCESS */) call.ack = ack.counts;
2895
3713
  if (ack.final) call.noRetry = true;
2896
3714
  return ack.result;
2897
- } else if (response.status === 408 || response.status === 504) {
3715
+ }
3716
+ this._noteRetryAfter(call, response.status, response.headers?.get?.("Retry-After") ?? null);
3717
+ if (response.status === 408 || response.status === 504) {
2898
3718
  debug(`HTTP export timeout: ${response.status}`);
2899
3719
  return "timeout" /* TIMEOUT */;
2900
3720
  }
2901
- this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
2902
3721
  debug(`HTTP export failed: ${response.status}`);
2903
3722
  return "failure" /* FAILURE */;
2904
3723
  } catch (e) {
@@ -2912,20 +3731,9 @@ var HttpExporter = class {
2912
3731
  }
2913
3732
  }
2914
3733
  shutdown() {
3734
+ this._noWait = false;
2915
3735
  }
2916
3736
  };
2917
- function sleep(ms, signal) {
2918
- return new Promise((resolve) => {
2919
- if (signal?.aborted) return resolve();
2920
- const done = () => {
2921
- clearTimeout(timer);
2922
- signal?.removeEventListener("abort", done);
2923
- resolve();
2924
- };
2925
- const timer = setTimeout(done, ms);
2926
- signal?.addEventListener("abort", done, { once: true });
2927
- });
2928
- }
2929
3737
  function asCount(v) {
2930
3738
  return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
2931
3739
  }
@@ -3424,7 +4232,7 @@ var FixApplier = class {
3424
4232
  const initialDelayMs = cfg.initial_delay_ms ?? cfg.initialDelayMs ?? 1e3;
3425
4233
  const maxDelayMs = cfg.max_delay_ms ?? cfg.maxDelayMs ?? 3e4;
3426
4234
  const exponentialBase = cfg.exponential_base ?? cfg.exponentialBase ?? 2;
3427
- const jitter = cfg.jitter ?? true;
4235
+ const jitter2 = cfg.jitter ?? true;
3428
4236
  const retryOn = cfg.retry_on ?? cfg.retryOn ?? [];
3429
4237
  const result = emptyResult(fix, "retry");
3430
4238
  if (this._config.dryRun) {
@@ -3452,7 +4260,7 @@ var FixApplier = class {
3452
4260
  initialDelayMs * Math.pow(exponentialBase, attempt),
3453
4261
  maxDelayMs
3454
4262
  );
3455
- if (jitter) {
4263
+ if (jitter2) {
3456
4264
  delayMs *= 0.5 + Math.random();
3457
4265
  }
3458
4266
  debug(
@@ -4299,7 +5107,8 @@ var RisicareClient = class {
4299
5107
  apiKey: this.config.apiKey,
4300
5108
  projectId: this.config.projectId || void 0,
4301
5109
  environment: this.config.environment || void 0,
4302
- compress: this.config.compress
5110
+ compress: this.config.compress,
5111
+ retryHorizonS: this.config.retryHorizonS
4303
5112
  });
4304
5113
  }
4305
5114
  this.processor = new BatchSpanProcessor({
@@ -4390,7 +5199,8 @@ var RisicareClient = class {
4390
5199
  }
4391
5200
  this._shutdownHandlers = [];
4392
5201
  endOpenProviderSpans();
4393
- await this.processor.shutdown(timeoutMs);
5202
+ const budgetMs = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) ? timeoutMs : this.config.shutdownTimeoutS * 1e3;
5203
+ await this.processor.shutdown(budgetMs);
4394
5204
  _failWaitingScores(SCORE_DEADLINE_REASON);
4395
5205
  this.isShutdown = true;
4396
5206
  _finalMetrics = this.processor.getMetrics();
@@ -4467,7 +5277,7 @@ var RisicareClient = class {
4467
5277
  const othersAtSignal = process.listeners(signal).filter((l) => l !== handler).length;
4468
5278
  const backstop = setTimeout(
4469
5279
  () => process.exit(128 + signum),
4470
- SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
5280
+ this.config.shutdownTimeoutS * 1e3 + BACKSTOP_MARGIN_MS
4471
5281
  );
4472
5282
  backstop.unref();
4473
5283
  this.shutdown().catch(() => {
@@ -4501,7 +5311,10 @@ function init(config) {
4501
5311
  "environment",
4502
5312
  "serviceName",
4503
5313
  "serviceVersion",
4504
- "sampleRate"
5314
+ "sampleRate",
5315
+ // Capture is on by default (R9): a library's early init() must not
5316
+ // make the program's traceContent: false void in silence.
5317
+ "traceContent"
4505
5318
  ];
4506
5319
  for (const k of checkedKeys) {
4507
5320
  if (incoming[k] !== existing.config[k]) {
@@ -4608,10 +5421,14 @@ function getMetrics() {
4608
5421
  transport_refused: 0,
4609
5422
  shutdown_residue: 0,
4610
5423
  unacknowledged: 0,
4611
- quota_exceeded: 0
5424
+ quota_exceeded: 0,
5425
+ retry_exhausted: 0,
5426
+ too_large: 0
4612
5427
  },
4613
5428
  droppedQuota: 0,
4614
5429
  failedExports: 0,
5430
+ attempts: 0,
5431
+ oldestPendingAgeS: 0,
4615
5432
  queueSize: 0,
4616
5433
  queueCapacity: 0,
4617
5434
  queueUtilization: 0,
@@ -4673,40 +5490,111 @@ function refuseScore(message) {
4673
5490
  const client = getClient();
4674
5491
  if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;
4675
5492
  }
4676
- function score(traceId, name, value, options) {
5493
+ var SCORE_KINDS = ["annotation", "eval", "feedback", "outcome"];
5494
+ var SCORE_NAME_MAX_LEN = 128;
5495
+ var SCORE_STRING_VALUE_MAX_LEN = 256;
5496
+ var SCORE_SESSION_ID_MAX_LEN = 255;
5497
+ var SCORE_COMMENT_MAX_LEN = 4096;
5498
+ var _positionalScoreWarned = false;
5499
+ function warnPositionalScore() {
5500
+ if (_positionalScoreWarned) return;
5501
+ _positionalScoreWarned = true;
5502
+ warn(
5503
+ "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."
5504
+ );
5505
+ }
5506
+ function scoreWireValue(value) {
5507
+ if (typeof value === "boolean") return value;
5508
+ if (typeof value === "number") {
5509
+ if (Number.isFinite(value)) return value;
5510
+ refuseScore(`score: a number value must be finite, not ${value}. The SDK does not send this score.`);
5511
+ return void 0;
5512
+ }
5513
+ if (typeof value === "string") {
5514
+ if (value.length >= 1 && value.length <= SCORE_STRING_VALUE_MAX_LEN) return value;
5515
+ refuseScore(
5516
+ `score: a string value must have 1 to ${SCORE_STRING_VALUE_MAX_LEN} characters, not ${value.length}. The SDK does not send this score.`
5517
+ );
5518
+ return void 0;
5519
+ }
5520
+ refuseScore(
5521
+ `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.`
5522
+ );
5523
+ return void 0;
5524
+ }
5525
+ function score(first, legacyName, legacyValue, legacyOptions) {
4677
5526
  try {
4678
- const raw = value;
4679
- if (typeof raw === "boolean") value = raw ? 1 : 0;
4680
- if (typeof value !== "number") {
4681
- refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
5527
+ let opts;
5528
+ if (typeof first === "object" && first !== null && arguments.length === 1) {
5529
+ opts = first;
5530
+ } else {
5531
+ warnPositionalScore();
5532
+ opts = {
5533
+ traceId: first,
5534
+ name: legacyName,
5535
+ value: legacyValue,
5536
+ spanId: legacyOptions?.spanId,
5537
+ comment: legacyOptions?.comment
5538
+ };
5539
+ }
5540
+ const { name, traceId, spanId, sessionId } = opts;
5541
+ const kind = opts.kind ?? "annotation";
5542
+ if (typeof name !== "string" || given(name) === void 0) {
5543
+ refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
4682
5544
  return;
4683
5545
  }
4684
- if (!Number.isFinite(value) || value < 0 || value > 1) {
4685
- refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
5546
+ if (name.length > SCORE_NAME_MAX_LEN) {
5547
+ refuseScore(
5548
+ `score: name must be at most ${SCORE_NAME_MAX_LEN} characters, not ${name.length}. The SDK does not send this score.`
5549
+ );
4686
5550
  return;
4687
5551
  }
4688
- if (typeof traceId !== "string" || given(traceId) === void 0) {
5552
+ const value = scoreWireValue(opts.value);
5553
+ if (value === void 0) return;
5554
+ if (traceId !== void 0 && (typeof traceId !== "string" || given(traceId) === void 0)) {
4689
5555
  refuseScore("score: traceId must be a non-empty string. The SDK does not send this score.");
4690
5556
  return;
4691
5557
  }
4692
- if (typeof name !== "string" || given(name) === void 0) {
4693
- refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
5558
+ if (sessionId !== void 0 && (typeof sessionId !== "string" || given(sessionId) === void 0 || sessionId.length > SCORE_SESSION_ID_MAX_LEN)) {
5559
+ refuseScore(
5560
+ `score: sessionId must be a non-empty string of at most ${SCORE_SESSION_ID_MAX_LEN} characters. The SDK does not send this score.`
5561
+ );
5562
+ return;
5563
+ }
5564
+ if (traceId === void 0 && sessionId === void 0) {
5565
+ refuseScore("score: give traceId or sessionId (or both). The SDK does not send this score.");
5566
+ return;
5567
+ }
5568
+ if (spanId && traceId === void 0) {
5569
+ refuseScore("score: spanId needs traceId. The SDK does not send this score.");
5570
+ return;
5571
+ }
5572
+ if (typeof kind !== "string" || !SCORE_KINDS.includes(kind)) {
5573
+ refuseScore(`score: kind must be one of ${SCORE_KINDS.join(", ")}. The SDK does not send this score.`);
4694
5574
  return;
4695
5575
  }
4696
5576
  const client = getClient();
4697
5577
  if (!client?.enabled || !client.config.apiKey) return;
4698
5578
  const endpoint = client.config.apiEndpoint.replace(/\/+$/, "");
4699
5579
  const url = `${endpoint}/v1/scores`;
4700
- let comment = options?.comment;
5580
+ let comment = opts.comment;
4701
5581
  if (comment !== void 0 && client.config.mask) {
4702
5582
  comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
4703
5583
  }
5584
+ if (comment && comment.length > SCORE_COMMENT_MAX_LEN) {
5585
+ refuseScore(
5586
+ `score: comment must be at most ${SCORE_COMMENT_MAX_LEN} characters, not ${comment.length}. The SDK does not send this score.`
5587
+ );
5588
+ return;
5589
+ }
4704
5590
  const body = JSON.stringify({
4705
- trace_id: traceId,
4706
5591
  name,
4707
- score: value,
5592
+ value,
5593
+ kind,
4708
5594
  source: "sdk",
4709
- ...options?.spanId && { span_id: options.spanId },
5595
+ ...traceId !== void 0 && { trace_id: traceId },
5596
+ ...sessionId !== void 0 && { session_id: sessionId },
5597
+ ...spanId && { span_id: spanId },
4710
5598
  ...comment && { comment }
4711
5599
  });
4712
5600
  if (_scoresInFlight >= SCORE_MAX_IN_FLIGHT && _scoreWaiters.length >= SCORE_MAX_WAITING) {
@@ -5923,6 +6811,7 @@ export {
5923
6811
  SpanKind,
5924
6812
  SpanStatus,
5925
6813
  WebhookVerificationError,
6814
+ addTags,
5926
6815
  agent,
5927
6816
  disable,
5928
6817
  enable,
@@ -5954,6 +6843,9 @@ export {
5954
6843
  reportError,
5955
6844
  score,
5956
6845
  session,
6846
+ setRelease,
6847
+ setSession,
6848
+ setUser,
5957
6849
  shutdown,
5958
6850
  shutdownFixRuntime,
5959
6851
  suppressProviderInstrumentation,