@anybio/govern 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,51 @@
2
2
 
3
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
4
 
5
+ ## 0.3.0
6
+
7
+ 0.3.0 changes the outcome report and the decision's outcome, so this minor version changes the public surface. It needs an API that records the outcome event trail. `turnRef` and `supersedes` take effect once the API accepts them and are ignored before that. The README and `spec/openapi.json` carry the field rules.
8
+
9
+ ### Breaking
10
+
11
+ - The outcome is an event trail. `reportOutcome(decisionId, input)` records one event, `{ kind, at, content | contentHash, deliveryRef?, reason? }`, with `kind` one of `released`, `delivered`, `discarded` or `failed`. `delivered: boolean` and `deliveredAt` are gone. `released` and `delivered` carry the SHA-256 of the text; `discarded` and `failed` carry none. Every field is checked before the request is sent; a slip is a `GovernConfigError` that names it.
12
+ - One event per kind per decision, `failed` excepted. The same event again resolves with the decision; a different event of a kind already on record is the API's 409, `GovernConflictError`.
13
+ - `Decision.outcome` is `{ state, events, raw }` or null. `state` is derived by the API from the trail. A server that predates the trail maps to null.
14
+ - `guard` reports no outcome. `GuardResult.ack()`, `AckOptions` and the automatic report the next `guard` made are removed; record what you wrote with `reportOutcome`. `flushPendingAcks()` is now `flushReports()`.
15
+ - The adapters (`withGovern`, `governed`, `GovernCallbackHandler` with `reportOutcome: true`) record `released` with the hash of the text they hand over, or `discarded` with a reason when nothing went out. Recording `delivered` is yours, from the channel's confirmation.
16
+ - A report an adapter made that did not land reaches `onError` as a `GovernReportError`, carrying the decision id and the event as it was sent, so the same event can be passed back to `reportOutcome`.
17
+ - A 409 on `evaluate` degrades with reason and cause `turn_conflict`, no longer `client_misconfigured`; the reply still holds in enforce.
18
+ - The `outcome` event is `{ type: "outcome", decisionId, kind }`. `delivered` and `auto` are gone.
19
+
20
+ ### Added
21
+
22
+ - `turnRef` and `supersedes` on `evaluate`, `guard` and the adapters, sent as `turn_ref` and `supersedes`. `turnRef` is your stable reference for the patient turn, the same on every draft of it (`MAX_TURN_REF_CHARS`, 128). `supersedes` names up to `MAX_SUPERSEDES` (8) decisions this turn replaces; each must belong to the turn's `patientRef`. The API refuses another patient's decision with 400, and with 409 one still being decided, delivered, acted on by a reviewer, or already superseded or retried.
23
+ - `retryOf` on `evaluate` and `guard`, sent as `retry_of`: the decision a new draft retries. The API answers a retry of a superseded, retried, delivered or reviewer-acted decision with 409, and one that was never retryable or belongs to another patient with 400. `retryable` and `retryOf` on `Decision`.
24
+ - `showHoldText` on `Decision` and `GuardResult`, following the API's `show_hold_text` when the decision carries it, else the channel rule.
25
+ - `gateSignal` on `guard`, and a per-call `signal` on the adapters, bounding the gate call alone. When it fires, the unreachable-API rule applies: a hold in enforce, a `degraded` draft in observe, `gate_unavailable` as the reason. A buffered patient stream whose gate call aborts releases the hold message in place of the draft. The generation's own abort signal is never passed to the gate, so a cancel never becomes a hold.
26
+ - `deliveredText` on the adapters: tell the adapter what actually went out, and its one report carries that. `null` or empty text records `discarded`.
27
+ - Types: `OutcomeKind`, `ReportedOutcomeKind`, `OutcomeSource`, `OutcomeEvent`, `WireOutcomeEvent`, `OUTCOME_REASONS`, `GovernReportError`, `DeliveredText` and `DeliveredMessage`; `turn_conflict` in `REASONS`.
28
+ - `spec/openapi.json` and the generated types follow the current API document. A field the document requires but an older server omits is optional in the exported types.
29
+
30
+ ### Changed
31
+
32
+ - `governed` resolves the call's context before the wrapped runnable runs, as `withGovern` does before the model. A run that cannot be gated fails with `GovernConfigError` before the model runs.
33
+ - An empty or blank `holdMessage` is refused with `GovernConfigError`.
34
+ - `reportOutcome: false` on an adapter means it records nothing.
35
+ - `voice` is an in-session channel for the hold rule, with `web_chat` and `app_message`; `sms` and `email` stay outbound. `voice` still requires a consent by default.
36
+ - For a server that predates `show_hold_text`, a hold a reviewer has released or rejected shows nothing.
37
+
38
+ ### Fixed
39
+
40
+ - A replayed turn whose decision already has an outcome on record is closed: no holding line is armed and no second report is made.
41
+ - `governed` no longer reports a cancelled run as delivered. It records `discarded` (`cancelled`) and throws.
42
+ - A `withGovern` buffered stream cancelled from inside `onDecision` records exactly one outcome.
43
+ - `flushReports()` waits for every report from the moment it is made, and a failed report has reached `onError` before it resolves.
44
+ - An error thrown by an adapter is an instance of the classes the root entry point exports, so `instanceof` and `isGovernError` hold across entry points.
45
+
46
+ ## 0.2.2
47
+
48
+ No change to the SDK. Built and published from github.com/anybio/govern-js with a provenance statement.
49
+
5
50
  ## 0.2.1
