risicare 0.10.0 → 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 +76 -5
  2. package/README.md +157 -39
  3. package/dist/frameworks/instructor.cjs +338 -117
  4. package/dist/frameworks/instructor.cjs.map +1 -1
  5. package/dist/frameworks/instructor.js +338 -117
  6. package/dist/frameworks/instructor.js.map +1 -1
  7. package/dist/frameworks/langchain.cjs +351 -130
  8. package/dist/frameworks/langchain.cjs.map +1 -1
  9. package/dist/frameworks/langchain.js +351 -130
  10. package/dist/frameworks/langchain.js.map +1 -1
  11. package/dist/frameworks/langgraph.cjs +351 -130
  12. package/dist/frameworks/langgraph.cjs.map +1 -1
  13. package/dist/frameworks/langgraph.js +351 -130
  14. package/dist/frameworks/langgraph.js.map +1 -1
  15. package/dist/frameworks/llamaindex.cjs +351 -130
  16. package/dist/frameworks/llamaindex.cjs.map +1 -1
  17. package/dist/frameworks/llamaindex.js +351 -130
  18. package/dist/frameworks/llamaindex.js.map +1 -1
  19. package/dist/index.cjs +808 -226
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +137 -21
  22. package/dist/index.d.ts +137 -21
  23. package/dist/index.js +804 -226
  24. package/dist/index.js.map +1 -1
  25. package/dist/providers/anthropic/index.cjs +351 -130
  26. package/dist/providers/anthropic/index.cjs.map +1 -1
  27. package/dist/providers/anthropic/index.js +351 -130
  28. package/dist/providers/anthropic/index.js.map +1 -1
  29. package/dist/providers/bedrock/index.cjs +346 -125
  30. package/dist/providers/bedrock/index.cjs.map +1 -1
  31. package/dist/providers/bedrock/index.js +346 -125
  32. package/dist/providers/bedrock/index.js.map +1 -1
  33. package/dist/providers/cerebras/index.cjs +351 -130
  34. package/dist/providers/cerebras/index.cjs.map +1 -1
  35. package/dist/providers/cerebras/index.js +351 -130
  36. package/dist/providers/cerebras/index.js.map +1 -1
  37. package/dist/providers/cohere/index.cjs +351 -130
  38. package/dist/providers/cohere/index.cjs.map +1 -1
  39. package/dist/providers/cohere/index.js +351 -130
  40. package/dist/providers/cohere/index.js.map +1 -1
  41. package/dist/providers/google/index.cjs +351 -130
  42. package/dist/providers/google/index.cjs.map +1 -1
  43. package/dist/providers/google/index.js +351 -130
  44. package/dist/providers/google/index.js.map +1 -1
  45. package/dist/providers/groq/index.cjs +351 -130
  46. package/dist/providers/groq/index.cjs.map +1 -1
  47. package/dist/providers/groq/index.js +351 -130
  48. package/dist/providers/groq/index.js.map +1 -1
  49. package/dist/providers/huggingface/index.cjs +351 -130
  50. package/dist/providers/huggingface/index.cjs.map +1 -1
  51. package/dist/providers/huggingface/index.js +351 -130
  52. package/dist/providers/huggingface/index.js.map +1 -1
  53. package/dist/providers/mistral/index.cjs +351 -130
  54. package/dist/providers/mistral/index.cjs.map +1 -1
  55. package/dist/providers/mistral/index.js +351 -130
  56. package/dist/providers/mistral/index.js.map +1 -1
  57. package/dist/providers/ollama/index.cjs +351 -130
  58. package/dist/providers/ollama/index.cjs.map +1 -1
  59. package/dist/providers/ollama/index.js +351 -130
  60. package/dist/providers/ollama/index.js.map +1 -1
  61. package/dist/providers/openai/index.cjs +351 -130
  62. package/dist/providers/openai/index.cjs.map +1 -1
  63. package/dist/providers/openai/index.js +351 -130
  64. package/dist/providers/openai/index.js.map +1 -1
  65. package/dist/providers/together/index.cjs +351 -130
  66. package/dist/providers/together/index.cjs.map +1 -1
  67. package/dist/providers/together/index.js +351 -130
  68. package/dist/providers/together/index.js.map +1 -1
  69. package/dist/providers/vercel-ai/index.cjs +351 -130
  70. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  71. package/dist/providers/vercel-ai/index.js +351 -130
  72. package/dist/providers/vercel-ai/index.js.map +1 -1
  73. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/client.ts","../../src/globals.ts","../../src/utils/log.ts","../../src/utils/text.ts","../../src/utils/scrub.ts","../../src/masking.ts","../../src/exporters/batch.ts","../../src/ids.ts","../../src/noop.ts","../../src/runtime/config.ts","../../src/runtime/taxonomy.generated.ts","../../src/version.ts","../../src/exporters/quota.ts","../../src/exporters/http.ts","../../src/runtime/applier.ts","../../src/runtime/loader.ts","../../src/utils/assert-client.ts","../../src/frameworks/instructor.ts"],"sourcesContent":["/**\n * RisicareClient — singleton client managing SDK lifecycle.\n *\n * Handles initialization, shutdown, and the connection between\n * the Tracer and the export pipeline (batch processor + HTTP exporter).\n *\n * Usage:\n * import { init, shutdown } from 'risicare';\n * init({ apiKey: 'rsk-...' }); // API key determines project\n * // ... instrument code ...\n * await shutdown(); // flush remaining spans\n */\n\n// ⚠ F-SDKJSREPORTERROR-001 (W20, 2026-08-14) — STATIC, and it must stay static.\n// This was `require('node:crypto')` INSIDE `_errorFingerprint()`. esbuild\n// rewrites a bare `require` in an ESM output bundle to `__require(\"crypto\")`,\n// whose shim THROWS at call time; `reportError`'s catch-all then swallowed it\n// (`client.ts` ~:597, \"Never crash the host application\"). Net effect measured\n// on clean tarball installs of the PUBLISHED 0.4.2: reportError() delivered\n// ZERO spans under ESM and one under CJS — a silent no-op for every ESM\n// customer, which is the default for modern Node apps.\n//\n// A static import adds NO new environmental constraint: the package's main\n// entry already pulls `node:crypto` statically, because `src/index.ts` re-\n// exports `./webhooks.js`, which does `import { createHmac, timingSafeEqual }\n// from 'node:crypto'` at `webhooks.ts:53`. Same precedent, same module.\n//\n// ⚠ Do NOT \"optimise\" this back to a lazy require to keep the module edge-safe.\n// It would not achieve that (see above) and it silently re-breaks ESM. Verify\n// with `bash fix-workstream/perf/sdkjs/reporterror_module_system_probe.sh`,\n// whose CJS arm is the non-vacuity control and gates the exit code.\nimport { createHash } from 'node:crypto';\nimport { type RisicareConfig, resolveConfig, given, tracingTurnedOff } from './config.js';\nimport { Tracer, attachErrorCode } from './tracer.js';\nimport { SDK_VERSION } from './version.js';\nimport { BatchSpanProcessor, SHUTDOWN_BUDGET_MS, normalizeTimeoutMs } from './exporters/batch.js';\nimport { HttpExporter } from './exporters/http.js';\nimport { SpanKind, SpanStatus } from './types.js';\nimport type { SpanExporter } from './exporters/base.js';\nimport { setDebug, debug, warn } from './utils/log.js';\nimport { cutCodePoints } from './utils/text.js';\nimport { endOpenProviderSpans } from './utils/stream-proxy.js';\nimport { maskText, SCORE_COMMENT_KEY } from './masking.js';\nimport {\n getClient as getGlobalClient,\n setClient as setGlobalClient,\n getTracer as getGlobalTracer,\n setTracer as setGlobalTracer,\n} from './globals.js';\n// PR-4+5 review NIT (2026-05-25): static ESM import. Pre-fix this was a\n// CJS `require('./runtime/runtime.js')` inside the constructor, which\n// dies in TS-source consumers (vitest, ts-node ESM) because the .js\n// resolution fails — tripping the FixRuntime catch and emitting a\n// spurious \"auto-fix is OFFLINE\" warning on EVERY test that calls init().\n// Static import resolves at module-load time and works identically under\n// ESM and CJS bundles produced by tsup. The CON-194 test still exercises\n// the failure path via vi.mock() (which intercepts ES imports correctly).\nimport { initFixRuntime, shutdownFixRuntime } from './runtime/runtime.js';\nimport { safeUrl, scrubText } from './utils/scrub.js';\n\n/**\n * Signals whose default disposition is TERMINATE, with their numbers — needed\n * for the conventional `128 + signum` exit code (SIGTERM 143, SIGINT 130).\n * SDK-RELEASE-RULING.md §3.\n */\nconst TERMINATING_SIGNALS: ReadonlyArray<readonly [string, number]> = [\n ['SIGTERM', 15],\n ['SIGINT', 2],\n];\n\n/**\n * Headroom between the shutdown budget and the backstop that force-exits if\n * shutdown never resolves. It must be > 0 or the backstop races the drain; it\n * is small because it buys nothing but the difference between \"the drain\n * finished\" and \"the drain is wedged\". The drain itself is a hard wall-clock\n * bound: each round is raced against the budget, and an export that the drain\n * abandons is aborted. So 500 ms covers only timer delay and the exporters'\n * own `shutdown()` after the drain, not a round that overruns the budget.\n */\nconst BACKSTOP_MARGIN_MS = 500;\n\n/**\n * SDK-RELEASE-RULING.md §5 — the final tally survives the teardown.\n *\n * `shutdown()` clears the global client, so without this the natural pattern\n * `await shutdown(); console.log(getMetrics())` reported `droppedSpans: 0` from\n * a hardcoded literal, in the exact process that had just discarded spans.\n *\n * Written once per shutdown; cleared by `init()` so a second lifecycle never\n * serves the first's tally. Mirrors `_final_metrics` in `client.py`.\n */\nlet _finalMetrics: ReturnType<BatchSpanProcessor['getMetrics']> | undefined;\n\n/**\n * The processor of the last shutdown, kept with the tally. Root `flush()` after\n * `shutdown()` asks it: the processor holds the loss mark, so a loss that the\n * shutdown counted (`shutdown_residue` included) makes ONE `flush()` false, as\n * every other loss does. Cleared by `init()`.\n */\nlet _finalProcessor: BatchSpanProcessor | undefined;\n/** Whether the client of that last shutdown was active (see `RisicareClient._activated`). */\nlet _finalActive = false;\n\n/**\n * score() requests: the timeout, the ones not yet settled, and the number that\n * failed since `init()`. Root `flush()` waits for the pending ones inside its\n * deadline. Through 0.7.1 a score request had no timeout, followed redirects,\n * never read the status, and a failure was a debug line only.\n */\nconst SCORE_TIMEOUT_MS = 2000;\nconst _pendingScores = new Set<Promise<void>>();\nlet _failedScores = 0;\n// The failed-score count that the last finished flush() saw. A flush() answers\n// false when the count is above this mark, and then raises the mark: each\n// failed score makes one flush false, also when it failed with no flush running.\nlet _failedScoresFlushMark = 0;\n\n/**\n * The score slot rule (both SDKs; review of PR #44):\n * - at most SCORE_MAX_IN_FLIGHT score requests are in flight;\n * - a score that finds no free slot waits, with NO timer of its own: the 2000 ms\n * bound of a score starts when its request starts;\n * - at most SCORE_MAX_WAITING scores wait; one more fails at once and is counted;\n * - when a flush or shutdown bound ends, the scores that still wait are counted as\n * failed and never start a request.\n * With one connection for each score, 200 scores at once overflowed the accept\n * queue of a server (128 on macOS). With a timer that also covered the wait, 150 of\n * 200 scores to a sink that answers in 1 s were lost.\n */\nconst SCORE_MAX_IN_FLIGHT = 50;\nconst SCORE_MAX_WAITING = 1000;\nconst SCORE_CAP_REASON = `not sent: ${SCORE_MAX_WAITING} scores wait for a free slot`;\nconst SCORE_DEADLINE_REASON = 'not sent before the deadline';\nlet _scoresInFlight = 0;\ninterface ScoreWaiter {\n start: () => void;\n fail: (reason: string) => void;\n}\nconst _scoreWaiters: ScoreWaiter[] = [];\n\n/** Start waiting scores while a slot is free. */\nfunction _startWaitingScores(): void {\n while (_scoresInFlight < SCORE_MAX_IN_FLIGHT && _scoreWaiters.length > 0) {\n _scoreWaiters.shift()!.start();\n }\n}\n\n/** Count every waiting score as failed. None of them starts a request after this. */\nfunction _failWaitingScores(reason: string): void {\n for (const waiter of _scoreWaiters.splice(0)) waiter.fail(reason);\n}\n\n// One WARNING for a failed score, then at most one for each window. The\n// failures in the window are counted, and the next WARNING gives their number.\nlet _scoreWarnWindowMs = 10_000;\nconst SCORE_NAME_MAX = 200;\nlet _scoreWarnedAt: number | undefined;\nlet _scoreHeld = 0;\nlet _scoreHeldReason = '';\n\n/** @internal Tests only: change the WARNING window. */\nexport function _setScoreWarnWindowMsForTesting(ms: number): void {\n _scoreWarnWindowMs = ms;\n}\n\nfunction _resetScoreFailures(): void {\n _failedScores = 0;\n _failedScoresFlushMark = 0;\n _scoreWarnedAt = undefined;\n _scoreHeld = 0;\n _scoreHeldReason = '';\n}\n\nfunction _heldText(): string {\n return ` ${_scoreHeld} more scores failed after the last warning. The last reason: ${_scoreHeldReason}.`;\n}\n\n/**\n * Count one failed score request, and write a WARNING when the window lets it.\n * The first failure writes at once. A failure less than 10 s after the last\n * WARNING is counted and held; the next WARNING gives the number of held\n * failures and the last reason. The WARNING gives the score name (at most 200\n * characters) and the status or the error code only.\n */\nfunction _scoreFailed(name: string, reason: string): void {\n _failedScores += 1;\n const now = Date.now();\n if (_scoreWarnedAt !== undefined && now - _scoreWarnedAt < _scoreWarnWindowMs) {\n _scoreHeld += 1;\n _scoreHeldReason = reason;\n return;\n }\n let message = `score ${JSON.stringify(name.slice(0, SCORE_NAME_MAX))} failed: ${reason}.`;\n if (_scoreHeld > 0) message += _heldText();\n _scoreWarnedAt = now;\n _scoreHeld = 0;\n _scoreHeldReason = '';\n warn(message);\n}\n\n/** Write the held failures now, if there are any. Root `flush()` calls this. */\nfunction _warnHeldScores(): void {\n if (_scoreHeld === 0) return;\n const message = _heldText().trimStart();\n _scoreWarnedAt = Date.now();\n _scoreHeld = 0;\n _scoreHeldReason = '';\n warn(message);\n}\n\n/** Resolve `true` when no score request is pending, `false` at the timeout. */\nasync function _waitForPendingScores(timeoutMs: number): Promise<boolean> {\n if (_pendingScores.size === 0) return true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));\n });\n const settled = (async () => {\n while (_pendingScores.size > 0) await Promise.all([..._pendingScores]);\n return true;\n })();\n try {\n return await Promise.race([settled, expired]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n// ─── Client Class ───────────────────────────────────────────────────────────\n\nclass RisicareClient {\n readonly config: ReturnType<typeof resolveConfig>;\n readonly processor: BatchSpanProcessor;\n readonly tracer: Tracer;\n /** RULING §5. The signal path does NOT clear the global client, so without\n * this flag `getMetrics()` would keep reporting `\"running\"` over a processor\n * that has already been torn down. */\n isShutdown = false;\n /**\n * Tracing was on at `init()` or since `enable()`. A client that never was\n * (no key, or tracing off) accepted nothing, and delivered nothing: its\n * `flush()` is false. `disable()` does not clear it: spans that were accepted\n * before keep their answer.\n */\n private _activated = false;\n private _shutdownPromise: Promise<void> | undefined;\n private _shutdownHandlers: { signal: string; handler: () => void }[] = [];\n\n constructor(config?: Partial<RisicareConfig>) {\n this.config = resolveConfig(config);\n\n // API key format validation. `rsk-` is the legacy format (kept working\n // forever); `rski_` (Ingest) and `rsks_` (Secret) are the new checksummed\n // format — design: closure-plan-2026-09-25/org-project-ux/\n // 12-A2-A5-key-model-design.md §3. This is a hint only, never enforced.\n //\n // S14: `warn`, not `debug`. `setDebug()` runs at the end of this\n // constructor, so a `debug()` call here never printed for a customer. The\n // message never contains any part of the key.\n const hasKnownPrefix =\n this.config.apiKey?.startsWith('rsk-') ||\n this.config.apiKey?.startsWith('rski_') ||\n this.config.apiKey?.startsWith('rsks_');\n if (this.config.apiKey && !hasKnownPrefix) {\n warn(\n 'the API key does not look like a Risicare key: it should start with \"rsk-\", \"rski_\" or \"rsks_\". ' +\n 'Tracing continues with this key.',\n );\n }\n // NO KEY: tracing is off (`resolveConfig` forces `enabled` false), the SDK\n // sends nothing to Risicare, and `flush()` returns false. Say so once, in\n // plain words. A caller who turned tracing off on purpose (`enabled: false`,\n // `RISICARE_TRACING=false`) gets no WARNING.\n if (!this.config.apiKey && !tracingTurnedOff(config)) {\n warn(\n 'Risicare found no API key. Nothing is sent to Risicare: tracing is off, no span is ' +\n 'created, and flush() returns false. Set the RISICARE_API_KEY environment variable, ' +\n 'or pass apiKey to init().',\n );\n }\n\n // Build exporter chain.\n //\n // Only a key gives an exporter. With no key none exists, and none can: the SDK\n // writes nothing to the console either. F-SDKJSCONSOLE-001 (2026-08-15): the\n // old fallback printed `JSON.stringify(span.toPayload())`, the whole payload\n // with no redaction, to the customer's stderr. Through 0.8.0 `debug: true`\n // still printed spans with no key, and the processor counted them as exported\n // (a console exporter that is the only one decides the batch). Now no key\n // means `enabled` false: no span is created, so nothing is printed, queued,\n // dropped or counted as exported. Python prints with `debug` and no key\n // (display only, never counted); JavaScript does not print.\n let exporter: SpanExporter | undefined;\n if (this.config.apiKey) {\n exporter = new HttpExporter({\n endpoint: this.config.endpoint,\n apiKey: this.config.apiKey,\n projectId: this.config.projectId || undefined,\n environment: this.config.environment || undefined,\n compress: this.config.compress,\n });\n }\n\n this.processor = new BatchSpanProcessor({\n exporters: exporter ? [exporter] : [],\n batchSize: this.config.batchSize,\n batchTimeoutMs: this.config.batchTimeoutMs,\n maxQueueSize: this.config.maxQueueSize,\n debug: this.config.debug,\n // The processor is the ONE choke point every exporter is behind. Masking\n // anywhere downstream (in the HTTP exporter, say) would leave a hole for\n // any other exporter; masking upstream would put customer code on the\n // span-end call path.\n mask: this.config.mask,\n // Same argument as `mask`: the processor is the ONE choke point every\n // exporter is behind, and the only place BOTH content paths — provider\n // capture and hand-set attributes — can be gated together. The Tracer\n // still carries `traceContent` for the provider patches to read; that is\n // now a convenience, not the enforcement point.\n traceContent: this.config.traceContent,\n });\n\n this.tracer = new Tracer({\n onSpanEnd: (span) => this.processor.onSpanEnd(span),\n sampleRate: this.config.sampleRate,\n enabled: this.config.enabled,\n traceContent: this.config.traceContent,\n // F-SDKJSSVCNAME-001 — these were resolved into `config` and then read by\n // nothing. The Tracer is where Python emits them, so JS emits them there\n // too rather than inventing a second site.\n serviceName: this.config.serviceName,\n serviceVersion: this.config.serviceVersion,\n });\n\n this._activated = this.tracer.enabled;\n\n // Start the batch processor (enables span queuing and periodic flushing)\n this.processor.start();\n\n // Start FixRuntime for runtime fix application, ONLY ON OPT-IN (0.7.0;\n // see `RisicareConfig.fixRuntime`). Through 0.6.0 it started whenever an\n // apiKey was set, so the server could change the customer's agent by\n // default. When it starts, it loads active fixes from /v1/fixes/active,\n // caches with TTL and background-refreshes every 60s. The OpenAI chat patch\n // calls interceptCall() before the LLM call. It runs the input guards; with\n // no errorCode it applies no prompt, parameter or fallback fix. When it is\n // off, no runtime exists, so interceptCall() finds nothing to apply.\n //\n // CON-194: previously the catch was an empty-body silent swallow,\n // which meant a customer whose FixRuntime failed to initialize\n // (network unreachable, bad API key, server 5xx, etc.) saw ZERO\n // signal and assumed auto-fix was running. Now the catch logs\n // console.warn with an actionable message — visible at default\n // console output, including the api endpoint (fix reads go there, not to\n // the span endpoint) so customers can verify reachability. Mirrors the\n // Python SDK fix at client.py:520-528.\n //\n // ⚠ A failed LOAD of the fixes (network, 401, 5xx) does not reach this\n // catch: `initFixRuntime()` catches every fault. `FixLoader.start()` logs\n // its own WARNING for a failed first load. No known path makes\n // `initFixRuntime()` throw; the tests reach this catch through a mock.\n if (this.config.apiKey && this.config.enabled && this.config.fixRuntime) {\n try {\n initFixRuntime({\n apiEndpoint: this.config.apiEndpoint,\n apiKey: this.config.apiKey,\n enabled: true,\n debug: this.config.debug,\n });\n } catch (e) {\n // FixRuntime failure is non-fatal — tracing still works.\n // Surface a one-time console.warn so the customer knows.\n const errName = e instanceof Error ? e.name : 'Error';\n const errMsg = scrubText(e instanceof Error ? e.message : String(e), [this.config.apiKey]);\n try {\n console.warn(\n `[risicare] FixRuntime initialization failed — auto-fix is OFFLINE for this process. ` +\n `apiEndpoint=${safeUrl(this.config.apiEndpoint)} error=${errName}: ${errMsg}. ` +\n `Tracing + reporting still work; only fix application is disabled. ` +\n `Pass debug:true in init() options for the full traceback.`\n );\n } catch {\n // Defensive: if console.warn itself throws (closed stderr in\n // some sandboxed/edge environments), prefer silent over crash.\n }\n if (this.config.debug) {\n debug(\n `FixRuntime init traceback: ${scrubText(e instanceof Error && e.stack ? e.stack : String(e), [this.config.apiKey], 2000)}`,\n );\n }\n }\n }\n\n // Register shutdown hooks\n this._registerShutdownHooks();\n\n // Enable internal debug logging if configured\n setDebug(this.config.debug);\n debug(`Initialized: enabled=${this.config.enabled}, endpoint=${safeUrl(this.config.endpoint)}`);\n if (!this.config.fixRuntime) {\n debug(\n 'FixRuntime is off: nothing polls /fixes/active and no fix is applied. ' +\n 'Opt in with fixRuntime: true or RISICARE_FIX_RUNTIME=true.',\n );\n }\n }\n\n get enabled(): boolean {\n return this.tracer.enabled;\n }\n\n set enabled(value: boolean) {\n // `enable()` with no key does not turn tracing on: nothing can be sent.\n if (value && !this.config.apiKey) {\n debug('enable() ignored: no API key is configured, so tracing stays off');\n return;\n }\n this.tracer.enabled = value;\n if (value) this._activated = true;\n }\n\n // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)\n async shutdown(timeoutMs?: number): Promise<void> {\n if (this._shutdownPromise) return this._shutdownPromise;\n this._shutdownPromise = this._doShutdown(timeoutMs);\n return this._shutdownPromise;\n }\n\n private async _doShutdown(timeoutMs?: number): Promise<void> {\n debug('Shutting down...');\n\n // Audit #3: Remove process listeners to prevent leak\n for (const { signal, handler } of this._shutdownHandlers) {\n process.removeListener(signal, handler);\n }\n this._shutdownHandlers = [];\n\n // A provider span that is still open (for example a stream that nobody\n // read) ends now, so the processor exports it and it is not lost.\n endOpenProviderSpans();\n\n await this.processor.shutdown(timeoutMs);\n // The shutdown bound ended (also on SIGTERM and SIGINT, which reach this method):\n // a score that still waits for a slot is counted as failed and is not sent.\n _failWaitingScores(SCORE_DEADLINE_REASON);\n\n // RULING §5: snapshot HERE, in the one place every teardown path passes\n // through.\n //\n // ⚠ THIS SITE IS THE WHOLE POINT, and the obvious site is wrong. A first\n // implementation snapshotted in the module-level `shutdown()` — which the\n // SIGTERM/SIGINT handlers never call. They call THIS method, so on exactly\n // the path a container redeploy takes, `getMetrics()` would have reported\n // a live-looking reading over a torn-down processor. The Python SDK had the\n // identical trap on its own signal path; one rule, two languages, both\n // instrumented at the shared site rather than the canonical one.\n this.isShutdown = true;\n _finalMetrics = this.processor.getMetrics();\n _finalProcessor = this.processor;\n _finalActive = this._activated;\n }\n\n /**\n * Flush pending spans.\n *\n * @returns `true` only if everything queued at entry was DELIVERED.\n *\n * RULING §6: this used to discard the processor's boolean and return\n * `Promise<void>`, which resolves without throwing and reads to a caller\n * exactly like success. A discarded answer is not meaningfully better than a\n * false one — both leave the customer unable to tell *drained* from\n * *discarded*.\n */\n async flush(timeoutMs?: number): Promise<boolean> {\n // Not active means not true: no key, or tracing was off from the start.\n if (!this._activated) return false;\n return this.processor.flush(timeoutMs);\n }\n\n /**\n * SDK-RELEASE-RULING.md §3 — who decides whether the process dies.\n *\n * The contract, and it is the same one the Python SDK now satisfies:\n *\n * the SDK's signal handler never CHANGES whether the signal\n * terminates the process.\n *\n * Registering ANY listener for SIGTERM/SIGINT displaces Node's default\n * terminate. Before this, the SDK registered one unconditionally, and on the\n * success path `clearTimeout` removed the 5 s `process.exit(1)` backstop —\n * so a JS app with a live event loop drained, cleared its own only exit, and\n * **ran forever**. The orchestrator waited out the whole grace period and\n * SIGKILLed, which exits **137** and reads as OOM-killed in every dashboard.\n * Measured >25 s alive on both 0.5.0 and a clean-rebuilt 0.4.2, so this is\n * PRE-EXISTING (`F-SDKJSEXIT-001`), not a regression of the data-loss fix.\n *\n * The rule splits on one question — did the signal already have an owner?\n *\n * * **No prior listener.** Node's default was termination and OUR\n * registration displaced it. We owe the process that death.\n * * **A prior listener exists.** The application took ownership before the\n * SDK loaded. We drain and RETURN; termination was never ours to decide,\n * and forcing it would cut off the app's own graceful shutdown.\n * * **A listener that the application adds after `init()`.** Node calls ours\n * first. The question is asked when OUR listener starts, at signal time:\n * is there another listener for this signal? If there is, it owns\n * termination as well: when the drain ends we do not raise the signal\n * again, and we do not arm the fail-safe exit. Its listener runs once and\n * decides the exit, in the same way as when it was registered before\n * `init()`. Through 0.8.0 the re-raise ran it a second time, and the\n * fail-safe ended the process with code 143, 100 ms later.\n * * **A listener that the application adds DURING the drain.** There was none\n * at signal time, so the 0.8.0 rule holds: after the drain we raise the\n * signal again, and that listener runs on it, and the process ends (fail-safe\n * after 100 ms if it does not). A count taken after the drain would have\n * counted that listener, and nothing would have run or ended the process.\n *\n * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and\n * carries no termination the SDK could displace — the loop has already\n * drained and the process is leaving on its own.\n */\n private _registerShutdownHooks(): void {\n // `beforeExit` first: no ownership question, no backstop, no exit.\n const onBeforeExit = () => {\n this.shutdown().catch(() => {});\n };\n process.once('beforeExit', onBeforeExit);\n this._shutdownHandlers.push({ signal: 'beforeExit', handler: onBeforeExit });\n\n for (const [signal, signum] of TERMINATING_SIGNALS) {\n // Captured ONCE, at registration — asking later would count our own.\n const weDisplacedDefault = process.listenerCount(signal) === 0;\n\n const handler = (): void => {\n // The other listeners for this signal, counted NOW, at signal time. A\n // listener that the application adds during the drain is not one of them.\n const othersAtSignal = process.listeners(signal as NodeJS.Signals).filter((l) => l !== handler).length;\n\n // Backstop: DERIVED from the shutdown budget, never a second literal.\n // The two used to be an independent `5000` each, so a drain allowed\n // 5,000 ms raced a `process.exit(1)` firing at 5,000 ms — killing the\n // drain at its deadline, with the wrong exit code, before the residue\n // WARNING (the previous ruling's primary remedy) could print.\n const backstop = setTimeout(\n () => process.exit(128 + signum),\n SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS,\n );\n backstop.unref();\n\n this.shutdown()\n .catch(() => {})\n .finally(() => {\n clearTimeout(backstop);\n if (!weDisplacedDefault) return; // the app owns termination\n // The application had a listener when the signal came (it added it\n // after init()): it owns termination too, so that the order of\n // registration does not change how often its listener runs, or who\n // decides the exit. (It does change which spans that listener ends are\n // delivered: see `BatchSpanProcessor.onSpanEnd`.) The\n // signal is not raised again (its listener would run a second time)\n // and the fail-safe exit is not armed (it ended the listener with code\n // 143, 100 ms later). With no listener at signal time, the 0.8.0 rule\n // below holds.\n if (othersAtSignal > 0) return;\n\n // Our listener is gone (`process.once` + `_doShutdown` removed\n // them), so re-raising reaches Node's default and terminates for\n // real — WIFSIGNALED, not merely an exit code that looks like one.\n try {\n process.kill(process.pid, signal as NodeJS.Signals);\n } catch {\n process.exit(128 + signum);\n }\n // Belt and braces: if the application added a listener DURING our\n // drain, the re-raise above went to it instead of terminating and\n // we would hang exactly as before. unref()'d, so it cannot itself\n // hold open a process that is already leaving.\n const failsafe = setTimeout(() => process.exit(128 + signum), 100);\n failsafe.unref();\n });\n };\n\n process.once(signal, handler);\n this._shutdownHandlers.push({ signal, handler });\n }\n }\n}\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/**\n * Initialize the Risicare SDK. Call once at application startup.\n *\n * @example\n * import { init } from 'risicare';\n * init({ apiKey: 'rsk-...', serviceName: 'my-agent', environment: 'production' });\n */\nexport function init(config?: Partial<RisicareConfig>): void {\n const existing = getGlobalClient() as RisicareClient | undefined;\n if (existing) {\n // F-359: warn loudly when re-init would silently discard a config change.\n // The first init wins; a second init with a different apiKey/endpoint/\n // environment is almost certainly a bug (e.g., a side-effect import that\n // calls init() in a library, then the app's own init() with real config\n // gets ignored).\n if (config) {\n const incoming = resolveConfig(config);\n const diffs: string[] = [];\n const checkedKeys: Array<keyof typeof incoming> = [\n 'apiKey',\n 'endpoint',\n 'environment',\n 'serviceName',\n 'serviceVersion',\n 'sampleRate',\n // Capture is on by default (R9): a library's early init() must not\n // make the program's traceContent: false void in silence.\n 'traceContent',\n ];\n for (const k of checkedKeys) {\n if (incoming[k] !== existing.config[k]) {\n // Don't print apiKey contents — just say \"differs\".\n const newRender = k === 'apiKey' ? '<redacted>' : JSON.stringify(incoming[k]);\n const oldRender = k === 'apiKey' ? '<redacted>' : JSON.stringify(existing.config[k]);\n diffs.push(`${String(k)}: ${oldRender} → ${newRender}`);\n }\n }\n if (diffs.length > 0) {\n console.warn(\n '[risicare] init() called twice with different config; the FIRST call wins. ' +\n 'Call shutdown() before re-initializing. Differences ignored: ' +\n diffs.join(', '),\n );\n } else {\n debug('init() called twice with identical config; no-op');\n }\n } else {\n debug('init() called twice; no-op');\n }\n return;\n }\n\n // RULING §5: a NEW lifecycle starts with no retained tally — otherwise\n // `init(); shutdown(); init()` would serve the FIRST run's losses as if they\n // belonged to the second.\n _finalMetrics = undefined;\n _finalProcessor = undefined;\n _finalActive = false;\n _resetScoreFailures();\n\n const client = new RisicareClient(config);\n setGlobalClient(client);\n setGlobalTracer(client.tracer);\n}\n\n/**\n * Gracefully shut down the SDK. Flushes pending spans before resolving.\n *\n * @param timeoutMs - The shutdown budget in milliseconds (default 5000). It is a\n * hard wall-clock bound. A value that is not a finite number (NaN, Infinity, a\n * string, null) gives 5000. A negative value gives 0. The largest value is\n * 2**31 - 1.\n *\n * At the deadline, `shutdown()` stops the export in flight. Spans still queued\n * and spans in the stopped export are counted as `shutdown_residue`, with one\n * WARNING: they were not confirmed as delivered. The server may have received\n * the spans of the stopped export. Each exporter's own `shutdown()` gets only\n * the time that is left of the budget.\n *\n * Limit: the stop does not end a TLS handshake that stalls. Such a handshake\n * can keep the process alive about 10 s after `shutdown()` returns.\n */\nexport async function shutdown(timeoutMs?: number): Promise<void> {\n // Stop FixRuntime first (stops background refresh)\n try {\n shutdownFixRuntime();\n } catch {\n // FixRuntime may not be initialized\n }\n\n const client = getGlobalClient() as RisicareClient | undefined;\n if (!client) return;\n // RULING §5: the final tally is snapshotted inside `_doShutdown()`, which\n // this reaches and which the signal handlers reach directly. Do NOT add a\n // second snapshot here.\n await client.shutdown(timeoutMs);\n setGlobalClient(undefined);\n setGlobalTracer(undefined);\n}\n\n/**\n * Flush all pending spans without shutting down.\n *\n * @param timeoutMs - The budget in milliseconds (default 5000). It is a hard\n * wall-clock bound on the wait: at the deadline `flush()` resolves `false`.\n * A value that is not a finite number (NaN, Infinity, a string, null) gives\n * 5000. A negative value gives 0. The largest value is 2**31 - 1.\n * @returns `true` only if everything queued at entry was DELIVERED and no span\n * was lost since the previous `flush()` returned. A loss is reported by the next\n * `flush()`, one time. It returns `false` in these cases:\n * - the deadline expired with spans still queued or in flight;\n * - a span was discarded since the previous flush returned (F-SDKCB-001 §6);\n * - the backend rejected a span since the previous flush returned, or its ack\n * did not account for a span;\n * - a `shutdown()` left spans undelivered (`shutdown_residue`) since the previous\n * flush returned. That loss is reported once, as every other loss.\n * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at\n * SIGTERM / SIGINT, or one that nobody awaited) waits for it inside its own\n * deadline, and then answers from the final tally with the same rule. So does a\n * `flush()` after `shutdown()`. Through 0.8.0 both answered from the empty queue.\n * Not active means not true: `flush()` returns `false` before `init()`, with tracing\n * off (`enabled: false`, `RISICARE_TRACING=false`), and with no API key. Through\n * 0.8.0 it returned `true` in those cases: nothing was queued.\n *\n * `flush()` never stops a request that is already sent. At the deadline it stops\n * waiting; the export in flight continues and ends by its own rules.\n *\n * Limit: that export can keep the process alive after `flush()` returns `false`,\n * until its own timeouts end (measured on a silent server: 22 s). To end a\n * process within a bound, call `await shutdown(timeoutMs)`. It stops the export\n * in flight.\n *\n * Scores: `flush()` also waits, inside the same deadline, for each `score()`\n * request that is not complete. It returns `false` when a score is not complete\n * at the deadline, or when a score failed since the previous `flush()` returned.\n * Each failed score makes one flush `false`, as each lost span does.\n *\n * ⚠ Signature change in 0.5.0 — was `Promise<void>`. Existing callers that\n * ignore the result keep working unchanged.\n */\nexport async function flush(timeoutMs?: number): Promise<boolean> {\n // The same rule as the processor: a value that is not a finite number gives\n // the default, so the score wait and the span wait share one deadline.\n const budgetMs = normalizeTimeoutMs(timeoutMs);\n const deadline = Date.now() + budgetMs;\n // Read at entry: two flushes that overlap both report a score that failed\n // before either of them ended.\n const scoreMark = _failedScoresFlushMark;\n const client = getGlobalClient() as RisicareClient | undefined;\n let spansOk: boolean;\n if (client) {\n spansOk = await client.flush(timeoutMs);\n } else if (_finalProcessor) {\n // `shutdown()` clears the global client. The processor of that shutdown\n // answers from its final tally, with its loss mark: a loss that the shutdown\n // counted (the residue too) makes one flush false. Through 0.8.0 only the\n // residue counted, so a rejection or a `transport_refused` drop gave true.\n // `init()` clears it. A client that was never active answers false.\n spansOk = _finalActive && (await _finalProcessor.flush(timeoutMs));\n } else {\n // Never initialised: not active means not true.\n spansOk = false;\n }\n // Pending score requests run in parallel with the span flush. Wait for the\n // remaining scores inside the same deadline.\n const scoresDone = await _waitForPendingScores(deadline - Date.now());\n // The bound ended: the scores that still wait for a slot fail now, with no request.\n if (!scoresDone) _failWaitingScores(SCORE_DEADLINE_REASON);\n _warnHeldScores();\n const failedNow = _failedScores;\n if (failedNow > _failedScoresFlushMark) _failedScoresFlushMark = failedNow;\n return spansOk && scoresDone && failedNow <= scoreMark;\n}\n\n/**\n * Enable tracing at runtime.\n */\nexport function enable(): void {\n const client = getGlobalClient() as RisicareClient | undefined;\n if (client) client.enabled = true;\n}\n\n/**\n * Disable tracing at runtime. Spans will not be created or exported.\n */\nexport function disable(): void {\n const client = getGlobalClient() as RisicareClient | undefined;\n if (client) client.enabled = false;\n}\n\n/**\n * Check whether tracing is currently enabled. False before `init()`, with no API\n * key (also with `RISICARE_TRACING=true`, `enabled: true` or `enable()`), with\n * tracing off, and after `shutdown()` or the SDK's own drain at SIGTERM / SIGINT.\n */\nexport function isEnabled(): boolean {\n const client = getGlobalClient() as RisicareClient | undefined;\n // False after the SDK's own drain at SIGTERM / SIGINT too: the signal path does\n // not clear the global client, but the processor is shut down.\n return client !== undefined && !client.isShutdown && client.enabled;\n}\n\n/**\n * Get the global tracer instance. Returns undefined if not initialized.\n */\nexport function getTracer(): Tracer | undefined {\n return getGlobalTracer() as Tracer | undefined;\n}\n\n/**\n * Get the global tracer, or throw if not initialized.\n * @internal Used by decorators and providers that require an active tracer.\n */\nexport function requireTracer(): Tracer {\n const tracer = getGlobalTracer() as Tracer | undefined;\n if (!tracer) {\n throw new Error(\n 'Risicare SDK not initialized. Call init() before using tracing features.',\n );\n }\n return tracer;\n}\n\n/**\n * Check whether content tracing (prompt/completion capture) is enabled.\n */\nexport function getTraceContent(): boolean {\n const tracer = getGlobalTracer() as Tracer | undefined;\n // Fail-closed when no tracer exists (`init()` has not run, so nothing is\n // exported). NOT the user default: that is `true`, in `resolveConfig`.\n return tracer?.traceContent ?? false;\n}\n\n/**\n * Get SDK metrics: exported spans (accepted by the backend), `rejectedSpans`,\n * dropped spans and their reasons (`unacknowledged` and `quota_exceeded` included; `droppedQuota` is the latter), failed exports,\n * queue stats, and `failedScores` (`score()` requests that failed since\n * `init()`).\n *\n * `sdkState` — SDK-RELEASE-RULING.md §5 — says WHICH of three different facts\n * the numbers are, because before it all three rendered as the same zeros:\n *\n * - `\"uninitialised\"` nothing was ever queued; the zeros are the truth\n * - `\"running\"` live readings from a live processor\n * - `\"shutdown\"` the RETAINED FINAL TALLY. Not live, and says so.\n *\n * The `\"shutdown\"` case is why this field exists. `shutdown()` clears the global\n * client, so this used to answer `droppedSpans: 0` from a hardcoded literal in\n * the very process that had just discarded spans — a guess presented\n * byte-identical to an authoritative answer, which is the W1/W3 class this\n * codebase already ruled against (`cost_source`, `settled`). The remedy there\n * and here is the same: do not hide the value and do not null it, LABEL it.\n * Every field of a retained tally is still true — the queue really is empty,\n * the capacity really is the configured one, and the drop counts describe the\n * whole life of the process, `shutdown_residue` included.\n *\n * ⚠ What it still CANNOT do: report loss to anything OUTSIDE the dying process.\n * A counter in memory about to be freed has no reader, and a SIGKILL takes this\n * and the WARNING together. The WARNING remains the primary signal.\n */\nexport function getMetrics() {\n const client = getGlobalClient() as RisicareClient | undefined;\n if (client && !client.isShutdown) {\n return {\n ...client.processor.getMetrics(),\n failedScores: _failedScores,\n sdkState: 'running' as const,\n };\n }\n if (_finalMetrics) {\n // Copy: a caller mutating the object must not corrupt the one tally the\n // process has left. The tally is read from the processor of the last shutdown,\n // not from the copy that `_doShutdown` took: a span that ends after the drain\n // is counted (`shutdown_residue`) and the tally must show it.\n const tally = _finalProcessor?.getMetrics() ?? _finalMetrics;\n return {\n ...tally,\n failedScores: _failedScores,\n droppedSpansByReason: { ...tally.droppedSpansByReason },\n sdkState: 'shutdown' as const,\n };\n }\n return {\n exportedSpans: 0,\n rejectedSpans: 0,\n failedScores: _failedScores,\n droppedSpans: 0,\n droppedSpansByReason: {\n queue_full: 0,\n transport_refused: 0,\n shutdown_residue: 0,\n unacknowledged: 0,\n quota_exceeded: 0,\n },\n droppedQuota: 0,\n failedExports: 0,\n queueSize: 0,\n queueCapacity: 0,\n queueUtilization: 0,\n sdkState: 'uninitialised' as const,\n };\n}\n\n// ─── reportError ──────────────────────────────────────────────────────────\n\n// Error dedup: SHA256 fingerprint → timestamp. Prevents retry loops from\n// creating N duplicate diagnoses. Matches Python SDK's 5-minute TTL.\nconst _ERROR_DEDUP_TTL_MS = 5 * 60 * 1000; // 5 minutes\nconst _ERROR_DEDUP_MAX = 1000;\nconst _recentErrors = new Map<string, number>(); // fingerprint → Date.now()\n\nfunction _errorFingerprint(err: Error): string {\n const raw = `${err.constructor?.name ?? 'Error'}:${String(err.message ?? '').slice(0, 200)}`;\n return createHash('sha256').update(raw).digest('hex').slice(0, 16);\n}\n\nfunction _isDuplicateError(fingerprint: string): boolean {\n const now = Date.now();\n // Evict expired entries\n for (const [fp, ts] of _recentErrors) {\n if (now - ts > _ERROR_DEDUP_TTL_MS) _recentErrors.delete(fp);\n else break; // Map iterates in insertion order\n }\n if (_recentErrors.has(fingerprint)) return true;\n // Enforce max size\n if (_recentErrors.size >= _ERROR_DEDUP_MAX) {\n const oldest = _recentErrors.keys().next().value;\n if (oldest !== undefined) _recentErrors.delete(oldest);\n }\n _recentErrors.set(fingerprint, now);\n return false;\n}\n\n/**\n * Report a caught exception to the error diagnosis pipeline.\n *\n * Creates an error span that triggers diagnosis and fix generation.\n * Deduplicates identical errors within a 5-minute window (SHA256 fingerprint).\n * This function never throws and is non-blocking.\n *\n * @param error - The caught exception (Error object or string)\n * @param options - Optional attributes and context overrides\n */\nexport function reportError(\n error: unknown,\n options?: { name?: string; attributes?: Record<string, unknown> },\n): void {\n try {\n const tracer = getTracer();\n if (!tracer) return;\n\n const err = error instanceof Error ? error : new Error(String(error ?? 'unknown'));\n const spanName = options?.name ?? `error:${err.constructor.name}`;\n\n // Dedup: suppress identical errors within TTL (matches Python SDK)\n const fp = _errorFingerprint(err);\n if (_isDuplicateError(fp)) {\n debug(`reportError: duplicate suppressed (fp=${fp.slice(0, 8)})`);\n return;\n }\n\n tracer.startSpan({ name: spanName, kind: SpanKind.INTERNAL }, (span) => {\n span.setStatus(SpanStatus.ERROR, err.message);\n span.setAttribute('error', true);\n span.setAttribute('error.type', err.constructor.name);\n // Limits count code points, so a cut never splits a surrogate pair.\n span.setAttribute('error.message', cutCodePoints(err.message, 2000));\n if (err.stack) span.setAttribute('error.stack', cutCodePoints(err.stack, 4000));\n span.setAttribute('risicare.reported_error', true);\n // F-R-REPORTERRCODE-001. `reportError` is the API our own docs name for\n // feeding the diagnosis pipeline, yet it attached error/type/message and\n // NO taxonomy code, while an uncaught throw through a traced frame did —\n // `tracer.ts::Tracer.startSpan` calls `attachErrorCode` on both of its\n // throw handlers. Measured on the published 0.5.2 against the lab: 4\n // uncaught spans carried TOOL.EXECUTION.CRASHED, the reportError span\n // carried none. Same shape as the Python asymmetry, same remedy — reuse\n // the ONE definition rather than re-classifying here.\n attachErrorCode(span, err);\n if (options?.attributes) {\n for (const [k, v] of Object.entries(options.attributes)) {\n span.setAttribute(k, v);\n }\n }\n });\n } catch {\n // Never crash the host application\n debug('reportError failed');\n }\n}\n\n// ─── score ─────────────────────────────────────────────────────────────────\n\n/**\n * A score that `score()` refuses at the call (a value that is not a number or is\n * outside [0, 1], an empty trace id or name). One WARNING, no request, and the\n * score counts as a failed score: `failedScores` rises by 1, so that the next\n * `flush()` is false, as for a score that the gateway refused. The WARNING of the\n * refusal is the one WARNING; `_scoreFailed` is not used, so it writes no second.\n * An SDK that is not active (never initialised, shut down by `shutdown()` or by the\n * SDK's own drain at SIGTERM / SIGINT, tracing off, no key) counts nothing: it was\n * handed no score to deliver. `isEnabled()` is false in the same cases.\n */\nfunction refuseScore(message: string): void {\n warn(message);\n const client = getGlobalClient() as RisicareClient | undefined;\n if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;\n}\n\n/**\n * Record a custom evaluation score on a trace.\n *\n * Sends the score in the background. The root `flush()` waits for it.\n * This function never throws and does not block. At most 50 score requests\n * are in flight at once. Up to 1,000 scores wait for a free slot, with no timer;\n * the 2000 ms bound of a score starts when its request starts. A score that\n * comes when 1,000 already wait fails at once and is counted. When a `flush()`\n * or `shutdown()` bound ends, the scores that still wait fail and are not sent.\n *\n * Delivery: the request stops after 2000 ms and never follows a redirect. A\n * status of 300 or more, an error or the timeout is a failure, and it adds 1\n * to `failedScores` in `getMetrics()`. The first failure writes a WARNING with\n * the score name and the status or the error code. Later failures in the next\n * 10 s are counted, and the next WARNING gives their number. Root `flush()`\n * waits for pending scores inside its deadline, and returns `false` when a\n * score failed since the previous `flush()` returned. An out-of-range value, a\n * value that is not a number, or an empty `traceId` or `name` writes one WARNING,\n * and the SDK does not send the score. It counts as a failed score, so the next\n * `flush()` is false (not when the SDK is not active: then nothing is counted).\n * `true` and `false` count as 1 and 0.\n *\n * If a `mask` is configured on `init()`, `options.comment` is passed to it under\n * the key `score.comment` before the request is built. `traceId`, `spanId` and\n * `name` are NOT masked — they are identifiers the platform joins and groups on.\n *\n * @param traceId - The trace to score\n * @param name - Score name (e.g., \"accuracy\", \"user_satisfaction\")\n * @param value - Score value between 0.0 and 1.0 inclusive\n * @param options - Optional span_id and comment\n */\nexport function score(\n traceId: string,\n name: string,\n value: number,\n options?: { spanId?: string; comment?: string },\n): void {\n try {\n // WARNING, as in the Python SDK. Through 0.7.1 these were debug lines, so\n // a rejected score was invisible without `debug: true`. The WARNING prints\n // the value only when it is a number: a string could forge a log line, and\n // an object's `toString()` could run. A boolean is a number here (true is\n // 1, false is 0), as in the Python SDK.\n const raw: unknown = value;\n if (typeof raw === 'boolean') value = raw ? 1 : 0;\n if (typeof value !== 'number') {\n refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);\n return;\n }\n if (!Number.isFinite(value) || value < 0.0 || value > 1.0) {\n refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);\n return;\n }\n if (typeof traceId !== 'string' || given(traceId) === undefined) {\n refuseScore('score: traceId must be a non-empty string. The SDK does not send this score.');\n return;\n }\n if (typeof name !== 'string' || given(name) === undefined) {\n refuseScore('score: name must be a non-empty string. The SDK does not send this score.');\n return;\n }\n\n const client = getGlobalClient() as RisicareClient | undefined;\n if (!client?.enabled || !client.config.apiKey) return;\n\n // ⚠ FIELD CHANGED 0.6.0 -> 0.7.0: this read `config.endpoint`, the SPAN\n // endpoint, and then composed an API path. That worked only while one\n // Caddy-fronted host served both services. It now reads `apiEndpoint`.\n // The order that sets it is in `config.ts`, `resolveEndpoints`. The\n // default ingest host never names an api host.\n // The `/api` prefix is gone with the proxy that stripped it.\n const endpoint = client.config.apiEndpoint.replace(/\\/+$/, '');\n const url = `${endpoint}/v1/scores`;\n\n // ⚠ THE ONE NON-SPAN EGRESS THE MASK COVERS (F-SDKMASKSCORE-001).\n // This POST does not go through BatchSpanProcessor, so `applyMask` never\n // sees it — `comment` is free customer text on our wire and was uncovered\n // until this call. The ruling (why the same hook rather than a second one,\n // why `name` is deliberately NOT masked, and the caller-thread cost) is in\n // `risicare/masking.py`, \"THE NON-SPAN SURFACE\".\n //\n // Runs BEFORE `JSON.stringify`, so the unmasked value is never serialized.\n // `maskText` is the same primitive `statusMessage` uses, so a throwing mask\n // yields the same marker and the score is still sent.\n let comment = options?.comment;\n if (comment !== undefined && client.config.mask) {\n comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);\n }\n\n const body = JSON.stringify({\n trace_id: traceId,\n name,\n score: value,\n source: 'sdk',\n ...(options?.spanId && { span_id: options.spanId }),\n ...(comment && { comment }),\n });\n\n // The caller does not wait. The score is pending until its request settles,\n // or until it fails while it waits for a slot; root `flush()` waits for it.\n if (_scoresInFlight >= SCORE_MAX_IN_FLIGHT && _scoreWaiters.length >= SCORE_MAX_WAITING) {\n _scoreFailed(name, SCORE_CAP_REASON);\n return;\n }\n let settle!: () => void;\n const request = new Promise<void>((resolve) => (settle = resolve));\n const send = async (): Promise<void> => {\n // The 2000 ms bound starts here, when the request starts.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), SCORE_TIMEOUT_MS);\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${client.config.apiKey}`,\n // F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI\n // server under /v1/, which `main.py::audit_logging_middleware` audits\n // into `audit_logs.user_agent`; ingest reaches the Rust gateway, which\n // discards it. This is the one client-identity visible with no gateway\n // change.\n 'User-Agent': `risicare-js/${SDK_VERSION} node/${process.version}`,\n 'X-Risicare-SDK-Version': SDK_VERSION,\n },\n body,\n // Never follow: a redirect is a misroute, not a route. Through 0.7.1\n // fetch followed a 307 and re-POSTed the score to the login page.\n redirect: 'manual',\n signal: controller.signal,\n });\n if (response.type === 'opaqueredirect' || response.status >= 300) {\n _scoreFailed(name, `HTTP ${response.status || '3xx'}`);\n }\n try {\n await response.body?.cancel();\n } catch {\n // The body is not needed.\n }\n } catch (err) {\n // The cause code tells a refused port, a DNS failure and a reset apart\n // (fetch wraps each of them in the same TypeError).\n const cause = err instanceof Error ? (err as Error & { cause?: { code?: unknown } }).cause : undefined;\n const code = typeof cause?.code === 'string' ? cause.code : undefined;\n const reason = controller.signal.aborted\n ? `no answer within ${SCORE_TIMEOUT_MS} ms`\n : code ?? (err instanceof Error ? err.name : 'Error');\n _scoreFailed(name, reason);\n } finally {\n clearTimeout(timer);\n _scoresInFlight--;\n settle();\n _startWaitingScores();\n }\n };\n const start = (): void => {\n _scoresInFlight++;\n void send();\n };\n if (_scoresInFlight < SCORE_MAX_IN_FLIGHT) {\n start();\n } else {\n _scoreWaiters.push({\n start,\n fail: (reason) => {\n _scoreFailed(name, reason);\n settle();\n },\n });\n }\n _pendingScores.add(request);\n void request.finally(() => _pendingScores.delete(request));\n } catch {\n // Never crash the host application\n debug('score failed');\n }\n}\n","/**\n * Shared state via globalThis — ensures all entry point bundles share\n * the same singleton instances.\n *\n * Problem: tsup with `splitting: false` gives each entry point (index,\n * openai, anthropic, vercel-ai) its own copy of module-level variables.\n * This means `init()` from 'risicare' sets a tracer that 'risicare/openai'\n * can't see — breaking all provider instrumentation silently.\n *\n * Solution: Store all mutable singletons on globalThis with a namespaced\n * prefix. Every bundle reads/writes the same global slots.\n *\n * This pattern is used by React, OpenTelemetry, and other SDKs that must\n * share state across independently bundled entry points.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst G = globalThis as any;\nconst PREFIX = '__risicare_';\n\n// ─── Client & Tracer ────────────────────────────────────────────────────────\n\nexport function getClient(): unknown {\n return G[PREFIX + 'client'];\n}\n\nexport function setClient(client: unknown): void {\n G[PREFIX + 'client'] = client;\n}\n\nexport function getTracer(): unknown {\n return G[PREFIX + 'tracer'];\n}\n\nexport function setTracer(tracer: unknown): void {\n G[PREFIX + 'tracer'] = tracer;\n}\n\n// ─── Context Storage ────────────────────────────────────────────────────────\n\nexport function getContextStorage(): AsyncLocalStorage<unknown> {\n if (!G[PREFIX + 'ctx']) {\n G[PREFIX + 'ctx'] = new AsyncLocalStorage();\n }\n return G[PREFIX + 'ctx'];\n}\n\n// ─── Span Registry ──────────────────────────────────────────────────────────\n\nexport function getRegistry(): Map<string, unknown> {\n if (!G[PREFIX + 'registry']) {\n G[PREFIX + 'registry'] = new Map();\n }\n return G[PREFIX + 'registry'];\n}\n\nexport function getOpCount(): number {\n return G[PREFIX + 'opcount'] ?? 0;\n}\n\nexport function setOpCount(n: number): void {\n G[PREFIX + 'opcount'] = n;\n}\n\n// ─── Debug Flag ─────────────────────────────────────────────────────────────\n\nexport function getDebug(): boolean {\n return G[PREFIX + 'debug'] ?? false;\n}\n\nexport function setDebugFlag(enabled: boolean): void {\n G[PREFIX + 'debug'] = enabled;\n}\n\n// ─── Fix Runtime ────────────────────────────────────────────────────────\n\nexport function getGlobalFixRuntime(): unknown {\n return G[PREFIX + 'fix_runtime'];\n}\n\nexport function setGlobalFixRuntime(runtime: unknown): void {\n G[PREFIX + 'fix_runtime'] = runtime;\n}\n\n// ─── Open provider spans (utils/stream-proxy.ts) ────────────────────────────\n\n/** An observed provider span that is not ended yet. */\nexport interface OpenProviderSpan {\n end(reason: 'shutdown'): void;\n release(): void;\n}\n\nexport interface ProviderSpanState {\n /** The shape of this object. Change it when the shape or a method of OpenProviderSpan changes. */\n version: 1;\n /** Every observed provider span that is still open: `shutdown()` ends them. */\n open: Set<OpenProviderSpan>;\n /** Ends a span when nobody can reach its promise, stream or iterators. */\n registry: FinalizationRegistry<OpenProviderSpan> | undefined;\n}\n\nconst PROVIDER_SPANS = Symbol.for('risicare.providerSpans');\n\n/** True when `s` is a version-1 state that this copy of the SDK can use. */\nfunction usableProviderSpanState(s: unknown): s is ProviderSpanState {\n if (!s || typeof s !== 'object') return false;\n const { version, open, registry } = s as Record<string, unknown>;\n const o = open as Record<PropertyKey, unknown> | undefined;\n return (\n version === 1 &&\n !!o &&\n typeof o.add === 'function' &&\n typeof o.delete === 'function' &&\n typeof o[Symbol.iterator] === 'function' &&\n (registry === undefined || typeof (registry as { register?: unknown }).register === 'function')\n );\n}\n\n/**\n * ONE set and ONE registry for every bundle. Each provider entry point bundles\n * its own copy of stream-proxy.ts (`splitting: false`), and `shutdown()` in the\n * main bundle must see the spans that `risicare/openai` opened.\n *\n * Two installed copies of the SDK share this state too. A copy uses it only\n * when it is version 1 and its shape checks pass; else this function throws,\n * and the caller of this function (stream-proxy.ts) does not observe the call.\n * It never replaces a state that another copy made.\n */\nexport function getProviderSpanState(): ProviderSpanState {\n const found: unknown = G[PROVIDER_SPANS];\n if (found === undefined) {\n const s: ProviderSpanState = {\n version: 1,\n open: new Set(),\n registry:\n typeof FinalizationRegistry === 'function'\n ? new FinalizationRegistry<OpenProviderSpan>((o) => o.release())\n : undefined,\n };\n G[PROVIDER_SPANS] = s;\n return s;\n }\n if (!usableProviderSpanState(found)) {\n throw new TypeError('the shared provider span state is not version 1');\n }\n return found;\n}\n","/**\n * Internal logger for the Risicare SDK.\n *\n * Centralizes all diagnostic output so that:\n * - Debug messages are gated by a single flag (zero-cost when disabled)\n * - Warnings always fire (operational alerts like queue full)\n * - All output goes to stderr with a consistent [risicare] prefix\n * - A future custom logger callback can be added in one place\n */\n\nimport { getDebug, setDebugFlag } from '../globals.js';\n\n/**\n * Enable or disable debug logging. Called once during init().\n * @internal\n */\nexport function setDebug(enabled: boolean): void {\n setDebugFlag(enabled);\n}\n\n/**\n * Log a debug message. Only outputs when debug mode is enabled.\n * @internal\n */\nexport function debug(msg: string): void {\n if (getDebug()) {\n process.stderr.write(`[risicare] ${msg}\\n`);\n }\n}\n\n/**\n * Log a warning. Always outputs regardless of debug mode.\n * Use sparingly — only for operational issues the user should see.\n * @internal\n */\nexport function warn(msg: string): void {\n process.stderr.write(`[risicare] WARNING: ${msg}\\n`);\n}\n\n/**\n * Log an informational line. Always outputs regardless of debug mode.\n * Use only for rare state changes the user should see once (for example, the\n * export pause for the monthly quota has ended).\n * @internal\n */\nexport function info(msg: string): void {\n process.stderr.write(`[risicare] INFO: ${msg}\\n`);\n}\n","/**\n * Text helpers for strings that go on the wire.\n *\n * @internal Not public API.\n */\n\n/**\n * The first `max` CODE POINTS of `text`, as Python's `text[:max]` gives.\n *\n * Not `text.slice(0, max)`: that counts UTF-16 code units and can keep the\n * first half of a surrogate pair. JSON.stringify writes a lone half as\n * `\\ud83d`, and a strict JSON parser refuses the whole request body, so the\n * whole batch is lost. The walk stops at `max` code points, so a very long\n * text costs no more than the part that is kept.\n */\nexport function cutCodePoints(text: string, max: number): string {\n // A text of at most `max` code units has at most `max` code points.\n if (text.length <= max) return text;\n let units = 0;\n for (let points = 0; points < max && units < text.length; points++) {\n units += (text.codePointAt(units) as number) > 0xffff ? 2 : 1;\n }\n return text.slice(0, units);\n}\n","/**\n * Text that is safe to put in a log line: THE one scrub function of the SDK.\n * Python twin: `risicare/_error_text.py` (`scrub_text`, `safe_url`).\n *\n * Every text that comes from the network (a header, a body, a redirect target) or\n * from an error, and that goes into a log line of the exporters, the fix loader or\n * `score()`, goes through `scrubText`. It:\n * 1. removes each key it is given, and `RISICARE_API_KEY`, in any case of letters\n * (a literal match: a key with regex metacharacters is not read as a pattern);\n * 2. also finds a key that is percent-encoded: when the URL-decoded copy of the\n * text holds a key, the DECODED text is printed, with the key removed;\n * 3. makes the text one line (each control character becomes a space);\n * 4. cuts the text at `limit` code points (default 200).\n *\n * @internal Not public API.\n */\nimport { cutCodePoints } from './text.js';\n\nexport const KEY_MARKER = '[REDACTED-KEY]';\n\nconst CONTROL = new RegExp('[\\\\u0000-\\\\u001f\\\\u007f-\\\\u009f\\\\u2028\\\\u2029]', 'g');\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/** Decode %XX sequences. A sequence that is not valid UTF-8 is decoded byte by byte. */\nfunction percentDecode(text: string): string {\n try {\n return decodeURIComponent(text);\n } catch {\n return text.replace(/%([0-9A-Fa-f]{2})/g, (_m, hex: string) => String.fromCharCode(parseInt(hex, 16)));\n }\n}\n\nfunction keyPattern(keys: ReadonlyArray<string | undefined | null>): RegExp | null {\n const values = new Set<string>();\n for (const k of [...keys, process.env.RISICARE_API_KEY]) if (k) values.add(k);\n if (values.size === 0) return null;\n // The longest value first, so that a key that contains another key is removed whole.\n const ordered = [...values].sort((a, b) => b.length - a.length);\n return new RegExp(ordered.map(escapeRegExp).join('|'), 'gi');\n}\n\n/** `text` as one line, with every given key removed, at most `limit` code points. */\nexport function scrubText(text: unknown, keys: ReadonlyArray<string | undefined | null>, limit = 200): string {\n let out: string;\n try {\n out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);\n } catch {\n out = typeof text;\n }\n const pattern = keyPattern(keys);\n if (pattern !== null) {\n if (out.includes('%')) {\n const decoded = percentDecode(out);\n pattern.lastIndex = 0;\n if (decoded !== out && pattern.test(decoded)) out = decoded;\n }\n pattern.lastIndex = 0;\n out = out.replace(pattern, KEY_MARKER);\n }\n return cutCodePoints(out.replace(CONTROL, ' '), limit);\n}\n\n/**\n * `url` without userinfo, query and fragment: scheme, host, port and path only. The SDK\n * prints an endpoint in WARNING and debug lines; a secret in its userinfo\n * (`http://user:secret@host`) or its query (`?k=secret`) must not reach the log.\n */\nexport function safeUrl(url: string): string {\n try {\n const u = new URL(url);\n const path = u.pathname === '/' && !/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]*\\//i.test(url) ? '' : u.pathname;\n return `${u.protocol}//${u.host}${path}`;\n } catch {\n return url.split('?')[0].split('#')[0].replace(/\\/\\/[^/@]*@/, '//');\n }\n}\n\n/** True when `url` holds userinfo (`user:password@host`). `fetch` refuses such a URL. */\nexport function hasCredentials(url: string): boolean {\n try {\n const u = new URL(url);\n return u.username !== '' || u.password !== '';\n } catch {\n return false;\n }\n}\n","/**\n * Customer-supplied masking of span content, applied before anything leaves the process.\n *\n * The full rationale — why this is the ONLY layer rather than defence in depth,\n * why the hook carries the key, what is deliberately not masked, and the\n * fail-closed-per-field ruling — is written once, in the Python twin:\n * `packages/risicare-sdk/src/risicare/masking.py`. This file mirrors it. Where\n * the two languages diverge, the divergence is called out inline below; do not\n * \"align\" them without reading both.\n *\n * ── Mirrored from Python ─────────────────────────────────────────────────────\n * • signature `mask(key, value) => value` — the key is REQUIRED, because our\n * span model has no input/output fields: the prompt and the model name are\n * both plain entries of `span.attributes`, so a keyless hook cannot tell\n * them apart and `() => '***'` would erase every dashboard label.\n * • masked: every attribute value, `statusMessage`, every event-attribute\n * value, every link-attribute value — plus `score.comment`, the one key\n * that is NOT a span field (see {@link SCORE_COMMENT_KEY}).\n * • NOT masked: traceId / spanId / parentSpanId, `span.name`, `event.name`,\n * and the typed identity + llm columns (agentId, agentName, agentType,\n * sessionId, toolName, llmModel, …). Masking an identifier breaks the\n * customer's own joins — the F-39C lesson. The OTel-style attribute forms\n * (`agent.name`, `session.user_id`) live in `attributes` and ARE masked.\n * • no type narrowing: the hook sees numbers and booleans too. A card number\n * is representable as a number, and deciding otherwise on the customer's\n * behalf is the quiet narrowing this codebase keeps paying for.\n * • fail closed per FIELD: a throwing hook yields `MASK_ERROR_MARKER` for\n * that field and the span is exported intact. Never drop the span — the\n * SDK is the last place the data exists, so a drop here is permanent loss,\n * and it additionally orphans the span's children for zero extra safety.\n * • idempotent: `_exportBatch` can re-queue a refused batch, and a user\n * callback cannot be assumed idempotent, so a masked span is flagged.\n *\n * ── Where JS DIFFERS from Python, and it matters ─────────────────────────────\n * 1. There is no `exceptions[]` on the JS Span — `toPayload()` emits none — so\n * there are no `exceptions.{i}.*` keys here. A port that adds exceptions to\n * the JS span must add them here in the same change.\n * 2. ⚠ THE HOT-PATH COST IS STRICTLY WORSE THAN PYTHON'S. Python runs the mask\n * on a background worker THREAD, so a slow mask costs only drain rate. Node\n * has one thread: `_exportBatch` is `async`, but the mask itself is sync, so\n * while it runs NOTHING else in the customer's process runs — not their\n * request handlers, not their timers. In Python a slow mask degrades\n * throughput; in JS it degrades the whole application. The budget warning\n * below is not advisory decoration here.\n * 3. `_masked` is a real private field on `Span` (we own that class), rather\n * than Python's `setattr` — which Python needs only because its `Span`\n * lives in the separate `risicare-core` package.\n */\n\nimport { warn, debug } from './utils/log.js';\nimport type { Span } from './span.js';\n\n/**\n * A customer mask callback.\n *\n * @param key Fully-qualified path of the value: an attribute key as-is\n * (`\"gen_ai.prompt.0.content\"`), or a dotted path\n * (`\"statusMessage\"`, `\"events.0.attributes.foo\"`,\n * `\"links.0.attributes.bar\"`).\n * @param value The current value — any type, not just string.\n * @returns The replacement, or `value` unchanged.\n */\nexport type MaskFn = (key: string, value: unknown) => unknown;\n\n/** Called with `(key, error)` for every field whose mask threw. */\nexport type MaskErrorReporter = (key: string, error: unknown) => void;\n\n/**\n * Substituted for a value whose mask threw. Fixed, deliberately not\n * valid-looking, and greppable in a dashboard.\n */\nexport const MASK_ERROR_MARKER = '<risicare:mask-error>';\n\n/**\n * The masking hot-path budget, in ms per span. MEASURED and NAMED, never\n * ENFORCED — see the Python twin. A \"disable the mask because it is slow\" rule\n * would fail OPEN on a security control, silently, which is the worst outcome\n * available; so exceeding this warns and nothing else.\n *\n * 1 ms/span leaves a 500-span batch at 500 ms, under the 1,000 ms default\n * `batchTimeoutMs` — the last point at which one batch's masking still fits\n * inside one batch's period. Past that the queue provably grows, and in Node\n * the event loop is blocked for the excess.\n */\nexport const MASK_BUDGET_MS_PER_SPAN = 1.0;\n\n/** Rate-limit window for both mask warnings, in ms. */\nexport const MASK_WARN_WINDOW_MS = 300_000;\n\n/**\n * The key the hook receives for `score(traceId, name, value, { comment })`.\n *\n * ⚠ THE ONE KEY THAT IS NOT A SPAN FIELD. `score()` POSTs direct to\n * `/api/v1/scores` (`client.ts`), outside `BatchSpanProcessor` and therefore\n * outside {@link applyMask} — so its free-text `comment` was uncovered until\n * F-SDKMASKSCORE-001. The full ruling (why the same hook rather than a second\n * one, why the score's `name` is deliberately NOT masked, and why the cost lands\n * on the caller here rather than on the exporter) is written once in the Python\n * twin: `risicare/masking.py`, \"THE NON-SPAN SURFACE\".\n *\n * A constant, not a literal at the call site, so the two SDKs cannot drift and a\n * customer's `if (key === ...)` has something importable to compare against.\n */\nexport const SCORE_COMMENT_KEY = 'score.comment';\n\n/**\n * Mask ONE free-text value that reaches the wire raw, and coerce the result.\n *\n * The exported form of the same primitive {@link applyMask} uses for\n * `statusMessage`. It exists so a non-span egress (today: `score(comment)`) gets\n * byte-identical semantics to a span field — same marker, same\n * fail-closed-per-field rule, same coercion — rather than a second\n * implementation that drifts from this one.\n *\n * Never throws.\n */\nexport function maskText(\n mask: MaskFn,\n key: string,\n value: unknown,\n onError?: MaskErrorReporter,\n): string {\n return maskString(mask, key, value, onError);\n}\n\n/** Apply `mask` to one value. Never throws; fails closed to the marker. */\nfunction maskOne(\n mask: MaskFn,\n key: string,\n value: unknown,\n onError: MaskErrorReporter | undefined,\n): unknown {\n try {\n return mask(key, value);\n } catch (e) {\n onError?.(key, e);\n return MASK_ERROR_MARKER;\n }\n}\n\n/**\n * Apply `mask` to a field that reaches the wire as a raw JSON string, and\n * coerce the result.\n *\n * `HttpExporter` serializes the WHOLE batch in one `JSON.stringify`\n * (`exporters/http.ts:119`). Unlike Python's `json.dumps`, `JSON.stringify`\n * does not throw on most objects — but it DOES throw on a circular reference\n * or a BigInt, and it silently emits `null` for a function or `undefined`,\n * which would erase the field without saying so. Coercing here keeps one bad\n * return value from one field from taking out every other span in the batch.\n */\nfunction maskString(\n mask: MaskFn,\n key: string,\n value: unknown,\n onError: MaskErrorReporter | undefined,\n): string {\n const masked = maskOne(mask, key, value, onError);\n if (typeof masked === 'string') return masked;\n try {\n return String(masked);\n } catch (e) {\n // A `Symbol`, or an object with a hostile `toString`.\n onError?.(key, e);\n return MASK_ERROR_MARKER;\n }\n}\n\n/** Mask every value of an attribute record IN PLACE. */\nfunction maskAttributes(\n mask: MaskFn,\n prefix: string,\n attrs: Record<string, unknown>,\n onError: MaskErrorReporter | undefined,\n): void {\n // Snapshot the keys: the hook is customer code and must not be able to make\n // us iterate a record it is concurrently reshaping.\n for (const k of Object.keys(attrs)) {\n attrs[k] = maskOne(mask, prefix + k, attrs[k], onError);\n }\n}\n\n/** Whether `applyMask` has already run over this span. */\nexport function isMasked(span: Span): boolean {\n return (span as unknown as { _risicareMasked?: boolean })._risicareMasked === true;\n}\n\nfunction markMasked(span: Span): void {\n try {\n (span as unknown as { _risicareMasked?: boolean })._risicareMasked = true;\n } catch {\n // Only reachable for a frozen/sealed stand-in. Degrade to \"may be masked\n // again on re-queue\", never to a throw inside the export path.\n debug('Could not mark span as masked; a re-queue may re-mask it');\n }\n}\n\n/**\n * Mask every content-bearing field of `span`, in place, exactly once.\n *\n * Never throws. A field whose mask throws is replaced with\n * {@link MASK_ERROR_MARKER}; the span is always preserved.\n */\nexport function applyMask(span: Span, mask: MaskFn, onError?: MaskErrorReporter): void {\n if (isMasked(span)) return;\n\n // ── attributes ─────────────────────────────────────────────────────────────\n if (span.attributes && typeof span.attributes === 'object') {\n maskAttributes(mask, '', span.attributes, onError);\n }\n\n // ── status message ─────────────────────────────────────────────────────────\n if (span.statusMessage !== undefined) {\n span.statusMessage = maskString(mask, 'statusMessage', span.statusMessage, onError);\n }\n\n // ── events ─────────────────────────────────────────────────────────────────\n // `event.name` is NOT masked — it is the timeline's grouping key, same\n // argument as `span.name`.\n if (Array.isArray(span.events)) {\n span.events.forEach((event, i) => {\n if (event?.attributes && typeof event.attributes === 'object') {\n maskAttributes(mask, `events.${i}.attributes.`, event.attributes, onError);\n }\n });\n }\n\n // ── links ──────────────────────────────────────────────────────────────────\n // `traceId` / `spanId` on a link are structural: masking them severs the\n // link, which is the one thing a link is for.\n if (Array.isArray(span.links)) {\n span.links.forEach((link, i) => {\n if (link?.attributes && typeof link.attributes === 'object') {\n maskAttributes(mask, `links.${i}.attributes.`, link.attributes, onError);\n }\n });\n }\n\n markMasked(span);\n}\n\n// ── content capture gate (traceContent) ───────────────────────────────────────\n//\n// ⚠ THIS IS A CAPTURE SWITCH, NOT A REDACTION FEATURE. `mask` above stays the\n// only pre-export redaction hook. The gate is a KEY-SHAPE filter, and it lives in\n// this module because this module already owns the one walk both content paths\n// cross. The key rule never reads a value. The one exception is the value rule V\n// below: it reads the STRUCTURE of one JSON-object value (its keys), never the\n// text in it.\n//\n// The Python twin is `risicare/masking.py::strip_content` and the two are kept\n// character-for-character equivalent in RULE — same exact sets, same segment and\n// suffix rules, same marker, same walk. Four divergences of exactly this shape have been\n// measured in this campaign (`debug` gated differently; `deleted_at IS NULL` in\n// the gateway only; three Redis cache-clear sites; `reportError` dead in ESM\n// only), so a one-sided fix here would become the fifth.\n//\n// Before 0.5.1 `traceContent` was carried by the Tracer (`tracer.ts`) behind a\n// getter and consulted ONLY by the provider patches. Measured on the published\n// 0.5.0: `getTraceContent()` returned false and a hand-set\n// `gen_ai.prompt.0.content` still reached the wire byte-for-byte.\n\n// ⚠ THE RULE IS THE JOINT CONTENT-KEY CORPUS v4 OF THE GATEWAY AND THE SDKs, AND\n// THE THREE GATES MUST AGREE. `risicare-ingestion` `content_control.rs` holds the\n// same rule, and it is the only gate for OTLP and for the SDKs already published.\n// Three corpora are the contract, and the gate gives every verdict of each:\n// `tests/fixtures/content-keys-v4.json` (the joint corpus, a byte-identical copy\n// of the gateway's file, with the value rule V and the `error_text` section that\n// the SDK does not apply; version 3 stays, with its pin and its key verdicts), `tests/fixtures/content-keys-v2.json` (the SDK corpus,\n// the same file in both SDKs) and `tests/fixtures/content-keys-gateway-v2.json`\n// (a byte-identical copy of the gateway's `content-keys-v2.json`, R41). Through\n// 0.6.0 the rule was the last segment `content`, the suffix `_content` and 2\n// exact keys, so `input.value`, `output.value`, `gen_ai.input.messages`,\n// `gen_ai.output.messages`, a bare `gen_ai.prompt` and CrewAI's task description\n// passed with traceContent off. v1 then kept the Vercel `ai.*`, Google ADK\n// `gcp.vertex.agent.*`, Pydantic AI, OpenLLMetry `crewai.*` and Mastra keys, the\n// lists of tool definitions, and the body of the OTel v1.36 message events.\n// ⚠ FAIL CLOSED: E and C also hold third-party content keys (OTel GenAI,\n// OpenInference, OpenLLMetry) that no v1 rule matched at first. A doubtful key is\n// content. The full statement of the rule (E, S, C, N, X, KEEP, the message\n// event rule M and the value rule V) is in the Python twin, `masking.py`.\n\n/** E — matched EXACTLY. A substring match would eat `*_system_prompt_length`. */\nconst CONTENT_KEYS_EXACT: ReadonlySet<string> = new Set([\n // spec v1\n 'gen_ai.system_prompt', // anthropic, bedrock\n 'gen_ai.prompt.message', // cohere\n 'gen_ai.prompt', // OTel GenAI (deprecated form)\n 'gen_ai.completion',\n 'gen_ai.input.messages', // OTel GenAI\n 'gen_ai.output.messages',\n 'gen_ai.system_instructions',\n 'gen_ai.tool.call.arguments',\n // Corpus v2: the list of tool definitions of a request. The names,\n // descriptions and schemas in it are text that the customer wrote.\n 'gen_ai.tool.definitions',\n 'gen_ai.tool.call.result',\n 'input.value', // OpenInference\n 'output.value',\n 'llm.prompts',\n 'llm.prompt_template.template',\n 'llm.prompt_template.variables',\n 'task_description', // CrewAI\n // ⚠ EXTENSION to spec v1: content keys that the Python SDK's integrations emit\n // and that no v1 rule strips. Kept here too, so the two SDKs agree on the rule.\n 'framework.crewai.task_description',\n 'framework.crewai.agent_goal',\n 'framework.crewai.agent_output',\n 'framework.crewai.result',\n 'framework.autogen.last_message',\n 'framework.autogen.reply',\n 'framework.autogen.response',\n 'framework.openai_agents.input',\n 'framework.openai_agents.output',\n 'framework.dspy.signature',\n 'gen_ai.request.messages',\n 'agent.action.input',\n 'agent.action.log',\n 'agent.finish.output',\n 'tool.input',\n 'tool.output',\n 'retriever.query',\n 'retriever.first_doc',\n // ⚠ FAIL CLOSED: third-party content keys that no other rule strips.\n 'gen_ai.retrieval.query.text', // OTel GenAI\n 'gen_ai.retrieval.documents',\n 'gen_ai.evaluation.explanation',\n 'llm.function_call', // OpenInference\n 'llm.choices',\n 'reranker.query',\n 'audio.transcript',\n 'traceloop.entity.input', // OpenLLMetry\n 'traceloop.entity.output',\n // Gateway corpus v2 (R41): the content keys of more frameworks. The same 75\n // keys as `CONTENT_KEYS_EXACT` in the gateway's `content_control.rs`.\n 'agent.backstory', // OpenInference\n 'agent.goal',\n 'llm.available_functions',\n 'llm.tools',\n 'ai.prompt', // Vercel AI SDK\n 'ai.prompt.messages',\n 'ai.prompt.tools',\n 'ai.response.files',\n 'ai.response.object',\n 'ai.response.reasoning',\n 'ai.response.text',\n 'ai.response.toolCalls',\n 'ai.result.object', // the older Vercel names\n 'ai.result.text',\n 'ai.result.toolCalls',\n 'ai.toolCall.args',\n 'ai.toolCall.result',\n 'ai.value', // the text of an embedding call\n 'ai.values',\n 'final_result', // Pydantic AI\n 'model_request_parameters',\n 'pydantic_ai.all_messages',\n 'tool_arguments',\n 'tool_response',\n 'gcp.vertex.agent.data', // Google ADK\n 'gcp.vertex.agent.llm_request',\n 'gcp.vertex.agent.llm_response',\n 'gcp.vertex.agent.tool_call_args',\n 'gcp.vertex.agent.tool_response',\n 'gen_ai.task.input', // OpenLLMetry\n 'gen_ai.task.output',\n 'sk.available_functions', // Semantic Kernel\n]);\n\n/**\n * C — last segment -> the earlier segments that make it content (empty: always).\n * The last-segment KEEP rule does not override C.\n */\nconst CONTENT_LAST_SEGMENT_IN_CONTEXT: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n ['function_call_arguments_json', new Set<string>()], // OpenInference `message.*`\n ['data', new Set(['message_content'])],\n ['url', new Set(['image'])], // `image.url` can hold base64 data\n ['metadata', new Set(['document', 'documents'])],\n // Gateway corpus v2: a list of tool definitions. The `description` of one tool\n // on a tool span (`tool.description`) is not content; the descriptions in a list are.\n ['description', new Set(['definitions', 'functions', 'tools'])],\n ['json_schema', new Set(['tool', 'tools'])],\n ['parameters', new Set(['definitions', 'functions', 'tool', 'tools'])],\n // Gateway corpus v2: the Mastra span I/O, `mastra.<span type>.input|output`.\n ['input', new Set(['mastra'])],\n ['output', new Set(['mastra'])],\n]);\n\n/** S — with a last segment `text` or `arguments`, content when an earlier segment is one of these. */\nconst CONTENT_CONTAINER_SEGMENTS: ReadonlySet<string> = new Set([\n 'message',\n 'messages',\n 'message_content',\n 'contents',\n 'embedding',\n 'embeddings',\n 'document',\n 'documents',\n 'tool_call',\n 'tool_calls',\n 'function',\n // Gateway corpus v2: LiteLLM `gen_ai.completion.{i}.function_call.arguments` and\n // OpenInference `llm.prompts.{i}.prompt.text`.\n 'function_call',\n 'prompt',\n 'prompts',\n]);\n\n/**\n * N — a first segment whose keys are content unless a KEEP rule names them\n * (OpenLLMetry CrewAI `crewai.<class>.<field>`). A bare `crewai` is not content,\n * and only the FIRST segment counts.\n */\nconst CONTENT_FIRST_SEGMENTS: ReadonlySet<string> = new Set(['crewai']);\n\n/**\n * M — span events whose attributes hold one message: the OTel v1.36 message\n * events and, by prefix, OpenLLMetry's `gen_ai.content.*` events.\n */\nconst CONTENT_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'gen_ai.assistant.message',\n 'gen_ai.choice',\n 'gen_ai.system.message',\n 'gen_ai.tool.message',\n 'gen_ai.user.message',\n]);\nconst CONTENT_EVENT_PREFIX = 'gen_ai.content.';\n\n/** M — attributes of a message event that are never content, beside the KEEP rules. */\nconst CONTENT_EVENT_KEEP_KEYS: ReadonlySet<string> = new Set(['gen_ai.provider.name', 'gen_ai.system']);\n\n/** Never content. Wins over every strip rule. */\nconst CONTENT_KEYS_KEEP_EXACT: ReadonlySet<string> = new Set([\n 'gen_ai.response.content_type',\n 'gen_ai.response.content_blocks',\n 'gen_ai.prompt.parts',\n 'gen_ai.prompt.count',\n 'gen_ai.response.choices',\n 'gen_ai.completion.tool_calls',\n]);\n\n/** Never content by the last segment. Wins over S and N, never over E, C or X. */\nconst KEEP_LAST_SEGMENTS: ReadonlySet<string> = new Set([\n 'role',\n 'name',\n 'id',\n 'type',\n 'count',\n 'index',\n 'model',\n 'finish_reason',\n 'mime_type',\n // Gateway v2 at risicare-ingestion main (PR 94): a model name\n // (`crewai.agent.llm`) and the crew process type are not content.\n 'llm',\n 'process',\n]);\nconst KEEP_LAST_SUFFIXES = ['_length', '_tokens', '_count'] as const;\n\n/**\n * V — a key whose value is a JSON object of request parameters -> the keys of\n * that object that are content, in their normalised form ({@link normalisedKey}:\n * `A` to `Z` lower case, no `_`). A new key is ONE line here (and in the Python\n * twin and the gateway's `CONTENT_IN_JSON_OBJECT`, with the corpus). The rule\n * (corpus v4): the value is a JSON object, or JSON text of one; a listed key gets\n * the marker at every depth, and when a part of a dotted key is listed; every\n * other entry is walked with the key rule under the key path\n * `llm.invocation_parameters.<path>`; text that starts as JSON is walked as JSON,\n * and gets the marker whole when it does not parse (cut text, `1e400`); the value\n * at the key is written back as compact JSON; a value that is not a JSON object\n * gets the marker whole; the key matches a flat attribute key or the dotted path\n * of a nested value, and a flat key `llm.invocation_parameters.<path>` takes the\n * same rule. The walk does not mark error text (only the project switch does,\n * R41b), and JSON text keeps the key order of the value (the gateway sorts the\n * keys).\n */\nconst CONTENT_IN_JSON_OBJECT: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n [\n 'llm.invocation_parameters',\n new Set([\n 'additionalinstructions', // OpenAI assistants run\n 'chathistory', // Cohere\n 'contents', // Gemini\n 'documents', // Cohere RAG\n 'functions',\n 'input',\n 'inputtext', // Bedrock Titan\n 'instructions',\n 'message', // Cohere\n 'messages',\n 'preamble', // Cohere\n 'prediction', // OpenAI predicted output\n 'prompt',\n 'system', // Anthropic\n 'systeminstruction', // Gemini\n 'texts', // Cohere embed\n 'toolconfig', // Gemini\n 'tools',\n ]),\n ],\n]);\n\n/**\n * V — each dotted path that leads to a key of `CONTENT_IN_JSON_OBJECT` (`llm` for\n * `llm.invocation_parameters`): the gate reads a nested value only below one.\n */\nconst VALUE_RULE_PREFIXES: ReadonlySet<string> = new Set(\n [...CONTENT_IN_JSON_OBJECT.keys()].flatMap((key) => {\n const segments = key.split('.');\n return segments.slice(1).map((_, i) => segments.slice(0, i + 1).join('.'));\n }),\n);\n\n/**\n * Replaces a stripped value, rather than deleting the key.\n *\n * Deleting would make \"the customer sent no prompt\" and \"the customer disabled\n * capture\" indistinguishable downstream — the W1/W3 honesty rule: label the\n * absence, never forge it.\n */\nexport const CONTENT_OMITTED_MARKER = '<risicare:content-omitted>';\n\nfunction hasKeepLastSegment(last: string): boolean {\n return KEEP_LAST_SEGMENTS.has(last) || KEEP_LAST_SUFFIXES.some((x) => last.endsWith(x));\n}\n\n/**\n * Whether `key` names a customer-content attribute (content-key spec v2).\n * Pure function of the KEY. Never looks at the value.\n *\n * Content when ANY is true — E: an exact key; S: the last segment is `content`,\n * or it is `text` / `arguments` under a container segment; C: a last segment in\n * its context, such as `url` under `image`; N: the first segment is `crewai` and\n * the key has more than one segment; X: the key ends in `_content`. Never\n * content: the exact-KEEP list (wins over all), or a last segment such as\n * `role`, `name`, `model`, `*_tokens` (wins over S and N only).\n */\nexport function isContentKey(key: string): boolean {\n if (CONTENT_KEYS_KEEP_EXACT.has(key)) return false;\n if (CONTENT_KEYS_EXACT.has(key) || key.endsWith('_content')) return true; // E, X\n const segments = key.split('.');\n const last = segments[segments.length - 1];\n const context = CONTENT_LAST_SEGMENT_IN_CONTEXT.get(last);\n if (context && (context.size === 0 || segments.slice(0, -1).some((s) => context.has(s)))) {\n return true; // C — `...message_content.image.image.url`\n }\n if (hasKeepLastSegment(last)) {\n return false; // `...tool_call.function.name` stays\n }\n if (segments.length > 1 && CONTENT_FIRST_SEGMENTS.has(segments[0])) return true; // N\n if (last === 'content') return true; // S\n if (last === 'text' || last === 'arguments') {\n return segments.slice(0, -1).some((s) => CONTENT_CONTAINER_SEGMENTS.has(s)); // S\n }\n return false;\n}\n\n/** Whether a span event of this `name` holds one message (rule M). */\nexport function isContentEvent(name: string): boolean {\n return CONTENT_EVENT_NAMES.has(name) || name.startsWith(CONTENT_EVENT_PREFIX);\n}\n\n/**\n * Whether `key` is content as an attribute of a message event (rule M). Fail\n * closed: every key is content unless a KEEP rule or `CONTENT_EVENT_KEEP_KEYS`\n * names it. Pure function of the KEY.\n */\nexport function isContentEventAttribute(key: string): boolean {\n if (isContentKey(key)) return true;\n const last = key.slice(key.lastIndexOf('.') + 1);\n return !(\n CONTENT_KEYS_KEEP_EXACT.has(key) ||\n CONTENT_EVENT_KEEP_KEYS.has(key) ||\n hasKeepLastSegment(last)\n );\n}\n\n/**\n * V — the content keys of the value rule that names `keyPath` or `key`. The\n * gateway's `json_object_content_keys`: the full dotted path or the entry key\n * alone matches, and the first rule of the table wins.\n */\nfunction jsonObjectContentKeys(keyPath: string, key: string): ReadonlySet<string> | undefined {\n for (const [ruleKey, keys] of CONTENT_IN_JSON_OBJECT) {\n if (ruleKey === keyPath || ruleKey === key) return keys;\n }\n return undefined;\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * V — a flat key below a key of a value rule\n * (`llm.invocation_parameters.extra_body.system`): the path after the rule key,\n * and the content keys of the rule. The gateway's `flat_value_rule`: the dotted\n * path or the key alone matches.\n */\nfunction flatValueRule(keyPath: string, key: string): [string, ReadonlySet<string>] | undefined {\n for (const [ruleKey, keys] of CONTENT_IN_JSON_OBJECT) {\n for (const k of [keyPath, key]) {\n if (k.startsWith(`${ruleKey}.`)) return [k.slice(ruleKey.length + 1), keys];\n }\n }\n return undefined;\n}\n\n/**\n * V — a key in its normalised form: `A` to `Z` become lower case and each `_` is\n * removed. Only ASCII letters change (`toLowerCase` changes other letters too),\n * so JavaScript, Python and the gateway give the same form.\n */\nexport function normalisedKey(key: string): string {\n return key.replace(/_/g, '').replace(/[A-Z]/g, (c) => c.toLowerCase());\n}\n\n/** V — whether `key`, or one of its parts between dots, is a listed key. */\nfunction namesListedKey(key: string, keys: ReadonlySet<string>): boolean {\n return key.split('.').some((part) => keys.has(normalisedKey(part)));\n}\n\n/**\n * V — whether the key rule withholds the value of `key` at `keyPath`. The gateway\n * also names the error-text keys here; only the project switch withholds error\n * text (R41b), so the SDK does not.\n */\nfunction isKeyRuleText(keyPath: string, key: string): boolean {\n return isContentKey(keyPath) || isContentKey(key);\n}\n\n/**\n * V — whether `text` starts as a JSON object or list, after JSON white space\n * (space, tab, line feed, carriage return).\n */\nfunction startsAsJson(text: string): boolean {\n return /^[ \\t\\n\\r]*[{[]/.test(text);\n}\n\n/**\n * V — parse JSON text as the gateway does. Throws when it does not parse. A\n * number out of the range of a 64-bit float (`1e400`) does not parse in the\n * gateway; `JSON.parse` reads it as Infinity, so it is refused here.\n */\nfunction parseJson(text: string): unknown {\n return JSON.parse(text, (_key, value: unknown) => {\n if (typeof value === 'number' && !Number.isFinite(value)) {\n throw new RangeError('not JSON: a number out of range');\n }\n return value;\n });\n}\n\n/**\n * V — an object or an array read through its JSON form (the form the exporter\n * sends), as a new value: the caller's object does not change. Throws when it\n * cannot be read (a cycle, a BigInt, a non-finite number: `JSON.stringify`\n * writes Infinity and NaN as null, and the Python twin refuses them).\n */\nfunction jsonCopy(value: unknown): unknown {\n return parseJson(\n JSON.stringify(value, (_key, v: unknown) => {\n if (typeof v === 'number' && !Number.isFinite(v)) throw new RangeError('not JSON: a non-finite number');\n return v;\n }),\n );\n}\n\n/**\n * V — apply the value rule to one value. Returns the new value and the count.\n *\n * A string is parsed and written back as compact JSON. An object is read through\n * its JSON form, so the result is a new object and the caller's object does not\n * change. A listed key gets the marker at every depth; every other entry is\n * walked ({@link omitInParameter}). Anything that is not a JSON object, or that\n * cannot be read as one (a cycle, a BigInt, a number out of range), gets the\n * marker whole.\n */\nfunction omitInJsonObject(\n value: unknown,\n keyPath: string,\n keys: ReadonlySet<string>,\n): [unknown, number] {\n try {\n let parsed: unknown;\n if (typeof value === 'string') parsed = parseJson(value);\n else if (typeof value === 'object' && value !== null) parsed = jsonCopy(value);\n if (!isJsonObject(parsed)) return [CONTENT_OMITTED_MARKER, 1];\n let n = 0;\n for (const k of Object.keys(parsed)) {\n const [entry, count] = omitInParameterEntry(parsed[k], `${keyPath}.${k}`, k, keys);\n parsed[k] = entry;\n n += count;\n }\n return [typeof value === 'string' ? JSON.stringify(parsed) : parsed, n];\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n}\n\n/**\n * V — one object entry at any depth inside a value of the value rule: a listed\n * key (or a dotted key with a listed part) and a key of the key rule get the\n * marker; every other value is walked.\n */\nfunction omitInParameterEntry(\n value: unknown,\n keyPath: string,\n key: string,\n keys: ReadonlySet<string>,\n): [unknown, number] {\n if (namesListedKey(key, keys) || isKeyRuleText(keyPath, key)) return [CONTENT_OMITTED_MARKER, 1];\n return omitInParameter(value, keyPath, keys);\n}\n\n/**\n * V — walk a PARSED value inside a value of the value rule (corpus v4). Objects\n * and arrays are walked in place (they are the gate's own copy). Text that starts\n * as JSON is parsed: when it parses, it is walked under the same path and, when a\n * value in it gets the marker, written back as compact JSON; when it does not\n * parse, or is too deep to walk, it gets the marker whole. Other text, numbers,\n * booleans and null stay. Returns the new value and the count.\n */\nfunction omitInParameter(value: unknown, path: string, keys: ReadonlySet<string>): [unknown, number] {\n let n = 0;\n if (Array.isArray(value)) {\n value.forEach((item, i) => {\n const [entry, count] = omitInParameter(item, `${path}.${i}`, keys);\n value[i] = entry;\n n += count;\n });\n } else if (isJsonObject(value)) {\n for (const k of Object.keys(value)) {\n const [entry, count] = omitInParameterEntry(value[k], `${path}.${k}`, k, keys);\n value[k] = entry;\n n += count;\n }\n } else if (typeof value === 'string' && startsAsJson(value)) {\n try {\n const [tree, count] = omitInParameter(parseJson(value), path, keys);\n return [count ? JSON.stringify(tree) : value, count];\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n }\n return [value, n];\n}\n\n/**\n * V — the value of a flat key `llm.invocation_parameters.<rest>` (the attribute\n * key, or the dotted path of a nested value): the marker when a part of `rest` is\n * listed or the key rule marks the key; else the value is walked as inside the\n * object. An object or an array is read through its JSON form; when it cannot be\n * read, the marker.\n */\nfunction omitFlat(\n value: unknown,\n keyPath: string,\n key: string,\n rest: string,\n keys: ReadonlySet<string>,\n): [unknown, number] {\n if (namesListedKey(rest, keys) || isKeyRuleText(keyPath, key)) return [CONTENT_OMITTED_MARKER, 1];\n try {\n if (typeof value === 'object' && value !== null) {\n const [tree, n] = omitInParameter(jsonCopy(value), keyPath, keys);\n return n ? [tree, n] : [value, 0];\n }\n return omitInParameter(value, keyPath, keys);\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n}\n\n/**\n * V — a nested value whose dotted path leads to the key of a value rule. `path`\n * is in `VALUE_RULE_PREFIXES` (`llm` for `llm.invocation_parameters`). The value\n * is read through its JSON form, and only the entries on a path to a value-rule\n * key, or with a dotted path below one (`{\"llm\": {\"invocation_parameters.system\":\n * ...}}`), are read: the key rule of the SDK reads flat keys only. JSON text of an\n * object or an array is read too. With no such entry below `path`, the value is\n * returned unchanged. A container that cannot be read gets the marker whole.\n */\nfunction omitBelow(value: unknown, path: string): [unknown, number] {\n // A String object is sent as its text (JSON.stringify), so it is read as text.\n const text = typeof value === 'string' ? value : value instanceof String ? value.valueOf() : undefined;\n if (text !== undefined) {\n // Text that starts as JSON and does not parse (too deep, a number out of\n // range, cut) gets the marker whole: the gateway does not read text at this\n // path, so the SDK is the only gate here. Other text that is not a JSON\n // object or array is not a value of this rule: it stays.\n let tree: unknown;\n try {\n tree = parseJson(text);\n } catch {\n return startsAsJson(text) ? [CONTENT_OMITTED_MARKER, 1] : [value, 0];\n }\n if (typeof tree !== 'object' || tree === null) return [value, 0];\n try {\n const [n, found] = omitBelowParsed(tree, path);\n return found ? [JSON.stringify(tree), n] : [value, 0];\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n }\n if (typeof value !== 'object' || value === null) return [value, 0];\n try {\n const tree = jsonCopy(value);\n const [n, found] = omitBelowParsed(tree, path);\n return found ? [tree, n] : [value, 0];\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n}\n\n/**\n * V — the walk of {@link omitBelow}, in place on the parsed copy. Returns the\n * count, and whether a value-rule key was found. An array item is never a match\n * itself (the gateway checks object entries only).\n */\nfunction omitBelowParsed(tree: unknown, path: string): [number, boolean] {\n let n = 0;\n let found = false;\n if (Array.isArray(tree)) {\n tree.forEach((item, i) => {\n const child = `${path}.${i}`;\n if (!VALUE_RULE_PREFIXES.has(child)) return;\n const [count, below] = omitBelowParsed(item, child);\n n += count;\n found ||= below;\n });\n } else if (isJsonObject(tree)) {\n for (const k of Object.keys(tree)) {\n const child = `${path}.${k}`;\n const keys = jsonObjectContentKeys(child, k);\n const flat = keys ? undefined : flatValueRule(child, k);\n if (keys) {\n const [entry, count] = omitInJsonObject(tree[k], child, keys);\n tree[k] = entry;\n n += count;\n found = true;\n } else if (flat) {\n const [entry, count] = omitFlat(tree[k], child, k, flat[0], flat[1]);\n tree[k] = entry;\n n += count;\n found = true;\n } else if (VALUE_RULE_PREFIXES.has(child)) {\n const [count, below] = omitBelowParsed(tree[k], child);\n n += count;\n found ||= below;\n }\n }\n }\n return [n, found];\n}\n\n/** V — whether the value of attribute `key` can hold a value-rule value. */\nfunction reachesValueRule(key: string): boolean {\n return (\n CONTENT_IN_JSON_OBJECT.has(key) ||\n VALUE_RULE_PREFIXES.has(key) ||\n flatValueRule(key, key) !== undefined\n );\n}\n\n/**\n * Replace every value in `attrs` whose key `rule` names, and apply the value rule\n * V, IN PLACE. Returns the number of values replaced.\n */\nfunction stripAttributes(\n attrs: Record<string, unknown>,\n rule: (key: string) => boolean = isContentKey,\n): number {\n let n = 0;\n for (const k of Object.keys(attrs)) {\n // The gateway's order: under the key rule, a value rule wins over the key\n // rule (`omit_in_entry`). A message event takes the event rule first\n // (`omit_in_event_attributes`).\n const keys = rule === isContentKey ? jsonObjectContentKeys(k, k) : undefined;\n const flat = rule === isContentKey && !keys ? flatValueRule(k, k) : undefined;\n let result: [unknown, number];\n if (keys) result = omitInJsonObject(attrs[k], k, keys);\n else if (flat) result = omitFlat(attrs[k], k, k, flat[0], flat[1]);\n else if (rule(k)) result = [CONTENT_OMITTED_MARKER, 1];\n else if (VALUE_RULE_PREFIXES.has(k)) result = omitBelow(attrs[k], k);\n else continue;\n attrs[k] = result[0];\n n += result[1];\n }\n return n;\n}\n\n/**\n * Strip the attributes of an event or a link without writing into the\n * caller's object. `addEvent(name, attrs)` keeps the caller's own object, so a\n * strip in place would change the caller's data. The strip works on a copy and\n * puts the copy on `holder`. When the copy cannot be set, it works in place. The\n * value rule V never changes a value in place; it puts a new value in the record.\n */\nfunction stripOwned(\n holder: { attributes?: Record<string, unknown> },\n rule: (key: string) => boolean = isContentKey,\n): number {\n const attrs = holder.attributes;\n if (\n !attrs ||\n typeof attrs !== 'object' ||\n !Object.keys(attrs).some((k) => rule(k) || reachesValueRule(k))\n ) {\n return 0;\n }\n const copy = { ...attrs };\n try {\n holder.attributes = copy;\n } catch {\n return stripAttributes(attrs, rule);\n }\n if (holder.attributes !== copy) return stripAttributes(attrs, rule);\n return stripAttributes(copy, rule);\n}\n\n/**\n * Remove customer prompt/completion content from `span`, in place.\n *\n * Walks the same surfaces as {@link applyMask} — span attributes, event\n * attributes, link attributes — because that is where content lives. The\n * attributes of a message event ({@link isContentEvent}) take the event rule,\n * {@link isContentEventAttribute}; all others take {@link isContentKey}. On every\n * surface, the value of a key of the value rule V (`llm.invocation_parameters`)\n * keeps its structure and loses only its content keys. No name is changed.\n *\n * `statusMessage` and exception text are deliberately NOT stripped: the\n * error-diagnosis product IS those fields, and this is a content-capture switch,\n * not a redaction feature. The `error_text` section of corpus v4 is the rule of\n * the gateway's PROJECT switch only (R41b).\n *\n * Returns the number of fields replaced. Never throws.\n */\nexport function stripContent(span: Span): number {\n let stripped = 0;\n\n if (span.attributes && typeof span.attributes === 'object') {\n stripped += stripAttributes(span.attributes);\n }\n\n if (Array.isArray(span.events)) {\n for (const event of span.events) {\n if (event?.attributes && typeof event.attributes === 'object') {\n const messageEvent = typeof event.name === 'string' && isContentEvent(event.name);\n stripped += stripOwned(event, messageEvent ? isContentEventAttribute : isContentKey);\n }\n }\n }\n\n if (Array.isArray(span.links)) {\n for (const link of span.links) {\n if (link?.attributes && typeof link.attributes === 'object') {\n stripped += stripOwned(link);\n }\n }\n }\n\n return stripped;\n}\n\n/** Strip content from every span in a batch, in place. Never throws. */\nexport function stripContentBatch(spans: Span[]): number {\n let total = 0;\n for (const span of spans) {\n try {\n total += stripContent(span);\n } catch {\n // A span we cannot walk must not take the batch down with it. It is also\n // the one span we could not gate, so say so at debug level.\n debug('Could not strip content from a span');\n }\n }\n return total;\n}\n\n/**\n * Mask a whole batch in place and report what it cost.\n *\n * Returns the field-level error count and the elapsed wall time so the caller\n * (the batch processor) owns the metric and the rate-limited warning — the\n * same split Python uses.\n */\nexport function applyMaskBatch(\n spans: Span[],\n mask: MaskFn,\n onError?: MaskErrorReporter,\n): { errors: number; elapsedMs: number } {\n let errors = 0;\n let firstKey: string | undefined;\n let firstError: unknown;\n\n const report: MaskErrorReporter = (key, error) => {\n errors++;\n if (firstKey === undefined) {\n firstKey = key;\n firstError = error;\n }\n onError?.(key, error);\n };\n\n const started = Date.now();\n for (const span of spans) {\n applyMask(span, mask, report);\n }\n const elapsedMs = Date.now() - started;\n\n if (errors > 0 && firstKey !== undefined) {\n // Attach the first failure to the returned shape via a side channel would\n // be noise; the processor logs from its own rate-limiter, so surface the\n // detail here at debug level for the case where the window suppressed it.\n let detail: string;\n try {\n detail = String(firstError);\n } catch {\n detail = typeof firstError; // a hostile `toString` must not break the export\n }\n debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${detail}`);\n }\n\n return { errors, elapsedMs };\n}\n\n/** Emit the rate-limited \"your mask is throwing\" warning. Exported for reuse. */\nexport function warnMaskErrors(batchErrors: number, totalErrors: number): void {\n warn(\n `the mask callback threw on ${batchErrors} field(s) in this batch ` +\n `(${totalErrors} since start). Those fields were replaced with ` +\n `\"${MASK_ERROR_MARKER}\" and the spans were exported intact — no span was ` +\n `dropped. Fix the callback; until then those fields carry no data.`,\n );\n}\n\n/** Emit the rate-limited \"your mask is slow\" warning. Exported for reuse. */\nexport function warnMaskSlow(spanCount: number, elapsedMs: number): void {\n warn(\n `masking ${spanCount} span(s) took ${elapsedMs} ms ` +\n `(budget ${MASK_BUDGET_MS_PER_SPAN * spanCount} ms, ` +\n `${MASK_BUDGET_MS_PER_SPAN} ms/span). Node is single-threaded: this time is ` +\n `taken from your event loop, so it delays your application as well as the ` +\n `export drain, and a queue that cannot drain drops spans (reason=queue_full). ` +\n `Keep the callback CPU-only: no I/O, no network, no unbounded retries.`,\n );\n}\n","/**\n * Batch span processor.\n *\n * Collects spans and exports them in batches based on:\n * - Batch size threshold (default: 500 spans — SDK-RELEASE-RULING.md §4.3 raised\n * this from 100; see `DEFAULT_BATCH_SIZE` below, which is the one true source)\n * - Time interval (default: 1000ms)\n * - Attribute product (`MAX_ATTRIBUTE_PAIRS_PER_BATCH`) and estimated serialized\n * size (`MAX_BATCH_BYTES`), both mirroring gateway constants\n *\n * Node.js is single-threaded — no locks needed.\n * Timer is unref()'d so it doesn't prevent process exit.\n */\n\nimport type { Span } from '../span.js';\nimport { ExportResult, type AckCounts, type SpanExporter } from './base.js';\nimport { debug, warn } from '../utils/log.js';\nimport { scrubText } from '../utils/scrub.js';\nimport {\n applyMaskBatch,\n stripContentBatch,\n warnMaskErrors,\n warnMaskSlow,\n MASK_BUDGET_MS_PER_SPAN,\n MASK_WARN_WINDOW_MS,\n type MaskFn,\n} from '../masking.js';\n\nexport interface BatchProcessorOptions {\n exporters: SpanExporter[];\n batchSize?: number;\n batchTimeoutMs?: number;\n maxQueueSize?: number;\n debug?: boolean;\n /**\n * Customer masking callback, `mask(key, value) => value`. Applied to every\n * content-bearing field of every span in this processor, once, BEFORE any\n * exporter sees the batch. See `../masking.ts`.\n */\n mask?: MaskFn;\n /**\n * Whether customer prompt/completion content may leave the process.\n * **Defaults to `false`** here, which is NOT the user default: `resolveConfig`\n * defaults to `true`, and `init()` always passes the resolved value. This\n * `false` applies only to a processor that is built by hand without it\n * (fail-closed). When false, every content-keyed attribute is replaced on the\n * export path before any exporter runs. See `../masking.ts` `stripContent`.\n */\n traceContent?: boolean;\n}\n\n/**\n * F-SDKCB-001 §5 (option J) — reason labels for a discarded span.\n *\n * One integer conflating an under-provisioned queue, a dead gateway and a\n * redeploy is the ambiguity W1/W3 was written against: the three causes demand\n * three different operator responses. The server side already landed on this\n * shape as `dropped{stage,reason,project_id}` (F-HONEST-001). Mirrors the\n * Python `DROP_*` constants in `exporters/batch.py`.\n *\n * `unacknowledged`: the backend's ack accounts for fewer spans than the batch\n * sent (after the counts are clamped to the batch size). Those spans are in no\n * other counter, so they are counted here: exported + rejected + dropped then\n * equals the spans that ended.\n *\n * `quota_exceeded` (S-1): the monthly event quota is used up. The backend discarded a batch, or\n * the queue overflowed while the exporter was paused for the quota. While it is paused the\n * processor keeps ended spans in the queue and sends them when the pause ends. See `quota.ts`.\n */\nexport type DropReason =\n | 'queue_full'\n | 'transport_refused'\n | 'shutdown_residue'\n | 'unacknowledged'\n | 'quota_exceeded';\n\n/** Outcome of one `_exportBatch()` round.\n *\n * `shutdown()`'s drain loop must tell \"the queue is empty\" from \"a batch was\n * taken and nobody accepted it\" — RULING §4's no-SUCCESS exit. Without that\n * distinction the loop would spin for the whole budget against a dead\n * transport, and (because the bounded re-queue keeps the queue non-empty)\n * would never terminate at all. */\nconst enum Round {\n Empty = 0,\n Delivered = 1,\n Failed = 2,\n /** an export was already in flight (`_flushing`); this call made no progress */\n Busy = 3,\n /**\n * Every exporter that delivers is paused for the monthly quota (S-1): nothing was taken from\n * the queue. The spans wait in the queue (bounded as always) and go out when the pause ends.\n */\n Paused = 4,\n}\n\n/** The value `raceDeadline` gives when the deadline comes first. */\nconst DEADLINE = Symbol('deadline');\n\n/**\n * Wait for `p`, but not longer than `ms`. The timer is cleared on both paths, so\n * it never keeps the process alive. `p` is not cancelled: it continues, and the\n * caller decides what its late answer means.\n */\nasync function raceDeadline<T>(p: Promise<T>, ms: number): Promise<T | typeof DEADLINE> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<typeof DEADLINE>((resolve) => {\n timer = setTimeout(() => resolve(DEADLINE), Math.max(0, ms));\n });\n try {\n return await Promise.race([p, deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Describe a thrown value for a debug line. Never throws (a Symbol, a hostile `toString`). */\nfunction describeThrown(e: unknown): string {\n // An error text can hold a key: scrubbed (`utils/scrub.ts`; the processor does not\n // know the exporter's key, so RISICARE_API_KEY and the forms of it are removed).\n return scrubText(e, []);\n}\n\n/**\n * Wait for an exporter's own `shutdown()`, but not longer than `ms`. A rejection\n * or a synchronous throw is logged at debug level. The timer is cleared.\n */\nasync function shutdownExporter(exporter: SpanExporter, ms: number): Promise<void> {\n try {\n const outcome = await raceDeadline(Promise.resolve().then(() => exporter.shutdown()), ms);\n if (outcome === DEADLINE) debug(`${exporter.name}.shutdown() did not finish within ${ms} ms`);\n } catch (e) {\n debug(`Error shutting down ${exporter.name}: ${describeThrown(e)}`);\n }\n}\n\n/** The batch that an export round has taken off the queue and not yet settled. */\ninterface InFlight {\n /** The batch: the key that the exporter's `abort(spans)` uses. */\n spans: Span[];\n size: number;\n /** Set by `shutdown()` when it stops waiting. A late answer then changes nothing. */\n abandoned: boolean;\n}\n\n/**\n * RULING §4 delegates this number with a derive-and-justify obligation.\n * `shutdown()` runs `exporter.shutdown()` AFTER the drain, so a drain that\n * spends the whole budget starves it.\n *\n * The built-in `HttpExporter.shutdown()` is a literal no-op — native fetch\n * needs no cleanup (`exporters/http.ts:159-161`) — so for the shipped exporter\n * the measured cost is ZERO. The reserve is therefore a policy allowance for a\n * CUSTOMER-supplied exporter, whose `shutdown(): Promise<void> | void`\n * (`exporters/base.ts:16`) we cannot measure. Held at 100 ms to match the\n * Python constant — the two SDKs must end with the same contract, and Python's\n * value is measured (see `_SHUTDOWN_RESERVE_MS` in `exporters/batch.py` and\n * `fix-workstream/perf/sdk_exporter_shutdown_cost_probe.py`). Against the\n * binding 2,000 ms SIGTERM budget this leaves 1,900 ms of drain.\n */\nconst SHUTDOWN_RESERVE_MS = 100;\n\n/**\n * SDK-RELEASE-RULING.md §4.3 — ONE shutdown budget, on every teardown path.\n *\n * 5,000 ms is bounded from ABOVE by something outside our control: the SDK's\n * shutdown runs inside the application's, which runs inside the container's\n * termination grace period. The tightest common default is `docker stop` at\n * 10 s (k8s `terminationGracePeriodSeconds` 30 s; systemd `TimeoutStopSec`\n * 90 s), and taking more than half of the tightest is hostile to the app's own\n * cleanup.\n *\n * ⚠ WHY A LONGER BUDGET IS NEARLY FREE: the drain exits on the FIRST round that\n * does not deliver (`Round.Delivered` check below). A dead transport costs one\n * round, not the budget. It is spent only while the transport is SUCCEEDING.\n *\n * ⚠ `client.ts` DERIVES its signal-handler backstop from this rather than\n * repeating a literal. Before the ruling both were an independent `5000`, so\n * the backstop's `process.exit(1)` raced the drain it exists to protect —\n * killing it at the deadline, with the wrong exit code, before the residue\n * warning could print. Do not re-introduce a second literal.\n *\n * Mirrors `SHUTDOWN_BUDGET_MS` in `client.py`.\n */\nexport const SHUTDOWN_BUDGET_MS = 5000;\n\n/** The largest delay that `setTimeout` accepts (2**31 - 1 ms). A larger one fires at once. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\n/**\n * The budget that `flush(timeoutMs)` and `shutdown(timeoutMs)` use.\n *\n * A value that is not a finite number (`undefined`, `NaN`, `Infinity`, a string,\n * `null`) gives the default, `SHUTDOWN_BUDGET_MS`. A negative value gives 0. A\n * value above 2**31 - 1 gives 2**31 - 1. Through 0.7.1 such values reached\n * `setTimeout` and string concatenation as they were: `flush(Infinity)` and\n * `flush('3000')` returned `false` at once, and `shutdown(NaN)` dropped every\n * span, on a healthy server.\n */\nexport function normalizeTimeoutMs(value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return SHUTDOWN_BUDGET_MS;\n if (value < 0) return 0;\n return Math.min(value, MAX_TIMEOUT_MS);\n}\n\n/**\n * The `transport_refused` warning is rate-limited to the exporter's existing\n * window (`exporters/http.ts`), so a flaky network cannot spam customer logs.\n * The `shutdown_residue` warning is NOT rate-limited (RULING §5): it fires at\n * most once per process lifetime by construction, so a window buys nothing and\n * would suppress the only signal in any process that had already warned about\n * the breaker — exactly the correlated case where the customer most needs it.\n */\nconst REFUSAL_WARN_WINDOW_MS = 300_000;\n\n/**\n * SDK-RELEASE-RULING.md §4.3 — the default batch size, raised 100 -> 500.\n *\n * DERIVED, not picked. `shutdown()`'s drain is strictly serial — one export per\n * round-trip — so the most it can save is\n * ceiling = floor((budget - reserve) / RTT) x batchSize\n * and the requirement is that it drain the SDK's OWN maximum queue\n * (`maxQueueSize` = 10,000, the most it can ever be holding) at the design\n * target RTT = 100 ms:\n * batchSize >= 10,000 x RTT / (5,000 - 100) -> 204 at 100 ms, 510 at 250 ms\n * 500 satisfies it to the 250 ms trans-Pacific tail and sits 1.55x under the\n * ceiling the gateway's attribute-product cap imposes (below).\n *\n * ⚠ NEITHER THIS NOR THE BUDGET IS SUFFICIENT ALONE — measured, ruling §2. At\n * 100 ms RTT: budget alone leaves 51 % lost, batch alone leaves 60 % lost at the\n * tail, both together lose nothing. Do not \"simplify\" one back.\n *\n * Mirrors `DEFAULT_BATCH_SIZE` in `exporters/batch.py` — the two SDKs must end\n * with the same contract.\n */\nexport const DEFAULT_BATCH_SIZE = 500;\n\n/**\n * The gateway refuses a request whose summed attribute count exceeds this\n * (`MAX_ATTRIBUTE_PAIRS_PER_REQUEST`, `handlers/ingest.rs`, F-ACKRSV-001) —\n * WHOLE request, never truncated, and the exporter treats that 4xx as a\n * failure, retries it futilely and finally discards the batch as\n * `transport_refused`. The cap is `sum(span.attributes.length)`, i.e. LINEAR in\n * batch size: at batch B a customer is refused above `24,000 / B` attributes\n * per span — 240 at B=100, but only 48 at B=500.\n *\n * Without this bound, raising the default would silently break every customer\n * between those two densities: accepted today, whole-request-refused tomorrow,\n * with no action on their part. So the batch is bounded on BOTH axes, and the\n * raise becomes strictly no-worse-than-today on the attribute axis.\n *\n * ⚠ COUPLING, DECLARED (ruling §4.5) — AND THE DIRECTIONS ARE NOT SYMMETRIC.\n * ⚠ CORRECTED 2026-07-27 (F-SDKBYTES-001 §4.1). This comment used to read\n * \"Stale in either direction is SAFE — too low means slightly smaller batches,\n * too high means the gateway refuses exactly as it does today.\" The second half\n * is FALSE, and the error mattered because it licenses a unilateral change on\n * the gateway side that this SDK cannot survive:\n *\n * • STALE LOW (SDK constant < gateway cap) — SAFE, unconditionally. The SDK\n * assembles smaller batches than it needed to; every one is accepted.\n * • STALE HIGH (SDK constant > gateway cap) — safe ONLY while the gateway's\n * cap does not DECREASE. If it is lowered, this SDK assembles batches the\n * gateway now refuses: requests that are accepted TODAY begin returning\n * 4xx, the exporter retries each one futilely and discards the whole batch\n * as `transport_refused`. That is a NEW refusal caused by the mismatch —\n * not \"exactly as it does today\".\n *\n * ⇒ RAISING the gateway cap is safe to do unilaterally. LOWERING it is not: the\n * SDK constant must move first and be adopted, and `F-SDKVER-001` records\n * that nothing pins or even observes an SDK version server-side, so \"adopted\"\n * is weeks-to-never rather than a deploy.\n *\n * The gateway remains the enforcer; this only stops OUR DEFAULT from moving a\n * customer across ITS boundary.\n */\nexport const MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24_000;\n\n/**\n * The per-batch SERIALIZED-BYTE bound (F-SDKBYTES-001) — the third axis.\n *\n * `SDK-RELEASE-RULING.md` §4.5 bounded the batch on span COUNT and attribute\n * PRODUCT and explicitly left BYTES open: \"a customer putting a 1 MB string in\n * an attribute can exceed the body limit at *any* batch size, and B=500 makes\n * it 5x more reachable. I did not guard this.\"\n *\n * MEASURED (`perf/sdk_batch_byte_ceiling_probe.py`, raw\n * `perf/sdk-batch-byte-ceiling.json`; its JS cross-check arm compiles\n * `src/span.ts` itself rather than trusting `dist/`):\n *\n * batch=500 crosses max_body_size (10,485,760 B) at 20,971 B/span\n * batch=100 crosses it at 104,857 B/span\n *\n * and the ruling's \"16x headroom\" quoted only the measured FLOOR. Against the\n * measured MAXIMUM realistic span (13,487 B) a 500-span batch is 6,743,500 B —\n * 1.55x headroom, not 16x. The count raise spent most of the byte margin.\n *\n * WITHOUT IT, MEASURED (probe ARM 2): the gateway answers 413, and the exporter\n * does NOT treat 413 as permanent — `http.ts` maps every non-2xx that is not\n * 408/504 to FAILURE and retries it. On a permanently-413 batch: 12 HTTP\n * requests (4 re-queue rounds x 3 exporter attempts), then the ENTIRE batch\n * discarded as `transport_refused`. Counted and warned — but total loss.\n *\n * THE ESTIMATE, AND WHICH WAY IT ERRS. Serialized size is not knowable without\n * serializing, and serializing to measure would double the export cost. So the\n * batch is bounded on an ESTIMATE:\n *\n * string -> 2 + utf8ByteLength(s), the bytes `fetch` will send for\n * the raw characters\n * number/bool/null -> a fixed allowance; containers recurse to depth 4\n * anything else -> a fixed allowance (see `EST_OPAQUE_VALUE_BYTES`)\n *\n * ⚠ ASYMMETRY WITH PYTHON, DELIBERATE. Each SDK estimates against ITS OWN\n * encoder. `JSON.stringify` emits non-ASCII RAW (UTF-8 on the wire);\n * `json.dumps` escapes it to `\\uXXXX`. Measured: a 9,525-char CJK attribute is\n * 28,859 B from JS and ~2x that from Python. Mirroring Python's per-character\n * multiplier here would over-estimate every non-ASCII JS batch by ~4x.\n *\n * ⚠ THE ONE UNDER-ESTIMATE, NAMED: JSON escaping. A `\"` costs 2 bytes and a\n * control character 6; `utf8ByteLength` charges 1 for each. The 20 % margin\n * below is what absorbs it — a batch may be up to ~25 % escape characters BY\n * COUNT before the estimate stops covering the real body. Past that the gateway\n * refuses, exactly as it does today: no new failure mode, the bound is simply\n * not helping. Stated rather than engineered away because counting escapes is a\n * second O(bytes) scan.\n *\n * THE FRACTION: 8 MiB is 80 % of the gateway's 10 MiB default. Below it the\n * measured realistic corpus does not bind at batch 500 (1.24x under this\n * budget); above it, the 20 % is the escape margin.\n *\n * ⚠ COUPLING, DECLARED, with the SAME asymmetry as the attribute cap above:\n * stale LOW is unconditionally safe; stale HIGH is safe only while\n * `max_body_size` does not DECREASE.\n */\nexport const MAX_BATCH_BYTES = 8 * 1024 * 1024; // 8,388,608 B = 80 % of max_body_size\n\nconst SPAN_ENVELOPE_BYTES = 512; // typed camelCase fields; a minimal span is ~250 B\nconst CHILD_ENVELOPE_BYTES = 128; // per event / link, before its strings\nconst SCALAR_BYTES = 24; // widest JSON number repr\nconst LITERAL_BYTES = 5; // \"false\" / \"null\"\nconst EST_MAX_DEPTH = 4;\n/**\n * Charge for a value the ladder cannot walk (a class instance, a Map, anything\n * past `EST_MAX_DEPTH`). ⚠ Unlike Python — whose `_coerce_attribute_value`\n * truncates its `str()` fallback at 4,096 chars, making the same charge there a\n * genuine BOUND — JS has no truncation at all (`F-SDKATTRLEN-001`), so this is\n * an ALLOWANCE and a deeply-nested object can exceed it. The gateway refuses\n * that shape exactly as it does today.\n */\nconst EST_OPAQUE_VALUE_BYTES = 4_096;\n\n/**\n * UTF-8 byte length, without allocating the encoded copy.\n *\n * `Buffer.byteLength` is a single native scan and is what `fetch` will actually\n * put on the wire for the raw characters. The fallback multiplier 3 is a true\n * upper bound on UTF-8 bytes per UTF-16 code unit (a BMP code point is 1 unit\n * and at most 3 bytes; an astral one is 2 units and 4 bytes, i.e. 2 per unit),\n * so a Buffer-less runtime errs HIGH rather than low.\n */\nconst utf8ByteLength: (s: string) => number =\n typeof Buffer !== 'undefined' && typeof Buffer.byteLength === 'function'\n ? (s) => Buffer.byteLength(s, 'utf8')\n : (s) => s.length * 3;\n\nfunction estStringBytes(s: string): number {\n return 2 + utf8ByteLength(s);\n}\n\nfunction estValueBytes(v: unknown, depth = 0): number {\n if (typeof v === 'string') return estStringBytes(v);\n if (v === null || v === undefined || typeof v === 'boolean') return LITERAL_BYTES;\n if (typeof v === 'number' || typeof v === 'bigint') return SCALAR_BYTES;\n if (Array.isArray(v) && depth < EST_MAX_DEPTH) {\n let total = 2 + Math.max(0, v.length - 1);\n for (const item of v) total += estValueBytes(item, depth + 1);\n return total;\n }\n if (\n typeof v === 'object' &&\n depth < EST_MAX_DEPTH &&\n Object.getPrototypeOf(v as object) === Object.prototype\n ) {\n let total = 2;\n for (const [k, val] of Object.entries(v as Record<string, unknown>)) {\n total += estStringBytes(k) + 2 + estValueBytes(val, depth + 1);\n }\n return total;\n }\n return EST_OPAQUE_VALUE_BYTES;\n}\n\nfunction estMappingBytes(m: Record<string, unknown>): number {\n let total = 0;\n for (const [k, v] of Object.entries(m)) total += estStringBytes(k) + 2 + estValueBytes(v);\n return total;\n}\n\n/**\n * Estimated serialized bytes this span contributes to a request body, or the\n * fixed envelope if the object is not span-shaped.\n *\n * ⚠ Defensive in exactly the shape `spanAttrCount` is, and for the same reason:\n * TypeScript types `_queue` as `Span[]`, but nothing stops a JS caller or a test\n * double from queueing something else. Throwing from inside the export path\n * would break export for the whole batch. On any surprise this returns the\n * envelope, which can only make the bound LESS binding — never more, and never\n * a wedge.\n */\nfunction spanBytesEstimate(span: Span): number {\n try {\n const s = span as unknown as Record<string, unknown>;\n let total = SPAN_ENVELOPE_BYTES;\n for (const field of ['name', 'statusMessage'] as const) {\n if (typeof s[field] === 'string') total += estStringBytes(s[field] as string);\n }\n const attrs = s.attributes;\n if (attrs != null && typeof attrs === 'object' && !Array.isArray(attrs)) {\n total += estMappingBytes(attrs as Record<string, unknown>);\n }\n for (const key of ['events', 'links'] as const) {\n const coll = s[key];\n if (!Array.isArray(coll)) continue;\n for (const child of coll) {\n total += CHILD_ENVELOPE_BYTES;\n const ca = (child as Record<string, unknown> | null)?.attributes;\n if (ca != null && typeof ca === 'object' && !Array.isArray(ca)) {\n total += estMappingBytes(ca as Record<string, unknown>);\n }\n }\n }\n return total;\n } catch {\n return SPAN_ENVELOPE_BYTES;\n }\n}\n\n/**\n * Attribute count for the per-batch product bound, or 0 if unknowable.\n *\n * ⚠ Defensive for the same reason the Python `_span_attr_count` is: TypeScript\n * types `_queue` as `Span[]`, but nothing stops a JS caller (or a test double)\n * from queueing an object without `attributes`. Reading `.length` off\n * `undefined` would throw from inside the export path and break export for the\n * whole batch. An object with no countable attributes contributes 0, which can\n * only make the bound less binding, never more.\n */\nfunction spanAttrCount(span: Span): number {\n const attrs = (span as { attributes?: unknown }).attributes;\n if (attrs == null) return 0;\n if (attrs instanceof Map) return attrs.size;\n if (typeof attrs === 'object') return Object.keys(attrs as object).length;\n return 0;\n}\n\nexport class BatchSpanProcessor {\n private readonly _exporters: SpanExporter[];\n private readonly _batchSize: number;\n private readonly _batchTimeoutMs: number;\n private readonly _maxQueueSize: number;\n // ⚠ NO `_debug` FIELD. It existed, was assigned, and was read by NOTHING —\n // `tsc --noEmit` had been RED on this package at HEAD for it (TS6133), which\n // survived because `ci-local.sh` runs this package's vitest and never its\n // typecheck, and `prepublishOnly` runs `build && test` — also no typecheck.\n // Filed F-SDKJSTYPECHECK-001. Debug output here is gated globally by\n // `setDebug()` in `../utils/log.ts`, so a per-processor flag was always\n // redundant; Python's `self._debug` exists because `logging` has no such\n // global switch.\n\n private _queue: Span[] = [];\n private _timer: ReturnType<typeof setInterval> | null = null;\n private _started = false;\n private _flushing = false;\n private _inFlight: InFlight | null = null;\n /**\n * The `shutdown()` that runs, or ran. A second `shutdown()` returns it, and a\n * `flush()` that comes while it runs waits for it (inside its own deadline).\n */\n private _closing: Promise<void> | null = null;\n /**\n * True from the start of the drain of `shutdown()` until its loop ends and the\n * residue is counted (no `await` between those two points). A span that ends\n * in this time joins the drain. After it, the processor can take no span.\n */\n private _drainOpen = false;\n private _lateSpanWarned = false;\n private _beforeExitHandler: (() => void) | null = null;\n\n // Retry tracking for failed batches (Audit #5)\n private _retryCounts = new Map<string, number>();\n /**\n * The HTTP requests that the failed rounds of each re-queued span sent, by span id (issue\n * #57). It has the same life as `_retryCounts`: `_forgetRetry` ends both. NaN = a round for\n * which the exporter did not say. Empty for an exporter that does not state it.\n */\n private _retryRequests = new Map<string, number>();\n private static readonly MAX_RETRIES = 3;\n\n private _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;\n private _lastUnackWarnAt = Number.NEGATIVE_INFINITY;\n /**\n * The loss total (dropped + rejected) that the last finished `flush()` saw.\n * A flush reports a loss that is new since then, one time.\n */\n private _lossMark = 0;\n\n // ── Masking (see `../masking.ts`) ──────────────────────────────────────────\n private readonly _mask: MaskFn | undefined;\n // ── Content capture gate (see `../masking.ts`) ─────────────────────────────\n // Fail-closed: an unspecified value means \"do not capture\". This is the ONE\n // place the gate runs for BOTH content paths — provider capture AND hand-set\n // attributes — so it must not be conditional on anything a caller might\n // forget to pass. Python twin: `BatchSpanProcessor._trace_content`.\n private readonly _traceContent: boolean;\n private _lastMaskWarnAt = Number.NEGATIVE_INFINITY;\n private _lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;\n\n // Metrics\n /** DEPRECATED flat total. Retained as the exact SUM of\n * `droppedSpansByReason` so existing readers keep working (RULING §5\n * back-compat — the same deprecate-and-alias shape this codebase used for\n * `complete`->`settled` and `spans_flushed_total`). Prefer the labelled\n * record: one integer cannot tell an under-provisioned queue from a dead\n * gateway from a redeploy. */\n droppedSpans = 0;\n droppedSpansByReason: Record<DropReason, number> = {\n queue_full: 0,\n transport_refused: 0,\n shutdown_residue: 0,\n unacknowledged: 0,\n quota_exceeded: 0,\n };\n exportedSpans = 0;\n /**\n * Spans that the backend acknowledged as REJECTED (the ack's `rejected`). They\n * are not stored and are not retried. An exporter without an ack adds nothing.\n */\n rejectedSpans = 0;\n /** Export ATTEMPTS, not a span count. */\n failedExports = 0;\n /**\n * Fields whose mask callback threw and were replaced with\n * `MASK_ERROR_MARKER`. A FIELD count, not a span count — one span can\n * contribute several. Non-zero means those fields carry a marker instead of\n * data: a customer-code bug, not a transport one.\n */\n maskErrors = 0;\n\n constructor(options: BatchProcessorOptions) {\n this._exporters = [...options.exporters];\n\n // batchSize: clamp to [1, 10000] AND warn on out-of-range — silent\n // clamping is a debugging tar pit (CON-257 / P1-3). Mirrors Python.\n const requestedBatchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;\n const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 10_000));\n if (clampedBatchSize !== requestedBatchSize) {\n warn(\n `batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`,\n );\n }\n this._batchSize = clampedBatchSize;\n\n this._batchTimeoutMs = options.batchTimeoutMs ?? 1000;\n this._maxQueueSize = options.maxQueueSize ?? 10000;\n this._mask = options.mask;\n // Fail-closed, NOT the user default (that is `true`, in `resolveConfig`).\n // `Client` always passes the resolved value; this `false` is for a processor built by hand.\n this._traceContent = options.traceContent ?? false;\n }\n\n start(): void {\n if (this._started) return;\n this._started = true;\n\n // Periodic flush timer — unref so it doesn't keep process alive\n this._timer = setInterval(() => {\n void this._exportBatch();\n }, this._batchTimeoutMs);\n this._timer.unref();\n\n // Flush on process exit (Audit #3: use .once, not .on; await, not void)\n this._beforeExitHandler = () => {\n void this.shutdown();\n };\n process.once('beforeExit', this._beforeExitHandler);\n }\n\n /** Record `count` discarded spans under `reason`.\n *\n * `droppedSpans` is maintained as the exact sum of the labelled counters\n * (RULING §5 back-compat), so the locked pins — which read the flat\n * integer — stay meaningful. */\n private _recordDropped(reason: DropReason, count = 1): void {\n this.droppedSpans += count;\n this.droppedSpansByReason[reason] += count;\n }\n\n /**\n * Run the customer mask over a batch, in place. Never throws.\n *\n * Failure semantics are ruled in `../masking.ts`: a field whose mask throws\n * becomes `MASK_ERROR_MARKER` and the span is kept. The counter is per FIELD;\n * both warnings are rate-limited to one per window so a mask that throws on\n * every span cannot flood the customer's logs — the same shape as the\n * transport-refusal warning above.\n */\n private _applyMask(batch: Span[]): void {\n const mask = this._mask;\n if (mask === undefined) return;\n\n const { errors, elapsedMs } = applyMaskBatch(batch, mask);\n const now = Date.now();\n\n if (errors > 0) {\n this.maskErrors += errors;\n if (now - this._lastMaskWarnAt > MASK_WARN_WINDOW_MS) {\n this._lastMaskWarnAt = now;\n warnMaskErrors(errors, this.maskErrors);\n }\n }\n\n if (\n elapsedMs > MASK_BUDGET_MS_PER_SPAN * batch.length &&\n now - this._lastSlowMaskWarnAt > MASK_WARN_WINDOW_MS\n ) {\n this._lastSlowMaskWarnAt = now;\n warnMaskSlow(batch.length, elapsedMs);\n }\n }\n\n /**\n * Drain what we hold, or name what we could not (F-SDKDRAIN-001).\n *\n * Per RULING §4 (option E, hard-bounded) the drain loops until ONE of: the\n * queue is empty; the deadline expires; or a full round completes with no\n * exporter returning SUCCESS.\n *\n * ⚠ The `_flushing` handling is load-bearing, and `SDKDRAIN_JS_004` exists\n * to catch its absence. `_exportBatch()` returns immediately when an export\n * is already in flight (`:171`), so a loop that merely calls it again makes\n * NO progress and abandons the queue exactly as before — measured at 900 of\n * 1,000. We await a tick instead, the shape `flush()` already models.\n *\n * The deadline is a hard wall-clock bound. Each round is raced against the\n * budget that remains. At the deadline, `shutdown()` stops the round in flight\n * through the exporter's optional `abort()`. That stopped round changes no\n * counter, does not move the circuit breaker and re-queues nothing. Through\n * 0.7.1 the deadline was checked only between rounds, so one round against a\n * silent server (3 attempts x 5 s) held a 5,000 ms shutdown for 15 s.\n *\n * Anything still queued when the loop stops, AND a batch whose export was\n * stopped, is COUNTED as `shutdown_residue` and announced with ONE WARNING\n * that gives both numbers. The server may have received the spans of the\n * stopped export. The warning is the primary signal, not the counter: a\n * counter incremented inside `shutdown()` is written to memory about to be\n * freed and has no reader (RULING §2 / §8.2).\n *\n * Each exporter's own `shutdown()` gets the time that is left of the budget.\n * An exporter that does not finish in that time is not awaited.\n *\n * Limit: the abort does not stop a TLS handshake that stalls. Measured, such a\n * handshake kept the process alive about 10 s after `shutdown()` returned.\n *\n * A second call, while the first runs or after it ended, returns the promise\n * of the first one. It does not return before the first drain ends.\n *\n * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for\n * the values that are not a finite number.\n */\n shutdown(timeoutMs: number = SHUTDOWN_BUDGET_MS): Promise<void> {\n if (!this._started) return this._closing ?? Promise.resolve();\n this._closing = this._shutdown(timeoutMs);\n return this._closing;\n }\n\n private async _shutdown(timeoutMs: number): Promise<void> {\n timeoutMs = normalizeTimeoutMs(timeoutMs);\n this._started = false;\n this._drainOpen = true;\n\n if (this._timer) {\n clearInterval(this._timer);\n this._timer = null;\n }\n\n // Remove process listener to prevent leak (Audit #3)\n if (this._beforeExitHandler) {\n process.removeListener('beforeExit', this._beforeExitHandler);\n this._beforeExitHandler = null;\n }\n\n // Halve rather than underflow on a tiny budget: shutdown(200) still gets\n // 100 ms of drain instead of none.\n const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);\n const shutdownDeadline = Date.now() + timeoutMs;\n const drainDeadline = shutdownDeadline - reserveMs;\n\n while (this._queue.length > 0 || this._flushing) {\n const remaining = drainDeadline - Date.now();\n if (remaining <= 0) break;\n // A hard wall-clock bound: the round is raced against the budget. At the\n // deadline the round in flight is stopped below.\n const outcome = await raceDeadline(this._exportBatch(), remaining);\n if (outcome === DEADLINE) break;\n if (outcome === Round.Busy) {\n // An export is mid-await. Yield rather than spin on a no-op call.\n await new Promise((r) => setTimeout(r, 1));\n continue;\n }\n if (outcome !== Round.Delivered) {\n // Paused -> the monthly quota pause is on; the spans cannot go out now, and shutdown()\n // counts what is left as `shutdown_residue`.\n // Empty -> nothing left, we are done.\n // Failed -> no exporter accepted this round; a further round cannot\n // help and would spin to the deadline on precisely the path\n // where there is nothing to save.\n break;\n }\n }\n\n // The drain takes no more spans from here on. This line and the residue\n // below have no `await` between them: a span that ends before them is in\n // `queued`, and one that ends after them is counted by `onSpanEnd`.\n this._drainOpen = false;\n\n // Once shutdown() has returned, holding IS abandoning: the timer is\n // cleared, the exit listener is gone, nothing will ever export these.\n //\n // A batch whose export did not finish inside the budget is abandoned too. It\n // is counted HERE, and its late answer changes no counter and re-queues\n // nothing (see `_exportBatch`).\n const queued = this._queue.length;\n const flight = this._inFlight;\n const inFlight = flight !== null && !flight.abandoned ? flight.size : 0;\n if (flight !== null && !flight.abandoned) {\n flight.abandoned = true;\n // Stop the abandoned export, so that its request, retries and backoff do\n // not keep the process alive. Without this, it ran on for up to 3\n // attempts of 5 s after shutdown() returned. An exporter without\n // `abort()` is left alone.\n for (const exporter of this._exporters) {\n try {\n exporter.abort?.(flight.spans);\n } catch (e) {\n debug(`Error aborting ${exporter.name}: ${describeThrown(e)}`);\n }\n }\n }\n const residue = queued + inFlight;\n if (residue > 0) {\n this._queue.length = 0;\n this._recordDropped('shutdown_residue', residue);\n // NOT rate-limited, by ruling. Names the counts AND the reason.\n if (this._quotaPaused()) {\n // S-1: the cause is the monthly quota pause, not the shutdown budget.\n warn(\n `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ` +\n `${queued} still queued and ${inFlight} in an export that shutdown() stopped. ` +\n `The monthly event quota is used up and export is paused until the next probe, so ` +\n `these spans could not be sent. A longer shutdown timeout does not help. Upgrade ` +\n `the plan or wait for the quota to reset.`,\n );\n } else {\n warn(\n `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ` +\n `${queued} still queued and ${inFlight} in an export that shutdown() stopped. ` +\n (inFlight > 0\n ? `The server may have received the ${inFlight} span(s) of the stopped export. `\n : '') +\n `All ${residue} were not confirmed as delivered, and are counted as dropped. ` +\n `The ${timeoutMs} ms shutdown ` +\n `budget expired or the transport stopped accepting. Pass a larger timeout to ` +\n `shutdown(timeoutMs), or raise your container's termination grace period, to lose less.`,\n );\n }\n }\n\n // Shutdown exporters, inside the time that is left. An exporter whose own\n // shutdown() is slow or never settles must not hold the process: through\n // 0.7.1 a 4 s exporter shutdown held shutdown(1000) for 4 s.\n for (const exporter of this._exporters) {\n await shutdownExporter(exporter, Math.max(0, shutdownDeadline - Date.now()));\n }\n\n // Clean up retry tracking — retry-map drain site 3 of 3\n this._retryCounts.clear();\n this._retryRequests.clear();\n\n debug(\n `BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, ` +\n `Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`\n );\n }\n\n onSpanEnd(span: Span): void {\n if (!this._started) {\n // A span that ends WHILE the drain of `shutdown()` runs joins that drain: its\n // loop exports it before it ends, inside the same bound. Through 0.8.0 it was\n // dropped with no count. A span that ends when the drain can take no more (its\n // loop ended, or the bound ended) is counted at once as `shutdown_residue`.\n // A processor that was never started took no span, and counts none.\n if (this._drainOpen) this._enqueue(span, false);\n else if (this._closing !== null) this._lateSpan();\n return;\n }\n this._enqueue(span, true);\n }\n\n private _enqueue(span: Span, exportAtBatchSize: boolean): void {\n // Check queue capacity\n if (this._queue.length >= this._maxQueueSize) {\n if (this._quotaPaused()) {\n // S-1: the queue is the buffer while the exporter is paused for the quota. Drop the\n // OLDEST span, so that the most recent spans survive to the probe and the drain (CTO\n // decision). It is a quota drop, not queue_full. Its WARNING is the hourly quota\n // WARNING of the exporter, not the queue-full one; the exporter adds it to its count.\n const oldest = this._queue.shift();\n if (oldest !== undefined) this._forgetRetry(oldest.spanId);\n this._recordDropped('quota_exceeded');\n for (const exporter of this._exporters) {\n try {\n exporter.noteQuotaDrop?.(1);\n } catch {\n // a customer exporter must not break onSpanEnd\n }\n }\n this._queue.push(span);\n return;\n }\n this._recordDropped('queue_full');\n if (this.droppedSpans === 1 || this.droppedSpans % 1000 === 0) {\n warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);\n }\n return;\n }\n\n this._queue.push(span);\n\n // Trigger immediate flush if batch size reached\n if (exportAtBatchSize && this._queue.length >= this._batchSize) {\n void this._exportBatch();\n }\n }\n\n /**\n * True when every exporter that delivers is paused for the monthly quota (S-1). An exporter\n * says so with `quotaPaused()`. A custom exporter has none: not paused.\n */\n private _quotaPaused(): boolean {\n const deciders = this._exporters.filter((e) => e.countsAsDelivery !== false);\n if (deciders.length === 0) return false;\n for (const exporter of deciders) {\n try {\n if (exporter.quotaPaused?.() !== true) return false;\n } catch {\n return false; // a customer exporter must not break a round\n }\n }\n return true;\n }\n\n /** A span that ended after the drain ended: counted, with one WARNING for the first. */\n private _lateSpan(): void {\n this._recordDropped('shutdown_residue');\n if (this._lateSpanWarned) return;\n this._lateSpanWarned = true;\n warn(\n 'a span ended after shutdown() had stopped taking spans (reason=shutdown_residue). ' +\n 'It was not delivered, and it is counted as dropped. Later spans of this kind are ' +\n 'counted without a WARNING.'\n );\n }\n\n /**\n * Flush pending spans.\n *\n * @returns `true` only if everything queued at entry was DELIVERED and no\n * span was lost since the previous flush returned.\n *\n * RULING §6. This used to answer a different question — \"is the queue\n * empty?\" — and those two diverge in exactly one case: when spans left the\n * queue WITHOUT reaching the transport. That case is the entire finding. A\n * customer who calls `flush()` before exit and gets `true` has done\n * everything right; silence lets them discover the problem, a false\n * affirmative forecloses it.\n *\n * A LOSS IS REPORTED BY THE NEXT `flush()`, ONE TIME (design section 0,\n * third revision). Returns `true` only when, at the moment it returns, the\n * queue is empty, no batch is in flight, and no span was discarded or\n * rejected since the previous `flush()` returned (or since start, for the\n * first call). Through 0.7.1 only a loss during the call counted: a script\n * whose spans the batch timer had discarded against a 401 sink got `true`\n * with nothing delivered. A failure that a retry repairs does not make it\n * `false`.\n *\n * Mechanics: the processor keeps a loss mark, the loss total (dropped +\n * rejected) that the last finished flush saw. A flush compares the total\n * with the mark it read at its start, then raises the mark to the total\n * (never lowers it). Two flushes that overlap both answer `false` for one\n * loss. The flush after that answers `true` when nothing new was lost.\n *\n * Returns `false` in these cases:\n * (a) the deadline expires with spans still queued or in flight, or while a\n * `shutdown()` that it waits for still runs;\n * (b) a span was discarded since the previous flush returned: queue full,\n * breaker refusal, retry exhaustion, spans that `shutdown()` left\n * (`shutdown_residue`), or an ack that did not account for it or a span\n * that could not be serialized (`unacknowledged`);\n * (c) the backend rejected a span since the previous flush returned.\n *\n * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at\n * SIGTERM or SIGINT, or a `shutdown()` that nobody awaited) waits for that\n * shutdown, inside its OWN deadline, and then answers from the final tally with\n * the same loss mark. After `shutdown()` it answers from the final tally in the\n * same way. Through 0.8.0 both answered from the empty queue: true in 0 ms,\n * with the batch in flight, and true after a rejection or a `transport_refused`\n * drop. A loss that `shutdown()` counts (also `shutdown_residue`) makes ONE\n * `flush()` false, as every other loss does.\n *\n * The deadline is a hard wall-clock bound on the WAIT. At the deadline\n * `flush()` returns `false`. Through 0.7.1 the deadline was checked only\n * between rounds.\n *\n * ⚠ `flush()` never stops a request that is already sent. The export round in\n * flight continues and ends by its own rules: its request timeout, its\n * retries, the circuit breaker. A short flush budget therefore costs no retry,\n * moves no breaker and sends nothing twice. Its result still counts.\n *\n * Limit: that round can keep the process alive after `flush()` returns\n * `false`, until its own timeouts end. Measured on a silent server: 22 s. To\n * end a process within a bound, call `await shutdown(timeoutMs)`: it stops\n * the round in flight.\n *\n * ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span\n * that arrived during the call also answers `false`. That is the\n * conservative direction on purpose: a false negative costs a caller one\n * more flush, a false positive is the defect being fixed.\n */\n async flush(timeoutMs: number = SHUTDOWN_BUDGET_MS): Promise<boolean> {\n timeoutMs = normalizeTimeoutMs(timeoutMs);\n\n const deadline = Date.now() + timeoutMs;\n const mark = this._lossMark;\n // Report a loss once: compare with the mark, then raise the mark to the\n // total this flush saw (never lower it). Two flushes that overlap both\n // answer false for one loss.\n const finish = (settled: boolean): boolean => {\n const lost = this.droppedSpans + this.rejectedSpans;\n this._lossMark = Math.max(this._lossMark, lost);\n return settled && lost === mark;\n };\n\n if (!this._started) {\n // A `shutdown()` that runs (the SDK's own drain, or one that nobody\n // awaited): its batch is in flight and its residue is not counted yet.\n // Wait for it, inside THIS deadline. The unconditional answer from the\n // empty queue was true in 0 ms, with nothing delivered.\n if (this._closing !== null) {\n const closed = await raceDeadline(this._closing.catch(() => undefined), timeoutMs);\n if (closed === DEADLINE) return finish(false);\n }\n // Shut down: the queue is empty, and a batch that `shutdown()` abandoned\n // is counted already (`shutdown_residue`), so the loss mark covers it.\n const held = this._inFlight !== null && !this._inFlight.abandoned;\n return finish(this._queue.length === 0 && !held);\n }\n\n // Wait for in-flight exports to complete AND queue to drain\n while (this._queue.length > 0 || this._flushing) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) return finish(false);\n // S-1: every exporter that delivers is paused for the monthly quota, nothing is in an\n // export, and spans wait in the queue. They cannot go out before the pause ends\n // (minutes), so waiting out the timeout only slows the caller. Answer false at once.\n if (!this._flushing && this._queue.length > 0 && this._quotaPaused()) return finish(false);\n if (!this._flushing && this._queue.length > 0) {\n // Race the WAIT only. The round continues after the deadline.\n const outcome = await raceDeadline(this._exportBatch(), remaining);\n if (outcome === DEADLINE) return finish(false);\n // Paused for the quota: nothing to do until the pause ends. Do not spin.\n if (outcome === Round.Paused) await new Promise((r) => setTimeout(r, 20));\n } else {\n // Wait a tick for the in-flight export to finish\n await new Promise((r) => setTimeout(r, 1));\n }\n }\n\n return finish(true);\n }\n\n getMetrics() {\n return {\n exportedSpans: this.exportedSpans,\n rejectedSpans: this.rejectedSpans,\n droppedSpans: this.droppedSpans,\n droppedSpansByReason: { ...this.droppedSpansByReason },\n // Spans dropped because the monthly event quota is used up (S-1). The same number as\n // `droppedSpansByReason.quota_exceeded`, for a reader that wants one key.\n droppedQuota: this.droppedSpansByReason.quota_exceeded,\n failedExports: this.failedExports,\n maskErrors: this.maskErrors,\n queueSize: this._queue.length,\n queueCapacity: this._maxQueueSize,\n queueUtilization: this._queue.length / this._maxQueueSize,\n };\n }\n\n /**\n * Count a delivered batch of `n` spans from the exporter's ack.\n *\n * The ack is not trusted. With r = min(rejected, n), a = min(accepted, n - r)\n * and u = n - a - r: `exportedSpans` rises by a, `rejectedSpans` by r, and the\n * u spans that no ack accounts for are dropped as `unacknowledged`, with one\n * rate-limited WARNING. Without an ack (console, custom exporter), the whole\n * batch counts as exported, as before. Python twin: the same clamp.\n */\n private _countDelivered(n: number, ack: AckCounts | null): void {\n if (ack === null) {\n this.exportedSpans += n;\n return;\n }\n // S-1: spans that the monthly quota paused or discarded. The exporter's ack is 0 and 0, so\n // they would be `unacknowledged`; count them as `quota_exceeded` and take them out first.\n const quota = Math.min(Math.max(ack.quotaDropped ?? 0, 0), n);\n if (quota > 0) {\n this._recordDropped('quota_exceeded', quota);\n n -= quota;\n if (n === 0) return;\n }\n // Pessimistic: a sink that says \"rejected\" is believed before one that says\n // \"accepted\" (design section 0, ack clamp REVISED).\n const rejected = Math.min(ack.rejected, n);\n const accepted = Math.min(ack.accepted, n - rejected);\n const unacknowledged = n - accepted - rejected;\n this.exportedSpans += accepted;\n this.rejectedSpans += rejected;\n if (unacknowledged > 0) {\n this._recordDropped('unacknowledged', unacknowledged);\n const now = Date.now();\n if (now - this._lastUnackWarnAt > REFUSAL_WARN_WINDOW_MS) {\n this._lastUnackWarnAt = now;\n warn(\n `Risicare: the backend's ack accounts for ${accepted + rejected} of ${n} span(s) ` +\n `in this batch. The other ${unacknowledged} are counted as dropped ` +\n `(reason=unacknowledged): they may not be stored. ` +\n `${this.droppedSpansByReason.unacknowledged} span(s) counted this way so far ` +\n `in this process.`,\n );\n }\n }\n }\n\n /** The one exporter that delivers, when there is exactly one. */\n private _soleDeliverer(): SpanExporter | undefined {\n const delivering = this._exporters.filter((e) => e.countsAsDelivery !== false);\n return delivering.length === 1 ? delivering[0] : undefined;\n }\n\n /** The most requests in one export round, when every exporter that delivers states it. */\n private _requestsPerRound(): number | undefined {\n const n = this._soleDeliverer()?.attemptsPerExport;\n return typeof n === 'number' && Number.isFinite(n) && n > 0 ? n : undefined;\n }\n\n /**\n * The HTTP requests that the failed round for `batch` really sent (issue #57). `undefined`\n * when the exporter that delivers does not state it, so that the WARNING keeps its \"up to\"\n * text. NaN when the exporter has no record of the round.\n */\n private _requestsSent(batch: Span[]): number | undefined {\n const exporter = this._soleDeliverer();\n if (exporter === undefined || typeof exporter.takeAttempts !== 'function') return undefined;\n try {\n const n = exporter.takeAttempts(batch);\n return typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : Number.NaN;\n } catch (e) {\n debug(`takeAttempts of ${exporter.name} failed: ${describeThrown(e)}`);\n return Number.NaN;\n }\n }\n\n /** End the retry tracking of one span (retry-map drain sites 1 and 2 of 3, and the queue drop). */\n private _forgetRetry(spanId: string): void {\n this._retryCounts.delete(spanId);\n this._retryRequests.delete(spanId);\n }\n\n /**\n * One export round.\n *\n * Which results decide delivery: an exporter that only shows spans locally\n * (`countsAsDelivery === false`, the console exporter) decides only when no\n * other kind of exporter is present. Among the exporters that deliver, ANY\n * success counts the batch as delivered, once.\n */\n private async _exportBatch(): Promise<Round> {\n if (this._flushing) return Round.Busy;\n if (this._queue.length === 0) return Round.Empty;\n // S-1: every exporter that delivers is paused for the monthly quota. Take nothing: the spans\n // stay in the queue and go out when the pause ends.\n if (this._quotaPaused()) return Round.Paused;\n this._flushing = true;\n let flight: InFlight | null = null;\n\n try {\n // Take up to batchSize spans — AND up to the attribute-product bound, AND\n // up to the serialized-byte bound; whichever binds first\n // (SDK-RELEASE-RULING.md §4.5 + F-SDKBYTES-001). `batchSize` is a CEILING,\n // not a fixed size, on all three axes.\n //\n // Take-at-least-one is unconditional on every axis: a single span that\n // alone exceeded a bound would otherwise be taken by no round ever,\n // wedging the queue permanently. One over-cap span is the gateway's\n // problem to refuse and the retry budget's to count; a wedged queue would\n // be ours forever.\n let take = 0;\n let pairs = 0;\n let nbytes = 0;\n const limit = Math.min(this._batchSize, this._queue.length);\n while (take < limit) {\n const head = this._queue[take];\n const spanPairs = spanAttrCount(head);\n const spanBytes = spanBytesEstimate(head);\n if (\n take > 0 &&\n (pairs + spanPairs > MAX_ATTRIBUTE_PAIRS_PER_BATCH ||\n nbytes + spanBytes > MAX_BATCH_BYTES)\n ) {\n break;\n }\n pairs += spanPairs;\n nbytes += spanBytes;\n take++;\n }\n const batch = this._queue.splice(0, take);\n if (batch.length === 0) return Round.Empty;\n flight = { spans: batch, size: batch.length, abandoned: false };\n this._inFlight = flight;\n\n // ⚠ MASK HERE — after the batch is off the queue, before any exporter.\n //\n // WHY NOT in `onSpanEnd()`: that runs on the call that ended the span,\n // i.e. inside the customer's own request path. This site is at least on\n // the export turn.\n //\n // ⚠ AND WHY THAT IS A WEAKER GUARANTEE THAN PYTHON'S: Node has one\n // thread. Python's mask runs on a background worker and costs only drain\n // rate; this one blocks the event loop for its duration. The budget\n // warning below is the whole of the protection, and it is a warning.\n //\n // ⚠ DECLARED RIPPLE, same as Python: the attribute-product and byte\n // bounds above are computed on PRE-mask values. Redaction shrinks, so the\n // estimate stays conservative for every realistic mask; a mask that GROWS\n // content can push the real body past the estimate, which the estimate\n // already declares for ASCII escaping and already answers the same way —\n // the gateway remains the enforcer.\n // ⚠ STRIP BEFORE MASK, and unconditionally when capture is off.\n //\n // Before mask because content the customer never wanted to leave the\n // process should not be handed to a customer callback either — and\n // because a mask never called over a stripped field costs nothing, which\n // matters more here than in Python: this runs on the ONE event loop.\n //\n // Unconditional (not `if this._mask !== undefined`) because THIS is the\n // gate: `_applyMask` runs only when a mask was supplied, and the whole\n // defect being closed is that content escaped when nobody had opted into\n // anything.\n if (!this._traceContent) {\n const stripped = stripContentBatch(batch);\n if (stripped > 0) {\n debug(\n `traceContent is off — omitted ${stripped} content field(s) from ${batch.length} span(s)`,\n );\n }\n }\n\n if (this._mask !== undefined) {\n this._applyMask(batch);\n }\n\n debug(`Exporting batch of ${batch.length} spans`);\n\n // Export to all exporters — count once, not per exporter\n let batchExported = false;\n const anyDelivers = this._exporters.some((e) => e.countsAsDelivery !== false);\n // Spans that an exporter could not serialize: not sent, dropped at once.\n const unserializable = new Set<Span>();\n for (const exporter of this._exporters) {\n const decides = !anyDelivers || exporter.countsAsDelivery !== false;\n try {\n const result = await exporter.export(batch);\n // `shutdown()` stopped this batch and counted it as residue. Its late\n // answer changes no counter and re-queues nothing.\n if (flight.abandoned) return Round.Failed;\n if (!decides) continue;\n for (const span of exporter.takeUnserializable?.(batch) ?? []) unserializable.add(span);\n if (result === ExportResult.SUCCESS) {\n const ack = exporter.takeAck?.(batch) ?? null;\n if (!batchExported) {\n this._countDelivered(batch.length - unserializable.size, ack);\n batchExported = true;\n // Clear retry counts for successfully exported spans\n for (const span of batch) {\n this._forgetRetry(span.spanId);\n }\n }\n } else {\n this.failedExports++;\n }\n } catch (e) {\n if (flight.abandoned) return Round.Failed;\n if (!decides) continue;\n this.failedExports++;\n debug(`Export to ${exporter.name} failed: ${describeThrown(e)}`);\n }\n }\n if (unserializable.size > 0) this._recordDropped('unacknowledged', unserializable.size);\n\n // Audit #5: Re-queue failed batches with retry limit\n if (!batchExported) {\n let dropped = 0;\n // The requests that this round sent. Each span of the batch was in all of them.\n const sent = this._requestsSent(batch);\n // The requests of ALL the failed rounds of each span that is dropped now.\n const droppedRequests: number[] = [];\n const retryable = batch.filter(span => {\n if (unserializable.has(span)) return false;\n const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;\n const requests =\n sent === undefined ? undefined : (this._retryRequests.get(span.spanId) ?? 0) + sent;\n if (count > BatchSpanProcessor.MAX_RETRIES) {\n // retry-map drain site 2 of 3\n this._forgetRetry(span.spanId);\n if (requests !== undefined) droppedRequests.push(requests);\n // The count is once per SPAN IDENTITY, at exhaustion — never once\n // per attempt. A span re-queued twice and then dropped is ONE lost\n // span; keying on spanId is what makes that true.\n this._recordDropped('transport_refused');\n dropped++;\n return false;\n }\n this._retryCounts.set(span.spanId, count);\n if (requests !== undefined) this._retryRequests.set(span.spanId, requests);\n return true;\n });\n if (retryable.length > 0) {\n this._queue.unshift(...retryable);\n debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);\n }\n if (dropped > 0) {\n // RULING §2: the PRIMARY remedy is a default-visible WARNING at the\n // moment of discard, naming the count and the reason — not a counter.\n // The log line survives the process; the counter does not, and on the\n // shutdown path there is no reader for it at all. `debug()` above is\n // suppressed at default level, which is why this is `warn()`.\n const now = Date.now();\n if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {\n this._lastRefusalWarnAt = now;\n const rounds = BatchSpanProcessor.MAX_RETRIES + 1;\n const perRound = this._requestsPerRound();\n // The number that the exporter says it sent, when it says so for every round of\n // every span that is dropped now. A 401 or 403 sends one request in a round, so the\n // old \"up to\" number was wrong for it. When the exporter does not say, the old text\n // stays: the most that the rounds may send.\n const stated =\n droppedRequests.length > 0 && droppedRequests.every((n) => Number.isFinite(n));\n let requestsText = '';\n if (stated) {\n let lo = droppedRequests[0];\n let hi = lo;\n for (const n of droppedRequests) {\n if (n < lo) lo = n;\n if (n > hi) hi = n;\n }\n requestsText =\n lo === hi\n ? ` (${hi} HTTP ${hi === 1 ? 'request' : 'requests'} sent)`\n : ` (${lo} to ${hi} HTTP requests sent)`;\n } else if (perRound !== undefined) {\n requestsText = ` (up to ${rounds * perRound} HTTP requests: ${perRound} in each round)`;\n }\n warn(\n `${dropped} span(s) DISCARDED (reason=transport_refused) after ` +\n `${rounds} failed export rounds each` +\n requestsText +\n ` — the endpoint is ` +\n `not accepting spans and the retry budget is spent. ` +\n `${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far ` +\n `in this process. This data is gone; check the apiKey and the endpoint.`\n );\n }\n }\n }\n return batchExported ? Round.Delivered : Round.Failed;\n } finally {\n if (this._inFlight === flight) this._inFlight = null;\n this._flushing = false;\n }\n }\n}\n","/**\n * ID generation for traces and spans.\n *\n * Trace IDs: 32 lowercase hex characters (16 random bytes)\n * Span IDs: 16 lowercase hex characters (8 random bytes)\n *\n * Uses crypto.randomBytes for cryptographically secure randomness.\n */\n\nimport { randomBytes } from 'node:crypto';\n\nconst HEX_REGEX_32 = /^[0-9a-f]{32}$/;\nconst HEX_REGEX_16 = /^[0-9a-f]{16}$/;\n\nexport function generateTraceId(): string {\n return randomBytes(16).toString('hex');\n}\n\nexport function generateSpanId(): string {\n return randomBytes(8).toString('hex');\n}\n\nexport function generateAgentId(prefix?: string): string {\n const suffix = randomBytes(8).toString('hex');\n return prefix ? `${prefix}-${suffix}` : suffix;\n}\n\nexport function validateTraceId(id: string): boolean {\n return HEX_REGEX_32.test(id);\n}\n\nexport function validateSpanId(id: string): boolean {\n return HEX_REGEX_16.test(id);\n}\n","/**\n * No-op implementations for the disabled path.\n *\n * When tracing is disabled, all operations return these no-op objects\n * to maintain zero overhead. No allocations, no side effects.\n */\n\nimport { SpanKind, SpanStatus, type SpanPayload } from './types.js';\n\n/**\n * A frozen no-op span that silently ignores all operations.\n * Used when SDK is disabled to avoid overhead.\n */\nexport const NOOP_SPAN = Object.freeze({\n traceId: '00000000000000000000000000000000',\n spanId: '0000000000000000',\n parentSpanId: undefined,\n name: 'noop',\n kind: SpanKind.INTERNAL,\n startTime: '',\n startHrtime: 0,\n endTime: undefined,\n status: SpanStatus.UNSET,\n statusMessage: undefined,\n attributes: Object.freeze({}) as Record<string, unknown>,\n events: Object.freeze([]) as readonly [],\n links: Object.freeze([]) as readonly [],\n sessionId: undefined,\n agentId: undefined,\n agentName: undefined,\n semanticPhase: undefined,\n llmProvider: undefined,\n llmModel: undefined,\n llmPromptTokens: undefined,\n llmCompletionTokens: undefined,\n llmTotalTokens: undefined,\n llmCostUsd: undefined,\n toolName: undefined,\n toolSuccess: undefined,\n isEnded: true,\n durationMs: 0,\n\n setAttribute() { return this; },\n setAttributes() { return this; },\n setStatus() { return this; },\n addEvent() { return this; },\n addLink() { return this; },\n recordException() { return this; },\n setLlmFields() { return this; },\n setToolFields() { return this; },\n end() {},\n toPayload(): SpanPayload {\n return {\n traceId: this.traceId,\n spanId: this.spanId,\n name: this.name,\n kind: this.kind,\n startTime: this.startTime,\n status: this.status,\n attributes: {},\n events: [],\n links: [],\n };\n },\n});\n\nexport type NoopSpan = typeof NOOP_SPAN;\n","/**\n * Fix Runtime Configuration.\n *\n * Settings for the fix runtime including caching, refresh intervals,\n * A/B testing, and fix application behavior.\n *\n * Port of Python SDK's runtime/config.py adapted for Node.js patterns.\n */\n\n// ─── Runtime Configuration ──────────────────────────────────────────────────\n\nexport interface FixRuntimeConfig {\n /** Api URL, serving /v1/fixes/active (e.g., \"https://api.risicare.ai\") */\n apiEndpoint: string;\n\n /** API key for authentication (format: \"rsk-{random}\") */\n apiKey: string;\n\n /** Whether the fix runtime is enabled (default: true) */\n enabled?: boolean;\n\n /** Whether caching is enabled (default: true) */\n cacheEnabled?: boolean;\n\n /** Cache entry TTL in milliseconds (default: 300_000 = 5 min) */\n cacheTtlMs?: number;\n\n /** Maximum number of cache entries (default: 1000) */\n cacheMaxEntries?: number;\n\n /** Whether to auto-refresh fixes in background (default: true) */\n autoRefresh?: boolean;\n\n /** Background refresh interval in milliseconds (default: 60_000 = 1 min) */\n refreshIntervalMs?: number;\n\n /** Log but don't apply fixes (default: false) */\n dryRun?: boolean;\n\n /** Whether A/B testing bucketing is active (default: true) */\n abTestingEnabled?: boolean;\n\n /** Timeout for API requests in milliseconds (default: 1000) */\n timeoutMs?: number;\n\n /** Enable debug logging (default: false) */\n debug?: boolean;\n}\n\n/** Resolve config with defaults applied. */\nexport function resolveFixRuntimeConfig(\n config: FixRuntimeConfig,\n): Required<FixRuntimeConfig> {\n return {\n apiEndpoint: config.apiEndpoint,\n apiKey: config.apiKey,\n enabled: config.enabled ?? true,\n cacheEnabled: config.cacheEnabled ?? true,\n cacheTtlMs: config.cacheTtlMs ?? 300_000,\n cacheMaxEntries: config.cacheMaxEntries ?? 1000,\n autoRefresh: config.autoRefresh ?? true,\n refreshIntervalMs: config.refreshIntervalMs ?? 60_000,\n dryRun: config.dryRun ?? false,\n abTestingEnabled: config.abTestingEnabled ?? true,\n timeoutMs: config.timeoutMs ?? 1000,\n debug: config.debug ?? false,\n };\n}\n\n// ─── Fix Type ───────────────────────────────────────────────────────────────\n\nexport type FixType =\n | 'prompt'\n | 'parameter'\n | 'retry'\n | 'fallback'\n | 'guard'\n | 'routing'\n | 'tool';\n\n// ─── Active Fix ─────────────────────────────────────────────────────────────\n\nexport interface ActiveFix {\n fixId: string;\n deploymentId?: string;\n errorCode: string;\n fixType: FixType;\n config: Record<string, unknown>;\n trafficPercentage: number; // 0–100\n version: number;\n}\n\n/**\n * Check if a fix matches the given error code.\n *\n * Supports exact match and wildcard prefix matching:\n * - \"TOOL.EXECUTION.TIMEOUT\" matches \"TOOL.EXECUTION.TIMEOUT\"\n * - \"TOOL.EXECUTION.*\" matches \"TOOL.EXECUTION.TIMEOUT\", \"TOOL.EXECUTION.FAILURE\", etc.\n * - \"TOOL.*\" matches any TOOL error\n */\nexport function matchesError(fix: ActiveFix, errorCode: string): boolean {\n if (fix.errorCode === errorCode) {\n return true;\n }\n\n // Wildcard matching\n if (fix.errorCode.endsWith('*')) {\n const prefix = fix.errorCode.slice(0, -1);\n return errorCode.startsWith(prefix);\n }\n\n return false;\n}\n\n/**\n * Determine if fix should be applied based on A/B traffic percentage.\n *\n * Uses consistent hashing so the same session always gets the same\n * treatment (fix or no fix).\n */\nexport function shouldApply(fix: ActiveFix, sessionHash: number): boolean {\n if (fix.trafficPercentage >= 100) return true;\n if (fix.trafficPercentage <= 0) return false;\n\n const bucket = sessionHash % 100;\n return bucket < fix.trafficPercentage;\n}\n\n/**\n * Create an ActiveFix from an API response item.\n *\n * Handles both snake_case (server API) and camelCase field names.\n */\nexport function activeFixFromApiResponse(\n item: Record<string, unknown>,\n): ActiveFix {\n return {\n fixId: (item.id ?? item.fix_id ?? item.fixId ?? '') as string,\n deploymentId: (item.deployment_id ?? item.deploymentId ?? '') as string,\n errorCode: (item.error_code ?? item.errorCode ?? '') as string,\n fixType: (item.fix_type ?? item.fixType ?? 'prompt') as FixType,\n config: (item.config ?? {}) as Record<string, unknown>,\n trafficPercentage: (item.traffic_percentage ?? item.trafficPercentage ?? 100) as number,\n version: (item.version ?? 1) as number,\n };\n}\n","// ⚠ GENERATED FILE — DO NOT EDIT BY HAND.\n//\n// Source of truth: packages/risicare-sdk/src/risicare/runtime/_error_taxonomy.py\n// Generator: packages/risicare-sdk/scripts/gen_js_taxonomy.py\n// Core rules: packages/risicare-core/src/risicare_core/taxonomy.py (_KEYWORD_RULES)\n// Verify: just taxonomy (gen_js_taxonomy.py --check)\n//\n// F-SDKTAXFORK-001. This SDK cannot import `risicare_core.taxonomy` —\n// `risicare-core` is not published to npm. Rather than hand-maintain a second\n// copy of one rule (a divergence this campaign has measured four times), the\n// rule table and the canonical code set are generated from the Python source\n// and a rail fails when the two drift.\n//\n// Each pattern is a translation of the Python pattern for the `u` flag\n// (`.` -> `[^\\n]`, `\\b` -> a lookaround on [\\p{L}\\p{N}_]). The text is\n// lowercased before the match, as in Python, so no rule has a case flag.\n//\n// 154 canonical codes across 10 modules.\n\nexport const CANONICAL_ERROR_CODES: ReadonlySet<string> = new Set([\n \"COMMUNICATION.CONTENT.AMBIGUOUS\",\n \"COMMUNICATION.CONTENT.CORRUPTED\",\n \"COMMUNICATION.CONTENT.INCOMPATIBLE\",\n \"COMMUNICATION.CONTENT.MALFORMED\",\n \"COMMUNICATION.CONTENT.TOO_LARGE\",\n \"COMMUNICATION.DELIVERY.DELAYED\",\n \"COMMUNICATION.DELIVERY.DUPLICATED\",\n \"COMMUNICATION.DELIVERY.EXPIRED\",\n \"COMMUNICATION.DELIVERY.OUT_OF_ORDER\",\n \"COMMUNICATION.DELIVERY.UNDELIVERABLE\",\n \"COMMUNICATION.ROUTING.BROADCAST_STORM\",\n \"COMMUNICATION.ROUTING.LOOP\",\n \"COMMUNICATION.ROUTING.NO_ROUTE\",\n \"COMMUNICATION.ROUTING.PARTITION\",\n \"COMMUNICATION.ROUTING.WRONG_ROUTE\",\n \"CONSENSUS.AGREEMENT.INCONSISTENT\",\n \"CONSENSUS.AGREEMENT.QUORUM_FAILED\",\n \"CONSENSUS.AGREEMENT.REJECTED\",\n \"CONSENSUS.AGREEMENT.STALE_VOTE\",\n \"CONSENSUS.AGREEMENT.TIMEOUT\",\n \"CONSENSUS.CONFLICT.BIAS\",\n \"CONSENSUS.CONFLICT.CASCADING\",\n \"CONSENSUS.CONFLICT.DEADLOCK\",\n \"CONSENSUS.CONFLICT.RESOLUTION_REJECTED\",\n \"CONSENSUS.CONFLICT.UNRESOLVED\",\n \"CONSENSUS.VOTING.ABSTENTION_FLOOD\",\n \"CONSENSUS.VOTING.COERCED_VOTE\",\n \"CONSENSUS.VOTING.DUPLICATE_VOTE\",\n \"CONSENSUS.VOTING.INVALID_VOTE\",\n \"CONSENSUS.VOTING.SPLIT_VOTE\",\n \"COORDINATION.HANDOFF.DELAYED\",\n \"COORDINATION.HANDOFF.DUPLICATED\",\n \"COORDINATION.HANDOFF.INCOMPLETE\",\n \"COORDINATION.HANDOFF.LOST\",\n \"COORDINATION.HANDOFF.WRONG_RECIPIENT\",\n \"COORDINATION.SYNCHRONIZATION.CLOCK_SKEW\",\n \"COORDINATION.SYNCHRONIZATION.OUT_OF_ORDER\",\n \"COORDINATION.SYNCHRONIZATION.RACE_CONDITION\",\n \"COORDINATION.SYNCHRONIZATION.SPLIT_BRAIN\",\n \"COORDINATION.SYNCHRONIZATION.VERSION_MISMATCH\",\n \"COORDINATION.WORKFLOW.CYCLE\",\n \"COORDINATION.WORKFLOW.DEADLOCK\",\n \"COORDINATION.WORKFLOW.LIVELOCK\",\n \"COORDINATION.WORKFLOW.ORPHANED\",\n \"COORDINATION.WORKFLOW.STARVATION\",\n \"MEMORY.CONTEXT_WINDOW.DROPPED\",\n \"MEMORY.CONTEXT_WINDOW.EXCEEDED\",\n \"MEMORY.CONTEXT_WINDOW.FRAGMENTED\",\n \"MEMORY.CONTEXT_WINDOW.PRIORITY_ERROR\",\n \"MEMORY.RETRIEVAL.INCOMPLETE\",\n \"MEMORY.RETRIEVAL.NOT_FOUND\",\n \"MEMORY.RETRIEVAL.OUTDATED\",\n \"MEMORY.RETRIEVAL.TOO_MANY\",\n \"MEMORY.RETRIEVAL.WRONG_MATCH\",\n \"MEMORY.STATE.CORRUPTED\",\n \"MEMORY.STATE.INCONSISTENT\",\n \"MEMORY.STATE.LOST\",\n \"MEMORY.STATE.OVERFLOW\",\n \"MEMORY.STATE.STALE\",\n \"ORCHESTRATION.DELEGATION.CAPABILITY_MISMATCH\",\n \"ORCHESTRATION.DELEGATION.CIRCULAR_DELEGATION\",\n \"ORCHESTRATION.DELEGATION.EXCESSIVE_DEPTH\",\n \"ORCHESTRATION.DELEGATION.NO_AVAILABLE_AGENT\",\n \"ORCHESTRATION.DELEGATION.OVERLOADED_AGENT\",\n \"ORCHESTRATION.LIFECYCLE.CLEANUP_FAILED\",\n \"ORCHESTRATION.LIFECYCLE.CRASHED\",\n \"ORCHESTRATION.LIFECYCLE.HUNG\",\n \"ORCHESTRATION.LIFECYCLE.SPAWN_FAILED\",\n \"ORCHESTRATION.LIFECYCLE.ZOMBIE\",\n \"ORCHESTRATION.SCALING.OVERLOADED\",\n \"ORCHESTRATION.SCALING.QUOTA_EXCEEDED\",\n \"ORCHESTRATION.SCALING.SCALE_DOWN_FAILED\",\n \"ORCHESTRATION.SCALING.SCALE_UP_FAILED\",\n \"ORCHESTRATION.SCALING.UNDERUTILIZED\",\n \"OUTPUT.FORMAT.ENCODING\",\n \"OUTPUT.FORMAT.INVALID_JSON\",\n \"OUTPUT.FORMAT.MALFORMED\",\n \"OUTPUT.FORMAT.SCHEMA_VIOLATION\",\n \"OUTPUT.FORMAT.TRUNCATED\",\n \"OUTPUT.QUALITY.INCOMPLETE\",\n \"OUTPUT.QUALITY.IRRELEVANT\",\n \"OUTPUT.QUALITY.REPETITIVE\",\n \"OUTPUT.QUALITY.UNCLEAR\",\n \"OUTPUT.QUALITY.VERBOSE\",\n \"OUTPUT.SAFETY.BIAS\",\n \"OUTPUT.SAFETY.COPYRIGHT\",\n \"OUTPUT.SAFETY.HARMFUL_CONTENT\",\n \"OUTPUT.SAFETY.PII_LEAK\",\n \"OUTPUT.SAFETY.POLICY_VIOLATION\",\n \"PERCEPTION.CONTEXT.CONFLICTING\",\n \"PERCEPTION.CONTEXT.IRRELEVANT\",\n \"PERCEPTION.CONTEXT.MISSING\",\n \"PERCEPTION.CONTEXT.OVERFLOW\",\n \"PERCEPTION.CONTEXT.STALE\",\n \"PERCEPTION.INPUT.ENCODING\",\n \"PERCEPTION.INPUT.INJECTION\",\n \"PERCEPTION.INPUT.MALFORMED\",\n \"PERCEPTION.INPUT.SCHEMA_MISMATCH\",\n \"PERCEPTION.INPUT.TRUNCATED\",\n \"PERCEPTION.PARSING.DATE_FORMAT\",\n \"PERCEPTION.PARSING.JSON_INVALID\",\n \"PERCEPTION.PARSING.NUMBER_FORMAT\",\n \"PERCEPTION.PARSING.REFERENCE_BROKEN\",\n \"PERCEPTION.PARSING.XML_INVALID\",\n \"REASONING.DECISION.BIASED\",\n \"REASONING.DECISION.INDECISIVE\",\n \"REASONING.DECISION.OSCILLATING\",\n \"REASONING.DECISION.OVERCONFIDENT\",\n \"REASONING.DECISION.PREMATURE\",\n \"REASONING.HALLUCINATION.CAPABILITY\",\n \"REASONING.HALLUCINATION.CITATION\",\n \"REASONING.HALLUCINATION.ENTITY\",\n \"REASONING.HALLUCINATION.FACTUAL\",\n \"REASONING.HALLUCINATION.TEMPORAL\",\n \"REASONING.LOGIC.CIRCULAR\",\n \"REASONING.LOGIC.CONTRADICTION\",\n \"REASONING.LOGIC.INCOMPLETE\",\n \"REASONING.LOGIC.INVALID_INFERENCE\",\n \"REASONING.LOGIC.MISSING_PREMISE\",\n \"REASONING.PLANNING.INCOMPLETE\",\n \"REASONING.PLANNING.INFEASIBLE\",\n \"REASONING.PLANNING.SCOPE_CREEP\",\n \"REASONING.PLANNING.SUBOPTIMAL\",\n \"REASONING.PLANNING.UNSAFE\",\n \"RESOURCES.ACCESS.DENIED\",\n \"RESOURCES.ACCESS.EXPIRED\",\n \"RESOURCES.ACCESS.LOCKED\",\n \"RESOURCES.ACCESS.NOT_FOUND\",\n \"RESOURCES.ACCESS.REVOKED\",\n \"RESOURCES.CONTENTION.DEADLOCK\",\n \"RESOURCES.CONTENTION.OVERFLOW\",\n \"RESOURCES.CONTENTION.PRIORITY_INVERSION\",\n \"RESOURCES.CONTENTION.STARVATION\",\n \"RESOURCES.CONTENTION.THRASHING\",\n \"RESOURCES.QUOTA.ALLOCATION_FAILED\",\n \"RESOURCES.QUOTA.EXCEEDED\",\n \"RESOURCES.QUOTA.LEAK\",\n \"RESOURCES.QUOTA.STALE\",\n \"RESOURCES.QUOTA.UNFAIR_DISTRIBUTION\",\n \"TOOL.EXECUTION.CRASHED\",\n \"TOOL.EXECUTION.DEPENDENCY_FAILED\",\n \"TOOL.EXECUTION.RATE_LIMITED\",\n \"TOOL.EXECUTION.RESOURCE_EXHAUSTED\",\n \"TOOL.EXECUTION.TIMEOUT\",\n \"TOOL.INVOCATION.INVALID_ARGS\",\n \"TOOL.INVOCATION.MISSING_REQUIRED\",\n \"TOOL.INVOCATION.NOT_FOUND\",\n \"TOOL.INVOCATION.PERMISSION_DENIED\",\n \"TOOL.INVOCATION.TYPE_MISMATCH\",\n \"TOOL.RESULT.EMPTY\",\n \"TOOL.RESULT.ERROR_IN_RESULT\",\n \"TOOL.RESULT.PARTIAL\",\n \"TOOL.RESULT.UNEXPECTED_FORMAT\",\n \"TOOL.RESULT.UNPARSEABLE\",\n]);\n\nexport interface TaxonomyRule {\n re: RegExp;\n code: string;\n}\n\n/**\n * risicare-core's keyword rules (`classify_error`). Python applies them FIRST,\n * to the lowercased message only. Order matters: first match wins.\n */\nexport const CORE_RULES: readonly TaxonomyRule[] = [\n { re: new RegExp(\"json\", 'u'), code: \"PERCEPTION.PARSING.JSON_INVALID\" },\n { re: new RegExp(\"encoding\", 'u'), code: \"PERCEPTION.INPUT.ENCODING\" },\n { re: new RegExp(\"injection\", 'u'), code: \"PERCEPTION.INPUT.INJECTION\" },\n { re: new RegExp(\"malformed\", 'u'), code: \"PERCEPTION.INPUT.MALFORMED\" },\n { re: new RegExp(\"hallucin\", 'u'), code: \"REASONING.HALLUCINATION.FACTUAL\" },\n { re: new RegExp(\"contradict\", 'u'), code: \"REASONING.LOGIC.CONTRADICTION\" },\n { re: new RegExp(\"timeout\", 'u'), code: \"TOOL.EXECUTION.TIMEOUT\" },\n { re: new RegExp(\"rate[^\\\\n]?limit\", 'u'), code: \"TOOL.EXECUTION.RATE_LIMITED\" },\n { re: new RegExp(\"permission\", 'u'), code: \"TOOL.INVOCATION.PERMISSION_DENIED\" },\n { re: new RegExp(\"context[^\\\\n]+overflow\", 'u'), code: \"MEMORY.CONTEXT_WINDOW.EXCEEDED\" },\n { re: new RegExp(\"state[^\\\\n]+corrupt\", 'u'), code: \"MEMORY.STATE.CORRUPTED\" },\n { re: new RegExp(\"pii\", 'u'), code: \"OUTPUT.SAFETY.PII_LEAK\" },\n { re: new RegExp(\"deadlock\", 'u'), code: \"COORDINATION.WORKFLOW.DEADLOCK\" },\n { re: new RegExp(\"undeliverable\", 'u'), code: \"COMMUNICATION.DELIVERY.UNDELIVERABLE\" },\n { re: new RegExp(\"crash\", 'u'), code: \"ORCHESTRATION.LIFECYCLE.CRASHED\" },\n { re: new RegExp(\"quorum\", 'u'), code: \"CONSENSUS.AGREEMENT.QUORUM_FAILED\" },\n { re: new RegExp(\"quota[^\\\\n]+exceed\", 'u'), code: \"RESOURCES.QUOTA.EXCEEDED\" },\n];\n\n/** Order matters: first match wins, most specific first. */\nexport const SUPPLEMENTAL_RULES: readonly TaxonomyRule[] = [\n { re: new RegExp(\"timeout|timedout|aborted\", 'u'), code: \"TOOL.EXECUTION.TIMEOUT\" },\n { re: new RegExp(\"rate[^\\\\n]?limit|(?<![\\\\p{L}\\\\p{N}_])429(?![\\\\p{L}\\\\p{N}_])|too many requests\", 'u'), code: \"TOOL.EXECUTION.RATE_LIMITED\" },\n { re: new RegExp(\"connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe\", 'u'), code: \"TOOL.EXECUTION.DEPENDENCY_FAILED\" },\n { re: new RegExp(\"(?<![\\\\p{L}\\\\p{N}_])auth|unauthorized|forbidden|permission|(?<![\\\\p{L}\\\\p{N}_])401(?![\\\\p{L}\\\\p{N}_])|(?<![\\\\p{L}\\\\p{N}_])403(?![\\\\p{L}\\\\p{N}_])\", 'u'), code: \"TOOL.INVOCATION.PERMISSION_DENIED\" },\n { re: new RegExp(\"json|syntaxerror|unexpected token|decodeerror\", 'u'), code: \"PERCEPTION.PARSING.JSON_INVALID\" },\n];\n\nexport const GENERIC_FALLBACK = \"TOOL.EXECUTION.CRASHED\";\n","/**\n * Single source of truth for the SDK version on the wire.\n *\n * F-720/F-351: prior to this file, two separate `SDK_VERSION` constants\n * existed in `exporters/http.ts` (\"0.1.1\") and `runtime/loader.ts` (\"0.1.3\"),\n * while `package.json` declared \"0.4.0\". Three different versions on the\n * wire confused customer telemetry and dashboard SDK-version-cohort filters.\n *\n * This file MUST stay in lock-step with the `version` field in\n * `packages/risicare-sdk-js/package.json`. Bumping the version is a\n * two-file edit (`package.json` + this file). The `prepublishOnly` script\n * verifies the match before any npm publish.\n *\n * Kept as a plain TS constant (not a runtime read of package.json) because:\n * 1. tsup bundles to ESM AND CJS for both Node and Edge; runtime fs\n * reads of package.json break in bundled-Edge environments.\n * 2. A constant inlines at tree-shake time, so no extra bytes shipped.\n * 3. The version is read in the hot path (every export); a static value\n * avoids per-call import-meta-resolve overhead.\n */\nexport const SDK_VERSION = '0.10.0';\n","/**\n * The monthly-quota discard of the Risicare ingest gateway (metering step S-1).\n *\n * When an organisation has used its monthly event quota, the gateway answers a request with\n * HTTP 200, discards it and queues nothing. The answer is one of these shapes, and every one\n * of them also carries the header `X-Risicare-Quota: exceeded`:\n *\n * - `/v1/spans`, `/v1/spans/batch`:\n * `{\"accepted\":0,\"rejected\":N,\"reason\":\"monthly_quota_exceeded\",\"resetsAt\":\"2026-11-01T00:00:00Z\",\"retryAfterSeconds\":300}`\n * - `/v1/traces` (native):\n * `{\"tracesAccepted\":0,\"spansAccepted\":0,\"spansRejected\":N,\"reason\":\"monthly_quota_exceeded\",\"resetsAt\":\"…\",\"retryAfterSeconds\":300}`\n * - OTLP/HTTP JSON:\n * `{\"partialSuccess\":{\"rejectedSpans\":N,\"errorMessage\":\"monthly_quota_exceeded; resets_at=…; retry_after_seconds=300\"}}`\n *\n * A discard is NOT an error. It is not retried, it does not count toward the circuit breaker,\n * and the SDK does not sleep until `resetsAt`. The exporter PAUSES for `retryAfterSeconds`\n * (300 s when the answer names none). In that time the batch processor keeps ended spans in its\n * existing bounded queue (`exporter.quotaPaused()`); then it sends one real batch as a probe,\n * and drains the queue when the backend accepts. A span is counted as `quota_exceeded` in\n * `droppedSpansByReason` only when the queue overflows in the pause, or when a probe batch is\n * discarded. A customer who upgrades or buys a pack is accepted again within one pause, not at\n * next month, and nothing new is lost unless the queue overflows.\n *\n * Python twin: `exporters/_quota.py`. Both follow the contract of the ingest gateway\n * (its quota middleware and its `/v1/spans`, `/v1/traces` and OTLP routes). The JS SDK\n * has no OTLP exporter; `parseOtlpDiscard` is kept for parity and for a custom exporter.\n */\n\nimport { debug, info, warn } from '../utils/log.js';\n\nexport const QUOTA_REASON = 'monthly_quota_exceeded';\nexport const QUOTA_HEADER = 'X-Risicare-Quota';\nexport const QUOTA_HEADER_VALUE = 'exceeded';\n\n/** Used when the answer names no (usable) `retryAfterSeconds`. The gateway always sends 300. */\nexport const DEFAULT_RETRY_AFTER_S = 300;\n/**\n * A server value is believed only inside this range. The floor stops a request loop (0 or a\n * negative number). The cap stops one bad value from silencing the SDK for a month.\n */\nexport const MIN_RETRY_AFTER_S = 1;\nexport const MAX_RETRY_AFTER_S = 3600;\n/** One WARNING when the pause starts, then at most one in this window while it lasts. */\nexport const QUOTA_WARN_WINDOW_MS = 3_600_000;\n\nconst MAX_RESETS_AT_CHARS = 40;\n\n/** What a quota-discard answer says. Both fields are already checked and bounded. */\nexport interface QuotaDiscard {\n retryAfterS: number;\n resetsAt: string | null;\n}\n\n/** True for a number (or proto3 JSON string) count above 0. */\nfunction asPositiveCount(v: unknown): boolean {\n if (typeof v === 'number') return Number.isFinite(v) && v > 0;\n if (typeof v === 'string' && /^[0-9]+$/.test(v)) return Number(v) > 0;\n return false;\n}\n\n/** The pause in seconds: the server's number inside [1, 3600], else the default. */\nexport function boundedRetryAfter(value: unknown): number {\n let n: number;\n if (typeof value === 'number') n = value;\n else if (typeof value === 'string' && value.trim() !== '') n = Number(value);\n else return DEFAULT_RETRY_AFTER_S;\n if (!Number.isFinite(n)) return DEFAULT_RETRY_AFTER_S;\n return Math.min(Math.max(n, MIN_RETRY_AFTER_S), MAX_RETRY_AFTER_S);\n}\n\n/** `resetsAt` for a log line: one printable ASCII line, at most 40 characters. */\nfunction boundedResetsAt(value: unknown): string | null {\n if (typeof value !== 'string' || value.length === 0) return null;\n const cut = value.slice(0, MAX_RESETS_AT_CHARS);\n return /^[ -~]*$/.test(cut) ? cut : null;\n}\n\n/** True when the answer carries `X-Risicare-Quota: exceeded`. */\nexport function headerSaysExceeded(\n headers: { get?: (name: string) => string | null } | null | undefined,\n): boolean {\n try {\n const value = headers?.get?.(QUOTA_HEADER);\n return typeof value === 'string' && value.trim().toLowerCase() === QUOTA_HEADER_VALUE;\n } catch {\n return false;\n }\n}\n\n/**\n * A quota discard in the JSON shape of `/v1/spans` or `/v1/traces`, else `null`.\n *\n * `reason === \"monthly_quota_exceeded\"` decides. The header alone decides too, when the body is\n * something else (an old or a future shape): the header is the contract's second signal.\n */\nexport function parseJsonDiscard(\n payload: unknown,\n headers?: { get?: (name: string) => string | null } | null,\n): QuotaDiscard | null {\n const body: Record<string, unknown> =\n payload !== null && typeof payload === 'object' && !Array.isArray(payload)\n ? (payload as Record<string, unknown>)\n : {};\n // The header alone decides only when the body does not show stored spans. A well-formed ack\n // with accepted > 0 (or spansAccepted > 0) is a healthy batch, whatever a proxy added.\n const stored = (asPositiveCount(body.accepted) || asPositiveCount(body.spansAccepted)) === true;\n if (body.reason === QUOTA_REASON || (headerSaysExceeded(headers) && !stored)) {\n return {\n retryAfterS: boundedRetryAfter(body.retryAfterSeconds),\n resetsAt: boundedResetsAt(body.resetsAt),\n };\n }\n return null;\n}\n\n/**\n * A quota discard in the OTLP shape (`partialSuccess.errorMessage`), else `null`. OTLP has no\n * field for a reason, so the gateway leads the message with it:\n * `monthly_quota_exceeded; resets_at=<RFC 3339>; retry_after_seconds=300`.\n */\nexport function parseOtlpDiscard(\n payload: unknown,\n headers?: { get?: (name: string) => string | null } | null,\n): QuotaDiscard | null {\n const partial =\n payload !== null && typeof payload === 'object'\n ? (payload as { partialSuccess?: { errorMessage?: unknown } }).partialSuccess\n : undefined;\n const message = partial?.errorMessage;\n const fields: Record<string, string> = {};\n let byMessage = false;\n if (typeof message === 'string') {\n const parts = message.split(';').map((p) => p.trim());\n byMessage = parts[0] === QUOTA_REASON;\n if (byMessage) {\n for (const part of parts.slice(1)) {\n const at = part.indexOf('=');\n if (at > 0) fields[part.slice(0, at).trim()] = part.slice(at + 1).trim();\n }\n }\n }\n if (!byMessage) {\n // The header alone decides when nothing is shown as stored: no partialSuccess, or\n // rejectedSpans > 0. A partialSuccess that rejects no span is a healthy batch.\n if (!headerSaysExceeded(headers)) return null;\n if (partial !== undefined && partial !== null && typeof partial === 'object') {\n if (!asPositiveCount((partial as { rejectedSpans?: unknown }).rejectedSpans)) return null;\n }\n }\n return {\n retryAfterS: boundedRetryAfter(fields['retry_after_seconds']),\n resetsAt: boundedResetsAt(fields['resets_at']),\n };\n}\n\n/**\n * An episode ends only after this many accepted batches in a row. The gateway fails open for an\n * organisation over its quota (a slow policy read, a busy pool), so one probe is sometimes\n * accepted although the quota is still used up. One accept must not end the episode.\n */\nexport const EPISODE_END_ACCEPTS = 3;\n\n/**\n * The paused state of one exporter, and its log lines.\n *\n * - `enter()` starts (or extends) the pause. It writes one WARNING, and at most one an hour for\n * the life of the process: the window is NOT reset when an episode ends, so a gateway that\n * accepts a probe now and then cannot make a WARNING and an INFO for every probe.\n * - `paused()` is true until `retryAfterS` has passed. After that the exporter sends one real\n * batch (the probe). A probe that is discarded again calls `enter()` again.\n * - `accepted()` counts a batch that the backend took. After `EPISODE_END_ACCEPTS` in a row the\n * episode ends, with one INFO (rate-limited like the WARNING). A discard in between starts the\n * count again.\n *\n * `now` is a MONOTONIC clock in ms (`performance.now`), not the wall clock: a step of the wall\n * clock (NTP, a VM restore, sleep and resume) must not lengthen the pause or the log window past\n * their caps. A test can inject its own.\n */\nexport class QuotaPause {\n private _until = -Infinity;\n private _inEpisode = false;\n private _accepts = 0;\n private _lastWarn = -Infinity;\n private _lastInfo = -Infinity;\n /**\n * Spans dropped since the last WARNING: the full queue's (`addDrops`) and the batches that a\n * probe lost while the WARNING was held back. The WARNING carries the number.\n */\n private _drops = 0;\n\n constructor(private readonly now: () => number = () => performance.now()) {}\n\n addDrops(count: number): void {\n this._drops += count;\n }\n\n paused(): boolean {\n return this.now() < this._until;\n }\n\n remainingS(): number {\n return Math.max(0, (this._until - this.now()) / 1000);\n }\n\n enter(discard: QuotaDiscard, where: string, dropped: number): void {\n const t = this.now();\n this._until = t + discard.retryAfterS * 1000;\n this._inEpisode = true;\n this._accepts = 0;\n if (t - this._lastWarn >= QUOTA_WARN_WINDOW_MS) {\n this._lastWarn = t;\n const since = this._drops;\n this._drops = 0;\n warn(\n `Risicare: the monthly event quota is used up (monthly_quota_exceeded). ${where} ` +\n `discarded ${dropped} span(s) and will discard new ones until the quota resets ` +\n `(resetsAt=${discard.resetsAt ?? 'unknown'}) or the plan changes. The SDK pauses ` +\n `export and sends one batch again in ${Math.round(discard.retryAfterS)} s. Spans ` +\n `that end in the meantime wait in the queue. When it is full the oldest spans are ` +\n `dropped (the most recent are kept) and counted as quota_exceeded in ` +\n `droppedSpansByReason; a batch that is discarded again is dropped and counted the ` +\n `same way. This is not an error and the SDK does not retry the batch. At most one ` +\n `such WARNING an hour.` +\n (since > 0 ? ` Spans dropped for the quota since the last WARNING: ${since}.` : ''),\n );\n } else {\n this._drops += dropped;\n debug(`Quota discard again: ${dropped} span(s); paused for ${Math.round(discard.retryAfterS)} s`);\n }\n }\n\n accepted(where: string): void {\n if (!this._inEpisode) return;\n this._accepts++;\n if (this._accepts < EPISODE_END_ACCEPTS) return;\n this._inEpisode = false;\n this._accepts = 0;\n this._until = -Infinity;\n const t = this.now();\n if (t - this._lastInfo >= QUOTA_WARN_WINDOW_MS) {\n this._lastInfo = t;\n info(`Risicare: ${where} accepts spans again; the export pause for the quota has ended.`);\n } else {\n debug('Quota pause ended (INFO already written this hour)');\n }\n }\n}\n","/**\n * HTTP exporter for sending spans to the Risicare gateway.\n *\n * Uses native fetch (Node.js 18+), with:\n * - Automatic retry with exponential backoff\n * - Circuit breaker with half-open probe state\n * - Never follows a redirect; a 3xx or a 2xx without a Risicare ack is a FAILURE\n * - Gzip compression for large payloads\n * - Bearer token authentication\n */\n\nimport type { Span } from '../span.js';\nimport { ExportResult, type AckCounts, type SpanExporter } from './base.js';\nimport { debug, warn } from '../utils/log.js';\nimport { SDK_VERSION } from '../version.js';\nimport { hasCredentials, safeUrl, scrubText } from '../utils/scrub.js';\nimport { QuotaPause, parseJsonDiscard, type QuotaDiscard } from './quota.js';\n\nexport interface HttpExporterOptions {\n endpoint: string;\n apiKey?: string;\n projectId?: string;\n environment?: string;\n timeoutMs?: number;\n maxRetries?: number;\n compress?: boolean;\n}\n\n/**\n * F-SDK503-001 · A CAPACITY REFUSAL IS NOT A SICK SERVER.\n *\n * ⚠ MEASURED ON THE PUBLISHED ARTEFACT (`risicare@0.5.0` from npm, clean install). The bundle\n * contains ZERO occurrences of `accepted`, one of `\"429\"` (which is TOOL-error classification,\n * not HTTP), and its export path is `if (response.status < 300) return SUCCESS` — so 429, 503\n * and 500 are byte-identical to it and `Retry-After` is never read. The Python twin measured\n * identically: `fix-workstream/perf/a3/sdk_python_refusal_probe.py`.\n *\n * ⚠ THE BREAKER IS THE DANGEROUS HALF. Five consecutive failing exports open it for 60 s, and\n * under sustained overload five refusals arrive in well under a second — so the SDK discards\n * everything the application emits for the next minute. A `503 QUEUE_NEAR_CAPACITY` is a\n * HEALTHY gateway shedding load whose backlog drains on its own; treating it as a dead sink\n * turns a transient server-side shed into total client-side loss.\n *\n * ⚠ THIS DOES NOT MAKE ANYTHING RETRY FOREVER. `maxRetries` still bounds the attempts and the\n * batch is still dropped when they are spent. A genuine 500 still opens the breaker — that is\n * the control arm, and losing it would turn our outage into the customer's retry loop.\n */\nconst CAPACITY_REFUSAL_STATUSES: ReadonlySet<number> = new Set([429, 503]);\n\n/** Ceiling on an honoured `Retry-After`, in ms. Matches the Python twin's 10 s. */\nconst RETRY_AFTER_CEILING_MS = 10_000;\n\n/** Backoff for a refusal carrying no `Retry-After` (1 s, 2 s, 4 s) — an order of magnitude\n * above the generic 100/200/400 ms ladder, because a queue needs time to drain. */\nconst REFUSAL_BACKOFF_BASE_MS = 1_000;\n\n/** Sentinel for \"refused, but the server named no delay\". */\nconst REFUSAL_NO_HINT = -1;\n\n/**\n * ⚠ A MISROUTE IS A CONFIGURATION ERROR, NOT AN OUTAGE (0.7.0). Two answers mean that the\n * request did not reach the Risicare ingest gateway: a 3xx, and a 2xx whose body is not a\n * Risicare ack. Measured: the old default `https://app.risicare.ai` is the dashboard, and it\n * answers `POST /v1/spans` with `307 -> /login`. Through 0.6.0 `fetch` followed that\n * redirect, got the login page as an HTML 200, and `checkAck` returned SUCCESS. Now:\n * - `fetch` runs with `redirect: 'manual'`, so a 3xx comes back as the answer;\n * - the retry loop stops at the first misroute — no backoff, no second attempt;\n * - the failure COUNTS toward the circuit breaker, as a genuine failure does: 5 requests,\n * then the breaker opens, then one probe per cooldown (60 s);\n * - one warning names the endpoint and the answer, at most once per 5 minutes.\n * A capacity refusal (429/503) is different: it does not count toward the breaker.\n * Python twin: `exporters/http.py`, the block above `HttpExporter`.\n */\nconst MISROUTE_WARN_WINDOW_MS = 300_000;\n\n/**\n * An AUTH REFUSAL cannot change on a retry: the same key gets the same answer. So\n * `export()` sends it once (no retry inside that call). The batch processor still\n * re-queues the batch a bounded number of times, and the circuit breaker counts the\n * failure as before. The Python twin uses the same two statuses.\n */\nconst AUTH_REFUSAL_STATUSES: ReadonlySet<number> = new Set([401, 403]);\n\n/**\n * The WARNING for a failed export (\"spans are NOT reaching ...\") is written at the\n * first failure of an outage, and at most once in this window. Python twin:\n * `_failure_warn_window` (300 s).\n */\nconst FAILURE_WARN_WINDOW_MS = 300_000;\n\n/**\n * The state of one `export()` call: the answer of its last attempt and its cancel signal.\n * It is per call, not on the instance, so that concurrent calls (two processors that share\n * one exporter) cannot read each other's answers across an `await`.\n */\ninterface Call {\n cancel: AbortController;\n /** F-SDK503-001: a CAPACITY REFUSAL. `null` = none; `REFUSAL_NO_HINT` = no `Retry-After`. */\n refusalAfterMs: number | null;\n /** A MISROUTE: a short description of the answer. `null` = none. */\n misroute: string | null;\n /** The answer cannot change on a retry (an ack of 0 and 0). */\n noRetry: boolean;\n /** The HTTP status of the last answer. `null` = no answer. For the WARNING and the retry loop. */\n status: number | null;\n /** The error code or class when the last attempt got no answer. `null` = none. */\n error: string | null;\n /** How many requests this call started (one for each pass of the retry loop). */\n attempts: number;\n}\n\nexport class HttpExporter implements SpanExporter {\n readonly name = 'http';\n\n private readonly _endpoint: string;\n private readonly _apiKey: string | undefined;\n private readonly _projectId: string | undefined;\n private readonly _environment: string | undefined;\n private readonly _timeoutMs: number;\n private readonly _maxRetries: number;\n private readonly _compress: boolean;\n\n // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for\n // a \"30-second prod restart\" scenario: with default 1s batch flush a\n // 5-failure threshold opens the circuit ~5s into an outage and the 60s\n // cooldown gives the gateway time to come back before the half-open\n // probe fires. Lower numbers (was 3@30s) tripped on transient blips.\n private _consecutiveFailures = 0;\n private _lastMisrouteWarnAt = -Infinity;\n private _lastFailureWarnAt = -Infinity;\n /**\n * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',\n * 'unknown'). `null` after a success. A new kind in the same outage writes one more\n * WARNING, also inside the window.\n */\n private _failureKind: string | null = null;\n /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */\n private readonly _safeEndpoint: string;\n /** The endpoint holds userinfo. `fetch` refuses such a URL. */\n private readonly _endpointHasCredentials: boolean;\n /** The calls in progress, by their batch, so that `abort(spans)` stops the right one. */\n private readonly _calls = new Map<Span[], Call>();\n /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */\n private readonly _acks = new WeakMap<Span[], AckCounts>();\n /** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */\n private readonly _requests = new WeakMap<Span[], number>();\n /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */\n noteQuotaDrop(count = 1): void {\n this._quota.addDrops(count);\n }\n\n /** True while the exporter is paused for the monthly event quota (S-1). */\n quotaPaused(): boolean {\n return this._quota.paused();\n }\n\n /** The spans of each finished call that could not be serialized, by its batch. */\n private readonly _unserializable = new WeakMap<Span[], Span[]>();\n /**\n * S-1: the paused state after a monthly-quota discard (see `quota.ts`). A discard is not a\n * failure: it does not touch the circuit breaker.\n */\n private readonly _quota = new QuotaPause();\n private _circuitOpenUntil = 0;\n private readonly _circuitBreakerThreshold = 5;\n private readonly _circuitBreakerCooldownMs = 60_000;\n\n constructor(options: HttpExporterOptions) {\n this._endpoint = options.endpoint.replace(/\\/+$/, '');\n this._apiKey = options.apiKey;\n this._projectId = options.projectId;\n this._environment = options.environment;\n this._timeoutMs = options.timeoutMs ?? 5000;\n this._maxRetries = options.maxRetries ?? 3;\n this._compress = options.compress ?? false;\n this._safeEndpoint = safeUrl(this._endpoint);\n this._endpointHasCredentials = hasCredentials(this._endpoint);\n }\n\n /**\n * Network or error text for a log line: the endpoint as `safeUrl` gives it, and no\n * form of the API key (`utils/scrub.ts`).\n */\n private _scrub(text: unknown, limit = 200): string {\n let out: string;\n try {\n out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);\n } catch {\n out = typeof text;\n }\n if (this._safeEndpoint !== this._endpoint) out = out.split(this._endpoint).join(this._safeEndpoint);\n return scrubText(out, [this._apiKey], limit);\n }\n\n /** Hide the key from `util.inspect` and `console.log` of the exporter. */\n [Symbol.for('nodejs.util.inspect.custom')](): string {\n return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;\n }\n\n /** The most requests that one `export()` call sends (`maxRetries`). */\n get attemptsPerExport(): number {\n return this._maxRetries;\n }\n\n /**\n * Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears\n * it. This is the number that was sent, not the most that the call may send\n * (`attemptsPerExport`): a 401 or 403 stops the loop after one request, and an open circuit\n * breaker sends none. Returns `null` when no call is on record for `spans`. The answer is\n * kept per batch, as `takeAck` keeps the ack.\n */\n takeAttempts(spans: Span[]): number | null {\n const n = this._requests.get(spans) ?? null;\n this._requests.delete(spans);\n return n;\n }\n\n /**\n * Returns the counts of the ack that the `export()` call for `spans` received, and clears\n * them. The answer is kept per batch, not on the instance: two processors that share this\n * exporter cannot read each other's ack across an `await`.\n */\n takeAck(spans: Span[]): AckCounts | null {\n const ack = this._acks.get(spans) ?? null;\n this._acks.delete(spans);\n return ack;\n }\n\n /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */\n takeUnserializable(spans: Span[]): Span[] {\n const bad = this._unserializable.get(spans) ?? [];\n this._unserializable.delete(spans);\n return bad;\n }\n\n /**\n * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its\n * request, its retries and its backoff sleep. The batch processor calls it when\n * `shutdown()` abandons the batch, so that the call does not keep the process alive. The\n * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and\n * logs no WARNING.\n */\n abort(spans?: Span[]): void {\n if (spans !== undefined) this._calls.get(spans)?.cancel.abort();\n else for (const call of this._calls.values()) call.cancel.abort();\n }\n\n /**\n * Send one batch. The limits are the request timeout and `maxRetries`.\n *\n * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never\n * cuts a request that is already sent. A short flush budget that cut the request made a\n * healthy, slow server look like a failure: the span used a retry, the breaker moved, and\n * the server stored the same spans again. Only `abort()` stops the call, and only\n * `shutdown()` calls it.\n */\n async export(spans: Span[]): Promise<ExportResult> {\n if (spans.length === 0) return ExportResult.SUCCESS;\n const call: Call = {\n cancel: new AbortController(),\n refusalAfterMs: null,\n misroute: null,\n noRetry: false,\n status: null,\n error: null,\n attempts: 0,\n };\n this._calls.set(spans, call);\n try {\n return await this._export(spans, call);\n } finally {\n this._calls.delete(spans);\n // `fetch` refuses a URL with credentials before it sends anything, so no request left.\n this._requests.set(spans, this._endpointHasCredentials ? 0 : call.attempts);\n }\n }\n\n private async _export(spans: Span[], call: Call): Promise<ExportResult> {\n const cancelled = call.cancel.signal;\n // S-1: the backend discarded the last batch for the monthly quota, and the pause that it\n // named is not over. The batch processor does not call export() in that time (it keeps the\n // spans in its queue). This guard covers an exporter that is used on its own: send nothing,\n // not even a serialization; the batch is dropped here and counted (`quotaDropped`). SUCCESS\n // with ack 0 and 0: not a failure, so the batch processor neither re-queues the batch nor\n // counts a failed export.\n if (this._quota.paused()) {\n debug(\n `Export skipped: monthly quota pause, ${Math.round(this._quota.remainingS())} s left; ` +\n `${spans.length} span(s) dropped`,\n );\n this._acks.set(spans, { accepted: 0, rejected: 0, quotaDropped: spans.length });\n return ExportResult.SUCCESS;\n }\n // Serialize each span alone. A span that cannot be serialized (a BigInt, a circular\n // value) is not sent; the batch processor drops it as `unacknowledged`. Through 0.7.1\n // one such span made the whole batch fail every round, and the WARNING blamed the\n // endpoint.\n const parts: string[] = [];\n const bad: Span[] = [];\n let errorClass = '';\n for (const span of spans) {\n try {\n parts.push(JSON.stringify(span.toPayload()));\n } catch (e) {\n bad.push(span);\n errorClass ||= e instanceof Error ? e.name : typeof e;\n }\n }\n if (bad.length > 0) {\n this._unserializable.set(spans, bad);\n warn(\n `Risicare: ${bad.length} of ${spans.length} span(s) in this batch could not be ` +\n `serialized (${errorClass}), for example an attribute with a BigInt or a circular ` +\n `reference. They are not sent and are counted as dropped (reason=unacknowledged).`,\n );\n }\n if (parts.length === 0) return ExportResult.SUCCESS;\n const payload =\n `{\"spans\":[${parts.join(',')}]` +\n (this._projectId ? `,\"projectId\":${JSON.stringify(this._projectId)}` : '') +\n (this._environment ? `,\"environment\":${JSON.stringify(this._environment)}` : '') +\n '}';\n\n // Circuit breaker: skip if open\n const now = Date.now();\n let isHalfOpen = false;\n if (this._consecutiveFailures >= this._circuitBreakerThreshold) {\n if (now < this._circuitOpenUntil) {\n return ExportResult.FAILURE;\n }\n // Cooldown expired — probe with single request (Audit #7: half-open state)\n isHalfOpen = true;\n }\n\n // Half-open: single probe request. Normal: full retry loop.\n const maxAttempts = isHalfOpen ? 1 : this._maxRetries;\n\n // Retry loop with exponential backoff\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n // F-SDK503-001: cleared before EVERY attempt, so a refusal recorded on attempt 1 cannot\n // be read as a refusal on attempt 2 (`_sendRequest` swallows transport errors and\n // returns FAILURE without touching the field).\n call.refusalAfterMs = null;\n call.misroute = null;\n call.noRetry = false;\n call.status = null;\n call.error = null;\n call.attempts++;\n const result = await this._sendRequest(payload, parts.length, call, spans);\n // Cancelled by `abort()`: no counter, no breaker step, no WARNING.\n if (cancelled.aborted) {\n this._acks.delete(spans);\n return ExportResult.FAILURE;\n }\n\n if (result === ExportResult.SUCCESS) {\n this._consecutiveFailures = 0;\n this._failureKind = null;\n return result;\n }\n\n // A misroute, or an ack of 0 and 0, gets the same answer on every attempt. Do not\n // retry it.\n if (call.misroute !== null || call.noRetry) break;\n // A 401 or 403 cannot change on a retry either.\n if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;\n\n // Backoff. A generic failure is usually a blip worth retrying at once (100/200/400 ms);\n // a CAPACITY REFUSAL waits on the SERVER's terms when the server names them, and an\n // order of magnitude longer when it does not.\n if (attempt < maxAttempts - 1) {\n const refusal = call.refusalAfterMs;\n const delay =\n refusal === null\n ? 100 * Math.pow(2, attempt)\n : refusal === REFUSAL_NO_HINT\n ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt)\n : refusal;\n await sleep(delay, cancelled);\n if (cancelled.aborted) return ExportResult.FAILURE;\n }\n }\n\n // ⚠ F-SDK503-001 — A CAPACITY REFUSAL DOES NOT COUNT TOWARD THE BREAKER.\n //\n // ⚠ THE COUNTER IS LEFT UNTOUCHED, NOT RESET. A refusal is not evidence of health either:\n // resetting would let an alternating 500/503 sequence hold the breaker open-ended at four.\n // It neither advances nor clears.\n if (call.refusalAfterMs !== null) {\n warn(\n `Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ` +\n `${call.attempts} attempt(s). This is a healthy server shedding load, not an outage. ` +\n `This export of the batch failed; the circuit breaker does not count it. Reduce ` +\n `batch size or export rate if it persists.`\n );\n return ExportResult.FAILURE;\n }\n\n const misroute = call.misroute;\n if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {\n this._lastMisrouteWarnAt = Date.now();\n warn(\n `Risicare: spans are NOT reaching ${this._safeEndpoint}. It answered POST /v1/spans with ` +\n `${misroute}. That is not the Risicare ingest gateway, so the endpoint is probably ` +\n `wrong (for example the dashboard URL instead of the ingest gateway URL). The SDK ` +\n `does not follow redirects, and this batch is counted as NOT delivered. Set ` +\n `endpoint or RISICARE_ENDPOINT to the ingest gateway URL.`,\n );\n }\n\n // All retries failed — update circuit breaker\n this._consecutiveFailures++;\n\n // The first failure of an outage writes one WARNING, at most once in the window\n // (as in Python). A misroute and an ack of 0 and 0 have their own WARNING. A new\n // kind of failure in the same outage (for example a 401, then no answer) writes one\n // more WARNING, also inside the window. The WARNING names the last HTTP status, or\n // the error code when there was no answer. It never names the key or the response\n // body, and names the API key as a cause only for a 401 or 403.\n if (misroute === null && !call.noRetry) {\n const status = call.status;\n const kind =\n status !== null && AUTH_REFUSAL_STATUSES.has(status)\n ? 'auth'\n : status !== null\n ? 'http'\n : call.error !== null\n ? 'none'\n : 'unknown';\n let write = false;\n if (this._consecutiveFailures === 1 || this._failureKind === null) {\n if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {\n this._lastFailureWarnAt = Date.now();\n write = true;\n }\n this._failureKind = kind;\n } else if (kind !== this._failureKind) {\n this._failureKind = kind;\n write = true;\n }\n if (write) this._warnOutage(kind, status, call.error);\n }\n if (this._consecutiveFailures >= this._circuitBreakerThreshold) {\n this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;\n warn(\n `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. ` +\n `Cooldown: ${this._circuitBreakerCooldownMs / 1000}s`\n );\n }\n\n return ExportResult.FAILURE;\n }\n\n /** The outage WARNING for one kind of failure. */\n private _warnOutage(kind: string, status: number | null, error: string | null): void {\n const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;\n const tail = 'Tracing continues, but the SDK drops the spans that it cannot send.';\n if (kind === 'auth') {\n warn(\n `${where}: it answered HTTP ${status}. The endpoint refused the API key. Check the ` +\n `apiKey (or RISICARE_API_KEY) and the project it belongs to. ${tail}`,\n );\n } else if (kind === 'http') {\n warn(\n `${where}: it answered HTTP ${status}. The server did not take the batch. Check the ` +\n `endpoint and the server. ${tail} Set debug: true to see each attempt.`,\n );\n } else if (kind === 'none' && this._endpointHasCredentials) {\n warn(\n `${where}: no answer (${error}). The endpoint URL holds credentials (a user name ` +\n `or a password before the host), and fetch does not send a request to such a URL. ` +\n `Remove the credentials from the endpoint URL. ${tail}`,\n );\n } else if (kind === 'none') {\n warn(\n `${where}: no answer (${error}). The endpoint cannot be reached, or it did not ` +\n `answer in time. Check the endpoint and the network. ${tail} Set debug: true to ` +\n `see each attempt.`,\n );\n } else {\n warn(\n `${where}: the export failed. Common causes: an invalid apiKey or an unreachable ` +\n `endpoint. ${tail} Set debug: true to see each attempt.`,\n );\n }\n }\n\n /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */\n private _noteMisroute(call: Call, answer: string): ExportResult {\n // The answer holds network text (a redirect target, a Content-Type): scrubbed here,\n // once, for the debug line below and for the WARNING.\n call.misroute = this._scrub(answer, 300);\n debug(`Ingest misroute: ${call.misroute}`);\n return ExportResult.FAILURE;\n }\n\n /**\n * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.\n *\n * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an\n * HTTP-date); anything else falls back to our own backoff rather than guessing at a date\n * parse.\n */\n private _noteRefusal(call: Call, status: number, retryAfterRaw: string | null): boolean {\n if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;\n let delay = REFUSAL_NO_HINT;\n if (retryAfterRaw) {\n const secs = Number(retryAfterRaw);\n if (Number.isFinite(secs) && secs >= 0) {\n delay = Math.min(secs * 1000, RETRY_AFTER_CEILING_MS);\n }\n }\n call.refusalAfterMs = delay;\n debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);\n return true;\n }\n\n private async _sendRequest(\n body: string,\n spansSent: number,\n call: Call,\n spans: Span[],\n ): Promise<ExportResult> {\n const cancelled = call.cancel.signal;\n const timeoutMs = this._timeoutMs;\n const url = `${this._endpoint}/v1/spans`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'User-Agent': `risicare-js/${SDK_VERSION} node/${process.version}`,\n // F-SDKVER-001 parity. Python's ingest exporter has always sent\n // `X-Risicare-SDK-Version`; JS sent only a User-Agent, so the two SDKs\n // disagreed about how a client identifies itself. A parser-free header is\n // strictly easier for the gateway to consume than picking a version out of\n // a UA string.\n 'X-Risicare-SDK-Version': SDK_VERSION,\n };\n if (this._apiKey) {\n headers['Authorization'] = `Bearer ${this._apiKey}`;\n }\n\n let payload: string | Uint8Array = body;\n\n if (this._compress && payload.length > 1024) {\n try {\n const { gzipSync } = await import('node:zlib');\n payload = gzipSync(Buffer.from(payload));\n headers['Content-Encoding'] = 'gzip';\n } catch (e) {\n // Audit #16: log compression failures instead of silently swallowing\n debug(`Gzip compression failed, sending uncompressed: ${this._scrub(e)}`);\n }\n }\n\n // ⚠ ONE TIMER FOR THE WHOLE REQUEST, BODY READ INCLUDED (A4). Through 0.7.1 the timer\n // was cleared as soon as `fetch` resolved, which is when the HEADERS arrive. A server\n // that sent 200 headers and then stalled the body held `checkAck` for 301 s (the\n // runtime's own body timeout). And the `catch` path never cleared the timer, so each\n // refused attempt kept the process alive for the full timeout. The timer now covers\n // the body read and is cleared in `finally` on every path.\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n // `abort()` on the exporter stops this request too.\n const onCancel = () => controller.abort();\n cancelled.addEventListener('abort', onCancel, { once: true });\n if (cancelled.aborted) controller.abort();\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: payload,\n signal: controller.signal,\n // Never follow: a redirect is a misroute (see MISROUTE_WARN_WINDOW_MS). Node returns\n // the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.\n redirect: 'manual',\n });\n call.status = response.status;\n\n const redirected = response.type === 'opaqueredirect';\n if (redirected || (response.status >= 300 && response.status < 400)) {\n const location = response.headers?.get?.('Location');\n // The target comes from the server, and it can contain the API key.\n const target = location ? this._scrub(location, 1000) : 'no Location header';\n return this._noteMisroute(call, `HTTP ${response.status || '3xx'}, a redirect to ${target}`);\n }\n if (response.status >= 200 && response.status < 300) {\n const ack = await checkAck(response, spansSent, (t) => this._scrub(t, 1000));\n if (ack === null) {\n // The timer ended the body read: a timeout, not a misroute.\n if (controller.signal.aborted) {\n call.status = null;\n call.error = `timeout after ${timeoutMs} ms`;\n debug(`HTTP export timeout: the ack body did not arrive within ${timeoutMs} ms`);\n return ExportResult.TIMEOUT;\n }\n return this._noteMisroute(\n call,\n `HTTP ${response.status} and a body that is not a Risicare ack ` +\n `(content-type: ${response.headers?.get?.('Content-Type') || 'none'})`,\n );\n }\n if (ack.quota !== undefined) {\n this._quota.enter(ack.quota, `The ingest endpoint ${this._safeEndpoint}`, spansSent);\n } else if (ack.result === ExportResult.SUCCESS) {\n // A well-formed ack that accounts for spans and is not a quota discard: it counts\n // toward the end of a quota episode. (An ack of 0 and 0 is a FAILURE and does not.)\n this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);\n }\n if (ack.result === ExportResult.SUCCESS) this._acks.set(spans, ack.counts);\n if (ack.final) call.noRetry = true;\n return ack.result;\n } else if (response.status === 408 || response.status === 504) {\n debug(`HTTP export timeout: ${response.status}`);\n return ExportResult.TIMEOUT;\n }\n // F-SDK503-001 — still a FAILURE for the return type (the batch did not land), but the\n // loop and the breaker treat it differently.\n this._noteRefusal(call, response.status, response.headers.get('Retry-After'));\n debug(`HTTP export failed: ${response.status}`);\n return ExportResult.FAILURE;\n } catch (e) {\n // The cause code tells a refused port, a DNS failure and a reset apart (fetch\n // wraps each of them in the same TypeError). A class name only: never a message.\n const cause = e instanceof Error ? (e as Error & { cause?: { code?: unknown } }).cause : undefined;\n call.error = controller.signal.aborted\n ? `timeout after ${timeoutMs} ms`\n : typeof cause?.code === 'string'\n ? cause.code\n : e instanceof Error\n ? e.name\n : 'Error';\n debug(`HTTP export error: ${this._scrub(e)}`);\n return ExportResult.FAILURE;\n } finally {\n clearTimeout(timeoutId);\n cancelled.removeEventListener('abort', onCancel);\n }\n }\n\n shutdown(): void {\n // Native fetch doesn't need cleanup\n }\n}\n\n/** Sleep for `ms`, or less when `signal` aborts. The timer never outlives the sleep. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) return resolve();\n const done = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n signal?.addEventListener('abort', done, { once: true });\n });\n}\n\n/** An integer that is not a `boolean` (JS `typeof true === 'boolean'`, but be explicit). */\nfunction asCount(v: unknown): number | undefined {\n return typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : undefined;\n}\n\n/**\n * Decide SUCCESS/FAILURE from a 2xx response, reading the ACK body. Returns `null` when the\n * body is not a well-formed Risicare ack. The caller records that as a misroute, or as a\n * timeout when the request timer stopped the body read.\n *\n * ⚠ F-SDKACKBLIND-001. A 2xx is NOT delivery. The gateway answers\n * `StatusCode::OK` unconditionally on the ingest route (`routes/spans.rs`) and\n * reports per-span outcomes in the BODY — `{ accepted, rejected, errors[] }`,\n * camelCase, `errors` omitted when empty. Every span in a batch can be rejected\n * (bad trace-id hex, attribute-cardinality cap, clamps) and the status is still\n * 200. Before 0.5.1 this returned SUCCESS on any status below 300 and never\n * opened the body, so total loss looked like a clean export — and the retry, the\n * circuit breaker and `failedExports` all stayed silent.\n *\n * ⚠ ONLY A WELL-FORMED ACK IS SUCCESS (0.7.0). The ack is a JSON object with\n * non-negative integer `accepted` and `rejected`; other fields are ignored.\n * Through 0.6.0 any other body returned SUCCESS, to fail safe against a proxy\n * that rewrites bodies. That hid TOTAL loss: the login page that the dashboard\n * host redirects to is an HTML 200. Any other 2xx body is now a misroute: a\n * FAILURE, with no retry. The cost, stated: behind a proxy that rewrites bodies,\n * stored spans are counted as lost, and the batch processor can send them again.\n * That failure is loud.\n *\n * ⚠ A REJECTION IS AN ANSWER, NOT A FAILURE (after 0.7.1). A well-formed ack with\n * `rejected` > 0 is SUCCESS for the transport, also when `accepted` is 0: span-level\n * rejects are permanent, so a retry sends the same spans to the same refusal. Through\n * 0.7.1 an ack with `accepted` 0 was a FAILURE: the batch went to the server up to 12\n * times, the circuit breaker moved, and the last WARNING blamed the API key. A PARTIAL\n * rejection was already not a failure: retrying the whole batch would duplicate the\n * accepted spans. The result carries the counts, so that the batch processor adds\n * `accepted` to `exportedSpans` and `rejected` to `rejectedSpans`, and `flush()` then\n * returns `false`. One WARNING gives the counts and the reasons.\n *\n * ⚠ A MONTHLY-QUOTA DISCARD IS NOT A REJECTION (S-1, 0.9.1). An answer with\n * `reason === 'monthly_quota_exceeded'` (or the header `X-Risicare-Quota: exceeded`) is checked\n * first. It is SUCCESS with the ack 0 and 0 and `quotaDropped` = the spans sent, and it starts\n * the pause in `quota.ts` (`retryAfterSeconds`, 300 s by default; never `resetsAt`) with one\n * WARNING an hour. The batch processor counts the spans as `quota_exceeded`. Before 0.9.1 the\n * same answer was a full rejection: one WARNING per batch, and the SDK kept sending every batch.\n *\n * ⚠ AN ACK OF 0 AND 0 FOR A NON-EMPTY BATCH IS A FAILURE (after 0.7.1). The gateway's\n * ack accounts for every span it got (accepted + rejected = spans sent). An ack\n * that counts no span is not a delivery. Through 0.7.1 it was SUCCESS, and the\n * whole batch was counted as exported. It is not retried inside the same\n * `export()` call, because the answer cannot change. The batch processor treats it\n * as any other failure.\n *\n * Other ack counts are not trusted here either: the batch processor clamps them to\n * the batch size (see `BatchSpanProcessor`).\n *\n * A WARNING names the reasons only: the distinct `errors[].error` strings (or\n * `errorMessage` when there are none), at most 3. Each one is made one printable\n * line (control characters become spaces) and then cut at 200 characters, so a\n * server cannot write a false log line. A WARNING never names a span index or span\n * content.\n *\n * Python twin: `exporters/http.py::_check_ack`. Same rule, same thresholds.\n */\ninterface AckOutcome {\n result: ExportResult;\n counts: AckCounts;\n /** True when a retry inside the same `export()` call cannot change the answer. */\n final: boolean;\n /** S-1: set when the answer is a monthly-quota discard (`quota.ts`). Not an error. */\n quota?: QuotaDiscard;\n}\n\nconst MAX_ACK_REASONS = 3;\nconst MAX_ACK_REASON_CHARS = 200;\n\n/** Make a reason from the server one printable line: control and line-break characters become spaces. */\nfunction oneLine(text: string): string {\n // eslint-disable-next-line no-control-regex\n return text.replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g, ' ');\n}\n\n/** The distinct reasons of an ack, for a WARNING. Never a span index, never span content. */\nfunction ackReasons(body: Record<string, unknown>): string {\n const reasons: string[] = [];\n const errors = body.errors;\n if (Array.isArray(errors)) {\n for (const entry of errors) {\n const text = (entry as { error?: unknown } | null)?.error;\n if (typeof text !== 'string' || text.length === 0) continue;\n const cut = oneLine(text).slice(0, MAX_ACK_REASON_CHARS);\n if (!reasons.includes(cut)) reasons.push(cut);\n if (reasons.length === MAX_ACK_REASONS) break;\n }\n }\n if (reasons.length === 0) {\n const message =\n (typeof body.errorMessage === 'string' && body.errorMessage) ||\n (typeof body.error_message === 'string' && body.error_message) ||\n '';\n if (message) reasons.push(oneLine(message).slice(0, MAX_ACK_REASON_CHARS));\n }\n return reasons.length === 0 ? 'No reason was returned.' : `Reasons: ${reasons.join('; ')}`;\n}\n\nasync function checkAck(\n response: Response,\n spansSent: number,\n scrub: (text: string) => string,\n): Promise<AckOutcome | null> {\n let payload: unknown;\n try {\n payload = await response.json();\n } catch {\n payload = undefined; // not JSON (or the body read was aborted)\n }\n\n // S-1: a monthly-quota discard (`reason`, or the `X-Risicare-Quota` header alone). It is\n // checked BEFORE the ack shape, because the `/v1/traces` shape has no `accepted` field and a\n // header-only answer may have a body that we do not know. It is not an error, not a misroute\n // and not a rejection: no retry, no breaker step, no per-batch WARNING. The ack is 0 and 0\n // with `quotaDropped`, so that the batch processor counts the spans as `quota_exceeded`.\n const discard = parseJsonDiscard(payload, response.headers);\n if (discard !== null) {\n return {\n result: ExportResult.SUCCESS,\n counts: { accepted: 0, rejected: 0, quotaDropped: spansSent },\n final: false,\n quota: discard,\n };\n }\n\n if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {\n return null; // not a Risicare ack\n }\n\n const body = payload as Record<string, unknown>;\n const accepted = asCount(body.accepted);\n const rejected = asCount(body.rejected);\n if (accepted === undefined || rejected === undefined) return null;\n const counts: AckCounts = { accepted, rejected };\n\n if (accepted === 0 && rejected === 0 && spansSent > 0) {\n warn(\n `Risicare: the backend acknowledged 0 of ${spansSent} span(s): its ack counts no ` +\n `span as accepted or rejected. This batch is counted as NOT delivered.`,\n );\n return { result: ExportResult.FAILURE, counts, final: true };\n }\n if (rejected === 0) return { result: ExportResult.SUCCESS, counts, final: false };\n\n const total = accepted + rejected;\n if (accepted === 0) {\n warn(\n `Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} — ` +\n `this batch was NOT stored. Rejected spans are permanently lost and are NOT ` +\n `retried. ${scrub(ackReasons(body))}`,\n );\n return { result: ExportResult.SUCCESS, counts, final: false };\n }\n\n warn(\n `Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ` +\n `${accepted} were stored. Those ${rejected} are permanently lost and are NOT ` +\n `retried. ${scrub(ackReasons(body))}`,\n );\n return { result: ExportResult.SUCCESS, counts, final: false };\n}\n","/**\n * Fix Applier — Applies fixes to agent operations.\n *\n * Handles different fix types:\n * - PromptFix: Modify system/user prompts (prepend, append, replace, few_shot)\n * - ParameterFix: Adjust LLM parameters (temperature, model, etc.)\n * - RetryFix: Retry with exponential backoff + jitter\n * - FallbackFix: Switch to fallback model or default response\n * - GuardFix: Input/output validation (content filter, format check, length)\n *\n * Port of Python SDK's runtime/applier.py adapted for Node.js.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { ActiveFix, FixRuntimeConfig } from './config.js';\nimport { shouldApply, resolveFixRuntimeConfig } from './config.js';\nimport type { FixCache } from './cache.js';\nimport { debug, warn } from '../utils/log.js';\n\n/**\n * Maximum length for fix content injected into prompts.\n * Prevents unbounded prompt injection from malicious/corrupted fix configs.\n */\nconst MAX_FIX_CONTENT_LENGTH = 10_000;\n\n// ─── Apply Result ───────────────────────────────────────────────────────────\n\nexport interface ApplyResult {\n applied: boolean;\n fixId?: string;\n deploymentId?: string;\n fixType?: string;\n modifications: Record<string, unknown>;\n error?: string;\n /**\n * Guard-only: human-readable reason a guard failed (passed=false). Used\n * by GuardRejectedError to surface an actionable message to the customer.\n * `error` carries the raw exception text; `reason` carries the audit\n * category ('guard_exception', 'content_filter', 'format_check', etc.).\n */\n reason?: string;\n}\n\nfunction emptyResult(fix: ActiveFix, fixType: string): ApplyResult {\n return {\n applied: false,\n fixId: fix.fixId,\n deploymentId: fix.deploymentId,\n fixType,\n modifications: {},\n };\n}\n\n/**\n * Escapes of a backslash and an ASCII letter that Python `re` and JavaScript\n * `RegExp` (without the `u` flag) read the same way. From the two grammars:\n * - Outside a class: `\\b \\B \\d \\D \\s \\S \\w \\W` (classes and word\n * boundaries) and `\\f \\n \\r \\t \\v` (control characters).\n * - Inside a class: the same, but not `\\B` (Python refuses it; JS reads B).\n * `[\\b]` is a backspace in both.\n * - `\\xHH` and `\\uHHHH` only with exactly 2 or 4 hex digits (Python refuses\n * a short one; JS reads it as the letter x or u).\n * - `\\A` and `\\Z` outside a class are translated (see below).\n * Every other letter fails closed. JS reads it as the letter itself; Python\n * refuses it (`\\e`, `\\q`, `\\z` before 3.14, `\\k`, `\\c`, `[\\A]`, `[\\Z]`) or\n * reads it differently (`\\a`, `\\N{...}`, `\\U........`, `\\z` from 3.14).\n */\nconst SAME_ESCAPES = 'bBdDsSwWfnrtv';\nconst SAME_ESCAPES_IN_CLASS = 'bdDsSwWfnrtv';\n\nconst LEADING_INLINE_FLAGS = /^\\(\\?([ims]+)\\)/;\nconst PY_NAMED_GROUP = /^\\(\\?P<([A-Za-z_][A-Za-z0-9_]*)>/;\nconst PY_NAMED_BACKREF = /^\\(\\?P=([A-Za-z_][A-Za-z0-9_]*)\\)/;\nconst JS_NAMED_GROUP = /^\\(\\?<([A-Za-z_][A-Za-z0-9_]*)>/;\n\n/**\n * Translate a Python `re` pattern to a JavaScript RegExp source and flags.\n *\n * - A leading inline-flag group `(?i)`, `(?s)`, `(?m)` or a combination such\n * as `(?is)` becomes RegExp flags. The `i` flag is always set.\n * - `\\A` becomes `(?<![\\s\\S])` and `\\Z` becomes `(?![\\s\\S])` (start and end\n * of the input, as in Python). Without the `u` flag, JavaScript reads `\\A`\n * and `\\Z` as the letters A and Z.\n * - `(?P<name>` becomes `(?<name>`, and `(?P=name)` becomes `\\k<name>`.\n *\n * It THROWS (the caller fails closed) on a backslash and a letter outside the\n * set above, and on a group name that occurs two times (Python refuses it).\n * Other escaped characters and the rest of a character class are copied\n * unchanged. Any other Python-only form stays as it is; if it does not\n * compile, the caller fails closed.\n * @internal\n */\nexport function translatePythonPattern(pattern: string): { source: string; flags: string } {\n let flags = 'i';\n let rest = pattern;\n const m = LEADING_INLINE_FLAGS.exec(rest);\n if (m) {\n for (const f of m[1]) if (!flags.includes(f)) flags += f;\n rest = rest.slice(m[0].length);\n }\n\n const names = new Set<string>();\n const addName = (name: string): void => {\n if (names.has(name)) throw new Error('a group name occurs two times');\n names.add(name);\n };\n\n let source = '';\n let inClass = false;\n for (let i = 0; i < rest.length; i++) {\n const c = rest[i];\n if (c === '\\\\' && i + 1 < rest.length) {\n const next = rest[i + 1];\n if (/[A-Za-z]/.test(next)) {\n if (!inClass && next === 'A') {\n source += '(?<![\\\\s\\\\S])';\n i++;\n continue;\n }\n if (!inClass && next === 'Z') {\n source += '(?![\\\\s\\\\S])';\n i++;\n continue;\n }\n if (next === 'x' || next === 'u') {\n const n = next === 'x' ? 2 : 4;\n const hex = rest.slice(i + 2, i + 2 + n);\n if (!new RegExp(`^[0-9A-Fa-f]{${n}}$`).test(hex)) throw new Error('short hex escape');\n source += c + next + hex;\n i += 1 + n;\n continue;\n }\n if (!(inClass ? SAME_ESCAPES_IN_CLASS : SAME_ESCAPES).includes(next)) {\n throw new Error('an escape that Python and JavaScript read differently');\n }\n }\n source += c + next;\n i++;\n continue;\n }\n if (inClass) {\n if (c === ']') inClass = false;\n source += c;\n continue;\n }\n if (c === '[') {\n inClass = true;\n source += c;\n continue;\n }\n const tail = rest.slice(i);\n let g: RegExpExecArray | null;\n if ((g = PY_NAMED_GROUP.exec(tail)) || (g = JS_NAMED_GROUP.exec(tail))) {\n addName(g[1]);\n source += `(?<${g[1]}>`;\n i += g[0].length - 1;\n continue;\n }\n if ((g = PY_NAMED_BACKREF.exec(tail))) {\n source += `\\\\k<${g[1]}>`;\n i += g[0].length - 1;\n continue;\n }\n source += c;\n }\n return { source, flags };\n}\n\n/** (fix id, pattern index) pairs whose \"not usable\" WARNING was written. */\nconst warnedGuardPatterns = new Set<string>();\n\n/** One WARNING per (fix id, pattern index) per process. Index -1: not a list. */\nfunction warnUnusablePattern(fixId: string | undefined, index: number): void {\n const key = `${fixId ?? 'unknown'}\\u0000${index}`;\n if (warnedGuardPatterns.has(key)) return;\n warnedGuardPatterns.add(key);\n warn(\n index < 0\n ? `Guard fix ${fixId ?? 'unknown'}: blocked_patterns is not a list. The guard rejects every call.`\n : `Guard fix ${fixId ?? 'unknown'}: blocked pattern ${index} is not usable (empty, not a ` +\n 'string, longer than 500 characters, or it does not compile). The guard rejects every call.',\n );\n}\n\n// ─── Fix Applier ────────────────────────────────────────────────────────────\n\nexport class FixApplier {\n private readonly _config: Required<FixRuntimeConfig>;\n private readonly _cache: FixCache;\n private _applicationLog: ApplyResult[] = [];\n\n constructor(config: FixRuntimeConfig, cache: FixCache) {\n this._config = resolveFixRuntimeConfig(config);\n this._cache = cache;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Fix Lookup\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Get applicable fix for an error code.\n *\n * Considers A/B testing bucket if sessionId is provided. Uses\n * crypto.createHash('md5') for deterministic bucketing across restarts.\n */\n getFixForError(\n errorCode: string,\n sessionId?: string,\n ): ActiveFix | null {\n try {\n const fix = this._cache.get(errorCode);\n if (!fix) return null;\n\n // Check A/B test bucketing\n if (sessionId && this._config.abTestingEnabled) {\n const hashHex = createHash('md5')\n .update(sessionId)\n .digest('hex')\n .substring(0, 8);\n const sessionHash = parseInt(hashHex, 16);\n\n if (!shouldApply(fix, sessionHash)) {\n debug(`Fix ${fix.fixId} not applied (A/B control group)`);\n return null;\n }\n }\n\n return fix;\n } catch (e) {\n debug(`getFixForError error: ${e}`);\n return null;\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 1. Prompt Fix\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a prompt fix to messages.\n *\n * Supports 4 modification types:\n * - prepend: Add content before first system message\n * - append: Add content after first system message\n * - replace: Regex replace across all messages\n * - few_shot: Insert user/assistant example pairs after system message\n */\n applyPromptFix(\n fix: ActiveFix,\n messages: Record<string, unknown>[],\n ): { messages: Record<string, unknown>[]; result: ApplyResult } {\n try {\n const cfg = fix.config;\n const modificationType = (cfg.modification_type ?? cfg.modificationType ?? 'append') as string;\n const target = (cfg.target ?? 'system') as string;\n let content = (cfg.content ?? '') as string;\n\n // Truncate oversized content to prevent prompt injection\n if (content.length > MAX_FIX_CONTENT_LENGTH) {\n warn(\n `Fix ${fix.fixId} content truncated from ${content.length} to ${MAX_FIX_CONTENT_LENGTH} chars`,\n );\n content = content.slice(0, MAX_FIX_CONTENT_LENGTH);\n }\n\n const result = emptyResult(fix, 'prompt');\n\n if (this._config.dryRun) {\n result.modifications = {\n type: modificationType,\n target,\n contentPreview: content.slice(0, 100),\n };\n return { messages, result };\n }\n\n let modified = messages.map((m) => ({ ...m }));\n\n if (modificationType === 'prepend') {\n modified = this._prependToTarget(modified, target, content);\n result.applied = true;\n result.modifications = { type: 'prepend', target };\n } else if (modificationType === 'append') {\n modified = this._appendToTarget(modified, target, content);\n result.applied = true;\n result.modifications = { type: 'append', target };\n } else if (modificationType === 'replace') {\n const pattern = (cfg.pattern ?? '') as string;\n if (pattern) {\n modified = this._replaceInMessages(modified, pattern, content);\n result.applied = true;\n result.modifications = { type: 'replace', pattern };\n }\n } else if (modificationType === 'few_shot') {\n const examples = (cfg.examples ?? []) as Array<Record<string, string>>;\n if (examples.length > 0) {\n modified = this._addFewShotExamples(modified, examples);\n result.applied = true;\n result.modifications = { type: 'few_shot', count: examples.length };\n }\n }\n\n return { messages: modified, result };\n } catch (e) {\n debug(`applyPromptFix error: ${e}`);\n return {\n messages,\n result: {\n applied: false,\n fixId: fix.fixId,\n fixType: 'prompt',\n modifications: {},\n error: String(e),\n },\n };\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 2. Parameter Fix\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a parameter fix — merge config.parameters into params.\n */\n applyParameterFix(\n fix: ActiveFix,\n params: Record<string, unknown>,\n ): { params: Record<string, unknown>; result: ApplyResult } {\n try {\n const newParams = (fix.config.parameters ?? {}) as Record<string, unknown>;\n const result = emptyResult(fix, 'parameter');\n\n if (this._config.dryRun) {\n result.modifications = { parameters: newParams };\n return { params, result };\n }\n\n const modified = { ...params, ...newParams };\n result.applied = true;\n result.modifications = { parameters: newParams };\n\n return { params: modified, result };\n } catch (e) {\n debug(`applyParameterFix error: ${e}`);\n return {\n params,\n result: {\n applied: false,\n fixId: fix.fixId,\n fixType: 'parameter',\n modifications: {},\n error: String(e),\n },\n };\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 3. Retry Fix (async — uses setTimeout for sleeping)\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a retry fix to an async operation.\n *\n * Retries with exponential backoff + jitter using\n * `await new Promise(r => setTimeout(r, delay))`.\n */\n async applyRetryFix<T>(\n fix: ActiveFix,\n operation: () => Promise<T>,\n ): Promise<{ value: T; result: ApplyResult }> {\n const cfg = fix.config;\n const maxRetries = (cfg.max_retries ?? cfg.maxRetries ?? 3) as number;\n const initialDelayMs = (cfg.initial_delay_ms ?? cfg.initialDelayMs ?? 1000) as number;\n const maxDelayMs = (cfg.max_delay_ms ?? cfg.maxDelayMs ?? 30_000) as number;\n const exponentialBase = (cfg.exponential_base ?? cfg.exponentialBase ?? 2.0) as number;\n const jitter = (cfg.jitter ?? true) as boolean;\n const retryOn = (cfg.retry_on ?? cfg.retryOn ?? []) as string[];\n\n const result = emptyResult(fix, 'retry');\n\n if (this._config.dryRun) {\n result.modifications = { maxRetries, initialDelayMs };\n const value = await operation();\n return { value, result };\n }\n\n let lastError: Error | null = null;\n let attempts = 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n attempts++;\n try {\n const value = await operation();\n result.applied = true;\n result.modifications = { attempts };\n return { value, result };\n } catch (e) {\n lastError = e instanceof Error ? e : new Error(String(e));\n const errorType = lastError.constructor.name;\n\n // Check if we should retry this specific error type\n if (retryOn.length > 0 && !retryOn.includes(errorType)) {\n throw lastError;\n }\n\n if (attempt < maxRetries) {\n // Calculate delay with exponential backoff\n let delayMs = Math.min(\n initialDelayMs * Math.pow(exponentialBase, attempt),\n maxDelayMs,\n );\n\n // Add jitter: multiply by random factor [0.5, 1.5)\n if (jitter) {\n delayMs *= 0.5 + Math.random();\n }\n\n debug(\n `Retry ${attempt + 1}/${maxRetries} after ${Math.round(delayMs)}ms`,\n );\n await new Promise<void>((r) => setTimeout(r, delayMs));\n }\n }\n }\n\n // All retries exhausted\n result.applied = true;\n result.error = lastError?.message;\n result.modifications = { attempts, exhausted: true };\n throw lastError;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 4. Fallback Fix\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a fallback fix.\n *\n * - 'model': Replace params.model with the fallback model\n * - 'default': Set params._fallbackResponse for the caller to use\n */\n applyFallbackFix(\n fix: ActiveFix,\n params: Record<string, unknown>,\n ): { params: Record<string, unknown>; result: ApplyResult } {\n try {\n const cfg = fix.config;\n const fallbackType = (cfg.fallback_type ?? cfg.fallbackType ?? 'model') as string;\n const fallbackConfig = (cfg.fallback_config ?? cfg.fallbackConfig ?? {}) as Record<string, unknown>;\n const result = emptyResult(fix, 'fallback');\n\n if (this._config.dryRun) {\n result.modifications = { fallbackType, fallbackConfig };\n return { params, result };\n }\n\n const modified = { ...params };\n\n if (fallbackType === 'model') {\n const fallbackModel = fallbackConfig.model as string | undefined;\n if (fallbackModel) {\n modified.model = fallbackModel;\n result.applied = true;\n result.modifications = { model: fallbackModel };\n }\n } else if (fallbackType === 'default') {\n const defaultResponse = fallbackConfig.response;\n if (defaultResponse !== undefined) {\n modified._fallbackResponse = defaultResponse;\n result.applied = true;\n result.modifications = { defaultResponse: true };\n }\n }\n\n return { params: modified, result };\n } catch (e) {\n debug(`applyFallbackFix error: ${e}`);\n return {\n params,\n result: {\n applied: false,\n fixId: fix.fixId,\n fixType: 'fallback',\n modifications: {},\n error: String(e),\n },\n };\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 5. Guard Fix\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a guard fix (validation).\n *\n * Guard types:\n * - content_filter: Regex-based blocked patterns\n * - format_check: JSON.parse() validity\n * - input_validation / output_validation: min/max length\n *\n * `content_filter` searches the content for each entry of `blocked_patterns`\n * (case-insensitive, after `translatePythonPattern`). It fails CLOSED: when\n * `blocked_patterns` is not a list, or an entry is empty, is not a string,\n * is longer than 500 characters or cannot be used, the guard does not pass.\n * One WARNING names the fix id and the pattern index, once for each pair in\n * the process. The reason names the pattern index, never the pattern or the\n * content.\n *\n * Limits:\n * - The interceptor runs only on the OpenAI chat patch (input guards) and on\n * `interceptCall` / `interceptResponse`. It does not run when a framework\n * integration suppresses provider instrumentation.\n * - Each SDK uses its own regular-expression engine. These constructs can\n * give a different result in JavaScript and Python: `$` before a final\n * newline, Unicode case folding, `\\d` and `\\w` on non-ASCII text,\n * `\\N{...}` and `\\U........` (JavaScript fails closed), and a `]` first\n * in a class.\n * - A pattern has no time bound. A pattern with nested repeats can take a\n * very long time on a long input.\n */\n applyGuardFix(\n fix: ActiveFix,\n content: string,\n isInput = true,\n ): { content: string; passed: boolean; result: ApplyResult } {\n try {\n const cfg = fix.config;\n const guardType = (cfg.guard_type ?? cfg.guardType ?? 'output_validation') as string;\n const guardConfig = (cfg.guard_config ?? cfg.guardConfig ?? {}) as Record<string, unknown>;\n const result = emptyResult(fix, 'guard');\n\n // Check if guard applies to this direction\n if (isInput && guardType !== 'input_validation' && guardType !== 'content_filter') {\n return { content, passed: true, result };\n }\n if (!isInput && guardType !== 'output_validation' && guardType !== 'format_check') {\n return { content, passed: true, result };\n }\n\n if (this._config.dryRun) {\n result.modifications = { guardType };\n return { content, passed: true, result };\n }\n\n let passed = true;\n let reason: string | undefined;\n\n if (guardType === 'content_filter') {\n // A key that is present with null is \"not a list\" (as in Python); only\n // a missing key means \"no patterns\".\n const blockedPatterns: unknown = 'blocked_patterns' in guardConfig\n ? guardConfig.blocked_patterns\n : 'blockedPatterns' in guardConfig ? guardConfig.blockedPatterns : [];\n // F-029: a pattern that is not usable makes the guard FAIL CLOSED.\n // Through 0.7.1 it was skipped with a debug line and the guard passed.\n // The reason names the index only: a literal pattern IS the blocked text.\n if (!Array.isArray(blockedPatterns)) {\n warnUnusablePattern(fix.fixId, -1);\n passed = false;\n reason = 'blocked_patterns is not a list';\n } else {\n for (let index = 0; index < blockedPatterns.length; index++) {\n const regex = this._safeCompileRegex(blockedPatterns[index] as string);\n if (!regex) {\n warnUnusablePattern(fix.fixId, index);\n passed = false;\n reason = `blocked pattern ${index} is not usable`;\n break;\n }\n if (regex.test(content)) {\n passed = false;\n reason = `blocked pattern matched (pattern ${index})`;\n break;\n }\n }\n }\n } else if (guardType === 'format_check') {\n const requiredFormat = guardConfig.format as string | undefined;\n if (requiredFormat === 'json') {\n try {\n JSON.parse(content);\n } catch {\n passed = false;\n reason = 'format_check: invalid JSON';\n }\n }\n } else if (guardType === 'input_validation' || guardType === 'output_validation') {\n const minLength = (guardConfig.min_length ?? guardConfig.minLength ?? 0) as number;\n const maxLength = (guardConfig.max_length ?? guardConfig.maxLength ?? Infinity) as number;\n if (content.length < minLength || content.length > maxLength) {\n passed = false;\n reason = `${guardType}: length ${content.length} outside [${minLength}, ${maxLength}]`;\n }\n }\n\n result.applied = true;\n result.modifications = { passed, guardType };\n if (reason !== undefined) result.reason = reason;\n\n return { content, passed, result };\n } catch (e) {\n // F-731: Fail-CLOSED on guard error. An unexpected exception in a\n // safety-validation path MUST NOT silently pass content through —\n // that would defeat the entire purpose of input/output validation.\n // PR-4+5 review B2 (2026-05-25): the interceptor LAYER now reads\n // `passed:false` and throws GuardRejectedError to short-circuit the\n // LLM call. Before B2 this `passed:false` was advisory only — the\n // provider patcher consumed `modifications` / `messages` but never\n // read `passed`, so a thrown-getter attack still hit the LLM with\n // the attacker payload. The applier's job is to TELL the truth;\n // the interceptor's job is to ACT on it.\n warn(`applyGuardFix error (failing CLOSED): ${e}`);\n return {\n content,\n passed: false,\n result: {\n applied: true,\n fixId: fix.fixId,\n fixType: 'guard',\n modifications: { passed: false, reason: 'guard_exception' },\n error: String(e),\n reason: 'guard_exception',\n },\n };\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Application Log\n // ═══════════════════════════════════════════════════════════════════════════\n\n /** Log a fix application result. */\n logApplication(result: ApplyResult): void {\n this._applicationLog.push(result);\n\n // Limit log size\n if (this._applicationLog.length > 1000) {\n this._applicationLog = this._applicationLog.slice(-500);\n }\n }\n\n /** Get the application log. */\n getApplicationLog(): ApplyResult[] {\n return [...this._applicationLog];\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Private Helpers\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Safely compile a regex pattern from untrusted input.\n * Returns null if invalid or too long.\n *\n * F-029: the fix patterns are written for Python `re`. Before it compiles\n * the pattern, this function translates the Python forms that have an exact\n * JavaScript equivalent (see `translatePythonPattern`). The `i` flag is\n * always on, as in the Python applier.\n */\n private _safeCompileRegex(\n pattern: string,\n maxLength = 500,\n ): RegExp | null {\n if (typeof pattern !== 'string' || !pattern || pattern.length > maxLength) return null;\n try {\n const { source, flags } = translatePythonPattern(pattern);\n return new RegExp(source, flags);\n } catch {\n debug(`Invalid regex pattern (length=${pattern.length})`);\n return null;\n }\n }\n\n /** Prepend content to the first message matching the target role. */\n private _prependToTarget(\n messages: Record<string, unknown>[],\n target: string,\n content: string,\n ): Record<string, unknown>[] {\n return messages.map((msg) => {\n if (msg.role === target) {\n return {\n ...msg,\n content: content + '\\n\\n' + ((msg.content as string) ?? ''),\n };\n }\n return msg;\n });\n }\n\n /** Append content to the first message matching the target role. */\n private _appendToTarget(\n messages: Record<string, unknown>[],\n target: string,\n content: string,\n ): Record<string, unknown>[] {\n return messages.map((msg) => {\n if (msg.role === target) {\n return {\n ...msg,\n content: ((msg.content as string) ?? '') + '\\n\\n' + content,\n };\n }\n return msg;\n });\n }\n\n /** Regex replace across all messages. */\n private _replaceInMessages(\n messages: Record<string, unknown>[],\n pattern: string,\n replacement: string,\n ): Record<string, unknown>[] {\n const regex = this._safeCompileRegex(pattern);\n if (!regex) {\n debug('Skipping invalid regex pattern in prompt fix');\n return messages;\n }\n\n return messages.map((msg) => {\n const msgContent = msg.content;\n if (typeof msgContent === 'string') {\n return { ...msg, content: msgContent.replace(regex, replacement) };\n }\n return msg;\n });\n }\n\n /** Add few-shot examples after the first system message. */\n private _addFewShotExamples(\n messages: Record<string, unknown>[],\n examples: Array<Record<string, string>>,\n ): Record<string, unknown>[] {\n const result: Record<string, unknown>[] = [];\n let systemFound = false;\n\n for (const msg of messages) {\n result.push(msg);\n\n if (msg.role === 'system' && !systemFound) {\n systemFound = true;\n for (const example of examples) {\n if (example.user) {\n result.push({ role: 'user', content: example.user });\n }\n if (example.assistant) {\n result.push({ role: 'assistant', content: example.assistant });\n }\n }\n }\n }\n\n return result;\n }\n}\n","/**\n * Fix Loader — Fetches active fixes from the Risicare API.\n *\n * Handles:\n * - Initial loading of fixes on startup\n * - Periodic background refresh via setInterval (unref'd)\n * - Exponential backoff on failure\n * - Circuit breaker: after 3 consecutive failures, stop trying for 30s\n *\n * Uses native fetch (Node.js 18+) with AbortController for timeouts.\n *\n * Port of Python SDK's runtime/loader.py adapted for Node.js.\n */\n\nimport type { ActiveFix } from './config.js';\nimport { activeFixFromApiResponse } from './config.js';\nimport type { FixRuntimeConfig } from './config.js';\nimport { resolveFixRuntimeConfig } from './config.js';\nimport type { FixCache } from './cache.js';\nimport { debug, warn } from '../utils/log.js';\nimport { safeUrl, scrubText } from '../utils/scrub.js';\nimport { SDK_VERSION } from '../version.js';\n\nexport class FixLoader {\n private readonly _config: Required<FixRuntimeConfig>;\n private readonly _cache: FixCache;\n\n private _refreshTimer: ReturnType<typeof setInterval> | null = null;\n private _lastLoadTime: number | null = null;\n private _consecutiveFailures = 0;\n private _circuitOpenUntil = 0;\n private _onLoadCallbacks: Array<(fixes: ActiveFix[]) => void> = [];\n // The HTTP status of the last load that got a non-2xx answer; null otherwise.\n private _lastStatus: number | null = null;\n\n // Circuit breaker settings\n private static readonly CIRCUIT_BREAKER_THRESHOLD = 3;\n private static readonly CIRCUIT_BREAKER_COOLDOWN_MS = 30_000;\n\n constructor(config: FixRuntimeConfig, cache: FixCache) {\n this._config = resolveFixRuntimeConfig(config);\n this._cache = cache;\n }\n\n /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */\n private _scrub(error: unknown): string {\n let out: string;\n try {\n out = error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n } catch {\n out = typeof error;\n }\n const endpoint = (this._config.apiEndpoint ?? '').replace(/\\/+$/, '');\n if (endpoint && safeUrl(endpoint) !== endpoint) out = out.split(endpoint).join(safeUrl(endpoint));\n return scrubText(out, [this._config.apiKey]);\n }\n\n /**\n * The WARNING for a failed first load: the request URL with no userinfo, no\n * query and no key, the HTTP status or the error class, and that tracing is\n * not affected. Never the error text: it can echo the URL with its query.\n */\n private _firstLoadWarning(error: unknown): string {\n let cause: string;\n if (this._lastStatus !== null) {\n cause = `HTTP ${this._lastStatus}`;\n } else {\n cause = error instanceof Error ? error.name : typeof error;\n const code = (error as { cause?: { code?: unknown } } | null)?.cause?.code;\n if (typeof code === 'string' && /^[A-Z][A-Z0-9_]*$/.test(code)) cause += ` (${code})`;\n }\n const endpoint = (this._config.apiEndpoint ?? '').replace(/\\/+$/, '');\n return scrubText(\n `The first load of the fixes from ${safeUrl(endpoint)}/v1/fixes/active failed (${cause}). ` +\n 'No fix is applied until a later load succeeds. Tracing is not affected.',\n [this._config.apiKey],\n 500,\n );\n }\n\n /** Hide the key from `util.inspect` and `console.log` of the loader. */\n [Symbol.for('nodejs.util.inspect.custom')](): string {\n return 'FixLoader {}';\n }\n\n /** Timestamp of last successful load. */\n get lastLoadTime(): number | null {\n return this._lastLoadTime;\n }\n\n /**\n * Start the loader: perform initial load and start background refresh.\n *\n * Never throws — failures are logged and the runtime degrades gracefully.\n */\n start(): void {\n try {\n if (!this._config.enabled) {\n debug('Fix runtime disabled, skipping loader start');\n return;\n }\n\n if (!this._config.apiKey) {\n warn('No API key configured, fixes will not be loaded');\n return;\n }\n\n // Initial load (fire-and-forget — don't block startup). A failure gives\n // ONE WARNING, as the Python loader does: `initFixRuntime()` catches\n // every fault, so this is the only signal that a customer sees for a\n // 5xx, a 401 or a refused connection.\n this.loadSync().catch((e) => {\n warn(this._firstLoadWarning(e));\n });\n\n // Start background refresh\n if (this._config.autoRefresh) {\n this._startRefreshInterval();\n }\n } catch (e) {\n debug(`FixLoader.start error: ${this._scrub(e)}`);\n }\n }\n\n /** Stop the loader: clear the refresh interval. */\n stop(): void {\n try {\n if (this._refreshTimer !== null) {\n clearInterval(this._refreshTimer);\n this._refreshTimer = null;\n }\n } catch (e) {\n debug(`FixLoader.stop error: ${this._scrub(e)}`);\n }\n }\n\n /**\n * Register a callback invoked after each successful load.\n */\n onLoad(callback: (fixes: ActiveFix[]) => void): void {\n this._onLoadCallbacks.push(callback);\n }\n\n /**\n * Load fixes from the API.\n *\n * Name kept as \"loadSync\" for parity with the Python SDK, but this\n * returns a Promise in JS (there's no synchronous fetch in Node.js).\n */\n async loadSync(): Promise<ActiveFix[]> {\n if (!this._config.apiKey) {\n return [];\n }\n\n // Circuit breaker: skip if circuit is open\n const now = Date.now();\n if (\n this._consecutiveFailures >= FixLoader.CIRCUIT_BREAKER_THRESHOLD &&\n now < this._circuitOpenUntil\n ) {\n debug('Fix loader circuit breaker open — skipping load');\n return this._cache.getAll();\n }\n\n this._lastStatus = null;\n try {\n // ⚠ PATH AND HOST CHANGED 0.6.0 -> 0.7.0. This was\n // `{apiEndpoint}/api/v1/fixes/active`, and the `/api` prefix existed\n // only because a Caddy reverse proxy stripped it before forwarding to\n // FastAPI. The split has two hosts and no Caddy: the api serves\n // /v1/fixes/active directly, and the gateway host serves only /v1/spans.\n const endpoint = this._config.apiEndpoint.replace(/\\/+$/, '');\n const url = `${endpoint}/v1/fixes/active`;\n\n // AbortController for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n this._config.timeoutMs,\n );\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this._config.apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Risicare-SDK-Version': SDK_VERSION,\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n this._lastStatus = response.status;\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n const fixes = this._parseResponse(data);\n this._onLoadSuccess(fixes);\n return fixes;\n } catch (e) {\n this._onLoadFailure(e as Error);\n throw e;\n }\n }\n\n /** Get currently cached fixes without hitting the API. */\n getCached(): ActiveFix[] {\n return this._cache.getAll();\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n private _parseResponse(data: Record<string, unknown>): ActiveFix[] {\n const fixes: ActiveFix[] = [];\n const items =\n (data.fixes as unknown[]) ??\n (data.data as unknown[]) ??\n [];\n\n if (!Array.isArray(items)) return fixes;\n\n for (const item of items) {\n try {\n if (item && typeof item === 'object') {\n fixes.push(activeFixFromApiResponse(item as Record<string, unknown>));\n }\n } catch (e) {\n debug(`Failed to parse fix item: ${this._scrub(e)}`);\n }\n }\n\n return fixes;\n }\n\n private _onLoadSuccess(fixes: ActiveFix[]): void {\n this._lastLoadTime = Date.now();\n this._consecutiveFailures = 0;\n\n // Update cache\n this._cache.setAll(fixes);\n\n // Notify callbacks\n for (const callback of this._onLoadCallbacks) {\n try {\n callback(fixes);\n } catch (e) {\n debug(`Load callback error: ${this._scrub(e)}`);\n }\n }\n\n debug(`Loaded ${fixes.length} active fixes`);\n }\n\n private _onLoadFailure(error: Error): void {\n this._consecutiveFailures++;\n\n if (this._consecutiveFailures >= FixLoader.CIRCUIT_BREAKER_THRESHOLD) {\n this._circuitOpenUntil = Date.now() + FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;\n warn(\n `Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. ` +\n `Cooldown: ${FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1000}s`,\n );\n } else {\n debug(\n `Fix load failed (attempt ${this._consecutiveFailures}): ${this._scrub(error)}`,\n );\n }\n }\n\n private _startRefreshInterval(): void {\n // Use exponential backoff on the refresh interval after failures\n const tick = (): void => {\n this.loadSync().catch((e) => {\n debug(`Background fix refresh failed: ${this._scrub(e)}`);\n });\n };\n\n this._refreshTimer = setInterval(\n () => {\n // Skip if circuit breaker is open (loadSync handles this,\n // but we also avoid the async overhead)\n if (\n this._consecutiveFailures >= FixLoader.CIRCUIT_BREAKER_THRESHOLD &&\n Date.now() < this._circuitOpenUntil\n ) {\n return;\n }\n tick();\n },\n this._config.refreshIntervalMs,\n );\n\n // unref() so the interval doesn't prevent Node.js process exit\n this._refreshTimer.unref();\n\n debug('Started fix refresh interval');\n }\n}\n","/**\n * Provider patcher input validation.\n *\n * F-722/F-620: every `patchX(client)` entry point creates `new Proxy(client, ...)`.\n * Proxy constructors throw an opaque `TypeError: Cannot create proxy with a non-object\n * as target or handler` when handed `null`, `undefined`, a primitive, or `false`.\n * That error happens deep in the SDK with no actionable message — and it crashes\n * the customer's app startup the moment they pass a maybe-null client.\n *\n * We fail-fast with a clear, named TypeError so the customer sees:\n * \"patchOpenAI requires a client object, got null\"\n * instead of:\n * \"Cannot create proxy with a non-object as target or handler\"\n *\n * Rationale for throwing (not returning the input):\n * - Returning the input would silently disable instrumentation; a customer who\n * expects spans would see \"no traces\" and have to root-cause it themselves.\n * - Throwing surfaces the bug at the call-site (their `patchOpenAI(maybeNull)`).\n * - It happens at init/setup time, not in the request hot path, so no latency cost.\n */\n// PR-4+5 review NIT (2026-05-25): asserts-style narrowing. Pre-fix the\n// signature returned `void` with an `unknown` client parameter, forcing\n// every patcher's `new Proxy(client, ...)` call to keep the `unknown` /\n// loose `T` type — TS could not prove the Proxy target was non-null.\n// `asserts client is NonNullable<T>` means TS narrows the caller's\n// variable after assertClient returns, so the surrounding code is\n// type-safe without redundant runtime checks.\nexport function assertClient<T>(\n patcherName: string,\n client: T,\n): asserts client is NonNullable<T> {\n if (client === null || client === undefined) {\n throw new TypeError(\n `${patcherName} requires a client object, got ${client === null ? 'null' : 'undefined'}`,\n );\n }\n const t = typeof client;\n if (t !== 'object' && t !== 'function') {\n throw new TypeError(\n `${patcherName} requires a client object, got ${t}`,\n );\n }\n}\n","/**\n * Instructor integration via Proxy wrapping.\n *\n * Instructor wraps an LLM client's create() method to extract structured\n * data from completions using a response model (Zod schema, etc.).\n *\n * F-884: The Instructor JS client (`@instructor-ai/instructor`) exposes the\n * structured-extraction method at `client.chat.completions.create(...)` —\n * mirroring the underlying OpenAI shape — NOT at a top-level `client.create`.\n * The previous patcher hooked the top-level `create`, which Instructor JS does\n * not have, so no spans ever fired. We now walk the nested path (chat →\n * completions → create) AND keep a top-level `create` intercept for forward-\n * compatibility with API shapes that may expose both.\n *\n * Usage:\n * import { patchInstructor } from 'risicare/instructor';\n * import Instructor from '@instructor-ai/instructor';\n * const client = patchInstructor(Instructor({ client: openai, mode: 'TOOLS' }));\n * const result = await client.chat.completions.create({\n * model: 'gpt-4o-mini',\n * messages: [...],\n * response_model: { schema: MySchema, name: 'MyExtraction' },\n * });\n *\n * Does NOT suppress provider instrumentation -- Instructor delegates to the\n * underlying LLM client, which should produce its own provider span.\n */\n\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { debug } from '../utils/log.js';\nimport { assertClient } from '../utils/assert-client.js';\n\n/**\n * Build the wrapped `create` function. Shared between top-level (legacy) and\n * nested (`chat.completions.create`, the real Instructor JS shape) intercepts.\n */\nfunction makePatchedCreate(originalCreate: Function): Function {\n return function patchedCreate(this: unknown, ...args: unknown[]): unknown {\n const tracer = getTracer();\n if (!tracer?.enabled) {\n debug('Tracer not initialized — call init() before using patchInstructor()');\n return originalCreate.apply(this, args);\n }\n\n const params = (args[0] ?? {}) as Record<string, unknown>;\n // Instructor JS accepts response_model as { schema, name } or a Zod schema\n const responseModel = params.response_model ?? params.responseModel;\n\n let modelName = 'unknown';\n if (responseModel && typeof responseModel === 'function') {\n modelName = (responseModel as { name?: string }).name || 'unknown';\n } else if (responseModel && typeof responseModel === 'object') {\n const rm = responseModel as Record<string, unknown>;\n modelName =\n (rm.name as string) ??\n (rm.description as string) ??\n ((rm.schema as { name?: string } | undefined)?.name) ??\n 'schema';\n } else if (typeof responseModel === 'string') {\n modelName = responseModel;\n }\n\n return tracer.startSpan(\n {\n name: 'instructor.create',\n kind: SpanKind.LLM_CALL,\n attributes: {\n framework: 'instructor',\n 'framework.span_kind': 'extraction',\n 'instructor.response_model': modelName,\n ...(params.max_retries != null\n ? { 'instructor.max_retries': params.max_retries }\n : {}),\n ...(params.model != null\n ? { 'gen_ai.request.model': params.model }\n : {}),\n },\n },\n (_span) => {\n const result = originalCreate.apply(this, args);\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n return (result as Promise<unknown>).then((r) => r);\n }\n return result;\n },\n );\n };\n}\n\n/**\n * Wrap an Instructor client with Risicare tracing.\n *\n * Intercepts BOTH:\n * - `client.chat.completions.create` (the real Instructor JS shape)\n * - `client.create` (legacy top-level shape, if present)\n *\n * @param client - An Instructor client\n * @returns A proxied client with tracing enabled\n */\nexport function patchInstructor<T extends object>(client: T): T {\n assertClient('patchInstructor', client);\n return new Proxy(client, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n // Legacy top-level create (rare, but harmless to keep for compat).\n if (prop === 'create' && typeof value === 'function') {\n return makePatchedCreate(value.bind(target));\n }\n\n // F-884: REAL Instructor JS shape — walk into `.chat.completions.create`.\n if (prop === 'chat' && value && typeof value === 'object') {\n return new Proxy(value as object, {\n get(chatTarget, chatProp, chatReceiver) {\n const chatValue = Reflect.get(chatTarget, chatProp, chatReceiver);\n if (chatProp === 'completions' && chatValue && typeof chatValue === 'object') {\n return new Proxy(chatValue as object, {\n get(compTarget, compProp, compReceiver) {\n const compValue = Reflect.get(compTarget, compProp, compReceiver);\n if (compProp === 'create' && typeof compValue === 'function') {\n return makePatchedCreate(compValue.bind(compTarget));\n }\n return compValue;\n },\n });\n }\n return chatValue;\n },\n });\n }\n\n return value;\n },\n });\n}\n"],"mappings":";AA+BA,SAAS,cAAAA,mBAAkB;;;ACb3B,SAAS,yBAAyB;AAGlC,IAAM,IAAI;AACV,IAAM,SAAS;AAYR,SAAS,YAAqB;AACnC,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAkCO,SA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;AAGhD,UAAI,SAAS,YAAY,OAAO,UAAU,YAAY;AACpD,eAAO,kBAAkB,MAAM,KAAK,MAAM,CAAC;AAAA,MAC7C;AAGA,UAAI,SAAS,UAAU,SAAS,OAAO,UAAU,UAAU;AACzD,eAAO,IAAI,MAAM,OAAiB;AAAA,UAChC,IAAI,YAAY,UAAU,cAAc;AACtC,kBAAM,YAAY,QAAQ,IAAI,YAAY,UAAU,YAAY;AAChE,gBAAI,aAAa,iBAAiB,aAAa,OAAO,cAAc,UAAU;AAC5E,qBAAO,IAAI,MAAM,WAAqB;AAAA,gBACpC,IAAI,YAAY,UAAU,cAAc;AACtC,wBAAM,YAAY,QAAQ,IAAI,YAAY,UAAU,YAAY;AAChE,sBAAI,aAAa,YAAY,OAAO,cAAc,YAAY;AAC5D,2BAAO,kBAAkB,UAAU,KAAK,UAAU,CAAC;AAAA,kBACrD;AACA,yBAAO;AAAA,gBACT;AAAA,cACF,CAAC;AAAA,YACH;AACA,mBAAO;AAAA,UACT;AAAA,QACF,CAAC;AAAA,MACH;AAEA,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":["createHash","getTracer","getTracer"]}
1
+ {"version":3,"sources":["../../src/client.ts","../../src/exporters/retry.ts","../../src/globals.ts","../../src/utils/log.ts","../../src/utils/text.ts","../../src/utils/scrub.ts","../../src/masking.ts","../../src/exporters/batch.ts","../../src/ids.ts","../../src/noop.ts","../../src/runtime/config.ts","../../src/runtime/taxonomy.generated.ts","../../src/version.ts","../../src/exporters/quota.ts","../../src/exporters/http.ts","../../src/runtime/applier.ts","../../src/runtime/loader.ts","../../src/utils/assert-client.ts","../../src/frameworks/instructor.ts"],"sourcesContent":["/**\n * RisicareClient — singleton client managing SDK lifecycle.\n *\n * Handles initialization, shutdown, and the connection between\n * the Tracer and the export pipeline (batch processor + HTTP exporter).\n *\n * Usage:\n * import { init, shutdown } from 'risicare';\n * init({ apiKey: 'rsk-...' }); // API key determines project\n * // ... instrument code ...\n * await shutdown(); // flush remaining spans\n */\n\n// ⚠ F-SDKJSREPORTERROR-001 (W20, 2026-08-14) — STATIC, and it must stay static.\n// This was `require('node:crypto')` INSIDE `_errorFingerprint()`. esbuild\n// rewrites a bare `require` in an ESM output bundle to `__require(\"crypto\")`,\n// whose shim THROWS at call time; `reportError`'s catch-all then swallowed it\n// (`client.ts` ~:597, \"Never crash the host application\"). Net effect measured\n// on clean tarball installs of the PUBLISHED 0.4.2: reportError() delivered\n// ZERO spans under ESM and one under CJS — a silent no-op for every ESM\n// customer, which is the default for modern Node apps.\n//\n// A static import adds NO new environmental constraint: the package's main\n// entry already pulls `node:crypto` statically, because `src/index.ts` re-\n// exports `./webhooks.js`, which does `import { createHmac, timingSafeEqual }\n// from 'node:crypto'` at `webhooks.ts:53`. Same precedent, same module.\n//\n// ⚠ Do NOT \"optimise\" this back to a lazy require to keep the module edge-safe.\n// It would not achieve that (see above) and it silently re-breaks ESM. Verify\n// with `bash fix-workstream/perf/sdkjs/reporterror_module_system_probe.sh`,\n// whose CJS arm is the non-vacuity control and gates the exit code.\nimport { createHash } from 'node:crypto';\nimport { type RisicareConfig, resolveConfig, given, tracingTurnedOff } from './config.js';\nimport { Tracer, attachErrorCode } from './tracer.js';\nimport { SDK_VERSION } from './version.js';\nimport { BatchSpanProcessor, normalizeTimeoutMs } from './exporters/batch.js';\nimport { HttpExporter } from './exporters/http.js';\nimport { SpanKind, SpanStatus } from './types.js';\nimport type { SpanExporter } from './exporters/base.js';\nimport { setDebug, debug, warn } from './utils/log.js';\nimport { cutCodePoints } from './utils/text.js';\nimport { endOpenProviderSpans } from './utils/stream-proxy.js';\nimport { maskText, SCORE_COMMENT_KEY } from './masking.js';\nimport {\n getClient as getGlobalClient,\n setClient as setGlobalClient,\n getTracer as getGlobalTracer,\n setTracer as setGlobalTracer,\n} from './globals.js';\n// PR-4+5 review NIT (2026-05-25): static ESM import. Pre-fix this was a\n// CJS `require('./runtime/runtime.js')` inside the constructor, which\n// dies in TS-source consumers (vitest, ts-node ESM) because the .js\n// resolution fails — tripping the FixRuntime catch and emitting a\n// spurious \"auto-fix is OFFLINE\" warning on EVERY test that calls init().\n// Static import resolves at module-load time and works identically under\n// ESM and CJS bundles produced by tsup. The CON-194 test still exercises\n// the failure path via vi.mock() (which intercepts ES imports correctly).\nimport { initFixRuntime, shutdownFixRuntime } from './runtime/runtime.js';\nimport { safeUrl, scrubText } from './utils/scrub.js';\n\n/**\n * Signals whose default disposition is TERMINATE, with their numbers — needed\n * for the conventional `128 + signum` exit code (SIGTERM 143, SIGINT 130).\n * SDK-RELEASE-RULING.md §3.\n */\nconst TERMINATING_SIGNALS: ReadonlyArray<readonly [string, number]> = [\n ['SIGTERM', 15],\n ['SIGINT', 2],\n];\n\n/**\n * Headroom between the shutdown budget and the backstop that force-exits if\n * shutdown never resolves. It must be > 0 or the backstop races the drain; it\n * is small because it buys nothing but the difference between \"the drain\n * finished\" and \"the drain is wedged\". The drain itself is a hard wall-clock\n * bound: each round is raced against the budget, and an export that the drain\n * abandons is aborted. So 500 ms covers only timer delay and the exporters'\n * own `shutdown()` after the drain, not a round that overruns the budget.\n */\nconst BACKSTOP_MARGIN_MS = 500;\n\n/**\n * SDK-RELEASE-RULING.md §5 — the final tally survives the teardown.\n *\n * `shutdown()` clears the global client, so without this the natural pattern\n * `await shutdown(); console.log(getMetrics())` reported `droppedSpans: 0` from\n * a hardcoded literal, in the exact process that had just discarded spans.\n *\n * Written once per shutdown; cleared by `init()` so a second lifecycle never\n * serves the first's tally. Mirrors `_final_metrics` in `client.py`.\n */\nlet _finalMetrics: ReturnType<BatchSpanProcessor['getMetrics']> | undefined;\n\n/**\n * The processor of the last shutdown, kept with the tally. Root `flush()` after\n * `shutdown()` asks it: the processor holds the loss mark, so a loss that the\n * shutdown counted (`shutdown_residue` included) makes ONE `flush()` false, as\n * every other loss does. Cleared by `init()`.\n */\nlet _finalProcessor: BatchSpanProcessor | undefined;\n/** Whether the client of that last shutdown was active (see `RisicareClient._activated`). */\nlet _finalActive = false;\n\n/**\n * score() requests: the timeout, the ones not yet settled, and the number that\n * failed since `init()`. Root `flush()` waits for the pending ones inside its\n * deadline. Through 0.7.1 a score request had no timeout, followed redirects,\n * never read the status, and a failure was a debug line only.\n */\nconst SCORE_TIMEOUT_MS = 2000;\nconst _pendingScores = new Set<Promise<void>>();\nlet _failedScores = 0;\n// The failed-score count that the last finished flush() saw. A flush() answers\n// false when the count is above this mark, and then raises the mark: each\n// failed score makes one flush false, also when it failed with no flush running.\nlet _failedScoresFlushMark = 0;\n\n/**\n * The score slot rule (both SDKs; review of PR #44):\n * - at most SCORE_MAX_IN_FLIGHT score requests are in flight;\n * - a score that finds no free slot waits, with NO timer of its own: the 2000 ms\n * bound of a score starts when its request starts;\n * - at most SCORE_MAX_WAITING scores wait; one more fails at once and is counted;\n * - when a flush or shutdown bound ends, the scores that still wait are counted as\n * failed and never start a request.\n * With one connection for each score, 200 scores at once overflowed the accept\n * queue of a server (128 on macOS). With a timer that also covered the wait, 150 of\n * 200 scores to a sink that answers in 1 s were lost.\n */\nconst SCORE_MAX_IN_FLIGHT = 50;\nconst SCORE_MAX_WAITING = 1000;\nconst SCORE_CAP_REASON = `not sent: ${SCORE_MAX_WAITING} scores wait for a free slot`;\nconst SCORE_DEADLINE_REASON = 'not sent before the deadline';\nlet _scoresInFlight = 0;\ninterface ScoreWaiter {\n start: () => void;\n fail: (reason: string) => void;\n}\nconst _scoreWaiters: ScoreWaiter[] = [];\n\n/** Start waiting scores while a slot is free. */\nfunction _startWaitingScores(): void {\n while (_scoresInFlight < SCORE_MAX_IN_FLIGHT && _scoreWaiters.length > 0) {\n _scoreWaiters.shift()!.start();\n }\n}\n\n/** Count every waiting score as failed. None of them starts a request after this. */\nfunction _failWaitingScores(reason: string): void {\n for (const waiter of _scoreWaiters.splice(0)) waiter.fail(reason);\n}\n\n// One WARNING for a failed score, then at most one for each window. The\n// failures in the window are counted, and the next WARNING gives their number.\nlet _scoreWarnWindowMs = 10_000;\nconst SCORE_NAME_MAX = 200;\nlet _scoreWarnedAt: number | undefined;\nlet _scoreHeld = 0;\nlet _scoreHeldReason = '';\n\n/** @internal Tests only: change the WARNING window. */\nexport function _setScoreWarnWindowMsForTesting(ms: number): void {\n _scoreWarnWindowMs = ms;\n}\n\n/**\n * @internal Tests only. The WARNING for the positional form of `score()` is one per process, so a\n * new `init()` does not reset it.\n */\nexport function _resetPositionalScoreWarningForTesting(): void {\n _positionalScoreWarned = false;\n}\n\nfunction _resetScoreFailures(): void {\n _failedScores = 0;\n _failedScoresFlushMark = 0;\n _scoreWarnedAt = undefined;\n _scoreHeld = 0;\n _scoreHeldReason = '';\n}\n\nfunction _heldText(): string {\n return ` ${_scoreHeld} more scores failed after the last warning. The last reason: ${_scoreHeldReason}.`;\n}\n\n/**\n * Count one failed score request, and write a WARNING when the window lets it.\n * The first failure writes at once. A failure less than 10 s after the last\n * WARNING is counted and held; the next WARNING gives the number of held\n * failures and the last reason. The WARNING gives the score name (at most 200\n * characters) and the status or the error code only.\n */\nfunction _scoreFailed(name: string, reason: string): void {\n _failedScores += 1;\n const now = Date.now();\n if (_scoreWarnedAt !== undefined && now - _scoreWarnedAt < _scoreWarnWindowMs) {\n _scoreHeld += 1;\n _scoreHeldReason = reason;\n return;\n }\n let message = `score ${JSON.stringify(name.slice(0, SCORE_NAME_MAX))} failed: ${reason}.`;\n if (_scoreHeld > 0) message += _heldText();\n _scoreWarnedAt = now;\n _scoreHeld = 0;\n _scoreHeldReason = '';\n warn(message);\n}\n\n/** Write the held failures now, if there are any. Root `flush()` calls this. */\nfunction _warnHeldScores(): void {\n if (_scoreHeld === 0) return;\n const message = _heldText().trimStart();\n _scoreWarnedAt = Date.now();\n _scoreHeld = 0;\n _scoreHeldReason = '';\n warn(message);\n}\n\n/** Resolve `true` when no score request is pending, `false` at the timeout. */\nasync function _waitForPendingScores(timeoutMs: number): Promise<boolean> {\n if (_pendingScores.size === 0) return true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));\n });\n const settled = (async () => {\n while (_pendingScores.size > 0) await Promise.all([..._pendingScores]);\n return true;\n })();\n try {\n return await Promise.race([settled, expired]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n// ─── Client Class ───────────────────────────────────────────────────────────\n\nclass RisicareClient {\n readonly config: ReturnType<typeof resolveConfig>;\n readonly processor: BatchSpanProcessor;\n readonly tracer: Tracer;\n /** RULING §5. The signal path does NOT clear the global client, so without\n * this flag `getMetrics()` would keep reporting `\"running\"` over a processor\n * that has already been torn down. */\n isShutdown = false;\n /**\n * Tracing was on at `init()` or since `enable()`. A client that never was\n * (no key, or tracing off) accepted nothing, and delivered nothing: its\n * `flush()` is false. `disable()` does not clear it: spans that were accepted\n * before keep their answer.\n */\n private _activated = false;\n private _shutdownPromise: Promise<void> | undefined;\n private _shutdownHandlers: { signal: string; handler: () => void }[] = [];\n\n constructor(config?: Partial<RisicareConfig>) {\n this.config = resolveConfig(config);\n\n // API key format validation. `rsk-` is the legacy format (kept working\n // forever); `rski_` (Ingest) and `rsks_` (Secret) are the new checksummed\n // format — design: closure-plan-2026-09-25/org-project-ux/\n // 12-A2-A5-key-model-design.md §3. This is a hint only, never enforced.\n //\n // S14: `warn`, not `debug`. `setDebug()` runs at the end of this\n // constructor, so a `debug()` call here never printed for a customer. The\n // message never contains any part of the key.\n const hasKnownPrefix =\n this.config.apiKey?.startsWith('rsk-') ||\n this.config.apiKey?.startsWith('rski_') ||\n this.config.apiKey?.startsWith('rsks_');\n if (this.config.apiKey && !hasKnownPrefix) {\n warn(\n 'the API key does not look like a Risicare key: it should start with \"rsk-\", \"rski_\" or \"rsks_\". ' +\n 'Tracing continues with this key.',\n );\n }\n // NO KEY: tracing is off (`resolveConfig` forces `enabled` false), the SDK\n // sends nothing to Risicare, and `flush()` returns false. Say so once, in\n // plain words. A caller who turned tracing off on purpose (`enabled: false`,\n // `RISICARE_TRACING=false`) gets no WARNING.\n if (!this.config.apiKey && !tracingTurnedOff(config)) {\n warn(\n 'Risicare found no API key. Nothing is sent to Risicare: tracing is off, no span is ' +\n 'created, and flush() returns false. Set the RISICARE_API_KEY environment variable, ' +\n 'or pass apiKey to init().',\n );\n }\n\n // Build exporter chain.\n //\n // Only a key gives an exporter. With no key none exists, and none can: the SDK\n // writes nothing to the console either. F-SDKJSCONSOLE-001 (2026-08-15): the\n // old fallback printed `JSON.stringify(span.toPayload())`, the whole payload\n // with no redaction, to the customer's stderr. Through 0.8.0 `debug: true`\n // still printed spans with no key, and the processor counted them as exported\n // (a console exporter that is the only one decides the batch). Now no key\n // means `enabled` false: no span is created, so nothing is printed, queued,\n // dropped or counted as exported. Python prints with `debug` and no key\n // (display only, never counted); JavaScript does not print.\n let exporter: SpanExporter | undefined;\n if (this.config.apiKey) {\n exporter = new HttpExporter({\n endpoint: this.config.endpoint,\n apiKey: this.config.apiKey,\n projectId: this.config.projectId || undefined,\n environment: this.config.environment || undefined,\n compress: this.config.compress,\n retryHorizonS: this.config.retryHorizonS,\n });\n }\n\n this.processor = new BatchSpanProcessor({\n exporters: exporter ? [exporter] : [],\n batchSize: this.config.batchSize,\n batchTimeoutMs: this.config.batchTimeoutMs,\n maxQueueSize: this.config.maxQueueSize,\n debug: this.config.debug,\n // The processor is the ONE choke point every exporter is behind. Masking\n // anywhere downstream (in the HTTP exporter, say) would leave a hole for\n // any other exporter; masking upstream would put customer code on the\n // span-end call path.\n mask: this.config.mask,\n // Same argument as `mask`: the processor is the ONE choke point every\n // exporter is behind, and the only place BOTH content paths — provider\n // capture and hand-set attributes — can be gated together. The Tracer\n // still carries `traceContent` for the provider patches to read; that is\n // now a convenience, not the enforcement point.\n traceContent: this.config.traceContent,\n });\n\n this.tracer = new Tracer({\n onSpanEnd: (span) => this.processor.onSpanEnd(span),\n sampleRate: this.config.sampleRate,\n enabled: this.config.enabled,\n traceContent: this.config.traceContent,\n // F-SDKJSSVCNAME-001 — these were resolved into `config` and then read by\n // nothing. The Tracer is where Python emits them, so JS emits them there\n // too rather than inventing a second site.\n serviceName: this.config.serviceName,\n serviceVersion: this.config.serviceVersion,\n });\n\n this._activated = this.tracer.enabled;\n\n // Start the batch processor (enables span queuing and periodic flushing)\n this.processor.start();\n\n // Start FixRuntime for runtime fix application, ONLY ON OPT-IN (0.7.0;\n // see `RisicareConfig.fixRuntime`). Through 0.6.0 it started whenever an\n // apiKey was set, so the server could change the customer's agent by\n // default. When it starts, it loads active fixes from /v1/fixes/active,\n // caches with TTL and background-refreshes every 60s. The OpenAI chat patch\n // calls interceptCall() before the LLM call. It runs the input guards; with\n // no errorCode it applies no prompt, parameter or fallback fix. When it is\n // off, no runtime exists, so interceptCall() finds nothing to apply.\n //\n // CON-194: previously the catch was an empty-body silent swallow,\n // which meant a customer whose FixRuntime failed to initialize\n // (network unreachable, bad API key, server 5xx, etc.) saw ZERO\n // signal and assumed auto-fix was running. Now the catch logs\n // console.warn with an actionable message — visible at default\n // console output, including the api endpoint (fix reads go there, not to\n // the span endpoint) so customers can verify reachability. Mirrors the\n // Python SDK fix at client.py:520-528.\n //\n // ⚠ A failed LOAD of the fixes (network, 401, 5xx) does not reach this\n // catch: `initFixRuntime()` catches every fault. `FixLoader.start()` logs\n // its own WARNING for a failed first load. No known path makes\n // `initFixRuntime()` throw; the tests reach this catch through a mock.\n if (this.config.apiKey && this.config.enabled && this.config.fixRuntime) {\n try {\n initFixRuntime({\n apiEndpoint: this.config.apiEndpoint,\n apiKey: this.config.apiKey,\n enabled: true,\n debug: this.config.debug,\n });\n } catch (e) {\n // FixRuntime failure is non-fatal — tracing still works.\n // Surface a one-time console.warn so the customer knows.\n const errName = e instanceof Error ? e.name : 'Error';\n const errMsg = scrubText(e instanceof Error ? e.message : String(e), [this.config.apiKey]);\n try {\n console.warn(\n `[risicare] FixRuntime initialization failed — auto-fix is OFFLINE for this process. ` +\n `apiEndpoint=${safeUrl(this.config.apiEndpoint)} error=${errName}: ${errMsg}. ` +\n `Tracing + reporting still work; only fix application is disabled. ` +\n `Pass debug:true in init() options for the full traceback.`\n );\n } catch {\n // Defensive: if console.warn itself throws (closed stderr in\n // some sandboxed/edge environments), prefer silent over crash.\n }\n if (this.config.debug) {\n debug(\n `FixRuntime init traceback: ${scrubText(e instanceof Error && e.stack ? e.stack : String(e), [this.config.apiKey], 2000)}`,\n );\n }\n }\n }\n\n // Register shutdown hooks\n this._registerShutdownHooks();\n\n // Enable internal debug logging if configured\n setDebug(this.config.debug);\n debug(`Initialized: enabled=${this.config.enabled}, endpoint=${safeUrl(this.config.endpoint)}`);\n if (!this.config.fixRuntime) {\n debug(\n 'FixRuntime is off: nothing polls /fixes/active and no fix is applied. ' +\n 'Opt in with fixRuntime: true or RISICARE_FIX_RUNTIME=true.',\n );\n }\n }\n\n get enabled(): boolean {\n return this.tracer.enabled;\n }\n\n set enabled(value: boolean) {\n // `enable()` with no key does not turn tracing on: nothing can be sent.\n if (value && !this.config.apiKey) {\n debug('enable() ignored: no API key is configured, so tracing stays off');\n return;\n }\n this.tracer.enabled = value;\n if (value) this._activated = true;\n }\n\n // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)\n async shutdown(timeoutMs?: number): Promise<void> {\n if (this._shutdownPromise) return this._shutdownPromise;\n this._shutdownPromise = this._doShutdown(timeoutMs);\n return this._shutdownPromise;\n }\n\n private async _doShutdown(timeoutMs?: number): Promise<void> {\n debug('Shutting down...');\n\n // Audit #3: Remove process listeners to prevent leak\n for (const { signal, handler } of this._shutdownHandlers) {\n process.removeListener(signal, handler);\n }\n this._shutdownHandlers = [];\n\n // A provider span that is still open (for example a stream that nobody\n // read) ends now, so the processor exports it and it is not lost.\n endOpenProviderSpans();\n\n // Not given, or not a finite number: the `shutdownTimeoutS` of the config (W2-1c,\n // default 10 s).\n const budgetMs =\n typeof timeoutMs === 'number' && Number.isFinite(timeoutMs)\n ? timeoutMs\n : this.config.shutdownTimeoutS * 1000;\n await this.processor.shutdown(budgetMs);\n // The shutdown bound ended (also on SIGTERM and SIGINT, which reach this method):\n // a score that still waits for a slot is counted as failed and is not sent.\n _failWaitingScores(SCORE_DEADLINE_REASON);\n\n // RULING §5: snapshot HERE, in the one place every teardown path passes\n // through.\n //\n // ⚠ THIS SITE IS THE WHOLE POINT, and the obvious site is wrong. A first\n // implementation snapshotted in the module-level `shutdown()` — which the\n // SIGTERM/SIGINT handlers never call. They call THIS method, so on exactly\n // the path a container redeploy takes, `getMetrics()` would have reported\n // a live-looking reading over a torn-down processor. The Python SDK had the\n // identical trap on its own signal path; one rule, two languages, both\n // instrumented at the shared site rather than the canonical one.\n this.isShutdown = true;\n _finalMetrics = this.processor.getMetrics();\n _finalProcessor = this.processor;\n _finalActive = this._activated;\n }\n\n /**\n * Flush pending spans.\n *\n * @returns `true` only if everything queued at entry was DELIVERED.\n *\n * RULING §6: this used to discard the processor's boolean and return\n * `Promise<void>`, which resolves without throwing and reads to a caller\n * exactly like success. A discarded answer is not meaningfully better than a\n * false one — both leave the customer unable to tell *drained* from\n * *discarded*.\n */\n async flush(timeoutMs?: number): Promise<boolean> {\n // Not active means not true: no key, or tracing was off from the start.\n if (!this._activated) return false;\n return this.processor.flush(timeoutMs);\n }\n\n /**\n * SDK-RELEASE-RULING.md §3 — who decides whether the process dies.\n *\n * The contract, and it is the same one the Python SDK now satisfies:\n *\n * the SDK's signal handler never CHANGES whether the signal\n * terminates the process.\n *\n * Registering ANY listener for SIGTERM/SIGINT displaces Node's default\n * terminate. Before this, the SDK registered one unconditionally, and on the\n * success path `clearTimeout` removed the 5 s `process.exit(1)` backstop —\n * so a JS app with a live event loop drained, cleared its own only exit, and\n * **ran forever**. The orchestrator waited out the whole grace period and\n * SIGKILLed, which exits **137** and reads as OOM-killed in every dashboard.\n * Measured >25 s alive on both 0.5.0 and a clean-rebuilt 0.4.2, so this is\n * PRE-EXISTING (`F-SDKJSEXIT-001`), not a regression of the data-loss fix.\n *\n * The rule splits on one question — did the signal already have an owner?\n *\n * * **No prior listener.** Node's default was termination and OUR\n * registration displaced it. We owe the process that death.\n * * **A prior listener exists.** The application took ownership before the\n * SDK loaded. We drain and RETURN; termination was never ours to decide,\n * and forcing it would cut off the app's own graceful shutdown.\n * * **A listener that the application adds after `init()`.** Node calls ours\n * first. The question is asked when OUR listener starts, at signal time:\n * is there another listener for this signal? If there is, it owns\n * termination as well: when the drain ends we do not raise the signal\n * again, and we do not arm the fail-safe exit. Its listener runs once and\n * decides the exit, in the same way as when it was registered before\n * `init()`. Through 0.8.0 the re-raise ran it a second time, and the\n * fail-safe ended the process with code 143, 100 ms later.\n * * **A listener that the application adds DURING the drain.** There was none\n * at signal time, so the 0.8.0 rule holds: after the drain we raise the\n * signal again, and that listener runs on it, and the process ends (fail-safe\n * after 100 ms if it does not). A count taken after the drain would have\n * counted that listener, and nothing would have run or ended the process.\n *\n * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and\n * carries no termination the SDK could displace — the loop has already\n * drained and the process is leaving on its own.\n */\n private _registerShutdownHooks(): void {\n // `beforeExit` first: no ownership question, no backstop, no exit.\n const onBeforeExit = () => {\n this.shutdown().catch(() => {});\n };\n process.once('beforeExit', onBeforeExit);\n this._shutdownHandlers.push({ signal: 'beforeExit', handler: onBeforeExit });\n\n for (const [signal, signum] of TERMINATING_SIGNALS) {\n // Captured ONCE, at registration — asking later would count our own.\n const weDisplacedDefault = process.listenerCount(signal) === 0;\n\n const handler = (): void => {\n // The other listeners for this signal, counted NOW, at signal time. A\n // listener that the application adds during the drain is not one of them.\n const othersAtSignal = process.listeners(signal as NodeJS.Signals).filter((l) => l !== handler).length;\n\n // Backstop: DERIVED from the shutdown budget, never a second literal.\n // The two used to be an independent `5000` each, so a drain allowed\n // 5,000 ms raced a `process.exit(1)` firing at 5,000 ms — killing the\n // drain at its deadline, with the wrong exit code, before the residue\n // WARNING (the previous ruling's primary remedy) could print.\n const backstop = setTimeout(\n () => process.exit(128 + signum),\n this.config.shutdownTimeoutS * 1000 + BACKSTOP_MARGIN_MS,\n );\n backstop.unref();\n\n this.shutdown()\n .catch(() => {})\n .finally(() => {\n clearTimeout(backstop);\n if (!weDisplacedDefault) return; // the app owns termination\n // The application had a listener when the signal came (it added it\n // after init()): it owns termination too, so that the order of\n // registration does not change how often its listener runs, or who\n // decides the exit. (It does change which spans that listener ends are\n // delivered: see `BatchSpanProcessor.onSpanEnd`.) The\n // signal is not raised again (its listener would run a second time)\n // and the fail-safe exit is not armed (it ended the listener with code\n // 143, 100 ms later). With no listener at signal time, the 0.8.0 rule\n // below holds.\n if (othersAtSignal > 0) return;\n\n // Our listener is gone (`process.once` + `_doShutdown` removed\n // them), so re-raising reaches Node's default and terminates for\n // real — WIFSIGNALED, not merely an exit code that looks like one.\n try {\n process.kill(process.pid, signal as NodeJS.Signals);\n } catch {\n process.exit(128 + signum);\n }\n // Belt and braces: if the application added a listener DURING our\n // drain, the re-raise above went to it instead of terminating and\n // we would hang exactly as before. unref()'d, so it cannot itself\n // hold open a process that is already leaving.\n const failsafe = setTimeout(() => process.exit(128 + signum), 100);\n failsafe.unref();\n });\n };\n\n process.once(signal, handler);\n this._shutdownHandlers.push({ signal, handler });\n }\n }\n}\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/**\n * Initialize the Risicare SDK. Call once at application startup.\n *\n * @example\n * import { init } from 'risicare';\n * init({ apiKey: 'rsk-...', serviceName: 'my-agent', environment: 'production' });\n */\nexport function init(config?: Partial<RisicareConfig>): void {\n const existing = getGlobalClient() as RisicareClient | undefined;\n if (existing) {\n // F-359: warn loudly when re-init would silently discard a config change.\n // The first init wins; a second init with a different apiKey/endpoint/\n // environment is almost certainly a bug (e.g., a side-effect import that\n // calls init() in a library, then the app's own init() with real config\n // gets ignored).\n if (config) {\n const incoming = resolveConfig(config);\n const diffs: string[] = [];\n const checkedKeys: Array<keyof typeof incoming> = [\n 'apiKey',\n 'endpoint',\n 'environment',\n 'serviceName',\n 'serviceVersion',\n 'sampleRate',\n // Capture is on by default (R9): a library's early init() must not\n // make the program's traceContent: false void in silence.\n 'traceContent',\n ];\n for (const k of checkedKeys) {\n if (incoming[k] !== existing.config[k]) {\n // Don't print apiKey contents — just say \"differs\".\n const newRender = k === 'apiKey' ? '<redacted>' : JSON.stringify(incoming[k]);\n const oldRender = k === 'apiKey' ? '<redacted>' : JSON.stringify(existing.config[k]);\n diffs.push(`${String(k)}: ${oldRender} → ${newRender}`);\n }\n }\n if (diffs.length > 0) {\n console.warn(\n '[risicare] init() called twice with different config; the FIRST call wins. ' +\n 'Call shutdown() before re-initializing. Differences ignored: ' +\n diffs.join(', '),\n );\n } else {\n debug('init() called twice with identical config; no-op');\n }\n } else {\n debug('init() called twice; no-op');\n }\n return;\n }\n\n // RULING §5: a NEW lifecycle starts with no retained tally — otherwise\n // `init(); shutdown(); init()` would serve the FIRST run's losses as if they\n // belonged to the second.\n _finalMetrics = undefined;\n _finalProcessor = undefined;\n _finalActive = false;\n _resetScoreFailures();\n\n const client = new RisicareClient(config);\n setGlobalClient(client);\n setGlobalTracer(client.tracer);\n}\n\n/**\n * Gracefully shut down the SDK. Flushes pending spans before resolving.\n *\n * @param timeoutMs - The shutdown budget in milliseconds. It is a hard wall-clock\n * bound. Not given, or a value that is not a finite number (NaN, Infinity, a\n * string, null): the `shutdownTimeoutS` of `init()` (default 10 s). A negative\n * value gives 0. The largest value is 2**31 - 1.\n *\n * At the deadline, `shutdown()` stops the export in flight. Spans still queued\n * and spans in the stopped export are counted as `shutdown_residue`, with one\n * WARNING: they were not confirmed as delivered. The server may have received\n * the spans of the stopped export. Each exporter's own `shutdown()` gets only\n * the time that is left of the budget.\n *\n * Limit: the stop does not end a TLS handshake that stalls. Such a handshake\n * can keep the process alive about 10 s after `shutdown()` returns.\n */\nexport async function shutdown(timeoutMs?: number): Promise<void> {\n // Stop FixRuntime first (stops background refresh)\n try {\n shutdownFixRuntime();\n } catch {\n // FixRuntime may not be initialized\n }\n\n const client = getGlobalClient() as RisicareClient | undefined;\n if (!client) return;\n // RULING §5: the final tally is snapshotted inside `_doShutdown()`, which\n // this reaches and which the signal handlers reach directly. Do NOT add a\n // second snapshot here.\n await client.shutdown(timeoutMs);\n setGlobalClient(undefined);\n setGlobalTracer(undefined);\n}\n\n/**\n * Flush all pending spans without shutting down.\n *\n * @param timeoutMs - The budget in milliseconds (default 5000). It is a hard\n * wall-clock bound on the wait: at the deadline `flush()` resolves `false`.\n * A value that is not a finite number (NaN, Infinity, a string, null) gives\n * 5000. A negative value gives 0. The largest value is 2**31 - 1.\n * @returns `true` only if everything queued at entry was DELIVERED and no span\n * was lost since the previous `flush()` returned. A loss is reported by the next\n * `flush()`, one time. It returns `false` in these cases:\n * - the deadline expired with spans still queued or in flight;\n * - a span was discarded since the previous flush returned (F-SDKCB-001 §6);\n * - the backend rejected a span since the previous flush returned, or its ack\n * did not account for a span;\n * - a `shutdown()` left spans undelivered (`shutdown_residue`) since the previous\n * flush returned. That loss is reported once, as every other loss.\n * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at\n * SIGTERM / SIGINT, or one that nobody awaited) waits for it inside its own\n * deadline, and then answers from the final tally with the same rule. So does a\n * `flush()` after `shutdown()`. Through 0.8.0 both answered from the empty queue.\n * Not active means not true: `flush()` returns `false` before `init()`, with tracing\n * off (`enabled: false`, `RISICARE_TRACING=false`), and with no API key. Through\n * 0.8.0 it returned `true` in those cases: nothing was queued.\n *\n * `flush()` never stops a request that is already sent. At the deadline it stops\n * waiting; the export in flight continues and ends by its own rules.\n *\n * Limit: that export can keep the process alive after `flush()` returns `false`,\n * until its own timeouts end (measured on a silent server: 22 s). To end a\n * process within a bound, call `await shutdown(timeoutMs)`. It stops the export\n * in flight.\n *\n * Scores: `flush()` also waits, inside the same deadline, for each `score()`\n * request that is not complete. It returns `false` when a score is not complete\n * at the deadline, or when a score failed since the previous `flush()` returned.\n * Each failed score makes one flush `false`, as each lost span does.\n *\n * ⚠ Signature change in 0.5.0 — was `Promise<void>`. Existing callers that\n * ignore the result keep working unchanged.\n */\nexport async function flush(timeoutMs?: number): Promise<boolean> {\n // The same rule as the processor: a value that is not a finite number gives\n // the default, so the score wait and the span wait share one deadline.\n const budgetMs = normalizeTimeoutMs(timeoutMs);\n const deadline = Date.now() + budgetMs;\n // Read at entry: two flushes that overlap both report a score that failed\n // before either of them ended.\n const scoreMark = _failedScoresFlushMark;\n const client = getGlobalClient() as RisicareClient | undefined;\n let spansOk: boolean;\n if (client) {\n spansOk = await client.flush(timeoutMs);\n } else if (_finalProcessor) {\n // `shutdown()` clears the global client. The processor of that shutdown\n // answers from its final tally, with its loss mark: a loss that the shutdown\n // counted (the residue too) makes one flush false. Through 0.8.0 only the\n // residue counted, so a rejection or a `transport_refused` drop gave true.\n // `init()` clears it. A client that was never active answers false.\n spansOk = _finalActive && (await _finalProcessor.flush(timeoutMs));\n } else {\n // Never initialised: not active means not true.\n spansOk = false;\n }\n // Pending score requests run in parallel with the span flush. Wait for the\n // remaining scores inside the same deadline.\n const scoresDone = await _waitForPendingScores(deadline - Date.now());\n // The bound ended: the scores that still wait for a slot fail now, with no request.\n if (!scoresDone) _failWaitingScores(SCORE_DEADLINE_REASON);\n _warnHeldScores();\n const failedNow = _failedScores;\n if (failedNow > _failedScoresFlushMark) _failedScoresFlushMark = failedNow;\n return spansOk && scoresDone && failedNow <= scoreMark;\n}\n\n/**\n * Enable tracing at runtime.\n */\nexport function enable(): void {\n const client = getGlobalClient() as RisicareClient | undefined;\n if (client) client.enabled = true;\n}\n\n/**\n * Disable tracing at runtime. Spans will not be created or exported.\n */\nexport function disable(): void {\n const client = getGlobalClient() as RisicareClient | undefined;\n if (client) client.enabled = false;\n}\n\n/**\n * Check whether tracing is currently enabled. False before `init()`, with no API\n * key (also with `RISICARE_TRACING=true`, `enabled: true` or `enable()`), with\n * tracing off, and after `shutdown()` or the SDK's own drain at SIGTERM / SIGINT.\n */\nexport function isEnabled(): boolean {\n const client = getGlobalClient() as RisicareClient | undefined;\n // False after the SDK's own drain at SIGTERM / SIGINT too: the signal path does\n // not clear the global client, but the processor is shut down.\n return client !== undefined && !client.isShutdown && client.enabled;\n}\n\n/**\n * Get the global tracer instance. Returns undefined if not initialized.\n */\nexport function getTracer(): Tracer | undefined {\n return getGlobalTracer() as Tracer | undefined;\n}\n\n/**\n * Get the global tracer, or throw if not initialized.\n * @internal Used by decorators and providers that require an active tracer.\n */\nexport function requireTracer(): Tracer {\n const tracer = getGlobalTracer() as Tracer | undefined;\n if (!tracer) {\n throw new Error(\n 'Risicare SDK not initialized. Call init() before using tracing features.',\n );\n }\n return tracer;\n}\n\n/**\n * Check whether content tracing (prompt/completion capture) is enabled.\n */\nexport function getTraceContent(): boolean {\n const tracer = getGlobalTracer() as Tracer | undefined;\n // Fail-closed when no tracer exists (`init()` has not run, so nothing is\n // exported). NOT the user default: that is `true`, in `resolveConfig`.\n return tracer?.traceContent ?? false;\n}\n\n/**\n * Get SDK metrics: exported spans (accepted by the backend), `rejectedSpans`,\n * dropped spans and their reasons (`unacknowledged` and `quota_exceeded` included; `droppedQuota` is the latter), failed exports,\n * queue stats, and `failedScores` (`score()` requests that failed since\n * `init()`).\n *\n * `sdkState` — SDK-RELEASE-RULING.md §5 — says WHICH of three different facts\n * the numbers are, because before it all three rendered as the same zeros:\n *\n * - `\"uninitialised\"` nothing was ever queued; the zeros are the truth\n * - `\"running\"` live readings from a live processor\n * - `\"shutdown\"` the RETAINED FINAL TALLY. Not live, and says so.\n *\n * The `\"shutdown\"` case is why this field exists. `shutdown()` clears the global\n * client, so this used to answer `droppedSpans: 0` from a hardcoded literal in\n * the very process that had just discarded spans — a guess presented\n * byte-identical to an authoritative answer, which is the W1/W3 class this\n * codebase already ruled against (`cost_source`, `settled`). The remedy there\n * and here is the same: do not hide the value and do not null it, LABEL it.\n * Every field of a retained tally is still true — the queue really is empty,\n * the capacity really is the configured one, and the drop counts describe the\n * whole life of the process, `shutdown_residue` included.\n *\n * ⚠ What it still CANNOT do: report loss to anything OUTSIDE the dying process.\n * A counter in memory about to be freed has no reader, and a SIGKILL takes this\n * and the WARNING together. The WARNING remains the primary signal.\n */\nexport function getMetrics() {\n const client = getGlobalClient() as RisicareClient | undefined;\n if (client && !client.isShutdown) {\n return {\n ...client.processor.getMetrics(),\n failedScores: _failedScores,\n sdkState: 'running' as const,\n };\n }\n if (_finalMetrics) {\n // Copy: a caller mutating the object must not corrupt the one tally the\n // process has left. The tally is read from the processor of the last shutdown,\n // not from the copy that `_doShutdown` took: a span that ends after the drain\n // is counted (`shutdown_residue`) and the tally must show it.\n const tally = _finalProcessor?.getMetrics() ?? _finalMetrics;\n return {\n ...tally,\n failedScores: _failedScores,\n droppedSpansByReason: { ...tally.droppedSpansByReason },\n sdkState: 'shutdown' as const,\n };\n }\n return {\n exportedSpans: 0,\n rejectedSpans: 0,\n failedScores: _failedScores,\n droppedSpans: 0,\n droppedSpansByReason: {\n queue_full: 0,\n transport_refused: 0,\n shutdown_residue: 0,\n unacknowledged: 0,\n quota_exceeded: 0,\n retry_exhausted: 0,\n too_large: 0,\n },\n droppedQuota: 0,\n failedExports: 0,\n attempts: 0,\n oldestPendingAgeS: 0,\n queueSize: 0,\n queueCapacity: 0,\n queueUtilization: 0,\n sdkState: 'uninitialised' as const,\n };\n}\n\n// ─── reportError ──────────────────────────────────────────────────────────\n\n// Error dedup: SHA256 fingerprint → timestamp. Prevents retry loops from\n// creating N duplicate diagnoses. Matches Python SDK's 5-minute TTL.\nconst _ERROR_DEDUP_TTL_MS = 5 * 60 * 1000; // 5 minutes\nconst _ERROR_DEDUP_MAX = 1000;\nconst _recentErrors = new Map<string, number>(); // fingerprint → Date.now()\n\nfunction _errorFingerprint(err: Error): string {\n const raw = `${err.constructor?.name ?? 'Error'}:${String(err.message ?? '').slice(0, 200)}`;\n return createHash('sha256').update(raw).digest('hex').slice(0, 16);\n}\n\nfunction _isDuplicateError(fingerprint: string): boolean {\n const now = Date.now();\n // Evict expired entries\n for (const [fp, ts] of _recentErrors) {\n if (now - ts > _ERROR_DEDUP_TTL_MS) _recentErrors.delete(fp);\n else break; // Map iterates in insertion order\n }\n if (_recentErrors.has(fingerprint)) return true;\n // Enforce max size\n if (_recentErrors.size >= _ERROR_DEDUP_MAX) {\n const oldest = _recentErrors.keys().next().value;\n if (oldest !== undefined) _recentErrors.delete(oldest);\n }\n _recentErrors.set(fingerprint, now);\n return false;\n}\n\n/**\n * Report a caught exception to the error diagnosis pipeline.\n *\n * Creates an error span that triggers diagnosis and fix generation.\n * Deduplicates identical errors within a 5-minute window (SHA256 fingerprint).\n * This function never throws and is non-blocking.\n *\n * @param error - The caught exception (Error object or string)\n * @param options - Optional attributes and context overrides\n */\nexport function reportError(\n error: unknown,\n options?: { name?: string; attributes?: Record<string, unknown> },\n): void {\n try {\n const tracer = getTracer();\n if (!tracer) return;\n\n const err = error instanceof Error ? error : new Error(String(error ?? 'unknown'));\n const spanName = options?.name ?? `error:${err.constructor.name}`;\n\n // Dedup: suppress identical errors within TTL (matches Python SDK)\n const fp = _errorFingerprint(err);\n if (_isDuplicateError(fp)) {\n debug(`reportError: duplicate suppressed (fp=${fp.slice(0, 8)})`);\n return;\n }\n\n tracer.startSpan({ name: spanName, kind: SpanKind.INTERNAL }, (span) => {\n span.setStatus(SpanStatus.ERROR, err.message);\n span.setAttribute('error', true);\n span.setAttribute('error.type', err.constructor.name);\n // Limits count code points, so a cut never splits a surrogate pair.\n span.setAttribute('error.message', cutCodePoints(err.message, 2000));\n if (err.stack) span.setAttribute('error.stack', cutCodePoints(err.stack, 4000));\n span.setAttribute('risicare.reported_error', true);\n // F-R-REPORTERRCODE-001. `reportError` is the API our own docs name for\n // feeding the diagnosis pipeline, yet it attached error/type/message and\n // NO taxonomy code, while an uncaught throw through a traced frame did —\n // `tracer.ts::Tracer.startSpan` calls `attachErrorCode` on both of its\n // throw handlers. Measured on the published 0.5.2 against the lab: 4\n // uncaught spans carried TOOL.EXECUTION.CRASHED, the reportError span\n // carried none. Same shape as the Python asymmetry, same remedy — reuse\n // the ONE definition rather than re-classifying here.\n attachErrorCode(span, err);\n if (options?.attributes) {\n for (const [k, v] of Object.entries(options.attributes)) {\n span.setAttribute(k, v);\n }\n }\n });\n } catch {\n // Never crash the host application\n debug('reportError failed');\n }\n}\n\n// ─── score ─────────────────────────────────────────────────────────────────\n\n/**\n * A score that `score()` refuses at the call (a value that is not a number or is\n * outside [0, 1], an empty trace id or name). One WARNING, no request, and the\n * score counts as a failed score: `failedScores` rises by 1, so that the next\n * `flush()` is false, as for a score that the gateway refused. The WARNING of the\n * refusal is the one WARNING; `_scoreFailed` is not used, so it writes no second.\n * An SDK that is not active (never initialised, shut down by `shutdown()` or by the\n * SDK's own drain at SIGTERM / SIGINT, tracing off, no key) counts nothing: it was\n * handed no score to deliver. `isEnabled()` is false in the same cases.\n */\nfunction refuseScore(message: string): void {\n warn(message);\n const client = getGlobalClient() as RisicareClient | undefined;\n if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;\n}\n\n/** What a score's judgment is (score v2, W2-5). See \"Scores, feedback and outcomes\" in the README. */\nexport type ScoreKind = 'annotation' | 'eval' | 'feedback' | 'outcome';\n\n/**\n * Score v2 (W2-5 section 1; risicare-api `models/scores.py`, `ScoreCreate`). The bounds of the\n * server's model, checked here so that a refused score is a WARNING at the call and not a 422\n * later. The Python SDK uses the same names and values.\n */\nexport const SCORE_KINDS: readonly ScoreKind[] = ['annotation', 'eval', 'feedback', 'outcome'];\nexport const SCORE_NAME_MAX_LEN = 128;\nexport const SCORE_STRING_VALUE_MAX_LEN = 256;\nexport const SCORE_SESSION_ID_MAX_LEN = 255;\nexport const SCORE_COMMENT_MAX_LEN = 4096;\n\n/** The arguments of `score()` (score v2). One of `traceId` and `sessionId` is required. */\nexport interface ScoreOptions {\n /** Score name, 1 to 128 characters (for example \"accuracy\", \"resolved\"). */\n name: string;\n /** A finite number (any range), a string of 1 to 256 characters, or a boolean. */\n value: number | string | boolean;\n /** The trace to score (32 lowercase hex characters). */\n traceId?: string;\n /** A span within the trace (16 lowercase hex characters). Needs `traceId`. */\n spanId?: string;\n /** The session to score (1 to 255 characters), with or instead of a trace. */\n sessionId?: string;\n /** A human-readable explanation, at most 4,096 characters. */\n comment?: string;\n /** What the judgment is. Default `annotation`. */\n kind?: ScoreKind;\n}\n\nlet _positionalScoreWarned = false;\n\nfunction warnPositionalScore(): void {\n if (_positionalScoreWarned) return;\n _positionalScoreWarned = true;\n warn(\n 'Risicare: score(traceId, name, value) with positional arguments is deprecated; this call ' +\n 'still sends the score. Use score({ name, value, traceId }). This WARNING is written one time.',\n );\n}\n\n/** `value` as the wire sends it, or `undefined` after a refusal WARNING. */\nfunction scoreWireValue(value: unknown): number | string | boolean | undefined {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n if (Number.isFinite(value)) return value;\n refuseScore(`score: a number value must be finite, not ${value}. The SDK does not send this score.`);\n return undefined;\n }\n if (typeof value === 'string') {\n if (value.length >= 1 && value.length <= SCORE_STRING_VALUE_MAX_LEN) return value;\n refuseScore(\n `score: a string value must have 1 to ${SCORE_STRING_VALUE_MAX_LEN} characters, not ` +\n `${value.length}. The SDK does not send this score.`,\n );\n return undefined;\n }\n // The type only: a value's text could forge a log line, and an object's `toString()` could run.\n refuseScore(\n `score: the value must be a number, a string or a boolean, not ${value === null ? 'null' : typeof value}. ` +\n 'The SDK does not send this score.',\n );\n return undefined;\n}\n\n/**\n * Record a score on a trace, a span or a session (score v2, W2-5).\n *\n * `value` is typed, and its type decides how the Risicare server stores it: a finite number (any\n * range) is numeric, a string of 1 to 256 characters is categorical, `true` or `false` is boolean.\n * `kind` says what the judgment is: `annotation` (a person's judgment, the default), `eval` (an\n * evaluator, a model or a rule), `feedback` (the end user's reaction) or `outcome` (a result that\n * your own system knows, such as resolved, refunded or goal met; no model infers it). One of\n * `traceId` and `sessionId` is required; `spanId` needs `traceId`.\n *\n * The positional form of 0.10.0 and earlier, `score(traceId, name, value, { spanId, comment })`,\n * still sends the score, and the first such call writes one WARNING. Use the object form.\n *\n * Sends the score in the background. The root `flush()` waits for it.\n * This function never throws and does not block. At most 50 score requests\n * are in flight at once. Up to 1,000 scores wait for a free slot, with no timer;\n * the 2000 ms bound of a score starts when its request starts. A score that\n * comes when 1,000 already wait fails at once and is counted. When a `flush()`\n * or `shutdown()` bound ends, the scores that still wait fail and are not sent.\n *\n * Delivery: the request stops after 2000 ms and never follows a redirect. A\n * status of 300 or more, an error or the timeout is a failure, and it adds 1\n * to `failedScores` in `getMetrics()`. The first failure writes a WARNING with\n * the score name and the status or the error code. Later failures in the next\n * 10 s are counted, and the next WARNING gives their number. Root `flush()`\n * waits for pending scores inside its deadline, and returns `false` when a\n * score failed since the previous `flush()` returned. A score that the SDK refuses at the call\n * (a value that is not a finite number, a string of 1 to 256 characters or a boolean; an empty or\n * too long name; no trace and no session; a span with no trace; an unknown kind) writes one\n * WARNING, and the SDK does not send it. It counts as a failed score, so the next `flush()` is\n * false (not when the SDK is not active: then nothing is counted).\n *\n * If a `mask` is configured on `init()`, `comment` is passed to it under the key `score.comment`\n * before the request is built. `traceId`, `spanId`, `sessionId`, `name` and `value` are NOT\n * masked: they are identifiers and the judgment itself, which the platform joins, groups and\n * filters on.\n *\n * @example\n * score({ name: 'factual_accuracy', value: 0.92, traceId });\n * score({ name: 'resolved', value: true, sessionId: 'conv-7', kind: 'outcome' });\n */\nexport function score(options: ScoreOptions): void;\n/** @deprecated Use `score({ name, value, traceId, spanId, comment })`. */\nexport function score(traceId: string, name: string, value: number, options?: { spanId?: string; comment?: string }): void;\nexport function score(\n first: ScoreOptions | string,\n legacyName?: string,\n legacyValue?: number,\n legacyOptions?: { spanId?: string; comment?: string },\n): void {\n try {\n let opts: ScoreOptions;\n if (typeof first === 'object' && first !== null && arguments.length === 1) {\n opts = first;\n } else {\n // The positional form of 0.10.0 and earlier: score(traceId, name, value, options).\n warnPositionalScore();\n opts = {\n traceId: first as string,\n name: legacyName as string,\n value: legacyValue as number,\n spanId: legacyOptions?.spanId,\n comment: legacyOptions?.comment,\n };\n }\n const { name, traceId, spanId, sessionId } = opts;\n const kind: unknown = opts.kind ?? 'annotation';\n // WARNING, as in the Python SDK.\n if (typeof name !== 'string' || given(name) === undefined) {\n refuseScore('score: name must be a non-empty string. The SDK does not send this score.');\n return;\n }\n if (name.length > SCORE_NAME_MAX_LEN) {\n refuseScore(\n `score: name must be at most ${SCORE_NAME_MAX_LEN} characters, not ${name.length}. The SDK ` +\n 'does not send this score.',\n );\n return;\n }\n const value = scoreWireValue(opts.value);\n if (value === undefined) return;\n if (traceId !== undefined && (typeof traceId !== 'string' || given(traceId) === undefined)) {\n refuseScore('score: traceId must be a non-empty string. The SDK does not send this score.');\n return;\n }\n if (\n sessionId !== undefined &&\n (typeof sessionId !== 'string' || given(sessionId) === undefined || sessionId.length > SCORE_SESSION_ID_MAX_LEN)\n ) {\n refuseScore(\n `score: sessionId must be a non-empty string of at most ${SCORE_SESSION_ID_MAX_LEN} characters. ` +\n 'The SDK does not send this score.',\n );\n return;\n }\n if (traceId === undefined && sessionId === undefined) {\n refuseScore('score: give traceId or sessionId (or both). The SDK does not send this score.');\n return;\n }\n if (spanId && traceId === undefined) {\n refuseScore('score: spanId needs traceId. The SDK does not send this score.');\n return;\n }\n if (typeof kind !== 'string' || !(SCORE_KINDS as readonly string[]).includes(kind)) {\n refuseScore(`score: kind must be one of ${SCORE_KINDS.join(', ')}. The SDK does not send this score.`);\n return;\n }\n\n const client = getGlobalClient() as RisicareClient | undefined;\n if (!client?.enabled || !client.config.apiKey) return;\n\n // ⚠ FIELD CHANGED 0.6.0 -> 0.7.0: this read `config.endpoint`, the SPAN\n // endpoint, and then composed an API path. That worked only while one\n // Caddy-fronted host served both services. It now reads `apiEndpoint`.\n // The order that sets it is in `config.ts`, `resolveEndpoints`. The\n // default ingest host never names an api host.\n // The `/api` prefix is gone with the proxy that stripped it.\n const endpoint = client.config.apiEndpoint.replace(/\\/+$/, '');\n const url = `${endpoint}/v1/scores`;\n\n // ⚠ THE ONE NON-SPAN EGRESS THE MASK COVERS (F-SDKMASKSCORE-001).\n // This POST does not go through BatchSpanProcessor, so `applyMask` never\n // sees it — `comment` is free customer text on our wire and was uncovered\n // until this call. The ruling (why the same hook rather than a second one,\n // why `name` is deliberately NOT masked, and the caller-thread cost) is in\n // `risicare/masking.py`, \"THE NON-SPAN SURFACE\".\n //\n // Runs BEFORE `JSON.stringify`, so the unmasked value is never serialized.\n // `maskText` is the same primitive `statusMessage` uses, so a throwing mask\n // yields the same marker and the score is still sent.\n let comment = opts.comment;\n if (comment !== undefined && client.config.mask) {\n comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);\n }\n if (comment && comment.length > SCORE_COMMENT_MAX_LEN) {\n refuseScore(\n `score: comment must be at most ${SCORE_COMMENT_MAX_LEN} characters, not ${comment.length}. ` +\n 'The SDK does not send this score.',\n );\n return;\n }\n\n // The v2 body of `POST /v1/scores` (W2-5 section 1; risicare-api `ScoreCreate`): `value`\n // typed, never the v1 `score` field (the server refuses both in one body).\n const body = JSON.stringify({\n name,\n value,\n kind,\n source: 'sdk',\n ...(traceId !== undefined && { trace_id: traceId }),\n ...(sessionId !== undefined && { session_id: sessionId }),\n ...(spanId && { span_id: spanId }),\n ...(comment && { comment }),\n });\n\n // The caller does not wait. The score is pending until its request settles,\n // or until it fails while it waits for a slot; root `flush()` waits for it.\n if (_scoresInFlight >= SCORE_MAX_IN_FLIGHT && _scoreWaiters.length >= SCORE_MAX_WAITING) {\n _scoreFailed(name, SCORE_CAP_REASON);\n return;\n }\n let settle!: () => void;\n const request = new Promise<void>((resolve) => (settle = resolve));\n const send = async (): Promise<void> => {\n // The 2000 ms bound starts here, when the request starts.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), SCORE_TIMEOUT_MS);\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${client.config.apiKey}`,\n // F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI\n // server under /v1/, which `main.py::audit_logging_middleware` audits\n // into `audit_logs.user_agent`; ingest reaches the Rust gateway, which\n // discards it. This is the one client-identity visible with no gateway\n // change.\n 'User-Agent': `risicare-js/${SDK_VERSION} node/${process.version}`,\n 'X-Risicare-SDK-Version': SDK_VERSION,\n },\n body,\n // Never follow: a redirect is a misroute, not a route. Through 0.7.1\n // fetch followed a 307 and re-POSTed the score to the login page.\n redirect: 'manual',\n signal: controller.signal,\n });\n if (response.type === 'opaqueredirect' || response.status >= 300) {\n _scoreFailed(name, `HTTP ${response.status || '3xx'}`);\n }\n try {\n await response.body?.cancel();\n } catch {\n // The body is not needed.\n }\n } catch (err) {\n // The cause code tells a refused port, a DNS failure and a reset apart\n // (fetch wraps each of them in the same TypeError).\n const cause = err instanceof Error ? (err as Error & { cause?: { code?: unknown } }).cause : undefined;\n const code = typeof cause?.code === 'string' ? cause.code : undefined;\n const reason = controller.signal.aborted\n ? `no answer within ${SCORE_TIMEOUT_MS} ms`\n : code ?? (err instanceof Error ? err.name : 'Error');\n _scoreFailed(name, reason);\n } finally {\n clearTimeout(timer);\n _scoresInFlight--;\n settle();\n _startWaitingScores();\n }\n };\n const start = (): void => {\n _scoresInFlight++;\n void send();\n };\n if (_scoresInFlight < SCORE_MAX_IN_FLIGHT) {\n start();\n } else {\n _scoreWaiters.push({\n start,\n fail: (reason) => {\n _scoreFailed(name, reason);\n settle();\n },\n });\n }\n _pendingScores.add(request);\n void request.finally(() => _pendingScores.delete(request));\n } catch {\n // Never crash the host application\n debug('score failed');\n }\n}\n","/**\n * The export retry policy (W2-1c). The Python twin is `risicare/exporters/_retry.py`.\n *\n * The two SDKs use the same constant names, the same values and the same rules. A change\n * here is a change in both files.\n *\n * The policy, for one batch:\n *\n * - An answer in `RETRY_STATUSES`, a connection error and a timeout are retried.\n * - 413 (`TOO_LARGE_STATUS`): the batch is split in two one time and both halves are sent.\n * A half that gets 413 again is dropped with the reason `too_large`.\n * - Every other answer is sent one time (400, 401, 403, 404 and 422 are the usual ones). A\n * redirect, a 2xx that is not a Risicare ack and an ack of 0 and 0 are sent one time too.\n * - The wait before retry `n` (0 for the first retry) is\n * `fraction * min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** n)` with a random\n * `fraction` in [0, 1) (full jitter). A `Retry-After` header (seconds or an HTTP date)\n * replaces that wait when it names a wait of more than 0 s; `Retry-After: 0` (or a date that\n * is not in the future) keeps the computed wait, so that a server that answers so every time\n * does not get a tight loop until the horizon.\n * - The retry horizon (`retryHorizonS`, default `DEFAULT_RETRY_HORIZON_S`) starts at the\n * first attempt of the batch. No wait goes past it. When it is used up, the batch is\n * dropped with the reason `retry_exhausted`. A gateway outage that is longer than the\n * horizon therefore loses spans.\n */\n\n/** Answers that a later attempt can change. */\nexport const RETRY_STATUSES: ReadonlySet<number> = new Set([408, 429, 500, 502, 503, 504]);\n\n/** The body is too large for the gateway: split the batch in two, one time. */\nexport const TOO_LARGE_STATUS = 413;\n\n/** Full-jitter exponential backoff. */\nexport const RETRY_BACKOFF_BASE_S = 1;\nexport const RETRY_BACKOFF_CAP_S = 30;\n\n/** How long one batch is retried, from its first attempt. */\nexport const DEFAULT_RETRY_HORIZON_S = 300;\n\n/** The default budget of `shutdown()`, and of the SDK's own teardown at exit and at a signal. */\nexport const DEFAULT_SHUTDOWN_TIMEOUT_S = 10;\n\n/**\n * The outage WARNING comes when a batch has failed this many attempts in a row. A blip that\n * the first or second retry repairs gives no WARNING.\n */\nexport const RETRY_WARN_AFTER_ATTEMPTS = 3;\n\n/** The random fraction of full jitter. A test replaces `fraction` to get a fixed schedule. */\nexport const jitter: { fraction: () => number } = { fraction: () => Math.random() };\n\n/** The wait before retry `retryNumber` (0 for the first retry), in seconds. */\nexport function backoffDelayS(retryNumber: number, fraction: number): number {\n const exponent = Math.min(Math.max(retryNumber, 0), 62);\n const ceiling = Math.min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** exponent);\n return Math.min(Math.max(fraction, 0), 1) * ceiling;\n}\n\nconst SECONDS = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n/**\n * The wait that a `Retry-After` header asks for, in seconds, or `null`.\n *\n * Two forms (RFC 9110, section 10.2.3): a number of seconds, and an HTTP date. A date in the\n * past gives 0. A value that is neither form gives `null`, and the computed backoff applies.\n * `nowMs` is the wall-clock time (`Date.now()`), for a test.\n */\nexport function parseRetryAfterS(\n value: string | null | undefined,\n nowMs: number = Date.now(),\n): number | null {\n if (value === null || value === undefined) return null;\n const text = String(value).trim();\n if (text === '') return null;\n if (SECONDS.test(text)) {\n const seconds = Number(text);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;\n }\n // An HTTP date always names a month and a day. `Date.parse` takes much more than dates\n // (a bare number is a year), so a value with no letter is not tried.\n if (!/[A-Za-z]/.test(text)) return null;\n const when = Date.parse(text);\n if (!Number.isFinite(when)) return null;\n return Math.max(0, (when - nowMs) / 1000);\n}\n","/**\n * Shared state via globalThis — ensures all entry point bundles share\n * the same singleton instances.\n *\n * Problem: tsup with `splitting: false` gives each entry point (index,\n * openai, anthropic, vercel-ai) its own copy of module-level variables.\n * This means `init()` from 'risicare' sets a tracer that 'risicare/openai'\n * can't see — breaking all provider instrumentation silently.\n *\n * Solution: Store all mutable singletons on globalThis with a namespaced\n * prefix. Every bundle reads/writes the same global slots.\n *\n * This pattern is used by React, OpenTelemetry, and other SDKs that must\n * share state across independently bundled entry points.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst G = globalThis as any;\nconst PREFIX = '__risicare_';\n\n// ─── Client & Tracer ────────────────────────────────────────────────────────\n\nexport function getClient(): unknown {\n return G[PREFIX + 'client'];\n}\n\nexport function setClient(client: unknown): void {\n G[PREFIX + 'client'] = client;\n}\n\nexport function getTracer(): unknown {\n return G[PREFIX + 'tracer'];\n}\n\nexport function setTracer(tracer: unknown): void {\n G[PREFIX + 'tracer'] = tracer;\n}\n\n// ─── Context Storage ────────────────────────────────────────────────────────\n\nexport function getContextStorage(): AsyncLocalStorage<unknown> {\n if (!G[PREFIX + 'ctx']) {\n G[PREFIX + 'ctx'] = new AsyncLocalStorage();\n }\n return G[PREFIX + 'ctx'];\n}\n\n// ─── Span Registry ──────────────────────────────────────────────────────────\n\nexport function getRegistry(): Map<string, unknown> {\n if (!G[PREFIX + 'registry']) {\n G[PREFIX + 'registry'] = new Map();\n }\n return G[PREFIX + 'registry'];\n}\n\nexport function getOpCount(): number {\n return G[PREFIX + 'opcount'] ?? 0;\n}\n\nexport function setOpCount(n: number): void {\n G[PREFIX + 'opcount'] = n;\n}\n\n// ─── Debug Flag ─────────────────────────────────────────────────────────────\n\nexport function getDebug(): boolean {\n return G[PREFIX + 'debug'] ?? false;\n}\n\nexport function setDebugFlag(enabled: boolean): void {\n G[PREFIX + 'debug'] = enabled;\n}\n\n// ─── Fix Runtime ────────────────────────────────────────────────────────\n\nexport function getGlobalFixRuntime(): unknown {\n return G[PREFIX + 'fix_runtime'];\n}\n\nexport function setGlobalFixRuntime(runtime: unknown): void {\n G[PREFIX + 'fix_runtime'] = runtime;\n}\n\n// ─── Open provider spans (utils/stream-proxy.ts) ────────────────────────────\n\n/** An observed provider span that is not ended yet. */\nexport interface OpenProviderSpan {\n end(reason: 'shutdown'): void;\n release(): void;\n}\n\nexport interface ProviderSpanState {\n /** The shape of this object. Change it when the shape or a method of OpenProviderSpan changes. */\n version: 1;\n /** Every observed provider span that is still open: `shutdown()` ends them. */\n open: Set<OpenProviderSpan>;\n /** Ends a span when nobody can reach its promise, stream or iterators. */\n registry: FinalizationRegistry<OpenProviderSpan> | undefined;\n}\n\nconst PROVIDER_SPANS = Symbol.for('risicare.providerSpans');\n\n/** True when `s` is a version-1 state that this copy of the SDK can use. */\nfunction usableProviderSpanState(s: unknown): s is ProviderSpanState {\n if (!s || typeof s !== 'object') return false;\n const { version, open, registry } = s as Record<string, unknown>;\n const o = open as Record<PropertyKey, unknown> | undefined;\n return (\n version === 1 &&\n !!o &&\n typeof o.add === 'function' &&\n typeof o.delete === 'function' &&\n typeof o[Symbol.iterator] === 'function' &&\n (registry === undefined || typeof (registry as { register?: unknown }).register === 'function')\n );\n}\n\n/**\n * ONE set and ONE registry for every bundle. Each provider entry point bundles\n * its own copy of stream-proxy.ts (`splitting: false`), and `shutdown()` in the\n * main bundle must see the spans that `risicare/openai` opened.\n *\n * Two installed copies of the SDK share this state too. A copy uses it only\n * when it is version 1 and its shape checks pass; else this function throws,\n * and the caller of this function (stream-proxy.ts) does not observe the call.\n * It never replaces a state that another copy made.\n */\nexport function getProviderSpanState(): ProviderSpanState {\n const found: unknown = G[PROVIDER_SPANS];\n if (found === undefined) {\n const s: ProviderSpanState = {\n version: 1,\n open: new Set(),\n registry:\n typeof FinalizationRegistry === 'function'\n ? new FinalizationRegistry<OpenProviderSpan>((o) => o.release())\n : undefined,\n };\n G[PROVIDER_SPANS] = s;\n return s;\n }\n if (!usableProviderSpanState(found)) {\n throw new TypeError('the shared provider span state is not version 1');\n }\n return found;\n}\n","/**\n * Internal logger for the Risicare SDK.\n *\n * Centralizes all diagnostic output so that:\n * - Debug messages are gated by a single flag (zero-cost when disabled)\n * - Warnings always fire (operational alerts like queue full)\n * - All output goes to stderr with a consistent [risicare] prefix\n * - A future custom logger callback can be added in one place\n */\n\nimport { getDebug, setDebugFlag } from '../globals.js';\n\n/**\n * Enable or disable debug logging. Called once during init().\n * @internal\n */\nexport function setDebug(enabled: boolean): void {\n setDebugFlag(enabled);\n}\n\n/**\n * Log a debug message. Only outputs when debug mode is enabled.\n * @internal\n */\nexport function debug(msg: string): void {\n if (getDebug()) {\n process.stderr.write(`[risicare] ${msg}\\n`);\n }\n}\n\n/**\n * Log a warning. Always outputs regardless of debug mode.\n * Use sparingly — only for operational issues the user should see.\n * @internal\n */\nexport function warn(msg: string): void {\n process.stderr.write(`[risicare] WARNING: ${msg}\\n`);\n}\n\n/**\n * Log an informational line. Always outputs regardless of debug mode.\n * Use only for rare state changes the user should see once (for example, the\n * export pause for the monthly quota has ended).\n * @internal\n */\nexport function info(msg: string): void {\n process.stderr.write(`[risicare] INFO: ${msg}\\n`);\n}\n","/**\n * Text helpers for strings that go on the wire.\n *\n * @internal Not public API.\n */\n\n/**\n * The first `max` CODE POINTS of `text`, as Python's `text[:max]` gives.\n *\n * Not `text.slice(0, max)`: that counts UTF-16 code units and can keep the\n * first half of a surrogate pair. JSON.stringify writes a lone half as\n * `\\ud83d`, and a strict JSON parser refuses the whole request body, so the\n * whole batch is lost. The walk stops at `max` code points, so a very long\n * text costs no more than the part that is kept.\n */\nexport function cutCodePoints(text: string, max: number): string {\n // A text of at most `max` code units has at most `max` code points.\n if (text.length <= max) return text;\n let units = 0;\n for (let points = 0; points < max && units < text.length; points++) {\n units += (text.codePointAt(units) as number) > 0xffff ? 2 : 1;\n }\n return text.slice(0, units);\n}\n","/**\n * Text that is safe to put in a log line: THE one scrub function of the SDK.\n * Python twin: `risicare/_error_text.py` (`scrub_text`, `safe_url`).\n *\n * Every text that comes from the network (a header, a body, a redirect target) or\n * from an error, and that goes into a log line of the exporters, the fix loader or\n * `score()`, goes through `scrubText`. It:\n * 1. removes each key it is given, and `RISICARE_API_KEY`, in any case of letters\n * (a literal match: a key with regex metacharacters is not read as a pattern);\n * 2. also finds a key that is percent-encoded: when the URL-decoded copy of the\n * text holds a key, the DECODED text is printed, with the key removed;\n * 3. makes the text one line (each control character becomes a space);\n * 4. cuts the text at `limit` code points (default 200).\n *\n * @internal Not public API.\n */\nimport { cutCodePoints } from './text.js';\n\nexport const KEY_MARKER = '[REDACTED-KEY]';\n\nconst CONTROL = new RegExp('[\\\\u0000-\\\\u001f\\\\u007f-\\\\u009f\\\\u2028\\\\u2029]', 'g');\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/** Decode %XX sequences. A sequence that is not valid UTF-8 is decoded byte by byte. */\nfunction percentDecode(text: string): string {\n try {\n return decodeURIComponent(text);\n } catch {\n return text.replace(/%([0-9A-Fa-f]{2})/g, (_m, hex: string) => String.fromCharCode(parseInt(hex, 16)));\n }\n}\n\nfunction keyPattern(keys: ReadonlyArray<string | undefined | null>): RegExp | null {\n const values = new Set<string>();\n for (const k of [...keys, process.env.RISICARE_API_KEY]) if (k) values.add(k);\n if (values.size === 0) return null;\n // The longest value first, so that a key that contains another key is removed whole.\n const ordered = [...values].sort((a, b) => b.length - a.length);\n return new RegExp(ordered.map(escapeRegExp).join('|'), 'gi');\n}\n\n/** `text` as one line, with every given key removed, at most `limit` code points. */\nexport function scrubText(text: unknown, keys: ReadonlyArray<string | undefined | null>, limit = 200): string {\n let out: string;\n try {\n out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);\n } catch {\n out = typeof text;\n }\n const pattern = keyPattern(keys);\n if (pattern !== null) {\n if (out.includes('%')) {\n const decoded = percentDecode(out);\n pattern.lastIndex = 0;\n if (decoded !== out && pattern.test(decoded)) out = decoded;\n }\n pattern.lastIndex = 0;\n out = out.replace(pattern, KEY_MARKER);\n }\n return cutCodePoints(out.replace(CONTROL, ' '), limit);\n}\n\n/**\n * `url` without userinfo, query and fragment: scheme, host, port and path only. The SDK\n * prints an endpoint in WARNING and debug lines; a secret in its userinfo\n * (`http://user:secret@host`) or its query (`?k=secret`) must not reach the log.\n */\nexport function safeUrl(url: string): string {\n try {\n const u = new URL(url);\n const path = u.pathname === '/' && !/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]*\\//i.test(url) ? '' : u.pathname;\n return `${u.protocol}//${u.host}${path}`;\n } catch {\n return url.split('?')[0].split('#')[0].replace(/\\/\\/[^/@]*@/, '//');\n }\n}\n\n/** True when `url` holds userinfo (`user:password@host`). `fetch` refuses such a URL. */\nexport function hasCredentials(url: string): boolean {\n try {\n const u = new URL(url);\n return u.username !== '' || u.password !== '';\n } catch {\n return false;\n }\n}\n","/**\n * Customer-supplied masking of span content, applied before anything leaves the process.\n *\n * The full rationale — why this is the ONLY layer rather than defence in depth,\n * why the hook carries the key, what is deliberately not masked, and the\n * fail-closed-per-field ruling — is written once, in the Python twin:\n * `packages/risicare-sdk/src/risicare/masking.py`. This file mirrors it. Where\n * the two languages diverge, the divergence is called out inline below; do not\n * \"align\" them without reading both.\n *\n * ── Mirrored from Python ─────────────────────────────────────────────────────\n * • signature `mask(key, value) => value` — the key is REQUIRED, because our\n * span model has no input/output fields: the prompt and the model name are\n * both plain entries of `span.attributes`, so a keyless hook cannot tell\n * them apart and `() => '***'` would erase every dashboard label.\n * • masked: every attribute value, `statusMessage`, every event-attribute\n * value, every link-attribute value — plus `score.comment`, the one key\n * that is NOT a span field (see {@link SCORE_COMMENT_KEY}).\n * • NOT masked: traceId / spanId / parentSpanId, `span.name`, `event.name`,\n * and the typed identity + llm columns (agentId, agentName, agentType,\n * sessionId, toolName, llmModel, …). Masking an identifier breaks the\n * customer's own joins — the F-39C lesson. The OTel-style attribute forms\n * (`agent.name`, `session.user_id`) live in `attributes` and ARE masked.\n * • no type narrowing: the hook sees numbers and booleans too. A card number\n * is representable as a number, and deciding otherwise on the customer's\n * behalf is the quiet narrowing this codebase keeps paying for.\n * • fail closed per FIELD: a throwing hook yields `MASK_ERROR_MARKER` for\n * that field and the span is exported intact. Never drop the span — the\n * SDK is the last place the data exists, so a drop here is permanent loss,\n * and it additionally orphans the span's children for zero extra safety.\n * • idempotent: `_exportBatch` can re-queue a refused batch, and a user\n * callback cannot be assumed idempotent, so a masked span is flagged.\n *\n * ── Where JS DIFFERS from Python, and it matters ─────────────────────────────\n * 1. There is no `exceptions[]` on the JS Span — `toPayload()` emits none — so\n * there are no `exceptions.{i}.*` keys here. A port that adds exceptions to\n * the JS span must add them here in the same change.\n * 2. ⚠ THE HOT-PATH COST IS STRICTLY WORSE THAN PYTHON'S. Python runs the mask\n * on a background worker THREAD, so a slow mask costs only drain rate. Node\n * has one thread: `_exportBatch` is `async`, but the mask itself is sync, so\n * while it runs NOTHING else in the customer's process runs — not their\n * request handlers, not their timers. In Python a slow mask degrades\n * throughput; in JS it degrades the whole application. The budget warning\n * below is not advisory decoration here.\n * 3. `_masked` is a real private field on `Span` (we own that class), rather\n * than Python's `setattr` — which Python needs only because its `Span`\n * lives in the separate `risicare-core` package.\n */\n\nimport { warn, debug } from './utils/log.js';\nimport type { Span } from './span.js';\n\n/**\n * A customer mask callback.\n *\n * @param key Fully-qualified path of the value: an attribute key as-is\n * (`\"gen_ai.prompt.0.content\"`), or a dotted path\n * (`\"statusMessage\"`, `\"events.0.attributes.foo\"`,\n * `\"links.0.attributes.bar\"`).\n * @param value The current value — any type, not just string.\n * @returns The replacement, or `value` unchanged.\n */\nexport type MaskFn = (key: string, value: unknown) => unknown;\n\n/** Called with `(key, error)` for every field whose mask threw. */\nexport type MaskErrorReporter = (key: string, error: unknown) => void;\n\n/**\n * Substituted for a value whose mask threw. Fixed, deliberately not\n * valid-looking, and greppable in a dashboard.\n */\nexport const MASK_ERROR_MARKER = '<risicare:mask-error>';\n\n/**\n * The masking hot-path budget, in ms per span. MEASURED and NAMED, never\n * ENFORCED — see the Python twin. A \"disable the mask because it is slow\" rule\n * would fail OPEN on a security control, silently, which is the worst outcome\n * available; so exceeding this warns and nothing else.\n *\n * 1 ms/span leaves a 500-span batch at 500 ms, under the 1,000 ms default\n * `batchTimeoutMs` — the last point at which one batch's masking still fits\n * inside one batch's period. Past that the queue provably grows, and in Node\n * the event loop is blocked for the excess.\n */\nexport const MASK_BUDGET_MS_PER_SPAN = 1.0;\n\n/** Rate-limit window for both mask warnings, in ms. */\nexport const MASK_WARN_WINDOW_MS = 300_000;\n\n/**\n * The key the hook receives for `score(traceId, name, value, { comment })`.\n *\n * ⚠ THE ONE KEY THAT IS NOT A SPAN FIELD. `score()` POSTs direct to\n * `/api/v1/scores` (`client.ts`), outside `BatchSpanProcessor` and therefore\n * outside {@link applyMask} — so its free-text `comment` was uncovered until\n * F-SDKMASKSCORE-001. The full ruling (why the same hook rather than a second\n * one, why the score's `name` is deliberately NOT masked, and why the cost lands\n * on the caller here rather than on the exporter) is written once in the Python\n * twin: `risicare/masking.py`, \"THE NON-SPAN SURFACE\".\n *\n * A constant, not a literal at the call site, so the two SDKs cannot drift and a\n * customer's `if (key === ...)` has something importable to compare against.\n */\nexport const SCORE_COMMENT_KEY = 'score.comment';\n\n/**\n * Mask ONE free-text value that reaches the wire raw, and coerce the result.\n *\n * The exported form of the same primitive {@link applyMask} uses for\n * `statusMessage`. It exists so a non-span egress (today: `score(comment)`) gets\n * byte-identical semantics to a span field — same marker, same\n * fail-closed-per-field rule, same coercion — rather than a second\n * implementation that drifts from this one.\n *\n * Never throws.\n */\nexport function maskText(\n mask: MaskFn,\n key: string,\n value: unknown,\n onError?: MaskErrorReporter,\n): string {\n return maskString(mask, key, value, onError);\n}\n\n/** Apply `mask` to one value. Never throws; fails closed to the marker. */\nfunction maskOne(\n mask: MaskFn,\n key: string,\n value: unknown,\n onError: MaskErrorReporter | undefined,\n): unknown {\n try {\n return mask(key, value);\n } catch (e) {\n onError?.(key, e);\n return MASK_ERROR_MARKER;\n }\n}\n\n/**\n * Apply `mask` to a field that reaches the wire as a raw JSON string, and\n * coerce the result.\n *\n * `HttpExporter` serializes the WHOLE batch in one `JSON.stringify`\n * (`exporters/http.ts:119`). Unlike Python's `json.dumps`, `JSON.stringify`\n * does not throw on most objects — but it DOES throw on a circular reference\n * or a BigInt, and it silently emits `null` for a function or `undefined`,\n * which would erase the field without saying so. Coercing here keeps one bad\n * return value from one field from taking out every other span in the batch.\n */\nfunction maskString(\n mask: MaskFn,\n key: string,\n value: unknown,\n onError: MaskErrorReporter | undefined,\n): string {\n const masked = maskOne(mask, key, value, onError);\n if (typeof masked === 'string') return masked;\n try {\n return String(masked);\n } catch (e) {\n // A `Symbol`, or an object with a hostile `toString`.\n onError?.(key, e);\n return MASK_ERROR_MARKER;\n }\n}\n\n/** Mask every value of an attribute record IN PLACE. */\nfunction maskAttributes(\n mask: MaskFn,\n prefix: string,\n attrs: Record<string, unknown>,\n onError: MaskErrorReporter | undefined,\n): void {\n // Snapshot the keys: the hook is customer code and must not be able to make\n // us iterate a record it is concurrently reshaping.\n for (const k of Object.keys(attrs)) {\n attrs[k] = maskOne(mask, prefix + k, attrs[k], onError);\n }\n}\n\n/** Whether `applyMask` has already run over this span. */\nexport function isMasked(span: Span): boolean {\n return (span as unknown as { _risicareMasked?: boolean })._risicareMasked === true;\n}\n\nfunction markMasked(span: Span): void {\n try {\n (span as unknown as { _risicareMasked?: boolean })._risicareMasked = true;\n } catch {\n // Only reachable for a frozen/sealed stand-in. Degrade to \"may be masked\n // again on re-queue\", never to a throw inside the export path.\n debug('Could not mark span as masked; a re-queue may re-mask it');\n }\n}\n\n/**\n * Mask every content-bearing field of `span`, in place, exactly once.\n *\n * Never throws. A field whose mask throws is replaced with\n * {@link MASK_ERROR_MARKER}; the span is always preserved.\n */\nexport function applyMask(span: Span, mask: MaskFn, onError?: MaskErrorReporter): void {\n if (isMasked(span)) return;\n\n // ── attributes ─────────────────────────────────────────────────────────────\n if (span.attributes && typeof span.attributes === 'object') {\n maskAttributes(mask, '', span.attributes, onError);\n }\n\n // ── status message ─────────────────────────────────────────────────────────\n if (span.statusMessage !== undefined) {\n span.statusMessage = maskString(mask, 'statusMessage', span.statusMessage, onError);\n }\n\n // ── events ─────────────────────────────────────────────────────────────────\n // `event.name` is NOT masked — it is the timeline's grouping key, same\n // argument as `span.name`.\n if (Array.isArray(span.events)) {\n span.events.forEach((event, i) => {\n if (event?.attributes && typeof event.attributes === 'object') {\n maskAttributes(mask, `events.${i}.attributes.`, event.attributes, onError);\n }\n });\n }\n\n // ── links ──────────────────────────────────────────────────────────────────\n // `traceId` / `spanId` on a link are structural: masking them severs the\n // link, which is the one thing a link is for.\n if (Array.isArray(span.links)) {\n span.links.forEach((link, i) => {\n if (link?.attributes && typeof link.attributes === 'object') {\n maskAttributes(mask, `links.${i}.attributes.`, link.attributes, onError);\n }\n });\n }\n\n markMasked(span);\n}\n\n// ── content capture gate (traceContent) ───────────────────────────────────────\n//\n// ⚠ THIS IS A CAPTURE SWITCH, NOT A REDACTION FEATURE. `mask` above stays the\n// only pre-export redaction hook. The gate is a KEY-SHAPE filter, and it lives in\n// this module because this module already owns the one walk both content paths\n// cross. The key rule never reads a value. The one exception is the value rule V\n// below: it reads the STRUCTURE of one JSON-object value (its keys), never the\n// text in it.\n//\n// The Python twin is `risicare/masking.py::strip_content` and the two are kept\n// character-for-character equivalent in RULE — same exact sets, same segment and\n// suffix rules, same marker, same walk. Four divergences of exactly this shape have been\n// measured in this campaign (`debug` gated differently; `deleted_at IS NULL` in\n// the gateway only; three Redis cache-clear sites; `reportError` dead in ESM\n// only), so a one-sided fix here would become the fifth.\n//\n// Before 0.5.1 `traceContent` was carried by the Tracer (`tracer.ts`) behind a\n// getter and consulted ONLY by the provider patches. Measured on the published\n// 0.5.0: `getTraceContent()` returned false and a hand-set\n// `gen_ai.prompt.0.content` still reached the wire byte-for-byte.\n\n// ⚠ THE RULE IS THE JOINT CONTENT-KEY CORPUS v4 OF THE GATEWAY AND THE SDKs, AND\n// THE THREE GATES MUST AGREE. `risicare-ingestion` `content_control.rs` holds the\n// same rule, and it is the only gate for OTLP and for the SDKs already published.\n// Three corpora are the contract, and the gate gives every verdict of each:\n// `tests/fixtures/content-keys-v4.json` (the joint corpus, a byte-identical copy\n// of the gateway's file, with the value rule V and the `error_text` section that\n// the SDK does not apply; version 3 stays, with its pin and its key verdicts), `tests/fixtures/content-keys-v2.json` (the SDK corpus,\n// the same file in both SDKs) and `tests/fixtures/content-keys-gateway-v2.json`\n// (a byte-identical copy of the gateway's `content-keys-v2.json`, R41). Through\n// 0.6.0 the rule was the last segment `content`, the suffix `_content` and 2\n// exact keys, so `input.value`, `output.value`, `gen_ai.input.messages`,\n// `gen_ai.output.messages`, a bare `gen_ai.prompt` and CrewAI's task description\n// passed with traceContent off. v1 then kept the Vercel `ai.*`, Google ADK\n// `gcp.vertex.agent.*`, Pydantic AI, OpenLLMetry `crewai.*` and Mastra keys, the\n// lists of tool definitions, and the body of the OTel v1.36 message events.\n// ⚠ FAIL CLOSED: E and C also hold third-party content keys (OTel GenAI,\n// OpenInference, OpenLLMetry) that no v1 rule matched at first. A doubtful key is\n// content. The full statement of the rule (E, S, C, N, X, KEEP, the message\n// event rule M and the value rule V) is in the Python twin, `masking.py`.\n\n/** E — matched EXACTLY. A substring match would eat `*_system_prompt_length`. */\nconst CONTENT_KEYS_EXACT: ReadonlySet<string> = new Set([\n // spec v1\n 'gen_ai.system_prompt', // anthropic, bedrock\n 'gen_ai.prompt.message', // cohere\n 'gen_ai.prompt', // OTel GenAI (deprecated form)\n 'gen_ai.completion',\n 'gen_ai.input.messages', // OTel GenAI\n 'gen_ai.output.messages',\n 'gen_ai.system_instructions',\n 'gen_ai.tool.call.arguments',\n // Corpus v2: the list of tool definitions of a request. The names,\n // descriptions and schemas in it are text that the customer wrote.\n 'gen_ai.tool.definitions',\n 'gen_ai.tool.call.result',\n 'input.value', // OpenInference\n 'output.value',\n 'llm.prompts',\n 'llm.prompt_template.template',\n 'llm.prompt_template.variables',\n 'task_description', // CrewAI\n // ⚠ EXTENSION to spec v1: content keys that the Python SDK's integrations emit\n // and that no v1 rule strips. Kept here too, so the two SDKs agree on the rule.\n 'framework.crewai.task_description',\n 'framework.crewai.agent_goal',\n 'framework.crewai.agent_output',\n 'framework.crewai.result',\n 'framework.autogen.last_message',\n 'framework.autogen.reply',\n 'framework.autogen.response',\n 'framework.openai_agents.input',\n 'framework.openai_agents.output',\n 'framework.dspy.signature',\n 'gen_ai.request.messages',\n 'agent.action.input',\n 'agent.action.log',\n 'agent.finish.output',\n 'tool.input',\n 'tool.output',\n 'retriever.query',\n 'retriever.first_doc',\n // ⚠ FAIL CLOSED: third-party content keys that no other rule strips.\n 'gen_ai.retrieval.query.text', // OTel GenAI\n 'gen_ai.retrieval.documents',\n 'gen_ai.evaluation.explanation',\n 'llm.function_call', // OpenInference\n 'llm.choices',\n 'reranker.query',\n 'audio.transcript',\n 'traceloop.entity.input', // OpenLLMetry\n 'traceloop.entity.output',\n // Gateway corpus v2 (R41): the content keys of more frameworks. The same 75\n // keys as `CONTENT_KEYS_EXACT` in the gateway's `content_control.rs`.\n 'agent.backstory', // OpenInference\n 'agent.goal',\n 'llm.available_functions',\n 'llm.tools',\n 'ai.prompt', // Vercel AI SDK\n 'ai.prompt.messages',\n 'ai.prompt.tools',\n 'ai.response.files',\n 'ai.response.object',\n 'ai.response.reasoning',\n 'ai.response.text',\n 'ai.response.toolCalls',\n 'ai.result.object', // the older Vercel names\n 'ai.result.text',\n 'ai.result.toolCalls',\n 'ai.toolCall.args',\n 'ai.toolCall.result',\n 'ai.value', // the text of an embedding call\n 'ai.values',\n 'final_result', // Pydantic AI\n 'model_request_parameters',\n 'pydantic_ai.all_messages',\n 'tool_arguments',\n 'tool_response',\n 'gcp.vertex.agent.data', // Google ADK\n 'gcp.vertex.agent.llm_request',\n 'gcp.vertex.agent.llm_response',\n 'gcp.vertex.agent.tool_call_args',\n 'gcp.vertex.agent.tool_response',\n 'gen_ai.task.input', // OpenLLMetry\n 'gen_ai.task.output',\n 'sk.available_functions', // Semantic Kernel\n]);\n\n/**\n * C — last segment -> the earlier segments that make it content (empty: always).\n * The last-segment KEEP rule does not override C.\n */\nconst CONTENT_LAST_SEGMENT_IN_CONTEXT: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n ['function_call_arguments_json', new Set<string>()], // OpenInference `message.*`\n ['data', new Set(['message_content'])],\n ['url', new Set(['image'])], // `image.url` can hold base64 data\n ['metadata', new Set(['document', 'documents'])],\n // Gateway corpus v2: a list of tool definitions. The `description` of one tool\n // on a tool span (`tool.description`) is not content; the descriptions in a list are.\n ['description', new Set(['definitions', 'functions', 'tools'])],\n ['json_schema', new Set(['tool', 'tools'])],\n ['parameters', new Set(['definitions', 'functions', 'tool', 'tools'])],\n // Gateway corpus v2: the Mastra span I/O, `mastra.<span type>.input|output`.\n ['input', new Set(['mastra'])],\n ['output', new Set(['mastra'])],\n]);\n\n/** S — with a last segment `text` or `arguments`, content when an earlier segment is one of these. */\nconst CONTENT_CONTAINER_SEGMENTS: ReadonlySet<string> = new Set([\n 'message',\n 'messages',\n 'message_content',\n 'contents',\n 'embedding',\n 'embeddings',\n 'document',\n 'documents',\n 'tool_call',\n 'tool_calls',\n 'function',\n // Gateway corpus v2: LiteLLM `gen_ai.completion.{i}.function_call.arguments` and\n // OpenInference `llm.prompts.{i}.prompt.text`.\n 'function_call',\n 'prompt',\n 'prompts',\n]);\n\n/**\n * N — a first segment whose keys are content unless a KEEP rule names them\n * (OpenLLMetry CrewAI `crewai.<class>.<field>`). A bare `crewai` is not content,\n * and only the FIRST segment counts.\n */\nconst CONTENT_FIRST_SEGMENTS: ReadonlySet<string> = new Set(['crewai']);\n\n/**\n * M — span events whose attributes hold one message: the OTel v1.36 message\n * events and, by prefix, OpenLLMetry's `gen_ai.content.*` events.\n */\nconst CONTENT_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'gen_ai.assistant.message',\n 'gen_ai.choice',\n 'gen_ai.system.message',\n 'gen_ai.tool.message',\n 'gen_ai.user.message',\n]);\nconst CONTENT_EVENT_PREFIX = 'gen_ai.content.';\n\n/** M — attributes of a message event that are never content, beside the KEEP rules. */\nconst CONTENT_EVENT_KEEP_KEYS: ReadonlySet<string> = new Set(['gen_ai.provider.name', 'gen_ai.system']);\n\n/** Never content. Wins over every strip rule. */\nconst CONTENT_KEYS_KEEP_EXACT: ReadonlySet<string> = new Set([\n 'gen_ai.response.content_type',\n 'gen_ai.response.content_blocks',\n 'gen_ai.prompt.parts',\n 'gen_ai.prompt.count',\n 'gen_ai.response.choices',\n 'gen_ai.completion.tool_calls',\n]);\n\n/** Never content by the last segment. Wins over S and N, never over E, C or X. */\nconst KEEP_LAST_SEGMENTS: ReadonlySet<string> = new Set([\n 'role',\n 'name',\n 'id',\n 'type',\n 'count',\n 'index',\n 'model',\n 'finish_reason',\n 'mime_type',\n // Gateway v2 at risicare-ingestion main (PR 94): a model name\n // (`crewai.agent.llm`) and the crew process type are not content.\n 'llm',\n 'process',\n]);\nconst KEEP_LAST_SUFFIXES = ['_length', '_tokens', '_count'] as const;\n\n/**\n * V — a key whose value is a JSON object of request parameters -> the keys of\n * that object that are content, in their normalised form ({@link normalisedKey}:\n * `A` to `Z` lower case, no `_`). A new key is ONE line here (and in the Python\n * twin and the gateway's `CONTENT_IN_JSON_OBJECT`, with the corpus). The rule\n * (corpus v4): the value is a JSON object, or JSON text of one; a listed key gets\n * the marker at every depth, and when a part of a dotted key is listed; every\n * other entry is walked with the key rule under the key path\n * `llm.invocation_parameters.<path>`; text that starts as JSON is walked as JSON,\n * and gets the marker whole when it does not parse (cut text, `1e400`); the value\n * at the key is written back as compact JSON; a value that is not a JSON object\n * gets the marker whole; the key matches a flat attribute key or the dotted path\n * of a nested value, and a flat key `llm.invocation_parameters.<path>` takes the\n * same rule. The walk does not mark error text (only the project switch does,\n * R41b), and JSON text keeps the key order of the value (the gateway sorts the\n * keys).\n */\nconst CONTENT_IN_JSON_OBJECT: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n [\n 'llm.invocation_parameters',\n new Set([\n 'additionalinstructions', // OpenAI assistants run\n 'chathistory', // Cohere\n 'contents', // Gemini\n 'documents', // Cohere RAG\n 'functions',\n 'input',\n 'inputtext', // Bedrock Titan\n 'instructions',\n 'message', // Cohere\n 'messages',\n 'preamble', // Cohere\n 'prediction', // OpenAI predicted output\n 'prompt',\n 'system', // Anthropic\n 'systeminstruction', // Gemini\n 'texts', // Cohere embed\n 'toolconfig', // Gemini\n 'tools',\n ]),\n ],\n]);\n\n/**\n * V — each dotted path that leads to a key of `CONTENT_IN_JSON_OBJECT` (`llm` for\n * `llm.invocation_parameters`): the gate reads a nested value only below one.\n */\nconst VALUE_RULE_PREFIXES: ReadonlySet<string> = new Set(\n [...CONTENT_IN_JSON_OBJECT.keys()].flatMap((key) => {\n const segments = key.split('.');\n return segments.slice(1).map((_, i) => segments.slice(0, i + 1).join('.'));\n }),\n);\n\n/**\n * Replaces a stripped value, rather than deleting the key.\n *\n * Deleting would make \"the customer sent no prompt\" and \"the customer disabled\n * capture\" indistinguishable downstream — the W1/W3 honesty rule: label the\n * absence, never forge it.\n */\nexport const CONTENT_OMITTED_MARKER = '<risicare:content-omitted>';\n\nfunction hasKeepLastSegment(last: string): boolean {\n return KEEP_LAST_SEGMENTS.has(last) || KEEP_LAST_SUFFIXES.some((x) => last.endsWith(x));\n}\n\n/**\n * Whether `key` names a customer-content attribute (content-key spec v2).\n * Pure function of the KEY. Never looks at the value.\n *\n * Content when ANY is true — E: an exact key; S: the last segment is `content`,\n * or it is `text` / `arguments` under a container segment; C: a last segment in\n * its context, such as `url` under `image`; N: the first segment is `crewai` and\n * the key has more than one segment; X: the key ends in `_content`. Never\n * content: the exact-KEEP list (wins over all), or a last segment such as\n * `role`, `name`, `model`, `*_tokens` (wins over S and N only).\n */\nexport function isContentKey(key: string): boolean {\n if (CONTENT_KEYS_KEEP_EXACT.has(key)) return false;\n if (CONTENT_KEYS_EXACT.has(key) || key.endsWith('_content')) return true; // E, X\n const segments = key.split('.');\n const last = segments[segments.length - 1];\n const context = CONTENT_LAST_SEGMENT_IN_CONTEXT.get(last);\n if (context && (context.size === 0 || segments.slice(0, -1).some((s) => context.has(s)))) {\n return true; // C — `...message_content.image.image.url`\n }\n if (hasKeepLastSegment(last)) {\n return false; // `...tool_call.function.name` stays\n }\n if (segments.length > 1 && CONTENT_FIRST_SEGMENTS.has(segments[0])) return true; // N\n if (last === 'content') return true; // S\n if (last === 'text' || last === 'arguments') {\n return segments.slice(0, -1).some((s) => CONTENT_CONTAINER_SEGMENTS.has(s)); // S\n }\n return false;\n}\n\n/** Whether a span event of this `name` holds one message (rule M). */\nexport function isContentEvent(name: string): boolean {\n return CONTENT_EVENT_NAMES.has(name) || name.startsWith(CONTENT_EVENT_PREFIX);\n}\n\n/**\n * Whether `key` is content as an attribute of a message event (rule M). Fail\n * closed: every key is content unless a KEEP rule or `CONTENT_EVENT_KEEP_KEYS`\n * names it. Pure function of the KEY.\n */\nexport function isContentEventAttribute(key: string): boolean {\n if (isContentKey(key)) return true;\n const last = key.slice(key.lastIndexOf('.') + 1);\n return !(\n CONTENT_KEYS_KEEP_EXACT.has(key) ||\n CONTENT_EVENT_KEEP_KEYS.has(key) ||\n hasKeepLastSegment(last)\n );\n}\n\n/**\n * V — the content keys of the value rule that names `keyPath` or `key`. The\n * gateway's `json_object_content_keys`: the full dotted path or the entry key\n * alone matches, and the first rule of the table wins.\n */\nfunction jsonObjectContentKeys(keyPath: string, key: string): ReadonlySet<string> | undefined {\n for (const [ruleKey, keys] of CONTENT_IN_JSON_OBJECT) {\n if (ruleKey === keyPath || ruleKey === key) return keys;\n }\n return undefined;\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * V — a flat key below a key of a value rule\n * (`llm.invocation_parameters.extra_body.system`): the path after the rule key,\n * and the content keys of the rule. The gateway's `flat_value_rule`: the dotted\n * path or the key alone matches.\n */\nfunction flatValueRule(keyPath: string, key: string): [string, ReadonlySet<string>] | undefined {\n for (const [ruleKey, keys] of CONTENT_IN_JSON_OBJECT) {\n for (const k of [keyPath, key]) {\n if (k.startsWith(`${ruleKey}.`)) return [k.slice(ruleKey.length + 1), keys];\n }\n }\n return undefined;\n}\n\n/**\n * V — a key in its normalised form: `A` to `Z` become lower case and each `_` is\n * removed. Only ASCII letters change (`toLowerCase` changes other letters too),\n * so JavaScript, Python and the gateway give the same form.\n */\nexport function normalisedKey(key: string): string {\n return key.replace(/_/g, '').replace(/[A-Z]/g, (c) => c.toLowerCase());\n}\n\n/** V — whether `key`, or one of its parts between dots, is a listed key. */\nfunction namesListedKey(key: string, keys: ReadonlySet<string>): boolean {\n return key.split('.').some((part) => keys.has(normalisedKey(part)));\n}\n\n/**\n * V — whether the key rule withholds the value of `key` at `keyPath`. The gateway\n * also names the error-text keys here; only the project switch withholds error\n * text (R41b), so the SDK does not.\n */\nfunction isKeyRuleText(keyPath: string, key: string): boolean {\n return isContentKey(keyPath) || isContentKey(key);\n}\n\n/**\n * V — whether `text` starts as a JSON object or list, after JSON white space\n * (space, tab, line feed, carriage return).\n */\nfunction startsAsJson(text: string): boolean {\n return /^[ \\t\\n\\r]*[{[]/.test(text);\n}\n\n/**\n * V — parse JSON text as the gateway does. Throws when it does not parse. A\n * number out of the range of a 64-bit float (`1e400`) does not parse in the\n * gateway; `JSON.parse` reads it as Infinity, so it is refused here.\n */\nfunction parseJson(text: string): unknown {\n return JSON.parse(text, (_key, value: unknown) => {\n if (typeof value === 'number' && !Number.isFinite(value)) {\n throw new RangeError('not JSON: a number out of range');\n }\n return value;\n });\n}\n\n/**\n * V — an object or an array read through its JSON form (the form the exporter\n * sends), as a new value: the caller's object does not change. Throws when it\n * cannot be read (a cycle, a BigInt, a non-finite number: `JSON.stringify`\n * writes Infinity and NaN as null, and the Python twin refuses them).\n */\nfunction jsonCopy(value: unknown): unknown {\n return parseJson(\n JSON.stringify(value, (_key, v: unknown) => {\n if (typeof v === 'number' && !Number.isFinite(v)) throw new RangeError('not JSON: a non-finite number');\n return v;\n }),\n );\n}\n\n/**\n * V — apply the value rule to one value. Returns the new value and the count.\n *\n * A string is parsed and written back as compact JSON. An object is read through\n * its JSON form, so the result is a new object and the caller's object does not\n * change. A listed key gets the marker at every depth; every other entry is\n * walked ({@link omitInParameter}). Anything that is not a JSON object, or that\n * cannot be read as one (a cycle, a BigInt, a number out of range), gets the\n * marker whole.\n */\nfunction omitInJsonObject(\n value: unknown,\n keyPath: string,\n keys: ReadonlySet<string>,\n): [unknown, number] {\n try {\n let parsed: unknown;\n if (typeof value === 'string') parsed = parseJson(value);\n else if (typeof value === 'object' && value !== null) parsed = jsonCopy(value);\n if (!isJsonObject(parsed)) return [CONTENT_OMITTED_MARKER, 1];\n let n = 0;\n for (const k of Object.keys(parsed)) {\n const [entry, count] = omitInParameterEntry(parsed[k], `${keyPath}.${k}`, k, keys);\n parsed[k] = entry;\n n += count;\n }\n return [typeof value === 'string' ? JSON.stringify(parsed) : parsed, n];\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n}\n\n/**\n * V — one object entry at any depth inside a value of the value rule: a listed\n * key (or a dotted key with a listed part) and a key of the key rule get the\n * marker; every other value is walked.\n */\nfunction omitInParameterEntry(\n value: unknown,\n keyPath: string,\n key: string,\n keys: ReadonlySet<string>,\n): [unknown, number] {\n if (namesListedKey(key, keys) || isKeyRuleText(keyPath, key)) return [CONTENT_OMITTED_MARKER, 1];\n return omitInParameter(value, keyPath, keys);\n}\n\n/**\n * V — walk a PARSED value inside a value of the value rule (corpus v4). Objects\n * and arrays are walked in place (they are the gate's own copy). Text that starts\n * as JSON is parsed: when it parses, it is walked under the same path and, when a\n * value in it gets the marker, written back as compact JSON; when it does not\n * parse, or is too deep to walk, it gets the marker whole. Other text, numbers,\n * booleans and null stay. Returns the new value and the count.\n */\nfunction omitInParameter(value: unknown, path: string, keys: ReadonlySet<string>): [unknown, number] {\n let n = 0;\n if (Array.isArray(value)) {\n value.forEach((item, i) => {\n const [entry, count] = omitInParameter(item, `${path}.${i}`, keys);\n value[i] = entry;\n n += count;\n });\n } else if (isJsonObject(value)) {\n for (const k of Object.keys(value)) {\n const [entry, count] = omitInParameterEntry(value[k], `${path}.${k}`, k, keys);\n value[k] = entry;\n n += count;\n }\n } else if (typeof value === 'string' && startsAsJson(value)) {\n try {\n const [tree, count] = omitInParameter(parseJson(value), path, keys);\n return [count ? JSON.stringify(tree) : value, count];\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n }\n return [value, n];\n}\n\n/**\n * V — the value of a flat key `llm.invocation_parameters.<rest>` (the attribute\n * key, or the dotted path of a nested value): the marker when a part of `rest` is\n * listed or the key rule marks the key; else the value is walked as inside the\n * object. An object or an array is read through its JSON form; when it cannot be\n * read, the marker.\n */\nfunction omitFlat(\n value: unknown,\n keyPath: string,\n key: string,\n rest: string,\n keys: ReadonlySet<string>,\n): [unknown, number] {\n if (namesListedKey(rest, keys) || isKeyRuleText(keyPath, key)) return [CONTENT_OMITTED_MARKER, 1];\n try {\n if (typeof value === 'object' && value !== null) {\n const [tree, n] = omitInParameter(jsonCopy(value), keyPath, keys);\n return n ? [tree, n] : [value, 0];\n }\n return omitInParameter(value, keyPath, keys);\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n}\n\n/**\n * V — a nested value whose dotted path leads to the key of a value rule. `path`\n * is in `VALUE_RULE_PREFIXES` (`llm` for `llm.invocation_parameters`). The value\n * is read through its JSON form, and only the entries on a path to a value-rule\n * key, or with a dotted path below one (`{\"llm\": {\"invocation_parameters.system\":\n * ...}}`), are read: the key rule of the SDK reads flat keys only. JSON text of an\n * object or an array is read too. With no such entry below `path`, the value is\n * returned unchanged. A container that cannot be read gets the marker whole.\n */\nfunction omitBelow(value: unknown, path: string): [unknown, number] {\n // A String object is sent as its text (JSON.stringify), so it is read as text.\n const text = typeof value === 'string' ? value : value instanceof String ? value.valueOf() : undefined;\n if (text !== undefined) {\n // Text that starts as JSON and does not parse (too deep, a number out of\n // range, cut) gets the marker whole: the gateway does not read text at this\n // path, so the SDK is the only gate here. Other text that is not a JSON\n // object or array is not a value of this rule: it stays.\n let tree: unknown;\n try {\n tree = parseJson(text);\n } catch {\n return startsAsJson(text) ? [CONTENT_OMITTED_MARKER, 1] : [value, 0];\n }\n if (typeof tree !== 'object' || tree === null) return [value, 0];\n try {\n const [n, found] = omitBelowParsed(tree, path);\n return found ? [JSON.stringify(tree), n] : [value, 0];\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n }\n if (typeof value !== 'object' || value === null) return [value, 0];\n try {\n const tree = jsonCopy(value);\n const [n, found] = omitBelowParsed(tree, path);\n return found ? [tree, n] : [value, 0];\n } catch {\n return [CONTENT_OMITTED_MARKER, 1];\n }\n}\n\n/**\n * V — the walk of {@link omitBelow}, in place on the parsed copy. Returns the\n * count, and whether a value-rule key was found. An array item is never a match\n * itself (the gateway checks object entries only).\n */\nfunction omitBelowParsed(tree: unknown, path: string): [number, boolean] {\n let n = 0;\n let found = false;\n if (Array.isArray(tree)) {\n tree.forEach((item, i) => {\n const child = `${path}.${i}`;\n if (!VALUE_RULE_PREFIXES.has(child)) return;\n const [count, below] = omitBelowParsed(item, child);\n n += count;\n found ||= below;\n });\n } else if (isJsonObject(tree)) {\n for (const k of Object.keys(tree)) {\n const child = `${path}.${k}`;\n const keys = jsonObjectContentKeys(child, k);\n const flat = keys ? undefined : flatValueRule(child, k);\n if (keys) {\n const [entry, count] = omitInJsonObject(tree[k], child, keys);\n tree[k] = entry;\n n += count;\n found = true;\n } else if (flat) {\n const [entry, count] = omitFlat(tree[k], child, k, flat[0], flat[1]);\n tree[k] = entry;\n n += count;\n found = true;\n } else if (VALUE_RULE_PREFIXES.has(child)) {\n const [count, below] = omitBelowParsed(tree[k], child);\n n += count;\n found ||= below;\n }\n }\n }\n return [n, found];\n}\n\n/** V — whether the value of attribute `key` can hold a value-rule value. */\nfunction reachesValueRule(key: string): boolean {\n return (\n CONTENT_IN_JSON_OBJECT.has(key) ||\n VALUE_RULE_PREFIXES.has(key) ||\n flatValueRule(key, key) !== undefined\n );\n}\n\n/**\n * Replace every value in `attrs` whose key `rule` names, and apply the value rule\n * V, IN PLACE. Returns the number of values replaced.\n */\nfunction stripAttributes(\n attrs: Record<string, unknown>,\n rule: (key: string) => boolean = isContentKey,\n): number {\n let n = 0;\n for (const k of Object.keys(attrs)) {\n // The gateway's order: under the key rule, a value rule wins over the key\n // rule (`omit_in_entry`). A message event takes the event rule first\n // (`omit_in_event_attributes`).\n const keys = rule === isContentKey ? jsonObjectContentKeys(k, k) : undefined;\n const flat = rule === isContentKey && !keys ? flatValueRule(k, k) : undefined;\n let result: [unknown, number];\n if (keys) result = omitInJsonObject(attrs[k], k, keys);\n else if (flat) result = omitFlat(attrs[k], k, k, flat[0], flat[1]);\n else if (rule(k)) result = [CONTENT_OMITTED_MARKER, 1];\n else if (VALUE_RULE_PREFIXES.has(k)) result = omitBelow(attrs[k], k);\n else continue;\n attrs[k] = result[0];\n n += result[1];\n }\n return n;\n}\n\n/**\n * Strip the attributes of an event or a link without writing into the\n * caller's object. `addEvent(name, attrs)` keeps the caller's own object, so a\n * strip in place would change the caller's data. The strip works on a copy and\n * puts the copy on `holder`. When the copy cannot be set, it works in place. The\n * value rule V never changes a value in place; it puts a new value in the record.\n */\nfunction stripOwned(\n holder: { attributes?: Record<string, unknown> },\n rule: (key: string) => boolean = isContentKey,\n): number {\n const attrs = holder.attributes;\n if (\n !attrs ||\n typeof attrs !== 'object' ||\n !Object.keys(attrs).some((k) => rule(k) || reachesValueRule(k))\n ) {\n return 0;\n }\n const copy = { ...attrs };\n try {\n holder.attributes = copy;\n } catch {\n return stripAttributes(attrs, rule);\n }\n if (holder.attributes !== copy) return stripAttributes(attrs, rule);\n return stripAttributes(copy, rule);\n}\n\n/**\n * Remove customer prompt/completion content from `span`, in place.\n *\n * Walks the same surfaces as {@link applyMask} — span attributes, event\n * attributes, link attributes — because that is where content lives. The\n * attributes of a message event ({@link isContentEvent}) take the event rule,\n * {@link isContentEventAttribute}; all others take {@link isContentKey}. On every\n * surface, the value of a key of the value rule V (`llm.invocation_parameters`)\n * keeps its structure and loses only its content keys. No name is changed.\n *\n * `statusMessage` and exception text are deliberately NOT stripped: the\n * error-diagnosis product IS those fields, and this is a content-capture switch,\n * not a redaction feature. The `error_text` section of corpus v4 is the rule of\n * the gateway's PROJECT switch only (R41b).\n *\n * Returns the number of fields replaced. Never throws.\n */\nexport function stripContent(span: Span): number {\n let stripped = 0;\n\n if (span.attributes && typeof span.attributes === 'object') {\n stripped += stripAttributes(span.attributes);\n }\n\n if (Array.isArray(span.events)) {\n for (const event of span.events) {\n if (event?.attributes && typeof event.attributes === 'object') {\n const messageEvent = typeof event.name === 'string' && isContentEvent(event.name);\n stripped += stripOwned(event, messageEvent ? isContentEventAttribute : isContentKey);\n }\n }\n }\n\n if (Array.isArray(span.links)) {\n for (const link of span.links) {\n if (link?.attributes && typeof link.attributes === 'object') {\n stripped += stripOwned(link);\n }\n }\n }\n\n return stripped;\n}\n\n/** Strip content from every span in a batch, in place. Never throws. */\nexport function stripContentBatch(spans: Span[]): number {\n let total = 0;\n for (const span of spans) {\n try {\n total += stripContent(span);\n } catch {\n // A span we cannot walk must not take the batch down with it. It is also\n // the one span we could not gate, so say so at debug level.\n debug('Could not strip content from a span');\n }\n }\n return total;\n}\n\n/**\n * Mask a whole batch in place and report what it cost.\n *\n * Returns the field-level error count and the elapsed wall time so the caller\n * (the batch processor) owns the metric and the rate-limited warning — the\n * same split Python uses.\n */\nexport function applyMaskBatch(\n spans: Span[],\n mask: MaskFn,\n onError?: MaskErrorReporter,\n): { errors: number; elapsedMs: number } {\n let errors = 0;\n let firstKey: string | undefined;\n let firstError: unknown;\n\n const report: MaskErrorReporter = (key, error) => {\n errors++;\n if (firstKey === undefined) {\n firstKey = key;\n firstError = error;\n }\n onError?.(key, error);\n };\n\n const started = Date.now();\n for (const span of spans) {\n applyMask(span, mask, report);\n }\n const elapsedMs = Date.now() - started;\n\n if (errors > 0 && firstKey !== undefined) {\n // Attach the first failure to the returned shape via a side channel would\n // be noise; the processor logs from its own rate-limiter, so surface the\n // detail here at debug level for the case where the window suppressed it.\n let detail: string;\n try {\n detail = String(firstError);\n } catch {\n detail = typeof firstError; // a hostile `toString` must not break the export\n }\n debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${detail}`);\n }\n\n return { errors, elapsedMs };\n}\n\n/** Emit the rate-limited \"your mask is throwing\" warning. Exported for reuse. */\nexport function warnMaskErrors(batchErrors: number, totalErrors: number): void {\n warn(\n `the mask callback threw on ${batchErrors} field(s) in this batch ` +\n `(${totalErrors} since start). Those fields were replaced with ` +\n `\"${MASK_ERROR_MARKER}\" and the spans were exported intact — no span was ` +\n `dropped. Fix the callback; until then those fields carry no data.`,\n );\n}\n\n/** Emit the rate-limited \"your mask is slow\" warning. Exported for reuse. */\nexport function warnMaskSlow(spanCount: number, elapsedMs: number): void {\n warn(\n `masking ${spanCount} span(s) took ${elapsedMs} ms ` +\n `(budget ${MASK_BUDGET_MS_PER_SPAN * spanCount} ms, ` +\n `${MASK_BUDGET_MS_PER_SPAN} ms/span). Node is single-threaded: this time is ` +\n `taken from your event loop, so it delays your application as well as the ` +\n `export drain, and a queue that cannot drain drops spans (reason=queue_full). ` +\n `Keep the callback CPU-only: no I/O, no network, no unbounded retries.`,\n );\n}\n","/**\n * Batch span processor.\n *\n * Collects spans and exports them in batches based on:\n * - Batch size threshold (default: 500 spans — SDK-RELEASE-RULING.md §4.3 raised\n * this from 100; see `DEFAULT_BATCH_SIZE` below, which is the one true source)\n * - Time interval (default: 1000ms)\n * - Attribute product (`MAX_ATTRIBUTE_PAIRS_PER_BATCH`) and estimated serialized\n * size (`MAX_BATCH_BYTES`), both mirroring gateway constants\n *\n * Node.js is single-threaded — no locks needed.\n * Timer is unref()'d so it doesn't prevent process exit.\n */\n\nimport type { Span } from '../span.js';\nimport { ExportResult, type AckCounts, type ExporterDropReason, type SpanExporter } from './base.js';\nimport { DEFAULT_SHUTDOWN_TIMEOUT_S } from './retry.js';\nimport { debug, warn } from '../utils/log.js';\nimport { scrubText } from '../utils/scrub.js';\nimport {\n applyMaskBatch,\n stripContentBatch,\n warnMaskErrors,\n warnMaskSlow,\n MASK_BUDGET_MS_PER_SPAN,\n MASK_WARN_WINDOW_MS,\n type MaskFn,\n} from '../masking.js';\n\nexport interface BatchProcessorOptions {\n exporters: SpanExporter[];\n batchSize?: number;\n batchTimeoutMs?: number;\n maxQueueSize?: number;\n debug?: boolean;\n /**\n * Customer masking callback, `mask(key, value) => value`. Applied to every\n * content-bearing field of every span in this processor, once, BEFORE any\n * exporter sees the batch. See `../masking.ts`.\n */\n mask?: MaskFn;\n /**\n * Whether customer prompt/completion content may leave the process.\n * **Defaults to `false`** here, which is NOT the user default: `resolveConfig`\n * defaults to `true`, and `init()` always passes the resolved value. This\n * `false` applies only to a processor that is built by hand without it\n * (fail-closed). When false, every content-keyed attribute is replaced on the\n * export path before any exporter runs. See `../masking.ts` `stripContent`.\n */\n traceContent?: boolean;\n}\n\n/**\n * F-SDKCB-001 §5 (option J) — reason labels for a discarded span.\n *\n * One integer conflating an under-provisioned queue, a dead gateway and a\n * redeploy is the ambiguity W1/W3 was written against: the three causes demand\n * three different operator responses. The server side already landed on this\n * shape as `dropped{stage,reason,project_id}` (F-HONEST-001). Mirrors the\n * Python `DROP_*` constants in `exporters/batch.py`.\n *\n * `unacknowledged`: the backend's ack accounts for fewer spans than the batch\n * sent (after the counts are clamped to the batch size). Those spans are in no\n * other counter, so they are counted here: exported + rejected + dropped then\n * equals the spans that ended.\n *\n * `quota_exceeded` (S-1): the monthly event quota is used up. The backend discarded a batch, or\n * the queue overflowed while the exporter was paused for the quota. While it is paused the\n * processor keeps ended spans in the queue and sends them when the pause ends. See `quota.ts`.\n *\n * `retry_exhausted` (W2-1c): the exporter retried the batch until its retry horizon\n * (`retryHorizonS`, or its `maxRetries`) and the endpoint did not take it. A gateway outage\n * that is longer than the horizon loses these spans.\n *\n * `too_large` (W2-1c): the endpoint answered 413 for a batch, and again for its half after one\n * split.\n *\n * `queue_full`: the queue was full when a span arrived. Since W2-1c the OLDEST queued span is\n * dropped and the new one is kept (through 0.10.0 the new span was dropped).\n */\nexport type DropReason =\n | 'queue_full'\n | 'transport_refused'\n | 'shutdown_residue'\n | 'unacknowledged'\n | 'quota_exceeded'\n | 'retry_exhausted'\n | 'too_large';\n\n/** The reasons an exporter can name for a failed batch (`takeDropReason`). */\nconst DECIDED_FAILURES: ReadonlySet<string> = new Set([\n 'transport_refused',\n 'retry_exhausted',\n 'shutdown_residue',\n]);\n\n/** The reasons an exporter can name in `AckCounts.dropped`. */\nconst DECIDED_DROPS: ReadonlySet<string> = new Set([\n 'transport_refused',\n 'retry_exhausted',\n 'shutdown_residue',\n 'too_large',\n]);\n\n/** The end time of a span in ms since the epoch, or `null` (a span-like stand-in). */\nfunction endMs(span: Span | undefined): number | null {\n const end = (span as { endTime?: unknown } | undefined)?.endTime;\n if (typeof end !== 'string') return null;\n const ms = Date.parse(end);\n return Number.isFinite(ms) ? ms : null;\n}\n\n/** The earliest end time in `spans`, or `null` when no span has one. */\nfunction oldestEndMs(spans: Span[]): number | null {\n let oldest: number | null = null;\n for (const span of spans) {\n const ms = endMs(span);\n if (ms !== null && (oldest === null || ms < oldest)) oldest = ms;\n }\n return oldest;\n}\n\n/** Outcome of one `_exportBatch()` round.\n *\n * `shutdown()`'s drain loop must tell \"the queue is empty\" from \"a batch was\n * taken and nobody accepted it\" — RULING §4's no-SUCCESS exit. Without that\n * distinction the loop would spin for the whole budget against a dead\n * transport, and (because the bounded re-queue keeps the queue non-empty)\n * would never terminate at all. */\nconst enum Round {\n Empty = 0,\n Delivered = 1,\n Failed = 2,\n /** an export was already in flight (`_flushing`); this call made no progress */\n Busy = 3,\n /**\n * Every exporter that delivers is paused for the monthly quota (S-1): nothing was taken from\n * the queue. The spans wait in the queue (bounded as always) and go out when the pause ends.\n */\n Paused = 4,\n}\n\n/** The value `raceDeadline` gives when the deadline comes first. */\nconst DEADLINE = Symbol('deadline');\n\n/**\n * Wait for `p`, but not longer than `ms`. The timer is cleared on both paths, so\n * it never keeps the process alive. `p` is not cancelled: it continues, and the\n * caller decides what its late answer means.\n */\nasync function raceDeadline<T>(p: Promise<T>, ms: number): Promise<T | typeof DEADLINE> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<typeof DEADLINE>((resolve) => {\n timer = setTimeout(() => resolve(DEADLINE), Math.max(0, ms));\n });\n try {\n return await Promise.race([p, deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Describe a thrown value for a debug line. Never throws (a Symbol, a hostile `toString`). */\nfunction describeThrown(e: unknown): string {\n // An error text can hold a key: scrubbed (`utils/scrub.ts`; the processor does not\n // know the exporter's key, so RISICARE_API_KEY and the forms of it are removed).\n return scrubText(e, []);\n}\n\n/**\n * Wait for an exporter's own `shutdown()`, but not longer than `ms`. A rejection\n * or a synchronous throw is logged at debug level. The timer is cleared.\n */\nasync function shutdownExporter(exporter: SpanExporter, ms: number): Promise<void> {\n try {\n const outcome = await raceDeadline(Promise.resolve().then(() => exporter.shutdown()), ms);\n if (outcome === DEADLINE) debug(`${exporter.name}.shutdown() did not finish within ${ms} ms`);\n } catch (e) {\n debug(`Error shutting down ${exporter.name}: ${describeThrown(e)}`);\n }\n}\n\n/** The batch that an export round has taken off the queue and not yet settled. */\ninterface InFlight {\n /** The batch: the key that the exporter's `abort(spans)` uses. */\n spans: Span[];\n size: number;\n /** Set by `shutdown()` when it stops waiting. A late answer then changes nothing. */\n abandoned: boolean;\n /** The earliest end time of the batch (ms since the epoch), for `oldestPendingAgeS`. */\n oldestEndMs: number | null;\n}\n\n/**\n * RULING §4 delegates this number with a derive-and-justify obligation.\n * `shutdown()` runs `exporter.shutdown()` AFTER the drain, so a drain that\n * spends the whole budget starves it.\n *\n * The built-in `HttpExporter.shutdown()` is a literal no-op — native fetch\n * needs no cleanup (`exporters/http.ts:159-161`) — so for the shipped exporter\n * the measured cost is ZERO. The reserve is therefore a policy allowance for a\n * CUSTOMER-supplied exporter, whose `shutdown(): Promise<void> | void`\n * (`exporters/base.ts:16`) we cannot measure. Held at 100 ms to match the\n * Python constant — the two SDKs must end with the same contract, and Python's\n * value is measured (see `_SHUTDOWN_RESERVE_MS` in `exporters/batch.py` and\n * `fix-workstream/perf/sdk_exporter_shutdown_cost_probe.py`). Against the\n * binding 2,000 ms SIGTERM budget this leaves 1,900 ms of drain.\n */\nconst SHUTDOWN_RESERVE_MS = 100;\n\n/**\n * SDK-RELEASE-RULING.md §4.3 — ONE shutdown budget, on every teardown path.\n *\n * 5,000 ms is bounded from ABOVE by something outside our control: the SDK's\n * shutdown runs inside the application's, which runs inside the container's\n * termination grace period. The tightest common default is `docker stop` at\n * 10 s (k8s `terminationGracePeriodSeconds` 30 s; systemd `TimeoutStopSec`\n * 90 s), and taking more than half of the tightest is hostile to the app's own\n * cleanup.\n *\n * ⚠ WHY A LONGER BUDGET IS NEARLY FREE: the drain exits on the FIRST round that\n * does not deliver (`Round.Delivered` check below). A dead transport costs one\n * round, not the budget. It is spent only while the transport is SUCCEEDING.\n *\n * ⚠ `client.ts` DERIVES its signal-handler backstop from this rather than\n * repeating a literal. Before the ruling both were an independent `5000`, so\n * the backstop's `process.exit(1)` raced the drain it exists to protect —\n * killing it at the deadline, with the wrong exit code, before the residue\n * warning could print. Do not re-introduce a second literal.\n *\n * Mirrors `SHUTDOWN_BUDGET_MS` in `client.py`.\n *\n * ⚠ W2-1c (contract spec W2-1, 2026-10-24) sets the default to 10 s (`shutdownTimeoutS`). The\n * exporter retries a batch for minutes now, so the drain calls `endRetries()` on each exporter:\n * a failed attempt in the drain is not retried, and the statement above stays true. `docker\n * stop` waits 10 s by default, so a container that needs time for its own cleanup sets\n * `shutdownTimeoutS` lower or raises its grace period. This constant is the default; the client\n * passes its own `shutdownTimeoutS`.\n */\nexport const SHUTDOWN_BUDGET_MS = DEFAULT_SHUTDOWN_TIMEOUT_S * 1000;\n\n/**\n * The default budget of `flush()`: 5,000 ms, as in Python (`flush(timeout_ms=5000)`). It was\n * `SHUTDOWN_BUDGET_MS` until W2-1c raised that to 10 s; the spec changes `shutdown()` only.\n */\nexport const FLUSH_BUDGET_MS = 5000;\n\n/** The largest delay that `setTimeout` accepts (2**31 - 1 ms). A larger one fires at once. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\n/**\n * The budget that `flush(timeoutMs)` and `shutdown(timeoutMs)` use.\n *\n * A value that is not a finite number (`undefined`, `NaN`, `Infinity`, a string,\n * `null`) gives the default: `fallback`, which is `FLUSH_BUDGET_MS` unless the caller\n * names another (`shutdown()` gives `SHUTDOWN_BUDGET_MS`). A negative value gives 0. A\n * value above 2**31 - 1 gives 2**31 - 1. Through 0.7.1 such values reached\n * `setTimeout` and string concatenation as they were: `flush(Infinity)` and\n * `flush('3000')` returned `false` at once, and `shutdown(NaN)` dropped every\n * span, on a healthy server.\n */\nexport function normalizeTimeoutMs(value: unknown, fallback: number = FLUSH_BUDGET_MS): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return fallback;\n if (value < 0) return 0;\n return Math.min(value, MAX_TIMEOUT_MS);\n}\n\n/**\n * The `transport_refused` warning is rate-limited to the exporter's existing\n * window (`exporters/http.ts`), so a flaky network cannot spam customer logs.\n * The `shutdown_residue` warning is NOT rate-limited (RULING §5): it fires at\n * most once per process lifetime by construction, so a window buys nothing and\n * would suppress the only signal in any process that had already warned about\n * the breaker — exactly the correlated case where the customer most needs it.\n */\nconst REFUSAL_WARN_WINDOW_MS = 300_000;\n\n/**\n * SDK-RELEASE-RULING.md §4.3 — the default batch size, raised 100 -> 500.\n *\n * DERIVED, not picked. `shutdown()`'s drain is strictly serial — one export per\n * round-trip — so the most it can save is\n * ceiling = floor((budget - reserve) / RTT) x batchSize\n * and the requirement is that it drain the SDK's OWN maximum queue\n * (`maxQueueSize` = 10,000, the most it can ever be holding) at the design\n * target RTT = 100 ms:\n * batchSize >= 10,000 x RTT / (5,000 - 100) -> 204 at 100 ms, 510 at 250 ms\n * 500 satisfies it to the 250 ms trans-Pacific tail and sits 1.55x under the\n * ceiling the gateway's attribute-product cap imposes (below).\n *\n * ⚠ NEITHER THIS NOR THE BUDGET IS SUFFICIENT ALONE — measured, ruling §2. At\n * 100 ms RTT: budget alone leaves 51 % lost, batch alone leaves 60 % lost at the\n * tail, both together lose nothing. Do not \"simplify\" one back.\n *\n * Mirrors `DEFAULT_BATCH_SIZE` in `exporters/batch.py` — the two SDKs must end\n * with the same contract.\n */\nexport const DEFAULT_BATCH_SIZE = 500;\n\n/**\n * The gateway refuses a request whose summed attribute count exceeds this\n * (`MAX_ATTRIBUTE_PAIRS_PER_REQUEST`, `handlers/ingest.rs`, F-ACKRSV-001) —\n * WHOLE request, never truncated, and the exporter treats that 4xx as a\n * failure, retries it futilely and finally discards the batch as\n * `transport_refused`. The cap is `sum(span.attributes.length)`, i.e. LINEAR in\n * batch size: at batch B a customer is refused above `24,000 / B` attributes\n * per span — 240 at B=100, but only 48 at B=500.\n *\n * Without this bound, raising the default would silently break every customer\n * between those two densities: accepted today, whole-request-refused tomorrow,\n * with no action on their part. So the batch is bounded on BOTH axes, and the\n * raise becomes strictly no-worse-than-today on the attribute axis.\n *\n * ⚠ COUPLING, DECLARED (ruling §4.5) — AND THE DIRECTIONS ARE NOT SYMMETRIC.\n * ⚠ CORRECTED 2026-07-27 (F-SDKBYTES-001 §4.1). This comment used to read\n * \"Stale in either direction is SAFE — too low means slightly smaller batches,\n * too high means the gateway refuses exactly as it does today.\" The second half\n * is FALSE, and the error mattered because it licenses a unilateral change on\n * the gateway side that this SDK cannot survive:\n *\n * • STALE LOW (SDK constant < gateway cap) — SAFE, unconditionally. The SDK\n * assembles smaller batches than it needed to; every one is accepted.\n * • STALE HIGH (SDK constant > gateway cap) — safe ONLY while the gateway's\n * cap does not DECREASE. If it is lowered, this SDK assembles batches the\n * gateway now refuses: requests that are accepted TODAY begin returning\n * 4xx, the exporter retries each one futilely and discards the whole batch\n * as `transport_refused`. That is a NEW refusal caused by the mismatch —\n * not \"exactly as it does today\".\n *\n * ⇒ RAISING the gateway cap is safe to do unilaterally. LOWERING it is not: the\n * SDK constant must move first and be adopted, and `F-SDKVER-001` records\n * that nothing pins or even observes an SDK version server-side, so \"adopted\"\n * is weeks-to-never rather than a deploy.\n *\n * The gateway remains the enforcer; this only stops OUR DEFAULT from moving a\n * customer across ITS boundary.\n */\nexport const MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24_000;\n\n/**\n * The per-batch SERIALIZED-BYTE bound (F-SDKBYTES-001) — the third axis.\n *\n * `SDK-RELEASE-RULING.md` §4.5 bounded the batch on span COUNT and attribute\n * PRODUCT and explicitly left BYTES open: \"a customer putting a 1 MB string in\n * an attribute can exceed the body limit at *any* batch size, and B=500 makes\n * it 5x more reachable. I did not guard this.\"\n *\n * MEASURED (`perf/sdk_batch_byte_ceiling_probe.py`, raw\n * `perf/sdk-batch-byte-ceiling.json`; its JS cross-check arm compiles\n * `src/span.ts` itself rather than trusting `dist/`):\n *\n * batch=500 crosses max_body_size (10,485,760 B) at 20,971 B/span\n * batch=100 crosses it at 104,857 B/span\n *\n * and the ruling's \"16x headroom\" quoted only the measured FLOOR. Against the\n * measured MAXIMUM realistic span (13,487 B) a 500-span batch is 6,743,500 B —\n * 1.55x headroom, not 16x. The count raise spent most of the byte margin.\n *\n * WITHOUT IT, MEASURED (probe ARM 2): the gateway answers 413, and the exporter\n * does NOT treat 413 as permanent — `http.ts` maps every non-2xx that is not\n * 408/504 to FAILURE and retries it. On a permanently-413 batch: 12 HTTP\n * requests (4 re-queue rounds x 3 exporter attempts), then the ENTIRE batch\n * discarded as `transport_refused`. Counted and warned — but total loss.\n * (W2-1c changed the exporter side: a 413 now splits the batch in two one time, and a half that\n * gets 413 again is dropped as `too_large`. This bound still keeps realistic batches under the\n * limit, so that the split is the exception.)\n *\n * THE ESTIMATE, AND WHICH WAY IT ERRS. Serialized size is not knowable without\n * serializing, and serializing to measure would double the export cost. So the\n * batch is bounded on an ESTIMATE:\n *\n * string -> 2 + utf8ByteLength(s), the bytes `fetch` will send for\n * the raw characters\n * number/bool/null -> a fixed allowance; containers recurse to depth 4\n * anything else -> a fixed allowance (see `EST_OPAQUE_VALUE_BYTES`)\n *\n * ⚠ ASYMMETRY WITH PYTHON, DELIBERATE. Each SDK estimates against ITS OWN\n * encoder. `JSON.stringify` emits non-ASCII RAW (UTF-8 on the wire);\n * `json.dumps` escapes it to `\\uXXXX`. Measured: a 9,525-char CJK attribute is\n * 28,859 B from JS and ~2x that from Python. Mirroring Python's per-character\n * multiplier here would over-estimate every non-ASCII JS batch by ~4x.\n *\n * ⚠ THE ONE UNDER-ESTIMATE, NAMED: JSON escaping. A `\"` costs 2 bytes and a\n * control character 6; `utf8ByteLength` charges 1 for each. The 20 % margin\n * below is what absorbs it — a batch may be up to ~25 % escape characters BY\n * COUNT before the estimate stops covering the real body. Past that the gateway\n * refuses, exactly as it does today: no new failure mode, the bound is simply\n * not helping. Stated rather than engineered away because counting escapes is a\n * second O(bytes) scan.\n *\n * THE FRACTION: 8 MiB is 80 % of the gateway's 10 MiB default. Below it the\n * measured realistic corpus does not bind at batch 500 (1.24x under this\n * budget); above it, the 20 % is the escape margin.\n *\n * ⚠ COUPLING, DECLARED, with the SAME asymmetry as the attribute cap above:\n * stale LOW is unconditionally safe; stale HIGH is safe only while\n * `max_body_size` does not DECREASE.\n */\nexport const MAX_BATCH_BYTES = 8 * 1024 * 1024; // 8,388,608 B = 80 % of max_body_size\n\nconst SPAN_ENVELOPE_BYTES = 512; // typed camelCase fields; a minimal span is ~250 B\nconst CHILD_ENVELOPE_BYTES = 128; // per event / link, before its strings\nconst SCALAR_BYTES = 24; // widest JSON number repr\nconst LITERAL_BYTES = 5; // \"false\" / \"null\"\nconst EST_MAX_DEPTH = 4;\n/**\n * Charge for a value the ladder cannot walk (a class instance, a Map, anything\n * past `EST_MAX_DEPTH`). ⚠ Unlike Python — whose `_coerce_attribute_value`\n * truncates its `str()` fallback at 4,096 chars, making the same charge there a\n * genuine BOUND — JS has no truncation at all (`F-SDKATTRLEN-001`), so this is\n * an ALLOWANCE and a deeply-nested object can exceed it. The gateway refuses\n * that shape exactly as it does today.\n */\nconst EST_OPAQUE_VALUE_BYTES = 4_096;\n\n/**\n * UTF-8 byte length, without allocating the encoded copy.\n *\n * `Buffer.byteLength` is a single native scan and is what `fetch` will actually\n * put on the wire for the raw characters. The fallback multiplier 3 is a true\n * upper bound on UTF-8 bytes per UTF-16 code unit (a BMP code point is 1 unit\n * and at most 3 bytes; an astral one is 2 units and 4 bytes, i.e. 2 per unit),\n * so a Buffer-less runtime errs HIGH rather than low.\n */\nconst utf8ByteLength: (s: string) => number =\n typeof Buffer !== 'undefined' && typeof Buffer.byteLength === 'function'\n ? (s) => Buffer.byteLength(s, 'utf8')\n : (s) => s.length * 3;\n\nfunction estStringBytes(s: string): number {\n return 2 + utf8ByteLength(s);\n}\n\nfunction estValueBytes(v: unknown, depth = 0): number {\n if (typeof v === 'string') return estStringBytes(v);\n if (v === null || v === undefined || typeof v === 'boolean') return LITERAL_BYTES;\n if (typeof v === 'number' || typeof v === 'bigint') return SCALAR_BYTES;\n if (Array.isArray(v) && depth < EST_MAX_DEPTH) {\n let total = 2 + Math.max(0, v.length - 1);\n for (const item of v) total += estValueBytes(item, depth + 1);\n return total;\n }\n if (\n typeof v === 'object' &&\n depth < EST_MAX_DEPTH &&\n Object.getPrototypeOf(v as object) === Object.prototype\n ) {\n let total = 2;\n for (const [k, val] of Object.entries(v as Record<string, unknown>)) {\n total += estStringBytes(k) + 2 + estValueBytes(val, depth + 1);\n }\n return total;\n }\n return EST_OPAQUE_VALUE_BYTES;\n}\n\nfunction estMappingBytes(m: Record<string, unknown>): number {\n let total = 0;\n for (const [k, v] of Object.entries(m)) total += estStringBytes(k) + 2 + estValueBytes(v);\n return total;\n}\n\n/**\n * Estimated serialized bytes this span contributes to a request body, or the\n * fixed envelope if the object is not span-shaped.\n *\n * ⚠ Defensive in exactly the shape `spanAttrCount` is, and for the same reason:\n * TypeScript types `_queue` as `Span[]`, but nothing stops a JS caller or a test\n * double from queueing something else. Throwing from inside the export path\n * would break export for the whole batch. On any surprise this returns the\n * envelope, which can only make the bound LESS binding — never more, and never\n * a wedge.\n */\nfunction spanBytesEstimate(span: Span): number {\n try {\n const s = span as unknown as Record<string, unknown>;\n let total = SPAN_ENVELOPE_BYTES;\n for (const field of ['name', 'statusMessage'] as const) {\n if (typeof s[field] === 'string') total += estStringBytes(s[field] as string);\n }\n const attrs = s.attributes;\n if (attrs != null && typeof attrs === 'object' && !Array.isArray(attrs)) {\n total += estMappingBytes(attrs as Record<string, unknown>);\n }\n for (const key of ['events', 'links'] as const) {\n const coll = s[key];\n if (!Array.isArray(coll)) continue;\n for (const child of coll) {\n total += CHILD_ENVELOPE_BYTES;\n const ca = (child as Record<string, unknown> | null)?.attributes;\n if (ca != null && typeof ca === 'object' && !Array.isArray(ca)) {\n total += estMappingBytes(ca as Record<string, unknown>);\n }\n }\n }\n return total;\n } catch {\n return SPAN_ENVELOPE_BYTES;\n }\n}\n\n/**\n * Attribute count for the per-batch product bound, or 0 if unknowable.\n *\n * ⚠ Defensive for the same reason the Python `_span_attr_count` is: TypeScript\n * types `_queue` as `Span[]`, but nothing stops a JS caller (or a test double)\n * from queueing an object without `attributes`. Reading `.length` off\n * `undefined` would throw from inside the export path and break export for the\n * whole batch. An object with no countable attributes contributes 0, which can\n * only make the bound less binding, never more.\n */\nfunction spanAttrCount(span: Span): number {\n const attrs = (span as { attributes?: unknown }).attributes;\n if (attrs == null) return 0;\n if (attrs instanceof Map) return attrs.size;\n if (typeof attrs === 'object') return Object.keys(attrs as object).length;\n return 0;\n}\n\nexport class BatchSpanProcessor {\n private readonly _exporters: SpanExporter[];\n private readonly _batchSize: number;\n private readonly _batchTimeoutMs: number;\n private readonly _maxQueueSize: number;\n // ⚠ NO `_debug` FIELD. It existed, was assigned, and was read by NOTHING —\n // `tsc --noEmit` had been RED on this package at HEAD for it (TS6133), which\n // survived because `ci-local.sh` runs this package's vitest and never its\n // typecheck, and `prepublishOnly` runs `build && test` — also no typecheck.\n // Filed F-SDKJSTYPECHECK-001. Debug output here is gated globally by\n // `setDebug()` in `../utils/log.ts`, so a per-processor flag was always\n // redundant; Python's `self._debug` exists because `logging` has no such\n // global switch.\n\n private _queue: Span[] = [];\n private _timer: ReturnType<typeof setInterval> | null = null;\n private _started = false;\n private _flushing = false;\n private _inFlight: InFlight | null = null;\n /**\n * The `shutdown()` that runs, or ran. A second `shutdown()` returns it, and a\n * `flush()` that comes while it runs waits for it (inside its own deadline).\n */\n private _closing: Promise<void> | null = null;\n /**\n * True from the start of the drain of `shutdown()` until its loop ends and the\n * residue is counted (no `await` between those two points). A span that ends\n * in this time joins the drain. After it, the processor can take no span.\n */\n private _drainOpen = false;\n private _lateSpanWarned = false;\n private _beforeExitHandler: (() => void) | null = null;\n\n // Retry tracking for failed batches (Audit #5)\n private _retryCounts = new Map<string, number>();\n /**\n * The HTTP requests that the failed rounds of each re-queued span sent, by span id (issue\n * #57). It has the same life as `_retryCounts`: `_forgetRetry` ends both. NaN = a round for\n * which the exporter did not say. Empty for an exporter that does not state it.\n */\n private _retryRequests = new Map<string, number>();\n private static readonly MAX_RETRIES = 3;\n\n private _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;\n private _lastUnackWarnAt = Number.NEGATIVE_INFINITY;\n /**\n * The loss total (dropped + rejected) that the last finished `flush()` saw.\n * A flush reports a loss that is new since then, one time.\n */\n private _lossMark = 0;\n\n // ── Masking (see `../masking.ts`) ──────────────────────────────────────────\n private readonly _mask: MaskFn | undefined;\n // ── Content capture gate (see `../masking.ts`) ─────────────────────────────\n // Fail-closed: an unspecified value means \"do not capture\". This is the ONE\n // place the gate runs for BOTH content paths — provider capture AND hand-set\n // attributes — so it must not be conditional on anything a caller might\n // forget to pass. Python twin: `BatchSpanProcessor._trace_content`.\n private readonly _traceContent: boolean;\n private _lastMaskWarnAt = Number.NEGATIVE_INFINITY;\n private _lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;\n\n // Metrics\n /** DEPRECATED flat total. Retained as the exact SUM of\n * `droppedSpansByReason` so existing readers keep working (RULING §5\n * back-compat — the same deprecate-and-alias shape this codebase used for\n * `complete`->`settled` and `spans_flushed_total`). Prefer the labelled\n * record: one integer cannot tell an under-provisioned queue from a dead\n * gateway from a redeploy. */\n droppedSpans = 0;\n droppedSpansByReason: Record<DropReason, number> = {\n queue_full: 0,\n transport_refused: 0,\n shutdown_residue: 0,\n unacknowledged: 0,\n quota_exceeded: 0,\n retry_exhausted: 0,\n too_large: 0,\n };\n exportedSpans = 0;\n /**\n * Export requests (W2-1c): for the SDK's HTTP exporter one for each HTTP request (each retry\n * and each half of a split counts), for another exporter one for each `export()` call.\n */\n attempts = 0;\n /**\n * Spans of a 413 split that `endRetries()` left unsent in the drain of `shutdown()`. They are\n * counted as `shutdown_residue` in their round; the residue WARNING adds them to its\n * in-export number.\n */\n private _drainResidue = 0;\n /**\n * Spans that the backend acknowledged as REJECTED (the ack's `rejected`). They\n * are not stored and are not retried. An exporter without an ack adds nothing.\n */\n rejectedSpans = 0;\n /** Export ATTEMPTS, not a span count. */\n failedExports = 0;\n /**\n * Fields whose mask callback threw and were replaced with\n * `MASK_ERROR_MARKER`. A FIELD count, not a span count — one span can\n * contribute several. Non-zero means those fields carry a marker instead of\n * data: a customer-code bug, not a transport one.\n */\n maskErrors = 0;\n\n constructor(options: BatchProcessorOptions) {\n this._exporters = [...options.exporters];\n\n // batchSize: clamp to [1, 10000] AND warn on out-of-range — silent\n // clamping is a debugging tar pit (CON-257 / P1-3). Mirrors Python.\n const requestedBatchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;\n const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 10_000));\n if (clampedBatchSize !== requestedBatchSize) {\n warn(\n `batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`,\n );\n }\n this._batchSize = clampedBatchSize;\n\n this._batchTimeoutMs = options.batchTimeoutMs ?? 1000;\n this._maxQueueSize = options.maxQueueSize ?? 10000;\n this._mask = options.mask;\n // Fail-closed, NOT the user default (that is `true`, in `resolveConfig`).\n // `Client` always passes the resolved value; this `false` is for a processor built by hand.\n this._traceContent = options.traceContent ?? false;\n }\n\n start(): void {\n if (this._started) return;\n this._started = true;\n\n // Periodic flush timer — unref so it doesn't keep process alive\n this._timer = setInterval(() => {\n void this._exportBatch();\n }, this._batchTimeoutMs);\n this._timer.unref();\n\n // Flush on process exit (Audit #3: use .once, not .on; await, not void)\n this._beforeExitHandler = () => {\n void this.shutdown();\n };\n process.once('beforeExit', this._beforeExitHandler);\n }\n\n /** Record `count` discarded spans under `reason`.\n *\n * `droppedSpans` is maintained as the exact sum of the labelled counters\n * (RULING §5 back-compat), so the locked pins — which read the flat\n * integer — stay meaningful. */\n private _recordDropped(reason: DropReason, count = 1): void {\n this.droppedSpans += count;\n this.droppedSpansByReason[reason] += count;\n }\n\n /**\n * Run the customer mask over a batch, in place. Never throws.\n *\n * Failure semantics are ruled in `../masking.ts`: a field whose mask throws\n * becomes `MASK_ERROR_MARKER` and the span is kept. The counter is per FIELD;\n * both warnings are rate-limited to one per window so a mask that throws on\n * every span cannot flood the customer's logs — the same shape as the\n * transport-refusal warning above.\n */\n private _applyMask(batch: Span[]): void {\n const mask = this._mask;\n if (mask === undefined) return;\n\n const { errors, elapsedMs } = applyMaskBatch(batch, mask);\n const now = Date.now();\n\n if (errors > 0) {\n this.maskErrors += errors;\n if (now - this._lastMaskWarnAt > MASK_WARN_WINDOW_MS) {\n this._lastMaskWarnAt = now;\n warnMaskErrors(errors, this.maskErrors);\n }\n }\n\n if (\n elapsedMs > MASK_BUDGET_MS_PER_SPAN * batch.length &&\n now - this._lastSlowMaskWarnAt > MASK_WARN_WINDOW_MS\n ) {\n this._lastSlowMaskWarnAt = now;\n warnMaskSlow(batch.length, elapsedMs);\n }\n }\n\n /**\n * Drain what we hold, or name what we could not (F-SDKDRAIN-001).\n *\n * Per RULING §4 (option E, hard-bounded) the drain loops until ONE of: the\n * queue is empty; the deadline expires; or a full round completes with no\n * exporter returning SUCCESS.\n *\n * ⚠ The `_flushing` handling is load-bearing, and `SDKDRAIN_JS_004` exists\n * to catch its absence. `_exportBatch()` returns immediately when an export\n * is already in flight (`:171`), so a loop that merely calls it again makes\n * NO progress and abandons the queue exactly as before — measured at 900 of\n * 1,000. We await a tick instead, the shape `flush()` already models.\n *\n * The deadline is a hard wall-clock bound. Each round is raced against the\n * budget that remains. At the deadline, `shutdown()` stops the round in flight\n * through the exporter's optional `abort()`. That stopped round changes no\n * counter, does not move the circuit breaker and re-queues nothing. Through\n * 0.7.1 the deadline was checked only between rounds, so one round against a\n * silent server (3 attempts x 5 s) held a 5,000 ms shutdown for 15 s.\n *\n * Anything still queued when the loop stops, AND a batch whose export was\n * stopped, is COUNTED as `shutdown_residue` and announced with ONE WARNING\n * that gives both numbers. The server may have received the spans of the\n * stopped export. The warning is the primary signal, not the counter: a\n * counter incremented inside `shutdown()` is written to memory about to be\n * freed and has no reader (RULING §2 / §8.2).\n *\n * Each exporter's own `shutdown()` gets the time that is left of the budget.\n * An exporter that does not finish in that time is not awaited.\n *\n * Limit: the abort does not stop a TLS handshake that stalls. Measured, such a\n * handshake kept the process alive about 10 s after `shutdown()` returned.\n *\n * A second call, while the first runs or after it ended, returns the promise\n * of the first one. It does not return before the first drain ends.\n *\n * @param timeoutMs - The budget (default `SHUTDOWN_BUDGET_MS`, 10,000 ms; the client passes\n * its `shutdownTimeoutS`). See `normalizeTimeoutMs` for the values that are not a finite\n * number.\n */\n shutdown(timeoutMs: number = SHUTDOWN_BUDGET_MS): Promise<void> {\n if (!this._started) return this._closing ?? Promise.resolve();\n this._closing = this._shutdown(timeoutMs);\n return this._closing;\n }\n\n private async _shutdown(timeoutMs: number): Promise<void> {\n timeoutMs = normalizeTimeoutMs(timeoutMs, SHUTDOWN_BUDGET_MS);\n this._started = false;\n this._drainOpen = true;\n this._drainResidue = 0;\n // W2-1c: no retry waits in the drain. A call that waits makes one more attempt at once, and\n // a failed attempt is not retried, so a dead endpoint costs one attempt for each batch and\n // not the whole budget. A batch that is not delivered that way stays in the queue and is\n // counted as `shutdown_residue` below.\n for (const exporter of this._exporters) {\n try {\n exporter.endRetries?.();\n } catch (e) {\n debug(`Error ending the retries of ${exporter.name}: ${describeThrown(e)}`);\n }\n }\n\n if (this._timer) {\n clearInterval(this._timer);\n this._timer = null;\n }\n\n // Remove process listener to prevent leak (Audit #3)\n if (this._beforeExitHandler) {\n process.removeListener('beforeExit', this._beforeExitHandler);\n this._beforeExitHandler = null;\n }\n\n // Halve rather than underflow on a tiny budget: shutdown(200) still gets\n // 100 ms of drain instead of none.\n const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);\n const shutdownDeadline = Date.now() + timeoutMs;\n const drainDeadline = shutdownDeadline - reserveMs;\n\n while (this._queue.length > 0 || this._flushing) {\n const remaining = drainDeadline - Date.now();\n if (remaining <= 0) break;\n // A hard wall-clock bound: the round is raced against the budget. At the\n // deadline the round in flight is stopped below.\n const outcome = await raceDeadline(this._exportBatch(), remaining);\n if (outcome === DEADLINE) break;\n if (outcome === Round.Busy) {\n // An export is mid-await. Yield rather than spin on a no-op call.\n await new Promise((r) => setTimeout(r, 1));\n continue;\n }\n if (outcome !== Round.Delivered) {\n // Paused -> the monthly quota pause is on; the spans cannot go out now, and shutdown()\n // counts what is left as `shutdown_residue`.\n // Empty -> nothing left, we are done.\n // Failed -> no exporter accepted this round; a further round cannot\n // help and would spin to the deadline on precisely the path\n // where there is nothing to save.\n break;\n }\n }\n\n // The drain takes no more spans from here on. This line and the residue\n // below have no `await` between them: a span that ends before them is in\n // `queued`, and one that ends after them is counted by `onSpanEnd`.\n this._drainOpen = false;\n\n // Once shutdown() has returned, holding IS abandoning: the timer is\n // cleared, the exit listener is gone, nothing will ever export these.\n //\n // A batch whose export did not finish inside the budget is abandoned too. It\n // is counted HERE, and its late answer changes no counter and re-queues\n // nothing (see `_exportBatch`).\n const queued = this._queue.length;\n const flight = this._inFlight;\n const inFlight = flight !== null && !flight.abandoned ? flight.size : 0;\n if (flight !== null && !flight.abandoned) {\n flight.abandoned = true;\n // Stop the abandoned export, so that its request, retries and backoff do\n // not keep the process alive. Without this, it ran on for up to 3\n // attempts of 5 s after shutdown() returned. An exporter without\n // `abort()` is left alone.\n for (const exporter of this._exporters) {\n try {\n exporter.abort?.(flight.spans);\n } catch (e) {\n debug(`Error aborting ${exporter.name}: ${describeThrown(e)}`);\n }\n }\n }\n // Counted already, in their round; named here (see `_drainResidue`).\n const drained = this._drainResidue;\n this._drainResidue = 0;\n const counted = queued + inFlight;\n const unfinished = inFlight + drained;\n const residue = counted + drained;\n if (residue > 0) {\n this._queue.length = 0;\n if (counted > 0) this._recordDropped('shutdown_residue', counted);\n // NOT rate-limited, by ruling. Names the counts AND the reason.\n if (this._quotaPaused()) {\n // S-1: the cause is the monthly quota pause, not the shutdown budget.\n warn(\n `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ` +\n `${queued} still queued and ${unfinished} in an export that shutdown() stopped. ` +\n `The monthly event quota is used up and export is paused until the next probe, so ` +\n `these spans could not be sent. A longer shutdown timeout does not help. Upgrade ` +\n `the plan or wait for the quota to reset.`,\n );\n } else {\n warn(\n `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ` +\n `${queued} still queued and ${unfinished} in an export that shutdown() stopped. ` +\n (inFlight > 0\n ? `The server may have received the ${inFlight} span(s) of the stopped export. `\n : '') +\n `All ${residue} were not confirmed as delivered, and are counted as dropped. ` +\n `The ${timeoutMs} ms shutdown ` +\n `budget expired or the transport stopped accepting. Pass a larger timeout to ` +\n `shutdown(timeoutMs), or raise your container's termination grace period, to lose less.`,\n );\n }\n }\n\n // Shutdown exporters, inside the time that is left. An exporter whose own\n // shutdown() is slow or never settles must not hold the process: through\n // 0.7.1 a 4 s exporter shutdown held shutdown(1000) for 4 s.\n for (const exporter of this._exporters) {\n await shutdownExporter(exporter, Math.max(0, shutdownDeadline - Date.now()));\n }\n\n // Clean up retry tracking — retry-map drain site 3 of 3\n this._retryCounts.clear();\n this._retryRequests.clear();\n\n debug(\n `BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, ` +\n `Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`\n );\n }\n\n onSpanEnd(span: Span): void {\n if (!this._started) {\n // A span that ends WHILE the drain of `shutdown()` runs joins that drain: its\n // loop exports it before it ends, inside the same bound. Through 0.8.0 it was\n // dropped with no count. A span that ends when the drain can take no more (its\n // loop ended, or the bound ended) is counted at once as `shutdown_residue`.\n // A processor that was never started took no span, and counts none.\n if (this._drainOpen) this._enqueue(span, false);\n else if (this._closing !== null) this._lateSpan();\n return;\n }\n this._enqueue(span, true);\n }\n\n private _enqueue(span: Span, exportAtBatchSize: boolean): void {\n // Check queue capacity\n if (this._queue.length >= this._maxQueueSize) {\n if (this._quotaPaused()) {\n // S-1: the queue is the buffer while the exporter is paused for the quota. Drop the\n // OLDEST span, so that the most recent spans survive to the probe and the drain (CTO\n // decision). It is a quota drop, not queue_full. Its WARNING is the hourly quota\n // WARNING of the exporter, not the queue-full one; the exporter adds it to its count.\n const oldest = this._queue.shift();\n if (oldest !== undefined) this._forgetRetry(oldest.spanId);\n this._recordDropped('quota_exceeded');\n for (const exporter of this._exporters) {\n try {\n exporter.noteQuotaDrop?.(1);\n } catch {\n // a customer exporter must not break onSpanEnd\n }\n }\n this._queue.push(span);\n return;\n }\n // W2-1c: drop the OLDEST queued span and keep the new one, so that the spans that\n // survive an outage are the most recent ones. Memory stays bounded by `maxQueueSize`.\n // (Through 0.10.0 the new span was dropped.)\n // A queue with no room at all (capacity 0) has no oldest span: the new span is the one\n // that is dropped.\n const oldest = this._queue.shift();\n if (oldest !== undefined) {\n this._forgetRetry(oldest.spanId);\n this._queue.push(span);\n }\n this._recordDropped('queue_full');\n if (this.droppedSpans === 1 || this.droppedSpans % 1000 === 0) {\n warn(\n `Span queue full (${this._maxQueueSize}): the oldest queued span is dropped and the new ` +\n `one is kept (reason=queue_full). ${this.droppedSpans} spans dropped so far.`,\n );\n }\n return;\n }\n\n this._queue.push(span);\n\n // Trigger immediate flush if batch size reached\n if (exportAtBatchSize && this._queue.length >= this._batchSize) {\n void this._exportBatch();\n }\n }\n\n /**\n * True when every exporter that delivers is paused for the monthly quota (S-1). An exporter\n * says so with `quotaPaused()`. A custom exporter has none: not paused.\n */\n private _quotaPaused(): boolean {\n const deciders = this._exporters.filter((e) => e.countsAsDelivery !== false);\n if (deciders.length === 0) return false;\n for (const exporter of deciders) {\n try {\n if (exporter.quotaPaused?.() !== true) return false;\n } catch {\n return false; // a customer exporter must not break a round\n }\n }\n return true;\n }\n\n /** A span that ended after the drain ended: counted, with one WARNING for the first. */\n private _lateSpan(): void {\n this._recordDropped('shutdown_residue');\n if (this._lateSpanWarned) return;\n this._lateSpanWarned = true;\n warn(\n 'a span ended after shutdown() had stopped taking spans (reason=shutdown_residue). ' +\n 'It was not delivered, and it is counted as dropped. Later spans of this kind are ' +\n 'counted without a WARNING.'\n );\n }\n\n /**\n * Flush pending spans.\n *\n * @returns `true` only if everything queued at entry was DELIVERED and no\n * span was lost since the previous flush returned.\n *\n * RULING §6. This used to answer a different question — \"is the queue\n * empty?\" — and those two diverge in exactly one case: when spans left the\n * queue WITHOUT reaching the transport. That case is the entire finding. A\n * customer who calls `flush()` before exit and gets `true` has done\n * everything right; silence lets them discover the problem, a false\n * affirmative forecloses it.\n *\n * A LOSS IS REPORTED BY THE NEXT `flush()`, ONE TIME (design section 0,\n * third revision). Returns `true` only when, at the moment it returns, the\n * queue is empty, no batch is in flight, and no span was discarded or\n * rejected since the previous `flush()` returned (or since start, for the\n * first call). Through 0.7.1 only a loss during the call counted: a script\n * whose spans the batch timer had discarded against a 401 sink got `true`\n * with nothing delivered. A failure that a retry repairs does not make it\n * `false`.\n *\n * Mechanics: the processor keeps a loss mark, the loss total (dropped +\n * rejected) that the last finished flush saw. A flush compares the total\n * with the mark it read at its start, then raises the mark to the total\n * (never lowers it). Two flushes that overlap both answer `false` for one\n * loss. The flush after that answers `true` when nothing new was lost.\n *\n * Returns `false` in these cases:\n * (a) the deadline expires with spans still queued or in flight, or while a\n * `shutdown()` that it waits for still runs;\n * (b) a span was discarded since the previous flush returned: queue full,\n * breaker refusal, retry exhaustion, spans that `shutdown()` left\n * (`shutdown_residue`), or an ack that did not account for it or a span\n * that could not be serialized (`unacknowledged`);\n * (c) the backend rejected a span since the previous flush returned.\n *\n * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at\n * SIGTERM or SIGINT, or a `shutdown()` that nobody awaited) waits for that\n * shutdown, inside its OWN deadline, and then answers from the final tally with\n * the same loss mark. After `shutdown()` it answers from the final tally in the\n * same way. Through 0.8.0 both answered from the empty queue: true in 0 ms,\n * with the batch in flight, and true after a rejection or a `transport_refused`\n * drop. A loss that `shutdown()` counts (also `shutdown_residue`) makes ONE\n * `flush()` false, as every other loss does.\n *\n * The deadline is a hard wall-clock bound on the WAIT. At the deadline\n * `flush()` returns `false`. Through 0.7.1 the deadline was checked only\n * between rounds.\n *\n * ⚠ `flush()` never stops a request that is already sent. The export round in\n * flight continues and ends by its own rules: its request timeout, its\n * retries, the circuit breaker. A short flush budget therefore costs no retry,\n * moves no breaker and sends nothing twice. Its result still counts.\n *\n * Limit: that round can keep the process alive after `flush()` returns\n * `false`, until its own timeouts end. Measured on a silent server: 22 s. To\n * end a process within a bound, call `await shutdown(timeoutMs)`: it stops\n * the round in flight.\n *\n * ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span\n * that arrived during the call also answers `false`. That is the\n * conservative direction on purpose: a false negative costs a caller one\n * more flush, a false positive is the defect being fixed.\n */\n async flush(timeoutMs: number = FLUSH_BUDGET_MS): Promise<boolean> {\n timeoutMs = normalizeTimeoutMs(timeoutMs);\n\n const deadline = Date.now() + timeoutMs;\n const mark = this._lossMark;\n // Report a loss once: compare with the mark, then raise the mark to the\n // total this flush saw (never lower it). Two flushes that overlap both\n // answer false for one loss.\n const finish = (settled: boolean): boolean => {\n const lost = this.droppedSpans + this.rejectedSpans;\n this._lossMark = Math.max(this._lossMark, lost);\n return settled && lost === mark;\n };\n\n if (!this._started) {\n // A `shutdown()` that runs (the SDK's own drain, or one that nobody\n // awaited): its batch is in flight and its residue is not counted yet.\n // Wait for it, inside THIS deadline. The unconditional answer from the\n // empty queue was true in 0 ms, with nothing delivered.\n if (this._closing !== null) {\n const closed = await raceDeadline(this._closing.catch(() => undefined), timeoutMs);\n if (closed === DEADLINE) return finish(false);\n }\n // Shut down: the queue is empty, and a batch that `shutdown()` abandoned\n // is counted already (`shutdown_residue`), so the loss mark covers it.\n const held = this._inFlight !== null && !this._inFlight.abandoned;\n return finish(this._queue.length === 0 && !held);\n }\n\n // Wait for in-flight exports to complete AND queue to drain\n while (this._queue.length > 0 || this._flushing) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) return finish(false);\n // A `shutdown()` started during this flush (the SDK's own drain at a signal, for\n // example): the drain owns the rounds now. Wait for it, as a flush() that comes during a\n // shutdown() does (above). W2-1c: the drain's `endRetries()` makes a failed round put its\n // batch back, so a flush loop that went on starting rounds would take the batch from the\n // drain again and again until this deadline, and the residue would be counted after it.\n if (!this._started && this._closing !== null) {\n const closed = await raceDeadline(this._closing.catch(() => undefined), remaining);\n if (closed === DEADLINE) return finish(false);\n const held = this._inFlight !== null && !this._inFlight.abandoned;\n return finish(this._queue.length === 0 && !held);\n }\n // S-1: every exporter that delivers is paused for the monthly quota, nothing is in an\n // export, and spans wait in the queue. They cannot go out before the pause ends\n // (minutes), so waiting out the timeout only slows the caller. Answer false at once.\n if (!this._flushing && this._queue.length > 0 && this._quotaPaused()) return finish(false);\n if (!this._flushing && this._queue.length > 0) {\n // Race the WAIT only. The round continues after the deadline.\n const outcome = await raceDeadline(this._exportBatch(), remaining);\n if (outcome === DEADLINE) return finish(false);\n // Paused for the quota: nothing to do until the pause ends. Do not spin.\n if (outcome === Round.Paused) await new Promise((r) => setTimeout(r, 20));\n } else {\n // Wait a tick for the in-flight export to finish\n await new Promise((r) => setTimeout(r, 1));\n }\n }\n\n return finish(true);\n }\n\n getMetrics() {\n const ends: number[] = [];\n const head = endMs(this._queue[0]);\n if (head !== null) ends.push(head);\n const flight = this._inFlight;\n if (flight !== null && !flight.abandoned && flight.oldestEndMs !== null) ends.push(flight.oldestEndMs);\n const oldestPendingAgeS = ends.length > 0 ? Math.max(0, (Date.now() - Math.min(...ends)) / 1000) : 0;\n return {\n exportedSpans: this.exportedSpans,\n rejectedSpans: this.rejectedSpans,\n droppedSpans: this.droppedSpans,\n droppedSpansByReason: { ...this.droppedSpansByReason },\n // Spans dropped because the monthly event quota is used up (S-1). The same number as\n // `droppedSpansByReason.quota_exceeded`, for a reader that wants one key.\n droppedQuota: this.droppedSpansByReason.quota_exceeded,\n failedExports: this.failedExports,\n /**\n * W2-1c: export requests (each retry and each half of a 413 split counts), added when the\n * export call ends: a batch that still retries is not in it yet.\n */\n attempts: this.attempts,\n /**\n * W2-1c: the age in seconds of the oldest span that is queued or in an export (its end\n * time to now). 0 when nothing is pending. It grows during an outage, up to the retry\n * horizon for the batch in an export.\n */\n oldestPendingAgeS,\n maskErrors: this.maskErrors,\n queueSize: this._queue.length,\n queueCapacity: this._maxQueueSize,\n queueUtilization: this._queue.length / this._maxQueueSize,\n };\n }\n\n /**\n * Count a delivered batch of `n` spans from the exporter's ack.\n *\n * The ack is not trusted. With r = min(rejected, n), a = min(accepted, n - r)\n * and u = n - a - r: `exportedSpans` rises by a, `rejectedSpans` by r, and the\n * u spans that no ack accounts for are dropped as `unacknowledged`, with one\n * rate-limited WARNING. Without an ack (console, custom exporter), the whole\n * batch counts as exported, as before. Python twin: the same clamp.\n */\n private _countDelivered(n: number, ack: AckCounts | null): void {\n if (ack === null) {\n this.exportedSpans += n;\n return;\n }\n // S-1: spans that the monthly quota paused or discarded. The exporter's ack is 0 and 0, so\n // they would be `unacknowledged`; count them as `quota_exceeded` and take them out first.\n const quota = Math.min(Math.max(ack.quotaDropped ?? 0, 0), n);\n if (quota > 0) {\n this._recordDropped('quota_exceeded', quota);\n n -= quota;\n if (n === 0) return;\n }\n // W2-1c: spans that the exporter dropped in a 413 split (`ack.dropped`). The ack's\n // `accepted` and `rejected` do not count them.\n for (const [reason, count] of Object.entries(ack.dropped ?? {})) {\n if (!DECIDED_DROPS.has(reason) || typeof count !== 'number' || !Number.isInteger(count) || count <= 0) {\n continue;\n }\n const take = Math.min(count, n);\n if (take === 0) continue;\n this._recordDropped(reason as DropReason, take);\n if (reason === 'shutdown_residue') this._drainResidue += take;\n n -= take;\n }\n if (n === 0) return;\n // Pessimistic: a sink that says \"rejected\" is believed before one that says\n // \"accepted\" (design section 0, ack clamp REVISED).\n const rejected = Math.min(ack.rejected, n);\n const accepted = Math.min(ack.accepted, n - rejected);\n const unacknowledged = n - accepted - rejected;\n this.exportedSpans += accepted;\n this.rejectedSpans += rejected;\n if (unacknowledged > 0) {\n this._recordDropped('unacknowledged', unacknowledged);\n const now = Date.now();\n if (now - this._lastUnackWarnAt > REFUSAL_WARN_WINDOW_MS) {\n this._lastUnackWarnAt = now;\n warn(\n `Risicare: the backend's ack accounts for ${accepted + rejected} of ${n} span(s) ` +\n `in this batch. The other ${unacknowledged} are counted as dropped ` +\n `(reason=unacknowledged): they may not be stored. ` +\n `${this.droppedSpansByReason.unacknowledged} span(s) counted this way so far ` +\n `in this process.`,\n );\n }\n }\n }\n\n /** The one exporter that delivers, when there is exactly one. */\n private _soleDeliverer(): SpanExporter | undefined {\n const delivering = this._exporters.filter((e) => e.countsAsDelivery !== false);\n return delivering.length === 1 ? delivering[0] : undefined;\n }\n\n /** The most requests in one export round, when every exporter that delivers states it. */\n private _requestsPerRound(): number | undefined {\n const n = this._soleDeliverer()?.attemptsPerExport;\n return typeof n === 'number' && Number.isFinite(n) && n > 0 ? n : undefined;\n }\n\n /**\n * The HTTP requests that `exporter`'s `export()` call for `batch` really sent (issue #57,\n * W2-1c). `undefined` when the exporter does not state it. NaN when it has no record of the\n * call, or the read threw.\n */\n private _takeAttempts(exporter: SpanExporter, batch: Span[]): number | undefined {\n if (typeof exporter.takeAttempts !== 'function') return undefined;\n try {\n const n = exporter.takeAttempts(batch);\n return typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : Number.NaN;\n } catch (e) {\n debug(`takeAttempts of ${exporter.name} failed: ${describeThrown(e)}`);\n return Number.NaN;\n }\n }\n\n /**\n * The drop reason of `exporter`'s failed `export()` call for `batch` (W2-1c), or `null`: the\n * exporter does not classify its failure, and the batch gets the bounded re-queue.\n */\n private _takeDropReason(exporter: SpanExporter, batch: Span[]): ExporterDropReason | null {\n if (typeof exporter.takeDropReason !== 'function') return null;\n try {\n const reason = exporter.takeDropReason(batch);\n return typeof reason === 'string' && DECIDED_FAILURES.has(reason) ? reason : null;\n } catch (e) {\n debug(`takeDropReason of ${exporter.name} failed: ${describeThrown(e)}`);\n return null;\n }\n }\n\n /**\n * A failed batch whose fate the exporter decided (`takeDropReason`, W2-1c).\n *\n * `transport_refused` and `retry_exhausted`: every span is dropped with that reason at once,\n * and COUNTED. A re-queue would only send it to the same answer, or past the retry horizon.\n * `shutdown_residue`: `endRetries()` ended the retries in the drain of `shutdown()`. The\n * batch goes back to the head of the queue, uncounted, and `shutdown()` counts it with the\n * queue in its one residue WARNING.\n */\n private _dropDecided(batch: Span[], unserializable: Set<Span>, reason: ExporterDropReason): void {\n const spans = batch.filter((span) => !unserializable.has(span));\n if (reason === 'shutdown_residue') {\n this._queue.unshift(...spans);\n return;\n }\n for (const span of spans) this._forgetRetry(span.spanId);\n this._recordDropped(reason as DropReason, spans.length);\n // `retry_exhausted` has its WARNING from the exporter, which knows the horizon and the\n // last answer.\n if (reason !== 'transport_refused' || spans.length === 0) return;\n const now = Date.now();\n if (now - this._lastRefusalWarnAt <= REFUSAL_WARN_WINDOW_MS) return;\n this._lastRefusalWarnAt = now;\n warn(\n `${spans.length} span(s) DISCARDED (reason=transport_refused): the endpoint gave an ` +\n `answer that a retry cannot change, so the batch was sent once. ` +\n `${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far in ` +\n `this process. This data is gone; check the apiKey and the endpoint.`,\n );\n }\n\n /** End the retry tracking of one span (retry-map drain sites 1 and 2 of 3, and the queue drop). */\n private _forgetRetry(spanId: string): void {\n this._retryCounts.delete(spanId);\n this._retryRequests.delete(spanId);\n }\n\n /**\n * One export round.\n *\n * Which results decide delivery: an exporter that only shows spans locally\n * (`countsAsDelivery === false`, the console exporter) decides only when no\n * other kind of exporter is present. Among the exporters that deliver, ANY\n * success counts the batch as delivered, once.\n */\n private async _exportBatch(): Promise<Round> {\n if (this._flushing) return Round.Busy;\n if (this._queue.length === 0) return Round.Empty;\n // S-1: every exporter that delivers is paused for the monthly quota. Take nothing: the spans\n // stay in the queue and go out when the pause ends.\n if (this._quotaPaused()) return Round.Paused;\n this._flushing = true;\n let flight: InFlight | null = null;\n\n try {\n // Take up to batchSize spans — AND up to the attribute-product bound, AND\n // up to the serialized-byte bound; whichever binds first\n // (SDK-RELEASE-RULING.md §4.5 + F-SDKBYTES-001). `batchSize` is a CEILING,\n // not a fixed size, on all three axes.\n //\n // Take-at-least-one is unconditional on every axis: a single span that\n // alone exceeded a bound would otherwise be taken by no round ever,\n // wedging the queue permanently. One over-cap span is the gateway's\n // problem to refuse and the retry budget's to count; a wedged queue would\n // be ours forever.\n let take = 0;\n let pairs = 0;\n let nbytes = 0;\n const limit = Math.min(this._batchSize, this._queue.length);\n while (take < limit) {\n const head = this._queue[take];\n const spanPairs = spanAttrCount(head);\n const spanBytes = spanBytesEstimate(head);\n if (\n take > 0 &&\n (pairs + spanPairs > MAX_ATTRIBUTE_PAIRS_PER_BATCH ||\n nbytes + spanBytes > MAX_BATCH_BYTES)\n ) {\n break;\n }\n pairs += spanPairs;\n nbytes += spanBytes;\n take++;\n }\n const batch = this._queue.splice(0, take);\n if (batch.length === 0) return Round.Empty;\n flight = { spans: batch, size: batch.length, abandoned: false, oldestEndMs: oldestEndMs(batch) };\n this._inFlight = flight;\n\n // ⚠ MASK HERE — after the batch is off the queue, before any exporter.\n //\n // WHY NOT in `onSpanEnd()`: that runs on the call that ended the span,\n // i.e. inside the customer's own request path. This site is at least on\n // the export turn.\n //\n // ⚠ AND WHY THAT IS A WEAKER GUARANTEE THAN PYTHON'S: Node has one\n // thread. Python's mask runs on a background worker and costs only drain\n // rate; this one blocks the event loop for its duration. The budget\n // warning below is the whole of the protection, and it is a warning.\n //\n // ⚠ DECLARED RIPPLE, same as Python: the attribute-product and byte\n // bounds above are computed on PRE-mask values. Redaction shrinks, so the\n // estimate stays conservative for every realistic mask; a mask that GROWS\n // content can push the real body past the estimate, which the estimate\n // already declares for ASCII escaping and already answers the same way —\n // the gateway remains the enforcer.\n // ⚠ STRIP BEFORE MASK, and unconditionally when capture is off.\n //\n // Before mask because content the customer never wanted to leave the\n // process should not be handed to a customer callback either — and\n // because a mask never called over a stripped field costs nothing, which\n // matters more here than in Python: this runs on the ONE event loop.\n //\n // Unconditional (not `if this._mask !== undefined`) because THIS is the\n // gate: `_applyMask` runs only when a mask was supplied, and the whole\n // defect being closed is that content escaped when nobody had opted into\n // anything.\n if (!this._traceContent) {\n const stripped = stripContentBatch(batch);\n if (stripped > 0) {\n debug(\n `traceContent is off — omitted ${stripped} content field(s) from ${batch.length} span(s)`,\n );\n }\n }\n\n if (this._mask !== undefined) {\n this._applyMask(batch);\n }\n\n debug(`Exporting batch of ${batch.length} spans`);\n\n // Export to all exporters — count once, not per exporter\n let batchExported = false;\n const anyDelivers = this._exporters.some((e) => e.countsAsDelivery !== false);\n // Spans that an exporter could not serialize: not sent, dropped at once.\n const unserializable = new Set<Span>();\n // W2-1c: the drop reason of the first failed exporter that delivers (`takeDropReason`).\n let failReason: ExporterDropReason | null = null;\n let failedDecider = false;\n // The requests of this round, as the sole deliverer states them (issue #57).\n const sole = this._soleDeliverer();\n let sent: number | undefined;\n for (const exporter of this._exporters) {\n const decides = !anyDelivers || exporter.countsAsDelivery !== false;\n try {\n const result = await exporter.export(batch);\n // `shutdown()` stopped this batch and counted it as residue. Its late\n // answer changes no counter and re-queues nothing.\n if (flight.abandoned) return Round.Failed;\n if (!decides) continue;\n if (exporter.countsAsDelivery !== false) {\n const requests = this._takeAttempts(exporter, batch);\n this.attempts += requests !== undefined && Number.isFinite(requests) ? requests : 1;\n if (exporter === sole) sent = requests;\n }\n for (const span of exporter.takeUnserializable?.(batch) ?? []) unserializable.add(span);\n if (result === ExportResult.SUCCESS) {\n const ack = exporter.takeAck?.(batch) ?? null;\n if (!batchExported) {\n this._countDelivered(batch.length - unserializable.size, ack);\n batchExported = true;\n // Clear retry counts for successfully exported spans\n for (const span of batch) {\n this._forgetRetry(span.spanId);\n }\n }\n } else {\n this.failedExports++;\n if (!failedDecider && exporter.countsAsDelivery !== false) {\n failedDecider = true;\n failReason = this._takeDropReason(exporter, batch);\n }\n }\n } catch (e) {\n if (flight.abandoned) return Round.Failed;\n if (!decides) continue;\n if (exporter.countsAsDelivery !== false) this.attempts++;\n this.failedExports++;\n debug(`Export to ${exporter.name} failed: ${describeThrown(e)}`);\n }\n }\n if (unserializable.size > 0) this._recordDropped('unacknowledged', unserializable.size);\n\n // W2-1c: the exporter decided the fate of the batch.\n if (!batchExported && failReason !== null) {\n this._dropDecided(batch, unserializable, failReason);\n return Round.Failed;\n }\n\n // Audit #5: Re-queue failed batches with retry limit. Since W2-1c only for a failure\n // that the exporter does not classify (a custom exporter, an exception).\n if (!batchExported) {\n let dropped = 0;\n // `sent`: the requests that this round sent. Each span of the batch was in all of them.\n // The requests of ALL the failed rounds of each span that is dropped now.\n const droppedRequests: number[] = [];\n const retryable = batch.filter(span => {\n if (unserializable.has(span)) return false;\n const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;\n const requests =\n sent === undefined ? undefined : (this._retryRequests.get(span.spanId) ?? 0) + sent;\n if (count > BatchSpanProcessor.MAX_RETRIES) {\n // retry-map drain site 2 of 3\n this._forgetRetry(span.spanId);\n if (requests !== undefined) droppedRequests.push(requests);\n // The count is once per SPAN IDENTITY, at exhaustion — never once\n // per attempt. A span re-queued twice and then dropped is ONE lost\n // span; keying on spanId is what makes that true.\n this._recordDropped('transport_refused');\n dropped++;\n return false;\n }\n this._retryCounts.set(span.spanId, count);\n if (requests !== undefined) this._retryRequests.set(span.spanId, requests);\n return true;\n });\n if (retryable.length > 0) {\n this._queue.unshift(...retryable);\n debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);\n }\n if (dropped > 0) {\n // RULING §2: the PRIMARY remedy is a default-visible WARNING at the\n // moment of discard, naming the count and the reason — not a counter.\n // The log line survives the process; the counter does not, and on the\n // shutdown path there is no reader for it at all. `debug()` above is\n // suppressed at default level, which is why this is `warn()`.\n const now = Date.now();\n if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {\n this._lastRefusalWarnAt = now;\n const rounds = BatchSpanProcessor.MAX_RETRIES + 1;\n const perRound = this._requestsPerRound();\n // The number that the exporter says it sent, when it says so for every round of\n // every span that is dropped now. A 401 or 403 sends one request in a round, so the\n // old \"up to\" number was wrong for it. When the exporter does not say, the old text\n // stays: the most that the rounds may send.\n const stated =\n droppedRequests.length > 0 && droppedRequests.every((n) => Number.isFinite(n));\n let requestsText = '';\n if (stated) {\n let lo = droppedRequests[0];\n let hi = lo;\n for (const n of droppedRequests) {\n if (n < lo) lo = n;\n if (n > hi) hi = n;\n }\n requestsText =\n lo === hi\n ? ` (${hi} HTTP ${hi === 1 ? 'request' : 'requests'} sent)`\n : ` (${lo} to ${hi} HTTP requests sent)`;\n } else if (perRound !== undefined) {\n requestsText = ` (up to ${rounds * perRound} HTTP requests: ${perRound} in each round)`;\n }\n warn(\n `${dropped} span(s) DISCARDED (reason=transport_refused) after ` +\n `${rounds} failed export rounds each` +\n requestsText +\n ` — the endpoint is ` +\n `not accepting spans and the retry budget is spent. ` +\n `${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far ` +\n `in this process. This data is gone; check the apiKey and the endpoint.`\n );\n }\n }\n }\n return batchExported ? Round.Delivered : Round.Failed;\n } finally {\n if (this._inFlight === flight) this._inFlight = null;\n this._flushing = false;\n }\n }\n}\n","/**\n * ID generation for traces and spans.\n *\n * Trace IDs: 32 lowercase hex characters (16 random bytes)\n * Span IDs: 16 lowercase hex characters (8 random bytes)\n *\n * Uses crypto.randomBytes for cryptographically secure randomness.\n */\n\nimport { randomBytes } from 'node:crypto';\n\nconst HEX_REGEX_32 = /^[0-9a-f]{32}$/;\nconst HEX_REGEX_16 = /^[0-9a-f]{16}$/;\n\nexport function generateTraceId(): string {\n return randomBytes(16).toString('hex');\n}\n\nexport function generateSpanId(): string {\n return randomBytes(8).toString('hex');\n}\n\nexport function generateAgentId(prefix?: string): string {\n const suffix = randomBytes(8).toString('hex');\n return prefix ? `${prefix}-${suffix}` : suffix;\n}\n\nexport function validateTraceId(id: string): boolean {\n return HEX_REGEX_32.test(id);\n}\n\nexport function validateSpanId(id: string): boolean {\n return HEX_REGEX_16.test(id);\n}\n","/**\n * No-op implementations for the disabled path.\n *\n * When tracing is disabled, all operations return these no-op objects\n * to maintain zero overhead. No allocations, no side effects.\n */\n\nimport { SpanKind, SpanStatus, type SpanPayload } from './types.js';\n\n/**\n * A frozen no-op span that silently ignores all operations.\n * Used when SDK is disabled to avoid overhead.\n */\nexport const NOOP_SPAN = Object.freeze({\n traceId: '00000000000000000000000000000000',\n spanId: '0000000000000000',\n parentSpanId: undefined,\n name: 'noop',\n kind: SpanKind.INTERNAL,\n startTime: '',\n startHrtime: 0,\n endTime: undefined,\n status: SpanStatus.UNSET,\n statusMessage: undefined,\n attributes: Object.freeze({}) as Record<string, unknown>,\n events: Object.freeze([]) as readonly [],\n links: Object.freeze([]) as readonly [],\n sessionId: undefined,\n agentId: undefined,\n agentName: undefined,\n semanticPhase: undefined,\n llmProvider: undefined,\n llmModel: undefined,\n llmPromptTokens: undefined,\n llmCompletionTokens: undefined,\n llmTotalTokens: undefined,\n llmCostUsd: undefined,\n toolName: undefined,\n toolSuccess: undefined,\n isEnded: true,\n durationMs: 0,\n\n setAttribute() { return this; },\n setAttributes() { return this; },\n setStatus() { return this; },\n addEvent() { return this; },\n addLink() { return this; },\n recordException() { return this; },\n setLlmFields() { return this; },\n setToolFields() { return this; },\n end() {},\n toPayload(): SpanPayload {\n return {\n traceId: this.traceId,\n spanId: this.spanId,\n name: this.name,\n kind: this.kind,\n startTime: this.startTime,\n status: this.status,\n attributes: {},\n events: [],\n links: [],\n };\n },\n});\n\nexport type NoopSpan = typeof NOOP_SPAN;\n","/**\n * Fix Runtime Configuration.\n *\n * Settings for the fix runtime including caching, refresh intervals,\n * A/B testing, and fix application behavior.\n *\n * Port of Python SDK's runtime/config.py adapted for Node.js patterns.\n */\n\n// ─── Runtime Configuration ──────────────────────────────────────────────────\n\nexport interface FixRuntimeConfig {\n /** Api URL, serving /v1/fixes/active (e.g., \"https://api.risicare.ai\") */\n apiEndpoint: string;\n\n /** API key for authentication (format: \"rsk-{random}\") */\n apiKey: string;\n\n /** Whether the fix runtime is enabled (default: true) */\n enabled?: boolean;\n\n /** Whether caching is enabled (default: true) */\n cacheEnabled?: boolean;\n\n /** Cache entry TTL in milliseconds (default: 300_000 = 5 min) */\n cacheTtlMs?: number;\n\n /** Maximum number of cache entries (default: 1000) */\n cacheMaxEntries?: number;\n\n /** Whether to auto-refresh fixes in background (default: true) */\n autoRefresh?: boolean;\n\n /** Background refresh interval in milliseconds (default: 60_000 = 1 min) */\n refreshIntervalMs?: number;\n\n /** Log but don't apply fixes (default: false) */\n dryRun?: boolean;\n\n /** Whether A/B testing bucketing is active (default: true) */\n abTestingEnabled?: boolean;\n\n /** Timeout for API requests in milliseconds (default: 1000) */\n timeoutMs?: number;\n\n /** Enable debug logging (default: false) */\n debug?: boolean;\n}\n\n/** Resolve config with defaults applied. */\nexport function resolveFixRuntimeConfig(\n config: FixRuntimeConfig,\n): Required<FixRuntimeConfig> {\n return {\n apiEndpoint: config.apiEndpoint,\n apiKey: config.apiKey,\n enabled: config.enabled ?? true,\n cacheEnabled: config.cacheEnabled ?? true,\n cacheTtlMs: config.cacheTtlMs ?? 300_000,\n cacheMaxEntries: config.cacheMaxEntries ?? 1000,\n autoRefresh: config.autoRefresh ?? true,\n refreshIntervalMs: config.refreshIntervalMs ?? 60_000,\n dryRun: config.dryRun ?? false,\n abTestingEnabled: config.abTestingEnabled ?? true,\n timeoutMs: config.timeoutMs ?? 1000,\n debug: config.debug ?? false,\n };\n}\n\n// ─── Fix Type ───────────────────────────────────────────────────────────────\n\nexport type FixType =\n | 'prompt'\n | 'parameter'\n | 'retry'\n | 'fallback'\n | 'guard'\n | 'routing'\n | 'tool';\n\n// ─── Active Fix ─────────────────────────────────────────────────────────────\n\nexport interface ActiveFix {\n fixId: string;\n deploymentId?: string;\n errorCode: string;\n fixType: FixType;\n config: Record<string, unknown>;\n trafficPercentage: number; // 0–100\n version: number;\n}\n\n/**\n * Check if a fix matches the given error code.\n *\n * Supports exact match and wildcard prefix matching:\n * - \"TOOL.EXECUTION.TIMEOUT\" matches \"TOOL.EXECUTION.TIMEOUT\"\n * - \"TOOL.EXECUTION.*\" matches \"TOOL.EXECUTION.TIMEOUT\", \"TOOL.EXECUTION.FAILURE\", etc.\n * - \"TOOL.*\" matches any TOOL error\n */\nexport function matchesError(fix: ActiveFix, errorCode: string): boolean {\n if (fix.errorCode === errorCode) {\n return true;\n }\n\n // Wildcard matching\n if (fix.errorCode.endsWith('*')) {\n const prefix = fix.errorCode.slice(0, -1);\n return errorCode.startsWith(prefix);\n }\n\n return false;\n}\n\n/**\n * Determine if fix should be applied based on A/B traffic percentage.\n *\n * Uses consistent hashing so the same session always gets the same\n * treatment (fix or no fix).\n */\nexport function shouldApply(fix: ActiveFix, sessionHash: number): boolean {\n if (fix.trafficPercentage >= 100) return true;\n if (fix.trafficPercentage <= 0) return false;\n\n const bucket = sessionHash % 100;\n return bucket < fix.trafficPercentage;\n}\n\n/**\n * Create an ActiveFix from an API response item.\n *\n * Handles both snake_case (server API) and camelCase field names.\n */\nexport function activeFixFromApiResponse(\n item: Record<string, unknown>,\n): ActiveFix {\n return {\n fixId: (item.id ?? item.fix_id ?? item.fixId ?? '') as string,\n deploymentId: (item.deployment_id ?? item.deploymentId ?? '') as string,\n errorCode: (item.error_code ?? item.errorCode ?? '') as string,\n fixType: (item.fix_type ?? item.fixType ?? 'prompt') as FixType,\n config: (item.config ?? {}) as Record<string, unknown>,\n trafficPercentage: (item.traffic_percentage ?? item.trafficPercentage ?? 100) as number,\n version: (item.version ?? 1) as number,\n };\n}\n","// ⚠ GENERATED FILE — DO NOT EDIT BY HAND.\n//\n// Source of truth: packages/risicare-sdk/src/risicare/runtime/_error_taxonomy.py\n// Generator: packages/risicare-sdk/scripts/gen_js_taxonomy.py\n// Core rules: packages/risicare-core/src/risicare_core/taxonomy.py (_KEYWORD_RULES)\n// Verify: just taxonomy (gen_js_taxonomy.py --check)\n//\n// F-SDKTAXFORK-001. This SDK cannot import `risicare_core.taxonomy` —\n// `risicare-core` is not published to npm. Rather than hand-maintain a second\n// copy of one rule (a divergence this campaign has measured four times), the\n// rule table and the canonical code set are generated from the Python source\n// and a rail fails when the two drift.\n//\n// Each pattern is a translation of the Python pattern for the `u` flag\n// (`.` -> `[^\\n]`, `\\b` -> a lookaround on [\\p{L}\\p{N}_]). The text is\n// lowercased before the match, as in Python, so no rule has a case flag.\n//\n// 154 canonical codes across 10 modules.\n\nexport const CANONICAL_ERROR_CODES: ReadonlySet<string> = new Set([\n \"COMMUNICATION.CONTENT.AMBIGUOUS\",\n \"COMMUNICATION.CONTENT.CORRUPTED\",\n \"COMMUNICATION.CONTENT.INCOMPATIBLE\",\n \"COMMUNICATION.CONTENT.MALFORMED\",\n \"COMMUNICATION.CONTENT.TOO_LARGE\",\n \"COMMUNICATION.DELIVERY.DELAYED\",\n \"COMMUNICATION.DELIVERY.DUPLICATED\",\n \"COMMUNICATION.DELIVERY.EXPIRED\",\n \"COMMUNICATION.DELIVERY.OUT_OF_ORDER\",\n \"COMMUNICATION.DELIVERY.UNDELIVERABLE\",\n \"COMMUNICATION.ROUTING.BROADCAST_STORM\",\n \"COMMUNICATION.ROUTING.LOOP\",\n \"COMMUNICATION.ROUTING.NO_ROUTE\",\n \"COMMUNICATION.ROUTING.PARTITION\",\n \"COMMUNICATION.ROUTING.WRONG_ROUTE\",\n \"CONSENSUS.AGREEMENT.INCONSISTENT\",\n \"CONSENSUS.AGREEMENT.QUORUM_FAILED\",\n \"CONSENSUS.AGREEMENT.REJECTED\",\n \"CONSENSUS.AGREEMENT.STALE_VOTE\",\n \"CONSENSUS.AGREEMENT.TIMEOUT\",\n \"CONSENSUS.CONFLICT.BIAS\",\n \"CONSENSUS.CONFLICT.CASCADING\",\n \"CONSENSUS.CONFLICT.DEADLOCK\",\n \"CONSENSUS.CONFLICT.RESOLUTION_REJECTED\",\n \"CONSENSUS.CONFLICT.UNRESOLVED\",\n \"CONSENSUS.VOTING.ABSTENTION_FLOOD\",\n \"CONSENSUS.VOTING.COERCED_VOTE\",\n \"CONSENSUS.VOTING.DUPLICATE_VOTE\",\n \"CONSENSUS.VOTING.INVALID_VOTE\",\n \"CONSENSUS.VOTING.SPLIT_VOTE\",\n \"COORDINATION.HANDOFF.DELAYED\",\n \"COORDINATION.HANDOFF.DUPLICATED\",\n \"COORDINATION.HANDOFF.INCOMPLETE\",\n \"COORDINATION.HANDOFF.LOST\",\n \"COORDINATION.HANDOFF.WRONG_RECIPIENT\",\n \"COORDINATION.SYNCHRONIZATION.CLOCK_SKEW\",\n \"COORDINATION.SYNCHRONIZATION.OUT_OF_ORDER\",\n \"COORDINATION.SYNCHRONIZATION.RACE_CONDITION\",\n \"COORDINATION.SYNCHRONIZATION.SPLIT_BRAIN\",\n \"COORDINATION.SYNCHRONIZATION.VERSION_MISMATCH\",\n \"COORDINATION.WORKFLOW.CYCLE\",\n \"COORDINATION.WORKFLOW.DEADLOCK\",\n \"COORDINATION.WORKFLOW.LIVELOCK\",\n \"COORDINATION.WORKFLOW.ORPHANED\",\n \"COORDINATION.WORKFLOW.STARVATION\",\n \"MEMORY.CONTEXT_WINDOW.DROPPED\",\n \"MEMORY.CONTEXT_WINDOW.EXCEEDED\",\n \"MEMORY.CONTEXT_WINDOW.FRAGMENTED\",\n \"MEMORY.CONTEXT_WINDOW.PRIORITY_ERROR\",\n \"MEMORY.RETRIEVAL.INCOMPLETE\",\n \"MEMORY.RETRIEVAL.NOT_FOUND\",\n \"MEMORY.RETRIEVAL.OUTDATED\",\n \"MEMORY.RETRIEVAL.TOO_MANY\",\n \"MEMORY.RETRIEVAL.WRONG_MATCH\",\n \"MEMORY.STATE.CORRUPTED\",\n \"MEMORY.STATE.INCONSISTENT\",\n \"MEMORY.STATE.LOST\",\n \"MEMORY.STATE.OVERFLOW\",\n \"MEMORY.STATE.STALE\",\n \"ORCHESTRATION.DELEGATION.CAPABILITY_MISMATCH\",\n \"ORCHESTRATION.DELEGATION.CIRCULAR_DELEGATION\",\n \"ORCHESTRATION.DELEGATION.EXCESSIVE_DEPTH\",\n \"ORCHESTRATION.DELEGATION.NO_AVAILABLE_AGENT\",\n \"ORCHESTRATION.DELEGATION.OVERLOADED_AGENT\",\n \"ORCHESTRATION.LIFECYCLE.CLEANUP_FAILED\",\n \"ORCHESTRATION.LIFECYCLE.CRASHED\",\n \"ORCHESTRATION.LIFECYCLE.HUNG\",\n \"ORCHESTRATION.LIFECYCLE.SPAWN_FAILED\",\n \"ORCHESTRATION.LIFECYCLE.ZOMBIE\",\n \"ORCHESTRATION.SCALING.OVERLOADED\",\n \"ORCHESTRATION.SCALING.QUOTA_EXCEEDED\",\n \"ORCHESTRATION.SCALING.SCALE_DOWN_FAILED\",\n \"ORCHESTRATION.SCALING.SCALE_UP_FAILED\",\n \"ORCHESTRATION.SCALING.UNDERUTILIZED\",\n \"OUTPUT.FORMAT.ENCODING\",\n \"OUTPUT.FORMAT.INVALID_JSON\",\n \"OUTPUT.FORMAT.MALFORMED\",\n \"OUTPUT.FORMAT.SCHEMA_VIOLATION\",\n \"OUTPUT.FORMAT.TRUNCATED\",\n \"OUTPUT.QUALITY.INCOMPLETE\",\n \"OUTPUT.QUALITY.IRRELEVANT\",\n \"OUTPUT.QUALITY.REPETITIVE\",\n \"OUTPUT.QUALITY.UNCLEAR\",\n \"OUTPUT.QUALITY.VERBOSE\",\n \"OUTPUT.SAFETY.BIAS\",\n \"OUTPUT.SAFETY.COPYRIGHT\",\n \"OUTPUT.SAFETY.HARMFUL_CONTENT\",\n \"OUTPUT.SAFETY.PII_LEAK\",\n \"OUTPUT.SAFETY.POLICY_VIOLATION\",\n \"PERCEPTION.CONTEXT.CONFLICTING\",\n \"PERCEPTION.CONTEXT.IRRELEVANT\",\n \"PERCEPTION.CONTEXT.MISSING\",\n \"PERCEPTION.CONTEXT.OVERFLOW\",\n \"PERCEPTION.CONTEXT.STALE\",\n \"PERCEPTION.INPUT.ENCODING\",\n \"PERCEPTION.INPUT.INJECTION\",\n \"PERCEPTION.INPUT.MALFORMED\",\n \"PERCEPTION.INPUT.SCHEMA_MISMATCH\",\n \"PERCEPTION.INPUT.TRUNCATED\",\n \"PERCEPTION.PARSING.DATE_FORMAT\",\n \"PERCEPTION.PARSING.JSON_INVALID\",\n \"PERCEPTION.PARSING.NUMBER_FORMAT\",\n \"PERCEPTION.PARSING.REFERENCE_BROKEN\",\n \"PERCEPTION.PARSING.XML_INVALID\",\n \"REASONING.DECISION.BIASED\",\n \"REASONING.DECISION.INDECISIVE\",\n \"REASONING.DECISION.OSCILLATING\",\n \"REASONING.DECISION.OVERCONFIDENT\",\n \"REASONING.DECISION.PREMATURE\",\n \"REASONING.HALLUCINATION.CAPABILITY\",\n \"REASONING.HALLUCINATION.CITATION\",\n \"REASONING.HALLUCINATION.ENTITY\",\n \"REASONING.HALLUCINATION.FACTUAL\",\n \"REASONING.HALLUCINATION.TEMPORAL\",\n \"REASONING.LOGIC.CIRCULAR\",\n \"REASONING.LOGIC.CONTRADICTION\",\n \"REASONING.LOGIC.INCOMPLETE\",\n \"REASONING.LOGIC.INVALID_INFERENCE\",\n \"REASONING.LOGIC.MISSING_PREMISE\",\n \"REASONING.PLANNING.INCOMPLETE\",\n \"REASONING.PLANNING.INFEASIBLE\",\n \"REASONING.PLANNING.SCOPE_CREEP\",\n \"REASONING.PLANNING.SUBOPTIMAL\",\n \"REASONING.PLANNING.UNSAFE\",\n \"RESOURCES.ACCESS.DENIED\",\n \"RESOURCES.ACCESS.EXPIRED\",\n \"RESOURCES.ACCESS.LOCKED\",\n \"RESOURCES.ACCESS.NOT_FOUND\",\n \"RESOURCES.ACCESS.REVOKED\",\n \"RESOURCES.CONTENTION.DEADLOCK\",\n \"RESOURCES.CONTENTION.OVERFLOW\",\n \"RESOURCES.CONTENTION.PRIORITY_INVERSION\",\n \"RESOURCES.CONTENTION.STARVATION\",\n \"RESOURCES.CONTENTION.THRASHING\",\n \"RESOURCES.QUOTA.ALLOCATION_FAILED\",\n \"RESOURCES.QUOTA.EXCEEDED\",\n \"RESOURCES.QUOTA.LEAK\",\n \"RESOURCES.QUOTA.STALE\",\n \"RESOURCES.QUOTA.UNFAIR_DISTRIBUTION\",\n \"TOOL.EXECUTION.CRASHED\",\n \"TOOL.EXECUTION.DEPENDENCY_FAILED\",\n \"TOOL.EXECUTION.RATE_LIMITED\",\n \"TOOL.EXECUTION.RESOURCE_EXHAUSTED\",\n \"TOOL.EXECUTION.TIMEOUT\",\n \"TOOL.INVOCATION.INVALID_ARGS\",\n \"TOOL.INVOCATION.MISSING_REQUIRED\",\n \"TOOL.INVOCATION.NOT_FOUND\",\n \"TOOL.INVOCATION.PERMISSION_DENIED\",\n \"TOOL.INVOCATION.TYPE_MISMATCH\",\n \"TOOL.RESULT.EMPTY\",\n \"TOOL.RESULT.ERROR_IN_RESULT\",\n \"TOOL.RESULT.PARTIAL\",\n \"TOOL.RESULT.UNEXPECTED_FORMAT\",\n \"TOOL.RESULT.UNPARSEABLE\",\n]);\n\nexport interface TaxonomyRule {\n re: RegExp;\n code: string;\n}\n\n/**\n * risicare-core's keyword rules (`classify_error`). Python applies them FIRST,\n * to the lowercased message only. Order matters: first match wins.\n */\nexport const CORE_RULES: readonly TaxonomyRule[] = [\n { re: new RegExp(\"json\", 'u'), code: \"PERCEPTION.PARSING.JSON_INVALID\" },\n { re: new RegExp(\"encoding\", 'u'), code: \"PERCEPTION.INPUT.ENCODING\" },\n { re: new RegExp(\"injection\", 'u'), code: \"PERCEPTION.INPUT.INJECTION\" },\n { re: new RegExp(\"malformed\", 'u'), code: \"PERCEPTION.INPUT.MALFORMED\" },\n { re: new RegExp(\"hallucin\", 'u'), code: \"REASONING.HALLUCINATION.FACTUAL\" },\n { re: new RegExp(\"contradict\", 'u'), code: \"REASONING.LOGIC.CONTRADICTION\" },\n { re: new RegExp(\"timeout\", 'u'), code: \"TOOL.EXECUTION.TIMEOUT\" },\n { re: new RegExp(\"rate[^\\\\n]?limit\", 'u'), code: \"TOOL.EXECUTION.RATE_LIMITED\" },\n { re: new RegExp(\"permission\", 'u'), code: \"TOOL.INVOCATION.PERMISSION_DENIED\" },\n { re: new RegExp(\"context[^\\\\n]+overflow\", 'u'), code: \"MEMORY.CONTEXT_WINDOW.EXCEEDED\" },\n { re: new RegExp(\"state[^\\\\n]+corrupt\", 'u'), code: \"MEMORY.STATE.CORRUPTED\" },\n { re: new RegExp(\"pii\", 'u'), code: \"OUTPUT.SAFETY.PII_LEAK\" },\n { re: new RegExp(\"deadlock\", 'u'), code: \"COORDINATION.WORKFLOW.DEADLOCK\" },\n { re: new RegExp(\"undeliverable\", 'u'), code: \"COMMUNICATION.DELIVERY.UNDELIVERABLE\" },\n { re: new RegExp(\"crash\", 'u'), code: \"ORCHESTRATION.LIFECYCLE.CRASHED\" },\n { re: new RegExp(\"quorum\", 'u'), code: \"CONSENSUS.AGREEMENT.QUORUM_FAILED\" },\n { re: new RegExp(\"quota[^\\\\n]+exceed\", 'u'), code: \"RESOURCES.QUOTA.EXCEEDED\" },\n];\n\n/** Order matters: first match wins, most specific first. */\nexport const SUPPLEMENTAL_RULES: readonly TaxonomyRule[] = [\n { re: new RegExp(\"timeout|timedout|aborted\", 'u'), code: \"TOOL.EXECUTION.TIMEOUT\" },\n { re: new RegExp(\"rate[^\\\\n]?limit|(?<![\\\\p{L}\\\\p{N}_])429(?![\\\\p{L}\\\\p{N}_])|too many requests\", 'u'), code: \"TOOL.EXECUTION.RATE_LIMITED\" },\n { re: new RegExp(\"connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe\", 'u'), code: \"TOOL.EXECUTION.DEPENDENCY_FAILED\" },\n { re: new RegExp(\"(?<![\\\\p{L}\\\\p{N}_])auth|unauthorized|forbidden|permission|(?<![\\\\p{L}\\\\p{N}_])401(?![\\\\p{L}\\\\p{N}_])|(?<![\\\\p{L}\\\\p{N}_])403(?![\\\\p{L}\\\\p{N}_])\", 'u'), code: \"TOOL.INVOCATION.PERMISSION_DENIED\" },\n { re: new RegExp(\"json|syntaxerror|unexpected token|decodeerror\", 'u'), code: \"PERCEPTION.PARSING.JSON_INVALID\" },\n];\n\nexport const GENERIC_FALLBACK = \"TOOL.EXECUTION.CRASHED\";\n","/**\n * Single source of truth for the SDK version on the wire.\n *\n * F-720/F-351: prior to this file, two separate `SDK_VERSION` constants\n * existed in `exporters/http.ts` (\"0.1.1\") and `runtime/loader.ts` (\"0.1.3\"),\n * while `package.json` declared \"0.4.0\". Three different versions on the\n * wire confused customer telemetry and dashboard SDK-version-cohort filters.\n *\n * This file MUST stay in lock-step with the `version` field in\n * `packages/risicare-sdk-js/package.json`. Bumping the version is a\n * two-file edit (`package.json` + this file). The `prepublishOnly` script\n * verifies the match before any npm publish.\n *\n * Kept as a plain TS constant (not a runtime read of package.json) because:\n * 1. tsup bundles to ESM AND CJS for both Node and Edge; runtime fs\n * reads of package.json break in bundled-Edge environments.\n * 2. A constant inlines at tree-shake time, so no extra bytes shipped.\n * 3. The version is read in the hot path (every export); a static value\n * avoids per-call import-meta-resolve overhead.\n */\nexport const SDK_VERSION = '0.11.0';\n","/**\n * The monthly-quota discard of the Risicare ingest gateway (metering step S-1).\n *\n * When an organisation has used its monthly event quota, the gateway answers a request with\n * HTTP 200, discards it and queues nothing. The answer is one of these shapes, and every one\n * of them also carries the header `X-Risicare-Quota: exceeded`:\n *\n * - `/v1/spans`, `/v1/spans/batch`:\n * `{\"accepted\":0,\"rejected\":N,\"reason\":\"monthly_quota_exceeded\",\"resetsAt\":\"2026-11-01T00:00:00Z\",\"retryAfterSeconds\":300}`\n * - `/v1/traces` (native):\n * `{\"tracesAccepted\":0,\"spansAccepted\":0,\"spansRejected\":N,\"reason\":\"monthly_quota_exceeded\",\"resetsAt\":\"…\",\"retryAfterSeconds\":300}`\n * - OTLP/HTTP JSON:\n * `{\"partialSuccess\":{\"rejectedSpans\":N,\"errorMessage\":\"monthly_quota_exceeded; resets_at=…; retry_after_seconds=300\"}}`\n *\n * A discard is NOT an error. It is not retried, it does not count toward the circuit breaker,\n * and the SDK does not sleep until `resetsAt`. The exporter PAUSES for `retryAfterSeconds`\n * (300 s when the answer names none). In that time the batch processor keeps ended spans in its\n * existing bounded queue (`exporter.quotaPaused()`); then it sends one real batch as a probe,\n * and drains the queue when the backend accepts. A span is counted as `quota_exceeded` in\n * `droppedSpansByReason` only when the queue overflows in the pause, or when a probe batch is\n * discarded. A customer who upgrades or buys a pack is accepted again within one pause, not at\n * next month, and nothing new is lost unless the queue overflows.\n *\n * Python twin: `exporters/_quota.py`. Both follow the contract of the ingest gateway\n * (its quota middleware and its `/v1/spans`, `/v1/traces` and OTLP routes). The JS SDK\n * has no OTLP exporter; `parseOtlpDiscard` is kept for parity and for a custom exporter.\n */\n\nimport { debug, info, warn } from '../utils/log.js';\n\nexport const QUOTA_REASON = 'monthly_quota_exceeded';\nexport const QUOTA_HEADER = 'X-Risicare-Quota';\nexport const QUOTA_HEADER_VALUE = 'exceeded';\n\n/** Used when the answer names no (usable) `retryAfterSeconds`. The gateway always sends 300. */\nexport const DEFAULT_RETRY_AFTER_S = 300;\n/**\n * A server value is believed only inside this range. The floor stops a request loop (0 or a\n * negative number). The cap stops one bad value from silencing the SDK for a month.\n */\nexport const MIN_RETRY_AFTER_S = 1;\nexport const MAX_RETRY_AFTER_S = 3600;\n/** One WARNING when the pause starts, then at most one in this window while it lasts. */\nexport const QUOTA_WARN_WINDOW_MS = 3_600_000;\n\nconst MAX_RESETS_AT_CHARS = 40;\n\n/** What a quota-discard answer says. Both fields are already checked and bounded. */\nexport interface QuotaDiscard {\n retryAfterS: number;\n resetsAt: string | null;\n}\n\n/** True for a number (or proto3 JSON string) count above 0. */\nfunction asPositiveCount(v: unknown): boolean {\n if (typeof v === 'number') return Number.isFinite(v) && v > 0;\n if (typeof v === 'string' && /^[0-9]+$/.test(v)) return Number(v) > 0;\n return false;\n}\n\n/** The pause in seconds: the server's number inside [1, 3600], else the default. */\nexport function boundedRetryAfter(value: unknown): number {\n let n: number;\n if (typeof value === 'number') n = value;\n else if (typeof value === 'string' && value.trim() !== '') n = Number(value);\n else return DEFAULT_RETRY_AFTER_S;\n if (!Number.isFinite(n)) return DEFAULT_RETRY_AFTER_S;\n return Math.min(Math.max(n, MIN_RETRY_AFTER_S), MAX_RETRY_AFTER_S);\n}\n\n/** `resetsAt` for a log line: one printable ASCII line, at most 40 characters. */\nfunction boundedResetsAt(value: unknown): string | null {\n if (typeof value !== 'string' || value.length === 0) return null;\n const cut = value.slice(0, MAX_RESETS_AT_CHARS);\n return /^[ -~]*$/.test(cut) ? cut : null;\n}\n\n/** True when the answer carries `X-Risicare-Quota: exceeded`. */\nexport function headerSaysExceeded(\n headers: { get?: (name: string) => string | null } | null | undefined,\n): boolean {\n try {\n const value = headers?.get?.(QUOTA_HEADER);\n return typeof value === 'string' && value.trim().toLowerCase() === QUOTA_HEADER_VALUE;\n } catch {\n return false;\n }\n}\n\n/**\n * A quota discard in the JSON shape of `/v1/spans` or `/v1/traces`, else `null`.\n *\n * `reason === \"monthly_quota_exceeded\"` decides. The header alone decides too, when the body is\n * something else (an old or a future shape): the header is the contract's second signal.\n */\nexport function parseJsonDiscard(\n payload: unknown,\n headers?: { get?: (name: string) => string | null } | null,\n): QuotaDiscard | null {\n const body: Record<string, unknown> =\n payload !== null && typeof payload === 'object' && !Array.isArray(payload)\n ? (payload as Record<string, unknown>)\n : {};\n // The header alone decides only when the body does not show stored spans. A well-formed ack\n // with accepted > 0 (or spansAccepted > 0) is a healthy batch, whatever a proxy added.\n const stored = (asPositiveCount(body.accepted) || asPositiveCount(body.spansAccepted)) === true;\n if (body.reason === QUOTA_REASON || (headerSaysExceeded(headers) && !stored)) {\n return {\n retryAfterS: boundedRetryAfter(body.retryAfterSeconds),\n resetsAt: boundedResetsAt(body.resetsAt),\n };\n }\n return null;\n}\n\n/**\n * A quota discard in the OTLP shape (`partialSuccess.errorMessage`), else `null`. OTLP has no\n * field for a reason, so the gateway leads the message with it:\n * `monthly_quota_exceeded; resets_at=<RFC 3339>; retry_after_seconds=300`.\n */\nexport function parseOtlpDiscard(\n payload: unknown,\n headers?: { get?: (name: string) => string | null } | null,\n): QuotaDiscard | null {\n const partial =\n payload !== null && typeof payload === 'object'\n ? (payload as { partialSuccess?: { errorMessage?: unknown } }).partialSuccess\n : undefined;\n const message = partial?.errorMessage;\n const fields: Record<string, string> = {};\n let byMessage = false;\n if (typeof message === 'string') {\n const parts = message.split(';').map((p) => p.trim());\n byMessage = parts[0] === QUOTA_REASON;\n if (byMessage) {\n for (const part of parts.slice(1)) {\n const at = part.indexOf('=');\n if (at > 0) fields[part.slice(0, at).trim()] = part.slice(at + 1).trim();\n }\n }\n }\n if (!byMessage) {\n // The header alone decides when nothing is shown as stored: no partialSuccess, or\n // rejectedSpans > 0. A partialSuccess that rejects no span is a healthy batch.\n if (!headerSaysExceeded(headers)) return null;\n if (partial !== undefined && partial !== null && typeof partial === 'object') {\n if (!asPositiveCount((partial as { rejectedSpans?: unknown }).rejectedSpans)) return null;\n }\n }\n return {\n retryAfterS: boundedRetryAfter(fields['retry_after_seconds']),\n resetsAt: boundedResetsAt(fields['resets_at']),\n };\n}\n\n/**\n * An episode ends only after this many accepted batches in a row. The gateway fails open for an\n * organisation over its quota (a slow policy read, a busy pool), so one probe is sometimes\n * accepted although the quota is still used up. One accept must not end the episode.\n */\nexport const EPISODE_END_ACCEPTS = 3;\n\n/**\n * The paused state of one exporter, and its log lines.\n *\n * - `enter()` starts (or extends) the pause. It writes one WARNING, and at most one an hour for\n * the life of the process: the window is NOT reset when an episode ends, so a gateway that\n * accepts a probe now and then cannot make a WARNING and an INFO for every probe.\n * - `paused()` is true until `retryAfterS` has passed. After that the exporter sends one real\n * batch (the probe). A probe that is discarded again calls `enter()` again.\n * - `accepted()` counts a batch that the backend took. After `EPISODE_END_ACCEPTS` in a row the\n * episode ends, with one INFO (rate-limited like the WARNING). A discard in between starts the\n * count again.\n *\n * `now` is a MONOTONIC clock in ms (`performance.now`), not the wall clock: a step of the wall\n * clock (NTP, a VM restore, sleep and resume) must not lengthen the pause or the log window past\n * their caps. A test can inject its own.\n */\nexport class QuotaPause {\n private _until = -Infinity;\n private _inEpisode = false;\n private _accepts = 0;\n private _lastWarn = -Infinity;\n private _lastInfo = -Infinity;\n /**\n * Spans dropped since the last WARNING: the full queue's (`addDrops`) and the batches that a\n * probe lost while the WARNING was held back. The WARNING carries the number.\n */\n private _drops = 0;\n\n constructor(private readonly now: () => number = () => performance.now()) {}\n\n addDrops(count: number): void {\n this._drops += count;\n }\n\n paused(): boolean {\n return this.now() < this._until;\n }\n\n remainingS(): number {\n return Math.max(0, (this._until - this.now()) / 1000);\n }\n\n enter(discard: QuotaDiscard, where: string, dropped: number): void {\n const t = this.now();\n this._until = t + discard.retryAfterS * 1000;\n this._inEpisode = true;\n this._accepts = 0;\n if (t - this._lastWarn >= QUOTA_WARN_WINDOW_MS) {\n this._lastWarn = t;\n const since = this._drops;\n this._drops = 0;\n warn(\n `Risicare: the monthly event quota is used up (monthly_quota_exceeded). ${where} ` +\n `discarded ${dropped} span(s) and will discard new ones until the quota resets ` +\n `(resetsAt=${discard.resetsAt ?? 'unknown'}) or the plan changes. The SDK pauses ` +\n `export and sends one batch again in ${Math.round(discard.retryAfterS)} s. Spans ` +\n `that end in the meantime wait in the queue. When it is full the oldest spans are ` +\n `dropped (the most recent are kept) and counted as quota_exceeded in ` +\n `droppedSpansByReason; a batch that is discarded again is dropped and counted the ` +\n `same way. This is not an error and the SDK does not retry the batch. At most one ` +\n `such WARNING an hour.` +\n (since > 0 ? ` Spans dropped for the quota since the last WARNING: ${since}.` : ''),\n );\n } else {\n this._drops += dropped;\n debug(`Quota discard again: ${dropped} span(s); paused for ${Math.round(discard.retryAfterS)} s`);\n }\n }\n\n accepted(where: string): void {\n if (!this._inEpisode) return;\n this._accepts++;\n if (this._accepts < EPISODE_END_ACCEPTS) return;\n this._inEpisode = false;\n this._accepts = 0;\n this._until = -Infinity;\n const t = this.now();\n if (t - this._lastInfo >= QUOTA_WARN_WINDOW_MS) {\n this._lastInfo = t;\n info(`Risicare: ${where} accepts spans again; the export pause for the quota has ended.`);\n } else {\n debug('Quota pause ended (INFO already written this hour)');\n }\n }\n}\n","/**\n * HTTP exporter for sending spans to the Risicare gateway.\n *\n * Uses native fetch (Node.js 18+), with:\n * - The W2-1c retry policy (`retry.ts`): retryable answers are sent again with full-jitter\n * backoff until the retry horizon; 413 splits the batch one time; every other answer is\n * sent once\n * - Circuit breaker for answers that a retry cannot change\n * - Never follows a redirect; a 3xx or a 2xx without a Risicare ack is a FAILURE\n * - Gzip compression for large payloads\n * - Bearer token authentication\n */\n\nimport type { Span } from '../span.js';\nimport { ExportResult, type AckCounts, type ExporterDropReason, type SpanExporter } from './base.js';\nimport { debug, warn } from '../utils/log.js';\nimport { SDK_VERSION } from '../version.js';\nimport { hasCredentials, safeUrl, scrubText } from '../utils/scrub.js';\nimport { QuotaPause, parseJsonDiscard, type QuotaDiscard } from './quota.js';\nimport {\n DEFAULT_RETRY_HORIZON_S,\n RETRY_STATUSES,\n RETRY_WARN_AFTER_ATTEMPTS,\n TOO_LARGE_STATUS,\n backoffDelayS,\n jitter,\n parseRetryAfterS,\n} from './retry.js';\n\nexport interface HttpExporterOptions {\n endpoint: string;\n apiKey?: string;\n projectId?: string;\n environment?: string;\n timeoutMs?: number;\n /**\n * The most attempts for one request body. Not given (the default after 0.10.0; it was 3):\n * no count, the retry horizon is the limit. A batch that reaches the count with a\n * retryable answer is dropped with the reason `retry_exhausted`. An answer that a retry\n * cannot change is sent once in all cases.\n */\n maxRetries?: number;\n compress?: boolean;\n /**\n * How long one batch is retried, in seconds from its first attempt (default 300). No\n * backoff wait goes past it. When it is used up, the batch is dropped with the reason\n * `retry_exhausted`: a gateway outage that is longer than the horizon loses spans. 0 sends\n * each batch once. The check is between attempts, so the last attempt can end up to one\n * request timeout after the horizon.\n */\n retryHorizonS?: number;\n}\n\n/**\n * W2-1c · THE RETRY POLICY (`exporters/retry.ts`; the Python twin is `exporters/_retry.py`).\n *\n * One `export()` call sends one batch and owns all of its retries:\n *\n * - 408, 429, 500, 502, 503, 504, a connection error and a timeout are retried, with\n * full-jitter exponential backoff (base 1 s, cap 30 s). `Retry-After` (seconds or an HTTP\n * date) replaces the computed wait when it is more than 0 s. No wait goes past the retry\n * horizon (`retryHorizonS`, default 300 s), which starts at the first attempt of the batch.\n * When the horizon is used up, the batch is dropped with the reason `retry_exhausted`\n * (`takeDropReason`).\n * - 413: the batch is split in two one time and both halves are sent. A half that gets 413\n * again is dropped with the reason `too_large` (`AckCounts.dropped`).\n * - Every other answer is sent one time: 400, 401, 403, 404, 422 and the rest, a redirect, a\n * 2xx that is not a Risicare ack, and an ack of 0 and 0. The batch is dropped with the\n * reason `transport_refused`.\n *\n * ⚠ THE CIRCUIT BREAKER COUNTS FINISHED CALLS, NEVER SINGLE ATTEMPTS. A call that ends refused\n * (one attempt) counts, and so does a call that ends `retry_exhausted`, EXCEPT when its last\n * answer was a capacity refusal (429 or 503): F-SDK503-001 found that counting a healthy server\n * that sheds load opened the breaker within a second and then discarded everything for 60 s.\n * With the default horizon a dead endpoint therefore opens the breaker only after five batches\n * in a row were retried for 300 s each. While it is open, a batch is dropped as\n * `transport_refused` with no request; after the cooldown the next call is the probe. Through\n * 0.10.0 the half-open probe was a single attempt with no retry; it now follows the policy, as\n * in Python.\n */\n\n/** Statuses that a WARNING calls \"over capacity\" (the server shed load). */\nconst CAPACITY_REFUSAL_STATUSES: ReadonlySet<number> = new Set([429, 503]);\n\n/**\n * ⚠ A MISROUTE IS A CONFIGURATION ERROR, NOT AN OUTAGE (0.7.0). Two answers mean that the\n * request did not reach the Risicare ingest gateway: a 3xx, and a 2xx whose body is not a\n * Risicare ack. Measured: the old default `https://app.risicare.ai` is the dashboard, and it\n * answers `POST /v1/spans` with `307 -> /login`. Through 0.6.0 `fetch` followed that\n * redirect, got the login page as an HTML 200, and `checkAck` returned SUCCESS. Now:\n * - `fetch` runs with `redirect: 'manual'`, so a 3xx comes back as the answer;\n * - the retry loop stops at the first misroute — no backoff, no second attempt;\n * - the failure COUNTS toward the circuit breaker, as every refused answer does: 5\n * requests, then the breaker opens, then one probe per cooldown (60 s);\n * - one warning names the endpoint and the answer, at most once per 5 minutes.\n * Python twin: `exporters/http.py`, the block above `HttpExporter`.\n */\nconst MISROUTE_WARN_WINDOW_MS = 300_000;\n\n/**\n * An AUTH REFUSAL cannot change on a retry: the same key gets the same answer. The WARNING\n * then says to check the API key. The Python twin uses the same two statuses.\n */\nconst AUTH_REFUSAL_STATUSES: ReadonlySet<number> = new Set([401, 403]);\n\n/**\n * The WARNING for a failed export (\"spans are NOT reaching ...\") is written at the\n * first failure of an outage, and at most once in this window. Python twin:\n * `_failure_warn_window` (300 s). The `retry_exhausted` WARNING uses the same window.\n */\nconst FAILURE_WARN_WINDOW_MS = 300_000;\n\n/** The largest delay that `setTimeout` accepts (2**31 - 1 ms). */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\n/** `retryHorizonS` as a finite number of 0 or more. Another value gives the default, with a WARNING. */\nfunction validHorizonS(value: unknown): number {\n if (value === undefined) return DEFAULT_RETRY_HORIZON_S;\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value;\n warn(\n `Risicare: retryHorizonS=${String(value)} is not a finite number of 0 or more; using the ` +\n `default, ${DEFAULT_RETRY_HORIZON_S} s.`,\n );\n return DEFAULT_RETRY_HORIZON_S;\n}\n\n/**\n * The state of one `export()` call: the answer of its last attempt and its cancel signal.\n * It is per call, not on the instance, so that concurrent calls (two processors that share\n * one exporter) cannot read each other's answers across an `await`.\n */\ninterface Call {\n cancel: AbortController;\n /** The `Retry-After` wait of a retryable answer, in seconds. `null` = no usable header. */\n retryAfterS: number | null;\n /** A MISROUTE: a short description of the answer. `null` = none. */\n misroute: string | null;\n /** The answer cannot change on a retry (an ack of 0 and 0). */\n noRetry: boolean;\n /** The HTTP status of the last answer. `null` = no answer. For the WARNING and the retry loop. */\n status: number | null;\n /** The error code or class when the last attempt got no answer. `null` = none. */\n error: string | null;\n /** How many requests this call started (each retry and each half of a split counts). */\n attempts: number;\n /** The ack counts of the last attempt, when it succeeded. */\n ack: AckCounts | null;\n}\n\n/** The answer of the last attempt of a part, for a WARNING and for the breaker. */\ninterface Answer {\n status: number | null;\n error: string | null;\n misroute: string | null;\n zeroAck: boolean;\n sent: number;\n}\n\ntype PartResult =\n | { kind: 'delivered'; ack: AckCounts | null }\n | { kind: 'too_large' }\n | { kind: 'cancelled' }\n | { kind: 'transport_refused' | 'retry_exhausted' | 'shutdown_residue'; answer: Answer };\n\n/** What happened to the parts of one batch in one `export()` call. */\ninterface Outcome {\n /** (span count, ack or null) for each part that the backend took. */\n delivered: Array<{ n: number; ack: AckCounts | null }>;\n /** Spans that a 413 split dropped, by reason (`too_large`). */\n dropped: Partial<Record<ExporterDropReason, number>>;\n /** (span count, reason, answer) for each part that failed. */\n failed: Array<{ n: number; reason: 'transport_refused' | 'retry_exhausted' | 'shutdown_residue'; answer: Answer }>;\n cancelled: boolean;\n}\n\nexport class HttpExporter implements SpanExporter {\n readonly name = 'http';\n\n private readonly _endpoint: string;\n private readonly _apiKey: string | undefined;\n private readonly _projectId: string | undefined;\n private readonly _environment: string | undefined;\n private readonly _timeoutMs: number;\n private readonly _maxRetries: number | undefined;\n private readonly _compress: boolean;\n private readonly _retryHorizonS: number;\n\n /** Total HTTP requests that this exporter sent (each retry and each half of a split counts). */\n attempts = 0;\n\n // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for\n // a \"30-second prod restart\" scenario. Since W2-1c only answers that a retry\n // cannot change move it (see the block above).\n private _consecutiveFailures = 0;\n private _lastMisrouteWarnAt = -Infinity;\n private _lastFailureWarnAt = -Infinity;\n private _lastExhaustedWarnAt = -Infinity;\n /** \"log once\" (W2-1c): the WARNING for a `too_large` drop is written one time. */\n private _tooLargeWarned = false;\n /**\n * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',\n * 'unknown'). `null` after a success. A new kind in the same outage writes one more\n * WARNING, also inside the window.\n */\n private _failureKind: string | null = null;\n /** `endRetries()` was called, and `shutdown()` has not run since. */\n private _noWait = false;\n /** The wake-ups of the backoff waits in progress. `endRetries()` calls each one. */\n private readonly _waits = new Set<() => void>();\n /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */\n private readonly _safeEndpoint: string;\n /** The endpoint holds userinfo. `fetch` refuses such a URL. */\n private readonly _endpointHasCredentials: boolean;\n /** The calls in progress, by their batch, so that `abort(spans)` stops the right one. */\n private readonly _calls = new Map<Span[], Call>();\n /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */\n private readonly _acks = new WeakMap<Span[], AckCounts>();\n /** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */\n private readonly _requests = new WeakMap<Span[], number>();\n /** The drop reason of each failed call, by its batch. Read once by `takeDropReason(spans)`. */\n private readonly _dropReasons = new WeakMap<Span[], ExporterDropReason>();\n /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */\n noteQuotaDrop(count = 1): void {\n this._quota.addDrops(count);\n }\n\n /** True while the exporter is paused for the monthly event quota (S-1). */\n quotaPaused(): boolean {\n return this._quota.paused();\n }\n\n /** The spans of each finished call that could not be serialized, by its batch. */\n private readonly _unserializable = new WeakMap<Span[], Span[]>();\n /**\n * S-1: the paused state after a monthly-quota discard (see `quota.ts`). A discard is not a\n * failure: it does not touch the circuit breaker.\n */\n private readonly _quota = new QuotaPause();\n private _circuitOpenUntil = 0;\n private readonly _circuitBreakerThreshold = 5;\n private readonly _circuitBreakerCooldownMs = 60_000;\n\n constructor(options: HttpExporterOptions) {\n this._endpoint = options.endpoint.replace(/\\/+$/, '');\n this._apiKey = options.apiKey;\n this._projectId = options.projectId;\n this._environment = options.environment;\n this._timeoutMs = options.timeoutMs ?? 5000;\n let maxRetries = options.maxRetries;\n if (maxRetries !== undefined && !(Number.isInteger(maxRetries) && maxRetries >= 1)) {\n warn(\n `Risicare: maxRetries=${String(maxRetries)} is not a whole number of 1 or more; the ` +\n `exporter uses no count limit (the retry horizon is the limit).`,\n );\n maxRetries = undefined;\n }\n this._maxRetries = maxRetries;\n this._compress = options.compress ?? false;\n this._retryHorizonS = validHorizonS(options.retryHorizonS);\n this._safeEndpoint = safeUrl(this._endpoint);\n this._endpointHasCredentials = hasCredentials(this._endpoint);\n }\n\n /**\n * Network or error text for a log line: the endpoint as `safeUrl` gives it, and no\n * form of the API key (`utils/scrub.ts`).\n */\n private _scrub(text: unknown, limit = 200): string {\n let out: string;\n try {\n out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);\n } catch {\n out = typeof text;\n }\n if (this._safeEndpoint !== this._endpoint) out = out.split(this._endpoint).join(this._safeEndpoint);\n return scrubText(out, [this._apiKey], limit);\n }\n\n /** Hide the key from `util.inspect` and `console.log` of the exporter. */\n [Symbol.for('nodejs.util.inspect.custom')](): string {\n return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;\n }\n\n /**\n * The most attempts for one request body (`maxRetries`). `undefined` when no count is set:\n * the retry horizon is the limit.\n */\n get attemptsPerExport(): number | undefined {\n return this._maxRetries;\n }\n\n /**\n * Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears\n * it. Each retry and each half of a 413 split counts one; a call that the open circuit\n * breaker or the quota pause stops sends none. Returns `null` when no call is on record for\n * `spans`. The answer is kept per batch, as `takeAck` keeps the ack.\n */\n takeAttempts(spans: Span[]): number | null {\n const n = this._requests.get(spans) ?? null;\n this._requests.delete(spans);\n return n;\n }\n\n /**\n * Returns the counts of the ack that the `export()` call for `spans` received, and clears\n * them. The answer is kept per batch, not on the instance: two processors that share this\n * exporter cannot read each other's ack across an `await`.\n */\n takeAck(spans: Span[]): AckCounts | null {\n const ack = this._acks.get(spans) ?? null;\n this._acks.delete(spans);\n return ack;\n }\n\n /** Returns why the `export()` call for `spans` failed (W2-1c), and clears it. See `SpanExporter`. */\n takeDropReason(spans: Span[]): ExporterDropReason | null {\n const reason = this._dropReasons.get(spans) ?? null;\n this._dropReasons.delete(spans);\n return reason;\n }\n\n /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */\n takeUnserializable(spans: Span[]): Span[] {\n const bad = this._unserializable.get(spans) ?? [];\n this._unserializable.delete(spans);\n return bad;\n }\n\n /**\n * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its\n * request, its retries and its backoff wait. The batch processor calls it when\n * `shutdown()` abandons the batch, so that the call does not keep the process alive. The\n * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and\n * logs no WARNING.\n */\n abort(spans?: Span[]): void {\n if (spans !== undefined) this._calls.get(spans)?.cancel.abort();\n else for (const call of this._calls.values()) call.cancel.abort();\n }\n\n /**\n * End the retry waits of this exporter until its next `shutdown()`. The batch processor\n * calls it when `shutdown()` starts. A call that waits for a retry makes one more attempt\n * at once. An attempt that fails after this is not retried: the call fails with the drop\n * reason `shutdown_residue`. So a drain against a dead endpoint costs one attempt for each\n * batch, not the shutdown budget.\n */\n endRetries(): void {\n this._noWait = true;\n for (const wake of [...this._waits]) wake();\n }\n\n /**\n * Send one batch, with the W2-1c retry policy (see the block above the class).\n *\n * Resolves SUCCESS when the backend accounted for the batch: `takeAck` has the counts (and\n * the spans that a 413 split dropped, in `dropped`). Resolves FAILURE when no span was\n * accounted for: `takeDropReason` then says why, and the batch processor drops the batch\n * with that reason.\n *\n * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never\n * cuts a request that is already sent. Only `abort()` stops the call, and only\n * `shutdown()` calls it.\n */\n async export(spans: Span[]): Promise<ExportResult> {\n if (spans.length === 0) return ExportResult.SUCCESS;\n const call: Call = {\n cancel: new AbortController(),\n retryAfterS: null,\n misroute: null,\n noRetry: false,\n status: null,\n error: null,\n attempts: 0,\n ack: null,\n };\n this._calls.set(spans, call);\n try {\n return await this._export(spans, call);\n } finally {\n this._calls.delete(spans);\n // `fetch` refuses a URL with credentials before it sends anything, so no request left.\n this._requests.set(spans, this._endpointHasCredentials ? 0 : call.attempts);\n }\n }\n\n private async _export(spans: Span[], call: Call): Promise<ExportResult> {\n const cancelled = call.cancel.signal;\n // S-1: the backend discarded the last batch for the monthly quota, and the pause that it\n // named is not over. The batch processor does not call export() in that time (it keeps the\n // spans in its queue). This guard covers an exporter that is used on its own: send nothing,\n // not even a serialization; the batch is dropped here and counted (`quotaDropped`). SUCCESS\n // with ack 0 and 0: not a failure, so the batch processor neither re-queues the batch nor\n // counts a failed export.\n if (this._quota.paused()) {\n debug(\n `Export skipped: monthly quota pause, ${Math.round(this._quota.remainingS())} s left; ` +\n `${spans.length} span(s) dropped`,\n );\n this._acks.set(spans, { accepted: 0, rejected: 0, quotaDropped: spans.length });\n return ExportResult.SUCCESS;\n }\n // Serialize each span alone. A span that cannot be serialized (a BigInt, a circular\n // value) is not sent; the batch processor drops it as `unacknowledged`. Through 0.7.1\n // one such span made the whole batch fail every round, and the WARNING blamed the\n // endpoint.\n const parts: string[] = [];\n const bad: Span[] = [];\n let errorClass = '';\n for (const span of spans) {\n try {\n parts.push(JSON.stringify(span.toPayload()));\n } catch (e) {\n bad.push(span);\n errorClass ||= e instanceof Error ? e.name : typeof e;\n }\n }\n if (bad.length > 0) {\n this._unserializable.set(spans, bad);\n warn(\n `Risicare: ${bad.length} of ${spans.length} span(s) in this batch could not be ` +\n `serialized (${errorClass}), for example an attribute with a BigInt or a circular ` +\n `reference. They are not sent and are counted as dropped (reason=unacknowledged).`,\n );\n }\n if (parts.length === 0) return ExportResult.SUCCESS;\n\n // Circuit breaker. Five finished calls in a row failed (see the block above the class): the\n // batch is dropped as `transport_refused`, with no request. After the cooldown the next call\n // is the probe.\n if (this._consecutiveFailures >= this._circuitBreakerThreshold && Date.now() < this._circuitOpenUntil) {\n this._dropReasons.set(spans, 'transport_refused');\n return ExportResult.FAILURE;\n }\n\n const out: Outcome = { delivered: [], dropped: {}, failed: [], cancelled: false };\n // The retry horizon of the batch starts at its first attempt, and both halves of a 413\n // split share it. `performance.now()` is monotonic.\n const start = performance.now();\n await this._deliver(parts, start, call, out, true);\n // Cancelled by `abort()`: no counter, no breaker step, no WARNING.\n if (cancelled.aborted || out.cancelled) {\n this._acks.delete(spans);\n return ExportResult.FAILURE;\n }\n return this._finish(spans, out, call.attempts);\n }\n\n /** The request body for `parts` (the serialized spans of one part of a batch). */\n private _payload(parts: string[]): string {\n return (\n `{\"spans\":[${parts.join(',')}]` +\n (this._projectId ? `,\"projectId\":${JSON.stringify(this._projectId)}` : '') +\n (this._environment ? `,\"environment\":${JSON.stringify(this._environment)}` : '') +\n '}'\n );\n }\n\n /**\n * Send one part of a batch with the retry policy, and record its outcome in `out`.\n * `maySplit` is true only for the whole batch: a 413 splits it in two one time. A half\n * that gets 413 again is dropped as `too_large`.\n */\n private async _deliver(\n parts: string[],\n start: number,\n call: Call,\n out: Outcome,\n maySplit: boolean,\n ): Promise<void> {\n const n = parts.length;\n if (!maySplit && this._quota.paused()) {\n // The first half entered the monthly-quota pause: the second half is not sent.\n out.delivered.push({ n, ack: { accepted: 0, rejected: 0, quotaDropped: n } });\n return;\n }\n const result = await this._sendWithRetries(this._payload(parts), n, start, call);\n if (result.kind === 'delivered') {\n out.delivered.push({ n, ack: result.ack });\n } else if (result.kind === 'too_large') {\n if (maySplit && n > 1) {\n const mid = Math.ceil(n / 2);\n debug(`Ingest answered HTTP 413 for ${n} span(s): sending two halves of ${mid} and ${n - mid}`);\n await this._deliver(parts.slice(0, mid), start, call, out, false);\n if (!out.cancelled) await this._deliver(parts.slice(mid), start, call, out, false);\n } else {\n out.dropped.too_large = (out.dropped.too_large ?? 0) + n;\n }\n } else if (result.kind === 'cancelled') {\n out.cancelled = true;\n } else {\n out.failed.push({ n, reason: result.kind, answer: result.answer });\n }\n }\n\n /** Send one request body until it is delivered or the policy stops. */\n private async _sendWithRetries(\n body: string,\n spansSent: number,\n start: number,\n call: Call,\n ): Promise<PartResult> {\n const cancelled = call.cancel.signal;\n let retryNumber = 0;\n let attemptsHere = 0;\n for (;;) {\n if (cancelled.aborted) return { kind: 'cancelled' };\n // Cleared before EVERY attempt, so an answer recorded on one attempt cannot be read as\n // the answer of the next (`_sendRequest` swallows transport errors and returns FAILURE\n // without touching these fields).\n call.retryAfterS = null;\n call.misroute = null;\n call.noRetry = false;\n call.status = null;\n call.error = null;\n call.ack = null;\n call.attempts++;\n attemptsHere++;\n this.attempts++;\n const result = await this._sendRequest(body, spansSent, call);\n if (cancelled.aborted) return { kind: 'cancelled' };\n if (result === ExportResult.SUCCESS) return { kind: 'delivered', ack: call.ack };\n if (call.status === TOO_LARGE_STATUS) return { kind: 'too_large' };\n const answer: Answer = {\n status: call.status,\n error: call.error,\n misroute: call.misroute,\n zeroAck: call.noRetry,\n sent: spansSent,\n };\n if (!this._retryable(call)) return { kind: 'transport_refused', answer };\n if (attemptsHere === RETRY_WARN_AFTER_ATTEMPTS) this._warnOutage(answer, true);\n if (this._noWait) return { kind: 'shutdown_residue', answer };\n if (this._maxRetries !== undefined && attemptsHere >= this._maxRetries) {\n return { kind: 'retry_exhausted', answer };\n }\n const remainingS = this._retryHorizonS - (performance.now() - start) / 1000;\n if (remainingS <= 0) return { kind: 'retry_exhausted', answer };\n // No usable header, or one that names no wait (0, or a date that is not in the future):\n // a server that answers that way every time would get a tight loop until the horizon, so\n // the computed backoff applies.\n const hint = call.retryAfterS;\n const waitS = hint !== null && hint > 0 ? hint : backoffDelayS(retryNumber, jitter.fraction());\n const delayS = Math.min(waitS, remainingS);\n retryNumber++;\n debug(\n `Ingest attempt ${attemptsHere} failed (${answer.status ?? answer.error ?? 'unknown'}); ` +\n `next attempt in ${delayS.toFixed(2)} s (${Math.round(remainingS)} s of the horizon left)`,\n );\n await this._retryWait(delayS * 1000, cancelled);\n }\n }\n\n /** True when the answer of the last attempt of `call` can change on a retry. */\n private _retryable(call: Call): boolean {\n if (call.misroute !== null || call.noRetry) return false;\n if (call.status !== null) return RETRY_STATUSES.has(call.status);\n // `fetch` refuses a URL with credentials before it sends anything: a retry cannot help.\n if (this._endpointHasCredentials) return false;\n // No answer: a connection error or a timeout. A failure that names neither is not known\n // to be transient, so it is sent once.\n return call.error !== null;\n }\n\n /**\n * Wait `ms` before the next attempt. `abort()` and `endRetries()` end the wait at once. The\n * timer does not keep the process alive: when nothing else runs, `beforeExit` starts the\n * SDK's `shutdown()`, which ends the wait.\n */\n private _retryWait(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted || this._noWait || ms <= 0) return resolve();\n const done = (): void => {\n clearTimeout(timer);\n signal.removeEventListener('abort', done);\n this._waits.delete(done);\n resolve();\n };\n const timer = setTimeout(done, Math.min(ms, MAX_TIMER_MS));\n timer.unref?.();\n signal.addEventListener('abort', done, { once: true });\n this._waits.add(done);\n });\n }\n\n /** Turn the outcome of the parts of one batch into the result of `export()`. */\n private _finish(spans: Span[], out: Outcome, attempts: number): ExportResult {\n const reasons = new Set(out.failed.map((f) => f.reason));\n if (out.delivered.length === 0 && Object.keys(out.dropped).length === 0 && reasons.size === 1) {\n // No span was accounted for, and one reason applies to all of them.\n const reason = out.failed[0].reason;\n const nFailed = out.failed.reduce((sum, f) => sum + f.n, 0);\n this._dropReasons.set(spans, reason);\n return this._fail(reason, out.failed[out.failed.length - 1].answer, nFailed, attempts);\n }\n\n // SUCCESS: at least one part was delivered or accounted for.\n let ack: AckCounts | null;\n if (out.delivered.length === 1 && Object.keys(out.dropped).length === 0 && out.failed.length === 0) {\n ack = out.delivered[0].ack;\n } else {\n let accepted = 0;\n let rejected = 0;\n let quotaDropped = 0;\n for (const part of out.delivered) {\n // A transport with no ack delivered the whole part.\n accepted += part.ack !== null ? part.ack.accepted : part.n;\n rejected += part.ack !== null ? part.ack.rejected : 0;\n quotaDropped += part.ack?.quotaDropped ?? 0;\n }\n const dropped: Partial<Record<ExporterDropReason, number>> = { ...out.dropped };\n for (const f of out.failed) dropped[f.reason] = (dropped[f.reason] ?? 0) + f.n;\n ack = { accepted, rejected };\n if (quotaDropped > 0) ack.quotaDropped = quotaDropped;\n if (Object.keys(dropped).length > 0) ack.dropped = dropped;\n }\n if (ack !== null) this._acks.set(spans, ack);\n this._consecutiveFailures = 0;\n this._failureKind = null;\n const tooLarge = out.dropped.too_large ?? 0;\n if (tooLarge > 0) this._warnTooLarge(tooLarge);\n for (const f of out.failed) {\n if (f.reason === 'retry_exhausted') this._warnExhausted(f.n, attempts, f.answer);\n }\n return ExportResult.SUCCESS;\n }\n\n /** End a call in which no span was accounted for. Always returns FAILURE. */\n private _fail(\n reason: 'transport_refused' | 'retry_exhausted' | 'shutdown_residue',\n answer: Answer,\n nSpans: number,\n attempts: number,\n ): ExportResult {\n if (reason === 'shutdown_residue') {\n // `endRetries()`: shutdown() runs its drain. Its residue WARNING names these spans.\n debug(`Export ended by shutdown after ${attempts} attempt(s)`);\n return ExportResult.FAILURE;\n }\n if (reason === 'retry_exhausted') {\n // The breaker counts the call, unless its last answer was a capacity refusal (see the\n // block above the class). The outage WARNING comes here when the retries ended before\n // `RETRY_WARN_AFTER_ATTEMPTS` (a short horizon, or `maxRetries`).\n if (answer.status === null || !CAPACITY_REFUSAL_STATUSES.has(answer.status)) this._stepBreaker();\n this._warnOutage(answer, true);\n this._warnExhausted(nSpans, attempts, answer);\n return ExportResult.FAILURE;\n }\n // transport_refused: one attempt, and the answer cannot change. It counts toward the\n // circuit breaker.\n this._stepBreaker();\n this._warnOutage(answer, false);\n return ExportResult.FAILURE;\n }\n\n /** Count one failed call toward the circuit breaker. */\n private _stepBreaker(): void {\n this._consecutiveFailures++;\n if (this._consecutiveFailures >= this._circuitBreakerThreshold) {\n this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;\n warn(\n `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. ` +\n `Cooldown: ${this._circuitBreakerCooldownMs / 1000}s`\n );\n }\n }\n\n /**\n * The outage WARNING: at the first failure of an outage, and when its kind changes. At most\n * one in the window for the first failure; a misroute has its own WARNING, at most one in\n * the window. `retrying` is true for a retryable answer (written after\n * `RETRY_WARN_AFTER_ATTEMPTS` failed attempts of one batch, or when its retries end before\n * that), false for an answer that a retry cannot change (one attempt). The WARNING names the last HTTP status, or the error\n * code when there was no answer. It never names the key or the response body, and names\n * the API key as a cause only for a 401 or 403. An ack of 0 and 0 has its WARNING from\n * `checkAck`.\n */\n private _warnOutage(answer: Answer, retrying: boolean): void {\n if (answer.misroute !== null) {\n if (Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {\n this._lastMisrouteWarnAt = Date.now();\n warn(\n `Risicare: spans are NOT reaching ${this._safeEndpoint}. It answered POST /v1/spans with ` +\n `${answer.misroute}. That is not the Risicare ingest gateway, so the endpoint is probably ` +\n `wrong (for example the dashboard URL instead of the ingest gateway URL). The SDK ` +\n `does not follow redirects, and this batch is counted as NOT delivered. Set ` +\n `endpoint or RISICARE_ENDPOINT to the ingest gateway URL.`,\n );\n }\n return;\n }\n if (answer.zeroAck) return;\n const status = answer.status;\n const kind =\n status !== null && AUTH_REFUSAL_STATUSES.has(status)\n ? 'auth'\n : status !== null\n ? 'http'\n : answer.error !== null\n ? 'none'\n : 'unknown';\n let write = false;\n if (this._failureKind === null || (!retrying && this._consecutiveFailures === 1)) {\n if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {\n this._lastFailureWarnAt = Date.now();\n write = true;\n }\n this._failureKind = kind;\n } else if (kind !== this._failureKind) {\n this._failureKind = kind;\n write = true;\n }\n if (!write) return;\n\n const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;\n if (retrying) {\n let limit = `${this._retryHorizonS} s from its first attempt (retryHorizonS)`;\n if (this._maxRetries !== undefined) limit = `${this._maxRetries} attempt(s) (maxRetries) or ${limit}`;\n const retryText =\n `The SDK sends each batch again with a growing wait, for up to ${limit}, and then drops ` +\n `it (reason=retry_exhausted).`;\n if (kind === 'http') {\n warn(`${where}: it answered HTTP ${status}. ${retryText} Set debug: true to see each attempt.`);\n } else {\n warn(\n `${where}: no answer (${answer.error}). The endpoint cannot be reached, or it did ` +\n `not answer in time. ${retryText} Set debug: true to see each attempt.`,\n );\n }\n return;\n }\n const tail = 'Tracing continues, but the SDK drops the spans that it cannot send.';\n if (kind === 'auth') {\n warn(\n `${where}: it answered HTTP ${status}. The endpoint refused the API key. Check the ` +\n `apiKey (or RISICARE_API_KEY) and the project it belongs to. ${tail}`,\n );\n } else if (kind === 'http') {\n warn(\n `${where}: it answered HTTP ${status}. The server did not take the batch, and a retry ` +\n `cannot change that answer. Check the endpoint and the server. ${tail} Set debug: ` +\n `true to see each attempt.`,\n );\n } else if (kind === 'none' && this._endpointHasCredentials) {\n warn(\n `${where}: no answer (${answer.error}). The endpoint URL holds credentials (a user name ` +\n `or a password before the host), and fetch does not send a request to such a URL. ` +\n `Remove the credentials from the endpoint URL. ${tail}`,\n );\n } else {\n warn(\n `${where}: the export failed. Common causes: an invalid apiKey or an unreachable ` +\n `endpoint. ${tail} Set debug: true to see each attempt.`,\n );\n }\n }\n\n /** The WARNING for spans dropped as `retry_exhausted`. At most one in the window. */\n private _warnExhausted(nSpans: number, attempts: number, answer: Answer): void {\n if (Date.now() - this._lastExhaustedWarnAt <= FAILURE_WARN_WINDOW_MS) return;\n this._lastExhaustedWarnAt = Date.now();\n const last = answer.status !== null ? `HTTP ${answer.status}` : `no answer (${answer.error})`;\n const capacity =\n answer.status !== null && CAPACITY_REFUSAL_STATUSES.has(answer.status) ? ' (over capacity)' : '';\n const limit =\n this._maxRetries !== undefined && attempts >= this._maxRetries\n ? `the maxRetries limit of ${this._maxRetries} attempt(s)`\n : `the retry horizon of ${this._retryHorizonS} s (retryHorizonS)`;\n warn(\n `Risicare: ${nSpans} span(s) DISCARDED (reason=retry_exhausted): ${this._safeEndpoint} did ` +\n `not take them in ${attempts} attempt(s), and ${limit} is used up. The last answer: ` +\n `${last}${capacity}. A gateway outage that is longer than the retry horizon loses ` +\n `spans. To wait longer, raise retryHorizonS.`,\n );\n }\n\n /** The WARNING for spans dropped as `too_large`. One time for each exporter. */\n private _warnTooLarge(nSpans: number): void {\n if (this._tooLargeWarned) return;\n this._tooLargeWarned = true;\n warn(\n `Risicare: ${nSpans} span(s) DISCARDED (reason=too_large): ${this._safeEndpoint} answered ` +\n `HTTP 413 (the request is too large) for a batch, and again for a half of it after one ` +\n `split. The SDK does not send these spans again. Make the span attributes smaller. ` +\n `This WARNING is written one time; droppedSpansByReason.too_large has the count.`,\n );\n }\n\n /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */\n private _noteMisroute(call: Call, answer: string): ExportResult {\n // The answer holds network text (a redirect target, a Content-Type): scrubbed here,\n // once, for the debug line below and for the WARNING.\n call.misroute = this._scrub(answer, 300);\n debug(`Ingest misroute: ${call.misroute}`);\n return ExportResult.FAILURE;\n }\n\n /** Record the `Retry-After` wait of a retryable answer for the retry loop. */\n private _noteRetryAfter(call: Call, status: number, retryAfterRaw: string | null): void {\n if (!RETRY_STATUSES.has(status)) return;\n call.retryAfterS = parseRetryAfterS(retryAfterRaw);\n debug(`Ingest answered HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);\n }\n\n private async _sendRequest(body: string, spansSent: number, call: Call): Promise<ExportResult> {\n const cancelled = call.cancel.signal;\n const timeoutMs = this._timeoutMs;\n const url = `${this._endpoint}/v1/spans`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'User-Agent': `risicare-js/${SDK_VERSION} node/${process.version}`,\n // F-SDKVER-001 parity. Python's ingest exporter has always sent\n // `X-Risicare-SDK-Version`; JS sent only a User-Agent, so the two SDKs\n // disagreed about how a client identifies itself. A parser-free header is\n // strictly easier for the gateway to consume than picking a version out of\n // a UA string.\n 'X-Risicare-SDK-Version': SDK_VERSION,\n };\n if (this._apiKey) {\n headers['Authorization'] = `Bearer ${this._apiKey}`;\n }\n\n let payload: string | Uint8Array = body;\n\n if (this._compress && payload.length > 1024) {\n try {\n const { gzipSync } = await import('node:zlib');\n payload = gzipSync(Buffer.from(payload));\n headers['Content-Encoding'] = 'gzip';\n } catch (e) {\n // Audit #16: log compression failures instead of silently swallowing\n debug(`Gzip compression failed, sending uncompressed: ${this._scrub(e)}`);\n }\n }\n\n // ⚠ ONE TIMER FOR THE WHOLE REQUEST, BODY READ INCLUDED (A4). Through 0.7.1 the timer\n // was cleared as soon as `fetch` resolved, which is when the HEADERS arrive. A server\n // that sent 200 headers and then stalled the body held `checkAck` for 301 s (the\n // runtime's own body timeout). And the `catch` path never cleared the timer, so each\n // refused attempt kept the process alive for the full timeout. The timer now covers\n // the body read and is cleared in `finally` on every path.\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n // `abort()` on the exporter stops this request too.\n const onCancel = () => controller.abort();\n cancelled.addEventListener('abort', onCancel, { once: true });\n if (cancelled.aborted) controller.abort();\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: payload,\n signal: controller.signal,\n // Never follow: a redirect is a misroute (see MISROUTE_WARN_WINDOW_MS). Node returns\n // the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.\n redirect: 'manual',\n });\n call.status = response.status;\n\n const redirected = response.type === 'opaqueredirect';\n if (redirected || (response.status >= 300 && response.status < 400)) {\n const location = response.headers?.get?.('Location');\n // The target comes from the server, and it can contain the API key.\n const target = location ? this._scrub(location, 1000) : 'no Location header';\n return this._noteMisroute(call, `HTTP ${response.status || '3xx'}, a redirect to ${target}`);\n }\n if (response.status >= 200 && response.status < 300) {\n const ack = await checkAck(response, spansSent, (t) => this._scrub(t, 1000));\n if (ack === null) {\n // The timer ended the body read: a timeout, not a misroute.\n if (controller.signal.aborted) {\n call.status = null;\n call.error = `timeout after ${timeoutMs} ms`;\n debug(`HTTP export timeout: the ack body did not arrive within ${timeoutMs} ms`);\n return ExportResult.TIMEOUT;\n }\n return this._noteMisroute(\n call,\n `HTTP ${response.status} and a body that is not a Risicare ack ` +\n `(content-type: ${response.headers?.get?.('Content-Type') || 'none'})`,\n );\n }\n if (ack.quota !== undefined) {\n this._quota.enter(ack.quota, `The ingest endpoint ${this._safeEndpoint}`, spansSent);\n } else if (ack.result === ExportResult.SUCCESS) {\n // A well-formed ack that accounts for spans and is not a quota discard: it counts\n // toward the end of a quota episode. (An ack of 0 and 0 is a FAILURE and does not.)\n this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);\n }\n if (ack.result === ExportResult.SUCCESS) call.ack = ack.counts;\n if (ack.final) call.noRetry = true;\n return ack.result;\n }\n this._noteRetryAfter(call, response.status, response.headers?.get?.('Retry-After') ?? null);\n if (response.status === 408 || response.status === 504) {\n debug(`HTTP export timeout: ${response.status}`);\n return ExportResult.TIMEOUT;\n }\n debug(`HTTP export failed: ${response.status}`);\n return ExportResult.FAILURE;\n } catch (e) {\n // The cause code tells a refused port, a DNS failure and a reset apart (fetch\n // wraps each of them in the same TypeError). A class name only: never a message.\n const cause = e instanceof Error ? (e as Error & { cause?: { code?: unknown } }).cause : undefined;\n call.error = controller.signal.aborted\n ? `timeout after ${timeoutMs} ms`\n : typeof cause?.code === 'string'\n ? cause.code\n : e instanceof Error\n ? e.name\n : 'Error';\n debug(`HTTP export error: ${this._scrub(e)}`);\n return ExportResult.FAILURE;\n } finally {\n clearTimeout(timeoutId);\n cancelled.removeEventListener('abort', onCancel);\n }\n }\n\n shutdown(): void {\n // Native fetch needs no cleanup. `endRetries()` applies until here: an export that\n // starts after `shutdown()` follows the whole policy again.\n this._noWait = false;\n }\n}\n\n/** An integer that is not a `boolean` (JS `typeof true === 'boolean'`, but be explicit). */\nfunction asCount(v: unknown): number | undefined {\n return typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : undefined;\n}\n\n/**\n * Decide SUCCESS/FAILURE from a 2xx response, reading the ACK body. Returns `null` when the\n * body is not a well-formed Risicare ack. The caller records that as a misroute, or as a\n * timeout when the request timer stopped the body read.\n *\n * ⚠ F-SDKACKBLIND-001. A 2xx is NOT delivery. The gateway answers\n * `StatusCode::OK` unconditionally on the ingest route (`routes/spans.rs`) and\n * reports per-span outcomes in the BODY — `{ accepted, rejected, errors[] }`,\n * camelCase, `errors` omitted when empty. Every span in a batch can be rejected\n * (bad trace-id hex, attribute-cardinality cap, clamps) and the status is still\n * 200. Before 0.5.1 this returned SUCCESS on any status below 300 and never\n * opened the body, so total loss looked like a clean export — and the retry, the\n * circuit breaker and `failedExports` all stayed silent.\n *\n * ⚠ ONLY A WELL-FORMED ACK IS SUCCESS (0.7.0). The ack is a JSON object with\n * non-negative integer `accepted` and `rejected`; other fields are ignored.\n * Through 0.6.0 any other body returned SUCCESS, to fail safe against a proxy\n * that rewrites bodies. That hid TOTAL loss: the login page that the dashboard\n * host redirects to is an HTML 200. Any other 2xx body is now a misroute: a\n * FAILURE, with no retry. The cost, stated: behind a proxy that rewrites bodies,\n * stored spans are counted as lost, and the batch processor can send them again.\n * That failure is loud.\n *\n * ⚠ A REJECTION IS AN ANSWER, NOT A FAILURE (after 0.7.1). A well-formed ack with\n * `rejected` > 0 is SUCCESS for the transport, also when `accepted` is 0: span-level\n * rejects are permanent, so a retry sends the same spans to the same refusal. Through\n * 0.7.1 an ack with `accepted` 0 was a FAILURE: the batch went to the server up to 12\n * times, the circuit breaker moved, and the last WARNING blamed the API key. A PARTIAL\n * rejection was already not a failure: retrying the whole batch would duplicate the\n * accepted spans. The result carries the counts, so that the batch processor adds\n * `accepted` to `exportedSpans` and `rejected` to `rejectedSpans`, and `flush()` then\n * returns `false`. One WARNING gives the counts and the reasons.\n *\n * ⚠ A MONTHLY-QUOTA DISCARD IS NOT A REJECTION (S-1, 0.9.1). An answer with\n * `reason === 'monthly_quota_exceeded'` (or the header `X-Risicare-Quota: exceeded`) is checked\n * first. It is SUCCESS with the ack 0 and 0 and `quotaDropped` = the spans sent, and it starts\n * the pause in `quota.ts` (`retryAfterSeconds`, 300 s by default; never `resetsAt`) with one\n * WARNING an hour. The batch processor counts the spans as `quota_exceeded`. Before 0.9.1 the\n * same answer was a full rejection: one WARNING per batch, and the SDK kept sending every batch.\n *\n * ⚠ AN ACK OF 0 AND 0 FOR A NON-EMPTY BATCH IS A FAILURE (after 0.7.1). The gateway's\n * ack accounts for every span it got (accepted + rejected = spans sent). An ack\n * that counts no span is not a delivery. Through 0.7.1 it was SUCCESS, and the\n * whole batch was counted as exported. It is not retried inside the same\n * `export()` call, because the answer cannot change. The batch processor treats it\n * as any other failure.\n *\n * Other ack counts are not trusted here either: the batch processor clamps them to\n * the batch size (see `BatchSpanProcessor`).\n *\n * A WARNING names the reasons only: the distinct `errors[].error` strings (or\n * `errorMessage` when there are none), at most 3. Each one is made one printable\n * line (control characters become spaces) and then cut at 200 characters, so a\n * server cannot write a false log line. A WARNING never names a span index or span\n * content.\n *\n * Python twin: `exporters/http.py::_check_ack`. Same rule, same thresholds.\n */\ninterface AckOutcome {\n result: ExportResult;\n counts: AckCounts;\n /** True when a retry inside the same `export()` call cannot change the answer. */\n final: boolean;\n /** S-1: set when the answer is a monthly-quota discard (`quota.ts`). Not an error. */\n quota?: QuotaDiscard;\n}\n\nconst MAX_ACK_REASONS = 3;\nconst MAX_ACK_REASON_CHARS = 200;\n\n/** Make a reason from the server one printable line: control and line-break characters become spaces. */\nfunction oneLine(text: string): string {\n // eslint-disable-next-line no-control-regex\n return text.replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g, ' ');\n}\n\n/** The distinct reasons of an ack, for a WARNING. Never a span index, never span content. */\nfunction ackReasons(body: Record<string, unknown>): string {\n const reasons: string[] = [];\n const errors = body.errors;\n if (Array.isArray(errors)) {\n for (const entry of errors) {\n const text = (entry as { error?: unknown } | null)?.error;\n if (typeof text !== 'string' || text.length === 0) continue;\n const cut = oneLine(text).slice(0, MAX_ACK_REASON_CHARS);\n if (!reasons.includes(cut)) reasons.push(cut);\n if (reasons.length === MAX_ACK_REASONS) break;\n }\n }\n if (reasons.length === 0) {\n const message =\n (typeof body.errorMessage === 'string' && body.errorMessage) ||\n (typeof body.error_message === 'string' && body.error_message) ||\n '';\n if (message) reasons.push(oneLine(message).slice(0, MAX_ACK_REASON_CHARS));\n }\n return reasons.length === 0 ? 'No reason was returned.' : `Reasons: ${reasons.join('; ')}`;\n}\n\nasync function checkAck(\n response: Response,\n spansSent: number,\n scrub: (text: string) => string,\n): Promise<AckOutcome | null> {\n let payload: unknown;\n try {\n payload = await response.json();\n } catch {\n payload = undefined; // not JSON (or the body read was aborted)\n }\n\n // S-1: a monthly-quota discard (`reason`, or the `X-Risicare-Quota` header alone). It is\n // checked BEFORE the ack shape, because the `/v1/traces` shape has no `accepted` field and a\n // header-only answer may have a body that we do not know. It is not an error, not a misroute\n // and not a rejection: no retry, no breaker step, no per-batch WARNING. The ack is 0 and 0\n // with `quotaDropped`, so that the batch processor counts the spans as `quota_exceeded`.\n const discard = parseJsonDiscard(payload, response.headers);\n if (discard !== null) {\n return {\n result: ExportResult.SUCCESS,\n counts: { accepted: 0, rejected: 0, quotaDropped: spansSent },\n final: false,\n quota: discard,\n };\n }\n\n if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {\n return null; // not a Risicare ack\n }\n\n const body = payload as Record<string, unknown>;\n const accepted = asCount(body.accepted);\n const rejected = asCount(body.rejected);\n if (accepted === undefined || rejected === undefined) return null;\n const counts: AckCounts = { accepted, rejected };\n\n if (accepted === 0 && rejected === 0 && spansSent > 0) {\n warn(\n `Risicare: the backend acknowledged 0 of ${spansSent} span(s): its ack counts no ` +\n `span as accepted or rejected. This batch is counted as NOT delivered.`,\n );\n return { result: ExportResult.FAILURE, counts, final: true };\n }\n if (rejected === 0) return { result: ExportResult.SUCCESS, counts, final: false };\n\n const total = accepted + rejected;\n if (accepted === 0) {\n warn(\n `Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} — ` +\n `this batch was NOT stored. Rejected spans are permanently lost and are NOT ` +\n `retried. ${scrub(ackReasons(body))}`,\n );\n return { result: ExportResult.SUCCESS, counts, final: false };\n }\n\n warn(\n `Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ` +\n `${accepted} were stored. Those ${rejected} are permanently lost and are NOT ` +\n `retried. ${scrub(ackReasons(body))}`,\n );\n return { result: ExportResult.SUCCESS, counts, final: false };\n}\n","/**\n * Fix Applier — Applies fixes to agent operations.\n *\n * Handles different fix types:\n * - PromptFix: Modify system/user prompts (prepend, append, replace, few_shot)\n * - ParameterFix: Adjust LLM parameters (temperature, model, etc.)\n * - RetryFix: Retry with exponential backoff + jitter\n * - FallbackFix: Switch to fallback model or default response\n * - GuardFix: Input/output validation (content filter, format check, length)\n *\n * Port of Python SDK's runtime/applier.py adapted for Node.js.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { ActiveFix, FixRuntimeConfig } from './config.js';\nimport { shouldApply, resolveFixRuntimeConfig } from './config.js';\nimport type { FixCache } from './cache.js';\nimport { debug, warn } from '../utils/log.js';\n\n/**\n * Maximum length for fix content injected into prompts.\n * Prevents unbounded prompt injection from malicious/corrupted fix configs.\n */\nconst MAX_FIX_CONTENT_LENGTH = 10_000;\n\n// ─── Apply Result ───────────────────────────────────────────────────────────\n\nexport interface ApplyResult {\n applied: boolean;\n fixId?: string;\n deploymentId?: string;\n fixType?: string;\n modifications: Record<string, unknown>;\n error?: string;\n /**\n * Guard-only: human-readable reason a guard failed (passed=false). Used\n * by GuardRejectedError to surface an actionable message to the customer.\n * `error` carries the raw exception text; `reason` carries the audit\n * category ('guard_exception', 'content_filter', 'format_check', etc.).\n */\n reason?: string;\n}\n\nfunction emptyResult(fix: ActiveFix, fixType: string): ApplyResult {\n return {\n applied: false,\n fixId: fix.fixId,\n deploymentId: fix.deploymentId,\n fixType,\n modifications: {},\n };\n}\n\n/**\n * Escapes of a backslash and an ASCII letter that Python `re` and JavaScript\n * `RegExp` (without the `u` flag) read the same way. From the two grammars:\n * - Outside a class: `\\b \\B \\d \\D \\s \\S \\w \\W` (classes and word\n * boundaries) and `\\f \\n \\r \\t \\v` (control characters).\n * - Inside a class: the same, but not `\\B` (Python refuses it; JS reads B).\n * `[\\b]` is a backspace in both.\n * - `\\xHH` and `\\uHHHH` only with exactly 2 or 4 hex digits (Python refuses\n * a short one; JS reads it as the letter x or u).\n * - `\\A` and `\\Z` outside a class are translated (see below).\n * Every other letter fails closed. JS reads it as the letter itself; Python\n * refuses it (`\\e`, `\\q`, `\\z` before 3.14, `\\k`, `\\c`, `[\\A]`, `[\\Z]`) or\n * reads it differently (`\\a`, `\\N{...}`, `\\U........`, `\\z` from 3.14).\n */\nconst SAME_ESCAPES = 'bBdDsSwWfnrtv';\nconst SAME_ESCAPES_IN_CLASS = 'bdDsSwWfnrtv';\n\nconst LEADING_INLINE_FLAGS = /^\\(\\?([ims]+)\\)/;\nconst PY_NAMED_GROUP = /^\\(\\?P<([A-Za-z_][A-Za-z0-9_]*)>/;\nconst PY_NAMED_BACKREF = /^\\(\\?P=([A-Za-z_][A-Za-z0-9_]*)\\)/;\nconst JS_NAMED_GROUP = /^\\(\\?<([A-Za-z_][A-Za-z0-9_]*)>/;\n\n/**\n * Translate a Python `re` pattern to a JavaScript RegExp source and flags.\n *\n * - A leading inline-flag group `(?i)`, `(?s)`, `(?m)` or a combination such\n * as `(?is)` becomes RegExp flags. The `i` flag is always set.\n * - `\\A` becomes `(?<![\\s\\S])` and `\\Z` becomes `(?![\\s\\S])` (start and end\n * of the input, as in Python). Without the `u` flag, JavaScript reads `\\A`\n * and `\\Z` as the letters A and Z.\n * - `(?P<name>` becomes `(?<name>`, and `(?P=name)` becomes `\\k<name>`.\n *\n * It THROWS (the caller fails closed) on a backslash and a letter outside the\n * set above, and on a group name that occurs two times (Python refuses it).\n * Other escaped characters and the rest of a character class are copied\n * unchanged. Any other Python-only form stays as it is; if it does not\n * compile, the caller fails closed.\n * @internal\n */\nexport function translatePythonPattern(pattern: string): { source: string; flags: string } {\n let flags = 'i';\n let rest = pattern;\n const m = LEADING_INLINE_FLAGS.exec(rest);\n if (m) {\n for (const f of m[1]) if (!flags.includes(f)) flags += f;\n rest = rest.slice(m[0].length);\n }\n\n const names = new Set<string>();\n const addName = (name: string): void => {\n if (names.has(name)) throw new Error('a group name occurs two times');\n names.add(name);\n };\n\n let source = '';\n let inClass = false;\n for (let i = 0; i < rest.length; i++) {\n const c = rest[i];\n if (c === '\\\\' && i + 1 < rest.length) {\n const next = rest[i + 1];\n if (/[A-Za-z]/.test(next)) {\n if (!inClass && next === 'A') {\n source += '(?<![\\\\s\\\\S])';\n i++;\n continue;\n }\n if (!inClass && next === 'Z') {\n source += '(?![\\\\s\\\\S])';\n i++;\n continue;\n }\n if (next === 'x' || next === 'u') {\n const n = next === 'x' ? 2 : 4;\n const hex = rest.slice(i + 2, i + 2 + n);\n if (!new RegExp(`^[0-9A-Fa-f]{${n}}$`).test(hex)) throw new Error('short hex escape');\n source += c + next + hex;\n i += 1 + n;\n continue;\n }\n if (!(inClass ? SAME_ESCAPES_IN_CLASS : SAME_ESCAPES).includes(next)) {\n throw new Error('an escape that Python and JavaScript read differently');\n }\n }\n source += c + next;\n i++;\n continue;\n }\n if (inClass) {\n if (c === ']') inClass = false;\n source += c;\n continue;\n }\n if (c === '[') {\n inClass = true;\n source += c;\n continue;\n }\n const tail = rest.slice(i);\n let g: RegExpExecArray | null;\n if ((g = PY_NAMED_GROUP.exec(tail)) || (g = JS_NAMED_GROUP.exec(tail))) {\n addName(g[1]);\n source += `(?<${g[1]}>`;\n i += g[0].length - 1;\n continue;\n }\n if ((g = PY_NAMED_BACKREF.exec(tail))) {\n source += `\\\\k<${g[1]}>`;\n i += g[0].length - 1;\n continue;\n }\n source += c;\n }\n return { source, flags };\n}\n\n/** (fix id, pattern index) pairs whose \"not usable\" WARNING was written. */\nconst warnedGuardPatterns = new Set<string>();\n\n/** One WARNING per (fix id, pattern index) per process. Index -1: not a list. */\nfunction warnUnusablePattern(fixId: string | undefined, index: number): void {\n const key = `${fixId ?? 'unknown'}\\u0000${index}`;\n if (warnedGuardPatterns.has(key)) return;\n warnedGuardPatterns.add(key);\n warn(\n index < 0\n ? `Guard fix ${fixId ?? 'unknown'}: blocked_patterns is not a list. The guard rejects every call.`\n : `Guard fix ${fixId ?? 'unknown'}: blocked pattern ${index} is not usable (empty, not a ` +\n 'string, longer than 500 characters, or it does not compile). The guard rejects every call.',\n );\n}\n\n// ─── Fix Applier ────────────────────────────────────────────────────────────\n\nexport class FixApplier {\n private readonly _config: Required<FixRuntimeConfig>;\n private readonly _cache: FixCache;\n private _applicationLog: ApplyResult[] = [];\n\n constructor(config: FixRuntimeConfig, cache: FixCache) {\n this._config = resolveFixRuntimeConfig(config);\n this._cache = cache;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Fix Lookup\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Get applicable fix for an error code.\n *\n * Considers A/B testing bucket if sessionId is provided. Uses\n * crypto.createHash('md5') for deterministic bucketing across restarts.\n */\n getFixForError(\n errorCode: string,\n sessionId?: string,\n ): ActiveFix | null {\n try {\n const fix = this._cache.get(errorCode);\n if (!fix) return null;\n\n // Check A/B test bucketing\n if (sessionId && this._config.abTestingEnabled) {\n const hashHex = createHash('md5')\n .update(sessionId)\n .digest('hex')\n .substring(0, 8);\n const sessionHash = parseInt(hashHex, 16);\n\n if (!shouldApply(fix, sessionHash)) {\n debug(`Fix ${fix.fixId} not applied (A/B control group)`);\n return null;\n }\n }\n\n return fix;\n } catch (e) {\n debug(`getFixForError error: ${e}`);\n return null;\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 1. Prompt Fix\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a prompt fix to messages.\n *\n * Supports 4 modification types:\n * - prepend: Add content before first system message\n * - append: Add content after first system message\n * - replace: Regex replace across all messages\n * - few_shot: Insert user/assistant example pairs after system message\n */\n applyPromptFix(\n fix: ActiveFix,\n messages: Record<string, unknown>[],\n ): { messages: Record<string, unknown>[]; result: ApplyResult } {\n try {\n const cfg = fix.config;\n const modificationType = (cfg.modification_type ?? cfg.modificationType ?? 'append') as string;\n const target = (cfg.target ?? 'system') as string;\n let content = (cfg.content ?? '') as string;\n\n // Truncate oversized content to prevent prompt injection\n if (content.length > MAX_FIX_CONTENT_LENGTH) {\n warn(\n `Fix ${fix.fixId} content truncated from ${content.length} to ${MAX_FIX_CONTENT_LENGTH} chars`,\n );\n content = content.slice(0, MAX_FIX_CONTENT_LENGTH);\n }\n\n const result = emptyResult(fix, 'prompt');\n\n if (this._config.dryRun) {\n result.modifications = {\n type: modificationType,\n target,\n contentPreview: content.slice(0, 100),\n };\n return { messages, result };\n }\n\n let modified = messages.map((m) => ({ ...m }));\n\n if (modificationType === 'prepend') {\n modified = this._prependToTarget(modified, target, content);\n result.applied = true;\n result.modifications = { type: 'prepend', target };\n } else if (modificationType === 'append') {\n modified = this._appendToTarget(modified, target, content);\n result.applied = true;\n result.modifications = { type: 'append', target };\n } else if (modificationType === 'replace') {\n const pattern = (cfg.pattern ?? '') as string;\n if (pattern) {\n modified = this._replaceInMessages(modified, pattern, content);\n result.applied = true;\n result.modifications = { type: 'replace', pattern };\n }\n } else if (modificationType === 'few_shot') {\n const examples = (cfg.examples ?? []) as Array<Record<string, string>>;\n if (examples.length > 0) {\n modified = this._addFewShotExamples(modified, examples);\n result.applied = true;\n result.modifications = { type: 'few_shot', count: examples.length };\n }\n }\n\n return { messages: modified, result };\n } catch (e) {\n debug(`applyPromptFix error: ${e}`);\n return {\n messages,\n result: {\n applied: false,\n fixId: fix.fixId,\n fixType: 'prompt',\n modifications: {},\n error: String(e),\n },\n };\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 2. Parameter Fix\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a parameter fix — merge config.parameters into params.\n */\n applyParameterFix(\n fix: ActiveFix,\n params: Record<string, unknown>,\n ): { params: Record<string, unknown>; result: ApplyResult } {\n try {\n const newParams = (fix.config.parameters ?? {}) as Record<string, unknown>;\n const result = emptyResult(fix, 'parameter');\n\n if (this._config.dryRun) {\n result.modifications = { parameters: newParams };\n return { params, result };\n }\n\n const modified = { ...params, ...newParams };\n result.applied = true;\n result.modifications = { parameters: newParams };\n\n return { params: modified, result };\n } catch (e) {\n debug(`applyParameterFix error: ${e}`);\n return {\n params,\n result: {\n applied: false,\n fixId: fix.fixId,\n fixType: 'parameter',\n modifications: {},\n error: String(e),\n },\n };\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 3. Retry Fix (async — uses setTimeout for sleeping)\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a retry fix to an async operation.\n *\n * Retries with exponential backoff + jitter using\n * `await new Promise(r => setTimeout(r, delay))`.\n */\n async applyRetryFix<T>(\n fix: ActiveFix,\n operation: () => Promise<T>,\n ): Promise<{ value: T; result: ApplyResult }> {\n const cfg = fix.config;\n const maxRetries = (cfg.max_retries ?? cfg.maxRetries ?? 3) as number;\n const initialDelayMs = (cfg.initial_delay_ms ?? cfg.initialDelayMs ?? 1000) as number;\n const maxDelayMs = (cfg.max_delay_ms ?? cfg.maxDelayMs ?? 30_000) as number;\n const exponentialBase = (cfg.exponential_base ?? cfg.exponentialBase ?? 2.0) as number;\n const jitter = (cfg.jitter ?? true) as boolean;\n const retryOn = (cfg.retry_on ?? cfg.retryOn ?? []) as string[];\n\n const result = emptyResult(fix, 'retry');\n\n if (this._config.dryRun) {\n result.modifications = { maxRetries, initialDelayMs };\n const value = await operation();\n return { value, result };\n }\n\n let lastError: Error | null = null;\n let attempts = 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n attempts++;\n try {\n const value = await operation();\n result.applied = true;\n result.modifications = { attempts };\n return { value, result };\n } catch (e) {\n lastError = e instanceof Error ? e : new Error(String(e));\n const errorType = lastError.constructor.name;\n\n // Check if we should retry this specific error type\n if (retryOn.length > 0 && !retryOn.includes(errorType)) {\n throw lastError;\n }\n\n if (attempt < maxRetries) {\n // Calculate delay with exponential backoff\n let delayMs = Math.min(\n initialDelayMs * Math.pow(exponentialBase, attempt),\n maxDelayMs,\n );\n\n // Add jitter: multiply by random factor [0.5, 1.5)\n if (jitter) {\n delayMs *= 0.5 + Math.random();\n }\n\n debug(\n `Retry ${attempt + 1}/${maxRetries} after ${Math.round(delayMs)}ms`,\n );\n await new Promise<void>((r) => setTimeout(r, delayMs));\n }\n }\n }\n\n // All retries exhausted\n result.applied = true;\n result.error = lastError?.message;\n result.modifications = { attempts, exhausted: true };\n throw lastError;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 4. Fallback Fix\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a fallback fix.\n *\n * - 'model': Replace params.model with the fallback model\n * - 'default': Set params._fallbackResponse for the caller to use\n */\n applyFallbackFix(\n fix: ActiveFix,\n params: Record<string, unknown>,\n ): { params: Record<string, unknown>; result: ApplyResult } {\n try {\n const cfg = fix.config;\n const fallbackType = (cfg.fallback_type ?? cfg.fallbackType ?? 'model') as string;\n const fallbackConfig = (cfg.fallback_config ?? cfg.fallbackConfig ?? {}) as Record<string, unknown>;\n const result = emptyResult(fix, 'fallback');\n\n if (this._config.dryRun) {\n result.modifications = { fallbackType, fallbackConfig };\n return { params, result };\n }\n\n const modified = { ...params };\n\n if (fallbackType === 'model') {\n const fallbackModel = fallbackConfig.model as string | undefined;\n if (fallbackModel) {\n modified.model = fallbackModel;\n result.applied = true;\n result.modifications = { model: fallbackModel };\n }\n } else if (fallbackType === 'default') {\n const defaultResponse = fallbackConfig.response;\n if (defaultResponse !== undefined) {\n modified._fallbackResponse = defaultResponse;\n result.applied = true;\n result.modifications = { defaultResponse: true };\n }\n }\n\n return { params: modified, result };\n } catch (e) {\n debug(`applyFallbackFix error: ${e}`);\n return {\n params,\n result: {\n applied: false,\n fixId: fix.fixId,\n fixType: 'fallback',\n modifications: {},\n error: String(e),\n },\n };\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // 5. Guard Fix\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Apply a guard fix (validation).\n *\n * Guard types:\n * - content_filter: Regex-based blocked patterns\n * - format_check: JSON.parse() validity\n * - input_validation / output_validation: min/max length\n *\n * `content_filter` searches the content for each entry of `blocked_patterns`\n * (case-insensitive, after `translatePythonPattern`). It fails CLOSED: when\n * `blocked_patterns` is not a list, or an entry is empty, is not a string,\n * is longer than 500 characters or cannot be used, the guard does not pass.\n * One WARNING names the fix id and the pattern index, once for each pair in\n * the process. The reason names the pattern index, never the pattern or the\n * content.\n *\n * Limits:\n * - The interceptor runs only on the OpenAI chat patch (input guards) and on\n * `interceptCall` / `interceptResponse`. It does not run when a framework\n * integration suppresses provider instrumentation.\n * - Each SDK uses its own regular-expression engine. These constructs can\n * give a different result in JavaScript and Python: `$` before a final\n * newline, Unicode case folding, `\\d` and `\\w` on non-ASCII text,\n * `\\N{...}` and `\\U........` (JavaScript fails closed), and a `]` first\n * in a class.\n * - A pattern has no time bound. A pattern with nested repeats can take a\n * very long time on a long input.\n */\n applyGuardFix(\n fix: ActiveFix,\n content: string,\n isInput = true,\n ): { content: string; passed: boolean; result: ApplyResult } {\n try {\n const cfg = fix.config;\n const guardType = (cfg.guard_type ?? cfg.guardType ?? 'output_validation') as string;\n const guardConfig = (cfg.guard_config ?? cfg.guardConfig ?? {}) as Record<string, unknown>;\n const result = emptyResult(fix, 'guard');\n\n // Check if guard applies to this direction\n if (isInput && guardType !== 'input_validation' && guardType !== 'content_filter') {\n return { content, passed: true, result };\n }\n if (!isInput && guardType !== 'output_validation' && guardType !== 'format_check') {\n return { content, passed: true, result };\n }\n\n if (this._config.dryRun) {\n result.modifications = { guardType };\n return { content, passed: true, result };\n }\n\n let passed = true;\n let reason: string | undefined;\n\n if (guardType === 'content_filter') {\n // A key that is present with null is \"not a list\" (as in Python); only\n // a missing key means \"no patterns\".\n const blockedPatterns: unknown = 'blocked_patterns' in guardConfig\n ? guardConfig.blocked_patterns\n : 'blockedPatterns' in guardConfig ? guardConfig.blockedPatterns : [];\n // F-029: a pattern that is not usable makes the guard FAIL CLOSED.\n // Through 0.7.1 it was skipped with a debug line and the guard passed.\n // The reason names the index only: a literal pattern IS the blocked text.\n if (!Array.isArray(blockedPatterns)) {\n warnUnusablePattern(fix.fixId, -1);\n passed = false;\n reason = 'blocked_patterns is not a list';\n } else {\n for (let index = 0; index < blockedPatterns.length; index++) {\n const regex = this._safeCompileRegex(blockedPatterns[index] as string);\n if (!regex) {\n warnUnusablePattern(fix.fixId, index);\n passed = false;\n reason = `blocked pattern ${index} is not usable`;\n break;\n }\n if (regex.test(content)) {\n passed = false;\n reason = `blocked pattern matched (pattern ${index})`;\n break;\n }\n }\n }\n } else if (guardType === 'format_check') {\n const requiredFormat = guardConfig.format as string | undefined;\n if (requiredFormat === 'json') {\n try {\n JSON.parse(content);\n } catch {\n passed = false;\n reason = 'format_check: invalid JSON';\n }\n }\n } else if (guardType === 'input_validation' || guardType === 'output_validation') {\n const minLength = (guardConfig.min_length ?? guardConfig.minLength ?? 0) as number;\n const maxLength = (guardConfig.max_length ?? guardConfig.maxLength ?? Infinity) as number;\n if (content.length < minLength || content.length > maxLength) {\n passed = false;\n reason = `${guardType}: length ${content.length} outside [${minLength}, ${maxLength}]`;\n }\n }\n\n result.applied = true;\n result.modifications = { passed, guardType };\n if (reason !== undefined) result.reason = reason;\n\n return { content, passed, result };\n } catch (e) {\n // F-731: Fail-CLOSED on guard error. An unexpected exception in a\n // safety-validation path MUST NOT silently pass content through —\n // that would defeat the entire purpose of input/output validation.\n // PR-4+5 review B2 (2026-05-25): the interceptor LAYER now reads\n // `passed:false` and throws GuardRejectedError to short-circuit the\n // LLM call. Before B2 this `passed:false` was advisory only — the\n // provider patcher consumed `modifications` / `messages` but never\n // read `passed`, so a thrown-getter attack still hit the LLM with\n // the attacker payload. The applier's job is to TELL the truth;\n // the interceptor's job is to ACT on it.\n warn(`applyGuardFix error (failing CLOSED): ${e}`);\n return {\n content,\n passed: false,\n result: {\n applied: true,\n fixId: fix.fixId,\n fixType: 'guard',\n modifications: { passed: false, reason: 'guard_exception' },\n error: String(e),\n reason: 'guard_exception',\n },\n };\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Application Log\n // ═══════════════════════════════════════════════════════════════════════════\n\n /** Log a fix application result. */\n logApplication(result: ApplyResult): void {\n this._applicationLog.push(result);\n\n // Limit log size\n if (this._applicationLog.length > 1000) {\n this._applicationLog = this._applicationLog.slice(-500);\n }\n }\n\n /** Get the application log. */\n getApplicationLog(): ApplyResult[] {\n return [...this._applicationLog];\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Private Helpers\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Safely compile a regex pattern from untrusted input.\n * Returns null if invalid or too long.\n *\n * F-029: the fix patterns are written for Python `re`. Before it compiles\n * the pattern, this function translates the Python forms that have an exact\n * JavaScript equivalent (see `translatePythonPattern`). The `i` flag is\n * always on, as in the Python applier.\n */\n private _safeCompileRegex(\n pattern: string,\n maxLength = 500,\n ): RegExp | null {\n if (typeof pattern !== 'string' || !pattern || pattern.length > maxLength) return null;\n try {\n const { source, flags } = translatePythonPattern(pattern);\n return new RegExp(source, flags);\n } catch {\n debug(`Invalid regex pattern (length=${pattern.length})`);\n return null;\n }\n }\n\n /** Prepend content to the first message matching the target role. */\n private _prependToTarget(\n messages: Record<string, unknown>[],\n target: string,\n content: string,\n ): Record<string, unknown>[] {\n return messages.map((msg) => {\n if (msg.role === target) {\n return {\n ...msg,\n content: content + '\\n\\n' + ((msg.content as string) ?? ''),\n };\n }\n return msg;\n });\n }\n\n /** Append content to the first message matching the target role. */\n private _appendToTarget(\n messages: Record<string, unknown>[],\n target: string,\n content: string,\n ): Record<string, unknown>[] {\n return messages.map((msg) => {\n if (msg.role === target) {\n return {\n ...msg,\n content: ((msg.content as string) ?? '') + '\\n\\n' + content,\n };\n }\n return msg;\n });\n }\n\n /** Regex replace across all messages. */\n private _replaceInMessages(\n messages: Record<string, unknown>[],\n pattern: string,\n replacement: string,\n ): Record<string, unknown>[] {\n const regex = this._safeCompileRegex(pattern);\n if (!regex) {\n debug('Skipping invalid regex pattern in prompt fix');\n return messages;\n }\n\n return messages.map((msg) => {\n const msgContent = msg.content;\n if (typeof msgContent === 'string') {\n return { ...msg, content: msgContent.replace(regex, replacement) };\n }\n return msg;\n });\n }\n\n /** Add few-shot examples after the first system message. */\n private _addFewShotExamples(\n messages: Record<string, unknown>[],\n examples: Array<Record<string, string>>,\n ): Record<string, unknown>[] {\n const result: Record<string, unknown>[] = [];\n let systemFound = false;\n\n for (const msg of messages) {\n result.push(msg);\n\n if (msg.role === 'system' && !systemFound) {\n systemFound = true;\n for (const example of examples) {\n if (example.user) {\n result.push({ role: 'user', content: example.user });\n }\n if (example.assistant) {\n result.push({ role: 'assistant', content: example.assistant });\n }\n }\n }\n }\n\n return result;\n }\n}\n","/**\n * Fix Loader — Fetches active fixes from the Risicare API.\n *\n * Handles:\n * - Initial loading of fixes on startup\n * - Periodic background refresh via setInterval (unref'd)\n * - Exponential backoff on failure\n * - Circuit breaker: after 3 consecutive failures, stop trying for 30s\n *\n * Uses native fetch (Node.js 18+) with AbortController for timeouts.\n *\n * Port of Python SDK's runtime/loader.py adapted for Node.js.\n */\n\nimport type { ActiveFix } from './config.js';\nimport { activeFixFromApiResponse } from './config.js';\nimport type { FixRuntimeConfig } from './config.js';\nimport { resolveFixRuntimeConfig } from './config.js';\nimport type { FixCache } from './cache.js';\nimport { debug, warn } from '../utils/log.js';\nimport { safeUrl, scrubText } from '../utils/scrub.js';\nimport { SDK_VERSION } from '../version.js';\n\nexport class FixLoader {\n private readonly _config: Required<FixRuntimeConfig>;\n private readonly _cache: FixCache;\n\n private _refreshTimer: ReturnType<typeof setInterval> | null = null;\n private _lastLoadTime: number | null = null;\n private _consecutiveFailures = 0;\n private _circuitOpenUntil = 0;\n private _onLoadCallbacks: Array<(fixes: ActiveFix[]) => void> = [];\n // The HTTP status of the last load that got a non-2xx answer; null otherwise.\n private _lastStatus: number | null = null;\n\n // Circuit breaker settings\n private static readonly CIRCUIT_BREAKER_THRESHOLD = 3;\n private static readonly CIRCUIT_BREAKER_COOLDOWN_MS = 30_000;\n\n constructor(config: FixRuntimeConfig, cache: FixCache) {\n this._config = resolveFixRuntimeConfig(config);\n this._cache = cache;\n }\n\n /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */\n private _scrub(error: unknown): string {\n let out: string;\n try {\n out = error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n } catch {\n out = typeof error;\n }\n const endpoint = (this._config.apiEndpoint ?? '').replace(/\\/+$/, '');\n if (endpoint && safeUrl(endpoint) !== endpoint) out = out.split(endpoint).join(safeUrl(endpoint));\n return scrubText(out, [this._config.apiKey]);\n }\n\n /**\n * The WARNING for a failed first load: the request URL with no userinfo, no\n * query and no key, the HTTP status or the error class, and that tracing is\n * not affected. Never the error text: it can echo the URL with its query.\n */\n private _firstLoadWarning(error: unknown): string {\n let cause: string;\n if (this._lastStatus !== null) {\n cause = `HTTP ${this._lastStatus}`;\n } else {\n cause = error instanceof Error ? error.name : typeof error;\n const code = (error as { cause?: { code?: unknown } } | null)?.cause?.code;\n if (typeof code === 'string' && /^[A-Z][A-Z0-9_]*$/.test(code)) cause += ` (${code})`;\n }\n const endpoint = (this._config.apiEndpoint ?? '').replace(/\\/+$/, '');\n return scrubText(\n `The first load of the fixes from ${safeUrl(endpoint)}/v1/fixes/active failed (${cause}). ` +\n 'No fix is applied until a later load succeeds. Tracing is not affected.',\n [this._config.apiKey],\n 500,\n );\n }\n\n /** Hide the key from `util.inspect` and `console.log` of the loader. */\n [Symbol.for('nodejs.util.inspect.custom')](): string {\n return 'FixLoader {}';\n }\n\n /** Timestamp of last successful load. */\n get lastLoadTime(): number | null {\n return this._lastLoadTime;\n }\n\n /**\n * Start the loader: perform initial load and start background refresh.\n *\n * Never throws — failures are logged and the runtime degrades gracefully.\n */\n start(): void {\n try {\n if (!this._config.enabled) {\n debug('Fix runtime disabled, skipping loader start');\n return;\n }\n\n if (!this._config.apiKey) {\n warn('No API key configured, fixes will not be loaded');\n return;\n }\n\n // Initial load (fire-and-forget — don't block startup). A failure gives\n // ONE WARNING, as the Python loader does: `initFixRuntime()` catches\n // every fault, so this is the only signal that a customer sees for a\n // 5xx, a 401 or a refused connection.\n this.loadSync().catch((e) => {\n warn(this._firstLoadWarning(e));\n });\n\n // Start background refresh\n if (this._config.autoRefresh) {\n this._startRefreshInterval();\n }\n } catch (e) {\n debug(`FixLoader.start error: ${this._scrub(e)}`);\n }\n }\n\n /** Stop the loader: clear the refresh interval. */\n stop(): void {\n try {\n if (this._refreshTimer !== null) {\n clearInterval(this._refreshTimer);\n this._refreshTimer = null;\n }\n } catch (e) {\n debug(`FixLoader.stop error: ${this._scrub(e)}`);\n }\n }\n\n /**\n * Register a callback invoked after each successful load.\n */\n onLoad(callback: (fixes: ActiveFix[]) => void): void {\n this._onLoadCallbacks.push(callback);\n }\n\n /**\n * Load fixes from the API.\n *\n * Name kept as \"loadSync\" for parity with the Python SDK, but this\n * returns a Promise in JS (there's no synchronous fetch in Node.js).\n */\n async loadSync(): Promise<ActiveFix[]> {\n if (!this._config.apiKey) {\n return [];\n }\n\n // Circuit breaker: skip if circuit is open\n const now = Date.now();\n if (\n this._consecutiveFailures >= FixLoader.CIRCUIT_BREAKER_THRESHOLD &&\n now < this._circuitOpenUntil\n ) {\n debug('Fix loader circuit breaker open — skipping load');\n return this._cache.getAll();\n }\n\n this._lastStatus = null;\n try {\n // ⚠ PATH AND HOST CHANGED 0.6.0 -> 0.7.0. This was\n // `{apiEndpoint}/api/v1/fixes/active`, and the `/api` prefix existed\n // only because a Caddy reverse proxy stripped it before forwarding to\n // FastAPI. The split has two hosts and no Caddy: the api serves\n // /v1/fixes/active directly, and the gateway host serves only /v1/spans.\n const endpoint = this._config.apiEndpoint.replace(/\\/+$/, '');\n const url = `${endpoint}/v1/fixes/active`;\n\n // AbortController for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n this._config.timeoutMs,\n );\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this._config.apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Risicare-SDK-Version': SDK_VERSION,\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n this._lastStatus = response.status;\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n const fixes = this._parseResponse(data);\n this._onLoadSuccess(fixes);\n return fixes;\n } catch (e) {\n this._onLoadFailure(e as Error);\n throw e;\n }\n }\n\n /** Get currently cached fixes without hitting the API. */\n getCached(): ActiveFix[] {\n return this._cache.getAll();\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n private _parseResponse(data: Record<string, unknown>): ActiveFix[] {\n const fixes: ActiveFix[] = [];\n const items =\n (data.fixes as unknown[]) ??\n (data.data as unknown[]) ??\n [];\n\n if (!Array.isArray(items)) return fixes;\n\n for (const item of items) {\n try {\n if (item && typeof item === 'object') {\n fixes.push(activeFixFromApiResponse(item as Record<string, unknown>));\n }\n } catch (e) {\n debug(`Failed to parse fix item: ${this._scrub(e)}`);\n }\n }\n\n return fixes;\n }\n\n private _onLoadSuccess(fixes: ActiveFix[]): void {\n this._lastLoadTime = Date.now();\n this._consecutiveFailures = 0;\n\n // Update cache\n this._cache.setAll(fixes);\n\n // Notify callbacks\n for (const callback of this._onLoadCallbacks) {\n try {\n callback(fixes);\n } catch (e) {\n debug(`Load callback error: ${this._scrub(e)}`);\n }\n }\n\n debug(`Loaded ${fixes.length} active fixes`);\n }\n\n private _onLoadFailure(error: Error): void {\n this._consecutiveFailures++;\n\n if (this._consecutiveFailures >= FixLoader.CIRCUIT_BREAKER_THRESHOLD) {\n this._circuitOpenUntil = Date.now() + FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;\n warn(\n `Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. ` +\n `Cooldown: ${FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1000}s`,\n );\n } else {\n debug(\n `Fix load failed (attempt ${this._consecutiveFailures}): ${this._scrub(error)}`,\n );\n }\n }\n\n private _startRefreshInterval(): void {\n // Use exponential backoff on the refresh interval after failures\n const tick = (): void => {\n this.loadSync().catch((e) => {\n debug(`Background fix refresh failed: ${this._scrub(e)}`);\n });\n };\n\n this._refreshTimer = setInterval(\n () => {\n // Skip if circuit breaker is open (loadSync handles this,\n // but we also avoid the async overhead)\n if (\n this._consecutiveFailures >= FixLoader.CIRCUIT_BREAKER_THRESHOLD &&\n Date.now() < this._circuitOpenUntil\n ) {\n return;\n }\n tick();\n },\n this._config.refreshIntervalMs,\n );\n\n // unref() so the interval doesn't prevent Node.js process exit\n this._refreshTimer.unref();\n\n debug('Started fix refresh interval');\n }\n}\n","/**\n * Provider patcher input validation.\n *\n * F-722/F-620: every `patchX(client)` entry point creates `new Proxy(client, ...)`.\n * Proxy constructors throw an opaque `TypeError: Cannot create proxy with a non-object\n * as target or handler` when handed `null`, `undefined`, a primitive, or `false`.\n * That error happens deep in the SDK with no actionable message — and it crashes\n * the customer's app startup the moment they pass a maybe-null client.\n *\n * We fail-fast with a clear, named TypeError so the customer sees:\n * \"patchOpenAI requires a client object, got null\"\n * instead of:\n * \"Cannot create proxy with a non-object as target or handler\"\n *\n * Rationale for throwing (not returning the input):\n * - Returning the input would silently disable instrumentation; a customer who\n * expects spans would see \"no traces\" and have to root-cause it themselves.\n * - Throwing surfaces the bug at the call-site (their `patchOpenAI(maybeNull)`).\n * - It happens at init/setup time, not in the request hot path, so no latency cost.\n */\n// PR-4+5 review NIT (2026-05-25): asserts-style narrowing. Pre-fix the\n// signature returned `void` with an `unknown` client parameter, forcing\n// every patcher's `new Proxy(client, ...)` call to keep the `unknown` /\n// loose `T` type — TS could not prove the Proxy target was non-null.\n// `asserts client is NonNullable<T>` means TS narrows the caller's\n// variable after assertClient returns, so the surrounding code is\n// type-safe without redundant runtime checks.\nexport function assertClient<T>(\n patcherName: string,\n client: T,\n): asserts client is NonNullable<T> {\n if (client === null || client === undefined) {\n throw new TypeError(\n `${patcherName} requires a client object, got ${client === null ? 'null' : 'undefined'}`,\n );\n }\n const t = typeof client;\n if (t !== 'object' && t !== 'function') {\n throw new TypeError(\n `${patcherName} requires a client object, got ${t}`,\n );\n }\n}\n","/**\n * Instructor integration via Proxy wrapping.\n *\n * Instructor wraps an LLM client's create() method to extract structured\n * data from completions using a response model (Zod schema, etc.).\n *\n * F-884: The Instructor JS client (`@instructor-ai/instructor`) exposes the\n * structured-extraction method at `client.chat.completions.create(...)` —\n * mirroring the underlying OpenAI shape — NOT at a top-level `client.create`.\n * The previous patcher hooked the top-level `create`, which Instructor JS does\n * not have, so no spans ever fired. We now walk the nested path (chat →\n * completions → create) AND keep a top-level `create` intercept for forward-\n * compatibility with API shapes that may expose both.\n *\n * Usage:\n * import { patchInstructor } from 'risicare/instructor';\n * import Instructor from '@instructor-ai/instructor';\n * const client = patchInstructor(Instructor({ client: openai, mode: 'TOOLS' }));\n * const result = await client.chat.completions.create({\n * model: 'gpt-4o-mini',\n * messages: [...],\n * response_model: { schema: MySchema, name: 'MyExtraction' },\n * });\n *\n * Does NOT suppress provider instrumentation -- Instructor delegates to the\n * underlying LLM client, which should produce its own provider span.\n */\n\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { debug } from '../utils/log.js';\nimport { assertClient } from '../utils/assert-client.js';\n\n/**\n * Build the wrapped `create` function. Shared between top-level (legacy) and\n * nested (`chat.completions.create`, the real Instructor JS shape) intercepts.\n */\nfunction makePatchedCreate(originalCreate: Function): Function {\n return function patchedCreate(this: unknown, ...args: unknown[]): unknown {\n const tracer = getTracer();\n if (!tracer?.enabled) {\n debug('Tracer not initialized — call init() before using patchInstructor()');\n return originalCreate.apply(this, args);\n }\n\n const params = (args[0] ?? {}) as Record<string, unknown>;\n // Instructor JS accepts response_model as { schema, name } or a Zod schema\n const responseModel = params.response_model ?? params.responseModel;\n\n let modelName = 'unknown';\n if (responseModel && typeof responseModel === 'function') {\n modelName = (responseModel as { name?: string }).name || 'unknown';\n } else if (responseModel && typeof responseModel === 'object') {\n const rm = responseModel as Record<string, unknown>;\n modelName =\n (rm.name as string) ??\n (rm.description as string) ??\n ((rm.schema as { name?: string } | undefined)?.name) ??\n 'schema';\n } else if (typeof responseModel === 'string') {\n modelName = responseModel;\n }\n\n return tracer.startSpan(\n {\n name: 'instructor.create',\n kind: SpanKind.LLM_CALL,\n attributes: {\n framework: 'instructor',\n 'framework.span_kind': 'extraction',\n 'instructor.response_model': modelName,\n ...(params.max_retries != null\n ? { 'instructor.max_retries': params.max_retries }\n : {}),\n ...(params.model != null\n ? { 'gen_ai.request.model': params.model }\n : {}),\n },\n },\n (_span) => {\n const result = originalCreate.apply(this, args);\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n return (result as Promise<unknown>).then((r) => r);\n }\n return result;\n },\n );\n };\n}\n\n/**\n * Wrap an Instructor client with Risicare tracing.\n *\n * Intercepts BOTH:\n * - `client.chat.completions.create` (the real Instructor JS shape)\n * - `client.create` (legacy top-level shape, if present)\n *\n * @param client - An Instructor client\n * @returns A proxied client with tracing enabled\n */\nexport function patchInstructor<T extends object>(client: T): T {\n assertClient('patchInstructor', client);\n return new Proxy(client, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n // Legacy top-level create (rare, but harmless to keep for compat).\n if (prop === 'create' && typeof value === 'function') {\n return makePatchedCreate(value.bind(target));\n }\n\n // F-884: REAL Instructor JS shape — walk into `.chat.completions.create`.\n if (prop === 'chat' && value && typeof value === 'object') {\n return new Proxy(value as object, {\n get(chatTarget, chatProp, chatReceiver) {\n const chatValue = Reflect.get(chatTarget, chatProp, chatReceiver);\n if (chatProp === 'completions' && chatValue && typeof chatValue === 'object') {\n return new Proxy(chatValue as object, {\n get(compTarget, compProp, compReceiver) {\n const compValue = Reflect.get(compTarget, compProp, compReceiver);\n if (compProp === 'create' && typeof compValue === 'function') {\n return makePatchedCreate(compValue.bind(compTarget));\n }\n return compValue;\n },\n });\n }\n return chatValue;\n },\n });\n }\n\n return value;\n },\n });\n}\n"],"mappings":";AA+BA,SAAS,cAAAA,mBAAkB;;;ACLpB,IAAM,iBAAsC,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAGlF,IAAM,mBAAmB;AAGzB,IAAM,uBAAuB;AAC7B,IAAM,sBAAsB;AAG5B,IAAM,0BAA0B;AAGhC,IAAM,6BAA6B;AAMnC,IAAM,4BAA4B;AAGlC,IAAM,SAAqC,EAAE,UAAU,MAAM,KAAK,OAAO,EAAE;AAG3E,SAAS,cAAc,aAAqB,UAA0B;AAC3E,QAAM,WAAW,KAAK,IAAI,KAAK,IAAI,aAAa,CAAC,GAAG,EAAE;AACtD,QAAM,UAAU,KAAK,IAAI,qBAAqB,uBAAuB,KAAK,QAAQ;AAClF,SAAO,KAAK,IAAI,KAAK,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI;AAC9C;AAEA,IAAM,UAAU;AAST,SAAS,iBACd,OACA,QAAgB,KAAK,IAAI,GACV;AACf,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,QAAM,OAAO,OAAO,KAAK,EAAE,KAAK;AAChC,MAAI,SAAS,GAAI,QAAO;AACxB,MAAI,QAAQ,KAAK,IAAI,GAAG;AACtB,UAAM,UAAU,OAAO,IAAI;AAC3B,WAAO,OAAO,SAAS,OAAO,KAAK,WAAW,IAAI,UAAU;AAAA,EAC9D;AAGA,MAAI,CAAC,WAAW,KAAK,IAAI,EAAG,QAAO;AACnC,QAAM,OAAO,KAAK,MAAM,IAAI;AAC5B,MAAI,CAAC,OAAO,SAAS,IAAI,EAAG,QAAO;AACnC,SAAO,KAAK,IAAI,IAAI,OAAO,SAAS,GAAI;AAC1C;;;ACjEA,SAAS,yBAAyB;AAGlC,IAAM,IAAI;AACV,IAAM,SAAS;AAYR,SAAS,YAA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