@cultured_computer/sight 0.7.1 → 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,7 +60,7 @@ 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
@@ -78,7 +81,7 @@ var IngestClient = class {
78
81
  }
79
82
  /**
80
83
  * Send a turn to the ingest API. Fire-and-log: errors are logged but never
81
- * thrown. The customer's LLM path never blocks on the Probe.
84
+ * thrown. The customer's LLM path never blocks on capture.
82
85
  */
83
86
  async sendTurn(turn) {
84
87
  try {
@@ -155,7 +158,7 @@ var IngestClient = class {
155
158
  }
156
159
  /**
157
160
  * Send a session-end event to the ingest API. Records why a session ended
158
- * on the sessions.probe_session_ended_reason column. Fire-and-log.
161
+ * on the session. Fire-and-log.
159
162
  */
160
163
  async sendSessionEnd(deploymentSlug, end) {
161
164
  try {
@@ -358,7 +361,7 @@ var OutcomeHookSchema = z.object({
358
361
  type: z.enum(["numeric", "categorical", "boolean", "duration"]),
359
362
  /**
360
363
  * Callback that resolves the outcome for a completed session. Invoked by
361
- * Probe.endSession() with the session's externalId; a non-null result
364
+ * Sight.endSession() with the session's externalId; a non-null result
362
365
  * lands as an outcome event on the session. Not invoked for sessions
363
366
  * swept server-side (no explicit endSession) — use emitOutcomeEvent()
364
367
  * for outcomes that become known out of band.
@@ -366,11 +369,12 @@ var OutcomeHookSchema = z.object({
366
369
  resolve: z.custom()
367
370
  });
368
371
  var ProbeConfigSchema = z.object({
369
- /** Unkey ingest key. Required. */
372
+ /** The project's API key (an ingest key from the dashboard). Required. */
370
373
  apiKey: z.string().min(1),
371
- /** Deployment slug registered in the Probe backend. Required. */
374
+ /** Deployment slug: the configuration this traffic belongs to. Required. */
372
375
  deployment: z.string().min(1),
373
- /** Ingest endpoint. Defaults to the production ingest service. */
376
+ /** Ingest endpoint. Defaults to the production ingest service,
377
+ `https://fieldwork-ingest.fly.dev`. */
374
378
  endpoint: z.string().url().default("https://fieldwork-ingest.fly.dev"),
375
379
  /**
376
380
  * Dashboard base URL used by the one-time first-capture announcement
@@ -419,14 +423,14 @@ var SessionStartSchema = z.object({
419
423
  */
420
424
  openedVia: z.enum(["link", "notification", "resume", "direct", "share"]).optional(),
421
425
  /**
422
- * Environmental context — browser / device / locale / tz (P2). Customer-
423
- * 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.
424
428
  */
425
429
  clientContext: z.record(z.string(), z.unknown()).optional(),
426
430
  /**
427
431
  * Optional customer metadata attached to the session. Forwarded with the
428
432
  * first captured turn merged into `clientContext` under the `metadata`
429
- * key, so it lands on sessions.probe_session_client_context.
433
+ * key, so it is stored with the session.
430
434
  */
431
435
  metadata: z.record(z.string(), z.unknown()).optional(),
432
436
  /**
@@ -442,7 +446,7 @@ var SessionStartSchema = z.object({
442
446
  environmentConfigHash: z.string().optional(),
443
447
  environmentConfigLabel: z.string().optional()
444
448
  });
445
- z.object({
449
+ var SessionEndSchema = z.object({
446
450
  externalId: z.string().min(1),
447
451
  endedReason: z.enum([
448
452
  "natural",
@@ -571,8 +575,53 @@ function getCurrentSessionId() {
571
575
  return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;
572
576
  }
573
577
 
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;
588
+ }
589
+ if (debug) {
590
+ console.warn(
591
+ `[sight] call not captured (${source}): no session scope; wrap it in Sight.withSession(id, fn).`
592
+ );
593
+ }
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
+
574
622
  // src/instrumentation/otel-processor.ts
575
623
  var MAX_DEDUP_SPANS = 1e4;
624
+ var MAX_TOOL_PARENTS = 1e3;
576
625
  function attr(attrs, key) {
577
626
  return attrs[key];
578
627
  }
@@ -585,64 +634,261 @@ function asNumber(v) {
585
634
  function asStringArray(v) {
586
635
  return Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
587
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
+ }
588
662
  function isLLMCall(attrs) {
589
663
  const op = asString(attrs["gen_ai.operation.name"]);
590
- if (op === "chat" || op === "text_completion" || op === "embeddings") {
591
- return true;
664
+ if (op !== void 0) {
665
+ return CAPTURED_OPERATIONS.has(op);
592
666
  }
593
- const traceloopKind = asString(attrs["traceloop.span.kind"]);
594
- if (traceloopKind === "agent") return true;
595
- return false;
667
+ if (isAiSdkModelCall(attrs)) return true;
668
+ return asString(attrs["traceloop.span.kind"]) === "agent";
596
669
  }
597
670
  function isVercelAgentRollup(spanName, attrs) {
598
671
  return spanName.startsWith("invoke_agent ") && attrs["ai.telemetry.functionId"] !== void 0;
599
672
  }
600
673
  function taggedProvider(attrs) {
601
- 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");
602
675
  const model = asString(attrs["gen_ai.request.model"]);
603
676
  if (model?.toLowerCase().startsWith("mercury")) {
604
677
  return "inception";
605
678
  }
606
679
  return rawProvider;
607
680
  }
608
- 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 = []) {
609
817
  const a = span.attributes;
610
818
  const start = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
611
819
  const end = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
612
820
  const latencyMs = Math.max(0, Math.round(end - start));
613
- const responseText = asString(attr(a, "ai.response.text")) ?? asString(attr(a, "gen_ai.output.messages"));
614
- const toolCallNames = asStringArray(attr(a, "gen_ai.response.tool_names"));
615
- const toolCallsCount = asNumber(attr(a, "gen_ai.response.tool_calls_count")) ?? toolCallNames?.length;
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"));
616
827
  const finishReasons = asStringArray(attr(a, "gen_ai.response.finish_reasons"));
617
- 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");
618
830
  const error = span.status.code === 2 ? span.status.message ?? "error" : void 0;
619
831
  return {
620
- // Plumbing (probe_* namespace lands on canonical turns columns per PROBE.md §2).
621
- probe_tokens_input: asNumber(attr(a, "gen_ai.usage.input_tokens")),
622
- probe_tokens_output: asNumber(attr(a, "gen_ai.usage.output_tokens")),
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
+ ),
623
848
  probe_latency_ms: latencyMs,
624
- probe_model: asString(attr(a, "gen_ai.response.model") ?? attr(a, "gen_ai.request.model")),
625
- probe_provider: taggedProvider(a),
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")),
626
863
  probe_tool_calls: toolCallsCount,
627
864
  probe_tool_names: toolCallNames,
628
865
  probe_error: error,
629
866
  probe_finish_reason: finishReason,
630
867
  // Response text so the SDK edge signature-phrase matcher has something to
631
- // match against; the server-side redactor scrubs PII on the Tier 1 →
632
- // Tier 2 boundary.
868
+ // match against; personal data is scrubbed server-side before storage.
633
869
  response: responseText ? { text: responseText } : void 0,
634
- // Anthropic cache tokens (per research report), promoted so the customer
635
- // can see cache-hit-rate in the dashboard without re-parsing raw messages.
636
- probe_cache_read_input_tokens: asNumber(attr(a, "gen_ai.usage.cache_read_input_tokens")),
637
- probe_cache_creation_input_tokens: asNumber(
638
- attr(a, "gen_ai.usage.cache_creation_input_tokens")
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"
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"
639
884
  ),
885
+ probe_cache_tokens_in_input: cacheTokensInInput(span),
640
886
  // Debug metadata (kept in payload, not projected to canonical columns).
641
887
  _otel: {
642
888
  spanName: span.name,
643
889
  traceId: span.spanContext().traceId,
644
890
  spanId: span.spanContext().spanId,
645
- operationName: asString(attr(a, "gen_ai.operation.name")),
891
+ operationName: firstString(a, "gen_ai.operation.name", "ai.operationId"),
646
892
  traceloopKind: asString(attr(a, "traceloop.span.kind"))
647
893
  }
648
894
  };
@@ -765,6 +1011,38 @@ var ProbeSpanProcessor = class {
765
1011
  state;
766
1012
  captureFn;
767
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
+ }
768
1046
  /**
769
1047
  * Re-point the processor at a new Probe state (or null after shutdown).
770
1048
  * A registered span processor cannot be removed from a provider, so
@@ -773,11 +1051,23 @@ var ProbeSpanProcessor = class {
773
1051
  * stamping the old deployment slug (production-safety audit R1).
774
1052
  */
775
1053
  rebind(state2, captureFn) {
776
- if (this.state !== state2) this.seenSpans.clear();
1054
+ if (this.state !== state2) {
1055
+ this.seenSpans.clear();
1056
+ this.toolChildren.clear();
1057
+ }
777
1058
  this.state = state2;
778
1059
  if (captureFn) this.captureFn = captureFn;
779
1060
  }
780
- 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
+ }
781
1071
  }
782
1072
  onEnd(span) {
783
1073
  try {
@@ -785,54 +1075,96 @@ var ProbeSpanProcessor = class {
785
1075
  const state2 = this.state;
786
1076
  const a = span.attributes;
787
1077
  if (isVercelAgentRollup(span.name, a)) return;
788
- if (!isLLMCall(a)) return;
789
- const sessionId = getCurrentSessionId();
790
- if (!sessionId) {
791
- if (state2.config.debug) {
792
- console.warn(
793
- `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`
794
- );
795
- }
1078
+ if (asString(a["gen_ai.operation.name"]) === "execute_tool") {
1079
+ this.noteToolSpan(span, a);
796
1080
  return;
797
1081
  }
798
- const { traceId, spanId } = span.spanContext();
799
- const identity = JSON.stringify([state2.config.deployment, sessionId, traceId, spanId]);
800
- if (this.seenSpans.has(identity)) return;
801
- this.seenSpans.add(identity);
802
- if (this.seenSpans.size > MAX_DEDUP_SPANS) {
803
- this.seenSpans.delete(this.seenSpans.values().next().value);
1082
+ if (!isLLMCall(a)) return;
1083
+ if (this.insideAiCall.has(span)) {
1084
+ this.takeToolChildren(span);
1085
+ return;
804
1086
  }
805
- const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
806
- state2,
807
- sessionId
1087
+ const sessionId = getCurrentSessionId() || firstString(
1088
+ a,
1089
+ "gen_ai.conversation.id",
1090
+ "ai.telemetry.metadata.sightSessionId",
1091
+ "ai.telemetry.metadata.sessionId"
808
1092
  );
809
- const captured = {
810
- deploymentSlug: state2.config.deployment,
811
- sessionExternalId,
812
- turnIndex,
813
- personaSlug: personaSlug ?? void 0,
814
- payload: buildPayload(span)
815
- };
816
- (async () => {
817
- await maybeAutoStampEnvironmentConfig(session, a);
818
- await this.captureFn(captured);
819
- })().catch((err) => {
820
- if (state2.config.debug) {
821
- console.error(
822
- `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
823
- );
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;
824
1098
  }
825
- });
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);
826
1120
  } catch (err) {
827
1121
  if (this.state?.config.debug) {
828
1122
  console.error(
829
- `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`
1123
+ `[sight] span processor error: ${err instanceof Error ? err.message : err}`
830
1124
  );
831
1125
  }
832
1126
  }
833
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
+ }
834
1165
  shutdown() {
835
1166
  this.seenSpans.clear();
1167
+ this.toolChildren.clear();
836
1168
  return Promise.resolve();
837
1169
  }
838
1170
  forceFlush() {
@@ -843,6 +1175,10 @@ var ProbeSpanProcessor = class {
843
1175
  // src/instrumentation/wrap-openai.ts
844
1176
  var bound = null;
845
1177
  var warnedUnbound = false;
1178
+ var wrappedClientSeen = false;
1179
+ function hasWrappedClient() {
1180
+ return wrappedClientSeen;
1181
+ }
846
1182
  function bindWrapOpenAI(state2, captureFn) {
847
1183
  bound = { state: state2, captureFn };
848
1184
  }
@@ -891,8 +1227,33 @@ function systemTextFromParams(params) {
891
1227
  }
892
1228
  return void 0;
893
1229
  }
894
- function providerFor(model) {
895
- 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;
896
1257
  }
897
1258
  function payloadFromChatResponse(r, requestModel) {
898
1259
  const choice = Array.isArray(r["choices"]) ? asRecord(r["choices"][0]) : void 0;
@@ -908,7 +1269,8 @@ function payloadFromChatResponse(r, requestModel) {
908
1269
  tokensOutput: asNumber2(usage?.["completion_tokens"]),
909
1270
  cachedTokens: asNumber2(promptDetails?.["cached_tokens"]),
910
1271
  finishReason: asString2(choice?.["finish_reason"]),
911
- toolNames
1272
+ toolNames,
1273
+ costUsd: costFromUsage(usage)
912
1274
  };
913
1275
  }
914
1276
  function payloadFromResponsesResponse(r, requestModel) {
@@ -944,23 +1306,31 @@ function payloadFromResponsesResponse(r, requestModel) {
944
1306
  tokensOutput: asNumber2(usage?.["output_tokens"]),
945
1307
  cachedTokens: asNumber2(inputDetails?.["cached_tokens"]),
946
1308
  finishReason: asString2(r["status"]),
947
- toolNames: toolNames.length > 0 ? toolNames : void 0
1309
+ toolNames: toolNames.length > 0 ? toolNames : void 0,
1310
+ costUsd: costFromUsage(usage)
948
1311
  };
949
1312
  }
950
- function buildTurnPayload(x, latencyMs, api) {
1313
+ function buildTurnPayload(x, call) {
951
1314
  return {
952
1315
  probe_tokens_input: x.tokensInput,
953
1316
  probe_tokens_output: x.tokensOutput,
954
- probe_latency_ms: latencyMs,
1317
+ probe_latency_ms: call.latencyMs,
1318
+ probe_first_token_ms: call.firstTokenMs,
1319
+ probe_cost_usd: x.costUsd,
955
1320
  probe_model: x.model,
956
- 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),
957
1325
  probe_tool_calls: x.toolNames?.length,
958
1326
  probe_tool_names: x.toolNames,
959
1327
  probe_error: void 0,
960
1328
  probe_finish_reason: x.finishReason,
961
1329
  response: x.text ? { text: x.text } : void 0,
962
1330
  probe_cache_read_input_tokens: x.cachedTokens,
963
- _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" }
964
1334
  };
965
1335
  }
966
1336
  function emit(params, payload) {
@@ -968,7 +1338,7 @@ function emit(params, payload) {
968
1338
  if (!warnedUnbound) {
969
1339
  warnedUnbound = true;
970
1340
  console.warn(
971
- "[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."
972
1342
  );
973
1343
  }
974
1344
  return;
@@ -976,11 +1346,7 @@ function emit(params, payload) {
976
1346
  const { state: state2, captureFn } = bound;
977
1347
  const sessionId = getCurrentSessionId();
978
1348
  if (!sessionId) {
979
- if (state2.config.debug) {
980
- console.warn(
981
- "[sight] wrapOpenAI: call with no session context; skipped (wrap calls in Probe.withSession())."
982
- );
983
- }
1349
+ reportNoSessionSkip("wrapOpenAI", state2.config.debug);
984
1350
  return;
985
1351
  }
986
1352
  const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
@@ -1045,80 +1411,143 @@ function teeStream(stream, onChunk, onDone) {
1045
1411
  }
1046
1412
  });
1047
1413
  }
1414
+ function nonEmpty(v) {
1415
+ return typeof v === "string" && v.length > 0;
1416
+ }
1048
1417
  function chatStreamAccumulator(requestModel) {
1049
1418
  const texts = [];
1419
+ const toolNameParts = /* @__PURE__ */ new Map();
1050
1420
  let model = requestModel;
1051
1421
  let finishReason;
1052
1422
  let tokensInput;
1053
1423
  let tokensOutput;
1054
1424
  let cachedTokens;
1425
+ let costUsd;
1055
1426
  return {
1056
1427
  onChunk(chunk) {
1057
1428
  const c = asRecord(chunk);
1058
- if (!c) return;
1429
+ if (!c) return false;
1059
1430
  model = asString2(c["model"]) ?? model;
1060
1431
  const choice = Array.isArray(c["choices"]) ? asRecord(c["choices"][0]) : void 0;
1061
1432
  const delta = asRecord(choice?.["delta"]);
1433
+ let content = false;
1062
1434
  const t = asString2(delta?.["content"]);
1063
- 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
+ }
1064
1451
  finishReason = asString2(choice?.["finish_reason"]) ?? finishReason;
1065
1452
  const usage = asRecord(c["usage"]);
1066
1453
  if (usage) {
1067
1454
  tokensInput = asNumber2(usage["prompt_tokens"]) ?? tokensInput;
1068
1455
  tokensOutput = asNumber2(usage["completion_tokens"]) ?? tokensOutput;
1069
1456
  cachedTokens = asNumber2(asRecord(usage["prompt_tokens_details"])?.["cached_tokens"]) ?? cachedTokens;
1457
+ costUsd = costFromUsage(usage) ?? costUsd;
1070
1458
  }
1459
+ return content;
1071
1460
  },
1072
- result: () => ({
1073
- model,
1074
- text: texts.length > 0 ? texts.join("") : void 0,
1075
- tokensInput,
1076
- tokensOutput,
1077
- cachedTokens,
1078
- finishReason,
1079
- toolNames: void 0
1080
- })
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
+ }
1081
1474
  };
1082
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
+ ]);
1083
1481
  function responsesStreamAccumulator(requestModel) {
1084
1482
  const texts = [];
1483
+ const toolNameByIndex = /* @__PURE__ */ new Map();
1085
1484
  let final = null;
1086
1485
  return {
1087
1486
  onChunk(chunk) {
1088
1487
  const c = asRecord(chunk);
1089
- if (!c) return;
1090
- 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") {
1091
1492
  const t = asString2(c["delta"]);
1092
1493
  if (t) texts.push(t);
1093
1494
  }
1094
- 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") {
1095
1507
  const response = asRecord(c["response"]);
1096
1508
  if (response) final = payloadFromResponsesResponse(response, requestModel);
1097
1509
  }
1510
+ return content;
1098
1511
  },
1099
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;
1100
1515
  if (final) {
1101
- 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
+ };
1102
1521
  }
1103
1522
  return {
1104
1523
  model: requestModel,
1105
- text: texts.length > 0 ? texts.join("") : void 0,
1524
+ text: streamedText,
1106
1525
  tokensInput: void 0,
1107
1526
  tokensOutput: void 0,
1108
1527
  cachedTokens: void 0,
1109
1528
  finishReason: void 0,
1110
- toolNames: void 0
1529
+ toolNames: streamedNames.length > 0 ? streamedNames : void 0,
1530
+ costUsd: void 0
1111
1531
  };
1112
1532
  }
1113
1533
  };
1114
1534
  }
1115
- function wrapCreate(target, api, makeAccumulator, extractResponse) {
1535
+ function wrapCreate(client, target, api, makeAccumulator, extractResponse) {
1116
1536
  const original = target["create"];
1117
1537
  if (typeof original !== "function") return;
1118
1538
  target["create"] = function(...args) {
1539
+ if (isInsideAiModelCall()) return original.apply(this, args);
1119
1540
  const params = asRecord(args[0]);
1120
1541
  const requestModel = asString2(params?.["model"]);
1121
- 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
+ });
1122
1551
  const result = original.apply(this, args);
1123
1552
  if (!result || typeof result.then !== "function") return result;
1124
1553
  return result.then(
@@ -1127,13 +1556,23 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1127
1556
  const isStream = resolved !== null && typeof resolved === "object" && Symbol.asyncIterator in resolved;
1128
1557
  if (isStream) {
1129
1558
  const acc = makeAccumulator(requestModel);
1130
- return teeStream(resolved, acc.onChunk, () => {
1131
- emit(params, buildTurnPayload(acc.result(), Date.now() - startedAt, api));
1132
- });
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
+ );
1133
1572
  }
1134
1573
  const r = asRecord(resolved);
1135
1574
  if (r) {
1136
- emit(params, buildTurnPayload(extractResponse(r, requestModel), Date.now() - startedAt, api));
1575
+ emit(params, buildTurnPayload(extractResponse(r, requestModel), facts()));
1137
1576
  }
1138
1577
  return resolved;
1139
1578
  } catch {
@@ -1149,9 +1588,10 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1149
1588
  tokensOutput: void 0,
1150
1589
  cachedTokens: void 0,
1151
1590
  finishReason: void 0,
1152
- toolNames: void 0
1591
+ toolNames: void 0,
1592
+ costUsd: void 0
1153
1593
  };
1154
- const payload = buildTurnPayload(x, Date.now() - startedAt, api);
1594
+ const payload = buildTurnPayload(x, facts());
1155
1595
  payload.probe_error = err instanceof Error ? err.message : String(err);
1156
1596
  emit(params, payload);
1157
1597
  } catch {
@@ -1162,19 +1602,465 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1162
1602
  };
1163
1603
  }
1164
1604
  function wrapOpenAI(client) {
1605
+ wrappedClientSeen = true;
1165
1606
  const c = client;
1166
1607
  if (c[WRAPPED]) return client;
1167
1608
  c[WRAPPED] = true;
1168
1609
  const completions = asRecord(asRecord(c["chat"])?.["completions"]);
1169
1610
  if (completions) {
1170
- wrapCreate(completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
1611
+ wrapCreate(c, completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
1171
1612
  }
1172
1613
  const responses = asRecord(c["responses"]);
1173
1614
  if (responses) {
1174
- wrapCreate(responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
1615
+ wrapCreate(c, responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
1175
1616
  }
1176
1617
  return client;
1177
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
+ }
1178
2064
 
1179
2065
  // src/instrumentation/setup.ts
1180
2066
  var installedProcessor = null;
@@ -1199,13 +2085,14 @@ function setupOtelProvider(state2, captureFn) {
1199
2085
  function detachOtelState() {
1200
2086
  installedProcessor?.rebind(null);
1201
2087
  unbindWrapOpenAI();
2088
+ unbindVercelAI();
1202
2089
  }
1203
2090
 
1204
2091
  // src/instrumentation/openai.ts
1205
- var registered = false;
2092
+ var registered2 = false;
1206
2093
  var instrumentation = null;
1207
2094
  async function registerOpenAI(state2) {
1208
- if (registered) return;
2095
+ if (registered2) return;
1209
2096
  try {
1210
2097
  const mod = await import('@traceloop/instrumentation-openai');
1211
2098
  instrumentation = new mod.OpenAIInstrumentation({
@@ -1213,18 +2100,18 @@ async function registerOpenAI(state2) {
1213
2100
  exceptionLogger: (err) => {
1214
2101
  if (state2.config.debug) {
1215
2102
  console.error(
1216
- `[probe/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`
2103
+ `[sight/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`
1217
2104
  );
1218
2105
  }
1219
2106
  }
1220
2107
  });
1221
2108
  instrumentation.enable();
1222
- registered = true;
2109
+ registered2 = true;
1223
2110
  void verifyPatchAttached();
1224
2111
  } catch (err) {
1225
2112
  if (state2.config.debug) {
1226
2113
  const msg = err instanceof Error ? err.message : String(err);
1227
- console.warn(`[probe/openai] instrumentation not enabled (${msg}); library not installed?`);
2114
+ console.warn(`[sight/openai] instrumentation not enabled (${msg}); library not installed?`);
1228
2115
  }
1229
2116
  }
1230
2117
  }
@@ -1234,94 +2121,85 @@ function isPatchDetached(mod) {
1234
2121
  if (typeof create !== "function") return true;
1235
2122
  return create.__wrapped !== true;
1236
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
+ }
1237
2130
  async function verifyPatchAttached() {
1238
2131
  try {
1239
2132
  const mod = await import('openai');
1240
- if (!isPatchDetached(mod)) return;
1241
- const version = mod?.default?.VERSION ?? mod?.VERSION;
1242
- console.warn(
1243
- `[sight] OpenAI autocapture via module patching did not attach` + (version ? ` (openai v${version})` : "") + `. This happens on openai >=5, under ESM, or when 'openai' loads before init. Wrap your client instead: import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()). Until then, no turns are captured from this client.`
1244
- );
2133
+ const line = patchWarning(mod, hasWrappedClient());
2134
+ if (line !== null) console.warn(line);
1245
2135
  } catch {
1246
2136
  }
1247
2137
  }
1248
2138
 
1249
2139
  // src/instrumentation/anthropic.ts
1250
- var registered2 = false;
2140
+ var registered3 = false;
1251
2141
  var instrumentation2 = null;
1252
2142
  async function registerAnthropic(state2) {
1253
- if (registered2) return;
2143
+ if (registered3) return;
1254
2144
  try {
1255
2145
  const mod = await import('@traceloop/instrumentation-anthropic');
1256
2146
  instrumentation2 = new mod.AnthropicInstrumentation({
1257
2147
  exceptionLogger: (err) => {
1258
2148
  if (state2.config.debug) {
1259
2149
  console.error(
1260
- `[probe/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`
2150
+ `[sight/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`
1261
2151
  );
1262
2152
  }
1263
2153
  }
1264
2154
  });
1265
2155
  instrumentation2.enable();
1266
- registered2 = true;
2156
+ registered3 = true;
1267
2157
  } catch (err) {
1268
2158
  if (state2.config.debug) {
1269
2159
  const msg = err instanceof Error ? err.message : String(err);
1270
2160
  console.warn(
1271
- `[probe/anthropic] instrumentation not enabled (${msg}); library not installed?`
2161
+ `[sight/anthropic] instrumentation not enabled (${msg}); library not installed?`
1272
2162
  );
1273
2163
  }
1274
2164
  }
1275
2165
  }
1276
2166
 
1277
2167
  // src/instrumentation/langchain.ts
1278
- var registered3 = false;
2168
+ var registered4 = false;
1279
2169
  var instrumentation3 = null;
1280
2170
  async function registerLangChain(state2) {
1281
- if (registered3) return;
2171
+ if (registered4) return;
1282
2172
  try {
1283
2173
  const mod = await import('@traceloop/instrumentation-langchain');
1284
2174
  instrumentation3 = new mod.LangChainInstrumentation({
1285
2175
  exceptionLogger: (err) => {
1286
2176
  if (state2.config.debug) {
1287
2177
  console.error(
1288
- `[probe/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`
2178
+ `[sight/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`
1289
2179
  );
1290
2180
  }
1291
2181
  }
1292
2182
  });
1293
2183
  instrumentation3.enable();
1294
- registered3 = true;
2184
+ registered4 = true;
1295
2185
  } catch (err) {
1296
2186
  if (state2.config.debug) {
1297
2187
  const msg = err instanceof Error ? err.message : String(err);
1298
2188
  console.warn(
1299
- `[probe/langchain] instrumentation not enabled (${msg}); library not installed?`
2189
+ `[sight/langchain] instrumentation not enabled (${msg}); library not installed?`
1300
2190
  );
1301
2191
  }
1302
2192
  }
1303
2193
  }
1304
2194
 
1305
2195
  // src/instrumentation/langgraph.ts
1306
- var registered4 = false;
1307
- async function registerLangGraph(state2) {
1308
- if (registered4) return;
1309
- registered4 = true;
1310
- if (state2.config.debug) {
1311
- console.log(
1312
- "[probe/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology"
1313
- );
1314
- }
1315
- }
1316
-
1317
- // src/instrumentation/vercel-ai.ts
1318
2196
  var registered5 = false;
1319
- async function registerVercelAI(state2) {
2197
+ async function registerLangGraph(state2) {
1320
2198
  if (registered5) return;
1321
2199
  registered5 = true;
1322
2200
  if (state2.config.debug) {
1323
2201
  console.log(
1324
- "[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"
1325
2203
  );
1326
2204
  }
1327
2205
  }
@@ -1333,7 +2211,7 @@ async function registerLiteLLM(state2) {
1333
2211
  registered6 = true;
1334
2212
  if (state2.config.debug) {
1335
2213
  console.log(
1336
- "[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"
1337
2215
  );
1338
2216
  }
1339
2217
  }
@@ -1345,7 +2223,7 @@ async function registerMercury(state2) {
1345
2223
  registered7 = true;
1346
2224
  if (state2.config.debug) {
1347
2225
  console.log(
1348
- "[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"
1349
2227
  );
1350
2228
  }
1351
2229
  }
@@ -1359,7 +2237,7 @@ function registerAllInstrumentations(state2, captureFn) {
1359
2237
  registerAnthropic(state2),
1360
2238
  registerLangChain(state2),
1361
2239
  registerLangGraph(state2),
1362
- registerVercelAI(state2),
2240
+ registerVercelAI(state2, captureFn),
1363
2241
  registerLiteLLM(state2),
1364
2242
  registerMercury(state2)
1365
2243
  ];
@@ -1530,7 +2408,7 @@ var UserOutcomeSchema = z.object({
1530
2408
  /** Thumbs-up / thumbs-down widget value. */
1531
2409
  thumbs: z.enum(["up", "down"]).optional()
1532
2410
  });
1533
- z.object({
2411
+ var TurnInputSchema = z.object({
1534
2412
  deploymentSlug: z.string().min(1),
1535
2413
  sessionExternalId: z.string().min(1),
1536
2414
  /**
@@ -1549,6 +2427,8 @@ z.object({
1549
2427
  */
1550
2428
  externalUserId: z.string().min(1).optional(),
1551
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(),
1552
2432
  /**
1553
2433
  * Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the
1554
2434
  * worker: when present it becomes turns.started_at; when absent the
@@ -1613,7 +2493,8 @@ z.object({
1613
2493
  * All optional. Powers Chapter 8e′ Card 3 version behavioral diff.
1614
2494
  */
1615
2495
  agentId: z.string().optional(),
1616
- 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),
1617
2498
  environmentConfigHash: z.string().optional(),
1618
2499
  environmentConfigLabel: z.string().optional(),
1619
2500
  /** Internal Studio runner provenance. Customer SDKs never set this. */
@@ -1636,7 +2517,7 @@ z.object({
1636
2517
  clientContext: z.record(z.string(), z.unknown()).optional(),
1637
2518
  payload: z.record(z.string(), z.unknown())
1638
2519
  });
1639
- z.object({
2520
+ var SessionEndSchema2 = z.object({
1640
2521
  deploymentSlug: z.string().min(1),
1641
2522
  sessionExternalId: z.string().min(1),
1642
2523
  /** Why the session ended. */
@@ -1651,6 +2532,13 @@ z.object({
1651
2532
  /** ISO timestamp of session end. */
1652
2533
  endedAt: z.string().optional()
1653
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
+ });
1654
2542
  z.object({
1655
2543
  deploymentSlug: z.string().min(1),
1656
2544
  sessionExternalId: z.string().min(1),
@@ -2074,9 +2962,25 @@ function validateOrDrop(schema, input, method) {
2074
2962
  }
2075
2963
  return result.data;
2076
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
+ }
2077
2981
  var Probe = class {
2078
2982
  /**
2079
- * Initialize the Probe SDK. Call once at process start. Subsequent calls are
2983
+ * Initialize the SDK. Call once at process start. Subsequent calls are
2080
2984
  * no-ops with a warning; re-init requires a shutdown() first.
2081
2985
  */
2082
2986
  static init(config) {
@@ -2108,16 +3012,23 @@ var Probe = class {
2108
3012
  )
2109
3013
  );
2110
3014
  }
2111
- registerAllInstrumentations(state, (turn) => this.captureTurn(turn));
3015
+ registerAllInstrumentations(
3016
+ state,
3017
+ (turn, hints) => this.captureWithHints(turn, hints)
3018
+ );
2112
3019
  }
2113
3020
  /**
2114
- * Run a callback inside a session context. Every LLM call made inside `fn`
2115
- * (through any instrumented library: OpenAI, Anthropic, LangChain, Vercel
2116
- * AI SDK, etc.) is automatically tagged with `sessionId` and captured as
2117
- * a turn on that session.
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.)
2118
3030
  *
2119
- * Under the hood, this uses OTel Baggage propagation; the shared span
2120
- * processor reads the session ID from baggage when each LLM span ends.
3031
+ * The scope is carried in OpenTelemetry baggage across awaits.
2121
3032
  */
2122
3033
  static async withSession(sessionId, fn) {
2123
3034
  if (state === null) {
@@ -2162,12 +3073,12 @@ var Probe = class {
2162
3073
  const validated = validateOrDrop(SessionStartSchema, input, "startSession");
2163
3074
  if (validated === null) return;
2164
3075
  const existing = state.sessions.get(validated.externalId);
2165
- const now = Date.now();
3076
+ const now2 = Date.now();
2166
3077
  const session = {
2167
3078
  externalId: validated.externalId,
2168
3079
  externalUserId: validated.externalUserId ?? existing?.externalUserId ?? null,
2169
3080
  turnIndex: existing?.turnIndex ?? 0,
2170
- startedAt: existing?.startedAt ?? now,
3081
+ startedAt: existing?.startedAt ?? now2,
2171
3082
  personaSlug: validated.persona ?? existing?.personaSlug ?? state.persona?.slug ?? null,
2172
3083
  metadata: validated.metadata ?? existing?.metadata ?? null,
2173
3084
  openedVia: validated.openedVia ?? existing?.openedVia ?? null,
@@ -2223,7 +3134,7 @@ var Probe = class {
2223
3134
  }
2224
3135
  /**
2225
3136
  * Compute a stable SHA-256 hex hash of prompt/config text for use as
2226
- * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —
3137
+ * `environmentConfigHash` on Sight.startSession(). Hash is *identity*:
2227
3138
  * pass the human-readable version alongside as `environmentConfigLabel`
2228
3139
  * for the diff table axis (a card keyed by a3f9c2… is unreadable).
2229
3140
  *
@@ -2258,8 +3169,10 @@ var Probe = class {
2258
3169
  */
2259
3170
  static async endSession(externalId) {
2260
3171
  if (state === null) return;
3172
+ const validEnd = typeof externalId === "string" ? validateOrDrop(SessionRefSchema, { externalId }, "endSession") : validateOrDrop(SessionEndSchema, externalId, "endSession");
3173
+ if (validEnd === null) return;
2261
3174
  const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
2262
- const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
3175
+ const endedReason = typeof externalId === "string" ? "natural" : externalId.endedReason ?? "natural";
2263
3176
  const declared = typeof externalId === "string" ? void 0 : externalId.outcome;
2264
3177
  if (declared) {
2265
3178
  await this.emitOutcomeEvent({
@@ -2313,28 +3226,30 @@ var Probe = class {
2313
3226
  // before startSession or the first LLM call) buffer per externalId and
2314
3227
  // flush into the session when it is created.
2315
3228
  /**
2316
- * User started typing — records the first-keystroke timestamp for
2317
- * 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
2318
3231
  * only once a previous agent turn exists; a pre-session typing start
2319
3232
  * buffers the pending-input entry without a firstKeystrokeMs value.
2320
3233
  */
2321
3234
  static userInputStart(externalId) {
2322
3235
  if (state === null) return;
3236
+ if (validateOrDrop(SessionRefSchema, { externalId }, "userInputStart") === null) return;
2323
3237
  const session = state.sessions.get(externalId);
2324
3238
  const target = session ?? this.preSessionEntry(externalId);
2325
- const now = Date.now();
2326
- const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0, now - session.lastAgentTurnAt) : void 0;
3239
+ const now2 = Date.now();
3240
+ const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0, now2 - session.lastAgentTurnAt) : void 0;
2327
3241
  target.pendingUserInput = {
2328
3242
  ...target.pendingUserInput ?? { editCount: 0 },
2329
3243
  firstKeystrokeMs: target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs
2330
3244
  };
2331
3245
  }
2332
3246
  /**
2333
- * User pressed backspace / edited — increments edit_count for
2334
- * 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.
2335
3249
  */
2336
3250
  static userInputEdit(externalId) {
2337
3251
  if (state === null) return;
3252
+ if (validateOrDrop(SessionRefSchema, { externalId }, "userInputEdit") === null) return;
2338
3253
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2339
3254
  target.pendingUserInput = {
2340
3255
  ...target.pendingUserInput ?? { editCount: 0 },
@@ -2342,36 +3257,41 @@ var Probe = class {
2342
3257
  };
2343
3258
  }
2344
3259
  /**
2345
- * User submitted their reply. Records the text (Presidio-scrubbed
2346
- * server-side before landing on probe_user_reply_text) plus the submit
2347
- * timestamp, which captureTurn uses to derive probe_agent_reflect_ms
2348
- * (submit → next agent turn) and probe_transition_time_ms (previous
2349
- * agent turn → submit).
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.
2350
3264
  */
2351
3265
  static userInputSubmit(externalId, text) {
2352
3266
  if (state === null) return;
3267
+ if (validateOrDrop(UserInputSubmitSchema, { externalId, text }, "userInputSubmit") === null)
3268
+ return;
2353
3269
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2354
- const now = Date.now();
3270
+ const now2 = Date.now();
2355
3271
  target.pendingUserInput = {
2356
3272
  ...target.pendingUserInput ?? { editCount: 0 },
2357
3273
  text,
2358
- submittedAt: now
3274
+ submittedAt: now2
2359
3275
  };
2360
- target.lastUserSubmitAt = now;
3276
+ target.lastUserSubmitAt = now2;
2361
3277
  }
2362
3278
  /** Attach a thumbs-up/down to the current turn. */
2363
3279
  static userThumbs(externalId, thumbs) {
2364
3280
  if (state === null) return;
3281
+ if (validateOrDrop(UserThumbsSchema, { externalId, thumbs }, "userThumbs") === null) return;
2365
3282
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2366
3283
  target.pendingUserOutcome = {
2367
3284
  ...target.pendingUserOutcome ?? {},
2368
3285
  thumbs
2369
3286
  };
2370
3287
  }
2371
- /** 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
+ */
2372
3292
  static userRating(externalId, rating) {
2373
3293
  if (state === null) return;
2374
- if (rating < 1 || rating > 5 || !Number.isInteger(rating)) return;
3294
+ if (validateOrDrop(UserRatingSchema, { externalId, rating }, "userRating") === null) return;
2375
3295
  const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
2376
3296
  target.pendingUserOutcome = {
2377
3297
  ...target.pendingUserOutcome ?? {},
@@ -2405,27 +3325,56 @@ var Probe = class {
2405
3325
  state.outcomeHook = hook;
2406
3326
  }
2407
3327
  /**
2408
- * Manually capture a turn. Instrumentation adapters call this internally;
2409
- * 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.
2410
3337
  *
2411
3338
  * Persona resolution order for the outgoing turn payload:
2412
3339
  * 1. turn.personaSlug (turn-level override)
2413
- * 2. sessions[externalId].personaSlug (from startSession)
2414
- * 3. state.persona.slug (init-level default)
3340
+ * 2. the session's persona (from startSession)
3341
+ * 3. the init-level default
2415
3342
  *
2416
- * Signature-phrase matching runs at the SDK edge when the resolved persona
3343
+ * Signature-phrase matching runs in the SDK when the resolved persona
2417
3344
  * has signature phrases registered. The matched slug list is attached to
2418
3345
  * `turn.signaturePhraseMatches` before send.
2419
3346
  */
2420
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) {
2421
3356
  if (state === null) {
2422
3357
  return;
2423
3358
  }
2424
- if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
3359
+ if (input === null || typeof input !== "object") {
3360
+ validateOrDrop(TurnInputSchema, input, "captureTurn");
2425
3361
  return;
2426
3362
  }
2427
- if (turn.payload === void 0 || turn.payload === null) {
2428
- 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;
2429
3378
  }
2430
3379
  const propensity = turn.propensity ?? turn.payload.propensity;
2431
3380
  let validPropensity = propensity;
@@ -2493,6 +3442,9 @@ var Probe = class {
2493
3442
  if (session.pendingUserOutcome && !userOutcome) {
2494
3443
  userOutcome = session.pendingUserOutcome;
2495
3444
  }
3445
+ if (hints?.observedUserText && !userInput?.text) {
3446
+ userInput = { ...userInput ?? {}, text: hints.observedUserText };
3447
+ }
2496
3448
  if (!interactivity && session.lastUserSubmitAt) {
2497
3449
  interactivity = {
2498
3450
  agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt)
@@ -2520,7 +3472,7 @@ var Probe = class {
2520
3472
  envelopeVersion: SDK_ENVELOPE_VERSION,
2521
3473
  personaSlug: resolvedPersona,
2522
3474
  signaturePhraseMatches: signatureMatches,
2523
- // User identity from the local session entry (Probe.startSession).
3475
+ // User identity from the local session entry (Sight.startSession).
2524
3476
  // The worker persists it on sessions.external_user_id; never the
2525
3477
  // session key. Turn-level override wins for advanced callers.
2526
3478
  externalUserId: turn.externalUserId ?? session.externalUserId ?? void 0,
@@ -2536,7 +3488,7 @@ var Probe = class {
2536
3488
  // columns (e2e audit 2026-07-13).
2537
3489
  propensity: validPropensity,
2538
3490
  // Forward RLDS provenance from the local session entry (populated
2539
- // by Probe.startSession). Worker persists at first-turn session
3491
+ // by Sight.startSession). Worker persists at first-turn session
2540
3492
  // create; nulls stay null.
2541
3493
  agentId: session.agentId ?? void 0,
2542
3494
  experimentId: session.experimentId ?? void 0,
@@ -2545,8 +3497,8 @@ var Probe = class {
2545
3497
  });
2546
3498
  }
2547
3499
  /**
2548
- * Emit a custom outcome event on a session. Populates probe_outcome_events
2549
- * 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
2550
3502
  * customer-defined kinds like "purchase_complete", "handoff_to_human",
2551
3503
  * "character_break_severe". Universal seed kinds (break, escalation,
2552
3504
  * resolution, thumbs_*, rating_*) are also emitted by worker-side
@@ -2737,6 +3689,6 @@ var Probe = class {
2737
3689
  }
2738
3690
  };
2739
3691
 
2740
- export { Probe, SPAN_INTERVAL_KINDS, SPAN_PAYLOAD_STATES, SPAN_STATUSES, SPAN_TYPES, SPAN_V2_STATUSES, Probe as Sight, SpanInputSchema, SpanInputV1Schema, SpanInputV2Schema, SpanIntervalSchema, SpanPayloadSchema, SpansBatchSchema, wrapOpenAI };
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 };
2741
3693
  //# sourceMappingURL=index.js.map
2742
3694
  //# sourceMappingURL=index.js.map