6
51
 
7
52
  First public release.
package/README.md CHANGED
@@ -13,10 +13,13 @@ const reply = await govern.guard(
13
13
  () => llm.chat(messages),
14
14
  { conversationId, turnId, channel: "sms", audience: "patient" },
15
15
  );
16
- if (reply.text !== "") await sendSms(patient.phone, reply.text);
16
+ if (reply.text !== "") {
17
+ const sent = await sendSms(patient.phone, reply.text);
18
+ if (reply.decisionId) await govern.reportOutcome(reply.decisionId, { kind: "released", at: new Date(), content: reply.text, deliveryRef: sent.id });
19
+ }
17
20
  ```
18
21
 
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.
22
+ `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`, `voice`), and on an outbound channel (`sms`, `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. Once you have written the reply to the channel, record it as `released`; when the channel confirms it reached the patient, record `delivered`. See [outcomes](#outcomes). The adapters record `released` for you.
20
23
 
21
24
  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
25
 
@@ -82,7 +85,26 @@ const result = streamText({
82
85
  });
83
86
  ```
84
87
 
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`.
88
+ `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`, `app_message` and `voice` the hold message always appears, on `sms` and `email` only when a holding line is owed, so a caller that sends whatever the model returns sends nothing. The outcome is recorded to match as the reply is handed over: `released` with the hash of the text let through (the hold message on a hold), or `discarded` with the reason `nothing_to_send` when no text went out. 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`.
89
+
90
+ **What went out.** The adapter makes one report per decision (`reportOutcome`, default true), as it hands the reply over: `released` with the text it let through. When you write something else, such as a line of your own on an `sms` hold that showed nothing, pass `deliveredText`. It receives the same info as `onDecision` and returns the text you wrote to the channel (hashed locally; only the hash is sent), `{ text, deliveredAt, deliveryRef }` to say when it went out (for a voice line, when it started to be spoken) and under which reference (`null` in either is none), or `null` when nothing went out. A `deliveryRef` is held to the API's rule: trimmed of Unicode white space at either end, not blank, at most 256 characters, no control character; anything else is a `GovernConfigError` naming `deliveredText`, passed to `onError`, and no report is made. Text is recorded as `released`, a shown hold message included; `null` and empty text are recorded as `discarded` with the reason `nothing_delivered`. The adapter does not wait for the hook before handing the reply over, so return a promise when you learn what went out later; its answer is the decision's one report, whenever it settles. A throw, a rejection or any other value goes to `onError`, and nothing is recorded for that decision. The hook is not called for a reply with no decision id, for a replayed decision whose outcome already has a state on record, or for a stream cancelled while the gate decides (recorded as `discarded`, reason `cancelled`). A decision a retry or a later turn's `supersedes` replaced is recorded like any other, from the hook's answer: on a retried hold nothing was shown, so answer `null` and it is `discarded`; the API adds its own `superseded` event beside it when it applies the retry or the list, and the derived state puts `superseded` on top. On a turn you retry, settle the hook after the retry's gate call: the stopped turn's answer (nothing, or the hold text after a refused retry) is known only once the retry is accepted or refused, and the SDK cannot order it for you. The adapter never records `delivered`: the channel's confirmation is yours to record with `govern.reportOutcome`. A report that did not land reaches `onError` as a `GovernReportError` carrying the event exactly as it was sent, to send again (see [outcomes](#outcomes)). A caller that records every outcome itself keeps `reportOutcome: false` and leaves `deliveredText` unset: then the adapter reports nothing, and a decision it never reports stays without an outcome.
91
+
92
+ **A bound on the gate call.** Pass a signal per call as `providerOptions.anybioGovern.signal` (`ai` types `providerOptions` as JSON, so it needs a cast there), or set the `signal` option, a function of the call params that the adapter calls when the gate call starts and only when the call carries no signal of its own. A signal's clock starts when you create it: one made before the call bounds the generation and the gate together, and on a clinician stream it has run through the whole stream before the trailing gate call; the option's `() => AbortSignal.timeout(ms)` is measured from the gate call. The option is a function and never a signal: one signal shared by every call would hold every call after it fired, so a bare signal is refused at construction. `null` is no bound. A per-call value that is not a signal is refused with `GovernConfigError` when the call starts, before the model runs; a value the option returns that is not a signal is refused when the gate call starts, which on a clinician stream comes after the text went out, so there it goes to `onError`. When the signal aborts, before or during the gate call, the call ends without a retry and [the unreachable-API rule](#when-the-api-cannot-be-reached) applies: in enforce a hold, with the hold message in session and no text on an outbound channel; in observe the draft, flagged `degraded`. Either way `reasons` is `["gate_unavailable"]`, there is no decision id, and the client emits its `degraded` event. The adapter passes the signal to `guard` as `gateSignal`, which answers this way; the call's own `signal` would be rethrown, and the adapter owns the delivery. One exception: a clinician stream, whose text has gone out before its trailing gate call, passes it as the call's own signal, so an abort there goes to `onError` and records nothing. The generation's own `abortSignal` is the caller's cancel and is never read for the gate call, so a cancel never becomes a hold.
93
+
94
+ ```ts
95
+ const middleware = withGovern({
96
+ govern,
97
+ channel: "voice",
98
+ audience: "patient",
99
+ conversationId: callId,
100
+ patientRef,
101
+ inbound: () => ({ content: lastUtterance, receivedAt: new Date() }),
102
+ signal: () => AbortSignal.timeout(800), // a fresh bound for each gate call
103
+ deliveredText: ({ turnId }) => spoken(turnId), // resolves with what was said, or null
104
+ });
105
+ ```
106
+
107
+ `inbound` requires `patientRef`, from the option or `providerOptions.anybioGovern.patientRef`. `retryOf`, `turnRef` and `supersedes` travel per call in `providerOptions.anybioGovern`, beside `turnId`.
86
108
 
87
109
  ### LangChain (`@langchain/core` v1)
88
110
 
@@ -95,11 +117,19 @@ const message = await gated.invoke(messages, {
95
117
  });
96
118
  ```
97
119
 
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.
120
+ 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 recorded to match: `released` with that text, or `discarded` when it is empty. `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
121
 
100
122
  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
123
 
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.
124
+ An output `governed` cannot read as text, such as the object a structured-output chain returns, is refused, not passed through: a gate that cannot see the output must not imply it approved it, and the error arrives on the first call, not 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.
125
+
126
+ `governed` resolves the call's context (conversation id, turn id, `retryOf`, `turnRef`, `supersedes`, patient reference, metadata, inbound and the per-call bound) before the wrapped runnable runs, as `withGovern` does before the model: a run that cannot be gated fails before the model runs, even one that would never reach the gate, and a resolver function you pass sees the state before the chain. `null` for `retryOf`, `turnRef` or `supersedes` is none on every surface. `governed` has the same two additions. `deliveredText` is an option and receives `{ reply, conversationId, turnId }` (what `onDecision` receives) and returns the text you wrote, `{ text, deliveredAt, deliveryRef }`, or `null`; the wrapper does not wait for it before returning, records its answer the same way (a failure goes to `onError` and records nothing), and with `reportOutcome: false` it is never called. `GovernCallbackHandler` takes `deliveredText` too, with `{ decision, runId }`, when `reportOutcome` is true: the handler does not wait for it, because LangChain runs callbacks one at a time and a hook that waits for the chain's delivery would hold every callback behind it. The per-call bound is `configurable.anybioGovern.signal`, passed as `gateSignal`, with the same unreachable-API rule and `degraded` event on abort. It takes a signal, which belongs to one call (bound once with `withConfig`, the same signal would hold every call after it fired), or a function called when the gate call starts, which is safe to bind once: `() => AbortSignal.timeout(ms)`. The run's own `config.signal` is LangChain's cancel and is never passed to the gate: a run cancelled before the gate call is not gated, and one cancelled while the gate decides is recorded as `discarded` (reason `cancelled`), with no `onDecision` or `deliveredText` for it. The callback handler sees no per-call config and makes no gate call of its own, so it takes no signal. `inbound` requires `patientRef`, from the option or `configurable.anybioGovern.patientRef`.
127
+
128
+ ```ts
129
+ const message = await gated.invoke(messages, {
130
+ configurable: { anybioGovern: { conversationId: threadId, turnId: messageId, signal: turnBudget.signal } },
131
+ });
132
+ ```
103
133
 
104
134
  ## What comes back
105
135
 
@@ -111,15 +141,19 @@ An output `governed` cannot read as text, such as the object a structured-output
111
141
  | `decision` | `allow`, `hold` or `block`. |
112
142
  | `mode` | `observe` or `enforce` (or `off`). |
113
143
  | `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. |
144
+ | `wouldHave` | Observe only: the raw gate decision (`allow`, `flag`, `block_and_review`, `policy_missing`) or `unavailable`. Decisions recorded before `flag` replaced `rewrite` keep `rewrite`. |
145
+ | `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 three only the SDK adds: `unknown_decision`, `client_misconfigured` when the API refused the call, and `turn_conflict` when it refused the turn with 409. `REASONS` exports the set. |
116
146
  | `disclosureRequired` | The policy demands the AI-identity disclosure and none is on record for the conversation. |
117
147
  | `reviewUrl`, `reviewState` | The console deep link and `pending` / `released` / `rejected`, when the decision is in the review queue. |
118
148
  | `deliverableContent` | Clinician audience only: the gate's term substitution to deliver. Never present for a patient audience, whatever the server sends. |
119
149
  | `releasedContent` | Present once a reviewer released the held message: what to deliver. |
120
150
  | `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
151
  | `sendHoldingLine` | Send your holding line now. True at most once per decision id per `Govern` instance; see [the holding line](#the-holding-line). |
152
+ | `showHoldText` | Whether the hold text is to be shown or sent for this decision: the same answer as `GuardResult.showHoldText`; see [in-session and outbound channels](#in-session-and-outbound-channels). |
153
+ | `retryable` | Your application may write one new draft for this stopped turn and evaluate it with `retryOf` set to this `id`. False from a server that predates the field. |
154
+ | `retryOf` | The decision this turn retried, when it was a retry. |
122
155
  | `model`, `modelVersion` | The model and version you named for this turn, as recorded. Null when none was sent. |
156
+ | `outcome` | What became of the reply: `{ state, events }`, null until the first event. See [outcomes](#outcomes). |
123
157
  | `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
158
  | `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
159
  | `inboundFlags` | The red-flag rules the inbound matched: rule id and category, never text. |
@@ -127,14 +161,18 @@ An output `governed` cannot read as text, such as the object a structured-output
127
161
  | `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
162
  | `raw` | The wire object, typed from the OpenAPI document. |
129
163
 
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.
164
+ A flag 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
165
 
132
- `guard` returns a `GuardResult`: `text`, `decisionId`, `decision`, `mode`, `degraded`, `reasons`, `held`, `sendHoldingLine`, `showHoldText`, `stopClass`, `routeToHuman`, `handoff`, `inboundFlags`, `record` and `ack()`.
166
+ `guard` returns a `GuardResult`: `text`, `decisionId`, `decision`, `mode`, `degraded`, `reasons`, `held`, `sendHoldingLine`, `showHoldText`, `stopClass`, `routeToHuman`, `handoff`, `inboundFlags` and `record`. It reports no outcome itself: record what you wrote with `reportOutcome` (see [outcomes](#outcomes)).
133
167
 
134
168
  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
169
 
136
170
  `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
171
 
172
+ `evaluate` and `guard` take `retryOf`, sent as `retry_of`: the `id` of a stopped turn whose decision came back `retryable`, answered with one new draft under a new `turnId` in the same conversation. Retry only when `retryable` is true: a never-sendable stop (a prohibited claim, a medication instruction) and every stop about the patient are not retryable by design. The API judges the new draft as any other turn. The retry is for the stopped turn's patient: the named decision must be recorded for this turn's `patientRef` (the same value, or neither has one), so if you set `patientRef` per call, keep it on the retry. The API refuses with `400` a `retryOf` that names a decision that was never retryable in the conversation, whatever a reviewer or another turn did with it, and one recorded for another `patientRef` (`retry_of must name a decision for the same patient_ref`); it refuses with `409` a retry of a decision another turn named in `supersedes`, a second retry of the same decision, a retry of a decision with a `delivered` event on record (`retry_of names a decision that was delivered`), and a retry of a decision that was retryable until a reviewer released or rejected it. A `409` is `GovernConflictError` and a `400` is `GovernApiError`, and `guard` treats either as any refused call, so the turn holds in enforce. A value that is not a decision id is refused with `GovernConfigError` before the draft function runs. On a retryable first hold, evaluate the retry before showing anything, and show the hold text only if the retry is stopped too, by the retry's own `showHoldText`: once the API has accepted the retry, the first turn reads `showHoldText` false. The first turn keeps its own report: nothing of it was shown, so record it `discarded` (an adapter does this when its `deliveredText` hook answers `null`). An API that applies the retry adds its own `superseded` event (source `retry`) beside it, and the derived state puts `superseded` on top. A retry that is refused, cannot reach the API, or whose draft function fails replaces nothing. The adapters take it per call, beside `turnId`: `providerOptions.anybioGovern.retryOf` for `withGovern`, `configurable.anybioGovern.retryOf` for `governed`.
173
+
174
+ `evaluate` and `guard` also take `turnRef` and `supersedes`, and the adapters take both per call beside `retryOf`. `turnRef`, sent as `turn_ref`, is your stable reference for the patient turn: the same on every draft written for that turn, a speculative re-send and a retry included, where `turnId` differs per draft; at most 128 characters (`MAX_TURN_REF_CHARS`), and a retry sent without one takes its parent's. `supersedes`, sent as `supersedes`, lists the decisions this turn replaces, such as a speculative reply your channel discarded: at most 8 decision ids (`MAX_SUPERSEDES`) of the same conversation, recorded for this turn's `patientRef` (the same value, or neither has one). Where the API applies it, each named decision leaves the review queue and gets a `superseded` event (source `supersedes`) beside its own report, which stays yours (or the adapter's) to make; an API that does not take the field ignores it, as it ignores `turnRef`. When the turn is an enforce `allow`, the hand-off a named stopped turn opened is resolved with the disposition `resolved_by_supersession` (`resolved_by_retry` when the decision in `retryOf` is on it), provided nothing else on it is owed and nobody has claimed it or acted on it; otherwise it stays open, with a note naming the new decision. The decision view returns both fields as `raw.turn_ref` and `raw.supersedes`, and a replaced decision's `raw.superseded_by` names the decision that replaced it. The API refuses with `400` an id named twice, the decision in `retryOf`, a decision of another application or conversation, and one recorded for another `patientRef` (`supersedes must name decisions for the same patient_ref`); it refuses with `409` an enforce decision still being decided, one with a `delivered` event, one a reviewer already released or rejected, and one another turn already superseded or retried. A refused turn records nothing. A value the API could not read (a blank or longer `turnRef`, a `supersedes` that is not a list of up to 8 decision ids) is refused with `GovernConfigError` before the draft function or the model runs. The API would refuse a list over 8 with `400` too; the SDK refuses it first, with `GovernConfigError`. `null` is none for all three, and an empty `supersedes` is none.
175
+
138
176
  **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
177
 
140
178
  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.
@@ -146,30 +184,36 @@ When a patient-bound draft is stopped, the patient is waiting on a reply that is
146
184
  ```ts
147
185
  const reply = await govern.guard(() => llm.chat(messages), { conversationId, turnId, channel: "sms", audience: "patient", patientRef });
148
186
  if (reply.text !== "") await sendSms(patient.phone, reply.text);
149
- // Equivalently: if (!reply.held || reply.showHoldText). On sms, showHoldText is sendHoldingLine.
187
+ // Equivalently: if (!reply.held || reply.showHoldText). On sms, showHoldText follows sendHoldingLine (one exception: see the channel section).
150
188
  ```
151
189
 
152
190
  - 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.
191
+ - It is false when another message would be the wrong thing, not merely an unnecessary one: `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
192
  - 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
193
 
156
194
  **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
195
 
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 })`.
196
+ What you record follows what you wrote: a hold shown in session is `released` with the hold message's hash, since it went to the patient, and a hold that showed nothing, where you wrote nothing, is `discarded` or left unreported. If you sent something anyway, record that text as `released`. The adapters record the same way: `released` with the hold message, or `discarded` with the reason `nothing_to_send`.
159
197
 
160
198
  ### In-session and outbound channels
161
199
 
162
200
  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
201
 
202
+ The in-session set is `web_chat`, `app_message` and `voice`. The outbound set is `sms` and `email`. Any other value is outbound.
203
+
164
204
  | Channel | On any hold or block | `showHoldText` | `text` |
165
205
  |---|---|---|---|
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 |
206
+ | In-session: `web_chat`, `app_message`, `voice` | The patient is in the session and waiting for the reply: in the chat or the app thread they opened, or on the line in a call, whoever dialed. The hold message is the reply there. | True on every stop no reviewer has released or rejected, including the fail-closed hold when the API cannot be reached, `patient_state_unavailable`, and the do-not-message stops | The hold message |
207
+ | Outbound: `sms`, `email` | Each message is a new contact. A message goes out only when the API says a holding line is owed | `sendHoldingLine` | The hold message when true, `""` when false |
208
+ | Any other value | Treated as outbound: fail closed | `sendHoldingLine` | As outbound |
209
+
210
+ This split is about replying inside a channel that is already open, and it is not the consent split: `voice` requires a consent by default, because an unsolicited call is a new contact, and it is in-session here, because a turn in a connected call is not one.
211
+
212
+ **The API's answer wins.** A current API states the same rule on every decision as `show_hold_text`, and `guard` and `Decision.showHoldText` follow it when it is there. It says false where the table alone cannot see why: once a reviewer has released or rejected the hold (`releasedContent` is the reply, or a person decided the turn), on a stopped turn once the API has accepted a retry of it or a turn that supersedes it (that turn's own decision answers), and on a decision the API can no longer read. That replaced turn is the one case where an outbound channel's `showHoldText` and `sendHoldingLine` differ: it keeps `sendHoldingLine` and reads `showHoldText` false. The API can also say true on a channel value this version does not know, when it knows that channel to be in-session. Two limits stay with the SDK whichever answered: on `sms` and `email` the hold text is the holding line, so it is never shown where `sendHoldingLine` is false, and on a channel this version does not know it is not shown where the SDK withheld a holding line the API offered. A server that predates the field gets the table above, except that a hold a reviewer has released or rejected shows nothing there either: the SDK reads the review state.
169
213
 
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.
214
+ The one-per-decision rule above is the holding line's. 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. On an outbound channel the hold text is the holding line, so a replayed turn shows nothing. `sendHoldingLine` is still reported beside an in-session hold for a caller that also sends the holding line somewhere else; in the session itself, the hold text is the one reply, so do not send a second one there.
171
215
 
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.
216
+ The classification is exported as `isInSessionChannel(channel)` (and the list as `IN_SESSION_CHANNELS`); `guard`, the decision mapping and every adapter read it, the known outbound set (`sms`, `email`) is derived from it, and nothing else in the SDK classifies a channel. The API applies the same classification.
173
217
 
174
218
  ## Modes
175
219
 
@@ -195,12 +239,17 @@ Idempotency: `turnId` is sent as `Idempotency-Key`. A retry, or a replay with th
195
239
 
196
240
  | Last known mode for the channel | `guard` returns |
197
241
  |---|---|
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 |
242
+ | `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`, `voice`) `text` is the hold message and `showHoldText` is true, because the patient is waiting in the session or on the line; 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
243
  | `observe` or `off` (or `assumeMode: "observe"` before anything is learned) | the draft, `decision: "allow"`, `degraded: true` |
200
244
 
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.
245
+ "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, and also a gate call whose `ctx.gateSignal` fired (below). Local configuration errors are rethrown, never degraded, and so is an abort of `ctx.signal`.
246
+
247
+ `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. There are two ways to bound one call:
248
+
249
+ - `ctx.gateSignal` bounds the gate call alone: the evaluate request and the waits between its attempts, not your draft function. When it fires, no further attempt is made and `guard` answers as in the table above, with `reasons: ["gate_unavailable"]`, no decision id and the `degraded` event (`cause: "gate_unavailable"`, `status: null`). On a retry (`retryOf`) the retried turn's pending report is left as it was, as on any unreachable gate. The adapters pass their per-call bound here.
250
+ - `ctx.signal` cancels the call: its abort is rethrown as `GovernAbortError`, 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. It wins when both fired.
202
251
 
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.
252
+ To bound every call, tighten `timeoutMs` and `maxRetries`.
204
253
 
205
254
  ### Which failure was it
206
255
 
@@ -210,14 +259,15 @@ The hold above is the same whatever went wrong, and it should be. What is not th
210
259
  |---|---|---|---|
211
260
  | `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
261
  | `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 |
262
+ | `turn_conflict` | `turn_conflict` | The API refused this turn with 409: the decision its `retryOf` names was already superseded, retried or delivered, or a reviewer acted on it first, or one its `supersedes` names was an enforce decision still being decided, or was delivered, reviewed, superseded or retried | Nothing to fix: a race on this turn's state. Refresh the decision (`getDecision`) and decide again |
213
263
 
214
264
  Rotating a key and missing one deployment produces the second: that process holds every patient message until the key is fixed.
215
265
 
216
266
  Treat them as different alerts. `gate_unavailable` is a rate to watch; a single `client_misconfigured` should page whoever owns the deployment.
217
267
 
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.
268
+ A 4xx is the caller's except `408` and `429`, which say "later", not "no", and `409`, which says the record moved: 429 is rate limiting the transport already retried, 408 is the server giving up on the request, which is the same class of event as a client-side timeout, and a 409 is `turn_conflict`, above. 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
269
 
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.
270
+ Every degraded reply from `guard` 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, a transport failure or a fired `gateSignal`. The adapters' replies go through `guard`, so theirs do too.
221
271
 
222
272
  **Both still hold in enforce.** This changes what an operator is told, not what reaches a patient.
223
273
 
@@ -243,7 +293,7 @@ if (result.routeToHuman) {
243
293
 
244
294
  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
295
 
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:
296
+ **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, not `automationResumedAt` alone, before sending anything automated to that patient:
247
297
 
248
298
  ```ts
249
299
  if (isAutomationPaused(result.handoff)) {
@@ -311,17 +361,51 @@ The SDK remembers the `ref` per conversation and attaches it to every later `eva
311
361
 
312
362
  **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
363
 
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.
364
+ **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: they describe the evidence, and need not echo your request.
315
365
 
316
366
  ## Outcomes
317
367
 
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.
368
+ What became of the reply is part of the record: proposed, decided, then what happened to the message. Delivery is known in stages, so each stage is its own event, and the record keeps all of them. `reportOutcome(decisionId, { kind, at, ... })` records one:
369
+
370
+ | `kind` | Record it when |
371
+ |---|---|
372
+ | `released` | your application wrote the reply to its channel (sent the SMS, started speaking it, posted it to the chat) |
373
+ | `delivered` | the channel confirmed the reply reached the person (a delivery receipt, a read receipt, playback that finished) |
374
+ | `discarded` | the reply was dropped before it reached anyone (the person spoke over it, the session ended, you chose not to send it) |
375
+ | `failed` | an attempt to deliver it failed (a bounce, a carrier rejection, a speech synthesis error) |
376
+
377
+ ```ts
378
+ await govern.reportOutcome(reply.decisionId, { kind: "released", at: new Date(), content: reply.text, deliveryRef: sms.id });
379
+ // later, from the channel's delivery receipt
380
+ await govern.reportOutcome(reply.decisionId, { kind: "delivered", at: receipt.at, content: reply.text, deliveryRef: sms.id });
381
+ ```
382
+
383
+ `released` and `delivered` carry the text: `content` is hashed with SHA-256 locally and only the hash is sent, or pass the hash itself as `contentHash` (64 hex characters, either case); the text never leaves your server. Empty `content` is no text, the SDK's one "nothing went out" value. `discarded` and `failed` carry none, and take a `reason` (a short code, never message text). `deliveryRef` and `reason` are bounded as the API bounds them: trimmed of Unicode white space at either end, not blank, at most 256 characters, no control characters; they are sent trimmed. `null` is none for every optional field. `at` is required: a Date or an RFC 3339 date-time string. `superseded` is written by the API only, when it applies a retry of the decision or a later turn's `supersedes`; `reportOutcome` refuses it. Every field is checked before anything is sent, and a slip is a `GovernConfigError` naming the field.
384
+
385
+ **One event per kind, `failed` excepted.** The same event again (the same `kind`, `at`, hash, `deliveryRef` and `reason`) is accepted and records nothing, so a report sent twice, by the transport's retry or by your own, is safe as long as `at` is the same. A different event of a kind already on record is refused with 409, `GovernConflictError`. A delivery can fail more than once, so `failed` repeats. Kinds do not exclude each other: a reply can be released, fail once, and then be delivered.
386
+
387
+ **The state.** `decision.outcome` is `{ state, events }`, null until the first event. The events are in the order the API recorded them, each with `kind`, `source` (`caller`, or `retry` and `supersedes` for the API's own `superseded` events), `at`, `recordedAt`, `contentHash`, `deliveryRef`, `reason`, `hashMatchesRelease` and `supersededBy`. `state` is derived, never stored: `delivered` if a delivered event exists, else `superseded`, else `discarded`, else `failed`, else `released`. A decision whose `record.outcome.state` is already set when the API answers was decided for an earlier draft of this turn: do not deliver new text under it. `guard` arms no holding line for it, and the adapters neither report it nor ask `deliveredText` about it.
388
+
389
+ `guard` reports nothing itself. The adapters record `released` as they hand the reply over, with the text they let through or what `deliveredText` says went out, and `discarded` when nothing went out, with a reason the SDK sets (`OUTCOME_REASONS`: `nothing_to_send`, `nothing_delivered`, `cancelled`, `not_handed_over`). They never record `delivered`: that is the channel's confirmation, yours to record. They report every decision, a retried or superseded one included; the API's own `superseded` event sits beside that report. A report that fails after the transport's retries reaches `reportOutcome`'s caller, or the adapter's `onError`; nothing retries it later. An adapter's failed report arrives as a `GovernReportError`: the decision id and the event exactly as it was sent (`kind`, `at`, `contentHash`, `deliveryRef`, `reason`), and the failure on `cause`. Sending that event again is safe, since the same `at` makes it the same event:
390
+
391
+ ```ts
392
+ onError: (error) => {
393
+ if (!(error instanceof GovernReportError) || error.cause instanceof GovernConflictError) return log(error);
394
+ govern.reportOutcome(error.decisionId, {
395
+ kind: error.kind,
396
+ at: error.at,
397
+ contentHash: error.contentHash,
398
+ deliveryRef: error.deliveryRef,
399
+ reason: error.reason,
400
+ }).catch(log);
401
+ },
402
+ ```
319
403
 
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.
404
+ A `GovernConflictError` cause means a different event of that kind is already on record, so resending changes nothing. `govern.flushReports()` waits for every report already on the wire, those you started and those an adapter made; call it on shutdown. It resolves only after an adapter's failed report has reached `onError`. A `deliveredText` hook that has not answered yet has nothing on the wire, so the flush does not wait for it.
321
405
 
322
406
  ## Streaming
323
407
 
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.
408
+ 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, never passed through beside the hold message. A stream the caller cancels while the gate is deciding is recorded as `discarded`. For a patient audience the first token arrives only after the decision, so show a typing indicator for the whole wait.
325
409
 
326
410
  ## The CLI
327
411
 
@@ -341,7 +425,7 @@ Node 20 and later, and edge runtimes; CI runs the suite on Node 20 and 22. `engi
341
425
 
342
426
  ## Events
343
427
 
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.
428
+ `onEvent` receives `request`, `response`, `retry`, `decision`, `degraded`, `outcome` and `error` events with ids, codes, statuses and durations. `outcome` carries the decision id and the `kind` of each outcome event the API accepted, recorded or answered as a replay. 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
429
 
346
430
  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
431
 
@@ -355,9 +439,10 @@ Every Govern surface the API exposes. The types are generated from `spec/openapi
355
439
  |---|---|
356
440
  | `guard`, `evaluate`, `getDecision`, `waitForRelease`, mode learning | The gate: evaluate a draft, read a decision, wait for a held one |
357
441
  | `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 |
442
+ | `showHoldText` on decisions and on `GuardResult`, `isInSessionChannel` | Whether a hold's `text` is to be shown: the API's `show_hold_text` when it sends one; else, for a patient audience, always in session (`web_chat`, `app_message`, `voice`) and `sendHoldingLine` on an outbound or unknown channel, and always for a clinician audience |
443
+ | `retryOf` on `evaluate` and `guard`; `retryable`, `retryOf` on decisions | One retry of a stopped turn under the gate's reasons: whether the API allows it, and the link between the two decisions |
359
444
  | `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 |
445
+ | `reportOutcome`, `flushReports` | What became of the reply (`released`, `delivered`, `discarded`, `failed`), as part of the record |
361
446
  | `recordDisclosure`, `rememberDisclosure`, `disclosureRef` | The AI-identity disclosure, per conversation |
362
447
  | `recordPatientConsent`, `recordPatientOptOut`, `getPatientState` | The patient's state the gate checks first |
363
448
  | `submitTranscripts`, `getTranscriptJob`, `getTranscriptJobTurns` | Observe-only ingest of past conversations |
@@ -0,0 +1,39 @@
1
+ /**
2
+ * What the framework adapters share: the outcome report they make, from
3
+ * what they handed over or from a caller's `deliveredText` hook, the replay
4
+ * check, and reporting a failure to `onError`.
5
+ * Internal; the adapters re-export the two answer types, and nothing else
6
+ * here leaves the package. The rule for a gate call whose bound fired lives
7
+ * in `guard` (`GuardContext.gateSignal`), not here.
8
+ */
9
+
10
+ /**
11
+ * What went out, with when and under which reference, for a caller that
12
+ * knows. Recorded as the decision's `released` event: the text's hash, at
13
+ * `deliveredAt`, under `deliveryRef`.
14
+ */
15
+ interface DeliveredMessage {
16
+ /** The text that went out. Hashed locally; only the hash is sent. The empty string means nothing went out. */
17
+ text: string;
18
+ /**
19
+ * When it went out (for a voice line, when it started to be spoken): a
20
+ * Date, or an RFC 3339 date-time string. The event's `at`. Default (also
21
+ * for `null`): when the hook answered.
22
+ */
23
+ deliveredAt?: Date | string | null;
24
+ /**
25
+ * Your own reference for the delivery (a message id on your channel).
26
+ * `null` is none. Trimmed of Unicode white space at either end, as the API
27
+ * trims it, it must not be blank, must be at most 256 characters and must
28
+ * carry no control character; anything else is a `GovernConfigError`
29
+ * naming `deliveredText`, passed to `onError`, and no report is made.
30
+ */
31
+ deliveryRef?: string | null;
32
+ }
33
+ /**
34
+ * What a `deliveredText` hook answers: the text that went out, the same with
35
+ * its time and reference, or `null` when nothing went out.
36
+ */
37
+ type DeliveredText = string | DeliveredMessage | null;
38
+
39
+ export type { DeliveredText as D, DeliveredMessage as a };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * What the framework adapters share: the outcome report they make, from
3
+ * what they handed over or from a caller's `deliveredText` hook, the replay
4
+ * check, and reporting a failure to `onError`.
5
+ * Internal; the adapters re-export the two answer types, and nothing else
6
+ * here leaves the package. The rule for a gate call whose bound fired lives
7
+ * in `guard` (`GuardContext.gateSignal`), not here.
8
+ */
9
+
10
+ /**
11
+ * What went out, with when and under which reference, for a caller that
12
+ * knows. Recorded as the decision's `released` event: the text's hash, at
13
+ * `deliveredAt`, under `deliveryRef`.
14
+ */
15
+ interface DeliveredMessage {
16
+ /** The text that went out. Hashed locally; only the hash is sent. The empty string means nothing went out. */
17
+ text: string;
18
+ /**
19
+ * When it went out (for a voice line, when it started to be spoken): a
20
+ * Date, or an RFC 3339 date-time string. The event's `at`. Default (also
21
+ * for `null`): when the hook answered.
22
+ */
23
+ deliveredAt?: Date | string | null;
24
+ /**
25
+ * Your own reference for the delivery (a message id on your channel).
26
+ * `null` is none. Trimmed of Unicode white space at either end, as the API
27
+ * trims it, it must not be blank, must be at most 256 characters and must
28
+ * carry no control character; anything else is a `GovernConfigError`
29
+ * naming `deliveredText`, passed to `onError`, and no report is made.
30
+ */
31
+ deliveryRef?: string | null;
32
+ }
33
+ /**
34
+ * What a `deliveredText` hook answers: the text that went out, the same with
35
+ * its time and reference, or `null` when nothing went out.
36
+ */
37
+ type DeliveredText = string | DeliveredMessage | null;
38
+
39
+ export type { DeliveredText as D, DeliveredMessage as a };
@@ -0,0 +1,64 @@
1
+ import { OUTCOME_REASONS, shortTextFault, timeValue, GovernConfigError, MAX_SHORT_TEXT_CHARS } from './chunk-CPNPQMEU.js';
2
+
3
+ // src/adapters.ts
4
+ function delivers(reply) {
5
+ return !reply.held || reply.showHoldText;
6
+ }
7
+ async function deliveredOutcome(hook, info) {
8
+ const answer = await hook(info);
9
+ if (answer === null || answer === "") return { kind: "discarded", reason: OUTCOME_REASONS.nothingDelivered };
10
+ if (typeof answer === "string") return { kind: "released", content: answer };
11
+ if (typeof answer === "object" && typeof answer.text === "string") {
12
+ const { text, deliveredAt, deliveryRef } = answer;
13
+ const report = text === "" ? { kind: "discarded", reason: OUTCOME_REASONS.nothingDelivered } : { kind: "released", content: text };
14
+ if (deliveredAt !== void 0 && deliveredAt !== null) report.at = timeOf(deliveredAt);
15
+ if (deliveryRef !== void 0 && deliveryRef !== null) {
16
+ const fault = shortTextFault(deliveryRef);
17
+ if (fault !== void 0) throw invalid(`a \`deliveryRef\` that ${fault} (the API takes a non-blank string of at most ${MAX_SHORT_TEXT_CHARS} characters, with no control characters)`);
18
+ report.deliveryRef = deliveryRef;
19
+ }
20
+ return report;
21
+ }
22
+ throw invalid(answer === void 0 ? "undefined" : `a ${typeof answer} with no string \`text\``);
23
+ }
24
+ function timeOf(value) {
25
+ const time = timeValue(value);
26
+ if (time !== void 0) return time;
27
+ throw invalid(
28
+ typeof value === "string" ? "a `deliveredAt` string that is not an RFC 3339 date-time (such as 2026-09-16T10:00:00Z)" : "a `deliveredAt` that is neither a valid Date nor an RFC 3339 date-time string"
29
+ );
30
+ }
31
+ function invalid(what) {
32
+ return new GovernConfigError(
33
+ `deliveredText must return a string, { text, deliveredAt?, deliveryRef? } or null (or a promise of one); it returned ${what}. No outcome was reported for the decision.`
34
+ );
35
+ }
36
+ function handedOver(text, reason) {
37
+ return text === null || text === "" ? { kind: "discarded", reason } : { kind: "released", content: text };
38
+ }
39
+ function postReport(govern, decisionId, report, onFailure) {
40
+ const at = report.at ?? /* @__PURE__ */ new Date();
41
+ const input = report.kind === "released" ? { kind: "released", at, content: report.content } : { kind: "discarded", at, reason: report.reason };
42
+ if (report.deliveryRef !== void 0) input.deliveryRef = report.deliveryRef;
43
+ return govern.reportForAdapter(decisionId, input, onFailure);
44
+ }
45
+ function failureReporter(onError) {
46
+ return (error) => {
47
+ try {
48
+ onError?.(error);
49
+ } catch {
50
+ }
51
+ };
52
+ }
53
+ function callSafely(run, reportFailure) {
54
+ try {
55
+ run();
56
+ } catch (error) {
57
+ reportFailure(error);
58
+ }
59
+ }
60
+ function hasOutcomeOnRecord(decision) {
61
+ return decision?.outcome?.state != null;
62
+ }
63
+
64
+ export { callSafely, deliveredOutcome, delivers, failureReporter, handedOver, hasOutcomeOnRecord, postReport };