osuite 2.15.0 → 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.
package/GOVERNED_TOOLS.md CHANGED
@@ -85,6 +85,66 @@ the mapping, not that the mapping is semantically complete. Studio still owns
85
85
  the allow/hold/deny decision. Do not put secrets in `input_summary`: that bounded
86
86
  description is sent to Studio even though full native arguments stay local.
87
87
 
88
+ For a USD tool that takes integer cents, configure the binding with
89
+ `amount: { currency: 'USD', unit: 'minor', path: ['amount_cents'] }`. `path`
90
+ selects a field in the original JSON arguments and can include nested keys.
91
+ The wrapper signs the integer cents, field path, mapping revision and native
92
+ input digest in both governance requests. Studio uses this evidence for
93
+ `amount_usd` threshold policies. `input_summary` can display the amount. If it
94
+ also specifies `amount_cents`, `amount_usd` or `currency`, the values must agree
95
+ with the mapping. Tool variants without a positive amount can run only when
96
+ their policies permit an action without amount evidence. Whole-CAD refunds
97
+ continue to use the exact `refund.create` mapping.
98
+
99
+ ### Reconcile With The Resource Owner
100
+
101
+ Bind `ownerReceipt: { resourceId, publicKey, query }` to the tool. `publicKey`
102
+ is the resource owner's Ed25519 SPKI DER encoded as base64. A workspace admin
103
+ pins the same key for `resourceId` in the `NATIVE_RESOURCE_OWNERS` setting,
104
+ an array of `{ resource_id, public_key }` entries. The owner should keep its
105
+ signing key separate from OSuite and the executing agent.
106
+
107
+ After a dropped reply or restart, call `tools.reconcile(operationId, params)`
108
+ with the same operation and arguments. `query` receives `operationId`, a
109
+ timeout signal and the signed receipt scope (`org_id`, `action_id`,
110
+ `input_digest`, `resource_id`, `key_id`). It performs the resource owner's
111
+ authenticated lookup and returns `{ claims, signature }`. The claims contain
112
+ that scope, `schema_version: 'osuite.native_owner_receipt.v1'`, `receipt_id`,
113
+ UTC `observed_at`, `complete: true`, `final: true` and `outcome` (`committed`
114
+ or `absent`). The signature is base64 Ed25519 over the schema version, a newline
115
+ and the canonical JSON claims. An `absent` receipt requires a complete scoped
116
+ read and a fence against a later submission for that action. The SDK returns
117
+ `unknown` while the receipt is incomplete, untrusted or unavailable. The
118
+ journal continues to prevent a second execution.
119
+
120
+ Studio's `GET /api/proof/export?format=native&action_id=…` returns a signed
121
+ native proof. Use `from` and `to` in UTC in place of `action_id` for a cohort
122
+ and `format=native-checkpoint` for its independently obtained checkpoint.
123
+ The window includes registered, verified native actions by creation time.
124
+ Studio reads `OSUITE_NATIVE_PROOF_SIGNING_KEY` and
125
+ `OSUITE_NATIVE_CHECKPOINT_SIGNING_KEY` as separately provisioned base64
126
+ Ed25519 PKCS8 DER keys. Give the reviewer the public keys through a trusted
127
+ channel along with the pinned owner keys. `verifyNativeProofCohort` from
128
+ `osuite/native-proof` verifies the signed records and checkpoint offline and
129
+ counts committed, absent and unknown outcomes.
130
+
131
+ ### Delegated Calls
132
+
133
+ Set `delegation: async intent => issuer.authorize(intent)` on a native tool
134
+ binding. The callback receives the frozen tool parameters, action and input
135
+ commitments and runtime scope. An authenticated workspace issuer supplies an
136
+ `osuite.business_authority.v2` assertion bound to the initiating user, tenant,
137
+ planner, executing agent, executor credential, resource principal and grant.
138
+ Reuse that assertion when resuming the same held operation.
139
+
140
+ Studio checks the issuer and current grant on both admission requests. Each
141
+ issuer in `BUSINESS_AUTHORITY_ISSUERS` can list `grants` with its active grant
142
+ IDs, expiry, authorized principals, action scope and eligible reviewer roles.
143
+ List the native agent IDs that require v2 assertions in
144
+ `NATIVE_DELEGATION_REQUIRED_FOR`. For offline verification of delegated proofs,
145
+ include the trusted issuer public keys in `roots.issuers` as entries with
146
+ `id`, `org_id` and `public_key`.
147
+
88
148
  Use a separately enrolled SDK/MCP identity with a current signing key. A Hook
89
149
  credential is not interchangeable with an SDK credential. The new `sdk`/`mcp`
90
150
  posture endpoint must be deployed server-side. Older servers fail explicitly;
