@cultured_computer/sight 0.2.0 → 0.2.1
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/dist/index.cjs +60 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -1
- package/dist/index.d.ts +22 -1
- package/dist/index.js +60 -4
- package/dist/index.js.map +1 -1
- package/package.json +13 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/types.ts","../src/client-context.ts","../src/hash.ts","../src/instrumentation/session-context.ts","../src/instrumentation/otel-processor.ts","../src/instrumentation/setup.ts","../src/instrumentation/openai.ts","../src/instrumentation/anthropic.ts","../src/instrumentation/langchain.ts","../src/instrumentation/langgraph.ts","../src/instrumentation/vercel-ai.ts","../src/instrumentation/litellm.ts","../src/instrumentation/mercury.ts","../src/instrumentation/index.ts","../../classifier/src/signature-phrase.ts","../../shared/src/index.ts","../src/probe.ts"],"names":["state","registered","instrumentation","z"],"mappings":";;;;AAuBO,IAAM,qBAAA,GAAwB,2CAAA;AAE9B,IAAM,eAAN,MAAmB;AAAA,EAChB,MAAA;AAAA,EACA,QAAA;AAAA,EACA,KAAA;AAAA,EACA,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,qBAAA,GAAwB,KAAA;AAAA,EAEhC,YAAY,IAAA,EAA2B;AACrC,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/C,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,gBAAgB,IAAA,CAAK,YAAA,IAAgB,qBAAA,EAAuB,OAAA,CAAQ,OAAO,EAAE,CAAA;AAAA,EACpF;AAAA;AAAA;AAAA;AAA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AAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,QAAQ,CAAA,EAAA,EAAK;AACnC,MAAA,IAAA,IAAQ,GAAA,CAAI,WAAW,CAAC,CAAA;AACxB,MAAA,IAAA,GAAQ,OAAO,QAAA,KAAgB,CAAA;AAAA,IACjC;AACA,IAAA,OAAO,OAAO,UAAA,GAAa,IAAA;AAAA,EAC7B;AACF","file":"index.js","sourcesContent":["/**\n * HTTP client for the Probe ingest API.\n *\n * Sends captured turns to POST /v1/turns with a Bearer token. Async, fire-and-log:\n * SDK never blocks the customer's LLM path on ingest.\n */\n\nimport type {\n CapturedTurn,\n FlagPersonaBreakInput,\n OutcomeEventEmit,\n SessionEndInput,\n} from './types';\n\nexport type IngestClientOptions = {\n apiKey: string;\n endpoint: string;\n debug: boolean;\n /** Dashboard base URL for the one-time first-capture announcement. */\n dashboardUrl?: string;\n};\n\n/** Default dashboard base for the first-capture permalink. */\nexport const DEFAULT_DASHBOARD_URL = 'https://field.cultured.computer/dashboard';\n\nexport class IngestClient {\n private apiKey: string;\n private endpoint: string;\n private debug: boolean;\n private dashboardUrl: string;\n /**\n * First-trace permalink ritual (PLAN-2026-07-14-adoptions A1): the first\n * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,\n * then never again for the life of this client (one IngestClient per\n * process — one `init` per process; a restart prints once more, accepted).\n * Failed sends do not consume the announcement. Only sendTurn announces:\n * flags, outcome events, and session-end sends never trigger it (a flag\n * arriving before any turn is not a captured session).\n */\n private firstCaptureAnnounced = false;\n\n constructor(opts: IngestClientOptions) {\n this.apiKey = opts.apiKey;\n this.endpoint = opts.endpoint.replace(/\\/$/, '');\n this.debug = opts.debug;\n this.dashboardUrl = (opts.dashboardUrl ?? DEFAULT_DASHBOARD_URL).replace(/\\/$/, '');\n }\n\n /**\n * Send a turn to the ingest API. Fire-and-log: errors are logged but never\n * thrown. The customer's LLM path never blocks on the Probe.\n */\n async sendTurn(turn: CapturedTurn): Promise<void> {\n try {\n const response = await fetch(`${this.endpoint}/v1/turns`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(turn),\n });\n\n if (!response.ok) {\n this.log(`[probe] ingest failed status=${response.status}`);\n return;\n }\n\n // Announce the first successful capture exactly once per process.\n // Deliberately NOT gated on debug — this is the install-to-first-\n // value ritual, one line, permalink included. Stderr only, same\n // channel as log(). \"Captured\" means accepted at ingest (202,\n // pre-redaction); the permalink resolves by external id once the\n // worker projects the session (seconds later).\n if (!this.firstCaptureAnnounced) {\n this.firstCaptureAnnounced = true;\n // eslint-disable-next-line no-console\n console.error(\n `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`,\n );\n }\n\n if (this.debug) {\n const body = (await response.json()) as { status?: string; pendingId?: string };\n this.log(`[probe] ingest ok id=${body.pendingId ?? '?'}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[probe] ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.\n * Populates the `user_flagged_break` outcome column in Chapter 9c.\n */\n async sendFlag(deploymentSlug: string, flag: FlagPersonaBreakInput): Promise<void> {\n try {\n const response = await fetch(`${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\n if (!response.ok) {\n this.log(`[probe] flag ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[probe] flag ingest ok session=${flag.sessionExternalId}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[probe] flag ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a session-end event to the ingest API. Records why a session ended\n * on the sessions.probe_session_ended_reason column. Fire-and-log.\n */\n async sendSessionEnd(deploymentSlug: string, end: SessionEndInput): Promise<void> {\n try {\n const response = await fetch(`${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 if (!response.ok) {\n this.log(`[probe] session-end ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[probe] session-end ingest ok session=${end.externalId}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[probe] session-end ingest error: ${msg}`);\n }\n }\n\n /**\n * Send an outcome event to the ingest API. Fire-and-log. Populates\n * probe_outcome_events per Amendment I Method D.\n */\n async sendOutcomeEvent(\n deploymentSlug: string,\n event: OutcomeEventEmit,\n ): Promise<void> {\n try {\n const response = await fetch(`${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 if (!response.ok) {\n this.log(`[probe] outcome-event ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(\n `[probe] 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(`[probe] outcome-event ingest error: ${msg}`);\n }\n }\n\n private log(msg: string): void {\n if (this.debug) {\n // stderr only; never leak to stdout\n // eslint-disable-next-line no-console\n console.error(msg);\n }\n }\n}\n","/**\n * Sight SDK (@cultured-computer/sight) shared types.\n */\n\nimport { z } from 'zod';\nimport type { PropensityInput } from '@fieldwork/shared';\n\n// ── Configuration ──────────────────────────────────────────────────────────\n\n/**\n * Signature phrases the customer authors per persona for Day-1 voice\n * consistency measurement per PROBE.md §2. The SDK edge computes matches\n * per turn (via @fieldwork/classifier signature-phrase) and includes the\n * matched slugs on the outgoing CapturedTurn.\n */\nexport const SignaturePhraseSchema = z.union([\n z.object({\n slug: z.string().min(1),\n phrase: z.string().min(1),\n description: z.string().optional(),\n }),\n z.object({\n slug: z.string().min(1),\n regex: z.string().min(1),\n flags: z.string().optional(),\n description: z.string().optional(),\n }),\n]);\nexport type SignaturePhraseInput = z.infer<typeof SignaturePhraseSchema>;\n\nexport const PersonaConfigSchema = z.object({\n /** Persona slug matching the deployment's registered persona. */\n slug: z.string().min(1),\n /**\n * RICE authorship artifact (Role, Identity, Communication, Engagement).\n * Either inline object or a path/URL to a JSON file loaded at init time.\n */\n rice: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),\n /**\n * Customer-authored signature phrases for this persona. Compiled once at\n * init and matched per turn at the SDK edge; matched slugs appear on the\n * outgoing turn as `signaturePhraseMatches`.\n */\n signaturePhrases: z.array(SignaturePhraseSchema).optional(),\n});\nexport type PersonaConfig = z.infer<typeof PersonaConfigSchema>;\n\nexport const OutcomeHookSchema = z.object({\n /** Type of outcome the deployment tracks. */\n type: z.enum(['numeric', 'categorical', 'boolean', 'duration']),\n /**\n * Callback that resolves the outcome for a completed session. Invoked by\n * Probe.endSession() with the session's externalId; a non-null result\n * lands as an outcome event on the session. Not invoked for sessions\n * swept server-side (no explicit endSession) — use emitOutcomeEvent()\n * for outcomes that become known out of band.\n */\n resolve: z.custom<(sessionId: string) => Promise<OutcomeResult | null>>(),\n});\nexport type OutcomeHook = z.infer<typeof OutcomeHookSchema>;\n\nexport type OutcomeResult = {\n outcome: string;\n type: 'numeric' | 'categorical' | 'boolean' | 'duration';\n value: string;\n};\n\nexport const ProbeConfigSchema = z.object({\n /** Unkey ingest key. Required. */\n apiKey: z.string().min(1),\n /** Deployment slug registered in the Probe backend. Required. */\n deployment: z.string().min(1),\n /** Ingest endpoint. Defaults to https://ingest.probe.io. */\n endpoint: z.string().url().default('https://ingest.probe.io'),\n /**\n * Dashboard base URL used by the one-time first-capture announcement\n * (the stderr permalink printed after the first successful send).\n * Self-hosted or staging dashboards override it the same way `endpoint`\n * is overridden.\n */\n dashboardUrl: z.string().url().default('https://field.cultured.computer/dashboard'),\n /** Persona identification. Optional at init; can be set later via identifyPersona(). */\n persona: PersonaConfigSchema.optional(),\n /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */\n outcomeHook: OutcomeHookSchema.optional(),\n /**\n * Sample rate for autocapture. 1.0 = 100% of calls captured. Lower values\n * sample deterministically so a given (turnId) always resolves identically.\n */\n sampleRate: z.number().min(0).max(1).default(1.0),\n /**\n * Debug mode: log every captured turn to stderr with a prefix. Never logs\n * the Bearer token or PII.\n */\n debug: z.boolean().default(false),\n});\nexport type ProbeConfig = z.infer<typeof ProbeConfigSchema>;\n/**\n * The shape callers pass to Probe.init(). This is the schema's INPUT type, so\n * fields with a `.default()` (endpoint, sampleRate, debug) are optional here —\n * the defaults are applied by ProbeConfigSchema.parse() inside init(). Use this\n * for the init argument; `ProbeConfig` is the resolved (post-parse) type held\n * internally, where those fields are always present.\n */\nexport type ProbeConfigInput = z.input<typeof ProbeConfigSchema>;\n\n// ── Session context (customer identifies persona per session) ──────────────\n\nexport const SessionStartSchema = z.object({\n /** Customer's session identity (opaque string; used as the correlation key). */\n externalId: z.string().min(1),\n /**\n * Customer's USER identity (opaque string), distinct from externalId:\n * externalId keys the session; externalUserId ties sessions to a\n * returning user. Forwarded on every captured turn so the worker can\n * persist it on the session row — return-with-persona-consistency and\n * prior-session metrics require it. Optional; deployments that do not\n * identify users simply skip the user-level return metrics.\n */\n externalUserId: z.string().min(1).optional(),\n /**\n * Persona slug active for this session. Overrides the init-level default.\n * Required for multi-persona deployments; optional for single-persona\n * deployments where init already carries the persona.\n */\n persona: z.string().min(1).optional(),\n /**\n * How the user got into this session (P2 per PLAN-2026-07-11).\n * Retention semantics differ radically between a resume and a fresh\n * notification landing.\n */\n openedVia: z.enum(['link', 'notification', 'resume', 'direct', 'share']).optional(),\n /**\n * Environmental context — browser / device / locale / tz (P2). Customer-\n * configurable which fields to include. See collectClientContext helper.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n /**\n * Optional customer metadata attached to the session. Forwarded with the\n * first captured turn merged into `clientContext` under the `metadata`\n * key, so it lands on sessions.probe_session_client_context.\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n /**\n * RLDS episode-level provenance (Amendment R populater 2026-07-11).\n * Powers Chapter 8e′ Card 3 version behavioral diff. All optional.\n * agentId — model/policy version\n * experimentId — A/B arm or feature flag\n * environmentConfigHash — SHA of prompt/config file(s)\n * environmentConfigLabel — human-readable version label\n */\n agentId: z.string().optional(),\n experimentId: z.string().optional(),\n environmentConfigHash: z.string().optional(),\n environmentConfigLabel: z.string().optional(),\n});\nexport type SessionStart = z.infer<typeof SessionStartSchema>;\n\n/**\n * Session end input (P2). Sent by Probe.endSession() so the worker records\n * why a session ended.\n */\nexport const SessionEndSchema = z.object({\n externalId: z.string().min(1),\n endedReason: z\n .enum(['natural', 'user_closed', 'timeout', 'agent_error', 'user_flagged', 'crashed'])\n .optional(),\n});\nexport type SessionEndInput = z.infer<typeof SessionEndSchema>;\n\n// ── Turn payload sent to ingest ────────────────────────────────────────────\n\nexport type CapturedTurn = {\n deploymentSlug: string;\n sessionExternalId: string;\n /**\n * Customer's user identity. Forwarded by captureTurn from the session\n * state (Probe.startSession({ externalUserId })); the worker persists it\n * on sessions.external_user_id at first-turn session create. Never\n * defaulted to sessionExternalId — that key identifies the session.\n */\n externalUserId?: string;\n turnIndex: number;\n /**\n * Persona slug active for this turn. Resolved by the SDK from (in order):\n * turn-level override, session-level from startSession(), init-level default.\n */\n personaSlug?: string;\n /**\n * Signature-phrase slugs matched at the SDK edge (computed from the\n * customer's signaturePhrases config at init). Empty array or omitted when\n * no signatures matched or none were registered.\n */\n signaturePhraseMatches?: string[];\n /**\n * Interpretive record fields passed through from a customer harness\n * (Oracle read hook wired). See PROBE.md §2. Populated only if the customer\n * runs the Cultured Computer harness pattern; null for non-harness deployments.\n */\n interpretive?: {\n situationType?: string[];\n read?: string;\n lensChosen?: string;\n reactionRegister?: string;\n reactionNextTurn?: string;\n };\n /**\n * User-side input for this turn (P1 per PLAN-2026-07-11). What the human\n * said + UI-level interactivity signals. Text is Presidio-scrubbed\n * server-side before landing on probe_user_reply_text.\n */\n userInput?: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount?: number;\n interruptedStream?: boolean;\n cancelledResponse?: boolean;\n submittedAt?: string;\n };\n /**\n * Interactivity: agent reflect time, stream completion, multimodal events.\n */\n interactivity?: {\n agentReflectMs?: number;\n agentStreamCompleted?: boolean;\n multimodalEvents?: Array<{ kind: string; at?: string; meta?: Record<string, unknown> }>;\n };\n /**\n * User outcome signals (Ch9-promoted first-class per PLAN-2026-07-11):\n * flagged break, explicit rating (1-5), thumbs.\n *\n * `flaggedBreak` is DEPRECATED in favor of Probe.flagPersonaBreak(),\n * which carries user attribution and emits a 'break' outcome event;\n * the turn-level boolean remains accepted for wire compat only.\n */\n userOutcome?: {\n flaggedBreak?: boolean;\n explicitRating?: number;\n thumbs?: 'up' | 'down';\n };\n /**\n * Propensity + candidate set (harness-supplied; see PROBE.md §2).\n * Manual-capture callers put this in payload.propensity; captureTurn\n * validates the Amendment S contract and hoists the valid object to\n * this top-level field so the worker projection lands it on the\n * read_candidates / read_propensities / selection_meta columns.\n */\n propensity?: PropensityInput;\n /**\n * Transition signals (the human's response to the previous reply).\n * Derived by captureTurn when the previous turn's capture time and this\n * turn's user submit time are both known; may also be supplied directly\n * by manual-capture callers.\n */\n transition?: {\n timeMs?: number;\n lengthDelta?: number;\n };\n /**\n * Session context forwarded on the FIRST captured turn of a session\n * (populated by captureTurn from Probe.startSession state; the worker\n * persists both at session find-or-create). Omitted on later turns.\n */\n openedVia?: 'link' | 'notification' | 'resume' | 'direct' | 'share';\n clientContext?: Record<string, unknown>;\n /**\n * RLDS episode-level provenance (Amendment R). Forwarded from the session\n * state on every turn so downstream storage can attribute each turn to the\n * arm/version that produced it. Populated by startSession() from either\n * the customer-provided value or the init-time default; null when neither\n * is set.\n */\n agentId?: string;\n experimentId?: string;\n environmentConfigHash?: string;\n environmentConfigLabel?: string;\n payload: Record<string, unknown>;\n};\n\n// ── Persona-break flag (from Probe.flagPersonaBreak) ──────────────────────\n\nexport const FlagPersonaBreakSchema = z.object({\n sessionExternalId: z.string().min(1),\n note: z.string().optional(),\n /** Turn index the flag refers to. Omit to attach to the session's latest turn. */\n turnIndex: z.number().int().nonnegative().optional(),\n});\nexport type FlagPersonaBreakInput = z.infer<typeof FlagPersonaBreakSchema>;\n\n// ── Outcome event (Amendment I Method D, 2026-07-12) ─────────────────────\n// Customer-emitted event marking a hard outcome (break/escalation/\n// resolution/etc.) durable on the probe_outcome_events table. Universal\n// seed kinds ship out of the box; deployments may register their own\n// arbitrary string kind.\nexport const OutcomeEventEmitSchema = z.object({\n sessionExternalId: z.string().min(1),\n kind: z.string().min(1),\n /** Optional turn index this event is caused by. Omit to attach to latest turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Optional detail payload (customer-defined). */\n detail: z.record(z.string(), z.unknown()).optional(),\n});\nexport type OutcomeEventEmit = z.infer<typeof OutcomeEventEmitSchema>;\n","/**\n * Client-context capture helper (P2 per PLAN-2026-07-11).\n *\n * At session start the SDK optionally collects browser/device/locale/tz\n * metadata to send as SessionStart.clientContext. Customers control which\n * fields land via ProbeConfig.clientContextIncludes; the default is\n * conservative (locale + timezone + agent kind, no fingerprinting fields).\n *\n * Node-side calls receive process metadata; browser-side calls receive\n * navigator + Intl.DateTimeFormat. Never leaks PII; anything that could\n * fingerprint the user is opt-in.\n */\n\nexport type ClientContextIncludes = {\n /** window.navigator.userAgent — off by default (fingerprinting risk). */\n userAgent?: boolean;\n /** window.navigator.language / process.env.LANG — on by default. */\n locale?: boolean;\n /** Intl timezone / process TZ — on by default. */\n timezone?: boolean;\n /** window.screen dimensions — off by default (fingerprinting risk). */\n screen?: boolean;\n /** Node process metadata (platform, node version) — on by default in Node. */\n runtime?: boolean;\n /** Custom key/value pairs the customer wants to attach. */\n custom?: Record<string, string | number | boolean | null>;\n};\n\nconst DEFAULT_INCLUDES: ClientContextIncludes = {\n locale: true,\n timezone: true,\n runtime: true,\n};\n\n/** Collect client context under the current environment (Node or browser). */\nexport function collectClientContext(\n includes: ClientContextIncludes = DEFAULT_INCLUDES,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n\n // Browser detection without lib.dom.d.ts (SDK doesn't include DOM lib to\n // keep node-side bundles small). We accept the global as `unknown` and\n // narrow via runtime checks.\n const globalAny = globalThis as unknown as {\n window?: {\n navigator?: {\n userAgent?: string;\n language?: string;\n languages?: ReadonlyArray<string>;\n };\n screen?: { width?: number; height?: number };\n };\n };\n const win = globalAny.window;\n const isBrowser = typeof win !== 'undefined' && typeof win?.navigator !== 'undefined';\n\n if (isBrowser && win) {\n const nav = win.navigator;\n if (includes.userAgent) out['userAgent'] = nav?.userAgent;\n if (includes.locale) {\n out['locale'] = nav?.language;\n if (nav?.languages) out['languages'] = [...nav.languages];\n }\n if (includes.timezone) {\n try {\n out['timezone'] = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* ignore */\n }\n }\n if (includes.screen && win.screen) {\n out['screen'] = { width: win.screen.width, height: win.screen.height };\n }\n out['agent'] = 'browser';\n } else if (typeof process !== 'undefined' && typeof process.versions !== 'undefined') {\n if (includes.locale) {\n const lang = process.env['LANG'] || process.env['LC_ALL'] || null;\n if (lang) out['locale'] = lang.split('.')[0];\n }\n if (includes.timezone) {\n try {\n out['timezone'] = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* ignore */\n }\n }\n if (includes.runtime) {\n out['runtime'] = {\n platform: process.platform,\n node: process.versions.node,\n };\n }\n out['agent'] = 'node';\n }\n\n if (includes.custom) {\n for (const [k, v] of Object.entries(includes.custom)) out[k] = v;\n }\n\n return out;\n}\n","/**\n * Stable SHA-256 hex hashing for environment-config identity.\n *\n * Shared by the public Probe.hashEnvironmentConfig() helper and the OTel\n * processor's autocapture version-stamping (auto environmentConfigHash from\n * the request's system message). Lives in its own module so the processor\n * can import it without a circular dependency on probe.ts.\n *\n * Prefers WebCrypto (browser + modern Node); falls back to node:crypto via\n * dynamic import so the SDK stays browser-friendly for callers that never\n * touch this helper.\n */\nexport async function hashEnvironmentConfig(input: string): Promise<string> {\n if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle) {\n const bytes = new TextEncoder().encode(input);\n const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n }\n const { createHash } = await import('node:crypto');\n return createHash('sha256').update(input).digest('hex');\n}\n","/**\n * Session context propagation via OpenTelemetry Baggage.\n *\n * Adapters need to know which session an in-flight LLM call belongs to. We\n * propagate the session ID through OTel Baggage rather than a parallel\n * AsyncLocalStorage instance because:\n * 1. OTel already runs AsyncLocalStorageContextManager under the hood\n * (auto-registered by NodeTracerProvider on Node 20+); a parallel ALS\n * would duplicate the async-hooks graph.\n * 2. Baggage propagates automatically across HTTP boundaries via the\n * `baggage:` header. A parallel ALS would break at every service hop.\n *\n * Customer wraps their conversation:\n *\n * await Probe.withSession(sessionId, async () => {\n * await openai.chat.completions.create({ ... }); // captured\n * await anthropic.messages.create({ ... }); // also captured\n * });\n *\n * Under the hood: baggage entry `probe.session_id` is set, context is\n * activated for the callback, spans emitted inside read the baggage in\n * their onEnd handler.\n */\n\nimport { context, propagation } from '@opentelemetry/api';\n\nexport const SESSION_BAGGAGE_KEY = 'probe.session_id';\n\n// Register an AsyncLocalStorage-backed ContextManager idempotently on first\n// use. Without this, `context.with(...)` uses the default NoopContextManager\n// which does not propagate across async boundaries; baggage would be dropped\n// as soon as an `await` happened inside the callback.\nlet contextManagerRegistered = false;\nasync function ensureContextManager(): Promise<void> {\n if (contextManagerRegistered) return;\n contextManagerRegistered = true;\n try {\n const mod = await import('@opentelemetry/context-async-hooks');\n const cm = new mod.AsyncLocalStorageContextManager();\n cm.enable();\n context.setGlobalContextManager(cm);\n } catch {\n // The context-async-hooks package may not be installed; fall back to\n // NoopContextManager. Baggage will not propagate across async boundaries\n // in that case, which is a known limitation surfaced in debug mode by\n // the OTel processor.\n }\n}\n\n/**\n * Run `fn` inside a context where the given session ID is available to any\n * OTel span emitted (directly or transitively). Returns the fn's return value.\n */\nexport async function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n await ensureContextManager();\n const currentBaggage = propagation.getBaggage(context.active());\n const nextBaggage = (currentBaggage ?? propagation.createBaggage()).setEntry(\n SESSION_BAGGAGE_KEY,\n { value: sessionId },\n );\n const nextContext = propagation.setBaggage(context.active(), nextBaggage);\n return context.with(nextContext, fn);\n}\n\n/**\n * Read the current session ID from OTel Baggage, or undefined if no session\n * is active. Called by the OTel span processor when a captured span ends.\n */\nexport function getCurrentSessionId(): string | undefined {\n const baggage = propagation.getBaggage(context.active());\n return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;\n}\n","/**\n * Probe OTel SpanProcessor.\n *\n * Consumes spans emitted by every registered instrumentation (Traceloop's\n * OpenAI / Anthropic / LangChain adapters, Vercel AI SDK's native\n * experimental_telemetry, custom fetch wrappers for Mercury-2). Maps the\n * standard `gen_ai.*` semantic-convention attributes onto CapturedTurn\n * payload and calls Probe.captureTurn().\n *\n * Filter rule: only capture spans that are actual LLM invocations. Skip:\n * - Vercel AI SDK `invoke_agent` rollups (double-count vs child `chat`).\n * - LangChain `traceloop.span.kind === \"workflow\" | \"task\"` (chain\n * scaffolding, not LLM calls).\n * - Any span with no `gen_ai.operation.name` or `gen_ai.system` attribute.\n *\n * Deduplication: when both `@traceloop/instrumentation-langchain` and\n * `@traceloop/instrumentation-openai` fire for the same call, prefer the\n * LangChain span (kind=agent) over the raw OpenAI span, keyed by traceId.\n */\n\nimport type { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-node';\nimport type { Context } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\nimport type { CapturedTurn } from '../types.js';\nimport { getCurrentSessionId } from './session-context.js';\nimport { hashEnvironmentConfig } from '../hash.js';\n\n// ── Deduplication cache (traceId → seen) ──────────────────────────────────\n// When LangChain instrumentation fires for a call, the underlying provider\n// (OpenAI/Anthropic) fires again on the same traceId. We take the first\n// span that arrives with a valid gen_ai.operation.name and skip the rest.\n// TTL is short (5s) because trace IDs recycle over a long-lived process.\nconst DEDUP_TTL_MS = 5_000;\nconst dedupCache = new Map<string, number>();\n\nfunction shouldSkipAsDuplicate(traceId: string): boolean {\n const now = Date.now();\n const seenAt = dedupCache.get(traceId);\n if (seenAt !== undefined && now - seenAt < DEDUP_TTL_MS) {\n return true;\n }\n dedupCache.set(traceId, now);\n // Sweep expired entries opportunistically (cheap, bounded work).\n if (dedupCache.size > 1000) {\n for (const [k, v] of dedupCache) {\n if (now - v > DEDUP_TTL_MS) dedupCache.delete(k);\n }\n }\n return false;\n}\n\n// ── Attribute helpers ─────────────────────────────────────────────────────\n\ntype AttrValue = string | number | boolean | Array<string | number | boolean> | undefined;\n\nfunction attr(attrs: Record<string, AttrValue>, key: string): AttrValue {\n return attrs[key];\n}\n\nfunction asString(v: AttrValue): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction asNumber(v: AttrValue): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\nfunction asStringArray(v: AttrValue): string[] | undefined {\n return Array.isArray(v) && v.every((x) => typeof x === 'string')\n ? (v as string[])\n : undefined;\n}\n\n// ── Filter: is this span an LLM call worth capturing? ────────────────────\n\nfunction isLLMCall(attrs: Record<string, AttrValue>): boolean {\n const op = asString(attrs['gen_ai.operation.name']);\n if (op === 'chat' || op === 'text_completion' || op === 'embeddings') {\n return true;\n }\n // LangChain via Traceloop emits spans with traceloop.span.kind. Only 'agent'\n // is an actual LLM call; 'workflow' / 'task' / 'tool' are scaffolding.\n const traceloopKind = asString(attrs['traceloop.span.kind']);\n if (traceloopKind === 'agent') return true;\n return false;\n}\n\n// ── Vercel AI SDK invoke_agent rollup detection ──────────────────────────\n\nfunction isVercelAgentRollup(\n spanName: string,\n attrs: Record<string, AttrValue>,\n): boolean {\n // Vercel AI SDK emits invoke_agent {modelId} spans that roll up token\n // usage across the child chat spans. Both spans have gen_ai.usage.*,\n // so we skip the rollup and keep the child chat span(s).\n return spanName.startsWith('invoke_agent ') && attrs['ai.telemetry.functionId'] !== undefined;\n}\n\n// ── Provider tagging (Mercury-2 via OpenAI-compat) ───────────────────────\n\nfunction taggedProvider(attrs: Record<string, AttrValue>): string | undefined {\n const rawProvider = asString(attrs['gen_ai.system'] ?? attrs['gen_ai.provider']);\n const model = asString(attrs['gen_ai.request.model']);\n // Mercury-2 goes through the OpenAI SDK with baseURL override; retag when\n // the model name signals Inception Labs.\n if (model?.toLowerCase().startsWith('mercury')) {\n return 'inception';\n }\n return rawProvider;\n}\n\n// ── Span → CapturedTurn.payload builder ──────────────────────────────────\n\nfunction buildPayload(span: ReadableSpan): Record<string, unknown> {\n const a = span.attributes as Record<string, AttrValue>;\n\n // Latency in ms from hrtime tuples.\n const start = span.startTime[0] * 1000 + span.startTime[1] / 1_000_000;\n const end = span.endTime[0] * 1000 + span.endTime[1] / 1_000_000;\n const latencyMs = Math.max(0, Math.round(end - start));\n\n // Response text: prefer ai.response.text (Vercel AI SDK) if present, then\n // fall back to gen_ai.output.messages (standard).\n const responseText =\n asString(attr(a, 'ai.response.text')) ?? asString(attr(a, 'gen_ai.output.messages'));\n\n // Tool calls: count and names.\n const toolCallNames = asStringArray(attr(a, 'gen_ai.response.tool_names'));\n const toolCallsCount =\n asNumber(attr(a, 'gen_ai.response.tool_calls_count')) ?? toolCallNames?.length;\n\n // Finish reason: gen_ai.response.finish_reasons is an array; take the first.\n const finishReasons = asStringArray(attr(a, 'gen_ai.response.finish_reasons'));\n const finishReason = finishReasons?.[0];\n\n // Error: OTel spans use span.status.code = ERROR when the call failed.\n // Message is in span.status.message.\n const error =\n span.status.code === 2 // SpanStatusCode.ERROR\n ? span.status.message ?? 'error'\n : undefined;\n\n return {\n // Plumbing (probe_* namespace lands on canonical turns columns per PROBE.md §2).\n probe_tokens_input: asNumber(attr(a, 'gen_ai.usage.input_tokens')),\n probe_tokens_output: asNumber(attr(a, 'gen_ai.usage.output_tokens')),\n probe_latency_ms: latencyMs,\n probe_model: asString(attr(a, 'gen_ai.response.model') ?? attr(a, 'gen_ai.request.model')),\n probe_provider: taggedProvider(a),\n probe_tool_calls: toolCallsCount,\n probe_tool_names: toolCallNames,\n probe_error: error,\n probe_finish_reason: finishReason,\n // Response text so the SDK edge signature-phrase matcher has something to\n // match against; the server-side redactor scrubs PII on the Tier 1 →\n // Tier 2 boundary.\n response: responseText ? { text: responseText } : undefined,\n // Anthropic cache tokens (per research report), promoted so the customer\n // can see cache-hit-rate in the dashboard without re-parsing raw messages.\n probe_cache_read_input_tokens: asNumber(attr(a, 'gen_ai.usage.cache_read_input_tokens')),\n probe_cache_creation_input_tokens: asNumber(\n attr(a, 'gen_ai.usage.cache_creation_input_tokens'),\n ),\n // Debug metadata (kept in payload, not projected to canonical columns).\n _otel: {\n spanName: span.name,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n operationName: asString(attr(a, 'gen_ai.operation.name')),\n traceloopKind: asString(attr(a, 'traceloop.span.kind')),\n },\n };\n}\n\n// ── System-prompt extraction (auto version-hash, 2026-07-14) ─────────────\n// Autocapture sees the request messages on the span. When a system message\n// is present and the deployer never set an environmentConfigHash on the\n// session, the session state is stamped with the SHA-256 of the system\n// prompt text plus an 'auto:xxxxxxxx' label — closing the version-diff\n// measurement with zero deployer work. Explicit startSession values always\n// win; nothing is logged or announced.\n\ntype MinimalSession = {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n};\n\n/** Join the text content of one message shape into a single string. */\nfunction messageText(content: unknown): string | undefined {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n const parts: string[] = [];\n for (const part of content) {\n if (typeof part === 'string') {\n parts.push(part);\n } else if (part && typeof part === 'object') {\n const p = part as Record<string, unknown>;\n // OTel gen_ai parts use {type:'text', content}; Vercel AI SDK and\n // provider SDKs use {type:'text', text}.\n const text = p['content'] ?? p['text'];\n if (typeof text === 'string') parts.push(text);\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n return undefined;\n}\n\n/** First system-role message text from a JSON-encoded message array. */\nfunction systemFromMessagesJson(raw: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return undefined;\n for (const msg of parsed) {\n if (msg && typeof msg === 'object') {\n const m = msg as Record<string, unknown>;\n if (m['role'] === 'system') {\n const text = messageText(m['content'] ?? m['parts']);\n if (text) return text;\n }\n }\n }\n } catch {\n // Not JSON — nothing to extract.\n }\n return undefined;\n}\n\n/**\n * Best-effort extraction of the request's system message text from span\n * attributes, across the conventions the registered instrumentations emit:\n * - `gen_ai.system_instructions` (OTel gen_ai semconv; string or JSON parts)\n * - `gen_ai.input.messages` (OTel gen_ai semconv; JSON message array)\n * - `gen_ai.prompt.{n}.role` / `.content` (Traceloop indexed convention)\n * - `ai.prompt.messages` / `ai.prompt` (Vercel AI SDK telemetry)\n * Returns undefined when no system message is present.\n */\nfunction extractSystemPromptText(attrs: Record<string, AttrValue>): string | undefined {\n // OTel semconv: dedicated system-instructions attribute.\n const instructions = attrs['gen_ai.system_instructions'];\n if (typeof instructions === 'string' && instructions.length > 0) {\n // May be plain text or a JSON parts array.\n try {\n const parsed: unknown = JSON.parse(instructions);\n const text = messageText(parsed);\n if (text) return text;\n } catch {\n return instructions;\n }\n return instructions;\n }\n\n // OTel semconv: full input message array as JSON.\n const inputMessages = asString(attrs['gen_ai.input.messages']);\n if (inputMessages) {\n const text = systemFromMessagesJson(inputMessages);\n if (text) return text;\n }\n\n // Traceloop: indexed prompt attributes (gen_ai.prompt.0.role, .content).\n for (let i = 0; ; i++) {\n const role = attrs[`gen_ai.prompt.${i}.role`];\n if (role === undefined) break;\n if (role === 'system') {\n const content = asString(attrs[`gen_ai.prompt.${i}.content`]);\n if (content) return content;\n }\n }\n\n // Vercel AI SDK: ai.prompt.messages (JSON CoreMessage array).\n const aiMessages = asString(attrs['ai.prompt.messages']);\n if (aiMessages) {\n const text = systemFromMessagesJson(aiMessages);\n if (text) return text;\n }\n\n // Vercel AI SDK: ai.prompt ({system, prompt/messages} as JSON).\n const aiPrompt = asString(attrs['ai.prompt']);\n if (aiPrompt) {\n try {\n const parsed: unknown = JSON.parse(aiPrompt);\n if (parsed && typeof parsed === 'object') {\n const system = (parsed as Record<string, unknown>)['system'];\n if (typeof system === 'string' && system.length > 0) return system;\n }\n } catch {\n // Not JSON — nothing to extract.\n }\n }\n\n return undefined;\n}\n\n/**\n * Stamp the session with the system prompt's hash when the deployer set no\n * environmentConfigHash. Awaited by onEnd BEFORE the capture is sent, so\n * captureTurn forwards the stamped values on this same turn. Re-checks\n * after the async hash so a concurrent explicit startSession always wins.\n */\nasync function maybeAutoStampEnvironmentConfig(\n session: MinimalSession,\n attrs: Record<string, AttrValue>,\n): Promise<void> {\n if (session.environmentConfigHash != null) return; // explicit or already stamped\n const systemText = extractSystemPromptText(attrs);\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\nfunction 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 state.sessions.set(sessionId, session);\n }\n const turnIndex = session.turnIndex;\n session.turnIndex += 1;\n return {\n session,\n sessionExternalId: sessionId,\n turnIndex,\n personaSlug: session.personaSlug ?? state.persona?.slug ?? null,\n };\n}\n\n// ── The processor ─────────────────────────────────────────────────────────\n\nexport class ProbeSpanProcessor implements SpanProcessor {\n constructor(\n private state: MinimalProbeState,\n private captureFn: (turn: CapturedTurn) => Promise<void>,\n ) {}\n\n onStart(_span: Span, _parentContext: Context): void {\n // No-op. All work happens in onEnd once all attributes are populated.\n }\n\n onEnd(span: ReadableSpan): void {\n try {\n const a = span.attributes as Record<string, AttrValue>;\n if (isVercelAgentRollup(span.name, a)) return;\n if (!isLLMCall(a)) return;\n\n const traceId = span.spanContext().traceId;\n if (shouldSkipAsDuplicate(traceId)) return;\n\n const sessionId = getCurrentSessionId();\n if (!sessionId) {\n if (this.state.config.debug) {\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`,\n );\n }\n return;\n }\n\n const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(\n this.state,\n sessionId,\n );\n\n const captured: CapturedTurn = {\n deploymentSlug: this.state.config.deployment,\n sessionExternalId,\n turnIndex,\n personaSlug: personaSlug ?? undefined,\n payload: buildPayload(span),\n };\n\n // Fire-and-log; SDK client swallows send errors. The auto version\n // stamp is awaited BEFORE the capture so the session-held\n // environmentConfigHash rides this same turn.\n (async () => {\n await maybeAutoStampEnvironmentConfig(session, a);\n await this.captureFn(captured);\n })().catch((err) => {\n if (this.state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`,\n );\n }\n });\n } catch (err) {\n if (this.state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n shutdown(): Promise<void> {\n dedupCache.clear();\n return Promise.resolve();\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n// ── Exported helpers for tests ────────────────────────────────────────────\nexport const _internals = {\n isLLMCall,\n isVercelAgentRollup,\n taggedProvider,\n buildPayload,\n shouldSkipAsDuplicate,\n dedupCache,\n extractSystemPromptText,\n maybeAutoStampEnvironmentConfig,\n};\n","/**\n * OTel provider setup.\n *\n * Registers a NodeTracerProvider with the ProbeSpanProcessor. Called once at\n * Probe.init() before any instrumentation is enabled.\n *\n * If the customer has already registered an OTel provider (e.g. Sentry, DD,\n * or their own), we do NOT overwrite it — instead we add our SpanProcessor\n * to the existing provider. This preserves customer observability.\n *\n * Trade-off: if the customer's provider does not expose addSpanProcessor\n * (older versions), we register our own NodeTracerProvider; OTel keeps the\n * first-registered global, so capture may not attach in that case. Chapter\n * 2 ships the pattern; hardening for edge cases lands with the first\n * enterprise customer.\n */\n\nimport { trace } from '@opentelemetry/api';\nimport { ProbeSpanProcessor } from './otel-processor.js';\nimport type { CapturedTurn } from '../types.js';\n\ntype MinimalProbeState = {\n config: { deployment: string; debug: boolean };\n persona: { slug: string } | null;\n sessions: Map<\n string,\n {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n // Auto version-hash stamping target (see otel-processor.ts).\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n }\n >;\n signatureMatchers: Map<string, unknown>;\n};\n\nlet installedProcessor: ProbeSpanProcessor | null = null;\n\nexport function setupOtelProvider(\n state: MinimalProbeState,\n captureFn: (turn: CapturedTurn) => Promise<void>,\n): void {\n if (installedProcessor !== null) {\n // Already set up.\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 * OpenAI instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-openai. Its spans flow through the\n * globally-registered ProbeSpanProcessor (see ./setup.ts and ./otel-processor.ts).\n *\n * Config: traceContent + enrichTokens on (customer wanting no-content mode\n * can flip Probe.init({ debug: false, sampleRate: 0 }) or override via\n * environment variable OTEL_INSTRUMENTATION_OPENAI_TRACE_CONTENT=false).\n *\n * This adapter also handles Mercury-2 via OpenAI SDK baseURL override; the\n * ProbeSpanProcessor tags `provider=inception` when gen_ai.request.model\n * starts with 'mercury'. Customers using Inception need no separate adapter.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerOpenAI(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-openai');\n instrumentation = new mod.OpenAIInstrumentation({\n enrichTokens: true,\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(`[probe/openai] instrumentation not enabled (${msg}); library not installed?`);\n }\n }\n}\n\nexport function unregisterOpenAI(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * Anthropic instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-anthropic. Cache-token attributes\n * (gen_ai.usage.cache_read_input_tokens, cache_creation_input_tokens) are\n * promoted onto the CapturedTurn payload by the shared processor.\n *\n * Anthropic finish reasons preserve their raw shape ('end_turn',\n * 'max_tokens', 'stop_sequence', 'tool_use') rather than being normalised to\n * OpenAI-style 'stop' / 'length'. Downstream analytics can pattern-match on\n * the raw value.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerAnthropic(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-anthropic');\n instrumentation = new mod.AnthropicInstrumentation({\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/anthropic] instrumentation not enabled (${msg}); library not installed?`,\n );\n }\n }\n}\n\nexport function unregisterAnthropic(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * LangChain instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-langchain. The shared ProbeSpanProcessor\n * filters LangChain spans by `traceloop.span.kind === \"agent\"` (actual LLM\n * calls; skips 'workflow' / 'task' chain scaffolding and 'tool' invocations).\n *\n * Double-instrumentation note: when a LangChain chain calls into OpenAI or\n * Anthropic, BOTH the langchain instrumentation and the provider\n * instrumentation fire on the same traceId. The ProbeSpanProcessor's dedup\n * cache (keyed on traceId with 5s TTL) drops the second one so we never\n * double-capture a turn.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerLangChain(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-langchain');\n instrumentation = new mod.LangChainInstrumentation({\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/langchain] instrumentation not enabled (${msg}); library not installed?`,\n );\n }\n }\n}\n\nexport function unregisterLangChain(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * LangGraph instrumentation adapter.\n *\n * LangGraph reuses LangChain callbacks, so @traceloop/instrumentation-langchain\n * already fires for LangGraph nodes. The catch: Traceloop tags them as generic\n * `traceloop.span.kind: \"task\"` without graph topology hints (node id, thread,\n * edges). Customers who want the Structure-axis flow-state metrics (F1-F5\n * conformance from ml-benchmark) to work with LangGraph need to pass the\n * node/thread identity into their RunnableConfig.\n *\n * This adapter itself is a no-op registration: the actual span emission is\n * covered by ./langchain.ts (Traceloop's callback handler). The value we add\n * here is DOCUMENTATION of the tag pattern (below) plus a marker that\n * LangGraph coverage is active.\n *\n * Recommended customer pattern (documented in packages/sdk/README.md):\n *\n * await graph.invoke(state, {\n * configurable: { thread_id: sessionId },\n * tags: ['langgraph', 'node:planner', 'thread:' + sessionId],\n * });\n *\n * The `tags` array surfaces as span attribute `traceloop.association.properties.tags`\n * which lands on the CapturedTurn.payload._otel debug block. Chapter 5 flow-\n * state calibration can pattern-match on the 'node:*' prefix.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerLangGraph(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology',\n );\n }\n}\n\nexport function unregisterLangGraph(): void {\n registered = false;\n}\n","/**\n * Vercel AI SDK adapter.\n *\n * Vercel AI SDK emits OTel spans natively when `experimental_telemetry` is\n * enabled on the call. No library to install, no monkey-patching. The\n * ProbeSpanProcessor already listens to every span emitted through the\n * global TracerProvider, so this adapter just documents the customer\n * activation pattern.\n *\n * Customer wires per-call:\n *\n * import { generateText } from 'ai';\n * import { openai } from '@ai-sdk/openai';\n *\n * await Probe.withSession(sessionId, async () => {\n * const { text } = await generateText({\n * model: openai('gpt-5'),\n * prompt: 'Explain the plan',\n * experimental_telemetry: {\n * isEnabled: true,\n * functionId: 'plan-explanation',\n * recordInputs: true,\n * recordOutputs: true,\n * },\n * });\n * });\n *\n * The processor filters the noisy `invoke_agent {modelId}` rollup and\n * keeps only the child `chat {modelId}` spans (which are the actual LLM\n * calls). Sub-`execute_tool` spans attach to their parent chat span via\n * traceId; the dedup cache keeps us from double-capturing.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerVercelAI(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/vercel-ai] active; customer must set experimental_telemetry: { isEnabled: true } per call',\n );\n }\n}\n\nexport function unregisterVercelAI(): void {\n registered = false;\n}\n","/**\n * LiteLLM adapter (deferred to Chapter 4 URL-swap proxy).\n *\n * LiteLLM is Python. The Probe SDK is TypeScript. Bridging them by hosting an\n * OTLP collector in the SDK is 500+ lines of code that duplicates real OTel\n * collectors and makes the SDK stateful and network-listening. Not the right\n * shape for a research lab shipping a research instrument.\n *\n * The pragmatic 2026 path: LiteLLM customers configure `api_base` to the\n * Probe URL-swap proxy (Chapter 4). Same wire format, capture happens\n * server-side on the proxy, done. Customers who already run an OTLP\n * pipeline can point their exporter at the Probe collector as an add-on;\n * that lands with Chapter 6 self-host.\n *\n * This adapter registration is a no-op stub with a debug-mode warning so\n * customers who imported the SDK explicitly know why LiteLLM is not\n * captured on the SDK side. Chapter 4 documents the proxy configuration.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerLiteLLM(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/litellm] not captured on SDK side; use the Chapter 4 URL-swap proxy for LiteLLM traffic',\n );\n }\n}\n\nexport function unregisterLiteLLM(): void {\n registered = false;\n}\n","/**\n * Mercury-2 adapter (Inception Labs, diffusion-class API).\n *\n * 99% of customer traffic to Mercury-2 goes through the OpenAI SDK with\n * `baseURL: 'https://api.inceptionlabs.ai/v1'`, which means\n * @traceloop/instrumentation-openai already captures every call and the\n * ProbeSpanProcessor tags `provider=inception` when\n * `gen_ai.request.model` starts with 'mercury'. No dedicated adapter needed\n * for that path.\n *\n * Fallback: for customers using a hand-rolled fetch call to the Inception\n * endpoint (rare), this adapter installs a fetch wrapper that emits an OTel\n * span for the request so the shared processor picks it up. Registered only\n * when Probe.init() is called with { instrumentation: { mercuryFetchWrapper:\n * true } } (opt-in; the default OpenAI SDK path covers everything).\n *\n * We do NOT ship a bespoke Mercury client. The maintenance cost of a\n * provider-specific wrapper for a single provider is not worth it when the\n * OpenAI-SDK path covers 99% of usage.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\nlet originalFetch: typeof globalThis.fetch | null = null;\n\nconst INCEPTION_HOSTS = ['api.inceptionlabs.ai', 'api.inception.ai'];\n\nfunction isInceptionUrl(url: string): boolean {\n return INCEPTION_HOSTS.some((h) => url.includes(h));\n}\n\nexport async function registerMercury(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route',\n );\n }\n}\n\n/**\n * Optional fetch monkey-patch for hand-rolled fetch calls to Inception.\n * Called only if the customer opts in explicitly (rare).\n */\nexport function enableMercuryFetchWrapper(state: ProbeState): void {\n if (originalFetch) return;\n originalFetch = globalThis.fetch;\n\n globalThis.fetch = async (input: string | URL | Request, init?: RequestInit) => {\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : input.url;\n if (!isInceptionUrl(url)) {\n return originalFetch!(input, init);\n }\n\n // Emit an OTel span so the shared processor picks it up.\n const { trace, SpanStatusCode } = await import('@opentelemetry/api');\n const tracer = trace.getTracer('@fieldwork/sdk/mercury');\n return tracer.startActiveSpan(`chat mercury-2`, async (span) => {\n span.setAttribute('gen_ai.system', 'inception');\n span.setAttribute('gen_ai.operation.name', 'chat');\n span.setAttribute('gen_ai.request.model', 'mercury-2');\n try {\n const response = await originalFetch!(input, init);\n if (!response.ok) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });\n }\n return response;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n throw err;\n } finally {\n span.end();\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(`[probe/mercury] captured fetch to ${url}`);\n }\n }\n });\n };\n}\n\nexport function unregisterMercury(): void {\n if (originalFetch) {\n globalThis.fetch = originalFetch;\n originalFetch = null;\n }\n registered = false;\n}\n","/**\n * Instrumentation registry.\n *\n * Each adapter enables its target library's OTel instrumentation (or, for\n * Vercel AI SDK / Mercury-2, documents / opts into the customer wiring).\n * All emitted spans flow through the shared ProbeSpanProcessor which maps\n * gen_ai.* semantic-convention attributes to CapturedTurn.payload and calls\n * Probe.captureTurn().\n *\n * Session correlation: OTel Baggage via session-context.ts. Customers wrap\n * their conversation in Probe.withSession(sessionId, async () => { ... }).\n * Adapters do not need to know about sessions; the processor reads baggage\n * on span end.\n */\n\nimport type { CapturedTurn } from '../types.js';\nimport { setupOtelProvider } from './setup.js';\nimport { 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 } from './setup.js';\nexport { ProbeSpanProcessor } from './otel-processor.js';\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<\n string,\n {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n // Auto version-hash stamping target (see otel-processor.ts).\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n }\n >;\n signatureMatchers: Map<string, unknown>;\n};\n\n/**\n * Register all instrumentation adapters at Probe.init() time.\n *\n * 1. Set up the OTel provider + ProbeSpanProcessor (once per process).\n * 2. Enable each adapter's instrumentation. Adapters no-op if the target\n * library is not installed in the customer's process.\n */\nexport function registerAllInstrumentations(\n state: ProbeState,\n captureFn: (turn: CapturedTurn) => Promise<void>,\n): void {\n setupOtelProvider(state, captureFn);\n\n const registrations: Array<Promise<void>> = [\n registerOpenAI(state),\n registerAnthropic(state),\n registerLangChain(state),\n registerLangGraph(state),\n registerVercelAI(state),\n registerLiteLLM(state),\n registerMercury(state),\n ];\n\n Promise.allSettled(registrations).then((results) => {\n if (!state.config.debug) return;\n for (const result of results) {\n if (result.status === 'rejected') {\n // eslint-disable-next-line no-console\n console.error(`[probe] adapter register rejected: ${result.reason}`);\n }\n }\n });\n}\n","/**\n * Signature-phrase matcher.\n *\n * Per-persona regex matching for voice consistency (Day 1 per PROBE.md §2).\n * Customer authors signature phrases at Probe.init({ persona: { signaturePhrases: [...] } }).\n * The SDK edge or a worker computes matches per turn and includes the list\n * of matched slugs in the turn payload.\n *\n * Signature phrase shape: { slug, pattern, description? }. The pattern is\n * either a plain string (case-insensitive whole-token match) or a regex\n * source string with optional flags. Slug is what appears in the matches\n * array; it is not the pattern.\n *\n * Trivial by design. Voice consistency at the embedding level lives in the\n * Chapter 5 Dream column (PSV representation with per-deployment STEL\n * calibration); this is the Day-1 heuristic that ships from ingest data alone.\n */\n\nexport type SignaturePhrase =\n | {\n /** Slug that appears in the matches array. Unique per persona. */\n slug: string;\n /** Plain-text phrase; matched case-insensitive with word boundaries. */\n phrase: string;\n description?: string;\n }\n | {\n slug: string;\n /** Regex source string. Compiled once per matcher construction. */\n regex: string;\n /** Regex flags (default: 'i'). */\n flags?: string;\n description?: string;\n };\n\ntype CompiledPhrase = {\n slug: string;\n pattern: RegExp;\n};\n\n/**\n * Compile a set of signature phrases into a matcher. Compile once at\n * Probe.init() and reuse per turn to avoid regex construction on every call.\n *\n * Invalid regex patterns are dropped with a stderr warning; other phrases\n * continue to match.\n */\nexport function compileSignaturePhrases(phrases: SignaturePhrase[]): CompiledPhrase[] {\n const compiled: CompiledPhrase[] = [];\n for (const p of phrases) {\n try {\n if ('phrase' in p) {\n const escaped = p.phrase.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // Only add \\b anchors where the phrase edge is a word character.\n // Otherwise \\b would require an impossible boundary next to punctuation.\n const startAnchor = /^\\w/.test(p.phrase) ? '\\\\b' : '';\n const endAnchor = /\\w$/.test(p.phrase) ? '\\\\b' : '';\n compiled.push({\n slug: p.slug,\n pattern: new RegExp(`${startAnchor}${escaped}${endAnchor}`, 'i'),\n });\n } else {\n compiled.push({\n slug: p.slug,\n pattern: new RegExp(p.regex, p.flags ?? 'i'),\n });\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(`[classifier/signature-phrase] invalid pattern for slug=${p.slug}: ${msg}`);\n }\n }\n return compiled;\n}\n\n/**\n * Match a text against a compiled signature-phrase set. Returns the list of\n * matched slugs (unique, in the order the phrases were compiled).\n *\n * Empty text or empty compiled set returns [].\n */\nexport function matchSignaturePhrases(\n text: string,\n compiled: CompiledPhrase[],\n): string[] {\n if (!text || compiled.length === 0) return [];\n const matches: string[] = [];\n for (const c of compiled) {\n if (c.pattern.test(text)) matches.push(c.slug);\n }\n return matches;\n}\n","/**\n * Shared types and constants across ingest, dashboard, and future SDK.\n * Keep this package small; anything domain-specific belongs in @fieldwork/db\n * or its own package.\n */\n\nimport { z } from 'zod';\n\n// ── Situation vocabulary (OPEN) ───────────────────────────────────────────\n// Situation-type is open-vocabulary. The Day-1 heuristic emits a general\n// dialogue-act seed; a deployment discovers its own situation types by\n// clustering across sessions, and a harness can pass any tag it authors.\n// The arrays below are SEEDS, not a closed enum — the situation column is\n// text[] and ingest accepts any string tag.\n\n// Domain-general dialogue-act seed (the default classifier vocabulary; fits\n// support, assistants, and any conversational deployment).\nexport const GENERAL_SITUATION_TAGS = [\n 'question',\n 'request',\n 'inform',\n 'correction',\n 'confirmation',\n 'escalation',\n 'closing',\n 'smalltalk',\n] as const;\n\n// Narrative pack (companion / roleplay), opt-in — the field-derived types.\nexport const NARRATIVE_SITUATION_TAGS = [\n 'status_power_shift',\n 'deception_concealment',\n 'dramatic_irony',\n 'reveal_recognition',\n 'betrayal_broken_trust',\n 'reconciliation_repair',\n 'moral_dilemma_subtext',\n 'comedic_incongruity',\n] as const;\n\n// Situation tags are open strings; the arrays above are seeds, not an enum.\nexport type SituationTag = string;\n\n// Back-compat aliases (the narrative pack keeps the historical names).\nexport const SITUATION_TYPES = NARRATIVE_SITUATION_TAGS;\nexport type SituationType = (typeof NARRATIVE_SITUATION_TAGS)[number];\n\n// ── Reaction register from Vincent's harness ──────────────────────────────\nexport const REACTION_REGISTERS = ['heavy', 'comic', 'edge'] as const;\nexport type ReactionRegister = (typeof REACTION_REGISTERS)[number];\n\n// ── Outcome type per probe.md §2 ──────────────────────────────────────────\nexport const OUTCOME_TYPES = ['numeric', 'categorical', 'boolean', 'duration'] as const;\nexport type OutcomeType = (typeof OUTCOME_TYPES)[number];\n\n// ── Interpretive fields the SDK may pass through from a harness ────────────\n// Customer running the Cultured Computer harness pattern or wiring the\n// Oracle read hook can populate these at the SDK edge; ingest passes them\n// through to canonical turns. When absent, the async classifier workers\n// (packages/classifier) populate situation_type and reaction_register from\n// Tier 1 records; lens_chosen stays null for non-harness deployments.\nexport const InterpretiveRecordSchema = z.object({\n // Open vocabulary: any string tag. Seeds live in GENERAL_SITUATION_TAGS /\n // NARRATIVE_SITUATION_TAGS but ingest never rejects an unseen situation.\n situationType: z.array(z.string()).optional(),\n read: z.string().optional(),\n lensChosen: z.string().optional(),\n reactionRegister: z.enum(REACTION_REGISTERS).optional(),\n reactionNextTurn: z.string().optional(),\n});\nexport type InterpretiveRecord = z.infer<typeof InterpretiveRecordSchema>;\n\n// ── Propensity + candidates (Day 1 harness-supplied, per PROBE.md §2) ─────\n// The one thing that cannot be backfilled: the alternative reads the harness\n// considered, the actual sampling distribution used to select among them,\n// which was selected, and (separately) raw model confidence/logprobs.\n//\n// `scores` and `propensities` are DIFFERENT things and must not be\n// conflated. Off-policy evaluation requires `propensities` — the behavior\n// policy's actual sampling probability at selection time — not scores.\n// A harness that samples with temperature/top_p and then reports raw\n// softmax(logits) as \"propensity\" will break DR estimators. `scores`\n// remains useful as a diagnostic and as input for later CI construction.\nexport const PropensitySchema = z.object({\n candidates: z.array(z.object({ label: z.string(), text: z.string().optional() })).optional(),\n /**\n * Raw model confidence / logprobs / ensemble scores per candidate.\n * Diagnostic only; NOT a propensity unless the harness confirms it is\n * the exact sampling distribution used and passes it also as\n * `propensities`.\n */\n scores: z.array(z.number()).optional(),\n /**\n * Behavior-policy sampling distribution at selection time. Must sum\n * to 1.0 (within float tolerance) if present. Load-bearing for OPE\n * (Dudík, Langford & Li 2011 for per-turn / Jiang & Li 2016 for\n * trajectory). When omitted, OPE is not possible on this turn.\n */\n propensities: z.array(z.number()).optional(),\n selectedIndex: z.number().int().nonnegative().optional(),\n /**\n * Sampling-policy metadata: temperature, top_p, top_k, seed, sampler\n * name, ensemble weights. Required for reviewers to verify that\n * `propensities` is the actual behavior distribution.\n */\n selectionMeta: z.record(z.string(), z.unknown()).optional(),\n});\nexport type PropensityInput = z.infer<typeof PropensitySchema>;\n\n/**\n * Amendment S (2026-07-14) — post-guardrail propensity contract validator.\n *\n * Saito et al. 2021 Open Bandit Pipeline (arXiv:2008.07146); Farhadi\n * field notes on OPE identification. Enforces the four bug classes at\n * the SDK edge — if a customer wants the directive/OPE half, propensity\n * logging must survive these checks.\n *\n * Bug classes:\n * 1. Deterministic decoding (temp=0) with propensity: zero support ⇒ OPE\n * undefined for any counterfactual (positivity/overlap failure).\n * 2. Missing policy version metadata: importance-weighted estimators\n * require the logging policy be identifiable.\n * 3. propensities present without summing to ~1.0: not a probability\n * distribution.\n * 4. selectionMeta absent when propensities present: reviewers cannot\n * verify that propensities is the actual behavior distribution.\n *\n * Returns { ok: true } when valid, { ok: false, reason } when contract\n * violated. Fire-and-log at SDK edge; do NOT block ingest — customers\n * without OPE ambitions still ship descriptive-half records.\n */\nexport type PropensityContractResult =\n | { ok: true }\n | { ok: false, reason: string, class: 'zero_support' | 'missing_policy_version' | 'malformed_distribution' | 'missing_selection_meta' };\n\nexport function validatePropensityContract(p: PropensityInput | undefined): PropensityContractResult {\n if (!p) return { ok: true }; // customer opted out of propensity logging — fine\n if (!p.propensities || p.propensities.length === 0) return { ok: true }; // descriptive-half only\n\n // Bug class 1: zero-support (deterministic decoding)\n const temp = p.selectionMeta?.['temperature'] as number | undefined;\n if (typeof temp === 'number' && temp === 0) {\n return {\n ok: false,\n class: 'zero_support',\n reason: 'temperature=0 with propensities logged: deterministic decoding has zero support. OPE is undefined for any counterfactual. Set temperature > 0 or omit propensities.',\n };\n }\n\n // Bug class 2: missing policy version\n const policyVersion = p.selectionMeta?.['policy_version'] as string | undefined;\n if (!policyVersion) {\n return {\n ok: false,\n class: 'missing_policy_version',\n reason: 'propensities logged without selectionMeta.policy_version. IPS/DR require the logging policy be identifiable across replays.',\n };\n }\n\n // Bug class 3: distribution doesn't sum to 1\n const sum = p.propensities.reduce((a, b) => a + b, 0);\n if (Math.abs(sum - 1.0) > 0.02) {\n return {\n ok: false,\n class: 'malformed_distribution',\n reason: `propensities sum to ${sum.toFixed(4)}, expected ~1.0. Not a probability distribution; likely raw softmax(logits). A score is not a probability.`,\n };\n }\n\n // Bug class 4: selectionMeta present but missing sampler details\n if (!p.selectionMeta) {\n return {\n ok: false,\n class: 'missing_selection_meta',\n reason: 'propensities logged without selectionMeta. Reviewers cannot verify propensities is the actual behavior distribution.',\n };\n }\n\n return { ok: true };\n}\n\n// ── Transition signals (Day 1, per PROBE.md §2) ───────────────────────────\n// The right half of the record: human's response to the reply. Cheap\n// observations the SDK captures without waiting for outcome-hook wiring.\nexport const TransitionSchema = z.object({\n timeMs: z.number().int().nonnegative().optional(),\n lengthDelta: z.number().int().optional(),\n});\nexport type TransitionInput = z.infer<typeof TransitionSchema>;\n\n// ── User-side input (P1, per PLAN-2026-07-11-p1-p2) ──────────────────────\n// What the human said + interactivity signals about how they said it.\n// The single most-important missing capture pre-2026-07-11: without user\n// text as a first-class column, the record is agent-centric. See PROBE.md\n// Amendment G (sequence primacy over classification).\nexport const UserInputSchema = z.object({\n /** The user's message text. Presidio-scrubbed server-side before landing on `probe_user_reply_text`. */\n text: z.string().optional(),\n /** Milliseconds between agent response end and user's first keystroke. Client-side UI hook, optional. */\n firstKeystrokeMs: z.number().int().nonnegative().optional(),\n /** Backspace/edit count while typing this reply. Client-side UI hook, optional. */\n editCount: z.number().int().nonnegative().optional(),\n /** Did the user submit before the agent's response finished streaming? */\n interruptedStream: z.boolean().optional(),\n /** Did the user click stop on an agent streaming response mid-flight? */\n cancelledResponse: z.boolean().optional(),\n /** ISO timestamp when the user submitted this reply. */\n submittedAt: z.string().optional(),\n});\nexport type UserInput = z.infer<typeof UserInputSchema>;\n\n// ── Interactivity (P1) — agent-side reflection + stream state ────────────\nexport const InteractivitySchema = z.object({\n /** Milliseconds between the user's submit and the next agent LLM call. */\n agentReflectMs: z.number().int().nonnegative().optional(),\n /** Did the agent's response stream finish fully (finish_reason='stop')? */\n agentStreamCompleted: z.boolean().optional(),\n /** Multimodal events observed on this turn (image upload, voice snippet, file, etc.). */\n multimodalEvents: z\n .array(\n z.object({\n kind: z.string(),\n at: z.string().optional(),\n meta: z.record(z.string(), z.unknown()).optional(),\n }),\n )\n .optional(),\n});\nexport type InteractivityInput = z.infer<typeof InteractivitySchema>;\n\n// ── User outcome signals (Ch9-promoted, first-class per PLAN-2026-07-11) ─\nexport const UserOutcomeSchema = z.object({\n /**\n * Explicit \"that didn't sound like you\" flag attached at turn level.\n * DEPRECATED: prefer Probe.flagPersonaBreak(), which routes through the\n * flags ingest path and carries user attribution + a 'break' outcome\n * event. This turn-level boolean remains accepted for wire compat but\n * new integrations should not set it.\n */\n flaggedBreak: z.boolean().optional(),\n /** Rating widget value 1-5, customer-supplied. */\n explicitRating: z.number().int().min(1).max(5).optional(),\n /** Thumbs-up / thumbs-down widget value. */\n thumbs: z.enum(['up', 'down']).optional(),\n});\nexport type UserOutcomeInput = z.infer<typeof UserOutcomeSchema>;\n\n// ── SDK ingest input schema (mirrored by apps/ingest/routes/turns.ts) ─────\nexport const TurnInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /**\n * Customer's user identity (opaque string), forwarded by the SDK from\n * Probe.startSession() state on every turn. Distinct from\n * sessionExternalId, which keys the SESSION: the worker persists this on\n * sessions.external_user_id at first-turn session create (falling back to\n * null — never to sessionExternalId) so return-with-persona-consistency\n * and prior-session metrics read a real user identity.\n */\n externalUserId: z.string().min(1).optional(),\n turnIndex: z.number().int().nonnegative(),\n /**\n * Persona slug active for this turn. Customer-supplied (from SDK persona\n * resolution: turn override / session / init default). Optional; deployments\n * with a single registered persona can omit this and the ingest worker\n * backfills from the deployment default at write time.\n */\n personaSlug: z.string().min(1).optional(),\n /**\n * Signature-phrase matches computed at the SDK edge (per PROBE.md §2).\n * List of matched signature-phrase slugs the customer registered via\n * Probe.init({ persona: { signaturePhrases: [...] } }). Empty array or\n * omitted when no signatures matched or the deployment did not register any.\n */\n signaturePhraseMatches: z.array(z.string()).optional(),\n /**\n * Interpretive record fields passed through from a customer harness\n * (Oracle read hook wired). Omitted for deployments not running the harness;\n * server-side classifier workers populate situation_type and reaction_register\n * from the raw payload instead.\n */\n interpretive: InterpretiveRecordSchema.optional(),\n /**\n * Propensity + candidate set + scores. Harness-supplied only. Substrate\n * for OPE in Chapter 5 Dream. Nearly free if the harness already computes\n * candidates + ensemble scores; cannot be backfilled from the reply alone.\n */\n propensity: PropensitySchema.optional(),\n /**\n * Transition signals (human's response to the reply). Populated when the\n * SDK observes the next user turn; may arrive on a subsequent turn ingest.\n */\n transition: TransitionSchema.optional(),\n /**\n * User-side input for this turn: what the human actually said + UI-level\n * interactivity hints. Server-side Presidio scrubs text before it lands\n * on the canonical probe_user_reply_text column. See PLAN-2026-07-11.\n */\n userInput: UserInputSchema.optional(),\n /**\n * Interactivity between agent and user for this turn: agent reflect time,\n * stream completion, multimodal events.\n */\n interactivity: InteractivitySchema.optional(),\n /**\n * Explicit user outcome signals (Ch9-promoted): flagged break, rating,\n * thumbs. Landed as first-class columns per PLAN-2026-07-11.\n */\n userOutcome: UserOutcomeSchema.optional(),\n /**\n * RLDS episode-level provenance (Amendment R populater 2026-07-11).\n * SDK forwards these from Probe.startSession() on every turn payload so\n * the worker can persist them on the sessions row at first-turn create.\n * All optional. Powers Chapter 8e′ Card 3 version behavioral diff.\n */\n agentId: z.string().optional(),\n experimentId: z.string().optional(),\n environmentConfigHash: z.string().optional(),\n environmentConfigLabel: z.string().optional(),\n /**\n * Session context riding the FIRST turn of a session (there is no\n * session-start wire route; the session row is created lazily by the\n * worker on the first turn that arrives). The SDK forwards these once\n * per session from Probe.startSession() state; the worker persists them\n * on sessions.probe_session_opened_via / probe_session_client_context\n * at session find-or-create and ignores them on later turns.\n */\n openedVia: z.enum(['link', 'notification', 'resume', 'direct', 'share']).optional(),\n /**\n * Browser / device / locale / tz environmental context, customer-\n * configurable which fields to include. Customer metadata from\n * Probe.startSession({ metadata }) is merged in by the SDK under the\n * `metadata` key so it has a durable landing place.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n payload: z.record(z.string(), z.unknown()),\n});\nexport type TurnInput = z.infer<typeof TurnInputSchema>;\n\n// ── Session lifecycle schemas (P2, per PLAN-2026-07-11) ──────────────────\n// Note: there is deliberately no SessionStartSchema here. A session-start\n// wire contract was drafted 2026-07-11 but no route ever consumed it; the\n// worker creates sessions lazily on the first ingested turn instead, and\n// session context (openedVia, clientContext) rides TurnInputSchema on that\n// first turn. Deleted rather than kept as dead surface (e2e audit\n// 2026-07-13); resurrect from git history if a dedicated route ships.\n\nexport const SessionEndSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /** Why the session ended. */\n endedReason: z\n .enum(['natural', 'user_closed', 'timeout', 'agent_error', 'user_flagged', 'crashed'])\n .optional(),\n /** ISO timestamp of session end. */\n endedAt: z.string().optional(),\n});\nexport type SessionEndInput = z.infer<typeof SessionEndSchema>;\n\n// ── SDK flag input schema (persona-break flag from Probe.flagPersonaBreak) ─\n// Populates the `user_flagged_break` outcome column in Chapter 9c. Consumer AI\n// products wire this to their in-product \"that didn't sound like you\" UX.\nexport const FlagInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n flagType: z.enum(['persona_break']),\n note: z.string().optional(),\n /**\n * Turn index the flag refers to. Optional; if omitted, the flag is\n * attached to the most recent turn of the session.\n */\n turnIndex: z.number().int().nonnegative().optional(),\n});\nexport type FlagInput = z.infer<typeof FlagInputSchema>;\n\n// ── Outcome event ingest (Amendment I Method D, 2026-07-12) ──────────────\n// Customer- or harness-emitted event marking a hard outcome. Universal seed\n// kinds ship as fallback; open-vocab lets deployments register their own.\n// Worker-side detectors also emit events without an SDK call, so this\n// schema is only the *customer-driven* portion of the outcome corpus.\nexport const OUTCOME_EVENT_KINDS_SEED = [\n 'break',\n 'escalation',\n 'resolution',\n 'abandonment',\n 'register_drift_cross',\n 'thumbs_down',\n 'thumbs_up',\n 'rating_low',\n 'rating_high',\n] as const;\nexport type OutcomeEventKindSeed = (typeof OUTCOME_EVENT_KINDS_SEED)[number];\n\n// ── Synthetic demo-data marker (2026-07-13 demo arc) ─────────────────────\n// A deployment whose classifier_config carries `synthetic: true` holds\n// generated data (the demo corpus), never customer traffic. One marker,\n// many readers: the dashboard banner + \"(demo)\" filter labels, the\n// measurement sweep's provenance stamp on probe_measurement_aggregates\n// rows, and the worker's seed_demo idempotency guard all read THIS\n// predicate rather than re-deriving the convention. Writers: the demo\n// seeding module (apps/worker/src/demo-seed.ts) and the seeder CLI\n// (scripts/seed-demo-corpus.mjs), both via the same merge helper.\nexport function isSyntheticClassifierConfig(config: unknown): boolean {\n return (\n typeof config === 'object' &&\n config !== null &&\n (config as Record<string, unknown>)['synthetic'] === true\n );\n}\n\n/**\n * DEMO_AUTOSEED feature gate, default ON in code: any value except an\n * explicit '0' / 'false' enables demo auto-seeding. Read at enqueue time\n * (dashboard onboarding) and at consume time (worker seed_demo handler)\n * through this one predicate. Pure over an env bag for unit tests.\n * Documented in docs/DEPLOY.md.\n */\nexport function demoAutoseedEnabled(\n env: Record<string, string | undefined> = typeof process !== 'undefined' ? process.env : {},\n): boolean {\n const v = env['DEMO_AUTOSEED'];\n return v !== '0' && v !== 'false';\n}\n\n// ── Demo seeding job schemas (auto-provision arc, 2026-07-13) ─────────────\n// Rides the pending_redaction queue like flag / session_end / outcome_event:\n// onboarding enqueues `_kind: 'seed_demo'` on project creation (gated by\n// DEMO_AUTOSEED, default ON); the worker consumes it, builds the\n// deterministic corpus in-process, and enqueues the corpus payloads plus a\n// trailing `_kind: 'seed_demo_backdate'` row that moves session/turn\n// timestamps onto the corpus schedule once the corpus rows have drained.\n/** Corpus window anchor offset: startDate defaults to now minus this, so\n the ~6.4-day corpus sits fully inside trailing-7-day sweep windows. */\nexport const DEMO_SEED_WINDOW_OFFSET_MS = 6.5 * 24 * 60 * 60 * 1000;\n\nexport const SeedDemoJobSchema = z.object({\n /** Slug for the demo deployment; defaults to 'demo'. */\n deploymentSlug: z.string().min(1).optional(),\n /** PRNG seed; the corpus is byte-identical per (seed, startDate). */\n seed: z.number().int().optional(),\n /**\n * ISO anchor for the corpus window (sessions land in\n * [startDate, startDate + ~6.4d]). Enqueuers stamp now-6.5d so the\n * trailing-7-day sweeps see the corpus; the worker defaults the same\n * way when absent.\n */\n startDate: z.string().optional(),\n});\nexport type SeedDemoJobInput = z.infer<typeof SeedDemoJobSchema>;\n\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\nexport const OutcomeEventInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /** Open-vocab kind label. Seeds above; customers may register any string. */\n kind: z.string().min(1),\n /** How was this event detected? Seed values below; customer sources allowed. */\n detectedBy: z\n .enum(['harness', 'sdk_flag', 'sdk_rating', 'sdk_thumbs', 'worker_detector', 'webhook', 'sdk_custom'])\n .or(z.string().min(1)),\n /** Optional turn index the event was caused by. Omitted → attaches to session's most recent turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Optional detail payload (customer-defined). */\n detail: z.record(z.string(), z.unknown()).optional(),\n /** ISO timestamp; defaults to server-side now. */\n firedAt: z.string().optional(),\n});\nexport type OutcomeEventInput = z.infer<typeof OutcomeEventInputSchema>;\n","/**\n * The Probe SDK main entry point.\n *\n * Usage:\n * import { Sight } from '@cultured-computer/sight';\n *\n * Probe.init({\n * apiKey: process.env.PROBE_API_KEY!,\n * deployment: 'alyssa-v2',\n * persona: { slug: 'alyssa' },\n * });\n *\n * // Autocapture is now on for any subsequent OpenAI / Anthropic / etc. call.\n */\n\nimport { IngestClient } from './client';\nimport {\n ProbeConfigSchema,\n SessionStartSchema,\n FlagPersonaBreakSchema,\n OutcomeEventEmitSchema,\n} from './types';\nimport type {\n ProbeConfig,\n ProbeConfigInput,\n PersonaConfig,\n OutcomeHook,\n CapturedTurn,\n SessionStart,\n SessionEndInput,\n FlagPersonaBreakInput,\n OutcomeEventEmit,\n} from './types';\nimport { collectClientContext, type ClientContextIncludes } from './client-context';\nimport { hashEnvironmentConfig } from './hash';\nimport { registerAllInstrumentations, withSession as withSessionContext } 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 type PropensityInput,\n} from '@fieldwork/shared';\n\n// ── Singleton state ────────────────────────────────────────────────────────\n\ntype ProbeState = {\n config: ProbeConfig;\n client: IngestClient;\n persona: PersonaConfig | null;\n outcomeHook: OutcomeHook | null;\n sessions: Map<string, SessionState>;\n /**\n * Signature phrases compiled once per persona at init/identify time.\n * Keyed by persona slug so per-session persona switches use the right\n * matcher without recompiling.\n */\n signatureMatchers: Map<string, ReturnType<typeof compileSignaturePhrases>>;\n /**\n * Interaction signals (userInputStart/Edit/Submit, userThumbs/userRating)\n * that arrived BEFORE any session entry existed for their externalId.\n * Flushed into the session entry when it is created (startSession or\n * lazy-create at captureTurn). FIFO-capped at PRE_SESSION_BUFFER_MAX ids\n * so signals for sessions that never capture a turn cannot leak memory.\n */\n preSessionBuffer: Map<string, PreSessionSignals>;\n};\n\ntype PreSessionSignals = {\n pendingUserInput: SessionState['pendingUserInput'];\n pendingUserOutcome: SessionState['pendingUserOutcome'];\n lastUserSubmitAt: number | null;\n};\n\n/** FIFO cap on pre-session signal buffering (distinct session ids). */\nconst PRE_SESSION_BUFFER_MAX = 100;\n\ntype SessionState = {\n externalId: string;\n /** Customer's user identity from startSession; forwarded on every turn. */\n externalUserId: string | null;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n metadata: Record<string, unknown> | null;\n openedVia: string | null;\n clientContext: Record<string, unknown> | null;\n // RLDS provenance (Amendment R populater 2026-07-11).\n agentId: string | null;\n experimentId: string | null;\n environmentConfigHash: string | null;\n environmentConfigLabel: string | null;\n /**\n * Timestamp of the last captured agent turn. Used on the NEXT turn to\n * derive transition.timeMs (previous agent reply → this turn's user\n * submit) and firstKeystrokeMs (previous agent reply → typing start).\n */\n lastAgentTurnAt: number | null;\n /**\n * Timestamp of the last userInputSubmit. Used at captureTurn to derive\n * agentReflectMs (user submit → agent turn capture). transition.timeMs\n * derives from the per-turn pendingUserInput.submittedAt instead, which\n * resets on every capture, so stale submits are never reused for it.\n */\n lastUserSubmitAt: number | null;\n /**\n * True once openedVia/clientContext have been sent with a captured turn.\n * The worker persists session context at session find-or-create (first\n * turn that arrives), so the SDK forwards it exactly once.\n */\n sessionContextForwarded: boolean;\n /** Per-turn user input pending on the SDK edge (unified capture helper). */\n pendingUserInput: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount: number;\n submittedAt?: number;\n } | null;\n /** Per-turn user outcome pending on the SDK edge (thumbs / rating). */\n pendingUserOutcome: {\n thumbs?: 'up' | 'down';\n explicitRating?: number;\n } | null;\n};\n\nlet state: ProbeState | null = null;\n\n// ── Public API ─────────────────────────────────────────────────────────────\n\nexport class Probe {\n /**\n * Initialize the Probe SDK. Call once at process start. Subsequent calls are\n * no-ops with a warning; re-init requires a shutdown() first.\n */\n static init(config: ProbeConfigInput): void {\n if (state !== null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] already initialized; call shutdown() first');\n return;\n }\n\n const validated = ProbeConfigSchema.parse(config);\n const client = new IngestClient({\n apiKey: validated.apiKey,\n endpoint: validated.endpoint,\n debug: validated.debug,\n dashboardUrl: validated.dashboardUrl,\n });\n\n state = {\n config: validated,\n client,\n persona: validated.persona ?? null,\n outcomeHook: validated.outcomeHook ?? null,\n sessions: new Map(),\n signatureMatchers: new Map(),\n preSessionBuffer: new Map(),\n };\n\n if (validated.persona?.signaturePhrases) {\n state.signatureMatchers.set(\n validated.persona.slug,\n compileSignaturePhrases(validated.persona.signaturePhrases as SignaturePhrase[]),\n );\n }\n\n registerAllInstrumentations(state, (turn) => this.captureTurn(turn));\n }\n\n /**\n * Run a callback inside a session context. Every LLM call made inside `fn`\n * (through any instrumented library: OpenAI, Anthropic, LangChain, Vercel\n * AI SDK, etc.) is automatically tagged with `sessionId` and captured as\n * a turn on that session.\n *\n * Under the hood, this uses OTel Baggage propagation; the shared span\n * processor reads the session ID from baggage when each LLM span ends.\n */\n static async withSession<T>(sessionId: string, fn: () => T | Promise<T>): Promise<T> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] withSession called before init');\n return fn();\n }\n return withSessionContext(sessionId, fn);\n }\n\n /**\n * Identify the process-level default persona. Overwrites any previously-set\n * default. For per-session persona identification (multi-persona products),\n * use startSession({ externalId, persona }) instead.\n */\n static identifyPersona(persona: PersonaConfig): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] identifyPersona called before init');\n return;\n }\n state.persona = persona;\n if (persona.signaturePhrases) {\n state.signatureMatchers.set(\n persona.slug,\n compileSignaturePhrases(persona.signaturePhrases as SignaturePhrase[]),\n );\n }\n }\n\n /**\n * Start (or update) a session with an active persona.\n *\n * Single-persona deployments can skip this if the init-level default is\n * enough; the SDK will still create a session entry lazily on first turn.\n * Multi-persona products call this at conversation start so every turn in\n * the session inherits the selected persona.\n *\n * Idempotent: calling with the same externalId updates the entry.\n */\n static startSession(input: SessionStart): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] startSession called before init');\n return;\n }\n const validated = SessionStartSchema.parse(input);\n const existing = state.sessions.get(validated.externalId);\n const now = Date.now();\n const session: SessionState = {\n externalId: validated.externalId,\n externalUserId: validated.externalUserId ?? existing?.externalUserId ?? null,\n turnIndex: existing?.turnIndex ?? 0,\n startedAt: existing?.startedAt ?? now,\n personaSlug: validated.persona ?? existing?.personaSlug ?? state.persona?.slug ?? null,\n metadata: validated.metadata ?? existing?.metadata ?? null,\n openedVia: validated.openedVia ?? existing?.openedVia ?? null,\n clientContext: validated.clientContext ?? existing?.clientContext ?? null,\n agentId: validated.agentId ?? existing?.agentId ?? null,\n experimentId: validated.experimentId ?? existing?.experimentId ?? null,\n environmentConfigHash:\n validated.environmentConfigHash ?? existing?.environmentConfigHash ?? null,\n environmentConfigLabel:\n validated.environmentConfigLabel ?? existing?.environmentConfigLabel ?? null,\n lastAgentTurnAt: existing?.lastAgentTurnAt ?? null,\n lastUserSubmitAt: existing?.lastUserSubmitAt ?? null,\n sessionContextForwarded: existing?.sessionContextForwarded ?? false,\n pendingUserInput: existing?.pendingUserInput ?? null,\n pendingUserOutcome: existing?.pendingUserOutcome ?? null,\n };\n this.flushPreSessionSignals(validated.externalId, session);\n state.sessions.set(validated.externalId, session);\n }\n\n /**\n * Move buffered pre-session interaction signals (recorded before any\n * session entry existed for this externalId) onto the session entry.\n * Session-held values win: buffered signals predate anything recorded\n * after the entry existed.\n */\n private static flushPreSessionSignals(externalId: string, session: SessionState): void {\n if (state === null) return;\n const buffered = state.preSessionBuffer.get(externalId);\n if (!buffered) return;\n state.preSessionBuffer.delete(externalId);\n session.pendingUserInput = session.pendingUserInput ?? buffered.pendingUserInput;\n session.pendingUserOutcome = session.pendingUserOutcome ?? buffered.pendingUserOutcome;\n session.lastUserSubmitAt = session.lastUserSubmitAt ?? buffered.lastUserSubmitAt;\n }\n\n /**\n * Get or create the pre-session signal buffer entry for an externalId.\n * FIFO-capped: when a new id would exceed PRE_SESSION_BUFFER_MAX, the\n * oldest id is dropped (Map preserves insertion order).\n */\n private static preSessionEntry(externalId: string): PreSessionSignals {\n // Callers check state !== null before calling.\n const buffer = state!.preSessionBuffer;\n const existing = buffer.get(externalId);\n if (existing) return existing;\n if (buffer.size >= PRE_SESSION_BUFFER_MAX) {\n const oldest = buffer.keys().next().value;\n if (oldest !== undefined) buffer.delete(oldest);\n }\n const entry: PreSessionSignals = {\n pendingUserInput: null,\n pendingUserOutcome: null,\n lastUserSubmitAt: null,\n };\n buffer.set(externalId, entry);\n return entry;\n }\n\n /**\n * Compute a stable SHA-256 hex hash of prompt/config text for use as\n * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —\n * pass the human-readable version alongside as `environmentConfigLabel`\n * for the diff table axis (a card keyed by a3f9c2… is unreadable).\n *\n * Ships as a helper because inconsistent hashing across restarts breaks\n * Chapter 8e′ Card 3 (version behavioral diff) — every customer would\n * hash their own way and version-diff would become noise.\n *\n * The same hashing (src/hash.ts) backs the OTel processor's automatic\n * version stamping: when autocapture sees a system message and the\n * deployer set no environmentConfigHash, the session is stamped with\n * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit\n * startSession values always win over the auto stamp.\n */\n static async hashEnvironmentConfig(input: string): Promise<string> {\n return hashEnvironmentConfig(input);\n }\n\n /**\n * End a session and release its in-memory entry. Optional (sessions time out\n * eventually), but recommended for long-running processes with many distinct\n * conversations. If `input.endedReason` is provided the SDK sends an end\n * event to ingest so the worker records the reason server-side.\n *\n * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`\n * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`\n * and, when it returns a non-null OutcomeResult, lands it as an outcome\n * event (kind = result.outcome, detail carries type/value). This is the\n * ONLY place the SDK invokes the hook — there are no client-side timers,\n * so sessions that are never ended explicitly are swept server-side as\n * `timeout` and receive no hook-resolved outcome; land those via\n * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:\n * a throwing or rejecting hook never breaks endSession.\n */\n static async endSession(externalId: string | SessionEndInput): Promise<void> {\n if (state === null) return;\n const externalIdStr = typeof externalId === 'string' ? externalId : externalId.externalId;\n const endedReason = typeof externalId === 'string' ? undefined : externalId.endedReason;\n if (state.outcomeHook) {\n try {\n const result = await state.outcomeHook.resolve(externalIdStr);\n // Re-check state: a shutdown() during a slow resolve drops the send.\n if (result && state !== null) {\n await this.emitOutcomeEvent({\n sessionExternalId: externalIdStr,\n kind: result.outcome,\n detail: {\n type: result.type,\n value: result.value,\n resolvedBy: 'outcome_hook',\n },\n });\n }\n } catch (err: unknown) {\n // eslint-disable-next-line no-console\n console.warn(\n '[probe] outcome hook resolve failed:',\n err instanceof Error ? err.message : err,\n );\n }\n }\n if (state === null) return;\n if (endedReason) {\n await state.client\n .sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason })\n .catch((err: unknown) => {\n // eslint-disable-next-line no-console\n console.warn('[probe] sendSessionEnd failed:', err instanceof Error ? err.message : err);\n });\n }\n state.sessions.delete(externalIdStr);\n }\n\n // ── User-side helpers (P1 per PLAN-2026-07-11) ─────────────────────────\n // These accumulate user-side signals during a turn; captureTurn folds the\n // accumulated state into TurnInput.userInput / userOutcome before send.\n // Signals that arrive before any session entry exists (typing starts\n // before startSession or the first LLM call) buffer per externalId and\n // flush into the session when it is created.\n\n /**\n * User started typing — records the first-keystroke timestamp for\n * probe_user_first_keystroke_ms derivation on captureTurn. Derivable\n * only once a previous agent turn exists; a pre-session typing start\n * buffers the pending-input entry without a firstKeystrokeMs value.\n */\n static userInputStart(externalId: string): void {\n if (state === null) return;\n const session = state.sessions.get(externalId);\n const target = session ?? this.preSessionEntry(externalId);\n const now = Date.now();\n const firstKeystrokeMs =\n session?.lastAgentTurnAt != null ? Math.max(0, now - session.lastAgentTurnAt) : undefined;\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n firstKeystrokeMs: target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs,\n };\n }\n\n /**\n * User pressed backspace / edited — increments edit_count for\n * probe_user_reply_edit_count.\n */\n static userInputEdit(externalId: string): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n editCount: (target.pendingUserInput?.editCount ?? 0) + 1,\n };\n }\n\n /**\n * User submitted their reply. Records the text (Presidio-scrubbed\n * server-side before landing on probe_user_reply_text) plus the submit\n * timestamp, which captureTurn uses to derive probe_agent_reflect_ms\n * (submit → next agent turn) and probe_transition_time_ms (previous\n * agent turn → submit).\n */\n static userInputSubmit(externalId: string, text: string): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n const now = Date.now();\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n text,\n submittedAt: now,\n };\n target.lastUserSubmitAt = now;\n }\n\n /** Attach a thumbs-up/down to the current turn. */\n static userThumbs(externalId: string, thumbs: 'up' | 'down'): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserOutcome = {\n ...(target.pendingUserOutcome ?? {}),\n thumbs,\n };\n }\n\n /** Attach an explicit 1-5 rating to the current turn. */\n static userRating(externalId: string, rating: number): void {\n if (state === null) return;\n if (rating < 1 || rating > 5 || !Number.isInteger(rating)) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserOutcome = {\n ...(target.pendingUserOutcome ?? {}),\n explicitRating: rating,\n };\n }\n\n /**\n * Helper: collect client context and pass it to startSession in one call.\n */\n static startSessionWithContext(\n input: SessionStart,\n includes?: ClientContextIncludes,\n ): void {\n this.startSession({\n ...input,\n clientContext: input.clientContext ?? collectClientContext(includes),\n });\n }\n\n /**\n * Register the outcome hook: declares the deployment's outcome type and\n * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked\n * by endSession() — explicit close is the only trigger; the SDK runs no\n * client-side timers. A non-null OutcomeResult lands as an outcome event\n * on the session. Sessions that are never ended explicitly are swept\n * server-side and never resolve through the hook; land those outcomes via\n * emitOutcomeEvent() from the place where the outcome becomes known\n * (webhook, CRM callback); it joins back by sessionExternalId.\n */\n static wireOutcomeHook(hook: OutcomeHook): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] wireOutcomeHook called before init');\n return;\n }\n state.outcomeHook = hook;\n }\n\n /**\n * Manually capture a turn. Instrumentation adapters call this internally;\n * exposed for advanced customers who want to bypass autocapture.\n *\n * Persona resolution order for the outgoing turn payload:\n * 1. turn.personaSlug (turn-level override)\n * 2. sessions[externalId].personaSlug (from startSession)\n * 3. state.persona.slug (init-level default)\n *\n * Signature-phrase matching runs at the SDK edge when the resolved persona\n * has signature phrases registered. The matched slug list is attached to\n * `turn.signaturePhraseMatches` before send.\n */\n static async captureTurn(turn: CapturedTurn): Promise<void> {\n if (state === null) {\n return;\n }\n if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {\n return;\n }\n\n // ── Amendment S (2026-07-14): post-guardrail propensity validator ──\n // If the payload includes propensity data (customer running an OPE-\n // bearing deployment), validate the contract per Saito 2021 OBP.\n // Log-and-strip on failure — descriptive-half records still ingest,\n // but the malformed propensity payload does not corrupt downstream\n // OPE. Do NOT block turn capture; the point is honest logging, not\n // customer-blocking.\n const propensity =\n turn.propensity ?? (turn.payload as { propensity?: PropensityInput }).propensity;\n let validPropensity: PropensityInput | undefined = propensity;\n if (propensity) {\n const contract = validatePropensityContract(propensity);\n if (!contract.ok) {\n // eslint-disable-next-line no-console\n console.warn(\n `[probe] Amendment S contract violation (${contract.class}): ${contract.reason}`,\n );\n // Strip malformed propensity from payload; keep the record.\n (turn.payload as { propensity?: PropensityInput }).propensity = undefined;\n validPropensity = undefined;\n }\n }\n\n const sessionPersona = state.sessions.get(turn.sessionExternalId)?.personaSlug ?? null;\n const resolvedPersona =\n turn.personaSlug ?? sessionPersona ?? state.persona?.slug ?? undefined;\n\n let signatureMatches = turn.signaturePhraseMatches;\n if (!signatureMatches && resolvedPersona) {\n 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 }\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 state.sessions.set(turn.sessionExternalId, session);\n }\n // Pre-session interaction signals (typing that started before the\n // session entry existed, including entries lazily created by the OTel\n // processor) flush here, on the turn that creates the session.\n this.flushPreSessionSignals(turn.sessionExternalId, session);\n\n let userInput: CapturedTurn['userInput'] = turn.userInput;\n let userOutcome: CapturedTurn['userOutcome'] = turn.userOutcome;\n let interactivity: CapturedTurn['interactivity'] = turn.interactivity;\n let transition: CapturedTurn['transition'] = turn.transition;\n if (session.pendingUserInput && !userInput) {\n const p = session.pendingUserInput;\n userInput = {\n text: p.text,\n firstKeystrokeMs: p.firstKeystrokeMs,\n editCount: p.editCount,\n submittedAt: p.submittedAt ? new Date(p.submittedAt).toISOString() : undefined,\n };\n }\n if (session.pendingUserOutcome && !userOutcome) {\n userOutcome = session.pendingUserOutcome;\n }\n // Agent reflect ms: time between user submit (session.lastUserSubmitAt)\n // and now (the moment we're capturing this new agent turn).\n if (!interactivity && session.lastUserSubmitAt) {\n interactivity = {\n agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt),\n };\n }\n // Transition time ms: gap between the previous agent turn's capture\n // and the user submit that led to THIS turn. Derivable only when both\n // timestamps exist: pendingUserInput.submittedAt is per-turn (reset on\n // every capture), so a submit from an earlier turn can never be\n // reused. Left unset otherwise — no guessing.\n const submittedAt = session.pendingUserInput?.submittedAt;\n if (\n !transition &&\n session.lastAgentTurnAt !== null &&\n submittedAt !== undefined &&\n submittedAt >= session.lastAgentTurnAt\n ) {\n transition = { timeMs: submittedAt - session.lastAgentTurnAt };\n }\n // Session context (openedVia / clientContext / metadata) rides the\n // first captured turn only; the worker persists it at session\n // find-or-create and ignores it on later turns. metadata merges into\n // clientContext under the `metadata` key so it lands on\n // sessions.probe_session_client_context.\n let openedVia: CapturedTurn['openedVia'];\n let clientContext: CapturedTurn['clientContext'];\n if (!session.sessionContextForwarded) {\n openedVia = (session.openedVia as CapturedTurn['openedVia']) ?? undefined;\n clientContext =\n session.clientContext || session.metadata\n ? {\n ...(session.clientContext ?? {}),\n ...(session.metadata ? { metadata: session.metadata } : {}),\n }\n : undefined;\n session.sessionContextForwarded = true;\n }\n // Reset per-turn pending state now that we've folded it.\n session.pendingUserInput = null;\n session.pendingUserOutcome = null;\n session.lastAgentTurnAt = Date.now();\n\n await state.client.sendTurn({\n ...turn,\n personaSlug: resolvedPersona,\n signaturePhraseMatches: signatureMatches,\n // User identity from the local session entry (Probe.startSession).\n // The worker persists it on sessions.external_user_id; never the\n // session key. Turn-level override wins for advanced callers.\n externalUserId: turn.externalUserId ?? session.externalUserId ?? undefined,\n userInput,\n userOutcome,\n interactivity,\n transition,\n openedVia,\n clientContext,\n // Hoist validated propensity to the top-level TurnInput field: the\n // worker projection reads input.propensity (not payload.propensity)\n // when landing read_candidates / read_propensities / selection_meta\n // columns (e2e audit 2026-07-13).\n propensity: validPropensity,\n // Forward RLDS provenance from the local session entry (populated\n // by Probe.startSession). Worker persists at first-turn session\n // create; nulls stay null. Amendment R populater 2026-07-11.\n agentId: session.agentId ?? undefined,\n experimentId: session.experimentId ?? undefined,\n environmentConfigHash: session.environmentConfigHash ?? undefined,\n environmentConfigLabel: session.environmentConfigLabel ?? undefined,\n });\n }\n\n /**\n * Emit a custom outcome event on a session. Populates probe_outcome_events\n * with the customer-supplied `kind` string (Amendment I Method D). Use for\n * customer-defined kinds like \"purchase_complete\", \"handoff_to_human\",\n * \"character_break_severe\". Universal seed kinds (break, escalation,\n * resolution, thumbs_*, rating_*) are also emitted by worker-side\n * detectors automatically — call this only when the customer has a\n * signal the worker cannot infer.\n */\n static async emitOutcomeEvent(input: OutcomeEventEmit): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] emitOutcomeEvent called before init');\n return;\n }\n const validated = OutcomeEventEmitSchema.parse(input);\n await state.client.sendOutcomeEvent(state.config.deployment, validated);\n }\n\n /**\n * Flag a persona break for a session. Wire this to the customer's in-product\n * \"that didn't sound like you\" UX. Populates the `user_flagged_break`\n * outcome column in Chapter 9c.\n *\n * If `turnIndex` is omitted, the flag attaches to the session's most\n * recent turn.\n */\n static async flagPersonaBreak(input: FlagPersonaBreakInput): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] flagPersonaBreak called before init');\n return;\n }\n const validated = FlagPersonaBreakSchema.parse(input);\n await state.client.sendFlag(state.config.deployment, validated);\n }\n\n /**\n * Best-effort extraction of the response text from a captured turn's payload\n * for signature-phrase matching. Adapters populate `payload.response.text`\n * or `payload.text` by convention; this method looks for both.\n */\n private static extractTextForMatching(payload: Record<string, unknown>): string {\n const response = payload['response'];\n if (response && typeof response === 'object') {\n const responseText = (response as Record<string, unknown>)['text'];\n if (typeof responseText === 'string') return responseText;\n }\n if (typeof payload['text'] === 'string') return payload['text'] as string;\n return '';\n }\n\n /**\n * Shut down the SDK: discards the singleton state (sessions, pending\n * user-side signals, the pre-session buffer) so init() can be called\n * again. There is no send queue to flush — every capture awaits its own\n * HTTP send — and instrumentation stays registered for the life of the\n * process. Idempotent.\n */\n static async shutdown(): Promise<void> {\n if (state === null) {\n return;\n }\n state = null;\n }\n\n // ── Internal helpers ─────────────────────────────────────────────────────\n\n /** Package-internal: instrumentation adapters read this to build turns. */\n static _getState(): ProbeState | null {\n return state;\n }\n\n private static shouldSample(sessionId: string, turnIndex: number): boolean {\n if (state === null) return false;\n const rate = state.config.sampleRate;\n if (rate >= 1.0) return true;\n if (rate <= 0.0) return false;\n // Deterministic hash so a given (sessionId, turnIndex) always resolves identically.\n // FNV-1a 32-bit for portability across runtimes.\n const key = `${sessionId}:${turnIndex}`;\n let hash = 0x811c9dc5;\n for (let i = 0; i < key.length; i++) {\n hash ^= key.charCodeAt(i);\n hash = (hash * 0x01000193) >>> 0;\n }\n return hash / 0xffffffff < rate;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/types.ts","../src/client-context.ts","../src/hash.ts","../src/instrumentation/session-context.ts","../src/instrumentation/otel-processor.ts","../src/instrumentation/setup.ts","../src/instrumentation/openai.ts","../src/instrumentation/anthropic.ts","../src/instrumentation/langchain.ts","../src/instrumentation/langgraph.ts","../src/instrumentation/vercel-ai.ts","../src/instrumentation/litellm.ts","../src/instrumentation/mercury.ts","../src/instrumentation/index.ts","../../classifier/src/signature-phrase.ts","../../shared/src/index.ts","../src/probe.ts"],"names":["state","registered","instrumentation","z"],"mappings":";;;;AAwBO,IAAM,qBAAA,GAAwB,2CAAA;AAQrC,IAAM,mBAAA,GAAsB,EAAA;AAErB,IAAM,eAAN,MAAmB;AAAA,EAChB,MAAA;AAAA,EACA,QAAA;AAAA,EACA,KAAA;AAAA,EACA,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,qBAAA,GAAwB,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQxB,kBAAA,GAAqB,KAAA;AAAA,EACrB,cAAA,GAAiB,CAAA;AAAA,EAEzB,YAAY,IAAA,EAA2B;AACrC,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/C,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,gBAAgB,IAAA,CAAK,YAAA,IAAgB,qBAAA,EAAuB,OAAA,CAAQ,OAAO,EAAE,CAAA;AAAA,EACpF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,SAAS,IAAA,EAAmC;AAChD,IAAA,IAAI;AACF,MAAA,MAAM,OAAO,MACX,KAAA,CAAM,CAAA,EAAG,IAAA,CAAK,QAAQ,CAAA,SAAA,CAAA,EAAa;AAAA,QACjC,MAAA,EAAQ,MAAA;AAAA,QACR,OAAA,EAAS;AAAA,UACP,a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;AAC3B,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,UAAA;AAC1B,IAAA,IAAI,IAAA,IAAQ,GAAK,OAAO,IAAA;AACxB,IAAA,IAAI,IAAA,IAAQ,GAAK,OAAO,KAAA;AAGxB,IAAA,MAAM,GAAA,GAAM,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,SAAS,CAAA,CAAA;AACrC,IAAA,IAAI,IAAA,GAAO,UAAA;AACX,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,QAAQ,CAAA,EAAA,EAAK;AACnC,MAAA,IAAA,IAAQ,GAAA,CAAI,WAAW,CAAC,CAAA;AACxB,MAAA,IAAA,GAAQ,OAAO,QAAA,KAAgB,CAAA;AAAA,IACjC;AACA,IAAA,OAAO,OAAO,UAAA,GAAa,IAAA;AAAA,EAC7B;AACF","file":"index.js","sourcesContent":["/**\n * HTTP client for the Probe ingest API.\n *\n * Sends captured turns to POST /v1/turns with a Bearer token. Async, fire-and-log:\n * SDK never blocks the customer's LLM path on ingest. Rate-limited sends (429)\n * are retried exactly once after Retry-After; sustained limiting drops captures.\n */\n\nimport type {\n CapturedTurn,\n FlagPersonaBreakInput,\n OutcomeEventEmit,\n SessionEndInput,\n} from './types';\n\nexport type IngestClientOptions = {\n apiKey: string;\n endpoint: string;\n debug: boolean;\n /** Dashboard base URL for the one-time first-capture announcement. */\n dashboardUrl?: string;\n};\n\n/** Default dashboard base for the first-capture permalink. */\nexport const DEFAULT_DASHBOARD_URL = 'https://field.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\nexport class IngestClient {\n private apiKey: string;\n private endpoint: string;\n private debug: boolean;\n private dashboardUrl: string;\n /**\n * First-trace permalink ritual (PLAN-2026-07-14-adoptions A1): the first\n * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,\n * then never again for the life of this client (one IngestClient per\n * process — one `init` per process; a restart prints once more, accepted).\n * Failed sends do not consume the announcement. Only sendTurn announces:\n * flags, outcome events, and session-end sends never trigger it (a flag\n * arriving before any turn is not a captured session).\n */\n private firstCaptureAnnounced = false;\n /**\n * Rate-limit (429) handling: the first 429 per process prints one stderr\n * warning (not debug-gated, same channel and lifetime as the first-capture\n * announce); subsequent 429s only debug-log. Each rate-limited request is\n * retried exactly once after Retry-After; pendingRetries counts retries\n * waiting on their timers so the cap can shed load.\n */\n private rateLimitAnnounced = false;\n private pendingRetries = 0;\n\n constructor(opts: IngestClientOptions) {\n this.apiKey = opts.apiKey;\n this.endpoint = opts.endpoint.replace(/\\/$/, '');\n this.debug = opts.debug;\n this.dashboardUrl = (opts.dashboardUrl ?? DEFAULT_DASHBOARD_URL).replace(/\\/$/, '');\n }\n\n /**\n * Send a turn to the ingest API. Fire-and-log: errors are logged but never\n * thrown. The customer's LLM path never blocks on the Probe.\n */\n async sendTurn(turn: CapturedTurn): Promise<void> {\n try {\n const send = () =>\n fetch(`${this.endpoint}/v1/turns`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(turn),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n\n if (!response.ok) {\n this.log(`[probe] ingest failed status=${response.status}`);\n return;\n }\n\n // Announce the first successful capture exactly once per process.\n // Deliberately NOT gated on debug — this is the install-to-first-\n // value ritual, one line, permalink included. Stderr only, same\n // channel as log(). \"Captured\" means accepted at ingest (202,\n // pre-redaction); the permalink resolves by external id once the\n // worker projects the session (seconds later).\n if (!this.firstCaptureAnnounced) {\n this.firstCaptureAnnounced = true;\n // eslint-disable-next-line no-console\n console.error(\n `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`,\n );\n }\n\n if (this.debug) {\n const body = (await response.json()) as { status?: string; pendingId?: string };\n this.log(`[probe] ingest ok id=${body.pendingId ?? '?'}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[probe] ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.\n * Populates the `user_flagged_break` outcome column in Chapter 9c.\n */\n async sendFlag(deploymentSlug: string, flag: FlagPersonaBreakInput): Promise<void> {\n try {\n const send = () =>\n fetch(`${this.endpoint}/v1/flags`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: flag.sessionExternalId,\n flagType: 'persona_break',\n note: flag.note,\n turnIndex: flag.turnIndex,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n\n if (!response.ok) {\n this.log(`[probe] flag ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[probe] flag ingest ok session=${flag.sessionExternalId}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[probe] flag ingest error: ${msg}`);\n }\n }\n\n /**\n * Send a session-end event to the ingest API. Records why a session ended\n * on the sessions.probe_session_ended_reason column. Fire-and-log.\n */\n async sendSessionEnd(deploymentSlug: string, end: SessionEndInput): Promise<void> {\n try {\n const send = () =>\n fetch(`${this.endpoint}/v1/sessions/end`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: end.externalId,\n endedReason: end.endedReason,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[probe] session-end ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(`[probe] session-end ingest ok session=${end.externalId}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log(`[probe] session-end ingest error: ${msg}`);\n }\n }\n\n /**\n * Send an outcome event to the ingest API. Fire-and-log. Populates\n * probe_outcome_events per Amendment I Method D.\n */\n async sendOutcomeEvent(\n deploymentSlug: string,\n event: OutcomeEventEmit,\n ): Promise<void> {\n try {\n const send = () =>\n fetch(`${this.endpoint}/v1/outcome-events`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n deploymentSlug,\n sessionExternalId: event.sessionExternalId,\n kind: event.kind,\n detectedBy: 'sdk_custom',\n causingTurnIndex: event.causingTurnIndex,\n detail: event.detail,\n }),\n });\n const response = await this.retryIfRateLimited(await send(), send);\n if (response === null) return;\n if (!response.ok) {\n this.log(`[probe] outcome-event ingest failed status=${response.status}`);\n return;\n }\n if (this.debug) {\n this.log(\n `[probe] 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(`[probe] outcome-event ingest error: ${msg}`);\n }\n }\n\n /**\n * Route a send response through the 429 retry policy. Non-429 responses\n * pass through untouched. A 429 is re-sent exactly once after Retry-After\n * seconds (default 1s when the header is missing or unparseable; clamped\n * to [1, 60]s); the retry's response is returned as-is, so a second 429 is\n * never retried again — callers log and drop it like any other failed\n * send. Returns null when the retry was dropped at the pending-retry cap.\n * The timer is unref'd (where supported) so a pending retry never holds\n * the process open.\n */\n private async retryIfRateLimited(\n response: Response,\n resend: () => Promise<Response>,\n ): Promise<Response | null> {\n if (response.status !== 429) return response;\n\n if (!this.rateLimitAnnounced) {\n this.rateLimitAnnounced = true;\n // Deliberately NOT gated on debug — sustained rate limiting is silent\n // data loss; the operator hears about it exactly once per process.\n // Stderr only, same channel as log().\n // eslint-disable-next-line no-console\n console.error(\n 'Sight: ingest rate limit (429) — retrying once per Retry-After; sustained limiting drops captures. See https://field.cultured.computer/sight/sdk-reference#rate-limits',\n );\n } else {\n this.log('[probe] ingest rate limited (429), retrying once');\n }\n\n if (this.pendingRetries >= MAX_PENDING_RETRIES) {\n this.log('[probe] retry buffer full, dropped');\n return null;\n }\n\n const raw = response.headers.get('retry-after');\n const parsed = raw === null ? Number.NaN : Number(raw);\n const seconds = Number.isFinite(parsed) ? Math.min(Math.max(parsed, 1), 60) : 1;\n\n this.pendingRetries += 1;\n try {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, seconds * 1000);\n // unref is absent outside Node (browsers, some edge runtimes) —\n // skip silently there.\n timer.unref?.();\n });\n return await resend();\n } finally {\n this.pendingRetries -= 1;\n }\n }\n\n private log(msg: string): void {\n if (this.debug) {\n // stderr only; never leak to stdout\n // eslint-disable-next-line no-console\n console.error(msg);\n }\n }\n}\n","/**\n * Sight SDK (@cultured-computer/sight) shared types.\n */\n\nimport { z } from 'zod';\nimport type { PropensityInput } from '@fieldwork/shared';\n\n// ── Configuration ──────────────────────────────────────────────────────────\n\n/**\n * Signature phrases the customer authors per persona for Day-1 voice\n * consistency measurement per PROBE.md §2. The SDK edge computes matches\n * per turn (via @fieldwork/classifier signature-phrase) and includes the\n * matched slugs on the outgoing CapturedTurn.\n */\nexport const SignaturePhraseSchema = z.union([\n z.object({\n slug: z.string().min(1),\n phrase: z.string().min(1),\n description: z.string().optional(),\n }),\n z.object({\n slug: z.string().min(1),\n regex: z.string().min(1),\n flags: z.string().optional(),\n description: z.string().optional(),\n }),\n]);\nexport type SignaturePhraseInput = z.infer<typeof SignaturePhraseSchema>;\n\nexport const PersonaConfigSchema = z.object({\n /** Persona slug matching the deployment's registered persona. */\n slug: z.string().min(1),\n /**\n * RICE authorship artifact (Role, Identity, Communication, Engagement).\n * Either inline object or a path/URL to a JSON file loaded at init time.\n */\n rice: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),\n /**\n * Customer-authored signature phrases for this persona. Compiled once at\n * init and matched per turn at the SDK edge; matched slugs appear on the\n * outgoing turn as `signaturePhraseMatches`.\n */\n signaturePhrases: z.array(SignaturePhraseSchema).optional(),\n});\nexport type PersonaConfig = z.infer<typeof PersonaConfigSchema>;\n\nexport const OutcomeHookSchema = z.object({\n /** Type of outcome the deployment tracks. */\n type: z.enum(['numeric', 'categorical', 'boolean', 'duration']),\n /**\n * Callback that resolves the outcome for a completed session. Invoked by\n * Probe.endSession() with the session's externalId; a non-null result\n * lands as an outcome event on the session. Not invoked for sessions\n * swept server-side (no explicit endSession) — use emitOutcomeEvent()\n * for outcomes that become known out of band.\n */\n resolve: z.custom<(sessionId: string) => Promise<OutcomeResult | null>>(),\n});\nexport type OutcomeHook = z.infer<typeof OutcomeHookSchema>;\n\nexport type OutcomeResult = {\n outcome: string;\n type: 'numeric' | 'categorical' | 'boolean' | 'duration';\n value: string;\n};\n\nexport const ProbeConfigSchema = z.object({\n /** Unkey ingest key. Required. */\n apiKey: z.string().min(1),\n /** Deployment slug registered in the Probe backend. Required. */\n deployment: z.string().min(1),\n /** Ingest endpoint. Defaults to https://ingest.probe.io. */\n endpoint: z.string().url().default('https://ingest.probe.io'),\n /**\n * Dashboard base URL used by the one-time first-capture announcement\n * (the stderr permalink printed after the first successful send).\n * Self-hosted or staging dashboards override it the same way `endpoint`\n * is overridden.\n */\n dashboardUrl: z.string().url().default('https://field.cultured.computer/dashboard'),\n /** Persona identification. Optional at init; can be set later via identifyPersona(). */\n persona: PersonaConfigSchema.optional(),\n /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */\n outcomeHook: OutcomeHookSchema.optional(),\n /**\n * Sample rate for autocapture. 1.0 = 100% of calls captured. Lower values\n * sample deterministically so a given (turnId) always resolves identically.\n */\n sampleRate: z.number().min(0).max(1).default(1.0),\n /**\n * Debug mode: log every captured turn to stderr with a prefix. Never logs\n * the Bearer token or PII.\n */\n debug: z.boolean().default(false),\n});\nexport type ProbeConfig = z.infer<typeof ProbeConfigSchema>;\n/**\n * The shape callers pass to Probe.init(). This is the schema's INPUT type, so\n * fields with a `.default()` (endpoint, sampleRate, debug) are optional here —\n * the defaults are applied by ProbeConfigSchema.parse() inside init(). Use this\n * for the init argument; `ProbeConfig` is the resolved (post-parse) type held\n * internally, where those fields are always present.\n */\nexport type ProbeConfigInput = z.input<typeof ProbeConfigSchema>;\n\n// ── Session context (customer identifies persona per session) ──────────────\n\nexport const SessionStartSchema = z.object({\n /** Customer's session identity (opaque string; used as the correlation key). */\n externalId: z.string().min(1),\n /**\n * Customer's USER identity (opaque string), distinct from externalId:\n * externalId keys the session; externalUserId ties sessions to a\n * returning user. Forwarded on every captured turn so the worker can\n * persist it on the session row — return-with-persona-consistency and\n * prior-session metrics require it. Optional; deployments that do not\n * identify users simply skip the user-level return metrics.\n */\n externalUserId: z.string().min(1).optional(),\n /**\n * Persona slug active for this session. Overrides the init-level default.\n * Required for multi-persona deployments; optional for single-persona\n * deployments where init already carries the persona.\n */\n persona: z.string().min(1).optional(),\n /**\n * How the user got into this session (P2 per PLAN-2026-07-11).\n * Retention semantics differ radically between a resume and a fresh\n * notification landing.\n */\n openedVia: z.enum(['link', 'notification', 'resume', 'direct', 'share']).optional(),\n /**\n * Environmental context — browser / device / locale / tz (P2). Customer-\n * configurable which fields to include. See collectClientContext helper.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n /**\n * Optional customer metadata attached to the session. Forwarded with the\n * first captured turn merged into `clientContext` under the `metadata`\n * key, so it lands on sessions.probe_session_client_context.\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n /**\n * RLDS episode-level provenance (Amendment R populater 2026-07-11).\n * Powers Chapter 8e′ Card 3 version behavioral diff. All optional.\n * agentId — model/policy version\n * experimentId — A/B arm or feature flag\n * environmentConfigHash — SHA of prompt/config file(s)\n * environmentConfigLabel — human-readable version label\n */\n agentId: z.string().optional(),\n experimentId: z.string().optional(),\n environmentConfigHash: z.string().optional(),\n environmentConfigLabel: z.string().optional(),\n});\nexport type SessionStart = z.infer<typeof SessionStartSchema>;\n\n/**\n * Session end input (P2). Sent by Probe.endSession() so the worker records\n * why a session ended.\n */\nexport const SessionEndSchema = z.object({\n externalId: z.string().min(1),\n endedReason: z\n .enum(['natural', 'user_closed', 'timeout', 'agent_error', 'user_flagged', 'crashed'])\n .optional(),\n});\nexport type SessionEndInput = z.infer<typeof SessionEndSchema>;\n\n// ── Turn payload sent to ingest ────────────────────────────────────────────\n\nexport type CapturedTurn = {\n deploymentSlug: string;\n sessionExternalId: string;\n /**\n * Customer's user identity. Forwarded by captureTurn from the session\n * state (Probe.startSession({ externalUserId })); the worker persists it\n * on sessions.external_user_id at first-turn session create. Never\n * defaulted to sessionExternalId — that key identifies the session.\n */\n externalUserId?: string;\n turnIndex: number;\n /**\n * Persona slug active for this turn. Resolved by the SDK from (in order):\n * turn-level override, session-level from startSession(), init-level default.\n */\n personaSlug?: string;\n /**\n * Signature-phrase slugs matched at the SDK edge (computed from the\n * customer's signaturePhrases config at init). Empty array or omitted when\n * no signatures matched or none were registered.\n */\n signaturePhraseMatches?: string[];\n /**\n * Interpretive record fields passed through from a customer harness\n * (Oracle read hook wired). See PROBE.md §2. Populated only if the customer\n * runs the Cultured Computer harness pattern; null for non-harness deployments.\n */\n interpretive?: {\n situationType?: string[];\n read?: string;\n lensChosen?: string;\n reactionRegister?: string;\n reactionNextTurn?: string;\n };\n /**\n * User-side input for this turn (P1 per PLAN-2026-07-11). What the human\n * said + UI-level interactivity signals. Text is Presidio-scrubbed\n * server-side before landing on probe_user_reply_text.\n */\n userInput?: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount?: number;\n interruptedStream?: boolean;\n cancelledResponse?: boolean;\n submittedAt?: string;\n };\n /**\n * Interactivity: agent reflect time, stream completion, multimodal events.\n */\n interactivity?: {\n agentReflectMs?: number;\n agentStreamCompleted?: boolean;\n multimodalEvents?: Array<{ kind: string; at?: string; meta?: Record<string, unknown> }>;\n };\n /**\n * User outcome signals (Ch9-promoted first-class per PLAN-2026-07-11):\n * flagged break, explicit rating (1-5), thumbs.\n *\n * `flaggedBreak` is DEPRECATED in favor of Probe.flagPersonaBreak(),\n * which carries user attribution and emits a 'break' outcome event;\n * the turn-level boolean remains accepted for wire compat only.\n */\n userOutcome?: {\n flaggedBreak?: boolean;\n explicitRating?: number;\n thumbs?: 'up' | 'down';\n };\n /**\n * Propensity + candidate set (harness-supplied; see PROBE.md §2).\n * Manual-capture callers put this in payload.propensity; captureTurn\n * validates the Amendment S contract and hoists the valid object to\n * this top-level field so the worker projection lands it on the\n * read_candidates / read_propensities / selection_meta columns.\n */\n propensity?: PropensityInput;\n /**\n * Transition signals (the human's response to the previous reply).\n * Derived by captureTurn when the previous turn's capture time and this\n * turn's user submit time are both known; may also be supplied directly\n * by manual-capture callers.\n */\n transition?: {\n timeMs?: number;\n lengthDelta?: number;\n };\n /**\n * Session context forwarded on the FIRST captured turn of a session\n * (populated by captureTurn from Probe.startSession state; the worker\n * persists both at session find-or-create). Omitted on later turns.\n */\n openedVia?: 'link' | 'notification' | 'resume' | 'direct' | 'share';\n clientContext?: Record<string, unknown>;\n /**\n * RLDS episode-level provenance (Amendment R). Forwarded from the session\n * state on every turn so downstream storage can attribute each turn to the\n * arm/version that produced it. Populated by startSession() from either\n * the customer-provided value or the init-time default; null when neither\n * is set.\n */\n agentId?: string;\n experimentId?: string;\n environmentConfigHash?: string;\n environmentConfigLabel?: string;\n payload: Record<string, unknown>;\n};\n\n// ── Persona-break flag (from Probe.flagPersonaBreak) ──────────────────────\n\nexport const FlagPersonaBreakSchema = z.object({\n sessionExternalId: z.string().min(1),\n note: z.string().optional(),\n /** Turn index the flag refers to. Omit to attach to the session's latest turn. */\n turnIndex: z.number().int().nonnegative().optional(),\n});\nexport type FlagPersonaBreakInput = z.infer<typeof FlagPersonaBreakSchema>;\n\n// ── Outcome event (Amendment I Method D, 2026-07-12) ─────────────────────\n// Customer-emitted event marking a hard outcome (break/escalation/\n// resolution/etc.) durable on the probe_outcome_events table. Universal\n// seed kinds ship out of the box; deployments may register their own\n// arbitrary string kind.\nexport const OutcomeEventEmitSchema = z.object({\n sessionExternalId: z.string().min(1),\n kind: z.string().min(1),\n /** Optional turn index this event is caused by. Omit to attach to latest turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Optional detail payload (customer-defined). */\n detail: z.record(z.string(), z.unknown()).optional(),\n});\nexport type OutcomeEventEmit = z.infer<typeof OutcomeEventEmitSchema>;\n","/**\n * Client-context capture helper (P2 per PLAN-2026-07-11).\n *\n * At session start the SDK optionally collects browser/device/locale/tz\n * metadata to send as SessionStart.clientContext. Customers control which\n * fields land via ProbeConfig.clientContextIncludes; the default is\n * conservative (locale + timezone + agent kind, no fingerprinting fields).\n *\n * Node-side calls receive process metadata; browser-side calls receive\n * navigator + Intl.DateTimeFormat. Never leaks PII; anything that could\n * fingerprint the user is opt-in.\n */\n\nexport type ClientContextIncludes = {\n /** window.navigator.userAgent — off by default (fingerprinting risk). */\n userAgent?: boolean;\n /** window.navigator.language / process.env.LANG — on by default. */\n locale?: boolean;\n /** Intl timezone / process TZ — on by default. */\n timezone?: boolean;\n /** window.screen dimensions — off by default (fingerprinting risk). */\n screen?: boolean;\n /** Node process metadata (platform, node version) — on by default in Node. */\n runtime?: boolean;\n /** Custom key/value pairs the customer wants to attach. */\n custom?: Record<string, string | number | boolean | null>;\n};\n\nconst DEFAULT_INCLUDES: ClientContextIncludes = {\n locale: true,\n timezone: true,\n runtime: true,\n};\n\n/** Collect client context under the current environment (Node or browser). */\nexport function collectClientContext(\n includes: ClientContextIncludes = DEFAULT_INCLUDES,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n\n // Browser detection without lib.dom.d.ts (SDK doesn't include DOM lib to\n // keep node-side bundles small). We accept the global as `unknown` and\n // narrow via runtime checks.\n const globalAny = globalThis as unknown as {\n window?: {\n navigator?: {\n userAgent?: string;\n language?: string;\n languages?: ReadonlyArray<string>;\n };\n screen?: { width?: number; height?: number };\n };\n };\n const win = globalAny.window;\n const isBrowser = typeof win !== 'undefined' && typeof win?.navigator !== 'undefined';\n\n if (isBrowser && win) {\n const nav = win.navigator;\n if (includes.userAgent) out['userAgent'] = nav?.userAgent;\n if (includes.locale) {\n out['locale'] = nav?.language;\n if (nav?.languages) out['languages'] = [...nav.languages];\n }\n if (includes.timezone) {\n try {\n out['timezone'] = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* ignore */\n }\n }\n if (includes.screen && win.screen) {\n out['screen'] = { width: win.screen.width, height: win.screen.height };\n }\n out['agent'] = 'browser';\n } else if (typeof process !== 'undefined' && typeof process.versions !== 'undefined') {\n if (includes.locale) {\n const lang = process.env['LANG'] || process.env['LC_ALL'] || null;\n if (lang) out['locale'] = lang.split('.')[0];\n }\n if (includes.timezone) {\n try {\n out['timezone'] = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* ignore */\n }\n }\n if (includes.runtime) {\n out['runtime'] = {\n platform: process.platform,\n node: process.versions.node,\n };\n }\n out['agent'] = 'node';\n }\n\n if (includes.custom) {\n for (const [k, v] of Object.entries(includes.custom)) out[k] = v;\n }\n\n return out;\n}\n","/**\n * Stable SHA-256 hex hashing for environment-config identity.\n *\n * Shared by the public Probe.hashEnvironmentConfig() helper and the OTel\n * processor's autocapture version-stamping (auto environmentConfigHash from\n * the request's system message). Lives in its own module so the processor\n * can import it without a circular dependency on probe.ts.\n *\n * Prefers WebCrypto (browser + modern Node); falls back to node:crypto via\n * dynamic import so the SDK stays browser-friendly for callers that never\n * touch this helper.\n */\nexport async function hashEnvironmentConfig(input: string): Promise<string> {\n if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle) {\n const bytes = new TextEncoder().encode(input);\n const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n }\n const { createHash } = await import('node:crypto');\n return createHash('sha256').update(input).digest('hex');\n}\n","/**\n * Session context propagation via OpenTelemetry Baggage.\n *\n * Adapters need to know which session an in-flight LLM call belongs to. We\n * propagate the session ID through OTel Baggage rather than a parallel\n * AsyncLocalStorage instance because:\n * 1. OTel already runs AsyncLocalStorageContextManager under the hood\n * (auto-registered by NodeTracerProvider on Node 20+); a parallel ALS\n * would duplicate the async-hooks graph.\n * 2. Baggage propagates automatically across HTTP boundaries via the\n * `baggage:` header. A parallel ALS would break at every service hop.\n *\n * Customer wraps their conversation:\n *\n * await Probe.withSession(sessionId, async () => {\n * await openai.chat.completions.create({ ... }); // captured\n * await anthropic.messages.create({ ... }); // also captured\n * });\n *\n * Under the hood: baggage entry `probe.session_id` is set, context is\n * activated for the callback, spans emitted inside read the baggage in\n * their onEnd handler.\n */\n\nimport { context, propagation } from '@opentelemetry/api';\n\nexport const SESSION_BAGGAGE_KEY = 'probe.session_id';\n\n// Register an AsyncLocalStorage-backed ContextManager idempotently on first\n// use. Without this, `context.with(...)` uses the default NoopContextManager\n// which does not propagate across async boundaries; baggage would be dropped\n// as soon as an `await` happened inside the callback.\nlet contextManagerRegistered = false;\nasync function ensureContextManager(): Promise<void> {\n if (contextManagerRegistered) return;\n contextManagerRegistered = true;\n try {\n const mod = await import('@opentelemetry/context-async-hooks');\n const cm = new mod.AsyncLocalStorageContextManager();\n cm.enable();\n context.setGlobalContextManager(cm);\n } catch {\n // The context-async-hooks package may not be installed; fall back to\n // NoopContextManager. Baggage will not propagate across async boundaries\n // in that case, which is a known limitation surfaced in debug mode by\n // the OTel processor.\n }\n}\n\n/**\n * Run `fn` inside a context where the given session ID is available to any\n * OTel span emitted (directly or transitively). Returns the fn's return value.\n */\nexport async function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n await ensureContextManager();\n const currentBaggage = propagation.getBaggage(context.active());\n const nextBaggage = (currentBaggage ?? propagation.createBaggage()).setEntry(\n SESSION_BAGGAGE_KEY,\n { value: sessionId },\n );\n const nextContext = propagation.setBaggage(context.active(), nextBaggage);\n return context.with(nextContext, fn);\n}\n\n/**\n * Read the current session ID from OTel Baggage, or undefined if no session\n * is active. Called by the OTel span processor when a captured span ends.\n */\nexport function getCurrentSessionId(): string | undefined {\n const baggage = propagation.getBaggage(context.active());\n return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;\n}\n","/**\n * Probe OTel SpanProcessor.\n *\n * Consumes spans emitted by every registered instrumentation (Traceloop's\n * OpenAI / Anthropic / LangChain adapters, Vercel AI SDK's native\n * experimental_telemetry, custom fetch wrappers for Mercury-2). Maps the\n * standard `gen_ai.*` semantic-convention attributes onto CapturedTurn\n * payload and calls Probe.captureTurn().\n *\n * Filter rule: only capture spans that are actual LLM invocations. Skip:\n * - Vercel AI SDK `invoke_agent` rollups (double-count vs child `chat`).\n * - LangChain `traceloop.span.kind === \"workflow\" | \"task\"` (chain\n * scaffolding, not LLM calls).\n * - Any span with no `gen_ai.operation.name` or `gen_ai.system` attribute.\n *\n * Deduplication: when both `@traceloop/instrumentation-langchain` and\n * `@traceloop/instrumentation-openai` fire for the same call, prefer the\n * LangChain span (kind=agent) over the raw OpenAI span, keyed by traceId.\n */\n\nimport type { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-node';\nimport type { Context } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\nimport type { CapturedTurn } from '../types.js';\nimport { getCurrentSessionId } from './session-context.js';\nimport { hashEnvironmentConfig } from '../hash.js';\n\n// ── Deduplication cache (traceId → seen) ──────────────────────────────────\n// When LangChain instrumentation fires for a call, the underlying provider\n// (OpenAI/Anthropic) fires again on the same traceId. We take the first\n// span that arrives with a valid gen_ai.operation.name and skip the rest.\n// TTL is short (5s) because trace IDs recycle over a long-lived process.\nconst DEDUP_TTL_MS = 5_000;\nconst dedupCache = new Map<string, number>();\n\nfunction shouldSkipAsDuplicate(traceId: string): boolean {\n const now = Date.now();\n const seenAt = dedupCache.get(traceId);\n if (seenAt !== undefined && now - seenAt < DEDUP_TTL_MS) {\n return true;\n }\n dedupCache.set(traceId, now);\n // Sweep expired entries opportunistically (cheap, bounded work).\n if (dedupCache.size > 1000) {\n for (const [k, v] of dedupCache) {\n if (now - v > DEDUP_TTL_MS) dedupCache.delete(k);\n }\n }\n return false;\n}\n\n// ── Attribute helpers ─────────────────────────────────────────────────────\n\ntype AttrValue = string | number | boolean | Array<string | number | boolean> | undefined;\n\nfunction attr(attrs: Record<string, AttrValue>, key: string): AttrValue {\n return attrs[key];\n}\n\nfunction asString(v: AttrValue): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction asNumber(v: AttrValue): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\nfunction asStringArray(v: AttrValue): string[] | undefined {\n return Array.isArray(v) && v.every((x) => typeof x === 'string')\n ? (v as string[])\n : undefined;\n}\n\n// ── Filter: is this span an LLM call worth capturing? ────────────────────\n\nfunction isLLMCall(attrs: Record<string, AttrValue>): boolean {\n const op = asString(attrs['gen_ai.operation.name']);\n if (op === 'chat' || op === 'text_completion' || op === 'embeddings') {\n return true;\n }\n // LangChain via Traceloop emits spans with traceloop.span.kind. Only 'agent'\n // is an actual LLM call; 'workflow' / 'task' / 'tool' are scaffolding.\n const traceloopKind = asString(attrs['traceloop.span.kind']);\n if (traceloopKind === 'agent') return true;\n return false;\n}\n\n// ── Vercel AI SDK invoke_agent rollup detection ──────────────────────────\n\nfunction isVercelAgentRollup(\n spanName: string,\n attrs: Record<string, AttrValue>,\n): boolean {\n // Vercel AI SDK emits invoke_agent {modelId} spans that roll up token\n // usage across the child chat spans. Both spans have gen_ai.usage.*,\n // so we skip the rollup and keep the child chat span(s).\n return spanName.startsWith('invoke_agent ') && attrs['ai.telemetry.functionId'] !== undefined;\n}\n\n// ── Provider tagging (Mercury-2 via OpenAI-compat) ───────────────────────\n\nfunction taggedProvider(attrs: Record<string, AttrValue>): string | undefined {\n const rawProvider = asString(attrs['gen_ai.system'] ?? attrs['gen_ai.provider']);\n const model = asString(attrs['gen_ai.request.model']);\n // Mercury-2 goes through the OpenAI SDK with baseURL override; retag when\n // the model name signals Inception Labs.\n if (model?.toLowerCase().startsWith('mercury')) {\n return 'inception';\n }\n return rawProvider;\n}\n\n// ── Span → CapturedTurn.payload builder ──────────────────────────────────\n\nfunction buildPayload(span: ReadableSpan): Record<string, unknown> {\n const a = span.attributes as Record<string, AttrValue>;\n\n // Latency in ms from hrtime tuples.\n const start = span.startTime[0] * 1000 + span.startTime[1] / 1_000_000;\n const end = span.endTime[0] * 1000 + span.endTime[1] / 1_000_000;\n const latencyMs = Math.max(0, Math.round(end - start));\n\n // Response text: prefer ai.response.text (Vercel AI SDK) if present, then\n // fall back to gen_ai.output.messages (standard).\n const responseText =\n asString(attr(a, 'ai.response.text')) ?? asString(attr(a, 'gen_ai.output.messages'));\n\n // Tool calls: count and names.\n const toolCallNames = asStringArray(attr(a, 'gen_ai.response.tool_names'));\n const toolCallsCount =\n asNumber(attr(a, 'gen_ai.response.tool_calls_count')) ?? toolCallNames?.length;\n\n // Finish reason: gen_ai.response.finish_reasons is an array; take the first.\n const finishReasons = asStringArray(attr(a, 'gen_ai.response.finish_reasons'));\n const finishReason = finishReasons?.[0];\n\n // Error: OTel spans use span.status.code = ERROR when the call failed.\n // Message is in span.status.message.\n const error =\n span.status.code === 2 // SpanStatusCode.ERROR\n ? span.status.message ?? 'error'\n : undefined;\n\n return {\n // Plumbing (probe_* namespace lands on canonical turns columns per PROBE.md §2).\n probe_tokens_input: asNumber(attr(a, 'gen_ai.usage.input_tokens')),\n probe_tokens_output: asNumber(attr(a, 'gen_ai.usage.output_tokens')),\n probe_latency_ms: latencyMs,\n probe_model: asString(attr(a, 'gen_ai.response.model') ?? attr(a, 'gen_ai.request.model')),\n probe_provider: taggedProvider(a),\n probe_tool_calls: toolCallsCount,\n probe_tool_names: toolCallNames,\n probe_error: error,\n probe_finish_reason: finishReason,\n // Response text so the SDK edge signature-phrase matcher has something to\n // match against; the server-side redactor scrubs PII on the Tier 1 →\n // Tier 2 boundary.\n response: responseText ? { text: responseText } : undefined,\n // Anthropic cache tokens (per research report), promoted so the customer\n // can see cache-hit-rate in the dashboard without re-parsing raw messages.\n probe_cache_read_input_tokens: asNumber(attr(a, 'gen_ai.usage.cache_read_input_tokens')),\n probe_cache_creation_input_tokens: asNumber(\n attr(a, 'gen_ai.usage.cache_creation_input_tokens'),\n ),\n // Debug metadata (kept in payload, not projected to canonical columns).\n _otel: {\n spanName: span.name,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n operationName: asString(attr(a, 'gen_ai.operation.name')),\n traceloopKind: asString(attr(a, 'traceloop.span.kind')),\n },\n };\n}\n\n// ── System-prompt extraction (auto version-hash, 2026-07-14) ─────────────\n// Autocapture sees the request messages on the span. When a system message\n// is present and the deployer never set an environmentConfigHash on the\n// session, the session state is stamped with the SHA-256 of the system\n// prompt text plus an 'auto:xxxxxxxx' label — closing the version-diff\n// measurement with zero deployer work. Explicit startSession values always\n// win; nothing is logged or announced.\n\ntype MinimalSession = {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n};\n\n/** Join the text content of one message shape into a single string. */\nfunction messageText(content: unknown): string | undefined {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n const parts: string[] = [];\n for (const part of content) {\n if (typeof part === 'string') {\n parts.push(part);\n } else if (part && typeof part === 'object') {\n const p = part as Record<string, unknown>;\n // OTel gen_ai parts use {type:'text', content}; Vercel AI SDK and\n // provider SDKs use {type:'text', text}.\n const text = p['content'] ?? p['text'];\n if (typeof text === 'string') parts.push(text);\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n return undefined;\n}\n\n/** First system-role message text from a JSON-encoded message array. */\nfunction systemFromMessagesJson(raw: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return undefined;\n for (const msg of parsed) {\n if (msg && typeof msg === 'object') {\n const m = msg as Record<string, unknown>;\n if (m['role'] === 'system') {\n const text = messageText(m['content'] ?? m['parts']);\n if (text) return text;\n }\n }\n }\n } catch {\n // Not JSON — nothing to extract.\n }\n return undefined;\n}\n\n/**\n * Best-effort extraction of the request's system message text from span\n * attributes, across the conventions the registered instrumentations emit:\n * - `gen_ai.system_instructions` (OTel gen_ai semconv; string or JSON parts)\n * - `gen_ai.input.messages` (OTel gen_ai semconv; JSON message array)\n * - `gen_ai.prompt.{n}.role` / `.content` (Traceloop indexed convention)\n * - `ai.prompt.messages` / `ai.prompt` (Vercel AI SDK telemetry)\n * Returns undefined when no system message is present.\n */\nfunction extractSystemPromptText(attrs: Record<string, AttrValue>): string | undefined {\n // OTel semconv: dedicated system-instructions attribute.\n const instructions = attrs['gen_ai.system_instructions'];\n if (typeof instructions === 'string' && instructions.length > 0) {\n // May be plain text or a JSON parts array.\n try {\n const parsed: unknown = JSON.parse(instructions);\n const text = messageText(parsed);\n if (text) return text;\n } catch {\n return instructions;\n }\n return instructions;\n }\n\n // OTel semconv: full input message array as JSON.\n const inputMessages = asString(attrs['gen_ai.input.messages']);\n if (inputMessages) {\n const text = systemFromMessagesJson(inputMessages);\n if (text) return text;\n }\n\n // Traceloop: indexed prompt attributes (gen_ai.prompt.0.role, .content).\n for (let i = 0; ; i++) {\n const role = attrs[`gen_ai.prompt.${i}.role`];\n if (role === undefined) break;\n if (role === 'system') {\n const content = asString(attrs[`gen_ai.prompt.${i}.content`]);\n if (content) return content;\n }\n }\n\n // Vercel AI SDK: ai.prompt.messages (JSON CoreMessage array).\n const aiMessages = asString(attrs['ai.prompt.messages']);\n if (aiMessages) {\n const text = systemFromMessagesJson(aiMessages);\n if (text) return text;\n }\n\n // Vercel AI SDK: ai.prompt ({system, prompt/messages} as JSON).\n const aiPrompt = asString(attrs['ai.prompt']);\n if (aiPrompt) {\n try {\n const parsed: unknown = JSON.parse(aiPrompt);\n if (parsed && typeof parsed === 'object') {\n const system = (parsed as Record<string, unknown>)['system'];\n if (typeof system === 'string' && system.length > 0) return system;\n }\n } catch {\n // Not JSON — nothing to extract.\n }\n }\n\n return undefined;\n}\n\n/**\n * Stamp the session with the system prompt's hash when the deployer set no\n * environmentConfigHash. Awaited by onEnd BEFORE the capture is sent, so\n * captureTurn forwards the stamped values on this same turn. Re-checks\n * after the async hash so a concurrent explicit startSession always wins.\n */\nasync function maybeAutoStampEnvironmentConfig(\n session: MinimalSession,\n attrs: Record<string, AttrValue>,\n): Promise<void> {\n if (session.environmentConfigHash != null) return; // explicit or already stamped\n const systemText = extractSystemPromptText(attrs);\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\nfunction 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 state.sessions.set(sessionId, session);\n }\n const turnIndex = session.turnIndex;\n session.turnIndex += 1;\n return {\n session,\n sessionExternalId: sessionId,\n turnIndex,\n personaSlug: session.personaSlug ?? state.persona?.slug ?? null,\n };\n}\n\n// ── The processor ─────────────────────────────────────────────────────────\n\nexport class ProbeSpanProcessor implements SpanProcessor {\n constructor(\n private state: MinimalProbeState,\n private captureFn: (turn: CapturedTurn) => Promise<void>,\n ) {}\n\n onStart(_span: Span, _parentContext: Context): void {\n // No-op. All work happens in onEnd once all attributes are populated.\n }\n\n onEnd(span: ReadableSpan): void {\n try {\n const a = span.attributes as Record<string, AttrValue>;\n if (isVercelAgentRollup(span.name, a)) return;\n if (!isLLMCall(a)) return;\n\n const traceId = span.spanContext().traceId;\n if (shouldSkipAsDuplicate(traceId)) return;\n\n const sessionId = getCurrentSessionId();\n if (!sessionId) {\n if (this.state.config.debug) {\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`,\n );\n }\n return;\n }\n\n const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(\n this.state,\n sessionId,\n );\n\n const captured: CapturedTurn = {\n deploymentSlug: this.state.config.deployment,\n sessionExternalId,\n turnIndex,\n personaSlug: personaSlug ?? undefined,\n payload: buildPayload(span),\n };\n\n // Fire-and-log; SDK client swallows send errors. The auto version\n // stamp is awaited BEFORE the capture so the session-held\n // environmentConfigHash rides this same turn.\n (async () => {\n await maybeAutoStampEnvironmentConfig(session, a);\n await this.captureFn(captured);\n })().catch((err) => {\n if (this.state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`,\n );\n }\n });\n } catch (err) {\n if (this.state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n shutdown(): Promise<void> {\n dedupCache.clear();\n return Promise.resolve();\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n// ── Exported helpers for tests ────────────────────────────────────────────\nexport const _internals = {\n isLLMCall,\n isVercelAgentRollup,\n taggedProvider,\n buildPayload,\n shouldSkipAsDuplicate,\n dedupCache,\n extractSystemPromptText,\n maybeAutoStampEnvironmentConfig,\n};\n","/**\n * OTel provider setup.\n *\n * Registers a NodeTracerProvider with the ProbeSpanProcessor. Called once at\n * Probe.init() before any instrumentation is enabled.\n *\n * If the customer has already registered an OTel provider (e.g. Sentry, DD,\n * or their own), we do NOT overwrite it — instead we add our SpanProcessor\n * to the existing provider. This preserves customer observability.\n *\n * Trade-off: if the customer's provider does not expose addSpanProcessor\n * (older versions), we register our own NodeTracerProvider; OTel keeps the\n * first-registered global, so capture may not attach in that case. Chapter\n * 2 ships the pattern; hardening for edge cases lands with the first\n * enterprise customer.\n */\n\nimport { trace } from '@opentelemetry/api';\nimport { ProbeSpanProcessor } from './otel-processor.js';\nimport type { CapturedTurn } from '../types.js';\n\ntype MinimalProbeState = {\n config: { deployment: string; debug: boolean };\n persona: { slug: string } | null;\n sessions: Map<\n string,\n {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n // Auto version-hash stamping target (see otel-processor.ts).\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n }\n >;\n signatureMatchers: Map<string, unknown>;\n};\n\nlet installedProcessor: ProbeSpanProcessor | null = null;\n\nexport function setupOtelProvider(\n state: MinimalProbeState,\n captureFn: (turn: CapturedTurn) => Promise<void>,\n): void {\n if (installedProcessor !== null) {\n // Already set up.\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 * OpenAI instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-openai. Its spans flow through the\n * globally-registered ProbeSpanProcessor (see ./setup.ts and ./otel-processor.ts).\n *\n * Config: traceContent + enrichTokens on (customer wanting no-content mode\n * can flip Probe.init({ debug: false, sampleRate: 0 }) or override via\n * environment variable OTEL_INSTRUMENTATION_OPENAI_TRACE_CONTENT=false).\n *\n * This adapter also handles Mercury-2 via OpenAI SDK baseURL override; the\n * ProbeSpanProcessor tags `provider=inception` when gen_ai.request.model\n * starts with 'mercury'. Customers using Inception need no separate adapter.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerOpenAI(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-openai');\n instrumentation = new mod.OpenAIInstrumentation({\n enrichTokens: true,\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(`[probe/openai] instrumentation not enabled (${msg}); library not installed?`);\n }\n }\n}\n\nexport function unregisterOpenAI(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * Anthropic instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-anthropic. Cache-token attributes\n * (gen_ai.usage.cache_read_input_tokens, cache_creation_input_tokens) are\n * promoted onto the CapturedTurn payload by the shared processor.\n *\n * Anthropic finish reasons preserve their raw shape ('end_turn',\n * 'max_tokens', 'stop_sequence', 'tool_use') rather than being normalised to\n * OpenAI-style 'stop' / 'length'. Downstream analytics can pattern-match on\n * the raw value.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerAnthropic(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-anthropic');\n instrumentation = new mod.AnthropicInstrumentation({\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/anthropic] instrumentation not enabled (${msg}); library not installed?`,\n );\n }\n }\n}\n\nexport function unregisterAnthropic(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * LangChain instrumentation adapter.\n *\n * Enables @traceloop/instrumentation-langchain. The shared ProbeSpanProcessor\n * filters LangChain spans by `traceloop.span.kind === \"agent\"` (actual LLM\n * calls; skips 'workflow' / 'task' chain scaffolding and 'tool' invocations).\n *\n * Double-instrumentation note: when a LangChain chain calls into OpenAI or\n * Anthropic, BOTH the langchain instrumentation and the provider\n * instrumentation fire on the same traceId. The ProbeSpanProcessor's dedup\n * cache (keyed on traceId with 5s TTL) drops the second one so we never\n * double-capture a turn.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet instrumentation: any = null;\n\nexport async function registerLangChain(state: ProbeState): Promise<void> {\n if (registered) return;\n\n try {\n const mod = await import('@traceloop/instrumentation-langchain');\n instrumentation = new mod.LangChainInstrumentation({\n exceptionLogger: (err: unknown) => {\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.error(\n `[probe/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`,\n );\n }\n },\n });\n instrumentation.enable();\n registered = true;\n } catch (err) {\n if (state.config.debug) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(\n `[probe/langchain] instrumentation not enabled (${msg}); library not installed?`,\n );\n }\n }\n}\n\nexport function unregisterLangChain(): void {\n if (instrumentation) {\n try {\n instrumentation.disable?.();\n } catch {\n // ignore\n }\n instrumentation = null;\n }\n registered = false;\n}\n","/**\n * LangGraph instrumentation adapter.\n *\n * LangGraph reuses LangChain callbacks, so @traceloop/instrumentation-langchain\n * already fires for LangGraph nodes. The catch: Traceloop tags them as generic\n * `traceloop.span.kind: \"task\"` without graph topology hints (node id, thread,\n * edges). Customers who want the Structure-axis flow-state metrics (F1-F5\n * conformance from ml-benchmark) to work with LangGraph need to pass the\n * node/thread identity into their RunnableConfig.\n *\n * This adapter itself is a no-op registration: the actual span emission is\n * covered by ./langchain.ts (Traceloop's callback handler). The value we add\n * here is DOCUMENTATION of the tag pattern (below) plus a marker that\n * LangGraph coverage is active.\n *\n * Recommended customer pattern (documented in packages/sdk/README.md):\n *\n * await graph.invoke(state, {\n * configurable: { thread_id: sessionId },\n * tags: ['langgraph', 'node:planner', 'thread:' + sessionId],\n * });\n *\n * The `tags` array surfaces as span attribute `traceloop.association.properties.tags`\n * which lands on the CapturedTurn.payload._otel debug block. Chapter 5 flow-\n * state calibration can pattern-match on the 'node:*' prefix.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerLangGraph(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology',\n );\n }\n}\n\nexport function unregisterLangGraph(): void {\n registered = false;\n}\n","/**\n * Vercel AI SDK adapter.\n *\n * Vercel AI SDK emits OTel spans natively when `experimental_telemetry` is\n * enabled on the call. No library to install, no monkey-patching. The\n * ProbeSpanProcessor already listens to every span emitted through the\n * global TracerProvider, so this adapter just documents the customer\n * activation pattern.\n *\n * Customer wires per-call:\n *\n * import { generateText } from 'ai';\n * import { openai } from '@ai-sdk/openai';\n *\n * await Probe.withSession(sessionId, async () => {\n * const { text } = await generateText({\n * model: openai('gpt-5'),\n * prompt: 'Explain the plan',\n * experimental_telemetry: {\n * isEnabled: true,\n * functionId: 'plan-explanation',\n * recordInputs: true,\n * recordOutputs: true,\n * },\n * });\n * });\n *\n * The processor filters the noisy `invoke_agent {modelId}` rollup and\n * keeps only the child `chat {modelId}` spans (which are the actual LLM\n * calls). Sub-`execute_tool` spans attach to their parent chat span via\n * traceId; the dedup cache keeps us from double-capturing.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerVercelAI(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/vercel-ai] active; customer must set experimental_telemetry: { isEnabled: true } per call',\n );\n }\n}\n\nexport function unregisterVercelAI(): void {\n registered = false;\n}\n","/**\n * LiteLLM adapter (deferred to Chapter 4 URL-swap proxy).\n *\n * LiteLLM is Python. The Probe SDK is TypeScript. Bridging them by hosting an\n * OTLP collector in the SDK is 500+ lines of code that duplicates real OTel\n * collectors and makes the SDK stateful and network-listening. Not the right\n * shape for a research lab shipping a research instrument.\n *\n * The pragmatic 2026 path: LiteLLM customers configure `api_base` to the\n * Probe URL-swap proxy (Chapter 4). Same wire format, capture happens\n * server-side on the proxy, done. Customers who already run an OTLP\n * pipeline can point their exporter at the Probe collector as an add-on;\n * that lands with Chapter 6 self-host.\n *\n * This adapter registration is a no-op stub with a debug-mode warning so\n * customers who imported the SDK explicitly know why LiteLLM is not\n * captured on the SDK side. Chapter 4 documents the proxy configuration.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\n\nexport async function registerLiteLLM(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/litellm] not captured on SDK side; use the Chapter 4 URL-swap proxy for LiteLLM traffic',\n );\n }\n}\n\nexport function unregisterLiteLLM(): void {\n registered = false;\n}\n","/**\n * Mercury-2 adapter (Inception Labs, diffusion-class API).\n *\n * 99% of customer traffic to Mercury-2 goes through the OpenAI SDK with\n * `baseURL: 'https://api.inceptionlabs.ai/v1'`, which means\n * @traceloop/instrumentation-openai already captures every call and the\n * ProbeSpanProcessor tags `provider=inception` when\n * `gen_ai.request.model` starts with 'mercury'. No dedicated adapter needed\n * for that path.\n *\n * Fallback: for customers using a hand-rolled fetch call to the Inception\n * endpoint (rare), this adapter installs a fetch wrapper that emits an OTel\n * span for the request so the shared processor picks it up. Registered only\n * when Probe.init() is called with { instrumentation: { mercuryFetchWrapper:\n * true } } (opt-in; the default OpenAI SDK path covers everything).\n *\n * We do NOT ship a bespoke Mercury client. The maintenance cost of a\n * provider-specific wrapper for a single provider is not worth it when the\n * OpenAI-SDK path covers 99% of usage.\n */\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<string, { externalId: string; turnIndex: number; startedAt: number }>;\n};\n\nlet registered = false;\nlet originalFetch: typeof globalThis.fetch | null = null;\n\nconst INCEPTION_HOSTS = ['api.inceptionlabs.ai', 'api.inception.ai'];\n\nfunction isInceptionUrl(url: string): boolean {\n return INCEPTION_HOSTS.some((h) => url.includes(h));\n}\n\nexport async function registerMercury(state: ProbeState): Promise<void> {\n if (registered) return;\n registered = true;\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[probe/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route',\n );\n }\n}\n\n/**\n * Optional fetch monkey-patch for hand-rolled fetch calls to Inception.\n * Called only if the customer opts in explicitly (rare).\n */\nexport function enableMercuryFetchWrapper(state: ProbeState): void {\n if (originalFetch) return;\n originalFetch = globalThis.fetch;\n\n globalThis.fetch = async (input: string | URL | Request, init?: RequestInit) => {\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : input.url;\n if (!isInceptionUrl(url)) {\n return originalFetch!(input, init);\n }\n\n // Emit an OTel span so the shared processor picks it up.\n const { trace, SpanStatusCode } = await import('@opentelemetry/api');\n const tracer = trace.getTracer('@fieldwork/sdk/mercury');\n return tracer.startActiveSpan(`chat mercury-2`, async (span) => {\n span.setAttribute('gen_ai.system', 'inception');\n span.setAttribute('gen_ai.operation.name', 'chat');\n span.setAttribute('gen_ai.request.model', 'mercury-2');\n try {\n const response = await originalFetch!(input, init);\n if (!response.ok) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });\n }\n return response;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n throw err;\n } finally {\n span.end();\n if (state.config.debug) {\n // eslint-disable-next-line no-console\n console.log(`[probe/mercury] captured fetch to ${url}`);\n }\n }\n });\n };\n}\n\nexport function unregisterMercury(): void {\n if (originalFetch) {\n globalThis.fetch = originalFetch;\n originalFetch = null;\n }\n registered = false;\n}\n","/**\n * Instrumentation registry.\n *\n * Each adapter enables its target library's OTel instrumentation (or, for\n * Vercel AI SDK / Mercury-2, documents / opts into the customer wiring).\n * All emitted spans flow through the shared ProbeSpanProcessor which maps\n * gen_ai.* semantic-convention attributes to CapturedTurn.payload and calls\n * Probe.captureTurn().\n *\n * Session correlation: OTel Baggage via session-context.ts. Customers wrap\n * their conversation in Probe.withSession(sessionId, async () => { ... }).\n * Adapters do not need to know about sessions; the processor reads baggage\n * on span end.\n */\n\nimport type { CapturedTurn } from '../types.js';\nimport { setupOtelProvider } from './setup.js';\nimport { 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 } from './setup.js';\nexport { ProbeSpanProcessor } from './otel-processor.js';\n\ntype ProbeState = {\n config: { debug: boolean; deployment: string };\n persona: { slug: string } | null;\n sessions: Map<\n string,\n {\n externalId: string;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n // Auto version-hash stamping target (see otel-processor.ts).\n environmentConfigHash?: string | null;\n environmentConfigLabel?: string | null;\n }\n >;\n signatureMatchers: Map<string, unknown>;\n};\n\n/**\n * Register all instrumentation adapters at Probe.init() time.\n *\n * 1. Set up the OTel provider + ProbeSpanProcessor (once per process).\n * 2. Enable each adapter's instrumentation. Adapters no-op if the target\n * library is not installed in the customer's process.\n */\nexport function registerAllInstrumentations(\n state: ProbeState,\n captureFn: (turn: CapturedTurn) => Promise<void>,\n): void {\n setupOtelProvider(state, captureFn);\n\n const registrations: Array<Promise<void>> = [\n registerOpenAI(state),\n registerAnthropic(state),\n registerLangChain(state),\n registerLangGraph(state),\n registerVercelAI(state),\n registerLiteLLM(state),\n registerMercury(state),\n ];\n\n Promise.allSettled(registrations).then((results) => {\n if (!state.config.debug) return;\n for (const result of results) {\n if (result.status === 'rejected') {\n // eslint-disable-next-line no-console\n console.error(`[probe] adapter register rejected: ${result.reason}`);\n }\n }\n });\n}\n","/**\n * Signature-phrase matcher.\n *\n * Per-persona regex matching for voice consistency (Day 1 per PROBE.md §2).\n * Customer authors signature phrases at Probe.init({ persona: { signaturePhrases: [...] } }).\n * The SDK edge or a worker computes matches per turn and includes the list\n * of matched slugs in the turn payload.\n *\n * Signature phrase shape: { slug, pattern, description? }. The pattern is\n * either a plain string (case-insensitive whole-token match) or a regex\n * source string with optional flags. Slug is what appears in the matches\n * array; it is not the pattern.\n *\n * Trivial by design. Voice consistency at the embedding level lives in the\n * Chapter 5 Dream column (PSV representation with per-deployment STEL\n * calibration); this is the Day-1 heuristic that ships from ingest data alone.\n */\n\nexport type SignaturePhrase =\n | {\n /** Slug that appears in the matches array. Unique per persona. */\n slug: string;\n /** Plain-text phrase; matched case-insensitive with word boundaries. */\n phrase: string;\n description?: string;\n }\n | {\n slug: string;\n /** Regex source string. Compiled once per matcher construction. */\n regex: string;\n /** Regex flags (default: 'i'). */\n flags?: string;\n description?: string;\n };\n\ntype CompiledPhrase = {\n slug: string;\n pattern: RegExp;\n};\n\n/**\n * Compile a set of signature phrases into a matcher. Compile once at\n * Probe.init() and reuse per turn to avoid regex construction on every call.\n *\n * Invalid regex patterns are dropped with a stderr warning; other phrases\n * continue to match.\n */\nexport function compileSignaturePhrases(phrases: SignaturePhrase[]): CompiledPhrase[] {\n const compiled: CompiledPhrase[] = [];\n for (const p of phrases) {\n try {\n if ('phrase' in p) {\n const escaped = p.phrase.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // Only add \\b anchors where the phrase edge is a word character.\n // Otherwise \\b would require an impossible boundary next to punctuation.\n const startAnchor = /^\\w/.test(p.phrase) ? '\\\\b' : '';\n const endAnchor = /\\w$/.test(p.phrase) ? '\\\\b' : '';\n compiled.push({\n slug: p.slug,\n pattern: new RegExp(`${startAnchor}${escaped}${endAnchor}`, 'i'),\n });\n } else {\n compiled.push({\n slug: p.slug,\n pattern: new RegExp(p.regex, p.flags ?? 'i'),\n });\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.warn(`[classifier/signature-phrase] invalid pattern for slug=${p.slug}: ${msg}`);\n }\n }\n return compiled;\n}\n\n/**\n * Match a text against a compiled signature-phrase set. Returns the list of\n * matched slugs (unique, in the order the phrases were compiled).\n *\n * Empty text or empty compiled set returns [].\n */\nexport function matchSignaturePhrases(\n text: string,\n compiled: CompiledPhrase[],\n): string[] {\n if (!text || compiled.length === 0) return [];\n const matches: string[] = [];\n for (const c of compiled) {\n if (c.pattern.test(text)) matches.push(c.slug);\n }\n return matches;\n}\n","/**\n * Shared types and constants across ingest, dashboard, and future SDK.\n * Keep this package small; anything domain-specific belongs in @fieldwork/db\n * or its own package.\n */\n\nimport { z } from 'zod';\n\n// ── Situation vocabulary (OPEN) ───────────────────────────────────────────\n// Situation-type is open-vocabulary. The Day-1 heuristic emits a general\n// dialogue-act seed; a deployment discovers its own situation types by\n// clustering across sessions, and a harness can pass any tag it authors.\n// The arrays below are SEEDS, not a closed enum — the situation column is\n// text[] and ingest accepts any string tag.\n\n// Domain-general dialogue-act seed (the default classifier vocabulary; fits\n// support, assistants, and any conversational deployment).\nexport const GENERAL_SITUATION_TAGS = [\n 'question',\n 'request',\n 'inform',\n 'correction',\n 'confirmation',\n 'escalation',\n 'closing',\n 'smalltalk',\n] as const;\n\n// Narrative pack (companion / roleplay), opt-in — the field-derived types.\nexport const NARRATIVE_SITUATION_TAGS = [\n 'status_power_shift',\n 'deception_concealment',\n 'dramatic_irony',\n 'reveal_recognition',\n 'betrayal_broken_trust',\n 'reconciliation_repair',\n 'moral_dilemma_subtext',\n 'comedic_incongruity',\n] as const;\n\n// Situation tags are open strings; the arrays above are seeds, not an enum.\nexport type SituationTag = string;\n\n// Back-compat aliases (the narrative pack keeps the historical names).\nexport const SITUATION_TYPES = NARRATIVE_SITUATION_TAGS;\nexport type SituationType = (typeof NARRATIVE_SITUATION_TAGS)[number];\n\n// ── Reaction register from Vincent's harness ──────────────────────────────\nexport const REACTION_REGISTERS = ['heavy', 'comic', 'edge'] as const;\nexport type ReactionRegister = (typeof REACTION_REGISTERS)[number];\n\n// ── Outcome type per probe.md §2 ──────────────────────────────────────────\nexport const OUTCOME_TYPES = ['numeric', 'categorical', 'boolean', 'duration'] as const;\nexport type OutcomeType = (typeof OUTCOME_TYPES)[number];\n\n// ── Interpretive fields the SDK may pass through from a harness ────────────\n// Customer running the Cultured Computer harness pattern or wiring the\n// Oracle read hook can populate these at the SDK edge; ingest passes them\n// through to canonical turns. When absent, the async classifier workers\n// (packages/classifier) populate situation_type and reaction_register from\n// Tier 1 records; lens_chosen stays null for non-harness deployments.\nexport const InterpretiveRecordSchema = z.object({\n // Open vocabulary: any string tag. Seeds live in GENERAL_SITUATION_TAGS /\n // NARRATIVE_SITUATION_TAGS but ingest never rejects an unseen situation.\n situationType: z.array(z.string()).optional(),\n read: z.string().optional(),\n lensChosen: z.string().optional(),\n reactionRegister: z.enum(REACTION_REGISTERS).optional(),\n reactionNextTurn: z.string().optional(),\n});\nexport type InterpretiveRecord = z.infer<typeof InterpretiveRecordSchema>;\n\n// ── Propensity + candidates (Day 1 harness-supplied, per PROBE.md §2) ─────\n// The one thing that cannot be backfilled: the alternative reads the harness\n// considered, the actual sampling distribution used to select among them,\n// which was selected, and (separately) raw model confidence/logprobs.\n//\n// `scores` and `propensities` are DIFFERENT things and must not be\n// conflated. Off-policy evaluation requires `propensities` — the behavior\n// policy's actual sampling probability at selection time — not scores.\n// A harness that samples with temperature/top_p and then reports raw\n// softmax(logits) as \"propensity\" will break DR estimators. `scores`\n// remains useful as a diagnostic and as input for later CI construction.\nexport const PropensitySchema = z.object({\n candidates: z.array(z.object({ label: z.string(), text: z.string().optional() })).optional(),\n /**\n * Raw model confidence / logprobs / ensemble scores per candidate.\n * Diagnostic only; NOT a propensity unless the harness confirms it is\n * the exact sampling distribution used and passes it also as\n * `propensities`.\n */\n scores: z.array(z.number()).optional(),\n /**\n * Behavior-policy sampling distribution at selection time. Must sum\n * to 1.0 (within float tolerance) if present. Load-bearing for OPE\n * (Dudík, Langford & Li 2011 for per-turn / Jiang & Li 2016 for\n * trajectory). When omitted, OPE is not possible on this turn.\n */\n propensities: z.array(z.number()).optional(),\n selectedIndex: z.number().int().nonnegative().optional(),\n /**\n * Sampling-policy metadata: temperature, top_p, top_k, seed, sampler\n * name, ensemble weights. Required for reviewers to verify that\n * `propensities` is the actual behavior distribution.\n */\n selectionMeta: z.record(z.string(), z.unknown()).optional(),\n});\nexport type PropensityInput = z.infer<typeof PropensitySchema>;\n\n/**\n * Amendment S (2026-07-14) — post-guardrail propensity contract validator.\n *\n * Saito et al. 2021 Open Bandit Pipeline (arXiv:2008.07146); Farhadi\n * field notes on OPE identification. Enforces the four bug classes at\n * the SDK edge — if a customer wants the directive/OPE half, propensity\n * logging must survive these checks.\n *\n * Bug classes:\n * 1. Deterministic decoding (temp=0) with propensity: zero support ⇒ OPE\n * undefined for any counterfactual (positivity/overlap failure).\n * 2. Missing policy version metadata: importance-weighted estimators\n * require the logging policy be identifiable.\n * 3. propensities present without summing to ~1.0: not a probability\n * distribution.\n * 4. selectionMeta absent when propensities present: reviewers cannot\n * verify that propensities is the actual behavior distribution.\n *\n * Returns { ok: true } when valid, { ok: false, reason } when contract\n * violated. Fire-and-log at SDK edge; do NOT block ingest — customers\n * without OPE ambitions still ship descriptive-half records.\n */\nexport type PropensityContractResult =\n | { ok: true }\n | { ok: false, reason: string, class: 'zero_support' | 'missing_policy_version' | 'malformed_distribution' | 'missing_selection_meta' };\n\nexport function validatePropensityContract(p: PropensityInput | undefined): PropensityContractResult {\n if (!p) return { ok: true }; // customer opted out of propensity logging — fine\n if (!p.propensities || p.propensities.length === 0) return { ok: true }; // descriptive-half only\n\n // Bug class 1: zero-support (deterministic decoding)\n const temp = p.selectionMeta?.['temperature'] as number | undefined;\n if (typeof temp === 'number' && temp === 0) {\n return {\n ok: false,\n class: 'zero_support',\n reason: 'temperature=0 with propensities logged: deterministic decoding has zero support. OPE is undefined for any counterfactual. Set temperature > 0 or omit propensities.',\n };\n }\n\n // Bug class 2: missing policy version\n const policyVersion = p.selectionMeta?.['policy_version'] as string | undefined;\n if (!policyVersion) {\n return {\n ok: false,\n class: 'missing_policy_version',\n reason: 'propensities logged without selectionMeta.policy_version. IPS/DR require the logging policy be identifiable across replays.',\n };\n }\n\n // Bug class 3: distribution doesn't sum to 1\n const sum = p.propensities.reduce((a, b) => a + b, 0);\n if (Math.abs(sum - 1.0) > 0.02) {\n return {\n ok: false,\n class: 'malformed_distribution',\n reason: `propensities sum to ${sum.toFixed(4)}, expected ~1.0. Not a probability distribution; likely raw softmax(logits). A score is not a probability.`,\n };\n }\n\n // Bug class 4: selectionMeta present but missing sampler details\n if (!p.selectionMeta) {\n return {\n ok: false,\n class: 'missing_selection_meta',\n reason: 'propensities logged without selectionMeta. Reviewers cannot verify propensities is the actual behavior distribution.',\n };\n }\n\n return { ok: true };\n}\n\n// ── Transition signals (Day 1, per PROBE.md §2) ───────────────────────────\n// The right half of the record: human's response to the reply. Cheap\n// observations the SDK captures without waiting for outcome-hook wiring.\nexport const TransitionSchema = z.object({\n timeMs: z.number().int().nonnegative().optional(),\n lengthDelta: z.number().int().optional(),\n});\nexport type TransitionInput = z.infer<typeof TransitionSchema>;\n\n// ── User-side input (P1, per PLAN-2026-07-11-p1-p2) ──────────────────────\n// What the human said + interactivity signals about how they said it.\n// The single most-important missing capture pre-2026-07-11: without user\n// text as a first-class column, the record is agent-centric. See PROBE.md\n// Amendment G (sequence primacy over classification).\nexport const UserInputSchema = z.object({\n /** The user's message text. Presidio-scrubbed server-side before landing on `probe_user_reply_text`. */\n text: z.string().optional(),\n /** Milliseconds between agent response end and user's first keystroke. Client-side UI hook, optional. */\n firstKeystrokeMs: z.number().int().nonnegative().optional(),\n /** Backspace/edit count while typing this reply. Client-side UI hook, optional. */\n editCount: z.number().int().nonnegative().optional(),\n /** Did the user submit before the agent's response finished streaming? */\n interruptedStream: z.boolean().optional(),\n /** Did the user click stop on an agent streaming response mid-flight? */\n cancelledResponse: z.boolean().optional(),\n /** ISO timestamp when the user submitted this reply. */\n submittedAt: z.string().optional(),\n});\nexport type UserInput = z.infer<typeof UserInputSchema>;\n\n// ── Interactivity (P1) — agent-side reflection + stream state ────────────\nexport const InteractivitySchema = z.object({\n /** Milliseconds between the user's submit and the next agent LLM call. */\n agentReflectMs: z.number().int().nonnegative().optional(),\n /** Did the agent's response stream finish fully (finish_reason='stop')? */\n agentStreamCompleted: z.boolean().optional(),\n /** Multimodal events observed on this turn (image upload, voice snippet, file, etc.). */\n multimodalEvents: z\n .array(\n z.object({\n kind: z.string(),\n at: z.string().optional(),\n meta: z.record(z.string(), z.unknown()).optional(),\n }),\n )\n .optional(),\n});\nexport type InteractivityInput = z.infer<typeof InteractivitySchema>;\n\n// ── User outcome signals (Ch9-promoted, first-class per PLAN-2026-07-11) ─\nexport const UserOutcomeSchema = z.object({\n /**\n * Explicit \"that didn't sound like you\" flag attached at turn level.\n * DEPRECATED: prefer Probe.flagPersonaBreak(), which routes through the\n * flags ingest path and carries user attribution + a 'break' outcome\n * event. This turn-level boolean remains accepted for wire compat but\n * new integrations should not set it.\n */\n flaggedBreak: z.boolean().optional(),\n /** Rating widget value 1-5, customer-supplied. */\n explicitRating: z.number().int().min(1).max(5).optional(),\n /** Thumbs-up / thumbs-down widget value. */\n thumbs: z.enum(['up', 'down']).optional(),\n});\nexport type UserOutcomeInput = z.infer<typeof UserOutcomeSchema>;\n\n// ── SDK ingest input schema (mirrored by apps/ingest/routes/turns.ts) ─────\nexport const TurnInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /**\n * Customer's user identity (opaque string), forwarded by the SDK from\n * Probe.startSession() state on every turn. Distinct from\n * sessionExternalId, which keys the SESSION: the worker persists this on\n * sessions.external_user_id at first-turn session create (falling back to\n * null — never to sessionExternalId) so return-with-persona-consistency\n * and prior-session metrics read a real user identity.\n */\n externalUserId: z.string().min(1).optional(),\n turnIndex: z.number().int().nonnegative(),\n /**\n * Persona slug active for this turn. Customer-supplied (from SDK persona\n * resolution: turn override / session / init default). Optional; deployments\n * with a single registered persona can omit this and the ingest worker\n * backfills from the deployment default at write time.\n */\n personaSlug: z.string().min(1).optional(),\n /**\n * Signature-phrase matches computed at the SDK edge (per PROBE.md §2).\n * List of matched signature-phrase slugs the customer registered via\n * Probe.init({ persona: { signaturePhrases: [...] } }). Empty array or\n * omitted when no signatures matched or the deployment did not register any.\n */\n signaturePhraseMatches: z.array(z.string()).optional(),\n /**\n * Interpretive record fields passed through from a customer harness\n * (Oracle read hook wired). Omitted for deployments not running the harness;\n * server-side classifier workers populate situation_type and reaction_register\n * from the raw payload instead.\n */\n interpretive: InterpretiveRecordSchema.optional(),\n /**\n * Propensity + candidate set + scores. Harness-supplied only. Substrate\n * for OPE in Chapter 5 Dream. Nearly free if the harness already computes\n * candidates + ensemble scores; cannot be backfilled from the reply alone.\n */\n propensity: PropensitySchema.optional(),\n /**\n * Transition signals (human's response to the reply). Populated when the\n * SDK observes the next user turn; may arrive on a subsequent turn ingest.\n */\n transition: TransitionSchema.optional(),\n /**\n * User-side input for this turn: what the human actually said + UI-level\n * interactivity hints. Server-side Presidio scrubs text before it lands\n * on the canonical probe_user_reply_text column. See PLAN-2026-07-11.\n */\n userInput: UserInputSchema.optional(),\n /**\n * Interactivity between agent and user for this turn: agent reflect time,\n * stream completion, multimodal events.\n */\n interactivity: InteractivitySchema.optional(),\n /**\n * Explicit user outcome signals (Ch9-promoted): flagged break, rating,\n * thumbs. Landed as first-class columns per PLAN-2026-07-11.\n */\n userOutcome: UserOutcomeSchema.optional(),\n /**\n * RLDS episode-level provenance (Amendment R populater 2026-07-11).\n * SDK forwards these from Probe.startSession() on every turn payload so\n * the worker can persist them on the sessions row at first-turn create.\n * All optional. Powers Chapter 8e′ Card 3 version behavioral diff.\n */\n agentId: z.string().optional(),\n experimentId: z.string().optional(),\n environmentConfigHash: z.string().optional(),\n environmentConfigLabel: z.string().optional(),\n /**\n * Session context riding the FIRST turn of a session (there is no\n * session-start wire route; the session row is created lazily by the\n * worker on the first turn that arrives). The SDK forwards these once\n * per session from Probe.startSession() state; the worker persists them\n * on sessions.probe_session_opened_via / probe_session_client_context\n * at session find-or-create and ignores them on later turns.\n */\n openedVia: z.enum(['link', 'notification', 'resume', 'direct', 'share']).optional(),\n /**\n * Browser / device / locale / tz environmental context, customer-\n * configurable which fields to include. Customer metadata from\n * Probe.startSession({ metadata }) is merged in by the SDK under the\n * `metadata` key so it has a durable landing place.\n */\n clientContext: z.record(z.string(), z.unknown()).optional(),\n payload: z.record(z.string(), z.unknown()),\n});\nexport type TurnInput = z.infer<typeof TurnInputSchema>;\n\n// ── Session lifecycle schemas (P2, per PLAN-2026-07-11) ──────────────────\n// Note: there is deliberately no SessionStartSchema here. A session-start\n// wire contract was drafted 2026-07-11 but no route ever consumed it; the\n// worker creates sessions lazily on the first ingested turn instead, and\n// session context (openedVia, clientContext) rides TurnInputSchema on that\n// first turn. Deleted rather than kept as dead surface (e2e audit\n// 2026-07-13); resurrect from git history if a dedicated route ships.\n\nexport const SessionEndSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /** Why the session ended. */\n endedReason: z\n .enum(['natural', 'user_closed', 'timeout', 'agent_error', 'user_flagged', 'crashed'])\n .optional(),\n /** ISO timestamp of session end. */\n endedAt: z.string().optional(),\n});\nexport type SessionEndInput = z.infer<typeof SessionEndSchema>;\n\n// ── SDK flag input schema (persona-break flag from Probe.flagPersonaBreak) ─\n// Populates the `user_flagged_break` outcome column in Chapter 9c. Consumer AI\n// products wire this to their in-product \"that didn't sound like you\" UX.\nexport const FlagInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n flagType: z.enum(['persona_break']),\n note: z.string().optional(),\n /**\n * Turn index the flag refers to. Optional; if omitted, the flag is\n * attached to the most recent turn of the session.\n */\n turnIndex: z.number().int().nonnegative().optional(),\n});\nexport type FlagInput = z.infer<typeof FlagInputSchema>;\n\n// ── Outcome event ingest (Amendment I Method D, 2026-07-12) ──────────────\n// Customer- or harness-emitted event marking a hard outcome. Universal seed\n// kinds ship as fallback; open-vocab lets deployments register their own.\n// Worker-side detectors also emit events without an SDK call, so this\n// schema is only the *customer-driven* portion of the outcome corpus.\nexport const OUTCOME_EVENT_KINDS_SEED = [\n 'break',\n 'escalation',\n 'resolution',\n 'abandonment',\n 'register_drift_cross',\n 'thumbs_down',\n 'thumbs_up',\n 'rating_low',\n 'rating_high',\n] as const;\nexport type OutcomeEventKindSeed = (typeof OUTCOME_EVENT_KINDS_SEED)[number];\n\n// ── Synthetic demo-data marker (2026-07-13 demo arc) ─────────────────────\n// A deployment whose classifier_config carries `synthetic: true` holds\n// generated data (the demo corpus), never customer traffic. One marker,\n// many readers: the dashboard banner + \"(demo)\" filter labels, the\n// measurement sweep's provenance stamp on probe_measurement_aggregates\n// rows, and the worker's seed_demo idempotency guard all read THIS\n// predicate rather than re-deriving the convention. Writers: the demo\n// seeding module (apps/worker/src/demo-seed.ts) and the seeder CLI\n// (scripts/seed-demo-corpus.mjs), both via the same merge helper.\nexport function isSyntheticClassifierConfig(config: unknown): boolean {\n return (\n typeof config === 'object' &&\n config !== null &&\n (config as Record<string, unknown>)['synthetic'] === true\n );\n}\n\n/**\n * DEMO_AUTOSEED feature gate, default ON in code: any value except an\n * explicit '0' / 'false' enables demo auto-seeding. Read at enqueue time\n * (dashboard onboarding) and at consume time (worker seed_demo handler)\n * through this one predicate. Pure over an env bag for unit tests.\n * Documented in docs/DEPLOY.md.\n */\nexport function demoAutoseedEnabled(\n env: Record<string, string | undefined> = typeof process !== 'undefined' ? process.env : {},\n): boolean {\n const v = env['DEMO_AUTOSEED'];\n return v !== '0' && v !== 'false';\n}\n\n// ── Demo seeding job schemas (auto-provision arc, 2026-07-13) ─────────────\n// Rides the pending_redaction queue like flag / session_end / outcome_event:\n// onboarding enqueues `_kind: 'seed_demo'` on project creation (gated by\n// DEMO_AUTOSEED, default ON); the worker consumes it, builds the\n// deterministic corpus in-process, and enqueues the corpus payloads plus a\n// trailing `_kind: 'seed_demo_backdate'` row that moves session/turn\n// timestamps onto the corpus schedule once the corpus rows have drained.\n/** Corpus window anchor offset: startDate defaults to now minus this, so\n the ~6.4-day corpus sits fully inside trailing-7-day sweep windows. */\nexport const DEMO_SEED_WINDOW_OFFSET_MS = 6.5 * 24 * 60 * 60 * 1000;\n\nexport const SeedDemoJobSchema = z.object({\n /** Slug for the demo deployment; defaults to 'demo'. */\n deploymentSlug: z.string().min(1).optional(),\n /** PRNG seed; the corpus is byte-identical per (seed, startDate). */\n seed: z.number().int().optional(),\n /**\n * ISO anchor for the corpus window (sessions land in\n * [startDate, startDate + ~6.4d]). Enqueuers stamp now-6.5d so the\n * trailing-7-day sweeps see the corpus; the worker defaults the same\n * way when absent.\n */\n startDate: z.string().optional(),\n});\nexport type SeedDemoJobInput = z.infer<typeof SeedDemoJobSchema>;\n\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\nexport const OutcomeEventInputSchema = z.object({\n deploymentSlug: z.string().min(1),\n sessionExternalId: z.string().min(1),\n /** Open-vocab kind label. Seeds above; customers may register any string. */\n kind: z.string().min(1),\n /** How was this event detected? Seed values below; customer sources allowed. */\n detectedBy: z\n .enum(['harness', 'sdk_flag', 'sdk_rating', 'sdk_thumbs', 'worker_detector', 'webhook', 'sdk_custom'])\n .or(z.string().min(1)),\n /** Optional turn index the event was caused by. Omitted → attaches to session's most recent turn. */\n causingTurnIndex: z.number().int().nonnegative().optional(),\n /** Optional detail payload (customer-defined). */\n detail: z.record(z.string(), z.unknown()).optional(),\n /** ISO timestamp; defaults to server-side now. */\n firedAt: z.string().optional(),\n});\nexport type OutcomeEventInput = z.infer<typeof OutcomeEventInputSchema>;\n","/**\n * The Probe SDK main entry point.\n *\n * Usage:\n * import { Sight } from '@cultured-computer/sight';\n *\n * Probe.init({\n * apiKey: process.env.PROBE_API_KEY!,\n * deployment: 'alyssa-v2',\n * persona: { slug: 'alyssa' },\n * });\n *\n * // Autocapture is now on for any subsequent OpenAI / Anthropic / etc. call.\n */\n\nimport { IngestClient } from './client';\nimport {\n ProbeConfigSchema,\n SessionStartSchema,\n FlagPersonaBreakSchema,\n OutcomeEventEmitSchema,\n} from './types';\nimport type {\n ProbeConfig,\n ProbeConfigInput,\n PersonaConfig,\n OutcomeHook,\n CapturedTurn,\n SessionStart,\n SessionEndInput,\n FlagPersonaBreakInput,\n OutcomeEventEmit,\n} from './types';\nimport { collectClientContext, type ClientContextIncludes } from './client-context';\nimport { hashEnvironmentConfig } from './hash';\nimport { registerAllInstrumentations, withSession as withSessionContext } 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 type PropensityInput,\n} from '@fieldwork/shared';\n\n// ── Singleton state ────────────────────────────────────────────────────────\n\ntype ProbeState = {\n config: ProbeConfig;\n client: IngestClient;\n persona: PersonaConfig | null;\n outcomeHook: OutcomeHook | null;\n sessions: Map<string, SessionState>;\n /**\n * Signature phrases compiled once per persona at init/identify time.\n * Keyed by persona slug so per-session persona switches use the right\n * matcher without recompiling.\n */\n signatureMatchers: Map<string, ReturnType<typeof compileSignaturePhrases>>;\n /**\n * Interaction signals (userInputStart/Edit/Submit, userThumbs/userRating)\n * that arrived BEFORE any session entry existed for their externalId.\n * Flushed into the session entry when it is created (startSession or\n * lazy-create at captureTurn). FIFO-capped at PRE_SESSION_BUFFER_MAX ids\n * so signals for sessions that never capture a turn cannot leak memory.\n */\n preSessionBuffer: Map<string, PreSessionSignals>;\n};\n\ntype PreSessionSignals = {\n pendingUserInput: SessionState['pendingUserInput'];\n pendingUserOutcome: SessionState['pendingUserOutcome'];\n lastUserSubmitAt: number | null;\n};\n\n/** FIFO cap on pre-session signal buffering (distinct session ids). */\nconst PRE_SESSION_BUFFER_MAX = 100;\n\ntype SessionState = {\n externalId: string;\n /** Customer's user identity from startSession; forwarded on every turn. */\n externalUserId: string | null;\n turnIndex: number;\n startedAt: number;\n personaSlug: string | null;\n metadata: Record<string, unknown> | null;\n openedVia: string | null;\n clientContext: Record<string, unknown> | null;\n // RLDS provenance (Amendment R populater 2026-07-11).\n agentId: string | null;\n experimentId: string | null;\n environmentConfigHash: string | null;\n environmentConfigLabel: string | null;\n /**\n * Timestamp of the last captured agent turn. Used on the NEXT turn to\n * derive transition.timeMs (previous agent reply → this turn's user\n * submit) and firstKeystrokeMs (previous agent reply → typing start).\n */\n lastAgentTurnAt: number | null;\n /**\n * Timestamp of the last userInputSubmit. Used at captureTurn to derive\n * agentReflectMs (user submit → agent turn capture). transition.timeMs\n * derives from the per-turn pendingUserInput.submittedAt instead, which\n * resets on every capture, so stale submits are never reused for it.\n */\n lastUserSubmitAt: number | null;\n /**\n * True once openedVia/clientContext have been sent with a captured turn.\n * The worker persists session context at session find-or-create (first\n * turn that arrives), so the SDK forwards it exactly once.\n */\n sessionContextForwarded: boolean;\n /** Per-turn user input pending on the SDK edge (unified capture helper). */\n pendingUserInput: {\n text?: string;\n firstKeystrokeMs?: number;\n editCount: number;\n submittedAt?: number;\n } | null;\n /** Per-turn user outcome pending on the SDK edge (thumbs / rating). */\n pendingUserOutcome: {\n thumbs?: 'up' | 'down';\n explicitRating?: number;\n } | null;\n};\n\nlet state: ProbeState | null = null;\n\n// ── Public API ─────────────────────────────────────────────────────────────\n\nexport class Probe {\n /**\n * Initialize the Probe SDK. Call once at process start. Subsequent calls are\n * no-ops with a warning; re-init requires a shutdown() first.\n */\n static init(config: ProbeConfigInput): void {\n if (state !== null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] already initialized; call shutdown() first');\n return;\n }\n\n const validated = ProbeConfigSchema.parse(config);\n const client = new IngestClient({\n apiKey: validated.apiKey,\n endpoint: validated.endpoint,\n debug: validated.debug,\n dashboardUrl: validated.dashboardUrl,\n });\n\n state = {\n config: validated,\n client,\n persona: validated.persona ?? null,\n outcomeHook: validated.outcomeHook ?? null,\n sessions: new Map(),\n signatureMatchers: new Map(),\n preSessionBuffer: new Map(),\n };\n\n if (validated.persona?.signaturePhrases) {\n state.signatureMatchers.set(\n validated.persona.slug,\n compileSignaturePhrases(validated.persona.signaturePhrases as SignaturePhrase[]),\n );\n }\n\n registerAllInstrumentations(state, (turn) => this.captureTurn(turn));\n }\n\n /**\n * Run a callback inside a session context. Every LLM call made inside `fn`\n * (through any instrumented library: OpenAI, Anthropic, LangChain, Vercel\n * AI SDK, etc.) is automatically tagged with `sessionId` and captured as\n * a turn on that session.\n *\n * Under the hood, this uses OTel Baggage propagation; the shared span\n * processor reads the session ID from baggage when each LLM span ends.\n */\n static async withSession<T>(sessionId: string, fn: () => T | Promise<T>): Promise<T> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] withSession called before init');\n return fn();\n }\n return withSessionContext(sessionId, fn);\n }\n\n /**\n * Identify the process-level default persona. Overwrites any previously-set\n * default. For per-session persona identification (multi-persona products),\n * use startSession({ externalId, persona }) instead.\n */\n static identifyPersona(persona: PersonaConfig): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] identifyPersona called before init');\n return;\n }\n state.persona = persona;\n if (persona.signaturePhrases) {\n state.signatureMatchers.set(\n persona.slug,\n compileSignaturePhrases(persona.signaturePhrases as SignaturePhrase[]),\n );\n }\n }\n\n /**\n * Start (or update) a session with an active persona.\n *\n * Single-persona deployments can skip this if the init-level default is\n * enough; the SDK will still create a session entry lazily on first turn.\n * Multi-persona products call this at conversation start so every turn in\n * the session inherits the selected persona.\n *\n * Idempotent: calling with the same externalId updates the entry.\n */\n static startSession(input: SessionStart): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] startSession called before init');\n return;\n }\n const validated = SessionStartSchema.parse(input);\n const existing = state.sessions.get(validated.externalId);\n const now = Date.now();\n const session: SessionState = {\n externalId: validated.externalId,\n externalUserId: validated.externalUserId ?? existing?.externalUserId ?? null,\n turnIndex: existing?.turnIndex ?? 0,\n startedAt: existing?.startedAt ?? now,\n personaSlug: validated.persona ?? existing?.personaSlug ?? state.persona?.slug ?? null,\n metadata: validated.metadata ?? existing?.metadata ?? null,\n openedVia: validated.openedVia ?? existing?.openedVia ?? null,\n clientContext: validated.clientContext ?? existing?.clientContext ?? null,\n agentId: validated.agentId ?? existing?.agentId ?? null,\n experimentId: validated.experimentId ?? existing?.experimentId ?? null,\n environmentConfigHash:\n validated.environmentConfigHash ?? existing?.environmentConfigHash ?? null,\n environmentConfigLabel:\n validated.environmentConfigLabel ?? existing?.environmentConfigLabel ?? null,\n lastAgentTurnAt: existing?.lastAgentTurnAt ?? null,\n lastUserSubmitAt: existing?.lastUserSubmitAt ?? null,\n sessionContextForwarded: existing?.sessionContextForwarded ?? false,\n pendingUserInput: existing?.pendingUserInput ?? null,\n pendingUserOutcome: existing?.pendingUserOutcome ?? null,\n };\n this.flushPreSessionSignals(validated.externalId, session);\n state.sessions.set(validated.externalId, session);\n }\n\n /**\n * Move buffered pre-session interaction signals (recorded before any\n * session entry existed for this externalId) onto the session entry.\n * Session-held values win: buffered signals predate anything recorded\n * after the entry existed.\n */\n private static flushPreSessionSignals(externalId: string, session: SessionState): void {\n if (state === null) return;\n const buffered = state.preSessionBuffer.get(externalId);\n if (!buffered) return;\n state.preSessionBuffer.delete(externalId);\n session.pendingUserInput = session.pendingUserInput ?? buffered.pendingUserInput;\n session.pendingUserOutcome = session.pendingUserOutcome ?? buffered.pendingUserOutcome;\n session.lastUserSubmitAt = session.lastUserSubmitAt ?? buffered.lastUserSubmitAt;\n }\n\n /**\n * Get or create the pre-session signal buffer entry for an externalId.\n * FIFO-capped: when a new id would exceed PRE_SESSION_BUFFER_MAX, the\n * oldest id is dropped (Map preserves insertion order).\n */\n private static preSessionEntry(externalId: string): PreSessionSignals {\n // Callers check state !== null before calling.\n const buffer = state!.preSessionBuffer;\n const existing = buffer.get(externalId);\n if (existing) return existing;\n if (buffer.size >= PRE_SESSION_BUFFER_MAX) {\n const oldest = buffer.keys().next().value;\n if (oldest !== undefined) buffer.delete(oldest);\n }\n const entry: PreSessionSignals = {\n pendingUserInput: null,\n pendingUserOutcome: null,\n lastUserSubmitAt: null,\n };\n buffer.set(externalId, entry);\n return entry;\n }\n\n /**\n * Compute a stable SHA-256 hex hash of prompt/config text for use as\n * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —\n * pass the human-readable version alongside as `environmentConfigLabel`\n * for the diff table axis (a card keyed by a3f9c2… is unreadable).\n *\n * Ships as a helper because inconsistent hashing across restarts breaks\n * Chapter 8e′ Card 3 (version behavioral diff) — every customer would\n * hash their own way and version-diff would become noise.\n *\n * The same hashing (src/hash.ts) backs the OTel processor's automatic\n * version stamping: when autocapture sees a system message and the\n * deployer set no environmentConfigHash, the session is stamped with\n * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit\n * startSession values always win over the auto stamp.\n */\n static async hashEnvironmentConfig(input: string): Promise<string> {\n return hashEnvironmentConfig(input);\n }\n\n /**\n * End a session and release its in-memory entry. Optional (sessions time out\n * eventually), but recommended for long-running processes with many distinct\n * conversations. If `input.endedReason` is provided the SDK sends an end\n * event to ingest so the worker records the reason server-side.\n *\n * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`\n * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`\n * and, when it returns a non-null OutcomeResult, lands it as an outcome\n * event (kind = result.outcome, detail carries type/value). This is the\n * ONLY place the SDK invokes the hook — there are no client-side timers,\n * so sessions that are never ended explicitly are swept server-side as\n * `timeout` and receive no hook-resolved outcome; land those via\n * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:\n * a throwing or rejecting hook never breaks endSession.\n */\n static async endSession(externalId: string | SessionEndInput): Promise<void> {\n if (state === null) return;\n const externalIdStr = typeof externalId === 'string' ? externalId : externalId.externalId;\n const endedReason = typeof externalId === 'string' ? undefined : externalId.endedReason;\n if (state.outcomeHook) {\n try {\n const result = await state.outcomeHook.resolve(externalIdStr);\n // Re-check state: a shutdown() during a slow resolve drops the send.\n if (result && state !== null) {\n await this.emitOutcomeEvent({\n sessionExternalId: externalIdStr,\n kind: result.outcome,\n detail: {\n type: result.type,\n value: result.value,\n resolvedBy: 'outcome_hook',\n },\n });\n }\n } catch (err: unknown) {\n // eslint-disable-next-line no-console\n console.warn(\n '[probe] outcome hook resolve failed:',\n err instanceof Error ? err.message : err,\n );\n }\n }\n if (state === null) return;\n if (endedReason) {\n await state.client\n .sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason })\n .catch((err: unknown) => {\n // eslint-disable-next-line no-console\n console.warn('[probe] sendSessionEnd failed:', err instanceof Error ? err.message : err);\n });\n }\n state.sessions.delete(externalIdStr);\n }\n\n // ── User-side helpers (P1 per PLAN-2026-07-11) ─────────────────────────\n // These accumulate user-side signals during a turn; captureTurn folds the\n // accumulated state into TurnInput.userInput / userOutcome before send.\n // Signals that arrive before any session entry exists (typing starts\n // before startSession or the first LLM call) buffer per externalId and\n // flush into the session when it is created.\n\n /**\n * User started typing — records the first-keystroke timestamp for\n * probe_user_first_keystroke_ms derivation on captureTurn. Derivable\n * only once a previous agent turn exists; a pre-session typing start\n * buffers the pending-input entry without a firstKeystrokeMs value.\n */\n static userInputStart(externalId: string): void {\n if (state === null) return;\n const session = state.sessions.get(externalId);\n const target = session ?? this.preSessionEntry(externalId);\n const now = Date.now();\n const firstKeystrokeMs =\n session?.lastAgentTurnAt != null ? Math.max(0, now - session.lastAgentTurnAt) : undefined;\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n firstKeystrokeMs: target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs,\n };\n }\n\n /**\n * User pressed backspace / edited — increments edit_count for\n * probe_user_reply_edit_count.\n */\n static userInputEdit(externalId: string): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n editCount: (target.pendingUserInput?.editCount ?? 0) + 1,\n };\n }\n\n /**\n * User submitted their reply. Records the text (Presidio-scrubbed\n * server-side before landing on probe_user_reply_text) plus the submit\n * timestamp, which captureTurn uses to derive probe_agent_reflect_ms\n * (submit → next agent turn) and probe_transition_time_ms (previous\n * agent turn → submit).\n */\n static userInputSubmit(externalId: string, text: string): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n const now = Date.now();\n target.pendingUserInput = {\n ...(target.pendingUserInput ?? { editCount: 0 }),\n text,\n submittedAt: now,\n };\n target.lastUserSubmitAt = now;\n }\n\n /** Attach a thumbs-up/down to the current turn. */\n static userThumbs(externalId: string, thumbs: 'up' | 'down'): void {\n if (state === null) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserOutcome = {\n ...(target.pendingUserOutcome ?? {}),\n thumbs,\n };\n }\n\n /** Attach an explicit 1-5 rating to the current turn. */\n static userRating(externalId: string, rating: number): void {\n if (state === null) return;\n if (rating < 1 || rating > 5 || !Number.isInteger(rating)) return;\n const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);\n target.pendingUserOutcome = {\n ...(target.pendingUserOutcome ?? {}),\n explicitRating: rating,\n };\n }\n\n /**\n * Helper: collect client context and pass it to startSession in one call.\n */\n static startSessionWithContext(\n input: SessionStart,\n includes?: ClientContextIncludes,\n ): void {\n this.startSession({\n ...input,\n clientContext: input.clientContext ?? collectClientContext(includes),\n });\n }\n\n /**\n * Register the outcome hook: declares the deployment's outcome type and\n * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked\n * by endSession() — explicit close is the only trigger; the SDK runs no\n * client-side timers. A non-null OutcomeResult lands as an outcome event\n * on the session. Sessions that are never ended explicitly are swept\n * server-side and never resolve through the hook; land those outcomes via\n * emitOutcomeEvent() from the place where the outcome becomes known\n * (webhook, CRM callback); it joins back by sessionExternalId.\n */\n static wireOutcomeHook(hook: OutcomeHook): void {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] wireOutcomeHook called before init');\n return;\n }\n state.outcomeHook = hook;\n }\n\n /**\n * Manually capture a turn. Instrumentation adapters call this internally;\n * exposed for advanced customers who want to bypass autocapture.\n *\n * Persona resolution order for the outgoing turn payload:\n * 1. turn.personaSlug (turn-level override)\n * 2. sessions[externalId].personaSlug (from startSession)\n * 3. state.persona.slug (init-level default)\n *\n * Signature-phrase matching runs at the SDK edge when the resolved persona\n * has signature phrases registered. The matched slug list is attached to\n * `turn.signaturePhraseMatches` before send.\n */\n static async captureTurn(turn: CapturedTurn): Promise<void> {\n if (state === null) {\n return;\n }\n if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {\n return;\n }\n\n // ── Amendment S (2026-07-14): post-guardrail propensity validator ──\n // If the payload includes propensity data (customer running an OPE-\n // bearing deployment), validate the contract per Saito 2021 OBP.\n // Log-and-strip on failure — descriptive-half records still ingest,\n // but the malformed propensity payload does not corrupt downstream\n // OPE. Do NOT block turn capture; the point is honest logging, not\n // customer-blocking.\n const propensity =\n turn.propensity ?? (turn.payload as { propensity?: PropensityInput }).propensity;\n let validPropensity: PropensityInput | undefined = propensity;\n if (propensity) {\n const contract = validatePropensityContract(propensity);\n if (!contract.ok) {\n // eslint-disable-next-line no-console\n console.warn(\n `[probe] Amendment S contract violation (${contract.class}): ${contract.reason}`,\n );\n // Strip malformed propensity from payload; keep the record.\n (turn.payload as { propensity?: PropensityInput }).propensity = undefined;\n validPropensity = undefined;\n }\n }\n\n const sessionPersona = state.sessions.get(turn.sessionExternalId)?.personaSlug ?? null;\n const resolvedPersona =\n turn.personaSlug ?? sessionPersona ?? state.persona?.slug ?? undefined;\n\n let signatureMatches = turn.signaturePhraseMatches;\n if (!signatureMatches && resolvedPersona) {\n 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 }\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 state.sessions.set(turn.sessionExternalId, session);\n }\n // Pre-session interaction signals (typing that started before the\n // session entry existed, including entries lazily created by the OTel\n // processor) flush here, on the turn that creates the session.\n this.flushPreSessionSignals(turn.sessionExternalId, session);\n\n let userInput: CapturedTurn['userInput'] = turn.userInput;\n let userOutcome: CapturedTurn['userOutcome'] = turn.userOutcome;\n let interactivity: CapturedTurn['interactivity'] = turn.interactivity;\n let transition: CapturedTurn['transition'] = turn.transition;\n if (session.pendingUserInput && !userInput) {\n const p = session.pendingUserInput;\n userInput = {\n text: p.text,\n firstKeystrokeMs: p.firstKeystrokeMs,\n editCount: p.editCount,\n submittedAt: p.submittedAt ? new Date(p.submittedAt).toISOString() : undefined,\n };\n }\n if (session.pendingUserOutcome && !userOutcome) {\n userOutcome = session.pendingUserOutcome;\n }\n // Agent reflect ms: time between user submit (session.lastUserSubmitAt)\n // and now (the moment we're capturing this new agent turn).\n if (!interactivity && session.lastUserSubmitAt) {\n interactivity = {\n agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt),\n };\n }\n // Transition time ms: gap between the previous agent turn's capture\n // and the user submit that led to THIS turn. Derivable only when both\n // timestamps exist: pendingUserInput.submittedAt is per-turn (reset on\n // every capture), so a submit from an earlier turn can never be\n // reused. Left unset otherwise — no guessing.\n const submittedAt = session.pendingUserInput?.submittedAt;\n if (\n !transition &&\n session.lastAgentTurnAt !== null &&\n submittedAt !== undefined &&\n submittedAt >= session.lastAgentTurnAt\n ) {\n transition = { timeMs: submittedAt - session.lastAgentTurnAt };\n }\n // Session context (openedVia / clientContext / metadata) rides the\n // first captured turn only; the worker persists it at session\n // find-or-create and ignores it on later turns. metadata merges into\n // clientContext under the `metadata` key so it lands on\n // sessions.probe_session_client_context.\n let openedVia: CapturedTurn['openedVia'];\n let clientContext: CapturedTurn['clientContext'];\n if (!session.sessionContextForwarded) {\n openedVia = (session.openedVia as CapturedTurn['openedVia']) ?? undefined;\n clientContext =\n session.clientContext || session.metadata\n ? {\n ...(session.clientContext ?? {}),\n ...(session.metadata ? { metadata: session.metadata } : {}),\n }\n : undefined;\n session.sessionContextForwarded = true;\n }\n // Reset per-turn pending state now that we've folded it.\n session.pendingUserInput = null;\n session.pendingUserOutcome = null;\n session.lastAgentTurnAt = Date.now();\n\n await state.client.sendTurn({\n ...turn,\n personaSlug: resolvedPersona,\n signaturePhraseMatches: signatureMatches,\n // User identity from the local session entry (Probe.startSession).\n // The worker persists it on sessions.external_user_id; never the\n // session key. Turn-level override wins for advanced callers.\n externalUserId: turn.externalUserId ?? session.externalUserId ?? undefined,\n userInput,\n userOutcome,\n interactivity,\n transition,\n openedVia,\n clientContext,\n // Hoist validated propensity to the top-level TurnInput field: the\n // worker projection reads input.propensity (not payload.propensity)\n // when landing read_candidates / read_propensities / selection_meta\n // columns (e2e audit 2026-07-13).\n propensity: validPropensity,\n // Forward RLDS provenance from the local session entry (populated\n // by Probe.startSession). Worker persists at first-turn session\n // create; nulls stay null. Amendment R populater 2026-07-11.\n agentId: session.agentId ?? undefined,\n experimentId: session.experimentId ?? undefined,\n environmentConfigHash: session.environmentConfigHash ?? undefined,\n environmentConfigLabel: session.environmentConfigLabel ?? undefined,\n });\n }\n\n /**\n * Emit a custom outcome event on a session. Populates probe_outcome_events\n * with the customer-supplied `kind` string (Amendment I Method D). Use for\n * customer-defined kinds like \"purchase_complete\", \"handoff_to_human\",\n * \"character_break_severe\". Universal seed kinds (break, escalation,\n * resolution, thumbs_*, rating_*) are also emitted by worker-side\n * detectors automatically — call this only when the customer has a\n * signal the worker cannot infer.\n */\n static async emitOutcomeEvent(input: OutcomeEventEmit): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] emitOutcomeEvent called before init');\n return;\n }\n const validated = OutcomeEventEmitSchema.parse(input);\n await state.client.sendOutcomeEvent(state.config.deployment, validated);\n }\n\n /**\n * Flag a persona break for a session. Wire this to the customer's in-product\n * \"that didn't sound like you\" UX. Populates the `user_flagged_break`\n * outcome column in Chapter 9c.\n *\n * If `turnIndex` is omitted, the flag attaches to the session's most\n * recent turn.\n */\n static async flagPersonaBreak(input: FlagPersonaBreakInput): Promise<void> {\n if (state === null) {\n // eslint-disable-next-line no-console\n console.warn('[probe] flagPersonaBreak called before init');\n return;\n }\n const validated = FlagPersonaBreakSchema.parse(input);\n await state.client.sendFlag(state.config.deployment, validated);\n }\n\n /**\n * Best-effort extraction of the response text from a captured turn's payload\n * for signature-phrase matching. Adapters populate `payload.response.text`\n * or `payload.text` by convention; this method looks for both.\n */\n private static extractTextForMatching(payload: Record<string, unknown>): string {\n const response = payload['response'];\n if (response && typeof response === 'object') {\n const responseText = (response as Record<string, unknown>)['text'];\n if (typeof responseText === 'string') return responseText;\n }\n if (typeof payload['text'] === 'string') return payload['text'] as string;\n return '';\n }\n\n /**\n * Shut down the SDK: discards the singleton state (sessions, pending\n * user-side signals, the pre-session buffer) so init() can be called\n * again. There is no send queue to flush — every capture awaits its own\n * HTTP send — and instrumentation stays registered for the life of the\n * process. Idempotent.\n */\n static async shutdown(): Promise<void> {\n if (state === null) {\n return;\n }\n state = null;\n }\n\n // ── Internal helpers ─────────────────────────────────────────────────────\n\n /** Package-internal: instrumentation adapters read this to build turns. */\n static _getState(): ProbeState | null {\n return state;\n }\n\n private static shouldSample(sessionId: string, turnIndex: number): boolean {\n if (state === null) return false;\n const rate = state.config.sampleRate;\n if (rate >= 1.0) return true;\n if (rate <= 0.0) return false;\n // Deterministic hash so a given (sessionId, turnIndex) always resolves identically.\n // FNV-1a 32-bit for portability across runtimes.\n const key = `${sessionId}:${turnIndex}`;\n let hash = 0x811c9dc5;\n for (let i = 0; i < key.length; i++) {\n hash ^= key.charCodeAt(i);\n hash = (hash * 0x01000193) >>> 0;\n }\n return hash / 0xffffffff < rate;\n }\n}\n"]}
|