@cultured_computer/sight 0.10.2 → 0.10.3
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 +31 -3
- package/README.md +3 -2
- package/dist/cli.js +5527 -151
- package/dist/index.cjs +105 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +100 -6
- package/dist/index.d.ts +100 -6
- package/dist/index.js +105 -24
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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/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","../src/field.ts"],"names":["response","z","context","propagation","createContextKey","state","asString","asNumber","messageText","value","bound","warnedUnbound","buildPayload","emit","performance","createRequire","trace","registered","instrumentation","SessionEndSchema","now","isRecord"],"mappings":";;;;;;;;;;AA4BO,IAAM,qBAAA,GAAwB,2CAAA;AAQrC,IAAM,mBAAA,GAAsB,EAAA;AAO5B,IAAM,eAAA,GAAkB,IAAA;AAOxB,IAAM,YAAA,GAAe,EAAA;AAOrB,IAAM,mBAAA,GAAsB,GAAA;AAE5B,IAAM,kBAAA,GAAqB,KAAA;AAG3B,eAAe,oBAAoB,QAAA,EAAqD;AACtF,EAAA,IAAI,CAAC,QAAA,CAAS,IAAA,EAAM,OAAO,EAAC;AAC5B,EAAA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A,EAAQ,kBAAA;AAAA,UACR,QAAQ,IAAA,CAAK;AAAA,SACd,CAAA;AACD,QAAA,OAAO,KAAsB,QAAQ,CAAA;AAAA,MACvC,CAAA;AAAA,MACA,OAAO,MAAA,CAAO,OAAA,EAAS,IAAA,EAAM;AAC3B,QAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,MAAA,EAAQ,gBAAgB,OAAA,CAAQ,OAAO,CAAC,CAAA,MAAA,CAAA,EAAU;AAAA,UAC/E,IAAA,EAAM,SAAS,IAAI,CAAA;AAAA,UACnB,WAAA,EAAa,kBAAA;AAAA,UACb,MAAA,EAAQ,mBAAA;AAAA,UACR,QAAQ,IAAA,CAAK;AAAA,SACd,CAAA;AACD,QAAA,IAAI,CAAC,SAAS,IAAA,EAAM;AACpB,QAAA,OAAO,UAAA,CAAW,SAAS,IAAI,CAAA;AAAA,MACjC;AAAA,KACF;AAAA,IACA,QAAA,EAAU;AAAA,MACR,MAAM,GAAA,CAAI,EAAA,EAAI,GAAA,GAAM,EAAC,EAAG;AACtB,QAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,KAAA,EAAO,gBAAgB,OAAA,CAAQ,EAAE,CAAC,CAAA,CAAA,EAAI,EAAE,MAAA,EAAQ,kBAAA,EAAoB,MAAA,EAAQ,GAAA,CAAI,QAAQ,CAAA;AACvH,QAAA,OAAO,KAAyB,QAAQ,CAAA;AAAA,MAC1C;AAAA;AACF,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * HTTP client for the Sight API. Internal; use the `Sight` methods.\n *\n * Sends captured turns to POST /v1/turns with a Bearer token. A failed send\n * is logged with `debug: true` and never thrown. The first send the API\n * rejects (a 4xx other than 429) prints one warning without `debug`, once\n * per process for each of: 401, 403, any other status. A rate-limited send\n * (429) is retried once after Retry-After; if the retry is limited too,\n * that capture is dropped.\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 link printed after the first accepted turn. */\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\nconst MAX_ACK_BODY_BYTES = 65_536;\n\n/** Only debug turns read acknowledgements; all other bodies are discarded. */\nasync function readAcknowledgement(response: Response): Promise<{ pendingId?: string }> {\n if (!response.body) return {};\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > MAX_ACK_BODY_BYTES) throw new Error('acknowledgement exceeds 65536 bytes');\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }\n const body: unknown = JSON.parse(new TextDecoder().decode(bytes));\n return body !== null && typeof body === 'object' && 'pendingId' in body && typeof body.pendingId === 'string'\n ? { pendingId: body.pendingId }\n : {};\n } finally {\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n\nexport class IngestClient {\n private apiKey: string;\n private endpoint: string;\n private debug: boolean;\n private dashboardUrl: string;\n /**\n * The first accepted turn prints one stderr line with a link to the\n * session on the dashboard, once per client (one client per init). A\n * failed send does not use it up. Only turns print it; flags, outcome\n * events and session ends do not.\n */\n private firstCaptureAnnounced = false;\n /**\n * Rate limiting (429): the first 429 prints one stderr warning, with or\n * without `debug`; later ones log only with `debug: true`. Each\n * rate-limited request is retried once after Retry-After. At most 50\n * retries wait at a time; past that, a rate-limited request is dropped.\n */\n private rateLimitAnnounced = false;\n private pendingRetries = 0;\n /**\n * Rejected sends (a 4xx other than 429): the first one of each class\n * (401, 403, any other status) prints one stderr warning, with or\n * without `debug`. A rejected send is never retried: the same key and\n * the same body get the same answer.\n */\n private rejectionAnnounced = new Set<'401' | '403' | 'other'>();\n private inFlight = 0;\n private shedAnnounced = false;\n\n /**\n * Every send goes through here: a 15 second timeout per send and at most\n * 64 sends in flight. Past that, a new send is dropped, not queued; the\n * first drop prints one stderr warning, later ones log only with\n * `debug: true`.\n */\n private async guardedFetch(\n url: string,\n init: RequestInit,\n consume?: (response: Response) => Promise<void>,\n ): 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 are already in flight, so new captures are dropped until some finish. The Sight API is slow or unreachable: check the endpoint and your network. This warning prints once per process.`,\n );\n }\n throw new Error(`${MAX_INFLIGHT} sends already in flight; this send was dropped`);\n }\n this.inFlight++;\n let response: Response | undefined;\n try {\n response = await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });\n await consume?.(response);\n return response;\n } finally {\n // fetch resolves at headers. Keep the slot until any debug body read\n // finishes or an unused body is cancelled, including failed/retry sends.\n if (response?.body && !response.body.locked) await response.body.cancel().catch(() => {});\n this.inFlight--;\n }\n }\n\n /**\n * Wait for sends in flight and pending retries, for at most `timeoutMs`\n * (default 15 seconds). Called by Sight.shutdown() so a short-lived\n * process can exit without losing a send. A retry still waiting when\n * the time is up is not guaranteed to be sent.\n */\n async drainInFlight(timeoutMs = SEND_TIMEOUT_MS): Promise<void> {\n const deadline = performance.now() + timeoutMs;\n while ((this.inFlight > 0 || this.pendingRetries > 0) && performance.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. Errors are logged with `debug: true`, never thrown.\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: its body is ${bodyBytes} bytes, over the ${MAX_TURN_BODY_BYTES}-byte limit ` +\n `(session=${turn.sessionExternalId} turn=${turn.turnIndex}). Send a smaller payload.`,\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 }, async (response) => {\n if (!response.ok) return;\n // Acceptance is known at headers, even if the optional debug\n // acknowledgement later fails. Never resend such a capture.\n if (!this.firstCaptureAnnounced) {\n this.firstCaptureAnnounced = true;\n console.error(\n `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`,\n );\n }\n if (this.debug) {\n const ack = await readAcknowledgement(response);\n this.log(`[sight] ingest ok id=${ack.pendingId ?? '?'}`);\n }\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n\n if (!response.ok) {\n this.announceRejection(response.status, 'a turn');\n this.log(`[sight] ingest failed status=${response.status}`);\n return;\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. Errors are logged with `debug: true`, never\n * thrown.\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.announceRejection(response.status, 'a flag');\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: why the session ended. Errors are logged with\n * `debug: true`, never thrown.\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.announceRejection(response.status, 'a session end');\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. Errors are logged with `debug: true`, never\n * thrown.\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.announceRejection(response.status, 'an outcome event');\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 a batch of environment events. Errors are logged with\n * `debug: true`, never thrown.\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.announceRejection(response.status, 'an environment events batch');\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 batch of spans. Errors are logged with `debug: true`, never\n * thrown.\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.announceRejection(response.status, 'a spans batch');\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 * The 429 retry rule. Any other response passes through. A 429 is sent\n * again once after Retry-After seconds (1 second when the header is\n * missing or unreadable; kept between 1 and 60 seconds). The retry's\n * response is returned as is, so a second 429 is not retried. Returns\n * null when the retry was dropped because 50 retries were already\n * waiting. A waiting retry does not keep the process alive.\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 // Not gated on debug: rate limiting that persists loses captures, so\n // the host is told once per process. Stderr only, same channel as\n // log().\n\n console.error(\n '[sight] rate limited (429). Each rate-limited send is retried once after Retry-After; if the retry is limited too, that capture is dropped. Send fewer requests per minute or ask for a higher limit: https://sight.cultured.computer/docs/sdk-reference#rate-limits (this warning prints once per process)',\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 /**\n * The once-per-class warning for a send the API rejected. Not gated on\n * debug: a rejected key drops every capture, so the host is told once.\n * 429 has its own warning (see retryIfRateLimited); a 5xx is the API's\n * failure, not the host's, and stays a debug line.\n */\n private announceRejection(status: number, what: string): void {\n if (status < 400 || status >= 500 || status === 429) return;\n const cls = status === 401 ? '401' : status === 403 ? '403' : 'other';\n if (this.rejectionAnnounced.has(cls)) return;\n this.rejectionAnnounced.add(cls);\n const line =\n cls === '401'\n ? '[sight] the API rejected the key (401). Nothing is being captured. Set apiKey to a key with the ingest capability.'\n : cls === '403'\n ? '[sight] this key cannot capture (403): it lacks the ingest permission. Nothing is being captured. Ask the project owner for a Capture key.'\n : `[sight] the API rejected ${what} (${status}) and it was dropped. Set debug: true to log every failed send. This warning prints once per process.`;\n\n console.error(line);\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 * A signature phrase you define for a persona: a plain phrase or a regex.\n * The SDK matches the phrases against each reply and sends the matched\n * slugs with the turn.\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 /** The persona's slug. */\n slug: z.string().min(1),\n /**\n * The persona's description (role, identity, communication, engagement):\n * an object, or a string reference to one. Optional. This SDK does not\n * read or send it.\n */\n rice: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),\n /**\n * Signature phrases for this persona. Compiled once and matched against\n * each reply in the SDK; matched slugs are sent with the turn as\n * `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 * Resolves the outcome of a finished session. Called by\n * Sight.endSession() with the session's externalId; a non-null result is\n * sent as an outcome event on the session. Not called for a session you\n * never end; use emitOutcomeEvent() for an outcome known later.\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: a key with the `ingest` capability. Required. */\n apiKey: z.string().min(1),\n /** Deployment slug: the configuration this traffic belongs to. Required. */\n deployment: z.string().min(1),\n /** The API host the captures are sent to. Defaults to\n `https://api.cultured.computer`. */\n endpoint: z.string().url().default(\"https://api.cultured.computer\"),\n /**\n * Dashboard base URL for the link printed on stderr after the first\n * accepted turn. Set it only for a self-hosted or staging dashboard.\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 * Share of turns sent, from 0 to 1. Default 1.0: every turn. Below 1.0\n * the choice is deterministic per (session id, turn index). Applies to\n * autocapture and to captureTurn.\n */\n sampleRate: z.number().min(0).max(1).default(1.0),\n /**\n * Debug mode: log every send and every failed send to stderr, prefixed\n * `[sight]`. Never logs the API key or conversation text.\n */\n debug: z.boolean().default(false),\n});\nexport type ProbeConfig = z.infer<typeof ProbeConfigSchema>;\n/**\n * The argument of Sight.init(). Fields with a default (endpoint,\n * dashboardUrl, sampleRate, debug) are optional here. `ProbeConfig` is the\n * same configuration after init has applied the defaults.\n */\nexport type ProbeConfigInput = z.input<typeof ProbeConfigSchema>;\n\n// ── Session context (customer identifies persona per session) ──────────────\n\nexport const SessionStartSchema = z.object({\n /** Your id for the session: one conversation. Any non-empty string. */\n externalId: z.string().min(1),\n /**\n * Your id for the person: a stable, pseudonymous string, distinct from\n * externalId. It ties one person's sessions together and is sent with\n * every captured turn. Optional; without it, sessions are still captured\n * and nothing links them to a returning person.\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 /** How the person arrived in this session. */\n openedVia: z\n .enum([\"link\", \"notification\", \"resume\", \"direct\", \"share\"])\n .optional(),\n /**\n * Client context: locale, timezone, runtime, and anything else you\n * choose to include. Stored as sent. See startSessionWithContext.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n /**\n * Your own metadata for the session. Sent with the first captured turn,\n * inside `clientContext` under the `metadata` key, and stored as sent.\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n /**\n * Version tags for the session, used to compare versions on the\n * dashboard. All optional.\n * agentId model or policy version\n * experimentId A/B arm or feature flag\n * environmentConfigHash hash of the prompt or configuration\n * (see Sight.hashEnvironmentConfig)\n * environmentConfigLabel readable name for that version\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 * The argument of Sight.endSession(): why the session ended. When you know\n * the outcome at close (a resolved ticket, an escalation), pass `outcome`\n * and optional `outcomeDetail`; the SDK sends it as an outcome event.\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 version of the turn format this SDK sends. Set by the SDK on every\n * captured turn; a value you supply is replaced.\n */\n envelopeVersion?: string;\n /**\n * Your id for the person. Filled from Sight.startSession({\n * externalUserId }) when omitted. Never defaults to sessionExternalId.\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 for this turn. When omitted: the session's persona from\n * startSession(), then the default from init.\n */\n personaSlug?: string;\n /**\n * Slugs of the persona's signature phrases found in the reply. Computed\n * by the SDK when omitted. Empty or absent when none matched or none are\n * registered.\n */\n signaturePhraseMatches?: string[];\n /**\n * Optional fields from your own decision layer, sent as given: how it\n * classified the situation and what it chose. Autocapture never sets it.\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 * Timing of the reply: time from the person's submit to the captured\n * turn, whether the stream completed, 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 * The person's feedback on the turn: rating (1 to 5), thumbs.\n *\n * `flaggedBreak` is deprecated: use Sight.flagPersonaBreak(), which\n * records an outcome event. The boolean is still accepted.\n */\n userOutcome?: {\n flaggedBreak?: boolean;\n explicitRating?: number;\n thumbs?: \"up\" | \"down\";\n };\n /**\n * The candidate replies and the probability of each, when your system\n * chooses among candidates. Supply it here or in payload.propensity;\n * captureTurn checks it and sends a valid one. An invalid one logs one\n * warning and is removed; the turn is still sent.\n */\n propensity?: PropensityInput;\n /**\n * The person's response to the previous reply: the time from that reply\n * to this turn's submit. Derived by the SDK when both times are known;\n * you may also supply it.\n */\n transition?: {\n timeMs?: number;\n lengthDelta?: number;\n };\n /**\n * Session context from Sight.startSession, sent on the first captured\n * turn of a session and omitted on later turns.\n */\n openedVia?: \"link\" | \"notification\" | \"resume\" | \"direct\" | \"share\";\n clientContext?: Record<string, unknown>;\n /**\n * Version tags from Sight.startSession, sent on every turn so each turn\n * is attributed to the version that produced it. Absent when not 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// An outcome you record on a session (a resolution, an escalation, a\n// conversion). `kind` is any non-empty string.\nexport const OutcomeEventEmitSchema = z.object({\n sessionExternalId: z.string().min(1),\n kind: z.string().min(1),\n /** The turn that caused the outcome. Omit to attach to the latest turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Your own detail for the outcome. Optional. */\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. You choose which fields\n * are sent with 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 /** Your own key/value pairs 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 three\n * autocapture paths (the `ai` telemetry integration in vercel-ai.ts,\n * wrapOpenAI, and the span processor) from capturing one call twice.\n *\n * Precedence: the `ai` integration, then wrapOpenAI, then the span\n * processor. The `ai` integration sees the call the way the application\n * made it (the model reply as `ai` parsed it, the per-call session id). A\n * wrapped client records the first-token time and the cost the provider\n * reported, which a span does not carry.\n *\n * Three 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 call through a client that is both wrapped and module-patched.\n * wrapOpenAI runs the underlying call under the same marker, so the\n * span the patch starts for that call is skipped.\n *\n * 3. 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 HANDLED_CALL_KEY = createContextKey('sight.handled_model_call');\n\n/**\n * Run `fn` in a context marked as \"inside a model call a Sight path\n * already captures\" (the `ai` integration or a wrapped client).\n */\nexport function runInsideHandledCall<T>(fn: () => T): T {\n return context.with(context.active().setValue(HANDLED_CALL_KEY, true), fn);\n}\n\n/** True when `ctx` (default: the active context) is inside such a call. */\nexport function isInsideHandledCall(ctx: Context = context.active()): boolean {\n return ctx.getValue(HANDLED_CALL_KEY) === true;\n}\n\n// ── Response id claims (case 3) ───────────────────────────────────────────\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 or a wrapped OpenAI client\n * captures is not captured a second time from a span (see ai-dedupe.ts): a\n * span started inside that call is skipped, and so is a span carrying the\n * response id the `ai` 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 { isInsideHandledCall, 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 a model call another Sight path captures: an `ai`\n * model call the `ai` integration handles (a provider that calls an\n * instrumented client), or a call through a wrapped OpenAI client that\n * is also module-patched. Never turns.\n */\n private readonly insideHandledCall = 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 (isInsideHandledCall(parentContext)) this.insideHandledCall.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 or a wrapped client\n // captures this call.\n if (this.insideHandledCall.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] a span could not be read and was skipped (${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] a span could not be read and was skipped (${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] a turn read from a span was not captured (${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) needs CommonJS and an openai version the\n * bundled instrumentation supports. wrapOpenAI() wraps the client instance\n * 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 * A wrapped client that is also module-patched (CommonJS, `openai` loaded\n * after init) sends one turn per call, the wrap's: the span the patch\n * emits for the call is skipped (see ai-dedupe.ts).\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 { isInsideHandledCall, runInsideHandledCall } 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: a call ran before Sight.init() and was not captured. Call Sight.init() once at startup.',\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: a turn was not captured (${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 (isInsideHandledCall()) 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 // The underlying call runs under the handled-call marker: when the\n // client is also module-patched, the patch starts a span for this same\n // call, and the span processor skips a span started under the marker.\n // This turn is the one sent: it has the first-token time and the cost\n // the provider reported.\n const result = runInsideHandledCall(() => (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 runInsideHandledCall,\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: a call ran before Sight.init() and was not captured. Call Sight.init() once at startup.',\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: a turn was not captured (${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: an event could not be read and was skipped (${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 runInsideHandledCall(() => 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] ai below 7 found: nothing 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] ai: the telemetry integration was already registered.');\n return;\n }\n (registerTelemetry as (...integrations: unknown[]) => void)(sightTelemetry());\n if (debug) {\n console.log(\n '[sight] 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] ai was not found, so nothing was registered. If ai is bundled where the SDK cannot resolve it, call registerTelemetry(sightTelemetry()) yourself.',\n );\n }\n return;\n }\n }\n try {\n register(mod, debug);\n } catch (err) {\n if (debug) {\n console.warn(\n `[sight] ai: the telemetry integration was not registered (${err instanceof Error ? err.message : err}). Call registerTelemetry(sightTelemetry()) yourself.`,\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: enrichTokens on.\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 error: ${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 module instrumentation is not enabled (${msg}). Wrap the client: wrapOpenAI(new OpenAI()).`);\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 `. It needs CommonJS and an openai version the bundled instrumentation supports. ` +\n `Calls through a client passed to wrapOpenAI() are captured; calls through an unwrapped OpenAI client are not. ` +\n `Fix: import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()).`\n );\n}\n\n/**\n * The copy of `openai` the application will use. The package ships its\n * CommonJS and ESM files as separate module instances, and the patch\n * attaches to the one loaded through `require`. So the CommonJS build of\n * this SDK inspects the `require`d copy, and the ESM build inspects\n * `import('openai')`. Checking the other copy reports a detached patch\n * that is attached.\n *\n * CommonJS is detected by `module.require`: Node defines `module` only in\n * a CommonJS file. It is read through `module`, not as a bare `require`,\n * because the bundler replaces a bare `require` in the ESM build with a\n * stand-in that is always a function and always throws.\n */\nasync function loadApplicationOpenAI(): Promise<any> {\n const cjsRequire: ((id: string) => unknown) | null =\n typeof module !== 'undefined' && typeof module.require === 'function'\n ? module.require.bind(module)\n : null;\n if (cjsRequire !== null) return cjsRequire('openai');\n return import('openai');\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 loadApplicationOpenAI();\n // Read at check time, after the load above has settled, so a client\n // 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 error: ${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 is not enabled (${msg}). Anthropic calls are not captured; record them with Sight.captureTurn().`,\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 error: ${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 is not enabled (${msg}). LangChain calls are not captured; record them with Sight.captureTurn().`,\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: model calls go through the LangChain instrumentation; no separate setup.',\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 (Python) calls are not captured by this SDK. Record them with Sight.captureTurn() or the HTTP API.',\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: a call through an OpenAI client pointed at Inception is sent with provider \"inception\". Wrap the client with wrapOpenAI().',\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: recorded a 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] an instrumentation failed to register (${result.reason}); calls through that library are not captured.`);\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\";\nimport { SOURCE_SESSION_KEY } from \"./session-origin\";\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) ─────\n/** Who writes a session's replies, as a client states it. */\nexport const REPLIES_BY = [\"model\", \"person\"] as const;\nexport type RepliesBy = (typeof REPLIES_BY)[number];\n\n/** The session column's value for each (sessions.subject_type). */\nexport const SUBJECT_TYPE_OF_REPLIES_BY: Record<RepliesBy, \"agent\" | \"human\"> = {\n model: \"agent\",\n person: \"human\",\n};\n\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 /**\n * Who writes the replies of this session: a model (the default) or a\n * person, as in a call between two people where one of them is the\n * agent. Session context like openedVia: the worker writes it on the\n * session at create (sessions.subject_type, 'agent' or 'human') and\n * ignores it afterwards. The session is created by whichever turn is\n * processed first, which need not be the first one sent, so send it on\n * every turn of the session (the import does). A session that\n * says a person replies carries no served model, and a judge run reads\n * that as a declaration, never as a model that went unrecorded.\n */\n repliesBy: z.enum(REPLIES_BY).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, SOURCE_SESSION_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\";\nexport * from \"./session-origin\";\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: 'my-assistant',\n * });\n *\n * // Model 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 * recorded before any session entry existed for their externalId. Moved\n * into the session entry when it is created (startSession, or the first\n * captured turn). Holds at most 100 session ids; the oldest is dropped.\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 /** Your user id from startSession; sent with 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 * Time of the last captured turn. Used on the next turn to derive\n * transition.timeMs (previous reply to this turn's submit) and\n * firstKeystrokeMs (previous reply to typing start).\n */\n lastAgentTurnAt: number | null;\n /**\n * Time of the last userInputSubmit. Used when a turn is captured to\n * derive agentReflectMs (submit to capture). transition.timeMs uses the\n * per-turn pendingUserInput.submittedAt instead, which resets on every\n * capture, so an earlier submit is never reused for it.\n */\n lastUserSubmitAt: number | null;\n /**\n * True once openedVia/clientContext have been sent with a captured turn.\n * The server stores session context from the first turn of a session, so\n * the SDK sends it once.\n */\n sessionContextForwarded: boolean;\n /** The person's input held for the next captured turn. */\n pendingUserInput: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount: number;\n submittedAt?: number;\n } | null;\n /** Thumbs or rating held for the next captured turn. */\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}` : \"the input does not match the expected shape\"}). Nothing was sent; fix that field.`,\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. Throws on an invalid\n * configuration; no other method throws on bad input. A second call\n * prints one warning and is ignored; call shutdown() first to\n * re-initialize.\n */\n static init(config: ProbeConfigInput): void {\n if (state !== null) {\n console.warn(\n \"[sight] Sight.init() was called again and ignored. Call Sight.shutdown() first to change the configuration.\",\n );\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 model call made inside\n * `fn` through a wrapped OpenAI client, the Vercel AI SDK or an\n * instrumented library is captured as a turn on the session `sessionId`\n * (your conversation id).\n *\n * Required for autocapture: a call made outside any session scope is not\n * captured. The first such call in a process prints one warning; later\n * ones log only with `debug: true`. Exceptions, used only when there is\n * no scope: a span that carries `gen_ai.conversation.id`, and an `ai`\n * call that names its session (see `sightTelemetry`). An explicit scope\n * always wins.\n *\n * The scope is carried across awaits. Returns what `fn` returns.\n */\n static async withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n ): Promise<T> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.withSession() ran before Sight.init(): the callback ran, nothing is captured. Call Sight.init() once at startup.\",\n );\n return fn();\n }\n return withSessionContext(sessionId, fn);\n }\n\n /**\n * Set the default persona for the process. Replaces the previous default.\n * To set a persona per session, use startSession({ externalId, persona }).\n */\n static identifyPersona(persona: PersonaConfig): void {\n if (state === null) {\n console.warn(\n \"[sight] Sight.identifyPersona() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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. Optional: a session is created on its\n * first captured turn. Call it to attach `externalUserId` (your stable,\n * pseudonymous user id), a persona, version tags or client context.\n *\n * Calling it again with the same externalId updates the entry. Invalid\n * input logs one warning and is ignored.\n */\n static startSession(input: SessionStart): void {\n if (state === null) {\n console.warn(\n \"[sight] Sight.startSession() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * SHA-256 hex hash of prompt or configuration text, for\n * `environmentConfigHash` on Sight.startSession(). The hash identifies a\n * version; pass a readable name alongside as `environmentConfigLabel`.\n *\n * Autocapture uses the same hash: when it sees a system prompt and the\n * session has no environmentConfigHash, the session gets the system\n * prompt's hash and the label 'auto:' plus its first 8 characters.\n * Values you pass to startSession always win.\n */\n static async hashEnvironmentConfig(input: string): Promise<string> {\n return hashEnvironmentConfig(input);\n }\n\n /**\n * End a session: sends the end reason (`natural` when none is given) and\n * releases the session's in-memory entry. Optional; a session you never\n * end times out on the server.\n *\n * - `outcome` (with optional `outcomeDetail`) is sent as an outcome\n * event before the session end.\n * - With no `outcome` and an outcome hook registered (init `outcomeHook`\n * or wireOutcomeHook()), `hook.resolve(externalId)` runs; a non-null\n * result is sent as an outcome event. This is the only place the hook\n * runs. A hook that throws logs one warning and does not break\n * endSession.\n * - For an outcome known later, or for a session you never end, call\n * emitOutcomeEvent().\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] the outcome hook's resolve() threw, so no outcome was sent for this session. Fix the hook, or send the outcome with Sight.emitOutcomeEvent(). Error:\",\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] the session end was not sent. Call Sight.endSession() again, or leave the session to time out. Error:\",\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 time since the previous reply,\n * sent as `userInput.firstKeystrokeMs` with the next captured turn. No\n * value is sent before the session's first captured turn.\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) and the submit time.\n * Both are sent with the next captured turn: a turn's person text is the\n * message that prompted its reply. Call it before the model call.\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 /** Record a thumbs-up or thumbs-down. Sent with the next captured 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 * Record a rating: an integer from 1 to 5. Sent with the next captured\n * turn. 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 * startSession, with client context (locale, timezone, runtime) collected\n * for you unless `input.clientContext` is given.\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: the deployment's outcome type and a\n * resolver for it. `resolve(sessionExternalId)` runs only when you call\n * endSession() without an `outcome`; the SDK runs no timers. A non-null\n * result is sent as an outcome event on the session. For a session you\n * never end, or an outcome known later (webhook, CRM callback), call\n * emitOutcomeEvent(); it joins to the session by sessionExternalId.\n */\n static wireOutcomeHook(hook: OutcomeHook): void {\n if (state === null) {\n console.warn(\n \"[sight] Sight.wireOutcomeHook() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\n return;\n }\n state.outcomeHook = hook;\n }\n\n /**\n * Capture a turn yourself, for a model call autocapture does not see.\n *\n * - `turnIndex` is the turn's position in the session, starting at 0.\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 checked 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 * - A failed send never throws; it logs with `debug: true`. The first\n * send the API rejects (401, 403, another 4xx) prints one warning\n * without it.\n *\n * Persona used for the turn, in this order:\n * 1. turn.personaSlug\n * 2. the session's persona (from startSession)\n * 3. the default from init or identifyPersona\n *\n * When that persona has signature phrases, the SDK matches them against\n * the reply text and sends the matched slugs as\n * `signaturePhraseMatches`.\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 * Record an outcome on a session, stored with the `kind` string you\n * supply: for example \"ticket_resolved\", \"purchase_complete\",\n * \"handoff_to_human\". Call it wherever the outcome becomes known, at any\n * time after the session; it joins to the session by sessionExternalId.\n * Invalid input logs one warning and is dropped. A failed send never\n * throws.\n */\n static async emitOutcomeEvent(input: OutcomeEventEmit): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.emitOutcomeEvent() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record one event from a channel beside the conversation (a feed, a\n * game state, an editor buffer) against a session. `source_type` and\n * `event` are free strings; you define their meaning. The event is\n * stored and attached to the session's turns by time, and is not\n * interpreted. Errors are logged with `debug: true`, never thrown.\n *\n * `alignment` describes the clock the event's time comes from. It\n * defaults to this process's clock; to state your own clock, or to send\n * a batch, call captureEnvironmentEvents.\n */\n static async captureEnvironmentEvent(\n event: EnvironmentEventInput,\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.captureEnvironmentEvent() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record a batch of environment events, with an optional `alignment`\n * (clock_source, skew_bound_ms, rule_version) describing their clock. At\n * most 100 events per call. Events in one batch may belong to different\n * sessions; each names its own. Errors are logged with `debug: true`,\n * never thrown.\n */\n static async captureEnvironmentEvents(\n events: EnvironmentEventInput[],\n alignment: AlignmentProvenance = DEFAULT_ENVIRONMENT_ALIGNMENT,\n ): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.captureEnvironmentEvents() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record one span: a step inside a turn (a model call, a tool call, a\n * framework step, or a custom unit). The span attaches to the turn named\n * by `turnIndex`; when omitted, to the session's latest turn at or\n * before the span's `startedAt` (the most recent turn when `startedAt`\n * is absent too). A span whose turn cannot be found is dropped by the\n * server. Errors are logged with `debug: true`, never thrown.\n *\n * `attributes` are metadata only (tool names, argument shapes), never\n * conversation text. `alignment` defaults to this process's clock; to\n * state your own clock, send a batch, or link parent and child spans,\n * call captureSpans.\n */\n static async captureSpan(\n span: SpanInput,\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.captureSpan() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record a batch of spans, with an optional `alignment` (clock_source,\n * skew_bound_ms, rule_version) describing their clock. At most 50 spans\n * per call. Spans in one batch may belong to different sessions; each\n * names its own. To link parent and child, give a span a `spanId` and\n * name it in another span's `parentSpanId` within the same batch; a\n * reference that matches no span is stored as null. Errors are logged\n * with `debug: true`, never thrown.\n */\n static async captureSpans(\n spans: SpanInput[],\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.captureSpans() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record a person's report that a reply was out of character. Connect it\n * to your product's report control. With no `turnIndex`, the flag\n * attaches to the session's most recent turn.\n */\n static async flagPersonaBreak(input: FlagPersonaBreakInput): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.flagPersonaBreak() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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: waits for sends in flight (at most 15 seconds),\n * then clears the in-memory state (sessions, pending input) so init()\n * can be called again. Model calls made after shutdown are not captured\n * until the next init. Await it before a short-lived process exits; a\n * send still in flight at exit is lost. Safe to call more than once.\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 /** Internal. Not part of the public API. */\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","/**\n * The serving client: a typed client for the Field API, the routes that put\n * a profile (a SOUL.md) at a name, serve it turn by turn and read its\n * record. It is separate from the capture API (`Sight`) and shares nothing\n * with it: its own key, its own requests, no process state.\n *\n * import { createFieldClient } from '@cultured_computer/sight';\n *\n * const field = createFieldClient({ apiKey: process.env.SIGHT_APP_KEY! });\n * await field.profiles.put('listener', soulMarkdown);\n * await field.conversations.start('listener', { conversation: 'c-1', user: 'u-1' });\n * const { reply } = await field.turns.send('listener', { conversation: 'c-1', message: 'Hi' });\n *\n * Every refused request throws a `FieldRefusal` carrying the HTTP status,\n * the refusal `code` and, when the answer has one, the `reason`. Nothing is\n * retried: a turn is not idempotent, and a refusal names what to do.\n *\n * Server-side only: the key it holds can rewrite the profile.\n */\n\n/** The API host. Every machine call, capture and serving, goes to it. */\nexport const DEFAULT_FIELD_ENDPOINT = 'https://api.cultured.computer';\n\n// ── Vocabulary ───────────────────────────────────────────────────────────\n\n/**\n * Every refusal code the routes this client calls can answer: the\n * conversation and turn routes, the rate limit, the profile put and the\n * profile read. A refusal with no code (a 401, a 403 for a key that lacks a\n * permission, a 413) carries `code: null`.\n */\nexport const FIELD_REFUSAL_CODES = [\n // The conversation and turn routes, and the rate limit.\n 'invalid_body',\n 'forbidden',\n 'not_enabled',\n 'no_such_profile',\n 'no_such_endpoint',\n 'no_such_conversation',\n 'conversation_unknown',\n 'archived',\n 'revoked',\n 'link_inactive',\n 'conversation_conflict',\n 'opening_forbidden',\n 'opening_conflict',\n 'runtime_forbidden',\n 'invalid_reasoning_effort',\n 'invalid_max_output_tokens',\n 'invalid_reply_check',\n 'conversation_ended',\n 'no_live_version',\n 'no_owner',\n 'model_unavailable',\n 'daily_cap',\n 'link_session_cap',\n 'rate_limited',\n 'turn_cap',\n 'stale_turn_index',\n 'record_gap',\n 'busy',\n 'interrupted',\n 'not_connected',\n 'budget',\n 'provider_error',\n 'provider_timeout',\n 'turn_failed',\n 'request_unknown',\n 'request_conflict',\n 'request_pending',\n 'request_interrupted',\n 'replay_expired',\n // The profile put.\n 'put_in_progress',\n 'scene_live',\n 'precondition_failed',\n 'invalid_consent',\n 'invalid_safeguards',\n 'invalid_scrub',\n 'invalid_fallback',\n 'invalid_scene',\n // The profile read.\n 'not_a_soul_md',\n 'not_a_scene',\n] as const;\nexport type FieldRefusalCode = (typeof FIELD_REFUSAL_CODES)[number];\n\n/**\n * The reasoning efforts a profile or a conversation can ask for. `none`\n * asks for no reasoning. An effort is sent only where the model's\n * catalogue entry lists it; elsewhere it is left out.\n */\nexport const FIELD_REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;\nexport type FieldReasoningEffort = (typeof FIELD_REASONING_EFFORTS)[number];\n\n/**\n * Why a model finished a turn with no reply text, on a `provider_error`:\n * `empty_completion`, or `empty_completion_length` when the output limit\n * ended it before any reply text (a reasoning model that spent\n * `maxOutputTokens` reasoning).\n */\nexport type FieldEmptyCompletionReason = 'empty_completion' | 'empty_completion_length';\n\n/**\n * Where a resolved runtime setting came from: the conversation's own\n * `runtime` (the request), the profile's, or the house default for the\n * model.\n */\nexport type FieldRuntimeSource = 'request' | 'profile' | 'default';\n\n/** The sources the profile read names: no request is in play there. */\nexport type FieldProfileRuntimeSource = Extract<FieldRuntimeSource, 'profile' | 'default'>;\n\n/** Why an ended conversation ended, on a `conversation_ended` refusal. */\nexport type FieldEndedReason = 'idle' | 'turn_cap' | 'floor' | 'failed' | 'ended';\n\n/**\n * The served runtime record: what the reply call is sent. Every key is\n * optional; a key left out keeps the profile's value (or, on a profile,\n * the default).\n */\nexport type FieldRuntime = {\n /** An OpenRouter model id the model catalogue routes, `vendor/model`. */\n model?: string;\n /** 0 to 2. Default 0.7. Sent unless the model's route takes none. */\n temperature?: number;\n /**\n * The reply's output budget in tokens: an integer from 256 to the\n * model's catalogue max_completion_tokens (16384 when it states none),\n * else `invalid_max_output_tokens`. A reasoning model's reasoning tokens\n * count inside it, with the answer. Default: the\n * smaller of 16384 and the model's catalogue max_completion_tokens;\n * 4096 when the catalogue says nothing of the model.\n */\n maxOutputTokens?: number;\n /**\n * Default: `low` where the model's catalogue lists it, else the lowest\n * effort it lists; nothing when it lists none.\n */\n reasoningEffort?: FieldReasoningEffort;\n};\n\n// ── The error ────────────────────────────────────────────────────────────\n\n/** A fixed platform text you must show the person, before the reply. */\nexport type FieldNotice = { kind: string; text: string };\n\n/** One frame of a turn, as the JSON answer collects it. */\nexport type FieldEventRecord = { event: string; data: unknown };\n\n/**\n * A request the Field API refused: any answer that is not a 2xx. Branch on\n * `code`, not on the message.\n */\nexport class FieldRefusal extends Error {\n override readonly name = 'FieldRefusal';\n /** The HTTP status. */\n readonly status: number;\n /**\n * The refusal's stable code, one of `FIELD_REFUSAL_CODES` from this\n * version; a newer API may answer a code this version does not list.\n * `null` when the answer carries none (401, a 403 for a missing\n * permission, 413, a 503 while the service drains).\n */\n readonly code: FieldRefusalCode | (string & {}) | null;\n /**\n * Why, when the answer says: the ended reason of a `conversation_ended`,\n * or the empty-completion reason of a `provider_error`. Otherwise null.\n */\n readonly reason: FieldEndedReason | FieldEmptyCompletionReason | (string & {}) | null;\n /** `Retry-After` in seconds, when the answer carries one (429, 503, a busy put). */\n readonly retryAfter: number | null;\n /** A failed turn still answers its notices; show them. Empty otherwise. */\n readonly notices: FieldNotice[];\n /** A failed turn's frames, collected before it failed. Empty otherwise. */\n readonly events: FieldEventRecord[];\n /** A failed turn's index, when the answer names one. */\n readonly turnIndex: number | null;\n /** The answer's body as sent: parsed JSON, or the text when it is not JSON. */\n readonly body: unknown;\n\n constructor(init: {\n status: number;\n message: string;\n code: string | null;\n reason: string | null;\n retryAfter: number | null;\n notices: FieldNotice[];\n events: FieldEventRecord[];\n turnIndex: number | null;\n body: unknown;\n }) {\n super(init.message);\n this.status = init.status;\n this.code = init.code;\n this.reason = init.reason;\n this.retryAfter = init.retryAfter;\n this.notices = init.notices;\n this.events = init.events;\n this.turnIndex = init.turnIndex;\n this.body = init.body;\n }\n}\n\n// ── Answer shapes ────────────────────────────────────────────────────────\n\nexport type FieldVersionRef = { id: string; contentHash: string; configHash: string; label: string };\nexport type FieldLimits = { idleMinutes: number; turnsPerConversation: number; conversationsPerDay: number };\nexport type FieldSafeguards = { crisis: boolean; disclosure: boolean; policy: string };\nexport type FieldConnection =\n | { openrouter: 'connected'; via: 'project' | 'operator' }\n | { openrouter: 'missing'; connect: string };\nexport type FieldProfileLinks = {\n profile: string;\n conversations: string;\n turns: string;\n sessions: string;\n versions: string;\n reviews: string;\n};\nexport type FieldProfileEndpoint = {\n id: string;\n name: string;\n versionMode: 'live' | 'pinned';\n guestsAllowed: boolean;\n idleMinutes: number;\n turnsPerConversation: number;\n conversationsPerDay: number;\n};\n\n/** The answer to `profiles.put`. */\nexport type FieldProfilePut = {\n profile: string;\n floor: 'steer' | 'exit';\n outcome: 'created' | 'new version, pointer moved' | 'settings changed' | 'no change';\n /** What moved: `file`, `model`, `temperature`, `reasoningEffort`, a limit, ... */\n changed: string[];\n format: 'soul-md' | 'scene';\n dryRun?: true;\n replaced?: { id: string; label: string };\n version: FieldVersionRef;\n endpoint: FieldProfileEndpoint;\n limits: FieldLimits;\n core: Array<{ heading: string; chars: number }>;\n detectors: { active: string[]; classifier: string } | { active: string[]; note: string };\n /** Parts of the file left out, each with why. Check it after every put. */\n refused: Array<{ heading: string; reason: string }>;\n runtime: {\n model: string;\n provider: 'openrouter';\n temperature: number;\n reasoningEffort?: FieldReasoningEffort;\n /** The output budget the saved version asks for; absent when it names none. */\n maxOutputTokens?: number;\n consent: boolean;\n fallback: string | null;\n fallbackNote?: string;\n };\n safeguards: FieldSafeguards;\n scrub: string;\n connection: FieldConnection;\n links: FieldProfileLinks;\n /** The `ETag` header: the live version's id, quoted. Send it as `ifMatch`. */\n etag: string | null;\n};\n\n/** The answer to `profiles.get`. */\nexport type FieldProfile = {\n profile: string;\n floor: 'steer' | 'exit';\n archived: boolean;\n archivedAt: string | null;\n version: { id: string; configHash: string; label: string } | null;\n endpoint: (FieldProfileEndpoint & { revokedAt: string | null }) | null;\n limits: FieldLimits | null;\n links: FieldProfileLinks;\n runtime: {\n model: string;\n provider: string;\n temperature: number;\n /**\n * The output budget the replies are sent with: the live version's own,\n * else the house default.\n */\n maxOutputTokens?: number;\n maxOutputTokensSource?: FieldProfileRuntimeSource;\n /**\n * The effort the replies ask for: the live version's own, else the\n * house default; null when nothing is asked (the catalogue lists no\n * efforts).\n */\n reasoningEffort?: FieldReasoningEffort | null;\n reasoningEffortSource?: FieldProfileRuntimeSource;\n readerModel: string | null;\n fallback: string | null;\n } | null;\n consent: boolean;\n safeguards: FieldSafeguards;\n scrub: string;\n connection: FieldConnection;\n /** The `ETag` header: the live version's id, quoted. Send it as `ifMatch`. */\n etag: string | null;\n};\n\n/** One session as the sessions list answers it. */\nexport type FieldSessionSummary = {\n id: string;\n /** Your own conversation id, as the start sent it. */\n conversation: string | null;\n runId: string;\n user: string | null;\n startedAt: string | null;\n endedAt: string | null;\n ended: boolean;\n endedReason: string | null;\n status: string;\n error?: string;\n turns: number;\n rehearsal: boolean;\n origin: 'observed' | 'constructed';\n opening: { turns: number } | null;\n version: FieldVersionRef;\n flags: number;\n shapes: Record<string, number>;\n path: string;\n};\n\n/** The answer to `profiles.sessions`: one page, newest first. */\nexport type FieldSessionsPage = {\n profile: string;\n archived: boolean;\n limit: number;\n sessions: FieldSessionSummary[];\n /** Pass as `cursor` for the next page; null on the last page. */\n nextBefore: string | null;\n links: { profile: string; sessions: string; versions: string };\n};\n\n/** One turn of a session's record. */\nexport type FieldSessionTurn = {\n index: number;\n at?: string;\n pending?: true;\n text: 'stored' | 'pending';\n message: string | null;\n reply: string | null;\n outcome: 'floor' | 'error' | 'reply';\n error?: string;\n version: FieldVersionRef | null;\n model: { id: string; provider: string } | null;\n fallbackFrom?: string;\n sent?: { temperature: number | null; seed: number | null; reasoning?: { effort: string }; maxOutputTokens?: number };\n detectors: Array<{\n statement: string;\n flagged: boolean;\n verdict: string;\n score: string | null;\n bar: number | null;\n phase: 'before' | 'after';\n steers: boolean;\n consequence?: string;\n entered?: { heading: string; replyTurn: number };\n }>;\n entered: Array<{ heading: string; detector: string; flaggedOnTurn: number | null }>;\n shapes: Array<{ shape: string; evidence: Record<string, unknown>; version: string | null }>;\n moves: unknown[];\n floor?: unknown;\n notices?: FieldNotice[];\n storedHistoryTurns?: number;\n usage: {\n model: string | null;\n tokensIn: number | null;\n tokensOut: number | null;\n latencyMs: number | null;\n costUsd: number | null;\n } | null;\n};\n\n/** The answer to `sessions.get`: the header and its turns in order. */\nexport type FieldSessionRecord = {\n profile: string;\n session: Omit<FieldSessionSummary, 'path'> & {\n usage: { model: string | null; tokensIn: number | null; tokensOut: number | null; costUsd: number | null };\n };\n text: 'stored';\n opening: {\n constructed: true;\n text: 'as-sent';\n turns: Array<{ role: 'person' | 'assistant'; text: string }>;\n } | null;\n turns: FieldSessionTurn[];\n readsTruncated?: true;\n links: { profile: string; sessions: string; versions: string };\n};\n\n/** The answer to `conversations.start`. */\nexport type FieldConversation = {\n runId: string;\n sessionId: string;\n version: number | null;\n /** The path of the session's record (`GET` it with the same key). */\n record: string;\n};\n\n/** The answer to `turns.send`. */\nexport type FieldTurnAnswer = {\n reply: string;\n /** Show these to the person, before the reply. Empty when none. */\n notices: FieldNotice[];\n /** Every other frame of the turn, in order. */\n events: FieldEventRecord[];\n turnIndex: number;\n};\n\n// ── Stream frames ────────────────────────────────────────────────────────\n\nexport type FieldRunFrame = {\n runId: string;\n sessionId: string;\n model: string;\n provider: string;\n modelKey?: string;\n /** What the reply call sent; null when the route takes none. */\n temperature: number | null;\n seed: number | null;\n /** Present only when an effort was sent. */\n reasoning?: { effort: string };\n /** The output budget the call sent (reasoning and answer together). */\n maxOutputTokens?: number;\n opening?: { turns: number };\n /** The conversation's runtime override, as its start sent it. */\n override?: FieldRuntime;\n};\nexport type FieldReadFrame = { statement: string; score?: number; bar?: number; moment?: string; phase: string };\nexport type FieldDoneFrame = { status: string; turnIndex: number };\nexport type FieldErrorFrame = {\n message: string;\n code: FieldRefusalCode | (string & {});\n /** On a `provider_error` with no reply text: why. */\n reason?: FieldEmptyCompletionReason | (string & {});\n turnIndex?: number;\n};\n\n/**\n * One server-sent frame of a streamed turn, in order: `run`, then any\n * `notice` and `reads` before the first `delta`, the `delta`s, `events`,\n * and `done` or `error`. A frame this version does not know arrives as\n * `other`, with its name.\n */\nexport type FieldTurnFrame =\n | { event: 'run'; data: FieldRunFrame }\n | { event: 'notice'; data: FieldNotice }\n | { event: 'reads'; data: FieldReadFrame[] }\n | { event: 'delta'; data: { text: string } }\n | { event: 'events'; data: unknown[] }\n | { event: 'done'; data: FieldDoneFrame }\n | { event: 'error'; data: FieldErrorFrame }\n | { event: 'other'; name: string; data: unknown };\n\n// ── Inputs ───────────────────────────────────────────────────────────────\n\nexport type FieldClientOptions = {\n /** An App key (`studio:serve` and `profiles:write`). Keep it on a server. */\n apiKey: string;\n /** The API host. Default `https://api.cultured.computer`. */\n endpoint?: string;\n};\n\n/** Options of `profiles.put`. Each overrides the file's frontmatter for this put. */\nexport type FieldPutOptions = FieldRuntime & {\n /** A model id that answers when the model fails before its reply started, or `none`. */\n fallback?: string;\n consent?: boolean;\n /** `crisis`, `disclosure`, both, or `none`. */\n safeguards?: Array<'crisis' | 'disclosure'> | 'none';\n scrub?: 'identifiers-only' | 'standard';\n idleMinutes?: number;\n turnsPerConversation?: number;\n conversationsPerDay?: number;\n /** Answer what the put would do and store nothing. */\n dryRun?: boolean;\n /** Replace a live stepped scene with the file. */\n force?: boolean;\n /** A conditional put: the `etag` a read or the last put answered. */\n ifMatch?: string;\n signal?: AbortSignal;\n};\n\nexport type FieldStartOptions = {\n /** Your own id for the conversation, at most 200 characters. One per thread. */\n conversation: string;\n /**\n * Your own opaque, stable id for the person, at most 200 characters: a\n * hash or your internal id, never an email or a name. A conversation\n * belongs to the person it was started for.\n */\n user: string;\n /**\n * This conversation's runtime, over the profile's. Only a key holding\n * `profiles:write` may send one (`runtime_forbidden` otherwise). A\n * repeated start must send the same (`opening_conflict` otherwise).\n */\n runtime?: FieldRuntime;\n /** A constructed opening: earlier exchanges, the person first and the assistant last. */\n opening?: Array<{ role: 'person' | 'assistant'; text: string }>;\n /** A signed 32-bit integer; each turn sends the seed plus its index where the route takes one. */\n seed?: number;\n signal?: AbortSignal;\n};\n\nexport type FieldTurnOptions = {\n conversation: string;\n message: string;\n /** The turn index you expect to be next; a stale one is refused with `stale_turn_index`. */\n resume?: { turnIndex: number };\n signal?: AbortSignal;\n};\n\nexport type FieldSessionsOptions = {\n /** Your own conversation id, exact match. */\n conversation?: string;\n /** The `nextBefore` of the previous page. */\n cursor?: string;\n /** Default 50, at most 200. */\n limit?: number;\n /** A content hash, a config hash or a version id. */\n version?: string;\n ended?: boolean;\n signal?: AbortSignal;\n};\n\nexport type FieldClient = {\n profiles: {\n /** Put a SOUL.md at a name: creates the profile, or saves a new version or new settings. */\n put(name: string, soulMarkdown: string, options?: FieldPutOptions): Promise<FieldProfilePut>;\n /** Read a profile: its live version, runtime, limits, safeguards and connection. */\n get(name: string, options?: { signal?: AbortSignal }): Promise<FieldProfile>;\n /** List a profile's served sessions, newest first, one page at a time. */\n sessions(name: string, options?: FieldSessionsOptions): Promise<FieldSessionsPage>;\n };\n conversations: {\n /** Start a conversation, or answer the running one under the same id. */\n start(profile: string, options: FieldStartOptions): Promise<FieldConversation>;\n };\n turns: {\n /** Serve one turn and answer it as one JSON body. Throws `FieldRefusal` when the turn fails. */\n send(profile: string, options: FieldTurnOptions): Promise<FieldTurnAnswer>;\n /**\n * Serve one turn as a stream of frames. A refusal before the stream\n * starts throws `FieldRefusal` from the loop; a failure once it has\n * started arrives as an `error` frame and ends the stream.\n */\n stream(profile: string, options: FieldTurnOptions): AsyncGenerator<FieldTurnFrame, void, undefined>;\n };\n sessions: {\n /** Read one session's record, turn by turn. */\n get(id: string, options?: { signal?: AbortSignal }): Promise<FieldSessionRecord>;\n };\n};\n\n// ── The client ───────────────────────────────────────────────────────────\n\ntype Query = Record<string, string | number | boolean | undefined>;\n\nfunction queryString(query: Query): string {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) params.append(key, String(value));\n }\n const text = params.toString();\n return text ? `?${text}` : '';\n}\n\nconst segment = (value: string): string => encodeURIComponent(value);\n\nfunction parseRetryAfter(value: string | null): number | null {\n if (value === null) return null;\n const seconds = Number(value);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Every non-2xx answer becomes a FieldRefusal, the body read once. */\nasync function refusalOf(response: Response): Promise<FieldRefusal> {\n const text = await response.text().catch(() => '');\n let body: unknown = text;\n try {\n body = text ? JSON.parse(text) : null;\n } catch {\n // Not JSON (a proxy's page): keep the text.\n }\n const record = isRecord(body) ? body : {};\n const events = Array.isArray(record['events']) ? (record['events'] as FieldEventRecord[]) : [];\n // A failed turn in JSON mode names its reason on the error frame it\n // collected; a conversation_ended names it at the top.\n const errorFrame = events.find((frame) => isRecord(frame) && frame.event === 'error');\n const frameReason = errorFrame && isRecord(errorFrame.data) ? errorFrame.data['reason'] : undefined;\n const reason = typeof record['reason'] === 'string' ? record['reason'] : typeof frameReason === 'string' ? frameReason : null;\n const sentence = typeof record['error'] === 'string' ? record['error'] : null;\n return new FieldRefusal({\n status: response.status,\n message: sentence ?? `the Field API answered ${response.status}`,\n code: typeof record['code'] === 'string' ? record['code'] : null,\n reason,\n retryAfter: parseRetryAfter(response.headers.get('retry-after')),\n notices: Array.isArray(record['notices']) ? (record['notices'] as FieldNotice[]) : [],\n events,\n turnIndex: typeof record['turnIndex'] === 'number' ? record['turnIndex'] : null,\n body,\n });\n}\n\nconst KNOWN_FRAMES = new Set(['run', 'notice', 'reads', 'delta', 'events', 'done', 'error']);\n\nfunction frameOf(name: string, raw: string): FieldTurnFrame {\n let data: unknown = raw;\n try {\n data = JSON.parse(raw);\n } catch {\n // A frame whose data is not JSON keeps its text.\n }\n if (KNOWN_FRAMES.has(name)) return { event: name, data } as FieldTurnFrame;\n return { event: 'other', name, data };\n}\n\n/**\n * The server-sent events grammar: frames separated by a blank line, `event:`\n * and `data:` fields (several `data:` lines join with a newline), comment\n * lines starting with `:` ignored. A frame with no `event:` is a `message`.\n * An unterminated frame at the end of the stream is dropped, as the grammar\n * says.\n */\nasync function* readFrames(body: ReadableStream<Uint8Array>): AsyncGenerator<FieldTurnFrame, void, undefined> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let name = '';\n let data: string[] = [];\n try {\n while (true) {\n const { done, value } = await reader.read();\n buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n let newline: number;\n while ((newline = buffer.search(/\\r\\n|\\r|\\n/)) !== -1) {\n // A lone \\r at the end of the buffer may be the first half of \\r\\n.\n if (buffer[newline] === '\\r' && newline === buffer.length - 1 && !done) break;\n const width = buffer.startsWith('\\r\\n', newline) ? 2 : 1;\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + width);\n if (line === '') {\n if (data.length > 0) yield frameOf(name || 'message', data.join('\\n'));\n name = '';\n data = [];\n continue;\n }\n if (line.startsWith(':')) continue;\n const colon = line.indexOf(':');\n const field = colon === -1 ? line : line.slice(0, colon);\n let content = colon === -1 ? '' : line.slice(colon + 1);\n if (content.startsWith(' ')) content = content.slice(1);\n if (field === 'event') name = content;\n else if (field === 'data') data.push(content);\n }\n if (done) return;\n }\n } finally {\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n\n/** The runtime record as the start's body carries it: only the keys set. */\nfunction runtimeBody(runtime: FieldRuntime): FieldRuntime {\n const out: FieldRuntime = {};\n if (runtime.model !== undefined) out.model = runtime.model;\n if (runtime.temperature !== undefined) out.temperature = runtime.temperature;\n if (runtime.maxOutputTokens !== undefined) out.maxOutputTokens = runtime.maxOutputTokens;\n if (runtime.reasoningEffort !== undefined) out.reasoningEffort = runtime.reasoningEffort;\n return out;\n}\n\n/**\n * Create a serving client. It holds the key and the host, nothing else: no\n * state between calls, no retries, no timeout of its own (pass `signal`).\n */\nexport function createFieldClient(options: FieldClientOptions): FieldClient {\n if (!options || typeof options.apiKey !== 'string' || options.apiKey.trim() === '') {\n throw new TypeError('createFieldClient: apiKey is required (an App key; keep it on a server)');\n }\n const apiKey = options.apiKey;\n const endpoint = (options.endpoint ?? DEFAULT_FIELD_ENDPOINT).replace(/\\/+$/, '');\n\n async function request(\n method: 'GET' | 'POST' | 'PUT',\n path: string,\n init: { body?: string; contentType?: string; accept: string; headers?: Record<string, string>; signal?: AbortSignal | undefined },\n ): Promise<Response> {\n const headers: Record<string, string> = { authorization: `Bearer ${apiKey}`, accept: init.accept, ...init.headers };\n if (init.contentType) headers['content-type'] = init.contentType;\n const response = await fetch(`${endpoint}${path}`, {\n method,\n headers,\n ...(init.body !== undefined ? { body: init.body } : {}),\n ...(init.signal ? { signal: init.signal } : {}),\n });\n if (!response.ok) throw await refusalOf(response);\n return response;\n }\n\n async function json<T>(response: Response): Promise<T> {\n return (await response.json()) as T;\n }\n\n function turnBody(input: FieldTurnOptions): string {\n return JSON.stringify({\n conversation: input.conversation,\n message: input.message,\n ...(input.resume ? { resume: { turnIndex: input.resume.turnIndex } } : {}),\n });\n }\n\n return {\n profiles: {\n async put(name, soulMarkdown, put = {}) {\n const query: Query = {\n model: put.model,\n temperature: put.temperature,\n maxOutputTokens: put.maxOutputTokens,\n reasoningEffort: put.reasoningEffort,\n fallback: put.fallback,\n consent: put.consent,\n safeguards: put.safeguards === undefined ? undefined : put.safeguards === 'none' ? 'none' : put.safeguards.join(','),\n scrub: put.scrub,\n idleMinutes: put.idleMinutes,\n turnsPerConversation: put.turnsPerConversation,\n conversationsPerDay: put.conversationsPerDay,\n dryRun: put.dryRun,\n force: put.force,\n };\n const response = await request('PUT', `/v1/profiles/${segment(name)}${queryString(query)}`, {\n body: soulMarkdown,\n contentType: 'text/markdown',\n accept: 'application/json',\n ...(put.ifMatch !== undefined ? { headers: { 'if-match': put.ifMatch } } : {}),\n signal: put.signal,\n });\n return { ...(await json<Omit<FieldProfilePut, 'etag'>>(response)), etag: response.headers.get('etag') };\n },\n async get(name, get = {}) {\n const response = await request('GET', `/v1/profiles/${segment(name)}`, { accept: 'application/json', signal: get.signal });\n return { ...(await json<Omit<FieldProfile, 'etag'>>(response)), etag: response.headers.get('etag') };\n },\n async sessions(name, list = {}) {\n const query: Query = {\n conversation: list.conversation,\n before: list.cursor,\n limit: list.limit,\n version: list.version,\n ended: list.ended,\n };\n const response = await request('GET', `/v1/profiles/${segment(name)}/sessions${queryString(query)}`, {\n accept: 'application/json',\n signal: list.signal,\n });\n return json<FieldSessionsPage>(response);\n },\n },\n conversations: {\n async start(profile, start) {\n const body = JSON.stringify({\n conversation: start.conversation,\n user: start.user,\n ...(start.runtime !== undefined ? { runtime: runtimeBody(start.runtime) } : {}),\n ...(start.opening !== undefined ? { opening: start.opening } : {}),\n ...(start.seed !== undefined ? { seed: start.seed } : {}),\n });\n const response = await request('POST', `/v1/profiles/${segment(profile)}/conversations`, {\n body,\n contentType: 'application/json',\n accept: 'application/json',\n signal: start.signal,\n });\n return json<FieldConversation>(response);\n },\n },\n turns: {\n async send(profile, turn) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/turns`, {\n body: turnBody(turn),\n contentType: 'application/json',\n accept: 'application/json',\n signal: turn.signal,\n });\n return json<FieldTurnAnswer>(response);\n },\n async *stream(profile, turn) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/turns`, {\n body: turnBody(turn),\n contentType: 'application/json',\n accept: 'text/event-stream',\n signal: turn.signal,\n });\n if (!response.body) return;\n yield* readFrames(response.body);\n },\n },\n sessions: {\n async get(id, get = {}) {\n const response = await request('GET', `/v1/sessions/${segment(id)}`, { accept: 'application/json', signal: get.signal });\n return json<FieldSessionRecord>(response);\n },\n },\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","../src/field.ts"],"names":["response","z","context","propagation","createContextKey","state","asString","asNumber","messageText","value","bound","warnedUnbound","buildPayload","emit","performance","createRequire","trace","registered","instrumentation","SessionEndSchema","now","isRecord"],"mappings":";;;;;;;;;;AA4BO,IAAM,qBAAA,GAAwB,2CAAA;AAQrC,IAAM,mBAAA,GAAsB,EAAA;AAO5B,IAAM,eAAA,GAAkB,IAAA;AAOxB,IAAM,YAAA,GAAe,EAAA;AAOrB,IAAM,mBAAA,GAAsB,GAAA;AAE5B,IAAM,kBAAA,GAAqB,KAAA;AAG3B,eAAe,oBAAoB,QAAA,EAAqD;AACtF,EAAA,IAAI,CAAC,QAAA,CAAS,IAAA,EAAM,OAAO,EAAC;AAC5B,EAAA,MAAM,MAAA,GAAS,QAAA,CAAS,IAAA,CAAK,SAAA,EAAU;AACvC,EAAA,MAAM,SAAuB,EAAC;AAC9B,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,EAAE,IAAA,EAAM,KAAA,EAAM,GAAI,MAAM,OAAO,IAAA,EAAK;AAC1C,MAAA,IAAI,IAAA,EAAM;AACV,MAAA,IAAA,IAAQ,KAAA,CAAM,UAAA;AACd,MAAA,IAAI,IAAA,GAAO,kBAAA,EAAoB,MAAM,IAAI,MAAM,qCAAqC,CAAA;AACpF,MAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AAAA,IACnB;AACA,IAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,IAAI,CAAA;AACjC,IAAA,IAAI,MAAA,GAAS,CAAA;AACb,IAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAAE,MAAA,KAAA,CAAM,GAAA,CA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K;AAAA,SACd,CAAA;AACD,QAAA,IAAI,CAAC,SAAS,IAAA,EAAM;AACpB,QAAA,OAAO,UAAA,CAAW,SAAS,IAAI,CAAA;AAAA,MACjC;AAAA,KACF;AAAA,IACA,QAAA,EAAU;AAAA,MACR,MAAM,GAAA,CAAI,EAAA,EAAI,GAAA,GAAM,EAAC,EAAG;AACtB,QAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,KAAA,EAAO,gBAAgB,OAAA,CAAQ,EAAE,CAAC,CAAA,CAAA,EAAI,EAAE,MAAA,EAAQ,kBAAA,EAAoB,MAAA,EAAQ,GAAA,CAAI,QAAQ,CAAA;AACvH,QAAA,OAAO,KAAyB,QAAQ,CAAA;AAAA,MAC1C;AAAA;AACF,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * HTTP client for the Sight API. Internal; use the `Sight` methods.\n *\n * Sends captured turns to POST /v1/turns with a Bearer token. A failed send\n * is logged with `debug: true` and never thrown. The first send the API\n * rejects (a 4xx other than 429) prints one warning without `debug`, once\n * per process for each of: 401, 403, any other status. A rate-limited send\n * (429) is retried once after Retry-After; if the retry is limited too,\n * that capture is dropped.\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 link printed after the first accepted turn. */\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\nconst MAX_ACK_BODY_BYTES = 65_536;\n\n/** Only debug turns read acknowledgements; all other bodies are discarded. */\nasync function readAcknowledgement(response: Response): Promise<{ pendingId?: string }> {\n if (!response.body) return {};\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > MAX_ACK_BODY_BYTES) throw new Error('acknowledgement exceeds 65536 bytes');\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }\n const body: unknown = JSON.parse(new TextDecoder().decode(bytes));\n return body !== null && typeof body === 'object' && 'pendingId' in body && typeof body.pendingId === 'string'\n ? { pendingId: body.pendingId }\n : {};\n } finally {\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n\nexport class IngestClient {\n private apiKey: string;\n private endpoint: string;\n private debug: boolean;\n private dashboardUrl: string;\n /**\n * The first accepted turn prints one stderr line with a link to the\n * session on the dashboard, once per client (one client per init). A\n * failed send does not use it up. Only turns print it; flags, outcome\n * events and session ends do not.\n */\n private firstCaptureAnnounced = false;\n /**\n * Rate limiting (429): the first 429 prints one stderr warning, with or\n * without `debug`; later ones log only with `debug: true`. Each\n * rate-limited request is retried once after Retry-After. At most 50\n * retries wait at a time; past that, a rate-limited request is dropped.\n */\n private rateLimitAnnounced = false;\n private pendingRetries = 0;\n /**\n * Rejected sends (a 4xx other than 429): the first one of each class\n * (401, 403, any other status) prints one stderr warning, with or\n * without `debug`. A rejected send is never retried: the same key and\n * the same body get the same answer.\n */\n private rejectionAnnounced = new Set<'401' | '403' | 'other'>();\n private inFlight = 0;\n private shedAnnounced = false;\n\n /**\n * Every send goes through here: a 15 second timeout per send and at most\n * 64 sends in flight. Past that, a new send is dropped, not queued; the\n * first drop prints one stderr warning, later ones log only with\n * `debug: true`.\n */\n private async guardedFetch(\n url: string,\n init: RequestInit,\n consume?: (response: Response) => Promise<void>,\n ): 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 are already in flight, so new captures are dropped until some finish. The Sight API is slow or unreachable: check the endpoint and your network. This warning prints once per process.`,\n );\n }\n throw new Error(`${MAX_INFLIGHT} sends already in flight; this send was dropped`);\n }\n this.inFlight++;\n let response: Response | undefined;\n try {\n response = await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });\n await consume?.(response);\n return response;\n } finally {\n // fetch resolves at headers. Keep the slot until any debug body read\n // finishes or an unused body is cancelled, including failed/retry sends.\n if (response?.body && !response.body.locked) await response.body.cancel().catch(() => {});\n this.inFlight--;\n }\n }\n\n /**\n * Wait for sends in flight and pending retries, for at most `timeoutMs`\n * (default 15 seconds). Called by Sight.shutdown() so a short-lived\n * process can exit without losing a send. A retry still waiting when\n * the time is up is not guaranteed to be sent.\n */\n async drainInFlight(timeoutMs = SEND_TIMEOUT_MS): Promise<void> {\n const deadline = performance.now() + timeoutMs;\n while ((this.inFlight > 0 || this.pendingRetries > 0) && performance.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. Errors are logged with `debug: true`, never thrown.\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: its body is ${bodyBytes} bytes, over the ${MAX_TURN_BODY_BYTES}-byte limit ` +\n `(session=${turn.sessionExternalId} turn=${turn.turnIndex}). Send a smaller payload.`,\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 }, async (response) => {\n if (!response.ok) return;\n // Acceptance is known at headers, even if the optional debug\n // acknowledgement later fails. Never resend such a capture.\n if (!this.firstCaptureAnnounced) {\n this.firstCaptureAnnounced = true;\n console.error(\n `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`,\n );\n }\n if (this.debug) {\n const ack = await readAcknowledgement(response);\n this.log(`[sight] ingest ok id=${ack.pendingId ?? '?'}`);\n }\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n\n if (!response.ok) {\n this.announceRejection(response.status, 'a turn');\n this.log(`[sight] ingest failed status=${response.status}`);\n return;\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. Errors are logged with `debug: true`, never\n * thrown.\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.announceRejection(response.status, 'a flag');\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: why the session ended. Errors are logged with\n * `debug: true`, never thrown.\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.announceRejection(response.status, 'a session end');\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. Errors are logged with `debug: true`, never\n * thrown.\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.announceRejection(response.status, 'an outcome event');\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 a batch of environment events. Errors are logged with\n * `debug: true`, never thrown.\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.announceRejection(response.status, 'an environment events batch');\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 batch of spans. Errors are logged with `debug: true`, never\n * thrown.\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.announceRejection(response.status, 'a spans batch');\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 * The 429 retry rule. Any other response passes through. A 429 is sent\n * again once after Retry-After seconds (1 second when the header is\n * missing or unreadable; kept between 1 and 60 seconds). The retry's\n * response is returned as is, so a second 429 is not retried. Returns\n * null when the retry was dropped because 50 retries were already\n * waiting. A waiting retry does not keep the process alive.\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 // Not gated on debug: rate limiting that persists loses captures, so\n // the host is told once per process. Stderr only, same channel as\n // log().\n\n console.error(\n '[sight] rate limited (429). Each rate-limited send is retried once after Retry-After; if the retry is limited too, that capture is dropped. Send fewer requests per minute or ask for a higher limit: https://sight.cultured.computer/docs/sdk-reference#rate-limits (this warning prints once per process)',\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 /**\n * The once-per-class warning for a send the API rejected. Not gated on\n * debug: a rejected key drops every capture, so the host is told once.\n * 429 has its own warning (see retryIfRateLimited); a 5xx is the API's\n * failure, not the host's, and stays a debug line.\n */\n private announceRejection(status: number, what: string): void {\n if (status < 400 || status >= 500 || status === 429) return;\n const cls = status === 401 ? '401' : status === 403 ? '403' : 'other';\n if (this.rejectionAnnounced.has(cls)) return;\n this.rejectionAnnounced.add(cls);\n const line =\n cls === '401'\n ? '[sight] the API rejected the key (401). Nothing is being captured. Set apiKey to a key with the ingest capability.'\n : cls === '403'\n ? '[sight] this key cannot capture (403): it lacks the ingest permission. Nothing is being captured. Ask the project owner for a Capture key.'\n : `[sight] the API rejected ${what} (${status}) and it was dropped. Set debug: true to log every failed send. This warning prints once per process.`;\n\n console.error(line);\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 * A signature phrase you define for a persona: a plain phrase or a regex.\n * The SDK matches the phrases against each reply and sends the matched\n * slugs with the turn.\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 /** The persona's slug. */\n slug: z.string().min(1),\n /**\n * The persona's description (role, identity, communication, engagement):\n * an object, or a string reference to one. Optional. This SDK does not\n * read or send it.\n */\n rice: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),\n /**\n * Signature phrases for this persona. Compiled once and matched against\n * each reply in the SDK; matched slugs are sent with the turn as\n * `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 * Resolves the outcome of a finished session. Called by\n * Sight.endSession() with the session's externalId; a non-null result is\n * sent as an outcome event on the session. Not called for a session you\n * never end; use emitOutcomeEvent() for an outcome known later.\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: a key with the `ingest` capability. Required. */\n apiKey: z.string().min(1),\n /** Deployment slug: the configuration this traffic belongs to. Required. */\n deployment: z.string().min(1),\n /** The API host the captures are sent to. Defaults to\n `https://api.cultured.computer`. */\n endpoint: z.string().url().default(\"https://api.cultured.computer\"),\n /**\n * Dashboard base URL for the link printed on stderr after the first\n * accepted turn. Set it only for a self-hosted or staging dashboard.\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 * Share of turns sent, from 0 to 1. Default 1.0: every turn. Below 1.0\n * the choice is deterministic per (session id, turn index). Applies to\n * autocapture and to captureTurn.\n */\n sampleRate: z.number().min(0).max(1).default(1.0),\n /**\n * Debug mode: log every send and every failed send to stderr, prefixed\n * `[sight]`. Never logs the API key or conversation text.\n */\n debug: z.boolean().default(false),\n});\nexport type ProbeConfig = z.infer<typeof ProbeConfigSchema>;\n/**\n * The argument of Sight.init(). Fields with a default (endpoint,\n * dashboardUrl, sampleRate, debug) are optional here. `ProbeConfig` is the\n * same configuration after init has applied the defaults.\n */\nexport type ProbeConfigInput = z.input<typeof ProbeConfigSchema>;\n\n// ── Session context (customer identifies persona per session) ──────────────\n\nexport const SessionStartSchema = z.object({\n /** Your id for the session: one conversation. Any non-empty string. */\n externalId: z.string().min(1),\n /**\n * Your id for the person: a stable, pseudonymous string, distinct from\n * externalId. It ties one person's sessions together and is sent with\n * every captured turn. Optional; without it, sessions are still captured\n * and nothing links them to a returning person.\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 /** How the person arrived in this session. */\n openedVia: z\n .enum([\"link\", \"notification\", \"resume\", \"direct\", \"share\"])\n .optional(),\n /**\n * Client context: locale, timezone, runtime, and anything else you\n * choose to include. Stored as sent. See startSessionWithContext.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n /**\n * Your own metadata for the session. Sent with the first captured turn,\n * inside `clientContext` under the `metadata` key, and stored as sent.\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n /**\n * Version tags for the session, used to compare versions on the\n * dashboard. All optional.\n * agentId model or policy version\n * experimentId A/B arm or feature flag\n * environmentConfigHash hash of the prompt or configuration\n * (see Sight.hashEnvironmentConfig)\n * environmentConfigLabel readable name for that version\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 * The argument of Sight.endSession(): why the session ended. When you know\n * the outcome at close (a resolved ticket, an escalation), pass `outcome`\n * and optional `outcomeDetail`; the SDK sends it as an outcome event.\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 version of the turn format this SDK sends. Set by the SDK on every\n * captured turn; a value you supply is replaced.\n */\n envelopeVersion?: string;\n /**\n * Your id for the person. Filled from Sight.startSession({\n * externalUserId }) when omitted. Never defaults to sessionExternalId.\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 for this turn. When omitted: the session's persona from\n * startSession(), then the default from init.\n */\n personaSlug?: string;\n /**\n * Slugs of the persona's signature phrases found in the reply. Computed\n * by the SDK when omitted. Empty or absent when none matched or none are\n * registered.\n */\n signaturePhraseMatches?: string[];\n /**\n * Optional fields from your own decision layer, sent as given: how it\n * classified the situation and what it chose. Autocapture never sets it.\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 * Timing of the reply: time from the person's submit to the captured\n * turn, whether the stream completed, 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 * The person's feedback on the turn: rating (1 to 5), thumbs.\n *\n * `flaggedBreak` is deprecated: use Sight.flagPersonaBreak(), which\n * records an outcome event. The boolean is still accepted.\n */\n userOutcome?: {\n flaggedBreak?: boolean;\n explicitRating?: number;\n thumbs?: \"up\" | \"down\";\n };\n /**\n * The candidate replies and the probability of each, when your system\n * chooses among candidates. Supply it here or in payload.propensity;\n * captureTurn checks it and sends a valid one. An invalid one logs one\n * warning and is removed; the turn is still sent.\n */\n propensity?: PropensityInput;\n /**\n * The person's response to the previous reply: the time from that reply\n * to this turn's submit. Derived by the SDK when both times are known;\n * you may also supply it.\n */\n transition?: {\n timeMs?: number;\n lengthDelta?: number;\n };\n /**\n * Session context from Sight.startSession, sent on the first captured\n * turn of a session and omitted on later turns.\n */\n openedVia?: \"link\" | \"notification\" | \"resume\" | \"direct\" | \"share\";\n clientContext?: Record<string, unknown>;\n /**\n * Version tags from Sight.startSession, sent on every turn so each turn\n * is attributed to the version that produced it. Absent when not 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// An outcome you record on a session (a resolution, an escalation, a\n// conversion). `kind` is any non-empty string.\nexport const OutcomeEventEmitSchema = z.object({\n sessionExternalId: z.string().min(1),\n kind: z.string().min(1),\n /** The turn that caused the outcome. Omit to attach to the latest turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Your own detail for the outcome. Optional. */\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. You choose which fields\n * are sent with 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 /** Your own key/value pairs 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 three\n * autocapture paths (the `ai` telemetry integration in vercel-ai.ts,\n * wrapOpenAI, and the span processor) from capturing one call twice.\n *\n * Precedence: the `ai` integration, then wrapOpenAI, then the span\n * processor. The `ai` integration sees the call the way the application\n * made it (the model reply as `ai` parsed it, the per-call session id). A\n * wrapped client records the first-token time and the cost the provider\n * reported, which a span does not carry.\n *\n * Three 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 call through a client that is both wrapped and module-patched.\n * wrapOpenAI runs the underlying call under the same marker, so the\n * span the patch starts for that call is skipped.\n *\n * 3. 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 HANDLED_CALL_KEY = createContextKey('sight.handled_model_call');\n\n/**\n * Run `fn` in a context marked as \"inside a model call a Sight path\n * already captures\" (the `ai` integration or a wrapped client).\n */\nexport function runInsideHandledCall<T>(fn: () => T): T {\n return context.with(context.active().setValue(HANDLED_CALL_KEY, true), fn);\n}\n\n/** True when `ctx` (default: the active context) is inside such a call. */\nexport function isInsideHandledCall(ctx: Context = context.active()): boolean {\n return ctx.getValue(HANDLED_CALL_KEY) === true;\n}\n\n// ── Response id claims (case 3) ───────────────────────────────────────────\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 or a wrapped OpenAI client\n * captures is not captured a second time from a span (see ai-dedupe.ts): a\n * span started inside that call is skipped, and so is a span carrying the\n * response id the `ai` 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 { isInsideHandledCall, 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 a model call another Sight path captures: an `ai`\n * model call the `ai` integration handles (a provider that calls an\n * instrumented client), or a call through a wrapped OpenAI client that\n * is also module-patched. Never turns.\n */\n private readonly insideHandledCall = 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 (isInsideHandledCall(parentContext)) this.insideHandledCall.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 or a wrapped client\n // captures this call.\n if (this.insideHandledCall.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] a span could not be read and was skipped (${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] a span could not be read and was skipped (${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] a turn read from a span was not captured (${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) needs CommonJS and an openai version the\n * bundled instrumentation supports. wrapOpenAI() wraps the client instance\n * 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 * A wrapped client that is also module-patched (CommonJS, `openai` loaded\n * after init) sends one turn per call, the wrap's: the span the patch\n * emits for the call is skipped (see ai-dedupe.ts).\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 { isInsideHandledCall, runInsideHandledCall } 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: a call ran before Sight.init() and was not captured. Call Sight.init() once at startup.',\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: a turn was not captured (${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 (isInsideHandledCall()) 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 // The underlying call runs under the handled-call marker: when the\n // client is also module-patched, the patch starts a span for this same\n // call, and the span processor skips a span started under the marker.\n // This turn is the one sent: it has the first-token time and the cost\n // the provider reported.\n const result = runInsideHandledCall(() => (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 runInsideHandledCall,\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: a call ran before Sight.init() and was not captured. Call Sight.init() once at startup.',\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: a turn was not captured (${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: an event could not be read and was skipped (${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 runInsideHandledCall(() => 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] ai below 7 found: nothing 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] ai: the telemetry integration was already registered.');\n return;\n }\n (registerTelemetry as (...integrations: unknown[]) => void)(sightTelemetry());\n if (debug) {\n console.log(\n '[sight] 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] ai was not found, so nothing was registered. If ai is bundled where the SDK cannot resolve it, call registerTelemetry(sightTelemetry()) yourself.',\n );\n }\n return;\n }\n }\n try {\n register(mod, debug);\n } catch (err) {\n if (debug) {\n console.warn(\n `[sight] ai: the telemetry integration was not registered (${err instanceof Error ? err.message : err}). Call registerTelemetry(sightTelemetry()) yourself.`,\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: enrichTokens on.\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 error: ${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 module instrumentation is not enabled (${msg}). Wrap the client: wrapOpenAI(new OpenAI()).`);\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 `. It needs CommonJS and an openai version the bundled instrumentation supports. ` +\n `Calls through a client passed to wrapOpenAI() are captured; calls through an unwrapped OpenAI client are not. ` +\n `Fix: import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()).`\n );\n}\n\n/**\n * The copy of `openai` the application will use. The package ships its\n * CommonJS and ESM files as separate module instances, and the patch\n * attaches to the one loaded through `require`. So the CommonJS build of\n * this SDK inspects the `require`d copy, and the ESM build inspects\n * `import('openai')`. Checking the other copy reports a detached patch\n * that is attached.\n *\n * CommonJS is detected by `module.require`: Node defines `module` only in\n * a CommonJS file. It is read through `module`, not as a bare `require`,\n * because the bundler replaces a bare `require` in the ESM build with a\n * stand-in that is always a function and always throws.\n */\nasync function loadApplicationOpenAI(): Promise<any> {\n const cjsRequire: ((id: string) => unknown) | null =\n typeof module !== 'undefined' && typeof module.require === 'function'\n ? module.require.bind(module)\n : null;\n if (cjsRequire !== null) return cjsRequire('openai');\n return import('openai');\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 loadApplicationOpenAI();\n // Read at check time, after the load above has settled, so a client\n // 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 error: ${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 is not enabled (${msg}). Anthropic calls are not captured; record them with Sight.captureTurn().`,\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 error: ${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 is not enabled (${msg}). LangChain calls are not captured; record them with Sight.captureTurn().`,\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: model calls go through the LangChain instrumentation; no separate setup.',\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 (Python) calls are not captured by this SDK. Record them with Sight.captureTurn() or the HTTP API.',\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: a call through an OpenAI client pointed at Inception is sent with provider \"inception\". Wrap the client with wrapOpenAI().',\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: recorded a 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] an instrumentation failed to register (${result.reason}); calls through that library are not captured.`);\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\";\nimport { SOURCE_SESSION_KEY } from \"./session-origin\";\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) ─────\n/** Who writes a session's replies, as a client states it. */\nexport const REPLIES_BY = [\"model\", \"person\"] as const;\nexport type RepliesBy = (typeof REPLIES_BY)[number];\n\n/** The session column's value for each (sessions.subject_type). */\nexport const SUBJECT_TYPE_OF_REPLIES_BY: Record<RepliesBy, \"agent\" | \"human\"> = {\n model: \"agent\",\n person: \"human\",\n};\n\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 /**\n * Who writes the replies of this session: a model (the default) or a\n * person, as in a call between two people where one of them is the\n * agent. Session context like openedVia: the worker writes it on the\n * session at create (sessions.subject_type, 'agent' or 'human') and\n * ignores it afterwards. The session is created by whichever turn is\n * processed first, which need not be the first one sent, so send it on\n * every turn of the session (the import does). A session that\n * says a person replies carries no served model, and a judge run reads\n * that as a declaration, never as a model that went unrecorded.\n */\n repliesBy: z.enum(REPLIES_BY).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, SOURCE_SESSION_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\";\nexport * from \"./session-origin\";\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: 'my-assistant',\n * });\n *\n * // Model 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 * recorded before any session entry existed for their externalId. Moved\n * into the session entry when it is created (startSession, or the first\n * captured turn). Holds at most 100 session ids; the oldest is dropped.\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 /** Your user id from startSession; sent with 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 * Time of the last captured turn. Used on the next turn to derive\n * transition.timeMs (previous reply to this turn's submit) and\n * firstKeystrokeMs (previous reply to typing start).\n */\n lastAgentTurnAt: number | null;\n /**\n * Time of the last userInputSubmit. Used when a turn is captured to\n * derive agentReflectMs (submit to capture). transition.timeMs uses the\n * per-turn pendingUserInput.submittedAt instead, which resets on every\n * capture, so an earlier submit is never reused for it.\n */\n lastUserSubmitAt: number | null;\n /**\n * True once openedVia/clientContext have been sent with a captured turn.\n * The server stores session context from the first turn of a session, so\n * the SDK sends it once.\n */\n sessionContextForwarded: boolean;\n /** The person's input held for the next captured turn. */\n pendingUserInput: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount: number;\n submittedAt?: number;\n } | null;\n /** Thumbs or rating held for the next captured turn. */\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}` : \"the input does not match the expected shape\"}). Nothing was sent; fix that field.`,\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. Throws on an invalid\n * configuration; no other method throws on bad input. A second call\n * prints one warning and is ignored; call shutdown() first to\n * re-initialize.\n */\n static init(config: ProbeConfigInput): void {\n if (state !== null) {\n console.warn(\n \"[sight] Sight.init() was called again and ignored. Call Sight.shutdown() first to change the configuration.\",\n );\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 model call made inside\n * `fn` through a wrapped OpenAI client, the Vercel AI SDK or an\n * instrumented library is captured as a turn on the session `sessionId`\n * (your conversation id).\n *\n * Required for autocapture: a call made outside any session scope is not\n * captured. The first such call in a process prints one warning; later\n * ones log only with `debug: true`. Exceptions, used only when there is\n * no scope: a span that carries `gen_ai.conversation.id`, and an `ai`\n * call that names its session (see `sightTelemetry`). An explicit scope\n * always wins.\n *\n * The scope is carried across awaits. Returns what `fn` returns.\n */\n static async withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n ): Promise<T> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.withSession() ran before Sight.init(): the callback ran, nothing is captured. Call Sight.init() once at startup.\",\n );\n return fn();\n }\n return withSessionContext(sessionId, fn);\n }\n\n /**\n * Set the default persona for the process. Replaces the previous default.\n * To set a persona per session, use startSession({ externalId, persona }).\n */\n static identifyPersona(persona: PersonaConfig): void {\n if (state === null) {\n console.warn(\n \"[sight] Sight.identifyPersona() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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. Optional: a session is created on its\n * first captured turn. Call it to attach `externalUserId` (your stable,\n * pseudonymous user id), a persona, version tags or client context.\n *\n * Calling it again with the same externalId updates the entry. Invalid\n * input logs one warning and is ignored.\n */\n static startSession(input: SessionStart): void {\n if (state === null) {\n console.warn(\n \"[sight] Sight.startSession() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * SHA-256 hex hash of prompt or configuration text, for\n * `environmentConfigHash` on Sight.startSession(). The hash identifies a\n * version; pass a readable name alongside as `environmentConfigLabel`.\n *\n * Autocapture uses the same hash: when it sees a system prompt and the\n * session has no environmentConfigHash, the session gets the system\n * prompt's hash and the label 'auto:' plus its first 8 characters.\n * Values you pass to startSession always win.\n */\n static async hashEnvironmentConfig(input: string): Promise<string> {\n return hashEnvironmentConfig(input);\n }\n\n /**\n * End a session: sends the end reason (`natural` when none is given) and\n * releases the session's in-memory entry. Optional; a session you never\n * end times out on the server.\n *\n * - `outcome` (with optional `outcomeDetail`) is sent as an outcome\n * event before the session end.\n * - With no `outcome` and an outcome hook registered (init `outcomeHook`\n * or wireOutcomeHook()), `hook.resolve(externalId)` runs; a non-null\n * result is sent as an outcome event. This is the only place the hook\n * runs. A hook that throws logs one warning and does not break\n * endSession.\n * - For an outcome known later, or for a session you never end, call\n * emitOutcomeEvent().\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] the outcome hook's resolve() threw, so no outcome was sent for this session. Fix the hook, or send the outcome with Sight.emitOutcomeEvent(). Error:\",\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] the session end was not sent. Call Sight.endSession() again, or leave the session to time out. Error:\",\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 time since the previous reply,\n * sent as `userInput.firstKeystrokeMs` with the next captured turn. No\n * value is sent before the session's first captured turn.\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) and the submit time.\n * Both are sent with the next captured turn: a turn's person text is the\n * message that prompted its reply. Call it before the model call.\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 /** Record a thumbs-up or thumbs-down. Sent with the next captured 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 * Record a rating: an integer from 1 to 5. Sent with the next captured\n * turn. 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 * startSession, with client context (locale, timezone, runtime) collected\n * for you unless `input.clientContext` is given.\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: the deployment's outcome type and a\n * resolver for it. `resolve(sessionExternalId)` runs only when you call\n * endSession() without an `outcome`; the SDK runs no timers. A non-null\n * result is sent as an outcome event on the session. For a session you\n * never end, or an outcome known later (webhook, CRM callback), call\n * emitOutcomeEvent(); it joins to the session by sessionExternalId.\n */\n static wireOutcomeHook(hook: OutcomeHook): void {\n if (state === null) {\n console.warn(\n \"[sight] Sight.wireOutcomeHook() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\n return;\n }\n state.outcomeHook = hook;\n }\n\n /**\n * Capture a turn yourself, for a model call autocapture does not see.\n *\n * - `turnIndex` is the turn's position in the session, starting at 0.\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 checked 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 * - A failed send never throws; it logs with `debug: true`. The first\n * send the API rejects (401, 403, another 4xx) prints one warning\n * without it.\n *\n * Persona used for the turn, in this order:\n * 1. turn.personaSlug\n * 2. the session's persona (from startSession)\n * 3. the default from init or identifyPersona\n *\n * When that persona has signature phrases, the SDK matches them against\n * the reply text and sends the matched slugs as\n * `signaturePhraseMatches`.\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 * Record an outcome on a session, stored with the `kind` string you\n * supply: for example \"ticket_resolved\", \"purchase_complete\",\n * \"handoff_to_human\". Call it wherever the outcome becomes known, at any\n * time after the session; it joins to the session by sessionExternalId.\n * Invalid input logs one warning and is dropped. A failed send never\n * throws.\n */\n static async emitOutcomeEvent(input: OutcomeEventEmit): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.emitOutcomeEvent() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record one event from a channel beside the conversation (a feed, a\n * game state, an editor buffer) against a session. `source_type` and\n * `event` are free strings; you define their meaning. The event is\n * stored and attached to the session's turns by time, and is not\n * interpreted. Errors are logged with `debug: true`, never thrown.\n *\n * `alignment` describes the clock the event's time comes from. It\n * defaults to this process's clock; to state your own clock, or to send\n * a batch, call captureEnvironmentEvents.\n */\n static async captureEnvironmentEvent(\n event: EnvironmentEventInput,\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.captureEnvironmentEvent() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record a batch of environment events, with an optional `alignment`\n * (clock_source, skew_bound_ms, rule_version) describing their clock. At\n * most 100 events per call. Events in one batch may belong to different\n * sessions; each names its own. Errors are logged with `debug: true`,\n * never thrown.\n */\n static async captureEnvironmentEvents(\n events: EnvironmentEventInput[],\n alignment: AlignmentProvenance = DEFAULT_ENVIRONMENT_ALIGNMENT,\n ): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.captureEnvironmentEvents() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record one span: a step inside a turn (a model call, a tool call, a\n * framework step, or a custom unit). The span attaches to the turn named\n * by `turnIndex`; when omitted, to the session's latest turn at or\n * before the span's `startedAt` (the most recent turn when `startedAt`\n * is absent too). A span whose turn cannot be found is dropped by the\n * server. Errors are logged with `debug: true`, never thrown.\n *\n * `attributes` are metadata only (tool names, argument shapes), never\n * conversation text. `alignment` defaults to this process's clock; to\n * state your own clock, send a batch, or link parent and child spans,\n * call captureSpans.\n */\n static async captureSpan(\n span: SpanInput,\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.captureSpan() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record a batch of spans, with an optional `alignment` (clock_source,\n * skew_bound_ms, rule_version) describing their clock. At most 50 spans\n * per call. Spans in one batch may belong to different sessions; each\n * names its own. To link parent and child, give a span a `spanId` and\n * name it in another span's `parentSpanId` within the same batch; a\n * reference that matches no span is stored as null. Errors are logged\n * with `debug: true`, never thrown.\n */\n static async captureSpans(\n spans: SpanInput[],\n alignment?: AlignmentProvenance,\n ): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.captureSpans() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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 * Record a person's report that a reply was out of character. Connect it\n * to your product's report control. With no `turnIndex`, the flag\n * attaches to the session's most recent turn.\n */\n static async flagPersonaBreak(input: FlagPersonaBreakInput): Promise<void> {\n if (state === null) {\n console.warn(\n \"[sight] Sight.flagPersonaBreak() was called before Sight.init() and ignored. Call Sight.init() once at startup.\",\n );\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: waits for sends in flight (at most 15 seconds),\n * then clears the in-memory state (sessions, pending input) so init()\n * can be called again. Model calls made after shutdown are not captured\n * until the next init. Await it before a short-lived process exits; a\n * send still in flight at exit is lost. Safe to call more than once.\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 /** Internal. Not part of the public API. */\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","/**\n * The serving client: a typed client for the Field API, the routes that put\n * a profile (a SOUL.md or complete scene) at a name, serve it turn by turn\n * and read its record. It is separate from the capture API (`Sight`) and shares nothing\n * with it: its own key, its own requests, no process state.\n *\n * import { createFieldClient } from '@cultured_computer/sight';\n *\n * const field = createFieldClient({ apiKey: process.env.SIGHT_APP_KEY! });\n * await field.profiles.put('listener', soulMarkdown);\n * await field.conversations.start('listener', { conversation: 'c-1', user: 'u-1' });\n * const { reply } = await field.turns.send('listener', { conversation: 'c-1', message: 'Hi' });\n *\n * Every refused request throws a `FieldRefusal` carrying the HTTP status,\n * the refusal `code` and, when the answer has one, the `reason`. Nothing is\n * retried automatically. Identified turns use `/turn-requests`; `replay`\n * reads the original receipt without admitting another provider call.\n *\n * Server-side only: the key it holds can rewrite the profile.\n */\n\n/** The API host. Every machine call, capture and serving, goes to it. */\nexport const DEFAULT_FIELD_ENDPOINT = 'https://api.cultured.computer';\n\n// ── Vocabulary ───────────────────────────────────────────────────────────\n\n/**\n * Every refusal code the routes this client calls can answer: the\n * conversation and turn routes, the rate limit, the profile put and the\n * profile read. A refusal with no code (a 401, a 403 for a key that lacks a\n * permission, a 413) carries `code: null`.\n */\nexport const FIELD_REFUSAL_CODES = [\n // The conversation and turn routes, and the rate limit.\n 'invalid_body',\n 'forbidden',\n 'not_enabled',\n 'no_such_profile',\n 'no_such_endpoint',\n 'no_such_conversation',\n 'conversation_unknown',\n 'archived',\n 'revoked',\n 'link_inactive',\n 'conversation_conflict',\n 'constructed_forbidden',\n 'opening_forbidden',\n 'opening_conflict',\n 'runtime_forbidden',\n 'invalid_reasoning_effort',\n 'invalid_max_output_tokens',\n 'invalid_reply_check',\n 'conversation_ended',\n 'no_live_version',\n 'no_owner',\n 'model_unavailable',\n 'daily_cap',\n 'link_session_cap',\n 'rate_limited',\n 'turn_cap',\n 'stale_turn_index',\n 'record_gap',\n 'busy',\n 'interrupted',\n 'not_connected',\n 'budget',\n 'provider_error',\n 'provider_timeout',\n 'turn_failed',\n 'request_unknown',\n 'request_conflict',\n 'request_pending',\n 'request_interrupted',\n 'replay_expired',\n // The profile put.\n 'put_in_progress',\n 'scene_live',\n 'precondition_failed',\n 'invalid_consent',\n 'invalid_safeguards',\n 'invalid_scrub',\n 'invalid_fallback',\n 'invalid_scene',\n // The profile read.\n 'not_a_soul_md',\n 'not_a_scene',\n] as const;\nexport type FieldRefusalCode = (typeof FIELD_REFUSAL_CODES)[number];\n\n/**\n * The reasoning efforts a profile or a conversation can ask for. `none`\n * asks for no reasoning. An effort is sent only where the model's\n * catalogue entry lists it; elsewhere it is left out.\n */\nexport const FIELD_REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;\nexport type FieldReasoningEffort = (typeof FIELD_REASONING_EFFORTS)[number];\n\n/**\n * Why a model finished a turn with no reply text, on a `provider_error`:\n * `empty_completion`, or `empty_completion_length` when the output limit\n * ended it before any reply text (a reasoning model that spent\n * `maxOutputTokens` reasoning).\n */\nexport type FieldEmptyCompletionReason = 'empty_completion' | 'empty_completion_length';\n\n/**\n * Where a resolved runtime setting came from: the conversation's own\n * `runtime` (the request), the profile's, or the house default for the\n * model.\n */\nexport type FieldRuntimeSource = 'request' | 'profile' | 'default';\n\n/** The sources the profile read names: no request is in play there. */\nexport type FieldProfileRuntimeSource = Extract<FieldRuntimeSource, 'profile' | 'default'>;\n\n/** Why an ended conversation ended, on a `conversation_ended` refusal. */\nexport type FieldEndedReason = 'idle' | 'turn_cap' | 'floor' | 'failed' | 'ended';\n\n/**\n * The served runtime record: what the reply call is sent. Every key is\n * optional; a key left out keeps the profile's value (or, on a profile,\n * the default).\n */\nexport type FieldRuntime = {\n /** An OpenRouter model id the model catalogue routes, `vendor/model`. */\n model?: string;\n /** 0 to 2. Default 0.7. Sent unless the model's route takes none. */\n temperature?: number;\n /**\n * The reply's output budget in tokens: an integer from 256 to the\n * model's catalogue max_completion_tokens (16384 when it states none),\n * else `invalid_max_output_tokens`. A reasoning model's reasoning tokens\n * count inside it, with the answer. Default: the\n * smaller of 16384 and the model's catalogue max_completion_tokens;\n * 4096 when the catalogue says nothing of the model.\n */\n maxOutputTokens?: number;\n /**\n * Default: `low` where the model's catalogue lists it, else the lowest\n * effort it lists; nothing when it lists none.\n */\n reasoningEffort?: FieldReasoningEffort;\n /** The declared reply screens: off, mark only, or re-voice a confirmed flat refusal. */\n replyCheck?: 'off' | 'mark' | 'revoice';\n};\n\n// ── The error ────────────────────────────────────────────────────────────\n\n/** A fixed platform text you must show the person, before the reply. */\nexport type FieldNotice = { kind: string; text: string };\n\n/** One frame of a turn, as the JSON answer collects it. */\nexport type FieldEventRecord = { event: string; data: unknown };\n\n/**\n * A request the Field API refused: any answer that is not a 2xx. Branch on\n * `code`, not on the message.\n */\nexport class FieldRefusal extends Error {\n override readonly name = 'FieldRefusal';\n /** The HTTP status. */\n readonly status: number;\n /**\n * The refusal's stable code, one of `FIELD_REFUSAL_CODES` from this\n * version; a newer API may answer a code this version does not list.\n * `null` when the answer carries none (401, a 403 for a missing\n * permission, 413, a 503 while the service drains).\n */\n readonly code: FieldRefusalCode | (string & {}) | null;\n /**\n * Why, when the answer says: the ended reason of a `conversation_ended`,\n * or the empty-completion reason of a `provider_error`. Otherwise null.\n */\n readonly reason: FieldEndedReason | FieldEmptyCompletionReason | (string & {}) | null;\n /** `Retry-After` in seconds, when the answer carries one (429, 503, a busy put). */\n readonly retryAfter: number | null;\n /** A failed turn still answers its notices; show them. Empty otherwise. */\n readonly notices: FieldNotice[];\n /** A failed turn's frames, collected before it failed. Empty otherwise. */\n readonly events: FieldEventRecord[];\n /** A failed turn's index, when the answer names one. */\n readonly turnIndex: number | null;\n /** The answer's body as sent: parsed JSON, or the text when it is not JSON. */\n readonly body: unknown;\n\n constructor(init: {\n status: number;\n message: string;\n code: string | null;\n reason: string | null;\n retryAfter: number | null;\n notices: FieldNotice[];\n events: FieldEventRecord[];\n turnIndex: number | null;\n body: unknown;\n }) {\n super(init.message);\n this.status = init.status;\n this.code = init.code;\n this.reason = init.reason;\n this.retryAfter = init.retryAfter;\n this.notices = init.notices;\n this.events = init.events;\n this.turnIndex = init.turnIndex;\n this.body = init.body;\n }\n}\n\n// ── Answer shapes ────────────────────────────────────────────────────────\n\nexport type FieldVersionRef = { id: string; contentHash: string; configHash: string; label: string };\nexport type FieldLimits = { idleMinutes: number; turnsPerConversation: number; conversationsPerDay: number };\nexport type FieldSafeguards = { crisis: boolean; disclosure: boolean; policy: string };\nexport type FieldConnection =\n | { openrouter: 'connected'; via: 'project' | 'operator' }\n | { openrouter: 'missing'; connect: string };\nexport type FieldProfileLinks = {\n profile: string;\n conversations: string;\n turns: string;\n sessions: string;\n versions: string;\n reviews: string;\n};\nexport type FieldProfileEndpoint = {\n id: string;\n name: string;\n versionMode: 'live' | 'pinned';\n guestsAllowed: boolean;\n idleMinutes: number;\n turnsPerConversation: number;\n conversationsPerDay: number;\n /** Effective execution configuration, readable by the profile key. */\n deploymentId?: string;\n readsPosture?: 'full' | 'post-reply';\n closingLine?: string | null;\n revealsState?: boolean;\n};\n\nexport type FieldSceneDocument = {\n title?: string;\n sections: unknown[];\n settings?: {\n model?: string;\n temperature?: number;\n consent?: boolean | string;\n safeguards?: string;\n fallback?: string;\n scrub?: string;\n replyCheck?: string;\n reasoningEffort?: string;\n maxOutputTokens?: number | string;\n reader?: 'jev-latest' | null;\n };\n};\n\n/** The answer to `profiles.put`. */\nexport type FieldProfilePut = {\n profile: string;\n floor: 'steer' | 'exit';\n outcome: 'created' | 'new version, pointer moved' | 'settings changed' | 'no change';\n /** What moved: `file`, `model`, `temperature`, `reasoningEffort`, a limit, ... */\n changed: string[];\n format: 'soul-md' | 'scene';\n dryRun?: true;\n replaced?: { id: string; label: string };\n version: FieldVersionRef;\n endpoint: FieldProfileEndpoint;\n limits: FieldLimits;\n core: Array<{ heading: string; chars: number }>;\n detectors: { active: string[]; classifier: string } | { active: string[]; note: string };\n /** Parts of the file left out, each with why. Check it after every put. */\n refused: Array<{ heading: string; reason: string }>;\n runtime: {\n model: string;\n provider: 'openrouter';\n temperature: number;\n reasoningEffort?: FieldReasoningEffort;\n /** The output budget the saved version asks for; absent when it names none. */\n maxOutputTokens?: number;\n consent: boolean;\n fallback: string | null;\n fallbackNote?: string;\n };\n safeguards: FieldSafeguards;\n scrub: string;\n connection: FieldConnection;\n links: FieldProfileLinks;\n /** The `ETag` header: the live version's id, quoted. Send it as `ifMatch`. */\n etag: string | null;\n};\n\n/** The answer to `profiles.get`. */\nexport type FieldProfile = {\n profile: string;\n deploymentId?: string;\n floor: 'steer' | 'exit';\n archived: boolean;\n archivedAt: string | null;\n version: { id: string; contentHash: string; configHash: string; label: string } | null;\n endpoint: (FieldProfileEndpoint & { revokedAt: string | null }) | null;\n limits: FieldLimits | null;\n links: FieldProfileLinks;\n runtime: {\n model: string;\n provider: string;\n temperature: number;\n /**\n * The output budget the replies are sent with: the live version's own,\n * else the house default.\n */\n maxOutputTokens?: number;\n maxOutputTokensSource?: FieldProfileRuntimeSource;\n /**\n * The effort the replies ask for: the live version's own, else the\n * house default; null when nothing is asked (the catalogue lists no\n * efforts).\n */\n reasoningEffort?: FieldReasoningEffort | null;\n reasoningEffortSource?: FieldProfileRuntimeSource;\n readerModel: string | null;\n fallback: string | null;\n } | null;\n consent: boolean;\n safeguards: FieldSafeguards;\n scrub: string;\n connection: FieldConnection;\n /** The `ETag` header: the live version's id, quoted. Send it as `ifMatch`. */\n etag: string | null;\n};\n\n/** One session as the sessions list answers it. */\nexport type FieldSessionSummary = {\n id: string;\n /** Your own conversation id, as the start sent it. */\n conversation: string | null;\n runId: string;\n user: string | null;\n startedAt: string | null;\n endedAt: string | null;\n ended: boolean;\n endedReason: string | null;\n status: string;\n error?: string;\n turns: number;\n rehearsal: boolean;\n /** The start's independent exemplar-sampling seed; null keeps legacy run-id sampling. */\n moveSeed: number | null;\n origin: 'observed' | 'constructed';\n opening: { turns: number } | null;\n version: FieldVersionRef;\n flags: number;\n shapes: Record<string, number>;\n path: string;\n};\n\n/** The answer to `profiles.sessions`: one page, newest first. */\nexport type FieldSessionsPage = {\n profile: string;\n archived: boolean;\n limit: number;\n sessions: FieldSessionSummary[];\n /** Pass as `cursor` for the next page; null on the last page. */\n nextBefore: string | null;\n links: { profile: string; sessions: string; versions: string };\n};\n\nexport type FieldSampledMove = {\n blockId: string;\n moveId: string;\n candidates: Array<{ label: string }>;\n /** Actual selection propensities in candidate order. */\n propensities: number[];\n selectedIndex: number;\n selectionMeta: { temperature: number; seed: string; policy_version: 'uniform-v1' };\n};\n\n/** One turn of a session's record. */\nexport type FieldSessionTurn = {\n index: number;\n at?: string;\n pending?: true;\n text: 'stored' | 'pending';\n message: string | null;\n reply: string | null;\n outcome: 'floor' | 'error' | 'reply';\n error?: string;\n version: FieldVersionRef | null;\n model: { id: string; provider: string } | null;\n fallbackFrom?: string;\n sent?: { temperature: number | null; seed: number | null; reasoning?: { effort: string }; maxOutputTokens?: number };\n detectors: Array<{\n statement: string;\n flagged: boolean;\n verdict: string;\n score: string | null;\n bar: number | null;\n phase: 'before' | 'after';\n steers: boolean;\n consequence?: string;\n entered?: { heading: string; replyTurn: number };\n }>;\n entered: Array<{ heading: string; detector: string; flaggedOnTurn: number | null }>;\n shapes: Array<{ shape: string; evidence: Record<string, unknown>; version: string | null }>;\n moves: unknown[];\n /** One draw per active moves block; empty when no exemplar was sampled. */\n sampledMoves: FieldSampledMove[];\n floor?: unknown;\n notices?: FieldNotice[];\n storedHistoryTurns?: number;\n usage: {\n model: string | null;\n tokensIn: number | null;\n tokensOut: number | null;\n latencyMs: number | null;\n costUsd: number | null;\n } | null;\n};\n\n/** The answer to `sessions.get`: the header and its turns in order. */\nexport type FieldSessionRecord = {\n profile: string;\n session: Omit<FieldSessionSummary, 'path'> & {\n usage: { model: string | null; tokensIn: number | null; tokensOut: number | null; costUsd: number | null };\n };\n text: 'stored';\n opening: {\n constructed: true;\n text: 'as-sent';\n turns: Array<{ role: 'person' | 'assistant'; text: string }>;\n } | null;\n turns: FieldSessionTurn[];\n readsTruncated?: true;\n links: { profile: string; sessions: string; versions: string };\n};\n\n/** The answer to `conversations.start`. */\nexport type FieldConversation = {\n runId: string;\n sessionId: string;\n version: number | null;\n /** The path of the session's record (`GET` it with the same key). */\n record: string;\n};\n\n/** The answer to `conversations.end`. */\nexport type FieldConversationEnd = {\n ok: true;\n /** True when an earlier end already closed the conversation. */\n alreadyEnded: boolean;\n runId: string;\n sessionId: string;\n /** The path of the session's record (`GET` it with the same key). */\n record: string;\n};\n\n/** The answer to `turns.send`. */\nexport type FieldTurnAnswer = {\n reply: string;\n /** Show these to the person, before the reply. Empty when none. */\n notices: FieldNotice[];\n /** Every other frame of the turn, in order. */\n events: FieldEventRecord[];\n turnIndex: number;\n};\n\n// ── Stream frames ────────────────────────────────────────────────────────\n\nexport type FieldRunFrame = {\n runId: string;\n sessionId: string;\n model: string;\n provider: string;\n modelKey?: string;\n /** What the reply call sent; null when the route takes none. */\n temperature: number | null;\n seed: number | null;\n /** Present only when an effort was sent. */\n reasoning?: { effort: string };\n /** The output budget the call sent (reasoning and answer together). */\n maxOutputTokens?: number;\n opening?: { turns: number };\n /** The conversation's runtime override, as its start sent it. */\n override?: FieldRuntime;\n};\nexport type FieldReadFrame = { statement: string; score?: number; bar?: number; moment?: string; phase: string };\nexport type FieldDoneFrame = { status: string; turnIndex: number };\nexport type FieldErrorFrame = {\n message: string;\n code: FieldRefusalCode | (string & {});\n /** On a `provider_error` with no reply text: why. */\n reason?: FieldEmptyCompletionReason | (string & {});\n turnIndex?: number;\n};\n\n/**\n * One server-sent frame of a streamed turn, in order: `run`, then any\n * `notice` and `reads` before the first `delta`, the `delta`s, `events`,\n * and `done` or `error`. A frame this version does not know arrives as\n * `other`, with its name.\n */\nexport type FieldTurnFrame =\n | { event: 'run'; data: FieldRunFrame }\n | { event: 'notice'; data: FieldNotice }\n | { event: 'reads'; data: FieldReadFrame[] }\n | { event: 'delta'; data: { text: string } }\n | { event: 'events'; data: unknown[] }\n | { event: 'done'; data: FieldDoneFrame }\n | { event: 'error'; data: FieldErrorFrame }\n | { event: 'other'; name: string; data: unknown };\n\n// ── Inputs ───────────────────────────────────────────────────────────────\n\nexport type FieldClientOptions = {\n /** An App key (`studio:serve` and `profiles:write`). Keep it on a server. */\n apiKey: string;\n /** The API host. Default `https://api.cultured.computer`. */\n endpoint?: string;\n};\n\n/** Options of `profiles.put` and `profiles.putScene`. Each overrides the document's settings for this put. */\nexport type FieldPutOptions = FieldRuntime & {\n /** A model id that answers when the model fails before its reply started, or `none`. */\n fallback?: string;\n consent?: boolean;\n /** `crisis`, `disclosure`, both, or `none`. */\n safeguards?: Array<'crisis' | 'disclosure'> | 'none';\n scrub?: 'identifiers-only' | 'standard';\n idleMinutes?: number;\n turnsPerConversation?: number;\n conversationsPerDay?: number;\n /** Answer what the put would do and store nothing. */\n dryRun?: boolean;\n /** Replace a live stepped scene with the file. */\n force?: boolean;\n /** A conditional put: the `etag` a read or the last put answered. */\n ifMatch?: string;\n /** Create-only with `*`: fail if the profile already exists. */\n ifNoneMatch?: string;\n signal?: AbortSignal;\n};\n\nexport type FieldStartOptions = {\n /** Your own id for the conversation, at most 200 characters. One per thread. */\n conversation: string;\n /**\n * Your own opaque, stable id for the person, at most 200 characters: a\n * hash or your internal id, never an email or a name. A conversation\n * belongs to the person it was started for.\n */\n user: string;\n /**\n * This conversation's runtime, over the profile's. Only a key holding\n * `profiles:write` may send one (`runtime_forbidden` otherwise). A\n * repeated start must send the same (`opening_conflict` otherwise).\n */\n runtime?: FieldRuntime;\n /** A constructed opening: earlier exchanges, the person first and the assistant last. */\n opening?: Array<{ role: 'person' | 'assistant'; text: string }>;\n /** Explicit provenance for a scripted run, including one with no constructed opening. */\n constructed?: 'scripted';\n /** A signed 32-bit integer; each turn sends the seed plus its index where the route takes one. */\n seed?: number;\n /** Independent exemplar-move sampling seed; absent keeps the service's legacy behavior. */\n moveSeed?: number;\n signal?: AbortSignal;\n};\n\nexport type FieldEndOptions = {\n /** Your own id for the conversation, at most 200 characters. */\n conversation: string;\n signal?: AbortSignal;\n};\n\nexport type FieldTurnOptions = {\n conversation: string;\n message: string;\n /** The turn index you expect to be next; a stale one is refused with `stale_turn_index`. */\n resume?: { turnIndex: number };\n signal?: AbortSignal;\n};\n\nexport type FieldTurnRequestOptions = FieldTurnOptions & {\n /** A UUID stable for this logical turn. Reuse it only with the same conversation, message and index. */\n requestId: string;\n /** Required request identity: the next turn index, zero on a new conversation. */\n resume: { turnIndex: number };\n};\n\nexport type FieldEndpointPatchOptions = {\n revealsState: boolean;\n signal?: AbortSignal;\n};\n\nexport type FieldSessionsOptions = {\n /** Your own conversation id, exact match. */\n conversation?: string;\n /** The `nextBefore` of the previous page. */\n cursor?: string;\n /** Default 50, at most 200. */\n limit?: number;\n /** A content hash, a config hash or a version id. */\n version?: string;\n ended?: boolean;\n signal?: AbortSignal;\n};\n\nexport type FieldClient = {\n profiles: {\n /** Put a SOUL.md at a name: creates the profile, or saves a new version or new settings. */\n put(name: string, soulMarkdown: string, options?: FieldPutOptions): Promise<FieldProfilePut>;\n /** Put one complete scene document; a string body is sent byte for byte. */\n putScene(name: string, scene: FieldSceneDocument | string, options?: FieldPutOptions): Promise<FieldProfilePut>;\n /** Read a profile: its live version, runtime, limits, safeguards and connection. */\n get(name: string, options?: { signal?: AbortSignal }): Promise<FieldProfile>;\n /** List a profile's served sessions, newest first, one page at a time. */\n sessions(name: string, options?: FieldSessionsOptions): Promise<FieldSessionsPage>;\n };\n endpoints: {\n /** Change keyed endpoint configuration by the id returned on the profile read. */\n update(id: string, options: FieldEndpointPatchOptions): Promise<FieldProfileEndpoint>;\n };\n conversations: {\n /** Start a conversation, or answer the running one under the same id. */\n start(profile: string, options: FieldStartOptions): Promise<FieldConversation>;\n /** End a conversation without a model call; replaying the end is safe. */\n end(profile: string, options: FieldEndOptions): Promise<FieldConversationEnd>;\n };\n turns: {\n /** Serve one turn and answer it as one JSON body. Throws `FieldRefusal` when the turn fails. */\n send(profile: string, options: FieldTurnOptions): Promise<FieldTurnAnswer>;\n /**\n * Serve one turn as a stream of frames. A refusal before the stream\n * starts throws `FieldRefusal` from the loop; a failure once it has\n * started arrives as an `error` frame and ends the stream.\n */\n stream(profile: string, options: FieldTurnOptions): AsyncGenerator<FieldTurnFrame, void, undefined>;\n /** Admit one identified turn, or replay an existing receipt with the same identity. */\n request(profile: string, options: FieldTurnRequestOptions): Promise<FieldTurnAnswer>;\n /** Read only the identified turn's receipt; never admits a conversation or model call. */\n replay(profile: string, options: FieldTurnRequestOptions): Promise<FieldTurnAnswer>;\n /** The identified request as raw ordered SSE frames. */\n requestStream(profile: string, options: FieldTurnRequestOptions): AsyncGenerator<FieldTurnFrame, void, undefined>;\n /** Replay-only receipt recovery as raw ordered SSE frames. */\n replayStream(profile: string, options: FieldTurnRequestOptions): AsyncGenerator<FieldTurnFrame, void, undefined>;\n };\n sessions: {\n /** Read one session's record, turn by turn. */\n get(id: string, options?: { signal?: AbortSignal }): Promise<FieldSessionRecord>;\n };\n};\n\n// ── The client ───────────────────────────────────────────────────────────\n\ntype Query = Record<string, string | number | boolean | undefined>;\n\nfunction queryString(query: Query): string {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) params.append(key, String(value));\n }\n const text = params.toString();\n return text ? `?${text}` : '';\n}\n\nconst segment = (value: string): string => encodeURIComponent(value);\n\nfunction parseRetryAfter(value: string | null): number | null {\n if (value === null) return null;\n const seconds = Number(value);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Every non-2xx answer becomes a FieldRefusal, the body read once. */\nasync function refusalOf(response: Response): Promise<FieldRefusal> {\n const text = await response.text().catch(() => '');\n let body: unknown = text;\n try {\n body = text ? JSON.parse(text) : null;\n } catch {\n // Not JSON (a proxy's page): keep the text.\n }\n const record = isRecord(body) ? body : {};\n const events = Array.isArray(record['events']) ? (record['events'] as FieldEventRecord[]) : [];\n // A failed turn in JSON mode names its reason on the error frame it\n // collected; a conversation_ended names it at the top.\n const errorFrame = events.find((frame) => isRecord(frame) && frame.event === 'error');\n const frameReason = errorFrame && isRecord(errorFrame.data) ? errorFrame.data['reason'] : undefined;\n const reason = typeof record['reason'] === 'string' ? record['reason'] : typeof frameReason === 'string' ? frameReason : null;\n const sentence = typeof record['error'] === 'string' ? record['error'] : null;\n return new FieldRefusal({\n status: response.status,\n message: sentence ?? `the Field API answered ${response.status}`,\n code: typeof record['code'] === 'string' ? record['code'] : null,\n reason,\n retryAfter: parseRetryAfter(response.headers.get('retry-after')),\n notices: Array.isArray(record['notices']) ? (record['notices'] as FieldNotice[]) : [],\n events,\n turnIndex: typeof record['turnIndex'] === 'number' ? record['turnIndex'] : null,\n body,\n });\n}\n\nconst KNOWN_FRAMES = new Set(['run', 'notice', 'reads', 'delta', 'events', 'done', 'error']);\n\nfunction frameOf(name: string, raw: string): FieldTurnFrame {\n let data: unknown = raw;\n try {\n data = JSON.parse(raw);\n } catch {\n // A frame whose data is not JSON keeps its text.\n }\n if (KNOWN_FRAMES.has(name)) return { event: name, data } as FieldTurnFrame;\n return { event: 'other', name, data };\n}\n\n/**\n * The server-sent events grammar: frames separated by a blank line, `event:`\n * and `data:` fields (several `data:` lines join with a newline), comment\n * lines starting with `:` ignored. A frame with no `event:` is a `message`.\n * An unterminated frame at the end of the stream is dropped, as the grammar\n * says.\n */\nasync function* readFrames(body: ReadableStream<Uint8Array>): AsyncGenerator<FieldTurnFrame, void, undefined> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let name = '';\n let data: string[] = [];\n try {\n while (true) {\n const { done, value } = await reader.read();\n buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n let newline: number;\n while ((newline = buffer.search(/\\r\\n|\\r|\\n/)) !== -1) {\n // A lone \\r at the end of the buffer may be the first half of \\r\\n.\n if (buffer[newline] === '\\r' && newline === buffer.length - 1 && !done) break;\n const width = buffer.startsWith('\\r\\n', newline) ? 2 : 1;\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + width);\n if (line === '') {\n if (data.length > 0) yield frameOf(name || 'message', data.join('\\n'));\n name = '';\n data = [];\n continue;\n }\n if (line.startsWith(':')) continue;\n const colon = line.indexOf(':');\n const field = colon === -1 ? line : line.slice(0, colon);\n let content = colon === -1 ? '' : line.slice(colon + 1);\n if (content.startsWith(' ')) content = content.slice(1);\n if (field === 'event') name = content;\n else if (field === 'data') data.push(content);\n }\n if (done) return;\n }\n } finally {\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n\n/** The runtime record as the start's body carries it: only the keys set. */\nfunction runtimeBody(runtime: FieldRuntime): FieldRuntime {\n const out: FieldRuntime = {};\n if (runtime.model !== undefined) out.model = runtime.model;\n if (runtime.temperature !== undefined) out.temperature = runtime.temperature;\n if (runtime.maxOutputTokens !== undefined) out.maxOutputTokens = runtime.maxOutputTokens;\n if (runtime.reasoningEffort !== undefined) out.reasoningEffort = runtime.reasoningEffort;\n if (runtime.replyCheck !== undefined) out.replyCheck = runtime.replyCheck;\n return out;\n}\n\n/**\n * Create a serving client. It holds the key and the host, nothing else: no\n * state between calls, no retries, no timeout of its own (pass `signal`).\n */\nexport function createFieldClient(options: FieldClientOptions): FieldClient {\n if (!options || typeof options.apiKey !== 'string' || options.apiKey.trim() === '') {\n throw new TypeError('createFieldClient: apiKey is required (an App key; keep it on a server)');\n }\n const apiKey = options.apiKey;\n const endpoint = (options.endpoint ?? DEFAULT_FIELD_ENDPOINT).replace(/\\/+$/, '');\n\n async function request(\n method: 'GET' | 'POST' | 'PUT' | 'PATCH',\n path: string,\n init: { body?: string; contentType?: string; accept: string; headers?: Record<string, string>; signal?: AbortSignal | undefined },\n ): Promise<Response> {\n const headers: Record<string, string> = { authorization: `Bearer ${apiKey}`, accept: init.accept, ...init.headers };\n if (init.contentType) headers['content-type'] = init.contentType;\n const response = await fetch(`${endpoint}${path}`, {\n method,\n headers,\n ...(init.body !== undefined ? { body: init.body } : {}),\n ...(init.signal ? { signal: init.signal } : {}),\n });\n if (!response.ok) throw await refusalOf(response);\n return response;\n }\n\n async function json<T>(response: Response): Promise<T> {\n return (await response.json()) as T;\n }\n\n function turnBody(input: FieldTurnOptions): string {\n return JSON.stringify({\n conversation: input.conversation,\n message: input.message,\n ...(input.resume ? { resume: { turnIndex: input.resume.turnIndex } } : {}),\n });\n }\n\n function turnRequestBody(input: FieldTurnRequestOptions, replayOnly: boolean): string {\n return JSON.stringify({\n conversation: input.conversation,\n message: input.message,\n resume: { turnIndex: input.resume.turnIndex },\n requestId: input.requestId,\n ...(replayOnly ? { replayOnly: true } : {}),\n });\n }\n\n async function putDocument(name: string, body: string, contentType: string, put: FieldPutOptions): Promise<FieldProfilePut> {\n const query: Query = {\n model: put.model,\n temperature: put.temperature,\n maxOutputTokens: put.maxOutputTokens,\n reasoningEffort: put.reasoningEffort,\n replyCheck: put.replyCheck,\n fallback: put.fallback,\n consent: put.consent,\n safeguards: put.safeguards === undefined ? undefined : put.safeguards === 'none' ? 'none' : put.safeguards.join(','),\n scrub: put.scrub,\n idleMinutes: put.idleMinutes,\n turnsPerConversation: put.turnsPerConversation,\n conversationsPerDay: put.conversationsPerDay,\n dryRun: put.dryRun,\n force: put.force,\n };\n const response = await request('PUT', `/v1/profiles/${segment(name)}${queryString(query)}`, {\n body,\n contentType,\n accept: 'application/json',\n ...(put.ifMatch !== undefined || put.ifNoneMatch !== undefined ? { headers: {\n ...(put.ifMatch !== undefined ? { 'if-match': put.ifMatch } : {}),\n ...(put.ifNoneMatch !== undefined ? { 'if-none-match': put.ifNoneMatch } : {}),\n } } : {}),\n signal: put.signal,\n });\n return { ...(await json<Omit<FieldProfilePut, 'etag'>>(response)), etag: response.headers.get('etag') };\n }\n\n return {\n profiles: {\n async put(name, soulMarkdown, put = {}) {\n return putDocument(name, soulMarkdown, 'text/markdown', put);\n },\n async putScene(name, scene, put = {}) {\n return putDocument(name, typeof scene === 'string' ? scene : JSON.stringify(scene), 'application/vnd.cultured.scene+json', put);\n },\n async get(name, get = {}) {\n const response = await request('GET', `/v1/profiles/${segment(name)}`, { accept: 'application/json', signal: get.signal });\n return { ...(await json<Omit<FieldProfile, 'etag'>>(response)), etag: response.headers.get('etag') };\n },\n async sessions(name, list = {}) {\n const query: Query = {\n conversation: list.conversation,\n before: list.cursor,\n limit: list.limit,\n version: list.version,\n ended: list.ended,\n };\n const response = await request('GET', `/v1/profiles/${segment(name)}/sessions${queryString(query)}`, {\n accept: 'application/json',\n signal: list.signal,\n });\n return json<FieldSessionsPage>(response);\n },\n },\n endpoints: {\n async update(id, update) {\n const response = await request('PATCH', `/v1/endpoints/${segment(id)}`, {\n body: JSON.stringify({ revealsState: update.revealsState }),\n contentType: 'application/json',\n accept: 'application/json',\n signal: update.signal,\n });\n return json<FieldProfileEndpoint>(response);\n },\n },\n conversations: {\n async start(profile, start) {\n const body = JSON.stringify({\n conversation: start.conversation,\n user: start.user,\n ...(start.runtime !== undefined ? { runtime: runtimeBody(start.runtime) } : {}),\n ...(start.opening !== undefined ? { opening: start.opening } : {}),\n ...(start.constructed !== undefined ? { constructed: start.constructed } : {}),\n ...(start.seed !== undefined ? { seed: start.seed } : {}),\n ...(start.moveSeed !== undefined ? { moveSeed: start.moveSeed } : {}),\n });\n const response = await request('POST', `/v1/profiles/${segment(profile)}/conversations`, {\n body,\n contentType: 'application/json',\n accept: 'application/json',\n signal: start.signal,\n });\n return json<FieldConversation>(response);\n },\n async end(profile, end) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/conversations/end`, {\n body: JSON.stringify({ conversation: end.conversation }),\n contentType: 'application/json',\n accept: 'application/json',\n signal: end.signal,\n });\n return json<FieldConversationEnd>(response);\n },\n },\n turns: {\n async send(profile, turn) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/turns`, {\n body: turnBody(turn),\n contentType: 'application/json',\n accept: 'application/json',\n signal: turn.signal,\n });\n return json<FieldTurnAnswer>(response);\n },\n async *stream(profile, turn) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/turns`, {\n body: turnBody(turn),\n contentType: 'application/json',\n accept: 'text/event-stream',\n signal: turn.signal,\n });\n if (!response.body) return;\n yield* readFrames(response.body);\n },\n async request(profile, turn) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/turn-requests`, {\n body: turnRequestBody(turn, false),\n contentType: 'application/json',\n accept: 'application/json',\n signal: turn.signal,\n });\n return json<FieldTurnAnswer>(response);\n },\n async replay(profile, turn) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/turn-requests`, {\n body: turnRequestBody(turn, true),\n contentType: 'application/json',\n accept: 'application/json',\n signal: turn.signal,\n });\n return json<FieldTurnAnswer>(response);\n },\n async *requestStream(profile, turn) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/turn-requests`, {\n body: turnRequestBody(turn, false),\n contentType: 'application/json',\n accept: 'text/event-stream',\n signal: turn.signal,\n });\n if (!response.body) return;\n yield* readFrames(response.body);\n },\n async *replayStream(profile, turn) {\n const response = await request('POST', `/v1/profiles/${segment(profile)}/turn-requests`, {\n body: turnRequestBody(turn, true),\n contentType: 'application/json',\n accept: 'text/event-stream',\n signal: turn.signal,\n });\n if (!response.body) return;\n yield* readFrames(response.body);\n },\n },\n sessions: {\n async get(id, get = {}) {\n const response = await request('GET', `/v1/sessions/${segment(id)}`, { accept: 'application/json', signal: get.signal });\n return json<FieldSessionRecord>(response);\n },\n },\n };\n}\n"]}
|