osuite 2.9.9 → 2.10.1

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/cli.js CHANGED
@@ -1,10 +1,26 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { spawn } from 'node:child_process';
3
4
  import fs from 'node:fs';
4
5
  import path from 'node:path';
5
6
  import crypto from 'node:crypto';
6
7
  import { fileURLToPath } from 'node:url';
7
8
  import { OSuite, buildReviewSurface } from './osuite.js';
9
+ import { runTryFlow } from './tryFlow.js';
10
+ import { runDoctorWithMeasurement } from './activationMetrics.js';
11
+ import {
12
+ CREDENTIAL_PATHS, acquireCredentialLock, inspectCredentialFile,
13
+ readCredentialFile, removeCredentialFile, writeCredentialFile,
14
+ } from './credentials.js';
15
+ import {
16
+ buildNodeRuntimeBootstrap,
17
+ describeInstallResult,
18
+ findHookInstallations,
19
+ installBlockers,
20
+ installProjectFile,
21
+ resolveProjectPath,
22
+ runHookCheck,
23
+ } from './projectHooks.js';
8
24
 
9
25
  const __filename = fileURLToPath(import.meta.url);
10
26
  const __dirname = path.dirname(__filename);
@@ -53,6 +69,14 @@ const PROJECT_BOOTSTRAPS = {
53
69
  runLine: 'Run Claude Code from this project root so .claude/settings.json can govern tool calls.',
54
70
  smokeLine: 'Try: osuite explain "git push origin main", then ask Claude Code to run a low-risk command such as git status.',
55
71
  },
72
+ cursor: {
73
+ label: 'Cursor hook runtime',
74
+ endpoint: '/api/runtimes/cursor/bootstrap',
75
+ envPath: '.cursor/.env.example',
76
+ readmePath: '.cursor/README.osuite.md',
77
+ runLine: 'Open this project in Cursor and review its .cursor/hooks.json; host invocation must be verified separately.',
78
+ smokeLine: 'Try: osuite doctor, then ask Cursor to run a low-risk command such as git status.',
79
+ },
56
80
  };
57
81
 
58
82
  const RUNTIME_COVERAGE_TIERS = [
@@ -107,7 +131,10 @@ function loadDotenvFile(relativePath) {
107
131
  }
108
132
 
109
133
  function loadProjectEnvironment() {
110
- ['.codex/.env', '.claude/.env', '.osuite/.env', '.env'].forEach(loadDotenvFile);
134
+ [...CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
135
+ if (process.argv[2] === 'doctor' && !inspectCredentialFile(process.cwd(), relativePath).safe) return;
136
+ loadDotenvFile(relativePath);
137
+ });
111
138
  }
112
139
 
