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