osuite 2.10.2 → 2.11.1
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 +210 -0
- package/README.md +52 -12
- package/cli.js +19 -3
- package/governed-tools/authority.mjs +134 -0
- package/governed-tools/contract.mjs +170 -0
- package/governed-tools/examples/native-client.mjs +47 -0
- package/governed-tools/executor.mjs +190 -0
- package/governed-tools/journal.mjs +448 -0
- package/governed-tools/mcp.mjs +95 -0
- package/governed-tools.mjs +10 -0
- package/package.json +8 -1
- package/projectHooks.js +150 -5
- package/runtime/admission.mjs +15 -8
- package/runtime/config.mjs +1 -1
- package/runtime/hook.mjs +36 -12
- package/runtime/mcp.mjs +30 -13
- package/runtime/posture.mjs +111 -26
- package/runtime/protocol.mjs +23 -3
|
@@ -0,0 +1,170 @@
|
|
|
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
|
+
const recoveryMessages = Object.freeze({
|
|
11
|
+
review_same_operation: 'Open the existing review URL. Resume with the same operation ID and unchanged arguments only after review; current authority is checked again. Status reads never execute the tool.',
|
|
12
|
+
read_business_result: 'This operation already completed. Read the original result from your application store; OSuite retains its digest, not the full output. Do not send the tool call again.',
|
|
13
|
+
reconcile_without_resend: 'Keep the operation ID and journal. Read the existing action and resource evidence with an authorized operator; an unknown or mismatched result is not proof that nothing executed. Do not resend.',
|
|
14
|
+
restore_connection: 'Restore the correct connection and current credentials, then read status for the same operation ID. Do not replace its ID or clear its journal to work around rejection.',
|
|
15
|
+
repair_journal: 'Preserve the journal and stop new sends. Ask an operator to inspect storage permissions, capacity and verified backups; never reinitialize a missing journal on the restart path.',
|
|
16
|
+
check_current_authority: 'Keep the same operation ID and arguments. A call must pass fresh authority checks before execution; this local status is not permission to execute.',
|
|
17
|
+
stop: 'This operation is denied, expired or cancelled. Stop and consult the policy owner. Changing its ID is not a way to bypass that decision.',
|
|
18
|
+
inspect_configuration: 'Check the supported runtime, input, mapping and connection configuration. Keep any existing operation ID and journal; do not automatically repeat a possibly sent call.',
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
function recoveryGuidance(code, state) {
|
|
22
|
+
let nextStep;
|
|
23
|
+
if (code === 'ALREADY_COMPLETED' || (state === 'completed' && code !== 'BINDING_MISMATCH')) nextStep = 'read_business_result';
|
|
24
|
+
else if (['OUTCOME_UNKNOWN', 'UNCERTAIN', 'BINDING_MISMATCH', 'CONFLICT'].includes(code)) nextStep = 'reconcile_without_resend';
|
|
25
|
+
else if (code?.startsWith('JOURNAL_')) nextStep = 'repair_journal';
|
|
26
|
+
else if (code === 'CURRENT_AUTHORITY_UNAVAILABLE') nextStep = 'restore_connection';
|
|
27
|
+
else if (['POLICY_DENIED', 'APPROVAL_EXPIRED', 'CANCELLED'].includes(code)
|
|
28
|
+
|| ['denied', 'expired', 'cancelled'].includes(state)) nextStep = 'stop';
|
|
29
|
+
else if (code === 'AWAITING_APPROVAL' || (!code && state === 'held')) nextStep = 'review_same_operation';
|
|
30
|
+
else if (['requesting', 'redeeming', 'dispatching', 'uncertain', 'uncertain_request', 'uncertain_redemption'].includes(state)) nextStep = 'reconcile_without_resend';
|
|
31
|
+
else if (!code && state === 'prepared') nextStep = 'check_current_authority';
|
|
32
|
+
else nextStep = 'inspect_configuration';
|
|
33
|
+
return Object.freeze({ nextStep, preserveOperationId: true, message: recoveryMessages[nextStep] });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class GovernedToolError extends Error {
|
|
37
|
+
constructor(code, status = null) {
|
|
38
|
+
const recovery = recoveryGuidance(code, status?.state);
|
|
39
|
+
super(`OSuite ${code}: ${recovery.message}`);
|
|
40
|
+
this.name = 'GovernedToolError';
|
|
41
|
+
this.code = code;
|
|
42
|
+
this.status = status === null ? null : Object.freeze({ ...status, recovery });
|
|
43
|
+
this.retryAutomatically = false;
|
|
44
|
+
this.recovery = recovery;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function reject(code, status) { throw new GovernedToolError(code, status); }
|
|
48
|
+
|
|
49
|
+
// Validate descriptors before reading values: JSON.stringify alone can invoke
|
|
50
|
+
// accessors/toJSON or quietly change undefined, non-finite numbers and arrays.
|
|
51
|
+
export function jsonSnapshot(input, maxBytes = 65536) {
|
|
52
|
+
const ancestors = new Set();
|
|
53
|
+
let nodes = 0;
|
|
54
|
+
function copy(value, depth) {
|
|
55
|
+
if (++nodes > 8192 || depth > 16) reject('INVALID_INPUT');
|
|
56
|
+
if (value === null || typeof value === 'boolean') return value;
|
|
57
|
+
if (typeof value === 'string') {
|
|
58
|
+
if (value.length > maxBytes || !value.isWellFormed()) reject('INVALID_INPUT');
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
if (typeof value === 'number') {
|
|
62
|
+
if (!Number.isFinite(value) || Object.is(value, -0)) reject('INVALID_INPUT');
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
if (typeof value !== 'object' || types.isProxy(value) || ancestors.has(value)) reject('INVALID_INPUT');
|
|
66
|
+
const array = Array.isArray(value), prototype = Object.getPrototypeOf(value);
|
|
67
|
+
if (prototype !== (array ? Array.prototype : Object.prototype) && !(prototype === null && !array)) reject('INVALID_INPUT');
|
|
68
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
69
|
+
const keys = Reflect.ownKeys(descriptors);
|
|
70
|
+
if (keys.some(key => typeof key !== 'string' || unsafeKeys.has(key)
|
|
71
|
+
|| !Object.hasOwn(descriptors[key], 'value') || (!descriptors[key].enumerable && !(array && key === 'length')))) reject('INVALID_INPUT');
|
|
72
|
+
if (array && (value.length > 8192 || keys.length !== value.length + 1
|
|
73
|
+
|| keys.some(key => key !== 'length' && !/^(0|[1-9][0-9]*)$/.test(key)))) reject('INVALID_INPUT');
|
|
74
|
+
ancestors.add(value);
|
|
75
|
+
const result = array ? [] : {};
|
|
76
|
+
for (const key of keys) {
|
|
77
|
+
if (array && key === 'length') continue;
|
|
78
|
+
if (!key.isWellFormed()) reject('INVALID_INPUT');
|
|
79
|
+
result[key] = copy(descriptors[key].value, depth + 1);
|
|
80
|
+
}
|
|
81
|
+
ancestors.delete(value);
|
|
82
|
+
return Object.freeze(result);
|
|
83
|
+
}
|
|
84
|
+
const snapshot = copy(input, 0);
|
|
85
|
+
if (Buffer.byteLength(canonicalJson(snapshot)) > maxBytes) reject('INVALID_INPUT');
|
|
86
|
+
return snapshot;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function scopeFor(config, namespace) {
|
|
90
|
+
const base = validatedBaseUrl(config?.baseUrl);
|
|
91
|
+
if (!base || !id(config.orgId) || !id(config.agentId) || !id(config.runtimeId) || !id(namespace)
|
|
92
|
+
|| (config.provider != null && !id(config.provider))) reject('INVALID_CONFIGURATION');
|
|
93
|
+
return sha256(canonicalJson({ origin: base, org: config.orgId, agent: config.agentId,
|
|
94
|
+
runtime: config.runtimeId, provider: config.provider || null, namespace }));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const strings = { action_type: 128, declared_goal: 2000, authorization_scope: 1000,
|
|
98
|
+
data_classification: 64, data_residency_region: 128 };
|
|
99
|
+
const booleans = new Set(['reversible', 'privacy_review_required', 'data_minimization_declared', 'cross_border_transfer']);
|
|
100
|
+
const numbers = new Set(['risk_score', 'personal_data_likelihood']);
|
|
101
|
+
const arrays = new Set(['systems_touched', 'sensitive_data_categories', 'external_data_processors']);
|
|
102
|
+
const allowed = new Set([...Object.keys(strings), ...booleans, ...numbers, ...arrays, 'input_summary']);
|
|
103
|
+
|
|
104
|
+
function describe(binding, args) {
|
|
105
|
+
let value;
|
|
106
|
+
try { value = jsonSnapshot(binding.describe(args), 6000); } catch { reject('INVALID_MAPPING'); }
|
|
107
|
+
if (!value || Array.isArray(value) || typeof value !== 'object'
|
|
108
|
+
|| Object.keys(value).some(key => !allowed.has(key)) || !value.action_type || !value.declared_goal) reject('INVALID_MAPPING');
|
|
109
|
+
for (const [key, item] of Object.entries(value)) {
|
|
110
|
+
if (strings[key] && (typeof item !== 'string' || !item.trim() || item.length > strings[key])) reject('INVALID_MAPPING');
|
|
111
|
+
if (booleans.has(key) && typeof item !== 'boolean') reject('INVALID_MAPPING');
|
|
112
|
+
if (numbers.has(key) && (!Number.isSafeInteger(item) || item < 0 || item > 100)) reject('INVALID_MAPPING');
|
|
113
|
+
if (arrays.has(key) && (!Array.isArray(item) || item.length > 20
|
|
114
|
+
|| item.some(entry => typeof entry !== 'string' || entry.length > 500))) reject('INVALID_MAPPING');
|
|
115
|
+
}
|
|
116
|
+
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'))) reject('INVALID_MAPPING');
|
|
118
|
+
return value;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function makeInvocation({ config, namespace, bindings, operationId, params }) {
|
|
122
|
+
const scope = scopeFor(config, namespace);
|
|
123
|
+
if (!id(operationId)) reject('INVALID_OPERATION_ID');
|
|
124
|
+
const native = jsonSnapshot(params, 32768);
|
|
125
|
+
if (!native || Array.isArray(native) || !id(native.name) || !Object.hasOwn(native, 'arguments')
|
|
126
|
+
|| Object.keys(native).some(key => !['name', 'arguments'].includes(key))) reject('INVALID_INPUT');
|
|
127
|
+
if (!bindings || !Object.hasOwn(bindings, native.name)) reject('UNSUPPORTED_TOOL');
|
|
128
|
+
const binding = bindings[native.name];
|
|
129
|
+
if (!binding || !id(binding.revision) || typeof binding.describe !== 'function') reject('INVALID_MAPPING');
|
|
130
|
+
const description = describe(binding, native.arguments);
|
|
131
|
+
// The historical Hook helper normalizes null to {}. Native calls must retain
|
|
132
|
+
// every JSON value exactly, including that distinction.
|
|
133
|
+
const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
|
|
134
|
+
const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description }));
|
|
135
|
+
const identity = sha256(canonicalJson([scope, operationId]));
|
|
136
|
+
const actionId = `act_${identity}`, sessionId = `sess_${identity}`, toolUseId = `tool_${identity}`;
|
|
137
|
+
const marker = { schema_version: CALL_SCHEMA, operation_digest: sha256(operationId), input_digest: inputDigest, binding_digest: bindingDigest };
|
|
138
|
+
const inputSummary = JSON.stringify({ ...description.input_summary, osuite_native_call: marker });
|
|
139
|
+
if (inputSummary.length > 4000) reject('INVALID_MAPPING');
|
|
140
|
+
const context = jsonSnapshot({ ...description, input_summary: inputSummary, action_id: actionId,
|
|
141
|
+
agent_id: config.agentId, runtime_session_id: sessionId, tool_use_id: toolUseId,
|
|
142
|
+
tool_input_digest: inputDigest, runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper' });
|
|
143
|
+
return Object.freeze({ params: native, context, marker, record: Object.freeze({ scope, operationId,
|
|
144
|
+
inputDigest, bindingDigest, contextDigest: sha256(canonicalJson(context)), actionId, sessionId, toolUseId }) });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function matchesStoredAction(payload, record, config) {
|
|
148
|
+
try {
|
|
149
|
+
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
|
+
const envelope = action?.action_envelope;
|
|
153
|
+
return action?.action_id === record.actionId && action.agent_id === config.agentId
|
|
154
|
+
&& action.org_id === config.orgId && action.verified === true
|
|
155
|
+
&& (!payload.action_id || payload.action_id === record.actionId)
|
|
156
|
+
&& envelope?.runtime_session_id === record.sessionId
|
|
157
|
+
&& marker?.schema_version === CALL_SCHEMA && marker.operation_digest === sha256(record.operationId)
|
|
158
|
+
&& marker.input_digest === record.inputDigest && marker.binding_digest === record.bindingDigest;
|
|
159
|
+
} catch { return false; }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function publicStatus(record, baseUrl, failureCode = null) {
|
|
163
|
+
if (!record) return null;
|
|
164
|
+
return Object.freeze({ operationId: record.operationId, actionId: record.actionId, state: record.state,
|
|
165
|
+
resultDigest: record.resultDigest || null, reportState: record.reportState,
|
|
166
|
+
reviewUrl: `${baseUrl}/approvals?action=${encodeURIComponent(record.actionId)}`,
|
|
167
|
+
replayUrl: `${baseUrl}/replay/${encodeURIComponent(record.actionId)}`,
|
|
168
|
+
admissionPath: ADMISSION_PATH, coverage: COVERAGE, retryAutomatically: false,
|
|
169
|
+
resultRetained: false, recovery: recoveryGuidance(failureCode, record.state) });
|
|
170
|
+
}
|
|
@@ -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,190 @@
|
|
|
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
|
+
let failureCode = observed.mismatch ? 'BINDING_MISMATCH' : observed.available ? null : 'CURRENT_AUTHORITY_UNAVAILABLE';
|
|
181
|
+
// Refine held-call guidance without changing durable execution state.
|
|
182
|
+
if (!failureCode && record.state === 'held'
|
|
183
|
+
&& (['blocked', 'denied', 'expired', 'cancelled'].includes(observed.action.status)
|
|
184
|
+
|| ['denied', 'expired', 'cancelled'].includes(observed.body?.approval?.state))) failureCode = 'POLICY_DENIED';
|
|
185
|
+
return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), remote: Object.freeze({ available: observed.available,
|
|
186
|
+
status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
|
|
187
|
+
},
|
|
188
|
+
close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
|
|
189
|
+
});
|
|
190
|
+
}
|