osuite 2.10.1 → 2.10.2

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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # OSuite SDK (v2.10.1)
1
+ # OSuite SDK (v2.10.2 Release Candidate)
2
2
 
3
3
  **Governed action SDK for AI agents.**
4
4
 
@@ -13,7 +13,7 @@ npm install osuite
13
13
 
14
14
  ### Connect And Verify
15
15
 
16
- For the checked-out 2.10.1 source, run from the project you want to connect:
16
+ For the checked-out 2.10.2 candidate source, run from the project you want to connect:
17
17
 
18
18
  ```bash
19
19
  node /absolute/path/to/osuite-sdk/sdk/cli.js connect
@@ -21,10 +21,11 @@ node /absolute/path/to/osuite-sdk/sdk/cli.js doctor
21
21
  node /absolute/path/to/osuite-sdk/sdk/cli.js try
22
22
  ```
23
23
 
24
- After the owner publishes 2.10.1 to npm, the equivalent pinned command is
25
- `npx osuite@2.10.1 connect`. A source release does not mean that npm's `latest`
24
+ After the owner publishes 2.10.2 to npm, the equivalent pinned command is
25
+ `npx osuite@2.10.2 connect`. A source release does not mean that npm's `latest`
26
26
  already contains it. Check `npm view osuite version` before relying on the new
27
- credential-recovery or Node-hook behavior.
27
+ installation-identity or acknowledged-recovery behavior. npm's latest was 2.10.1
28
+ when checked on 2026-10-22; this checkout is not a registry publication.
28
29
 
29
30
  The alternative installer follows npm's published `latest`:
30
31
 
@@ -518,6 +519,49 @@ For local CLI agents, `osuite connect auto` opens the browser handoff in your br
518
519
 
519
520
  Project installation refuses settings or hook paths whose symlinks resolve outside the project's real root, including linked parent directories. Credential storage also refuses any symlink, hardlink or Git-tracked destination; successful POSIX writes use mode `0600` and exact ignore entries. A browser approval alone does not retire the previous runtime credential: the versioned connection protocol waits for durable local storage and acknowledgement. If interrupted, resume the same `osuite connect` command rather than deleting its recovery journal. Manual API keys and other runtime connections are not replaced. Existing settings are merged; `disableAllHooks: true` and explicit Codex hook-disable flags stay disabled even with `--force`. Disabled setup is reported as not ready, not as a successful connection.
520
521
 
522
+ Fresh project/runtime installations now keep two separate random identifiers in
523
+ an ignored, protected `.env.identity.json` beside the runtime's credential file:
524
+ an installation identifier and the default agent identifier. Neither identifies
525
+ a person or attests hardware. Different project/runtime installations on the same
526
+ computer remain different installations, not additional licensed developers.
527
+ Do not copy identity/credential files between devices. Existing configured agent
528
+ identifiers and interrupted connection journals are preserved.
529
+
530
+ Replacing an existing connection requires its current credential, including when
531
+ only one legacy connection has that name. An omitted, incorrect or revoked key
532
+ cannot implicitly reclaim the identity. If a device/credential is lost, an
533
+ authorized administrator retires that connection and approves a new unique
534
+ identity; use an explicit new `--agent-id` if retaining the old project directory.
535
+ Preserve historical records and signing keys instead of reassigning past actions
536
+ to the replacement. A client-side installation ID is not permission to rotate.
537
+
538
+ ### SDK and MCP Credential Separation (2.10.2 Candidate)
539
+
540
+ SDK connections use `.osuite/.env`; MCP connections use `.osuite/mcp/.env`.
541
+ Their installation metadata and recovery journals live beside their respective
542
+ credential files. Connecting one runtime does not borrow another runtime's key
543
+ from a merged project configuration. If an interrupted journal conflicts with
544
+ the current credential bundle, the CLI stops before storage or acknowledgement;
545
+ inspect the current connection instead of deleting the journal to force a retry.
546
+
547
+ For an older MCP installation stored at the SDK path, stop that local MCP client
548
+ and run this explicit, local-only migration from its project directory:
549
+
550
+ ```sh
551
+ osuite connect mcp --migrate-legacy
552
+ ```
553
+
554
+ This moves the verified MCP bundle, including any identity and recovery state,
555
+ without issuing a key, contacting Studio, or acknowledging an enrollment. It
556
+ refuses ambiguous runtime ownership or an occupied destination. An interrupted
557
+ move leaves a durable marker; inspect the files and rerun the same migration,
558
+ rather than deleting its marker or copying credentials. Update the MCP launcher's
559
+ credential-file reference to `.osuite/mcp/.env` before restarting it or creating an
560
+ SDK connection. The command does not rewrite vendor launchers or enable hooks.
561
+
562
+ This section describes the unpublished 2.10.2 candidate. Do not use a previous
563
+ published CLI version to perform the new migration.
564
+
521
565
  `doctor` separates hook configuration, project enablement, credentials, connectivity, telemetry, and an enforced policy outcome. Observation-only mode, an unavailable guard (whether fail-open or fail-closed), or telemetry without a matching policy outcome does not pass the governance check. Hook warnings are printed even when the probe otherwise succeeds. The probe never executes its sample tool command and does not prove the host loaded the hooks: start or restart the runtime and verify its actual hook invocation separately.
522
566
 
523
567
  Onboarding diagnostics are opt-in: `OSUITE_ONBOARDING_METRICS=1 osuite doctor` reports only the first diagnostic pass/fail result and, when supplied by the installer, its start timestamp. It sends no command text, filesystem paths or diagnostic log. Reconnection or a later passing check does not erase the first failure. Without the opt-in, no diagnostic measurement is sent. Reporting failure never changes the doctor result. Aggregate dashboards distinguish reported samples from all connected agents.
