@cultured_computer/sight 0.8.0 → 0.8.2

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
@@ -19,41 +19,44 @@ var IngestClient = class {
19
19
  debug;
20
20
  dashboardUrl;
21
21
  /**
22
- * First-trace permalink: the first
23
- * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,
24
- * then never again for the life of this client (one IngestClient per
25
- * process — one `init` per process; a restart prints once more, accepted).
26
- * Failed sends do not consume the announcement. Only sendTurn announces:
27
- * flags, outcome events, and session-end sends never trigger it (a flag
28
- * arriving before any turn is not a captured session).
22
+ * The first accepted turn prints one stderr line with a link to the
23
+ * session on the dashboard, once per client (one client per init). A
24
+ * failed send does not use it up. Only turns print it; flags, outcome
25
+ * events and session ends do not.
29
26
  */
30
27
  firstCaptureAnnounced = false;
31
28
  /**
32
- * Rate-limit (429) handling: the first 429 per process prints one stderr
33
- * warning (not debug-gated, same channel and lifetime as the first-capture
34
- * announce); subsequent 429s only debug-log. Each rate-limited request is
35
- * retried exactly once after Retry-After; pendingRetries counts retries
36
- * waiting on their timers so the cap can shed load.
29
+ * Rate limiting (429): the first 429 prints one stderr warning, with or
30
+ * without `debug`; later ones log only with `debug: true`. Each
31
+ * rate-limited request is retried once after Retry-After. At most 50
32
+ * retries wait at a time; past that, a rate-limited request is dropped.
37
33
  */
38
34
  rateLimitAnnounced = false;
39
35
  pendingRetries = 0;
36
+ /**
37
+ * Rejected sends (a 4xx other than 429): the first one of each class
38
+ * (401, 403, any other status) prints one stderr warning, with or
39
+ * without `debug`. A rejected send is never retried: the same key and
40
+ * the same body get the same answer.
41
+ */
42
+ rejectionAnnounced = /* @__PURE__ */ new Set();
40
43
  inFlight = 0;
41
44
  shedAnnounced = false;
42
45
  /**
43
- * Every network send goes through here: adds the per-send timeout and
44
- * the in-flight cap. At the cap, the send is SHED (thrown into the
45
- * caller's existing fire-and-log catch) rather than queued;
46
- * the first shed per process warns on stderr, the rest debug-log.
46
+ * Every send goes through here: a 15 second timeout per send and at most
47
+ * 64 sends in flight. Past that, a new send is dropped, not queued; the
48
+ * first drop prints one stderr warning, later ones log only with
49
+ * `debug: true`.
47
50
  */
48
51
  async guardedFetch(url, init) {
49
52
  if (this.inFlight >= MAX_INFLIGHT) {
50
53
  if (!this.shedAnnounced) {
51
54
  this.shedAnnounced = true;
52
55
  console.error(
53
- `[sight] ${MAX_INFLIGHT} sends already in flight \u2014 shedding new sends (ingest slow or unreachable; this warning prints once)`
56
+ `[sight] ${MAX_INFLIGHT} sends are already in flight, so new captures are dropped until some finish. The Sight API is slow or unreachable: check the endpoint and your network. This warning prints once per process.`
54
57
  );
55
58
  }
56
- throw new Error("in-flight cap reached \u2014 send shed");
59
+ throw new Error(`${MAX_INFLIGHT} sends already in flight; this send was dropped`);
57
60
  }
58
61
  this.inFlight++;
59
62
  try {
@@ -63,12 +66,10 @@ var IngestClient = class {
63
66
  }
64
67
  }
65
68
  /**
66
- * Await all in-flight sends (bounded). Called by Sight.shutdown() so
67
- * short-lived processes (serverless, CLI scripts) can actually exit after
68
- * it — the documented "in-flight sends finish within 15s" only holds while
69
- * the process lives. Polling is coarse on purpose: sends report through
70
- * guardedFetch's counter and scheduled retries, never awaited individually.
71
- * Retries beyond the drain budget remain best-effort, not durable delivery.
69
+ * Wait for sends in flight and pending retries, for at most `timeoutMs`
70
+ * (default 15 seconds). Called by Sight.shutdown() so a short-lived
71
+ * process can exit without losing a send. A retry still waiting when
72
+ * the time is up is not guaranteed to be sent.
72
73
  */
73
74
  async drainInFlight(timeoutMs = SEND_TIMEOUT_MS) {
74
75
  const deadline = Date.now() + timeoutMs;
@@ -83,8 +84,7 @@ var IngestClient = class {
83
84
  this.dashboardUrl = (opts.dashboardUrl ?? DEFAULT_DASHBOARD_URL).replace(/\/$/, "");
84
85
  }
85
86
  /**
86
- * Send a turn to the ingest API. Fire-and-log: errors are logged but never
87
- * thrown. The customer's LLM path never blocks on capture.
87
+ * Send a turn. Errors are logged with `debug: true`, never thrown.
88
88
  */
89
89
  async sendTurn(turn) {
90
90
  try {
@@ -92,7 +92,7 @@ var IngestClient = class {
92
92
  const bodyBytes = new TextEncoder().encode(body).byteLength;
93
93
  if (bodyBytes > MAX_TURN_BODY_BYTES) {
94
94
  this.log(
95
- `[sight] turn dropped: payload ${bodyBytes} bytes exceeds the ${MAX_TURN_BODY_BYTES}-byte cap (session=${turn.sessionExternalId} turn=${turn.turnIndex}) \u2014 trim the payload you attach`
95
+ `[sight] turn dropped: its body is ${bodyBytes} bytes, over the ${MAX_TURN_BODY_BYTES}-byte limit (session=${turn.sessionExternalId} turn=${turn.turnIndex}). Send a smaller payload.`
96
96
  );
97
97
  return;
98
98
  }
@@ -107,6 +107,7 @@ var IngestClient = class {
107
107
  const response = await this.retryIfRateLimited(await send(), send);
108
108
  if (response === null) return;
109
109
  if (!response.ok) {
110
+ this.announceRejection(response.status, "a turn");
110
111
  this.log(`[sight] ingest failed status=${response.status}`);
111
112
  return;
112
113
  }
@@ -126,8 +127,8 @@ var IngestClient = class {
126
127
  }
127
128
  }
128
129
  /**
129
- * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.
130
- * Populates the `user_flagged_break` outcome column on the dashboard.
130
+ * Send a persona-break flag. Errors are logged with `debug: true`, never
131
+ * thrown.
131
132
  */
132
133
  async sendFlag(deploymentSlug, flag) {
133
134
  try {
@@ -148,6 +149,7 @@ var IngestClient = class {
148
149
  const response = await this.retryIfRateLimited(await send(), send);
149
150
  if (response === null) return;
150
151
  if (!response.ok) {
152
+ this.announceRejection(response.status, "a flag");
151
153
  this.log(`[sight] flag ingest failed status=${response.status}`);
152
154
  return;
153
155
  }
@@ -160,8 +162,8 @@ var IngestClient = class {
160
162
  }
161
163
  }
162
164
  /**
163
- * Send a session-end event to the ingest API. Records why a session ended
164
- * on the session. Fire-and-log.
165
+ * Send a session end: why the session ended. Errors are logged with
166
+ * `debug: true`, never thrown.
165
167
  */
166
168
  async sendSessionEnd(deploymentSlug, end) {
167
169
  try {
@@ -180,6 +182,7 @@ var IngestClient = class {
180
182
  const response = await this.retryIfRateLimited(await send(), send);
181
183
  if (response === null) return;
182
184
  if (!response.ok) {
185
+ this.announceRejection(response.status, "a session end");
183
186
  this.log(`[sight] session-end ingest failed status=${response.status}`);
184
187
  return;
185
188
  }
@@ -192,8 +195,8 @@ var IngestClient = class {
192
195
  }
193
196
  }
194
197
  /**
195
- * Send an outcome event to the ingest API. Fire-and-log. Populates
196
- * the outcome-events store.
198
+ * Send an outcome event. Errors are logged with `debug: true`, never
199
+ * thrown.
197
200
  */
198
201
  async sendOutcomeEvent(deploymentSlug, event) {
199
202
  try {
@@ -215,6 +218,7 @@ var IngestClient = class {
215
218
  const response = await this.retryIfRateLimited(await send(), send);
216
219
  if (response === null) return;
217
220
  if (!response.ok) {
221
+ this.announceRejection(response.status, "an outcome event");
218
222
  this.log(`[sight] outcome-event ingest failed status=${response.status}`);
219
223
  return;
220
224
  }
@@ -229,9 +233,8 @@ var IngestClient = class {
229
233
  }
230
234
  }
231
235
  /**
232
- * Send an environment-event batch to the ingest API. Fire-and-log, same as
233
- * sendTurn. The envelope is generalized: the worker attaches each event to
234
- * its session's record by time; meaning is per-deployment.
236
+ * Send a batch of environment events. Errors are logged with
237
+ * `debug: true`, never thrown.
235
238
  */
236
239
  async sendEnvironmentEvents(batch) {
237
240
  try {
@@ -246,6 +249,7 @@ var IngestClient = class {
246
249
  const response = await this.retryIfRateLimited(await send(), send);
247
250
  if (response === null) return;
248
251
  if (!response.ok) {
252
+ this.announceRejection(response.status, "an environment events batch");
249
253
  this.log(`[sight] environment-events ingest failed status=${response.status}`);
250
254
  return;
251
255
  }
@@ -258,10 +262,8 @@ var IngestClient = class {
258
262
  }
259
263
  }
260
264
  /**
261
- * Send a span batch to the ingest API. Fire-and-log, same as sendTurn.
262
- * Spans carry sub-turn structure (llm_call / tool_call / framework_step /
263
- * custom); the worker resolves each span's session/turn and wires in-batch
264
- * parent references.
265
+ * Send a batch of spans. Errors are logged with `debug: true`, never
266
+ * thrown.
265
267
  */
266
268
  async sendSpans(batch) {
267
269
  try {
@@ -276,6 +278,7 @@ var IngestClient = class {
276
278
  const response = await this.retryIfRateLimited(await send(), send);
277
279
  if (response === null) return;
278
280
  if (!response.ok) {
281
+ this.announceRejection(response.status, "a spans batch");
279
282
  this.log(`[sight] spans ingest failed status=${response.status}`);
280
283
  return;
281
284
  }
@@ -288,21 +291,19 @@ var IngestClient = class {
288
291
  }
289
292
  }
290
293
  /**
291
- * Route a send response through the 429 retry policy. Non-429 responses
292
- * pass through untouched. A 429 is re-sent exactly once after Retry-After
293
- * seconds (default 1s when the header is missing or unparseable; clamped
294
- * to [1, 60]s); the retry's response is returned as-is, so a second 429 is
295
- * never retried again — callers log and drop it like any other failed
296
- * send. Returns null when the retry was dropped at the pending-retry cap.
297
- * The timer is unref'd (where supported) so a pending retry never holds
298
- * the process open.
294
+ * The 429 retry rule. Any other response passes through. A 429 is sent
295
+ * again once after Retry-After seconds (1 second when the header is
296
+ * missing or unreadable; kept between 1 and 60 seconds). The retry's
297
+ * response is returned as is, so a second 429 is not retried. Returns
298
+ * null when the retry was dropped because 50 retries were already
299
+ * waiting. A waiting retry does not keep the process alive.
299
300
  */
300
301
  async retryIfRateLimited(response, resend) {
301
302
  if (response.status !== 429) return response;
302
303
  if (!this.rateLimitAnnounced) {
303
304
  this.rateLimitAnnounced = true;
304
305
  console.error(
305
- "Sight: ingest rate limit (429) \u2014 retrying once per Retry-After; sustained limiting drops captures. See https://sight.cultured.computer/docs/sdk-reference#rate-limits"
306
+ "[sight] rate limited (429). Each rate-limited send is retried once after Retry-After; if the retry is limited too, that capture is dropped. Send fewer requests per minute or ask for a higher limit: https://sight.cultured.computer/docs/sdk-reference#rate-limits (this warning prints once per process)"
306
307
  );
307
308
  } else {
308
309
  this.log("[sight] ingest rate limited (429), retrying once");
@@ -325,6 +326,20 @@ var IngestClient = class {
325
326
  this.pendingRetries -= 1;
326
327
  }
327
328
  }
329
+ /**
330
+ * The once-per-class warning for a send the API rejected. Not gated on
331
+ * debug: a rejected key drops every capture, so the host is told once.
332
+ * 429 has its own warning (see retryIfRateLimited); a 5xx is the API's
333
+ * failure, not the host's, and stays a debug line.
334
+ */
335
+ announceRejection(status, what) {
336
+ if (status < 400 || status >= 500 || status === 429) return;
337
+ const cls = status === 401 ? "401" : status === 403 ? "403" : "other";
338
+ if (this.rejectionAnnounced.has(cls)) return;
339
+ this.rejectionAnnounced.add(cls);
340
+ const line = cls === "401" ? "[sight] the API rejected the key (401). Nothing is being captured. Set apiKey to a key with the ingest capability." : cls === "403" ? "[sight] this key cannot capture (403): it lacks the ingest permission. Nothing is being captured. Ask the project owner for a Capture key." : `[sight] the API rejected ${what} (${status}) and it was dropped. Set debug: true to log every failed send. This warning prints once per process.`;
341
+ console.error(line);
342
+ }
328
343
  log(msg) {
329
344
  if (this.debug) {
330
345
  console.error(msg);
@@ -345,17 +360,18 @@ var SignaturePhraseSchema = zod.z.union([
345
360
  })
346
361
  ]);
347
362
  var PersonaConfigSchema = zod.z.object({
348
- /** Persona slug matching the deployment's registered persona. */
363
+ /** The persona's slug. */
349
364
  slug: zod.z.string().min(1),
350
365
  /**
351
- * RICE authorship artifact (Role, Identity, Communication, Engagement).
352
- * Either inline object or a path/URL to a JSON file loaded at init time.
366
+ * The persona's description (role, identity, communication, engagement):
367
+ * an object, or a string reference to one. Optional. This SDK does not
368
+ * read or send it.
353
369
  */
354
370
  rice: zod.z.union([zod.z.record(zod.z.string(), zod.z.unknown()), zod.z.string()]).optional(),
355
371
  /**
356
- * Customer-authored signature phrases for this persona. Compiled once at
357
- * init and matched per turn at the SDK edge; matched slugs appear on the
358
- * outgoing turn as `signaturePhraseMatches`.
372
+ * Signature phrases for this persona. Compiled once and matched against
373
+ * each reply in the SDK; matched slugs are sent with the turn as
374
+ * `signaturePhraseMatches`.
359
375
  */
360
376
  signaturePhrases: zod.z.array(SignaturePhraseSchema).optional()
361
377
  });
@@ -363,27 +379,24 @@ var OutcomeHookSchema = zod.z.object({
363
379
  /** Type of outcome the deployment tracks. */
364
380
  type: zod.z.enum(["numeric", "categorical", "boolean", "duration"]),
365
381
  /**
366
- * Callback that resolves the outcome for a completed session. Invoked by
367
- * Sight.endSession() with the session's externalId; a non-null result
368
- * lands as an outcome event on the session. Not invoked for sessions
369
- * swept server-side (no explicit endSession) — use emitOutcomeEvent()
370
- * for outcomes that become known out of band.
382
+ * Resolves the outcome of a finished session. Called by
383
+ * Sight.endSession() with the session's externalId; a non-null result is
384
+ * sent as an outcome event on the session. Not called for a session you
385
+ * never end; use emitOutcomeEvent() for an outcome known later.
371
386
  */
372
387
  resolve: zod.z.custom()
373
388
  });
374
389
  var ProbeConfigSchema = zod.z.object({
375
- /** The project's API key (an ingest key from the dashboard). Required. */
390
+ /** The project's API key: a key with the `ingest` capability. Required. */
376
391
  apiKey: zod.z.string().min(1),
377
392
  /** Deployment slug: the configuration this traffic belongs to. Required. */
378
393
  deployment: zod.z.string().min(1),
379
- /** Ingest endpoint. Defaults to the production ingest service,
380
- `https://fieldwork-ingest.fly.dev`. */
381
- endpoint: zod.z.string().url().default("https://fieldwork-ingest.fly.dev"),
394
+ /** The API host the captures are sent to. Defaults to
395
+ `https://api.cultured.computer`. */
396
+ endpoint: zod.z.string().url().default("https://api.cultured.computer"),
382
397
  /**
383
- * Dashboard base URL used by the one-time first-capture announcement
384
- * (the stderr permalink printed after the first successful send).
385
- * Self-hosted or staging dashboards override it the same way `endpoint`
386
- * is overridden.
398
+ * Dashboard base URL for the link printed on stderr after the first
399
+ * accepted turn. Set it only for a self-hosted or staging dashboard.
387
400
  */
388
401
  dashboardUrl: zod.z.string().url().default("https://sight.cultured.computer/dashboard"),
389
402
  /** Persona identification. Optional at init; can be set later via identifyPersona(). */
@@ -391,26 +404,25 @@ var ProbeConfigSchema = zod.z.object({
391
404
  /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */
392
405
  outcomeHook: OutcomeHookSchema.optional(),
393
406
  /**
394
- * Sample rate for autocapture. 1.0 = 100% of calls captured. Lower values
395
- * sample deterministically so a given (turnId) always resolves identically.
407
+ * Share of turns sent, from 0 to 1. Default 1.0: every turn. Below 1.0
408
+ * the choice is deterministic per (session id, turn index). Applies to
409
+ * autocapture and to captureTurn.
396
410
  */
397
411
  sampleRate: zod.z.number().min(0).max(1).default(1),
398
412
  /**
399
- * Debug mode: log every captured turn to stderr with a prefix. Never logs
400
- * the Bearer token or PII.
413
+ * Debug mode: log every send and every failed send to stderr, prefixed
414
+ * `[sight]`. Never logs the API key or conversation text.
401
415
  */
402
416
  debug: zod.z.boolean().default(false)
403
417
  });
404
418
  var SessionStartSchema = zod.z.object({
405
- /** Customer's session identity (opaque string; used as the correlation key). */
419
+ /** Your id for the session: one conversation. Any non-empty string. */
406
420
  externalId: zod.z.string().min(1),
407
421
  /**
408
- * Customer's USER identity (opaque string), distinct from externalId:
409
- * externalId keys the session; externalUserId ties sessions to a
410
- * returning user. Forwarded on every captured turn so the worker can
411
- * persist it on the session row — return-with-persona-consistency and
412
- * prior-session metrics require it. Optional; deployments that do not
413
- * identify users simply skip the user-level return metrics.
422
+ * Your id for the person: a stable, pseudonymous string, distinct from
423
+ * externalId. It ties one person's sessions together and is sent with
424
+ * every captured turn. Optional; without it, sessions are still captured
425
+ * and nothing links them to a returning person.
414
426
  */
415
427
  externalUserId: zod.z.string().min(1).optional(),
416
428
  /**
@@ -419,30 +431,26 @@ var SessionStartSchema = zod.z.object({
419
431
  * deployments where init already carries the persona.
420
432
  */
421
433
  persona: zod.z.string().min(1).optional(),
422
- /**
423
- * How the user got into this session.
424
- * Retention semantics differ radically between a resume and a fresh
425
- * notification landing.
426
- */
434
+ /** How the person arrived in this session. */
427
435
  openedVia: zod.z.enum(["link", "notification", "resume", "direct", "share"]).optional(),
428
436
  /**
429
- * Environmental context: browser / device / locale / tz. You choose
430
- * which fields to include. See the collectClientContext helper.
437
+ * Client context: locale, timezone, runtime, and anything else you
438
+ * choose to include. Stored as sent. See startSessionWithContext.
431
439
  */
432
440
  clientContext: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
433
441
  /**
434
- * Optional customer metadata attached to the session. Forwarded with the
435
- * first captured turn merged into `clientContext` under the `metadata`
436
- * key, so it is stored with the session.
442
+ * Your own metadata for the session. Sent with the first captured turn,
443
+ * inside `clientContext` under the `metadata` key, and stored as sent.
437
444
  */
438
445
  metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
439
446
  /**
440
- * RLDS episode-level provenance. Powers the version behavioral diff
441
- * on the dashboard. All optional.
442
- * agentId — model/policy version
443
- * experimentId — A/B arm or feature flag
444
- * environmentConfigHash — SHA of prompt/config file(s)
445
- * environmentConfigLabel — human-readable version label
447
+ * Version tags for the session, used to compare versions on the
448
+ * dashboard. All optional.
449
+ * agentId model or policy version
450
+ * experimentId A/B arm or feature flag
451
+ * environmentConfigHash hash of the prompt or configuration
452
+ * (see Sight.hashEnvironmentConfig)
453
+ * environmentConfigLabel readable name for that version
446
454
  */
447
455
  agentId: zod.z.string().optional(),
448
456
  experimentId: zod.z.string().optional(),
@@ -471,9 +479,9 @@ var FlagPersonaBreakSchema = zod.z.object({
471
479
  var OutcomeEventEmitSchema = zod.z.object({
472
480
  sessionExternalId: zod.z.string().min(1),
473
481
  kind: zod.z.string().min(1),
474
- /** Optional turn index this event is caused by. Omit to attach to latest turn. */
482
+ /** The turn that caused the outcome. Omit to attach to the latest turn. */
475
483
  causingTurnIndex: zod.z.number().int().nonnegative().optional(),
476
- /** Optional detail payload (customer-defined). */
484
+ /** Your own detail for the outcome. Optional. */
477
485
  detail: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
478
486
  });
479
487
 
@@ -595,12 +603,12 @@ function reportNoSessionSkip(source, debug) {
595
603
  );
596
604
  }
597
605
  }
598
- var AI_MODEL_CALL_KEY = api.createContextKey("sight.ai_model_call");
599
- function runInsideAiModelCall(fn) {
600
- return api.context.with(api.context.active().setValue(AI_MODEL_CALL_KEY, true), fn);
606
+ var HANDLED_CALL_KEY = api.createContextKey("sight.handled_model_call");
607
+ function runInsideHandledCall(fn) {
608
+ return api.context.with(api.context.active().setValue(HANDLED_CALL_KEY, true), fn);
601
609
  }
602
- function isInsideAiModelCall(ctx = api.context.active()) {
603
- return ctx.getValue(AI_MODEL_CALL_KEY) === true;
610
+ function isInsideHandledCall(ctx = api.context.active()) {
611
+ return ctx.getValue(HANDLED_CALL_KEY) === true;
604
612
  }
605
613
  var MAX_CLAIMS = 1e3;
606
614
  var claims = /* @__PURE__ */ new Set();
@@ -1062,13 +1070,15 @@ var ProbeSpanProcessor = class {
1062
1070
  if (captureFn) this.captureFn = captureFn;
1063
1071
  }
1064
1072
  /**
1065
- * Spans started inside an `ai` model call that the Sight `ai` integration
1066
- * captures (a provider that calls an instrumented client). Never turns.
1073
+ * Spans started inside a model call another Sight path captures: an `ai`
1074
+ * model call the `ai` integration handles (a provider that calls an
1075
+ * instrumented client), or a call through a wrapped OpenAI client that
1076
+ * is also module-patched. Never turns.
1067
1077
  */
1068
- insideAiCall = /* @__PURE__ */ new WeakSet();
1078
+ insideHandledCall = /* @__PURE__ */ new WeakSet();
1069
1079
  onStart(span, parentContext) {
1070
1080
  try {
1071
- if (isInsideAiModelCall(parentContext)) this.insideAiCall.add(span);
1081
+ if (isInsideHandledCall(parentContext)) this.insideHandledCall.add(span);
1072
1082
  } catch {
1073
1083
  }
1074
1084
  }
@@ -1083,7 +1093,7 @@ var ProbeSpanProcessor = class {
1083
1093
  return;
1084
1094
  }
1085
1095
  if (!isLLMCall(a)) return;
1086
- if (this.insideAiCall.has(span)) {
1096
+ if (this.insideHandledCall.has(span)) {
1087
1097
  this.takeToolChildren(span);
1088
1098
  return;
1089
1099
  }
@@ -1111,7 +1121,7 @@ var ProbeSpanProcessor = class {
1111
1121
  } catch (err) {
1112
1122
  if (state2.config.debug) {
1113
1123
  console.error(
1114
- `[sight] span processor error: ${err instanceof Error ? err.message : err}`
1124
+ `[sight] a span could not be read and was skipped (${err instanceof Error ? err.message : err}).`
1115
1125
  );
1116
1126
  }
1117
1127
  }
@@ -1123,7 +1133,7 @@ var ProbeSpanProcessor = class {
1123
1133
  } catch (err) {
1124
1134
  if (this.state?.config.debug) {
1125
1135
  console.error(
1126
- `[sight] span processor error: ${err instanceof Error ? err.message : err}`
1136
+ `[sight] a span could not be read and was skipped (${err instanceof Error ? err.message : err}).`
1127
1137
  );
1128
1138
  }
1129
1139
  }
@@ -1160,7 +1170,7 @@ var ProbeSpanProcessor = class {
1160
1170
  })().catch((err) => {
1161
1171
  if (state2.config.debug) {
1162
1172
  console.error(
1163
- `[sight] span capture error: ${err instanceof Error ? err.message : err}`
1173
+ `[sight] a turn read from a span was not captured (${err instanceof Error ? err.message : err}).`
1164
1174
  );
1165
1175
  }
1166
1176
  });
@@ -1341,7 +1351,7 @@ function emit(params, payload) {
1341
1351
  if (!warnedUnbound) {
1342
1352
  warnedUnbound = true;
1343
1353
  console.warn(
1344
- "[sight] wrapOpenAI: call observed before Sight.init(); nothing captured until init runs."
1354
+ "[sight] wrapOpenAI: a call ran before Sight.init() and was not captured. Call Sight.init() once at startup."
1345
1355
  );
1346
1356
  }
1347
1357
  return;
@@ -1368,7 +1378,7 @@ function emit(params, payload) {
1368
1378
  await captureFn(captured);
1369
1379
  })().catch((err) => {
1370
1380
  if (state2.config.debug) {
1371
- console.error(`[sight] wrapOpenAI capture error: ${err instanceof Error ? err.message : err}`);
1381
+ console.error(`[sight] wrapOpenAI: a turn was not captured (${err instanceof Error ? err.message : err}).`);
1372
1382
  }
1373
1383
  });
1374
1384
  }
@@ -1539,7 +1549,7 @@ function wrapCreate(client, target, api, makeAccumulator, extractResponse) {
1539
1549
  const original = target["create"];
1540
1550
  if (typeof original !== "function") return;
1541
1551
  target["create"] = function(...args) {
1542
- if (isInsideAiModelCall()) return original.apply(this, args);
1552
+ if (isInsideHandledCall()) return original.apply(this, args);
1543
1553
  const params = asRecord(args[0]);
1544
1554
  const requestModel = asString2(params?.["model"]);
1545
1555
  const startedAt = now();
@@ -1551,7 +1561,7 @@ function wrapCreate(client, target, api, makeAccumulator, extractResponse) {
1551
1561
  requestModel,
1552
1562
  baseURL
1553
1563
  });
1554
- const result = original.apply(this, args);
1564
+ const result = runInsideHandledCall(() => original.apply(this, args));
1555
1565
  if (!result || typeof result.then !== "function") return result;
1556
1566
  return result.then(
1557
1567
  (resolved) => {
@@ -1767,7 +1777,7 @@ function emit2(options, call, request, fields) {
1767
1777
  if (!everBound && !warnedUnbound2) {
1768
1778
  warnedUnbound2 = true;
1769
1779
  console.warn(
1770
- "[sight] ai telemetry: call observed before Sight.init(); nothing captured until init runs."
1780
+ "[sight] ai telemetry: a call ran before Sight.init() and was not captured. Call Sight.init() once at startup."
1771
1781
  );
1772
1782
  }
1773
1783
  return;
@@ -1797,7 +1807,7 @@ function emit2(options, call, request, fields) {
1797
1807
  })().catch((err) => {
1798
1808
  if (state2.config.debug) {
1799
1809
  console.error(
1800
- `[sight] ai telemetry capture error: ${err instanceof Error ? err.message : err}`
1810
+ `[sight] ai telemetry: a turn was not captured (${err instanceof Error ? err.message : err}).`
1801
1811
  );
1802
1812
  }
1803
1813
  });
@@ -1814,7 +1824,7 @@ function guarded(fn) {
1814
1824
  } catch (err) {
1815
1825
  if (bound2?.state.config.debug) {
1816
1826
  console.error(
1817
- `[sight] ai telemetry hook error: ${err instanceof Error ? err.message : err}`
1827
+ `[sight] ai telemetry: an event could not be read and was skipped (${err instanceof Error ? err.message : err}).`
1818
1828
  );
1819
1829
  }
1820
1830
  }
@@ -1978,7 +1988,7 @@ function createIntegration(options) {
1978
1988
  }),
1979
1989
  executeLanguageModelCall(callOptions) {
1980
1990
  if (!bound2) return callOptions.execute();
1981
- return runInsideAiModelCall(() => callOptions.execute());
1991
+ return runInsideHandledCall(() => callOptions.execute());
1982
1992
  }
1983
1993
  };
1984
1994
  Object.defineProperty(integration, BRAND, { value: true });
@@ -2015,20 +2025,20 @@ function register(mod, debug) {
2015
2025
  if (typeof registerTelemetry !== "function") {
2016
2026
  if (debug) {
2017
2027
  console.log(
2018
- "[sight/vercel-ai] ai <7 found: no integration to register; calls made with experimental_telemetry: { isEnabled: true } are captured from their OpenTelemetry spans"
2028
+ "[sight] ai below 7 found: nothing to register. Calls made with experimental_telemetry: { isEnabled: true } are captured from their OpenTelemetry spans."
2019
2029
  );
2020
2030
  }
2021
2031
  return;
2022
2032
  }
2023
2033
  registered = true;
2024
2034
  if (globalIntegrations().some(isSightIntegration)) {
2025
- if (debug) console.log("[sight/vercel-ai] telemetry integration already registered");
2035
+ if (debug) console.log("[sight] ai: the telemetry integration was already registered.");
2026
2036
  return;
2027
2037
  }
2028
2038
  registerTelemetry(sightTelemetry());
2029
2039
  if (debug) {
2030
2040
  console.log(
2031
- "[sight/vercel-ai] telemetry integration registered; generateText, streamText, generateObject and streamObject calls are captured, one turn per model call"
2041
+ "[sight] ai: telemetry integration registered. generateText, streamText, generateObject and streamObject calls are captured, one turn per model call."
2032
2042
  );
2033
2043
  }
2034
2044
  }
@@ -2048,7 +2058,7 @@ async function registerVercelAI(state2, captureFn, loaders = defaultLoaders) {
2048
2058
  } catch {
2049
2059
  if (debug) {
2050
2060
  console.log(
2051
- "[sight/vercel-ai] ai is not installed; nothing registered. If ai is bundled where the SDK cannot resolve it, call registerTelemetry(sightTelemetry())."
2061
+ "[sight] ai was not found, so nothing was registered. If ai is bundled where the SDK cannot resolve it, call registerTelemetry(sightTelemetry()) yourself."
2052
2062
  );
2053
2063
  }
2054
2064
  return;
@@ -2059,7 +2069,7 @@ async function registerVercelAI(state2, captureFn, loaders = defaultLoaders) {
2059
2069
  } catch (err) {
2060
2070
  if (debug) {
2061
2071
  console.warn(
2062
- `[sight/vercel-ai] telemetry integration not registered (${err instanceof Error ? err.message : err})`
2072
+ `[sight] ai: the telemetry integration was not registered (${err instanceof Error ? err.message : err}). Call registerTelemetry(sightTelemetry()) yourself.`
2063
2073
  );
2064
2074
  }
2065
2075
  }
@@ -2103,7 +2113,7 @@ async function registerOpenAI(state2) {
2103
2113
  exceptionLogger: (err) => {
2104
2114
  if (state2.config.debug) {
2105
2115
  console.error(
2106
- `[sight/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`
2116
+ `[sight] OpenAI instrumentation error: ${err instanceof Error ? err.message : err}`
2107
2117
  );
2108
2118
  }
2109
2119
  }
@@ -2114,7 +2124,7 @@ async function registerOpenAI(state2) {
2114
2124
  } catch (err) {
2115
2125
  if (state2.config.debug) {
2116
2126
  const msg = err instanceof Error ? err.message : String(err);
2117
- console.warn(`[sight/openai] instrumentation not enabled (${msg}); library not installed?`);
2127
+ console.warn(`[sight] OpenAI module instrumentation is not enabled (${msg}). Wrap the client: wrapOpenAI(new OpenAI()).`);
2118
2128
  }
2119
2129
  }
2120
2130
  }
@@ -2128,11 +2138,16 @@ function patchWarning(mod, wrappedClientInUse) {
2128
2138
  if (!isPatchDetached(mod)) return null;
2129
2139
  if (wrappedClientInUse) return null;
2130
2140
  const version = mod?.default?.VERSION ?? mod?.VERSION;
2131
- return `[sight] OpenAI module patching did not attach` + (version ? ` (openai v${version})` : "") + `. This happens on openai >=5, under ESM, or when 'openai' loads before init. Calls through a client passed to wrapOpenAI() are captured; calls through an unwrapped OpenAI client are not. import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()).`;
2141
+ return `[sight] OpenAI module patching did not attach` + (version ? ` (openai v${version})` : "") + `. It needs CommonJS and an openai version the bundled instrumentation supports. Calls through a client passed to wrapOpenAI() are captured; calls through an unwrapped OpenAI client are not. Fix: import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()).`;
2142
+ }
2143
+ async function loadApplicationOpenAI() {
2144
+ const cjsRequire = typeof module !== "undefined" && typeof module.require === "function" ? module.require.bind(module) : null;
2145
+ if (cjsRequire !== null) return cjsRequire("openai");
2146
+ return import('openai');
2132
2147
  }
2133
2148
  async function verifyPatchAttached() {
2134
2149
  try {
2135
- const mod = await import('openai');
2150
+ const mod = await loadApplicationOpenAI();
2136
2151
  const line = patchWarning(mod, hasWrappedClient());
2137
2152
  if (line !== null) console.warn(line);
2138
2153
  } catch {
@@ -2150,7 +2165,7 @@ async function registerAnthropic(state2) {
2150
2165
  exceptionLogger: (err) => {
2151
2166
  if (state2.config.debug) {
2152
2167
  console.error(
2153
- `[sight/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`
2168
+ `[sight] Anthropic instrumentation error: ${err instanceof Error ? err.message : err}`
2154
2169
  );
2155
2170
  }
2156
2171
  }
@@ -2161,7 +2176,7 @@ async function registerAnthropic(state2) {
2161
2176
  if (state2.config.debug) {
2162
2177
  const msg = err instanceof Error ? err.message : String(err);
2163
2178
  console.warn(
2164
- `[sight/anthropic] instrumentation not enabled (${msg}); library not installed?`
2179
+ `[sight] Anthropic instrumentation is not enabled (${msg}). Anthropic calls are not captured; record them with Sight.captureTurn().`
2165
2180
  );
2166
2181
  }
2167
2182
  }
@@ -2178,7 +2193,7 @@ async function registerLangChain(state2) {
2178
2193
  exceptionLogger: (err) => {
2179
2194
  if (state2.config.debug) {
2180
2195
  console.error(
2181
- `[sight/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`
2196
+ `[sight] LangChain instrumentation error: ${err instanceof Error ? err.message : err}`
2182
2197
  );
2183
2198
  }
2184
2199
  }
@@ -2189,7 +2204,7 @@ async function registerLangChain(state2) {
2189
2204
  if (state2.config.debug) {
2190
2205
  const msg = err instanceof Error ? err.message : String(err);
2191
2206
  console.warn(
2192
- `[sight/langchain] instrumentation not enabled (${msg}); library not installed?`
2207
+ `[sight] LangChain instrumentation is not enabled (${msg}). LangChain calls are not captured; record them with Sight.captureTurn().`
2193
2208
  );
2194
2209
  }
2195
2210
  }
@@ -2202,7 +2217,7 @@ async function registerLangGraph(state2) {
2202
2217
  registered5 = true;
2203
2218
  if (state2.config.debug) {
2204
2219
  console.log(
2205
- "[sight/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology"
2220
+ "[sight] LangGraph: model calls go through the LangChain instrumentation; no separate setup."
2206
2221
  );
2207
2222
  }
2208
2223
  }
@@ -2214,7 +2229,7 @@ async function registerLiteLLM(state2) {
2214
2229
  registered6 = true;
2215
2230
  if (state2.config.debug) {
2216
2231
  console.log(
2217
- "[sight/litellm] LiteLLM (Python) traffic is not captured by this SDK"
2232
+ "[sight] LiteLLM (Python) calls are not captured by this SDK. Record them with Sight.captureTurn() or the HTTP API."
2218
2233
  );
2219
2234
  }
2220
2235
  }
@@ -2226,7 +2241,7 @@ async function registerMercury(state2) {
2226
2241
  registered7 = true;
2227
2242
  if (state2.config.debug) {
2228
2243
  console.log(
2229
- "[sight/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route"
2244
+ '[sight] Mercury: a call through an OpenAI client pointed at Inception is sent with provider "inception". Wrap the client with wrapOpenAI().'
2230
2245
  );
2231
2246
  }
2232
2247
  }
@@ -2248,7 +2263,7 @@ function registerAllInstrumentations(state2, captureFn) {
2248
2263
  if (!state2.config.debug) return;
2249
2264
  for (const result of results) {
2250
2265
  if (result.status === "rejected") {
2251
- console.error(`[sight] adapter register rejected: ${result.reason}`);
2266
+ console.error(`[sight] an instrumentation failed to register (${result.reason}); calls through that library are not captured.`);
2252
2267
  }
2253
2268
  }
2254
2269
  });
@@ -2959,7 +2974,7 @@ function validateOrDrop(schema, input, method) {
2959
2974
  if (!result.success) {
2960
2975
  const issue = result.error?.issues?.[0];
2961
2976
  console.warn(
2962
- `[sight] ${method}: invalid input dropped \u2014 ${issue ? `${issue.path?.join(".") || "(root)"}: ${issue.message}` : "schema mismatch"}`
2977
+ `[sight] ${method}: invalid input dropped (${issue ? `${issue.path?.join(".") || "(root)"}: ${issue.message}` : "the input does not match the expected shape"}). Nothing was sent; fix that field.`
2963
2978
  );
2964
2979
  return null;
2965
2980
  }
@@ -2983,12 +2998,16 @@ function newTurnId() {
2983
2998
  }
2984
2999
  var Probe = class {
2985
3000
  /**
2986
- * Initialize the SDK. Call once at process start. Subsequent calls are
2987
- * no-ops with a warning; re-init requires a shutdown() first.
3001
+ * Initialize the SDK. Call once at process start. Throws on an invalid
3002
+ * configuration; no other method throws on bad input. A second call
3003
+ * prints one warning and is ignored; call shutdown() first to
3004
+ * re-initialize.
2988
3005
  */
2989
3006
  static init(config) {
2990
3007
  if (state !== null) {
2991
- console.warn("[sight] already initialized; call shutdown() first");
3008
+ console.warn(
3009
+ "[sight] Sight.init() was called again and ignored. Call Sight.shutdown() first to change the configuration."
3010
+ );
2992
3011
  return;
2993
3012
  }
2994
3013
  const validated = ProbeConfigSchema.parse(config);
@@ -3021,33 +3040,38 @@ var Probe = class {
3021
3040
  );
3022
3041
  }
3023
3042
  /**
3024
- * Run a callback inside a session scope. Every LLM call made inside `fn`
3025
- * through a wrapped OpenAI client or an instrumented library is captured
3026
- * as a turn on the session `sessionId`.
3043
+ * Run a callback inside a session scope. Every model call made inside
3044
+ * `fn` through a wrapped OpenAI client, the Vercel AI SDK or an
3045
+ * instrumented library is captured as a turn on the session `sessionId`
3046
+ * (your conversation id).
3027
3047
  *
3028
- * Autocapture needs this scope: a call made outside any session scope is
3029
- * not captured. The first such call in a process prints one warning;
3030
- * later ones log only with `debug: true`. (Spans that carry
3031
- * `gen_ai.conversation.id` are the one exception: with no scope, that id
3032
- * is used as the session id. An explicit scope always wins.)
3048
+ * Required for autocapture: a call made outside any session scope is not
3049
+ * captured. The first such call in a process prints one warning; later
3050
+ * ones log only with `debug: true`. Exceptions, used only when there is
3051
+ * no scope: a span that carries `gen_ai.conversation.id`, and an `ai`
3052
+ * call that names its session (see `sightTelemetry`). An explicit scope
3053
+ * always wins.
3033
3054
  *
3034
- * The scope is carried in OpenTelemetry baggage across awaits.
3055
+ * The scope is carried across awaits. Returns what `fn` returns.
3035
3056
  */
3036
3057
  static async withSession(sessionId, fn) {
3037
3058
  if (state === null) {
3038
- console.warn("[sight] withSession called before init");
3059
+ console.warn(
3060
+ "[sight] Sight.withSession() ran before Sight.init(): the callback ran, nothing is captured. Call Sight.init() once at startup."
3061
+ );
3039
3062
  return fn();
3040
3063
  }
3041
3064
  return withSession(sessionId, fn);
3042
3065
  }
3043
3066
  /**
3044
- * Identify the process-level default persona. Overwrites any previously-set
3045
- * default. For per-session persona identification (multi-persona products),
3046
- * use startSession({ externalId, persona }) instead.
3067
+ * Set the default persona for the process. Replaces the previous default.
3068
+ * To set a persona per session, use startSession({ externalId, persona }).
3047
3069
  */
3048
3070
  static identifyPersona(persona) {
3049
3071
  if (state === null) {
3050
- console.warn("[sight] identifyPersona called before init");
3072
+ console.warn(
3073
+ "[sight] Sight.identifyPersona() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3074
+ );
3051
3075
  return;
3052
3076
  }
3053
3077
  state.persona = persona;
@@ -3059,18 +3083,18 @@ var Probe = class {
3059
3083
  }
3060
3084
  }
3061
3085
  /**
3062
- * Start (or update) a session with an active persona.
3086
+ * Start (or update) a session. Optional: a session is created on its
3087
+ * first captured turn. Call it to attach `externalUserId` (your stable,
3088
+ * pseudonymous user id), a persona, version tags or client context.
3063
3089
  *
3064
- * Single-persona deployments can skip this if the init-level default is
3065
- * enough; the SDK will still create a session entry lazily on first turn.
3066
- * Multi-persona products call this at conversation start so every turn in
3067
- * the session inherits the selected persona.
3068
- *
3069
- * Idempotent: calling with the same externalId updates the entry.
3090
+ * Calling it again with the same externalId updates the entry. Invalid
3091
+ * input logs one warning and is ignored.
3070
3092
  */
3071
3093
  static startSession(input) {
3072
3094
  if (state === null) {
3073
- console.warn("[sight] startSession called before init");
3095
+ console.warn(
3096
+ "[sight] Sight.startSession() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3097
+ );
3074
3098
  return;
3075
3099
  }
3076
3100
  const validated = validateOrDrop(SessionStartSchema, input, "startSession");
@@ -3136,39 +3160,32 @@ var Probe = class {
3136
3160
  return entry;
3137
3161
  }
3138
3162
  /**
3139
- * Compute a stable SHA-256 hex hash of prompt/config text for use as
3140
- * `environmentConfigHash` on Sight.startSession(). Hash is *identity*:
3141
- * pass the human-readable version alongside as `environmentConfigLabel`
3142
- * for the diff table axis (a card keyed by a3f9c2… is unreadable).
3143
- *
3144
- * Ships as a helper because inconsistent hashing across restarts breaks
3145
- * The version behavioral diff — every customer would
3146
- * hash their own way and version-diff would become noise.
3163
+ * SHA-256 hex hash of prompt or configuration text, for
3164
+ * `environmentConfigHash` on Sight.startSession(). The hash identifies a
3165
+ * version; pass a readable name alongside as `environmentConfigLabel`.
3147
3166
  *
3148
- * The same hashing (src/hash.ts) backs the OTel processor's automatic
3149
- * version stamping: when autocapture sees a system message and the
3150
- * deployer set no environmentConfigHash, the session is stamped with
3151
- * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit
3152
- * startSession values always win over the auto stamp.
3167
+ * Autocapture uses the same hash: when it sees a system prompt and the
3168
+ * session has no environmentConfigHash, the session gets the system
3169
+ * prompt's hash and the label 'auto:' plus its first 8 characters.
3170
+ * Values you pass to startSession always win.
3153
3171
  */
3154
3172
  static async hashEnvironmentConfig(input) {
3155
3173
  return hashEnvironmentConfig(input);
3156
3174
  }
3157
3175
  /**
3158
- * End a session and release its in-memory entry. Optional (sessions time out
3159
- * eventually), but recommended for long-running processes with many distinct
3160
- * conversations. If `input.endedReason` is provided the SDK sends an end
3161
- * event to ingest so the worker records the reason server-side.
3176
+ * End a session: sends the end reason (`natural` when none is given) and
3177
+ * releases the session's in-memory entry. Optional; a session you never
3178
+ * end times out on the server.
3162
3179
  *
3163
- * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`
3164
- * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`
3165
- * and, when it returns a non-null OutcomeResult, lands it as an outcome
3166
- * event (kind = result.outcome, detail carries type/value). This is the
3167
- * ONLY place the SDK invokes the hook — there are no client-side timers,
3168
- * so sessions that are never ended explicitly are swept server-side as
3169
- * `timeout` and receive no hook-resolved outcome; land those via
3170
- * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:
3171
- * a throwing or rejecting hook never breaks endSession.
3180
+ * - `outcome` (with optional `outcomeDetail`) is sent as an outcome
3181
+ * event before the session end.
3182
+ * - With no `outcome` and an outcome hook registered (init `outcomeHook`
3183
+ * or wireOutcomeHook()), `hook.resolve(externalId)` runs; a non-null
3184
+ * result is sent as an outcome event. This is the only place the hook
3185
+ * runs. A hook that throws logs one warning and does not break
3186
+ * endSession.
3187
+ * - For an outcome known later, or for a session you never end, call
3188
+ * emitOutcomeEvent().
3172
3189
  */
3173
3190
  static async endSession(externalId) {
3174
3191
  if (state === null) return;
@@ -3203,7 +3220,7 @@ var Probe = class {
3203
3220
  }
3204
3221
  } catch (err) {
3205
3222
  console.warn(
3206
- "[sight] outcome hook resolve failed:",
3223
+ "[sight] the outcome hook's resolve() threw, so no outcome was sent for this session. Fix the hook, or send the outcome with Sight.emitOutcomeEvent(). Error:",
3207
3224
  err instanceof Error ? err.message : err
3208
3225
  );
3209
3226
  }
@@ -3215,7 +3232,7 @@ var Probe = class {
3215
3232
  endedReason
3216
3233
  }).catch((err) => {
3217
3234
  console.warn(
3218
- "[sight] sendSessionEnd failed:",
3235
+ "[sight] the session end was not sent. Call Sight.endSession() again, or leave the session to time out. Error:",
3219
3236
  err instanceof Error ? err.message : err
3220
3237
  );
3221
3238
  });
@@ -3229,10 +3246,9 @@ var Probe = class {
3229
3246
  // before startSession or the first LLM call) buffer per externalId and
3230
3247
  // flush into the session when it is created.
3231
3248
  /**
3232
- * The person started typing. Records the first-keystroke time, sent as
3233
- * `userInput.firstKeystrokeMs` with the next captured turn. Derivable
3234
- * only once a previous agent turn exists; a pre-session typing start
3235
- * buffers the pending-input entry without a firstKeystrokeMs value.
3249
+ * The person started typing. Records the time since the previous reply,
3250
+ * sent as `userInput.firstKeystrokeMs` with the next captured turn. No
3251
+ * value is sent before the session's first captured turn.
3236
3252
  */
3237
3253
  static userInputStart(externalId) {
3238
3254
  if (state === null) return;
@@ -3261,9 +3277,9 @@ var Probe = class {
3261
3277
  }
3262
3278
  /**
3263
3279
  * The person submitted their message. Records the text (scrubbed of
3264
- * personal data server-side before it is stored) plus the submit
3265
- * timestamp. The text and timings are sent with the NEXT captured turn:
3266
- * a turn's person text is the message that prompted its reply.
3280
+ * personal data server-side before it is stored) and the submit time.
3281
+ * Both are sent with the next captured turn: a turn's person text is the
3282
+ * message that prompted its reply. Call it before the model call.
3267
3283
  */
3268
3284
  static userInputSubmit(externalId, text) {
3269
3285
  if (state === null) return;
@@ -3278,7 +3294,7 @@ var Probe = class {
3278
3294
  };
3279
3295
  target.lastUserSubmitAt = now2;
3280
3296
  }
3281
- /** Attach a thumbs-up/down to the current turn. */
3297
+ /** Record a thumbs-up or thumbs-down. Sent with the next captured turn. */
3282
3298
  static userThumbs(externalId, thumbs) {
3283
3299
  if (state === null) return;
3284
3300
  if (validateOrDrop(UserThumbsSchema, { externalId, thumbs }, "userThumbs") === null) return;
@@ -3289,8 +3305,8 @@ var Probe = class {
3289
3305
  };
3290
3306
  }
3291
3307
  /**
3292
- * Attach an explicit rating to the current turn: an integer from 1 to 5.
3293
- * Any other value logs one warning line and is dropped.
3308
+ * Record a rating: an integer from 1 to 5. Sent with the next captured
3309
+ * turn. Any other value logs one warning line and is dropped.
3294
3310
  */
3295
3311
  static userRating(externalId, rating) {
3296
3312
  if (state === null) return;
@@ -3302,7 +3318,8 @@ var Probe = class {
3302
3318
  };
3303
3319
  }
3304
3320
  /**
3305
- * Helper: collect client context and pass it to startSession in one call.
3321
+ * startSession, with client context (locale, timezone, runtime) collected
3322
+ * for you unless `input.clientContext` is given.
3306
3323
  */
3307
3324
  static startSessionWithContext(input, includes) {
3308
3325
  this.startSession({
@@ -3311,41 +3328,45 @@ var Probe = class {
3311
3328
  });
3312
3329
  }
3313
3330
  /**
3314
- * Register the outcome hook: declares the deployment's outcome type and
3315
- * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked
3316
- * by endSession() — explicit close is the only trigger; the SDK runs no
3317
- * client-side timers. A non-null OutcomeResult lands as an outcome event
3318
- * on the session. Sessions that are never ended explicitly are swept
3319
- * server-side and never resolve through the hook; land those outcomes via
3320
- * emitOutcomeEvent() from the place where the outcome becomes known
3321
- * (webhook, CRM callback); it joins back by sessionExternalId.
3331
+ * Register the outcome hook: the deployment's outcome type and a
3332
+ * resolver for it. `resolve(sessionExternalId)` runs only when you call
3333
+ * endSession() without an `outcome`; the SDK runs no timers. A non-null
3334
+ * result is sent as an outcome event on the session. For a session you
3335
+ * never end, or an outcome known later (webhook, CRM callback), call
3336
+ * emitOutcomeEvent(); it joins to the session by sessionExternalId.
3322
3337
  */
3323
3338
  static wireOutcomeHook(hook) {
3324
3339
  if (state === null) {
3325
- console.warn("[sight] wireOutcomeHook called before init");
3340
+ console.warn(
3341
+ "[sight] Sight.wireOutcomeHook() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3342
+ );
3326
3343
  return;
3327
3344
  }
3328
3345
  state.outcomeHook = hook;
3329
3346
  }
3330
3347
  /**
3331
- * Manually capture a turn. For callers that do not use autocapture.
3348
+ * Capture a turn yourself, for a model call autocapture does not see.
3332
3349
  *
3350
+ * - `turnIndex` is the turn's position in the session, starting at 0.
3333
3351
  * - `deploymentSlug` may be omitted: the `deployment` given to `init` is
3334
3352
  * used. An explicit value wins.
3335
3353
  * - Every turn is sent with a `turnId` (a fresh UUID unless you supply
3336
3354
  * one). A retried send carries the same `turnId`.
3337
- * - The turn is validated before it is sent. An invalid turn logs one
3355
+ * - The turn is checked before it is sent. An invalid turn logs one
3338
3356
  * warning line naming the first invalid field and is dropped; nothing
3339
3357
  * is sent.
3358
+ * - A failed send never throws; it logs with `debug: true`. The first
3359
+ * send the API rejects (401, 403, another 4xx) prints one warning
3360
+ * without it.
3340
3361
  *
3341
- * Persona resolution order for the outgoing turn payload:
3342
- * 1. turn.personaSlug (turn-level override)
3362
+ * Persona used for the turn, in this order:
3363
+ * 1. turn.personaSlug
3343
3364
  * 2. the session's persona (from startSession)
3344
- * 3. the init-level default
3365
+ * 3. the default from init or identifyPersona
3345
3366
  *
3346
- * Signature-phrase matching runs in the SDK when the resolved persona
3347
- * has signature phrases registered. The matched slug list is attached to
3348
- * `turn.signaturePhraseMatches` before send.
3367
+ * When that persona has signature phrases, the SDK matches them against
3368
+ * the reply text and sends the matched slugs as
3369
+ * `signaturePhraseMatches`.
3349
3370
  */
3350
3371
  static async captureTurn(turn) {
3351
3372
  return this.captureWithHints(turn);
@@ -3500,17 +3521,18 @@ var Probe = class {
3500
3521
  });
3501
3522
  }
3502
3523
  /**
3503
- * Emit a custom outcome event on a session, stored with the `kind`
3504
- * string you supply. Use for
3505
- * customer-defined kinds like "purchase_complete", "handoff_to_human",
3506
- * "character_break_severe". Universal seed kinds (break, escalation,
3507
- * resolution, thumbs_*, rating_*) are also emitted by worker-side
3508
- * detectors automatically — call this only when the customer has a
3509
- * signal the worker cannot infer.
3524
+ * Record an outcome on a session, stored with the `kind` string you
3525
+ * supply: for example "ticket_resolved", "purchase_complete",
3526
+ * "handoff_to_human". Call it wherever the outcome becomes known, at any
3527
+ * time after the session; it joins to the session by sessionExternalId.
3528
+ * Invalid input logs one warning and is dropped. A failed send never
3529
+ * throws.
3510
3530
  */
3511
3531
  static async emitOutcomeEvent(input) {
3512
3532
  if (state === null) {
3513
- console.warn("[sight] emitOutcomeEvent called before init");
3533
+ console.warn(
3534
+ "[sight] Sight.emitOutcomeEvent() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3535
+ );
3514
3536
  return;
3515
3537
  }
3516
3538
  const validated = validateOrDrop(
@@ -3522,21 +3544,21 @@ var Probe = class {
3522
3544
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
3523
3545
  }
3524
3546
  /**
3525
- * Capture one environment event against a session. The
3526
- * envelope is generalized: `source_type` and `event` are free strings whose
3527
- * meaning is defined per deployment — the instrument stores the event and
3528
- * attaches it to the session's record by time (the next turn's state
3529
- * corner, plus the causing turn's outcome corner when `causeProvenance`
3530
- * names a turn index), and never interprets it. Fire-and-log, like
3531
- * captureTurn: errors are debug-logged, never thrown.
3547
+ * Record one event from a channel beside the conversation (a feed, a
3548
+ * game state, an editor buffer) against a session. `source_type` and
3549
+ * `event` are free strings; you define their meaning. The event is
3550
+ * stored and attached to the session's turns by time, and is not
3551
+ * interpreted. Errors are logged with `debug: true`, never thrown.
3532
3552
  *
3533
- * Alignment defaults to the SDK's own clock claim; deployments with a
3534
- * stricter clock contract (or batches) should call
3535
- * captureEnvironmentEvents with explicit alignment provenance.
3553
+ * `alignment` describes the clock the event's time comes from. It
3554
+ * defaults to this process's clock; to state your own clock, or to send
3555
+ * a batch, call captureEnvironmentEvents.
3536
3556
  */
3537
3557
  static async captureEnvironmentEvent(event, alignment) {
3538
3558
  if (state === null) {
3539
- console.warn("[sight] captureEnvironmentEvent called before init");
3559
+ console.warn(
3560
+ "[sight] Sight.captureEnvironmentEvent() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3561
+ );
3540
3562
  return;
3541
3563
  }
3542
3564
  const validated = validateOrDrop(
@@ -3556,15 +3578,17 @@ var Probe = class {
3556
3578
  });
3557
3579
  }
3558
3580
  /**
3559
- * Capture a batch of environment events with explicit alignment provenance
3560
- * (clock_source, skew_bound_ms, rule_version). Batches are capped at 100
3561
- * events and may span sessions — every event is self-addressed. Same
3562
- * generalized envelope and fire-and-log discipline as the single-event
3563
- * capture above.
3581
+ * Record a batch of environment events, with an optional `alignment`
3582
+ * (clock_source, skew_bound_ms, rule_version) describing their clock. At
3583
+ * most 100 events per call. Events in one batch may belong to different
3584
+ * sessions; each names its own. Errors are logged with `debug: true`,
3585
+ * never thrown.
3564
3586
  */
3565
3587
  static async captureEnvironmentEvents(events, alignment = DEFAULT_ENVIRONMENT_ALIGNMENT) {
3566
3588
  if (state === null) {
3567
- console.warn("[sight] captureEnvironmentEvents called before init");
3589
+ console.warn(
3590
+ "[sight] Sight.captureEnvironmentEvents() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3591
+ );
3568
3592
  return;
3569
3593
  }
3570
3594
  const batch = validateOrDrop(
@@ -3576,22 +3600,23 @@ var Probe = class {
3576
3600
  await state.client.sendEnvironmentEvents(batch);
3577
3601
  }
3578
3602
  /**
3579
- * Capture one sub-turn span against a session: one LLM call, one tool
3580
- * call, one framework step, or a custom unit inside a turn. The span lands
3581
- * on the turn named by `turnIndex`, or — when omitted — on the session's
3582
- * latest turn at/under the span's `startedAt` (most recent turn when
3583
- * `startedAt` is also absent). A span whose turn cannot be resolved is
3584
- * dropped server-side; spans never land unattributed. Fire-and-log, like
3585
- * captureTurn: errors are debug-logged, never thrown.
3603
+ * Record one span: a step inside a turn (a model call, a tool call, a
3604
+ * framework step, or a custom unit). The span attaches to the turn named
3605
+ * by `turnIndex`; when omitted, to the session's latest turn at or
3606
+ * before the span's `startedAt` (the most recent turn when `startedAt`
3607
+ * is absent too). A span whose turn cannot be found is dropped by the
3608
+ * server. Errors are logged with `debug: true`, never thrown.
3586
3609
  *
3587
- * `attributes` are metadata only (tool names, argument shapes) — never
3588
- * free-text conversation content. Alignment defaults to the SDK's own
3589
- * clock claim; deployments with a stricter clock contract (or batches, or
3590
- * parent references between spans) should call captureSpans.
3610
+ * `attributes` are metadata only (tool names, argument shapes), never
3611
+ * conversation text. `alignment` defaults to this process's clock; to
3612
+ * state your own clock, send a batch, or link parent and child spans,
3613
+ * call captureSpans.
3591
3614
  */
3592
3615
  static async captureSpan(span, alignment) {
3593
3616
  if (state === null) {
3594
- console.warn("[sight] captureSpan called before init");
3617
+ console.warn(
3618
+ "[sight] Sight.captureSpan() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3619
+ );
3595
3620
  return;
3596
3621
  }
3597
3622
  const validated = validateOrDrop(SpanInputSchema, span, "captureSpan");
@@ -3600,17 +3625,19 @@ var Probe = class {
3600
3625
  await state.client.sendSpans({ spans: [validated], alignment: align });
3601
3626
  }
3602
3627
  /**
3603
- * Capture a batch of spans with explicit alignment provenance
3604
- * (clock_source, skew_bound_ms, rule_version). Batches are capped at 50
3605
- * spans and may span sessions — every span is self-addressed. Parent
3606
- * structure rides the batch: a span's `parentSpanId` names another span's
3607
- * caller-local `spanId` within the same batch and is wired server-side
3608
- * (unresolvable references land null). Same fire-and-log discipline as the
3609
- * single-span capture above.
3628
+ * Record a batch of spans, with an optional `alignment` (clock_source,
3629
+ * skew_bound_ms, rule_version) describing their clock. At most 50 spans
3630
+ * per call. Spans in one batch may belong to different sessions; each
3631
+ * names its own. To link parent and child, give a span a `spanId` and
3632
+ * name it in another span's `parentSpanId` within the same batch; a
3633
+ * reference that matches no span is stored as null. Errors are logged
3634
+ * with `debug: true`, never thrown.
3610
3635
  */
3611
3636
  static async captureSpans(spans, alignment) {
3612
3637
  if (state === null) {
3613
- console.warn("[sight] captureSpans called before init");
3638
+ console.warn(
3639
+ "[sight] Sight.captureSpans() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3640
+ );
3614
3641
  return;
3615
3642
  }
3616
3643
  const batch = validateOrDrop(
@@ -3622,16 +3649,15 @@ var Probe = class {
3622
3649
  await state.client.sendSpans(batch);
3623
3650
  }
3624
3651
  /**
3625
- * Flag a persona break for a session. Wire this to the customer's in-product
3626
- * "that didn't sound like you" UX. Populates the `user_flagged_break`
3627
- * outcome column on the dashboard.
3628
- *
3629
- * If `turnIndex` is omitted, the flag attaches to the session's most
3630
- * recent turn.
3652
+ * Record a person's report that a reply was out of character. Connect it
3653
+ * to your product's report control. With no `turnIndex`, the flag
3654
+ * attaches to the session's most recent turn.
3631
3655
  */
3632
3656
  static async flagPersonaBreak(input) {
3633
3657
  if (state === null) {
3634
- console.warn("[sight] flagPersonaBreak called before init");
3658
+ console.warn(
3659
+ "[sight] Sight.flagPersonaBreak() was called before Sight.init() and ignored. Call Sight.init() once at startup."
3660
+ );
3635
3661
  return;
3636
3662
  }
3637
3663
  const validated = validateOrDrop(
@@ -3657,11 +3683,11 @@ var Probe = class {
3657
3683
  return "";
3658
3684
  }
3659
3685
  /**
3660
- * Shut down the SDK: discards the singleton state (sessions, pending
3661
- * user-side signals, the pre-session buffer) so init() can be called
3662
- * again. There is no send queue to flush — every capture awaits its own
3663
- * HTTP send — and instrumentation stays registered for the life of the
3664
- * process. Idempotent.
3686
+ * Shut down the SDK: waits for sends in flight (at most 15 seconds),
3687
+ * then clears the in-memory state (sessions, pending input) so init()
3688
+ * can be called again. Model calls made after shutdown are not captured
3689
+ * until the next init. Await it before a short-lived process exits; a
3690
+ * send still in flight at exit is lost. Safe to call more than once.
3665
3691
  */
3666
3692
  static async shutdown() {
3667
3693
  if (state === null) {
@@ -3673,7 +3699,7 @@ var Probe = class {
3673
3699
  await client.drainInFlight();
3674
3700
  }
3675
3701
  // ── Internal helpers ─────────────────────────────────────────────────────
3676
- /** Package-internal: instrumentation adapters read this to build turns. */
3702
+ /** Internal. Not part of the public API. */
3677
3703
  static _getState() {
3678
3704
  return state;
3679
3705
  }