osuite 2.11.1 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -145,7 +145,7 @@ function loadDotenvFile(relativePath) {
145
145
 
146
146
  function loadProjectEnvironment() {
147
147
  // Enrollment selects one whole runtime bundle, never a merged global env.
148
- if (process.argv[2] === 'connect') return;
148
+ if (process.argv[2] === 'connect' || CONTROLLED_TRANSFER_CLI) return;
149
149
  [...CLI_CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
150
150
  if (process.argv[2] === 'doctor' && !inspectCredentialFile(process.cwd(), relativePath).safe) return;
151
151
  loadDotenvFile(relativePath);
@@ -174,6 +174,8 @@ function parseArgs(argv) {
174
174
 
175
175
  // Hooks run with the agent's environment, not the values this CLI loads from project .env files.
176
176
  const SHELL_ENV = { ...process.env };
177
+ const CONTROLLED_TRANSFER_CLI = ['doctor', 'mcp'].includes(process.argv[2])
178
+ && process.argv.slice(3).some(value => /^--(?:controlled-transfers|require-controlled-transfers)(?:=|$)/.test(value));
177
179
  loadProjectEnvironment();
178
180
 
179
181
  function envValue(name, fallback) {
@@ -729,6 +731,9 @@ function printHelp() {
729
731
  write('');
730
732
  write(c('Useful commands', ANSI.bold));
731
733
  write(' osuite doctor Check connection, then run the project hook with a sample call');
734
+ write(' osuite doctor --controlled-transfers Read strict profile capabilities only (Node 24; --runtime sdk|mcp)');
735
+ write(' --require-controlled-transfers is an alias; this does not certify deployment qualification');
736
+ write(' osuite mcp --controlled-transfers Three controlled-ledger tools over bounded NDJSON stdio (Node 24)');
732
737
  write(' osuite try Review one fixed, harmless terminal acknowledgement');
733
738
  write(' osuite status Ping Studio and show current workspace connection');
734
739
  write(' osuite explain "git push origin main" Explain how CAVA/Decision V2 will read a command');
@@ -1183,6 +1188,37 @@ function printExplanation(command) {
1183
1188
  }
1184
1189
  }
1185
1190
 
1191
+ async function controlledTransferDiagnosis({ strict = false, runtime = 'sdk' } = {}) {
1192
+ const { probeMatoiStatus, formatMatoiStatus } = await import('./matoiDoctor.mjs');
1193
+ const { loadControlledTransferCliConfig } = await import('./controlled-transfers/cli-config.mjs');
1194
+ let status;
1195
+ try {
1196
+ const config = loadControlledTransferCliConfig({ projectRoot: process.cwd(), shellEnv: SHELL_ENV, runtime });
1197
+ status = await probeMatoiStatus({ config });
1198
+ } catch (error) {
1199
+ status = { ...await probeMatoiStatus(), code: error.code || 'INVALID_CONFIGURATION' };
1200
+ }
1201
+ write(formatMatoiStatus(status));
1202
+ if (strict && !status.configured) process.exitCode = 1;
1203
+ return status.configured === true;
1204
+ }
1205
+
1206
+ async function controlledTransferCommand(command, args) {
1207
+ const { fail } = await import('./controlled-transfers/contract.mjs');
1208
+ const allowed = command === 'doctor' ? ['_', 'controlled-transfers', 'require-controlled-transfers', 'runtime'] : ['_', 'controlled-transfers'];
1209
+ if (args._.length || Object.keys(args).some(key => !allowed.includes(key))
1210
+ || ['controlled-transfers', 'require-controlled-transfers'].some(key => Object.hasOwn(args, key) && args[key] !== true)
1211
+ || (command === 'mcp' && args['controlled-transfers'] !== true)
1212
+ || (command === 'doctor' && args.runtime !== undefined && !['sdk', 'mcp'].includes(args.runtime))) {
1213
+ fail('INVALID_CONTROLLED_TRANSFER_OPTIONS');
1214
+ }
1215
+ if (command === 'doctor') return controlledTransferDiagnosis({ strict: true, runtime: args.runtime || 'sdk' });
1216
+ const { loadControlledTransferCliConfig } = await import('./controlled-transfers/cli-config.mjs');
1217
+ const { runControlledTransferStdio } = await import('./controlled-transfers-stdio.mjs');
1218
+ const config = loadControlledTransferCliConfig({ projectRoot: process.cwd(), shellEnv: SHELL_ENV, runtime: 'mcp' });
1219
+ if (!await runControlledTransferStdio(config)) process.exitCode = 1;
1220
+ }
1221
+
1186
1222
  async function doctor() {
1187
1223
  const config = readConfig();
1188
1224
  let ok = true;
@@ -1246,6 +1282,8 @@ async function doctor() {
1246
1282
  if (!hookChecks.length) writeCheckLine('miss', 'Agent hooks', 'none in this project (fine for SDK and MCP runtimes)');
1247
1283
  const hooksOk = hookChecks.every((check) => check.ok);
1248
1284
 
1285
+ write('');
1286
+ await controlledTransferDiagnosis();
1249
1287
  write('');
1250
1288
  if (!ok || !hooksOk) {
1251
1289
  write(c('Next step', ANSI.bold));
@@ -1775,6 +1813,7 @@ async function main() {
1775
1813
 
1776
1814
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1777
1815
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1816
+ if (CONTROLLED_TRANSFER_CLI) return controlledTransferCommand(command, args);
1778
1817
  if (command === 'doctor') return runDoctorWithMeasurement(doctor, { config: readConfig(), emit: write });
1779
1818
  if (command === 'try') return tryWalkthrough(args);
1780
1819
  if (command === 'status') return status();
@@ -1796,6 +1835,9 @@ async function main() {
1796
1835
  }
1797
1836
 
1798
1837
  main().catch((error) => {
1799
- process.stderr.write(`${error?.message || String(error)}\n`);
1838
+ const message = CONTROLLED_TRANSFER_CLI
1839
+ ? /^[A-Z][A-Z0-9_]{0,63}$/.test(error?.code) ? `Matoi ${error.code}` : 'Matoi CONTROLLED_TRANSFER_COMMAND_FAILED'
1840
+ : error?.message || String(error);
1841
+ process.stderr.write(`${message}\n`);
1800
1842
  process.exit(1);
1801
1843
  });
@@ -0,0 +1,89 @@
1
+ import { statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { inspectCredentialFile, readCredentialFile } from '../credentials.js';
4
+ import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity } from '../installationIdentity.js';
5
+ import { loadRuntimeConfig } from '../runtime/config.mjs';
6
+ import { configuration, ControlledTransferError, fail } from './contract.mjs';
7
+
8
+ const fields = ['BASE_URL', 'API_KEY', 'PRIVATE_KEY_BASE64', 'AGENT_ID', 'ORG_ID', 'AGENT_KEY_ID',
9
+ 'RUNTIME_ADAPTER_ID', 'SIGNATURE_MODE', 'GUARD_FAILURE_MODE', 'HOOK_MODE', 'ALLOW_INSECURE_HTTP',
10
+ 'MATOI_ISSUER_PUBLIC_KEY_BASE64', 'MATOI_TRUSTED_ISSUER_PUBLIC_KEYS_B64', 'MATOI_TIMEOUT_MS'];
11
+
12
+ function parseEnvironment(raw) {
13
+ if (Buffer.byteLength(raw) > 65536) fail('INVALID_CREDENTIAL_FILE');
14
+ const env = Object.create(null);
15
+ for (const line of raw.split(/\r?\n/)) {
16
+ if (!line.trim() || line.trim().startsWith('#')) continue;
17
+ const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
18
+ if (!match) fail('INVALID_CREDENTIAL_FILE');
19
+ if (Object.hasOwn(env, match[1])) fail('INVALID_CREDENTIAL_FILE');
20
+ let value = match[2];
21
+ if (/^['"]/.test(value)) {
22
+ const quoted = value.match(/^(['"])(.*?)\1(?:\s+#.*)?$/);
23
+ if (!quoted) fail('INVALID_CREDENTIAL_FILE');
24
+ value = quoted[2];
25
+ } else value = value.replace(/\s+#.*$/, '');
26
+ env[match[1]] = value;
27
+ }
28
+ return env;
29
+ }
30
+
31
+ function selectedEnvironment(env) {
32
+ const result = Object.create(null);
33
+ for (const field of fields) {
34
+ const primary = env[`OSUITE_${field}`], legacy = env[`DASHCLAW_${field}`];
35
+ if (primary !== undefined && legacy !== undefined && primary !== legacy) fail('CREDENTIAL_SOURCE_CONFLICT');
36
+ if (primary !== undefined || legacy !== undefined) result[`OSUITE_${field}`] = primary ?? legacy;
37
+ }
38
+ return result;
39
+ }
40
+
41
+ export function loadControlledTransferCliConfig({ projectRoot = process.cwd(), shellEnv = process.env, runtime = 'sdk' } = {}) {
42
+ if (Number(process.versions.node.split('.')[0]) !== 24) fail('NODE_24_REQUIRED');
43
+ if (!['sdk', 'mcp'].includes(runtime)) fail('INVALID_CONTROLLED_TRANSFER_OPTIONS');
44
+ const envPath = runtime === 'mcp' ? MCP_ENV_PATH : SDK_ENV_PATH;
45
+ let raw;
46
+ try {
47
+ const checks = [envPath, `${envPath}.identity.json`, `${envPath}.connect.json`, `${envPath}.connect.lock`, MCP_MIGRATION_PATH]
48
+ .map(file => inspectCredentialFile(projectRoot, file));
49
+ if (checks.some(check => !check.safe)) fail('UNSAFE_CREDENTIALS');
50
+ if (checks.find(check => check.relativePath === MCP_MIGRATION_PATH)?.exists) fail('MCP_MIGRATION_PENDING');
51
+ if (checks.some(check => check.exists && /\.connect\.(json|lock)$/.test(check.relativePath))) fail('CONNECTION_RECOVERY_PENDING');
52
+ if (checks[0].exists && statSync(path.join(projectRoot, envPath)).size > 65536) fail('INVALID_CREDENTIAL_FILE');
53
+ raw = readCredentialFile(projectRoot, envPath);
54
+ parseInstallationIdentity(readCredentialFile(projectRoot, `${envPath}.identity.json`), runtime);
55
+ } catch (error) {
56
+ if (error instanceof ControlledTransferError) throw error;
57
+ fail('UNSAFE_CREDENTIALS');
58
+ }
59
+ const shell = selectedEnvironment(shellEnv);
60
+ const source = raw === null ? shell : selectedEnvironment(parseEnvironment(raw));
61
+ if (raw !== null && Object.entries(shell).some(([key, value]) => source[key] !== value)) fail('CREDENTIAL_SOURCE_CONFLICT');
62
+ // Never fill a partial credential/identity bundle from another file or from the shell.
63
+ if (['BASE_URL', 'API_KEY', 'PRIVATE_KEY_BASE64', 'AGENT_ID', 'ORG_ID'].some(key => !source[`OSUITE_${key}`])
64
+ || source.OSUITE_SIGNATURE_MODE !== 'required' || source.OSUITE_GUARD_FAILURE_MODE !== 'block'
65
+ || (source.OSUITE_HOOK_MODE !== undefined && !['enforce', 'strict'].includes(source.OSUITE_HOOK_MODE))
66
+ || (source.OSUITE_ALLOW_INSECURE_HTTP !== undefined && source.OSUITE_ALLOW_INSECURE_HTTP !== '0')
67
+ || !(runtime === 'mcp' ? ['mcp'] : ['sdk', 'framework_sdk', 'inline_sdk']).includes(source.OSUITE_RUNTIME_ADAPTER_ID)) {
68
+ fail('INVALID_CONFIGURATION');
69
+ }
70
+ const configured = loadRuntimeConfig({ env: source, host: runtime, runtimeId: source.OSUITE_RUNTIME_ADAPTER_ID });
71
+ const pin = source.OSUITE_MATOI_ISSUER_PUBLIC_KEY_BASE64;
72
+ if (pin !== undefined && !/^[A-Za-z0-9+/]+={0,2}$/.test(pin)) fail('INVALID_CONFIGURATION');
73
+ const timeout = source.OSUITE_MATOI_TIMEOUT_MS;
74
+ if (timeout !== undefined && !/^[1-9][0-9]{0,4}$/.test(timeout)) fail('INVALID_CONFIGURATION');
75
+ const history = source.OSUITE_MATOI_TRUSTED_ISSUER_PUBLIC_KEYS_B64;
76
+ let trustedIssuerPublicKeys = [];
77
+ if (history !== undefined) {
78
+ try {
79
+ if (history.length > 32768 || !/^[A-Za-z0-9+/]+={0,2}$/.test(history)) throw new Error();
80
+ const bytes = Buffer.from(history, 'base64');
81
+ if (bytes.toString('base64') !== history) throw new Error();
82
+ trustedIssuerPublicKeys = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
83
+ } catch { fail('INVALID_CONFIGURATION'); }
84
+ }
85
+ return configuration({ config: { ...configured, keyId: source.OSUITE_AGENT_KEY_ID,
86
+ issuerPublicKey: pin === undefined ? null : Buffer.from(pin, 'base64').toString('utf8'),
87
+ trustedIssuerPublicKeys,
88
+ timeoutMs: timeout === undefined ? 2500 : Number(timeout) } });
89
+ }
@@ -0,0 +1,395 @@
1
+ import { canonicalJson, createApiClient, sha256 } from '../runtime/protocol.mjs';
2
+ import { CONTROLLED_TRANSFER_PROFILE as PROFILE, COMPACT_TRANSFER_LEASE_PROFILE as COMPACT,
3
+ CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES, ENDPOINT, ControlledTransferError,
4
+ configuration, fail, identifier, inspectCapabilities, issuerIdentity, prepareLeaseFormat, record, reviewFields, snapshot } from './contract.mjs';
5
+ import { verifyPreparation, verifyReceipt } from './verification.mjs';
6
+ import { normalizeProjection, snapshotWithProjection } from './projection.mjs';
7
+
8
+ const MAX_HOT_OPERATIONS = 16;
9
+ const MAX_OPERATION_RECORDS = 65536;
10
+ const bit = ordinal => 1n << BigInt(ordinal);
11
+ const preparationBinding = prepared => sha256(canonicalJson([
12
+ prepared.grantId, prepared.preparationDigest, prepared.lease, prepared.effects,
13
+ ]));
14
+
15
+ export function createControlledTransfers(options) {
16
+ const config = configuration(options);
17
+ const api = createApiClient(config, { timeoutMs: config.timeoutMs, maxResponseBytes: CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES });
18
+ let issuer = config.issuerPublicKey ? issuerIdentity(config.issuerPublicKey) : null;
19
+ const operations = new Map();
20
+ const hot = new Map();
21
+
22
+ function operationFor(operationId) {
23
+ let operation = operations.get(operationId);
24
+ if (!operation) {
25
+ if (operations.size >= MAX_OPERATION_RECORDS) fail('CLIENT_CAPACITY_EXCEEDED', { operationId, reason: 'operation-record-limit' });
26
+ operation = { operationId, acknowledged: 0n, receiptMask: 0n };
27
+ operations.set(operationId, operation);
28
+ }
29
+ return operation;
30
+ }
31
+
32
+ const active = operation => operation.preparing || operation.recoveringPreparation || operation.executing || operation.reading;
33
+ function keepHot(operation) {
34
+ if (!hot.has(operation.operationId) && hot.size >= MAX_HOT_OPERATIONS) {
35
+ const entry = [...hot].find(([, candidate]) => !active(candidate));
36
+ if (!entry) fail('CLIENT_CAPACITY_EXCEEDED', { operationId: operation.operationId, reason: 'active-operation-limit' });
37
+ const [id, previous] = entry;
38
+ previous.prepared = null;
39
+ previous.completed = null;
40
+ hot.delete(id);
41
+ }
42
+ hot.delete(operation.operationId);
43
+ hot.set(operation.operationId, operation);
44
+ }
45
+
46
+ function releaseIdle(operation) {
47
+ if (active(operation)) return;
48
+ if (!operation.prepared && !operation.completed?.size) hot.delete(operation.operationId);
49
+ // Only a preflight that never observed or sent an operation may be forgotten.
50
+ if (!operation.seen && !operation.unknown) {
51
+ hot.delete(operation.operationId);
52
+ operations.delete(operation.operationId);
53
+ }
54
+ }
55
+
56
+ function checkBinding(operation, prepared, statusRead = false) {
57
+ const code = statusRead ? 'INVALID_STATUS' : 'OPERATION_CONFLICT';
58
+ if ((operation.grantId !== undefined && operation.grantId !== prepared.grantId)
59
+ || (operation.effectCount !== undefined && operation.effectCount !== prepared.effects.length)) fail(code);
60
+ if (!operation.binding) return;
61
+ if (operation.binding !== preparationBinding(prepared)
62
+ || ((!statusRead || operation.actionId) && (operation.actionId !== prepared.actionId || operation.fingerprint !== prepared.fingerprint))
63
+ || (!statusRead && operation.preparationState !== prepared.state)) fail(code);
64
+ }
65
+
66
+ function rememberPreparation(operation, prepared, statusRead = false) {
67
+ checkBinding(operation, prepared, statusRead);
68
+ keepHot(operation);
69
+ operation.grantId = prepared.grantId;
70
+ operation.leaseFormat = prepared.lease.payload.profile;
71
+ operation.binding = preparationBinding(prepared);
72
+ operation.effectCount = prepared.effects.length;
73
+ operation.actionId = prepared.actionId;
74
+ operation.fingerprint = prepared.fingerprint;
75
+ operation.preparationState = prepared.state;
76
+ operation.prepared = prepared;
77
+ operation.seen = true;
78
+ }
79
+
80
+ function receiptDigest(operation, ordinal) {
81
+ return operation.receiptMask & bit(ordinal)
82
+ ? operation.receiptDigests.toString('hex', ordinal * 32, (ordinal + 1) * 32) : null;
83
+ }
84
+
85
+ function checkReceipt(operation, ordinal, receipt, code) {
86
+ const digest = sha256(canonicalJson(receipt)), previous = receiptDigest(operation, ordinal);
87
+ if (previous && previous !== digest) fail(code);
88
+ return digest;
89
+ }
90
+
91
+ function rememberReceipt(operation, ordinal, receipt, acknowledged = false) {
92
+ const digest = checkReceipt(operation, ordinal, receipt, 'INVALID_RECEIPT');
93
+ operation.receiptDigests ??= Buffer.alloc(operation.effectCount * 32);
94
+ Buffer.from(digest, 'hex').copy(operation.receiptDigests, ordinal * 32);
95
+ operation.receiptMask |= bit(ordinal);
96
+ if (acknowledged) operation.acknowledged |= bit(ordinal);
97
+ }
98
+
99
+ function replayResult(operationId, prepared, receipt, projection) {
100
+ return snapshotWithProjection({ profile: PROFILE, operationId, state: 'already_committed', receipt,
101
+ projection, ...reviewFields(prepared, config.baseUrl), newlyCommitted: false });
102
+ }
103
+
104
+ async function recover(operation) {
105
+ const observed = await status(operation.operationId);
106
+ if (operation.unknown) throw operation.unknown;
107
+ const prepared = observed.prepared ?? operation.prepared;
108
+ if (!prepared) throw unknown(operation.operationId, 'MISSING_HISTORICAL_PREPARATION');
109
+ return { observed, prepared };
110
+ }
111
+
112
+ async function capabilities() {
113
+ const response = await api.request('GET', ENDPOINT);
114
+ if (!response.ok) fail('CAPABILITY_UNAVAILABLE', { reason: response.error, httpStatus: response.status });
115
+ const value = inspectCapabilities(response.body);
116
+ if (value.issuerPublicKey) {
117
+ const advertised = issuerIdentity(value.issuerPublicKey, 'INVALID_CAPABILITY');
118
+ if (issuer && issuer.fingerprint !== advertised.fingerprint) fail('CAPABILITY_MISMATCH');
119
+ issuer = advertised;
120
+ }
121
+ return value;
122
+ }
123
+
124
+ async function requireCapability() {
125
+ const value = await capabilities();
126
+ if (!value.configured || !value.resourceEnforced || !issuer) fail('PROFILE_UNAVAILABLE');
127
+ return value;
128
+ }
129
+
130
+ function unknown(operationId, reason, httpStatus = null) {
131
+ const error = new ControlledTransferError('OUTCOME_UNKNOWN', { operationId, reason, httpStatus });
132
+ const operation = operationFor(operationId);
133
+ operation.unknown = error;
134
+ return error;
135
+ }
136
+
137
+ async function post(kind, operationId, fields) {
138
+ if (operations.get(operationId)?.unknown) throw operations.get(operationId).unknown;
139
+ const response = await api.request('POST', ENDPOINT, { profile: PROFILE, agent_id: config.agentId,
140
+ kind, operationId, timestamp: Date.now(), ...fields });
141
+ if (!response.ok) throw unknown(operationId, response.error, response.status);
142
+ let body;
143
+ try {
144
+ body = kind === 'execute' ? snapshotWithProjection(response.body) : snapshot(response.body);
145
+ } catch { throw unknown(operationId, 'INVALID_RESPONSE'); }
146
+ if (body.profile !== PROFILE || body.operationId !== operationId) {
147
+ throw unknown(operationId, 'RESPONSE_BINDING_MISMATCH');
148
+ }
149
+ return body;
150
+ }
151
+
152
+ function checkPrepareChoice(operation, grantId, leaseFormat) {
153
+ if ((operation.grantId !== undefined && operation.grantId !== grantId)
154
+ || (operation.preparingGrantId !== undefined && operation.preparingGrantId !== grantId)) fail('OPERATION_CONFLICT');
155
+ if ((operation.leaseFormat !== undefined && operation.leaseFormat !== leaseFormat)
156
+ || (operation.preparingFormat !== undefined && operation.preparingFormat !== leaseFormat)) fail('LEASE_FORMAT_CONFLICT');
157
+ }
158
+
159
+ function prepareOnce(operation, grantId, leaseFormat, work, recovery = false) {
160
+ const slot = recovery ? 'recoveringPreparation' : 'preparing';
161
+ operation.preparingGrantId = grantId;
162
+ operation.preparingFormat = leaseFormat;
163
+ operation[slot] = Promise.resolve().then(work).finally(() => {
164
+ operation[slot] = null;
165
+ operation.preparingGrantId = undefined;
166
+ operation.preparingFormat = undefined;
167
+ releaseIdle(operation);
168
+ });
169
+ return operation[slot];
170
+ }
171
+
172
+ async function prepare(operationId, grantId, options) {
173
+ if (!identifier(operationId)) fail('INVALID_OPERATION_ID');
174
+ if (!identifier(grantId)) fail('INVALID_GRANT_ID');
175
+ const existing = operations.get(operationId);
176
+ if (existing?.unknown) throw existing.unknown;
177
+ const leaseFormat = prepareLeaseFormat(options);
178
+ if (existing) {
179
+ checkPrepareChoice(existing, grantId, leaseFormat);
180
+ if (existing.prepared) { keepHot(existing); return existing.prepared; }
181
+ if (existing.preparing || existing.recoveringPreparation) return existing.preparing ?? existing.recoveringPreparation;
182
+ if (existing.executing) fail('EXECUTION_IN_PROGRESS');
183
+ return prepareOnce(existing, grantId, leaseFormat, async () => {
184
+ const { prepared } = await recover(existing);
185
+ checkPrepareChoice(existing, grantId, leaseFormat);
186
+ return prepared;
187
+ }, true);
188
+ }
189
+ const operation = operationFor(operationId);
190
+ operation.grantId = grantId;
191
+ try { keepHot(operation); } catch (error) { releaseIdle(operation); throw error; }
192
+ return prepareOnce(operation, grantId, leaseFormat, async () => {
193
+ let capability;
194
+ try { capability = await requireCapability(); } catch (error) {
195
+ if (operation.unknown) throw operation.unknown;
196
+ throw error;
197
+ }
198
+ if (operation.reading) await operation.reading;
199
+ if (operation.unknown) throw operation.unknown;
200
+ checkPrepareChoice(operation, grantId, leaseFormat);
201
+ if (operation.prepared) return operation.prepared;
202
+ if (operation.seen) throw unknown(operationId, 'MISSING_HISTORICAL_PREPARATION');
203
+ if (leaseFormat === COMPACT) {
204
+ if (!capability.leaseFormats.supported.includes(COMPACT)) fail('LEASE_FORMAT_UNSUPPORTED');
205
+ if (!capability.leaseFormats.compactIssuanceEnabled) fail('COMPACT_LEASE_ISSUANCE_DISABLED');
206
+ }
207
+ operation.seen = true;
208
+ const body = await post('prepare', operationId, { grantId, ...(leaseFormat === COMPACT ? { leaseFormat } : {}) });
209
+ try {
210
+ const verified = verifyPreparation(body, { config, issuer, operationId, grantId });
211
+ if (verified.lease.payload.profile !== leaseFormat) fail('LEASE_FORMAT_CONFLICT');
212
+ rememberPreparation(operation, snapshot({ ...verified, ...reviewFields(verified, config.baseUrl) }));
213
+ }
214
+ catch { throw unknown(operationId, 'INVALID_PREPARATION'); }
215
+ return operation.prepared;
216
+ });
217
+ }
218
+
219
+ async function execute(prepared, ordinal = 0) {
220
+ prepared = snapshot(prepared, 'INVALID_PREPARATION');
221
+ if (!record(prepared) || !identifier(prepared.operationId) || !identifier(prepared.grantId) || !record(prepared.lease)) fail('INVALID_PREPARATION');
222
+ if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal >= prepared.effects?.length) fail('INVALID_ORDINAL');
223
+ const operationId = prepared.operationId;
224
+ let operation = operations.get(operationId);
225
+ if (operation?.unknown) throw operation.unknown;
226
+ if (operation && operation.grantId !== undefined && operation.grantId !== prepared.grantId) fail('OPERATION_CONFLICT');
227
+ if (operation?.preparing && !operation.prepared) fail('PREPARATION_IN_PROGRESS');
228
+ if (operation) checkBinding(operation, prepared);
229
+ const previous = operation?.prepared ?? operation?.executing?.prepared;
230
+ if (previous && ['grantId', 'preparationDigest', 'actionId', 'fingerprint', 'lease', 'effects', 'state']
231
+ .some(field => canonicalJson(prepared[field]) !== canonicalJson(previous[field]))) fail('OPERATION_CONFLICT');
232
+ if (!operation) {
233
+ operation = operationFor(operationId);
234
+ operation.grantId = prepared.grantId;
235
+ }
236
+ if (operation.completed?.has(ordinal)) {
237
+ keepHot(operation);
238
+ const completed = operation.completed.get(ordinal);
239
+ return snapshotWithProjection({ ...completed, state: 'already_committed', newlyCommitted: false,
240
+ projection: normalizeProjection(completed.projection, { cached: true }) });
241
+ }
242
+ if (operation.acknowledged & bit(ordinal)) {
243
+ const recovered = await recover(operation);
244
+ const effect = recovered.observed.effects[ordinal];
245
+ if (!effect?.receiptVerified || receiptDigest(operation, ordinal) !== sha256(canonicalJson(effect.receipt))) {
246
+ throw unknown(operationId, 'INVALID_HISTORICAL_RECEIPT');
247
+ }
248
+ return replayResult(operationId, recovered.prepared, effect.receipt, recovered.observed.projection);
249
+ }
250
+ if (operation.executing) {
251
+ if (operation.executing.ordinal !== ordinal) fail('EXECUTION_IN_PROGRESS');
252
+ return operation.executing.promise;
253
+ }
254
+ try { keepHot(operation); } catch (error) { releaseIdle(operation); throw error; }
255
+ const pending = { ordinal, prepared };
256
+ operation.executing = pending;
257
+ pending.promise = (async () => {
258
+ if (operation.reading) await operation.reading;
259
+ if (operation.unknown) throw operation.unknown;
260
+ const capability = await requireCapability();
261
+ if (operation.unknown) throw operation.unknown;
262
+ prepared = verifyPreparation(prepared, { config, issuer, operationId, grantId: prepared.grantId });
263
+ checkBinding(operation, prepared);
264
+ if (prepared.state === 'denied') fail('PREPARATION_DENIED');
265
+ if (!prepared.actionId) fail('APPROVAL_NOT_BOUND');
266
+ if (prepared.lease.payload.profile === COMPACT && !capability.leaseFormats.supported.includes(COMPACT)) {
267
+ fail('LEASE_FORMAT_UNSUPPORTED');
268
+ }
269
+ // Reuse the immutable snapshot, rather than retaining another full copy per execution.
270
+ prepared = operation.prepared ?? prepared;
271
+ rememberPreparation(operation, prepared);
272
+ pending.dispatched = true;
273
+ const binding = capability.executionTransport === 'bound-reference-v1'
274
+ ? { preparationDigest: prepared.preparationDigest } : { lease: prepared.lease };
275
+ const body = await post('execute', operationId, { ...binding, ordinal });
276
+ let result;
277
+ if (body.state === 'denied' && identifier(body.code) && body.receipt == null) {
278
+ result = snapshotWithProjection({ ...body, ...reviewFields(prepared, config.baseUrl), newlyCommitted: false });
279
+ } else if (['committed', 'already_committed'].includes(body.state)) {
280
+ let receipt;
281
+ try { receipt = verifyReceipt(body.receipt, { issuer, config, prepared, ordinal, historical: body.state === 'already_committed',
282
+ sourcePrepared: body.receipt?.payload?.operationId !== operationId
283
+ ? operations.get(body.receipt?.payload?.operationId)?.prepared : undefined }); }
284
+ catch { throw unknown(operationId, 'INVALID_RECEIPT'); }
285
+ result = snapshotWithProjection({ ...body, receipt, ...reviewFields(prepared, config.baseUrl), newlyCommitted: body.state === 'committed' });
286
+ rememberReceipt(operation, ordinal, receipt, true);
287
+ operation.completed ??= new Map();
288
+ operation.completed.set(ordinal, result);
289
+ } else { throw unknown(operationId, 'INVALID_EXECUTION_RESPONSE'); }
290
+ return result;
291
+ })().catch(error => {
292
+ if (operation.unknown) throw operation.unknown;
293
+ if (pending.dispatched) throw unknown(operationId, 'INVALID_EXECUTION_RESPONSE');
294
+ throw error;
295
+ });
296
+ try { return await pending.promise; }
297
+ catch (error) { throw operation.unknown ?? error; }
298
+ finally {
299
+ operation.executing = null;
300
+ releaseIdle(operation);
301
+ }
302
+ }
303
+
304
+ function unknownStatus(operationId, reason, httpStatus = null, prepared, projection) {
305
+ const error = unknown(operationId, reason, httpStatus);
306
+ return snapshotWithProjection({ profile: PROFILE, operationId, state: 'unknown', code: error.code,
307
+ reason, httpStatus, lastDenial: null, effects: [], newlyCommitted: false, projection,
308
+ ...reviewFields(operations.get(operationId), config.baseUrl), recovery: error.recovery,
309
+ ...(prepared ? { prepared } : {}) });
310
+ }
311
+
312
+ async function status(operationId) {
313
+ if (!identifier(operationId)) fail('INVALID_OPERATION_ID');
314
+ const operation = operationFor(operationId);
315
+ if (operation.reading) return operation.reading;
316
+ try { keepHot(operation); } catch (error) { releaseIdle(operation); throw error; }
317
+ operation.reading = readStatus(operationId, operation);
318
+ try { return await operation.reading; }
319
+ finally { operation.reading = null; releaseIdle(operation); }
320
+ }
321
+
322
+ async function readStatus(operationId, operation) {
323
+ const response = await api.request('GET', `${ENDPOINT}?operationId=${encodeURIComponent(operationId)}&agent_id=${encodeURIComponent(config.agentId)}`);
324
+ if (!response.ok) return unknownStatus(operationId, response.error, response.status);
325
+ try {
326
+ const body = snapshotWithProjection(response.body, 'INVALID_STATUS');
327
+ if (!record(body) || body.profile !== PROFILE || body.operationId !== operationId
328
+ || !['committed', 'partially_committed', 'denied', 'awaiting_approval', 'ready', 'unknown'].includes(body.state)
329
+ || !(body.actionId === null || identifier(body.actionId))
330
+ || !(body.lastDenial === null || identifier(body.lastDenial))
331
+ || !Array.isArray(body.effects) || body.effects.length > 64
332
+ || (body.state === 'ready' && !body.actionId)) fail('INVALID_STATUS');
333
+ const hasPrepared = Object.hasOwn(body, 'prepared');
334
+ if (!issuer && (hasPrepared || body.effects.some(effect => effect?.state === 'committed'))) await capabilities();
335
+ let prepared = operation?.prepared;
336
+ if (!prepared && operation.binding && !hasPrepared) fail('INVALID_STATUS');
337
+ if (hasPrepared) {
338
+ const verified = verifyPreparation(body.prepared, { config, issuer, operationId,
339
+ grantId: operation?.grantId ?? body.prepared?.grantId, checkExpiry: false, historical: true });
340
+ checkBinding(operation, verified, true);
341
+ const previous = prepared ?? operation?.executing?.prepared;
342
+ if (previous && (['grantId', 'preparationDigest', 'lease', 'effects']
343
+ .some(field => canonicalJson(verified[field]) !== canonicalJson(previous[field]))
344
+ || (previous.actionId && (verified.actionId !== previous.actionId || verified.fingerprint !== previous.fingerprint)))) {
345
+ fail('INVALID_STATUS');
346
+ }
347
+ prepared = snapshot({ ...verified, ...reviewFields(verified, config.baseUrl) });
348
+ }
349
+ if (prepared && body.actionId !== prepared.actionId) fail('INVALID_STATUS');
350
+ if (body.state === 'unknown') return unknownStatus(operationId, 'OWNER_OUTCOME_UNKNOWN', null,
351
+ hasPrepared ? prepared : undefined, body.projection);
352
+ if (!body.effects.length || (prepared && body.effects.length !== prepared.effects.length)
353
+ || (operation.effectCount !== undefined && body.effects.length !== operation.effectCount)) fail('INVALID_STATUS');
354
+ let committed = 0;
355
+ const payments = new Set();
356
+ const effects = body.effects.map((effect, ordinal) => {
357
+ if (!record(effect) || effect.ordinal !== ordinal || !identifier(effect.paymentId)
358
+ || payments.has(effect.paymentId) || !['committed', 'not_committed'].includes(effect.state)
359
+ || (prepared && effect.paymentId !== prepared.effects[ordinal].paymentId)) fail('INVALID_STATUS');
360
+ payments.add(effect.paymentId);
361
+ if (effect.state !== 'committed') {
362
+ if (effect.receipt != null || receiptDigest(operation, ordinal)) fail('INVALID_STATUS');
363
+ return { ...effect, receiptVerified: false };
364
+ }
365
+ const receipt = verifyReceipt(effect.receipt, { issuer, config, prepared, ordinal, historical: true,
366
+ sourcePrepared: effect.receipt?.payload?.operationId !== operationId
367
+ ? operations.get(effect.receipt?.payload?.operationId)?.prepared : undefined,
368
+ operationId, actionId: body.actionId, paymentId: effect.paymentId });
369
+ checkReceipt(operation, ordinal, receipt, 'INVALID_STATUS');
370
+ committed++;
371
+ return { ...effect, receipt, receiptVerified: true };
372
+ });
373
+ if ((body.state === 'committed' && committed !== effects.length)
374
+ || (body.state === 'partially_committed' && (committed === 0 || committed === effects.length))
375
+ || (['denied', 'awaiting_approval', 'ready'].includes(body.state) && committed !== 0)) fail('INVALID_STATUS');
376
+ if (hasPrepared) {
377
+ // Recover the original lease without replacing any physical-outcome uncertainty fence.
378
+ rememberPreparation(operation, prepared, true);
379
+ }
380
+ operation.seen = true;
381
+ operation.effectCount = effects.length;
382
+ for (const effect of effects) if (effect.receiptVerified) {
383
+ rememberReceipt(operation, effect.ordinal, effect.receipt);
384
+ if (operation.acknowledged & bit(effect.ordinal)) {
385
+ operation.completed ??= new Map();
386
+ operation.completed.set(effect.ordinal, replayResult(operationId, prepared, effect.receipt, body.projection));
387
+ }
388
+ }
389
+ return snapshotWithProjection({ ...body, effects, ...reviewFields(body, config.baseUrl), newlyCommitted: false,
390
+ ...(hasPrepared ? { prepared } : {}) });
391
+ } catch (error) { return unknownStatus(operationId, error.code ?? 'INVALID_STATUS'); }
392
+ }
393
+
394
+ return Object.freeze({ capabilities, prepare, execute, status });
395
+ }