@cultured_computer/sight 0.3.2 → 0.3.3

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.d.cts CHANGED
@@ -980,6 +980,15 @@ declare class IngestClient {
980
980
  */
981
981
  private rateLimitAnnounced;
982
982
  private pendingRetries;
983
+ private inFlight;
984
+ private shedAnnounced;
985
+ /**
986
+ * Every network send goes through here: adds the per-send timeout and
987
+ * the in-flight cap (audit B1). At the cap, the send is SHED — thrown
988
+ * into the caller's existing fire-and-log catch — rather than queued;
989
+ * the first shed per process warns on stderr, the rest debug-log.
990
+ */
991
+ private guardedFetch;
983
992
  constructor(opts: IngestClientOptions);
984
993
  /**
985
994
  * Send a turn to the ingest API. Fire-and-log: errors are logged but never
@@ -1140,6 +1149,7 @@ type PreSessionSignals = {
1140
1149
  pendingUserOutcome: SessionState['pendingUserOutcome'];
1141
1150
  lastUserSubmitAt: number | null;
1142
1151
  };
1152
+
1143
1153
  type SessionState = {
1144
1154
  externalId: string;
1145
1155
  /** Customer's user identity from startSession; forwarded on every turn. */
@@ -1350,7 +1360,7 @@ declare class Probe {
1350
1360
  * generalized envelope and fire-and-log discipline as the single-event
1351
1361
  * capture above.
1352
1362
  */
1353
- static captureEnvironmentEvents(events: EnvironmentEventInput[], alignment: AlignmentProvenance): Promise<void>;
1363
+ static captureEnvironmentEvents(events: EnvironmentEventInput[], alignment?: AlignmentProvenance): Promise<void>;
1354
1364
  /**
1355
1365
  * Capture one sub-turn span against a session: one LLM call, one tool
1356
1366
  * call, one framework step, or a custom unit inside a turn. The span lands
@@ -1375,7 +1385,7 @@ declare class Probe {
1375
1385
  * (unresolvable references land null). Same fire-and-log discipline as the
1376
1386
  * single-span capture above.
1377
1387
  */
1378
- static captureSpans(spans: SpanInput[], alignment: AlignmentProvenance): Promise<void>;
1388
+ static captureSpans(spans: SpanInput[], alignment?: AlignmentProvenance): Promise<void>;
1379
1389
  /**
1380
1390
  * Flag a persona break for a session. Wire this to the customer's in-product
1381
1391
  * "that didn't sound like you" UX. Populates the `user_flagged_break`
package/dist/index.d.ts CHANGED
@@ -980,6 +980,15 @@ declare class IngestClient {
980
980
  */
981
981
  private rateLimitAnnounced;
982
982
  private pendingRetries;
983
+ private inFlight;
984
+ private shedAnnounced;
985
+ /**
986
+ * Every network send goes through here: adds the per-send timeout and
987
+ * the in-flight cap (audit B1). At the cap, the send is SHED — thrown
988
+ * into the caller's existing fire-and-log catch — rather than queued;
989
+ * the first shed per process warns on stderr, the rest debug-log.
990
+ */
991
+ private guardedFetch;
983
992
  constructor(opts: IngestClientOptions);
984
993
  /**
985
994
  * Send a turn to the ingest API. Fire-and-log: errors are logged but never
@@ -1140,6 +1149,7 @@ type PreSessionSignals = {
1140
1149
  pendingUserOutcome: SessionState['pendingUserOutcome'];
1141
1150
  lastUserSubmitAt: number | null;
1142
1151
  };
1152
+
1143
1153
  type SessionState = {
1144
1154
  externalId: string;
1145
1155
  /** Customer's user identity from startSession; forwarded on every turn. */
@@ -1350,7 +1360,7 @@ declare class Probe {
1350
1360
  * generalized envelope and fire-and-log discipline as the single-event
1351
1361
  * capture above.
1352
1362
  */
1353
- static captureEnvironmentEvents(events: EnvironmentEventInput[], alignment: AlignmentProvenance): Promise<void>;
1363
+ static captureEnvironmentEvents(events: EnvironmentEventInput[], alignment?: AlignmentProvenance): Promise<void>;
1354
1364
  /**
1355
1365
  * Capture one sub-turn span against a session: one LLM call, one tool
1356
1366
  * call, one framework step, or a custom unit inside a turn. The span lands
@@ -1375,7 +1385,7 @@ declare class Probe {
1375
1385
  * (unresolvable references land null). Same fire-and-log discipline as the
1376
1386
  * single-span capture above.
1377
1387
  */
1378
- static captureSpans(spans: SpanInput[], alignment: AlignmentProvenance): Promise<void>;
1388
+ static captureSpans(spans: SpanInput[], alignment?: AlignmentProvenance): Promise<void>;
1379
1389
  /**
1380
1390
  * Flag a persona break for a session. Wire this to the customer's in-product
1381
1391
  * "that didn't sound like you" UX. Populates the `user_flagged_break`
package/dist/index.js CHANGED
@@ -4,6 +4,9 @@ import { propagation, context, trace } from '@opentelemetry/api';
4
4
  // src/client.ts
5
5
  var DEFAULT_DASHBOARD_URL = "https://field.cultured.computer/dashboard";
6
6
  var MAX_PENDING_RETRIES = 50;
7
+ var SEND_TIMEOUT_MS = 15e3;
8
+ var MAX_INFLIGHT = 64;
9
+ var MAX_TURN_BODY_BYTES = 9e5;
7
10
  var IngestClient = class {
8
11
  apiKey;
9
12
  endpoint;
@@ -28,6 +31,31 @@ var IngestClient = class {
28
31
  */
29
32
  rateLimitAnnounced = false;
30
33
  pendingRetries = 0;
34
+ inFlight = 0;
35
+ shedAnnounced = false;
36
+ /**
37
+ * Every network send goes through here: adds the per-send timeout and
38
+ * the in-flight cap (audit B1). At the cap, the send is SHED — thrown
39
+ * into the caller's existing fire-and-log catch — rather than queued;
40
+ * the first shed per process warns on stderr, the rest debug-log.
41
+ */
42
+ async guardedFetch(url, init) {
43
+ if (this.inFlight >= MAX_INFLIGHT) {
44
+ if (!this.shedAnnounced) {
45
+ this.shedAnnounced = true;
46
+ console.error(
47
+ `[sight] ${MAX_INFLIGHT} sends already in flight \u2014 shedding new sends (ingest slow or unreachable; this warning prints once)`
48
+ );
49
+ }
50
+ throw new Error("in-flight cap reached \u2014 send shed");
51
+ }
52
+ this.inFlight++;
53
+ try {
54
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });
55
+ } finally {
56
+ this.inFlight--;
57
+ }
58
+ }
31
59
  constructor(opts) {
32
60
  this.apiKey = opts.apiKey;
33
61
  this.endpoint = opts.endpoint.replace(/\/$/, "");
@@ -40,13 +68,20 @@ var IngestClient = class {
40
68
  */
41
69
  async sendTurn(turn) {
42
70
  try {
43
- const send = () => fetch(`${this.endpoint}/v1/turns`, {
71
+ const body = JSON.stringify(turn);
72
+ if (body.length > MAX_TURN_BODY_BYTES) {
73
+ this.log(
74
+ `[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`
75
+ );
76
+ return;
77
+ }
78
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/turns`, {
44
79
  method: "POST",
45
80
  headers: {
46
81
  Authorization: `Bearer ${this.apiKey}`,
47
82
  "content-type": "application/json"
48
83
  },
49
- body: JSON.stringify(turn)
84
+ body
50
85
  });
51
86
  const response = await this.retryIfRateLimited(await send(), send);
52
87
  if (response === null) return;
@@ -61,8 +96,8 @@ var IngestClient = class {
61
96
  );
62
97
  }
63
98
  if (this.debug) {
64
- const body = await response.json();
65
- this.log(`[sight] ingest ok id=${body.pendingId ?? "?"}`);
99
+ const body2 = await response.json();
100
+ this.log(`[sight] ingest ok id=${body2.pendingId ?? "?"}`);
66
101
  }
67
102
  } catch (err) {
68
103
  const msg = err instanceof Error ? err.message : String(err);
@@ -75,7 +110,7 @@ var IngestClient = class {
75
110
  */
76
111
  async sendFlag(deploymentSlug, flag) {
77
112
  try {
78
- const send = () => fetch(`${this.endpoint}/v1/flags`, {
113
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/flags`, {
79
114
  method: "POST",
80
115
  headers: {
81
116
  Authorization: `Bearer ${this.apiKey}`,
@@ -109,7 +144,7 @@ var IngestClient = class {
109
144
  */
110
145
  async sendSessionEnd(deploymentSlug, end) {
111
146
  try {
112
- const send = () => fetch(`${this.endpoint}/v1/sessions/end`, {
147
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/sessions/end`, {
113
148
  method: "POST",
114
149
  headers: {
115
150
  Authorization: `Bearer ${this.apiKey}`,
@@ -141,7 +176,7 @@ var IngestClient = class {
141
176
  */
142
177
  async sendOutcomeEvent(deploymentSlug, event) {
143
178
  try {
144
- const send = () => fetch(`${this.endpoint}/v1/outcome-events`, {
179
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/outcome-events`, {
145
180
  method: "POST",
146
181
  headers: {
147
182
  Authorization: `Bearer ${this.apiKey}`,
@@ -179,7 +214,7 @@ var IngestClient = class {
179
214
  */
180
215
  async sendEnvironmentEvents(batch) {
181
216
  try {
182
- const send = () => fetch(`${this.endpoint}/v1/environment-events`, {
217
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/environment-events`, {
183
218
  method: "POST",
184
219
  headers: {
185
220
  Authorization: `Bearer ${this.apiKey}`,
@@ -209,7 +244,7 @@ var IngestClient = class {
209
244
  */
210
245
  async sendSpans(batch) {
211
246
  try {
212
- const send = () => fetch(`${this.endpoint}/v1/spans`, {
247
+ const send = () => this.guardedFetch(`${this.endpoint}/v1/spans`, {
213
248
  method: "POST",
214
249
  headers: {
215
250
  Authorization: `Bearer ${this.apiKey}`,
@@ -466,6 +501,16 @@ function collectClientContext(includes = DEFAULT_INCLUDES) {
466
501
  return out;
467
502
  }
468
503
 
504
+ // src/session-bounds.ts
505
+ var MAX_TRACKED_SESSIONS = 5e3;
506
+ function boundedSessionSet(sessions, key, session) {
507
+ if (!sessions.has(key) && sessions.size >= MAX_TRACKED_SESSIONS) {
508
+ const oldest = sessions.keys().next().value;
509
+ if (oldest !== void 0) sessions.delete(oldest);
510
+ }
511
+ sessions.set(key, session);
512
+ }
513
+
469
514
  // src/hash.ts
470
515
  async function hashEnvironmentConfig(input) {
471
516
  if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
@@ -692,7 +737,7 @@ function resolveSessionAndTurn(state2, sessionId) {
692
737
  environmentConfigHash: null,
693
738
  environmentConfigLabel: null
694
739
  };
695
- state2.sessions.set(sessionId, session);
740
+ boundedSessionSet(state2.sessions, sessionId, session);
696
741
  }
697
742
  const turnIndex = session.turnIndex;
698
743
  session.turnIndex += 1;
@@ -710,10 +755,23 @@ var ProbeSpanProcessor = class {
710
755
  }
711
756
  state;
712
757
  captureFn;
758
+ /**
759
+ * Re-point the processor at a new Probe state (or null after shutdown).
760
+ * A registered span processor cannot be removed from a provider, so
761
+ * re-init REBINDS instead of orphaning: without this, autocapture after
762
+ * shutdown()/re-init kept mutating the dead state's sessions map and
763
+ * stamping the old deployment slug (production-safety audit R1).
764
+ */
765
+ rebind(state2, captureFn) {
766
+ this.state = state2;
767
+ if (captureFn) this.captureFn = captureFn;
768
+ }
713
769
  onStart(_span, _parentContext) {
714
770
  }
715
771
  onEnd(span) {
716
772
  try {
773
+ if (this.state === null) return;
774
+ const state2 = this.state;
717
775
  const a = span.attributes;
718
776
  if (isVercelAgentRollup(span.name, a)) return;
719
777
  if (!isLLMCall(a)) return;
@@ -721,7 +779,7 @@ var ProbeSpanProcessor = class {
721
779
  if (shouldSkipAsDuplicate(traceId)) return;
722
780
  const sessionId = getCurrentSessionId();
723
781
  if (!sessionId) {
724
- if (this.state.config.debug) {
782
+ if (state2.config.debug) {
725
783
  console.warn(
726
784
  `[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`
727
785
  );
@@ -729,11 +787,11 @@ var ProbeSpanProcessor = class {
729
787
  return;
730
788
  }
731
789
  const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
732
- this.state,
790
+ state2,
733
791
  sessionId
734
792
  );
735
793
  const captured = {
736
- deploymentSlug: this.state.config.deployment,
794
+ deploymentSlug: state2.config.deployment,
737
795
  sessionExternalId,
738
796
  turnIndex,
739
797
  personaSlug: personaSlug ?? void 0,
@@ -743,14 +801,14 @@ var ProbeSpanProcessor = class {
743
801
  await maybeAutoStampEnvironmentConfig(session, a);
744
802
  await this.captureFn(captured);
745
803
  })().catch((err) => {
746
- if (this.state.config.debug) {
804
+ if (state2.config.debug) {
747
805
  console.error(
748
806
  `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
749
807
  );
750
808
  }
751
809
  });
752
810
  } catch (err) {
753
- if (this.state.config.debug) {
811
+ if (this.state?.config.debug) {
754
812
  console.error(
755
813
  `[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`
756
814
  );
@@ -770,6 +828,7 @@ var ProbeSpanProcessor = class {
770
828
  var installedProcessor = null;
771
829
  function setupOtelProvider(state2, captureFn) {
772
830
  if (installedProcessor !== null) {
831
+ installedProcessor.rebind(state2, captureFn);
773
832
  return;
774
833
  }
775
834
  installedProcessor = new ProbeSpanProcessor(state2, captureFn);
@@ -785,6 +844,9 @@ function setupOtelProvider(state2, captureFn) {
785
844
  provider.register();
786
845
  });
787
846
  }
847
+ function detachOtelState() {
848
+ installedProcessor?.rebind(null);
849
+ }
788
850
 
789
851
  // src/instrumentation/openai.ts
790
852
  var registered = false;
@@ -1382,6 +1444,17 @@ var DEFAULT_SPAN_ALIGNMENT = {
1382
1444
  rule_version: "v1"
1383
1445
  };
1384
1446
  var state = null;
1447
+ function validateOrDrop(schema, input, method) {
1448
+ const result = schema.safeParse(input);
1449
+ if (!result.success) {
1450
+ const issue = result.error?.issues?.[0];
1451
+ console.warn(
1452
+ `[sight] ${method}: invalid input dropped \u2014 ${issue ? `${issue.path?.join(".") || "(root)"}: ${issue.message}` : "schema mismatch"}`
1453
+ );
1454
+ return null;
1455
+ }
1456
+ return result.data;
1457
+ }
1385
1458
  var Probe = class {
1386
1459
  /**
1387
1460
  * Initialize the Probe SDK. Call once at process start. Subsequent calls are
@@ -1465,7 +1538,8 @@ var Probe = class {
1465
1538
  console.warn("[sight] startSession called before init");
1466
1539
  return;
1467
1540
  }
1468
- const validated = SessionStartSchema.parse(input);
1541
+ const validated = validateOrDrop(SessionStartSchema, input, "startSession");
1542
+ if (validated === null) return;
1469
1543
  const existing = state.sessions.get(validated.externalId);
1470
1544
  const now = Date.now();
1471
1545
  const session = {
@@ -1488,7 +1562,7 @@ var Probe = class {
1488
1562
  pendingUserOutcome: existing?.pendingUserOutcome ?? null
1489
1563
  };
1490
1564
  this.flushPreSessionSignals(validated.externalId, session);
1491
- state.sessions.set(validated.externalId, session);
1565
+ boundedSessionSet(state.sessions, validated.externalId, session);
1492
1566
  }
1493
1567
  /**
1494
1568
  * Move buffered pre-session interaction signals (recorded before any
@@ -1723,6 +1797,9 @@ var Probe = class {
1723
1797
  if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
1724
1798
  return;
1725
1799
  }
1800
+ if (turn.payload === void 0 || turn.payload === null) {
1801
+ turn = { ...turn, payload: {} };
1802
+ }
1726
1803
  const propensity = turn.propensity ?? turn.payload.propensity;
1727
1804
  let validPropensity = propensity;
1728
1805
  if (propensity) {
@@ -1739,10 +1816,14 @@ var Probe = class {
1739
1816
  const resolvedPersona = turn.personaSlug ?? sessionPersona ?? state.persona?.slug ?? void 0;
1740
1817
  let signatureMatches = turn.signaturePhraseMatches;
1741
1818
  if (!signatureMatches && resolvedPersona) {
1742
- const matcher = state.signatureMatchers.get(resolvedPersona);
1743
- if (matcher && matcher.length > 0) {
1744
- const text = this.extractTextForMatching(turn.payload);
1745
- signatureMatches = text ? matchSignaturePhrases(text, matcher) : [];
1819
+ try {
1820
+ const matcher = state.signatureMatchers.get(resolvedPersona);
1821
+ if (matcher && matcher.length > 0) {
1822
+ const text = this.extractTextForMatching(turn.payload);
1823
+ signatureMatches = text ? matchSignaturePhrases(text, matcher) : [];
1824
+ }
1825
+ } catch {
1826
+ signatureMatches = [];
1746
1827
  }
1747
1828
  }
1748
1829
  let session = state.sessions.get(turn.sessionExternalId);
@@ -1766,7 +1847,7 @@ var Probe = class {
1766
1847
  pendingUserInput: null,
1767
1848
  pendingUserOutcome: null
1768
1849
  };
1769
- state.sessions.set(turn.sessionExternalId, session);
1850
+ boundedSessionSet(state.sessions, turn.sessionExternalId, session);
1770
1851
  }
1771
1852
  this.flushPreSessionSignals(turn.sessionExternalId, session);
1772
1853
  let userInput = turn.userInput;
@@ -1849,7 +1930,8 @@ var Probe = class {
1849
1930
  console.warn("[sight] emitOutcomeEvent called before init");
1850
1931
  return;
1851
1932
  }
1852
- const validated = OutcomeEventEmitSchema.parse(input);
1933
+ const validated = validateOrDrop(OutcomeEventEmitSchema, input, "emitOutcomeEvent");
1934
+ if (validated === null) return;
1853
1935
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
1854
1936
  }
1855
1937
  /**
@@ -1870,8 +1952,9 @@ var Probe = class {
1870
1952
  console.warn("[sight] captureEnvironmentEvent called before init");
1871
1953
  return;
1872
1954
  }
1873
- const validated = EnvironmentEventInputSchema.parse(event);
1874
- const align = alignment ? AlignmentProvenanceSchema.parse(alignment) : DEFAULT_ENVIRONMENT_ALIGNMENT;
1955
+ const validated = validateOrDrop(EnvironmentEventInputSchema, event, "captureEnvironmentEvent");
1956
+ if (validated === null) return;
1957
+ const align = alignment ? validateOrDrop(AlignmentProvenanceSchema, alignment, "captureEnvironmentEvent") ?? DEFAULT_ENVIRONMENT_ALIGNMENT : DEFAULT_ENVIRONMENT_ALIGNMENT;
1875
1958
  await state.client.sendEnvironmentEvents({ events: [validated], alignment: align });
1876
1959
  }
1877
1960
  /**
@@ -1881,12 +1964,13 @@ var Probe = class {
1881
1964
  * generalized envelope and fire-and-log discipline as the single-event
1882
1965
  * capture above.
1883
1966
  */
1884
- static async captureEnvironmentEvents(events, alignment) {
1967
+ static async captureEnvironmentEvents(events, alignment = DEFAULT_ENVIRONMENT_ALIGNMENT) {
1885
1968
  if (state === null) {
1886
1969
  console.warn("[sight] captureEnvironmentEvents called before init");
1887
1970
  return;
1888
1971
  }
1889
- const batch = EnvironmentEventsBatchSchema.parse({ events, alignment });
1972
+ const batch = validateOrDrop(EnvironmentEventsBatchSchema, { events, alignment }, "captureEnvironmentEvents");
1973
+ if (batch === null) return;
1890
1974
  await state.client.sendEnvironmentEvents(batch);
1891
1975
  }
1892
1976
  /**
@@ -1908,8 +1992,9 @@ var Probe = class {
1908
1992
  console.warn("[sight] captureSpan called before init");
1909
1993
  return;
1910
1994
  }
1911
- const validated = SpanInputSchema.parse(span);
1912
- const align = alignment ? AlignmentProvenanceSchema.parse(alignment) : DEFAULT_SPAN_ALIGNMENT;
1995
+ const validated = validateOrDrop(SpanInputSchema, span, "captureSpan");
1996
+ if (validated === null) return;
1997
+ const align = alignment ? validateOrDrop(AlignmentProvenanceSchema, alignment, "captureSpan") ?? DEFAULT_SPAN_ALIGNMENT : DEFAULT_SPAN_ALIGNMENT;
1913
1998
  await state.client.sendSpans({ spans: [validated], alignment: align });
1914
1999
  }
1915
2000
  /**
@@ -1926,7 +2011,8 @@ var Probe = class {
1926
2011
  console.warn("[sight] captureSpans called before init");
1927
2012
  return;
1928
2013
  }
1929
- const batch = SpansBatchSchema.parse({ spans, alignment });
2014
+ const batch = validateOrDrop(SpansBatchSchema, { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT }, "captureSpans");
2015
+ if (batch === null) return;
1930
2016
  await state.client.sendSpans(batch);
1931
2017
  }
1932
2018
  /**
@@ -1942,7 +2028,8 @@ var Probe = class {
1942
2028
  console.warn("[sight] flagPersonaBreak called before init");
1943
2029
  return;
1944
2030
  }
1945
- const validated = FlagPersonaBreakSchema.parse(input);
2031
+ const validated = validateOrDrop(FlagPersonaBreakSchema, input, "flagPersonaBreak");
2032
+ if (validated === null) return;
1946
2033
  await state.client.sendFlag(state.config.deployment, validated);
1947
2034
  }
1948
2035
  /**
@@ -1970,6 +2057,7 @@ var Probe = class {
1970
2057
  if (state === null) {
1971
2058
  return;
1972
2059
  }
2060
+ detachOtelState();
1973
2061
  state = null;
1974
2062
  }
1975
2063
  // ── Internal helpers ─────────────────────────────────────────────────────