osuite 2.14.2 → 2.16.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.
@@ -7,8 +7,19 @@ import { OperationJournal } from './journal.mjs';
7
7
  import { createStudioAuthority } from './authority.mjs';
8
8
  import { GovernedToolError, jsonSnapshot, makeInvocation, publicStatus, reject, scopeFor } from './contract.mjs';
9
9
  import { recoveryAdapter, recoveryScope, makeRecoveryInvocation, observeEvidence, validateEvidence, checkRecoveryAuthority } from './recovery.mjs';
10
+ import { validUsdMapping } from './amount.mjs';
11
+ import { ownerReceiptKey, verifyOwnerReceipt } from './owner-receipt.mjs';
10
12
 
11
13
  const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
14
+ const terminalCodes = Object.freeze({ denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' });
15
+
16
+ function terminalReview(action, approval) {
17
+ if (action === 'expired' || approval === 'expired') return 'expired';
18
+ if (action === 'cancelled' || approval === 'cancelled') return 'cancelled';
19
+ if (action === 'blocked' || action === 'denied' || approval === 'denied') return 'denied';
20
+ return null;
21
+ }
22
+
12
23
  function runOptions(options) {
13
24
  if (!options || typeof options !== 'object' || types.isProxy(options)) reject('INVALID_OPTIONS');
14
25
  const descriptors = Object.getOwnPropertyDescriptors(options);
@@ -47,8 +58,30 @@ function registrySnapshot(bindings) {
47
58
  if (!Object.hasOwn(fields.revision || {}, 'value') || !Object.hasOwn(fields.describe || {}, 'value')
48
59
  || !safeId(fields.revision.value) || fields.revision.value.length > 128
49
60
  || typeof fields.describe.value !== 'function' || types.isProxy(fields.describe.value)) reject('INVALID_MAPPING');
61
+ let amount;
62
+ if (fields.amount) {
63
+ if (!Object.hasOwn(fields.amount, 'value')) reject('INVALID_MAPPING');
64
+ try { amount = jsonSnapshot(fields.amount.value, 1024); } catch { reject('INVALID_MAPPING'); }
65
+ if (!validUsdMapping(amount)) reject('INVALID_MAPPING');
66
+ }
67
+ const receipt = fields.ownerReceipt;
68
+ const delegation = fields.delegation?.value;
69
+ if (fields.delegation && (!Object.hasOwn(fields.delegation, 'value') || typeof delegation !== 'function' || types.isProxy(delegation))) reject('INVALID_MAPPING');
70
+ let ownerReceipt;
71
+ if (receipt) {
72
+ if (!Object.hasOwn(receipt, 'value') || !receipt.value || types.isProxy(receipt.value)
73
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(receipt.value))) reject('INVALID_MAPPING');
74
+ const properties = Object.getOwnPropertyDescriptors(receipt.value);
75
+ const expected = ['resourceId', 'publicKey', 'query'];
76
+ if (Reflect.ownKeys(properties).length !== expected.length
77
+ || expected.some(key => !Object.hasOwn(properties[key] || {}, 'value'))) reject('INVALID_MAPPING');
78
+ const { resourceId, publicKey, query } = Object.fromEntries(expected.map(key => [key, properties[key].value]));
79
+ const signer = ownerReceiptKey(publicKey);
80
+ if (!signer || !safeId(resourceId) || resourceId.length > 128 || typeof query !== 'function' || types.isProxy(query)) reject('INVALID_MAPPING');
81
+ ownerReceipt = Object.freeze({ resource: Object.freeze({ resource_id: resourceId, key_id: signer.id }), publicKey, query });
82
+ }
50
83
  Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value,
51
- describe: fields.describe.value, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
84
+ describe: fields.describe.value, amount, ownerReceipt, delegation, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
52
85
  }
53
86
  return Object.freeze(result);
54
87
  }
@@ -73,6 +106,24 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
73
106
  let closed = false, inFlight = 0;
74
107
  const local = operationId => journal.get(scope, operationId);
75
108
  const status = record => publicStatus(record, config.baseUrl);
109
+ async function bindDelegation(invocation) {
110
+ const authorize = bindings[invocation.params.name].delegation;
111
+ if (!authorize) return invocation;
112
+ const { context, record } = invocation;
113
+ let assertion;
114
+ try {
115
+ assertion = jsonSnapshot(await authorize(Object.freeze({
116
+ actionId: record.actionId, inputDigest: record.inputDigest, sessionId: record.sessionId,
117
+ toolUseId: record.toolUseId, operationId: record.operationId, orgId: config.orgId, agentId: config.agentId,
118
+ params: invocation.params,
119
+ actionType: context.action_type, systemsTouched: context.systems_touched || Object.freeze([]),
120
+ })), 8192);
121
+ } catch { reject('DELEGATION_REQUIRED'); }
122
+ if (assertion?.claims?.schema_version !== 'osuite.business_authority.v2' || typeof assertion.signature !== 'string') reject('DELEGATION_REQUIRED');
123
+ const boundContext = jsonSnapshot({ ...context, business_authority_assertion: assertion });
124
+ return { ...invocation, context: boundContext,
125
+ record: { ...record, contextDigest: sha256(canonicalJson(boundContext)) } };
126
+ }
76
127
  const recoveryStatus = operationId => {
77
128
  const child = journal.get(recoveryScope(scope), operationId);
78
129
  return child ? Object.freeze({ ...status(child), evidenceDigest: child.errorCode?.startsWith('recovery_')
@@ -83,8 +134,8 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
83
134
  return Object.freeze({ ...(recoveryAttempt || parent), parent, recoveryAttempt });
84
135
  };
85
136
  function stopForState(record) {
86
- const codes = { completed: 'ALREADY_COMPLETED', denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' };
87
- if (codes[record.state]) reject(codes[record.state], status(record));
137
+ if (record.state === 'completed') reject('ALREADY_COMPLETED', status(record));
138
+ if (Object.hasOwn(terminalCodes, record.state)) reject(terminalCodes[record.state], status(record));
88
139
  if (!['prepared', 'held', 'requesting', 'uncertain_request'].includes(record.state)) reject('OUTCOME_UNKNOWN', status(record));
89
140
  }
90
141
  function transitionHeld(record, next, owner) {
@@ -96,7 +147,9 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
96
147
  const { scope, operationId } = invocation.record;
97
148
  const local = operationId => {
98
149
  const record = journal.get(scope, operationId);
99
- return record && invocation.recovery ? { ...record, recovery: invocation.recovery } : record;
150
+ return record && { ...record, recovery: invocation.recovery, nativeAmount: invocation.context.native_amount,
151
+ delegationDigest: invocation.context.business_authority_assertion && sha256(canonicalJson(invocation.context.business_authority_assertion.claims)),
152
+ nativeResource: invocation.context.native_resource };
100
153
  };
101
154
  if (aborted()) reject('ABORTED');
102
155
  const started = performance.now(), deadline = started + waitMs, owner = randomUUID();
@@ -120,25 +173,23 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
120
173
  record = local(operationId);
121
174
  }
122
175
  if (!record.fingerprint || record.fingerprint !== cavaFingerprint(observed.body)) reject('BINDING_MISMATCH', status(record));
176
+ const terminal = terminalReview(action.status, observed.body.approval?.state);
177
+ if (terminal) {
178
+ transitionHeld(record, terminal, owner); stopForState(local(operationId));
179
+ }
123
180
  if (action.status === 'pending_approval') {
124
181
  if (performance.now() >= deadline) waiting();
125
182
  try { await delay(Math.min(200, deadline - performance.now()), undefined, { signal }); }
126
183
  catch { reject('ABORTED', status(record)); }
127
184
  continue;
128
185
  }
129
- if (['blocked', 'denied', 'expired', 'cancelled'].includes(action.status)
130
- || ['denied', 'expired', 'cancelled'].includes(observed.body.approval?.state)) {
131
- const state = action.status === 'expired' || observed.body.approval?.state === 'expired' ? 'expired'
132
- : action.status === 'cancelled' ? 'cancelled' : 'denied';
133
- transitionHeld(record, state, owner); stopForState(local(operationId));
134
- }
135
186
  if (action.status !== 'running' || action.timestamp_end != null || action.approval_redeemed_at != null
136
187
  || !action.approved_by || !action.approved_at) reject('OUTCOME_UNKNOWN', status(record));
137
188
  }
138
189
  let admitted;
139
190
  try { admitted = await authority.admit(invocation, journal, owner, aborted); }
140
191
  catch (error) {
141
- if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)));
192
+ if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)), error.details);
142
193
  reject('OUTCOME_UNKNOWN', status(local(operationId)));
