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