package/cli.js CHANGED
@@ -8,6 +8,11 @@ import { fileURLToPath } from 'node:url';
8
8
  import { OSuite, buildReviewSurface } from './osuite.js';
9
9
  import { runTryFlow } from './tryFlow.js';
10
10
  import { runDoctorWithMeasurement } from './activationMetrics.js';
11
+ import {
12
+ credentialDigest, getInstallationIdentity, migrateMcpInstallation, parseInstallationIdentity,
13
+ readInstallationBundle, readInstallationIdentity, readMcpMigration,
14
+ MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH,
15
+ } from './installationIdentity.js';
11
16
  import {
12
17
  CREDENTIAL_PATHS, acquireCredentialLock, inspectCredentialFile,
13
18
  readCredentialFile, removeCredentialFile, writeCredentialFile,
@@ -52,6 +57,7 @@ const GIT_OBSERVATION_RISKS = {
52
57
  const PUBLIC_FILE_HOST_HINTS = ['transfer.sh', 'file.io', 'tmpfiles.org', '0x0.st', 'ufile.io', 'gofile.io', 'wetransfer.com'];
53
58
  const SECURITY_CONTROL_WEAKENING_RE = /(\bspctl\b[\s\S]*(--master-disable|--global-disable|--disable)|\bcsrutil\b[\s\S]*\bdisable\b|Set-MpPreference[\s\S]*Disable(?:RealtimeMonitoring|BehaviorMonitoring|IOAVProtection)[\s\S]*(true|\$true|1)|netsh\s+advfirewall\s+set\s+allprofiles\s+state\s+off|\bsystemctl\b[\s\S]*\b(stop|disable|mask)\b[\s\S]*(auditd|falcon|crowdstrike|osquery|defender|mdatp|sentinel|carbonblack|firewalld|ufw)|\bufw\b[\s\S]*\bdisable\b)/i;
54
59
  const DEFAULT_BASE_URL = 'https://studio.osuite.ai';
60
+ const CLI_CREDENTIAL_PATHS = [...CREDENTIAL_PATHS, MCP_ENV_PATH];
55
61
  const PROJECT_BOOTSTRAPS = {
56
62
  codex: {
57
63
  label: 'Codex hook runtime',
@@ -115,10 +121,8 @@ function write(value = '') {
115
121
  process.stdout.write(`${value}\n`);
116
122
  }
117
123
 
118
- function loadDotenvFile(relativePath) {
119
- const absolute = path.join(process.cwd(), relativePath);
120
- if (!fs.existsSync(absolute)) return;
121
- const body = fs.readFileSync(absolute, 'utf8');
124
+ function parseEnvBody(body = '') {
125
+ const env = Object.create(null);
122
126
  body.split(/\r?\n/).forEach((line) => {
123
127
  const trimmed = line.trim();
124
128
  if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) return;
@@ -126,12 +130,23 @@ function loadDotenvFile(relativePath) {
126
130
  const key = rawKey.trim();
127
131
  let value = rawValue.join('=').trim().replace(/^['"]|['"]$/g, '');
128
132
  if (value.includes(' #')) value = value.slice(0, value.indexOf(' #')).trim();
129
- if (key && !process.env[key]) process.env[key] = value;
133
+ if (key && !env[key]) env[key] = value;
130
134
  });
135
+ return env;
136
+ }
137
+
138
+ function loadDotenvFile(relativePath) {
139
+ const absolute = path.join(process.cwd(), relativePath);
140
+ if (!fs.existsSync(absolute)) return;
141
+ for (const [key, value] of Object.entries(parseEnvBody(fs.readFileSync(absolute, 'utf8')))) {
142
+ if (!process.env[key]) process.env[key] = value;
143
+ }
131
144
  }
132
145
 
133
146
  function loadProjectEnvironment() {
134
- [...CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
147
+ // Enrollment selects one whole runtime bundle, never a merged global env.
148
+ if (process.argv[2] === 'connect') return;
149
+ [...CLI_CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
135
150
  if (process.argv[2] === 'doctor' && !inspectCredentialFile(process.cwd(), relativePath).safe) return;
136
151
  loadDotenvFile(relativePath);
137
152
  });
@@ -165,14 +180,15 @@ function envValue(name, fallback) {
165
180
  return process.env[name] || process.env[fallback] || '';
166
181
  }
167
182
 
168
- function readConfig() {
183
+ function readConfig(env = process.env) {
184
+ const value = (name, fallback) => env[name] || env[fallback] || '';
169
185
  return {
170
- baseUrl: envValue('OSUITE_BASE_URL', 'DASHCLAW_BASE_URL'),
171
- apiKey: envValue('OSUITE_API_KEY', 'DASHCLAW_API_KEY'),
172
- agentId: envValue('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID') || 'osuite-cli',
173
- agentKeyId: envValue('OSUITE_AGENT_KEY_ID', 'DASHCLAW_AGENT_KEY_ID') || null,
174
- runtimeAdapterId: process.env.OSUITE_RUNTIME_ADAPTER_ID || '',
175
- signatureMode: process.env.OSUITE_SIGNATURE_MODE || '',
186
+ baseUrl: value('OSUITE_BASE_URL', 'DASHCLAW_BASE_URL'),
187
+ apiKey: value('OSUITE_API_KEY', 'DASHCLAW_API_KEY'),
188
+ agentId: value('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID') || 'osuite-cli',
189
+ agentKeyId: value('OSUITE_AGENT_KEY_ID', 'DASHCLAW_AGENT_KEY_ID') || null,
190
+ runtimeAdapterId: env.OSUITE_RUNTIME_ADAPTER_ID || '',
191
+ signatureMode: env.OSUITE_SIGNATURE_MODE || '',
176
192
  };
177
193
  }
178
194
 
@@ -227,14 +243,6 @@ function buildConnectHandoffUrl({ baseUrl, runtime, code }) {
227
243
  return url.toString();
228
244
  }
229
245
 
230
- function defaultAgentIdForRuntime(runtime) {
231
- if (runtime === 'codex') return 'codex-runtime';
232
- if (runtime === 'claude') return 'claude-code-runtime';
233
- if (runtime === 'cursor') return 'cursor-runtime';
234
- if (runtime === 'mcp') return 'mcp-runtime';
235
- return 'sdk-runtime';
236
- }
237
-
238
246
  function sanitizeConfiguredAgentId(runtime, agentId) {
239
247
  const value = String(agentId || '').trim();
240
248
  if (!value) return '';
@@ -266,7 +274,61 @@ function envPathForRuntime(runtime) {
266
274
  if (runtime === 'codex') return '.codex/.env';
267
275
  if (runtime === 'claude') return '.claude/.env';
268
276
  if (runtime === 'cursor') return '.cursor/.env';
269
- return '.osuite/.env';
277
+ return runtime === 'mcp' ? MCP_ENV_PATH : SDK_ENV_PATH;
278
+ }
279
+
280
+ function connectionConfig(runtime, liveEnv, { dryRun = false } = {}) {
281
+ if (liveEnv !== null) return readConfig(parseEnvBody(liveEnv));
282
+ const shell = readConfig(SHELL_ENV);
283
+ if (runtimeMatchesConfiguredAdapter(runtime, shell.runtimeAdapterId)) return shell;
284
+ const legacy = dryRun ? null : readCredentialFile(process.cwd(), '.env');
285
+ if (legacy !== null) {
286
+ const config = readConfig(parseEnvBody(legacy));
287
+ if (runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)) return config;
288
+ }
289
+ return readConfig(!shell.apiKey && !shell.runtimeAdapterId ? { OSUITE_BASE_URL: shell.baseUrl } : {});
290
+ }
291
+
292
+ function parseConnectionJournal(raw) {
293
+ if (raw === null) return null;
294
+ try {
295
+ const journal = JSON.parse(raw);
296
+ if (journal && typeof journal === 'object' && !Array.isArray(journal)) return journal;
297
+ } catch { /* Report only metadata, never journal contents. */ }
298
+ throw new Error('The saved connection recovery journal is invalid; it was left unchanged.');
299
+ }
300
+
301
+ function assertRecoveryState(journal, { runtime, baseUrl, agentId, liveEnv, config, installation }) {
302
+ if (journal.protocol_version !== 2 || journal.runtime !== runtime || journal.base_url !== baseUrl
303
+ || typeof journal.agent_id !== 'string' || !journal.agent_id || (agentId && journal.agent_id !== agentId)
304
+ || !journal.session?.device_code || !journal.session?.poll_token) {
305
+ throw new Error('A recovery journal exists for a different connection. Resume its original runtime, agent and Studio URL before reconnecting.');
306
+ }
307
+ if (journal.credential) assertConnectionCredentialScope(journal.credential, { baseUrl, runtime, agentId: journal.agent_id });
308
+ if (Object.hasOwn(journal, 'live_env_sha256')) {
309
+ const digest = journal.live_env_sha256;
310
+ const promoted = journal.credential && liveEnv === formatEnvBody(journal.credential.env);
311
+ if ((digest !== null && (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)))
312
+ || (credentialDigest(liveEnv) !== digest && !promoted)) {
313
+ throw new Error('Connection recovery conflicts with a changed live credential bundle. Stopped without replacing it; inspect the saved handoff in Studio before retrying.');
314
+ }
315
+ } else if (liveEnv !== null && (config.agentId !== journal.agent_id
316
+ || !runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) || normalizedBaseUrl(config.baseUrl) !== baseUrl)) {
317
+ // Pre-candidate journals lack the local snapshot. Never let their agent ID
318
+ // override a different live scope; the server still validates the predecessor.
319
+ throw new Error('Legacy connection recovery conflicts with the live runtime, agent or Studio URL; files were left unchanged.');
320
+ }
321
+ // A fresh explicit choice may differ from inherited config. Retain that
322
+ // original context for retries, rather than letting a new flag waive conflicts.
323
+ const explicitSelection = journal.live_env_sha256 === null
324
+ && journal.explicit_agent_selection?.agent_id === journal.agent_id
325
+ && journal.explicit_agent_selection?.configured_agent_id === config.agentId;
326
+ if (liveEnv === null && config.agentId !== 'osuite-cli' && config.agentId !== journal.agent_id && !explicitSelection) {
327
+ throw new Error('Connection recovery conflicts with the configured agent; files were left unchanged.');
328
+ }
329
+ if (journal.installation_id && journal.installation_id !== installation?.installation_id) {
330
+ throw new Error('Connection recovery installation identity changed or is missing; files were left unchanged.');
331
+ }
270
332
  }
271
333
 
272
334
  function orderedEnvEntries(env = {}) {
@@ -331,10 +393,11 @@ async function postJson(url, body) {
331
393
  return { response, payload };
332
394
  }
333
395
 
334
- async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey }) {
396
+ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId }) {
335
397
  const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/start`, {
336
398
  runtime,
337
399
  agent_id: agentId,
400
+ ...(installationId ? { installation_id: installationId } : {}),
338
401
  project_root: process.cwd(),
339
402
  protocol_version: 2,
340
403
  client_version: pkg.version,
@@ -423,9 +486,10 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
423
486
  return null;
424
487
  }
425
488
 
426
- async function finalizeDeviceConnect(journal, journalPath) {
489
+ async function finalizeDeviceConnect(journal, journalPath, validateLive) {
427
490
  const { credential, session, base_url: baseUrl } = journal;
428
491
  for (let attempt = 0; attempt < 3; attempt += 1) {
492
+ validateLive();
429
493
  let result;
430
494
  try {
431
495
  result = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/ack`, {
@@ -435,6 +499,7 @@ async function finalizeDeviceConnect(journal, journalPath) {
435
499
  } catch {
436
500
  // A lost response may mean the transaction committed. Retry the same receipt.
437
501
  }
502
+ validateLive();
438
503
  if (result?.response.ok) {
439
504
  if (result.payload.status !== 'finalized' || result.payload.key_id !== credential.key_id || typeof result.payload.active !== 'boolean') {
440
505
  throw new Error('Studio did not confirm this saved connection. The recovery journal was left unchanged; retry the same osuite connect command.');
@@ -457,6 +522,19 @@ async function finalizeDeviceConnect(journal, journalPath) {
457
522
  throw new Error('Could not confirm finalization. The recovery journal is saved; rerun the same osuite connect command to resume safely.');
458
523
  }
459
524
 
525
+ function assertConnectionCredentialScope(credential, { baseUrl, runtime, agentId }) {
526
+ const adapter = { codex: 'codex_hooks', claude: 'claude_code_hooks', cursor: 'cursor_hooks' }[runtime] || runtime;
527
+ const env = credential?.env;
528
+ if (credential?.protocol_version !== 2 || !env || !credential.key_id || !credential.ack_token
529
+ || !env.OSUITE_API_KEY || !env.OSUITE_PRIVATE_KEY_BASE64
530
+ || typeof env.OSUITE_BASE_URL !== 'string' || normalizedBaseUrl(env.OSUITE_BASE_URL) !== baseUrl
531
+ || env.OSUITE_AGENT_ID !== agentId || env.OSUITE_RUNTIME_ADAPTER_ID !== adapter
532
+ || (credential.runtime !== undefined && credential.runtime !== runtime)
533
+ || (credential.agent_id !== undefined && credential.agent_id !== agentId)) {
534
+ throw new Error('Delivered credentials do not match this connection. No acknowledgement or local replacement was attempted; inspect this enrollment in Studio.');
535
+ }
536
+ }
537
+
460
538
  function projectFilePath(relativePath) {
461
539
  return resolveProjectPath(process.cwd(), relativePath);
462
540
  }
@@ -658,6 +736,7 @@ function printHelp() {
658
736
  write(' osuite external configure --provider babyblue_invinoveritas --mode shadow --api-key <key> --expected-source-class independent_mediator');
659
737
  write(' osuite connect [auto|codex|claude|cursor|sdk|mcp] Detect runtime and start browser handoff');
660
738
  write(' --no-browser prints the link instead of opening it');
739
+ write(' osuite connect mcp --migrate-legacy Move legacy MCP state locally; no enrollment or ACK');
661
740
  write(' osuite init [sdk|codex|claude|cursor|mcp] Prepare a runtime lane');
662
741
  write('');
663
742
  write(c('Environment', ANSI.bold));
@@ -1104,7 +1183,7 @@ async function doctor() {
1104
1183
  write(c('Checking the local developer entry point.', ANSI.dim));
1105
1184
  write('');
1106
1185
 
1107
- const credentialChecks = [...CREDENTIAL_PATHS.flatMap((file) => [file, `${file}.connect.json`, `${file}.connect.lock`]), '.env']
1186
+ const credentialChecks = [...CLI_CREDENTIAL_PATHS.flatMap((file) => [file, `${file}.identity.json`, `${file}.connect.json`, `${file}.connect.lock`]), MCP_MIGRATION_PATH, '.env']
1108
1187
  .map((relativePath) => inspectCredentialFile(process.cwd(), relativePath));
1109
1188
  const unsafeCredentials = credentialChecks.filter((check) => check.exists && !check.safe);
1110
1189
  for (const check of credentialChecks.filter((item) => item.exists)) {
@@ -1115,6 +1194,11 @@ async function doctor() {
1115
1194
  process.exitCode = 1;
1116
1195
  return false;
1117
1196
  }
1197
+ if (credentialChecks.some((check) => check.exists && check.relativePath === MCP_MIGRATION_PATH)) {
1198
+ writeCheckLine('warn', 'MCP migration', 'resume osuite connect mcp --migrate-legacy before using either SDK or MCP.');
1199
+ process.exitCode = 1;
1200
+ return false;
1201
+ }
1118
1202
  if (credentialChecks.some((check) => check.exists && check.relativePath.endsWith('.connect.json'))) {
1119
1203
  writeCheckLine('warn', 'Connection recovery', 'resume the original osuite connect command before running this runtime.');
1120
1204
  process.exitCode = 1;
@@ -1179,7 +1263,10 @@ async function tryWalkthrough(args) {
1179
1263
  if (args._.length || Object.keys(args).some((key) => !['_', 'timeout-ms'].includes(key))) {
1180
1264
  throw new Error('osuite try accepts no command arguments: its output is fixed. Only --timeout-ms may be set.');
1181
1265
  }
1182
- for (const file of [...CREDENTIAL_PATHS, '.env']) {
1266
+ if (inspectCredentialFile(process.cwd(), MCP_MIGRATION_PATH).exists) {
1267
+ throw new Error('Resume osuite connect mcp --migrate-legacy before starting the walkthrough.');
1268
+ }
1269
+ for (const file of [...CLI_CREDENTIAL_PATHS, '.env']) {
1183
1270
  const check = inspectCredentialFile(process.cwd(), file);
1184
1271
  if (check.exists && !check.safe) throw new Error('Credential storage needs attention. Run osuite doctor before starting the walkthrough.');
1185
1272
  if (inspectCredentialFile(process.cwd(), `${file}.connect.json`).exists) {
@@ -1406,39 +1493,63 @@ async function init(target = 'generic', args = {}) {
1406
1493
  }
1407
1494
 
1408
1495
  async function connectProject(target = 'auto', args = {}) {
1409
- const config = readConfig();
1410
1496
  const runtime = detectRuntimeTarget(target);
1497
+ const envPath = envPathForRuntime(runtime);
1498
+ const journalPath = `${envPath}.connect.json`;
1499
+ const liveEnv = args['dry-run'] ? null : readCredentialFile(process.cwd(), envPath);
1500
+ const config = connectionConfig(runtime, liveEnv, { dryRun: Boolean(args['dry-run']) });
1411
1501
  const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || DEFAULT_BASE_URL);
1502
+ const saved = args['dry-run'] ? null : readCredentialFile(process.cwd(), journalPath);
1503
+ let storedJournal = saved;
1504
+ let journal = parseConnectionJournal(saved);
1505
+ const existingInstallation = args['dry-run'] ? null : readInstallationIdentity(process.cwd(), envPath, runtime);
1506
+ if (journal) {
1507
+ assertRecoveryState(journal, { runtime, baseUrl, agentId: args['agent-id'], liveEnv, config, installation: existingInstallation });
1508
+ } else if (liveEnv !== null && config.runtimeAdapterId && !runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)) {
1509
+ throw new Error('The live credential bundle belongs to a different runtime; it was left unchanged.');
1510
+ }
1511
+ // Validation above is read-only: even missing metadata must not be recreated
1512
+ // over a conflicting live installation merely because a receipt is resumable.
1513
+ const installation = existingInstallation || getInstallationIdentity(process.cwd(), envPath, runtime, { dryRun: Boolean(args['dry-run']) });
1412
1514
  const configuredAgentId = sanitizeConfiguredAgentId(
1413
1515
  runtime,
1414
- runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)
1415
- ? envValue('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID')
1516
+ runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) && config.agentId !== 'osuite-cli'
1517
+ ? config.agentId
1416
1518
  : '',
1417
1519
  );
1418
- const agentId = String(args['agent-id'] || configuredAgentId || defaultAgentIdForRuntime(runtime));
1520
+ const agentId = String(args['agent-id'] || journal?.agent_id || configuredAgentId || installation.agent_id);
1521
+ const validateLive = (receipt = journal) => {
1522
+ if (readCredentialFile(process.cwd(), journalPath) !== storedJournal) {
1523
+ throw new Error('The connection recovery journal changed during this operation; it was left unchanged. Inspect the handoff in Studio before retrying.');
1524
+ }
1525
+ const current = readCredentialFile(process.cwd(), envPath);
1526
+ assertRecoveryState(receipt, { runtime, baseUrl, agentId, liveEnv: current,
1527
+ config: connectionConfig(runtime, current), installation: readInstallationIdentity(process.cwd(), envPath, runtime) });
1528
+ };
1529
+ const saveJournal = () => {
1530
+ validateLive();
1531
+ const body = `${JSON.stringify(journal)}\n`;
1532
+ writeCredentialFile(process.cwd(), journalPath, body);
1533
+ storedJournal = body;
1534
+ };
1419
1535
  const dryRunCode = String(args.code || generateConnectCode()).trim() || generateConnectCode();
1420
1536
  let connectPayload = null;
1421
1537
  let code = dryRunCode;
1422
1538
  let handoffUrl = buildConnectHandoffUrl({ baseUrl, runtime, code });
1423
1539
  const hasApiKey = Boolean(config.apiKey);
1424
- const envPath = envPathForRuntime(runtime);
1425
- const journalPath = `${envPath}.connect.json`;
1426
- let journal = null;
1427
-
1428
1540
  if (!args['dry-run']) {
1429
- const saved = readCredentialFile(process.cwd(), journalPath);
1430
- if (saved) {
1431
- try { journal = JSON.parse(saved); } catch { throw new Error('The saved connection recovery journal is invalid; it was left unchanged.'); }
1432
- if (journal.protocol_version !== 2 || journal.base_url !== baseUrl || journal.runtime !== runtime || journal.agent_id !== agentId || !journal.session?.device_code || !journal.session?.poll_token) {
1433
- throw new Error('A recovery journal exists for a different connection. Resume its original runtime, agent and Studio URL before reconnecting.');
1434
- }
1541
+ if (journal) {
1435
1542
  connectPayload = journal.session;
1436
1543
  } else {
1437
1544
  const previousKey = normalizedBaseUrl(config.baseUrl) === baseUrl && runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) && configuredAgentId === agentId ? config.apiKey : '';
1438
- connectPayload = await startDeviceConnect({ baseUrl, runtime, agentId, previousKey });
1545
+ connectPayload = await startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId: installation.installation_id });
1439
1546
  if (connectPayload.protocol_version === 2) {
1440
- journal = { protocol_version: 2, base_url: baseUrl, runtime, agent_id: agentId, session: connectPayload };
1441
- writeCredentialFile(process.cwd(), journalPath, `${JSON.stringify(journal)}\n`);
1547
+ journal = { protocol_version: 2, base_url: baseUrl, runtime, agent_id: agentId, installation_id: installation.installation_id,
1548
+ live_env_sha256: credentialDigest(liveEnv), session: connectPayload };
1549
+ if (liveEnv === null && args['agent-id']) {
1550
+ journal.explicit_agent_selection = { agent_id: agentId, configured_agent_id: config.agentId };
1551
+ }
1552
+ saveJournal();
1442
1553
  } else {
1443
1554
  if (hasApiKey && fs.existsSync(projectFilePath(envPath))) {
1444
1555
  throw new Error('This Studio does not support acknowledged reconnect. Upgrade Studio before replacing existing credentials; they were left unchanged.');
@@ -1472,7 +1583,7 @@ async function connectProject(target = 'auto', args = {}) {
1472
1583
  if (args['dry-run']) {
1473
1584
  write(`Dry run: would install project hook files for ${runtime}.`);
1474
1585
  } else {
1475
- install = await installRuntimeProjectBootstrap(runtime, args, { nextSteps: false });
1586
+ install = await installRuntimeProjectBootstrap(runtime, { ...args, 'base-url': baseUrl }, { nextSteps: false });
1476
1587
  }
1477
1588
  } else {
1478
1589
  write(c('Runtime setup', ANSI.bold));
@@ -1506,18 +1617,25 @@ async function connectProject(target = 'auto', args = {}) {
1506
1617
  protocolVersion: connectPayload.protocol_version || 1,
1507
1618
  });
1508
1619
  } catch (error) {
1509
- if (journal && error.code === 'DEVICE_CONNECT_EXPIRED') removeCredentialFile(process.cwd(), journalPath);
1620
+ if (journal && error.code === 'DEVICE_CONNECT_EXPIRED') {
1621
+ validateLive();
1622
+ removeCredentialFile(process.cwd(), journalPath);
1623
+ }
1510
1624
  throw error;
1511
1625
  }
1512
1626
  }
1513
1627
 
1514
1628
  if (credential?.env) {
1515
1629
  if (journal) {
1630
+ // Check both a fresh delivery and a journal resumed after process death.
1631
+ assertConnectionCredentialScope(credential, { baseUrl, runtime, agentId });
1632
+ validateLive();
1516
1633
  journal = { ...journal, credential };
1517
1634
  // fsync both the file and its directory before telling the server to retire
1518
1635
  // the old key. The live env stays unchanged until that transaction commits.
1519
- writeCredentialFile(process.cwd(), journalPath, `${JSON.stringify(journal)}\n`);
1520
- await finalizeDeviceConnect(journal, journalPath);
1636
+ saveJournal();
1637
+ await finalizeDeviceConnect(journal, journalPath, validateLive);
1638
+ validateLive();
1521
1639
  }
1522
1640
  const result = writeCredentialFile(process.cwd(), envPath, formatEnvBody(credential.env));
1523
1641
  if (journal) removeCredentialFile(process.cwd(), journalPath);
@@ -1549,7 +1667,9 @@ async function connectProject(target = 'auto', args = {}) {
1549
1667
  } else {
1550
1668
  write('');
1551
1669
  write(c('Not connected: nobody approved this terminal in the browser in time.', ANSI.yellow));
1552
- write(` Run osuite connect ${runtime} again for a new code${install?.ok ? '; the hook files are already installed, only the credentials are missing' : ''}.`);
1670
+ write(journal
1671
+ ? ` Run osuite connect ${runtime} again to resume this same pending connection; no new request is created while this code remains valid.`
1672
+ : ` Run osuite connect ${runtime} again for a new code${install?.ok ? '; the hook files are already installed, only the credentials are missing' : ''}.`);
1553
1673
  write(' If the browser did not open, copy the handoff link above into it.');
1554
1674
  process.exitCode = 1;
1555
1675
  }
@@ -1568,11 +1688,70 @@ async function connectProject(target = 'auto', args = {}) {
1568
1688
  }
1569
1689
 
1570
1690
  async function connect(target = 'auto', args = {}) {
1571
- if (args['dry-run']) return connectProject(target, args);
1572
1691
  const runtime = detectRuntimeTarget(target);
1573
- const release = acquireCredentialLock(process.cwd(), envPathForRuntime(runtime));
1574
- try { return await connectProject(runtime, args); }
1575
- finally { release(); }
1692
+ if (args['migrate-legacy'] && runtime !== 'mcp') throw new Error('Legacy migration requires osuite connect mcp --migrate-legacy.');
1693
+ if (args['dry-run']) {
1694
+ if (args['migrate-legacy']) return write(`Dry run: would move legacy MCP credentials, identity and journal from ${SDK_ENV_PATH} to ${MCP_ENV_PATH}; no network or file changes.`);
1695
+ return connectProject(runtime, args);
1696
+ }
1697
+ const releases = [];
1698
+ try {
1699
+ if (args['migrate-legacy']) releases.push(acquireCredentialLock(process.cwd(), SDK_ENV_PATH));
1700
+ releases.push(acquireCredentialLock(process.cwd(), envPathForRuntime(runtime)));
1701
+ if (args['migrate-legacy']) return migrateLegacyMcp(args);
1702
+ if (runtime === 'sdk' || runtime === 'mcp') {
1703
+ if (readCredentialFile(process.cwd(), MCP_MIGRATION_PATH) !== null) {
1704
+ throw new Error('MCP migration is incomplete. Resume osuite connect mcp --migrate-legacy before using either runtime.');
1705
+ }
1706
+ const legacy = readInstallationBundle(process.cwd(), SDK_ENV_PATH);
1707
+ const legacyEnv = parseEnvBody(legacy.env || '');
1708
+ const legacyConfig = readConfig(legacyEnv);
1709
+ if (!runtimeMatchesConfiguredAdapter('sdk', legacyConfig.runtimeAdapterId)
1710
+ && !runtimeMatchesConfiguredAdapter('mcp', legacyConfig.runtimeAdapterId)
1711
+ && (legacyConfig.apiKey || legacyConfig.agentId !== 'osuite-cli' || legacyEnv.OSUITE_PRIVATE_KEY_BASE64 || legacyEnv.DASHCLAW_PRIVATE_KEY_BASE64)) {
1712
+ throw new Error('Shared legacy credential ownership is ambiguous. Verify and declare its OSUITE_RUNTIME_ADAPTER_ID before connecting; MCP owners must then use osuite connect mcp --migrate-legacy. Files were left unchanged.');
1713
+ }
1714
+ if (legacyMcpPresent(legacy)) {
1715
+ throw new Error('Legacy MCP state conflicts with the shared .osuite/.env namespace. Run osuite connect mcp --migrate-legacy to move it explicitly; no credentials were replaced.');
1716
+ }
1717
+ }
1718
+ return await connectProject(runtime, args);
1719
+ } finally { releases.reverse().forEach(release => release()); }
1720
+ }
1721
+
1722
+ function legacyMcpPresent(bundle) {
1723
+ const config = readConfig(parseEnvBody(bundle.env || ''));
1724
+ const journal = parseConnectionJournal(bundle.journal);
1725
+ let identity;
1726
+ try { identity = bundle.identity === null ? null : JSON.parse(bundle.identity); }
1727
+ catch { throw new Error('Invalid installation identity file; it was left unchanged.'); }
1728
+ return runtimeMatchesConfiguredAdapter('mcp', config.runtimeAdapterId) || identity?.runtime === 'mcp' || journal?.runtime === 'mcp';
1729
+ }
1730
+
1731
+ function migrateLegacyMcp(args) {
1732
+ const inspected = readMcpMigration(process.cwd());
1733
+ if (!inspected.manifest && Object.values(inspected.destination).some(body => body !== null)) {
1734
+ throw new Error('MCP migration destination is already occupied; nothing was overwritten.');
1735
+ }
1736
+ const { bundle } = inspected;
1737
+ if (!legacyMcpPresent(bundle)) throw new Error('No unambiguous legacy MCP installation to migrate; files were left unchanged.');
1738
+ const config = readConfig(parseEnvBody(bundle.env || ''));
1739
+ const installation = parseInstallationIdentity(bundle.identity, 'mcp');
1740
+ const journal = parseConnectionJournal(bundle.journal);
1741
+ if (bundle.env !== null && (!runtimeMatchesConfiguredAdapter('mcp', config.runtimeAdapterId) || config.agentId === 'osuite-cli')) {
1742
+ throw new Error('Legacy MCP migration conflicts with an ambiguous or different live runtime; files were left unchanged.');
1743
+ }
1744
+ const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || journal?.base_url);
1745
+ if ((args['base-url'] && config.baseUrl && normalizedBaseUrl(config.baseUrl) !== baseUrl)
1746
+ || (args['agent-id'] && args['agent-id'] !== config.agentId)) {
1747
+ throw new Error('MCP migration cannot change the live agent or Studio URL; files were left unchanged.');
1748
+ }
1749
+ if (journal) assertRecoveryState(journal, { runtime: 'mcp', baseUrl, agentId: args['agent-id'], liveEnv: bundle.env, config, installation });
1750
+ migrateMcpInstallation(process.cwd(), inspected);
1751
+ write(`MCP migration complete: moved credentials, identity and recovery state to ${MCP_ENV_PATH}.`);
1752
+ write('No enrollment, acknowledgement or server identity change was performed.');
1753
+ write('Update the MCP launcher to read this env path before restarting it or connecting SDK in this project.');
1754
+ write('Run osuite connect mcp to resume a saved handoff or rotate with the same identity. SDK continues to use .osuite/.env.');
1576
1755
  }
1577
1756
 
1578
1757
  async function main() {
@@ -0,0 +1,113 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { prepareCredentialFile, readCredentialFile, removeCredentialFile, writeCredentialFile } from './credentials.js';
5
+
6
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
7
+ const PREFIX = { codex: 'codex-runtime', claude: 'claude-code-runtime', cursor: 'cursor-runtime', mcp: 'mcp-runtime', sdk: 'sdk-runtime' };
8
+ export const SDK_ENV_PATH = '.osuite/.env';
9
+ export const MCP_ENV_PATH = '.osuite/mcp/.env';
10
+ export const MCP_MIGRATION_PATH = '.osuite/.env.migrate-mcp.json';
11
+ const BUNDLE_FILES = { env: '', identity: '.identity.json', journal: '.connect.json' };
12
+
13
+ export function parseInstallationIdentity(raw, runtime) {
14
+ if (raw === null) return null;
15
+ let identity;
16
+ try { identity = JSON.parse(raw); } catch { throw new Error('Invalid installation identity file; it was left unchanged.'); }
17
+ if (identity?.schema_version !== 'osuite.installation.v1' || identity.runtime !== runtime
18
+ || typeof identity.installation_id !== 'string' || !UUID.test(identity.installation_id)
19
+ || typeof identity.agent_id !== 'string' || !identity.agent_id.startsWith(`${PREFIX[runtime]}-`)
20
+ || !UUID.test(identity.agent_id.slice(PREFIX[runtime].length + 1))) {
21
+ throw new Error('Installation identity does not match this runtime; it was left unchanged.');
22
+ }
23
+ return identity;
24
+ }
25
+
26
+ export function readInstallationIdentity(projectRoot, envPath, runtime) {
27
+ if (!Object.hasOwn(PREFIX, runtime)) throw new Error('Unsupported installation runtime.');
28
+ return parseInstallationIdentity(readCredentialFile(projectRoot, `${envPath}.identity.json`), runtime);
29
+ }
30
+
31
+ // A project/runtime installation identifier is metadata, not a human identity or
32
+ // hardware attestation. Rotation still requires the current scoped credential.
33
+ export function getInstallationIdentity(projectRoot, envPath, runtime, { dryRun = false } = {}) {
34
+ if (!Object.hasOwn(PREFIX, runtime)) throw new Error('Unsupported installation runtime.');
35
+ const relativePath = `${envPath}.identity.json`;
36
+ // A preview must also work before Git is installed and must not inspect or
37
+ // repair private credential files. Its temporary IDs are never enrolled.
38
+ const existing = dryRun ? null : readInstallationIdentity(projectRoot, envPath, runtime);
39
+ if (existing) return existing;
40
+ const identity = { schema_version: 'osuite.installation.v1', runtime,
41
+ installation_id: crypto.randomUUID(), agent_id: `${PREFIX[runtime]}-${crypto.randomUUID()}` };
42
+ if (!dryRun) writeCredentialFile(projectRoot, relativePath, `${JSON.stringify(identity)}\n`);
43
+ return identity;
44
+ }
45
+
46
+ export function credentialDigest(raw) {
47
+ return raw === null ? null : crypto.createHash('sha256').update(raw).digest('hex');
48
+ }
49
+
50
+ export function readInstallationBundle(projectRoot, envPath) {
51
+ return Object.fromEntries(Object.entries(BUNDLE_FILES).map(([kind, suffix]) => [kind, readCredentialFile(projectRoot, `${envPath}${suffix}`)]));
52
+ }
53
+
54
+ export function readMcpMigration(projectRoot) {
55
+ const raw = readCredentialFile(projectRoot, MCP_MIGRATION_PATH);
56
+ const source = readInstallationBundle(projectRoot, SDK_ENV_PATH);
57
+ const destination = readInstallationBundle(projectRoot, MCP_ENV_PATH);
58
+ if (raw === null) return { manifest: null, source, destination, bundle: source };
59
+ let manifest;
60
+ try { manifest = JSON.parse(raw); } catch { throw new Error('Invalid MCP migration marker; files were left unchanged.'); }
61
+ if (manifest?.schema_version !== 'osuite.mcp-migration.v1' || !manifest.files
62
+ || Object.keys(manifest.files).sort().join(',') !== Object.keys(BUNDLE_FILES).sort().join(',')
63
+ || Object.values(manifest.files).some(value => value !== null && (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value)))) {
64
+ throw new Error('Invalid MCP migration marker; files were left unchanged.');
65
+ }
66
+ const bundle = {};
67
+ for (const kind of Object.keys(BUNDLE_FILES)) {
68
+ const expected = manifest.files[kind];
69
+ const bodies = [source[kind], destination[kind]].filter(body => body !== null);
70
+ if (expected === null ? bodies.length !== 0 : bodies.length !== 1 || credentialDigest(bodies[0]) !== expected) {
71
+ throw new Error('MCP migration conflicts with changed, missing or duplicated files; nothing was overwritten.');
72
+ }
73
+ bundle[kind] = bodies[0] ?? null;
74
+ }
75
+ return { manifest, source, destination, bundle };
76
+ }
77
+
78
+ function syncDirectory(directory) {
79
+ if (process.platform === 'win32') return;
80
+ const fd = fs.openSync(directory, fs.constants.O_RDONLY | (fs.constants.O_DIRECTORY || 0) | (fs.constants.O_NOFOLLOW || 0));
81
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
82
+ }
83
+
84
+ // Explicit, local-only migration. The caller must hold BOTH credential locks and
85
+ // validate runtime/recovery scope first. A durable, secret-free marker blocks
86
+ // either CLI enrollment lane until every original file has moved, never copied
87
+ // or overwritten. Existing server identity and keys are not changed by the move.
88
+ export function migrateMcpInstallation(projectRoot, inspected) {
89
+ let current = readMcpMigration(projectRoot);
90
+ if (JSON.stringify(current) !== JSON.stringify(inspected)) throw new Error('MCP migration files changed during validation; retry after inspection.');
91
+ if (!current.manifest) {
92
+ if (Object.values(current.destination).some(body => body !== null)) throw new Error('MCP migration destination is already occupied; nothing was overwritten.');
93
+ for (const [kind, suffix] of Object.entries(BUNDLE_FILES)) {
94
+ if (current.source[kind] !== null) prepareCredentialFile(projectRoot, `${MCP_ENV_PATH}${suffix}`);
95
+ }
96
+ writeCredentialFile(projectRoot, MCP_MIGRATION_PATH, `${JSON.stringify({ schema_version: 'osuite.mcp-migration.v1',
97
+ files: Object.fromEntries(Object.entries(current.source).map(([kind, body]) => [kind, credentialDigest(body)])) })}\n`);
98
+ }
99
+ for (const [kind, suffix] of Object.entries(BUNDLE_FILES)) {
100
+ current = readMcpMigration(projectRoot);
101
+ if (current.source[kind] === null) continue;
102
+ const from = prepareCredentialFile(projectRoot, `${SDK_ENV_PATH}${suffix}`);
103
+ const to = prepareCredentialFile(projectRoot, `${MCP_ENV_PATH}${suffix}`);
104
+ if (to.stat || credentialDigest(readCredentialFile(projectRoot, `${SDK_ENV_PATH}${suffix}`)) !== current.manifest.files[kind]) {
105
+ throw new Error('MCP migration destination or source changed; resume only after inspection.');
106
+ }
107
+ fs.renameSync(from.absolute, to.absolute);
108
+ syncDirectory(path.dirname(to.absolute));
109
+ syncDirectory(path.dirname(from.absolute));
110
+ }
111
+ readMcpMigration(projectRoot);
112
+ removeCredentialFile(projectRoot, MCP_MIGRATION_PATH);
113
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.10.1",
3
+ "version": "2.10.2",
4
4
  "description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -24,6 +24,7 @@
24
24
  "files": [
25
25
  "cli.js",
26
26
  "credentials.js",
27
+ "installationIdentity.js",
27
28
  "activationMetrics.js",
28
29
  "tryFlow.js",
29
30
  "tryContract.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;