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