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