113
140
  function parseArgs(argv) {
@@ -130,6 +157,8 @@ function parseArgs(argv) {
130
157
  return { command, args };
131
158
  }
132
159
 
160
+ // Hooks run with the agent's environment, not the values this CLI loads from project .env files.
161
+ const SHELL_ENV = { ...process.env };
133
162
  loadProjectEnvironment();
134
163
 
135
164
  function envValue(name, fallback) {
@@ -141,6 +170,7 @@ function readConfig() {
141
170
  baseUrl: envValue('OSUITE_BASE_URL', 'DASHCLAW_BASE_URL'),
142
171
  apiKey: envValue('OSUITE_API_KEY', 'DASHCLAW_API_KEY'),
143
172
  agentId: envValue('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID') || 'osuite-cli',
173
+ agentKeyId: envValue('OSUITE_AGENT_KEY_ID', 'DASHCLAW_AGENT_KEY_ID') || null,
144
174
  runtimeAdapterId: process.env.OSUITE_RUNTIME_ADAPTER_ID || '',
145
175
  signatureMode: process.env.OSUITE_SIGNATURE_MODE || '',
146
176
  };
@@ -179,6 +209,7 @@ function detectRuntimeTarget(preferred = 'auto') {
179
209
  const cwd = process.cwd();
180
210
  if (fs.existsSync(path.join(cwd, '.codex'))) return 'codex';
181
211
  if (fs.existsSync(path.join(cwd, '.claude'))) return 'claude';
212
+ if (fs.existsSync(path.join(cwd, '.cursor'))) return 'cursor';
182
213
  if (fs.existsSync(path.join(cwd, 'mcp.json')) || fs.existsSync(path.join(cwd, '.mcp.json'))) return 'mcp';
183
214
  if (fs.existsSync(path.join(cwd, 'package.json'))) return 'sdk';
184
215
  return 'sdk';
@@ -199,6 +230,7 @@ function buildConnectHandoffUrl({ baseUrl, runtime, code }) {
199
230
  function defaultAgentIdForRuntime(runtime) {
200
231
  if (runtime === 'codex') return 'codex-runtime';
201
232
  if (runtime === 'claude') return 'claude-code-runtime';
233
+ if (runtime === 'cursor') return 'cursor-runtime';
202
234
  if (runtime === 'mcp') return 'mcp-runtime';
203
235
  return 'sdk-runtime';
204
236
  }
@@ -209,6 +241,7 @@ function sanitizeConfiguredAgentId(runtime, agentId) {
209
241
  const knownDefaults = {
210
242
  codex: 'codex-runtime',
211
243
  claude: 'claude-code-runtime',
244
+ cursor: 'cursor-runtime',
212
245
  mcp: 'mcp-runtime',
213
246
  sdk: 'sdk-runtime',
214
247
  };
@@ -223,6 +256,7 @@ function runtimeMatchesConfiguredAdapter(runtime, adapterId) {
223
256
  if (!adapter) return false;
224
257
  if (runtime === 'codex') return adapter === 'codex_hooks';
225
258
  if (runtime === 'claude') return adapter === 'claude_code_hooks' || adapter === 'claude_hooks';
259
+ if (runtime === 'cursor') return adapter === 'cursor_hooks';
226
260
  if (runtime === 'mcp') return adapter.includes('mcp');
227
261
  if (runtime === 'sdk') return ['sdk', 'framework_sdk', 'inline_sdk'].includes(adapter);
228
262
  return false;
@@ -231,6 +265,7 @@ function runtimeMatchesConfiguredAdapter(runtime, adapterId) {
231
265
  function envPathForRuntime(runtime) {
232
266
  if (runtime === 'codex') return '.codex/.env';
233
267
  if (runtime === 'claude') return '.claude/.env';
268
+ if (runtime === 'cursor') return '.cursor/.env';
234
269
  return '.osuite/.env';
235
270
  }
236
271
 
@@ -281,6 +316,8 @@ async function postJson(url, body) {
281
316
  method: 'POST',
282
317
  headers: { 'content-type': 'application/json' },
283
318
  body: JSON.stringify(body || {}),
319
+ signal: AbortSignal.timeout(15000),
320
+ redirect: 'error',
284
321
  });
285
322
  const text = await response.text();
286
323
  let payload = {};
@@ -294,11 +331,14 @@ async function postJson(url, body) {
294
331
  return { response, payload };
295
332
  }
296
333
 
297
- async function startDeviceConnect({ baseUrl, runtime, agentId }) {
334
+ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey }) {
298
335
  const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/start`, {
299
336
  runtime,
300
337
  agent_id: agentId,
301
338
  project_root: process.cwd(),
339
+ protocol_version: 2,
340
+ client_version: pkg.version,
341
+ ...(previousKey ? { previous_key: previousKey } : {}),
302
342
  });
303
343
  if (!response.ok) {
304
344
  throw new Error(payload.error || `Unable to start browser handoff: HTTP ${response.status}`);
@@ -309,24 +349,68 @@ async function startDeviceConnect({ baseUrl, runtime, agentId }) {
309
349
  return payload;
310
350
  }
311
351
 
312
- async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs }) {
352
+ // Opens the handoff in the browser, as `gh auth login` does. Not with
353
+ // --no-browser or OSUITE_NO_BROWSER=1, in CI, over SSH, without a terminal or
354
+ // a Linux display: there the printed link is opened by hand.
355
+ function shouldOpenBrowser(args = {}, env = process.env) {
356
+ if (args['no-browser']) return false;
357
+ if (['1', 'true', 'yes'].includes(String(env.OSUITE_NO_BROWSER || '').trim().toLowerCase())) return false;
358
+ if (env.CI || env.SSH_CONNECTION || env.SSH_TTY) return false;
359
+ if (process.platform === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY) return false;
360
+ return Boolean(process.stdout.isTTY);
361
+ }
362
+
363
+ function openInBrowser(url) {
364
+ const [command, commandArgs] = process.platform === 'darwin'
365
+ ? ['open', [url]]
366
+ : process.platform === 'win32'
367
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
368
+ : ['xdg-open', [url]];
369
+ try {
370
+ const child = spawn(command, commandArgs, { stdio: 'ignore', detached: true });
371
+ child.on('error', () => {});
372
+ child.unref();
373
+ return true;
374
+ } catch {
375
+ return false;
376
+ }
377
+ }
378
+
379
+ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs, protocolVersion = 1 }) {
313
380
  const deadline = Date.now() + timeoutMs;
314
381
  while (Date.now() <= deadline) {
315
- const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/poll`, {
316
- device_code: deviceCode,
317
- poll_token: pollToken,
318
- });
382
+ let result;
383
+ try {
384
+ result = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/poll`, {
385
+ device_code: deviceCode,
386
+ poll_token: pollToken,
387
+ });
388
+ } catch (error) {
389
+ if (protocolVersion !== 2) throw error;
390
+ await sleep(Math.max(10, intervalMs));
391
+ continue;
392
+ }
393
+ const { response, payload } = result;
319
394
 
320
395
  if (response.status === 200 && payload.status === 'approved' && payload.credential?.env) {
396
+ if (protocolVersion === 2 && (payload.credential.protocol_version !== 2 || !payload.credential.key_id || !payload.credential.ack_token || !payload.credential.env.OSUITE_API_KEY || !payload.credential.env.OSUITE_PRIVATE_KEY_BASE64)) {
397
+ throw new Error('Studio did not deliver an acknowledged credential. Existing credentials were not changed.');
398
+ }
321
399
  return payload.credential;
322
400
  }
401
+ if (protocolVersion === 2 && response.status >= 500) {
402
+ await sleep(Math.max(10, intervalMs));
403
+ continue;
404
+ }
323
405
  if (response.status === 202 || payload.status === 'pending') {
324
406
  const serverInterval = Number(payload.interval_seconds || 0) * 1000;
325
407
  await sleep(serverInterval > 0 ? Math.max(intervalMs, serverInterval) : intervalMs);
326
408
  continue;
327
409
  }
328
410
  if (response.status === 410 || payload.status === 'expired') {
329
- throw new Error('Browser handoff expired. Run osuite connect again.');
411
+ const error = new Error('The connect code expired before it was approved. Run osuite connect again for a new code.');
412
+ error.code = 'DEVICE_CONNECT_EXPIRED';
413
+ throw error;
330
414
  }
331
415
  if (response.status === 409 || payload.status === 'consumed') {
332
416
  throw new Error(payload.error || 'Browser handoff was already consumed.');
@@ -339,14 +423,42 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
339
423
  return null;
340
424
  }
341
425
 
342
- function projectFilePath(relativePath) {
343
- const clean = String(relativePath || '').replace(/^\/+/, '');
344
- const root = path.resolve(process.cwd());
345
- const absolute = path.resolve(root, clean);
346
- if (absolute !== root && !absolute.startsWith(`${root}${path.sep}`)) {
347
- throw new Error(`Refusing to write outside the project root: ${relativePath}`);
426
+ async function finalizeDeviceConnect(journal, journalPath) {
427
+ const { credential, session, base_url: baseUrl } = journal;
428
+ for (let attempt = 0; attempt < 3; attempt += 1) {
429
+ let result;
430
+ try {
431
+ result = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/ack`, {
432
+ protocol_version: 2, device_code: session.device_code, poll_token: session.poll_token,
433
+ key_id: credential.key_id, ack_token: credential.ack_token,
434
+ });
435
+ } catch {
436
+ // A lost response may mean the transaction committed. Retry the same receipt.
437
+ }
438
+ if (result?.response.ok) {
439
+ if (result.payload.status !== 'finalized' || result.payload.key_id !== credential.key_id || typeof result.payload.active !== 'boolean') {
440
+ throw new Error('Studio did not confirm this saved connection. The recovery journal was left unchanged; retry the same osuite connect command.');
441
+ }
442
+ if (!result.payload.active) {
443
+ removeCredentialFile(process.cwd(), journalPath);
444
+ 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.');
445
+ }
446
+ return;
447
+ }
448
+ if (result && result.response.status < 500) {
449
+ if (result.response.status === 410) {
450
+ removeCredentialFile(process.cwd(), journalPath);
451
+ throw new Error('Saved connection expired before finalization. Existing credentials were not changed; run osuite connect again.');
452
+ }
453
+ throw new Error(`Connection was not finalized (HTTP ${result.response.status}). The recovery journal is saved; rerun the same osuite connect command to resume.`);
454
+ }
455
+ await sleep(100 * (attempt + 1));
348
456
  }
349
- return absolute;
457
+ throw new Error('Could not confirm finalization. The recovery journal is saved; rerun the same osuite connect command to resume safely.');
458
+ }
459
+
460
+ function projectFilePath(relativePath) {
461
+ return resolveProjectPath(process.cwd(), relativePath);
350
462
  }
351
463
 
352
464
  function writeProjectFile(relativePath, body, { force = false } = {}) {
@@ -438,44 +550,82 @@ async function loadRuntimeBootstrap(spec, args, config) {
438
550
  }
439
551
 
440
552
  const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || DEFAULT_BASE_URL);
441
- const response = await fetch(`${baseUrl}${spec.endpoint}`);
553
+ const response = await fetch(`${baseUrl}${spec.endpoint}`, {
554
+ signal: AbortSignal.timeout(30000),
555
+ redirect: 'error',
556
+ });
442
557
  if (!response.ok) {
443
558
  throw new Error(`Unable to download ${spec.label} bootstrap: HTTP ${response.status}`);
444
559
  }
445
560
  return response.json();
446
561
  }
447
562
 
448
- async function installRuntimeProjectBootstrap(target, args = {}) {
563
+ async function installRuntimeProjectBootstrap(target, args = {}, { nextSteps = true } = {}) {
449
564
  const spec = PROJECT_BOOTSTRAPS[target];
450
565
  const config = readConfig();
451
- const bootstrap = await loadRuntimeBootstrap(spec, args, config);
566
+ const bootstrap = buildNodeRuntimeBootstrap(target, await loadRuntimeBootstrap(spec, args, config));
452
567
  const force = Boolean(args.force);
453
568
  const results = [];
454
569
 
455
570
  Object.entries(bootstrap.files || {}).forEach(([relativePath, body]) => {
456
- results.push(writeProjectFile(remapBootstrapPath(spec, relativePath), body, { force }));
571
+ results.push(installProjectFile(process.cwd(), remapBootstrapPath(spec, relativePath), body, { force }));
457
572
  });
458
573
 
459
574
  if (bootstrap.recommended_env) {
460
- results.push(writeProjectFile(spec.envPath, `${bootstrap.recommended_env.trim()}\n`, { force }));
575
+ results.push(installProjectFile(process.cwd(), spec.envPath, `${bootstrap.recommended_env.trim()}\n`, { force }));
461
576
  }
462
577
 
463
- const written = results.filter((item) => item.status === 'written');
464
- const skipped = results.filter((item) => item.status === 'skipped');
578
+ const blockers = installBlockers(results);
579
+ const colors = { created: ANSI.green, merged: ANSI.green, replaced: ANSI.green, failed: ANSI.red, kept: ANSI.yellow };
465
580
 
466
581
  write(c(spec.label, ANSI.bold));
467
582
  write(`Installing project files into ${process.cwd()}`);
468
583
  write('');
469
- written.forEach((item) => write(` ${c('created', ANSI.green)} ${item.relativePath}`));
470
- skipped.forEach((item) => write(` ${c('kept ', ANSI.yellow)} ${item.relativePath} (use --force to replace)`));
471
- write('');
472
- write(c('Next steps', ANSI.bold));
473
- write(` 1. Copy ${spec.envPath} to ${spec.envPath.replace(/\.example$/, '')} and fill OSUITE_API_KEY.`);
474
- write(' 2. Run osuite doctor.');
475
- write(` 3. ${spec.runLine}`);
476
- write(` 4. ${spec.smokeLine}`);
477
- write('');
478
- write(c('OSuite CLI is the control surface; the project hook files are what intercept agent actions.', ANSI.dim));
584
+ results.forEach((result) => {
585
+ describeInstallResult(result).forEach((line) => {
586
+ const status = line.split(/\s+/)[0];
587
+ write(` ${colors[status] ? `${c(status, colors[status])}${line.slice(status.length)}` : line}`);
588
+ });
589
+ });
590
+ if (blockers.length) {
591
+ write('');
592
+ write(c('OSuite hook setup is not ready, so this agent is not governed:', ANSI.red));
593
+ blockers.forEach((blocker) => write(` ${blocker}`));
594
+ }
595
+ if (nextSteps) {
596
+ write('');
597
+ write(c('Next steps', ANSI.bold));
598
+ write(` 1. Run osuite connect ${target} to save protected credentials through the browser handoff.`);
599
+ write(' 2. Run osuite doctor. It checks project enablement, connection, telemetry, and governance with a direct hook probe.');
600
+ write(` 3. ${spec.runLine}`);
601
+ write(` 4. ${spec.smokeLine}`);
602
+ write('');
603
+ write(c('OSuite CLI is the control surface; the project hook files are what intercept agent actions.', ANSI.dim));
604
+ }
605
+ return { ok: blockers.length === 0, results, blockers };
606
+ }
607
+
608
+ function writeCheckLine(status, label, detail) {
609
+ const tags = {
610
+ ok: c('OK ', ANSI.green),
611
+ miss: c('MISS', ANSI.yellow),
612
+ warn: c('WARN', ANSI.yellow),
613
+ fail: c('FAIL', ANSI.red),
614
+ };
615
+ write(`${tags[status]} ${label.padEnd(18)} ${detail}`);
616
+ }
617
+
618
+ // A telemetry-only result must never count as successful governance.
619
+ async function verifyProjectHooks(runtimes) {
620
+ const installations = findHookInstallations(process.cwd(), runtimes);
621
+ const checks = [];
622
+ for (const installation of installations) {
623
+ const check = await runHookCheck({ projectRoot: process.cwd(), installation, shellEnv: SHELL_ENV });
624
+ check.steps.forEach((step) => writeCheckLine(step.ok ? 'ok' : 'fail', step.label, `${installation.label}: ${step.detail}`));
625
+ (check.warnings || []).forEach((warning) => writeCheckLine('warn', 'Hook warning', `${installation.label}: ${warning}`));
626
+ checks.push({ installation, ...check });
627
+ }
628
+ return checks;
479
629
  }
480
630
 
481
631
  function banner() {
@@ -492,20 +642,23 @@ function printHelp() {
492
642
  write(c(`OSuite CLI v${pkg.version}`, ANSI.dim));
493
643
  write('');
494
644
  write(c('Useful commands', ANSI.bold));
495
- write(' osuite doctor Check connection, runtime, signatures, package health');
645
+ write(' osuite doctor Check connection, then run the project hook with a sample call');
646
+ write(' osuite try Review one fixed, harmless terminal acknowledgement');
496
647
  write(' osuite status Ping Studio and show current workspace connection');
497
648
  write(' osuite explain "git push origin main" Explain how CAVA/Decision V2 will read a command');
498
649
  write(' osuite approvals --limit 20 Show pending approval inbox');
499
650
  write(' osuite review <actionId> Render the decision review card');
500
- write(' osuite approve <actionId> --reason "Looks safe"');
651
+ write(' osuite approve <actionId> Approve from the CLI where the workspace allows it;');
652
+ write(' otherwise prints the Studio link to approve it');
501
653
  write(' osuite deny <actionId> --reason "Outside change window"');
502
654
  write(' osuite adapters [status|coverage] Explain Runtime Coverage tiers and next steps');
503
655
  write(' osuite adapter init <name> Scaffold an enterprise custom adapter mapping');
504
656
  write(' osuite adapter test <file> Validate an enterprise custom adapter mapping');
505
657
  write(' osuite external status Show external verifier network setup and usage');
506
658
  write(' osuite external configure --provider babyblue_invinoveritas --mode shadow --api-key <key> --expected-source-class independent_mediator');
507
- write(' osuite connect [auto|codex|claude|sdk|mcp] Detect runtime and start browser handoff');
508
- write(' osuite init [sdk|codex|claude|mcp] Print setup steps for a runtime lane');
659
+ write(' osuite connect [auto|codex|claude|cursor|sdk|mcp] Detect runtime and start browser handoff');
660
+ write(' --no-browser prints the link instead of opening it');
661
+ write(' osuite init [sdk|codex|claude|cursor|mcp] Prepare a runtime lane');
509
662
  write('');
510
663
  write(c('Environment', ANSI.bold));
511
664
  write(' OSUITE_BASE_URL Studio URL, for example https://studio.osuite.ai');
@@ -951,6 +1104,23 @@ async function doctor() {
951
1104
  write(c('Checking the local developer entry point.', ANSI.dim));
952
1105
  write('');
953
1106
 
1107
+ const credentialChecks = [...CREDENTIAL_PATHS.flatMap((file) => [file, `${file}.connect.json`, `${file}.connect.lock`]), '.env']
1108
+ .map((relativePath) => inspectCredentialFile(process.cwd(), relativePath));
1109
+ const unsafeCredentials = credentialChecks.filter((check) => check.exists && !check.safe);
1110
+ for (const check of credentialChecks.filter((item) => item.exists)) {
1111
+ writeCheckLine(check.safe ? 'ok' : 'fail', 'Credential file', `${check.relativePath}: ${check.safe ? check.mode ? `${check.mode}; owner-only` : 'review platform ACLs; POSIX mode unavailable' : `unsafe; ${check.problems.join('; ')}`}`);
1112
+ }
1113
+ if (unsafeCredentials.length) {
1114
+ write('Repair credential protection before running hooks. Reconnect to rotate any possibly exposed key; chmod alone cannot undo disclosure.');
1115
+ process.exitCode = 1;
1116
+ return false;
1117
+ }
1118
+ if (credentialChecks.some((check) => check.exists && check.relativePath.endsWith('.connect.json'))) {
1119
+ writeCheckLine('warn', 'Connection recovery', 'resume the original osuite connect command before running this runtime.');
1120
+ process.exitCode = 1;
1121
+ return false;
1122
+ }
1123
+
954
1124
  const checks = [
955
1125
  ['OSUITE_BASE_URL', Boolean(config.baseUrl), config.baseUrl || 'missing'],
956
1126
  ['OSUITE_API_KEY', Boolean(config.apiKey), config.apiKey ? 'present' : 'missing'],
@@ -966,9 +1136,11 @@ async function doctor() {
966
1136
 
967
1137
  if (config.baseUrl) {
968
1138
  try {
969
- const response = await fetch(`${config.baseUrl.replace(/\/$/, '')}/api/health`);
970
- const body = await response.text();
971
- const healthy = response.ok && body.includes('healthy');
1139
+ const response = await fetch(`${config.baseUrl.replace(/\/$/, '')}/api/health`, {
1140
+ redirect: 'error', signal: AbortSignal.timeout(10000),
1141
+ });
1142
+ const body = await response.json();
1143
+ const healthy = response.ok && body.status === 'healthy';
972
1144
  ok = ok && healthy;
973
1145
  write(`${healthy ? c('OK ', ANSI.green) : c('WARN', ANSI.yellow)} ${'Studio health'.padEnd(18)} HTTP ${response.status}`);
974
1146
  } catch (error) {
@@ -977,16 +1149,51 @@ async function doctor() {
977
1149
  }
978
1150
  }
979
1151
 
1152
+ const hookChecks = await verifyProjectHooks();
1153
+ if (!hookChecks.length) writeCheckLine('miss', 'Agent hooks', 'none in this project (fine for SDK and MCP runtimes)');
1154
+ const hooksOk = hookChecks.every((check) => check.ok);
1155
+
980
1156
  write('');
981
- if (!ok) {
1157
+ if (!ok || !hooksOk) {
982
1158
  write(c('Next step', ANSI.bold));
983
- write(' osuite init');
984
- write(' export OSUITE_BASE_URL=https://studio.osuite.ai');
985
- write(' export OSUITE_API_KEY=<workspace-api-key>');
986
- process.exit(1);
1159
+ if (!ok) {
1160
+ write(' osuite init');
1161
+ write(' export OSUITE_BASE_URL=https://studio.osuite.ai');
1162
+ write(' export OSUITE_API_KEY=<workspace-api-key>');
1163
+ }
1164
+ hookChecks.filter((check) => !check.ok).forEach((check) => {
1165
+ write(` ${check.installation.label} is not governed yet. Fix the FAIL line above, or run osuite connect ${check.installation.runtime} to reinstall, then run osuite doctor again.`);
1166
+ });
1167
+ process.exitCode = 1;
1168
+ return false;
987
1169
  }
988
1170
 
989
1171
  write(c('Your OSuite CLI is ready.', ANSI.green));
1172
+ hookChecks.forEach((check) => {
1173
+ write(` ${check.installation.label} direct hook probe was governed and reached OSuite; verify host invocation after starting the runtime.`);
1174
+ });
1175
+ return true;
1176
+ }
1177
+
1178
+ async function tryWalkthrough(args) {
1179
+ if (args._.length || Object.keys(args).some((key) => !['_', 'timeout-ms'].includes(key))) {
1180
+ throw new Error('osuite try accepts no command arguments: its output is fixed. Only --timeout-ms may be set.');
1181
+ }
1182
+ for (const file of [...CREDENTIAL_PATHS, '.env']) {
1183
+ const check = inspectCredentialFile(process.cwd(), file);
1184
+ if (check.exists && !check.safe) throw new Error('Credential storage needs attention. Run osuite doctor before starting the walkthrough.');
1185
+ if (inspectCredentialFile(process.cwd(), `${file}.connect.json`).exists) {
1186
+ throw new Error('Resume the saved osuite connect operation before starting the walkthrough.');
1187
+ }
1188
+ }
1189
+ const config = readConfig();
1190
+ const result = await runTryFlow({
1191
+ client: requireClient(), emit: write,
1192
+ timeoutMs: args['timeout-ms'] === undefined ? 300000 : Number(args['timeout-ms']),
1193
+ privateKeyBase64: envValue('OSUITE_PRIVATE_KEY_BASE64', 'DASHCLAW_PRIVATE_KEY_BASE64'),
1194
+ signatureRequired: config.signatureMode === 'required',
1195
+ });
1196
+ write(`Walkthrough completed. Evidence: ${result.replayUrl}`);
990
1197
  }
991
1198
 
992
1199
  async function status() {
@@ -1028,6 +1235,9 @@ async function approvals(args) {
1028
1235
 
1029
1236
  write(`${'Action ID'.padEnd(18)} ${'Risk'.padStart(3)} ${'Type'.padEnd(24)} ${'Agent'.padEnd(18)} Goal`);
1030
1237
  actions.forEach((action) => write(renderActionRow(action)));
1238
+ write('');
1239
+ write(c('Review and decide in Studio:', ANSI.dim));
1240
+ actions.forEach((action) => write(` ${client.baseUrl}/approvals?action=${encodeURIComponent(action.action_id)}`));
1031
1241
  }
1032
1242
 
1033
1243
  async function review(actionId) {
@@ -1047,7 +1257,19 @@ async function decide(actionId, decision, args) {
1047
1257
  process.exit(1);
1048
1258
  }
1049
1259
  const client = requireClient();
1050
- const result = await client.approveAction(actionId, decision, args.reason || args.reasoning);
1260
+ let result;
1261
+ try {
1262
+ result = await client.approveAction(actionId, decision, args.reason || args.reasoning);
1263
+ } catch (error) {
1264
+ // Agents share this machine's API key, so the workspace only accepts
1265
+ // decisions from a person signed in to Studio.
1266
+ if (error?.response?.code === 'HUMAN_APPROVER_REQUIRED') {
1267
+ write(c('Approvals are made by a person signed in to OSuite Studio.', ANSI.yellow));
1268
+ write(`Open this request to ${decision === 'allow' ? 'approve' : 'deny'} it: ${error.response.review_url || `${client.baseUrl}/approvals?action=${encodeURIComponent(actionId)}`}`);
1269
+ process.exit(1);
1270
+ }
1271
+ throw error;
1272
+ }
1051
1273
  const label = decision === 'allow' ? 'Approved' : 'Denied';
1052
1274
  write(c(`${label} ${actionId}`, decision === 'allow' ? ANSI.green : ANSI.red));
1053
1275
  if (result?.action?.status) write(`New status ${result.action.status}`);
@@ -1159,7 +1381,8 @@ async function external(args = {}) {
1159
1381
  async function init(target = 'generic', args = {}) {
1160
1382
  write(c('OSuite init', `${ANSI.bold}${ANSI.cyan}`));
1161
1383
  if (PROJECT_BOOTSTRAPS[target]) {
1162
- await installRuntimeProjectBootstrap(target, args);
1384
+ const install = await installRuntimeProjectBootstrap(target, args);
1385
+ if (!install.ok) process.exitCode = 1;
1163
1386
  return;
1164
1387
  }
1165
1388
 
@@ -1182,7 +1405,7 @@ async function init(target = 'generic', args = {}) {
1182
1405
  }
1183
1406
  }
1184
1407
 
1185
- async function connect(target = 'auto', args = {}) {
1408
+ async function connectProject(target = 'auto', args = {}) {
1186
1409
  const config = readConfig();
1187
1410
  const runtime = detectRuntimeTarget(target);
1188
1411
  const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || DEFAULT_BASE_URL);
@@ -1198,9 +1421,31 @@ async function connect(target = 'auto', args = {}) {
1198
1421
  let code = dryRunCode;
1199
1422
  let handoffUrl = buildConnectHandoffUrl({ baseUrl, runtime, code });
1200
1423
  const hasApiKey = Boolean(config.apiKey);
1424
+ const envPath = envPathForRuntime(runtime);
1425
+ const journalPath = `${envPath}.connect.json`;
1426
+ let journal = null;
1201
1427
 
1202
1428
  if (!args['dry-run']) {
1203
- connectPayload = await startDeviceConnect({ baseUrl, runtime, agentId });
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
+ }
1435
+ connectPayload = journal.session;
1436
+ } else {
1437
+ const previousKey = normalizedBaseUrl(config.baseUrl) === baseUrl && runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) && configuredAgentId === agentId ? config.apiKey : '';
1438
+ connectPayload = await startDeviceConnect({ baseUrl, runtime, agentId, previousKey });
1439
+ 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`);
1442
+ } else {
1443
+ if (hasApiKey && fs.existsSync(projectFilePath(envPath))) {
1444
+ throw new Error('This Studio does not support acknowledged reconnect. Upgrade Studio before replacing existing credentials; they were left unchanged.');
1445
+ }
1446
+ write(c('Legacy Studio protocol: secure file storage is available, but delivery has no acknowledgement or interruption recovery. Upgrade Studio for safe reconnect.', ANSI.yellow));
1447
+ }
1448
+ }
1204
1449
  code = connectPayload.user_code;
1205
1450
  handoffUrl = connectPayload.verification_uri_complete || buildConnectHandoffUrl({ baseUrl, runtime, code });
1206
1451
  }
@@ -1213,17 +1458,21 @@ async function connect(target = 'auto', args = {}) {
1213
1458
  write(`Browser handoff ${handoffUrl}`);
1214
1459
  write(`One-time code ${code}`);
1215
1460
  write('');
1461
+ const opened = !args['dry-run'] && shouldOpenBrowser(args) && openInBrowser(handoffUrl);
1216
1462
  write(c('What happens next', ANSI.bold));
1217
- write(' 1. Open the browser handoff URL and approve this terminal connection in Studio.');
1463
+ write(opened
1464
+ ? ' 1. Studio opened in your browser. Check the code matches, then approve this terminal.'
1465
+ : ' 1. Open the browser handoff URL, check the code matches, then approve this terminal in Studio.');
1218
1466
  write(' 2. OSuite prepares the runtime identity, project hook lane, and signed env for this project.');
1219
1467
  write(' 3. Return here; the CLI will finish automatically and then you can run osuite doctor.');
1220
1468
  write('');
1221
1469
 
1470
+ let install = null;
1222
1471
  if (PROJECT_BOOTSTRAPS[runtime]) {
1223
1472
  if (args['dry-run']) {
1224
1473
  write(`Dry run: would install project hook files for ${runtime}.`);
1225
1474
  } else {
1226
- await installRuntimeProjectBootstrap(runtime, args);
1475
+ install = await installRuntimeProjectBootstrap(runtime, args, { nextSteps: false });
1227
1476
  }
1228
1477
  } else {
1229
1478
  write(c('Runtime setup', ANSI.bold));
@@ -1233,7 +1482,9 @@ async function connect(target = 'auto', args = {}) {
1233
1482
  }
1234
1483
 
1235
1484
  if (!args['dry-run'] && connectPayload) {
1236
- const timeoutMs = parsePositiveInt(args['poll-timeout-ms'], 180000);
1485
+ // Wait as long as the code is valid, so approving late still connects.
1486
+ const expiresInSeconds = Math.max(30, Number(connectPayload.expires_in || 600));
1487
+ const timeoutMs = parsePositiveInt(args['poll-timeout-ms'], expiresInSeconds * 1000);
1237
1488
  const intervalMs = parsePositiveInt(
1238
1489
  args['poll-interval-ms'],
1239
1490
  Math.max(1000, Number(connectPayload.interval_seconds || 2) * 1000),
@@ -1241,27 +1492,66 @@ async function connect(target = 'auto', args = {}) {
1241
1492
 
1242
1493
  write('');
1243
1494
  write(c('Waiting for browser approval', ANSI.bold));
1244
- write(` Code ${code} expires in about ${Math.round(Number(connectPayload.expires_in || 600) / 60)} minutes.`);
1245
-
1246
- const credential = await pollDeviceConnect({
1247
- baseUrl,
1248
- deviceCode: connectPayload.device_code,
1249
- pollToken: connectPayload.poll_token,
1250
- timeoutMs,
1251
- intervalMs,
1252
- });
1495
+ write(` Code ${code} expires in about ${Math.round(expiresInSeconds / 60)} minutes. Press Ctrl+C to stop waiting.`);
1496
+
1497
+ let credential = journal?.credential;
1498
+ if (!credential) {
1499
+ try {
1500
+ credential = await pollDeviceConnect({
1501
+ baseUrl,
1502
+ deviceCode: connectPayload.device_code,
1503
+ pollToken: connectPayload.poll_token,
1504
+ timeoutMs,
1505
+ intervalMs,
1506
+ protocolVersion: connectPayload.protocol_version || 1,
1507
+ });
1508
+ } catch (error) {
1509
+ if (journal && error.code === 'DEVICE_CONNECT_EXPIRED') removeCredentialFile(process.cwd(), journalPath);
1510
+ throw error;
1511
+ }
1512
+ }
1253
1513
 
1254
1514
  if (credential?.env) {
1255
- const envPath = envPathForRuntime(runtime);
1256
- const result = writeProjectFile(envPath, formatEnvBody(credential.env), { force: true });
1515
+ if (journal) {
1516
+ journal = { ...journal, credential };
1517
+ // fsync both the file and its directory before telling the server to retire
1518
+ // 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);
1521
+ }
1522
+ const result = writeCredentialFile(process.cwd(), envPath, formatEnvBody(credential.env));
1523
+ if (journal) removeCredentialFile(process.cwd(), journalPath);
1257
1524
  write('');
1258
- write(c('Connected to OSuite', ANSI.green));
1259
- write(` ${result.status === 'written' ? 'wrote' : 'kept'} ${result.relativePath}`);
1260
- write(' Run osuite doctor, then start the agent from this project root.');
1525
+ write(`Saved credentials to ${result.relativePath}`);
1526
+ if (!PROJECT_BOOTSTRAPS[runtime]) {
1527
+ write(c('Connected to OSuite', ANSI.green));
1528
+ write(' Run osuite doctor, then start the agent from this project root.');
1529
+ } else if (!install?.ok) {
1530
+ write(c('Not connected: OSuite hook setup is not ready, so this agent is not governed.', ANSI.red));
1531
+ (install?.blockers || []).forEach((blocker) => write(` ${blocker}`));
1532
+ write(` Fix the file above, then run osuite connect ${runtime} again.`);
1533
+ process.exitCode = 1;
1534
+ } else {
1535
+ write('');
1536
+ write(c('Checking the installed hook', ANSI.bold));
1537
+ const checks = await verifyProjectHooks([runtime]);
1538
+ write('');
1539
+ if (checks.length && checks.every((check) => check.ok)) {
1540
+ write(c('Connected to OSuite', ANSI.green));
1541
+ write(` The direct ${PROJECT_BOOTSTRAPS[runtime].label.replace(/ hook runtime$/, '')} hook probe was governed and reached Studio; host invocation still needs runtime verification.`);
1542
+ write(` ${PROJECT_BOOTSTRAPS[runtime].runLine}`);
1543
+ } else {
1544
+ write(c('Not connected: credentials are saved, but the hook check failed, so this agent is not governed yet.', ANSI.red));
1545
+ write(' Fix the FAIL line above, then run osuite doctor.');
1546
+ process.exitCode = 1;
1547
+ }
1548
+ }
1261
1549
  } else {
1262
1550
  write('');
1263
- write(c('Browser approval not completed before the timeout.', ANSI.yellow));
1264
- write(' Keep the browser handoff open or run osuite connect again.');
1551
+ 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' : ''}.`);
1553
+ write(' If the browser did not open, copy the handoff link above into it.');
1554
+ process.exitCode = 1;
1265
1555
  }
1266
1556
  }
1267
1557
 
@@ -1270,19 +1560,28 @@ async function connect(target = 'auto', args = {}) {
1270
1560
  if (hasApiKey) {
1271
1561
  write(' OSUITE_API_KEY is already present in this shell or project env. Browser handoff can be skipped for this project.');
1272
1562
  } else if (PROJECT_BOOTSTRAPS[runtime]) {
1273
- const envPath = PROJECT_BOOTSTRAPS[runtime].envPath.replace(/\.example$/, '');
1274
- write(` If browser handoff is unavailable, copy ${PROJECT_BOOTSTRAPS[runtime].envPath} to ${envPath} and paste a workspace API key.`);
1563
+ write(' If browser handoff is unavailable, supply OSUITE_BASE_URL and OSUITE_API_KEY through your secret manager or process environment.');
1564
+ write(' Do not copy secrets into an unprotected project file; run osuite doctor before relying on the connection.');
1275
1565
  } else {
1276
1566
  write(' If browser handoff is unavailable, export OSUITE_BASE_URL and OSUITE_API_KEY before running the agent.');
1277
1567
  }
1278
1568
  }
1279
1569
 
1570
+ async function connect(target = 'auto', args = {}) {
1571
+ if (args['dry-run']) return connectProject(target, args);
1572
+ const runtime = detectRuntimeTarget(target);
1573
+ const release = acquireCredentialLock(process.cwd(), envPathForRuntime(runtime));
1574
+ try { return await connectProject(runtime, args); }
1575
+ finally { release(); }
1576
+ }
1577
+
1280
1578
  async function main() {
1281
1579
  const { command, args } = parseArgs(process.argv.slice(2));
1282
1580
 
1283
1581
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1284
1582
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1285
- if (command === 'doctor') return doctor();
1583
+ if (command === 'doctor') return runDoctorWithMeasurement(doctor, { config: readConfig(), emit: write });
1584
+ if (command === 'try') return tryWalkthrough(args);
1286
1585
  if (command === 'status') return status();
1287
1586
  if (command === 'explain') return printExplanation(args._.join(' '));
1288
1587
  if (command === 'approvals') return approvals(args);