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