osuite 2.10.1 → 2.11.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/GOVERNED_TOOLS.md +202 -0
- package/README.md +57 -7
- package/cli.js +231 -52
- package/governed-tools/authority.mjs +134 -0
- package/governed-tools/contract.mjs +142 -0
- package/governed-tools/examples/native-client.mjs +47 -0
- package/governed-tools/executor.mjs +185 -0
- package/governed-tools/journal.mjs +448 -0
- package/governed-tools/mcp.mjs +95 -0
- package/governed-tools.mjs +10 -0
- package/installationIdentity.js +113 -0
- package/package.json +9 -1
- package/runtime/admission.mjs +67 -8
- package/runtime/config.mjs +2 -0
- package/runtime/hook.mjs +11 -9
- package/runtime/mcp.mjs +1 -1
- package/runtime/posture.mjs +72 -7
- package/runtime/protocol.mjs +7 -2
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { types } from 'node:util';
|
|
2
|
+
import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
|
|
3
|
+
|
|
4
|
+
export const CALL_SCHEMA = 'osuite.native_tool_call.v1';
|
|
5
|
+
export const COVERAGE = 'wrapped-call-only';
|
|
6
|
+
export const ADMISSION_PATH = 'studio-current-action';
|
|
7
|
+
const unsafeKeys = new Set(['__proto__', 'prototype', 'constructor']);
|
|
8
|
+
const id = value => safeId(value) && value.length <= 128;
|
|
9
|
+
|
|
10
|
+
export class GovernedToolError extends Error {
|
|
11
|
+
constructor(code, status = null) {
|
|
12
|
+
super(`OSuite ${code}: no automatic repeat of this operation.`);
|
|
13
|
+
this.name = 'GovernedToolError';
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.retryAutomatically = false;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export function reject(code, status) { throw new GovernedToolError(code, status); }
|
|
20
|
+
|
|
21
|
+
// Validate descriptors before reading values: JSON.stringify alone can invoke
|
|
22
|
+
// accessors/toJSON or quietly change undefined, non-finite numbers and arrays.
|
|
23
|
+
export function jsonSnapshot(input, maxBytes = 65536) {
|
|
24
|
+
const ancestors = new Set();
|
|
25
|
+
let nodes = 0;
|
|
26
|
+
function copy(value, depth) {
|
|
27
|
+
if (++nodes > 8192 || depth > 16) reject('INVALID_INPUT');
|
|
28
|
+
if (value === null || typeof value === 'boolean') return value;
|
|
29
|
+
if (typeof value === 'string') {
|
|
30
|
+
if (value.length > maxBytes || !value.isWellFormed()) reject('INVALID_INPUT');
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
if (typeof value === 'number') {
|
|
34
|
+
if (!Number.isFinite(value) || Object.is(value, -0)) reject('INVALID_INPUT');
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
if (typeof value !== 'object' || types.isProxy(value) || ancestors.has(value)) reject('INVALID_INPUT');
|
|
38
|
+
const array = Array.isArray(value), prototype = Object.getPrototypeOf(value);
|
|
39
|
+
if (prototype !== (array ? Array.prototype : Object.prototype) && !(prototype === null && !array)) reject('INVALID_INPUT');
|
|
40
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
41
|
+
const keys = Reflect.ownKeys(descriptors);
|
|
42
|
+
if (keys.some(key => typeof key !== 'string' || unsafeKeys.has(key)
|
|
43
|
+
|| !Object.hasOwn(descriptors[key], 'value') || (!descriptors[key].enumerable && !(array && key === 'length')))) reject('INVALID_INPUT');
|
|
44
|
+
if (array && (value.length > 8192 || keys.length !== value.length + 1
|
|
45
|
+
|| keys.some(key => key !== 'length' && !/^(0|[1-9][0-9]*)$/.test(key)))) reject('INVALID_INPUT');
|
|
46
|
+
ancestors.add(value);
|
|
47
|
+
const result = array ? [] : {};
|
|
48
|
+
for (const key of keys) {
|
|
49
|
+
if (array && key === 'length') continue;
|
|
50
|
+
if (!key.isWellFormed()) reject('INVALID_INPUT');
|
|
51
|
+
result[key] = copy(descriptors[key].value, depth + 1);
|
|
52
|
+
}
|
|
53
|
+
ancestors.delete(value);
|
|
54
|
+
return Object.freeze(result);
|
|
55
|
+
}
|
|
56
|
+
const snapshot = copy(input, 0);
|
|
57
|
+
if (Buffer.byteLength(canonicalJson(snapshot)) > maxBytes) reject('INVALID_INPUT');
|
|
58
|
+
return snapshot;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function scopeFor(config, namespace) {
|
|
62
|
+
const base = validatedBaseUrl(config?.baseUrl);
|
|
63
|
+
if (!base || !id(config.orgId) || !id(config.agentId) || !id(config.runtimeId) || !id(namespace)
|
|
64
|
+
|| (config.provider != null && !id(config.provider))) reject('INVALID_CONFIGURATION');
|
|
65
|
+
return sha256(canonicalJson({ origin: base, org: config.orgId, agent: config.agentId,
|
|
66
|
+
runtime: config.runtimeId, provider: config.provider || null, namespace }));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const strings = { action_type: 128, declared_goal: 2000, authorization_scope: 1000,
|
|
70
|
+
data_classification: 64, data_residency_region: 128 };
|
|
71
|
+
const booleans = new Set(['reversible', 'privacy_review_required', 'data_minimization_declared', 'cross_border_transfer']);
|
|
72
|
+
const numbers = new Set(['risk_score', 'personal_data_likelihood']);
|
|
73
|
+
const arrays = new Set(['systems_touched', 'sensitive_data_categories', 'external_data_processors']);
|
|
74
|
+
const allowed = new Set([...Object.keys(strings), ...booleans, ...numbers, ...arrays, 'input_summary']);
|
|
75
|
+
|
|
76
|
+
function describe(binding, args) {
|
|
77
|
+
let value;
|
|
78
|
+
try { value = jsonSnapshot(binding.describe(args), 6000); } catch { reject('INVALID_MAPPING'); }
|
|
79
|
+
if (!value || Array.isArray(value) || typeof value !== 'object'
|
|
80
|
+
|| Object.keys(value).some(key => !allowed.has(key)) || !value.action_type || !value.declared_goal) reject('INVALID_MAPPING');
|
|
81
|
+
for (const [key, item] of Object.entries(value)) {
|
|
82
|
+
if (strings[key] && (typeof item !== 'string' || !item.trim() || item.length > strings[key])) reject('INVALID_MAPPING');
|
|
83
|
+
if (booleans.has(key) && typeof item !== 'boolean') reject('INVALID_MAPPING');
|
|
84
|
+
if (numbers.has(key) && (!Number.isSafeInteger(item) || item < 0 || item > 100)) reject('INVALID_MAPPING');
|
|
85
|
+
if (arrays.has(key) && (!Array.isArray(item) || item.length > 20
|
|
86
|
+
|| item.some(entry => typeof entry !== 'string' || entry.length > 500))) reject('INVALID_MAPPING');
|
|
87
|
+
}
|
|
88
|
+
if (value.input_summary !== undefined && (!value.input_summary || Array.isArray(value.input_summary)
|
|
89
|
+
|| typeof value.input_summary !== 'object' || Object.hasOwn(value.input_summary, 'osuite_native_call'))) reject('INVALID_MAPPING');
|
|
90
|
+
return value;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function makeInvocation({ config, namespace, bindings, operationId, params }) {
|
|
94
|
+
const scope = scopeFor(config, namespace);
|
|
95
|
+
if (!id(operationId)) reject('INVALID_OPERATION_ID');
|
|
96
|
+
const native = jsonSnapshot(params, 32768);
|
|
97
|
+
if (!native || Array.isArray(native) || !id(native.name) || !Object.hasOwn(native, 'arguments')
|
|
98
|
+
|| Object.keys(native).some(key => !['name', 'arguments'].includes(key))) reject('INVALID_INPUT');
|
|
99
|
+
if (!bindings || !Object.hasOwn(bindings, native.name)) reject('UNSUPPORTED_TOOL');
|
|
100
|
+
const binding = bindings[native.name];
|
|
101
|
+
if (!binding || !id(binding.revision) || typeof binding.describe !== 'function') reject('INVALID_MAPPING');
|
|
102
|
+
const description = describe(binding, native.arguments);
|
|
103
|
+
// The historical Hook helper normalizes null to {}. Native calls must retain
|
|
104
|
+
// every JSON value exactly, including that distinction.
|
|
105
|
+
const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
|
|
106
|
+
const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description }));
|
|
107
|
+
const identity = sha256(canonicalJson([scope, operationId]));
|
|
108
|
+
const actionId = `act_${identity}`, sessionId = `sess_${identity}`, toolUseId = `tool_${identity}`;
|
|
109
|
+
const marker = { schema_version: CALL_SCHEMA, operation_digest: sha256(operationId), input_digest: inputDigest, binding_digest: bindingDigest };
|
|
110
|
+
const inputSummary = JSON.stringify({ ...description.input_summary, osuite_native_call: marker });
|
|
111
|
+
if (inputSummary.length > 4000) reject('INVALID_MAPPING');
|
|
112
|
+
const context = jsonSnapshot({ ...description, input_summary: inputSummary, action_id: actionId,
|
|
113
|
+
agent_id: config.agentId, runtime_session_id: sessionId, tool_use_id: toolUseId,
|
|
114
|
+
tool_input_digest: inputDigest, runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper' });
|
|
115
|
+
return Object.freeze({ params: native, context, marker, record: Object.freeze({ scope, operationId,
|
|
116
|
+
inputDigest, bindingDigest, contextDigest: sha256(canonicalJson(context)), actionId, sessionId, toolUseId }) });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function matchesStoredAction(payload, record, config) {
|
|
120
|
+
try {
|
|
121
|
+
const action = payload?.action || payload;
|
|
122
|
+
const summary = typeof action?.input_summary === 'string' ? JSON.parse(action.input_summary) : action?.input_summary;
|
|
123
|
+
const marker = summary?.osuite_native_call;
|
|
124
|
+
const envelope = action?.action_envelope;
|
|
125
|
+
return action?.action_id === record.actionId && action.agent_id === config.agentId
|
|
126
|
+
&& action.org_id === config.orgId && action.verified === true
|
|
127
|
+
&& (!payload.action_id || payload.action_id === record.actionId)
|
|
128
|
+
&& envelope?.runtime_session_id === record.sessionId
|
|
129
|
+
&& marker?.schema_version === CALL_SCHEMA && marker.operation_digest === sha256(record.operationId)
|
|
130
|
+
&& marker.input_digest === record.inputDigest && marker.binding_digest === record.bindingDigest;
|
|
131
|
+
} catch { return false; }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function publicStatus(record, baseUrl) {
|
|
135
|
+
if (!record) return null;
|
|
136
|
+
return Object.freeze({ operationId: record.operationId, actionId: record.actionId, state: record.state,
|
|
137
|
+
resultDigest: record.resultDigest || null, reportState: record.reportState,
|
|
138
|
+
reviewUrl: `${baseUrl}/approvals?action=${encodeURIComponent(record.actionId)}`,
|
|
139
|
+
replayUrl: `${baseUrl}/replay/${encodeURIComponent(record.actionId)}`,
|
|
140
|
+
admissionPath: ADMISSION_PATH, coverage: COVERAGE, retryAutomatically: false,
|
|
141
|
+
resultRetained: false });
|
|
142
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { createGovernedTools } from '../../governed-tools.mjs';
|
|
2
|
+
import { sha256, canonicalJson, validatedBaseUrl } from '../../runtime/protocol.mjs';
|
|
3
|
+
|
|
4
|
+
const initializeJournal = process.argv.includes('--initialize-journal');
|
|
5
|
+
if (process.argv.includes('--help') || (!process.argv.includes('--execute') && !initializeJournal)) {
|
|
6
|
+
console.log('Native tool example (Node 24). No calls performed.\n'
|
|
7
|
+
+ 'To execute one explicitly configured operation, set OSUITE_BASE_URL, OSUITE_ORG_ID, '
|
|
8
|
+
+ 'OSUITE_AGENT_ID, OSUITE_API_KEY, OSUITE_PRIVATE_KEY_BASE64, OSUITE_JOURNAL_PATH, '
|
|
9
|
+
+ 'NATIVE_TOOL_URL and OPERATION_ID. Provision once with --initialize-journal; '
|
|
10
|
+
+ 'later pass --execute to run against the existing journal.\n'
|
|
11
|
+
+ 'The target receives one synthetic append; use a dedicated resource you control.');
|
|
12
|
+
} else {
|
|
13
|
+
if (initializeJournal && process.argv.includes('--execute')) throw new Error('Provisioning and execution are separate operations.');
|
|
14
|
+
const url = validatedBaseUrl(process.env.NATIVE_TOOL_URL);
|
|
15
|
+
if (!url) throw new Error('NATIVE_TOOL_URL must be an explicit HTTPS or loopback resource.');
|
|
16
|
+
const tools = createGovernedTools({
|
|
17
|
+
config: { baseUrl: process.env.OSUITE_BASE_URL, orgId: process.env.OSUITE_ORG_ID,
|
|
18
|
+
agentId: process.env.OSUITE_AGENT_ID, runtimeId: 'sdk', provider: 'sdk',
|
|
19
|
+
apiKey: process.env.OSUITE_API_KEY, privateKeyBase64: process.env.OSUITE_PRIVATE_KEY_BASE64,
|
|
20
|
+
mode: 'enforce', signatureMode: 'required', guardFailureMode: 'block' },
|
|
21
|
+
namespace: 'native-example', journalPath: process.env.OSUITE_JOURNAL_PATH, initializeJournal,
|
|
22
|
+
bindings: { 'ledger.append': { revision: 'example-1', describe: args => ({
|
|
23
|
+
action_type: 'api', declared_goal: 'Append one synthetic native-tool example record',
|
|
24
|
+
systems_touched: [url], reversible: false,
|
|
25
|
+
input_summary: { url, method: 'POST', tool_name: 'ledger.append', payload_digest: sha256(canonicalJson(args)) },
|
|
26
|
+
}) } },
|
|
27
|
+
});
|
|
28
|
+
if (initializeJournal) {
|
|
29
|
+
tools.close();
|
|
30
|
+
console.log('Journal provisioned. No tool, network call or host installation performed.');
|
|
31
|
+
} else {
|
|
32
|
+
try {
|
|
33
|
+
await tools.run(process.env.OPERATION_ID,
|
|
34
|
+
{ name: 'ledger.append', arguments: { example: true, amount: 3 } },
|
|
35
|
+
async ({ arguments: args }) => {
|
|
36
|
+
const response = await fetch(url, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),
|
|
37
|
+
headers: { 'content-type': 'application/json' }, body: JSON.stringify(args) });
|
|
38
|
+
if (!response.ok) throw new Error('Native response was not successful.');
|
|
39
|
+
return response.json();
|
|
40
|
+
});
|
|
41
|
+
console.log(JSON.stringify(await tools.status(process.env.OPERATION_ID)));
|
|
42
|
+
} catch (error) {
|
|
43
|
+
console.error(JSON.stringify({ code: error.code || 'OUTCOME_UNKNOWN', status: error.status || null, retryAutomatically: false }));
|
|
44
|
+
process.exitCode = 1;
|
|
45
|
+
} finally { tools.close(); }
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { createPrivateKey, randomUUID } from 'node:crypto';
|
|
2
|
+
import { types } from 'node:util';
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
|
+
import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
|
|
5
|
+
import { cavaFingerprint } from '../runtime/admission.mjs';
|
|
6
|
+
import { OperationJournal } from './journal.mjs';
|
|
7
|
+
import { createStudioAuthority } from './authority.mjs';
|
|
8
|
+
import { GovernedToolError, jsonSnapshot, makeInvocation, publicStatus, reject, scopeFor } from './contract.mjs';
|
|
9
|
+
|
|
10
|
+
const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
|
|
11
|
+
function runOptions(options) {
|
|
12
|
+
if (!options || typeof options !== 'object' || types.isProxy(options)) reject('INVALID_OPTIONS');
|
|
13
|
+
const descriptors = Object.getOwnPropertyDescriptors(options);
|
|
14
|
+
if (Reflect.ownKeys(descriptors).some(key => !['waitMs', 'signal'].includes(key)
|
|
15
|
+
|| !Object.hasOwn(descriptors[key], 'value') || !descriptors[key].enumerable)) reject('INVALID_OPTIONS');
|
|
16
|
+
const waitMs = descriptors.waitMs?.value ?? 0, signal = descriptors.signal?.value;
|
|
17
|
+
if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > 600000) reject('INVALID_OPTIONS');
|
|
18
|
+
const aborted = () => {
|
|
19
|
+
if (signal === undefined) return false;
|
|
20
|
+
try { return Reflect.apply(signalAborted, signal, []); } catch { reject('INVALID_OPTIONS'); }
|
|
21
|
+
};
|
|
22
|
+
aborted();
|
|
23
|
+
return { waitMs, signal, aborted };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function checkedConfig(input) {
|
|
27
|
+
let config;
|
|
28
|
+
try { config = jsonSnapshot(input, 32768); } catch { reject('INVALID_CONFIGURATION'); }
|
|
29
|
+
if (!['enforce', 'strict'].includes(config?.mode) || config.signatureMode !== 'required'
|
|
30
|
+
|| config.guardFailureMode !== 'block' || typeof config.apiKey !== 'string' || !config.apiKey
|
|
31
|
+
|| typeof config.privateKeyBase64 !== 'string' || !config.privateKeyBase64
|
|
32
|
+
|| config.allowInsecureHttp || !validatedBaseUrl(config.baseUrl)) reject('INVALID_CONFIGURATION');
|
|
33
|
+
try { if (createPrivateKey(Buffer.from(config.privateKeyBase64, 'base64')).asymmetricKeyType !== 'rsa') throw new Error(); }
|
|
34
|
+
catch { reject('INVALID_CONFIGURATION'); }
|
|
35
|
+
return Object.freeze({ ...config, baseUrl: validatedBaseUrl(config.baseUrl), approvalWaitMs: 0 });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function registrySnapshot(bindings) {
|
|
39
|
+
if (!bindings || types.isProxy(bindings) || typeof bindings !== 'object') reject('INVALID_MAPPING');
|
|
40
|
+
const result = {};
|
|
41
|
+
for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(bindings))) {
|
|
42
|
+
if (!Object.hasOwn(descriptor, 'value') || !safeId(name) || name.length > 128) reject('INVALID_MAPPING');
|
|
43
|
+
const binding = descriptor.value;
|
|
44
|
+
if (!binding || types.isProxy(binding) || typeof binding !== 'object') reject('INVALID_MAPPING');
|
|
45
|
+
const fields = Object.getOwnPropertyDescriptors(binding);
|
|
46
|
+
if (!Object.hasOwn(fields.revision || {}, 'value') || !Object.hasOwn(fields.describe || {}, 'value')
|
|
47
|
+
|| !safeId(fields.revision.value) || fields.revision.value.length > 128
|
|
48
|
+
|| 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, describe: fields.describe.value }), enumerable: true });
|
|
50
|
+
}
|
|
51
|
+
return Object.freeze(result);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function publicError(error) {
|
|
55
|
+
if (error instanceof GovernedToolError) throw error;
|
|
56
|
+
if (error?.name === 'OperationJournalError' && /^(CONFLICT|JOURNAL_[A-Z_]+)$/.test(error.code)) reject(error.code);
|
|
57
|
+
reject('OUTCOME_UNKNOWN');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createGovernedTools({ config: rawConfig, namespace, journalPath, bindings: rawBindings,
|
|
61
|
+
journalOptions = {}, initializeJournal = false } = {}) {
|
|
62
|
+
if (Number(process.versions.node.split('.')[0]) !== 24) reject('NODE_24_REQUIRED');
|
|
63
|
+
const config = checkedConfig(rawConfig), scope = scopeFor(config, namespace), bindings = registrySnapshot(rawBindings);
|
|
64
|
+
const storage = jsonSnapshot(journalOptions);
|
|
65
|
+
if (typeof initializeJournal !== 'boolean' || !storage || Array.isArray(storage) || typeof storage !== 'object'
|
|
66
|
+
|| Object.keys(storage).some(key => !['maxOperations', 'busyTimeoutMs'].includes(key))) reject('INVALID_CONFIGURATION');
|
|
67
|
+
let journal;
|
|
68
|
+
try { journal = new OperationJournal(journalPath, { ...storage, create: initializeJournal }); } catch (error) { publicError(error); }
|
|
69
|
+
let authority;
|
|
70
|
+
try { authority = createStudioAuthority(config, journalPath); } catch { journal.close(); reject('JOURNAL_UNAVAILABLE'); }
|
|
71
|
+
let closed = false, inFlight = 0;
|
|
72
|
+
const local = operationId => journal.get(scope, operationId);
|
|
73
|
+
const status = record => publicStatus(record, config.baseUrl);
|
|
74
|
+
function stopForState(record) {
|
|
75
|
+
const codes = { completed: 'ALREADY_COMPLETED', denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' };
|
|
76
|
+
if (codes[record.state]) reject(codes[record.state], status(record));
|
|
77
|
+
if (!['prepared', 'held', 'requesting', 'uncertain_request'].includes(record.state)) reject('OUTCOME_UNKNOWN', status(record));
|
|
78
|
+
}
|
|
79
|
+
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(local(record.operationId)));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return Object.freeze({
|
|
85
|
+
async run(operationId, params, execute, options = {}) {
|
|
86
|
+
if (closed) reject('CLOSED');
|
|
87
|
+
inFlight++;
|
|
88
|
+
try {
|
|
89
|
+
const invocation = makeInvocation({ config, namespace, bindings, operationId, params });
|
|
90
|
+
if (typeof execute !== 'function' || types.isProxy(execute)) reject('INVALID_EXECUTOR');
|
|
91
|
+
const { waitMs, signal, aborted } = runOptions(options);
|
|
92
|
+
if (aborted()) reject('ABORTED');
|
|
93
|
+
const started = performance.now(), deadline = started + waitMs, owner = randomUUID();
|
|
94
|
+
let record = journal.prepare(invocation.record);
|
|
95
|
+
const waiting = () => reject('AWAITING_APPROVAL', { ...status(local(operationId)), elapsedMs: Math.round(performance.now() - started) });
|
|
96
|
+
while (true) {
|
|
97
|
+
record = local(operationId); stopForState(record);
|
|
98
|
+
if (closed) reject('CLOSED');
|
|
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));
|
|
127
|
+
}
|
|
128
|
+
let admitted;
|
|
129
|
+
try { admitted = await authority.admit(invocation, journal, owner, aborted); }
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)));
|
|
132
|
+
reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
133
|
+
}
|
|
134
|
+
if (!admitted) { if (performance.now() >= deadline) waiting(); continue; }
|
|
135
|
+
// No await or user observer between this last check, the durable fence,
|
|
136
|
+
// and invoking the original tool. This is not resource-side atomicity.
|
|
137
|
+
if (aborted() || closed || performance.now() - admitted.receivedAt > 5000) {
|
|
138
|
+
journal.settle(scope, operationId, owner, admitted.phase,
|
|
139
|
+
admitted.phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
|
|
140
|
+
reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
|
|
141
|
+
}
|
|
142
|
+
if (!journal.settle(scope, operationId, owner, admitted.phase, 'dispatching')) reject('OPERATION_BUSY', status(local(operationId)));
|
|
143
|
+
let result, resultDigest = null, state = 'completed', thrown = false;
|
|
144
|
+
try { result = await execute(invocation.params); }
|
|
145
|
+
catch { thrown = true; state = 'uncertain'; }
|
|
146
|
+
if (!thrown) {
|
|
147
|
+
if (result !== null && typeof result === 'object') {
|
|
148
|
+
if (types.isProxy(result)) state = 'uncertain';
|
|
149
|
+
else {
|
|
150
|
+
const errorFlag = Object.getOwnPropertyDescriptor(result, 'isError');
|
|
151
|
+
if (errorFlag && (!Object.hasOwn(errorFlag, 'value') || errorFlag.value !== false)) state = 'uncertain';
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const value = jsonSnapshot(result);
|
|
156
|
+
resultDigest = sha256(canonicalJson(value));
|
|
157
|
+
if (value?.isError === true) state = 'uncertain';
|
|
158
|
+
} catch { /* Opaque native returns are not serialized or independently verified. */ }
|
|
159
|
+
}
|
|
160
|
+
if (!journal.settle(scope, operationId, owner, 'dispatching', state, { resultDigest, reportState: 'uncertain' })) reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
161
|
+
let confirmed = false;
|
|
162
|
+
try { confirmed = await authority.report(local(operationId), state, resultDigest); } catch { /* Keep the observed native outcome. */ }
|
|
163
|
+
try { if (confirmed) journal.settle(scope, operationId, owner, state, state, { reportState: 'confirmed' }); }
|
|
164
|
+
catch { /* Reporting bookkeeping cannot hide a durably observed native return. */ }
|
|
165
|
+
if (thrown) reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
} catch (error) { publicError(error); }
|
|
169
|
+
finally {
|
|
170
|
+
inFlight--;
|
|
171
|
+
if (closed && inFlight === 0) journal.close();
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
async status(operationId) {
|
|
175
|
+
if (closed) reject('CLOSED');
|
|
176
|
+
if (!safeId(operationId) || operationId.length > 128) reject('INVALID_OPERATION_ID');
|
|
177
|
+
const record = local(operationId);
|
|
178
|
+
if (!record) return null;
|
|
179
|
+
const observed = await authority.read(record);
|
|
180
|
+
return Object.freeze({ ...status(record), remote: Object.freeze({ available: observed.available,
|
|
181
|
+
status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
|
|
182
|
+
},
|
|
183
|
+
close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
|
|
184
|
+
});
|
|
185
|
+
}
|