osuite 2.16.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/GOVERNED_TOOLS.md CHANGED
@@ -96,6 +96,43 @@ with the mapping. Tool variants without a positive amount can run only when
96
96
  their policies permit an action without amount evidence. Whole-CAD refunds
97
97
  continue to use the exact `refund.create` mapping.
98
98
 
99
+ Missing, conflicting, unsupported, and unsigned amount evidence has a dedicated
100
+ `NATIVE_AMOUNT_*` code and a configuration hint. Studio shows these refusals in
101
+ **Policies → Rules → Amount rule errors**. The wrapper refuses a call with an
102
+ invalid binding before it can start the native tool. A JavaScript binding that
103
+ cannot be safely copied as JSON produces its configuration error locally.
104
+
105
+ ### Limit The Cumulative Amount Per Request
106
+
107
+ Add `businessKey: { path: ['request_id'] }` to each related USD tool binding.
108
+ Use the same stable identifier in the native arguments across agents and
109
+ tools for a single business request. Nested paths work when they end in the
110
+ same field name. The signed evidence contains the field path and a digest of
111
+ the value. Supply both bindings before recording the first related action.
112
+
113
+ Create an `amount_threshold` policy through `POST /api/policies` with the
114
+ following JSON encoded as the `rules` string.
115
+
116
+ ```json
117
+ {
118
+ "action_types": ["api"],
119
+ "max_amount_usd": 500,
120
+ "action": "require_approval",
121
+ "on_missing": "block",
122
+ "aggregate": { "key": "request_id", "on_denied": "block" }
123
+ }
124
+ ```
125
+
126
+ Studio reserves an action once and includes completed, in-flight, uncertain
127
+ and pending amounts for the same workspace and business key. A confirmed
128
+ denial or expiry releases the amount. A reservation whose action record has
129
+ been deleted still counts conservatively. Set `on_denied` to `require_approval`
130
+ to route later actions for that key through a new review, or omit it to apply
131
+ only the cumulative cap. Set `action` to `block` for a hard cap. This policy
132
+ requires the direct PostgreSQL connection (`DASHCLAW_DB_DRIVER=postgres`) and
133
+ the current Studio schema. Calls from before the business key was configured
134
+ have no key to associate with a reservation.
135
+
99
136
  ### Reconcile With The Resource Owner
100
137
 
101
138
  Bind `ownerReceipt: { resourceId, publicKey, query }` to the tool. `publicKey`
package/README.md CHANGED
@@ -23,6 +23,29 @@ npm install osuite
23
23
 
24
24
  ### Connect And Verify
25
25
 
26
+ With Studio's acknowledged terminal enrollment enabled, start from your project directory.
27
+
28
+ ```bash
29
+ osuite login
30
+ osuite test
31
+ ```
32
+
33
+ Use `osuite login --no-browser` to enter the displayed code in Studio from another device.
34
+ Run the same command after a timeout or interruption to resume. Project markers
35
+ preselect Claude Code and Codex. Use `--runtimes claude,codex` to specify the
36
+ hosts directly, or `--runtimes sdk` for an SDK-only project. For piped runs,
37
+ `--yes` applies the previewed changes and `--test` records the initial test.
38
+ Codex still requires you to review project Hook trust in `/hooks`.
39
+
40
+ The project SDK can load its signed credentials from `.osuite/terminal/.env`.
41
+ Follow [Native Tool Compatibility](GOVERNED_TOOLS.md) to wrap your tool callback
42
+ and verify the application path. `osuite test` records a policy evaluation for
43
+ a fixed test action without running the callback.
44
+
45
+ For an isolated sample, start `npm run demo -- --serve` in a Studio checkout
46
+ and run `osuite demo` from your terminal. Demo data belongs to that loopback
47
+ Studio process.
48
+
26
49
  For a checked-out SDK source tree, run from the project you want to connect:
27
50
 
28
51
  ```bash
package/cli.js CHANGED
@@ -10,10 +10,11 @@ import { runTryFlow } from './tryFlow.js';
10
10
  import { runDoctorWithMeasurement } from './activationMetrics.js';
11
11
  import { auditCodexTrust, codexExecArguments, inspectCodexTrust } from './codexTrust.mjs';
12
12
  import { runCodexExec } from './codexExec.mjs';
13
+ import { onboardingWelcome, runOnboardingLogin, runOnboardingTest, showOnboardingError } from './onboardingCli.js';
13
14
  import {
14
15
  credentialDigest, getInstallationIdentity, migrateMcpInstallation, parseInstallationIdentity,
15
16
  readInstallationBundle, readInstallationIdentity, readMcpMigration,
16
- MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH,
17
+ MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, TERMINAL_ENV_PATH,
17
18
  } from './installationIdentity.js';
18
19
  import {
19
20
  CREDENTIAL_PATHS, acquireCredentialLock, inspectCredentialFile,
@@ -59,7 +60,7 @@ const GIT_OBSERVATION_RISKS = {
59
60
  const PUBLIC_FILE_HOST_HINTS = ['transfer.sh', 'file.io', 'tmpfiles.org', '0x0.st', 'ufile.io', 'gofile.io', 'wetransfer.com'];
60
61
  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;
61
62
  const DEFAULT_BASE_URL = 'https://studio.osuite.ai';
62
- const CLI_CREDENTIAL_PATHS = [...CREDENTIAL_PATHS, MCP_ENV_PATH];
63
+ const CLI_CREDENTIAL_PATHS = [...CREDENTIAL_PATHS, MCP_ENV_PATH, TERMINAL_ENV_PATH];
63
64
  const PROJECT_BOOTSTRAPS = {
64
65
  codex: {
65
66
  label: 'Codex hook runtime',
@@ -112,7 +113,7 @@ const RUNTIME_COVERAGE_TIERS = [
112
113
  ];
113
114
 
114
115
  function useColor() {
115
- return !process.env.NO_COLOR && process.stdout.isTTY !== false;
116
+ return !Object.hasOwn(process.env, 'NO_COLOR') && process.stdout.isTTY === true;
116
117
  }
117
118
 
118
119
  function c(value, color) {
@@ -139,7 +140,7 @@ function parseEnvBody(body = '') {
139
140
 
140
141
  function loadProjectEnvironment() {
141
142
  // Enrollment selects one whole runtime bundle, never a merged global env.
142
- if (['connect', 'codex'].includes(process.argv[2]) || CONTROLLED_TRANSFER_CLI || NATIVE_RUNTIME_DOCTOR) return;
143
+ if (!process.argv[2] || ['connect', 'codex', 'login', 'test', 'demo'].includes(process.argv[2]) || CONTROLLED_TRANSFER_CLI || NATIVE_RUNTIME_DOCTOR) return;
143
144
  for (const relativePath of [...CLI_CREDENTIAL_PATHS, '.env']) {
144
145
  let body;
145
146
  try { body = readCredentialFile(process.cwd(), relativePath, { maxBytes: 65536 }); }
@@ -151,7 +152,7 @@ function loadProjectEnvironment() {
151
152
  }
152
153
 
153
154
  function parseArgs(argv) {
154
- const [command = 'help', ...rest] = argv;
155
+ const [command = '', ...rest] = argv;
155
156
  const args = { _: [] };
156
157
  for (let index = 0; index < rest.length; index += 1) {
157
158
  const token = rest[index];
@@ -375,12 +376,12 @@ function sleep(ms) {
375
376
  return new Promise((resolve) => setTimeout(resolve, ms));
376
377
  }
377
378
 
378
- async function postJson(url, body) {
379
+ async function postJson(url, body, timeoutMs = 15000) {
379
380
  const response = await fetch(url, {
380
381
  method: 'POST',
381
382
  headers: { 'content-type': 'application/json' },
382
383
  body: JSON.stringify(body || {}),
383
- signal: AbortSignal.timeout(15000),
384
+ signal: AbortSignal.timeout(timeoutMs),
384
385
  redirect: 'error',
385
386
  });
386
387
  const text = await response.text();
@@ -395,7 +396,7 @@ async function postJson(url, body) {
395
396
  return { response, payload };
396
397
  }
397
398
 
398
- async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId }) {
399
+ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId, onboarding, sample, requests, expectedOrgId }) {
399
400
  const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/start`, {
400
401
  runtime,
401
402
  agent_id: agentId,
@@ -404,8 +405,17 @@ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, inst
404
405
  protocol_version: 2,
405
406
  client_version: pkg.version,
406
407
  ...(previousKey ? { previous_key: previousKey } : {}),
408
+ ...(onboarding ? { onboarding: true, sample_only: Boolean(sample), runtime_requests: requests || [] } : {}),
409
+ ...(expectedOrgId ? { expected_org_id: expectedOrgId } : {}),
407
410
  });
408
411
  if (!response.ok) {
412
+ if (onboarding) {
413
+ const reasons = {
414
+ DEVICE_CONNECT_V2_DISABLED: 'Studio has not enabled terminal enrollment. Check Setup Status or ask your workspace administrator.',
415
+ LOCAL_DEMO_REQUIRED: 'Use osuite demo with a loopback Studio running in local Demo mode.',
416
+ };
417
+ throw Object.assign(new Error(reasons[payload.code] || `Could not start terminal enrollment (HTTP ${response.status}).`), { publicOnboardingError: true });
418
+ }
409
419
  throw new Error(payload.error || `Unable to start browser handoff: HTTP ${response.status}`);
410
420
  }
