@cultured_computer/sight 0.1.0 → 0.2.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
@@ -2,14 +2,37 @@ import { z } from 'zod';
2
2
  import { propagation, context, trace } from '@opentelemetry/api';
3
3
 
4
4
  // src/client.ts
5
+ var DEFAULT_DASHBOARD_URL = "https://field.cultured.computer/dashboard";
6
+ var MAX_PENDING_RETRIES = 50;
5
7
  var IngestClient = class {
6
8
  apiKey;
7
9
  endpoint;
8
10
  debug;
11
+ dashboardUrl;
12
+ /**
13
+ * First-trace permalink ritual (PLAN-2026-07-14-adoptions A1): the first
14
+ * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,
15
+ * then never again for the life of this client (one IngestClient per
16
+ * process — one `init` per process; a restart prints once more, accepted).
17
+ * Failed sends do not consume the announcement. Only sendTurn announces:
18
+ * flags, outcome events, and session-end sends never trigger it (a flag
19
+ * arriving before any turn is not a captured session).
20
+ */
21
+ firstCaptureAnnounced = false;
22
+ /**
23
+ * Rate-limit (429) handling: the first 429 per process prints one stderr
24
+ * warning (not debug-gated, same channel and lifetime as the first-capture
25
+ * announce); subsequent 429s only debug-log. Each rate-limited request is
26
+ * retried exactly once after Retry-After; pendingRetries counts retries
27
+ * waiting on their timers so the cap can shed load.
28
+ */
29
+ rateLimitAnnounced = false;
30
+ pendingRetries = 0;
9
31
  constructor(opts) {
10
32
  this.apiKey = opts.apiKey;
11
33
  this.endpoint = opts.endpoint.replace(/\/$/, "");
12
34
  this.debug = opts.debug;
35
+ this.dashboardUrl = (opts.dashboardUrl ?? DEFAULT_DASHBOARD_URL).replace(/\/$/, "");
13
36
  }
14
37
  /**
15
38
  * Send a turn to the ingest API. Fire-and-log: errors are logged but never
@@ -17,7 +40,7 @@ var IngestClient = class {
17
40
  */
18
41
  async sendTurn(turn) {
19
42
  try {
20
- const response = await fetch(`${this.endpoint}/v1/turns`, {
43
+ const send = () => fetch(`${this.endpoint}/v1/turns`, {
21
44
  method: "POST",
22
45
  headers: {
23
46
  Authorization: `Bearer ${this.apiKey}`,
@@ -25,10 +48,18 @@ var IngestClient = class {
25
48
  },
26
49
  body: JSON.stringify(turn)
27
50
  });
51
+ const response = await this.retryIfRateLimited(await send(), send);
52
+ if (response === null) return;
28
53
  if (!response.ok) {
29
54
  this.log(`[probe] ingest failed status=${response.status}`);
30
55
  return;
31
56
  }
57
+ if (!this.firstCaptureAnnounced) {
58
+ this.firstCaptureAnnounced = true;
59
+ console.error(
60
+ `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`
61
+ );
62
+ }
32
63
  if (this.debug) {
33
64
  const body = await response.json();
34
65
  this.log(`[probe] ingest ok id=${body.pendingId ?? "?"}`);
@@ -44,7 +75,7 @@ var IngestClient = class {
44
75
  */
45
76
  async sendFlag(deploymentSlug, flag) {
46
77
  try {
47
- const response = await fetch(`${this.endpoint}/v1/flags`, {
78
+ const send = () => fetch(`${this.endpoint}/v1/flags`, {
48
79
  method: "POST",
49
80
  headers: {
50
81
  Authorization: `Bearer ${this.apiKey}`,
@@ -58,6 +89,8 @@ var IngestClient = class {
58
89
  turnIndex: flag.turnIndex
59
90
  })
60
91
  });
92
+ const response = await this.retryIfRateLimited(await send(), send);
93
+ if (response === null) return;
61
94
  if (!response.ok) {
62
95
  this.log(`[probe] flag ingest failed status=${response.status}`);
63
96
  return;
@@ -76,7 +109,7 @@ var IngestClient = class {
76
109
  */
77
110
  async sendSessionEnd(deploymentSlug, end) {
78
111
  try {
79
- const response = await fetch(`${this.endpoint}/v1/sessions/end`, {
112
+ const send = () => fetch(`${this.endpoint}/v1/sessions/end`, {
80
113
  method: "POST",
81
114
  headers: {
82
115
  Authorization: `Bearer ${this.apiKey}`,
@@ -88,6 +121,8 @@ var IngestClient = class {
88
121
  endedReason: end.endedReason
89
122
  })
90
123
  });
124
+ const response = await this.retryIfRateLimited(await send(), send);
125
+ if (response === null) return;
91
126
  if (!response.ok) {
92
127
  this.log(`[probe] session-end ingest failed status=${response.status}`);
93
128
  return;
@@ -106,7 +141,7 @@ var IngestClient = class {
106
141
  */
107
142
  async sendOutcomeEvent(deploymentSlug, event) {
108
143
  try {
109
- const response = await fetch(`${this.endpoint}/v1/outcome-events`, {
144
+ const send = () => fetch(`${this.endpoint}/v1/outcome-events`, {
110
145
  method: "POST",
111
146
  headers: {
112
147
  Authorization: `Bearer ${this.apiKey}`,
@@ -121,6 +156,8 @@ var IngestClient = class {
121
156
  detail: event.detail
122
157
  })
123
158
  });
159
+ const response = await this.retryIfRateLimited(await send(), send);
160
+ if (response === null) return;
124
161
  if (!response.ok) {
125
162
  this.log(`[probe] outcome-event ingest failed status=${response.status}`);
126
163
  return;
@@ -135,6 +172,44 @@ var IngestClient = class {
135
172
  this.log(`[probe] outcome-event ingest error: ${msg}`);
136
173
  }
137
174
  }
175
+ /**
176
+ * Route a send response through the 429 retry policy. Non-429 responses
177
+ * pass through untouched. A 429 is re-sent exactly once after Retry-After
178
+ * seconds (default 1s when the header is missing or unparseable; clamped
179
+ * to [1, 60]s); the retry's response is returned as-is, so a second 429 is
180
+ * never retried again — callers log and drop it like any other failed
181
+ * send. Returns null when the retry was dropped at the pending-retry cap.
182
+ * The timer is unref'd (where supported) so a pending retry never holds
183
+ * the process open.
184
+ */
185
+ async retryIfRateLimited(response, resend) {
186
+ if (response.status !== 429) return response;
187
+ if (!this.rateLimitAnnounced) {
188
+ this.rateLimitAnnounced = true;
189
+ console.error(
190
+ "Sight: ingest rate limit (429) \u2014 retrying once per Retry-After; sustained limiting drops captures. See https://field.cultured.computer/sight/sdk-reference#rate-limits"
191
+ );
192
+ } else {
193
+ this.log("[probe] ingest rate limited (429), retrying once");
194
+ }
195
+ if (this.pendingRetries >= MAX_PENDING_RETRIES) {
196
+ this.log("[probe] retry buffer full, dropped");
197
+ return null;
198
+ }
199
+ const raw = response.headers.get("retry-after");
200
+ const parsed = raw === null ? Number.NaN : Number(raw);
201
+ const seconds = Number.isFinite(parsed) ? Math.min(Math.max(parsed, 1), 60) : 1;
202
+ this.pendingRetries += 1;
203
+ try {
204
+ await new Promise((resolve) => {
205
+ const timer = setTimeout(resolve, seconds * 1e3);
206
+ timer.unref?.();
207
+ });
208
+ return await resend();
209
+ } finally {
210
+ this.pendingRetries -= 1;
211
+ }
212
+ }
138
213
  log(msg) {
139
214
  if (this.debug) {
140
215
  console.error(msg);
@@ -172,7 +247,13 @@ var PersonaConfigSchema = z.object({
172
247
  var OutcomeHookSchema = z.object({
173
248
  /** Type of outcome the deployment tracks. */
174
249
  type: z.enum(["numeric", "categorical", "boolean", "duration"]),
175
- /** Callback that resolves the outcome for a completed session. */
250
+ /**
251
+ * Callback that resolves the outcome for a completed session. Invoked by
252
+ * Probe.endSession() with the session's externalId; a non-null result
253
+ * lands as an outcome event on the session. Not invoked for sessions
254
+ * swept server-side (no explicit endSession) — use emitOutcomeEvent()
255
+ * for outcomes that become known out of band.
256
+ */
176
257
  resolve: z.custom()
177
258
  });
178
259
  var ProbeConfigSchema = z.object({
@@ -182,6 +263,13 @@ var ProbeConfigSchema = z.object({
182
263
  deployment: z.string().min(1),
183
264
  /** Ingest endpoint. Defaults to https://ingest.probe.io. */
184
265
  endpoint: z.string().url().default("https://ingest.probe.io"),
266
+ /**
267
+ * Dashboard base URL used by the one-time first-capture announcement
268
+ * (the stderr permalink printed after the first successful send).
269
+ * Self-hosted or staging dashboards override it the same way `endpoint`
270
+ * is overridden.
271
+ */
272
+ dashboardUrl: z.string().url().default("https://field.cultured.computer/dashboard"),
185
273
  /** Persona identification. Optional at init; can be set later via identifyPersona(). */
186
274
  persona: PersonaConfigSchema.optional(),
187
275
  /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */
@@ -316,6 +404,17 @@ function collectClientContext(includes = DEFAULT_INCLUDES) {
316
404
  }
317
405
  return out;
318
406
  }
407
+
408
+ // src/hash.ts
409
+ async function hashEnvironmentConfig(input) {
410
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
411
+ const bytes = new TextEncoder().encode(input);
412
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
413
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
414
+ }
415
+ const { createHash } = await import('crypto');
416
+ return createHash("sha256").update(input).digest("hex");
417
+ }
319
418
  var SESSION_BAGGAGE_KEY = "probe.session_id";
320
419
  var contextManagerRegistered = false;
321
420
  async function ensureContextManager() {
@@ -435,6 +534,92 @@ function buildPayload(span) {
435
534
  }
436
535
  };
437
536
  }
537
+ function messageText(content) {
538
+ if (typeof content === "string") return content;
539
+ if (Array.isArray(content)) {
540
+ const parts = [];
541
+ for (const part of content) {
542
+ if (typeof part === "string") {
543
+ parts.push(part);
544
+ } else if (part && typeof part === "object") {
545
+ const p = part;
546
+ const text = p["content"] ?? p["text"];
547
+ if (typeof text === "string") parts.push(text);
548
+ }
549
+ }
550
+ return parts.length > 0 ? parts.join("\n") : void 0;
551
+ }
552
+ return void 0;
553
+ }
554
+ function systemFromMessagesJson(raw) {
555
+ try {
556
+ const parsed = JSON.parse(raw);
557
+ if (!Array.isArray(parsed)) return void 0;
558
+ for (const msg of parsed) {
559
+ if (msg && typeof msg === "object") {
560
+ const m = msg;
561
+ if (m["role"] === "system") {
562
+ const text = messageText(m["content"] ?? m["parts"]);
563
+ if (text) return text;
564
+ }
565
+ }
566
+ }
567
+ } catch {
568
+ }
569
+ return void 0;
570
+ }
571
+ function extractSystemPromptText(attrs) {
572
+ const instructions = attrs["gen_ai.system_instructions"];
573
+ if (typeof instructions === "string" && instructions.length > 0) {
574
+ try {
575
+ const parsed = JSON.parse(instructions);
576
+ const text = messageText(parsed);
577
+ if (text) return text;
578
+ } catch {
579
+ return instructions;
580
+ }
581
+ return instructions;
582
+ }
583
+ const inputMessages = asString(attrs["gen_ai.input.messages"]);
584
+ if (inputMessages) {
585
+ const text = systemFromMessagesJson(inputMessages);
586
+ if (text) return text;
587
+ }
588
+ for (let i = 0; ; i++) {
589
+ const role = attrs[`gen_ai.prompt.${i}.role`];
590
+ if (role === void 0) break;
591
+ if (role === "system") {
592
+ const content = asString(attrs[`gen_ai.prompt.${i}.content`]);
593
+ if (content) return content;
594
+ }
595
+ }
596
+ const aiMessages = asString(attrs["ai.prompt.messages"]);
597
+ if (aiMessages) {
598
+ const text = systemFromMessagesJson(aiMessages);
599
+ if (text) return text;
600
+ }
601
+ const aiPrompt = asString(attrs["ai.prompt"]);
602
+ if (aiPrompt) {
603
+ try {
604
+ const parsed = JSON.parse(aiPrompt);
605
+ if (parsed && typeof parsed === "object") {
606
+ const system = parsed["system"];
607
+ if (typeof system === "string" && system.length > 0) return system;
608
+ }
609
+ } catch {
610
+ }
611
+ }
612
+ return void 0;
613
+ }
614
+ async function maybeAutoStampEnvironmentConfig(session, attrs) {
615
+ if (session.environmentConfigHash != null) return;
616
+ const systemText = extractSystemPromptText(attrs);
617
+ if (!systemText) return;
618
+ const hash = await hashEnvironmentConfig(systemText);
619
+ if (session.environmentConfigHash != null) return;
620
+ session.environmentConfigHash = hash;
621
+ session.environmentConfigLabel = `auto:${hash.slice(0, 8)}`;
622
+ }
438
623
  function resolveSessionAndTurn(state2, sessionId) {
439
624
  let session = state2.sessions.get(sessionId);
440
625
  if (!session) {
@@ -442,13 +627,16 @@ function resolveSessionAndTurn(state2, sessionId) {
442
627
  externalId: sessionId,
443
628
  turnIndex: 0,
444
629
  startedAt: Date.now(),
445
- personaSlug: state2.persona?.slug ?? null
630
+ personaSlug: state2.persona?.slug ?? null,
631
+ environmentConfigHash: null,
632
+ environmentConfigLabel: null
446
633
  };
447
634
  state2.sessions.set(sessionId, session);
448
635
  }
449
636
  const turnIndex = session.turnIndex;
450
637
  session.turnIndex += 1;
451
638
  return {
639
+ session,
452
640
  sessionExternalId: sessionId,
453
641
  turnIndex,
454
642
  personaSlug: session.personaSlug ?? state2.persona?.slug ?? null
@@ -479,7 +667,7 @@ var ProbeSpanProcessor = class {
479
667
  }
480
668
  return;
481
669
  }
482
- const { sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
670
+ const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
483
671
  this.state,
484
672
  sessionId
485
673
  );
@@ -490,7 +678,10 @@ var ProbeSpanProcessor = class {
490
678
  personaSlug: personaSlug ?? void 0,
491
679
  payload: buildPayload(span)
492
680
  };
493
- this.captureFn(captured).catch((err) => {
681
+ (async () => {
682
+ await maybeAutoStampEnvironmentConfig(session, a);
683
+ await this.captureFn(captured);
684
+ })().catch((err) => {
494
685
  if (this.state.config.debug) {
495
686
  console.error(
496
687
  `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
@@ -997,7 +1188,8 @@ var Probe = class {
997
1188
  const client = new IngestClient({
998
1189
  apiKey: validated.apiKey,
999
1190
  endpoint: validated.endpoint,
1000
- debug: validated.debug
1191
+ debug: validated.debug,
1192
+ dashboardUrl: validated.dashboardUrl
1001
1193
  });
1002
1194
  state = {
1003
1195
  config: validated,
@@ -1136,28 +1328,57 @@ var Probe = class {
1136
1328
  * Chapter 8e′ Card 3 (version behavioral diff) — every customer would
1137
1329
  * hash their own way and version-diff would become noise.
1138
1330
  *
1139
- * Node runtime; use dynamic import so the SDK stays browser-friendly
1140
- * for callers that never touch this helper.
1331
+ * The same hashing (src/hash.ts) backs the OTel processor's automatic
1332
+ * version stamping: when autocapture sees a system message and the
1333
+ * deployer set no environmentConfigHash, the session is stamped with
1334
+ * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit
1335
+ * startSession values always win over the auto stamp.
1141
1336
  */
1142
1337
  static async hashEnvironmentConfig(input) {
1143
- if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
1144
- const bytes = new TextEncoder().encode(input);
1145
- const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
1146
- return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
1147
- }
1148
- const { createHash } = await import('crypto');
1149
- return createHash("sha256").update(input).digest("hex");
1338
+ return hashEnvironmentConfig(input);
1150
1339
  }
1151
1340
  /**
1152
1341
  * End a session and release its in-memory entry. Optional (sessions time out
1153
1342
  * eventually), but recommended for long-running processes with many distinct
1154
1343
  * conversations. If `input.endedReason` is provided the SDK sends an end
1155
1344
  * event to ingest so the worker records the reason server-side.
1345
+ *
1346
+ * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`
1347
+ * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`
1348
+ * and, when it returns a non-null OutcomeResult, lands it as an outcome
1349
+ * event (kind = result.outcome, detail carries type/value). This is the
1350
+ * ONLY place the SDK invokes the hook — there are no client-side timers,
1351
+ * so sessions that are never ended explicitly are swept server-side as
1352
+ * `timeout` and receive no hook-resolved outcome; land those via
1353
+ * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:
1354
+ * a throwing or rejecting hook never breaks endSession.
1156
1355
  */
1157
1356
  static async endSession(externalId) {
1158
1357
  if (state === null) return;
1159
1358
  const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
1160
1359
  const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
1360
+ if (state.outcomeHook) {
1361
+ try {
1362
+ const result = await state.outcomeHook.resolve(externalIdStr);
1363
+ if (result && state !== null) {
1364
+ await this.emitOutcomeEvent({
1365
+ sessionExternalId: externalIdStr,
1366
+ kind: result.outcome,
1367
+ detail: {
1368
+ type: result.type,
1369
+ value: result.value,
1370
+ resolvedBy: "outcome_hook"
1371
+ }
1372
+ });
1373
+ }
1374
+ } catch (err) {
1375
+ console.warn(
1376
+ "[probe] outcome hook resolve failed:",
1377
+ err instanceof Error ? err.message : err
1378
+ );
1379
+ }
1380
+ }
1381
+ if (state === null) return;
1161
1382
  if (endedReason) {
1162
1383
  await state.client.sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason }).catch((err) => {
1163
1384
  console.warn("[probe] sendSessionEnd failed:", err instanceof Error ? err.message : err);
@@ -1248,9 +1469,11 @@ var Probe = class {
1248
1469
  }
1249
1470
  /**
1250
1471
  * Register the outcome hook: declares the deployment's outcome type and
1251
- * the resolver for it. NOTE: automatic invocation on session close is
1252
- * not wired in the current build — the hook is stored but nothing calls
1253
- * `resolve` yet. To land a downstream outcome on a session today, call
1472
+ * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked
1473
+ * by endSession() — explicit close is the only trigger; the SDK runs no
1474
+ * client-side timers. A non-null OutcomeResult lands as an outcome event
1475
+ * on the session. Sessions that are never ended explicitly are swept
1476
+ * server-side and never resolve through the hook; land those outcomes via
1254
1477
  * emitOutcomeEvent() from the place where the outcome becomes known
1255
1478
  * (webhook, CRM callback); it joins back by sessionExternalId.
1256
1479
  */