@@ -0,0 +1,22 @@
1
+ import { isObject } from '../runtime/protocol.mjs';
2
+
3
+ export const NATIVE_AMOUNT_SCHEMA = 'osuite.native_amount.v1';
4
+ const reserved = new Set(['__proto__', 'constructor', 'prototype']);
5
+
6
+ export function validUsdMapping(mapping) {
7
+ return isObject(mapping) && Object.keys(mapping).length === 3
8
+ && mapping.currency === 'USD' && mapping.unit === 'minor'
9
+ && Array.isArray(mapping.path) && mapping.path.length > 0 && mapping.path.length <= 8
10
+ && mapping.path.every(key => typeof key === 'string' && /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(key) && !reserved.has(key));
11
+ }
12
+
13
+ export function usdMinorToMajor(value) {
14
+ // At this bound the major-unit number still distinguishes adjacent cents.
15
+ return Number.isSafeInteger(value) && value > 0 && value <= 10 ** 15 ? value / 100 : null;
16
+ }
17
+
18
+ export function agreesWithUsdAmount(value, minor) {
19
+ if (!isObject(value)) return true;
20
+ return [['currency', 'USD'], ['amount_cents', minor], ['amount_usd', usdMinorToMajor(minor)]]
21
+ .every(([key, expected]) => !Object.hasOwn(value, key) || value[key] === expected);
22
+ }
@@ -1,26 +1,35 @@
1
1
  import path from 'node:path';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
- import { canonicalJson, createApiClient } from '../runtime/protocol.mjs';
4
- import { resolveRemotePosture } from '../runtime/posture.mjs';
3
+ import { canonicalJson, createApiClient, isTransientFailure, sha256 } from '../runtime/protocol.mjs';
4
+ import { rejectionFenceUnchanged, resolveRemotePosture } from '../runtime/posture.mjs';
5
5
  import { createStateStore } from '../runtime/state.mjs';
6
6
  import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
7
7
  import { matchesStoredAction, reject } from './contract.mjs';
8
8
 
9
9
  const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
10
10
 
