@cultured_computer/sight 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1478 @@
1
+ import { z } from 'zod';
2
+ import { propagation, context, trace } from '@opentelemetry/api';
3
+
4
+ // src/client.ts
5
+ var IngestClient = class {
6
+ apiKey;
7
+ endpoint;
8
+ debug;
9
+ constructor(opts) {
10
+ this.apiKey = opts.apiKey;
11
+ this.endpoint = opts.endpoint.replace(/\/$/, "");
12
+ this.debug = opts.debug;
13
+ }
14
+ /**
15
+ * Send a turn to the ingest API. Fire-and-log: errors are logged but never
16
+ * thrown. The customer's LLM path never blocks on the Probe.
17
+ */
18
+ async sendTurn(turn) {
19
+ try {
20
+ const response = await fetch(`${this.endpoint}/v1/turns`, {
21
+ method: "POST",
22
+ headers: {
23
+ Authorization: `Bearer ${this.apiKey}`,
24
+ "content-type": "application/json"
25
+ },
26
+ body: JSON.stringify(turn)
27
+ });
28
+ if (!response.ok) {
29
+ this.log(`[probe] ingest failed status=${response.status}`);
30
+ return;
31
+ }
32
+ if (this.debug) {
33
+ const body = await response.json();
34
+ this.log(`[probe] ingest ok id=${body.pendingId ?? "?"}`);
35
+ }
36
+ } catch (err) {
37
+ const msg = err instanceof Error ? err.message : String(err);
38
+ this.log(`[probe] ingest error: ${msg}`);
39
+ }
40
+ }
41
+ /**
42
+ * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.
43
+ * Populates the `user_flagged_break` outcome column in Chapter 9c.
44
+ */
45
+ async sendFlag(deploymentSlug, flag) {
46
+ try {
47
+ const response = await fetch(`${this.endpoint}/v1/flags`, {
48
+ method: "POST",
49
+ headers: {
50
+ Authorization: `Bearer ${this.apiKey}`,
51
+ "content-type": "application/json"
52
+ },
53
+ body: JSON.stringify({
54
+ deploymentSlug,
55
+ sessionExternalId: flag.sessionExternalId,
56
+ flagType: "persona_break",
57
+ note: flag.note,
58
+ turnIndex: flag.turnIndex
59
+ })
60
+ });
61
+ if (!response.ok) {
62
+ this.log(`[probe] flag ingest failed status=${response.status}`);
63
+ return;
64
+ }
65
+ if (this.debug) {
66
+ this.log(`[probe] flag ingest ok session=${flag.sessionExternalId}`);
67
+ }
68
+ } catch (err) {
69
+ const msg = err instanceof Error ? err.message : String(err);
70
+ this.log(`[probe] flag ingest error: ${msg}`);
71
+ }
72
+ }
73
+ /**
74
+ * Send a session-end event to the ingest API. Records why a session ended
75
+ * on the sessions.probe_session_ended_reason column. Fire-and-log.
76
+ */
77
+ async sendSessionEnd(deploymentSlug, end) {
78
+ try {
79
+ const response = await fetch(`${this.endpoint}/v1/sessions/end`, {
80
+ method: "POST",
81
+ headers: {
82
+ Authorization: `Bearer ${this.apiKey}`,
83
+ "content-type": "application/json"
84
+ },
85
+ body: JSON.stringify({
86
+ deploymentSlug,
87
+ sessionExternalId: end.externalId,
88
+ endedReason: end.endedReason
89
+ })
90
+ });
91
+ if (!response.ok) {
92
+ this.log(`[probe] session-end ingest failed status=${response.status}`);
93
+ return;
94
+ }
95
+ if (this.debug) {
96
+ this.log(`[probe] session-end ingest ok session=${end.externalId}`);
97
+ }
98
+ } catch (err) {
99
+ const msg = err instanceof Error ? err.message : String(err);
100
+ this.log(`[probe] session-end ingest error: ${msg}`);
101
+ }
102
+ }
103
+ /**
104
+ * Send an outcome event to the ingest API. Fire-and-log. Populates
105
+ * probe_outcome_events per Amendment I Method D.
106
+ */
107
+ async sendOutcomeEvent(deploymentSlug, event) {
108
+ try {
109
+ const response = await fetch(`${this.endpoint}/v1/outcome-events`, {
110
+ method: "POST",
111
+ headers: {
112
+ Authorization: `Bearer ${this.apiKey}`,
113
+ "content-type": "application/json"
114
+ },
115
+ body: JSON.stringify({
116
+ deploymentSlug,
117
+ sessionExternalId: event.sessionExternalId,
118
+ kind: event.kind,
119
+ detectedBy: "sdk_custom",
120
+ causingTurnIndex: event.causingTurnIndex,
121
+ detail: event.detail
122
+ })
123
+ });
124
+ if (!response.ok) {
125
+ this.log(`[probe] outcome-event ingest failed status=${response.status}`);
126
+ return;
127
+ }
128
+ if (this.debug) {
129
+ this.log(
130
+ `[probe] outcome-event ingest ok session=${event.sessionExternalId} kind=${event.kind}`
131
+ );
132
+ }
133
+ } catch (err) {
134
+ const msg = err instanceof Error ? err.message : String(err);
135
+ this.log(`[probe] outcome-event ingest error: ${msg}`);
136
+ }
137
+ }
138
+ log(msg) {
139
+ if (this.debug) {
140
+ console.error(msg);
141
+ }
142
+ }
143
+ };
144
+ var SignaturePhraseSchema = z.union([
145
+ z.object({
146
+ slug: z.string().min(1),
147
+ phrase: z.string().min(1),
148
+ description: z.string().optional()
149
+ }),
150
+ z.object({
151
+ slug: z.string().min(1),
152
+ regex: z.string().min(1),
153
+ flags: z.string().optional(),
154
+ description: z.string().optional()
155
+ })
156
+ ]);
157
+ var PersonaConfigSchema = z.object({
158
+ /** Persona slug matching the deployment's registered persona. */
159
+ slug: z.string().min(1),
160
+ /**
161
+ * RICE authorship artifact (Role, Identity, Communication, Engagement).
162
+ * Either inline object or a path/URL to a JSON file loaded at init time.
163
+ */
164
+ rice: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),
165
+ /**
166
+ * Customer-authored signature phrases for this persona. Compiled once at
167
+ * init and matched per turn at the SDK edge; matched slugs appear on the
168
+ * outgoing turn as `signaturePhraseMatches`.
169
+ */
170
+ signaturePhrases: z.array(SignaturePhraseSchema).optional()
171
+ });
172
+ var OutcomeHookSchema = z.object({
173
+ /** Type of outcome the deployment tracks. */
174
+ type: z.enum(["numeric", "categorical", "boolean", "duration"]),
175
+ /** Callback that resolves the outcome for a completed session. */
176
+ resolve: z.custom()
177
+ });
178
+ var ProbeConfigSchema = z.object({
179
+ /** Unkey ingest key. Required. */
180
+ apiKey: z.string().min(1),
181
+ /** Deployment slug registered in the Probe backend. Required. */
182
+ deployment: z.string().min(1),
183
+ /** Ingest endpoint. Defaults to https://ingest.probe.io. */
184
+ endpoint: z.string().url().default("https://ingest.probe.io"),
185
+ /** Persona identification. Optional at init; can be set later via identifyPersona(). */
186
+ persona: PersonaConfigSchema.optional(),
187
+ /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */
188
+ outcomeHook: OutcomeHookSchema.optional(),
189
+ /**
190
+ * Sample rate for autocapture. 1.0 = 100% of calls captured. Lower values
191
+ * sample deterministically so a given (turnId) always resolves identically.
192
+ */
193
+ sampleRate: z.number().min(0).max(1).default(1),
194
+ /**
195
+ * Debug mode: log every captured turn to stderr with a prefix. Never logs
196
+ * the Bearer token or PII.
197
+ */
198
+ debug: z.boolean().default(false)
199
+ });
200
+ var SessionStartSchema = z.object({
201
+ /** Customer's session identity (opaque string; used as the correlation key). */
202
+ externalId: z.string().min(1),
203
+ /**
204
+ * Customer's USER identity (opaque string), distinct from externalId:
205
+ * externalId keys the session; externalUserId ties sessions to a
206
+ * returning user. Forwarded on every captured turn so the worker can
207
+ * persist it on the session row — return-with-persona-consistency and
208
+ * prior-session metrics require it. Optional; deployments that do not
209
+ * identify users simply skip the user-level return metrics.
210
+ */
211
+ externalUserId: z.string().min(1).optional(),
212
+ /**
213
+ * Persona slug active for this session. Overrides the init-level default.
214
+ * Required for multi-persona deployments; optional for single-persona
215
+ * deployments where init already carries the persona.
216
+ */
217
+ persona: z.string().min(1).optional(),
218
+ /**
219
+ * How the user got into this session (P2 per PLAN-2026-07-11).
220
+ * Retention semantics differ radically between a resume and a fresh
221
+ * notification landing.
222
+ */
223
+ openedVia: z.enum(["link", "notification", "resume", "direct", "share"]).optional(),
224
+ /**
225
+ * Environmental context — browser / device / locale / tz (P2). Customer-
226
+ * configurable which fields to include. See collectClientContext helper.
227
+ */
228
+ clientContext: z.record(z.string(), z.unknown()).optional(),
229
+ /**
230
+ * Optional customer metadata attached to the session. Forwarded with the
231
+ * first captured turn merged into `clientContext` under the `metadata`
232
+ * key, so it lands on sessions.probe_session_client_context.
233
+ */
234
+ metadata: z.record(z.string(), z.unknown()).optional(),
235
+ /**
236
+ * RLDS episode-level provenance (Amendment R populater 2026-07-11).
237
+ * Powers Chapter 8e′ Card 3 version behavioral diff. All optional.
238
+ * agentId — model/policy version
239
+ * experimentId — A/B arm or feature flag
240
+ * environmentConfigHash — SHA of prompt/config file(s)
241
+ * environmentConfigLabel — human-readable version label
242
+ */
243
+ agentId: z.string().optional(),
244
+ experimentId: z.string().optional(),
245
+ environmentConfigHash: z.string().optional(),
246
+ environmentConfigLabel: z.string().optional()
247
+ });
248
+ z.object({
249
+ externalId: z.string().min(1),
250
+ endedReason: z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional()
251
+ });
252
+ var FlagPersonaBreakSchema = z.object({
253
+ sessionExternalId: z.string().min(1),
254
+ note: z.string().optional(),
255
+ /** Turn index the flag refers to. Omit to attach to the session's latest turn. */
256
+ turnIndex: z.number().int().nonnegative().optional()
257
+ });
258
+ var OutcomeEventEmitSchema = z.object({
259
+ sessionExternalId: z.string().min(1),
260
+ kind: z.string().min(1),
261
+ /** Optional turn index this event is caused by. Omit to attach to latest turn. */
262
+ causingTurnIndex: z.number().int().nonnegative().optional(),
263
+ /** Optional detail payload (customer-defined). */
264
+ detail: z.record(z.string(), z.unknown()).optional()
265
+ });
266
+
267
+ // src/client-context.ts
268
+ var DEFAULT_INCLUDES = {
269
+ locale: true,
270
+ timezone: true,
271
+ runtime: true
272
+ };
273
+ function collectClientContext(includes = DEFAULT_INCLUDES) {
274
+ const out = {};
275
+ const globalAny = globalThis;
276
+ const win = globalAny.window;
277
+ const isBrowser = typeof win !== "undefined" && typeof win?.navigator !== "undefined";
278
+ if (isBrowser && win) {
279
+ const nav = win.navigator;
280
+ if (includes.userAgent) out["userAgent"] = nav?.userAgent;
281
+ if (includes.locale) {
282
+ out["locale"] = nav?.language;
283
+ if (nav?.languages) out["languages"] = [...nav.languages];
284
+ }
285
+ if (includes.timezone) {
286
+ try {
287
+ out["timezone"] = Intl.DateTimeFormat().resolvedOptions().timeZone;
288
+ } catch {
289
+ }
290
+ }
291
+ if (includes.screen && win.screen) {
292
+ out["screen"] = { width: win.screen.width, height: win.screen.height };
293
+ }
294
+ out["agent"] = "browser";
295
+ } else if (typeof process !== "undefined" && typeof process.versions !== "undefined") {
296
+ if (includes.locale) {
297
+ const lang = process.env["LANG"] || process.env["LC_ALL"] || null;
298
+ if (lang) out["locale"] = lang.split(".")[0];
299
+ }
300
+ if (includes.timezone) {
301
+ try {
302
+ out["timezone"] = Intl.DateTimeFormat().resolvedOptions().timeZone;
303
+ } catch {
304
+ }
305
+ }
306
+ if (includes.runtime) {
307
+ out["runtime"] = {
308
+ platform: process.platform,
309
+ node: process.versions.node
310
+ };
311
+ }
312
+ out["agent"] = "node";
313
+ }
314
+ if (includes.custom) {
315
+ for (const [k, v] of Object.entries(includes.custom)) out[k] = v;
316
+ }
317
+ return out;
318
+ }
319
+ var SESSION_BAGGAGE_KEY = "probe.session_id";
320
+ var contextManagerRegistered = false;
321
+ async function ensureContextManager() {
322
+ if (contextManagerRegistered) return;
323
+ contextManagerRegistered = true;
324
+ try {
325
+ const mod = await import('@opentelemetry/context-async-hooks');
326
+ const cm = new mod.AsyncLocalStorageContextManager();
327
+ cm.enable();
328
+ context.setGlobalContextManager(cm);
329
+ } catch {
330
+ }
331
+ }
332
+ async function withSession(sessionId, fn) {
333
+ await ensureContextManager();
334
+ const currentBaggage = propagation.getBaggage(context.active());
335
+ const nextBaggage = (currentBaggage ?? propagation.createBaggage()).setEntry(
336
+ SESSION_BAGGAGE_KEY,
337
+ { value: sessionId }
338
+ );
339
+ const nextContext = propagation.setBaggage(context.active(), nextBaggage);
340
+ return context.with(nextContext, fn);
341
+ }
342
+ function getCurrentSessionId() {
343
+ const baggage = propagation.getBaggage(context.active());
344
+ return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;
345
+ }
346
+
347
+ // src/instrumentation/otel-processor.ts
348
+ var DEDUP_TTL_MS = 5e3;
349
+ var dedupCache = /* @__PURE__ */ new Map();
350
+ function shouldSkipAsDuplicate(traceId) {
351
+ const now = Date.now();
352
+ const seenAt = dedupCache.get(traceId);
353
+ if (seenAt !== void 0 && now - seenAt < DEDUP_TTL_MS) {
354
+ return true;
355
+ }
356
+ dedupCache.set(traceId, now);
357
+ if (dedupCache.size > 1e3) {
358
+ for (const [k, v] of dedupCache) {
359
+ if (now - v > DEDUP_TTL_MS) dedupCache.delete(k);
360
+ }
361
+ }
362
+ return false;
363
+ }
364
+ function attr(attrs, key) {
365
+ return attrs[key];
366
+ }
367
+ function asString(v) {
368
+ return typeof v === "string" ? v : void 0;
369
+ }
370
+ function asNumber(v) {
371
+ return typeof v === "number" ? v : void 0;
372
+ }
373
+ function asStringArray(v) {
374
+ return Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
375
+ }
376
+ function isLLMCall(attrs) {
377
+ const op = asString(attrs["gen_ai.operation.name"]);
378
+ if (op === "chat" || op === "text_completion" || op === "embeddings") {
379
+ return true;
380
+ }
381
+ const traceloopKind = asString(attrs["traceloop.span.kind"]);
382
+ if (traceloopKind === "agent") return true;
383
+ return false;
384
+ }
385
+ function isVercelAgentRollup(spanName, attrs) {
386
+ return spanName.startsWith("invoke_agent ") && attrs["ai.telemetry.functionId"] !== void 0;
387
+ }
388
+ function taggedProvider(attrs) {
389
+ const rawProvider = asString(attrs["gen_ai.system"] ?? attrs["gen_ai.provider"]);
390
+ const model = asString(attrs["gen_ai.request.model"]);
391
+ if (model?.toLowerCase().startsWith("mercury")) {
392
+ return "inception";
393
+ }
394
+ return rawProvider;
395
+ }
396
+ function buildPayload(span) {
397
+ const a = span.attributes;
398
+ const start = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
399
+ const end = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
400
+ const latencyMs = Math.max(0, Math.round(end - start));
401
+ const responseText = asString(attr(a, "ai.response.text")) ?? asString(attr(a, "gen_ai.output.messages"));
402
+ const toolCallNames = asStringArray(attr(a, "gen_ai.response.tool_names"));
403
+ const toolCallsCount = asNumber(attr(a, "gen_ai.response.tool_calls_count")) ?? toolCallNames?.length;
404
+ const finishReasons = asStringArray(attr(a, "gen_ai.response.finish_reasons"));
405
+ const finishReason = finishReasons?.[0];
406
+ const error = span.status.code === 2 ? span.status.message ?? "error" : void 0;
407
+ return {
408
+ // Plumbing (probe_* namespace lands on canonical turns columns per PROBE.md §2).
409
+ probe_tokens_input: asNumber(attr(a, "gen_ai.usage.input_tokens")),
410
+ probe_tokens_output: asNumber(attr(a, "gen_ai.usage.output_tokens")),
411
+ probe_latency_ms: latencyMs,
412
+ probe_model: asString(attr(a, "gen_ai.response.model") ?? attr(a, "gen_ai.request.model")),
413
+ probe_provider: taggedProvider(a),
414
+ probe_tool_calls: toolCallsCount,
415
+ probe_tool_names: toolCallNames,
416
+ probe_error: error,
417
+ probe_finish_reason: finishReason,
418
+ // Response text so the SDK edge signature-phrase matcher has something to
419
+ // match against; the server-side redactor scrubs PII on the Tier 1 →
420
+ // Tier 2 boundary.
421
+ response: responseText ? { text: responseText } : void 0,
422
+ // Anthropic cache tokens (per research report), promoted so the customer
423
+ // can see cache-hit-rate in the dashboard without re-parsing raw messages.
424
+ probe_cache_read_input_tokens: asNumber(attr(a, "gen_ai.usage.cache_read_input_tokens")),
425
+ probe_cache_creation_input_tokens: asNumber(
426
+ attr(a, "gen_ai.usage.cache_creation_input_tokens")
427
+ ),
428
+ // Debug metadata (kept in payload, not projected to canonical columns).
429
+ _otel: {
430
+ spanName: span.name,
431
+ traceId: span.spanContext().traceId,
432
+ spanId: span.spanContext().spanId,
433
+ operationName: asString(attr(a, "gen_ai.operation.name")),
434
+ traceloopKind: asString(attr(a, "traceloop.span.kind"))
435
+ }
436
+ };
437
+ }
438
+ function resolveSessionAndTurn(state2, sessionId) {
439
+ let session = state2.sessions.get(sessionId);
440
+ if (!session) {
441
+ session = {
442
+ externalId: sessionId,
443
+ turnIndex: 0,
444
+ startedAt: Date.now(),
445
+ personaSlug: state2.persona?.slug ?? null
446
+ };
447
+ state2.sessions.set(sessionId, session);
448
+ }
449
+ const turnIndex = session.turnIndex;
450
+ session.turnIndex += 1;
451
+ return {
452
+ sessionExternalId: sessionId,
453
+ turnIndex,
454
+ personaSlug: session.personaSlug ?? state2.persona?.slug ?? null
455
+ };
456
+ }
457
+ var ProbeSpanProcessor = class {
458
+ constructor(state2, captureFn) {
459
+ this.state = state2;
460
+ this.captureFn = captureFn;
461
+ }
462
+ state;
463
+ captureFn;
464
+ onStart(_span, _parentContext) {
465
+ }
466
+ onEnd(span) {
467
+ try {
468
+ const a = span.attributes;
469
+ if (isVercelAgentRollup(span.name, a)) return;
470
+ if (!isLLMCall(a)) return;
471
+ const traceId = span.spanContext().traceId;
472
+ if (shouldSkipAsDuplicate(traceId)) return;
473
+ const sessionId = getCurrentSessionId();
474
+ if (!sessionId) {
475
+ if (this.state.config.debug) {
476
+ console.warn(
477
+ `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`
478
+ );
479
+ }
480
+ return;
481
+ }
482
+ const { sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
483
+ this.state,
484
+ sessionId
485
+ );
486
+ const captured = {
487
+ deploymentSlug: this.state.config.deployment,
488
+ sessionExternalId,
489
+ turnIndex,
490
+ personaSlug: personaSlug ?? void 0,
491
+ payload: buildPayload(span)
492
+ };
493
+ this.captureFn(captured).catch((err) => {
494
+ if (this.state.config.debug) {
495
+ console.error(
496
+ `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
497
+ );
498
+ }
499
+ });
500
+ } catch (err) {
501
+ if (this.state.config.debug) {
502
+ console.error(
503
+ `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`
504
+ );
505
+ }
506
+ }
507
+ }
508
+ shutdown() {
509
+ dedupCache.clear();
510
+ return Promise.resolve();
511
+ }
512
+ forceFlush() {
513
+ return Promise.resolve();
514
+ }
515
+ };
516
+
517
+ // src/instrumentation/setup.ts
518
+ var installedProcessor = null;
519
+ function setupOtelProvider(state2, captureFn) {
520
+ if (installedProcessor !== null) {
521
+ return;
522
+ }
523
+ installedProcessor = new ProbeSpanProcessor(state2, captureFn);
524
+ const currentProvider = trace.getTracerProvider();
525
+ if (typeof currentProvider.addSpanProcessor === "function") {
526
+ currentProvider.addSpanProcessor(installedProcessor);
527
+ return;
528
+ }
529
+ void import('@opentelemetry/sdk-trace-node').then((mod) => {
530
+ const provider = new mod.NodeTracerProvider({
531
+ spanProcessors: [installedProcessor]
532
+ });
533
+ provider.register();
534
+ });
535
+ }
536
+
537
+ // src/instrumentation/openai.ts
538
+ var registered = false;
539
+ var instrumentation = null;
540
+ async function registerOpenAI(state2) {
541
+ if (registered) return;
542
+ try {
543
+ const mod = await import('@traceloop/instrumentation-openai');
544
+ instrumentation = new mod.OpenAIInstrumentation({
545
+ enrichTokens: true,
546
+ exceptionLogger: (err) => {
547
+ if (state2.config.debug) {
548
+ console.error(
549
+ `[probe/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`
550
+ );
551
+ }
552
+ }
553
+ });
554
+ instrumentation.enable();
555
+ registered = true;
556
+ } catch (err) {
557
+ if (state2.config.debug) {
558
+ const msg = err instanceof Error ? err.message : String(err);
559
+ console.warn(`[probe/openai] instrumentation not enabled (${msg}); library not installed?`);
560
+ }
561
+ }
562
+ }
563
+
564
+ // src/instrumentation/anthropic.ts
565
+ var registered2 = false;
566
+ var instrumentation2 = null;
567
+ async function registerAnthropic(state2) {
568
+ if (registered2) return;
569
+ try {
570
+ const mod = await import('@traceloop/instrumentation-anthropic');
571
+ instrumentation2 = new mod.AnthropicInstrumentation({
572
+ exceptionLogger: (err) => {
573
+ if (state2.config.debug) {
574
+ console.error(
575
+ `[probe/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`
576
+ );
577
+ }
578
+ }
579
+ });
580
+ instrumentation2.enable();
581
+ registered2 = true;
582
+ } catch (err) {
583
+ if (state2.config.debug) {
584
+ const msg = err instanceof Error ? err.message : String(err);
585
+ console.warn(
586
+ `[probe/anthropic] instrumentation not enabled (${msg}); library not installed?`
587
+ );
588
+ }
589
+ }
590
+ }
591
+
592
+ // src/instrumentation/langchain.ts
593
+ var registered3 = false;
594
+ var instrumentation3 = null;
595
+ async function registerLangChain(state2) {
596
+ if (registered3) return;
597
+ try {
598
+ const mod = await import('@traceloop/instrumentation-langchain');
599
+ instrumentation3 = new mod.LangChainInstrumentation({
600
+ exceptionLogger: (err) => {
601
+ if (state2.config.debug) {
602
+ console.error(
603
+ `[probe/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`
604
+ );
605
+ }
606
+ }
607
+ });
608
+ instrumentation3.enable();
609
+ registered3 = true;
610
+ } catch (err) {
611
+ if (state2.config.debug) {
612
+ const msg = err instanceof Error ? err.message : String(err);
613
+ console.warn(
614
+ `[probe/langchain] instrumentation not enabled (${msg}); library not installed?`
615
+ );
616
+ }
617
+ }
618
+ }
619
+
620
+ // src/instrumentation/langgraph.ts
621
+ var registered4 = false;
622
+ async function registerLangGraph(state2) {
623
+ if (registered4) return;
624
+ registered4 = true;
625
+ if (state2.config.debug) {
626
+ console.log(
627
+ "[probe/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology"
628
+ );
629
+ }
630
+ }
631
+
632
+ // src/instrumentation/vercel-ai.ts
633
+ var registered5 = false;
634
+ async function registerVercelAI(state2) {
635
+ if (registered5) return;
636
+ registered5 = true;
637
+ if (state2.config.debug) {
638
+ console.log(
639
+ "[probe/vercel-ai] active; customer must set experimental_telemetry: { isEnabled: true } per call"
640
+ );
641
+ }
642
+ }
643
+
644
+ // src/instrumentation/litellm.ts
645
+ var registered6 = false;
646
+ async function registerLiteLLM(state2) {
647
+ if (registered6) return;
648
+ registered6 = true;
649
+ if (state2.config.debug) {
650
+ console.log(
651
+ "[probe/litellm] not captured on SDK side; use the Chapter 4 URL-swap proxy for LiteLLM traffic"
652
+ );
653
+ }
654
+ }
655
+
656
+ // src/instrumentation/mercury.ts
657
+ var registered7 = false;
658
+ async function registerMercury(state2) {
659
+ if (registered7) return;
660
+ registered7 = true;
661
+ if (state2.config.debug) {
662
+ console.log(
663
+ "[probe/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route"
664
+ );
665
+ }
666
+ }
667
+
668
+ // src/instrumentation/index.ts
669
+ function registerAllInstrumentations(state2, captureFn) {
670
+ setupOtelProvider(state2, captureFn);
671
+ const registrations = [
672
+ registerOpenAI(state2),
673
+ registerAnthropic(state2),
674
+ registerLangChain(state2),
675
+ registerLangGraph(state2),
676
+ registerVercelAI(state2),
677
+ registerLiteLLM(state2),
678
+ registerMercury(state2)
679
+ ];
680
+ Promise.allSettled(registrations).then((results) => {
681
+ if (!state2.config.debug) return;
682
+ for (const result of results) {
683
+ if (result.status === "rejected") {
684
+ console.error(`[probe] adapter register rejected: ${result.reason}`);
685
+ }
686
+ }
687
+ });
688
+ }
689
+
690
+ // ../classifier/src/signature-phrase.ts
691
+ function compileSignaturePhrases(phrases) {
692
+ const compiled = [];
693
+ for (const p of phrases) {
694
+ try {
695
+ if ("phrase" in p) {
696
+ const escaped = p.phrase.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
697
+ const startAnchor = /^\w/.test(p.phrase) ? "\\b" : "";
698
+ const endAnchor = /\w$/.test(p.phrase) ? "\\b" : "";
699
+ compiled.push({
700
+ slug: p.slug,
701
+ pattern: new RegExp(`${startAnchor}${escaped}${endAnchor}`, "i")
702
+ });
703
+ } else {
704
+ compiled.push({
705
+ slug: p.slug,
706
+ pattern: new RegExp(p.regex, p.flags ?? "i")
707
+ });
708
+ }
709
+ } catch (err) {
710
+ const msg = err instanceof Error ? err.message : String(err);
711
+ console.warn(`[classifier/signature-phrase] invalid pattern for slug=${p.slug}: ${msg}`);
712
+ }
713
+ }
714
+ return compiled;
715
+ }
716
+ function matchSignaturePhrases(text, compiled) {
717
+ if (!text || compiled.length === 0) return [];
718
+ const matches = [];
719
+ for (const c of compiled) {
720
+ if (c.pattern.test(text)) matches.push(c.slug);
721
+ }
722
+ return matches;
723
+ }
724
+ var REACTION_REGISTERS = ["heavy", "comic", "edge"];
725
+ var InterpretiveRecordSchema = z.object({
726
+ // Open vocabulary: any string tag. Seeds live in GENERAL_SITUATION_TAGS /
727
+ // NARRATIVE_SITUATION_TAGS but ingest never rejects an unseen situation.
728
+ situationType: z.array(z.string()).optional(),
729
+ read: z.string().optional(),
730
+ lensChosen: z.string().optional(),
731
+ reactionRegister: z.enum(REACTION_REGISTERS).optional(),
732
+ reactionNextTurn: z.string().optional()
733
+ });
734
+ var PropensitySchema = z.object({
735
+ candidates: z.array(z.object({ label: z.string(), text: z.string().optional() })).optional(),
736
+ /**
737
+ * Raw model confidence / logprobs / ensemble scores per candidate.
738
+ * Diagnostic only; NOT a propensity unless the harness confirms it is
739
+ * the exact sampling distribution used and passes it also as
740
+ * `propensities`.
741
+ */
742
+ scores: z.array(z.number()).optional(),
743
+ /**
744
+ * Behavior-policy sampling distribution at selection time. Must sum
745
+ * to 1.0 (within float tolerance) if present. Load-bearing for OPE
746
+ * (Dudík, Langford & Li 2011 for per-turn / Jiang & Li 2016 for
747
+ * trajectory). When omitted, OPE is not possible on this turn.
748
+ */
749
+ propensities: z.array(z.number()).optional(),
750
+ selectedIndex: z.number().int().nonnegative().optional(),
751
+ /**
752
+ * Sampling-policy metadata: temperature, top_p, top_k, seed, sampler
753
+ * name, ensemble weights. Required for reviewers to verify that
754
+ * `propensities` is the actual behavior distribution.
755
+ */
756
+ selectionMeta: z.record(z.string(), z.unknown()).optional()
757
+ });
758
+ function validatePropensityContract(p) {
759
+ if (!p) return { ok: true };
760
+ if (!p.propensities || p.propensities.length === 0) return { ok: true };
761
+ const temp = p.selectionMeta?.["temperature"];
762
+ if (typeof temp === "number" && temp === 0) {
763
+ return {
764
+ ok: false,
765
+ class: "zero_support",
766
+ reason: "temperature=0 with propensities logged: deterministic decoding has zero support. OPE is undefined for any counterfactual. Set temperature > 0 or omit propensities."
767
+ };
768
+ }
769
+ const policyVersion = p.selectionMeta?.["policy_version"];
770
+ if (!policyVersion) {
771
+ return {
772
+ ok: false,
773
+ class: "missing_policy_version",
774
+ reason: "propensities logged without selectionMeta.policy_version. IPS/DR require the logging policy be identifiable across replays."
775
+ };
776
+ }
777
+ const sum = p.propensities.reduce((a, b) => a + b, 0);
778
+ if (Math.abs(sum - 1) > 0.02) {
779
+ return {
780
+ ok: false,
781
+ class: "malformed_distribution",
782
+ reason: `propensities sum to ${sum.toFixed(4)}, expected ~1.0. Not a probability distribution; likely raw softmax(logits). A score is not a probability.`
783
+ };
784
+ }
785
+ if (!p.selectionMeta) {
786
+ return {
787
+ ok: false,
788
+ class: "missing_selection_meta",
789
+ reason: "propensities logged without selectionMeta. Reviewers cannot verify propensities is the actual behavior distribution."
790
+ };
791
+ }
792
+ return { ok: true };
793
+ }
794
+ var TransitionSchema = z.object({
795
+ timeMs: z.number().int().nonnegative().optional(),
796
+ lengthDelta: z.number().int().optional()
797
+ });
798
+ var UserInputSchema = z.object({
799
+ /** The user's message text. Presidio-scrubbed server-side before landing on `probe_user_reply_text`. */
800
+ text: z.string().optional(),
801
+ /** Milliseconds between agent response end and user's first keystroke. Client-side UI hook, optional. */
802
+ firstKeystrokeMs: z.number().int().nonnegative().optional(),
803
+ /** Backspace/edit count while typing this reply. Client-side UI hook, optional. */
804
+ editCount: z.number().int().nonnegative().optional(),
805
+ /** Did the user submit before the agent's response finished streaming? */
806
+ interruptedStream: z.boolean().optional(),
807
+ /** Did the user click stop on an agent streaming response mid-flight? */
808
+ cancelledResponse: z.boolean().optional(),
809
+ /** ISO timestamp when the user submitted this reply. */
810
+ submittedAt: z.string().optional()
811
+ });
812
+ var InteractivitySchema = z.object({
813
+ /** Milliseconds between the user's submit and the next agent LLM call. */
814
+ agentReflectMs: z.number().int().nonnegative().optional(),
815
+ /** Did the agent's response stream finish fully (finish_reason='stop')? */
816
+ agentStreamCompleted: z.boolean().optional(),
817
+ /** Multimodal events observed on this turn (image upload, voice snippet, file, etc.). */
818
+ multimodalEvents: z.array(
819
+ z.object({
820
+ kind: z.string(),
821
+ at: z.string().optional(),
822
+ meta: z.record(z.string(), z.unknown()).optional()
823
+ })
824
+ ).optional()
825
+ });
826
+ var UserOutcomeSchema = z.object({
827
+ /**
828
+ * Explicit "that didn't sound like you" flag attached at turn level.
829
+ * DEPRECATED: prefer Probe.flagPersonaBreak(), which routes through the
830
+ * flags ingest path and carries user attribution + a 'break' outcome
831
+ * event. This turn-level boolean remains accepted for wire compat but
832
+ * new integrations should not set it.
833
+ */
834
+ flaggedBreak: z.boolean().optional(),
835
+ /** Rating widget value 1-5, customer-supplied. */
836
+ explicitRating: z.number().int().min(1).max(5).optional(),
837
+ /** Thumbs-up / thumbs-down widget value. */
838
+ thumbs: z.enum(["up", "down"]).optional()
839
+ });
840
+ z.object({
841
+ deploymentSlug: z.string().min(1),
842
+ sessionExternalId: z.string().min(1),
843
+ /**
844
+ * Customer's user identity (opaque string), forwarded by the SDK from
845
+ * Probe.startSession() state on every turn. Distinct from
846
+ * sessionExternalId, which keys the SESSION: the worker persists this on
847
+ * sessions.external_user_id at first-turn session create (falling back to
848
+ * null — never to sessionExternalId) so return-with-persona-consistency
849
+ * and prior-session metrics read a real user identity.
850
+ */
851
+ externalUserId: z.string().min(1).optional(),
852
+ turnIndex: z.number().int().nonnegative(),
853
+ /**
854
+ * Persona slug active for this turn. Customer-supplied (from SDK persona
855
+ * resolution: turn override / session / init default). Optional; deployments
856
+ * with a single registered persona can omit this and the ingest worker
857
+ * backfills from the deployment default at write time.
858
+ */
859
+ personaSlug: z.string().min(1).optional(),
860
+ /**
861
+ * Signature-phrase matches computed at the SDK edge (per PROBE.md §2).
862
+ * List of matched signature-phrase slugs the customer registered via
863
+ * Probe.init({ persona: { signaturePhrases: [...] } }). Empty array or
864
+ * omitted when no signatures matched or the deployment did not register any.
865
+ */
866
+ signaturePhraseMatches: z.array(z.string()).optional(),
867
+ /**
868
+ * Interpretive record fields passed through from a customer harness
869
+ * (Oracle read hook wired). Omitted for deployments not running the harness;
870
+ * server-side classifier workers populate situation_type and reaction_register
871
+ * from the raw payload instead.
872
+ */
873
+ interpretive: InterpretiveRecordSchema.optional(),
874
+ /**
875
+ * Propensity + candidate set + scores. Harness-supplied only. Substrate
876
+ * for OPE in Chapter 5 Dream. Nearly free if the harness already computes
877
+ * candidates + ensemble scores; cannot be backfilled from the reply alone.
878
+ */
879
+ propensity: PropensitySchema.optional(),
880
+ /**
881
+ * Transition signals (human's response to the reply). Populated when the
882
+ * SDK observes the next user turn; may arrive on a subsequent turn ingest.
883
+ */
884
+ transition: TransitionSchema.optional(),
885
+ /**
886
+ * User-side input for this turn: what the human actually said + UI-level
887
+ * interactivity hints. Server-side Presidio scrubs text before it lands
888
+ * on the canonical probe_user_reply_text column. See PLAN-2026-07-11.
889
+ */
890
+ userInput: UserInputSchema.optional(),
891
+ /**
892
+ * Interactivity between agent and user for this turn: agent reflect time,
893
+ * stream completion, multimodal events.
894
+ */
895
+ interactivity: InteractivitySchema.optional(),
896
+ /**
897
+ * Explicit user outcome signals (Ch9-promoted): flagged break, rating,
898
+ * thumbs. Landed as first-class columns per PLAN-2026-07-11.
899
+ */
900
+ userOutcome: UserOutcomeSchema.optional(),
901
+ /**
902
+ * RLDS episode-level provenance (Amendment R populater 2026-07-11).
903
+ * SDK forwards these from Probe.startSession() on every turn payload so
904
+ * the worker can persist them on the sessions row at first-turn create.
905
+ * All optional. Powers Chapter 8e′ Card 3 version behavioral diff.
906
+ */
907
+ agentId: z.string().optional(),
908
+ experimentId: z.string().optional(),
909
+ environmentConfigHash: z.string().optional(),
910
+ environmentConfigLabel: z.string().optional(),
911
+ /**
912
+ * Session context riding the FIRST turn of a session (there is no
913
+ * session-start wire route; the session row is created lazily by the
914
+ * worker on the first turn that arrives). The SDK forwards these once
915
+ * per session from Probe.startSession() state; the worker persists them
916
+ * on sessions.probe_session_opened_via / probe_session_client_context
917
+ * at session find-or-create and ignores them on later turns.
918
+ */
919
+ openedVia: z.enum(["link", "notification", "resume", "direct", "share"]).optional(),
920
+ /**
921
+ * Browser / device / locale / tz environmental context, customer-
922
+ * configurable which fields to include. Customer metadata from
923
+ * Probe.startSession({ metadata }) is merged in by the SDK under the
924
+ * `metadata` key so it has a durable landing place.
925
+ */
926
+ clientContext: z.record(z.string(), z.unknown()).optional(),
927
+ payload: z.record(z.string(), z.unknown())
928
+ });
929
+ z.object({
930
+ deploymentSlug: z.string().min(1),
931
+ sessionExternalId: z.string().min(1),
932
+ /** Why the session ended. */
933
+ endedReason: z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional(),
934
+ /** ISO timestamp of session end. */
935
+ endedAt: z.string().optional()
936
+ });
937
+ z.object({
938
+ deploymentSlug: z.string().min(1),
939
+ sessionExternalId: z.string().min(1),
940
+ flagType: z.enum(["persona_break"]),
941
+ note: z.string().optional(),
942
+ /**
943
+ * Turn index the flag refers to. Optional; if omitted, the flag is
944
+ * attached to the most recent turn of the session.
945
+ */
946
+ turnIndex: z.number().int().nonnegative().optional()
947
+ });
948
+ z.object({
949
+ /** Slug for the demo deployment; defaults to 'demo'. */
950
+ deploymentSlug: z.string().min(1).optional(),
951
+ /** PRNG seed; the corpus is byte-identical per (seed, startDate). */
952
+ seed: z.number().int().optional(),
953
+ /**
954
+ * ISO anchor for the corpus window (sessions land in
955
+ * [startDate, startDate + ~6.4d]). Enqueuers stamp now-6.5d so the
956
+ * trailing-7-day sweeps see the corpus; the worker defaults the same
957
+ * way when absent.
958
+ */
959
+ startDate: z.string().optional()
960
+ });
961
+ z.object({
962
+ deploymentSlug: z.string().min(1),
963
+ /** Same (seed, startDate) the seeding job used — the plan is recomputed
964
+ deterministically rather than serialized through the queue. */
965
+ seed: z.number().int(),
966
+ startDate: z.string()
967
+ });
968
+ z.object({
969
+ deploymentSlug: z.string().min(1),
970
+ sessionExternalId: z.string().min(1),
971
+ /** Open-vocab kind label. Seeds above; customers may register any string. */
972
+ kind: z.string().min(1),
973
+ /** How was this event detected? Seed values below; customer sources allowed. */
974
+ detectedBy: z.enum(["harness", "sdk_flag", "sdk_rating", "sdk_thumbs", "worker_detector", "webhook", "sdk_custom"]).or(z.string().min(1)),
975
+ /** Optional turn index the event was caused by. Omitted → attaches to session's most recent turn. */
976
+ causingTurnIndex: z.number().int().nonnegative().optional(),
977
+ /** Optional detail payload (customer-defined). */
978
+ detail: z.record(z.string(), z.unknown()).optional(),
979
+ /** ISO timestamp; defaults to server-side now. */
980
+ firedAt: z.string().optional()
981
+ });
982
+
983
+ // src/probe.ts
984
+ var PRE_SESSION_BUFFER_MAX = 100;
985
+ var state = null;
986
+ var Probe = class {
987
+ /**
988
+ * Initialize the Probe SDK. Call once at process start. Subsequent calls are
989
+ * no-ops with a warning; re-init requires a shutdown() first.
990
+ */
991
+ static init(config) {
992
+ if (state !== null) {
993
+ console.warn("[probe] already initialized; call shutdown() first");
994
+ return;
995
+ }
996
+ const validated = ProbeConfigSchema.parse(config);
997
+ const client = new IngestClient({
998
+ apiKey: validated.apiKey,
999
+ endpoint: validated.endpoint,
1000
+ debug: validated.debug
1001
+ });
1002
+ state = {
1003
+ config: validated,
1004
+ client,
1005
+ persona: validated.persona ?? null,
1006
+ outcomeHook: validated.outcomeHook ?? null,
1007
+ sessions: /* @__PURE__ */ new Map(),
1008
+ signatureMatchers: /* @__PURE__ */ new Map(),
1009
+ preSessionBuffer: /* @__PURE__ */ new Map()
1010
+ };
1011
+ if (validated.persona?.signaturePhrases) {
1012
+ state.signatureMatchers.set(
1013
+ validated.persona.slug,
1014
+ compileSignaturePhrases(validated.persona.signaturePhrases)
1015
+ );
1016
+ }
1017
+ registerAllInstrumentations(state, (turn) => this.captureTurn(turn));
1018
+ }
1019
+ /**
1020
+ * Run a callback inside a session context. Every LLM call made inside `fn`
1021
+ * (through any instrumented library: OpenAI, Anthropic, LangChain, Vercel
1022
+ * AI SDK, etc.) is automatically tagged with `sessionId` and captured as
1023
+ * a turn on that session.
1024
+ *
1025
+ * Under the hood, this uses OTel Baggage propagation; the shared span
1026
+ * processor reads the session ID from baggage when each LLM span ends.
1027
+ */
1028
+ static async withSession(sessionId, fn) {
1029
+ if (state === null) {
1030
+ console.warn("[probe] withSession called before init");
1031
+ return fn();
1032
+ }
1033
+ return withSession(sessionId, fn);
1034
+ }
1035
+ /**
1036
+ * Identify the process-level default persona. Overwrites any previously-set
1037
+ * default. For per-session persona identification (multi-persona products),
1038
+ * use startSession({ externalId, persona }) instead.
1039
+ */
1040
+ static identifyPersona(persona) {
1041
+ if (state === null) {
1042
+ console.warn("[probe] identifyPersona called before init");
1043
+ return;
1044
+ }
1045
+ state.persona = persona;
1046
+ if (persona.signaturePhrases) {
1047
+ state.signatureMatchers.set(
1048
+ persona.slug,
1049
+ compileSignaturePhrases(persona.signaturePhrases)
1050
+ );
1051
+ }
1052
+ }
1053
+ /**
1054
+ * Start (or update) a session with an active persona.
1055
+ *
1056
+ * Single-persona deployments can skip this if the init-level default is
1057
+ * enough; the SDK will still create a session entry lazily on first turn.
1058
+ * Multi-persona products call this at conversation start so every turn in
1059
+ * the session inherits the selected persona.
1060
+ *
1061
+ * Idempotent: calling with the same externalId updates the entry.
1062
+ */
1063
+ static startSession(input) {
1064
+ if (state === null) {
1065
+ console.warn("[probe] startSession called before init");
1066
+ return;
1067
+ }
1068
+ const validated = SessionStartSchema.parse(input);
1069
+ const existing = state.sessions.get(validated.externalId);
1070
+ const now = Date.now();
1071
+ const session = {
1072
+ externalId: validated.externalId,
1073
+ externalUserId: validated.externalUserId ?? existing?.externalUserId ?? null,
1074
+ turnIndex: existing?.turnIndex ?? 0,
1075
+ startedAt: existing?.startedAt ?? now,
1076
+ personaSlug: validated.persona ?? existing?.personaSlug ?? state.persona?.slug ?? null,
1077
+ metadata: validated.metadata ?? existing?.metadata ?? null,
1078
+ openedVia: validated.openedVia ?? existing?.openedVia ?? null,
1079
+ clientContext: validated.clientContext ?? existing?.clientContext ?? null,
1080
+ agentId: validated.agentId ?? existing?.agentId ?? null,
1081
+ experimentId: validated.experimentId ?? existing?.experimentId ?? null,
1082
+ environmentConfigHash: validated.environmentConfigHash ?? existing?.environmentConfigHash ?? null,
1083
+ environmentConfigLabel: validated.environmentConfigLabel ?? existing?.environmentConfigLabel ?? null,
1084
+ lastAgentTurnAt: existing?.lastAgentTurnAt ?? null,
1085
+ lastUserSubmitAt: existing?.lastUserSubmitAt ?? null,
1086
+ sessionContextForwarded: existing?.sessionContextForwarded ?? false,
1087
+ pendingUserInput: existing?.pendingUserInput ?? null,
1088
+ pendingUserOutcome: existing?.pendingUserOutcome ?? null
1089
+ };
1090
+ this.flushPreSessionSignals(validated.externalId, session);
1091
+ state.sessions.set(validated.externalId, session);
1092
+ }
1093
+ /**
1094
+ * Move buffered pre-session interaction signals (recorded before any
1095
+ * session entry existed for this externalId) onto the session entry.
1096
+ * Session-held values win: buffered signals predate anything recorded
1097
+ * after the entry existed.
1098
+ */
1099
+ static flushPreSessionSignals(externalId, session) {
1100
+ if (state === null) return;
1101
+ const buffered = state.preSessionBuffer.get(externalId);
1102
+ if (!buffered) return;
1103
+ state.preSessionBuffer.delete(externalId);
1104
+ session.pendingUserInput = session.pendingUserInput ?? buffered.pendingUserInput;
1105
+ session.pendingUserOutcome = session.pendingUserOutcome ?? buffered.pendingUserOutcome;
1106
+ session.lastUserSubmitAt = session.lastUserSubmitAt ?? buffered.lastUserSubmitAt;
1107
+ }
1108
+ /**
1109
+ * Get or create the pre-session signal buffer entry for an externalId.
1110
+ * FIFO-capped: when a new id would exceed PRE_SESSION_BUFFER_MAX, the
1111
+ * oldest id is dropped (Map preserves insertion order).
1112
+ */
1113
+ static preSessionEntry(externalId) {
1114
+ const buffer = state.preSessionBuffer;
1115
+ const existing = buffer.get(externalId);
1116
+ if (existing) return existing;
1117
+ if (buffer.size >= PRE_SESSION_BUFFER_MAX) {
1118
+ const oldest = buffer.keys().next().value;
1119
+ if (oldest !== void 0) buffer.delete(oldest);
1120
+ }
1121
+ const entry = {
1122
+ pendingUserInput: null,
1123
+ pendingUserOutcome: null,
1124
+ lastUserSubmitAt: null
1125
+ };
1126
+ buffer.set(externalId, entry);
1127
+ return entry;
1128
+ }
1129
+ /**
1130
+ * Compute a stable SHA-256 hex hash of prompt/config text for use as
1131
+ * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —
1132
+ * pass the human-readable version alongside as `environmentConfigLabel`
1133
+ * for the diff table axis (a card keyed by a3f9c2… is unreadable).
1134
+ *
1135
+ * Ships as a helper because inconsistent hashing across restarts breaks
1136
+ * Chapter 8e′ Card 3 (version behavioral diff) — every customer would
1137
+ * hash their own way and version-diff would become noise.
1138
+ *
1139
+ * Node runtime; use dynamic import so the SDK stays browser-friendly
1140
+ * for callers that never touch this helper.
1141
+ */
1142
+ static async hashEnvironmentConfig(input) {
1143
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
1144
+ const bytes = new TextEncoder().encode(input);
1145
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
1146
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
1147
+ }
1148
+ const { createHash } = await import('crypto');
1149
+ return createHash("sha256").update(input).digest("hex");
1150
+ }
1151
+ /**
1152
+ * End a session and release its in-memory entry. Optional (sessions time out
1153
+ * eventually), but recommended for long-running processes with many distinct
1154
+ * conversations. If `input.endedReason` is provided the SDK sends an end
1155
+ * event to ingest so the worker records the reason server-side.
1156
+ */
1157
+ static async endSession(externalId) {
1158
+ if (state === null) return;
1159
+ const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
1160
+ const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
1161
+ if (endedReason) {
1162
+ await state.client.sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason }).catch((err) => {
1163
+ console.warn("[probe] sendSessionEnd failed:", err instanceof Error ? err.message : err);
1164
+ });
1165
+ }
1166
+ state.sessions.delete(externalIdStr);
1167
+ }
1168
+ // ── User-side helpers (P1 per PLAN-2026-07-11) ─────────────────────────
1169
+ // These accumulate user-side signals during a turn; captureTurn folds the
1170
+ // accumulated state into TurnInput.userInput / userOutcome before send.
1171
+ // Signals that arrive before any session entry exists (typing starts
1172
+ // before startSession or the first LLM call) buffer per externalId and
1173
+ // flush into the session when it is created.
1174
+ /**
1175
+ * User started typing — records the first-keystroke timestamp for
1176
+ * probe_user_first_keystroke_ms derivation on captureTurn. Derivable
1177
+ * only once a previous agent turn exists; a pre-session typing start
1178
+ * buffers the pending-input entry without a firstKeystrokeMs value.
1179
+ */
1180
+ static userInputStart(externalId) {
1181
+ if (state === null) return;
1182
+ const session = state.sessions.get(externalId);
1183
+ const target = session ?? this.preSessionEntry(externalId);
1184
+ const now = Date.now();
1185
+ const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0, now - session.lastAgentTurnAt) : void 0;
1186
+ target.pendingUserInput = {
1187
+ ...target.pendingUserInput ?? { editCount: 0 },
1188
+ firstKeystrokeMs: target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs
1189
+ };
1190
+ }
1191
+ /**
1192
+ * User pressed backspace / edited — increments edit_count for
1193
+ * probe_user_reply_edit_count.
1194
+ */
1195
+ static userInputEdit(externalId) {
1196
+ if (state === null) return;
1197
+ const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
1198
+ target.pendingUserInput = {
1199
+ ...target.pendingUserInput ?? { editCount: 0 },
1200
+ editCount: (target.pendingUserInput?.editCount ?? 0) + 1
1201
+ };
1202
+ }
1203
+ /**
1204
+ * User submitted their reply. Records the text (Presidio-scrubbed
1205
+ * server-side before landing on probe_user_reply_text) plus the submit
1206
+ * timestamp, which captureTurn uses to derive probe_agent_reflect_ms
1207
+ * (submit → next agent turn) and probe_transition_time_ms (previous
1208
+ * agent turn → submit).
1209
+ */
1210
+ static userInputSubmit(externalId, text) {
1211
+ if (state === null) return;
1212
+ const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
1213
+ const now = Date.now();
1214
+ target.pendingUserInput = {
1215
+ ...target.pendingUserInput ?? { editCount: 0 },
1216
+ text,
1217
+ submittedAt: now
1218
+ };
1219
+ target.lastUserSubmitAt = now;
1220
+ }
1221
+ /** Attach a thumbs-up/down to the current turn. */
1222
+ static userThumbs(externalId, thumbs) {
1223
+ if (state === null) return;
1224
+ const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
1225
+ target.pendingUserOutcome = {
1226
+ ...target.pendingUserOutcome ?? {},
1227
+ thumbs
1228
+ };
1229
+ }
1230
+ /** Attach an explicit 1-5 rating to the current turn. */
1231
+ static userRating(externalId, rating) {
1232
+ if (state === null) return;
1233
+ if (rating < 1 || rating > 5 || !Number.isInteger(rating)) return;
1234
+ const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
1235
+ target.pendingUserOutcome = {
1236
+ ...target.pendingUserOutcome ?? {},
1237
+ explicitRating: rating
1238
+ };
1239
+ }
1240
+ /**
1241
+ * Helper: collect client context and pass it to startSession in one call.
1242
+ */
1243
+ static startSessionWithContext(input, includes) {
1244
+ this.startSession({
1245
+ ...input,
1246
+ clientContext: input.clientContext ?? collectClientContext(includes)
1247
+ });
1248
+ }
1249
+ /**
1250
+ * Register the outcome hook: declares the deployment's outcome type and
1251
+ * the resolver for it. NOTE: automatic invocation on session close is
1252
+ * not wired in the current build — the hook is stored but nothing calls
1253
+ * `resolve` yet. To land a downstream outcome on a session today, call
1254
+ * emitOutcomeEvent() from the place where the outcome becomes known
1255
+ * (webhook, CRM callback); it joins back by sessionExternalId.
1256
+ */
1257
+ static wireOutcomeHook(hook) {
1258
+ if (state === null) {
1259
+ console.warn("[probe] wireOutcomeHook called before init");
1260
+ return;
1261
+ }
1262
+ state.outcomeHook = hook;
1263
+ }
1264
+ /**
1265
+ * Manually capture a turn. Instrumentation adapters call this internally;
1266
+ * exposed for advanced customers who want to bypass autocapture.
1267
+ *
1268
+ * Persona resolution order for the outgoing turn payload:
1269
+ * 1. turn.personaSlug (turn-level override)
1270
+ * 2. sessions[externalId].personaSlug (from startSession)
1271
+ * 3. state.persona.slug (init-level default)
1272
+ *
1273
+ * Signature-phrase matching runs at the SDK edge when the resolved persona
1274
+ * has signature phrases registered. The matched slug list is attached to
1275
+ * `turn.signaturePhraseMatches` before send.
1276
+ */
1277
+ static async captureTurn(turn) {
1278
+ if (state === null) {
1279
+ return;
1280
+ }
1281
+ if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
1282
+ return;
1283
+ }
1284
+ const propensity = turn.propensity ?? turn.payload.propensity;
1285
+ let validPropensity = propensity;
1286
+ if (propensity) {
1287
+ const contract = validatePropensityContract(propensity);
1288
+ if (!contract.ok) {
1289
+ console.warn(
1290
+ `[probe] Amendment S contract violation (${contract.class}): ${contract.reason}`
1291
+ );
1292
+ turn.payload.propensity = void 0;
1293
+ validPropensity = void 0;
1294
+ }
1295
+ }
1296
+ const sessionPersona = state.sessions.get(turn.sessionExternalId)?.personaSlug ?? null;
1297
+ const resolvedPersona = turn.personaSlug ?? sessionPersona ?? state.persona?.slug ?? void 0;
1298
+ let signatureMatches = turn.signaturePhraseMatches;
1299
+ if (!signatureMatches && resolvedPersona) {
1300
+ const matcher = state.signatureMatchers.get(resolvedPersona);
1301
+ if (matcher && matcher.length > 0) {
1302
+ const text = this.extractTextForMatching(turn.payload);
1303
+ signatureMatches = text ? matchSignaturePhrases(text, matcher) : [];
1304
+ }
1305
+ }
1306
+ let session = state.sessions.get(turn.sessionExternalId);
1307
+ if (!session) {
1308
+ session = {
1309
+ externalId: turn.sessionExternalId,
1310
+ externalUserId: null,
1311
+ turnIndex: turn.turnIndex + 1,
1312
+ startedAt: Date.now(),
1313
+ personaSlug: resolvedPersona ?? null,
1314
+ metadata: null,
1315
+ openedVia: null,
1316
+ clientContext: null,
1317
+ agentId: null,
1318
+ experimentId: null,
1319
+ environmentConfigHash: null,
1320
+ environmentConfigLabel: null,
1321
+ lastAgentTurnAt: null,
1322
+ lastUserSubmitAt: null,
1323
+ sessionContextForwarded: false,
1324
+ pendingUserInput: null,
1325
+ pendingUserOutcome: null
1326
+ };
1327
+ state.sessions.set(turn.sessionExternalId, session);
1328
+ }
1329
+ this.flushPreSessionSignals(turn.sessionExternalId, session);
1330
+ let userInput = turn.userInput;
1331
+ let userOutcome = turn.userOutcome;
1332
+ let interactivity = turn.interactivity;
1333
+ let transition = turn.transition;
1334
+ if (session.pendingUserInput && !userInput) {
1335
+ const p = session.pendingUserInput;
1336
+ userInput = {
1337
+ text: p.text,
1338
+ firstKeystrokeMs: p.firstKeystrokeMs,
1339
+ editCount: p.editCount,
1340
+ submittedAt: p.submittedAt ? new Date(p.submittedAt).toISOString() : void 0
1341
+ };
1342
+ }
1343
+ if (session.pendingUserOutcome && !userOutcome) {
1344
+ userOutcome = session.pendingUserOutcome;
1345
+ }
1346
+ if (!interactivity && session.lastUserSubmitAt) {
1347
+ interactivity = {
1348
+ agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt)
1349
+ };
1350
+ }
1351
+ const submittedAt = session.pendingUserInput?.submittedAt;
1352
+ if (!transition && session.lastAgentTurnAt !== null && submittedAt !== void 0 && submittedAt >= session.lastAgentTurnAt) {
1353
+ transition = { timeMs: submittedAt - session.lastAgentTurnAt };
1354
+ }
1355
+ let openedVia;
1356
+ let clientContext;
1357
+ if (!session.sessionContextForwarded) {
1358
+ openedVia = session.openedVia ?? void 0;
1359
+ clientContext = session.clientContext || session.metadata ? {
1360
+ ...session.clientContext ?? {},
1361
+ ...session.metadata ? { metadata: session.metadata } : {}
1362
+ } : void 0;
1363
+ session.sessionContextForwarded = true;
1364
+ }
1365
+ session.pendingUserInput = null;
1366
+ session.pendingUserOutcome = null;
1367
+ session.lastAgentTurnAt = Date.now();
1368
+ await state.client.sendTurn({
1369
+ ...turn,
1370
+ personaSlug: resolvedPersona,
1371
+ signaturePhraseMatches: signatureMatches,
1372
+ // User identity from the local session entry (Probe.startSession).
1373
+ // The worker persists it on sessions.external_user_id; never the
1374
+ // session key. Turn-level override wins for advanced callers.
1375
+ externalUserId: turn.externalUserId ?? session.externalUserId ?? void 0,
1376
+ userInput,
1377
+ userOutcome,
1378
+ interactivity,
1379
+ transition,
1380
+ openedVia,
1381
+ clientContext,
1382
+ // Hoist validated propensity to the top-level TurnInput field: the
1383
+ // worker projection reads input.propensity (not payload.propensity)
1384
+ // when landing read_candidates / read_propensities / selection_meta
1385
+ // columns (e2e audit 2026-07-13).
1386
+ propensity: validPropensity,
1387
+ // Forward RLDS provenance from the local session entry (populated
1388
+ // by Probe.startSession). Worker persists at first-turn session
1389
+ // create; nulls stay null. Amendment R populater 2026-07-11.
1390
+ agentId: session.agentId ?? void 0,
1391
+ experimentId: session.experimentId ?? void 0,
1392
+ environmentConfigHash: session.environmentConfigHash ?? void 0,
1393
+ environmentConfigLabel: session.environmentConfigLabel ?? void 0
1394
+ });
1395
+ }
1396
+ /**
1397
+ * Emit a custom outcome event on a session. Populates probe_outcome_events
1398
+ * with the customer-supplied `kind` string (Amendment I Method D). Use for
1399
+ * customer-defined kinds like "purchase_complete", "handoff_to_human",
1400
+ * "character_break_severe". Universal seed kinds (break, escalation,
1401
+ * resolution, thumbs_*, rating_*) are also emitted by worker-side
1402
+ * detectors automatically — call this only when the customer has a
1403
+ * signal the worker cannot infer.
1404
+ */
1405
+ static async emitOutcomeEvent(input) {
1406
+ if (state === null) {
1407
+ console.warn("[probe] emitOutcomeEvent called before init");
1408
+ return;
1409
+ }
1410
+ const validated = OutcomeEventEmitSchema.parse(input);
1411
+ await state.client.sendOutcomeEvent(state.config.deployment, validated);
1412
+ }
1413
+ /**
1414
+ * Flag a persona break for a session. Wire this to the customer's in-product
1415
+ * "that didn't sound like you" UX. Populates the `user_flagged_break`
1416
+ * outcome column in Chapter 9c.
1417
+ *
1418
+ * If `turnIndex` is omitted, the flag attaches to the session's most
1419
+ * recent turn.
1420
+ */
1421
+ static async flagPersonaBreak(input) {
1422
+ if (state === null) {
1423
+ console.warn("[probe] flagPersonaBreak called before init");
1424
+ return;
1425
+ }
1426
+ const validated = FlagPersonaBreakSchema.parse(input);
1427
+ await state.client.sendFlag(state.config.deployment, validated);
1428
+ }
1429
+ /**
1430
+ * Best-effort extraction of the response text from a captured turn's payload
1431
+ * for signature-phrase matching. Adapters populate `payload.response.text`
1432
+ * or `payload.text` by convention; this method looks for both.
1433
+ */
1434
+ static extractTextForMatching(payload) {
1435
+ const response = payload["response"];
1436
+ if (response && typeof response === "object") {
1437
+ const responseText = response["text"];
1438
+ if (typeof responseText === "string") return responseText;
1439
+ }
1440
+ if (typeof payload["text"] === "string") return payload["text"];
1441
+ return "";
1442
+ }
1443
+ /**
1444
+ * Shut down the SDK: discards the singleton state (sessions, pending
1445
+ * user-side signals, the pre-session buffer) so init() can be called
1446
+ * again. There is no send queue to flush — every capture awaits its own
1447
+ * HTTP send — and instrumentation stays registered for the life of the
1448
+ * process. Idempotent.
1449
+ */
1450
+ static async shutdown() {
1451
+ if (state === null) {
1452
+ return;
1453
+ }
1454
+ state = null;
1455
+ }
1456
+ // ── Internal helpers ─────────────────────────────────────────────────────
1457
+ /** Package-internal: instrumentation adapters read this to build turns. */
1458
+ static _getState() {
1459
+ return state;
1460
+ }
1461
+ static shouldSample(sessionId, turnIndex) {
1462
+ if (state === null) return false;
1463
+ const rate = state.config.sampleRate;
1464
+ if (rate >= 1) return true;
1465
+ if (rate <= 0) return false;
1466
+ const key = `${sessionId}:${turnIndex}`;
1467
+ let hash = 2166136261;
1468
+ for (let i = 0; i < key.length; i++) {
1469
+ hash ^= key.charCodeAt(i);
1470
+ hash = hash * 16777619 >>> 0;
1471
+ }
1472
+ return hash / 4294967295 < rate;
1473
+ }
1474
+ };
1475
+
1476
+ export { Probe, Probe as Sight };
1477
+ //# sourceMappingURL=index.js.map
1478
+ //# sourceMappingURL=index.js.map