@cultured_computer/sight 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6,13 +6,16 @@ var api = require('@opentelemetry/api');
6
6
  // src/client.ts
7
7
  var DEFAULT_DASHBOARD_URL = "https://field.cultured.computer/dashboard";
8
8
  var MAX_PENDING_RETRIES = 50;
9
+ var SEND_TIMEOUT_MS = 15e3;
10
+ var MAX_INFLIGHT = 64;
11
+ var MAX_TURN_BODY_BYTES = 9e5;
9
12
  var IngestClient = class {
10
13
  apiKey;
11
14
  endpoint;
12
15
  debug;
13
16
  dashboardUrl;
14
17
  /**
15
- * First-trace permalink ritual (PLAN-2026-07-14-adoptions A1): the first
18
+ * First-trace permalink: the first
16
19
  * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,
17
20
  * then never again for the life of this client (one IngestClient per
18
21
  * process — one `init` per process; a restart prints once more, accepted).
@@ -30,6 +33,31 @@ var IngestClient = class {
30
33
  */
31
34
  rateLimitAnnounced = false;
32
35
  pendingRetries = 0;
36
+ inFlight = 0;
37
+ shedAnnounced = false;
38
+ /**
39
+ * Every network send goes through here: adds the per-send timeout and
40
+ * the in-flight cap (audit B1). At the cap, the send is SHED — thrown
41
+ * into the caller's existing fire-and-log catch — rather than queued;
42
+ * the first shed per process warns on stderr, the rest debug-log.
43
+ */
44
+ async guardedFetch(url, init) {
45
+ if (this.inFlight >= MAX_INFLIGHT) {
46
+ if (!this.shedAnnounced) {
47
+ this.shedAnnounced = true;
48
+ console.error(
49
+ `[sight] ${MAX_INFLIGHT} sends already in flight \u2014 shedding new sends (ingest slow or unreachable; this warning prints once)`
50
+ );
51
+ }
52
+ throw new Error("in-flight cap reached \u2014 send shed");
53
+ }
54
+ this.inFlight++;
55
+ try {
56
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });
57
+ } finally {
58
+ this.inFlight--;
59
+ }
60
+ }
33
61
  constructor(opts) {
34
62
  this.apiKey = opts.apiKey;
35
63
  this.endpoint = opts.endpoint.replace(/\/$/, "");
@@ -42,18 +70,25 @@ var IngestClient = class {
42
70
  */
43
71
  async sendTurn(turn) {
44
72
  try {
45
- const send = () => fetch(`${this.endpoint}/v1/turns`, {
73
+ const body = JSON.stringify(turn);
74
+ if (body.length > MAX_TURN_BODY_BYTES) {
75
+ this.log(
76
+ `[sight] turn dropped: payload ${body.length} bytes exceeds the ${MAX_TURN_BODY_BYTES}-byte cap (session=${turn.sessionExternalId} turn=${turn.turnIndex}) \u2014 trim the payload you attach`
77
+ );
78
+ return;
79
+ }
80
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/turns`, {
46
81
  method: "POST",
47
82
  headers: {
48
83
  Authorization: `Bearer ${this.apiKey}`,
49
84
  "content-type": "application/json"
50
85
  },
51
- body: JSON.stringify(turn)
86
+ body
52
87
  });
53
88
  const response = await this.retryIfRateLimited(await send(), send);
54
89
  if (response === null) return;
55
90
  if (!response.ok) {
56
- this.log(`[probe] ingest failed status=${response.status}`);
91
+ this.log(`[sight] ingest failed status=${response.status}`);
57
92
  return;
58
93
  }
59
94
  if (!this.firstCaptureAnnounced) {
@@ -63,21 +98,21 @@ var IngestClient = class {
63
98
  );
64
99
  }
65
100
  if (this.debug) {
66
- const body = await response.json();
67
- this.log(`[probe] ingest ok id=${body.pendingId ?? "?"}`);
101
+ const body2 = await response.json();
102
+ this.log(`[sight] ingest ok id=${body2.pendingId ?? "?"}`);
68
103
  }
69
104
  } catch (err) {
70
105
  const msg = err instanceof Error ? err.message : String(err);
71
- this.log(`[probe] ingest error: ${msg}`);
106
+ this.log(`[sight] ingest error: ${msg}`);
72
107
  }
73
108
  }
74
109
  /**
75
110
  * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.
76
- * Populates the `user_flagged_break` outcome column in Chapter 9c.
111
+ * Populates the `user_flagged_break` outcome column on the dashboard.
77
112
  */
78
113
  async sendFlag(deploymentSlug, flag) {
79
114
  try {
80
- const send = () => fetch(`${this.endpoint}/v1/flags`, {
115
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/flags`, {
81
116
  method: "POST",
82
117
  headers: {
83
118
  Authorization: `Bearer ${this.apiKey}`,
@@ -94,15 +129,15 @@ var IngestClient = class {
94
129
  const response = await this.retryIfRateLimited(await send(), send);
95
130
  if (response === null) return;
96
131
  if (!response.ok) {
97
- this.log(`[probe] flag ingest failed status=${response.status}`);
132
+ this.log(`[sight] flag ingest failed status=${response.status}`);
98
133
  return;
99
134
  }
100
135
  if (this.debug) {
101
- this.log(`[probe] flag ingest ok session=${flag.sessionExternalId}`);
136
+ this.log(`[sight] flag ingest ok session=${flag.sessionExternalId}`);
102
137
  }
103
138
  } catch (err) {
104
139
  const msg = err instanceof Error ? err.message : String(err);
105
- this.log(`[probe] flag ingest error: ${msg}`);
140
+ this.log(`[sight] flag ingest error: ${msg}`);
106
141
  }
107
142
  }
108
143
  /**
@@ -111,7 +146,7 @@ var IngestClient = class {
111
146
  */
112
147
  async sendSessionEnd(deploymentSlug, end) {
113
148
  try {
114
- const send = () => fetch(`${this.endpoint}/v1/sessions/end`, {
149
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/sessions/end`, {
115
150
  method: "POST",
116
151
  headers: {
117
152
  Authorization: `Bearer ${this.apiKey}`,
@@ -126,24 +161,24 @@ var IngestClient = class {
126
161
  const response = await this.retryIfRateLimited(await send(), send);
127
162
  if (response === null) return;
128
163
  if (!response.ok) {
129
- this.log(`[probe] session-end ingest failed status=${response.status}`);
164
+ this.log(`[sight] session-end ingest failed status=${response.status}`);
130
165
  return;
131
166
  }
132
167
  if (this.debug) {
133
- this.log(`[probe] session-end ingest ok session=${end.externalId}`);
168
+ this.log(`[sight] session-end ingest ok session=${end.externalId}`);
134
169
  }
135
170
  } catch (err) {
136
171
  const msg = err instanceof Error ? err.message : String(err);
137
- this.log(`[probe] session-end ingest error: ${msg}`);
172
+ this.log(`[sight] session-end ingest error: ${msg}`);
138
173
  }
139
174
  }
140
175
  /**
141
176
  * Send an outcome event to the ingest API. Fire-and-log. Populates
142
- * probe_outcome_events per Amendment I Method D.
177
+ * the outcome-events store.
143
178
  */
144
179
  async sendOutcomeEvent(deploymentSlug, event) {
145
180
  try {
146
- const send = () => fetch(`${this.endpoint}/v1/outcome-events`, {
181
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/outcome-events`, {
147
182
  method: "POST",
148
183
  headers: {
149
184
  Authorization: `Bearer ${this.apiKey}`,
@@ -161,17 +196,17 @@ var IngestClient = class {
161
196
  const response = await this.retryIfRateLimited(await send(), send);
162
197
  if (response === null) return;
163
198
  if (!response.ok) {
164
- this.log(`[probe] outcome-event ingest failed status=${response.status}`);
199
+ this.log(`[sight] outcome-event ingest failed status=${response.status}`);
165
200
  return;
166
201
  }
167
202
  if (this.debug) {
168
203
  this.log(
169
- `[probe] outcome-event ingest ok session=${event.sessionExternalId} kind=${event.kind}`
204
+ `[sight] outcome-event ingest ok session=${event.sessionExternalId} kind=${event.kind}`
170
205
  );
171
206
  }
172
207
  } catch (err) {
173
208
  const msg = err instanceof Error ? err.message : String(err);
174
- this.log(`[probe] outcome-event ingest error: ${msg}`);
209
+ this.log(`[sight] outcome-event ingest error: ${msg}`);
175
210
  }
176
211
  }
177
212
  /**
@@ -181,7 +216,7 @@ var IngestClient = class {
181
216
  */
182
217
  async sendEnvironmentEvents(batch) {
183
218
  try {
184
- const send = () => fetch(`${this.endpoint}/v1/environment-events`, {
219
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/environment-events`, {
185
220
  method: "POST",
186
221
  headers: {
187
222
  Authorization: `Bearer ${this.apiKey}`,
@@ -192,15 +227,45 @@ var IngestClient = class {
192
227
  const response = await this.retryIfRateLimited(await send(), send);
193
228
  if (response === null) return;
194
229
  if (!response.ok) {
195
- this.log(`[probe] environment-events ingest failed status=${response.status}`);
230
+ this.log(`[sight] environment-events ingest failed status=${response.status}`);
196
231
  return;
197
232
  }
198
233
  if (this.debug) {
199
- this.log(`[probe] environment-events ingest ok events=${batch.events.length}`);
234
+ this.log(`[sight] environment-events ingest ok events=${batch.events.length}`);
200
235
  }
201
236
  } catch (err) {
202
237
  const msg = err instanceof Error ? err.message : String(err);
203
- this.log(`[probe] environment-events ingest error: ${msg}`);
238
+ this.log(`[sight] environment-events ingest error: ${msg}`);
239
+ }
240
+ }
241
+ /**
242
+ * Send a span batch to the ingest API. Fire-and-log, same as sendTurn.
243
+ * Spans carry sub-turn structure (llm_call / tool_call / framework_step /
244
+ * custom); the worker resolves each span's session/turn and wires in-batch
245
+ * parent references.
246
+ */
247
+ async sendSpans(batch) {
248
+ try {
249
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/spans`, {
250
+ method: "POST",
251
+ headers: {
252
+ Authorization: `Bearer ${this.apiKey}`,
253
+ "content-type": "application/json"
254
+ },
255
+ body: JSON.stringify(batch)
256
+ });
257
+ const response = await this.retryIfRateLimited(await send(), send);
258
+ if (response === null) return;
259
+ if (!response.ok) {
260
+ this.log(`[sight] spans ingest failed status=${response.status}`);
261
+ return;
262
+ }
263
+ if (this.debug) {
264
+ this.log(`[sight] spans ingest ok spans=${batch.spans.length}`);
265
+ }
266
+ } catch (err) {
267
+ const msg = err instanceof Error ? err.message : String(err);
268
+ this.log(`[sight] spans ingest error: ${msg}`);
204
269
  }
205
270
  }
206
271
  /**
@@ -221,10 +286,10 @@ var IngestClient = class {
221
286
  "Sight: ingest rate limit (429) \u2014 retrying once per Retry-After; sustained limiting drops captures. See https://field.cultured.computer/sight/sdk-reference#rate-limits"
222
287
  );
223
288
  } else {
224
- this.log("[probe] ingest rate limited (429), retrying once");
289
+ this.log("[sight] ingest rate limited (429), retrying once");
225
290
  }
226
291
  if (this.pendingRetries >= MAX_PENDING_RETRIES) {
227
- this.log("[probe] retry buffer full, dropped");
292
+ this.log("[sight] retry buffer full, dropped");
228
293
  return null;
229
294
  }
230
295
  const raw = response.headers.get("retry-after");
@@ -335,7 +400,7 @@ var SessionStartSchema = zod.z.object({
335
400
  */
336
401
  persona: zod.z.string().min(1).optional(),
337
402
  /**
338
- * How the user got into this session (P2 per PLAN-2026-07-11).
403
+ * How the user got into this session.
339
404
  * Retention semantics differ radically between a resume and a fresh
340
405
  * notification landing.
341
406
  */
@@ -352,8 +417,8 @@ var SessionStartSchema = zod.z.object({
352
417
  */
353
418
  metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
354
419
  /**
355
- * RLDS episode-level provenance (Amendment R populater 2026-07-11).
356
- * Powers Chapter 8e′ Card 3 version behavioral diff. All optional.
420
+ * RLDS episode-level provenance. Powers the version behavioral diff
421
+ * on the dashboard. All optional.
357
422
  * agentId — model/policy version
358
423
  * experimentId — A/B arm or feature flag
359
424
  * environmentConfigHash — SHA of prompt/config file(s)
@@ -366,7 +431,9 @@ var SessionStartSchema = zod.z.object({
366
431
  });
367
432
  zod.z.object({
368
433
  externalId: zod.z.string().min(1),
369
- endedReason: zod.z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional()
434
+ endedReason: zod.z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional(),
435
+ outcome: zod.z.string().min(1).max(64).optional(),
436
+ outcomeDetail: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
370
437
  });
371
438
  var FlagPersonaBreakSchema = zod.z.object({
372
439
  sessionExternalId: zod.z.string().min(1),
@@ -436,6 +503,16 @@ function collectClientContext(includes = DEFAULT_INCLUDES) {
436
503
  return out;
437
504
  }
438
505
 
506
+ // src/session-bounds.ts
507
+ var MAX_TRACKED_SESSIONS = 5e3;
508
+ function boundedSessionSet(sessions, key, session) {
509
+ if (!sessions.has(key) && sessions.size >= MAX_TRACKED_SESSIONS) {
510
+ const oldest = sessions.keys().next().value;
511
+ if (oldest !== void 0) sessions.delete(oldest);
512
+ }
513
+ sessions.set(key, session);
514
+ }
515
+
439
516
  // src/hash.ts
440
517
  async function hashEnvironmentConfig(input) {
441
518
  if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
@@ -662,7 +739,7 @@ function resolveSessionAndTurn(state2, sessionId) {
662
739
  environmentConfigHash: null,
663
740
  environmentConfigLabel: null
664
741
  };
665
- state2.sessions.set(sessionId, session);
742
+ boundedSessionSet(state2.sessions, sessionId, session);
666
743
  }
667
744
  const turnIndex = session.turnIndex;
668
745
  session.turnIndex += 1;
@@ -680,10 +757,23 @@ var ProbeSpanProcessor = class {
680
757
  }
681
758
  state;
682
759
  captureFn;
760
+ /**
761
+ * Re-point the processor at a new Probe state (or null after shutdown).
762
+ * A registered span processor cannot be removed from a provider, so
763
+ * re-init REBINDS instead of orphaning: without this, autocapture after
764
+ * shutdown()/re-init kept mutating the dead state's sessions map and
765
+ * stamping the old deployment slug (production-safety audit R1).
766
+ */
767
+ rebind(state2, captureFn) {
768
+ this.state = state2;
769
+ if (captureFn) this.captureFn = captureFn;
770
+ }
683
771
  onStart(_span, _parentContext) {
684
772
  }
685
773
  onEnd(span) {
686
774
  try {
775
+ if (this.state === null) return;
776
+ const state2 = this.state;
687
777
  const a = span.attributes;
688
778
  if (isVercelAgentRollup(span.name, a)) return;
689
779
  if (!isLLMCall(a)) return;
@@ -691,7 +781,7 @@ var ProbeSpanProcessor = class {
691
781
  if (shouldSkipAsDuplicate(traceId)) return;
692
782
  const sessionId = getCurrentSessionId();
693
783
  if (!sessionId) {
694
- if (this.state.config.debug) {
784
+ if (state2.config.debug) {
695
785
  console.warn(
696
786
  `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`
697
787
  );
@@ -699,11 +789,11 @@ var ProbeSpanProcessor = class {
699
789
  return;
700
790
  }
701
791
  const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
702
- this.state,
792
+ state2,
703
793
  sessionId
704
794
  );
705
795
  const captured = {
706
- deploymentSlug: this.state.config.deployment,
796
+ deploymentSlug: state2.config.deployment,
707
797
  sessionExternalId,
708
798
  turnIndex,
709
799
  personaSlug: personaSlug ?? void 0,
@@ -713,14 +803,14 @@ var ProbeSpanProcessor = class {
713
803
  await maybeAutoStampEnvironmentConfig(session, a);
714
804
  await this.captureFn(captured);
715
805
  })().catch((err) => {
716
- if (this.state.config.debug) {
806
+ if (state2.config.debug) {
717
807
  console.error(
718
808
  `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
719
809
  );
720
810
  }
721
811
  });
722
812
  } catch (err) {
723
- if (this.state.config.debug) {
813
+ if (this.state?.config.debug) {
724
814
  console.error(
725
815
  `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`
726
816
  );
@@ -740,6 +830,7 @@ var ProbeSpanProcessor = class {
740
830
  var installedProcessor = null;
741
831
  function setupOtelProvider(state2, captureFn) {
742
832
  if (installedProcessor !== null) {
833
+ installedProcessor.rebind(state2, captureFn);
743
834
  return;
744
835
  }
745
836
  installedProcessor = new ProbeSpanProcessor(state2, captureFn);
@@ -755,6 +846,9 @@ function setupOtelProvider(state2, captureFn) {
755
846
  provider.register();
756
847
  });
757
848
  }
849
+ function detachOtelState() {
850
+ installedProcessor?.rebind(null);
851
+ }
758
852
 
759
853
  // src/instrumentation/openai.ts
760
854
  var registered = false;
@@ -903,7 +997,7 @@ function registerAllInstrumentations(state2, captureFn) {
903
997
  if (!state2.config.debug) return;
904
998
  for (const result of results) {
905
999
  if (result.status === "rejected") {
906
- console.error(`[probe] adapter register rejected: ${result.reason}`);
1000
+ console.error(`[sight] adapter register rejected: ${result.reason}`);
907
1001
  }
908
1002
  }
909
1003
  });
@@ -943,6 +1037,13 @@ function matchSignaturePhrases(text, compiled) {
943
1037
  }
944
1038
  return matches;
945
1039
  }
1040
+
1041
+ // ../shared/src/effectiveness-gap.ts
1042
+ new Set(
1043
+ "the a an to of and or is are was were do does did how what where when who why which can could should would may might i you your my me it its this that these those in on for with at by from as be been being am not no yes okay ok um uh hi hello please thanks thank".split(" ")
1044
+ );
1045
+
1046
+ // ../shared/src/index.ts
946
1047
  var REACTION_REGISTERS = ["heavy", "comic", "edge"];
947
1048
  var InterpretiveRecordSchema = zod.z.object({
948
1049
  // Open vocabulary: any string tag. Seeds live in GENERAL_SITUATION_TAGS /
@@ -1072,6 +1173,15 @@ zod.z.object({
1072
1173
  */
1073
1174
  externalUserId: zod.z.string().min(1).optional(),
1074
1175
  turnIndex: zod.z.number().int().nonnegative(),
1176
+ /**
1177
+ * Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the
1178
+ * worker: when present it becomes turns.started_at; when absent the
1179
+ * insert defaults to processing time. This is PROVENANCE, not
1180
+ * verification — intended for historical imports (ZVA telemetry, log
1181
+ * backfills, the datadump importer); live SDK traffic leaves it unset
1182
+ * (arrival time is the honest clock there).
1183
+ */
1184
+ startedAt: zod.z.string().datetime().optional(),
1075
1185
  /**
1076
1186
  * Persona slug active for this turn. Customer-supplied (from SDK persona
1077
1187
  * resolution: turn override / session / init default). Optional; deployments
@@ -1216,6 +1326,61 @@ var EnvironmentEventsBatchSchema = zod.z.object({
1216
1326
  events: zod.z.array(EnvironmentEventInputSchema).min(1).max(100),
1217
1327
  alignment: AlignmentProvenanceSchema
1218
1328
  });
1329
+ var SPAN_TYPES = ["llm_call", "tool_call", "framework_step", "custom"];
1330
+ var SpanInputSchema = zod.z.object({
1331
+ deploymentSlug: zod.z.string().min(1),
1332
+ sessionExternalId: zod.z.string().min(1),
1333
+ /**
1334
+ * Turn the span belongs to. Optional: when omitted the worker resolves the
1335
+ * session's latest turn at/under the span's startedAt (falling back to the
1336
+ * session's most recent turn when startedAt is also absent — the outcome
1337
+ * events' rule). A span whose turn cannot be resolved is SKIPPED by the
1338
+ * worker (logged, batch still processed): spans never land unattributed.
1339
+ */
1340
+ turnIndex: zod.z.number().int().nonnegative().optional(),
1341
+ spanType: zod.z.enum(SPAN_TYPES),
1342
+ /** Human/otel-style span name (tool name, model call label). */
1343
+ name: zod.z.string().optional(),
1344
+ /**
1345
+ * Caller-asserted span start (ISO). OPTIONAL and honored like
1346
+ * TurnInput.startedAt: provenance, not verification — when absent the
1347
+ * worker stamps processing time.
1348
+ */
1349
+ startedAt: zod.z.string().datetime().optional(),
1350
+ endedAt: zod.z.string().datetime().optional(),
1351
+ durationMs: zod.z.number().int().nonnegative().optional(),
1352
+ model: zod.z.string().optional(),
1353
+ provider: zod.z.string().optional(),
1354
+ tokensInput: zod.z.number().int().nonnegative().optional(),
1355
+ tokensOutput: zod.z.number().int().nonnegative().optional(),
1356
+ costUsd: zod.z.number().nonnegative().optional(),
1357
+ error: zod.z.string().optional(),
1358
+ /**
1359
+ * OpenInference / OpenTelemetry gen_ai.*-style attributes. String values
1360
+ * are Presidio-scrubbed by the worker before storage (see the PII rule
1361
+ * above). Capped at 16k JSON chars per span.
1362
+ */
1363
+ attributes: zod.z.record(zod.z.string(), zod.z.unknown()).optional().refine((v) => v === void 0 || JSON.stringify(v).length <= 16e3, {
1364
+ message: "attributes exceed 16k JSON chars \u2014 spans are telemetry, not blob storage"
1365
+ }),
1366
+ /**
1367
+ * Caller-local span id, unique within the batch. Exists only so sibling
1368
+ * spans can name this span as their parentSpanId; never stored (the DB
1369
+ * assigns the real uuid).
1370
+ */
1371
+ spanId: zod.z.string().min(1).optional(),
1372
+ /**
1373
+ * Caller-local reference to another span's `spanId` IN THE SAME BATCH (NOT
1374
+ * a database uuid). The worker wires spans.parent_span_id when the parent
1375
+ * resolves within the batch, stores null otherwise.
1376
+ */
1377
+ parentSpanId: zod.z.string().min(1).optional()
1378
+ });
1379
+ var SpansBatchSchema = zod.z.object({
1380
+ /** Spans are self-addressed: a batch may span sessions/deployments. */
1381
+ spans: zod.z.array(SpanInputSchema).min(1).max(50),
1382
+ alignment: AlignmentProvenanceSchema
1383
+ });
1219
1384
  var DEFINITION_SLUG = /^[a-z][a-z0-9_-]{0,63}$/;
1220
1385
  var DEFINITION_VALUE = zod.z.string().trim().min(1).max(64);
1221
1386
  zod.z.object({
@@ -1276,7 +1441,22 @@ var DEFAULT_ENVIRONMENT_ALIGNMENT = {
1276
1441
  clock_source: "sdk",
1277
1442
  rule_version: "v1"
1278
1443
  };
1444
+ var DEFAULT_SPAN_ALIGNMENT = {
1445
+ clock_source: "sdk",
1446
+ rule_version: "v1"
1447
+ };
1279
1448
  var state = null;
1449
+ function validateOrDrop(schema, input, method) {
1450
+ const result = schema.safeParse(input);
1451
+ if (!result.success) {
1452
+ const issue = result.error?.issues?.[0];
1453
+ console.warn(
1454
+ `[sight] ${method}: invalid input dropped \u2014 ${issue ? `${issue.path?.join(".") || "(root)"}: ${issue.message}` : "schema mismatch"}`
1455
+ );
1456
+ return null;
1457
+ }
1458
+ return result.data;
1459
+ }
1280
1460
  var Probe = class {
1281
1461
  /**
1282
1462
  * Initialize the Probe SDK. Call once at process start. Subsequent calls are
@@ -1284,7 +1464,7 @@ var Probe = class {
1284
1464
  */
1285
1465
  static init(config) {
1286
1466
  if (state !== null) {
1287
- console.warn("[probe] already initialized; call shutdown() first");
1467
+ console.warn("[sight] already initialized; call shutdown() first");
1288
1468
  return;
1289
1469
  }
1290
1470
  const validated = ProbeConfigSchema.parse(config);
@@ -1322,7 +1502,7 @@ var Probe = class {
1322
1502
  */
1323
1503
  static async withSession(sessionId, fn) {
1324
1504
  if (state === null) {
1325
- console.warn("[probe] withSession called before init");
1505
+ console.warn("[sight] withSession called before init");
1326
1506
  return fn();
1327
1507
  }
1328
1508
  return withSession(sessionId, fn);
@@ -1334,7 +1514,7 @@ var Probe = class {
1334
1514
  */
1335
1515
  static identifyPersona(persona) {
1336
1516
  if (state === null) {
1337
- console.warn("[probe] identifyPersona called before init");
1517
+ console.warn("[sight] identifyPersona called before init");
1338
1518
  return;
1339
1519
  }
1340
1520
  state.persona = persona;
@@ -1357,10 +1537,11 @@ var Probe = class {
1357
1537
  */
1358
1538
  static startSession(input) {
1359
1539
  if (state === null) {
1360
- console.warn("[probe] startSession called before init");
1540
+ console.warn("[sight] startSession called before init");
1361
1541
  return;
1362
1542
  }
1363
- const validated = SessionStartSchema.parse(input);
1543
+ const validated = validateOrDrop(SessionStartSchema, input, "startSession");
1544
+ if (validated === null) return;
1364
1545
  const existing = state.sessions.get(validated.externalId);
1365
1546
  const now = Date.now();
1366
1547
  const session = {
@@ -1383,7 +1564,7 @@ var Probe = class {
1383
1564
  pendingUserOutcome: existing?.pendingUserOutcome ?? null
1384
1565
  };
1385
1566
  this.flushPreSessionSignals(validated.externalId, session);
1386
- state.sessions.set(validated.externalId, session);
1567
+ boundedSessionSet(state.sessions, validated.externalId, session);
1387
1568
  }
1388
1569
  /**
1389
1570
  * Move buffered pre-session interaction signals (recorded before any
@@ -1428,7 +1609,7 @@ var Probe = class {
1428
1609
  * for the diff table axis (a card keyed by a3f9c2… is unreadable).
1429
1610
  *
1430
1611
  * Ships as a helper because inconsistent hashing across restarts breaks
1431
- * Chapter 8e′ Card 3 (version behavioral diff) — every customer would
1612
+ * The version behavioral diff — every customer would
1432
1613
  * hash their own way and version-diff would become noise.
1433
1614
  *
1434
1615
  * The same hashing (src/hash.ts) backs the OTel processor's automatic
@@ -1460,7 +1641,18 @@ var Probe = class {
1460
1641
  if (state === null) return;
1461
1642
  const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
1462
1643
  const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
1463
- if (state.outcomeHook) {
1644
+ const declared = typeof externalId === "string" ? void 0 : externalId.outcome;
1645
+ if (declared) {
1646
+ await this.emitOutcomeEvent({
1647
+ sessionExternalId: externalIdStr,
1648
+ kind: declared,
1649
+ detail: {
1650
+ declaredAt: "endSession",
1651
+ ...typeof externalId === "object" && externalId.outcomeDetail ? externalId.outcomeDetail : {}
1652
+ }
1653
+ });
1654
+ }
1655
+ if (!declared && state.outcomeHook) {
1464
1656
  try {
1465
1657
  const result = await state.outcomeHook.resolve(externalIdStr);
1466
1658
  if (result && state !== null) {
@@ -1476,7 +1668,7 @@ var Probe = class {
1476
1668
  }
1477
1669
  } catch (err) {
1478
1670
  console.warn(
1479
- "[probe] outcome hook resolve failed:",
1671
+ "[sight] outcome hook resolve failed:",
1480
1672
  err instanceof Error ? err.message : err
1481
1673
  );
1482
1674
  }
@@ -1484,12 +1676,12 @@ var Probe = class {
1484
1676
  if (state === null) return;
1485
1677
  if (endedReason) {
1486
1678
  await state.client.sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason }).catch((err) => {
1487
- console.warn("[probe] sendSessionEnd failed:", err instanceof Error ? err.message : err);
1679
+ console.warn("[sight] sendSessionEnd failed:", err instanceof Error ? err.message : err);
1488
1680
  });
1489
1681
  }
1490
1682
  state.sessions.delete(externalIdStr);
1491
1683
  }
1492
- // ── User-side helpers (P1 per PLAN-2026-07-11) ─────────────────────────
1684
+ // ── User-side helpers ──────────────────────────────────────────────────
1493
1685
  // These accumulate user-side signals during a turn; captureTurn folds the
1494
1686
  // accumulated state into TurnInput.userInput / userOutcome before send.
1495
1687
  // Signals that arrive before any session entry exists (typing starts
@@ -1582,7 +1774,7 @@ var Probe = class {
1582
1774
  */
1583
1775
  static wireOutcomeHook(hook) {
1584
1776
  if (state === null) {
1585
- console.warn("[probe] wireOutcomeHook called before init");
1777
+ console.warn("[sight] wireOutcomeHook called before init");
1586
1778
  return;
1587
1779
  }
1588
1780
  state.outcomeHook = hook;
@@ -1607,6 +1799,9 @@ var Probe = class {
1607
1799
  if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
1608
1800
  return;
1609
1801
  }
1802
+ if (turn.payload === void 0 || turn.payload === null) {
1803
+ turn = { ...turn, payload: {} };
1804
+ }
1610
1805
  const propensity = turn.propensity ?? turn.payload.propensity;
1611
1806
  let validPropensity = propensity;
1612
1807
  if (propensity) {
@@ -1623,10 +1818,14 @@ var Probe = class {
1623
1818
  const resolvedPersona = turn.personaSlug ?? sessionPersona ?? state.persona?.slug ?? void 0;
1624
1819
  let signatureMatches = turn.signaturePhraseMatches;
1625
1820
  if (!signatureMatches && resolvedPersona) {
1626
- const matcher = state.signatureMatchers.get(resolvedPersona);
1627
- if (matcher && matcher.length > 0) {
1628
- const text = this.extractTextForMatching(turn.payload);
1629
- signatureMatches = text ? matchSignaturePhrases(text, matcher) : [];
1821
+ try {
1822
+ const matcher = state.signatureMatchers.get(resolvedPersona);
1823
+ if (matcher && matcher.length > 0) {
1824
+ const text = this.extractTextForMatching(turn.payload);
1825
+ signatureMatches = text ? matchSignaturePhrases(text, matcher) : [];
1826
+ }
1827
+ } catch {
1828
+ signatureMatches = [];
1630
1829
  }
1631
1830
  }
1632
1831
  let session = state.sessions.get(turn.sessionExternalId);
@@ -1650,7 +1849,7 @@ var Probe = class {
1650
1849
  pendingUserInput: null,
1651
1850
  pendingUserOutcome: null
1652
1851
  };
1653
- state.sessions.set(turn.sessionExternalId, session);
1852
+ boundedSessionSet(state.sessions, turn.sessionExternalId, session);
1654
1853
  }
1655
1854
  this.flushPreSessionSignals(turn.sessionExternalId, session);
1656
1855
  let userInput = turn.userInput;
@@ -1712,7 +1911,7 @@ var Probe = class {
1712
1911
  propensity: validPropensity,
1713
1912
  // Forward RLDS provenance from the local session entry (populated
1714
1913
  // by Probe.startSession). Worker persists at first-turn session
1715
- // create; nulls stay null. Amendment R populater 2026-07-11.
1914
+ // create; nulls stay null.
1716
1915
  agentId: session.agentId ?? void 0,
1717
1916
  experimentId: session.experimentId ?? void 0,
1718
1917
  environmentConfigHash: session.environmentConfigHash ?? void 0,
@@ -1721,7 +1920,7 @@ var Probe = class {
1721
1920
  }
1722
1921
  /**
1723
1922
  * Emit a custom outcome event on a session. Populates probe_outcome_events
1724
- * with the customer-supplied `kind` string (Amendment I Method D). Use for
1923
+ * with the customer-supplied `kind` string. Use for
1725
1924
  * customer-defined kinds like "purchase_complete", "handoff_to_human",
1726
1925
  * "character_break_severe". Universal seed kinds (break, escalation,
1727
1926
  * resolution, thumbs_*, rating_*) are also emitted by worker-side
@@ -1730,14 +1929,15 @@ var Probe = class {
1730
1929
  */
1731
1930
  static async emitOutcomeEvent(input) {
1732
1931
  if (state === null) {
1733
- console.warn("[probe] emitOutcomeEvent called before init");
1932
+ console.warn("[sight] emitOutcomeEvent called before init");
1734
1933
  return;
1735
1934
  }
1736
- const validated = OutcomeEventEmitSchema.parse(input);
1935
+ const validated = validateOrDrop(OutcomeEventEmitSchema, input, "emitOutcomeEvent");
1936
+ if (validated === null) return;
1737
1937
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
1738
1938
  }
1739
1939
  /**
1740
- * Capture one environment event against a session (Arc D-rail). The
1940
+ * Capture one environment event against a session. The
1741
1941
  * envelope is generalized: `source_type` and `event` are free strings whose
1742
1942
  * meaning is defined per deployment — the instrument stores the event and
1743
1943
  * attaches it to the session's record by time (the next turn's state
@@ -1751,11 +1951,12 @@ var Probe = class {
1751
1951
  */
1752
1952
  static async captureEnvironmentEvent(event, alignment) {
1753
1953
  if (state === null) {
1754
- console.warn("[probe] captureEnvironmentEvent called before init");
1954
+ console.warn("[sight] captureEnvironmentEvent called before init");
1755
1955
  return;
1756
1956
  }
1757
- const validated = EnvironmentEventInputSchema.parse(event);
1758
- const align = alignment ? AlignmentProvenanceSchema.parse(alignment) : DEFAULT_ENVIRONMENT_ALIGNMENT;
1957
+ const validated = validateOrDrop(EnvironmentEventInputSchema, event, "captureEnvironmentEvent");
1958
+ if (validated === null) return;
1959
+ const align = alignment ? validateOrDrop(AlignmentProvenanceSchema, alignment, "captureEnvironmentEvent") ?? DEFAULT_ENVIRONMENT_ALIGNMENT : DEFAULT_ENVIRONMENT_ALIGNMENT;
1759
1960
  await state.client.sendEnvironmentEvents({ events: [validated], alignment: align });
1760
1961
  }
1761
1962
  /**
@@ -1765,28 +1966,72 @@ var Probe = class {
1765
1966
  * generalized envelope and fire-and-log discipline as the single-event
1766
1967
  * capture above.
1767
1968
  */
1768
- static async captureEnvironmentEvents(events, alignment) {
1969
+ static async captureEnvironmentEvents(events, alignment = DEFAULT_ENVIRONMENT_ALIGNMENT) {
1769
1970
  if (state === null) {
1770
- console.warn("[probe] captureEnvironmentEvents called before init");
1971
+ console.warn("[sight] captureEnvironmentEvents called before init");
1771
1972
  return;
1772
1973
  }
1773
- const batch = EnvironmentEventsBatchSchema.parse({ events, alignment });
1974
+ const batch = validateOrDrop(EnvironmentEventsBatchSchema, { events, alignment }, "captureEnvironmentEvents");
1975
+ if (batch === null) return;
1774
1976
  await state.client.sendEnvironmentEvents(batch);
1775
1977
  }
1978
+ /**
1979
+ * Capture one sub-turn span against a session: one LLM call, one tool
1980
+ * call, one framework step, or a custom unit inside a turn. The span lands
1981
+ * on the turn named by `turnIndex`, or — when omitted — on the session's
1982
+ * latest turn at/under the span's `startedAt` (most recent turn when
1983
+ * `startedAt` is also absent). A span whose turn cannot be resolved is
1984
+ * dropped server-side; spans never land unattributed. Fire-and-log, like
1985
+ * captureTurn: errors are debug-logged, never thrown.
1986
+ *
1987
+ * `attributes` are metadata only (tool names, argument shapes) — never
1988
+ * free-text conversation content. Alignment defaults to the SDK's own
1989
+ * clock claim; deployments with a stricter clock contract (or batches, or
1990
+ * parent references between spans) should call captureSpans.
1991
+ */
1992
+ static async captureSpan(span, alignment) {
1993
+ if (state === null) {
1994
+ console.warn("[sight] captureSpan called before init");
1995
+ return;
1996
+ }
1997
+ const validated = validateOrDrop(SpanInputSchema, span, "captureSpan");
1998
+ if (validated === null) return;
1999
+ const align = alignment ? validateOrDrop(AlignmentProvenanceSchema, alignment, "captureSpan") ?? DEFAULT_SPAN_ALIGNMENT : DEFAULT_SPAN_ALIGNMENT;
2000
+ await state.client.sendSpans({ spans: [validated], alignment: align });
2001
+ }
2002
+ /**
2003
+ * Capture a batch of spans with explicit alignment provenance
2004
+ * (clock_source, skew_bound_ms, rule_version). Batches are capped at 50
2005
+ * spans and may span sessions — every span is self-addressed. Parent
2006
+ * structure rides the batch: a span's `parentSpanId` names another span's
2007
+ * caller-local `spanId` within the same batch and is wired server-side
2008
+ * (unresolvable references land null). Same fire-and-log discipline as the
2009
+ * single-span capture above.
2010
+ */
2011
+ static async captureSpans(spans, alignment) {
2012
+ if (state === null) {
2013
+ console.warn("[sight] captureSpans called before init");
2014
+ return;
2015
+ }
2016
+ const batch = validateOrDrop(SpansBatchSchema, { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT }, "captureSpans");
2017
+ if (batch === null) return;
2018
+ await state.client.sendSpans(batch);
2019
+ }
1776
2020
  /**
1777
2021
  * Flag a persona break for a session. Wire this to the customer's in-product
1778
2022
  * "that didn't sound like you" UX. Populates the `user_flagged_break`
1779
- * outcome column in Chapter 9c.
2023
+ * outcome column on the dashboard.
1780
2024
  *
1781
2025
  * If `turnIndex` is omitted, the flag attaches to the session's most
1782
2026
  * recent turn.
1783
2027
  */
1784
2028
  static async flagPersonaBreak(input) {
1785
2029
  if (state === null) {
1786
- console.warn("[probe] flagPersonaBreak called before init");
2030
+ console.warn("[sight] flagPersonaBreak called before init");
1787
2031
  return;
1788
2032
  }
1789
- const validated = FlagPersonaBreakSchema.parse(input);
2033
+ const validated = validateOrDrop(FlagPersonaBreakSchema, input, "flagPersonaBreak");
2034
+ if (validated === null) return;
1790
2035
  await state.client.sendFlag(state.config.deployment, validated);
1791
2036
  }
1792
2037
  /**
@@ -1814,6 +2059,7 @@ var Probe = class {
1814
2059
  if (state === null) {
1815
2060
  return;
1816
2061
  }
2062
+ detachOtelState();
1817
2063
  state = null;
1818
2064
  }
1819
2065
  // ── Internal helpers ─────────────────────────────────────────────────────