osuite 2.10.1 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.10.1",
3
+ "version": "2.11.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": {
@@ -19,15 +19,23 @@
19
19
  "./legacy": {
20
20
  "import": "./legacy/osuite-v1.js",
21
21
  "require": "./legacy/index-v1.cjs"
22
+ },
23
+ "./governed-tools": {
24
+ "import": "./governed-tools.mjs"
22
25
  }
23
26
  },
24
27
  "files": [
25
28
  "cli.js",
26
29
  "credentials.js",
30
+ "installationIdentity.js",
27
31
  "activationMetrics.js",
28
32
  "tryFlow.js",
29
33
  "tryContract.js",
30
34
  "runtime/",
35
+ "governed-tools.mjs",
36
+ "governed-tools/*.mjs",
37
+ "governed-tools/examples/*.mjs",
38
+ "GOVERNED_TOOLS.md",
31
39
  "projectHooks.js",
32
40
  "reviewSurface.js",
33
41
  "osuite.js",
@@ -1,10 +1,55 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
- import { isObject, safeId } from './protocol.mjs';
2
+ import { canonicalJson, isObject, safeId, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
3
3
 
4
4
  export const REVIEW_DECISIONS = new Set(['require_approval', 'require_dual_approval']);
5
5
  const DECISIONS = new Set(['allow', 'warn', 'block', ...REVIEW_DECISIONS]);
6
6
  const closed = (reason, extra = {}) => ({ authorized: false, decision: 'block', reason, retryAutomatically: false, ...extra });
7
7
 
8
+ function rolloutSnapshots(payload) {
9
+ const current = isObject(payload?.decision) ? payload.decision : payload;
10
+ return [current?.policy_snapshot, payload?.contracts?.policy_snapshot, payload?.action?.policy_snapshot,
11
+ payload?.action?.proof_bundle?.policy_snapshot, payload?.contracts?.proof_bundle?.policy_snapshot].filter(isObject);
12
+ }
13
+
14
+ function rolloutAuthority(payload, context, config, expected) {
15
+ const current = isObject(payload?.decision) ? payload.decision : payload;
16
+ const snapshots = rolloutSnapshots(payload);
17
+ const present = [current, ...snapshots].filter(isObject)
18
+ .some(value => Object.hasOwn(value, 'rule_rollout') || Object.hasOwn(value, 'rule_rollout_binding'));
19
+ const negotiated = config.ruleRollout;
20
+ if (!present && !expected && !negotiated?.enabled) return { valid: true, binding: null };
21
+ const binding = current?.rule_rollout_binding, report = current?.rule_rollout;
22
+ const scopeKeys = ['org_id', 'runtime_id', 'agent_id', 'provider', 'connection_id'];
23
+ const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
24
+ // These fields arrive from the authenticated API, never the tool request.
25
+ // Their only authority is to forbid observe bypass, not to grant execution.
26
+ if (expected === null || !isObject(binding) || !isObject(report) || (negotiated && !negotiated.enabled)
27
+ || binding.schema_version !== 'osuite.rule_rollout_binding.v1' || binding.enforcement_required !== true
28
+ || !isObject(binding.scope) || Object.keys(binding.scope).length !== scopeKeys.length
29
+ || scopeKeys.some(key => !safeId(binding.scope[key]) || binding.scope[key].length > 128)
30
+ || binding.scope.agent_id !== config.agentId || binding.scope.agent_id !== context.agent_id
31
+ || binding.scope.runtime_id !== config.runtimeId
32
+ || (negotiated?.enabled && (binding.version !== negotiated.version || canonicalJson(binding.scope) !== canonicalJson(negotiated.scope)
33
+ || binding.credential_id !== negotiated.credential_id || binding.connection_generation !== negotiated.connection_generation
34
+ || binding.expires_at !== negotiated.expires_at))
35
+ || (config.orgId && binding.scope.org_id !== config.orgId) || (config.provider && binding.scope.provider !== config.provider)
36
+ || !Number.isSafeInteger(binding.version) || binding.version < 1
37
+ || !Number.isFinite(approvalTime(binding.expires_at)) || approvalTime(binding.expires_at) <= Date.now()
38
+ || !safeId(binding.runtime_session_id) || binding.runtime_session_id !== context.runtime_session_id
39
+ || !digest(binding.tool_input_digest) || binding.tool_input_digest !== context.tool_input_digest
40
+ || !binding.action_type || binding.action_type !== context.action_type
41
+ || !digest(binding.policy_context_fingerprint) || binding.policy_context_fingerprint !== current.policy_context_fingerprint
42
+ || report.schema_version !== 'osuite.rule_rollout_evaluation.v1' || report.status !== 'evaluated'
43
+ || report.version !== binding.version || report.expires_at !== binding.expires_at
44
+ || canonicalJson(report.scope) !== canonicalJson(binding.scope)
45
+ || !isObject(current.policy_snapshot) || !snapshots.length
46
+ || current.policy_snapshot.effective_decision !== ({ block: 'deny', warn: 'allow_with_evidence' }[current.decision] || current.decision)
47
+ || snapshots.some(snapshot => canonicalJson(snapshot.rule_rollout_binding) !== canonicalJson(binding)
48
+ || canonicalJson(snapshot.rule_rollout) !== canonicalJson(report))
49
+ || (expected && canonicalJson(binding) !== canonicalJson(expected))) return { valid: false, binding: null };
50
+ return { valid: true, binding };
51
+ }
52
+
8
53
  function approvalReceipts(payload) {
9
54
  const action = payload?.action || payload || {};
10
55
  return [action.approval_receipts, action.proof_bundle?.approval_receipts,
@@ -97,33 +142,40 @@ function installCheck(payload, context) {
97
142
  export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(), beforeRelease = async () => true } = {}) {
98
143
  const guard = await api.request('POST', '/api/guard', context);
99
144
  if (!guard.ok) {
100
- const failOpen = config.guardFailureMode === 'allow' && ![401, 403].includes(guard.status)
145
+ const failOpen = config.ruleRolloutCapability !== RULE_ROLLOUT_CAPABILITY && !config.ruleRollout?.enabled
146
+ && config.guardFailureMode === 'allow' && ![401, 403, 409].includes(guard.status)
101
147
  && !['signing_unavailable', 'invalid_response', 'invalid_request'].includes(guard.error);
102
148
  return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true };
103
149
  }
104
150
  const requestedDecision = guard.body?.decision;
105
151
  if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
152
+ const rollout = rolloutAuthority(guard.body, context, config);
153
+ if (!rollout.valid) return closed('rule_rollout_binding_invalid');
154
+ const finish = result => rollout.binding ? { ...result, observeOnly: false, ruleRolloutBinding: rollout.binding } : result;
106
155
  if (requestedDecision === 'block') {
107
156
  // Observation still persists the would-block result, but never calls it authority.
108
- if (config.mode === 'observe') await api.request('POST', '/api/actions', { ...context, status: 'blocked' });
109
- return { ...closed('policy_block'), observeOnly: config.mode === 'observe', response: guard.body };
157
+ const observeOnly = config.mode === 'observe' && !rollout.binding;
158
+ if (observeOnly) await api.request('POST', '/api/actions', { ...context, status: 'blocked' });
159
+ return finish({ ...closed('policy_block'), observeOnly, response: guard.body });
110
160
  }
111
161
  const created = await api.request('POST', '/api/actions', {
112
162
  ...context, status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running',
113
163
  });
114
164
  if (!created.ok) return closed('admission_unconfirmed');
165
+ if (!rolloutAuthority(created.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid');
115
166
  const diagnostic = installCheck(created.body, context);
116
- if (diagnostic) return diagnostic;
117
- let result = actionAdmission(created.body, requestedDecision, context);
167
+ if (diagnostic) return finish(diagnostic);
168
+ let result = finish(actionAdmission(created.body, requestedDecision, context));
118
169
  if (result.authorized) return await beforeRelease(result.response) ? result : closed('action_evidence_changed');
119
170
  if (result.decision !== 'require_approval') return result;
120
- if (config.mode === 'observe') return { ...result, observeOnly: true };
171
+ if (config.mode === 'observe' && !rollout.binding) return { ...result, observeOnly: true };
121
172
 
122
173
  const expected = { actionId: result.actionId, fingerprint: cavaFingerprint(created.body) };
123
174
  const waitMs = Math.max(0, Math.min(config.approvalWaitMs ?? 30000, 600000));
124
175
  const deadline = now() + waitMs;
125
176
  while (now() < deadline) {
126
177
  await sleep(Math.min(3000, Math.max(0, deadline - now())));
178
+ if (rollout.binding && approvalTime(rollout.binding.expires_at) <= Date.now()) return closed('rule_rollout_expired', { actionId: expected.actionId });
127
179
  const polled = await api.request('GET', `/api/actions/${encodeURIComponent(expected.actionId)}`, undefined, {
128
180
  timeoutMs: Math.max(1, Math.min(2500, deadline - now())),
129
181
  });
@@ -133,6 +185,12 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
133
185
  }
134
186
  const action = polled.body?.action || polled.body;
135
187
  if (!matchesAction(polled.body, context, expected)) return closed('approval_binding_mismatch', { actionId: expected.actionId });
188
+ if (rollout.binding) {
189
+ const snapshots = rolloutSnapshots(polled.body);
190
+ if (!snapshots.length || snapshots.some(snapshot => canonicalJson(snapshot.rule_rollout_binding) !== canonicalJson(rollout.binding))) {
191
+ return closed('rule_rollout_binding_invalid', { actionId: expected.actionId });
192
+ }
193
+ }
136
194
  if (action.status === 'pending_approval') continue;
137
195
  if (action.status !== 'running') return closed('approval_closed', { actionId: expected.actionId });
138
196
  if (action.approval_redeemed_at != null || action.timestamp_end != null) return closed('execution_outcome_unknown', { actionId: expected.actionId });
@@ -142,7 +200,8 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
142
200
  // GET observes a grant. Only this fresh POST may redeem it. Never retry a lost reply.
143
201
  const current = await api.request('POST', '/api/actions', { ...context, status: 'running' });
144
202
  if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId });
145
- result = actionAdmission(current.body, 'allow', context, expected);
203
+ if (!rolloutAuthority(current.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid', { actionId: expected.actionId });
204
+ result = finish(actionAdmission(current.body, 'allow', context, expected));
146
205
  if (result.authorized && !await beforeRelease(result.response)) return closed('action_evidence_changed', { actionId: result.actionId });
147
206
  return result;
148
207
  }
@@ -1,5 +1,6 @@
1
1
  import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
3
4
 
4
5
  function readDotenv(installDir, filename = '.env') {
5
6
  let fd;
@@ -34,6 +35,7 @@ export function loadRuntimeConfig({ installDir, env = process.env, host = 'claud
34
35
  const mode = ['observe', 'enforce', 'strict'].includes(requestedMode) ? requestedMode : 'strict';
35
36
  return {
36
37
  host,
38
+ ruleRolloutCapability: get('SCOPED_RULE_ROLLOUT') === '1' ? RULE_ROLLOUT_CAPABILITY : undefined,
37
39
  runtimeId: get('RUNTIME_ADAPTER_ID', runtimeId || (host === 'cursor' ? 'cursor_hooks' : host === 'codex' ? 'codex_hooks' : 'claude_code_hooks')),
38
40
  agentId: get('AGENT_ID', plugin ? 'codex-plugin-runtime' : host === 'cursor' ? 'cursor' : host === 'codex' ? 'codex' : 'claude-code'),
39
41
  orgId: get('ORG_ID'), provider: get('RUNTIME_PROVIDER') || null,
package/runtime/hook.mjs CHANGED
@@ -109,14 +109,16 @@ export async function runHook(data, localConfig, dependencies = {}) {
109
109
  const initialContext = pre ? buildActionContext(data, localConfig) : null;
110
110
  const store = dependencies.store || createStateStore(localConfig);
111
111
  const now = dependencies.now || Date.now;
112
- let api = dependencies.api || createApiClient(localConfig);
112
+ const apiFactory = dependencies.apiFactory || createApiClient;
113
+ let api = dependencies.api || apiFactory(localConfig);
113
114
  if (event === 'PostToolUse' || event === 'PostToolUseFailure') {
114
115
  const result = await recordOutcome(localConfig, data, { api, store, now });
115
116
  return note(result.reason ? 'Tool outcome is not yet acknowledged. Evidence was retained; do not repeat the side effect.' : '');
116
117
  }
117
118
  const remote = await resolveRemotePosture(localConfig, { api, store, now: now() });
118
- const config = applyPosture(localConfig, remote.posture);
119
- api = dependencies.api || createApiClient(config);
119
+ const config = { ...applyPosture(localConfig, remote.posture), ruleRollout: remote.ruleRollout,
120
+ orgId: remote.orgId || localConfig.orgId };
121
+ api = dependencies.api || apiFactory(config);
120
122
  if (event === 'Stop') return stopHook(data, config, api, store);
121
123
  if (remote.blocked) return pre ? deny('Verified runtime posture is unavailable or expired. Execution is blocked; reconnect or restore access.')
122
124
  : note('Verified runtime posture is unavailable. Enforce hooks will block execution until it can be verified.');
@@ -152,17 +154,17 @@ export async function runHook(data, localConfig, dependencies = {}) {
152
154
  } catch { return deny('Cannot persist the exact-action receipt state. The admitted tool was not released; reconcile its action in Studio before retrying.'); }
153
155
  updatePending(store, context);
154
156
  await emitRuntimeEvent(api, config, context, 'tool_allowed', result.actionId, { decision: result.decision, install_check: config.installCheck === true });
155
- return note(config.mode === 'observe' ? 'Observe mode recorded a policy result; it does not enforce OSuite policy.' : result.decision === 'warn' ? 'OSuite authorized this call with a policy warning.' : '');
157
+ return note(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.' : '');
156
158
  }
157
159
  if (result.decision === 'require_approval') {
158
- if (config.mode !== 'observe') updatePending(store, context, { action_id: result.actionId, agent_id: config.agentId,
160
+ if (result.observeOnly !== true) updatePending(store, context, { action_id: result.actionId, agent_id: config.agentId,
159
161
  runtime_session_id: session, tool_input_digest: context.tool_input_digest, fingerprint: cavaFingerprint(result.response) });
160
- await emitRuntimeEvent(api, config, context, 'tool_requires_approval', result.actionId, { decision: config.mode === 'observe' ? 'observe_would_require_approval' : result.response?.decision?.decision || 'require_approval' });
161
- return config.mode === 'observe' ? note('Observe mode: this call would require human approval; it is not authorized by a reviewer.')
162
+ await emitRuntimeEvent(api, config, context, 'tool_requires_approval', result.actionId, { decision: result.observeOnly === true ? 'observe_would_require_approval' : result.response?.decision?.decision || 'require_approval' });
163
+ return result.observeOnly === true ? note('Observe mode: this call would require human approval; it is not authorized by a reviewer.')
162
164
  : deny(`Human approval is still required for action ${result.actionId}. Do not run or automatically retry it. Review it in OSuite Studio.`);
163
165
  }
164
- await emitRuntimeEvent(api, config, context, 'tool_blocked', result.actionId, { decision: config.mode === 'observe' ? 'observe_would_block' : 'block', reason: result.reason });
165
- return config.mode === 'observe' ? note('Observe mode: OSuite policy would block this call. It is not authorized by OSuite.')
166
+ await emitRuntimeEvent(api, config, context, 'tool_blocked', result.actionId, { decision: result.observeOnly === true ? 'observe_would_block' : 'block', reason: result.reason });
167
+ return result.observeOnly === true ? note('Observe mode: OSuite policy would block this call. It is not authorized by OSuite.')
166
168
  : deny(`OSuite policy did not authorize this exact action (${result.reason}). Do not retry automatically.`);
167
169
  } catch {
168
170
  return pre ? deny('Hook evidence or state is invalid. Execution is blocked; no successful admission is claimed.')
package/runtime/mcp.mjs CHANGED
@@ -163,7 +163,7 @@ export function createMcpServer(localConfig, dependencies = {}) {
163
163
  const response = { jsonrpc: '2.0', id: request.id };
164
164
  if (request.method === 'initialize') return { ...response, result: {
165
165
  protocolVersion: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(request.params?.protocolVersion) ? request.params.protocolVersion : '2025-11-25',
166
- capabilities: { tools: {} }, serverInfo: { name: 'osuite_runtime_governance', version: '1.1.0-node' }, instructions: COVERAGE,
166
+ capabilities: { tools: {} }, serverInfo: { name: 'osuite_runtime_governance', version: '1.1.1-node' }, instructions: COVERAGE,
167
167
  } };
168
168
  if (request.method === 'ping') return { ...response, result: {} };
169
169
  if (request.method === 'tools/list') return { ...response, result: { tools: MCP_TOOLS } };
@@ -1,9 +1,54 @@
1
1
  import { createHmac, timingSafeEqual } from 'node:crypto';
2
- import { canonicalJson, isObject, sha256 } from './protocol.mjs';
2
+ import { canonicalJson, isObject, safeId, sha256, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
3
3
 
4
4
  export const POSTURE_SCHEMA = 'osuite.runtime_posture.v1';
5
5
  const MAX_FRESHNESS_MS = 300000;
6
6
  const MODE_STRENGTH = { observe: 0, enforce: 1, strict: 2 };
7
+ const scopeKeys = ['org_id', 'runtime_id', 'agent_id', 'provider', 'connection_id'];
8
+
9
+ function validAcknowledgement(value, config, now) {
10
+ const binding = value?.device_binding, issued = Date.parse(value?.acknowledged_at), expires = Date.parse(value?.expires_at);
11
+ return value?.schema_version === 'osuite.rule_rollout_client.v1' && value.capability === RULE_ROLLOUT_CAPABILITY
12
+ && isObject(value.scope) && Object.keys(value.scope).length === scopeKeys.length && scopeKeys.every(key => safeId(value.scope[key]))
13
+ && value.scope.runtime_id === config.runtimeId && value.scope.agent_id === config.agentId
14
+ && (!config.orgId || value.scope.org_id === config.orgId) && (!config.provider || value.scope.provider === config.provider)
15
+ && isObject(binding) && safeId(binding.credential_id) && binding.capability === RULE_ROLLOUT_CAPABILITY
16
+ && Number.isSafeInteger(binding.connection_generation) && binding.connection_generation >= 1
17
+ && typeof binding.public_key_fingerprint === 'string' && /^[a-f0-9]{64}$/.test(binding.public_key_fingerprint)
18
+ && Number.isFinite(issued) && Number.isFinite(expires) && issued <= now + 30000 && expires > now
19
+ && expires > issued && expires - issued <= 900000;
20
+ }
21
+
22
+ function matchesAcknowledgement(document, acknowledgement) {
23
+ return document.credential_id === acknowledgement.device_binding.credential_id
24
+ && document.org_id === acknowledgement.scope.org_id
25
+ && canonicalJson(document.rule_rollout?.scope) === canonicalJson(acknowledgement.scope)
26
+ && document.rule_rollout?.credential_id === acknowledgement.device_binding.credential_id
27
+ && document.rule_rollout?.connection_generation === acknowledgement.device_binding.connection_generation;
28
+ }
29
+
30
+ function preservesRolloutFloor(previous, current) {
31
+ const before = previous?.rule_rollout, after = current?.rule_rollout;
32
+ if (!before?.enabled) return true;
33
+ return after?.enabled === true && canonicalJson(before.scope) === canonicalJson(after.scope)
34
+ && before.credential_id === after.credential_id && after.connection_generation >= before.connection_generation
35
+ && after.version >= before.version && (after.version !== before.version || canonicalJson(before) === canonicalJson(after));
36
+ }
37
+
38
+ function validNegotiation(document, config, now) {
39
+ if (config.ruleRolloutCapability !== RULE_ROLLOUT_CAPABILITY) return true;
40
+ const rollout = document.rule_rollout;
41
+ if (!isObject(rollout) || rollout.schema_version !== 'osuite.rule_rollout_negotiation.v1'
42
+ || rollout.capability !== RULE_ROLLOUT_CAPABILITY || typeof rollout.enabled !== 'boolean') return false;
43
+ if (!rollout.enabled) return true;
44
+ return isObject(rollout.scope) && Object.keys(rollout.scope).length === scopeKeys.length && scopeKeys.every(key => safeId(rollout.scope[key]))
45
+ && rollout.scope.org_id === document.org_id && rollout.scope.runtime_id === config.runtimeId
46
+ && rollout.scope.agent_id === config.agentId && (!config.provider || rollout.scope.provider === config.provider)
47
+ && rollout.credential_id === document.credential_id && Number.isSafeInteger(rollout.connection_generation) && rollout.connection_generation >= 1
48
+ && Number.isSafeInteger(rollout.version) && rollout.version >= 1 && Date.parse(rollout.expires_at) > now
49
+ && rollout.strict_floor === true && document.posture?.mode === 'strict'
50
+ && document.posture?.on_guard_unavailable === 'block' && document.posture?.require_signature === true;
51
+ }
7
52
 
8
53
  export function localPosture(config) {
9
54
  return {
@@ -35,6 +80,7 @@ function validDocument(value, config, now, allowExpired = false) {
35
80
  if (value.credential_fingerprint !== sha256(config.apiKey || '')) return false;
36
81
  if (value.targeting?.agent_id !== config.agentId || (value.targeting?.provider || null) !== (config.provider || null)) return false;
37
82
  if (typeof value.revision !== 'string' || !/^[a-f0-9]{64}$/.test(value.revision)) return false;
83
+ if (!validNegotiation(value, config, allowExpired ? 0 : now)) return false;
38
84
  const posture = value.posture;
39
85
  if (!isObject(posture) || posture.runtime_id !== config.runtimeId || !Object.hasOwn(MODE_STRENGTH, posture.mode)) return false;
40
86
  if (!['allow', 'block'].includes(posture.on_guard_unavailable)) return false;
@@ -50,6 +96,7 @@ function configurationOnly(document) {
50
96
  return Object.fromEntries([
51
97
  'schema_version', 'runtime_id', 'org_id', 'credential_id', 'credential_fingerprint',
52
98
  'targeting', 'posture', 'revision', 'issued_at', 'valid_until',
99
+ ...(document.rule_rollout ? ['rule_rollout'] : []),
53
100
  ].map(key => [key, document[key]]));
54
101
  }
55
102
 
@@ -70,11 +117,25 @@ function readCache(store, config, now) {
70
117
  }
71
118
 
72
119
  export async function resolveRemotePosture(config, { api, store, now = Date.now() }) {
120
+ const capable = config.ruleRolloutCapability === RULE_ROLLOUT_CAPABILITY;
121
+ let acknowledged = null;
122
+ if (capable) {
123
+ const acknowledgement = await api.request('PUT', `/api/runtimes/${encodeURIComponent(config.runtimeId)}/posture`, {
124
+ capability: RULE_ROLLOUT_CAPABILITY, runtime_id: config.runtimeId, agent_id: config.agentId, issued_at: new Date(now).toISOString(),
125
+ }, { timeoutMs: 2000 });
126
+ const value = acknowledgement.body;
127
+ if (!acknowledgement.ok || !validAcknowledgement(value, config, now)) {
128
+ return { available: false, blocked: true, source: 'unavailable', posture: localPosture(config), revision: null };
129
+ }
130
+ acknowledged = value;
131
+ }
73
132
  const query = new URLSearchParams({ agent_id: config.agentId });
74
133
  if (config.provider) query.set('provider', config.provider);
75
134
  const response = await api.request('GET', `/api/runtimes/${encodeURIComponent(config.runtimeId)}/posture?${query}`, undefined, { timeoutMs: 2000 });
135
+ const rejected = [401, 403, 409].includes(response.status);
76
136
  let cached = readCache(store, config, now);
77
137
  if (response.ok && response.status === 200 && validDocument(response.body, config, now)
138
+ && (!capable || matchesAcknowledgement(response.body, acknowledged)) && preservesRolloutFloor(cached, response.body)
78
139
  && (!cached || Date.parse(response.body.issued_at) >= Date.parse(cached.issued_at))) {
79
140
  const document = configurationOnly(response.body);
80
141
  try {
@@ -82,22 +143,26 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
82
143
  // response must not replace a stronger configuration published meanwhile.
83
144
  const saved = store.update('posture', value => {
84
145
  const latest = cachedDocument(value, config, now);
85
- return latest && Date.parse(latest.issued_at) > Date.parse(document.issued_at)
146
+ return latest && (Date.parse(latest.issued_at) > Date.parse(document.issued_at) || !preservesRolloutFloor(latest, document))
86
147
  ? value : { document, mac: mac(document, config) };
87
148
  });
88
149
  cached = cachedDocument(saved, config, now);
89
150
  if (cached && canonicalJson(cached) === canonicalJson(document)) {
90
- return { available: true, blocked: false, source: 'remote', posture: document.posture, revision: document.revision };
151
+ return { available: true, blocked: false, source: 'remote', posture: document.posture, revision: document.revision,
152
+ ruleRollout: document.rule_rollout, orgId: document.org_id };
91
153
  }
92
154
  } catch {
93
155
  const posture = offlinePosture(offlinePosture(localPosture(config), readCache(store, config, now)?.posture), document.posture);
94
- return { available: false, blocked: posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
156
+ return { available: false, blocked: capable || posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
95
157
  }
96
158
  }
97
159
  const posture = offlinePosture(localPosture(config), cached?.posture);
98
160
  // Revocation and explicit scope rejection invalidate cached authority immediately.
99
- if (response.status !== 401 && response.status !== 403 && cached && Date.parse(cached.valid_until) > now) {
100
- return { available: true, blocked: false, source: 'cache', posture, revision: cached.revision };
161
+ if (!rejected && !(capable && response.ok) && cached && Date.parse(cached.valid_until) > now
162
+ && validNegotiation(cached, config, now)) {
163
+ if (capable && !matchesAcknowledgement(cached, acknowledged)) return { available: false, blocked: true, source: 'unavailable', posture, revision: cached.revision };
164
+ return { available: true, blocked: false, source: 'cache', posture, revision: cached.revision,
165
+ ruleRollout: cached.rule_rollout, orgId: cached.org_id };
101
166
  }
102
- return { available: false, blocked: posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
167
+ return { available: false, blocked: rejected || capable || posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
103
168
  }
@@ -1,5 +1,7 @@
1
1
  import { createHash, createPrivateKey, sign } from 'node:crypto';
2
2
 
3
+ export const RULE_ROLLOUT_CAPABILITY = 'osuite.scoped_rule_rollout.v1';
4
+
3
5
  export const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
6
  export const sha256 = value => createHash('sha256').update(value).digest('hex');
5
7
  export const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,199}$/.test(value) && !value.includes('..');
@@ -24,7 +26,8 @@ export function validatedBaseUrl(value, { allowInsecureHttp = false } = {}) {
24
26
  } catch { return null; }
25
27
  }
26
28
 
27
- export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutMs = 2500, maxResponseBytes = 262144 } = {}) {
29
+ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutMs = 2500,
30
+ maxResponseBytes = config.ruleRolloutCapability === RULE_ROLLOUT_CAPABILITY ? 1048576 : 262144 } = {}) {
28
31
  return {
29
32
  async request(method, endpoint, body, options = {}) {
30
33
  const baseUrl = validatedBaseUrl(config.baseUrl, config);
@@ -60,7 +63,9 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
60
63
  try {
61
64
  const response = await fetchImpl(baseUrl + endpoint, {
62
65
  method, redirect: 'manual', signal: controller.signal,
63
- headers: { 'content-type': 'application/json', 'x-api-key': config.apiKey },
66
+ headers: { 'content-type': 'application/json', 'x-api-key': config.apiKey,
67
+ ...(config.ruleRolloutCapability === RULE_ROLLOUT_CAPABILITY ? { 'x-osuite-runtime-capability': RULE_ROLLOUT_CAPABILITY } : {}),
68
+ ...(config.ruleRollout?.enabled ? { 'x-osuite-rule-rollout-version': String(config.ruleRollout.version) } : {}) },
64
69
  ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
65
70
  });
66
71
  status = response.status;