11
+ function failureDetails(phase, response, mayHaveRegistered = false) {
12
+ return {
13
+ phase, httpStatus: response?.status || null, cause: response?.error || 'authority_evidence_unconfirmed',
14
+ retryAfterSeconds: response?.retryAfterSeconds ?? null,
15
+ retrySameOperation: !mayHaveRegistered && (isTransientFailure(response) || response?.status === 429),
16
+ };
17
+ }
18
+
11
19
  export function createStudioAuthority(config, journalPath) {
12
20
  const responseLimits = { maxResponseBytes: 1048576 };
13
21
  const baseApi = createApiClient(config, responseLimits);
14
22
  const store = createStateStore({ ...config, stateDir: path.join(path.dirname(journalPath), 'posture') });
23
+ let currentRead;
15
24
 
16
- async function current(aborted) {
17
- let remote;
25
+ async function readCurrent() {
26
+ let remote, lastResponse;
18
27
  const deadline = performance.now() + 2000;
19
28
  for (let attempt = 0; attempt < 6; attempt++) {
20
- if (aborted()) reject('ABORTED');
21
29
  let readStatus = null;
22
30
  remote = await resolveRemotePosture(config, { store, api: { async request(method, endpoint, ...args) {
23
31
  const response = await baseApi.request(method, endpoint, ...args);
32
+ lastResponse = response;
24
33
  if (method === 'GET') readStatus = response.status;
25
34
  return response;
26
35
  } } });
@@ -40,11 +49,22 @@ export function createStudioAuthority(config, journalPath) {
40
49
  || !['enforce', 'strict'].includes(remote.posture.mode)
41
50
  || remote.posture.require_assumption_capture !== false
42
51
  || remote.posture.require_signature !== true || remote.posture.on_guard_unavailable !== 'block') {
43
- reject('CURRENT_AUTHORITY_UNAVAILABLE');
52
+ reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('posture', lastResponse));
44
53
  }
45
54
  const effective = { ...config, mode: remote.posture.mode, guardFailureMode: 'block', signatureMode: 'required',
46
55
  approvalWaitMs: 0, ruleRollout: remote.ruleRollout };
47
- return { api: createApiClient(effective, responseLimits), effective };
56
+ return { api: createApiClient(effective, responseLimits), effective, fence: remote.rejectionFence };
57
+ }
58
+
59
+ async function current(aborted) {
60
+ if (aborted()) reject('ABORTED');
61
+ // A single live read can serve overlapping invocations of this scope.
62
+ // The next invocation after it settles must start another remote read.
63
+ currentRead ??= readCurrent().finally(() => { currentRead = null; });
64
+ const value = await currentRead;
65
+ if (aborted()) reject('ABORTED');
66
+ if (!rejectionFenceUnchanged(config, store, value.fence)) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('posture'));
67
+ return value;
48
68
  }
49
69
 
50
70
  async function read(record) {
@@ -56,6 +76,9 @@ export function createStudioAuthority(config, journalPath) {
56
76
 
57
77
  async function admit(invocation, journal, owner, aborted) {
58
78
  const record = { ...journal.get(invocation.record.scope, invocation.record.operationId),
79
+ nativeAmount: invocation.context.native_amount,
80
+ nativeResource: invocation.context.native_resource,
81
+ delegationDigest: invocation.context.business_authority_assertion && sha256(canonicalJson(invocation.context.business_authority_assertion.claims)),
59
82
  ...(invocation.recovery ? { recovery: invocation.recovery } : {}) };
60
83
  const phase = record.state === 'held' ? 'redeeming' : 'requesting';
61
84
  const { api, effective } = await current(aborted);
@@ -68,7 +91,7 @@ export function createStudioAuthority(config, journalPath) {
68
91
  const actualSession = session.body?.session || session.body?.runtime_session;
69
92
  if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
70
93
  || actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
71
- || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE');
94
+ || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('runtime_session', session));
72
95
  let claimed = false, requestStartedAt = null;
73
96
  const claim = () => {
74
97
  if (claimed) reject('OUTCOME_UNKNOWN');
@@ -85,11 +108,15 @@ export function createStudioAuthority(config, journalPath) {
85
108
  const registering = method === 'POST' && endpoint === '/api/actions';
86
109
  if (registering) { claim(); requestStartedAt = performance.now(); }
87
110
  const response = await api.request(method, endpoint, body, registering ? receiptWindow : options);
111
+ if (endpoint === '/api/guard' && !response.ok) {
112
+ reject(response.status === 403 && invocation.context.business_authority_assertion ? 'DELEGATION_REJECTED' : 'CURRENT_AUTHORITY_UNAVAILABLE',
113
+ null, failureDetails('guard', response));
114
+ }
88
115
  if (registering) {
89
116
  if (!response.ok || !matchesStoredAction(response.body, record, config)
90
117
  || !cavaFingerprint(response.body)) {
91
118
  settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
92
- reject('OUTCOME_UNKNOWN');
119
+ reject('OUTCOME_UNKNOWN', null, failureDetails('action_registration', response, true));
93
120
  }
94
121
  }
95
122
  return response;
@@ -136,5 +163,11 @@ export function createStudioAuthority(config, journalPath) {
136
163
  && typeof response.body.action?.timestamp_end === 'string';
137
164
  }
138
165
 
139
- return { admit, read, report };
166
+ async function closeOwnerOutcome(record, receipt) {
167
+ const response = await baseApi.request('POST', `/api/actions/${encodeURIComponent(record.actionId)}/resource-confirmation`,
168
+ { agent_id: config.agentId, native_owner_receipt: receipt }, receiptWindow);
169
+ return response.ok && response.body.action_id === record.actionId ? response.body.owner_receipt : null;
170
+ }
171
+
172
+ return { admit, read, report, closeOwnerOutcome };
140
173
  }
@@ -1,5 +1,6 @@
1
1
  import { types } from 'node:util';
2
2
  import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
3
+ import { NATIVE_AMOUNT_SCHEMA, agreesWithUsdAmount, usdMinorToMajor, validUsdMapping } from './amount.mjs';
3
4
 
4
5
  export const CALL_SCHEMA = 'osuite.native_tool_call.v1';
5
6
  export const COVERAGE = 'wrapped-call-only';
@@ -12,18 +13,19 @@ const recoveryMessages = Object.freeze({
12
13
  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
14
  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
15
  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.',
16
+ retry_same_operation: 'Wait for Studio to recover or until the retry delay elapses. Use the same operation ID and unchanged input.',
15
17
  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
18
  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
19
  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
20
  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
21
  });
20
22
 
21
- function recoveryGuidance(code, state) {
23
+ function recoveryGuidance(code, state, details) {
22
24
  let nextStep;
23
25
  if (code === 'ALREADY_COMPLETED' || (state === 'completed' && code !== 'BINDING_MISMATCH')) nextStep = 'read_business_result';
24
26
  else if (['OUTCOME_UNKNOWN', 'UNCERTAIN', 'BINDING_MISMATCH', 'CONFLICT'].includes(code)) nextStep = 'reconcile_without_resend';
25
27
  else if (code?.startsWith('JOURNAL_')) nextStep = 'repair_journal';
26
- else if (code === 'CURRENT_AUTHORITY_UNAVAILABLE') nextStep = 'restore_connection';
28
+ else if (code === 'CURRENT_AUTHORITY_UNAVAILABLE') nextStep = details?.retrySameOperation ? 'retry_same_operation' : 'restore_connection';
27
29
  else if (['POLICY_DENIED', 'APPROVAL_EXPIRED', 'CANCELLED'].includes(code)
28
30
  || ['denied', 'expired', 'cancelled'].includes(state)) nextStep = 'stop';
29
31
  else if (code === 'AWAITING_APPROVAL' || (!code && state === 'held')) nextStep = 'review_same_operation';
@@ -37,17 +39,18 @@ function recoveryGuidance(code, state) {
37
39
  }
38
40
 
39
41
  export class GovernedToolError extends Error {
40
- constructor(code, status = null) {
41
- const recovery = recoveryGuidance(code, status?.state);
42
+ constructor(code, status = null, details = null) {
43
+ const recovery = recoveryGuidance(code, status?.state, details);
42
44
  super(`OSuite ${code}: ${recovery.message}`);
43
45
  this.name = 'GovernedToolError';
44
46
  this.code = code;
45
47
  this.status = status === null ? null : Object.freeze({ ...status, recovery });
46
48
  this.retryAutomatically = false;
47
49
  this.recovery = recovery;
50
+ if (details) this.details = Object.freeze({ ...details });
48
51
  }
49
52
  }
50
- export function reject(code, status) { throw new GovernedToolError(code, status); }
53
+ export function reject(code, status, details) { throw new GovernedToolError(code, status, details); }
51
54
 
52
55
  // Validate descriptors before reading values: JSON.stringify alone can invoke
53
56
  // accessors/toJSON or quietly change undefined, non-finite numbers and arrays.
@@ -122,6 +125,24 @@ function describe(binding, args) {
122
125
  return value;
123
126
  }
124
127
 
128
+ function nativeAmount(binding, native, description, inputDigest) {
129
+ if (!binding.amount) return null;
130
+ if (!validUsdMapping(binding.amount)) reject('INVALID_MAPPING');
131
+ let owner = native.arguments;
132
+ for (const key of binding.amount.path.slice(0, -1)) {
133
+ owner = owner && Object.hasOwn(owner, key) ? owner[key] : null;
134
+ }
135
+ const field = binding.amount.path.at(-1);
136
+ const value = owner && Object.hasOwn(owner, field) ? owner[field] : null;
137
+ // A binding may also describe non-financial variants. A monetary policy
138
+ // independently requires evidence before any of those variants can execute.
139
+ if (value == null || value === 0) return null;
140
+ if (usdMinorToMajor(value) === null || !agreesWithUsdAmount(owner, value)
141
+ || !agreesWithUsdAmount(native.arguments, value) || !agreesWithUsdAmount(description.input_summary, value)) reject('INVALID_AMOUNT');
142
+ return { schema_version: NATIVE_AMOUNT_SCHEMA, mapping: binding.amount, value,
143
+ tool_name: native.name, binding_revision: binding.revision, input_digest: inputDigest };
144
+ }
145
+
125
146
  export function makeInvocation({ config, namespace, bindings, operationId, params }) {
126
147
  const scope = scopeFor(config, namespace);
127
148
  if (!id(operationId)) reject('INVALID_OPERATION_ID');
@@ -135,7 +156,11 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
135
156
  // The historical Hook helper normalizes null to {}. Native calls must retain
136
157
  // every JSON value exactly, including that distinction.
137
158
  const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
159
+ const amount = nativeAmount(binding, native, description, inputDigest);
138
160
  const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description,
161
+ ...(binding.amount ? { amountMapping: binding.amount } : {}),
162
+ ...(binding.ownerReceipt ? { nativeResource: binding.ownerReceipt.resource } : {}),
163
+ ...(binding.delegation ? { delegationRequired: true } : {}),
139
164
  ...(binding.recovery ? { recovery: { revision: binding.recovery.revision,
140
165
  resourceId: binding.recovery.resourceId, contract: binding.recovery.contract } } : {}) }));
141
166
  const identity = sha256(canonicalJson([scope, operationId]));
@@ -145,6 +170,8 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
145
170
  if (inputSummary.length > 4000) reject('INVALID_MAPPING');
146
171
  const context = jsonSnapshot({ ...description, input_summary: inputSummary, action_id: actionId,
147
172
  agent_id: config.agentId, runtime_session_id: sessionId, tool_use_id: toolUseId,
173
+ ...(amount ? { native_amount: { ...amount, binding_digest: bindingDigest } } : {}),
174
+ ...(binding.ownerReceipt ? { native_resource: { ...binding.ownerReceipt.resource, input_digest: inputDigest } } : {}),
148
175
  tool_input_digest: inputDigest, runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper' });
149
176
  return Object.freeze({ params: native, context, marker, record: Object.freeze({ scope, operationId,
150
177
  inputDigest, bindingDigest, contextDigest: sha256(canonicalJson(context)), actionId, sessionId, toolUseId }) });
@@ -173,6 +200,9 @@ export function matchesStoredAction(payload, record, config) {
173
200
  && envelope.action_id === record.actionId && envelope.org_id === config.orgId && envelope.agent_id === config.agentId
174
201
  && envelope.runtime_session_id === record.sessionId && envelope.tool_use_id === record.toolUseId
175
202
  && (!Object.hasOwn(envelope, 'tool_input_digest') || envelope.tool_input_digest === record.inputDigest)
203
+ && (!record.nativeAmount || canonicalJson(envelope.native_amount) === canonicalJson(record.nativeAmount))
204
+ && (!record.nativeResource || canonicalJson(envelope.native_resource) === canonicalJson(record.nativeResource))
205
+ && (!record.delegationDigest || envelope.business_authority?.assertion_digest === record.delegationDigest)
176
206
  && matchesStoredSummary(action.input_summary, record) && matchesStoredSummary(envelope.input_summary, record);
177
207
  } catch { return false; }
178
208
  }
@@ -7,6 +7,8 @@ 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;
12
14
  const terminalCodes = Object.freeze({ denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' });
@@ -56,8 +58,30 @@ function registrySnapshot(bindings) {
56
58
  if (!Object.hasOwn(fields.revision || {}, 'value') || !Object.hasOwn(fields.describe || {}, 'value')
57
59
  || !safeId(fields.revision.value) || fields.revision.value.length > 128
58
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
+ }
59
83
  Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value,
60
- describe: fields.describe.value, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
84
+ describe: fields.describe.value, amount, ownerReceipt, delegation, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
61
85
  }
62
86
  return Object.freeze(result);
63
87
  }
@@ -82,6 +106,24 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
82
106
  let closed = false, inFlight = 0;
83
107
  const local = operationId => journal.get(scope, operationId);
84
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
+ }
85
127
  const recoveryStatus = operationId => {
86
128
  const child = journal.get(recoveryScope(scope), operationId);
87
129
  return child ? Object.freeze({ ...status(child), evidenceDigest: child.errorCode?.startsWith('recovery_')
@@ -105,7 +147,9 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
105
147
  const { scope, operationId } = invocation.record;
106
148
  const local = operationId => {
107
149
  const record = journal.get(scope, operationId);
108
- 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 };
109
153
  };
110
154
  if (aborted()) reject('ABORTED');
111
155
  const started = performance.now(), deadline = started + waitMs, owner = randomUUID();
@@ -145,7 +189,7 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
145
189
  let admitted;
146
190
  try { admitted = await authority.admit(invocation, journal, owner, aborted); }
147
191
  catch (error) {
148
- 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);
149
193
  reject('OUTCOME_UNKNOWN', status(local(operationId)));
150
194
  }
151
195
  if (!admitted) { if (performance.now() >= deadline) waiting(); continue; }
@@ -162,7 +206,8 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
162
206
  // and invoking the original tool. This is not resource-side atomicity.
163
207
  const grantExpiry = admitted.phase === 'redeeming' ? Date.parse(admitted.response.action.approval_expires_at) : Infinity;
164
208
  const ruleExpiry = admitted.ruleExpiresAt == null ? Infinity : Date.parse(admitted.ruleExpiresAt);
165
- 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)
166
211
  && (!recovery || recovery.fresh());
167
212
  if (aborted() || closed || !current()) {
168
213
  journal.settle(scope, operationId, owner, admitted.phase,
@@ -215,10 +260,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
215
260
 
216
261
  return Object.freeze({
217
262
  async run(operationId, params, execute, options = {}) {
218
- return work(() => {
263
+ return work(async () => {
219
264
  const invocation = makeInvocation({ config, namespace, bindings, operationId, params });
220
265
  if (typeof execute !== 'function' || types.isProxy(execute)) reject('INVALID_EXECUTOR');
221
- 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);
222
269
  });
223
270
  },
224
271
  async recover(operationId, params, options = {}) {
@@ -227,11 +274,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
227
274
  const settings = runOptions(options);
228
275
  if (settings.aborted()) reject('ABORTED');
229
276
  const adapter = bindings[parent.params.name].recovery;
230
- const record = journal.getBound(parent.record);
277
+ const record = journal.getBound((await bindDelegation(parent)).record);
231
278
  if (!adapter) reject('RECOVERY_UNSUPPORTED', status(record));
232
279
  if (!record) reject('RECOVERY_UNAVAILABLE');
233
280
  if (record.state !== 'uncertain') { stopForState(record); reject('RECOVERY_UNAVAILABLE', status(record)); }
234
- const { invocation, request } = makeRecoveryInvocation(parent, adapter);
281
+ const { invocation: childInvocation, request } = makeRecoveryInvocation(parent, adapter);
282
+ const invocation = await bindDelegation(childInvocation);
235
283
  try {
236
284
  const child = journal.get(invocation.record.scope, operationId);
237
285
  if (child) {
@@ -274,10 +322,42 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
274
322
  if (terminal) failureCode = terminalCodes[terminal];
275
323
  }
276
324
  const attempt = recoveryStatus(operationId);
277
- 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,
278
327
  status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
279
328
  });
280
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
+ },
281
361
  close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
282
362
  });
283
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.15.0",
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,9 @@
23
23
  "./governed-tools": {
24
24
  "import": "./governed-tools.mjs"
25
25
  },
26
+ "./native-proof": {
27
+ "import": "./native-proof.mjs"
28
+ },
26
29
  "./experimental/business-evidence": {
27
30
  "import": "./business-evidence.mjs"
28
31
  },
@@ -39,6 +42,7 @@
39
42
  "tryContract.js",
40
43
  "runtime/",
41
44
  "governed-tools.mjs",
45
+ "native-proof.mjs",
42
46
  "governed-tools/*.mjs",
43
47
  "governed-tools/examples/*.mjs",
44
48
  "GOVERNED_TOOLS.md",
package/projectHooks.js CHANGED
@@ -1036,6 +1036,13 @@ export async function runHookCheck({
1036
1036
  const nodeHook = /\bosuite_pretool\.mjs\b/.test(installation.pretool.command);
1037
1037
  const preflightModes = seen.filter((event) => event.event_type === 'tool_preflight')
1038
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
+ }
1039
1046
  const observing = (!preflightModes.length && credentials.hookMode === 'observe') || seen.some((event) => (
1040
1047
  event.payload?.hook_mode === 'observe' || event.payload?.observe_only === true
1041
1048
  || String(event.payload?.decision || '').startsWith('observe_')
@@ -144,11 +144,13 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
144
144
  const guard = await api.request('POST', '/api/guard', rememberOperation ? { ...context, hook_dispatch: 'v1' } : context);
145
145
  if (!guard.ok) {
146
146
  // Rejection, bad evidence and unknown errors are not availability failures.
147
- if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status });
147
+ if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status,
148
+ phase: 'guard', retrySameOperation: guard.status === 429, retryAfterSeconds: guard.retryAfterSeconds });
148
149
  const failOpen = ['observe', 'enforce'].includes(config.mode)
149
150
  && config.ruleRolloutCapability !== RULE_ROLLOUT_CAPABILITY && !config.ruleRollout?.enabled
150
151
  && config.guardFailureMode === 'allow';
151
- return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true };
152
+ return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true,
153
+ phase: 'guard', retrySameOperation: !failOpen, retryAfterSeconds: guard.retryAfterSeconds };
152
154
  }
153
155
  const requestedDecision = guard.body?.decision;
154
156
  if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
@@ -163,6 +165,18 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
163
165
  ...(rollout.binding ? { observeOnly: false, ruleRolloutBinding: rollout.binding } : {}),
164
166
  });
165
167
  const create = fields => api.request('POST', '/api/actions', { ...context, ...binding, ...fields });
168
+ if (context.hook_observation) {
169
+ if (!operationId || config.mode !== 'observe' || rollout.binding) return finish(closed('observation_posture_unconfirmed'));
170
+ const observed = await create({ status: 'running' });
171
+ const action = observed.body?.action;
172
+ if (!observed.ok || action?.status !== 'running' || action.timestamp_end != null
173
+ || action.action_envelope?.hook_observation?.revision !== context.hook_observation.revision
174
+ || !matchesAction(observed.body, context, { actionId: operationId })) {
175
+ return finish(closed('observation_registration_unconfirmed', { actionId: operationId, rejectedStatus: observed.status }));
176
+ }
177
+ return finish({ authorized: false, observeOnly: true, observeRecorded: true, actionId: operationId,
178
+ decision: observed.body.decision?.decision, response: observed.body });
179
+ }
166
180
  if (requestedDecision === 'block') {
167
181
  // Observation still persists the would-block result, but never calls it authority.
168
182
  const observeOnly = config.mode === 'observe' && !rollout.binding;
@@ -179,7 +193,8 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
179
193
  return finish({ ...closed('policy_block'), observeOnly, response: guard.body, actionId });
180
194
  }
181
195
  const created = await create({ status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running' });
182
- if (!created.ok) return finish(closed('admission_unconfirmed', { rejectedStatus: created.status, actionId: operationId }));
196
+ if (!created.ok) return finish(closed('admission_unconfirmed', { rejectedStatus: created.status, actionId: operationId,
197
+ phase: 'action_registration', retrySameOperation: false, retryAfterSeconds: created.retryAfterSeconds }));
183
198
  if (operationId && created.body?.action_id !== operationId) return finish(closed('hook_operation_binding_changed', { actionId: operationId }));
184
199
  if (!rolloutAuthority(created.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid');
185
200
  const diagnostic = installCheck(created.body, context);
package/runtime/hook.mjs CHANGED
@@ -137,12 +137,15 @@ export async function runHook(data, localConfig, dependencies = {}) {
137
137
  const checkedNote = message => fenceUnchanged() ? note(message) : pre ? deny(accessChanged) : note(accessChanged);
138
138
  const config = { ...applyPosture(localConfig, remote.posture), ruleRollout: remote.ruleRollout,
139
139
  orgId: remote.orgId || localConfig.orgId };
140
+ const postureEvidence = { local_mode: localConfig.mode, effective_mode: config.mode,
141
+ source: remote.source, scope: remote.scope || null, valid_until: remote.validUntil || null,
142
+ revision: remote.revision, fallback: remote.source === 'unavailable' ? config.guardFailureMode : null };
140
143
  api = trackPostureRejections(dependencies.api || apiFactory(config), localConfig, store, now);
141
144
  if (event === 'Stop') {
142
145
  const stopped = await stopHook(data, config, api, store, fenceUnchanged);
143
146
  return fenceUnchanged() ? stopped : note(accessChanged);
144
147
  }
145
- if (remote.blocked) return pre ? deny('Verified runtime posture is unavailable or expired. Execution is blocked; reconnect or restore access.')
148
+ if (remote.blocked) return pre ? deny('POSTURE_UNAVAILABLE. Verified runtime posture is unavailable or expired. Execution is blocked. Reconnect or restore access.')
146
149
  : note('Verified runtime posture is unavailable. Enforce hooks will block execution until it can be verified.');
147
150
  if (!pre && event !== 'SessionStart' && event !== 'SessionEnd') return note('Unsupported hook event; no execution decision was made.');
148
151
  const session = await openSession(api, config, data, store, now());
@@ -156,7 +159,8 @@ export async function runHook(data, localConfig, dependencies = {}) {
156
159
  rememberGap(store, 'posture_unavailable', now());
157
160
  return checkedNote('Not governed: remote posture is unavailable; explicit observe mode does not enforce OSuite policy.');
158
161
  }
159
- await emitRuntimeEvent(api, config, context, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest, install_check: config.installCheck === true });
162
+ await emitRuntimeEvent(api, config, context, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest,
163
+ install_check: config.installCheck === true, runtime_posture: postureEvidence });
160
164
  if (!fenceUnchanged()) return deny(accessChanged);
161
165
  const operationKey = `operation:${session}:${context.tool_use_id}`;
162
166
  const rememberOperation = ['claude', 'codex'].includes(config.host) && config.privateKeyBase64 && !config.installCheck
@@ -164,6 +168,10 @@ export async function runHook(data, localConfig, dependencies = {}) {
164
168
  const current = store.update(operationKey, prior => prior || { action_id: actionId, input_digest: context.tool_input_digest });
165
169
  return current.action_id === actionId && current.input_digest === context.tool_input_digest;
166
170
  } : undefined;
171
+ if (rememberOperation && config.mode === 'observe' && remote.source === 'remote' && !remote.ruleRollout?.enabled) {
172
+ context.hook_observation = { runtime_id: config.runtimeId, provider: config.provider ?? null,
173
+ local_mode: localConfig.mode, valid_until: remote.validUntil, revision: remote.revision };
174
+ }
167
175
  const result = await admitAction(context, { api, config, ...dependencies.admission, rememberOperation,
168
176
  beforeRelease: response => validateGitPublication(context, response) });
169
177
  const dispatchBody = result.hookOperationId ? { hook_action_id: result.hookOperationId, tool_input_digest: context.tool_input_digest } : null;
@@ -176,7 +184,9 @@ export async function runHook(data, localConfig, dependencies = {}) {
176
184
  };
177
185
  if (result.degraded) {
178
186
  rememberGap(store, result.reason, now());
179
- await emitRuntimeEvent(api, config, context, 'governance_unavailable', null, { decision: result.decision === 'allow' ? 'guard_unavailable' : 'guard_unavailable_blocked' });
187
+ await emitRuntimeEvent(api, config, context, 'governance_unavailable', null, { decision: result.decision === 'allow' ? 'guard_unavailable' : 'guard_unavailable_blocked',
188
+ phase: result.phase || 'guard', retry_same_operation: result.retrySameOperation === true,
189
+ retry_after_seconds: result.retryAfterSeconds ?? null });
180
190
  return result.decision === 'allow' ? checkedNote('Not governed: the guard is unavailable and this verified posture explicitly allows availability fallback. No authorization or completion is claimed.')
181
191
  : deny('Guard unavailable. Verified policy requires blocking this call.');
182
192
  }
@@ -185,7 +195,7 @@ export async function runHook(data, localConfig, dependencies = {}) {
185
195
  await emitRuntimeEvent(api, config, context, 'install_check_policy_result', null, { decision: result.decision, approval_state: 'not_requested', install_check: true });
186
196
  return deny('Install check: policy would require human approval. No request was sent to reviewers and no tool was executed.');
187
197
  }
188
- if (result.authorized) {
198
+ if (result.authorized || result.observeRecorded) {
189
199
  try {
190
200
  store.write(`action:${context.tool_use_id}`, { schema: 'osuite.node_action.v1', action_id: result.actionId,
191
201
  runtime_session_id: session, tool_name: data.tool_name, tool_use_id: context.tool_use_id,
@@ -203,7 +213,9 @@ export async function runHook(data, localConfig, dependencies = {}) {
203
213
  }
204
214
  }
205
215
  updatePending(store, context);
206
- await emitRuntimeEvent(api, config, context, 'tool_allowed', result.actionId, { decision: result.decision, install_check: config.installCheck === true });
216
+ await emitRuntimeEvent(api, config, context, 'tool_allowed', result.actionId, { decision: result.observeRecorded ? 'observed_dispatch' : result.decision,
217
+ ...(result.observeRecorded ? { observe_only: true, policy_recommendation: result.decision } : {}),
218
+ approval_required: false, install_check: config.installCheck === true });
207
219
  return checkedNote(config.mode === 'observe' && !result.ruleRolloutBinding ? 'Observe mode recorded a policy result; it does not enforce OSuite policy.' : result.decision === 'warn' ? 'OSuite authorized this call with a policy warning.' : '');
208
220
  }
209
221
  if (result.reason === 'action_evidence_changed') await cancelUnreleased();
@@ -214,7 +226,8 @@ export async function runHook(data, localConfig, dependencies = {}) {
214
226
  return result.observeOnly === true ? checkedNote('Observe mode: this call would require human approval; it is not authorized by a reviewer.')
215
227
  : deny(`Human approval is still required for action ${result.actionId}. Do not run or automatically retry it. Review it in OSuite Studio.`);
216
228
  }
217
- await emitRuntimeEvent(api, config, context, 'tool_blocked', result.actionId, { decision: result.observeOnly === true ? 'observe_would_block' : 'block', reason: result.reason });
229
+ await emitRuntimeEvent(api, config, context, 'tool_blocked', result.actionId, { decision: result.observeOnly === true ? 'observe_would_block' : 'block', reason: result.reason,
230
+ phase: result.phase || null, retry_same_operation: result.retrySameOperation === true, retry_after_seconds: result.retryAfterSeconds ?? null });
218
231
  return result.observeOnly === true ? checkedNote('Observe mode: OSuite policy would block this call. It is not authorized by OSuite.')
219
232
  : deny(`OSuite policy did not authorize this exact action (${result.reason}). Do not retry automatically.`);
220
233
  } catch {
@@ -232,7 +232,7 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
232
232
  entry = cacheEntry(saved, config, now); cached = entry?.document;
233
233
  if (rejectionFenceUnchanged(config, store, rejectionFence) && cached && canonicalJson(cached) === canonicalJson(document)) {
234
234
  return { available: true, blocked: false, source: 'remote', posture: document.posture, revision: document.revision,
235
- ruleRollout: document.rule_rollout, orgId: document.org_id, rejectionFence };
235
+ validUntil: document.valid_until, scope: response.body.scope, ruleRollout: document.rule_rollout, orgId: document.org_id, rejectionFence };
236
236
  }
237
237
  } catch {
238
238
  const posture = offlinePosture(offlinePosture(localPosture(config), readEntry(store, config, now)?.document?.posture), document.posture);
@@ -246,7 +246,7 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
246
246
  && validNegotiation(cached, config, now)) {
247
247
  if (capable && !matchesAcknowledgement(cached, acknowledged)) return { available: false, blocked: true, source: 'unavailable', posture, revision: cached.revision };
248
248
  return { available: true, blocked: false, source: 'cache', posture, revision: cached.revision,
249
- ruleRollout: cached.rule_rollout, orgId: cached.org_id, rejectionFence };
249
+ validUntil: cached.valid_until, ruleRollout: cached.rule_rollout, orgId: cached.org_id, rejectionFence };
250
250
  }
251
251
  return { available: false, blocked: rejected || fenced || entry?.rejected === true || capable || posture.mode !== 'observe',
252
252
  source: 'unavailable', posture, revision: cached?.revision || null, rejectionFence };
@@ -102,8 +102,10 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
102
102
  timer = setTimeout(() => controller.abort(), Math.max(1, totalMs - elapsed));
103
103
  }
104
104
  if (status < 200 || status >= 300) {
105
+ const retryAfter = response.headers?.get('retry-after');
106
+ const retryAfterSeconds = /^\d{1,4}$/.test(retryAfter || '') && Number(retryAfter) <= 3600 ? Number(retryAfter) : null;
105
107
  await response.body?.cancel();
106
- return { ok: false, status, error: 'http_error' };
108
+ return { ok: false, status, error: 'http_error', ...(retryAfterSeconds !== null ? { retryAfterSeconds } : {}) };
107
109
  }
108
110
  const reader = response.body?.getReader();
109
111
  if (!reader) return { ok: false, status, error: 'invalid_response' };