@anybio/govern 0.2.1 → 0.3.0

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