411
421
  if (!payload.device_code || !payload.poll_token || !payload.user_code) {
@@ -441,7 +451,7 @@ function openInBrowser(url) {
441
451
  }
442
452
  }
443
453
 
444
- async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs, protocolVersion = 1 }) {
454
+ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs, protocolVersion = 1, onboarding = false }) {
445
455
  const deadline = Date.now() + timeoutMs;
446
456
  while (Date.now() <= deadline) {
447
457
  let result;
@@ -449,7 +459,7 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
449
459
  result = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/poll`, {
450
460
  device_code: deviceCode,
451
461
  poll_token: pollToken,
452
- });
462
+ }, onboarding ? Math.max(1, Math.min(15000, deadline - Date.now())) : 15000);
453
463
  } catch (error) {
454
464
  if (protocolVersion !== 2) throw error;
455
465
  await sleep(Math.max(10, intervalMs));
@@ -473,14 +483,19 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
473
483
  continue;
474
484
  }
475
485
  if (response.status === 410 || payload.status === 'expired') {
476
- const error = new Error('The connect code expired before it was approved. Run osuite connect again for a new code.');
486
+ const error = new Error(onboarding ? 'The device code expired. Run the same command to get a new code.' : 'The connect code expired before it was approved. Run osuite connect again for a new code.');
477
487
  error.code = 'DEVICE_CONNECT_EXPIRED';
488
+ error.publicOnboardingError = onboarding;
478
489
  throw error;
479
490
  }
491
+ if (onboarding && payload.status === 'declined') {
492
+ throw Object.assign(new Error('Studio could not reserve credentials for this runtime. Check the workspace API key limit.'), { code: 'RUNTIME_APPROVAL_FAILED', publicOnboardingError: true });
493
+ }
480
494
  if (response.status === 409 || payload.status === 'consumed') {
481
495
  throw new Error(payload.error || 'Browser handoff was already consumed.');
482
496
  }
483
497
  if (response.status === 404) {
498
+ if (onboarding) throw Object.assign(new Error('Studio could not find the saved handoff. Rerun to request a new device code.'), { code: 'DEVICE_CONNECT_NOT_FOUND', publicOnboardingError: true });
484
499
  throw new Error('Browser handoff was not found. Run osuite connect again.');
485
500
  }
486
501
  throw new Error(payload.error || `Unable to finish browser handoff: HTTP ${response.status}`);
@@ -507,15 +522,16 @@ async function finalizeDeviceConnect(journal, journalPath, validateLive) {
507
522
  throw new Error('Studio did not confirm this saved connection. The recovery journal was left unchanged; retry the same osuite connect command.');
508
523
  }
509
524
  if (!result.payload.active) {
510
- removeCredentialFile(process.cwd(), journalPath);
525
+ if (journalPath) removeCredentialFile(process.cwd(), journalPath);
511
526
  throw new Error('Saved connection was superseded or revoked. It was not installed over the current credentials. Run osuite connect again for a fresh connection.');
512
527
  }
513
528
  return;
514
529
  }
515
530
  if (result && result.response.status < 500) {
516
531
  if (result.response.status === 410) {
517
- removeCredentialFile(process.cwd(), journalPath);
518
- throw new Error('Saved connection expired before finalization. Existing credentials were not changed; run osuite connect again.');
532
+ if (journalPath) removeCredentialFile(process.cwd(), journalPath);
533
+ throw Object.assign(new Error(journalPath ? 'Saved connection expired before finalization. Existing credentials were not changed; run osuite connect again.'
534
+ : 'The saved approval expired before confirmation. Rerun to obtain a new device code.'), { code: 'DEVICE_CONNECT_EXPIRED', publicOnboardingError: !journalPath });
519
535
  }
520
536
  throw new Error(`Connection was not finalized (HTTP ${result.response.status}). The recovery journal is saved; rerun the same osuite connect command to resume.`);
521
537
  }
@@ -765,6 +781,9 @@ function printHelp() {
765
781
  write(c(`OSuite CLI v${pkg.version}`, ANSI.dim));
766
782
  write('');
767
783
  write(c('Useful commands', ANSI.bold));
784
+ write(' osuite login [--no-browser] Connect this project and configure detected runtimes');
785
+ write(' osuite test Record a test decision in the connected workspace');
786
+ write(' osuite demo [--base-url URL] Record a labeled sample in a loopback Demo Studio');
768
787
  write(' osuite doctor Check connection, then run the project hook with a sample call');
769
788
  write(' osuite doctor --runtime sdk|mcp Check only that native connection; never run project hooks');
770
789
  write(' osuite doctor --controlled-transfers Read strict profile capabilities only (Node 24; --runtime sdk|mcp)');
@@ -1868,6 +1887,7 @@ async function main() {
1868
1887
  const { command, args } = parseArgs(process.argv.slice(2));
1869
1888
 
1870
1889
  if (command === 'codex') return managedCodexExec(process.argv.slice(3));
1890
+ if (!command) return onboardingWelcome();
1871
1891
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1872
1892
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1873
1893
  if (CONTROLLED_TRANSFER_CLI) return controlledTransferCommand(command, args);
@@ -1913,6 +1933,25 @@ async function main() {
1913
1933
  if (command === 'external') return external(args);
1914
1934
  if (command === 'connect') return connect(args._[0] || 'auto', args);
1915
1935
  if (command === 'init') return init(args._[0] || 'generic', args);
1936
+ if (['login', 'test', 'demo'].includes(command)) {
1937
+ if (args.help || args._.includes('-h')) return printHelp();
1938
+ const sample = command === 'demo';
1939
+ const deps = { startDeviceConnect, pollDeviceConnect, finalizeDeviceConnect, assertConnectionCredentialScope,
1940
+ parseEnvBody, formatEnvBody, shouldOpenBrowser, openInBrowser, baseUrl: readConfig(SHELL_ENV).baseUrl || DEFAULT_BASE_URL };
1941
+ const onInterrupt = () => {
1942
+ write(`\nSetup paused. Run osuite ${command} again to resume.`);
1943
+ process.exit(130);
1944
+ };
1945
+ process.once('SIGINT', onInterrupt);
1946
+ try {
1947
+ if (command === 'test') await runOnboardingTest(args, deps);
1948
+ else await runOnboardingLogin(args, deps, { sample });
1949
+ } catch (error) {
1950
+ showOnboardingError(error, command);
1951
+ process.exitCode = 1;
1952
+ } finally { process.removeListener('SIGINT', onInterrupt); }
1953
+ return;
1954
+ }
1916
1955
 
1917
1956
  write(`Unknown command: ${command}`);
1918
1957
  write('');
@@ -1,13 +1,16 @@
1
- import { isObject } from '../runtime/protocol.mjs';
2
-
3
1
  export const NATIVE_AMOUNT_SCHEMA = 'osuite.native_amount.v1';
4
2
  const reserved = new Set(['__proto__', 'constructor', 'prototype']);
3
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+
5
+ export function validNativePath(path) {
6
+ return Array.isArray(path) && path.length > 0 && path.length <= 8
7
+ && path.every(key => typeof key === 'string' && /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(key) && !reserved.has(key));
8
+ }
5
9
 
6
10
  export function validUsdMapping(mapping) {
7
11
  return isObject(mapping) && Object.keys(mapping).length === 3
8
12
  && mapping.currency === 'USD' && mapping.unit === 'minor'
9
- && Array.isArray(mapping.path) && mapping.path.length > 0 && mapping.path.length <= 8
10
- && mapping.path.every(key => typeof key === 'string' && /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(key) && !reserved.has(key));
13
+ && validNativePath(mapping.path);
11
14
  }
12
15
 
13
16
  export function usdMinorToMajor(value) {
@@ -17,6 +20,25 @@ export function usdMinorToMajor(value) {
17
20
 
18
21
  export function agreesWithUsdAmount(value, minor) {
19
22
  if (!isObject(value)) return true;
20
- return [['currency', 'USD'], ['amount_cents', minor], ['amount_usd', usdMinorToMajor(minor)]]
23
+ return [['currency', 'USD'], ['amount_cents', minor], ['amount_usd', minor === 0 ? 0 : usdMinorToMajor(minor)]]
21
24
  .every(([key, expected]) => !Object.hasOwn(value, key) || value[key] === expected);
22
25
  }
26
+
27
+ const mappingHint = "Configure the SDK tool binding with amount: { currency: 'USD', unit: 'minor', path: ['amount_cents'] }, using the path in your native arguments.";
28
+ const keyHint = "Set businessKey: { path: ['request_id'] } in the SDK binding. Use the same stable business identifier for every related payment and match the final path segment to the policy's aggregate.key.";
29
+ const issues = Object.freeze({
30
+ NATIVE_AMOUNT_REQUIRED: ['The applicable amount rule requires a signed USD amount.', mappingHint],
31
+ NATIVE_AMOUNT_UNSUPPORTED: ['The native amount mapping is unsupported.', mappingHint],
32
+ NATIVE_AMOUNT_UNSIGNED: ['The native amount evidence has no verified agent signature.', 'Connect the SDK with signatureMode set to required and register its signing public key for this agent in Studio.'],
33
+ NATIVE_AMOUNT_INVALID: ['The native amount evidence is invalid.', 'Use a positive integer in USD cents at the configured native argument path. Check the tool binding and signing SDK version.'],
34
+ NATIVE_AMOUNT_CONFLICT: ['Native amount representations disagree.', 'Use one source of USD cents. If supplied, currency, amount_cents, and amount_usd must agree with the mapped amount.'],
35
+ NATIVE_AMOUNT_KEY_REQUIRED: ['The cumulative amount rule requires a matching signed business key.', keyHint],
36
+ NATIVE_AMOUNT_KEY_INVALID: ['The native business key mapping or value is invalid.', keyHint],
37
+ NATIVE_AMOUNT_LEDGER_UNAVAILABLE: ['The cumulative amount ledger is unavailable.', 'Use the direct PostgreSQL driver (DASHCLAW_DB_DRIVER=postgres) and run the current Studio schema migration. Retry the same operation after Studio is healthy.'],
38
+ });
39
+
40
+ export function nativeAmountIssue(code) {
41
+ if (typeof code !== 'string' || !Object.hasOwn(issues, code)) return null;
42
+ const [reason, configuration_hint] = issues[code];
43
+ return { code, reason, configuration_hint };
44
+ }
@@ -5,6 +5,7 @@ import { rejectionFenceUnchanged, resolveRemotePosture } from '../runtime/postur
5
5
  import { createStateStore } from '../runtime/state.mjs';
6
6
  import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
7
7
  import { matchesStoredAction, reject } from './contract.mjs';
8
+ import { nativeAmountIssue } from './amount.mjs';
8
9
 
9
10
  const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
10
11
 
@@ -107,12 +108,27 @@ export function createStudioAuthority(config, journalPath) {
107
108
  if (aborted()) reject('ABORTED');
108
109
  const registering = method === 'POST' && endpoint === '/api/actions';
109
110
  if (registering) { claim(); requestStartedAt = performance.now(); }
110
- const response = await api.request(method, endpoint, body, registering ? receiptWindow : options);
111
- if (endpoint === '/api/guard' && !response.ok) {
112
- reject(response.status === 403 && invocation.context.business_authority_assertion ? 'DELEGATION_REJECTED' : 'CURRENT_AUTHORITY_UNAVAILABLE',
113
- null, failureDetails('guard', response));
111
+ const guardRequest = endpoint === '/api/guard';
112
+ const response = await api.request(method, endpoint, body, {
113
+ ...(registering ? receiptWindow : options), readForbiddenBody: registering || guardRequest,
114
+ });
115
+ if (guardRequest) {
116
+ const issue = nativeAmountIssue(response.body?.code) || nativeAmountIssue(invocation.context.native_amount_issue);
117
+ if (issue && (!response.ok || invocation.context.native_amount_issue)) {
118
+ reject(issue.code, null, { ...failureDetails('guard', response), cause: issue.code,
119
+ ...(issue.code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE' ? { retrySameOperation: true } : {}) });
120
+ }
121
+ if (!response.ok) {
122
+ reject(response.status === 403 && invocation.context.business_authority_assertion ? 'DELEGATION_REJECTED' : 'CURRENT_AUTHORITY_UNAVAILABLE',
123
+ null, failureDetails('guard', response));
124
+ }
114
125
  }
115
126
  if (registering) {
127
+ if (response.status === 403 && response.body?.decision?.decision === 'block'
128
+ && response.body.action?.status === 'blocked' && matchesStoredAction(response.body, record, config)) {
129
+ const code = nativeAmountIssue(response.body.decision.code)?.code || 'POLICY_DENIED';
130
+ if (settle('denied')) reject(code, null, { ...failureDetails('action_registration', response), cause: code });
131
+ }
116
132
  if (!response.ok || !matchesStoredAction(response.body, record, config)
117
133
  || !cavaFingerprint(response.body)) {
118
134
  settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
@@ -132,8 +148,10 @@ export function createStudioAuthority(config, journalPath) {
132
148
  if (result.authorized) return { phase, dispatchDeadline: requestStartedAt + receiptWindow.timeoutMs, response: result.response,
133
149
  ruleExpiresAt: result.ruleRolloutBinding?.expires_at ?? null };
134
150
  if (result.reason === 'policy_block') {
151
+ const issue = nativeAmountIssue(result.response?.code);
152
+ if (issue?.code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE') reject(issue.code, null, { phase: 'guard', retrySameOperation: true });
135
153
  if (!claimed) claim();
136
- settle('denied'); reject('POLICY_DENIED');
154
+ settle('denied'); reject(issue?.code || 'POLICY_DENIED');
137
155
  }
138
156
  if (result.decision === 'require_approval' && result.response?.action?.status === 'pending_approval') {
139
157
  if (!settle('held', { fingerprint: cavaFingerprint(result.response) })) reject('OUTCOME_UNKNOWN');
@@ -1,6 +1,6 @@
1
1
  import { types } from 'node:util';
2
2
  import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
3
- import { NATIVE_AMOUNT_SCHEMA, agreesWithUsdAmount, usdMinorToMajor, validUsdMapping } from './amount.mjs';
3
+ import { NATIVE_AMOUNT_SCHEMA, agreesWithUsdAmount, nativeAmountIssue, usdMinorToMajor, validNativePath, validUsdMapping } from './amount.mjs';
4
4
 
5
5
  export const CALL_SCHEMA = 'osuite.native_tool_call.v1';
6
6
  export const COVERAGE = 'wrapped-call-only';
@@ -21,6 +21,11 @@ const recoveryMessages = Object.freeze({
21
21
  });
22
22
 
23
23
  function recoveryGuidance(code, state, details) {
24
+ const amountIssue = nativeAmountIssue(code);
25
+ if (amountIssue) {
26
+ return Object.freeze({ nextStep: code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE' ? 'retry_same_operation' : 'inspect_configuration',
27
+ preserveOperationId: true, message: `${amountIssue.reason} ${amountIssue.configuration_hint}` });
28
+ }
24
29
  let nextStep;
25
30
  if (code === 'ALREADY_COMPLETED' || (state === 'completed' && code !== 'BINDING_MISMATCH')) nextStep = 'read_business_result';
26
31
  else if (['OUTCOME_UNKNOWN', 'UNCERTAIN', 'BINDING_MISMATCH', 'CONFLICT'].includes(code)) nextStep = 'reconcile_without_resend';
@@ -47,7 +52,8 @@ export class GovernedToolError extends Error {
47
52
  this.status = status === null ? null : Object.freeze({ ...status, recovery });
48
53
  this.retryAutomatically = false;
49
54
  this.recovery = recovery;
50
- if (details) this.details = Object.freeze({ ...details });
55
+ const hint = nativeAmountIssue(code)?.configuration_hint;
56
+ if (details || hint) this.details = Object.freeze({ ...details, ...(hint ? { configurationHint: hint } : {}) });
51
57
  }
52
58
  }
53
59
  export function reject(code, status, details) { throw new GovernedToolError(code, status, details); }
@@ -125,22 +131,34 @@ function describe(binding, args) {
125
131
  return value;
126
132
  }
127
133
 
134
+ function readOwnPath(input, path) {
135
+ return path.reduce((object, key) => object && Object.hasOwn(object, key) ? object[key] : undefined, input);
136
+ }
137
+
128
138
  function nativeAmount(binding, native, description, inputDigest) {
129
- if (!binding.amount) return null;
130
- if (!validUsdMapping(binding.amount)) reject('INVALID_MAPPING');
131
- let owner = native.arguments;
132
- for (const key of binding.amount.path.slice(0, -1)) {
133
- owner = owner && Object.hasOwn(owner, key) ? owner[key] : null;
134
- }
135
- const field = binding.amount.path.at(-1);
136
- const value = owner && Object.hasOwn(owner, field) ? owner[field] : null;
139
+ if (binding.amount === undefined) return {};
140
+ if (!validUsdMapping(binding.amount)) return { issue: 'NATIVE_AMOUNT_UNSUPPORTED' };
141
+ const { path } = binding.amount;
142
+ const owner = readOwnPath(native.arguments, path.slice(0, -1));
143
+ const value = readOwnPath(owner, path.slice(-1));
137
144
  // A binding may also describe non-financial variants. A monetary policy
138
145
  // independently requires evidence before any of those variants can execute.
139
- if (value == null || value === 0) return null;
140
- if (usdMinorToMajor(value) === null || !agreesWithUsdAmount(owner, value)
141
- || !agreesWithUsdAmount(native.arguments, value) || !agreesWithUsdAmount(description.input_summary, value)) reject('INVALID_AMOUNT');
142
- return { schema_version: NATIVE_AMOUNT_SCHEMA, mapping: binding.amount, value,
146
+ if (value == null) return {};
147
+ if (value !== 0 && usdMinorToMajor(value) === null) return { issue: 'NATIVE_AMOUNT_INVALID' };
148
+ if (!agreesWithUsdAmount(owner, value) || !agreesWithUsdAmount(native.arguments, value)
149
+ || !agreesWithUsdAmount(description.input_summary, value)) return { issue: 'NATIVE_AMOUNT_CONFLICT' };
150
+ if (value === 0) return {};
151
+ const amount = { schema_version: NATIVE_AMOUNT_SCHEMA, mapping: binding.amount, value,
143
152
  tool_name: native.name, binding_revision: binding.revision, input_digest: inputDigest };
153
+ if (binding.businessKey === undefined) return { amount };
154
+ const keyPath = binding.businessKey?.path;
155
+ if (!validNativePath(keyPath) || Object.keys(binding.businessKey).length !== 1) return { issue: 'NATIVE_AMOUNT_KEY_INVALID' };
156
+ const key = readOwnPath(native.arguments, keyPath);
157
+ const name = keyPath.at(-1);
158
+ if (!id(key) || [native.arguments, description.input_summary].some(source => source && Object.hasOwn(source, name) && source[name] !== key)) {
159
+ return { issue: 'NATIVE_AMOUNT_KEY_INVALID' };
160
+ }
161
+ return { amount: { ...amount, business_key: { path: keyPath, value_digest: sha256(canonicalJson(key)) } } };
144
162
  }
145
163
 
146
164
  export function makeInvocation({ config, namespace, bindings, operationId, params }) {
@@ -156,9 +174,10 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
156
174
  // The historical Hook helper normalizes null to {}. Native calls must retain
157
175
  // every JSON value exactly, including that distinction.
158
176
  const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
159
- const amount = nativeAmount(binding, native, description, inputDigest);
177
+ const { amount, issue } = nativeAmount(binding, native, description, inputDigest);
160
178
  const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description,
161
- ...(binding.amount ? { amountMapping: binding.amount } : {}),
179
+ ...(binding.amount === undefined ? {} : { amountMapping: binding.amount }),
180
+ ...(binding.businessKey === undefined ? {} : { businessKey: binding.businessKey }),
162
181
  ...(binding.ownerReceipt ? { nativeResource: binding.ownerReceipt.resource } : {}),
163
182
  ...(binding.delegation ? { delegationRequired: true } : {}),
164
183
  ...(binding.recovery ? { recovery: { revision: binding.recovery.revision,
@@ -171,6 +190,7 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
171
190
  const context = jsonSnapshot({ ...description, input_summary: inputSummary, action_id: actionId,
172
191
  agent_id: config.agentId, runtime_session_id: sessionId, tool_use_id: toolUseId,
173
192
  ...(amount ? { native_amount: { ...amount, binding_digest: bindingDigest } } : {}),
193
+ ...(issue ? { native_amount_issue: issue } : {}),
174
194
  ...(binding.ownerReceipt ? { native_resource: { ...binding.ownerReceipt.resource, input_digest: inputDigest } } : {}),
175
195
  tool_input_digest: inputDigest, runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper' });
176
196
  return Object.freeze({ params: native, context, marker, record: Object.freeze({ scope, operationId,
@@ -7,7 +7,6 @@ import { OperationJournal } from './journal.mjs';
7
7
  import { createStudioAuthority } from './authority.mjs';
8
8
  import { GovernedToolError, jsonSnapshot, makeInvocation, publicStatus, reject, scopeFor } from './contract.mjs';
9
9
  import { recoveryAdapter, recoveryScope, makeRecoveryInvocation, observeEvidence, validateEvidence, checkRecoveryAuthority } from './recovery.mjs';
10
- import { validUsdMapping } from './amount.mjs';
11
10
  import { ownerReceiptKey, verifyOwnerReceipt } from './owner-receipt.mjs';
12
11
 
13
12
  const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
@@ -60,9 +59,13 @@ function registrySnapshot(bindings) {
60
59
  || typeof fields.describe.value !== 'function' || types.isProxy(fields.describe.value)) reject('INVALID_MAPPING');
61
60
  let amount;
62
61
  if (fields.amount) {
63
- if (!Object.hasOwn(fields.amount, 'value')) reject('INVALID_MAPPING');
64
- try { amount = jsonSnapshot(fields.amount.value, 1024); } catch { reject('INVALID_MAPPING'); }
65
- if (!validUsdMapping(amount)) reject('INVALID_MAPPING');
62
+ if (!Object.hasOwn(fields.amount, 'value')) reject('NATIVE_AMOUNT_UNSUPPORTED');
63
+ try { amount = jsonSnapshot(fields.amount.value, 1024); } catch { reject('NATIVE_AMOUNT_UNSUPPORTED'); }
64
+ }
65
+ let businessKey;
66
+ if (fields.businessKey) {
67
+ if (!Object.hasOwn(fields.businessKey, 'value')) reject('NATIVE_AMOUNT_KEY_INVALID');
68
+ try { businessKey = jsonSnapshot(fields.businessKey.value, 1024); } catch { reject('NATIVE_AMOUNT_KEY_INVALID'); }
66
69
  }
67
70
  const receipt = fields.ownerReceipt;
68
71
  const delegation = fields.delegation?.value;
@@ -81,7 +84,7 @@ function registrySnapshot(bindings) {
81
84
  ownerReceipt = Object.freeze({ resource: Object.freeze({ resource_id: resourceId, key_id: signer.id }), publicKey, query });
82
85
  }
83
86
  Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value,
84
- describe: fields.describe.value, amount, ownerReceipt, delegation, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
87
+ describe: fields.describe.value, amount, businessKey, ownerReceipt, delegation, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
85
88
  }
86
89
  return Object.freeze(result);
87
90
  }
@@ -6,6 +6,7 @@ import { prepareCredentialFile, readCredentialFile, removeCredentialFile, writeC
6
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
7
  const PREFIX = { codex: 'codex-runtime', claude: 'claude-code-runtime', cursor: 'cursor-runtime', mcp: 'mcp-runtime', sdk: 'sdk-runtime' };
8
8
  export const SDK_ENV_PATH = '.osuite/.env';
9
+ export const TERMINAL_ENV_PATH = '.osuite/terminal/.env';
9
10
  export const MCP_ENV_PATH = '.osuite/mcp/.env';
10
11
  export const MCP_MIGRATION_PATH = '.osuite/.env.migrate-mcp.json';
11
12
  const BUNDLE_FILES = { env: '', identity: '.identity.json', journal: '.connect.json' };
package/nativeDoctor.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
2
  import { inspectCredentialFile, readCredentialFile } from './credentials.js';
3
- import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity, readMcpMigration } from './installationIdentity.js';
3
+ import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, TERMINAL_ENV_PATH, parseInstallationIdentity, readMcpMigration } from './installationIdentity.js';
4
4
  import { loadRuntimeConfig } from './runtime/config.mjs';
5
5
  import { createApiClient, safeId, validatedBaseUrl } from './runtime/protocol.mjs';
6
6
  import { resolveRemotePosture } from './runtime/posture.mjs';
@@ -26,8 +26,10 @@ function parse(raw) {
26
26
 
27
27
  export function loadNativeDoctorConfig({ projectRoot = process.cwd(), runtime, shellEnv = process.env }) {
28
28
  if (!['sdk', 'mcp'].includes(runtime)) fail('INVALID_RUNTIME_OPTIONS');
29
- const envPath = runtime === 'mcp' ? MCP_ENV_PATH : SDK_ENV_PATH;
30
29
  try {
30
+ const legacy = runtime === 'sdk' ? inspectCredentialFile(projectRoot, SDK_ENV_PATH) : null;
31
+ const envPath = runtime === 'mcp' ? MCP_ENV_PATH : !legacy.safe || legacy.exists
32
+ || !inspectCredentialFile(projectRoot, TERMINAL_ENV_PATH).exists ? SDK_ENV_PATH : TERMINAL_ENV_PATH;
31
33
  const files = [envPath, `${envPath}.identity.json`, `${envPath}.connect.json`, `${envPath}.connect.lock`, MCP_MIGRATION_PATH];
32
34
  const checks = files.map(file => inspectCredentialFile(projectRoot, file));
33
35
  if (checks.some(check => !check.safe)) fail('UNSAFE_CREDENTIALS');
@@ -0,0 +1,469 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { acquireCredentialLock, readCredentialFile, removeCredentialFile, writeCredentialFile } from './credentials.js';
6
+ import { credentialDigest, getInstallationIdentity, SDK_ENV_PATH, TERMINAL_ENV_PATH } from './installationIdentity.js';
7
+ import { buildNodeRuntimeBootstrap, findHookInstallations, installProjectFile, planProjectFile, resolveProjectPath } from './projectHooks.js';
8
+ import { createApiClient, validatedBaseUrl } from './runtime/protocol.mjs';
9
+
10
+ const hosts = ['claude', 'codex'];
11
+ const labels = { claude: 'Claude Code', codex: 'Codex', sdk: 'SDK' };
12
+ const demoEnv = '.osuite/demo/.env';
13
+ const endpoint = '/api/onboarding/first-decision';
14
+ const colors = { active: '\x1b[36m', done: '\x1b[32m', attention: '\x1b[33m', failed: '\x1b[31m' };
15
+ const marks = { done: '✓ Done', attention: '! Needs attention', failed: '× Failed' };
16
+ const safeText = value => String(value ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').slice(0, 600);
17
+ const plain = () => !process.stdout.isTTY || Object.hasOwn(process.env, 'NO_COLOR');
18
+
19
+ function status(kind, message) {
20
+ const label = marks[kind];
21
+ console.log(`${plain() ? label : `${colors[kind]}${label}\x1b[0m`} ${safeText(message)}`);
22
+ }
23
+
24
+ function current(message) {
25
+ const line = safeText(message);
26
+ const width = line.length + 4;
27
+ if (plain() || (process.stdout.columns || 80) < width) { console.log(line); return; }
28
+ console.log(`${colors.active}┌${'─'.repeat(width - 2)}┐\n│ ${line} │\n└${'─'.repeat(width - 2)}┘\x1b[0m`);
29
+ }
30
+
31
+ function failure(code, message) {
32
+ return Object.assign(new Error(message), { code, publicOnboardingError: true });
33
+ }
34
+
35
+ export function showOnboardingError(error, command) {
36
+ const reason = error.publicOnboardingError ? error.message : 'Could not finish this step. Check the Studio address and local project files.';
37
+ status('failed', reason);
38
+ console.log(`Next osuite ${error.code === 'NOT_CONNECTED' ? 'login' : command}${command === 'demo' ? ' (resume the local sample)' : ''}`);
39
+ }
40
+
41
+ function statePath(envPath) { return `${envPath}.onboarding.json`; }
42
+
43
+ function readState(root, envPath) {
44
+ const raw = readCredentialFile(root, statePath(envPath), { maxBytes: 65536 });
45
+ if (!raw) return null;
46
+ try {
47
+ const state = JSON.parse(raw);
48
+ if (state?.version === 1 && state.lanes?.sdk && validatedBaseUrl(state.baseUrl) === state.baseUrl) return state;
49
+ } catch { /* Protected state is never printed. */ }
50
+ throw failure('STATE', 'The saved setup could not be read. Inspect the protected onboarding state in this project.');
51
+ }
52
+
53
+ function projectFile(root, relativePath) {
54
+ const filename = resolveProjectPath(root, relativePath);
55
+ const stat = fs.statSync(filename, { throwIfNoEntry: false });
56
+ return stat?.isFile() && stat.size <= 1048576 ? filename : null;
57
+ }
58
+
59
+ export function detectProjectRuntimes(root) {
60
+ const has = relative => Boolean(projectFile(root, relative));
61
+ let pkg;
62
+ const manifest = projectFile(root, 'package.json');
63
+ try { if (manifest) pkg = JSON.parse(fs.readFileSync(manifest, 'utf8')); } catch { /* Invalid manifest is not SDK evidence. */ }
64
+ return {
65
+ claude: ['CLAUDE.md', '.claude/CLAUDE.md', '.claude/settings.json', '.claude/settings.local.json'].some(has),
66
+ codex: ['.codex/config.toml', '.codex/hooks.json', '.codex/AGENTS.md'].some(has),
67
+ sdk: ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].some(key => Object.hasOwn(pkg?.[key] || {}, 'osuite')),
68
+ };
69
+ }
70
+
71
+ function requestedHosts(args, detected, sample) {
72
+ if (sample || args['skip-config']) return [];
73
+ if (!args.runtimes) return hosts.filter(runtime => detected[runtime]);
74
+ if (typeof args.runtimes !== 'string') throw failure('OPTIONS', 'Use --runtimes claude,codex or --runtimes sdk.');
75
+ const wanted = args.runtimes.split(',');
76
+ if (wanted.some(runtime => !Object.hasOwn(labels, runtime))) throw failure('OPTIONS', 'Use --runtimes claude,codex or --runtimes sdk.');
77
+ return hosts.filter(runtime => wanted.includes(runtime));
78
+ }
79
+
80
+ const scopeEnv = { claude: '.claude/.env', codex: '.codex/.env' };
81
+
82
+ function previewRuntime(root, runtime, lane, sharedDigest) {
83
+ try {
84
+ const { files } = buildNodeRuntimeBootstrap(runtime, {}, { projectRoot: root });
85
+ const entries = Object.entries(files).map(([file, contents]) => ({ contents, ...planProjectFile(root, file, contents) }));
86
+ const installation = findHookInstallations(root, [runtime], { diagnose: true })[0];
87
+ const blocked = entries.some(entry => ['error', 'kept'].includes(entry.status) || entry.conflicts?.length)
88
+ || (installation?.hostEnabled === false && installation?.disabledReasons?.length > 0);
89
+ const existingEnv = readCredentialFile(root, scopeEnv[runtime], { maxBytes: 65536 });
90
+ const digest = credentialDigest(existingEnv);
91
+ const credentialsConflict = digest !== null && digest !== lane?.envDigest && digest !== sharedDigest && !lane?.credential;
92
+ return { entries, blocked: blocked || credentialsConflict, credentialsConflict };
93
+ } catch { return { entries: [], blocked: true, unreadable: true }; }
94
+ }
95
+
96
+ function syncSharedCredential(root, runtime, lane, envPath) {
97
+ const body = readCredentialFile(root, envPath);
98
+ const live = readCredentialFile(root, scopeEnv[runtime]);
99
+ if (live !== null && live !== body && credentialDigest(live) !== lane.envDigest) {
100
+ throw failure('CREDENTIAL_CONFLICT', 'The project credential changed after review.');
101
+ }
102
+ if (body !== live) writeCredentialFile(root, scopeEnv[runtime], body);
103
+ lane.envDigest = credentialDigest(body);
104
+ }
105
+
106
+ function writePreview(runtime, preview) {
107
+ if (!preview) return;
108
+ if (preview.credentialsConflict) console.log(` ! ${scopeEnv[runtime]} has existing credentials. Review this runtime's connection before retrying.`);
109
+ if (preview.unreadable) console.log(` ! Could not safely read the ${labels[runtime]} project files.`);
110
+ const entries = preview.entries.filter(entry => ['created', 'merged', 'kept', 'error'].includes(entry.status));
111
+ const configs = entries.filter(entry => entry.kind || ['kept', 'error'].includes(entry.status));
112
+ for (const entry of configs) {
113
+ console.log(` ${entry.status === 'created' ? '+' : entry.status === 'merged' ? '~' : '!'} ${entry.relativePath}`);
114
+ for (const hook of entry.added || []) console.log(` + ${typeof hook === 'string' ? safeText(hook) : hook.event + ' OSuite Hook'}`);
115
+ for (const hook of entry.migrated || []) console.log(` ~ ${hook.event} OSuite Hook`);
116
+ if (entry.conflicts?.length || ['kept', 'error'].includes(entry.status)) console.log(' ! Resolve the existing configuration before applying this runtime.');
117
+ }
118
+ const scripts = entries.length - configs.length;
119
+ if (scripts) console.log(` + ${scripts} packaged files in .${runtime}/`);
120
+ }
121
+
122
+ function sdkSteps() {
123
+ console.log(' SDK wrapper for Node.js');
124
+ console.log(' 1. Install the project dependency with npm install osuite.');
125
+ console.log(` 2. On Node 24 start with node --env-file=${TERMINAL_ENV_PATH} your-agent.mjs.`);
126
+ console.log(' 3. Import createGovernedTools from osuite/governed-tools. Bind your tool name and arguments to a private journal,');
127
+ console.log(' then call tools.run(operationId, { name, arguments: args }, ({ arguments: input }) => originalTool(input)).');
128
+ console.log(' Keep the operation ID across retries. See node_modules/osuite/GOVERNED_TOOLS.md for the config and journal setup.');
129
+ }
130
+
131
+ async function confirm(prompt, args) {
132
+ if (args.yes) return true;
133
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
134
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
135
+ try { return ['', 'y', 'yes'].includes((await terminal.question(`${prompt} [Y/n] `)).trim().toLowerCase()); }
136
+ finally { terminal.close(); }
137
+ }
138
+
139
+ async function selectRuntimeChanges(ready, args) {
140
+ if (args.yes) return ready;
141
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
142
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
143
+ try {
144
+ const answer = (await terminal.question(`Apply Hook changes? Enter for all, choose ${ready.join(',')} or n to pause: `)).trim().toLowerCase();
145
+ if (!answer || answer === 'y' || answer === 'yes') return ready;
146
+ const selected = answer.split(',').map(value => value.trim());
147
+ return selected.every(runtime => ready.includes(runtime)) ? [...new Set(selected)] : null;
148
+ } finally { terminal.close(); }
149
+ }
150
+
151
+ async function waitForApproval(run) {
152
+ if (plain()) return run();
153
+ let tick = 0;
154
+ const frames = ['⠋', '⠙', '⠹', '⠸'];
155
+ const timer = setInterval(() => process.stdout.write(`\r${colors.active}${frames[tick++ % frames.length]}\x1b[0m Waiting for Studio…`), 140);
156
+ try { return await run(); }
157
+ finally { clearInterval(timer); if (tick) process.stdout.write('\r\x1b[2K'); }
158
+ }
159
+
160
+ function apiFromEnv(root, envPath, deps) {
161
+ const env = deps.parseEnvBody(readCredentialFile(root, envPath, { maxBytes: 65536 }) || '');
162
+ if (!validatedBaseUrl(env.OSUITE_BASE_URL) || !env.OSUITE_API_KEY || !env.OSUITE_PRIVATE_KEY_BASE64 || !env.OSUITE_ORG_ID) {
163
+ throw failure('NOT_CONNECTED', 'Connect this project before recording a test.');
164
+ }
165
+ return { baseUrl: env.OSUITE_BASE_URL, orgId: env.OSUITE_ORG_ID, api: createApiClient({
166
+ baseUrl: env.OSUITE_BASE_URL, apiKey: env.OSUITE_API_KEY,
167
+ privateKeyBase64: env.OSUITE_PRIVATE_KEY_BASE64, signatureMode: 'required',
168
+ }, { timeoutMs: 15000 }) };
169
+ }
170
+
171
+ function testResponse(result, { orgId, actionId, sample }) {
172
+ const receipt = result.body?.receipt;
173
+ if (!result.ok || receipt?.action_id !== actionId || receipt.workspace?.id !== orgId || receipt.sample !== sample
174
+ || typeof receipt.reason !== 'string' || typeof receipt.decision !== 'string') {
175
+ throw failure('TEST', `Test receipt could not be confirmed${result.status ? ` (HTTP ${result.status})` : ''}. Retry to recover the same action.`);
176
+ }
177
+ return receipt;
178
+ }
179
+
180
+ export async function runOnboardingTest(args, deps, { sample = false } = {}) {
181
+ const root = process.cwd();
182
+ const envPath = sample ? demoEnv : TERMINAL_ENV_PATH;
183
+ const { api, orgId, baseUrl } = apiFromEnv(root, envPath, deps);
184
+ const pendingPath = `${envPath}.test.json`;
185
+ const release = acquireCredentialLock(root, pendingPath);
186
+ try {
187
+ const saved = readCredentialFile(root, pendingPath, { maxBytes: 4096 });
188
+ const run = saved ? JSON.parse(saved) : { orgId, baseUrl, actionId: `act_test_${randomUUID()}` };
189
+ if (run.orgId !== orgId || run.baseUrl !== baseUrl || !/^act_test_[a-f0-9-]{36}$/.test(run.actionId)) {
190
+ throw failure('TEST_STATE', 'The pending test belongs to a different connection. Inspect the original workspace before retrying.');
191
+ }
192
+ if (!saved) writeCredentialFile(root, pendingPath, `${JSON.stringify(run)}\n`);
193
+ current('3/3 Record test decision');
194
+ const response = await api.request('POST', endpoint, { operation: 'test', action_id: run.actionId });
195
+ const receipt = testResponse(response, { orgId, actionId: run.actionId, sample });
196
+ removeCredentialFile(root, pendingPath);
197
+ const decision = { allow: 'Allowed', warn: 'Allowed with warnings', block: 'Blocked', require_approval: 'Review required',
198
+ require_dual_approval: 'Dual review required', simulate_first: 'Simulation required' }[receipt.decision] || 'Recorded';
199
+ status('done', `Test decision recorded · ${decision}`);
200
+ console.log(` Action ID ${receipt.action_id}`);
201
+ console.log(` Workspace ${safeText(receipt.workspace.name)} (${safeText(orgId)})`);
202
+ console.log(` Source ${sample ? 'Local demo sample' : 'CLI test'}`);
203
+ console.log(` Reason ${safeText(receipt.reason)}`);
204
+ const query = sample ? '' : `?${new URLSearchParams({ orgId })}`;
205
+ console.log(` Studio ${baseUrl}/decisions/${receipt.action_id}${query}`);
206
+ console.log(` Replay ${baseUrl}/replay/${receipt.action_id}${query}`);
207
+ return receipt;
208
+ } finally { release(); }
209
+ }
210
+
211
+ export function onboardingWelcome() {
212
+ const root = process.cwd();
213
+ console.log('OSuite');
214
+ try {
215
+ const state = readState(root, TERMINAL_ENV_PATH);
216
+ if (state?.lanes.sdk.envDigest && state.lanes.sdk.envDigest === credentialDigest(readCredentialFile(root, TERMINAL_ENV_PATH))) {
217
+ status('done', `Connected to ${state.workspace.name}`);
218
+ console.log(state.configured ? 'Next osuite test' : 'Next osuite login Resume runtime setup');
219
+ } else if (state) {
220
+ status('attention', 'Setup in progress');
221
+ console.log('Next osuite login Resume this project');
222
+ } else if ([SDK_ENV_PATH, ...Object.values(scopeEnv)].some(file => readCredentialFile(root, file) !== null)) {
223
+ status('attention', 'Existing runtime credentials found');
224
+ console.log('Next osuite login Set up terminal access for this project');
225
+ } else {
226
+ console.log('Connect this project and record your first decision.');
227
+ console.log('Next osuite login');
228
+ }
229
+ } catch {
230
+ status('attention', 'Check the saved project connection');
231
+ console.log('Next osuite login');
232
+ }
233
+ console.log('Help osuite --help');
234
+ }
235
+
236
+ async function deliver({ lane, state, envPath, root, args, deps, save, terminal }) {
237
+ if (lane.envDigest) return;
238
+ const scope = { baseUrl: state.baseUrl, runtime: lane.runtime, agentId: lane.agentId };
239
+ const currentBody = () => readCredentialFile(root, envPath, { maxBytes: 65536 });
240
+ const validateLive = () => {
241
+ const body = currentBody();
242
+ if (credentialDigest(body) !== lane.before && !(lane.credential && body === deps.formatEnvBody(lane.credential.env))) {
243
+ throw failure('CREDENTIAL_CONFLICT', `Existing credentials changed in ${envPath}. Review the file before resuming.`);
244
+ }
245
+ };
246
+ if (!lane.credential) {
247
+ validateLive();
248
+ const request = lane.request;
249
+ const poll = () => deps.pollDeviceConnect({
250
+ ...scope, deviceCode: request.device_code, pollToken: request.poll_token,
251
+ intervalMs: 750, timeoutMs: Math.min(600000, Number(args['poll-timeout-ms']) || (terminal ? 600000 : 12000)),
252
+ protocolVersion: 2, onboarding: true,
253
+ });
254
+ const credential = terminal ? await waitForApproval(poll) : await poll();
255
+ if (!credential) throw failure('WAIT_TIMEOUT', terminal ? 'Timed out at browser approval. The handoff is saved.' : 'Runtime approval is still pending. Resume in the original approval tab.');
256
+ deps.assertConnectionCredentialScope(credential, scope);
257
+ if (typeof credential.org_id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(credential.org_id)
258
+ || (state.workspace?.id && credential.org_id !== state.workspace.id)) throw failure('WORKSPACE', 'Studio approved a different workspace. Check the original authorization.');
259
+ credential.env.OSUITE_ORG_ID = credential.org_id;
260
+ lane.credential = credential;
261
+ save();
262
+ }
263
+ deps.assertConnectionCredentialScope(lane.credential, scope);
264
+ validateLive();
265
+ if (terminal) console.log(' Browser approved. Confirming the saved connection with Studio…');
266
+ await deps.finalizeDeviceConnect({ credential: lane.credential, session: lane.request, base_url: state.baseUrl }, null, validateLive);
267
+ validateLive();
268
+ const body = deps.formatEnvBody(lane.credential.env);
269
+ writeCredentialFile(root, envPath, body);
270
+ lane.envDigest = credentialDigest(body);
271
+ delete lane.request;
272
+ delete lane.credential;
273
+ save();
274
+ }
275
+
276
+ function handoffLink(session, baseUrl) {
277
+ const link = new URL(session.verification_uri_complete);
278
+ if (link.origin !== baseUrl || link.pathname !== '/connect' || link.search !== '?source=login'
279
+ || link.hash !== `#code=${session.user_code}` || !/^OS-[A-Z0-9]{6}$/.test(session.user_code)) {
280
+ throw failure('HANDOFF', 'Studio returned an invalid authorization link.');
281
+ }
282
+ return link.href;
283
+ }
284
+
285
+ export async function runOnboardingLogin(args, deps, { sample = false } = {}) {
286
+ const root = process.cwd();
287
+ const envPath = sample ? demoEnv : TERMINAL_ENV_PATH;
288
+ const command = sample ? 'demo' : 'login';
289
+ const releases = [];
290
+ try {
291
+ releases.push(acquireCredentialLock(root, envPath));
292
+ let state = readState(root, envPath);
293
+ const baseUrl = validatedBaseUrl(args['base-url'] || state?.baseUrl || (sample ? 'http://127.0.0.1:3000' : deps.baseUrl));
294
+ if (!baseUrl || new URL(baseUrl).origin !== baseUrl || (sample && !['127.0.0.1', 'localhost', '[::1]'].includes(new URL(baseUrl).hostname))) {
295
+ throw failure('STUDIO_URL', sample ? 'Demo needs a loopback Studio URL.' : 'Use a Studio HTTPS origin or a loopback HTTP origin.');
296
+ }
297
+ if (state && state.baseUrl !== baseUrl) throw failure('STUDIO_CHANGED', 'This project has a saved setup for a different Studio. Resume with its original URL.');
298
+ const save = () => writeCredentialFile(root, statePath(envPath), `${JSON.stringify(state)}\n`);
299
+ const detected = sample ? {} : detectProjectRuntimes(root);
300
+ const wanted = state?.wanted || requestedHosts(args, detected, sample);
301
+ for (const runtime of wanted) releases.push(acquireCredentialLock(root, scopeEnv[runtime]));
302
+ if (!state || state.renew) {
303
+ const primaryEnv = readCredentialFile(root, envPath);
304
+ const old = state?.lanes.sdk;
305
+ const before = credentialDigest(primaryEnv);
306
+ if (primaryEnv !== null && before !== (old?.envDigest || old?.before)) {
307
+ throw failure('CREDENTIAL_CONFLICT', `A credential already exists in ${envPath}. Restore the setup state or use a clean project.`);
308
+ }
309
+ // A coding-only project can use one of its Hook identities for CLI receipts.
310
+ // This leaves two key slots sufficient for a dual-host starter workspace.
311
+ const primary = old?.runtime || (!sample && !detected.sdk && !String(args.runtimes || '').split(',').includes('sdk')
312
+ ? wanted.find(runtime => readCredentialFile(root, scopeEnv[runtime]) === null) : null) || 'sdk';
313
+ const identity = getInstallationIdentity(root, envPath, primary);
314
+ const lanes = { sdk: { runtime: primary, agentId: identity.agent_id, before } };
315
+ const requests = [];
316
+ for (const runtime of wanted) {
317
+ if (state?.lanes[runtime]?.envDigest) {
318
+ lanes[runtime] = state.lanes[runtime];
319
+ continue;
320
+ }
321
+ if (state?.skipped?.includes(runtime)) continue;
322
+ if (runtime === primary) {
323
+ lanes[runtime] = { runtime, agentId: identity.agent_id, shared: true };
324
+ continue;
325
+ }
326
+ if (readCredentialFile(root, scopeEnv[runtime]) !== null) continue;
327
+ const host = getInstallationIdentity(root, scopeEnv[runtime], runtime);
328
+ requests.push({ runtime, agent_id: host.agent_id, installation_id: host.installation_id });
329
+ lanes[runtime] = { runtime, agentId: host.agent_id, before: null };
330
+ }
331
+ current('1/3 Connect terminal');
332
+ console.log(` Project ${safeText(path.basename(root))}`);
333
+ console.log(` Studio ${baseUrl}`);
334
+ const session = await deps.startDeviceConnect({ baseUrl, runtime: primary, agentId: identity.agent_id, installationId: identity.installation_id,
335
+ onboarding: true, sample, requests, expectedOrgId: state?.workspace?.id,
336
+ previousKey: primaryEnv ? deps.parseEnvBody(primaryEnv).OSUITE_API_KEY : undefined });
337
+ handoffLink(session, baseUrl);
338
+ if (session.protocol_version !== 2 || session.sample !== sample || !Array.isArray(session.runtime_requests)) {
339
+ throw failure('PROTOCOL', 'This Studio does not support the terminal setup protocol.');
340
+ }
341
+ for (const request of session.runtime_requests) {
342
+ if (!hosts.includes(request.runtime) || lanes[request.runtime]?.agentId !== request.agent_id || lanes[request.runtime].request
343
+ || !request.device_code || !request.poll_token) throw failure('PROTOCOL', 'Studio returned an unexpected runtime binding.');
344
+ lanes[request.runtime].request = request;
345
+ }
346
+ if (requests.some(({ runtime }) => !lanes[runtime].request)) throw failure('PROTOCOL', 'Studio omitted a requested runtime binding.');
347
+ const { device_code, poll_token } = session;
348
+ lanes.sdk.request = { device_code, poll_token };
349
+ state = { version: 1, baseUrl, wanted, sample, lanes, link: handoffLink(session, baseUrl), code: session.user_code,
350
+ connectionId: session.connection_id, workspace: state?.workspace, skipped: state?.skipped || [] };
351
+ save();
352
+ } else if (!state.lanes.sdk.envDigest) current('1/3 Resume terminal connection');
353
+
354
+ if (!state.lanes.sdk.envDigest) {
355
+ console.log(` Open ${baseUrl}/connect?source=login`);
356
+ console.log(` Device code ${state.code}`);
357
+ if (deps.shouldOpenBrowser(args)) deps.openInBrowser(state.link);
358
+ console.log(' Approve this terminal in Studio. Press Ctrl+C to pause.');
359
+ try { await deliver({ lane: state.lanes.sdk, state, envPath, root, args, deps, save, terminal: true }); }
360
+ catch (error) {
361
+ if (['DEVICE_CONNECT_EXPIRED', 'DEVICE_CONNECT_NOT_FOUND'].includes(error.code)
362
+ && (!state.lanes.sdk.credential || error.code === 'DEVICE_CONNECT_EXPIRED')) {
363
+ state.renew = true;
364
+ save();
365
+ }
366
+ throw error;
367
+ }
368
+ }
369
+
370
+ if (state.lanes.sdk.envDigest !== credentialDigest(readCredentialFile(root, envPath))) {
371
+ throw failure('CREDENTIAL_CONFLICT', `Saved credentials changed in ${envPath}. Review them before resuming.`);
372
+ }
373
+ const { api, orgId } = apiFromEnv(root, envPath, deps);
374
+ const connection = await api.request('GET', `${endpoint}?runtimes=1`);
375
+ if (!connection.ok || connection.body.workspace?.id !== orgId || connection.body.connection_id !== state.connectionId) {
376
+ if (sample && [401, 403].includes(connection.status)) {
377
+ removeCredentialFile(root, envPath);
378
+ removeCredentialFile(root, statePath(envPath));
379
+ throw failure('DEMO_RESET', 'The local Demo session was reset. Run osuite demo again for a new sample.');
380
+ }
381
+ throw failure('CONNECTION_NOT_CONFIRMED', 'Studio could not confirm this saved connection.');
382
+ }
383
+ state.workspace = connection.body.workspace;
384
+ delete state.code;
385
+ delete state.link;
386
+ save();
387
+ status('done', `1/3 Connected to ${state.workspace.name}${sample ? ' · Sample' : ''}`);
388
+
389
+ if (!sample) {
390
+ current('2/3 Configure this project');
391
+ const primaryHost = state.lanes[state.lanes.sdk.runtime];
392
+ if (primaryHost?.shared && primaryHost.installed) {
393
+ syncSharedCredential(root, primaryHost.runtime, primaryHost, envPath);
394
+ save();
395
+ }
396
+ const previews = Object.fromEntries(wanted.filter(runtime => !state.lanes[runtime]?.installed && !state.skipped?.includes(runtime))
397
+ .map(runtime => [runtime, previewRuntime(root, runtime, state.lanes[runtime], state.lanes[runtime]?.shared ? state.lanes.sdk.envDigest : undefined)]));
398
+ for (const runtime of [...hosts, 'sdk']) {
399
+ const selected = runtime === 'sdk' ? detected.sdk || args.runtimes?.includes('sdk') : wanted.includes(runtime);
400
+ console.log(` [${selected ? 'x' : ' '}] ${labels[runtime]}${selected && runtime !== 'sdk' ? ' · Add project Hook' : ''}`);
401
+ writePreview(runtime, previews[runtime]);
402
+ }
403
+ const ready = wanted.filter(runtime => previews[runtime] && !previews[runtime].blocked
404
+ && (state.lanes[runtime]?.request || state.lanes[runtime]?.envDigest || state.lanes[runtime]?.shared));
405
+ const approvedFor = (runtime, entry) => state.lanes[runtime].approvedPlan?.[entry.relativePath];
406
+ const alreadyReviewed = ready.filter(runtime => previews[runtime].entries.every(entry => {
407
+ const previous = approvedFor(runtime, entry);
408
+ return previous && (previous.before === entry.before || previous.after === entry.before)
409
+ && (entry.status === 'unchanged' || previous.after === credentialDigest(String(entry.body)));
410
+ }));
411
+ const toReview = ready.filter(runtime => !alreadyReviewed.includes(runtime));
412
+ const selected = toReview.length ? await selectRuntimeChanges(toReview, args) : [];
413
+ if (selected === null) status('attention', 'Runtime changes are pending. Resume with osuite login or pass --yes after review.');
414
+ if (selected) {
415
+ state.skipped = [...new Set([...(state.skipped || []), ...toReview.filter(runtime => !selected.includes(runtime))])];
416
+ for (const runtime of selected) {
417
+ state.lanes[runtime].approvedPlan = Object.fromEntries(previews[runtime].entries.map(entry => [entry.relativePath,
418
+ { before: entry.before, after: entry.status === 'unchanged' ? entry.before : credentialDigest(String(entry.body)) }]));
419
+ }
420
+ save();
421
+ }
422
+ if (wanted.some(runtime => previews[runtime] && !previews[runtime].blocked && !state.lanes[runtime])) {
423
+ state.renew = true;
424
+ save();
425
+ status('attention', 'Runtime conflict resolved. Run osuite login again to authorize the remaining runtime.');
426
+ }
427
+ for (const runtime of [...alreadyReviewed, ...(selected || [])]) {
428
+ const lane = state.lanes[runtime];
429
+ try {
430
+ if (lane.shared) {
431
+ syncSharedCredential(root, runtime, lane, envPath);
432
+ save();
433
+ } else await deliver({ lane, state, envPath: scopeEnv[runtime], root, args, deps, save, terminal: false });
434
+ for (const entry of previews[runtime].entries) installProjectFile(root, entry.relativePath, entry.contents, { expectedDigest: entry.before });
435
+ lane.installed = true;
436
+ save();
437
+ } catch (error) {
438
+ if (['DEVICE_CONNECT_EXPIRED', 'DEVICE_CONNECT_NOT_FOUND', 'RUNTIME_APPROVAL_FAILED'].includes(error.code)) {
439
+ state.renew = true;
440
+ save();
441
+ }
442
+ status('attention', `${labels[runtime]} setup paused. ${error.publicOnboardingError ? error.message : 'Review the project files and resume with osuite login.'}`);
443
+ }
444
+ }
445
+ for (const runtime of hosts.filter(runtime => wanted.includes(runtime))) {
446
+ const lane = state.lanes[runtime];
447
+ const evidence = connection.body.runtimes?.[runtime];
448
+ console.log(` ${labels[runtime]} Files written: ${lane?.installed ? 'yes' : state.skipped?.includes(runtime) ? 'skipped' : 'pending'} · Host loaded: ${evidence?.host_loaded ? 'yes' : 'unconfirmed'} · Test action: ${evidence?.action_recorded ? 'recorded' : 'pending'}`);
449
+ if (lane?.installed && runtime === 'codex') console.log(' Open Codex in this project and review the OSuite entries in /hooks to confirm host trust.');
450
+ if (lane?.installed && !evidence?.action_recorded) console.log(` After opening ${labels[runtime]} here, ask it to run a read-only project command such as git status.`);
451
+ }
452
+ if (detected.sdk || wanted.length === 0 || args.runtimes?.includes('sdk')) sdkSteps();
453
+ if (state.lanes.sdk.runtime === 'sdk') console.log(` SDK Files written: credential saved · Wrapper: ${connection.body.runtimes?.sdk?.action_recorded ? 'verified by a recorded action' : 'awaiting an application action'}`);
454
+ }
455
+
456
+ if (sample || wanted.every(runtime => state.lanes[runtime]?.installed || state.skipped?.includes(runtime))) {
457
+ if (!connection.body.configured) {
458
+ const progress = await api.request('POST', endpoint, { operation: 'configured' });
459
+ if (!progress.ok || !progress.body.configured) throw failure('CONFIGURED', 'Studio could not confirm runtime setup. Resume this project to retry.');
460
+ }
461
+ state.configured = true;
462
+ save();
463
+ status('done', '2/3 Runtime setup recorded');
464
+ } else status('attention', '2/3 Some project runtime changes still need attention. Resume with osuite login.');
465
+
466
+ if (sample || args.test || (!args['no-test'] && await confirm('Run test now?', { yes: false }))) await runOnboardingTest(args, deps, { sample });
467
+ else console.log(`Next osuite ${command === 'demo' ? 'demo' : 'test'}`);
468
+ } finally { releases.reverse().forEach(release => release()); }
469
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.16.0",
3
+ "version": "2.17.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": {
@@ -35,6 +35,7 @@
35
35
  },
36
36
  "files": [
37
37
  "cli.js",
38
+ "onboardingCli.js",
38
39
  "credentials.js",
39
40
  "installationIdentity.js",
40
41
  "activationMetrics.js",
package/projectHooks.js CHANGED
@@ -535,9 +535,10 @@ function writeFile(absolute, body) {
535
535
  * Install one bootstrap file. Settings files are merged; OSuite's own files
536
536
  * are created, left alone when identical, and replaced only with --force.
537
537
  */
538
- export function installProjectFile(projectRoot, relativePath, body, { force = false } = {}) {
538
+ export function planProjectFile(projectRoot, relativePath, body, { force = false } = {}) {
539
539
  const absolute = resolveProjectPath(projectRoot, relativePath);
540
540
  const existing = readIfExists(absolute);
541
+ const before = existing === null ? null : crypto.createHash('sha256').update(existing).digest('hex');
541
542
  const kind = MERGED_FILES[relativePath];
542
543
 
543
544
  if (kind) {
@@ -548,21 +549,40 @@ export function installProjectFile(projectRoot, relativePath, body, { force = fa
548
549
  } catch (error) {
549
550
  merge = { status: 'error', error: `OSuite template could not be read (${error.message})` };
550
551
  }
551
- if (merge.status === 'created' || merge.status === 'merged') writeFile(absolute, merge.body);
552
- const { body: _body, ...report } = merge;
553
- return { relativePath, kind, ...report };
552
+ return { relativePath, kind, before, ...merge };
554
553
  }
555
554
 
556
555
  if (existing === null) {
557
- writeFile(absolute, body);
558
- return { relativePath, status: 'created' };
556
+ return { relativePath, before, body, status: 'created' };
559
557
  }
560
- if (existing === String(body ?? '')) return { relativePath, status: 'unchanged' };
558
+ if (existing === String(body ?? '')) return { relativePath, before, status: 'unchanged' };
561
559
  if (force) {
562
- writeFile(absolute, body);
563
- return { relativePath, status: 'replaced' };
560
+ return { relativePath, before, body, status: 'replaced' };
564
561
  }
565
- return { relativePath, status: 'kept' };
562
+ return { relativePath, before, status: 'kept' };
563
+ }
564
+
565
+ export function installProjectFile(projectRoot, relativePath, body, options = {}) {
566
+ const { before, body: proposed, ...report } = planProjectFile(projectRoot, relativePath, body, options);
567
+ const reviewed = Object.hasOwn(options, 'expectedDigest');
568
+ if (reviewed && before !== options.expectedDigest) {
569
+ throw new Error(`Project file changed after the preview: ${relativePath}`);
570
+ }
571
+ if (!['created', 'merged', 'replaced'].includes(report.status)) return report;
572
+ const absolute = resolveProjectPath(projectRoot, relativePath);
573
+ if (!reviewed) { writeFile(absolute, proposed); return report; }
574
+
575
+ // Interruptions during a reviewed install must leave complete files.
576
+ const temporary = path.join(path.dirname(absolute), `.osuite-hook-${crypto.randomUUID()}.tmp`);
577
+ fs.mkdirSync(path.dirname(absolute), { recursive: true });
578
+ try {
579
+ const mode = fs.statSync(absolute, { throwIfNoEntry: false })?.mode ?? 0o644;
580
+ fs.writeFileSync(temporary, proposed, { flag: 'wx', mode });
581
+ if (resolveProjectPath(projectRoot, relativePath) !== absolute
582
+ || planProjectFile(projectRoot, relativePath, body, options).before !== before) throw new Error(`Project file changed during installation: ${relativePath}`);
583
+ fs.renameSync(temporary, absolute);
584
+ } finally { fs.rmSync(temporary, { force: true }); }
585
+ return report;
566
586
  }
567
587
 
568
588
  export function installBlockers(results = []) {
@@ -101,7 +101,8 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
101
101
  clearTimeout(timer);
102
102
  timer = setTimeout(() => controller.abort(), Math.max(1, totalMs - elapsed));
103
103
  }
104
- if (status < 200 || status >= 300) {
104
+ const ok = status >= 200 && status < 300;
105
+ if (!ok && !(status === 403 && options.readForbiddenBody === true)) {
105
106
  const retryAfter = response.headers?.get('retry-after');
106
107
  const retryAfterSeconds = /^\d{1,4}$/.test(retryAfter || '') && Number(retryAfter) <= 3600 ? Number(retryAfter) : null;
107
108
  await response.body?.cancel();
@@ -129,7 +130,7 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
129
130
  return { ok: false, status, error: 'timeout' };
130
131
  }
131
132
  if (!isObject(parsed)) return { ok: false, status, error: 'invalid_response' };
132
- return { ok: true, status, body: parsed };
133
+ return ok ? { ok, status, body: parsed } : { ok, status, body: parsed, error: 'http_error' };
133
134
  } catch (error) {
134
135
  return { ok: false, status, error: status ? 'invalid_response' : controller.signal.aborted ? 'timeout'
135
136
  : transientTransport(error) ? 'transport_failure' : 'request_failed' };