@anybio/govern 0.2.1 → 0.3.0

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