@cultured_computer/sight 0.8.0 → 0.8.1

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