@cultured_computer/sight 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -85,13 +85,13 @@ live experiment.
85
85
 
86
86
  ## Docs
87
87
 
88
- - [Get started](https://field.cultured.computer/sight/docs/get-started):
88
+ - [Get started](https://field.cultured.computer/sight/get-started):
89
89
  install, initialise, verify capture.
90
- - [Worked examples](https://field.cultured.computer/sight/docs/examples):
90
+ - [Worked examples](https://field.cultured.computer/sight/examples):
91
91
  runnable snippets, each with what it lands in the record.
92
- - [SDK reference](https://field.cultured.computer/sight/docs/sdk-reference):
92
+ - [SDK reference](https://field.cultured.computer/sight/sdk-reference):
93
93
  the full method surface.
94
- - [Status](https://field.cultured.computer/sight/docs/where-it-stands): what
94
+ - [Status](https://field.cultured.computer/sight/where-it-stands): what
95
95
  is available now versus in beta.
96
96
 
97
97
  ## License
package/dist/index.cjs CHANGED
@@ -4,14 +4,27 @@ var zod = require('zod');
4
4
  var api = require('@opentelemetry/api');
5
5
 
6
6
  // src/client.ts
7
+ var DEFAULT_DASHBOARD_URL = "https://field.cultured.computer/dashboard";
7
8
  var IngestClient = class {
8
9
  apiKey;
9
10
  endpoint;
10
11
  debug;
12
+ dashboardUrl;
13
+ /**
14
+ * First-trace permalink ritual (PLAN-2026-07-14-adoptions A1): the first
15
+ * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,
16
+ * then never again for the life of this client (one IngestClient per
17
+ * process — one `init` per process; a restart prints once more, accepted).
18
+ * Failed sends do not consume the announcement. Only sendTurn announces:
19
+ * flags, outcome events, and session-end sends never trigger it (a flag
20
+ * arriving before any turn is not a captured session).
21
+ */
22
+ firstCaptureAnnounced = false;
11
23
  constructor(opts) {
12
24
  this.apiKey = opts.apiKey;
13
25
  this.endpoint = opts.endpoint.replace(/\/$/, "");
14
26
  this.debug = opts.debug;
27
+ this.dashboardUrl = (opts.dashboardUrl ?? DEFAULT_DASHBOARD_URL).replace(/\/$/, "");
15
28
  }
16
29
  /**
17
30
  * Send a turn to the ingest API. Fire-and-log: errors are logged but never
@@ -31,6 +44,12 @@ var IngestClient = class {
31
44
  this.log(`[probe] ingest failed status=${response.status}`);
32
45
  return;
33
46
  }
47
+ if (!this.firstCaptureAnnounced) {
48
+ this.firstCaptureAnnounced = true;
49
+ console.error(
50
+ `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`
51
+ );
52
+ }
34
53
  if (this.debug) {
35
54
  const body = await response.json();
36
55
  this.log(`[probe] ingest ok id=${body.pendingId ?? "?"}`);
@@ -174,7 +193,13 @@ var PersonaConfigSchema = zod.z.object({
174
193
  var OutcomeHookSchema = zod.z.object({
175
194
  /** Type of outcome the deployment tracks. */
176
195
  type: zod.z.enum(["numeric", "categorical", "boolean", "duration"]),
177
- /** Callback that resolves the outcome for a completed session. */
196
+ /**
197
+ * Callback that resolves the outcome for a completed session. Invoked by
198
+ * Probe.endSession() with the session's externalId; a non-null result
199
+ * lands as an outcome event on the session. Not invoked for sessions
200
+ * swept server-side (no explicit endSession) — use emitOutcomeEvent()
201
+ * for outcomes that become known out of band.
202
+ */
178
203
  resolve: zod.z.custom()
179
204
  });
180
205
  var ProbeConfigSchema = zod.z.object({
@@ -184,6 +209,13 @@ var ProbeConfigSchema = zod.z.object({
184
209
  deployment: zod.z.string().min(1),
185
210
  /** Ingest endpoint. Defaults to https://ingest.probe.io. */
186
211
  endpoint: zod.z.string().url().default("https://ingest.probe.io"),
212
+ /**
213
+ * Dashboard base URL used by the one-time first-capture announcement
214
+ * (the stderr permalink printed after the first successful send).
215
+ * Self-hosted or staging dashboards override it the same way `endpoint`
216
+ * is overridden.
217
+ */
218
+ dashboardUrl: zod.z.string().url().default("https://field.cultured.computer/dashboard"),
187
219
  /** Persona identification. Optional at init; can be set later via identifyPersona(). */
188
220
  persona: PersonaConfigSchema.optional(),
189
221
  /** Outcome hook. Optional at init; can be set later via wireOutcomeHook(). */
@@ -318,6 +350,17 @@ function collectClientContext(includes = DEFAULT_INCLUDES) {
318
350
  }
319
351
  return out;
320
352
  }
353
+
354
+ // src/hash.ts
355
+ async function hashEnvironmentConfig(input) {
356
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
357
+ const bytes = new TextEncoder().encode(input);
358
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
359
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
360
+ }
361
+ const { createHash } = await import('crypto');
362
+ return createHash("sha256").update(input).digest("hex");
363
+ }
321
364
  var SESSION_BAGGAGE_KEY = "probe.session_id";
322
365
  var contextManagerRegistered = false;
323
366
  async function ensureContextManager() {
@@ -437,6 +480,92 @@ function buildPayload(span) {
437
480
  }
438
481
  };
439
482
  }
483
+ function messageText(content) {
484
+ if (typeof content === "string") return content;
485
+ if (Array.isArray(content)) {
486
+ const parts = [];
487
+ for (const part of content) {
488
+ if (typeof part === "string") {
489
+ parts.push(part);
490
+ } else if (part && typeof part === "object") {
491
+ const p = part;
492
+ const text = p["content"] ?? p["text"];
493
+ if (typeof text === "string") parts.push(text);
494
+ }
495
+ }
496
+ return parts.length > 0 ? parts.join("\n") : void 0;
497
+ }
498
+ return void 0;
499
+ }
500
+ function systemFromMessagesJson(raw) {
501
+ try {
502
+ const parsed = JSON.parse(raw);
503
+ if (!Array.isArray(parsed)) return void 0;
504
+ for (const msg of parsed) {
505
+ if (msg && typeof msg === "object") {
506
+ const m = msg;
507
+ if (m["role"] === "system") {
508
+ const text = messageText(m["content"] ?? m["parts"]);
509
+ if (text) return text;
510
+ }
511
+ }
512
+ }
513
+ } catch {
514
+ }
515
+ return void 0;
516
+ }
517
+ function extractSystemPromptText(attrs) {
518
+ const instructions = attrs["gen_ai.system_instructions"];
519
+ if (typeof instructions === "string" && instructions.length > 0) {
520
+ try {
521
+ const parsed = JSON.parse(instructions);
522
+ const text = messageText(parsed);
523
+ if (text) return text;
524
+ } catch {
525
+ return instructions;
526
+ }
527
+ return instructions;
528
+ }
529
+ const inputMessages = asString(attrs["gen_ai.input.messages"]);
530
+ if (inputMessages) {
531
+ const text = systemFromMessagesJson(inputMessages);
532
+ if (text) return text;
533
+ }
534
+ for (let i = 0; ; i++) {
535
+ const role = attrs[`gen_ai.prompt.${i}.role`];
536
+ if (role === void 0) break;
537
+ if (role === "system") {
538
+ const content = asString(attrs[`gen_ai.prompt.${i}.content`]);
539
+ if (content) return content;
540
+ }
541
+ }
542
+ const aiMessages = asString(attrs["ai.prompt.messages"]);
543
+ if (aiMessages) {
544
+ const text = systemFromMessagesJson(aiMessages);
545
+ if (text) return text;
546
+ }
547
+ const aiPrompt = asString(attrs["ai.prompt"]);
548
+ if (aiPrompt) {
549
+ try {
550
+ const parsed = JSON.parse(aiPrompt);
551
+ if (parsed && typeof parsed === "object") {
552
+ const system = parsed["system"];
553
+ if (typeof system === "string" && system.length > 0) return system;
554
+ }
555
+ } catch {
556
+ }
557
+ }
558
+ return void 0;
559
+ }
560
+ async function maybeAutoStampEnvironmentConfig(session, attrs) {
561
+ if (session.environmentConfigHash != null) return;
562
+ const systemText = extractSystemPromptText(attrs);
563
+ if (!systemText) return;
564
+ const hash = await hashEnvironmentConfig(systemText);
565
+ if (session.environmentConfigHash != null) return;
566
+ session.environmentConfigHash = hash;
567
+ session.environmentConfigLabel = `auto:${hash.slice(0, 8)}`;
568
+ }
440
569
  function resolveSessionAndTurn(state2, sessionId) {
441
570
  let session = state2.sessions.get(sessionId);
442
571
  if (!session) {
@@ -444,13 +573,16 @@ function resolveSessionAndTurn(state2, sessionId) {
444
573
  externalId: sessionId,
445
574
  turnIndex: 0,
446
575
  startedAt: Date.now(),
447
- personaSlug: state2.persona?.slug ?? null
576
+ personaSlug: state2.persona?.slug ?? null,
577
+ environmentConfigHash: null,
578
+ environmentConfigLabel: null
448
579
  };
449
580
  state2.sessions.set(sessionId, session);
450
581
  }
451
582
  const turnIndex = session.turnIndex;
452
583
  session.turnIndex += 1;
453
584
  return {
585
+ session,
454
586
  sessionExternalId: sessionId,
455
587
  turnIndex,
456
588
  personaSlug: session.personaSlug ?? state2.persona?.slug ?? null
@@ -481,7 +613,7 @@ var ProbeSpanProcessor = class {
481
613
  }
482
614
  return;
483
615
  }
484
- const { sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
616
+ const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
485
617
  this.state,
486
618
  sessionId
487
619
  );
@@ -492,7 +624,10 @@ var ProbeSpanProcessor = class {
492
624
  personaSlug: personaSlug ?? void 0,
493
625
  payload: buildPayload(span)
494
626
  };
495
- this.captureFn(captured).catch((err) => {
627
+ (async () => {
628
+ await maybeAutoStampEnvironmentConfig(session, a);
629
+ await this.captureFn(captured);
630
+ })().catch((err) => {
496
631
  if (this.state.config.debug) {
497
632
  console.error(
498
633
  `[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
@@ -999,7 +1134,8 @@ var Probe = class {
999
1134
  const client = new IngestClient({
1000
1135
  apiKey: validated.apiKey,
1001
1136
  endpoint: validated.endpoint,
1002
- debug: validated.debug
1137
+ debug: validated.debug,
1138
+ dashboardUrl: validated.dashboardUrl
1003
1139
  });
1004
1140
  state = {
1005
1141
  config: validated,
@@ -1138,28 +1274,57 @@ var Probe = class {
1138
1274
  * Chapter 8e′ Card 3 (version behavioral diff) — every customer would
1139
1275
  * hash their own way and version-diff would become noise.
1140
1276
  *
1141
- * Node runtime; use dynamic import so the SDK stays browser-friendly
1142
- * for callers that never touch this helper.
1277
+ * The same hashing (src/hash.ts) backs the OTel processor's automatic
1278
+ * version stamping: when autocapture sees a system message and the
1279
+ * deployer set no environmentConfigHash, the session is stamped with
1280
+ * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit
1281
+ * startSession values always win over the auto stamp.
1143
1282
  */
1144
1283
  static async hashEnvironmentConfig(input) {
1145
- if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
1146
- const bytes = new TextEncoder().encode(input);
1147
- const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
1148
- return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
1149
- }
1150
- const { createHash } = await import('crypto');
1151
- return createHash("sha256").update(input).digest("hex");
1284
+ return hashEnvironmentConfig(input);
1152
1285
  }
1153
1286
  /**
1154
1287
  * End a session and release its in-memory entry. Optional (sessions time out
1155
1288
  * eventually), but recommended for long-running processes with many distinct
1156
1289
  * conversations. If `input.endedReason` is provided the SDK sends an end
1157
1290
  * event to ingest so the worker records the reason server-side.
1291
+ *
1292
+ * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`
1293
+ * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`
1294
+ * and, when it returns a non-null OutcomeResult, lands it as an outcome
1295
+ * event (kind = result.outcome, detail carries type/value). This is the
1296
+ * ONLY place the SDK invokes the hook — there are no client-side timers,
1297
+ * so sessions that are never ended explicitly are swept server-side as
1298
+ * `timeout` and receive no hook-resolved outcome; land those via
1299
+ * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:
1300
+ * a throwing or rejecting hook never breaks endSession.
1158
1301
  */
1159
1302
  static async endSession(externalId) {
1160
1303
  if (state === null) return;
1161
1304
  const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
1162
1305
  const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
1306
+ if (state.outcomeHook) {
1307
+ try {
1308
+ const result = await state.outcomeHook.resolve(externalIdStr);
1309
+ if (result && state !== null) {
1310
+ await this.emitOutcomeEvent({
1311
+ sessionExternalId: externalIdStr,
1312
+ kind: result.outcome,
1313
+ detail: {
1314
+ type: result.type,
1315
+ value: result.value,
1316
+ resolvedBy: "outcome_hook"
1317
+ }
1318
+ });
1319
+ }
1320
+ } catch (err) {
1321
+ console.warn(
1322
+ "[probe] outcome hook resolve failed:",
1323
+ err instanceof Error ? err.message : err
1324
+ );
1325
+ }
1326
+ }
1327
+ if (state === null) return;
1163
1328
  if (endedReason) {
1164
1329
  await state.client.sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason }).catch((err) => {
1165
1330
  console.warn("[probe] sendSessionEnd failed:", err instanceof Error ? err.message : err);
@@ -1250,9 +1415,11 @@ var Probe = class {
1250
1415
  }
1251
1416
  /**
1252
1417
  * Register the outcome hook: declares the deployment's outcome type and
1253
- * the resolver for it. NOTE: automatic invocation on session close is
1254
- * not wired in the current build — the hook is stored but nothing calls
1255
- * `resolve` yet. To land a downstream outcome on a session today, call
1418
+ * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked
1419
+ * by endSession() — explicit close is the only trigger; the SDK runs no
1420
+ * client-side timers. A non-null OutcomeResult lands as an outcome event
1421
+ * on the session. Sessions that are never ended explicitly are swept
1422
+ * server-side and never resolve through the hook; land those outcomes via
1256
1423
  * emitOutcomeEvent() from the place where the outcome becomes known
1257
1424
  * (webhook, CRM callback); it joins back by sessionExternalId.
1258
1425
  */