osuite 2.10.0 → 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
@@ -6,7 +6,14 @@ import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { OSuite, buildReviewSurface } from './osuite.js';
9
+ import { runTryFlow } from './tryFlow.js';
10
+ import { runDoctorWithMeasurement } from './activationMetrics.js';
9
11
  import {
12
+ CREDENTIAL_PATHS, acquireCredentialLock, inspectCredentialFile,
13
+ readCredentialFile, removeCredentialFile, writeCredentialFile,
14
+ } from './credentials.js';
15
+ import {
16
+ buildNodeRuntimeBootstrap,
10
17
  describeInstallResult,
11
18
  findHookInstallations,
12
19
  installBlockers,
@@ -62,6 +69,14 @@ const PROJECT_BOOTSTRAPS = {
62
69
  runLine: 'Run Claude Code from this project root so .claude/settings.json can govern tool calls.',
63
70
  smokeLine: 'Try: osuite explain "git push origin main", then ask Claude Code to run a low-risk command such as git status.',
64
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
+ },
65
80
  };
66
81
 
67
82
  const RUNTIME_COVERAGE_TIERS = [
@@ -116,7 +131,10 @@ function loadDotenvFile(relativePath) {
116
131
  }
117
132
 
118
133
  function loadProjectEnvironment() {
119
- ['.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
+ });
120
138
  }
121
139
 
