@cultured_computer/sight 0.6.0 → 0.8.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/CHANGELOG.md +257 -0
- package/README.md +482 -88
- package/dist/cli.js +242 -27
- package/dist/index.cjs +1470 -224
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1034 -112
- package/dist/index.d.ts +1034 -112
- package/dist/index.js +1459 -226
- package/dist/index.js.map +1 -1
- package/package.json +17 -14
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/types.ts","../src/client-context.ts","../src/session-bounds.ts","../src/hash.ts","../src/instrumentation/session-context.ts","../src/instrumentation/otel-processor.ts","../src/instrumentation/wrap-openai.ts","../src/instrumentation/setup.ts","../src/instrumentation/openai.ts","../src/instrumentation/anthropic.ts","../src/instrumentation/langchain.ts","../src/instrumentation/langgraph.ts","../src/instrumentation/vercel-ai.ts","../src/instrumentation/litellm.ts","../src/instrumentation/mercury.ts","../src/instrumentation/index.ts","../../classifier/src/signature-phrase.ts","../../shared/src/effectiveness-gap.ts","../../shared/src/index.ts","../src/probe.ts"],"names":["body","z","context","propagation","state","asString","asNumber","messageText","value","trace","registered","instrumentation"],"mappings":";;;;;;AAyBO,IAAM,qBAAA,GAAwB,2CAAA;AAQrC,IAAM,mBAAA,GAAsB,EAAA;AAO5B,IAAM,eAAA,GAAkB,IAAA;AAOxB,IAAM,YAAA,GAAe,EAAA;AAOrB,IAAM,mBAAA,GAAsB,GAAA;AAErB,IAAM,eAAN,MAAmB;AAAA,EAChB,MAAA;AAAA,EACA,QAAA;AAAA,EACA,KAAA;AAAA,EACA,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,qBAAA,GAAwB,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQxB,kBAAA,GAAqB,KAAA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M,OAAO,KAAA;AAC3B,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,UAAA;AAC1B,IAAA,IAAI,IAAA,IAAQ,GAAK,OAAO,IAAA;AACxB,IAAA,IAAI,IAAA,IAAQ,GAAK,OAAO,KAAA;AAGxB,IAAA,MAAM,GAAA,GAAM,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,SAAS,CAAA,CAAA;AACrC,IAAA,IAAI,IAAA,GAAO,UAAA;AACX,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,QAAQ,CAAA,EAAA,EAAK;AACnC,MAAA,IAAA,IAAQ,GAAA,CAAI,WAAW,CAAC,CAAA;AACxB,MAAA,IAAA,GAAQ,OAAO,QAAA,KAAgB,CAAA;AAAA,IACjC;AACA,IAAA,OAAO,OAAO,UAAA,GAAa,IAAA;AAAA,EAC7B;AACF","file":"index.cjs","sourcesContent":["/**\n * HTTP client for the Probe ingest API.\n *\n * Sends captured turns to POST /v1/turns with a Bearer token. Async, fire-and-log:\n * SDK never blocks the customer's LLM path on ingest. Rate-limited sends (429)\n * are retried exactly once after Retry-After; sustained limiting drops captures.\n */\n\nimport type { EnvironmentEventsBatch, SpansBatch } from '@fieldwork/shared';\nimport type {\n CapturedTurn,\n FlagPersonaBreakInput,\n OutcomeEventEmit,\n SessionEndInput,\n} from './types';\n\nexport type IngestClientOptions = {\n apiKey: string;\n endpoint: string;\n debug: boolean;\n /** Dashboard base URL for the one-time first-capture announcement. */\n dashboardUrl?: string;\n};\n\n/** Default dashboard base for the first-capture permalink. */\nexport const DEFAULT_DASHBOARD_URL = 'https://sight.cultured.computer/dashboard';\n\n/**\n * Cap on concurrently pending 429 retries. A counter, not a queue: once this\n * many retries are waiting on their Retry-After timers, further rate-limited\n * requests are dropped instead of scheduled. Bounds memory under sustained\n * limiting — the SDK sheds load rather than buffering it.\n */\nconst MAX_PENDING_RETRIES = 50;\n\n/**\n * Per-send timeout: a hung ingest connection must never leak sockets or\n * pending promises into the host (production-safety audit B1, 2026-07-22).\n * Generous — ingest answers in ~50ms; a cold start in seconds.\n */\nconst SEND_TIMEOUT_MS = 15_000;\n\n/**\n * Cap on concurrently in-flight sends. Under ingest slowness (anything\n * short of a clean 429) the SDK sheds new sends past this ceiling instead\n * of accumulating fetches without bound inside the host.\n */\nconst MAX_INFLIGHT = 64;\n\n/**\n * Client-side turn-payload cap, mirroring the server's 1MB body limit: a\n * doomed oversized send is dropped LOUDLY here instead of serialized,\n * shipped, and rejected silently there (audit R2).\n */\nconst MAX_TURN_BODY_BYTES = 900_000;\n\nexport class IngestClient {\n private apiKey: string;\n private endpoint: string;\n private debug: boolean;\n private dashboardUrl: string;\n /**\n * First-trace permalink: the first\n * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,\n * then never again for the life of this client (one IngestClient per\n * process — one `init` per process; a restart prints once more, accepted).\n * Failed sends do not consume the announcement. Only sendTurn announces:\n * flags, outcome events, and session-end sends never trigger it (a flag\n * arriving before any turn is not a captured session).\n */\n private firstCaptureAnnounced = false;\n /**\n * Rate-limit (429) handling: the first 429 per process prints one stderr\n * warning (not debug-gated, same channel and lifetime as the first-capture\n * announce); subsequent 429s only debug-log. Each rate-limited request is\n * retried exactly once after Retry-After; pendingRetries counts retries\n * waiting on their timers so the cap can shed load.\n */\n private rateLimitAnnounced = false;\n private pendingRetries = 0;\n private inFlight = 0;\n private shedAnnounced = false;\n\n /**\n * Every network send goes through here: adds the per-send timeout and\n * the in-flight cap (audit B1). At the cap, the send is SHED — thrown\n * into the caller's existing fire-and-log catch — rather than queued;\n * the first shed per process warns on stderr, the rest debug-log.\n */\n private async guardedFetch(url: string, init: RequestInit): Promise<Response> {\n if (this.inFlight >= MAX_INFLIGHT) {\n if (!this.shedAnnounced) {\n this.shedAnnounced = true;\n // eslint-disable-next-line no-console\n console.error(\n `[sight] ${MAX_INFLIGHT} sends already in flight — shedding new sends (ingest slow or unreachable; this warning prints once)`,\n );\n }\n throw new Error('in-flight cap reached — send shed');\n }\n this.inFlight++;\n try {\n return await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });\n } finally {\n this.inFlight--;\n }\n }\n\n /**\n * Await all in-flight sends (bounded). Called by Probe.shutdown() so\n * short-lived processes (serverless, CLI scripts) can actually exit after\n * it — the documented \"in-flight sends finish within 15s\" only holds while\n * the process lives. Polling is coarse on purpose: sends report through\n * guardedFetch's counter, never awaited individually.\n */\n async drainInFlight(timeoutMs = SEND_TIMEOUT_MS): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (this.inFlight > 0 && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 50));\n }\n }\n\n constructor(opts: IngestClientOptions) {\n this.apiKey = opts.apiKey;\n this.endpoint = opts.endpoint.replace(/\\/$/, '');\n this.debug = opts.debug;\n this.dashboardUrl = (opts.dashboardUrl ?? DEFAULT_DASHBOARD_URL).replace(/\\/$/, '');\n }\n\n /**\n * Send a turn to the ingest API. Fire-and-log: errors are logged but never\n * thrown. The customer's LLM path never blocks on the Probe.\n */\n async sendTurn(turn: CapturedTurn): Promise<void> {\n try {\n const body = JSON.stringify(turn);\n if (body.length > MAX_TURN_BODY_BYTES) {\n // Loud drop beats a doomed 1MB+ POST the server rejects anyway.\n this.log(\n `[sight] turn dropped: payload ${body.length} bytes exceeds the ${MAX_TURN_BODY_BYTES}-byte cap ` +\n `(session=${turn.sessionExternalId} turn=${turn.turnIndex}) — trim the payload you attach`,\n );\n return;\n }\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/turns`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body,\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n\n if (!response.ok) {\n this.log(`[sight] ingest failed status=${response.status}`);\n return;\n }\n\n // Announce the first successful capture exactly once per process.\n // Deliberately NOT gated on debug — this is the install-to-first-\n // value ritual, one line, permalink included. Stderr only, same\n // channel as log(). \"Captured\" means accepted at ingest (202,\n // pre-redaction); the permalink resolves by external id once the\n // worker projects the session (seconds later).\n if (!this.firstCaptureAnnounced) {\n this.firstCaptureAnnounced = true;\n // eslint-disable-next-line no-console\n console.error(\n `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`,\n );\n }\n\n if (this.debug) {\n const body = (await response.json()) as { status?: string; pendingId?: string };\n this.log(`[sight] ingest ok id=${body.pendingId ?? '?'}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.\n * Populates the `user_flagged_break` outcome column on the dashboard.\n */\n async sendFlag(deploymentSlug: string, flag: FlagPersonaBreakInput): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/flags`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: flag.sessionExternalId,\n flagType: 'persona_break',\n note: flag.note,\n turnIndex: flag.turnIndex,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n\n if (!response.ok) {\n this.log(`[sight] flag ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[sight] flag ingest ok session=${flag.sessionExternalId}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] flag ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a session-end event to the ingest API. Records why a session ended\n * on the sessions.probe_session_ended_reason column. Fire-and-log.\n */\n async sendSessionEnd(deploymentSlug: string, end: SessionEndInput): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/sessions/end`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: end.externalId,\n endedReason: end.endedReason,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[sight] session-end ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[sight] session-end ingest ok session=${end.externalId}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] session-end ingest error: ${msg}`);\n }\n }\n\n /**\n * Send an outcome event to the ingest API. Fire-and-log. Populates\n * the outcome-events store.\n */\n async sendOutcomeEvent(\n deploymentSlug: string,\n event: OutcomeEventEmit,\n ): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/outcome-events`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: event.sessionExternalId,\n kind: event.kind,\n detectedBy: 'sdk_custom',\n causingTurnIndex: event.causingTurnIndex,\n detail: event.detail,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[sight] outcome-event ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(\n `[sight] outcome-event ingest ok session=${event.sessionExternalId} kind=${event.kind}`,\n );\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] outcome-event ingest error: ${msg}`);\n }\n }\n\n /**\n * Send an environment-event batch to the ingest API. Fire-and-log, same as\n * sendTurn. The envelope is generalized: the worker attaches each event to\n * its session's record by time; meaning is per-deployment.\n */\n async sendEnvironmentEvents(batch: EnvironmentEventsBatch): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/environment-events`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(batch),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[sight] environment-events ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[sight] environment-events ingest ok events=${batch.events.length}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] environment-events ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a span batch to the ingest API. Fire-and-log, same as sendTurn.\n * Spans carry sub-turn structure (llm_call / tool_call / framework_step /\n * custom); the worker resolves each span's session/turn and wires in-batch\n * parent references.\n */\n async sendSpans(batch: SpansBatch): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/spans`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(batch),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[sight] spans ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[sight] spans ingest ok spans=${batch.spans.length}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] spans ingest error: ${msg}`);\n }\n }\n\n /**\n * Route a send response through the 429 retry policy. Non-429 responses\n * pass through untouched. A 429 is re-sent exactly once after Retry-After\n * seconds (default 1s when the header is missing or unparseable; clamped\n * to [1, 60]s); the retry's response is returned as-is, so a second 429 is\n * never retried again — callers log and drop it like any other failed\n * send. Returns null when the retry was dropped at the pending-retry cap.\n * The timer is unref'd (where supported) so a pending retry never holds\n * the process open.\n */\n private async retryIfRateLimited(\n response: Response,\n resend: () => Promise<Response>,\n ): Promise<Response | null> {\n if (response.status !== 429) return response;\n\n if (!this.rateLimitAnnounced) {\n this.rateLimitAnnounced = true;\n // Deliberately NOT gated on debug — sustained rate limiting is silent\n // data loss; the operator hears about it exactly once per process.\n // Stderr only, same channel as log().\n // eslint-disable-next-line no-console\n console.error(\n 'Sight: ingest rate limit (429) — retrying once per Retry-After; sustained limiting drops captures. See https://sight.cultured.computer/docs/sdk-reference#rate-limits',\n );\n } else {\n this.log('[sight] ingest rate limited (429), retrying once');\n }\n\n if (this.pendingRetries >= MAX_PENDING_RETRIES) {\n this.log('[sight] retry buffer full, dropped');\n return null;\n }\n\n const raw = response.headers.get('retry-after');\n const parsed = raw === null ? Number.NaN : Number(raw);\n const seconds = Number.isFinite(parsed) ? Math.min(Math.max(parsed, 1), 60) : 1;\n\n this.pendingRetries += 1;\n try {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, seconds * 1000);\n // unref is absent outside Node (browsers, some edge runtimes) —\n // skip silently there.\n timer.unref?.();\n });\n return await resend();\n } finally {\n this.pendingRetries -= 1;\n }\n }\n\n private log(msg: string): void {\n if (this.debug) {\n // stderr only; never leak to stdout\n // eslint-disable-next-line no-console\n console.error(msg);\n }\n }\n}\n","/**\n * Sight SDK (@cultured-computer/sight) shared types.\n */\n\nimport { z } from 'zod';\nimport type { PropensityInput } from '@fieldwork/shared';\n\n// ── Configuration ──────────────────────────────────────────────────────────\n\n/**\n * Signature phrases the customer authors per persona for Day-1 voice\n * consistency measurement. The SDK edge computes matches\n * per turn (via @fieldwork/classifier signature-phrase) and includes the\n * matched slugs on the outgoing CapturedTurn.\n */\nexport const SignaturePhraseSchema = z.union([\n z.object({\n slug: z.string().min(1),\n phrase: z.string().min(1),\n description: z.string().optional(),\n }),\n z.object({\n slug: z.string().min(1),\n regex: z.string().min(1),\n flags: z.string().optional(),\n description: z.string().optional(),\n }),\n]);\nexport type SignaturePhraseInput = z.infer<typeof SignaturePhraseSchema>;\n\nexport const PersonaConfigSchema = z.object({\n /** Persona slug matching the deployment's registered persona. */\n slug: z.string().min(1),\n /**\n * RICE authorship artifact (Role, Identity, Communication, Engagement).\n * Either inline object or a path/URL to a JSON file loaded at init time.\n */\n rice: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),\n /**\n * Customer-authored signature phrases for this persona. Compiled once at\n * init and matched per turn at the SDK edge; matched slugs appear on the\n * outgoing turn as `signaturePhraseMatches`.\n */\n signaturePhrases: z.array(SignaturePhraseSchema).optional(),\n});\nexport type PersonaConfig = z.infer<typeof PersonaConfigSchema>;\n\nexport const OutcomeHookSchema = z.object({\n /** Type of outcome the deployment tracks. */\n type: z.enum(['numeric', 'categorical', 'boolean', 'duration']),\n /**\n * Callback that resolves the outcome for a completed session. Invoked by\n * Probe.endSession() with the session's externalId; a non-null result\n * lands as an outcome event on the session. Not invoked for sessions\n * swept server-side (no explicit endSession) — use emitOutcomeEvent()\n * for outcomes that become known out of band.\n */\n resolve: z.custom<(sessionId: string) => Promise<OutcomeResult | null>>(),\n});\nexport type OutcomeHook = z.infer<typeof OutcomeHookSchema>;\n\nexport type OutcomeResult = {\n outcome: string;\n type: 'numeric' | 'categorical' | 'boolean' | 'duration';\n value: string;\n};\n\nexport const ProbeConfigSchema = z.object({\n /** Unkey ingest key. Required. */\n apiKey: z.string().min(1),\n /** Deployment slug registered in the Probe backend. Required. */\n deployment: z.string().min(1),\n /** Ingest endpoint. Defaults to the production ingest service. */\n endpoint: z.string().url().default('https://fieldwork-ingest.fly.dev'),\n /**\n * Dashboard base URL used by the one-time first-capture announcement\n * (the stderr permalink printed after the first successful send).\n * Self-hosted or staging dashboards override it the same way `endpoint`\n * is overridden.\n */\n dashboardUrl: z.string().url().default('https://sight.cultured.computer/dashboard'),\n /** Persona identification. Optional at init; can be set later via identifyPersona(). */\n persona: PersonaConfigSchema.optional(),\n /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */\n outcomeHook: OutcomeHookSchema.optional(),\n /**\n * Sample rate for autocapture. 1.0 = 100% of calls captured. Lower values\n * sample deterministically so a given (turnId) always resolves identically.\n */\n sampleRate: z.number().min(0).max(1).default(1.0),\n /**\n * Debug mode: log every captured turn to stderr with a prefix. Never logs\n * the Bearer token or PII.\n */\n debug: z.boolean().default(false),\n});\nexport type ProbeConfig = z.infer<typeof ProbeConfigSchema>;\n/**\n * The shape callers pass to Probe.init(). This is the schema's INPUT type, so\n * fields with a `.default()` (endpoint, sampleRate, debug) are optional here —\n * the defaults are applied by ProbeConfigSchema.parse() inside init(). Use this\n * for the init argument; `ProbeConfig` is the resolved (post-parse) type held\n * internally, where those fields are always present.\n */\nexport type ProbeConfigInput = z.input<typeof ProbeConfigSchema>;\n\n// ── Session context (customer identifies persona per session) ──────────────\n\nexport const SessionStartSchema = z.object({\n /** Customer's session identity (opaque string; used as the correlation key). */\n externalId: z.string().min(1),\n /**\n * Customer's USER identity (opaque string), distinct from externalId:\n * externalId keys the session; externalUserId ties sessions to a\n * returning user. Forwarded on every captured turn so the worker can\n * persist it on the session row — return-with-persona-consistency and\n * prior-session metrics require it. Optional; deployments that do not\n * identify users simply skip the user-level return metrics.\n */\n externalUserId: z.string().min(1).optional(),\n /**\n * Persona slug active for this session. Overrides the init-level default.\n * Required for multi-persona deployments; optional for single-persona\n * deployments where init already carries the persona.\n */\n persona: z.string().min(1).optional(),\n /**\n * How the user got into this session.\n * Retention semantics differ radically between a resume and a fresh\n * notification landing.\n */\n openedVia: z.enum(['link', 'notification', 'resume', 'direct', 'share']).optional(),\n /**\n * Environmental context — browser / device / locale / tz (P2). Customer-\n * configurable which fields to include. See collectClientContext helper.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n /**\n * Optional customer metadata attached to the session. Forwarded with the\n * first captured turn merged into `clientContext` under the `metadata`\n * key, so it lands on sessions.probe_session_client_context.\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n /**\n * RLDS episode-level provenance. Powers the version behavioral diff\n * on the dashboard. All optional.\n * agentId — model/policy version\n * experimentId — A/B arm or feature flag\n * environmentConfigHash — SHA of prompt/config file(s)\n * environmentConfigLabel — human-readable version label\n */\n agentId: z.string().optional(),\n experimentId: z.string().optional(),\n environmentConfigHash: z.string().optional(),\n environmentConfigLabel: z.string().optional(),\n});\nexport type SessionStart = z.infer<typeof SessionStartSchema>;\n\n/**\n * Session end input (P2). Sent by Probe.endSession() so the worker records\n * why a session ended. `outcome` + `outcomeDetail` are the one-call\n * outcome helper: when the deployer knows the outcome at close (a\n * resolved ticket, an escalation, an abandonment), the SDK emits it as an\n * outcome event alongside the session end — it never rides the\n * session-end wire itself.\n */\nexport const SessionEndSchema = z.object({\n externalId: z.string().min(1),\n endedReason: z\n .enum(['natural', 'user_closed', 'timeout', 'agent_error', 'user_flagged', 'crashed'])\n .optional(),\n outcome: z.string().min(1).max(64).optional(),\n outcomeDetail: z.record(z.string(), z.unknown()).optional(),\n});\nexport type SessionEndInput = z.infer<typeof SessionEndSchema>;\n\n// ── Turn payload sent to ingest ────────────────────────────────────────────\n\nexport type CapturedTurn = {\n deploymentSlug: string;\n sessionExternalId: string;\n /**\n * Customer's user identity. Forwarded by captureTurn from the session\n * state (Probe.startSession({ externalUserId })); the worker persists it\n * on sessions.external_user_id at first-turn session create. Never\n * defaulted to sessionExternalId — that key identifies the session.\n */\n externalUserId?: string;\n turnIndex: number;\n /**\n * Persona slug active for this turn. Resolved by the SDK from (in order):\n * turn-level override, session-level from startSession(), init-level default.\n */\n personaSlug?: string;\n /**\n * Signature-phrase slugs matched at the SDK edge (computed from the\n * customer's signaturePhrases config at init). Empty array or omitted when\n * no signatures matched or none were registered.\n */\n signaturePhraseMatches?: string[];\n /**\n * Interpretive record fields passed through from a customer harness\n * (read hook wired). Populated only if the customer\n * runs the Cultured Computer harness pattern; null for non-harness deployments.\n */\n interpretive?: {\n situationType?: string[];\n read?: string;\n lensChosen?: string;\n reactionRegister?: string;\n reactionNextTurn?: string;\n };\n /**\n * User-side input for this turn. What the human\n * said + UI-level interactivity signals. Text is Presidio-scrubbed\n * server-side before landing on probe_user_reply_text.\n */\n userInput?: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount?: number;\n interruptedStream?: boolean;\n cancelledResponse?: boolean;\n submittedAt?: string;\n };\n /**\n * Interactivity: agent reflect time, stream completion, multimodal events.\n */\n interactivity?: {\n agentReflectMs?: number;\n agentStreamCompleted?: boolean;\n multimodalEvents?: Array<{ kind: string; at?: string; meta?: Record<string, unknown> }>;\n };\n /**\n * User outcome signals:\n * flagged break, explicit rating (1-5), thumbs.\n *\n * `flaggedBreak` is DEPRECATED in favor of Probe.flagPersonaBreak(),\n * which carries user attribution and emits a 'break' outcome event;\n * the turn-level boolean remains accepted for wire compat only.\n */\n userOutcome?: {\n flaggedBreak?: boolean;\n explicitRating?: number;\n thumbs?: 'up' | 'down';\n };\n /**\n * Propensity + candidate set (harness-supplied).\n * Manual-capture callers put this in payload.propensity; captureTurn\n * validates the contract and hoists the valid object to\n * this top-level field so the worker projection lands it on the\n * read_candidates / read_propensities / selection_meta columns.\n */\n propensity?: PropensityInput;\n /**\n * Transition signals (the human's response to the previous reply).\n * Derived by captureTurn when the previous turn's capture time and this\n * turn's user submit time are both known; may also be supplied directly\n * by manual-capture callers.\n */\n transition?: {\n timeMs?: number;\n lengthDelta?: number;\n };\n /**\n * Session context forwarded on the FIRST captured turn of a session\n * (populated by captureTurn from Probe.startSession state; the worker\n * persists both at session find-or-create). Omitted on later turns.\n */\n openedVia?: 'link' | 'notification' | 'resume' | 'direct' | 'share';\n clientContext?: Record<string, unknown>;\n /**\n * RLDS episode-level provenance. Forwarded from the session\n * state on every turn so downstream storage can attribute each turn to the\n * arm/version that produced it. Populated by startSession() from either\n * the customer-provided value or the init-time default; null when neither\n * is set.\n */\n agentId?: string;\n experimentId?: string;\n environmentConfigHash?: string;\n environmentConfigLabel?: string;\n payload: Record<string, unknown>;\n};\n\n// ── Persona-break flag (from Probe.flagPersonaBreak) ──────────────────────\n\nexport const FlagPersonaBreakSchema = z.object({\n sessionExternalId: z.string().min(1),\n note: z.string().optional(),\n /** Turn index the flag refers to. Omit to attach to the session's latest turn. */\n turnIndex: z.number().int().nonnegative().optional(),\n});\nexport type FlagPersonaBreakInput = z.infer<typeof FlagPersonaBreakSchema>;\n\n// ── Outcome event ────────────────────────────────────────────────────────\n// Customer-emitted event marking a hard outcome (break/escalation/\n// resolution/etc.) durable on the probe_outcome_events table. Universal\n// seed kinds ship out of the box; deployments may register their own\n// arbitrary string kind.\nexport const OutcomeEventEmitSchema = z.object({\n sessionExternalId: z.string().min(1),\n kind: z.string().min(1),\n /** Optional turn index this event is caused by. Omit to attach to latest turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Optional detail payload (customer-defined). */\n detail: z.record(z.string(), z.unknown()).optional(),\n});\nexport type OutcomeEventEmit = z.infer<typeof OutcomeEventEmitSchema>;\n","/**\n * Client-context capture helper (P2 per PLAN-2026-07-11).\n *\n * At session start the SDK optionally collects browser/device/locale/tz\n * metadata to send as SessionStart.clientContext. Customers control which\n * fields land via ProbeConfig.clientContextIncludes; the default is\n * conservative (locale + timezone + agent kind, no fingerprinting fields).\n *\n * Node-side calls receive process metadata; browser-side calls receive\n * navigator + Intl.DateTimeFormat. Never leaks PII; anything that could\n * fingerprint the user is opt-in.\n */\n\nexport type ClientContextIncludes = {\n /** window.navigator.userAgent — off by default (fingerprinting risk). */\n userAgent?: boolean;\n /** window.navigator.language / process.env.LANG — on by default. */\n locale?: boolean;\n /** Intl timezone / process TZ — on by default. */\n timezone?: boolean;\n /** window.screen dimensions — off by default (fingerprinting risk). */\n screen?: boolean;\n /** Node process metadata (platform, node version) — on by default in Node. */\n runtime?: boolean;\n /** Custom key/value pairs the customer wants to attach. */\n custom?: Record<string, string | number | boolean | null>;\n};\n\nconst DEFAULT_INCLUDES: ClientContextIncludes = {\n locale: true,\n timezone: true,\n runtime: true,\n};\n\n/** Collect client context under the current environment (Node or browser). */\nexport function collectClientContext(\n includes: ClientContextIncludes = DEFAULT_INCLUDES,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n\n // Browser detection without lib.dom.d.ts (SDK doesn't include DOM lib to\n // keep node-side bundles small). We accept the global as `unknown` and\n // narrow via runtime checks.\n const globalAny = globalThis as unknown as {\n window?: {\n navigator?: {\n userAgent?: string;\n language?: string;\n languages?: ReadonlyArray<string>;\n };\n screen?: { width?: number; height?: number };\n };\n };\n const win = globalAny.window;\n const isBrowser = typeof win !== 'undefined' && typeof win?.navigator !== 'undefined';\n\n if (isBrowser && win) {\n const nav = win.navigator;\n if (includes.userAgent) out['userAgent'] = nav?.userAgent;\n if (includes.locale) {\n out['locale'] = nav?.language;\n if (nav?.languages) out['languages'] = [...nav.languages];\n }\n if (includes.timezone) {\n try {\n out['timezone'] = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* ignore */\n }\n }\n if (includes.screen && win.screen) {\n out['screen'] = { width: win.screen.width, height: win.screen.height };\n }\n out['agent'] = 'browser';\n } else if (typeof process !== 'undefined' && typeof process.versions !== 'undefined') {\n if (includes.locale) {\n const lang = process.env['LANG'] || process.env['LC_ALL'] || null;\n if (lang) out['locale'] = lang.split('.')[0];\n }\n if (includes.timezone) {\n try {\n out['timezone'] = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* ignore */\n }\n }\n if (includes.runtime) {\n out['runtime'] = {\n platform: process.platform,\n node: process.versions.node,\n };\n }\n out['agent'] = 'node';\n }\n\n if (includes.custom) {\n for (const [k, v] of Object.entries(includes.custom)) out[k] = v;\n }\n\n return out;\n}\n","/**\n * Bounded insert for the tracked-sessions map (production-safety audit B2).\n *\n * endSession is optional, so on long-running high-cardinality servers the\n * sessions map would otherwise grow one entry per conversation forever. At\n * the cap the OLDEST entry (Map insertion order) is evicted — its later\n * turns still capture (lazy re-create), only edge-derived interactivity\n * context resets.\n *\n * Shared by probe.ts and instrumentation/otel-processor.ts so EVERY set\n * site on the sessions map goes through the same cap.\n */\n\nexport const MAX_TRACKED_SESSIONS = 5_000;\n\nexport function boundedSessionSet<T>(sessions: Map<string, T>, key: string, session: T): void {\n if (!sessions.has(key) && sessions.size >= MAX_TRACKED_SESSIONS) {\n const oldest = sessions.keys().next().value;\n if (oldest !== undefined) sessions.delete(oldest);\n }\n sessions.set(key, session);\n}\n","/**\n * Stable SHA-256 hex hashing for environment-config identity.\n *\n * Shared by the public Probe.hashEnvironmentConfig() helper and the OTel\n * processor's autocapture version-stamping (auto environmentConfigHash from\n * the request's system message). Lives in its own module so the processor\n * can import it without a circular dependency on probe.ts.\n *\n * Prefers WebCrypto (browser + modern Node); falls back to node:crypto via\n * dynamic import so the SDK stays browser-friendly for callers that never\n * touch this helper.\n */\nexport async function hashEnvironmentConfig(input: string): Promise<string> {\n if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle) {\n const bytes = new TextEncoder().encode(input);\n const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n }\n const { createHash } = await import('node:crypto');\n return createHash('sha256').update(input).digest('hex');\n}\n","/**\n * Session context propagation via OpenTelemetry Baggage.\n *\n * Adapters need to know which session an in-flight LLM call belongs to. We\n * propagate the session ID through OTel Baggage rather than a parallel\n * AsyncLocalStorage instance because:\n * 1. OTel already runs AsyncLocalStorageContextManager under the hood\n * (auto-registered by NodeTracerProvider on Node 20+); a parallel ALS\n * would duplicate the async-hooks graph.\n * 2. Baggage propagates automatically across HTTP boundaries via the\n * `baggage:` header. A parallel ALS would break at every service hop.\n *\n * Customer wraps their conversation:\n *\n * await Probe.withSession(sessionId, async () => {\n * await openai.chat.completions.create({ ... }); // captured\n * await anthropic.messages.create({ ... }); // also captured\n * });\n *\n * Under the hood: baggage entry `probe.session_id` is set, context is\n * activated for the callback, spans emitted inside read the baggage in\n * their onEnd handler.\n */\n\nimport { context, propagation } from '@opentelemetry/api';\n\nexport const SESSION_BAGGAGE_KEY = 'probe.session_id';\n\n// Register an AsyncLocalStorage-backed ContextManager idempotently on first\n// use. Without this, `context.with(...)` uses the default NoopContextManager\n// which does not propagate across async boundaries; baggage would be dropped\n// as soon as an `await` happened inside the callback.\nlet contextManagerRegistered = false;\nasync function ensureContextManager(): Promise<void> {\n if (contextManagerRegistered) return;\n contextManagerRegistered = true;\n try {\n const mod = await import('@opentelemetry/context-async-hooks');\n const cm = new mod.AsyncLocalStorageContextManager();\n cm.enable();\n context.setGlobalContextManager(cm);\n } catch {\n // The context-async-hooks package may not be installed; fall back to\n // NoopContextManager. Baggage will not propagate across async boundaries\n // in that case, which is a known limitation surfaced in debug mode by\n // the OTel processor.\n }\n}\n\n/**\n * Run `fn` inside a context where the given session ID is available to any\n * OTel span emitted (directly or transitively). Returns the fn's return value.\n */\nexport async function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n await ensureContextManager();\n const currentBaggage = propagation.getBaggage(context.active());\n const nextBaggage = (currentBaggage ?? propagation.createBaggage()).setEntry(\n SESSION_BAGGAGE_KEY,\n { value: sessionId },\n );\n const nextContext = propagation.setBaggage(context.active(), nextBaggage);\n return context.with(nextContext, fn);\n}\n\n/**\n * Read the current session ID from OTel Baggage, or undefined if no session\n * is active. Called by the OTel span processor when a captured span ends.\n */\nexport function getCurrentSessionId(): string | undefined {\n const baggage = propagation.getBaggage(context.active());\n return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;\n}\n","/**\n * Probe OTel SpanProcessor.\n *\n * Consumes spans emitted by every registered instrumentation (Traceloop's\n * OpenAI / Anthropic / LangChain adapters, Vercel AI SDK's native\n * experimental_telemetry, custom fetch wrappers for Mercury-2). Maps the\n * standard `gen_ai.*` semantic-convention attributes onto CapturedTurn\n * payload and calls Probe.captureTurn().\n *\n * Filter rule: only capture spans that are actual LLM invocations. Skip:\n * - Vercel AI SDK `invoke_agent` rollups (double-count vs child `chat`).\n * - LangChain `traceloop.span.kind === \"workflow\" | \"task\"` (chain\n * scaffolding, not LLM calls).\n * - Any span with no `gen_ai.operation.name` or `gen_ai.system` attribute.\n *\n * Deduplication: when both `@traceloop/instrumentation-langchain` and\n * `@traceloop/instrumentation-openai` fire for the same call, prefer the\n * LangChain span (kind=agent) over the raw OpenAI span, keyed by traceId.\n */\n\nimport type { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-node';\nimport type { Context } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\nimport type { CapturedTurn } from '../types.js';\nimport { getCurrentSessionId } from './session-context.js';\nimport { boundedSessionSet } from '../session-bounds.js';\nimport { hashEnvironmentConfig } from '../hash.js';\n\n// ── Deduplication cache (traceId → seen) ──────────────────────────────────\n// When LangChain instrumentation fires for a call, the underlying provider\n// (OpenAI/Anthropic) fires again on the same traceId. We take the first\n// span that arrives with a valid gen_ai.operation.name and skip the rest.\n// TTL is short (5s) because trace IDs recycle over a long-lived process.\nconst DEDUP_TTL_MS = 5_000;\nconst dedupCache = new Map<string, number>();\n\nfunction shouldSkipAsDuplicate(traceId: string): boolean {\n const now = Date.now();\n const seenAt = dedupCache.get(traceId);\n if (seenAt !== undefined && now - seenAt < DEDUP_TTL_MS) {\n return true;\n }\n dedupCache.set(traceId, now);\n // Sweep expired entries opportunistically (cheap, bounded work).\n if (dedupCache.size > 1000) {\n for (const [k, v] of dedupCache) {\n if (now - v > DEDUP_TTL_MS) dedupCache.delete(k);\n }\n }\n return false;\n}\n\n// ── Attribute helpers ─────────────────────────────────────────────────────\n\ntype AttrValue = string | number | boolean | Array<string | number | boolean> | undefined;\n\nfunction attr(attrs: Record<string, AttrValue>, key: string): AttrValue {\n return attrs[key];\n}\n\nfunction asString(v: AttrValue): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction asNumber(v: AttrValue): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\nfunction asStringArray(v: AttrValue): string[] | undefined {\n return Array.isArray(v) && v.every((x) => typeof x === 'string')\n ? (v as string[])\n : undefined;\n}\n\n// ── Filter: is this span an LLM call worth capturing? ────────────────────\n\nfunction isLLMCall(attrs: Record<string, AttrValue>): boolean {\n const op = asString(attrs['gen_ai.operation.name']);\n if (op === 'chat' || op === 'text_completion' || op === 'embeddings') {\n return true;\n }\n // LangChain via Traceloop emits spans with traceloop.span.kind. Only 'agent'\n // is an actual LLM call; 'workflow' / 'task' / 'tool' are scaffolding.\n const traceloopKind = asString(attrs['traceloop.span.kind']);\n if (traceloopKind === 'agent') return true;\n return false;\n}\n\n// ── Vercel AI SDK invoke_agent rollup detection ──────────────────────────\n\nfunction isVercelAgentRollup(\n spanName: string,\n attrs: Record<string, AttrValue>,\n): boolean {\n // Vercel AI SDK emits invoke_agent {modelId} spans that roll up token\n // usage across the child chat spans. Both spans have gen_ai.usage.*,\n // so we skip the rollup and keep the child chat span(s).\n return spanName.startsWith('invoke_agent ') && attrs['ai.telemetry.functionId'] !== undefined;\n}\n\n// ── Provider tagging (Mercury-2 via OpenAI-compat) ───────────────────────\n\nfunction taggedProvider(attrs: Record<string, AttrValue>): string | undefined {\n const rawProvider = asString(attrs['gen_ai.system'] ?? attrs['gen_ai.provider']);\n const model = asString(attrs['gen_ai.request.model']);\n // Mercury-2 goes through the OpenAI SDK with baseURL override; retag when\n // the model name signals Inception Labs.\n if (model?.toLowerCase().startsWith('mercury')) {\n return 'inception';\n }\n return rawProvider;\n}\n\n// ── Span → CapturedTurn.payload builder ──────────────────────────────────\n\nfunction buildPayload(span: ReadableSpan): Record<string, unknown> {\n const a = span.attributes as Record<string, AttrValue>;\n\n // Latency in ms from hrtime tuples.\n const start = span.startTime[0] * 1000 + span.startTime[1] / 1_000_000;\n const end = span.endTime[0] * 1000 + span.endTime[1] / 1_000_000;\n const latencyMs = Math.max(0, Math.round(end - start));\n\n // Response text: prefer ai.response.text (Vercel AI SDK) if present, then\n // fall back to gen_ai.output.messages (standard).\n const responseText =\n asString(attr(a, 'ai.response.text')) ?? asString(attr(a, 'gen_ai.output.messages'));\n\n // Tool calls: count and names.\n const toolCallNames = asStringArray(attr(a, 'gen_ai.response.tool_names'));\n const toolCallsCount =\n asNumber(attr(a, 'gen_ai.response.tool_calls_count')) ?? toolCallNames?.length;\n\n // Finish reason: gen_ai.response.finish_reasons is an array; take the first.\n const finishReasons = asStringArray(attr(a, 'gen_ai.response.finish_reasons'));\n const finishReason = finishReasons?.[0];\n\n // Error: OTel spans use span.status.code = ERROR when the call failed.\n // Message is in span.status.message.\n const error =\n span.status.code === 2 // SpanStatusCode.ERROR\n ? span.status.message ?? 'error'\n : undefined;\n\n return {\n // Plumbing (probe_* namespace lands on canonical turns columns per PROBE.md §2).\n probe_tokens_input: asNumber(attr(a, 'gen_ai.usage.input_tokens')),\n probe_tokens_output: asNumber(attr(a, 'gen_ai.usage.output_tokens')),\n probe_latency_ms: latencyMs,\n probe_model: asString(attr(a, 'gen_ai.response.model') ?? attr(a, 'gen_ai.request.model')),\n probe_provider: taggedProvider(a),\n probe_tool_calls: toolCallsCount,\n probe_tool_names: toolCallNames,\n probe_error: error,\n probe_finish_reason: finishReason,\n // Response text so the SDK edge signature-phrase matcher has something to\n // match against; the server-side redactor scrubs PII on the Tier 1 →\n // Tier 2 boundary.\n response: responseText ? { text: responseText } : undefined,\n // Anthropic cache tokens (per research report), promoted so the customer\n // can see cache-hit-rate in the dashboard without re-parsing raw messages.\n probe_cache_read_input_tokens: asNumber(attr(a, 'gen_ai.usage.cache_read_input_tokens')),\n probe_cache_creation_input_tokens: asNumber(\n attr(a, 'gen_ai.usage.cache_creation_input_tokens'),\n ),\n // Debug metadata (kept in payload, not projected to canonical columns).\n _otel: {\n spanName: span.name,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n operationName: asString(attr(a, 'gen_ai.operation.name')),\n traceloopKind: asString(attr(a, 'traceloop.span.kind')),\n },\n };\n}\n\n// ── System-prompt extraction (auto version-hash, 2026-07-14) ─────────────\n// Autocapture sees the request messages on the span. When a system message\n// is present and the deployer never set an environmentConfigHash on the\n// session, the session state is stamped with the SHA-256 of the system\n// prompt text plus an 'auto:xxxxxxxx' label — closing the version-diff\n// measurement with zero deployer work. Explicit startSession values always\n// win; nothing is logged or announced.\n\ntype MinimalSession = {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n};\n\n/** Join the text content of one message shape into a single string. */\nfunction messageText(content: unknown): string | undefined {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n const parts: string[] = [];\n for (const part of content) {\n if (typeof part === 'string') {\n parts.push(part);\n } else if (part && typeof part === 'object') {\n const p = part as Record<string, unknown>;\n // OTel gen_ai parts use {type:'text', content}; Vercel AI SDK and\n // provider SDKs use {type:'text', text}.\n const text = p['content'] ?? p['text'];\n if (typeof text === 'string') parts.push(text);\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n return undefined;\n}\n\n/** First system-role message text from a JSON-encoded message array. */\nfunction systemFromMessagesJson(raw: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return undefined;\n for (const msg of parsed) {\n if (msg && typeof msg === 'object') {\n const m = msg as Record<string, unknown>;\n if (m['role'] === 'system') {\n const text = messageText(m['content'] ?? m['parts']);\n if (text) return text;\n }\n }\n }\n } catch {\n // Not JSON — nothing to extract.\n }\n return undefined;\n}\n\n/**\n * Best-effort extraction of the request's system message text from span\n * attributes, across the conventions the registered instrumentations emit:\n * - `gen_ai.system_instructions` (OTel gen_ai semconv; string or JSON parts)\n * - `gen_ai.input.messages` (OTel gen_ai semconv; JSON message array)\n * - `gen_ai.prompt.{n}.role` / `.content` (Traceloop indexed convention)\n * - `ai.prompt.messages` / `ai.prompt` (Vercel AI SDK telemetry)\n * Returns undefined when no system message is present.\n */\nfunction extractSystemPromptText(attrs: Record<string, AttrValue>): string | undefined {\n // OTel semconv: dedicated system-instructions attribute.\n const instructions = attrs['gen_ai.system_instructions'];\n if (typeof instructions === 'string' && instructions.length > 0) {\n // May be plain text or a JSON parts array.\n try {\n const parsed: unknown = JSON.parse(instructions);\n const text = messageText(parsed);\n if (text) return text;\n } catch {\n return instructions;\n }\n return instructions;\n }\n\n // OTel semconv: full input message array as JSON.\n const inputMessages = asString(attrs['gen_ai.input.messages']);\n if (inputMessages) {\n const text = systemFromMessagesJson(inputMessages);\n if (text) return text;\n }\n\n // Traceloop: indexed prompt attributes (gen_ai.prompt.0.role, .content).\n for (let i = 0; ; i++) {\n const role = attrs[`gen_ai.prompt.${i}.role`];\n if (role === undefined) break;\n if (role === 'system') {\n const content = asString(attrs[`gen_ai.prompt.${i}.content`]);\n if (content) return content;\n }\n }\n\n // Vercel AI SDK: ai.prompt.messages (JSON CoreMessage array).\n const aiMessages = asString(attrs['ai.prompt.messages']);\n if (aiMessages) {\n const text = systemFromMessagesJson(aiMessages);\n if (text) return text;\n }\n\n // Vercel AI SDK: ai.prompt ({system, prompt/messages} as JSON).\n const aiPrompt = asString(attrs['ai.prompt']);\n if (aiPrompt) {\n try {\n const parsed: unknown = JSON.parse(aiPrompt);\n if (parsed && typeof parsed === 'object') {\n const system = (parsed as Record<string, unknown>)['system'];\n if (typeof system === 'string' && system.length > 0) return system;\n }\n } catch {\n // Not JSON — nothing to extract.\n }\n }\n\n return undefined;\n}\n\n/**\n * Stamp the session with the system prompt's hash when the deployer set no\n * environmentConfigHash. Awaited by onEnd BEFORE the capture is sent, so\n * captureTurn forwards the stamped values on this same turn. Re-checks\n * after the async hash so a concurrent explicit startSession always wins.\n */\nasync function maybeAutoStampEnvironmentConfig(\n session: MinimalSession,\n attrs: Record<string, AttrValue>,\n): Promise<void> {\n await autoStampFromSystemText(session, extractSystemPromptText(attrs));\n}\n\n/**\n * The guarded stamp itself, shared with the instance-wrapping adapter\n * (wrap-openai.ts), which extracts system text from request params rather\n * than span attributes but must stamp under the exact same rules.\n */\nexport async function autoStampFromSystemText(\n session: MinimalSession,\n systemText: string | undefined,\n): Promise<void> {\n if (session.environmentConfigHash != null) return; // explicit or already stamped\n if (!systemText) return;\n const hash = await hashEnvironmentConfig(systemText);\n if (session.environmentConfigHash != null) return; // raced with startSession\n session.environmentConfigHash = hash;\n session.environmentConfigLabel = `auto:${hash.slice(0, 8)}`;\n}\n\n// ── Turn index allocation ─────────────────────────────────────────────────\n// Sessions live in Probe singleton state as Map<externalId, SessionState>.\n// Each captured turn increments SessionState.turnIndex atomically (Node is\n// single-threaded so ++ is atomic).\n\ntype MinimalProbeState = {\n config: { deployment: string; debug: boolean };\n persona: { slug: string } | null;\n sessions: Map<string, MinimalSession>;\n signatureMatchers: Map<string, unknown>;\n};\n\n/** Shared with wrap-openai.ts so both capture paths bind the same state shape. */\nexport type ProcessorProbeState = MinimalProbeState;\n\nexport function resolveSessionAndTurn(\n state: MinimalProbeState,\n sessionId: string,\n): { session: MinimalSession; sessionExternalId: string; turnIndex: number; personaSlug: string | null } {\n let session = state.sessions.get(sessionId);\n if (!session) {\n session = {\n externalId: sessionId,\n turnIndex: 0,\n startedAt: Date.now(),\n personaSlug: state.persona?.slug ?? null,\n environmentConfigHash: null,\n environmentConfigLabel: null,\n };\n // Bounded insert (audit B2): the lazy-create path shares the same cap\n // as probe.ts — autocapture without endSession must not grow the map\n // one entry per conversation forever.\n boundedSessionSet(state.sessions, sessionId, session);\n }\n const turnIndex = session.turnIndex;\n session.turnIndex += 1;\n return {\n session,\n sessionExternalId: sessionId,\n turnIndex,\n personaSlug: session.personaSlug ?? state.persona?.slug ?? null,\n };\n}\n\n// ── The processor ─────────────────────────────────────────────────────────\n\nexport class ProbeSpanProcessor implements SpanProcessor {\n constructor(\n private state: MinimalProbeState | null,\n private captureFn: (turn: CapturedTurn) => Promise<void>,\n ) {}\n\n /**\n * Re-point the processor at a new Probe state (or null after shutdown).\n * A registered span processor cannot be removed from a provider, so\n * re-init REBINDS instead of orphaning: without this, autocapture after\n * shutdown()/re-init kept mutating the dead state's sessions map and\n * stamping the old deployment slug (production-safety audit R1).\n */\n rebind(state: MinimalProbeState | null, captureFn?: (turn: CapturedTurn) => Promise<void>): void {\n this.state = state;\n if (captureFn) this.captureFn = captureFn;\n }\n\n onStart(_span: Span, _parentContext: Context): void {\n // No-op. All work happens in onEnd once all attributes are populated.\n }\n\n onEnd(span: ReadableSpan): void {\n try {\n // Detached (post-shutdown, pre-re-init): drop silently — the host's\n // spans flow on; Sight is simply not listening.\n if (this.state === null) return;\n // Local binding: the state at span-end time. The async capture below\n // must use THIS state even if a rebind happens mid-flight.\n const state = this.state;\n const a = span.attributes as Record<string, AttrValue>;\n if (isVercelAgentRollup(span.name, a)) return;\n if (!isLLMCall(a)) return;\n\n const traceId = span.spanContext().traceId;\n if (shouldSkipAsDuplicate(traceId)) return;\n\n const sessionId = getCurrentSessionId();\n if (!sessionId) {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`,\n );\n }\n return;\n }\n\n const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(\n state,\n sessionId,\n );\n\n const captured: CapturedTurn = {\n deploymentSlug: state.config.deployment,\n sessionExternalId,\n turnIndex,\n personaSlug: personaSlug ?? undefined,\n payload: buildPayload(span),\n };\n\n // Fire-and-log; SDK client swallows send errors. The auto version\n // stamp is awaited BEFORE the capture so the session-held\n // environmentConfigHash rides this same turn.\n (async () => {\n await maybeAutoStampEnvironmentConfig(session, a);\n await this.captureFn(captured);\n })().catch((err) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`,\n );\n }\n });\n } catch (err) {\n if (this.state?.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n shutdown(): Promise<void> {\n dedupCache.clear();\n return Promise.resolve();\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n// ── Exported helpers for tests ────────────────────────────────────────────\nexport const _internals = {\n isLLMCall,\n isVercelAgentRollup,\n taggedProvider,\n buildPayload,\n shouldSkipAsDuplicate,\n dedupCache,\n extractSystemPromptText,\n maybeAutoStampEnvironmentConfig,\n};\n","/**\n * Explicit OpenAI client wrapping — the autocapture path that cannot miss.\n *\n * Module patching (registerOpenAI → @traceloop/instrumentation-openai) only\n * attaches under CommonJS, only when `openai` is loaded after Probe.init(),\n * and only for openai <5 (the instrumentation's declared supportedVersions).\n * A modern ESM app on openai v5+ therefore captures nothing through the\n * patch path, and did so silently until registerOpenAI grew its post-enable\n * verification. wrapOpenAI() is the documented default instead: it wraps\n * the client INSTANCE the customer already holds, which is immune to module\n * format, load order, and library version.\n *\n * import OpenAI from 'openai';\n * import { Probe, wrapOpenAI } from '@cultured_computer/sight';\n * const openai = wrapOpenAI(new OpenAI());\n *\n * Covers chat.completions.create and responses.create, streaming included:\n * the stream is teed, chunks reach the caller unchanged, and the turn is\n * emitted when the stream completes. Turns flow through the same session\n * resolution and captureTurn path as the OTel processor, so payload keys\n * are identical downstream.\n *\n * Binding: registerAllInstrumentations() binds this module to live Probe\n * state at init. wrapOpenAI() may be called before init — the wrap is\n * inert (pure passthrough) until the binding lands, and warns once if a\n * call happens while unbound so a missing init is never silent.\n */\n\nimport type { CapturedTurn } from '../types.js';\nimport { getCurrentSessionId } from './session-context.js';\nimport {\n resolveSessionAndTurn,\n autoStampFromSystemText,\n type ProcessorProbeState,\n} from './otel-processor.js';\n\ntype Bound = {\n state: ProcessorProbeState;\n captureFn: (turn: CapturedTurn) => Promise<void>;\n};\n\nlet bound: Bound | null = null;\nlet warnedUnbound = false;\n\nexport function bindWrapOpenAI(\n state: ProcessorProbeState,\n captureFn: (turn: CapturedTurn) => Promise<void>,\n): void {\n bound = { state, captureFn };\n}\n\n/** Probe.shutdown() detaches; a later init rebinds. */\nexport function unbindWrapOpenAI(): void {\n bound = null;\n}\n\nconst WRAPPED = Symbol.for('sight.wrapOpenAI');\n\n// ── Payload extraction ────────────────────────────────────────────────────\n\ntype AnyRecord = Record<string, unknown>;\n\nfunction asRecord(v: unknown): AnyRecord | undefined {\n return v !== null && typeof v === 'object' ? (v as AnyRecord) : undefined;\n}\n\nfunction asString(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction asNumber(v: unknown): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\n/** Join string-or-parts message content into one string (mirrors the processor). */\nfunction messageText(content: unknown): string | undefined {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n const parts: string[] = [];\n for (const part of content) {\n if (typeof part === 'string') parts.push(part);\n else {\n const p = asRecord(part);\n const text = p?.['text'] ?? p?.['content'];\n if (typeof text === 'string') parts.push(text);\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n return undefined;\n}\n\n/** System text from chat params (messages[]) or responses params (instructions). */\nfunction systemTextFromParams(params: AnyRecord | undefined): string | undefined {\n if (!params) return undefined;\n const instructions = asString(params['instructions']);\n if (instructions && instructions.length > 0) return instructions;\n const messages = params['messages'];\n if (Array.isArray(messages)) {\n for (const raw of messages) {\n const m = asRecord(raw);\n if (m && (m['role'] === 'system' || m['role'] === 'developer')) {\n const text = messageText(m['content']);\n if (text) return text;\n }\n }\n }\n return undefined;\n}\n\nfunction providerFor(model: string | undefined): string {\n return model?.toLowerCase().startsWith('mercury') ? 'inception' : 'openai';\n}\n\n/** chat.completions non-streaming response → payload fields. */\nfunction payloadFromChatResponse(r: AnyRecord, requestModel: string | undefined) {\n const choice = Array.isArray(r['choices']) ? asRecord(r['choices'][0]) : undefined;\n const message = asRecord(choice?.['message']);\n const usage = asRecord(r['usage']);\n const promptDetails = asRecord(usage?.['prompt_tokens_details']);\n const toolCalls = Array.isArray(message?.['tool_calls'])\n ? (message['tool_calls'] as unknown[])\n : undefined;\n const toolNames = toolCalls\n ?.map((t) => asString(asRecord(asRecord(t)?.['function'])?.['name']))\n .filter((n): n is string => typeof n === 'string');\n return {\n model: asString(r['model']) ?? requestModel,\n text: messageText(message?.['content']),\n tokensInput: asNumber(usage?.['prompt_tokens']),\n tokensOutput: asNumber(usage?.['completion_tokens']),\n cachedTokens: asNumber(promptDetails?.['cached_tokens']),\n finishReason: asString(choice?.['finish_reason']),\n toolNames,\n };\n}\n\n/** responses API non-streaming response → payload fields. */\nfunction payloadFromResponsesResponse(r: AnyRecord, requestModel: string | undefined) {\n const usage = asRecord(r['usage']);\n const inputDetails = asRecord(usage?.['input_tokens_details']);\n let text = asString(r['output_text']);\n const toolNames: string[] = [];\n if (Array.isArray(r['output'])) {\n const texts: string[] = [];\n for (const raw of r['output'] as unknown[]) {\n const item = asRecord(raw);\n if (!item) continue;\n if (item['type'] === 'function_call') {\n const name = asString(item['name']);\n if (name) toolNames.push(name);\n }\n if (item['type'] === 'message' && Array.isArray(item['content'])) {\n for (const c of item['content'] as unknown[]) {\n const cr = asRecord(c);\n if (cr?.['type'] === 'output_text') {\n const t = asString(cr['text']);\n if (t) texts.push(t);\n }\n }\n }\n }\n if (!text && texts.length > 0) text = texts.join('\\n');\n }\n return {\n model: asString(r['model']) ?? requestModel,\n text,\n tokensInput: asNumber(usage?.['input_tokens']),\n tokensOutput: asNumber(usage?.['output_tokens']),\n cachedTokens: asNumber(inputDetails?.['cached_tokens']),\n finishReason: asString(r['status']),\n toolNames: toolNames.length > 0 ? toolNames : undefined,\n };\n}\n\ntype Extracted = ReturnType<typeof payloadFromChatResponse>;\n\nfunction buildTurnPayload(x: Extracted, latencyMs: number, api: 'chat' | 'responses') {\n return {\n probe_tokens_input: x.tokensInput,\n probe_tokens_output: x.tokensOutput,\n probe_latency_ms: latencyMs,\n probe_model: x.model,\n probe_provider: providerFor(x.model),\n probe_tool_calls: x.toolNames?.length,\n probe_tool_names: x.toolNames,\n probe_error: undefined as string | undefined,\n probe_finish_reason: x.finishReason,\n response: x.text ? { text: x.text } : undefined,\n probe_cache_read_input_tokens: x.cachedTokens,\n _wrap: { api, adapter: 'wrapOpenAI' },\n };\n}\n\n// ── Emission ──────────────────────────────────────────────────────────────\n\nfunction emit(params: AnyRecord | undefined, payload: Record<string, unknown>): void {\n if (!bound) {\n if (!warnedUnbound) {\n warnedUnbound = true;\n // eslint-disable-next-line no-console\n console.warn(\n '[sight] wrapOpenAI: call observed before Probe.init(); nothing captured until init runs.',\n );\n }\n return;\n }\n const { state, captureFn } = bound;\n const sessionId = getCurrentSessionId();\n if (!sessionId) {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.warn(\n '[sight] wrapOpenAI: call with no session context; skipped (wrap calls in Probe.withSession()).',\n );\n }\n return;\n }\n const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(\n state,\n sessionId,\n );\n const captured: CapturedTurn = {\n deploymentSlug: state.config.deployment,\n sessionExternalId,\n turnIndex,\n personaSlug: personaSlug ?? undefined,\n payload,\n };\n void (async () => {\n await autoStampFromSystemText(session, systemTextFromParams(params));\n await captureFn(captured);\n })().catch((err) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(`[sight] wrapOpenAI capture error: ${err instanceof Error ? err.message : err}`);\n }\n });\n}\n\n// ── Streaming tee ─────────────────────────────────────────────────────────\n\n/**\n * Proxy the stream object so every property and method passes through\n * untouched, but iteration is observed: chunks are forwarded to the caller\n * unchanged while an accumulator builds the turn, emitted at stream end.\n */\nfunction teeStream<T extends object>(\n stream: T,\n onChunk: (chunk: unknown) => void,\n onDone: () => void,\n): T {\n let done = false;\n const finish = () => {\n if (!done) {\n done = true;\n onDone();\n }\n };\n return new Proxy(stream, {\n get(target, prop, receiver) {\n if (prop === Symbol.asyncIterator) {\n return function () {\n const inner = (target as AsyncIterable<unknown>)[Symbol.asyncIterator]();\n return {\n async next(): Promise<IteratorResult<unknown>> {\n try {\n const r = await inner.next();\n if (r.done) finish();\n else onChunk(r.value);\n return r;\n } catch (err) {\n finish();\n throw err;\n }\n },\n async return(value?: unknown): Promise<IteratorResult<unknown>> {\n finish();\n return inner.return ? inner.return(value) : { done: true, value };\n },\n async throw(err?: unknown): Promise<IteratorResult<unknown>> {\n finish();\n if (inner.throw) return inner.throw(err);\n throw err;\n },\n };\n };\n }\n const value = Reflect.get(target, prop, receiver);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\ntype StreamAccumulator = {\n onChunk: (chunk: unknown) => void;\n result: () => Extracted;\n};\n\nfunction chatStreamAccumulator(requestModel: string | undefined): StreamAccumulator {\n const texts: string[] = [];\n let model = requestModel;\n let finishReason: string | undefined;\n let tokensInput: number | undefined;\n let tokensOutput: number | undefined;\n let cachedTokens: number | undefined;\n return {\n onChunk(chunk) {\n const c = asRecord(chunk);\n if (!c) return;\n model = asString(c['model']) ?? model;\n const choice = Array.isArray(c['choices']) ? asRecord(c['choices'][0]) : undefined;\n const delta = asRecord(choice?.['delta']);\n const t = asString(delta?.['content']);\n if (t) texts.push(t);\n finishReason = asString(choice?.['finish_reason']) ?? finishReason;\n const usage = asRecord(c['usage']);\n if (usage) {\n tokensInput = asNumber(usage['prompt_tokens']) ?? tokensInput;\n tokensOutput = asNumber(usage['completion_tokens']) ?? tokensOutput;\n cachedTokens =\n asNumber(asRecord(usage['prompt_tokens_details'])?.['cached_tokens']) ?? cachedTokens;\n }\n },\n result: () => ({\n model,\n text: texts.length > 0 ? texts.join('') : undefined,\n tokensInput,\n tokensOutput,\n cachedTokens,\n finishReason,\n toolNames: undefined,\n }),\n };\n}\n\nfunction responsesStreamAccumulator(requestModel: string | undefined): StreamAccumulator {\n const texts: string[] = [];\n let final: Extracted | null = null;\n return {\n onChunk(chunk) {\n const c = asRecord(chunk);\n if (!c) return;\n if (c['type'] === 'response.output_text.delta') {\n const t = asString(c['delta']);\n if (t) texts.push(t);\n }\n if (c['type'] === 'response.completed') {\n const response = asRecord(c['response']);\n if (response) final = payloadFromResponsesResponse(response, requestModel);\n }\n },\n result: () => {\n if (final) {\n return { ...final, text: final.text ?? (texts.length > 0 ? texts.join('') : undefined) };\n }\n return {\n model: requestModel,\n text: texts.length > 0 ? texts.join('') : undefined,\n tokensInput: undefined,\n tokensOutput: undefined,\n cachedTokens: undefined,\n finishReason: undefined,\n toolNames: undefined,\n };\n },\n };\n}\n\n// ── The wrap ──────────────────────────────────────────────────────────────\n\ntype CreateFn = (...args: unknown[]) => Promise<unknown>;\n\nfunction wrapCreate(\n target: AnyRecord,\n api: 'chat' | 'responses',\n makeAccumulator: (model: string | undefined) => StreamAccumulator,\n extractResponse: (r: AnyRecord, model: string | undefined) => Extracted,\n): void {\n const original = target['create'];\n if (typeof original !== 'function') return;\n target['create'] = function (this: unknown, ...args: unknown[]) {\n const params = asRecord(args[0]);\n const requestModel = asString(params?.['model']);\n const startedAt = Date.now();\n const result = (original as CreateFn).apply(this, args);\n // Non-promise (unexpected shape): pass through untouched.\n if (!result || typeof (result as Promise<unknown>).then !== 'function') return result;\n return (result as Promise<unknown>).then(\n (resolved) => {\n try {\n const isStream =\n resolved !== null &&\n typeof resolved === 'object' &&\n Symbol.asyncIterator in (resolved as object);\n if (isStream) {\n const acc = makeAccumulator(requestModel);\n return teeStream(resolved as object, acc.onChunk, () => {\n emit(params, buildTurnPayload(acc.result(), Date.now() - startedAt, api));\n });\n }\n const r = asRecord(resolved);\n if (r) {\n emit(params, buildTurnPayload(extractResponse(r, requestModel), Date.now() - startedAt, api));\n }\n return resolved;\n } catch {\n // Capture must never damage the customer's call path.\n return resolved;\n }\n },\n (err: unknown) => {\n // Failed call: record the error turn, then rethrow untouched.\n try {\n const x: Extracted = {\n model: requestModel,\n text: undefined,\n tokensInput: undefined,\n tokensOutput: undefined,\n cachedTokens: undefined,\n finishReason: undefined,\n toolNames: undefined,\n };\n const payload = buildTurnPayload(x, Date.now() - startedAt, api);\n payload.probe_error = err instanceof Error ? err.message : String(err);\n emit(params, payload);\n } catch {\n // ignore\n }\n throw err;\n },\n );\n };\n}\n\n/**\n * Wrap an OpenAI client instance so every chat.completions.create and\n * responses.create call is captured as a Sight turn. Returns the same\n * client. Idempotent; safe to call before Probe.init() (capture starts\n * once init binds).\n */\nexport function wrapOpenAI<T extends object>(client: T): T {\n const c = client as AnyRecord & { [WRAPPED]?: boolean };\n if (c[WRAPPED]) return client;\n c[WRAPPED] = true;\n\n const completions = asRecord(asRecord(c['chat'])?.['completions']);\n if (completions) {\n wrapCreate(completions, 'chat', chatStreamAccumulator, payloadFromChatResponse);\n }\n const responses = asRecord(c['responses']);\n if (responses) {\n wrapCreate(responses, 'responses', responsesStreamAccumulator, payloadFromResponsesResponse);\n }\n return client;\n}\n\n// ── Exported for tests ────────────────────────────────────────────────────\nexport const _wrapInternals = {\n payloadFromChatResponse,\n payloadFromResponsesResponse,\n systemTextFromParams,\n teeStream,\n isBound: () => bound !== null,\n};\n","/**\n * OTel provider setup.\n *\n * Registers a NodeTracerProvider with the ProbeSpanProcessor. Called once at\n * Probe.init() before any instrumentation is enabled.\n *\n * If the customer has already registered an OTel provider (e.g. Sentry, DD,\n * or their own), we do NOT overwrite it — instead we add our SpanProcessor\n * to the existing provider. This preserves customer observability.\n *\n * Trade-off: if the customer's provider does not expose addSpanProcessor\n * (older versions), we register our own NodeTracerProvider; OTel keeps the\n * first-registered global, so capture may not attach in that case. Chapter\n * 2 ships the pattern; hardening for edge cases lands with the first\n * enterprise customer.\n */\n\nimport { trace } from '@opentelemetry/api';\nimport { ProbeSpanProcessor } from './otel-processor.js';\nimport { unbindWrapOpenAI } from './wrap-openai.js';\nimport type { CapturedTurn } from '../types.js';\n\ntype MinimalProbeState = {\n config: { deployment: string; debug: boolean };\n persona: { slug: string } | null;\n sessions: Map<\n string,\n {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n // Auto version-hash stamping target (see otel-processor.ts).\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n }\n >;\n signatureMatchers: Map<string, unknown>;\n};\n\nlet installedProcessor: ProbeSpanProcessor | null = null;\n\nexport function setupOtelProvider(\n state: MinimalProbeState,\n captureFn: (turn: CapturedTurn) => Promise<void>,\n): void {\n if (installedProcessor !== null) {\n // Already set up: a registered span processor cannot be removed from\n // the provider, so re-init REBINDS the existing one to the new state\n // instead of leaving it pointed at a dead state object (audit R1).\n installedProcessor.rebind(state, captureFn);\n return;\n }\n installedProcessor = new ProbeSpanProcessor(state, captureFn);\n\n const currentProvider = trace.getTracerProvider() as {\n addSpanProcessor?: (p: ProbeSpanProcessor) => void;\n };\n\n // Case 1: customer has already registered a provider that supports addSpanProcessor.\n if (typeof currentProvider.addSpanProcessor === 'function') {\n currentProvider.addSpanProcessor(installedProcessor);\n return;\n }\n\n // Case 2: no provider registered yet (NoopTracerProvider). Create a new one.\n // We use dynamic import so the base @opentelemetry/sdk-trace-node cost\n // is only paid when Probe.init() is called (not on module load).\n void import('@opentelemetry/sdk-trace-node').then((mod) => {\n const provider = new mod.NodeTracerProvider({\n spanProcessors: [installedProcessor!],\n });\n provider.register();\n });\n}\n\nexport function teardownOtelProvider(): void {\n if (installedProcessor) {\n void installedProcessor.shutdown();\n installedProcessor = null;\n }\n}\n\n/**\n * Detach the installed processor from Probe state without tearing the\n * provider down (Probe.shutdown): post-shutdown LLM calls stop feeding the\n * orphaned state (audit R1 — the old behavior grew a dead sessions map\n * forever); a later re-init rebinds via setupOtelProvider.\n */\nexport function detachOtelState(): void {\n installedProcessor?.rebind(null);\n // The instance-wrapping path shares the same lifecycle: post-shutdown\n // LLM calls through a wrapped client must stop feeding the dead state.\n unbindWrapOpenAI();\n}\n","/**\n * OpenAI instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-openai. Its spans flow through the\n * globally-registered ProbeSpanProcessor (see ./setup.ts and ./otel-processor.ts).\n *\n * Config: traceContent + enrichTokens on (customer wanting no-content mode\n * can flip Probe.init({ debug: false, sampleRate: 0 }) or override via\n * environment variable OTEL_INSTRUMENTATION_OPENAI_TRACE_CONTENT=false).\n *\n * This adapter also handles Mercury-2 via OpenAI SDK baseURL override; the\n * ProbeSpanProcessor tags `provider=inception` when gen_ai.request.model\n * starts with 'mercury'. Customers using Inception need no separate adapter.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerOpenAI(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-openai');\n instrumentation = new mod.OpenAIInstrumentation({\n enrichTokens: true,\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n // The patch attaches only under CommonJS, only when `openai` loads\n // after init, and only for the instrumentation's declared version\n // range (<5 as of @traceloop/instrumentation-openai 0.14.x). Every\n // one of those failures is otherwise SILENT: requests succeed, zero\n // turns captured. Verify and warn loudly — this is the exact gap a\n // tester found on 0.5.1 (autocapture dead on both openai v4-ESM and\n // v5) that no unit test could see.\n void verifyPatchAttached();\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(`[probe/openai] instrumentation not enabled (${msg}); library not installed?`);\n }\n }\n}\n\n/**\n * True when the openai module's chat-completions create function shows no\n * shimmer wrap marker — meaning the traceloop patch did NOT attach and\n * autocapture through the patch path will record nothing. Pure and\n * exported for tests; tolerant of unknown module shapes (treated as\n * detached, which errs on the side of warning).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isPatchDetached(mod: any): boolean {\n const OpenAIClass = mod?.default ?? mod?.OpenAI;\n const create = OpenAIClass?.Chat?.Completions?.prototype?.create;\n if (typeof create !== 'function') return true;\n return (create as { __wrapped?: boolean }).__wrapped !== true;\n}\n\nasync function verifyPatchAttached(): Promise<void> {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const mod: any = await import('openai');\n if (!isPatchDetached(mod)) return;\n const version: string | undefined = mod?.default?.VERSION ?? mod?.VERSION;\n // NOT debug-gated on purpose: a dead capture path must never be silent.\n // eslint-disable-next-line no-console\n console.warn(\n `[sight] OpenAI autocapture via module patching did not attach` +\n (version ? ` (openai v${version})` : '') +\n `. This happens on openai >=5, under ESM, or when 'openai' loads before init. ` +\n `Wrap your client instead: import { wrapOpenAI } from '@cultured_computer/sight'; ` +\n `const client = wrapOpenAI(new OpenAI()). Until then, no turns are captured from this client.`,\n );\n } catch {\n // openai not installed in this process — nothing to verify.\n }\n}\n\nexport function unregisterOpenAI(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * Anthropic instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-anthropic. Cache-token attributes\n * (gen_ai.usage.cache_read_input_tokens, cache_creation_input_tokens) are\n * promoted onto the CapturedTurn payload by the shared processor.\n *\n * Anthropic finish reasons preserve their raw shape ('end_turn',\n * 'max_tokens', 'stop_sequence', 'tool_use') rather than being normalised to\n * OpenAI-style 'stop' / 'length'. Downstream analytics can pattern-match on\n * the raw value.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerAnthropic(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-anthropic');\n instrumentation = new mod.AnthropicInstrumentation({\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/anthropic] instrumentation not enabled (${msg}); library not installed?`,\n );\n }\n }\n}\n\nexport function unregisterAnthropic(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * LangChain instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-langchain. The shared ProbeSpanProcessor\n * filters LangChain spans by `traceloop.span.kind === \"agent\"` (actual LLM\n * calls; skips 'workflow' / 'task' chain scaffolding and 'tool' invocations).\n *\n * Double-instrumentation note: when a LangChain chain calls into OpenAI or\n * Anthropic, BOTH the langchain instrumentation and the provider\n * instrumentation fire on the same traceId. The ProbeSpanProcessor's dedup\n * cache (keyed on traceId with 5s TTL) drops the second one so we never\n * double-capture a turn.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerLangChain(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-langchain');\n instrumentation = new mod.LangChainInstrumentation({\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/langchain] instrumentation not enabled (${msg}); library not installed?`,\n );\n }\n }\n}\n\nexport function unregisterLangChain(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * LangGraph instrumentation adapter.\n *\n * LangGraph reuses LangChain callbacks, so @traceloop/instrumentation-langchain\n * already fires for LangGraph nodes. The catch: Traceloop tags them as generic\n * `traceloop.span.kind: \"task\"` without graph topology hints (node id, thread,\n * edges). Customers who want future Structure-axis flow-state metrics\n * (Chapter 5 research direction; nothing ships today) to work with LangGraph\n * need to pass the node/thread identity into their RunnableConfig.\n *\n * This adapter itself is a no-op registration: the actual span emission is\n * covered by ./langchain.ts (Traceloop's callback handler). The value we add\n * here is DOCUMENTATION of the tag pattern (below) plus a marker that\n * LangGraph coverage is active.\n *\n * Recommended customer pattern (documented in packages/sdk/README.md):\n *\n * await graph.invoke(state, {\n * configurable: { thread_id: sessionId },\n * tags: ['langgraph', 'node:planner', 'thread:' + sessionId],\n * });\n *\n * The `tags` array surfaces as span attribute `traceloop.association.properties.tags`\n * which lands on the CapturedTurn.payload._otel debug block. Chapter 5 flow-\n * state calibration can pattern-match on the 'node:*' prefix.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerLangGraph(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology',\n );\n }\n}\n\nexport function unregisterLangGraph(): void {\n registered = false;\n}\n","/**\n * Vercel AI SDK adapter.\n *\n * Vercel AI SDK emits OTel spans natively when `experimental_telemetry` is\n * enabled on the call. No library to install, no monkey-patching. The\n * ProbeSpanProcessor already listens to every span emitted through the\n * global TracerProvider, so this adapter just documents the customer\n * activation pattern.\n *\n * Customer wires per-call:\n *\n * import { generateText } from 'ai';\n * import { openai } from '@ai-sdk/openai';\n *\n * await Probe.withSession(sessionId, async () => {\n * const { text } = await generateText({\n * model: openai('gpt-5'),\n * prompt: 'Explain the plan',\n * experimental_telemetry: {\n * isEnabled: true,\n * functionId: 'plan-explanation',\n * recordInputs: true,\n * recordOutputs: true,\n * },\n * });\n * });\n *\n * The processor filters the noisy `invoke_agent {modelId}` rollup and\n * keeps only the child `chat {modelId}` spans (which are the actual LLM\n * calls). Sub-`execute_tool` spans attach to their parent chat span via\n * traceId; the dedup cache keeps us from double-capturing.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerVercelAI(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/vercel-ai] active; customer must set experimental_telemetry: { isEnabled: true } per call',\n );\n }\n}\n\nexport function unregisterVercelAI(): void {\n registered = false;\n}\n","/**\n * LiteLLM adapter (deferred to Chapter 4 URL-swap proxy).\n *\n * LiteLLM is Python. The Probe SDK is TypeScript. Bridging them by hosting an\n * OTLP collector in the SDK is 500+ lines of code that duplicates real OTel\n * collectors and makes the SDK stateful and network-listening. Not the right\n * shape for a research lab shipping a research instrument.\n *\n * The pragmatic 2026 path: LiteLLM customers configure `api_base` to the\n * Probe URL-swap proxy (Chapter 4). Same wire format, capture happens\n * server-side on the proxy, done. Customers who already run an OTLP\n * pipeline can point their exporter at the Probe collector as an add-on;\n * that lands with Chapter 6 self-host.\n *\n * This adapter registration is a no-op stub with a debug-mode warning so\n * customers who imported the SDK explicitly know why LiteLLM is not\n * captured on the SDK side. Chapter 4 documents the proxy configuration.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerLiteLLM(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/litellm] not captured on SDK side; use the Chapter 4 URL-swap proxy for LiteLLM traffic',\n );\n }\n}\n\nexport function unregisterLiteLLM(): void {\n registered = false;\n}\n","/**\n * Mercury-2 adapter (Inception Labs, diffusion-class API).\n *\n * 99% of customer traffic to Mercury-2 goes through the OpenAI SDK with\n * `baseURL: 'https://api.inceptionlabs.ai/v1'`, which means\n * @traceloop/instrumentation-openai already captures every call and the\n * ProbeSpanProcessor tags `provider=inception` when\n * `gen_ai.request.model` starts with 'mercury'. No dedicated adapter needed\n * for that path.\n *\n * Fallback: for customers using a hand-rolled fetch call to the Inception\n * endpoint (rare), this adapter installs a fetch wrapper that emits an OTel\n * span for the request so the shared processor picks it up. Registered only\n * when Probe.init() is called with { instrumentation: { mercuryFetchWrapper:\n * true } } (opt-in; the default OpenAI SDK path covers everything).\n *\n * We do NOT ship a bespoke Mercury client. The maintenance cost of a\n * provider-specific wrapper for a single provider is not worth it when the\n * OpenAI-SDK path covers 99% of usage.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\nlet originalFetch: typeof globalThis.fetch | null = null;\n\nconst INCEPTION_HOSTS = ['api.inceptionlabs.ai', 'api.inception.ai'];\n\nfunction isInceptionUrl(url: string): boolean {\n return INCEPTION_HOSTS.some((h) => url.includes(h));\n}\n\nexport async function registerMercury(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route',\n );\n }\n}\n\n/**\n * Optional fetch monkey-patch for hand-rolled fetch calls to Inception.\n * Called only if the customer opts in explicitly (rare).\n */\nexport function enableMercuryFetchWrapper(state: ProbeState): void {\n if (originalFetch) return;\n originalFetch = globalThis.fetch;\n\n globalThis.fetch = async (input: string | URL | Request, init?: RequestInit) => {\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : input.url;\n if (!isInceptionUrl(url)) {\n return originalFetch!(input, init);\n }\n\n // Emit an OTel span so the shared processor picks it up.\n const { trace, SpanStatusCode } = await import('@opentelemetry/api');\n const tracer = trace.getTracer('@fieldwork/sdk/mercury');\n return tracer.startActiveSpan(`chat mercury-2`, async (span) => {\n span.setAttribute('gen_ai.system', 'inception');\n span.setAttribute('gen_ai.operation.name', 'chat');\n span.setAttribute('gen_ai.request.model', 'mercury-2');\n try {\n const response = await originalFetch!(input, init);\n if (!response.ok) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });\n }\n return response;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n throw err;\n } finally {\n span.end();\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(`[probe/mercury] captured fetch to ${url}`);\n }\n }\n });\n };\n}\n\nexport function unregisterMercury(): void {\n if (originalFetch) {\n globalThis.fetch = originalFetch;\n originalFetch = null;\n }\n registered = false;\n}\n","/**\n * Instrumentation registry.\n *\n * Each adapter enables its target library's OTel instrumentation (or, for\n * Vercel AI SDK / Mercury-2, documents / opts into the customer wiring).\n * All emitted spans flow through the shared ProbeSpanProcessor which maps\n * gen_ai.* semantic-convention attributes to CapturedTurn.payload and calls\n * Probe.captureTurn().\n *\n * Session correlation: OTel Baggage via session-context.ts. Customers wrap\n * their conversation in Probe.withSession(sessionId, async () => { ... }).\n * Adapters do not need to know about sessions; the processor reads baggage\n * on span end.\n */\n\nimport type { CapturedTurn } from '../types.js';\nimport { setupOtelProvider } from './setup.js';\nimport { bindWrapOpenAI } from './wrap-openai.js';\nimport { registerOpenAI } from './openai.js';\nimport { registerAnthropic } from './anthropic.js';\nimport { registerLangChain } from './langchain.js';\nimport { registerLangGraph } from './langgraph.js';\nimport { registerVercelAI } from './vercel-ai.js';\nimport { registerLiteLLM } from './litellm.js';\nimport { registerMercury } from './mercury.js';\n\nexport { withSession, getCurrentSessionId } from './session-context.js';\nexport { setupOtelProvider, teardownOtelProvider, detachOtelState } from './setup.js';\nexport { ProbeSpanProcessor } from './otel-processor.js';\nexport { wrapOpenAI } from './wrap-openai.js';\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<\n string,\n {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n // Auto version-hash stamping target (see otel-processor.ts).\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n }\n >;\n signatureMatchers: Map<string, unknown>;\n};\n\n/**\n * Register all instrumentation adapters at Probe.init() time.\n *\n * 1. Set up the OTel provider + ProbeSpanProcessor (once per process).\n * 2. Enable each adapter's instrumentation. Adapters no-op if the target\n * library is not installed in the customer's process.\n */\nexport function registerAllInstrumentations(\n state: ProbeState,\n captureFn: (turn: CapturedTurn) => Promise<void>,\n): void {\n setupOtelProvider(state, captureFn);\n\n // Bind the explicit client-wrapping path (wrapOpenAI). Wrapping may have\n // happened before init; capture starts the moment this binding lands.\n bindWrapOpenAI(state, captureFn);\n\n const registrations: Array<Promise<void>> = [\n registerOpenAI(state),\n registerAnthropic(state),\n registerLangChain(state),\n registerLangGraph(state),\n registerVercelAI(state),\n registerLiteLLM(state),\n registerMercury(state),\n ];\n\n Promise.allSettled(registrations).then((results) => {\n if (!state.config.debug) return;\n for (const result of results) {\n if (result.status === 'rejected') {\n // eslint-disable-next-line no-console\n console.error(`[sight] adapter register rejected: ${result.reason}`);\n }\n }\n });\n}\n","/**\n * Signature-phrase matcher.\n *\n * Per-persona regex matching for voice consistency (Day 1 per PROBE.md §2).\n * Customer authors signature phrases at Probe.init({ persona: { signaturePhrases: [...] } }).\n * The SDK edge or a worker computes matches per turn and includes the list\n * of matched slugs in the turn payload.\n *\n * Signature phrase shape: { slug, pattern, description? }. The pattern is\n * either a plain string (case-insensitive whole-token match) or a regex\n * source string with optional flags. Slug is what appears in the matches\n * array; it is not the pattern.\n *\n * Trivial by design. Voice consistency at the embedding level lives in the\n * Chapter 5 Dream column (PSV representation with per-deployment STEL\n * calibration); this is the Day-1 heuristic that ships from ingest data alone.\n */\n\nexport type SignaturePhrase =\n | {\n /** Slug that appears in the matches array. Unique per persona. */\n slug: string;\n /** Plain-text phrase; matched case-insensitive with word boundaries. */\n phrase: string;\n description?: string;\n }\n | {\n slug: string;\n /** Regex source string. Compiled once per matcher construction. */\n regex: string;\n /** Regex flags (default: 'i'). */\n flags?: string;\n description?: string;\n };\n\ntype CompiledPhrase = {\n slug: string;\n pattern: RegExp;\n};\n\n/**\n * Compile a set of signature phrases into a matcher. Compile once at\n * Probe.init() and reuse per turn to avoid regex construction on every call.\n *\n * Invalid regex patterns are dropped with a stderr warning; other phrases\n * continue to match.\n */\nexport function compileSignaturePhrases(phrases: SignaturePhrase[]): CompiledPhrase[] {\n const compiled: CompiledPhrase[] = [];\n for (const p of phrases) {\n try {\n if ('phrase' in p) {\n const escaped = p.phrase.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // Only add \\b anchors where the phrase edge is a word character.\n // Otherwise \\b would require an impossible boundary next to punctuation.\n const startAnchor = /^\\w/.test(p.phrase) ? '\\\\b' : '';\n const endAnchor = /\\w$/.test(p.phrase) ? '\\\\b' : '';\n compiled.push({\n slug: p.slug,\n pattern: new RegExp(`${startAnchor}${escaped}${endAnchor}`, 'i'),\n });\n } else {\n compiled.push({\n slug: p.slug,\n pattern: new RegExp(p.regex, p.flags ?? 'i'),\n });\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(`[classifier/signature-phrase] invalid pattern for slug=${p.slug}: ${msg}`);\n }\n }\n return compiled;\n}\n\n/**\n * Match a text against a compiled signature-phrase set. Returns the list of\n * matched slugs (unique, in the order the phrases were compiled).\n *\n * Empty text or empty compiled set returns [].\n */\nexport function matchSignaturePhrases(\n text: string,\n compiled: CompiledPhrase[],\n): string[] {\n if (!text || compiled.length === 0) return [];\n const matches: string[] = [];\n for (const c of compiled) {\n if (c.pattern.test(text)) matches.push(c.slug);\n }\n return matches;\n}\n","/**\n * The four gap-class families (the Zoom milestone's elevated Z2;\n * core.effectiveness predicate tier) — pure computations over imported\n * records (sessions with their turns + spans), testable without a\n * database. The GENERALIZATION IS STRUCTURAL: every class keys on a\n * telemetry channel and a tool CLASS (the caller passes the\n * per-deployment name→class map), never on a vendor's tool names —\n * Zoom's map is the first instance, a deployer's map is their own\n * definition config (PLAN-2026-07-21: generalized body, per-deployment\n * meaning).\n *\n * Honesty boundary (each family names its own):\n * kb.retrieval-attribution — REFERENCE-FREE structural candidates\n * (3-gram containment + ignorance cues), NOT RAGAS faithfulness;\n * context precision/recall and faithfulness are Z3 judge tiers.\n * Attribution is EXCLUSIVE (retrieval-wrong gates the usage\n * judgment; the unclear band is disclosed) — classes sum to\n * kbFired, never more, never silently less.\n * tooltrajectory.failure-mode — loops/errors/non-termination computed\n * from span sequences + result provenance; wrong-tool is NOT\n * computed (a judgment; MAST's full 14-mode taxonomy is the Z3\n * anchor, κ=0.88 per Cemri 2025).\n * repair.misunderstanding — rephrase/re-ask chains by containment\n * (Schegloff 1977 repair is the anchor; the classifier's\n * conversation-management family is the preliminary lens).\n * interactivity.barge-in-friction — rates/positions/recovery\n * computed; whether a barge-in WAS friction is Z3 (turn-taking /\n * full-duplex literature anchors).\n *\n * All examples are REFERENCES (sessionExternalId + turnIndex) — never\n * verbatim text (the corpus's no-verbatim-in-artifacts rule,\n * DATASETS.md zoom-zva-corpus).\n */\n\n// ── The record shapes the families compute over ─────────────────────────\n\nexport interface GapEnvironmentEvent {\n event: string;\n at?: string;\n meta?: Record<string, unknown>;\n}\n\nexport interface GapTurn {\n turnIndex: number;\n startedAt?: string | null;\n agentText?: string | null;\n userReplyText?: string | null;\n initiatingUserText?: string | null;\n environmentEventStream?: GapEnvironmentEvent[];\n /** probe_user_grounding_move — the user's grounding moves on this turn\n ('repair-initiate' = the user initiates repair against the agent's\n prior turn — the corrections-unmet predicate's trigger; E2). NEVER\n the deprecated probe_user_correction_signals column (Amendment H:\n subsumed by discourse_relation + grounding_move). */\n userGroundingMove?: string[] | null;\n /** probe_pair_completed — the pair machinery's own completion mark\n (false = pair opened, never completed; null = no pair opened). */\n pairCompleted?: boolean | null;\n}\n\nexport interface GapSpan {\n turnIndex: number;\n spanType: string;\n name: string;\n durationMs?: number | null;\n tokensInput?: number | null;\n tokensOutput?: number | null;\n attributes?: Record<string, unknown> | null;\n}\n\nexport interface GapSession {\n externalId: string;\n turns: GapTurn[];\n spans: GapSpan[];\n}\n\nexport interface GapExample {\n sessionExternalId: string;\n turnIndex: number;\n note: string;\n}\n\n/** The per-deployment generalization knob: a name→class map OR a\n classifier function (defaultToolClass for pattern-based defaults). */\nexport type ToolClassifier = ((name: string) => string) | Record<string, string>;\n\n/**\n * The pattern-based default tool classifier — the generalized body when\n * no per-deployment map exists. Zoom's explicit map ships in\n * fixtures/zva/effectiveness-definitions.mjs as the first instance;\n * anything unmatched falls to 'other' (a finding, never an error).\n *\n * NOT a duplicate of session-insights' isEscalationKind (P1-R2 note):\n * this predicate classifies TOOL NAMES (`transfer_to_agent` the\n * function) into tool classes; that one classifies OUTCOME KINDS\n * (`transferred_to_sales` the emitted event). Same vocabulary, two\n * domains — merging them would let a tool-name pattern claim an outcome\n * happened.\n */\nexport function defaultToolClass(name: string): string {\n const n = name.toLowerCase();\n if (/knowledge|kb|retriev|article|faq/.test(n)) return 'kb';\n if (/otp|password|passcode|verif|one.?time/.test(n)) return 'auth_otp';\n if (/transfer|hand.?off|escalat|live.?agent|human.?agent/.test(n)) return 'transfer';\n if (/end_conversation|hangup|hang.?up|end_call|goodbye|close_conversation/.test(n)) return 'end';\n if (/survey|csat|nps|feedback/.test(n)) return 'survey';\n if (/sms|email|message|notify/.test(n)) return 'comms';\n if (/^get_|lookup|search|find|fetch|query|detail|entitle|eligib|existing|is_/.test(n)) return 'lookup';\n if (/^set_|config|admin|assign|route/.test(n)) return 'admin';\n return 'other';\n}\n\n/** Resolve the classifier to a function. */\nfunction classifyTool(tc: ToolClassifier, name: string): string {\n return typeof tc === 'function' ? tc(name) : (tc[name] ?? 'other');\n}\n\n\nexport interface KbAttributionResult {\n // EXCLUSIVE classes (the RAGChecker three-way split made honest): each\n // fired lookup lands in exactly one of retrievedWrong / grounded /\n // ignored / indeterminate / noChunksRecorded, so the classes always sum\n // to kbFired — the rows reconcile on inspection, never 112 > 96.\n counts: {\n needsRetrieval: number;\n kbFired: number;\n grounded: number;\n retrievedWrong: number;\n ignored: number;\n /** Usage neither visibly grounded nor clearly ignored (the 0.05–0.2\n band) — disclosed, never silently dropped. */\n indeterminate: number;\n /** Lookup fired but no chunks were recorded on the span — a telemetry\n gap, counted separately so the classes still reconcile. */\n noChunksRecorded: number;\n notRetrieved: number;\n };\n examples: { retrievedWrong: GapExample[]; ignored: GapExample[]; notRetrieved: GapExample[] };\n}\nexport interface ToolFailureResult {\n counts: { loops: number; toolErrors: number; sessionsWithErrors: number; nonTermination: number };\n /** Per-tool breakdown — the card's \"most failing / most looped tool\"\n rows. Counts loop-RUNS and error events keyed on the deployer's own\n tool name (their vocabulary, unhumanized). */\n byTool: { errors: Record<string, number>; loops: Record<string, number> };\n examples: { loops: GapExample[]; toolErrors: GapExample[]; nonTermination: GapExample[] };\n}\nexport interface RepairResult {\n counts: { userRephrase: number; userVerbatim: number; agentReask: number };\n examples: { userRephrase: GapExample[]; agentReask: GapExample[] };\n}\nexport interface BargeResult {\n counts: { events: number; killed: number };\n positionsMs: number[];\n recoveryMs: number[];\n examples: GapExample[];\n}\n\n// ── Text helpers (the Contain metric — Zhang 2026 appendix's 3-gram\n// containment, reused as the reference-free overlap proxy) ───────────────\n\nfunction ngrams(text: unknown, n = 3): Set<string> {\n const words = String(text ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ')\n .split(/\\s+/)\n .filter(Boolean);\n if (words.length === 0) return new Set();\n if (words.length < n) return new Set(words);\n const out = new Set<string>();\n for (let i = 0; i + n <= words.length; i++) out.add(words.slice(i, i + n).join(' '));\n return out;\n}\n\n/** Asymmetric containment: how much of a's n-gram mass appears in b. */\nexport function contain(a: unknown, b: unknown): number {\n const A = ngrams(a);\n const B = ngrams(b);\n if (A.size === 0) return 0;\n let hit = 0;\n for (const g of A) if (B.has(g)) hit++;\n return hit / A.size;\n}\n\nconst IGNORANCE_RE =\n /unable to find|can't find|couldn't find|could not find|not able to find|don't have (that|any|the) information|do not have (that|any|the) information|no information|i was unable/i;\nconst QUESTION_RE =\n /^(hi |hello |okay[, ]|um[, ]|uh[, ])*\\s*(who|what|when|where|why|how|can|could|is|are|do|does|did|may|might|should)\\b|\\?\\s*$|how (to|do|can)|what is|where is|can you (tell|help|check|find)/i;\nconst SILENCE_RE = /^\\((user is silent|user connected)/i;\n/** Conventionalized open/close formulas — verbatim by convention, not by\n misunderstanding (\"Anything else I can help with today?\" re-asked is\n a closing ritual, not a repair loop). Excluded from re-ask detection. */\nconst CLOSING_FORMULA_RE =\n /anything else|is there anything|how (can|may) i (help|assist)|thank(s| you) for (calling|your time)|have a (great|good|wonderful) (day|one|rest)/i;\n\nconst STOPWORDS = new Set(\n 'the a an to of and or is are was were do does did how what where when who why which can could should would may might i you your my me it its this that these those in on for with at by from as be been being am not no yes okay ok um uh hi hello please thanks thank'.split(' '),\n);\n\n/** Stopword-stripped unigram containment — the IR-style query↔document\n relevance proxy (robust to phrasing where 3-gram containment is not:\n \"how do i change my billing email\" vs \"change the billing email\n address\" shares every content token). */\nfunction containTokens(a: unknown, b: unknown): number {\n const tok = (s: unknown): string[] =>\n String(s ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ')\n .split(/\\s+/)\n .filter((w) => w && !STOPWORDS.has(w));\n const A = new Set(tok(a));\n const B = new Set(tok(b));\n if (A.size === 0) return 0;\n let hit = 0;\n for (const w of A) if (B.has(w)) hit++;\n return hit / A.size;\n}\n\nfunction isQuestion(text: unknown): boolean {\n return typeof text === 'string' && QUESTION_RE.test(text.trim());\n}\n\n/** Agent re-ask shape: interrogative OR an imperative service question\n (\"please provide the phone number…\" — no '?' anywhere). */\nfunction isQuestionShape(text: unknown): boolean {\n return (\n isQuestion(text) ||\n (typeof text === 'string' &&\n (/\\?/.test(text) || /please (provide|tell|confirm|say|enter|share|verify)/i.test(text)))\n );\n}\n\n// ── Family 1: kb.retrieval-attribution ──────────────────────────────────\n\nconst WRONG_MAX = 0.2; // stopword-stripped token containment under which the retrieval looks irrelevant to the question\nconst IGNORED_MAX = 0.05; // answer↔chunk 3-gram containment under which the answer ignores retrieval\nconst GROUNDED_MIN = 0.2; // answer↔chunk 3-gram containment above which usage is visible\n\n/** The per-turn KB classes — the EXCLUSIVE attribution (retrieval-wrong\n gates the usage judgment; the unclear band is disclosed). */\nexport type KbTurnClass =\n | 'grounded'\n | 'retrievedWrong'\n | 'ignored'\n | 'indeterminate'\n | 'noChunksRecorded';\n\nexport type KbTurnAttribution = {\n turnIndex: number;\n cls: KbTurnClass;\n /** The answer↔chunk usage score (null on the gated classes). */\n usage: number | null;\n /** The reply carried an ignorance cue (drives the ignored example note). */\n ignoranceCue: boolean;\n};\n\n/**\n * THE per-turn KB classifier (D26 extraction): kbRetrievalAttribution's\n * counts are a fold over these classes, and the grouped drill's flagged\n * set reads the same classes — one definition, never a re-derived\n * lookalike. Only turns that FIRED a lookup are attributed;\n * needsRetrieval / notRetrieved are question-shape judgments, not\n * retrieval classes, and stay in the counting wrapper.\n */\nexport function attributeKbTurns(session: GapSession, toolClasses: ToolClassifier): KbTurnAttribution[] {\n const kbSpans = session.spans.filter((s: GapSpan) => classifyTool(toolClasses, s.name) === 'kb');\n const out: KbTurnAttribution[] = [];\n for (const turn of session.turns) {\n const userText = turn.userReplyText ?? turn.initiatingUserText ?? null;\n const kb = kbSpans.filter((s) => s.turnIndex === turn.turnIndex);\n if (kb.length === 0) continue;\n const chunkCorpus = kb\n .flatMap((s: GapSpan) => ((s.attributes?.['chunks'] as any[] | undefined) ?? []))\n .map((c: any) => `${c.articleTitle ?? ''} ${c.chunkContent ?? ''}`)\n .join('\\n');\n // The telemetry-gap bucket: the lookup fired but its chunks weren't\n // recorded — counted so the classes reconcile, never silently skipped.\n if (chunkCorpus.trim().length === 0) {\n out.push({ turnIndex: turn.turnIndex, cls: 'noChunksRecorded', usage: null, ignoranceCue: false });\n continue;\n }\n // EXCLUSIVE attribution: when the retrieval missed the question, the\n // usage judgment is a category error — you cannot blame grounding for\n // ignoring irrelevant chunks (the RAGChecker split, applied as GATING,\n // not as an overlapping axis). retrievedWrong ends the classification.\n if (userText && containTokens(userText, chunkCorpus) < WRONG_MAX) {\n out.push({ turnIndex: turn.turnIndex, cls: 'retrievedWrong', usage: null, ignoranceCue: false });\n continue;\n }\n const usage = contain(turn.agentText ?? '', chunkCorpus);\n const ignoranceCue = IGNORANCE_RE.test(turn.agentText ?? '');\n if (usage >= GROUNDED_MIN) {\n out.push({ turnIndex: turn.turnIndex, cls: 'grounded', usage, ignoranceCue });\n } else if (usage < IGNORED_MAX || ignoranceCue) {\n out.push({ turnIndex: turn.turnIndex, cls: 'ignored', usage, ignoranceCue });\n } else {\n // The disclosed middle band: usage neither visible nor clearly\n // absent (paraphrase-heavy synthesis lands here). Counted, never\n // hidden — the classes sum to kbFired.\n out.push({ turnIndex: turn.turnIndex, cls: 'indeterminate', usage, ignoranceCue });\n }\n }\n return out;\n}\n\nexport function kbRetrievalAttribution(session: GapSession, toolClasses: ToolClassifier): KbAttributionResult {\n const out: KbAttributionResult = { counts: { needsRetrieval: 0, kbFired: 0, grounded: 0, retrievedWrong: 0, ignored: 0, indeterminate: 0, noChunksRecorded: 0, notRetrieved: 0 }, examples: { retrievedWrong: [], ignored: [], notRetrieved: [] } };\n // The count fold over the SHARED per-turn classifier (attributeKbTurns\n // owns every class boundary; this wrapper adds the question-shape\n // counts, which are not retrieval classes).\n const attributed = attributeKbTurns(session, toolClasses);\n const attributedTurnIndices = new Set(attributed.map((a) => a.turnIndex));\n for (const a of attributed) {\n out.counts.kbFired++;\n out.counts[a.cls]++;\n if (a.cls === 'retrievedWrong' && out.examples.retrievedWrong.length < 5) {\n out.examples.retrievedWrong.push({ sessionExternalId: session.externalId, turnIndex: a.turnIndex, note: `query↔chunk token containment < ${WRONG_MAX} (stopword-stripped)` });\n }\n if (a.cls === 'ignored' && out.examples.ignored.length < 5) {\n out.examples.ignored.push({ sessionExternalId: session.externalId, turnIndex: a.turnIndex, note: `answer↔chunk containment ${(a.usage ?? 0).toFixed(3)}${a.ignoranceCue ? ' + ignorance cue' : ''}` });\n }\n }\n for (const turn of session.turns) {\n const userText = turn.userReplyText ?? turn.initiatingUserText ?? null;\n const needsRetrieval = isQuestion(userText);\n if (needsRetrieval) out.counts.needsRetrieval++;\n if (!attributedTurnIndices.has(turn.turnIndex) && needsRetrieval && IGNORANCE_RE.test(turn.agentText ?? '')) {\n out.counts.notRetrieved++;\n if (out.examples.notRetrieved.length < 5) {\n out.examples.notRetrieved.push({ sessionExternalId: session.externalId, turnIndex: turn.turnIndex, note: 'question-like user turn, no KB call, ignorance-claim reply' });\n }\n }\n }\n return out;\n}\n\n// ── Family 2: tooltrajectory.failure-mode ───────────────────────────────\n\n/**\n * The method version of the tool-error predicate below (F2, 2026-08-05).\n * v1: the success-whitelist + value-regex form (asserted failure from\n * unrecognized vocabulary; fired on routine flag writes — the \"84 tool\n * errors\" overcount). v2: affirmative-only result provenance (the raw\n * audit's correction: 84 → 60 on zoom-zva). Bumped on every predicate\n * change so an audit packet can name the method its numbers came from —\n * judges carry versions; computed predicates carry them too, because a\n * number that changes under a method revision must be able to SAY so.\n */\nexport const TOOL_ERROR_PREDICATE_VERSION = 2;\n\n/** Affirmative error vocabulary for STATUS-BEARING fields (status /\n responseType) — a field whose job is to report outcome counts as an\n error only when it SAYS so. The old success-whitelist asserted\n failure from any unrecognized word (the anti-theater violation the\n 2026-08-05 raw audit caught: routine vocab counted as errors). */\nconst TOOL_ERROR_STATUS_RE = /error|fail|invalid|denied|expired|timeout|exception/i;\n\n/** Variable updates report an error only through a variable NAMED for\n it (ani_error_message, lookup_failure, …) carrying a real value.\n The old value-regex fired on `false` booleans and `Unknown` defaults\n in ordinary variables — 45 of Zoom's \"84 tool errors\" were routine\n flag writes (raw audit, 2026-08-05). */\nconst ERROR_VAR_NAME_RE = /error|fail/i;\nconst EMPTYISH_RE = /^(?:|null|undefined|none)$/i;\n\n/**\n * THE span-level tool-error predicate (D26 extraction, re-grounded\n * 2026-08-05): error arrives by AFFIRMATIVE result provenance —\n * explicit false status, an error-ish status/responseType word, error\n * logs, or an error-NAMED variable carrying a value. Never asserted\n * from unrecognized vocabulary (a status word we don't know is not a\n * failure), never from a boolean flag's value. status arrives as a\n * BOOLEAN in this telemetry (true = success — the 190-false-fire\n * lesson). tooltrajectory.failure-mode's error counts fold this, and\n * the grouped drill's flagged set reads the same predicate —\n * turn-level probe_error is a DIFFERENT instrument (the drill-audit\n * revert), never a substitute.\n */\nexport function isToolErrorishAttributes(a: Record<string, unknown> | null | undefined): boolean {\n if (!a) return false;\n const statusFail =\n a['status'] === false ||\n (typeof a['status'] === 'string' && TOOL_ERROR_STATUS_RE.test(a['status'] as string));\n const responseFail =\n typeof a['responseType'] === 'string' &&\n TOOL_ERROR_STATUS_RE.test(a['responseType'] as string);\n return (\n statusFail ||\n responseFail ||\n (Array.isArray(a['errorLogs']) && (a['errorLogs'] as unknown[]).length > 0) ||\n (Array.isArray(a['variableUpdated']) &&\n (a['variableUpdated'] as any[]).some(\n (v: any) =>\n ERROR_VAR_NAME_RE.test(String(v.variableName ?? '')) &&\n !EMPTYISH_RE.test(String(v.currentValue ?? '').trim()),\n ))\n );\n}\n\n/**\n * The turn indices of a session's tool-call spans carrying an error —\n * the family's error set read per turn (the D26 drill's flagged set).\n * Counts fold error EVENTS (a turn with two failing spans counts twice\n * there); this set dedupes to the turn, as a turns-page filter must.\n */\nexport function toolErrorTurnIndices(session: GapSession): number[] {\n const out = new Set<number>();\n for (const s of session.spans) {\n if (s.spanType !== 'tool_call') continue;\n if (isToolErrorishAttributes(s.attributes ?? null)) out.add(s.turnIndex);\n }\n return [...out].sort((a, b) => a - b);\n}\n\nexport function toolTrajectoryFailureMode(session: GapSession, toolClasses: ToolClassifier, outcomesByKind?: Set<string>): ToolFailureResult {\n const out: ToolFailureResult = {\n counts: { loops: 0, toolErrors: 0, sessionsWithErrors: 0, nonTermination: 0 },\n byTool: { errors: {}, loops: {} },\n examples: { loops: [], toolErrors: [], nonTermination: [] },\n };\n const tools = session.spans.filter((s) => s.spanType === 'tool_call');\n // Consecutive same-name runs ≥3 = loop.\n let run: { name: string; length: number; firstTurnIndex: number } | null = null;\n const flushRun = () => {\n if (run && run.length >= 3) {\n out.counts.loops++;\n out.byTool.loops[run.name] = (out.byTool.loops[run.name] ?? 0) + 1;\n if (out.examples.loops.length < 5) {\n out.examples.loops.push({ sessionExternalId: session.externalId, turnIndex: run.firstTurnIndex, note: `${run.name} × ${run.length} consecutive` });\n }\n }\n };\n for (const s of tools) {\n if (run && s.name === run.name) {\n run.length++;\n } else {\n flushRun();\n run = { name: s.name, length: 1, firstTurnIndex: s.turnIndex };\n }\n }\n flushRun();\n // Tool errors from result provenance — the SHARED predicate\n // (isToolErrorishAttributes owns the definition; the reason note for\n // the example is presentation, recomputed here).\n let sessionHasError = false;\n for (const s of tools) {\n if (isToolErrorishAttributes(s.attributes ?? null)) {\n const a = (s.attributes ?? {}) as any;\n const statusFail =\n a.status === false ||\n (typeof a.status === 'string' && TOOL_ERROR_STATUS_RE.test(a.status));\n const responseFail =\n typeof a.responseType === 'string' && TOOL_ERROR_STATUS_RE.test(a.responseType);\n out.counts.toolErrors++;\n out.byTool.errors[s.name] = (out.byTool.errors[s.name] ?? 0) + 1;\n sessionHasError = true;\n if (out.examples.toolErrors.length < 5) {\n const reason =\n a.variableUpdated?.find(\n (v: any) =>\n ERROR_VAR_NAME_RE.test(String(v.variableName ?? '')) &&\n !EMPTYISH_RE.test(String(v.currentValue ?? '').trim()),\n )?.currentValue ??\n (statusFail ? `status=${String(a.status)}` : null) ??\n (responseFail ? a.responseType : null) ??\n 'errorLogs';\n out.examples.toolErrors.push({ sessionExternalId: session.externalId, turnIndex: s.turnIndex, note: `${s.name}: ${reason}` });\n }\n }\n }\n if (sessionHasError) out.counts.sessionsWithErrors++;\n // Non-termination: no ending outcome AND the tail is silence/empty.\n if ((outcomesByKind?.size ?? 0) === 0) {\n const last = session.turns[session.turns.length - 1];\n const tailSilent = SILENCE_RE.test(last?.userReplyText ?? '') || (last?.agentText ?? '') === '';\n if (tailSilent) {\n out.counts.nonTermination++;\n if (out.examples.nonTermination.length < 5) {\n out.examples.nonTermination.push({ sessionExternalId: session.externalId, turnIndex: last?.turnIndex ?? 0, note: 'no ending outcome; tail is silence/empty' });\n }\n }\n }\n return out;\n}\n\n// ── Family 3: repair.misunderstanding ───────────────────────────────────\n\n/** The content floor: \"yes / okay / thanks\" pairs repeat verbatim ~100%\n of the time and are conversation, not repair (the 963-false-fire\n lesson from the first prod run). Repetition only signals\n misunderstanding when BOTH sides carry ≥4 content words. */\nconst contentWords = (text: unknown): number =>\n String(text ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ')\n .split(/\\s+/)\n .filter((w: string) => w && !STOPWORDS.has(w)).length;\n\nexport interface RepairFlaggedTurn {\n turnIndex: number;\n /** The consecutive-pair containment that flagged it (provenance). */\n containment: number;\n}\n\n/**\n * THE repair family's flagged turns (D26 extraction): the SECOND turn of\n * each consecutive content pair meeting the family's bands — user\n * verbatim ≥0.9, user rephrase 0.5–0.9, agent re-ask ≥0.6 on a question\n * shape with closing formulas excluded. repairMisunderstanding's counts\n * are these lists' lengths; the grouped drill reads the same refs. (The\n * refs resolve to the pair's own turn — the pre-extraction code resolved\n * examples by text match, which could point at an earlier same-text\n * turn; counts were and are pair counts, unchanged.)\n */\nexport function repairFlaggedTurns(session: GapSession): {\n userRephrase: RepairFlaggedTurn[];\n userVerbatim: RepairFlaggedTurn[];\n agentReask: RepairFlaggedTurn[];\n} {\n const userTurns = session.turns.filter(\n (t) =>\n typeof t.userReplyText === 'string' &&\n !SILENCE_RE.test(t.userReplyText) &&\n contentWords(t.userReplyText) >= 4,\n );\n const userRephrase: RepairFlaggedTurn[] = [];\n const userVerbatim: RepairFlaggedTurn[] = [];\n for (let i = 0; i + 1 < userTurns.length; i++) {\n const c = contain(userTurns[i]!.userReplyText, userTurns[i + 1]!.userReplyText);\n if (c >= 0.9) userVerbatim.push({ turnIndex: userTurns[i + 1]!.turnIndex, containment: c });\n else if (c >= 0.5) userRephrase.push({ turnIndex: userTurns[i + 1]!.turnIndex, containment: c });\n }\n const agentTurns = session.turns.filter(\n (t) => typeof t.agentText === 'string' && contentWords(t.agentText) >= 4,\n );\n const agentReask: RepairFlaggedTurn[] = [];\n for (let i = 0; i + 1 < agentTurns.length; i++) {\n const c = contain(agentTurns[i]!.agentText, agentTurns[i + 1]!.agentText);\n if (\n c >= 0.6 &&\n isQuestionShape(agentTurns[i]!.agentText) &&\n !CLOSING_FORMULA_RE.test(agentTurns[i]!.agentText!)\n ) {\n agentReask.push({ turnIndex: agentTurns[i + 1]!.turnIndex, containment: c });\n }\n }\n return { userRephrase, userVerbatim, agentReask };\n}\n\nexport function repairMisunderstanding(session: GapSession): RepairResult {\n const flagged = repairFlaggedTurns(session);\n const out: RepairResult = {\n counts: {\n userRephrase: flagged.userRephrase.length,\n userVerbatim: flagged.userVerbatim.length,\n agentReask: flagged.agentReask.length,\n },\n examples: { userRephrase: [], agentReask: [] },\n };\n for (const f of flagged.userRephrase.slice(0, 5)) {\n out.examples.userRephrase.push({ sessionExternalId: session.externalId, turnIndex: f.turnIndex, note: `consecutive-user containment ${f.containment.toFixed(2)}` });\n }\n for (const f of flagged.agentReask.slice(0, 5)) {\n out.examples.agentReask.push({ sessionExternalId: session.externalId, turnIndex: f.turnIndex, note: `agent re-ask, containment ${f.containment.toFixed(2)}` });\n }\n return out;\n}\n\n// ── Family 4: interactivity.barge-in-friction ───────────────────────────\n\nexport interface BargeInRef {\n /** The interrupted turn — null when the event predates the first turn\n (still counted as an event; resolvable to no turn, so never part of\n the drill's flagged set). */\n turnIndex: number | null;\n positionMs: number | null;\n /** null when the interrupt killed the conversation (no following turn). */\n recoveryMs: number | null;\n killed: boolean;\n}\n\n/**\n * THE barge-in event set (D26 extraction): one ref per interrupt event\n * with a parseable timestamp. bargeInFriction's counts fold these; the\n * grouped drill reads the interrupted turns from the same refs (null\n * turnIndex refs dropped, the rest deduped — a turn interrupted twice is\n * one row). Resolve the interrupted turn BY TIME, never by the event's\n * stored attachment: the worker's next-turn attach ran when turns\n * carried processing-time started_at (imported historical corpus), so\n * attachment position is not meaningful — the event's own `at` on the\n * telemetry clock is the authority (restored by the backfill).\n */\nexport function bargeInRefs(session: GapSession): BargeInRef[] {\n const interrupts: GapEnvironmentEvent[] = [];\n for (const turn of session.turns) {\n for (const e of turn.environmentEventStream ?? []) {\n if (e.event === 'interrupt') interrupts.push(e);\n }\n }\n const turnStart = (t: GapTurn): number => Date.parse(t.startedAt ?? '');\n const out: BargeInRef[] = [];\n for (const e of interrupts) {\n const at = Date.parse(e.at ?? '');\n if (!Number.isFinite(at)) continue;\n let activeIdx: number | null = null;\n for (let i = 0; i < session.turns.length; i++) {\n if (turnStart(session.turns[i]!) <= at) activeIdx = i;\n else break;\n }\n if (activeIdx === null) {\n out.push({ turnIndex: null, positionMs: null, recoveryMs: null, killed: false });\n continue;\n }\n const next = session.turns[activeIdx + 1];\n const recovered = next !== undefined && Number.isFinite(turnStart(next));\n out.push({\n turnIndex: session.turns[activeIdx]!.turnIndex,\n positionMs: Math.max(0, at - turnStart(session.turns[activeIdx]!)),\n recoveryMs: recovered ? Math.max(0, turnStart(next!) - at) : null,\n killed: !recovered,\n });\n }\n return out;\n}\n\nexport function bargeInFriction(session: GapSession): BargeResult {\n const refs = bargeInRefs(session);\n const out: BargeResult = {\n counts: {\n events: refs.length,\n killed: refs.filter((r) => r.killed).length,\n },\n positionsMs: refs.flatMap((r) => (r.positionMs !== null ? [r.positionMs] : [])),\n recoveryMs: refs.flatMap((r) => (r.recoveryMs !== null ? [r.recoveryMs] : [])),\n examples: [],\n };\n for (const r of refs.filter((x) => x.turnIndex !== null).slice(0, 5)) {\n out.examples.push({\n sessionExternalId: session.externalId,\n turnIndex: r.turnIndex!,\n note: r.killed ? 'no following turn' : `recovered in ${Math.round((r.recoveryMs ?? 0) / 1000)}s`,\n });\n }\n return out;\n}\n\n// ── Timing trustworthiness guard ─────────────────────────────────────────\n// Voice timing (barge-in position / recovery) is a measurement ONLY when the\n// event and turn clocks are real and reconcilable. An imported historical\n// corpus can carry backfilled or processing-time timestamps whose deltas are\n// meaningless — a \"recovery\" of days, or every position pinned to 0. Rather\n// than print a broken number, a timing channel is reported only when enough\n// samples land in a plausible window AND carry real spread; otherwise the\n// median is suppressed with a reason and only the event COUNT stands.\n// GENERALIZED: any corpus with unusable timing is flagged the same way — this\n// is not a Zoom special case, it is the honesty rule for the timing channel.\nconst MAX_POSITION_MS = 120_000; // a barge-in lands ≤ 2 min into an agent turn\nconst MAX_RECOVERY_MS = 120_000; // the next turn follows ≤ 2 min after\nconst MIN_TIMING_SAMPLES = 3;\n\nexport function summarizeTiming(samples: number[], maxMs: number) {\n const plausible = samples.filter((x) => Number.isFinite(x) && x >= 0 && x <= maxMs);\n const dropped = samples.length - plausible.length;\n // Real spread guards against a degenerate channel where every sample\n // collapses to the same value (e.g. positions all pinned to 0).\n const hasSpread = new Set(plausible).size > 1;\n const available =\n plausible.length >= MIN_TIMING_SAMPLES && plausible.length >= dropped && hasSpread;\n let medianMs: number | null = null;\n if (available) {\n const s = [...plausible].sort((a, b) => a - b);\n medianMs = s[Math.floor(s.length / 2)] ?? null;\n }\n return { available, medianMs, plausible: plausible.length, dropped };\n}\n\n// ── The driver-facing aggregate ─────────────────────────────────────────\n\nexport function computeGapClasses(sessions: GapSession[], { toolClasses, outcomesBySession }: { toolClasses: ToolClassifier; outcomesBySession?: Map<string, Set<string>> }) {\n const kb = { needsRetrieval: 0, kbFired: 0, grounded: 0, retrievedWrong: 0, ignored: 0, indeterminate: 0, noChunksRecorded: 0, notRetrieved: 0 };\n const tool = { loops: 0, toolErrors: 0, sessionsWithErrors: 0, nonTermination: 0 };\n const toolByTool: { errors: Record<string, number>; loops: Record<string, number> } = { errors: {}, loops: {} };\n const repair = { userRephrase: 0, userVerbatim: 0, agentReask: 0 };\n const barge = { events: 0, killed: 0 };\n const examples: {\n retrievedWrong: GapExample[]; ignored: GapExample[]; notRetrieved: GapExample[];\n loops: GapExample[]; toolErrors: GapExample[]; nonTermination: GapExample[];\n userRephrase: GapExample[]; agentReask: GapExample[]; bargeIn: GapExample[];\n } = { retrievedWrong: [], ignored: [], notRetrieved: [], loops: [], toolErrors: [], nonTermination: [], userRephrase: [], agentReask: [], bargeIn: [] };\n const positions: number[] = [];\n const recoveries: number[] = [];\n for (const s of sessions) {\n const k = kbRetrievalAttribution(s, toolClasses);\n for (const key of Object.keys(kb) as Array<keyof KbAttributionResult[\"counts\"]>) kb[key] += k.counts[key];\n examples.retrievedWrong.push(...k.examples.retrievedWrong.slice(0, 5 - examples.retrievedWrong.length));\n examples.ignored.push(...k.examples.ignored.slice(0, 5 - examples.ignored.length));\n examples.notRetrieved.push(...k.examples.notRetrieved.slice(0, 5 - examples.notRetrieved.length));\n const t = toolTrajectoryFailureMode(s, toolClasses, outcomesBySession?.get(s.externalId));\n tool.loops += t.counts.loops;\n tool.toolErrors += t.counts.toolErrors;\n tool.sessionsWithErrors += t.counts.sessionsWithErrors;\n tool.nonTermination += t.counts.nonTermination;\n for (const [n, c] of Object.entries(t.byTool.errors)) toolByTool.errors[n] = (toolByTool.errors[n] ?? 0) + c;\n for (const [n, c] of Object.entries(t.byTool.loops)) toolByTool.loops[n] = (toolByTool.loops[n] ?? 0) + c;\n examples.loops.push(...t.examples.loops.slice(0, 5 - examples.loops.length));\n examples.toolErrors.push(...t.examples.toolErrors.slice(0, 5 - examples.toolErrors.length));\n examples.nonTermination.push(...t.examples.nonTermination.slice(0, 5 - examples.nonTermination.length));\n const r = repairMisunderstanding(s);\n repair.userRephrase += r.counts.userRephrase;\n repair.userVerbatim += r.counts.userVerbatim;\n repair.agentReask += r.counts.agentReask;\n examples.userRephrase.push(...r.examples.userRephrase.slice(0, 5 - examples.userRephrase.length));\n examples.agentReask.push(...r.examples.agentReask.slice(0, 5 - examples.agentReask.length));\n const b = bargeInFriction(s);\n barge.events += b.counts.events;\n barge.killed += b.counts.killed;\n positions.push(...b.positionsMs);\n recoveries.push(...b.recoveryMs);\n examples.bargeIn.push(...b.examples.slice(0, 5 - examples.bargeIn.length));\n }\n const position = summarizeTiming(positions, MAX_POSITION_MS);\n const recovery = summarizeTiming(recoveries, MAX_RECOVERY_MS);\n const timingAvailable = position.available || recovery.available;\n return {\n 'kb.retrieval-attribution': { counts: kb, examples: { retrievedWrong: examples.retrievedWrong, ignored: examples.ignored, notRetrieved: examples.notRetrieved } },\n 'tooltrajectory.failure-mode': { counts: tool, byTool: toolByTool, examples: { loops: examples.loops, toolErrors: examples.toolErrors, nonTermination: examples.nonTermination } },\n 'repair.misunderstanding': { counts: repair, examples: { userRephrase: examples.userRephrase, agentReask: examples.agentReask } },\n 'interactivity.barge-in-friction': {\n counts: barge,\n timing: {\n available: timingAvailable,\n // Suppressed, not faked: the event count is trustworthy; the sub-turn\n // timing on this corpus is not (degenerate/backfilled timestamps).\n reason: timingAvailable\n ? null\n : 'backfilled or processing-time timestamps on this imported corpus',\n positionMedianMs: position.medianMs,\n recoveryMedianMs: recovery.medianMs,\n samples: {\n position: position.plausible,\n positionDropped: position.dropped,\n recovery: recovery.plausible,\n recoveryDropped: recovery.dropped,\n },\n },\n examples: examples.bargeIn,\n },\n };\n}\n","/**\n * Shared types and constants across ingest, dashboard, and future SDK.\n * Keep this package small; anything domain-specific belongs in @fieldwork/db\n * or its own package.\n */\n\nimport { z } from 'zod';\n\n// ── Situation vocabulary (OPEN) ───────────────────────────────────────────\n// Situation-type is open-vocabulary. The Day-1 heuristic emits a general\n// dialogue-act seed; a deployment discovers its own situation types by\n// clustering across sessions, and a harness can pass any tag it authors.\n// The arrays below are SEEDS, not a closed enum — the situation column is\n// text[] and ingest accepts any string tag.\n\n// Domain-general dialogue-act seed (the default classifier vocabulary; fits\n// support, assistants, and any conversational deployment).\nexport const GENERAL_SITUATION_TAGS = [\n 'question',\n 'request',\n 'inform',\n 'correction',\n 'confirmation',\n 'escalation',\n 'closing',\n 'smalltalk',\n] as const;\n\n// Narrative pack (companion / roleplay), opt-in — the field-derived types.\nexport const NARRATIVE_SITUATION_TAGS = [\n 'status_power_shift',\n 'deception_concealment',\n 'dramatic_irony',\n 'reveal_recognition',\n 'betrayal_broken_trust',\n 'reconciliation_repair',\n 'moral_dilemma_subtext',\n 'comedic_incongruity',\n] as const;\n\n// Situation tags are open strings; the arrays above are seeds, not an enum.\nexport type SituationTag = string;\n\n// Back-compat aliases (the narrative pack keeps the historical names).\nexport const SITUATION_TYPES = NARRATIVE_SITUATION_TAGS;\nexport type SituationType = (typeof NARRATIVE_SITUATION_TAGS)[number];\n\n// ── Reaction register from Vincent's harness ──────────────────────────────\nexport const REACTION_REGISTERS = ['heavy', 'comic', 'edge'] as const;\nexport type ReactionRegister = (typeof REACTION_REGISTERS)[number];\n\n// ── Outcome type per probe.md §2 ──────────────────────────────────────────\nexport const OUTCOME_TYPES = ['numeric', 'categorical', 'boolean', 'duration'] as const;\nexport type OutcomeType = (typeof OUTCOME_TYPES)[number];\n\n// ── Interpretive fields the SDK may pass through from a harness ────────────\n// Customer running the Cultured Computer harness pattern or wiring the\n// Oracle read hook can populate these at the SDK edge; ingest passes them\n// through to canonical turns. When absent, the async classifier workers\n// (packages/classifier) populate situation_type and reaction_register from\n// Tier 1 records; lens_chosen stays null for non-harness deployments.\nexport const InterpretiveRecordSchema = z.object({\n // Open vocabulary: any string tag. Seeds live in GENERAL_SITUATION_TAGS /\n // NARRATIVE_SITUATION_TAGS but ingest never rejects an unseen situation.\n situationType: z.array(z.string()).optional(),\n read: z.string().optional(),\n lensChosen: z.string().optional(),\n reactionRegister: z.enum(REACTION_REGISTERS).optional(),\n reactionNextTurn: z.string().optional(),\n});\nexport type InterpretiveRecord = z.infer<typeof InterpretiveRecordSchema>;\n\n// ── Propensity + candidates (Day 1 harness-supplied, per PROBE.md §2) ─────\n// The one thing that cannot be backfilled: the alternative reads the harness\n// considered, the actual sampling distribution used to select among them,\n// which was selected, and (separately) raw model confidence/logprobs.\n//\n// `scores` and `propensities` are DIFFERENT things and must not be\n// conflated. Off-policy evaluation requires `propensities` — the behavior\n// policy's actual sampling probability at selection time — not scores.\n// A harness that samples with temperature/top_p and then reports raw\n// softmax(logits) as \"propensity\" will break DR estimators. `scores`\n// remains useful as a diagnostic and as input for later CI construction.\nexport const PropensitySchema = z.object({\n candidates: z.array(z.object({ label: z.string(), text: z.string().optional() })).optional(),\n /**\n * Raw model confidence / logprobs / ensemble scores per candidate.\n * Diagnostic only; NOT a propensity unless the harness confirms it is\n * the exact sampling distribution used and passes it also as\n * `propensities`.\n */\n scores: z.array(z.number()).optional(),\n /**\n * Behavior-policy sampling distribution at selection time. Must sum\n * to 1.0 (within float tolerance) if present. Load-bearing for OPE\n * (Dudík, Langford & Li 2011 for per-turn / Jiang & Li 2016 for\n * trajectory). When omitted, OPE is not possible on this turn.\n */\n propensities: z.array(z.number()).optional(),\n selectedIndex: z.number().int().nonnegative().optional(),\n /**\n * Sampling-policy metadata: temperature, top_p, top_k, seed, sampler\n * name, ensemble weights. Required for reviewers to verify that\n * `propensities` is the actual behavior distribution.\n */\n selectionMeta: z.record(z.string(), z.unknown()).optional(),\n});\nexport type PropensityInput = z.infer<typeof PropensitySchema>;\n\n/**\n * Amendment S (2026-07-14) — post-guardrail propensity contract validator.\n *\n * Saito et al. 2021 Open Bandit Pipeline (arXiv:2008.07146); Farhadi\n * field notes on OPE identification. Enforces the four bug classes at\n * the SDK edge — if a customer wants the directive/OPE half, propensity\n * logging must survive these checks.\n *\n * Bug classes:\n * 1. Deterministic decoding (temp=0) with propensity: zero support ⇒ OPE\n * undefined for any counterfactual (positivity/overlap failure).\n * 2. Missing policy version metadata: importance-weighted estimators\n * require the logging policy be identifiable.\n * 3. propensities present without summing to ~1.0: not a probability\n * distribution.\n * 4. selectionMeta absent when propensities present: reviewers cannot\n * verify that propensities is the actual behavior distribution.\n *\n * Returns { ok: true } when valid, { ok: false, reason } when contract\n * violated. Fire-and-log at SDK edge; do NOT block ingest — customers\n * without OPE ambitions still ship descriptive-half records.\n */\nexport type PropensityContractResult =\n | { ok: true }\n | { ok: false, reason: string, class: 'zero_support' | 'missing_policy_version' | 'malformed_distribution' | 'missing_selection_meta' };\n\nexport function validatePropensityContract(p: PropensityInput | undefined): PropensityContractResult {\n if (!p) return { ok: true }; // customer opted out of propensity logging — fine\n if (!p.propensities || p.propensities.length === 0) return { ok: true }; // descriptive-half only\n\n // Bug class 1: zero-support (deterministic decoding)\n const temp = p.selectionMeta?.['temperature'] as number | undefined;\n if (typeof temp === 'number' && temp === 0) {\n return {\n ok: false,\n class: 'zero_support',\n reason: 'temperature=0 with propensities logged: deterministic decoding has zero support. OPE is undefined for any counterfactual. Set temperature > 0 or omit propensities.',\n };\n }\n\n // Bug class 2: missing policy version\n const policyVersion = p.selectionMeta?.['policy_version'] as string | undefined;\n if (!policyVersion) {\n return {\n ok: false,\n class: 'missing_policy_version',\n reason: 'propensities logged without selectionMeta.policy_version. IPS/DR require the logging policy be identifiable across replays.',\n };\n }\n\n // Bug class 3: distribution doesn't sum to 1\n const sum = p.propensities.reduce((a, b) => a + b, 0);\n if (Math.abs(sum - 1.0) > 0.02) {\n return {\n ok: false,\n class: 'malformed_distribution',\n reason: `propensities sum to ${sum.toFixed(4)}, expected ~1.0. Not a probability distribution; likely raw softmax(logits). A score is not a probability.`,\n };\n }\n\n // Bug class 4: selectionMeta present but missing sampler details\n if (!p.selectionMeta) {\n return {\n ok: false,\n class: 'missing_selection_meta',\n reason: 'propensities logged without selectionMeta. Reviewers cannot verify propensities is the actual behavior distribution.',\n };\n }\n\n return { ok: true };\n}\n\n// ── Transition signals (Day 1, per PROBE.md §2) ───────────────────────────\n// The right half of the record: human's response to the reply. Cheap\n// observations the SDK captures without waiting for outcome-hook wiring.\nexport const TransitionSchema = z.object({\n timeMs: z.number().int().nonnegative().optional(),\n lengthDelta: z.number().int().optional(),\n});\nexport type TransitionInput = z.infer<typeof TransitionSchema>;\n\n// ── User-side input (P1, per PLAN-2026-07-11-p1-p2) ──────────────────────\n// What the human said + interactivity signals about how they said it.\n// The single most-important missing capture pre-2026-07-11: without user\n// text as a first-class column, the record is agent-centric. See PROBE.md\n// Amendment G (sequence primacy over classification).\nexport const UserInputSchema = z.object({\n /** The user's message text. Presidio-scrubbed server-side before landing on `probe_user_reply_text`. */\n text: z.string().optional(),\n /** Milliseconds between agent response end and user's first keystroke. Client-side UI hook, optional. */\n firstKeystrokeMs: z.number().int().nonnegative().optional(),\n /** Backspace/edit count while typing this reply. Client-side UI hook, optional. */\n editCount: z.number().int().nonnegative().optional(),\n /** Did the user submit before the agent's response finished streaming? */\n interruptedStream: z.boolean().optional(),\n /** Did the user click stop on an agent streaming response mid-flight? */\n cancelledResponse: z.boolean().optional(),\n /** ISO timestamp when the user submitted this reply. */\n submittedAt: z.string().optional(),\n});\nexport type UserInput = z.infer<typeof UserInputSchema>;\n\n// ── Interactivity (P1) — agent-side reflection + stream state ────────────\nexport const InteractivitySchema = z.object({\n /** Milliseconds between the user's submit and the next agent LLM call. */\n agentReflectMs: z.number().int().nonnegative().optional(),\n /** Did the agent's response stream finish fully (finish_reason='stop')? */\n agentStreamCompleted: z.boolean().optional(),\n /** Multimodal events observed on this turn (image upload, voice snippet, file, etc.). */\n multimodalEvents: z\n .array(\n z.object({\n kind: z.string(),\n at: z.string().optional(),\n meta: z.record(z.string(), z.unknown()).optional(),\n }),\n )\n .optional(),\n});\nexport type InteractivityInput = z.infer<typeof InteractivitySchema>;\n\n// ── User outcome signals (Ch9-promoted, first-class per PLAN-2026-07-11) ─\nexport const UserOutcomeSchema = z.object({\n /**\n * Explicit \"that didn't sound like you\" flag attached at turn level.\n * DEPRECATED: prefer Probe.flagPersonaBreak(), which routes through the\n * flags ingest path and carries user attribution + a 'break' outcome\n * event. This turn-level boolean remains accepted for wire compat but\n * new integrations should not set it.\n */\n flaggedBreak: z.boolean().optional(),\n /** Rating widget value 1-5, customer-supplied. */\n explicitRating: z.number().int().min(1).max(5).optional(),\n /** Thumbs-up / thumbs-down widget value. */\n thumbs: z.enum(['up', 'down']).optional(),\n});\nexport type UserOutcomeInput = z.infer<typeof UserOutcomeSchema>;\n\n// ── SDK ingest input schema (mirrored by apps/ingest/routes/turns.ts) ─────\nexport const TurnInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /**\n * Customer's user identity (opaque string), forwarded by the SDK from\n * Probe.startSession() state on every turn. Distinct from\n * sessionExternalId, which keys the SESSION: the worker persists this on\n * sessions.external_user_id at first-turn session create (falling back to\n * null — never to sessionExternalId) so return-with-persona-consistency\n * and prior-session metrics read a real user identity.\n */\n externalUserId: z.string().min(1).optional(),\n turnIndex: z.number().int().nonnegative(),\n /**\n * Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the\n * worker: when present it becomes turns.started_at; when absent the\n * insert defaults to processing time. This is PROVENANCE, not\n * verification — intended for historical imports (ZVA telemetry, log\n * backfills, the datadump importer); live SDK traffic leaves it unset\n * (arrival time is the honest clock there).\n */\n startedAt: z.string().datetime().optional(),\n /**\n * Persona slug active for this turn. Customer-supplied (from SDK persona\n * resolution: turn override / session / init default). Optional; deployments\n * with a single registered persona can omit this and the ingest worker\n * backfills from the deployment default at write time.\n */\n personaSlug: z.string().min(1).optional(),\n /**\n * Signature-phrase matches computed at the SDK edge (per PROBE.md §2).\n * List of matched signature-phrase slugs the customer registered via\n * Probe.init({ persona: { signaturePhrases: [...] } }). Empty array or\n * omitted when no signatures matched or the deployment did not register any.\n */\n signaturePhraseMatches: z.array(z.string()).optional(),\n /**\n * Interpretive record fields passed through from a customer harness\n * (Oracle read hook wired). Omitted for deployments not running the harness;\n * server-side classifier workers populate situation_type and reaction_register\n * from the raw payload instead.\n */\n interpretive: InterpretiveRecordSchema.optional(),\n /**\n * Propensity + candidate set + scores. Harness-supplied only. Substrate\n * for OPE in Chapter 5 Dream. Nearly free if the harness already computes\n * candidates + ensemble scores; cannot be backfilled from the reply alone.\n */\n propensity: PropensitySchema.optional(),\n /**\n * Transition signals (human's response to the reply). Populated when the\n * SDK observes the next user turn; may arrive on a subsequent turn ingest.\n */\n transition: TransitionSchema.optional(),\n /**\n * User-side input for this turn: what the human actually said + UI-level\n * interactivity hints. Server-side Presidio scrubs text before it lands\n * on the canonical probe_user_reply_text column. See PLAN-2026-07-11.\n */\n userInput: UserInputSchema.optional(),\n /**\n * Interactivity between agent and user for this turn: agent reflect time,\n * stream completion, multimodal events.\n */\n interactivity: InteractivitySchema.optional(),\n /**\n * Explicit user outcome signals (Ch9-promoted): flagged break, rating,\n * thumbs. Landed as first-class columns per PLAN-2026-07-11.\n */\n userOutcome: UserOutcomeSchema.optional(),\n /**\n * RLDS episode-level provenance (Amendment R populater 2026-07-11).\n * SDK forwards these from Probe.startSession() on every turn payload so\n * the worker can persist them on the sessions row at first-turn create.\n * All optional. Powers Chapter 8e′ Card 3 version behavioral diff.\n */\n agentId: z.string().optional(),\n experimentId: z.string().optional(),\n environmentConfigHash: z.string().optional(),\n environmentConfigLabel: z.string().optional(),\n /**\n * Session context riding the FIRST turn of a session (there is no\n * session-start wire route; the session row is created lazily by the\n * worker on the first turn that arrives). The SDK forwards these once\n * per session from Probe.startSession() state; the worker persists them\n * on sessions.probe_session_opened_via / probe_session_client_context\n * at session find-or-create and ignores them on later turns.\n */\n openedVia: z.enum(['link', 'notification', 'resume', 'direct', 'share']).optional(),\n /**\n * Browser / device / locale / tz environmental context, customer-\n * configurable which fields to include. Customer metadata from\n * Probe.startSession({ metadata }) is merged in by the SDK under the\n * `metadata` key so it has a durable landing place.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n payload: z.record(z.string(), z.unknown()),\n});\nexport type TurnInput = z.infer<typeof TurnInputSchema>;\n\n// ── Session lifecycle schemas (P2, per PLAN-2026-07-11) ──────────────────\n// Note: there is deliberately no SessionStartSchema here. A session-start\n// wire contract was drafted 2026-07-11 but no route ever consumed it; the\n// worker creates sessions lazily on the first ingested turn instead, and\n// session context (openedVia, clientContext) rides TurnInputSchema on that\n// first turn. Deleted rather than kept as dead surface (e2e audit\n// 2026-07-13); resurrect from git history if a dedicated route ships.\n\nexport const SessionEndSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /** Why the session ended. */\n endedReason: z\n .enum(['natural', 'user_closed', 'timeout', 'agent_error', 'user_flagged', 'crashed'])\n .optional(),\n /** ISO timestamp of session end. */\n endedAt: z.string().optional(),\n});\nexport type SessionEndInput = z.infer<typeof SessionEndSchema>;\n\n// ── SDK flag input schema (persona-break flag from Probe.flagPersonaBreak) ─\n// Populates the `user_flagged_break` outcome column in Chapter 9c. Consumer AI\n// products wire this to their in-product \"that didn't sound like you\" UX.\nexport const FlagInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n flagType: z.enum(['persona_break']),\n note: z.string().optional(),\n /**\n * Turn index the flag refers to. Optional; if omitted, the flag is\n * attached to the most recent turn of the session.\n */\n turnIndex: z.number().int().nonnegative().optional(),\n});\nexport type FlagInput = z.infer<typeof FlagInputSchema>;\n\n// ── Outcome event ingest (Amendment I Method D, 2026-07-12) ──────────────\n// Customer- or harness-emitted event marking a hard outcome. Universal seed\n// kinds ship as fallback; open-vocab lets deployments register their own.\n// Worker-side detectors also emit events without an SDK call, so this\n// schema is only the *customer-driven* portion of the outcome corpus.\nexport const OUTCOME_EVENT_KINDS_SEED = [\n 'break',\n 'escalation',\n 'resolution',\n 'abandonment',\n 'register_drift_cross',\n 'thumbs_down',\n 'thumbs_up',\n 'rating_low',\n 'rating_high',\n] as const;\nexport type OutcomeEventKindSeed = (typeof OUTCOME_EVENT_KINDS_SEED)[number];\n\n// ── Synthetic demo-data marker (2026-07-13 demo arc) ─────────────────────\n// A deployment whose classifier_config carries `synthetic: true` holds\n// generated data (the demo corpus), never customer traffic. One marker,\n// many readers: the dashboard banner + \"(demo)\" filter labels, the\n// measurement sweep's provenance stamp on probe_measurement_aggregates\n// rows, and the worker's seed_demo idempotency guard all read THIS\n// predicate rather than re-deriving the convention. Writers: the demo\n// seeding module (apps/worker/src/demo-seed.ts) and the seeder CLI\n// (scripts/seed-demo-corpus.mjs), both via the same merge helper.\nexport function isSyntheticClassifierConfig(config: unknown): boolean {\n return (\n typeof config === 'object' &&\n config !== null &&\n (config as Record<string, unknown>)['synthetic'] === true\n );\n}\n\n/**\n * DEMO_AUTOSEED feature gate, default ON in code: any value except an\n * explicit '0' / 'false' enables demo auto-seeding. Read at enqueue time\n * (dashboard onboarding) and at consume time (worker seed_demo handler)\n * through this one predicate. Pure over an env bag for unit tests.\n * Documented in docs/DEPLOY.md.\n */\nexport function demoAutoseedEnabled(\n env: Record<string, string | undefined> = typeof process !== 'undefined' ? process.env : {},\n): boolean {\n const v = env['DEMO_AUTOSEED'];\n return v !== '0' && v !== 'false';\n}\n\n// ── Demo seeding job schemas (auto-provision arc, 2026-07-13) ─────────────\n// Rides the pending_redaction queue like flag / session_end / outcome_event:\n// onboarding enqueues `_kind: 'seed_demo'` on project creation (gated by\n// DEMO_AUTOSEED, default ON); the worker consumes it, builds the\n// deterministic corpus in-process, and enqueues the corpus payloads plus a\n// trailing `_kind: 'seed_demo_backdate'` row that moves session/turn\n// timestamps onto the corpus schedule once the corpus rows have drained.\n/** Corpus window anchor offset: startDate defaults to now minus this, so\n the ~6.4-day corpus sits fully inside trailing-7-day sweep windows. */\nexport const DEMO_SEED_WINDOW_OFFSET_MS = 6.5 * 24 * 60 * 60 * 1000;\n\nexport const SeedDemoJobSchema = z.object({\n /** Slug for the demo deployment; defaults to 'demo'. */\n deploymentSlug: z.string().min(1).optional(),\n /** PRNG seed; the corpus is byte-identical per (seed, startDate). */\n seed: z.number().int().optional(),\n /**\n * ISO anchor for the corpus window (sessions land in\n * [startDate, startDate + ~6.4d]). Enqueuers stamp now-6.5d so the\n * trailing-7-day sweeps see the corpus; the worker defaults the same\n * way when absent.\n */\n startDate: z.string().optional(),\n});\nexport type SeedDemoJobInput = z.infer<typeof SeedDemoJobSchema>;\n\n/** The in-product runner's job (2026-07-23): execution for one\n studio_run_requests row, riding the same pending_redaction _kind lane\n as seed_demo. The request row carries all parameters; the job only\n points at it. */\nexport const StudioRunJobSchema = z.object({\n requestId: z.string().uuid(),\n});\nexport type StudioRunJobInput = z.infer<typeof StudioRunJobSchema>;\n\nexport const SeedDemoBackdateSchema = z.object({\n deploymentSlug: z.string().min(1),\n /** Same (seed, startDate) the seeding job used — the plan is recomputed\n deterministically rather than serialized through the queue. */\n seed: z.number().int(),\n startDate: z.string(),\n});\nexport type SeedDemoBackdateInput = z.infer<typeof SeedDemoBackdateSchema>;\n\n// ── Environment event ingest (Arc D-rail, PLAN.md §4; 2026-07-19) ─────────\n// The generalized environment-envelope contract: coupled human↔environment\n// reaction records. `source_type` and `event` are FREE strings supplied by\n// the deployment — open vocabulary by construction (same discipline as\n// situation tags and outcome-event kinds). The instrument stores, attaches\n// by time, and never interprets; there is deliberately no seed list here.\nexport const EnvironmentEventInputSchema = z.object({\n /** Free-form channel label (e.g. a stimulus feed, a game state stream). Open vocabulary — NOT an enum. */\n source_type: z.string().min(1),\n /** Free-form event name. Open vocabulary — NOT an enum. */\n event: z.string().min(1),\n /** ISO timestamp of the event on the deployer's clock (see alignment). */\n at: z.string().datetime(),\n /** Optional detail payload (deployer-defined). */\n meta: z.record(z.string(), z.unknown()).optional(),\n sessionExternalId: z.string().min(1),\n deploymentSlug: z.string().min(1),\n /**\n * Optional reference to the causing turn. v1 resolves a turn index within\n * the same session (string-encoded integer); any other value is stored\n * verbatim on the event record without an outcome-corner link. The\n * instrument records the reference only — no causal inference.\n */\n causeProvenance: z.string().min(1).optional(),\n});\nexport type EnvironmentEventInput = z.infer<typeof EnvironmentEventInputSchema>;\n\n/**\n * Clock contract for a batch: whose clock produced the events' `at`, the\n * deployer's bound on skew against the instrument's clock, and the version\n * of the attach rule the deployer aligned to. Free-form strings — the\n * instrument stores the claim, it does not verify clocks.\n */\nexport const AlignmentProvenanceSchema = z.object({\n clock_source: z.string().min(1),\n skew_bound_ms: z.number().nonnegative().optional(),\n rule_version: z.string().min(1),\n});\nexport type AlignmentProvenance = z.infer<typeof AlignmentProvenanceSchema>;\n\nexport const EnvironmentEventsBatchSchema = z.object({\n /** Events are self-addressed: a batch may span sessions/deployments. */\n events: z.array(EnvironmentEventInputSchema).min(1).max(100),\n alignment: AlignmentProvenanceSchema,\n});\nexport type EnvironmentEventsBatch = z.infer<typeof EnvironmentEventsBatchSchema>;\n\n// ── Span ingest (sub-turn structure; 2026-07-22) ───────────────────────────\n// One span = one LLM call, one tool call, one framework step, or a custom\n// sub-turn unit inside a turn. This is the REMOTE capture lane for the\n// `spans` table (SDK → POST /v1/spans → pending_redaction `_kind: 'spans'`\n// → worker); the import lane (scripts/import-zva-corpus.mjs) writes the same\n// table directly as owner.\n//\n// Spans are self-addressed like environment events: a batch may span\n// sessions/deployments. The batch carries the same alignment provenance\n// contract (whose clock produced the caller-asserted startedAt values).\n//\n// PII RULE (2026-07-22, the never-bypassed rule): `attributes` MAY carry\n// content-bearing strings (KB chunk text, tool results — the retrieval\n// gap family reads them), because the worker scrubs EVERY string value\n// through the same Presidio pass as turn text before insert; a\n// passthrough result drops the value rather than storing it raw. Prefer\n// metadata where content adds nothing — scrubbed ≠ free. Size-capped\n// (16k JSON chars per span) so the lane cannot be used as blob storage.\nexport const SPAN_TYPES = ['llm_call', 'tool_call', 'framework_step', 'custom'] as const;\nexport type SpanType = (typeof SPAN_TYPES)[number];\n\nexport const SpanInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /**\n * Turn the span belongs to. Optional: when omitted the worker resolves the\n * session's latest turn at/under the span's startedAt (falling back to the\n * session's most recent turn when startedAt is also absent — the outcome\n * events' rule). A span whose turn cannot be resolved is SKIPPED by the\n * worker (logged, batch still processed): spans never land unattributed.\n */\n turnIndex: z.number().int().nonnegative().optional(),\n spanType: z.enum(SPAN_TYPES),\n /** Human/otel-style span name (tool name, model call label). */\n name: z.string().optional(),\n /**\n * Caller-asserted span start (ISO). OPTIONAL and honored like\n * TurnInput.startedAt: provenance, not verification — when absent the\n * worker stamps processing time.\n */\n startedAt: z.string().datetime().optional(),\n endedAt: z.string().datetime().optional(),\n durationMs: z.number().int().nonnegative().optional(),\n model: z.string().optional(),\n provider: z.string().optional(),\n tokensInput: z.number().int().nonnegative().optional(),\n tokensOutput: z.number().int().nonnegative().optional(),\n costUsd: z.number().nonnegative().optional(),\n error: z.string().optional(),\n /**\n * OpenInference / OpenTelemetry gen_ai.*-style attributes. String values\n * are Presidio-scrubbed by the worker before storage (see the PII rule\n * above). Capped at 16k JSON chars per span.\n */\n attributes: z\n .record(z.string(), z.unknown())\n .optional()\n .refine((v) => v === undefined || JSON.stringify(v).length <= 16_000, {\n message: 'attributes exceed 16k JSON chars — spans are telemetry, not blob storage',\n }),\n /**\n * Caller-local span id, unique within the batch. Exists only so sibling\n * spans can name this span as their parentSpanId; never stored (the DB\n * assigns the real uuid).\n */\n spanId: z.string().min(1).optional(),\n /**\n * Caller-local reference to another span's `spanId` IN THE SAME BATCH (NOT\n * a database uuid). The worker wires spans.parent_span_id when the parent\n * resolves within the batch, stores null otherwise.\n */\n parentSpanId: z.string().min(1).optional(),\n});\nexport type SpanInput = z.infer<typeof SpanInputSchema>;\n\nexport const SpansBatchSchema = z.object({\n /** Spans are self-addressed: a batch may span sessions/deployments. */\n spans: z.array(SpanInputSchema).min(1).max(50),\n alignment: AlignmentProvenanceSchema,\n});\nexport type SpansBatch = z.infer<typeof SpansBatchSchema>;\n\n// ── Measurement definitions (elicit tier, PLAN-2026-07-19) ─────────────────\n// The Configure authoring input for a deployer-owned elicit rubric (label\n// chips). One definition = family + name + version; the server assigns the\n// version (create → 1, edit → version+1 with superseded_by set — versions\n// are rows, never updates). Constraints that are load-bearing downstream:\n// · family/name are slugs — they key the definition and appear in the\n// label store's classifier key lineage;\n// · chips are 2–9 — the blind queue is keyboard-first (number keys 1–9),\n// so a rubric wider than 9 chips is unanswerable there;\n// · metric 'ordinal' requires ordinalScale to be exactly the values in\n// rank order (α's ordinal difference metric reads it);\n// · v1 elicit metrics are nominal/ordinal (score belongs to the judge tier).\nconst DEFINITION_SLUG = /^[a-z][a-z0-9_-]{0,63}$/;\nconst DEFINITION_VALUE = z.string().trim().min(1).max(64);\n\nexport const MeasurementDefinitionInputSchema = z\n .object({\n /** Measurement family the definition belongs to (e.g. 'voice-conformance'). */\n family: z.string().regex(DEFINITION_SLUG, 'family must be a lowercase slug (a-z, 0-9, _-).'),\n /** Slug within the family. family+name identifies the definition across versions. */\n name: z.string().regex(DEFINITION_SLUG, 'name must be a lowercase slug (a-z, 0-9, _-).'),\n /** The elicitation prompt — the queue row's plain-language question. */\n question: z.string().trim().min(1).max(280),\n /** Difference metric for α (Krippendorff). Elicit v1: nominal | ordinal. */\n metric: z.enum(['nominal', 'ordinal']),\n /** The chips (closed vocabulary the rater chooses from). */\n values: z\n .array(DEFINITION_VALUE)\n .min(2, 'A rubric needs at least two chips.')\n .max(9, 'The queue is keyboard-first — at most 9 chips.'),\n /** Rank order (lowest first) — required iff metric is 'ordinal'. */\n ordinalScale: z.array(DEFINITION_VALUE).min(2).max(9).optional(),\n })\n .refine((input) => new Set(input.values).size === input.values.length, {\n message: 'Chips must be unique.',\n path: ['values'],\n })\n .superRefine((input, ctx) => {\n if (input.metric === 'ordinal') {\n const scale = input.ordinalScale;\n if (!scale) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'ordinalScale is required when metric is ordinal.',\n path: ['ordinalScale'],\n });\n return;\n }\n const same =\n scale.length === input.values.length &&\n [...scale].sort().join('') === [...input.values].sort().join('');\n if (!same) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'ordinalScale must be exactly the chips in rank order (lowest first).',\n path: ['ordinalScale'],\n });\n }\n }\n });\nexport type MeasurementDefinitionInput = z.infer<typeof MeasurementDefinitionInputSchema>;\n\nexport const OutcomeEventInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /** Open-vocab kind label. Seeds above; customers may register any string. */\n kind: z.string().min(1),\n /** How was this event detected? Seed values below; customer sources allowed. */\n detectedBy: z\n .enum(['harness', 'sdk_flag', 'sdk_rating', 'sdk_thumbs', 'worker_detector', 'webhook', 'sdk_custom'])\n .or(z.string().min(1)),\n /** Optional turn index the event was caused by. Omitted → attaches to session's most recent turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Optional detail payload (customer-defined). */\n detail: z.record(z.string(), z.unknown()).optional(),\n /** ISO timestamp; defaults to server-side now. */\n firedAt: z.string().optional(),\n});\nexport type OutcomeEventInput = z.infer<typeof OutcomeEventInputSchema>;\nexport * from '@fieldwork/shared/effectiveness-gap';\n","/**\n * The Probe SDK main entry point.\n *\n * Usage:\n * import { Sight } from '@cultured-computer/sight';\n *\n * Probe.init({\n * apiKey: process.env.PROBE_API_KEY!,\n * deployment: 'support-agent',\n * persona: { slug: 'casey' },\n * });\n *\n * // Autocapture is now on for any subsequent OpenAI / Anthropic / etc. call.\n */\n\nimport { IngestClient } from './client';\nimport {\n ProbeConfigSchema,\n SessionStartSchema,\n FlagPersonaBreakSchema,\n OutcomeEventEmitSchema,\n} from './types';\nimport type {\n ProbeConfig,\n ProbeConfigInput,\n PersonaConfig,\n OutcomeHook,\n CapturedTurn,\n SessionStart,\n SessionEndInput,\n FlagPersonaBreakInput,\n OutcomeEventEmit,\n} from './types';\nimport { collectClientContext, type ClientContextIncludes } from './client-context';\nimport { boundedSessionSet } from './session-bounds';\nimport { hashEnvironmentConfig } from './hash';\nimport { registerAllInstrumentations, withSession as withSessionContext, detachOtelState } from './instrumentation';\n// Subpath import (not the classifier root index): only the signature-phrase\n// machinery ships in the published bundle. The root index drags in the\n// situation-type / dimension cue catalogs via top-level buildVocabulary()\n// calls that defeat treeshaking.\nimport {\n compileSignaturePhrases,\n matchSignaturePhrases,\n type SignaturePhrase,\n} from '@fieldwork/classifier/signature-phrase';\nimport {\n validatePropensityContract,\n EnvironmentEventInputSchema,\n EnvironmentEventsBatchSchema,\n AlignmentProvenanceSchema,\n SpanInputSchema,\n SpansBatchSchema,\n type PropensityInput,\n type EnvironmentEventInput,\n type AlignmentProvenance,\n type SpanInput,\n} from '@fieldwork/shared';\n\n// ── Singleton state ────────────────────────────────────────────────────────\n\ntype ProbeState = {\n config: ProbeConfig;\n client: IngestClient;\n persona: PersonaConfig | null;\n outcomeHook: OutcomeHook | null;\n sessions: Map<string, SessionState>;\n /**\n * Signature phrases compiled once per persona at init/identify time.\n * Keyed by persona slug so per-session persona switches use the right\n * matcher without recompiling.\n */\n signatureMatchers: Map<string, ReturnType<typeof compileSignaturePhrases>>;\n /**\n * Interaction signals (userInputStart/Edit/Submit, userThumbs/userRating)\n * that arrived BEFORE any session entry existed for their externalId.\n * Flushed into the session entry when it is created (startSession or\n * lazy-create at captureTurn). FIFO-capped at PRE_SESSION_BUFFER_MAX ids\n * so signals for sessions that never capture a turn cannot leak memory.\n */\n preSessionBuffer: Map<string, PreSessionSignals>;\n};\n\ntype PreSessionSignals = {\n pendingUserInput: SessionState['pendingUserInput'];\n pendingUserOutcome: SessionState['pendingUserOutcome'];\n lastUserSubmitAt: number | null;\n};\n\n/** FIFO cap on pre-session signal buffering (distinct session ids). */\nconst PRE_SESSION_BUFFER_MAX = 100;\n\n// Cap + bounded insert for the sessions map live in session-bounds.ts so\n// the OTel processor's lazy-create site shares the exact same cap (B2).\nexport { MAX_TRACKED_SESSIONS } from './session-bounds';\n\n/**\n * Default alignment provenance for single-event environment captures\n * (captureEnvironmentEvent without an explicit alignment argument): the\n * event's `at` rides the SDK host's clock, attached under the v1 rule\n * (next-turn dual-attach). Deployments with their own clock contract pass\n * explicit alignment via captureEnvironmentEvents.\n */\nconst DEFAULT_ENVIRONMENT_ALIGNMENT: AlignmentProvenance = {\n clock_source: 'sdk',\n rule_version: 'v1',\n};\n\n/**\n * Default alignment provenance for single-span captures (captureSpan without\n * an explicit alignment argument): the span's caller-asserted timestamps ride\n * the SDK host's clock. Deployments with their own clock contract (or\n * batches) pass explicit alignment via captureSpans.\n */\nconst DEFAULT_SPAN_ALIGNMENT: AlignmentProvenance = {\n clock_source: 'sdk',\n rule_version: 'v1',\n};\n\ntype SessionState = {\n externalId: string;\n /** Customer's user identity from startSession; forwarded on every turn. */\n externalUserId: string | null;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n metadata: Record<string, unknown> | null;\n openedVia: string | null;\n clientContext: Record<string, unknown> | null;\n // RLDS provenance.\n agentId: string | null;\n experimentId: string | null;\n environmentConfigHash: string | null;\n environmentConfigLabel: string | null;\n /**\n * Timestamp of the last captured agent turn. Used on the NEXT turn to\n * derive transition.timeMs (previous agent reply → this turn's user\n * submit) and firstKeystrokeMs (previous agent reply → typing start).\n */\n lastAgentTurnAt: number | null;\n /**\n * Timestamp of the last userInputSubmit. Used at captureTurn to derive\n * agentReflectMs (user submit → agent turn capture). transition.timeMs\n * derives from the per-turn pendingUserInput.submittedAt instead, which\n * resets on every capture, so stale submits are never reused for it.\n */\n lastUserSubmitAt: number | null;\n /**\n * True once openedVia/clientContext have been sent with a captured turn.\n * The worker persists session context at session find-or-create (first\n * turn that arrives), so the SDK forwards it exactly once.\n */\n sessionContextForwarded: boolean;\n /** Per-turn user input pending on the SDK edge (unified capture helper). */\n pendingUserInput: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount: number;\n submittedAt?: number;\n } | null;\n /** Per-turn user outcome pending on the SDK edge (thumbs / rating). */\n pendingUserOutcome: {\n thumbs?: 'up' | 'down';\n explicitRating?: number;\n } | null;\n};\n\nlet state: ProbeState | null = null;\n\n// ── Public API ─────────────────────────────────────────────────────────────\n\n\n/**\n * The fire-and-log validator (production-safety audit B3, 2026-07-22):\n * every PER-REQUEST public method validates with safeParse and, on invalid\n * input, warns once per call and DROPS — a throwing parse inside an async\n * method becomes an unhandledRejection in the documented fire-and-forget\n * contract, which can terminate the host process. Only init() throws\n * (boot-time contract, fail loud at integration time).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction validateOrDrop<S extends { safeParse: (input: unknown) => any }>(\n schema: S,\n input: unknown,\n method: string,\n): NonNullable<ReturnType<S['safeParse']>['data']> | null {\n const result = schema.safeParse(input);\n if (!result.success) {\n const issue = result.error?.issues?.[0];\n // eslint-disable-next-line no-console\n console.warn(\n `[sight] ${method}: invalid input dropped — ${issue ? `${issue.path?.join('.') || '(root)'}: ${issue.message}` : 'schema mismatch'}`,\n );\n return null;\n }\n return result.data;\n}\n\nexport class Probe {\n /**\n * Initialize the Probe SDK. Call once at process start. Subsequent calls are\n * no-ops with a warning; re-init requires a shutdown() first.\n */\n static init(config: ProbeConfigInput): void {\n if (state !== null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] already initialized; call shutdown() first');\n return;\n }\n\n const validated = ProbeConfigSchema.parse(config);\n const client = new IngestClient({\n apiKey: validated.apiKey,\n endpoint: validated.endpoint,\n debug: validated.debug,\n dashboardUrl: validated.dashboardUrl,\n });\n\n state = {\n config: validated,\n client,\n persona: validated.persona ?? null,\n outcomeHook: validated.outcomeHook ?? null,\n sessions: new Map(),\n signatureMatchers: new Map(),\n preSessionBuffer: new Map(),\n };\n\n if (validated.persona?.signaturePhrases) {\n state.signatureMatchers.set(\n validated.persona.slug,\n compileSignaturePhrases(validated.persona.signaturePhrases as SignaturePhrase[]),\n );\n }\n\n registerAllInstrumentations(state, (turn) => this.captureTurn(turn));\n }\n\n /**\n * Run a callback inside a session context. Every LLM call made inside `fn`\n * (through any instrumented library: OpenAI, Anthropic, LangChain, Vercel\n * AI SDK, etc.) is automatically tagged with `sessionId` and captured as\n * a turn on that session.\n *\n * Under the hood, this uses OTel Baggage propagation; the shared span\n * processor reads the session ID from baggage when each LLM span ends.\n */\n static async withSession<T>(sessionId: string, fn: () => T | Promise<T>): Promise<T> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] withSession called before init');\n return fn();\n }\n return withSessionContext(sessionId, fn);\n }\n\n /**\n * Identify the process-level default persona. Overwrites any previously-set\n * default. For per-session persona identification (multi-persona products),\n * use startSession({ externalId, persona }) instead.\n */\n static identifyPersona(persona: PersonaConfig): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] identifyPersona called before init');\n return;\n }\n state.persona = persona;\n if (persona.signaturePhrases) {\n state.signatureMatchers.set(\n persona.slug,\n compileSignaturePhrases(persona.signaturePhrases as SignaturePhrase[]),\n );\n }\n }\n\n /**\n * Start (or update) a session with an active persona.\n *\n * Single-persona deployments can skip this if the init-level default is\n * enough; the SDK will still create a session entry lazily on first turn.\n * Multi-persona products call this at conversation start so every turn in\n * the session inherits the selected persona.\n *\n * Idempotent: calling with the same externalId updates the entry.\n */\n static startSession(input: SessionStart): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] startSession called before init');\n return;\n }\n // Per-request path: invalid input warns and drops, never throws into\n // the host's conversation-start (audit B3; init alone keeps its throw —\n // a boot-time contract should fail loud at integration time).\n const validated = validateOrDrop(SessionStartSchema, input, 'startSession');\n if (validated === null) return;\n const existing = state.sessions.get(validated.externalId);\n const now = Date.now();\n const session: SessionState = {\n externalId: validated.externalId,\n externalUserId: validated.externalUserId ?? existing?.externalUserId ?? null,\n turnIndex: existing?.turnIndex ?? 0,\n startedAt: existing?.startedAt ?? now,\n personaSlug: validated.persona ?? existing?.personaSlug ?? state.persona?.slug ?? null,\n metadata: validated.metadata ?? existing?.metadata ?? null,\n openedVia: validated.openedVia ?? existing?.openedVia ?? null,\n clientContext: validated.clientContext ?? existing?.clientContext ?? null,\n agentId: validated.agentId ?? existing?.agentId ?? null,\n experimentId: validated.experimentId ?? existing?.experimentId ?? null,\n environmentConfigHash:\n validated.environmentConfigHash ?? existing?.environmentConfigHash ?? null,\n environmentConfigLabel:\n validated.environmentConfigLabel ?? existing?.environmentConfigLabel ?? null,\n lastAgentTurnAt: existing?.lastAgentTurnAt ?? null,\n lastUserSubmitAt: existing?.lastUserSubmitAt ?? null,\n sessionContextForwarded: existing?.sessionContextForwarded ?? false,\n pendingUserInput: existing?.pendingUserInput ?? null,\n pendingUserOutcome: existing?.pendingUserOutcome ?? null,\n };\n this.flushPreSessionSignals(validated.externalId, session);\n boundedSessionSet(state.sessions, validated.externalId, session);\n }\n\n /**\n * Move buffered pre-session interaction signals (recorded before any\n * session entry existed for this externalId) onto the session entry.\n * Session-held values win: buffered signals predate anything recorded\n * after the entry existed.\n */\n private static flushPreSessionSignals(externalId: string, session: SessionState): void {\n if (state === null) return;\n const buffered = state.preSessionBuffer.get(externalId);\n if (!buffered) return;\n state.preSessionBuffer.delete(externalId);\n session.pendingUserInput = session.pendingUserInput ?? buffered.pendingUserInput;\n session.pendingUserOutcome = session.pendingUserOutcome ?? buffered.pendingUserOutcome;\n session.lastUserSubmitAt = session.lastUserSubmitAt ?? buffered.lastUserSubmitAt;\n }\n\n /**\n * Get or create the pre-session signal buffer entry for an externalId.\n * FIFO-capped: when a new id would exceed PRE_SESSION_BUFFER_MAX, the\n * oldest id is dropped (Map preserves insertion order).\n */\n private static preSessionEntry(externalId: string): PreSessionSignals {\n // Callers check state !== null before calling.\n const buffer = state!.preSessionBuffer;\n const existing = buffer.get(externalId);\n if (existing) return existing;\n if (buffer.size >= PRE_SESSION_BUFFER_MAX) {\n const oldest = buffer.keys().next().value;\n if (oldest !== undefined) buffer.delete(oldest);\n }\n const entry: PreSessionSignals = {\n pendingUserInput: null,\n pendingUserOutcome: null,\n lastUserSubmitAt: null,\n };\n buffer.set(externalId, entry);\n return entry;\n }\n\n /**\n * Compute a stable SHA-256 hex hash of prompt/config text for use as\n * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —\n * pass the human-readable version alongside as `environmentConfigLabel`\n * for the diff table axis (a card keyed by a3f9c2… is unreadable).\n *\n * Ships as a helper because inconsistent hashing across restarts breaks\n * The version behavioral diff — every customer would\n * hash their own way and version-diff would become noise.\n *\n * The same hashing (src/hash.ts) backs the OTel processor's automatic\n * version stamping: when autocapture sees a system message and the\n * deployer set no environmentConfigHash, the session is stamped with\n * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit\n * startSession values always win over the auto stamp.\n */\n static async hashEnvironmentConfig(input: string): Promise<string> {\n return hashEnvironmentConfig(input);\n }\n\n /**\n * End a session and release its in-memory entry. Optional (sessions time out\n * eventually), but recommended for long-running processes with many distinct\n * conversations. If `input.endedReason` is provided the SDK sends an end\n * event to ingest so the worker records the reason server-side.\n *\n * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`\n * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`\n * and, when it returns a non-null OutcomeResult, lands it as an outcome\n * event (kind = result.outcome, detail carries type/value). This is the\n * ONLY place the SDK invokes the hook — there are no client-side timers,\n * so sessions that are never ended explicitly are swept server-side as\n * `timeout` and receive no hook-resolved outcome; land those via\n * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:\n * a throwing or rejecting hook never breaks endSession.\n */\n static async endSession(externalId: string | SessionEndInput): Promise<void> {\n if (state === null) return;\n const externalIdStr = typeof externalId === 'string' ? externalId : externalId.externalId;\n const endedReason = typeof externalId === 'string' ? undefined : externalId.endedReason;\n // The one-call outcome helper: an explicit outcome declared at close\n // lands as an outcome event before the hook path and the session end\n // (fire-and-log, same discipline as every capture call).\n const declared = typeof externalId === 'string' ? undefined : externalId.outcome;\n if (declared) {\n await this.emitOutcomeEvent({\n sessionExternalId: externalIdStr,\n kind: declared,\n detail: {\n declaredAt: 'endSession',\n ...(typeof externalId === 'object' && externalId.outcomeDetail\n ? externalId.outcomeDetail\n : {}),\n },\n });\n }\n // A DECLARED outcome wins: when the caller states the outcome at close,\n // the hook is skipped for this end — otherwise one endSession emits TWO\n // outcome events for the same close and every kind tally over-counts.\n // Hook-resolved outcomes remain the path for ends with no declaration.\n if (!declared && state.outcomeHook) {\n try {\n const result = await state.outcomeHook.resolve(externalIdStr);\n // Re-check state: a shutdown() during a slow resolve drops the send.\n if (result && state !== null) {\n await this.emitOutcomeEvent({\n sessionExternalId: externalIdStr,\n kind: result.outcome,\n detail: {\n type: result.type,\n value: result.value,\n resolvedBy: 'outcome_hook',\n },\n });\n }\n } catch (err: unknown) {\n // eslint-disable-next-line no-console\n console.warn(\n '[sight] outcome hook resolve failed:',\n err instanceof Error ? err.message : err,\n );\n }\n }\n if (state === null) return;\n if (endedReason) {\n await state.client\n .sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason })\n .catch((err: unknown) => {\n // eslint-disable-next-line no-console\n console.warn('[sight] sendSessionEnd failed:', err instanceof Error ? err.message : err);\n });\n }\n state.sessions.delete(externalIdStr);\n }\n\n // ── User-side helpers ──────────────────────────────────────────────────\n // These accumulate user-side signals during a turn; captureTurn folds the\n // accumulated state into TurnInput.userInput / userOutcome before send.\n // Signals that arrive before any session entry exists (typing starts\n // before startSession or the first LLM call) buffer per externalId and\n // flush into the session when it is created.\n\n /**\n * User started typing — records the first-keystroke timestamp for\n * probe_user_first_keystroke_ms derivation on captureTurn. Derivable\n * only once a previous agent turn exists; a pre-session typing start\n * buffers the pending-input entry without a firstKeystrokeMs value.\n */\n static userInputStart(externalId: string): void {\n if (state === null) return;\n const session = state.sessions.get(externalId);\n const target = session ?? this.preSessionEntry(externalId);\n const now = Date.now();\n const firstKeystrokeMs =\n session?.lastAgentTurnAt != null ? Math.max(0, now - session.lastAgentTurnAt) : undefined;\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n firstKeystrokeMs: target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs,\n };\n }\n\n /**\n * User pressed backspace / edited — increments edit_count for\n * probe_user_reply_edit_count.\n */\n static userInputEdit(externalId: string): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n editCount: (target.pendingUserInput?.editCount ?? 0) + 1,\n };\n }\n\n /**\n * User submitted their reply. Records the text (Presidio-scrubbed\n * server-side before landing on probe_user_reply_text) plus the submit\n * timestamp, which captureTurn uses to derive probe_agent_reflect_ms\n * (submit → next agent turn) and probe_transition_time_ms (previous\n * agent turn → submit).\n */\n static userInputSubmit(externalId: string, text: string): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n const now = Date.now();\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n text,\n submittedAt: now,\n };\n target.lastUserSubmitAt = now;\n }\n\n /** Attach a thumbs-up/down to the current turn. */\n static userThumbs(externalId: string, thumbs: 'up' | 'down'): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserOutcome = {\n ...(target.pendingUserOutcome ?? {}),\n thumbs,\n };\n }\n\n /** Attach an explicit 1-5 rating to the current turn. */\n static userRating(externalId: string, rating: number): void {\n if (state === null) return;\n if (rating < 1 || rating > 5 || !Number.isInteger(rating)) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserOutcome = {\n ...(target.pendingUserOutcome ?? {}),\n explicitRating: rating,\n };\n }\n\n /**\n * Helper: collect client context and pass it to startSession in one call.\n */\n static startSessionWithContext(\n input: SessionStart,\n includes?: ClientContextIncludes,\n ): void {\n this.startSession({\n ...input,\n clientContext: input.clientContext ?? collectClientContext(includes),\n });\n }\n\n /**\n * Register the outcome hook: declares the deployment's outcome type and\n * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked\n * by endSession() — explicit close is the only trigger; the SDK runs no\n * client-side timers. A non-null OutcomeResult lands as an outcome event\n * on the session. Sessions that are never ended explicitly are swept\n * server-side and never resolve through the hook; land those outcomes via\n * emitOutcomeEvent() from the place where the outcome becomes known\n * (webhook, CRM callback); it joins back by sessionExternalId.\n */\n static wireOutcomeHook(hook: OutcomeHook): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] wireOutcomeHook called before init');\n return;\n }\n state.outcomeHook = hook;\n }\n\n /**\n * Manually capture a turn. Instrumentation adapters call this internally;\n * exposed for advanced customers who want to bypass autocapture.\n *\n * Persona resolution order for the outgoing turn payload:\n * 1. turn.personaSlug (turn-level override)\n * 2. sessions[externalId].personaSlug (from startSession)\n * 3. state.persona.slug (init-level default)\n *\n * Signature-phrase matching runs at the SDK edge when the resolved persona\n * has signature phrases registered. The matched slug list is attached to\n * `turn.signaturePhraseMatches` before send.\n */\n static async captureTurn(turn: CapturedTurn): Promise<void> {\n if (state === null) {\n return;\n }\n if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {\n return;\n }\n // Never-break-the-host: `payload` is required by the TYPE, but a JS\n // caller (or an `any`-typed TS caller) can reach here without it — and\n // an unguarded property read would throw a TypeError INTO the host's\n // serving path (found by the 2026-07-22 production-safety smoke).\n // Normalize once; the type keeps guiding compiled callers.\n if (turn.payload === undefined || turn.payload === null) {\n turn = { ...turn, payload: {} };\n }\n\n // ── Post-guardrail propensity validator ──\n // If the payload includes propensity data (customer running an OPE-\n // bearing deployment), validate the contract per Saito 2021 OBP.\n // Log-and-strip on failure — descriptive-half records still ingest,\n // but the malformed propensity payload does not corrupt downstream\n // OPE. Do NOT block turn capture; the point is honest logging, not\n // customer-blocking.\n const propensity =\n turn.propensity ?? (turn.payload as { propensity?: PropensityInput }).propensity;\n let validPropensity: PropensityInput | undefined = propensity;\n if (propensity) {\n const contract = validatePropensityContract(propensity);\n if (!contract.ok) {\n // eslint-disable-next-line no-console\n console.warn(\n `[sight] propensity contract violation (${contract.class}): ${contract.reason}`,\n );\n // Strip malformed propensity from payload; keep the record.\n (turn.payload as { propensity?: PropensityInput }).propensity = undefined;\n validPropensity = undefined;\n }\n }\n\n const sessionPersona = state.sessions.get(turn.sessionExternalId)?.personaSlug ?? null;\n const resolvedPersona =\n turn.personaSlug ?? sessionPersona ?? state.persona?.slug ?? undefined;\n\n let signatureMatches = turn.signaturePhraseMatches;\n if (!signatureMatches && resolvedPersona) {\n // Contained (audit R4): a pathological persona regex must degrade to\n // \"no matches\", never reject a manual captureTurn into the host.\n try {\n const matcher = state.signatureMatchers.get(resolvedPersona);\n if (matcher && matcher.length > 0) {\n const text = this.extractTextForMatching(turn.payload);\n signatureMatches = text ? matchSignaturePhrases(text, matcher) : [];\n }\n } catch {\n signatureMatches = [];\n }\n }\n\n // Fold in the accumulated user-side state (from userInputSubmit /\n // userInputEdit / userInputStart / userThumbs / userRating helpers)\n // and derive interactivity signals from timestamps. Manual-capture\n // callers may reach here without startSession or the OTel processor\n // having created a session entry — create one lazily so pre-session\n // buffered signals and per-session timestamps have a home.\n let session = state.sessions.get(turn.sessionExternalId);\n if (!session) {\n session = {\n externalId: turn.sessionExternalId,\n externalUserId: null,\n turnIndex: turn.turnIndex + 1,\n startedAt: Date.now(),\n personaSlug: resolvedPersona ?? null,\n metadata: null,\n openedVia: null,\n clientContext: null,\n agentId: null,\n experimentId: null,\n environmentConfigHash: null,\n environmentConfigLabel: null,\n lastAgentTurnAt: null,\n lastUserSubmitAt: null,\n sessionContextForwarded: false,\n pendingUserInput: null,\n pendingUserOutcome: null,\n };\n boundedSessionSet(state.sessions, turn.sessionExternalId, session);\n }\n // Pre-session interaction signals (typing that started before the\n // session entry existed, including entries lazily created by the OTel\n // processor) flush here, on the turn that creates the session.\n this.flushPreSessionSignals(turn.sessionExternalId, session);\n\n let userInput: CapturedTurn['userInput'] = turn.userInput;\n let userOutcome: CapturedTurn['userOutcome'] = turn.userOutcome;\n let interactivity: CapturedTurn['interactivity'] = turn.interactivity;\n let transition: CapturedTurn['transition'] = turn.transition;\n if (session.pendingUserInput && !userInput) {\n const p = session.pendingUserInput;\n userInput = {\n text: p.text,\n firstKeystrokeMs: p.firstKeystrokeMs,\n editCount: p.editCount,\n submittedAt: p.submittedAt ? new Date(p.submittedAt).toISOString() : undefined,\n };\n }\n if (session.pendingUserOutcome && !userOutcome) {\n userOutcome = session.pendingUserOutcome;\n }\n // Agent reflect ms: time between user submit (session.lastUserSubmitAt)\n // and now (the moment we're capturing this new agent turn).\n if (!interactivity && session.lastUserSubmitAt) {\n interactivity = {\n agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt),\n };\n }\n // Transition time ms: gap between the previous agent turn's capture\n // and the user submit that led to THIS turn. Derivable only when both\n // timestamps exist: pendingUserInput.submittedAt is per-turn (reset on\n // every capture), so a submit from an earlier turn can never be\n // reused. Left unset otherwise — no guessing.\n const submittedAt = session.pendingUserInput?.submittedAt;\n if (\n !transition &&\n session.lastAgentTurnAt !== null &&\n submittedAt !== undefined &&\n submittedAt >= session.lastAgentTurnAt\n ) {\n transition = { timeMs: submittedAt - session.lastAgentTurnAt };\n }\n // Session context (openedVia / clientContext / metadata) rides the\n // first captured turn only; the worker persists it at session\n // find-or-create and ignores it on later turns. metadata merges into\n // clientContext under the `metadata` key so it lands on\n // sessions.probe_session_client_context.\n let openedVia: CapturedTurn['openedVia'];\n let clientContext: CapturedTurn['clientContext'];\n if (!session.sessionContextForwarded) {\n openedVia = (session.openedVia as CapturedTurn['openedVia']) ?? undefined;\n clientContext =\n session.clientContext || session.metadata\n ? {\n ...(session.clientContext ?? {}),\n ...(session.metadata ? { metadata: session.metadata } : {}),\n }\n : undefined;\n session.sessionContextForwarded = true;\n }\n // Reset per-turn pending state now that we've folded it.\n session.pendingUserInput = null;\n session.pendingUserOutcome = null;\n session.lastAgentTurnAt = Date.now();\n\n await state.client.sendTurn({\n ...turn,\n personaSlug: resolvedPersona,\n signaturePhraseMatches: signatureMatches,\n // User identity from the local session entry (Probe.startSession).\n // The worker persists it on sessions.external_user_id; never the\n // session key. Turn-level override wins for advanced callers.\n externalUserId: turn.externalUserId ?? session.externalUserId ?? undefined,\n userInput,\n userOutcome,\n interactivity,\n transition,\n openedVia,\n clientContext,\n // Hoist validated propensity to the top-level TurnInput field: the\n // worker projection reads input.propensity (not payload.propensity)\n // when landing read_candidates / read_propensities / selection_meta\n // columns (e2e audit 2026-07-13).\n propensity: validPropensity,\n // Forward RLDS provenance from the local session entry (populated\n // by Probe.startSession). Worker persists at first-turn session\n // create; nulls stay null.\n agentId: session.agentId ?? undefined,\n experimentId: session.experimentId ?? undefined,\n environmentConfigHash: session.environmentConfigHash ?? undefined,\n environmentConfigLabel: session.environmentConfigLabel ?? undefined,\n });\n }\n\n /**\n * Emit a custom outcome event on a session. Populates probe_outcome_events\n * with the customer-supplied `kind` string. Use for\n * customer-defined kinds like \"purchase_complete\", \"handoff_to_human\",\n * \"character_break_severe\". Universal seed kinds (break, escalation,\n * resolution, thumbs_*, rating_*) are also emitted by worker-side\n * detectors automatically — call this only when the customer has a\n * signal the worker cannot infer.\n */\n static async emitOutcomeEvent(input: OutcomeEventEmit): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] emitOutcomeEvent called before init');\n return;\n }\n const validated = validateOrDrop(OutcomeEventEmitSchema, input, 'emitOutcomeEvent');\n if (validated === null) return;\n await state.client.sendOutcomeEvent(state.config.deployment, validated);\n }\n\n /**\n * Capture one environment event against a session. The\n * envelope is generalized: `source_type` and `event` are free strings whose\n * meaning is defined per deployment — the instrument stores the event and\n * attaches it to the session's record by time (the next turn's state\n * corner, plus the causing turn's outcome corner when `causeProvenance`\n * names a turn index), and never interprets it. Fire-and-log, like\n * captureTurn: errors are debug-logged, never thrown.\n *\n * Alignment defaults to the SDK's own clock claim; deployments with a\n * stricter clock contract (or batches) should call\n * captureEnvironmentEvents with explicit alignment provenance.\n */\n static async captureEnvironmentEvent(\n event: EnvironmentEventInput,\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] captureEnvironmentEvent called before init');\n return;\n }\n const validated = validateOrDrop(EnvironmentEventInputSchema, event, 'captureEnvironmentEvent');\n if (validated === null) return;\n const align = alignment\n ? (validateOrDrop(AlignmentProvenanceSchema, alignment, 'captureEnvironmentEvent') ?? DEFAULT_ENVIRONMENT_ALIGNMENT)\n : DEFAULT_ENVIRONMENT_ALIGNMENT;\n await state.client.sendEnvironmentEvents({ events: [validated], alignment: align });\n }\n\n /**\n * Capture a batch of environment events with explicit alignment provenance\n * (clock_source, skew_bound_ms, rule_version). Batches are capped at 100\n * events and may span sessions — every event is self-addressed. Same\n * generalized envelope and fire-and-log discipline as the single-event\n * capture above.\n */\n static async captureEnvironmentEvents(\n events: EnvironmentEventInput[],\n alignment: AlignmentProvenance = DEFAULT_ENVIRONMENT_ALIGNMENT,\n ): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] captureEnvironmentEvents called before init');\n return;\n }\n const batch = validateOrDrop(EnvironmentEventsBatchSchema, { events, alignment }, 'captureEnvironmentEvents');\n if (batch === null) return;\n await state.client.sendEnvironmentEvents(batch);\n }\n\n /**\n * Capture one sub-turn span against a session: one LLM call, one tool\n * call, one framework step, or a custom unit inside a turn. The span lands\n * on the turn named by `turnIndex`, or — when omitted — on the session's\n * latest turn at/under the span's `startedAt` (most recent turn when\n * `startedAt` is also absent). A span whose turn cannot be resolved is\n * dropped server-side; spans never land unattributed. Fire-and-log, like\n * captureTurn: errors are debug-logged, never thrown.\n *\n * `attributes` are metadata only (tool names, argument shapes) — never\n * free-text conversation content. Alignment defaults to the SDK's own\n * clock claim; deployments with a stricter clock contract (or batches, or\n * parent references between spans) should call captureSpans.\n */\n static async captureSpan(span: SpanInput, alignment?: AlignmentProvenance): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] captureSpan called before init');\n return;\n }\n const validated = validateOrDrop(SpanInputSchema, span, 'captureSpan');\n if (validated === null) return;\n const align = alignment\n ? (validateOrDrop(AlignmentProvenanceSchema, alignment, 'captureSpan') ?? DEFAULT_SPAN_ALIGNMENT)\n : DEFAULT_SPAN_ALIGNMENT;\n await state.client.sendSpans({ spans: [validated], alignment: align });\n }\n\n /**\n * Capture a batch of spans with explicit alignment provenance\n * (clock_source, skew_bound_ms, rule_version). Batches are capped at 50\n * spans and may span sessions — every span is self-addressed. Parent\n * structure rides the batch: a span's `parentSpanId` names another span's\n * caller-local `spanId` within the same batch and is wired server-side\n * (unresolvable references land null). Same fire-and-log discipline as the\n * single-span capture above.\n */\n static async captureSpans(spans: SpanInput[], alignment?: AlignmentProvenance): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] captureSpans called before init');\n return;\n }\n const batch = validateOrDrop(SpansBatchSchema, { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT }, 'captureSpans');\n if (batch === null) return;\n await state.client.sendSpans(batch);\n }\n\n /**\n * Flag a persona break for a session. Wire this to the customer's in-product\n * \"that didn't sound like you\" UX. Populates the `user_flagged_break`\n * outcome column on the dashboard.\n *\n * If `turnIndex` is omitted, the flag attaches to the session's most\n * recent turn.\n */\n static async flagPersonaBreak(input: FlagPersonaBreakInput): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[sight] flagPersonaBreak called before init');\n return;\n }\n const validated = validateOrDrop(FlagPersonaBreakSchema, input, 'flagPersonaBreak');\n if (validated === null) return;\n await state.client.sendFlag(state.config.deployment, validated);\n }\n\n /**\n * Best-effort extraction of the response text from a captured turn's payload\n * for signature-phrase matching. Adapters populate `payload.response.text`\n * or `payload.text` by convention; this method looks for both.\n */\n private static extractTextForMatching(payload: Record<string, unknown>): string {\n const response = payload['response'];\n if (response && typeof response === 'object') {\n const responseText = (response as Record<string, unknown>)['text'];\n if (typeof responseText === 'string') return responseText;\n }\n if (typeof payload['text'] === 'string') return payload['text'] as string;\n return '';\n }\n\n /**\n * Shut down the SDK: discards the singleton state (sessions, pending\n * user-side signals, the pre-session buffer) so init() can be called\n * again. There is no send queue to flush — every capture awaits its own\n * HTTP send — and instrumentation stays registered for the life of the\n * process. Idempotent.\n */\n static async shutdown(): Promise<void> {\n if (state === null) {\n return;\n }\n // Drain in-flight sends first (bounded by the client's send timeout):\n // short-lived processes (serverless, CLI scripts) exit right after this,\n // and a send still on the wire at exit is lost. Each send is fire-and-\n // forget at capture time, so the drain is usually instant.\n const client = state.client;\n // Detach autocapture from this state (audit R1): the span processor\n // stays registered (OTel providers cannot remove processors) but stops\n // reading the dead state — post-shutdown LLM calls no longer grow an\n // orphaned sessions map, and a re-init rebinds cleanly.\n detachOtelState();\n state = null;\n await client.drainInFlight();\n }\n\n // ── Internal helpers ─────────────────────────────────────────────────────\n\n /** Package-internal: instrumentation adapters read this to build turns. */\n static _getState(): ProbeState | null {\n return state;\n }\n\n private static shouldSample(sessionId: string, turnIndex: number): boolean {\n if (state === null) return false;\n const rate = state.config.sampleRate;\n if (rate >= 1.0) return true;\n if (rate <= 0.0) return false;\n // Deterministic hash so a given (sessionId, turnIndex) always resolves identically.\n // FNV-1a 32-bit for portability across runtimes.\n const key = `${sessionId}:${turnIndex}`;\n let hash = 0x811c9dc5;\n for (let i = 0; i < key.length; i++) {\n hash ^= key.charCodeAt(i);\n hash = (hash * 0x01000193) >>> 0;\n }\n return hash / 0xffffffff < rate;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/types.ts","../src/client-context.ts","../src/session-bounds.ts","../src/hash.ts","../src/instrumentation/session-context.ts","../src/instrumentation/no-session.ts","../src/instrumentation/ai-dedupe.ts","../src/instrumentation/otel-processor.ts","../src/instrumentation/wrap-openai.ts","../src/instrumentation/vercel-ai.ts","../src/instrumentation/setup.ts","../src/instrumentation/openai.ts","../src/instrumentation/anthropic.ts","../src/instrumentation/langchain.ts","../src/instrumentation/langgraph.ts","../src/instrumentation/litellm.ts","../src/instrumentation/mercury.ts","../src/instrumentation/index.ts","../../classifier/src/signature-phrase.ts","../../shared/src/effectiveness-gap.ts","../../shared/src/index.ts","../src/probe.ts"],"names":["body","z","context","propagation","createContextKey","state","asString","asNumber","messageText","value","bound","warnedUnbound","buildPayload","emit","createRequire","trace","registered","instrumentation","SessionEndSchema","now"],"mappings":";;;;;;;;;;AAyBO,IAAM,qBAAA,GAAwB,2CAAA;AAQrC,IAAM,mBAAA,GAAsB,EAAA;AAO5B,IAAM,eAAA,GAAkB,IAAA;AAOxB,IAAM,YAAA,GAAe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AAA;AAC3B,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,UAAA;AAC1B,IAAA,IAAI,IAAA,IAAQ,GAAK,OAAO,IAAA;AACxB,IAAA,IAAI,IAAA,IAAQ,GAAK,OAAO,KAAA;AAGxB,IAAA,MAAM,GAAA,GAAM,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,SAAS,CAAA,CAAA;AACrC,IAAA,IAAI,IAAA,GAAO,UAAA;AACX,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,QAAQ,CAAA,EAAA,EAAK;AACnC,MAAA,IAAA,IAAQ,GAAA,CAAI,WAAW,CAAC,CAAA;AACxB,MAAA,IAAA,GAAQ,OAAO,QAAA,KAAgB,CAAA;AAAA,IACjC;AACA,IAAA,OAAO,OAAO,UAAA,GAAa,IAAA;AAAA,EAC7B;AACF","file":"index.cjs","sourcesContent":["/**\n * HTTP client for the Sight ingest API.\n *\n * Sends captured turns to POST /v1/turns with a Bearer token. Async, fire-and-log:\n * SDK never blocks the customer's LLM path on ingest. Rate-limited sends (429)\n * are retried exactly once after Retry-After; sustained limiting drops captures.\n */\n\nimport type { EnvironmentEventsBatch, SpansBatch } from '@fieldwork/shared';\nimport type {\n CapturedTurn,\n FlagPersonaBreakInput,\n OutcomeEventEmit,\n SessionEndInput,\n} from './types';\n\nexport type IngestClientOptions = {\n apiKey: string;\n endpoint: string;\n debug: boolean;\n /** Dashboard base URL for the one-time first-capture announcement. */\n dashboardUrl?: string;\n};\n\n/** Default dashboard base for the first-capture permalink. */\nexport const DEFAULT_DASHBOARD_URL = 'https://sight.cultured.computer/dashboard';\n\n/**\n * Cap on concurrently pending 429 retries. A counter, not a queue: once this\n * many retries are waiting on their Retry-After timers, further rate-limited\n * requests are dropped instead of scheduled. Bounds memory under sustained\n * limiting — the SDK sheds load rather than buffering it.\n */\nconst MAX_PENDING_RETRIES = 50;\n\n/**\n * Per-send timeout: a hung ingest connection must never leak sockets or\n * pending promises into the host. Generous: ingest answers in ~50ms; a\n * cold start in seconds.\n */\nconst SEND_TIMEOUT_MS = 15_000;\n\n/**\n * Cap on concurrently in-flight sends. Under ingest slowness (anything\n * short of a clean 429) the SDK sheds new sends past this ceiling instead\n * of accumulating fetches without bound inside the host.\n */\nconst MAX_INFLIGHT = 64;\n\n/**\n * Client-side turn-payload cap, mirroring the server's 1MB body limit: a\n * doomed oversized send is dropped LOUDLY here instead of serialized,\n * shipped, and rejected silently there (audit R2).\n */\nconst MAX_TURN_BODY_BYTES = 900_000;\n\nexport class IngestClient {\n private apiKey: string;\n private endpoint: string;\n private debug: boolean;\n private dashboardUrl: string;\n /**\n * First-trace permalink: the first\n * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,\n * then never again for the life of this client (one IngestClient per\n * process — one `init` per process; a restart prints once more, accepted).\n * Failed sends do not consume the announcement. Only sendTurn announces:\n * flags, outcome events, and session-end sends never trigger it (a flag\n * arriving before any turn is not a captured session).\n */\n private firstCaptureAnnounced = false;\n /**\n * Rate-limit (429) handling: the first 429 per process prints one stderr\n * warning (not debug-gated, same channel and lifetime as the first-capture\n * announce); subsequent 429s only debug-log. Each rate-limited request is\n * retried exactly once after Retry-After; pendingRetries counts retries\n * waiting on their timers so the cap can shed load.\n */\n private rateLimitAnnounced = false;\n private pendingRetries = 0;\n private inFlight = 0;\n private shedAnnounced = false;\n\n /**\n * Every network send goes through here: adds the per-send timeout and\n * the in-flight cap. At the cap, the send is SHED (thrown into the\n * caller's existing fire-and-log catch) rather than queued;\n * the first shed per process warns on stderr, the rest debug-log.\n */\n private async guardedFetch(url: string, init: RequestInit): Promise<Response> {\n if (this.inFlight >= MAX_INFLIGHT) {\n if (!this.shedAnnounced) {\n this.shedAnnounced = true;\n\n console.error(\n `[sight] ${MAX_INFLIGHT} sends already in flight — shedding new sends (ingest slow or unreachable; this warning prints once)`,\n );\n }\n throw new Error('in-flight cap reached — send shed');\n }\n this.inFlight++;\n try {\n return await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });\n } finally {\n this.inFlight--;\n }\n }\n\n /**\n * Await all in-flight sends (bounded). Called by Sight.shutdown() so\n * short-lived processes (serverless, CLI scripts) can actually exit after\n * it — the documented \"in-flight sends finish within 15s\" only holds while\n * the process lives. Polling is coarse on purpose: sends report through\n * guardedFetch's counter and scheduled retries, never awaited individually.\n * Retries beyond the drain budget remain best-effort, not durable delivery.\n */\n async drainInFlight(timeoutMs = SEND_TIMEOUT_MS): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while ((this.inFlight > 0 || this.pendingRetries > 0) && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 50));\n }\n }\n\n constructor(opts: IngestClientOptions) {\n this.apiKey = opts.apiKey;\n this.endpoint = opts.endpoint.replace(/\\/$/, '');\n this.debug = opts.debug;\n this.dashboardUrl = (opts.dashboardUrl ?? DEFAULT_DASHBOARD_URL).replace(/\\/$/, '');\n }\n\n /**\n * Send a turn to the ingest API. Fire-and-log: errors are logged but never\n * thrown. The customer's LLM path never blocks on capture.\n */\n async sendTurn(turn: CapturedTurn): Promise<void> {\n try {\n const body = JSON.stringify(turn);\n const bodyBytes = new TextEncoder().encode(body).byteLength;\n if (bodyBytes > MAX_TURN_BODY_BYTES) {\n // Loud drop beats a doomed 1MB+ POST the server rejects anyway.\n this.log(\n `[sight] turn dropped: payload ${bodyBytes} bytes exceeds the ${MAX_TURN_BODY_BYTES}-byte cap ` +\n `(session=${turn.sessionExternalId} turn=${turn.turnIndex}) — trim the payload you attach`,\n );\n return;\n }\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/turns`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body,\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n\n if (!response.ok) {\n this.log(`[sight] ingest failed status=${response.status}`);\n return;\n }\n\n // Announce the first successful capture exactly once per process.\n // Deliberately NOT gated on debug — this is the install-to-first-\n // value ritual, one line, permalink included. Stderr only, same\n // channel as log(). \"Captured\" means accepted at ingest (202,\n // pre-redaction); the permalink resolves by external id once the\n // worker projects the session (seconds later).\n if (!this.firstCaptureAnnounced) {\n this.firstCaptureAnnounced = true;\n\n console.error(\n `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`,\n );\n }\n\n if (this.debug) {\n const body = (await response.json()) as { status?: string; pendingId?: string };\n this.log(`[sight] ingest ok id=${body.pendingId ?? '?'}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.\n * Populates the `user_flagged_break` outcome column on the dashboard.\n */\n async sendFlag(deploymentSlug: string, flag: FlagPersonaBreakInput): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/flags`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: flag.sessionExternalId,\n flagType: 'persona_break',\n note: flag.note,\n turnIndex: flag.turnIndex,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n\n if (!response.ok) {\n this.log(`[sight] flag ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[sight] flag ingest ok session=${flag.sessionExternalId}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] flag ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a session-end event to the ingest API. Records why a session ended\n * on the session. Fire-and-log.\n */\n async sendSessionEnd(deploymentSlug: string, end: SessionEndInput): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/sessions/end`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: end.externalId,\n endedReason: end.endedReason,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[sight] session-end ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[sight] session-end ingest ok session=${end.externalId}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] session-end ingest error: ${msg}`);\n }\n }\n\n /**\n * Send an outcome event to the ingest API. Fire-and-log. Populates\n * the outcome-events store.\n */\n async sendOutcomeEvent(\n deploymentSlug: string,\n event: OutcomeEventEmit,\n ): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/outcome-events`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: event.sessionExternalId,\n kind: event.kind,\n detectedBy: 'sdk_custom',\n causingTurnIndex: event.causingTurnIndex,\n detail: event.detail,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[sight] outcome-event ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(\n `[sight] outcome-event ingest ok session=${event.sessionExternalId} kind=${event.kind}`,\n );\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] outcome-event ingest error: ${msg}`);\n }\n }\n\n /**\n * Send an environment-event batch to the ingest API. Fire-and-log, same as\n * sendTurn. The envelope is generalized: the worker attaches each event to\n * its session's record by time; meaning is per-deployment.\n */\n async sendEnvironmentEvents(batch: EnvironmentEventsBatch): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/environment-events`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(batch),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[sight] environment-events ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[sight] environment-events ingest ok events=${batch.events.length}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] environment-events ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a span batch to the ingest API. Fire-and-log, same as sendTurn.\n * Spans carry sub-turn structure (llm_call / tool_call / framework_step /\n * custom); the worker resolves each span's session/turn and wires in-batch\n * parent references.\n */\n async sendSpans(batch: SpansBatch): Promise<void> {\n try {\n const send = () =>\n this.guardedFetch(`${this.endpoint}/v1/spans`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(batch),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[sight] spans ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[sight] spans ingest ok spans=${batch.spans.length}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[sight] spans ingest error: ${msg}`);\n }\n }\n\n /**\n * Route a send response through the 429 retry policy. Non-429 responses\n * pass through untouched. A 429 is re-sent exactly once after Retry-After\n * seconds (default 1s when the header is missing or unparseable; clamped\n * to [1, 60]s); the retry's response is returned as-is, so a second 429 is\n * never retried again — callers log and drop it like any other failed\n * send. Returns null when the retry was dropped at the pending-retry cap.\n * The timer is unref'd (where supported) so a pending retry never holds\n * the process open.\n */\n private async retryIfRateLimited(\n response: Response,\n resend: () => Promise<Response>,\n ): Promise<Response | null> {\n if (response.status !== 429) return response;\n\n if (!this.rateLimitAnnounced) {\n this.rateLimitAnnounced = true;\n // Deliberately NOT gated on debug — sustained rate limiting is silent\n // data loss; the operator hears about it exactly once per process.\n // Stderr only, same channel as log().\n\n console.error(\n 'Sight: ingest rate limit (429) — retrying once per Retry-After; sustained limiting drops captures. See https://sight.cultured.computer/docs/sdk-reference#rate-limits',\n );\n } else {\n this.log('[sight] ingest rate limited (429), retrying once');\n }\n\n if (this.pendingRetries >= MAX_PENDING_RETRIES) {\n this.log('[sight] retry buffer full, dropped');\n return null;\n }\n\n const raw = response.headers.get('retry-after');\n const parsed = raw === null ? Number.NaN : Number(raw);\n const seconds = Number.isFinite(parsed) ? Math.min(Math.max(parsed, 1), 60) : 1;\n\n this.pendingRetries += 1;\n try {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, seconds * 1000);\n // unref is absent outside Node (browsers, some edge runtimes) —\n // skip silently there.\n timer.unref?.();\n });\n return await resend();\n } finally {\n this.pendingRetries -= 1;\n }\n }\n\n private log(msg: string): void {\n if (this.debug) {\n // stderr only; never leak to stdout\n\n console.error(msg);\n }\n }\n}\n","/**\n * Sight SDK (@cultured_computer/sight) shared types.\n */\n\nimport { z } from \"zod\";\nimport type { PropensityInput } from \"@fieldwork/shared\";\n\n// ── Configuration ──────────────────────────────────────────────────────────\n\n/**\n * Signature phrases the customer authors per persona for Day-1 voice\n * consistency measurement. The SDK edge computes matches\n * per turn (via @fieldwork/classifier signature-phrase) and includes the\n * matched slugs on the outgoing CapturedTurn.\n */\nexport const SignaturePhraseSchema = z.union([\n z.object({\n slug: z.string().min(1),\n phrase: z.string().min(1),\n description: z.string().optional(),\n }),\n z.object({\n slug: z.string().min(1),\n regex: z.string().min(1),\n flags: z.string().optional(),\n description: z.string().optional(),\n }),\n]);\nexport type SignaturePhraseInput = z.infer<typeof SignaturePhraseSchema>;\n\nexport const PersonaConfigSchema = z.object({\n /** Persona slug matching the deployment's registered persona. */\n slug: z.string().min(1),\n /**\n * RICE authorship artifact (Role, Identity, Communication, Engagement).\n * Either inline object or a path/URL to a JSON file loaded at init time.\n */\n rice: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),\n /**\n * Customer-authored signature phrases for this persona. Compiled once at\n * init and matched per turn at the SDK edge; matched slugs appear on the\n * outgoing turn as `signaturePhraseMatches`.\n */\n signaturePhrases: z.array(SignaturePhraseSchema).optional(),\n});\nexport type PersonaConfig = z.infer<typeof PersonaConfigSchema>;\n\nexport const OutcomeHookSchema = z.object({\n /** Type of outcome the deployment tracks. */\n type: z.enum([\"numeric\", \"categorical\", \"boolean\", \"duration\"]),\n /**\n * Callback that resolves the outcome for a completed session. Invoked by\n * Sight.endSession() with the session's externalId; a non-null result\n * lands as an outcome event on the session. Not invoked for sessions\n * swept server-side (no explicit endSession) — use emitOutcomeEvent()\n * for outcomes that become known out of band.\n */\n resolve: z.custom<(sessionId: string) => Promise<OutcomeResult | null>>(),\n});\nexport type OutcomeHook = z.infer<typeof OutcomeHookSchema>;\n\nexport type OutcomeResult = {\n outcome: string;\n type: \"numeric\" | \"categorical\" | \"boolean\" | \"duration\";\n value: string;\n};\n\nexport const ProbeConfigSchema = z.object({\n /** The project's API key (an ingest key from the dashboard). Required. */\n apiKey: z.string().min(1),\n /** Deployment slug: the configuration this traffic belongs to. Required. */\n deployment: z.string().min(1),\n /** Ingest endpoint. Defaults to the production ingest service,\n `https://fieldwork-ingest.fly.dev`. */\n endpoint: z.string().url().default(\"https://fieldwork-ingest.fly.dev\"),\n /**\n * Dashboard base URL used by the one-time first-capture announcement\n * (the stderr permalink printed after the first successful send).\n * Self-hosted or staging dashboards override it the same way `endpoint`\n * is overridden.\n */\n dashboardUrl: z\n .string()\n .url()\n .default(\"https://sight.cultured.computer/dashboard\"),\n /** Persona identification. Optional at init; can be set later via identifyPersona(). */\n persona: PersonaConfigSchema.optional(),\n /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */\n outcomeHook: OutcomeHookSchema.optional(),\n /**\n * Sample rate for autocapture. 1.0 = 100% of calls captured. Lower values\n * sample deterministically so a given (turnId) always resolves identically.\n */\n sampleRate: z.number().min(0).max(1).default(1.0),\n /**\n * Debug mode: log every captured turn to stderr with a prefix. Never logs\n * the Bearer token or PII.\n */\n debug: z.boolean().default(false),\n});\nexport type ProbeConfig = z.infer<typeof ProbeConfigSchema>;\n/**\n * The shape callers pass to Sight.init(). This is the schema's INPUT type, so\n * fields with a `.default()` (endpoint, sampleRate, debug) are optional here —\n * the defaults are applied by ProbeConfigSchema.parse() inside init(). Use this\n * for the init argument; `ProbeConfig` is the resolved (post-parse) type held\n * internally, where those fields are always present.\n */\nexport type ProbeConfigInput = z.input<typeof ProbeConfigSchema>;\n\n// ── Session context (customer identifies persona per session) ──────────────\n\nexport const SessionStartSchema = z.object({\n /** Customer's session identity (opaque string; used as the correlation key). */\n externalId: z.string().min(1),\n /**\n * Customer's USER identity (opaque string), distinct from externalId:\n * externalId keys the session; externalUserId ties sessions to a\n * returning user. Forwarded on every captured turn so the worker can\n * persist it on the session row — return-with-persona-consistency and\n * prior-session metrics require it. Optional; deployments that do not\n * identify users simply skip the user-level return metrics.\n */\n externalUserId: z.string().min(1).optional(),\n /**\n * Persona slug active for this session. Overrides the init-level default.\n * Required for multi-persona deployments; optional for single-persona\n * deployments where init already carries the persona.\n */\n persona: z.string().min(1).optional(),\n /**\n * How the user got into this session.\n * Retention semantics differ radically between a resume and a fresh\n * notification landing.\n */\n openedVia: z\n .enum([\"link\", \"notification\", \"resume\", \"direct\", \"share\"])\n .optional(),\n /**\n * Environmental context: browser / device / locale / tz. You choose\n * which fields to include. See the collectClientContext helper.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n /**\n * Optional customer metadata attached to the session. Forwarded with the\n * first captured turn merged into `clientContext` under the `metadata`\n * key, so it is stored with the session.\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n /**\n * RLDS episode-level provenance. Powers the version behavioral diff\n * on the dashboard. All optional.\n * agentId — model/policy version\n * experimentId — A/B arm or feature flag\n * environmentConfigHash — SHA of prompt/config file(s)\n * environmentConfigLabel — human-readable version label\n */\n agentId: z.string().optional(),\n experimentId: z.string().optional(),\n environmentConfigHash: z.string().optional(),\n environmentConfigLabel: z.string().optional(),\n});\nexport type SessionStart = z.infer<typeof SessionStartSchema>;\n\n/**\n * Session end input. Sent by Sight.endSession() so the worker records\n * why a session ended. `outcome` + `outcomeDetail` are the one-call\n * outcome helper: when the deployer knows the outcome at close (a\n * resolved ticket, an escalation, an abandonment), the SDK emits it as an\n * outcome event alongside the session end — it never rides the\n * session-end wire itself.\n */\nexport const SessionEndSchema = z.object({\n externalId: z.string().min(1),\n endedReason: z\n .enum([\n \"natural\",\n \"user_closed\",\n \"timeout\",\n \"agent_error\",\n \"user_flagged\",\n \"crashed\",\n ])\n .optional(),\n outcome: z.string().min(1).max(64).optional(),\n outcomeDetail: z.record(z.string(), z.unknown()).optional(),\n});\nexport type SessionEndInput = z.infer<typeof SessionEndSchema>;\n\n// ── Turn payload sent to ingest ────────────────────────────────────────────\n\nexport type CapturedTurn = {\n deploymentSlug: string;\n sessionExternalId: string;\n /**\n * The SDK payload contract version:\n * stamped on EVERY captured turn by this SDK; absent on payloads from\n * older SDKs (read as 'envelope-v0-unstamped' downstream). Data lineage\n * across SDK upgrades — additive-only, tolerated-absent.\n */\n envelopeVersion?: string;\n /**\n * Customer's user identity. Forwarded by captureTurn from the session\n * state (Sight.startSession({ externalUserId })); the worker persists it\n * on sessions.external_user_id at first-turn session create. Never\n * defaulted to sessionExternalId — that key identifies the session.\n */\n externalUserId?: string;\n turnIndex: number;\n /**\n * The identity of one logical turn: a UUID. The SDK stamps a fresh one\n * on every captured turn and re-sends the same value when it retries\n * the send, so the server can tell a re-sent turn (same turnId) from a\n * different turn that reached the same turnIndex (another process, a\n * restart). Supply your own only when you already hold a stable UUID for\n * the turn; a supplied value is sent as given.\n */\n turnId?: string;\n /**\n * Persona slug active for this turn. Resolved by the SDK from (in order):\n * turn-level override, session-level from startSession(), init-level default.\n */\n personaSlug?: string;\n /**\n * Signature-phrase slugs matched at the SDK edge (computed from the\n * customer's signaturePhrases config at init). Empty array or omitted when\n * no signatures matched or none were registered.\n */\n signaturePhraseMatches?: string[];\n /**\n * Interpretive record fields passed through from a customer harness\n * (read hook wired). Populated only if the customer\n * runs the Cultured Computer harness pattern; null for non-harness deployments.\n */\n interpretive?: {\n situationType?: string[];\n read?: string;\n lensChosen?: string;\n reactionRegister?: string;\n reactionNextTurn?: string;\n };\n /**\n * The person's input for this turn: the message that prompted this\n * reply, plus UI-level interactivity signals. The text is scrubbed of\n * personal data server-side before it is stored.\n */\n userInput?: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount?: number;\n interruptedStream?: boolean;\n cancelledResponse?: boolean;\n submittedAt?: string;\n };\n /**\n * Interactivity: agent reflect time, stream completion, multimodal events.\n */\n interactivity?: {\n agentReflectMs?: number;\n agentStreamCompleted?: boolean;\n multimodalEvents?: Array<{\n kind: string;\n at?: string;\n meta?: Record<string, unknown>;\n }>;\n };\n /**\n * User outcome signals:\n * flagged break, explicit rating (1-5), thumbs.\n *\n * `flaggedBreak` is DEPRECATED in favor of Sight.flagPersonaBreak(),\n * which carries user attribution and emits a 'break' outcome event;\n * the turn-level boolean remains accepted for wire compat only.\n */\n userOutcome?: {\n flaggedBreak?: boolean;\n explicitRating?: number;\n thumbs?: \"up\" | \"down\";\n };\n /**\n * Propensity + candidate set (harness-supplied).\n * Manual-capture callers put this in payload.propensity; captureTurn\n * validates the contract and hoists the valid object to\n * this top-level field so the worker projection lands it on the\n * read_candidates / read_propensities / selection_meta columns.\n */\n propensity?: PropensityInput;\n /**\n * Transition signals (the human's response to the previous reply).\n * Derived by captureTurn when the previous turn's capture time and this\n * turn's user submit time are both known; may also be supplied directly\n * by manual-capture callers.\n */\n transition?: {\n timeMs?: number;\n lengthDelta?: number;\n };\n /**\n * Session context forwarded on the FIRST captured turn of a session\n * (populated by captureTurn from Sight.startSession state; the worker\n * persists both at session find-or-create). Omitted on later turns.\n */\n openedVia?: \"link\" | \"notification\" | \"resume\" | \"direct\" | \"share\";\n clientContext?: Record<string, unknown>;\n /**\n * RLDS episode-level provenance. Forwarded from the session\n * state on every turn so downstream storage can attribute each turn to the\n * arm/version that produced it. Populated by startSession() from either\n * the customer-provided value or the init-time default; null when neither\n * is set.\n */\n agentId?: string;\n experimentId?: string;\n environmentConfigHash?: string;\n environmentConfigLabel?: string;\n payload: Record<string, unknown>;\n};\n\n/**\n * What `captureTurn` accepts: a captured turn whose `deploymentSlug` may be\n * omitted. When it is, the `deployment` given to `init` is used; an\n * explicit value wins.\n */\nexport type CaptureTurnInput = Omit<CapturedTurn, \"deploymentSlug\"> & {\n deploymentSlug?: string;\n};\n\n// ── Persona-break flag (from Sight.flagPersonaBreak) ──────────────────────\n\nexport const FlagPersonaBreakSchema = z.object({\n sessionExternalId: z.string().min(1),\n note: z.string().optional(),\n /** Turn index the flag refers to. Omit to attach to the session's latest turn. */\n turnIndex: z.number().int().nonnegative().optional(),\n});\nexport type FlagPersonaBreakInput = z.infer<typeof FlagPersonaBreakSchema>;\n\n// ── Outcome event ────────────────────────────────────────────────────────\n// Customer-emitted event marking a hard outcome (break/escalation/\n// resolution/etc.) durable on the probe_outcome_events table. Universal\n// seed kinds ship out of the box; deployments may register their own\n// arbitrary string kind.\nexport const OutcomeEventEmitSchema = z.object({\n sessionExternalId: z.string().min(1),\n kind: z.string().min(1),\n /** Optional turn index this event is caused by. Omit to attach to latest turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Optional detail payload (customer-defined). */\n detail: z.record(z.string(), z.unknown()).optional(),\n});\nexport type OutcomeEventEmit = z.infer<typeof OutcomeEventEmitSchema>;\n","/**\n * Client-context capture helper.\n *\n * At session start the SDK optionally collects browser/device/locale/tz\n * metadata to send as SessionStart.clientContext. Customers control which\n * fields land via the `includes` argument; the default is\n * conservative (locale + timezone + agent kind, no fingerprinting fields).\n *\n * Node-side calls receive process metadata; browser-side calls receive\n * navigator + Intl.DateTimeFormat. Never leaks PII; anything that could\n * fingerprint the user is opt-in.\n */\n\nexport type ClientContextIncludes = {\n /** window.navigator.userAgent — off by default (fingerprinting risk). */\n userAgent?: boolean;\n /** window.navigator.language / process.env.LANG — on by default. */\n locale?: boolean;\n /** Intl timezone / process TZ — on by default. */\n timezone?: boolean;\n /** window.screen dimensions — off by default (fingerprinting risk). */\n screen?: boolean;\n /** Node process metadata (platform, node version) — on by default in Node. */\n runtime?: boolean;\n /** Custom key/value pairs the customer wants to attach. */\n custom?: Record<string, string | number | boolean | null>;\n};\n\nconst DEFAULT_INCLUDES: ClientContextIncludes = {\n locale: true,\n timezone: true,\n runtime: true,\n};\n\n/** Collect client context under the current environment (Node or browser). */\nexport function collectClientContext(\n includes: ClientContextIncludes = DEFAULT_INCLUDES,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n\n // Browser detection without lib.dom.d.ts (SDK doesn't include DOM lib to\n // keep node-side bundles small). We accept the global as `unknown` and\n // narrow via runtime checks.\n const globalAny = globalThis as unknown as {\n window?: {\n navigator?: {\n userAgent?: string;\n language?: string;\n languages?: ReadonlyArray<string>;\n };\n screen?: { width?: number; height?: number };\n };\n };\n const win = globalAny.window;\n const isBrowser = typeof win !== 'undefined' && typeof win?.navigator !== 'undefined';\n\n if (isBrowser && win) {\n const nav = win.navigator;\n if (includes.userAgent) out['userAgent'] = nav?.userAgent;\n if (includes.locale) {\n out['locale'] = nav?.language;\n if (nav?.languages) out['languages'] = [...nav.languages];\n }\n if (includes.timezone) {\n try {\n out['timezone'] = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* ignore */\n }\n }\n if (includes.screen && win.screen) {\n out['screen'] = { width: win.screen.width, height: win.screen.height };\n }\n out['agent'] = 'browser';\n } else if (typeof process !== 'undefined' && typeof process.versions !== 'undefined') {\n if (includes.locale) {\n const lang = process.env['LANG'] || process.env['LC_ALL'] || null;\n if (lang) out['locale'] = lang.split('.')[0];\n }\n if (includes.timezone) {\n try {\n out['timezone'] = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* ignore */\n }\n }\n if (includes.runtime) {\n out['runtime'] = {\n platform: process.platform,\n node: process.versions.node,\n };\n }\n out['agent'] = 'node';\n }\n\n if (includes.custom) {\n for (const [k, v] of Object.entries(includes.custom)) out[k] = v;\n }\n\n return out;\n}\n","/**\n * Bounded insert for the tracked-sessions map (production-safety audit B2).\n *\n * endSession is optional, so on long-running high-cardinality servers the\n * sessions map would otherwise grow one entry per conversation forever. At\n * the cap the OLDEST entry (Map insertion order) is evicted — its later\n * turns still capture (lazy re-create), only edge-derived interactivity\n * context resets.\n *\n * Shared by probe.ts and instrumentation/otel-processor.ts so EVERY set\n * site on the sessions map goes through the same cap.\n */\n\nexport const MAX_TRACKED_SESSIONS = 5_000;\n\nexport function boundedSessionSet<T>(sessions: Map<string, T>, key: string, session: T): void {\n if (!sessions.has(key) && sessions.size >= MAX_TRACKED_SESSIONS) {\n const oldest = sessions.keys().next().value;\n if (oldest !== undefined) sessions.delete(oldest);\n }\n sessions.set(key, session);\n}\n","/**\n * Stable SHA-256 hex hashing for environment-config identity.\n *\n * Shared by the public Probe.hashEnvironmentConfig() helper and the OTel\n * processor's autocapture version-stamping (auto environmentConfigHash from\n * the request's system message). Lives in its own module so the processor\n * can import it without a circular dependency on probe.ts.\n *\n * Prefers WebCrypto (browser + modern Node); falls back to node:crypto via\n * dynamic import so the SDK stays browser-friendly for callers that never\n * touch this helper.\n */\nexport async function hashEnvironmentConfig(input: string): Promise<string> {\n if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle) {\n const bytes = new TextEncoder().encode(input);\n const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n }\n const { createHash } = await import('node:crypto');\n return createHash('sha256').update(input).digest('hex');\n}\n","/**\n * Session context propagation via OpenTelemetry Baggage.\n *\n * Adapters need to know which session an in-flight LLM call belongs to. We\n * propagate the session ID through OTel Baggage rather than a parallel\n * AsyncLocalStorage instance because:\n * 1. OTel already runs AsyncLocalStorageContextManager under the hood\n * (auto-registered by NodeTracerProvider on Node 20+); a parallel ALS\n * would duplicate the async-hooks graph.\n * 2. Baggage propagates automatically across HTTP boundaries via the\n * `baggage:` header. A parallel ALS would break at every service hop.\n *\n * Customer wraps their conversation:\n *\n * await Probe.withSession(sessionId, async () => {\n * await openai.chat.completions.create({ ... }); // captured\n * await anthropic.messages.create({ ... }); // also captured\n * });\n *\n * Under the hood: baggage entry `probe.session_id` is set, context is\n * activated for the callback, spans emitted inside read the baggage in\n * their onEnd handler.\n */\n\nimport { context, propagation } from '@opentelemetry/api';\n\nexport const SESSION_BAGGAGE_KEY = 'probe.session_id';\n\n// Register an AsyncLocalStorage-backed ContextManager idempotently on first\n// use. Without this, `context.with(...)` uses the default NoopContextManager\n// which does not propagate across async boundaries; baggage would be dropped\n// as soon as an `await` happened inside the callback.\nlet contextManagerRegistered = false;\nasync function ensureContextManager(): Promise<void> {\n if (contextManagerRegistered) return;\n contextManagerRegistered = true;\n try {\n const mod = await import('@opentelemetry/context-async-hooks');\n const cm = new mod.AsyncLocalStorageContextManager();\n cm.enable();\n context.setGlobalContextManager(cm);\n } catch {\n // The context-async-hooks package may not be installed; fall back to\n // NoopContextManager. Baggage will not propagate across async boundaries\n // in that case, which is a known limitation surfaced in debug mode by\n // the OTel processor.\n }\n}\n\n/**\n * Run `fn` inside a context where the given session ID is available to any\n * OTel span emitted (directly or transitively). Returns the fn's return value.\n */\nexport async function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n await ensureContextManager();\n const currentBaggage = propagation.getBaggage(context.active());\n const nextBaggage = (currentBaggage ?? propagation.createBaggage()).setEntry(\n SESSION_BAGGAGE_KEY,\n { value: sessionId },\n );\n const nextContext = propagation.setBaggage(context.active(), nextBaggage);\n return context.with(nextContext, fn);\n}\n\n/**\n * Read the current session ID from OTel Baggage, or undefined if no session\n * is active. Called by the OTel span processor when a captured span ends.\n */\nexport function getCurrentSessionId(): string | undefined {\n const baggage = propagation.getBaggage(context.active());\n return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;\n}\n","/**\n * The one warning for an LLM call seen outside any session scope.\n *\n * Autocapture (wrapOpenAI and the span processor) needs a session id to\n * attach a turn to. A call with none is skipped. The FIRST such skip in a\n * process prints one line on stderr whether or not `debug` is set, so a\n * missing Sight.withSession() is never a silent drop. Later skips log only\n * with `debug: true`, so a hot path that is deliberately unscoped does not\n * flood the host's logs.\n */\n\nlet warned = false;\n\n/** The line printed once per process. `source` names the call that was skipped. */\nexport function noSessionWarning(source: string): string {\n return (\n `[sight] call not captured (${source}): no session scope. ` +\n `Wrap LLM calls in Sight.withSession(id, fn) so they are recorded as turns. ` +\n `This warning prints once per process; later skips log only with debug: true.`\n );\n}\n\nexport function reportNoSessionSkip(source: string, debug: boolean): void {\n if (!warned) {\n warned = true;\n console.warn(noSessionWarning(source));\n return;\n }\n if (debug) {\n console.warn(\n `[sight] call not captured (${source}): no session scope; wrap it in Sight.withSession(id, fn).`,\n );\n }\n}\n\n/** Test hook: a new process starts unwarned. */\nexport function _resetNoSessionWarning(): void {\n warned = false;\n}\n","/**\n * One model call, one turn: the shared state that keeps the `ai` telemetry\n * integration (vercel-ai.ts) from double capturing with the other two\n * autocapture paths (the span processor and wrapOpenAI).\n *\n * Precedence: the `ai` integration wins. It sees the call the way the\n * application made it (the model reply as `ai` parsed it, the per-call\n * session id), so the other paths stand down for a call it handles.\n *\n * Two cases, two mechanisms:\n *\n * 1. A provider call made INSIDE an `ai` model call (a custom provider\n * that calls a wrapped or patched OpenAI client). The integration runs\n * the provider call in an OpenTelemetry context that carries a marker;\n * wrapOpenAI and the span processor skip a call or span that started\n * under the marker.\n *\n * 2. A span the AI SDK's own OpenTelemetry integration (`@ai-sdk/otel`)\n * emits for the same model call. That span is not started under the\n * marker, so it is matched on the provider response id, which both the\n * span (`gen_ai.response.id` / `ai.response.id`) and the integration's\n * model-call-end event carry.\n */\n\nimport { context, createContextKey, type Context } from '@opentelemetry/api';\n\nconst AI_MODEL_CALL_KEY = createContextKey('sight.ai_model_call');\n\n/** Run `fn` in a context marked as \"inside an `ai` model call Sight handles\". */\nexport function runInsideAiModelCall<T>(fn: () => T): T {\n return context.with(context.active().setValue(AI_MODEL_CALL_KEY, true), fn);\n}\n\n/** True when `ctx` (default: the active context) is inside such a call. */\nexport function isInsideAiModelCall(ctx: Context = context.active()): boolean {\n return ctx.getValue(AI_MODEL_CALL_KEY) === true;\n}\n\n// ── Response id claims (case 2) ───────────────────────────────────────────\n\n// Bounded FIFO. A claim is removed when the matching span arrives; with no\n// OpenTelemetry integration registered the claims just age out.\nconst MAX_CLAIMS = 1_000;\nconst claims = new Set<string>();\n\n/** Model calls the integration has seen start and not yet finish. */\nlet openCalls = 0;\n\nexport function noteAiModelCallOpened(): void {\n openCalls += 1;\n}\n\nexport function noteAiModelCallClosed(): void {\n if (openCalls > 0) openCalls -= 1;\n}\n\n/**\n * True while the integration has a model call in flight. The span processor\n * reads it to decide whether a span with an unclaimed response id may still\n * be claimed in the same event dispatch (the SDK's OpenTelemetry integration\n * can end its span before the Sight integration's callback runs).\n */\nexport function aiModelCallsOpen(): boolean {\n return openCalls > 0;\n}\n\n/** The integration will capture the model call that returned this response id. */\nexport function claimAiResponse(responseId: string): void {\n claims.add(responseId);\n if (claims.size > MAX_CLAIMS) claims.delete(claims.values().next().value!);\n}\n\n/** True, once, when the integration claimed this response id. */\nexport function takeAiResponseClaim(responseId: string): boolean {\n return claims.delete(responseId);\n}\n\n/** Test hook. */\nexport function _resetAiDedupe(): void {\n claims.clear();\n openCalls = 0;\n}\n","/**\n * The Sight span processor.\n *\n * Consumes spans emitted by the registered instrumentations (Traceloop's\n * OpenAI, Anthropic and LangChain adapters, or any OpenTelemetry GenAI\n * instrumentation the host registers). Maps the `gen_ai.*`\n * semantic-convention attributes onto a captured turn's payload and hands\n * it to the capture function.\n *\n * Attribute names follow the current GenAI semantic conventions as the\n * installed instrumentations emit them (@traceloop/instrumentation-* 0.27,\n * @opentelemetry/semantic-conventions 1.42). Every older name stays as a\n * fallback, read only when the current one is absent.\n *\n * Filter rule: only spans that are one model call become turns.\n * - captured: `gen_ai.operation.name` = chat | generate_content |\n * text_completion.\n * - captured: the model-call spans of the Vercel AI SDK 6 (`ai.operationId`\n * = ai.generateText.doGenerate | ai.streamText.doStream |\n * ai.generateObject.doGenerate | ai.streamObject.doStream). They carry\n * `ai.*` attributes and no `gen_ai.operation.name`. The outer\n * `ai.generateText` / `ai.streamText` / `ai.generateObject` span rolls\n * the model calls up and is never a turn.\n * - not captured: embeddings (no reply), invoke_agent / create_agent /\n * workflow wrappers (they roll up the child model calls and would\n * double count), execute_tool (read for the tool name only).\n * - legacy: a span with no operation name and\n * `traceloop.span.kind = \"agent\"` is still accepted.\n *\n * Deduplication suppresses repeated delivery of the same scoped span identity.\n * A shared trace is not proof that two instrumentation spans are the same call.\n *\n * A model call the `ai` telemetry integration captures is not captured a\n * second time from a span (see ai-dedupe.ts): a span started inside that\n * call is skipped, and so is a span carrying the response id the\n * integration claimed.\n */\n\nimport type { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-node';\nimport type { Context } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\nimport type { CapturedTurn } from '../types.js';\nimport { getCurrentSessionId } from './session-context.js';\nimport { reportNoSessionSkip } from './no-session.js';\nimport { boundedSessionSet } from '../session-bounds.js';\nimport { hashEnvironmentConfig } from '../hash.js';\nimport { isInsideAiModelCall, aiModelCallsOpen, takeAiResponseClaim } from './ai-dedupe.js';\n\n// Bounded FIFO retention, not a delivery guarantee across eviction or restart.\nconst MAX_DEDUP_SPANS = 10_000;\n\n// Bound on parents with buffered execute_tool children (see noteToolSpan).\nconst MAX_TOOL_PARENTS = 1_000;\n\n/**\n * What autocapture observed besides the turn itself. Passed alongside the\n * turn so the capture function can apply it under its own precedence rules\n * instead of the adapter overwriting explicit input.\n */\nexport type CaptureHints = {\n /**\n * The person's message that prompted this reply, read from the request\n * the model call carried. Used only when no explicit input text exists\n * for the turn (see Probe.captureTurn).\n */\n observedUserText?: string;\n};\n\nexport type CaptureFn = (turn: CapturedTurn, hints?: CaptureHints) => Promise<void>;\n\n// ── Attribute helpers ─────────────────────────────────────────────────────\n\ntype AttrValue = string | number | boolean | Array<string | number | boolean> | undefined;\n\nfunction attr(attrs: Record<string, AttrValue>, key: string): AttrValue {\n return attrs[key];\n}\n\nfunction asString(v: AttrValue): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction asNumber(v: AttrValue): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\nfunction asStringArray(v: AttrValue): string[] | undefined {\n return Array.isArray(v) && v.every((x) => typeof x === 'string')\n ? (v as string[])\n : undefined;\n}\n\n/** First attribute among `keys` that holds a number (current name first, then fallbacks). */\nfunction firstNumber(attrs: Record<string, AttrValue>, ...keys: string[]): number | undefined {\n for (const key of keys) {\n const n = asNumber(attrs[key]);\n if (n !== undefined) return n;\n }\n return undefined;\n}\n\n/** First attribute among `keys` that holds a non-empty string. */\nfunction firstString(attrs: Record<string, AttrValue>, ...keys: string[]): string | undefined {\n for (const key of keys) {\n const s = asString(attrs[key]);\n if (s !== undefined && s.length > 0) return s;\n }\n return undefined;\n}\n\n// ── Filter: is this span an LLM call worth capturing? ────────────────────\n\n/** Operations that are one model call producing a reply. */\nconst CAPTURED_OPERATIONS = new Set(['chat', 'generate_content', 'text_completion']);\n\n/**\n * Vercel AI SDK 6 model-call spans (observed on ai 6.0.300 with\n * `experimental_telemetry: { isEnabled: true }`, and on ai 7 with the\n * `LegacyOpenTelemetry` integration of `@ai-sdk/otel`). One per model round\n * trip; the parent span (`ai.generateText`, ...) is not in this set.\n */\nconst AI_SDK_MODEL_CALL_OPERATIONS = new Set([\n 'ai.generateText.doGenerate',\n 'ai.streamText.doStream',\n 'ai.generateObject.doGenerate',\n 'ai.streamObject.doStream',\n]);\n\nfunction isAiSdkModelCall(attrs: Record<string, AttrValue>): boolean {\n const op = asString(attrs['ai.operationId']);\n return op !== undefined && AI_SDK_MODEL_CALL_OPERATIONS.has(op);\n}\n\nfunction isLLMCall(attrs: Record<string, AttrValue>): boolean {\n const op = asString(attrs['gen_ai.operation.name']);\n if (op !== undefined) {\n // embeddings carry no reply; invoke_agent / create_agent / workflow are\n // wrappers around the model calls below them; execute_tool is a tool.\n return CAPTURED_OPERATIONS.has(op);\n }\n if (isAiSdkModelCall(attrs)) return true;\n // Legacy fallback (older Traceloop LangChain output, no operation name):\n // `traceloop.span.kind = agent` was accepted; 'workflow' / 'task' / 'tool'\n // were scaffolding. Current versions always set the operation name.\n return asString(attrs['traceloop.span.kind']) === 'agent';\n}\n\n// ── Vercel AI SDK invoke_agent rollup detection ──────────────────────────\n\nfunction isVercelAgentRollup(\n spanName: string,\n attrs: Record<string, AttrValue>,\n): boolean {\n // Older Vercel AI SDK versions emit invoke_agent {modelId} spans that roll\n // up token usage across the child chat spans. Both spans have\n // gen_ai.usage.*, so we skip the rollup and keep the child chat span(s).\n return spanName.startsWith('invoke_agent ') && attrs['ai.telemetry.functionId'] !== undefined;\n}\n\n// ── Provider tagging (Mercury-2 via OpenAI-compat) ───────────────────────\n\nfunction taggedProvider(attrs: Record<string, AttrValue>): string | undefined {\n // Current name first; `gen_ai.system` (deprecated) and `gen_ai.provider`\n // (never standard, read by earlier SDK versions) stay as fallbacks.\n const rawProvider = firstString(attrs, 'gen_ai.provider.name', 'gen_ai.system', 'gen_ai.provider');\n const model = asString(attrs['gen_ai.request.model']);\n // Mercury-2 goes through the OpenAI SDK with baseURL override; retag when\n // the model name signals Inception Labs.\n if (model?.toLowerCase().startsWith('mercury')) {\n return 'inception';\n }\n return rawProvider;\n}\n\n// ── Structured messages (gen_ai.input.messages / gen_ai.output.messages) ──\n// Current convention: a JSON string holding an array of\n// { role, parts: [{ type: 'text', content } | { type: 'tool_call', name, ... } | ...] }\n// plus `finish_reason` on output messages. Also tolerated: the array passed\n// through unserialized, `content` in place of `parts`, and `text` in place\n// of `content` on a part.\n\ntype Rec = Record<string, unknown>;\n\nfunction isRecord(v: unknown): v is Rec {\n return v !== null && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction isMessageLike(v: unknown): v is Rec {\n return isRecord(v) && ('parts' in v || 'content' in v || 'role' in v);\n}\n\n/** JSON string, array, or object in; parsed value out. Undefined when it is plain text. */\nfunction parseStructured(raw: unknown): unknown {\n if (typeof raw === 'string') {\n const t = raw.trimStart();\n if (!t.startsWith('[') && !t.startsWith('{')) return undefined;\n try {\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n }\n if (Array.isArray(raw)) {\n // Some SDKs set a string[] attribute with one JSON message per element.\n return raw.map((el) => {\n if (typeof el !== 'string') return el;\n try {\n return JSON.parse(el) as unknown;\n } catch {\n return el;\n }\n });\n }\n return raw;\n}\n\n/** The message objects in a parsed value, or undefined when it is not a message list. */\nfunction asMessageList(parsed: unknown): Rec[] | undefined {\n const list: unknown[] | undefined = Array.isArray(parsed)\n ? parsed\n : isMessageLike(parsed)\n ? [parsed]\n : undefined;\n if (!list) return undefined;\n const records = list.filter(isRecord);\n return records.some(isMessageLike) ? records : undefined;\n}\n\nfunction partsOf(message: Rec): unknown[] {\n const p = message['parts'] ?? message['content'];\n if (typeof p === 'string') return [{ type: 'text', content: p }];\n return Array.isArray(p) ? p : [];\n}\n\n/** Text of one part when it is a text part; undefined for every other part type. */\nfunction textOfPart(part: unknown, types: ReadonlySet<string>): string | undefined {\n if (typeof part === 'string') return part;\n if (!isRecord(part)) return undefined;\n const type = part['type'];\n if (type !== undefined && !(typeof type === 'string' && types.has(type))) return undefined;\n const text = part['content'] ?? part['text'];\n return typeof text === 'string' ? text : undefined;\n}\n\nconst TEXT_PART = new Set(['text']);\n// `input_text` is the OpenAI Responses request part; it appears when an\n// instrumentation serializes the raw request into one text part.\nconst INPUT_TEXT_PART = new Set(['text', 'input_text']);\nconst REFUSAL_PART = new Set(['refusal']);\n\nfunction joinText(parts: unknown[], types: ReadonlySet<string>, sep: string): string | undefined {\n const texts: string[] = [];\n for (const part of parts) {\n const t = textOfPart(part, types);\n if (t !== undefined && t.length > 0) texts.push(t);\n }\n return texts.length > 0 ? texts.join(sep) : undefined;\n}\n\ntype ParsedOutput = {\n /** True when the attribute held structured messages (so it is never stored verbatim). */\n structured: boolean;\n text: string | undefined;\n toolNames: string[];\n};\n\n/**\n * Plain assistant text and requested tool names from `gen_ai.output.messages`.\n * The first assistant message is the reply (instrumentations that record\n * several candidates put the chosen one first). Reasoning, blob and tool\n * parts never enter the text. A refusal part is the reply only when the\n * message has no text part.\n */\nfunction parseOutputMessages(raw: unknown): ParsedOutput {\n const messages = asMessageList(parseStructured(raw));\n if (!messages) return { structured: false, text: undefined, toolNames: [] };\n const reply = messages.find((m) => {\n const role = m['role'];\n return role !== 'user' && role !== 'system' && role !== 'developer' && role !== 'tool';\n });\n if (!reply) return { structured: true, text: undefined, toolNames: [] };\n const parts = partsOf(reply);\n const toolNames: string[] = [];\n for (const part of parts) {\n if (!isRecord(part)) continue;\n if (part['type'] === 'tool_call' || part['type'] === 'server_tool_call') {\n const name = part['name'];\n if (typeof name === 'string' && name.length > 0) toolNames.push(name);\n }\n }\n return {\n structured: true,\n text: joinText(parts, TEXT_PART, '') ?? joinText(parts, REFUSAL_PART, ''),\n toolNames,\n };\n}\n\n/**\n * The person's message that prompted this reply, from `gen_ai.input.messages`:\n * the last message of the request when that message is the person's and\n * carries text. System and developer messages after it are skipped. When the\n * request ends on anything else (a tool result, an assistant prefill), the\n * model call was not prompted by a new message from the person and nothing\n * is returned, so a tool loop does not repeat one message across its turns.\n */\nfunction userTextFromMessages(raw: unknown, nested = false): string | undefined {\n const messages = asMessageList(parseStructured(raw));\n if (!messages) return undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]!;\n const role = message['role'];\n if (role === 'system' || role === 'developer') continue;\n if (role !== 'user') return undefined;\n const text = joinText(partsOf(message), nested ? INPUT_TEXT_PART : TEXT_PART, '\\n');\n if (text === undefined) return undefined;\n return nested ? text : unwrapSerializedRequest(text);\n }\n return undefined;\n}\n\n/**\n * Some instrumentations put a whole serialized request into one text part\n * (Traceloop OpenAI Responses: JSON.stringify(input) when input is a list;\n * Traceloop LangChain: JSON.stringify(content) for multi-part content).\n * Read the person's text out of that structure; never return the blob.\n * Text that is not a serialized list of API objects is returned unchanged.\n */\nfunction unwrapSerializedRequest(text: string): string | undefined {\n const parsed = parseStructured(text);\n if (!Array.isArray(parsed) || !parsed.some(isRecord)) return text;\n if (parsed.some(isMessageLike)) return userTextFromMessages(parsed, true);\n // A list of content parts.\n return joinText(parsed, INPUT_TEXT_PART, '\\n');\n}\n\nfunction extractUserText(attrs: Record<string, AttrValue>): string | undefined {\n // `ai.prompt.messages` (Vercel AI SDK 6): the same shape with `content`\n // parts of `{ type: 'text', text }`, read only when the current name is absent.\n return (\n userTextFromMessages(attrs['gen_ai.input.messages']) ??\n (attrs['gen_ai.input.messages'] === undefined\n ? userTextFromMessages(attrs['ai.prompt.messages'])\n : undefined)\n );\n}\n\n/**\n * Tool names from `ai.response.toolCalls` (Vercel AI SDK 6): a JSON array of\n * `{ toolCallId, toolName, input }`. Names only; the input is never read.\n */\nfunction aiSdkToolNames(raw: AttrValue): string[] {\n if (typeof raw !== 'string') return [];\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n const names: string[] = [];\n for (const call of parsed) {\n const name = isRecord(call) ? call['toolName'] : undefined;\n if (typeof name === 'string' && name.length > 0) names.push(name);\n }\n return names;\n } catch {\n return [];\n }\n}\n\n/** Tool name from an execute_tool span, across the names instrumentations use. */\nfunction toolNameOfSpan(spanName: string, attrs: Record<string, AttrValue>): string | undefined {\n const named = firstString(attrs, 'gen_ai.tool.name', 'traceloop.entity.name');\n if (named) return named;\n // Convention: the span is named \"execute_tool {tool name}\".\n const prefix = 'execute_tool ';\n return spanName.startsWith(prefix) && spanName.length > prefix.length\n ? spanName.slice(prefix.length)\n : undefined;\n}\n\n// ── Span → CapturedTurn.payload builder ──────────────────────────────────\n\n/**\n * Whether the input-token count on the span already includes cached\n * tokens. Known only per instrumentation: the OpenAI one passes OpenAI's\n * usage through (cached tokens are part of the prompt count), the\n * Anthropic one passes Anthropic's (cache reads and writes are counted\n * apart from input). Any other emitter: unknown, undefined.\n */\nfunction cacheTokensInInput(span: ReadableSpan): boolean | undefined {\n const scope = (span as { instrumentationScope?: { name?: string } }).instrumentationScope?.name;\n if (scope === '@traceloop/instrumentation-openai') return true;\n if (scope === '@traceloop/instrumentation-anthropic') return false;\n return undefined;\n}\n\n/** A cost the span reports for the call. Absent or invalid: undefined, never 0. */\nfunction reportedCost(attrs: Record<string, AttrValue>): number | undefined {\n const cost = asNumber(attrs['gen_ai.usage.cost']);\n return cost !== undefined && Number.isFinite(cost) && cost >= 0 ? cost : undefined;\n}\n\nfunction buildPayload(span: ReadableSpan, childToolNames: string[] = []): Record<string, unknown> {\n const a = span.attributes as Record<string, AttrValue>;\n\n // Latency in ms from hrtime tuples.\n const start = span.startTime[0] * 1000 + span.startTime[1] / 1_000_000;\n const end = span.endTime[0] * 1000 + span.endTime[1] / 1_000_000;\n const latencyMs = Math.max(0, Math.round(end - start));\n\n // Reply text. `ai.response.text` (older Vercel AI SDK) wins when present.\n // Otherwise `gen_ai.output.messages` is parsed into plain assistant text;\n // a structured value is never stored as the reply. A value that is not\n // structured messages is plain text set by a custom instrumentation and\n // is kept verbatim (the earlier behavior).\n const rawOutput = (a as Record<string, unknown>)['gen_ai.output.messages'];\n const output = parseOutputMessages(rawOutput);\n // `ai.response.object` is the JSON text of a generateObject call.\n const responseText =\n asString(attr(a, 'ai.response.text')) ??\n (output.structured ? output.text : typeof rawOutput === 'string' ? rawOutput : undefined) ??\n asString(attr(a, 'ai.response.object'));\n\n // Tool calls. Names come from the reply's tool-call parts; when the reply\n // carries none, from execute_tool spans that ended as children of this\n // span; last, from the attribute names earlier SDK versions read.\n const aiToolNames = aiSdkToolNames(attr(a, 'ai.response.toolCalls'));\n const toolCallNames =\n output.toolNames.length > 0\n ? output.toolNames\n : aiToolNames.length > 0\n ? aiToolNames\n : childToolNames.length > 0\n ? childToolNames\n : asStringArray(attr(a, 'gen_ai.response.tool_names'));\n const toolCallsCount =\n toolCallNames?.length ?? asNumber(attr(a, 'gen_ai.response.tool_calls_count'));\n\n // Finish reason: gen_ai.response.finish_reasons is an array; take the first.\n const finishReasons = asStringArray(attr(a, 'gen_ai.response.finish_reasons'));\n const finishReason = finishReasons?.[0] ?? asString(attr(a, 'ai.response.finishReason'));\n\n // Time to the first streamed chunk (Vercel AI SDK 6 stream spans), in ms.\n // streamText spans name it ai.response.*, streamObject spans ai.stream.*.\n const firstChunkMs = firstNumber(a, 'ai.response.msToFirstChunk', 'ai.stream.msToFirstChunk');\n\n // Error: OTel spans use span.status.code = ERROR when the call failed.\n // Message is in span.status.message.\n const error =\n span.status.code === 2 // SpanStatusCode.ERROR\n ? span.status.message ?? 'error'\n : undefined;\n\n return {\n // Operational fields (the probe_* keys land on the turn's own columns).\n // The `ai.*` names are the Vercel AI SDK 6 ones, read last.\n probe_tokens_input: firstNumber(\n a,\n 'gen_ai.usage.input_tokens',\n 'gen_ai.usage.prompt_tokens',\n 'ai.usage.inputTokens',\n 'ai.usage.promptTokens',\n ),\n probe_tokens_output: firstNumber(\n a,\n 'gen_ai.usage.output_tokens',\n 'gen_ai.usage.completion_tokens',\n 'ai.usage.outputTokens',\n 'ai.usage.completionTokens',\n ),\n probe_latency_ms: latencyMs,\n // First-token time: only ai streams put a first-chunk time on the span;\n // the OpenAI, Anthropic and LangChain instrumentations do not.\n ...(firstChunkMs === undefined ? {} : { probe_first_token_ms: Math.max(0, Math.round(firstChunkMs)) }),\n probe_model: firstString(\n a,\n 'gen_ai.response.model',\n 'ai.response.model',\n 'gen_ai.request.model',\n 'ai.model.id',\n ),\n // The model as requested; the response names a dated snapshot.\n probe_request_model: firstString(a, 'gen_ai.request.model', 'ai.model.id'),\n probe_cost_usd: reportedCost(a),\n probe_provider: taggedProvider(a) ?? asString(attr(a, 'ai.model.provider')),\n probe_tool_calls: toolCallsCount,\n probe_tool_names: toolCallNames,\n probe_error: error,\n probe_finish_reason: finishReason,\n // Response text so the SDK edge signature-phrase matcher has something to\n // match against; personal data is scrubbed server-side before storage.\n response: responseText ? { text: responseText } : undefined,\n // Cache tokens. Current names are dotted (`cache_read.input_tokens`);\n // the underscore names are the earlier Traceloop ones, kept as fallback.\n probe_cache_read_input_tokens: firstNumber(\n a,\n 'gen_ai.usage.cache_read.input_tokens',\n 'gen_ai.usage.cache_read_input_tokens',\n 'ai.usage.inputTokenDetails.cacheReadTokens',\n 'ai.usage.cachedInputTokens',\n ),\n probe_cache_creation_input_tokens: firstNumber(\n a,\n 'gen_ai.usage.cache_creation.input_tokens',\n 'gen_ai.usage.cache_creation_input_tokens',\n 'ai.usage.inputTokenDetails.cacheWriteTokens',\n ),\n probe_cache_tokens_in_input: cacheTokensInInput(span),\n // Debug metadata (kept in payload, not projected to canonical columns).\n _otel: {\n spanName: span.name,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n operationName: firstString(a, 'gen_ai.operation.name', 'ai.operationId'),\n traceloopKind: asString(attr(a, 'traceloop.span.kind')),\n },\n };\n}\n\n// ── System-prompt extraction (auto version-hash, 2026-07-14) ─────────────\n// Autocapture sees the request messages on the span. When a system message\n// is present and the deployer never set an environmentConfigHash on the\n// session, the session state is stamped with the SHA-256 of the system\n// prompt text plus an 'auto:xxxxxxxx' label — closing the version-diff\n// measurement with zero deployer work. Explicit startSession values always\n// win; nothing is logged or announced.\n\ntype MinimalSession = {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n};\n\n/** Join the text content of one message shape into a single string. */\nfunction messageText(content: unknown): string | undefined {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n const parts: string[] = [];\n for (const part of content) {\n if (typeof part === 'string') {\n parts.push(part);\n } else if (part && typeof part === 'object') {\n const p = part as Record<string, unknown>;\n // OTel gen_ai parts use {type:'text', content}; Vercel AI SDK and\n // provider SDKs use {type:'text', text}.\n const text = p['content'] ?? p['text'];\n if (typeof text === 'string') parts.push(text);\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n return undefined;\n}\n\n/** First system-role message text from a JSON-encoded message array. */\nfunction systemFromMessagesJson(raw: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return undefined;\n for (const msg of parsed) {\n if (msg && typeof msg === 'object') {\n const m = msg as Record<string, unknown>;\n if (m['role'] === 'system') {\n const text = messageText(m['content'] ?? m['parts']);\n if (text) return text;\n }\n }\n }\n } catch {\n // Not JSON — nothing to extract.\n }\n return undefined;\n}\n\n/**\n * Best-effort extraction of the request's system message text from span\n * attributes, across the conventions the registered instrumentations emit:\n * - `gen_ai.system_instructions` (OTel gen_ai semconv; string or JSON parts)\n * - `gen_ai.input.messages` (OTel gen_ai semconv; JSON message array)\n * - `gen_ai.prompt.{n}.role` / `.content` (Traceloop indexed convention)\n * - `ai.prompt.messages` / `ai.prompt` (Vercel AI SDK telemetry)\n * Returns undefined when no system message is present.\n */\nfunction extractSystemPromptText(attrs: Record<string, AttrValue>): string | undefined {\n // OTel semconv: dedicated system-instructions attribute.\n const instructions = attrs['gen_ai.system_instructions'];\n if (typeof instructions === 'string' && instructions.length > 0) {\n // May be plain text or a JSON parts array.\n try {\n const parsed: unknown = JSON.parse(instructions);\n const text = messageText(parsed);\n if (text) return text;\n } catch {\n return instructions;\n }\n return instructions;\n }\n\n // OTel semconv: full input message array as JSON.\n const inputMessages = asString(attrs['gen_ai.input.messages']);\n if (inputMessages) {\n const text = systemFromMessagesJson(inputMessages);\n if (text) return text;\n }\n\n // Traceloop: indexed prompt attributes (gen_ai.prompt.0.role, .content).\n for (let i = 0; ; i++) {\n const role = attrs[`gen_ai.prompt.${i}.role`];\n if (role === undefined) break;\n if (role === 'system') {\n const content = asString(attrs[`gen_ai.prompt.${i}.content`]);\n if (content) return content;\n }\n }\n\n // Vercel AI SDK: ai.prompt.messages (JSON CoreMessage array).\n const aiMessages = asString(attrs['ai.prompt.messages']);\n if (aiMessages) {\n const text = systemFromMessagesJson(aiMessages);\n if (text) return text;\n }\n\n // Vercel AI SDK: ai.prompt ({system, prompt/messages} as JSON).\n const aiPrompt = asString(attrs['ai.prompt']);\n if (aiPrompt) {\n try {\n const parsed: unknown = JSON.parse(aiPrompt);\n if (parsed && typeof parsed === 'object') {\n const system = (parsed as Record<string, unknown>)['system'];\n if (typeof system === 'string' && system.length > 0) return system;\n }\n } catch {\n // Not JSON — nothing to extract.\n }\n }\n\n return undefined;\n}\n\n/**\n * Stamp the session with the system prompt's hash when the deployer set no\n * environmentConfigHash. Awaited by onEnd BEFORE the capture is sent, so\n * captureTurn forwards the stamped values on this same turn. Re-checks\n * after the async hash so a concurrent explicit startSession always wins.\n */\nasync function maybeAutoStampEnvironmentConfig(\n session: MinimalSession,\n attrs: Record<string, AttrValue>,\n): Promise<void> {\n await autoStampFromSystemText(session, extractSystemPromptText(attrs));\n}\n\n/**\n * The guarded stamp itself, shared with the instance-wrapping adapter\n * (wrap-openai.ts), which extracts system text from request params rather\n * than span attributes but must stamp under the exact same rules.\n */\nexport async function autoStampFromSystemText(\n session: MinimalSession,\n systemText: string | undefined,\n): Promise<void> {\n if (session.environmentConfigHash != null) return; // explicit or already stamped\n if (!systemText) return;\n const hash = await hashEnvironmentConfig(systemText);\n if (session.environmentConfigHash != null) return; // raced with startSession\n session.environmentConfigHash = hash;\n session.environmentConfigLabel = `auto:${hash.slice(0, 8)}`;\n}\n\n// ── Turn index allocation ─────────────────────────────────────────────────\n// Sessions live in Probe singleton state as Map<externalId, SessionState>.\n// Each captured turn increments SessionState.turnIndex atomically (Node is\n// single-threaded so ++ is atomic).\n\ntype MinimalProbeState = {\n config: { deployment: string; debug: boolean };\n persona: { slug: string } | null;\n sessions: Map<string, MinimalSession>;\n signatureMatchers: Map<string, unknown>;\n};\n\n/** Shared with wrap-openai.ts so both capture paths bind the same state shape. */\nexport type ProcessorProbeState = MinimalProbeState;\n\nexport function resolveSessionAndTurn(\n state: MinimalProbeState,\n sessionId: string,\n): { session: MinimalSession; sessionExternalId: string; turnIndex: number; personaSlug: string | null } {\n let session = state.sessions.get(sessionId);\n if (!session) {\n session = {\n externalId: sessionId,\n turnIndex: 0,\n startedAt: Date.now(),\n personaSlug: state.persona?.slug ?? null,\n environmentConfigHash: null,\n environmentConfigLabel: null,\n };\n // Bounded insert (audit B2): the lazy-create path shares the same cap\n // as probe.ts — autocapture without endSession must not grow the map\n // one entry per conversation forever.\n boundedSessionSet(state.sessions, sessionId, session);\n }\n const turnIndex = session.turnIndex;\n session.turnIndex += 1;\n return {\n session,\n sessionExternalId: sessionId,\n turnIndex,\n personaSlug: session.personaSlug ?? state.persona?.slug ?? null,\n };\n}\n\n// ── The processor ─────────────────────────────────────────────────────────\n\nexport class ProbeSpanProcessor implements SpanProcessor {\n private readonly seenSpans = new Set<string>();\n\n /**\n * Tool names from execute_tool spans, keyed by \"traceId:parentSpanId\".\n * A child span ends before its parent, so when the model-call span that\n * owns these tools ends, its tool names are already here.\n */\n private readonly toolChildren = new Map<string, string[]>();\n\n constructor(\n private state: MinimalProbeState | null,\n private captureFn: CaptureFn,\n ) {}\n\n /** Remember an execute_tool span's tool name under its parent span. */\n private noteToolSpan(span: ReadableSpan, a: Record<string, AttrValue>): void {\n const name = toolNameOfSpan(span.name, a);\n if (!name) return;\n const parent = span as unknown as {\n parentSpanContext?: { spanId?: string };\n parentSpanId?: string;\n };\n const parentSpanId = parent.parentSpanContext?.spanId ?? parent.parentSpanId;\n if (!parentSpanId) return;\n const key = `${span.spanContext().traceId}:${parentSpanId}`;\n const names = this.toolChildren.get(key);\n if (names) {\n names.push(name);\n return;\n }\n if (this.toolChildren.size >= MAX_TOOL_PARENTS) {\n this.toolChildren.delete(this.toolChildren.keys().next().value!);\n }\n this.toolChildren.set(key, [name]);\n }\n\n private takeToolChildren(span: ReadableSpan): string[] {\n const { traceId, spanId } = span.spanContext();\n const key = `${traceId}:${spanId}`;\n const names = this.toolChildren.get(key);\n if (!names) return [];\n this.toolChildren.delete(key);\n return names;\n }\n\n /**\n * Re-point the processor at a new Probe state (or null after shutdown).\n * A registered span processor cannot be removed from a provider, so\n * re-init REBINDS instead of orphaning: without this, autocapture after\n * shutdown()/re-init kept mutating the dead state's sessions map and\n * stamping the old deployment slug (production-safety audit R1).\n */\n rebind(state: MinimalProbeState | null, captureFn?: CaptureFn): void {\n if (this.state !== state) {\n this.seenSpans.clear();\n this.toolChildren.clear();\n }\n this.state = state;\n if (captureFn) this.captureFn = captureFn;\n }\n\n /**\n * Spans started inside an `ai` model call that the Sight `ai` integration\n * captures (a provider that calls an instrumented client). Never turns.\n */\n private readonly insideAiCall = new WeakSet<object>();\n\n onStart(span: Span, parentContext: Context): void {\n // All mapping happens in onEnd once the attributes are populated. The\n // one thing only knowable here is the context the span started in.\n try {\n if (isInsideAiModelCall(parentContext)) this.insideAiCall.add(span);\n } catch {\n // Never break the host's tracing.\n }\n }\n\n onEnd(span: ReadableSpan): void {\n try {\n // Detached (post-shutdown, pre-re-init): drop silently — the host's\n // spans flow on; Sight is simply not listening.\n if (this.state === null) return;\n // Local binding: the state at span-end time. The async capture below\n // must use THIS state even if a rebind happens mid-flight.\n const state = this.state;\n const a = span.attributes as Record<string, AttrValue>;\n if (isVercelAgentRollup(span.name, a)) return;\n if (asString(a['gen_ai.operation.name']) === 'execute_tool') {\n // Never a turn; its name is read when the parent model call ends.\n this.noteToolSpan(span, a);\n return;\n }\n if (!isLLMCall(a)) return;\n\n // One model call, one turn: the `ai` integration captures this call.\n if (this.insideAiCall.has(span)) {\n this.takeToolChildren(span);\n return;\n }\n\n // Session precedence: the explicit Sight.withSession() scope first.\n // With no scope, a span that carries `gen_ai.conversation.id` (the\n // GenAI convention's own conversation key) is attached to that id;\n // a Vercel AI SDK 6 span, to the session id in the call's\n // `experimental_telemetry.metadata` (sightSessionId, then sessionId).\n const sessionId =\n getCurrentSessionId() ||\n firstString(\n a,\n 'gen_ai.conversation.id',\n 'ai.telemetry.metadata.sightSessionId',\n 'ai.telemetry.metadata.sessionId',\n );\n\n // The span the AI SDK's own OpenTelemetry integration emits for a\n // call the Sight `ai` integration also sees: both carry the provider\n // response id. Claimed already: skip. Not claimed while the\n // integration has a model call in flight: its callback for this same\n // event may run right after this one, so decide one microtask later.\n const responseId = firstString(a, 'gen_ai.response.id', 'ai.response.id');\n if (responseId !== undefined) {\n if (takeAiResponseClaim(responseId)) {\n this.takeToolChildren(span);\n return;\n }\n if (aiModelCallsOpen()) {\n void Promise.resolve().then(() => {\n try {\n if (this.state !== state) return;\n if (takeAiResponseClaim(responseId)) {\n this.takeToolChildren(span);\n return;\n }\n this.captureSpan(state, span, a, sessionId);\n } catch (err) {\n if (state.config.debug) {\n console.error(\n `[sight] span processor error: ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n });\n return;\n }\n }\n\n this.captureSpan(state, span, a, sessionId);\n } catch (err) {\n if (this.state?.config.debug) {\n\n console.error(\n `[sight] span processor error: ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n /** The capture itself, once the span is known to be this call's only turn. */\n private captureSpan(\n state: MinimalProbeState,\n span: ReadableSpan,\n a: Record<string, AttrValue>,\n sessionId: string | undefined,\n ): void {\n if (!sessionId) {\n this.takeToolChildren(span);\n reportNoSessionSkip(`span \"${span.name}\"`, state.config.debug);\n return;\n }\n\n const { traceId, spanId } = span.spanContext();\n const identity = JSON.stringify([state.config.deployment, sessionId, traceId, spanId]);\n if (this.seenSpans.has(identity)) return;\n this.seenSpans.add(identity);\n if (this.seenSpans.size > MAX_DEDUP_SPANS) {\n this.seenSpans.delete(this.seenSpans.values().next().value!);\n }\n\n const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(\n state,\n sessionId,\n );\n\n const captured: CapturedTurn = {\n deploymentSlug: state.config.deployment,\n sessionExternalId,\n turnIndex,\n personaSlug: personaSlug ?? undefined,\n payload: buildPayload(span, this.takeToolChildren(span)),\n };\n // The row order: a turn's person text is the message that prompted\n // this reply. That is what the SDK already does for input recorded\n // with userInputSubmit (folded into the next captured turn, see\n // Probe.captureTurn), so the message observed on the request lands\n // the same way. Explicit input wins; this is only the fallback.\n const hints: CaptureHints = { observedUserText: extractUserText(a) };\n\n // Fire-and-log; SDK client swallows send errors. The auto version\n // stamp is awaited BEFORE the capture so the session-held\n // environmentConfigHash rides this same turn.\n (async () => {\n await maybeAutoStampEnvironmentConfig(session, a);\n await this.captureFn(captured, hints);\n })().catch((err) => {\n if (state.config.debug) {\n\n console.error(\n `[sight] span capture error: ${err instanceof Error ? err.message : err}`,\n );\n }\n });\n }\n\n shutdown(): Promise<void> {\n this.seenSpans.clear();\n this.toolChildren.clear();\n return Promise.resolve();\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n// ── Exported helpers for tests ────────────────────────────────────────────\nexport const _internals = {\n isLLMCall,\n isAiSdkModelCall,\n isVercelAgentRollup,\n taggedProvider,\n buildPayload,\n MAX_DEDUP_SPANS,\n extractSystemPromptText,\n maybeAutoStampEnvironmentConfig,\n parseOutputMessages,\n extractUserText,\n toolNameOfSpan,\n};\n","/**\n * Explicit OpenAI client wrapping: the autocapture path that does not\n * depend on module format, load order, or the openai version.\n *\n * Module patching (the other path) attaches only under CommonJS, only when\n * `openai` is loaded after Sight.init(), and only for openai <5. wrapOpenAI()\n * wraps the client instance the caller already holds instead.\n *\n * import OpenAI from 'openai';\n * import { Sight, wrapOpenAI } from '@cultured_computer/sight';\n * const openai = wrapOpenAI(new OpenAI());\n * await Sight.withSession(conversationId, () =>\n * openai.chat.completions.create({ ... }),\n * );\n *\n * Covers chat.completions.create and responses.create, streaming included:\n * the stream is teed, chunks reach the caller unchanged, and the turn is\n * emitted when the stream completes. A call is captured only inside a\n * Sight.withSession() scope; the first call outside one prints one warning.\n *\n * A streamed call also records the time to the first token: request start\n * to the first chunk that carries reply text, a refusal, or a tool call.\n * A non-streamed call has no first-token time and sends none. A cost is\n * sent only when the response reports one (`usage.cost`).\n *\n * wrapOpenAI() may be called before Sight.init(): the wrap passes calls\n * through untouched until init runs, and warns once if a call happens\n * before it.\n */\n\nimport type { CapturedTurn } from '../types.js';\nimport { getCurrentSessionId } from './session-context.js';\nimport { reportNoSessionSkip } from './no-session.js';\nimport { isInsideAiModelCall } from './ai-dedupe.js';\nimport {\n resolveSessionAndTurn,\n autoStampFromSystemText,\n type ProcessorProbeState,\n type CaptureFn,\n} from './otel-processor.js';\n\ntype Bound = {\n state: ProcessorProbeState;\n captureFn: CaptureFn;\n};\n\nlet bound: Bound | null = null;\nlet warnedUnbound = false;\n/** True once any client has been wrapped in this process. */\nlet wrappedClientSeen = false;\n\n/**\n * Whether the host uses the wrapped-client path. The module-patch check\n * reads this so it does not report a dead capture path to a host whose\n * calls are captured through the wrap.\n */\nexport function hasWrappedClient(): boolean {\n return wrappedClientSeen;\n}\n\nexport function bindWrapOpenAI(state: ProcessorProbeState, captureFn: CaptureFn): void {\n bound = { state, captureFn };\n}\n\n/** shutdown() detaches; a later init rebinds. */\nexport function unbindWrapOpenAI(): void {\n bound = null;\n}\n\nconst WRAPPED = Symbol.for('sight.wrapOpenAI');\n\n// ── Payload extraction ────────────────────────────────────────────────────\n\ntype AnyRecord = Record<string, unknown>;\n\nfunction asRecord(v: unknown): AnyRecord | undefined {\n return v !== null && typeof v === 'object' ? (v as AnyRecord) : undefined;\n}\n\nfunction asString(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction asNumber(v: unknown): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\n/** Join string-or-parts message content into one string (mirrors the processor). */\nfunction messageText(content: unknown): string | undefined {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n const parts: string[] = [];\n for (const part of content) {\n if (typeof part === 'string') parts.push(part);\n else {\n const p = asRecord(part);\n const text = p?.['text'] ?? p?.['content'];\n if (typeof text === 'string') parts.push(text);\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n return undefined;\n}\n\n/** System text from chat params (messages[]) or responses params (instructions). */\nfunction systemTextFromParams(params: AnyRecord | undefined): string | undefined {\n if (!params) return undefined;\n const instructions = asString(params['instructions']);\n if (instructions && instructions.length > 0) return instructions;\n const messages = params['messages'];\n if (Array.isArray(messages)) {\n for (const raw of messages) {\n const m = asRecord(raw);\n if (m && (m['role'] === 'system' || m['role'] === 'developer')) {\n const text = messageText(m['content']);\n if (text) return text;\n }\n }\n }\n return undefined;\n}\n\n/** Clock for latency and first-token time; tests replace it. */\nlet now: () => number = Date.now;\n\nfunction hostOf(baseURL: string | undefined): string | undefined {\n if (!baseURL) return undefined;\n try {\n return new URL(baseURL).hostname.toLowerCase();\n } catch {\n return undefined;\n }\n}\n\n/**\n * The provider that served the call, read from the client's base URL.\n * A client with no readable base URL is the default OpenAI endpoint. A\n * host this function does not know yields no provider: an\n * OpenAI-compatible endpoint is not OpenAI, and a wrong provider would\n * let the server price the turn from the wrong price list.\n */\nfunction providerFor(model: string | undefined, baseURL?: string): string | undefined {\n if (model?.toLowerCase().startsWith('mercury')) return 'inception';\n const host = hostOf(baseURL);\n if (!host || host === 'api.openai.com') return 'openai';\n if (host === 'openrouter.ai' || host.endsWith('.openrouter.ai')) return 'openrouter';\n if (host.endsWith('.openai.azure.com')) return 'azure';\n if (host === 'inceptionlabs.ai' || host.endsWith('.inceptionlabs.ai')) return 'inception';\n return undefined;\n}\n\n/**\n * Cost as the provider reported it in the usage block (OpenRouter sends\n * `usage.cost`). Absent, negative or non-numeric means not reported:\n * undefined, never 0. A reported 0 stays 0. On a bring-your-own-key\n * OpenRouter call `cost` is only the router's fee; the upstream charge is\n * `cost_details.upstream_inference_cost`, and the total is sent only when\n * that is reported too.\n */\nfunction costFromUsage(usage: AnyRecord | undefined): number | undefined {\n const cost = asNumber(usage?.['cost']);\n if (cost === undefined || !Number.isFinite(cost) || cost < 0) return undefined;\n if (usage?.['is_byok'] === true) {\n const upstream = asNumber(asRecord(usage['cost_details'])?.['upstream_inference_cost']);\n if (upstream === undefined || !Number.isFinite(upstream) || upstream < 0) return undefined;\n return cost + upstream;\n }\n return cost;\n}\n\n/** chat.completions non-streaming response → payload fields. */\nfunction payloadFromChatResponse(r: AnyRecord, requestModel: string | undefined) {\n const choice = Array.isArray(r['choices']) ? asRecord(r['choices'][0]) : undefined;\n const message = asRecord(choice?.['message']);\n const usage = asRecord(r['usage']);\n const promptDetails = asRecord(usage?.['prompt_tokens_details']);\n const toolCalls = Array.isArray(message?.['tool_calls'])\n ? (message['tool_calls'] as unknown[])\n : undefined;\n const toolNames = toolCalls\n ?.map((t) => asString(asRecord(asRecord(t)?.['function'])?.['name']))\n .filter((n): n is string => typeof n === 'string');\n return {\n model: asString(r['model']) ?? requestModel,\n text: messageText(message?.['content']),\n tokensInput: asNumber(usage?.['prompt_tokens']),\n tokensOutput: asNumber(usage?.['completion_tokens']),\n cachedTokens: asNumber(promptDetails?.['cached_tokens']),\n finishReason: asString(choice?.['finish_reason']),\n toolNames,\n costUsd: costFromUsage(usage),\n };\n}\n\n/** responses API non-streaming response → payload fields. */\nfunction payloadFromResponsesResponse(r: AnyRecord, requestModel: string | undefined) {\n const usage = asRecord(r['usage']);\n const inputDetails = asRecord(usage?.['input_tokens_details']);\n let text = asString(r['output_text']);\n const toolNames: string[] = [];\n if (Array.isArray(r['output'])) {\n const texts: string[] = [];\n for (const raw of r['output'] as unknown[]) {\n const item = asRecord(raw);\n if (!item) continue;\n if (item['type'] === 'function_call') {\n const name = asString(item['name']);\n if (name) toolNames.push(name);\n }\n if (item['type'] === 'message' && Array.isArray(item['content'])) {\n for (const c of item['content'] as unknown[]) {\n const cr = asRecord(c);\n if (cr?.['type'] === 'output_text') {\n const t = asString(cr['text']);\n if (t) texts.push(t);\n }\n }\n }\n }\n if (!text && texts.length > 0) text = texts.join('\\n');\n }\n return {\n model: asString(r['model']) ?? requestModel,\n text,\n tokensInput: asNumber(usage?.['input_tokens']),\n tokensOutput: asNumber(usage?.['output_tokens']),\n cachedTokens: asNumber(inputDetails?.['cached_tokens']),\n finishReason: asString(r['status']),\n toolNames: toolNames.length > 0 ? toolNames : undefined,\n costUsd: costFromUsage(usage),\n };\n}\n\ntype Extracted = ReturnType<typeof payloadFromChatResponse>;\n\ntype CallFacts = {\n api: 'chat' | 'responses';\n latencyMs: number;\n /** Streamed calls only; undefined when not streamed or no token arrived. */\n firstTokenMs?: number;\n /** The model string the caller sent. */\n requestModel: string | undefined;\n baseURL: string | undefined;\n};\n\nfunction buildTurnPayload(x: Extracted, call: CallFacts) {\n return {\n probe_tokens_input: x.tokensInput,\n probe_tokens_output: x.tokensOutput,\n probe_latency_ms: call.latencyMs,\n probe_first_token_ms: call.firstTokenMs,\n probe_cost_usd: x.costUsd,\n probe_model: x.model,\n // The model as requested. The response names a dated snapshot; the\n // server prices a turn by whichever of the two the catalogue lists.\n probe_request_model: call.requestModel,\n probe_provider: providerFor(x.model ?? call.requestModel, call.baseURL),\n probe_tool_calls: x.toolNames?.length,\n probe_tool_names: x.toolNames,\n probe_error: undefined as string | undefined,\n probe_finish_reason: x.finishReason,\n response: x.text ? { text: x.text } : undefined,\n probe_cache_read_input_tokens: x.cachedTokens,\n // OpenAI usage counts cached tokens inside the input count.\n probe_cache_tokens_in_input: x.cachedTokens !== undefined ? true : undefined,\n _wrap: { api: call.api, adapter: 'wrapOpenAI' },\n };\n}\n\n// ── Emission ──────────────────────────────────────────────────────────────\n\nfunction emit(params: AnyRecord | undefined, payload: Record<string, unknown>): void {\n if (!bound) {\n if (!warnedUnbound) {\n warnedUnbound = true;\n console.warn(\n '[sight] wrapOpenAI: call observed before Sight.init(); nothing captured until init runs.',\n );\n }\n return;\n }\n const { state, captureFn } = bound;\n const sessionId = getCurrentSessionId();\n if (!sessionId) {\n reportNoSessionSkip('wrapOpenAI', state.config.debug);\n return;\n }\n const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(\n state,\n sessionId,\n );\n const captured: CapturedTurn = {\n deploymentSlug: state.config.deployment,\n sessionExternalId,\n turnIndex,\n personaSlug: personaSlug ?? undefined,\n payload,\n };\n void (async () => {\n await autoStampFromSystemText(session, systemTextFromParams(params));\n await captureFn(captured);\n })().catch((err) => {\n if (state.config.debug) {\n console.error(`[sight] wrapOpenAI capture error: ${err instanceof Error ? err.message : err}`);\n }\n });\n}\n\n// ── Streaming tee ─────────────────────────────────────────────────────────\n\n/**\n * Proxy the stream object so every property and method passes through\n * untouched, but iteration is observed: chunks are forwarded to the caller\n * unchanged while an accumulator builds the turn, emitted at stream end.\n */\nfunction teeStream<T extends object>(\n stream: T,\n onChunk: (chunk: unknown) => void,\n onDone: () => void,\n): T {\n let done = false;\n const finish = () => {\n if (!done) {\n done = true;\n onDone();\n }\n };\n return new Proxy(stream, {\n get(target, prop, receiver) {\n if (prop === Symbol.asyncIterator) {\n return function () {\n const inner = (target as AsyncIterable<unknown>)[Symbol.asyncIterator]();\n return {\n async next(): Promise<IteratorResult<unknown>> {\n try {\n const r = await inner.next();\n if (r.done) finish();\n else onChunk(r.value);\n return r;\n } catch (err) {\n finish();\n throw err;\n }\n },\n async return(value?: unknown): Promise<IteratorResult<unknown>> {\n finish();\n return inner.return ? inner.return(value) : { done: true, value };\n },\n async throw(err?: unknown): Promise<IteratorResult<unknown>> {\n finish();\n if (inner.throw) return inner.throw(err);\n throw err;\n },\n };\n };\n }\n const value = Reflect.get(target, prop, receiver);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\ntype StreamAccumulator = {\n /** Returns true when the chunk carries output: reply text, a refusal, or a tool call. */\n onChunk: (chunk: unknown) => boolean;\n result: () => Extracted;\n};\n\nfunction nonEmpty(v: unknown): boolean {\n return typeof v === 'string' && v.length > 0;\n}\n\nfunction chatStreamAccumulator(requestModel: string | undefined): StreamAccumulator {\n const texts: string[] = [];\n // Tool-call names by call index: the name arrives on the call's first\n // delta, later deltas carry only argument fragments.\n const toolNameParts = new Map<number, string>();\n let model = requestModel;\n let finishReason: string | undefined;\n let tokensInput: number | undefined;\n let tokensOutput: number | undefined;\n let cachedTokens: number | undefined;\n let costUsd: number | undefined;\n return {\n onChunk(chunk) {\n const c = asRecord(chunk);\n if (!c) return false;\n model = asString(c['model']) ?? model;\n const choice = Array.isArray(c['choices']) ? asRecord(c['choices'][0]) : undefined;\n const delta = asRecord(choice?.['delta']);\n // The opening chunk carries the role and an empty content string:\n // it is not a token.\n let content = false;\n const t = asString(delta?.['content']);\n if (t) {\n texts.push(t);\n content = true;\n }\n if (nonEmpty(delta?.['refusal'])) content = true;\n const toolCalls = delta?.['tool_calls'];\n if (Array.isArray(toolCalls) && toolCalls.length > 0) {\n content = true;\n toolCalls.forEach((raw, position) => {\n const call = asRecord(raw);\n const name = asString(asRecord(call?.['function'])?.['name']);\n if (!name) return;\n const index = asNumber(call?.['index']) ?? position;\n toolNameParts.set(index, (toolNameParts.get(index) ?? '') + name);\n });\n }\n finishReason = asString(choice?.['finish_reason']) ?? finishReason;\n const usage = asRecord(c['usage']);\n if (usage) {\n tokensInput = asNumber(usage['prompt_tokens']) ?? tokensInput;\n tokensOutput = asNumber(usage['completion_tokens']) ?? tokensOutput;\n cachedTokens =\n asNumber(asRecord(usage['prompt_tokens_details'])?.['cached_tokens']) ?? cachedTokens;\n costUsd = costFromUsage(usage) ?? costUsd;\n }\n return content;\n },\n result: () => {\n const toolNames = [...toolNameParts.entries()].sort((x, y) => x[0] - y[0]).map((e) => e[1]);\n return {\n model,\n text: texts.length > 0 ? texts.join('') : undefined,\n tokensInput,\n tokensOutput,\n cachedTokens,\n finishReason,\n toolNames: toolNames.length > 0 ? toolNames : undefined,\n costUsd,\n };\n },\n };\n}\n\n/** Responses-API stream events that carry output. */\nconst RESPONSES_OUTPUT_DELTAS = new Set([\n 'response.output_text.delta',\n 'response.refusal.delta',\n 'response.function_call_arguments.delta',\n]);\n\nfunction responsesStreamAccumulator(requestModel: string | undefined): StreamAccumulator {\n const texts: string[] = [];\n // Function-call names by output index, for a stream that ends without\n // the completed envelope.\n const toolNameByIndex = new Map<number, string>();\n let final: Extracted | null = null;\n return {\n onChunk(chunk) {\n const c = asRecord(chunk);\n if (!c) return false;\n const type = asString(c['type']);\n let content = false;\n if (type === 'response.output_text.delta') {\n const t = asString(c['delta']);\n if (t) texts.push(t);\n }\n if (type !== undefined && RESPONSES_OUTPUT_DELTAS.has(type) && nonEmpty(c['delta'])) {\n content = true;\n }\n if (type === 'response.output_item.added' || type === 'response.output_item.done') {\n const item = asRecord(c['item']);\n if (item?.['type'] === 'function_call') {\n // A function call opening is the first sign of a tool call.\n content = true;\n const name = asString(item['name']);\n if (name) toolNameByIndex.set(asNumber(c['output_index']) ?? toolNameByIndex.size, name);\n }\n }\n if (type === 'response.completed') {\n const response = asRecord(c['response']);\n if (response) final = payloadFromResponsesResponse(response, requestModel);\n }\n return content;\n },\n result: () => {\n const streamedNames = [...toolNameByIndex.entries()]\n .sort((x, y) => x[0] - y[0])\n .map((e) => e[1]);\n const streamedText = texts.length > 0 ? texts.join('') : undefined;\n if (final) {\n return {\n ...final,\n text: final.text ?? streamedText,\n toolNames: final.toolNames ?? (streamedNames.length > 0 ? streamedNames : undefined),\n };\n }\n return {\n model: requestModel,\n text: streamedText,\n tokensInput: undefined,\n tokensOutput: undefined,\n cachedTokens: undefined,\n finishReason: undefined,\n toolNames: streamedNames.length > 0 ? streamedNames : undefined,\n costUsd: undefined,\n };\n },\n };\n}\n\n// ── The wrap ──────────────────────────────────────────────────────────────\n\ntype CreateFn = (...args: unknown[]) => Promise<unknown>;\n\nfunction wrapCreate(\n client: AnyRecord,\n target: AnyRecord,\n api: 'chat' | 'responses',\n makeAccumulator: (model: string | undefined) => StreamAccumulator,\n extractResponse: (r: AnyRecord, model: string | undefined) => Extracted,\n): void {\n const original = target['create'];\n if (typeof original !== 'function') return;\n target['create'] = function (this: unknown, ...args: unknown[]) {\n // A call made by a provider inside an `ai` model call that the Sight\n // `ai` integration captures: that integration records the turn, so\n // this one passes through (one model call, one turn).\n if (isInsideAiModelCall()) return (original as CreateFn).apply(this, args);\n const params = asRecord(args[0]);\n const requestModel = asString(params?.['model']);\n const startedAt = now();\n const baseURL = asString(client['baseURL']);\n const facts = (firstTokenMs?: number): CallFacts => ({\n api,\n latencyMs: now() - startedAt,\n firstTokenMs,\n requestModel,\n baseURL,\n });\n const result = (original as CreateFn).apply(this, args);\n // Non-promise (unexpected shape): pass through untouched.\n if (!result || typeof (result as Promise<unknown>).then !== 'function') return result;\n return (result as Promise<unknown>).then(\n (resolved) => {\n try {\n const isStream =\n resolved !== null &&\n typeof resolved === 'object' &&\n Symbol.asyncIterator in (resolved as object);\n if (isStream) {\n const acc = makeAccumulator(requestModel);\n // Time to the first token: request start to the first chunk\n // that carries output. Stays undefined when none arrives.\n let firstTokenMs: number | undefined;\n return teeStream(\n resolved as object,\n (chunk) => {\n const arrivedAt = now();\n if (acc.onChunk(chunk) && firstTokenMs === undefined) {\n firstTokenMs = Math.max(0, Math.round(arrivedAt - startedAt));\n }\n },\n () => {\n emit(params, buildTurnPayload(acc.result(), facts(firstTokenMs)));\n },\n );\n }\n const r = asRecord(resolved);\n if (r) {\n // Not streamed: no first-token time, and never the total latency.\n emit(params, buildTurnPayload(extractResponse(r, requestModel), facts()));\n }\n return resolved;\n } catch {\n // Capture must never damage the customer's call path.\n return resolved;\n }\n },\n (err: unknown) => {\n // Failed call: record the error turn, then rethrow untouched.\n try {\n const x: Extracted = {\n model: requestModel,\n text: undefined,\n tokensInput: undefined,\n tokensOutput: undefined,\n cachedTokens: undefined,\n finishReason: undefined,\n toolNames: undefined,\n costUsd: undefined,\n };\n const payload = buildTurnPayload(x, facts());\n payload.probe_error = err instanceof Error ? err.message : String(err);\n emit(params, payload);\n } catch {\n // ignore\n }\n throw err;\n },\n );\n };\n}\n\n/**\n * Wrap an OpenAI client instance so every chat.completions.create and\n * responses.create call made inside a Sight.withSession() scope is captured\n * as a turn. Returns the same client. Idempotent; safe to call before\n * Sight.init() (capture starts once init has run). A call outside any\n * session scope is not captured; the first one prints one warning.\n */\nexport function wrapOpenAI<T extends object>(client: T): T {\n wrappedClientSeen = true;\n const c = client as AnyRecord & { [WRAPPED]?: boolean };\n if (c[WRAPPED]) return client;\n c[WRAPPED] = true;\n\n const completions = asRecord(asRecord(c['chat'])?.['completions']);\n if (completions) {\n wrapCreate(c, completions, 'chat', chatStreamAccumulator, payloadFromChatResponse);\n }\n const responses = asRecord(c['responses']);\n if (responses) {\n wrapCreate(c, responses, 'responses', responsesStreamAccumulator, payloadFromResponsesResponse);\n }\n return client;\n}\n\n// ── Exported for tests ────────────────────────────────────────────────────\nexport const _wrapInternals = {\n payloadFromChatResponse,\n payloadFromResponsesResponse,\n systemTextFromParams,\n teeStream,\n isBound: () => bound !== null,\n resetWrappedClientSeen: () => {\n wrappedClientSeen = false;\n },\n providerFor,\n costFromUsage,\n /** Replace the clock (tests); call with no argument to restore Date.now. */\n setClock: (clock?: () => number) => {\n now = clock ?? Date.now;\n },\n};\n","/**\n * Vercel AI SDK (`ai`) autocapture.\n *\n * `ai` 7 creates no OpenTelemetry spans itself. It calls the telemetry\n * integrations registered with `registerTelemetry()` (kept on the global\n * `AI_SDK_TELEMETRY_INTEGRATIONS`), and once one integration is registered\n * every call emits events with no per-call flag. This file is that\n * integration: Sight.init() registers it when `ai` 7 is resolvable, and\n * `sightTelemetry()` exports it for hosts that register it themselves.\n *\n * The turn unit is ONE MODEL CALL (one step of `generateText` / `streamText`,\n * or the single call of `generateObject` / `streamObject`), the same unit\n * wrapOpenAI and the span processor use. A tool loop of N model calls is N\n * turns: each carries the text of that reply (which may be empty when the\n * model only requested tools) and the tool names it requested. The outer\n * `generateText` operation is never a turn.\n *\n * Events used (interface `Telemetry` of `ai` 7):\n * onStart session scope and runtimeContext of the call\n * onStepStart runtimeContext of the step\n * onLanguageModelCallStart request instructions and messages\n * executeLanguageModelCall marks the provider call (see ai-dedupe.ts)\n * onLanguageModelCallEnd provider response id (see ai-dedupe.ts)\n * onStepEnd the turn: reply, model, usage, finish, timing\n * onObjectStepStart / End the same for generateObject / streamObject\n * onError / onAbort a model call that failed or was aborted\n * onEnd releases the per-call state\n * `onStepFinish` is deliberately not implemented: `ai` 7 sends every step\n * end to both names, and `ai` 6 (which has no `onStepEnd`) is captured\n * through its OpenTelemetry spans instead (see otel-processor.ts).\n *\n * `ai` 3 to 6 are not handled here. `ai` 6 emits `ai.*` OpenTelemetry spans\n * when a call sets `experimental_telemetry: { isEnabled: true }`; the span\n * processor maps those.\n */\n\nimport { createRequire } from 'node:module';\nimport type { CapturedTurn } from '../types.js';\nimport { getCurrentSessionId } from './session-context.js';\nimport { reportNoSessionSkip } from './no-session.js';\nimport {\n resolveSessionAndTurn,\n autoStampFromSystemText,\n type ProcessorProbeState,\n type CaptureFn,\n type CaptureHints,\n} from './otel-processor.js';\nimport {\n runInsideAiModelCall,\n claimAiResponse,\n noteAiModelCallOpened,\n noteAiModelCallClosed,\n} from './ai-dedupe.js';\n\n// ── Public types ──────────────────────────────────────────────────────────\n\n/** Options for `sightTelemetry()`. */\nexport type SightAiTelemetryOptions = {\n /**\n * The session the calls this integration sees belong to, for a call made\n * outside any Sight.withSession() scope. An explicit scope wins.\n */\n sessionId?: string;\n};\n\n/**\n * The Sight telemetry integration for the Vercel AI SDK (`ai` 7). It is\n * structurally a `Telemetry` from `ai`: pass it to `registerTelemetry()` or\n * to a call's `telemetry.integrations`.\n */\nexport type SightAiTelemetry = {\n readonly name: 'sight';\n onStart(event: unknown): void;\n onStepStart(event: unknown): void;\n onLanguageModelCallStart(event: unknown): void;\n onLanguageModelCallEnd(event: unknown): void;\n onStepEnd(event: unknown): void;\n onObjectStepStart(event: unknown): void;\n onObjectStepEnd(event: unknown): void;\n onEnd(event: unknown): void;\n onAbort(event: unknown): void;\n onError(event: unknown): void;\n executeLanguageModelCall<T>(options: { execute: () => PromiseLike<T> }): PromiseLike<T>;\n};\n\n/** Runtime-context keys read as the session id, in this order. */\nexport const AI_SESSION_KEYS = ['sightSessionId', 'sessionId'] as const;\n\n// ── Binding (same lifecycle as the span processor and wrapOpenAI) ─────────\n\ntype Bound = { state: ProcessorProbeState; captureFn: CaptureFn };\n\nlet bound: Bound | null = null;\nlet everBound = false;\nlet warnedUnbound = false;\n\nfunction bindVercelAI(state: ProcessorProbeState, captureFn: CaptureFn): void {\n bound = { state, captureFn };\n everBound = true;\n}\n\n/** shutdown() detaches; a later init rebinds. The integration stays registered. */\nexport function unbindVercelAI(): void {\n bound = null;\n for (const call of calls.values()) closeModelCall(call);\n calls.clear();\n}\n\n// ── Event reading ─────────────────────────────────────────────────────────\n\ntype Rec = Record<string, unknown>;\n\nfunction rec(v: unknown): Rec | undefined {\n return v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Rec) : undefined;\n}\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\n\nfunction num(v: unknown): number | undefined {\n return typeof v === 'number' && Number.isFinite(v) ? v : undefined;\n}\n\nfunction ms(v: unknown): number | undefined {\n const n = num(v);\n return n === undefined ? undefined : Math.max(0, Math.round(n));\n}\n\n/** Text parts of one message's content (a string, or parts). Nothing else. */\nfunction textOfContent(content: unknown, sep: string): string | undefined {\n if (typeof content === 'string') return content.length > 0 ? content : undefined;\n if (!Array.isArray(content)) return undefined;\n const texts: string[] = [];\n for (const part of content) {\n const p = rec(part);\n if (p?.['type'] === 'text' && typeof p['text'] === 'string' && p['text'].length > 0) {\n texts.push(p['text']);\n }\n }\n return texts.length > 0 ? texts.join(sep) : undefined;\n}\n\n/**\n * The person's message that prompted this model call: the request's last\n * message when it is the person's and carries text (system messages after it\n * are skipped). A request that ends on a tool result or an assistant message\n * was not prompted by a new message from the person, so a tool loop does not\n * repeat one message across its turns. Same rule as the span mapping.\n */\nfunction userTextOf(messages: unknown): string | undefined {\n if (!Array.isArray(messages)) return undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = rec(messages[i]);\n if (!m) return undefined;\n if (m['role'] === 'system') continue;\n if (m['role'] !== 'user') return undefined;\n return textOfContent(m['content'], '\\n');\n }\n return undefined;\n}\n\n/** System text: `instructions` (string or system messages), else a system message. */\nfunction systemTextOf(instructions: unknown, messages: unknown): string | undefined {\n if (typeof instructions === 'string') return str(instructions);\n const list = Array.isArray(instructions) ? instructions : instructions ? [instructions] : [];\n const texts: string[] = [];\n for (const item of list) {\n const t = textOfContent(rec(item)?.['content'], '\\n');\n if (t) texts.push(t);\n }\n if (texts.length > 0) return texts.join('\\n');\n if (Array.isArray(messages)) {\n for (const raw of messages) {\n const m = rec(raw);\n if (m?.['role'] === 'system') {\n const t = textOfContent(m['content'], '\\n');\n if (t) return t;\n }\n }\n }\n return undefined;\n}\n\nfunction sessionFromContext(runtimeContext: unknown): string | undefined {\n const ctx = rec(runtimeContext);\n if (!ctx) return undefined;\n for (const key of AI_SESSION_KEYS) {\n const v = str(ctx[key]);\n if (v) return v;\n }\n return undefined;\n}\n\nfunction errorMessage(err: unknown): string {\n if (err instanceof Error) return err.message || err.name;\n return typeof err === 'string' && err.length > 0 ? err : 'error';\n}\n\n// ── Per-call state ────────────────────────────────────────────────────────\n// `callId` identifies one generateText / streamText / generateObject\n// operation; its model calls run one after another, so one open model call\n// per callId is enough to tie a start to its end.\n\ntype ModelCall = {\n startedAt: number;\n instructions: unknown;\n messages: unknown;\n provider: string | undefined;\n modelId: string | undefined;\n};\n\ntype CallState = {\n /** Sight.withSession() scope active when the operation started. */\n scopeSession: string | undefined;\n /** Session id found in the call's runtimeContext. */\n contextSession: string | undefined;\n operationId: string | undefined;\n /** generateObject carries its system text on the start event only. */\n system: unknown;\n open: ModelCall | null;\n};\n\n// Bounded: an operation whose end, abort and error events never arrive\n// (a stream nobody consumes) must not hold its state forever.\nconst MAX_CALLS = 1_000;\nconst calls = new Map<string, CallState>();\n\nfunction stateFor(callId: string): CallState {\n let call = calls.get(callId);\n if (!call) {\n call = {\n scopeSession: undefined,\n contextSession: undefined,\n operationId: undefined,\n system: undefined,\n open: null,\n };\n if (calls.size >= MAX_CALLS) {\n const oldest = calls.keys().next().value!;\n closeModelCall(calls.get(oldest)!);\n calls.delete(oldest);\n }\n calls.set(callId, call);\n }\n return call;\n}\n\nfunction openModelCall(call: CallState, modelCall: ModelCall): void {\n if (call.open === null) noteAiModelCallOpened();\n call.open = modelCall;\n}\n\nfunction closeModelCall(call: CallState): void {\n if (call.open !== null) noteAiModelCallClosed();\n call.open = null;\n}\n\n// ── Emission ──────────────────────────────────────────────────────────────\n\ntype TurnFields = {\n callId: string;\n text?: string;\n model?: string;\n provider?: string;\n usage?: unknown;\n finishReason?: string;\n rawFinishReason?: string;\n toolNames?: string[];\n latencyMs?: number;\n firstTokenMs?: number;\n error?: string;\n responseId?: string;\n stepNumber?: number;\n functionId?: string;\n};\n\nfunction buildPayload(call: CallState, f: TurnFields): Record<string, unknown> {\n const usage = rec(f.usage);\n const inputDetails = rec(usage?.['inputTokenDetails']);\n const outputDetails = rec(usage?.['outputTokenDetails']);\n const toolNames = f.toolNames && f.toolNames.length > 0 ? f.toolNames : undefined;\n return {\n probe_tokens_input: num(usage?.['inputTokens']),\n probe_tokens_output: num(usage?.['outputTokens']),\n probe_latency_ms: f.latencyMs,\n probe_first_token_ms: f.firstTokenMs,\n probe_model: f.model,\n probe_provider: f.provider,\n probe_tool_calls: toolNames?.length,\n probe_tool_names: toolNames,\n probe_error: f.error,\n probe_finish_reason: f.finishReason,\n response: f.text ? { text: f.text } : undefined,\n probe_cache_read_input_tokens: num(inputDetails?.['cacheReadTokens']),\n probe_cache_creation_input_tokens: num(inputDetails?.['cacheWriteTokens']),\n // Debug metadata (kept in payload, not projected to canonical columns).\n _ai: {\n adapter: 'ai-telemetry',\n operationId: call.operationId,\n callId: f.callId,\n stepNumber: f.stepNumber,\n functionId: f.functionId,\n responseId: f.responseId,\n rawFinishReason: f.rawFinishReason,\n reasoningTokens: num(outputDetails?.['reasoningTokens']),\n },\n };\n}\n\nfunction emit(\n options: SightAiTelemetryOptions,\n call: CallState,\n request: { instructions: unknown; messages: unknown },\n fields: TurnFields,\n): void {\n if (!bound) {\n // Registered or passed to a call before Sight.init(). After a\n // shutdown() the integration is simply not listening.\n if (!everBound && !warnedUnbound) {\n warnedUnbound = true;\n console.warn(\n '[sight] ai telemetry: call observed before Sight.init(); nothing captured until init runs.',\n );\n }\n return;\n }\n const { state, captureFn } = bound;\n // Explicit scope first, then the per-call ids, in a fixed order.\n const sessionId =\n call.scopeSession ?? (getCurrentSessionId() || options.sessionId || call.contextSession);\n if (!sessionId) {\n reportNoSessionSkip(`ai ${call.operationId ?? 'model call'}`, state.config.debug);\n return;\n }\n const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(\n state,\n sessionId,\n );\n const captured: CapturedTurn = {\n deploymentSlug: state.config.deployment,\n sessionExternalId,\n turnIndex,\n personaSlug: personaSlug ?? undefined,\n payload: buildPayload(call, fields),\n };\n const hints: CaptureHints = { observedUserText: userTextOf(request.messages) };\n const systemText = systemTextOf(request.instructions, request.messages);\n void (async () => {\n await autoStampFromSystemText(session, systemText);\n await captureFn(captured, hints);\n })().catch((err) => {\n if (state.config.debug) {\n console.error(\n `[sight] ai telemetry capture error: ${err instanceof Error ? err.message : err}`,\n );\n }\n });\n}\n\n// ── The integration ───────────────────────────────────────────────────────\n\n/** Brand shared by every instance, across module copies (ESM and CJS builds). */\nconst BRAND = Symbol.for('sight.aiTelemetry');\n\nfunction isSightIntegration(v: unknown): boolean {\n return v !== null && typeof v === 'object' && (v as Record<symbol, unknown>)[BRAND] === true;\n}\n\n/** A hook must never throw into the host's generation call. */\nfunction guarded(fn: (event: Rec) => void): (event: unknown) => void {\n return (event) => {\n try {\n const e = rec(event);\n if (e) fn(e);\n } catch (err) {\n if (bound?.state.config.debug) {\n console.error(\n `[sight] ai telemetry hook error: ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n };\n}\n\nfunction createIntegration(options: SightAiTelemetryOptions): SightAiTelemetry {\n const failed = (callId: string | undefined, error: string, functionId: unknown): void => {\n if (!callId) return;\n const call = calls.get(callId);\n if (!call) return;\n const open = call.open;\n closeModelCall(call);\n // The operation is over: no end event follows an error or an abort. A\n // step end that still arrives for it finds no state and is ignored.\n calls.delete(callId);\n // Only a failure of the model call itself is a turn. An error raised\n // after the reply was captured (a tool, output parsing) is not.\n if (!open) return;\n emit(\n options,\n call,\n { instructions: open.instructions, messages: open.messages },\n {\n callId,\n model: open.modelId,\n provider: open.provider,\n latencyMs: Math.max(0, Date.now() - open.startedAt),\n error,\n functionId: str(functionId),\n },\n );\n };\n\n /** The request as recorded for the open model call; nothing with recordInputs: false. */\n const begin = (e: Rec, instructions: unknown, messages: unknown): void => {\n const callId = str(e['callId']);\n if (!callId) return;\n const call = stateFor(callId);\n call.scopeSession ??= getCurrentSessionId() || undefined;\n const record = e['recordInputs'] !== false;\n openModelCall(call, {\n startedAt: Date.now(),\n instructions: record ? instructions : undefined,\n messages: record ? messages : undefined,\n provider: str(e['provider']),\n modelId: str(e['modelId']),\n });\n };\n\n const integration: SightAiTelemetry = {\n name: 'sight',\n\n onStart: guarded((e) => {\n const callId = str(e['callId']);\n if (!callId) return;\n const call = stateFor(callId);\n call.scopeSession = getCurrentSessionId() || undefined;\n call.contextSession = sessionFromContext(e['runtimeContext']);\n call.operationId = str(e['operationId']);\n call.system = e['system'] ?? e['instructions'];\n }),\n\n onStepStart: guarded((e) => {\n const callId = str(e['callId']);\n if (!callId) return;\n const call = stateFor(callId);\n call.contextSession = sessionFromContext(e['runtimeContext']) ?? call.contextSession;\n }),\n\n onLanguageModelCallStart: guarded((e) => {\n begin(e, e['instructions'], e['messages']);\n }),\n\n onLanguageModelCallEnd: guarded((e) => {\n // The step end below is the turn. Here: tell the span processor this\n // response id is taken, before a span for the same call can end.\n const responseId = str(e['responseId']);\n if (bound && responseId) claimAiResponse(responseId);\n }),\n\n onStepEnd: guarded((e) => {\n const callId = str(e['callId']);\n if (!callId) return;\n // No state: the operation already failed or was aborted, or it\n // started before this integration was registered.\n const call = calls.get(callId);\n if (!call) return;\n const open = call.open;\n closeModelCall(call);\n call.contextSession = sessionFromContext(e['runtimeContext']) ?? call.contextSession;\n\n const model = rec(e['model']);\n const response = rec(e['response']);\n const performance = rec(e['performance']);\n const content = Array.isArray(e['content']) ? (e['content'] as unknown[]) : [];\n const toolNames: string[] = [];\n for (const part of content) {\n const p = rec(part);\n if (p?.['type'] === 'tool-call') {\n const name = str(p['toolName']);\n if (name) toolNames.push(name);\n }\n }\n const finishReason = str(e['finishReason']);\n emit(\n options,\n call,\n { instructions: open?.instructions, messages: open?.messages },\n {\n callId,\n // Text parts only: never reasoning, tool input or tool output.\n text: e['recordOutputs'] === false ? undefined : textOfContent(content, ''),\n // The id the provider returned; the requested id when it returned none.\n model: str(response?.['modelId']) ?? str(model?.['modelId']) ?? open?.modelId,\n provider: str(model?.['provider']) ?? open?.provider,\n usage: e['usage'],\n finishReason,\n rawFinishReason: str(e['rawFinishReason']),\n toolNames,\n latencyMs:\n ms(performance?.['responseTimeMs']) ??\n (open ? Math.max(0, Date.now() - open.startedAt) : undefined),\n firstTokenMs: ms(performance?.['timeToFirstOutputMs']),\n // A stream that failed part way ends its step with this finish\n // reason; the events carry no error message for it.\n error:\n finishReason === 'error' ? 'model call ended with finish reason \"error\"' : undefined,\n responseId: str(response?.['id']),\n stepNumber: num(e['stepNumber']),\n functionId: str(e['functionId']),\n },\n );\n }),\n\n onObjectStepStart: guarded((e) => {\n const callId = str(e['callId']);\n begin(e, callId ? calls.get(callId)?.system : undefined, e['promptMessages']);\n }),\n\n onObjectStepEnd: guarded((e) => {\n const callId = str(e['callId']);\n if (!callId) return;\n const call = calls.get(callId);\n if (!call) return;\n const open = call.open;\n closeModelCall(call);\n const response = rec(e['response']);\n const responseId = str(response?.['id']);\n if (bound && responseId) claimAiResponse(responseId);\n emit(\n options,\n call,\n { instructions: open?.instructions, messages: open?.messages },\n {\n callId,\n // The reply of an object call is the JSON text the model produced.\n text: e['recordOutputs'] === false ? undefined : str(e['objectText']),\n model: str(response?.['modelId']) ?? str(e['modelId']) ?? open?.modelId,\n provider: str(e['provider']) ?? open?.provider,\n usage: e['usage'],\n finishReason: str(e['finishReason']),\n latencyMs: open ? Math.max(0, Date.now() - open.startedAt) : undefined,\n firstTokenMs: ms(e['msToFirstChunk']),\n responseId,\n stepNumber: num(e['stepNumber']),\n functionId: str(e['functionId']),\n },\n );\n }),\n\n onError: guarded((e) => {\n failed(str(e['callId']), errorMessage(e['error']), e['functionId']);\n }),\n\n onAbort: guarded((e) => {\n failed(str(e['callId']), 'aborted', e['functionId']);\n }),\n\n onEnd: guarded((e) => {\n const callId = str(e['callId']);\n if (!callId) return;\n const call = calls.get(callId);\n if (!call) return;\n closeModelCall(call);\n calls.delete(callId);\n }),\n\n executeLanguageModelCall<T>(callOptions: { execute: () => PromiseLike<T> }): PromiseLike<T> {\n // Unbound: Sight captures nothing for this call, so the other paths\n // must not be told to stand down.\n if (!bound) return callOptions.execute();\n return runInsideAiModelCall(() => callOptions.execute());\n },\n };\n Object.defineProperty(integration, BRAND, { value: true });\n return integration;\n}\n\nlet shared: SightAiTelemetry | null = null;\n\n/**\n * The Sight telemetry integration for the Vercel AI SDK (`ai` 7).\n *\n * Sight.init() registers it when `ai` is resolvable. Call this yourself when\n * that cannot work (a bundle where the SDK cannot resolve the host's `ai`):\n *\n * import { registerTelemetry } from 'ai';\n * import { sightTelemetry } from '@cultured_computer/sight';\n * registerTelemetry(sightTelemetry());\n *\n * or per call, with the session the call belongs to:\n *\n * generateText({ model, prompt,\n * telemetry: { integrations: sightTelemetry({ sessionId }) } });\n *\n * With no options it returns one shared instance, so Sight.init() does not\n * register it a second time. Safe to call before Sight.init(): nothing is\n * captured until init runs.\n */\nexport function sightTelemetry(options?: SightAiTelemetryOptions): SightAiTelemetry {\n if (options && options.sessionId !== undefined) return createIntegration(options);\n shared ??= createIntegration({});\n return shared;\n}\n\n// ── Registration at init ──────────────────────────────────────────────────\n\nexport type AiLoaders = {\n /** Synchronous load; throws or returns null when not possible in this runtime. */\n sync: () => unknown;\n /** Asynchronous load; rejects when `ai` is not installed. */\n async: () => Promise<unknown>;\n};\n\n/**\n * Node versions where require() loads an ES module without printing an\n * experimental warning: 22.13 and later on the 22 line, 23.5 and later.\n */\nfunction canRequireEsModule(): boolean {\n const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);\n return major >= 24 || (major === 23 && minor >= 5) || (major === 22 && minor >= 13);\n}\n\nconst defaultLoaders: AiLoaders = {\n // `ai` reads its integration list when a call starts, so a registration\n // that lands a tick after init would miss a call made right after init.\n // `ai` 7 is ES module only; where require() can load it this registers\n // before init returns, and anywhere else the asynchronous import is used.\n // createRequire, never a bare `require`: the bundler replaces a bare one\n // in the ES module build with a stub that always throws.\n sync: () => (canRequireEsModule() ? (createRequire(import.meta.url)('ai') as unknown) : null),\n async: () => import('ai'),\n};\n\nfunction globalIntegrations(): unknown[] {\n const list = (globalThis as { AI_SDK_TELEMETRY_INTEGRATIONS?: unknown })\n .AI_SDK_TELEMETRY_INTEGRATIONS;\n return Array.isArray(list) ? list : [];\n}\n\nlet registered = false;\n\nfunction register(mod: unknown, debug: boolean): void {\n if (registered) return;\n const registerTelemetry = rec(mod)?.['registerTelemetry'];\n if (typeof registerTelemetry !== 'function') {\n // `ai` 3 to 6: no registerTelemetry(). Nothing to install; the span\n // processor captures the `ai.*` spans `ai` 6 emits.\n if (debug) {\n console.log(\n '[sight/vercel-ai] ai <7 found: no integration to register; calls made with experimental_telemetry: { isEnabled: true } are captured from their OpenTelemetry spans',\n );\n }\n return;\n }\n registered = true;\n if (globalIntegrations().some(isSightIntegration)) {\n if (debug) console.log('[sight/vercel-ai] telemetry integration already registered');\n return;\n }\n (registerTelemetry as (...integrations: unknown[]) => void)(sightTelemetry());\n if (debug) {\n console.log(\n '[sight/vercel-ai] telemetry integration registered; generateText, streamText, generateObject and streamObject calls are captured, one turn per model call',\n );\n }\n}\n\n/**\n * Bind the integration to this init's state and register it with `ai` once\n * per process. A host without `ai` gets no warning and no error.\n */\nexport async function registerVercelAI(\n state: ProcessorProbeState,\n captureFn?: CaptureFn,\n loaders: AiLoaders = defaultLoaders,\n): Promise<void> {\n if (captureFn) bindVercelAI(state, captureFn);\n if (registered) return;\n const debug = state.config.debug;\n let mod: unknown = null;\n try {\n mod = loaders.sync();\n } catch {\n mod = null;\n }\n if (mod === null || mod === undefined) {\n try {\n mod = await loaders.async();\n } catch {\n if (debug) {\n console.log(\n '[sight/vercel-ai] ai is not installed; nothing registered. If ai is bundled where the SDK cannot resolve it, call registerTelemetry(sightTelemetry()).',\n );\n }\n return;\n }\n }\n try {\n register(mod, debug);\n } catch (err) {\n if (debug) {\n console.warn(\n `[sight/vercel-ai] telemetry integration not registered (${err instanceof Error ? err.message : err})`,\n );\n }\n }\n}\n\n/**\n * Test hook: forget the registration and remove the integration from `ai`'s\n * global list. `ai` has no unregister call, so production code never does\n * this; shutdown() unbinds instead.\n */\nexport function unregisterVercelAI(): void {\n registered = false;\n everBound = false;\n warnedUnbound = false;\n unbindVercelAI();\n const g = globalThis as { AI_SDK_TELEMETRY_INTEGRATIONS?: unknown[] };\n if (Array.isArray(g.AI_SDK_TELEMETRY_INTEGRATIONS)) {\n g.AI_SDK_TELEMETRY_INTEGRATIONS = g.AI_SDK_TELEMETRY_INTEGRATIONS.filter(\n (i) => !isSightIntegration(i),\n );\n }\n}\n\n// ── Exported for tests ────────────────────────────────────────────────────\nexport const _aiInternals = {\n userTextOf,\n systemTextOf,\n sessionFromContext,\n isBound: () => bound !== null,\n trackedCalls: () => calls.size,\n registeredCount: (): number => globalIntegrations().filter(isSightIntegration).length,\n};\n","/**\n * OTel provider setup.\n *\n * Registers a NodeTracerProvider with the ProbeSpanProcessor. Called once at\n * Probe.init() before any instrumentation is enabled.\n *\n * If the customer has already registered an OTel provider (e.g. Sentry, DD,\n * or their own), we do NOT overwrite it — instead we add our SpanProcessor\n * to the existing provider. This preserves customer observability.\n *\n * Trade-off: if the customer's provider does not expose addSpanProcessor\n * (older versions), we register our own NodeTracerProvider; OTel keeps the\n * first-registered global, so capture may not attach in that case. Chapter\n * 2 ships the pattern; hardening for edge cases lands with the first\n * enterprise customer.\n */\n\nimport { trace } from '@opentelemetry/api';\nimport { ProbeSpanProcessor, type CaptureFn } from './otel-processor.js';\nimport { unbindWrapOpenAI } from './wrap-openai.js';\nimport { unbindVercelAI } from './vercel-ai.js';\n\ntype MinimalProbeState = {\n config: { deployment: string; debug: boolean };\n persona: { slug: string } | null;\n sessions: Map<\n string,\n {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n // Auto version-hash stamping target (see otel-processor.ts).\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n }\n >;\n signatureMatchers: Map<string, unknown>;\n};\n\nlet installedProcessor: ProbeSpanProcessor | null = null;\n\nexport function setupOtelProvider(\n state: MinimalProbeState,\n captureFn: CaptureFn,\n): void {\n if (installedProcessor !== null) {\n // Already set up: a registered span processor cannot be removed from\n // the provider, so re-init REBINDS the existing one to the new state\n // instead of leaving it pointed at a dead state object (audit R1).\n installedProcessor.rebind(state, captureFn);\n return;\n }\n installedProcessor = new ProbeSpanProcessor(state, captureFn);\n\n const currentProvider = trace.getTracerProvider() as {\n addSpanProcessor?: (p: ProbeSpanProcessor) => void;\n };\n\n // Case 1: customer has already registered a provider that supports addSpanProcessor.\n if (typeof currentProvider.addSpanProcessor === 'function') {\n currentProvider.addSpanProcessor(installedProcessor);\n return;\n }\n\n // Case 2: no provider registered yet (NoopTracerProvider). Create a new one.\n // We use dynamic import so the base @opentelemetry/sdk-trace-node cost\n // is only paid when Probe.init() is called (not on module load).\n void import('@opentelemetry/sdk-trace-node').then((mod) => {\n const provider = new mod.NodeTracerProvider({\n spanProcessors: [installedProcessor!],\n });\n provider.register();\n });\n}\n\nexport function teardownOtelProvider(): void {\n if (installedProcessor) {\n void installedProcessor.shutdown();\n installedProcessor = null;\n }\n}\n\n/**\n * Detach the installed processor from Probe state without tearing the\n * provider down (Probe.shutdown): post-shutdown LLM calls stop feeding the\n * orphaned state (audit R1 — the old behavior grew a dead sessions map\n * forever); a later re-init rebinds via setupOtelProvider.\n */\nexport function detachOtelState(): void {\n installedProcessor?.rebind(null);\n // The instance-wrapping path shares the same lifecycle: post-shutdown\n // LLM calls through a wrapped client must stop feeding the dead state.\n unbindWrapOpenAI();\n // So does the `ai` telemetry integration: it stays registered with `ai`\n // (there is no unregister call) and stops capturing.\n unbindVercelAI();\n}\n","/**\n * OpenAI instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-openai. Its spans flow through the\n * globally-registered ProbeSpanProcessor (see ./setup.ts and ./otel-processor.ts).\n *\n * Config: traceContent + enrichTokens on (customer wanting no-content mode\n * can flip Probe.init({ debug: false, sampleRate: 0 }) or override via\n * environment variable OTEL_INSTRUMENTATION_OPENAI_TRACE_CONTENT=false).\n *\n * This adapter also handles Mercury-2 via OpenAI SDK baseURL override; the\n * ProbeSpanProcessor tags `provider=inception` when gen_ai.request.model\n * starts with 'mercury'. Customers using Inception need no separate adapter.\n */\n\nimport { hasWrappedClient } from './wrap-openai.js';\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\nlet instrumentation: any = null;\n\nexport async function registerOpenAI(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-openai');\n instrumentation = new mod.OpenAIInstrumentation({\n enrichTokens: true,\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n console.error(\n `[sight/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n // The patch attaches only under CommonJS, only when `openai` loads\n // after init, and only for the instrumentation's declared version\n // range. Each of those failures is otherwise silent: requests succeed,\n // zero turns captured through the patch. Verify and say so, unless\n // the host captures through a wrapped client (see patchWarning).\n void verifyPatchAttached();\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[sight/openai] instrumentation not enabled (${msg}); library not installed?`);\n }\n }\n}\n\n/**\n * True when the openai module's chat-completions create function shows no\n * shimmer wrap marker, meaning the module patch did NOT attach and\n * autocapture through the patch path will record nothing. Pure and\n * exported for tests; tolerant of unknown module shapes (treated as\n * detached, which errs on the side of warning).\n */\nexport function isPatchDetached(mod: any): boolean {\n const OpenAIClass = mod?.default ?? mod?.OpenAI;\n const create = OpenAIClass?.Chat?.Completions?.prototype?.create;\n if (typeof create !== 'function') return true;\n return (create as { __wrapped?: boolean }).__wrapped !== true;\n}\n\n/**\n * The startup line for a module patch that did not attach, or null when\n * nothing should print. Pure and exported for tests.\n *\n * What the check knows: the shape of the loaded `openai` module, and\n * whether the host has wrapped a client. It cannot see calls made through\n * an unwrapped client. So:\n * - patch attached: nothing to say.\n * - patch detached, a client is wrapped: nothing to say. The wrapped\n * client captures on its own; the patch is not the path in use.\n * - patch detached, no client wrapped yet: say exactly what is and is\n * not captured, without claiming that a later wrapped client is dead.\n */\nexport function patchWarning(mod: any, wrappedClientInUse: boolean): string | null {\n if (!isPatchDetached(mod)) return null;\n if (wrappedClientInUse) return null;\n const version: string | undefined = mod?.default?.VERSION ?? mod?.VERSION;\n return (\n `[sight] OpenAI module patching did not attach` +\n (version ? ` (openai v${version})` : '') +\n `. This happens on openai >=5, under ESM, or when 'openai' loads before init. ` +\n `Calls through a client passed to wrapOpenAI() are captured; calls through an unwrapped OpenAI client are not. ` +\n `import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()).`\n );\n}\n\n/** Exported for tests; init runs it once after enabling the module patch. */\nexport async function verifyPatchAttached(): Promise<void> {\n try {\n const mod: any = await import('openai');\n // Read at check time, after the dynamic imports above have settled, so\n // a client wrapped during startup (before or after init) is counted.\n const line = patchWarning(mod, hasWrappedClient());\n // NOT debug-gated on purpose: a dead capture path must never be silent.\n if (line !== null) console.warn(line);\n } catch {\n // openai not installed in this process: nothing to verify.\n }\n}\n\nexport function unregisterOpenAI(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * Anthropic instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-anthropic. Cache-token attributes\n * (gen_ai.usage.cache_read_input_tokens, cache_creation_input_tokens) are\n * promoted onto the CapturedTurn payload by the shared processor.\n *\n * Anthropic finish reasons preserve their raw shape ('end_turn',\n * 'max_tokens', 'stop_sequence', 'tool_use') rather than being normalised to\n * OpenAI-style 'stop' / 'length'. Downstream analytics can pattern-match on\n * the raw value.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nlet instrumentation: any = null;\n\nexport async function registerAnthropic(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-anthropic');\n instrumentation = new mod.AnthropicInstrumentation({\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n\n console.error(\n `[sight/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n\n console.warn(\n `[sight/anthropic] instrumentation not enabled (${msg}); library not installed?`,\n );\n }\n }\n}\n\nexport function unregisterAnthropic(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * LangChain instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-langchain. The shared ProbeSpanProcessor\n * filters LangChain spans by `traceloop.span.kind === \"agent\"` (actual LLM\n * calls; skips 'workflow' / 'task' chain scaffolding and 'tool' invocations).\n *\n * Double-instrumentation note: when a LangChain chain calls into OpenAI or\n * Anthropic, BOTH the langchain instrumentation and the provider\n * instrumentation fire on the same traceId. The ProbeSpanProcessor's dedup\n * cache (keyed on traceId with 5s TTL) drops the second one so we never\n * double-capture a turn.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nlet instrumentation: any = null;\n\nexport async function registerLangChain(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-langchain');\n instrumentation = new mod.LangChainInstrumentation({\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n\n console.error(\n `[sight/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n\n console.warn(\n `[sight/langchain] instrumentation not enabled (${msg}); library not installed?`,\n );\n }\n }\n}\n\nexport function unregisterLangChain(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * LangGraph instrumentation adapter.\n *\n * LangGraph reuses LangChain callbacks, so @traceloop/instrumentation-langchain\n * already fires for LangGraph nodes. The catch: Traceloop tags them as generic\n * `traceloop.span.kind: \"task\"` without graph topology hints (node id, thread,\n * edges). Customers who want future Structure-axis flow-state metrics\n * (Chapter 5 research direction; nothing ships today) to work with LangGraph\n * need to pass the node/thread identity into their RunnableConfig.\n *\n * This adapter itself is a no-op registration: the actual span emission is\n * covered by ./langchain.ts (Traceloop's callback handler). The value we add\n * here is DOCUMENTATION of the tag pattern (below) plus a marker that\n * LangGraph coverage is active.\n *\n * Recommended customer pattern (documented in packages/sdk/README.md):\n *\n * await graph.invoke(state, {\n * configurable: { thread_id: sessionId },\n * tags: ['langgraph', 'node:planner', 'thread:' + sessionId],\n * });\n *\n * The `tags` array surfaces as span attribute `traceloop.association.properties.tags`\n * which lands on the CapturedTurn.payload._otel debug block. Chapter 5 flow-\n * state calibration can pattern-match on the 'node:*' prefix.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerLangGraph(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n\n console.log(\n '[sight/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology',\n );\n }\n}\n\nexport function unregisterLangGraph(): void {\n registered = false;\n}\n","/**\n * LiteLLM adapter: a no-op.\n *\n * LiteLLM is Python; this SDK is TypeScript and does not capture LiteLLM\n * traffic. The registration exists so that, in debug mode, a host that\n * expected LiteLLM capture is told why there is none.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerLiteLLM(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n\n console.log(\n '[sight/litellm] LiteLLM (Python) traffic is not captured by this SDK',\n );\n }\n}\n\nexport function unregisterLiteLLM(): void {\n registered = false;\n}\n","/**\n * Mercury-2 adapter (Inception Labs, diffusion-class API).\n *\n * 99% of customer traffic to Mercury-2 goes through the OpenAI SDK with\n * `baseURL: 'https://api.inceptionlabs.ai/v1'`, which means\n * @traceloop/instrumentation-openai already captures every call and the\n * ProbeSpanProcessor tags `provider=inception` when\n * `gen_ai.request.model` starts with 'mercury'. No dedicated adapter needed\n * for that path.\n *\n * Fallback: for customers using a hand-rolled fetch call to the Inception\n * endpoint (rare), this adapter installs a fetch wrapper that emits an OTel\n * span for the request so the shared processor picks it up. Registered only\n * when Sight.init() is called with { instrumentation: { mercuryFetchWrapper:\n * true } } (opt-in; the default OpenAI SDK path covers everything).\n *\n * We do NOT ship a bespoke Mercury client. The maintenance cost of a\n * provider-specific wrapper for a single provider is not worth it when the\n * OpenAI-SDK path covers 99% of usage.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\nlet originalFetch: typeof globalThis.fetch | null = null;\n\nconst INCEPTION_HOSTS = ['api.inceptionlabs.ai', 'api.inception.ai'];\n\nfunction isInceptionUrl(url: string): boolean {\n return INCEPTION_HOSTS.some((h) => url.includes(h));\n}\n\nexport async function registerMercury(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n\n console.log(\n '[sight/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route',\n );\n }\n}\n\n/**\n * Optional fetch monkey-patch for hand-rolled fetch calls to Inception.\n * Called only if the customer opts in explicitly (rare).\n */\nexport function enableMercuryFetchWrapper(state: ProbeState): void {\n if (originalFetch) return;\n originalFetch = globalThis.fetch;\n\n globalThis.fetch = async (input: string | URL | Request, init?: RequestInit) => {\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : input.url;\n if (!isInceptionUrl(url)) {\n return originalFetch!(input, init);\n }\n\n // Emit an OTel span so the shared processor picks it up.\n const { trace, SpanStatusCode } = await import('@opentelemetry/api');\n const tracer = trace.getTracer('@cultured_computer/sight/mercury');\n return tracer.startActiveSpan(`chat mercury-2`, async (span) => {\n span.setAttribute('gen_ai.system', 'inception');\n span.setAttribute('gen_ai.operation.name', 'chat');\n span.setAttribute('gen_ai.request.model', 'mercury-2');\n try {\n const response = await originalFetch!(input, init);\n if (!response.ok) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });\n }\n return response;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n throw err;\n } finally {\n span.end();\n if (state.config.debug) {\n\n console.log(`[sight/mercury] captured fetch to ${url}`);\n }\n }\n });\n };\n}\n\nexport function unregisterMercury(): void {\n if (originalFetch) {\n globalThis.fetch = originalFetch;\n originalFetch = null;\n }\n registered = false;\n}\n","/**\n * Instrumentation registry.\n *\n * Each adapter enables its target library's OTel instrumentation (or, for\n * Mercury-2, documents / opts into the customer wiring). The emitted spans\n * flow through the shared ProbeSpanProcessor which maps gen_ai.*\n * semantic-convention attributes to CapturedTurn.payload and calls\n * Probe.captureTurn(). The Vercel AI SDK adapter is not span based: it\n * registers a telemetry integration with `ai` (see vercel-ai.ts).\n *\n * Session correlation: OTel Baggage via session-context.ts. Customers wrap\n * their conversation in Probe.withSession(sessionId, async () => { ... }).\n * Adapters do not need to know about sessions; the processor reads baggage\n * on span end.\n */\n\nimport type { CaptureFn } from './otel-processor.js';\nimport { setupOtelProvider } from './setup.js';\nimport { bindWrapOpenAI } from './wrap-openai.js';\nimport { registerOpenAI } from './openai.js';\nimport { registerAnthropic } from './anthropic.js';\nimport { registerLangChain } from './langchain.js';\nimport { registerLangGraph } from './langgraph.js';\nimport { registerVercelAI } from './vercel-ai.js';\nimport { registerLiteLLM } from './litellm.js';\nimport { registerMercury } from './mercury.js';\n\nexport { withSession, getCurrentSessionId } from './session-context.js';\nexport { setupOtelProvider, teardownOtelProvider, detachOtelState } from './setup.js';\nexport { ProbeSpanProcessor } from './otel-processor.js';\nexport type { CaptureFn, CaptureHints } from './otel-processor.js';\nexport { wrapOpenAI } from './wrap-openai.js';\nexport { sightTelemetry } from './vercel-ai.js';\nexport type { SightAiTelemetry, SightAiTelemetryOptions } from './vercel-ai.js';\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<\n string,\n {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n // Auto version-hash stamping target (see otel-processor.ts).\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n }\n >;\n signatureMatchers: Map<string, unknown>;\n};\n\n/**\n * Register all instrumentation adapters at Probe.init() time.\n *\n * 1. Set up the OTel provider + ProbeSpanProcessor (once per process).\n * 2. Enable each adapter's instrumentation. Adapters no-op if the target\n * library is not installed in the customer's process.\n */\nexport function registerAllInstrumentations(\n state: ProbeState,\n captureFn: CaptureFn,\n): void {\n setupOtelProvider(state, captureFn);\n\n // Bind the explicit client-wrapping path (wrapOpenAI). Wrapping may have\n // happened before init; capture starts the moment this binding lands.\n bindWrapOpenAI(state, captureFn);\n\n const registrations: Array<Promise<void>> = [\n registerOpenAI(state),\n registerAnthropic(state),\n registerLangChain(state),\n registerLangGraph(state),\n registerVercelAI(state, captureFn),\n registerLiteLLM(state),\n registerMercury(state),\n ];\n\n Promise.allSettled(registrations).then((results) => {\n if (!state.config.debug) return;\n for (const result of results) {\n if (result.status === 'rejected') {\n\n console.error(`[sight] adapter register rejected: ${result.reason}`);\n }\n }\n });\n}\n","/**\n * Signature-phrase matcher.\n *\n * Per-persona regex matching for voice consistency (Day 1 per PROBE.md §2).\n * Customer authors signature phrases at Probe.init({ persona: { signaturePhrases: [...] } }).\n * The SDK edge or a worker computes matches per turn and includes the list\n * of matched slugs in the turn payload.\n *\n * Signature phrase shape: { slug, pattern, description? }. The pattern is\n * either a plain string (case-insensitive whole-token match) or a regex\n * source string with optional flags. Slug is what appears in the matches\n * array; it is not the pattern.\n *\n * Trivial by design. Voice consistency at the embedding level lives in the\n * Chapter 5 Dream column (PSV representation with per-deployment STEL\n * calibration); this is the Day-1 heuristic that ships from ingest data alone.\n */\n\nexport type SignaturePhrase =\n | {\n /** Slug that appears in the matches array. Unique per persona. */\n slug: string;\n /** Plain-text phrase; matched case-insensitive with word boundaries. */\n phrase: string;\n description?: string;\n }\n | {\n slug: string;\n /** Regex source string. Compiled once per matcher construction. */\n regex: string;\n /** Regex flags (default: 'i'). */\n flags?: string;\n description?: string;\n };\n\ntype CompiledPhrase = {\n slug: string;\n pattern: RegExp;\n};\n\n/**\n * Compile a set of signature phrases into a matcher. Compile once at\n * Probe.init() and reuse per turn to avoid regex construction on every call.\n *\n * Invalid regex patterns are dropped with a stderr warning; other phrases\n * continue to match.\n */\nexport function compileSignaturePhrases(phrases: SignaturePhrase[]): CompiledPhrase[] {\n const compiled: CompiledPhrase[] = [];\n for (const p of phrases) {\n try {\n if ('phrase' in p) {\n const escaped = p.phrase.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // Only add \\b anchors where the phrase edge is a word character.\n // Otherwise \\b would require an impossible boundary next to punctuation.\n const startAnchor = /^\\w/.test(p.phrase) ? '\\\\b' : '';\n const endAnchor = /\\w$/.test(p.phrase) ? '\\\\b' : '';\n compiled.push({\n slug: p.slug,\n pattern: new RegExp(`${startAnchor}${escaped}${endAnchor}`, 'i'),\n });\n } else {\n compiled.push({\n slug: p.slug,\n pattern: new RegExp(p.regex, p.flags ?? 'i'),\n });\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n\n console.warn(`[classifier/signature-phrase] invalid pattern for slug=${p.slug}: ${msg}`);\n }\n }\n return compiled;\n}\n\n/**\n * Match a text against a compiled signature-phrase set. Returns the list of\n * matched slugs (unique, in the order the phrases were compiled).\n *\n * Empty text or empty compiled set returns [].\n */\nexport function matchSignaturePhrases(\n text: string,\n compiled: CompiledPhrase[],\n): string[] {\n if (!text || compiled.length === 0) return [];\n const matches: string[] = [];\n for (const c of compiled) {\n if (c.pattern.test(text)) matches.push(c.slug);\n }\n return matches;\n}\n","/**\n * The four gap-class families (the Zoom milestone's elevated Z2;\n * core.effectiveness predicate tier) — pure computations over imported\n * records (sessions with their turns + spans), testable without a\n * database. The GENERALIZATION IS STRUCTURAL: every class keys on a\n * telemetry channel and a tool CLASS (the caller passes the\n * per-deployment name→class map), never on a vendor's tool names —\n * Zoom's map is the first instance, a deployer's map is their own\n * definition config (PLAN-2026-07-21: generalized body, per-deployment\n * meaning).\n *\n * Honesty boundary (each family names its own):\n * kb.retrieval-attribution — REFERENCE-FREE structural candidates\n * (3-gram containment + ignorance cues), NOT RAGAS faithfulness;\n * context precision/recall and faithfulness are Z3 judge tiers.\n * Attribution is EXCLUSIVE (retrieval-wrong gates the usage\n * judgment; the unclear band is disclosed) — classes sum to\n * kbFired, never more, never silently less.\n * tooltrajectory.failure-mode — loops/errors/non-termination computed\n * from span sequences + result provenance; wrong-tool is NOT\n * computed (a judgment; MAST's full 14-mode taxonomy is the Z3\n * anchor, κ=0.88 per Cemri 2025).\n * repair.misunderstanding — rephrase/re-ask chains by containment\n * (Schegloff 1977 repair is the anchor; the classifier's\n * conversation-management family is the preliminary lens).\n * interactivity.barge-in-friction — rates/positions/recovery\n * computed; whether a barge-in WAS friction is Z3 (turn-taking /\n * full-duplex literature anchors).\n *\n * All examples are REFERENCES (sessionExternalId + turnIndex) — never\n * verbatim text (the corpus's no-verbatim-in-artifacts rule,\n * DATASETS.md zoom-zva-corpus).\n */\n\n// ── The record shapes the families compute over ─────────────────────────\n\nexport interface GapEnvironmentEvent {\n event: string;\n at?: string;\n meta?: Record<string, unknown>;\n}\n\nexport interface GapTurn {\n turnIndex: number;\n startedAt?: string | null;\n agentText?: string | null;\n userReplyText?: string | null;\n initiatingUserText?: string | null;\n environmentEventStream?: GapEnvironmentEvent[];\n /** probe_user_grounding_move — the user's grounding moves on this turn\n ('repair-initiate' = the user initiates repair against the agent's\n prior turn — the corrections-unmet predicate's trigger; E2). NEVER\n the deprecated probe_user_correction_signals column (Amendment H:\n subsumed by discourse_relation + grounding_move). */\n userGroundingMove?: string[] | null;\n /** probe_pair_completed — the pair machinery's own completion mark\n (false = pair opened, never completed; null = no pair opened). */\n pairCompleted?: boolean | null;\n}\n\nexport interface GapSpan {\n turnIndex: number;\n spanType: string;\n name: string;\n contractVersion?: number;\n status?: \"unset\" | \"ok\" | \"error\";\n error?: string | null;\n durationMs?: number | null;\n tokensInput?: number | null;\n tokensOutput?: number | null;\n outputState?:\n | \"captured\"\n | \"empty\"\n | \"not_captured\"\n | \"redacted\"\n | \"unavailable\";\n outputPayload?: unknown;\n attributes?: Record<string, unknown> | null;\n}\n\nfunction spanOutputRecord(span: GapSpan): Record<string, unknown> | null {\n if (span.contractVersion !== 2 || span.outputState !== 'captured') return null;\n const value = span.outputPayload;\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction spanChunks(span: GapSpan): unknown[] {\n if (span.contractVersion === 2) {\n const chunks = spanOutputRecord(span)?.['chunks'];\n return Array.isArray(chunks) ? chunks : [];\n }\n const chunks = span.attributes?.['chunks'];\n return Array.isArray(chunks) ? chunks : [];\n}\n\nfunction spanIsToolError(span: GapSpan): boolean {\n return span.contractVersion === 2\n ? span.status === 'error'\n : isToolErrorishAttributes(span.attributes ?? null);\n}\n\nexport interface GapSession {\n externalId: string;\n turns: GapTurn[];\n spans: GapSpan[];\n}\n\nexport interface GapExample {\n sessionExternalId: string;\n turnIndex: number;\n note: string;\n}\n\n/** The per-deployment generalization knob: a name→class map OR a\n classifier function (defaultToolClass for pattern-based defaults). */\nexport type ToolClassifier = ((name: string) => string) | Record<string, string>;\n\n/**\n * The pattern-based default tool classifier — the generalized body when\n * no per-deployment map exists. Zoom's explicit map ships in\n * fixtures/zva/effectiveness-definitions.mjs as the first instance;\n * anything unmatched falls to 'other' (a finding, never an error).\n *\n * NOT a duplicate of session-insights' isEscalationKind (P1-R2 note):\n * this predicate classifies TOOL NAMES (`transfer_to_agent` the\n * function) into tool classes; that one classifies OUTCOME KINDS\n * (`transferred_to_sales` the emitted event). Same vocabulary, two\n * domains — merging them would let a tool-name pattern claim an outcome\n * happened.\n */\nexport function defaultToolClass(name: string): string {\n const n = name.toLowerCase();\n if (/knowledge|kb|retriev|article|faq/.test(n)) return 'kb';\n if (/otp|password|passcode|verif|one.?time/.test(n)) return 'auth_otp';\n if (/transfer|hand.?off|escalat|live.?agent|human.?agent/.test(n)) return 'transfer';\n if (/end_conversation|hangup|hang.?up|end_call|goodbye|close_conversation/.test(n)) return 'end';\n if (/survey|csat|nps|feedback/.test(n)) return 'survey';\n if (/sms|email|message|notify/.test(n)) return 'comms';\n if (/^get_|lookup|search|find|fetch|query|detail|entitle|eligib|existing|is_/.test(n)) return 'lookup';\n if (/^set_|config|admin|assign|route/.test(n)) return 'admin';\n return 'other';\n}\n\n/** Resolve the classifier to a function. */\nfunction classifyTool(tc: ToolClassifier, name: string): string {\n return typeof tc === 'function' ? tc(name) : (tc[name] ?? 'other');\n}\n\n\nexport interface KbAttributionResult {\n // EXCLUSIVE classes (the RAGChecker three-way split made honest): each\n // fired lookup lands in exactly one of retrievedWrong / grounded /\n // ignored / indeterminate / noChunksRecorded, so the classes always sum\n // to kbFired — the rows reconcile on inspection, never 112 > 96.\n counts: {\n needsRetrieval: number;\n kbFired: number;\n grounded: number;\n retrievedWrong: number;\n ignored: number;\n /** Usage neither visibly grounded nor clearly ignored (the 0.05–0.2\n band) — disclosed, never silently dropped. */\n indeterminate: number;\n /** Lookup fired but no chunks were recorded on the span — a telemetry\n gap, counted separately so the classes still reconcile. */\n noChunksRecorded: number;\n notRetrieved: number;\n };\n examples: { retrievedWrong: GapExample[]; ignored: GapExample[]; notRetrieved: GapExample[] };\n}\nexport interface ToolFailureResult {\n counts: { loops: number; toolErrors: number; sessionsWithErrors: number; nonTermination: number };\n /** Per-tool breakdown — the card's \"most failing / most looped tool\"\n rows. Counts loop-RUNS and error events keyed on the deployer's own\n tool name (their vocabulary, unhumanized). */\n byTool: { errors: Record<string, number>; loops: Record<string, number> };\n examples: { loops: GapExample[]; toolErrors: GapExample[]; nonTermination: GapExample[] };\n}\nexport interface RepairResult {\n counts: { userRephrase: number; userVerbatim: number; agentReask: number };\n examples: { userRephrase: GapExample[]; agentReask: GapExample[] };\n}\nexport interface BargeResult {\n counts: { events: number; killed: number };\n positionsMs: number[];\n recoveryMs: number[];\n examples: GapExample[];\n}\n\n// ── Text helpers (the Contain metric — Zhang 2026 appendix's 3-gram\n// containment, reused as the reference-free overlap proxy) ───────────────\n\nfunction ngrams(text: unknown, n = 3): Set<string> {\n const words = String(text ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ')\n .split(/\\s+/)\n .filter(Boolean);\n if (words.length === 0) return new Set();\n if (words.length < n) return new Set(words);\n const out = new Set<string>();\n for (let i = 0; i + n <= words.length; i++) out.add(words.slice(i, i + n).join(' '));\n return out;\n}\n\n/** Asymmetric containment: how much of a's n-gram mass appears in b. */\nexport function contain(a: unknown, b: unknown): number {\n const A = ngrams(a);\n const B = ngrams(b);\n if (A.size === 0) return 0;\n let hit = 0;\n for (const g of A) if (B.has(g)) hit++;\n return hit / A.size;\n}\n\nconst IGNORANCE_RE =\n /unable to find|can't find|couldn't find|could not find|not able to find|don't have (that|any|the) information|do not have (that|any|the) information|no information|i was unable/i;\nconst QUESTION_RE =\n /^(hi |hello |okay[, ]|um[, ]|uh[, ])*\\s*(who|what|when|where|why|how|can|could|is|are|do|does|did|may|might|should)\\b|\\?\\s*$|how (to|do|can)|what is|where is|can you (tell|help|check|find)/i;\nconst SILENCE_RE = /^\\((user is silent|user connected)/i;\n/** Conventionalized open/close formulas — verbatim by convention, not by\n misunderstanding (\"Anything else I can help with today?\" re-asked is\n a closing ritual, not a repair loop). Excluded from re-ask detection. */\nconst CLOSING_FORMULA_RE =\n /anything else|is there anything|how (can|may) i (help|assist)|thank(s| you) for (calling|your time)|have a (great|good|wonderful) (day|one|rest)/i;\n\nconst STOPWORDS = new Set(\n 'the a an to of and or is are was were do does did how what where when who why which can could should would may might i you your my me it its this that these those in on for with at by from as be been being am not no yes okay ok um uh hi hello please thanks thank'.split(' '),\n);\n\n/** Stopword-stripped unigram containment — the IR-style query↔document\n relevance proxy (robust to phrasing where 3-gram containment is not:\n \"how do i change my billing email\" vs \"change the billing email\n address\" shares every content token). */\nfunction containTokens(a: unknown, b: unknown): number {\n const tok = (s: unknown): string[] =>\n String(s ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ')\n .split(/\\s+/)\n .filter((w) => w && !STOPWORDS.has(w));\n const A = new Set(tok(a));\n const B = new Set(tok(b));\n if (A.size === 0) return 0;\n let hit = 0;\n for (const w of A) if (B.has(w)) hit++;\n return hit / A.size;\n}\n\nfunction isQuestion(text: unknown): boolean {\n return typeof text === 'string' && QUESTION_RE.test(text.trim());\n}\n\n/** Agent re-ask shape: interrogative OR an imperative service question\n (\"please provide the phone number…\" — no '?' anywhere). */\nfunction isQuestionShape(text: unknown): boolean {\n return (\n isQuestion(text) ||\n (typeof text === 'string' &&\n (/\\?/.test(text) || /please (provide|tell|confirm|say|enter|share|verify)/i.test(text)))\n );\n}\n\n// ── Family 1: kb.retrieval-attribution ──────────────────────────────────\n\nconst WRONG_MAX = 0.2; // stopword-stripped token containment under which the retrieval looks irrelevant to the question\nconst IGNORED_MAX = 0.05; // answer↔chunk 3-gram containment under which the answer ignores retrieval\nconst GROUNDED_MIN = 0.2; // answer↔chunk 3-gram containment above which usage is visible\n\n/** The per-turn KB classes — the EXCLUSIVE attribution (retrieval-wrong\n gates the usage judgment; the unclear band is disclosed). */\nexport type KbTurnClass =\n | 'grounded'\n | 'retrievedWrong'\n | 'ignored'\n | 'indeterminate'\n | 'noChunksRecorded';\n\nexport type KbTurnAttribution = {\n turnIndex: number;\n cls: KbTurnClass;\n /** The answer↔chunk usage score (null on the gated classes). */\n usage: number | null;\n /** The reply carried an ignorance cue (drives the ignored example note). */\n ignoranceCue: boolean;\n};\n\n/**\n * THE per-turn KB classifier (D26 extraction): kbRetrievalAttribution's\n * counts are a fold over these classes, and the grouped drill's flagged\n * set reads the same classes — one definition, never a re-derived\n * lookalike. Only turns that FIRED a lookup are attributed;\n * needsRetrieval / notRetrieved are question-shape judgments, not\n * retrieval classes, and stay in the counting wrapper.\n */\nexport function attributeKbTurns(session: GapSession, toolClasses: ToolClassifier): KbTurnAttribution[] {\n const kbSpans = session.spans.filter((s: GapSpan) => classifyTool(toolClasses, s.name) === 'kb');\n const out: KbTurnAttribution[] = [];\n for (const turn of session.turns) {\n const userText = turn.userReplyText ?? turn.initiatingUserText ?? null;\n const kb = kbSpans.filter((s) => s.turnIndex === turn.turnIndex);\n if (kb.length === 0) continue;\n const chunkCorpus = kb\n .flatMap(spanChunks)\n .map((c: any) => `${c.articleTitle ?? ''} ${c.chunkContent ?? ''}`)\n .join('\\n');\n // The telemetry-gap bucket: the lookup fired but its chunks weren't\n // recorded — counted so the classes reconcile, never silently skipped.\n if (chunkCorpus.trim().length === 0) {\n out.push({ turnIndex: turn.turnIndex, cls: 'noChunksRecorded', usage: null, ignoranceCue: false });\n continue;\n }\n // EXCLUSIVE attribution: when the retrieval missed the question, the\n // usage judgment is a category error — you cannot blame grounding for\n // ignoring irrelevant chunks (the RAGChecker split, applied as GATING,\n // not as an overlapping axis). retrievedWrong ends the classification.\n if (userText && containTokens(userText, chunkCorpus) < WRONG_MAX) {\n out.push({ turnIndex: turn.turnIndex, cls: 'retrievedWrong', usage: null, ignoranceCue: false });\n continue;\n }\n const usage = contain(turn.agentText ?? '', chunkCorpus);\n const ignoranceCue = IGNORANCE_RE.test(turn.agentText ?? '');\n if (usage >= GROUNDED_MIN) {\n out.push({ turnIndex: turn.turnIndex, cls: 'grounded', usage, ignoranceCue });\n } else if (usage < IGNORED_MAX || ignoranceCue) {\n out.push({ turnIndex: turn.turnIndex, cls: 'ignored', usage, ignoranceCue });\n } else {\n // The disclosed middle band: usage neither visible nor clearly\n // absent (paraphrase-heavy synthesis lands here). Counted, never\n // hidden — the classes sum to kbFired.\n out.push({ turnIndex: turn.turnIndex, cls: 'indeterminate', usage, ignoranceCue });\n }\n }\n return out;\n}\n\nexport function kbRetrievalAttribution(session: GapSession, toolClasses: ToolClassifier): KbAttributionResult {\n const out: KbAttributionResult = { counts: { needsRetrieval: 0, kbFired: 0, grounded: 0, retrievedWrong: 0, ignored: 0, indeterminate: 0, noChunksRecorded: 0, notRetrieved: 0 }, examples: { retrievedWrong: [], ignored: [], notRetrieved: [] } };\n // The count fold over the SHARED per-turn classifier (attributeKbTurns\n // owns every class boundary; this wrapper adds the question-shape\n // counts, which are not retrieval classes).\n const attributed = attributeKbTurns(session, toolClasses);\n const attributedTurnIndices = new Set(attributed.map((a) => a.turnIndex));\n for (const a of attributed) {\n out.counts.kbFired++;\n out.counts[a.cls]++;\n if (a.cls === 'retrievedWrong' && out.examples.retrievedWrong.length < 5) {\n out.examples.retrievedWrong.push({ sessionExternalId: session.externalId, turnIndex: a.turnIndex, note: `query↔chunk token containment < ${WRONG_MAX} (stopword-stripped)` });\n }\n if (a.cls === 'ignored' && out.examples.ignored.length < 5) {\n out.examples.ignored.push({ sessionExternalId: session.externalId, turnIndex: a.turnIndex, note: `answer↔chunk containment ${(a.usage ?? 0).toFixed(3)}${a.ignoranceCue ? ' + ignorance cue' : ''}` });\n }\n }\n for (const turn of session.turns) {\n const userText = turn.userReplyText ?? turn.initiatingUserText ?? null;\n const needsRetrieval = isQuestion(userText);\n if (needsRetrieval) out.counts.needsRetrieval++;\n if (!attributedTurnIndices.has(turn.turnIndex) && needsRetrieval && IGNORANCE_RE.test(turn.agentText ?? '')) {\n out.counts.notRetrieved++;\n if (out.examples.notRetrieved.length < 5) {\n out.examples.notRetrieved.push({ sessionExternalId: session.externalId, turnIndex: turn.turnIndex, note: 'question-like user turn, no KB call, ignorance-claim reply' });\n }\n }\n }\n return out;\n}\n\n// ── Family 2: tooltrajectory.failure-mode ───────────────────────────────\n\n/**\n * The method version of the tool-error predicate below (F2, 2026-08-05).\n * v1: the success-whitelist + value-regex form (asserted failure from\n * unrecognized vocabulary; fired on routine flag writes — the \"84 tool\n * errors\" overcount). v2: affirmative-only result provenance (the raw\n * audit's correction: 84 → 60 on zoom-zva). Bumped on every predicate\n * change so an audit packet can name the method its numbers came from —\n * judges carry versions; computed predicates carry them too, because a\n * number that changes under a method revision must be able to SAY so.\n */\nexport const TOOL_ERROR_PREDICATE_VERSION = 2;\n\n/** Affirmative error vocabulary for STATUS-BEARING fields (status /\n responseType) — a field whose job is to report outcome counts as an\n error only when it SAYS so. The old success-whitelist asserted\n failure from any unrecognized word (the anti-theater violation the\n 2026-08-05 raw audit caught: routine vocab counted as errors). */\nconst TOOL_ERROR_STATUS_RE = /error|fail|invalid|denied|expired|timeout|exception/i;\n\n/** Variable updates report an error only through a variable NAMED for\n it (ani_error_message, lookup_failure, …) carrying a real value.\n The old value-regex fired on `false` booleans and `Unknown` defaults\n in ordinary variables — 45 of Zoom's \"84 tool errors\" were routine\n flag writes (raw audit, 2026-08-05). */\nconst ERROR_VAR_NAME_RE = /error|fail/i;\nconst EMPTYISH_RE = /^(?:|null|undefined|none)$/i;\n\n/**\n * THE span-level tool-error predicate (D26 extraction, re-grounded\n * 2026-08-05): error arrives by AFFIRMATIVE result provenance —\n * explicit false status, an error-ish status/responseType word, error\n * logs, or an error-NAMED variable carrying a value. Never asserted\n * from unrecognized vocabulary (a status word we don't know is not a\n * failure), never from a boolean flag's value. status arrives as a\n * BOOLEAN in this telemetry (true = success — the 190-false-fire\n * lesson). tooltrajectory.failure-mode's error counts fold this, and\n * the grouped drill's flagged set reads the same predicate —\n * turn-level probe_error is a DIFFERENT instrument (the drill-audit\n * revert), never a substitute.\n */\nexport function isToolErrorishAttributes(a: Record<string, unknown> | null | undefined): boolean {\n if (!a) return false;\n const statusFail =\n a['status'] === false ||\n (typeof a['status'] === 'string' && TOOL_ERROR_STATUS_RE.test(a['status'] as string));\n const responseFail =\n typeof a['responseType'] === 'string' &&\n TOOL_ERROR_STATUS_RE.test(a['responseType'] as string);\n return (\n statusFail ||\n responseFail ||\n (Array.isArray(a['errorLogs']) && (a['errorLogs'] as unknown[]).length > 0) ||\n (Array.isArray(a['variableUpdated']) &&\n (a['variableUpdated'] as any[]).some(\n (v: any) =>\n ERROR_VAR_NAME_RE.test(String(v.variableName ?? '')) &&\n !EMPTYISH_RE.test(String(v.currentValue ?? '').trim()),\n ))\n );\n}\n\n/**\n * The turn indices of a session's tool-call spans carrying an error —\n * the family's error set read per turn (the D26 drill's flagged set).\n * Counts fold error EVENTS (a turn with two failing spans counts twice\n * there); this set dedupes to the turn, as a turns-page filter must.\n */\nexport function toolErrorTurnIndices(session: GapSession): number[] {\n const out = new Set<number>();\n for (const s of session.spans) {\n if (s.spanType !== 'tool_call') continue;\n if (spanIsToolError(s)) out.add(s.turnIndex);\n }\n return [...out].sort((a, b) => a - b);\n}\n\nexport function toolTrajectoryFailureMode(session: GapSession, toolClasses: ToolClassifier, outcomesByKind?: Set<string>): ToolFailureResult {\n const out: ToolFailureResult = {\n counts: { loops: 0, toolErrors: 0, sessionsWithErrors: 0, nonTermination: 0 },\n byTool: { errors: {}, loops: {} },\n examples: { loops: [], toolErrors: [], nonTermination: [] },\n };\n const tools = session.spans.filter((s) => s.spanType === 'tool_call');\n // Consecutive same-name runs ≥3 = loop.\n let run: { name: string; length: number; firstTurnIndex: number } | null = null;\n const flushRun = () => {\n if (run && run.length >= 3) {\n out.counts.loops++;\n out.byTool.loops[run.name] = (out.byTool.loops[run.name] ?? 0) + 1;\n if (out.examples.loops.length < 5) {\n out.examples.loops.push({ sessionExternalId: session.externalId, turnIndex: run.firstTurnIndex, note: `${run.name} × ${run.length} consecutive` });\n }\n }\n };\n for (const s of tools) {\n if (run && s.name === run.name) {\n run.length++;\n } else {\n flushRun();\n run = { name: s.name, length: 1, firstTurnIndex: s.turnIndex };\n }\n }\n flushRun();\n // Tool errors from result provenance — the SHARED predicate\n // (isToolErrorishAttributes owns the definition; the reason note for\n // the example is presentation, recomputed here).\n let sessionHasError = false;\n for (const s of tools) {\n if (spanIsToolError(s)) {\n const a = (s.attributes ?? {}) as any;\n const statusFail =\n a.status === false ||\n (typeof a.status === 'string' && TOOL_ERROR_STATUS_RE.test(a.status));\n const responseFail =\n typeof a.responseType === 'string' && TOOL_ERROR_STATUS_RE.test(a.responseType);\n out.counts.toolErrors++;\n out.byTool.errors[s.name] = (out.byTool.errors[s.name] ?? 0) + 1;\n sessionHasError = true;\n if (out.examples.toolErrors.length < 5) {\n const reason =\n a.variableUpdated?.find(\n (v: any) =>\n ERROR_VAR_NAME_RE.test(String(v.variableName ?? '')) &&\n !EMPTYISH_RE.test(String(v.currentValue ?? '').trim()),\n )?.currentValue ??\n (statusFail ? `status=${String(a.status)}` : null) ??\n (responseFail ? a.responseType : null) ??\n (s.contractVersion === 2 ? s.error ?? 'status=error' : 'errorLogs');\n out.examples.toolErrors.push({ sessionExternalId: session.externalId, turnIndex: s.turnIndex, note: `${s.name}: ${reason}` });\n }\n }\n }\n if (sessionHasError) out.counts.sessionsWithErrors++;\n // Non-termination: no ending outcome AND the tail is silence/empty.\n if ((outcomesByKind?.size ?? 0) === 0) {\n const last = session.turns[session.turns.length - 1];\n const tailSilent = SILENCE_RE.test(last?.userReplyText ?? '') || (last?.agentText ?? '') === '';\n if (tailSilent) {\n out.counts.nonTermination++;\n if (out.examples.nonTermination.length < 5) {\n out.examples.nonTermination.push({ sessionExternalId: session.externalId, turnIndex: last?.turnIndex ?? 0, note: 'no ending outcome; tail is silence/empty' });\n }\n }\n }\n return out;\n}\n\n// ── Family 3: repair.misunderstanding ───────────────────────────────────\n\n/** The content floor: \"yes / okay / thanks\" pairs repeat verbatim ~100%\n of the time and are conversation, not repair (the 963-false-fire\n lesson from the first prod run). Repetition only signals\n misunderstanding when BOTH sides carry ≥4 content words. */\nconst contentWords = (text: unknown): number =>\n String(text ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ')\n .split(/\\s+/)\n .filter((w: string) => w && !STOPWORDS.has(w)).length;\n\nexport interface RepairFlaggedTurn {\n turnIndex: number;\n /** The consecutive-pair containment that flagged it (provenance). */\n containment: number;\n}\n\n/**\n * THE repair family's flagged turns (D26 extraction): the SECOND turn of\n * each consecutive content pair meeting the family's bands — user\n * verbatim ≥0.9, user rephrase 0.5–0.9, agent re-ask ≥0.6 on a question\n * shape with closing formulas excluded. repairMisunderstanding's counts\n * are these lists' lengths; the grouped drill reads the same refs. (The\n * refs resolve to the pair's own turn — the pre-extraction code resolved\n * examples by text match, which could point at an earlier same-text\n * turn; counts were and are pair counts, unchanged.)\n */\nexport function repairFlaggedTurns(session: GapSession): {\n userRephrase: RepairFlaggedTurn[];\n userVerbatim: RepairFlaggedTurn[];\n agentReask: RepairFlaggedTurn[];\n} {\n const userTurns = session.turns.filter(\n (t) =>\n typeof t.userReplyText === 'string' &&\n !SILENCE_RE.test(t.userReplyText) &&\n contentWords(t.userReplyText) >= 4,\n );\n const userRephrase: RepairFlaggedTurn[] = [];\n const userVerbatim: RepairFlaggedTurn[] = [];\n for (let i = 0; i + 1 < userTurns.length; i++) {\n const c = contain(userTurns[i]!.userReplyText, userTurns[i + 1]!.userReplyText);\n if (c >= 0.9) userVerbatim.push({ turnIndex: userTurns[i + 1]!.turnIndex, containment: c });\n else if (c >= 0.5) userRephrase.push({ turnIndex: userTurns[i + 1]!.turnIndex, containment: c });\n }\n const agentTurns = session.turns.filter(\n (t) => typeof t.agentText === 'string' && contentWords(t.agentText) >= 4,\n );\n const agentReask: RepairFlaggedTurn[] = [];\n for (let i = 0; i + 1 < agentTurns.length; i++) {\n const c = contain(agentTurns[i]!.agentText, agentTurns[i + 1]!.agentText);\n if (\n c >= 0.6 &&\n isQuestionShape(agentTurns[i]!.agentText) &&\n !CLOSING_FORMULA_RE.test(agentTurns[i]!.agentText!)\n ) {\n agentReask.push({ turnIndex: agentTurns[i + 1]!.turnIndex, containment: c });\n }\n }\n return { userRephrase, userVerbatim, agentReask };\n}\n\nexport function repairMisunderstanding(session: GapSession): RepairResult {\n const flagged = repairFlaggedTurns(session);\n const out: RepairResult = {\n counts: {\n userRephrase: flagged.userRephrase.length,\n userVerbatim: flagged.userVerbatim.length,\n agentReask: flagged.agentReask.length,\n },\n examples: { userRephrase: [], agentReask: [] },\n };\n for (const f of flagged.userRephrase.slice(0, 5)) {\n out.examples.userRephrase.push({ sessionExternalId: session.externalId, turnIndex: f.turnIndex, note: `consecutive-user containment ${f.containment.toFixed(2)}` });\n }\n for (const f of flagged.agentReask.slice(0, 5)) {\n out.examples.agentReask.push({ sessionExternalId: session.externalId, turnIndex: f.turnIndex, note: `agent re-ask, containment ${f.containment.toFixed(2)}` });\n }\n return out;\n}\n\n// ── Family 4: interactivity.barge-in-friction ───────────────────────────\n\nexport interface BargeInRef {\n /** The interrupted turn — null when the event predates the first turn\n (still counted as an event; resolvable to no turn, so never part of\n the drill's flagged set). */\n turnIndex: number | null;\n positionMs: number | null;\n /** null when the interrupt killed the conversation (no following turn). */\n recoveryMs: number | null;\n killed: boolean;\n}\n\n/**\n * THE barge-in event set (D26 extraction): one ref per interrupt event\n * with a parseable timestamp. bargeInFriction's counts fold these; the\n * grouped drill reads the interrupted turns from the same refs (null\n * turnIndex refs dropped, the rest deduped — a turn interrupted twice is\n * one row). Resolve the interrupted turn BY TIME, never by the event's\n * stored attachment: the worker's next-turn attach ran when turns\n * carried processing-time started_at (imported historical corpus), so\n * attachment position is not meaningful — the event's own `at` on the\n * telemetry clock is the authority (restored by the backfill).\n */\nexport function bargeInRefs(session: GapSession): BargeInRef[] {\n const interrupts: GapEnvironmentEvent[] = [];\n for (const turn of session.turns) {\n for (const e of turn.environmentEventStream ?? []) {\n if (e.event === 'interrupt') interrupts.push(e);\n }\n }\n const turnStart = (t: GapTurn): number => Date.parse(t.startedAt ?? '');\n const out: BargeInRef[] = [];\n for (const e of interrupts) {\n const at = Date.parse(e.at ?? '');\n if (!Number.isFinite(at)) continue;\n let activeIdx: number | null = null;\n for (let i = 0; i < session.turns.length; i++) {\n if (turnStart(session.turns[i]!) <= at) activeIdx = i;\n else break;\n }\n if (activeIdx === null) {\n out.push({ turnIndex: null, positionMs: null, recoveryMs: null, killed: false });\n continue;\n }\n const next = session.turns[activeIdx + 1];\n const recovered = next !== undefined && Number.isFinite(turnStart(next));\n out.push({\n turnIndex: session.turns[activeIdx]!.turnIndex,\n positionMs: Math.max(0, at - turnStart(session.turns[activeIdx]!)),\n recoveryMs: recovered ? Math.max(0, turnStart(next!) - at) : null,\n killed: !recovered,\n });\n }\n return out;\n}\n\nexport function bargeInFriction(session: GapSession): BargeResult {\n const refs = bargeInRefs(session);\n const out: BargeResult = {\n counts: {\n events: refs.length,\n killed: refs.filter((r) => r.killed).length,\n },\n positionsMs: refs.flatMap((r) => (r.positionMs !== null ? [r.positionMs] : [])),\n recoveryMs: refs.flatMap((r) => (r.recoveryMs !== null ? [r.recoveryMs] : [])),\n examples: [],\n };\n for (const r of refs.filter((x) => x.turnIndex !== null).slice(0, 5)) {\n out.examples.push({\n sessionExternalId: session.externalId,\n turnIndex: r.turnIndex!,\n note: r.killed ? 'no following turn' : `recovered in ${Math.round((r.recoveryMs ?? 0) / 1000)}s`,\n });\n }\n return out;\n}\n\n// ── Timing trustworthiness guard ─────────────────────────────────────────\n// Voice timing (barge-in position / recovery) is a measurement ONLY when the\n// event and turn clocks are real and reconcilable. An imported historical\n// corpus can carry backfilled or processing-time timestamps whose deltas are\n// meaningless — a \"recovery\" of days, or every position pinned to 0. Rather\n// than print a broken number, a timing channel is reported only when enough\n// samples land in a plausible window AND carry real spread; otherwise the\n// median is suppressed with a reason and only the event COUNT stands.\n// GENERALIZED: any corpus with unusable timing is flagged the same way — this\n// is not a Zoom special case, it is the honesty rule for the timing channel.\nconst MAX_POSITION_MS = 120_000; // a barge-in lands ≤ 2 min into an agent turn\nconst MAX_RECOVERY_MS = 120_000; // the next turn follows ≤ 2 min after\nconst MIN_TIMING_SAMPLES = 3;\n\nexport function summarizeTiming(samples: number[], maxMs: number) {\n const plausible = samples.filter((x) => Number.isFinite(x) && x >= 0 && x <= maxMs);\n const dropped = samples.length - plausible.length;\n // Real spread guards against a degenerate channel where every sample\n // collapses to the same value (e.g. positions all pinned to 0).\n const hasSpread = new Set(plausible).size > 1;\n const available =\n plausible.length >= MIN_TIMING_SAMPLES && plausible.length >= dropped && hasSpread;\n let medianMs: number | null = null;\n if (available) {\n const s = [...plausible].sort((a, b) => a - b);\n medianMs = s[Math.floor(s.length / 2)] ?? null;\n }\n return { available, medianMs, plausible: plausible.length, dropped };\n}\n\n// ── The driver-facing aggregate ─────────────────────────────────────────\n\nexport function computeGapClasses(sessions: GapSession[], { toolClasses, outcomesBySession }: { toolClasses: ToolClassifier; outcomesBySession?: Map<string, Set<string>> }) {\n const kb = { needsRetrieval: 0, kbFired: 0, grounded: 0, retrievedWrong: 0, ignored: 0, indeterminate: 0, noChunksRecorded: 0, notRetrieved: 0 };\n const tool = { loops: 0, toolErrors: 0, sessionsWithErrors: 0, nonTermination: 0 };\n const toolByTool: { errors: Record<string, number>; loops: Record<string, number> } = { errors: {}, loops: {} };\n const repair = { userRephrase: 0, userVerbatim: 0, agentReask: 0 };\n const barge = { events: 0, killed: 0 };\n const examples: {\n retrievedWrong: GapExample[]; ignored: GapExample[]; notRetrieved: GapExample[];\n loops: GapExample[]; toolErrors: GapExample[]; nonTermination: GapExample[];\n userRephrase: GapExample[]; agentReask: GapExample[]; bargeIn: GapExample[];\n } = { retrievedWrong: [], ignored: [], notRetrieved: [], loops: [], toolErrors: [], nonTermination: [], userRephrase: [], agentReask: [], bargeIn: [] };\n const positions: number[] = [];\n const recoveries: number[] = [];\n for (const s of sessions) {\n const k = kbRetrievalAttribution(s, toolClasses);\n for (const key of Object.keys(kb) as Array<keyof KbAttributionResult[\"counts\"]>) kb[key] += k.counts[key];\n examples.retrievedWrong.push(...k.examples.retrievedWrong.slice(0, 5 - examples.retrievedWrong.length));\n examples.ignored.push(...k.examples.ignored.slice(0, 5 - examples.ignored.length));\n examples.notRetrieved.push(...k.examples.notRetrieved.slice(0, 5 - examples.notRetrieved.length));\n const t = toolTrajectoryFailureMode(s, toolClasses, outcomesBySession?.get(s.externalId));\n tool.loops += t.counts.loops;\n tool.toolErrors += t.counts.toolErrors;\n tool.sessionsWithErrors += t.counts.sessionsWithErrors;\n tool.nonTermination += t.counts.nonTermination;\n for (const [n, c] of Object.entries(t.byTool.errors)) toolByTool.errors[n] = (toolByTool.errors[n] ?? 0) + c;\n for (const [n, c] of Object.entries(t.byTool.loops)) toolByTool.loops[n] = (toolByTool.loops[n] ?? 0) + c;\n examples.loops.push(...t.examples.loops.slice(0, 5 - examples.loops.length));\n examples.toolErrors.push(...t.examples.toolErrors.slice(0, 5 - examples.toolErrors.length));\n examples.nonTermination.push(...t.examples.nonTermination.slice(0, 5 - examples.nonTermination.length));\n const r = repairMisunderstanding(s);\n repair.userRephrase += r.counts.userRephrase;\n repair.userVerbatim += r.counts.userVerbatim;\n repair.agentReask += r.counts.agentReask;\n examples.userRephrase.push(...r.examples.userRephrase.slice(0, 5 - examples.userRephrase.length));\n examples.agentReask.push(...r.examples.agentReask.slice(0, 5 - examples.agentReask.length));\n const b = bargeInFriction(s);\n barge.events += b.counts.events;\n barge.killed += b.counts.killed;\n positions.push(...b.positionsMs);\n recoveries.push(...b.recoveryMs);\n examples.bargeIn.push(...b.examples.slice(0, 5 - examples.bargeIn.length));\n }\n const position = summarizeTiming(positions, MAX_POSITION_MS);\n const recovery = summarizeTiming(recoveries, MAX_RECOVERY_MS);\n const timingAvailable = position.available || recovery.available;\n return {\n 'kb.retrieval-attribution': { counts: kb, examples: { retrievedWrong: examples.retrievedWrong, ignored: examples.ignored, notRetrieved: examples.notRetrieved } },\n 'tooltrajectory.failure-mode': { counts: tool, byTool: toolByTool, examples: { loops: examples.loops, toolErrors: examples.toolErrors, nonTermination: examples.nonTermination } },\n 'repair.misunderstanding': { counts: repair, examples: { userRephrase: examples.userRephrase, agentReask: examples.agentReask } },\n 'interactivity.barge-in-friction': {\n counts: barge,\n timing: {\n available: timingAvailable,\n // Suppressed, not faked: the event count is trustworthy; the sub-turn\n // timing on this corpus is not (degenerate/backfilled timestamps).\n reason: timingAvailable\n ? null\n : 'backfilled or processing-time timestamps on this imported corpus',\n positionMedianMs: position.medianMs,\n recoveryMedianMs: recovery.medianMs,\n samples: {\n position: position.plausible,\n positionDropped: position.dropped,\n recovery: recovery.plausible,\n recoveryDropped: recovery.dropped,\n },\n },\n examples: examples.bargeIn,\n },\n };\n}\n","/**\n * Shared types and constants across ingest, dashboard, and future SDK.\n * Keep this package small; anything domain-specific belongs in @fieldwork/db\n * or its own package.\n */\n\nimport { z } from \"zod\";\n\nexport { operationalErrorCode } from './operational-error';\n\n// ── Situation vocabulary (OPEN) ───────────────────────────────────────────\n// Situation-type is open-vocabulary. The Day-1 heuristic emits a general\n// dialogue-act seed; a deployment discovers its own situation types by\n// clustering across sessions, and a harness can pass any tag it authors.\n// The arrays below are SEEDS, not a closed enum — the situation column is\n// text[] and ingest accepts any string tag.\n\n// Domain-general dialogue-act seed (the default classifier vocabulary; fits\n// support, assistants, and any conversational deployment).\nexport const GENERAL_SITUATION_TAGS = [\n \"question\",\n \"request\",\n \"inform\",\n \"correction\",\n \"confirmation\",\n \"escalation\",\n \"closing\",\n \"smalltalk\",\n] as const;\n\n// Narrative pack (companion / roleplay), opt-in — the field-derived types.\nexport const NARRATIVE_SITUATION_TAGS = [\n \"status_power_shift\",\n \"deception_concealment\",\n \"dramatic_irony\",\n \"reveal_recognition\",\n \"betrayal_broken_trust\",\n \"reconciliation_repair\",\n \"moral_dilemma_subtext\",\n \"comedic_incongruity\",\n] as const;\n\n// Situation tags are open strings; the arrays above are seeds, not an enum.\nexport type SituationTag = string;\n\n// Back-compat aliases (the narrative pack keeps the historical names).\nexport const SITUATION_TYPES = NARRATIVE_SITUATION_TAGS;\nexport type SituationType = (typeof NARRATIVE_SITUATION_TAGS)[number];\n\n// ── Reaction register from Vincent's harness ──────────────────────────────\nexport const REACTION_REGISTERS = [\"heavy\", \"comic\", \"edge\"] as const;\nexport type ReactionRegister = (typeof REACTION_REGISTERS)[number];\n\n// ── Outcome type per probe.md §2 ──────────────────────────────────────────\nexport const OUTCOME_TYPES = [\n \"numeric\",\n \"categorical\",\n \"boolean\",\n \"duration\",\n] as const;\nexport type OutcomeType = (typeof OUTCOME_TYPES)[number];\n\n// ── Interpretive fields the SDK may pass through from a harness ────────────\n// Customer running the Cultured Computer harness pattern or wiring the\n// Oracle read hook can populate these at the SDK edge; ingest passes them\n// through to canonical turns. When absent, the async classifier workers\n// (packages/classifier) populate situation_type and reaction_register from\n// Tier 1 records; lens_chosen stays null for non-harness deployments.\nexport const InterpretiveRecordSchema = z.object({\n // Open vocabulary: any string tag. Seeds live in GENERAL_SITUATION_TAGS /\n // NARRATIVE_SITUATION_TAGS but ingest never rejects an unseen situation.\n situationType: z.array(z.string()).optional(),\n read: z.string().optional(),\n lensChosen: z.string().optional(),\n reactionRegister: z.enum(REACTION_REGISTERS).optional(),\n reactionNextTurn: z.string().optional(),\n});\nexport type InterpretiveRecord = z.infer<typeof InterpretiveRecordSchema>;\n\n// ── Propensity + candidates (Day 1 harness-supplied, per PROBE.md §2) ─────\n// The one thing that cannot be backfilled: the alternative reads the harness\n// considered, the actual sampling distribution used to select among them,\n// which was selected, and (separately) raw model confidence/logprobs.\n//\n// `scores` and `propensities` are DIFFERENT things and must not be\n// conflated. Off-policy evaluation requires `propensities` — the behavior\n// policy's actual sampling probability at selection time — not scores.\n// A harness that samples with temperature/top_p and then reports raw\n// softmax(logits) as \"propensity\" will break DR estimators. `scores`\n// remains useful as a diagnostic and as input for later CI construction.\nexport const PropensitySchema = z.object({\n candidates: z\n .array(z.object({ label: z.string(), text: z.string().optional() }))\n .optional(),\n /**\n * Raw model confidence / logprobs / ensemble scores per candidate.\n * Diagnostic only; NOT a propensity unless the harness confirms it is\n * the exact sampling distribution used and passes it also as\n * `propensities`.\n */\n scores: z.array(z.number()).optional(),\n /**\n * Behavior-policy sampling distribution at selection time. Must sum\n * to 1.0 (within float tolerance) if present. Load-bearing for OPE\n * (Dudík, Langford & Li 2011 for per-turn / Jiang & Li 2016 for\n * trajectory). When omitted, OPE is not possible on this turn.\n */\n propensities: z.array(z.number()).optional(),\n selectedIndex: z.number().int().nonnegative().optional(),\n /**\n * Sampling-policy metadata: temperature, top_p, top_k, seed, sampler\n * name, ensemble weights. Required for reviewers to verify that\n * `propensities` is the actual behavior distribution.\n */\n selectionMeta: z.record(z.string(), z.unknown()).optional(),\n});\nexport type PropensityInput = z.infer<typeof PropensitySchema>;\n\n/**\n * Amendment S (2026-07-14) — post-guardrail propensity contract validator.\n *\n * Saito et al. 2021 Open Bandit Pipeline (arXiv:2008.07146); Farhadi\n * field notes on OPE identification. Enforces the four bug classes at\n * the SDK edge — if a customer wants the directive/OPE half, propensity\n * logging must survive these checks.\n *\n * Bug classes:\n * 1. Deterministic decoding (temp=0) with propensity: zero support ⇒ OPE\n * undefined for any counterfactual (positivity/overlap failure).\n * 2. Missing policy version metadata: importance-weighted estimators\n * require the logging policy be identifiable.\n * 3. propensities present without summing to ~1.0: not a probability\n * distribution.\n * 4. selectionMeta absent when propensities present: reviewers cannot\n * verify that propensities is the actual behavior distribution.\n *\n * Returns { ok: true } when valid, { ok: false, reason } when contract\n * violated. Fire-and-log at SDK edge; do NOT block ingest — customers\n * without OPE ambitions still ship descriptive-half records.\n */\nexport type PropensityContractResult =\n | { ok: true }\n | {\n ok: false;\n reason: string;\n class:\n | \"zero_support\"\n | \"missing_policy_version\"\n | \"malformed_distribution\"\n | \"missing_selection_meta\";\n };\n\nexport function validatePropensityContract(\n p: PropensityInput | undefined,\n): PropensityContractResult {\n if (!p) return { ok: true }; // customer opted out of propensity logging — fine\n if (!p.propensities || p.propensities.length === 0) return { ok: true }; // descriptive-half only\n\n // Bug class 1: zero-support (deterministic decoding)\n const temp = p.selectionMeta?.[\"temperature\"] as number | undefined;\n if (typeof temp === \"number\" && temp === 0) {\n return {\n ok: false,\n class: \"zero_support\",\n reason:\n \"temperature=0 with propensities logged: deterministic decoding has zero support. OPE is undefined for any counterfactual. Set temperature > 0 or omit propensities.\",\n };\n }\n\n // Bug class 2: missing policy version\n const policyVersion = p.selectionMeta?.[\"policy_version\"] as\n string | undefined;\n if (!policyVersion) {\n return {\n ok: false,\n class: \"missing_policy_version\",\n reason:\n \"propensities logged without selectionMeta.policy_version. IPS/DR require the logging policy be identifiable across replays.\",\n };\n }\n\n // Bug class 3: distribution doesn't sum to 1\n const sum = p.propensities.reduce((a, b) => a + b, 0);\n if (Math.abs(sum - 1.0) > 0.02) {\n return {\n ok: false,\n class: \"malformed_distribution\",\n reason: `propensities sum to ${sum.toFixed(4)}, expected ~1.0. Not a probability distribution; likely raw softmax(logits). A score is not a probability.`,\n };\n }\n\n // Bug class 4: selectionMeta present but missing sampler details\n if (!p.selectionMeta) {\n return {\n ok: false,\n class: \"missing_selection_meta\",\n reason:\n \"propensities logged without selectionMeta. Reviewers cannot verify propensities is the actual behavior distribution.\",\n };\n }\n\n return { ok: true };\n}\n\n// ── Transition signals (Day 1, per PROBE.md §2) ───────────────────────────\n// The right half of the record: human's response to the reply. Cheap\n// observations the SDK captures without waiting for outcome-hook wiring.\nexport const TransitionSchema = z.object({\n timeMs: z.number().int().nonnegative().optional(),\n lengthDelta: z.number().int().optional(),\n});\nexport type TransitionInput = z.infer<typeof TransitionSchema>;\n\n// ── User-side input (P1, per PLAN-2026-07-11-p1-p2) ──────────────────────\n// What the human said + interactivity signals about how they said it.\n// The single most-important missing capture pre-2026-07-11: without user\n// text as a first-class column, the record is agent-centric. See PROBE.md\n// Amendment G (sequence primacy over classification).\nexport const UserInputSchema = z.object({\n /** The user's message text. Presidio-scrubbed server-side before landing on `probe_user_reply_text`. */\n text: z.string().optional(),\n /** Milliseconds between agent response end and user's first keystroke. Client-side UI hook, optional. */\n firstKeystrokeMs: z.number().int().nonnegative().optional(),\n /** Backspace/edit count while typing this reply. Client-side UI hook, optional. */\n editCount: z.number().int().nonnegative().optional(),\n /** Did the user submit before the agent's response finished streaming? */\n interruptedStream: z.boolean().optional(),\n /** Did the user click stop on an agent streaming response mid-flight? */\n cancelledResponse: z.boolean().optional(),\n /** ISO timestamp when the user submitted this reply. */\n submittedAt: z.string().optional(),\n});\nexport type UserInput = z.infer<typeof UserInputSchema>;\n\n// ── Interactivity (P1) — agent-side reflection + stream state ────────────\nexport const InteractivitySchema = z.object({\n /** Milliseconds between the user's submit and the next agent LLM call. */\n agentReflectMs: z.number().int().nonnegative().optional(),\n /** Did the agent's response stream finish fully (finish_reason='stop')? */\n agentStreamCompleted: z.boolean().optional(),\n /** Multimodal events observed on this turn (image upload, voice snippet, file, etc.). */\n multimodalEvents: z\n .array(\n z.object({\n kind: z.string(),\n at: z.string().optional(),\n meta: z.record(z.string(), z.unknown()).optional(),\n }),\n )\n .optional(),\n});\nexport type InteractivityInput = z.infer<typeof InteractivitySchema>;\n\n// ── User outcome signals (Ch9-promoted, first-class per PLAN-2026-07-11) ─\nexport const UserOutcomeSchema = z.object({\n /**\n * Explicit \"that didn't sound like you\" flag attached at turn level.\n * DEPRECATED: prefer Probe.flagPersonaBreak(), which routes through the\n * flags ingest path and carries user attribution + a 'break' outcome\n * event. This turn-level boolean remains accepted for wire compat but\n * new integrations should not set it.\n */\n flaggedBreak: z.boolean().optional(),\n /** Rating widget value 1-5, customer-supplied. */\n explicitRating: z.number().int().min(1).max(5).optional(),\n /** Thumbs-up / thumbs-down widget value. */\n thumbs: z.enum([\"up\", \"down\"]).optional(),\n});\nexport type UserOutcomeInput = z.infer<typeof UserOutcomeSchema>;\n\n// ── SDK ingest input schema (mirrored by apps/ingest/routes/turns.ts) ─────\nexport const TurnInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /**\n * The SDK payload contract version (D2): optional, additive-only. Every\n * reader treats a missing stamp as 'envelope-v0-unstamped' — payloads\n * from older SDKs are valid by construction (tolerated-absent).\n */\n envelopeVersion: z.string().max(40).optional(),\n /**\n * Customer's user identity (opaque string), forwarded by the SDK from\n * Probe.startSession() state on every turn. Distinct from\n * sessionExternalId, which keys the SESSION: the worker persists this on\n * sessions.external_user_id at first-turn session create (falling back to\n * null — never to sessionExternalId) so return-with-persona-consistency\n * and prior-session metrics read a real user identity.\n */\n externalUserId: z.string().min(1).optional(),\n turnIndex: z.number().int().nonnegative(),\n // the SDK's identity for one logical turn; with it, an index collision takes the next index instead of dropping\n turnId: z.string().uuid().optional(),\n /**\n * Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the\n * worker: when present it becomes turns.started_at; when absent the\n * insert defaults to processing time. This is PROVENANCE, not\n * verification — intended for historical imports (ZVA telemetry, log\n * backfills, the datadump importer); live SDK traffic leaves it unset\n * (arrival time is the honest clock there).\n */\n startedAt: z.string().datetime().optional(),\n /**\n * Persona slug active for this turn. Customer-supplied (from SDK persona\n * resolution: turn override / session / init default). Optional; deployments\n * with a single registered persona can omit this and the ingest worker\n * backfills from the deployment default at write time.\n */\n personaSlug: z.string().min(1).optional(),\n /**\n * Signature-phrase matches computed at the SDK edge (per PROBE.md §2).\n * List of matched signature-phrase slugs the customer registered via\n * Probe.init({ persona: { signaturePhrases: [...] } }). Empty array or\n * omitted when no signatures matched or the deployment did not register any.\n */\n signaturePhraseMatches: z.array(z.string()).optional(),\n /**\n * Interpretive record fields passed through from a customer harness\n * (Oracle read hook wired). Omitted for deployments not running the harness;\n * server-side classifier workers populate situation_type and reaction_register\n * from the raw payload instead.\n */\n interpretive: InterpretiveRecordSchema.optional(),\n /**\n * Propensity + candidate set + scores. Harness-supplied only. Substrate\n * for OPE in Chapter 5 Dream. Nearly free if the harness already computes\n * candidates + ensemble scores; cannot be backfilled from the reply alone.\n */\n propensity: PropensitySchema.optional(),\n /**\n * Transition signals (human's response to the reply). Populated when the\n * SDK observes the next user turn; may arrive on a subsequent turn ingest.\n */\n transition: TransitionSchema.optional(),\n /**\n * User-side input for this turn: what the human actually said + UI-level\n * interactivity hints. Server-side Presidio scrubs text before it lands\n * on the canonical probe_user_reply_text column. See PLAN-2026-07-11.\n */\n userInput: UserInputSchema.optional(),\n /**\n * Interactivity between agent and user for this turn: agent reflect time,\n * stream completion, multimodal events.\n */\n interactivity: InteractivitySchema.optional(),\n /**\n * Explicit user outcome signals (Ch9-promoted): flagged break, rating,\n * thumbs. Landed as first-class columns per PLAN-2026-07-11.\n */\n userOutcome: UserOutcomeSchema.optional(),\n /**\n * RLDS episode-level provenance (Amendment R populater 2026-07-11).\n * SDK forwards these from Probe.startSession() on every turn payload so\n * the worker can persist them on the sessions row at first-turn create.\n * All optional. Powers Chapter 8e′ Card 3 version behavioral diff.\n */\n agentId: z.string().optional(),\n // Endpoint capture explicitly records no experiment; older SDKs omit it.\n experimentId: z.string().nullish().transform(value => value ?? undefined),\n environmentConfigHash: z.string().optional(),\n environmentConfigLabel: z.string().optional(),\n /** Internal Studio runner provenance. Customer SDKs never set this. */\n studioRunRequestId: z.string().uuid().optional(),\n /**\n * Session context riding the FIRST turn of a session (there is no\n * session-start wire route; the session row is created lazily by the\n * worker on the first turn that arrives). The SDK forwards these once\n * per session from Probe.startSession() state; the worker persists them\n * on sessions.probe_session_opened_via / probe_session_client_context\n * at session find-or-create and ignores them on later turns.\n */\n openedVia: z\n .enum([\"link\", \"notification\", \"resume\", \"direct\", \"share\"])\n .optional(),\n /**\n * Browser / device / locale / tz environmental context, customer-\n * configurable which fields to include. Customer metadata from\n * Probe.startSession({ metadata }) is merged in by the SDK under the\n * `metadata` key so it has a durable landing place.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n payload: z.record(z.string(), z.unknown()),\n});\nexport type TurnInput = z.infer<typeof TurnInputSchema>;\n\n/**\n * The constructed-lane marker on a pending turn payload: `true` says the\n * row's text is ours (a sim or scripted caller, delivered lines, the runner,\n * a replay), written by one of our own lanes straight into the queue. It is\n * what lets the worker store that text without the PII scrub. It is NOT a\n * TurnInputSchema field, so the schema strips it from anything a client\n * sends, and the ingest route deletes it by name as well: nothing arriving\n * over HTTP can carry it. Only code with database access can set it.\n */\nexport const CONSTRUCTED_LANE_KEY = \"_constructedLane\";\n\n/**\n * TurnInput fields only our own lanes may set. A client that sends one has\n * it removed at the ingest door (removed, not refused: no released SDK\n * sends them, and a refusal would turn a stray field into lost turns).\n */\nexport const INTERNAL_TURN_FIELDS = [\"studioRunRequestId\", CONSTRUCTED_LANE_KEY] as const;\n\n/** The turn payload as a client may send it: internal-only fields removed. */\nexport function stripInternalTurnFields<T extends Record<string, unknown>>(payload: T): T {\n const out: Record<string, unknown> = { ...payload };\n for (const key of INTERNAL_TURN_FIELDS) delete out[key];\n return out as T;\n}\n\n// ── Session lifecycle schemas (P2, per PLAN-2026-07-11) ──────────────────\n// Note: there is deliberately no SessionStartSchema here. A session-start\n// wire contract was drafted 2026-07-11 but no route ever consumed it; the\n// worker creates sessions lazily on the first ingested turn instead, and\n// session context (openedVia, clientContext) rides TurnInputSchema on that\n// first turn. Deleted rather than kept as dead surface (e2e audit\n// 2026-07-13); resurrect from git history if a dedicated route ships.\n\nexport const SessionEndSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /** Why the session ended. */\n endedReason: z\n .enum([\n \"natural\",\n \"user_closed\",\n \"timeout\",\n \"agent_error\",\n \"user_flagged\",\n \"crashed\",\n ])\n .optional(),\n /** ISO timestamp of session end. */\n endedAt: z.string().optional(),\n});\n\n/** The ended reasons the serve engine writes for the endings it makes\n itself (docs/PLAN-2026-10-02-soul-headless-ready.md, lane H2): the house\n floor fired ('floor'), or the conversation reached its turn cap\n ('turn_cap'). Before H2 both were recorded 'natural'. They ride the\n engine's own session_end row (studio-session-lifecycle.ts), never the\n public ingest route: SessionEndSchema, the SDK's contract, is unchanged. */\nexport const ENGINE_ENDED_REASONS = [\"floor\", \"turn_cap\"] as const;\n\n/** The session_end payload as the worker accepts it: the SDK's reasons\n plus the engine's own two. */\nexport const WorkerSessionEndSchema = SessionEndSchema.extend({\n endedReason: z\n .enum([\n ...SessionEndSchema.shape.endedReason.unwrap().options,\n ...ENGINE_ENDED_REASONS,\n ])\n .optional(),\n});\nexport type SessionEndInput = z.infer<typeof SessionEndSchema>;\n\n// ── SDK flag input schema (persona-break flag from Probe.flagPersonaBreak) ─\n// Populates the `user_flagged_break` outcome column in Chapter 9c. Consumer AI\n// products wire this to their in-product \"that didn't sound like you\" UX.\nexport const FlagInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n flagType: z.enum([\"persona_break\"]),\n note: z.string().optional(),\n /**\n * Turn index the flag refers to. Optional; if omitted, the flag is\n * attached to the most recent turn of the session.\n */\n turnIndex: z.number().int().nonnegative().optional(),\n});\nexport type FlagInput = z.infer<typeof FlagInputSchema>;\n\n// ── Outcome event ingest (Amendment I Method D, 2026-07-12) ──────────────\n// Customer- or harness-emitted event marking a hard outcome. Universal seed\n// kinds ship as fallback; open-vocab lets deployments register their own.\n// Worker-side detectors also emit events without an SDK call, so this\n// schema is only the *customer-driven* portion of the outcome corpus.\nexport const OUTCOME_EVENT_KINDS_SEED = [\n \"break\",\n \"escalation\",\n \"resolution\",\n \"abandonment\",\n \"register_drift_cross\",\n \"thumbs_down\",\n \"thumbs_up\",\n \"rating_low\",\n \"rating_high\",\n] as const;\nexport type OutcomeEventKindSeed = (typeof OUTCOME_EVENT_KINDS_SEED)[number];\n\n// ── Synthetic demo-data marker (2026-07-13 demo arc) ─────────────────────\n// A deployment whose classifier_config carries `synthetic: true` holds\n// generated data (the demo corpus), never customer traffic. One marker,\n// many readers: the dashboard banner + \"(demo)\" filter labels, the\n// measurement sweep's provenance stamp on probe_measurement_aggregates\n// rows, and the worker's seed_demo idempotency guard all read THIS\n// predicate rather than re-deriving the convention. Writers: the demo\n// seeding module (apps/worker/src/demo-seed.ts) and the seeder CLI\n// (scripts/seed-demo-corpus.mjs), both via the same merge helper.\nexport function isSyntheticClassifierConfig(config: unknown): boolean {\n return (\n typeof config === \"object\" &&\n config !== null &&\n (config as Record<string, unknown>)[\"synthetic\"] === true\n );\n}\n\n/**\n * DEMO_AUTOSEED feature gate, default ON in code: any value except an\n * explicit '0' / 'false' enables demo auto-seeding. Read at enqueue time\n * (dashboard onboarding) and at consume time (worker seed_demo handler)\n * through this one predicate. Pure over an env bag for unit tests.\n * Documented in docs/DEPLOY.md.\n */\nexport function demoAutoseedEnabled(\n env: Record<string, string | undefined> = typeof process !== \"undefined\"\n ? process.env\n : {},\n): boolean {\n const v = env[\"DEMO_AUTOSEED\"];\n return v !== \"0\" && v !== \"false\";\n}\n\n// ── Demo seeding job schemas (auto-provision arc, 2026-07-13) ─────────────\n// Rides the pending_redaction queue like flag / session_end / outcome_event:\n// onboarding enqueues `_kind: 'seed_demo'` on project creation (gated by\n// DEMO_AUTOSEED, default ON); the worker consumes it, builds the\n// deterministic corpus in-process, and enqueues the corpus payloads plus a\n// trailing `_kind: 'seed_demo_backdate'` row that moves session/turn\n// timestamps onto the corpus schedule once the corpus rows have drained.\n/** Corpus window anchor offset: startDate defaults to now minus this, so\n the ~6.4-day corpus sits fully inside trailing-7-day sweep windows. */\nexport const DEMO_SEED_WINDOW_OFFSET_MS = 6.5 * 24 * 60 * 60 * 1000;\n\nexport const SeedDemoJobSchema = z.object({\n /** Slug for the demo deployment; defaults to 'demo'. */\n deploymentSlug: z.string().min(1).optional(),\n /** PRNG seed; the corpus is byte-identical per (seed, startDate). */\n seed: z.number().int().optional(),\n /**\n * ISO anchor for the corpus window (sessions land in\n * [startDate, startDate + ~6.4d]). Enqueuers stamp now-6.5d so the\n * trailing-7-day sweeps see the corpus; the worker defaults the same\n * way when absent.\n */\n startDate: z.string().optional(),\n});\nexport type SeedDemoJobInput = z.infer<typeof SeedDemoJobSchema>;\n\n/** The in-product runner's job (2026-07-23): execution for one\n studio_run_requests row, riding the same pending_redaction _kind lane\n as seed_demo. The request row carries all parameters; the job only\n points at it. */\nexport const StudioRunJobSchema = z.object({\n requestId: z.string().uuid(),\n});\nexport type StudioRunJobInput = z.infer<typeof StudioRunJobSchema>;\n\nexport const SeedDemoBackdateSchema = z.object({\n deploymentSlug: z.string().min(1),\n /** Same (seed, startDate) the seeding job used — the plan is recomputed\n deterministically rather than serialized through the queue. */\n seed: z.number().int(),\n startDate: z.string(),\n});\nexport type SeedDemoBackdateInput = z.infer<typeof SeedDemoBackdateSchema>;\n\n// ── Environment event ingest (Arc D-rail, PLAN.md §4; 2026-07-19) ─────────\n// The generalized environment-envelope contract: coupled human↔environment\n// reaction records. `source_type` and `event` are FREE strings supplied by\n// the deployment — open vocabulary by construction (same discipline as\n// situation tags and outcome-event kinds). The instrument stores, attaches\n// by time, and never interprets; there is deliberately no seed list here.\nexport const EnvironmentEventInputSchema = z.object({\n /** Free-form channel label (e.g. a stimulus feed, a game state stream). Open vocabulary — NOT an enum. */\n source_type: z.string().min(1),\n /** Free-form event name. Open vocabulary — NOT an enum. */\n event: z.string().min(1),\n /** ISO timestamp of the event on the deployer's clock (see alignment). */\n at: z.string().datetime(),\n /** Optional detail payload (deployer-defined). */\n meta: z.record(z.string(), z.unknown()).optional(),\n sessionExternalId: z.string().min(1),\n deploymentSlug: z.string().min(1),\n /**\n * Optional reference to the causing turn. v1 resolves a turn index within\n * the same session (string-encoded integer); any other value is stored\n * verbatim on the event record without an outcome-corner link. The\n * instrument records the reference only — no causal inference.\n */\n causeProvenance: z.string().min(1).optional(),\n});\nexport type EnvironmentEventInput = z.infer<typeof EnvironmentEventInputSchema>;\n\n/**\n * Clock contract for a batch: whose clock produced the events' `at`, the\n * deployer's bound on skew against the instrument's clock, and the version\n * of the attach rule the deployer aligned to. Free-form strings — the\n * instrument stores the claim, it does not verify clocks.\n */\nexport const AlignmentProvenanceSchema = z.object({\n clock_source: z.string().min(1),\n skew_bound_ms: z.number().nonnegative().optional(),\n rule_version: z.string().min(1),\n});\nexport type AlignmentProvenance = z.infer<typeof AlignmentProvenanceSchema>;\n\nexport const EnvironmentEventsBatchSchema = z.object({\n /** Events are self-addressed: a batch may span sessions/deployments. */\n events: z.array(EnvironmentEventInputSchema).min(1).max(100),\n alignment: AlignmentProvenanceSchema,\n});\nexport type EnvironmentEventsBatch = z.infer<\n typeof EnvironmentEventsBatchSchema\n>;\n\n// ── Span ingest (sub-turn structure; 2026-07-22) ───────────────────────────\n// One span = one LLM call, one tool call, one framework step, or a custom\n// sub-turn unit inside a turn. This is the REMOTE capture lane for the\n// `spans` table (SDK → POST /v1/spans → pending_redaction `_kind: 'spans'`\n// → worker); the import lane (scripts/import-zva-corpus.mjs) writes the same\n// table directly as owner.\n//\n// Spans are self-addressed like environment events: a batch may span\n// sessions/deployments. The batch carries the same alignment provenance\n// contract (whose clock produced the caller-asserted startedAt values).\n//\n// PII RULE (2026-07-22, the never-bypassed rule): `attributes` and captured\n// v2 input/output MAY carry content-bearing strings. The worker scrubs EVERY\n// string value through the same Presidio pass as turn text before insert. An\n// attributes passthrough drops the object; a v2 payload passthrough becomes\n// the explicit `redacted` state. Prefer metadata where content adds nothing\n// — scrubbed ≠ free. Each JSON surface is capped at 16k so this lane cannot\n// be used as blob storage.\nexport const SPAN_TYPES = [\n \"agent_call\",\n \"llm_call\",\n \"tool_call\",\n \"framework_step\",\n \"custom\",\n] as const;\nexport type SpanType = (typeof SPAN_TYPES)[number];\n\nexport const SPAN_STATUSES = [\"unset\", \"ok\", \"error\"] as const;\nexport type SpanStatus = (typeof SPAN_STATUSES)[number];\nexport const SPAN_V2_STATUSES = [\"ok\", \"error\"] as const;\n\nexport const SPAN_PAYLOAD_STATES = [\n \"captured\",\n \"empty\",\n \"not_captured\",\n \"redacted\",\n \"unavailable\",\n] as const;\nexport type SpanPayloadState = (typeof SPAN_PAYLOAD_STATES)[number];\nexport interface SpanPayload {\n state: SpanPayloadState;\n value: unknown;\n}\n\nexport const SPAN_INTERVAL_KINDS = [\n \"active\",\n \"waiting\",\n \"retry\",\n \"error\",\n] as const;\nexport type SpanIntervalKind = (typeof SPAN_INTERVAL_KINDS)[number];\nexport interface SpanInterval {\n kind: SpanIntervalKind;\n startedAt: string;\n endedAt: string;\n}\n\nexport const SpanIntervalSchema = z\n .object({\n kind: z.enum(SPAN_INTERVAL_KINDS),\n startedAt: z.string().datetime(),\n endedAt: z.string().datetime(),\n })\n .superRefine((interval, ctx) => {\n if (\n new Date(interval.endedAt).getTime() <=\n new Date(interval.startedAt).getTime()\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"endedAt\"],\n message: \"interval endedAt must follow startedAt\",\n });\n }\n });\n\nfunction serializedJsonLength(value: unknown): number {\n try {\n return JSON.stringify(value)?.length ?? 0;\n } catch {\n return Number.POSITIVE_INFINITY;\n }\n}\n\nfunction isJsonValue(\n value: unknown,\n ancestors: Set<object> = new Set(),\n): boolean {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n if (typeof value === \"number\") return Number.isFinite(value);\n if (typeof value !== \"object\") return false;\n if (ancestors.has(value)) return false;\n\n const nextAncestors = new Set(ancestors).add(value);\n if (Array.isArray(value)) {\n return value.every((item) => isJsonValue(item, nextAncestors));\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) return false;\n return Object.values(value as Record<string, unknown>).every((item) =>\n isJsonValue(item, nextAncestors),\n );\n}\n\nfunction isStructurallyEmptyPayload(value: unknown): boolean {\n if (value === \"\") return true;\n if (Array.isArray(value)) return value.length === 0;\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype &&\n Object.keys(value).length === 0\n );\n}\n\nexport const SpanPayloadSchema = z\n .object({\n state: z.enum(SPAN_PAYLOAD_STATES),\n value: z.unknown().nullable(),\n })\n .superRefine((payload, ctx) => {\n if (!(\"value\" in payload)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"value\"],\n message:\n \"payload value must be present; use null for non-captured states\",\n });\n return;\n }\n if (payload.state === \"captured\" && !isJsonValue(payload.value)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"value\"],\n message: \"captured payload must be JSON-compatible\",\n });\n }\n if (payload.state === \"captured\" && payload.value === null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"value\"],\n message: \"captured payload requires a non-null value\",\n });\n }\n if (\n payload.state === \"captured\" &&\n isStructurallyEmptyPayload(payload.value)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"value\"],\n message: \"genuinely empty payloads require state=empty\",\n });\n }\n if (payload.state !== \"captured\" && payload.value !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"value\"],\n message: `${payload.state} payload must carry a null value`,\n });\n }\n })\n .refine((payload) => serializedJsonLength(payload.value) <= 16_000, {\n message: \"span payload exceeds 16k JSON chars\",\n }) as z.ZodType<SpanPayload>;\n\nconst SpanAddressSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /**\n * Turn the span belongs to. Optional: when omitted the worker resolves the\n * session's latest turn at/under the span's startedAt (falling back to the\n * session's most recent turn when startedAt is also absent — the outcome\n * events' rule). A span whose turn cannot be resolved is SKIPPED by the\n * worker (logged, batch still processed): spans never land unattributed.\n */\n turnIndex: z.number().int().nonnegative().optional(),\n spanType: z.enum(SPAN_TYPES),\n});\n\n/** Legacy span wire shape. Kept as an explicit compatibility lane while SDK\n * callers migrate to the versioned v2 telemetry contract. */\nexport const SpanInputV1Schema = SpanAddressSchema.extend({\n contractVersion: z.literal(1).optional(),\n /** Human/otel-style span name (tool name, model call label). */\n name: z.string().optional(),\n /**\n * Caller-asserted span start (ISO). OPTIONAL and honored like\n * TurnInput.startedAt: provenance, not verification — when absent the\n * worker stamps processing time.\n */\n startedAt: z.string().datetime().optional(),\n endedAt: z.string().datetime().optional(),\n durationMs: z.number().int().nonnegative().optional(),\n model: z.string().optional(),\n provider: z.string().optional(),\n tokensInput: z.number().int().nonnegative().optional(),\n tokensOutput: z.number().int().nonnegative().optional(),\n costUsd: z.number().nonnegative().optional(),\n error: z.string().optional(),\n /**\n * OpenInference / OpenTelemetry gen_ai.*-style attributes. String values\n * are Presidio-scrubbed by the worker before storage (see the PII rule\n * above). Capped at 16k JSON chars per span.\n */\n attributes: z\n .record(z.string(), z.unknown())\n .optional()\n .refine((v) => v === undefined || JSON.stringify(v).length <= 16_000, {\n message:\n \"attributes exceed 16k JSON chars — spans are telemetry, not blob storage\",\n }),\n /**\n * Caller-local span id, unique within the batch. Exists only so sibling\n * spans can name this span as their parentSpanId; never stored (the DB\n * assigns the real uuid).\n */\n spanId: z.string().min(1).optional(),\n /**\n * Caller-local reference to another span's `spanId` IN THE SAME BATCH (NOT\n * a database uuid). The worker wires spans.parent_span_id when the parent\n * resolves within the batch, stores null otherwise.\n */\n parentSpanId: z.string().min(1).optional(),\n});\n\n/** First-class span telemetry. Every operational key exists on every agent,\n * tool and model span; null means unknown rather than a fabricated zero. */\nexport const SpanInputV2Schema = SpanAddressSchema.extend({\n contractVersion: z.literal(2),\n /** Stable within a deployment/session across batches and retries. */\n spanId: z.string().min(1),\n parentSpanId: z.string().min(1).nullable(),\n name: z.string().min(1),\n status: z.enum(SPAN_V2_STATUSES),\n startedAt: z.string().datetime(),\n endedAt: z.string().datetime().nullable(),\n durationMs: z.number().int().nonnegative().nullable(),\n model: z.string().min(1).nullable(),\n provider: z.string().min(1).nullable(),\n tokensInput: z.number().int().nonnegative().nullable(),\n tokensOutput: z.number().int().nonnegative().nullable(),\n costUsd: z.number().nonnegative().nullable(),\n error: z.string().nullable(),\n input: SpanPayloadSchema,\n output: SpanPayloadSchema,\n /** Optional first-class internal timing. An omitted list means the source\n * did not capture interval telemetry; readers must not infer segments. */\n intervals: z.array(SpanIntervalSchema).max(128).optional(),\n attributes: z\n .record(z.string(), z.unknown())\n .nullable()\n .refine(\n (value) => value === null || JSON.stringify(value).length <= 16_000,\n {\n message:\n \"attributes exceed 16k JSON chars — spans are telemetry, not blob storage\",\n },\n ),\n}).superRefine((span, ctx) => {\n if (span.status !== \"error\" && span.error !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"error\"],\n message: \"error detail requires status=error\",\n });\n }\n if (\n span.endedAt !== null &&\n new Date(span.endedAt).getTime() < new Date(span.startedAt).getTime()\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"endedAt\"],\n message: \"endedAt must not precede startedAt\",\n });\n }\n const spanStart = new Date(span.startedAt).getTime();\n const spanEnd =\n span.endedAt !== null\n ? new Date(span.endedAt).getTime()\n : span.durationMs !== null\n ? spanStart + span.durationMs\n : null;\n span.intervals?.forEach((interval, index) => {\n const intervalStart = new Date(interval.startedAt).getTime();\n const intervalEnd = new Date(interval.endedAt).getTime();\n if (\n intervalStart < spanStart ||\n (spanEnd !== null && intervalEnd > spanEnd)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"intervals\", index],\n message: \"interval must stay within the measured span window\",\n });\n }\n });\n});\n\nexport const SpanInputSchema = z.union([SpanInputV2Schema, SpanInputV1Schema]);\nexport type SpanInput = z.infer<typeof SpanInputSchema>;\nexport type SpanInputV1 = z.infer<typeof SpanInputV1Schema>;\nexport type SpanInputV2 = z.infer<typeof SpanInputV2Schema>;\n\nexport const SpansBatchSchema = z\n .object({\n /** Spans are self-addressed: a batch may span sessions/deployments. */\n spans: z.array(SpanInputSchema).min(1).max(50),\n alignment: AlignmentProvenanceSchema,\n })\n .superRefine((batch, ctx) => {\n const spanIdCounts = new Map<string, number>();\n const spansById = new Map<string, (typeof batch.spans)[number]>();\n const parents = new Map<string, string>();\n for (const span of batch.spans) {\n if (span.spanId !== undefined) {\n spanIdCounts.set(span.spanId, (spanIdCounts.get(span.spanId) ?? 0) + 1);\n spansById.set(span.spanId, span);\n }\n if (\n span.parentSpanId !== undefined &&\n span.parentSpanId !== null &&\n span.spanId\n ) {\n parents.set(span.spanId, span.parentSpanId);\n }\n }\n\n batch.spans.forEach((span, index) => {\n if (span.contractVersion !== 2) return;\n if ((spanIdCounts.get(span.spanId) ?? 0) !== 1) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"spans\", index, \"spanId\"],\n message: \"v2 spanId must be unique within the batch\",\n });\n }\n if (\n span.parentSpanId !== null &&\n (spanIdCounts.get(span.parentSpanId) ?? 0) !== 1\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"spans\", index, \"parentSpanId\"],\n message: \"v2 parentSpanId must resolve uniquely within the batch\",\n });\n }\n const parent =\n span.parentSpanId === null\n ? undefined\n : spansById.get(span.parentSpanId);\n if (\n parent &&\n (parent.deploymentSlug !== span.deploymentSlug ||\n parent.sessionExternalId !== span.sessionExternalId)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"spans\", index, \"parentSpanId\"],\n message:\n \"v2 parentSpanId must belong to the same deployment and session\",\n });\n }\n\n const seen = new Set<string>();\n let cursor: string | undefined = span.spanId;\n while (cursor !== undefined) {\n if (seen.has(cursor)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"spans\", index, \"parentSpanId\"],\n message: \"v2 parentSpanId graph must not contain a cycle\",\n });\n break;\n }\n seen.add(cursor);\n cursor = parents.get(cursor);\n }\n });\n });\nexport type SpansBatch = z.infer<typeof SpansBatchSchema>;\n\n// ── Measurement definitions (elicit tier, PLAN-2026-07-19) ─────────────────\n// The Configure authoring input for a deployer-owned elicit rubric (label\n// chips). One definition = family + name + version; the server assigns the\n// version (create → 1, edit → version+1 with superseded_by set — versions\n// are rows, never updates). Constraints that are load-bearing downstream:\n// · family/name are slugs — they key the definition and appear in the\n// label store's classifier key lineage;\n// · chips are 2–9 — the blind queue is keyboard-first (number keys 1–9),\n// so a rubric wider than 9 chips is unanswerable there;\n// · metric 'ordinal' requires ordinalScale to be exactly the values in\n// rank order (α's ordinal difference metric reads it);\n// · v1 elicit metrics are nominal/ordinal (score belongs to the judge tier).\nconst DEFINITION_SLUG = /^[a-z][a-z0-9_-]{0,63}$/;\nconst DEFINITION_VALUE = z.string().trim().min(1).max(64);\n\nexport const MeasurementDefinitionInputSchema = z\n .object({\n /** Measurement family the definition belongs to (e.g. 'voice-conformance'). */\n family: z\n .string()\n .regex(\n DEFINITION_SLUG,\n \"family must be a lowercase slug (a-z, 0-9, _-).\",\n ),\n /** Slug within the family. family+name identifies the definition across versions. */\n name: z\n .string()\n .regex(DEFINITION_SLUG, \"name must be a lowercase slug (a-z, 0-9, _-).\"),\n /** The elicitation prompt — the queue row's plain-language question. */\n question: z.string().trim().min(1).max(280),\n /** Difference metric for α (Krippendorff). Elicit v1: nominal | ordinal. */\n metric: z.enum([\"nominal\", \"ordinal\"]),\n /** The chips (closed vocabulary the rater chooses from). */\n values: z\n .array(DEFINITION_VALUE)\n .min(2, \"A rubric needs at least two chips.\")\n .max(9, \"The queue is keyboard-first — at most 9 chips.\"),\n /** Rank order (lowest first) — required iff metric is 'ordinal'. */\n ordinalScale: z.array(DEFINITION_VALUE).min(2).max(9).optional(),\n })\n .refine((input) => new Set(input.values).size === input.values.length, {\n message: \"Chips must be unique.\",\n path: [\"values\"],\n })\n .superRefine((input, ctx) => {\n if (input.metric === \"ordinal\") {\n const scale = input.ordinalScale;\n if (!scale) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"ordinalScale is required when metric is ordinal.\",\n path: [\"ordinalScale\"],\n });\n return;\n }\n const same =\n scale.length === input.values.length &&\n [...scale].sort().join(\"\") === [...input.values].sort().join(\"\");\n if (!same) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"ordinalScale must be exactly the chips in rank order (lowest first).\",\n path: [\"ordinalScale\"],\n });\n }\n }\n });\nexport type MeasurementDefinitionInput = z.infer<\n typeof MeasurementDefinitionInputSchema\n>;\n\nexport const OutcomeEventInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /** Open-vocab kind label. Seeds above; customers may register any string. */\n kind: z.string().min(1),\n /** How was this event detected? Seed values below; customer sources allowed. */\n detectedBy: z\n .enum([\n \"harness\",\n \"sdk_flag\",\n \"sdk_rating\",\n \"sdk_thumbs\",\n \"worker_detector\",\n \"webhook\",\n \"sdk_custom\",\n ])\n .or(z.string().min(1)),\n /** Optional turn index the event was caused by. Omitted → attaches to session's most recent turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Optional detail payload (customer-defined). */\n detail: z.record(z.string(), z.unknown()).optional(),\n /** ISO timestamp; defaults to server-side now. */\n firedAt: z.string().optional(),\n});\nexport type OutcomeEventInput = z.infer<typeof OutcomeEventInputSchema>;\nexport * from \"@fieldwork/shared/effectiveness-gap\";\n","/**\n * The Sight SDK class. Exported as `Sight`, and as `Probe` (its earlier\n * name) for compatibility.\n *\n * Usage:\n * import { Sight } from '@cultured_computer/sight';\n *\n * Sight.init({\n * apiKey: process.env.SIGHT_API_KEY!,\n * deployment: 'support-agent',\n * });\n *\n * // Calls made inside Sight.withSession(id, fn) are captured as turns.\n */\n\nimport { z } from \"zod\";\nimport { IngestClient } from \"./client\";\nimport {\n ProbeConfigSchema,\n SessionStartSchema,\n SessionEndSchema,\n FlagPersonaBreakSchema,\n OutcomeEventEmitSchema,\n} from \"./types\";\nimport type {\n ProbeConfig,\n ProbeConfigInput,\n PersonaConfig,\n OutcomeHook,\n CapturedTurn,\n CaptureTurnInput,\n SessionStart,\n SessionEndInput,\n FlagPersonaBreakInput,\n OutcomeEventEmit,\n} from \"./types\";\nimport {\n collectClientContext,\n type ClientContextIncludes,\n} from \"./client-context\";\nimport { boundedSessionSet } from \"./session-bounds\";\nimport { hashEnvironmentConfig } from \"./hash\";\nimport {\n registerAllInstrumentations,\n withSession as withSessionContext,\n detachOtelState,\n type CaptureHints,\n} from \"./instrumentation\";\n// Subpath import (not the classifier root index): only the signature-phrase\n// machinery ships in the published bundle. The root index drags in the\n// situation-type / dimension cue catalogs via top-level buildVocabulary()\n// calls that defeat treeshaking.\nimport {\n compileSignaturePhrases,\n matchSignaturePhrases,\n type SignaturePhrase,\n} from \"@fieldwork/classifier/signature-phrase\";\nimport {\n validatePropensityContract,\n EnvironmentEventInputSchema,\n EnvironmentEventsBatchSchema,\n AlignmentProvenanceSchema,\n SpanInputSchema,\n SpansBatchSchema,\n TurnInputSchema,\n type PropensityInput,\n type EnvironmentEventInput,\n type AlignmentProvenance,\n type SpanInput,\n} from \"@fieldwork/shared\";\n\n// ── Singleton state ────────────────────────────────────────────────────────\n\ntype ProbeState = {\n config: ProbeConfig;\n client: IngestClient;\n persona: PersonaConfig | null;\n outcomeHook: OutcomeHook | null;\n sessions: Map<string, SessionState>;\n /**\n * Signature phrases compiled once per persona at init/identify time.\n * Keyed by persona slug so per-session persona switches use the right\n * matcher without recompiling.\n */\n signatureMatchers: Map<string, ReturnType<typeof compileSignaturePhrases>>;\n /**\n * Interaction signals (userInputStart/Edit/Submit, userThumbs/userRating)\n * that arrived BEFORE any session entry existed for their externalId.\n * Flushed into the session entry when it is created (startSession or\n * lazy-create at captureTurn). FIFO-capped at PRE_SESSION_BUFFER_MAX ids\n * so signals for sessions that never capture a turn cannot leak memory.\n */\n preSessionBuffer: Map<string, PreSessionSignals>;\n};\n\ntype PreSessionSignals = {\n pendingUserInput: SessionState[\"pendingUserInput\"];\n pendingUserOutcome: SessionState[\"pendingUserOutcome\"];\n lastUserSubmitAt: number | null;\n};\n\n/** FIFO cap on pre-session signal buffering (distinct session ids). */\nconst PRE_SESSION_BUFFER_MAX = 100;\n\n// Cap + bounded insert for the sessions map live in session-bounds.ts so\n// the OTel processor's lazy-create site shares the exact same cap (B2).\nexport { MAX_TRACKED_SESSIONS } from \"./session-bounds\";\n\n/**\n * Default alignment provenance for single-event environment captures\n * (captureEnvironmentEvent without an explicit alignment argument): the\n * event's `at` rides the SDK host's clock, attached under the v1 rule\n * (next-turn dual-attach). Deployments with their own clock contract pass\n * explicit alignment via captureEnvironmentEvents.\n */\nconst DEFAULT_ENVIRONMENT_ALIGNMENT: AlignmentProvenance = {\n clock_source: \"sdk\",\n rule_version: \"v1\",\n};\n\n/**\n * The SDK payload contract version (D2): stamped on every captured turn so\n * data lineage across SDK upgrades is readable downstream. The SDK's own\n * stamp wins over any caller-supplied field (it is the SDK's word about\n * itself, not a caller claim). Absent on payloads from older SDKs — every\n * reader treats a missing stamp as 'envelope-v0-unstamped'.\n */\nexport const SDK_ENVELOPE_VERSION = \"sdk-envelope-v1\";\n\n/**\n * Default alignment provenance for single-span captures (captureSpan without\n * an explicit alignment argument): the span's caller-asserted timestamps ride\n * the SDK host's clock. Deployments with their own clock contract (or\n * batches) pass explicit alignment via captureSpans.\n */\nconst DEFAULT_SPAN_ALIGNMENT: AlignmentProvenance = {\n clock_source: \"sdk\",\n rule_version: \"v1\",\n};\n\ntype SessionState = {\n externalId: string;\n /** Customer's user identity from startSession; forwarded on every turn. */\n externalUserId: string | null;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n metadata: Record<string, unknown> | null;\n openedVia: string | null;\n clientContext: Record<string, unknown> | null;\n // RLDS provenance.\n agentId: string | null;\n experimentId: string | null;\n environmentConfigHash: string | null;\n environmentConfigLabel: string | null;\n /**\n * Timestamp of the last captured agent turn. Used on the NEXT turn to\n * derive transition.timeMs (previous agent reply → this turn's user\n * submit) and firstKeystrokeMs (previous agent reply → typing start).\n */\n lastAgentTurnAt: number | null;\n /**\n * Timestamp of the last userInputSubmit. Used at captureTurn to derive\n * agentReflectMs (user submit → agent turn capture). transition.timeMs\n * derives from the per-turn pendingUserInput.submittedAt instead, which\n * resets on every capture, so stale submits are never reused for it.\n */\n lastUserSubmitAt: number | null;\n /**\n * True once openedVia/clientContext have been sent with a captured turn.\n * The worker persists session context at session find-or-create (first\n * turn that arrives), so the SDK forwards it exactly once.\n */\n sessionContextForwarded: boolean;\n /** Per-turn user input pending on the SDK edge (unified capture helper). */\n pendingUserInput: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount: number;\n submittedAt?: number;\n } | null;\n /** Per-turn user outcome pending on the SDK edge (thumbs / rating). */\n pendingUserOutcome: {\n thumbs?: \"up\" | \"down\";\n explicitRating?: number;\n } | null;\n};\n\nlet state: ProbeState | null = null;\n\n// ── Public API ─────────────────────────────────────────────────────────────\n\n/**\n * The fire-and-log validator (production-safety audit B3, 2026-07-22):\n * every PER-REQUEST public method validates with safeParse and, on invalid\n * input, warns once per call and DROPS — a throwing parse inside an async\n * method becomes an unhandledRejection in the documented fire-and-forget\n * contract, which can terminate the host process. Only init() throws\n * (boot-time contract, fail loud at integration time).\n */\n\nfunction validateOrDrop<S extends { safeParse: (input: unknown) => any }>(\n schema: S,\n input: unknown,\n method: string,\n): NonNullable<ReturnType<S[\"safeParse\"]>[\"data\"]> | null {\n const result = schema.safeParse(input);\n if (!result.success) {\n const issue = result.error?.issues?.[0];\n\n console.warn(\n `[sight] ${method}: invalid input dropped — ${issue ? `${issue.path?.join(\".\") || \"(root)\"}: ${issue.message}` : \"schema mismatch\"}`,\n );\n return null;\n }\n return result.data;\n}\n\n// Input shapes of the user-side signal helpers. Each helper validates with\n// validateOrDrop like every other per-request method: invalid input logs\n// one warning line and is dropped.\nconst SessionRefSchema = z.object({ externalId: z.string().min(1) });\nconst UserInputSubmitSchema = SessionRefSchema.extend({ text: z.string() });\nconst UserThumbsSchema = SessionRefSchema.extend({\n thumbs: z.enum([\"up\", \"down\"]),\n});\nconst UserRatingSchema = SessionRefSchema.extend({\n rating: z.number().int().min(1).max(5),\n});\n\n/**\n * A fresh turn identity (UUID v4). Identity only, never a secret, so the\n * fallback for a runtime without crypto.randomUUID may use Math.random.\n */\nfunction newTurnId(): string {\n const c = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (c && typeof c.randomUUID === \"function\") return c.randomUUID();\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (ch) => {\n const r = Math.floor(Math.random() * 16);\n return (ch === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\nexport class Probe {\n /**\n * Initialize the SDK. Call once at process start. Subsequent calls are\n * no-ops with a warning; re-init requires a shutdown() first.\n */\n static init(config: ProbeConfigInput): void {\n if (state !== null) {\n console.warn(\"[sight] already initialized; call shutdown() first\");\n return;\n }\n\n const validated = ProbeConfigSchema.parse(config);\n const client = new IngestClient({\n apiKey: validated.apiKey,\n endpoint: validated.endpoint,\n debug: validated.debug,\n dashboardUrl: validated.dashboardUrl,\n });\n\n state = {\n config: validated,\n client,\n persona: validated.persona ?? null,\n outcomeHook: validated.outcomeHook ?? null,\n sessions: new Map(),\n signatureMatchers: new Map(),\n preSessionBuffer: new Map(),\n };\n\n if (validated.persona?.signaturePhrases) {\n state.signatureMatchers.set(\n validated.persona.slug,\n compileSignaturePhrases(\n validated.persona.signaturePhrases as SignaturePhrase[],\n ),\n );\n }\n\n registerAllInstrumentations(state, (turn, hints) =>\n this.captureWithHints(turn, hints),\n );\n }\n\n /**\n * Run a callback inside a session scope. Every LLM call made inside `fn`\n * through a wrapped OpenAI client or an instrumented library is captured\n * as a turn on the session `sessionId`.\n *\n * Autocapture needs this scope: a call made outside any session scope is\n * not captured. The first such call in a process prints one warning;\n * later ones log only with `debug: true`. (Spans that carry\n * `gen_ai.conversation.id` are the one exception: with no scope, that id\n * is used as the session id. An explicit scope always wins.)\n *\n * The scope is carried in OpenTelemetry baggage across awaits.\n */\n static async withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n ): Promise<T> {\n if (state === null) {\n console.warn(\"[sight] withSession called before init\");\n return fn();\n }\n return withSessionContext(sessionId, fn);\n }\n\n /**\n * Identify the process-level default persona. Overwrites any previously-set\n * default. For per-session persona identification (multi-persona products),\n * use startSession({ externalId, persona }) instead.\n */\n static identifyPersona(persona: PersonaConfig): void {\n if (state === null) {\n console.warn(\"[sight] identifyPersona called before init\");\n return;\n }\n state.persona = persona;\n if (persona.signaturePhrases) {\n state.signatureMatchers.set(\n persona.slug,\n compileSignaturePhrases(persona.signaturePhrases as SignaturePhrase[]),\n );\n }\n }\n\n /**\n * Start (or update) a session with an active persona.\n *\n * Single-persona deployments can skip this if the init-level default is\n * enough; the SDK will still create a session entry lazily on first turn.\n * Multi-persona products call this at conversation start so every turn in\n * the session inherits the selected persona.\n *\n * Idempotent: calling with the same externalId updates the entry.\n */\n static startSession(input: SessionStart): void {\n if (state === null) {\n console.warn(\"[sight] startSession called before init\");\n return;\n }\n // Per-request path: invalid input warns and drops, never throws into\n // the host's conversation-start (audit B3; init alone keeps its throw —\n // a boot-time contract should fail loud at integration time).\n const validated = validateOrDrop(SessionStartSchema, input, \"startSession\");\n if (validated === null) return;\n const existing = state.sessions.get(validated.externalId);\n const now = Date.now();\n const session: SessionState = {\n externalId: validated.externalId,\n externalUserId:\n validated.externalUserId ?? existing?.externalUserId ?? null,\n turnIndex: existing?.turnIndex ?? 0,\n startedAt: existing?.startedAt ?? now,\n personaSlug:\n validated.persona ??\n existing?.personaSlug ??\n state.persona?.slug ??\n null,\n metadata: validated.metadata ?? existing?.metadata ?? null,\n openedVia: validated.openedVia ?? existing?.openedVia ?? null,\n clientContext: validated.clientContext ?? existing?.clientContext ?? null,\n agentId: validated.agentId ?? existing?.agentId ?? null,\n experimentId: validated.experimentId ?? existing?.experimentId ?? null,\n environmentConfigHash:\n validated.environmentConfigHash ??\n existing?.environmentConfigHash ??\n null,\n environmentConfigLabel:\n validated.environmentConfigLabel ??\n existing?.environmentConfigLabel ??\n null,\n lastAgentTurnAt: existing?.lastAgentTurnAt ?? null,\n lastUserSubmitAt: existing?.lastUserSubmitAt ?? null,\n sessionContextForwarded: existing?.sessionContextForwarded ?? false,\n pendingUserInput: existing?.pendingUserInput ?? null,\n pendingUserOutcome: existing?.pendingUserOutcome ?? null,\n };\n this.flushPreSessionSignals(validated.externalId, session);\n boundedSessionSet(state.sessions, validated.externalId, session);\n }\n\n /**\n * Move buffered pre-session interaction signals (recorded before any\n * session entry existed for this externalId) onto the session entry.\n * Session-held values win: buffered signals predate anything recorded\n * after the entry existed.\n */\n private static flushPreSessionSignals(\n externalId: string,\n session: SessionState,\n ): void {\n if (state === null) return;\n const buffered = state.preSessionBuffer.get(externalId);\n if (!buffered) return;\n state.preSessionBuffer.delete(externalId);\n session.pendingUserInput =\n session.pendingUserInput ?? buffered.pendingUserInput;\n session.pendingUserOutcome =\n session.pendingUserOutcome ?? buffered.pendingUserOutcome;\n session.lastUserSubmitAt =\n session.lastUserSubmitAt ?? buffered.lastUserSubmitAt;\n }\n\n /**\n * Get or create the pre-session signal buffer entry for an externalId.\n * FIFO-capped: when a new id would exceed PRE_SESSION_BUFFER_MAX, the\n * oldest id is dropped (Map preserves insertion order).\n */\n private static preSessionEntry(externalId: string): PreSessionSignals {\n // Callers check state !== null before calling.\n const buffer = state!.preSessionBuffer;\n const existing = buffer.get(externalId);\n if (existing) return existing;\n if (buffer.size >= PRE_SESSION_BUFFER_MAX) {\n const oldest = buffer.keys().next().value;\n if (oldest !== undefined) buffer.delete(oldest);\n }\n const entry: PreSessionSignals = {\n pendingUserInput: null,\n pendingUserOutcome: null,\n lastUserSubmitAt: null,\n };\n buffer.set(externalId, entry);\n return entry;\n }\n\n /**\n * Compute a stable SHA-256 hex hash of prompt/config text for use as\n * `environmentConfigHash` on Sight.startSession(). Hash is *identity*:\n * pass the human-readable version alongside as `environmentConfigLabel`\n * for the diff table axis (a card keyed by a3f9c2… is unreadable).\n *\n * Ships as a helper because inconsistent hashing across restarts breaks\n * The version behavioral diff — every customer would\n * hash their own way and version-diff would become noise.\n *\n * The same hashing (src/hash.ts) backs the OTel processor's automatic\n * version stamping: when autocapture sees a system message and the\n * deployer set no environmentConfigHash, the session is stamped with\n * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit\n * startSession values always win over the auto stamp.\n */\n static async hashEnvironmentConfig(input: string): Promise<string> {\n return hashEnvironmentConfig(input);\n }\n\n /**\n * End a session and release its in-memory entry. Optional (sessions time out\n * eventually), but recommended for long-running processes with many distinct\n * conversations. If `input.endedReason` is provided the SDK sends an end\n * event to ingest so the worker records the reason server-side.\n *\n * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`\n * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`\n * and, when it returns a non-null OutcomeResult, lands it as an outcome\n * event (kind = result.outcome, detail carries type/value). This is the\n * ONLY place the SDK invokes the hook — there are no client-side timers,\n * so sessions that are never ended explicitly are swept server-side as\n * `timeout` and receive no hook-resolved outcome; land those via\n * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:\n * a throwing or rejecting hook never breaks endSession.\n */\n static async endSession(externalId: string | SessionEndInput): Promise<void> {\n if (state === null) return;\n const validEnd =\n typeof externalId === \"string\"\n ? validateOrDrop(SessionRefSchema, { externalId }, \"endSession\")\n : validateOrDrop(SessionEndSchema, externalId, \"endSession\");\n if (validEnd === null) return;\n const externalIdStr =\n typeof externalId === \"string\" ? externalId : externalId.externalId;\n const endedReason =\n typeof externalId === \"string\"\n ? \"natural\"\n : externalId.endedReason ?? \"natural\";\n // The one-call outcome helper: an explicit outcome declared at close\n // lands as an outcome event before the hook path and the session end\n // (fire-and-log, same discipline as every capture call).\n const declared =\n typeof externalId === \"string\" ? undefined : externalId.outcome;\n if (declared) {\n await this.emitOutcomeEvent({\n sessionExternalId: externalIdStr,\n kind: declared,\n detail: {\n declaredAt: \"endSession\",\n ...(typeof externalId === \"object\" && externalId.outcomeDetail\n ? externalId.outcomeDetail\n : {}),\n },\n });\n }\n // A DECLARED outcome wins: when the caller states the outcome at close,\n // the hook is skipped for this end — otherwise one endSession emits TWO\n // outcome events for the same close and every kind tally over-counts.\n // Hook-resolved outcomes remain the path for ends with no declaration.\n if (!declared && state.outcomeHook) {\n try {\n const result = await state.outcomeHook.resolve(externalIdStr);\n // Re-check state: a shutdown() during a slow resolve drops the send.\n if (result && state !== null) {\n await this.emitOutcomeEvent({\n sessionExternalId: externalIdStr,\n kind: result.outcome,\n detail: {\n type: result.type,\n value: result.value,\n resolvedBy: \"outcome_hook\",\n },\n });\n }\n } catch (err: unknown) {\n console.warn(\n \"[sight] outcome hook resolve failed:\",\n err instanceof Error ? err.message : err,\n );\n }\n }\n if (state === null) return;\n if (endedReason) {\n await state.client\n .sendSessionEnd(state.config.deployment, {\n externalId: externalIdStr,\n endedReason,\n })\n .catch((err: unknown) => {\n console.warn(\n \"[sight] sendSessionEnd failed:\",\n err instanceof Error ? err.message : err,\n );\n });\n }\n state.sessions.delete(externalIdStr);\n }\n\n // ── User-side helpers ──────────────────────────────────────────────────\n // These accumulate user-side signals during a turn; captureTurn folds the\n // accumulated state into TurnInput.userInput / userOutcome before send.\n // Signals that arrive before any session entry exists (typing starts\n // before startSession or the first LLM call) buffer per externalId and\n // flush into the session when it is created.\n\n /**\n * The person started typing. Records the first-keystroke time, sent as\n * `userInput.firstKeystrokeMs` with the next captured turn. Derivable\n * only once a previous agent turn exists; a pre-session typing start\n * buffers the pending-input entry without a firstKeystrokeMs value.\n */\n static userInputStart(externalId: string): void {\n if (state === null) return;\n if (validateOrDrop(SessionRefSchema, { externalId }, \"userInputStart\") === null) return;\n const session = state.sessions.get(externalId);\n const target = session ?? this.preSessionEntry(externalId);\n const now = Date.now();\n const firstKeystrokeMs =\n session?.lastAgentTurnAt != null\n ? Math.max(0, now - session.lastAgentTurnAt)\n : undefined;\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n firstKeystrokeMs:\n target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs,\n };\n }\n\n /**\n * The person pressed backspace or edited. Increments the edit count,\n * sent as `userInput.editCount` with the next captured turn.\n */\n static userInputEdit(externalId: string): void {\n if (state === null) return;\n if (validateOrDrop(SessionRefSchema, { externalId }, \"userInputEdit\") === null) return;\n const target =\n state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n editCount: (target.pendingUserInput?.editCount ?? 0) + 1,\n };\n }\n\n /**\n * The person submitted their message. Records the text (scrubbed of\n * personal data server-side before it is stored) plus the submit\n * timestamp. The text and timings are sent with the NEXT captured turn:\n * a turn's person text is the message that prompted its reply.\n */\n static userInputSubmit(externalId: string, text: string): void {\n if (state === null) return;\n if (\n validateOrDrop(UserInputSubmitSchema, { externalId, text }, \"userInputSubmit\") === null\n )\n return;\n const target =\n state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n const now = Date.now();\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n text,\n submittedAt: now,\n };\n target.lastUserSubmitAt = now;\n }\n\n /** Attach a thumbs-up/down to the current turn. */\n static userThumbs(externalId: string, thumbs: \"up\" | \"down\"): void {\n if (state === null) return;\n if (validateOrDrop(UserThumbsSchema, { externalId, thumbs }, \"userThumbs\") === null) return;\n const target =\n state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserOutcome = {\n ...(target.pendingUserOutcome ?? {}),\n thumbs,\n };\n }\n\n /**\n * Attach an explicit rating to the current turn: an integer from 1 to 5.\n * Any other value logs one warning line and is dropped.\n */\n static userRating(externalId: string, rating: number): void {\n if (state === null) return;\n if (validateOrDrop(UserRatingSchema, { externalId, rating }, \"userRating\") === null) return;\n const target =\n state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserOutcome = {\n ...(target.pendingUserOutcome ?? {}),\n explicitRating: rating,\n };\n }\n\n /**\n * Helper: collect client context and pass it to startSession in one call.\n */\n static startSessionWithContext(\n input: SessionStart,\n includes?: ClientContextIncludes,\n ): void {\n this.startSession({\n ...input,\n clientContext: input.clientContext ?? collectClientContext(includes),\n });\n }\n\n /**\n * Register the outcome hook: declares the deployment's outcome type and\n * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked\n * by endSession() — explicit close is the only trigger; the SDK runs no\n * client-side timers. A non-null OutcomeResult lands as an outcome event\n * on the session. Sessions that are never ended explicitly are swept\n * server-side and never resolve through the hook; land those outcomes via\n * emitOutcomeEvent() from the place where the outcome becomes known\n * (webhook, CRM callback); it joins back by sessionExternalId.\n */\n static wireOutcomeHook(hook: OutcomeHook): void {\n if (state === null) {\n console.warn(\"[sight] wireOutcomeHook called before init\");\n return;\n }\n state.outcomeHook = hook;\n }\n\n /**\n * Manually capture a turn. For callers that do not use autocapture.\n *\n * - `deploymentSlug` may be omitted: the `deployment` given to `init` is\n * used. An explicit value wins.\n * - Every turn is sent with a `turnId` (a fresh UUID unless you supply\n * one). A retried send carries the same `turnId`.\n * - The turn is validated before it is sent. An invalid turn logs one\n * warning line naming the first invalid field and is dropped; nothing\n * is sent.\n *\n * Persona resolution order for the outgoing turn payload:\n * 1. turn.personaSlug (turn-level override)\n * 2. the session's persona (from startSession)\n * 3. the init-level default\n *\n * Signature-phrase matching runs in the SDK when the resolved persona\n * has signature phrases registered. The matched slug list is attached to\n * `turn.signaturePhraseMatches` before send.\n */\n static async captureTurn(turn: CaptureTurnInput): Promise<void> {\n return this.captureWithHints(turn);\n }\n\n /**\n * The one capture path. Manual captureTurn calls and autocapture both\n * land here; autocapture also passes what it observed on the request\n * (`hints`), applied below under the explicit-input-wins rule.\n */\n private static async captureWithHints(\n input: CaptureTurnInput,\n hints?: CaptureHints,\n ): Promise<void> {\n if (state === null) {\n return;\n }\n if (input === null || typeof input !== \"object\") {\n validateOrDrop(TurnInputSchema, input, \"captureTurn\");\n return;\n }\n // Never-break-the-host: `payload` is required by the TYPE, but a JS\n // caller (or an `any`-typed TS caller) can reach here without it, and\n // an unguarded property read would throw a TypeError INTO the host's\n // serving path. Normalize once; the type keeps guiding compiled callers.\n // The same pass fills the two fields the SDK owns a default for: the\n // deployment (from init) and the turn's identity.\n const turn: CapturedTurn = {\n ...input,\n deploymentSlug: input.deploymentSlug ?? state.config.deployment,\n turnId: input.turnId ?? newTurnId(),\n payload:\n input.payload === undefined || input.payload === null\n ? {}\n : input.payload,\n };\n // Validate against the wire schema BEFORE anything is sent or any\n // session state is touched (the same fire-and-log rule as every other\n // capture method). Propensity is checked where it will be sent: at the\n // top level, wherever the caller put it.\n const payloadPropensity =\n typeof turn.payload === \"object\"\n ? (turn.payload as { propensity?: PropensityInput }).propensity\n : undefined;\n const checked = validateOrDrop(\n TurnInputSchema,\n { ...turn, propensity: turn.propensity ?? payloadPropensity },\n \"captureTurn\",\n );\n if (checked === null) return;\n if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {\n return;\n }\n\n // ── Post-guardrail propensity validator ──\n // If the payload includes propensity data (customer running an OPE-\n // bearing deployment), validate the contract per Saito 2021 OBP.\n // Log-and-strip on failure — descriptive-half records still ingest,\n // but the malformed propensity payload does not corrupt downstream\n // OPE. Do NOT block turn capture; the point is honest logging, not\n // customer-blocking.\n const propensity =\n turn.propensity ??\n (turn.payload as { propensity?: PropensityInput }).propensity;\n let validPropensity: PropensityInput | undefined = propensity;\n if (propensity) {\n const contract = validatePropensityContract(propensity);\n if (!contract.ok) {\n console.warn(\n `[sight] propensity contract violation (${contract.class}): ${contract.reason}`,\n );\n // Strip malformed propensity from payload; keep the record.\n (turn.payload as { propensity?: PropensityInput }).propensity =\n undefined;\n validPropensity = undefined;\n }\n }\n\n const sessionPersona =\n state.sessions.get(turn.sessionExternalId)?.personaSlug ?? null;\n const resolvedPersona =\n turn.personaSlug ?? sessionPersona ?? state.persona?.slug ?? undefined;\n\n let signatureMatches = turn.signaturePhraseMatches;\n if (!signatureMatches && resolvedPersona) {\n // Contained (audit R4): a pathological persona regex must degrade to\n // \"no matches\", never reject a manual captureTurn into the host.\n try {\n const matcher = state.signatureMatchers.get(resolvedPersona);\n if (matcher && matcher.length > 0) {\n const text = this.extractTextForMatching(turn.payload);\n signatureMatches = text ? matchSignaturePhrases(text, matcher) : [];\n }\n } catch {\n signatureMatches = [];\n }\n }\n\n // Fold in the accumulated user-side state (from userInputSubmit /\n // userInputEdit / userInputStart / userThumbs / userRating helpers)\n // and derive interactivity signals from timestamps. Manual-capture\n // callers may reach here without startSession or the OTel processor\n // having created a session entry — create one lazily so pre-session\n // buffered signals and per-session timestamps have a home.\n let session = state.sessions.get(turn.sessionExternalId);\n if (!session) {\n session = {\n externalId: turn.sessionExternalId,\n externalUserId: null,\n turnIndex: turn.turnIndex + 1,\n startedAt: Date.now(),\n personaSlug: resolvedPersona ?? null,\n metadata: null,\n openedVia: null,\n clientContext: null,\n agentId: null,\n experimentId: null,\n environmentConfigHash: null,\n environmentConfigLabel: null,\n lastAgentTurnAt: null,\n lastUserSubmitAt: null,\n sessionContextForwarded: false,\n pendingUserInput: null,\n pendingUserOutcome: null,\n };\n boundedSessionSet(state.sessions, turn.sessionExternalId, session);\n }\n // Pre-session interaction signals (typing that started before the\n // session entry existed, including entries lazily created by the OTel\n // processor) flush here, on the turn that creates the session.\n this.flushPreSessionSignals(turn.sessionExternalId, session);\n\n let userInput: CapturedTurn[\"userInput\"] = turn.userInput;\n let userOutcome: CapturedTurn[\"userOutcome\"] = turn.userOutcome;\n let interactivity: CapturedTurn[\"interactivity\"] = turn.interactivity;\n let transition: CapturedTurn[\"transition\"] = turn.transition;\n if (session.pendingUserInput && !userInput) {\n const p = session.pendingUserInput;\n userInput = {\n text: p.text,\n firstKeystrokeMs: p.firstKeystrokeMs,\n editCount: p.editCount,\n submittedAt: p.submittedAt\n ? new Date(p.submittedAt).toISOString()\n : undefined,\n };\n }\n if (session.pendingUserOutcome && !userOutcome) {\n userOutcome = session.pendingUserOutcome;\n }\n // The person's message as autocapture observed it on the request: the\n // message that prompted this reply, the same row order as input\n // recorded with userInputSubmit above. Used only when no explicit text\n // exists for this turn (turn.userInput.text or a pending submit).\n if (hints?.observedUserText && !userInput?.text) {\n userInput = { ...(userInput ?? {}), text: hints.observedUserText };\n }\n // Agent reflect ms: time between user submit (session.lastUserSubmitAt)\n // and now (the moment we're capturing this new agent turn).\n if (!interactivity && session.lastUserSubmitAt) {\n interactivity = {\n agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt),\n };\n }\n // Transition time ms: gap between the previous agent turn's capture\n // and the user submit that led to THIS turn. Derivable only when both\n // timestamps exist: pendingUserInput.submittedAt is per-turn (reset on\n // every capture), so a submit from an earlier turn can never be\n // reused. Left unset otherwise — no guessing.\n const submittedAt = session.pendingUserInput?.submittedAt;\n if (\n !transition &&\n session.lastAgentTurnAt !== null &&\n submittedAt !== undefined &&\n submittedAt >= session.lastAgentTurnAt\n ) {\n transition = { timeMs: submittedAt - session.lastAgentTurnAt };\n }\n // Session context (openedVia / clientContext / metadata) rides the\n // first captured turn only; the worker persists it at session\n // find-or-create and ignores it on later turns. metadata merges into\n // clientContext under the `metadata` key so it lands on\n // sessions.probe_session_client_context.\n let openedVia: CapturedTurn[\"openedVia\"];\n let clientContext: CapturedTurn[\"clientContext\"];\n if (!session.sessionContextForwarded) {\n openedVia = (session.openedVia as CapturedTurn[\"openedVia\"]) ?? undefined;\n clientContext =\n session.clientContext || session.metadata\n ? {\n ...(session.clientContext ?? {}),\n ...(session.metadata ? { metadata: session.metadata } : {}),\n }\n : undefined;\n session.sessionContextForwarded = true;\n }\n // Reset per-turn pending state now that we've folded it.\n session.pendingUserInput = null;\n session.pendingUserOutcome = null;\n session.lastAgentTurnAt = Date.now();\n\n await state.client.sendTurn({\n ...turn,\n envelopeVersion: SDK_ENVELOPE_VERSION,\n personaSlug: resolvedPersona,\n signaturePhraseMatches: signatureMatches,\n // User identity from the local session entry (Sight.startSession).\n // The worker persists it on sessions.external_user_id; never the\n // session key. Turn-level override wins for advanced callers.\n externalUserId:\n turn.externalUserId ?? session.externalUserId ?? undefined,\n userInput,\n userOutcome,\n interactivity,\n transition,\n openedVia,\n clientContext,\n // Hoist validated propensity to the top-level TurnInput field: the\n // worker projection reads input.propensity (not payload.propensity)\n // when landing read_candidates / read_propensities / selection_meta\n // columns (e2e audit 2026-07-13).\n propensity: validPropensity,\n // Forward RLDS provenance from the local session entry (populated\n // by Sight.startSession). Worker persists at first-turn session\n // create; nulls stay null.\n agentId: session.agentId ?? undefined,\n experimentId: session.experimentId ?? undefined,\n environmentConfigHash: session.environmentConfigHash ?? undefined,\n environmentConfigLabel: session.environmentConfigLabel ?? undefined,\n });\n }\n\n /**\n * Emit a custom outcome event on a session, stored with the `kind`\n * string you supply. Use for\n * customer-defined kinds like \"purchase_complete\", \"handoff_to_human\",\n * \"character_break_severe\". Universal seed kinds (break, escalation,\n * resolution, thumbs_*, rating_*) are also emitted by worker-side\n * detectors automatically — call this only when the customer has a\n * signal the worker cannot infer.\n */\n static async emitOutcomeEvent(input: OutcomeEventEmit): Promise<void> {\n if (state === null) {\n console.warn(\"[sight] emitOutcomeEvent called before init\");\n return;\n }\n const validated = validateOrDrop(\n OutcomeEventEmitSchema,\n input,\n \"emitOutcomeEvent\",\n );\n if (validated === null) return;\n await state.client.sendOutcomeEvent(state.config.deployment, validated);\n }\n\n /**\n * Capture one environment event against a session. The\n * envelope is generalized: `source_type` and `event` are free strings whose\n * meaning is defined per deployment — the instrument stores the event and\n * attaches it to the session's record by time (the next turn's state\n * corner, plus the causing turn's outcome corner when `causeProvenance`\n * names a turn index), and never interprets it. Fire-and-log, like\n * captureTurn: errors are debug-logged, never thrown.\n *\n * Alignment defaults to the SDK's own clock claim; deployments with a\n * stricter clock contract (or batches) should call\n * captureEnvironmentEvents with explicit alignment provenance.\n */\n static async captureEnvironmentEvent(\n event: EnvironmentEventInput,\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\"[sight] captureEnvironmentEvent called before init\");\n return;\n }\n const validated = validateOrDrop(\n EnvironmentEventInputSchema,\n event,\n \"captureEnvironmentEvent\",\n );\n if (validated === null) return;\n const align = alignment\n ? (validateOrDrop(\n AlignmentProvenanceSchema,\n alignment,\n \"captureEnvironmentEvent\",\n ) ?? DEFAULT_ENVIRONMENT_ALIGNMENT)\n : DEFAULT_ENVIRONMENT_ALIGNMENT;\n await state.client.sendEnvironmentEvents({\n events: [validated],\n alignment: align,\n });\n }\n\n /**\n * Capture a batch of environment events with explicit alignment provenance\n * (clock_source, skew_bound_ms, rule_version). Batches are capped at 100\n * events and may span sessions — every event is self-addressed. Same\n * generalized envelope and fire-and-log discipline as the single-event\n * capture above.\n */\n static async captureEnvironmentEvents(\n events: EnvironmentEventInput[],\n alignment: AlignmentProvenance = DEFAULT_ENVIRONMENT_ALIGNMENT,\n ): Promise<void> {\n if (state === null) {\n console.warn(\"[sight] captureEnvironmentEvents called before init\");\n return;\n }\n const batch = validateOrDrop(\n EnvironmentEventsBatchSchema,\n { events, alignment },\n \"captureEnvironmentEvents\",\n );\n if (batch === null) return;\n await state.client.sendEnvironmentEvents(batch);\n }\n\n /**\n * Capture one sub-turn span against a session: one LLM call, one tool\n * call, one framework step, or a custom unit inside a turn. The span lands\n * on the turn named by `turnIndex`, or — when omitted — on the session's\n * latest turn at/under the span's `startedAt` (most recent turn when\n * `startedAt` is also absent). A span whose turn cannot be resolved is\n * dropped server-side; spans never land unattributed. Fire-and-log, like\n * captureTurn: errors are debug-logged, never thrown.\n *\n * `attributes` are metadata only (tool names, argument shapes) — never\n * free-text conversation content. Alignment defaults to the SDK's own\n * clock claim; deployments with a stricter clock contract (or batches, or\n * parent references between spans) should call captureSpans.\n */\n static async captureSpan(\n span: SpanInput,\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\"[sight] captureSpan called before init\");\n return;\n }\n const validated = validateOrDrop(SpanInputSchema, span, \"captureSpan\");\n if (validated === null) return;\n const align = alignment\n ? (validateOrDrop(AlignmentProvenanceSchema, alignment, \"captureSpan\") ??\n DEFAULT_SPAN_ALIGNMENT)\n : DEFAULT_SPAN_ALIGNMENT;\n await state.client.sendSpans({ spans: [validated], alignment: align });\n }\n\n /**\n * Capture a batch of spans with explicit alignment provenance\n * (clock_source, skew_bound_ms, rule_version). Batches are capped at 50\n * spans and may span sessions — every span is self-addressed. Parent\n * structure rides the batch: a span's `parentSpanId` names another span's\n * caller-local `spanId` within the same batch and is wired server-side\n * (unresolvable references land null). Same fire-and-log discipline as the\n * single-span capture above.\n */\n static async captureSpans(\n spans: SpanInput[],\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\"[sight] captureSpans called before init\");\n return;\n }\n const batch = validateOrDrop(\n SpansBatchSchema,\n { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT },\n \"captureSpans\",\n );\n if (batch === null) return;\n await state.client.sendSpans(batch);\n }\n\n /**\n * Flag a persona break for a session. Wire this to the customer's in-product\n * \"that didn't sound like you\" UX. Populates the `user_flagged_break`\n * outcome column on the dashboard.\n *\n * If `turnIndex` is omitted, the flag attaches to the session's most\n * recent turn.\n */\n static async flagPersonaBreak(input: FlagPersonaBreakInput): Promise<void> {\n if (state === null) {\n console.warn(\"[sight] flagPersonaBreak called before init\");\n return;\n }\n const validated = validateOrDrop(\n FlagPersonaBreakSchema,\n input,\n \"flagPersonaBreak\",\n );\n if (validated === null) return;\n await state.client.sendFlag(state.config.deployment, validated);\n }\n\n /**\n * Best-effort extraction of the response text from a captured turn's payload\n * for signature-phrase matching. Adapters populate `payload.response.text`\n * or `payload.text` by convention; this method looks for both.\n */\n private static extractTextForMatching(\n payload: Record<string, unknown>,\n ): string {\n const response = payload[\"response\"];\n if (response && typeof response === \"object\") {\n const responseText = (response as Record<string, unknown>)[\"text\"];\n if (typeof responseText === \"string\") return responseText;\n }\n if (typeof payload[\"text\"] === \"string\") return payload[\"text\"] as string;\n return \"\";\n }\n\n /**\n * Shut down the SDK: discards the singleton state (sessions, pending\n * user-side signals, the pre-session buffer) so init() can be called\n * again. There is no send queue to flush — every capture awaits its own\n * HTTP send — and instrumentation stays registered for the life of the\n * process. Idempotent.\n */\n static async shutdown(): Promise<void> {\n if (state === null) {\n return;\n }\n // Drain in-flight sends first (bounded by the client's send timeout):\n // short-lived processes (serverless, CLI scripts) exit right after this,\n // and a send still on the wire at exit is lost. Each send is fire-and-\n // forget at capture time, so the drain is usually instant.\n const client = state.client;\n // Detach autocapture from this state (audit R1): the span processor\n // stays registered (OTel providers cannot remove processors) but stops\n // reading the dead state — post-shutdown LLM calls no longer grow an\n // orphaned sessions map, and a re-init rebinds cleanly.\n detachOtelState();\n state = null;\n await client.drainInFlight();\n }\n\n // ── Internal helpers ─────────────────────────────────────────────────────\n\n /** Package-internal: instrumentation adapters read this to build turns. */\n static _getState(): ProbeState | null {\n return state;\n }\n\n private static shouldSample(sessionId: string, turnIndex: number): boolean {\n if (state === null) return false;\n const rate = state.config.sampleRate;\n if (rate >= 1.0) return true;\n if (rate <= 0.0) return false;\n // Deterministic hash so a given (sessionId, turnIndex) always resolves identically.\n // FNV-1a 32-bit for portability across runtimes.\n const key = `${sessionId}:${turnIndex}`;\n let hash = 0x811c9dc5;\n for (let i = 0; i < key.length; i++) {\n hash ^= key.charCodeAt(i);\n hash = (hash * 0x01000193) >>> 0;\n }\n return hash / 0xffffffff < rate;\n }\n}\n"]}
|