@fungi.computer/approvals 0.2.2 → 0.2.4
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/README.md +32 -42
- package/dist/contract.d.ts +20 -0
- package/dist/contract.js +5 -0
- package/dist/index.d.ts +1 -1
- package/dist/ledger.d.ts +11 -45
- package/dist/ledger.js +41 -146
- package/docs/api/README.md +167 -164
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -62,28 +62,30 @@ policy-approved request inline through the authority recheck.
|
|
|
62
62
|
## Examples
|
|
63
63
|
|
|
64
64
|
The home example stages one pending write using native SQLite. The packed
|
|
65
|
-
consumer in `test/stranger/runtime.mjs` continues through a human answer
|
|
66
|
-
application
|
|
67
|
-
|
|
65
|
+
consumer in `test/stranger/runtime.mjs` continues through a human answer and
|
|
66
|
+
application. It observes one dispatch across sequential successful retries; it
|
|
67
|
+
is not a real Agent transport proof.
|
|
68
68
|
|
|
69
69
|
To integrate those steps, pass `answer` a freshly resolved human member and the
|
|
70
70
|
record's expected revision. Supply `apply` with an `ApprovalApplyHost`:
|
|
71
71
|
`recheck` reads the requester's current authority and fence, and `dispatch`
|
|
72
72
|
calls your existing operation door. Approval does not grant missing authority.
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
73
|
+
The result belongs to the call that asked: the host that staged the record waits
|
|
74
|
+
for the answer inside its own tool call, applies it there and returns the output
|
|
75
|
+
as that call's result. Nothing is sent as a message.
|
|
76
76
|
|
|
77
77
|
## Contract model
|
|
78
78
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
79
|
+
`submit` stages a write needing approval and returns a typed pending_approval
|
|
80
|
+
status with its recordId and description; the host keeps that tool call open
|
|
81
|
+
until the answer. A request staged with `expiresAt` (the waiting call's own
|
|
82
|
+
deadline) never outlives the call: `withdraw` expires an unclaimed record when
|
|
83
|
+
the call is cancelled or ends, and `withdrawWaiting` does so for every unclaimed
|
|
84
|
+
record at native boot. On approval the ledger durably claims, rechecks the exact
|
|
85
|
+
fence and requester's current Mycelium authority, dispatches the existing host
|
|
86
|
+
operation at most once, and stores applied/denied/outcome_unknown. Auto-approve
|
|
87
|
+
applies inline through the same record. No MuleTool.resume, Watchdog park/wake,
|
|
88
|
+
stored tool suspension, or unsafe execute replay belongs to this model.
|
|
87
89
|
|
|
88
90
|
The member-bound capability exposes approvals.list/get/answer/setAutoApprove.
|
|
89
91
|
Actors and live grants come from the host, never from request bodies. Reads are
|
|
@@ -93,9 +95,10 @@ requester authority over an operation.
|
|
|
93
95
|
Auto-approve matches a module (or all modules) and access class write/external,
|
|
94
96
|
optionally for one Agent. ON includes irreversible actions, still records the
|
|
95
97
|
decision, and never overrides revoked authority. Local and the solo Oyster owner
|
|
96
|
-
default ON; Teams default OFF. Only the Oyster owner answers on an Oyster.
|
|
97
|
-
|
|
98
|
-
|
|
98
|
+
default ON; Teams default OFF. Only the Oyster owner answers on an Oyster. A
|
|
99
|
+
request with no `expiresAt` expires after 24 hours (the Oyster home, whose host
|
|
100
|
+
applies approved records from its own work loop). A call-owned request expires
|
|
101
|
+
with its call. Expiry never approves.
|
|
99
102
|
|
|
100
103
|
## Current implementation boundary
|
|
101
104
|
|
|
@@ -108,31 +111,18 @@ bounded batches; the native host must call it only at boot, never during a live
|
|
|
108
111
|
dispatch.
|
|
109
112
|
|
|
110
113
|
ledger.capability({ actor, decision }) binds the four public methods. The host
|
|
111
|
-
must supply fresh member/operation facts on every call and actual durable
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
are never notification cargo. The host owns current recipient admission and safe
|
|
124
|
-
ordinary-message presentation of the result.
|
|
125
|
-
|
|
126
|
-
The consumer test uses the public Shiitake memory host with borrowed native
|
|
127
|
-
SQLite owners, loses an acknowledgement after session.send accepts, reopens both
|
|
128
|
-
databases and owners, and observes one new-message turn with the same command
|
|
129
|
-
identity. This is real Session/storage component proof, not a deployed home,
|
|
130
|
-
transport-loss drill or a full-host security law.
|
|
131
|
-
|
|
132
|
-
Host integration is still in progress: the native Team/Oyster compositions,
|
|
133
|
-
ordinary new-message handoff and configurable expiry are not yet wired. The
|
|
134
|
-
current store uses the 24-hour default. Store tests and the page/RPC consumer
|
|
135
|
-
fixture do not establish those production behaviors or the ten full-host laws.
|
|
114
|
+
must supply fresh member/operation facts on every call and actual durable apply
|
|
115
|
+
work after a decision; there is no success-shaped default hook. List reads are
|
|
116
|
+
bounded to at most 100 records with a continuation cursor. Request bodies cannot
|
|
117
|
+
select their actor. Policy is persisted by home and Agent/module/access family.
|
|
118
|
+
|
|
119
|
+
Private input bytes are never part of a result sent anywhere: a waiting call
|
|
120
|
+
receives the operation's own output or a typed refusal. The Local and Hub hosts
|
|
121
|
+
resolve the waiting call from their own answer hook; the ledger keeps one claim
|
|
122
|
+
and one effect attempt per record, so a duplicate waiter cannot dispatch twice.
|
|
123
|
+
|
|
124
|
+
Store tests and the page/RPC consumer fixture do not establish the production
|
|
125
|
+
behaviors of the hosts or the ten full-host laws.
|
|
136
126
|
|
|
137
127
|
## Host admission policy read
|
|
138
128
|
|
package/dist/contract.d.ts
CHANGED
|
@@ -20,6 +20,11 @@ export declare const ApprovalRequesterSchema: Schema.Struct<{
|
|
|
20
20
|
/** A renderer sees metadata and a byte digest, never the proposed input. */
|
|
21
21
|
export declare const ApprovalDescriptionSchema: Schema.Struct<{
|
|
22
22
|
readonly title: Schema.String;
|
|
23
|
+
/** Catalog-authored App copy, not identity or authorization. */
|
|
24
|
+
readonly app: Schema.optionalKey<Schema.Struct<{
|
|
25
|
+
readonly displayName: Schema.String;
|
|
26
|
+
readonly operationLabel: Schema.String;
|
|
27
|
+
}>>;
|
|
23
28
|
readonly inputBytes: Schema.Int;
|
|
24
29
|
readonly inputSha256: Schema.String;
|
|
25
30
|
}>;
|
|
@@ -29,6 +34,11 @@ export declare const PendingApprovalSchema: Schema.Struct<{
|
|
|
29
34
|
readonly recordId: Schema.String;
|
|
30
35
|
readonly description: Schema.Struct<{
|
|
31
36
|
readonly title: Schema.String;
|
|
37
|
+
/** Catalog-authored App copy, not identity or authorization. */
|
|
38
|
+
readonly app: Schema.optionalKey<Schema.Struct<{
|
|
39
|
+
readonly displayName: Schema.String;
|
|
40
|
+
readonly operationLabel: Schema.String;
|
|
41
|
+
}>>;
|
|
32
42
|
readonly inputBytes: Schema.Int;
|
|
33
43
|
readonly inputSha256: Schema.String;
|
|
34
44
|
}>;
|
|
@@ -70,6 +80,11 @@ export declare const ApprovalRecordSchema: Schema.Struct<{
|
|
|
70
80
|
readonly access: Schema.Literals<readonly ["write", "external"]>;
|
|
71
81
|
readonly description: Schema.Struct<{
|
|
72
82
|
readonly title: Schema.String;
|
|
83
|
+
/** Catalog-authored App copy, not identity or authorization. */
|
|
84
|
+
readonly app: Schema.optionalKey<Schema.Struct<{
|
|
85
|
+
readonly displayName: Schema.String;
|
|
86
|
+
readonly operationLabel: Schema.String;
|
|
87
|
+
}>>;
|
|
73
88
|
readonly inputBytes: Schema.Int;
|
|
74
89
|
readonly inputSha256: Schema.String;
|
|
75
90
|
}>;
|
|
@@ -110,6 +125,11 @@ export declare const ApprovalViewSchema: Schema.Struct<{
|
|
|
110
125
|
readonly access: Schema.Literals<readonly ["write", "external"]>;
|
|
111
126
|
readonly description: Schema.Struct<{
|
|
112
127
|
readonly title: Schema.String;
|
|
128
|
+
/** Catalog-authored App copy, not identity or authorization. */
|
|
129
|
+
readonly app: Schema.optionalKey<Schema.Struct<{
|
|
130
|
+
readonly displayName: Schema.String;
|
|
131
|
+
readonly operationLabel: Schema.String;
|
|
132
|
+
}>>;
|
|
113
133
|
readonly inputBytes: Schema.Int;
|
|
114
134
|
readonly inputSha256: Schema.String;
|
|
115
135
|
}>;
|
package/dist/contract.js
CHANGED
|
@@ -23,6 +23,11 @@ export const ApprovalRequesterSchema = Schema.Struct({
|
|
|
23
23
|
/** A renderer sees metadata and a byte digest, never the proposed input. */
|
|
24
24
|
export const ApprovalDescriptionSchema = Schema.Struct({
|
|
25
25
|
title: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)),
|
|
26
|
+
/** Catalog-authored App copy, not identity or authorization. */
|
|
27
|
+
app: Schema.optionalKey(Schema.Struct({
|
|
28
|
+
displayName: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(80)),
|
|
29
|
+
operationLabel: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1000)),
|
|
30
|
+
})),
|
|
26
31
|
inputBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
27
32
|
inputSha256: Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/)),
|
|
28
33
|
});
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export * from "./contract.js";
|
|
2
2
|
export { denialFeedbackOpening } from "./denial-message.js";
|
|
3
|
-
export { ApprovalLedger, ApprovalRefusalSchema, DEFAULT_APPROVAL_EXPIRY_MS, type AutoApproveQuery, type ApprovalHome, type ApprovalRequest, type ApprovalAnswerer, type ApprovalAdmission, type ApprovalRuleSetter, type ApprovalApplyHost, type ApprovalSubmitHost, type ApprovalDispatchCompletion, type ApprovalApplyResult,
|
|
3
|
+
export { ApprovalLedger, ApprovalRefusalSchema, DEFAULT_APPROVAL_EXPIRY_MS, type AutoApproveQuery, type ApprovalHome, type ApprovalRequest, type ApprovalAnswerer, type ApprovalAdmission, type ApprovalRuleSetter, type ApprovalApplyHost, type ApprovalSubmitHost, type ApprovalDispatchCompletion, type ApprovalApplyResult, } from "./ledger.js";
|
package/dist/ledger.d.ts
CHANGED
|
@@ -17,12 +17,16 @@ export type ApprovalRequest = Readonly<{
|
|
|
17
17
|
requester: ApprovalRecord["requester"];
|
|
18
18
|
module: string;
|
|
19
19
|
operation: string;
|
|
20
|
+
/** Display copy from the admitted App catalog; never inferred from IDs. */
|
|
21
|
+
app?: ApprovalRecord["description"]["app"];
|
|
20
22
|
access: ApprovalRecord["access"];
|
|
21
23
|
reversibility: ApprovalRecord["reversibility"];
|
|
22
24
|
authorityFence: string;
|
|
23
25
|
/** Persisted turn/tool identity and operation ordinal; never random on retry. */
|
|
24
26
|
idempotencyKey: string;
|
|
25
27
|
inputJson: string;
|
|
28
|
+
/** The waiting call's own deadline: the record never outlives the call that asked. */
|
|
29
|
+
expiresAt?: number;
|
|
26
30
|
/** Host-only containment escalation: a general auto-approve rule cannot bypass the sandbox. */
|
|
27
31
|
requireHumanApproval?: boolean;
|
|
28
32
|
/** Host-attested matching command-prefix policy; independent of the general auto-approve switch. */
|
|
@@ -86,29 +90,12 @@ export type ApprovalApplyHost = Readonly<{
|
|
|
86
90
|
export type ApprovalSubmitHost = ApprovalApplyHost & Readonly<{
|
|
87
91
|
evidence?: ApprovalEvidence;
|
|
88
92
|
}>;
|
|
89
|
-
/**
|
|
93
|
+
/** The result of applying one approved record. */
|
|
90
94
|
export type ApprovalApplyResult = Readonly<{
|
|
91
95
|
kind: "applied";
|
|
92
96
|
record: ApprovalRecord;
|
|
93
97
|
output: typeof Schema.Json.Type;
|
|
94
98
|
}> | ApprovalRefusal;
|
|
95
|
-
/** Deferred result cargo; stored request input is not a field on this port. */
|
|
96
|
-
export type ApprovalResultNotice = Readonly<{
|
|
97
|
-
deliveryId: string;
|
|
98
|
-
record: ApprovalRecord;
|
|
99
|
-
result: ApprovalApplyResult;
|
|
100
|
-
}>;
|
|
101
|
-
/** Ordinary new-message receipt, explicit no-delivery result, or typed refusal. */
|
|
102
|
-
export type ApprovalHandoffResult = Readonly<{
|
|
103
|
-
kind: "delivered";
|
|
104
|
-
commandId: string;
|
|
105
|
-
}> | Readonly<{
|
|
106
|
-
kind: "not-required";
|
|
107
|
-
}>
|
|
108
|
-
/** The home's attempt limit was reached; the decided record is kept. */
|
|
109
|
-
| Readonly<{
|
|
110
|
-
kind: "undeliverable";
|
|
111
|
-
}> | ApprovalRefusal;
|
|
112
99
|
/** The initial owner-controlled wait duration; passing the deadline never approves. */
|
|
113
100
|
export declare const DEFAULT_APPROVAL_EXPIRY_MS: number;
|
|
114
101
|
/** SQLite lifecycle beside Mycelium. Native owner transactions serialize every transition. */
|
|
@@ -121,16 +108,6 @@ export declare class ApprovalLedger {
|
|
|
121
108
|
now: () => number;
|
|
122
109
|
/** Host-private dispatch target, committed in the same SQLite transaction as the record. */
|
|
123
110
|
persistIntent?: (record: ApprovalRecord) => undefined;
|
|
124
|
-
/**
|
|
125
|
-
* Present when this home's wake sends result messages: its wake then
|
|
126
|
-
* covers undelivered results, and a failed send waits retryDelay(attempt)
|
|
127
|
-
* from the home's existing delivery policy before the next try. The
|
|
128
|
-
* attemptLimit-th failure makes the result undeliverable: no more wakes.
|
|
129
|
-
*/
|
|
130
|
-
resultDelivery?: Readonly<{
|
|
131
|
-
retryDelay: (attempt: number) => number;
|
|
132
|
-
attemptLimit: number;
|
|
133
|
-
}>;
|
|
134
111
|
}>);
|
|
135
112
|
/** Bound control surface; null identity means membership is gone, never an impersonated key. */
|
|
136
113
|
capability(host: Readonly<{
|
|
@@ -171,6 +148,10 @@ export declare class ApprovalLedger {
|
|
|
171
148
|
private canManagePolicy;
|
|
172
149
|
/** Pure policy selection: no record, claim, dispatch, grant widening or containment choice. */
|
|
173
150
|
selectAutoApprove(query: AutoApproveQuery): boolean;
|
|
151
|
+
/** Withdraw an unclaimed call; a claimed effect must retain its outcome record. */
|
|
152
|
+
withdraw(recordId: string): void;
|
|
153
|
+
/** Native boot only: a prior owner's waiting calls no longer exist. */
|
|
154
|
+
withdrawWaiting(): number;
|
|
174
155
|
/** Expire one bounded home-local quantum without a member read or an approval. */
|
|
175
156
|
expirePending(): void;
|
|
176
157
|
/** Earliest native wake for waiting or unfinished effects; no claim or dispatch. */
|
|
@@ -179,26 +160,11 @@ export declare class ApprovalLedger {
|
|
|
179
160
|
pendingApplications(): readonly string[];
|
|
180
161
|
/** Host-private display recovery; never exposed by the member-bound capability. */
|
|
181
162
|
readInput(recordId: string): typeof Schema.Json.Type | null;
|
|
182
|
-
/** Bounded, home-local terminal notices for the native owner's work loop. */
|
|
183
|
-
pendingHandoffs(): readonly string[];
|
|
184
163
|
/**
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
* The host must return the real Session acceptance, not a success-shaped placeholder.
|
|
188
|
-
*/
|
|
189
|
-
handoff(recordId: string, send: (notice: ApprovalResultNotice) => Promise<Readonly<{
|
|
190
|
-
commandId: string;
|
|
191
|
-
}>>): Promise<ApprovalHandoffResult>;
|
|
192
|
-
/**
|
|
193
|
-
* The home's work loop: only a durable approved record claims the existing
|
|
194
|
-
* host operation, and its result always reaches a waiting Agent as a message.
|
|
164
|
+
* Claim and apply one approved record exactly once. A waiting call applies
|
|
165
|
+
* its own record; the native owner's work loop applies the rest.
|
|
195
166
|
*/
|
|
196
167
|
apply(recordId: string, host: ApprovalApplyHost): Promise<ApprovalApplyResult>;
|
|
197
|
-
/**
|
|
198
|
-
* Apply the caller's own just-staged policy approval inside its live tool
|
|
199
|
-
* call; that call's result is the outcome, so no later message is owed.
|
|
200
|
-
*/
|
|
201
|
-
applyInline(recordId: string, host: ApprovalApplyHost): Promise<ApprovalApplyResult>;
|
|
202
168
|
private run;
|
|
203
169
|
private finishDenied;
|
|
204
170
|
/** Native host boot only: orphaned durable claims must never be redispatched. */
|
package/dist/ledger.js
CHANGED
|
@@ -11,12 +11,6 @@ const defaultAutoApprove = {
|
|
|
11
11
|
oyster: true,
|
|
12
12
|
local: true,
|
|
13
13
|
};
|
|
14
|
-
/** An unguessable recipient idempotency key; never part of any record view. */
|
|
15
|
-
function mintDeliveryId() {
|
|
16
|
-
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
17
|
-
return ("approval-result:" +
|
|
18
|
-
[...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""));
|
|
19
|
-
}
|
|
20
14
|
/** The initial owner-controlled wait duration; passing the deadline never approves. */
|
|
21
15
|
export const DEFAULT_APPROVAL_EXPIRY_MS = 24 * 60 * 60 * 1000;
|
|
22
16
|
const decodeRecord = Schema.decodeUnknownSync(Schema.fromJsonString(ApprovalRecordSchema), { onExcessProperty: "error" });
|
|
@@ -45,8 +39,6 @@ export class ApprovalLedger {
|
|
|
45
39
|
options.owner.sql.exec("CREATE TABLE IF NOT EXISTS approval_records (home_key TEXT NOT NULL, record_id TEXT NOT NULL, record_json TEXT NOT NULL, PRIMARY KEY (home_key, record_id))");
|
|
46
40
|
options.owner.sql.exec("CREATE INDEX IF NOT EXISTS approval_records_by_state ON approval_records (home_key, json_extract(record_json, '$.state'), record_id)");
|
|
47
41
|
options.owner.sql.exec("CREATE TABLE IF NOT EXISTS approval_payloads (home_key TEXT NOT NULL, record_id TEXT NOT NULL, input_json TEXT NOT NULL, output_json TEXT, PRIMARY KEY (home_key, record_id))");
|
|
48
|
-
options.owner.sql.exec("CREATE TABLE IF NOT EXISTS approval_handoffs (home_key TEXT NOT NULL, record_id TEXT NOT NULL, delivery_id TEXT NOT NULL, command_id TEXT, attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER, undeliverable_at INTEGER, PRIMARY KEY (home_key, record_id))");
|
|
49
|
-
options.owner.sql.exec("CREATE INDEX IF NOT EXISTS approval_handoffs_by_receipt ON approval_handoffs (home_key, command_id, record_id)");
|
|
50
42
|
}
|
|
51
43
|
/** Bound control surface; null identity means membership is gone, never an impersonated key. */
|
|
52
44
|
capability(host) {
|
|
@@ -150,7 +142,7 @@ export class ApprovalLedger {
|
|
|
150
142
|
// Only this call's own policy approval applies inline. Every other
|
|
151
143
|
// approved record is applied by the home's work loop, never by a retry.
|
|
152
144
|
if (staged.created && record.state === "approved")
|
|
153
|
-
return this.
|
|
145
|
+
return this.apply(record.recordId, host);
|
|
154
146
|
return this.outcome(record);
|
|
155
147
|
}
|
|
156
148
|
/** A retried request's current outcome, without claiming any work. */
|
|
@@ -166,7 +158,7 @@ export class ApprovalLedger {
|
|
|
166
158
|
description: record.description,
|
|
167
159
|
};
|
|
168
160
|
case "applied": {
|
|
169
|
-
// A human-approved result
|
|
161
|
+
// A human-approved result went to the call that waited for it.
|
|
170
162
|
if (record.by?.kind !== "policy")
|
|
171
163
|
return { kind: "refused", reason: "already-answered" };
|
|
172
164
|
const output = this.payload(record.recordId).output_json;
|
|
@@ -230,6 +222,11 @@ export class ApprovalLedger {
|
|
|
230
222
|
module: request.module,
|
|
231
223
|
access: request.access,
|
|
232
224
|
}));
|
|
225
|
+
const description = {
|
|
226
|
+
title: (request.module + "." + request.operation).slice(0, 512),
|
|
227
|
+
inputBytes: bytes.length,
|
|
228
|
+
inputSha256,
|
|
229
|
+
};
|
|
233
230
|
const record = Schema.decodeUnknownSync(ApprovalRecordSchema, {
|
|
234
231
|
onExcessProperty: "error",
|
|
235
232
|
})({
|
|
@@ -238,11 +235,9 @@ export class ApprovalLedger {
|
|
|
238
235
|
module: request.module,
|
|
239
236
|
operation: request.operation,
|
|
240
237
|
access: request.access,
|
|
241
|
-
description:
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
inputSha256,
|
|
245
|
-
},
|
|
238
|
+
description: request.app === undefined
|
|
239
|
+
? description
|
|
240
|
+
: { ...description, app: request.app },
|
|
246
241
|
...attachments,
|
|
247
242
|
authorityFence: request.authorityFence,
|
|
248
243
|
reversibility: request.reversibility,
|
|
@@ -250,19 +245,13 @@ export class ApprovalLedger {
|
|
|
250
245
|
by: autoApproved ? { kind: "policy" } : null,
|
|
251
246
|
reason: null,
|
|
252
247
|
requestedAt: now,
|
|
253
|
-
expiresAt: now + DEFAULT_APPROVAL_EXPIRY_MS,
|
|
248
|
+
expiresAt: request.expiresAt ?? now + DEFAULT_APPROVAL_EXPIRY_MS,
|
|
254
249
|
updatedAt: now,
|
|
255
250
|
revision: 1,
|
|
256
251
|
});
|
|
257
252
|
this.options.persistIntent?.(record);
|
|
258
253
|
this.options.owner.sql.exec("INSERT INTO approval_records (home_key, record_id, record_json) VALUES (?, ?, ?)", this.homeKey, recordId, encodeRecord(record));
|
|
259
254
|
this.options.owner.sql.exec("INSERT INTO approval_payloads (home_key, record_id, input_json) VALUES (?, ?, ?)", this.homeKey, recordId, request.inputJson);
|
|
260
|
-
// Only a waiting, host-attested Agent Session needs an ordinary later message.
|
|
261
|
-
// Policy-approved inline calls must not manufacture another Agent turn.
|
|
262
|
-
if (!autoApproved &&
|
|
263
|
-
record.requester.agentId !== null &&
|
|
264
|
-
record.requester.sessionId !== null)
|
|
265
|
-
this.options.owner.sql.exec("INSERT INTO approval_handoffs (home_key, record_id, delivery_id) VALUES (?, ?, ?)", this.homeKey, recordId, mintDeliveryId());
|
|
266
255
|
return { kind: "record", record, created: true };
|
|
267
256
|
});
|
|
268
257
|
}
|
|
@@ -338,6 +327,31 @@ export class ApprovalLedger {
|
|
|
338
327
|
return defaultAutoApprove[this.options.home.kind];
|
|
339
328
|
return (Schema.decodeUnknownSync(Schema.Struct({ enabled: Schema.Literals([0, 1]) }))(raw).enabled === 1);
|
|
340
329
|
}
|
|
330
|
+
/** Withdraw an unclaimed call; a claimed effect must retain its outcome record. */
|
|
331
|
+
withdraw(recordId) {
|
|
332
|
+
this.options.owner.transactionSync(() => {
|
|
333
|
+
const record = this.get(recordId);
|
|
334
|
+
if (record?.state !== "pending" && record?.state !== "approved")
|
|
335
|
+
return;
|
|
336
|
+
this.save({
|
|
337
|
+
...record,
|
|
338
|
+
state: "expired",
|
|
339
|
+
reason: "expired",
|
|
340
|
+
updatedAt: this.options.now(),
|
|
341
|
+
revision: record.revision + 1,
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
/** Native boot only: a prior owner's waiting calls no longer exist. */
|
|
346
|
+
withdrawWaiting() {
|
|
347
|
+
const decode = Schema.decodeUnknownSync(Schema.Struct({ record_id: ApprovalRecordSchema.fields.recordId }));
|
|
348
|
+
const rows = this.options.owner.sql
|
|
349
|
+
.exec("SELECT record_id FROM approval_records WHERE home_key = ? AND json_extract(record_json, '$.state') IN ('pending', 'approved') ORDER BY record_id LIMIT 100", this.homeKey)
|
|
350
|
+
.toArray();
|
|
351
|
+
for (const row of rows)
|
|
352
|
+
this.withdraw(decode(row).record_id);
|
|
353
|
+
return rows.length;
|
|
354
|
+
}
|
|
341
355
|
/** Expire one bounded home-local quantum without a member read or an approval. */
|
|
342
356
|
expirePending() {
|
|
343
357
|
const decode = Schema.decodeUnknownSync(Schema.Struct({
|
|
@@ -358,17 +372,7 @@ export class ApprovalLedger {
|
|
|
358
372
|
wake_at: Schema.NullOr(ApprovalRecordSchema.fields.expiresAt),
|
|
359
373
|
}));
|
|
360
374
|
const effects = decodeWake(row).wake_at;
|
|
361
|
-
|
|
362
|
-
return effects;
|
|
363
|
-
const now = this.options.now();
|
|
364
|
-
const results = decodeWake(this.options.owner.sql
|
|
365
|
-
.exec("SELECT MIN(COALESCE(h.next_attempt_at, ?)) AS wake_at FROM approval_handoffs h JOIN approval_records r ON r.home_key = h.home_key AND r.record_id = h.record_id WHERE h.home_key = ? AND h.command_id IS NULL AND h.undeliverable_at IS NULL AND (json_extract(r.record_json, '$.state') IN ('applied', 'denied', 'expired', 'outcome_unknown') OR (json_extract(r.record_json, '$.state') = 'pending' AND json_extract(r.record_json, '$.expiresAt') <= ?))", now, this.homeKey, now)
|
|
366
|
-
.toArray()[0]).wake_at;
|
|
367
|
-
return effects === null
|
|
368
|
-
? results
|
|
369
|
-
: results === null
|
|
370
|
-
? effects
|
|
371
|
-
: Math.min(effects, results);
|
|
375
|
+
return effects;
|
|
372
376
|
}
|
|
373
377
|
/** Bounded approved work for the native owner; selection never claims or dispatches. */
|
|
374
378
|
pendingApplications() {
|
|
@@ -384,118 +388,14 @@ export class ApprovalLedger {
|
|
|
384
388
|
return null;
|
|
385
389
|
return decodeJson(this.payload(recordId).input_json);
|
|
386
390
|
}
|
|
387
|
-
/** Bounded, home-local terminal notices for the native owner's work loop. */
|
|
388
|
-
pendingHandoffs() {
|
|
389
|
-
const decode = Schema.decodeUnknownSync(Schema.Struct({
|
|
390
|
-
record_id: ApprovalRecordSchema.fields.recordId,
|
|
391
|
-
}));
|
|
392
|
-
return this.options.owner.sql
|
|
393
|
-
.exec("SELECT h.record_id FROM approval_handoffs h JOIN approval_records r ON r.home_key = h.home_key AND r.record_id = h.record_id WHERE h.home_key = ? AND h.command_id IS NULL AND h.undeliverable_at IS NULL AND (h.next_attempt_at IS NULL OR h.next_attempt_at <= ?) AND (json_extract(r.record_json, '$.state') IN ('applied', 'denied', 'expired', 'outcome_unknown') OR (json_extract(r.record_json, '$.state') = 'pending' AND json_extract(r.record_json, '$.expiresAt') <= ?)) ORDER BY h.record_id LIMIT 100", this.homeKey, this.options.now(), this.options.now())
|
|
394
|
-
.toArray()
|
|
395
|
-
.map((row) => decode(row).record_id);
|
|
396
|
-
}
|
|
397
391
|
/**
|
|
398
|
-
*
|
|
399
|
-
*
|
|
400
|
-
* The host must return the real Session acceptance, not a success-shaped placeholder.
|
|
401
|
-
*/
|
|
402
|
-
async handoff(recordId, send) {
|
|
403
|
-
const record = this.get(recordId);
|
|
404
|
-
if (record === null)
|
|
405
|
-
return { kind: "refused", reason: "not-found" };
|
|
406
|
-
const receipt = () => {
|
|
407
|
-
const raw = this.options.owner.sql
|
|
408
|
-
.exec("SELECT command_id, delivery_id, attempts, undeliverable_at FROM approval_handoffs WHERE home_key = ? AND record_id = ?", this.homeKey, recordId)
|
|
409
|
-
.toArray()[0];
|
|
410
|
-
return raw === undefined
|
|
411
|
-
? null
|
|
412
|
-
: Schema.decodeUnknownSync(Schema.Struct({
|
|
413
|
-
command_id: Schema.NullOr(Schema.String),
|
|
414
|
-
delivery_id: Schema.String,
|
|
415
|
-
attempts: Schema.Int,
|
|
416
|
-
undeliverable_at: Schema.NullOr(Schema.Int),
|
|
417
|
-
}))(raw);
|
|
418
|
-
};
|
|
419
|
-
const previous = receipt();
|
|
420
|
-
if (previous === null)
|
|
421
|
-
return { kind: "not-required" };
|
|
422
|
-
if (previous.command_id !== null)
|
|
423
|
-
return { kind: "delivered", commandId: previous.command_id };
|
|
424
|
-
if (previous.undeliverable_at !== null)
|
|
425
|
-
return { kind: "undeliverable" };
|
|
426
|
-
let result;
|
|
427
|
-
switch (record.state) {
|
|
428
|
-
case "applied": {
|
|
429
|
-
const output = this.payload(recordId).output_json;
|
|
430
|
-
if (output === null)
|
|
431
|
-
throw new Error("Applied approval has no recorded output");
|
|
432
|
-
result = { kind: "applied", record, output: decodeJson(output) };
|
|
433
|
-
break;
|
|
434
|
-
}
|
|
435
|
-
case "denied":
|
|
436
|
-
result = this.deniedResult(record);
|
|
437
|
-
break;
|
|
438
|
-
case "expired":
|
|
439
|
-
result = { kind: "refused", reason: "expired" };
|
|
440
|
-
break;
|
|
441
|
-
case "outcome_unknown":
|
|
442
|
-
result = { kind: "refused", reason: "outcome-unknown" };
|
|
443
|
-
break;
|
|
444
|
-
case "claimed":
|
|
445
|
-
return { kind: "refused", reason: "in-flight" };
|
|
446
|
-
case "requested":
|
|
447
|
-
case "pending":
|
|
448
|
-
case "approved":
|
|
449
|
-
return { kind: "refused", reason: "pending" };
|
|
450
|
-
}
|
|
451
|
-
let accepted;
|
|
452
|
-
try {
|
|
453
|
-
// The minted id is the recipient's idempotency key on every retry.
|
|
454
|
-
accepted = await send({
|
|
455
|
-
deliveryId: previous.delivery_id,
|
|
456
|
-
record,
|
|
457
|
-
result,
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
catch (cause) {
|
|
461
|
-
const delivery = this.options.resultDelivery;
|
|
462
|
-
if (delivery !== undefined) {
|
|
463
|
-
const attempt = previous.attempts + 1;
|
|
464
|
-
// An absent or erased requester never accepts: stop, keep the record.
|
|
465
|
-
if (attempt >= delivery.attemptLimit) {
|
|
466
|
-
this.options.owner.sql.exec("UPDATE approval_handoffs SET attempts = ?, next_attempt_at = NULL, undeliverable_at = ? WHERE home_key = ? AND record_id = ? AND command_id IS NULL", attempt, this.options.now(), this.homeKey, recordId);
|
|
467
|
-
return { kind: "undeliverable" };
|
|
468
|
-
}
|
|
469
|
-
this.options.owner.sql.exec("UPDATE approval_handoffs SET attempts = ?, next_attempt_at = ? WHERE home_key = ? AND record_id = ? AND command_id IS NULL", attempt, this.options.now() + delivery.retryDelay(attempt), this.homeKey, recordId);
|
|
470
|
-
}
|
|
471
|
-
throw cause;
|
|
472
|
-
}
|
|
473
|
-
return this.options.owner.transactionSync(() => {
|
|
474
|
-
const current = receipt();
|
|
475
|
-
if (current === null)
|
|
476
|
-
throw new Error("Approval result delivery intent is missing");
|
|
477
|
-
if (current.command_id !== null &&
|
|
478
|
-
current.command_id !== accepted.commandId)
|
|
479
|
-
throw new Error("Approval result delivery identity conflicted");
|
|
480
|
-
this.options.owner.sql.exec("UPDATE approval_handoffs SET command_id = ? WHERE home_key = ? AND record_id = ? AND command_id IS NULL", accepted.commandId, this.homeKey, recordId);
|
|
481
|
-
return { kind: "delivered", commandId: accepted.commandId };
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
/**
|
|
485
|
-
* The home's work loop: only a durable approved record claims the existing
|
|
486
|
-
* host operation, and its result always reaches a waiting Agent as a message.
|
|
392
|
+
* Claim and apply one approved record exactly once. A waiting call applies
|
|
393
|
+
* its own record; the native owner's work loop applies the rest.
|
|
487
394
|
*/
|
|
488
395
|
apply(recordId, host) {
|
|
489
|
-
return this.run(recordId, host
|
|
490
|
-
}
|
|
491
|
-
/**
|
|
492
|
-
* Apply the caller's own just-staged policy approval inside its live tool
|
|
493
|
-
* call; that call's result is the outcome, so no later message is owed.
|
|
494
|
-
*/
|
|
495
|
-
applyInline(recordId, host) {
|
|
496
|
-
return this.run(recordId, host, false);
|
|
396
|
+
return this.run(recordId, host);
|
|
497
397
|
}
|
|
498
|
-
async run(recordId, host
|
|
398
|
+
async run(recordId, host) {
|
|
499
399
|
const claim = this.options.owner.transactionSync(() => {
|
|
500
400
|
const record = this.get(recordId);
|
|
501
401
|
if (record === null)
|
|
@@ -537,11 +437,6 @@ export class ApprovalLedger {
|
|
|
537
437
|
revision: record.revision + 1,
|
|
538
438
|
};
|
|
539
439
|
this.save(claimed);
|
|
540
|
-
// A deferred apply (even one policy approved) answers no live tool call.
|
|
541
|
-
if (deferred &&
|
|
542
|
-
claimed.requester.agentId !== null &&
|
|
543
|
-
claimed.requester.sessionId !== null)
|
|
544
|
-
this.options.owner.sql.exec("INSERT OR IGNORE INTO approval_handoffs (home_key, record_id, delivery_id) VALUES (?, ?, ?)", this.homeKey, recordId, mintDeliveryId());
|
|
545
440
|
return { kind: "claimed", record: claimed, input };
|
|
546
441
|
});
|
|
547
442
|
if (claim.kind !== "claimed")
|