@commonlyai/cli 0.1.320 → 0.1.322

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.320",
3
+ "version": "0.1.322",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -25,7 +25,8 @@ import {
25
25
  } from '../lib/daemon-supervisor.js';
26
26
  import { loadAgentToken, saveAgentToken } from './agent.js';
27
27
  import { getLastTurn } from '../lib/session-store.js';
28
- import { getAdapter, providerKeyEnvNames } from '../lib/adapters/index.js';
28
+ import { getAdapter, providerKeyEnvNames, seatProviderKeyEnv } from '../lib/adapters/index.js';
29
+ import { runLoginStatus, signedOutAdapters, signedOutHint } from '../lib/adapter-login.js';
29
30
  import {
30
31
  installDaemonService,
31
32
  installSummary,
@@ -34,7 +35,6 @@ import {
34
35
  stopDaemonService,
35
36
  restartDaemonService,
36
37
  daemonLogPath,
37
- missingProviderKeys,
38
38
  servicePaths,
39
39
  } from '../lib/daemon-service.js';
40
40
  import { daemonLogsDir, daemonSeatLogPath, readLogTail } from '../lib/daemon-logs.js';
@@ -51,6 +51,7 @@ import {
51
51
  } from '../lib/daemon-agent-states.js';
52
52
  import { installedCliVersion, startUpdateNotice, UPDATE_CHECK_OPT_OUT_ENV } from '../lib/update-check.js';
53
53
  import { machineHostReport } from '../lib/machine-host.js';
54
+ import { orchestrateDaemonSetup } from '../lib/stable-install.js';
54
55
 
55
56
  // One supervised seat, as `commonly daemon status --verbose` names it. Two of these
56
57
  // fields are worth reading closely: the seat's `instanceId` (the identity the
@@ -265,6 +266,20 @@ export const daemonStatusErrorMessage = (error) => (isRevokedDaemonKey(error)
265
266
  ? 'This computer is no longer registered. Run: commonly daemon register'
266
267
  : `Daemon status failed: ${error.message}`);
267
268
 
269
+ // `daemon setup` on a computer that is already registered for this instance
270
+ // skips login and register (it would stop at "already registered"). Only a
271
+ // stored key the server still accepts counts; a revoked or missing one goes
272
+ // through register, which replaces it.
273
+ export const setupFindsRegistration = async ({
274
+ instance, load = loadDaemonRecord, state = storedDaemonState, clientFor = createClient,
275
+ }) => {
276
+ const record = load();
277
+ if (!record || !instance) return false;
278
+ if (String(record.instanceUrl || '').replace(/\/+$/, '') !== instance) return false;
279
+ const client = clientFor({ instance: record.instanceUrl, token: record.daemonToken });
280
+ return (await state(client, record)) === 'active';
281
+ };
282
+
268
283
  // Keep the old record until a new registration is securely persisted. A
269
284
  // network failure or a still-live daemon key must never silently mint another.
270
285
  export const allowRevokedDaemonReplacement = async ({ existing, client }) => {
@@ -348,6 +363,7 @@ The daemon token is scoped to this machine and stored in a 0600 file under
348
363
  ~/.commonly/daemon/. It is never shown again after registration.
349
364
 
350
365
  Examples:
366
+ $ commonly daemon setup # install, log in, register, and start — one step
351
367
  $ commonly daemon register --name "Sam's MacBook"
352
368
  $ commonly daemon heartbeat
353
369
  $ commonly daemon status --verbose
@@ -356,6 +372,44 @@ Examples:
356
372
  $ commonly daemon unregister
357
373
  `);
358
374
 
375
+ daemon
376
+ .command('setup')
377
+ .description('From a fresh computer in one step: install the CLI under your home (no sudo, no global install), log in, register this computer, and start the daemon')
378
+ .option('--instance <url-or-key>', 'Target Commonly instance')
379
+ .option(UNSANDBOXED_FLAG, 'Native Windows only: the agents this daemon runs have no sandbox (see `commonly daemon install`). Forwarded to the install step.')
380
+ .action(async (opts) => {
381
+ try {
382
+ const instanceUrl = resolveInstanceUrl(opts.instance);
383
+ await orchestrateDaemonSetup({
384
+ version: installedCliVersion(),
385
+ instanceUrl,
386
+ unsandboxed: Boolean(opts.unsandboxed),
387
+ alreadyRegistered: (instance) => setupFindsRegistration({ instance }),
388
+ log: (line) => console.log(line),
389
+ // Run the stable CLI once with the user's terminal attached, so login
390
+ // device-auth and any prompts work; reject on a non-zero exit so a
391
+ // failed step stops the chain before the next one.
392
+ runCli: (entry, args) => new Promise((resolve, reject) => {
393
+ const child = spawn(process.execPath, [entry, ...args], { stdio: 'inherit', env: process.env });
394
+ child.on('error', reject);
395
+ child.on('close', (code) => (code === 0
396
+ ? resolve()
397
+ : reject(new Error(`\`commonly ${args.join(' ')}\` exited with code ${code}`))));
398
+ }),
399
+ });
400
+ // Growth's F370 walk: setup said all was well, and the first @mention
401
+ // then failed with "claude exited 1: Not logged in".
402
+ const signedOut = await signedOutAdapters({
403
+ detect: (name) => getAdapter(name)?.detect(),
404
+ runStatus: runLoginStatus,
405
+ });
406
+ for (const name of signedOut) console.log(`Note: ${signedOutHint(name)}.`);
407
+ } catch (error) {
408
+ console.error(`Daemon setup failed: ${error.message}`);
409
+ process.exitCode = 1;
410
+ }
411
+ });
412
+
359
413
  daemon
