risicare 0.5.0 → 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 +44 -6
- package/dist/frameworks/instructor.cjs +9 -0
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.js +9 -0
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs +9 -0
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.js +9 -0
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs +9 -0
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js +9 -0
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs +9 -0
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.js +9 -0
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +685 -313
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -2
- package/dist/index.d.ts +38 -2
- package/dist/index.js +685 -313
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs +9 -0
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.js +9 -0
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs +9 -0
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.js +9 -0
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs +9 -0
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js +9 -0
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs +9 -0
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js +9 -0
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs +9 -0
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js +9 -0
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs +9 -0
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js +9 -0
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs +9 -0
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.js +9 -0
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs +9 -0
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js +9 -0
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs +9 -0
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js +9 -0
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs +9 -0
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.js +9 -0
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs +9 -0
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js +9 -0
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs +9 -0
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.js +9 -0
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/client.ts","../../../src/globals.ts","../../../src/utils/log.ts","../../../src/exporters/batch.ts","../../../src/ids.ts","../../../src/noop.ts","../../../src/context/storage.ts","../../../src/runtime/applier.ts","../../../src/utils/pricing.ts","../../../src/utils/assert-client.ts","../../../src/context/dedup.ts","../../../src/providers/together/patch.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 });\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 });\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 return tracer?.traceContent ?? true;\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 * 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 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\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 private readonly _debug: boolean;\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 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._debug = options.debug ?? false;\n this._mask = options.mask;\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 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 * ID generation for traces and spans.\n *\n * Trace IDs: 32 lowercase hex characters (16 random bytes)\n * Span IDs: 16 lowercase hex characters (8 random bytes)\n *\n * Uses crypto.randomBytes for cryptographically secure randomness.\n */\n\nimport { randomBytes } from 'node:crypto';\n\nconst HEX_REGEX_32 = /^[0-9a-f]{32}$/;\nconst HEX_REGEX_16 = /^[0-9a-f]{16}$/;\n\nexport function generateTraceId(): string {\n return randomBytes(16).toString('hex');\n}\n\nexport function generateSpanId(): string {\n return randomBytes(8).toString('hex');\n}\n\nexport function generateAgentId(prefix?: string): string {\n const suffix = randomBytes(8).toString('hex');\n return prefix ? `${prefix}-${suffix}` : suffix;\n}\n\nexport function validateTraceId(id: string): boolean {\n return HEX_REGEX_32.test(id);\n}\n\nexport function validateSpanId(id: string): boolean {\n return HEX_REGEX_16.test(id);\n}\n","/**\n * No-op implementations for the disabled path.\n *\n * When tracing is disabled, all operations return these no-op objects\n * to maintain zero overhead. No allocations, no side effects.\n */\n\nimport { SpanKind, SpanStatus, type SpanPayload } from './types.js';\n\n/**\n * A frozen no-op span that silently ignores all operations.\n * Used when SDK is disabled to avoid overhead.\n */\nexport const NOOP_SPAN = Object.freeze({\n traceId: '00000000000000000000000000000000',\n spanId: '0000000000000000',\n parentSpanId: undefined,\n name: 'noop',\n kind: SpanKind.INTERNAL,\n startTime: '',\n startHrtime: 0,\n endTime: undefined,\n status: SpanStatus.UNSET,\n statusMessage: undefined,\n attributes: Object.freeze({}) as Record<string, unknown>,\n events: Object.freeze([]) as readonly [],\n links: Object.freeze([]) as readonly [],\n sessionId: undefined,\n agentId: undefined,\n agentName: undefined,\n semanticPhase: undefined,\n llmProvider: undefined,\n llmModel: undefined,\n llmPromptTokens: undefined,\n llmCompletionTokens: undefined,\n llmTotalTokens: undefined,\n llmCostUsd: undefined,\n toolName: undefined,\n toolSuccess: undefined,\n isEnded: true,\n durationMs: 0,\n\n setAttribute() { return this; },\n setAttributes() { return this; },\n setStatus() { return this; },\n addEvent() { return this; },\n addLink() { return this; },\n recordException() { return this; },\n setLlmFields() { return this; },\n setToolFields() { return this; },\n end() {},\n toPayload(): SpanPayload {\n return {\n traceId: this.traceId,\n spanId: this.spanId,\n name: this.name,\n kind: this.kind,\n startTime: this.startTime,\n status: this.status,\n attributes: {},\n events: [],\n links: [],\n };\n },\n});\n\nexport type NoopSpan = typeof NOOP_SPAN;\n","/**\n * 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\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 * 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 * Token cost calculation table.\n *\n * Prices are per 1M tokens. Update monthly.\n * Source: provider pricing pages.\n */\n\ninterface ModelPricing {\n input: number; // USD per 1M input tokens\n output: number; // USD per 1M output tokens\n}\n\nconst PRICING: Record<string, ModelPricing> = {\n // OpenAI\n 'gpt-4o': { input: 2.50, output: 10.00 },\n 'gpt-4o-mini': { input: 0.15, output: 0.60 },\n 'gpt-4-turbo': { input: 10.00, output: 30.00 },\n 'gpt-4': { input: 30.00, output: 60.00 },\n 'gpt-3.5-turbo': { input: 0.50, output: 1.50 },\n 'o1': { input: 15.00, output: 60.00 },\n 'o1-mini': { input: 3.00, output: 12.00 },\n 'o3-mini': { input: 1.10, output: 4.40 },\n\n // Anthropic\n 'claude-opus-4-5-20251101': { input: 15.00, output: 75.00 },\n 'claude-sonnet-4-5-20250929': { input: 3.00, output: 15.00 },\n 'claude-haiku-4-5-20251001': { input: 0.80, output: 4.00 },\n 'claude-3-5-sonnet-20241022': { input: 3.00, output: 15.00 },\n 'claude-3-haiku-20240307': { input: 0.25, output: 1.25 },\n 'claude-3-opus-20240229': { input: 15.00, output: 75.00 },\n\n // Google\n 'gemini-2.0-flash': { input: 0.10, output: 0.40 },\n 'gemini-1.5-pro': { input: 1.25, output: 5.00 },\n 'gemini-1.5-flash': { input: 0.075, output: 0.30 },\n\n // Groq\n 'llama-3.3-70b-versatile': { input: 0.59, output: 0.79 },\n 'llama-3.1-8b-instant': { input: 0.05, output: 0.08 },\n 'mixtral-8x7b-32768': { input: 0.24, output: 0.24 },\n\n // DeepSeek\n 'deepseek-chat': { input: 0.14, output: 0.28 },\n 'deepseek-reasoner': { input: 0.55, output: 2.19 },\n\n // Together.ai (open-source models)\n 'meta-llama/llama-3.3-70b-instruct-turbo': { input: 0.88, output: 0.88 },\n 'meta-llama/meta-llama-3.1-8b-instruct-turbo': { input: 0.18, output: 0.18 },\n 'meta-llama/llama-3.2-3b-instruct-turbo': { input: 0.06, output: 0.06 },\n 'qwen/qwen2.5-7b-instruct-turbo': { input: 0.20, output: 0.20 },\n 'mistralai/mistral-small-24b-instruct-2501': { input: 0.20, output: 0.20 },\n 'mistralai/mixtral-8x7b-instruct-v0.1': { input: 0.60, output: 0.60 },\n 'deepseek-ai/deepseek-v3': { input: 0.27, output: 1.10 },\n};\n\n/**\n * Calculate cost in USD for a model's token usage.\n * Returns undefined if model is not in pricing table.\n */\nexport function calculateCost(\n model: string,\n promptTokens: number,\n completionTokens: number,\n): number | undefined {\n const pricing = PRICING[model] ?? PRICING[model.toLowerCase()];\n if (!pricing) return undefined;\n\n const inputCost = (promptTokens / 1_000_000) * pricing.input;\n const outputCost = (completionTokens / 1_000_000) * pricing.output;\n return inputCost + outputCost;\n}\n\n/**\n * Check if a model has pricing data.\n */\nexport function hasPricing(model: string): boolean {\n return model in PRICING || model.toLowerCase() in PRICING;\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 * 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 * Together AI (together-ai) Proxy-based instrumentation.\n *\n * Together's API is OpenAI-compatible (chat.completions.create). This instrumentor\n * follows the exact same nested-proxy pattern as the Groq one but labels spans\n * as \"together\".\n *\n * Usage:\n * import Together from 'together-ai';\n * import { patchTogether } from 'risicare/together';\n * const together = patchTogether(new Together({ apiKey: '...' }));\n */\n\nimport { requireTracer } from '../../client.js';\nimport { SpanKind } from '../../types.js';\nimport { calculateCost } from '../../utils/pricing.js';\nimport { debug } from '../../utils/log.js';\nimport { assertClient } from '../../utils/assert-client.js';\nimport { isProviderInstrumentationSuppressed } from '../../context/dedup.js';\nimport type { Span } from '../../span.js';\n\n/**\n * Extract request-time attributes from the API call parameters.\n */\nfunction enrichSpanFromRequest(span: Span, params: Record<string, unknown>): void {\n const model = params.model as string | undefined;\n if (model) {\n span.setAttribute('gen_ai.system', 'together');\n span.setAttribute('gen_ai.request.model', model);\n }\n if (params.temperature !== undefined) span.setAttribute('gen_ai.request.temperature', params.temperature);\n if (params.max_tokens !== undefined) span.setAttribute('gen_ai.request.max_tokens', params.max_tokens);\n if (params.top_p !== undefined) span.setAttribute('gen_ai.request.top_p', params.top_p);\n if (params.frequency_penalty !== undefined) span.setAttribute('gen_ai.request.frequency_penalty', params.frequency_penalty);\n if (params.presence_penalty !== undefined) span.setAttribute('gen_ai.request.presence_penalty', params.presence_penalty);\n if (params.stream !== undefined) span.setAttribute('llm.stream', !!params.stream);\n}\n\n/**\n * Extract response-time attributes from the API response.\n */\nfunction enrichFromResponse(span: Span, response: Record<string, unknown>): void {\n try {\n const model = response.model as string | undefined;\n const usage = response.usage as Record<string, number> | undefined;\n\n if (model) {\n span.setLlmFields({ model });\n span.setAttribute('gen_ai.response.model', model);\n }\n\n // Response ID\n if (response.id) span.setAttribute('gen_ai.response.id', response.id);\n\n // Finish reasons from choices (OpenAI-compatible)\n const choices = response.choices as Array<Record<string, unknown>> | undefined;\n if (Array.isArray(choices) && choices.length > 0) {\n const reasons = choices.map(c => c.finish_reason).filter(Boolean);\n if (reasons.length > 0) span.setAttribute('gen_ai.response.finish_reasons', reasons);\n }\n\n if (usage) {\n const promptTokens = usage.prompt_tokens ?? 0;\n const completionTokens = usage.completion_tokens ?? 0;\n const totalTokens = usage.total_tokens ?? (promptTokens + completionTokens);\n const cost = (model ?? span.llmModel)\n ? calculateCost(model ?? span.llmModel ?? '', promptTokens, completionTokens)\n : undefined;\n\n span.setLlmFields({ promptTokens, completionTokens, totalTokens, costUsd: cost });\n\n // Also set as gen_ai attributes for worker column promotion\n span.setAttribute('gen_ai.usage.prompt_tokens', promptTokens);\n span.setAttribute('gen_ai.usage.completion_tokens', completionTokens);\n span.setAttribute('gen_ai.usage.total_tokens', totalTokens);\n if (cost !== undefined) span.setAttribute('llm.cost.total_usd', cost);\n }\n } catch {\n // Never fail enrichment\n }\n}\n\nfunction createCompletionProxy(originalCreate: Function): Function {\n return function patchedCreate(this: unknown, ...args: unknown[]) {\n if (isProviderInstrumentationSuppressed()) {\n return originalCreate.apply(this, args);\n }\n\n let tracer;\n try {\n tracer = requireTracer();\n } catch {\n debug('Tracer not initialized — call init() before using patchTogether()');\n return originalCreate.apply(this, args);\n }\n\n const params = (args[0] ?? {}) as Record<string, unknown>;\n const model = (params.model as string) ?? 'unknown';\n const isStream = !!params.stream;\n\n return tracer.startSpan(\n { name: 'together.chat.completions.create', kind: SpanKind.LLM_CALL, attributes: { 'llm.request.model': model, 'llm.stream': isStream } },\n (span) => {\n span.setLlmFields({ provider: 'together', model });\n enrichSpanFromRequest(span, params);\n\n const result = originalCreate.apply(this, args);\n\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n return (result as Promise<Record<string, unknown>>).then((response) => {\n if (!isStream && response) {\n enrichFromResponse(span, response);\n }\n return response;\n });\n }\n\n return result;\n },\n );\n };\n}\n\n/**\n * Wrap a Together AI client instance with tracing instrumentation.\n *\n * Returns a Proxy that intercepts chat.completions.create.\n * The original client is NOT modified.\n *\n * @param client - A Together AI SDK client instance\n * @returns A proxied client with automatic tracing\n */\nexport function patchTogether<T extends object>(client: T): T {\n assertClient('patchTogether', client);\n return new Proxy(client, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\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\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\n if (compProp === 'create' && typeof compValue === 'function') {\n return createCompletionProxy(compValue.bind(compTarget));\n }\n\n return compValue;\n },\n });\n }\n\n return chatValue;\n },\n });\n }\n\n return value;\n },\n });\n}\n"],"mappings":";AA+BA,SAAS,cAAAA,mBAAkB;;;ACb3B,SAAS,yBAAyB;AAGlC,IAAM,IAAI;AACV,IAAM,SAAS;AAYR,SAAS,YAAqB;AACnC,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAQO,SAAS,oBAAgD;AAC9D,MAAI,CAAC,EAAE,SAAS,KAAK,GAAG;AACtB,MAAE,SAAS,KAAK,IAAI,IAAI,kBAAkB;AAAA,EAC5C;AACA,SAAO,EAAE,SAAS,KAAK;AACzB;AAqBO,SAAS,WAAoB;AAClC,SAAO,EAAE,SAAS,OAAO,KAAK;AAChC;;;AChDO,SAAS,MAAM,KAAmB;AACvC,MAAI,SAAS,GAAG;AACd,YAAQ,OAAO,MAAM,cAAc,GAAG;AAAA,CAAI;AAAA,EAC5C;AACF;;;AC+MO,IAAM,kBAAkB,IAAI,OAAO;AA0B1C,IAAM,iBACJ,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,aAC1D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AA,IACF;AAAA,EACF;AACF;AAWO,SAAS,cAAgC,QAAc;AAC5D,eAAa,iBAAiB,MAAM;AACpC,SAAO,IAAI,MAAM,QAAQ;AAAA,IACvB,IAAI,QAAQ,MAAM,UAAU;AAC1B,YAAM,QAAQ,QAAQ,IAAI,QAAQ,MAAM,QAAQ;AAEhD,UAAI,SAAS,UAAU,SAAS,OAAO,UAAU,UAAU;AACzD,eAAO,IAAI,MAAM,OAAiB;AAAA,UAChC,IAAI,YAAY,UAAU,cAAc;AACtC,kBAAM,YAAY,QAAQ,IAAI,YAAY,UAAU,YAAY;AAEhE,gBAAI,aAAa,iBAAiB,aAAa,OAAO,cAAc,UAAU;AAC5E,qBAAO,IAAI,MAAM,WAAqB;AAAA,gBACpC,IAAI,YAAY,UAAU,cAAc;AACtC,wBAAM,YAAY,QAAQ,IAAI,YAAY,UAAU,YAAY;AAEhE,sBAAI,aAAa,YAAY,OAAO,cAAc,YAAY;AAC5D,2BAAO,sBAAsB,UAAU,KAAK,UAAU,CAAC;AAAA,kBACzD;AAEA,yBAAO;AAAA,gBACT;AAAA,cACF,CAAC;AAAA,YACH;AAEA,mBAAO;AAAA,UACT;AAAA,QACF,CAAC;AAAA,MACH;AAEA,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":["createHash"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/client.ts","../../../src/globals.ts","../../../src/utils/log.ts","../../../src/exporters/batch.ts","../../../src/ids.ts","../../../src/noop.ts","../../../src/runtime/taxonomy.generated.ts","../../../src/context/storage.ts","../../../src/runtime/applier.ts","../../../src/utils/pricing.ts","../../../src/utils/assert-client.ts","../../../src/context/dedup.ts","../../../src/providers/together/patch.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 * 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 * ID generation for traces and spans.\n *\n * Trace IDs: 32 lowercase hex characters (16 random bytes)\n * Span IDs: 16 lowercase hex characters (8 random bytes)\n *\n * Uses crypto.randomBytes for cryptographically secure randomness.\n */\n\nimport { randomBytes } from 'node:crypto';\n\nconst HEX_REGEX_32 = /^[0-9a-f]{32}$/;\nconst HEX_REGEX_16 = /^[0-9a-f]{16}$/;\n\nexport function generateTraceId(): string {\n return randomBytes(16).toString('hex');\n}\n\nexport function generateSpanId(): string {\n return randomBytes(8).toString('hex');\n}\n\nexport function generateAgentId(prefix?: string): string {\n const suffix = randomBytes(8).toString('hex');\n return prefix ? `${prefix}-${suffix}` : suffix;\n}\n\nexport function validateTraceId(id: string): boolean {\n return HEX_REGEX_32.test(id);\n}\n\nexport function validateSpanId(id: string): boolean {\n return HEX_REGEX_16.test(id);\n}\n","/**\n * No-op implementations for the disabled path.\n *\n * When tracing is disabled, all operations return these no-op objects\n * to maintain zero overhead. No allocations, no side effects.\n */\n\nimport { SpanKind, SpanStatus, type SpanPayload } from './types.js';\n\n/**\n * A frozen no-op span that silently ignores all operations.\n * Used when SDK is disabled to avoid overhead.\n */\nexport const NOOP_SPAN = Object.freeze({\n traceId: '00000000000000000000000000000000',\n spanId: '0000000000000000',\n parentSpanId: undefined,\n name: 'noop',\n kind: SpanKind.INTERNAL,\n startTime: '',\n startHrtime: 0,\n endTime: undefined,\n status: SpanStatus.UNSET,\n statusMessage: undefined,\n attributes: Object.freeze({}) as Record<string, unknown>,\n events: Object.freeze([]) as readonly [],\n links: Object.freeze([]) as readonly [],\n sessionId: undefined,\n agentId: undefined,\n agentName: undefined,\n semanticPhase: undefined,\n llmProvider: undefined,\n llmModel: undefined,\n llmPromptTokens: undefined,\n llmCompletionTokens: undefined,\n llmTotalTokens: undefined,\n llmCostUsd: undefined,\n toolName: undefined,\n toolSuccess: undefined,\n isEnded: true,\n durationMs: 0,\n\n setAttribute() { return this; },\n setAttributes() { return this; },\n setStatus() { return this; },\n addEvent() { return this; },\n addLink() { return this; },\n recordException() { return this; },\n setLlmFields() { return this; },\n setToolFields() { return this; },\n end() {},\n toPayload(): SpanPayload {\n return {\n traceId: this.traceId,\n spanId: this.spanId,\n name: this.name,\n kind: this.kind,\n startTime: this.startTime,\n status: this.status,\n attributes: {},\n events: [],\n links: [],\n };\n },\n});\n\nexport type NoopSpan = typeof NOOP_SPAN;\n","// ⚠ 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 * 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 * 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 * Token cost calculation table.\n *\n * Prices are per 1M tokens. Update monthly.\n * Source: provider pricing pages.\n */\n\ninterface ModelPricing {\n input: number; // USD per 1M input tokens\n output: number; // USD per 1M output tokens\n}\n\nconst PRICING: Record<string, ModelPricing> = {\n // OpenAI\n 'gpt-4o': { input: 2.50, output: 10.00 },\n 'gpt-4o-mini': { input: 0.15, output: 0.60 },\n 'gpt-4-turbo': { input: 10.00, output: 30.00 },\n 'gpt-4': { input: 30.00, output: 60.00 },\n 'gpt-3.5-turbo': { input: 0.50, output: 1.50 },\n 'o1': { input: 15.00, output: 60.00 },\n 'o1-mini': { input: 3.00, output: 12.00 },\n 'o3-mini': { input: 1.10, output: 4.40 },\n\n // Anthropic\n 'claude-opus-4-5-20251101': { input: 15.00, output: 75.00 },\n 'claude-sonnet-4-5-20250929': { input: 3.00, output: 15.00 },\n 'claude-haiku-4-5-20251001': { input: 0.80, output: 4.00 },\n 'claude-3-5-sonnet-20241022': { input: 3.00, output: 15.00 },\n 'claude-3-haiku-20240307': { input: 0.25, output: 1.25 },\n 'claude-3-opus-20240229': { input: 15.00, output: 75.00 },\n\n // Google\n 'gemini-2.0-flash': { input: 0.10, output: 0.40 },\n 'gemini-1.5-pro': { input: 1.25, output: 5.00 },\n 'gemini-1.5-flash': { input: 0.075, output: 0.30 },\n\n // Groq\n 'llama-3.3-70b-versatile': { input: 0.59, output: 0.79 },\n 'llama-3.1-8b-instant': { input: 0.05, output: 0.08 },\n 'mixtral-8x7b-32768': { input: 0.24, output: 0.24 },\n\n // DeepSeek\n 'deepseek-chat': { input: 0.14, output: 0.28 },\n 'deepseek-reasoner': { input: 0.55, output: 2.19 },\n\n // Together.ai (open-source models)\n 'meta-llama/llama-3.3-70b-instruct-turbo': { input: 0.88, output: 0.88 },\n 'meta-llama/meta-llama-3.1-8b-instruct-turbo': { input: 0.18, output: 0.18 },\n 'meta-llama/llama-3.2-3b-instruct-turbo': { input: 0.06, output: 0.06 },\n 'qwen/qwen2.5-7b-instruct-turbo': { input: 0.20, output: 0.20 },\n 'mistralai/mistral-small-24b-instruct-2501': { input: 0.20, output: 0.20 },\n 'mistralai/mixtral-8x7b-instruct-v0.1': { input: 0.60, output: 0.60 },\n 'deepseek-ai/deepseek-v3': { input: 0.27, output: 1.10 },\n};\n\n/**\n * Calculate cost in USD for a model's token usage.\n * Returns undefined if model is not in pricing table.\n */\nexport function calculateCost(\n model: string,\n promptTokens: number,\n completionTokens: number,\n): number | undefined {\n const pricing = PRICING[model] ?? PRICING[model.toLowerCase()];\n if (!pricing) return undefined;\n\n const inputCost = (promptTokens / 1_000_000) * pricing.input;\n const outputCost = (completionTokens / 1_000_000) * pricing.output;\n return inputCost + outputCost;\n}\n\n/**\n * Check if a model has pricing data.\n */\nexport function hasPricing(model: string): boolean {\n return model in PRICING || model.toLowerCase() in PRICING;\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 * 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 * Together AI (together-ai) Proxy-based instrumentation.\n *\n * Together's API is OpenAI-compatible (chat.completions.create). This instrumentor\n * follows the exact same nested-proxy pattern as the Groq one but labels spans\n * as \"together\".\n *\n * Usage:\n * import Together from 'together-ai';\n * import { patchTogether } from 'risicare/together';\n * const together = patchTogether(new Together({ apiKey: '...' }));\n */\n\nimport { requireTracer } from '../../client.js';\nimport { SpanKind } from '../../types.js';\nimport { calculateCost } from '../../utils/pricing.js';\nimport { debug } from '../../utils/log.js';\nimport { assertClient } from '../../utils/assert-client.js';\nimport { isProviderInstrumentationSuppressed } from '../../context/dedup.js';\nimport type { Span } from '../../span.js';\n\n/**\n * Extract request-time attributes from the API call parameters.\n */\nfunction enrichSpanFromRequest(span: Span, params: Record<string, unknown>): void {\n const model = params.model as string | undefined;\n if (model) {\n span.setAttribute('gen_ai.system', 'together');\n span.setAttribute('gen_ai.request.model', model);\n }\n if (params.temperature !== undefined) span.setAttribute('gen_ai.request.temperature', params.temperature);\n if (params.max_tokens !== undefined) span.setAttribute('gen_ai.request.max_tokens', params.max_tokens);\n if (params.top_p !== undefined) span.setAttribute('gen_ai.request.top_p', params.top_p);\n if (params.frequency_penalty !== undefined) span.setAttribute('gen_ai.request.frequency_penalty', params.frequency_penalty);\n if (params.presence_penalty !== undefined) span.setAttribute('gen_ai.request.presence_penalty', params.presence_penalty);\n if (params.stream !== undefined) span.setAttribute('llm.stream', !!params.stream);\n}\n\n/**\n * Extract response-time attributes from the API response.\n */\nfunction enrichFromResponse(span: Span, response: Record<string, unknown>): void {\n try {\n const model = response.model as string | undefined;\n const usage = response.usage as Record<string, number> | undefined;\n\n if (model) {\n span.setLlmFields({ model });\n span.setAttribute('gen_ai.response.model', model);\n }\n\n // Response ID\n if (response.id) span.setAttribute('gen_ai.response.id', response.id);\n\n // Finish reasons from choices (OpenAI-compatible)\n const choices = response.choices as Array<Record<string, unknown>> | undefined;\n if (Array.isArray(choices) && choices.length > 0) {\n const reasons = choices.map(c => c.finish_reason).filter(Boolean);\n if (reasons.length > 0) span.setAttribute('gen_ai.response.finish_reasons', reasons);\n }\n\n if (usage) {\n const promptTokens = usage.prompt_tokens ?? 0;\n const completionTokens = usage.completion_tokens ?? 0;\n const totalTokens = usage.total_tokens ?? (promptTokens + completionTokens);\n const cost = (model ?? span.llmModel)\n ? calculateCost(model ?? span.llmModel ?? '', promptTokens, completionTokens)\n : undefined;\n\n span.setLlmFields({ promptTokens, completionTokens, totalTokens, costUsd: cost });\n\n // Also set as gen_ai attributes for worker column promotion\n span.setAttribute('gen_ai.usage.prompt_tokens', promptTokens);\n span.setAttribute('gen_ai.usage.completion_tokens', completionTokens);\n span.setAttribute('gen_ai.usage.total_tokens', totalTokens);\n if (cost !== undefined) span.setAttribute('llm.cost.total_usd', cost);\n }\n } catch {\n // Never fail enrichment\n }\n}\n\nfunction createCompletionProxy(originalCreate: Function): Function {\n return function patchedCreate(this: unknown, ...args: unknown[]) {\n if (isProviderInstrumentationSuppressed()) {\n return originalCreate.apply(this, args);\n }\n\n let tracer;\n try {\n tracer = requireTracer();\n } catch {\n debug('Tracer not initialized — call init() before using patchTogether()');\n return originalCreate.apply(this, args);\n }\n\n const params = (args[0] ?? {}) as Record<string, unknown>;\n const model = (params.model as string) ?? 'unknown';\n const isStream = !!params.stream;\n\n return tracer.startSpan(\n { name: 'together.chat.completions.create', kind: SpanKind.LLM_CALL, attributes: { 'llm.request.model': model, 'llm.stream': isStream } },\n (span) => {\n span.setLlmFields({ provider: 'together', model });\n enrichSpanFromRequest(span, params);\n\n const result = originalCreate.apply(this, args);\n\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n return (result as Promise<Record<string, unknown>>).then((response) => {\n if (!isStream && response) {\n enrichFromResponse(span, response);\n }\n return response;\n });\n }\n\n return result;\n },\n );\n };\n}\n\n/**\n * Wrap a Together AI client instance with tracing instrumentation.\n *\n * Returns a Proxy that intercepts chat.completions.create.\n * The original client is NOT modified.\n *\n * @param client - A Together AI SDK client instance\n * @returns A proxied client with automatic tracing\n */\nexport function patchTogether<T extends object>(client: T): T {\n assertClient('patchTogether', client);\n return new Proxy(client, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\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\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\n if (compProp === 'create' && typeof compValue === 'function') {\n return createCompletionProxy(compValue.bind(compTarget));\n }\n\n return compValue;\n },\n });\n }\n\n return chatValue;\n },\n });\n }\n\n return value;\n },\n });\n}\n"],"mappings":";AA+BA,SAAS,cAAAA,mBAAkB;;;ACb3B,SAAS,yBAAyB;AAGlC,IAAM,IAAI;AACV,IAAM,SAAS;AAYR,SAAS,YAAqB;AACnC,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAQO,SAAS,oBAAgD;AAC9D,MAAI,CAAC,EAAE,SAAS,KAAK,GAAG;AACtB,MAAE,SAAS,KAAK,IAAI,IAAI,kBAAkB;AAAA,EAC5C;AACA,SAAO,EAAE,SAAS,KAAK;AACzB;AAqBO,SAAS,WAAoB;AAClC,SAAO,EAAE,SAAS,OAAO,KAAK;AAChC;;;AChDO,SAAS,MAAM,KAAmB;AACvC,MAAI,SAAS,GAAG;AACd,YAAQ,OAAO,MAAM,cAAc,GAAG;AAAA,CAAI;AAAA,EAC5C;AACF;;;ACuNO,IAAM,kBAAkB,IAAI,OAAO;AA0B1C,IAAM,iBACJ,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,aAC1D,CAAC,MAAM,OAAO,WAAW,GAAG,MAAM,IAClC,CAAC,MAAM,EAAE,SAAS;;;ACvQxB,SAAS,mBAAmB;;;ACIrB,IAAM,YAAY,OAAO,OAAO;AAAA,EACrC,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,MAAM;AAAA,EACN;AAAA,EACA,WAAW;AAAA,EACX,aAAa;AAAA,EACb,SAAS;AAAA,EACT;AAAA,EACA,eAAe;AAAA,EACf,YAAY,OAAO,OAAO,CAAC,CAAC;AAAA,EAC5B,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