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