143
194
  }
144
195
  if (!admitted) { if (performance.now() >= deadline) waiting(); continue; }
@@ -155,7 +206,8 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
155
206
  // and invoking the original tool. This is not resource-side atomicity.
156
207
  const grantExpiry = admitted.phase === 'redeeming' ? Date.parse(admitted.response.action.approval_expires_at) : Infinity;
157
208
  const ruleExpiry = admitted.ruleExpiresAt == null ? Infinity : Date.parse(admitted.ruleExpiresAt);
158
- const current = () => performance.now() < admitted.dispatchDeadline && Date.now() < Math.min(grantExpiry, ruleExpiry)
209
+ const delegationExpiry = invocation.context.business_authority_assertion ? Date.parse(invocation.context.business_authority_assertion.claims.expires_at) : Infinity;
210
+ const current = () => performance.now() < admitted.dispatchDeadline && Date.now() < Math.min(grantExpiry, ruleExpiry, delegationExpiry)
159
211
  && (!recovery || recovery.fresh());
160
212
  if (aborted() || closed || !current()) {
161
213
  journal.settle(scope, operationId, owner, admitted.phase,
@@ -208,10 +260,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
208
260
 
209
261
  return Object.freeze({
210
262
  async run(operationId, params, execute, options = {}) {
211
- return work(() => {
263
+ return work(async () => {
212
264
  const invocation = makeInvocation({ config, namespace, bindings, operationId, params });
213
265
  if (typeof execute !== 'function' || types.isProxy(execute)) reject('INVALID_EXECUTOR');
214
- return perform(invocation, execute, runOptions(options));
266
+ const settings = runOptions(options);
267
+ if (settings.aborted()) reject('ABORTED');
268
+ return perform(await bindDelegation(invocation), execute, settings);
215
269
  });
216
270
  },
217
271
  async recover(operationId, params, options = {}) {
@@ -220,11 +274,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
220
274
  const settings = runOptions(options);
221
275
  if (settings.aborted()) reject('ABORTED');
222
276
  const adapter = bindings[parent.params.name].recovery;
223
- const record = journal.getBound(parent.record);
277
+ const record = journal.getBound((await bindDelegation(parent)).record);
224
278
  if (!adapter) reject('RECOVERY_UNSUPPORTED', status(record));
225
279
  if (!record) reject('RECOVERY_UNAVAILABLE');
226
280
  if (record.state !== 'uncertain') { stopForState(record); reject('RECOVERY_UNAVAILABLE', status(record)); }
227
- const { invocation, request } = makeRecoveryInvocation(parent, adapter);
281
+ const { invocation: childInvocation, request } = makeRecoveryInvocation(parent, adapter);
282
+ const invocation = await bindDelegation(childInvocation);
228
283
  try {
229
284
  const child = journal.get(invocation.record.scope, operationId);
230
285
  if (child) {
@@ -262,14 +317,47 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
262
317
  const observed = await authority.read(record);
263
318
  let failureCode = observed.mismatch ? 'BINDING_MISMATCH' : observed.available ? null : 'CURRENT_AUTHORITY_UNAVAILABLE';
264
319
  // Refine held-call guidance without changing durable execution state.
265
- if (!failureCode && record.state === 'held'
266
- && (['blocked', 'denied', 'expired', 'cancelled'].includes(observed.action.status)
267
- || ['denied', 'expired', 'cancelled'].includes(observed.body?.approval?.state))) failureCode = 'POLICY_DENIED';
320
+ if (!failureCode && record.state === 'held') {
321
+ const terminal = terminalReview(observed.action.status, observed.body?.approval?.state);
322
+ if (terminal) failureCode = terminalCodes[terminal];
323
+ }
268
324
  const attempt = recoveryStatus(operationId);
269
- return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}), remote: Object.freeze({ available: observed.available,
325
+ return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}),
326
+ ...(observed.body?.owner_receipt ? { ownerReceipt: observed.body.owner_receipt } : {}), remote: Object.freeze({ available: observed.available,
270
327
  status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
271
328
  });
272
329
  },
330
+ async reconcile(operationId, params, options = {}) {
331
+ return work(async () => {
332
+ const invocation = makeInvocation({ config, namespace, bindings, operationId, params });
333
+ const adapter = bindings[invocation.params.name].ownerReceipt;
334
+ const localRecord = local(operationId);
335
+ if (localRecord && ['inputDigest', 'bindingDigest', 'actionId'].some(key => localRecord[key] !== invocation.record[key])) reject('CONFLICT');
336
+ if (!adapter || !localRecord) reject('OWNER_RECONCILIATION_UNAVAILABLE', status(localRecord));
337
+ const settings = runOptions(options);
338
+ const unknown = { ...status(localRecord), outcome: 'unknown' };
339
+ if (settings.aborted()) reject('ABORTED', status(localRecord));
340
+ if (!['dispatching', 'uncertain', 'completed'].includes(localRecord.state)) return unknown;
341
+ const nativeResource = invocation.context.native_resource;
342
+ const record = { ...localRecord, nativeResource, nativeAmount: invocation.context.native_amount };
343
+ const expected = Object.freeze({ ...nativeResource, org_id: config.orgId, action_id: record.actionId });
344
+ const observed = await authority.read(record);
345
+ if (!observed.available) return unknown;
346
+ const valid = receipt => verifyOwnerReceipt(receipt, expected, adapter.publicKey, { startedAt: observed.action.timestamp_start });
347
+ let receipt = observed.body.owner_receipt;
348
+ if (!valid(receipt)) {
349
+ const timeout = AbortSignal.timeout(5000);
350
+ const signal = settings.signal ? AbortSignal.any([timeout, settings.signal]) : timeout;
351
+ try { receipt = jsonSnapshot(await adapter.query({ ...expected, operationId, signal }), 8192); }
352
+ catch { return unknown; }
353
+ if (signal.aborted || !valid(receipt)) return unknown;
354
+ const submitted = receipt;
355
+ receipt = await authority.closeOwnerOutcome(record, submitted);
356
+ if (!valid(receipt) || receipt.claims.outcome !== submitted.claims.outcome) return unknown;
357
+ }
358
+ return Object.freeze({ ...status(localRecord), outcome: receipt.claims.outcome, ownerReceipt: receipt });
359
+ });
360
+ },
273
361
  close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
274
362
  });
275
363
  }
@@ -0,0 +1,40 @@
1
+ import { createPublicKey, verify } from 'node:crypto';
2
+ import { canonicalJson, isObject, safeId, sha256 } from '../runtime/protocol.mjs';
3
+
4
+ export const OWNER_RECEIPT_SCHEMA = 'osuite.native_owner_receipt.v1';
5
+ const digest = /^[a-f0-9]{64}$/;
6
+ const timestamp = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/;
7
+
8
+ function bytes(value, size) {
9
+ if (typeof value !== 'string' || value.length !== Math.ceil(size / 3) * 4) return null;
10
+ const buffer = Buffer.from(value, 'base64');
11
+ return buffer.length === size && buffer.toString('base64') === value ? buffer : null;
12
+ }
13
+
14
+ export function ownerReceiptKey(value) {
15
+ const spki = bytes(value, 44);
16
+ if (!spki) return null;
17
+ try {
18
+ const key = createPublicKey({ key: spki, format: 'der', type: 'spki' });
19
+ return key.asymmetricKeyType === 'ed25519' ? { key, id: sha256(spki) } : null;
20
+ } catch { return null; }
21
+ }
22
+
23
+ export function ownerReceiptPayload(claims) {
24
+ return Buffer.from(`${OWNER_RECEIPT_SCHEMA}\n${canonicalJson(claims)}`);
25
+ }
26
+
27
+ export function verifyOwnerReceipt(receipt, expected, publicKey, { startedAt, now = Date.now() } = {}) {
28
+ const { claims, signature } = receipt || {};
29
+ if (!isObject(receipt) || Object.keys(receipt).length !== 2 || !isObject(claims) || Object.keys(claims).length !== 11
30
+ || claims.schema_version !== OWNER_RECEIPT_SCHEMA || claims.complete !== true || claims.final !== true
31
+ || !['committed', 'absent'].includes(claims.outcome) || !safeId(claims.receipt_id)
32
+ || !['org_id', 'action_id', 'resource_id'].every(key => safeId(claims[key]) && claims[key] === expected[key])
33
+ || !['input_digest', 'key_id'].every(key => digest.test(claims[key] || '') && claims[key] === expected[key])
34
+ || !timestamp.test(claims.observed_at || '')) return false;
35
+ const date = Date.parse(claims.observed_at);
36
+ if (!Number.isFinite(date) || date > now + 30000 || (startedAt !== undefined && !(date >= Date.parse(startedAt)))) return false;
37
+ const signer = ownerReceiptKey(publicKey);
38
+ const sig = bytes(signature, 64);
39
+ return Boolean(signer?.id === claims.key_id && sig && verify(null, ownerReceiptPayload(claims), signer.key, sig));
40
+ }
@@ -46,6 +46,7 @@ export function makeRecoveryInvocation(parent, adapter) {
46
46
  const inputSummary = JSON.stringify(summary);
47
47
  if (inputSummary.length > 4000) reject('INVALID_MAPPING');
48
48
  const context = jsonSnapshot({ ...parent.context, input_summary: inputSummary,
49
+ ...(parent.context.native_amount ? { native_amount: { ...parent.context.native_amount, binding_digest: bindingDigest } } : {}),
49
50
  action_id: actionId, runtime_session_id: sessionId, tool_use_id: toolUseId });
50
51
  const invocation = Object.freeze({ params: parent.params, context, marker, recovery: linkage,
51
52
  record: Object.freeze({ ...original, scope, actionId, sessionId, toolUseId, bindingDigest,
@@ -0,0 +1,109 @@
1
+ import { sign, verify } from 'node:crypto';
2
+ import { canonicalJson, isObject, sha256 } from './runtime/protocol.mjs';
3
+ import { ownerReceiptKey, verifyOwnerReceipt } from './governed-tools/owner-receipt.mjs';
4
+
5
+ export const NATIVE_PROOF_TYPE = 'application/vnd.in-toto+json';
6
+ export const NATIVE_CHECKPOINT_TYPE = 'application/vnd.osuite.native-checkpoint+json';
7
+ export const NATIVE_CHECKPOINT_SCOPE = 'registered_native_tools';
8
+ const hex = /^[0-9a-f]{64}$/;
9
+ const actionId = /^act_[0-9a-f]{64}$/;
10
+
11
+ function pae(type, data) {
12
+ return Buffer.concat([Buffer.from(`DSSEv1 ${Buffer.byteLength(type)} ${type} ${data.length} `), data]);
13
+ }
14
+
15
+ export function signNativeEvidence(payloadType, value, signer) {
16
+ const payload = Buffer.from(canonicalJson(value));
17
+ return { payloadType, payload: payload.toString('base64'),
18
+ signatures: [{ keyid: signer.id, sig: sign(null, pae(payloadType, payload), signer.key).toString('base64') }] };
19
+ }
20
+
21
+ function open(envelope, payloadType, pin) {
22
+ if (envelope?.payloadType !== payloadType || typeof envelope.payload !== 'string' || envelope.payload.length > 1500000
23
+ || !Array.isArray(envelope.signatures) || envelope.signatures.length !== 1) return null;
24
+ if (!isObject(envelope.signatures[0])) return null;
25
+ const { keyid, sig } = envelope.signatures[0];
26
+ if (!pin || keyid !== pin.id || typeof sig !== 'string' || sig.length !== 88) return null;
27
+ try {
28
+ const data = Buffer.from(envelope.payload, 'base64'), signature = Buffer.from(sig, 'base64');
29
+ if (data.toString('base64') !== envelope.payload || signature.length !== 64 || signature.toString('base64') !== sig
30
+ || !verify(null, pae(payloadType, data), pin.key, signature)) return null;
31
+ const value = JSON.parse(data);
32
+ if (!isObject(value) || !Buffer.from(canonicalJson(value)).equals(data)) return null;
33
+ return { value, digest: sha256(data) };
34
+ } catch { return null; }
35
+ }
36
+
37
+ export function nativeProofRoot(entries) {
38
+ const ordered = [...entries].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
39
+ return sha256(canonicalJson([NATIVE_CHECKPOINT_SCOPE, ordered]));
40
+ }
41
+
42
+ function validDelegation(predicate, issuers) {
43
+ const authority = predicate.business_authority;
44
+ if (authority?.schema_version !== 'osuite.business_authority.v2') return true;
45
+ const assertion = authority.delegation_assertion;
46
+ const claims = assertion?.claims;
47
+ if (claims?.schema_version !== authority.schema_version || claims.kind !== 'delegated'
48
+ || claims.org_id !== predicate.org_id || claims.principal_org_id !== predicate.org_id
49
+ || claims.agent_id !== predicate.agent_id || claims.action_id !== predicate.action_id || claims.input_digest !== predicate.input_digest
50
+ || !Array.isArray(claims.reviewer_roles) || !Array.isArray(predicate.approval_receipts)
51
+ || !(Date.parse(claims.not_before) <= Date.parse(predicate.timestamp_start) && Date.parse(predicate.timestamp_start) < Date.parse(claims.expires_at))) return false;
52
+ const pin = Array.isArray(issuers) && issuers.filter(root => root?.id === claims.issuer_id && root?.org_id === claims.org_id);
53
+ const issuer = pin?.length === 1 ? ownerReceiptKey(pin[0].public_key) : null;
54
+ if (!issuer || issuer.id !== authority.issuer_key_fingerprint || sha256(canonicalJson(claims)) !== authority.assertion_digest
55
+ || typeof assertion.signature !== 'string' || assertion.signature.length !== 88) return false;
56
+ const signature = Buffer.from(assertion.signature, 'base64');
57
+ if (signature.length !== 64 || signature.toString('base64') !== assertion.signature
58
+ || !verify(null, Buffer.from(`${claims.schema_version}\n${canonicalJson(claims)}`), issuer.key, signature)) return false;
59
+ const { credential_id, ...projected } = claims;
60
+ if (Object.entries(projected).some(([name, value]) => canonicalJson(authority[name]) !== canonicalJson(value))) return false;
61
+ return predicate.approval_receipts.filter(receipt => receipt?.source === 'workspace').every(receipt => {
62
+ const review = receipt.reviewer_authority;
63
+ return review?.org_id === predicate.org_id && review.grant_id === claims.grant_id && review.input_digest === predicate.input_digest
64
+ && review.executor_agent_id === predicate.agent_id && review.assertion_digest === authority.assertion_digest
65
+ && claims.reviewer_roles.includes(review.role) && receipt.action_id === predicate.action_id;
66
+ });
67
+ }
68
+
69
+ export function verifyNativeProofCohort(records, roots, checkpoint) {
70
+ const fail = code => ({ verified: false, code });
71
+ const proofKey = ownerReceiptKey(roots?.proof), checkpointKey = ownerReceiptKey(roots?.checkpoint);
72
+ if (!proofKey || !checkpointKey || proofKey.id === checkpointKey.id || !Array.isArray(roots.owners)) return fail('INVALID_TRUST_ROOTS');
73
+ const opened = open(checkpoint, NATIVE_CHECKPOINT_TYPE, checkpointKey);
74
+ const scope = opened?.value;
75
+ const from = Date.parse(scope?.from), to = Date.parse(scope?.to);
76
+ if (scope?.schema_version !== 'osuite.native_checkpoint.v1' || scope.scope !== NATIVE_CHECKPOINT_SCOPE
77
+ || typeof scope.org_id !== 'string' || !scope.org_id || !(from < to) || !hex.test(scope.root || '')
78
+ || !Number.isSafeInteger(scope.count) || scope.count < 0 || scope.count > 1000) return fail('INVALID_CHECKPOINT');
79
+ if (!Array.isArray(records) || records.length !== scope.count) return fail('INCOMPLETE_COHORT');
80
+
81
+ const seen = new Map();
82
+ const outcomes = { committed: 0, absent: 0, unknown: 0 };
83
+ for (const record of records) {
84
+ const decoded = open(record?.dsse_envelope, NATIVE_PROOF_TYPE, proofKey);
85
+ const statement = decoded?.value, p = statement?.predicate, subject = statement?.subject;
86
+ const created = Date.parse(p?.created_at);
87
+ if (!decoded || record.schema_version !== 'osuite.native_proof.v1' || decoded.digest !== record.payload_sha256
88
+ || statement._type !== 'https://in-toto.io/Statement/v1' || statement.predicateType !== 'https://osuite.ai/attestations/native-tool/v1'
89
+ || !Array.isArray(subject) || subject.length !== 1 || subject[0]?.name !== p?.action_id || !hex.test(subject[0]?.digest?.sha256 || '')
90
+ || !actionId.test(p?.action_id || '') || p.org_id !== scope.org_id || !(created >= from && created < to)
91
+ || !hex.test(p.input_digest || '') || !hex.test(p.binding_digest || '') || !['committed', 'absent', 'unknown'].includes(p.outcome)) return fail('INVALID_RECORD');
92
+ if (seen.has(p.action_id)) return fail('DUPLICATE_RECORD');
93
+ if (!validDelegation(p, roots.issuers)) return fail('INVALID_DELEGATION');
94
+ if (p.outcome === 'unknown') {
95
+ if (p.owner_receipt !== null) return fail('INVALID_OWNER_RECEIPT');
96
+ } else {
97
+ const resource = p.native_resource;
98
+ const pins = roots.owners.filter(root => root && resource && root.resource_id === resource.resource_id
99
+ && ownerReceiptKey(root.public_key)?.id === resource.key_id);
100
+ if (!resource || resource.input_digest !== p.input_digest || pins.length !== 1 || [proofKey.id, checkpointKey.id].includes(resource.key_id)
101
+ || p.owner_receipt?.claims?.outcome !== p.outcome || !verifyOwnerReceipt(p.owner_receipt,
102
+ { ...resource, org_id: p.org_id, action_id: p.action_id }, pins[0].public_key, { startedAt: p.timestamp_start })) return fail('INVALID_OWNER_RECEIPT');
103
+ }
104
+ seen.set(p.action_id, decoded.digest);
105
+ outcomes[p.outcome]++;
106
+ }
107
+ if (nativeProofRoot(seen) !== scope.root) return fail('CHECKPOINT_MISMATCH');
108
+ return { verified: true, count: seen.size, outcomes };
109
+ }
package/nativeDoctor.mjs CHANGED
@@ -1,8 +1,6 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
- import { statSync } from 'node:fs';
3
- import path from 'node:path';
4
2
  import { inspectCredentialFile, readCredentialFile } from './credentials.js';
5
- import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity } from './installationIdentity.js';
3
+ import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity, readMcpMigration } from './installationIdentity.js';
6
4
  import { loadRuntimeConfig } from './runtime/config.mjs';
7
5
  import { createApiClient, safeId, validatedBaseUrl } from './runtime/protocol.mjs';
8
6
  import { resolveRemotePosture } from './runtime/posture.mjs';
@@ -34,10 +32,11 @@ export function loadNativeDoctorConfig({ projectRoot = process.cwd(), runtime, s
34
32
  const checks = files.map(file => inspectCredentialFile(projectRoot, file));
35
33
  if (checks.some(check => !check.safe)) fail('UNSAFE_CREDENTIALS');
36
34
  if (checks.some(check => check.exists && /\.connect\.(json|lock)$/.test(check.relativePath))) fail('CONNECTION_RECOVERY_PENDING');
37
- if (checks.at(-1).exists) fail('MCP_MIGRATION_PENDING');
38
- if (checks[0].exists && statSync(path.join(projectRoot, envPath)).size > 65536) fail('INVALID_CREDENTIAL_FILE');
35
+ if (checks.at(-1).exists) {
36
+ if (readMcpMigration(projectRoot).manifest) fail('MCP_MIGRATION_PENDING');
37
+ }
39
38
  parseInstallationIdentity(readCredentialFile(projectRoot, `${envPath}.identity.json`), runtime);
40
- const raw = readCredentialFile(projectRoot, envPath);
39
+ const raw = readCredentialFile(projectRoot, envPath, { maxBytes: 65536 });
41
40
  // Choose one complete bundle. Never borrow a missing field from another lane.
42
41
  const source = raw === null ? shellEnv : parse(raw);
43
42
  for (const [name, value] of Object.entries(source)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.14.2",
3
+ "version": "2.16.0",
4
4
  "description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -23,6 +23,12 @@
23
23
  "./governed-tools": {
24
24
  "import": "./governed-tools.mjs"
25
25
  },
26
+ "./native-proof": {
27
+ "import": "./native-proof.mjs"
28
+ },
29
+ "./experimental/business-evidence": {
30
+ "import": "./business-evidence.mjs"
31
+ },
26
32
  "./controlled-transfers": {
27
33
  "import": "./controlled-transfers.mjs"
28
34
  }
@@ -36,10 +42,13 @@
36
42
  "tryContract.js",
37
43
  "runtime/",
38
44
  "governed-tools.mjs",
45
+ "native-proof.mjs",
39
46
  "governed-tools/*.mjs",
40
47
  "governed-tools/examples/*.mjs",
41
48
  "GOVERNED_TOOLS.md",
42
49
  "GOVERNED_RECOVERY.md",
50
+ "business-evidence.mjs",
51
+ "BUSINESS_EVIDENCE.md",
43
52
  "controlled-transfers.mjs",
44
53
  "controlled-transfers-stdio.mjs",
45
54
  "controlled-transfers/*.mjs",
@@ -47,6 +56,8 @@
47
56
  "matoiDoctor.mjs",
48
57
  "nativeDoctor.mjs",
49
58
  "projectHooks.js",
59
+ "codexTrust.mjs",
60
+ "codexExec.mjs",
50
61
  "reviewSurface.js",
51
62
  "osuite.js",
52
63
  "index.cjs",
package/projectHooks.js CHANGED
@@ -6,8 +6,11 @@ import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import { spawn } from 'node:child_process';
8
8
  import { fileURLToPath } from 'node:url';
9
+ import { inspectCredentialFile, readCredentialFile } from './runtime/credentials.mjs';
9
10
 
10
11
  const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop|session)\.(?:py|mjs)/;
12
+ const CODEX_RUNTIME_TAG = / --osuite-hook-version=[a-f0-9]{16}$/;
13
+ const withoutCodexTag = command => String(command || '').replace(CODEX_RUNTIME_TAG, '');
11
14
 
12
15
  export const RUNTIME_HOOKS = {
13
16
  claude: {
@@ -112,6 +115,12 @@ export function mergeHookSettings(existingText, templateText) {
112
115
  const requested = (Array.isArray(groups) ? groups : []).flatMap(group => group.hooks || []);
113
116
  const next = current.map(group => ({ ...group, hooks: (group.hooks || []).map(existing => {
114
117
  const replacement = requested.find(hook => sameHook(existing, hook));
118
+ if (replacement && CODEX_RUNTIME_TAG.test(replacement.command) && existing.command !== replacement.command
119
+ && withoutCodexTag(existing.command) === withoutCodexTag(replacement.command)
120
+ && (existing.commandWindows === undefined || withoutCodexTag(existing.commandWindows) === withoutCodexTag(replacement.commandWindows))) {
121
+ migrated.push({ event, matcher: group.matcher, command: replacement.command });
122
+ return { ...existing, command: replacement.command, commandWindows: replacement.commandWindows };
123
+ }
115
124
  if (!replacement || !hookScriptName(existing.command).endsWith('.py') || !hookScriptName(replacement.command).endsWith('.mjs')) return existing;
116
125
  const script = hookScriptName(existing.command);
117
126
  const stock = [`python3 .claude/hooks/${script}`, `python3 .codex/hooks/${script}`,
@@ -236,12 +245,19 @@ export function buildNodeRuntimeBootstrap(runtime, bootstrap = {}, { projectRoot
236
245
  const shellQuote = value => `'${String(value).replace(/'/g, "'\\''")}'`;
237
246
  const events = { PreToolUse: 'pretool', PostToolUse: 'posttool', SessionStart: 'session', Stop: 'stop' };
238
247
  const settings = { hooks: {} };
248
+ const runtimeHash = crypto.createHash('sha256').update(JSON.stringify(Object.entries(files)
249
+ .filter(([name]) => name.startsWith(`${directory}/runtime/`)))).digest('hex');
239
250
  for (const [event, script] of Object.entries(events)) {
240
251
  files[`${directory}/hooks/osuite_${script}.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runHookCli } from '../runtime/hook.mjs';\nawait runHookCli({ host: ${literal(host)}, runtimeId: ${literal(runtimeId)}, installDir: fileURLToPath(new URL('..', import.meta.url)), event: ${literal(event)} });\n`;
241
252
  const absolute = path.join(path.resolve(projectRoot), directory, `hooks/osuite_${script}.mjs`);
242
253
  const handler = { type: 'command', command: `node ${shellQuote(absolute)}`, timeout: 60 };
243
254
  if (host === 'claude' && event === 'PreToolUse') handler.onFailure = 'block';
244
- if (host === 'codex') handler.commandWindows = `node "${absolute.replace(/"/g, '""')}"`;
255
+ if (host === 'codex') {
256
+ const hash = crypto.createHash('sha256').update(runtimeHash).update(files[`${directory}/hooks/osuite_${script}.mjs`]).digest('hex').slice(0, 16);
257
+ const tag = ` --osuite-hook-version=${hash}`;
258
+ handler.command += tag;
259
+ handler.commandWindows = `node "${absolute.replace(/"/g, '""')}"${tag}`;
260
+ }
245
261
  settings.hooks[event] = [{ hooks: [handler] }];
246
262
  }
247
263
  if (host === 'claude') settings.hooks.PostToolUseFailure = settings.hooks.PostToolUse;
@@ -632,7 +648,7 @@ function managedFileStatus(projectRoot, relativePath, expected) {
632
648
  function isManagedHookCommand(command, projectRoot, relativePath) {
633
649
  if (typeof command !== 'string') return false;
634
650
  const executable = relativePath.endsWith('.py') ? 'python3' : 'node';
635
- const text = command.trim();
651
+ const text = (relativePath.startsWith('.codex/') ? withoutCodexTag(command) : command).trim();
636
652
  // Recognize the former stock Codex template without evaluating its substitution.
637
653
  if (relativePath.startsWith('.codex/') && executable === 'python3'
638
654
  && text === `python3 "$(git rev-parse --show-toplevel)/${relativePath}"`) return true;
@@ -825,7 +841,8 @@ export function parseDotenv(body) {
825
841
 
826
842
  /** The credentials the installed hook will use: shell values first, then its own .env. */
827
843
  export function hookCredentials(projectRoot, installation, shellEnv = process.env) {
828
- const dotenv = parseDotenv(readIfExists(path.join(projectRoot, installation.installDir, '.env')));
844
+ const relativePath = `${installation.installDir}/.env`;
845
+ const dotenv = parseDotenv(readCredentialFile(projectRoot, relativePath, { maxBytes: 65536 }));
829
846
  const env = { ...dotenv };
830
847
  Object.entries(shellEnv || {}).forEach(([key, value]) => {
831
848
  if (value !== undefined) env[key] = value;
@@ -833,7 +850,7 @@ export function hookCredentials(projectRoot, installation, shellEnv = process.en
833
850
  return {
834
851
  baseUrl: String(env.OSUITE_BASE_URL || env.DASHCLAW_BASE_URL || '').replace(/\/$/, ''),
835
852
  apiKey: String(env.OSUITE_API_KEY || env.DASHCLAW_API_KEY || ''),
836
- envFile: `${installation.installDir}/.env`,
853
+ envFile: inspectCredentialFile(projectRoot, relativePath).storagePath,
837
854
  hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || (installation.runtime === 'cursor' ? 'observe' : 'enforce')),
838
855
  };
839
856
  }
@@ -1019,6 +1036,13 @@ export async function runHookCheck({
1019
1036
  const nodeHook = /\bosuite_pretool\.mjs\b/.test(installation.pretool.command);
1020
1037
  const preflightModes = seen.filter((event) => event.event_type === 'tool_preflight')
1021
1038
  .map((event) => event.payload?.hook_mode).filter((mode) => ['observe', 'enforce', 'strict'].includes(mode));
1039
+ const postureEvent = seen.find(event => event.event_type === 'tool_preflight' && event.payload?.runtime_posture);
1040
+ if (postureEvent) {
1041
+ const observed = postureEvent.payload.runtime_posture;
1042
+ const approval = seen.find(event => ['tool_requires_approval', 'install_check_policy_result'].includes(event.event_type));
1043
+ state.posture = { ...observed, approval_required: Boolean(approval && observed.effective_mode !== 'observe') };
1044
+ steps.push({ ok: true, label: 'Runtime posture', detail: JSON.stringify(state.posture) });
1045
+ }
1022
1046
  const observing = (!preflightModes.length && credentials.hookMode === 'observe') || seen.some((event) => (
1023
1047
  event.payload?.hook_mode === 'observe' || event.payload?.observe_only === true
1024
1048
  || String(event.payload?.decision || '').startsWith('observe_')