@anybio/govern 0.0.0 → 0.2.2

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.
@@ -0,0 +1,1695 @@
1
+ import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
2
+ import { isBaseMessage, AIMessage } from '@langchain/core/messages';
3
+ import { RunnableLambda } from '@langchain/core/runnables';
4
+
5
+ // src/langchain.ts
6
+
7
+ // src/errors.ts
8
+ var MAX_SERVER_MESSAGE_CHARS = 300;
9
+ var GovernError = class extends Error {
10
+ name = "GovernError";
11
+ constructor(message, options) {
12
+ super(message, options);
13
+ Object.setPrototypeOf(this, new.target.prototype);
14
+ }
15
+ };
16
+ var GovernConfigError = class extends GovernError {
17
+ name = "GovernConfigError";
18
+ };
19
+ var GovernApiError = class extends GovernError {
20
+ name = "GovernApiError";
21
+ status;
22
+ /** The server's machine-readable error kind (for example `BAD_REQUEST_ERROR`), when it sent one. */
23
+ kind;
24
+ /** Whether the SDK considered the failure retryable (429 and 5xx). */
25
+ retryable;
26
+ /** Milliseconds the server asked us to wait, from `Retry-After`, when it sent one. */
27
+ retryAfterMs;
28
+ /**
29
+ * The server's own error text, collapsed to one line and bounded, or `null`.
30
+ *
31
+ * Deliberately not part of `.message`: an error message is the string that
32
+ * ends up in a log line, an alert and a bug report, and the SDK cannot
33
+ * promise what a server put in this one. Read it when you are debugging a
34
+ * call, and treat what comes back the way you treat the message it was
35
+ * about.
36
+ */
37
+ serverMessage;
38
+ constructor(input) {
39
+ super(`AnyBio Govern API responded ${input.status}${input.kind ? ` (${input.kind})` : ""}`);
40
+ this.status = input.status;
41
+ this.kind = input.kind;
42
+ this.retryable = input.retryable;
43
+ this.retryAfterMs = input.retryAfterMs;
44
+ this.serverMessage = input.serverMessage === null ? null : truncate(input.serverMessage);
45
+ }
46
+ };
47
+ var GovernConflictError = class extends GovernApiError {
48
+ name = "GovernConflictError";
49
+ };
50
+ var GovernNetworkError = class extends GovernError {
51
+ name = "GovernNetworkError";
52
+ constructor(message, options) {
53
+ super(message, options);
54
+ }
55
+ };
56
+ var GovernTimeoutError = class extends GovernError {
57
+ name = "GovernTimeoutError";
58
+ timeoutMs;
59
+ constructor(timeoutMs) {
60
+ super(`AnyBio Govern request timed out after ${timeoutMs} ms`);
61
+ this.timeoutMs = timeoutMs;
62
+ }
63
+ };
64
+ var GovernAbortError = class extends GovernError {
65
+ name = "GovernAbortError";
66
+ constructor(reason) {
67
+ super("AnyBio Govern request aborted", reason === void 0 ? void 0 : { cause: reason });
68
+ }
69
+ };
70
+ var GovernWebhookError = class extends GovernError {
71
+ name = "GovernWebhookError";
72
+ };
73
+ function truncate(text) {
74
+ const oneLine = text.replace(/\s+/g, " ").trim();
75
+ return oneLine.length > MAX_SERVER_MESSAGE_CHARS ? `${oneLine.slice(0, MAX_SERVER_MESSAGE_CHARS)}...` : oneLine;
76
+ }
77
+
78
+ // src/crypto.ts
79
+ var cached = null;
80
+ function webCrypto() {
81
+ if (cached) return cached;
82
+ cached = (async () => {
83
+ const global = globalThis.crypto;
84
+ if (global?.subtle) return global;
85
+ try {
86
+ const specifier = "node:crypto";
87
+ const mod = await import(
88
+ /* @vite-ignore */
89
+ specifier
90
+ );
91
+ if (mod.webcrypto?.subtle) return mod.webcrypto;
92
+ } catch {
93
+ }
94
+ throw new GovernConfigError(
95
+ "Web Crypto (crypto.subtle) is not available in this runtime. Node 20+ and edge runtimes provide it."
96
+ );
97
+ })();
98
+ return cached;
99
+ }
100
+ var HEX = "0123456789abcdef";
101
+ function toHex(bytes) {
102
+ let out = "";
103
+ for (const byte of bytes) out += HEX[byte >> 4] + HEX[byte & 15];
104
+ return out;
105
+ }
106
+ async function sha256Hex(text) {
107
+ const { subtle } = await webCrypto();
108
+ const digest = await subtle.digest("SHA-256", new TextEncoder().encode(text));
109
+ return toHex(new Uint8Array(digest));
110
+ }
111
+ async function hmacSha256Hex(secret, message) {
112
+ const { subtle } = await webCrypto();
113
+ const key = await subtle.importKey(
114
+ "raw",
115
+ new TextEncoder().encode(secret),
116
+ { name: "HMAC", hash: "SHA-256" },
117
+ false,
118
+ ["sign"]
119
+ );
120
+ const bytes = typeof message === "string" ? new TextEncoder().encode(message) : message;
121
+ const signature = await subtle.sign("HMAC", key, bytes);
122
+ return toHex(new Uint8Array(signature));
123
+ }
124
+ function timingSafeEqual(a, b) {
125
+ if (a.length !== b.length) return false;
126
+ let diff = 0;
127
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
128
+ return diff === 0;
129
+ }
130
+ function randomId() {
131
+ const global = globalThis.crypto;
132
+ if (global?.randomUUID) return global.randomUUID();
133
+ const bytes = new Uint8Array(16);
134
+ if (global?.getRandomValues) {
135
+ global.getRandomValues(bytes);
136
+ } else {
137
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
138
+ }
139
+ bytes[6] = bytes[6] & 15 | 64;
140
+ bytes[8] = bytes[8] & 63 | 128;
141
+ const hex = toHex(bytes);
142
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
143
+ }
144
+
145
+ // src/version.ts
146
+ var SDK_VERSION = "0.2.2";
147
+ var SDK_NAME = "@anybio/govern";
148
+
149
+ // src/http.ts
150
+ var BACKOFF_BASE_MS = 250;
151
+ var BACKOFF_MAX_MS = 5e3;
152
+ var RETRY_AFTER_MAX_MS = 3e4;
153
+ var HEADER_IDEMPOTENCY_KEY = "Idempotency-Key";
154
+ async function send(config, request) {
155
+ const url = buildUrl(config.baseUrl, request.path, request.query);
156
+ const headers = {
157
+ Authorization: `Bearer ${config.apiKey}`,
158
+ Accept: "application/json",
159
+ "X-AnyBio-Govern-SDK": `${SDK_NAME}/${SDK_VERSION}`
160
+ };
161
+ if (request.body !== void 0) headers["Content-Type"] = "application/json";
162
+ if (request.idempotencyKey) headers[HEADER_IDEMPOTENCY_KEY] = request.idempotencyKey;
163
+ const payload = request.body === void 0 ? void 0 : JSON.stringify(request.body);
164
+ const retry = request.retry ?? true;
165
+ const attempts = retry ? config.maxRetries + 1 : 1;
166
+ let lastError = null;
167
+ for (let attempt = 1; attempt <= attempts; attempt++) {
168
+ if (request.signal?.aborted) throw new GovernAbortError(request.signal.reason);
169
+ config.onEvent?.({ type: "request", method: request.method, path: request.path, attempt });
170
+ const started = now();
171
+ let response;
172
+ try {
173
+ response = await withTimeout(
174
+ config.fetch,
175
+ url,
176
+ { method: request.method, headers, body: payload },
177
+ config.timeoutMs,
178
+ request.signal
179
+ );
180
+ } catch (error) {
181
+ if (error instanceof GovernAbortError) throw error;
182
+ const failure2 = error instanceof GovernTimeoutError ? error : new GovernNetworkError("AnyBio Govern request failed before a response arrived", {
183
+ cause: error
184
+ });
185
+ lastError = failure2;
186
+ if (attempt < attempts) {
187
+ const delayMs = backoff(attempt);
188
+ config.onEvent?.({
189
+ type: "retry",
190
+ method: request.method,
191
+ path: request.path,
192
+ attempt,
193
+ status: null,
194
+ delayMs,
195
+ reason: failure2 instanceof GovernTimeoutError ? "timeout" : "network"
196
+ });
197
+ await sleep(delayMs, request.signal);
198
+ continue;
199
+ }
200
+ throw failure2;
201
+ }
202
+ config.onEvent?.({
203
+ type: "response",
204
+ method: request.method,
205
+ path: request.path,
206
+ status: response.status,
207
+ attempt,
208
+ durationMs: Math.round(now() - started)
209
+ });
210
+ if (response.ok) {
211
+ return { status: response.status, body: await readJson(response), headers: response.headers };
212
+ }
213
+ const retryable = response.status === 429 || response.status >= 500;
214
+ const retryAfterMs = response.status === 429 ? parseRetryAfter(response.headers.get("retry-after")) : null;
215
+ const { kind, message } = await readError(response);
216
+ const detail = { status: response.status, kind, serverMessage: message, retryable, retryAfterMs };
217
+ const failure = response.status === 409 ? new GovernConflictError(detail) : new GovernApiError(detail);
218
+ lastError = failure;
219
+ if (retryable && attempt < attempts) {
220
+ const delayMs = retryAfterMs ?? backoff(attempt);
221
+ config.onEvent?.({
222
+ type: "retry",
223
+ method: request.method,
224
+ path: request.path,
225
+ attempt,
226
+ status: response.status,
227
+ delayMs,
228
+ reason: response.status === 429 ? "rate_limited" : "server_error"
229
+ });
230
+ await sleep(delayMs, request.signal);
231
+ continue;
232
+ }
233
+ throw failure;
234
+ }
235
+ throw lastError ?? new GovernNetworkError("AnyBio Govern request failed");
236
+ }
237
+ function buildUrl(baseUrl, path, query) {
238
+ const base = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
239
+ const url = new URL(`${base}${path}`);
240
+ if (query) {
241
+ for (const [key, value] of Object.entries(query)) {
242
+ if (value !== void 0) url.searchParams.set(key, value);
243
+ }
244
+ }
245
+ return url.toString();
246
+ }
247
+ async function withTimeout(fetchImpl, url, init, timeoutMs, signal) {
248
+ const controller = new AbortController();
249
+ let timedOut = false;
250
+ let rejectTimeout = () => {
251
+ };
252
+ const timeout = new Promise((_, reject) => {
253
+ rejectTimeout = reject;
254
+ });
255
+ const timer = setTimeout(() => {
256
+ timedOut = true;
257
+ controller.abort();
258
+ rejectTimeout(new GovernTimeoutError(timeoutMs));
259
+ }, timeoutMs);
260
+ const onAbort = () => {
261
+ controller.abort();
262
+ rejectTimeout(new GovernAbortError(signal?.reason));
263
+ };
264
+ signal?.addEventListener("abort", onAbort, { once: true });
265
+ try {
266
+ return await Promise.race([fetchImpl(url, { ...init, signal: controller.signal }), timeout]);
267
+ } catch (error) {
268
+ if (signal?.aborted) throw new GovernAbortError(signal.reason);
269
+ if (timedOut) throw new GovernTimeoutError(timeoutMs);
270
+ throw error;
271
+ } finally {
272
+ clearTimeout(timer);
273
+ signal?.removeEventListener("abort", onAbort);
274
+ }
275
+ }
276
+ async function readJson(response) {
277
+ const text = await response.text();
278
+ if (!text) return void 0;
279
+ try {
280
+ return JSON.parse(text);
281
+ } catch {
282
+ throw new GovernNetworkError(`AnyBio Govern API returned a non-JSON body with status ${response.status}`);
283
+ }
284
+ }
285
+ async function readError(response) {
286
+ let text = "";
287
+ try {
288
+ text = await response.text();
289
+ } catch {
290
+ return { kind: null, message: null };
291
+ }
292
+ if (!text) return { kind: null, message: null };
293
+ try {
294
+ const parsed = JSON.parse(text);
295
+ const kind = typeof parsed.kind === "string" ? parsed.kind : null;
296
+ const message = typeof parsed.error_message === "string" ? parsed.error_message : typeof parsed.error === "string" ? parsed.error : typeof parsed.message === "string" ? parsed.message : null;
297
+ return { kind, message };
298
+ } catch {
299
+ return { kind: null, message: null };
300
+ }
301
+ }
302
+ function parseRetryAfter(header2, nowMs = Date.now()) {
303
+ if (!header2) return null;
304
+ const trimmed = header2.trim();
305
+ if (/^\d+$/.test(trimmed)) {
306
+ return Math.min(Number(trimmed) * 1e3, RETRY_AFTER_MAX_MS);
307
+ }
308
+ const at = Date.parse(trimmed);
309
+ if (Number.isNaN(at)) return null;
310
+ return Math.max(0, Math.min(at - nowMs, RETRY_AFTER_MAX_MS));
311
+ }
312
+ function backoff(attempt, random = Math.random) {
313
+ const ceiling = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.max(0, attempt - 1));
314
+ return Math.round(random() * ceiling);
315
+ }
316
+ function sleep(ms, signal) {
317
+ return new Promise((resolve2, reject) => {
318
+ if (signal?.aborted) {
319
+ reject(new GovernAbortError(signal.reason));
320
+ return;
321
+ }
322
+ const timer = setTimeout(() => {
323
+ signal?.removeEventListener("abort", onAbort);
324
+ resolve2();
325
+ }, ms);
326
+ const onAbort = () => {
327
+ clearTimeout(timer);
328
+ reject(new GovernAbortError(signal?.reason));
329
+ };
330
+ signal?.addEventListener("abort", onAbort, { once: true });
331
+ });
332
+ }
333
+ function now() {
334
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
335
+ }
336
+
337
+ // src/types.ts
338
+ var IN_SESSION_CHANNELS = ["web_chat", "app_message"];
339
+ function isInSessionChannel(channel) {
340
+ return typeof channel === "string" && IN_SESSION_CHANNELS.includes(channel);
341
+ }
342
+ var REASONS = {
343
+ gateUnavailable: "gate_unavailable",
344
+ /** The patient opted out: `block`, on every channel. */
345
+ optedOut: "opted_out",
346
+ /**
347
+ * No `granted` consent on record, on a channel that requires one, for a turn
348
+ * that answers nothing the patient sent: `block`. A turn that carries the
349
+ * patient's `inbound` proceeds.
350
+ */
351
+ consentMissing: "consent_missing",
352
+ /** The consent on record was revoked: `block`, on every outbound channel. */
353
+ consentRevoked: "consent_revoked",
354
+ /** The patient is over the application's cap in the current window: `hold`. */
355
+ frequencyCap: "frequency_cap",
356
+ /**
357
+ * The patient-state store (opt-out, consent, the cap) could not be read, so
358
+ * nothing is known about whether this patient may be messaged. Always beside
359
+ * `gate_unavailable`. `sendHoldingLine` is false on it: another message could
360
+ * be the wrong thing, not merely an unnecessary one.
361
+ */
362
+ patientStateUnavailable: "patient_state_unavailable",
363
+ /**
364
+ * SDK-only: the API answered and refused the call, and would refuse it again.
365
+ * A revoked or wrong application key, a key not bound to the application, a
366
+ * request the server will not accept. `guard` still holds in enforce, so
367
+ * nothing reaches a patient, but the thing to check is the integration's own
368
+ * configuration, not the API's availability: this does not heal on its own.
369
+ */
370
+ clientMisconfigured: "client_misconfigured",
371
+ /** SDK-only: the server sent a decision value this version does not know. */
372
+ unknownDecision: "unknown_decision"
373
+ };
374
+
375
+ // src/webhook.ts
376
+ var WEBHOOK_HEADERS = {
377
+ timestamp: "x-govern-timestamp",
378
+ signature: "x-govern-signature",
379
+ event: "x-govern-event",
380
+ delivery: "x-govern-delivery"
381
+ };
382
+ var WEBHOOK_EVENTS = {
383
+ decisionReleased: "decision.released",
384
+ decisionRejected: "decision.rejected",
385
+ handoffOpened: "handoff.opened",
386
+ handoffClaimed: "handoff.claimed",
387
+ handoffResolved: "handoff.resolved",
388
+ handoffResumed: "handoff.resumed"
389
+ };
390
+ async function signWebhookPayload(secret, timestamp, body) {
391
+ requireSecret(secret, "signWebhookPayload");
392
+ return `v1=${await hmacSha256Hex(secret, signedMessage(timestamp, body))}`;
393
+ }
394
+ async function verifyWebhookSignature(rawBody, headers, secret, options = {}) {
395
+ requireSecret(secret, "verifyWebhookSignature");
396
+ const tolerance = options.toleranceSeconds ?? 300;
397
+ if (!Number.isFinite(tolerance) || tolerance < 0) {
398
+ throw new GovernConfigError(
399
+ "verifyWebhookSignature: toleranceSeconds must be a finite number of seconds, zero or more. Pass 0 to accept a delivery of any age on purpose; a negative or non-finite value did that silently, which is a replay window left open by accident."
400
+ );
401
+ }
402
+ const bodyBytes = toBytes(rawBody);
403
+ const timestampHeader = header(headers, WEBHOOK_HEADERS.timestamp);
404
+ const signatureHeader = header(headers, WEBHOOK_HEADERS.signature);
405
+ if (!timestampHeader || !signatureHeader) {
406
+ throw new GovernWebhookError("missing X-Govern-Timestamp or X-Govern-Signature header");
407
+ }
408
+ const timestamp = Number(timestampHeader.trim());
409
+ if (!Number.isInteger(timestamp)) {
410
+ throw new GovernWebhookError("X-Govern-Timestamp is not an integer");
411
+ }
412
+ if (tolerance > 0) {
413
+ const now2 = options.now ? options.now() : Math.floor(Date.now() / 1e3);
414
+ if (!Number.isFinite(now2)) {
415
+ throw new GovernConfigError(
416
+ "verifyWebhookSignature: the `now` option must return the current unix time in seconds as a finite number. A value that is not one cannot be compared with the delivery's timestamp, which leaves the replay window open."
417
+ );
418
+ }
419
+ if (Math.abs(now2 - timestamp) > tolerance) {
420
+ throw new GovernWebhookError("X-Govern-Timestamp is outside the accepted window");
421
+ }
422
+ }
423
+ const expected = await signWebhookPayload(secret, timestamp, bodyBytes);
424
+ const candidates = signatureHeader.split(/[\s,]+/).map((s) => s.trim()).filter((s) => s.startsWith("v1="));
425
+ const matched = candidates.some((candidate) => timingSafeEqual(candidate, expected));
426
+ if (!matched) throw new GovernWebhookError("webhook signature does not match");
427
+ return {
428
+ timestamp,
429
+ event: header(headers, WEBHOOK_HEADERS.event),
430
+ deliveryId: header(headers, WEBHOOK_HEADERS.delivery),
431
+ body: new TextDecoder().decode(bodyBytes)
432
+ };
433
+ }
434
+ async function handleWebhook(rawBody, headers, secret, options = {}) {
435
+ const verified = await verifyWebhookSignature(rawBody, headers, secret, options);
436
+ let parsed;
437
+ try {
438
+ parsed = JSON.parse(verified.body);
439
+ } catch {
440
+ throw new GovernWebhookError("webhook body is not JSON");
441
+ }
442
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
443
+ throw new GovernWebhookError("webhook body is not a JSON object");
444
+ }
445
+ return parseEvent(parsed, verified.event);
446
+ }
447
+ function parseEvent(raw, headerEvent) {
448
+ const event = str(raw.event) ?? headerEvent ?? "unknown";
449
+ const envelope = {
450
+ id: str(raw.id) ?? "",
451
+ attempt: num(raw.attempt) ?? 1,
452
+ createdAt: str(raw.created_at) ?? "",
453
+ applicationId: str(raw.application_id) ?? "",
454
+ at: str(raw.at) ?? "",
455
+ raw
456
+ };
457
+ switch (event) {
458
+ case WEBHOOK_EVENTS.decisionReleased:
459
+ case WEBHOOK_EVENTS.decisionRejected: {
460
+ const reviewer = raw.reviewer && typeof raw.reviewer === "object" ? raw.reviewer : {};
461
+ return {
462
+ ...envelope,
463
+ type: event,
464
+ decisionId: str(raw.decision_id) ?? "",
465
+ conversationId: str(raw.conversation_id) ?? "",
466
+ turnId: str(raw.turn_id) ?? "",
467
+ channel: str(raw.channel) ?? "",
468
+ reviewState: event === WEBHOOK_EVENTS.decisionReleased ? "released" : "rejected",
469
+ reviewer: { role: str(reviewer.role) },
470
+ releasedContent: event === WEBHOOK_EVENTS.decisionReleased ? str(raw.released_content) : null,
471
+ releasedWith: str(raw.released_with),
472
+ model: str(raw.model),
473
+ modelVersion: str(raw.model_version),
474
+ stopClass: raw.stop_class === void 0 || raw.stop_class === null ? null : raw.stop_class === "never_sendable" ? "never_sendable" : "uncertain"
475
+ };
476
+ }
477
+ case WEBHOOK_EVENTS.handoffOpened:
478
+ case WEBHOOK_EVENTS.handoffClaimed:
479
+ case WEBHOOK_EVENTS.handoffResolved:
480
+ case WEBHOOK_EVENTS.handoffResumed:
481
+ return {
482
+ ...envelope,
483
+ type: event,
484
+ handoffId: str(raw.handoff_id) ?? "",
485
+ decisionId: str(raw.decision_id),
486
+ patientRefHash: str(raw.patient_ref_hash),
487
+ state: str(raw.state) ?? "",
488
+ version: num(raw.version) ?? 0,
489
+ queueLabel: str(raw.queue_label),
490
+ assigned: raw.assigned === true,
491
+ dueAt: str(raw.due_at),
492
+ resolvedAt: str(raw.resolved_at),
493
+ pausesAutomation: raw.pauses_automation !== false
494
+ };
495
+ default:
496
+ return { ...envelope, type: "unknown", event };
497
+ }
498
+ }
499
+ function requireSecret(secret, fn) {
500
+ if (typeof secret !== "string" || secret.trim() === "") {
501
+ throw new GovernConfigError(
502
+ `${fn}: a webhook secret is required. Pass the application's signing secret (\`whsec_...\`); an empty or blank one cannot verify anything.`
503
+ );
504
+ }
505
+ }
506
+ function signedMessage(timestamp, body) {
507
+ const prefix = new TextEncoder().encode(`${timestamp}.`);
508
+ const bodyBytes = typeof body === "string" ? new TextEncoder().encode(body) : body;
509
+ const out = new Uint8Array(prefix.length + bodyBytes.length);
510
+ out.set(prefix, 0);
511
+ out.set(bodyBytes, prefix.length);
512
+ return out;
513
+ }
514
+ function toBytes(body) {
515
+ if (typeof body === "string") return new TextEncoder().encode(body);
516
+ if (body instanceof Uint8Array) return body;
517
+ if (body instanceof ArrayBuffer) return new Uint8Array(body);
518
+ throw new GovernConfigError(
519
+ "verifyWebhookSignature: the body must be the raw request body, as a string, a Uint8Array (a Node Buffer is one) or an ArrayBuffer. A body that has been through JSON.parse, or no body at all, is not the bytes that were signed, so there is nothing a signature can be checked against."
520
+ );
521
+ }
522
+ function header(headers, name) {
523
+ if (typeof headers.get === "function") {
524
+ const value2 = headers.get(name);
525
+ return value2 ?? null;
526
+ }
527
+ const record = headers;
528
+ const key = Object.keys(record).find((k) => k.toLowerCase() === name);
529
+ if (!key) return null;
530
+ const value = record[key];
531
+ if (Array.isArray(value)) return value[0] ?? null;
532
+ return value ?? null;
533
+ }
534
+ function str(value) {
535
+ return typeof value === "string" ? value : null;
536
+ }
537
+ function num(value) {
538
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
539
+ }
540
+
541
+ // src/client.ts
542
+ var DEFAULT_BASE_URL = "https://api.anybio.io";
543
+ var DEFAULT_TIMEOUT_MS = 5e3;
544
+ var DEFAULT_MAX_RETRIES = 2;
545
+ var DEFAULT_HOLD_MESSAGE = "Thanks for your message. A person from our team will review it and follow up with you shortly.";
546
+ var RESERVED_TURN_ID_PREFIX = "govern:";
547
+ var MAX_CONVERSATION_ID_CHARS = 187;
548
+ var MAX_TURN_ID_CHARS = 206;
549
+ var TRANSIENT_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429]);
550
+ function isClientMisconfiguration(error) {
551
+ if (!(error instanceof GovernApiError)) return false;
552
+ if (error.status < 400 || error.status >= 500) return false;
553
+ return !TRANSIENT_HTTP_STATUSES.has(error.status);
554
+ }
555
+ var GOVERN_PATHS = {
556
+ evaluate: "/api/v1/govern/evaluate",
557
+ decision: (id) => `/api/v1/govern/decisions/${encodeURIComponent(id)}`,
558
+ outcome: (id) => `/api/v1/govern/decisions/${encodeURIComponent(id)}/outcome`,
559
+ disclosures: "/api/v1/govern/disclosures",
560
+ transcripts: "/api/v1/govern/transcripts",
561
+ transcriptJob: (id) => `/api/v1/govern/transcripts/${encodeURIComponent(id)}`,
562
+ transcriptTurns: (id) => `/api/v1/govern/transcripts/${encodeURIComponent(id)}/turns`,
563
+ patientConsent: "/api/v1/govern/patients/consent",
564
+ patientOptOut: "/api/v1/govern/patients/opt-out",
565
+ patientState: "/api/v1/govern/patients/state",
566
+ webhookDeliveries: "/api/v1/govern/webhook-deliveries",
567
+ handoffs: "/api/v1/govern/handoffs",
568
+ handoff: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}`,
569
+ handoffClaim: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}/claim`,
570
+ handoffContact: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}/contact-attempt`,
571
+ handoffResolve: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}/resolve`,
572
+ handoffResume: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}/resume`
573
+ };
574
+ var KNOWN_VERDICTS = /* @__PURE__ */ new Set(["allow", "hold", "block", "route_to_human"]);
575
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
576
+ var Govern = class {
577
+ application;
578
+ applicationId;
579
+ baseUrl;
580
+ holdMessage;
581
+ assumeMode;
582
+ /** Hand-offs on your team. */
583
+ handoffs;
584
+ transport;
585
+ onEvent;
586
+ modes = /* @__PURE__ */ new Map();
587
+ disclosureRefs = new BoundedMap(1e4);
588
+ pendingAcks = new BoundedMap(1e4);
589
+ reportedDecisions = new BoundedMap(1e4);
590
+ /** Decision ids whose holding line this instance has already armed. */
591
+ holdingLines = new BoundedMap(1e4);
592
+ releaseWaiters = /* @__PURE__ */ new Map();
593
+ constructor(options) {
594
+ if (!options.dangerouslyAllowBrowser && runningInBrowser()) {
595
+ throw new GovernConfigError(
596
+ "Govern must not run in a browser: the application key is a server-side secret. Call the API from your server, or from an edge or serverless function."
597
+ );
598
+ }
599
+ if (typeof options.apiKey !== "string" || options.apiKey.trim() === "") {
600
+ throw new GovernConfigError("Govern requires apiKey (the application key from the console).");
601
+ }
602
+ if (typeof options.application !== "string" || options.application.trim() === "") {
603
+ throw new GovernConfigError("Govern requires application (the application id or a label).");
604
+ }
605
+ const fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch : void 0);
606
+ if (!fetchImpl) {
607
+ throw new GovernConfigError("No fetch implementation found. Pass one as `fetch` or run on Node 18+.");
608
+ }
609
+ this.application = options.application.trim();
610
+ this.applicationId = UUID.test(this.application) ? this.application.toLowerCase() : null;
611
+ this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
612
+ this.holdMessage = options.holdMessage ?? DEFAULT_HOLD_MESSAGE;
613
+ this.assumeMode = options.assumeMode ?? "enforce";
614
+ this.onEvent = isolateEvents(options.onEvent);
615
+ this.transport = {
616
+ baseUrl: this.baseUrl,
617
+ apiKey: options.apiKey.trim(),
618
+ fetch: fetchImpl,
619
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
620
+ maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
621
+ onEvent: this.onEvent
622
+ };
623
+ this.handoffs = new GovernHandoffs(this.transport);
624
+ }
625
+ // -------------------------------------------------------------------------
626
+ // The contract
627
+ // -------------------------------------------------------------------------
628
+ /**
629
+ * Evaluate one turn. Enforce answers inline (200). Observe answers 202 at
630
+ * once with `decision: "allow"` and a decision id; the gate runs after the
631
+ * response and its verdict lands on the record as `wouldHave`. A replay of
632
+ * the same `turnId` returns the stored decision.
633
+ */
634
+ async evaluate(input) {
635
+ requireConversationId(input.conversationId);
636
+ requireTurnId(input.turnId);
637
+ requireText(input.content, "content");
638
+ const disclosure = input.disclosure ?? this.disclosureAttachment(input.conversationId);
639
+ const body = {
640
+ conversation_id: input.conversationId,
641
+ turn_id: input.turnId,
642
+ channel: input.channel,
643
+ audience: input.audience,
644
+ content: input.content
645
+ };
646
+ if (this.applicationId) body.application_id = this.applicationId;
647
+ if (input.patientRef !== void 0) body.patient_ref = input.patientRef;
648
+ if (disclosure) {
649
+ body.disclosure = {};
650
+ if (disclosure.established !== void 0) body.disclosure.established = disclosure.established;
651
+ if (disclosure.ref !== void 0) body.disclosure.ref = disclosure.ref;
652
+ }
653
+ if (input.metadata !== void 0) body.metadata = input.metadata;
654
+ if (input.modeHint !== void 0) body.mode_hint = input.modeHint;
655
+ if (input.inbound) {
656
+ body.inbound = {
657
+ content: input.inbound.content,
658
+ received_at: isoString(input.inbound.receivedAt)
659
+ };
660
+ }
661
+ const model = input.model?.trim();
662
+ if (model) body.model = model;
663
+ const modelVersion = input.modelVersion?.trim();
664
+ if (modelVersion) body.model_version = modelVersion;
665
+ const response = await send(this.transport, {
666
+ method: "POST",
667
+ path: GOVERN_PATHS.evaluate,
668
+ body,
669
+ idempotencyKey: input.turnId,
670
+ signal: input.signal
671
+ });
672
+ const decision = this.read(toDecision(response.body, response.status === 202));
673
+ this.onEvent?.({
674
+ type: "decision",
675
+ decisionId: decision.id,
676
+ conversationId: decision.conversationId,
677
+ turnId: decision.turnId,
678
+ channel: decision.channel,
679
+ audience: decision.audience,
680
+ decision: decision.decision,
681
+ mode: decision.mode,
682
+ status: decision.status,
683
+ accepted: decision.accepted,
684
+ reasons: decision.reasons
685
+ });
686
+ return decision;
687
+ }
688
+ /** The decision with its current review state; the first hold-resolution path. */
689
+ async getDecision(decisionId, options = {}) {
690
+ requireText(decisionId, "decisionId");
691
+ const response = await send(this.transport, {
692
+ method: "GET",
693
+ path: GOVERN_PATHS.decision(decisionId),
694
+ signal: options.signal
695
+ });
696
+ return this.read(toDecision(response.body, false));
697
+ }
698
+ /**
699
+ * Report what went out. The text is hashed here with SHA-256 and only the
700
+ * hash is sent. One outcome per decision: the same report again is
701
+ * accepted; a different one is refused with 409.
702
+ */
703
+ async reportOutcome(decisionId, input) {
704
+ requireText(decisionId, "decisionId");
705
+ const given = input.contentHash?.trim().toLowerCase();
706
+ let hash = given === "" ? void 0 : given;
707
+ if (hash === void 0 && input.content !== void 0) hash = await sha256Hex(input.content);
708
+ if (input.delivered && hash === void 0) {
709
+ throw new GovernConfigError(
710
+ "reportOutcome: pass `content` (hashed locally) or `contentHash` when delivered is true."
711
+ );
712
+ }
713
+ const decision = await this.postOutcome(decisionId, {
714
+ delivered: input.delivered,
715
+ deliveredAt: isoString(input.deliveredAt ?? /* @__PURE__ */ new Date()),
716
+ contentHash: hash,
717
+ deliveryRef: input.deliveryRef,
718
+ signal: input.signal
719
+ });
720
+ this.reportedDecisions.set(decisionId, true);
721
+ this.onEvent?.({ type: "outcome", decisionId, delivered: input.delivered, auto: false });
722
+ return decision;
723
+ }
724
+ /**
725
+ * Record the AI-identity disclosure shown at the start of a conversation.
726
+ * Once per conversation; the returned `ref` is attached to every later
727
+ * `evaluate` for the conversation automatically.
728
+ */
729
+ async recordDisclosure(input) {
730
+ requireConversationId(input.conversationId);
731
+ requireText(input.textShown, "textShown");
732
+ const body = {
733
+ conversation_id: input.conversationId,
734
+ channel: input.channel,
735
+ text_shown: input.textShown,
736
+ at: isoString(input.at ?? /* @__PURE__ */ new Date())
737
+ };
738
+ if (this.applicationId) body.application_id = this.applicationId;
739
+ const response = await send(this.transport, {
740
+ method: "POST",
741
+ path: GOVERN_PATHS.disclosures,
742
+ body,
743
+ signal: input.signal
744
+ });
745
+ const view = response.body;
746
+ this.disclosureRefs.set(input.conversationId, view.ref);
747
+ return {
748
+ ref: view.ref,
749
+ applicationId: view.application_id,
750
+ conversationId: view.conversation_id,
751
+ channel: view.channel,
752
+ evidenceId: view.evidence_id,
753
+ recordedAt: view.recorded_at,
754
+ created: response.status === 201,
755
+ raw: view
756
+ };
757
+ }
758
+ /**
759
+ * Poll a held decision with backoff until a reviewer releases or rejects
760
+ * it. Resolves `null` on timeout; throws `GovernAbortError` if `signal`
761
+ * fires. A webhook handled through `handleWebhook` wakes the poll early.
762
+ */
763
+ async waitForRelease(decisionId, options = {}) {
764
+ requireText(decisionId, "decisionId");
765
+ const timeoutMs = options.timeoutMs ?? 15 * 6e4;
766
+ const maxIntervalMs = options.maxIntervalMs ?? 15e3;
767
+ let intervalMs = options.intervalMs ?? 1e3;
768
+ const deadline = Date.now() + timeoutMs;
769
+ for (; ; ) {
770
+ const decision = await this.getDecision(decisionId, { signal: options.signal });
771
+ const settled = settle(decision);
772
+ if (settled) return settled;
773
+ const remaining = deadline - Date.now();
774
+ if (remaining <= 0) return null;
775
+ await this.sleepOrWake(decisionId, Math.min(intervalMs, remaining), options.signal);
776
+ intervalMs = Math.min(intervalMs * 2, maxIntervalMs);
777
+ }
778
+ }
779
+ /**
780
+ * Verify a webhook delivery and return the typed event. When the event
781
+ * resolves a held decision, any `waitForRelease` on it is woken at once.
782
+ */
783
+ async handleWebhook(rawBody, headers, secret, options) {
784
+ const event = await handleWebhook(rawBody, headers, secret, options);
785
+ if (event.type === "decision.released" || event.type === "decision.rejected") {
786
+ this.wake(event.decisionId);
787
+ }
788
+ return event;
789
+ }
790
+ // -------------------------------------------------------------------------
791
+ // guard
792
+ // -------------------------------------------------------------------------
793
+ /**
794
+ * Run `fn` to get the draft, evaluate it, and return what to deliver.
795
+ *
796
+ * - allow: the draft (or, for a clinician audience, the gate's substitution when it returns one)
797
+ * - hold or block: the hold message when `showHoldText`, else the empty string
798
+ * - API unreachable: a hold, as above, when the channel's last known mode is
799
+ * enforce (or unknown), the draft flagged `degraded` when it is observe or off
800
+ *
801
+ * On a hold, `sendHoldingLine` says whether a holding line is owed to the
802
+ * patient now: at most once per decision in this instance, and never where
803
+ * the contract says another message is the wrong thing. `showHoldText`
804
+ * applies the channel: true on every hold in an in-session channel
805
+ * (`web_chat`, `app_message`), where the patient is waiting for the reply,
806
+ * and exactly `sendHoldingLine` on an outbound or unknown channel.
807
+ *
808
+ * Never returns rewritten text for a patient audience.
809
+ */
810
+ async guard(fn, ctx) {
811
+ requireConversationId(ctx.conversationId);
812
+ if (ctx.turnId !== void 0) requireTurnId(ctx.turnId);
813
+ void this.flushPendingAck(ctx.conversationId);
814
+ const produced = await fn();
815
+ const draft = typeof produced === "string" ? produced : produced?.text;
816
+ if (typeof draft !== "string") {
817
+ throw new GovernConfigError("guard: the draft function must return a string or { text: string }.");
818
+ }
819
+ const turnId = ctx.turnId ?? randomId();
820
+ const holdMessage = ctx.holdMessage ?? this.holdMessage;
821
+ let record = null;
822
+ let mode;
823
+ let degraded = false;
824
+ let degradeCause = "gate_unavailable";
825
+ let routeToHuman = false;
826
+ let handoff = null;
827
+ let inboundFlags = [];
828
+ try {
829
+ const input = {
830
+ conversationId: ctx.conversationId,
831
+ turnId,
832
+ channel: ctx.channel,
833
+ audience: ctx.audience,
834
+ content: draft
835
+ };
836
+ if (ctx.patientRef !== void 0) input.patientRef = ctx.patientRef;
837
+ if (ctx.disclosure !== void 0) input.disclosure = ctx.disclosure;
838
+ if (ctx.metadata !== void 0) input.metadata = ctx.metadata;
839
+ if (ctx.inbound !== void 0) input.inbound = ctx.inbound;
840
+ if (ctx.model !== void 0) input.model = ctx.model;
841
+ if (ctx.modelVersion !== void 0) input.modelVersion = ctx.modelVersion;
842
+ if (ctx.signal !== void 0) input.signal = ctx.signal;
843
+ record = await this.evaluate(input);
844
+ mode = record.mode;
845
+ degraded = record.degraded;
846
+ routeToHuman = record.routeToHuman || record.decision === "route_to_human";
847
+ handoff = record.handoff;
848
+ inboundFlags = record.inboundFlags;
849
+ } catch (error) {
850
+ if (error instanceof GovernAbortError || error instanceof GovernConfigError) throw error;
851
+ degraded = true;
852
+ degradeCause = isClientMisconfiguration(error) ? REASONS.clientMisconfigured : REASONS.gateUnavailable;
853
+ const learned = this.modes.get(ctx.channel);
854
+ mode = learned ?? this.assumeMode;
855
+ this.onEvent?.({
856
+ type: "degraded",
857
+ conversationId: ctx.conversationId,
858
+ turnId,
859
+ channel: ctx.channel,
860
+ mode,
861
+ modeSource: learned ? "learned" : "assumed",
862
+ cause: degradeCause,
863
+ status: error instanceof GovernApiError ? error.status : null,
864
+ error: describe(error)
865
+ });
866
+ }
867
+ let decision;
868
+ let text;
869
+ let reasons;
870
+ if (record) {
871
+ decision = record.decision;
872
+ reasons = record.unknownDecision ? [...record.reasons, REASONS.unknownDecision] : record.reasons;
873
+ if (decision === "allow") {
874
+ text = record.audience === "clinician" && record.deliverableContent ? record.deliverableContent : draft;
875
+ } else {
876
+ text = holdMessage;
877
+ }
878
+ } else if (mode === "enforce") {
879
+ decision = "hold";
880
+ text = holdMessage;
881
+ reasons = [degradeCause];
882
+ } else {
883
+ decision = "allow";
884
+ text = draft;
885
+ reasons = [degradeCause];
886
+ }
887
+ const held = decision !== "allow";
888
+ const sendHoldingLine = held && record !== null && record.sendHoldingLine;
889
+ const showHoldText = held && (ctx.audience !== "patient" || isInSessionChannel(ctx.channel) || sendHoldingLine);
890
+ if (held && !showHoldText) text = "";
891
+ const stopClass = record?.stopClass ?? null;
892
+ const owed = !held || showHoldText;
893
+ const decisionId = record?.id ?? null;
894
+ if (decisionId) {
895
+ const delivered = owed;
896
+ this.pendingAcks.set(ctx.conversationId, {
897
+ decisionId,
898
+ delivered,
899
+ contentHash: delivered ? await sha256Hex(text) : void 0,
900
+ at: (/* @__PURE__ */ new Date()).toISOString()
901
+ });
902
+ }
903
+ let acked = false;
904
+ const ack = async (options = {}) => {
905
+ if (acked) return;
906
+ acked = true;
907
+ if (!decisionId) return;
908
+ const pending = this.pendingAcks.get(ctx.conversationId);
909
+ if (pending?.decisionId === decisionId) this.pendingAcks.delete(ctx.conversationId);
910
+ if (this.reportedDecisions.has(decisionId)) return;
911
+ const delivered = options.delivered ?? owed;
912
+ const outcome = { delivered };
913
+ if (options.content !== void 0) outcome.content = options.content;
914
+ else if (delivered) outcome.content = text;
915
+ if (options.deliveredAt !== void 0) outcome.deliveredAt = options.deliveredAt;
916
+ if (options.deliveryRef !== void 0) outcome.deliveryRef = options.deliveryRef;
917
+ await this.reportOutcome(decisionId, outcome);
918
+ };
919
+ return {
920
+ text,
921
+ decisionId,
922
+ decision,
923
+ mode,
924
+ degraded,
925
+ reasons,
926
+ held,
927
+ sendHoldingLine,
928
+ showHoldText,
929
+ stopClass,
930
+ routeToHuman,
931
+ handoff,
932
+ inboundFlags,
933
+ record,
934
+ ack
935
+ };
936
+ }
937
+ /** Report every outcome `guard` is still holding as delivered. Call on shutdown. */
938
+ async flushPendingAcks() {
939
+ const conversations = [...this.pendingAcks.keys()];
940
+ await Promise.all(conversations.map((c) => this.flushPendingAck(c)));
941
+ }
942
+ // -------------------------------------------------------------------------
943
+ // Memory the caller may read or seed
944
+ // -------------------------------------------------------------------------
945
+ /** The mode last seen for a channel, learned from responses. */
946
+ lastKnownMode(channel) {
947
+ return this.modes.get(channel);
948
+ }
949
+ /** Seed the mode memory, for example from a value persisted across processes. */
950
+ rememberMode(channel, mode) {
951
+ this.modes.set(channel, mode);
952
+ }
953
+ /** The disclosure `ref` recorded for a conversation in this process, if any. */
954
+ disclosureRef(conversationId) {
955
+ return this.disclosureRefs.get(conversationId);
956
+ }
957
+ /** Seed a disclosure `ref` recorded elsewhere so it is attached to later evaluates. */
958
+ rememberDisclosure(conversationId, ref) {
959
+ this.disclosureRefs.set(conversationId, ref);
960
+ }
961
+ // -------------------------------------------------------------------------
962
+ // Transcripts, patient state and webhook deliveries
963
+ // -------------------------------------------------------------------------
964
+ /** Observe only: a batch of past turns, each evaluated and recorded as would-have. */
965
+ async submitTranscripts(input) {
966
+ if (!Array.isArray(input.turns) || input.turns.length === 0) {
967
+ throw new GovernConfigError("submitTranscripts: turns must be a non-empty array.");
968
+ }
969
+ input.turns.forEach((turn, index) => {
970
+ requireConversationId(turn.conversationId, `turns[${index}].conversationId`);
971
+ requireTurnId(turn.turnId, `turns[${index}].turnId`);
972
+ });
973
+ const body = {
974
+ turns: input.turns.map((turn) => ({
975
+ conversation_id: turn.conversationId,
976
+ turn_id: turn.turnId,
977
+ channel: turn.channel,
978
+ audience: turn.audience,
979
+ content: turn.content,
980
+ sent_at: isoString(turn.sentAt)
981
+ }))
982
+ };
983
+ if (this.applicationId) body.application_id = this.applicationId;
984
+ const response = await send(this.transport, {
985
+ method: "POST",
986
+ path: GOVERN_PATHS.transcripts,
987
+ body,
988
+ signal: input.signal,
989
+ // The transport retries a 500, and the API replays a batch by this key.
990
+ // Without one, a 500-then-success opens a second job. Defaulted per call, so every attempt of this call is the one
991
+ // write and a genuinely new batch is still a new job.
992
+ idempotencyKey: idempotencyKey(input.idempotencyKey)
993
+ });
994
+ return toTranscriptJob(response.body, response.status === 202);
995
+ }
996
+ async getTranscriptJob(jobId, options = {}) {
997
+ requireText(jobId, "jobId");
998
+ const response = await send(this.transport, {
999
+ method: "GET",
1000
+ path: GOVERN_PATHS.transcriptJob(jobId),
1001
+ signal: options.signal
1002
+ });
1003
+ return toTranscriptJob(response.body, false);
1004
+ }
1005
+ async getTranscriptJobTurns(jobId, options = {}) {
1006
+ requireText(jobId, "jobId");
1007
+ const response = await send(this.transport, {
1008
+ method: "GET",
1009
+ path: GOVERN_PATHS.transcriptTurns(jobId),
1010
+ signal: options.signal
1011
+ });
1012
+ return response.body;
1013
+ }
1014
+ /** Record that the patient granted or revoked consent to be contacted. The reference travels in the body, never a URL. */
1015
+ async recordPatientConsent(input) {
1016
+ requireText(input.patientRef, "patientRef");
1017
+ const body = { patient_ref: input.patientRef, state: input.state };
1018
+ if (input.channel !== void 0) body.channel = input.channel;
1019
+ if (input.at !== void 0) body.at = isoString(input.at);
1020
+ const response = await send(this.transport, {
1021
+ method: "POST",
1022
+ path: GOVERN_PATHS.patientConsent,
1023
+ body,
1024
+ signal: input.signal,
1025
+ idempotencyKey: idempotencyKey(input.idempotencyKey)
1026
+ });
1027
+ return response.body;
1028
+ }
1029
+ /** Record an opt-out (or, for an opt-out you recorded yourself, an opt back in). */
1030
+ async recordPatientOptOut(input) {
1031
+ requireText(input.patientRef, "patientRef");
1032
+ const body = { patient_ref: input.patientRef, opted_out: input.optedOut };
1033
+ if (input.channel !== void 0) body.channel = input.channel;
1034
+ if (input.at !== void 0) body.at = isoString(input.at);
1035
+ const response = await send(this.transport, {
1036
+ method: "POST",
1037
+ path: GOVERN_PATHS.patientOptOut,
1038
+ body,
1039
+ signal: input.signal,
1040
+ idempotencyKey: idempotencyKey(input.idempotencyKey)
1041
+ });
1042
+ return response.body;
1043
+ }
1044
+ /** The patient's consent, opt-out and frequency state. A POST so the reference stays out of the URL. */
1045
+ async getPatientState(patientRef, options = {}) {
1046
+ requireText(patientRef, "patientRef");
1047
+ const response = await send(this.transport, {
1048
+ method: "POST",
1049
+ path: GOVERN_PATHS.patientState,
1050
+ body: { patient_ref: patientRef },
1051
+ signal: options.signal
1052
+ });
1053
+ return response.body;
1054
+ }
1055
+ /** The webhook delivery log for the application: counts and codes, never a body. */
1056
+ async listWebhookDeliveries(query = {}) {
1057
+ const response = await send(this.transport, {
1058
+ method: "GET",
1059
+ path: GOVERN_PATHS.webhookDeliveries,
1060
+ query: {
1061
+ decision_id: query.decisionId,
1062
+ handoff_id: query.handoffId,
1063
+ status: query.status
1064
+ },
1065
+ signal: query.signal
1066
+ });
1067
+ return response.body;
1068
+ }
1069
+ // -------------------------------------------------------------------------
1070
+ // Internals
1071
+ // -------------------------------------------------------------------------
1072
+ async postOutcome(decisionId, input) {
1073
+ const body = {
1074
+ delivered: input.delivered,
1075
+ delivered_at: input.deliveredAt
1076
+ };
1077
+ if (input.contentHash !== void 0) body.delivered_content_hash = input.contentHash;
1078
+ if (input.deliveryRef !== void 0) body.delivery_ref = input.deliveryRef;
1079
+ const response = await send(this.transport, {
1080
+ method: "POST",
1081
+ path: GOVERN_PATHS.outcome(decisionId),
1082
+ body,
1083
+ signal: input.signal
1084
+ });
1085
+ return this.read(toDecision(response.body, false), { arm: false });
1086
+ }
1087
+ async flushPendingAck(conversationId) {
1088
+ const pending = this.pendingAcks.get(conversationId);
1089
+ if (!pending) return;
1090
+ this.pendingAcks.delete(conversationId);
1091
+ if (this.reportedDecisions.has(pending.decisionId)) return;
1092
+ try {
1093
+ await this.postOutcome(pending.decisionId, {
1094
+ delivered: pending.delivered,
1095
+ deliveredAt: pending.at,
1096
+ contentHash: pending.contentHash,
1097
+ deliveryRef: void 0,
1098
+ signal: void 0
1099
+ });
1100
+ this.reportedDecisions.set(pending.decisionId, true);
1101
+ this.onEvent?.({ type: "outcome", decisionId: pending.decisionId, delivered: pending.delivered, auto: true });
1102
+ } catch (error) {
1103
+ if (!this.pendingAcks.has(conversationId)) this.pendingAcks.set(conversationId, pending);
1104
+ this.onEvent?.({ type: "error", operation: "auto_ack", error: describe(error) });
1105
+ }
1106
+ }
1107
+ disclosureAttachment(conversationId) {
1108
+ const ref = this.disclosureRefs.get(conversationId);
1109
+ return ref ? { established: true, ref } : void 0;
1110
+ }
1111
+ /**
1112
+ * Every decision the API returns passes through here: the channel's mode is
1113
+ * learned, and the holding line is armed at most once per decision id.
1114
+ *
1115
+ * The API's `send_holding_line` is a property of the decision, returned on
1116
+ * every read of it, and the contract asks the caller to send at most one
1117
+ * holding line per decision. Handing that flag through unfiltered would put
1118
+ * the dedup on every integration, and the obvious integration (send the
1119
+ * holding line whenever the flag is set) would send it again on a retried
1120
+ * turn. So the first read that carries it arms it and every later read in
1121
+ * this instance answers false. The API's own value stays on `raw`.
1122
+ *
1123
+ * The conditions the API already applies are applied again here, so a
1124
+ * server that disagrees with its own contract cannot make this SDK tell a
1125
+ * caller to message a patient who opted out.
1126
+ */
1127
+ read(decision, options = { arm: true }) {
1128
+ this.modes.set(decision.channel, decision.mode);
1129
+ const id = decision.id;
1130
+ if (!decision.sendHoldingLine || !id) return decision;
1131
+ const eligible = options.arm && holdingLineApplies(decision) && !this.holdingLines.has(id);
1132
+ this.holdingLines.set(id, true);
1133
+ return eligible ? decision : { ...decision, sendHoldingLine: false };
1134
+ }
1135
+ sleepOrWake(decisionId, ms, signal) {
1136
+ return new Promise((resolve2, reject) => {
1137
+ if (signal?.aborted) {
1138
+ reject(new GovernAbortError(signal.reason));
1139
+ return;
1140
+ }
1141
+ const waiters = this.releaseWaiters.get(decisionId) ?? /* @__PURE__ */ new Set();
1142
+ this.releaseWaiters.set(decisionId, waiters);
1143
+ const done = () => {
1144
+ clearTimeout(timer);
1145
+ waiters.delete(wake);
1146
+ if (waiters.size === 0) this.releaseWaiters.delete(decisionId);
1147
+ signal?.removeEventListener("abort", onAbort);
1148
+ };
1149
+ const wake = () => {
1150
+ done();
1151
+ resolve2();
1152
+ };
1153
+ const onAbort = () => {
1154
+ done();
1155
+ reject(new GovernAbortError(signal?.reason));
1156
+ };
1157
+ const timer = setTimeout(wake, ms);
1158
+ waiters.add(wake);
1159
+ signal?.addEventListener("abort", onAbort, { once: true });
1160
+ });
1161
+ }
1162
+ wake(decisionId) {
1163
+ const waiters = this.releaseWaiters.get(decisionId);
1164
+ if (!waiters) return;
1165
+ for (const wake of [...waiters]) wake();
1166
+ }
1167
+ };
1168
+ function toDecision(wire, accepted) {
1169
+ const rawVerdict = String(wire.decision);
1170
+ const known = KNOWN_VERDICTS.has(rawVerdict);
1171
+ const failOpen = wire.mode === "observe" || wire.mode === "off";
1172
+ const decision = known ? rawVerdict : failOpen ? "allow" : "hold";
1173
+ return {
1174
+ id: wire.decision_id ?? null,
1175
+ status: wire.status,
1176
+ decision,
1177
+ mode: wire.mode,
1178
+ channel: wire.channel,
1179
+ audience: wire.audience,
1180
+ conversationId: wire.conversation_id,
1181
+ turnId: wire.turn_id,
1182
+ wouldHave: wire.would_have ?? null,
1183
+ policy: wire.policy ? { id: wire.policy.id, name: wire.policy.name, version: wire.policy.version } : null,
1184
+ reasons: Array.isArray(wire.reasons) ? [...wire.reasons] : [],
1185
+ rationale: wire.rationale ?? null,
1186
+ detectedClaims: Array.isArray(wire.detected_claims) ? [...wire.detected_claims] : [],
1187
+ disclosureRequired: wire.disclosure_required === true,
1188
+ reviewUrl: wire.review_url ?? null,
1189
+ reviewState: wire.review_state ?? null,
1190
+ // A patient audience never receives text from this field, whatever the server sends.
1191
+ deliverableContent: wire.audience === "clinician" ? wire.deliverable_content ?? null : null,
1192
+ releasedContent: wire.released_content ?? null,
1193
+ stopClass: toStopClass(wire.stop_class),
1194
+ // The API's value. `Govern` narrows it to at most once per decision id on
1195
+ // the way out (see `Govern.read`); `raw.send_holding_line` keeps the original.
1196
+ sendHoldingLine: wire.send_holding_line === true,
1197
+ model: typeof wire.model === "string" ? wire.model : null,
1198
+ modelVersion: typeof wire.model_version === "string" ? wire.model_version : null,
1199
+ createdAt: wire.created_at ?? null,
1200
+ decidedAt: wire.decided_at ?? null,
1201
+ reviewedAt: wire.reviewed_at ?? null,
1202
+ outcome: wire.outcome ? toOutcome(wire.outcome) : null,
1203
+ // Read from the typed wire. Absent means false.
1204
+ routeToHuman: wire.route_to_human === true,
1205
+ wouldHaveRouted: wire.would_have_routed === true,
1206
+ inboundFlags: toInboundFlags(wire.inbound_flags),
1207
+ handoff: toHandoffRef(wire.handoff),
1208
+ webhookDeliveries: Array.isArray(wire.webhook_deliveries) ? [...wire.webhook_deliveries] : [],
1209
+ unknownDecision: known ? null : rawVerdict,
1210
+ accepted,
1211
+ degraded: !known,
1212
+ raw: wire
1213
+ };
1214
+ }
1215
+ function toStopClass(value) {
1216
+ if (value === null || value === void 0) return null;
1217
+ return value === "never_sendable" ? "never_sendable" : "uncertain";
1218
+ }
1219
+ var NO_HOLDING_LINE = /* @__PURE__ */ new Set([
1220
+ REASONS.optedOut,
1221
+ REASONS.consentMissing,
1222
+ REASONS.consentRevoked,
1223
+ REASONS.frequencyCap,
1224
+ REASONS.patientStateUnavailable
1225
+ ]);
1226
+ function holdingLineApplies(decision) {
1227
+ if (decision.decision === "allow") return false;
1228
+ if (decision.audience !== "patient") return false;
1229
+ if (decision.reviewState === "released" || decision.reviewState === "rejected") return false;
1230
+ return !decision.reasons.some((reason) => NO_HOLDING_LINE.has(reason));
1231
+ }
1232
+ function toInboundFlags(value) {
1233
+ if (!Array.isArray(value)) return [];
1234
+ const out = [];
1235
+ for (const item of value) {
1236
+ if (item && typeof item === "object") {
1237
+ const flag = item;
1238
+ out.push({
1239
+ ruleId: typeof flag.rule_id === "string" ? flag.rule_id : "",
1240
+ category: typeof flag.category === "string" ? flag.category : ""
1241
+ });
1242
+ }
1243
+ }
1244
+ return out;
1245
+ }
1246
+ function toHandoffRef(value) {
1247
+ if (!value || typeof value !== "object") return null;
1248
+ const h = value;
1249
+ if (typeof h.id !== "string") return null;
1250
+ const str2 = (v) => typeof v === "string" ? v : null;
1251
+ return {
1252
+ id: h.id,
1253
+ state: str2(h.state) ?? "",
1254
+ version: typeof h.version === "number" ? h.version : 0,
1255
+ queueLabel: str2(h.queue_label) ?? "",
1256
+ assignedTo: str2(h.assigned_to),
1257
+ dueAt: str2(h.due_at),
1258
+ escalationDueAt: str2(h.escalation_due_at),
1259
+ resolvedAt: str2(h.resolved_at),
1260
+ automationResumedAt: str2(h.automation_resumed_at),
1261
+ // Absent only from a server that predates the field, where every open
1262
+ // hand-off paused automation; read it that way rather than as "not paused".
1263
+ pausesAutomation: h.pauses_automation !== false
1264
+ };
1265
+ }
1266
+ var GovernHandoffs = class {
1267
+ constructor(transport) {
1268
+ this.transport = transport;
1269
+ }
1270
+ transport;
1271
+ async list(query = {}) {
1272
+ const response = await send(this.transport, {
1273
+ method: "GET",
1274
+ path: GOVERN_PATHS.handoffs,
1275
+ query: {
1276
+ application_id: query.applicationId,
1277
+ status: query.status,
1278
+ assigned_to: query.assignedTo,
1279
+ overdue: query.overdue === void 0 ? void 0 : String(query.overdue),
1280
+ sort: query.sort,
1281
+ limit: query.limit === void 0 ? void 0 : String(query.limit),
1282
+ offset: query.offset === void 0 ? void 0 : String(query.offset)
1283
+ },
1284
+ signal: query.signal
1285
+ });
1286
+ return {
1287
+ items: response.body.items,
1288
+ total: response.body.total,
1289
+ patientNames: { ...response.body.patient_names },
1290
+ awaitingReply: Array.isArray(response.body.awaiting_reply) ? [...response.body.awaiting_reply] : [],
1291
+ raw: response.body
1292
+ };
1293
+ }
1294
+ async get(handoffId, options = {}) {
1295
+ requireText(handoffId, "handoffId");
1296
+ const response = await send(this.transport, {
1297
+ method: "GET",
1298
+ path: GOVERN_PATHS.handoff(handoffId),
1299
+ signal: options.signal
1300
+ });
1301
+ return response.body;
1302
+ }
1303
+ /** Take the hand-off. */
1304
+ claim(handoffId, input) {
1305
+ return this.act(GOVERN_PATHS.handoffClaim, handoffId, input, { expected_version: input.expectedVersion });
1306
+ }
1307
+ /** Record an attempt to reach the patient on a claimed hand-off. */
1308
+ contactAttempt(handoffId, input) {
1309
+ const body = {
1310
+ expected_version: input.expectedVersion,
1311
+ outcome: input.outcome,
1312
+ note: input.note
1313
+ };
1314
+ if (input.nextDueAt !== void 0) body.next_due_at = isoString(input.nextDueAt);
1315
+ return this.act(GOVERN_PATHS.handoffContact, handoffId, input, body);
1316
+ }
1317
+ /** Resolve a claimed hand-off. */
1318
+ resolve(handoffId, input) {
1319
+ return this.act(GOVERN_PATHS.handoffResolve, handoffId, input, {
1320
+ expected_version: input.expectedVersion,
1321
+ disposition: input.disposition,
1322
+ note: input.note,
1323
+ resume_automation: input.resumeAutomation
1324
+ });
1325
+ }
1326
+ /** Release the hold on automation for the patient of a resolved hand-off. */
1327
+ resume(handoffId, input) {
1328
+ return this.act(GOVERN_PATHS.handoffResume, handoffId, input, {
1329
+ expected_version: input.expectedVersion,
1330
+ note: input.note
1331
+ });
1332
+ }
1333
+ async act(path, handoffId, input, body) {
1334
+ requireText(handoffId, "handoffId");
1335
+ if (!Number.isInteger(input.expectedVersion)) {
1336
+ throw new GovernConfigError("expectedVersion is required and must be the integer version you last read.");
1337
+ }
1338
+ const response = await send(this.transport, {
1339
+ method: "POST",
1340
+ path: path(handoffId),
1341
+ body,
1342
+ signal: input.signal,
1343
+ retry: false
1344
+ });
1345
+ return response.body;
1346
+ }
1347
+ };
1348
+ function toOutcome(wire) {
1349
+ return {
1350
+ delivered: wire.delivered,
1351
+ deliveredAt: wire.delivered_at,
1352
+ deliveredContentHash: wire.delivered_content_hash ?? null,
1353
+ deliveryRef: wire.delivery_ref ?? null,
1354
+ recordedAt: wire.recorded_at,
1355
+ hashMatchesRelease: wire.hash_matches_release ?? null,
1356
+ raw: wire
1357
+ };
1358
+ }
1359
+ function toTranscriptJob(wire, created) {
1360
+ return {
1361
+ jobId: wire.job_id,
1362
+ applicationId: wire.application_id,
1363
+ status: wire.status,
1364
+ total: wire.total,
1365
+ processed: wire.processed,
1366
+ evaluated: wire.evaluated,
1367
+ duplicate: wire.duplicate,
1368
+ unavailable: wire.unavailable,
1369
+ abandoned: wire.abandoned,
1370
+ wouldHave: { ...wire.would_have },
1371
+ created,
1372
+ raw: wire
1373
+ };
1374
+ }
1375
+ function settle(decision) {
1376
+ if (decision.reviewState === "released") {
1377
+ return { state: "released", content: decision.releasedContent, decision };
1378
+ }
1379
+ if (decision.reviewState === "rejected") return { state: "rejected", decision };
1380
+ if (decision.decision === "allow") return { state: "not_held", decision };
1381
+ if (decision.decision === "block" && decision.reviewState === null) return { state: "blocked", decision };
1382
+ return null;
1383
+ }
1384
+ function runningInBrowser() {
1385
+ const w = globalThis.window;
1386
+ return typeof w !== "undefined" && typeof w.document !== "undefined";
1387
+ }
1388
+ function requireText(value, name) {
1389
+ if (typeof value !== "string" || value.trim() === "") {
1390
+ throw new GovernConfigError(`${name} is required and must be a non-empty string.`);
1391
+ }
1392
+ }
1393
+ function codePoints(value) {
1394
+ return [...value].length;
1395
+ }
1396
+ function requireConversationId(value, name = "conversationId") {
1397
+ requireText(value, name);
1398
+ if (codePoints(value.trim()) > MAX_CONVERSATION_ID_CHARS) {
1399
+ throw new GovernConfigError(
1400
+ `${name} must be at most ${MAX_CONVERSATION_ID_CHARS} characters. The API composes the conversation's disclosure reference from it, and that reference is bounded.`
1401
+ );
1402
+ }
1403
+ }
1404
+ function requireTurnId(value, name = "turnId") {
1405
+ requireText(value, name);
1406
+ const trimmed = value.trim();
1407
+ if (trimmed.startsWith(RESERVED_TURN_ID_PREFIX)) {
1408
+ throw new GovernConfigError(
1409
+ `${name} must not start with "${RESERVED_TURN_ID_PREFIX}", which is reserved for the rows the API writes itself.`
1410
+ );
1411
+ }
1412
+ if (codePoints(trimmed) > MAX_TURN_ID_CHARS) {
1413
+ throw new GovernConfigError(
1414
+ `${name} must be at most ${MAX_TURN_ID_CHARS} characters. The API composes the turn's reference from it, and that reference is bounded.`
1415
+ );
1416
+ }
1417
+ }
1418
+ function idempotencyKey(given) {
1419
+ return given?.trim() || randomId();
1420
+ }
1421
+ function isoString(value) {
1422
+ return value instanceof Date ? value.toISOString() : value;
1423
+ }
1424
+ function describe(error) {
1425
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
1426
+ return String(error);
1427
+ }
1428
+ function isolateEvents(onEvent) {
1429
+ if (!onEvent) return void 0;
1430
+ let reporting = false;
1431
+ return (event) => {
1432
+ try {
1433
+ onEvent(event);
1434
+ } catch (error) {
1435
+ if (reporting) return;
1436
+ reporting = true;
1437
+ try {
1438
+ onEvent({ type: "error", operation: "on_event", error: describe(error) });
1439
+ } catch {
1440
+ } finally {
1441
+ reporting = false;
1442
+ }
1443
+ }
1444
+ };
1445
+ }
1446
+ var BoundedMap = class {
1447
+ constructor(max) {
1448
+ this.max = max;
1449
+ }
1450
+ max;
1451
+ map = /* @__PURE__ */ new Map();
1452
+ get(key) {
1453
+ return this.map.get(key);
1454
+ }
1455
+ has(key) {
1456
+ return this.map.has(key);
1457
+ }
1458
+ set(key, value) {
1459
+ if (this.map.has(key)) this.map.delete(key);
1460
+ this.map.set(key, value);
1461
+ while (this.map.size > this.max) {
1462
+ const oldest = this.map.keys().next();
1463
+ if (oldest.done) break;
1464
+ this.map.delete(oldest.value);
1465
+ }
1466
+ }
1467
+ delete(key) {
1468
+ this.map.delete(key);
1469
+ }
1470
+ keys() {
1471
+ return this.map.keys();
1472
+ }
1473
+ };
1474
+
1475
+ // src/langchain.ts
1476
+ var CONFIGURABLE_KEY = "anybioGovern";
1477
+ var RESPONSE_METADATA_KEY = "anybio_govern";
1478
+ function governed(runnable, options) {
1479
+ requireOptions(options);
1480
+ const govern = resolveGovern(options.govern);
1481
+ const reportOutcome = options.reportOutcome ?? true;
1482
+ return RunnableLambda.from(async (input, config) => {
1483
+ const output = await runnable.invoke(input, config);
1484
+ const draft = draftOf(output);
1485
+ if (draft === null) {
1486
+ const error = new GovernConfigError(
1487
+ `governed: the runnable returned ${outputKind(output)}, which this adapter cannot read as text, so nothing was evaluated. Wrap a runnable that returns a string or a message, gate the text where it is produced, or pass ungatedOutput: "pass" to return this output unevaluated on purpose.`
1488
+ );
1489
+ if ((options.ungatedOutput ?? "error") === "error") throw error;
1490
+ safely(() => options.onError?.(error));
1491
+ return untouched(output);
1492
+ }
1493
+ if (draft.length === 0) return untouched(output);
1494
+ const ctx = resolveContext(options, config, void 0, {
1495
+ model: modelOfRunnable(runnable),
1496
+ modelVersion: reportedModel(output)
1497
+ });
1498
+ const reply = await govern.guard(() => draft, guardContext(options, ctx));
1499
+ safely(() => options.onDecision?.({ reply, conversationId: ctx.conversationId, turnId: ctx.turnId }), options.onError);
1500
+ if (reportOutcome) {
1501
+ const outcome = !reply.held || reply.showHoldText ? { delivered: true, content: reply.text } : { delivered: false };
1502
+ reply.ack(outcome).catch((error) => safely(() => options.onError?.(error)));
1503
+ }
1504
+ if (!reply.held && reply.text === draft) return untouched(output);
1505
+ return replace(output, reply);
1506
+ }).withConfig({ runName: "anybio_govern" });
1507
+ }
1508
+ var GovernCallbackHandler = class extends BaseCallbackHandler {
1509
+ name = "anybio_govern";
1510
+ options;
1511
+ govern;
1512
+ /** The model each run named at its start, until the run ends. Bounded, for runs that never end. */
1513
+ runModels = /* @__PURE__ */ new Map();
1514
+ constructor(options) {
1515
+ super();
1516
+ requireOptions(options);
1517
+ this.options = options;
1518
+ this.govern = resolveGovern(options.govern);
1519
+ }
1520
+ handleLLMStart(_llm, _prompts, runId, _parentRunId, extraParams, _tags, metadata) {
1521
+ this.rememberModel(runId, extraParams, metadata);
1522
+ }
1523
+ handleChatModelStart(_llm, _messages, runId, _parentRunId, extraParams, _tags, metadata) {
1524
+ this.rememberModel(runId, extraParams, metadata);
1525
+ }
1526
+ handleLLMError(_error, runId) {
1527
+ this.runModels.delete(runId);
1528
+ }
1529
+ async handleLLMEnd(output, runId) {
1530
+ const model = this.runModels.get(runId);
1531
+ this.runModels.delete(runId);
1532
+ const llmOutputModel = nonBlank(output.llmOutput?.model_name);
1533
+ const texts = [];
1534
+ for (const generations of output.generations) {
1535
+ for (const generation of generations) {
1536
+ const message = generation.message;
1537
+ const text = typeof generation.text === "string" && generation.text.length > 0 ? generation.text : draftOf(message);
1538
+ if (text && text.length > 0) texts.push({ text, modelVersion: reportedModel(message) ?? llmOutputModel });
1539
+ }
1540
+ }
1541
+ const reportOutcome = this.options.reportOutcome ?? false;
1542
+ for (const [index, { text, modelVersion }] of texts.entries()) {
1543
+ const ctx = resolveContext(this.options, void 0, texts.length === 1 ? runId : `${runId}:${index}`, {
1544
+ model,
1545
+ modelVersion
1546
+ });
1547
+ try {
1548
+ const decision = await this.govern.evaluate({
1549
+ ...evaluateFields(this.options, ctx),
1550
+ content: text
1551
+ });
1552
+ safely(() => this.options.onDecision?.({ decision, runId }), this.options.onError);
1553
+ if (reportOutcome && decision.id) {
1554
+ await this.govern.reportOutcome(decision.id, { delivered: true, content: text });
1555
+ }
1556
+ } catch (error) {
1557
+ safely(() => this.options.onError?.(error));
1558
+ }
1559
+ }
1560
+ }
1561
+ rememberModel(runId, extraParams, metadata) {
1562
+ const invocation = extraParams?.invocation_params;
1563
+ const model = nonBlank(invocation?.model) ?? nonBlank(invocation?.model_name) ?? nonBlank(metadata?.ls_model_name);
1564
+ if (model === void 0) return;
1565
+ this.runModels.set(runId, model);
1566
+ if (this.runModels.size > 1e4) {
1567
+ const oldest = this.runModels.keys().next();
1568
+ if (!oldest.done) this.runModels.delete(oldest.value);
1569
+ }
1570
+ }
1571
+ };
1572
+ function resolveGovern(value) {
1573
+ return typeof value.guard === "function" ? value : new Govern(value);
1574
+ }
1575
+ function requireOptions(options) {
1576
+ if (!options.govern) throw new GovernConfigError("@anybio/govern/langchain: `govern` (a Govern client or its options) is required.");
1577
+ if (!options.channel || !options.audience) {
1578
+ throw new GovernConfigError("@anybio/govern/langchain: `channel` and `audience` are required.");
1579
+ }
1580
+ }
1581
+ function resolveContext(options, config, fallbackTurnId, observed) {
1582
+ const configurable = config?.configurable ?? {};
1583
+ const perCall = configurable[CONFIGURABLE_KEY] ?? {};
1584
+ const threadId = typeof configurable.thread_id === "string" ? configurable.thread_id : void 0;
1585
+ const conversationId = resolve(options.conversationId, config) ?? perCall.conversationId ?? threadId;
1586
+ if (!conversationId) {
1587
+ throw new GovernConfigError(
1588
+ "@anybio/govern/langchain: a conversationId is required. Pass `conversationId` in the options or `configurable.anybioGovern.conversationId` (or `configurable.thread_id`) on the call."
1589
+ );
1590
+ }
1591
+ const turnId = resolve(options.turnId, config) ?? perCall.turnId ?? (typeof config?.runId === "string" ? config.runId : void 0) ?? fallbackTurnId ?? randomId();
1592
+ return {
1593
+ conversationId,
1594
+ turnId,
1595
+ patientRef: resolve(options.patientRef, config) ?? perCall.patientRef,
1596
+ metadata: resolve(options.metadata, config) ?? perCall.metadata,
1597
+ inbound: options.inbound?.(config),
1598
+ model: nonBlank(resolve(options.model, config)) ?? observed.model,
1599
+ modelVersion: nonBlank(resolve(options.modelVersion, config)) ?? observed.modelVersion
1600
+ };
1601
+ }
1602
+ function modelOfRunnable(runnable) {
1603
+ if (!runnable || typeof runnable !== "object") return void 0;
1604
+ const r = runnable;
1605
+ return nonBlank(r.model) ?? nonBlank(r.modelName);
1606
+ }
1607
+ function reportedModel(output) {
1608
+ if (!isBaseMessage(output)) return void 0;
1609
+ const metadata = output.response_metadata ?? {};
1610
+ return nonBlank(metadata.model_name) ?? nonBlank(metadata.model);
1611
+ }
1612
+ function nonBlank(value) {
1613
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
1614
+ }
1615
+ function resolve(value, config) {
1616
+ if (value === void 0) return void 0;
1617
+ return typeof value === "function" ? value(config) : value;
1618
+ }
1619
+ function guardContext(options, ctx) {
1620
+ const guard = {
1621
+ conversationId: ctx.conversationId,
1622
+ turnId: ctx.turnId,
1623
+ channel: options.channel,
1624
+ audience: options.audience
1625
+ };
1626
+ if (ctx.patientRef !== void 0) guard.patientRef = ctx.patientRef;
1627
+ if (ctx.metadata !== void 0) guard.metadata = ctx.metadata;
1628
+ if (ctx.inbound !== void 0) guard.inbound = ctx.inbound;
1629
+ if (options.holdMessage !== void 0) guard.holdMessage = options.holdMessage;
1630
+ if (ctx.model !== void 0) guard.model = ctx.model;
1631
+ if (ctx.modelVersion !== void 0) guard.modelVersion = ctx.modelVersion;
1632
+ return guard;
1633
+ }
1634
+ function evaluateFields(options, ctx) {
1635
+ const fields = {
1636
+ conversationId: ctx.conversationId,
1637
+ turnId: ctx.turnId,
1638
+ channel: options.channel,
1639
+ audience: options.audience
1640
+ };
1641
+ if (ctx.patientRef !== void 0) fields.patientRef = ctx.patientRef;
1642
+ if (ctx.metadata !== void 0) fields.metadata = ctx.metadata;
1643
+ if (ctx.inbound !== void 0) fields.inbound = ctx.inbound;
1644
+ if (ctx.model !== void 0) fields.model = ctx.model;
1645
+ if (ctx.modelVersion !== void 0) fields.modelVersion = ctx.modelVersion;
1646
+ return fields;
1647
+ }
1648
+ function safely(run, onFailure) {
1649
+ try {
1650
+ run();
1651
+ } catch (error) {
1652
+ try {
1653
+ onFailure?.(error);
1654
+ } catch {
1655
+ }
1656
+ }
1657
+ }
1658
+ function outputKind(output) {
1659
+ if (output === null) return "null";
1660
+ if (Array.isArray(output)) return "an array";
1661
+ if (typeof output === "object") {
1662
+ const name = output.constructor?.name;
1663
+ return name && name !== "Object" ? `a ${name}` : "an object";
1664
+ }
1665
+ return `a ${typeof output}`;
1666
+ }
1667
+ function draftOf(output) {
1668
+ if (typeof output === "string") return output;
1669
+ if (isBaseMessage(output)) return output.text;
1670
+ return null;
1671
+ }
1672
+ function untouched(output) {
1673
+ return output;
1674
+ }
1675
+ function replace(output, reply) {
1676
+ const metadata = {
1677
+ decision_id: reply.decisionId,
1678
+ decision: reply.decision,
1679
+ mode: reply.mode,
1680
+ held: reply.held,
1681
+ send_holding_line: reply.sendHoldingLine,
1682
+ show_hold_text: reply.showHoldText,
1683
+ stop_class: reply.stopClass,
1684
+ degraded: reply.degraded,
1685
+ reasons: [...reply.reasons]
1686
+ };
1687
+ if (typeof output === "string") return reply.text;
1688
+ const original = output;
1689
+ return new AIMessage({
1690
+ content: reply.text,
1691
+ response_metadata: { ...original.response_metadata ?? {}, [RESPONSE_METADATA_KEY]: metadata }
1692
+ });
1693
+ }
1694
+
1695
+ export { CONFIGURABLE_KEY, GovernCallbackHandler, RESPONSE_METADATA_KEY, governed };