@anybio/govern 0.0.0 → 0.2.2
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 +34 -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 -5
- package/spec/README.md +17 -0
- package/spec/openapi.json +3967 -0
- package/README +0 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@anybio/govern` are recorded here. The format follows Keep a Changelog; versions follow Semantic Versioning. Until 1.0.0, a minor version may change the public surface.
|
|
4
|
+
|
|
5
|
+
## 0.2.2
|
|
6
|
+
|
|
7
|
+
No change to the SDK. Built and published from github.com/anybio/govern-js with a provenance statement.
|
|
8
|
+
|
|
9
|
+
## 0.2.1
|
|
10
|
+
|
|
11
|
+
First public release.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- `Govern` client: `evaluate` (idempotent by `turnId`; observe answers 202 with allow at once; retries on 429 with `Retry-After`, 5xx, timeouts and network failures), `getDecision`, `reportOutcome` (SHA-256 of the delivered text, computed locally), `recordDisclosure` (the `ref` is attached to later evaluates for the conversation), `waitForRelease` (polls with backoff; a verified webhook wakes it), `handleWebhook`.
|
|
16
|
+
- `guard(fn, ctx)`: the draft on allow, the hold message or nothing on hold or block, the clinician substitution when supplied. Fails closed in enforce and fails open, flagged `degraded`, in observe, with the mode learned per channel. `ack()` reports the outcome, and the next turn in the conversation reports it automatically if you do not.
|
|
17
|
+
- The holding line: `sendHoldingLine` on `Decision` and `GuardResult` says the patient is owed your fixed holding line now. The SDK arms it at most once per decision id per `Govern` instance. The memory is in process and bounded to the most recent 10,000 decisions; an application that runs more than one process records the send itself, keyed on `decisionId`. It is never true on an allow, a clinician audience, a released or rejected hold, a stop carrying `opted_out`, `consent_missing`, `consent_revoked`, `frequency_cap` or `patient_state_unavailable`, or a hold the SDK produced because the API could not be reached.
|
|
18
|
+
- The channel rule: `showHoldText` on `GuardResult`. For a patient audience, in-session channels (`web_chat`, `app_message`) show the hold message on every hold or block; outbound channels (`sms`, `voice`, `email`) and unknown channel values follow `sendHoldingLine`, and `text` is the empty string when nothing is owed. A clinician-audience hold always shows the hold message. `isInSessionChannel` and `IN_SESSION_CHANNELS` are exported.
|
|
19
|
+
- `stopClass` on `Decision` and `GuardResult`: `never_sendable` (no reviewer can release it) or `uncertain` (a reviewer can).
|
|
20
|
+
- `model` and `modelVersion` on `evaluate` and `guard`, recorded on the decision and counted in the observe report. Every adapter fills both.
|
|
21
|
+
- Route to a person: `inbound` on `evaluate` and `guard`; `routeToHuman`, `handoff`, `inboundFlags` and `wouldHaveRouted` on decisions; `govern.handoffs` (`list`, `get`, `claim`, `contactAttempt`, `resolve`, `resume`) with `expectedVersion`, and 409 mapped to `GovernConflictError`. `pausesAutomation` and `isAutomationPaused` say whether a hand-off pauses automated messaging; `awaitingReply` lists the hand-offs that still owe a reply.
|
|
22
|
+
- Consent, opt-out and the frequency cap: `recordPatientConsent`, `recordPatientOptOut`, `getPatientState`, and the reason codes the API returns when the patient's state stops a turn.
|
|
23
|
+
- Transcripts and webhooks: `submitTranscripts`, `getTranscriptJob`, `getTranscriptJobTurns`, `listWebhookDeliveries`, `verifyWebhookSignature`. Webhook configuration mistakes (no secret, a tolerance that is not a window, a parsed body) raise `GovernConfigError`, distinct from `GovernWebhookError` for a delivery that fails to verify.
|
|
24
|
+
- `guard` tells a refused call apart from an outage: `client_misconfigured` for a 4xx the API would refuse again (other than 408 and 429), `gate_unavailable` otherwise. Both hold in enforce. `isClientMisconfiguration` and `TRANSIENT_HTTP_STATUSES` are exported.
|
|
25
|
+
- Unknown decision values fail closed: `unknownDecision` keeps the value, and `decision` is normalised to hold in enforce and allow in observe.
|
|
26
|
+
- Identifiers are checked before the request: `turnId` outside the reserved `govern:` prefix, `conversationId` at most 187 code points and `turnId` at most 206, each refused with `GovernConfigError`.
|
|
27
|
+
- No callback can change a verdict: `onEvent` and the adapters' `onDecision` and `onError` run isolated, and a throw comes back as an `error` event.
|
|
28
|
+
- No event and no error message carries message content. The server's own error text is on `GovernApiError.serverMessage` only.
|
|
29
|
+
- Writes the transport retries carry an idempotency key by default, so a retried write is recorded once.
|
|
30
|
+
- `@anybio/govern/vercel-ai`: middleware for `ai` v7, with buffer and release for a patient-audience stream and a trailing evaluation for a clinician audience. Cancelling a buffered stream stops the provider's generation.
|
|
31
|
+
- `@anybio/govern/langchain`: the `governed` runnable wrapper (gates) and `GovernCallbackHandler` (records). `governed` refuses an output it cannot read as text unless `ungatedOutput: "pass"` is set.
|
|
32
|
+
- CLI: `init`, `test-message`, `decision`.
|
|
33
|
+
- Wire types generated from `spec/openapi.json`, which ships in the package.
|
|
34
|
+
- ESM and CommonJS builds with type declarations; Node 20 and later, and edge runtimes.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
# @anybio/govern
|
|
2
|
+
|
|
3
|
+
The AnyBio Govern SDK for JavaScript and TypeScript.
|
|
4
|
+
|
|
5
|
+
Put one server-side call between the text your AI produced and the moment it reaches a patient. The gate evaluates the draft against your policy and returns allow, hold or block, with the record already written. Watch for two weeks in observe mode, then enforce policy by policy.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Govern } from "@anybio/govern";
|
|
9
|
+
|
|
10
|
+
const govern = new Govern({ apiKey: process.env.ANYBIO_GOVERN_KEY, application: "care-companion" });
|
|
11
|
+
|
|
12
|
+
const reply = await govern.guard(
|
|
13
|
+
() => llm.chat(messages),
|
|
14
|
+
{ conversationId, turnId, channel: "sms", audience: "patient" },
|
|
15
|
+
);
|
|
16
|
+
if (reply.text !== "") await sendSms(patient.phone, reply.text);
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`reply.text` is the draft when the gate allows it. When it does not, `reply.text` is the hold message when `reply.showHoldText` is true, and the empty string when nothing is owed to the patient: for a patient audience, always the hold message in an in-session channel (`web_chat`, `app_message`), and on an outbound channel (`sms`, `voice`, `email`) only when a holding line is owed. A clinician-audience hold always gets the hold message. See [in-session and outbound channels](#in-session-and-outbound-channels). `reply.decisionId` is the record. Call `reply.ack()` after you send; if you do not, the next turn in the same conversation reports the previous one for you.
|
|
20
|
+
|
|
21
|
+
Status: pre-1.0. The public surface may change in a minor version; see the CHANGELOG. Documentation: [developer.anybio.io](https://developer.anybio.io).
|
|
22
|
+
|
|
23
|
+
## Contents
|
|
24
|
+
|
|
25
|
+
- [Install](#install)
|
|
26
|
+
- [Framework adapters](#framework-adapters)
|
|
27
|
+
- [What comes back](#what-comes-back)
|
|
28
|
+
- [Modes](#modes)
|
|
29
|
+
- [Conversation and turn ids](#conversation-and-turn-ids)
|
|
30
|
+
- [When the API cannot be reached](#when-the-api-cannot-be-reached)
|
|
31
|
+
- [Route to a person](#route-to-a-person)
|
|
32
|
+
- [Consent, opt-out and the frequency cap](#consent-opt-out-and-the-frequency-cap)
|
|
33
|
+
- [Hold resolution](#hold-resolution)
|
|
34
|
+
- [The identity disclosure](#the-identity-disclosure)
|
|
35
|
+
- [Outcomes](#outcomes)
|
|
36
|
+
- [Streaming](#streaming)
|
|
37
|
+
- [The CLI](#the-cli)
|
|
38
|
+
- [Runtime support](#runtime-support)
|
|
39
|
+
- [Events](#events)
|
|
40
|
+
- [What the SDK covers](#what-the-sdk-covers)
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
npm install @anybio/govern
|
|
46
|
+
# or: pnpm add @anybio/govern
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Or let the CLI detect your framework and print the exact lines:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
npx @anybio/govern init # prints; add --write to create the file
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Set the application key from the console in your server's environment. It is a server-side secret: the constructor throws if it finds a browser `window` global.
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
ANYBIO_GOVERN_KEY=gk_...
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Then run `npx @anybio/govern test-message`: it posts a synthetic draft and prints the decision, so you watch the gate hold a message with no PHI involved. More documentation is at [developer.anybio.io](https://developer.anybio.io).
|
|
62
|
+
|
|
63
|
+
## Framework adapters
|
|
64
|
+
|
|
65
|
+
The adapters are the install; the raw client is the escape hatch. Each ships as a subpath export and declares its framework as an optional peer dependency.
|
|
66
|
+
|
|
67
|
+
### Vercel AI SDK (`ai` v7)
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
import { wrapLanguageModel, streamText } from "ai";
|
|
71
|
+
import { withGovern } from "@anybio/govern/vercel-ai";
|
|
72
|
+
|
|
73
|
+
const model = wrapLanguageModel({
|
|
74
|
+
model: openai("gpt-4o"),
|
|
75
|
+
middleware: withGovern({ govern, channel: "web_chat", audience: "patient" }),
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const result = streamText({
|
|
79
|
+
model,
|
|
80
|
+
messages,
|
|
81
|
+
providerOptions: { anybioGovern: { conversationId: chatId, turnId: messageId } },
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`wrapGenerate` evaluates the generated text before it is returned. `wrapStream` buffers a patient-audience stream and releases it whole after the decision, or replaces it; a clinician-audience stream passes through and is evaluated after it ends. A held draft is replaced by the hold message when `showHoldText` is true, and by no text at all when it is false, following [the channel rule](#in-session-and-outbound-channels): on `web_chat` and `app_message` the hold message always appears, on `sms`, `voice` and `email` only when a holding line is owed, so a caller that sends whatever the model returns sends nothing. The outcome is reported to match: delivered with the hold message, or not delivered. The decision lands in `providerMetadata.anybioGovern` (on the result, and on the `finish` part of a stream), with `sendHoldingLine`, `showHoldText` and `stopClass` beside it. Every evaluation names the model: `model` is the wrapped model's `modelId` (what you asked for, `gpt-4o`), and `model_version` is the model id the provider reported on the response (the resolved snapshot, `gpt-4o-2024-08-06`) when it reports one; the `model` and `modelVersion` options override either. The adapter imports only types from `ai`.
|
|
86
|
+
|
|
87
|
+
### LangChain (`@langchain/core` v1)
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { governed, GovernCallbackHandler } from "@anybio/govern/langchain";
|
|
91
|
+
|
|
92
|
+
const gated = governed(model, { govern, channel: "web_chat", audience: "patient" });
|
|
93
|
+
const message = await gated.invoke(messages, {
|
|
94
|
+
configurable: { anybioGovern: { conversationId: threadId, turnId: messageId } },
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Callbacks run beside the chain and cannot withhold text; by the time `handleLLMEnd` fires the output is on its way. So `governed` is the gating path: it invokes the wrapped runnable, evaluates the `AIMessage` (or string) it returns, and when the decision is not allow returns a message (or string) with `reply.text` in its place, with the decision in `response_metadata.anybio_govern`. Like `guard`, that text is the hold message when `showHoldText` is true and empty when it is false (an outbound channel with no holding line owed), and the outcome is reported to match. `GovernCallbackHandler` records a decision per generation and is the observe-mode install for chains you do not want to wrap. `configurable.thread_id` is read as the conversation id when nothing else names one.
|
|
99
|
+
|
|
100
|
+
Both name the model on every evaluation. `governed` sends the chat model's own `model` (or `modelName`) and, as the version, the model the provider reported in the message's `response_metadata` (`model_name` for OpenAI-shaped integrations, `model` for Anthropic-shaped ones). `GovernCallbackHandler` sends the model named at the run's start (`invocation_params.model`, else `ls_model_name`) and the version on the generation. The `model` and `modelVersion` options override either, which is the route for a chain whose runnable is not itself a chat model. `governed` writes `send_holding_line`, `show_hold_text` and `stop_class` into `response_metadata.anybio_govern` with the rest of the decision. `GovernCallbackHandler` renders no text of its own: it records what the chain already returned.
|
|
101
|
+
|
|
102
|
+
An output `governed` cannot read as text, such as the object a structured-output chain returns, is refused rather than passed through: a gate that cannot see the output must not imply it approved it, and the error arrives on the first call rather than in production. Pass `ungatedOutput: "pass"` for a chain whose text you gate somewhere else; it returns the output unevaluated and calls `onError` with the same error.
|
|
103
|
+
|
|
104
|
+
## What comes back
|
|
105
|
+
|
|
106
|
+
`evaluate` returns a `Decision`:
|
|
107
|
+
|
|
108
|
+
| Field | Meaning |
|
|
109
|
+
|---|---|
|
|
110
|
+
| `id` | The decision id. Null only when the channel is `off`. |
|
|
111
|
+
| `decision` | `allow`, `hold` or `block`. |
|
|
112
|
+
| `mode` | `observe` or `enforce` (or `off`). |
|
|
113
|
+
| `status` | `pending` (observe, evaluated off the request path), `decided`, `unavailable`, `not_evaluated`. |
|
|
114
|
+
| `wouldHave` | Observe only: the raw gate decision (`allow`, `rewrite`, `block_and_review`, `policy_missing`) or `unavailable`. |
|
|
115
|
+
| `reasons` | Codes, safe to log, never patient text. The gate's: `prohibited_claim`, `medication_instruction`, `missing_disclaimer`, `clinical_claim`, `review_required`, `patient_rewrite_withheld`, `rewritten`, `held_for_review`, `disclosure_missing`, `policy_missing`, `not_evaluated`, `gate_unavailable`. The patient's state, checked before the gate: `opted_out`, `consent_missing`, `consent_revoked`, `frequency_cap`, and `patient_state_unavailable` (always beside `gate_unavailable`) when that state could not be read. And the two only the SDK adds: `unknown_decision`, and `client_misconfigured` when the API refused the call. `REASONS` exports the set. |
|
|
116
|
+
| `disclosureRequired` | The policy demands the AI-identity disclosure and none is on record for the conversation. |
|
|
117
|
+
| `reviewUrl`, `reviewState` | The console deep link and `pending` / `released` / `rejected`, when the decision is in the review queue. |
|
|
118
|
+
| `deliverableContent` | Clinician audience only: the gate's term substitution to deliver. Never present for a patient audience, whatever the server sends. |
|
|
119
|
+
| `releasedContent` | Present once a reviewer released the held message: what to deliver. |
|
|
120
|
+
| `stopClass` | What kind of stop a stopped draft is: `never_sendable` (a deterministic rule matched the message itself, a prohibited claim or the medication-instruction floor; no reviewer can release it) or `uncertain` (held because nobody has read it yet; a reviewer can release it). In observe it describes the stop that would have been. Null when nothing was stopped. |
|
|
121
|
+
| `sendHoldingLine` | Send your holding line now. True at most once per decision id per `Govern` instance; see [the holding line](#the-holding-line). |
|
|
122
|
+
| `model`, `modelVersion` | The model and version you named for this turn, as recorded. Null when none was sent. |
|
|
123
|
+
| `routeToHuman` | A person is being routed to the patient because the inbound matched a red-flag rule. Distinct from `decision`: a clean draft can be `allow` with `routeToHuman: true`. |
|
|
124
|
+
| `handoff` | The hand-off task opened or joined (`id`, `state`, `version`, `queueLabel`, due times, `pausesAutomation`, `automationResumedAt`), when there is one. See [route to a person](#route-to-a-person) for whether it pauses automation. |
|
|
125
|
+
| `inboundFlags` | The red-flag rules the inbound matched: rule id and category, never text. |
|
|
126
|
+
| `webhookDeliveries` | The signed webhook deliveries about this decision: the delivery log (event, status, attempts), never the body. |
|
|
127
|
+
| `unknownDecision` | Set when the server sent a decision value this SDK version does not know; `decision` was then normalised fail closed and `degraded` is true. |
|
|
128
|
+
| `raw` | The wire object, typed from the OpenAPI document. |
|
|
129
|
+
|
|
130
|
+
A rewrite for a patient audience is a hold: the message goes to a person, and the SDK never receives rewritten text to send. For a clinician audience `guard` returns `deliverableContent` in place of the draft when the API supplies one.
|
|
131
|
+
|
|
132
|
+
`guard` returns a `GuardResult`: `text`, `decisionId`, `decision`, `mode`, `degraded`, `reasons`, `held`, `sendHoldingLine`, `showHoldText`, `stopClass`, `routeToHuman`, `handoff`, `inboundFlags`, `record` and `ack()`.
|
|
133
|
+
|
|
134
|
+
On an allow, `text` is the reply. On a hold, `showHoldText` says whether `text` is the hold message to show or send now; when it is false, `text` is the empty string, the one value `guard` uses for "send nothing". Deliver `text` when it is not empty and nothing otherwise, on every channel. For a patient audience, which of the two a hold gets depends on the channel: see [in-session and outbound channels](#in-session-and-outbound-channels). A clinician-audience hold always gets the hold message.
|
|
135
|
+
|
|
136
|
+
`evaluate` and `guard` take `model` and `modelVersion`: the model your application ran for the turn and its version. They are recorded as sent (the API has nothing to check them against), counted per pair in the observe report, and either may be sent without the other. A blank value is not sent. The adapters fill both for you.
|
|
137
|
+
|
|
138
|
+
**Unknown decision values fail closed.** If a server ever returns a decision value this version of the SDK does not know (a future outcome), `evaluate` does not throw: it keeps the value on `decision.unknownDecision` and `decision.raw.decision`, sets `degraded: true`, and normalises `decision` to `hold` in enforce and `allow` in observe or off. `guard` then delivers the hold message in enforce and the draft (flagged `degraded: true`) in observe, with `unknown_decision` appended to `reasons`. `route_to_human` is known: as a decision value it delivers the hold message and sets `routeToHuman`.
|
|
139
|
+
|
|
140
|
+
The hold message is what a patient sees on hold or block, when `showHoldText` is true. Set `holdMessage` on the client or per `guard` call; the default says that a person will follow up.
|
|
141
|
+
|
|
142
|
+
### The holding line
|
|
143
|
+
|
|
144
|
+
When a patient-bound draft is stopped, the patient is waiting on a reply that is not coming. The holding line is the fixed text your clinical owner wrote in advance, saying that a person will reply, when, and what to do if it is urgent. It is yours, never model-written, and the API never sends it for you; with `guard` it is the hold message, returned as `text`. The API decides when it is owed, and `sendHoldingLine` carries the answer:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
const reply = await govern.guard(() => llm.chat(messages), { conversationId, turnId, channel: "sms", audience: "patient", patientRef });
|
|
148
|
+
if (reply.text !== "") await sendSms(patient.phone, reply.text);
|
|
149
|
+
// Equivalently: if (!reply.held || reply.showHoldText). On sms, showHoldText is sendHoldingLine.
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
- It is true on a patient-audience `hold` or `block`, including the fail-closed hold with `gate_unavailable` alone.
|
|
153
|
+
- It is false when another message would be the wrong thing rather than merely unnecessary: `opted_out`, `consent_missing`, `consent_revoked` and `frequency_cap` stop the turn because this patient should not be messaged, and `patient_state_unavailable` means none of that could be checked. It is false in observe, where nothing was stopped, and once a reviewer has released or rejected the hold.
|
|
154
|
+
- It is false when the SDK could not reach the API at all. That hold is the SDK's own fail-closed answer, and no patient state was read for it, which is the `patient_state_unavailable` case.
|
|
155
|
+
|
|
156
|
+
**At most one per decision.** The API's flag is a property of the decision and comes back on every read of it: a replayed `turnId`, `getDecision`, `waitForRelease`. The SDK arms it on the first read in a `Govern` instance that carries it and answers false on every later read, so a retried turn does not send the holding line twice. A new `turnId` is a new decision with its own answer. The memory is in process and bounded (the most recent 10,000 decisions); an application that runs more than one process, or restarts between the hold and a replay, records the send itself, keyed on `decisionId`. `record.raw.send_holding_line` keeps the API's own value, unfiltered.
|
|
157
|
+
|
|
158
|
+
The automatic outcome report follows what `guard` handed over: a hold that showed nothing is reported as nothing delivered, and a hold shown in session is reported as delivered with the hold message's hash, since the patient saw it. `ack()` defaults the same way. If you sent something anyway, say so with `reply.ack({ delivered: true, content })`.
|
|
159
|
+
|
|
160
|
+
### In-session and outbound channels
|
|
161
|
+
|
|
162
|
+
For a patient audience, what a hold hands the caller depends on where the patient is. The rule exists for contacting the patient (consent and patient state), so it applies to the patient audience only: a clinician-audience hold has `showHoldText` true and `text` the hold message on every channel, and `sendHoldingLine` is always false for it.
|
|
163
|
+
|
|
164
|
+
| Channel | On any hold or block | `showHoldText` | `text` |
|
|
165
|
+
|---|---|---|---|
|
|
166
|
+
| In-session: `web_chat`, `app_message` | The patient opened the session and is waiting in it. The hold message is the reply in that session, and consent does not govern a reply there. | Always true, including the fail-closed hold when the API cannot be reached, `patient_state_unavailable`, a released or rejected hold, and the do-not-message stops | The hold message |
|
|
167
|
+
| Outbound: `sms`, `voice`, `email` | A message goes out only when the API says a holding line is owed | Exactly `sendHoldingLine` | The hold message when true, `""` when false |
|
|
168
|
+
| Any other value | Treated as outbound: fail closed | Exactly `sendHoldingLine` | As outbound |
|
|
169
|
+
|
|
170
|
+
The one-per-decision rule above applies to `sendHoldingLine` only. Showing the hold message in session is a reply in the conversation, not a holding-line send, so a replayed turn shows it again: it is the same reply. `sendHoldingLine` is still reported beside it, for a caller that also sends the holding line somewhere else.
|
|
171
|
+
|
|
172
|
+
The classification is exported as `isInSessionChannel(channel)` (and the list as `IN_SESSION_CHANNELS`); `guard` and every adapter read it, and nothing else in the SDK classifies a channel. The API applies the same classification.
|
|
173
|
+
|
|
174
|
+
## Modes
|
|
175
|
+
|
|
176
|
+
Per policy, per application, set in the console: **off** (not evaluated, nothing recorded), **observe** (evaluated and recorded as would-have; you are always told allow), **enforce** (the decision is returned and binding). A new application starts in observe.
|
|
177
|
+
|
|
178
|
+
Observe is off your hot path: the server accepts the turn with 202 and evaluates after answering. The SDK returns as soon as the 202 arrives, with `decision: "allow"`, `mode: "observe"`, `status: "pending"` and the decision id. Enforce answers inline; the server bounds the gate at three seconds and answers hold with `gate_unavailable` if it does not decide in time. Flipping a policy to enforce is an audited event; the SDK's next call on that channel is synchronous.
|
|
179
|
+
|
|
180
|
+
Idempotency: `turnId` is sent as `Idempotency-Key`. A retry, or a replay with the same turn id, returns the stored decision and writes one record.
|
|
181
|
+
|
|
182
|
+
## Conversation and turn ids
|
|
183
|
+
|
|
184
|
+
`conversationId` and `turnId` are yours to choose, with two rules. The SDK checks both before it sends, and throws `GovernConfigError`; the API answers 400 if anything reaches it another way.
|
|
185
|
+
|
|
186
|
+
**`govern:` is reserved.** Turn ids starting with `govern:` belong to the rows the API writes about a conversation itself, the disclosure evidence among them. A `turnId` or `Idempotency-Key` in that range is refused. Only the prefix is reserved: `disclosure:conv-1` is yours to use, `govern:disclosure:conv-1` is not.
|
|
187
|
+
|
|
188
|
+
**Lengths are bounded.** `conversationId` is at most **187** characters and `turnId` at most **206**, counted in code points. Longer identifiers are refused. Anything you would pass through (a UUID, a message id from your channel, a thread id) is far inside both.
|
|
189
|
+
|
|
190
|
+
`turnId` is optional on `guard`, which mints a UUID when you leave it out. Supply your own message id when you want a retry to replay the same decision.
|
|
191
|
+
|
|
192
|
+
## When the API cannot be reached
|
|
193
|
+
|
|
194
|
+
`guard` applies fail semantics learned per channel from the last successful response:
|
|
195
|
+
|
|
196
|
+
| Last known mode for the channel | `guard` returns |
|
|
197
|
+
|---|---|
|
|
198
|
+
| `enforce`, or nothing learned yet (`assumeMode` defaults to `enforce`) | a hold: `decision: "hold"`, `degraded: true`, `reasons: ["gate_unavailable"]`, `decisionId: null`, `sendHoldingLine: false`. For a patient audience, on an in-session channel (`web_chat`, `app_message`) `text` is the hold message and `showHoldText` is true, because the patient is waiting in the session; on an outbound channel `text` is `""` and `showHoldText` is false: no patient state was read, so nothing goes out. For a clinician audience `text` is the hold message and `showHoldText` is true on every channel |
|
|
199
|
+
| `observe` or `off` (or `assumeMode: "observe"` before anything is learned) | the draft, `decision: "allow"`, `degraded: true` |
|
|
200
|
+
|
|
201
|
+
"Cannot be reached" means every attempt failed: a network error, a per-attempt timeout (`timeoutMs`, default 5000 ms), a 5xx or 429 after the retries (`maxRetries`, default 2, full-jitter backoff, `Retry-After` honoured and capped at 30 s), or a 4xx. The caller's own `AbortSignal` and local configuration errors are rethrown, never degraded.
|
|
202
|
+
|
|
203
|
+
`timeoutMs` bounds an attempt, not the call. With the defaults, three attempts of up to 5 s and two `Retry-After` waits capped at 30 s each, the worst case before `guard` holds is about 75 s. That is not the latency of a healthy call; if a call of yours needs a bound of its own, pass `ctx.signal`. An abort is rethrown rather than degraded, so what to send next is yours to decide, and for a patient audience that is the hold message in session and nothing on an outbound channel. Tighten `timeoutMs` and `maxRetries` if you would rather bound it globally.
|
|
204
|
+
|
|
205
|
+
### Which failure was it
|
|
206
|
+
|
|
207
|
+
The hold above is the same whatever went wrong, and it should be. What is not the same is who has work to do, so the signal says which:
|
|
208
|
+
|
|
209
|
+
| `reasons` | `cause` on the event | What it is | What to check |
|
|
210
|
+
|---|---|---|---|
|
|
211
|
+
| `gate_unavailable` | `gate_unavailable` | The API did not answer: a 5xx, a timeout, a dropped connection, a 429 that outlived its retries | Nothing, usually. It heals on its own. Alert if it persists |
|
|
212
|
+
| `client_misconfigured` | `client_misconfigured` | The API answered and refused the call, and would refuse it again: a revoked or wrong application key, a key not bound to the application, a request the server will not accept | Your own configuration. **This does not heal.** Every message from that process holds until someone acts |
|
|
213
|
+
|
|
214
|
+
Rotating a key and missing one deployment produces the second: that process holds every patient message until the key is fixed.
|
|
215
|
+
|
|
216
|
+
Treat them as different alerts. `gate_unavailable` is a rate to watch; a single `client_misconfigured` should page whoever owns the deployment.
|
|
217
|
+
|
|
218
|
+
A 4xx is the caller's except `408` and `429`, which say "later" rather than "no": 429 is rate limiting the transport already retried, and 408 is the server giving up on the request, which is the same class of event as a client-side timeout. A failure the SDK does not recognise is reported as `gate_unavailable`. `isClientMisconfiguration(error)` and `TRANSIENT_HTTP_STATUSES` are exported if you want to make the same split around your own `evaluate` calls.
|
|
219
|
+
|
|
220
|
+
Every degraded reply emits `onEvent({ type: "degraded", mode, modeSource: "learned" | "assumed", cause, status, error })`, where `status` is the HTTP status when the API answered and `null` for a timeout or a transport failure.
|
|
221
|
+
|
|
222
|
+
**Both still hold in enforce.** This changes what an operator is told, not what reaches a patient.
|
|
223
|
+
|
|
224
|
+
`evaluate` itself throws (`GovernApiError`, `GovernConflictError` for 409, `GovernNetworkError`, `GovernTimeoutError`, `GovernAbortError`); only `guard` degrades. No error message ever contains the draft.
|
|
225
|
+
|
|
226
|
+
To carry the learned mode across processes, read `govern.lastKnownMode(channel)` and seed a new client with `govern.rememberMode(channel, mode)`.
|
|
227
|
+
|
|
228
|
+
## Route to a person
|
|
229
|
+
|
|
230
|
+
Pass the patient's inbound message on `evaluate` or `guard` (`inbound: { content, receivedAt }`, with `patientRef`) and the gate screens it against the application's red-flag rules before it evaluates the draft. A match opens (or joins) a hand-off task on your team and the decision says so:
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
const result = await govern.guard(() => llm.chat(messages), {
|
|
234
|
+
conversationId, turnId, channel: "sms", audience: "patient", patientRef,
|
|
235
|
+
inbound: { content: inboundText, receivedAt: new Date() },
|
|
236
|
+
});
|
|
237
|
+
await sendSms(patient.phone, result.text);
|
|
238
|
+
if (result.routeToHuman) {
|
|
239
|
+
await sendSms(patient.phone, "A member of your care team will contact you shortly.");
|
|
240
|
+
await yourOwnSignal(result.handoff?.id);
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Routing is distinct from the outbound decision. A clean draft is `allow` with `routeToHuman: true`: the draft goes out and a person is routed beside it. A draft the policy holds is `hold` with `routeToHuman: true`: `text` follows `showHoldText` as on any hold, and a person is routed. In observe mode the record carries `wouldHaveRouted` instead. A replay of the same `turnId` returns the same decision and opens no second task; one open task exists per patient.
|
|
245
|
+
|
|
246
|
+
**A hand-off that a person owns does not always pause automation.** Every hand-off says whether it also pauses automated messaging to the patient while a person works it: `pausesAutomation` on `HandoffRef` (as on `decision.handoff` and `result.handoff`), `pauses_automation` on a wire hand-off row and on hand-off webhook events. A red flag, an exhausted budget, a missing policy, an unknown wire outcome and the route-to-human path all pause; an item that only owes the patient a reply does not. Automation is paused while `pausesAutomation` is true and `automationResumedAt` is null; a null `automationResumedAt` alone says only that a person owns the item. `isAutomationPaused(handoff)` applies exactly that rule to a `HandoffRef` or a wire row, so read it rather than `automationResumedAt` before sending anything automated to that patient:
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
if (isAutomationPaused(result.handoff)) {
|
|
250
|
+
await pauseYourOwnOutreach(patientRef);
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
The pause survives resolution: it ends only when a person releases it (`resume`, or `resolve` with `resumeAutomation: true`), which sets `automationResumedAt` and sends `handoff.resumed`. A server that predates `pauses_automation` reads as paused while not resumed, which is what every open hand-off meant then.
|
|
255
|
+
|
|
256
|
+
The task itself is on `govern.handoffs`: `list(query)` and `get(id)` work with the application key and see only this application's hand-offs. `claim`, `contactAttempt`, `resolve` and `resume` take `expectedVersion` (the version you last read; a stale one is refused with `GovernConflictError`) and are staff actions: the API refuses an application key on them with 403, so they are here for a server that presents a staff credential. Actions are never retried. `list` also returns `awaitingReply`: the ids of the hand-offs on the page that carry a stopped draft nobody has answered yet. A patient has one open item, so a stop joins whatever the patient already has, and the item keeps the reason it was opened for; `awaitingReply` says what it now also owes.
|
|
257
|
+
|
|
258
|
+
## Consent, opt-out and the frequency cap
|
|
259
|
+
|
|
260
|
+
Before the gate reads a word of the draft, the turn passes the patient's own state. A turn stopped here is stopped whatever the draft says, and nothing of the draft is kept.
|
|
261
|
+
|
|
262
|
+
| What is on record | Decision | Reason |
|
|
263
|
+
|---|---|---|
|
|
264
|
+
| The patient opted out (a STOP keyword in the inbound, or a report from you) | `block`, on every channel | `opted_out` |
|
|
265
|
+
| No `granted` consent, on a channel that requires one | `block` | `consent_missing` |
|
|
266
|
+
| The consent on record was revoked | `block`, on every outbound channel | `consent_revoked` |
|
|
267
|
+
| Over the application's cap in the current window | `hold` | `frequency_cap` |
|
|
268
|
+
|
|
269
|
+
`sms`, `voice` and `email` require consent by default; `app_message` and `web_chat` do not. A per-channel override lives on the application beside the channel's mode, and `consent_required_channels` on the application reads back the resolved answer. A turn that carries the patient's `inbound` is answering something the patient sent, so a *missing* consent does not stop it; a revocation still does, on every outbound channel. A clinician audience is never consulted about consent, which is the rule about contacting the patient.
|
|
270
|
+
|
|
271
|
+
Observe never blocks: each of these is recorded as the `wouldHave` and you are still told allow.
|
|
272
|
+
|
|
273
|
+
You record the events; the API enforces the state you gave it. AnyBio is not the system of record for consent.
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
await govern.recordPatientConsent({ patientRef, state: "granted", channel: "sms" });
|
|
277
|
+
await govern.recordPatientOptOut({ patientRef, optedOut: true });
|
|
278
|
+
const state = await govern.getPatientState(patientRef);
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
The patient's word outranks yours: an opt-out that came from a STOP keyword can only be lifted by a START from the patient, not by a report from your application.
|
|
282
|
+
|
|
283
|
+
## Hold resolution
|
|
284
|
+
|
|
285
|
+
A hold sits in the review queue until a person releases or rejects it. Two paths:
|
|
286
|
+
|
|
287
|
+
**Poll.** `await govern.waitForRelease(decisionId, { timeoutMs: 15 * 60_000 })` polls `getDecision` with backoff (1 s doubling to 15 s) and resolves `{ state: "released", content }`, `{ state: "rejected" }`, `{ state: "not_held" }` for a decision that was allowed, `{ state: "blocked" }` for a block no reviewer will lift, or `null` on timeout. Pass `signal` to abort.
|
|
288
|
+
|
|
289
|
+
**Webhook.** The application's endpoint receives a signed `POST` per state change. Verify and parse it with the SDK:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
const event = await govern.handleWebhook(rawBody, request.headers, process.env.ANYBIO_GOVERN_WEBHOOK_SECRET);
|
|
293
|
+
if (event.type === "decision.released") await deliver(event.releasedContent);
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
Verify the raw body, not a re-serialised one. The signature is `v1=` followed by the hex HMAC-SHA256 of `"{X-Govern-Timestamp}.{body}"` with the application's webhook secret; deliveries older than 300 s are refused. Two error classes, because a handler owes them different answers: a delivery that fails to verify raises `GovernWebhookError`, which is the 400 you return, and a call that could never have verified anything raises `GovernConfigError` (no secret, a tolerance that is not a window, a clock that does not return a time, a body that has already been through `JSON.parse`). The second one is yours to fix; answering 400 to it would tell the sender their signature is wrong when it is not. A verified `decision.released` or `decision.rejected` wakes any `waitForRelease` on the same decision at once. Decision events carry `model`, `modelVersion` and `stopClass` as the decision recorded them; hand-off events carry `pausesAutomation`. `handleWebhook` and `verifyWebhookSignature` are also exported as standalone functions.
|
|
297
|
+
|
|
298
|
+
## The identity disclosure
|
|
299
|
+
|
|
300
|
+
The gate refuses patient-facing content on a channel that requires the AI disclosure when no disclosure evidence is on record. Record it once per conversation, when the session starts:
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
const { ref } = await govern.recordDisclosure({
|
|
304
|
+
conversationId,
|
|
305
|
+
channel: "web_chat",
|
|
306
|
+
textShown: "You are chatting with an AI assistant. A person reviews held messages and can be reached at any time.",
|
|
307
|
+
});
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
The SDK remembers the `ref` per conversation and attaches it to every later `evaluate`. If you record the disclosure in one process and evaluate in another, `govern.rememberDisclosure(conversationId, ref)` seeds the cache. `disclosureRequired: true` on a decision means the policy demands the disclosure and none is on record for the conversation.
|
|
311
|
+
|
|
312
|
+
**A presented `ref` must be the conversation's own.** The API answers every turn on the evidence it holds for that `conversationId`, so the reference you send decides nothing: send the right one and it agrees, send another conversation's, another application's, an empty or a malformed one, and it is **ignored, never refused**. The turn is evaluated, and if the conversation has no evidence of its own it comes back `disclosureRequired` with `disclosure_missing`. Nothing is gained by attaching one by hand, and a borrowed reference cannot stand in for a disclosure that was never shown. This is also why the SDK sends what you give it without checking the shape.
|
|
313
|
+
|
|
314
|
+
**Recording twice is safe, and the second answer describes the first.** `recordDisclosure` is idempotent per conversation: the first call creates the evidence and answers 201, a later call answers 200 and describes **the evidence on record**: its `channel`, its `evidenceId`, the time it was recorded, not the call you just made. Read `created` to tell them apart, and read `channel` and `recordedAt` off the result rather than assuming they echo your request.
|
|
315
|
+
|
|
316
|
+
## Outcomes
|
|
317
|
+
|
|
318
|
+
What you delivered is part of the record: proposed, decided, delivered. `reportOutcome(decisionId, { delivered: true, content })` hashes `content` with SHA-256 locally and sends only the hash; the text never leaves your server. One outcome per decision: the same report again is accepted, a different one is refused with 409.
|
|
319
|
+
|
|
320
|
+
With `guard`, `reply.ack()` does this for you with the text it returned. If you never call `ack()`, the next `guard` call for the same conversation reports the previous turn as `delivered: true` with the hash of the text it returned, at the time it returned it (or `delivered: false` for a hold with `showHoldText` false, where `text` was empty); a late `ack()` after that is a no-op. `govern.flushPendingAcks()` reports everything still held; call it on shutdown. The automatic report is best effort and `ack()` is the reliable route: a conversation holds one pending outcome, so an automatic write that fails after a newer turn has taken that place is dropped rather than queued behind it. It costs a row in the record, never a verdict and never a word of returned text. The adapters report the outcome themselves (`reportOutcome: true` by default) with the text they let through, or as not delivered when they let nothing through.
|
|
321
|
+
|
|
322
|
+
## Streaming
|
|
323
|
+
|
|
324
|
+
A gate cannot approve text it has not seen. For a patient audience the rule is buffer and release: the patient sees a typing state, then the gated message; no token reaches them before the decision. For a clinician audience the stream may pass through with a trailing evaluation. The Vercel AI adapter's `wrapStream` implements both; `governed(...).stream()` yields one chunk after the decision. On a hold, tool-call parts are dropped rather than passed through beside the hold message. A stream the caller cancels while the gate is deciding is reported as not delivered. For a patient audience the first token arrives only after the decision, so show a typing indicator for the whole wait.
|
|
325
|
+
|
|
326
|
+
## The CLI
|
|
327
|
+
|
|
328
|
+
```
|
|
329
|
+
npx @anybio/govern init [--write] [--dir <path>] [--channel <c>] [--audience <a>]
|
|
330
|
+
npx @anybio/govern test-message [--channel <c>] [--audience <a>] [--base-url <url>] [--content <text>]
|
|
331
|
+
npx @anybio/govern decision <id>
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
`init` reads `package.json`, detects the Vercel AI SDK or LangChain, and prints the install command, the environment variable and the file to add. It writes nothing unless you pass `--write`, and then it creates `lib/govern.ts` (or `src/lib/`) and appends the variable names to `.env.example`; it never edits an existing source file. `test-message` posts a synthetic draft that names a cure and a medication change, records a disclosure for the throwaway conversation first, and prints the decision: in observe you see the would-have block, in enforce you see the hold. `decision <id>` fetches a decision and its review state.
|
|
335
|
+
|
|
336
|
+
Environment: `ANYBIO_GOVERN_KEY` (required), `ANYBIO_GOVERN_APPLICATION` (optional), `ANYBIO_GOVERN_BASE_URL` (optional; for example a local mock server).
|
|
337
|
+
|
|
338
|
+
## Runtime support
|
|
339
|
+
|
|
340
|
+
Node 20 and later, and edge runtimes; CI runs the suite on Node 20 and 22. `engines.node` is `>=20` and that is the floor for every entry point in this package, the vercel-ai one included: the middleware imports `ai` for types only, so nothing in this package needs a newer runtime. Your floor is the higher of this package's and your framework's. `ai` 7 declares `engines.node` `>=22` itself, so a Vercel AI SDK project is a Node 22 project and npm and pnpm will tell you so at install; `@langchain/core` 1 declares `>=20`. The core path uses `fetch` and Web Crypto only and imports no Node module at the top level; where `globalThis.crypto` is absent it falls back to `node:crypto` through a dynamic import that bundlers do not follow. ESM and CommonJS builds ship with type declarations. The CLI is Node only.
|
|
341
|
+
|
|
342
|
+
## Events
|
|
343
|
+
|
|
344
|
+
`onEvent` receives `request`, `response`, `retry`, `decision`, `degraded`, `outcome` and `error` events with ids, codes, statuses and durations. No event carries message content, and neither does any error message: an error's text is built from the HTTP status and the server's machine-readable `kind`. Log them freely.
|
|
345
|
+
|
|
346
|
+
The server's own error text is the one thing held back from that. The evaluate 400 covers invalid content and the API document declares no schema for the body, so the SDK cannot promise what is in it; it is kept off `.message` and out of every event, and parked on `GovernApiError.serverMessage`. Read it when you are debugging one call, and treat what comes back the way you treat the message it was about.
|
|
347
|
+
|
|
348
|
+
The hook is telemetry and is treated as such: every call is isolated, so a callback that throws cannot change a verdict, fail a request or escape `guard`. The throw comes back as an `error` event with `operation: "on_event"`; a callback that throws on that one too is left alone. The adapters treat their own `onDecision` and `onError` callbacks the same way.
|
|
349
|
+
|
|
350
|
+
## What the SDK covers
|
|
351
|
+
|
|
352
|
+
Every Govern surface the API exposes. The types are generated from `spec/openapi.json`, which ships in the package.
|
|
353
|
+
|
|
354
|
+
| SDK surface | What it is |
|
|
355
|
+
|---|---|
|
|
356
|
+
| `guard`, `evaluate`, `getDecision`, `waitForRelease`, mode learning | The gate: evaluate a draft, read a decision, wait for a held one |
|
|
357
|
+
| `sendHoldingLine`, `stopClass` on decisions and on `GuardResult` | When the patient is owed your holding line (at most once per decision), and whether a stop can ever be released |
|
|
358
|
+
| `showHoldText` on `GuardResult`, `isInSessionChannel` | Whether a hold's `text` is to be shown: for a patient audience, always in session (`web_chat`, `app_message`), exactly `sendHoldingLine` on an outbound or unknown channel; always for a clinician audience |
|
|
359
|
+
| `model`, `modelVersion` on `evaluate` and `guard`, filled by every adapter | The model and version each turn ran on, as recorded |
|
|
360
|
+
| `reportOutcome`, `ack()` | What you delivered, as part of the record |
|
|
361
|
+
| `recordDisclosure`, `rememberDisclosure`, `disclosureRef` | The AI-identity disclosure, per conversation |
|
|
362
|
+
| `recordPatientConsent`, `recordPatientOptOut`, `getPatientState` | The patient's state the gate checks first |
|
|
363
|
+
| `submitTranscripts`, `getTranscriptJob`, `getTranscriptJobTurns` | Observe-only ingest of past conversations |
|
|
364
|
+
| `handleWebhook`, `verifyWebhookSignature`, `listWebhookDeliveries` | Signed delivery of hold and hand-off resolution |
|
|
365
|
+
| `inbound` on `evaluate` and `guard`; `routeToHuman`, `handoff`, `inboundFlags`, `wouldHaveRouted`; `govern.handoffs.*` | The red-flag screen and the hand-off on your team (the four hand-off actions need a staff credential) |
|
|
366
|
+
| `pausesAutomation` on hand-offs, `isAutomationPaused`, `awaitingReply` on `govern.handoffs.list` | Whether a hand-off pauses automated messaging to the patient, and which items still owe a reply |
|
|
367
|
+
|
|
368
|
+
## Maintainers
|
|
369
|
+
|
|
370
|
+
Maintained by AnyBio Engineering (platform@anybio.io). Documentation and the developer portal: [developer.anybio.io](https://developer.anybio.io).
|
|
371
|
+
|
|
372
|
+
## License
|
|
373
|
+
|
|
374
|
+
Apache License 2.0. See `LICENSE` and `NOTICE`.
|