osuite 2.10.0 → 2.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -6,7 +6,19 @@ 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
+ credentialDigest, getInstallationIdentity, migrateMcpInstallation, parseInstallationIdentity,
13
+ readInstallationBundle, readInstallationIdentity, readMcpMigration,
14
+ MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH,
15
+ } from './installationIdentity.js';
16
+ import {
17
+ CREDENTIAL_PATHS, acquireCredentialLock, inspectCredentialFile,
18
+ readCredentialFile, removeCredentialFile, writeCredentialFile,
19
+ } from './credentials.js';
20
+ import {
21
+ buildNodeRuntimeBootstrap,
10
22
  describeInstallResult,
11
23
  findHookInstallations,
12
24
  installBlockers,
@@ -45,6 +57,7 @@ const GIT_OBSERVATION_RISKS = {
45
57
  const PUBLIC_FILE_HOST_HINTS = ['transfer.sh', 'file.io', 'tmpfiles.org', '0x0.st', 'ufile.io', 'gofile.io', 'wetransfer.com'];
46
58
  const SECURITY_CONTROL_WEAKENING_RE = /(\bspctl\b[\s\S]*(--master-disable|--global-disable|--disable)|\bcsrutil\b[\s\S]*\bdisable\b|Set-MpPreference[\s\S]*Disable(?:RealtimeMonitoring|BehaviorMonitoring|IOAVProtection)[\s\S]*(true|\$true|1)|netsh\s+advfirewall\s+set\s+allprofiles\s+state\s+off|\bsystemctl\b[\s\S]*\b(stop|disable|mask)\b[\s\S]*(auditd|falcon|crowdstrike|osquery|defender|mdatp|sentinel|carbonblack|firewalld|ufw)|\bufw\b[\s\S]*\bdisable\b)/i;
47
59
  const DEFAULT_BASE_URL = 'https://studio.osuite.ai';
60
+ const CLI_CREDENTIAL_PATHS = [...CREDENTIAL_PATHS, MCP_ENV_PATH];
48
61
  const PROJECT_BOOTSTRAPS = {
49
62
  codex: {
50
63
  label: 'Codex hook runtime',
@@ -62,6 +75,14 @@ const PROJECT_BOOTSTRAPS = {
62
75
  runLine: 'Run Claude Code from this project root so .claude/settings.json can govern tool calls.',
63
76
  smokeLine: 'Try: osuite explain "git push origin main", then ask Claude Code to run a low-risk command such as git status.',
64
77
  },
78
+ cursor: {
79
+ label: 'Cursor hook runtime',
80
+ endpoint: '/api/runtimes/cursor/bootstrap',
81
+ envPath: '.cursor/.env.example',
82
+ readmePath: '.cursor/README.osuite.md',
83
+ runLine: 'Open this project in Cursor and review its .cursor/hooks.json; host invocation must be verified separately.',
84
+ smokeLine: 'Try: osuite doctor, then ask Cursor to run a low-risk command such as git status.',
85
+ },
65
86
  };
66
87
 
67
88
  const RUNTIME_COVERAGE_TIERS = [
@@ -100,10 +121,8 @@ function write(value = '') {
100
121
  process.stdout.write(`${value}\n`);
101
122
  }
102
123
 
103
- function loadDotenvFile(relativePath) {
104
- const absolute = path.join(process.cwd(), relativePath);
105
- if (!fs.existsSync(absolute)) return;
106
- const body = fs.readFileSync(absolute, 'utf8');
124
+ function parseEnvBody(body = '') {
125
+ const env = Object.create(null);
107
126
  body.split(/\r?\n/).forEach((line) => {
108
127
  const trimmed = line.trim();
109
128
  if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) return;
@@ -111,12 +130,26 @@ function loadDotenvFile(relativePath) {
111
130
  const key = rawKey.trim();
112
131
  let value = rawValue.join('=').trim().replace(/^['"]|['"]$/g, '');
113
132
  if (value.includes(' #')) value = value.slice(0, value.indexOf(' #')).trim();
114
- if (key && !process.env[key]) process.env[key] = value;
133
+ if (key && !env[key]) env[key] = value;
115
134
  });
135
+ return env;
136
+ }
137
+
138
+ function loadDotenvFile(relativePath) {
139
+ const absolute = path.join(process.cwd(), relativePath);
140
+ if (!fs.existsSync(absolute)) return;
141
+ for (const [key, value] of Object.entries(parseEnvBody(fs.readFileSync(absolute, 'utf8')))) {
142
+ if (!process.env[key]) process.env[key] = value;
143
+ }
116
144
  }
117
145
 
118
146
  function loadProjectEnvironment() {
119
- ['.codex/.env', '.claude/.env', '.osuite/.env', '.env'].forEach(loadDotenvFile);
147
+ // Enrollment selects one whole runtime bundle, never a merged global env.
148
+ if (process.argv[2] === 'connect') return;
149
+ [...CLI_CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
150
+ if (process.argv[2] === 'doctor' && !inspectCredentialFile(process.cwd(), relativePath).safe) return;
151
+ loadDotenvFile(relativePath);
152
+ });
120
153
  }
121
154
 
122
155
  function parseArgs(argv) {
@@ -147,13 +180,15 @@ function envValue(name, fallback) {
147
180
  return process.env[name] || process.env[fallback] || '';
148
181
  }
149
182
 
150
- function readConfig() {
183
+ function readConfig(env = process.env) {
184
+ const value = (name, fallback) => env[name] || env[fallback] || '';
151
185
  return {
152
- baseUrl: envValue('OSUITE_BASE_URL', 'DASHCLAW_BASE_URL'),
153
- apiKey: envValue('OSUITE_API_KEY', 'DASHCLAW_API_KEY'),
154
- agentId: envValue('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID') || 'osuite-cli',
155
- runtimeAdapterId: process.env.OSUITE_RUNTIME_ADAPTER_ID || '',
156
- signatureMode: process.env.OSUITE_SIGNATURE_MODE || '',
186
+ baseUrl: value('OSUITE_BASE_URL', 'DASHCLAW_BASE_URL'),
187
+ apiKey: value('OSUITE_API_KEY', 'DASHCLAW_API_KEY'),
188
+ agentId: value('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID') || 'osuite-cli',
189
+ agentKeyId: value('OSUITE_AGENT_KEY_ID', 'DASHCLAW_AGENT_KEY_ID') || null,
190
+ runtimeAdapterId: env.OSUITE_RUNTIME_ADAPTER_ID || '',
191
+ signatureMode: env.OSUITE_SIGNATURE_MODE || '',
157
192
  };
158
193
  }
159
194
 
@@ -190,6 +225,7 @@ function detectRuntimeTarget(preferred = 'auto') {
190
225
  const cwd = process.cwd();
191
226
  if (fs.existsSync(path.join(cwd, '.codex'))) return 'codex';
192
227
  if (fs.existsSync(path.join(cwd, '.claude'))) return 'claude';
228
+ if (fs.existsSync(path.join(cwd, '.cursor'))) return 'cursor';
193
229
  if (fs.existsSync(path.join(cwd, 'mcp.json')) || fs.existsSync(path.join(cwd, '.mcp.json'))) return 'mcp';
194
230
  if (fs.existsSync(path.join(cwd, 'package.json'))) return 'sdk';
195
231
  return 'sdk';
@@ -207,19 +243,13 @@ function buildConnectHandoffUrl({ baseUrl, runtime, code }) {
207
243
  return url.toString();
208
244
  }
209
245
 
210
- function defaultAgentIdForRuntime(runtime) {
211
- if (runtime === 'codex') return 'codex-runtime';
212
- if (runtime === 'claude') return 'claude-code-runtime';
213
- if (runtime === 'mcp') return 'mcp-runtime';
214
- return 'sdk-runtime';
215
- }
216
-
217
246
  function sanitizeConfiguredAgentId(runtime, agentId) {
218
247
  const value = String(agentId || '').trim();
219
248
  if (!value) return '';
220
249
  const knownDefaults = {
221
250
  codex: 'codex-runtime',
222
251
  claude: 'claude-code-runtime',
252
+ cursor: 'cursor-runtime',
223
253
  mcp: 'mcp-runtime',
224
254
  sdk: 'sdk-runtime',
225
255
  };
@@ -234,6 +264,7 @@ function runtimeMatchesConfiguredAdapter(runtime, adapterId) {
234
264
  if (!adapter) return false;
235
265
  if (runtime === 'codex') return adapter === 'codex_hooks';
236
266
  if (runtime === 'claude') return adapter === 'claude_code_hooks' || adapter === 'claude_hooks';
267
+ if (runtime === 'cursor') return adapter === 'cursor_hooks';
237
268
  if (runtime === 'mcp') return adapter.includes('mcp');
238
269
  if (runtime === 'sdk') return ['sdk', 'framework_sdk', 'inline_sdk'].includes(adapter);
239
270
  return false;
@@ -242,7 +273,62 @@ function runtimeMatchesConfiguredAdapter(runtime, adapterId) {
242
273
  function envPathForRuntime(runtime) {
243
274
  if (runtime === 'codex') return '.codex/.env';
244
275
  if (runtime === 'claude') return '.claude/.env';
245
- return '.osuite/.env';
276
+ if (runtime === 'cursor') return '.cursor/.env';
277
+ return runtime === 'mcp' ? MCP_ENV_PATH : SDK_ENV_PATH;
278
+ }
279
+
280
+ function connectionConfig(runtime, liveEnv, { dryRun = false } = {}) {
281
+ if (liveEnv !== null) return readConfig(parseEnvBody(liveEnv));
282
+ const shell = readConfig(SHELL_ENV);
283
+ if (runtimeMatchesConfiguredAdapter(runtime, shell.runtimeAdapterId)) return shell;
284
+ const legacy = dryRun ? null : readCredentialFile(process.cwd(), '.env');
285
+ if (legacy !== null) {
286
+ const config = readConfig(parseEnvBody(legacy));
287
+ if (runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)) return config;
288
+ }
289
+ return readConfig(!shell.apiKey && !shell.runtimeAdapterId ? { OSUITE_BASE_URL: shell.baseUrl } : {});
290
+ }
291
+
292
+ function parseConnectionJournal(raw) {
293
+ if (raw === null) return null;
294
+ try {
295
+ const journal = JSON.parse(raw);
296
+ if (journal && typeof journal === 'object' && !Array.isArray(journal)) return journal;
297
+ } catch { /* Report only metadata, never journal contents. */ }
298
+ throw new Error('The saved connection recovery journal is invalid; it was left unchanged.');
299
+ }
300
+
301
+ function assertRecoveryState(journal, { runtime, baseUrl, agentId, liveEnv, config, installation }) {
302
+ if (journal.protocol_version !== 2 || journal.runtime !== runtime || journal.base_url !== baseUrl
303
+ || typeof journal.agent_id !== 'string' || !journal.agent_id || (agentId && journal.agent_id !== agentId)
304
+ || !journal.session?.device_code || !journal.session?.poll_token) {
305
+ throw new Error('A recovery journal exists for a different connection. Resume its original runtime, agent and Studio URL before reconnecting.');
306
+ }
307
+ if (journal.credential) assertConnectionCredentialScope(journal.credential, { baseUrl, runtime, agentId: journal.agent_id });
308
+ if (Object.hasOwn(journal, 'live_env_sha256')) {
309
+ const digest = journal.live_env_sha256;
310
+ const promoted = journal.credential && liveEnv === formatEnvBody(journal.credential.env);
311
+ if ((digest !== null && (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)))
312
+ || (credentialDigest(liveEnv) !== digest && !promoted)) {
313
+ throw new Error('Connection recovery conflicts with a changed live credential bundle. Stopped without replacing it; inspect the saved handoff in Studio before retrying.');
314
+ }
315
+ } else if (liveEnv !== null && (config.agentId !== journal.agent_id
316
+ || !runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) || normalizedBaseUrl(config.baseUrl) !== baseUrl)) {
317
+ // Pre-candidate journals lack the local snapshot. Never let their agent ID
318
+ // override a different live scope; the server still validates the predecessor.
319
+ throw new Error('Legacy connection recovery conflicts with the live runtime, agent or Studio URL; files were left unchanged.');
320
+ }
321
+ // A fresh explicit choice may differ from inherited config. Retain that
322
+ // original context for retries, rather than letting a new flag waive conflicts.
323
+ const explicitSelection = journal.live_env_sha256 === null
324
+ && journal.explicit_agent_selection?.agent_id === journal.agent_id
325
+ && journal.explicit_agent_selection?.configured_agent_id === config.agentId;
326
+ if (liveEnv === null && config.agentId !== 'osuite-cli' && config.agentId !== journal.agent_id && !explicitSelection) {
327
+ throw new Error('Connection recovery conflicts with the configured agent; files were left unchanged.');
328
+ }
329
+ if (journal.installation_id && journal.installation_id !== installation?.installation_id) {
330
+ throw new Error('Connection recovery installation identity changed or is missing; files were left unchanged.');
331
+ }
246
332
  }
247
333
 
248
334
  function orderedEnvEntries(env = {}) {
@@ -292,6 +378,8 @@ async function postJson(url, body) {
292
378
  method: 'POST',
293
379
  headers: { 'content-type': 'application/json' },
294
380
  body: JSON.stringify(body || {}),
381
+ signal: AbortSignal.timeout(15000),
382
+ redirect: 'error',
295
383
  });
296
384
  const text = await response.text();
297
385
  let payload = {};
@@ -305,11 +393,15 @@ async function postJson(url, body) {
305
393
  return { response, payload };
306
394
  }
307
395
 
308
- async function startDeviceConnect({ baseUrl, runtime, agentId }) {
396
+ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId }) {
309
397
  const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/start`, {
310
398
  runtime,
311
399
  agent_id: agentId,
400
+ ...(installationId ? { installation_id: installationId } : {}),
312
401
  project_root: process.cwd(),
402
+ protocol_version: 2,
403
+ client_version: pkg.version,
404
+ ...(previousKey ? { previous_key: previousKey } : {}),
313
405
  });
314
406
  if (!response.ok) {
315
407
  throw new Error(payload.error || `Unable to start browser handoff: HTTP ${response.status}`);
@@ -347,24 +439,41 @@ function openInBrowser(url) {
347
439
  }
348
440
  }
349
441
 
350
- async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs }) {
442
+ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs, protocolVersion = 1 }) {
351
443
  const deadline = Date.now() + timeoutMs;
352
444
  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
- });
445
+ let result;
446
+ try {
447
+ result = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/poll`, {
448
+ device_code: deviceCode,
449
+ poll_token: pollToken,
450
+ });
451
+ } catch (error) {
452
+ if (protocolVersion !== 2) throw error;
453
+ await sleep(Math.max(10, intervalMs));
454
+ continue;
455
+ }
456
+ const { response, payload } = result;
357
457
 
358
458
  if (response.status === 200 && payload.status === 'approved' && payload.credential?.env) {
459
+ 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)) {
460
+ throw new Error('Studio did not deliver an acknowledged credential. Existing credentials were not changed.');
461
+ }
359
462
  return payload.credential;
360
463
  }
464
+ if (protocolVersion === 2 && response.status >= 500) {
465
+ await sleep(Math.max(10, intervalMs));
466
+ continue;
467
+ }
361
468
  if (response.status === 202 || payload.status === 'pending') {
362
469
  const serverInterval = Number(payload.interval_seconds || 0) * 1000;
363
470
  await sleep(serverInterval > 0 ? Math.max(intervalMs, serverInterval) : intervalMs);
364
471
  continue;
365
472
  }
366
473
  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.');
474
+ const error = new Error('The connect code expired before it was approved. Run osuite connect again for a new code.');
475
+ error.code = 'DEVICE_CONNECT_EXPIRED';
476
+ throw error;
368
477
  }
369
478
  if (response.status === 409 || payload.status === 'consumed') {
370
479
  throw new Error(payload.error || 'Browser handoff was already consumed.');
@@ -377,6 +486,55 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
377
486
  return null;
378
487
  }
379
488
 
489
+ async function finalizeDeviceConnect(journal, journalPath, validateLive) {
490
+ const { credential, session, base_url: baseUrl } = journal;
491
+ for (let attempt = 0; attempt < 3; attempt += 1) {
492
+ validateLive();
493
+ let result;
494
+ try {
495
+ result = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/ack`, {
496
+ protocol_version: 2, device_code: session.device_code, poll_token: session.poll_token,
497
+ key_id: credential.key_id, ack_token: credential.ack_token,
498
+ });
499
+ } catch {
500
+ // A lost response may mean the transaction committed. Retry the same receipt.
501
+ }
502
+ validateLive();
503
+ if (result?.response.ok) {
504
+ if (result.payload.status !== 'finalized' || result.payload.key_id !== credential.key_id || typeof result.payload.active !== 'boolean') {
505
+ throw new Error('Studio did not confirm this saved connection. The recovery journal was left unchanged; retry the same osuite connect command.');
506
+ }
507
+ if (!result.payload.active) {
508
+ removeCredentialFile(process.cwd(), journalPath);
509
+ 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.');
510
+ }
511
+ return;
512
+ }
513
+ if (result && result.response.status < 500) {
514
+ if (result.response.status === 410) {
515
+ removeCredentialFile(process.cwd(), journalPath);
516
+ throw new Error('Saved connection expired before finalization. Existing credentials were not changed; run osuite connect again.');
517
+ }
518
+ throw new Error(`Connection was not finalized (HTTP ${result.response.status}). The recovery journal is saved; rerun the same osuite connect command to resume.`);
519
+ }
520
+ await sleep(100 * (attempt + 1));
521
+ }
522
+ throw new Error('Could not confirm finalization. The recovery journal is saved; rerun the same osuite connect command to resume safely.');
523
+ }
524
+
525
+ function assertConnectionCredentialScope(credential, { baseUrl, runtime, agentId }) {
526
+ const adapter = { codex: 'codex_hooks', claude: 'claude_code_hooks', cursor: 'cursor_hooks' }[runtime] || runtime;
527
+ const env = credential?.env;
528
+ if (credential?.protocol_version !== 2 || !env || !credential.key_id || !credential.ack_token
529
+ || !env.OSUITE_API_KEY || !env.OSUITE_PRIVATE_KEY_BASE64
530
+ || typeof env.OSUITE_BASE_URL !== 'string' || normalizedBaseUrl(env.OSUITE_BASE_URL) !== baseUrl
531
+ || env.OSUITE_AGENT_ID !== agentId || env.OSUITE_RUNTIME_ADAPTER_ID !== adapter
532
+ || (credential.runtime !== undefined && credential.runtime !== runtime)
533
+ || (credential.agent_id !== undefined && credential.agent_id !== agentId)) {
534
+ throw new Error('Delivered credentials do not match this connection. No acknowledgement or local replacement was attempted; inspect this enrollment in Studio.');
535
+ }
536
+ }
537
+
380
538
  function projectFilePath(relativePath) {
381
539
  return resolveProjectPath(process.cwd(), relativePath);
382
540
  }
@@ -470,7 +628,10 @@ async function loadRuntimeBootstrap(spec, args, config) {
470
628
  }
471
629
 
472
630
  const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || DEFAULT_BASE_URL);
473
- const response = await fetch(`${baseUrl}${spec.endpoint}`);
631
+ const response = await fetch(`${baseUrl}${spec.endpoint}`, {
632
+ signal: AbortSignal.timeout(30000),
633
+ redirect: 'error',
634
+ });
474
635
  if (!response.ok) {
475
636
  throw new Error(`Unable to download ${spec.label} bootstrap: HTTP ${response.status}`);
476
637
  }
@@ -480,7 +641,7 @@ async function loadRuntimeBootstrap(spec, args, config) {
480
641
  async function installRuntimeProjectBootstrap(target, args = {}, { nextSteps = true } = {}) {
481
642
  const spec = PROJECT_BOOTSTRAPS[target];
482
643
  const config = readConfig();
483
- const bootstrap = await loadRuntimeBootstrap(spec, args, config);
644
+ const bootstrap = buildNodeRuntimeBootstrap(target, await loadRuntimeBootstrap(spec, args, config));
484
645
  const force = Boolean(args.force);
485
646
  const results = [];
486
647
 
@@ -512,7 +673,7 @@ async function installRuntimeProjectBootstrap(target, args = {}, { nextSteps = t
512
673
  if (nextSteps) {
513
674
  write('');
514
675
  write(c('Next steps', ANSI.bold));
515
- write(` 1. Copy ${spec.envPath} to ${spec.envPath.replace(/\.example$/, '')} and fill OSUITE_API_KEY.`);
676
+ write(` 1. Run osuite connect ${target} to save protected credentials through the browser handoff.`);
516
677
  write(' 2. Run osuite doctor. It checks project enablement, connection, telemetry, and governance with a direct hook probe.');
517
678
  write(` 3. ${spec.runLine}`);
518
679
  write(` 4. ${spec.smokeLine}`);
@@ -560,6 +721,7 @@ function printHelp() {
560
721
  write('');
561
722
  write(c('Useful commands', ANSI.bold));
562
723
  write(' osuite doctor Check connection, then run the project hook with a sample call');
724
+ write(' osuite try Review one fixed, harmless terminal acknowledgement');
563
725
  write(' osuite status Ping Studio and show current workspace connection');
564
726
  write(' osuite explain "git push origin main" Explain how CAVA/Decision V2 will read a command');
565
727
  write(' osuite approvals --limit 20 Show pending approval inbox');
@@ -572,9 +734,10 @@ function printHelp() {
572
734
  write(' osuite adapter test <file> Validate an enterprise custom adapter mapping');
573
735
  write(' osuite external status Show external verifier network setup and usage');
574
736
  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');
737
+ write(' osuite connect [auto|codex|claude|cursor|sdk|mcp] Detect runtime and start browser handoff');
576
738
  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');
739
+ write(' osuite connect mcp --migrate-legacy Move legacy MCP state locally; no enrollment or ACK');
740
+ write(' osuite init [sdk|codex|claude|cursor|mcp] Prepare a runtime lane');
578
741
  write('');
579
742
  write(c('Environment', ANSI.bold));
580
743
  write(' OSUITE_BASE_URL Studio URL, for example https://studio.osuite.ai');
@@ -1020,6 +1183,28 @@ async function doctor() {
1020
1183
  write(c('Checking the local developer entry point.', ANSI.dim));
1021
1184
  write('');
1022
1185
 
1186
+ const credentialChecks = [...CLI_CREDENTIAL_PATHS.flatMap((file) => [file, `${file}.identity.json`, `${file}.connect.json`, `${file}.connect.lock`]), MCP_MIGRATION_PATH, '.env']
1187
+ .map((relativePath) => inspectCredentialFile(process.cwd(), relativePath));
1188
+ const unsafeCredentials = credentialChecks.filter((check) => check.exists && !check.safe);
1189
+ for (const check of credentialChecks.filter((item) => item.exists)) {
1190
+ 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('; ')}`}`);
1191
+ }
1192
+ if (unsafeCredentials.length) {
1193
+ write('Repair credential protection before running hooks. Reconnect to rotate any possibly exposed key; chmod alone cannot undo disclosure.');
1194
+ process.exitCode = 1;
1195
+ return false;
1196
+ }
1197
+ if (credentialChecks.some((check) => check.exists && check.relativePath === MCP_MIGRATION_PATH)) {
1198
+ writeCheckLine('warn', 'MCP migration', 'resume osuite connect mcp --migrate-legacy before using either SDK or MCP.');
1199
+ process.exitCode = 1;
1200
+ return false;
1201
+ }
1202
+ if (credentialChecks.some((check) => check.exists && check.relativePath.endsWith('.connect.json'))) {
1203
+ writeCheckLine('warn', 'Connection recovery', 'resume the original osuite connect command before running this runtime.');
1204
+ process.exitCode = 1;
1205
+ return false;
1206
+ }
1207
+
1023
1208
  const checks = [
1024
1209
  ['OSUITE_BASE_URL', Boolean(config.baseUrl), config.baseUrl || 'missing'],
1025
1210
  ['OSUITE_API_KEY', Boolean(config.apiKey), config.apiKey ? 'present' : 'missing'],
@@ -1035,9 +1220,11 @@ async function doctor() {
1035
1220
 
1036
1221
  if (config.baseUrl) {
1037
1222
  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');
1223
+ const response = await fetch(`${config.baseUrl.replace(/\/$/, '')}/api/health`, {
1224
+ redirect: 'error', signal: AbortSignal.timeout(10000),
1225
+ });
1226
+ const body = await response.json();
1227
+ const healthy = response.ok && body.status === 'healthy';
1041
1228
  ok = ok && healthy;
1042
1229
  write(`${healthy ? c('OK ', ANSI.green) : c('WARN', ANSI.yellow)} ${'Studio health'.padEnd(18)} HTTP ${response.status}`);
1043
1230
  } catch (error) {
@@ -1061,13 +1248,39 @@ async function doctor() {
1061
1248
  hookChecks.filter((check) => !check.ok).forEach((check) => {
1062
1249
  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
1250
  });
1064
- process.exit(1);
1251
+ process.exitCode = 1;
1252
+ return false;
1065
1253
  }
1066
1254
 
1067
1255
  write(c('Your OSuite CLI is ready.', ANSI.green));
1068
1256
  hookChecks.forEach((check) => {
1069
1257
  write(` ${check.installation.label} direct hook probe was governed and reached OSuite; verify host invocation after starting the runtime.`);
1070
1258
  });
1259
+ return true;
1260
+ }
1261
+
1262
+ async function tryWalkthrough(args) {
1263
+ if (args._.length || Object.keys(args).some((key) => !['_', 'timeout-ms'].includes(key))) {
1264
+ throw new Error('osuite try accepts no command arguments: its output is fixed. Only --timeout-ms may be set.');
1265
+ }
1266
+ if (inspectCredentialFile(process.cwd(), MCP_MIGRATION_PATH).exists) {
1267
+ throw new Error('Resume osuite connect mcp --migrate-legacy before starting the walkthrough.');
1268
+ }
1269
+ for (const file of [...CLI_CREDENTIAL_PATHS, '.env']) {
1270
+ const check = inspectCredentialFile(process.cwd(), file);
1271
+ if (check.exists && !check.safe) throw new Error('Credential storage needs attention. Run osuite doctor before starting the walkthrough.');
1272
+ if (inspectCredentialFile(process.cwd(), `${file}.connect.json`).exists) {
1273
+ throw new Error('Resume the saved osuite connect operation before starting the walkthrough.');
1274
+ }
1275
+ }
1276
+ const config = readConfig();
1277
+ const result = await runTryFlow({
1278
+ client: requireClient(), emit: write,
1279
+ timeoutMs: args['timeout-ms'] === undefined ? 300000 : Number(args['timeout-ms']),
1280
+ privateKeyBase64: envValue('OSUITE_PRIVATE_KEY_BASE64', 'DASHCLAW_PRIVATE_KEY_BASE64'),
1281
+ signatureRequired: config.signatureMode === 'required',
1282
+ });
1283
+ write(`Walkthrough completed. Evidence: ${result.replayUrl}`);
1071
1284
  }
1072
1285
 
1073
1286
  async function status() {
@@ -1279,25 +1492,71 @@ async function init(target = 'generic', args = {}) {
1279
1492
  }
1280
1493
  }
1281
1494
 
1282
- async function connect(target = 'auto', args = {}) {
1283
- const config = readConfig();
1495
+ async function connectProject(target = 'auto', args = {}) {
1284
1496
  const runtime = detectRuntimeTarget(target);
1497
+ const envPath = envPathForRuntime(runtime);
1498
+ const journalPath = `${envPath}.connect.json`;
1499
+ const liveEnv = args['dry-run'] ? null : readCredentialFile(process.cwd(), envPath);
1500
+ const config = connectionConfig(runtime, liveEnv, { dryRun: Boolean(args['dry-run']) });
1285
1501
  const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || DEFAULT_BASE_URL);
1502
+ const saved = args['dry-run'] ? null : readCredentialFile(process.cwd(), journalPath);
1503
+ let storedJournal = saved;
1504
+ let journal = parseConnectionJournal(saved);
1505
+ const existingInstallation = args['dry-run'] ? null : readInstallationIdentity(process.cwd(), envPath, runtime);
1506
+ if (journal) {
1507
+ assertRecoveryState(journal, { runtime, baseUrl, agentId: args['agent-id'], liveEnv, config, installation: existingInstallation });
1508
+ } else if (liveEnv !== null && config.runtimeAdapterId && !runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)) {
1509
+ throw new Error('The live credential bundle belongs to a different runtime; it was left unchanged.');
1510
+ }
1511
+ // Validation above is read-only: even missing metadata must not be recreated
1512
+ // over a conflicting live installation merely because a receipt is resumable.
1513
+ const installation = existingInstallation || getInstallationIdentity(process.cwd(), envPath, runtime, { dryRun: Boolean(args['dry-run']) });
1286
1514
  const configuredAgentId = sanitizeConfiguredAgentId(
1287
1515
  runtime,
1288
- runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)
1289
- ? envValue('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID')
1516
+ runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) && config.agentId !== 'osuite-cli'
1517
+ ? config.agentId
1290
1518
  : '',
1291
1519
  );
1292
- const agentId = String(args['agent-id'] || configuredAgentId || defaultAgentIdForRuntime(runtime));
1520
+ const agentId = String(args['agent-id'] || journal?.agent_id || configuredAgentId || installation.agent_id);
1521
+ const validateLive = (receipt = journal) => {
1522
+ if (readCredentialFile(process.cwd(), journalPath) !== storedJournal) {
1523
+ throw new Error('The connection recovery journal changed during this operation; it was left unchanged. Inspect the handoff in Studio before retrying.');
1524
+ }
1525
+ const current = readCredentialFile(process.cwd(), envPath);
1526
+ assertRecoveryState(receipt, { runtime, baseUrl, agentId, liveEnv: current,
1527
+ config: connectionConfig(runtime, current), installation: readInstallationIdentity(process.cwd(), envPath, runtime) });
1528
+ };
1529
+ const saveJournal = () => {
1530
+ validateLive();
1531
+ const body = `${JSON.stringify(journal)}\n`;
1532
+ writeCredentialFile(process.cwd(), journalPath, body);
1533
+ storedJournal = body;
1534
+ };
1293
1535
  const dryRunCode = String(args.code || generateConnectCode()).trim() || generateConnectCode();
1294
1536
  let connectPayload = null;
1295
1537
  let code = dryRunCode;
1296
1538
  let handoffUrl = buildConnectHandoffUrl({ baseUrl, runtime, code });
1297
1539
  const hasApiKey = Boolean(config.apiKey);
1298
-
1299
1540
  if (!args['dry-run']) {
1300
- connectPayload = await startDeviceConnect({ baseUrl, runtime, agentId });
1541
+ if (journal) {
1542
+ connectPayload = journal.session;
1543
+ } else {
1544
+ const previousKey = normalizedBaseUrl(config.baseUrl) === baseUrl && runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) && configuredAgentId === agentId ? config.apiKey : '';
1545
+ connectPayload = await startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId: installation.installation_id });
1546
+ if (connectPayload.protocol_version === 2) {
1547
+ journal = { protocol_version: 2, base_url: baseUrl, runtime, agent_id: agentId, installation_id: installation.installation_id,
1548
+ live_env_sha256: credentialDigest(liveEnv), session: connectPayload };
1549
+ if (liveEnv === null && args['agent-id']) {
1550
+ journal.explicit_agent_selection = { agent_id: agentId, configured_agent_id: config.agentId };
1551
+ }
1552
+ saveJournal();
1553
+ } else {
1554
+ if (hasApiKey && fs.existsSync(projectFilePath(envPath))) {
1555
+ throw new Error('This Studio does not support acknowledged reconnect. Upgrade Studio before replacing existing credentials; they were left unchanged.');
1556
+ }
1557
+ 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));
1558
+ }
1559
+ }
1301
1560
  code = connectPayload.user_code;
1302
1561
  handoffUrl = connectPayload.verification_uri_complete || buildConnectHandoffUrl({ baseUrl, runtime, code });
1303
1562
  }
@@ -1324,7 +1583,7 @@ async function connect(target = 'auto', args = {}) {
1324
1583
  if (args['dry-run']) {
1325
1584
  write(`Dry run: would install project hook files for ${runtime}.`);
1326
1585
  } else {
1327
- install = await installRuntimeProjectBootstrap(runtime, args, { nextSteps: false });
1586
+ install = await installRuntimeProjectBootstrap(runtime, { ...args, 'base-url': baseUrl }, { nextSteps: false });
1328
1587
  }
1329
1588
  } else {
1330
1589
  write(c('Runtime setup', ANSI.bold));
@@ -1346,17 +1605,40 @@ async function connect(target = 'auto', args = {}) {
1346
1605
  write(c('Waiting for browser approval', ANSI.bold));
1347
1606
  write(` Code ${code} expires in about ${Math.round(expiresInSeconds / 60)} minutes. Press Ctrl+C to stop waiting.`);
1348
1607
 
1349
- const credential = await pollDeviceConnect({
1350
- baseUrl,
1351
- deviceCode: connectPayload.device_code,
1352
- pollToken: connectPayload.poll_token,
1353
- timeoutMs,
1354
- intervalMs,
1355
- });
1608
+ let credential = journal?.credential;
1609
+ if (!credential) {
1610
+ try {
1611
+ credential = await pollDeviceConnect({
1612
+ baseUrl,
1613
+ deviceCode: connectPayload.device_code,
1614
+ pollToken: connectPayload.poll_token,
1615
+ timeoutMs,
1616
+ intervalMs,
1617
+ protocolVersion: connectPayload.protocol_version || 1,
1618
+ });
1619
+ } catch (error) {
1620
+ if (journal && error.code === 'DEVICE_CONNECT_EXPIRED') {
1621
+ validateLive();
1622
+ removeCredentialFile(process.cwd(), journalPath);
1623
+ }
1624
+ throw error;
1625
+ }
1626
+ }
1356
1627
 
1357
1628
  if (credential?.env) {
1358
- const envPath = envPathForRuntime(runtime);
1359
- const result = writeProjectFile(envPath, formatEnvBody(credential.env), { force: true });
1629
+ if (journal) {
1630
+ // Check both a fresh delivery and a journal resumed after process death.
1631
+ assertConnectionCredentialScope(credential, { baseUrl, runtime, agentId });
1632
+ validateLive();
1633
+ journal = { ...journal, credential };
1634
+ // fsync both the file and its directory before telling the server to retire
1635
+ // the old key. The live env stays unchanged until that transaction commits.
1636
+ saveJournal();
1637
+ await finalizeDeviceConnect(journal, journalPath, validateLive);
1638
+ validateLive();
1639
+ }
1640
+ const result = writeCredentialFile(process.cwd(), envPath, formatEnvBody(credential.env));
1641
+ if (journal) removeCredentialFile(process.cwd(), journalPath);
1360
1642
  write('');
1361
1643
  write(`Saved credentials to ${result.relativePath}`);
1362
1644
  if (!PROJECT_BOOTSTRAPS[runtime]) {
@@ -1385,7 +1667,9 @@ async function connect(target = 'auto', args = {}) {
1385
1667
  } else {
1386
1668
  write('');
1387
1669
  write(c('Not connected: nobody approved this terminal in the browser in time.', ANSI.yellow));
1388
- write(` Run osuite connect ${runtime} again for a new code${install?.ok ? '; the hook files are already installed, only the credentials are missing' : ''}.`);
1670
+ write(journal
1671
+ ? ` Run osuite connect ${runtime} again to resume this same pending connection; no new request is created while this code remains valid.`
1672
+ : ` Run osuite connect ${runtime} again for a new code${install?.ok ? '; the hook files are already installed, only the credentials are missing' : ''}.`);
1389
1673
  write(' If the browser did not open, copy the handoff link above into it.');
1390
1674
  process.exitCode = 1;
1391
1675
  }
@@ -1396,19 +1680,87 @@ async function connect(target = 'auto', args = {}) {
1396
1680
  if (hasApiKey) {
1397
1681
  write(' OSUITE_API_KEY is already present in this shell or project env. Browser handoff can be skipped for this project.');
1398
1682
  } 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.`);
1683
+ write(' If browser handoff is unavailable, supply OSUITE_BASE_URL and OSUITE_API_KEY through your secret manager or process environment.');
1684
+ write(' Do not copy secrets into an unprotected project file; run osuite doctor before relying on the connection.');
1401
1685
  } else {
1402
1686
  write(' If browser handoff is unavailable, export OSUITE_BASE_URL and OSUITE_API_KEY before running the agent.');
1403
1687
  }
1404
1688
  }
1405
1689
 
1690
+ async function connect(target = 'auto', args = {}) {
1691
+ const runtime = detectRuntimeTarget(target);
1692
+ if (args['migrate-legacy'] && runtime !== 'mcp') throw new Error('Legacy migration requires osuite connect mcp --migrate-legacy.');
1693
+ if (args['dry-run']) {
1694
+ if (args['migrate-legacy']) return write(`Dry run: would move legacy MCP credentials, identity and journal from ${SDK_ENV_PATH} to ${MCP_ENV_PATH}; no network or file changes.`);
1695
+ return connectProject(runtime, args);
1696
+ }
1697
+ const releases = [];
1698
+ try {
1699
+ if (args['migrate-legacy']) releases.push(acquireCredentialLock(process.cwd(), SDK_ENV_PATH));
1700
+ releases.push(acquireCredentialLock(process.cwd(), envPathForRuntime(runtime)));
1701
+ if (args['migrate-legacy']) return migrateLegacyMcp(args);
1702
+ if (runtime === 'sdk' || runtime === 'mcp') {
1703
+ if (readCredentialFile(process.cwd(), MCP_MIGRATION_PATH) !== null) {
1704
+ throw new Error('MCP migration is incomplete. Resume osuite connect mcp --migrate-legacy before using either runtime.');
1705
+ }
1706
+ const legacy = readInstallationBundle(process.cwd(), SDK_ENV_PATH);
1707
+ const legacyEnv = parseEnvBody(legacy.env || '');
1708
+ const legacyConfig = readConfig(legacyEnv);
1709
+ if (!runtimeMatchesConfiguredAdapter('sdk', legacyConfig.runtimeAdapterId)
1710
+ && !runtimeMatchesConfiguredAdapter('mcp', legacyConfig.runtimeAdapterId)
1711
+ && (legacyConfig.apiKey || legacyConfig.agentId !== 'osuite-cli' || legacyEnv.OSUITE_PRIVATE_KEY_BASE64 || legacyEnv.DASHCLAW_PRIVATE_KEY_BASE64)) {
1712
+ throw new Error('Shared legacy credential ownership is ambiguous. Verify and declare its OSUITE_RUNTIME_ADAPTER_ID before connecting; MCP owners must then use osuite connect mcp --migrate-legacy. Files were left unchanged.');
1713
+ }
1714
+ if (legacyMcpPresent(legacy)) {
1715
+ throw new Error('Legacy MCP state conflicts with the shared .osuite/.env namespace. Run osuite connect mcp --migrate-legacy to move it explicitly; no credentials were replaced.');
1716
+ }
1717
+ }
1718
+ return await connectProject(runtime, args);
1719
+ } finally { releases.reverse().forEach(release => release()); }
1720
+ }
1721
+
1722
+ function legacyMcpPresent(bundle) {
1723
+ const config = readConfig(parseEnvBody(bundle.env || ''));
1724
+ const journal = parseConnectionJournal(bundle.journal);
1725
+ let identity;
1726
+ try { identity = bundle.identity === null ? null : JSON.parse(bundle.identity); }
1727
+ catch { throw new Error('Invalid installation identity file; it was left unchanged.'); }
1728
+ return runtimeMatchesConfiguredAdapter('mcp', config.runtimeAdapterId) || identity?.runtime === 'mcp' || journal?.runtime === 'mcp';
1729
+ }
1730
+
1731
+ function migrateLegacyMcp(args) {
1732
+ const inspected = readMcpMigration(process.cwd());
1733
+ if (!inspected.manifest && Object.values(inspected.destination).some(body => body !== null)) {
1734
+ throw new Error('MCP migration destination is already occupied; nothing was overwritten.');
1735
+ }
1736
+ const { bundle } = inspected;
1737
+ if (!legacyMcpPresent(bundle)) throw new Error('No unambiguous legacy MCP installation to migrate; files were left unchanged.');
1738
+ const config = readConfig(parseEnvBody(bundle.env || ''));
1739
+ const installation = parseInstallationIdentity(bundle.identity, 'mcp');
1740
+ const journal = parseConnectionJournal(bundle.journal);
1741
+ if (bundle.env !== null && (!runtimeMatchesConfiguredAdapter('mcp', config.runtimeAdapterId) || config.agentId === 'osuite-cli')) {
1742
+ throw new Error('Legacy MCP migration conflicts with an ambiguous or different live runtime; files were left unchanged.');
1743
+ }
1744
+ const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || journal?.base_url);
1745
+ if ((args['base-url'] && config.baseUrl && normalizedBaseUrl(config.baseUrl) !== baseUrl)
1746
+ || (args['agent-id'] && args['agent-id'] !== config.agentId)) {
1747
+ throw new Error('MCP migration cannot change the live agent or Studio URL; files were left unchanged.');
1748
+ }
1749
+ if (journal) assertRecoveryState(journal, { runtime: 'mcp', baseUrl, agentId: args['agent-id'], liveEnv: bundle.env, config, installation });
1750
+ migrateMcpInstallation(process.cwd(), inspected);
1751
+ write(`MCP migration complete: moved credentials, identity and recovery state to ${MCP_ENV_PATH}.`);
1752
+ write('No enrollment, acknowledgement or server identity change was performed.');
1753
+ write('Update the MCP launcher to read this env path before restarting it or connecting SDK in this project.');
1754
+ write('Run osuite connect mcp to resume a saved handoff or rotate with the same identity. SDK continues to use .osuite/.env.');
1755
+ }
1756
+
1406
1757
  async function main() {
1407
1758
  const { command, args } = parseArgs(process.argv.slice(2));
1408
1759
 
1409
1760
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1410
1761
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1411
- if (command === 'doctor') return doctor();
1762
+ if (command === 'doctor') return runDoctorWithMeasurement(doctor, { config: readConfig(), emit: write });
1763
+ if (command === 'try') return tryWalkthrough(args);
1412
1764
  if (command === 'status') return status();
1413
1765
  if (command === 'explain') return printExplanation(args._.join(' '));
1414
1766
  if (command === 'approvals') return approvals(args);