360
414
  .command('register')
361
415
  .description('Register this machine and securely store its daemon credential')
@@ -605,19 +659,25 @@ Examples:
605
659
  chmodSync(logsDir, 0o700);
606
660
  const stampLog = (line) => console.log(`${new Date().toISOString()} ${line}`);
607
661
 
608
- // TASK-049: fail loudly at BIND, once, naming the variable.
662
+ // TASK-049: fail loudly, once, naming the variable.
609
663
  //
610
664
  // A service-started daemon inherits a clean environment, so a provider
611
- // key that lives only in the operator's shell is absent here; every pi
612
- // seat then dies at adapter start with `COMMONLY_LITELLM_KEY is not set`
613
- // and the operator sees crash loops with no cause at daemon level. One
614
- // line at startup answers the question the log would otherwise take a
615
- // seat autopsy to answer. Not fatal: the daemon's other seats are
616
- // unaffected, and refusing to start would turn one missing key into a
617
- // whole-machine outage.
618
- for (const name of missingProviderKeys({ names: providerKeyEnvNames() })) {
619
- stampLog(`WARNING: ${name} is not set in this environment — a seat that relies on it will fail to start (one with its own provider.keyFile won't). Export it and re-run: commonly daemon install (docs/agents/daemon-service-environment.md)`);
620
- }
665
+ // key that lives only in the operator's shell is absent here; a pi seat
666
+ // then dies at adapter start with `COMMONLY_LITELLM_KEY is not set` and
667
+ // the operator sees crash loops with no cause at daemon level. The
668
+ // warning names the seat that needs the key, when that seat starts:
669
+ // at daemon start it went to every BYO user, who needs none of them
670
+ // (Growth's F370 walk). Not fatal: the daemon's other seats are
671
+ // unaffected.
672
+ const warnedKeys = new Set();
673
+ const warnMissingSeatKey = (agentName) => {
674
+ let saved = null;
675
+ try { saved = loadAgentToken(agentName); } catch { return; }
676
+ const name = seatProviderKeyEnv({ adapter: saved?.adapter, environment: saved?.environment });
677
+ if (!name || process.env[name] || warnedKeys.has(`${agentName}:${name}`)) return;
678
+ warnedKeys.add(`${agentName}:${name}`);
679
+ stampLog(`WARNING: [${agentName}] needs ${name}, which is not set in this environment, so it will fail to start (a provider.keyFile avoids this); export it and re-run: commonly daemon install (docs/agents/daemon-service-environment.md)`);
680
+ };
621
681
  // TASK-660: the daemon outlives many publishes, so say once at start-up
622
682
  // when it is stale. Not awaited: supervision never waits on the registry.
623
683
  startUpdateNotice({ installedVersion: installedCliVersion(), log: stampLog });
