@cultured_computer/sight 0.5.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -61,11 +61,12 @@ var IngestClient = class {
61
61
  * short-lived processes (serverless, CLI scripts) can actually exit after
62
62
  * it — the documented "in-flight sends finish within 15s" only holds while
63
63
  * the process lives. Polling is coarse on purpose: sends report through
64
- * guardedFetch's counter, never awaited individually.
64
+ * guardedFetch's counter and scheduled retries, never awaited individually.
65
+ * Retries beyond the drain budget remain best-effort, not durable delivery.
65
66
  */
66
67
  async drainInFlight(timeoutMs = SEND_TIMEOUT_MS) {
67
68
  const deadline = Date.now() + timeoutMs;
68
- while (this.inFlight > 0 && Date.now() < deadline) {
69
+ while ((this.inFlight > 0 || this.pendingRetries > 0) && Date.now() < deadline) {
69
70
  await new Promise((r) => setTimeout(r, 50));
70
71
  }
71
72
  }
@@ -82,9 +83,10 @@ var IngestClient = class {
82
83
  async sendTurn(turn) {
83
84
  try {
84
85
  const body = JSON.stringify(turn);
85
- if (body.length > MAX_TURN_BODY_BYTES) {
86
+ const bodyBytes = new TextEncoder().encode(body).byteLength;
87
+ if (bodyBytes > MAX_TURN_BODY_BYTES) {
86
88
  this.log(
87
- `[sight] turn dropped: payload ${body.length} bytes exceeds the ${MAX_TURN_BODY_BYTES}-byte cap (session=${turn.sessionExternalId} turn=${turn.turnIndex}) \u2014 trim the payload you attach`
89
+ `[sight] turn dropped: payload ${bodyBytes} bytes exceeds the ${MAX_TURN_BODY_BYTES}-byte cap (session=${turn.sessionExternalId} turn=${turn.turnIndex}) \u2014 trim the payload you attach`
88
90
  );
89
91
  return;
90
92
  }
@@ -442,7 +444,14 @@ var SessionStartSchema = z.object({
442
444
  });
443
445
  z.object({
444
446
  externalId: z.string().min(1),
445
- endedReason: z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional(),
447
+ endedReason: z.enum([
448
+ "natural",
449
+ "user_closed",
450
+ "timeout",
451
+ "agent_error",
452
+ "user_flagged",
453
+ "crashed"
454
+ ]).optional(),
446
455
  outcome: z.string().min(1).max(64).optional(),
447
456
  outcomeDetail: z.record(z.string(), z.unknown()).optional()
448
457
  });
@@ -563,22 +572,7 @@ function getCurrentSessionId() {
563
572
  }
564
573
 
565
574
  // src/instrumentation/otel-processor.ts
566
- var DEDUP_TTL_MS = 5e3;
567
- var dedupCache = /* @__PURE__ */ new Map();
568
- function shouldSkipAsDuplicate(traceId) {
569
- const now = Date.now();
570
- const seenAt = dedupCache.get(traceId);
571
- if (seenAt !== void 0 && now - seenAt < DEDUP_TTL_MS) {
572
- return true;
573
- }
574
- dedupCache.set(traceId, now);
575
- if (dedupCache.size > 1e3) {
576
- for (const [k, v] of dedupCache) {
577
- if (now - v > DEDUP_TTL_MS) dedupCache.delete(k);
578
- }
579
- }
580
- return false;
581
- }
575
+ var MAX_DEDUP_SPANS = 1e4;
582
576
  function attr(attrs, key) {
583
577
  return attrs[key];
584
578
  }
@@ -731,8 +725,10 @@ function extractSystemPromptText(attrs) {
731
725
  return void 0;
732
726
  }
733
727
  async function maybeAutoStampEnvironmentConfig(session, attrs) {
728
+ await autoStampFromSystemText(session, extractSystemPromptText(attrs));
729
+ }
730
+ async function autoStampFromSystemText(session, systemText) {
734
731
  if (session.environmentConfigHash != null) return;
735
- const systemText = extractSystemPromptText(attrs);
736
732
  if (!systemText) return;
737
733
  const hash = await hashEnvironmentConfig(systemText);
738
734
  if (session.environmentConfigHash != null) return;
@@ -768,6 +764,7 @@ var ProbeSpanProcessor = class {
768
764
  }
769
765
  state;
770
766
  captureFn;
767
+ seenSpans = /* @__PURE__ */ new Set();
771
768
  /**
772
769
  * Re-point the processor at a new Probe state (or null after shutdown).
773
770
  * A registered span processor cannot be removed from a provider, so
@@ -776,6 +773,7 @@ var ProbeSpanProcessor = class {
776
773
  * stamping the old deployment slug (production-safety audit R1).
777
774
  */
778
775
  rebind(state2, captureFn) {
776
+ if (this.state !== state2) this.seenSpans.clear();
779
777
  this.state = state2;
780
778
  if (captureFn) this.captureFn = captureFn;
781
779
  }
@@ -788,8 +786,6 @@ var ProbeSpanProcessor = class {
788
786
  const a = span.attributes;
789
787
  if (isVercelAgentRollup(span.name, a)) return;
790
788
  if (!isLLMCall(a)) return;
791
- const traceId = span.spanContext().traceId;
792
- if (shouldSkipAsDuplicate(traceId)) return;
793
789
  const sessionId = getCurrentSessionId();
794
790
  if (!sessionId) {
795
791
  if (state2.config.debug) {
@@ -799,6 +795,13 @@ var ProbeSpanProcessor = class {
799
795
  }
800
796
  return;
801
797
  }
798
+ const { traceId, spanId } = span.spanContext();
799
+ const identity = JSON.stringify([state2.config.deployment, sessionId, traceId, spanId]);
800
+ if (this.seenSpans.has(identity)) return;
801
+ this.seenSpans.add(identity);
802
+ if (this.seenSpans.size > MAX_DEDUP_SPANS) {
803
+ this.seenSpans.delete(this.seenSpans.values().next().value);
804
+ }
802
805
  const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
803
806
  state2,
804
807
  sessionId
@@ -829,7 +832,7 @@ var ProbeSpanProcessor = class {
829
832
  }
830
833
  }
831
834
  shutdown() {
832
- dedupCache.clear();
835
+ this.seenSpans.clear();
833
836
  return Promise.resolve();
834
837
  }
835
838
  forceFlush() {
@@ -837,6 +840,342 @@ var ProbeSpanProcessor = class {
837
840
  }
838
841
  };
839
842
 
843
+ // src/instrumentation/wrap-openai.ts
844
+ var bound = null;
845
+ var warnedUnbound = false;
846
+ function bindWrapOpenAI(state2, captureFn) {
847
+ bound = { state: state2, captureFn };
848
+ }
849
+ function unbindWrapOpenAI() {
850
+ bound = null;
851
+ }
852
+ var WRAPPED = /* @__PURE__ */ Symbol.for("sight.wrapOpenAI");
853
+ function asRecord(v) {
854
+ return v !== null && typeof v === "object" ? v : void 0;
855
+ }
856
+ function asString2(v) {
857
+ return typeof v === "string" ? v : void 0;
858
+ }
859
+ function asNumber2(v) {
860
+ return typeof v === "number" ? v : void 0;
861
+ }
862
+ function messageText2(content) {
863
+ if (typeof content === "string") return content;
864
+ if (Array.isArray(content)) {
865
+ const parts = [];
866
+ for (const part of content) {
867
+ if (typeof part === "string") parts.push(part);
868
+ else {
869
+ const p = asRecord(part);
870
+ const text = p?.["text"] ?? p?.["content"];
871
+ if (typeof text === "string") parts.push(text);
872
+ }
873
+ }
874
+ return parts.length > 0 ? parts.join("\n") : void 0;
875
+ }
876
+ return void 0;
877
+ }
878
+ function systemTextFromParams(params) {
879
+ if (!params) return void 0;
880
+ const instructions = asString2(params["instructions"]);
881
+ if (instructions && instructions.length > 0) return instructions;
882
+ const messages = params["messages"];
883
+ if (Array.isArray(messages)) {
884
+ for (const raw of messages) {
885
+ const m = asRecord(raw);
886
+ if (m && (m["role"] === "system" || m["role"] === "developer")) {
887
+ const text = messageText2(m["content"]);
888
+ if (text) return text;
889
+ }
890
+ }
891
+ }
892
+ return void 0;
893
+ }
894
+ function providerFor(model) {
895
+ return model?.toLowerCase().startsWith("mercury") ? "inception" : "openai";
896
+ }
897
+ function payloadFromChatResponse(r, requestModel) {
898
+ const choice = Array.isArray(r["choices"]) ? asRecord(r["choices"][0]) : void 0;
899
+ const message = asRecord(choice?.["message"]);
900
+ const usage = asRecord(r["usage"]);
901
+ const promptDetails = asRecord(usage?.["prompt_tokens_details"]);
902
+ const toolCalls = Array.isArray(message?.["tool_calls"]) ? message["tool_calls"] : void 0;
903
+ const toolNames = toolCalls?.map((t) => asString2(asRecord(asRecord(t)?.["function"])?.["name"])).filter((n) => typeof n === "string");
904
+ return {
905
+ model: asString2(r["model"]) ?? requestModel,
906
+ text: messageText2(message?.["content"]),
907
+ tokensInput: asNumber2(usage?.["prompt_tokens"]),
908
+ tokensOutput: asNumber2(usage?.["completion_tokens"]),
909
+ cachedTokens: asNumber2(promptDetails?.["cached_tokens"]),
910
+ finishReason: asString2(choice?.["finish_reason"]),
911
+ toolNames
912
+ };
913
+ }
914
+ function payloadFromResponsesResponse(r, requestModel) {
915
+ const usage = asRecord(r["usage"]);
916
+ const inputDetails = asRecord(usage?.["input_tokens_details"]);
917
+ let text = asString2(r["output_text"]);
918
+ const toolNames = [];
919
+ if (Array.isArray(r["output"])) {
920
+ const texts = [];
921
+ for (const raw of r["output"]) {
922
+ const item = asRecord(raw);
923
+ if (!item) continue;
924
+ if (item["type"] === "function_call") {
925
+ const name = asString2(item["name"]);
926
+ if (name) toolNames.push(name);
927
+ }
928
+ if (item["type"] === "message" && Array.isArray(item["content"])) {
929
+ for (const c of item["content"]) {
930
+ const cr = asRecord(c);
931
+ if (cr?.["type"] === "output_text") {
932
+ const t = asString2(cr["text"]);
933
+ if (t) texts.push(t);
934
+ }
935
+ }
936
+ }
937
+ }
938
+ if (!text && texts.length > 0) text = texts.join("\n");
939
+ }
940
+ return {
941
+ model: asString2(r["model"]) ?? requestModel,
942
+ text,
943
+ tokensInput: asNumber2(usage?.["input_tokens"]),
944
+ tokensOutput: asNumber2(usage?.["output_tokens"]),
945
+ cachedTokens: asNumber2(inputDetails?.["cached_tokens"]),
946
+ finishReason: asString2(r["status"]),
947
+ toolNames: toolNames.length > 0 ? toolNames : void 0
948
+ };
949
+ }
950
+ function buildTurnPayload(x, latencyMs, api) {
951
+ return {
952
+ probe_tokens_input: x.tokensInput,
953
+ probe_tokens_output: x.tokensOutput,
954
+ probe_latency_ms: latencyMs,
955
+ probe_model: x.model,
956
+ probe_provider: providerFor(x.model),
957
+ probe_tool_calls: x.toolNames?.length,
958
+ probe_tool_names: x.toolNames,
959
+ probe_error: void 0,
960
+ probe_finish_reason: x.finishReason,
961
+ response: x.text ? { text: x.text } : void 0,
962
+ probe_cache_read_input_tokens: x.cachedTokens,
963
+ _wrap: { api, adapter: "wrapOpenAI" }
964
+ };
965
+ }
966
+ function emit(params, payload) {
967
+ if (!bound) {
968
+ if (!warnedUnbound) {
969
+ warnedUnbound = true;
970
+ console.warn(
971
+ "[sight] wrapOpenAI: call observed before Probe.init(); nothing captured until init runs."
972
+ );
973
+ }
974
+ return;
975
+ }
976
+ const { state: state2, captureFn } = bound;
977
+ const sessionId = getCurrentSessionId();
978
+ if (!sessionId) {
979
+ if (state2.config.debug) {
980
+ console.warn(
981
+ "[sight] wrapOpenAI: call with no session context; skipped (wrap calls in Probe.withSession())."
982
+ );
983
+ }
984
+ return;
985
+ }
986
+ const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
987
+ state2,
988
+ sessionId
989
+ );
990
+ const captured = {
991
+ deploymentSlug: state2.config.deployment,
992
+ sessionExternalId,
993
+ turnIndex,
994
+ personaSlug: personaSlug ?? void 0,
995
+ payload
996
+ };
997
+ void (async () => {
998
+ await autoStampFromSystemText(session, systemTextFromParams(params));
999
+ await captureFn(captured);
1000
+ })().catch((err) => {
1001
+ if (state2.config.debug) {
1002
+ console.error(`[sight] wrapOpenAI capture error: ${err instanceof Error ? err.message : err}`);
1003
+ }
1004
+ });
1005
+ }
1006
+ function teeStream(stream, onChunk, onDone) {
1007
+ let done = false;
1008
+ const finish = () => {
1009
+ if (!done) {
1010
+ done = true;
1011
+ onDone();
1012
+ }
1013
+ };
1014
+ return new Proxy(stream, {
1015
+ get(target, prop, receiver) {
1016
+ if (prop === Symbol.asyncIterator) {
1017
+ return function() {
1018
+ const inner = target[Symbol.asyncIterator]();
1019
+ return {
1020
+ async next() {
1021
+ try {
1022
+ const r = await inner.next();
1023
+ if (r.done) finish();
1024
+ else onChunk(r.value);
1025
+ return r;
1026
+ } catch (err) {
1027
+ finish();
1028
+ throw err;
1029
+ }
1030
+ },
1031
+ async return(value2) {
1032
+ finish();
1033
+ return inner.return ? inner.return(value2) : { done: true, value: value2 };
1034
+ },
1035
+ async throw(err) {
1036
+ finish();
1037
+ if (inner.throw) return inner.throw(err);
1038
+ throw err;
1039
+ }
1040
+ };
1041
+ };
1042
+ }
1043
+ const value = Reflect.get(target, prop, receiver);
1044
+ return typeof value === "function" ? value.bind(target) : value;
1045
+ }
1046
+ });
1047
+ }
1048
+ function chatStreamAccumulator(requestModel) {
1049
+ const texts = [];
1050
+ let model = requestModel;
1051
+ let finishReason;
1052
+ let tokensInput;
1053
+ let tokensOutput;
1054
+ let cachedTokens;
1055
+ return {
1056
+ onChunk(chunk) {
1057
+ const c = asRecord(chunk);
1058
+ if (!c) return;
1059
+ model = asString2(c["model"]) ?? model;
1060
+ const choice = Array.isArray(c["choices"]) ? asRecord(c["choices"][0]) : void 0;
1061
+ const delta = asRecord(choice?.["delta"]);
1062
+ const t = asString2(delta?.["content"]);
1063
+ if (t) texts.push(t);
1064
+ finishReason = asString2(choice?.["finish_reason"]) ?? finishReason;
1065
+ const usage = asRecord(c["usage"]);
1066
+ if (usage) {
1067
+ tokensInput = asNumber2(usage["prompt_tokens"]) ?? tokensInput;
1068
+ tokensOutput = asNumber2(usage["completion_tokens"]) ?? tokensOutput;
1069
+ cachedTokens = asNumber2(asRecord(usage["prompt_tokens_details"])?.["cached_tokens"]) ?? cachedTokens;
1070
+ }
1071
+ },
1072
+ result: () => ({
1073
+ model,
1074
+ text: texts.length > 0 ? texts.join("") : void 0,
1075
+ tokensInput,
1076
+ tokensOutput,
1077
+ cachedTokens,
1078
+ finishReason,
1079
+ toolNames: void 0
1080
+ })
1081
+ };
1082
+ }
1083
+ function responsesStreamAccumulator(requestModel) {
1084
+ const texts = [];
1085
+ let final = null;
1086
+ return {
1087
+ onChunk(chunk) {
1088
+ const c = asRecord(chunk);
1089
+ if (!c) return;
1090
+ if (c["type"] === "response.output_text.delta") {
1091
+ const t = asString2(c["delta"]);
1092
+ if (t) texts.push(t);
1093
+ }
1094
+ if (c["type"] === "response.completed") {
1095
+ const response = asRecord(c["response"]);
1096
+ if (response) final = payloadFromResponsesResponse(response, requestModel);
1097
+ }
1098
+ },
1099
+ result: () => {
1100
+ if (final) {
1101
+ return { ...final, text: final.text ?? (texts.length > 0 ? texts.join("") : void 0) };
1102
+ }
1103
+ return {
1104
+ model: requestModel,
1105
+ text: texts.length > 0 ? texts.join("") : void 0,
1106
+ tokensInput: void 0,
1107
+ tokensOutput: void 0,
1108
+ cachedTokens: void 0,
1109
+ finishReason: void 0,
1110
+ toolNames: void 0
1111
+ };
1112
+ }
1113
+ };
1114
+ }
1115
+ function wrapCreate(target, api, makeAccumulator, extractResponse) {
1116
+ const original = target["create"];
1117
+ if (typeof original !== "function") return;
1118
+ target["create"] = function(...args) {
1119
+ const params = asRecord(args[0]);
1120
+ const requestModel = asString2(params?.["model"]);
1121
+ const startedAt = Date.now();
1122
+ const result = original.apply(this, args);
1123
+ if (!result || typeof result.then !== "function") return result;
1124
+ return result.then(
1125
+ (resolved) => {
1126
+ try {
1127
+ const isStream = resolved !== null && typeof resolved === "object" && Symbol.asyncIterator in resolved;
1128
+ if (isStream) {
1129
+ const acc = makeAccumulator(requestModel);
1130
+ return teeStream(resolved, acc.onChunk, () => {
1131
+ emit(params, buildTurnPayload(acc.result(), Date.now() - startedAt, api));
1132
+ });
1133
+ }
1134
+ const r = asRecord(resolved);
1135
+ if (r) {
1136
+ emit(params, buildTurnPayload(extractResponse(r, requestModel), Date.now() - startedAt, api));
1137
+ }
1138
+ return resolved;
1139
+ } catch {
1140
+ return resolved;
1141
+ }
1142
+ },
1143
+ (err) => {
1144
+ try {
1145
+ const x = {
1146
+ model: requestModel,
1147
+ text: void 0,
1148
+ tokensInput: void 0,
1149
+ tokensOutput: void 0,
1150
+ cachedTokens: void 0,
1151
+ finishReason: void 0,
1152
+ toolNames: void 0
1153
+ };
1154
+ const payload = buildTurnPayload(x, Date.now() - startedAt, api);
1155
+ payload.probe_error = err instanceof Error ? err.message : String(err);
1156
+ emit(params, payload);
1157
+ } catch {
1158
+ }
1159
+ throw err;
1160
+ }
1161
+ );
1162
+ };
1163
+ }
1164
+ function wrapOpenAI(client) {
1165
+ const c = client;
1166
+ if (c[WRAPPED]) return client;
1167
+ c[WRAPPED] = true;
1168
+ const completions = asRecord(asRecord(c["chat"])?.["completions"]);
1169
+ if (completions) {
1170
+ wrapCreate(completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
1171
+ }
1172
+ const responses = asRecord(c["responses"]);
1173
+ if (responses) {
1174
+ wrapCreate(responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
1175
+ }
1176
+ return client;
1177
+ }
1178
+
840
1179
  // src/instrumentation/setup.ts
841
1180
  var installedProcessor = null;
842
1181
  function setupOtelProvider(state2, captureFn) {
@@ -859,6 +1198,7 @@ function setupOtelProvider(state2, captureFn) {
859
1198
  }
860
1199
  function detachOtelState() {
861
1200
  installedProcessor?.rebind(null);
1201
+ unbindWrapOpenAI();
862
1202
  }
863
1203
 
864
1204
  // src/instrumentation/openai.ts
@@ -880,6 +1220,7 @@ async function registerOpenAI(state2) {
880
1220
  });
881
1221
  instrumentation.enable();
882
1222
  registered = true;
1223
+ void verifyPatchAttached();
883
1224
  } catch (err) {
884
1225
  if (state2.config.debug) {
885
1226
  const msg = err instanceof Error ? err.message : String(err);
@@ -887,6 +1228,23 @@ async function registerOpenAI(state2) {
887
1228
  }
888
1229
  }
889
1230
  }
1231
+ function isPatchDetached(mod) {
1232
+ const OpenAIClass = mod?.default ?? mod?.OpenAI;
1233
+ const create = OpenAIClass?.Chat?.Completions?.prototype?.create;
1234
+ if (typeof create !== "function") return true;
1235
+ return create.__wrapped !== true;
1236
+ }
1237
+ async function verifyPatchAttached() {
1238
+ try {
1239
+ const mod = await import('openai');
1240
+ if (!isPatchDetached(mod)) return;
1241
+ const version = mod?.default?.VERSION ?? mod?.VERSION;
1242
+ console.warn(
1243
+ `[sight] OpenAI autocapture via module patching did not attach` + (version ? ` (openai v${version})` : "") + `. This happens on openai >=5, under ESM, or when 'openai' loads before init. Wrap your client instead: import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()). Until then, no turns are captured from this client.`
1244
+ );
1245
+ } catch {
1246
+ }
1247
+ }
890
1248
 
891
1249
  // src/instrumentation/anthropic.ts
892
1250
  var registered2 = false;
@@ -995,6 +1353,7 @@ async function registerMercury(state2) {
995
1353
  // src/instrumentation/index.ts
996
1354
  function registerAllInstrumentations(state2, captureFn) {
997
1355
  setupOtelProvider(state2, captureFn);
1356
+ bindWrapOpenAI(state2, captureFn);
998
1357
  const registrations = [
999
1358
  registerOpenAI(state2),
1000
1359
  registerAnthropic(state2),
@@ -1174,6 +1533,12 @@ var UserOutcomeSchema = z.object({
1174
1533
  z.object({
1175
1534
  deploymentSlug: z.string().min(1),
1176
1535
  sessionExternalId: z.string().min(1),
1536
+ /**
1537
+ * The SDK payload contract version (D2): optional, additive-only. Every
1538
+ * reader treats a missing stamp as 'envelope-v0-unstamped' — payloads
1539
+ * from older SDKs are valid by construction (tolerated-absent).
1540
+ */
1541
+ envelopeVersion: z.string().max(40).optional(),
1177
1542
  /**
1178
1543
  * Customer's user identity (opaque string), forwarded by the SDK from
1179
1544
  * Probe.startSession() state on every turn. Distinct from
@@ -1251,6 +1616,8 @@ z.object({
1251
1616
  experimentId: z.string().optional(),
1252
1617
  environmentConfigHash: z.string().optional(),
1253
1618
  environmentConfigLabel: z.string().optional(),
1619
+ /** Internal Studio runner provenance. Customer SDKs never set this. */
1620
+ studioRunRequestId: z.string().uuid().optional(),
1254
1621
  /**
1255
1622
  * Session context riding the FIRST turn of a session (there is no
1256
1623
  * session-start wire route; the session row is created lazily by the
@@ -1273,7 +1640,14 @@ z.object({
1273
1640
  deploymentSlug: z.string().min(1),
1274
1641
  sessionExternalId: z.string().min(1),
1275
1642
  /** Why the session ended. */
1276
- endedReason: z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional(),
1643
+ endedReason: z.enum([
1644
+ "natural",
1645
+ "user_closed",
1646
+ "timeout",
1647
+ "agent_error",
1648
+ "user_flagged",
1649
+ "crashed"
1650
+ ]).optional(),
1277
1651
  /** ISO timestamp of session end. */
1278
1652
  endedAt: z.string().optional()
1279
1653
  });
@@ -1340,8 +1714,113 @@ var EnvironmentEventsBatchSchema = z.object({
1340
1714
  events: z.array(EnvironmentEventInputSchema).min(1).max(100),
1341
1715
  alignment: AlignmentProvenanceSchema
1342
1716
  });
1343
- var SPAN_TYPES = ["llm_call", "tool_call", "framework_step", "custom"];
1344
- var SpanInputSchema = z.object({
1717
+ var SPAN_TYPES = [
1718
+ "agent_call",
1719
+ "llm_call",
1720
+ "tool_call",
1721
+ "framework_step",
1722
+ "custom"
1723
+ ];
1724
+ var SPAN_STATUSES = ["unset", "ok", "error"];
1725
+ var SPAN_V2_STATUSES = ["ok", "error"];
1726
+ var SPAN_PAYLOAD_STATES = [
1727
+ "captured",
1728
+ "empty",
1729
+ "not_captured",
1730
+ "redacted",
1731
+ "unavailable"
1732
+ ];
1733
+ var SPAN_INTERVAL_KINDS = [
1734
+ "active",
1735
+ "waiting",
1736
+ "retry",
1737
+ "error"
1738
+ ];
1739
+ var SpanIntervalSchema = z.object({
1740
+ kind: z.enum(SPAN_INTERVAL_KINDS),
1741
+ startedAt: z.string().datetime(),
1742
+ endedAt: z.string().datetime()
1743
+ }).superRefine((interval, ctx) => {
1744
+ if (new Date(interval.endedAt).getTime() <= new Date(interval.startedAt).getTime()) {
1745
+ ctx.addIssue({
1746
+ code: z.ZodIssueCode.custom,
1747
+ path: ["endedAt"],
1748
+ message: "interval endedAt must follow startedAt"
1749
+ });
1750
+ }
1751
+ });
1752
+ function serializedJsonLength(value) {
1753
+ try {
1754
+ return JSON.stringify(value)?.length ?? 0;
1755
+ } catch {
1756
+ return Number.POSITIVE_INFINITY;
1757
+ }
1758
+ }
1759
+ function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
1760
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
1761
+ return true;
1762
+ }
1763
+ if (typeof value === "number") return Number.isFinite(value);
1764
+ if (typeof value !== "object") return false;
1765
+ if (ancestors.has(value)) return false;
1766
+ const nextAncestors = new Set(ancestors).add(value);
1767
+ if (Array.isArray(value)) {
1768
+ return value.every((item) => isJsonValue(item, nextAncestors));
1769
+ }
1770
+ if (Object.getPrototypeOf(value) !== Object.prototype) return false;
1771
+ return Object.values(value).every(
1772
+ (item) => isJsonValue(item, nextAncestors)
1773
+ );
1774
+ }
1775
+ function isStructurallyEmptyPayload(value) {
1776
+ if (value === "") return true;
1777
+ if (Array.isArray(value)) return value.length === 0;
1778
+ return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype && Object.keys(value).length === 0;
1779
+ }
1780
+ var SpanPayloadSchema = z.object({
1781
+ state: z.enum(SPAN_PAYLOAD_STATES),
1782
+ value: z.unknown().nullable()
1783
+ }).superRefine((payload, ctx) => {
1784
+ if (!("value" in payload)) {
1785
+ ctx.addIssue({
1786
+ code: z.ZodIssueCode.custom,
1787
+ path: ["value"],
1788
+ message: "payload value must be present; use null for non-captured states"
1789
+ });
1790
+ return;
1791
+ }
1792
+ if (payload.state === "captured" && !isJsonValue(payload.value)) {
1793
+ ctx.addIssue({
1794
+ code: z.ZodIssueCode.custom,
1795
+ path: ["value"],
1796
+ message: "captured payload must be JSON-compatible"
1797
+ });
1798
+ }
1799
+ if (payload.state === "captured" && payload.value === null) {
1800
+ ctx.addIssue({
1801
+ code: z.ZodIssueCode.custom,
1802
+ path: ["value"],
1803
+ message: "captured payload requires a non-null value"
1804
+ });
1805
+ }
1806
+ if (payload.state === "captured" && isStructurallyEmptyPayload(payload.value)) {
1807
+ ctx.addIssue({
1808
+ code: z.ZodIssueCode.custom,
1809
+ path: ["value"],
1810
+ message: "genuinely empty payloads require state=empty"
1811
+ });
1812
+ }
1813
+ if (payload.state !== "captured" && payload.value !== null) {
1814
+ ctx.addIssue({
1815
+ code: z.ZodIssueCode.custom,
1816
+ path: ["value"],
1817
+ message: `${payload.state} payload must carry a null value`
1818
+ });
1819
+ }
1820
+ }).refine((payload) => serializedJsonLength(payload.value) <= 16e3, {
1821
+ message: "span payload exceeds 16k JSON chars"
1822
+ });
1823
+ var SpanAddressSchema = z.object({
1345
1824
  deploymentSlug: z.string().min(1),
1346
1825
  sessionExternalId: z.string().min(1),
1347
1826
  /**
@@ -1352,7 +1831,10 @@ var SpanInputSchema = z.object({
1352
1831
  * worker (logged, batch still processed): spans never land unattributed.
1353
1832
  */
1354
1833
  turnIndex: z.number().int().nonnegative().optional(),
1355
- spanType: z.enum(SPAN_TYPES),
1834
+ spanType: z.enum(SPAN_TYPES)
1835
+ });
1836
+ var SpanInputV1Schema = SpanAddressSchema.extend({
1837
+ contractVersion: z.literal(1).optional(),
1356
1838
  /** Human/otel-style span name (tool name, model call label). */
1357
1839
  name: z.string().optional(),
1358
1840
  /**
@@ -1390,16 +1872,128 @@ var SpanInputSchema = z.object({
1390
1872
  */
1391
1873
  parentSpanId: z.string().min(1).optional()
1392
1874
  });
1875
+ var SpanInputV2Schema = SpanAddressSchema.extend({
1876
+ contractVersion: z.literal(2),
1877
+ /** Stable within a deployment/session across batches and retries. */
1878
+ spanId: z.string().min(1),
1879
+ parentSpanId: z.string().min(1).nullable(),
1880
+ name: z.string().min(1),
1881
+ status: z.enum(SPAN_V2_STATUSES),
1882
+ startedAt: z.string().datetime(),
1883
+ endedAt: z.string().datetime().nullable(),
1884
+ durationMs: z.number().int().nonnegative().nullable(),
1885
+ model: z.string().min(1).nullable(),
1886
+ provider: z.string().min(1).nullable(),
1887
+ tokensInput: z.number().int().nonnegative().nullable(),
1888
+ tokensOutput: z.number().int().nonnegative().nullable(),
1889
+ costUsd: z.number().nonnegative().nullable(),
1890
+ error: z.string().nullable(),
1891
+ input: SpanPayloadSchema,
1892
+ output: SpanPayloadSchema,
1893
+ /** Optional first-class internal timing. An omitted list means the source
1894
+ * did not capture interval telemetry; readers must not infer segments. */
1895
+ intervals: z.array(SpanIntervalSchema).max(128).optional(),
1896
+ attributes: z.record(z.string(), z.unknown()).nullable().refine(
1897
+ (value) => value === null || JSON.stringify(value).length <= 16e3,
1898
+ {
1899
+ message: "attributes exceed 16k JSON chars \u2014 spans are telemetry, not blob storage"
1900
+ }
1901
+ )
1902
+ }).superRefine((span, ctx) => {
1903
+ if (span.status !== "error" && span.error !== null) {
1904
+ ctx.addIssue({
1905
+ code: z.ZodIssueCode.custom,
1906
+ path: ["error"],
1907
+ message: "error detail requires status=error"
1908
+ });
1909
+ }
1910
+ if (span.endedAt !== null && new Date(span.endedAt).getTime() < new Date(span.startedAt).getTime()) {
1911
+ ctx.addIssue({
1912
+ code: z.ZodIssueCode.custom,
1913
+ path: ["endedAt"],
1914
+ message: "endedAt must not precede startedAt"
1915
+ });
1916
+ }
1917
+ const spanStart = new Date(span.startedAt).getTime();
1918
+ const spanEnd = span.endedAt !== null ? new Date(span.endedAt).getTime() : span.durationMs !== null ? spanStart + span.durationMs : null;
1919
+ span.intervals?.forEach((interval, index) => {
1920
+ const intervalStart = new Date(interval.startedAt).getTime();
1921
+ const intervalEnd = new Date(interval.endedAt).getTime();
1922
+ if (intervalStart < spanStart || spanEnd !== null && intervalEnd > spanEnd) {
1923
+ ctx.addIssue({
1924
+ code: z.ZodIssueCode.custom,
1925
+ path: ["intervals", index],
1926
+ message: "interval must stay within the measured span window"
1927
+ });
1928
+ }
1929
+ });
1930
+ });
1931
+ var SpanInputSchema = z.union([SpanInputV2Schema, SpanInputV1Schema]);
1393
1932
  var SpansBatchSchema = z.object({
1394
1933
  /** Spans are self-addressed: a batch may span sessions/deployments. */
1395
1934
  spans: z.array(SpanInputSchema).min(1).max(50),
1396
1935
  alignment: AlignmentProvenanceSchema
1936
+ }).superRefine((batch, ctx) => {
1937
+ const spanIdCounts = /* @__PURE__ */ new Map();
1938
+ const spansById = /* @__PURE__ */ new Map();
1939
+ const parents = /* @__PURE__ */ new Map();
1940
+ for (const span of batch.spans) {
1941
+ if (span.spanId !== void 0) {
1942
+ spanIdCounts.set(span.spanId, (spanIdCounts.get(span.spanId) ?? 0) + 1);
1943
+ spansById.set(span.spanId, span);
1944
+ }
1945
+ if (span.parentSpanId !== void 0 && span.parentSpanId !== null && span.spanId) {
1946
+ parents.set(span.spanId, span.parentSpanId);
1947
+ }
1948
+ }
1949
+ batch.spans.forEach((span, index) => {
1950
+ if (span.contractVersion !== 2) return;
1951
+ if ((spanIdCounts.get(span.spanId) ?? 0) !== 1) {
1952
+ ctx.addIssue({
1953
+ code: z.ZodIssueCode.custom,
1954
+ path: ["spans", index, "spanId"],
1955
+ message: "v2 spanId must be unique within the batch"
1956
+ });
1957
+ }
1958
+ if (span.parentSpanId !== null && (spanIdCounts.get(span.parentSpanId) ?? 0) !== 1) {
1959
+ ctx.addIssue({
1960
+ code: z.ZodIssueCode.custom,
1961
+ path: ["spans", index, "parentSpanId"],
1962
+ message: "v2 parentSpanId must resolve uniquely within the batch"
1963
+ });
1964
+ }
1965
+ const parent = span.parentSpanId === null ? void 0 : spansById.get(span.parentSpanId);
1966
+ if (parent && (parent.deploymentSlug !== span.deploymentSlug || parent.sessionExternalId !== span.sessionExternalId)) {
1967
+ ctx.addIssue({
1968
+ code: z.ZodIssueCode.custom,
1969
+ path: ["spans", index, "parentSpanId"],
1970
+ message: "v2 parentSpanId must belong to the same deployment and session"
1971
+ });
1972
+ }
1973
+ const seen = /* @__PURE__ */ new Set();
1974
+ let cursor = span.spanId;
1975
+ while (cursor !== void 0) {
1976
+ if (seen.has(cursor)) {
1977
+ ctx.addIssue({
1978
+ code: z.ZodIssueCode.custom,
1979
+ path: ["spans", index, "parentSpanId"],
1980
+ message: "v2 parentSpanId graph must not contain a cycle"
1981
+ });
1982
+ break;
1983
+ }
1984
+ seen.add(cursor);
1985
+ cursor = parents.get(cursor);
1986
+ }
1987
+ });
1397
1988
  });
1398
1989
  var DEFINITION_SLUG = /^[a-z][a-z0-9_-]{0,63}$/;
1399
1990
  var DEFINITION_VALUE = z.string().trim().min(1).max(64);
1400
1991
  z.object({
1401
1992
  /** Measurement family the definition belongs to (e.g. 'voice-conformance'). */
1402
- family: z.string().regex(DEFINITION_SLUG, "family must be a lowercase slug (a-z, 0-9, _-)."),
1993
+ family: z.string().regex(
1994
+ DEFINITION_SLUG,
1995
+ "family must be a lowercase slug (a-z, 0-9, _-)."
1996
+ ),
1403
1997
  /** Slug within the family. family+name identifies the definition across versions. */
1404
1998
  name: z.string().regex(DEFINITION_SLUG, "name must be a lowercase slug (a-z, 0-9, _-)."),
1405
1999
  /** The elicitation prompt — the queue row's plain-language question. */
@@ -1440,7 +2034,15 @@ z.object({
1440
2034
  /** Open-vocab kind label. Seeds above; customers may register any string. */
1441
2035
  kind: z.string().min(1),
1442
2036
  /** How was this event detected? Seed values below; customer sources allowed. */
1443
- detectedBy: z.enum(["harness", "sdk_flag", "sdk_rating", "sdk_thumbs", "worker_detector", "webhook", "sdk_custom"]).or(z.string().min(1)),
2037
+ detectedBy: z.enum([
2038
+ "harness",
2039
+ "sdk_flag",
2040
+ "sdk_rating",
2041
+ "sdk_thumbs",
2042
+ "worker_detector",
2043
+ "webhook",
2044
+ "sdk_custom"
2045
+ ]).or(z.string().min(1)),
1444
2046
  /** Optional turn index the event was caused by. Omitted → attaches to session's most recent turn. */
1445
2047
  causingTurnIndex: z.number().int().nonnegative().optional(),
1446
2048
  /** Optional detail payload (customer-defined). */
@@ -1455,6 +2057,7 @@ var DEFAULT_ENVIRONMENT_ALIGNMENT = {
1455
2057
  clock_source: "sdk",
1456
2058
  rule_version: "v1"
1457
2059
  };
2060
+ var SDK_ENVELOPE_VERSION = "sdk-envelope-v1";
1458
2061
  var DEFAULT_SPAN_ALIGNMENT = {
1459
2062
  clock_source: "sdk",
1460
2063
  rule_version: "v1"
@@ -1500,7 +2103,9 @@ var Probe = class {
1500
2103
  if (validated.persona?.signaturePhrases) {
1501
2104
  state.signatureMatchers.set(
1502
2105
  validated.persona.slug,
1503
- compileSignaturePhrases(validated.persona.signaturePhrases)
2106
+ compileSignaturePhrases(
2107
+ validated.persona.signaturePhrases
2108
+ )
1504
2109
  );
1505
2110
  }
1506
2111
  registerAllInstrumentations(state, (turn) => this.captureTurn(turn));
@@ -1689,8 +2294,14 @@ var Probe = class {
1689
2294
  }
1690
2295
  if (state === null) return;
1691
2296
  if (endedReason) {
1692
- await state.client.sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason }).catch((err) => {
1693
- console.warn("[sight] sendSessionEnd failed:", err instanceof Error ? err.message : err);
2297
+ await state.client.sendSessionEnd(state.config.deployment, {
2298
+ externalId: externalIdStr,
2299
+ endedReason
2300
+ }).catch((err) => {
2301
+ console.warn(
2302
+ "[sight] sendSessionEnd failed:",
2303
+ err instanceof Error ? err.message : err
2304
+ );
1694
2305
  });
1695
2306
  }
1696
2307
  state.sessions.delete(externalIdStr);
@@ -1906,6 +2517,7 @@ var Probe = class {
1906
2517
  session.lastAgentTurnAt = Date.now();
1907
2518
  await state.client.sendTurn({
1908
2519
  ...turn,
2520
+ envelopeVersion: SDK_ENVELOPE_VERSION,
1909
2521
  personaSlug: resolvedPersona,
1910
2522
  signaturePhraseMatches: signatureMatches,
1911
2523
  // User identity from the local session entry (Probe.startSession).
@@ -1946,7 +2558,11 @@ var Probe = class {
1946
2558
  console.warn("[sight] emitOutcomeEvent called before init");
1947
2559
  return;
1948
2560
  }
1949
- const validated = validateOrDrop(OutcomeEventEmitSchema, input, "emitOutcomeEvent");
2561
+ const validated = validateOrDrop(
2562
+ OutcomeEventEmitSchema,
2563
+ input,
2564
+ "emitOutcomeEvent"
2565
+ );
1950
2566
  if (validated === null) return;
1951
2567
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
1952
2568
  }
@@ -1968,10 +2584,21 @@ var Probe = class {
1968
2584
  console.warn("[sight] captureEnvironmentEvent called before init");
1969
2585
  return;
1970
2586
  }
1971
- const validated = validateOrDrop(EnvironmentEventInputSchema, event, "captureEnvironmentEvent");
2587
+ const validated = validateOrDrop(
2588
+ EnvironmentEventInputSchema,
2589
+ event,
2590
+ "captureEnvironmentEvent"
2591
+ );
1972
2592
  if (validated === null) return;
1973
- const align = alignment ? validateOrDrop(AlignmentProvenanceSchema, alignment, "captureEnvironmentEvent") ?? DEFAULT_ENVIRONMENT_ALIGNMENT : DEFAULT_ENVIRONMENT_ALIGNMENT;
1974
- await state.client.sendEnvironmentEvents({ events: [validated], alignment: align });
2593
+ const align = alignment ? validateOrDrop(
2594
+ AlignmentProvenanceSchema,
2595
+ alignment,
2596
+ "captureEnvironmentEvent"
2597
+ ) ?? DEFAULT_ENVIRONMENT_ALIGNMENT : DEFAULT_ENVIRONMENT_ALIGNMENT;
2598
+ await state.client.sendEnvironmentEvents({
2599
+ events: [validated],
2600
+ alignment: align
2601
+ });
1975
2602
  }
1976
2603
  /**
1977
2604
  * Capture a batch of environment events with explicit alignment provenance
@@ -1985,7 +2612,11 @@ var Probe = class {
1985
2612
  console.warn("[sight] captureEnvironmentEvents called before init");
1986
2613
  return;
1987
2614
  }
1988
- const batch = validateOrDrop(EnvironmentEventsBatchSchema, { events, alignment }, "captureEnvironmentEvents");
2615
+ const batch = validateOrDrop(
2616
+ EnvironmentEventsBatchSchema,
2617
+ { events, alignment },
2618
+ "captureEnvironmentEvents"
2619
+ );
1989
2620
  if (batch === null) return;
1990
2621
  await state.client.sendEnvironmentEvents(batch);
1991
2622
  }
@@ -2027,7 +2658,11 @@ var Probe = class {
2027
2658
  console.warn("[sight] captureSpans called before init");
2028
2659
  return;
2029
2660
  }
2030
- const batch = validateOrDrop(SpansBatchSchema, { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT }, "captureSpans");
2661
+ const batch = validateOrDrop(
2662
+ SpansBatchSchema,
2663
+ { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT },
2664
+ "captureSpans"
2665
+ );
2031
2666
  if (batch === null) return;
2032
2667
  await state.client.sendSpans(batch);
2033
2668
  }
@@ -2044,7 +2679,11 @@ var Probe = class {
2044
2679
  console.warn("[sight] flagPersonaBreak called before init");
2045
2680
  return;
2046
2681
  }
2047
- const validated = validateOrDrop(FlagPersonaBreakSchema, input, "flagPersonaBreak");
2682
+ const validated = validateOrDrop(
2683
+ FlagPersonaBreakSchema,
2684
+ input,
2685
+ "flagPersonaBreak"
2686
+ );
2048
2687
  if (validated === null) return;
2049
2688
  await state.client.sendFlag(state.config.deployment, validated);
2050
2689
  }
@@ -2098,6 +2737,6 @@ var Probe = class {
2098
2737
  }
2099
2738
  };
2100
2739
 
2101
- export { Probe, Probe as Sight };
2740
+ export { Probe, SPAN_INTERVAL_KINDS, SPAN_PAYLOAD_STATES, SPAN_STATUSES, SPAN_TYPES, SPAN_V2_STATUSES, Probe as Sight, SpanInputSchema, SpanInputV1Schema, SpanInputV2Schema, SpanIntervalSchema, SpanPayloadSchema, SpansBatchSchema, wrapOpenAI };
2102
2741
  //# sourceMappingURL=index.js.map
2103
2742
  //# sourceMappingURL=index.js.map