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