osuite 2.13.0 → 2.14.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/GOVERNED_RECOVERY.md +248 -0
- package/GOVERNED_TOOLS.md +67 -0
- package/README.md +9 -3
- package/governed-tools/authority.mjs +15 -10
- package/governed-tools/contract.mjs +26 -8
- package/governed-tools/executor.mjs +180 -101
- package/governed-tools/journal.mjs +12 -5
- package/governed-tools/recovery.mjs +109 -0
- package/package.json +2 -1
- package/runtime/protocol.mjs +17 -1
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
# Evidence-bound native recovery
|
|
2
|
+
|
|
3
|
+
Version 2.14.0 adds the opt-in
|
|
4
|
+
`tools.recover(operationId, unchangedParams, options)` API to
|
|
5
|
+
`createGovernedTools` on Node 24/POSIX. Confirm registry availability with
|
|
6
|
+
`npm view osuite@2.14.0 version` before installing that version. The published
|
|
7
|
+
2.13.0 package does not include this API.
|
|
8
|
+
|
|
9
|
+
Ordinary `run()` and `status()` never invoke a recovery adapter or retry an
|
|
10
|
+
uncertain native call. Recovery is an explicit host application decision, not an
|
|
11
|
+
agent-supplied permission flag. All errors retain `retryAutomatically: false`.
|
|
12
|
+
|
|
13
|
+
When a known uncertain call has no adapter, `recover()` returns
|
|
14
|
+
`RECOVERY_UNSUPPORTED` with the matching parent's local state, action ID,
|
|
15
|
+
replay URL and no-resend guidance. It does not contact Studio, inspect the
|
|
16
|
+
resource, or create a child. A different input or binding conflicts without
|
|
17
|
+
returning the original record. An unused ID creates no record. An authoritative
|
|
18
|
+
empty status is only a point-in-time observation, not a guarantee that another
|
|
19
|
+
writer cannot commit after the read.
|
|
20
|
+
|
|
21
|
+
## Trust boundary
|
|
22
|
+
|
|
23
|
+
The developer installs a trusted, versioned adapter on a tool binding **before
|
|
24
|
+
the original run**. It owns resource observation and conditional execution. Its
|
|
25
|
+
revision, resource ID and contract are part of the original binding digest.
|
|
26
|
+
Changing them, the description, mapping revision or input conflicts with the
|
|
27
|
+
stored operation. Existing operations created without an adapter cannot acquire
|
|
28
|
+
one retroactively. Functions are snapshotted, but developer code and its closures
|
|
29
|
+
remain trusted; this is not code attestation or protection from a malicious host.
|
|
30
|
+
|
|
31
|
+
Two resource contracts are supported:
|
|
32
|
+
|
|
33
|
+
- `settled-absence`: authoritative evidence proves the original attempt has
|
|
34
|
+
settled without an effect, no deferred effect can arrive, and an enforced
|
|
35
|
+
exclusive writer/exclusion mechanism prevents another writer for this business
|
|
36
|
+
operation through recovery. A plain timeout, a connection failure, an eventually
|
|
37
|
+
consistent negative read, or an actor's assertion is not this evidence.
|
|
38
|
+
- `same-id-idempotent`: the native resource guarantees same-business-ID,
|
|
39
|
+
same-payload replay for original and recovery calls, with stable receipts and
|
|
40
|
+
no duplicate effects. The adapter validates this actual resource contract.
|
|
41
|
+
Replay may create a first effect if none exists, so it needs fresh authority
|
|
42
|
+
even when the goal is only to recover a receipt.
|
|
43
|
+
|
|
44
|
+
Append-only ambiguity is not recoverable. An append-only resource can opt in to
|
|
45
|
+
`settled-absence` only with the stated authoritative absence and enforced
|
|
46
|
+
exclusion guarantees. The SDK cannot derive these guarantees from JSON fields,
|
|
47
|
+
authenticate arbitrary resources, prevent direct unwrapped calls, or make an
|
|
48
|
+
arbitrary distributed resource exactly-once. The adapter must enforce the native
|
|
49
|
+
contract and revalidate its resource conditions before any possible effect.
|
|
50
|
+
|
|
51
|
+
## API and adapter
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
import { createGovernedTools } from 'osuite/governed-tools';
|
|
55
|
+
|
|
56
|
+
const tools = createGovernedTools({
|
|
57
|
+
config, namespace: 'native-commits', journalPath,
|
|
58
|
+
// initializeJournal: true only for deliberate first-time provisioning.
|
|
59
|
+
bindings: {
|
|
60
|
+
'benchmark.invoke': {
|
|
61
|
+
revision: 'mapping-1',
|
|
62
|
+
describe,
|
|
63
|
+
recovery: {
|
|
64
|
+
revision: 'native-recovery-1',
|
|
65
|
+
resourceId: 'ledger-A',
|
|
66
|
+
contract: 'settled-absence', // or 'same-id-idempotent'
|
|
67
|
+
async observe({ params, binding }) {
|
|
68
|
+
if (params.arguments.tool_name !== 'commit') return null;
|
|
69
|
+
// Application-owned authenticated public reads, not model/scorer data.
|
|
70
|
+
const observation = await readPublicNativeEvidence(params);
|
|
71
|
+
validateOriginalIdsPayloadContractAndExclusion(observation, params);
|
|
72
|
+
if (!observation.definitivelySettled) return null;
|
|
73
|
+
const now = Date.now();
|
|
74
|
+
return {
|
|
75
|
+
...binding,
|
|
76
|
+
schemaVersion: 'osuite.native_recovery_evidence.v1',
|
|
77
|
+
observedAt: now,
|
|
78
|
+
expiresAt: now + 5000,
|
|
79
|
+
settled: true,
|
|
80
|
+
outcome: observation.outcome,
|
|
81
|
+
proof: boundedPublicProof(observation),
|
|
82
|
+
};
|
|
83
|
+
},
|
|
84
|
+
async execute(unchangedParams, { binding, evidence }) {
|
|
85
|
+
// These are application adapter functions, not additional SDK APIs.
|
|
86
|
+
// Enforce evidence/exclusion or resource idempotence through the write.
|
|
87
|
+
await revalidateNativeConditions(unchangedParams, evidence);
|
|
88
|
+
return commitOriginalRequestAndProposal(unchangedParams);
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// Call only after a settled uncertain run, with the exact original input.
|
|
96
|
+
const receipt = await tools.recover(originalOperationId, unchangedParams, {
|
|
97
|
+
waitMs: 0,
|
|
98
|
+
// signal: abortController.signal,
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`recover` accepts only `waitMs` (integer 0..600000, default 0) and an optional
|
|
103
|
+
native `AbortSignal`. It accepts no callback, evidence, retry flag, business ID
|
|
104
|
+
override or admission ID. A multiplexed binding must restrict recovery to the
|
|
105
|
+
specific native commit; installing it is not permission to recover generic
|
|
106
|
+
`api_fetch` calls. Return `null` or throw from `observe` for unsupported calls.
|
|
107
|
+
|
|
108
|
+
The frozen observer input is `{ params, binding }`. `params` is the original
|
|
109
|
+
native `{ name, arguments }` snapshot. `binding` contains exactly:
|
|
110
|
+
|
|
111
|
+
```js
|
|
112
|
+
{
|
|
113
|
+
operationId, // Original SDK business operation ID.
|
|
114
|
+
scope, // Original tenant/origin/runtime/namespace digest.
|
|
115
|
+
inputDigest, // Original tool name and exact arguments digest.
|
|
116
|
+
bindingDigest, // Original mapping and recovery descriptor digest.
|
|
117
|
+
actionId, // Original Studio action, NOT the recovery child.
|
|
118
|
+
resourceId,
|
|
119
|
+
adapterRevision,
|
|
120
|
+
contract,
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Adapter revision and resource ID are safe IDs of at most 128 characters (letters,
|
|
125
|
+
digits, underscores, dots, hyphens; no `..`). All five adapter properties in the
|
|
126
|
+
example are required; accessors, proxies and extra adapter fields are rejected.
|
|
127
|
+
|
|
128
|
+
Evidence copies every `binding` field unchanged and adds only `schemaVersion`,
|
|
129
|
+
`observedAt`, `expiresAt`, `settled`, `outcome`, and `proof`. It is immutable plain
|
|
130
|
+
JSON, at most **8192 bytes in total**, with a nonempty plain-object `proof`.
|
|
131
|
+
Timestamps are integer Unix milliseconds. Evidence cannot be future-dated, older
|
|
132
|
+
than five seconds, expired, or valid for more than five seconds after observation.
|
|
133
|
+
`settled` must be `true`. `settled-absence` permits only `outcome: 'absent'`;
|
|
134
|
+
`same-id-idempotent` also permits `'applied'` and `'unknown'`.
|
|
135
|
+
|
|
136
|
+
Store full public observations in the application's audit channel if needed;
|
|
137
|
+
put bounded resource metadata/digests in `proof`. The SDK verifies the envelope
|
|
138
|
+
and commitments, not the meaning or provenance of arbitrary proof fields. The
|
|
139
|
+
trusted adapter must verify authenticated resource facts, contract, current
|
|
140
|
+
native grants/status, exact original request/proposal identity and payload. No
|
|
141
|
+
hidden case label, expected score or caller assertion is recovery evidence.
|
|
142
|
+
|
|
143
|
+
The SDK invokes `observe` before admission and again after fresh authorization.
|
|
144
|
+
It then rereads parent and child Studio state and checks evidence/authorization
|
|
145
|
+
freshness immediately before and after the synchronous durable dispatch fence.
|
|
146
|
+
Validated scoped-rule and redeemed-grant expiry also bound that dispatch window.
|
|
147
|
+
`execute` receives the frozen original params and `{ binding, evidence }` using
|
|
148
|
+
the second observation. It must preserve native business IDs, enforce the native
|
|
149
|
+
contract, return the actual resource receipt and throw on an unconfirmed result.
|
|
150
|
+
Recovery does not claim completion from opaque/non-JSON or oversized returns;
|
|
151
|
+
results must fit the existing 64 KiB JSON result-digest bound and not be MCP
|
|
152
|
+
`isError` results. Full business results are never retained in the SDK journal.
|
|
153
|
+
|
|
154
|
+
Adapters must use bounded, read-only observation I/O and bounded native transport.
|
|
155
|
+
An abort is checked at SDK boundaries, not a guarantee to cancel an in-flight
|
|
156
|
+
adapter request or undo an effect. There is no SDK resource-poll or effect-retry
|
|
157
|
+
loop. Native revalidation and the effect are not atomic with Studio authorization;
|
|
158
|
+
enforcement across that gap belongs to the trusted resource/adapter contract.
|
|
159
|
+
|
|
160
|
+
## Journal and current authority
|
|
161
|
+
|
|
162
|
+
Only a local parent in `uncertain` is eligible. An in-flight/crashed `dispatching`
|
|
163
|
+
parent, uncertain create/redemption, held, completed, denied, cancelled or expired
|
|
164
|
+
operation cannot enter recovery. The parent must currently match its original
|
|
165
|
+
Studio action and be `running` (e.g. lost report) or `failed`. Current denial,
|
|
166
|
+
cancellation, expiry, missing evidence or identity mismatch blocks recovery.
|
|
167
|
+
|
|
168
|
+
The supported Studio projection is `osuite.action_envelope.v1`. Both the persisted
|
|
169
|
+
action's `input_summary.osuite_native_call` and the envelope's copy must match the
|
|
170
|
+
journal's operation, input and binding digests and native-call schema. The envelope
|
|
171
|
+
must also match the action, organization, agent, session and tool-use identities.
|
|
172
|
+
Neither `action.tool_input_digest` nor `action_envelope.tool_input_digest` is a
|
|
173
|
+
persisted field in this schema; absence is normal. If either duplicate is present,
|
|
174
|
+
it must match, but it never substitutes for a missing or mismatched persisted
|
|
175
|
+
marker. Unsupported envelope profiles fail closed. Recovery linkage is checked
|
|
176
|
+
in both summaries as well, on admission and on fresh current reads.
|
|
177
|
+
|
|
178
|
+
One deterministic private-scope child record uses the **same operation ID** but a
|
|
179
|
+
distinct SDK-generated Studio action/session identity. It uses the same input
|
|
180
|
+
digest and native parameters. The signed child input summary contains
|
|
181
|
+
`osuite_native_recovery` with `schema_version`, `parent_action_id`, `parent_scope`,
|
|
182
|
+
`operation_digest`, `input_digest`, `binding_digest`, `adapter_revision`,
|
|
183
|
+
`resource_id` and `contract`. This link is verified in admission and current reads;
|
|
184
|
+
it is not caller-controlled. Both allow and reviewed recovery use fresh posture,
|
|
185
|
+
guard and action admission. A consumed parent approval is never reused.
|
|
186
|
+
|
|
187
|
+
The original record and its evidence remain unchanged, including its `uncertain`
|
|
188
|
+
state. The child uses existing journal version 1 states, transaction ownership and
|
|
189
|
+
CAS transitions. There is no schema migration, parent reset, owner takeover or
|
|
190
|
+
lock-expiry retry. Older executors cannot dispatch the uncertain parent, and a
|
|
191
|
+
binding without the installed adapter conflicts with its digest. Keep one shared
|
|
192
|
+
durable journal for all workers; copied/deleted journals do not preserve this
|
|
193
|
+
serialization guarantee. Each eligible recovery consumes one additional record
|
|
194
|
+
from the existing journal capacity, with no eviction.
|
|
195
|
+
|
|
196
|
+
Before dispatch the existing bounded `error_code` metadata slot records
|
|
197
|
+
`recovery_<sha256(canonicalJson({ initial, revalidated }))>`, committing both frozen
|
|
198
|
+
observations. This is an evidence commitment, not an error or an execution grant.
|
|
199
|
+
The child outcome report includes the parent linkage and this evidence digest.
|
|
200
|
+
Journal records retain only identifiers, metadata and digests, not proof bodies,
|
|
201
|
+
native arguments or receipts. Keep the exact envelopes in your own audit if you
|
|
202
|
+
need to independently recompute the evidence commitment.
|
|
203
|
+
|
|
204
|
+
## Results and no-retry boundaries
|
|
205
|
+
|
|
206
|
+
`recover` returns the actual adapter result only after durable completion. Read
|
|
207
|
+
`(await tools.status(originalOperationId)).recoveryAttempt` for the child state,
|
|
208
|
+
result digest, evidence digest, report state and review/replay URLs. The top-level
|
|
209
|
+
state/action/URLs still describe the original parent. Recovery errors also attach
|
|
210
|
+
`status.recoveryAttempt`. When a child exists, the error's top-level
|
|
211
|
+
`status.actionId`, `status.state`, `status.reviewUrl` and `status.replayUrl`
|
|
212
|
+
describe that child, so `AWAITING_APPROVAL` points directly to the actionable
|
|
213
|
+
review. The original parent's immutable status remains in `error.status.parent`;
|
|
214
|
+
the business `operationId` is unchanged. Child status is local evidence, not permission to execute. Status
|
|
215
|
+
reads never observe the resource, redeem approval or execute either callback.
|
|
216
|
+
|
|
217
|
+
A child durably in `held` can resume its same review using another explicit
|
|
218
|
+
`recover` with unchanged params, including after reopening the journal. It still
|
|
219
|
+
reobserves resource evidence and gets fresh current authority. An unclaimed
|
|
220
|
+
`prepared` child or a failed initial evidence read has not consumed a grant;
|
|
221
|
+
manual reinspection is possible, but the SDK never schedules another attempt.
|
|
222
|
+
|
|
223
|
+
After a child is claimed, uncertain admission/redemption, failed revalidation,
|
|
224
|
+
callback failure, or a crash permanently fences this single recovery attempt.
|
|
225
|
+
Even later authoritative absence cannot create a third action. A completed child
|
|
226
|
+
returns `ALREADY_COMPLETED` on subsequent recovery; read its result from the
|
|
227
|
+
application store rather than resending. Lost outcome-report acknowledgement
|
|
228
|
+
does not hide a durably successful resource result. `run` continues to return
|
|
229
|
+
`OUTCOME_UNKNOWN` for the original parent, including after successful recovery.
|
|
230
|
+
Never change business IDs or reinitialize storage to bypass these boundaries.
|
|
231
|
+
|
|
232
|
+
## Verification
|
|
233
|
+
|
|
234
|
+
Run with Node 24, without installations or external model calls:
|
|
235
|
+
|
|
236
|
+
```sh
|
|
237
|
+
/Users/jw/.nvm/versions/node/v24.22.0/bin/node --test sdk/governed-tools/test/*.test.mjs
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
The recovery tests use actual localhost HTTP resources and a signed Studio wire
|
|
241
|
+
fixture. C1 proves a settled before-effect failure can complete once; C3 proves
|
|
242
|
+
lost receipt replay has one physical effect. Coverage includes bad/stale evidence,
|
|
243
|
+
append-only ambiguity, identity/mapping changes, fresh denial/cancellation,
|
|
244
|
+
approval consumption/expiry, concurrency in separate processes, crash/reopen,
|
|
245
|
+
invalid results, journal preservation and default no-retry behavior. This is not
|
|
246
|
+
a substitute for qualification against the actual Studio routes and production
|
|
247
|
+
resource contract. The experiment owner performs that qualification and the
|
|
248
|
+
separate finite benchmark rerun before making product claims.
|
package/GOVERNED_TOOLS.md
CHANGED
|
@@ -96,6 +96,37 @@ is current client configuration, not a resource capability or proof that every
|
|
|
96
96
|
unsigned request to the server is prohibited. Actual signed action responses
|
|
97
97
|
and fresh admission are checked separately.
|
|
98
98
|
|
|
99
|
+
### Choose The Intended Configuration Scope
|
|
100
|
+
|
|
101
|
+
Device enrollment and a tool/provider connection are different records. An
|
|
102
|
+
enrolled SDK identity does not by itself create an `agent_connections` entry.
|
|
103
|
+
Administrative posture writes to `/api/runtimes/sdk/posture` use these targets:
|
|
104
|
+
|
|
105
|
+
| POST target fields | Intended scope |
|
|
106
|
+
| --- | --- |
|
|
107
|
+
| Neither `agent_id` nor `provider` | Workspace SDK defaults. |
|
|
108
|
+
| `agent_id`, without `provider` | That agent's SDK posture. |
|
|
109
|
+
| Both `agent_id` and `provider: sdk` | An existing provider connection's SDK override. |
|
|
110
|
+
|
|
111
|
+
Only an authorized administrator may write posture. A device credential's
|
|
112
|
+
ability to read effective posture is not permission to manage it. Read the
|
|
113
|
+
current complete posture before an intended update, retain its other fields,
|
|
114
|
+
and re-read the effective configuration afterward. Do not silently broaden a
|
|
115
|
+
connection-targeted update to agent or workspace scope after a 404.
|
|
116
|
+
|
|
117
|
+
An SDK read with `agent_id` and `provider=sdk` inherits the agent posture when no
|
|
118
|
+
connection override exists. Check `scope`, `source` and `targeting`, rather than
|
|
119
|
+
inferring writable scope from a successful GET. `Connection not found for posture
|
|
120
|
+
override` means the selected connection write target was absent, not that the
|
|
121
|
+
agent-scoped route is necessarily unavailable.
|
|
122
|
+
|
|
123
|
+
POST and GET revision hashes do not currently share an identical input shape:
|
|
124
|
+
GET also includes rollout-negotiation metadata. Different target tuples also
|
|
125
|
+
change the revision. Check each response against its own declared scope and
|
|
126
|
+
content; do not treat POST/GET hash inequality alone as a failed write. A required
|
|
127
|
+
capability that this wrapper cannot satisfy must still stop execution; reducing
|
|
128
|
+
that requirement is an administrator's policy decision, not an SDK recovery step.
|
|
129
|
+
|
|
99
130
|
## Connected MCP Client
|
|
100
131
|
|
|
101
132
|
```js
|
|
@@ -183,6 +214,42 @@ the native result remains the return value and `reportState` is `uncertain`.
|
|
|
183
214
|
Do not replay the tool to repair a report. `close()` prevents new work; an
|
|
184
215
|
already-started native call is allowed to record its outcome before SQLite closes.
|
|
185
216
|
|
|
217
|
+
### Read Status At The Correct Layer
|
|
218
|
+
|
|
219
|
+
Do not collapse the following fields into one business-success flag:
|
|
220
|
+
|
|
221
|
+
| Observation | Meaning | Does not establish |
|
|
222
|
+
| --- | --- | --- |
|
|
223
|
+
| Local `state: completed` | The wrapper observed a native return without its error flag. | Independent resource verification, settlement or retention of the full result. |
|
|
224
|
+
| Local `state: uncertain` | The operation is fenced without a confirmed native outcome; the callback may not have run. | Failure, rollback or permission to resend. |
|
|
225
|
+
| `reportState: confirmed` | Studio acknowledged the wrapper's outcome report. | Successful business execution. An uncertainty report can itself be confirmed. |
|
|
226
|
+
| `remote.status: failed` with local `uncertain` | The SDK reports native uncertainty using this lifecycle label with `observation: outcome_unknown`; neither business failure nor reporting failure follows from the label. | Proof that the external resource did not commit. |
|
|
227
|
+
| Authorized resource readback | Evidence about the resource's recorded operation and effect. | A new execution grant or an automatic transition of the SDK journal to completed. |
|
|
228
|
+
|
|
229
|
+
For example, a resource can commit and then lose its acknowledgement. The native
|
|
230
|
+
callback throws, the SDK retains `uncertain`, and Studio may show `failed` with
|
|
231
|
+
an `osuite.native_tool_observation.v1` summary whose observation is
|
|
232
|
+
`outcome_unknown`. A confirmed report of that uncertainty is consistent with a
|
|
233
|
+
real resource commit. `status()` is read-only; restarting the adapter does not
|
|
234
|
+
resolve this disagreement or authorize redispatch.
|
|
235
|
+
Inspect `output_summary` through an authorized action read; SDK `status()` does
|
|
236
|
+
not expose that summary.
|
|
237
|
+
|
|
238
|
+
An application recovery procedure should preserve the original operation ID,
|
|
239
|
+
scope and journal, read SDK status, then use its existing authenticated resource
|
|
240
|
+
status interface. Check the tenant/resource identity, business operation ID,
|
|
241
|
+
target and relevant arguments or commitments against the original job. Missing,
|
|
242
|
+
ambiguous or mismatched evidence remains unknown. Even `not_found` may reflect
|
|
243
|
+
an incomplete index or an in-flight request, not proof of non-execution. Display
|
|
244
|
+
a verified resource result separately from local execution and reporting state;
|
|
245
|
+
do not edit the SDK journal, manufacture a receipt, or rerun the callback to make
|
|
246
|
+
the labels agree. This release has no general resource-reconciliation callback
|
|
247
|
+
that automatically converts an arbitrary tool's uncertain result to completed.
|
|
248
|
+
Version 2.14.0 adds an explicit host-selected `recover()` path for bindings with
|
|
249
|
+
a preinstalled trusted resource adapter. It preserves the uncertain parent and
|
|
250
|
+
uses a separately authorized recovery child; it does not change ordinary
|
|
251
|
+
`run()` or `status()`. See [Evidence-bound native recovery](GOVERNED_RECOVERY.md).
|
|
252
|
+
|
|
186
253
|
Use an owner-only directory and a durable local filesystem. Unsafe ownership,
|
|
187
254
|
permissions, symlinks/hardlinks and invalid database paths are rejected. SQLite
|
|
188
255
|
uses transactional CAS and full durability. The default limit is 10,000 retained
|
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# OSuite SDK (v2.
|
|
1
|
+
# OSuite SDK (v2.14.0)
|
|
2
2
|
|
|
3
3
|
**Governed action SDK for AI agents.**
|
|
4
4
|
|
|
@@ -8,6 +8,12 @@ The opt-in Node 24 `osuite/governed-tools` entry preserves native tool calls
|
|
|
8
8
|
and adds durable approval recovery. See [Native Tool Compatibility](GOVERNED_TOOLS.md).
|
|
9
9
|
It was introduced in 2.11.0 and does not enable Hook or a gateway.
|
|
10
10
|
|
|
11
|
+
Version 2.14.0 adds explicit [evidence-bound native recovery](GOVERNED_RECOVERY.md).
|
|
12
|
+
With a trusted resource adapter installed before execution, applications can
|
|
13
|
+
recover a settled uncertain call under fresh authorization and the original
|
|
14
|
+
business ID. Ordinary calls still never automatically resend an uncertain
|
|
15
|
+
effect. Arbitrary resources and append-only ambiguity are not made exactly-once.
|
|
16
|
+
|
|
11
17
|
## Installation
|
|
12
18
|
|
|
13
19
|
### Node.js
|
|
@@ -25,8 +31,8 @@ node /absolute/path/to/osuite-sdk/sdk/cli.js doctor
|
|
|
25
31
|
node /absolute/path/to/osuite-sdk/sdk/cli.js try
|
|
26
32
|
```
|
|
27
33
|
|
|
28
|
-
For this version, use `npx osuite@2.
|
|
29
|
-
with `npm view osuite@2.
|
|
34
|
+
For this version, use `npx osuite@2.14.0 connect` only after confirming availability
|
|
35
|
+
with `npm view osuite@2.14.0 version`. A source checkout or this document alone
|
|
30
36
|
does not establish registry publication, and npm's `latest` may differ from the
|
|
31
37
|
checked-out version. The stable credential-recovery behavior and the new
|
|
32
38
|
native-call operation journal are different mechanisms.
|
|
@@ -6,6 +6,8 @@ import { createStateStore } from '../runtime/state.mjs';
|
|
|
6
6
|
import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
|
|
7
7
|
import { matchesStoredAction, reject } from './contract.mjs';
|
|
8
8
|
|
|
9
|
+
const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
|
|
10
|
+
|
|
9
11
|
export function createStudioAuthority(config, journalPath) {
|
|
10
12
|
const responseLimits = { maxResponseBytes: 1048576 };
|
|
11
13
|
const baseApi = createApiClient(config, responseLimits);
|
|
@@ -46,14 +48,15 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
async function read(record) {
|
|
49
|
-
const response = await baseApi.request('GET', `/api/actions/${encodeURIComponent(record.actionId)}
|
|
51
|
+
const response = await baseApi.request('GET', `/api/actions/${encodeURIComponent(record.actionId)}`, undefined, receiptWindow);
|
|
50
52
|
if (!response.ok) return { available: false, status: response.status };
|
|
51
53
|
if (!matchesStoredAction(response.body, record, config)) return { available: false, status: response.status, mismatch: true };
|
|
52
54
|
return { available: true, body: response.body, action: response.body.action || response.body };
|
|
53
55
|
}
|
|
54
56
|
|
|
55
57
|
async function admit(invocation, journal, owner, aborted) {
|
|
56
|
-
const record = journal.get(invocation.record.scope, invocation.record.operationId)
|
|
58
|
+
const record = { ...journal.get(invocation.record.scope, invocation.record.operationId),
|
|
59
|
+
...(invocation.recovery ? { recovery: invocation.recovery } : {}) };
|
|
57
60
|
const phase = record.state === 'held' ? 'redeeming' : 'requesting';
|
|
58
61
|
const { api, effective } = await current(aborted);
|
|
59
62
|
if (aborted()) reject('ABORTED');
|
|
@@ -66,7 +69,7 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
66
69
|
if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
|
|
67
70
|
|| actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
|
|
68
71
|
|| actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE');
|
|
69
|
-
let claimed = false,
|
|
72
|
+
let claimed = false, requestStartedAt = null;
|
|
70
73
|
const claim = () => {
|
|
71
74
|
if (claimed) reject('OUTCOME_UNKNOWN');
|
|
72
75
|
if (aborted()) reject('ABORTED');
|
|
@@ -79,10 +82,10 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
79
82
|
config: effective,
|
|
80
83
|
api: { async request(method, endpoint, body, options) {
|
|
81
84
|
if (aborted()) reject('ABORTED');
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
85
|
+
const registering = method === 'POST' && endpoint === '/api/actions';
|
|
86
|
+
if (registering) { claim(); requestStartedAt = performance.now(); }
|
|
87
|
+
const response = await api.request(method, endpoint, body, registering ? receiptWindow : options);
|
|
88
|
+
if (registering) {
|
|
86
89
|
if (!response.ok || !matchesStoredAction(response.body, record, config)
|
|
87
90
|
|| !cavaFingerprint(response.body)) {
|
|
88
91
|
settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
|
|
@@ -99,7 +102,8 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
99
102
|
{ actionId: record.actionId, fingerprint: record.fingerprint }).authorized);
|
|
100
103
|
},
|
|
101
104
|
});
|
|
102
|
-
if (result.authorized) return { phase,
|
|
105
|
+
if (result.authorized) return { phase, dispatchDeadline: requestStartedAt + receiptWindow.timeoutMs, response: result.response,
|
|
106
|
+
ruleExpiresAt: result.ruleRolloutBinding?.expires_at ?? null };
|
|
103
107
|
if (result.reason === 'policy_block') {
|
|
104
108
|
if (!claimed) claim();
|
|
105
109
|
settle('denied'); reject('POLICY_DENIED');
|
|
@@ -123,9 +127,10 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
123
127
|
timestamp_end: new Date().toISOString(),
|
|
124
128
|
output_summary: JSON.stringify({ schema_version: 'osuite.native_tool_observation.v1',
|
|
125
129
|
observation: state === 'completed' ? 'native_return' : 'outcome_unknown',
|
|
126
|
-
result_digest: resultDigest, result_retained: false, independent_resource_verification: false
|
|
130
|
+
result_digest: resultDigest, result_retained: false, independent_resource_verification: false,
|
|
131
|
+
...(record.recovery ? { recovery: record.recovery, recovery_evidence_digest: record.errorCode?.slice('recovery_'.length) ?? null } : {}) }),
|
|
127
132
|
...(state === 'uncertain' ? { error_message: 'Native call outcome is uncertain; no automatic resend.' } : {}),
|
|
128
|
-
});
|
|
133
|
+
}, receiptWindow);
|
|
129
134
|
return response.ok && matchesStoredAction(response.body, record, config)
|
|
130
135
|
&& response.body.action?.status === (state === 'completed' ? 'completed' : 'failed')
|
|
131
136
|
&& typeof response.body.action?.timestamp_end === 'string';
|
|
@@ -30,7 +30,10 @@ function recoveryGuidance(code, state) {
|
|
|
30
30
|
else if (['requesting', 'redeeming', 'dispatching', 'uncertain', 'uncertain_request', 'uncertain_redemption'].includes(state)) nextStep = 'reconcile_without_resend';
|
|
31
31
|
else if (!code && state === 'prepared') nextStep = 'check_current_authority';
|
|
32
32
|
else nextStep = 'inspect_configuration';
|
|
33
|
-
|
|
33
|
+
const message = code === 'RECOVERY_UNSUPPORTED' && state === 'uncertain'
|
|
34
|
+
? 'No resource recovery contract was installed for this call. Keep the same operation ID and reconcile against the original receipt. An empty lookup is not permission to resend.'
|
|
35
|
+
: recoveryMessages[nextStep];
|
|
36
|
+
return Object.freeze({ nextStep, preserveOperationId: true, message });
|
|
34
37
|
}
|
|
35
38
|
|
|
36
39
|
export class GovernedToolError extends Error {
|
|
@@ -114,7 +117,8 @@ function describe(binding, args) {
|
|
|
114
117
|
|| item.some(entry => typeof entry !== 'string' || entry.length > 500))) reject('INVALID_MAPPING');
|
|
115
118
|
}
|
|
116
119
|
if (value.input_summary !== undefined && (!value.input_summary || Array.isArray(value.input_summary)
|
|
117
|
-
|| typeof value.input_summary !== 'object' || Object.hasOwn(value.input_summary, 'osuite_native_call')
|
|
120
|
+
|| typeof value.input_summary !== 'object' || Object.hasOwn(value.input_summary, 'osuite_native_call')
|
|
121
|
+
|| Object.hasOwn(value.input_summary, 'osuite_native_recovery'))) reject('INVALID_MAPPING');
|
|
118
122
|
return value;
|
|
119
123
|
}
|
|
120
124
|
|
|
@@ -131,7 +135,9 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
|
|
|
131
135
|
// The historical Hook helper normalizes null to {}. Native calls must retain
|
|
132
136
|
// every JSON value exactly, including that distinction.
|
|
133
137
|
const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
|
|
134
|
-
const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description
|
|
138
|
+
const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description,
|
|
139
|
+
...(binding.recovery ? { recovery: { revision: binding.recovery.revision,
|
|
140
|
+
resourceId: binding.recovery.resourceId, contract: binding.recovery.contract } } : {}) }));
|
|
135
141
|
const identity = sha256(canonicalJson([scope, operationId]));
|
|
136
142
|
const actionId = `act_${identity}`, sessionId = `sess_${identity}`, toolUseId = `tool_${identity}`;
|
|
137
143
|
const marker = { schema_version: CALL_SCHEMA, operation_digest: sha256(operationId), input_digest: inputDigest, binding_digest: bindingDigest };
|
|
@@ -144,18 +150,30 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
|
|
|
144
150
|
inputDigest, bindingDigest, contextDigest: sha256(canonicalJson(context)), actionId, sessionId, toolUseId }) });
|
|
145
151
|
}
|
|
146
152
|
|
|
153
|
+
function matchesStoredSummary(value, record) {
|
|
154
|
+
const summary = typeof value === 'string' ? JSON.parse(value) : value;
|
|
155
|
+
const marker = summary?.osuite_native_call;
|
|
156
|
+
return marker?.schema_version === CALL_SCHEMA && marker.operation_digest === sha256(record.operationId)
|
|
157
|
+
&& marker.input_digest === record.inputDigest && marker.binding_digest === record.bindingDigest
|
|
158
|
+
&& (!record.recovery || canonicalJson(summary.osuite_native_recovery) === canonicalJson(record.recovery));
|
|
159
|
+
}
|
|
160
|
+
|
|
147
161
|
export function matchesStoredAction(payload, record, config) {
|
|
148
162
|
try {
|
|
149
163
|
const action = payload?.action || payload;
|
|
150
|
-
const summary = typeof action?.input_summary === 'string' ? JSON.parse(action.input_summary) : action?.input_summary;
|
|
151
|
-
const marker = summary?.osuite_native_call;
|
|
152
164
|
const envelope = action?.action_envelope;
|
|
165
|
+
// Studio persists the signed call marker in both summaries, not a direct
|
|
166
|
+
// tool_input_digest column. An optional echo must agree; it cannot replace
|
|
167
|
+
// either mandatory v1 marker or select a less strict contract profile.
|
|
153
168
|
return action?.action_id === record.actionId && action.agent_id === config.agentId
|
|
154
169
|
&& action.org_id === config.orgId && action.verified === true
|
|
170
|
+
&& (!Object.hasOwn(action, 'tool_input_digest') || action.tool_input_digest === record.inputDigest)
|
|
155
171
|
&& (!payload.action_id || payload.action_id === record.actionId)
|
|
156
|
-
&& envelope?.
|
|
157
|
-
&&
|
|
158
|
-
&&
|
|
172
|
+
&& envelope?.schema_version === 'osuite.action_envelope.v1'
|
|
173
|
+
&& envelope.action_id === record.actionId && envelope.org_id === config.orgId && envelope.agent_id === config.agentId
|
|
174
|
+
&& envelope.runtime_session_id === record.sessionId && envelope.tool_use_id === record.toolUseId
|
|
175
|
+
&& (!Object.hasOwn(envelope, 'tool_input_digest') || envelope.tool_input_digest === record.inputDigest)
|
|
176
|
+
&& matchesStoredSummary(action.input_summary, record) && matchesStoredSummary(envelope.input_summary, record);
|
|
159
177
|
} catch { return false; }
|
|
160
178
|
}
|
|
161
179
|
|
|
@@ -6,6 +6,7 @@ import { cavaFingerprint } from '../runtime/admission.mjs';
|
|
|
6
6
|
import { OperationJournal } from './journal.mjs';
|
|
7
7
|
import { createStudioAuthority } from './authority.mjs';
|
|
8
8
|
import { GovernedToolError, jsonSnapshot, makeInvocation, publicStatus, reject, scopeFor } from './contract.mjs';
|
|
9
|
+
import { recoveryAdapter, recoveryScope, makeRecoveryInvocation, observeEvidence, validateEvidence, checkRecoveryAuthority } from './recovery.mjs';
|
|
9
10
|
|
|
10
11
|
const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
|
|
11
12
|
function runOptions(options) {
|
|
@@ -46,7 +47,8 @@ function registrySnapshot(bindings) {
|
|
|
46
47
|
if (!Object.hasOwn(fields.revision || {}, 'value') || !Object.hasOwn(fields.describe || {}, 'value')
|
|
47
48
|
|| !safeId(fields.revision.value) || fields.revision.value.length > 128
|
|
48
49
|
|| typeof fields.describe.value !== 'function' || types.isProxy(fields.describe.value)) reject('INVALID_MAPPING');
|
|
49
|
-
Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value,
|
|
50
|
+
Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value,
|
|
51
|
+
describe: fields.describe.value, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
|
|
50
52
|
}
|
|
51
53
|
return Object.freeze(result);
|
|
52
54
|
}
|
|
@@ -71,125 +73,202 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
71
73
|
let closed = false, inFlight = 0;
|
|
72
74
|
const local = operationId => journal.get(scope, operationId);
|
|
73
75
|
const status = record => publicStatus(record, config.baseUrl);
|
|
76
|
+
const recoveryStatus = operationId => {
|
|
77
|
+
const child = journal.get(recoveryScope(scope), operationId);
|
|
78
|
+
return child ? Object.freeze({ ...status(child), evidenceDigest: child.errorCode?.startsWith('recovery_')
|
|
79
|
+
? child.errorCode.slice('recovery_'.length) : null }) : null;
|
|
80
|
+
};
|
|
81
|
+
const combinedStatus = operationId => {
|
|
82
|
+
const parent = status(local(operationId)), recoveryAttempt = recoveryStatus(operationId);
|
|
83
|
+
return Object.freeze({ ...(recoveryAttempt || parent), parent, recoveryAttempt });
|
|
84
|
+
};
|
|
74
85
|
function stopForState(record) {
|
|
75
86
|
const codes = { completed: 'ALREADY_COMPLETED', denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' };
|
|
76
87
|
if (codes[record.state]) reject(codes[record.state], status(record));
|
|
77
88
|
if (!['prepared', 'held', 'requesting', 'uncertain_request'].includes(record.state)) reject('OUTCOME_UNKNOWN', status(record));
|
|
78
89
|
}
|
|
79
90
|
function transitionHeld(record, next, owner) {
|
|
80
|
-
if (!journal.claim(scope, record.operationId, ['held'], 'redeeming', owner)
|
|
81
|
-
|| !journal.settle(scope, record.operationId, owner, 'redeeming', next)) reject('OPERATION_BUSY', status(
|
|
91
|
+
if (!journal.claim(record.scope, record.operationId, ['held'], 'redeeming', owner)
|
|
92
|
+
|| !journal.settle(record.scope, record.operationId, owner, 'redeeming', next)) reject('OPERATION_BUSY', status(journal.get(record.scope, record.operationId)));
|
|
82
93
|
}
|
|
83
94
|
|
|
84
|
-
|
|
85
|
-
|
|
95
|
+
async function perform(invocation, execute, { waitMs, signal, aborted }, recovery = null) {
|
|
96
|
+
const { scope, operationId } = invocation.record;
|
|
97
|
+
const local = operationId => {
|
|
98
|
+
const record = journal.get(scope, operationId);
|
|
99
|
+
return record && invocation.recovery ? { ...record, recovery: invocation.recovery } : record;
|
|
100
|
+
};
|
|
101
|
+
if (aborted()) reject('ABORTED');
|
|
102
|
+
const started = performance.now(), deadline = started + waitMs, owner = randomUUID();
|
|
103
|
+
let record = journal.prepare(invocation.record);
|
|
104
|
+
const waiting = () => reject('AWAITING_APPROVAL', { ...status(local(operationId)), elapsedMs: Math.round(performance.now() - started) });
|
|
105
|
+
while (true) {
|
|
106
|
+
record = local(operationId); stopForState(record);
|
|
107
|
+
if (recovery && !['prepared', 'held'].includes(record.state)) reject('OUTCOME_UNKNOWN', status(record));
|
|
86
108
|
if (closed) reject('CLOSED');
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
if (aborted()) reject('ABORTED', status(record));
|
|
100
|
-
if (record.state !== 'prepared') {
|
|
101
|
-
const observed = await authority.read(record);
|
|
102
|
-
if (!observed.available) reject(record.state !== 'held' ? 'OUTCOME_UNKNOWN'
|
|
103
|
-
: observed.mismatch ? 'BINDING_MISMATCH' : 'CURRENT_AUTHORITY_UNAVAILABLE', status(record));
|
|
104
|
-
const action = observed.action;
|
|
105
|
-
if (['requesting', 'uncertain_request'].includes(record.state)) {
|
|
106
|
-
if (action.status !== 'pending_approval' || action.approval_redeemed_at != null || action.timestamp_end != null) reject('OUTCOME_UNKNOWN', status(record));
|
|
107
|
-
const fingerprint = cavaFingerprint(observed.body);
|
|
108
|
-
if (!fingerprint) reject('OUTCOME_UNKNOWN', status(record));
|
|
109
|
-
if (!journal.recoverHeld(scope, operationId, fingerprint)) reject('OPERATION_BUSY', status(local(operationId)));
|
|
110
|
-
record = local(operationId);
|
|
111
|
-
}
|
|
112
|
-
if (!record.fingerprint || record.fingerprint !== cavaFingerprint(observed.body)) reject('BINDING_MISMATCH', status(record));
|
|
113
|
-
if (action.status === 'pending_approval') {
|
|
114
|
-
if (performance.now() >= deadline) waiting();
|
|
115
|
-
try { await delay(Math.min(200, deadline - performance.now()), undefined, { signal }); }
|
|
116
|
-
catch { reject('ABORTED', status(record)); }
|
|
117
|
-
continue;
|
|
118
|
-
}
|
|
119
|
-
if (['blocked', 'denied', 'expired', 'cancelled'].includes(action.status)
|
|
120
|
-
|| ['denied', 'expired', 'cancelled'].includes(observed.body.approval?.state)) {
|
|
121
|
-
const state = action.status === 'expired' || observed.body.approval?.state === 'expired' ? 'expired'
|
|
122
|
-
: action.status === 'cancelled' ? 'cancelled' : 'denied';
|
|
123
|
-
transitionHeld(record, state, owner); stopForState(local(operationId));
|
|
124
|
-
}
|
|
125
|
-
if (action.status !== 'running' || action.timestamp_end != null || action.approval_redeemed_at != null
|
|
126
|
-
|| !action.approved_by || !action.approved_at) reject('OUTCOME_UNKNOWN', status(record));
|
|
109
|
+
if (aborted()) reject('ABORTED', status(record));
|
|
110
|
+
if (record.state !== 'prepared') {
|
|
111
|
+
const observed = await authority.read(record);
|
|
112
|
+
if (!observed.available) reject(record.state !== 'held' ? 'OUTCOME_UNKNOWN'
|
|
113
|
+
: observed.mismatch ? 'BINDING_MISMATCH' : 'CURRENT_AUTHORITY_UNAVAILABLE', status(record));
|
|
114
|
+
const action = observed.action;
|
|
115
|
+
if (['requesting', 'uncertain_request'].includes(record.state)) {
|
|
116
|
+
if (action.status !== 'pending_approval' || action.approval_redeemed_at != null || action.timestamp_end != null) reject('OUTCOME_UNKNOWN', status(record));
|
|
117
|
+
const fingerprint = cavaFingerprint(observed.body);
|
|
118
|
+
if (!fingerprint) reject('OUTCOME_UNKNOWN', status(record));
|
|
119
|
+
if (!journal.recoverHeld(scope, operationId, fingerprint)) reject('OPERATION_BUSY', status(local(operationId)));
|
|
120
|
+
record = local(operationId);
|
|
127
121
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
reject('
|
|
122
|
+
if (!record.fingerprint || record.fingerprint !== cavaFingerprint(observed.body)) reject('BINDING_MISMATCH', status(record));
|
|
123
|
+
if (action.status === 'pending_approval') {
|
|
124
|
+
if (performance.now() >= deadline) waiting();
|
|
125
|
+
try { await delay(Math.min(200, deadline - performance.now()), undefined, { signal }); }
|
|
126
|
+
catch { reject('ABORTED', status(record)); }
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (['blocked', 'denied', 'expired', 'cancelled'].includes(action.status)
|
|
130
|
+
|| ['denied', 'expired', 'cancelled'].includes(observed.body.approval?.state)) {
|
|
131
|
+
const state = action.status === 'expired' || observed.body.approval?.state === 'expired' ? 'expired'
|
|
132
|
+
: action.status === 'cancelled' ? 'cancelled' : 'denied';
|
|
133
|
+
transitionHeld(record, state, owner); stopForState(local(operationId));
|
|
133
134
|
}
|
|
134
|
-
if (
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
135
|
+
if (action.status !== 'running' || action.timestamp_end != null || action.approval_redeemed_at != null
|
|
136
|
+
|| !action.approved_by || !action.approved_at) reject('OUTCOME_UNKNOWN', status(record));
|
|
137
|
+
}
|
|
138
|
+
let admitted;
|
|
139
|
+
try { admitted = await authority.admit(invocation, journal, owner, aborted); }
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)));
|
|
142
|
+
reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
143
|
+
}
|
|
144
|
+
if (!admitted) { if (performance.now() >= deadline) waiting(); continue; }
|
|
145
|
+
let dispatchPatch = {};
|
|
146
|
+
if (recovery) {
|
|
147
|
+
try { dispatchPatch = await recovery.beforeDispatch(local(operationId), admitted); }
|
|
148
|
+
catch (error) {
|
|
138
149
|
journal.settle(scope, operationId, owner, admitted.phase,
|
|
139
150
|
admitted.phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
|
|
140
|
-
|
|
141
|
-
}
|
|
142
|
-
if (!journal.settle(scope, operationId, owner, admitted.phase, 'dispatching')) reject('OPERATION_BUSY', status(local(operationId)));
|
|
143
|
-
// Durable local I/O can outlive the admission, even without an await.
|
|
144
|
-
if (aborted() || closed || performance.now() - admitted.receivedAt > 5000) {
|
|
145
|
-
try { journal.settle(scope, operationId, owner, 'dispatching', 'uncertain'); }
|
|
146
|
-
catch { /* The committed dispatch fence still forbids replay if cleanup cannot write. */ }
|
|
147
|
-
reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
|
|
151
|
+
throw error;
|
|
148
152
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
153
|
+
}
|
|
154
|
+
// No await or user observer between this last check, the durable fence,
|
|
155
|
+
// and invoking the original tool. This is not resource-side atomicity.
|
|
156
|
+
const grantExpiry = admitted.phase === 'redeeming' ? Date.parse(admitted.response.action.approval_expires_at) : Infinity;
|
|
157
|
+
const ruleExpiry = admitted.ruleExpiresAt == null ? Infinity : Date.parse(admitted.ruleExpiresAt);
|
|
158
|
+
const current = () => performance.now() < admitted.dispatchDeadline && Date.now() < Math.min(grantExpiry, ruleExpiry)
|
|
159
|
+
&& (!recovery || recovery.fresh());
|
|
160
|
+
if (aborted() || closed || !current()) {
|
|
161
|
+
journal.settle(scope, operationId, owner, admitted.phase,
|
|
162
|
+
admitted.phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
|
|
163
|
+
reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
|
|
164
|
+
}
|
|
165
|
+
if (!journal.settle(scope, operationId, owner, admitted.phase, 'dispatching', dispatchPatch)) reject('OPERATION_BUSY', status(local(operationId)));
|
|
166
|
+
// Durable local I/O can outlive the admission, even without an await.
|
|
167
|
+
if (aborted() || closed || !current()) {
|
|
168
|
+
try { journal.settle(scope, operationId, owner, 'dispatching', 'uncertain'); }
|
|
169
|
+
catch { /* The committed dispatch fence still forbids replay if cleanup cannot write. */ }
|
|
170
|
+
reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
|
|
171
|
+
}
|
|
172
|
+
let result, resultDigest = null, state = 'completed', thrown = false;
|
|
173
|
+
try { result = await execute(invocation.params); }
|
|
174
|
+
catch { thrown = true; state = 'uncertain'; }
|
|
175
|
+
if (!thrown) {
|
|
176
|
+
if (result !== null && typeof result === 'object') {
|
|
177
|
+
if (types.isProxy(result)) state = 'uncertain';
|
|
178
|
+
else {
|
|
179
|
+
const errorFlag = Object.getOwnPropertyDescriptor(result, 'isError');
|
|
180
|
+
if (errorFlag && (!Object.hasOwn(errorFlag, 'value') || errorFlag.value !== false)) state = 'uncertain';
|
|
159
181
|
}
|
|
160
|
-
try {
|
|
161
|
-
const value = jsonSnapshot(result);
|
|
162
|
-
resultDigest = sha256(canonicalJson(value));
|
|
163
|
-
if (value?.isError === true) state = 'uncertain';
|
|
164
|
-
} catch { /* Opaque native returns are not serialized or independently verified. */ }
|
|
165
182
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
catch { /*
|
|
171
|
-
if (thrown) reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
172
|
-
return result;
|
|
173
|
-
}
|
|
174
|
-
} catch (error) { publicError(error); }
|
|
175
|
-
finally {
|
|
176
|
-
inFlight--;
|
|
177
|
-
if (closed && inFlight === 0) journal.close();
|
|
183
|
+
try {
|
|
184
|
+
const value = jsonSnapshot(result);
|
|
185
|
+
resultDigest = sha256(canonicalJson(value));
|
|
186
|
+
if (value?.isError === true) state = 'uncertain';
|
|
187
|
+
} catch { if (recovery) state = 'uncertain'; /* Recovery cannot claim success from opaque output. */ }
|
|
178
188
|
}
|
|
189
|
+
if (!journal.settle(scope, operationId, owner, 'dispatching', state, { resultDigest, reportState: 'uncertain' })) reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
190
|
+
let confirmed = false;
|
|
191
|
+
try { confirmed = await authority.report(local(operationId), state, resultDigest); } catch { /* Keep the observed native outcome. */ }
|
|
192
|
+
try { if (confirmed) journal.settle(scope, operationId, owner, state, state, { reportState: 'confirmed' }); }
|
|
193
|
+
catch { /* Reporting bookkeeping cannot hide a durably observed native return. */ }
|
|
194
|
+
if (thrown || (recovery && state !== 'completed')) reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function work(fn) {
|
|
200
|
+
if (closed) reject('CLOSED');
|
|
201
|
+
inFlight++;
|
|
202
|
+
try { return await fn(); } catch (error) { publicError(error); }
|
|
203
|
+
finally {
|
|
204
|
+
inFlight--;
|
|
205
|
+
if (closed && inFlight === 0) journal.close();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return Object.freeze({
|
|
210
|
+
async run(operationId, params, execute, options = {}) {
|
|
211
|
+
return work(() => {
|
|
212
|
+
const invocation = makeInvocation({ config, namespace, bindings, operationId, params });
|
|
213
|
+
if (typeof execute !== 'function' || types.isProxy(execute)) reject('INVALID_EXECUTOR');
|
|
214
|
+
return perform(invocation, execute, runOptions(options));
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
async recover(operationId, params, options = {}) {
|
|
218
|
+
return work(async () => {
|
|
219
|
+
const parent = makeInvocation({ config, namespace, bindings, operationId, params });
|
|
220
|
+
const settings = runOptions(options);
|
|
221
|
+
if (settings.aborted()) reject('ABORTED');
|
|
222
|
+
const adapter = bindings[parent.params.name].recovery;
|
|
223
|
+
const record = journal.getBound(parent.record);
|
|
224
|
+
if (!adapter) reject('RECOVERY_UNSUPPORTED', status(record));
|
|
225
|
+
if (!record) reject('RECOVERY_UNAVAILABLE');
|
|
226
|
+
if (record.state !== 'uncertain') { stopForState(record); reject('RECOVERY_UNAVAILABLE', status(record)); }
|
|
227
|
+
const { invocation, request } = makeRecoveryInvocation(parent, adapter);
|
|
228
|
+
try {
|
|
229
|
+
const child = journal.get(invocation.record.scope, operationId);
|
|
230
|
+
if (child) {
|
|
231
|
+
journal.prepare(invocation.record);
|
|
232
|
+
stopForState(child);
|
|
233
|
+
if (!['prepared', 'held'].includes(child.state)) reject('OUTCOME_UNKNOWN');
|
|
234
|
+
}
|
|
235
|
+
await checkRecoveryAuthority(authority, record);
|
|
236
|
+
const initial = await observeEvidence(adapter, request);
|
|
237
|
+
let evidence, authorityExpiresAt = Infinity;
|
|
238
|
+
const recovery = {
|
|
239
|
+
async beforeDispatch(child, admitted) {
|
|
240
|
+
evidence = await observeEvidence(adapter, request);
|
|
241
|
+
await checkRecoveryAuthority(authority, local(operationId));
|
|
242
|
+
authorityExpiresAt = await checkRecoveryAuthority(authority, child, admitted);
|
|
243
|
+
return { errorCode: `recovery_${sha256(canonicalJson({ initial, revalidated: evidence }))}` };
|
|
244
|
+
},
|
|
245
|
+
fresh() {
|
|
246
|
+
try { validateEvidence(evidence, request.binding); return Date.now() < authorityExpiresAt; } catch { return false; }
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
return await perform(invocation, native => adapter.execute(native,
|
|
250
|
+
Object.freeze({ binding: request.binding, evidence })), settings, recovery);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, combinedStatus(operationId));
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
});
|
|
179
256
|
},
|
|
180
257
|
async status(operationId) {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
258
|
+
return work(async () => {
|
|
259
|
+
if (!safeId(operationId) || operationId.length > 128) reject('INVALID_OPERATION_ID');
|
|
260
|
+
const record = local(operationId);
|
|
261
|
+
if (!record) return null;
|
|
262
|
+
const observed = await authority.read(record);
|
|
263
|
+
let failureCode = observed.mismatch ? 'BINDING_MISMATCH' : observed.available ? null : 'CURRENT_AUTHORITY_UNAVAILABLE';
|
|
264
|
+
// Refine held-call guidance without changing durable execution state.
|
|
265
|
+
if (!failureCode && record.state === 'held'
|
|
266
|
+
&& (['blocked', 'denied', 'expired', 'cancelled'].includes(observed.action.status)
|
|
267
|
+
|| ['denied', 'expired', 'cancelled'].includes(observed.body?.approval?.state))) failureCode = 'POLICY_DENIED';
|
|
268
|
+
const attempt = recoveryStatus(operationId);
|
|
269
|
+
return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}), remote: Object.freeze({ available: observed.available,
|
|
270
|
+
status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
|
|
271
|
+
});
|
|
193
272
|
},
|
|
194
273
|
close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
|
|
195
274
|
});
|
|
@@ -333,6 +333,12 @@ export class OperationJournal {
|
|
|
333
333
|
return this.#db.prepare('SELECT * FROM operations WHERE scope=? AND operation_id=?').get(scope, operationId);
|
|
334
334
|
}
|
|
335
335
|
|
|
336
|
+
#boundRow(value) {
|
|
337
|
+
const row = this.#read(value.scope, value.operationId);
|
|
338
|
+
if (row && Object.entries(FIELDS).some(([field, column]) => value[field] !== row[column])) fail('CONFLICT');
|
|
339
|
+
return row;
|
|
340
|
+
}
|
|
341
|
+
|
|
336
342
|
#row(row) {
|
|
337
343
|
if (!row) return null;
|
|
338
344
|
return Object.freeze({
|
|
@@ -353,11 +359,8 @@ export class OperationJournal {
|
|
|
353
359
|
return this.#run(() => {
|
|
354
360
|
const value = validateRecord(record);
|
|
355
361
|
return this.#transaction(() => {
|
|
356
|
-
const prior = this.#
|
|
357
|
-
if (prior)
|
|
358
|
-
if (Object.entries(FIELDS).some(([field, column]) => value[field] !== prior[column])) fail('CONFLICT');
|
|
359
|
-
return this.#row(prior);
|
|
360
|
-
}
|
|
362
|
+
const prior = this.#boundRow(value);
|
|
363
|
+
if (prior) return this.#row(prior);
|
|
361
364
|
if (this.#db.prepare('SELECT count(*) AS n FROM operations').get().n >= this.#maxOperations) fail('JOURNAL_CAPACITY');
|
|
362
365
|
const now = Date.now();
|
|
363
366
|
this.#db.prepare(`INSERT INTO operations(scope,operation_id,input_digest,context_digest,binding_digest,
|
|
@@ -378,6 +381,10 @@ export class OperationJournal {
|
|
|
378
381
|
});
|
|
379
382
|
}
|
|
380
383
|
|
|
384
|
+
getBound(record) {
|
|
385
|
+
return this.#run(() => this.#row(this.#boundRow(validateRecord(record))));
|
|
386
|
+
}
|
|
387
|
+
|
|
381
388
|
claim(scope, operationId, fromStates, nextState, owner) {
|
|
382
389
|
return this.#run(() => {
|
|
383
390
|
identity(scope, operationId);
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { types } from 'node:util';
|
|
2
|
+
import { canonicalJson, safeId, sha256 } from '../runtime/protocol.mjs';
|
|
3
|
+
import { cavaFingerprint } from '../runtime/admission.mjs';
|
|
4
|
+
import { jsonSnapshot, reject } from './contract.mjs';
|
|
5
|
+
|
|
6
|
+
const SCHEMA = 'osuite.native_recovery.v1';
|
|
7
|
+
const EVIDENCE_SCHEMA = 'osuite.native_recovery_evidence.v1';
|
|
8
|
+
const CONTRACTS = ['settled-absence', 'same-id-idempotent'];
|
|
9
|
+
const MAX_AGE_MS = 5000;
|
|
10
|
+
|
|
11
|
+
export function recoveryAdapter(descriptor) {
|
|
12
|
+
if (!descriptor) return undefined;
|
|
13
|
+
if (!Object.hasOwn(descriptor, 'value')) reject('INVALID_MAPPING');
|
|
14
|
+
const input = descriptor.value;
|
|
15
|
+
if (!input || typeof input !== 'object' || types.isProxy(input)
|
|
16
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(input))) reject('INVALID_MAPPING');
|
|
17
|
+
const fields = Object.getOwnPropertyDescriptors(input);
|
|
18
|
+
const keys = ['revision', 'resourceId', 'contract', 'observe', 'execute'];
|
|
19
|
+
if (Reflect.ownKeys(fields).length !== keys.length || Reflect.ownKeys(fields).some(key => !keys.includes(key)
|
|
20
|
+
|| !Object.hasOwn(fields[key], 'value') || !fields[key].enumerable)) reject('INVALID_MAPPING');
|
|
21
|
+
const value = Object.fromEntries(keys.map(key => [key, fields[key]?.value]));
|
|
22
|
+
if (![value.revision, value.resourceId].every(id => safeId(id) && id.length <= 128)
|
|
23
|
+
|| !CONTRACTS.includes(value.contract)
|
|
24
|
+
|| ![value.observe, value.execute].every(fn => typeof fn === 'function' && !types.isProxy(fn))) reject('INVALID_MAPPING');
|
|
25
|
+
return Object.freeze(value);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// A separate, deterministic scope keeps the parent permanently fenced, even in
|
|
29
|
+
// old SDKs. No caller can select another attempt or replace this child's grant.
|
|
30
|
+
export const recoveryScope = scope => sha256(canonicalJson([SCHEMA, scope]));
|
|
31
|
+
|
|
32
|
+
export function makeRecoveryInvocation(parent, adapter) {
|
|
33
|
+
const original = parent.record, scope = recoveryScope(original.scope);
|
|
34
|
+
const identity = sha256(canonicalJson([scope, original.operationId]));
|
|
35
|
+
const actionId = `act_${identity}`, sessionId = `sess_${identity}`, toolUseId = `tool_${identity}`;
|
|
36
|
+
const binding = jsonSnapshot({ operationId: original.operationId, scope: original.scope,
|
|
37
|
+
inputDigest: original.inputDigest, bindingDigest: original.bindingDigest, actionId: original.actionId,
|
|
38
|
+
resourceId: adapter.resourceId, adapterRevision: adapter.revision, contract: adapter.contract });
|
|
39
|
+
const linkage = jsonSnapshot({ schema_version: SCHEMA, parent_action_id: original.actionId,
|
|
40
|
+
parent_scope: original.scope, operation_digest: sha256(original.operationId), input_digest: original.inputDigest,
|
|
41
|
+
binding_digest: original.bindingDigest, adapter_revision: adapter.revision,
|
|
42
|
+
resource_id: adapter.resourceId, contract: adapter.contract });
|
|
43
|
+
const bindingDigest = sha256(canonicalJson(linkage));
|
|
44
|
+
const marker = { ...parent.marker, binding_digest: bindingDigest };
|
|
45
|
+
const summary = { ...JSON.parse(parent.context.input_summary), osuite_native_call: marker, osuite_native_recovery: linkage };
|
|
46
|
+
const inputSummary = JSON.stringify(summary);
|
|
47
|
+
if (inputSummary.length > 4000) reject('INVALID_MAPPING');
|
|
48
|
+
const context = jsonSnapshot({ ...parent.context, input_summary: inputSummary,
|
|
49
|
+
action_id: actionId, runtime_session_id: sessionId, tool_use_id: toolUseId });
|
|
50
|
+
const invocation = Object.freeze({ params: parent.params, context, marker, recovery: linkage,
|
|
51
|
+
record: Object.freeze({ ...original, scope, actionId, sessionId, toolUseId, bindingDigest,
|
|
52
|
+
contextDigest: sha256(canonicalJson(context)) }) });
|
|
53
|
+
return { invocation, request: Object.freeze({ params: parent.params, binding }) };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function validateEvidence(input, binding) {
|
|
57
|
+
let value;
|
|
58
|
+
try { value = jsonSnapshot(input, 8192); } catch { reject('RECOVERY_EVIDENCE_INVALID'); }
|
|
59
|
+
const fields = [...Object.keys(binding), 'schemaVersion', 'observedAt', 'expiresAt', 'settled', 'outcome', 'proof'];
|
|
60
|
+
const now = Date.now();
|
|
61
|
+
if (!value || Array.isArray(value) || typeof value !== 'object'
|
|
62
|
+
|| Object.keys(value).length !== fields.length || Object.keys(value).some(key => !fields.includes(key))
|
|
63
|
+
|| Object.entries(binding).some(([key, expected]) => value[key] !== expected)
|
|
64
|
+
|| value.schemaVersion !== EVIDENCE_SCHEMA || value.settled !== true
|
|
65
|
+
|| !Number.isSafeInteger(value.observedAt) || !Number.isSafeInteger(value.expiresAt)
|
|
66
|
+
|| value.observedAt < now - MAX_AGE_MS || value.observedAt > now
|
|
67
|
+
|| value.expiresAt <= now || value.expiresAt <= value.observedAt || value.expiresAt > value.observedAt + MAX_AGE_MS
|
|
68
|
+
|| !['absent', 'applied', 'unknown'].includes(value.outcome)
|
|
69
|
+
|| (binding.contract === 'settled-absence' && value.outcome !== 'absent')
|
|
70
|
+
|| !value.proof || Array.isArray(value.proof) || typeof value.proof !== 'object'
|
|
71
|
+
|| Object.keys(value.proof).length === 0) reject('RECOVERY_EVIDENCE_INVALID');
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function observeEvidence(adapter, request) {
|
|
76
|
+
let result;
|
|
77
|
+
try { result = await adapter.observe(request); } catch { reject('RECOVERY_EVIDENCE_INVALID'); }
|
|
78
|
+
return validateEvidence(result, request.binding);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function checkRecoveryAuthority(authority, record, admission = null) {
|
|
82
|
+
const observed = await authority.read(record);
|
|
83
|
+
if (!observed.available) reject(observed.mismatch ? 'BINDING_MISMATCH' : 'CURRENT_AUTHORITY_UNAVAILABLE');
|
|
84
|
+
const states = [observed.action.status, observed.body.approval?.state];
|
|
85
|
+
if (states.includes('cancelled')) reject('CANCELLED');
|
|
86
|
+
if (states.includes('expired')) reject('APPROVAL_EXPIRED');
|
|
87
|
+
if (states.some(state => ['denied', 'blocked'].includes(state))) reject('POLICY_DENIED');
|
|
88
|
+
const fingerprint = admission ? cavaFingerprint(admission.response) : record.fingerprint;
|
|
89
|
+
if (fingerprint && fingerprint !== cavaFingerprint(observed.body)) reject('BINDING_MISMATCH');
|
|
90
|
+
let expiresAt = Infinity;
|
|
91
|
+
if (admission) {
|
|
92
|
+
if (observed.action.status !== 'running' || observed.action.timestamp_end != null) reject('OUTCOME_UNKNOWN');
|
|
93
|
+
if (admission.ruleExpiresAt != null) {
|
|
94
|
+
expiresAt = Date.parse(admission.ruleExpiresAt);
|
|
95
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) reject('OUTCOME_UNKNOWN');
|
|
96
|
+
}
|
|
97
|
+
// A consumed child grant is not reusable authority: it must still match the
|
|
98
|
+
// fresh redemption we just observed, and must not expire before dispatch.
|
|
99
|
+
if (admission.phase === 'redeeming') {
|
|
100
|
+
const original = admission.response.action;
|
|
101
|
+
for (const key of ['approved_by', 'approved_at', 'approval_redeemed_at', 'approval_expires_at', 'approval_decision']) {
|
|
102
|
+
if (observed.action[key] !== original[key]) reject('OUTCOME_UNKNOWN');
|
|
103
|
+
}
|
|
104
|
+
expiresAt = Math.min(expiresAt, Date.parse(observed.action.approval_expires_at));
|
|
105
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) reject('APPROVAL_EXPIRED');
|
|
106
|
+
}
|
|
107
|
+
} else if (!['running', 'failed'].includes(observed.action.status)) reject('OUTCOME_UNKNOWN');
|
|
108
|
+
return expiresAt;
|
|
109
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "osuite",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.14.2",
|
|
4
4
|
"description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"governed-tools/*.mjs",
|
|
40
40
|
"governed-tools/examples/*.mjs",
|
|
41
41
|
"GOVERNED_TOOLS.md",
|
|
42
|
+
"GOVERNED_RECOVERY.md",
|
|
42
43
|
"controlled-transfers.mjs",
|
|
43
44
|
"controlled-transfers-stdio.mjs",
|
|
44
45
|
"controlled-transfers/*.mjs",
|
package/runtime/protocol.mjs
CHANGED
|
@@ -77,7 +77,10 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
|
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
const controller = new AbortController();
|
|
80
|
-
const
|
|
80
|
+
const totalMs = Math.max(1, Math.min(options.timeoutMs ?? timeoutMs, 30000));
|
|
81
|
+
const headMs = Math.max(1, Math.min(options.headersTimeoutMs ?? totalMs, totalMs));
|
|
82
|
+
const started = performance.now();
|
|
83
|
+
let timer = setTimeout(() => controller.abort(), headMs);
|
|
81
84
|
let status = 0;
|
|
82
85
|
try {
|
|
83
86
|
const response = await fetchImpl(baseUrl + endpoint, {
|
|
@@ -88,6 +91,16 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
|
|
|
88
91
|
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
|
89
92
|
});
|
|
90
93
|
status = response.status;
|
|
94
|
+
if (headMs < totalMs) {
|
|
95
|
+
const elapsed = performance.now() - started;
|
|
96
|
+
if (controller.signal.aborted || elapsed >= headMs) {
|
|
97
|
+
controller.abort();
|
|
98
|
+
return { ok: false, status, error: 'timeout' };
|
|
99
|
+
}
|
|
100
|
+
// A timely header buys only the remainder of the original total, never a fresh timeout per chunk.
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
timer = setTimeout(() => controller.abort(), Math.max(1, totalMs - elapsed));
|
|
103
|
+
}
|
|
91
104
|
if (status < 200 || status >= 300) {
|
|
92
105
|
await response.body?.cancel();
|
|
93
106
|
return { ok: false, status, error: 'http_error' };
|
|
@@ -110,6 +123,9 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
|
|
|
110
123
|
try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } catch {
|
|
111
124
|
return { ok: false, status, error: 'invalid_response' };
|
|
112
125
|
}
|
|
126
|
+
if (headMs < totalMs && (controller.signal.aborted || performance.now() - started >= totalMs)) {
|
|
127
|
+
return { ok: false, status, error: 'timeout' };
|
|
128
|
+
}
|
|
113
129
|
if (!isObject(parsed)) return { ok: false, status, error: 'invalid_response' };
|
|
114
130
|
return { ok: true, status, body: parsed };
|
|
115
131
|
} catch (error) {
|