@@ -656,6 +716,7 @@ Examples:
656
716
  // ordinary `commonly agent run <name>` — the daemon is its
657
717
  // supervisor, never its replacement (D6).
658
718
  spawnChild: (agentName) => {
719
+ warnMissingSeatKey(agentName);
659
720
  const seatLog = daemonSeatLogPath(agentName);
660
721
  const out = openSync(seatLog, 'a', 0o600);
661
722
  chmodSync(seatLog, 0o600);
@@ -11,6 +11,7 @@ import { getToken, resolveInstance, resolveInstanceUrl } from '../lib/config.js'
11
11
  import { loadDaemonRecord } from '../lib/daemon-store.js';
12
12
  import { servicePaths } from '../lib/daemon-service.js';
13
13
  import { getAdapter } from '../lib/adapters/index.js';
14
+ import { runLoginStatus, signedOutAdapters } from '../lib/adapter-login.js';
14
15
  import { detectSeatbelt } from '../lib/sandbox/seatbelt.js';
15
16
  import { daemonStatusErrorMessage, getDaemonMachineStatus } from './daemon.js';
16
17
  import { listLocalAgents, listUnreadableAgentTokens } from './agent.js';
@@ -109,6 +110,10 @@ export const hostDoctorDeps = ({ instance: instanceArg = null } = {}) => ({
109
110
  describeError: daemonStatusErrorMessage,
110
111
  now: Date.now(),
111
112
  },
113
+ adapterLogin: () => signedOutAdapters({
114
+ detect: (name) => getAdapter(name)?.detect(),
115
+ runStatus: runLoginStatus,
116
+ }),
112
117
  macos: {
113
118
  platform: process.platform,
114
119
  detectSeatbelt,
@@ -0,0 +1,63 @@
1
+ import { spawn } from 'child_process';
2
+
3
+ // Whether each installed CLI adapter is signed in, by the exit code of its own
4
+ // status command. A stranger on a fresh computer otherwise learns it from a
5
+ // failed @mention ("claude exited 1: Not logged in"), after setup said all was
6
+ // well (Growth's F370 hand walk). Only the exit code is read: the commands'
7
+ // output, which names the account, is never captured or printed.
8
+ //
9
+ // Both commands exit 1 when signed out (checked 2026-11-10 under an empty HOME:
10
+ // `claude auth status --json`, `codex login status`). opencode is left out: its
11
+ // `auth list` was not checked, and a guessed probe would cry wolf.
12
+ export const LOGIN_STATUS_ARGS = {
13
+ claude: ['auth', 'status', '--json'],
14
+ codex: ['login', 'status'],
15
+ };
16
+
17
+ // Credentials a seat runs on without a CLI login, so the probe is skipped.
18
+ // codex's are the ones codexAuthKind and the proxy route accept (adapters/
19
+ // codex.js), even though `codex login status` exits 1 with only a key set.
20
+ const KEY_ENV = {
21
+ claude: ['ANTHROPIC_API_KEY'],
22
+ codex: ['OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_ACCESS_TOKEN'],
23
+ };
24
+ const envSet = (env, name) => typeof env[name] === 'string' && env[name].trim() !== '';
25
+
26
+ // Both CLIs exit exactly 1 when signed out. Any other non-zero code (2 for an
27
+ // unknown subcommand on an old CLI) is no verdict, not "signed out".
28
+ const SIGNED_OUT_EXIT = 1;
29
+
30
+ export const signedOutHint = (name) => `${name} is installed but not signed in; run \`${name}\` once to log in before adding an agent`;
31
+
32
+ /**
33
+ * The installed adapters that report signed out. `detect(name)` resolves truthy
34
+ * when the CLI is installed; `runStatus(name, args)` resolves its exit code, or
35
+ * null when it could not be run (timeout, spawn error), which is not a verdict.
36
+ */
37
+ export const signedOutAdapters = async ({ detect, runStatus, env = process.env, names = Object.keys(LOGIN_STATUS_ARGS) }) => {
38
+ const out = [];
39
+ for (const name of names) {
40
+ if (!LOGIN_STATUS_ARGS[name] || (KEY_ENV[name] || []).some((key) => envSet(env, key))) continue;
41
+ let installed = false;
42
+ try { installed = Boolean(await detect(name)); } catch { /* not installed */ }
43
+ if (!installed) continue;
44
+ const code = await runStatus(name, LOGIN_STATUS_ARGS[name]).catch(() => null);
45
+ if (code === SIGNED_OUT_EXIT) out.push(name);
46
+ }
47
+ return out;
48
+ };
49
+
50
+ // The exit code of `<name> <args>`, with every stream discarded. null when it
51
+ // cannot run or takes longer than `timeoutMs` (a CLI that opens a prompt).
52
+ export const runLoginStatus = (name, args, { timeoutMs = 10_000, spawnFn = spawn } = {}) => new Promise((done) => {
53
+ let child;
54
+ try {
55
+ child = spawnFn(name, args, { stdio: 'ignore', windowsHide: true, shell: process.platform === 'win32' });
56
+ } catch {
57
+ done(null);
58
+ return;
59
+ }
60
+ const timer = setTimeout(() => { child.kill(); done(null); }, timeoutMs);
61
+ child.on('error', () => { clearTimeout(timer); done(null); });
62
+ child.on('exit', (code) => { clearTimeout(timer); done(typeof code === 'number' ? code : null); });
63
+ });
@@ -51,3 +51,18 @@ export const getAdapter = (name) => ADAPTERS[name] || null;
51
51
  export const providerKeyEnvNames = (adapters = ADAPTERS) => [...new Set(
52
52
  Object.values(adapters).map((adapter) => adapter.providerKeyEnv).filter(Boolean),
53
53
  )];
54
+
55
+ /**
56
+ * The provider key ONE seat reads from the environment, or null when it reads
57
+ * none: its adapter signs in through its own CLI (claude, codex), or its
58
+ * provider block names a keyFile. The daemon warns per seat with this, so a
59
+ * BYO computer running only claude never hears about keys it has no use for
60
+ * (Growth's F370 walk).
61
+ */
62
+ export const seatProviderKeyEnv = ({ adapter, environment, adapters = ADAPTERS } = {}) => {
63
+ const declared = adapters[adapter]?.providerKeyEnv;
64
+ if (!declared) return null;
65
+ const provider = environment?.provider;
66
+ if (provider?.keyFile) return null;
67
+ return provider?.apiKeyEnv || declared;
68
+ };
package/src/lib/doctor.js CHANGED
@@ -13,7 +13,9 @@
13
13
  * runs `security`, so it cannot prompt, unlock or read a secret.
14
14
  */
15
15
  import { delimiter, join } from 'node:path';
16
+ import { DAEMON_SETUP_LINE, runsFromStableInstall } from './stable-install.js';
16
17
  import { parseVersion, versionOlderThan } from './mcp-server-version.js';
18
+ import { signedOutHint } from './adapter-login.js';
17
19
 
18
20
  export const PASS = 'pass';
19
21
  export const FAIL = 'fail';
@@ -57,9 +59,10 @@ export const findOnPath = ({ command, pathValue, platform, isExecutable }) => {
57
59
 
58
60
  // (b) Which `commonly` a shell runs, and its version.
59
61
  export const checkInstall = ({
60
- pathValue, platform, isExecutable, runVersion, runningVersion,
62
+ pathValue, platform, isExecutable, runVersion, runningVersion, fromSetup = runsFromStableInstall(),
61
63
  }) => {
62
- const fix = 'npm install -g @commonlyai/cli';
64
+ // A `daemon setup` copy is updated by running setup again, never a global install.
65
+ const fix = fromSetup ? DAEMON_SETUP_LINE : 'npm install -g @commonlyai/cli';
63
66
  const found = findOnPath({ command: 'commonly', pathValue, platform, isExecutable });
64
67
  if (!found.length) return result('install', FAIL, 'no `commonly` on PATH', fix);
65
68
  const [binary] = found;
@@ -232,6 +235,20 @@ export const checkMacClaude = ({
232
235
  return result('macos-claude', PASS, 'Seatbelt runs, the login keychain and /usr/bin/security are present');
233
236
  };
234
237
 
238
+ // (g) Each installed CLI adapter's own sign-in (adapter-login.js). A fail only
239
+ // when an agent here uses the signed-out one; otherwise the line still says it,
240
+ // since the next agent added may pick that adapter.
241
+ export const checkAdapterLogin = async ({ agents = [], probe }) => {
242
+ if (!probe) return result('adapter-login', SKIP, 'no login probe on this host');
243
+ const signedOut = await probe();
244
+ if (!signedOut.length) return result('adapter-login', PASS, 'every installed claude or codex is signed in');
245
+ const detail = signedOut.map(signedOutHint).join('; ');
246
+ const used = signedOut.filter((name) => agents.some((agent) => agent?.adapter === name));
247
+ return used.length
248
+ ? result('adapter-login', FAIL, detail, `run ${used.map((name) => `\`${name}\``).join(' and ')} once to log in`)
249
+ : result('adapter-login', PASS, detail);
250
+ };
251
+
235
252
  /** Every check, in the order the lines print. */
236
253
  export const runDoctor = async (deps) => {
237
254
  // An unreadable tokens dir is one fail line, not a doctor that prints nothing.
@@ -257,6 +274,7 @@ export const runDoctor = async (deps) => {
257
274
  : [
258
275
  ...(await checkAdapters({ agents, getAdapter: deps.getAdapter, unreadable })),
259
276
  checkMacClaude({ ...deps.macos, agents }),
277
+ await checkAdapterLogin({ agents, probe: deps.adapterLogin }),
260
278
  ]),
261
279
  ];
262
280
  };
@@ -0,0 +1,164 @@
1
+ /**
2
+ * F370 (ADR-026): a stable, user-owned install of @commonlyai/cli, so the
3
+ * daemon-first one-paste works from `npx` with no global install.
4
+ *
5
+ * Why this exists. `commonly daemon install` pins the launchd/systemd/schtasks
6
+ * service to the EXACT interpreter + CLI entry that ran it (daemon-service.js,
7
+ * resolved at install time). Run from the npx cache (`~/.npm/_npx/<hash>`),
8
+ * that entry is shared across every npx run and evictable — `npm cache clean`
9
+ * or ordinary reclamation deletes it, and the daemon then fails to start at the
10
+ * next boot with nothing on screen to say why. `npm i -g` keeps a stable path
11
+ * but is EACCES on a stock-Node Mac (the nodejs.org .pkg, no version manager)
12
+ * and needs sudo — the exact wall that cost a first-time user an hour.
13
+ *
14
+ * So `daemon setup` installs the CLI UNDER $HOME — no sudo, no EACCES, no npx
15
+ * cache — and runs `daemon install` AS that stable copy, which pins the service
16
+ * there. The daemon then spawns its seats with its own argv (daemon.js `run`),
17
+ * so the seats are pinned to the same stable CLI by construction.
18
+ *
19
+ * Side effects are injected so the install decision and the setup sequence are
20
+ * unit-testable without touching npm or the network.
21
+ */
22
+ import { spawn } from 'child_process';
23
+ import { existsSync, mkdirSync, readFileSync } from 'fs';
24
+ import { homedir } from 'os';
25
+ import { join, sep } from 'path';
26
+ import { resolveLaunch } from './windows-command.js';
27
+
28
+ export const CLI_PACKAGE = '@commonlyai/cli';
29
+
30
+ // The daemon's adapters (claude, codex) need a current Node; below this the
31
+ // setup fails later with a cryptic error, so it is named up front instead.
32
+ export const MIN_NODE_MAJOR = 22;
33
+
34
+ // One stable copy, one version at a time. `daemon setup` keeps it at the
35
+ // version that invoked it, so what runs resident is what the user installed.
36
+ export const stableCliDir = (home = homedir()) => join(home, '.commonly', 'cli');
37
+ /** The one line that sets up or updates a computer, for advice the CLI prints. */
38
+ export const DAEMON_SETUP_LINE = `npx -y ${CLI_PACKAGE}@latest daemon setup`;
39
+
40
+ /** True when this process runs the copy `daemon setup` installed under $HOME. */
41
+ export const runsFromStableInstall = (entry = process.argv[1], home = homedir()) => (
42
+ // The folder plus a separator, so a sibling such as ~/.commonly/cli-old never matches.
43
+ Boolean(entry) && String(entry).startsWith(`${stableCliDir(home)}${sep}`)
44
+ );
45
+
46
+ export const stableCliEntry = (home = homedir()) => (
47
+ join(stableCliDir(home), 'node_modules', CLI_PACKAGE, 'src', 'index.js')
48
+ );
49
+
50
+ /** The version installed at the stable path, or null when it is not there. */
51
+ export const stableInstalledVersion = (home = homedir(), { readFile = readFileSync, exists = existsSync } = {}) => {
52
+ const manifest = join(stableCliDir(home), 'node_modules', CLI_PACKAGE, 'package.json');
53
+ if (!exists(manifest)) return null;
54
+ try {
55
+ return JSON.parse(readFile(manifest, 'utf8')).version || null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ };
60
+
61
+ /** A message when this Node is too old for the daemon, or null when it is fine. */
62
+ export const nodeTooOld = (version = process.version, min = MIN_NODE_MAJOR) => {
63
+ const major = Number.parseInt(String(version).replace(/^v/, '').split('.')[0], 10);
64
+ if (!Number.isFinite(major) || major >= min) return null;
65
+ return `Node ${version} is too old for the Commonly daemon, which needs Node ${min} or newer. `
66
+ + 'Install the current Node from nodejs.org, or with a version manager such as nvm, then run this again.';
67
+ };
68
+
69
+ // Spawn one `npm` with the Windows-safe launcher the adapters use (npm is
70
+ // npm.cmd there, which Node cannot spawn without a shell). Inherits stdio so
71
+ // the one-time install is visible; rejects on a non-zero exit.
72
+ const runNpm = (args, { cwd, stdio = 'inherit', spawnImpl = spawn, resolution } = {}) => new Promise((resolve, reject) => {
73
+ let launch;
74
+ try {
75
+ launch = resolveLaunch('npm', args, { cwd, ...resolution });
76
+ } catch (error) {
77
+ reject(error);
78
+ return;
79
+ }
80
+ const child = spawnImpl(launch.command, launch.args, { cwd, stdio, env: process.env });
81
+ child.on('error', reject);
82
+ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`npm ${args[0] || ''} exited with code ${code}`))));
83
+ });
84
+
85
+ /**
86
+ * Ensure @commonlyai/cli@<version> is installed under $HOME and return the
87
+ * stable CLI entry to pin the daemon to. Idempotent: a stable copy already at
88
+ * <version> is left as is.
89
+ */
90
+ export const ensureStableCliInstall = async ({
91
+ version,
92
+ home = homedir(),
93
+ mkdir = (dir) => mkdirSync(dir, { recursive: true }),
94
+ installedVersion = stableInstalledVersion,
95
+ runInstall = runNpm,
96
+ log = () => {},
97
+ } = {}) => {
98
+ if (!version) throw new Error('ensureStableCliInstall needs the version to pin');
99
+ const dir = stableCliDir(home);
100
+ const entry = stableCliEntry(home);
101
+ if (installedVersion(home) === version) {
102
+ return { entry, dir, version, installed: false };
103
+ }
104
+ mkdir(dir);
105
+ log(`Installing ${CLI_PACKAGE}@${version} under ${dir} (no global install, no sudo)…`);
106
+ // --prefix keeps it a local install under $HOME; the quiet flags keep the
107
+ // one-time setup output readable.
108
+ await runInstall(['install', '--prefix', dir, '--no-audit', '--no-fund', `${CLI_PACKAGE}@${version}`], { cwd: dir });
109
+ return { entry, dir, version, installed: true };
110
+ };
111
+
112
+ /**
113
+ * The daemon-first one-paste: a stable install, then login → register → install
114
+ * run AS the stable CLI so the service is pinned there (and the seats with it).
115
+ * `runCli(entry, args)` runs the stable CLI once and rejects on a non-zero exit.
116
+ */
117
+ export const orchestrateDaemonSetup = async ({
118
+ version,
119
+ instanceUrl,
120
+ runCli,
121
+ unsandboxed = false,
122
+ // Resolves true when this computer already holds an active registration for
123
+ // the instance. Setup then skips login and register, so re-running it is the
124
+ // way to update the CLI and restart the daemon.
125
+ alreadyRegistered = async () => false,
126
+ platform = process.platform,
127
+ nodeVersion = process.version,
128
+ ensureStable = ensureStableCliInstall,
129
+ home = homedir(),
130
+ log = () => {},
131
+ }) => {
132
+ const tooOld = nodeTooOld(nodeVersion);
133
+ if (tooOld) throw new Error(tooOld);
134
+ if (typeof runCli !== 'function') throw new Error('orchestrateDaemonSetup needs a runCli function');
135
+ const { entry } = await ensureStable({ version, home, log });
136
+ // One spelling for both steps: login saves the URL without trailing slashes,
137
+ // so register must look it up the same way or it can't find the token.
138
+ const instance = instanceUrl ? String(instanceUrl).replace(/\/+$/, '') : '';
139
+ const instanceArgs = instance ? ['--instance', instance] : [];
140
+ // Each step must land before the next: a failed login must not register, a
141
+ // failed register must not install. runCli rejects on a non-zero exit.
142
+ if (await alreadyRegistered(instance)) {
143
+ log('This computer is already registered here, so setup skips login and register, '
144
+ + 'and reinstalls the daemon on the CLI it just installed.');
145
+ } else {
146
+ await runCli(entry, ['login', ...instanceArgs]);
147
+ await runCli(entry, ['daemon', 'register', ...instanceArgs]);
148
+ }
149
+ // --unsandboxed is forwarded to the install step. Without it, native Windows
150
+ // clears the opt-in and the daemon's seats are refused at run time.
151
+ const installArgs = ['daemon', 'install', ...(unsandboxed ? ['--unsandboxed'] : [])];
152
+ try {
153
+ await runCli(entry, installArgs);
154
+ } catch (error) {
155
+ // The computer is registered by now. Name the one step left, in a form the
156
+ // user's shell runs as pasted: PowerShell needs `&` before a quoted program.
157
+ const call = `${platform === 'win32' ? '& ' : ''}"${process.execPath}" "${entry}" ${installArgs.join(' ')}`;
158
+ throw new Error(`${error.message}. This computer is registered; after fixing the error above, `
159
+ + `finish with: ${call} (or run the setup line again)`);
160
+ }
161
+ log('This computer is set up: the daemon is running and starts when you log in. '
162
+ + 'Add an agent to it from the web app and it comes online here.');
163
+ return { entry };
164
+ };
@@ -17,6 +17,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
17
17
  import { homedir } from 'node:os';
18
18
  import { dirname, join } from 'node:path';
19
19
  import { exactVersion, parseVersion } from './mcp-server-version.js';
20
+ import { DAEMON_SETUP_LINE, runsFromStableInstall } from './stable-install.js';
20
21
 
21
22
  export const CLI_PACKAGE = '@commonlyai/cli';
22
23
  export const REGISTRY_LATEST_URL = 'https://registry.npmjs.org/@commonlyai%2fcli/latest';
@@ -46,14 +47,19 @@ export const versionsBehind = (installed, latest) => {
46
47
  };
47
48
 
48
49
  /** The one line to print, or null when there is nothing worth saying. */
49
- export const updateNoticeLine = ({ installed, latest, minBehind = UPDATE_NOTICE_MIN_BEHIND }) => {
50
+ export const updateNoticeLine = ({
51
+ installed, latest, minBehind = UPDATE_NOTICE_MIN_BEHIND, fromSetup = runsFromStableInstall(),
52
+ }) => {
50
53
  const behind = versionsBehind(installed, latest);
51
54
  if (behind === null || behind < minBehind) return null;
52
55
  // Only the parsed triple is printed: the registry's string never reaches the log.
53
56
  const from = exactVersion(installed);
54
57
  const to = exactVersion(latest);
55
58
  const gap = Number.isFinite(behind) ? `${behind} versions behind` : 'behind a newer release line';
56
- return `your CLI is ${gap} (installed ${from}, latest ${to}). Update: npm install -g ${CLI_PACKAGE}@latest`
59
+ // A `daemon setup` copy lives under $HOME and has no global install to update;
60
+ // running setup again updates it and restarts the daemon.
61
+ const update = fromSetup ? DAEMON_SETUP_LINE : `npm install -g ${CLI_PACKAGE}@latest`;
62
+ return `your CLI is ${gap} (installed ${from}, latest ${to}). Update: ${update}`
57
63
  + ` (silence with ${UPDATE_CHECK_OPT_OUT_ENV}=1)`;
58
64
  };
59
65