@anybio/govern 0.0.0 → 0.2.1

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