osuite 2.10.1 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -8,6 +8,11 @@ import { fileURLToPath } from 'node:url';
8
8
  import { OSuite, buildReviewSurface } from './osuite.js';
9
9
  import { runTryFlow } from './tryFlow.js';
10
10
  import { runDoctorWithMeasurement } from './activationMetrics.js';
11
+ import {
12
+ credentialDigest, getInstallationIdentity, migrateMcpInstallation, parseInstallationIdentity,
13
+ readInstallationBundle, readInstallationIdentity, readMcpMigration,
14
+ MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH,
15
+ } from './installationIdentity.js';
11
16
  import {
12
17
  CREDENTIAL_PATHS, acquireCredentialLock, inspectCredentialFile,
13
18
  readCredentialFile, removeCredentialFile, writeCredentialFile,
@@ -52,6 +57,7 @@ const GIT_OBSERVATION_RISKS = {
52
57
  const PUBLIC_FILE_HOST_HINTS = ['transfer.sh', 'file.io', 'tmpfiles.org', '0x0.st', 'ufile.io', 'gofile.io', 'wetransfer.com'];
53
58
  const SECURITY_CONTROL_WEAKENING_RE = /(\bspctl\b[\s\S]*(--master-disable|--global-disable|--disable)|\bcsrutil\b[\s\S]*\bdisable\b|Set-MpPreference[\s\S]*Disable(?:RealtimeMonitoring|BehaviorMonitoring|IOAVProtection)[\s\S]*(true|\$true|1)|netsh\s+advfirewall\s+set\s+allprofiles\s+state\s+off|\bsystemctl\b[\s\S]*\b(stop|disable|mask)\b[\s\S]*(auditd|falcon|crowdstrike|osquery|defender|mdatp|sentinel|carbonblack|firewalld|ufw)|\bufw\b[\s\S]*\bdisable\b)/i;
54
59
  const DEFAULT_BASE_URL = 'https://studio.osuite.ai';
60
+ const CLI_CREDENTIAL_PATHS = [...CREDENTIAL_PATHS, MCP_ENV_PATH];
55
61
  const PROJECT_BOOTSTRAPS = {
56
62
  codex: {
57
63
  label: 'Codex hook runtime',
@@ -115,10 +121,8 @@ function write(value = '') {
115
121
  process.stdout.write(`${value}\n`);
116
122
  }
117
123
 
118
- function loadDotenvFile(relativePath) {
119
- const absolute = path.join(process.cwd(), relativePath);
120
- if (!fs.existsSync(absolute)) return;
121
- const body = fs.readFileSync(absolute, 'utf8');
124
+ function parseEnvBody(body = '') {
125
+ const env = Object.create(null);
122
126
  body.split(/\r?\n/).forEach((line) => {
123
127
  const trimmed = line.trim();
124
128
  if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) return;
@@ -126,12 +130,23 @@ function loadDotenvFile(relativePath) {
126
130
  const key = rawKey.trim();
127
131
  let value = rawValue.join('=').trim().replace(/^['"]|['"]$/g, '');
128
132
  if (value.includes(' #')) value = value.slice(0, value.indexOf(' #')).trim();
129
- if (key && !process.env[key]) process.env[key] = value;
133
+ if (key && !env[key]) env[key] = value;
130
134
  });
135
+ return env;
136
+ }
137
+
138
+ function loadDotenvFile(relativePath) {
139
+ const absolute = path.join(process.cwd(), relativePath);
140
+ if (!fs.existsSync(absolute)) return;
141
+ for (const [key, value] of Object.entries(parseEnvBody(fs.readFileSync(absolute, 'utf8')))) {
142
+ if (!process.env[key]) process.env[key] = value;
143
+ }
131
144
  }
132
145
 
133
146
  function loadProjectEnvironment() {
134
- [...CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
147
+ // Enrollment selects one whole runtime bundle, never a merged global env.
148
+ if (process.argv[2] === 'connect') return;
149
+ [...CLI_CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
135
150
  if (process.argv[2] === 'doctor' && !inspectCredentialFile(process.cwd(), relativePath).safe) return;
136
151
  loadDotenvFile(relativePath);
137
152
  });
@@ -165,14 +180,15 @@ function envValue(name, fallback) {
165
180
  return process.env[name] || process.env[fallback] || '';
166
181
  }
167
182
 
168
- function readConfig() {
183
+ function readConfig(env = process.env) {
184
+ const value = (name, fallback) => env[name] || env[fallback] || '';
169
185
  return {
170
- baseUrl: envValue('OSUITE_BASE_URL', 'DASHCLAW_BASE_URL'),
171
- apiKey: envValue('OSUITE_API_KEY', 'DASHCLAW_API_KEY'),
172
- agentId: envValue('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID') || 'osuite-cli',
173
- agentKeyId: envValue('OSUITE_AGENT_KEY_ID', 'DASHCLAW_AGENT_KEY_ID') || null,
174
- runtimeAdapterId: process.env.OSUITE_RUNTIME_ADAPTER_ID || '',
175
- signatureMode: process.env.OSUITE_SIGNATURE_MODE || '',
186
+ baseUrl: value('OSUITE_BASE_URL', 'DASHCLAW_BASE_URL'),
187
+ apiKey: value('OSUITE_API_KEY', 'DASHCLAW_API_KEY'),
188
+ agentId: value('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID') || 'osuite-cli',
189
+ agentKeyId: value('OSUITE_AGENT_KEY_ID', 'DASHCLAW_AGENT_KEY_ID') || null,
190
+ runtimeAdapterId: env.OSUITE_RUNTIME_ADAPTER_ID || '',
191
+ signatureMode: env.OSUITE_SIGNATURE_MODE || '',
176
192
  };
177
193
  }
178
194
 
@@ -227,14 +243,6 @@ function buildConnectHandoffUrl({ baseUrl, runtime, code }) {
227
243
  return url.toString();
228
244
  }
229
245
 
230
- function defaultAgentIdForRuntime(runtime) {
231
- if (runtime === 'codex') return 'codex-runtime';
232
- if (runtime === 'claude') return 'claude-code-runtime';
233
- if (runtime === 'cursor') return 'cursor-runtime';
234
- if (runtime === 'mcp') return 'mcp-runtime';
235
- return 'sdk-runtime';
236
- }
237
-
238
246
  function sanitizeConfiguredAgentId(runtime, agentId) {
239
247
  const value = String(agentId || '').trim();
240
248
  if (!value) return '';
@@ -266,7 +274,61 @@ function envPathForRuntime(runtime) {
266
274
  if (runtime === 'codex') return '.codex/.env';
267
275
  if (runtime === 'claude') return '.claude/.env';
268
276
  if (runtime === 'cursor') return '.cursor/.env';
269
- return '.osuite/.env';
277
+ return runtime === 'mcp' ? MCP_ENV_PATH : SDK_ENV_PATH;
278
+ }
279
+
280
+ function connectionConfig(runtime, liveEnv, { dryRun = false } = {}) {
281
+ if (liveEnv !== null) return readConfig(parseEnvBody(liveEnv));
282
+ const shell = readConfig(SHELL_ENV);
283
+ if (runtimeMatchesConfiguredAdapter(runtime, shell.runtimeAdapterId)) return shell;
284
+ const legacy = dryRun ? null : readCredentialFile(process.cwd(), '.env');
285
+ if (legacy !== null) {
286
+ const config = readConfig(parseEnvBody(legacy));
287
+ if (runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)) return config;
288
+ }
289
+ return readConfig(!shell.apiKey && !shell.runtimeAdapterId ? { OSUITE_BASE_URL: shell.baseUrl } : {});
290
+ }
291
+
292
+ function parseConnectionJournal(raw) {
293
+ if (raw === null) return null;
294
+ try {
295
+ const journal = JSON.parse(raw);
296
+ if (journal && typeof journal === 'object' && !Array.isArray(journal)) return journal;
297
+ } catch { /* Report only metadata, never journal contents. */ }
298
+ throw new Error('The saved connection recovery journal is invalid; it was left unchanged.');
299
+ }
300
+
301
+ function assertRecoveryState(journal, { runtime, baseUrl, agentId, liveEnv, config, installation }) {
302
+ if (journal.protocol_version !== 2 || journal.runtime !== runtime || journal.base_url !== baseUrl
303
+ || typeof journal.agent_id !== 'string' || !journal.agent_id || (agentId && journal.agent_id !== agentId)
304
+ || !journal.session?.device_code || !journal.session?.poll_token) {
305
+ throw new Error('A recovery journal exists for a different connection. Resume its original runtime, agent and Studio URL before reconnecting.');
306
+ }
307
+ if (journal.credential) assertConnectionCredentialScope(journal.credential, { baseUrl, runtime, agentId: journal.agent_id });
308
+ if (Object.hasOwn(journal, 'live_env_sha256')) {
309
+ const digest = journal.live_env_sha256;
310
+ const promoted = journal.credential && liveEnv === formatEnvBody(journal.credential.env);
311
+ if ((digest !== null && (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)))
312
+ || (credentialDigest(liveEnv) !== digest && !promoted)) {
313
+ throw new Error('Connection recovery conflicts with a changed live credential bundle. Stopped without replacing it; inspect the saved handoff in Studio before retrying.');
314
+ }
315
+ } else if (liveEnv !== null && (config.agentId !== journal.agent_id
316
+ || !runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) || normalizedBaseUrl(config.baseUrl) !== baseUrl)) {
317
+ // Pre-candidate journals lack the local snapshot. Never let their agent ID
318
+ // override a different live scope; the server still validates the predecessor.
319
+ throw new Error('Legacy connection recovery conflicts with the live runtime, agent or Studio URL; files were left unchanged.');
320
+ }
321
+ // A fresh explicit choice may differ from inherited config. Retain that
322
+ // original context for retries, rather than letting a new flag waive conflicts.
323
+ const explicitSelection = journal.live_env_sha256 === null
324
+ && journal.explicit_agent_selection?.agent_id === journal.agent_id
325
+ && journal.explicit_agent_selection?.configured_agent_id === config.agentId;
326
+ if (liveEnv === null && config.agentId !== 'osuite-cli' && config.agentId !== journal.agent_id && !explicitSelection) {
327
+ throw new Error('Connection recovery conflicts with the configured agent; files were left unchanged.');
328
+ }
329
+ if (journal.installation_id && journal.installation_id !== installation?.installation_id) {
330
+ throw new Error('Connection recovery installation identity changed or is missing; files were left unchanged.');
331
+ }
270
332
  }
271
333
 
272
334
  function orderedEnvEntries(env = {}) {
@@ -331,10 +393,11 @@ async function postJson(url, body) {
331
393
  return { response, payload };
332
394
  }
333
395
 
334
- async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey }) {
396
+ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId }) {
335
397
  const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/start`, {
336
398
  runtime,
337
399
  agent_id: agentId,
400
+ ...(installationId ? { installation_id: installationId } : {}),
338
401
  project_root: process.cwd(),
339
402
  protocol_version: 2,
340
403
  client_version: pkg.version,
@@ -423,9 +486,10 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
423
486
  return null;
424
487
  }
425
488
 
426
- async function finalizeDeviceConnect(journal, journalPath) {
489
+ async function finalizeDeviceConnect(journal, journalPath, validateLive) {
427
490
  const { credential, session, base_url: baseUrl } = journal;
428
491
  for (let attempt = 0; attempt < 3; attempt += 1) {
492
+ validateLive();
429
493
  let result;
430
494
  try {
431
495
  result = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/ack`, {
@@ -435,6 +499,7 @@ async function finalizeDeviceConnect(journal, journalPath) {
435
499
  } catch {
436
500
  // A lost response may mean the transaction committed. Retry the same receipt.
437
501
  }
502
+ validateLive();
438
503
  if (result?.response.ok) {
439
504
  if (result.payload.status !== 'finalized' || result.payload.key_id !== credential.key_id || typeof result.payload.active !== 'boolean') {
440
505
  throw new Error('Studio did not confirm this saved connection. The recovery journal was left unchanged; retry the same osuite connect command.');
@@ -457,6 +522,19 @@ async function finalizeDeviceConnect(journal, journalPath) {
457
522
  throw new Error('Could not confirm finalization. The recovery journal is saved; rerun the same osuite connect command to resume safely.');
458
523
  }
459
524
 
525
+ function assertConnectionCredentialScope(credential, { baseUrl, runtime, agentId }) {
526
+ const adapter = { codex: 'codex_hooks', claude: 'claude_code_hooks', cursor: 'cursor_hooks' }[runtime] || runtime;
527
+ const env = credential?.env;
528
+ if (credential?.protocol_version !== 2 || !env || !credential.key_id || !credential.ack_token
529
+ || !env.OSUITE_API_KEY || !env.OSUITE_PRIVATE_KEY_BASE64
530
+ || typeof env.OSUITE_BASE_URL !== 'string' || normalizedBaseUrl(env.OSUITE_BASE_URL) !== baseUrl
531
+ || env.OSUITE_AGENT_ID !== agentId || env.OSUITE_RUNTIME_ADAPTER_ID !== adapter
532
+ || (credential.runtime !== undefined && credential.runtime !== runtime)
533
+ || (credential.agent_id !== undefined && credential.agent_id !== agentId)) {
534
+ throw new Error('Delivered credentials do not match this connection. No acknowledgement or local replacement was attempted; inspect this enrollment in Studio.');
535
+ }
536
+ }
537
+
460
538
  function projectFilePath(relativePath) {
461
539
  return resolveProjectPath(process.cwd(), relativePath);
462
540
  }
@@ -658,6 +736,7 @@ function printHelp() {
658
736
  write(' osuite external configure --provider babyblue_invinoveritas --mode shadow --api-key <key> --expected-source-class independent_mediator');
659
737
  write(' osuite connect [auto|codex|claude|cursor|sdk|mcp] Detect runtime and start browser handoff');
660
738
  write(' --no-browser prints the link instead of opening it');
739
+ write(' osuite connect mcp --migrate-legacy Move legacy MCP state locally; no enrollment or ACK');
661
740
  write(' osuite init [sdk|codex|claude|cursor|mcp] Prepare a runtime lane');
662
741
  write('');
663
742
  write(c('Environment', ANSI.bold));
@@ -1104,7 +1183,7 @@ async function doctor() {
1104
1183
  write(c('Checking the local developer entry point.', ANSI.dim));
1105
1184
  write('');
1106
1185
 
1107
- const credentialChecks = [...CREDENTIAL_PATHS.flatMap((file) => [file, `${file}.connect.json`, `${file}.connect.lock`]), '.env']
1186
+ const credentialChecks = [...CLI_CREDENTIAL_PATHS.flatMap((file) => [file, `${file}.identity.json`, `${file}.connect.json`, `${file}.connect.lock`]), MCP_MIGRATION_PATH, '.env']
1108
1187
  .map((relativePath) => inspectCredentialFile(process.cwd(), relativePath));
1109
1188
  const unsafeCredentials = credentialChecks.filter((check) => check.exists && !check.safe);
1110
1189
  for (const check of credentialChecks.filter((item) => item.exists)) {
@@ -1115,6 +1194,11 @@ async function doctor() {
1115
1194
  process.exitCode = 1;
1116
1195
  return false;
1117
1196
  }
1197
+ if (credentialChecks.some((check) => check.exists && check.relativePath === MCP_MIGRATION_PATH)) {
1198
+ writeCheckLine('warn', 'MCP migration', 'resume osuite connect mcp --migrate-legacy before using either SDK or MCP.');
1199
+ process.exitCode = 1;
1200
+ return false;
1201
+ }
1118
1202
  if (credentialChecks.some((check) => check.exists && check.relativePath.endsWith('.connect.json'))) {
1119
1203
  writeCheckLine('warn', 'Connection recovery', 'resume the original osuite connect command before running this runtime.');
1120
1204
  process.exitCode = 1;
@@ -1179,7 +1263,10 @@ async function tryWalkthrough(args) {
1179
1263
  if (args._.length || Object.keys(args).some((key) => !['_', 'timeout-ms'].includes(key))) {
1180
1264
  throw new Error('osuite try accepts no command arguments: its output is fixed. Only --timeout-ms may be set.');
1181
1265
  }
1182
- for (const file of [...CREDENTIAL_PATHS, '.env']) {
1266
+ if (inspectCredentialFile(process.cwd(), MCP_MIGRATION_PATH).exists) {
1267
+ throw new Error('Resume osuite connect mcp --migrate-legacy before starting the walkthrough.');
1268
+ }
1269
+ for (const file of [...CLI_CREDENTIAL_PATHS, '.env']) {
1183
1270
  const check = inspectCredentialFile(process.cwd(), file);
1184
1271
  if (check.exists && !check.safe) throw new Error('Credential storage needs attention. Run osuite doctor before starting the walkthrough.');
1185
1272
  if (inspectCredentialFile(process.cwd(), `${file}.connect.json`).exists) {
@@ -1406,39 +1493,63 @@ async function init(target = 'generic', args = {}) {
1406
1493
  }
1407
1494
 
1408
1495
  async function connectProject(target = 'auto', args = {}) {
1409
- const config = readConfig();
1410
1496
  const runtime = detectRuntimeTarget(target);
1497
+ const envPath = envPathForRuntime(runtime);
1498
+ const journalPath = `${envPath}.connect.json`;
1499
+ const liveEnv = args['dry-run'] ? null : readCredentialFile(process.cwd(), envPath);
1500
+ const config = connectionConfig(runtime, liveEnv, { dryRun: Boolean(args['dry-run']) });
1411
1501
  const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || DEFAULT_BASE_URL);
1502
+ const saved = args['dry-run'] ? null : readCredentialFile(process.cwd(), journalPath);
1503
+ let storedJournal = saved;
1504
+ let journal = parseConnectionJournal(saved);
1505
+ const existingInstallation = args['dry-run'] ? null : readInstallationIdentity(process.cwd(), envPath, runtime);
1506
+ if (journal) {
1507
+ assertRecoveryState(journal, { runtime, baseUrl, agentId: args['agent-id'], liveEnv, config, installation: existingInstallation });
1508
+ } else if (liveEnv !== null && config.runtimeAdapterId && !runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)) {
1509
+ throw new Error('The live credential bundle belongs to a different runtime; it was left unchanged.');
1510
+ }
1511
+ // Validation above is read-only: even missing metadata must not be recreated
1512
+ // over a conflicting live installation merely because a receipt is resumable.
1513
+ const installation = existingInstallation || getInstallationIdentity(process.cwd(), envPath, runtime, { dryRun: Boolean(args['dry-run']) });
1412
1514
  const configuredAgentId = sanitizeConfiguredAgentId(
1413
1515
  runtime,
1414
- runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId)
1415
- ? envValue('OSUITE_AGENT_ID', 'DASHCLAW_AGENT_ID')
1516
+ runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) && config.agentId !== 'osuite-cli'
1517
+ ? config.agentId
1416
1518
  : '',
1417
1519
  );
1418
- const agentId = String(args['agent-id'] || configuredAgentId || defaultAgentIdForRuntime(runtime));
1520
+ const agentId = String(args['agent-id'] || journal?.agent_id || configuredAgentId || installation.agent_id);
1521
+ const validateLive = (receipt = journal) => {
1522
+ if (readCredentialFile(process.cwd(), journalPath) !== storedJournal) {
1523
+ throw new Error('The connection recovery journal changed during this operation; it was left unchanged. Inspect the handoff in Studio before retrying.');
1524
+ }
1525
+ const current = readCredentialFile(process.cwd(), envPath);
1526
+ assertRecoveryState(receipt, { runtime, baseUrl, agentId, liveEnv: current,
1527
+ config: connectionConfig(runtime, current), installation: readInstallationIdentity(process.cwd(), envPath, runtime) });
1528
+ };
1529
+ const saveJournal = () => {
1530
+ validateLive();
1531
+ const body = `${JSON.stringify(journal)}\n`;
1532
+ writeCredentialFile(process.cwd(), journalPath, body);
1533
+ storedJournal = body;
1534
+ };
1419
1535
  const dryRunCode = String(args.code || generateConnectCode()).trim() || generateConnectCode();
1420
1536
  let connectPayload = null;
1421
1537
  let code = dryRunCode;
1422
1538
  let handoffUrl = buildConnectHandoffUrl({ baseUrl, runtime, code });
1423
1539
  const hasApiKey = Boolean(config.apiKey);
1424
- const envPath = envPathForRuntime(runtime);
1425
- const journalPath = `${envPath}.connect.json`;
1426
- let journal = null;
1427
-
1428
1540
  if (!args['dry-run']) {
1429
- const saved = readCredentialFile(process.cwd(), journalPath);
1430
- if (saved) {
1431
- try { journal = JSON.parse(saved); } catch { throw new Error('The saved connection recovery journal is invalid; it was left unchanged.'); }
1432
- if (journal.protocol_version !== 2 || journal.base_url !== baseUrl || journal.runtime !== runtime || journal.agent_id !== agentId || !journal.session?.device_code || !journal.session?.poll_token) {
1433
- throw new Error('A recovery journal exists for a different connection. Resume its original runtime, agent and Studio URL before reconnecting.');
1434
- }
1541
+ if (journal) {
1435
1542
  connectPayload = journal.session;
1436
1543
  } else {
1437
1544
  const previousKey = normalizedBaseUrl(config.baseUrl) === baseUrl && runtimeMatchesConfiguredAdapter(runtime, config.runtimeAdapterId) && configuredAgentId === agentId ? config.apiKey : '';
1438
- connectPayload = await startDeviceConnect({ baseUrl, runtime, agentId, previousKey });
1545
+ connectPayload = await startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId: installation.installation_id });
1439
1546
  if (connectPayload.protocol_version === 2) {
1440
- journal = { protocol_version: 2, base_url: baseUrl, runtime, agent_id: agentId, session: connectPayload };
1441
- writeCredentialFile(process.cwd(), journalPath, `${JSON.stringify(journal)}\n`);
1547
+ journal = { protocol_version: 2, base_url: baseUrl, runtime, agent_id: agentId, installation_id: installation.installation_id,
1548
+ live_env_sha256: credentialDigest(liveEnv), session: connectPayload };
1549
+ if (liveEnv === null && args['agent-id']) {
1550
+ journal.explicit_agent_selection = { agent_id: agentId, configured_agent_id: config.agentId };
1551
+ }
1552
+ saveJournal();
1442
1553
  } else {
1443
1554
  if (hasApiKey && fs.existsSync(projectFilePath(envPath))) {
1444
1555
  throw new Error('This Studio does not support acknowledged reconnect. Upgrade Studio before replacing existing credentials; they were left unchanged.');
@@ -1472,7 +1583,7 @@ async function connectProject(target = 'auto', args = {}) {
1472
1583
  if (args['dry-run']) {
1473
1584
  write(`Dry run: would install project hook files for ${runtime}.`);
1474
1585
  } else {
1475
- install = await installRuntimeProjectBootstrap(runtime, args, { nextSteps: false });
1586
+ install = await installRuntimeProjectBootstrap(runtime, { ...args, 'base-url': baseUrl }, { nextSteps: false });
1476
1587
  }
1477
1588
  } else {
1478
1589
  write(c('Runtime setup', ANSI.bold));
@@ -1506,18 +1617,25 @@ async function connectProject(target = 'auto', args = {}) {
1506
1617
  protocolVersion: connectPayload.protocol_version || 1,
1507
1618
  });
1508
1619
  } catch (error) {
1509
- if (journal && error.code === 'DEVICE_CONNECT_EXPIRED') removeCredentialFile(process.cwd(), journalPath);
1620
+ if (journal && error.code === 'DEVICE_CONNECT_EXPIRED') {
1621
+ validateLive();
1622
+ removeCredentialFile(process.cwd(), journalPath);
1623
+ }
1510
1624
  throw error;
1511
1625
  }
1512
1626
  }
1513
1627
 
1514
1628
  if (credential?.env) {
1515
1629
  if (journal) {
1630
+ // Check both a fresh delivery and a journal resumed after process death.
1631
+ assertConnectionCredentialScope(credential, { baseUrl, runtime, agentId });
1632
+ validateLive();
1516
1633
  journal = { ...journal, credential };
1517
1634
  // fsync both the file and its directory before telling the server to retire
1518
1635
  // the old key. The live env stays unchanged until that transaction commits.
1519
- writeCredentialFile(process.cwd(), journalPath, `${JSON.stringify(journal)}\n`);
1520
- await finalizeDeviceConnect(journal, journalPath);
1636
+ saveJournal();
1637
+ await finalizeDeviceConnect(journal, journalPath, validateLive);
1638
+ validateLive();
1521
1639
  }
1522
1640
  const result = writeCredentialFile(process.cwd(), envPath, formatEnvBody(credential.env));
1523
1641
  if (journal) removeCredentialFile(process.cwd(), journalPath);
@@ -1549,7 +1667,9 @@ async function connectProject(target = 'auto', args = {}) {
1549
1667
  } else {
1550
1668
  write('');
1551
1669
  write(c('Not connected: nobody approved this terminal in the browser in time.', ANSI.yellow));
1552
- write(` Run osuite connect ${runtime} again for a new code${install?.ok ? '; the hook files are already installed, only the credentials are missing' : ''}.`);
1670
+ write(journal
1671
+ ? ` Run osuite connect ${runtime} again to resume this same pending connection; no new request is created while this code remains valid.`
1672
+ : ` Run osuite connect ${runtime} again for a new code${install?.ok ? '; the hook files are already installed, only the credentials are missing' : ''}.`);
1553
1673
  write(' If the browser did not open, copy the handoff link above into it.');
1554
1674
  process.exitCode = 1;
1555
1675
  }
@@ -1568,11 +1688,70 @@ async function connectProject(target = 'auto', args = {}) {
1568
1688
  }
1569
1689
 
1570
1690
  async function connect(target = 'auto', args = {}) {
1571
- if (args['dry-run']) return connectProject(target, args);
1572
1691
  const runtime = detectRuntimeTarget(target);
1573
- const release = acquireCredentialLock(process.cwd(), envPathForRuntime(runtime));
1574
- try { return await connectProject(runtime, args); }
1575
- finally { release(); }
1692
+ if (args['migrate-legacy'] && runtime !== 'mcp') throw new Error('Legacy migration requires osuite connect mcp --migrate-legacy.');
1693
+ if (args['dry-run']) {
1694
+ if (args['migrate-legacy']) return write(`Dry run: would move legacy MCP credentials, identity and journal from ${SDK_ENV_PATH} to ${MCP_ENV_PATH}; no network or file changes.`);
1695
+ return connectProject(runtime, args);
1696
+ }
1697
+ const releases = [];
1698
+ try {
1699
+ if (args['migrate-legacy']) releases.push(acquireCredentialLock(process.cwd(), SDK_ENV_PATH));
1700
+ releases.push(acquireCredentialLock(process.cwd(), envPathForRuntime(runtime)));
1701
+ if (args['migrate-legacy']) return migrateLegacyMcp(args);
1702
+ if (runtime === 'sdk' || runtime === 'mcp') {
1703
+ if (readCredentialFile(process.cwd(), MCP_MIGRATION_PATH) !== null) {
1704
+ throw new Error('MCP migration is incomplete. Resume osuite connect mcp --migrate-legacy before using either runtime.');
1705
+ }
1706
+ const legacy = readInstallationBundle(process.cwd(), SDK_ENV_PATH);
1707
+ const legacyEnv = parseEnvBody(legacy.env || '');
1708
+ const legacyConfig = readConfig(legacyEnv);
1709
+ if (!runtimeMatchesConfiguredAdapter('sdk', legacyConfig.runtimeAdapterId)
1710
+ && !runtimeMatchesConfiguredAdapter('mcp', legacyConfig.runtimeAdapterId)
1711
+ && (legacyConfig.apiKey || legacyConfig.agentId !== 'osuite-cli' || legacyEnv.OSUITE_PRIVATE_KEY_BASE64 || legacyEnv.DASHCLAW_PRIVATE_KEY_BASE64)) {
1712
+ throw new Error('Shared legacy credential ownership is ambiguous. Verify and declare its OSUITE_RUNTIME_ADAPTER_ID before connecting; MCP owners must then use osuite connect mcp --migrate-legacy. Files were left unchanged.');
1713
+ }
1714
+ if (legacyMcpPresent(legacy)) {
1715
+ throw new Error('Legacy MCP state conflicts with the shared .osuite/.env namespace. Run osuite connect mcp --migrate-legacy to move it explicitly; no credentials were replaced.');
1716
+ }
1717
+ }
1718
+ return await connectProject(runtime, args);
1719
+ } finally { releases.reverse().forEach(release => release()); }
1720
+ }
1721
+
1722
+ function legacyMcpPresent(bundle) {
1723
+ const config = readConfig(parseEnvBody(bundle.env || ''));
1724
+ const journal = parseConnectionJournal(bundle.journal);
1725
+ let identity;
1726
+ try { identity = bundle.identity === null ? null : JSON.parse(bundle.identity); }
1727
+ catch { throw new Error('Invalid installation identity file; it was left unchanged.'); }
1728
+ return runtimeMatchesConfiguredAdapter('mcp', config.runtimeAdapterId) || identity?.runtime === 'mcp' || journal?.runtime === 'mcp';
1729
+ }
1730
+
1731
+ function migrateLegacyMcp(args) {
1732
+ const inspected = readMcpMigration(process.cwd());
1733
+ if (!inspected.manifest && Object.values(inspected.destination).some(body => body !== null)) {
1734
+ throw new Error('MCP migration destination is already occupied; nothing was overwritten.');
1735
+ }
1736
+ const { bundle } = inspected;
1737
+ if (!legacyMcpPresent(bundle)) throw new Error('No unambiguous legacy MCP installation to migrate; files were left unchanged.');
1738
+ const config = readConfig(parseEnvBody(bundle.env || ''));
1739
+ const installation = parseInstallationIdentity(bundle.identity, 'mcp');
1740
+ const journal = parseConnectionJournal(bundle.journal);
1741
+ if (bundle.env !== null && (!runtimeMatchesConfiguredAdapter('mcp', config.runtimeAdapterId) || config.agentId === 'osuite-cli')) {
1742
+ throw new Error('Legacy MCP migration conflicts with an ambiguous or different live runtime; files were left unchanged.');
1743
+ }
1744
+ const baseUrl = normalizedBaseUrl(args['base-url'] || config.baseUrl || journal?.base_url);
1745
+ if ((args['base-url'] && config.baseUrl && normalizedBaseUrl(config.baseUrl) !== baseUrl)
1746
+ || (args['agent-id'] && args['agent-id'] !== config.agentId)) {
1747
+ throw new Error('MCP migration cannot change the live agent or Studio URL; files were left unchanged.');
1748
+ }
1749
+ if (journal) assertRecoveryState(journal, { runtime: 'mcp', baseUrl, agentId: args['agent-id'], liveEnv: bundle.env, config, installation });
1750
+ migrateMcpInstallation(process.cwd(), inspected);
1751
+ write(`MCP migration complete: moved credentials, identity and recovery state to ${MCP_ENV_PATH}.`);
1752
+ write('No enrollment, acknowledgement or server identity change was performed.');
1753
+ write('Update the MCP launcher to read this env path before restarting it or connecting SDK in this project.');
1754
+ write('Run osuite connect mcp to resume a saved handoff or rotate with the same identity. SDK continues to use .osuite/.env.');
1576
1755
  }
1577
1756
 
1578
1757
  async function main() {
@@ -0,0 +1,134 @@
1
+ import path from 'node:path';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { canonicalJson, createApiClient } from '../runtime/protocol.mjs';
4
+ import { resolveRemotePosture } from '../runtime/posture.mjs';
5
+ import { createStateStore } from '../runtime/state.mjs';
6
+ import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
7
+ import { matchesStoredAction, reject } from './contract.mjs';
8
+
9
+ export function createStudioAuthority(config, journalPath) {
10
+ const responseLimits = { maxResponseBytes: 1048576 };
11
+ const baseApi = createApiClient(config, responseLimits);
12
+ const store = createStateStore({ ...config, stateDir: path.join(path.dirname(journalPath), 'posture') });
13
+
14
+ async function current(aborted) {
15
+ let remote;
16
+ const deadline = performance.now() + 2000;
17
+ for (let attempt = 0; attempt < 6; attempt++) {
18
+ if (aborted()) reject('ABORTED');
19
+ let readStatus = null;
20
+ remote = await resolveRemotePosture(config, { store, api: { async request(method, endpoint, ...args) {
21
+ const response = await baseApi.request(method, endpoint, ...args);
22
+ if (method === 'GET') readStatus = response.status;
23
+ return response;
24
+ } } });
25
+ if (remote.source === 'remote' || readStatus !== 200 || attempt === 5 || performance.now() >= deadline) break;
26
+ // A concurrent cache writer can supersede a valid response or hold its
27
+ // short lock. Reread current configuration, never replay an action POST.
28
+ await delay(10 * (attempt + 1));
29
+ }
30
+ const pinned = config.ruleRollout, actual = remote.ruleRollout;
31
+ const preservesConfiguredFloor = !pinned?.enabled || (actual?.enabled === true
32
+ && canonicalJson(actual.scope) === canonicalJson(pinned.scope)
33
+ && actual.credential_id === pinned.credential_id
34
+ && actual.connection_generation >= pinned.connection_generation && actual.version >= pinned.version
35
+ && (actual.version !== pinned.version || canonicalJson(actual) === canonicalJson(pinned)));
36
+ if (!remote.available || remote.blocked || remote.source !== 'remote'
37
+ || !preservesConfiguredFloor
38
+ || !['enforce', 'strict'].includes(remote.posture.mode)
39
+ || remote.posture.require_assumption_capture !== false
40
+ || remote.posture.require_signature !== true || remote.posture.on_guard_unavailable !== 'block') {
41
+ reject('CURRENT_AUTHORITY_UNAVAILABLE');
42
+ }
43
+ const effective = { ...config, mode: remote.posture.mode, guardFailureMode: 'block', signatureMode: 'required',
44
+ approvalWaitMs: 0, ruleRollout: remote.ruleRollout };
45
+ return { api: createApiClient(effective, responseLimits), effective };
46
+ }
47
+
48
+ async function read(record) {
49
+ const response = await baseApi.request('GET', `/api/actions/${encodeURIComponent(record.actionId)}`);
50
+ if (!response.ok) return { available: false, status: response.status };
51
+ if (!matchesStoredAction(response.body, record, config)) return { available: false, status: response.status, mismatch: true };
52
+ return { available: true, body: response.body, action: response.body.action || response.body };
53
+ }
54
+
55
+ async function admit(invocation, journal, owner, aborted) {
56
+ const record = journal.get(invocation.record.scope, invocation.record.operationId);
57
+ const phase = record.state === 'held' ? 'redeeming' : 'requesting';
58
+ const { api, effective } = await current(aborted);
59
+ if (aborted()) reject('ABORTED');
60
+ const session = await api.request('POST', '/api/runtime-sessions', {
61
+ runtime_session_id: record.sessionId, agent_id: config.agentId, runtime_adapter_id: config.runtimeId,
62
+ runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper', client_name: 'osuite/governed-tools',
63
+ governance_posture: effective.mode, signature_mode: 'required', status: 'active',
64
+ });
65
+ const actualSession = session.body?.session || session.body?.runtime_session;
66
+ if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
67
+ || actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
68
+ || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE');
69
+ let claimed = false, receivedAt = null;
70
+ const claim = () => {
71
+ if (claimed) reject('OUTCOME_UNKNOWN');
72
+ if (aborted()) reject('ABORTED');
73
+ if (!journal.claim(record.scope, record.operationId, [record.state], phase, owner)) reject('OPERATION_BUSY');
74
+ claimed = true;
75
+ };
76
+ const settle = (state, patch = {}) => journal.settle(record.scope, record.operationId, owner, phase, state, patch);
77
+ try {
78
+ const result = await admitAction(invocation.context, {
79
+ config: effective,
80
+ api: { async request(method, endpoint, body, options) {
81
+ if (aborted()) reject('ABORTED');
82
+ if (method === 'POST' && endpoint === '/api/actions') claim();
83
+ const response = await api.request(method, endpoint, body, options);
84
+ if (method === 'POST' && endpoint === '/api/actions') {
85
+ receivedAt = performance.now();
86
+ if (!response.ok || !matchesStoredAction(response.body, record, config)
87
+ || !cavaFingerprint(response.body)) {
88
+ settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
89
+ reject('OUTCOME_UNKNOWN');
90
+ }
91
+ }
92
+ return response;
93
+ } },
94
+ beforeRelease: async payload => {
95
+ if (aborted() || !matchesStoredAction(payload, record, config)) return false;
96
+ // A held operation must redeem its original one-use grant, even when
97
+ // a current guard decision has become less restrictive meanwhile.
98
+ return phase !== 'redeeming' || (Boolean(record.fingerprint) && actionAdmission(payload, 'require_approval', invocation.context,
99
+ { actionId: record.actionId, fingerprint: record.fingerprint }).authorized);
100
+ },
101
+ });
102
+ if (result.authorized) return { phase, receivedAt, response: result.response };
103
+ if (result.reason === 'policy_block') {
104
+ if (!claimed) claim();
105
+ settle('denied'); reject('POLICY_DENIED');
106
+ }
107
+ if (result.decision === 'require_approval' && result.response?.action?.status === 'pending_approval') {
108
+ if (!settle('held', { fingerprint: cavaFingerprint(result.response) })) reject('OUTCOME_UNKNOWN');
109
+ return null;
110
+ }
111
+ if (claimed) settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
112
+ reject(claimed ? 'OUTCOME_UNKNOWN' : 'CURRENT_AUTHORITY_UNAVAILABLE');
113
+ } catch (error) {
114
+ if (claimed) settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
115
+ throw error;
116
+ }
117
+ }
118
+
119
+ async function report(record, state, resultDigest) {
120
+ const response = await baseApi.request('PATCH', `/api/actions/${encodeURIComponent(record.actionId)}`, {
121
+ status: state === 'completed' ? 'completed' : 'failed',
122
+ timestamp_end: new Date().toISOString(),
123
+ output_summary: JSON.stringify({ schema_version: 'osuite.native_tool_observation.v1',
124
+ observation: state === 'completed' ? 'native_return' : 'outcome_unknown',
125
+ result_digest: resultDigest, result_retained: false, independent_resource_verification: false }),
126
+ ...(state === 'uncertain' ? { error_message: 'Native call outcome is uncertain; no automatic resend.' } : {}),
127
+ });
128
+ return response.ok && matchesStoredAction(response.body, record, config)
129
+ && response.body.action?.status === (state === 'completed' ? 'completed' : 'failed')
130
+ && typeof response.body.action?.timestamp_end === 'string';
131
+ }
132
+
133
+ return { admit, read, report };
134
+ }