risicare 0.5.2 → 0.6.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.
- package/README.md +11 -6
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +19 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +19 -5
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/globals.ts","../src/utils/log.ts","../src/masking.ts","../src/exporters/batch.ts","../src/config.ts","../src/ids.ts","../src/types.ts","../src/utils/clock.ts","../src/span.ts","../src/noop.ts","../src/utils/sampling.ts","../src/runtime/config.ts","../src/runtime/taxonomy.generated.ts","../src/runtime/interceptors.ts","../src/context/storage.ts","../src/tracer.ts","../src/version.ts","../src/exporters/http.ts","../src/exporters/console.ts","../src/runtime/cache.ts","../src/runtime/applier.ts","../src/runtime/loader.ts","../src/runtime/runtime.ts","../src/context/agent.ts","../src/lifecycle.ts","../src/decorators/agent.ts","../src/context/session.ts","../src/decorators/session.ts","../src/context/phase.ts","../src/decorators/phase.ts","../src/decorators/multi-agent.ts","../src/context/trace-context.ts","../src/context/registry.ts","../src/streaming.ts","../src/context/dedup.ts","../src/frameworks/langchain.ts","../src/frameworks/langgraph.ts","../src/utils/assert-client.ts","../src/frameworks/instructor.ts","../src/frameworks/llamaindex.ts","../src/webhooks.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 } from './config.js';\nimport { Tracer } from './tracer.js';\nimport { BatchSpanProcessor, SHUTDOWN_BUDGET_MS } from './exporters/batch.js';\nimport { HttpExporter } from './exporters/http.js';\nimport { ConsoleExporter } from './exporters/console.js';\nimport { SpanKind, SpanStatus } from './types.js';\nimport type { SpanExporter } from './exporters/base.js';\nimport { setDebug, debug } from './utils/log.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';\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\". 500 ms covers the up-to-one-RTT overrun\n * the between-rounds deadline check permits (ruling §4.4).\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// ─── 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 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\n if (this.config.apiKey && !this.config.apiKey.startsWith('rsk-')) {\n debug('Warning: API key should start with \"rsk-\". Got: ' + this.config.apiKey.slice(0, 4) + '...');\n }\n\n // Build exporter chain\n //\n // ⚠ F-SDKJSCONSOLE-001 (fixed 2026-08-15, W23). The `else` arm below used to\n // read `exporter = new ConsoleExporter()` — \"No API key and not debug — use\n // console as fallback\". `exporters/console.ts` writes\n // `JSON.stringify(span.toPayload())` to `process.stderr`: the WHOLE payload,\n // every attribute, every event, every exception, with NO redaction of any\n // kind. Neither Tier-1 (credentials) nor Tier-2 (email/phone/SSN/card/IPv4)\n // exists in the SDK — both run server-side, one hop later — so there is\n // nothing to fall back on and the only safe action is not to write.\n //\n // A falsy API key is not an exotic state: it is a missing, mistyped or\n // not-injected `RISICARE_API_KEY` — CI, staging, a new dev's laptop, a\n // container whose secret failed to mount. Measured from the extracted,\n // PUBLISHED `risicare-0.4.2.tgz` in BOTH module systems (W20-P2, re-derived\n // W23): `RISICARE_TRACING=true` with no key printed a synthetic email, SSN,\n // Visa test PAN and RFC-5737 address to the customer's own stderr. No debug\n // flag was required and no warning was emitted.\n //\n // Python in the identical state WARNS AND DROPS (`client.py:941-947`) and\n // attaches its ConsoleExporter only under `if config.debug`\n // (`client.py:868-875`). This makes JS match Python rather than inventing a\n // third behaviour: the explicit debug opt-in below is UNCHANGED — a customer\n // who asks for console output still gets it — and the accidental state now\n // configures NO exporter at all, which is exactly what Python does.\n //\n // Consequence, deliberate and honest: with an empty exporter array the\n // processor's existing accounting takes over — spans are re-queued to the\n // MAX_RETRIES bound and then discarded as `transport_refused`, COUNTED and\n // WARNED (\"check the api_key and the endpoint\"), instead of being reported\n // as delivered. A DropExporter returning SUCCESS would have been the smaller\n // diff and would have inflated `exportedSpans` for spans that reached\n // nothing — the F-HONEST-001 defect, re-introduced in the SDK.\n let exporter: SpanExporter | undefined;\n if (this.config.debug && !this.config.apiKey) {\n exporter = new ConsoleExporter();\n } else 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 } else {\n // No API key and not debug — configure NO exporter, and say so. Spans are\n // created and then dropped, exactly as in Python.\n exporter = undefined;\n if (this.config.enabled) {\n // console.warn, not debug() — `debug` is off by default, which is how\n // F-SDKJSREPORTERROR-001 stayed invisible in a shipped release. Same\n // defensive wrapper as the FixRuntime warning below: some sandboxed and\n // edge runtimes have a closed stderr, and a logging call must never be\n // the thing that crashes a customer's process.\n try {\n console.warn(\n `[risicare] tracing is enabled but NO API key is configured — spans are ` +\n `created and then DROPPED, not sent to ${this.config.endpoint}. ` +\n `Pass apiKey to init() (or set the RISICARE_API_KEY env var). ` +\n `Span data is NOT written to the console: it would be unredacted. ` +\n `Pass debug:true if you want console output for local development.`\n );\n } catch {\n // Prefer silent over crash.\n }\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 // Start the batch processor (enables span queuing and periodic flushing)\n this.processor.start();\n\n // Start FixRuntime for runtime fix application (preparatory\n // infrastructure for Stage 4 deployment; today /v1/fixes/active\n // always returns empty since no fix is promoted past status=draft).\n // Loads active fixes from /api/v1/fixes/active, caches with TTL,\n // background-refreshes every 60s. Provider patches call interceptCall()\n // to apply fixes before LLM calls.\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 endpoint so customers can verify\n // reachability. Mirrors the Python SDK fix at client.py:520-528.\n if (this.config.apiKey && this.config.enabled) {\n try {\n initFixRuntime({\n apiEndpoint: this.config.endpoint,\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 = e instanceof Error ? e.message : String(e);\n try {\n console.warn(\n `[risicare] FixRuntime initialization failed — auto-fix is OFFLINE for this process. ` +\n `endpoint=${this.config.endpoint} 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(`FixRuntime init traceback: ${e instanceof Error && e.stack ? e.stack : String(e)}`);\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=${this.config.endpoint}`);\n }\n\n get enabled(): boolean {\n return this.tracer.enabled;\n }\n\n set enabled(value: boolean) {\n this.tracer.enabled = value;\n }\n\n // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)\n async shutdown(): Promise<void> {\n if (this._shutdownPromise) return this._shutdownPromise;\n this._shutdownPromise = this._doShutdown();\n return this._shutdownPromise;\n }\n\n private async _doShutdown(): 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 await this.processor.shutdown();\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 }\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(): Promise<boolean> {\n return this.processor.flush();\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 *\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 = () => {\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\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 ];\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\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 */\nexport async function shutdown(): 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();\n setGlobalClient(undefined);\n setGlobalTracer(undefined);\n}\n\n/**\n * Flush all pending spans without shutting down.\n *\n * @returns `true` only if everything queued at entry was DELIVERED — `false`\n * if the deadline expired with spans still queued, or if any span was\n * discarded during the window (F-SDKCB-001 §6). An uninitialised SDK returns\n * `true`: it was handed nothing, and it lost nothing.\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(): Promise<boolean> {\n const client = getGlobalClient() as RisicareClient | undefined;\n if (!client) return true;\n return client.flush();\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.\n */\nexport function isEnabled(): boolean {\n const client = getGlobalClient() as RisicareClient | undefined;\n return client?.enabled ?? false;\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, matching the 0.5.1 config default.\n return tracer?.traceContent ?? false;\n}\n\n/**\n * Get SDK metrics: exported spans, dropped spans, failed exports, queue stats.\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 { ...client.processor.getMetrics(), sdkState: 'running' as const };\n }\n if (_finalMetrics) {\n // Copy: a caller mutating the object must not corrupt the one tally the\n // process has left.\n return {\n ..._finalMetrics,\n droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },\n sdkState: 'shutdown' as const,\n };\n }\n return {\n exportedSpans: 0,\n droppedSpans: 0,\n droppedSpansByReason: {\n queue_full: 0,\n transport_refused: 0,\n shutdown_residue: 0,\n },\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 span.setAttribute('error.message', err.message.slice(0, 2000));\n if (err.stack) span.setAttribute('error.stack', err.stack.slice(0, 4000));\n span.setAttribute('risicare.reported_error', true);\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 * Record a custom evaluation score on a trace.\n *\n * Sends the score to the server in a fire-and-forget fashion.\n * This function never throws and is non-blocking.\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 if (typeof value !== 'number' || !Number.isFinite(value) || value < 0.0 || value > 1.0) {\n debug(`score: value must be in [0.0, 1.0], got ${value}. Score not sent.`);\n return;\n }\n if (!traceId || !name) {\n debug('score: traceId and name are required');\n return;\n }\n\n const client = getGlobalClient() as RisicareClient | undefined;\n if (!client?.enabled || !client.config.apiKey) return;\n\n const endpoint = client.config.endpoint.replace(/\\/$/, '');\n const url = `${endpoint}/api/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 // Fire-and-forget — never blocks caller\n fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${client.config.apiKey}`,\n },\n body,\n }).catch((err) => debug(`score: send failed: ${err}`));\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 * 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 * 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; nothing here inspects a VALUE. The gate is a\n// pure KEY-SHAPE filter, and it lives in this module because this module already\n// owns the one walk both content paths cross.\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-match set, same suffix\n// rule, 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/**\n * Attribute keys that carry customer content but do not match the suffix rule.\n *\n * ⚠ LOAD-BEARING. `gen_ai.system_prompt` (anthropic, bedrock) and\n * `gen_ai.prompt.message` (cohere) carry content and do NOT end in `content` —\n * a suffix rule alone silently leaks both. Matched EXACTLY rather than by\n * substring, because `framework.pydantic_ai.system_prompt_length` is a number\n * and must survive.\n */\nconst CONTENT_KEYS_EXACT: ReadonlySet<string> = new Set([\n 'gen_ai.system_prompt',\n 'gen_ai.prompt.message',\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\n/**\n * Whether `key` names a customer-content attribute. Pure function of the KEY.\n *\n * Derived from what the PLATFORM treats as content — exactly the keys\n * `spans_worker._extract_input_preview` / `_extract_output_preview` read — plus\n * every `*.content` key the providers and integrations emit. Guards on the\n * SHAPE, not an enumeration (F-COMPATGUARD-001: an enumeration rots the moment\n * a provider adds a key).\n *\n * Deliberately does NOT match: `gen_ai.response.content_type` (a MIME type),\n * `gen_ai.response.content_blocks` / `gen_ai.prompt.parts` /\n * `gen_ai.response.choices` / `gen_ai.completion.tool_calls` (counts),\n * `gen_ai.prompt.{i}.role` (a role name).\n */\nexport function isContentKey(key: string): boolean {\n if (CONTENT_KEYS_EXACT.has(key)) return true;\n const lastSegment = key.slice(key.lastIndexOf('.') + 1);\n if (lastSegment === 'content') return true;\n return key.endsWith('_content');\n}\n\n/** Replace every content-keyed value in `attrs` IN PLACE. Returns the count. */\nfunction stripAttributes(attrs: Record<string, unknown>): number {\n let n = 0;\n for (const k of Object.keys(attrs)) {\n if (isContentKey(k)) {\n attrs[k] = CONTENT_OMITTED_MARKER;\n n++;\n }\n }\n return n;\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.\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.\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 stripped += stripAttributes(event.attributes);\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 += stripAttributes(link.attributes);\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 debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);\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 SpanExporter } from './base.js';\nimport { debug, warn } from '../utils/log.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`** — the same fail-closed default as `resolveConfig`.\n * When false, every content-keyed attribute is replaced on the export path\n * 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 */\nexport type DropReason = 'queue_full' | 'transport_refused' | 'shutdown_residue';\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\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/**\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 _beforeExitHandler: (() => void) | null = null;\n\n // Retry tracking for failed batches (Audit #5)\n private _retryCounts = new Map<string, number>();\n private static readonly MAX_RETRIES = 3;\n\n private _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;\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 };\n exportedSpans = 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 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 * Anything still queued when the loop stops is COUNTED as `shutdown_residue`\n * and announced with a WARNING. The warning is the primary signal, not the\n * counter: a counter incremented inside `shutdown()` is written to memory\n * about to be freed and has no reader (RULING §2 / §8.2).\n */\n async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS): Promise<void> {\n if (!this._started) return;\n this._started = false;\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 drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);\n\n while (this._queue.length > 0 || this._flushing) {\n if (Date.now() >= drainDeadline) break;\n const outcome = await this._exportBatch();\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 // 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 // Once shutdown() has returned, holding IS abandoning: the timer is\n // cleared, the exit listener is gone, nothing will ever export these.\n const residue = this._queue.length;\n if (residue > 0) {\n this._queue.length = 0;\n this._recordDropped('shutdown_residue', residue);\n // NOT rate-limited, by ruling. Names the count AND the reason.\n warn(\n `shutdown() gave up with ${residue} span(s) still queued ` +\n `(reason=shutdown_residue) — they were NOT delivered. The ${timeoutMs} ms ` +\n `shutdown budget expired or the transport stopped accepting. Raise the ` +\n `shutdown timeout, or your container's termination grace period, to lose less.`\n );\n }\n\n // Shutdown exporters\n for (const exporter of this._exporters) {\n try {\n await exporter.shutdown();\n } catch (e) {\n debug(`Error shutting down ${exporter.name}: ${e}`);\n }\n }\n\n // Clean up retry tracking — retry-map drain site 3 of 3\n this._retryCounts.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) return;\n\n // Check queue capacity\n if (this._queue.length >= this._maxQueueSize) {\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 (this._queue.length >= this._batchSize) {\n void this._exportBatch();\n }\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 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 * Returns `false` when (a) the deadline expires with spans still queued,\n * (b) any span was discarded during the window — breaker refusal or retry\n * exhaustion — or (c) it is called after `shutdown()` and the shutdown\n * residue was non-zero.\n *\n * ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span\n * that arrived DURING the window 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 = SHUTDOWN_BUDGET_MS): Promise<boolean> {\n if (!this._started) {\n // (c) — the `!_started => true` early return was unconditional, so\n // `flush()` after `shutdown()` reported success over abandoned data.\n return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;\n }\n\n const start = Date.now();\n const discardedAtEntry = this.droppedSpans;\n\n // Wait for in-flight exports to complete AND queue to drain\n while (this._queue.length > 0 || this._flushing) {\n if (!this._flushing && this._queue.length > 0) {\n await this._exportBatch();\n } else {\n // Wait a tick for the in-flight export to finish\n await new Promise((r) => setTimeout(r, 1));\n }\n if (Date.now() - start > timeoutMs) return false;\n }\n\n return this.droppedSpans === discardedAtEntry;\n }\n\n getMetrics() {\n return {\n exportedSpans: this.exportedSpans,\n droppedSpans: this.droppedSpans,\n droppedSpansByReason: { ...this.droppedSpansByReason },\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 private async _exportBatch(): Promise<Round> {\n if (this._flushing) return Round.Busy;\n if (this._queue.length === 0) return Round.Empty;\n this._flushing = true;\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\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 for (const exporter of this._exporters) {\n try {\n const result = await exporter.export(batch);\n if (result === ExportResult.SUCCESS) {\n if (!batchExported) {\n this.exportedSpans += batch.length;\n batchExported = true;\n // Clear retry counts for successfully exported spans\n for (const span of batch) {\n this._retryCounts.delete(span.spanId);\n }\n }\n } else {\n this.failedExports++;\n }\n } catch (e) {\n this.failedExports++;\n debug(`Export to ${exporter.name} failed: ${e}`);\n }\n }\n\n // Audit #5: Re-queue failed batches with retry limit\n if (!batchExported) {\n let dropped = 0;\n const retryable = batch.filter(span => {\n const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;\n if (count > BatchSpanProcessor.MAX_RETRIES) {\n // retry-map drain site 2 of 3\n this._retryCounts.delete(span.spanId);\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 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 warn(\n `${dropped} span(s) DISCARDED (reason=transport_refused) after ` +\n `${BatchSpanProcessor.MAX_RETRIES} failed export attempts each — 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 this._flushing = false;\n }\n }\n}\n","/**\n * SDK configuration with environment variable loading.\n *\n * Environment variables match the Python SDK exactly:\n * RISICARE_API_KEY, RISICARE_ENDPOINT, RISICARE_PROJECT_ID, etc.\n */\n\nimport { DEFAULT_BATCH_SIZE } from './exporters/batch.js';\nimport type { MaskFn } from './masking.js';\n\nexport interface RisicareConfig {\n /** API key for authentication (format: \"rsk-{random}\"). Each key is scoped to one project. */\n apiKey?: string;\n\n /** Gateway endpoint URL */\n endpoint?: string;\n\n /**\n * @deprecated Project is determined by your API key. This field is ignored\n * by the gateway and will be removed in v1.0. Use `serviceName` and\n * `environment` for within-project organization.\n */\n projectId?: string;\n\n /** Environment name (production, staging, development). Used for within-project organization. */\n environment?: string;\n\n /** Service name for within-project organization. */\n serviceName?: string;\n\n /** Service version */\n serviceVersion?: string;\n\n /** Whether tracing is enabled (default: true if apiKey provided) */\n enabled?: boolean;\n\n /**\n * Whether prompt/completion content may leave the process.\n *\n * **Default `false` since 0.5.1** (was `true`). When false, every\n * content-keyed attribute is replaced with `<risicare:content-omitted>` on\n * the export path — including content you set by hand, which 0.5.0 and\n * earlier did NOT gate.\n */\n traceContent?: boolean;\n\n /** Sample rate 0.0–1.0 (default: 1.0 = trace all) */\n sampleRate?: number;\n\n /** Batch size threshold before flush (default: 100) */\n batchSize?: number;\n\n /** Batch timeout in ms before flush (default: 1000) */\n batchTimeoutMs?: number;\n\n /** Maximum queue size (default: 10000) */\n maxQueueSize?: number;\n\n /** Enable debug logging (default: false) */\n debug?: boolean;\n\n /** Enable gzip compression for HTTP exports (default: false) */\n compress?: boolean;\n\n /** Custom metadata attached to all spans */\n metadata?: Record<string, unknown>;\n\n /**\n * Masking callback applied to every content-bearing field of every span\n * BEFORE the batch leaves the process — `mask(key, value) => value`.\n *\n * This is the only layer at which you can keep data off Risicare's wire, so\n * it applies to every exporter, including custom ones. `key` is the attribute\n * key (`\"gen_ai.prompt.0.content\"`) or a dotted path (`\"statusMessage\"`,\n * `\"events.0.attributes.x\"`). Identifiers and span/event names are NOT passed\n * to it — masking those breaks trace structure and your own joins.\n *\n * ⚠ Must be CPU-only and fast: Node is single-threaded, so this runs on your\n * event loop. No I/O, no network, no unbounded retries, no per-request state.\n * If it throws, that one field becomes `\"<risicare:mask-error>\"` and the span\n * is still exported. See `masking.ts`.\n *\n * ⚠ Has NO environment-variable form, deliberately: the shapes that would\n * make a callable env-resolvable are arbitrary code execution driven by the\n * process environment. Masking is configured in code, by the application that\n * owns the data.\n */\n mask?: MaskFn;\n}\n\nconst DEFAULT_ENDPOINT = 'https://app.risicare.ai';\n\n/**\n * Load configuration from environment variables, merged with explicit config.\n * Explicit config takes precedence over env vars.\n */\nexport function resolveConfig(\n config?: Partial<RisicareConfig>,\n): Required<Omit<RisicareConfig, 'metadata' | 'mask'>> & {\n metadata: Record<string, unknown>;\n // `mask` is excluded from `Required<>` on purpose: \"no mask\" is a real,\n // supported state and must stay expressible as `undefined`. Defaulting it to\n // an identity function would make \"is masking configured?\" unanswerable by\n // inspection — the processor skips the whole pass when this is undefined.\n mask: MaskFn | undefined;\n} {\n const env = process.env;\n\n const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;\n const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;\n const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;\n\n // Deprecation warning for projectId\n if (config?.projectId || env.RISICARE_PROJECT_ID) {\n console.warn(\n '[risicare] projectId is deprecated and ignored by the gateway. ' +\n 'Your API key determines the project. ' +\n 'Use serviceName and environment for within-project organization. ' +\n 'projectId will be removed in v1.0.'\n );\n }\n const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? 'development';\n const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;\n const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;\n // ⚠ DEFAULT CHANGED 0.5.0 -> 0.5.1: was `true`. `RISICARE_TRACE_CONTENT=true`\n // (or `traceContent: true`) restores capture explicitly.\n const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);\n const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? '1.0');\n const debug = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);\n const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);\n // SDK-RELEASE-RULING.md §4.3: default raised 100 -> 500. Derived, and stated\n // once in `exporters/batch.ts` — imported rather than repeated so the env\n // default and the validation default cannot drift apart from the processor's.\n const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, DEFAULT_BATCH_SIZE);\n const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1000);\n const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 10000);\n\n // F-355/F-356/F-357: numeric inputs must validate, clamp, and warn —\n // silent NaN/negative/string acceptance breaks the exporter unpredictably.\n const sampleRate = validateSampleRate(sampleRateRaw);\n // F-SDKSAMPRATEBLIND-001 — the rate never reaches the platform, so say so at\n // the one moment the customer chose it. Verified 2026-08-17 across 539\n // first-party server / worker / dashboard / gateway / schema files (controls:\n // 128 files match trace_id, 228 match project_id): no ingest field, no\n // column, no query and no W3C traceparent flag carries it — both emitters\n // hardcode `-01`, and `TraceFlags.SAMPLED` has zero call sites. So every\n // server-side count is a count of SAMPLED traces and nothing downstream can\n // scale it back up. Re-run: fix-workstream/perf/w34/sampling_wire_probe.sh\n if (sampleRate < 1.0) {\n console.warn(\n `[risicare] sampleRate=${sampleRate} — head sampling is applied in-process ` +\n `and the rate is NOT transmitted to the platform. Trace counts, error rates ` +\n `and cost figures in the dashboard will describe the sampled subset only, ` +\n `and cannot be scaled back to totals. Sampling is trace-coherent: a dropped ` +\n `trace drops whole.`,\n );\n }\n const batchSize = validatePositiveInt('batchSize', batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 10_000);\n const batchTimeoutMs = validatePositiveInt('batchTimeoutMs', batchTimeoutMsRaw, 1000, 1, 600_000);\n const maxQueueSize = validatePositiveInt('maxQueueSize', maxQueueSizeRaw, 10_000, 1, 1_000_000);\n\n // Enabled logic: explicit > env RISICARE_TRACING > (true if apiKey present)\n let enabled: boolean;\n if (config?.enabled !== undefined) {\n enabled = config.enabled;\n } else if (env.RISICARE_TRACING !== undefined) {\n enabled = parseBool(env.RISICARE_TRACING, false);\n } else {\n enabled = !!apiKey;\n }\n\n return {\n apiKey: apiKey ?? '',\n endpoint,\n projectId: projectId ?? '',\n environment,\n serviceName: serviceName ?? '',\n serviceVersion: serviceVersion ?? '',\n enabled,\n traceContent,\n sampleRate,\n batchSize,\n batchTimeoutMs,\n maxQueueSize,\n debug,\n compress,\n metadata: config?.metadata ?? {},\n // No env fallback — see the field's note on RisicareConfig.\n mask: config?.mask,\n };\n}\n\nfunction parseBool(value: string | undefined, defaultValue: boolean): boolean {\n if (value === undefined) return defaultValue;\n const lower = value.toLowerCase();\n return lower === 'true' || lower === '1' || lower === 'yes';\n}\n\n/**\n * Parse a numeric env var with a fallback default. parseInt returns NaN on\n * non-numeric input — we want the default in that case, not NaN propagating.\n */\nfunction parseNumericEnv(value: string | undefined, defaultValue: number): number {\n if (value === undefined) return defaultValue;\n const n = Number(value);\n return Number.isFinite(n) ? n : defaultValue;\n}\n\n/**\n * F-355: sampleRate must be a finite number in [0, 1]. Anything else warns\n * and falls back to 1.0 (trace everything — safer default for an observability\n * platform than \"trace nothing\" on a typo).\n */\nfunction validateSampleRate(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1) {\n return value;\n }\n // Try string→number coercion once for env vars that arrive as strings.\n if (typeof value === 'string') {\n const n = Number(value);\n if (Number.isFinite(n) && n >= 0 && n <= 1) return n;\n }\n console.warn(\n `[risicare] sampleRate must be a finite number in [0, 1], got ${typeof value}=${JSON.stringify(value)}; defaulting to 1.0`,\n );\n return 1.0;\n}\n\n/**\n * F-356/F-357: validate a positive-integer config knob. Coerces strings,\n * rejects NaN/negative/non-finite, clamps to [min, max] with a warning.\n */\nfunction validatePositiveInt(\n name: string,\n value: unknown,\n defaultValue: number,\n min: number,\n max: number,\n): number {\n let n: number;\n if (typeof value === 'number') {\n n = value;\n } else if (typeof value === 'string') {\n n = Number(value);\n if (Number.isFinite(n)) {\n console.warn(\n `[risicare] ${name} was a string (\"${value}\"); coerced to ${n}. Pass a number to avoid this warning.`,\n );\n }\n } else {\n console.warn(\n `[risicare] ${name} must be a positive integer, got ${typeof value}; defaulting to ${defaultValue}`,\n );\n return defaultValue;\n }\n if (!Number.isFinite(n) || n <= 0) {\n console.warn(\n `[risicare] ${name} must be > 0, got ${value}; defaulting to ${defaultValue}`,\n );\n return defaultValue;\n }\n if (n < min) {\n console.warn(`[risicare] ${name}=${n} below floor; clamping to ${min}`);\n return min;\n }\n if (n > max) {\n console.warn(`[risicare] ${name}=${n} above ceiling; clamping to ${max}`);\n return max;\n }\n return Math.floor(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 * Core type definitions for the Risicare SDK.\n *\n * These enums and types mirror the Python SDK's risicare-core types\n * and align with the Rust gateway's SpanData struct.\n */\n\n// ─── Span Kind ───────────────────────────────────────────────────────────────\n\nexport enum SpanKind {\n INTERNAL = 'internal',\n CLIENT = 'client',\n SERVER = 'server',\n PRODUCER = 'producer',\n CONSUMER = 'consumer',\n AGENT = 'agent',\n LLM_CALL = 'llm_call',\n TOOL_CALL = 'tool_call',\n RETRIEVAL = 'retrieval',\n DECISION = 'decision',\n MESSAGE = 'message',\n DELEGATION = 'delegation',\n COORDINATION = 'coordination',\n THINK = 'think',\n DECIDE = 'decide',\n OBSERVE = 'observe',\n REFLECT = 'reflect',\n}\n\n// ─── Span Status ─────────────────────────────────────────────────────────────\n\nexport enum SpanStatus {\n UNSET = 'unset',\n OK = 'ok',\n ERROR = 'error',\n}\n\n// ─── Semantic Phase (Tier 4: Decision Tracking) ──────────────────────────────\n\nexport enum SemanticPhase {\n THINK = 'think',\n DECIDE = 'decide',\n ACT = 'act',\n OBSERVE = 'observe',\n REFLECT = 'reflect',\n COMMUNICATE = 'communicate',\n COORDINATE = 'coordinate',\n}\n\n// ─── Agent Role ──────────────────────────────────────────────────────────────\n\nexport enum AgentRole {\n // Primary roles\n ORCHESTRATOR = 'orchestrator',\n WORKER = 'worker',\n SUPERVISOR = 'supervisor',\n SPECIALIST = 'specialist',\n // Communication roles\n ROUTER = 'router',\n AGGREGATOR = 'aggregator',\n BROADCASTER = 'broadcaster',\n // Specialized roles\n CRITIC = 'critic',\n PLANNER = 'planner',\n EXECUTOR = 'executor',\n RETRIEVER = 'retriever',\n VALIDATOR = 'validator',\n // JS-specific (backwards compatibility)\n REVIEWER = 'reviewer',\n CUSTOM = 'custom',\n}\n\n// ─── Message Type (Tier 5: Multi-Agent) ──────────────────────────────────────\n\nexport enum MessageType {\n // Control messages\n TASK = 'task',\n RESULT = 'result',\n STATUS = 'status',\n ERROR = 'error',\n // Communication messages\n QUERY = 'query',\n RESPONSE = 'response',\n BROADCAST = 'broadcast',\n DIRECT = 'direct',\n // Coordination messages\n PROPOSAL = 'proposal',\n VOTE = 'vote',\n CONSENSUS = 'consensus',\n CONFLICT = 'conflict',\n // Lifecycle messages\n HEARTBEAT = 'heartbeat',\n SHUTDOWN = 'shutdown',\n HANDOFF = 'handoff',\n // JS-specific (backwards compatibility)\n REQUEST = 'request',\n DELEGATE = 'delegate',\n COORDINATE = 'coordinate',\n}\n\n// ─── Span Event ──────────────────────────────────────────────────────────────\n\nexport interface SpanEvent {\n name: string;\n timestamp: string;\n attributes?: Record<string, unknown>;\n}\n\n// ─── Span Link ───────────────────────────────────────────────────────────────\n\nexport interface SpanLink {\n traceId: string;\n spanId: string;\n attributes?: Record<string, unknown>;\n}\n\n// ─── Span Payload (Wire Format) ──────────────────────────────────────────────\n// Matches Rust gateway SpanData struct exactly (camelCase)\n\nexport interface SpanPayload {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n kind: string;\n startTime: string;\n endTime?: string;\n durationMs?: number;\n status: string;\n statusMessage?: string;\n attributes: Record<string, unknown>;\n events: SpanEvent[];\n links: SpanLink[];\n sessionId?: string;\n agentId?: string;\n agentName?: string;\n agentType?: string;\n semanticPhase?: string;\n llmProvider?: string;\n llmModel?: string;\n llmPromptTokens?: number;\n llmCompletionTokens?: number;\n llmTotalTokens?: number;\n llmCostUsd?: number;\n toolName?: string;\n toolSuccess?: boolean;\n}\n\n// ─── Ingest Request ──────────────────────────────────────────────────────────\n\nexport interface IngestRequest {\n spans: SpanPayload[];\n batchId?: string;\n projectId?: string;\n environment?: string;\n}\n","/**\n * High-resolution timing and ISO 8601 formatting utilities.\n */\n\n/**\n * Get current time as ISO 8601 string with millisecond precision.\n */\nexport function nowISO(): string {\n return new Date().toISOString();\n}\n\n/**\n * Get high-resolution monotonic time in milliseconds.\n * Uses process.hrtime.bigint() for sub-ms precision.\n */\nexport function hrtimeMs(): number {\n return Number(process.hrtime.bigint()) / 1_000_000;\n}\n\n/**\n * Compute duration in milliseconds between two hrtime values.\n */\nexport function durationMs(startHrtime: number, endHrtime: number): number {\n return Math.max(0, endHrtime - startHrtime);\n}\n\n/**\n * Format a Date or ISO string to ISO 8601 with millisecond precision.\n */\nexport function toISO(time: Date | string | number): string {\n if (typeof time === 'string') return time;\n if (typeof time === 'number') return new Date(time).toISOString();\n return time.toISOString();\n}\n","/**\n * Span class — the core unit of tracing.\n *\n * A span represents a single operation (LLM call, tool use, agent step).\n * Spans are mutable: attributes, events, and status can be set after creation.\n * Call end() to finalize the span and trigger export.\n */\n\nimport { generateSpanId, generateTraceId } from './ids.js';\nimport {\n SpanKind,\n SpanStatus,\n type SpanEvent,\n type SpanLink,\n type SpanPayload,\n} from './types.js';\nimport { nowISO, hrtimeMs } from './utils/clock.js';\n\nexport interface SpanOptions {\n name: string;\n kind?: SpanKind;\n traceId?: string;\n spanId?: string;\n parentSpanId?: string;\n attributes?: Record<string, unknown>;\n links?: SpanLink[];\n sessionId?: string;\n agentId?: string;\n agentName?: string;\n agentType?: string;\n semanticPhase?: string;\n}\n\nexport type SpanEndCallback = (span: Span) => void;\n\nexport class Span {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId: string | undefined;\n readonly name: string;\n readonly kind: SpanKind;\n readonly startTime: string;\n readonly startHrtime: number;\n\n endTime: string | undefined;\n status: SpanStatus;\n statusMessage: string | undefined;\n attributes: Record<string, unknown>;\n events: SpanEvent[];\n links: SpanLink[];\n\n // Agent/session fields\n sessionId: string | undefined;\n agentId: string | undefined;\n agentName: string | undefined;\n agentType: string | undefined;\n semanticPhase: string | undefined;\n\n // LLM-specific fields\n llmProvider: string | undefined;\n llmModel: string | undefined;\n llmPromptTokens: number | undefined;\n llmCompletionTokens: number | undefined;\n llmTotalTokens: number | undefined;\n llmCostUsd: number | undefined;\n\n // Tool fields\n toolName: string | undefined;\n toolSuccess: boolean | undefined;\n\n private _ended = false;\n private _endHrtime: number | undefined;\n private _onEnd: SpanEndCallback | undefined;\n\n constructor(options: SpanOptions, onEnd?: SpanEndCallback) {\n this.traceId = options.traceId ?? generateTraceId();\n this.spanId = options.spanId ?? generateSpanId();\n this.parentSpanId = options.parentSpanId;\n this.name = options.name;\n this.kind = options.kind ?? SpanKind.INTERNAL;\n this.startTime = nowISO();\n this.startHrtime = hrtimeMs();\n\n this.status = SpanStatus.UNSET;\n this.attributes = options.attributes ? { ...options.attributes } : {};\n this.events = [];\n this.links = options.links ? [...options.links] : [];\n\n this.sessionId = options.sessionId;\n this.agentId = options.agentId;\n this.agentName = options.agentName;\n this.agentType = options.agentType;\n this.semanticPhase = options.semanticPhase;\n\n this._onEnd = onEnd;\n }\n\n get isEnded(): boolean {\n return this._ended;\n }\n\n get durationMs(): number {\n if (this._ended && this._endHrtime !== undefined) {\n return this._endHrtime - this.startHrtime;\n }\n return hrtimeMs() - this.startHrtime;\n }\n\n setAttribute(key: string, value: unknown): this {\n if (this._ended) return this;\n this.attributes[key] = value;\n return this;\n }\n\n setAttributes(attrs: Record<string, unknown>): this {\n if (this._ended) return this;\n Object.assign(this.attributes, attrs);\n return this;\n }\n\n setStatus(status: SpanStatus, message?: string): this {\n if (this._ended) return this;\n this.status = status;\n if (message !== undefined) {\n this.statusMessage = message;\n }\n return this;\n }\n\n addEvent(name: string, attributes?: Record<string, unknown>): this {\n if (this._ended) return this;\n this.events.push({\n name,\n timestamp: nowISO(),\n attributes,\n });\n return this;\n }\n\n addLink(traceId: string, spanId: string, attributes?: Record<string, unknown>): this {\n if (this._ended) return this;\n this.links.push({ traceId, spanId, attributes });\n return this;\n }\n\n recordException(error: Error | string): this {\n if (this._ended) return this;\n\n const message = typeof error === 'string' ? error : error.message;\n const stack = typeof error === 'string' ? undefined : error.stack;\n\n this.setStatus(SpanStatus.ERROR, message);\n this.addEvent('exception', {\n 'exception.type': typeof error === 'string' ? 'Error' : error.constructor.name,\n 'exception.message': message,\n ...(stack ? { 'exception.stacktrace': stack } : {}),\n });\n\n return this;\n }\n\n setLlmFields(fields: {\n provider?: string;\n model?: string;\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n costUsd?: number;\n }): this {\n if (this._ended) return this;\n if (fields.provider !== undefined) this.llmProvider = fields.provider;\n if (fields.model !== undefined) this.llmModel = fields.model;\n if (fields.promptTokens !== undefined) this.llmPromptTokens = fields.promptTokens;\n if (fields.completionTokens !== undefined) this.llmCompletionTokens = fields.completionTokens;\n if (fields.totalTokens !== undefined) this.llmTotalTokens = fields.totalTokens;\n if (fields.costUsd !== undefined) this.llmCostUsd = fields.costUsd;\n return this;\n }\n\n setToolFields(fields: { name?: string; success?: boolean }): this {\n if (this._ended) return this;\n if (fields.name !== undefined) this.toolName = fields.name;\n if (fields.success !== undefined) this.toolSuccess = fields.success;\n return this;\n }\n\n end(): void {\n if (this._ended) return;\n this._ended = true;\n this._endHrtime = hrtimeMs();\n this.endTime = nowISO();\n\n if (this.status === SpanStatus.UNSET) {\n this.status = SpanStatus.OK;\n }\n\n this._onEnd?.(this);\n }\n\n /**\n * Serialize to the wire format expected by the Rust gateway.\n */\n toPayload(): SpanPayload {\n const payload: SpanPayload = {\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: this.attributes,\n events: this.events,\n links: this.links,\n };\n\n if (this.parentSpanId !== undefined) payload.parentSpanId = this.parentSpanId;\n if (this.endTime !== undefined) payload.endTime = this.endTime;\n if (this._ended) payload.durationMs = this.durationMs;\n if (this.statusMessage !== undefined) payload.statusMessage = this.statusMessage;\n if (this.sessionId !== undefined) payload.sessionId = this.sessionId;\n if (this.agentId !== undefined) payload.agentId = this.agentId;\n if (this.agentName !== undefined) payload.agentName = this.agentName;\n if (this.agentType !== undefined) payload.agentType = this.agentType;\n if (this.semanticPhase !== undefined) payload.semanticPhase = this.semanticPhase;\n if (this.llmProvider !== undefined) payload.llmProvider = this.llmProvider;\n if (this.llmModel !== undefined) payload.llmModel = this.llmModel;\n if (this.llmPromptTokens !== undefined) payload.llmPromptTokens = this.llmPromptTokens;\n if (this.llmCompletionTokens !== undefined) payload.llmCompletionTokens = this.llmCompletionTokens;\n if (this.llmTotalTokens !== undefined) payload.llmTotalTokens = this.llmTotalTokens;\n if (this.llmCostUsd !== undefined) payload.llmCostUsd = this.llmCostUsd;\n if (this.toolName !== undefined) payload.toolName = this.toolName;\n if (this.toolSuccess !== undefined) payload.toolSuccess = this.toolSuccess;\n\n return payload;\n }\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 * Head-based deterministic sampling.\n *\n * Uses the first 8 hex characters of the trace ID as a hash\n * to make a deterministic sampling decision. This ensures:\n * - Same trace ID always produces the same decision\n * - Consistent across Python and JS/TS SDKs\n * - No external state needed\n */\n\n/**\n * Determine whether a trace should be sampled.\n *\n * @param traceId - 32-character hex trace ID\n * @param sampleRate - Rate between 0.0 (none) and 1.0 (all)\n * @returns true if the trace should be sampled\n */\nexport function shouldSample(traceId: string, sampleRate: number): boolean {\n if (sampleRate >= 1.0) return true;\n if (sampleRate <= 0.0) return false;\n\n // Parse first 8 hex chars as unsigned 32-bit integer\n const hash = parseInt(traceId.substring(0, 8), 16);\n return (hash / 0xFFFFFFFF) < sampleRate;\n}\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 endpoint URL (e.g., \"https://app.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// Verify: scripts/contracts/lint-taxonomy-parity.sh\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// 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/** Order matters: first match wins, most specific first. */\nexport const SUPPLEMENTAL_RULES: readonly TaxonomyRule[] = [\n { re: new RegExp(\"timeout|timedout|aborted\", 'i'), code: \"TOOL.EXECUTION.TIMEOUT\" },\n { re: new RegExp(\"rate.?limit|\\\\b429\\\\b|too many requests\", 'i'), code: \"TOOL.EXECUTION.RATE_LIMITED\" },\n { re: new RegExp(\"connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe\", 'i'), code: \"TOOL.EXECUTION.DEPENDENCY_FAILED\" },\n { re: new RegExp(\"\\\\bauth|unauthorized|forbidden|permission|\\\\b401\\\\b|\\\\b403\\\\b\", 'i'), code: \"TOOL.INVOCATION.PERMISSION_DENIED\" },\n { re: new RegExp(\"json|syntaxerror|unexpected token|decodeerror\", 'i'), code: \"PERCEPTION.PARSING.JSON_INVALID\" },\n];\n\nexport const GENERIC_FALLBACK = \"TOOL.EXECUTION.CRASHED\";\n","/**\n * Fix Interceptors — Hook into LLM/tool calls to apply fixes.\n *\n * Interceptors are registered with the runtime and called during agent\n * execution to apply relevant fixes at three interception points:\n * - preCall: Before the LLM/tool call (prompt/parameter/fallback fixes)\n * - postCall: After the call (output guard validation)\n * - onError: When an error occurs (retry/fallback decisions)\n *\n * Port of Python SDK's runtime/interceptors.py adapted for Node.js.\n */\n\nimport type { ApplyResult } from './applier.js';\nimport { FixApplier } from './applier.js';\nimport type { FixCache } from './cache.js';\nimport type { FixRuntimeConfig } from './config.js';\nimport { resolveFixRuntimeConfig } from './config.js';\nimport { debug, warn } from '../utils/log.js';\nimport {\n CANONICAL_ERROR_CODES,\n GENERIC_FALLBACK,\n SUPPLEMENTAL_RULES,\n} from './taxonomy.generated.js';\n\n// ─── Guard Rejection ────────────────────────────────────────────────────────\n\n/**\n * Thrown by the fix interceptor when a guard fix returns `passed: false`.\n *\n * PR-4+5 review B2 (2026-05-25): pre-fix, `applyGuardFix` returned\n * `passed:false` correctly but no caller read `passed` — the provider\n * patcher consumed `result.messages` / `result.params` and proceeded to the\n * LLM with the attacker payload anyway. The `fail-CLOSED` was advisory only.\n *\n * Now the interceptor THROWS this error on both pre-call and post-call\n * guard rejection. The provider patcher's surrounding span.startSpan\n * already catches and records exceptions, so the customer sees a\n * `GuardRejectedError` propagated out of their `openai.chat.completions.create`\n * call — the LLM is NEVER invoked.\n *\n * Customers who want to handle rejection gracefully can:\n * try { await openai.chat.completions.create({ ... }); }\n * catch (e) {\n * if (e instanceof GuardRejectedError) { ... fallback ... }\n * else throw e;\n * }\n */\nexport class GuardRejectedError extends Error {\n public readonly guardId: string;\n public readonly reason: string;\n public readonly phase: 'pre_call' | 'post_call';\n\n constructor(guardId: string, reason: string, phase: 'pre_call' | 'post_call') {\n super(`Risicare guard rejected operation: ${guardId} (${phase}) — ${reason}`);\n this.name = 'GuardRejectedError';\n this.guardId = guardId;\n this.reason = reason;\n this.phase = phase;\n }\n}\n\n// ─── Intercept Context ──────────────────────────────────────────────────────\n\nexport interface InterceptContext {\n /** Type of operation: \"llm_call\", \"tool_call\", \"agent_delegate\" */\n operationType: string;\n\n /** Name of the operation: model name, tool name, agent name */\n operationName: string;\n\n /** Session ID for A/B testing bucketing */\n sessionId?: string;\n\n /** Trace ID for correlation */\n traceId?: string;\n\n /** Error code (set when retrying after error) */\n errorCode?: string;\n\n /** Error message (set when retrying after error) */\n errorMessage?: string;\n\n /** Current attempt number (1-based) */\n attempt: number;\n\n /** Fixes applied during this intercept lifecycle */\n appliedFixes: ApplyResult[];\n}\n\n/** Create a fresh InterceptContext. */\nexport function createInterceptContext(\n operationType: string,\n operationName: string,\n options?: {\n sessionId?: string;\n traceId?: string;\n errorCode?: string;\n },\n): InterceptContext {\n return {\n operationType,\n operationName,\n sessionId: options?.sessionId,\n traceId: options?.traceId,\n errorCode: options?.errorCode,\n attempt: 1,\n appliedFixes: [],\n };\n}\n\n// ─── Interceptor Interface ──────────────────────────────────────────────────\n\nexport interface FixInterceptor {\n /**\n * Called before an LLM/tool call.\n * Returns modified messages and params.\n */\n preCall(\n ctx: InterceptContext,\n messages: unknown[] | null,\n params: Record<string, unknown>,\n ): { messages: unknown[] | null; params: Record<string, unknown> };\n\n /**\n * Called after an LLM/tool call.\n * Returns modified response and whether to continue.\n */\n postCall(\n ctx: InterceptContext,\n response: unknown,\n ): { response: unknown; shouldContinue: boolean };\n\n /**\n * Called when an error occurs.\n * Returns whether to retry and optional modified params.\n */\n onError(\n ctx: InterceptContext,\n error: Error,\n ): { shouldRetry: boolean; modifiedParams: Record<string, unknown> | null };\n}\n\n// ─── Default Fix Interceptor ────────────────────────────────────────────────\n\nexport class DefaultFixInterceptor implements FixInterceptor {\n private readonly _config: Required<FixRuntimeConfig>;\n private readonly _cache: FixCache;\n private readonly _applier: FixApplier;\n\n constructor(config: FixRuntimeConfig, cache: FixCache, applier: FixApplier) {\n this._config = resolveFixRuntimeConfig(config);\n this._cache = cache;\n this._applier = applier;\n }\n\n /**\n * Apply pre-call fixes.\n *\n * - If retrying after error: look up fix by error_code, apply\n * prompt/parameter/fallback fixes\n * - Runs input guard fixes on all message content\n */\n preCall(\n ctx: InterceptContext,\n messages: unknown[] | null,\n params: Record<string, unknown>,\n ): { messages: unknown[] | null; params: Record<string, unknown> } {\n try {\n if (!this._config.enabled) {\n return { messages, params };\n }\n\n let modifiedMessages = messages;\n let modifiedParams = { ...params };\n\n // If retrying after error, check for applicable fixes\n if (ctx.errorCode) {\n const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);\n\n if (fix) {\n debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);\n\n if (fix.fixType === 'prompt' && messages) {\n const msgRecords = messages as Record<string, unknown>[];\n const { messages: newMessages, result } =\n this._applier.applyPromptFix(fix, msgRecords);\n modifiedMessages = newMessages;\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n } else if (fix.fixType === 'parameter') {\n const { params: newParams, result } =\n this._applier.applyParameterFix(fix, modifiedParams);\n modifiedParams = newParams;\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n } else if (fix.fixType === 'fallback') {\n const { params: newParams, result } =\n this._applier.applyFallbackFix(fix, modifiedParams);\n modifiedParams = newParams;\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n }\n }\n }\n\n // Apply input guard fixes on all message content.\n // PR-4+5 review B2: when a guard returns passed:false (including the\n // F-731 fail-CLOSED-on-exception path), THROW a GuardRejectedError so\n // the provider patcher short-circuits BEFORE invoking the LLM. The\n // outer try/catch below explicitly re-raises GuardRejectedError so\n // the swallow-and-degrade behaviour for OTHER errors does NOT apply\n // to safety rejections.\n if (modifiedMessages && this._config.enabled) {\n for (const msg of modifiedMessages as Record<string, unknown>[]) {\n const content = msg.content;\n if (typeof content === 'string') {\n for (const fix of this._cache.getAll()) {\n if (fix.fixType === 'guard') {\n const { passed, result } = this._applier.applyGuardFix(\n fix,\n content,\n true,\n );\n if (result.applied) {\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n }\n if (!passed) {\n throw new GuardRejectedError(\n fix.fixId ?? 'unknown',\n result.reason ?? 'guard rejected input',\n 'pre_call',\n );\n }\n }\n }\n }\n }\n }\n\n return { messages: modifiedMessages, params: modifiedParams };\n } catch (e) {\n // PR-4+5 review B2: GuardRejectedError MUST propagate. The catch\n // below exists for unrelated failures (e.g., cache lookup explosion)\n // where degrading to the unmodified call is correct — but a safety\n // rejection MUST abort the LLM call, not silently let it through.\n if (e instanceof GuardRejectedError) throw e;\n debug(`DefaultFixInterceptor.preCall error: ${e}`);\n return { messages, params };\n }\n }\n\n /**\n * Apply post-call fixes (output validation).\n *\n * Runs output guard fixes on response content.\n */\n postCall(\n ctx: InterceptContext,\n response: unknown,\n ): { response: unknown; shouldContinue: boolean } {\n try {\n if (!this._config.enabled) {\n return { response, shouldContinue: true };\n }\n\n for (const fix of this._cache.getAll()) {\n if (fix.fixType !== 'guard') continue;\n\n const content = this._extractResponseContent(response);\n if (!content) continue;\n\n const { passed, result } = this._applier.applyGuardFix(\n fix,\n content,\n false,\n );\n\n if (result.applied) {\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n }\n\n if (!passed) {\n // PR-4+5 review B2: output guard failure must NOT be a warn-only\n // signal. Pre-fix the caller received the unredacted LLM response\n // alongside shouldContinue:true — the rejection was advisory only.\n // Now we throw GuardRejectedError so the caller surfaces the\n // safety violation to the customer instead of returning a payload\n // an output filter said is unsafe to emit.\n warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? 'unknown'}`);\n throw new GuardRejectedError(\n fix.fixId ?? 'unknown',\n result.reason ?? 'guard rejected output',\n 'post_call',\n );\n }\n }\n\n return { response, shouldContinue: true };\n } catch (e) {\n // PR-4+5 review B2: GuardRejectedError MUST propagate (see preCall).\n if (e instanceof GuardRejectedError) throw e;\n debug(`DefaultFixInterceptor.postCall error: ${e}`);\n return { response, shouldContinue: true };\n }\n }\n\n /**\n * Handle errors and decide whether to retry.\n *\n * Classifies the error, looks up retry/fallback fixes, and returns\n * whether the caller should retry.\n */\n onError(\n ctx: InterceptContext,\n error: Error,\n ): { shouldRetry: boolean; modifiedParams: Record<string, unknown> | null } {\n try {\n if (!this._config.enabled) {\n return { shouldRetry: false, modifiedParams: null };\n }\n\n // Classify the error\n const errorCode = classifyError(error);\n ctx.errorCode = errorCode;\n ctx.errorMessage = error.message;\n\n // Check for retry fix\n const fix = this._applier.getFixForError(errorCode, ctx.sessionId);\n if (!fix) {\n return { shouldRetry: false, modifiedParams: null };\n }\n\n if (fix.fixType === 'retry') {\n const maxRetries = (fix.config.max_retries ?? fix.config.maxRetries ?? 3) as number;\n\n if (ctx.attempt <= maxRetries) {\n debug(\n `Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`,\n );\n\n const result: ApplyResult = {\n applied: true,\n fixId: fix.fixId,\n deploymentId: fix.deploymentId,\n fixType: 'retry',\n modifications: { attempt: ctx.attempt },\n };\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n\n return { shouldRetry: true, modifiedParams: null };\n }\n }\n\n // Check for fallback fix\n if (fix.fixType === 'fallback') {\n const { params: modifiedParams, result } =\n this._applier.applyFallbackFix(fix, {});\n if (result.applied) {\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n return { shouldRetry: true, modifiedParams };\n }\n }\n\n return { shouldRetry: false, modifiedParams: null };\n } catch (e) {\n debug(`DefaultFixInterceptor.onError error: ${e}`);\n return { shouldRetry: false, modifiedParams: null };\n }\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n /** Extract text content from a response object. */\n private _extractResponseContent(response: unknown): string | null {\n if (typeof response === 'string') return response;\n\n if (response && typeof response === 'object') {\n const resp = response as Record<string, unknown>;\n\n // OpenAI-style response: { choices: [{ message: { content: \"...\" } }] }\n const choices = resp.choices as unknown[];\n if (Array.isArray(choices) && choices.length > 0) {\n const first = choices[0] as Record<string, unknown>;\n const message = first?.message as Record<string, unknown>;\n if (typeof message?.content === 'string') {\n return message.content;\n }\n }\n\n // Anthropic-style response: { content: [{ text: \"...\" }] }\n const content = resp.content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content) && content.length > 0) {\n const first = content[0] as Record<string, unknown>;\n if (typeof first?.text === 'string') return first.text;\n }\n }\n\n return null;\n }\n}\n\n// ─── Error Classification ───────────────────────────────────────────────────\n\n/**\n * Classify an error into an error code.\n *\n * Simple heuristic classification. In production, this would use the full\n * taxonomy from risicare-core (10 modules, 35+ categories).\n */\nexport function classifyError(error: Error): string {\n // F-SDKTAXFORK-001 — this used to be a private six-code vocabulary of which\n // exactly ONE code existed in the canonical 154-code taxonomy (measured\n // 2026-08-17: RATE_LIMIT vs canonical RATE_LIMITED, JSON_INVALID vs\n // INVALID_JSON, and three with no canonical sibling at all). The Python SDK\n // carried a byte-identical fork of the same wrong set.\n //\n // The rules and the canonical code set now come from ONE source\n // (packages/risicare-sdk/src/risicare/runtime/_error_taxonomy.py) and are\n // GENERATED into ./taxonomy.generated.ts, because `risicare-core` is not on\n // npm and this SDK cannot import the taxonomy directly. Drift is caught by\n // scripts/contracts/lint-taxonomy-parity.sh.\n //\n // Every code below is checked against CANONICAL_ERROR_CODES before it is\n // returned, so an invented code cannot reach the wire even if this file and\n // the generator ever disagree.\n const haystack = `${error?.constructor?.name ?? 'Error'} ${error?.message ?? ''}`;\n\n for (const rule of SUPPLEMENTAL_RULES) {\n // RegExp objects carry lastIndex state only with /g; these are built\n // without it, so .test() is safe to reuse across calls.\n if (rule.re.test(haystack)) {\n return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;\n }\n }\n\n return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : '';\n}\n","/**\n * AsyncLocalStorage-based context propagation.\n *\n * Uses a single AsyncLocalStorage instance with a composite state object.\n * This is simpler and more performant than multiple separate stores.\n *\n * Node.js AsyncLocalStorage automatically propagates through:\n * - Promise / async-await\n * - setTimeout / setImmediate\n * - EventEmitter callbacks\n * - process.nextTick\n * - async generators (unlike Python's contextvars!)\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Span } from '../span.js';\nimport type { SemanticPhase } from '../types.js';\nimport { getContextStorage } from '../globals.js';\n\n// ─── Context Types ───────────────────────────────────────────────────────────\n\nexport interface SessionContext {\n sessionId: string;\n userId?: string;\n metadata?: Record<string, unknown>;\n parentSessionId?: string;\n turnNumber?: number;\n}\n\nexport interface AgentContext {\n agentId: string;\n agentName?: string;\n agentRole?: string;\n agentType?: string;\n parentAgentId?: string;\n version?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface ContextState {\n session?: SessionContext;\n agent?: AgentContext;\n span?: Span;\n phase?: SemanticPhase;\n /** When true, provider instrumentors skip span creation (framework is handling it). */\n _suppressProviderInstrumentation?: boolean;\n /**\n * Pre-allocated trace ID from getTraceContext() when no span exists yet.\n * Ensures that getTraceContext().traceId matches the next span created\n * in this context — preventing the \"trace ID mismatch\" bug.\n */\n _rootTraceId?: string;\n /**\n * F-SDKSAMPORPHAN-001 — the trace's head-sampling decision, recorded ONLY\n * when it was `false`.\n *\n * A dropped root creates no Span, so `span` above stays undefined and every\n * nested call looks like a fresh root to the tracer. Without this flag it\n * re-rolls its own decision and the half that passes is delivered as a\n * root — a trace that never existed. This is the only carrier of \"you are\n * inside a trace we already decided to drop\".\n *\n * Scoped by runWithContext(), so unlike Python's ContextVar token it cannot\n * leak past the callback that set it.\n */\n _traceSampled?: boolean;\n}\n\n// ─── Storage Accessor ────────────────────────────────────────────────────────\n\nfunction storage(): AsyncLocalStorage<ContextState> {\n return getContextStorage() as AsyncLocalStorage<ContextState>;\n}\n\n// ─── Core Operations ─────────────────────────────────────────────────────────\n\n/**\n * Get the current context state, or empty object if outside any context.\n */\nexport function getContext(): ContextState {\n return storage().getStore() ?? {};\n}\n\n/**\n * Run a callback within a new context scope.\n * The new scope inherits from the parent, with overrides applied.\n */\nexport function runWithContext<T>(overrides: Partial<ContextState>, fn: () => T): T {\n const parent = getContext();\n const merged: ContextState = { ...parent, ...overrides };\n return storage().run(merged, fn);\n}\n\n/**\n * Run an async callback within a new context scope.\n */\nexport function runWithContextAsync<T>(overrides: Partial<ContextState>, fn: () => Promise<T>): Promise<T> {\n const parent = getContext();\n const merged: ContextState = { ...parent, ...overrides };\n return storage().run(merged, fn);\n}\n\n// ─── Context Accessors ───────────────────────────────────────────────────────\n\nexport function getCurrentSession(): SessionContext | undefined {\n return getContext().session;\n}\n\nexport function getCurrentAgent(): AgentContext | undefined {\n return getContext().agent;\n}\n\nexport function getCurrentSpan(): Span | undefined {\n return getContext().span;\n}\n\nexport function getCurrentPhase(): SemanticPhase | undefined {\n return getContext().phase;\n}\n\nexport function getCurrentSessionId(): string | undefined {\n return getContext().session?.sessionId;\n}\n\nexport function getCurrentAgentId(): string | undefined {\n return getContext().agent?.agentId;\n}\n\nexport function getCurrentTraceId(): string | undefined {\n return getContext().span?.traceId;\n}\n\nexport function getCurrentSpanId(): string | undefined {\n return getContext().span?.spanId;\n}\n\nexport function getCurrentParentSpanId(): string | undefined {\n return getContext().span?.parentSpanId;\n}\n\n/**\n * Get all current context as a plain object (for debugging/serialization).\n */\nexport function getCurrentContext(): Record<string, unknown> {\n const ctx = getContext();\n return {\n session: ctx.session ? {\n sessionId: ctx.session.sessionId,\n userId: ctx.session.userId,\n ...(ctx.session.parentSessionId !== undefined ? { parentSessionId: ctx.session.parentSessionId } : {}),\n ...(ctx.session.turnNumber !== undefined ? { turnNumber: ctx.session.turnNumber } : {}),\n ...(ctx.session.metadata !== undefined ? { metadata: ctx.session.metadata } : {}),\n } : null,\n agent: ctx.agent ? {\n agentId: ctx.agent.agentId,\n agentName: ctx.agent.agentName,\n agentRole: ctx.agent.agentRole,\n agentType: ctx.agent.agentType,\n ...(ctx.agent.parentAgentId !== undefined ? { parentAgentId: ctx.agent.parentAgentId } : {}),\n ...(ctx.agent.version !== undefined ? { version: ctx.agent.version } : {}),\n ...(ctx.agent.metadata !== undefined ? { metadata: ctx.agent.metadata } : {}),\n } : null,\n span: ctx.span ? { spanId: ctx.span.spanId, traceId: ctx.span.traceId } : null,\n phase: ctx.phase ?? null,\n };\n}\n","/**\n * Tracer — creates spans with automatic context nesting.\n *\n * The Tracer is the primary API for creating spans. It automatically:\n * - Links child spans to parent spans via parentSpanId\n * - Propagates the trace ID from the active context\n * - Injects session/agent/phase context into new spans\n * - Runs the callback within the span's context scope\n *\n * Usage:\n * const tracer = new Tracer(processor);\n * await tracer.startSpan('my-operation', async (span) => {\n * span.setAttribute('key', 'value');\n * // Nested spans automatically become children\n * await tracer.startSpan('sub-op', async (child) => { ... });\n * });\n */\n\nimport { Span, type SpanOptions, type SpanEndCallback } from './span.js';\nimport { NOOP_SPAN } from './noop.js';\nimport { SpanKind } from './types.js';\nimport { generateTraceId } from './ids.js';\nimport { shouldSample } from './utils/sampling.js';\nimport { classifyError } from './runtime/interceptors.js';\nimport {\n runWithContext,\n getContext,\n getCurrentSpan,\n getCurrentSession,\n getCurrentAgent,\n getCurrentPhase,\n} from './context/storage.js';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport interface StartSpanOptions {\n name: string;\n kind?: SpanKind;\n attributes?: Record<string, unknown>;\n /** Override trace ID (default: inherit from parent or generate new) */\n traceId?: string;\n /** Override parent span ID (default: current span in context) */\n parentSpanId?: string;\n}\n\nexport interface TracerConfig {\n /** Called when a span ends (typically feeds into batch processor) */\n onSpanEnd: SpanEndCallback;\n /** Sample rate 0.0–1.0 (default: 1.0) */\n sampleRate?: number;\n /** Whether tracing is enabled */\n enabled?: boolean;\n /**\n * Whether prompt/completion content may leave the process (default: false).\n *\n * ⚠ The Tracer only CARRIES this for the provider patches to read via\n * `getTraceContent()`. It is NOT the enforcement point — the gate runs in the\n * batch processor, which is the one place both content paths cross. See\n * `masking.ts` `stripContent`.\n */\n traceContent?: boolean;\n /**\n * Service name, emitted as the OTel `service.name` span attribute.\n *\n * ⚠ F-SDKJSSVCNAME-001. `serviceName` was accepted by `init()`, typed in\n * `RisicareConfig`, documented, and recommended over the deprecated\n * `projectId` — and reached the wire NOWHERE. Measured on the published\n * 0.5.0: `serviceName: 'X'` at init, `X` absent from every request body,\n * while a sibling control attribute in the same span arrived. Python has\n * always emitted it (`tracer.py`, `service.name`); this makes JS match.\n */\n serviceName?: string;\n /**\n * Service version, emitted as `service.version`.\n *\n * ⚠ Was dropped by BOTH SDKs — same defect one field over, measured in the\n * same run. Unlike `service.name` it is NOT suppressed under an agent: a\n * version is a property of the deployed code, not of which agent owns the\n * span.\n */\n serviceVersion?: string;\n}\n\n/**\n * F-SDKTAXFORK-001 — attach the canonical taxonomy code to EVERY errored span,\n * whether or not a fix was applied.\n *\n * ⚠ The \"whether or not\" clause is the load-bearing one.\n * `risicare.fix.error_code` is written only inside the branch that also sets\n * `risicare.fix.applied` (providers/openai/patch.ts), so a span carrying an\n * error code has ALWAYS had a non-empty fix_applied — which makes the A/B\n * CONTROL predicate `fix_applied = '' AND error_code = X` unsatisfiable by\n * algebra, not merely empty. Emitting here is what makes that cohort populable.\n *\n * The worker already reads this key and has since before any producer existed\n * (`spans_worker.py:3744` — `risicare.fix.error_code` OR `error.code`; its own\n * comment calls it \"generic taxonomy code attached by any error\"). This is\n * attribute-first per .claude/rules/schema-contract.md: no gateway or worker\n * change is required.\n *\n * Guarded throughout: classification must never replace the customer's own\n * exception with ours, and must never write an empty attribute.\n */\nfunction attachErrorCode(span: Span, error: unknown): void {\n try {\n const err = error instanceof Error ? error : new Error(String(error));\n const code = classifyError(err);\n if (code) {\n span.setAttribute('error.code', code);\n }\n } catch {\n /* never let attribution break the customer's error path */\n }\n}\n\n// ─── Tracer Class ───────────────────────────────────────────────────────────\n\nexport class Tracer {\n private _onSpanEnd: SpanEndCallback;\n private _sampleRate: number;\n private _enabled: boolean;\n private _traceContent: boolean;\n private _serviceName: string | undefined;\n private _serviceVersion: string | undefined;\n\n constructor(config: TracerConfig) {\n this._onSpanEnd = config.onSpanEnd;\n this._sampleRate = config.sampleRate ?? 1.0;\n this._enabled = config.enabled ?? true;\n this._traceContent = config.traceContent ?? false;\n // Empty string is what `resolveConfig` uses for \"unset\" — treat it as unset\n // rather than emitting `service.name: \"\"`, which is worse than absent.\n this._serviceName = config.serviceName || undefined;\n this._serviceVersion = config.serviceVersion || undefined;\n }\n\n get enabled(): boolean {\n return this._enabled;\n }\n\n set enabled(value: boolean) {\n this._enabled = value;\n }\n\n get traceContent(): boolean {\n return this._traceContent;\n }\n\n /**\n * Start a span, run the callback within its context, and auto-end on completion.\n *\n * The span is automatically:\n * - Linked to the current parent span (if any)\n * - Given the current trace ID (or a new one for root spans)\n * - Enriched with session/agent/phase context\n * - Ended when the callback returns (or throws)\n * - Marked as ERROR if the callback throws\n *\n * @returns The callback's return value\n */\n startSpan<T>(options: StartSpanOptions | string, fn: (span: Span) => T): T {\n const opts = typeof options === 'string' ? { name: options } : options;\n\n // Fast path: disabled SDK\n if (!this._enabled) {\n return fn(NOOP_SPAN as unknown as Span);\n }\n\n // Resolve context\n const parentSpan = getCurrentSpan();\n const session = getCurrentSession();\n const agent = getCurrentAgent();\n const phase = getCurrentPhase();\n\n // Determine trace ID: explicit > parent > pre-allocated (from getTraceContext) > new\n const ctx = getContext();\n const traceId = opts.traceId ?? parentSpan?.traceId ?? ctx._rootTraceId ?? generateTraceId();\n\n // Sampling: check once per trace (root span decides)\n //\n // F-SDKSAMPORPHAN-001 — CONSULT BEFORE ROLLING. A dropped root creates no\n // Span, so `getCurrentSpan()` stays undefined and every nested call\n // arrives here as though it were itself a root. Re-rolling there does not\n // subsample; it FABRICATES. Measured pre-fix from an installed 0.5.1\n // tarball, N=400 roots each wrapping one nested startSpan, sampleRate=0.5:\n // ESM 104 of 303 delivered traces (34.3%) and CJS 94 of 310 (30.3%)\n // contained no root span — they never existed as traces. Both arms at\n // sampleRate=1.0 fabricated 0 of 400.\n // ⚠ Downstream cannot repair this: the delivered count is N*r*(2-r), not\n // N*r, so scaling by 1/r overstates by 50% at r=0.5 and 90% at r=0.1.\n if (!parentSpan) {\n if (ctx._traceSampled === false) {\n return fn(NOOP_SPAN as unknown as Span);\n }\n if (this._sampleRate < 1.0 && !shouldSample(traceId, this._sampleRate)) {\n // Record the drop for the duration of the callback so nested calls\n // inherit it. runWithContext scopes the flag to exactly this callback,\n // so it cannot latch the way an un-reset ContextVar token can.\n return runWithContext({ _traceSampled: false }, () =>\n fn(NOOP_SPAN as unknown as Span),\n );\n }\n }\n\n // Parent span ID: explicit > current span in context\n const parentSpanId = opts.parentSpanId ?? parentSpan?.spanId;\n\n // Create the span\n const spanOptions: SpanOptions = {\n name: opts.name,\n kind: opts.kind ?? SpanKind.INTERNAL,\n traceId,\n parentSpanId,\n attributes: {\n ...opts.attributes,\n // Propagate context fields as attributes (matching Python SDK tracer.py:497-511)\n ...(agent?.agentRole ? { 'agent.role': agent.agentRole } : {}),\n ...(agent?.parentAgentId ? { 'parent_agent_id': agent.parentAgentId } : {}),\n ...(session?.userId ? { 'session.user_id': session.userId } : {}),\n // F-SDKJSSVCNAME-001 — `service.name` is suppressed when an agent\n // identity is present (the agent takes priority), matching Python;\n // `service.version` never is.\n ...(this._serviceName && !agent ? { 'service.name': this._serviceName } : {}),\n ...(this._serviceVersion ? { 'service.version': this._serviceVersion } : {}),\n },\n sessionId: session?.sessionId,\n agentId: agent?.agentId,\n agentName: agent?.agentName,\n agentType: agent?.agentType,\n semanticPhase: phase,\n };\n\n const span = new Span(spanOptions, this._onSpanEnd);\n\n // Run callback within span context\n try {\n const result = runWithContext({ span }, () => fn(span));\n\n // Handle async results (Promises)\n if (result instanceof Promise) {\n return result.then(\n (value) => {\n span.end();\n return value;\n },\n (error) => {\n span.recordException(error instanceof Error ? error : String(error));\n attachErrorCode(span, error);\n span.end();\n throw error;\n },\n ) as T;\n }\n\n // Sync: end span immediately\n span.end();\n return result;\n } catch (error) {\n // Sync error: record and re-throw\n span.recordException(error instanceof Error ? error : String(error));\n attachErrorCode(span, error);\n span.end();\n throw error;\n }\n }\n\n /**\n * Create a span without auto-ending. Caller is responsible for calling span.end().\n *\n * Useful for long-running operations where you need manual control.\n * The span is still linked to context and enriched with session/agent/phase.\n */\n createSpan(options: StartSpanOptions | string): Span {\n const opts = typeof options === 'string' ? { name: options } : options;\n\n if (!this._enabled) {\n return NOOP_SPAN as unknown as Span;\n }\n\n const parentSpan = getCurrentSpan();\n const session = getCurrentSession();\n const agent = getCurrentAgent();\n const phase = getCurrentPhase();\n\n const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();\n\n // F-SDKSAMPORPHAN-001 — see the sibling site in startSpan(). Measured\n // pre-fix on this path (createSpan nested inside a startSpan root, the\n // streaming pattern), N=400, sampleRate=0.5: ESM 111 of 296 fabricated\n // (37.5%), CJS 105 of 294 (35.7%); both 0 of 400 at sampleRate=1.0.\n // ⚠ This site CONSULTS but does not RECORD: createSpan hands the span's\n // lifetime to the caller and owns no callback scope to unwind in, so\n // recording here would latch `_traceSampled` for the rest of the enclosing\n // context. Documented bound: a createSpan root that is itself dropped does\n // not suppress a re-roll by a following createSpan.\n if (!parentSpan) {\n if (getContext()._traceSampled === false) {\n return NOOP_SPAN as unknown as Span;\n }\n if (this._sampleRate < 1.0 && !shouldSample(traceId, this._sampleRate)) {\n return NOOP_SPAN as unknown as Span;\n }\n }\n\n const parentSpanId = opts.parentSpanId ?? parentSpan?.spanId;\n\n return new Span(\n {\n name: opts.name,\n kind: opts.kind ?? SpanKind.INTERNAL,\n traceId,\n parentSpanId,\n attributes: {\n ...opts.attributes,\n // Propagate context fields as attributes (matching Python SDK tracer.py:497-511)\n ...(agent?.agentRole ? { 'agent.role': agent.agentRole } : {}),\n ...(agent?.parentAgentId ? { 'parent_agent_id': agent.parentAgentId } : {}),\n ...(session?.userId ? { 'session.user_id': session.userId } : {}),\n // F-SDKJSSVCNAME-001 — see the sibling site above.\n ...(this._serviceName && !agent ? { 'service.name': this._serviceName } : {}),\n ...(this._serviceVersion ? { 'service.version': this._serviceVersion } : {}),\n },\n sessionId: session?.sessionId,\n agentId: agent?.agentId,\n agentName: agent?.agentName,\n agentType: agent?.agentType,\n semanticPhase: phase,\n },\n this._onSpanEnd,\n );\n }\n}\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.5.2';\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 * - Gzip compression for large payloads\n * - Bearer token authentication\n */\n\nimport type { Span } from '../span.js';\nimport type { IngestRequest } from '../types.js';\nimport { ExportResult, type SpanExporter } from './base.js';\nimport { debug, warn } from '../utils/log.js';\nimport { SDK_VERSION } from '../version.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\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 /**\n * F-SDK503-001. Set by `_sendRequest` when a response is a CAPACITY REFUSAL, read by the\n * retry loop and the breaker. `null` = not a refusal; `REFUSAL_NO_HINT` = refused with no\n * `Retry-After`; otherwise the honoured delay in ms.\n *\n * ⚠ Node has ONE thread and `export()` is `async`, so two concurrent exports interleave on\n * this field at every `await`. It is written immediately after the awaited `fetch` resolves\n * and read on the very next statement, with no `await` between — so the value cannot be\n * clobbered mid-decision. The Python twin carries the same per-call state on `self` for the\n * same reason (its `_send_request` signature is pin-locked).\n */\n private _lastRefusalAfterMs: number | null = null;\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 }\n\n async export(spans: Span[]): Promise<ExportResult> {\n if (spans.length === 0) return ExportResult.SUCCESS;\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 const body: IngestRequest = {\n spans: spans.map((s) => s.toPayload()),\n };\n if (this._projectId) body.projectId = this._projectId;\n if (this._environment) body.environment = this._environment;\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 this._lastRefusalAfterMs = null;\n const result = await this._sendRequest(body);\n\n if (result === ExportResult.SUCCESS) {\n this._consecutiveFailures = 0;\n return result;\n }\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 = this._lastRefusalAfterMs;\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);\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 const refusedForCapacity = this._lastRefusalAfterMs !== null;\n this._lastRefusalAfterMs = null;\n if (refusedForCapacity) {\n warn(\n `Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ` +\n `${maxAttempts} attempt(s). This is a healthy server shedding load, not an outage — ` +\n `the batch is dropped but the exporter keeps sending. Reduce batch size or export ` +\n `rate if it persists.`\n );\n return ExportResult.FAILURE;\n }\n\n // All retries failed — update circuit breaker\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 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(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 this._lastRefusalAfterMs = delay;\n debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);\n return true;\n }\n\n private async _sendRequest(body: IngestRequest): Promise<ExportResult> {\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 };\n if (this._apiKey) {\n headers['Authorization'] = `Bearer ${this._apiKey}`;\n }\n\n let payload: string | Uint8Array = JSON.stringify(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: ${e}`);\n }\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this._timeoutMs);\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: payload,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.status < 300) {\n return await checkAck(response);\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(response.status, response.headers.get('Retry-After'));\n debug(`HTTP export failed: ${response.status}`);\n return ExportResult.FAILURE;\n } catch (e) {\n debug(`HTTP export error: ${e}`);\n return ExportResult.FAILURE;\n }\n }\n\n shutdown(): void {\n // Native fetch doesn't need cleanup\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\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 <300 response, reading the ACK body.\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 * ⚠ FAIL SAFE, AND THAT IS THE WHOLE DESIGN CONSTRAINT. A body we cannot parse,\n * a body from something that is not our gateway, a field that is missing or not\n * an integer — every one returns SUCCESS, exactly as before. We only turn a 2xx\n * into a FAILURE on an AFFIRMATIVE, well-formed statement that nothing was\n * accepted. Anything less and a proxy that rewrites bodies, or a future gateway\n * that adds a field, becomes an outage.\n *\n * A PARTIAL rejection is deliberately NOT a failure: retrying the whole batch\n * would duplicate the accepted spans, and span-level rejects are permanent.\n * It is surfaced as a warning instead — the signal that was missing.\n *\n * Python twin: `exporters/http.py::_check_ack`. Same rule, same thresholds.\n */\nasync function checkAck(response: Response): Promise<ExportResult> {\n let payload: unknown;\n try {\n payload = await response.json();\n } catch {\n return ExportResult.SUCCESS; // not JSON, or not ours — unchanged behaviour\n }\n if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {\n return ExportResult.SUCCESS;\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 || rejected <= 0) {\n return ExportResult.SUCCESS;\n }\n\n const errors = body.errors;\n const detail =\n (typeof body.errorMessage === 'string' && body.errorMessage) ||\n (typeof body.error_message === 'string' && body.error_message) ||\n (Array.isArray(errors) && errors.length > 0 ? JSON.stringify(errors[0]) : '') ||\n 'No reason was returned.';\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. ${detail}`,\n );\n return ExportResult.FAILURE;\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. ${detail}`,\n );\n return ExportResult.SUCCESS;\n}\n","/**\n * Console exporter for debugging.\n *\n * Prints span data to stderr in a readable format.\n */\n\nimport type { Span } from '../span.js';\nimport { ExportResult, type SpanExporter } from './base.js';\n\nexport class ConsoleExporter implements SpanExporter {\n readonly name = 'console';\n\n export(spans: Span[]): ExportResult {\n for (const span of spans) {\n const payload = span.toPayload();\n const line = JSON.stringify(payload);\n process.stderr.write(`[risicare] ${line}\\n`);\n }\n return ExportResult.SUCCESS;\n }\n\n shutdown(): void {\n // Nothing to clean up\n }\n}\n","/**\n * Fix Cache — Local cache for active fixes with TTL eviction.\n *\n * Provides fast lookup of fixes keyed by error code with exact match\n * and wildcard fallback. No locks needed — JS is single-threaded.\n *\n * Port of Python SDK's runtime/cache.py.\n */\n\nimport type { ActiveFix, FixRuntimeConfig } from './config.js';\nimport { matchesError } from './config.js';\nimport { debug } from '../utils/log.js';\n\n// ─── Cache Entry ────────────────────────────────────────────────────────────\n\ninterface CacheEntry {\n fix: ActiveFix;\n createdAt: number;\n expiresAt: number;\n}\n\n// ─── Cache Stats ────────────────────────────────────────────────────────────\n\nexport interface CacheStats {\n hits: number;\n misses: number;\n evictions: number;\n size: number;\n lastRefresh: number | null;\n}\n\n// ─── Fix Cache ──────────────────────────────────────────────────────────────\n\nexport class FixCache {\n private readonly _ttlMs: number;\n private readonly _maxEntries: number;\n private readonly _enabled: boolean;\n private _cache: Map<string, CacheEntry>;\n private _stats: CacheStats;\n\n constructor(config?: Pick<FixRuntimeConfig, 'cacheEnabled' | 'cacheTtlMs' | 'cacheMaxEntries'>) {\n this._enabled = config?.cacheEnabled ?? true;\n this._ttlMs = config?.cacheTtlMs ?? 300_000;\n this._maxEntries = config?.cacheMaxEntries ?? 1000;\n this._cache = new Map();\n this._stats = {\n hits: 0,\n misses: 0,\n evictions: 0,\n size: 0,\n lastRefresh: null,\n };\n }\n\n /** Whether caching is enabled. */\n get enabled(): boolean {\n return this._enabled;\n }\n\n /**\n * Get a fix by error code.\n *\n * Checks exact match first, then scans for wildcard matches.\n * Expired entries are evicted on access.\n */\n get(errorCode: string): ActiveFix | null {\n try {\n if (!this._enabled) return null;\n\n const now = Date.now();\n\n // Try exact match first (fast path)\n const exactEntry = this._cache.get(errorCode);\n if (exactEntry) {\n if (exactEntry.expiresAt > now) {\n this._stats.hits++;\n return exactEntry.fix;\n }\n // Expired — evict\n this._cache.delete(errorCode);\n this._stats.evictions++;\n }\n\n // Wildcard scan (slower path)\n for (const [key, entry] of this._cache) {\n if (entry.expiresAt <= now) {\n this._cache.delete(key);\n this._stats.evictions++;\n continue;\n }\n\n if (matchesError(entry.fix, errorCode)) {\n this._stats.hits++;\n return entry.fix;\n }\n }\n\n this._stats.misses++;\n return null;\n } catch (e) {\n debug(`FixCache.get error: ${e}`);\n return null;\n }\n }\n\n /**\n * Add a single fix to the cache.\n *\n * Evicts the oldest entry if at capacity.\n */\n set(fix: ActiveFix): void {\n try {\n if (!this._enabled) return;\n\n // Evict oldest if at capacity\n if (this._cache.size >= this._maxEntries) {\n this._evictOldest();\n }\n\n const now = Date.now();\n this._cache.set(fix.errorCode, {\n fix,\n createdAt: now,\n expiresAt: now + this._ttlMs,\n });\n this._stats.size = this._cache.size;\n } catch (e) {\n debug(`FixCache.set error: ${e}`);\n }\n }\n\n /**\n * Replace all cached fixes (bulk refresh).\n *\n * Clears the cache and populates with the given fixes.\n */\n setAll(fixes: ActiveFix[]): void {\n try {\n if (!this._enabled) return;\n\n this._cache.clear();\n const now = Date.now();\n\n for (const fix of fixes) {\n if (this._cache.size >= this._maxEntries) break;\n\n this._cache.set(fix.errorCode, {\n fix,\n createdAt: now,\n expiresAt: now + this._ttlMs,\n });\n }\n\n this._stats.size = this._cache.size;\n this._stats.lastRefresh = now;\n } catch (e) {\n debug(`FixCache.setAll error: ${e}`);\n }\n }\n\n /**\n * Get all non-expired fixes.\n */\n getAll(): ActiveFix[] {\n try {\n const now = Date.now();\n const valid: ActiveFix[] = [];\n const expired: string[] = [];\n\n for (const [key, entry] of this._cache) {\n if (entry.expiresAt > now) {\n valid.push(entry.fix);\n } else {\n expired.push(key);\n }\n }\n\n // Clean up expired entries\n for (const key of expired) {\n this._cache.delete(key);\n this._stats.evictions++;\n }\n\n this._stats.size = this._cache.size;\n return valid;\n } catch (e) {\n debug(`FixCache.getAll error: ${e}`);\n return [];\n }\n }\n\n /** Clear all cache entries. Returns the number of entries cleared. */\n clear(): number {\n const count = this._cache.size;\n this._cache.clear();\n this._stats.size = 0;\n return count;\n }\n\n /** Get cache statistics. */\n get stats(): CacheStats {\n this._stats.size = this._cache.size;\n return { ...this._stats };\n }\n\n /** Evict the oldest cache entry. */\n private _evictOldest(): void {\n if (this._cache.size === 0) return;\n\n let oldestKey: string | null = null;\n let oldestTime = Infinity;\n\n for (const [key, entry] of this._cache) {\n if (entry.createdAt < oldestTime) {\n oldestTime = entry.createdAt;\n oldestKey = key;\n }\n }\n\n if (oldestKey !== null) {\n this._cache.delete(oldestKey);\n this._stats.evictions++;\n }\n }\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// ─── 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 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 const blockedPatterns = (guardConfig.blocked_patterns ?? guardConfig.blockedPatterns ?? []) as string[];\n for (const pattern of blockedPatterns) {\n const regex = this._safeCompileRegex(pattern);\n if (regex && regex.test(content)) {\n passed = false;\n reason = `blocked pattern matched: ${pattern.slice(0, 80)}`;\n break;\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 private _safeCompileRegex(\n pattern: string,\n maxLength = 500,\n ): RegExp | null {\n if (!pattern || pattern.length > maxLength) return null;\n try {\n return new RegExp(pattern, 'i');\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 { 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\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 /** 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)\n this.loadSync().catch((e) => {\n debug(`Initial fix load failed: ${e}`);\n });\n\n // Start background refresh\n if (this._config.autoRefresh) {\n this._startRefreshInterval();\n }\n } catch (e) {\n debug(`FixLoader.start error: ${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: ${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 try {\n // Build URL: /api/v1/ routes to FastAPI via Caddy (NOT /v1/ which is the Rust gateway)\n const endpoint = this._config.apiEndpoint.replace(/\\/+$/, '');\n const url = `${endpoint}/api/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 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: ${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: ${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}): ${error.message}`,\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: ${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 * Fix Runtime — Main orchestrator for the fix application system.\n *\n * Manages:\n * - Loading active fixes from the API (via FixLoader)\n * - Caching fixes locally (via FixCache)\n * - Applying fixes via interceptors (via DefaultFixInterceptor)\n * - Tracking fix effectiveness\n *\n * Singleton management via globalThis (same pattern as the tracer).\n *\n * Port of Python SDK's runtime/runtime.py adapted for Node.js.\n */\n\nimport { FixCache } from './cache.js';\nimport type { ActiveFix, FixRuntimeConfig } from './config.js';\nimport { resolveFixRuntimeConfig } from './config.js';\nimport { FixApplier } from './applier.js';\nimport { FixLoader } from './loader.js';\nimport {\n DefaultFixInterceptor,\n createInterceptContext,\n GuardRejectedError,\n type FixInterceptor,\n type InterceptContext,\n} from './interceptors.js';\nimport { debug, warn } from '../utils/log.js';\n\n// ─── globalThis singleton key ───────────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst G = globalThis as any;\nconst RUNTIME_KEY = '__risicare_fix_runtime';\n\n// ─── Fix Runtime ────────────────────────────────────────────────────────────\n\nexport class FixRuntime {\n private readonly _config: Required<FixRuntimeConfig>;\n private readonly _cache: FixCache;\n private readonly _loader: FixLoader;\n private readonly _applier: FixApplier;\n private readonly _interceptor: DefaultFixInterceptor;\n private _started = false;\n\n // Effectiveness tracking\n private _fixApplications = new Map<string, number>();\n private _fixSuccesses = new Map<string, number>();\n\n constructor(config: FixRuntimeConfig) {\n this._config = resolveFixRuntimeConfig(config);\n this._cache = new FixCache(this._config);\n this._loader = new FixLoader(config, this._cache);\n this._applier = new FixApplier(config, this._cache);\n this._interceptor = new DefaultFixInterceptor(\n config,\n this._cache,\n this._applier,\n );\n }\n\n // ─── Accessors ──────────────────────────────────────────────────────────\n\n /** Runtime configuration (with defaults resolved). */\n get config(): Required<FixRuntimeConfig> {\n return this._config;\n }\n\n /** Whether the runtime is enabled and started. */\n get isEnabled(): boolean {\n return this._config.enabled && this._started;\n }\n\n /** The fix cache. */\n get cache(): FixCache {\n return this._cache;\n }\n\n /** The fix loader. */\n get loader(): FixLoader {\n return this._loader;\n }\n\n /** The fix applier. */\n get applier(): FixApplier {\n return this._applier;\n }\n\n /** The interceptor. */\n get interceptor(): FixInterceptor {\n return this._interceptor;\n }\n\n // ─── Lifecycle ──────────────────────────────────────────────────────────\n\n /**\n * Start the runtime.\n *\n * Triggers initial fix load and starts background refresh.\n * Never throws — failures degrade gracefully.\n */\n start(): void {\n try {\n if (this._started) return;\n\n if (!this._config.enabled) {\n debug('Fix runtime disabled');\n return;\n }\n\n debug('Starting fix runtime...');\n this._loader.start();\n this._started = true;\n debug('Fix runtime started');\n } catch (e) {\n warn(`Fix runtime start failed: ${e}`);\n }\n }\n\n /**\n * Stop the runtime.\n *\n * Stops background refresh and clears the cache.\n * Never throws.\n */\n stop(): void {\n try {\n if (!this._started) return;\n\n debug('Stopping fix runtime...');\n this._loader.stop();\n this._cache.clear();\n this._started = false;\n debug('Fix runtime stopped');\n } catch (e) {\n debug(`Fix runtime stop error: ${e}`);\n }\n }\n\n // ─── Intercept API ──────────────────────────────────────────────────────\n\n /**\n * Intercept a call: create context and run preCall fixes.\n *\n * Returns modified messages/params and the InterceptContext for\n * use in subsequent interceptResponse / interceptError calls.\n */\n interceptCall(\n operationType: string,\n operationName: string,\n messages: unknown[] | null,\n params: Record<string, unknown>,\n options?: {\n sessionId?: string;\n traceId?: string;\n errorCode?: string;\n },\n ): {\n messages: unknown[] | null;\n params: Record<string, unknown>;\n ctx: InterceptContext;\n } {\n const ctx = createInterceptContext(operationType, operationName, options);\n\n try {\n if (!this.isEnabled) {\n return { messages, params, ctx };\n }\n\n const result = this._interceptor.preCall(ctx, messages, params);\n return { messages: result.messages, params: result.params, ctx };\n } catch (e) {\n // PR-4+5 review B2: GuardRejectedError MUST surface to the provider\n // patcher so the LLM call is aborted. Everything else degrades to the\n // unmodified call (FixRuntime failures must never break customers).\n if (e instanceof GuardRejectedError) throw e;\n debug(`interceptCall error: ${e}`);\n return { messages, params, ctx };\n }\n }\n\n /**\n * Intercept a response: run postCall fixes (output validation).\n */\n interceptResponse(\n ctx: InterceptContext,\n response: unknown,\n ): { response: unknown; shouldContinue: boolean } {\n try {\n if (!this.isEnabled) {\n return { response, shouldContinue: true };\n }\n\n const result = this._interceptor.postCall(ctx, response);\n\n // Track success for effectiveness\n this._trackSuccess(ctx);\n\n return result;\n } catch (e) {\n // PR-4+5 review B2: same as interceptCall — output guard rejections\n // must surface; everything else degrades.\n if (e instanceof GuardRejectedError) throw e;\n debug(`interceptResponse error: ${e}`);\n return { response, shouldContinue: true };\n }\n }\n\n /**\n * Intercept an error: decide on retry/fallback.\n */\n interceptError(\n ctx: InterceptContext,\n error: Error,\n ): { shouldRetry: boolean; modifiedParams: Record<string, unknown> | null } {\n try {\n if (!this.isEnabled) {\n return { shouldRetry: false, modifiedParams: null };\n }\n\n ctx.attempt++;\n const result = this._interceptor.onError(ctx, error);\n\n // If not retrying, track failure for effectiveness\n if (!result.shouldRetry) {\n this._trackFailure(ctx);\n }\n\n return result;\n } catch (e) {\n debug(`interceptError error: ${e}`);\n return { shouldRetry: false, modifiedParams: null };\n }\n }\n\n // ─── Direct Fix Access ──────────────────────────────────────────────────\n\n /**\n * Get applicable fix for an error code.\n */\n getFix(errorCode: string, sessionId?: string): ActiveFix | null {\n try {\n if (!this.isEnabled) return null;\n return this._applier.getFixForError(errorCode, sessionId);\n } catch (e) {\n debug(`getFix error: ${e}`);\n return null;\n }\n }\n\n /**\n * Manually refresh fixes from the API.\n */\n async refreshFixes(): Promise<ActiveFix[]> {\n try {\n return await this._loader.loadSync();\n } catch (e) {\n debug(`refreshFixes error: ${e}`);\n return [];\n }\n }\n\n // ─── Effectiveness ──────────────────────────────────────────────────────\n\n /** Get effectiveness statistics for all fixes. */\n getEffectivenessStats(): Record<\n string,\n { applications: number; successes: number; successRate: number }\n > {\n const stats: Record<\n string,\n { applications: number; successes: number; successRate: number }\n > = {};\n\n for (const [fixId, applications] of this._fixApplications) {\n const successes = this._fixSuccesses.get(fixId) ?? 0;\n stats[fixId] = {\n applications,\n successes,\n successRate: applications > 0 ? successes / applications : 0,\n };\n }\n\n return stats;\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n private _trackSuccess(ctx: InterceptContext): void {\n for (const result of ctx.appliedFixes) {\n if (result.applied && result.fixId) {\n this._fixApplications.set(\n result.fixId,\n (this._fixApplications.get(result.fixId) ?? 0) + 1,\n );\n this._fixSuccesses.set(\n result.fixId,\n (this._fixSuccesses.get(result.fixId) ?? 0) + 1,\n );\n }\n }\n }\n\n private _trackFailure(ctx: InterceptContext): void {\n for (const result of ctx.appliedFixes) {\n if (result.applied && result.fixId) {\n this._fixApplications.set(\n result.fixId,\n (this._fixApplications.get(result.fixId) ?? 0) + 1,\n );\n // Don't increment success count\n }\n }\n }\n}\n\n// ─── Singleton Management ───────────────────────────────────────────────────\n\n/** Get the global FixRuntime instance, if initialized. */\nexport function getFixRuntime(): FixRuntime | undefined {\n return G[RUNTIME_KEY] as FixRuntime | undefined;\n}\n\n/** Set the global FixRuntime instance (for advanced use). */\nexport function setFixRuntime(runtime: FixRuntime): void {\n G[RUNTIME_KEY] = runtime;\n}\n\n/**\n * Initialize and start the global FixRuntime.\n *\n * If already initialized, returns the existing instance.\n * Never throws — initialization failures degrade gracefully.\n */\nexport function initFixRuntime(config: FixRuntimeConfig): FixRuntime {\n try {\n const existing = G[RUNTIME_KEY] as FixRuntime | undefined;\n if (existing) {\n debug('Fix runtime already initialized');\n return existing;\n }\n\n const runtime = new FixRuntime(config);\n runtime.start();\n G[RUNTIME_KEY] = runtime;\n return runtime;\n } catch (e) {\n warn(`initFixRuntime failed: ${e}`);\n // Return a disabled runtime so callers don't need null checks\n const fallback = new FixRuntime({ ...config, enabled: false });\n G[RUNTIME_KEY] = fallback;\n return fallback;\n }\n}\n\n/**\n * Shutdown and remove the global FixRuntime.\n *\n * Never throws.\n */\nexport function shutdownFixRuntime(): void {\n try {\n const runtime = G[RUNTIME_KEY] as FixRuntime | undefined;\n if (runtime) {\n runtime.stop();\n }\n G[RUNTIME_KEY] = undefined;\n } catch (e) {\n debug(`shutdownFixRuntime error: ${e}`);\n G[RUNTIME_KEY] = undefined;\n }\n}\n","/**\n * Agent context — identifies which agent is executing.\n * Supports nesting: inner agents automatically track parent.\n */\n\nimport { generateAgentId } from '../ids.js';\nimport { runWithContext, getCurrentAgent, type AgentContext } from './storage.js';\n\nexport interface AgentOptions {\n agentId?: string;\n name?: string;\n role?: string;\n agentType?: string;\n version?: number;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Run a callback within an agent context.\n * If nested inside another agent, parentAgentId is set automatically.\n *\n * @example\n * await withAgent({ name: 'researcher', role: 'worker' }, async () => {\n * const result = await llm.invoke(query);\n * return result;\n * });\n */\nexport function withAgent<T>(options: AgentOptions, fn: () => T): T {\n const parent = getCurrentAgent();\n const agentName = options.name ?? 'agent';\n\n const agent: AgentContext = {\n agentId: options.agentId ?? generateAgentId(agentName),\n agentName: agentName,\n agentRole: options.role,\n agentType: options.agentType,\n parentAgentId: parent?.agentId,\n version: options.version,\n metadata: options.metadata,\n };\n\n return runWithContext({ agent }, fn);\n}\n","/**\n * Lifecycle end-marker (F-B-012) — the JS SDK's run-end signal.\n *\n * At agent() / session() / phase / multi-agent context-manager exit the SDK\n * emits a lifecycle-end marker so downstream (\"did this run finish or die?\")\n * is answerable. The marker is three attributes carried on a span via the open\n * `attributes` map (schema-contract.md \"attribute-first\") plus the typed status:\n *\n * risicare.lifecycle.event = \"end\"\n * risicare.lifecycle.entity = \"session\" | \"agent\" | \"trace\"\n * risicare.lifecycle.status = \"ok\" (normal exit) | \"error\" (the body threw)\n *\n * Mirrors the Python SDK (packages/risicare-sdk/src/risicare/decorators.py).\n * See fix-workstream/F-B-012-DESIGN-CONTRACT.md for the settled contract.\n */\n\nimport type { Span } from './span.js';\nimport { getTracer } from './client.js';\nimport { SpanKind, SpanStatus } from './types.js';\n\nexport const LIFECYCLE_EVENT = 'risicare.lifecycle.event';\nexport const LIFECYCLE_ENTITY = 'risicare.lifecycle.entity';\nexport const LIFECYCLE_STATUS = 'risicare.lifecycle.status';\n\n// Cap the exception summary so a huge message can't bloat the span.\nconst STATUS_MESSAGE_MAX = 500;\n\nexport type LifecycleEntity = 'session' | 'agent' | 'trace';\n\nfunction excSummary(error: unknown): string {\n if (error instanceof Error) {\n return `${error.constructor.name}: ${error.message}`.slice(0, STATUS_MESSAGE_MAX);\n }\n return String(error).slice(0, STATUS_MESSAGE_MAX);\n}\n\n/**\n * Stamp the three lifecycle-end marker attributes + typed status on a span.\n *\n * Best-effort: a marker failure must never crash the host. When `span` is the\n * NOOP span (tracer disabled) its setters are no-ops so nothing is exported\n * (zero-overhead).\n */\nexport function stampEndMarker(\n span: Span,\n entity: LifecycleEntity,\n error: unknown | undefined,\n): void {\n try {\n const statusValue = error !== undefined ? 'error' : 'ok';\n span.setAttribute(LIFECYCLE_EVENT, 'end');\n span.setAttribute(LIFECYCLE_ENTITY, entity);\n span.setAttribute(LIFECYCLE_STATUS, statusValue);\n if (error !== undefined) {\n span.setStatus(SpanStatus.ERROR, excSummary(error));\n }\n } catch {\n // Never crash the host application.\n }\n}\n\n/**\n * Run `body` and stamp the lifecycle end-marker on `span` at completion —\n * `ok` on normal return, `error` on throw (then re-throw; host semantics\n * unchanged). Handles both sync results and Promises (SDK-004 parity).\n *\n * Intended to wrap the inner-body callback of an entity-span decorator, e.g.\n * tracer.startSpan({ ... }, (span) => withEndMarker(span, 'agent', () => fn()))\n */\nexport function withEndMarker<T>(span: Span, entity: LifecycleEntity, body: () => T): T {\n let result: T;\n try {\n result = body();\n } catch (error) {\n stampEndMarker(span, entity, error);\n throw error;\n }\n\n if (result instanceof Promise) {\n return result.then(\n (value) => {\n stampEndMarker(span, entity, undefined);\n return value;\n },\n (error) => {\n stampEndMarker(span, entity, error);\n throw error;\n },\n ) as unknown as T;\n }\n\n stampEndMarker(span, entity, undefined);\n return result;\n}\n\n/**\n * Emit a dedicated, near-zero-duration `session.end` marker span for the\n * session() path (which owns no span of its own).\n *\n * MUST be called INSIDE the active session context so the tracer auto-stamps\n * the span's `sessionId` from the current session — the worker needs that to\n * attribute the marker. Best-effort: never crashes the host. When the tracer\n * is disabled, startSpan runs over the NOOP span and nothing is exported.\n */\nexport function emitSessionEndMarker(error: unknown | undefined): void {\n try {\n const tracer = getTracer();\n if (!tracer) return;\n const statusValue = error !== undefined ? 'error' : 'ok';\n tracer.startSpan(\n {\n name: 'session.end',\n kind: SpanKind.INTERNAL,\n attributes: {\n [LIFECYCLE_EVENT]: 'end',\n [LIFECYCLE_ENTITY]: 'session',\n [LIFECYCLE_STATUS]: statusValue,\n },\n },\n (span) => {\n if (error !== undefined) {\n span.setStatus(SpanStatus.ERROR, excSummary(error));\n }\n },\n );\n } catch {\n // Never crash the host application.\n }\n}\n\n/**\n * Run `body` inside the active session context and emit the `session.end`\n * marker at completion — ok on normal return, error on throw (then re-throw).\n * Handles both sync results and Promises (SDK-004 parity).\n */\nexport function withSessionEndMarker<T>(body: () => T): T {\n let result: T;\n try {\n result = body();\n } catch (error) {\n emitSessionEndMarker(error);\n throw error;\n }\n\n if (result instanceof Promise) {\n return result.then(\n (value) => {\n emitSessionEndMarker(undefined);\n return value;\n },\n (error) => {\n emitSessionEndMarker(error);\n throw error;\n },\n ) as unknown as T;\n }\n\n emitSessionEndMarker(undefined);\n return result;\n}\n","/**\n * agent() — Higher-order function wrapper for agent identity (Tier 2).\n *\n * Wraps a function to execute within an agent context. All spans created\n * inside will be tagged with the agent's identity.\n *\n * Two equivalent calling forms are supported:\n *\n * // 2-arg form\n * const research = agent({ name: 'researcher' }, async (q) => { ... });\n *\n * // Curried form (decorator factory)\n * const research = agent({ name: 'researcher' })(async (q) => { ... });\n *\n * Both return a wrapped function — call it to actually run the body inside\n * the agent context.\n *\n * @example\n * const research = agent({ name: 'researcher', role: 'worker' }, async (query: string) => {\n * const result = await openai.chat.completions.create({ ... });\n * return result.choices[0].message.content;\n * });\n *\n * const answer = await research('What is quantum computing?');\n */\n\nimport { withAgent, type AgentOptions } from '../context/agent.js';\nimport { generateAgentId } from '../ids.js';\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { withEndMarker } from '../lifecycle.js';\n\n// Type-narrowing helper for the wrapper produced by both calling forms.\nfunction _wrapAgent<TArgs extends unknown[], TReturn>(\n options: AgentOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const spanName = `agent:${options.name ?? 'agent'}`;\n // ── F-AGENTID-JS-001 (W36/session-1a): MINT THE ID AT WRAP TIME, NOT PER CALL ──\n // ⚠ THE TWO SDKs PUT THE SAME FIELD NAME ON TWO DIFFERENT SEMANTICS, AND ONLY ONE\n // OF THEM CAN BE RIGHT. Python mints inside `decorator(fn)` — ONE id per (function\n // x process), and its `agent_context()` will not mint at all (agent_id is a\n // REQUIRED positional there, so the decorator is Python's only minting site).\n // JS minted inside `withAgent`, i.e. on EVERY INVOCATION: measured by execution,\n // three calls to one wrapped function produced three distinct `agent_id`s.\n //\n // The consequence is server-side and it is not cosmetic. `agent_id` is the grain of\n // `agent_spans`, so a JS customer's agent cardinality grows with TRAFFIC, not with\n // how many agents they wrote — measured on the lab: 10 distinct `agent_name`\n // against 151,552 distinct `agent_id`. That is what made the KPI read \"151.6K\n // agents\" (F-AGENTCOUNT-001) and what made GET /v1/agents/topology materialise\n // 151,552 nodes and OOM the whole API (F-TOPOOM-001). Same root, three surfaces.\n //\n // `spanName` above was ALREADY computed here, at wrap time — this line simply gives\n // the identity the same lifetime the label already had.\n //\n // ⚠ BOUND, stated so nobody reads more into this than it does: a caller using the\n // exported `withAgent()` DIRECTLY still gets a fresh id per call when they pass no\n // `agentId`. That is deliberate — `withAgent` is the twin of Python's\n // `agent_context()`, which has no minting behaviour to match, and removing the\n // fallback would be a breaking change to a published API. `agent()` is the\n // documented Tier-2 surface and the one both READMEs show.\n //\n // ⚠ NOT IN SCOPE and NOT decided here: whether `agent_id` should be stable ACROSS\n // processes. That is an OTel-semantics ruling (`service.instance.id` vs logical\n // identity) and belongs to the lead. This change only makes JS behave the way\n // Python already does.\n const agentId = options.agentId ?? generateAgentId(options.name ?? 'agent');\n const boundOptions: AgentOptions = { ...options, agentId };\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) {\n // Graceful degradation: run user code without tracing\n return fn(...args);\n }\n return withAgent(boundOptions, () => {\n // F-B-012: stamp the lifecycle end-marker (entity=\"agent\") on the entity\n // span — ok on normal exit, error on throw (then re-throw).\n return tracer.startSpan({ name: spanName, kind: SpanKind.AGENT }, (span) =>\n withEndMarker(span, 'agent', () => fn(...args)),\n );\n });\n };\n}\n\n// Overloads — typed for both calling forms.\nexport function agent<TArgs extends unknown[], TReturn>(\n options: AgentOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\nexport function agent(\n options: AgentOptions,\n): <TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => TReturn,\n) => (...args: TArgs) => TReturn;\nexport function agent<TArgs extends unknown[], TReturn>(\n options: AgentOptions,\n fn?: (...args: TArgs) => TReturn,\n): unknown {\n // Curried form: agent(options)(fn). Return a factory that accepts fn.\n if (fn === undefined) {\n return <TA extends unknown[], TR>(realFn: (...args: TA) => TR) =>\n _wrapAgent(options, realFn);\n }\n // 2-arg form: agent(options, fn). Wrap directly.\n return _wrapAgent(options, fn);\n}\n","/**\n * Session context — groups multiple traces from the same user interaction.\n */\n\nimport { runWithContext, type SessionContext } from './storage.js';\n\nexport interface SessionOptions {\n sessionId: string;\n userId?: string;\n metadata?: Record<string, unknown>;\n parentSessionId?: string;\n turnNumber?: number;\n}\n\n/**\n * Run a callback within a session context.\n *\n * @example\n * await withSession({ sessionId: 'sess-123', userId: 'user-1' }, async () => {\n * const result = await agent.run(query);\n * return result;\n * });\n */\nexport function withSession<T>(options: SessionOptions, fn: () => T): T {\n const session: SessionContext = {\n sessionId: options.sessionId,\n userId: options.userId,\n metadata: options.metadata,\n parentSessionId: options.parentSessionId,\n turnNumber: options.turnNumber ?? 1,\n };\n return runWithContext({ session }, fn);\n}\n","/**\n * session() — Higher-order function wrapper for session context (Tier 3).\n *\n * Wraps a function to execute within a session context. All spans created\n * inside will be tagged with the session identity.\n *\n * @example\n * const handleRequest = session(\n * (req) => ({ sessionId: req.sessionId, userId: req.userId }),\n * async (req: Request) => {\n * return await agent.run(req.query);\n * },\n * );\n */\n\nimport { withSession, type SessionOptions } from '../context/session.js';\nimport { withSessionEndMarker } from '../lifecycle.js';\n\nfunction _wrapSession<TArgs extends unknown[], TReturn>(\n optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions),\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n return (...args: TArgs): TReturn => {\n const options =\n typeof optionsOrResolver === 'function'\n ? optionsOrResolver(...args)\n : optionsOrResolver;\n // F-B-012: emit a dedicated `session.end` marker INSIDE the session context\n // (so it carries sessionId) — ok on normal exit, error on throw (re-thrown).\n return withSession(options, () => withSessionEndMarker(() => fn(...args)));\n };\n}\n\n/**\n * Wrap a function with session context.\n *\n * Two equivalent calling forms are supported (F-54 ergonomics):\n *\n * // 2-arg form\n * const handle = session({ sessionId: 's1' }, async (req) => { ... });\n *\n * // Curried form (decorator factory)\n * const handle = session({ sessionId: 's1' })(async (req) => { ... });\n *\n * @param optionsOrResolver - Static session options, or a function that derives them from args\n * @param fn - The function to wrap. If omitted, returns a decorator factory.\n */\nexport function session<TArgs extends unknown[], TReturn>(\n optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions),\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\nexport function session<TArgs extends unknown[]>(\n optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions),\n): <TR>(fn: (...args: TArgs) => TR) => (...args: TArgs) => TR;\nexport function session<TArgs extends unknown[], TReturn>(\n optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions),\n fn?: (...args: TArgs) => TReturn,\n): unknown {\n if (fn === undefined) {\n return <TR>(realFn: (...args: TArgs) => TR) =>\n _wrapSession(optionsOrResolver, realFn);\n }\n return _wrapSession(optionsOrResolver, fn);\n}\n","/**\n * Phase context — cognitive phase tracking (THINK/DECIDE/ACT/OBSERVE).\n */\n\nimport { SemanticPhase } from '../types.js';\nimport { runWithContext } from './storage.js';\n\n/**\n * Run a callback within a semantic phase context.\n */\nexport function withPhase<T>(phase: SemanticPhase, fn: () => T): T {\n return runWithContext({ phase }, fn);\n}\n","/**\n * Phase decorators — decision phase tracking (Tier 4).\n *\n * Wraps functions to execute within a semantic phase context (THINK/DECIDE/ACT/OBSERVE).\n * Each creates a span named after the phase.\n *\n * @example\n * const analyze = traceThink(async (data: string) => {\n * return await llm.invoke(`Analyze: ${data}`);\n * });\n *\n * const decide = traceDecide(async (analysis: string) => {\n * return await llm.invoke(`Decide action: ${analysis}`);\n * });\n */\n\nimport { withPhase } from '../context/phase.js';\nimport { getTracer } from '../client.js';\nimport { SemanticPhase, SpanKind } from '../types.js';\nimport { withEndMarker } from '../lifecycle.js';\n\nfunction phaseWrapper<TArgs extends unknown[], TReturn>(\n phase: SemanticPhase,\n kind: SpanKind,\n name: string,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) {\n return fn(...args);\n }\n return withPhase(phase, () => {\n // F-B-012: phase decorators are @trace-family — stamp the lifecycle\n // end-marker (entity=\"trace\") for uniform emission.\n return tracer.startSpan({ name, kind }, (span) =>\n withEndMarker(span, 'trace', () => fn(...args)),\n );\n });\n };\n}\n\n/**\n * Wrap a function in a THINK phase context with auto-span.\n *\n * @example traceThink(async () => { ... })\n * @example traceThink(\"analyze-data\", async () => { ... })\n */\nexport function traceThink<TArgs extends unknown[], TReturn>(\n fnOrName: ((...args: TArgs) => TReturn) | string,\n maybeFn?: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const name = typeof fnOrName === 'string' ? fnOrName : `phase:think`;\n const fn = typeof fnOrName === 'function' ? fnOrName : maybeFn!;\n return phaseWrapper(SemanticPhase.THINK, SpanKind.THINK, name, fn);\n}\n\n/**\n * Wrap a function in a DECIDE phase context with auto-span.\n *\n * @example traceDecide(async () => { ... })\n * @example traceDecide(\"choose-action\", async () => { ... })\n */\nexport function traceDecide<TArgs extends unknown[], TReturn>(\n fnOrName: ((...args: TArgs) => TReturn) | string,\n maybeFn?: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const name = typeof fnOrName === 'string' ? fnOrName : `phase:decide`;\n const fn = typeof fnOrName === 'function' ? fnOrName : maybeFn!;\n return phaseWrapper(SemanticPhase.DECIDE, SpanKind.DECIDE, name, fn);\n}\n\n/**\n * Wrap a function in an ACT phase context with auto-span.\n *\n * @example traceAct(async () => { ... })\n * @example traceAct(\"execute-tool\", async () => { ... })\n */\nexport function traceAct<TArgs extends unknown[], TReturn>(\n fnOrName: ((...args: TArgs) => TReturn) | string,\n maybeFn?: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const name = typeof fnOrName === 'string' ? fnOrName : `phase:act`;\n const fn = typeof fnOrName === 'function' ? fnOrName : maybeFn!;\n return phaseWrapper(SemanticPhase.ACT, SpanKind.TOOL_CALL, name, fn);\n}\n\n/**\n * Wrap a function in an OBSERVE phase context with auto-span.\n *\n * @example traceObserve(async () => { ... })\n * @example traceObserve(\"check-result\", async () => { ... })\n */\nexport function traceObserve<TArgs extends unknown[], TReturn>(\n fnOrName: ((...args: TArgs) => TReturn) | string,\n maybeFn?: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const name = typeof fnOrName === 'string' ? fnOrName : `phase:observe`;\n const fn = typeof fnOrName === 'function' ? fnOrName : maybeFn!;\n return phaseWrapper(SemanticPhase.OBSERVE, SpanKind.OBSERVE, name, fn);\n}\n","/**\n * Multi-agent communication decorators (Tier 5).\n *\n * Track inter-agent messages, delegations, and coordination.\n *\n * @example\n * const sendToWorker = traceMessage({ to: 'worker-1', type: MessageType.DELEGATE },\n * async (task: string) => { ... }\n * );\n */\n\nimport { getTracer } from '../client.js';\nimport { MessageType, SpanKind } from '../types.js';\nimport { withEndMarker } from '../lifecycle.js';\n\ninterface MessageOptions {\n to: string;\n type?: MessageType;\n metadata?: Record<string, unknown>;\n}\n\ninterface DelegateOptions {\n to: string;\n metadata?: Record<string, unknown>;\n}\n\ninterface CoordinateOptions {\n participants: string[];\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Namespace user metadata under 'metadata.*' to prevent overwriting\n * critical span attributes like message.type, message.to, etc.\n */\nfunction namespacedMetadata(metadata?: Record<string, unknown>): Record<string, unknown> {\n if (!metadata) return {};\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(metadata)) {\n result[`metadata.${key}`] = value;\n }\n return result;\n}\n\n/**\n * Wrap a function that sends a message to another agent.\n */\nexport function traceMessage<TArgs extends unknown[], TReturn>(\n options: MessageOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const msgType = options.type ?? MessageType.REQUEST;\n\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) return fn(...args);\n return tracer.startSpan(\n {\n name: `message:${msgType}→${options.to}`,\n kind: SpanKind.MESSAGE,\n attributes: {\n ...namespacedMetadata(options.metadata),\n 'message.to': options.to,\n 'message.type': msgType,\n 'message.target_agent_id': options.to,\n },\n },\n // F-B-012: multi-agent decorators are @trace-family — entity=\"trace\".\n (span) => withEndMarker(span, 'trace', () => fn(...args)),\n );\n };\n}\n\n/**\n * Wrap a function that delegates work to a sub-agent.\n */\nexport function traceDelegate<TArgs extends unknown[], TReturn>(\n options: DelegateOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) return fn(...args);\n return tracer.startSpan(\n {\n name: `delegate→${options.to}`,\n kind: SpanKind.DELEGATION,\n attributes: {\n ...namespacedMetadata(options.metadata),\n 'delegate.to': options.to,\n 'message.type': MessageType.DELEGATE,\n 'message.target_agent_id': options.to,\n },\n },\n // F-B-012: multi-agent decorators are @trace-family — entity=\"trace\".\n (span) => withEndMarker(span, 'trace', () => fn(...args)),\n );\n };\n}\n\n/**\n * Wrap a function that coordinates multiple agents.\n */\nexport function traceCoordinate<TArgs extends unknown[], TReturn>(\n options: CoordinateOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) return fn(...args);\n return tracer.startSpan(\n {\n name: `coordinate:[${options.participants.join(',')}]`,\n kind: SpanKind.COORDINATION,\n attributes: {\n ...namespacedMetadata(options.metadata),\n 'coordinate.participants': options.participants.join(','),\n 'message.type': MessageType.COORDINATE,\n },\n },\n // F-B-012: multi-agent decorators are @trace-family — entity=\"trace\".\n (span) => withEndMarker(span, 'trace', () => fn(...args)),\n );\n };\n}\n","/**\n * Serializable trace context + W3C Trace Context headers.\n *\n * TraceContext is a plain object that can be passed across process\n * boundaries (JSON serialization, HTTP headers, message queues).\n *\n * W3C Trace Context:\n * traceparent: {version}-{trace_id}-{span_id}-{flags}\n * tracestate: risicare=session_id={...};agent_id={...}\n */\n\nimport { generateTraceId, generateSpanId, validateTraceId, validateSpanId } from '../ids.js';\nimport { getCurrentSpan, getCurrentSession, getCurrentAgent, getContext } from './storage.js';\n\n// ─── Serializable Trace Context ──────────────────────────────────────────────\n\nexport interface TraceContext {\n traceId: string;\n spanId: string;\n sessionId?: string;\n agentId?: string;\n}\n\n/**\n * Get the current trace context as a serializable object.\n *\n * When called inside a span context, returns the active span's IDs.\n * When called outside a span (e.g. inside session() but before agent()),\n * pre-allocates a trace ID and stores it in context so the next\n * startSpan() call inherits it — preventing trace ID mismatch.\n */\nexport function getTraceContext(): TraceContext {\n const span = getCurrentSpan();\n const session = getCurrentSession();\n const agent = getCurrentAgent();\n\n let traceId: string;\n if (span) {\n traceId = span.traceId;\n } else {\n // No active span — check for a previously pre-allocated root trace ID\n const ctx = getContext();\n if (ctx._rootTraceId) {\n traceId = ctx._rootTraceId;\n } else {\n // Pre-allocate and store so startSpan() will inherit this ID\n traceId = generateTraceId();\n // Store in the current context scope (if one exists)\n // This is a no-op if we're outside any runWithContext scope\n if (ctx.session || ctx.agent) {\n // We're inside a session/agent scope — store the pre-allocated ID\n // by mutating the existing context object (safe because AsyncLocalStorage\n // gives each scope its own copy via spread in runWithContext)\n (ctx as Record<string, unknown>)._rootTraceId = traceId;\n }\n }\n }\n\n return {\n traceId,\n spanId: span?.spanId ?? generateSpanId(),\n sessionId: session?.sessionId,\n agentId: agent?.agentId,\n };\n}\n\n// ─── W3C Trace Context Headers ───────────────────────────────────────────────\n\nconst TRACEPARENT_HEADER = 'traceparent';\nconst TRACESTATE_HEADER = 'tracestate';\nconst RISICARE_STATE_DELIMITER = ';';\n\n/**\n * Inject trace context into HTTP headers (W3C format).\n */\nexport function injectTraceContext(headers: Record<string, string>): Record<string, string> {\n const span = getCurrentSpan();\n const session = getCurrentSession();\n const agent = getCurrentAgent();\n\n if (span) {\n // W3C traceparent: version-trace_id-span_id-flags\n headers[TRACEPARENT_HEADER] = `00-${span.traceId}-${span.spanId}-01`;\n\n // Custom tracestate for Risicare (uses ';' as internal delimiter)\n // Preserve other vendors' tracestate entries per W3C spec\n const parts: string[] = [];\n if (session) parts.push(`session_id=${session.sessionId}`);\n if (agent) parts.push(`agent_id=${agent.agentId}`);\n\n if (parts.length > 0) {\n const riscareEntry = `risicare=${parts.join(RISICARE_STATE_DELIMITER)}`;\n const existing = headers[TRACESTATE_HEADER] ?? '';\n // Keep non-risicare vendor entries from any existing tracestate\n const otherEntries = existing\n .split(',')\n .map((e) => e.trim())\n .filter((e) => e && !e.startsWith('risicare='));\n headers[TRACESTATE_HEADER] = [riscareEntry, ...otherEntries].join(',');\n }\n }\n\n return headers;\n}\n\n/**\n * Extract trace context from HTTP headers (W3C format).\n */\nexport function extractTraceContext(headers: Record<string, string>): Record<string, string | undefined> {\n const result: Record<string, string | undefined> = {};\n\n // Normalize header keys to lowercase (HTTP headers are case-insensitive)\n const normalizedHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n normalizedHeaders[key.toLowerCase()] = value;\n }\n\n // Parse traceparent\n const traceparent = normalizedHeaders[TRACEPARENT_HEADER] ?? '';\n if (traceparent) {\n const parts = traceparent.split('-');\n if (parts.length >= 4) {\n const traceId = parts[1].toLowerCase();\n const spanId = parts[2].toLowerCase();\n if (validateTraceId(traceId)) result.traceId = traceId;\n if (validateSpanId(spanId)) result.parentSpanId = spanId;\n result.flags = parts[3];\n }\n }\n\n // Parse tracestate\n const tracestate = normalizedHeaders[TRACESTATE_HEADER] ?? '';\n if (tracestate) {\n for (const entry of tracestate.split(',')) {\n const trimmed = entry.trim();\n if (trimmed.startsWith('risicare=')) {\n const state = trimmed.slice(9); // len(\"risicare=\")\n for (const kv of state.split(RISICARE_STATE_DELIMITER)) {\n const eqIdx = kv.indexOf('=');\n if (eqIdx > 0) {\n const key = kv.slice(0, eqIdx).trim();\n const value = kv.slice(eqIdx + 1).trim();\n if (key && value) {\n // Normalize known tracestate keys to camelCase\n const camelKey = key === 'session_id' ? 'sessionId'\n : key === 'agent_id' ? 'agentId'\n : key;\n result[camelKey] = value;\n }\n }\n }\n }\n }\n }\n\n return result;\n}\n","/**\n * Span registry — TTL-based span store for edge cases.\n *\n * While AsyncLocalStorage handles most context propagation in Node.js,\n * the registry is useful for:\n * - Cross-process span tracking\n * - Explicit span passing via ID\n * - Long-running operations that outlive their original context\n */\n\nimport type { Span } from '../span.js';\nimport { getRegistry, getOpCount, setOpCount } from '../globals.js';\n\ninterface RegistryEntry {\n span: Span;\n registeredAt: number;\n ttlMs: number;\n}\n\nconst DEFAULT_TTL_MS = 60_000;\nconst MAX_ENTRIES = 10_000;\nconst CLEANUP_INTERVAL = 100;\n\nfunction entries(): Map<string, RegistryEntry> {\n return getRegistry() as Map<string, RegistryEntry>;\n}\n\nexport function registerSpan(span: Span, ttlMs = DEFAULT_TTL_MS): void {\n entries().set(span.spanId, {\n span,\n registeredAt: Date.now(),\n ttlMs,\n });\n setOpCount(getOpCount() + 1);\n maybeCleanup();\n}\n\nexport function getSpanById(spanId: string): Span | undefined {\n const entry = entries().get(spanId);\n if (!entry) return undefined;\n\n if (Date.now() - entry.registeredAt > entry.ttlMs) {\n entries().delete(spanId);\n return undefined;\n }\n\n return entry.span;\n}\n\nexport function unregisterSpan(spanId: string): void {\n entries().delete(spanId);\n}\n\nexport function extendSpanTtl(spanId: string, additionalMs: number): boolean {\n const entry = entries().get(spanId);\n if (!entry) return false;\n\n if (Date.now() - entry.registeredAt > entry.ttlMs) {\n entries().delete(spanId);\n return false;\n }\n\n entry.ttlMs += additionalMs;\n return true;\n}\n\nexport function getRegistryStats(): { totalEntries: number; operationCount: number } {\n return {\n totalEntries: entries().size,\n operationCount: getOpCount(),\n };\n}\n\nexport function clearRegistry(): void {\n entries().clear();\n setOpCount(0);\n}\n\nfunction maybeCleanup(): void {\n if (getOpCount() % CLEANUP_INTERVAL !== 0) return;\n if (entries().size <= MAX_ENTRIES) return;\n\n const now = Date.now();\n for (const [id, entry] of entries()) {\n if (now - entry.registeredAt > entry.ttlMs) {\n entries().delete(id);\n }\n }\n}\n","/**\n * tracedStream — Wrap an async iterable in a trace span.\n *\n * Creates a span that starts when iteration begins and ends when\n * iteration completes (or errors). Chunks pass through UNCHANGED.\n *\n * This is the user-level streaming utility. For provider-level streaming\n * enrichment (token counts, cost), see individual provider instrumentors.\n *\n * Usage:\n * const stream = await openai.chat.completions.create({ stream: true, ... });\n * for await (const chunk of tracedStream(stream, { name: 'llm-stream' })) {\n * process(chunk);\n * }\n */\n\nimport { getTracer } from './client.js';\nimport { SpanKind } from './types.js';\n\nexport interface TracedStreamOptions {\n /** Span name */\n name: string;\n /** Span kind (default: INTERNAL) */\n kind?: SpanKind;\n /** Additional span attributes */\n attributes?: Record<string, unknown>;\n}\n\n/**\n * Wrap an async iterable in a trace span.\n *\n * - Span starts on first iteration\n * - chunk_count attribute set when iteration ends\n * - On error: span records exception, error re-thrown to caller\n * - On early break: span ended cleanly via finally\n * - If SDK not initialized: chunks pass through without wrapping\n */\nexport async function* tracedStream<T>(\n source: AsyncIterable<T>,\n options: TracedStreamOptions | string,\n): AsyncGenerator<T, void, undefined> {\n const opts = typeof options === 'string' ? { name: options } : options;\n\n // Graceful degradation: if SDK not initialized, pass through\n const tracer = getTracer();\n if (!tracer || !tracer.enabled) {\n yield* source;\n return;\n }\n\n const span = tracer.createSpan({\n name: opts.name,\n kind: opts.kind ?? SpanKind.INTERNAL,\n attributes: opts.attributes,\n });\n\n let chunkCount = 0;\n\n try {\n for await (const chunk of source) {\n chunkCount++;\n yield chunk;\n }\n\n span.setAttribute('stream.chunk_count', chunkCount);\n span.setAttribute('stream.completed', true);\n } catch (error) {\n span.setAttribute('stream.chunk_count', chunkCount);\n span.setAttribute('stream.completed', false);\n span.recordException(error instanceof Error ? error : String(error));\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Double-tracing prevention for framework integrations.\n *\n * When a framework integration (e.g., LlamaIndex handler) creates its own\n * LLM span, the underlying provider proxy (e.g., patchOpenAI) would also\n * create a duplicate span. This module provides suppression:\n *\n * - Framework integrations SET suppression via suppressProviderInstrumentation()\n * - Provider proxies CHECK via isProviderInstrumentationSuppressed() and skip\n *\n * Scoped to AsyncLocalStorage — concurrent calls are independent.\n */\n\nimport { getContext, runWithContext } from './storage.js';\n\n/**\n * Run a callback with provider instrumentation suppressed.\n *\n * During this callback, all provider instrumentors (patchOpenAI, etc.) will\n * skip span creation. The framework is responsible for creating the span.\n *\n * @param fn - The function to run with suppression active\n * @returns The function's return value\n */\nexport function suppressProviderInstrumentation<T>(fn: () => T): T {\n return runWithContext({ _suppressProviderInstrumentation: true }, fn);\n}\n\n/**\n * Check if provider instrumentation should be suppressed.\n *\n * Called by provider instrumentors as an early-exit guard. When true,\n * the provider calls the original method directly without creating a span.\n */\nexport function isProviderInstrumentationSuppressed(): boolean {\n return getContext()._suppressProviderInstrumentation === true;\n}\n","/**\n * LangChain.js integration via callback handler.\n *\n * LangChain.js uses BaseCallbackHandler from @langchain/core/callbacks/base.\n * F-628/F-729: prior versions of this handler did NOT extend BaseCallbackHandler\n * — LangChain v0.2+ tightened its callback registration to do `instanceof\n * BaseCallbackHandler` checks, silently dropping any handler that does not\n * inherit. Zero spans fired from any LCEL chain.\n *\n * PR-4+5 review B1 (2026-05-25): even with `extends BaseCallbackHandler`,\n * `instanceof` would fail for ESM consumers because we resolve via\n * `createRequire()` (CJS) — the two module instances are DIFFERENT class\n * identities. LangChain v0.3 ships `isBaseCallbackHandler(x)` which checks\n * duck-type markers (`x.copy` function, `x.name` string, `x.awaitHandlers`\n * boolean). We now set those markers explicitly so we pass the duck-typed\n * check regardless of which class identity ends up resolving in the customer\n * environment. We ALSO still extend the resolved BaseCallbackHandler when\n * available — that satisfies any remaining v0.2 `instanceof` callsite in\n * the customer's bundle AND inherits the real `copy()` method.\n *\n * Usage:\n * import { RisicareCallbackHandler } from 'risicare/langchain';\n * const handler = new RisicareCallbackHandler();\n * const result = await handler.withSuppression(() =>\n * chain.invoke(input, { callbacks: [handler] })\n * );\n *\n * SUPPRESSES provider instrumentation — LangChain handler creates LLM spans,\n * so provider-level spans (patchOpenAI, etc.) would duplicate without suppression.\n */\n\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { suppressProviderInstrumentation } from '../context/dedup.js';\nimport { debug } from '../utils/log.js';\nimport type { Span } from '../span.js';\n\ninterface SpanEntry {\n span: Span;\n startTime: number;\n}\n\n/**\n * Resolve BaseCallbackHandler lazily. We cannot `import` it statically because\n * @langchain/core is an OPTIONAL peer dep — a bare `import` would fail at\n * load time for customers who don't have LangChain. The dynamic require is\n * wrapped in try/catch; on failure we fall back to `Object` so the handler\n * still constructs (it just won't satisfy LangChain v0.2+'s instanceof check).\n */\nfunction resolveBaseCallbackHandler(): new (...args: unknown[]) => object {\n try {\n // Use createRequire so this works under both CJS and ESM.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { createRequire } = require('node:module') as typeof import('node:module');\n const req = createRequire(import.meta.url);\n const mod = req('@langchain/core/callbacks/base') as {\n BaseCallbackHandler?: new (...args: unknown[]) => object;\n };\n if (mod?.BaseCallbackHandler) {\n return mod.BaseCallbackHandler;\n }\n } catch {\n // Either ESM context without createRequire, or peer dep not installed.\n // Fall through to the require fallback below.\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require('@langchain/core/callbacks/base') as {\n BaseCallbackHandler?: new (...args: unknown[]) => object;\n };\n if (mod?.BaseCallbackHandler) {\n return mod.BaseCallbackHandler;\n }\n } catch {\n debug('RisicareCallbackHandler: @langchain/core not installed; handler will not satisfy LangChain v0.2+ instanceof check');\n }\n return Object as unknown as new (...args: unknown[]) => object;\n}\n\nconst _BaseCallbackHandler = resolveBaseCallbackHandler();\n\n/**\n * RisicareCallbackHandler — emits Risicare spans for every LangChain callback.\n *\n * Extends BaseCallbackHandler at runtime when @langchain/core is installed,\n * which is required for LangChain v0.2+ to accept it.\n *\n * F-882/F-883: chat-model and agent events are NEW in v0.2; older handlers\n * that only implement handleLLMStart get zero spans from `ChatModel`s (every\n * modern LangChain LLM is a ChatModel). The full chat / agent / custom-event\n * surface is now covered.\n */\nexport class RisicareCallbackHandler extends _BaseCallbackHandler {\n // PR-4+5 review B1: duck-type markers that LangChain v0.3's\n // `isBaseCallbackHandler(x)` checks. This is the ONLY reliable way to be\n // recognised across the CJS↔ESM identity split — `instanceof` cannot work\n // when our `createRequire`-loaded BaseCallbackHandler is a different\n // class object from the customer's ESM-imported BaseCallbackHandler.\n // Keep these as instance properties (not prototype) so they survive any\n // Object-fallback path when @langchain/core is absent.\n name = 'RisicareCallbackHandler';\n awaitHandlers = true;\n ignoreLLM = false;\n ignoreChain = false;\n ignoreAgent = false;\n ignoreRetriever = false;\n ignoreCustomEvent = false;\n raiseError = false;\n lc_serializable = false;\n lc_kwargs: Record<string, unknown> = {};\n\n private _spans = new Map<string, SpanEntry>();\n\n constructor() {\n // Call super() even if BaseCallbackHandler is the Object fallback.\n super();\n }\n\n /**\n * Required by LangChain's `isBaseCallbackHandler(x)` duck-type check\n * (`typeof x.copy === 'function'`). When @langchain/core is installed\n * BaseCallbackHandler's prototype provides its own `copy()`; this\n * declaration overrides with a Risicare-aware copy that re-instantiates\n * — sufficient for the handler-cloning paths LangChain uses internally\n * (e.g., per-run isolation in concurrent chains). Spans map starts empty\n * because a fresh handler should not share span state with its parent.\n */\n copy(): RisicareCallbackHandler {\n return new RisicareCallbackHandler();\n }\n\n /**\n * Run a function with provider instrumentation suppressed.\n *\n * Wrap your chain.invoke() call with this to prevent duplicate spans.\n * The handler creates LLM/tool spans, so provider proxies (patchOpenAI, etc.)\n * should be suppressed during chain execution.\n *\n * @example\n * const handler = new RisicareCallbackHandler();\n * const result = await handler.withSuppression(() =>\n * chain.invoke(input, { callbacks: [handler] })\n * );\n */\n withSuppression<T>(fn: () => T): T {\n return suppressProviderInstrumentation(fn);\n }\n\n // ── Internal helpers ──────────────────────────────────────────────────────\n\n private _startSpan(\n runId: string,\n parentRunId: string | undefined,\n name: string,\n kind: SpanKind,\n extraAttrs: Record<string, unknown> = {},\n ): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n\n const parentEntry = parentRunId ? this._spans.get(parentRunId) : undefined;\n const span = tracer.createSpan({\n name,\n kind,\n parentSpanId: parentEntry?.span.spanId,\n traceId: parentEntry?.span.traceId,\n attributes: {\n framework: 'langchain',\n 'langchain.run_id': runId,\n ...(parentRunId ? { 'langchain.parent_run_id': parentRunId } : {}),\n ...extraAttrs,\n },\n });\n\n this._spans.set(runId, { span, startTime: Date.now() });\n }\n\n private _endSpan(runId: string, extraAttrs: Record<string, unknown> = {}): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n for (const [k, v] of Object.entries(extraAttrs)) {\n entry.span.setAttribute(k, v);\n }\n entry.span.setAttribute('gen_ai.latency_ms', Date.now() - entry.startTime);\n entry.span.end();\n this._spans.delete(runId);\n }\n\n private _errorSpan(runId: string, error: Error): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n entry.span.recordException(error);\n entry.span.end();\n this._spans.delete(runId);\n }\n\n // ── Chain lifecycle ────────────────────────────────────────────────────────\n\n handleChainStart(\n chain: { name?: string; _type?: string },\n _inputs: Record<string, unknown>,\n runId: string,\n parentRunId?: string,\n ): void {\n this._startSpan(runId, parentRunId, chain.name || chain._type || 'chain', SpanKind.INTERNAL, {\n ...(chain._type ? { 'langchain.chain_type': chain._type } : {}),\n });\n }\n\n handleChainEnd(_outputs: Record<string, unknown>, runId: string): void {\n this._endSpan(runId);\n }\n\n handleChainError(error: Error, runId: string): void {\n this._errorSpan(runId, error);\n }\n\n // ── LLM lifecycle ─────────────────────────────────────────────────────────\n\n handleLLMStart(\n llm: { name?: string; _type?: string },\n _prompts: string[],\n runId: string,\n parentRunId?: string,\n ): void {\n this._startSpan(runId, parentRunId, llm.name || llm._type || 'llm', SpanKind.LLM_CALL, {\n 'gen_ai.system': 'langchain',\n 'gen_ai.prompt.count': _prompts.length,\n });\n }\n\n /**\n * F-882: chat-model lifecycle — LangChain v0.2+ emits this for any\n * ChatModel (which is EVERY production LLM today). Without this method,\n * not a single `langchain` LLM span fires when used via LCEL.\n *\n * The messages payload is an array-of-arrays (one inner array per prompt);\n * we just count rather than materialize content (PII boundary).\n */\n handleChatModelStart(\n llm: { name?: string; _type?: string },\n messages: unknown[][],\n runId: string,\n parentRunId?: string,\n ): void {\n const messageCount = Array.isArray(messages)\n ? messages.reduce((sum, arr) => sum + (Array.isArray(arr) ? arr.length : 0), 0)\n : 0;\n this._startSpan(runId, parentRunId, llm.name || llm._type || 'chat_model', SpanKind.LLM_CALL, {\n 'gen_ai.system': 'langchain',\n 'gen_ai.message.count': messageCount,\n });\n }\n\n handleLLMEnd(\n output: {\n generations?: unknown[][];\n llmOutput?: Record<string, unknown>;\n },\n runId: string,\n ): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n\n // Extract token usage from llmOutput\n const usage = output.llmOutput?.tokenUsage as\n | Record<string, number>\n | undefined;\n if (usage) {\n entry.span.setLlmFields({\n promptTokens: usage.promptTokens ?? usage.prompt_tokens,\n completionTokens: usage.completionTokens ?? usage.completion_tokens,\n totalTokens: usage.totalTokens ?? usage.total_tokens,\n });\n }\n\n const model = (output.llmOutput?.model ??\n output.llmOutput?.modelName) as string | undefined;\n if (model) {\n entry.span.setLlmFields({ model });\n }\n\n entry.span.setAttribute('gen_ai.latency_ms', Date.now() - entry.startTime);\n entry.span.end();\n this._spans.delete(runId);\n }\n\n handleLLMError(error: Error, runId: string): void {\n this._errorSpan(runId, error);\n }\n\n /**\n * F-883: streaming-token event. We do NOT create a new span (the LLM span\n * already exists from handleLLMStart/handleChatModelStart) — just count tokens\n * on the existing span. This is a HIGH-FREQUENCY event; do the cheap work only.\n */\n handleLLMNewToken(_token: string, _idx: unknown, runId: string): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n const prior = (entry.span.attributes?.['gen_ai.stream.token_count'] as number) ?? 0;\n entry.span.setAttribute('gen_ai.stream.token_count', prior + 1);\n }\n\n // ── Tool lifecycle ────────────────────────────────────────────────────────\n\n handleToolStart(\n tool: { name?: string },\n input: string,\n runId: string,\n parentRunId?: string,\n ): void {\n this._startSpan(runId, parentRunId, tool.name || 'tool', SpanKind.TOOL_CALL, {\n 'tool.name': tool.name || 'unknown',\n 'tool.input_length': input?.length ?? 0,\n });\n }\n\n handleToolEnd(output: string, runId: string): void {\n this._endSpan(runId, { 'tool.output_length': output?.length ?? 0 });\n }\n\n handleToolError(error: Error, runId: string): void {\n this._errorSpan(runId, error);\n }\n\n // ── Retriever lifecycle ───────────────────────────────────────────────────\n\n handleRetrieverStart(\n retriever: { name?: string },\n _query: string,\n runId: string,\n parentRunId?: string,\n ): void {\n this._startSpan(runId, parentRunId, retriever.name || 'retriever', SpanKind.RETRIEVAL);\n }\n\n handleRetrieverEnd(documents: unknown[], runId: string): void {\n this._endSpan(runId, { 'retriever.document_count': documents?.length ?? 0 });\n }\n\n handleRetrieverError(error: Error, runId: string): void {\n this._errorSpan(runId, error);\n }\n\n // ── Agent lifecycle (F-882) ───────────────────────────────────────────────\n\n /**\n * Agent decided to take an action (call a tool). LangChain v0.2 agents emit\n * this between LLM calls. Cheap span, no parent change.\n */\n handleAgentAction(\n action: { tool?: string; toolInput?: unknown; log?: string },\n runId: string,\n parentRunId?: string,\n ): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n const parentEntry = parentRunId ? this._spans.get(parentRunId) : undefined;\n const span = tracer.createSpan({\n name: `agent.action:${action.tool ?? 'unknown'}`,\n kind: SpanKind.INTERNAL,\n parentSpanId: parentEntry?.span.spanId,\n traceId: parentEntry?.span.traceId,\n attributes: {\n framework: 'langchain',\n 'langchain.run_id': runId,\n 'agent.action.tool': action.tool ?? '',\n },\n });\n // Agent actions are point-in-time events, not durations — end immediately.\n span.end();\n }\n\n /**\n * Agent finished (final answer produced). Mirror of handleAgentAction.\n */\n handleAgentEnd(\n action: { returnValues?: Record<string, unknown>; log?: string },\n runId: string,\n parentRunId?: string,\n ): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n const parentEntry = parentRunId ? this._spans.get(parentRunId) : undefined;\n const span = tracer.createSpan({\n name: 'agent.end',\n kind: SpanKind.INTERNAL,\n parentSpanId: parentEntry?.span.spanId,\n traceId: parentEntry?.span.traceId,\n attributes: {\n framework: 'langchain',\n 'langchain.run_id': runId,\n 'agent.return_keys': action.returnValues\n ? Object.keys(action.returnValues).length\n : 0,\n },\n });\n span.end();\n }\n\n // ── Misc (F-882) ──────────────────────────────────────────────────────────\n\n /**\n * Free-text emission (logging-style). Used by ConversationalRetrievalChain\n * and verbose prints. Adds an event to the current chain span if one exists.\n */\n handleText(text: string, runId: string, _parentRunId?: string): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n entry.span.addEvent('langchain.text', {\n 'text.length': text?.length ?? 0,\n });\n }\n\n /**\n * Custom event hook (introduced in @langchain/core 0.2.14). Customer code can\n * `dispatchCustomEvent(name, payload)` from inside a runnable. We surface as\n * a span event on the closest enclosing run so it shows up in the trace.\n */\n handleCustomEvent(\n eventName: string,\n _payload: unknown,\n runId: string,\n _tags?: string[],\n _metadata?: Record<string, unknown>,\n ): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n entry.span.addEvent('langchain.custom_event', { name: eventName });\n }\n}\n","/**\n * LangGraph.js integration via Proxy wrapping.\n *\n * LangGraph uses LangChain callbacks under the hood. This integration wraps\n * a compiled graph's invoke/stream methods to:\n * 1. Create a parent \"langgraph.invoke\" or \"langgraph.stream\" span\n * 2. Inject a RisicareCallbackHandler into the config so all internal\n * chain/LLM/tool calls are also traced\n *\n * Usage:\n * import { instrumentLangGraph } from 'risicare/frameworks/langgraph';\n * const graph = instrumentLangGraph(compiledGraph);\n * const result = await graph.invoke(input);\n *\n * Does NOT suppress provider instrumentation.\n */\n\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { RisicareCallbackHandler } from './langchain.js';\n\n/**\n * Wrap a compiled LangGraph graph with Risicare tracing.\n *\n * Returns a Proxy that intercepts `invoke` and `stream` calls to create\n * a parent span and inject the LangChain callback handler.\n *\n * @param graph - A compiled LangGraph graph object with invoke/stream methods\n * @returns A proxied graph with tracing enabled\n */\nexport function instrumentLangGraph<T extends object>(graph: T): T {\n return new Proxy(graph, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (\n (prop === 'invoke' || prop === 'stream') &&\n typeof value === 'function'\n ) {\n return function patchedMethod(\n this: unknown,\n ...args: unknown[]\n ): unknown {\n const tracer = getTracer();\n if (!tracer?.enabled) return value.apply(this, args);\n\n return tracer.startSpan(\n {\n name: `langgraph.${String(prop)}`,\n kind: SpanKind.AGENT,\n attributes: { framework: 'langgraph' },\n },\n (_span) => {\n // Inject RisicareCallbackHandler into config (second argument)\n const config = (args[1] ?? {}) as Record<string, unknown>;\n const callbacks = (config.callbacks ?? []) as unknown[];\n callbacks.push(new RisicareCallbackHandler());\n args[1] = { ...config, callbacks };\n\n const result = value.apply(this, args);\n\n // Handle async results (Promises)\n if (\n result &&\n typeof (result as Promise<unknown>).then === 'function'\n ) {\n return (result as Promise<unknown>).then((r) => r);\n }\n return result;\n },\n );\n };\n }\n\n return value;\n },\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","/**\n * LlamaIndex.TS integration via event handler.\n *\n * LlamaIndex.TS emits CustomEvent-shaped events through the global\n * `Settings.callbackManager` (a DOM-style EventTarget). F-880/F-881:\n * - Event NAMES use hyphens (`llm-start`, `llm-end`, `retrieve-start`,\n * `retrieve-end`, `query-start`, `query-end`, `embedding-start`, etc.),\n * NOT dotted suffixes (`.start` / `.end`). The previous handler used\n * `event.type.endsWith('.start')` and silently matched nothing.\n * - Payload lives on `event.detail` (DOM CustomEvent convention), NOT\n * `event.data` — the prior code was reading from `undefined`.\n *\n * We support both the hyphenated DOM CustomEvent shape (the real LlamaIndex.TS\n * format) and the dotted-suffix shape (the form the old code expected, kept\n * for back-compat with any customer who already wrote integration code\n * against the buggy contract).\n *\n * Usage:\n * import { RisicareLlamaIndexHandler } from 'risicare/llamaindex';\n * import { Settings } from 'llamaindex';\n * const handler = new RisicareLlamaIndexHandler();\n *\n * // Register every event we care about:\n * for (const name of RisicareLlamaIndexHandler.EVENT_NAMES) {\n * Settings.callbackManager.on(name, (e) => handler.onEvent(e));\n * }\n *\n * // For LLM/embedding calls, suppress provider instrumentation:\n * const result = handler.withSuppression(() => query(...));\n *\n * SUPPRESSES provider instrumentation -- LlamaIndex creates its own LLM spans,\n * so provider-level spans (patchOpenAI, etc.) would duplicate.\n */\n\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { suppressProviderInstrumentation } from '../context/dedup.js';\nimport type { Span } from '../span.js';\n\ninterface SpanEntry {\n span: Span;\n startTime: number;\n componentKind: string;\n}\n\n/**\n * Loose event shape. LlamaIndex.TS dispatches `CustomEvent`s where the payload\n * is on `.detail`. We also accept `.data` for back-compat with the older buggy\n * contract.\n */\nexport interface LlamaIndexEvent {\n type: string;\n // DOM CustomEvent payload (the real LlamaIndex.TS shape)\n detail?: Record<string, unknown>;\n // Back-compat fallback (the shape the old handler expected)\n data?: Record<string, unknown>;\n // Some payloads carry id/parentId at the top level instead of in detail\n id?: string;\n parentId?: string;\n}\n\n/**\n * Registry of (event-name → lifecycle-phase) for the events LlamaIndex.TS\n * actually emits. Maintained explicitly so the handler doesn't false-match\n * on customer-defined custom events that happen to end with `-start`.\n */\nconst EVENT_PHASE: Record<string, 'start' | 'end' | 'error'> = {\n // LLM\n 'llm-start': 'start',\n 'llm-end': 'end',\n 'llm-error': 'error',\n 'llm-tool-call': 'start',\n 'llm-tool-result': 'end',\n 'llm-stream': 'end',\n // Chat\n 'chat-start': 'start',\n 'chat-end': 'end',\n // Embeddings\n 'embedding-start': 'start',\n 'embedding-end': 'end',\n // Retrieval\n 'retrieve-start': 'start',\n 'retrieve-end': 'end',\n // Query / synthesis\n 'query-start': 'start',\n 'query-end': 'end',\n 'synthesize-start': 'start',\n 'synthesize-end': 'end',\n // Agent\n 'agent-start': 'start',\n 'agent-end': 'end',\n 'agent-step-start': 'start',\n 'agent-step-end': 'end',\n};\n\nexport class RisicareLlamaIndexHandler {\n /**\n * Public, iterable list of all event names this handler responds to.\n * Customers should subscribe to each on the LlamaIndex callback manager:\n * for (const n of RisicareLlamaIndexHandler.EVENT_NAMES) Settings.callbackManager.on(n, ...)\n */\n static readonly EVENT_NAMES = Object.keys(EVENT_PHASE);\n\n private _spans = new Map<string, SpanEntry>();\n\n /**\n * Handle a LlamaIndex lifecycle event.\n */\n onEvent(event: LlamaIndexEvent): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n\n // F-881: prefer .detail (DOM CustomEvent convention); fall back to .data.\n const payload = event.detail ?? event.data ?? {};\n\n // F-880: lookup by exact event name first (real LlamaIndex format).\n let phase = EVENT_PHASE[event.type];\n\n // Back-compat: accept legacy dotted suffix form (`*.start`/`*.end`/`*.error`).\n if (!phase) {\n if (event.type.endsWith('.start') || event.type.endsWith('.begin')) {\n phase = 'start';\n } else if (event.type.endsWith('.end') || event.type.endsWith('.complete')) {\n phase = 'end';\n } else if (event.type.endsWith('.error')) {\n phase = 'error';\n }\n }\n\n if (!phase) return;\n\n const id = (payload.id as string) ?? event.id ?? '';\n const parentId = (payload.parentId as string) ?? event.parentId;\n if (!id) return; // can't track spans without an id\n\n if (phase === 'start') {\n this._handleStart(event.type, id, parentId, payload);\n } else if (phase === 'end') {\n this._handleEnd(id, payload);\n } else {\n this._handleError(id, payload);\n }\n }\n\n /**\n * Run a function with provider instrumentation suppressed.\n */\n withSuppression<T>(fn: () => T): T {\n return suppressProviderInstrumentation(fn);\n }\n\n // ── Internal event handlers ───────────────────────────────────────────────\n\n private _handleStart(\n eventType: string,\n id: string,\n parentId: string | undefined,\n payload: Record<string, unknown>,\n ): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n\n const componentKind = this._classifyComponent(eventType);\n const parentEntry = parentId ? this._spans.get(parentId) : undefined;\n\n const spanKind =\n componentKind === 'llm'\n ? SpanKind.LLM_CALL\n : componentKind === 'retrieval'\n ? SpanKind.RETRIEVAL\n : componentKind === 'embedding'\n ? SpanKind.LLM_CALL\n : SpanKind.INTERNAL;\n\n // Strip both shapes of suffix so the span name is just the component.\n const spanName = eventType\n .replace(/\\.(start|begin)$/, '')\n .replace(/-(start|begin)$/, '');\n\n const span = tracer.createSpan({\n name: spanName,\n kind: spanKind,\n parentSpanId: parentEntry?.span.spanId,\n traceId: parentEntry?.span.traceId,\n attributes: {\n framework: 'llamaindex',\n 'framework.span_kind': componentKind,\n ...(payload.model ? { 'gen_ai.request.model': payload.model } : {}),\n },\n });\n\n this._spans.set(id, { span, startTime: Date.now(), componentKind });\n }\n\n private _handleEnd(id: string, payload: Record<string, unknown>): void {\n const entry = this._spans.get(id);\n if (!entry) return;\n\n entry.span.setAttribute('gen_ai.latency_ms', Date.now() - entry.startTime);\n\n // Extract token usage if available\n const usage = payload.usage as Record<string, number> | undefined;\n if (usage) {\n entry.span.setLlmFields({\n promptTokens: usage.promptTokens ?? usage.prompt_tokens,\n completionTokens: usage.completionTokens ?? usage.completion_tokens,\n });\n }\n\n if (payload.documentCount != null) {\n entry.span.setAttribute(\n 'retriever.document_count',\n payload.documentCount,\n );\n } else if (Array.isArray(payload.nodes)) {\n // LlamaIndex retrieve-end emits a `nodes` array; fall back to length.\n entry.span.setAttribute('retriever.document_count', payload.nodes.length);\n }\n\n entry.span.end();\n this._spans.delete(id);\n }\n\n private _handleError(id: string, payload: Record<string, unknown>): void {\n const entry = this._spans.get(id);\n if (!entry) return;\n\n const error = payload.error;\n entry.span.recordException(\n error instanceof Error ? error : String(error ?? 'Unknown error'),\n );\n entry.span.end();\n this._spans.delete(id);\n }\n\n /**\n * Classify a LlamaIndex event type into a component kind.\n */\n private _classifyComponent(eventType: string): string {\n const lower = eventType.toLowerCase();\n if (lower.includes('llm') || lower.includes('chat')) return 'llm';\n if (lower.includes('embed')) return 'embedding';\n if (lower.includes('retriev') || lower.includes('vector')) return 'retrieval';\n if (lower.includes('synth') || lower.includes('response')) return 'synthesis';\n if (lower.includes('query')) return 'query';\n if (lower.includes('agent')) return 'agent';\n return 'component';\n }\n}\n","/**\n * Webhook signature verification helpers (CON-195 / B-7, F-34).\n *\n * Customers receive Risicare webhooks at endpoints they configure. Each\n * delivery is signed by the sender (`packages/workers/src/workers/\n * webhook_dispatch.py`) with HMAC-SHA256 over `<timestamp>.<payload_bytes>`\n * using the per-webhook shared secret. The signature is delivered in the\n * `X-Risicare-Signature` header in Stripe-style format `t=<unix>,v1=<hex>`,\n * and the timestamp is also exposed verbatim as `X-Risicare-Timestamp`.\n *\n * This module is the TypeScript port of `risicare-sdk/src/risicare/\n * webhooks.py`. It enforces THREE checks (all must pass):\n *\n * 1. Header parsing — both headers must be present and well-formed.\n * 2. Time skew — `Math.abs(now - timestamp) <= toleranceS` (default\n * 5 minutes). This is what makes captured signed payloads\n * non-replayable past the tolerance window.\n * 3. HMAC equality — constant-time compare against a fresh signature\n * computed from the secret + the SAME timestamp + the raw body.\n *\n * Example (Express/Node receiver):\n *\n * import express from 'express';\n * import { verifyWebhookSignature, WebhookVerificationError } from 'risicare';\n *\n * const app = express();\n * // IMPORTANT: use raw body, not parsed JSON — the signature is\n * // over the EXACT bytes received; JSON re-serialization changes\n * // key ordering / whitespace and the signature will not match.\n * app.post('/risicare-webhook', express.raw({ type: '*\\/*' }), (req, res) => {\n * try {\n * verifyWebhookSignature(req.body, req.headers, YOUR_WEBHOOK_SECRET);\n * } catch (e) {\n * if (e instanceof WebhookVerificationError) {\n * return res.status(401).send(e.message);\n * }\n * throw e;\n * }\n * // ... process the verified event ...\n * res.status(200).end();\n * });\n *\n * The helper is dependency-light (Node `crypto` stdlib only) so customers\n * can use it without pulling in the rest of the SDK if they only need\n * verification.\n *\n * Edge runtime note: this verifier is synchronous and uses Node's\n * `crypto.timingSafeEqual` + `crypto.createHmac`. It will not run in\n * Cloudflare Workers / Vercel Edge / Deno Deploy as-is. An async Web\n * Crypto variant can be added if customers request it.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport { Buffer } from 'node:buffer';\n\n/**\n * Default skew window (seconds). 5 minutes matches Stripe / GitHub /\n * common industry practice. Customers can override per-call if their\n * clock infrastructure warrants a tighter or looser bound.\n *\n * Mirrors `DEFAULT_TIMESTAMP_TOLERANCE_S` in the Python SDK.\n */\nexport const DEFAULT_TIMESTAMP_TOLERANCE_S = 300;\n\nconst SIGNATURE_HEADER = 'X-Risicare-Signature';\nconst TIMESTAMP_HEADER = 'X-Risicare-Timestamp';\n\n// The Python sender emits exactly one supported scheme today (`v1`). The\n// parser is structured so adding `v2` later is a non-breaking change:\n// list newer schemes first; the first match wins.\nconst SUPPORTED_SCHEMES = ['v1'] as const;\n\n// SHA-256 hex digest is always 64 lowercase hex chars. We pre-validate\n// the parsed signature against this shape BEFORE constant-time compare\n// so `Buffer.from(s, 'hex')` cannot silently truncate non-hex chars\n// (Node's Buffer.from 'hex' parser is lenient — it stops at the first\n// invalid character without raising).\nconst HEX_SHA256_RE = /^[0-9a-f]{64}$/;\n\n/**\n * Raised when a webhook delivery fails any verification check.\n *\n * Customers should catch this specifically rather than a generic `Error`\n * so verification failures are not conflated with other input problems\n * (e.g. body-parsing errors at the framework layer).\n *\n * The `message` is safe to log — it never includes the secret, the\n * expected signature, or the computed signature.\n */\nexport class WebhookVerificationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WebhookVerificationError';\n // Preserve prototype chain across the ES5/ES2022 transpilation\n // boundary so `instanceof` works for callers compiled to older\n // targets that interact with this library.\n Object.setPrototypeOf(this, WebhookVerificationError.prototype);\n }\n}\n\n/**\n * Options for `verifyWebhookSignature`. All fields are optional.\n */\nexport interface VerifyWebhookOptions {\n /**\n * Maximum clock-skew tolerance in seconds. Defaults to\n * `DEFAULT_TIMESTAMP_TOLERANCE_S` (300). Setting to 0 is supported\n * (strict same-second match) but discouraged in distributed\n * deployments.\n */\n toleranceS?: number;\n /**\n * Test hook — override \"current time\" in unix seconds.\n * Customers should not pass this.\n */\n _now?: number;\n}\n\n/**\n * Header-like inputs accepted by `verifyWebhookSignature`.\n *\n * Covers (a) Web API `Headers` (case-insensitive `.get`), (b) Node\n * `IncomingHttpHeaders` (plain object with lowercase keys, possibly\n * array-valued for multi-set headers), (c) `Map<string, string>`\n * (case-sensitive `.get`), and (d) plain `Record` (case-sensitive\n * property lookup, possibly array-valued).\n *\n * Lookup strategy: try the canonical mixed-case name first\n * (`X-Risicare-Signature`). If that returns undefined, fall back to the\n * lowercased form (`x-risicare-signature`). Mirrors the Python\n * `_get_header` helper.\n */\nexport type HeaderLookup =\n | Headers\n | Map<string, string>\n | Record<string, string | string[] | undefined>;\n\n/**\n * Payload shapes accepted by `verifyWebhookSignature`.\n *\n * `Buffer extends Uint8Array` in Node, so callers passing `Buffer`\n * satisfy the `Uint8Array` arm. `ArrayBuffer` is explicitly accepted\n * for callers using Web-API request bodies. `string` is UTF-8 encoded\n * internally.\n *\n * Crucially, callers must pass the EXACT bytes received over the\n * wire. Parsing JSON and re-serializing changes byte order and\n * whitespace; the signature will not match.\n */\nexport type WebhookPayload = Uint8Array | ArrayBuffer | string;\n\n/**\n * Look up a header by name, trying canonical mixed-case first, then\n * lowercase. Returns `undefined` if neither lookup yields a value.\n *\n * Web `Headers` and Node `IncomingHttpHeaders` are case-insensitive\n * lookups by spec; a plain `Record` is case-sensitive. We try both to\n * support either.\n */\nfunction getHeader(headers: HeaderLookup, name: string): string | undefined {\n const lower = name.toLowerCase();\n\n // Anything with a `.get(name)` method — covers Web `Headers`\n // (case-insensitive by spec, so the lowercase fallback is a no-op)\n // AND `Map<string, string>` (case-sensitive, so the fallback DOES\n // matter when the caller set lowercase keys). Web `Headers.get`\n // returns `null` for missing keys; Map returns `undefined`. Both\n // are normalised to `undefined` here.\n if (\n typeof (headers as { get?: (k: string) => unknown }).get === 'function'\n ) {\n const accessor = headers as { get: (k: string) => string | null | undefined };\n const v = accessor.get(name) ?? accessor.get(lower);\n return v ?? undefined;\n }\n\n // Plain object / IncomingHttpHeaders. IncomingHttpHeaders values\n // can be `string | string[] | undefined` (multi-set headers). For\n // a signature header there should only ever be one — but if a\n // client genuinely sets the same header twice, joining with `, `\n // would corrupt the signature. Take the first element only and let\n // a malformed-segment error surface downstream if the duplication\n // produced a problem.\n const dict = headers as Record<string, string | string[] | undefined>;\n const raw = dict[name] ?? dict[lower];\n if (raw === undefined) {\n return undefined;\n }\n if (Array.isArray(raw)) {\n return raw[0];\n }\n return raw;\n}\n\n/**\n * Coerce any accepted payload shape to a `Buffer` for HMAC consumption.\n *\n * `string` → UTF-8 encode.\n * `Uint8Array` (including `Buffer`) → `Buffer.from(uint8)` shares the\n * underlying ArrayBuffer with no copy.\n * `ArrayBuffer` → `Buffer.from(ab)` copies into a Node Buffer.\n *\n * Anything else throws `WebhookVerificationError`.\n */\nfunction coercePayload(payload: WebhookPayload): Buffer {\n if (typeof payload === 'string') {\n return Buffer.from(payload, 'utf-8');\n }\n // `Buffer` is a subclass of `Uint8Array`, so this arm covers both.\n if (payload instanceof Uint8Array) {\n return Buffer.from(\n payload.buffer,\n payload.byteOffset,\n payload.byteLength,\n );\n }\n if (payload instanceof ArrayBuffer) {\n return Buffer.from(payload);\n }\n throw new WebhookVerificationError(\n `payload must be Uint8Array, ArrayBuffer, Buffer, or string, got ${typeof payload}`,\n );\n}\n\n/**\n * Parse `t=<int>,v1=<hex>` (with possible additional unknown `kN=v`\n * segments) into `[timestamp, hex_signature]`.\n *\n * Tolerates extra segments for forward-compat: future scheme versions\n * may add new k=v pairs and this parser must not break.\n *\n * Mirrors `_parse_signature_header` in the Python SDK.\n */\nfunction parseSignatureHeader(raw: string): [number, string] {\n // Use a null-prototype object so a malicious segment like\n // `__proto__=v1=<hex>` or `constructor=...` cannot pollute the\n // global Object prototype via bracket-assignment, and so that\n // `'t' in parts` cannot return a false positive from inherited\n // properties like `toString` or `hasOwnProperty`. Python uses a\n // plain dict which has no equivalent prototype chain; this is a\n // JS-specific hardening with no Python counterpart.\n const parts: Record<string, string> = Object.create(null);\n\n for (const rawSegment of raw.split(',')) {\n const segment = rawSegment.trim();\n if (segment === '') {\n continue;\n }\n const eqIdx = segment.indexOf('=');\n if (eqIdx === -1) {\n throw new WebhookVerificationError(\n `Malformed segment in ${SIGNATURE_HEADER}: ${JSON.stringify(segment)}`,\n );\n }\n const key = segment.slice(0, eqIdx).trim();\n const value = segment.slice(eqIdx + 1).trim();\n parts[key] = value;\n }\n\n if (!('t' in parts)) {\n throw new WebhookVerificationError(\n `Missing \\`t=\\` (timestamp) in ${SIGNATURE_HEADER}`,\n );\n }\n\n // Pick the first supported scheme present. Today only `v1` exists.\n let scheme: string | undefined;\n for (const candidate of SUPPORTED_SCHEMES) {\n if (candidate in parts) {\n scheme = candidate;\n break;\n }\n }\n if (scheme === undefined) {\n // Sorted keys so the error message is deterministic regardless\n // of segment order in the input header.\n const keys = Object.keys(parts).sort();\n throw new WebhookVerificationError(\n `No supported signature scheme in ${SIGNATURE_HEADER}; ` +\n `expected one of (${SUPPORTED_SCHEMES.map((s) => `'${s}'`).join(', ')}), ` +\n `got keys [${keys.map((k) => `'${k}'`).join(', ')}]`,\n );\n }\n\n // parts['t'] is guaranteed defined by the `'t' in parts` check above.\n const tRaw = parts['t'] as string;\n // The segment was already `.trim()`ed during parsing, so leading /\n // trailing whitespace cannot reach here. The strict regex rejects\n // (a) empty string, (b) sign-only (\"-\", \"+\"), and (c) numeric-\n // prefix-then-garbage like \"123abc\" that `parseInt` would\n // permissively coerce to 123. Note: a leading `+` is rejected here\n // for parity with the Python sender's output (which is always\n // `str(int(time.time()))` — never carries a sign).\n if (!/^-?\\d+$/.test(tRaw)) {\n throw new WebhookVerificationError(\n `Non-integer timestamp in ${SIGNATURE_HEADER}: ${JSON.stringify(tRaw)}`,\n );\n }\n const ts = parseInt(tRaw, 10);\n if (!Number.isFinite(ts)) {\n // Defensive: a 21+ digit decimal string would `parseInt` to a\n // value outside `Number.MAX_SAFE_INTEGER`, and while `parseInt`\n // returns Infinity only for very specific inputs, treating any\n // non-finite result as a parse failure is the safe move.\n throw new WebhookVerificationError(\n `Non-integer timestamp in ${SIGNATURE_HEADER}: ${JSON.stringify(tRaw)}`,\n );\n }\n\n // scheme is one of SUPPORTED_SCHEMES so it's a known key.\n const sigHex = parts[scheme];\n if (sigHex === undefined || sigHex === '') {\n throw new WebhookVerificationError(\n `Empty ${scheme}= value in ${SIGNATURE_HEADER}`,\n );\n }\n\n return [ts, sigHex];\n}\n\n/**\n * Constant-time HMAC-SHA256 hex compare with explicit length pre-check.\n *\n * `crypto.timingSafeEqual` throws if the two buffers have different\n * lengths. To avoid leaking length information via the exception path,\n * we pre-validate the expected hex against the canonical sha256-hex\n * shape (64 lowercase hex chars) BEFORE attempting comparison. A\n * malformed expected → generic mismatch with no detail.\n *\n * The `computed` value comes from `createHmac(...).digest('hex')` and\n * is therefore always 64-char lowercase hex by construction; we don't\n * re-validate it.\n */\nfunction safeHexEqual(computed: string, expected: string): boolean {\n if (!HEX_SHA256_RE.test(expected)) {\n return false;\n }\n const a = Buffer.from(computed, 'hex');\n const b = Buffer.from(expected, 'hex');\n // Defensive: both buffers must be exactly 32 bytes after the regex\n // check above. If the platform ever returns a different length, the\n // explicit check below makes the failure mode a benign `false`\n // rather than a thrown RangeError from timingSafeEqual.\n if (a.length !== b.length) {\n return false;\n }\n return timingSafeEqual(a, b);\n}\n\n/**\n * Verify a Risicare webhook delivery. Throws `WebhookVerificationError`\n * on any failure; returns `undefined` on success.\n *\n * @param payload Raw request body bytes — the EXACT bytes received over\n * the wire. Re-serializing parsed JSON will change byte ordering and\n * break the signature.\n * @param headers Header lookup. Web `Headers`, `Map<string,string>`,\n * Node `IncomingHttpHeaders`, or plain `Record` all work. Lookup is\n * case-insensitive (canonical mixed-case tried first, then lowercase).\n * @param secret The shared secret configured on the Risicare webhook\n * record. Returned by `POST /v1/webhooks` once at create time.\n * @param opts Optional overrides — `toleranceS` (default 300) and\n * `_now` (test hook).\n *\n * @throws WebhookVerificationError on any of: missing headers, malformed\n * signature, timestamp outside tolerance, HMAC mismatch, or invalid\n * payload type.\n */\nexport function verifyWebhookSignature(\n payload: WebhookPayload,\n headers: HeaderLookup,\n secret: string,\n opts: VerifyWebhookOptions = {},\n): void {\n const toleranceS =\n opts.toleranceS ?? DEFAULT_TIMESTAMP_TOLERANCE_S;\n\n // Validate payload type FIRST so a caller passing a clearly-wrong\n // type gets the most informative error (same ordering as Python).\n const payloadBytes = coercePayload(payload);\n\n const sigHeader = getHeader(headers, SIGNATURE_HEADER);\n if (sigHeader === undefined || sigHeader === '') {\n throw new WebhookVerificationError(\n `Missing ${SIGNATURE_HEADER} header`,\n );\n }\n const tsHeader = getHeader(headers, TIMESTAMP_HEADER);\n if (tsHeader === undefined || tsHeader === '') {\n throw new WebhookVerificationError(\n `Missing ${TIMESTAMP_HEADER} header`,\n );\n }\n\n const [tsInSig, expectedHex] = parseSignatureHeader(sigHeader);\n\n // Cross-check: the standalone X-Risicare-Timestamp header MUST agree\n // with the t= value baked into the signature. A discrepancy means\n // the sender is buggy or someone has split the request — either way\n // refuse. Mirrors Python webhooks.py:214-217.\n if (!/^-?\\d+$/.test(tsHeader)) {\n throw new WebhookVerificationError(\n `Non-integer ${TIMESTAMP_HEADER}: ${JSON.stringify(tsHeader)}`,\n );\n }\n const tsStandalone = parseInt(tsHeader, 10);\n if (!Number.isFinite(tsStandalone)) {\n throw new WebhookVerificationError(\n `Non-integer ${TIMESTAMP_HEADER}: ${JSON.stringify(tsHeader)}`,\n );\n }\n if (tsStandalone !== tsInSig) {\n throw new WebhookVerificationError(\n `Timestamp mismatch: ${TIMESTAMP_HEADER}=${tsStandalone}, signature t=${tsInSig}`,\n );\n }\n\n const now =\n opts._now !== undefined\n ? Math.trunc(opts._now)\n : Math.floor(Date.now() / 1000);\n const skew = Math.abs(now - tsInSig);\n if (skew > toleranceS) {\n throw new WebhookVerificationError(\n `Webhook timestamp outside tolerance: skew=${skew}s, max=${toleranceS}s`,\n );\n }\n\n // Compute the canonical-string HMAC: `<ts>.<payload_bytes>`.\n // Two .update() calls is equivalent to one .update(concatenated)\n // and avoids materializing a copy of the payload.\n const hmac = createHmac('sha256', secret);\n hmac.update(`${tsInSig}.`);\n hmac.update(payloadBytes);\n const computed = hmac.digest('hex');\n\n if (!safeHexEqual(computed, expectedHex)) {\n // Deliberately generic message — leaking \"computed != expected\"\n // or the expected value would assist an attacker doing oracle\n // attacks. Mirrors Python webhooks.py:228-231.\n throw new WebhookVerificationError('Webhook signature mismatch');\n }\n}\n"],"mappings":";;;;;;;;AA+BA,SAAS,cAAAA,mBAAkB;;;ACb3B,SAAS,yBAAyB;AAGlC,IAAM,IAAI;AACV,IAAM,SAAS;AAIR,SAAS,YAAqB;AACnC,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAEO,SAAS,UAAU,QAAuB;AAC/C,IAAE,SAAS,QAAQ,IAAI;AACzB;AAEO,SAAS,YAAqB;AACnC,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAEO,SAAS,UAAU,QAAuB;AAC/C,IAAE,SAAS,QAAQ,IAAI;AACzB;AAIO,SAAS,oBAAgD;AAC9D,MAAI,CAAC,EAAE,SAAS,KAAK,GAAG;AACtB,MAAE,SAAS,KAAK,IAAI,IAAI,kBAAkB;AAAA,EAC5C;AACA,SAAO,EAAE,SAAS,KAAK;AACzB;AAIO,SAAS,cAAoC;AAClD,MAAI,CAAC,EAAE,SAAS,UAAU,GAAG;AAC3B,MAAE,SAAS,UAAU,IAAI,oBAAI,IAAI;AAAA,EACnC;AACA,SAAO,EAAE,SAAS,UAAU;AAC9B;AAEO,SAAS,aAAqB;AACnC,SAAO,EAAE,SAAS,SAAS,KAAK;AAClC;AAEO,SAAS,WAAW,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A;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAQM,IAAM,qBAA8C;AAAA,EACzD,EAAE,IAAI,IAAI,OAAO,4BAA4B,GAAG,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KAAK,UAAU,QAAQ,CAAC;AAAA,IAC9D;AAAA,EACF;AACA,QAAM,eAAe,SAAS,UAAU,EAAE;AAC1C,MAAI,CAAC,OAAO,SAAS,YAAY,GAAG;AAClC,UAAM,IAAI;AAAA,MACR,eAAe,gBAAgB,KAAK,KAAK,UAAU,QAAQ,CAAC;AAAA,IAC9D;AAAA,EACF;AACA,MAAI,iBAAiB,SAAS;AAC5B,UAAM,IAAI;AAAA,MACR,uBAAuB,gBAAgB,IAAI,YAAY,iBAAiB,OAAO;AAAA,IACjF;AAAA,EACF;AAEA,QAAM,MACJ,KAAK,SAAS,SACV,KAAK,MAAM,KAAK,IAAI,IACpB,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAClC,QAAM,OAAO,KAAK,IAAI,MAAM,OAAO;AACnC,MAAI,OAAO,YAAY;AACrB,UAAM,IAAI;AAAA,MACR,6CAA6C,IAAI,UAAU,UAAU;AAAA,IACvE;AAAA,EACF;AAKA,QAAM,OAAO,WAAW,UAAU,MAAM;AACxC,OAAK,OAAO,GAAG,OAAO,GAAG;AACzB,OAAK,OAAO,YAAY;AACxB,QAAM,WAAW,KAAK,OAAO,KAAK;AAElC,MAAI,CAAC,aAAa,UAAU,WAAW,GAAG;AAIxC,UAAM,IAAI,yBAAyB,4BAA4B;AAAA,EACjE;AACF;","names":["createHash","debug","SpanKind","SpanStatus","SemanticPhase","AgentRole","MessageType","session","agent","G","G","getTracer","createHash","getTracer","agent","getTracer","getTracer","session","getTracer","getTracer","session","agent","getTracer","getTracer","getTracer","getTracer","getTracer","Buffer"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/globals.ts","../src/utils/log.ts","../src/masking.ts","../src/exporters/batch.ts","../src/config.ts","../src/ids.ts","../src/types.ts","../src/utils/clock.ts","../src/span.ts","../src/noop.ts","../src/utils/sampling.ts","../src/runtime/config.ts","../src/runtime/taxonomy.generated.ts","../src/runtime/interceptors.ts","../src/context/storage.ts","../src/tracer.ts","../src/version.ts","../src/exporters/http.ts","../src/exporters/console.ts","../src/runtime/cache.ts","../src/runtime/applier.ts","../src/runtime/loader.ts","../src/runtime/runtime.ts","../src/context/agent.ts","../src/lifecycle.ts","../src/decorators/agent.ts","../src/context/session.ts","../src/decorators/session.ts","../src/context/phase.ts","../src/decorators/phase.ts","../src/decorators/multi-agent.ts","../src/context/trace-context.ts","../src/context/registry.ts","../src/streaming.ts","../src/context/dedup.ts","../src/frameworks/langchain.ts","../src/frameworks/langgraph.ts","../src/utils/assert-client.ts","../src/frameworks/instructor.ts","../src/frameworks/llamaindex.ts","../src/webhooks.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 } from './config.js';\nimport { Tracer, attachErrorCode } from './tracer.js';\nimport { SDK_VERSION } from './version.js';\nimport { BatchSpanProcessor, SHUTDOWN_BUDGET_MS } from './exporters/batch.js';\nimport { HttpExporter } from './exporters/http.js';\nimport { ConsoleExporter } from './exporters/console.js';\nimport { SpanKind, SpanStatus } from './types.js';\nimport type { SpanExporter } from './exporters/base.js';\nimport { setDebug, debug } from './utils/log.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';\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\". 500 ms covers the up-to-one-RTT overrun\n * the between-rounds deadline check permits (ruling §4.4).\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// ─── 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 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\n if (this.config.apiKey && !this.config.apiKey.startsWith('rsk-')) {\n debug('Warning: API key should start with \"rsk-\". Got: ' + this.config.apiKey.slice(0, 4) + '...');\n }\n\n // Build exporter chain\n //\n // ⚠ F-SDKJSCONSOLE-001 (fixed 2026-08-15, W23). The `else` arm below used to\n // read `exporter = new ConsoleExporter()` — \"No API key and not debug — use\n // console as fallback\". `exporters/console.ts` writes\n // `JSON.stringify(span.toPayload())` to `process.stderr`: the WHOLE payload,\n // every attribute, every event, every exception, with NO redaction of any\n // kind. Neither Tier-1 (credentials) nor Tier-2 (email/phone/SSN/card/IPv4)\n // exists in the SDK — both run server-side, one hop later — so there is\n // nothing to fall back on and the only safe action is not to write.\n //\n // A falsy API key is not an exotic state: it is a missing, mistyped or\n // not-injected `RISICARE_API_KEY` — CI, staging, a new dev's laptop, a\n // container whose secret failed to mount. Measured from the extracted,\n // PUBLISHED `risicare-0.4.2.tgz` in BOTH module systems (W20-P2, re-derived\n // W23): `RISICARE_TRACING=true` with no key printed a synthetic email, SSN,\n // Visa test PAN and RFC-5737 address to the customer's own stderr. No debug\n // flag was required and no warning was emitted.\n //\n // Python in the identical state WARNS AND DROPS (`client.py:941-947`) and\n // attaches its ConsoleExporter only under `if config.debug`\n // (`client.py:868-875`). This makes JS match Python rather than inventing a\n // third behaviour: the explicit debug opt-in below is UNCHANGED — a customer\n // who asks for console output still gets it — and the accidental state now\n // configures NO exporter at all, which is exactly what Python does.\n //\n // Consequence, deliberate and honest: with an empty exporter array the\n // processor's existing accounting takes over — spans are re-queued to the\n // MAX_RETRIES bound and then discarded as `transport_refused`, COUNTED and\n // WARNED (\"check the api_key and the endpoint\"), instead of being reported\n // as delivered. A DropExporter returning SUCCESS would have been the smaller\n // diff and would have inflated `exportedSpans` for spans that reached\n // nothing — the F-HONEST-001 defect, re-introduced in the SDK.\n let exporter: SpanExporter | undefined;\n if (this.config.debug && !this.config.apiKey) {\n exporter = new ConsoleExporter();\n } else 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 } else {\n // No API key and not debug — configure NO exporter, and say so. Spans are\n // created and then dropped, exactly as in Python.\n exporter = undefined;\n if (this.config.enabled) {\n // console.warn, not debug() — `debug` is off by default, which is how\n // F-SDKJSREPORTERROR-001 stayed invisible in a shipped release. Same\n // defensive wrapper as the FixRuntime warning below: some sandboxed and\n // edge runtimes have a closed stderr, and a logging call must never be\n // the thing that crashes a customer's process.\n try {\n console.warn(\n `[risicare] tracing is enabled but NO API key is configured — spans are ` +\n `created and then DROPPED, not sent to ${this.config.endpoint}. ` +\n `Pass apiKey to init() (or set the RISICARE_API_KEY env var). ` +\n `Span data is NOT written to the console: it would be unredacted. ` +\n `Pass debug:true if you want console output for local development.`\n );\n } catch {\n // Prefer silent over crash.\n }\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 // Start the batch processor (enables span queuing and periodic flushing)\n this.processor.start();\n\n // Start FixRuntime for runtime fix application (preparatory\n // infrastructure for Stage 4 deployment; today /v1/fixes/active\n // always returns empty since no fix is promoted past status=draft).\n // Loads active fixes from /api/v1/fixes/active, caches with TTL,\n // background-refreshes every 60s. Provider patches call interceptCall()\n // to apply fixes before LLM calls.\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 endpoint so customers can verify\n // reachability. Mirrors the Python SDK fix at client.py:520-528.\n if (this.config.apiKey && this.config.enabled) {\n try {\n initFixRuntime({\n apiEndpoint: this.config.endpoint,\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 = e instanceof Error ? e.message : String(e);\n try {\n console.warn(\n `[risicare] FixRuntime initialization failed — auto-fix is OFFLINE for this process. ` +\n `endpoint=${this.config.endpoint} 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(`FixRuntime init traceback: ${e instanceof Error && e.stack ? e.stack : String(e)}`);\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=${this.config.endpoint}`);\n }\n\n get enabled(): boolean {\n return this.tracer.enabled;\n }\n\n set enabled(value: boolean) {\n this.tracer.enabled = value;\n }\n\n // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)\n async shutdown(): Promise<void> {\n if (this._shutdownPromise) return this._shutdownPromise;\n this._shutdownPromise = this._doShutdown();\n return this._shutdownPromise;\n }\n\n private async _doShutdown(): 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 await this.processor.shutdown();\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 }\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(): Promise<boolean> {\n return this.processor.flush();\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 *\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 = () => {\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\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 ];\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\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 */\nexport async function shutdown(): 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();\n setGlobalClient(undefined);\n setGlobalTracer(undefined);\n}\n\n/**\n * Flush all pending spans without shutting down.\n *\n * @returns `true` only if everything queued at entry was DELIVERED — `false`\n * if the deadline expired with spans still queued, or if any span was\n * discarded during the window (F-SDKCB-001 §6). An uninitialised SDK returns\n * `true`: it was handed nothing, and it lost nothing.\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(): Promise<boolean> {\n const client = getGlobalClient() as RisicareClient | undefined;\n if (!client) return true;\n return client.flush();\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.\n */\nexport function isEnabled(): boolean {\n const client = getGlobalClient() as RisicareClient | undefined;\n return client?.enabled ?? false;\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, matching the 0.5.1 config default.\n return tracer?.traceContent ?? false;\n}\n\n/**\n * Get SDK metrics: exported spans, dropped spans, failed exports, queue stats.\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 { ...client.processor.getMetrics(), sdkState: 'running' as const };\n }\n if (_finalMetrics) {\n // Copy: a caller mutating the object must not corrupt the one tally the\n // process has left.\n return {\n ..._finalMetrics,\n droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },\n sdkState: 'shutdown' as const,\n };\n }\n return {\n exportedSpans: 0,\n droppedSpans: 0,\n droppedSpansByReason: {\n queue_full: 0,\n transport_refused: 0,\n shutdown_residue: 0,\n },\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 span.setAttribute('error.message', err.message.slice(0, 2000));\n if (err.stack) span.setAttribute('error.stack', err.stack.slice(0, 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 * Record a custom evaluation score on a trace.\n *\n * Sends the score to the server in a fire-and-forget fashion.\n * This function never throws and is non-blocking.\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 if (typeof value !== 'number' || !Number.isFinite(value) || value < 0.0 || value > 1.0) {\n debug(`score: value must be in [0.0, 1.0], got ${value}. Score not sent.`);\n return;\n }\n if (!traceId || !name) {\n debug('score: traceId and name are required');\n return;\n }\n\n const client = getGlobalClient() as RisicareClient | undefined;\n if (!client?.enabled || !client.config.apiKey) return;\n\n const endpoint = client.config.endpoint.replace(/\\/$/, '');\n const url = `${endpoint}/api/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 // Fire-and-forget — never blocks caller\n 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 }).catch((err) => debug(`score: send failed: ${err}`));\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 * 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 * 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; nothing here inspects a VALUE. The gate is a\n// pure KEY-SHAPE filter, and it lives in this module because this module already\n// owns the one walk both content paths cross.\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-match set, same suffix\n// rule, 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/**\n * Attribute keys that carry customer content but do not match the suffix rule.\n *\n * ⚠ LOAD-BEARING. `gen_ai.system_prompt` (anthropic, bedrock) and\n * `gen_ai.prompt.message` (cohere) carry content and do NOT end in `content` —\n * a suffix rule alone silently leaks both. Matched EXACTLY rather than by\n * substring, because `framework.pydantic_ai.system_prompt_length` is a number\n * and must survive.\n */\nconst CONTENT_KEYS_EXACT: ReadonlySet<string> = new Set([\n 'gen_ai.system_prompt',\n 'gen_ai.prompt.message',\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\n/**\n * Whether `key` names a customer-content attribute. Pure function of the KEY.\n *\n * Derived from what the PLATFORM treats as content — exactly the keys\n * `spans_worker._extract_input_preview` / `_extract_output_preview` read — plus\n * every `*.content` key the providers and integrations emit. Guards on the\n * SHAPE, not an enumeration (F-COMPATGUARD-001: an enumeration rots the moment\n * a provider adds a key).\n *\n * Deliberately does NOT match: `gen_ai.response.content_type` (a MIME type),\n * `gen_ai.response.content_blocks` / `gen_ai.prompt.parts` /\n * `gen_ai.response.choices` / `gen_ai.completion.tool_calls` (counts),\n * `gen_ai.prompt.{i}.role` (a role name).\n */\nexport function isContentKey(key: string): boolean {\n if (CONTENT_KEYS_EXACT.has(key)) return true;\n const lastSegment = key.slice(key.lastIndexOf('.') + 1);\n if (lastSegment === 'content') return true;\n return key.endsWith('_content');\n}\n\n/** Replace every content-keyed value in `attrs` IN PLACE. Returns the count. */\nfunction stripAttributes(attrs: Record<string, unknown>): number {\n let n = 0;\n for (const k of Object.keys(attrs)) {\n if (isContentKey(k)) {\n attrs[k] = CONTENT_OMITTED_MARKER;\n n++;\n }\n }\n return n;\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.\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.\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 stripped += stripAttributes(event.attributes);\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 += stripAttributes(link.attributes);\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 debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);\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 SpanExporter } from './base.js';\nimport { debug, warn } from '../utils/log.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`** — the same fail-closed default as `resolveConfig`.\n * When false, every content-keyed attribute is replaced on the export path\n * 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 */\nexport type DropReason = 'queue_full' | 'transport_refused' | 'shutdown_residue';\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\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/**\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 _beforeExitHandler: (() => void) | null = null;\n\n // Retry tracking for failed batches (Audit #5)\n private _retryCounts = new Map<string, number>();\n private static readonly MAX_RETRIES = 3;\n\n private _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;\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 };\n exportedSpans = 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 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 * Anything still queued when the loop stops is COUNTED as `shutdown_residue`\n * and announced with a WARNING. The warning is the primary signal, not the\n * counter: a counter incremented inside `shutdown()` is written to memory\n * about to be freed and has no reader (RULING §2 / §8.2).\n */\n async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS): Promise<void> {\n if (!this._started) return;\n this._started = false;\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 drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);\n\n while (this._queue.length > 0 || this._flushing) {\n if (Date.now() >= drainDeadline) break;\n const outcome = await this._exportBatch();\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 // 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 // Once shutdown() has returned, holding IS abandoning: the timer is\n // cleared, the exit listener is gone, nothing will ever export these.\n const residue = this._queue.length;\n if (residue > 0) {\n this._queue.length = 0;\n this._recordDropped('shutdown_residue', residue);\n // NOT rate-limited, by ruling. Names the count AND the reason.\n warn(\n `shutdown() gave up with ${residue} span(s) still queued ` +\n `(reason=shutdown_residue) — they were NOT delivered. The ${timeoutMs} ms ` +\n `shutdown budget expired or the transport stopped accepting. Raise the ` +\n `shutdown timeout, or your container's termination grace period, to lose less.`\n );\n }\n\n // Shutdown exporters\n for (const exporter of this._exporters) {\n try {\n await exporter.shutdown();\n } catch (e) {\n debug(`Error shutting down ${exporter.name}: ${e}`);\n }\n }\n\n // Clean up retry tracking — retry-map drain site 3 of 3\n this._retryCounts.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) return;\n\n // Check queue capacity\n if (this._queue.length >= this._maxQueueSize) {\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 (this._queue.length >= this._batchSize) {\n void this._exportBatch();\n }\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 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 * Returns `false` when (a) the deadline expires with spans still queued,\n * (b) any span was discarded during the window — breaker refusal or retry\n * exhaustion — or (c) it is called after `shutdown()` and the shutdown\n * residue was non-zero.\n *\n * ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span\n * that arrived DURING the window 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 = SHUTDOWN_BUDGET_MS): Promise<boolean> {\n if (!this._started) {\n // (c) — the `!_started => true` early return was unconditional, so\n // `flush()` after `shutdown()` reported success over abandoned data.\n return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;\n }\n\n const start = Date.now();\n const discardedAtEntry = this.droppedSpans;\n\n // Wait for in-flight exports to complete AND queue to drain\n while (this._queue.length > 0 || this._flushing) {\n if (!this._flushing && this._queue.length > 0) {\n await this._exportBatch();\n } else {\n // Wait a tick for the in-flight export to finish\n await new Promise((r) => setTimeout(r, 1));\n }\n if (Date.now() - start > timeoutMs) return false;\n }\n\n return this.droppedSpans === discardedAtEntry;\n }\n\n getMetrics() {\n return {\n exportedSpans: this.exportedSpans,\n droppedSpans: this.droppedSpans,\n droppedSpansByReason: { ...this.droppedSpansByReason },\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 private async _exportBatch(): Promise<Round> {\n if (this._flushing) return Round.Busy;\n if (this._queue.length === 0) return Round.Empty;\n this._flushing = true;\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\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 for (const exporter of this._exporters) {\n try {\n const result = await exporter.export(batch);\n if (result === ExportResult.SUCCESS) {\n if (!batchExported) {\n this.exportedSpans += batch.length;\n batchExported = true;\n // Clear retry counts for successfully exported spans\n for (const span of batch) {\n this._retryCounts.delete(span.spanId);\n }\n }\n } else {\n this.failedExports++;\n }\n } catch (e) {\n this.failedExports++;\n debug(`Export to ${exporter.name} failed: ${e}`);\n }\n }\n\n // Audit #5: Re-queue failed batches with retry limit\n if (!batchExported) {\n let dropped = 0;\n const retryable = batch.filter(span => {\n const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;\n if (count > BatchSpanProcessor.MAX_RETRIES) {\n // retry-map drain site 2 of 3\n this._retryCounts.delete(span.spanId);\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 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 warn(\n `${dropped} span(s) DISCARDED (reason=transport_refused) after ` +\n `${BatchSpanProcessor.MAX_RETRIES} failed export attempts each — 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 this._flushing = false;\n }\n }\n}\n","/**\n * SDK configuration with environment variable loading.\n *\n * Environment variables match the Python SDK exactly:\n * RISICARE_API_KEY, RISICARE_ENDPOINT, RISICARE_PROJECT_ID, etc.\n */\n\nimport { DEFAULT_BATCH_SIZE } from './exporters/batch.js';\nimport type { MaskFn } from './masking.js';\n\nexport interface RisicareConfig {\n /** API key for authentication (format: \"rsk-{random}\"). Each key is scoped to one project. */\n apiKey?: string;\n\n /** Gateway endpoint URL */\n endpoint?: string;\n\n /**\n * @deprecated Project is determined by your API key. This field is ignored\n * by the gateway and will be removed in v1.0. Use `serviceName` and\n * `environment` for within-project organization.\n */\n projectId?: string;\n\n /** Environment name (production, staging, development). Used for within-project organization. */\n environment?: string;\n\n /** Service name for within-project organization. */\n serviceName?: string;\n\n /** Service version */\n serviceVersion?: string;\n\n /** Whether tracing is enabled (default: true if apiKey provided) */\n enabled?: boolean;\n\n /**\n * Whether prompt/completion content may leave the process.\n *\n * **Default `false` since 0.5.1** (was `true`). When false, every\n * content-keyed attribute is replaced with `<risicare:content-omitted>` on\n * the export path — including content you set by hand, which 0.5.0 and\n * earlier did NOT gate.\n */\n traceContent?: boolean;\n\n /** Sample rate 0.0–1.0 (default: 1.0 = trace all) */\n sampleRate?: number;\n\n /** Batch size threshold before flush (default: 100) */\n batchSize?: number;\n\n /** Batch timeout in ms before flush (default: 1000) */\n batchTimeoutMs?: number;\n\n /** Maximum queue size (default: 10000) */\n maxQueueSize?: number;\n\n /** Enable debug logging (default: false) */\n debug?: boolean;\n\n /** Enable gzip compression for HTTP exports (default: false) */\n compress?: boolean;\n\n /** Custom metadata attached to all spans */\n metadata?: Record<string, unknown>;\n\n /**\n * Masking callback applied to every content-bearing field of every span\n * BEFORE the batch leaves the process — `mask(key, value) => value`.\n *\n * This is the only layer at which you can keep data off Risicare's wire, so\n * it applies to every exporter, including custom ones. `key` is the attribute\n * key (`\"gen_ai.prompt.0.content\"`) or a dotted path (`\"statusMessage\"`,\n * `\"events.0.attributes.x\"`). Identifiers and span/event names are NOT passed\n * to it — masking those breaks trace structure and your own joins.\n *\n * ⚠ Must be CPU-only and fast: Node is single-threaded, so this runs on your\n * event loop. No I/O, no network, no unbounded retries, no per-request state.\n * If it throws, that one field becomes `\"<risicare:mask-error>\"` and the span\n * is still exported. See `masking.ts`.\n *\n * ⚠ Has NO environment-variable form, deliberately: the shapes that would\n * make a callable env-resolvable are arbitrary code execution driven by the\n * process environment. Masking is configured in code, by the application that\n * owns the data.\n */\n mask?: MaskFn;\n}\n\nconst DEFAULT_ENDPOINT = 'https://app.risicare.ai';\n\n/**\n * Load configuration from environment variables, merged with explicit config.\n * Explicit config takes precedence over env vars.\n */\nexport function resolveConfig(\n config?: Partial<RisicareConfig>,\n): Required<Omit<RisicareConfig, 'metadata' | 'mask'>> & {\n metadata: Record<string, unknown>;\n // `mask` is excluded from `Required<>` on purpose: \"no mask\" is a real,\n // supported state and must stay expressible as `undefined`. Defaulting it to\n // an identity function would make \"is masking configured?\" unanswerable by\n // inspection — the processor skips the whole pass when this is undefined.\n mask: MaskFn | undefined;\n} {\n const env = process.env;\n\n const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;\n const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;\n const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;\n\n // Deprecation warning for projectId\n if (config?.projectId || env.RISICARE_PROJECT_ID) {\n console.warn(\n '[risicare] projectId is deprecated and ignored by the gateway. ' +\n 'Your API key determines the project. ' +\n 'Use serviceName and environment for within-project organization. ' +\n 'projectId will be removed in v1.0.'\n );\n }\n const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? 'development';\n const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;\n const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;\n // ⚠ DEFAULT CHANGED 0.5.0 -> 0.5.1: was `true`. `RISICARE_TRACE_CONTENT=true`\n // (or `traceContent: true`) restores capture explicitly.\n const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);\n const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? '1.0');\n const debug = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);\n const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);\n // SDK-RELEASE-RULING.md §4.3: default raised 100 -> 500. Derived, and stated\n // once in `exporters/batch.ts` — imported rather than repeated so the env\n // default and the validation default cannot drift apart from the processor's.\n const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, DEFAULT_BATCH_SIZE);\n const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1000);\n const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 10000);\n\n // F-355/F-356/F-357: numeric inputs must validate, clamp, and warn —\n // silent NaN/negative/string acceptance breaks the exporter unpredictably.\n const sampleRate = validateSampleRate(sampleRateRaw);\n // F-SDKSAMPRATEBLIND-001 — the rate never reaches the platform, so say so at\n // the one moment the customer chose it. Verified 2026-08-17 across 539\n // first-party server / worker / dashboard / gateway / schema files (controls:\n // 128 files match trace_id, 228 match project_id): no ingest field, no\n // column, no query and no W3C traceparent flag carries it — both emitters\n // hardcode `-01`, and `TraceFlags.SAMPLED` has zero call sites. So every\n // server-side count is a count of SAMPLED traces and nothing downstream can\n // scale it back up. Re-run: fix-workstream/perf/w34/sampling_wire_probe.sh\n if (sampleRate < 1.0) {\n console.warn(\n `[risicare] sampleRate=${sampleRate} — head sampling is applied in-process ` +\n `and the rate is NOT transmitted to the platform. Trace counts, error rates ` +\n `and cost figures in the dashboard will describe the sampled subset only, ` +\n `and cannot be scaled back to totals. Sampling is trace-coherent: a dropped ` +\n `trace drops whole.`,\n );\n }\n const batchSize = validatePositiveInt('batchSize', batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 10_000);\n const batchTimeoutMs = validatePositiveInt('batchTimeoutMs', batchTimeoutMsRaw, 1000, 1, 600_000);\n const maxQueueSize = validatePositiveInt('maxQueueSize', maxQueueSizeRaw, 10_000, 1, 1_000_000);\n\n // Enabled logic: explicit > env RISICARE_TRACING > (true if apiKey present)\n let enabled: boolean;\n if (config?.enabled !== undefined) {\n enabled = config.enabled;\n } else if (env.RISICARE_TRACING !== undefined) {\n enabled = parseBool(env.RISICARE_TRACING, false);\n } else {\n enabled = !!apiKey;\n }\n\n return {\n apiKey: apiKey ?? '',\n endpoint,\n projectId: projectId ?? '',\n environment,\n serviceName: serviceName ?? '',\n serviceVersion: serviceVersion ?? '',\n enabled,\n traceContent,\n sampleRate,\n batchSize,\n batchTimeoutMs,\n maxQueueSize,\n debug,\n compress,\n metadata: config?.metadata ?? {},\n // No env fallback — see the field's note on RisicareConfig.\n mask: config?.mask,\n };\n}\n\nfunction parseBool(value: string | undefined, defaultValue: boolean): boolean {\n if (value === undefined) return defaultValue;\n const lower = value.toLowerCase();\n return lower === 'true' || lower === '1' || lower === 'yes';\n}\n\n/**\n * Parse a numeric env var with a fallback default. parseInt returns NaN on\n * non-numeric input — we want the default in that case, not NaN propagating.\n */\nfunction parseNumericEnv(value: string | undefined, defaultValue: number): number {\n if (value === undefined) return defaultValue;\n const n = Number(value);\n return Number.isFinite(n) ? n : defaultValue;\n}\n\n/**\n * F-355: sampleRate must be a finite number in [0, 1]. Anything else warns\n * and falls back to 1.0 (trace everything — safer default for an observability\n * platform than \"trace nothing\" on a typo).\n */\nfunction validateSampleRate(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1) {\n return value;\n }\n // Try string→number coercion once for env vars that arrive as strings.\n if (typeof value === 'string') {\n const n = Number(value);\n if (Number.isFinite(n) && n >= 0 && n <= 1) return n;\n }\n console.warn(\n `[risicare] sampleRate must be a finite number in [0, 1], got ${typeof value}=${JSON.stringify(value)}; defaulting to 1.0`,\n );\n return 1.0;\n}\n\n/**\n * F-356/F-357: validate a positive-integer config knob. Coerces strings,\n * rejects NaN/negative/non-finite, clamps to [min, max] with a warning.\n */\nfunction validatePositiveInt(\n name: string,\n value: unknown,\n defaultValue: number,\n min: number,\n max: number,\n): number {\n let n: number;\n if (typeof value === 'number') {\n n = value;\n } else if (typeof value === 'string') {\n n = Number(value);\n if (Number.isFinite(n)) {\n console.warn(\n `[risicare] ${name} was a string (\"${value}\"); coerced to ${n}. Pass a number to avoid this warning.`,\n );\n }\n } else {\n console.warn(\n `[risicare] ${name} must be a positive integer, got ${typeof value}; defaulting to ${defaultValue}`,\n );\n return defaultValue;\n }\n if (!Number.isFinite(n) || n <= 0) {\n console.warn(\n `[risicare] ${name} must be > 0, got ${value}; defaulting to ${defaultValue}`,\n );\n return defaultValue;\n }\n if (n < min) {\n console.warn(`[risicare] ${name}=${n} below floor; clamping to ${min}`);\n return min;\n }\n if (n > max) {\n console.warn(`[risicare] ${name}=${n} above ceiling; clamping to ${max}`);\n return max;\n }\n return Math.floor(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 * Core type definitions for the Risicare SDK.\n *\n * These enums and types mirror the Python SDK's risicare-core types\n * and align with the Rust gateway's SpanData struct.\n */\n\n// ─── Span Kind ───────────────────────────────────────────────────────────────\n\nexport enum SpanKind {\n INTERNAL = 'internal',\n CLIENT = 'client',\n SERVER = 'server',\n PRODUCER = 'producer',\n CONSUMER = 'consumer',\n AGENT = 'agent',\n LLM_CALL = 'llm_call',\n TOOL_CALL = 'tool_call',\n RETRIEVAL = 'retrieval',\n DECISION = 'decision',\n MESSAGE = 'message',\n DELEGATION = 'delegation',\n COORDINATION = 'coordination',\n THINK = 'think',\n DECIDE = 'decide',\n OBSERVE = 'observe',\n REFLECT = 'reflect',\n}\n\n// ─── Span Status ─────────────────────────────────────────────────────────────\n\nexport enum SpanStatus {\n UNSET = 'unset',\n OK = 'ok',\n ERROR = 'error',\n}\n\n// ─── Semantic Phase (Tier 4: Decision Tracking) ──────────────────────────────\n\nexport enum SemanticPhase {\n THINK = 'think',\n DECIDE = 'decide',\n ACT = 'act',\n OBSERVE = 'observe',\n REFLECT = 'reflect',\n COMMUNICATE = 'communicate',\n COORDINATE = 'coordinate',\n}\n\n// ─── Agent Role ──────────────────────────────────────────────────────────────\n\nexport enum AgentRole {\n // Primary roles\n ORCHESTRATOR = 'orchestrator',\n WORKER = 'worker',\n SUPERVISOR = 'supervisor',\n SPECIALIST = 'specialist',\n // Communication roles\n ROUTER = 'router',\n AGGREGATOR = 'aggregator',\n BROADCASTER = 'broadcaster',\n // Specialized roles\n CRITIC = 'critic',\n PLANNER = 'planner',\n EXECUTOR = 'executor',\n RETRIEVER = 'retriever',\n VALIDATOR = 'validator',\n // JS-specific (backwards compatibility)\n REVIEWER = 'reviewer',\n CUSTOM = 'custom',\n}\n\n// ─── Message Type (Tier 5: Multi-Agent) ──────────────────────────────────────\n\nexport enum MessageType {\n // Control messages\n TASK = 'task',\n RESULT = 'result',\n STATUS = 'status',\n ERROR = 'error',\n // Communication messages\n QUERY = 'query',\n RESPONSE = 'response',\n BROADCAST = 'broadcast',\n DIRECT = 'direct',\n // Coordination messages\n PROPOSAL = 'proposal',\n VOTE = 'vote',\n CONSENSUS = 'consensus',\n CONFLICT = 'conflict',\n // Lifecycle messages\n HEARTBEAT = 'heartbeat',\n SHUTDOWN = 'shutdown',\n HANDOFF = 'handoff',\n // JS-specific (backwards compatibility)\n REQUEST = 'request',\n DELEGATE = 'delegate',\n COORDINATE = 'coordinate',\n}\n\n// ─── Span Event ──────────────────────────────────────────────────────────────\n\nexport interface SpanEvent {\n name: string;\n timestamp: string;\n attributes?: Record<string, unknown>;\n}\n\n// ─── Span Link ───────────────────────────────────────────────────────────────\n\nexport interface SpanLink {\n traceId: string;\n spanId: string;\n attributes?: Record<string, unknown>;\n}\n\n// ─── Span Payload (Wire Format) ──────────────────────────────────────────────\n// Matches Rust gateway SpanData struct exactly (camelCase)\n\nexport interface SpanPayload {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n kind: string;\n startTime: string;\n endTime?: string;\n durationMs?: number;\n status: string;\n statusMessage?: string;\n attributes: Record<string, unknown>;\n events: SpanEvent[];\n links: SpanLink[];\n sessionId?: string;\n agentId?: string;\n agentName?: string;\n agentType?: string;\n semanticPhase?: string;\n llmProvider?: string;\n llmModel?: string;\n llmPromptTokens?: number;\n llmCompletionTokens?: number;\n llmTotalTokens?: number;\n llmCostUsd?: number;\n toolName?: string;\n toolSuccess?: boolean;\n}\n\n// ─── Ingest Request ──────────────────────────────────────────────────────────\n\nexport interface IngestRequest {\n spans: SpanPayload[];\n batchId?: string;\n projectId?: string;\n environment?: string;\n}\n","/**\n * High-resolution timing and ISO 8601 formatting utilities.\n */\n\n/**\n * Get current time as ISO 8601 string with millisecond precision.\n */\nexport function nowISO(): string {\n return new Date().toISOString();\n}\n\n/**\n * Get high-resolution monotonic time in milliseconds.\n * Uses process.hrtime.bigint() for sub-ms precision.\n */\nexport function hrtimeMs(): number {\n return Number(process.hrtime.bigint()) / 1_000_000;\n}\n\n/**\n * Compute duration in milliseconds between two hrtime values.\n */\nexport function durationMs(startHrtime: number, endHrtime: number): number {\n return Math.max(0, endHrtime - startHrtime);\n}\n\n/**\n * Format a Date or ISO string to ISO 8601 with millisecond precision.\n */\nexport function toISO(time: Date | string | number): string {\n if (typeof time === 'string') return time;\n if (typeof time === 'number') return new Date(time).toISOString();\n return time.toISOString();\n}\n","/**\n * Span class — the core unit of tracing.\n *\n * A span represents a single operation (LLM call, tool use, agent step).\n * Spans are mutable: attributes, events, and status can be set after creation.\n * Call end() to finalize the span and trigger export.\n */\n\nimport { generateSpanId, generateTraceId } from './ids.js';\nimport {\n SpanKind,\n SpanStatus,\n type SpanEvent,\n type SpanLink,\n type SpanPayload,\n} from './types.js';\nimport { nowISO, hrtimeMs } from './utils/clock.js';\n\nexport interface SpanOptions {\n name: string;\n kind?: SpanKind;\n traceId?: string;\n spanId?: string;\n parentSpanId?: string;\n attributes?: Record<string, unknown>;\n links?: SpanLink[];\n sessionId?: string;\n agentId?: string;\n agentName?: string;\n agentType?: string;\n semanticPhase?: string;\n}\n\nexport type SpanEndCallback = (span: Span) => void;\n\nexport class Span {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId: string | undefined;\n readonly name: string;\n readonly kind: SpanKind;\n readonly startTime: string;\n readonly startHrtime: number;\n\n endTime: string | undefined;\n status: SpanStatus;\n statusMessage: string | undefined;\n attributes: Record<string, unknown>;\n events: SpanEvent[];\n links: SpanLink[];\n\n // Agent/session fields\n sessionId: string | undefined;\n agentId: string | undefined;\n agentName: string | undefined;\n agentType: string | undefined;\n semanticPhase: string | undefined;\n\n // LLM-specific fields\n llmProvider: string | undefined;\n llmModel: string | undefined;\n llmPromptTokens: number | undefined;\n llmCompletionTokens: number | undefined;\n llmTotalTokens: number | undefined;\n llmCostUsd: number | undefined;\n\n // Tool fields\n toolName: string | undefined;\n toolSuccess: boolean | undefined;\n\n private _ended = false;\n private _endHrtime: number | undefined;\n private _onEnd: SpanEndCallback | undefined;\n\n constructor(options: SpanOptions, onEnd?: SpanEndCallback) {\n this.traceId = options.traceId ?? generateTraceId();\n this.spanId = options.spanId ?? generateSpanId();\n this.parentSpanId = options.parentSpanId;\n this.name = options.name;\n this.kind = options.kind ?? SpanKind.INTERNAL;\n this.startTime = nowISO();\n this.startHrtime = hrtimeMs();\n\n this.status = SpanStatus.UNSET;\n this.attributes = options.attributes ? { ...options.attributes } : {};\n this.events = [];\n this.links = options.links ? [...options.links] : [];\n\n this.sessionId = options.sessionId;\n this.agentId = options.agentId;\n this.agentName = options.agentName;\n this.agentType = options.agentType;\n this.semanticPhase = options.semanticPhase;\n\n this._onEnd = onEnd;\n }\n\n get isEnded(): boolean {\n return this._ended;\n }\n\n get durationMs(): number {\n if (this._ended && this._endHrtime !== undefined) {\n return this._endHrtime - this.startHrtime;\n }\n return hrtimeMs() - this.startHrtime;\n }\n\n setAttribute(key: string, value: unknown): this {\n if (this._ended) return this;\n this.attributes[key] = value;\n return this;\n }\n\n setAttributes(attrs: Record<string, unknown>): this {\n if (this._ended) return this;\n Object.assign(this.attributes, attrs);\n return this;\n }\n\n setStatus(status: SpanStatus, message?: string): this {\n if (this._ended) return this;\n this.status = status;\n if (message !== undefined) {\n this.statusMessage = message;\n }\n return this;\n }\n\n addEvent(name: string, attributes?: Record<string, unknown>): this {\n if (this._ended) return this;\n this.events.push({\n name,\n timestamp: nowISO(),\n attributes,\n });\n return this;\n }\n\n addLink(traceId: string, spanId: string, attributes?: Record<string, unknown>): this {\n if (this._ended) return this;\n this.links.push({ traceId, spanId, attributes });\n return this;\n }\n\n recordException(error: Error | string): this {\n if (this._ended) return this;\n\n const message = typeof error === 'string' ? error : error.message;\n const stack = typeof error === 'string' ? undefined : error.stack;\n\n this.setStatus(SpanStatus.ERROR, message);\n this.addEvent('exception', {\n 'exception.type': typeof error === 'string' ? 'Error' : error.constructor.name,\n 'exception.message': message,\n ...(stack ? { 'exception.stacktrace': stack } : {}),\n });\n\n return this;\n }\n\n setLlmFields(fields: {\n provider?: string;\n model?: string;\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n costUsd?: number;\n }): this {\n if (this._ended) return this;\n if (fields.provider !== undefined) this.llmProvider = fields.provider;\n if (fields.model !== undefined) this.llmModel = fields.model;\n if (fields.promptTokens !== undefined) this.llmPromptTokens = fields.promptTokens;\n if (fields.completionTokens !== undefined) this.llmCompletionTokens = fields.completionTokens;\n if (fields.totalTokens !== undefined) this.llmTotalTokens = fields.totalTokens;\n if (fields.costUsd !== undefined) this.llmCostUsd = fields.costUsd;\n return this;\n }\n\n setToolFields(fields: { name?: string; success?: boolean }): this {\n if (this._ended) return this;\n if (fields.name !== undefined) this.toolName = fields.name;\n if (fields.success !== undefined) this.toolSuccess = fields.success;\n return this;\n }\n\n end(): void {\n if (this._ended) return;\n this._ended = true;\n this._endHrtime = hrtimeMs();\n this.endTime = nowISO();\n\n if (this.status === SpanStatus.UNSET) {\n this.status = SpanStatus.OK;\n }\n\n this._onEnd?.(this);\n }\n\n /**\n * Serialize to the wire format expected by the Rust gateway.\n */\n toPayload(): SpanPayload {\n const payload: SpanPayload = {\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: this.attributes,\n events: this.events,\n links: this.links,\n };\n\n if (this.parentSpanId !== undefined) payload.parentSpanId = this.parentSpanId;\n if (this.endTime !== undefined) payload.endTime = this.endTime;\n if (this._ended) payload.durationMs = this.durationMs;\n if (this.statusMessage !== undefined) payload.statusMessage = this.statusMessage;\n if (this.sessionId !== undefined) payload.sessionId = this.sessionId;\n if (this.agentId !== undefined) payload.agentId = this.agentId;\n if (this.agentName !== undefined) payload.agentName = this.agentName;\n if (this.agentType !== undefined) payload.agentType = this.agentType;\n if (this.semanticPhase !== undefined) payload.semanticPhase = this.semanticPhase;\n if (this.llmProvider !== undefined) payload.llmProvider = this.llmProvider;\n if (this.llmModel !== undefined) payload.llmModel = this.llmModel;\n if (this.llmPromptTokens !== undefined) payload.llmPromptTokens = this.llmPromptTokens;\n if (this.llmCompletionTokens !== undefined) payload.llmCompletionTokens = this.llmCompletionTokens;\n if (this.llmTotalTokens !== undefined) payload.llmTotalTokens = this.llmTotalTokens;\n if (this.llmCostUsd !== undefined) payload.llmCostUsd = this.llmCostUsd;\n if (this.toolName !== undefined) payload.toolName = this.toolName;\n if (this.toolSuccess !== undefined) payload.toolSuccess = this.toolSuccess;\n\n return payload;\n }\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 * Head-based deterministic sampling.\n *\n * Uses the first 8 hex characters of the trace ID as a hash\n * to make a deterministic sampling decision. This ensures:\n * - Same trace ID always produces the same decision\n * - Consistent across Python and JS/TS SDKs\n * - No external state needed\n */\n\n/**\n * Determine whether a trace should be sampled.\n *\n * @param traceId - 32-character hex trace ID\n * @param sampleRate - Rate between 0.0 (none) and 1.0 (all)\n * @returns true if the trace should be sampled\n */\nexport function shouldSample(traceId: string, sampleRate: number): boolean {\n if (sampleRate >= 1.0) return true;\n if (sampleRate <= 0.0) return false;\n\n // Parse first 8 hex chars as unsigned 32-bit integer\n const hash = parseInt(traceId.substring(0, 8), 16);\n return (hash / 0xFFFFFFFF) < sampleRate;\n}\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 endpoint URL (e.g., \"https://app.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// Verify: scripts/contracts/lint-taxonomy-parity.sh\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// 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/** Order matters: first match wins, most specific first. */\nexport const SUPPLEMENTAL_RULES: readonly TaxonomyRule[] = [\n { re: new RegExp(\"timeout|timedout|aborted\", 'i'), code: \"TOOL.EXECUTION.TIMEOUT\" },\n { re: new RegExp(\"rate.?limit|\\\\b429\\\\b|too many requests\", 'i'), code: \"TOOL.EXECUTION.RATE_LIMITED\" },\n { re: new RegExp(\"connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe\", 'i'), code: \"TOOL.EXECUTION.DEPENDENCY_FAILED\" },\n { re: new RegExp(\"\\\\bauth|unauthorized|forbidden|permission|\\\\b401\\\\b|\\\\b403\\\\b\", 'i'), code: \"TOOL.INVOCATION.PERMISSION_DENIED\" },\n { re: new RegExp(\"json|syntaxerror|unexpected token|decodeerror\", 'i'), code: \"PERCEPTION.PARSING.JSON_INVALID\" },\n];\n\nexport const GENERIC_FALLBACK = \"TOOL.EXECUTION.CRASHED\";\n","/**\n * Fix Interceptors — Hook into LLM/tool calls to apply fixes.\n *\n * Interceptors are registered with the runtime and called during agent\n * execution to apply relevant fixes at three interception points:\n * - preCall: Before the LLM/tool call (prompt/parameter/fallback fixes)\n * - postCall: After the call (output guard validation)\n * - onError: When an error occurs (retry/fallback decisions)\n *\n * Port of Python SDK's runtime/interceptors.py adapted for Node.js.\n */\n\nimport type { ApplyResult } from './applier.js';\nimport { FixApplier } from './applier.js';\nimport type { FixCache } from './cache.js';\nimport type { FixRuntimeConfig } from './config.js';\nimport { resolveFixRuntimeConfig } from './config.js';\nimport { debug, warn } from '../utils/log.js';\nimport {\n CANONICAL_ERROR_CODES,\n GENERIC_FALLBACK,\n SUPPLEMENTAL_RULES,\n} from './taxonomy.generated.js';\n\n// ─── Guard Rejection ────────────────────────────────────────────────────────\n\n/**\n * Thrown by the fix interceptor when a guard fix returns `passed: false`.\n *\n * PR-4+5 review B2 (2026-05-25): pre-fix, `applyGuardFix` returned\n * `passed:false` correctly but no caller read `passed` — the provider\n * patcher consumed `result.messages` / `result.params` and proceeded to the\n * LLM with the attacker payload anyway. The `fail-CLOSED` was advisory only.\n *\n * Now the interceptor THROWS this error on both pre-call and post-call\n * guard rejection. The provider patcher's surrounding span.startSpan\n * already catches and records exceptions, so the customer sees a\n * `GuardRejectedError` propagated out of their `openai.chat.completions.create`\n * call — the LLM is NEVER invoked.\n *\n * Customers who want to handle rejection gracefully can:\n * try { await openai.chat.completions.create({ ... }); }\n * catch (e) {\n * if (e instanceof GuardRejectedError) { ... fallback ... }\n * else throw e;\n * }\n */\nexport class GuardRejectedError extends Error {\n public readonly guardId: string;\n public readonly reason: string;\n public readonly phase: 'pre_call' | 'post_call';\n\n constructor(guardId: string, reason: string, phase: 'pre_call' | 'post_call') {\n super(`Risicare guard rejected operation: ${guardId} (${phase}) — ${reason}`);\n this.name = 'GuardRejectedError';\n this.guardId = guardId;\n this.reason = reason;\n this.phase = phase;\n }\n}\n\n// ─── Intercept Context ──────────────────────────────────────────────────────\n\nexport interface InterceptContext {\n /** Type of operation: \"llm_call\", \"tool_call\", \"agent_delegate\" */\n operationType: string;\n\n /** Name of the operation: model name, tool name, agent name */\n operationName: string;\n\n /** Session ID for A/B testing bucketing */\n sessionId?: string;\n\n /** Trace ID for correlation */\n traceId?: string;\n\n /** Error code (set when retrying after error) */\n errorCode?: string;\n\n /** Error message (set when retrying after error) */\n errorMessage?: string;\n\n /** Current attempt number (1-based) */\n attempt: number;\n\n /** Fixes applied during this intercept lifecycle */\n appliedFixes: ApplyResult[];\n}\n\n/** Create a fresh InterceptContext. */\nexport function createInterceptContext(\n operationType: string,\n operationName: string,\n options?: {\n sessionId?: string;\n traceId?: string;\n errorCode?: string;\n },\n): InterceptContext {\n return {\n operationType,\n operationName,\n sessionId: options?.sessionId,\n traceId: options?.traceId,\n errorCode: options?.errorCode,\n attempt: 1,\n appliedFixes: [],\n };\n}\n\n// ─── Interceptor Interface ──────────────────────────────────────────────────\n\nexport interface FixInterceptor {\n /**\n * Called before an LLM/tool call.\n * Returns modified messages and params.\n */\n preCall(\n ctx: InterceptContext,\n messages: unknown[] | null,\n params: Record<string, unknown>,\n ): { messages: unknown[] | null; params: Record<string, unknown> };\n\n /**\n * Called after an LLM/tool call.\n * Returns modified response and whether to continue.\n */\n postCall(\n ctx: InterceptContext,\n response: unknown,\n ): { response: unknown; shouldContinue: boolean };\n\n /**\n * Called when an error occurs.\n * Returns whether to retry and optional modified params.\n */\n onError(\n ctx: InterceptContext,\n error: Error,\n ): { shouldRetry: boolean; modifiedParams: Record<string, unknown> | null };\n}\n\n// ─── Default Fix Interceptor ────────────────────────────────────────────────\n\nexport class DefaultFixInterceptor implements FixInterceptor {\n private readonly _config: Required<FixRuntimeConfig>;\n private readonly _cache: FixCache;\n private readonly _applier: FixApplier;\n\n constructor(config: FixRuntimeConfig, cache: FixCache, applier: FixApplier) {\n this._config = resolveFixRuntimeConfig(config);\n this._cache = cache;\n this._applier = applier;\n }\n\n /**\n * Apply pre-call fixes.\n *\n * - If retrying after error: look up fix by error_code, apply\n * prompt/parameter/fallback fixes\n * - Runs input guard fixes on all message content\n */\n preCall(\n ctx: InterceptContext,\n messages: unknown[] | null,\n params: Record<string, unknown>,\n ): { messages: unknown[] | null; params: Record<string, unknown> } {\n try {\n if (!this._config.enabled) {\n return { messages, params };\n }\n\n let modifiedMessages = messages;\n let modifiedParams = { ...params };\n\n // If retrying after error, check for applicable fixes\n if (ctx.errorCode) {\n const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);\n\n if (fix) {\n debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);\n\n if (fix.fixType === 'prompt' && messages) {\n const msgRecords = messages as Record<string, unknown>[];\n const { messages: newMessages, result } =\n this._applier.applyPromptFix(fix, msgRecords);\n modifiedMessages = newMessages;\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n } else if (fix.fixType === 'parameter') {\n const { params: newParams, result } =\n this._applier.applyParameterFix(fix, modifiedParams);\n modifiedParams = newParams;\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n } else if (fix.fixType === 'fallback') {\n const { params: newParams, result } =\n this._applier.applyFallbackFix(fix, modifiedParams);\n modifiedParams = newParams;\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n }\n }\n }\n\n // Apply input guard fixes on all message content.\n // PR-4+5 review B2: when a guard returns passed:false (including the\n // F-731 fail-CLOSED-on-exception path), THROW a GuardRejectedError so\n // the provider patcher short-circuits BEFORE invoking the LLM. The\n // outer try/catch below explicitly re-raises GuardRejectedError so\n // the swallow-and-degrade behaviour for OTHER errors does NOT apply\n // to safety rejections.\n if (modifiedMessages && this._config.enabled) {\n for (const msg of modifiedMessages as Record<string, unknown>[]) {\n const content = msg.content;\n if (typeof content === 'string') {\n for (const fix of this._cache.getAll()) {\n if (fix.fixType === 'guard') {\n const { passed, result } = this._applier.applyGuardFix(\n fix,\n content,\n true,\n );\n if (result.applied) {\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n }\n if (!passed) {\n throw new GuardRejectedError(\n fix.fixId ?? 'unknown',\n result.reason ?? 'guard rejected input',\n 'pre_call',\n );\n }\n }\n }\n }\n }\n }\n\n return { messages: modifiedMessages, params: modifiedParams };\n } catch (e) {\n // PR-4+5 review B2: GuardRejectedError MUST propagate. The catch\n // below exists for unrelated failures (e.g., cache lookup explosion)\n // where degrading to the unmodified call is correct — but a safety\n // rejection MUST abort the LLM call, not silently let it through.\n if (e instanceof GuardRejectedError) throw e;\n debug(`DefaultFixInterceptor.preCall error: ${e}`);\n return { messages, params };\n }\n }\n\n /**\n * Apply post-call fixes (output validation).\n *\n * Runs output guard fixes on response content.\n */\n postCall(\n ctx: InterceptContext,\n response: unknown,\n ): { response: unknown; shouldContinue: boolean } {\n try {\n if (!this._config.enabled) {\n return { response, shouldContinue: true };\n }\n\n for (const fix of this._cache.getAll()) {\n if (fix.fixType !== 'guard') continue;\n\n const content = this._extractResponseContent(response);\n if (!content) continue;\n\n const { passed, result } = this._applier.applyGuardFix(\n fix,\n content,\n false,\n );\n\n if (result.applied) {\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n }\n\n if (!passed) {\n // PR-4+5 review B2: output guard failure must NOT be a warn-only\n // signal. Pre-fix the caller received the unredacted LLM response\n // alongside shouldContinue:true — the rejection was advisory only.\n // Now we throw GuardRejectedError so the caller surfaces the\n // safety violation to the customer instead of returning a payload\n // an output filter said is unsafe to emit.\n warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? 'unknown'}`);\n throw new GuardRejectedError(\n fix.fixId ?? 'unknown',\n result.reason ?? 'guard rejected output',\n 'post_call',\n );\n }\n }\n\n return { response, shouldContinue: true };\n } catch (e) {\n // PR-4+5 review B2: GuardRejectedError MUST propagate (see preCall).\n if (e instanceof GuardRejectedError) throw e;\n debug(`DefaultFixInterceptor.postCall error: ${e}`);\n return { response, shouldContinue: true };\n }\n }\n\n /**\n * Handle errors and decide whether to retry.\n *\n * Classifies the error, looks up retry/fallback fixes, and returns\n * whether the caller should retry.\n */\n onError(\n ctx: InterceptContext,\n error: Error,\n ): { shouldRetry: boolean; modifiedParams: Record<string, unknown> | null } {\n try {\n if (!this._config.enabled) {\n return { shouldRetry: false, modifiedParams: null };\n }\n\n // Classify the error\n const errorCode = classifyError(error);\n ctx.errorCode = errorCode;\n ctx.errorMessage = error.message;\n\n // Check for retry fix\n const fix = this._applier.getFixForError(errorCode, ctx.sessionId);\n if (!fix) {\n return { shouldRetry: false, modifiedParams: null };\n }\n\n if (fix.fixType === 'retry') {\n const maxRetries = (fix.config.max_retries ?? fix.config.maxRetries ?? 3) as number;\n\n if (ctx.attempt <= maxRetries) {\n debug(\n `Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`,\n );\n\n const result: ApplyResult = {\n applied: true,\n fixId: fix.fixId,\n deploymentId: fix.deploymentId,\n fixType: 'retry',\n modifications: { attempt: ctx.attempt },\n };\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n\n return { shouldRetry: true, modifiedParams: null };\n }\n }\n\n // Check for fallback fix\n if (fix.fixType === 'fallback') {\n const { params: modifiedParams, result } =\n this._applier.applyFallbackFix(fix, {});\n if (result.applied) {\n ctx.appliedFixes.push(result);\n this._applier.logApplication(result);\n return { shouldRetry: true, modifiedParams };\n }\n }\n\n return { shouldRetry: false, modifiedParams: null };\n } catch (e) {\n debug(`DefaultFixInterceptor.onError error: ${e}`);\n return { shouldRetry: false, modifiedParams: null };\n }\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n /** Extract text content from a response object. */\n private _extractResponseContent(response: unknown): string | null {\n if (typeof response === 'string') return response;\n\n if (response && typeof response === 'object') {\n const resp = response as Record<string, unknown>;\n\n // OpenAI-style response: { choices: [{ message: { content: \"...\" } }] }\n const choices = resp.choices as unknown[];\n if (Array.isArray(choices) && choices.length > 0) {\n const first = choices[0] as Record<string, unknown>;\n const message = first?.message as Record<string, unknown>;\n if (typeof message?.content === 'string') {\n return message.content;\n }\n }\n\n // Anthropic-style response: { content: [{ text: \"...\" }] }\n const content = resp.content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content) && content.length > 0) {\n const first = content[0] as Record<string, unknown>;\n if (typeof first?.text === 'string') return first.text;\n }\n }\n\n return null;\n }\n}\n\n// ─── Error Classification ───────────────────────────────────────────────────\n\n/**\n * Classify an error into an error code.\n *\n * Simple heuristic classification. In production, this would use the full\n * taxonomy from risicare-core (10 modules, 35+ categories).\n */\nexport function classifyError(error: Error): string {\n // F-SDKTAXFORK-001 — this used to be a private six-code vocabulary of which\n // exactly ONE code existed in the canonical 154-code taxonomy (measured\n // 2026-08-17: RATE_LIMIT vs canonical RATE_LIMITED, JSON_INVALID vs\n // INVALID_JSON, and three with no canonical sibling at all). The Python SDK\n // carried a byte-identical fork of the same wrong set.\n //\n // The rules and the canonical code set now come from ONE source\n // (packages/risicare-sdk/src/risicare/runtime/_error_taxonomy.py) and are\n // GENERATED into ./taxonomy.generated.ts, because `risicare-core` is not on\n // npm and this SDK cannot import the taxonomy directly. Drift is caught by\n // scripts/contracts/lint-taxonomy-parity.sh.\n //\n // Every code below is checked against CANONICAL_ERROR_CODES before it is\n // returned, so an invented code cannot reach the wire even if this file and\n // the generator ever disagree.\n const haystack = `${error?.constructor?.name ?? 'Error'} ${error?.message ?? ''}`;\n\n for (const rule of SUPPLEMENTAL_RULES) {\n // RegExp objects carry lastIndex state only with /g; these are built\n // without it, so .test() is safe to reuse across calls.\n if (rule.re.test(haystack)) {\n return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;\n }\n }\n\n return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : '';\n}\n","/**\n * AsyncLocalStorage-based context propagation.\n *\n * Uses a single AsyncLocalStorage instance with a composite state object.\n * This is simpler and more performant than multiple separate stores.\n *\n * Node.js AsyncLocalStorage automatically propagates through:\n * - Promise / async-await\n * - setTimeout / setImmediate\n * - EventEmitter callbacks\n * - process.nextTick\n * - async generators (unlike Python's contextvars!)\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Span } from '../span.js';\nimport type { SemanticPhase } from '../types.js';\nimport { getContextStorage } from '../globals.js';\n\n// ─── Context Types ───────────────────────────────────────────────────────────\n\nexport interface SessionContext {\n sessionId: string;\n userId?: string;\n metadata?: Record<string, unknown>;\n parentSessionId?: string;\n turnNumber?: number;\n}\n\nexport interface AgentContext {\n agentId: string;\n agentName?: string;\n agentRole?: string;\n agentType?: string;\n parentAgentId?: string;\n version?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface ContextState {\n session?: SessionContext;\n agent?: AgentContext;\n span?: Span;\n phase?: SemanticPhase;\n /** When true, provider instrumentors skip span creation (framework is handling it). */\n _suppressProviderInstrumentation?: boolean;\n /**\n * Pre-allocated trace ID from getTraceContext() when no span exists yet.\n * Ensures that getTraceContext().traceId matches the next span created\n * in this context — preventing the \"trace ID mismatch\" bug.\n */\n _rootTraceId?: string;\n /**\n * F-SDKSAMPORPHAN-001 — the trace's head-sampling decision, recorded ONLY\n * when it was `false`.\n *\n * A dropped root creates no Span, so `span` above stays undefined and every\n * nested call looks like a fresh root to the tracer. Without this flag it\n * re-rolls its own decision and the half that passes is delivered as a\n * root — a trace that never existed. This is the only carrier of \"you are\n * inside a trace we already decided to drop\".\n *\n * Scoped by runWithContext(), so unlike Python's ContextVar token it cannot\n * leak past the callback that set it.\n */\n _traceSampled?: boolean;\n}\n\n// ─── Storage Accessor ────────────────────────────────────────────────────────\n\nfunction storage(): AsyncLocalStorage<ContextState> {\n return getContextStorage() as AsyncLocalStorage<ContextState>;\n}\n\n// ─── Core Operations ─────────────────────────────────────────────────────────\n\n/**\n * Get the current context state, or empty object if outside any context.\n */\nexport function getContext(): ContextState {\n return storage().getStore() ?? {};\n}\n\n/**\n * Run a callback within a new context scope.\n * The new scope inherits from the parent, with overrides applied.\n */\nexport function runWithContext<T>(overrides: Partial<ContextState>, fn: () => T): T {\n const parent = getContext();\n const merged: ContextState = { ...parent, ...overrides };\n return storage().run(merged, fn);\n}\n\n/**\n * Run an async callback within a new context scope.\n */\nexport function runWithContextAsync<T>(overrides: Partial<ContextState>, fn: () => Promise<T>): Promise<T> {\n const parent = getContext();\n const merged: ContextState = { ...parent, ...overrides };\n return storage().run(merged, fn);\n}\n\n// ─── Context Accessors ───────────────────────────────────────────────────────\n\nexport function getCurrentSession(): SessionContext | undefined {\n return getContext().session;\n}\n\nexport function getCurrentAgent(): AgentContext | undefined {\n return getContext().agent;\n}\n\nexport function getCurrentSpan(): Span | undefined {\n return getContext().span;\n}\n\nexport function getCurrentPhase(): SemanticPhase | undefined {\n return getContext().phase;\n}\n\nexport function getCurrentSessionId(): string | undefined {\n return getContext().session?.sessionId;\n}\n\nexport function getCurrentAgentId(): string | undefined {\n return getContext().agent?.agentId;\n}\n\nexport function getCurrentTraceId(): string | undefined {\n return getContext().span?.traceId;\n}\n\nexport function getCurrentSpanId(): string | undefined {\n return getContext().span?.spanId;\n}\n\nexport function getCurrentParentSpanId(): string | undefined {\n return getContext().span?.parentSpanId;\n}\n\n/**\n * Get all current context as a plain object (for debugging/serialization).\n */\nexport function getCurrentContext(): Record<string, unknown> {\n const ctx = getContext();\n return {\n session: ctx.session ? {\n sessionId: ctx.session.sessionId,\n userId: ctx.session.userId,\n ...(ctx.session.parentSessionId !== undefined ? { parentSessionId: ctx.session.parentSessionId } : {}),\n ...(ctx.session.turnNumber !== undefined ? { turnNumber: ctx.session.turnNumber } : {}),\n ...(ctx.session.metadata !== undefined ? { metadata: ctx.session.metadata } : {}),\n } : null,\n agent: ctx.agent ? {\n agentId: ctx.agent.agentId,\n agentName: ctx.agent.agentName,\n agentRole: ctx.agent.agentRole,\n agentType: ctx.agent.agentType,\n ...(ctx.agent.parentAgentId !== undefined ? { parentAgentId: ctx.agent.parentAgentId } : {}),\n ...(ctx.agent.version !== undefined ? { version: ctx.agent.version } : {}),\n ...(ctx.agent.metadata !== undefined ? { metadata: ctx.agent.metadata } : {}),\n } : null,\n span: ctx.span ? { spanId: ctx.span.spanId, traceId: ctx.span.traceId } : null,\n phase: ctx.phase ?? null,\n };\n}\n","/**\n * Tracer — creates spans with automatic context nesting.\n *\n * The Tracer is the primary API for creating spans. It automatically:\n * - Links child spans to parent spans via parentSpanId\n * - Propagates the trace ID from the active context\n * - Injects session/agent/phase context into new spans\n * - Runs the callback within the span's context scope\n *\n * Usage:\n * const tracer = new Tracer(processor);\n * await tracer.startSpan('my-operation', async (span) => {\n * span.setAttribute('key', 'value');\n * // Nested spans automatically become children\n * await tracer.startSpan('sub-op', async (child) => { ... });\n * });\n */\n\nimport { Span, type SpanOptions, type SpanEndCallback } from './span.js';\nimport { NOOP_SPAN } from './noop.js';\nimport { SpanKind } from './types.js';\nimport { generateTraceId } from './ids.js';\nimport { shouldSample } from './utils/sampling.js';\nimport { classifyError } from './runtime/interceptors.js';\nimport {\n runWithContext,\n getContext,\n getCurrentSpan,\n getCurrentSession,\n getCurrentAgent,\n getCurrentPhase,\n} from './context/storage.js';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport interface StartSpanOptions {\n name: string;\n kind?: SpanKind;\n attributes?: Record<string, unknown>;\n /** Override trace ID (default: inherit from parent or generate new) */\n traceId?: string;\n /** Override parent span ID (default: current span in context) */\n parentSpanId?: string;\n}\n\nexport interface TracerConfig {\n /** Called when a span ends (typically feeds into batch processor) */\n onSpanEnd: SpanEndCallback;\n /** Sample rate 0.0–1.0 (default: 1.0) */\n sampleRate?: number;\n /** Whether tracing is enabled */\n enabled?: boolean;\n /**\n * Whether prompt/completion content may leave the process (default: false).\n *\n * ⚠ The Tracer only CARRIES this for the provider patches to read via\n * `getTraceContent()`. It is NOT the enforcement point — the gate runs in the\n * batch processor, which is the one place both content paths cross. See\n * `masking.ts` `stripContent`.\n */\n traceContent?: boolean;\n /**\n * Service name, emitted as the OTel `service.name` span attribute.\n *\n * ⚠ F-SDKJSSVCNAME-001. `serviceName` was accepted by `init()`, typed in\n * `RisicareConfig`, documented, and recommended over the deprecated\n * `projectId` — and reached the wire NOWHERE. Measured on the published\n * 0.5.0: `serviceName: 'X'` at init, `X` absent from every request body,\n * while a sibling control attribute in the same span arrived. Python has\n * always emitted it (`tracer.py`, `service.name`); this makes JS match.\n */\n serviceName?: string;\n /**\n * Service version, emitted as `service.version`.\n *\n * ⚠ Was dropped by BOTH SDKs — same defect one field over, measured in the\n * same run. Unlike `service.name` it is NOT suppressed under an agent: a\n * version is a property of the deployed code, not of which agent owns the\n * span.\n */\n serviceVersion?: string;\n}\n\n/**\n * F-SDKTAXFORK-001 — attach the canonical taxonomy code to EVERY errored span,\n * whether or not a fix was applied.\n *\n * ⚠ The \"whether or not\" clause is the load-bearing one.\n * `risicare.fix.error_code` is written only inside the branch that also sets\n * `risicare.fix.applied` (providers/openai/patch.ts), so a span carrying an\n * error code has ALWAYS had a non-empty fix_applied — which makes the A/B\n * CONTROL predicate `fix_applied = '' AND error_code = X` unsatisfiable by\n * algebra, not merely empty. Emitting here is what makes that cohort populable.\n *\n * The worker already reads this key and has since before any producer existed\n * (`spans_worker.py:3744` — `risicare.fix.error_code` OR `error.code`; its own\n * comment calls it \"generic taxonomy code attached by any error\"). This is\n * attribute-first per .claude/rules/schema-contract.md: no gateway or worker\n * change is required.\n *\n * Guarded throughout: classification must never replace the customer's own\n * exception with ours, and must never write an empty attribute.\n */\nexport function attachErrorCode(span: Span, error: unknown): void {\n try {\n const err = error instanceof Error ? error : new Error(String(error));\n const code = classifyError(err);\n if (code) {\n span.setAttribute('error.code', code);\n }\n } catch {\n /* never let attribution break the customer's error path */\n }\n}\n\n// ─── Tracer Class ───────────────────────────────────────────────────────────\n\nexport class Tracer {\n private _onSpanEnd: SpanEndCallback;\n private _sampleRate: number;\n private _enabled: boolean;\n private _traceContent: boolean;\n private _serviceName: string | undefined;\n private _serviceVersion: string | undefined;\n\n constructor(config: TracerConfig) {\n this._onSpanEnd = config.onSpanEnd;\n this._sampleRate = config.sampleRate ?? 1.0;\n this._enabled = config.enabled ?? true;\n this._traceContent = config.traceContent ?? false;\n // Empty string is what `resolveConfig` uses for \"unset\" — treat it as unset\n // rather than emitting `service.name: \"\"`, which is worse than absent.\n this._serviceName = config.serviceName || undefined;\n this._serviceVersion = config.serviceVersion || undefined;\n }\n\n get enabled(): boolean {\n return this._enabled;\n }\n\n set enabled(value: boolean) {\n this._enabled = value;\n }\n\n get traceContent(): boolean {\n return this._traceContent;\n }\n\n /**\n * Start a span, run the callback within its context, and auto-end on completion.\n *\n * The span is automatically:\n * - Linked to the current parent span (if any)\n * - Given the current trace ID (or a new one for root spans)\n * - Enriched with session/agent/phase context\n * - Ended when the callback returns (or throws)\n * - Marked as ERROR if the callback throws\n *\n * @returns The callback's return value\n */\n startSpan<T>(options: StartSpanOptions | string, fn: (span: Span) => T): T {\n const opts = typeof options === 'string' ? { name: options } : options;\n\n // Fast path: disabled SDK\n if (!this._enabled) {\n return fn(NOOP_SPAN as unknown as Span);\n }\n\n // Resolve context\n const parentSpan = getCurrentSpan();\n const session = getCurrentSession();\n const agent = getCurrentAgent();\n const phase = getCurrentPhase();\n\n // Determine trace ID: explicit > parent > pre-allocated (from getTraceContext) > new\n const ctx = getContext();\n const traceId = opts.traceId ?? parentSpan?.traceId ?? ctx._rootTraceId ?? generateTraceId();\n\n // Sampling: check once per trace (root span decides)\n //\n // F-SDKSAMPORPHAN-001 — CONSULT BEFORE ROLLING. A dropped root creates no\n // Span, so `getCurrentSpan()` stays undefined and every nested call\n // arrives here as though it were itself a root. Re-rolling there does not\n // subsample; it FABRICATES. Measured pre-fix from an installed 0.5.1\n // tarball, N=400 roots each wrapping one nested startSpan, sampleRate=0.5:\n // ESM 104 of 303 delivered traces (34.3%) and CJS 94 of 310 (30.3%)\n // contained no root span — they never existed as traces. Both arms at\n // sampleRate=1.0 fabricated 0 of 400.\n // ⚠ Downstream cannot repair this: the delivered count is N*r*(2-r), not\n // N*r, so scaling by 1/r overstates by 50% at r=0.5 and 90% at r=0.1.\n if (!parentSpan) {\n if (ctx._traceSampled === false) {\n return fn(NOOP_SPAN as unknown as Span);\n }\n if (this._sampleRate < 1.0 && !shouldSample(traceId, this._sampleRate)) {\n // Record the drop for the duration of the callback so nested calls\n // inherit it. runWithContext scopes the flag to exactly this callback,\n // so it cannot latch the way an un-reset ContextVar token can.\n return runWithContext({ _traceSampled: false }, () =>\n fn(NOOP_SPAN as unknown as Span),\n );\n }\n }\n\n // Parent span ID: explicit > current span in context\n const parentSpanId = opts.parentSpanId ?? parentSpan?.spanId;\n\n // Create the span\n const spanOptions: SpanOptions = {\n name: opts.name,\n kind: opts.kind ?? SpanKind.INTERNAL,\n traceId,\n parentSpanId,\n attributes: {\n ...opts.attributes,\n // Propagate context fields as attributes (matching Python SDK tracer.py:497-511)\n ...(agent?.agentRole ? { 'agent.role': agent.agentRole } : {}),\n ...(agent?.parentAgentId ? { 'parent_agent_id': agent.parentAgentId } : {}),\n ...(session?.userId ? { 'session.user_id': session.userId } : {}),\n // F-SDKJSSVCNAME-001 — `service.name` is suppressed when an agent\n // identity is present (the agent takes priority), matching Python;\n // `service.version` never is.\n ...(this._serviceName && !agent ? { 'service.name': this._serviceName } : {}),\n ...(this._serviceVersion ? { 'service.version': this._serviceVersion } : {}),\n },\n sessionId: session?.sessionId,\n agentId: agent?.agentId,\n agentName: agent?.agentName,\n agentType: agent?.agentType,\n semanticPhase: phase,\n };\n\n const span = new Span(spanOptions, this._onSpanEnd);\n\n // Run callback within span context\n try {\n const result = runWithContext({ span }, () => fn(span));\n\n // Handle async results (Promises)\n if (result instanceof Promise) {\n return result.then(\n (value) => {\n span.end();\n return value;\n },\n (error) => {\n span.recordException(error instanceof Error ? error : String(error));\n attachErrorCode(span, error);\n span.end();\n throw error;\n },\n ) as T;\n }\n\n // Sync: end span immediately\n span.end();\n return result;\n } catch (error) {\n // Sync error: record and re-throw\n span.recordException(error instanceof Error ? error : String(error));\n attachErrorCode(span, error);\n span.end();\n throw error;\n }\n }\n\n /**\n * Create a span without auto-ending. Caller is responsible for calling span.end().\n *\n * Useful for long-running operations where you need manual control.\n * The span is still linked to context and enriched with session/agent/phase.\n */\n createSpan(options: StartSpanOptions | string): Span {\n const opts = typeof options === 'string' ? { name: options } : options;\n\n if (!this._enabled) {\n return NOOP_SPAN as unknown as Span;\n }\n\n const parentSpan = getCurrentSpan();\n const session = getCurrentSession();\n const agent = getCurrentAgent();\n const phase = getCurrentPhase();\n\n const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();\n\n // F-SDKSAMPORPHAN-001 — see the sibling site in startSpan(). Measured\n // pre-fix on this path (createSpan nested inside a startSpan root, the\n // streaming pattern), N=400, sampleRate=0.5: ESM 111 of 296 fabricated\n // (37.5%), CJS 105 of 294 (35.7%); both 0 of 400 at sampleRate=1.0.\n // ⚠ This site CONSULTS but does not RECORD: createSpan hands the span's\n // lifetime to the caller and owns no callback scope to unwind in, so\n // recording here would latch `_traceSampled` for the rest of the enclosing\n // context. Documented bound: a createSpan root that is itself dropped does\n // not suppress a re-roll by a following createSpan.\n if (!parentSpan) {\n if (getContext()._traceSampled === false) {\n return NOOP_SPAN as unknown as Span;\n }\n if (this._sampleRate < 1.0 && !shouldSample(traceId, this._sampleRate)) {\n return NOOP_SPAN as unknown as Span;\n }\n }\n\n const parentSpanId = opts.parentSpanId ?? parentSpan?.spanId;\n\n return new Span(\n {\n name: opts.name,\n kind: opts.kind ?? SpanKind.INTERNAL,\n traceId,\n parentSpanId,\n attributes: {\n ...opts.attributes,\n // Propagate context fields as attributes (matching Python SDK tracer.py:497-511)\n ...(agent?.agentRole ? { 'agent.role': agent.agentRole } : {}),\n ...(agent?.parentAgentId ? { 'parent_agent_id': agent.parentAgentId } : {}),\n ...(session?.userId ? { 'session.user_id': session.userId } : {}),\n // F-SDKJSSVCNAME-001 — see the sibling site above.\n ...(this._serviceName && !agent ? { 'service.name': this._serviceName } : {}),\n ...(this._serviceVersion ? { 'service.version': this._serviceVersion } : {}),\n },\n sessionId: session?.sessionId,\n agentId: agent?.agentId,\n agentName: agent?.agentName,\n agentType: agent?.agentType,\n semanticPhase: phase,\n },\n this._onSpanEnd,\n );\n }\n}\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.6.0';\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 * - Gzip compression for large payloads\n * - Bearer token authentication\n */\n\nimport type { Span } from '../span.js';\nimport type { IngestRequest } from '../types.js';\nimport { ExportResult, type SpanExporter } from './base.js';\nimport { debug, warn } from '../utils/log.js';\nimport { SDK_VERSION } from '../version.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\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 /**\n * F-SDK503-001. Set by `_sendRequest` when a response is a CAPACITY REFUSAL, read by the\n * retry loop and the breaker. `null` = not a refusal; `REFUSAL_NO_HINT` = refused with no\n * `Retry-After`; otherwise the honoured delay in ms.\n *\n * ⚠ Node has ONE thread and `export()` is `async`, so two concurrent exports interleave on\n * this field at every `await`. It is written immediately after the awaited `fetch` resolves\n * and read on the very next statement, with no `await` between — so the value cannot be\n * clobbered mid-decision. The Python twin carries the same per-call state on `self` for the\n * same reason (its `_send_request` signature is pin-locked).\n */\n private _lastRefusalAfterMs: number | null = null;\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 }\n\n async export(spans: Span[]): Promise<ExportResult> {\n if (spans.length === 0) return ExportResult.SUCCESS;\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 const body: IngestRequest = {\n spans: spans.map((s) => s.toPayload()),\n };\n if (this._projectId) body.projectId = this._projectId;\n if (this._environment) body.environment = this._environment;\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 this._lastRefusalAfterMs = null;\n const result = await this._sendRequest(body);\n\n if (result === ExportResult.SUCCESS) {\n this._consecutiveFailures = 0;\n return result;\n }\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 = this._lastRefusalAfterMs;\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);\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 const refusedForCapacity = this._lastRefusalAfterMs !== null;\n this._lastRefusalAfterMs = null;\n if (refusedForCapacity) {\n warn(\n `Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ` +\n `${maxAttempts} attempt(s). This is a healthy server shedding load, not an outage — ` +\n `the batch is dropped but the exporter keeps sending. Reduce batch size or export ` +\n `rate if it persists.`\n );\n return ExportResult.FAILURE;\n }\n\n // All retries failed — update circuit breaker\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 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(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 this._lastRefusalAfterMs = delay;\n debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);\n return true;\n }\n\n private async _sendRequest(body: IngestRequest): Promise<ExportResult> {\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 = JSON.stringify(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: ${e}`);\n }\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this._timeoutMs);\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: payload,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.status < 300) {\n return await checkAck(response);\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(response.status, response.headers.get('Retry-After'));\n debug(`HTTP export failed: ${response.status}`);\n return ExportResult.FAILURE;\n } catch (e) {\n debug(`HTTP export error: ${e}`);\n return ExportResult.FAILURE;\n }\n }\n\n shutdown(): void {\n // Native fetch doesn't need cleanup\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\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 <300 response, reading the ACK body.\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 * ⚠ FAIL SAFE, AND THAT IS THE WHOLE DESIGN CONSTRAINT. A body we cannot parse,\n * a body from something that is not our gateway, a field that is missing or not\n * an integer — every one returns SUCCESS, exactly as before. We only turn a 2xx\n * into a FAILURE on an AFFIRMATIVE, well-formed statement that nothing was\n * accepted. Anything less and a proxy that rewrites bodies, or a future gateway\n * that adds a field, becomes an outage.\n *\n * A PARTIAL rejection is deliberately NOT a failure: retrying the whole batch\n * would duplicate the accepted spans, and span-level rejects are permanent.\n * It is surfaced as a warning instead — the signal that was missing.\n *\n * Python twin: `exporters/http.py::_check_ack`. Same rule, same thresholds.\n */\nasync function checkAck(response: Response): Promise<ExportResult> {\n let payload: unknown;\n try {\n payload = await response.json();\n } catch {\n return ExportResult.SUCCESS; // not JSON, or not ours — unchanged behaviour\n }\n if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {\n return ExportResult.SUCCESS;\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 || rejected <= 0) {\n return ExportResult.SUCCESS;\n }\n\n const errors = body.errors;\n const detail =\n (typeof body.errorMessage === 'string' && body.errorMessage) ||\n (typeof body.error_message === 'string' && body.error_message) ||\n (Array.isArray(errors) && errors.length > 0 ? JSON.stringify(errors[0]) : '') ||\n 'No reason was returned.';\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. ${detail}`,\n );\n return ExportResult.FAILURE;\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. ${detail}`,\n );\n return ExportResult.SUCCESS;\n}\n","/**\n * Console exporter for debugging.\n *\n * Prints span data to stderr in a readable format.\n */\n\nimport type { Span } from '../span.js';\nimport { ExportResult, type SpanExporter } from './base.js';\n\nexport class ConsoleExporter implements SpanExporter {\n readonly name = 'console';\n\n export(spans: Span[]): ExportResult {\n for (const span of spans) {\n const payload = span.toPayload();\n const line = JSON.stringify(payload);\n process.stderr.write(`[risicare] ${line}\\n`);\n }\n return ExportResult.SUCCESS;\n }\n\n shutdown(): void {\n // Nothing to clean up\n }\n}\n","/**\n * Fix Cache — Local cache for active fixes with TTL eviction.\n *\n * Provides fast lookup of fixes keyed by error code with exact match\n * and wildcard fallback. No locks needed — JS is single-threaded.\n *\n * Port of Python SDK's runtime/cache.py.\n */\n\nimport type { ActiveFix, FixRuntimeConfig } from './config.js';\nimport { matchesError } from './config.js';\nimport { debug } from '../utils/log.js';\n\n// ─── Cache Entry ────────────────────────────────────────────────────────────\n\ninterface CacheEntry {\n fix: ActiveFix;\n createdAt: number;\n expiresAt: number;\n}\n\n// ─── Cache Stats ────────────────────────────────────────────────────────────\n\nexport interface CacheStats {\n hits: number;\n misses: number;\n evictions: number;\n size: number;\n lastRefresh: number | null;\n}\n\n// ─── Fix Cache ──────────────────────────────────────────────────────────────\n\nexport class FixCache {\n private readonly _ttlMs: number;\n private readonly _maxEntries: number;\n private readonly _enabled: boolean;\n private _cache: Map<string, CacheEntry>;\n private _stats: CacheStats;\n\n constructor(config?: Pick<FixRuntimeConfig, 'cacheEnabled' | 'cacheTtlMs' | 'cacheMaxEntries'>) {\n this._enabled = config?.cacheEnabled ?? true;\n this._ttlMs = config?.cacheTtlMs ?? 300_000;\n this._maxEntries = config?.cacheMaxEntries ?? 1000;\n this._cache = new Map();\n this._stats = {\n hits: 0,\n misses: 0,\n evictions: 0,\n size: 0,\n lastRefresh: null,\n };\n }\n\n /** Whether caching is enabled. */\n get enabled(): boolean {\n return this._enabled;\n }\n\n /**\n * Get a fix by error code.\n *\n * Checks exact match first, then scans for wildcard matches.\n * Expired entries are evicted on access.\n */\n get(errorCode: string): ActiveFix | null {\n try {\n if (!this._enabled) return null;\n\n const now = Date.now();\n\n // Try exact match first (fast path)\n const exactEntry = this._cache.get(errorCode);\n if (exactEntry) {\n if (exactEntry.expiresAt > now) {\n this._stats.hits++;\n return exactEntry.fix;\n }\n // Expired — evict\n this._cache.delete(errorCode);\n this._stats.evictions++;\n }\n\n // Wildcard scan (slower path)\n for (const [key, entry] of this._cache) {\n if (entry.expiresAt <= now) {\n this._cache.delete(key);\n this._stats.evictions++;\n continue;\n }\n\n if (matchesError(entry.fix, errorCode)) {\n this._stats.hits++;\n return entry.fix;\n }\n }\n\n this._stats.misses++;\n return null;\n } catch (e) {\n debug(`FixCache.get error: ${e}`);\n return null;\n }\n }\n\n /**\n * Add a single fix to the cache.\n *\n * Evicts the oldest entry if at capacity.\n */\n set(fix: ActiveFix): void {\n try {\n if (!this._enabled) return;\n\n // Evict oldest if at capacity\n if (this._cache.size >= this._maxEntries) {\n this._evictOldest();\n }\n\n const now = Date.now();\n this._cache.set(fix.errorCode, {\n fix,\n createdAt: now,\n expiresAt: now + this._ttlMs,\n });\n this._stats.size = this._cache.size;\n } catch (e) {\n debug(`FixCache.set error: ${e}`);\n }\n }\n\n /**\n * Replace all cached fixes (bulk refresh).\n *\n * Clears the cache and populates with the given fixes.\n */\n setAll(fixes: ActiveFix[]): void {\n try {\n if (!this._enabled) return;\n\n this._cache.clear();\n const now = Date.now();\n\n for (const fix of fixes) {\n if (this._cache.size >= this._maxEntries) break;\n\n this._cache.set(fix.errorCode, {\n fix,\n createdAt: now,\n expiresAt: now + this._ttlMs,\n });\n }\n\n this._stats.size = this._cache.size;\n this._stats.lastRefresh = now;\n } catch (e) {\n debug(`FixCache.setAll error: ${e}`);\n }\n }\n\n /**\n * Get all non-expired fixes.\n */\n getAll(): ActiveFix[] {\n try {\n const now = Date.now();\n const valid: ActiveFix[] = [];\n const expired: string[] = [];\n\n for (const [key, entry] of this._cache) {\n if (entry.expiresAt > now) {\n valid.push(entry.fix);\n } else {\n expired.push(key);\n }\n }\n\n // Clean up expired entries\n for (const key of expired) {\n this._cache.delete(key);\n this._stats.evictions++;\n }\n\n this._stats.size = this._cache.size;\n return valid;\n } catch (e) {\n debug(`FixCache.getAll error: ${e}`);\n return [];\n }\n }\n\n /** Clear all cache entries. Returns the number of entries cleared. */\n clear(): number {\n const count = this._cache.size;\n this._cache.clear();\n this._stats.size = 0;\n return count;\n }\n\n /** Get cache statistics. */\n get stats(): CacheStats {\n this._stats.size = this._cache.size;\n return { ...this._stats };\n }\n\n /** Evict the oldest cache entry. */\n private _evictOldest(): void {\n if (this._cache.size === 0) return;\n\n let oldestKey: string | null = null;\n let oldestTime = Infinity;\n\n for (const [key, entry] of this._cache) {\n if (entry.createdAt < oldestTime) {\n oldestTime = entry.createdAt;\n oldestKey = key;\n }\n }\n\n if (oldestKey !== null) {\n this._cache.delete(oldestKey);\n this._stats.evictions++;\n }\n }\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// ─── 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 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 const blockedPatterns = (guardConfig.blocked_patterns ?? guardConfig.blockedPatterns ?? []) as string[];\n for (const pattern of blockedPatterns) {\n const regex = this._safeCompileRegex(pattern);\n if (regex && regex.test(content)) {\n passed = false;\n reason = `blocked pattern matched: ${pattern.slice(0, 80)}`;\n break;\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 private _safeCompileRegex(\n pattern: string,\n maxLength = 500,\n ): RegExp | null {\n if (!pattern || pattern.length > maxLength) return null;\n try {\n return new RegExp(pattern, 'i');\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 { 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\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 /** 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)\n this.loadSync().catch((e) => {\n debug(`Initial fix load failed: ${e}`);\n });\n\n // Start background refresh\n if (this._config.autoRefresh) {\n this._startRefreshInterval();\n }\n } catch (e) {\n debug(`FixLoader.start error: ${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: ${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 try {\n // Build URL: /api/v1/ routes to FastAPI via Caddy (NOT /v1/ which is the Rust gateway)\n const endpoint = this._config.apiEndpoint.replace(/\\/+$/, '');\n const url = `${endpoint}/api/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 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: ${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: ${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}): ${error.message}`,\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: ${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 * Fix Runtime — Main orchestrator for the fix application system.\n *\n * Manages:\n * - Loading active fixes from the API (via FixLoader)\n * - Caching fixes locally (via FixCache)\n * - Applying fixes via interceptors (via DefaultFixInterceptor)\n * - Tracking fix effectiveness\n *\n * Singleton management via globalThis (same pattern as the tracer).\n *\n * Port of Python SDK's runtime/runtime.py adapted for Node.js.\n */\n\nimport { FixCache } from './cache.js';\nimport type { ActiveFix, FixRuntimeConfig } from './config.js';\nimport { resolveFixRuntimeConfig } from './config.js';\nimport { FixApplier } from './applier.js';\nimport { FixLoader } from './loader.js';\nimport {\n DefaultFixInterceptor,\n createInterceptContext,\n GuardRejectedError,\n type FixInterceptor,\n type InterceptContext,\n} from './interceptors.js';\nimport { debug, warn } from '../utils/log.js';\n\n// ─── globalThis singleton key ───────────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst G = globalThis as any;\nconst RUNTIME_KEY = '__risicare_fix_runtime';\n\n// ─── Fix Runtime ────────────────────────────────────────────────────────────\n\nexport class FixRuntime {\n private readonly _config: Required<FixRuntimeConfig>;\n private readonly _cache: FixCache;\n private readonly _loader: FixLoader;\n private readonly _applier: FixApplier;\n private readonly _interceptor: DefaultFixInterceptor;\n private _started = false;\n\n // Effectiveness tracking\n private _fixApplications = new Map<string, number>();\n private _fixSuccesses = new Map<string, number>();\n\n constructor(config: FixRuntimeConfig) {\n this._config = resolveFixRuntimeConfig(config);\n this._cache = new FixCache(this._config);\n this._loader = new FixLoader(config, this._cache);\n this._applier = new FixApplier(config, this._cache);\n this._interceptor = new DefaultFixInterceptor(\n config,\n this._cache,\n this._applier,\n );\n }\n\n // ─── Accessors ──────────────────────────────────────────────────────────\n\n /** Runtime configuration (with defaults resolved). */\n get config(): Required<FixRuntimeConfig> {\n return this._config;\n }\n\n /** Whether the runtime is enabled and started. */\n get isEnabled(): boolean {\n return this._config.enabled && this._started;\n }\n\n /** The fix cache. */\n get cache(): FixCache {\n return this._cache;\n }\n\n /** The fix loader. */\n get loader(): FixLoader {\n return this._loader;\n }\n\n /** The fix applier. */\n get applier(): FixApplier {\n return this._applier;\n }\n\n /** The interceptor. */\n get interceptor(): FixInterceptor {\n return this._interceptor;\n }\n\n // ─── Lifecycle ──────────────────────────────────────────────────────────\n\n /**\n * Start the runtime.\n *\n * Triggers initial fix load and starts background refresh.\n * Never throws — failures degrade gracefully.\n */\n start(): void {\n try {\n if (this._started) return;\n\n if (!this._config.enabled) {\n debug('Fix runtime disabled');\n return;\n }\n\n debug('Starting fix runtime...');\n this._loader.start();\n this._started = true;\n debug('Fix runtime started');\n } catch (e) {\n warn(`Fix runtime start failed: ${e}`);\n }\n }\n\n /**\n * Stop the runtime.\n *\n * Stops background refresh and clears the cache.\n * Never throws.\n */\n stop(): void {\n try {\n if (!this._started) return;\n\n debug('Stopping fix runtime...');\n this._loader.stop();\n this._cache.clear();\n this._started = false;\n debug('Fix runtime stopped');\n } catch (e) {\n debug(`Fix runtime stop error: ${e}`);\n }\n }\n\n // ─── Intercept API ──────────────────────────────────────────────────────\n\n /**\n * Intercept a call: create context and run preCall fixes.\n *\n * Returns modified messages/params and the InterceptContext for\n * use in subsequent interceptResponse / interceptError calls.\n */\n interceptCall(\n operationType: string,\n operationName: string,\n messages: unknown[] | null,\n params: Record<string, unknown>,\n options?: {\n sessionId?: string;\n traceId?: string;\n errorCode?: string;\n },\n ): {\n messages: unknown[] | null;\n params: Record<string, unknown>;\n ctx: InterceptContext;\n } {\n const ctx = createInterceptContext(operationType, operationName, options);\n\n try {\n if (!this.isEnabled) {\n return { messages, params, ctx };\n }\n\n const result = this._interceptor.preCall(ctx, messages, params);\n return { messages: result.messages, params: result.params, ctx };\n } catch (e) {\n // PR-4+5 review B2: GuardRejectedError MUST surface to the provider\n // patcher so the LLM call is aborted. Everything else degrades to the\n // unmodified call (FixRuntime failures must never break customers).\n if (e instanceof GuardRejectedError) throw e;\n debug(`interceptCall error: ${e}`);\n return { messages, params, ctx };\n }\n }\n\n /**\n * Intercept a response: run postCall fixes (output validation).\n */\n interceptResponse(\n ctx: InterceptContext,\n response: unknown,\n ): { response: unknown; shouldContinue: boolean } {\n try {\n if (!this.isEnabled) {\n return { response, shouldContinue: true };\n }\n\n const result = this._interceptor.postCall(ctx, response);\n\n // Track success for effectiveness\n this._trackSuccess(ctx);\n\n return result;\n } catch (e) {\n // PR-4+5 review B2: same as interceptCall — output guard rejections\n // must surface; everything else degrades.\n if (e instanceof GuardRejectedError) throw e;\n debug(`interceptResponse error: ${e}`);\n return { response, shouldContinue: true };\n }\n }\n\n /**\n * Intercept an error: decide on retry/fallback.\n */\n interceptError(\n ctx: InterceptContext,\n error: Error,\n ): { shouldRetry: boolean; modifiedParams: Record<string, unknown> | null } {\n try {\n if (!this.isEnabled) {\n return { shouldRetry: false, modifiedParams: null };\n }\n\n ctx.attempt++;\n const result = this._interceptor.onError(ctx, error);\n\n // If not retrying, track failure for effectiveness\n if (!result.shouldRetry) {\n this._trackFailure(ctx);\n }\n\n return result;\n } catch (e) {\n debug(`interceptError error: ${e}`);\n return { shouldRetry: false, modifiedParams: null };\n }\n }\n\n // ─── Direct Fix Access ──────────────────────────────────────────────────\n\n /**\n * Get applicable fix for an error code.\n */\n getFix(errorCode: string, sessionId?: string): ActiveFix | null {\n try {\n if (!this.isEnabled) return null;\n return this._applier.getFixForError(errorCode, sessionId);\n } catch (e) {\n debug(`getFix error: ${e}`);\n return null;\n }\n }\n\n /**\n * Manually refresh fixes from the API.\n */\n async refreshFixes(): Promise<ActiveFix[]> {\n try {\n return await this._loader.loadSync();\n } catch (e) {\n debug(`refreshFixes error: ${e}`);\n return [];\n }\n }\n\n // ─── Effectiveness ──────────────────────────────────────────────────────\n\n /** Get effectiveness statistics for all fixes. */\n getEffectivenessStats(): Record<\n string,\n { applications: number; successes: number; successRate: number }\n > {\n const stats: Record<\n string,\n { applications: number; successes: number; successRate: number }\n > = {};\n\n for (const [fixId, applications] of this._fixApplications) {\n const successes = this._fixSuccesses.get(fixId) ?? 0;\n stats[fixId] = {\n applications,\n successes,\n successRate: applications > 0 ? successes / applications : 0,\n };\n }\n\n return stats;\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n private _trackSuccess(ctx: InterceptContext): void {\n for (const result of ctx.appliedFixes) {\n if (result.applied && result.fixId) {\n this._fixApplications.set(\n result.fixId,\n (this._fixApplications.get(result.fixId) ?? 0) + 1,\n );\n this._fixSuccesses.set(\n result.fixId,\n (this._fixSuccesses.get(result.fixId) ?? 0) + 1,\n );\n }\n }\n }\n\n private _trackFailure(ctx: InterceptContext): void {\n for (const result of ctx.appliedFixes) {\n if (result.applied && result.fixId) {\n this._fixApplications.set(\n result.fixId,\n (this._fixApplications.get(result.fixId) ?? 0) + 1,\n );\n // Don't increment success count\n }\n }\n }\n}\n\n// ─── Singleton Management ───────────────────────────────────────────────────\n\n/** Get the global FixRuntime instance, if initialized. */\nexport function getFixRuntime(): FixRuntime | undefined {\n return G[RUNTIME_KEY] as FixRuntime | undefined;\n}\n\n/** Set the global FixRuntime instance (for advanced use). */\nexport function setFixRuntime(runtime: FixRuntime): void {\n G[RUNTIME_KEY] = runtime;\n}\n\n/**\n * Initialize and start the global FixRuntime.\n *\n * If already initialized, returns the existing instance.\n * Never throws — initialization failures degrade gracefully.\n */\nexport function initFixRuntime(config: FixRuntimeConfig): FixRuntime {\n try {\n const existing = G[RUNTIME_KEY] as FixRuntime | undefined;\n if (existing) {\n debug('Fix runtime already initialized');\n return existing;\n }\n\n const runtime = new FixRuntime(config);\n runtime.start();\n G[RUNTIME_KEY] = runtime;\n return runtime;\n } catch (e) {\n warn(`initFixRuntime failed: ${e}`);\n // Return a disabled runtime so callers don't need null checks\n const fallback = new FixRuntime({ ...config, enabled: false });\n G[RUNTIME_KEY] = fallback;\n return fallback;\n }\n}\n\n/**\n * Shutdown and remove the global FixRuntime.\n *\n * Never throws.\n */\nexport function shutdownFixRuntime(): void {\n try {\n const runtime = G[RUNTIME_KEY] as FixRuntime | undefined;\n if (runtime) {\n runtime.stop();\n }\n G[RUNTIME_KEY] = undefined;\n } catch (e) {\n debug(`shutdownFixRuntime error: ${e}`);\n G[RUNTIME_KEY] = undefined;\n }\n}\n","/**\n * Agent context — identifies which agent is executing.\n * Supports nesting: inner agents automatically track parent.\n */\n\nimport { generateAgentId } from '../ids.js';\nimport { runWithContext, getCurrentAgent, type AgentContext } from './storage.js';\n\nexport interface AgentOptions {\n agentId?: string;\n name?: string;\n role?: string;\n agentType?: string;\n version?: number;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Run a callback within an agent context.\n * If nested inside another agent, parentAgentId is set automatically.\n *\n * @example\n * await withAgent({ name: 'researcher', role: 'worker' }, async () => {\n * const result = await llm.invoke(query);\n * return result;\n * });\n */\nexport function withAgent<T>(options: AgentOptions, fn: () => T): T {\n const parent = getCurrentAgent();\n const agentName = options.name ?? 'agent';\n\n const agent: AgentContext = {\n agentId: options.agentId ?? generateAgentId(agentName),\n agentName: agentName,\n agentRole: options.role,\n agentType: options.agentType,\n parentAgentId: parent?.agentId,\n version: options.version,\n metadata: options.metadata,\n };\n\n return runWithContext({ agent }, fn);\n}\n","/**\n * Lifecycle end-marker (F-B-012) — the JS SDK's run-end signal.\n *\n * At agent() / session() / phase / multi-agent context-manager exit the SDK\n * emits a lifecycle-end marker so downstream (\"did this run finish or die?\")\n * is answerable. The marker is three attributes carried on a span via the open\n * `attributes` map (schema-contract.md \"attribute-first\") plus the typed status:\n *\n * risicare.lifecycle.event = \"end\"\n * risicare.lifecycle.entity = \"session\" | \"agent\" | \"trace\"\n * risicare.lifecycle.status = \"ok\" (normal exit) | \"error\" (the body threw)\n *\n * Mirrors the Python SDK (packages/risicare-sdk/src/risicare/decorators.py).\n * See fix-workstream/F-B-012-DESIGN-CONTRACT.md for the settled contract.\n */\n\nimport type { Span } from './span.js';\nimport { getTracer } from './client.js';\nimport { SpanKind, SpanStatus } from './types.js';\n\nexport const LIFECYCLE_EVENT = 'risicare.lifecycle.event';\nexport const LIFECYCLE_ENTITY = 'risicare.lifecycle.entity';\nexport const LIFECYCLE_STATUS = 'risicare.lifecycle.status';\n\n// Cap the exception summary so a huge message can't bloat the span.\nconst STATUS_MESSAGE_MAX = 500;\n\nexport type LifecycleEntity = 'session' | 'agent' | 'trace';\n\nfunction excSummary(error: unknown): string {\n if (error instanceof Error) {\n return `${error.constructor.name}: ${error.message}`.slice(0, STATUS_MESSAGE_MAX);\n }\n return String(error).slice(0, STATUS_MESSAGE_MAX);\n}\n\n/**\n * Stamp the three lifecycle-end marker attributes + typed status on a span.\n *\n * Best-effort: a marker failure must never crash the host. When `span` is the\n * NOOP span (tracer disabled) its setters are no-ops so nothing is exported\n * (zero-overhead).\n */\nexport function stampEndMarker(\n span: Span,\n entity: LifecycleEntity,\n error: unknown | undefined,\n): void {\n try {\n const statusValue = error !== undefined ? 'error' : 'ok';\n span.setAttribute(LIFECYCLE_EVENT, 'end');\n span.setAttribute(LIFECYCLE_ENTITY, entity);\n span.setAttribute(LIFECYCLE_STATUS, statusValue);\n if (error !== undefined) {\n span.setStatus(SpanStatus.ERROR, excSummary(error));\n }\n } catch {\n // Never crash the host application.\n }\n}\n\n/**\n * Run `body` and stamp the lifecycle end-marker on `span` at completion —\n * `ok` on normal return, `error` on throw (then re-throw; host semantics\n * unchanged). Handles both sync results and Promises (SDK-004 parity).\n *\n * Intended to wrap the inner-body callback of an entity-span decorator, e.g.\n * tracer.startSpan({ ... }, (span) => withEndMarker(span, 'agent', () => fn()))\n */\nexport function withEndMarker<T>(span: Span, entity: LifecycleEntity, body: () => T): T {\n let result: T;\n try {\n result = body();\n } catch (error) {\n stampEndMarker(span, entity, error);\n throw error;\n }\n\n if (result instanceof Promise) {\n return result.then(\n (value) => {\n stampEndMarker(span, entity, undefined);\n return value;\n },\n (error) => {\n stampEndMarker(span, entity, error);\n throw error;\n },\n ) as unknown as T;\n }\n\n stampEndMarker(span, entity, undefined);\n return result;\n}\n\n/**\n * Emit a dedicated, near-zero-duration `session.end` marker span for the\n * session() path (which owns no span of its own).\n *\n * MUST be called INSIDE the active session context so the tracer auto-stamps\n * the span's `sessionId` from the current session — the worker needs that to\n * attribute the marker. Best-effort: never crashes the host. When the tracer\n * is disabled, startSpan runs over the NOOP span and nothing is exported.\n */\nexport function emitSessionEndMarker(error: unknown | undefined): void {\n try {\n const tracer = getTracer();\n if (!tracer) return;\n const statusValue = error !== undefined ? 'error' : 'ok';\n tracer.startSpan(\n {\n name: 'session.end',\n kind: SpanKind.INTERNAL,\n attributes: {\n [LIFECYCLE_EVENT]: 'end',\n [LIFECYCLE_ENTITY]: 'session',\n [LIFECYCLE_STATUS]: statusValue,\n },\n },\n (span) => {\n if (error !== undefined) {\n span.setStatus(SpanStatus.ERROR, excSummary(error));\n }\n },\n );\n } catch {\n // Never crash the host application.\n }\n}\n\n/**\n * Run `body` inside the active session context and emit the `session.end`\n * marker at completion — ok on normal return, error on throw (then re-throw).\n * Handles both sync results and Promises (SDK-004 parity).\n */\nexport function withSessionEndMarker<T>(body: () => T): T {\n let result: T;\n try {\n result = body();\n } catch (error) {\n emitSessionEndMarker(error);\n throw error;\n }\n\n if (result instanceof Promise) {\n return result.then(\n (value) => {\n emitSessionEndMarker(undefined);\n return value;\n },\n (error) => {\n emitSessionEndMarker(error);\n throw error;\n },\n ) as unknown as T;\n }\n\n emitSessionEndMarker(undefined);\n return result;\n}\n","/**\n * agent() — Higher-order function wrapper for agent identity (Tier 2).\n *\n * Wraps a function to execute within an agent context. All spans created\n * inside will be tagged with the agent's identity.\n *\n * Two equivalent calling forms are supported:\n *\n * // 2-arg form\n * const research = agent({ name: 'researcher' }, async (q) => { ... });\n *\n * // Curried form (decorator factory)\n * const research = agent({ name: 'researcher' })(async (q) => { ... });\n *\n * Both return a wrapped function — call it to actually run the body inside\n * the agent context.\n *\n * @example\n * const research = agent({ name: 'researcher', role: 'worker' }, async (query: string) => {\n * const result = await openai.chat.completions.create({ ... });\n * return result.choices[0].message.content;\n * });\n *\n * const answer = await research('What is quantum computing?');\n */\n\nimport { withAgent, type AgentOptions } from '../context/agent.js';\nimport { generateAgentId } from '../ids.js';\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { withEndMarker } from '../lifecycle.js';\n\n// Type-narrowing helper for the wrapper produced by both calling forms.\nfunction _wrapAgent<TArgs extends unknown[], TReturn>(\n options: AgentOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const spanName = `agent:${options.name ?? 'agent'}`;\n // ── F-AGENTID-JS-001 (W36/session-1a): MINT THE ID AT WRAP TIME, NOT PER CALL ──\n // ⚠ THE TWO SDKs PUT THE SAME FIELD NAME ON TWO DIFFERENT SEMANTICS, AND ONLY ONE\n // OF THEM CAN BE RIGHT. Python mints inside `decorator(fn)` — ONE id per (function\n // x process), and its `agent_context()` will not mint at all (agent_id is a\n // REQUIRED positional there, so the decorator is Python's only minting site).\n // JS minted inside `withAgent`, i.e. on EVERY INVOCATION: measured by execution,\n // three calls to one wrapped function produced three distinct `agent_id`s.\n //\n // The consequence is server-side and it is not cosmetic. `agent_id` is the grain of\n // `agent_spans`, so a JS customer's agent cardinality grows with TRAFFIC, not with\n // how many agents they wrote — measured on the lab: 10 distinct `agent_name`\n // against 151,552 distinct `agent_id`. That is what made the KPI read \"151.6K\n // agents\" (F-AGENTCOUNT-001) and what made GET /v1/agents/topology materialise\n // 151,552 nodes and OOM the whole API (F-TOPOOM-001). Same root, three surfaces.\n //\n // `spanName` above was ALREADY computed here, at wrap time — this line simply gives\n // the identity the same lifetime the label already had.\n //\n // ⚠ BOUND, stated so nobody reads more into this than it does: a caller using the\n // exported `withAgent()` DIRECTLY still gets a fresh id per call when they pass no\n // `agentId`. That is deliberate — `withAgent` is the twin of Python's\n // `agent_context()`, which has no minting behaviour to match, and removing the\n // fallback would be a breaking change to a published API. `agent()` is the\n // documented Tier-2 surface and the one both READMEs show.\n //\n // ⚠ NOT IN SCOPE and NOT decided here: whether `agent_id` should be stable ACROSS\n // processes. That is an OTel-semantics ruling (`service.instance.id` vs logical\n // identity) and belongs to the lead. This change only makes JS behave the way\n // Python already does.\n const agentId = options.agentId ?? generateAgentId(options.name ?? 'agent');\n const boundOptions: AgentOptions = { ...options, agentId };\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) {\n // Graceful degradation: run user code without tracing\n return fn(...args);\n }\n return withAgent(boundOptions, () => {\n // F-B-012: stamp the lifecycle end-marker (entity=\"agent\") on the entity\n // span — ok on normal exit, error on throw (then re-throw).\n return tracer.startSpan({ name: spanName, kind: SpanKind.AGENT }, (span) =>\n withEndMarker(span, 'agent', () => fn(...args)),\n );\n });\n };\n}\n\n// Overloads — typed for both calling forms.\nexport function agent<TArgs extends unknown[], TReturn>(\n options: AgentOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\nexport function agent(\n options: AgentOptions,\n): <TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => TReturn,\n) => (...args: TArgs) => TReturn;\nexport function agent<TArgs extends unknown[], TReturn>(\n options: AgentOptions,\n fn?: (...args: TArgs) => TReturn,\n): unknown {\n // Curried form: agent(options)(fn). Return a factory that accepts fn.\n if (fn === undefined) {\n return <TA extends unknown[], TR>(realFn: (...args: TA) => TR) =>\n _wrapAgent(options, realFn);\n }\n // 2-arg form: agent(options, fn). Wrap directly.\n return _wrapAgent(options, fn);\n}\n","/**\n * Session context — groups multiple traces from the same user interaction.\n */\n\nimport { runWithContext, type SessionContext } from './storage.js';\nimport { withSessionEndMarker } from '../lifecycle.js';\n\nexport interface SessionOptions {\n sessionId: string;\n userId?: string;\n metadata?: Record<string, unknown>;\n parentSessionId?: string;\n turnNumber?: number;\n}\n\n/**\n * Run a callback within a session context.\n *\n * @example\n * await withSession({ sessionId: 'sess-123', userId: 'user-1' }, async () => {\n * const result = await agent.run(query);\n * return result;\n * });\n */\nexport function withSession<T>(options: SessionOptions, fn: () => T): T {\n const session: SessionContext = {\n sessionId: options.sessionId,\n userId: options.userId,\n metadata: options.metadata,\n parentSessionId: options.parentSessionId,\n turnNumber: options.turnNumber ?? 1,\n };\n // F-R-SESSIONCMEND-001. `withSession` and `session()` are both exported from\n // index.ts, side by side under one \"Tier 3: Sessions\" heading, as\n // alternatives. Until this line the decorator emitted the `session.end`\n // lifecycle marker and this — the plainer, more obvious spelling — emitted\n // nothing, so which behaviour a customer got depended only on which name they\n // reached for. `routers/sessions.py::_SESSION_AGG_SELECT` computes\n // `is_active` as NOT(a span carrying BOTH `risicare.lifecycle.event='end'`\n // AND `.entity='session'`), so a `withSession` session read ACTIVE FOREVER.\n //\n // The marker is emitted INSIDE `runWithContext` so the tracer stamps\n // sessionId from the active context. `withSessionEndMarker` is now the ONE\n // definition — `decorators/session.ts` no longer wraps separately, so the two\n // paths cannot drift apart again.\n return runWithContext({ session }, () => withSessionEndMarker(fn));\n}\n","/**\n * session() — Higher-order function wrapper for session context (Tier 3).\n *\n * Wraps a function to execute within a session context. All spans created\n * inside will be tagged with the session identity.\n *\n * @example\n * const handleRequest = session(\n * (req) => ({ sessionId: req.sessionId, userId: req.userId }),\n * async (req: Request) => {\n * return await agent.run(req.query);\n * },\n * );\n */\n\nimport { withSession, type SessionOptions } from '../context/session.js';\n\nfunction _wrapSession<TArgs extends unknown[], TReturn>(\n optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions),\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n return (...args: TArgs): TReturn => {\n const options =\n typeof optionsOrResolver === 'function'\n ? optionsOrResolver(...args)\n : optionsOrResolver;\n // F-B-012 / F-R-SESSIONCMEND-001: the `session.end` marker is emitted by\n // `withSession` itself, so both public session APIs share ONE definition.\n // Wrapping again here would emit the marker twice.\n return withSession(options, () => fn(...args));\n };\n}\n\n/**\n * Wrap a function with session context.\n *\n * Two equivalent calling forms are supported (F-54 ergonomics):\n *\n * // 2-arg form\n * const handle = session({ sessionId: 's1' }, async (req) => { ... });\n *\n * // Curried form (decorator factory)\n * const handle = session({ sessionId: 's1' })(async (req) => { ... });\n *\n * @param optionsOrResolver - Static session options, or a function that derives them from args\n * @param fn - The function to wrap. If omitted, returns a decorator factory.\n */\nexport function session<TArgs extends unknown[], TReturn>(\n optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions),\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\nexport function session<TArgs extends unknown[]>(\n optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions),\n): <TR>(fn: (...args: TArgs) => TR) => (...args: TArgs) => TR;\nexport function session<TArgs extends unknown[], TReturn>(\n optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions),\n fn?: (...args: TArgs) => TReturn,\n): unknown {\n if (fn === undefined) {\n return <TR>(realFn: (...args: TArgs) => TR) =>\n _wrapSession(optionsOrResolver, realFn);\n }\n return _wrapSession(optionsOrResolver, fn);\n}\n","/**\n * Phase context — cognitive phase tracking (THINK/DECIDE/ACT/OBSERVE).\n */\n\nimport { SemanticPhase } from '../types.js';\nimport { runWithContext } from './storage.js';\n\n/**\n * Run a callback within a semantic phase context.\n */\nexport function withPhase<T>(phase: SemanticPhase, fn: () => T): T {\n return runWithContext({ phase }, fn);\n}\n","/**\n * Phase decorators — decision phase tracking (Tier 4).\n *\n * Wraps functions to execute within a semantic phase context (THINK/DECIDE/ACT/OBSERVE).\n * Each creates a span named after the phase.\n *\n * @example\n * const analyze = traceThink(async (data: string) => {\n * return await llm.invoke(`Analyze: ${data}`);\n * });\n *\n * const decide = traceDecide(async (analysis: string) => {\n * return await llm.invoke(`Decide action: ${analysis}`);\n * });\n */\n\nimport { withPhase } from '../context/phase.js';\nimport { getTracer } from '../client.js';\nimport { SemanticPhase, SpanKind } from '../types.js';\nimport { withEndMarker } from '../lifecycle.js';\n\nfunction phaseWrapper<TArgs extends unknown[], TReturn>(\n phase: SemanticPhase,\n kind: SpanKind,\n name: string,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) {\n return fn(...args);\n }\n return withPhase(phase, () => {\n // F-B-012: phase decorators are @trace-family — stamp the lifecycle\n // end-marker (entity=\"trace\") for uniform emission.\n return tracer.startSpan({ name, kind }, (span) =>\n withEndMarker(span, 'trace', () => fn(...args)),\n );\n });\n };\n}\n\n/**\n * Wrap a function in a THINK phase context with auto-span.\n *\n * @example traceThink(async () => { ... })\n * @example traceThink(\"analyze-data\", async () => { ... })\n */\nexport function traceThink<TArgs extends unknown[], TReturn>(\n fnOrName: ((...args: TArgs) => TReturn) | string,\n maybeFn?: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const name = typeof fnOrName === 'string' ? fnOrName : `phase:think`;\n const fn = typeof fnOrName === 'function' ? fnOrName : maybeFn!;\n return phaseWrapper(SemanticPhase.THINK, SpanKind.THINK, name, fn);\n}\n\n/**\n * Wrap a function in a DECIDE phase context with auto-span.\n *\n * @example traceDecide(async () => { ... })\n * @example traceDecide(\"choose-action\", async () => { ... })\n */\nexport function traceDecide<TArgs extends unknown[], TReturn>(\n fnOrName: ((...args: TArgs) => TReturn) | string,\n maybeFn?: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const name = typeof fnOrName === 'string' ? fnOrName : `phase:decide`;\n const fn = typeof fnOrName === 'function' ? fnOrName : maybeFn!;\n return phaseWrapper(SemanticPhase.DECIDE, SpanKind.DECIDE, name, fn);\n}\n\n/**\n * Wrap a function in an ACT phase context with auto-span.\n *\n * @example traceAct(async () => { ... })\n * @example traceAct(\"execute-tool\", async () => { ... })\n */\nexport function traceAct<TArgs extends unknown[], TReturn>(\n fnOrName: ((...args: TArgs) => TReturn) | string,\n maybeFn?: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const name = typeof fnOrName === 'string' ? fnOrName : `phase:act`;\n const fn = typeof fnOrName === 'function' ? fnOrName : maybeFn!;\n return phaseWrapper(SemanticPhase.ACT, SpanKind.TOOL_CALL, name, fn);\n}\n\n/**\n * Wrap a function in an OBSERVE phase context with auto-span.\n *\n * @example traceObserve(async () => { ... })\n * @example traceObserve(\"check-result\", async () => { ... })\n */\nexport function traceObserve<TArgs extends unknown[], TReturn>(\n fnOrName: ((...args: TArgs) => TReturn) | string,\n maybeFn?: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const name = typeof fnOrName === 'string' ? fnOrName : `phase:observe`;\n const fn = typeof fnOrName === 'function' ? fnOrName : maybeFn!;\n return phaseWrapper(SemanticPhase.OBSERVE, SpanKind.OBSERVE, name, fn);\n}\n","/**\n * Multi-agent communication decorators (Tier 5).\n *\n * Track inter-agent messages, delegations, and coordination.\n *\n * @example\n * const sendToWorker = traceMessage({ to: 'worker-1', type: MessageType.DELEGATE },\n * async (task: string) => { ... }\n * );\n */\n\nimport { getTracer } from '../client.js';\nimport { MessageType, SpanKind } from '../types.js';\nimport { withEndMarker } from '../lifecycle.js';\n\ninterface MessageOptions {\n to: string;\n type?: MessageType;\n metadata?: Record<string, unknown>;\n}\n\ninterface DelegateOptions {\n to: string;\n metadata?: Record<string, unknown>;\n}\n\ninterface CoordinateOptions {\n participants: string[];\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Namespace user metadata under 'metadata.*' to prevent overwriting\n * critical span attributes like message.type, message.to, etc.\n */\nfunction namespacedMetadata(metadata?: Record<string, unknown>): Record<string, unknown> {\n if (!metadata) return {};\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(metadata)) {\n result[`metadata.${key}`] = value;\n }\n return result;\n}\n\n/**\n * Wrap a function that sends a message to another agent.\n */\nexport function traceMessage<TArgs extends unknown[], TReturn>(\n options: MessageOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n const msgType = options.type ?? MessageType.REQUEST;\n\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) return fn(...args);\n return tracer.startSpan(\n {\n name: `message:${msgType}→${options.to}`,\n kind: SpanKind.MESSAGE,\n attributes: {\n ...namespacedMetadata(options.metadata),\n 'message.to': options.to,\n 'message.type': msgType,\n 'message.target_agent_id': options.to,\n },\n },\n // F-B-012: multi-agent decorators are @trace-family — entity=\"trace\".\n (span) => withEndMarker(span, 'trace', () => fn(...args)),\n );\n };\n}\n\n/**\n * Wrap a function that delegates work to a sub-agent.\n */\nexport function traceDelegate<TArgs extends unknown[], TReturn>(\n options: DelegateOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) return fn(...args);\n return tracer.startSpan(\n {\n name: `delegate→${options.to}`,\n kind: SpanKind.DELEGATION,\n attributes: {\n ...namespacedMetadata(options.metadata),\n 'delegate.to': options.to,\n 'message.type': MessageType.DELEGATE,\n 'message.target_agent_id': options.to,\n },\n },\n // F-B-012: multi-agent decorators are @trace-family — entity=\"trace\".\n (span) => withEndMarker(span, 'trace', () => fn(...args)),\n );\n };\n}\n\n/**\n * Wrap a function that coordinates multiple agents.\n */\nexport function traceCoordinate<TArgs extends unknown[], TReturn>(\n options: CoordinateOptions,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn {\n return (...args: TArgs): TReturn => {\n const tracer = getTracer();\n if (!tracer) return fn(...args);\n return tracer.startSpan(\n {\n name: `coordinate:[${options.participants.join(',')}]`,\n kind: SpanKind.COORDINATION,\n attributes: {\n ...namespacedMetadata(options.metadata),\n 'coordinate.participants': options.participants.join(','),\n 'message.type': MessageType.COORDINATE,\n },\n },\n // F-B-012: multi-agent decorators are @trace-family — entity=\"trace\".\n (span) => withEndMarker(span, 'trace', () => fn(...args)),\n );\n };\n}\n","/**\n * Serializable trace context + W3C Trace Context headers.\n *\n * TraceContext is a plain object that can be passed across process\n * boundaries (JSON serialization, HTTP headers, message queues).\n *\n * W3C Trace Context:\n * traceparent: {version}-{trace_id}-{span_id}-{flags}\n * tracestate: risicare=session_id={...};agent_id={...}\n */\n\nimport { generateTraceId, generateSpanId, validateTraceId, validateSpanId } from '../ids.js';\nimport { getCurrentSpan, getCurrentSession, getCurrentAgent, getContext } from './storage.js';\n\n// ─── Serializable Trace Context ──────────────────────────────────────────────\n\nexport interface TraceContext {\n traceId: string;\n spanId: string;\n sessionId?: string;\n agentId?: string;\n}\n\n/**\n * Get the current trace context as a serializable object.\n *\n * When called inside a span context, returns the active span's IDs.\n * When called outside a span (e.g. inside session() but before agent()),\n * pre-allocates a trace ID and stores it in context so the next\n * startSpan() call inherits it — preventing trace ID mismatch.\n */\nexport function getTraceContext(): TraceContext {\n const span = getCurrentSpan();\n const session = getCurrentSession();\n const agent = getCurrentAgent();\n\n let traceId: string;\n if (span) {\n traceId = span.traceId;\n } else {\n // No active span — check for a previously pre-allocated root trace ID\n const ctx = getContext();\n if (ctx._rootTraceId) {\n traceId = ctx._rootTraceId;\n } else {\n // Pre-allocate and store so startSpan() will inherit this ID\n traceId = generateTraceId();\n // Store in the current context scope (if one exists)\n // This is a no-op if we're outside any runWithContext scope\n if (ctx.session || ctx.agent) {\n // We're inside a session/agent scope — store the pre-allocated ID\n // by mutating the existing context object (safe because AsyncLocalStorage\n // gives each scope its own copy via spread in runWithContext)\n (ctx as Record<string, unknown>)._rootTraceId = traceId;\n }\n }\n }\n\n return {\n traceId,\n spanId: span?.spanId ?? generateSpanId(),\n sessionId: session?.sessionId,\n agentId: agent?.agentId,\n };\n}\n\n// ─── W3C Trace Context Headers ───────────────────────────────────────────────\n\nconst TRACEPARENT_HEADER = 'traceparent';\nconst TRACESTATE_HEADER = 'tracestate';\nconst RISICARE_STATE_DELIMITER = ';';\n\n/**\n * Inject trace context into HTTP headers (W3C format).\n */\nexport function injectTraceContext(headers: Record<string, string>): Record<string, string> {\n const span = getCurrentSpan();\n const session = getCurrentSession();\n const agent = getCurrentAgent();\n\n if (span) {\n // W3C traceparent: version-trace_id-span_id-flags\n headers[TRACEPARENT_HEADER] = `00-${span.traceId}-${span.spanId}-01`;\n\n // Custom tracestate for Risicare (uses ';' as internal delimiter)\n // Preserve other vendors' tracestate entries per W3C spec\n const parts: string[] = [];\n if (session) parts.push(`session_id=${session.sessionId}`);\n if (agent) parts.push(`agent_id=${agent.agentId}`);\n\n if (parts.length > 0) {\n const riscareEntry = `risicare=${parts.join(RISICARE_STATE_DELIMITER)}`;\n const existing = headers[TRACESTATE_HEADER] ?? '';\n // Keep non-risicare vendor entries from any existing tracestate\n const otherEntries = existing\n .split(',')\n .map((e) => e.trim())\n .filter((e) => e && !e.startsWith('risicare='));\n headers[TRACESTATE_HEADER] = [riscareEntry, ...otherEntries].join(',');\n }\n }\n\n return headers;\n}\n\n/**\n * Extract trace context from HTTP headers (W3C format).\n */\nexport function extractTraceContext(headers: Record<string, string>): Record<string, string | undefined> {\n const result: Record<string, string | undefined> = {};\n\n // Normalize header keys to lowercase (HTTP headers are case-insensitive)\n const normalizedHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n normalizedHeaders[key.toLowerCase()] = value;\n }\n\n // Parse traceparent\n const traceparent = normalizedHeaders[TRACEPARENT_HEADER] ?? '';\n if (traceparent) {\n const parts = traceparent.split('-');\n if (parts.length >= 4) {\n const traceId = parts[1].toLowerCase();\n const spanId = parts[2].toLowerCase();\n if (validateTraceId(traceId)) result.traceId = traceId;\n if (validateSpanId(spanId)) result.parentSpanId = spanId;\n result.flags = parts[3];\n }\n }\n\n // Parse tracestate\n const tracestate = normalizedHeaders[TRACESTATE_HEADER] ?? '';\n if (tracestate) {\n for (const entry of tracestate.split(',')) {\n const trimmed = entry.trim();\n if (trimmed.startsWith('risicare=')) {\n const state = trimmed.slice(9); // len(\"risicare=\")\n for (const kv of state.split(RISICARE_STATE_DELIMITER)) {\n const eqIdx = kv.indexOf('=');\n if (eqIdx > 0) {\n const key = kv.slice(0, eqIdx).trim();\n const value = kv.slice(eqIdx + 1).trim();\n if (key && value) {\n // Normalize known tracestate keys to camelCase\n const camelKey = key === 'session_id' ? 'sessionId'\n : key === 'agent_id' ? 'agentId'\n : key;\n result[camelKey] = value;\n }\n }\n }\n }\n }\n }\n\n return result;\n}\n","/**\n * Span registry — TTL-based span store for edge cases.\n *\n * While AsyncLocalStorage handles most context propagation in Node.js,\n * the registry is useful for:\n * - Cross-process span tracking\n * - Explicit span passing via ID\n * - Long-running operations that outlive their original context\n */\n\nimport type { Span } from '../span.js';\nimport { getRegistry, getOpCount, setOpCount } from '../globals.js';\n\ninterface RegistryEntry {\n span: Span;\n registeredAt: number;\n ttlMs: number;\n}\n\nconst DEFAULT_TTL_MS = 60_000;\nconst MAX_ENTRIES = 10_000;\nconst CLEANUP_INTERVAL = 100;\n\nfunction entries(): Map<string, RegistryEntry> {\n return getRegistry() as Map<string, RegistryEntry>;\n}\n\nexport function registerSpan(span: Span, ttlMs = DEFAULT_TTL_MS): void {\n entries().set(span.spanId, {\n span,\n registeredAt: Date.now(),\n ttlMs,\n });\n setOpCount(getOpCount() + 1);\n maybeCleanup();\n}\n\nexport function getSpanById(spanId: string): Span | undefined {\n const entry = entries().get(spanId);\n if (!entry) return undefined;\n\n if (Date.now() - entry.registeredAt > entry.ttlMs) {\n entries().delete(spanId);\n return undefined;\n }\n\n return entry.span;\n}\n\nexport function unregisterSpan(spanId: string): void {\n entries().delete(spanId);\n}\n\nexport function extendSpanTtl(spanId: string, additionalMs: number): boolean {\n const entry = entries().get(spanId);\n if (!entry) return false;\n\n if (Date.now() - entry.registeredAt > entry.ttlMs) {\n entries().delete(spanId);\n return false;\n }\n\n entry.ttlMs += additionalMs;\n return true;\n}\n\nexport function getRegistryStats(): { totalEntries: number; operationCount: number } {\n return {\n totalEntries: entries().size,\n operationCount: getOpCount(),\n };\n}\n\nexport function clearRegistry(): void {\n entries().clear();\n setOpCount(0);\n}\n\nfunction maybeCleanup(): void {\n if (getOpCount() % CLEANUP_INTERVAL !== 0) return;\n if (entries().size <= MAX_ENTRIES) return;\n\n const now = Date.now();\n for (const [id, entry] of entries()) {\n if (now - entry.registeredAt > entry.ttlMs) {\n entries().delete(id);\n }\n }\n}\n","/**\n * tracedStream — Wrap an async iterable in a trace span.\n *\n * Creates a span that starts when iteration begins and ends when\n * iteration completes (or errors). Chunks pass through UNCHANGED.\n *\n * This is the user-level streaming utility. For provider-level streaming\n * enrichment (token counts, cost), see individual provider instrumentors.\n *\n * Usage:\n * const stream = await openai.chat.completions.create({ stream: true, ... });\n * for await (const chunk of tracedStream(stream, { name: 'llm-stream' })) {\n * process(chunk);\n * }\n */\n\nimport { getTracer } from './client.js';\nimport { SpanKind } from './types.js';\n\nexport interface TracedStreamOptions {\n /** Span name */\n name: string;\n /** Span kind (default: INTERNAL) */\n kind?: SpanKind;\n /** Additional span attributes */\n attributes?: Record<string, unknown>;\n}\n\n/**\n * Wrap an async iterable in a trace span.\n *\n * - Span starts on first iteration\n * - chunk_count attribute set when iteration ends\n * - On error: span records exception, error re-thrown to caller\n * - On early break: span ended cleanly via finally\n * - If SDK not initialized: chunks pass through without wrapping\n */\nexport async function* tracedStream<T>(\n source: AsyncIterable<T>,\n options: TracedStreamOptions | string,\n): AsyncGenerator<T, void, undefined> {\n const opts = typeof options === 'string' ? { name: options } : options;\n\n // Graceful degradation: if SDK not initialized, pass through\n const tracer = getTracer();\n if (!tracer || !tracer.enabled) {\n yield* source;\n return;\n }\n\n const span = tracer.createSpan({\n name: opts.name,\n kind: opts.kind ?? SpanKind.INTERNAL,\n attributes: opts.attributes,\n });\n\n let chunkCount = 0;\n\n try {\n for await (const chunk of source) {\n chunkCount++;\n yield chunk;\n }\n\n span.setAttribute('stream.chunk_count', chunkCount);\n span.setAttribute('stream.completed', true);\n } catch (error) {\n span.setAttribute('stream.chunk_count', chunkCount);\n span.setAttribute('stream.completed', false);\n span.recordException(error instanceof Error ? error : String(error));\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Double-tracing prevention for framework integrations.\n *\n * When a framework integration (e.g., LlamaIndex handler) creates its own\n * LLM span, the underlying provider proxy (e.g., patchOpenAI) would also\n * create a duplicate span. This module provides suppression:\n *\n * - Framework integrations SET suppression via suppressProviderInstrumentation()\n * - Provider proxies CHECK via isProviderInstrumentationSuppressed() and skip\n *\n * Scoped to AsyncLocalStorage — concurrent calls are independent.\n */\n\nimport { getContext, runWithContext } from './storage.js';\n\n/**\n * Run a callback with provider instrumentation suppressed.\n *\n * During this callback, all provider instrumentors (patchOpenAI, etc.) will\n * skip span creation. The framework is responsible for creating the span.\n *\n * @param fn - The function to run with suppression active\n * @returns The function's return value\n */\nexport function suppressProviderInstrumentation<T>(fn: () => T): T {\n return runWithContext({ _suppressProviderInstrumentation: true }, fn);\n}\n\n/**\n * Check if provider instrumentation should be suppressed.\n *\n * Called by provider instrumentors as an early-exit guard. When true,\n * the provider calls the original method directly without creating a span.\n */\nexport function isProviderInstrumentationSuppressed(): boolean {\n return getContext()._suppressProviderInstrumentation === true;\n}\n","/**\n * LangChain.js integration via callback handler.\n *\n * LangChain.js uses BaseCallbackHandler from @langchain/core/callbacks/base.\n * F-628/F-729: prior versions of this handler did NOT extend BaseCallbackHandler\n * — LangChain v0.2+ tightened its callback registration to do `instanceof\n * BaseCallbackHandler` checks, silently dropping any handler that does not\n * inherit. Zero spans fired from any LCEL chain.\n *\n * PR-4+5 review B1 (2026-05-25): even with `extends BaseCallbackHandler`,\n * `instanceof` would fail for ESM consumers because we resolve via\n * `createRequire()` (CJS) — the two module instances are DIFFERENT class\n * identities. LangChain v0.3 ships `isBaseCallbackHandler(x)` which checks\n * duck-type markers (`x.copy` function, `x.name` string, `x.awaitHandlers`\n * boolean). We now set those markers explicitly so we pass the duck-typed\n * check regardless of which class identity ends up resolving in the customer\n * environment. We ALSO still extend the resolved BaseCallbackHandler when\n * available — that satisfies any remaining v0.2 `instanceof` callsite in\n * the customer's bundle AND inherits the real `copy()` method.\n *\n * Usage:\n * import { RisicareCallbackHandler } from 'risicare/langchain';\n * const handler = new RisicareCallbackHandler();\n * const result = await handler.withSuppression(() =>\n * chain.invoke(input, { callbacks: [handler] })\n * );\n *\n * SUPPRESSES provider instrumentation — LangChain handler creates LLM spans,\n * so provider-level spans (patchOpenAI, etc.) would duplicate without suppression.\n */\n\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { suppressProviderInstrumentation } from '../context/dedup.js';\nimport { debug } from '../utils/log.js';\nimport type { Span } from '../span.js';\n\ninterface SpanEntry {\n span: Span;\n startTime: number;\n}\n\n/**\n * Resolve BaseCallbackHandler lazily. We cannot `import` it statically because\n * @langchain/core is an OPTIONAL peer dep — a bare `import` would fail at\n * load time for customers who don't have LangChain. The dynamic require is\n * wrapped in try/catch; on failure we fall back to `Object` so the handler\n * still constructs (it just won't satisfy LangChain v0.2+'s instanceof check).\n */\nfunction resolveBaseCallbackHandler(): new (...args: unknown[]) => object {\n try {\n // Use createRequire so this works under both CJS and ESM.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { createRequire } = require('node:module') as typeof import('node:module');\n const req = createRequire(import.meta.url);\n const mod = req('@langchain/core/callbacks/base') as {\n BaseCallbackHandler?: new (...args: unknown[]) => object;\n };\n if (mod?.BaseCallbackHandler) {\n return mod.BaseCallbackHandler;\n }\n } catch {\n // Either ESM context without createRequire, or peer dep not installed.\n // Fall through to the require fallback below.\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require('@langchain/core/callbacks/base') as {\n BaseCallbackHandler?: new (...args: unknown[]) => object;\n };\n if (mod?.BaseCallbackHandler) {\n return mod.BaseCallbackHandler;\n }\n } catch {\n debug('RisicareCallbackHandler: @langchain/core not installed; handler will not satisfy LangChain v0.2+ instanceof check');\n }\n return Object as unknown as new (...args: unknown[]) => object;\n}\n\nconst _BaseCallbackHandler = resolveBaseCallbackHandler();\n\n/**\n * RisicareCallbackHandler — emits Risicare spans for every LangChain callback.\n *\n * Extends BaseCallbackHandler at runtime when @langchain/core is installed,\n * which is required for LangChain v0.2+ to accept it.\n *\n * F-882/F-883: chat-model and agent events are NEW in v0.2; older handlers\n * that only implement handleLLMStart get zero spans from `ChatModel`s (every\n * modern LangChain LLM is a ChatModel). The full chat / agent / custom-event\n * surface is now covered.\n */\nexport class RisicareCallbackHandler extends _BaseCallbackHandler {\n // PR-4+5 review B1: duck-type markers that LangChain v0.3's\n // `isBaseCallbackHandler(x)` checks. This is the ONLY reliable way to be\n // recognised across the CJS↔ESM identity split — `instanceof` cannot work\n // when our `createRequire`-loaded BaseCallbackHandler is a different\n // class object from the customer's ESM-imported BaseCallbackHandler.\n // Keep these as instance properties (not prototype) so they survive any\n // Object-fallback path when @langchain/core is absent.\n name = 'RisicareCallbackHandler';\n awaitHandlers = true;\n ignoreLLM = false;\n ignoreChain = false;\n ignoreAgent = false;\n ignoreRetriever = false;\n ignoreCustomEvent = false;\n raiseError = false;\n lc_serializable = false;\n lc_kwargs: Record<string, unknown> = {};\n\n private _spans = new Map<string, SpanEntry>();\n\n constructor() {\n // Call super() even if BaseCallbackHandler is the Object fallback.\n super();\n }\n\n /**\n * Required by LangChain's `isBaseCallbackHandler(x)` duck-type check\n * (`typeof x.copy === 'function'`). When @langchain/core is installed\n * BaseCallbackHandler's prototype provides its own `copy()`; this\n * declaration overrides with a Risicare-aware copy that re-instantiates\n * — sufficient for the handler-cloning paths LangChain uses internally\n * (e.g., per-run isolation in concurrent chains). Spans map starts empty\n * because a fresh handler should not share span state with its parent.\n */\n copy(): RisicareCallbackHandler {\n return new RisicareCallbackHandler();\n }\n\n /**\n * Run a function with provider instrumentation suppressed.\n *\n * Wrap your chain.invoke() call with this to prevent duplicate spans.\n * The handler creates LLM/tool spans, so provider proxies (patchOpenAI, etc.)\n * should be suppressed during chain execution.\n *\n * @example\n * const handler = new RisicareCallbackHandler();\n * const result = await handler.withSuppression(() =>\n * chain.invoke(input, { callbacks: [handler] })\n * );\n */\n withSuppression<T>(fn: () => T): T {\n return suppressProviderInstrumentation(fn);\n }\n\n // ── Internal helpers ──────────────────────────────────────────────────────\n\n private _startSpan(\n runId: string,\n parentRunId: string | undefined,\n name: string,\n kind: SpanKind,\n extraAttrs: Record<string, unknown> = {},\n ): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n\n const parentEntry = parentRunId ? this._spans.get(parentRunId) : undefined;\n const span = tracer.createSpan({\n name,\n kind,\n parentSpanId: parentEntry?.span.spanId,\n traceId: parentEntry?.span.traceId,\n attributes: {\n framework: 'langchain',\n 'langchain.run_id': runId,\n ...(parentRunId ? { 'langchain.parent_run_id': parentRunId } : {}),\n ...extraAttrs,\n },\n });\n\n this._spans.set(runId, { span, startTime: Date.now() });\n }\n\n private _endSpan(runId: string, extraAttrs: Record<string, unknown> = {}): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n for (const [k, v] of Object.entries(extraAttrs)) {\n entry.span.setAttribute(k, v);\n }\n entry.span.setAttribute('gen_ai.latency_ms', Date.now() - entry.startTime);\n entry.span.end();\n this._spans.delete(runId);\n }\n\n private _errorSpan(runId: string, error: Error): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n entry.span.recordException(error);\n entry.span.end();\n this._spans.delete(runId);\n }\n\n // ── Chain lifecycle ────────────────────────────────────────────────────────\n\n handleChainStart(\n chain: { name?: string; _type?: string },\n _inputs: Record<string, unknown>,\n runId: string,\n parentRunId?: string,\n ): void {\n this._startSpan(runId, parentRunId, chain.name || chain._type || 'chain', SpanKind.INTERNAL, {\n ...(chain._type ? { 'langchain.chain_type': chain._type } : {}),\n });\n }\n\n handleChainEnd(_outputs: Record<string, unknown>, runId: string): void {\n this._endSpan(runId);\n }\n\n handleChainError(error: Error, runId: string): void {\n this._errorSpan(runId, error);\n }\n\n // ── LLM lifecycle ─────────────────────────────────────────────────────────\n\n handleLLMStart(\n llm: { name?: string; _type?: string },\n _prompts: string[],\n runId: string,\n parentRunId?: string,\n ): void {\n this._startSpan(runId, parentRunId, llm.name || llm._type || 'llm', SpanKind.LLM_CALL, {\n 'gen_ai.system': 'langchain',\n 'gen_ai.prompt.count': _prompts.length,\n });\n }\n\n /**\n * F-882: chat-model lifecycle — LangChain v0.2+ emits this for any\n * ChatModel (which is EVERY production LLM today). Without this method,\n * not a single `langchain` LLM span fires when used via LCEL.\n *\n * The messages payload is an array-of-arrays (one inner array per prompt);\n * we just count rather than materialize content (PII boundary).\n */\n handleChatModelStart(\n llm: { name?: string; _type?: string },\n messages: unknown[][],\n runId: string,\n parentRunId?: string,\n ): void {\n const messageCount = Array.isArray(messages)\n ? messages.reduce((sum, arr) => sum + (Array.isArray(arr) ? arr.length : 0), 0)\n : 0;\n this._startSpan(runId, parentRunId, llm.name || llm._type || 'chat_model', SpanKind.LLM_CALL, {\n 'gen_ai.system': 'langchain',\n 'gen_ai.message.count': messageCount,\n });\n }\n\n handleLLMEnd(\n output: {\n generations?: unknown[][];\n llmOutput?: Record<string, unknown>;\n },\n runId: string,\n ): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n\n // Extract token usage from llmOutput\n const usage = output.llmOutput?.tokenUsage as\n | Record<string, number>\n | undefined;\n if (usage) {\n entry.span.setLlmFields({\n promptTokens: usage.promptTokens ?? usage.prompt_tokens,\n completionTokens: usage.completionTokens ?? usage.completion_tokens,\n totalTokens: usage.totalTokens ?? usage.total_tokens,\n });\n }\n\n const model = (output.llmOutput?.model ??\n output.llmOutput?.modelName) as string | undefined;\n if (model) {\n entry.span.setLlmFields({ model });\n }\n\n entry.span.setAttribute('gen_ai.latency_ms', Date.now() - entry.startTime);\n entry.span.end();\n this._spans.delete(runId);\n }\n\n handleLLMError(error: Error, runId: string): void {\n this._errorSpan(runId, error);\n }\n\n /**\n * F-883: streaming-token event. We do NOT create a new span (the LLM span\n * already exists from handleLLMStart/handleChatModelStart) — just count tokens\n * on the existing span. This is a HIGH-FREQUENCY event; do the cheap work only.\n */\n handleLLMNewToken(_token: string, _idx: unknown, runId: string): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n const prior = (entry.span.attributes?.['gen_ai.stream.token_count'] as number) ?? 0;\n entry.span.setAttribute('gen_ai.stream.token_count', prior + 1);\n }\n\n // ── Tool lifecycle ────────────────────────────────────────────────────────\n\n handleToolStart(\n tool: { name?: string },\n input: string,\n runId: string,\n parentRunId?: string,\n ): void {\n this._startSpan(runId, parentRunId, tool.name || 'tool', SpanKind.TOOL_CALL, {\n 'tool.name': tool.name || 'unknown',\n 'tool.input_length': input?.length ?? 0,\n });\n }\n\n handleToolEnd(output: string, runId: string): void {\n this._endSpan(runId, { 'tool.output_length': output?.length ?? 0 });\n }\n\n handleToolError(error: Error, runId: string): void {\n this._errorSpan(runId, error);\n }\n\n // ── Retriever lifecycle ───────────────────────────────────────────────────\n\n handleRetrieverStart(\n retriever: { name?: string },\n _query: string,\n runId: string,\n parentRunId?: string,\n ): void {\n this._startSpan(runId, parentRunId, retriever.name || 'retriever', SpanKind.RETRIEVAL);\n }\n\n handleRetrieverEnd(documents: unknown[], runId: string): void {\n this._endSpan(runId, { 'retriever.document_count': documents?.length ?? 0 });\n }\n\n handleRetrieverError(error: Error, runId: string): void {\n this._errorSpan(runId, error);\n }\n\n // ── Agent lifecycle (F-882) ───────────────────────────────────────────────\n\n /**\n * Agent decided to take an action (call a tool). LangChain v0.2 agents emit\n * this between LLM calls. Cheap span, no parent change.\n */\n handleAgentAction(\n action: { tool?: string; toolInput?: unknown; log?: string },\n runId: string,\n parentRunId?: string,\n ): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n const parentEntry = parentRunId ? this._spans.get(parentRunId) : undefined;\n const span = tracer.createSpan({\n name: `agent.action:${action.tool ?? 'unknown'}`,\n kind: SpanKind.INTERNAL,\n parentSpanId: parentEntry?.span.spanId,\n traceId: parentEntry?.span.traceId,\n attributes: {\n framework: 'langchain',\n 'langchain.run_id': runId,\n 'agent.action.tool': action.tool ?? '',\n },\n });\n // Agent actions are point-in-time events, not durations — end immediately.\n span.end();\n }\n\n /**\n * Agent finished (final answer produced). Mirror of handleAgentAction.\n */\n handleAgentEnd(\n action: { returnValues?: Record<string, unknown>; log?: string },\n runId: string,\n parentRunId?: string,\n ): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n const parentEntry = parentRunId ? this._spans.get(parentRunId) : undefined;\n const span = tracer.createSpan({\n name: 'agent.end',\n kind: SpanKind.INTERNAL,\n parentSpanId: parentEntry?.span.spanId,\n traceId: parentEntry?.span.traceId,\n attributes: {\n framework: 'langchain',\n 'langchain.run_id': runId,\n 'agent.return_keys': action.returnValues\n ? Object.keys(action.returnValues).length\n : 0,\n },\n });\n span.end();\n }\n\n // ── Misc (F-882) ──────────────────────────────────────────────────────────\n\n /**\n * Free-text emission (logging-style). Used by ConversationalRetrievalChain\n * and verbose prints. Adds an event to the current chain span if one exists.\n */\n handleText(text: string, runId: string, _parentRunId?: string): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n entry.span.addEvent('langchain.text', {\n 'text.length': text?.length ?? 0,\n });\n }\n\n /**\n * Custom event hook (introduced in @langchain/core 0.2.14). Customer code can\n * `dispatchCustomEvent(name, payload)` from inside a runnable. We surface as\n * a span event on the closest enclosing run so it shows up in the trace.\n */\n handleCustomEvent(\n eventName: string,\n _payload: unknown,\n runId: string,\n _tags?: string[],\n _metadata?: Record<string, unknown>,\n ): void {\n const entry = this._spans.get(runId);\n if (!entry) return;\n entry.span.addEvent('langchain.custom_event', { name: eventName });\n }\n}\n","/**\n * LangGraph.js integration via Proxy wrapping.\n *\n * LangGraph uses LangChain callbacks under the hood. This integration wraps\n * a compiled graph's invoke/stream methods to:\n * 1. Create a parent \"langgraph.invoke\" or \"langgraph.stream\" span\n * 2. Inject a RisicareCallbackHandler into the config so all internal\n * chain/LLM/tool calls are also traced\n *\n * Usage:\n * import { instrumentLangGraph } from 'risicare/frameworks/langgraph';\n * const graph = instrumentLangGraph(compiledGraph);\n * const result = await graph.invoke(input);\n *\n * Does NOT suppress provider instrumentation.\n */\n\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { RisicareCallbackHandler } from './langchain.js';\n\n/**\n * Wrap a compiled LangGraph graph with Risicare tracing.\n *\n * Returns a Proxy that intercepts `invoke` and `stream` calls to create\n * a parent span and inject the LangChain callback handler.\n *\n * @param graph - A compiled LangGraph graph object with invoke/stream methods\n * @returns A proxied graph with tracing enabled\n */\nexport function instrumentLangGraph<T extends object>(graph: T): T {\n return new Proxy(graph, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (\n (prop === 'invoke' || prop === 'stream') &&\n typeof value === 'function'\n ) {\n return function patchedMethod(\n this: unknown,\n ...args: unknown[]\n ): unknown {\n const tracer = getTracer();\n if (!tracer?.enabled) return value.apply(this, args);\n\n return tracer.startSpan(\n {\n name: `langgraph.${String(prop)}`,\n kind: SpanKind.AGENT,\n attributes: { framework: 'langgraph' },\n },\n (_span) => {\n // Inject RisicareCallbackHandler into config (second argument)\n const config = (args[1] ?? {}) as Record<string, unknown>;\n const callbacks = (config.callbacks ?? []) as unknown[];\n callbacks.push(new RisicareCallbackHandler());\n args[1] = { ...config, callbacks };\n\n const result = value.apply(this, args);\n\n // Handle async results (Promises)\n if (\n result &&\n typeof (result as Promise<unknown>).then === 'function'\n ) {\n return (result as Promise<unknown>).then((r) => r);\n }\n return result;\n },\n );\n };\n }\n\n return value;\n },\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","/**\n * LlamaIndex.TS integration via event handler.\n *\n * LlamaIndex.TS emits CustomEvent-shaped events through the global\n * `Settings.callbackManager` (a DOM-style EventTarget). F-880/F-881:\n * - Event NAMES use hyphens (`llm-start`, `llm-end`, `retrieve-start`,\n * `retrieve-end`, `query-start`, `query-end`, `embedding-start`, etc.),\n * NOT dotted suffixes (`.start` / `.end`). The previous handler used\n * `event.type.endsWith('.start')` and silently matched nothing.\n * - Payload lives on `event.detail` (DOM CustomEvent convention), NOT\n * `event.data` — the prior code was reading from `undefined`.\n *\n * We support both the hyphenated DOM CustomEvent shape (the real LlamaIndex.TS\n * format) and the dotted-suffix shape (the form the old code expected, kept\n * for back-compat with any customer who already wrote integration code\n * against the buggy contract).\n *\n * Usage:\n * import { RisicareLlamaIndexHandler } from 'risicare/llamaindex';\n * import { Settings } from 'llamaindex';\n * const handler = new RisicareLlamaIndexHandler();\n *\n * // Register every event we care about:\n * for (const name of RisicareLlamaIndexHandler.EVENT_NAMES) {\n * Settings.callbackManager.on(name, (e) => handler.onEvent(e));\n * }\n *\n * // For LLM/embedding calls, suppress provider instrumentation:\n * const result = handler.withSuppression(() => query(...));\n *\n * SUPPRESSES provider instrumentation -- LlamaIndex creates its own LLM spans,\n * so provider-level spans (patchOpenAI, etc.) would duplicate.\n */\n\nimport { getTracer } from '../client.js';\nimport { SpanKind } from '../types.js';\nimport { suppressProviderInstrumentation } from '../context/dedup.js';\nimport type { Span } from '../span.js';\n\ninterface SpanEntry {\n span: Span;\n startTime: number;\n componentKind: string;\n}\n\n/**\n * Loose event shape. LlamaIndex.TS dispatches `CustomEvent`s where the payload\n * is on `.detail`. We also accept `.data` for back-compat with the older buggy\n * contract.\n */\nexport interface LlamaIndexEvent {\n type: string;\n // DOM CustomEvent payload (the real LlamaIndex.TS shape)\n detail?: Record<string, unknown>;\n // Back-compat fallback (the shape the old handler expected)\n data?: Record<string, unknown>;\n // Some payloads carry id/parentId at the top level instead of in detail\n id?: string;\n parentId?: string;\n}\n\n/**\n * Registry of (event-name → lifecycle-phase) for the events LlamaIndex.TS\n * actually emits. Maintained explicitly so the handler doesn't false-match\n * on customer-defined custom events that happen to end with `-start`.\n */\nconst EVENT_PHASE: Record<string, 'start' | 'end' | 'error'> = {\n // LLM\n 'llm-start': 'start',\n 'llm-end': 'end',\n 'llm-error': 'error',\n 'llm-tool-call': 'start',\n 'llm-tool-result': 'end',\n 'llm-stream': 'end',\n // Chat\n 'chat-start': 'start',\n 'chat-end': 'end',\n // Embeddings\n 'embedding-start': 'start',\n 'embedding-end': 'end',\n // Retrieval\n 'retrieve-start': 'start',\n 'retrieve-end': 'end',\n // Query / synthesis\n 'query-start': 'start',\n 'query-end': 'end',\n 'synthesize-start': 'start',\n 'synthesize-end': 'end',\n // Agent\n 'agent-start': 'start',\n 'agent-end': 'end',\n 'agent-step-start': 'start',\n 'agent-step-end': 'end',\n};\n\nexport class RisicareLlamaIndexHandler {\n /**\n * Public, iterable list of all event names this handler responds to.\n * Customers should subscribe to each on the LlamaIndex callback manager:\n * for (const n of RisicareLlamaIndexHandler.EVENT_NAMES) Settings.callbackManager.on(n, ...)\n */\n static readonly EVENT_NAMES = Object.keys(EVENT_PHASE);\n\n private _spans = new Map<string, SpanEntry>();\n\n /**\n * Handle a LlamaIndex lifecycle event.\n */\n onEvent(event: LlamaIndexEvent): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n\n // F-881: prefer .detail (DOM CustomEvent convention); fall back to .data.\n const payload = event.detail ?? event.data ?? {};\n\n // F-880: lookup by exact event name first (real LlamaIndex format).\n let phase = EVENT_PHASE[event.type];\n\n // Back-compat: accept legacy dotted suffix form (`*.start`/`*.end`/`*.error`).\n if (!phase) {\n if (event.type.endsWith('.start') || event.type.endsWith('.begin')) {\n phase = 'start';\n } else if (event.type.endsWith('.end') || event.type.endsWith('.complete')) {\n phase = 'end';\n } else if (event.type.endsWith('.error')) {\n phase = 'error';\n }\n }\n\n if (!phase) return;\n\n const id = (payload.id as string) ?? event.id ?? '';\n const parentId = (payload.parentId as string) ?? event.parentId;\n if (!id) return; // can't track spans without an id\n\n if (phase === 'start') {\n this._handleStart(event.type, id, parentId, payload);\n } else if (phase === 'end') {\n this._handleEnd(id, payload);\n } else {\n this._handleError(id, payload);\n }\n }\n\n /**\n * Run a function with provider instrumentation suppressed.\n */\n withSuppression<T>(fn: () => T): T {\n return suppressProviderInstrumentation(fn);\n }\n\n // ── Internal event handlers ───────────────────────────────────────────────\n\n private _handleStart(\n eventType: string,\n id: string,\n parentId: string | undefined,\n payload: Record<string, unknown>,\n ): void {\n const tracer = getTracer();\n if (!tracer?.enabled) return;\n\n const componentKind = this._classifyComponent(eventType);\n const parentEntry = parentId ? this._spans.get(parentId) : undefined;\n\n const spanKind =\n componentKind === 'llm'\n ? SpanKind.LLM_CALL\n : componentKind === 'retrieval'\n ? SpanKind.RETRIEVAL\n : componentKind === 'embedding'\n ? SpanKind.LLM_CALL\n : SpanKind.INTERNAL;\n\n // Strip both shapes of suffix so the span name is just the component.\n const spanName = eventType\n .replace(/\\.(start|begin)$/, '')\n .replace(/-(start|begin)$/, '');\n\n const span = tracer.createSpan({\n name: spanName,\n kind: spanKind,\n parentSpanId: parentEntry?.span.spanId,\n traceId: parentEntry?.span.traceId,\n attributes: {\n framework: 'llamaindex',\n 'framework.span_kind': componentKind,\n ...(payload.model ? { 'gen_ai.request.model': payload.model } : {}),\n },\n });\n\n this._spans.set(id, { span, startTime: Date.now(), componentKind });\n }\n\n private _handleEnd(id: string, payload: Record<string, unknown>): void {\n const entry = this._spans.get(id);\n if (!entry) return;\n\n entry.span.setAttribute('gen_ai.latency_ms', Date.now() - entry.startTime);\n\n // Extract token usage if available\n const usage = payload.usage as Record<string, number> | undefined;\n if (usage) {\n entry.span.setLlmFields({\n promptTokens: usage.promptTokens ?? usage.prompt_tokens,\n completionTokens: usage.completionTokens ?? usage.completion_tokens,\n });\n }\n\n if (payload.documentCount != null) {\n entry.span.setAttribute(\n 'retriever.document_count',\n payload.documentCount,\n );\n } else if (Array.isArray(payload.nodes)) {\n // LlamaIndex retrieve-end emits a `nodes` array; fall back to length.\n entry.span.setAttribute('retriever.document_count', payload.nodes.length);\n }\n\n entry.span.end();\n this._spans.delete(id);\n }\n\n private _handleError(id: string, payload: Record<string, unknown>): void {\n const entry = this._spans.get(id);\n if (!entry) return;\n\n const error = payload.error;\n entry.span.recordException(\n error instanceof Error ? error : String(error ?? 'Unknown error'),\n );\n entry.span.end();\n this._spans.delete(id);\n }\n\n /**\n * Classify a LlamaIndex event type into a component kind.\n */\n private _classifyComponent(eventType: string): string {\n const lower = eventType.toLowerCase();\n if (lower.includes('llm') || lower.includes('chat')) return 'llm';\n if (lower.includes('embed')) return 'embedding';\n if (lower.includes('retriev') || lower.includes('vector')) return 'retrieval';\n if (lower.includes('synth') || lower.includes('response')) return 'synthesis';\n if (lower.includes('query')) return 'query';\n if (lower.includes('agent')) return 'agent';\n return 'component';\n }\n}\n","/**\n * Webhook signature verification helpers (CON-195 / B-7, F-34).\n *\n * Customers receive Risicare webhooks at endpoints they configure. Each\n * delivery is signed by the sender (`packages/workers/src/workers/\n * webhook_dispatch.py`) with HMAC-SHA256 over `<timestamp>.<payload_bytes>`\n * using the per-webhook shared secret. The signature is delivered in the\n * `X-Risicare-Signature` header in Stripe-style format `t=<unix>,v1=<hex>`,\n * and the timestamp is also exposed verbatim as `X-Risicare-Timestamp`.\n *\n * This module is the TypeScript port of `risicare-sdk/src/risicare/\n * webhooks.py`. It enforces THREE checks (all must pass):\n *\n * 1. Header parsing — both headers must be present and well-formed.\n * 2. Time skew — `Math.abs(now - timestamp) <= toleranceS` (default\n * 5 minutes). This is what makes captured signed payloads\n * non-replayable past the tolerance window.\n * 3. HMAC equality — constant-time compare against a fresh signature\n * computed from the secret + the SAME timestamp + the raw body.\n *\n * Example (Express/Node receiver):\n *\n * import express from 'express';\n * import { verifyWebhookSignature, WebhookVerificationError } from 'risicare';\n *\n * const app = express();\n * // IMPORTANT: use raw body, not parsed JSON — the signature is\n * // over the EXACT bytes received; JSON re-serialization changes\n * // key ordering / whitespace and the signature will not match.\n * app.post('/risicare-webhook', express.raw({ type: '*\\/*' }), (req, res) => {\n * try {\n * verifyWebhookSignature(req.body, req.headers, YOUR_WEBHOOK_SECRET);\n * } catch (e) {\n * if (e instanceof WebhookVerificationError) {\n * return res.status(401).send(e.message);\n * }\n * throw e;\n * }\n * // ... process the verified event ...\n * res.status(200).end();\n * });\n *\n * The helper is dependency-light (Node `crypto` stdlib only) so customers\n * can use it without pulling in the rest of the SDK if they only need\n * verification.\n *\n * Edge runtime note: this verifier is synchronous and uses Node's\n * `crypto.timingSafeEqual` + `crypto.createHmac`. It will not run in\n * Cloudflare Workers / Vercel Edge / Deno Deploy as-is. An async Web\n * Crypto variant can be added if customers request it.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport { Buffer } from 'node:buffer';\n\n/**\n * Default skew window (seconds). 5 minutes matches Stripe / GitHub /\n * common industry practice. Customers can override per-call if their\n * clock infrastructure warrants a tighter or looser bound.\n *\n * Mirrors `DEFAULT_TIMESTAMP_TOLERANCE_S` in the Python SDK.\n */\nexport const DEFAULT_TIMESTAMP_TOLERANCE_S = 300;\n\nconst SIGNATURE_HEADER = 'X-Risicare-Signature';\nconst TIMESTAMP_HEADER = 'X-Risicare-Timestamp';\n\n// The Python sender emits exactly one supported scheme today (`v1`). The\n// parser is structured so adding `v2` later is a non-breaking change:\n// list newer schemes first; the first match wins.\nconst SUPPORTED_SCHEMES = ['v1'] as const;\n\n// SHA-256 hex digest is always 64 lowercase hex chars. We pre-validate\n// the parsed signature against this shape BEFORE constant-time compare\n// so `Buffer.from(s, 'hex')` cannot silently truncate non-hex chars\n// (Node's Buffer.from 'hex' parser is lenient — it stops at the first\n// invalid character without raising).\nconst HEX_SHA256_RE = /^[0-9a-f]{64}$/;\n\n/**\n * Raised when a webhook delivery fails any verification check.\n *\n * Customers should catch this specifically rather than a generic `Error`\n * so verification failures are not conflated with other input problems\n * (e.g. body-parsing errors at the framework layer).\n *\n * The `message` is safe to log — it never includes the secret, the\n * expected signature, or the computed signature.\n */\nexport class WebhookVerificationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WebhookVerificationError';\n // Preserve prototype chain across the ES5/ES2022 transpilation\n // boundary so `instanceof` works for callers compiled to older\n // targets that interact with this library.\n Object.setPrototypeOf(this, WebhookVerificationError.prototype);\n }\n}\n\n/**\n * Options for `verifyWebhookSignature`. All fields are optional.\n */\nexport interface VerifyWebhookOptions {\n /**\n * Maximum clock-skew tolerance in seconds. Defaults to\n * `DEFAULT_TIMESTAMP_TOLERANCE_S` (300). Setting to 0 is supported\n * (strict same-second match) but discouraged in distributed\n * deployments.\n */\n toleranceS?: number;\n /**\n * Test hook — override \"current time\" in unix seconds.\n * Customers should not pass this.\n */\n _now?: number;\n}\n\n/**\n * Header-like inputs accepted by `verifyWebhookSignature`.\n *\n * Covers (a) Web API `Headers` (case-insensitive `.get`), (b) Node\n * `IncomingHttpHeaders` (plain object with lowercase keys, possibly\n * array-valued for multi-set headers), (c) `Map<string, string>`\n * (case-sensitive `.get`), and (d) plain `Record` (case-sensitive\n * property lookup, possibly array-valued).\n *\n * Lookup strategy: try the canonical mixed-case name first\n * (`X-Risicare-Signature`). If that returns undefined, fall back to the\n * lowercased form (`x-risicare-signature`). Mirrors the Python\n * `_get_header` helper.\n */\nexport type HeaderLookup =\n | Headers\n | Map<string, string>\n | Record<string, string | string[] | undefined>;\n\n/**\n * Payload shapes accepted by `verifyWebhookSignature`.\n *\n * `Buffer extends Uint8Array` in Node, so callers passing `Buffer`\n * satisfy the `Uint8Array` arm. `ArrayBuffer` is explicitly accepted\n * for callers using Web-API request bodies. `string` is UTF-8 encoded\n * internally.\n *\n * Crucially, callers must pass the EXACT bytes received over the\n * wire. Parsing JSON and re-serializing changes byte order and\n * whitespace; the signature will not match.\n */\nexport type WebhookPayload = Uint8Array | ArrayBuffer | string;\n\n/**\n * Look up a header by name, trying canonical mixed-case first, then\n * lowercase. Returns `undefined` if neither lookup yields a value.\n *\n * Web `Headers` and Node `IncomingHttpHeaders` are case-insensitive\n * lookups by spec; a plain `Record` is case-sensitive. We try both to\n * support either.\n */\nfunction getHeader(headers: HeaderLookup, name: string): string | undefined {\n const lower = name.toLowerCase();\n\n // Anything with a `.get(name)` method — covers Web `Headers`\n // (case-insensitive by spec, so the lowercase fallback is a no-op)\n // AND `Map<string, string>` (case-sensitive, so the fallback DOES\n // matter when the caller set lowercase keys). Web `Headers.get`\n // returns `null` for missing keys; Map returns `undefined`. Both\n // are normalised to `undefined` here.\n if (\n typeof (headers as { get?: (k: string) => unknown }).get === 'function'\n ) {\n const accessor = headers as { get: (k: string) => string | null | undefined };\n const v = accessor.get(name) ?? accessor.get(lower);\n return v ?? undefined;\n }\n\n // Plain object / IncomingHttpHeaders. IncomingHttpHeaders values\n // can be `string | string[] | undefined` (multi-set headers). For\n // a signature header there should only ever be one — but if a\n // client genuinely sets the same header twice, joining with `, `\n // would corrupt the signature. Take the first element only and let\n // a malformed-segment error surface downstream if the duplication\n // produced a problem.\n const dict = headers as Record<string, string | string[] | undefined>;\n const raw = dict[name] ?? dict[lower];\n if (raw === undefined) {\n return undefined;\n }\n if (Array.isArray(raw)) {\n return raw[0];\n }\n return raw;\n}\n\n/**\n * Coerce any accepted payload shape to a `Buffer` for HMAC consumption.\n *\n * `string` → UTF-8 encode.\n * `Uint8Array` (including `Buffer`) → `Buffer.from(uint8)` shares the\n * underlying ArrayBuffer with no copy.\n * `ArrayBuffer` → `Buffer.from(ab)` copies into a Node Buffer.\n *\n * Anything else throws `WebhookVerificationError`.\n */\nfunction coercePayload(payload: WebhookPayload): Buffer {\n if (typeof payload === 'string') {\n return Buffer.from(payload, 'utf-8');\n }\n // `Buffer` is a subclass of `Uint8Array`, so this arm covers both.\n if (payload instanceof Uint8Array) {\n return Buffer.from(\n payload.buffer,\n payload.byteOffset,\n payload.byteLength,\n );\n }\n if (payload instanceof ArrayBuffer) {\n return Buffer.from(payload);\n }\n throw new WebhookVerificationError(\n `payload must be Uint8Array, ArrayBuffer, Buffer, or string, got ${typeof payload}`,\n );\n}\n\n/**\n * Parse `t=<int>,v1=<hex>` (with possible additional unknown `kN=v`\n * segments) into `[timestamp, hex_signature]`.\n *\n * Tolerates extra segments for forward-compat: future scheme versions\n * may add new k=v pairs and this parser must not break.\n *\n * Mirrors `_parse_signature_header` in the Python SDK.\n */\nfunction parseSignatureHeader(raw: string): [number, string] {\n // Use a null-prototype object so a malicious segment like\n // `__proto__=v1=<hex>` or `constructor=...` cannot pollute the\n // global Object prototype via bracket-assignment, and so that\n // `'t' in parts` cannot return a false positive from inherited\n // properties like `toString` or `hasOwnProperty`. Python uses a\n // plain dict which has no equivalent prototype chain; this is a\n // JS-specific hardening with no Python counterpart.\n const parts: Record<string, string> = Object.create(null);\n\n for (const rawSegment of raw.split(',')) {\n const segment = rawSegment.trim();\n if (segment === '') {\n continue;\n }\n const eqIdx = segment.indexOf('=');\n if (eqIdx === -1) {\n throw new WebhookVerificationError(\n `Malformed segment in ${SIGNATURE_HEADER}: ${JSON.stringify(segment)}`,\n );\n }\n const key = segment.slice(0, eqIdx).trim();\n const value = segment.slice(eqIdx + 1).trim();\n parts[key] = value;\n }\n\n if (!('t' in parts)) {\n throw new WebhookVerificationError(\n `Missing \\`t=\\` (timestamp) in ${SIGNATURE_HEADER}`,\n );\n }\n\n // Pick the first supported scheme present. Today only `v1` exists.\n let scheme: string | undefined;\n for (const candidate of SUPPORTED_SCHEMES) {\n if (candidate in parts) {\n scheme = candidate;\n break;\n }\n }\n if (scheme === undefined) {\n // Sorted keys so the error message is deterministic regardless\n // of segment order in the input header.\n const keys = Object.keys(parts).sort();\n throw new WebhookVerificationError(\n `No supported signature scheme in ${SIGNATURE_HEADER}; ` +\n `expected one of (${SUPPORTED_SCHEMES.map((s) => `'${s}'`).join(', ')}), ` +\n `got keys [${keys.map((k) => `'${k}'`).join(', ')}]`,\n );\n }\n\n // parts['t'] is guaranteed defined by the `'t' in parts` check above.\n const tRaw = parts['t'] as string;\n // The segment was already `.trim()`ed during parsing, so leading /\n // trailing whitespace cannot reach here. The strict regex rejects\n // (a) empty string, (b) sign-only (\"-\", \"+\"), and (c) numeric-\n // prefix-then-garbage like \"123abc\" that `parseInt` would\n // permissively coerce to 123. Note: a leading `+` is rejected here\n // for parity with the Python sender's output (which is always\n // `str(int(time.time()))` — never carries a sign).\n if (!/^-?\\d+$/.test(tRaw)) {\n throw new WebhookVerificationError(\n `Non-integer timestamp in ${SIGNATURE_HEADER}: ${JSON.stringify(tRaw)}`,\n );\n }\n const ts = parseInt(tRaw, 10);\n if (!Number.isFinite(ts)) {\n // Defensive: a 21+ digit decimal string would `parseInt` to a\n // value outside `Number.MAX_SAFE_INTEGER`, and while `parseInt`\n // returns Infinity only for very specific inputs, treating any\n // non-finite result as a parse failure is the safe move.\n throw new WebhookVerificationError(\n `Non-integer timestamp in ${SIGNATURE_HEADER}: ${JSON.stringify(tRaw)}`,\n );\n }\n\n // scheme is one of SUPPORTED_SCHEMES so it's a known key.\n const sigHex = parts[scheme];\n if (sigHex === undefined || sigHex === '') {\n throw new WebhookVerificationError(\n `Empty ${scheme}= value in ${SIGNATURE_HEADER}`,\n );\n }\n\n return [ts, sigHex];\n}\n\n/**\n * Constant-time HMAC-SHA256 hex compare with explicit length pre-check.\n *\n * `crypto.timingSafeEqual` throws if the two buffers have different\n * lengths. To avoid leaking length information via the exception path,\n * we pre-validate the expected hex against the canonical sha256-hex\n * shape (64 lowercase hex chars) BEFORE attempting comparison. A\n * malformed expected → generic mismatch with no detail.\n *\n * The `computed` value comes from `createHmac(...).digest('hex')` and\n * is therefore always 64-char lowercase hex by construction; we don't\n * re-validate it.\n */\nfunction safeHexEqual(computed: string, expected: string): boolean {\n if (!HEX_SHA256_RE.test(expected)) {\n return false;\n }\n const a = Buffer.from(computed, 'hex');\n const b = Buffer.from(expected, 'hex');\n // Defensive: both buffers must be exactly 32 bytes after the regex\n // check above. If the platform ever returns a different length, the\n // explicit check below makes the failure mode a benign `false`\n // rather than a thrown RangeError from timingSafeEqual.\n if (a.length !== b.length) {\n return false;\n }\n return timingSafeEqual(a, b);\n}\n\n/**\n * Verify a Risicare webhook delivery. Throws `WebhookVerificationError`\n * on any failure; returns `undefined` on success.\n *\n * @param payload Raw request body bytes — the EXACT bytes received over\n * the wire. Re-serializing parsed JSON will change byte ordering and\n * break the signature.\n * @param headers Header lookup. Web `Headers`, `Map<string,string>`,\n * Node `IncomingHttpHeaders`, or plain `Record` all work. Lookup is\n * case-insensitive (canonical mixed-case tried first, then lowercase).\n * @param secret The shared secret configured on the Risicare webhook\n * record. Returned by `POST /v1/webhooks` once at create time.\n * @param opts Optional overrides — `toleranceS` (default 300) and\n * `_now` (test hook).\n *\n * @throws WebhookVerificationError on any of: missing headers, malformed\n * signature, timestamp outside tolerance, HMAC mismatch, or invalid\n * payload type.\n */\nexport function verifyWebhookSignature(\n payload: WebhookPayload,\n headers: HeaderLookup,\n secret: string,\n opts: VerifyWebhookOptions = {},\n): void {\n const toleranceS =\n opts.toleranceS ?? DEFAULT_TIMESTAMP_TOLERANCE_S;\n\n // Validate payload type FIRST so a caller passing a clearly-wrong\n // type gets the most informative error (same ordering as Python).\n const payloadBytes = coercePayload(payload);\n\n const sigHeader = getHeader(headers, SIGNATURE_HEADER);\n if (sigHeader === undefined || sigHeader === '') {\n throw new WebhookVerificationError(\n `Missing ${SIGNATURE_HEADER} header`,\n );\n }\n const tsHeader = getHeader(headers, TIMESTAMP_HEADER);\n if (tsHeader === undefined || tsHeader === '') {\n throw new WebhookVerificationError(\n `Missing ${TIMESTAMP_HEADER} header`,\n );\n }\n\n const [tsInSig, expectedHex] = parseSignatureHeader(sigHeader);\n\n // Cross-check: the standalone X-Risicare-Timestamp header MUST agree\n // with the t= value baked into the signature. A discrepancy means\n // the sender is buggy or someone has split the request — either way\n // refuse. Mirrors Python webhooks.py:214-217.\n if (!/^-?\\d+$/.test(tsHeader)) {\n throw new WebhookVerificationError(\n `Non-integer ${TIMESTAMP_HEADER}: ${JSON.stringify(tsHeader)}`,\n );\n }\n const tsStandalone = parseInt(tsHeader, 10);\n if (!Number.isFinite(tsStandalone)) {\n throw new WebhookVerificationError(\n `Non-integer ${TIMESTAMP_HEADER}: ${JSON.stringify(tsHeader)}`,\n );\n }\n if (tsStandalone !== tsInSig) {\n throw new WebhookVerificationError(\n `Timestamp mismatch: ${TIMESTAMP_HEADER}=${tsStandalone}, signature t=${tsInSig}`,\n );\n }\n\n const now =\n opts._now !== undefined\n ? Math.trunc(opts._now)\n : Math.floor(Date.now() / 1000);\n const skew = Math.abs(now - tsInSig);\n if (skew > toleranceS) {\n throw new WebhookVerificationError(\n `Webhook timestamp outside tolerance: skew=${skew}s, max=${toleranceS}s`,\n );\n }\n\n // Compute the canonical-string HMAC: `<ts>.<payload_bytes>`.\n // Two .update() calls is equivalent to one .update(concatenated)\n // and avoids materializing a copy of the payload.\n const hmac = createHmac('sha256', secret);\n hmac.update(`${tsInSig}.`);\n hmac.update(payloadBytes);\n const computed = hmac.digest('hex');\n\n if (!safeHexEqual(computed, expectedHex)) {\n // Deliberately generic message — leaking \"computed != expected\"\n // or the expected value would assist an attacker doing oracle\n // attacks. Mirrors Python webhooks.py:228-231.\n throw new WebhookVerificationError('Webhook signature mismatch');\n }\n}\n"],"mappings":";;;;;;;;AA+BA,SAAS,cAAAA,mBAAkB;;;ACb3B,SAAS,yBAAyB;AAGlC,IAAM,IAAI;AACV,IAAM,SAAS;AAIR,SAAS,YAAqB;AACnC,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAEO,SAAS,UAAU,QAAuB;AAC/C,IAAE,SAAS,QAAQ,IAAI;AACzB;AAEO,SAAS,YAAqB;AACnC,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAEO,SAAS,UAAU,QAAuB;AAC/C,IAAE,SAAS,QAAQ,IAAI;AACzB;AAIO,SAAS,oBAAgD;AAC9D,MAAI,CAAC,EAAE,SAAS,KAAK,GAAG;AACtB,MAAE,SAAS,KAAK,IAAI,IAAI,kBAAkB;AAAA,EAC5C;AACA,SAAO,EAAE,SAAS,KAAK;AACzB;AAIO,SAAS,cAAoC;AAClD,MAAI,CAAC,EAAE,SAAS,UAAU,GAAG;AAC3B,MAAE,SAAS,UAAU,IAAI,oBAAI,IAAI;AAAA,EACnC;AACA,SAAO,EAAE,SAAS,UAAU;AAC9B;AAEO,SAAS,aAAqB;AACnC,SAAO,EAAE,SAAS,SAAS,KAAK;AAClC;AAEO,SAAS,WAAW,GAAiB;AAC1C,IAAE,SAAS,SAAS,IAAI;AAC1B;AAIO,SAAS,WAAoB;AAClC,SAAO,EAAE,SAAS,OAAO,KAAK;AAChC;AAEO,SAAS,aAAa,SAAwB;AACnD,IAAE,SAAS,OAAO,IAAI;AACxB;;;AC5DO,SAAS,SAAS,SAAwB;AAC/C,eAAa,OAAO;AACtB;AAMO,SAAS,MAAM,KAAmB;AACvC,MAAI,SAAS,GAAG;AACd,YAAQ,OAAO,MAAM,cAAc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AY,GAAG;AAClC,UAAM,IAAI;AAAA,MACR,eAAe,gBAAgB,KAAK,KAAK,UAAU,QAAQ,CAAC;AAAA,IAC9D;AAAA,EACF;AACA,MAAI,iBAAiB,SAAS;AAC5B,UAAM,IAAI;AAAA,MACR,uBAAuB,gBAAgB,IAAI,YAAY,iBAAiB,OAAO;AAAA,IACjF;AAAA,EACF;AAEA,QAAM,MACJ,KAAK,SAAS,SACV,KAAK,MAAM,KAAK,IAAI,IACpB,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAClC,QAAM,OAAO,KAAK,IAAI,MAAM,OAAO;AACnC,MAAI,OAAO,YAAY;AACrB,UAAM,IAAI;AAAA,MACR,6CAA6C,IAAI,UAAU,UAAU;AAAA,IACvE;AAAA,EACF;AAKA,QAAM,OAAO,WAAW,UAAU,MAAM;AACxC,OAAK,OAAO,GAAG,OAAO,GAAG;AACzB,OAAK,OAAO,YAAY;AACxB,QAAM,WAAW,KAAK,OAAO,KAAK;AAElC,MAAI,CAAC,aAAa,UAAU,WAAW,GAAG;AAIxC,UAAM,IAAI,yBAAyB,4BAA4B;AAAA,EACjE;AACF;","names":["createHash","debug","SpanKind","SpanStatus","SemanticPhase","AgentRole","MessageType","session","agent","G","G","getTracer","createHash","getTracer","agent","getTracer","getTracer","session","getTracer","getTracer","session","agent","getTracer","getTracer","getTracer","getTracer","getTracer","Buffer"]}
|