@cultured_computer/sight 0.7.1 → 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.cjs CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  var zod = require('zod');
4
4
  var api = require('@opentelemetry/api');
5
+ var module$1 = require('module');
6
+
7
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
8
+ // src/probe.ts
5
9
 
6
10
  // src/client.ts
7
11
  var DEFAULT_DASHBOARD_URL = "https://sight.cultured.computer/dashboard";
@@ -15,41 +19,44 @@ var IngestClient = class {
15
19
  debug;
16
20
  dashboardUrl;
17
21
  /**
18
- * First-trace permalink: the first
19
- * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,
20
- * then never again for the life of this client (one IngestClient per
21
- * process — one `init` per process; a restart prints once more, accepted).
22
- * Failed sends do not consume the announcement. Only sendTurn announces:
23
- * flags, outcome events, and session-end sends never trigger it (a flag
24
- * 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.
25
26
  */
26
27
  firstCaptureAnnounced = false;
27
28
  /**
28
- * Rate-limit (429) handling: the first 429 per process prints one stderr
29
- * warning (not debug-gated, same channel and lifetime as the first-capture
30
- * announce); subsequent 429s only debug-log. Each rate-limited request is
31
- * retried exactly once after Retry-After; pendingRetries counts retries
32
- * 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.
33
33
  */
34
34
  rateLimitAnnounced = false;
35
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();
36
43
  inFlight = 0;
37
44
  shedAnnounced = false;
38
45
  /**
39
- * Every network send goes through here: adds the per-send timeout and
40
- * the in-flight cap (audit B1). At the cap, the send is SHED — thrown
41
- * into the caller's existing fire-and-log catch — rather than queued;
42
- * the first shed per process warns on stderr, the rest debug-log.
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`.
43
50
  */
44
51
  async guardedFetch(url, init) {
45
52
  if (this.inFlight >= MAX_INFLIGHT) {
46
53
  if (!this.shedAnnounced) {
47
54
  this.shedAnnounced = true;
48
55
  console.error(
49
- `[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.`
50
57
  );
51
58
  }
52
- throw new Error("in-flight cap reached \u2014 send shed");
59
+ throw new Error(`${MAX_INFLIGHT} sends already in flight; this send was dropped`);
53
60
  }
54
61
  this.inFlight++;
55
62
  try {
@@ -59,12 +66,10 @@ var IngestClient = class {
59
66
  }
60
67
  }
61
68
  /**
62
- * Await all in-flight sends (bounded). Called by Probe.shutdown() so
63
- * short-lived processes (serverless, CLI scripts) can actually exit after
64
- * it — the documented "in-flight sends finish within 15s" only holds while
65
- * the process lives. Polling is coarse on purpose: sends report through
66
- * guardedFetch's counter and scheduled retries, never awaited individually.
67
- * 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.
68
73
  */
69
74
  async drainInFlight(timeoutMs = SEND_TIMEOUT_MS) {
70
75
  const deadline = Date.now() + timeoutMs;
@@ -79,8 +84,7 @@ var IngestClient = class {
79
84
  this.dashboardUrl = (opts.dashboardUrl ?? DEFAULT_DASHBOARD_URL).replace(/\/$/, "");
80
85
  }
81
86
  /**
82
- * Send a turn to the ingest API. Fire-and-log: errors are logged but never
83
- * thrown. The customer's LLM path never blocks on the Probe.
87
+ * Send a turn. Errors are logged with `debug: true`, never thrown.
84
88
  */
85
89
  async sendTurn(turn) {
86
90
  try {
@@ -88,7 +92,7 @@ var IngestClient = class {
88
92
  const bodyBytes = new TextEncoder().encode(body).byteLength;
89
93
  if (bodyBytes > MAX_TURN_BODY_BYTES) {
90
94
  this.log(
91
- `[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.`
92
96
  );
93
97
  return;
94
98
  }
@@ -103,6 +107,7 @@ var IngestClient = class {
103
107
  const response = await this.retryIfRateLimited(await send(), send);
104
108
  if (response === null) return;
105
109
  if (!response.ok) {
110
+ this.announceRejection(response.status, "a turn");
106
111
  this.log(`[sight] ingest failed status=${response.status}`);
107
112
  return;
108
113
  }
@@ -122,8 +127,8 @@ var IngestClient = class {
122
127
  }
123
128
  }
124
129
  /**
125
- * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.
126
- * 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.
127
132
  */
128
133
  async sendFlag(deploymentSlug, flag) {
129
134
  try {
@@ -144,6 +149,7 @@ var IngestClient = class {
144
149
  const response = await this.retryIfRateLimited(await send(), send);
145
150
  if (response === null) return;
146
151
  if (!response.ok) {
152
+ this.announceRejection(response.status, "a flag");
147
153
  this.log(`[sight] flag ingest failed status=${response.status}`);
148
154
  return;
149
155
  }
@@ -156,8 +162,8 @@ var IngestClient = class {
156
162
  }
157
163
  }
158
164
  /**
159
- * Send a session-end event to the ingest API. Records why a session ended
160
- * on the sessions.probe_session_ended_reason column. Fire-and-log.
165
+ * Send a session end: why the session ended. Errors are logged with
166
+ * `debug: true`, never thrown.
161
167
  */
162
168
  async sendSessionEnd(deploymentSlug, end) {
163
169
  try {
@@ -176,6 +182,7 @@ var IngestClient = class {
176
182
  const response = await this.retryIfRateLimited(await send(), send);
177
183
  if (response === null) return;
178
184
  if (!response.ok) {
185
+ this.announceRejection(response.status, "a session end");
179
186
  this.log(`[sight] session-end ingest failed status=${response.status}`);
180
187
  return;
181
188
  }
@@ -188,8 +195,8 @@ var IngestClient = class {
188
195
  }
189
196
  }
190
197
  /**
191
- * Send an outcome event to the ingest API. Fire-and-log. Populates
192
- * the outcome-events store.
198
+ * Send an outcome event. Errors are logged with `debug: true`, never
199
+ * thrown.
193
200
  */
194
201
  async sendOutcomeEvent(deploymentSlug, event) {
195
202
  try {
@@ -211,6 +218,7 @@ var IngestClient = class {
211
218
  const response = await this.retryIfRateLimited(await send(), send);
212
219
  if (response === null) return;
213
220
  if (!response.ok) {
221
+ this.announceRejection(response.status, "an outcome event");
214
222
  this.log(`[sight] outcome-event ingest failed status=${response.status}`);
215
223
  return;
216
224
  }
@@ -225,9 +233,8 @@ var IngestClient = class {
225
233
  }
226
234
  }
227
235
  /**
228
- * Send an environment-event batch to the ingest API. Fire-and-log, same as
229
- * sendTurn. The envelope is generalized: the worker attaches each event to
230
- * 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.
231
238
  */
232
239
  async sendEnvironmentEvents(batch) {
233
240
  try {
@@ -242,6 +249,7 @@ var IngestClient = class {
242
249
  const response = await this.retryIfRateLimited(await send(), send);
243
250
  if (response === null) return;
244
251
  if (!response.ok) {
252
+ this.announceRejection(response.status, "an environment events batch");
245
253
  this.log(`[sight] environment-events ingest failed status=${response.status}`);
246
254
  return;
247
255
  }
@@ -254,10 +262,8 @@ var IngestClient = class {
254
262
  }
255
263
  }
256
264
  /**
257
- * Send a span batch to the ingest API. Fire-and-log, same as sendTurn.
258
- * Spans carry sub-turn structure (llm_call / tool_call / framework_step /
259
- * custom); the worker resolves each span's session/turn and wires in-batch
260
- * parent references.
265
+ * Send a batch of spans. Errors are logged with `debug: true`, never
266
+ * thrown.
261
267
  */
262
268
  async sendSpans(batch) {
263
269
  try {
@@ -272,6 +278,7 @@ var IngestClient = class {
272
278
  const response = await this.retryIfRateLimited(await send(), send);
273
279
  if (response === null) return;
274
280
  if (!response.ok) {
281
+ this.announceRejection(response.status, "a spans batch");
275
282
  this.log(`[sight] spans ingest failed status=${response.status}`);
276
283
  return;
277
284
  }
@@ -284,21 +291,19 @@ var IngestClient = class {
284
291
  }
285
292
  }
286
293
  /**
287
- * Route a send response through the 429 retry policy. Non-429 responses
288
- * pass through untouched. A 429 is re-sent exactly once after Retry-After
289
- * seconds (default 1s when the header is missing or unparseable; clamped
290
- * to [1, 60]s); the retry's response is returned as-is, so a second 429 is
291
- * never retried again — callers log and drop it like any other failed
292
- * send. Returns null when the retry was dropped at the pending-retry cap.
293
- * The timer is unref'd (where supported) so a pending retry never holds
294
- * 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.
295
300
  */
296
301
  async retryIfRateLimited(response, resend) {
297
302
  if (response.status !== 429) return response;
298
303
  if (!this.rateLimitAnnounced) {
299
304
  this.rateLimitAnnounced = true;
300
305
  console.error(
301
- "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)"
302
307
  );
303
308
  } else {
304
309
  this.log("[sight] ingest rate limited (429), retrying once");
@@ -321,6 +326,20 @@ var IngestClient = class {
321
326
  this.pendingRetries -= 1;
322
327
  }
323
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 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.`;
341
+ console.error(line);
342
+ }
324
343
  log(msg) {
325
344
  if (this.debug) {
326
345
  console.error(msg);
@@ -341,17 +360,18 @@ var SignaturePhraseSchema = zod.z.union([
341
360
  })
342
361
  ]);
343
362
  var PersonaConfigSchema = zod.z.object({
344
- /** Persona slug matching the deployment's registered persona. */
363
+ /** The persona's slug. */
345
364
  slug: zod.z.string().min(1),
346
365
  /**
347
- * RICE authorship artifact (Role, Identity, Communication, Engagement).
348
- * 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.
349
369
  */
350
370
  rice: zod.z.union([zod.z.record(zod.z.string(), zod.z.unknown()), zod.z.string()]).optional(),
351
371
  /**
352
- * Customer-authored signature phrases for this persona. Compiled once at
353
- * init and matched per turn at the SDK edge; matched slugs appear on the
354
- * 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`.
355
375
  */
356
376
  signaturePhrases: zod.z.array(SignaturePhraseSchema).optional()
357
377
  });
@@ -359,26 +379,24 @@ var OutcomeHookSchema = zod.z.object({
359
379
  /** Type of outcome the deployment tracks. */
360
380
  type: zod.z.enum(["numeric", "categorical", "boolean", "duration"]),
361
381
  /**
362
- * Callback that resolves the outcome for a completed session. Invoked by
363
- * Probe.endSession() with the session's externalId; a non-null result
364
- * lands as an outcome event on the session. Not invoked for sessions
365
- * swept server-side (no explicit endSession) — use emitOutcomeEvent()
366
- * 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.
367
386
  */
368
387
  resolve: zod.z.custom()
369
388
  });
370
389
  var ProbeConfigSchema = zod.z.object({
371
- /** Unkey ingest key. Required. */
390
+ /** The project's API key: a key with the `ingest` capability. Required. */
372
391
  apiKey: zod.z.string().min(1),
373
- /** Deployment slug registered in the Probe backend. Required. */
392
+ /** Deployment slug: the configuration this traffic belongs to. Required. */
374
393
  deployment: zod.z.string().min(1),
375
- /** Ingest endpoint. Defaults to the production ingest service. */
376
- 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"),
377
397
  /**
378
- * Dashboard base URL used by the one-time first-capture announcement
379
- * (the stderr permalink printed after the first successful send).
380
- * Self-hosted or staging dashboards override it the same way `endpoint`
381
- * 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.
382
400
  */
383
401
  dashboardUrl: zod.z.string().url().default("https://sight.cultured.computer/dashboard"),
384
402
  /** Persona identification. Optional at init; can be set later via identifyPersona(). */
@@ -386,26 +404,25 @@ var ProbeConfigSchema = zod.z.object({
386
404
  /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */
387
405
  outcomeHook: OutcomeHookSchema.optional(),
388
406
  /**
389
- * Sample rate for autocapture. 1.0 = 100% of calls captured. Lower values
390
- * 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.
391
410
  */
392
411
  sampleRate: zod.z.number().min(0).max(1).default(1),
393
412
  /**
394
- * Debug mode: log every captured turn to stderr with a prefix. Never logs
395
- * 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.
396
415
  */
397
416
  debug: zod.z.boolean().default(false)
398
417
  });
399
418
  var SessionStartSchema = zod.z.object({
400
- /** Customer's session identity (opaque string; used as the correlation key). */
419
+ /** Your id for the session: one conversation. Any non-empty string. */
401
420
  externalId: zod.z.string().min(1),
402
421
  /**
403
- * Customer's USER identity (opaque string), distinct from externalId:
404
- * externalId keys the session; externalUserId ties sessions to a
405
- * returning user. Forwarded on every captured turn so the worker can
406
- * persist it on the session row — return-with-persona-consistency and
407
- * prior-session metrics require it. Optional; deployments that do not
408
- * 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.
409
426
  */
410
427
  externalUserId: zod.z.string().min(1).optional(),
411
428
  /**
@@ -414,37 +431,33 @@ var SessionStartSchema = zod.z.object({
414
431
  * deployments where init already carries the persona.
415
432
  */
416
433
  persona: zod.z.string().min(1).optional(),
417
- /**
418
- * How the user got into this session.
419
- * Retention semantics differ radically between a resume and a fresh
420
- * notification landing.
421
- */
434
+ /** How the person arrived in this session. */
422
435
  openedVia: zod.z.enum(["link", "notification", "resume", "direct", "share"]).optional(),
423
436
  /**
424
- * Environmental context — browser / device / locale / tz (P2). Customer-
425
- * configurable which fields to include. See collectClientContext helper.
437
+ * Client context: locale, timezone, runtime, and anything else you
438
+ * choose to include. Stored as sent. See startSessionWithContext.
426
439
  */
427
440
  clientContext: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
428
441
  /**
429
- * Optional customer metadata attached to the session. Forwarded with the
430
- * first captured turn merged into `clientContext` under the `metadata`
431
- * key, so it lands on sessions.probe_session_client_context.
442
+ * Your own metadata for the session. Sent with the first captured turn,
443
+ * inside `clientContext` under the `metadata` key, and stored as sent.
432
444
  */
433
445
  metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
434
446
  /**
435
- * RLDS episode-level provenance. Powers the version behavioral diff
436
- * on the dashboard. All optional.
437
- * agentId — model/policy version
438
- * experimentId — A/B arm or feature flag
439
- * environmentConfigHash — SHA of prompt/config file(s)
440
- * 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
441
454
  */
442
455
  agentId: zod.z.string().optional(),
443
456
  experimentId: zod.z.string().optional(),
444
457
  environmentConfigHash: zod.z.string().optional(),
445
458
  environmentConfigLabel: zod.z.string().optional()
446
459
  });
447
- zod.z.object({
460
+ var SessionEndSchema = zod.z.object({
448
461
  externalId: zod.z.string().min(1),
449
462
  endedReason: zod.z.enum([
450
463
  "natural",
@@ -466,9 +479,9 @@ var FlagPersonaBreakSchema = zod.z.object({
466
479
  var OutcomeEventEmitSchema = zod.z.object({
467
480
  sessionExternalId: zod.z.string().min(1),
468
481
  kind: zod.z.string().min(1),
469
- /** 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. */
470
483
  causingTurnIndex: zod.z.number().int().nonnegative().optional(),
471
- /** Optional detail payload (customer-defined). */
484
+ /** Your own detail for the outcome. Optional. */
472
485
  detail: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
473
486
  });
474
487
 
@@ -573,8 +586,53 @@ function getCurrentSessionId() {
573
586
  return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;
574
587
  }
575
588
 
589
+ // src/instrumentation/no-session.ts
590
+ var warned = false;
591
+ function noSessionWarning(source) {
592
+ return `[sight] call not captured (${source}): no session scope. Wrap LLM calls in Sight.withSession(id, fn) so they are recorded as turns. This warning prints once per process; later skips log only with debug: true.`;
593
+ }
594
+ function reportNoSessionSkip(source, debug) {
595
+ if (!warned) {
596
+ warned = true;
597
+ console.warn(noSessionWarning(source));
598
+ return;
599
+ }
600
+ if (debug) {
601
+ console.warn(
602
+ `[sight] call not captured (${source}): no session scope; wrap it in Sight.withSession(id, fn).`
603
+ );
604
+ }
605
+ }
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);
609
+ }
610
+ function isInsideHandledCall(ctx = api.context.active()) {
611
+ return ctx.getValue(HANDLED_CALL_KEY) === true;
612
+ }
613
+ var MAX_CLAIMS = 1e3;
614
+ var claims = /* @__PURE__ */ new Set();
615
+ var openCalls = 0;
616
+ function noteAiModelCallOpened() {
617
+ openCalls += 1;
618
+ }
619
+ function noteAiModelCallClosed() {
620
+ if (openCalls > 0) openCalls -= 1;
621
+ }
622
+ function aiModelCallsOpen() {
623
+ return openCalls > 0;
624
+ }
625
+ function claimAiResponse(responseId) {
626
+ claims.add(responseId);
627
+ if (claims.size > MAX_CLAIMS) claims.delete(claims.values().next().value);
628
+ }
629
+ function takeAiResponseClaim(responseId) {
630
+ return claims.delete(responseId);
631
+ }
632
+
576
633
  // src/instrumentation/otel-processor.ts
577
634
  var MAX_DEDUP_SPANS = 1e4;
635
+ var MAX_TOOL_PARENTS = 1e3;
578
636
  function attr(attrs, key) {
579
637
  return attrs[key];
580
638
  }
@@ -587,64 +645,261 @@ function asNumber(v) {
587
645
  function asStringArray(v) {
588
646
  return Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
589
647
  }
648
+ function firstNumber(attrs, ...keys) {
649
+ for (const key of keys) {
650
+ const n = asNumber(attrs[key]);
651
+ if (n !== void 0) return n;
652
+ }
653
+ return void 0;
654
+ }
655
+ function firstString(attrs, ...keys) {
656
+ for (const key of keys) {
657
+ const s = asString(attrs[key]);
658
+ if (s !== void 0 && s.length > 0) return s;
659
+ }
660
+ return void 0;
661
+ }
662
+ var CAPTURED_OPERATIONS = /* @__PURE__ */ new Set(["chat", "generate_content", "text_completion"]);
663
+ var AI_SDK_MODEL_CALL_OPERATIONS = /* @__PURE__ */ new Set([
664
+ "ai.generateText.doGenerate",
665
+ "ai.streamText.doStream",
666
+ "ai.generateObject.doGenerate",
667
+ "ai.streamObject.doStream"
668
+ ]);
669
+ function isAiSdkModelCall(attrs) {
670
+ const op = asString(attrs["ai.operationId"]);
671
+ return op !== void 0 && AI_SDK_MODEL_CALL_OPERATIONS.has(op);
672
+ }
590
673
  function isLLMCall(attrs) {
591
674
  const op = asString(attrs["gen_ai.operation.name"]);
592
- if (op === "chat" || op === "text_completion" || op === "embeddings") {
593
- return true;
675
+ if (op !== void 0) {
676
+ return CAPTURED_OPERATIONS.has(op);
594
677
  }
595
- const traceloopKind = asString(attrs["traceloop.span.kind"]);
596
- if (traceloopKind === "agent") return true;
597
- return false;
678
+ if (isAiSdkModelCall(attrs)) return true;
679
+ return asString(attrs["traceloop.span.kind"]) === "agent";
598
680
  }
599
681
  function isVercelAgentRollup(spanName, attrs) {
600
682
  return spanName.startsWith("invoke_agent ") && attrs["ai.telemetry.functionId"] !== void 0;
601
683
  }
602
684
  function taggedProvider(attrs) {
603
- const rawProvider = asString(attrs["gen_ai.system"] ?? attrs["gen_ai.provider"]);
685
+ const rawProvider = firstString(attrs, "gen_ai.provider.name", "gen_ai.system", "gen_ai.provider");
604
686
  const model = asString(attrs["gen_ai.request.model"]);
605
687
  if (model?.toLowerCase().startsWith("mercury")) {
606
688
  return "inception";
607
689
  }
608
690
  return rawProvider;
609
691
  }
610
- function buildPayload(span) {
692
+ function isRecord(v) {
693
+ return v !== null && typeof v === "object" && !Array.isArray(v);
694
+ }
695
+ function isMessageLike(v) {
696
+ return isRecord(v) && ("parts" in v || "content" in v || "role" in v);
697
+ }
698
+ function parseStructured(raw) {
699
+ if (typeof raw === "string") {
700
+ const t = raw.trimStart();
701
+ if (!t.startsWith("[") && !t.startsWith("{")) return void 0;
702
+ try {
703
+ return JSON.parse(raw);
704
+ } catch {
705
+ return void 0;
706
+ }
707
+ }
708
+ if (Array.isArray(raw)) {
709
+ return raw.map((el) => {
710
+ if (typeof el !== "string") return el;
711
+ try {
712
+ return JSON.parse(el);
713
+ } catch {
714
+ return el;
715
+ }
716
+ });
717
+ }
718
+ return raw;
719
+ }
720
+ function asMessageList(parsed) {
721
+ const list = Array.isArray(parsed) ? parsed : isMessageLike(parsed) ? [parsed] : void 0;
722
+ if (!list) return void 0;
723
+ const records = list.filter(isRecord);
724
+ return records.some(isMessageLike) ? records : void 0;
725
+ }
726
+ function partsOf(message) {
727
+ const p = message["parts"] ?? message["content"];
728
+ if (typeof p === "string") return [{ type: "text", content: p }];
729
+ return Array.isArray(p) ? p : [];
730
+ }
731
+ function textOfPart(part, types) {
732
+ if (typeof part === "string") return part;
733
+ if (!isRecord(part)) return void 0;
734
+ const type = part["type"];
735
+ if (type !== void 0 && !(typeof type === "string" && types.has(type))) return void 0;
736
+ const text = part["content"] ?? part["text"];
737
+ return typeof text === "string" ? text : void 0;
738
+ }
739
+ var TEXT_PART = /* @__PURE__ */ new Set(["text"]);
740
+ var INPUT_TEXT_PART = /* @__PURE__ */ new Set(["text", "input_text"]);
741
+ var REFUSAL_PART = /* @__PURE__ */ new Set(["refusal"]);
742
+ function joinText(parts, types, sep) {
743
+ const texts = [];
744
+ for (const part of parts) {
745
+ const t = textOfPart(part, types);
746
+ if (t !== void 0 && t.length > 0) texts.push(t);
747
+ }
748
+ return texts.length > 0 ? texts.join(sep) : void 0;
749
+ }
750
+ function parseOutputMessages(raw) {
751
+ const messages = asMessageList(parseStructured(raw));
752
+ if (!messages) return { structured: false, text: void 0, toolNames: [] };
753
+ const reply = messages.find((m) => {
754
+ const role = m["role"];
755
+ return role !== "user" && role !== "system" && role !== "developer" && role !== "tool";
756
+ });
757
+ if (!reply) return { structured: true, text: void 0, toolNames: [] };
758
+ const parts = partsOf(reply);
759
+ const toolNames = [];
760
+ for (const part of parts) {
761
+ if (!isRecord(part)) continue;
762
+ if (part["type"] === "tool_call" || part["type"] === "server_tool_call") {
763
+ const name = part["name"];
764
+ if (typeof name === "string" && name.length > 0) toolNames.push(name);
765
+ }
766
+ }
767
+ return {
768
+ structured: true,
769
+ text: joinText(parts, TEXT_PART, "") ?? joinText(parts, REFUSAL_PART, ""),
770
+ toolNames
771
+ };
772
+ }
773
+ function userTextFromMessages(raw, nested = false) {
774
+ const messages = asMessageList(parseStructured(raw));
775
+ if (!messages) return void 0;
776
+ for (let i = messages.length - 1; i >= 0; i--) {
777
+ const message = messages[i];
778
+ const role = message["role"];
779
+ if (role === "system" || role === "developer") continue;
780
+ if (role !== "user") return void 0;
781
+ const text = joinText(partsOf(message), nested ? INPUT_TEXT_PART : TEXT_PART, "\n");
782
+ if (text === void 0) return void 0;
783
+ return nested ? text : unwrapSerializedRequest(text);
784
+ }
785
+ return void 0;
786
+ }
787
+ function unwrapSerializedRequest(text) {
788
+ const parsed = parseStructured(text);
789
+ if (!Array.isArray(parsed) || !parsed.some(isRecord)) return text;
790
+ if (parsed.some(isMessageLike)) return userTextFromMessages(parsed, true);
791
+ return joinText(parsed, INPUT_TEXT_PART, "\n");
792
+ }
793
+ function extractUserText(attrs) {
794
+ return userTextFromMessages(attrs["gen_ai.input.messages"]) ?? (attrs["gen_ai.input.messages"] === void 0 ? userTextFromMessages(attrs["ai.prompt.messages"]) : void 0);
795
+ }
796
+ function aiSdkToolNames(raw) {
797
+ if (typeof raw !== "string") return [];
798
+ try {
799
+ const parsed = JSON.parse(raw);
800
+ if (!Array.isArray(parsed)) return [];
801
+ const names = [];
802
+ for (const call of parsed) {
803
+ const name = isRecord(call) ? call["toolName"] : void 0;
804
+ if (typeof name === "string" && name.length > 0) names.push(name);
805
+ }
806
+ return names;
807
+ } catch {
808
+ return [];
809
+ }
810
+ }
811
+ function toolNameOfSpan(spanName, attrs) {
812
+ const named = firstString(attrs, "gen_ai.tool.name", "traceloop.entity.name");
813
+ if (named) return named;
814
+ const prefix = "execute_tool ";
815
+ return spanName.startsWith(prefix) && spanName.length > prefix.length ? spanName.slice(prefix.length) : void 0;
816
+ }
817
+ function cacheTokensInInput(span) {
818
+ const scope = span.instrumentationScope?.name;
819
+ if (scope === "@traceloop/instrumentation-openai") return true;
820
+ if (scope === "@traceloop/instrumentation-anthropic") return false;
821
+ return void 0;
822
+ }
823
+ function reportedCost(attrs) {
824
+ const cost = asNumber(attrs["gen_ai.usage.cost"]);
825
+ return cost !== void 0 && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
826
+ }
827
+ function buildPayload(span, childToolNames = []) {
611
828
  const a = span.attributes;
612
829
  const start = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
613
830
  const end = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
614
831
  const latencyMs = Math.max(0, Math.round(end - start));
615
- const responseText = asString(attr(a, "ai.response.text")) ?? asString(attr(a, "gen_ai.output.messages"));
616
- const toolCallNames = asStringArray(attr(a, "gen_ai.response.tool_names"));
617
- const toolCallsCount = asNumber(attr(a, "gen_ai.response.tool_calls_count")) ?? toolCallNames?.length;
832
+ const rawOutput = a["gen_ai.output.messages"];
833
+ const output = parseOutputMessages(rawOutput);
834
+ const responseText = asString(attr(a, "ai.response.text")) ?? (output.structured ? output.text : typeof rawOutput === "string" ? rawOutput : void 0) ?? asString(attr(a, "ai.response.object"));
835
+ const aiToolNames = aiSdkToolNames(attr(a, "ai.response.toolCalls"));
836
+ const toolCallNames = output.toolNames.length > 0 ? output.toolNames : aiToolNames.length > 0 ? aiToolNames : childToolNames.length > 0 ? childToolNames : asStringArray(attr(a, "gen_ai.response.tool_names"));
837
+ const toolCallsCount = toolCallNames?.length ?? asNumber(attr(a, "gen_ai.response.tool_calls_count"));
618
838
  const finishReasons = asStringArray(attr(a, "gen_ai.response.finish_reasons"));
619
- const finishReason = finishReasons?.[0];
839
+ const finishReason = finishReasons?.[0] ?? asString(attr(a, "ai.response.finishReason"));
840
+ const firstChunkMs = firstNumber(a, "ai.response.msToFirstChunk", "ai.stream.msToFirstChunk");
620
841
  const error = span.status.code === 2 ? span.status.message ?? "error" : void 0;
621
842
  return {
622
- // Plumbing (probe_* namespace lands on canonical turns columns per PROBE.md §2).
623
- probe_tokens_input: asNumber(attr(a, "gen_ai.usage.input_tokens")),
624
- probe_tokens_output: asNumber(attr(a, "gen_ai.usage.output_tokens")),
843
+ // Operational fields (the probe_* keys land on the turn's own columns).
844
+ // The `ai.*` names are the Vercel AI SDK 6 ones, read last.
845
+ probe_tokens_input: firstNumber(
846
+ a,
847
+ "gen_ai.usage.input_tokens",
848
+ "gen_ai.usage.prompt_tokens",
849
+ "ai.usage.inputTokens",
850
+ "ai.usage.promptTokens"
851
+ ),
852
+ probe_tokens_output: firstNumber(
853
+ a,
854
+ "gen_ai.usage.output_tokens",
855
+ "gen_ai.usage.completion_tokens",
856
+ "ai.usage.outputTokens",
857
+ "ai.usage.completionTokens"
858
+ ),
625
859
  probe_latency_ms: latencyMs,
626
- probe_model: asString(attr(a, "gen_ai.response.model") ?? attr(a, "gen_ai.request.model")),
627
- probe_provider: taggedProvider(a),
860
+ // First-token time: only ai streams put a first-chunk time on the span;
861
+ // the OpenAI, Anthropic and LangChain instrumentations do not.
862
+ ...firstChunkMs === void 0 ? {} : { probe_first_token_ms: Math.max(0, Math.round(firstChunkMs)) },
863
+ probe_model: firstString(
864
+ a,
865
+ "gen_ai.response.model",
866
+ "ai.response.model",
867
+ "gen_ai.request.model",
868
+ "ai.model.id"
869
+ ),
870
+ // The model as requested; the response names a dated snapshot.
871
+ probe_request_model: firstString(a, "gen_ai.request.model", "ai.model.id"),
872
+ probe_cost_usd: reportedCost(a),
873
+ probe_provider: taggedProvider(a) ?? asString(attr(a, "ai.model.provider")),
628
874
  probe_tool_calls: toolCallsCount,
629
875
  probe_tool_names: toolCallNames,
630
876
  probe_error: error,
631
877
  probe_finish_reason: finishReason,
632
878
  // Response text so the SDK edge signature-phrase matcher has something to
633
- // match against; the server-side redactor scrubs PII on the Tier 1 →
634
- // Tier 2 boundary.
879
+ // match against; personal data is scrubbed server-side before storage.
635
880
  response: responseText ? { text: responseText } : void 0,
636
- // Anthropic cache tokens (per research report), promoted so the customer
637
- // can see cache-hit-rate in the dashboard without re-parsing raw messages.
638
- probe_cache_read_input_tokens: asNumber(attr(a, "gen_ai.usage.cache_read_input_tokens")),
639
- probe_cache_creation_input_tokens: asNumber(
640
- attr(a, "gen_ai.usage.cache_creation_input_tokens")
881
+ // Cache tokens. Current names are dotted (`cache_read.input_tokens`);
882
+ // the underscore names are the earlier Traceloop ones, kept as fallback.
883
+ probe_cache_read_input_tokens: firstNumber(
884
+ a,
885
+ "gen_ai.usage.cache_read.input_tokens",
886
+ "gen_ai.usage.cache_read_input_tokens",
887
+ "ai.usage.inputTokenDetails.cacheReadTokens",
888
+ "ai.usage.cachedInputTokens"
889
+ ),
890
+ probe_cache_creation_input_tokens: firstNumber(
891
+ a,
892
+ "gen_ai.usage.cache_creation.input_tokens",
893
+ "gen_ai.usage.cache_creation_input_tokens",
894
+ "ai.usage.inputTokenDetails.cacheWriteTokens"
641
895
  ),
896
+ probe_cache_tokens_in_input: cacheTokensInInput(span),
642
897
  // Debug metadata (kept in payload, not projected to canonical columns).
643
898
  _otel: {
644
899
  spanName: span.name,
645
900
  traceId: span.spanContext().traceId,
646
901
  spanId: span.spanContext().spanId,
647
- operationName: asString(attr(a, "gen_ai.operation.name")),
902
+ operationName: firstString(a, "gen_ai.operation.name", "ai.operationId"),
648
903
  traceloopKind: asString(attr(a, "traceloop.span.kind"))
649
904
  }
650
905
  };
@@ -767,6 +1022,38 @@ var ProbeSpanProcessor = class {
767
1022
  state;
768
1023
  captureFn;
769
1024
  seenSpans = /* @__PURE__ */ new Set();
1025
+ /**
1026
+ * Tool names from execute_tool spans, keyed by "traceId:parentSpanId".
1027
+ * A child span ends before its parent, so when the model-call span that
1028
+ * owns these tools ends, its tool names are already here.
1029
+ */
1030
+ toolChildren = /* @__PURE__ */ new Map();
1031
+ /** Remember an execute_tool span's tool name under its parent span. */
1032
+ noteToolSpan(span, a) {
1033
+ const name = toolNameOfSpan(span.name, a);
1034
+ if (!name) return;
1035
+ const parent = span;
1036
+ const parentSpanId = parent.parentSpanContext?.spanId ?? parent.parentSpanId;
1037
+ if (!parentSpanId) return;
1038
+ const key = `${span.spanContext().traceId}:${parentSpanId}`;
1039
+ const names = this.toolChildren.get(key);
1040
+ if (names) {
1041
+ names.push(name);
1042
+ return;
1043
+ }
1044
+ if (this.toolChildren.size >= MAX_TOOL_PARENTS) {
1045
+ this.toolChildren.delete(this.toolChildren.keys().next().value);
1046
+ }
1047
+ this.toolChildren.set(key, [name]);
1048
+ }
1049
+ takeToolChildren(span) {
1050
+ const { traceId, spanId } = span.spanContext();
1051
+ const key = `${traceId}:${spanId}`;
1052
+ const names = this.toolChildren.get(key);
1053
+ if (!names) return [];
1054
+ this.toolChildren.delete(key);
1055
+ return names;
1056
+ }
770
1057
  /**
771
1058
  * Re-point the processor at a new Probe state (or null after shutdown).
772
1059
  * A registered span processor cannot be removed from a provider, so
@@ -775,11 +1062,25 @@ var ProbeSpanProcessor = class {
775
1062
  * stamping the old deployment slug (production-safety audit R1).
776
1063
  */
777
1064
  rebind(state2, captureFn) {
778
- if (this.state !== state2) this.seenSpans.clear();
1065
+ if (this.state !== state2) {
1066
+ this.seenSpans.clear();
1067
+ this.toolChildren.clear();
1068
+ }
779
1069
  this.state = state2;
780
1070
  if (captureFn) this.captureFn = captureFn;
781
1071
  }
782
- onStart(_span, _parentContext) {
1072
+ /**
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.
1077
+ */
1078
+ insideHandledCall = /* @__PURE__ */ new WeakSet();
1079
+ onStart(span, parentContext) {
1080
+ try {
1081
+ if (isInsideHandledCall(parentContext)) this.insideHandledCall.add(span);
1082
+ } catch {
1083
+ }
783
1084
  }
784
1085
  onEnd(span) {
785
1086
  try {
@@ -787,54 +1088,96 @@ var ProbeSpanProcessor = class {
787
1088
  const state2 = this.state;
788
1089
  const a = span.attributes;
789
1090
  if (isVercelAgentRollup(span.name, a)) return;
790
- if (!isLLMCall(a)) return;
791
- const sessionId = getCurrentSessionId();
792
- if (!sessionId) {
793
- if (state2.config.debug) {
794
- console.warn(
795
- `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`
796
- );
797
- }
1091
+ if (asString(a["gen_ai.operation.name"]) === "execute_tool") {
1092
+ this.noteToolSpan(span, a);
798
1093
  return;
799
1094
  }
800
- const { traceId, spanId } = span.spanContext();
801
- const identity = JSON.stringify([state2.config.deployment, sessionId, traceId, spanId]);
802
- if (this.seenSpans.has(identity)) return;
803
- this.seenSpans.add(identity);
804
- if (this.seenSpans.size > MAX_DEDUP_SPANS) {
805
- this.seenSpans.delete(this.seenSpans.values().next().value);
1095
+ if (!isLLMCall(a)) return;
1096
+ if (this.insideHandledCall.has(span)) {
1097
+ this.takeToolChildren(span);
1098
+ return;
806
1099
  }
807
- const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
808
- state2,
809
- sessionId
1100
+ const sessionId = getCurrentSessionId() || firstString(
1101
+ a,
1102
+ "gen_ai.conversation.id",
1103
+ "ai.telemetry.metadata.sightSessionId",
1104
+ "ai.telemetry.metadata.sessionId"
810
1105
  );
811
- const captured = {
812
- deploymentSlug: state2.config.deployment,
813
- sessionExternalId,
814
- turnIndex,
815
- personaSlug: personaSlug ?? void 0,
816
- payload: buildPayload(span)
817
- };
818
- (async () => {
819
- await maybeAutoStampEnvironmentConfig(session, a);
820
- await this.captureFn(captured);
821
- })().catch((err) => {
822
- if (state2.config.debug) {
823
- console.error(
824
- `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
825
- );
1106
+ const responseId = firstString(a, "gen_ai.response.id", "ai.response.id");
1107
+ if (responseId !== void 0) {
1108
+ if (takeAiResponseClaim(responseId)) {
1109
+ this.takeToolChildren(span);
1110
+ return;
826
1111
  }
827
- });
1112
+ if (aiModelCallsOpen()) {
1113
+ void Promise.resolve().then(() => {
1114
+ try {
1115
+ if (this.state !== state2) return;
1116
+ if (takeAiResponseClaim(responseId)) {
1117
+ this.takeToolChildren(span);
1118
+ return;
1119
+ }
1120
+ this.captureSpan(state2, span, a, sessionId);
1121
+ } catch (err) {
1122
+ if (state2.config.debug) {
1123
+ console.error(
1124
+ `[sight] a span could not be read and was skipped (${err instanceof Error ? err.message : err}).`
1125
+ );
1126
+ }
1127
+ }
1128
+ });
1129
+ return;
1130
+ }
1131
+ }
1132
+ this.captureSpan(state2, span, a, sessionId);
828
1133
  } catch (err) {
829
1134
  if (this.state?.config.debug) {
830
1135
  console.error(
831
- `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`
1136
+ `[sight] a span could not be read and was skipped (${err instanceof Error ? err.message : err}).`
832
1137
  );
833
1138
  }
834
1139
  }
835
1140
  }
1141
+ /** The capture itself, once the span is known to be this call's only turn. */
1142
+ captureSpan(state2, span, a, sessionId) {
1143
+ if (!sessionId) {
1144
+ this.takeToolChildren(span);
1145
+ reportNoSessionSkip(`span "${span.name}"`, state2.config.debug);
1146
+ return;
1147
+ }
1148
+ const { traceId, spanId } = span.spanContext();
1149
+ const identity = JSON.stringify([state2.config.deployment, sessionId, traceId, spanId]);
1150
+ if (this.seenSpans.has(identity)) return;
1151
+ this.seenSpans.add(identity);
1152
+ if (this.seenSpans.size > MAX_DEDUP_SPANS) {
1153
+ this.seenSpans.delete(this.seenSpans.values().next().value);
1154
+ }
1155
+ const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
1156
+ state2,
1157
+ sessionId
1158
+ );
1159
+ const captured = {
1160
+ deploymentSlug: state2.config.deployment,
1161
+ sessionExternalId,
1162
+ turnIndex,
1163
+ personaSlug: personaSlug ?? void 0,
1164
+ payload: buildPayload(span, this.takeToolChildren(span))
1165
+ };
1166
+ const hints = { observedUserText: extractUserText(a) };
1167
+ (async () => {
1168
+ await maybeAutoStampEnvironmentConfig(session, a);
1169
+ await this.captureFn(captured, hints);
1170
+ })().catch((err) => {
1171
+ if (state2.config.debug) {
1172
+ console.error(
1173
+ `[sight] a turn read from a span was not captured (${err instanceof Error ? err.message : err}).`
1174
+ );
1175
+ }
1176
+ });
1177
+ }
836
1178
  shutdown() {
837
1179
  this.seenSpans.clear();
1180
+ this.toolChildren.clear();
838
1181
  return Promise.resolve();
839
1182
  }
840
1183
  forceFlush() {
@@ -845,6 +1188,10 @@ var ProbeSpanProcessor = class {
845
1188
  // src/instrumentation/wrap-openai.ts
846
1189
  var bound = null;
847
1190
  var warnedUnbound = false;
1191
+ var wrappedClientSeen = false;
1192
+ function hasWrappedClient() {
1193
+ return wrappedClientSeen;
1194
+ }
848
1195
  function bindWrapOpenAI(state2, captureFn) {
849
1196
  bound = { state: state2, captureFn };
850
1197
  }
@@ -893,8 +1240,33 @@ function systemTextFromParams(params) {
893
1240
  }
894
1241
  return void 0;
895
1242
  }
896
- function providerFor(model) {
897
- return model?.toLowerCase().startsWith("mercury") ? "inception" : "openai";
1243
+ var now = Date.now;
1244
+ function hostOf(baseURL) {
1245
+ if (!baseURL) return void 0;
1246
+ try {
1247
+ return new URL(baseURL).hostname.toLowerCase();
1248
+ } catch {
1249
+ return void 0;
1250
+ }
1251
+ }
1252
+ function providerFor(model, baseURL) {
1253
+ if (model?.toLowerCase().startsWith("mercury")) return "inception";
1254
+ const host = hostOf(baseURL);
1255
+ if (!host || host === "api.openai.com") return "openai";
1256
+ if (host === "openrouter.ai" || host.endsWith(".openrouter.ai")) return "openrouter";
1257
+ if (host.endsWith(".openai.azure.com")) return "azure";
1258
+ if (host === "inceptionlabs.ai" || host.endsWith(".inceptionlabs.ai")) return "inception";
1259
+ return void 0;
1260
+ }
1261
+ function costFromUsage(usage) {
1262
+ const cost = asNumber2(usage?.["cost"]);
1263
+ if (cost === void 0 || !Number.isFinite(cost) || cost < 0) return void 0;
1264
+ if (usage?.["is_byok"] === true) {
1265
+ const upstream = asNumber2(asRecord(usage["cost_details"])?.["upstream_inference_cost"]);
1266
+ if (upstream === void 0 || !Number.isFinite(upstream) || upstream < 0) return void 0;
1267
+ return cost + upstream;
1268
+ }
1269
+ return cost;
898
1270
  }
899
1271
  function payloadFromChatResponse(r, requestModel) {
900
1272
  const choice = Array.isArray(r["choices"]) ? asRecord(r["choices"][0]) : void 0;
@@ -910,7 +1282,8 @@ function payloadFromChatResponse(r, requestModel) {
910
1282
  tokensOutput: asNumber2(usage?.["completion_tokens"]),
911
1283
  cachedTokens: asNumber2(promptDetails?.["cached_tokens"]),
912
1284
  finishReason: asString2(choice?.["finish_reason"]),
913
- toolNames
1285
+ toolNames,
1286
+ costUsd: costFromUsage(usage)
914
1287
  };
915
1288
  }
916
1289
  function payloadFromResponsesResponse(r, requestModel) {
@@ -946,23 +1319,31 @@ function payloadFromResponsesResponse(r, requestModel) {
946
1319
  tokensOutput: asNumber2(usage?.["output_tokens"]),
947
1320
  cachedTokens: asNumber2(inputDetails?.["cached_tokens"]),
948
1321
  finishReason: asString2(r["status"]),
949
- toolNames: toolNames.length > 0 ? toolNames : void 0
1322
+ toolNames: toolNames.length > 0 ? toolNames : void 0,
1323
+ costUsd: costFromUsage(usage)
950
1324
  };
951
1325
  }
952
- function buildTurnPayload(x, latencyMs, api) {
1326
+ function buildTurnPayload(x, call) {
953
1327
  return {
954
1328
  probe_tokens_input: x.tokensInput,
955
1329
  probe_tokens_output: x.tokensOutput,
956
- probe_latency_ms: latencyMs,
1330
+ probe_latency_ms: call.latencyMs,
1331
+ probe_first_token_ms: call.firstTokenMs,
1332
+ probe_cost_usd: x.costUsd,
957
1333
  probe_model: x.model,
958
- probe_provider: providerFor(x.model),
1334
+ // The model as requested. The response names a dated snapshot; the
1335
+ // server prices a turn by whichever of the two the catalogue lists.
1336
+ probe_request_model: call.requestModel,
1337
+ probe_provider: providerFor(x.model ?? call.requestModel, call.baseURL),
959
1338
  probe_tool_calls: x.toolNames?.length,
960
1339
  probe_tool_names: x.toolNames,
961
1340
  probe_error: void 0,
962
1341
  probe_finish_reason: x.finishReason,
963
1342
  response: x.text ? { text: x.text } : void 0,
964
1343
  probe_cache_read_input_tokens: x.cachedTokens,
965
- _wrap: { api, adapter: "wrapOpenAI" }
1344
+ // OpenAI usage counts cached tokens inside the input count.
1345
+ probe_cache_tokens_in_input: x.cachedTokens !== void 0 ? true : void 0,
1346
+ _wrap: { api: call.api, adapter: "wrapOpenAI" }
966
1347
  };
967
1348
  }
968
1349
  function emit(params, payload) {
@@ -970,7 +1351,7 @@ function emit(params, payload) {
970
1351
  if (!warnedUnbound) {
971
1352
  warnedUnbound = true;
972
1353
  console.warn(
973
- "[sight] wrapOpenAI: call observed before Probe.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."
974
1355
  );
975
1356
  }
976
1357
  return;
@@ -978,11 +1359,7 @@ function emit(params, payload) {
978
1359
  const { state: state2, captureFn } = bound;
979
1360
  const sessionId = getCurrentSessionId();
980
1361
  if (!sessionId) {
981
- if (state2.config.debug) {
982
- console.warn(
983
- "[sight] wrapOpenAI: call with no session context; skipped (wrap calls in Probe.withSession())."
984
- );
985
- }
1362
+ reportNoSessionSkip("wrapOpenAI", state2.config.debug);
986
1363
  return;
987
1364
  }
988
1365
  const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
@@ -1001,7 +1378,7 @@ function emit(params, payload) {
1001
1378
  await captureFn(captured);
1002
1379
  })().catch((err) => {
1003
1380
  if (state2.config.debug) {
1004
- 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}).`);
1005
1382
  }
1006
1383
  });
1007
1384
  }
@@ -1047,81 +1424,144 @@ function teeStream(stream, onChunk, onDone) {
1047
1424
  }
1048
1425
  });
1049
1426
  }
1427
+ function nonEmpty(v) {
1428
+ return typeof v === "string" && v.length > 0;
1429
+ }
1050
1430
  function chatStreamAccumulator(requestModel) {
1051
1431
  const texts = [];
1432
+ const toolNameParts = /* @__PURE__ */ new Map();
1052
1433
  let model = requestModel;
1053
1434
  let finishReason;
1054
1435
  let tokensInput;
1055
1436
  let tokensOutput;
1056
1437
  let cachedTokens;
1438
+ let costUsd;
1057
1439
  return {
1058
1440
  onChunk(chunk) {
1059
1441
  const c = asRecord(chunk);
1060
- if (!c) return;
1442
+ if (!c) return false;
1061
1443
  model = asString2(c["model"]) ?? model;
1062
1444
  const choice = Array.isArray(c["choices"]) ? asRecord(c["choices"][0]) : void 0;
1063
1445
  const delta = asRecord(choice?.["delta"]);
1446
+ let content = false;
1064
1447
  const t = asString2(delta?.["content"]);
1065
- if (t) texts.push(t);
1448
+ if (t) {
1449
+ texts.push(t);
1450
+ content = true;
1451
+ }
1452
+ if (nonEmpty(delta?.["refusal"])) content = true;
1453
+ const toolCalls = delta?.["tool_calls"];
1454
+ if (Array.isArray(toolCalls) && toolCalls.length > 0) {
1455
+ content = true;
1456
+ toolCalls.forEach((raw, position) => {
1457
+ const call = asRecord(raw);
1458
+ const name = asString2(asRecord(call?.["function"])?.["name"]);
1459
+ if (!name) return;
1460
+ const index = asNumber2(call?.["index"]) ?? position;
1461
+ toolNameParts.set(index, (toolNameParts.get(index) ?? "") + name);
1462
+ });
1463
+ }
1066
1464
  finishReason = asString2(choice?.["finish_reason"]) ?? finishReason;
1067
1465
  const usage = asRecord(c["usage"]);
1068
1466
  if (usage) {
1069
1467
  tokensInput = asNumber2(usage["prompt_tokens"]) ?? tokensInput;
1070
1468
  tokensOutput = asNumber2(usage["completion_tokens"]) ?? tokensOutput;
1071
1469
  cachedTokens = asNumber2(asRecord(usage["prompt_tokens_details"])?.["cached_tokens"]) ?? cachedTokens;
1470
+ costUsd = costFromUsage(usage) ?? costUsd;
1072
1471
  }
1472
+ return content;
1073
1473
  },
1074
- result: () => ({
1075
- model,
1076
- text: texts.length > 0 ? texts.join("") : void 0,
1077
- tokensInput,
1078
- tokensOutput,
1079
- cachedTokens,
1080
- finishReason,
1081
- toolNames: void 0
1082
- })
1474
+ result: () => {
1475
+ const toolNames = [...toolNameParts.entries()].sort((x, y) => x[0] - y[0]).map((e) => e[1]);
1476
+ return {
1477
+ model,
1478
+ text: texts.length > 0 ? texts.join("") : void 0,
1479
+ tokensInput,
1480
+ tokensOutput,
1481
+ cachedTokens,
1482
+ finishReason,
1483
+ toolNames: toolNames.length > 0 ? toolNames : void 0,
1484
+ costUsd
1485
+ };
1486
+ }
1083
1487
  };
1084
1488
  }
1489
+ var RESPONSES_OUTPUT_DELTAS = /* @__PURE__ */ new Set([
1490
+ "response.output_text.delta",
1491
+ "response.refusal.delta",
1492
+ "response.function_call_arguments.delta"
1493
+ ]);
1085
1494
  function responsesStreamAccumulator(requestModel) {
1086
1495
  const texts = [];
1496
+ const toolNameByIndex = /* @__PURE__ */ new Map();
1087
1497
  let final = null;
1088
1498
  return {
1089
1499
  onChunk(chunk) {
1090
1500
  const c = asRecord(chunk);
1091
- if (!c) return;
1092
- if (c["type"] === "response.output_text.delta") {
1501
+ if (!c) return false;
1502
+ const type = asString2(c["type"]);
1503
+ let content = false;
1504
+ if (type === "response.output_text.delta") {
1093
1505
  const t = asString2(c["delta"]);
1094
1506
  if (t) texts.push(t);
1095
1507
  }
1096
- if (c["type"] === "response.completed") {
1508
+ if (type !== void 0 && RESPONSES_OUTPUT_DELTAS.has(type) && nonEmpty(c["delta"])) {
1509
+ content = true;
1510
+ }
1511
+ if (type === "response.output_item.added" || type === "response.output_item.done") {
1512
+ const item = asRecord(c["item"]);
1513
+ if (item?.["type"] === "function_call") {
1514
+ content = true;
1515
+ const name = asString2(item["name"]);
1516
+ if (name) toolNameByIndex.set(asNumber2(c["output_index"]) ?? toolNameByIndex.size, name);
1517
+ }
1518
+ }
1519
+ if (type === "response.completed") {
1097
1520
  const response = asRecord(c["response"]);
1098
1521
  if (response) final = payloadFromResponsesResponse(response, requestModel);
1099
1522
  }
1523
+ return content;
1100
1524
  },
1101
1525
  result: () => {
1526
+ const streamedNames = [...toolNameByIndex.entries()].sort((x, y) => x[0] - y[0]).map((e) => e[1]);
1527
+ const streamedText = texts.length > 0 ? texts.join("") : void 0;
1102
1528
  if (final) {
1103
- return { ...final, text: final.text ?? (texts.length > 0 ? texts.join("") : void 0) };
1529
+ return {
1530
+ ...final,
1531
+ text: final.text ?? streamedText,
1532
+ toolNames: final.toolNames ?? (streamedNames.length > 0 ? streamedNames : void 0)
1533
+ };
1104
1534
  }
1105
1535
  return {
1106
1536
  model: requestModel,
1107
- text: texts.length > 0 ? texts.join("") : void 0,
1537
+ text: streamedText,
1108
1538
  tokensInput: void 0,
1109
1539
  tokensOutput: void 0,
1110
1540
  cachedTokens: void 0,
1111
1541
  finishReason: void 0,
1112
- toolNames: void 0
1542
+ toolNames: streamedNames.length > 0 ? streamedNames : void 0,
1543
+ costUsd: void 0
1113
1544
  };
1114
1545
  }
1115
1546
  };
1116
1547
  }
1117
- function wrapCreate(target, api, makeAccumulator, extractResponse) {
1548
+ function wrapCreate(client, target, api, makeAccumulator, extractResponse) {
1118
1549
  const original = target["create"];
1119
1550
  if (typeof original !== "function") return;
1120
1551
  target["create"] = function(...args) {
1552
+ if (isInsideHandledCall()) return original.apply(this, args);
1121
1553
  const params = asRecord(args[0]);
1122
1554
  const requestModel = asString2(params?.["model"]);
1123
- const startedAt = Date.now();
1124
- const result = original.apply(this, args);
1555
+ const startedAt = now();
1556
+ const baseURL = asString2(client["baseURL"]);
1557
+ const facts = (firstTokenMs) => ({
1558
+ api,
1559
+ latencyMs: now() - startedAt,
1560
+ firstTokenMs,
1561
+ requestModel,
1562
+ baseURL
1563
+ });
1564
+ const result = runInsideHandledCall(() => original.apply(this, args));
1125
1565
  if (!result || typeof result.then !== "function") return result;
1126
1566
  return result.then(
1127
1567
  (resolved) => {
@@ -1129,13 +1569,23 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1129
1569
  const isStream = resolved !== null && typeof resolved === "object" && Symbol.asyncIterator in resolved;
1130
1570
  if (isStream) {
1131
1571
  const acc = makeAccumulator(requestModel);
1132
- return teeStream(resolved, acc.onChunk, () => {
1133
- emit(params, buildTurnPayload(acc.result(), Date.now() - startedAt, api));
1134
- });
1572
+ let firstTokenMs;
1573
+ return teeStream(
1574
+ resolved,
1575
+ (chunk) => {
1576
+ const arrivedAt = now();
1577
+ if (acc.onChunk(chunk) && firstTokenMs === void 0) {
1578
+ firstTokenMs = Math.max(0, Math.round(arrivedAt - startedAt));
1579
+ }
1580
+ },
1581
+ () => {
1582
+ emit(params, buildTurnPayload(acc.result(), facts(firstTokenMs)));
1583
+ }
1584
+ );
1135
1585
  }
1136
1586
  const r = asRecord(resolved);
1137
1587
  if (r) {
1138
- emit(params, buildTurnPayload(extractResponse(r, requestModel), Date.now() - startedAt, api));
1588
+ emit(params, buildTurnPayload(extractResponse(r, requestModel), facts()));
1139
1589
  }
1140
1590
  return resolved;
1141
1591
  } catch {
@@ -1151,9 +1601,10 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1151
1601
  tokensOutput: void 0,
1152
1602
  cachedTokens: void 0,
1153
1603
  finishReason: void 0,
1154
- toolNames: void 0
1604
+ toolNames: void 0,
1605
+ costUsd: void 0
1155
1606
  };
1156
- const payload = buildTurnPayload(x, Date.now() - startedAt, api);
1607
+ const payload = buildTurnPayload(x, facts());
1157
1608
  payload.probe_error = err instanceof Error ? err.message : String(err);
1158
1609
  emit(params, payload);
1159
1610
  } catch {
@@ -1164,19 +1615,465 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1164
1615
  };
1165
1616
  }
1166
1617
  function wrapOpenAI(client) {
1618
+ wrappedClientSeen = true;
1167
1619
  const c = client;
1168
1620
  if (c[WRAPPED]) return client;
1169
1621
  c[WRAPPED] = true;
1170
1622
  const completions = asRecord(asRecord(c["chat"])?.["completions"]);
1171
1623
  if (completions) {
1172
- wrapCreate(completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
1624
+ wrapCreate(c, completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
1173
1625
  }
1174
1626
  const responses = asRecord(c["responses"]);
1175
1627
  if (responses) {
1176
- wrapCreate(responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
1628
+ wrapCreate(c, responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
1177
1629
  }
1178
1630
  return client;
1179
1631
  }
1632
+ var AI_SESSION_KEYS = ["sightSessionId", "sessionId"];
1633
+ var bound2 = null;
1634
+ var everBound = false;
1635
+ var warnedUnbound2 = false;
1636
+ function bindVercelAI(state2, captureFn) {
1637
+ bound2 = { state: state2, captureFn };
1638
+ everBound = true;
1639
+ }
1640
+ function unbindVercelAI() {
1641
+ bound2 = null;
1642
+ for (const call of calls.values()) closeModelCall(call);
1643
+ calls.clear();
1644
+ }
1645
+ function rec(v) {
1646
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : void 0;
1647
+ }
1648
+ function str(v) {
1649
+ return typeof v === "string" && v.length > 0 ? v : void 0;
1650
+ }
1651
+ function num(v) {
1652
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
1653
+ }
1654
+ function ms(v) {
1655
+ const n = num(v);
1656
+ return n === void 0 ? void 0 : Math.max(0, Math.round(n));
1657
+ }
1658
+ function textOfContent(content, sep) {
1659
+ if (typeof content === "string") return content.length > 0 ? content : void 0;
1660
+ if (!Array.isArray(content)) return void 0;
1661
+ const texts = [];
1662
+ for (const part of content) {
1663
+ const p = rec(part);
1664
+ if (p?.["type"] === "text" && typeof p["text"] === "string" && p["text"].length > 0) {
1665
+ texts.push(p["text"]);
1666
+ }
1667
+ }
1668
+ return texts.length > 0 ? texts.join(sep) : void 0;
1669
+ }
1670
+ function userTextOf(messages) {
1671
+ if (!Array.isArray(messages)) return void 0;
1672
+ for (let i = messages.length - 1; i >= 0; i--) {
1673
+ const m = rec(messages[i]);
1674
+ if (!m) return void 0;
1675
+ if (m["role"] === "system") continue;
1676
+ if (m["role"] !== "user") return void 0;
1677
+ return textOfContent(m["content"], "\n");
1678
+ }
1679
+ return void 0;
1680
+ }
1681
+ function systemTextOf(instructions, messages) {
1682
+ if (typeof instructions === "string") return str(instructions);
1683
+ const list = Array.isArray(instructions) ? instructions : instructions ? [instructions] : [];
1684
+ const texts = [];
1685
+ for (const item of list) {
1686
+ const t = textOfContent(rec(item)?.["content"], "\n");
1687
+ if (t) texts.push(t);
1688
+ }
1689
+ if (texts.length > 0) return texts.join("\n");
1690
+ if (Array.isArray(messages)) {
1691
+ for (const raw of messages) {
1692
+ const m = rec(raw);
1693
+ if (m?.["role"] === "system") {
1694
+ const t = textOfContent(m["content"], "\n");
1695
+ if (t) return t;
1696
+ }
1697
+ }
1698
+ }
1699
+ return void 0;
1700
+ }
1701
+ function sessionFromContext(runtimeContext) {
1702
+ const ctx = rec(runtimeContext);
1703
+ if (!ctx) return void 0;
1704
+ for (const key of AI_SESSION_KEYS) {
1705
+ const v = str(ctx[key]);
1706
+ if (v) return v;
1707
+ }
1708
+ return void 0;
1709
+ }
1710
+ function errorMessage(err) {
1711
+ if (err instanceof Error) return err.message || err.name;
1712
+ return typeof err === "string" && err.length > 0 ? err : "error";
1713
+ }
1714
+ var MAX_CALLS = 1e3;
1715
+ var calls = /* @__PURE__ */ new Map();
1716
+ function stateFor(callId) {
1717
+ let call = calls.get(callId);
1718
+ if (!call) {
1719
+ call = {
1720
+ scopeSession: void 0,
1721
+ contextSession: void 0,
1722
+ operationId: void 0,
1723
+ system: void 0,
1724
+ open: null
1725
+ };
1726
+ if (calls.size >= MAX_CALLS) {
1727
+ const oldest = calls.keys().next().value;
1728
+ closeModelCall(calls.get(oldest));
1729
+ calls.delete(oldest);
1730
+ }
1731
+ calls.set(callId, call);
1732
+ }
1733
+ return call;
1734
+ }
1735
+ function openModelCall(call, modelCall) {
1736
+ if (call.open === null) noteAiModelCallOpened();
1737
+ call.open = modelCall;
1738
+ }
1739
+ function closeModelCall(call) {
1740
+ if (call.open !== null) noteAiModelCallClosed();
1741
+ call.open = null;
1742
+ }
1743
+ function buildPayload2(call, f) {
1744
+ const usage = rec(f.usage);
1745
+ const inputDetails = rec(usage?.["inputTokenDetails"]);
1746
+ const outputDetails = rec(usage?.["outputTokenDetails"]);
1747
+ const toolNames = f.toolNames && f.toolNames.length > 0 ? f.toolNames : void 0;
1748
+ return {
1749
+ probe_tokens_input: num(usage?.["inputTokens"]),
1750
+ probe_tokens_output: num(usage?.["outputTokens"]),
1751
+ probe_latency_ms: f.latencyMs,
1752
+ probe_first_token_ms: f.firstTokenMs,
1753
+ probe_model: f.model,
1754
+ probe_provider: f.provider,
1755
+ probe_tool_calls: toolNames?.length,
1756
+ probe_tool_names: toolNames,
1757
+ probe_error: f.error,
1758
+ probe_finish_reason: f.finishReason,
1759
+ response: f.text ? { text: f.text } : void 0,
1760
+ probe_cache_read_input_tokens: num(inputDetails?.["cacheReadTokens"]),
1761
+ probe_cache_creation_input_tokens: num(inputDetails?.["cacheWriteTokens"]),
1762
+ // Debug metadata (kept in payload, not projected to canonical columns).
1763
+ _ai: {
1764
+ adapter: "ai-telemetry",
1765
+ operationId: call.operationId,
1766
+ callId: f.callId,
1767
+ stepNumber: f.stepNumber,
1768
+ functionId: f.functionId,
1769
+ responseId: f.responseId,
1770
+ rawFinishReason: f.rawFinishReason,
1771
+ reasoningTokens: num(outputDetails?.["reasoningTokens"])
1772
+ }
1773
+ };
1774
+ }
1775
+ function emit2(options, call, request, fields) {
1776
+ if (!bound2) {
1777
+ if (!everBound && !warnedUnbound2) {
1778
+ warnedUnbound2 = true;
1779
+ console.warn(
1780
+ "[sight] ai telemetry: a call ran before Sight.init() and was not captured. Call Sight.init() once at startup."
1781
+ );
1782
+ }
1783
+ return;
1784
+ }
1785
+ const { state: state2, captureFn } = bound2;
1786
+ const sessionId = call.scopeSession ?? (getCurrentSessionId() || options.sessionId || call.contextSession);
1787
+ if (!sessionId) {
1788
+ reportNoSessionSkip(`ai ${call.operationId ?? "model call"}`, state2.config.debug);
1789
+ return;
1790
+ }
1791
+ const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
1792
+ state2,
1793
+ sessionId
1794
+ );
1795
+ const captured = {
1796
+ deploymentSlug: state2.config.deployment,
1797
+ sessionExternalId,
1798
+ turnIndex,
1799
+ personaSlug: personaSlug ?? void 0,
1800
+ payload: buildPayload2(call, fields)
1801
+ };
1802
+ const hints = { observedUserText: userTextOf(request.messages) };
1803
+ const systemText = systemTextOf(request.instructions, request.messages);
1804
+ void (async () => {
1805
+ await autoStampFromSystemText(session, systemText);
1806
+ await captureFn(captured, hints);
1807
+ })().catch((err) => {
1808
+ if (state2.config.debug) {
1809
+ console.error(
1810
+ `[sight] ai telemetry: a turn was not captured (${err instanceof Error ? err.message : err}).`
1811
+ );
1812
+ }
1813
+ });
1814
+ }
1815
+ var BRAND = /* @__PURE__ */ Symbol.for("sight.aiTelemetry");
1816
+ function isSightIntegration(v) {
1817
+ return v !== null && typeof v === "object" && v[BRAND] === true;
1818
+ }
1819
+ function guarded(fn) {
1820
+ return (event) => {
1821
+ try {
1822
+ const e = rec(event);
1823
+ if (e) fn(e);
1824
+ } catch (err) {
1825
+ if (bound2?.state.config.debug) {
1826
+ console.error(
1827
+ `[sight] ai telemetry: an event could not be read and was skipped (${err instanceof Error ? err.message : err}).`
1828
+ );
1829
+ }
1830
+ }
1831
+ };
1832
+ }
1833
+ function createIntegration(options) {
1834
+ const failed = (callId, error, functionId) => {
1835
+ if (!callId) return;
1836
+ const call = calls.get(callId);
1837
+ if (!call) return;
1838
+ const open = call.open;
1839
+ closeModelCall(call);
1840
+ calls.delete(callId);
1841
+ if (!open) return;
1842
+ emit2(
1843
+ options,
1844
+ call,
1845
+ { instructions: open.instructions, messages: open.messages },
1846
+ {
1847
+ callId,
1848
+ model: open.modelId,
1849
+ provider: open.provider,
1850
+ latencyMs: Math.max(0, Date.now() - open.startedAt),
1851
+ error,
1852
+ functionId: str(functionId)
1853
+ }
1854
+ );
1855
+ };
1856
+ const begin = (e, instructions, messages) => {
1857
+ const callId = str(e["callId"]);
1858
+ if (!callId) return;
1859
+ const call = stateFor(callId);
1860
+ call.scopeSession ??= getCurrentSessionId() || void 0;
1861
+ const record = e["recordInputs"] !== false;
1862
+ openModelCall(call, {
1863
+ startedAt: Date.now(),
1864
+ instructions: record ? instructions : void 0,
1865
+ messages: record ? messages : void 0,
1866
+ provider: str(e["provider"]),
1867
+ modelId: str(e["modelId"])
1868
+ });
1869
+ };
1870
+ const integration = {
1871
+ name: "sight",
1872
+ onStart: guarded((e) => {
1873
+ const callId = str(e["callId"]);
1874
+ if (!callId) return;
1875
+ const call = stateFor(callId);
1876
+ call.scopeSession = getCurrentSessionId() || void 0;
1877
+ call.contextSession = sessionFromContext(e["runtimeContext"]);
1878
+ call.operationId = str(e["operationId"]);
1879
+ call.system = e["system"] ?? e["instructions"];
1880
+ }),
1881
+ onStepStart: guarded((e) => {
1882
+ const callId = str(e["callId"]);
1883
+ if (!callId) return;
1884
+ const call = stateFor(callId);
1885
+ call.contextSession = sessionFromContext(e["runtimeContext"]) ?? call.contextSession;
1886
+ }),
1887
+ onLanguageModelCallStart: guarded((e) => {
1888
+ begin(e, e["instructions"], e["messages"]);
1889
+ }),
1890
+ onLanguageModelCallEnd: guarded((e) => {
1891
+ const responseId = str(e["responseId"]);
1892
+ if (bound2 && responseId) claimAiResponse(responseId);
1893
+ }),
1894
+ onStepEnd: guarded((e) => {
1895
+ const callId = str(e["callId"]);
1896
+ if (!callId) return;
1897
+ const call = calls.get(callId);
1898
+ if (!call) return;
1899
+ const open = call.open;
1900
+ closeModelCall(call);
1901
+ call.contextSession = sessionFromContext(e["runtimeContext"]) ?? call.contextSession;
1902
+ const model = rec(e["model"]);
1903
+ const response = rec(e["response"]);
1904
+ const performance = rec(e["performance"]);
1905
+ const content = Array.isArray(e["content"]) ? e["content"] : [];
1906
+ const toolNames = [];
1907
+ for (const part of content) {
1908
+ const p = rec(part);
1909
+ if (p?.["type"] === "tool-call") {
1910
+ const name = str(p["toolName"]);
1911
+ if (name) toolNames.push(name);
1912
+ }
1913
+ }
1914
+ const finishReason = str(e["finishReason"]);
1915
+ emit2(
1916
+ options,
1917
+ call,
1918
+ { instructions: open?.instructions, messages: open?.messages },
1919
+ {
1920
+ callId,
1921
+ // Text parts only: never reasoning, tool input or tool output.
1922
+ text: e["recordOutputs"] === false ? void 0 : textOfContent(content, ""),
1923
+ // The id the provider returned; the requested id when it returned none.
1924
+ model: str(response?.["modelId"]) ?? str(model?.["modelId"]) ?? open?.modelId,
1925
+ provider: str(model?.["provider"]) ?? open?.provider,
1926
+ usage: e["usage"],
1927
+ finishReason,
1928
+ rawFinishReason: str(e["rawFinishReason"]),
1929
+ toolNames,
1930
+ latencyMs: ms(performance?.["responseTimeMs"]) ?? (open ? Math.max(0, Date.now() - open.startedAt) : void 0),
1931
+ firstTokenMs: ms(performance?.["timeToFirstOutputMs"]),
1932
+ // A stream that failed part way ends its step with this finish
1933
+ // reason; the events carry no error message for it.
1934
+ error: finishReason === "error" ? 'model call ended with finish reason "error"' : void 0,
1935
+ responseId: str(response?.["id"]),
1936
+ stepNumber: num(e["stepNumber"]),
1937
+ functionId: str(e["functionId"])
1938
+ }
1939
+ );
1940
+ }),
1941
+ onObjectStepStart: guarded((e) => {
1942
+ const callId = str(e["callId"]);
1943
+ begin(e, callId ? calls.get(callId)?.system : void 0, e["promptMessages"]);
1944
+ }),
1945
+ onObjectStepEnd: guarded((e) => {
1946
+ const callId = str(e["callId"]);
1947
+ if (!callId) return;
1948
+ const call = calls.get(callId);
1949
+ if (!call) return;
1950
+ const open = call.open;
1951
+ closeModelCall(call);
1952
+ const response = rec(e["response"]);
1953
+ const responseId = str(response?.["id"]);
1954
+ if (bound2 && responseId) claimAiResponse(responseId);
1955
+ emit2(
1956
+ options,
1957
+ call,
1958
+ { instructions: open?.instructions, messages: open?.messages },
1959
+ {
1960
+ callId,
1961
+ // The reply of an object call is the JSON text the model produced.
1962
+ text: e["recordOutputs"] === false ? void 0 : str(e["objectText"]),
1963
+ model: str(response?.["modelId"]) ?? str(e["modelId"]) ?? open?.modelId,
1964
+ provider: str(e["provider"]) ?? open?.provider,
1965
+ usage: e["usage"],
1966
+ finishReason: str(e["finishReason"]),
1967
+ latencyMs: open ? Math.max(0, Date.now() - open.startedAt) : void 0,
1968
+ firstTokenMs: ms(e["msToFirstChunk"]),
1969
+ responseId,
1970
+ stepNumber: num(e["stepNumber"]),
1971
+ functionId: str(e["functionId"])
1972
+ }
1973
+ );
1974
+ }),
1975
+ onError: guarded((e) => {
1976
+ failed(str(e["callId"]), errorMessage(e["error"]), e["functionId"]);
1977
+ }),
1978
+ onAbort: guarded((e) => {
1979
+ failed(str(e["callId"]), "aborted", e["functionId"]);
1980
+ }),
1981
+ onEnd: guarded((e) => {
1982
+ const callId = str(e["callId"]);
1983
+ if (!callId) return;
1984
+ const call = calls.get(callId);
1985
+ if (!call) return;
1986
+ closeModelCall(call);
1987
+ calls.delete(callId);
1988
+ }),
1989
+ executeLanguageModelCall(callOptions) {
1990
+ if (!bound2) return callOptions.execute();
1991
+ return runInsideHandledCall(() => callOptions.execute());
1992
+ }
1993
+ };
1994
+ Object.defineProperty(integration, BRAND, { value: true });
1995
+ return integration;
1996
+ }
1997
+ var shared = null;
1998
+ function sightTelemetry(options) {
1999
+ if (options && options.sessionId !== void 0) return createIntegration(options);
2000
+ shared ??= createIntegration({});
2001
+ return shared;
2002
+ }
2003
+ function canRequireEsModule() {
2004
+ const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
2005
+ return major >= 24 || major === 23 && minor >= 5 || major === 22 && minor >= 13;
2006
+ }
2007
+ var defaultLoaders = {
2008
+ // `ai` reads its integration list when a call starts, so a registration
2009
+ // that lands a tick after init would miss a call made right after init.
2010
+ // `ai` 7 is ES module only; where require() can load it this registers
2011
+ // before init returns, and anywhere else the asynchronous import is used.
2012
+ // createRequire, never a bare `require`: the bundler replaces a bare one
2013
+ // in the ES module build with a stub that always throws.
2014
+ sync: () => canRequireEsModule() ? module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))("ai") : null,
2015
+ async: () => import('ai')
2016
+ };
2017
+ function globalIntegrations() {
2018
+ const list = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS;
2019
+ return Array.isArray(list) ? list : [];
2020
+ }
2021
+ var registered = false;
2022
+ function register(mod, debug) {
2023
+ if (registered) return;
2024
+ const registerTelemetry = rec(mod)?.["registerTelemetry"];
2025
+ if (typeof registerTelemetry !== "function") {
2026
+ if (debug) {
2027
+ console.log(
2028
+ "[sight] ai below 7 found: nothing to register. Calls made with experimental_telemetry: { isEnabled: true } are captured from their OpenTelemetry spans."
2029
+ );
2030
+ }
2031
+ return;
2032
+ }
2033
+ registered = true;
2034
+ if (globalIntegrations().some(isSightIntegration)) {
2035
+ if (debug) console.log("[sight] ai: the telemetry integration was already registered.");
2036
+ return;
2037
+ }
2038
+ registerTelemetry(sightTelemetry());
2039
+ if (debug) {
2040
+ console.log(
2041
+ "[sight] ai: telemetry integration registered. generateText, streamText, generateObject and streamObject calls are captured, one turn per model call."
2042
+ );
2043
+ }
2044
+ }
2045
+ async function registerVercelAI(state2, captureFn, loaders = defaultLoaders) {
2046
+ if (captureFn) bindVercelAI(state2, captureFn);
2047
+ if (registered) return;
2048
+ const debug = state2.config.debug;
2049
+ let mod = null;
2050
+ try {
2051
+ mod = loaders.sync();
2052
+ } catch {
2053
+ mod = null;
2054
+ }
2055
+ if (mod === null || mod === void 0) {
2056
+ try {
2057
+ mod = await loaders.async();
2058
+ } catch {
2059
+ if (debug) {
2060
+ console.log(
2061
+ "[sight] ai was not found, so nothing was registered. If ai is bundled where the SDK cannot resolve it, call registerTelemetry(sightTelemetry()) yourself."
2062
+ );
2063
+ }
2064
+ return;
2065
+ }
2066
+ }
2067
+ try {
2068
+ register(mod, debug);
2069
+ } catch (err) {
2070
+ if (debug) {
2071
+ console.warn(
2072
+ `[sight] ai: the telemetry integration was not registered (${err instanceof Error ? err.message : err}). Call registerTelemetry(sightTelemetry()) yourself.`
2073
+ );
2074
+ }
2075
+ }
2076
+ }
1180
2077
 
1181
2078
  // src/instrumentation/setup.ts
1182
2079
  var installedProcessor = null;
@@ -1201,13 +2098,14 @@ function setupOtelProvider(state2, captureFn) {
1201
2098
  function detachOtelState() {
1202
2099
  installedProcessor?.rebind(null);
1203
2100
  unbindWrapOpenAI();
2101
+ unbindVercelAI();
1204
2102
  }
1205
2103
 
1206
2104
  // src/instrumentation/openai.ts
1207
- var registered = false;
2105
+ var registered2 = false;
1208
2106
  var instrumentation = null;
1209
2107
  async function registerOpenAI(state2) {
1210
- if (registered) return;
2108
+ if (registered2) return;
1211
2109
  try {
1212
2110
  const mod = await import('@traceloop/instrumentation-openai');
1213
2111
  instrumentation = new mod.OpenAIInstrumentation({
@@ -1215,18 +2113,18 @@ async function registerOpenAI(state2) {
1215
2113
  exceptionLogger: (err) => {
1216
2114
  if (state2.config.debug) {
1217
2115
  console.error(
1218
- `[probe/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`
2116
+ `[sight] OpenAI instrumentation error: ${err instanceof Error ? err.message : err}`
1219
2117
  );
1220
2118
  }
1221
2119
  }
1222
2120
  });
1223
2121
  instrumentation.enable();
1224
- registered = true;
2122
+ registered2 = true;
1225
2123
  void verifyPatchAttached();
1226
2124
  } catch (err) {
1227
2125
  if (state2.config.debug) {
1228
2126
  const msg = err instanceof Error ? err.message : String(err);
1229
- console.warn(`[probe/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()).`);
1230
2128
  }
1231
2129
  }
1232
2130
  }
@@ -1236,94 +2134,90 @@ function isPatchDetached(mod) {
1236
2134
  if (typeof create !== "function") return true;
1237
2135
  return create.__wrapped !== true;
1238
2136
  }
2137
+ function patchWarning(mod, wrappedClientInUse) {
2138
+ if (!isPatchDetached(mod)) return null;
2139
+ if (wrappedClientInUse) return null;
2140
+ const version = mod?.default?.VERSION ?? mod?.VERSION;
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');
2147
+ }
1239
2148
  async function verifyPatchAttached() {
1240
2149
  try {
1241
- const mod = await import('openai');
1242
- if (!isPatchDetached(mod)) return;
1243
- const version = mod?.default?.VERSION ?? mod?.VERSION;
1244
- console.warn(
1245
- `[sight] OpenAI autocapture via module patching did not attach` + (version ? ` (openai v${version})` : "") + `. This happens on openai >=5, under ESM, or when 'openai' loads before init. Wrap your client instead: import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()). Until then, no turns are captured from this client.`
1246
- );
2150
+ const mod = await loadApplicationOpenAI();
2151
+ const line = patchWarning(mod, hasWrappedClient());
2152
+ if (line !== null) console.warn(line);
1247
2153
  } catch {
1248
2154
  }
1249
2155
  }
1250
2156
 
1251
2157
  // src/instrumentation/anthropic.ts
1252
- var registered2 = false;
2158
+ var registered3 = false;
1253
2159
  var instrumentation2 = null;
1254
2160
  async function registerAnthropic(state2) {
1255
- if (registered2) return;
2161
+ if (registered3) return;
1256
2162
  try {
1257
2163
  const mod = await import('@traceloop/instrumentation-anthropic');
1258
2164
  instrumentation2 = new mod.AnthropicInstrumentation({
1259
2165
  exceptionLogger: (err) => {
1260
2166
  if (state2.config.debug) {
1261
2167
  console.error(
1262
- `[probe/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`
2168
+ `[sight] Anthropic instrumentation error: ${err instanceof Error ? err.message : err}`
1263
2169
  );
1264
2170
  }
1265
2171
  }
1266
2172
  });
1267
2173
  instrumentation2.enable();
1268
- registered2 = true;
2174
+ registered3 = true;
1269
2175
  } catch (err) {
1270
2176
  if (state2.config.debug) {
1271
2177
  const msg = err instanceof Error ? err.message : String(err);
1272
2178
  console.warn(
1273
- `[probe/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().`
1274
2180
  );
1275
2181
  }
1276
2182
  }
1277
2183
  }
1278
2184
 
1279
2185
  // src/instrumentation/langchain.ts
1280
- var registered3 = false;
2186
+ var registered4 = false;
1281
2187
  var instrumentation3 = null;
1282
2188
  async function registerLangChain(state2) {
1283
- if (registered3) return;
2189
+ if (registered4) return;
1284
2190
  try {
1285
2191
  const mod = await import('@traceloop/instrumentation-langchain');
1286
2192
  instrumentation3 = new mod.LangChainInstrumentation({
1287
2193
  exceptionLogger: (err) => {
1288
2194
  if (state2.config.debug) {
1289
2195
  console.error(
1290
- `[probe/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`
2196
+ `[sight] LangChain instrumentation error: ${err instanceof Error ? err.message : err}`
1291
2197
  );
1292
2198
  }
1293
2199
  }
1294
2200
  });
1295
2201
  instrumentation3.enable();
1296
- registered3 = true;
2202
+ registered4 = true;
1297
2203
  } catch (err) {
1298
2204
  if (state2.config.debug) {
1299
2205
  const msg = err instanceof Error ? err.message : String(err);
1300
2206
  console.warn(
1301
- `[probe/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().`
1302
2208
  );
1303
2209
  }
1304
2210
  }
1305
2211
  }
1306
2212
 
1307
2213
  // src/instrumentation/langgraph.ts
1308
- var registered4 = false;
1309
- async function registerLangGraph(state2) {
1310
- if (registered4) return;
1311
- registered4 = true;
1312
- if (state2.config.debug) {
1313
- console.log(
1314
- "[probe/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology"
1315
- );
1316
- }
1317
- }
1318
-
1319
- // src/instrumentation/vercel-ai.ts
1320
2214
  var registered5 = false;
1321
- async function registerVercelAI(state2) {
2215
+ async function registerLangGraph(state2) {
1322
2216
  if (registered5) return;
1323
2217
  registered5 = true;
1324
2218
  if (state2.config.debug) {
1325
2219
  console.log(
1326
- "[probe/vercel-ai] active; customer must set experimental_telemetry: { isEnabled: true } per call"
2220
+ "[sight] LangGraph: model calls go through the LangChain instrumentation; no separate setup."
1327
2221
  );
1328
2222
  }
1329
2223
  }
@@ -1335,7 +2229,7 @@ async function registerLiteLLM(state2) {
1335
2229
  registered6 = true;
1336
2230
  if (state2.config.debug) {
1337
2231
  console.log(
1338
- "[probe/litellm] not captured on SDK side; use the Chapter 4 URL-swap proxy for LiteLLM traffic"
2232
+ "[sight] LiteLLM (Python) calls are not captured by this SDK. Record them with Sight.captureTurn() or the HTTP API."
1339
2233
  );
1340
2234
  }
1341
2235
  }
@@ -1347,7 +2241,7 @@ async function registerMercury(state2) {
1347
2241
  registered7 = true;
1348
2242
  if (state2.config.debug) {
1349
2243
  console.log(
1350
- "[probe/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().'
1351
2245
  );
1352
2246
  }
1353
2247
  }
@@ -1361,7 +2255,7 @@ function registerAllInstrumentations(state2, captureFn) {
1361
2255
  registerAnthropic(state2),
1362
2256
  registerLangChain(state2),
1363
2257
  registerLangGraph(state2),
1364
- registerVercelAI(state2),
2258
+ registerVercelAI(state2, captureFn),
1365
2259
  registerLiteLLM(state2),
1366
2260
  registerMercury(state2)
1367
2261
  ];
@@ -1369,7 +2263,7 @@ function registerAllInstrumentations(state2, captureFn) {
1369
2263
  if (!state2.config.debug) return;
1370
2264
  for (const result of results) {
1371
2265
  if (result.status === "rejected") {
1372
- 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.`);
1373
2267
  }
1374
2268
  }
1375
2269
  });
@@ -1532,7 +2426,7 @@ var UserOutcomeSchema = zod.z.object({
1532
2426
  /** Thumbs-up / thumbs-down widget value. */
1533
2427
  thumbs: zod.z.enum(["up", "down"]).optional()
1534
2428
  });
1535
- zod.z.object({
2429
+ var TurnInputSchema = zod.z.object({
1536
2430
  deploymentSlug: zod.z.string().min(1),
1537
2431
  sessionExternalId: zod.z.string().min(1),
1538
2432
  /**
@@ -1551,6 +2445,8 @@ zod.z.object({
1551
2445
  */
1552
2446
  externalUserId: zod.z.string().min(1).optional(),
1553
2447
  turnIndex: zod.z.number().int().nonnegative(),
2448
+ // the SDK's identity for one logical turn; with it, an index collision takes the next index instead of dropping
2449
+ turnId: zod.z.string().uuid().optional(),
1554
2450
  /**
1555
2451
  * Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the
1556
2452
  * worker: when present it becomes turns.started_at; when absent the
@@ -1615,7 +2511,8 @@ zod.z.object({
1615
2511
  * All optional. Powers Chapter 8e′ Card 3 version behavioral diff.
1616
2512
  */
1617
2513
  agentId: zod.z.string().optional(),
1618
- experimentId: zod.z.string().optional(),
2514
+ // Endpoint capture explicitly records no experiment; older SDKs omit it.
2515
+ experimentId: zod.z.string().nullish().transform((value) => value ?? void 0),
1619
2516
  environmentConfigHash: zod.z.string().optional(),
1620
2517
  environmentConfigLabel: zod.z.string().optional(),
1621
2518
  /** Internal Studio runner provenance. Customer SDKs never set this. */
@@ -1638,7 +2535,7 @@ zod.z.object({
1638
2535
  clientContext: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
1639
2536
  payload: zod.z.record(zod.z.string(), zod.z.unknown())
1640
2537
  });
1641
- zod.z.object({
2538
+ var SessionEndSchema2 = zod.z.object({
1642
2539
  deploymentSlug: zod.z.string().min(1),
1643
2540
  sessionExternalId: zod.z.string().min(1),
1644
2541
  /** Why the session ended. */
@@ -1653,6 +2550,13 @@ zod.z.object({
1653
2550
  /** ISO timestamp of session end. */
1654
2551
  endedAt: zod.z.string().optional()
1655
2552
  });
2553
+ var ENGINE_ENDED_REASONS = ["floor", "turn_cap"];
2554
+ SessionEndSchema2.extend({
2555
+ endedReason: zod.z.enum([
2556
+ ...SessionEndSchema2.shape.endedReason.unwrap().options,
2557
+ ...ENGINE_ENDED_REASONS
2558
+ ]).optional()
2559
+ });
1656
2560
  zod.z.object({
1657
2561
  deploymentSlug: zod.z.string().min(1),
1658
2562
  sessionExternalId: zod.z.string().min(1),
@@ -2070,20 +2974,40 @@ function validateOrDrop(schema, input, method) {
2070
2974
  if (!result.success) {
2071
2975
  const issue = result.error?.issues?.[0];
2072
2976
  console.warn(
2073
- `[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.`
2074
2978
  );
2075
2979
  return null;
2076
2980
  }
2077
2981
  return result.data;
2078
2982
  }
2983
+ var SessionRefSchema = zod.z.object({ externalId: zod.z.string().min(1) });
2984
+ var UserInputSubmitSchema = SessionRefSchema.extend({ text: zod.z.string() });
2985
+ var UserThumbsSchema = SessionRefSchema.extend({
2986
+ thumbs: zod.z.enum(["up", "down"])
2987
+ });
2988
+ var UserRatingSchema = SessionRefSchema.extend({
2989
+ rating: zod.z.number().int().min(1).max(5)
2990
+ });
2991
+ function newTurnId() {
2992
+ const c = globalThis.crypto;
2993
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
2994
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
2995
+ const r = Math.floor(Math.random() * 16);
2996
+ return (ch === "x" ? r : r & 3 | 8).toString(16);
2997
+ });
2998
+ }
2079
2999
  var Probe = class {
2080
3000
  /**
2081
- * Initialize the Probe SDK. Call once at process start. Subsequent calls are
2082
- * 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.
2083
3005
  */
2084
3006
  static init(config) {
2085
3007
  if (state !== null) {
2086
- 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
+ );
2087
3011
  return;
2088
3012
  }
2089
3013
  const validated = ProbeConfigSchema.parse(config);
@@ -2110,32 +3034,44 @@ var Probe = class {
2110
3034
  )
2111
3035
  );
2112
3036
  }
2113
- registerAllInstrumentations(state, (turn) => this.captureTurn(turn));
3037
+ registerAllInstrumentations(
3038
+ state,
3039
+ (turn, hints) => this.captureWithHints(turn, hints)
3040
+ );
2114
3041
  }
2115
3042
  /**
2116
- * Run a callback inside a session context. Every LLM call made inside `fn`
2117
- * (through any instrumented library: OpenAI, Anthropic, LangChain, Vercel
2118
- * AI SDK, etc.) is automatically tagged with `sessionId` and captured as
2119
- * a turn on that session.
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).
3047
+ *
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.
2120
3054
  *
2121
- * Under the hood, this uses OTel Baggage propagation; the shared span
2122
- * processor reads the session ID from baggage when each LLM span ends.
3055
+ * The scope is carried across awaits. Returns what `fn` returns.
2123
3056
  */
2124
3057
  static async withSession(sessionId, fn) {
2125
3058
  if (state === null) {
2126
- 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
+ );
2127
3062
  return fn();
2128
3063
  }
2129
3064
  return withSession(sessionId, fn);
2130
3065
  }
2131
3066
  /**
2132
- * Identify the process-level default persona. Overwrites any previously-set
2133
- * default. For per-session persona identification (multi-persona products),
2134
- * 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 }).
2135
3069
  */
2136
3070
  static identifyPersona(persona) {
2137
3071
  if (state === null) {
2138
- 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
+ );
2139
3075
  return;
2140
3076
  }
2141
3077
  state.persona = persona;
@@ -2147,29 +3083,29 @@ var Probe = class {
2147
3083
  }
2148
3084
  }
2149
3085
  /**
2150
- * Start (or update) a session with an active persona.
2151
- *
2152
- * Single-persona deployments can skip this if the init-level default is
2153
- * enough; the SDK will still create a session entry lazily on first turn.
2154
- * Multi-persona products call this at conversation start so every turn in
2155
- * the session inherits the selected 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.
2156
3089
  *
2157
- * 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.
2158
3092
  */
2159
3093
  static startSession(input) {
2160
3094
  if (state === null) {
2161
- 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
+ );
2162
3098
  return;
2163
3099
  }
2164
3100
  const validated = validateOrDrop(SessionStartSchema, input, "startSession");
2165
3101
  if (validated === null) return;
2166
3102
  const existing = state.sessions.get(validated.externalId);
2167
- const now = Date.now();
3103
+ const now2 = Date.now();
2168
3104
  const session = {
2169
3105
  externalId: validated.externalId,
2170
3106
  externalUserId: validated.externalUserId ?? existing?.externalUserId ?? null,
2171
3107
  turnIndex: existing?.turnIndex ?? 0,
2172
- startedAt: existing?.startedAt ?? now,
3108
+ startedAt: existing?.startedAt ?? now2,
2173
3109
  personaSlug: validated.persona ?? existing?.personaSlug ?? state.persona?.slug ?? null,
2174
3110
  metadata: validated.metadata ?? existing?.metadata ?? null,
2175
3111
  openedVia: validated.openedVia ?? existing?.openedVia ?? null,
@@ -2224,44 +3160,39 @@ var Probe = class {
2224
3160
  return entry;
2225
3161
  }
2226
3162
  /**
2227
- * Compute a stable SHA-256 hex hash of prompt/config text for use as
2228
- * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —
2229
- * pass the human-readable version alongside as `environmentConfigLabel`
2230
- * for the diff table axis (a card keyed by a3f9c2… is unreadable).
2231
- *
2232
- * Ships as a helper because inconsistent hashing across restarts breaks
2233
- * The version behavioral diff — every customer would
2234
- * 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`.
2235
3166
  *
2236
- * The same hashing (src/hash.ts) backs the OTel processor's automatic
2237
- * version stamping: when autocapture sees a system message and the
2238
- * deployer set no environmentConfigHash, the session is stamped with
2239
- * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit
2240
- * 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.
2241
3171
  */
2242
3172
  static async hashEnvironmentConfig(input) {
2243
3173
  return hashEnvironmentConfig(input);
2244
3174
  }
2245
3175
  /**
2246
- * End a session and release its in-memory entry. Optional (sessions time out
2247
- * eventually), but recommended for long-running processes with many distinct
2248
- * conversations. If `input.endedReason` is provided the SDK sends an end
2249
- * 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.
2250
3179
  *
2251
- * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`
2252
- * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`
2253
- * and, when it returns a non-null OutcomeResult, lands it as an outcome
2254
- * event (kind = result.outcome, detail carries type/value). This is the
2255
- * ONLY place the SDK invokes the hook — there are no client-side timers,
2256
- * so sessions that are never ended explicitly are swept server-side as
2257
- * `timeout` and receive no hook-resolved outcome; land those via
2258
- * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:
2259
- * 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().
2260
3189
  */
2261
3190
  static async endSession(externalId) {
2262
3191
  if (state === null) return;
3192
+ const validEnd = typeof externalId === "string" ? validateOrDrop(SessionRefSchema, { externalId }, "endSession") : validateOrDrop(SessionEndSchema, externalId, "endSession");
3193
+ if (validEnd === null) return;
2263
3194
  const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
2264
- const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
3195
+ const endedReason = typeof externalId === "string" ? "natural" : externalId.endedReason ?? "natural";
2265
3196
  const declared = typeof externalId === "string" ? void 0 : externalId.outcome;
2266
3197
  if (declared) {
2267
3198
  await this.emitOutcomeEvent({
@@ -2289,7 +3220,7 @@ var Probe = class {
2289
3220
  }
2290
3221
  } catch (err) {
2291
3222
  console.warn(
2292
- "[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:",
2293
3224
  err instanceof Error ? err.message : err
2294
3225
  );
2295
3226
  }
@@ -2301,7 +3232,7 @@ var Probe = class {
2301
3232
  endedReason
2302
3233
  }).catch((err) => {
2303
3234
  console.warn(
2304
- "[sight] sendSessionEnd failed:",
3235
+ "[sight] the session end was not sent. Call Sight.endSession() again, or leave the session to time out. Error:",
2305
3236
  err instanceof Error ? err.message : err
2306
3237
  );
2307
3238
  });
@@ -2315,28 +3246,29 @@ var Probe = class {
2315
3246
  // before startSession or the first LLM call) buffer per externalId and
2316
3247
  // flush into the session when it is created.
2317
3248
  /**
2318
- * User started typing — records the first-keystroke timestamp for
2319
- * probe_user_first_keystroke_ms derivation on captureTurn. Derivable
2320
- * only once a previous agent turn exists; a pre-session typing start
2321
- * 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.
2322
3252
  */
2323
3253
  static userInputStart(externalId) {
2324
3254
  if (state === null) return;
3255
+ if (validateOrDrop(SessionRefSchema, { externalId }, "userInputStart") === null) return;
2325
3256
  const session = state.sessions.get(externalId);
2326
3257
  const target = session ?? this.preSessionEntry(externalId);
2327
- const now = Date.now();
2328
- const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0, now - session.lastAgentTurnAt) : void 0;
3258
+ const now2 = Date.now();
3259
+ const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0, now2 - session.lastAgentTurnAt) : void 0;
2329
3260
  target.pendingUserInput = {
2330
3261
  ...target.pendingUserInput ?? { editCount: 0 },
2331
3262
  firstKeystrokeMs: target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs
2332
3263
  };
2333
3264
  }
2334
3265
  /**
2335
- * User pressed backspace / edited — increments edit_count for
2336
- * probe_user_reply_edit_count.
3266
+ * The person pressed backspace or edited. Increments the edit count,
3267
+ * sent as `userInput.editCount` with the next captured turn.
2337
3268
  */
2338
3269
  static userInputEdit(externalId) {
2339
3270
  if (state === null) return;
3271
+ if (validateOrDrop(SessionRefSchema, { externalId }, "userInputEdit") === null) return;
2340
3272
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2341
3273
  target.pendingUserInput = {
2342
3274
  ...target.pendingUserInput ?? { editCount: 0 },
@@ -2344,36 +3276,41 @@ var Probe = class {
2344
3276
  };
2345
3277
  }
2346
3278
  /**
2347
- * User submitted their reply. Records the text (Presidio-scrubbed
2348
- * server-side before landing on probe_user_reply_text) plus the submit
2349
- * timestamp, which captureTurn uses to derive probe_agent_reflect_ms
2350
- * (submit → next agent turn) and probe_transition_time_ms (previous
2351
- * agent turn → submit).
3279
+ * The person submitted their message. Records the text (scrubbed of
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.
2352
3283
  */
2353
3284
  static userInputSubmit(externalId, text) {
2354
3285
  if (state === null) return;
3286
+ if (validateOrDrop(UserInputSubmitSchema, { externalId, text }, "userInputSubmit") === null)
3287
+ return;
2355
3288
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2356
- const now = Date.now();
3289
+ const now2 = Date.now();
2357
3290
  target.pendingUserInput = {
2358
3291
  ...target.pendingUserInput ?? { editCount: 0 },
2359
3292
  text,
2360
- submittedAt: now
3293
+ submittedAt: now2
2361
3294
  };
2362
- target.lastUserSubmitAt = now;
3295
+ target.lastUserSubmitAt = now2;
2363
3296
  }
2364
- /** Attach a thumbs-up/down to the current turn. */
3297
+ /** Record a thumbs-up or thumbs-down. Sent with the next captured turn. */
2365
3298
  static userThumbs(externalId, thumbs) {
2366
3299
  if (state === null) return;
3300
+ if (validateOrDrop(UserThumbsSchema, { externalId, thumbs }, "userThumbs") === null) return;
2367
3301
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2368
3302
  target.pendingUserOutcome = {
2369
3303
  ...target.pendingUserOutcome ?? {},
2370
3304
  thumbs
2371
3305
  };
2372
3306
  }
2373
- /** Attach an explicit 1-5 rating to the current turn. */
3307
+ /**
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.
3310
+ */
2374
3311
  static userRating(externalId, rating) {
2375
3312
  if (state === null) return;
2376
- if (rating < 1 || rating > 5 || !Number.isInteger(rating)) return;
3313
+ if (validateOrDrop(UserRatingSchema, { externalId, rating }, "userRating") === null) return;
2377
3314
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2378
3315
  target.pendingUserOutcome = {
2379
3316
  ...target.pendingUserOutcome ?? {},
@@ -2381,7 +3318,8 @@ var Probe = class {
2381
3318
  };
2382
3319
  }
2383
3320
  /**
2384
- * 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.
2385
3323
  */
2386
3324
  static startSessionWithContext(input, includes) {
2387
3325
  this.startSession({
@@ -2390,44 +3328,77 @@ var Probe = class {
2390
3328
  });
2391
3329
  }
2392
3330
  /**
2393
- * Register the outcome hook: declares the deployment's outcome type and
2394
- * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked
2395
- * by endSession() — explicit close is the only trigger; the SDK runs no
2396
- * client-side timers. A non-null OutcomeResult lands as an outcome event
2397
- * on the session. Sessions that are never ended explicitly are swept
2398
- * server-side and never resolve through the hook; land those outcomes via
2399
- * emitOutcomeEvent() from the place where the outcome becomes known
2400
- * (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.
2401
3337
  */
2402
3338
  static wireOutcomeHook(hook) {
2403
3339
  if (state === null) {
2404
- 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
+ );
2405
3343
  return;
2406
3344
  }
2407
3345
  state.outcomeHook = hook;
2408
3346
  }
2409
3347
  /**
2410
- * Manually capture a turn. Instrumentation adapters call this internally;
2411
- * exposed for advanced customers who want to bypass autocapture.
3348
+ * Capture a turn yourself, for a model call autocapture does not see.
3349
+ *
3350
+ * - `turnIndex` is the turn's position in the session, starting at 0.
3351
+ * - `deploymentSlug` may be omitted: the `deployment` given to `init` is
3352
+ * used. An explicit value wins.
3353
+ * - Every turn is sent with a `turnId` (a fresh UUID unless you supply
3354
+ * one). A retried send carries the same `turnId`.
3355
+ * - The turn is checked before it is sent. An invalid turn logs one
3356
+ * warning line naming the first invalid field and is dropped; nothing
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.
2412
3361
  *
2413
- * Persona resolution order for the outgoing turn payload:
2414
- * 1. turn.personaSlug (turn-level override)
2415
- * 2. sessions[externalId].personaSlug (from startSession)
2416
- * 3. state.persona.slug (init-level default)
3362
+ * Persona used for the turn, in this order:
3363
+ * 1. turn.personaSlug
3364
+ * 2. the session's persona (from startSession)
3365
+ * 3. the default from init or identifyPersona
2417
3366
  *
2418
- * Signature-phrase matching runs at the SDK edge when the resolved persona
2419
- * has signature phrases registered. The matched slug list is attached to
2420
- * `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`.
2421
3370
  */
2422
3371
  static async captureTurn(turn) {
3372
+ return this.captureWithHints(turn);
3373
+ }
3374
+ /**
3375
+ * The one capture path. Manual captureTurn calls and autocapture both
3376
+ * land here; autocapture also passes what it observed on the request
3377
+ * (`hints`), applied below under the explicit-input-wins rule.
3378
+ */
3379
+ static async captureWithHints(input, hints) {
2423
3380
  if (state === null) {
2424
3381
  return;
2425
3382
  }
2426
- if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
3383
+ if (input === null || typeof input !== "object") {
3384
+ validateOrDrop(TurnInputSchema, input, "captureTurn");
2427
3385
  return;
2428
3386
  }
2429
- if (turn.payload === void 0 || turn.payload === null) {
2430
- turn = { ...turn, payload: {} };
3387
+ const turn = {
3388
+ ...input,
3389
+ deploymentSlug: input.deploymentSlug ?? state.config.deployment,
3390
+ turnId: input.turnId ?? newTurnId(),
3391
+ payload: input.payload === void 0 || input.payload === null ? {} : input.payload
3392
+ };
3393
+ const payloadPropensity = typeof turn.payload === "object" ? turn.payload.propensity : void 0;
3394
+ const checked = validateOrDrop(
3395
+ TurnInputSchema,
3396
+ { ...turn, propensity: turn.propensity ?? payloadPropensity },
3397
+ "captureTurn"
3398
+ );
3399
+ if (checked === null) return;
3400
+ if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
3401
+ return;
2431
3402
  }
2432
3403
  const propensity = turn.propensity ?? turn.payload.propensity;
2433
3404
  let validPropensity = propensity;
@@ -2495,6 +3466,9 @@ var Probe = class {
2495
3466
  if (session.pendingUserOutcome && !userOutcome) {
2496
3467
  userOutcome = session.pendingUserOutcome;
2497
3468
  }
3469
+ if (hints?.observedUserText && !userInput?.text) {
3470
+ userInput = { ...userInput ?? {}, text: hints.observedUserText };
3471
+ }
2498
3472
  if (!interactivity && session.lastUserSubmitAt) {
2499
3473
  interactivity = {
2500
3474
  agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt)
@@ -2522,7 +3496,7 @@ var Probe = class {
2522
3496
  envelopeVersion: SDK_ENVELOPE_VERSION,
2523
3497
  personaSlug: resolvedPersona,
2524
3498
  signaturePhraseMatches: signatureMatches,
2525
- // User identity from the local session entry (Probe.startSession).
3499
+ // User identity from the local session entry (Sight.startSession).
2526
3500
  // The worker persists it on sessions.external_user_id; never the
2527
3501
  // session key. Turn-level override wins for advanced callers.
2528
3502
  externalUserId: turn.externalUserId ?? session.externalUserId ?? void 0,
@@ -2538,7 +3512,7 @@ var Probe = class {
2538
3512
  // columns (e2e audit 2026-07-13).
2539
3513
  propensity: validPropensity,
2540
3514
  // Forward RLDS provenance from the local session entry (populated
2541
- // by Probe.startSession). Worker persists at first-turn session
3515
+ // by Sight.startSession). Worker persists at first-turn session
2542
3516
  // create; nulls stay null.
2543
3517
  agentId: session.agentId ?? void 0,
2544
3518
  experimentId: session.experimentId ?? void 0,
@@ -2547,17 +3521,18 @@ var Probe = class {
2547
3521
  });
2548
3522
  }
2549
3523
  /**
2550
- * Emit a custom outcome event on a session. Populates probe_outcome_events
2551
- * with the customer-supplied `kind` string. Use for
2552
- * customer-defined kinds like "purchase_complete", "handoff_to_human",
2553
- * "character_break_severe". Universal seed kinds (break, escalation,
2554
- * resolution, thumbs_*, rating_*) are also emitted by worker-side
2555
- * detectors automatically — call this only when the customer has a
2556
- * 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.
2557
3530
  */
2558
3531
  static async emitOutcomeEvent(input) {
2559
3532
  if (state === null) {
2560
- 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
+ );
2561
3536
  return;
2562
3537
  }
2563
3538
  const validated = validateOrDrop(
@@ -2569,21 +3544,21 @@ var Probe = class {
2569
3544
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
2570
3545
  }
2571
3546
  /**
2572
- * Capture one environment event against a session. The
2573
- * envelope is generalized: `source_type` and `event` are free strings whose
2574
- * meaning is defined per deployment — the instrument stores the event and
2575
- * attaches it to the session's record by time (the next turn's state
2576
- * corner, plus the causing turn's outcome corner when `causeProvenance`
2577
- * names a turn index), and never interprets it. Fire-and-log, like
2578
- * 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.
2579
3552
  *
2580
- * Alignment defaults to the SDK's own clock claim; deployments with a
2581
- * stricter clock contract (or batches) should call
2582
- * 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.
2583
3556
  */
2584
3557
  static async captureEnvironmentEvent(event, alignment) {
2585
3558
  if (state === null) {
2586
- 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
+ );
2587
3562
  return;
2588
3563
  }
2589
3564
  const validated = validateOrDrop(
@@ -2603,15 +3578,17 @@ var Probe = class {
2603
3578
  });
2604
3579
  }
2605
3580
  /**
2606
- * Capture a batch of environment events with explicit alignment provenance
2607
- * (clock_source, skew_bound_ms, rule_version). Batches are capped at 100
2608
- * events and may span sessions — every event is self-addressed. Same
2609
- * generalized envelope and fire-and-log discipline as the single-event
2610
- * 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.
2611
3586
  */
2612
3587
  static async captureEnvironmentEvents(events, alignment = DEFAULT_ENVIRONMENT_ALIGNMENT) {
2613
3588
  if (state === null) {
2614
- 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
+ );
2615
3592
  return;
2616
3593
  }
2617
3594
  const batch = validateOrDrop(
@@ -2623,22 +3600,23 @@ var Probe = class {
2623
3600
  await state.client.sendEnvironmentEvents(batch);
2624
3601
  }
2625
3602
  /**
2626
- * Capture one sub-turn span against a session: one LLM call, one tool
2627
- * call, one framework step, or a custom unit inside a turn. The span lands
2628
- * on the turn named by `turnIndex`, or — when omitted — on the session's
2629
- * latest turn at/under the span's `startedAt` (most recent turn when
2630
- * `startedAt` is also absent). A span whose turn cannot be resolved is
2631
- * dropped server-side; spans never land unattributed. Fire-and-log, like
2632
- * 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.
2633
3609
  *
2634
- * `attributes` are metadata only (tool names, argument shapes) — never
2635
- * free-text conversation content. Alignment defaults to the SDK's own
2636
- * clock claim; deployments with a stricter clock contract (or batches, or
2637
- * 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.
2638
3614
  */
2639
3615
  static async captureSpan(span, alignment) {
2640
3616
  if (state === null) {
2641
- 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
+ );
2642
3620
  return;
2643
3621
  }
2644
3622
  const validated = validateOrDrop(SpanInputSchema, span, "captureSpan");
@@ -2647,17 +3625,19 @@ var Probe = class {
2647
3625
  await state.client.sendSpans({ spans: [validated], alignment: align });
2648
3626
  }
2649
3627
  /**
2650
- * Capture a batch of spans with explicit alignment provenance
2651
- * (clock_source, skew_bound_ms, rule_version). Batches are capped at 50
2652
- * spans and may span sessions — every span is self-addressed. Parent
2653
- * structure rides the batch: a span's `parentSpanId` names another span's
2654
- * caller-local `spanId` within the same batch and is wired server-side
2655
- * (unresolvable references land null). Same fire-and-log discipline as the
2656
- * 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.
2657
3635
  */
2658
3636
  static async captureSpans(spans, alignment) {
2659
3637
  if (state === null) {
2660
- 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
+ );
2661
3641
  return;
2662
3642
  }
2663
3643
  const batch = validateOrDrop(
@@ -2669,16 +3649,15 @@ var Probe = class {
2669
3649
  await state.client.sendSpans(batch);
2670
3650
  }
2671
3651
  /**
2672
- * Flag a persona break for a session. Wire this to the customer's in-product
2673
- * "that didn't sound like you" UX. Populates the `user_flagged_break`
2674
- * outcome column on the dashboard.
2675
- *
2676
- * If `turnIndex` is omitted, the flag attaches to the session's most
2677
- * 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.
2678
3655
  */
2679
3656
  static async flagPersonaBreak(input) {
2680
3657
  if (state === null) {
2681
- 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
+ );
2682
3661
  return;
2683
3662
  }
2684
3663
  const validated = validateOrDrop(
@@ -2704,11 +3683,11 @@ var Probe = class {
2704
3683
  return "";
2705
3684
  }
2706
3685
  /**
2707
- * Shut down the SDK: discards the singleton state (sessions, pending
2708
- * user-side signals, the pre-session buffer) so init() can be called
2709
- * again. There is no send queue to flush — every capture awaits its own
2710
- * HTTP send — and instrumentation stays registered for the life of the
2711
- * 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.
2712
3691
  */
2713
3692
  static async shutdown() {
2714
3693
  if (state === null) {
@@ -2720,7 +3699,7 @@ var Probe = class {
2720
3699
  await client.drainInFlight();
2721
3700
  }
2722
3701
  // ── Internal helpers ─────────────────────────────────────────────────────
2723
- /** Package-internal: instrumentation adapters read this to build turns. */
3702
+ /** Internal. Not part of the public API. */
2724
3703
  static _getState() {
2725
3704
  return state;
2726
3705
  }
@@ -2752,6 +3731,7 @@ exports.SpanInputV2Schema = SpanInputV2Schema;
2752
3731
  exports.SpanIntervalSchema = SpanIntervalSchema;
2753
3732
  exports.SpanPayloadSchema = SpanPayloadSchema;
2754
3733
  exports.SpansBatchSchema = SpansBatchSchema;
3734
+ exports.sightTelemetry = sightTelemetry;
2755
3735
  exports.wrapOpenAI = wrapOpenAI;
2756
3736
  //# sourceMappingURL=index.cjs.map
2757
3737
  //# sourceMappingURL=index.cjs.map