@cultured_computer/sight 0.6.0 → 0.8.0

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";
@@ -35,8 +38,8 @@ var IngestClient = class {
35
38
  shedAnnounced = false;
36
39
  /**
37
40
  * 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;
41
+ * the in-flight cap. At the cap, the send is SHED (thrown into the
42
+ * caller's existing fire-and-log catch) rather than queued;
40
43
  * the first shed per process warns on stderr, the rest debug-log.
41
44
  */
42
45
  async guardedFetch(url, init) {
@@ -57,15 +60,16 @@ var IngestClient = class {
57
60
  }
58
61
  }
59
62
  /**
60
- * Await all in-flight sends (bounded). Called by Probe.shutdown() so
63
+ * Await all in-flight sends (bounded). Called by Sight.shutdown() so
61
64
  * short-lived processes (serverless, CLI scripts) can actually exit after
62
65
  * it — the documented "in-flight sends finish within 15s" only holds while
63
66
  * the process lives. Polling is coarse on purpose: sends report through
64
- * guardedFetch's counter, never awaited individually.
67
+ * guardedFetch's counter and scheduled retries, never awaited individually.
68
+ * Retries beyond the drain budget remain best-effort, not durable delivery.
65
69
  */
66
70
  async drainInFlight(timeoutMs = SEND_TIMEOUT_MS) {
67
71
  const deadline = Date.now() + timeoutMs;
68
- while (this.inFlight > 0 && Date.now() < deadline) {
72
+ while ((this.inFlight > 0 || this.pendingRetries > 0) && Date.now() < deadline) {
69
73
  await new Promise((r) => setTimeout(r, 50));
70
74
  }
71
75
  }
@@ -77,14 +81,15 @@ var IngestClient = class {
77
81
  }
78
82
  /**
79
83
  * Send a turn to the ingest API. Fire-and-log: errors are logged but never
80
- * thrown. The customer's LLM path never blocks on the Probe.
84
+ * thrown. The customer's LLM path never blocks on capture.
81
85
  */
82
86
  async sendTurn(turn) {
83
87
  try {
84
88
  const body = JSON.stringify(turn);
85
- if (body.length > MAX_TURN_BODY_BYTES) {
89
+ const bodyBytes = new TextEncoder().encode(body).byteLength;
90
+ if (bodyBytes > MAX_TURN_BODY_BYTES) {
86
91
  this.log(
87
- `[sight] turn dropped: payload ${body.length} bytes exceeds the ${MAX_TURN_BODY_BYTES}-byte cap (session=${turn.sessionExternalId} turn=${turn.turnIndex}) \u2014 trim the payload you attach`
92
+ `[sight] turn dropped: payload ${bodyBytes} bytes exceeds the ${MAX_TURN_BODY_BYTES}-byte cap (session=${turn.sessionExternalId} turn=${turn.turnIndex}) \u2014 trim the payload you attach`
88
93
  );
89
94
  return;
90
95
  }
@@ -153,7 +158,7 @@ var IngestClient = class {
153
158
  }
154
159
  /**
155
160
  * Send a session-end event to the ingest API. Records why a session ended
156
- * on the sessions.probe_session_ended_reason column. Fire-and-log.
161
+ * on the session. Fire-and-log.
157
162
  */
158
163
  async sendSessionEnd(deploymentSlug, end) {
159
164
  try {
@@ -356,7 +361,7 @@ var OutcomeHookSchema = z.object({
356
361
  type: z.enum(["numeric", "categorical", "boolean", "duration"]),
357
362
  /**
358
363
  * Callback that resolves the outcome for a completed session. Invoked by
359
- * Probe.endSession() with the session's externalId; a non-null result
364
+ * Sight.endSession() with the session's externalId; a non-null result
360
365
  * lands as an outcome event on the session. Not invoked for sessions
361
366
  * swept server-side (no explicit endSession) — use emitOutcomeEvent()
362
367
  * for outcomes that become known out of band.
@@ -364,11 +369,12 @@ var OutcomeHookSchema = z.object({
364
369
  resolve: z.custom()
365
370
  });
366
371
  var ProbeConfigSchema = z.object({
367
- /** Unkey ingest key. Required. */
372
+ /** The project's API key (an ingest key from the dashboard). Required. */
368
373
  apiKey: z.string().min(1),
369
- /** Deployment slug registered in the Probe backend. Required. */
374
+ /** Deployment slug: the configuration this traffic belongs to. Required. */
370
375
  deployment: z.string().min(1),
371
- /** Ingest endpoint. Defaults to the production ingest service. */
376
+ /** Ingest endpoint. Defaults to the production ingest service,
377
+ `https://fieldwork-ingest.fly.dev`. */
372
378
  endpoint: z.string().url().default("https://fieldwork-ingest.fly.dev"),
373
379
  /**
374
380
  * Dashboard base URL used by the one-time first-capture announcement
@@ -417,14 +423,14 @@ var SessionStartSchema = z.object({
417
423
  */
418
424
  openedVia: z.enum(["link", "notification", "resume", "direct", "share"]).optional(),
419
425
  /**
420
- * Environmental context — browser / device / locale / tz (P2). Customer-
421
- * configurable which fields to include. See collectClientContext helper.
426
+ * Environmental context: browser / device / locale / tz. You choose
427
+ * which fields to include. See the collectClientContext helper.
422
428
  */
423
429
  clientContext: z.record(z.string(), z.unknown()).optional(),
424
430
  /**
425
431
  * Optional customer metadata attached to the session. Forwarded with the
426
432
  * first captured turn merged into `clientContext` under the `metadata`
427
- * key, so it lands on sessions.probe_session_client_context.
433
+ * key, so it is stored with the session.
428
434
  */
429
435
  metadata: z.record(z.string(), z.unknown()).optional(),
430
436
  /**
@@ -440,9 +446,16 @@ var SessionStartSchema = z.object({
440
446
  environmentConfigHash: z.string().optional(),
441
447
  environmentConfigLabel: z.string().optional()
442
448
  });
443
- z.object({
449
+ var SessionEndSchema = z.object({
444
450
  externalId: z.string().min(1),
445
- endedReason: z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional(),
451
+ endedReason: z.enum([
452
+ "natural",
453
+ "user_closed",
454
+ "timeout",
455
+ "agent_error",
456
+ "user_flagged",
457
+ "crashed"
458
+ ]).optional(),
446
459
  outcome: z.string().min(1).max(64).optional(),
447
460
  outcomeDetail: z.record(z.string(), z.unknown()).optional()
448
461
  });
@@ -562,23 +575,53 @@ function getCurrentSessionId() {
562
575
  return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;
563
576
  }
564
577
 
565
- // src/instrumentation/otel-processor.ts
566
- var DEDUP_TTL_MS = 5e3;
567
- var dedupCache = /* @__PURE__ */ new Map();
568
- function shouldSkipAsDuplicate(traceId) {
569
- const now = Date.now();
570
- const seenAt = dedupCache.get(traceId);
571
- if (seenAt !== void 0 && now - seenAt < DEDUP_TTL_MS) {
572
- return true;
578
+ // src/instrumentation/no-session.ts
579
+ var warned = false;
580
+ function noSessionWarning(source) {
581
+ 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.`;
582
+ }
583
+ function reportNoSessionSkip(source, debug) {
584
+ if (!warned) {
585
+ warned = true;
586
+ console.warn(noSessionWarning(source));
587
+ return;
573
588
  }
574
- dedupCache.set(traceId, now);
575
- if (dedupCache.size > 1e3) {
576
- for (const [k, v] of dedupCache) {
577
- if (now - v > DEDUP_TTL_MS) dedupCache.delete(k);
578
- }
589
+ if (debug) {
590
+ console.warn(
591
+ `[sight] call not captured (${source}): no session scope; wrap it in Sight.withSession(id, fn).`
592
+ );
579
593
  }
580
- return false;
581
594
  }
595
+ var AI_MODEL_CALL_KEY = createContextKey("sight.ai_model_call");
596
+ function runInsideAiModelCall(fn) {
597
+ return context.with(context.active().setValue(AI_MODEL_CALL_KEY, true), fn);
598
+ }
599
+ function isInsideAiModelCall(ctx = context.active()) {
600
+ return ctx.getValue(AI_MODEL_CALL_KEY) === true;
601
+ }
602
+ var MAX_CLAIMS = 1e3;
603
+ var claims = /* @__PURE__ */ new Set();
604
+ var openCalls = 0;
605
+ function noteAiModelCallOpened() {
606
+ openCalls += 1;
607
+ }
608
+ function noteAiModelCallClosed() {
609
+ if (openCalls > 0) openCalls -= 1;
610
+ }
611
+ function aiModelCallsOpen() {
612
+ return openCalls > 0;
613
+ }
614
+ function claimAiResponse(responseId) {
615
+ claims.add(responseId);
616
+ if (claims.size > MAX_CLAIMS) claims.delete(claims.values().next().value);
617
+ }
618
+ function takeAiResponseClaim(responseId) {
619
+ return claims.delete(responseId);
620
+ }
621
+
622
+ // src/instrumentation/otel-processor.ts
623
+ var MAX_DEDUP_SPANS = 1e4;
624
+ var MAX_TOOL_PARENTS = 1e3;
582
625
  function attr(attrs, key) {
583
626
  return attrs[key];
584
627
  }
@@ -591,64 +634,261 @@ function asNumber(v) {
591
634
  function asStringArray(v) {
592
635
  return Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
593
636
  }
637
+ function firstNumber(attrs, ...keys) {
638
+ for (const key of keys) {
639
+ const n = asNumber(attrs[key]);
640
+ if (n !== void 0) return n;
641
+ }
642
+ return void 0;
643
+ }
644
+ function firstString(attrs, ...keys) {
645
+ for (const key of keys) {
646
+ const s = asString(attrs[key]);
647
+ if (s !== void 0 && s.length > 0) return s;
648
+ }
649
+ return void 0;
650
+ }
651
+ var CAPTURED_OPERATIONS = /* @__PURE__ */ new Set(["chat", "generate_content", "text_completion"]);
652
+ var AI_SDK_MODEL_CALL_OPERATIONS = /* @__PURE__ */ new Set([
653
+ "ai.generateText.doGenerate",
654
+ "ai.streamText.doStream",
655
+ "ai.generateObject.doGenerate",
656
+ "ai.streamObject.doStream"
657
+ ]);
658
+ function isAiSdkModelCall(attrs) {
659
+ const op = asString(attrs["ai.operationId"]);
660
+ return op !== void 0 && AI_SDK_MODEL_CALL_OPERATIONS.has(op);
661
+ }
594
662
  function isLLMCall(attrs) {
595
663
  const op = asString(attrs["gen_ai.operation.name"]);
596
- if (op === "chat" || op === "text_completion" || op === "embeddings") {
597
- return true;
664
+ if (op !== void 0) {
665
+ return CAPTURED_OPERATIONS.has(op);
598
666
  }
599
- const traceloopKind = asString(attrs["traceloop.span.kind"]);
600
- if (traceloopKind === "agent") return true;
601
- return false;
667
+ if (isAiSdkModelCall(attrs)) return true;
668
+ return asString(attrs["traceloop.span.kind"]) === "agent";
602
669
  }
603
670
  function isVercelAgentRollup(spanName, attrs) {
604
671
  return spanName.startsWith("invoke_agent ") && attrs["ai.telemetry.functionId"] !== void 0;
605
672
  }
606
673
  function taggedProvider(attrs) {
607
- const rawProvider = asString(attrs["gen_ai.system"] ?? attrs["gen_ai.provider"]);
674
+ const rawProvider = firstString(attrs, "gen_ai.provider.name", "gen_ai.system", "gen_ai.provider");
608
675
  const model = asString(attrs["gen_ai.request.model"]);
609
676
  if (model?.toLowerCase().startsWith("mercury")) {
610
677
  return "inception";
611
678
  }
612
679
  return rawProvider;
613
680
  }
614
- function buildPayload(span) {
681
+ function isRecord(v) {
682
+ return v !== null && typeof v === "object" && !Array.isArray(v);
683
+ }
684
+ function isMessageLike(v) {
685
+ return isRecord(v) && ("parts" in v || "content" in v || "role" in v);
686
+ }
687
+ function parseStructured(raw) {
688
+ if (typeof raw === "string") {
689
+ const t = raw.trimStart();
690
+ if (!t.startsWith("[") && !t.startsWith("{")) return void 0;
691
+ try {
692
+ return JSON.parse(raw);
693
+ } catch {
694
+ return void 0;
695
+ }
696
+ }
697
+ if (Array.isArray(raw)) {
698
+ return raw.map((el) => {
699
+ if (typeof el !== "string") return el;
700
+ try {
701
+ return JSON.parse(el);
702
+ } catch {
703
+ return el;
704
+ }
705
+ });
706
+ }
707
+ return raw;
708
+ }
709
+ function asMessageList(parsed) {
710
+ const list = Array.isArray(parsed) ? parsed : isMessageLike(parsed) ? [parsed] : void 0;
711
+ if (!list) return void 0;
712
+ const records = list.filter(isRecord);
713
+ return records.some(isMessageLike) ? records : void 0;
714
+ }
715
+ function partsOf(message) {
716
+ const p = message["parts"] ?? message["content"];
717
+ if (typeof p === "string") return [{ type: "text", content: p }];
718
+ return Array.isArray(p) ? p : [];
719
+ }
720
+ function textOfPart(part, types) {
721
+ if (typeof part === "string") return part;
722
+ if (!isRecord(part)) return void 0;
723
+ const type = part["type"];
724
+ if (type !== void 0 && !(typeof type === "string" && types.has(type))) return void 0;
725
+ const text = part["content"] ?? part["text"];
726
+ return typeof text === "string" ? text : void 0;
727
+ }
728
+ var TEXT_PART = /* @__PURE__ */ new Set(["text"]);
729
+ var INPUT_TEXT_PART = /* @__PURE__ */ new Set(["text", "input_text"]);
730
+ var REFUSAL_PART = /* @__PURE__ */ new Set(["refusal"]);
731
+ function joinText(parts, types, sep) {
732
+ const texts = [];
733
+ for (const part of parts) {
734
+ const t = textOfPart(part, types);
735
+ if (t !== void 0 && t.length > 0) texts.push(t);
736
+ }
737
+ return texts.length > 0 ? texts.join(sep) : void 0;
738
+ }
739
+ function parseOutputMessages(raw) {
740
+ const messages = asMessageList(parseStructured(raw));
741
+ if (!messages) return { structured: false, text: void 0, toolNames: [] };
742
+ const reply = messages.find((m) => {
743
+ const role = m["role"];
744
+ return role !== "user" && role !== "system" && role !== "developer" && role !== "tool";
745
+ });
746
+ if (!reply) return { structured: true, text: void 0, toolNames: [] };
747
+ const parts = partsOf(reply);
748
+ const toolNames = [];
749
+ for (const part of parts) {
750
+ if (!isRecord(part)) continue;
751
+ if (part["type"] === "tool_call" || part["type"] === "server_tool_call") {
752
+ const name = part["name"];
753
+ if (typeof name === "string" && name.length > 0) toolNames.push(name);
754
+ }
755
+ }
756
+ return {
757
+ structured: true,
758
+ text: joinText(parts, TEXT_PART, "") ?? joinText(parts, REFUSAL_PART, ""),
759
+ toolNames
760
+ };
761
+ }
762
+ function userTextFromMessages(raw, nested = false) {
763
+ const messages = asMessageList(parseStructured(raw));
764
+ if (!messages) return void 0;
765
+ for (let i = messages.length - 1; i >= 0; i--) {
766
+ const message = messages[i];
767
+ const role = message["role"];
768
+ if (role === "system" || role === "developer") continue;
769
+ if (role !== "user") return void 0;
770
+ const text = joinText(partsOf(message), nested ? INPUT_TEXT_PART : TEXT_PART, "\n");
771
+ if (text === void 0) return void 0;
772
+ return nested ? text : unwrapSerializedRequest(text);
773
+ }
774
+ return void 0;
775
+ }
776
+ function unwrapSerializedRequest(text) {
777
+ const parsed = parseStructured(text);
778
+ if (!Array.isArray(parsed) || !parsed.some(isRecord)) return text;
779
+ if (parsed.some(isMessageLike)) return userTextFromMessages(parsed, true);
780
+ return joinText(parsed, INPUT_TEXT_PART, "\n");
781
+ }
782
+ function extractUserText(attrs) {
783
+ return userTextFromMessages(attrs["gen_ai.input.messages"]) ?? (attrs["gen_ai.input.messages"] === void 0 ? userTextFromMessages(attrs["ai.prompt.messages"]) : void 0);
784
+ }
785
+ function aiSdkToolNames(raw) {
786
+ if (typeof raw !== "string") return [];
787
+ try {
788
+ const parsed = JSON.parse(raw);
789
+ if (!Array.isArray(parsed)) return [];
790
+ const names = [];
791
+ for (const call of parsed) {
792
+ const name = isRecord(call) ? call["toolName"] : void 0;
793
+ if (typeof name === "string" && name.length > 0) names.push(name);
794
+ }
795
+ return names;
796
+ } catch {
797
+ return [];
798
+ }
799
+ }
800
+ function toolNameOfSpan(spanName, attrs) {
801
+ const named = firstString(attrs, "gen_ai.tool.name", "traceloop.entity.name");
802
+ if (named) return named;
803
+ const prefix = "execute_tool ";
804
+ return spanName.startsWith(prefix) && spanName.length > prefix.length ? spanName.slice(prefix.length) : void 0;
805
+ }
806
+ function cacheTokensInInput(span) {
807
+ const scope = span.instrumentationScope?.name;
808
+ if (scope === "@traceloop/instrumentation-openai") return true;
809
+ if (scope === "@traceloop/instrumentation-anthropic") return false;
810
+ return void 0;
811
+ }
812
+ function reportedCost(attrs) {
813
+ const cost = asNumber(attrs["gen_ai.usage.cost"]);
814
+ return cost !== void 0 && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
815
+ }
816
+ function buildPayload(span, childToolNames = []) {
615
817
  const a = span.attributes;
616
818
  const start = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
617
819
  const end = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
618
820
  const latencyMs = Math.max(0, Math.round(end - start));
619
- const responseText = asString(attr(a, "ai.response.text")) ?? asString(attr(a, "gen_ai.output.messages"));
620
- const toolCallNames = asStringArray(attr(a, "gen_ai.response.tool_names"));
621
- const toolCallsCount = asNumber(attr(a, "gen_ai.response.tool_calls_count")) ?? toolCallNames?.length;
821
+ const rawOutput = a["gen_ai.output.messages"];
822
+ const output = parseOutputMessages(rawOutput);
823
+ const responseText = asString(attr(a, "ai.response.text")) ?? (output.structured ? output.text : typeof rawOutput === "string" ? rawOutput : void 0) ?? asString(attr(a, "ai.response.object"));
824
+ const aiToolNames = aiSdkToolNames(attr(a, "ai.response.toolCalls"));
825
+ const toolCallNames = output.toolNames.length > 0 ? output.toolNames : aiToolNames.length > 0 ? aiToolNames : childToolNames.length > 0 ? childToolNames : asStringArray(attr(a, "gen_ai.response.tool_names"));
826
+ const toolCallsCount = toolCallNames?.length ?? asNumber(attr(a, "gen_ai.response.tool_calls_count"));
622
827
  const finishReasons = asStringArray(attr(a, "gen_ai.response.finish_reasons"));
623
- const finishReason = finishReasons?.[0];
828
+ const finishReason = finishReasons?.[0] ?? asString(attr(a, "ai.response.finishReason"));
829
+ const firstChunkMs = firstNumber(a, "ai.response.msToFirstChunk", "ai.stream.msToFirstChunk");
624
830
  const error = span.status.code === 2 ? span.status.message ?? "error" : void 0;
625
831
  return {
626
- // Plumbing (probe_* namespace lands on canonical turns columns per PROBE.md §2).
627
- probe_tokens_input: asNumber(attr(a, "gen_ai.usage.input_tokens")),
628
- probe_tokens_output: asNumber(attr(a, "gen_ai.usage.output_tokens")),
832
+ // Operational fields (the probe_* keys land on the turn's own columns).
833
+ // The `ai.*` names are the Vercel AI SDK 6 ones, read last.
834
+ probe_tokens_input: firstNumber(
835
+ a,
836
+ "gen_ai.usage.input_tokens",
837
+ "gen_ai.usage.prompt_tokens",
838
+ "ai.usage.inputTokens",
839
+ "ai.usage.promptTokens"
840
+ ),
841
+ probe_tokens_output: firstNumber(
842
+ a,
843
+ "gen_ai.usage.output_tokens",
844
+ "gen_ai.usage.completion_tokens",
845
+ "ai.usage.outputTokens",
846
+ "ai.usage.completionTokens"
847
+ ),
629
848
  probe_latency_ms: latencyMs,
630
- probe_model: asString(attr(a, "gen_ai.response.model") ?? attr(a, "gen_ai.request.model")),
631
- probe_provider: taggedProvider(a),
849
+ // First-token time: only ai streams put a first-chunk time on the span;
850
+ // the OpenAI, Anthropic and LangChain instrumentations do not.
851
+ ...firstChunkMs === void 0 ? {} : { probe_first_token_ms: Math.max(0, Math.round(firstChunkMs)) },
852
+ probe_model: firstString(
853
+ a,
854
+ "gen_ai.response.model",
855
+ "ai.response.model",
856
+ "gen_ai.request.model",
857
+ "ai.model.id"
858
+ ),
859
+ // The model as requested; the response names a dated snapshot.
860
+ probe_request_model: firstString(a, "gen_ai.request.model", "ai.model.id"),
861
+ probe_cost_usd: reportedCost(a),
862
+ probe_provider: taggedProvider(a) ?? asString(attr(a, "ai.model.provider")),
632
863
  probe_tool_calls: toolCallsCount,
633
864
  probe_tool_names: toolCallNames,
634
865
  probe_error: error,
635
866
  probe_finish_reason: finishReason,
636
867
  // Response text so the SDK edge signature-phrase matcher has something to
637
- // match against; the server-side redactor scrubs PII on the Tier 1 →
638
- // Tier 2 boundary.
868
+ // match against; personal data is scrubbed server-side before storage.
639
869
  response: responseText ? { text: responseText } : void 0,
640
- // Anthropic cache tokens (per research report), promoted so the customer
641
- // can see cache-hit-rate in the dashboard without re-parsing raw messages.
642
- probe_cache_read_input_tokens: asNumber(attr(a, "gen_ai.usage.cache_read_input_tokens")),
643
- probe_cache_creation_input_tokens: asNumber(
644
- attr(a, "gen_ai.usage.cache_creation_input_tokens")
870
+ // Cache tokens. Current names are dotted (`cache_read.input_tokens`);
871
+ // the underscore names are the earlier Traceloop ones, kept as fallback.
872
+ probe_cache_read_input_tokens: firstNumber(
873
+ a,
874
+ "gen_ai.usage.cache_read.input_tokens",
875
+ "gen_ai.usage.cache_read_input_tokens",
876
+ "ai.usage.inputTokenDetails.cacheReadTokens",
877
+ "ai.usage.cachedInputTokens"
645
878
  ),
879
+ probe_cache_creation_input_tokens: firstNumber(
880
+ a,
881
+ "gen_ai.usage.cache_creation.input_tokens",
882
+ "gen_ai.usage.cache_creation_input_tokens",
883
+ "ai.usage.inputTokenDetails.cacheWriteTokens"
884
+ ),
885
+ probe_cache_tokens_in_input: cacheTokensInInput(span),
646
886
  // Debug metadata (kept in payload, not projected to canonical columns).
647
887
  _otel: {
648
888
  spanName: span.name,
649
889
  traceId: span.spanContext().traceId,
650
890
  spanId: span.spanContext().spanId,
651
- operationName: asString(attr(a, "gen_ai.operation.name")),
891
+ operationName: firstString(a, "gen_ai.operation.name", "ai.operationId"),
652
892
  traceloopKind: asString(attr(a, "traceloop.span.kind"))
653
893
  }
654
894
  };
@@ -770,6 +1010,39 @@ var ProbeSpanProcessor = class {
770
1010
  }
771
1011
  state;
772
1012
  captureFn;
1013
+ seenSpans = /* @__PURE__ */ new Set();
1014
+ /**
1015
+ * Tool names from execute_tool spans, keyed by "traceId:parentSpanId".
1016
+ * A child span ends before its parent, so when the model-call span that
1017
+ * owns these tools ends, its tool names are already here.
1018
+ */
1019
+ toolChildren = /* @__PURE__ */ new Map();
1020
+ /** Remember an execute_tool span's tool name under its parent span. */
1021
+ noteToolSpan(span, a) {
1022
+ const name = toolNameOfSpan(span.name, a);
1023
+ if (!name) return;
1024
+ const parent = span;
1025
+ const parentSpanId = parent.parentSpanContext?.spanId ?? parent.parentSpanId;
1026
+ if (!parentSpanId) return;
1027
+ const key = `${span.spanContext().traceId}:${parentSpanId}`;
1028
+ const names = this.toolChildren.get(key);
1029
+ if (names) {
1030
+ names.push(name);
1031
+ return;
1032
+ }
1033
+ if (this.toolChildren.size >= MAX_TOOL_PARENTS) {
1034
+ this.toolChildren.delete(this.toolChildren.keys().next().value);
1035
+ }
1036
+ this.toolChildren.set(key, [name]);
1037
+ }
1038
+ takeToolChildren(span) {
1039
+ const { traceId, spanId } = span.spanContext();
1040
+ const key = `${traceId}:${spanId}`;
1041
+ const names = this.toolChildren.get(key);
1042
+ if (!names) return [];
1043
+ this.toolChildren.delete(key);
1044
+ return names;
1045
+ }
773
1046
  /**
774
1047
  * Re-point the processor at a new Probe state (or null after shutdown).
775
1048
  * A registered span processor cannot be removed from a provider, so
@@ -778,10 +1051,23 @@ var ProbeSpanProcessor = class {
778
1051
  * stamping the old deployment slug (production-safety audit R1).
779
1052
  */
780
1053
  rebind(state2, captureFn) {
1054
+ if (this.state !== state2) {
1055
+ this.seenSpans.clear();
1056
+ this.toolChildren.clear();
1057
+ }
781
1058
  this.state = state2;
782
1059
  if (captureFn) this.captureFn = captureFn;
783
1060
  }
784
- onStart(_span, _parentContext) {
1061
+ /**
1062
+ * Spans started inside an `ai` model call that the Sight `ai` integration
1063
+ * captures (a provider that calls an instrumented client). Never turns.
1064
+ */
1065
+ insideAiCall = /* @__PURE__ */ new WeakSet();
1066
+ onStart(span, parentContext) {
1067
+ try {
1068
+ if (isInsideAiModelCall(parentContext)) this.insideAiCall.add(span);
1069
+ } catch {
1070
+ }
785
1071
  }
786
1072
  onEnd(span) {
787
1073
  try {
@@ -789,49 +1075,96 @@ var ProbeSpanProcessor = class {
789
1075
  const state2 = this.state;
790
1076
  const a = span.attributes;
791
1077
  if (isVercelAgentRollup(span.name, a)) return;
1078
+ if (asString(a["gen_ai.operation.name"]) === "execute_tool") {
1079
+ this.noteToolSpan(span, a);
1080
+ return;
1081
+ }
792
1082
  if (!isLLMCall(a)) return;
793
- const traceId = span.spanContext().traceId;
794
- if (shouldSkipAsDuplicate(traceId)) return;
795
- const sessionId = getCurrentSessionId();
796
- if (!sessionId) {
797
- if (state2.config.debug) {
798
- console.warn(
799
- `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`
800
- );
801
- }
1083
+ if (this.insideAiCall.has(span)) {
1084
+ this.takeToolChildren(span);
802
1085
  return;
803
1086
  }
804
- const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
805
- state2,
806
- sessionId
1087
+ const sessionId = getCurrentSessionId() || firstString(
1088
+ a,
1089
+ "gen_ai.conversation.id",
1090
+ "ai.telemetry.metadata.sightSessionId",
1091
+ "ai.telemetry.metadata.sessionId"
807
1092
  );
808
- const captured = {
809
- deploymentSlug: state2.config.deployment,
810
- sessionExternalId,
811
- turnIndex,
812
- personaSlug: personaSlug ?? void 0,
813
- payload: buildPayload(span)
814
- };
815
- (async () => {
816
- await maybeAutoStampEnvironmentConfig(session, a);
817
- await this.captureFn(captured);
818
- })().catch((err) => {
819
- if (state2.config.debug) {
820
- console.error(
821
- `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
822
- );
1093
+ const responseId = firstString(a, "gen_ai.response.id", "ai.response.id");
1094
+ if (responseId !== void 0) {
1095
+ if (takeAiResponseClaim(responseId)) {
1096
+ this.takeToolChildren(span);
1097
+ return;
823
1098
  }
824
- });
1099
+ if (aiModelCallsOpen()) {
1100
+ void Promise.resolve().then(() => {
1101
+ try {
1102
+ if (this.state !== state2) return;
1103
+ if (takeAiResponseClaim(responseId)) {
1104
+ this.takeToolChildren(span);
1105
+ return;
1106
+ }
1107
+ this.captureSpan(state2, span, a, sessionId);
1108
+ } catch (err) {
1109
+ if (state2.config.debug) {
1110
+ console.error(
1111
+ `[sight] span processor error: ${err instanceof Error ? err.message : err}`
1112
+ );
1113
+ }
1114
+ }
1115
+ });
1116
+ return;
1117
+ }
1118
+ }
1119
+ this.captureSpan(state2, span, a, sessionId);
825
1120
  } catch (err) {
826
1121
  if (this.state?.config.debug) {
827
1122
  console.error(
828
- `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`
1123
+ `[sight] span processor error: ${err instanceof Error ? err.message : err}`
829
1124
  );
830
1125
  }
831
1126
  }
832
1127
  }
1128
+ /** The capture itself, once the span is known to be this call's only turn. */
1129
+ captureSpan(state2, span, a, sessionId) {
1130
+ if (!sessionId) {
1131
+ this.takeToolChildren(span);
1132
+ reportNoSessionSkip(`span "${span.name}"`, state2.config.debug);
1133
+ return;
1134
+ }
1135
+ const { traceId, spanId } = span.spanContext();
1136
+ const identity = JSON.stringify([state2.config.deployment, sessionId, traceId, spanId]);
1137
+ if (this.seenSpans.has(identity)) return;
1138
+ this.seenSpans.add(identity);
1139
+ if (this.seenSpans.size > MAX_DEDUP_SPANS) {
1140
+ this.seenSpans.delete(this.seenSpans.values().next().value);
1141
+ }
1142
+ const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
1143
+ state2,
1144
+ sessionId
1145
+ );
1146
+ const captured = {
1147
+ deploymentSlug: state2.config.deployment,
1148
+ sessionExternalId,
1149
+ turnIndex,
1150
+ personaSlug: personaSlug ?? void 0,
1151
+ payload: buildPayload(span, this.takeToolChildren(span))
1152
+ };
1153
+ const hints = { observedUserText: extractUserText(a) };
1154
+ (async () => {
1155
+ await maybeAutoStampEnvironmentConfig(session, a);
1156
+ await this.captureFn(captured, hints);
1157
+ })().catch((err) => {
1158
+ if (state2.config.debug) {
1159
+ console.error(
1160
+ `[sight] span capture error: ${err instanceof Error ? err.message : err}`
1161
+ );
1162
+ }
1163
+ });
1164
+ }
833
1165
  shutdown() {
834
- dedupCache.clear();
1166
+ this.seenSpans.clear();
1167
+ this.toolChildren.clear();
835
1168
  return Promise.resolve();
836
1169
  }
837
1170
  forceFlush() {
@@ -842,6 +1175,10 @@ var ProbeSpanProcessor = class {
842
1175
  // src/instrumentation/wrap-openai.ts
843
1176
  var bound = null;
844
1177
  var warnedUnbound = false;
1178
+ var wrappedClientSeen = false;
1179
+ function hasWrappedClient() {
1180
+ return wrappedClientSeen;
1181
+ }
845
1182
  function bindWrapOpenAI(state2, captureFn) {
846
1183
  bound = { state: state2, captureFn };
847
1184
  }
@@ -890,8 +1227,33 @@ function systemTextFromParams(params) {
890
1227
  }
891
1228
  return void 0;
892
1229
  }
893
- function providerFor(model) {
894
- return model?.toLowerCase().startsWith("mercury") ? "inception" : "openai";
1230
+ var now = Date.now;
1231
+ function hostOf(baseURL) {
1232
+ if (!baseURL) return void 0;
1233
+ try {
1234
+ return new URL(baseURL).hostname.toLowerCase();
1235
+ } catch {
1236
+ return void 0;
1237
+ }
1238
+ }
1239
+ function providerFor(model, baseURL) {
1240
+ if (model?.toLowerCase().startsWith("mercury")) return "inception";
1241
+ const host = hostOf(baseURL);
1242
+ if (!host || host === "api.openai.com") return "openai";
1243
+ if (host === "openrouter.ai" || host.endsWith(".openrouter.ai")) return "openrouter";
1244
+ if (host.endsWith(".openai.azure.com")) return "azure";
1245
+ if (host === "inceptionlabs.ai" || host.endsWith(".inceptionlabs.ai")) return "inception";
1246
+ return void 0;
1247
+ }
1248
+ function costFromUsage(usage) {
1249
+ const cost = asNumber2(usage?.["cost"]);
1250
+ if (cost === void 0 || !Number.isFinite(cost) || cost < 0) return void 0;
1251
+ if (usage?.["is_byok"] === true) {
1252
+ const upstream = asNumber2(asRecord(usage["cost_details"])?.["upstream_inference_cost"]);
1253
+ if (upstream === void 0 || !Number.isFinite(upstream) || upstream < 0) return void 0;
1254
+ return cost + upstream;
1255
+ }
1256
+ return cost;
895
1257
  }
896
1258
  function payloadFromChatResponse(r, requestModel) {
897
1259
  const choice = Array.isArray(r["choices"]) ? asRecord(r["choices"][0]) : void 0;
@@ -907,7 +1269,8 @@ function payloadFromChatResponse(r, requestModel) {
907
1269
  tokensOutput: asNumber2(usage?.["completion_tokens"]),
908
1270
  cachedTokens: asNumber2(promptDetails?.["cached_tokens"]),
909
1271
  finishReason: asString2(choice?.["finish_reason"]),
910
- toolNames
1272
+ toolNames,
1273
+ costUsd: costFromUsage(usage)
911
1274
  };
912
1275
  }
913
1276
  function payloadFromResponsesResponse(r, requestModel) {
@@ -943,23 +1306,31 @@ function payloadFromResponsesResponse(r, requestModel) {
943
1306
  tokensOutput: asNumber2(usage?.["output_tokens"]),
944
1307
  cachedTokens: asNumber2(inputDetails?.["cached_tokens"]),
945
1308
  finishReason: asString2(r["status"]),
946
- toolNames: toolNames.length > 0 ? toolNames : void 0
1309
+ toolNames: toolNames.length > 0 ? toolNames : void 0,
1310
+ costUsd: costFromUsage(usage)
947
1311
  };
948
1312
  }
949
- function buildTurnPayload(x, latencyMs, api) {
1313
+ function buildTurnPayload(x, call) {
950
1314
  return {
951
1315
  probe_tokens_input: x.tokensInput,
952
1316
  probe_tokens_output: x.tokensOutput,
953
- probe_latency_ms: latencyMs,
1317
+ probe_latency_ms: call.latencyMs,
1318
+ probe_first_token_ms: call.firstTokenMs,
1319
+ probe_cost_usd: x.costUsd,
954
1320
  probe_model: x.model,
955
- probe_provider: providerFor(x.model),
1321
+ // The model as requested. The response names a dated snapshot; the
1322
+ // server prices a turn by whichever of the two the catalogue lists.
1323
+ probe_request_model: call.requestModel,
1324
+ probe_provider: providerFor(x.model ?? call.requestModel, call.baseURL),
956
1325
  probe_tool_calls: x.toolNames?.length,
957
1326
  probe_tool_names: x.toolNames,
958
1327
  probe_error: void 0,
959
1328
  probe_finish_reason: x.finishReason,
960
1329
  response: x.text ? { text: x.text } : void 0,
961
1330
  probe_cache_read_input_tokens: x.cachedTokens,
962
- _wrap: { api, adapter: "wrapOpenAI" }
1331
+ // OpenAI usage counts cached tokens inside the input count.
1332
+ probe_cache_tokens_in_input: x.cachedTokens !== void 0 ? true : void 0,
1333
+ _wrap: { api: call.api, adapter: "wrapOpenAI" }
963
1334
  };
964
1335
  }
965
1336
  function emit(params, payload) {
@@ -967,7 +1338,7 @@ function emit(params, payload) {
967
1338
  if (!warnedUnbound) {
968
1339
  warnedUnbound = true;
969
1340
  console.warn(
970
- "[sight] wrapOpenAI: call observed before Probe.init(); nothing captured until init runs."
1341
+ "[sight] wrapOpenAI: call observed before Sight.init(); nothing captured until init runs."
971
1342
  );
972
1343
  }
973
1344
  return;
@@ -975,11 +1346,7 @@ function emit(params, payload) {
975
1346
  const { state: state2, captureFn } = bound;
976
1347
  const sessionId = getCurrentSessionId();
977
1348
  if (!sessionId) {
978
- if (state2.config.debug) {
979
- console.warn(
980
- "[sight] wrapOpenAI: call with no session context; skipped (wrap calls in Probe.withSession())."
981
- );
982
- }
1349
+ reportNoSessionSkip("wrapOpenAI", state2.config.debug);
983
1350
  return;
984
1351
  }
985
1352
  const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
@@ -1044,80 +1411,143 @@ function teeStream(stream, onChunk, onDone) {
1044
1411
  }
1045
1412
  });
1046
1413
  }
1414
+ function nonEmpty(v) {
1415
+ return typeof v === "string" && v.length > 0;
1416
+ }
1047
1417
  function chatStreamAccumulator(requestModel) {
1048
1418
  const texts = [];
1419
+ const toolNameParts = /* @__PURE__ */ new Map();
1049
1420
  let model = requestModel;
1050
1421
  let finishReason;
1051
1422
  let tokensInput;
1052
1423
  let tokensOutput;
1053
1424
  let cachedTokens;
1425
+ let costUsd;
1054
1426
  return {
1055
1427
  onChunk(chunk) {
1056
1428
  const c = asRecord(chunk);
1057
- if (!c) return;
1429
+ if (!c) return false;
1058
1430
  model = asString2(c["model"]) ?? model;
1059
1431
  const choice = Array.isArray(c["choices"]) ? asRecord(c["choices"][0]) : void 0;
1060
1432
  const delta = asRecord(choice?.["delta"]);
1433
+ let content = false;
1061
1434
  const t = asString2(delta?.["content"]);
1062
- if (t) texts.push(t);
1435
+ if (t) {
1436
+ texts.push(t);
1437
+ content = true;
1438
+ }
1439
+ if (nonEmpty(delta?.["refusal"])) content = true;
1440
+ const toolCalls = delta?.["tool_calls"];
1441
+ if (Array.isArray(toolCalls) && toolCalls.length > 0) {
1442
+ content = true;
1443
+ toolCalls.forEach((raw, position) => {
1444
+ const call = asRecord(raw);
1445
+ const name = asString2(asRecord(call?.["function"])?.["name"]);
1446
+ if (!name) return;
1447
+ const index = asNumber2(call?.["index"]) ?? position;
1448
+ toolNameParts.set(index, (toolNameParts.get(index) ?? "") + name);
1449
+ });
1450
+ }
1063
1451
  finishReason = asString2(choice?.["finish_reason"]) ?? finishReason;
1064
1452
  const usage = asRecord(c["usage"]);
1065
1453
  if (usage) {
1066
1454
  tokensInput = asNumber2(usage["prompt_tokens"]) ?? tokensInput;
1067
1455
  tokensOutput = asNumber2(usage["completion_tokens"]) ?? tokensOutput;
1068
1456
  cachedTokens = asNumber2(asRecord(usage["prompt_tokens_details"])?.["cached_tokens"]) ?? cachedTokens;
1457
+ costUsd = costFromUsage(usage) ?? costUsd;
1069
1458
  }
1459
+ return content;
1070
1460
  },
1071
- result: () => ({
1072
- model,
1073
- text: texts.length > 0 ? texts.join("") : void 0,
1074
- tokensInput,
1075
- tokensOutput,
1076
- cachedTokens,
1077
- finishReason,
1078
- toolNames: void 0
1079
- })
1461
+ result: () => {
1462
+ const toolNames = [...toolNameParts.entries()].sort((x, y) => x[0] - y[0]).map((e) => e[1]);
1463
+ return {
1464
+ model,
1465
+ text: texts.length > 0 ? texts.join("") : void 0,
1466
+ tokensInput,
1467
+ tokensOutput,
1468
+ cachedTokens,
1469
+ finishReason,
1470
+ toolNames: toolNames.length > 0 ? toolNames : void 0,
1471
+ costUsd
1472
+ };
1473
+ }
1080
1474
  };
1081
1475
  }
1476
+ var RESPONSES_OUTPUT_DELTAS = /* @__PURE__ */ new Set([
1477
+ "response.output_text.delta",
1478
+ "response.refusal.delta",
1479
+ "response.function_call_arguments.delta"
1480
+ ]);
1082
1481
  function responsesStreamAccumulator(requestModel) {
1083
1482
  const texts = [];
1483
+ const toolNameByIndex = /* @__PURE__ */ new Map();
1084
1484
  let final = null;
1085
1485
  return {
1086
1486
  onChunk(chunk) {
1087
1487
  const c = asRecord(chunk);
1088
- if (!c) return;
1089
- if (c["type"] === "response.output_text.delta") {
1488
+ if (!c) return false;
1489
+ const type = asString2(c["type"]);
1490
+ let content = false;
1491
+ if (type === "response.output_text.delta") {
1090
1492
  const t = asString2(c["delta"]);
1091
1493
  if (t) texts.push(t);
1092
1494
  }
1093
- if (c["type"] === "response.completed") {
1495
+ if (type !== void 0 && RESPONSES_OUTPUT_DELTAS.has(type) && nonEmpty(c["delta"])) {
1496
+ content = true;
1497
+ }
1498
+ if (type === "response.output_item.added" || type === "response.output_item.done") {
1499
+ const item = asRecord(c["item"]);
1500
+ if (item?.["type"] === "function_call") {
1501
+ content = true;
1502
+ const name = asString2(item["name"]);
1503
+ if (name) toolNameByIndex.set(asNumber2(c["output_index"]) ?? toolNameByIndex.size, name);
1504
+ }
1505
+ }
1506
+ if (type === "response.completed") {
1094
1507
  const response = asRecord(c["response"]);
1095
1508
  if (response) final = payloadFromResponsesResponse(response, requestModel);
1096
1509
  }
1510
+ return content;
1097
1511
  },
1098
1512
  result: () => {
1513
+ const streamedNames = [...toolNameByIndex.entries()].sort((x, y) => x[0] - y[0]).map((e) => e[1]);
1514
+ const streamedText = texts.length > 0 ? texts.join("") : void 0;
1099
1515
  if (final) {
1100
- return { ...final, text: final.text ?? (texts.length > 0 ? texts.join("") : void 0) };
1516
+ return {
1517
+ ...final,
1518
+ text: final.text ?? streamedText,
1519
+ toolNames: final.toolNames ?? (streamedNames.length > 0 ? streamedNames : void 0)
1520
+ };
1101
1521
  }
1102
1522
  return {
1103
1523
  model: requestModel,
1104
- text: texts.length > 0 ? texts.join("") : void 0,
1524
+ text: streamedText,
1105
1525
  tokensInput: void 0,
1106
1526
  tokensOutput: void 0,
1107
1527
  cachedTokens: void 0,
1108
1528
  finishReason: void 0,
1109
- toolNames: void 0
1529
+ toolNames: streamedNames.length > 0 ? streamedNames : void 0,
1530
+ costUsd: void 0
1110
1531
  };
1111
1532
  }
1112
1533
  };
1113
1534
  }
1114
- function wrapCreate(target, api, makeAccumulator, extractResponse) {
1535
+ function wrapCreate(client, target, api, makeAccumulator, extractResponse) {
1115
1536
  const original = target["create"];
1116
1537
  if (typeof original !== "function") return;
1117
1538
  target["create"] = function(...args) {
1539
+ if (isInsideAiModelCall()) return original.apply(this, args);
1118
1540
  const params = asRecord(args[0]);
1119
1541
  const requestModel = asString2(params?.["model"]);
1120
- const startedAt = Date.now();
1542
+ const startedAt = now();
1543
+ const baseURL = asString2(client["baseURL"]);
1544
+ const facts = (firstTokenMs) => ({
1545
+ api,
1546
+ latencyMs: now() - startedAt,
1547
+ firstTokenMs,
1548
+ requestModel,
1549
+ baseURL
1550
+ });
1121
1551
  const result = original.apply(this, args);
1122
1552
  if (!result || typeof result.then !== "function") return result;
1123
1553
  return result.then(
@@ -1126,13 +1556,23 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1126
1556
  const isStream = resolved !== null && typeof resolved === "object" && Symbol.asyncIterator in resolved;
1127
1557
  if (isStream) {
1128
1558
  const acc = makeAccumulator(requestModel);
1129
- return teeStream(resolved, acc.onChunk, () => {
1130
- emit(params, buildTurnPayload(acc.result(), Date.now() - startedAt, api));
1131
- });
1559
+ let firstTokenMs;
1560
+ return teeStream(
1561
+ resolved,
1562
+ (chunk) => {
1563
+ const arrivedAt = now();
1564
+ if (acc.onChunk(chunk) && firstTokenMs === void 0) {
1565
+ firstTokenMs = Math.max(0, Math.round(arrivedAt - startedAt));
1566
+ }
1567
+ },
1568
+ () => {
1569
+ emit(params, buildTurnPayload(acc.result(), facts(firstTokenMs)));
1570
+ }
1571
+ );
1132
1572
  }
1133
1573
  const r = asRecord(resolved);
1134
1574
  if (r) {
1135
- emit(params, buildTurnPayload(extractResponse(r, requestModel), Date.now() - startedAt, api));
1575
+ emit(params, buildTurnPayload(extractResponse(r, requestModel), facts()));
1136
1576
  }
1137
1577
  return resolved;
1138
1578
  } catch {
@@ -1148,9 +1588,10 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1148
1588
  tokensOutput: void 0,
1149
1589
  cachedTokens: void 0,
1150
1590
  finishReason: void 0,
1151
- toolNames: void 0
1591
+ toolNames: void 0,
1592
+ costUsd: void 0
1152
1593
  };
1153
- const payload = buildTurnPayload(x, Date.now() - startedAt, api);
1594
+ const payload = buildTurnPayload(x, facts());
1154
1595
  payload.probe_error = err instanceof Error ? err.message : String(err);
1155
1596
  emit(params, payload);
1156
1597
  } catch {
@@ -1161,19 +1602,465 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1161
1602
  };
1162
1603
  }
1163
1604
  function wrapOpenAI(client) {
1605
+ wrappedClientSeen = true;
1164
1606
  const c = client;
1165
1607
  if (c[WRAPPED]) return client;
1166
1608
  c[WRAPPED] = true;
1167
1609
  const completions = asRecord(asRecord(c["chat"])?.["completions"]);
1168
1610
  if (completions) {
1169
- wrapCreate(completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
1611
+ wrapCreate(c, completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
1170
1612
  }
1171
1613
  const responses = asRecord(c["responses"]);
1172
1614
  if (responses) {
1173
- wrapCreate(responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
1615
+ wrapCreate(c, responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
1174
1616
  }
1175
1617
  return client;
1176
1618
  }
1619
+ var AI_SESSION_KEYS = ["sightSessionId", "sessionId"];
1620
+ var bound2 = null;
1621
+ var everBound = false;
1622
+ var warnedUnbound2 = false;
1623
+ function bindVercelAI(state2, captureFn) {
1624
+ bound2 = { state: state2, captureFn };
1625
+ everBound = true;
1626
+ }
1627
+ function unbindVercelAI() {
1628
+ bound2 = null;
1629
+ for (const call of calls.values()) closeModelCall(call);
1630
+ calls.clear();
1631
+ }
1632
+ function rec(v) {
1633
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : void 0;
1634
+ }
1635
+ function str(v) {
1636
+ return typeof v === "string" && v.length > 0 ? v : void 0;
1637
+ }
1638
+ function num(v) {
1639
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
1640
+ }
1641
+ function ms(v) {
1642
+ const n = num(v);
1643
+ return n === void 0 ? void 0 : Math.max(0, Math.round(n));
1644
+ }
1645
+ function textOfContent(content, sep) {
1646
+ if (typeof content === "string") return content.length > 0 ? content : void 0;
1647
+ if (!Array.isArray(content)) return void 0;
1648
+ const texts = [];
1649
+ for (const part of content) {
1650
+ const p = rec(part);
1651
+ if (p?.["type"] === "text" && typeof p["text"] === "string" && p["text"].length > 0) {
1652
+ texts.push(p["text"]);
1653
+ }
1654
+ }
1655
+ return texts.length > 0 ? texts.join(sep) : void 0;
1656
+ }
1657
+ function userTextOf(messages) {
1658
+ if (!Array.isArray(messages)) return void 0;
1659
+ for (let i = messages.length - 1; i >= 0; i--) {
1660
+ const m = rec(messages[i]);
1661
+ if (!m) return void 0;
1662
+ if (m["role"] === "system") continue;
1663
+ if (m["role"] !== "user") return void 0;
1664
+ return textOfContent(m["content"], "\n");
1665
+ }
1666
+ return void 0;
1667
+ }
1668
+ function systemTextOf(instructions, messages) {
1669
+ if (typeof instructions === "string") return str(instructions);
1670
+ const list = Array.isArray(instructions) ? instructions : instructions ? [instructions] : [];
1671
+ const texts = [];
1672
+ for (const item of list) {
1673
+ const t = textOfContent(rec(item)?.["content"], "\n");
1674
+ if (t) texts.push(t);
1675
+ }
1676
+ if (texts.length > 0) return texts.join("\n");
1677
+ if (Array.isArray(messages)) {
1678
+ for (const raw of messages) {
1679
+ const m = rec(raw);
1680
+ if (m?.["role"] === "system") {
1681
+ const t = textOfContent(m["content"], "\n");
1682
+ if (t) return t;
1683
+ }
1684
+ }
1685
+ }
1686
+ return void 0;
1687
+ }
1688
+ function sessionFromContext(runtimeContext) {
1689
+ const ctx = rec(runtimeContext);
1690
+ if (!ctx) return void 0;
1691
+ for (const key of AI_SESSION_KEYS) {
1692
+ const v = str(ctx[key]);
1693
+ if (v) return v;
1694
+ }
1695
+ return void 0;
1696
+ }
1697
+ function errorMessage(err) {
1698
+ if (err instanceof Error) return err.message || err.name;
1699
+ return typeof err === "string" && err.length > 0 ? err : "error";
1700
+ }
1701
+ var MAX_CALLS = 1e3;
1702
+ var calls = /* @__PURE__ */ new Map();
1703
+ function stateFor(callId) {
1704
+ let call = calls.get(callId);
1705
+ if (!call) {
1706
+ call = {
1707
+ scopeSession: void 0,
1708
+ contextSession: void 0,
1709
+ operationId: void 0,
1710
+ system: void 0,
1711
+ open: null
1712
+ };
1713
+ if (calls.size >= MAX_CALLS) {
1714
+ const oldest = calls.keys().next().value;
1715
+ closeModelCall(calls.get(oldest));
1716
+ calls.delete(oldest);
1717
+ }
1718
+ calls.set(callId, call);
1719
+ }
1720
+ return call;
1721
+ }
1722
+ function openModelCall(call, modelCall) {
1723
+ if (call.open === null) noteAiModelCallOpened();
1724
+ call.open = modelCall;
1725
+ }
1726
+ function closeModelCall(call) {
1727
+ if (call.open !== null) noteAiModelCallClosed();
1728
+ call.open = null;
1729
+ }
1730
+ function buildPayload2(call, f) {
1731
+ const usage = rec(f.usage);
1732
+ const inputDetails = rec(usage?.["inputTokenDetails"]);
1733
+ const outputDetails = rec(usage?.["outputTokenDetails"]);
1734
+ const toolNames = f.toolNames && f.toolNames.length > 0 ? f.toolNames : void 0;
1735
+ return {
1736
+ probe_tokens_input: num(usage?.["inputTokens"]),
1737
+ probe_tokens_output: num(usage?.["outputTokens"]),
1738
+ probe_latency_ms: f.latencyMs,
1739
+ probe_first_token_ms: f.firstTokenMs,
1740
+ probe_model: f.model,
1741
+ probe_provider: f.provider,
1742
+ probe_tool_calls: toolNames?.length,
1743
+ probe_tool_names: toolNames,
1744
+ probe_error: f.error,
1745
+ probe_finish_reason: f.finishReason,
1746
+ response: f.text ? { text: f.text } : void 0,
1747
+ probe_cache_read_input_tokens: num(inputDetails?.["cacheReadTokens"]),
1748
+ probe_cache_creation_input_tokens: num(inputDetails?.["cacheWriteTokens"]),
1749
+ // Debug metadata (kept in payload, not projected to canonical columns).
1750
+ _ai: {
1751
+ adapter: "ai-telemetry",
1752
+ operationId: call.operationId,
1753
+ callId: f.callId,
1754
+ stepNumber: f.stepNumber,
1755
+ functionId: f.functionId,
1756
+ responseId: f.responseId,
1757
+ rawFinishReason: f.rawFinishReason,
1758
+ reasoningTokens: num(outputDetails?.["reasoningTokens"])
1759
+ }
1760
+ };
1761
+ }
1762
+ function emit2(options, call, request, fields) {
1763
+ if (!bound2) {
1764
+ if (!everBound && !warnedUnbound2) {
1765
+ warnedUnbound2 = true;
1766
+ console.warn(
1767
+ "[sight] ai telemetry: call observed before Sight.init(); nothing captured until init runs."
1768
+ );
1769
+ }
1770
+ return;
1771
+ }
1772
+ const { state: state2, captureFn } = bound2;
1773
+ const sessionId = call.scopeSession ?? (getCurrentSessionId() || options.sessionId || call.contextSession);
1774
+ if (!sessionId) {
1775
+ reportNoSessionSkip(`ai ${call.operationId ?? "model call"}`, state2.config.debug);
1776
+ return;
1777
+ }
1778
+ const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
1779
+ state2,
1780
+ sessionId
1781
+ );
1782
+ const captured = {
1783
+ deploymentSlug: state2.config.deployment,
1784
+ sessionExternalId,
1785
+ turnIndex,
1786
+ personaSlug: personaSlug ?? void 0,
1787
+ payload: buildPayload2(call, fields)
1788
+ };
1789
+ const hints = { observedUserText: userTextOf(request.messages) };
1790
+ const systemText = systemTextOf(request.instructions, request.messages);
1791
+ void (async () => {
1792
+ await autoStampFromSystemText(session, systemText);
1793
+ await captureFn(captured, hints);
1794
+ })().catch((err) => {
1795
+ if (state2.config.debug) {
1796
+ console.error(
1797
+ `[sight] ai telemetry capture error: ${err instanceof Error ? err.message : err}`
1798
+ );
1799
+ }
1800
+ });
1801
+ }
1802
+ var BRAND = /* @__PURE__ */ Symbol.for("sight.aiTelemetry");
1803
+ function isSightIntegration(v) {
1804
+ return v !== null && typeof v === "object" && v[BRAND] === true;
1805
+ }
1806
+ function guarded(fn) {
1807
+ return (event) => {
1808
+ try {
1809
+ const e = rec(event);
1810
+ if (e) fn(e);
1811
+ } catch (err) {
1812
+ if (bound2?.state.config.debug) {
1813
+ console.error(
1814
+ `[sight] ai telemetry hook error: ${err instanceof Error ? err.message : err}`
1815
+ );
1816
+ }
1817
+ }
1818
+ };
1819
+ }
1820
+ function createIntegration(options) {
1821
+ const failed = (callId, error, functionId) => {
1822
+ if (!callId) return;
1823
+ const call = calls.get(callId);
1824
+ if (!call) return;
1825
+ const open = call.open;
1826
+ closeModelCall(call);
1827
+ calls.delete(callId);
1828
+ if (!open) return;
1829
+ emit2(
1830
+ options,
1831
+ call,
1832
+ { instructions: open.instructions, messages: open.messages },
1833
+ {
1834
+ callId,
1835
+ model: open.modelId,
1836
+ provider: open.provider,
1837
+ latencyMs: Math.max(0, Date.now() - open.startedAt),
1838
+ error,
1839
+ functionId: str(functionId)
1840
+ }
1841
+ );
1842
+ };
1843
+ const begin = (e, instructions, messages) => {
1844
+ const callId = str(e["callId"]);
1845
+ if (!callId) return;
1846
+ const call = stateFor(callId);
1847
+ call.scopeSession ??= getCurrentSessionId() || void 0;
1848
+ const record = e["recordInputs"] !== false;
1849
+ openModelCall(call, {
1850
+ startedAt: Date.now(),
1851
+ instructions: record ? instructions : void 0,
1852
+ messages: record ? messages : void 0,
1853
+ provider: str(e["provider"]),
1854
+ modelId: str(e["modelId"])
1855
+ });
1856
+ };
1857
+ const integration = {
1858
+ name: "sight",
1859
+ onStart: guarded((e) => {
1860
+ const callId = str(e["callId"]);
1861
+ if (!callId) return;
1862
+ const call = stateFor(callId);
1863
+ call.scopeSession = getCurrentSessionId() || void 0;
1864
+ call.contextSession = sessionFromContext(e["runtimeContext"]);
1865
+ call.operationId = str(e["operationId"]);
1866
+ call.system = e["system"] ?? e["instructions"];
1867
+ }),
1868
+ onStepStart: guarded((e) => {
1869
+ const callId = str(e["callId"]);
1870
+ if (!callId) return;
1871
+ const call = stateFor(callId);
1872
+ call.contextSession = sessionFromContext(e["runtimeContext"]) ?? call.contextSession;
1873
+ }),
1874
+ onLanguageModelCallStart: guarded((e) => {
1875
+ begin(e, e["instructions"], e["messages"]);
1876
+ }),
1877
+ onLanguageModelCallEnd: guarded((e) => {
1878
+ const responseId = str(e["responseId"]);
1879
+ if (bound2 && responseId) claimAiResponse(responseId);
1880
+ }),
1881
+ onStepEnd: guarded((e) => {
1882
+ const callId = str(e["callId"]);
1883
+ if (!callId) return;
1884
+ const call = calls.get(callId);
1885
+ if (!call) return;
1886
+ const open = call.open;
1887
+ closeModelCall(call);
1888
+ call.contextSession = sessionFromContext(e["runtimeContext"]) ?? call.contextSession;
1889
+ const model = rec(e["model"]);
1890
+ const response = rec(e["response"]);
1891
+ const performance = rec(e["performance"]);
1892
+ const content = Array.isArray(e["content"]) ? e["content"] : [];
1893
+ const toolNames = [];
1894
+ for (const part of content) {
1895
+ const p = rec(part);
1896
+ if (p?.["type"] === "tool-call") {
1897
+ const name = str(p["toolName"]);
1898
+ if (name) toolNames.push(name);
1899
+ }
1900
+ }
1901
+ const finishReason = str(e["finishReason"]);
1902
+ emit2(
1903
+ options,
1904
+ call,
1905
+ { instructions: open?.instructions, messages: open?.messages },
1906
+ {
1907
+ callId,
1908
+ // Text parts only: never reasoning, tool input or tool output.
1909
+ text: e["recordOutputs"] === false ? void 0 : textOfContent(content, ""),
1910
+ // The id the provider returned; the requested id when it returned none.
1911
+ model: str(response?.["modelId"]) ?? str(model?.["modelId"]) ?? open?.modelId,
1912
+ provider: str(model?.["provider"]) ?? open?.provider,
1913
+ usage: e["usage"],
1914
+ finishReason,
1915
+ rawFinishReason: str(e["rawFinishReason"]),
1916
+ toolNames,
1917
+ latencyMs: ms(performance?.["responseTimeMs"]) ?? (open ? Math.max(0, Date.now() - open.startedAt) : void 0),
1918
+ firstTokenMs: ms(performance?.["timeToFirstOutputMs"]),
1919
+ // A stream that failed part way ends its step with this finish
1920
+ // reason; the events carry no error message for it.
1921
+ error: finishReason === "error" ? 'model call ended with finish reason "error"' : void 0,
1922
+ responseId: str(response?.["id"]),
1923
+ stepNumber: num(e["stepNumber"]),
1924
+ functionId: str(e["functionId"])
1925
+ }
1926
+ );
1927
+ }),
1928
+ onObjectStepStart: guarded((e) => {
1929
+ const callId = str(e["callId"]);
1930
+ begin(e, callId ? calls.get(callId)?.system : void 0, e["promptMessages"]);
1931
+ }),
1932
+ onObjectStepEnd: guarded((e) => {
1933
+ const callId = str(e["callId"]);
1934
+ if (!callId) return;
1935
+ const call = calls.get(callId);
1936
+ if (!call) return;
1937
+ const open = call.open;
1938
+ closeModelCall(call);
1939
+ const response = rec(e["response"]);
1940
+ const responseId = str(response?.["id"]);
1941
+ if (bound2 && responseId) claimAiResponse(responseId);
1942
+ emit2(
1943
+ options,
1944
+ call,
1945
+ { instructions: open?.instructions, messages: open?.messages },
1946
+ {
1947
+ callId,
1948
+ // The reply of an object call is the JSON text the model produced.
1949
+ text: e["recordOutputs"] === false ? void 0 : str(e["objectText"]),
1950
+ model: str(response?.["modelId"]) ?? str(e["modelId"]) ?? open?.modelId,
1951
+ provider: str(e["provider"]) ?? open?.provider,
1952
+ usage: e["usage"],
1953
+ finishReason: str(e["finishReason"]),
1954
+ latencyMs: open ? Math.max(0, Date.now() - open.startedAt) : void 0,
1955
+ firstTokenMs: ms(e["msToFirstChunk"]),
1956
+ responseId,
1957
+ stepNumber: num(e["stepNumber"]),
1958
+ functionId: str(e["functionId"])
1959
+ }
1960
+ );
1961
+ }),
1962
+ onError: guarded((e) => {
1963
+ failed(str(e["callId"]), errorMessage(e["error"]), e["functionId"]);
1964
+ }),
1965
+ onAbort: guarded((e) => {
1966
+ failed(str(e["callId"]), "aborted", e["functionId"]);
1967
+ }),
1968
+ onEnd: guarded((e) => {
1969
+ const callId = str(e["callId"]);
1970
+ if (!callId) return;
1971
+ const call = calls.get(callId);
1972
+ if (!call) return;
1973
+ closeModelCall(call);
1974
+ calls.delete(callId);
1975
+ }),
1976
+ executeLanguageModelCall(callOptions) {
1977
+ if (!bound2) return callOptions.execute();
1978
+ return runInsideAiModelCall(() => callOptions.execute());
1979
+ }
1980
+ };
1981
+ Object.defineProperty(integration, BRAND, { value: true });
1982
+ return integration;
1983
+ }
1984
+ var shared = null;
1985
+ function sightTelemetry(options) {
1986
+ if (options && options.sessionId !== void 0) return createIntegration(options);
1987
+ shared ??= createIntegration({});
1988
+ return shared;
1989
+ }
1990
+ function canRequireEsModule() {
1991
+ const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
1992
+ return major >= 24 || major === 23 && minor >= 5 || major === 22 && minor >= 13;
1993
+ }
1994
+ var defaultLoaders = {
1995
+ // `ai` reads its integration list when a call starts, so a registration
1996
+ // that lands a tick after init would miss a call made right after init.
1997
+ // `ai` 7 is ES module only; where require() can load it this registers
1998
+ // before init returns, and anywhere else the asynchronous import is used.
1999
+ // createRequire, never a bare `require`: the bundler replaces a bare one
2000
+ // in the ES module build with a stub that always throws.
2001
+ sync: () => canRequireEsModule() ? createRequire(import.meta.url)("ai") : null,
2002
+ async: () => import('ai')
2003
+ };
2004
+ function globalIntegrations() {
2005
+ const list = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS;
2006
+ return Array.isArray(list) ? list : [];
2007
+ }
2008
+ var registered = false;
2009
+ function register(mod, debug) {
2010
+ if (registered) return;
2011
+ const registerTelemetry = rec(mod)?.["registerTelemetry"];
2012
+ if (typeof registerTelemetry !== "function") {
2013
+ if (debug) {
2014
+ console.log(
2015
+ "[sight/vercel-ai] ai <7 found: no integration to register; calls made with experimental_telemetry: { isEnabled: true } are captured from their OpenTelemetry spans"
2016
+ );
2017
+ }
2018
+ return;
2019
+ }
2020
+ registered = true;
2021
+ if (globalIntegrations().some(isSightIntegration)) {
2022
+ if (debug) console.log("[sight/vercel-ai] telemetry integration already registered");
2023
+ return;
2024
+ }
2025
+ registerTelemetry(sightTelemetry());
2026
+ if (debug) {
2027
+ console.log(
2028
+ "[sight/vercel-ai] telemetry integration registered; generateText, streamText, generateObject and streamObject calls are captured, one turn per model call"
2029
+ );
2030
+ }
2031
+ }
2032
+ async function registerVercelAI(state2, captureFn, loaders = defaultLoaders) {
2033
+ if (captureFn) bindVercelAI(state2, captureFn);
2034
+ if (registered) return;
2035
+ const debug = state2.config.debug;
2036
+ let mod = null;
2037
+ try {
2038
+ mod = loaders.sync();
2039
+ } catch {
2040
+ mod = null;
2041
+ }
2042
+ if (mod === null || mod === void 0) {
2043
+ try {
2044
+ mod = await loaders.async();
2045
+ } catch {
2046
+ if (debug) {
2047
+ console.log(
2048
+ "[sight/vercel-ai] ai is not installed; nothing registered. If ai is bundled where the SDK cannot resolve it, call registerTelemetry(sightTelemetry())."
2049
+ );
2050
+ }
2051
+ return;
2052
+ }
2053
+ }
2054
+ try {
2055
+ register(mod, debug);
2056
+ } catch (err) {
2057
+ if (debug) {
2058
+ console.warn(
2059
+ `[sight/vercel-ai] telemetry integration not registered (${err instanceof Error ? err.message : err})`
2060
+ );
2061
+ }
2062
+ }
2063
+ }
1177
2064
 
1178
2065
  // src/instrumentation/setup.ts
1179
2066
  var installedProcessor = null;
@@ -1198,13 +2085,14 @@ function setupOtelProvider(state2, captureFn) {
1198
2085
  function detachOtelState() {
1199
2086
  installedProcessor?.rebind(null);
1200
2087
  unbindWrapOpenAI();
2088
+ unbindVercelAI();
1201
2089
  }
1202
2090
 
1203
2091
  // src/instrumentation/openai.ts
1204
- var registered = false;
2092
+ var registered2 = false;
1205
2093
  var instrumentation = null;
1206
2094
  async function registerOpenAI(state2) {
1207
- if (registered) return;
2095
+ if (registered2) return;
1208
2096
  try {
1209
2097
  const mod = await import('@traceloop/instrumentation-openai');
1210
2098
  instrumentation = new mod.OpenAIInstrumentation({
@@ -1212,18 +2100,18 @@ async function registerOpenAI(state2) {
1212
2100
  exceptionLogger: (err) => {
1213
2101
  if (state2.config.debug) {
1214
2102
  console.error(
1215
- `[probe/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`
2103
+ `[sight/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`
1216
2104
  );
1217
2105
  }
1218
2106
  }
1219
2107
  });
1220
2108
  instrumentation.enable();
1221
- registered = true;
2109
+ registered2 = true;
1222
2110
  void verifyPatchAttached();
1223
2111
  } catch (err) {
1224
2112
  if (state2.config.debug) {
1225
2113
  const msg = err instanceof Error ? err.message : String(err);
1226
- console.warn(`[probe/openai] instrumentation not enabled (${msg}); library not installed?`);
2114
+ console.warn(`[sight/openai] instrumentation not enabled (${msg}); library not installed?`);
1227
2115
  }
1228
2116
  }
1229
2117
  }
@@ -1233,94 +2121,85 @@ function isPatchDetached(mod) {
1233
2121
  if (typeof create !== "function") return true;
1234
2122
  return create.__wrapped !== true;
1235
2123
  }
2124
+ function patchWarning(mod, wrappedClientInUse) {
2125
+ if (!isPatchDetached(mod)) return null;
2126
+ if (wrappedClientInUse) return null;
2127
+ const version = mod?.default?.VERSION ?? mod?.VERSION;
2128
+ return `[sight] OpenAI module patching did not attach` + (version ? ` (openai v${version})` : "") + `. This happens on openai >=5, under ESM, or when 'openai' loads before init. Calls through a client passed to wrapOpenAI() are captured; calls through an unwrapped OpenAI client are not. import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()).`;
2129
+ }
1236
2130
  async function verifyPatchAttached() {
1237
2131
  try {
1238
2132
  const mod = await import('openai');
1239
- if (!isPatchDetached(mod)) return;
1240
- const version = mod?.default?.VERSION ?? mod?.VERSION;
1241
- console.warn(
1242
- `[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.`
1243
- );
2133
+ const line = patchWarning(mod, hasWrappedClient());
2134
+ if (line !== null) console.warn(line);
1244
2135
  } catch {
1245
2136
  }
1246
2137
  }
1247
2138
 
1248
2139
  // src/instrumentation/anthropic.ts
1249
- var registered2 = false;
2140
+ var registered3 = false;
1250
2141
  var instrumentation2 = null;
1251
2142
  async function registerAnthropic(state2) {
1252
- if (registered2) return;
2143
+ if (registered3) return;
1253
2144
  try {
1254
2145
  const mod = await import('@traceloop/instrumentation-anthropic');
1255
2146
  instrumentation2 = new mod.AnthropicInstrumentation({
1256
2147
  exceptionLogger: (err) => {
1257
2148
  if (state2.config.debug) {
1258
2149
  console.error(
1259
- `[probe/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`
2150
+ `[sight/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`
1260
2151
  );
1261
2152
  }
1262
2153
  }
1263
2154
  });
1264
2155
  instrumentation2.enable();
1265
- registered2 = true;
2156
+ registered3 = true;
1266
2157
  } catch (err) {
1267
2158
  if (state2.config.debug) {
1268
2159
  const msg = err instanceof Error ? err.message : String(err);
1269
2160
  console.warn(
1270
- `[probe/anthropic] instrumentation not enabled (${msg}); library not installed?`
2161
+ `[sight/anthropic] instrumentation not enabled (${msg}); library not installed?`
1271
2162
  );
1272
2163
  }
1273
2164
  }
1274
2165
  }
1275
2166
 
1276
2167
  // src/instrumentation/langchain.ts
1277
- var registered3 = false;
2168
+ var registered4 = false;
1278
2169
  var instrumentation3 = null;
1279
2170
  async function registerLangChain(state2) {
1280
- if (registered3) return;
2171
+ if (registered4) return;
1281
2172
  try {
1282
2173
  const mod = await import('@traceloop/instrumentation-langchain');
1283
2174
  instrumentation3 = new mod.LangChainInstrumentation({
1284
2175
  exceptionLogger: (err) => {
1285
2176
  if (state2.config.debug) {
1286
2177
  console.error(
1287
- `[probe/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`
2178
+ `[sight/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`
1288
2179
  );
1289
2180
  }
1290
2181
  }
1291
2182
  });
1292
2183
  instrumentation3.enable();
1293
- registered3 = true;
2184
+ registered4 = true;
1294
2185
  } catch (err) {
1295
2186
  if (state2.config.debug) {
1296
2187
  const msg = err instanceof Error ? err.message : String(err);
1297
2188
  console.warn(
1298
- `[probe/langchain] instrumentation not enabled (${msg}); library not installed?`
2189
+ `[sight/langchain] instrumentation not enabled (${msg}); library not installed?`
1299
2190
  );
1300
2191
  }
1301
2192
  }
1302
2193
  }
1303
2194
 
1304
2195
  // src/instrumentation/langgraph.ts
1305
- var registered4 = false;
1306
- async function registerLangGraph(state2) {
1307
- if (registered4) return;
1308
- registered4 = true;
1309
- if (state2.config.debug) {
1310
- console.log(
1311
- "[probe/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology"
1312
- );
1313
- }
1314
- }
1315
-
1316
- // src/instrumentation/vercel-ai.ts
1317
2196
  var registered5 = false;
1318
- async function registerVercelAI(state2) {
2197
+ async function registerLangGraph(state2) {
1319
2198
  if (registered5) return;
1320
2199
  registered5 = true;
1321
2200
  if (state2.config.debug) {
1322
2201
  console.log(
1323
- "[probe/vercel-ai] active; customer must set experimental_telemetry: { isEnabled: true } per call"
2202
+ "[sight/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology"
1324
2203
  );
1325
2204
  }
1326
2205
  }
@@ -1332,7 +2211,7 @@ async function registerLiteLLM(state2) {
1332
2211
  registered6 = true;
1333
2212
  if (state2.config.debug) {
1334
2213
  console.log(
1335
- "[probe/litellm] not captured on SDK side; use the Chapter 4 URL-swap proxy for LiteLLM traffic"
2214
+ "[sight/litellm] LiteLLM (Python) traffic is not captured by this SDK"
1336
2215
  );
1337
2216
  }
1338
2217
  }
@@ -1344,7 +2223,7 @@ async function registerMercury(state2) {
1344
2223
  registered7 = true;
1345
2224
  if (state2.config.debug) {
1346
2225
  console.log(
1347
- "[probe/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route"
2226
+ "[sight/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route"
1348
2227
  );
1349
2228
  }
1350
2229
  }
@@ -1358,7 +2237,7 @@ function registerAllInstrumentations(state2, captureFn) {
1358
2237
  registerAnthropic(state2),
1359
2238
  registerLangChain(state2),
1360
2239
  registerLangGraph(state2),
1361
- registerVercelAI(state2),
2240
+ registerVercelAI(state2, captureFn),
1362
2241
  registerLiteLLM(state2),
1363
2242
  registerMercury(state2)
1364
2243
  ];
@@ -1529,9 +2408,15 @@ var UserOutcomeSchema = z.object({
1529
2408
  /** Thumbs-up / thumbs-down widget value. */
1530
2409
  thumbs: z.enum(["up", "down"]).optional()
1531
2410
  });
1532
- z.object({
2411
+ var TurnInputSchema = z.object({
1533
2412
  deploymentSlug: z.string().min(1),
1534
2413
  sessionExternalId: z.string().min(1),
2414
+ /**
2415
+ * The SDK payload contract version (D2): optional, additive-only. Every
2416
+ * reader treats a missing stamp as 'envelope-v0-unstamped' — payloads
2417
+ * from older SDKs are valid by construction (tolerated-absent).
2418
+ */
2419
+ envelopeVersion: z.string().max(40).optional(),
1535
2420
  /**
1536
2421
  * Customer's user identity (opaque string), forwarded by the SDK from
1537
2422
  * Probe.startSession() state on every turn. Distinct from
@@ -1542,6 +2427,8 @@ z.object({
1542
2427
  */
1543
2428
  externalUserId: z.string().min(1).optional(),
1544
2429
  turnIndex: z.number().int().nonnegative(),
2430
+ // the SDK's identity for one logical turn; with it, an index collision takes the next index instead of dropping
2431
+ turnId: z.string().uuid().optional(),
1545
2432
  /**
1546
2433
  * Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the
1547
2434
  * worker: when present it becomes turns.started_at; when absent the
@@ -1606,9 +2493,12 @@ z.object({
1606
2493
  * All optional. Powers Chapter 8e′ Card 3 version behavioral diff.
1607
2494
  */
1608
2495
  agentId: z.string().optional(),
1609
- experimentId: z.string().optional(),
2496
+ // Endpoint capture explicitly records no experiment; older SDKs omit it.
2497
+ experimentId: z.string().nullish().transform((value) => value ?? void 0),
1610
2498
  environmentConfigHash: z.string().optional(),
1611
2499
  environmentConfigLabel: z.string().optional(),
2500
+ /** Internal Studio runner provenance. Customer SDKs never set this. */
2501
+ studioRunRequestId: z.string().uuid().optional(),
1612
2502
  /**
1613
2503
  * Session context riding the FIRST turn of a session (there is no
1614
2504
  * session-start wire route; the session row is created lazily by the
@@ -1627,14 +2517,28 @@ z.object({
1627
2517
  clientContext: z.record(z.string(), z.unknown()).optional(),
1628
2518
  payload: z.record(z.string(), z.unknown())
1629
2519
  });
1630
- z.object({
2520
+ var SessionEndSchema2 = z.object({
1631
2521
  deploymentSlug: z.string().min(1),
1632
2522
  sessionExternalId: z.string().min(1),
1633
2523
  /** Why the session ended. */
1634
- endedReason: z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional(),
2524
+ endedReason: z.enum([
2525
+ "natural",
2526
+ "user_closed",
2527
+ "timeout",
2528
+ "agent_error",
2529
+ "user_flagged",
2530
+ "crashed"
2531
+ ]).optional(),
1635
2532
  /** ISO timestamp of session end. */
1636
2533
  endedAt: z.string().optional()
1637
2534
  });
2535
+ var ENGINE_ENDED_REASONS = ["floor", "turn_cap"];
2536
+ SessionEndSchema2.extend({
2537
+ endedReason: z.enum([
2538
+ ...SessionEndSchema2.shape.endedReason.unwrap().options,
2539
+ ...ENGINE_ENDED_REASONS
2540
+ ]).optional()
2541
+ });
1638
2542
  z.object({
1639
2543
  deploymentSlug: z.string().min(1),
1640
2544
  sessionExternalId: z.string().min(1),
@@ -1698,8 +2602,113 @@ var EnvironmentEventsBatchSchema = z.object({
1698
2602
  events: z.array(EnvironmentEventInputSchema).min(1).max(100),
1699
2603
  alignment: AlignmentProvenanceSchema
1700
2604
  });
1701
- var SPAN_TYPES = ["llm_call", "tool_call", "framework_step", "custom"];
1702
- var SpanInputSchema = z.object({
2605
+ var SPAN_TYPES = [
2606
+ "agent_call",
2607
+ "llm_call",
2608
+ "tool_call",
2609
+ "framework_step",
2610
+ "custom"
2611
+ ];
2612
+ var SPAN_STATUSES = ["unset", "ok", "error"];
2613
+ var SPAN_V2_STATUSES = ["ok", "error"];
2614
+ var SPAN_PAYLOAD_STATES = [
2615
+ "captured",
2616
+ "empty",
2617
+ "not_captured",
2618
+ "redacted",
2619
+ "unavailable"
2620
+ ];
2621
+ var SPAN_INTERVAL_KINDS = [
2622
+ "active",
2623
+ "waiting",
2624
+ "retry",
2625
+ "error"
2626
+ ];
2627
+ var SpanIntervalSchema = z.object({
2628
+ kind: z.enum(SPAN_INTERVAL_KINDS),
2629
+ startedAt: z.string().datetime(),
2630
+ endedAt: z.string().datetime()
2631
+ }).superRefine((interval, ctx) => {
2632
+ if (new Date(interval.endedAt).getTime() <= new Date(interval.startedAt).getTime()) {
2633
+ ctx.addIssue({
2634
+ code: z.ZodIssueCode.custom,
2635
+ path: ["endedAt"],
2636
+ message: "interval endedAt must follow startedAt"
2637
+ });
2638
+ }
2639
+ });
2640
+ function serializedJsonLength(value) {
2641
+ try {
2642
+ return JSON.stringify(value)?.length ?? 0;
2643
+ } catch {
2644
+ return Number.POSITIVE_INFINITY;
2645
+ }
2646
+ }
2647
+ function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
2648
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
2649
+ return true;
2650
+ }
2651
+ if (typeof value === "number") return Number.isFinite(value);
2652
+ if (typeof value !== "object") return false;
2653
+ if (ancestors.has(value)) return false;
2654
+ const nextAncestors = new Set(ancestors).add(value);
2655
+ if (Array.isArray(value)) {
2656
+ return value.every((item) => isJsonValue(item, nextAncestors));
2657
+ }
2658
+ if (Object.getPrototypeOf(value) !== Object.prototype) return false;
2659
+ return Object.values(value).every(
2660
+ (item) => isJsonValue(item, nextAncestors)
2661
+ );
2662
+ }
2663
+ function isStructurallyEmptyPayload(value) {
2664
+ if (value === "") return true;
2665
+ if (Array.isArray(value)) return value.length === 0;
2666
+ return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype && Object.keys(value).length === 0;
2667
+ }
2668
+ var SpanPayloadSchema = z.object({
2669
+ state: z.enum(SPAN_PAYLOAD_STATES),
2670
+ value: z.unknown().nullable()
2671
+ }).superRefine((payload, ctx) => {
2672
+ if (!("value" in payload)) {
2673
+ ctx.addIssue({
2674
+ code: z.ZodIssueCode.custom,
2675
+ path: ["value"],
2676
+ message: "payload value must be present; use null for non-captured states"
2677
+ });
2678
+ return;
2679
+ }
2680
+ if (payload.state === "captured" && !isJsonValue(payload.value)) {
2681
+ ctx.addIssue({
2682
+ code: z.ZodIssueCode.custom,
2683
+ path: ["value"],
2684
+ message: "captured payload must be JSON-compatible"
2685
+ });
2686
+ }
2687
+ if (payload.state === "captured" && payload.value === null) {
2688
+ ctx.addIssue({
2689
+ code: z.ZodIssueCode.custom,
2690
+ path: ["value"],
2691
+ message: "captured payload requires a non-null value"
2692
+ });
2693
+ }
2694
+ if (payload.state === "captured" && isStructurallyEmptyPayload(payload.value)) {
2695
+ ctx.addIssue({
2696
+ code: z.ZodIssueCode.custom,
2697
+ path: ["value"],
2698
+ message: "genuinely empty payloads require state=empty"
2699
+ });
2700
+ }
2701
+ if (payload.state !== "captured" && payload.value !== null) {
2702
+ ctx.addIssue({
2703
+ code: z.ZodIssueCode.custom,
2704
+ path: ["value"],
2705
+ message: `${payload.state} payload must carry a null value`
2706
+ });
2707
+ }
2708
+ }).refine((payload) => serializedJsonLength(payload.value) <= 16e3, {
2709
+ message: "span payload exceeds 16k JSON chars"
2710
+ });
2711
+ var SpanAddressSchema = z.object({
1703
2712
  deploymentSlug: z.string().min(1),
1704
2713
  sessionExternalId: z.string().min(1),
1705
2714
  /**
@@ -1710,7 +2719,10 @@ var SpanInputSchema = z.object({
1710
2719
  * worker (logged, batch still processed): spans never land unattributed.
1711
2720
  */
1712
2721
  turnIndex: z.number().int().nonnegative().optional(),
1713
- spanType: z.enum(SPAN_TYPES),
2722
+ spanType: z.enum(SPAN_TYPES)
2723
+ });
2724
+ var SpanInputV1Schema = SpanAddressSchema.extend({
2725
+ contractVersion: z.literal(1).optional(),
1714
2726
  /** Human/otel-style span name (tool name, model call label). */
1715
2727
  name: z.string().optional(),
1716
2728
  /**
@@ -1748,16 +2760,128 @@ var SpanInputSchema = z.object({
1748
2760
  */
1749
2761
  parentSpanId: z.string().min(1).optional()
1750
2762
  });
2763
+ var SpanInputV2Schema = SpanAddressSchema.extend({
2764
+ contractVersion: z.literal(2),
2765
+ /** Stable within a deployment/session across batches and retries. */
2766
+ spanId: z.string().min(1),
2767
+ parentSpanId: z.string().min(1).nullable(),
2768
+ name: z.string().min(1),
2769
+ status: z.enum(SPAN_V2_STATUSES),
2770
+ startedAt: z.string().datetime(),
2771
+ endedAt: z.string().datetime().nullable(),
2772
+ durationMs: z.number().int().nonnegative().nullable(),
2773
+ model: z.string().min(1).nullable(),
2774
+ provider: z.string().min(1).nullable(),
2775
+ tokensInput: z.number().int().nonnegative().nullable(),
2776
+ tokensOutput: z.number().int().nonnegative().nullable(),
2777
+ costUsd: z.number().nonnegative().nullable(),
2778
+ error: z.string().nullable(),
2779
+ input: SpanPayloadSchema,
2780
+ output: SpanPayloadSchema,
2781
+ /** Optional first-class internal timing. An omitted list means the source
2782
+ * did not capture interval telemetry; readers must not infer segments. */
2783
+ intervals: z.array(SpanIntervalSchema).max(128).optional(),
2784
+ attributes: z.record(z.string(), z.unknown()).nullable().refine(
2785
+ (value) => value === null || JSON.stringify(value).length <= 16e3,
2786
+ {
2787
+ message: "attributes exceed 16k JSON chars \u2014 spans are telemetry, not blob storage"
2788
+ }
2789
+ )
2790
+ }).superRefine((span, ctx) => {
2791
+ if (span.status !== "error" && span.error !== null) {
2792
+ ctx.addIssue({
2793
+ code: z.ZodIssueCode.custom,
2794
+ path: ["error"],
2795
+ message: "error detail requires status=error"
2796
+ });
2797
+ }
2798
+ if (span.endedAt !== null && new Date(span.endedAt).getTime() < new Date(span.startedAt).getTime()) {
2799
+ ctx.addIssue({
2800
+ code: z.ZodIssueCode.custom,
2801
+ path: ["endedAt"],
2802
+ message: "endedAt must not precede startedAt"
2803
+ });
2804
+ }
2805
+ const spanStart = new Date(span.startedAt).getTime();
2806
+ const spanEnd = span.endedAt !== null ? new Date(span.endedAt).getTime() : span.durationMs !== null ? spanStart + span.durationMs : null;
2807
+ span.intervals?.forEach((interval, index) => {
2808
+ const intervalStart = new Date(interval.startedAt).getTime();
2809
+ const intervalEnd = new Date(interval.endedAt).getTime();
2810
+ if (intervalStart < spanStart || spanEnd !== null && intervalEnd > spanEnd) {
2811
+ ctx.addIssue({
2812
+ code: z.ZodIssueCode.custom,
2813
+ path: ["intervals", index],
2814
+ message: "interval must stay within the measured span window"
2815
+ });
2816
+ }
2817
+ });
2818
+ });
2819
+ var SpanInputSchema = z.union([SpanInputV2Schema, SpanInputV1Schema]);
1751
2820
  var SpansBatchSchema = z.object({
1752
2821
  /** Spans are self-addressed: a batch may span sessions/deployments. */
1753
2822
  spans: z.array(SpanInputSchema).min(1).max(50),
1754
2823
  alignment: AlignmentProvenanceSchema
2824
+ }).superRefine((batch, ctx) => {
2825
+ const spanIdCounts = /* @__PURE__ */ new Map();
2826
+ const spansById = /* @__PURE__ */ new Map();
2827
+ const parents = /* @__PURE__ */ new Map();
2828
+ for (const span of batch.spans) {
2829
+ if (span.spanId !== void 0) {
2830
+ spanIdCounts.set(span.spanId, (spanIdCounts.get(span.spanId) ?? 0) + 1);
2831
+ spansById.set(span.spanId, span);
2832
+ }
2833
+ if (span.parentSpanId !== void 0 && span.parentSpanId !== null && span.spanId) {
2834
+ parents.set(span.spanId, span.parentSpanId);
2835
+ }
2836
+ }
2837
+ batch.spans.forEach((span, index) => {
2838
+ if (span.contractVersion !== 2) return;
2839
+ if ((spanIdCounts.get(span.spanId) ?? 0) !== 1) {
2840
+ ctx.addIssue({
2841
+ code: z.ZodIssueCode.custom,
2842
+ path: ["spans", index, "spanId"],
2843
+ message: "v2 spanId must be unique within the batch"
2844
+ });
2845
+ }
2846
+ if (span.parentSpanId !== null && (spanIdCounts.get(span.parentSpanId) ?? 0) !== 1) {
2847
+ ctx.addIssue({
2848
+ code: z.ZodIssueCode.custom,
2849
+ path: ["spans", index, "parentSpanId"],
2850
+ message: "v2 parentSpanId must resolve uniquely within the batch"
2851
+ });
2852
+ }
2853
+ const parent = span.parentSpanId === null ? void 0 : spansById.get(span.parentSpanId);
2854
+ if (parent && (parent.deploymentSlug !== span.deploymentSlug || parent.sessionExternalId !== span.sessionExternalId)) {
2855
+ ctx.addIssue({
2856
+ code: z.ZodIssueCode.custom,
2857
+ path: ["spans", index, "parentSpanId"],
2858
+ message: "v2 parentSpanId must belong to the same deployment and session"
2859
+ });
2860
+ }
2861
+ const seen = /* @__PURE__ */ new Set();
2862
+ let cursor = span.spanId;
2863
+ while (cursor !== void 0) {
2864
+ if (seen.has(cursor)) {
2865
+ ctx.addIssue({
2866
+ code: z.ZodIssueCode.custom,
2867
+ path: ["spans", index, "parentSpanId"],
2868
+ message: "v2 parentSpanId graph must not contain a cycle"
2869
+ });
2870
+ break;
2871
+ }
2872
+ seen.add(cursor);
2873
+ cursor = parents.get(cursor);
2874
+ }
2875
+ });
1755
2876
  });
1756
2877
  var DEFINITION_SLUG = /^[a-z][a-z0-9_-]{0,63}$/;
1757
2878
  var DEFINITION_VALUE = z.string().trim().min(1).max(64);
1758
2879
  z.object({
1759
2880
  /** Measurement family the definition belongs to (e.g. 'voice-conformance'). */
1760
- family: z.string().regex(DEFINITION_SLUG, "family must be a lowercase slug (a-z, 0-9, _-)."),
2881
+ family: z.string().regex(
2882
+ DEFINITION_SLUG,
2883
+ "family must be a lowercase slug (a-z, 0-9, _-)."
2884
+ ),
1761
2885
  /** Slug within the family. family+name identifies the definition across versions. */
1762
2886
  name: z.string().regex(DEFINITION_SLUG, "name must be a lowercase slug (a-z, 0-9, _-)."),
1763
2887
  /** The elicitation prompt — the queue row's plain-language question. */
@@ -1798,7 +2922,15 @@ z.object({
1798
2922
  /** Open-vocab kind label. Seeds above; customers may register any string. */
1799
2923
  kind: z.string().min(1),
1800
2924
  /** How was this event detected? Seed values below; customer sources allowed. */
1801
- detectedBy: z.enum(["harness", "sdk_flag", "sdk_rating", "sdk_thumbs", "worker_detector", "webhook", "sdk_custom"]).or(z.string().min(1)),
2925
+ detectedBy: z.enum([
2926
+ "harness",
2927
+ "sdk_flag",
2928
+ "sdk_rating",
2929
+ "sdk_thumbs",
2930
+ "worker_detector",
2931
+ "webhook",
2932
+ "sdk_custom"
2933
+ ]).or(z.string().min(1)),
1802
2934
  /** Optional turn index the event was caused by. Omitted → attaches to session's most recent turn. */
1803
2935
  causingTurnIndex: z.number().int().nonnegative().optional(),
1804
2936
  /** Optional detail payload (customer-defined). */
@@ -1813,6 +2945,7 @@ var DEFAULT_ENVIRONMENT_ALIGNMENT = {
1813
2945
  clock_source: "sdk",
1814
2946
  rule_version: "v1"
1815
2947
  };
2948
+ var SDK_ENVELOPE_VERSION = "sdk-envelope-v1";
1816
2949
  var DEFAULT_SPAN_ALIGNMENT = {
1817
2950
  clock_source: "sdk",
1818
2951
  rule_version: "v1"
@@ -1829,9 +2962,25 @@ function validateOrDrop(schema, input, method) {
1829
2962
  }
1830
2963
  return result.data;
1831
2964
  }
2965
+ var SessionRefSchema = z.object({ externalId: z.string().min(1) });
2966
+ var UserInputSubmitSchema = SessionRefSchema.extend({ text: z.string() });
2967
+ var UserThumbsSchema = SessionRefSchema.extend({
2968
+ thumbs: z.enum(["up", "down"])
2969
+ });
2970
+ var UserRatingSchema = SessionRefSchema.extend({
2971
+ rating: z.number().int().min(1).max(5)
2972
+ });
2973
+ function newTurnId() {
2974
+ const c = globalThis.crypto;
2975
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
2976
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
2977
+ const r = Math.floor(Math.random() * 16);
2978
+ return (ch === "x" ? r : r & 3 | 8).toString(16);
2979
+ });
2980
+ }
1832
2981
  var Probe = class {
1833
2982
  /**
1834
- * Initialize the Probe SDK. Call once at process start. Subsequent calls are
2983
+ * Initialize the SDK. Call once at process start. Subsequent calls are
1835
2984
  * no-ops with a warning; re-init requires a shutdown() first.
1836
2985
  */
1837
2986
  static init(config) {
@@ -1858,19 +3007,28 @@ var Probe = class {
1858
3007
  if (validated.persona?.signaturePhrases) {
1859
3008
  state.signatureMatchers.set(
1860
3009
  validated.persona.slug,
1861
- compileSignaturePhrases(validated.persona.signaturePhrases)
3010
+ compileSignaturePhrases(
3011
+ validated.persona.signaturePhrases
3012
+ )
1862
3013
  );
1863
3014
  }
1864
- registerAllInstrumentations(state, (turn) => this.captureTurn(turn));
3015
+ registerAllInstrumentations(
3016
+ state,
3017
+ (turn, hints) => this.captureWithHints(turn, hints)
3018
+ );
1865
3019
  }
1866
3020
  /**
1867
- * Run a callback inside a session context. Every LLM call made inside `fn`
1868
- * (through any instrumented library: OpenAI, Anthropic, LangChain, Vercel
1869
- * AI SDK, etc.) is automatically tagged with `sessionId` and captured as
1870
- * a turn on that session.
3021
+ * Run a callback inside a session scope. Every LLM call made inside `fn`
3022
+ * through a wrapped OpenAI client or an instrumented library is captured
3023
+ * as a turn on the session `sessionId`.
3024
+ *
3025
+ * Autocapture needs this scope: a call made outside any session scope is
3026
+ * not captured. The first such call in a process prints one warning;
3027
+ * later ones log only with `debug: true`. (Spans that carry
3028
+ * `gen_ai.conversation.id` are the one exception: with no scope, that id
3029
+ * is used as the session id. An explicit scope always wins.)
1871
3030
  *
1872
- * Under the hood, this uses OTel Baggage propagation; the shared span
1873
- * processor reads the session ID from baggage when each LLM span ends.
3031
+ * The scope is carried in OpenTelemetry baggage across awaits.
1874
3032
  */
1875
3033
  static async withSession(sessionId, fn) {
1876
3034
  if (state === null) {
@@ -1915,12 +3073,12 @@ var Probe = class {
1915
3073
  const validated = validateOrDrop(SessionStartSchema, input, "startSession");
1916
3074
  if (validated === null) return;
1917
3075
  const existing = state.sessions.get(validated.externalId);
1918
- const now = Date.now();
3076
+ const now2 = Date.now();
1919
3077
  const session = {
1920
3078
  externalId: validated.externalId,
1921
3079
  externalUserId: validated.externalUserId ?? existing?.externalUserId ?? null,
1922
3080
  turnIndex: existing?.turnIndex ?? 0,
1923
- startedAt: existing?.startedAt ?? now,
3081
+ startedAt: existing?.startedAt ?? now2,
1924
3082
  personaSlug: validated.persona ?? existing?.personaSlug ?? state.persona?.slug ?? null,
1925
3083
  metadata: validated.metadata ?? existing?.metadata ?? null,
1926
3084
  openedVia: validated.openedVia ?? existing?.openedVia ?? null,
@@ -1976,7 +3134,7 @@ var Probe = class {
1976
3134
  }
1977
3135
  /**
1978
3136
  * Compute a stable SHA-256 hex hash of prompt/config text for use as
1979
- * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —
3137
+ * `environmentConfigHash` on Sight.startSession(). Hash is *identity*:
1980
3138
  * pass the human-readable version alongside as `environmentConfigLabel`
1981
3139
  * for the diff table axis (a card keyed by a3f9c2… is unreadable).
1982
3140
  *
@@ -2011,8 +3169,10 @@ var Probe = class {
2011
3169
  */
2012
3170
  static async endSession(externalId) {
2013
3171
  if (state === null) return;
3172
+ const validEnd = typeof externalId === "string" ? validateOrDrop(SessionRefSchema, { externalId }, "endSession") : validateOrDrop(SessionEndSchema, externalId, "endSession");
3173
+ if (validEnd === null) return;
2014
3174
  const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
2015
- const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
3175
+ const endedReason = typeof externalId === "string" ? "natural" : externalId.endedReason ?? "natural";
2016
3176
  const declared = typeof externalId === "string" ? void 0 : externalId.outcome;
2017
3177
  if (declared) {
2018
3178
  await this.emitOutcomeEvent({
@@ -2047,8 +3207,14 @@ var Probe = class {
2047
3207
  }
2048
3208
  if (state === null) return;
2049
3209
  if (endedReason) {
2050
- await state.client.sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason }).catch((err) => {
2051
- console.warn("[sight] sendSessionEnd failed:", err instanceof Error ? err.message : err);
3210
+ await state.client.sendSessionEnd(state.config.deployment, {
3211
+ externalId: externalIdStr,
3212
+ endedReason
3213
+ }).catch((err) => {
3214
+ console.warn(
3215
+ "[sight] sendSessionEnd failed:",
3216
+ err instanceof Error ? err.message : err
3217
+ );
2052
3218
  });
2053
3219
  }
2054
3220
  state.sessions.delete(externalIdStr);
@@ -2060,28 +3226,30 @@ var Probe = class {
2060
3226
  // before startSession or the first LLM call) buffer per externalId and
2061
3227
  // flush into the session when it is created.
2062
3228
  /**
2063
- * User started typing — records the first-keystroke timestamp for
2064
- * probe_user_first_keystroke_ms derivation on captureTurn. Derivable
3229
+ * The person started typing. Records the first-keystroke time, sent as
3230
+ * `userInput.firstKeystrokeMs` with the next captured turn. Derivable
2065
3231
  * only once a previous agent turn exists; a pre-session typing start
2066
3232
  * buffers the pending-input entry without a firstKeystrokeMs value.
2067
3233
  */
2068
3234
  static userInputStart(externalId) {
2069
3235
  if (state === null) return;
3236
+ if (validateOrDrop(SessionRefSchema, { externalId }, "userInputStart") === null) return;
2070
3237
  const session = state.sessions.get(externalId);
2071
3238
  const target = session ?? this.preSessionEntry(externalId);
2072
- const now = Date.now();
2073
- const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0, now - session.lastAgentTurnAt) : void 0;
3239
+ const now2 = Date.now();
3240
+ const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0, now2 - session.lastAgentTurnAt) : void 0;
2074
3241
  target.pendingUserInput = {
2075
3242
  ...target.pendingUserInput ?? { editCount: 0 },
2076
3243
  firstKeystrokeMs: target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs
2077
3244
  };
2078
3245
  }
2079
3246
  /**
2080
- * User pressed backspace / edited — increments edit_count for
2081
- * probe_user_reply_edit_count.
3247
+ * The person pressed backspace or edited. Increments the edit count,
3248
+ * sent as `userInput.editCount` with the next captured turn.
2082
3249
  */
2083
3250
  static userInputEdit(externalId) {
2084
3251
  if (state === null) return;
3252
+ if (validateOrDrop(SessionRefSchema, { externalId }, "userInputEdit") === null) return;
2085
3253
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2086
3254
  target.pendingUserInput = {
2087
3255
  ...target.pendingUserInput ?? { editCount: 0 },
@@ -2089,36 +3257,41 @@ var Probe = class {
2089
3257
  };
2090
3258
  }
2091
3259
  /**
2092
- * User submitted their reply. Records the text (Presidio-scrubbed
2093
- * server-side before landing on probe_user_reply_text) plus the submit
2094
- * timestamp, which captureTurn uses to derive probe_agent_reflect_ms
2095
- * (submit → next agent turn) and probe_transition_time_ms (previous
2096
- * agent turn → submit).
3260
+ * The person submitted their message. Records the text (scrubbed of
3261
+ * personal data server-side before it is stored) plus the submit
3262
+ * timestamp. The text and timings are sent with the NEXT captured turn:
3263
+ * a turn's person text is the message that prompted its reply.
2097
3264
  */
2098
3265
  static userInputSubmit(externalId, text) {
2099
3266
  if (state === null) return;
3267
+ if (validateOrDrop(UserInputSubmitSchema, { externalId, text }, "userInputSubmit") === null)
3268
+ return;
2100
3269
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2101
- const now = Date.now();
3270
+ const now2 = Date.now();
2102
3271
  target.pendingUserInput = {
2103
3272
  ...target.pendingUserInput ?? { editCount: 0 },
2104
3273
  text,
2105
- submittedAt: now
3274
+ submittedAt: now2
2106
3275
  };
2107
- target.lastUserSubmitAt = now;
3276
+ target.lastUserSubmitAt = now2;
2108
3277
  }
2109
3278
  /** Attach a thumbs-up/down to the current turn. */
2110
3279
  static userThumbs(externalId, thumbs) {
2111
3280
  if (state === null) return;
3281
+ if (validateOrDrop(UserThumbsSchema, { externalId, thumbs }, "userThumbs") === null) return;
2112
3282
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2113
3283
  target.pendingUserOutcome = {
2114
3284
  ...target.pendingUserOutcome ?? {},
2115
3285
  thumbs
2116
3286
  };
2117
3287
  }
2118
- /** Attach an explicit 1-5 rating to the current turn. */
3288
+ /**
3289
+ * Attach an explicit rating to the current turn: an integer from 1 to 5.
3290
+ * Any other value logs one warning line and is dropped.
3291
+ */
2119
3292
  static userRating(externalId, rating) {
2120
3293
  if (state === null) return;
2121
- if (rating < 1 || rating > 5 || !Number.isInteger(rating)) return;
3294
+ if (validateOrDrop(UserRatingSchema, { externalId, rating }, "userRating") === null) return;
2122
3295
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2123
3296
  target.pendingUserOutcome = {
2124
3297
  ...target.pendingUserOutcome ?? {},
@@ -2152,27 +3325,56 @@ var Probe = class {
2152
3325
  state.outcomeHook = hook;
2153
3326
  }
2154
3327
  /**
2155
- * Manually capture a turn. Instrumentation adapters call this internally;
2156
- * exposed for advanced customers who want to bypass autocapture.
3328
+ * Manually capture a turn. For callers that do not use autocapture.
3329
+ *
3330
+ * - `deploymentSlug` may be omitted: the `deployment` given to `init` is
3331
+ * used. An explicit value wins.
3332
+ * - Every turn is sent with a `turnId` (a fresh UUID unless you supply
3333
+ * one). A retried send carries the same `turnId`.
3334
+ * - The turn is validated before it is sent. An invalid turn logs one
3335
+ * warning line naming the first invalid field and is dropped; nothing
3336
+ * is sent.
2157
3337
  *
2158
3338
  * Persona resolution order for the outgoing turn payload:
2159
3339
  * 1. turn.personaSlug (turn-level override)
2160
- * 2. sessions[externalId].personaSlug (from startSession)
2161
- * 3. state.persona.slug (init-level default)
3340
+ * 2. the session's persona (from startSession)
3341
+ * 3. the init-level default
2162
3342
  *
2163
- * Signature-phrase matching runs at the SDK edge when the resolved persona
3343
+ * Signature-phrase matching runs in the SDK when the resolved persona
2164
3344
  * has signature phrases registered. The matched slug list is attached to
2165
3345
  * `turn.signaturePhraseMatches` before send.
2166
3346
  */
2167
3347
  static async captureTurn(turn) {
3348
+ return this.captureWithHints(turn);
3349
+ }
3350
+ /**
3351
+ * The one capture path. Manual captureTurn calls and autocapture both
3352
+ * land here; autocapture also passes what it observed on the request
3353
+ * (`hints`), applied below under the explicit-input-wins rule.
3354
+ */
3355
+ static async captureWithHints(input, hints) {
2168
3356
  if (state === null) {
2169
3357
  return;
2170
3358
  }
2171
- if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
3359
+ if (input === null || typeof input !== "object") {
3360
+ validateOrDrop(TurnInputSchema, input, "captureTurn");
2172
3361
  return;
2173
3362
  }
2174
- if (turn.payload === void 0 || turn.payload === null) {
2175
- turn = { ...turn, payload: {} };
3363
+ const turn = {
3364
+ ...input,
3365
+ deploymentSlug: input.deploymentSlug ?? state.config.deployment,
3366
+ turnId: input.turnId ?? newTurnId(),
3367
+ payload: input.payload === void 0 || input.payload === null ? {} : input.payload
3368
+ };
3369
+ const payloadPropensity = typeof turn.payload === "object" ? turn.payload.propensity : void 0;
3370
+ const checked = validateOrDrop(
3371
+ TurnInputSchema,
3372
+ { ...turn, propensity: turn.propensity ?? payloadPropensity },
3373
+ "captureTurn"
3374
+ );
3375
+ if (checked === null) return;
3376
+ if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
3377
+ return;
2176
3378
  }
2177
3379
  const propensity = turn.propensity ?? turn.payload.propensity;
2178
3380
  let validPropensity = propensity;
@@ -2240,6 +3442,9 @@ var Probe = class {
2240
3442
  if (session.pendingUserOutcome && !userOutcome) {
2241
3443
  userOutcome = session.pendingUserOutcome;
2242
3444
  }
3445
+ if (hints?.observedUserText && !userInput?.text) {
3446
+ userInput = { ...userInput ?? {}, text: hints.observedUserText };
3447
+ }
2243
3448
  if (!interactivity && session.lastUserSubmitAt) {
2244
3449
  interactivity = {
2245
3450
  agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt)
@@ -2264,9 +3469,10 @@ var Probe = class {
2264
3469
  session.lastAgentTurnAt = Date.now();
2265
3470
  await state.client.sendTurn({
2266
3471
  ...turn,
3472
+ envelopeVersion: SDK_ENVELOPE_VERSION,
2267
3473
  personaSlug: resolvedPersona,
2268
3474
  signaturePhraseMatches: signatureMatches,
2269
- // User identity from the local session entry (Probe.startSession).
3475
+ // User identity from the local session entry (Sight.startSession).
2270
3476
  // The worker persists it on sessions.external_user_id; never the
2271
3477
  // session key. Turn-level override wins for advanced callers.
2272
3478
  externalUserId: turn.externalUserId ?? session.externalUserId ?? void 0,
@@ -2282,7 +3488,7 @@ var Probe = class {
2282
3488
  // columns (e2e audit 2026-07-13).
2283
3489
  propensity: validPropensity,
2284
3490
  // Forward RLDS provenance from the local session entry (populated
2285
- // by Probe.startSession). Worker persists at first-turn session
3491
+ // by Sight.startSession). Worker persists at first-turn session
2286
3492
  // create; nulls stay null.
2287
3493
  agentId: session.agentId ?? void 0,
2288
3494
  experimentId: session.experimentId ?? void 0,
@@ -2291,8 +3497,8 @@ var Probe = class {
2291
3497
  });
2292
3498
  }
2293
3499
  /**
2294
- * Emit a custom outcome event on a session. Populates probe_outcome_events
2295
- * with the customer-supplied `kind` string. Use for
3500
+ * Emit a custom outcome event on a session, stored with the `kind`
3501
+ * string you supply. Use for
2296
3502
  * customer-defined kinds like "purchase_complete", "handoff_to_human",
2297
3503
  * "character_break_severe". Universal seed kinds (break, escalation,
2298
3504
  * resolution, thumbs_*, rating_*) are also emitted by worker-side
@@ -2304,7 +3510,11 @@ var Probe = class {
2304
3510
  console.warn("[sight] emitOutcomeEvent called before init");
2305
3511
  return;
2306
3512
  }
2307
- const validated = validateOrDrop(OutcomeEventEmitSchema, input, "emitOutcomeEvent");
3513
+ const validated = validateOrDrop(
3514
+ OutcomeEventEmitSchema,
3515
+ input,
3516
+ "emitOutcomeEvent"
3517
+ );
2308
3518
  if (validated === null) return;
2309
3519
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
2310
3520
  }
@@ -2326,10 +3536,21 @@ var Probe = class {
2326
3536
  console.warn("[sight] captureEnvironmentEvent called before init");
2327
3537
  return;
2328
3538
  }
2329
- const validated = validateOrDrop(EnvironmentEventInputSchema, event, "captureEnvironmentEvent");
3539
+ const validated = validateOrDrop(
3540
+ EnvironmentEventInputSchema,
3541
+ event,
3542
+ "captureEnvironmentEvent"
3543
+ );
2330
3544
  if (validated === null) return;
2331
- const align = alignment ? validateOrDrop(AlignmentProvenanceSchema, alignment, "captureEnvironmentEvent") ?? DEFAULT_ENVIRONMENT_ALIGNMENT : DEFAULT_ENVIRONMENT_ALIGNMENT;
2332
- await state.client.sendEnvironmentEvents({ events: [validated], alignment: align });
3545
+ const align = alignment ? validateOrDrop(
3546
+ AlignmentProvenanceSchema,
3547
+ alignment,
3548
+ "captureEnvironmentEvent"
3549
+ ) ?? DEFAULT_ENVIRONMENT_ALIGNMENT : DEFAULT_ENVIRONMENT_ALIGNMENT;
3550
+ await state.client.sendEnvironmentEvents({
3551
+ events: [validated],
3552
+ alignment: align
3553
+ });
2333
3554
  }
2334
3555
  /**
2335
3556
  * Capture a batch of environment events with explicit alignment provenance
@@ -2343,7 +3564,11 @@ var Probe = class {
2343
3564
  console.warn("[sight] captureEnvironmentEvents called before init");
2344
3565
  return;
2345
3566
  }
2346
- const batch = validateOrDrop(EnvironmentEventsBatchSchema, { events, alignment }, "captureEnvironmentEvents");
3567
+ const batch = validateOrDrop(
3568
+ EnvironmentEventsBatchSchema,
3569
+ { events, alignment },
3570
+ "captureEnvironmentEvents"
3571
+ );
2347
3572
  if (batch === null) return;
2348
3573
  await state.client.sendEnvironmentEvents(batch);
2349
3574
  }
@@ -2385,7 +3610,11 @@ var Probe = class {
2385
3610
  console.warn("[sight] captureSpans called before init");
2386
3611
  return;
2387
3612
  }
2388
- const batch = validateOrDrop(SpansBatchSchema, { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT }, "captureSpans");
3613
+ const batch = validateOrDrop(
3614
+ SpansBatchSchema,
3615
+ { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT },
3616
+ "captureSpans"
3617
+ );
2389
3618
  if (batch === null) return;
2390
3619
  await state.client.sendSpans(batch);
2391
3620
  }
@@ -2402,7 +3631,11 @@ var Probe = class {
2402
3631
  console.warn("[sight] flagPersonaBreak called before init");
2403
3632
  return;
2404
3633
  }
2405
- const validated = validateOrDrop(FlagPersonaBreakSchema, input, "flagPersonaBreak");
3634
+ const validated = validateOrDrop(
3635
+ FlagPersonaBreakSchema,
3636
+ input,
3637
+ "flagPersonaBreak"
3638
+ );
2406
3639
  if (validated === null) return;
2407
3640
  await state.client.sendFlag(state.config.deployment, validated);
2408
3641
  }
@@ -2456,6 +3689,6 @@ var Probe = class {
2456
3689
  }
2457
3690
  };
2458
3691
 
2459
- export { Probe, Probe as Sight, wrapOpenAI };
3692
+ 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 };
2460
3693
  //# sourceMappingURL=index.js.map
2461
3694
  //# sourceMappingURL=index.js.map