@cultured_computer/sight 0.3.1 → 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/README.md +62 -6
- package/dist/index.cjs +315 -69
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +305 -19
- package/dist/index.d.ts +305 -19
- package/dist/index.js +315 -69
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -4,13 +4,16 @@ 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;
|
|
10
13
|
debug;
|
|
11
14
|
dashboardUrl;
|
|
12
15
|
/**
|
|
13
|
-
* First-trace permalink
|
|
16
|
+
* First-trace permalink: the first
|
|
14
17
|
* SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,
|
|
15
18
|
* then never again for the life of this client (one IngestClient per
|
|
16
19
|
* process — one `init` per process; a restart prints once more, accepted).
|
|
@@ -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,18 +68,25 @@ var IngestClient = class {
|
|
|
40
68
|
*/
|
|
41
69
|
async sendTurn(turn) {
|
|
42
70
|
try {
|
|
43
|
-
const
|
|
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
|
|
84
|
+
body
|
|
50
85
|
});
|
|
51
86
|
const response = await this.retryIfRateLimited(await send(), send);
|
|
52
87
|
if (response === null) return;
|
|
53
88
|
if (!response.ok) {
|
|
54
|
-
this.log(`[
|
|
89
|
+
this.log(`[sight] ingest failed status=${response.status}`);
|
|
55
90
|
return;
|
|
56
91
|
}
|
|
57
92
|
if (!this.firstCaptureAnnounced) {
|
|
@@ -61,21 +96,21 @@ var IngestClient = class {
|
|
|
61
96
|
);
|
|
62
97
|
}
|
|
63
98
|
if (this.debug) {
|
|
64
|
-
const
|
|
65
|
-
this.log(`[
|
|
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);
|
|
69
|
-
this.log(`[
|
|
104
|
+
this.log(`[sight] ingest error: ${msg}`);
|
|
70
105
|
}
|
|
71
106
|
}
|
|
72
107
|
/**
|
|
73
108
|
* Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.
|
|
74
|
-
* Populates the `user_flagged_break` outcome column
|
|
109
|
+
* Populates the `user_flagged_break` outcome column on the dashboard.
|
|
75
110
|
*/
|
|
76
111
|
async sendFlag(deploymentSlug, flag) {
|
|
77
112
|
try {
|
|
78
|
-
const send = () =>
|
|
113
|
+
const send = () => this.guardedFetch(`${this.endpoint}/v1/flags`, {
|
|
79
114
|
method: "POST",
|
|
80
115
|
headers: {
|
|
81
116
|
Authorization: `Bearer ${this.apiKey}`,
|
|
@@ -92,15 +127,15 @@ var IngestClient = class {
|
|
|
92
127
|
const response = await this.retryIfRateLimited(await send(), send);
|
|
93
128
|
if (response === null) return;
|
|
94
129
|
if (!response.ok) {
|
|
95
|
-
this.log(`[
|
|
130
|
+
this.log(`[sight] flag ingest failed status=${response.status}`);
|
|
96
131
|
return;
|
|
97
132
|
}
|
|
98
133
|
if (this.debug) {
|
|
99
|
-
this.log(`[
|
|
134
|
+
this.log(`[sight] flag ingest ok session=${flag.sessionExternalId}`);
|
|
100
135
|
}
|
|
101
136
|
} catch (err) {
|
|
102
137
|
const msg = err instanceof Error ? err.message : String(err);
|
|
103
|
-
this.log(`[
|
|
138
|
+
this.log(`[sight] flag ingest error: ${msg}`);
|
|
104
139
|
}
|
|
105
140
|
}
|
|
106
141
|
/**
|
|
@@ -109,7 +144,7 @@ var IngestClient = class {
|
|
|
109
144
|
*/
|
|
110
145
|
async sendSessionEnd(deploymentSlug, end) {
|
|
111
146
|
try {
|
|
112
|
-
const send = () =>
|
|
147
|
+
const send = () => this.guardedFetch(`${this.endpoint}/v1/sessions/end`, {
|
|
113
148
|
method: "POST",
|
|
114
149
|
headers: {
|
|
115
150
|
Authorization: `Bearer ${this.apiKey}`,
|
|
@@ -124,24 +159,24 @@ var IngestClient = class {
|
|
|
124
159
|
const response = await this.retryIfRateLimited(await send(), send);
|
|
125
160
|
if (response === null) return;
|
|
126
161
|
if (!response.ok) {
|
|
127
|
-
this.log(`[
|
|
162
|
+
this.log(`[sight] session-end ingest failed status=${response.status}`);
|
|
128
163
|
return;
|
|
129
164
|
}
|
|
130
165
|
if (this.debug) {
|
|
131
|
-
this.log(`[
|
|
166
|
+
this.log(`[sight] session-end ingest ok session=${end.externalId}`);
|
|
132
167
|
}
|
|
133
168
|
} catch (err) {
|
|
134
169
|
const msg = err instanceof Error ? err.message : String(err);
|
|
135
|
-
this.log(`[
|
|
170
|
+
this.log(`[sight] session-end ingest error: ${msg}`);
|
|
136
171
|
}
|
|
137
172
|
}
|
|
138
173
|
/**
|
|
139
174
|
* Send an outcome event to the ingest API. Fire-and-log. Populates
|
|
140
|
-
*
|
|
175
|
+
* the outcome-events store.
|
|
141
176
|
*/
|
|
142
177
|
async sendOutcomeEvent(deploymentSlug, event) {
|
|
143
178
|
try {
|
|
144
|
-
const send = () =>
|
|
179
|
+
const send = () => this.guardedFetch(`${this.endpoint}/v1/outcome-events`, {
|
|
145
180
|
method: "POST",
|
|
146
181
|
headers: {
|
|
147
182
|
Authorization: `Bearer ${this.apiKey}`,
|
|
@@ -159,17 +194,17 @@ var IngestClient = class {
|
|
|
159
194
|
const response = await this.retryIfRateLimited(await send(), send);
|
|
160
195
|
if (response === null) return;
|
|
161
196
|
if (!response.ok) {
|
|
162
|
-
this.log(`[
|
|
197
|
+
this.log(`[sight] outcome-event ingest failed status=${response.status}`);
|
|
163
198
|
return;
|
|
164
199
|
}
|
|
165
200
|
if (this.debug) {
|
|
166
201
|
this.log(
|
|
167
|
-
`[
|
|
202
|
+
`[sight] outcome-event ingest ok session=${event.sessionExternalId} kind=${event.kind}`
|
|
168
203
|
);
|
|
169
204
|
}
|
|
170
205
|
} catch (err) {
|
|
171
206
|
const msg = err instanceof Error ? err.message : String(err);
|
|
172
|
-
this.log(`[
|
|
207
|
+
this.log(`[sight] outcome-event ingest error: ${msg}`);
|
|
173
208
|
}
|
|
174
209
|
}
|
|
175
210
|
/**
|
|
@@ -179,7 +214,7 @@ var IngestClient = class {
|
|
|
179
214
|
*/
|
|
180
215
|
async sendEnvironmentEvents(batch) {
|
|
181
216
|
try {
|
|
182
|
-
const send = () =>
|
|
217
|
+
const send = () => this.guardedFetch(`${this.endpoint}/v1/environment-events`, {
|
|
183
218
|
method: "POST",
|
|
184
219
|
headers: {
|
|
185
220
|
Authorization: `Bearer ${this.apiKey}`,
|
|
@@ -190,15 +225,45 @@ var IngestClient = class {
|
|
|
190
225
|
const response = await this.retryIfRateLimited(await send(), send);
|
|
191
226
|
if (response === null) return;
|
|
192
227
|
if (!response.ok) {
|
|
193
|
-
this.log(`[
|
|
228
|
+
this.log(`[sight] environment-events ingest failed status=${response.status}`);
|
|
194
229
|
return;
|
|
195
230
|
}
|
|
196
231
|
if (this.debug) {
|
|
197
|
-
this.log(`[
|
|
232
|
+
this.log(`[sight] environment-events ingest ok events=${batch.events.length}`);
|
|
198
233
|
}
|
|
199
234
|
} catch (err) {
|
|
200
235
|
const msg = err instanceof Error ? err.message : String(err);
|
|
201
|
-
this.log(`[
|
|
236
|
+
this.log(`[sight] environment-events ingest error: ${msg}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Send a span batch to the ingest API. Fire-and-log, same as sendTurn.
|
|
241
|
+
* Spans carry sub-turn structure (llm_call / tool_call / framework_step /
|
|
242
|
+
* custom); the worker resolves each span's session/turn and wires in-batch
|
|
243
|
+
* parent references.
|
|
244
|
+
*/
|
|
245
|
+
async sendSpans(batch) {
|
|
246
|
+
try {
|
|
247
|
+
const send = () => this.guardedFetch(`${this.endpoint}/v1/spans`, {
|
|
248
|
+
method: "POST",
|
|
249
|
+
headers: {
|
|
250
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
251
|
+
"content-type": "application/json"
|
|
252
|
+
},
|
|
253
|
+
body: JSON.stringify(batch)
|
|
254
|
+
});
|
|
255
|
+
const response = await this.retryIfRateLimited(await send(), send);
|
|
256
|
+
if (response === null) return;
|
|
257
|
+
if (!response.ok) {
|
|
258
|
+
this.log(`[sight] spans ingest failed status=${response.status}`);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (this.debug) {
|
|
262
|
+
this.log(`[sight] spans ingest ok spans=${batch.spans.length}`);
|
|
263
|
+
}
|
|
264
|
+
} catch (err) {
|
|
265
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
266
|
+
this.log(`[sight] spans ingest error: ${msg}`);
|
|
202
267
|
}
|
|
203
268
|
}
|
|
204
269
|
/**
|
|
@@ -219,10 +284,10 @@ var IngestClient = class {
|
|
|
219
284
|
"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"
|
|
220
285
|
);
|
|
221
286
|
} else {
|
|
222
|
-
this.log("[
|
|
287
|
+
this.log("[sight] ingest rate limited (429), retrying once");
|
|
223
288
|
}
|
|
224
289
|
if (this.pendingRetries >= MAX_PENDING_RETRIES) {
|
|
225
|
-
this.log("[
|
|
290
|
+
this.log("[sight] retry buffer full, dropped");
|
|
226
291
|
return null;
|
|
227
292
|
}
|
|
228
293
|
const raw = response.headers.get("retry-after");
|
|
@@ -333,7 +398,7 @@ var SessionStartSchema = z.object({
|
|
|
333
398
|
*/
|
|
334
399
|
persona: z.string().min(1).optional(),
|
|
335
400
|
/**
|
|
336
|
-
* How the user got into this session
|
|
401
|
+
* How the user got into this session.
|
|
337
402
|
* Retention semantics differ radically between a resume and a fresh
|
|
338
403
|
* notification landing.
|
|
339
404
|
*/
|
|
@@ -350,8 +415,8 @@ var SessionStartSchema = z.object({
|
|
|
350
415
|
*/
|
|
351
416
|
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
352
417
|
/**
|
|
353
|
-
* RLDS episode-level provenance
|
|
354
|
-
*
|
|
418
|
+
* RLDS episode-level provenance. Powers the version behavioral diff
|
|
419
|
+
* on the dashboard. All optional.
|
|
355
420
|
* agentId — model/policy version
|
|
356
421
|
* experimentId — A/B arm or feature flag
|
|
357
422
|
* environmentConfigHash — SHA of prompt/config file(s)
|
|
@@ -364,7 +429,9 @@ var SessionStartSchema = z.object({
|
|
|
364
429
|
});
|
|
365
430
|
z.object({
|
|
366
431
|
externalId: z.string().min(1),
|
|
367
|
-
endedReason: z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional()
|
|
432
|
+
endedReason: z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional(),
|
|
433
|
+
outcome: z.string().min(1).max(64).optional(),
|
|
434
|
+
outcomeDetail: z.record(z.string(), z.unknown()).optional()
|
|
368
435
|
});
|
|
369
436
|
var FlagPersonaBreakSchema = z.object({
|
|
370
437
|
sessionExternalId: z.string().min(1),
|
|
@@ -434,6 +501,16 @@ function collectClientContext(includes = DEFAULT_INCLUDES) {
|
|
|
434
501
|
return out;
|
|
435
502
|
}
|
|
436
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
|
+
|
|
437
514
|
// src/hash.ts
|
|
438
515
|
async function hashEnvironmentConfig(input) {
|
|
439
516
|
if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
|
|
@@ -660,7 +737,7 @@ function resolveSessionAndTurn(state2, sessionId) {
|
|
|
660
737
|
environmentConfigHash: null,
|
|
661
738
|
environmentConfigLabel: null
|
|
662
739
|
};
|
|
663
|
-
state2.sessions
|
|
740
|
+
boundedSessionSet(state2.sessions, sessionId, session);
|
|
664
741
|
}
|
|
665
742
|
const turnIndex = session.turnIndex;
|
|
666
743
|
session.turnIndex += 1;
|
|
@@ -678,10 +755,23 @@ var ProbeSpanProcessor = class {
|
|
|
678
755
|
}
|
|
679
756
|
state;
|
|
680
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
|
+
}
|
|
681
769
|
onStart(_span, _parentContext) {
|
|
682
770
|
}
|
|
683
771
|
onEnd(span) {
|
|
684
772
|
try {
|
|
773
|
+
if (this.state === null) return;
|
|
774
|
+
const state2 = this.state;
|
|
685
775
|
const a = span.attributes;
|
|
686
776
|
if (isVercelAgentRollup(span.name, a)) return;
|
|
687
777
|
if (!isLLMCall(a)) return;
|
|
@@ -689,7 +779,7 @@ var ProbeSpanProcessor = class {
|
|
|
689
779
|
if (shouldSkipAsDuplicate(traceId)) return;
|
|
690
780
|
const sessionId = getCurrentSessionId();
|
|
691
781
|
if (!sessionId) {
|
|
692
|
-
if (
|
|
782
|
+
if (state2.config.debug) {
|
|
693
783
|
console.warn(
|
|
694
784
|
`[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`
|
|
695
785
|
);
|
|
@@ -697,11 +787,11 @@ var ProbeSpanProcessor = class {
|
|
|
697
787
|
return;
|
|
698
788
|
}
|
|
699
789
|
const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
|
|
700
|
-
|
|
790
|
+
state2,
|
|
701
791
|
sessionId
|
|
702
792
|
);
|
|
703
793
|
const captured = {
|
|
704
|
-
deploymentSlug:
|
|
794
|
+
deploymentSlug: state2.config.deployment,
|
|
705
795
|
sessionExternalId,
|
|
706
796
|
turnIndex,
|
|
707
797
|
personaSlug: personaSlug ?? void 0,
|
|
@@ -711,14 +801,14 @@ var ProbeSpanProcessor = class {
|
|
|
711
801
|
await maybeAutoStampEnvironmentConfig(session, a);
|
|
712
802
|
await this.captureFn(captured);
|
|
713
803
|
})().catch((err) => {
|
|
714
|
-
if (
|
|
804
|
+
if (state2.config.debug) {
|
|
715
805
|
console.error(
|
|
716
806
|
`[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
|
|
717
807
|
);
|
|
718
808
|
}
|
|
719
809
|
});
|
|
720
810
|
} catch (err) {
|
|
721
|
-
if (this.state
|
|
811
|
+
if (this.state?.config.debug) {
|
|
722
812
|
console.error(
|
|
723
813
|
`[probe/otel] onEnd error: ${err instanceof Error ? err.message : err}`
|
|
724
814
|
);
|
|
@@ -738,6 +828,7 @@ var ProbeSpanProcessor = class {
|
|
|
738
828
|
var installedProcessor = null;
|
|
739
829
|
function setupOtelProvider(state2, captureFn) {
|
|
740
830
|
if (installedProcessor !== null) {
|
|
831
|
+
installedProcessor.rebind(state2, captureFn);
|
|
741
832
|
return;
|
|
742
833
|
}
|
|
743
834
|
installedProcessor = new ProbeSpanProcessor(state2, captureFn);
|
|
@@ -753,6 +844,9 @@ function setupOtelProvider(state2, captureFn) {
|
|
|
753
844
|
provider.register();
|
|
754
845
|
});
|
|
755
846
|
}
|
|
847
|
+
function detachOtelState() {
|
|
848
|
+
installedProcessor?.rebind(null);
|
|
849
|
+
}
|
|
756
850
|
|
|
757
851
|
// src/instrumentation/openai.ts
|
|
758
852
|
var registered = false;
|
|
@@ -901,7 +995,7 @@ function registerAllInstrumentations(state2, captureFn) {
|
|
|
901
995
|
if (!state2.config.debug) return;
|
|
902
996
|
for (const result of results) {
|
|
903
997
|
if (result.status === "rejected") {
|
|
904
|
-
console.error(`[
|
|
998
|
+
console.error(`[sight] adapter register rejected: ${result.reason}`);
|
|
905
999
|
}
|
|
906
1000
|
}
|
|
907
1001
|
});
|
|
@@ -941,6 +1035,13 @@ function matchSignaturePhrases(text, compiled) {
|
|
|
941
1035
|
}
|
|
942
1036
|
return matches;
|
|
943
1037
|
}
|
|
1038
|
+
|
|
1039
|
+
// ../shared/src/effectiveness-gap.ts
|
|
1040
|
+
new Set(
|
|
1041
|
+
"the a an to of and or is are was were do does did how what where when who why which can could should would may might i you your my me it its this that these those in on for with at by from as be been being am not no yes okay ok um uh hi hello please thanks thank".split(" ")
|
|
1042
|
+
);
|
|
1043
|
+
|
|
1044
|
+
// ../shared/src/index.ts
|
|
944
1045
|
var REACTION_REGISTERS = ["heavy", "comic", "edge"];
|
|
945
1046
|
var InterpretiveRecordSchema = z.object({
|
|
946
1047
|
// Open vocabulary: any string tag. Seeds live in GENERAL_SITUATION_TAGS /
|
|
@@ -1070,6 +1171,15 @@ z.object({
|
|
|
1070
1171
|
*/
|
|
1071
1172
|
externalUserId: z.string().min(1).optional(),
|
|
1072
1173
|
turnIndex: z.number().int().nonnegative(),
|
|
1174
|
+
/**
|
|
1175
|
+
* Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the
|
|
1176
|
+
* worker: when present it becomes turns.started_at; when absent the
|
|
1177
|
+
* insert defaults to processing time. This is PROVENANCE, not
|
|
1178
|
+
* verification — intended for historical imports (ZVA telemetry, log
|
|
1179
|
+
* backfills, the datadump importer); live SDK traffic leaves it unset
|
|
1180
|
+
* (arrival time is the honest clock there).
|
|
1181
|
+
*/
|
|
1182
|
+
startedAt: z.string().datetime().optional(),
|
|
1073
1183
|
/**
|
|
1074
1184
|
* Persona slug active for this turn. Customer-supplied (from SDK persona
|
|
1075
1185
|
* resolution: turn override / session / init default). Optional; deployments
|
|
@@ -1214,6 +1324,61 @@ var EnvironmentEventsBatchSchema = z.object({
|
|
|
1214
1324
|
events: z.array(EnvironmentEventInputSchema).min(1).max(100),
|
|
1215
1325
|
alignment: AlignmentProvenanceSchema
|
|
1216
1326
|
});
|
|
1327
|
+
var SPAN_TYPES = ["llm_call", "tool_call", "framework_step", "custom"];
|
|
1328
|
+
var SpanInputSchema = z.object({
|
|
1329
|
+
deploymentSlug: z.string().min(1),
|
|
1330
|
+
sessionExternalId: z.string().min(1),
|
|
1331
|
+
/**
|
|
1332
|
+
* Turn the span belongs to. Optional: when omitted the worker resolves the
|
|
1333
|
+
* session's latest turn at/under the span's startedAt (falling back to the
|
|
1334
|
+
* session's most recent turn when startedAt is also absent — the outcome
|
|
1335
|
+
* events' rule). A span whose turn cannot be resolved is SKIPPED by the
|
|
1336
|
+
* worker (logged, batch still processed): spans never land unattributed.
|
|
1337
|
+
*/
|
|
1338
|
+
turnIndex: z.number().int().nonnegative().optional(),
|
|
1339
|
+
spanType: z.enum(SPAN_TYPES),
|
|
1340
|
+
/** Human/otel-style span name (tool name, model call label). */
|
|
1341
|
+
name: z.string().optional(),
|
|
1342
|
+
/**
|
|
1343
|
+
* Caller-asserted span start (ISO). OPTIONAL and honored like
|
|
1344
|
+
* TurnInput.startedAt: provenance, not verification — when absent the
|
|
1345
|
+
* worker stamps processing time.
|
|
1346
|
+
*/
|
|
1347
|
+
startedAt: z.string().datetime().optional(),
|
|
1348
|
+
endedAt: z.string().datetime().optional(),
|
|
1349
|
+
durationMs: z.number().int().nonnegative().optional(),
|
|
1350
|
+
model: z.string().optional(),
|
|
1351
|
+
provider: z.string().optional(),
|
|
1352
|
+
tokensInput: z.number().int().nonnegative().optional(),
|
|
1353
|
+
tokensOutput: z.number().int().nonnegative().optional(),
|
|
1354
|
+
costUsd: z.number().nonnegative().optional(),
|
|
1355
|
+
error: z.string().optional(),
|
|
1356
|
+
/**
|
|
1357
|
+
* OpenInference / OpenTelemetry gen_ai.*-style attributes. String values
|
|
1358
|
+
* are Presidio-scrubbed by the worker before storage (see the PII rule
|
|
1359
|
+
* above). Capped at 16k JSON chars per span.
|
|
1360
|
+
*/
|
|
1361
|
+
attributes: z.record(z.string(), z.unknown()).optional().refine((v) => v === void 0 || JSON.stringify(v).length <= 16e3, {
|
|
1362
|
+
message: "attributes exceed 16k JSON chars \u2014 spans are telemetry, not blob storage"
|
|
1363
|
+
}),
|
|
1364
|
+
/**
|
|
1365
|
+
* Caller-local span id, unique within the batch. Exists only so sibling
|
|
1366
|
+
* spans can name this span as their parentSpanId; never stored (the DB
|
|
1367
|
+
* assigns the real uuid).
|
|
1368
|
+
*/
|
|
1369
|
+
spanId: z.string().min(1).optional(),
|
|
1370
|
+
/**
|
|
1371
|
+
* Caller-local reference to another span's `spanId` IN THE SAME BATCH (NOT
|
|
1372
|
+
* a database uuid). The worker wires spans.parent_span_id when the parent
|
|
1373
|
+
* resolves within the batch, stores null otherwise.
|
|
1374
|
+
*/
|
|
1375
|
+
parentSpanId: z.string().min(1).optional()
|
|
1376
|
+
});
|
|
1377
|
+
var SpansBatchSchema = z.object({
|
|
1378
|
+
/** Spans are self-addressed: a batch may span sessions/deployments. */
|
|
1379
|
+
spans: z.array(SpanInputSchema).min(1).max(50),
|
|
1380
|
+
alignment: AlignmentProvenanceSchema
|
|
1381
|
+
});
|
|
1217
1382
|
var DEFINITION_SLUG = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
1218
1383
|
var DEFINITION_VALUE = z.string().trim().min(1).max(64);
|
|
1219
1384
|
z.object({
|
|
@@ -1274,7 +1439,22 @@ var DEFAULT_ENVIRONMENT_ALIGNMENT = {
|
|
|
1274
1439
|
clock_source: "sdk",
|
|
1275
1440
|
rule_version: "v1"
|
|
1276
1441
|
};
|
|
1442
|
+
var DEFAULT_SPAN_ALIGNMENT = {
|
|
1443
|
+
clock_source: "sdk",
|
|
1444
|
+
rule_version: "v1"
|
|
1445
|
+
};
|
|
1277
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
|
+
}
|
|
1278
1458
|
var Probe = class {
|
|
1279
1459
|
/**
|
|
1280
1460
|
* Initialize the Probe SDK. Call once at process start. Subsequent calls are
|
|
@@ -1282,7 +1462,7 @@ var Probe = class {
|
|
|
1282
1462
|
*/
|
|
1283
1463
|
static init(config) {
|
|
1284
1464
|
if (state !== null) {
|
|
1285
|
-
console.warn("[
|
|
1465
|
+
console.warn("[sight] already initialized; call shutdown() first");
|
|
1286
1466
|
return;
|
|
1287
1467
|
}
|
|
1288
1468
|
const validated = ProbeConfigSchema.parse(config);
|
|
@@ -1320,7 +1500,7 @@ var Probe = class {
|
|
|
1320
1500
|
*/
|
|
1321
1501
|
static async withSession(sessionId, fn) {
|
|
1322
1502
|
if (state === null) {
|
|
1323
|
-
console.warn("[
|
|
1503
|
+
console.warn("[sight] withSession called before init");
|
|
1324
1504
|
return fn();
|
|
1325
1505
|
}
|
|
1326
1506
|
return withSession(sessionId, fn);
|
|
@@ -1332,7 +1512,7 @@ var Probe = class {
|
|
|
1332
1512
|
*/
|
|
1333
1513
|
static identifyPersona(persona) {
|
|
1334
1514
|
if (state === null) {
|
|
1335
|
-
console.warn("[
|
|
1515
|
+
console.warn("[sight] identifyPersona called before init");
|
|
1336
1516
|
return;
|
|
1337
1517
|
}
|
|
1338
1518
|
state.persona = persona;
|
|
@@ -1355,10 +1535,11 @@ var Probe = class {
|
|
|
1355
1535
|
*/
|
|
1356
1536
|
static startSession(input) {
|
|
1357
1537
|
if (state === null) {
|
|
1358
|
-
console.warn("[
|
|
1538
|
+
console.warn("[sight] startSession called before init");
|
|
1359
1539
|
return;
|
|
1360
1540
|
}
|
|
1361
|
-
const validated = SessionStartSchema
|
|
1541
|
+
const validated = validateOrDrop(SessionStartSchema, input, "startSession");
|
|
1542
|
+
if (validated === null) return;
|
|
1362
1543
|
const existing = state.sessions.get(validated.externalId);
|
|
1363
1544
|
const now = Date.now();
|
|
1364
1545
|
const session = {
|
|
@@ -1381,7 +1562,7 @@ var Probe = class {
|
|
|
1381
1562
|
pendingUserOutcome: existing?.pendingUserOutcome ?? null
|
|
1382
1563
|
};
|
|
1383
1564
|
this.flushPreSessionSignals(validated.externalId, session);
|
|
1384
|
-
state.sessions
|
|
1565
|
+
boundedSessionSet(state.sessions, validated.externalId, session);
|
|
1385
1566
|
}
|
|
1386
1567
|
/**
|
|
1387
1568
|
* Move buffered pre-session interaction signals (recorded before any
|
|
@@ -1426,7 +1607,7 @@ var Probe = class {
|
|
|
1426
1607
|
* for the diff table axis (a card keyed by a3f9c2… is unreadable).
|
|
1427
1608
|
*
|
|
1428
1609
|
* Ships as a helper because inconsistent hashing across restarts breaks
|
|
1429
|
-
*
|
|
1610
|
+
* The version behavioral diff — every customer would
|
|
1430
1611
|
* hash their own way and version-diff would become noise.
|
|
1431
1612
|
*
|
|
1432
1613
|
* The same hashing (src/hash.ts) backs the OTel processor's automatic
|
|
@@ -1458,7 +1639,18 @@ var Probe = class {
|
|
|
1458
1639
|
if (state === null) return;
|
|
1459
1640
|
const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
|
|
1460
1641
|
const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
|
|
1461
|
-
|
|
1642
|
+
const declared = typeof externalId === "string" ? void 0 : externalId.outcome;
|
|
1643
|
+
if (declared) {
|
|
1644
|
+
await this.emitOutcomeEvent({
|
|
1645
|
+
sessionExternalId: externalIdStr,
|
|
1646
|
+
kind: declared,
|
|
1647
|
+
detail: {
|
|
1648
|
+
declaredAt: "endSession",
|
|
1649
|
+
...typeof externalId === "object" && externalId.outcomeDetail ? externalId.outcomeDetail : {}
|
|
1650
|
+
}
|
|
1651
|
+
});
|
|
1652
|
+
}
|
|
1653
|
+
if (!declared && state.outcomeHook) {
|
|
1462
1654
|
try {
|
|
1463
1655
|
const result = await state.outcomeHook.resolve(externalIdStr);
|
|
1464
1656
|
if (result && state !== null) {
|
|
@@ -1474,7 +1666,7 @@ var Probe = class {
|
|
|
1474
1666
|
}
|
|
1475
1667
|
} catch (err) {
|
|
1476
1668
|
console.warn(
|
|
1477
|
-
"[
|
|
1669
|
+
"[sight] outcome hook resolve failed:",
|
|
1478
1670
|
err instanceof Error ? err.message : err
|
|
1479
1671
|
);
|
|
1480
1672
|
}
|
|
@@ -1482,12 +1674,12 @@ var Probe = class {
|
|
|
1482
1674
|
if (state === null) return;
|
|
1483
1675
|
if (endedReason) {
|
|
1484
1676
|
await state.client.sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason }).catch((err) => {
|
|
1485
|
-
console.warn("[
|
|
1677
|
+
console.warn("[sight] sendSessionEnd failed:", err instanceof Error ? err.message : err);
|
|
1486
1678
|
});
|
|
1487
1679
|
}
|
|
1488
1680
|
state.sessions.delete(externalIdStr);
|
|
1489
1681
|
}
|
|
1490
|
-
// ── User-side helpers
|
|
1682
|
+
// ── User-side helpers ──────────────────────────────────────────────────
|
|
1491
1683
|
// These accumulate user-side signals during a turn; captureTurn folds the
|
|
1492
1684
|
// accumulated state into TurnInput.userInput / userOutcome before send.
|
|
1493
1685
|
// Signals that arrive before any session entry exists (typing starts
|
|
@@ -1580,7 +1772,7 @@ var Probe = class {
|
|
|
1580
1772
|
*/
|
|
1581
1773
|
static wireOutcomeHook(hook) {
|
|
1582
1774
|
if (state === null) {
|
|
1583
|
-
console.warn("[
|
|
1775
|
+
console.warn("[sight] wireOutcomeHook called before init");
|
|
1584
1776
|
return;
|
|
1585
1777
|
}
|
|
1586
1778
|
state.outcomeHook = hook;
|
|
@@ -1605,6 +1797,9 @@ var Probe = class {
|
|
|
1605
1797
|
if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
|
|
1606
1798
|
return;
|
|
1607
1799
|
}
|
|
1800
|
+
if (turn.payload === void 0 || turn.payload === null) {
|
|
1801
|
+
turn = { ...turn, payload: {} };
|
|
1802
|
+
}
|
|
1608
1803
|
const propensity = turn.propensity ?? turn.payload.propensity;
|
|
1609
1804
|
let validPropensity = propensity;
|
|
1610
1805
|
if (propensity) {
|
|
@@ -1621,10 +1816,14 @@ var Probe = class {
|
|
|
1621
1816
|
const resolvedPersona = turn.personaSlug ?? sessionPersona ?? state.persona?.slug ?? void 0;
|
|
1622
1817
|
let signatureMatches = turn.signaturePhraseMatches;
|
|
1623
1818
|
if (!signatureMatches && resolvedPersona) {
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
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 = [];
|
|
1628
1827
|
}
|
|
1629
1828
|
}
|
|
1630
1829
|
let session = state.sessions.get(turn.sessionExternalId);
|
|
@@ -1648,7 +1847,7 @@ var Probe = class {
|
|
|
1648
1847
|
pendingUserInput: null,
|
|
1649
1848
|
pendingUserOutcome: null
|
|
1650
1849
|
};
|
|
1651
|
-
state.sessions
|
|
1850
|
+
boundedSessionSet(state.sessions, turn.sessionExternalId, session);
|
|
1652
1851
|
}
|
|
1653
1852
|
this.flushPreSessionSignals(turn.sessionExternalId, session);
|
|
1654
1853
|
let userInput = turn.userInput;
|
|
@@ -1710,7 +1909,7 @@ var Probe = class {
|
|
|
1710
1909
|
propensity: validPropensity,
|
|
1711
1910
|
// Forward RLDS provenance from the local session entry (populated
|
|
1712
1911
|
// by Probe.startSession). Worker persists at first-turn session
|
|
1713
|
-
// create; nulls stay null.
|
|
1912
|
+
// create; nulls stay null.
|
|
1714
1913
|
agentId: session.agentId ?? void 0,
|
|
1715
1914
|
experimentId: session.experimentId ?? void 0,
|
|
1716
1915
|
environmentConfigHash: session.environmentConfigHash ?? void 0,
|
|
@@ -1719,7 +1918,7 @@ var Probe = class {
|
|
|
1719
1918
|
}
|
|
1720
1919
|
/**
|
|
1721
1920
|
* Emit a custom outcome event on a session. Populates probe_outcome_events
|
|
1722
|
-
* with the customer-supplied `kind` string
|
|
1921
|
+
* with the customer-supplied `kind` string. Use for
|
|
1723
1922
|
* customer-defined kinds like "purchase_complete", "handoff_to_human",
|
|
1724
1923
|
* "character_break_severe". Universal seed kinds (break, escalation,
|
|
1725
1924
|
* resolution, thumbs_*, rating_*) are also emitted by worker-side
|
|
@@ -1728,14 +1927,15 @@ var Probe = class {
|
|
|
1728
1927
|
*/
|
|
1729
1928
|
static async emitOutcomeEvent(input) {
|
|
1730
1929
|
if (state === null) {
|
|
1731
|
-
console.warn("[
|
|
1930
|
+
console.warn("[sight] emitOutcomeEvent called before init");
|
|
1732
1931
|
return;
|
|
1733
1932
|
}
|
|
1734
|
-
const validated = OutcomeEventEmitSchema
|
|
1933
|
+
const validated = validateOrDrop(OutcomeEventEmitSchema, input, "emitOutcomeEvent");
|
|
1934
|
+
if (validated === null) return;
|
|
1735
1935
|
await state.client.sendOutcomeEvent(state.config.deployment, validated);
|
|
1736
1936
|
}
|
|
1737
1937
|
/**
|
|
1738
|
-
* Capture one environment event against a session
|
|
1938
|
+
* Capture one environment event against a session. The
|
|
1739
1939
|
* envelope is generalized: `source_type` and `event` are free strings whose
|
|
1740
1940
|
* meaning is defined per deployment — the instrument stores the event and
|
|
1741
1941
|
* attaches it to the session's record by time (the next turn's state
|
|
@@ -1749,11 +1949,12 @@ var Probe = class {
|
|
|
1749
1949
|
*/
|
|
1750
1950
|
static async captureEnvironmentEvent(event, alignment) {
|
|
1751
1951
|
if (state === null) {
|
|
1752
|
-
console.warn("[
|
|
1952
|
+
console.warn("[sight] captureEnvironmentEvent called before init");
|
|
1753
1953
|
return;
|
|
1754
1954
|
}
|
|
1755
|
-
const validated = EnvironmentEventInputSchema
|
|
1756
|
-
|
|
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;
|
|
1757
1958
|
await state.client.sendEnvironmentEvents({ events: [validated], alignment: align });
|
|
1758
1959
|
}
|
|
1759
1960
|
/**
|
|
@@ -1763,28 +1964,72 @@ var Probe = class {
|
|
|
1763
1964
|
* generalized envelope and fire-and-log discipline as the single-event
|
|
1764
1965
|
* capture above.
|
|
1765
1966
|
*/
|
|
1766
|
-
static async captureEnvironmentEvents(events, alignment) {
|
|
1967
|
+
static async captureEnvironmentEvents(events, alignment = DEFAULT_ENVIRONMENT_ALIGNMENT) {
|
|
1767
1968
|
if (state === null) {
|
|
1768
|
-
console.warn("[
|
|
1969
|
+
console.warn("[sight] captureEnvironmentEvents called before init");
|
|
1769
1970
|
return;
|
|
1770
1971
|
}
|
|
1771
|
-
const batch = EnvironmentEventsBatchSchema
|
|
1972
|
+
const batch = validateOrDrop(EnvironmentEventsBatchSchema, { events, alignment }, "captureEnvironmentEvents");
|
|
1973
|
+
if (batch === null) return;
|
|
1772
1974
|
await state.client.sendEnvironmentEvents(batch);
|
|
1773
1975
|
}
|
|
1976
|
+
/**
|
|
1977
|
+
* Capture one sub-turn span against a session: one LLM call, one tool
|
|
1978
|
+
* call, one framework step, or a custom unit inside a turn. The span lands
|
|
1979
|
+
* on the turn named by `turnIndex`, or — when omitted — on the session's
|
|
1980
|
+
* latest turn at/under the span's `startedAt` (most recent turn when
|
|
1981
|
+
* `startedAt` is also absent). A span whose turn cannot be resolved is
|
|
1982
|
+
* dropped server-side; spans never land unattributed. Fire-and-log, like
|
|
1983
|
+
* captureTurn: errors are debug-logged, never thrown.
|
|
1984
|
+
*
|
|
1985
|
+
* `attributes` are metadata only (tool names, argument shapes) — never
|
|
1986
|
+
* free-text conversation content. Alignment defaults to the SDK's own
|
|
1987
|
+
* clock claim; deployments with a stricter clock contract (or batches, or
|
|
1988
|
+
* parent references between spans) should call captureSpans.
|
|
1989
|
+
*/
|
|
1990
|
+
static async captureSpan(span, alignment) {
|
|
1991
|
+
if (state === null) {
|
|
1992
|
+
console.warn("[sight] captureSpan called before init");
|
|
1993
|
+
return;
|
|
1994
|
+
}
|
|
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;
|
|
1998
|
+
await state.client.sendSpans({ spans: [validated], alignment: align });
|
|
1999
|
+
}
|
|
2000
|
+
/**
|
|
2001
|
+
* Capture a batch of spans with explicit alignment provenance
|
|
2002
|
+
* (clock_source, skew_bound_ms, rule_version). Batches are capped at 50
|
|
2003
|
+
* spans and may span sessions — every span is self-addressed. Parent
|
|
2004
|
+
* structure rides the batch: a span's `parentSpanId` names another span's
|
|
2005
|
+
* caller-local `spanId` within the same batch and is wired server-side
|
|
2006
|
+
* (unresolvable references land null). Same fire-and-log discipline as the
|
|
2007
|
+
* single-span capture above.
|
|
2008
|
+
*/
|
|
2009
|
+
static async captureSpans(spans, alignment) {
|
|
2010
|
+
if (state === null) {
|
|
2011
|
+
console.warn("[sight] captureSpans called before init");
|
|
2012
|
+
return;
|
|
2013
|
+
}
|
|
2014
|
+
const batch = validateOrDrop(SpansBatchSchema, { spans, alignment: alignment ?? DEFAULT_SPAN_ALIGNMENT }, "captureSpans");
|
|
2015
|
+
if (batch === null) return;
|
|
2016
|
+
await state.client.sendSpans(batch);
|
|
2017
|
+
}
|
|
1774
2018
|
/**
|
|
1775
2019
|
* Flag a persona break for a session. Wire this to the customer's in-product
|
|
1776
2020
|
* "that didn't sound like you" UX. Populates the `user_flagged_break`
|
|
1777
|
-
* outcome column
|
|
2021
|
+
* outcome column on the dashboard.
|
|
1778
2022
|
*
|
|
1779
2023
|
* If `turnIndex` is omitted, the flag attaches to the session's most
|
|
1780
2024
|
* recent turn.
|
|
1781
2025
|
*/
|
|
1782
2026
|
static async flagPersonaBreak(input) {
|
|
1783
2027
|
if (state === null) {
|
|
1784
|
-
console.warn("[
|
|
2028
|
+
console.warn("[sight] flagPersonaBreak called before init");
|
|
1785
2029
|
return;
|
|
1786
2030
|
}
|
|
1787
|
-
const validated = FlagPersonaBreakSchema
|
|
2031
|
+
const validated = validateOrDrop(FlagPersonaBreakSchema, input, "flagPersonaBreak");
|
|
2032
|
+
if (validated === null) return;
|
|
1788
2033
|
await state.client.sendFlag(state.config.deployment, validated);
|
|
1789
2034
|
}
|
|
1790
2035
|
/**
|
|
@@ -1812,6 +2057,7 @@ var Probe = class {
|
|
|
1812
2057
|
if (state === null) {
|
|
1813
2058
|
return;
|
|
1814
2059
|
}
|
|
2060
|
+
detachOtelState();
|
|
1815
2061
|
state = null;
|
|
1816
2062
|
}
|
|
1817
2063
|
// ── Internal helpers ─────────────────────────────────────────────────────
|