122
140
  function parseArgs(argv) {
@@ -152,6 +170,7 @@ function readConfig() {
152
170
  baseUrl: envValue('OSUITE_BASE_URL', 'DASHCLAW_BASE_URL'),
153
171
  apiKey: envValue('OSUITE_API_KEY', 'DASHCLAW_API_KEY'),
154
172
  agentId: envValue('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID') || 'osuite-cli',
173
+ agentKeyId: envValue('OSUITE_AGENT_KEY_ID', 'DASHCLAW_AGENT_KEY_ID') || null,
155
174
  runtimeAdapterId: process.env.OSUITE_RUNTIME_ADAPTER_ID || '',
156
175
  signatureMode: process.env.OSUITE_SIGNATURE_MODE || '',
157
176
  };
@@ -190,6 +209,7 @@ function detectRuntimeTarget(preferred = 'auto') {
190
209
  const cwd = process.cwd();
191
210
  if (fs.existsSync(path.join(cwd, '.codex'))) return 'codex';
192
211
  if (fs.existsSync(path.join(cwd, '.claude'))) return 'claude';
212
+ if (fs.existsSync(path.join(cwd, '.cursor'))) return 'cursor';
193
213
  if (fs.existsSync(path.join(cwd, 'mcp.json')) || fs.existsSync(path.join(cwd, '.mcp.json'))) return 'mcp';
194
214
  if (fs.existsSync(path.join(cwd, 'package.json'))) return 'sdk';
195
215
  return 'sdk';
@@ -210,6 +230,7 @@ function buildConnectHandoffUrl({ baseUrl, runtime, code }) {
210
230
  function defaultAgentIdForRuntime(runtime) {
211
231
  if (runtime === 'codex') return 'codex-runtime';
212
232
  if (runtime === 'claude') return 'claude-code-runtime';
233
+ if (runtime === 'cursor') return 'cursor-runtime';
213
234
  if (runtime === 'mcp') return 'mcp-runtime';
214
235
  return 'sdk-runtime';
215
236
  }
@@ -220,6 +241,7 @@ function sanitizeConfiguredAgentId(runtime, agentId) {
220
241
  const knownDefaults = {
221
242
  codex: 'codex-runtime',
222
243
  claude: 'claude-code-runtime',
244
+ cursor: 'cursor-runtime',
223
245
  mcp: 'mcp-runtime',
224
246
  sdk: 'sdk-runtime',
225
247
  };
@@ -234,6 +256,7 @@ function runtimeMatchesConfiguredAdapter(runtime, adapterId) {
234
256
  if (!adapter) return false;
235
257
  if (runtime === 'codex') return adapter === 'codex_hooks';
236
258
  if (runtime === 'claude') return adapter === 'claude_code_hooks' || adapter === 'claude_hooks';
259
+ if (runtime === 'cursor') return adapter === 'cursor_hooks';
237
260
  if (runtime === 'mcp') return adapter.includes('mcp');
238
261
  if (runtime === 'sdk') return ['sdk', 'framework_sdk', 'inline_sdk'].includes(adapter);
239
262
  return false;
@@ -242,6 +265,7 @@ function runtimeMatchesConfiguredAdapter(runtime, adapterId) {
242
265
  function envPathForRuntime(runtime) {
243
266
  if (runtime === 'codex') return '.codex/.env';
244
267
  if (runtime === 'claude') return '.claude/.env';
268
+ if (runtime === 'cursor') return '.cursor/.env';
245
269
  return '.osuite/.env';
246
270
  }
247
271
 
@@ -292,6 +316,8 @@ async function postJson(url, body) {
292
316
  method: 'POST',
293
317
  headers: { 'content-type': 'application/json' },
294
318
  body: JSON.stringify(body || {}),
319
+ signal: AbortSignal.timeout(15000),
320
+ redirect: 'error',
295
321
  });
296
322
  const text = await response.text();
297
323
  let payload = {};
@@ -305,11 +331,14 @@ async function postJson(url, body) {
305
331
  return { response, payload };
306
332
  }
307
333
 
308
- async function startDeviceConnect({ baseUrl, runtime, agentId }) {
334
+ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey }) {
309
335
  const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/start`, {
310
336
  runtime,
311
337
  agent_id: agentId,
312
338
  project_root: process.cwd(),
339
+ protocol_version: 2,
340
+ client_version: pkg.version,
341
+ ...(previousKey ? { previous_key: previousKey } : {}),
313
342
  });
314
343
  if (!response.ok) {
315
344
  throw new Error(payload.error || `Unable to start browser handoff: HTTP ${response.status}`);
@@ -347,24 +376,41 @@ function openInBrowser(url) {
347
376
  }
348
377
  }
349
378
 
350
- async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs }) {
379
+ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs, protocolVersion = 1 }) {
351
380
  const deadline = Date.now() + timeoutMs;
352
381
  while (Date.now() <= deadline) {
353
- const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/poll`, {
354
- device_code: deviceCode,
355
- poll_token: pollToken,
356
- });
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;
357
394
 
358
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
+ }
359
399
  return payload.credential;
360
400
  }
401
+ if (protocolVersion === 2 && response.status >= 500) {
402
+ await sleep(Math.max(10, intervalMs));
403
+ continue;
404
+ }
361
405
  if (response.status === 202 || payload.status === 'pending') {
362
406
  const serverInterval = Number(payload.interval_seconds || 0) * 1000;
363
407
  await sleep(serverInterval > 0 ? Math.max(intervalMs, serverInterval) : intervalMs);
364
408
  continue;
365
409
  }
366
410
  if (response.status === 410 || payload.status === 'expired') {
367
- throw new Error('The connect code expired before it was approved. Run osuite connect again for a new code.');
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;
368
414
  }
369
415
  if (response.status === 409 || payload.status === 'consumed') {
370
416
  throw new Error(payload.error || 'Browser handoff was already consumed.');
@@ -377,6 +423,40 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
377
423
  return null;
378
424
  }
379
425
 
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));
456
+ }
457
+ throw new Error('Could not confirm finalization. The recovery journal is saved; rerun the same osuite connect command to resume safely.');
458
+ }
459
+
380
460
  function projectFilePath(relativePath) {
381
461
  return resolveProjectPath(process.cwd(), relativePath);
382
462
  }
@@ -470,7 +550,10 @@ async function loadRuntimeBootstrap(spec, args, config) {
470
550
  }
471
551
 
472
552
  const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || DEFAULT_BASE_URL);
473
- const response = await fetch(`${baseUrl}${spec.endpoint}`);
553
+ const response = await fetch(`${baseUrl}${spec.endpoint}`, {
554
+ signal: AbortSignal.timeout(30000),
555
+ redirect: 'error',
556
+ });
474
557
  if (!response.ok) {
475
558
  throw new Error(`Unable to download ${spec.label} bootstrap: HTTP ${response.status}`);
476
559
  }
@@ -480,7 +563,7 @@ async function loadRuntimeBootstrap(spec, args, config) {
480
563
  async function installRuntimeProjectBootstrap(target, args = {}, { nextSteps = true } = {}) {
481
564
  const spec = PROJECT_BOOTSTRAPS[target];
482
565
  const config = readConfig();
483
- const bootstrap = await loadRuntimeBootstrap(spec, args, config);
566
+ const bootstrap = buildNodeRuntimeBootstrap(target, await loadRuntimeBootstrap(spec, args, config));
484
567
  const force = Boolean(args.force);
485
568
  const results = [];
486
569
 
@@ -512,7 +595,7 @@ async function installRuntimeProjectBootstrap(target, args = {}, { nextSteps = t
512
595
  if (nextSteps) {
513
596
  write('');
514
597
  write(c('Next steps', ANSI.bold));
515
- write(` 1. Copy ${spec.envPath} to ${spec.envPath.replace(/\.example$/, '')} and fill OSUITE_API_KEY.`);
598
+ write(` 1. Run osuite connect ${target} to save protected credentials through the browser handoff.`);
516
599
  write(' 2. Run osuite doctor. It checks project enablement, connection, telemetry, and governance with a direct hook probe.');
517
600
  write(` 3. ${spec.runLine}`);
518
601
  write(` 4. ${spec.smokeLine}`);
@@ -560,6 +643,7 @@ function printHelp() {
560
643
  write('');
561
644
  write(c('Useful commands', ANSI.bold));
562
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');
563
647
  write(' osuite status Ping Studio and show current workspace connection');
564
648
  write(' osuite explain "git push origin main" Explain how CAVA/Decision V2 will read a command');
565
649
  write(' osuite approvals --limit 20 Show pending approval inbox');
@@ -572,9 +656,9 @@ function printHelp() {
572
656
  write(' osuite adapter test <file> Validate an enterprise custom adapter mapping');
573
657
  write(' osuite external status Show external verifier network setup and usage');
574
658
  write(' osuite external configure --provider babyblue_invinoveritas --mode shadow --api-key <key> --expected-source-class independent_mediator');
575
- write(' osuite connect [auto|codex|claude|sdk|mcp] Detect runtime and start browser handoff');
659
+ write(' osuite connect [auto|codex|claude|cursor|sdk|mcp] Detect runtime and start browser handoff');
576
660
  write(' --no-browser prints the link instead of opening it');
577
- write(' osuite init [sdk|codex|claude|mcp] Print setup steps for a runtime lane');
661
+ write(' osuite init [sdk|codex|claude|cursor|mcp] Prepare a runtime lane');
578
662
  write('');
579
663
  write(c('Environment', ANSI.bold));
580
664
  write(' OSUITE_BASE_URL Studio URL, for example https://studio.osuite.ai');
@@ -1020,6 +1104,23 @@ async function doctor() {
1020
1104
  write(c('Checking the local developer entry point.', ANSI.dim));
1021
1105
  write('');
1022
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
+
1023
1124
  const checks = [
1024
1125
  ['OSUITE_BASE_URL', Boolean(config.baseUrl), config.baseUrl || 'missing'],
1025
1126
  ['OSUITE_API_KEY', Boolean(config.apiKey), config.apiKey ? 'present' : 'missing'],
@@ -1035,9 +1136,11 @@ async function doctor() {
1035
1136
 
1036
1137
  if (config.baseUrl) {
1037
1138
  try {
1038
- const response = await fetch(`${config.baseUrl.replace(/\/$/, '')}/api/health`);
1039
- const body = await response.text();
1040
- 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';
1041
1144
  ok = ok && healthy;
1042
1145
  write(`${healthy ? c('OK ', ANSI.green) : c('WARN', ANSI.yellow)} ${'Studio health'.padEnd(18)} HTTP ${response.status}`);
1043
1146
  } catch (error) {
@@ -1061,13 +1164,36 @@ async function doctor() {
1061
1164
  hookChecks.filter((check) => !check.ok).forEach((check) => {
1062
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.`);
1063
1166
  });
1064
- process.exit(1);
1167
+ process.exitCode = 1;
1168
+ return false;
1065
1169
  }
1066
1170
 
1067
1171
  write(c('Your OSuite CLI is ready.', ANSI.green));
1068
1172
  hookChecks.forEach((check) => {
1069
1173
  write(` ${check.installation.label} direct hook probe was governed and reached OSuite; verify host invocation after starting the runtime.`);
1070
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}`);
1071
1197
  }
1072
1198
 
1073
1199
  async function status() {
@@ -1279,7 +1405,7 @@ async function init(target = 'generic', args = {}) {
1279
1405
  }
1280
1406
  }
1281
1407
 
1282
- async function connect(target = 'auto', args = {}) {
1408
+ async function connectProject(target = 'auto', args = {}) {
1283
1409
  const config = readConfig();
1284
1410
  const runtime = detectRuntimeTarget(target);
1285
1411
  const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || DEFAULT_BASE_URL);
@@ -1295,9 +1421,31 @@ async function connect(target = 'auto', args = {}) {
1295
1421
  let code = dryRunCode;
1296
1422
  let handoffUrl = buildConnectHandoffUrl({ baseUrl, runtime, code });
1297
1423
  const hasApiKey = Boolean(config.apiKey);
1424
+ const envPath = envPathForRuntime(runtime);
1425
+ const journalPath = `${envPath}.connect.json`;
1426
+ let journal = null;
1298
1427
 
1299
1428
  if (!args['dry-run']) {
1300
- 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
+ }
1301
1449
  code = connectPayload.user_code;
1302
1450
  handoffUrl = connectPayload.verification_uri_complete || buildConnectHandoffUrl({ baseUrl, runtime, code });
1303
1451
  }
@@ -1346,17 +1494,33 @@ async function connect(target = 'auto', args = {}) {
1346
1494
  write(c('Waiting for browser approval', ANSI.bold));
1347
1495
  write(` Code ${code} expires in about ${Math.round(expiresInSeconds / 60)} minutes. Press Ctrl+C to stop waiting.`);
1348
1496
 
1349
- const credential = await pollDeviceConnect({
1350
- baseUrl,
1351
- deviceCode: connectPayload.device_code,
1352
- pollToken: connectPayload.poll_token,
1353
- timeoutMs,
1354
- intervalMs,
1355
- });
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
+ }
1356
1513
 
1357
1514
  if (credential?.env) {
1358
- const envPath = envPathForRuntime(runtime);
1359
- 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);
1360
1524
  write('');
1361
1525
  write(`Saved credentials to ${result.relativePath}`);
1362
1526
  if (!PROJECT_BOOTSTRAPS[runtime]) {
@@ -1396,19 +1560,28 @@ async function connect(target = 'auto', args = {}) {
1396
1560
  if (hasApiKey) {
1397
1561
  write(' OSUITE_API_KEY is already present in this shell or project env. Browser handoff can be skipped for this project.');
1398
1562
  } else if (PROJECT_BOOTSTRAPS[runtime]) {
1399
- const envPath = PROJECT_BOOTSTRAPS[runtime].envPath.replace(/\.example$/, '');
1400
- 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.');
1401
1565
  } else {
1402
1566
  write(' If browser handoff is unavailable, export OSUITE_BASE_URL and OSUITE_API_KEY before running the agent.');
1403
1567
  }
1404
1568
  }
1405
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
+
1406
1578
  async function main() {
1407
1579
  const { command, args } = parseArgs(process.argv.slice(2));
1408
1580
 
1409
1581
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1410
1582
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1411
- if (command === 'doctor') return doctor();
1583
+ if (command === 'doctor') return runDoctorWithMeasurement(doctor, { config: readConfig(), emit: write });
1584
+ if (command === 'try') return tryWalkthrough(args);
1412
1585
  if (command === 'status') return status();
1413
1586
  if (command === 'explain') return printExplanation(args._.join(' '));
1414
1587
  if (command === 'approvals') return approvals(args);