@commonlyai/cli 0.1.321 → 0.1.323

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.321",
3
+ "version": "0.1.323",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -58,8 +58,8 @@ import {
58
58
  import {
59
59
  buildRecycleBriefing,
60
60
  idleMinutesSince,
61
+ recycleReason,
61
62
  recycleThresholds,
62
- shouldStartFreshSession,
63
63
  } from '../lib/session-recycle.js';
64
64
  import { catchUpBeforeTurn } from '../lib/pod-catch-up.js';
65
65
  import { readLongTerm, syncBack } from '../lib/memory-bridge.js';
@@ -2869,23 +2869,31 @@ export const performRun = ({
2869
2869
  }
2870
2870
  }
2871
2871
  // TASK-440: a cold, large session starts fresh at wake instead of being
2872
- // resumed. The restart note leads the prompt; memory still reaches the
2873
- // fresh session through the adapter's preamble.
2872
+ // resumed, and F392: so does one past the hard ceiling, however recently it
2873
+ // ran. The restart note leads the prompt; memory still reaches the fresh
2874
+ // session through the adapter's preamble.
2874
2875
  const sessionEntry = getSessionEntry(stateKey, eventPodId, { binding: placement.binding });
2875
2876
  let sessionId = getSession(stateKey, eventPodId, { binding: placement.binding });
2876
2877
  let recycleBriefing = null;
2877
- if (sessionId && shouldStartFreshSession({
2878
+ const thresholds = recycleThresholds();
2879
+ const reason = sessionId ? recycleReason({
2878
2880
  lastTurn: sessionEntry?.lastTurn,
2879
2881
  contextTokens: sessionEntry?.contextTokens,
2880
- thresholds: recycleThresholds(),
2881
- })) {
2882
+ thresholds,
2883
+ }) : null;
2884
+ if (reason) {
2882
2885
  recycleBriefing = buildRecycleBriefing({
2883
2886
  agentName,
2887
+ reason,
2884
2888
  idleMinutes: idleMinutesSince(sessionEntry.lastTurn),
2885
2889
  contextTokens: sessionEntry.contextTokens,
2890
+ maxContextTokens: thresholds.maxContextTokens,
2886
2891
  });
2887
- log(`session recycled: idle ${idleMinutesSince(sessionEntry.lastTurn)} min, `
2888
- + `${sessionEntry.contextTokens} context tokens; starting fresh`);
2892
+ log(reason === 'size'
2893
+ ? `session recycled: ${sessionEntry.contextTokens} context tokens, past the `
2894
+ + `${thresholds.maxContextTokens}-token ceiling; starting fresh`
2895
+ : `session recycled: idle ${idleMinutesSince(sessionEntry.lastTurn)} min, `
2896
+ + `${sessionEntry.contextTokens} context tokens; starting fresh`);
2889
2897
  sessionId = null;
2890
2898
  }
2891
2899
  // ADR-005 §Memory bridge: read long_term before spawn, inject via ctx,
@@ -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,9 +35,13 @@ import {
34
35
  stopDaemonService,
35
36
  restartDaemonService,
36
37
  daemonLogPath,
37
- missingProviderKeys,
38
38
  servicePaths,
39
+ serviceOwnerQuery,
40
+ loadedServiceFile,
41
+ foreignServiceRefusal,
42
+ decodeCmdOutput,
39
43
  } from '../lib/daemon-service.js';
44
+
40
45
  import { daemonLogsDir, daemonSeatLogPath, readLogTail } from '../lib/daemon-logs.js';
41
46
  import { watchWindowsLauncher } from '../lib/daemon-service-windows.js';
42
47
  import {
@@ -53,6 +58,11 @@ import { installedCliVersion, startUpdateNotice, UPDATE_CHECK_OPT_OUT_ENV } from
53
58
  import { machineHostReport } from '../lib/machine-host.js';
54
59
  import { orchestrateDaemonSetup } from '../lib/stable-install.js';
55
60
 
61
+ // launchd, systemd and Task Scheduler hold one Commonly daemon per computer
62
+ // account. Install refuses to stop another HOME's; this flag takes it over.
63
+ const REPLACE_FLAG = '--replace';
64
+ const REPLACE_HELP = 'Replace a Commonly daemon that another account (another HOME) runs on this computer account. Without it, install stops and names that daemon.';
65
+
56
66
  // One supervised seat, as `commonly daemon status --verbose` names it. Two of these
57
67
  // fields are worth reading closely: the seat's `instanceId` (the identity the
58
68
  // platform routes by, so a seat attached to the wrong instance is otherwise
@@ -377,6 +387,7 @@ Examples:
377
387
  .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
388
  .option('--instance <url-or-key>', 'Target Commonly instance')
379
389
  .option(UNSANDBOXED_FLAG, 'Native Windows only: the agents this daemon runs have no sandbox (see `commonly daemon install`). Forwarded to the install step.')
390
+ .option(REPLACE_FLAG, REPLACE_HELP)
380
391
  .action(async (opts) => {
381
392
  try {
382
393
  const instanceUrl = resolveInstanceUrl(opts.instance);
@@ -385,6 +396,12 @@ Examples:
385
396
  instanceUrl,
386
397
  unsandboxed: Boolean(opts.unsandboxed),
387
398
  alreadyRegistered: (instance) => setupFindsRegistration({ instance }),
399
+ replace: Boolean(opts.replace),
400
+ foreignDaemon: async () => {
401
+ const target = servicePaths(process.platform, homedir());
402
+ const answer = await readServiceCmd(serviceOwnerQuery(process.platform)).catch(() => '');
403
+ return foreignServiceRefusal({ target, loadedFile: loadedServiceFile(target.kind, answer) });
404
+ },
388
405
  log: (line) => console.log(line),
389
406
  // Run the stable CLI once with the user's terminal attached, so login
390
407
  // device-auth and any prompts work; reject on a non-zero exit so a
@@ -397,6 +414,13 @@ Examples:
397
414
  : reject(new Error(`\`commonly ${args.join(' ')}\` exited with code ${code}`))));
398
415
  }),
399
416
  });
417
+ // Growth's F370 walk: setup said all was well, and the first @mention
418
+ // then failed with "claude exited 1: Not logged in".
419
+ const signedOut = await signedOutAdapters({
420
+ detect: (name) => getAdapter(name)?.detect(),
421
+ runStatus: runLoginStatus,
422
+ });
423
+ for (const name of signedOut) console.log(`Note: ${signedOutHint(name)}.`);
400
424
  } catch (error) {
401
425
  console.error(`Daemon setup failed: ${error.message}`);
402
426
  process.exitCode = 1;
@@ -492,6 +516,17 @@ Examples:
492
516
  });
493
517
 
494
518
  // ── install / uninstall (ADR-026 D1) ──────────────────────────────────────
519
+ // The service manager's answer about the live daemon; rejects when it has none.
520
+ const readServiceCmd = (argv) => new Promise((resolvePromise, rejectPromise) => {
521
+ const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'ignore'] });
522
+ const chunks = [];
523
+ child.stdout.on('data', (chunk) => { chunks.push(chunk); });
524
+ child.on('error', rejectPromise);
525
+ child.on('close', (code) => (code === 0
526
+ ? resolvePromise(decodeCmdOutput(Buffer.concat(chunks)))
527
+ : rejectPromise(new Error(`${argv.join(' ')} exited ${code}`))));
528
+ });
529
+
495
530
  const serviceDeps = () => ({
496
531
  // writeFile is deliberately NOT injected here: daemon-service.js's default
497
532
  // writer sets the 0600 mode at CREATION, and a bare `writeFileSync(file,
@@ -502,6 +537,7 @@ Examples:
502
537
  ensureFile: (path) => { const fd = openSync(path, 'a', 0o600); closeSync(fd); },
503
538
  existsFile: (file) => existsSync(file),
504
539
  removeFile: (file) => rmSync(file),
540
+ readCmd: readServiceCmd,
505
541
  execCmd: (argv) => new Promise((resolvePromise, rejectPromise) => {
506
542
  const child = spawn(argv[0], argv.slice(1), { stdio: 'ignore' });
507
543
  child.on('error', rejectPromise);
@@ -526,6 +562,7 @@ Examples:
526
562
  .command('install')
527
563
  .description('Register the daemon as a login service (launchd, systemd, or a Windows scheduled task); on Linux, also turn on lingering so it starts at boot')
528
564
  .option(UNSANDBOXED_FLAG, 'Native Windows only: the agents this daemon runs have no sandbox, and run with your own access to files and commands. They get no connector grants. Codex can run commands in invite-only pods, where anyone in the pod, including people invited later, can direct it. Install again without it to turn it off.')
565
+ .option(REPLACE_FLAG, REPLACE_HELP)
529
566
  .action(async (opts) => {
530
567
  try {
531
568
  if (opts.unsandboxed) {
@@ -555,6 +592,7 @@ Examples:
555
592
  try {
556
593
  installed = await installDaemonService({
557
594
  ...serviceDeps(),
595
+ replace: Boolean(opts.replace),
558
596
  providerKeyEnvNames: providerKeyEnvNames(),
559
597
  optionalEnvNames: [UPDATE_CHECK_OPT_OUT_ENV],
560
598
  });
@@ -652,19 +690,25 @@ Examples:
652
690
  chmodSync(logsDir, 0o700);
653
691
  const stampLog = (line) => console.log(`${new Date().toISOString()} ${line}`);
654
692
 
655
- // TASK-049: fail loudly at BIND, once, naming the variable.
693
+ // TASK-049: fail loudly, once, naming the variable.
656
694
  //
657
695
  // A service-started daemon inherits a clean environment, so a provider
658
- // key that lives only in the operator's shell is absent here; every pi
659
- // seat then dies at adapter start with `COMMONLY_LITELLM_KEY is not set`
660
- // and the operator sees crash loops with no cause at daemon level. One
661
- // line at startup answers the question the log would otherwise take a
662
- // seat autopsy to answer. Not fatal: the daemon's other seats are
663
- // unaffected, and refusing to start would turn one missing key into a
664
- // whole-machine outage.
665
- for (const name of missingProviderKeys({ names: providerKeyEnvNames() })) {
666
- 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)`);
667
- }
696
+ // key that lives only in the operator's shell is absent here; a pi seat
697
+ // then dies at adapter start with `COMMONLY_LITELLM_KEY is not set` and
698
+ // the operator sees crash loops with no cause at daemon level. The
699
+ // warning names the seat that needs the key, when that seat starts:
700
+ // at daemon start it went to every BYO user, who needs none of them
701
+ // (Growth's F370 walk). Not fatal: the daemon's other seats are
702
+ // unaffected.
703
+ const warnedKeys = new Set();
704
+ const warnMissingSeatKey = (agentName) => {
705
+ let saved = null;
706
+ try { saved = loadAgentToken(agentName); } catch { return; }
707
+ const name = seatProviderKeyEnv({ adapter: saved?.adapter, environment: saved?.environment });
708
+ if (!name || process.env[name] || warnedKeys.has(`${agentName}:${name}`)) return;
709
+ warnedKeys.add(`${agentName}:${name}`);
710
+ 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)`);
711
+ };
668
712
  // TASK-660: the daemon outlives many publishes, so say once at start-up
669
713
  // when it is stale. Not awaited: supervision never waits on the registry.
670
714
  startUpdateNotice({ installedVersion: installedCliVersion(), log: stampLog });
@@ -703,6 +747,7 @@ Examples:
703
747
  // ordinary `commonly agent run <name>` — the daemon is its
704
748
  // supervisor, never its replacement (D6).
705
749
  spawnChild: (agentName) => {
750
+ warnMissingSeatKey(agentName);
706
751
  const seatLog = daemonSeatLogPath(agentName);
707
752
  const out = openSync(seatLog, 'a', 0o600);
708
753
  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
+ };
@@ -12,11 +12,11 @@
12
12
  */
13
13
 
14
14
  import { randomBytes } from 'crypto';
15
- import { existsSync, renameSync, unlinkSync, writeFileSync } from 'fs';
15
+ import { existsSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'fs';
16
16
  import { homedir, userInfo } from 'os';
17
- import { join, dirname, resolve } from 'path';
17
+ import { basename, join, dirname, resolve } from 'path';
18
18
  import {
19
- installWindowsService, uninstallWindowsService, windowsServiceAction, windowsServicePaths,
19
+ WINDOWS_TASK_NAME, installWindowsService, uninstallWindowsService, windowsServiceAction, windowsServicePaths,
20
20
  } from './daemon-service-windows.js';
21
21
 
22
22
  export const LAUNCHD_LABEL = 'me.commonly.daemon';
@@ -249,6 +249,78 @@ const ensureLinger = async ({ username, existsFile, execCmd, warn }) => {
249
249
  // The line the install command ends with. "Survives reboots" is said only when
250
250
  // the service starts at boot: a LaunchAgent, like a systemd user unit without
251
251
  // lingering, starts at login.
252
+ // A launchd label, a systemd user unit and a scheduled-task name are one per OS
253
+ // user, not one per HOME. Without this check a second Commonly account's
254
+ // install on the same computer account unloaded the first account's running
255
+ // daemon and loaded its own under the same name, and nothing said so (Growth's
256
+ // F370 walk). So install first asks the service manager which file the live
257
+ // service came from, and goes ahead only when it is this HOME's own file.
258
+ export const serviceOwnerQuery = (platform = process.platform, uid = process.getuid?.()) => {
259
+ if (platform === 'darwin') return ['launchctl', 'print', `gui/${uid}/${LAUNCHD_LABEL}`];
260
+ if (platform === 'win32') return ['schtasks', '/Query', '/TN', WINDOWS_TASK_NAME, '/XML'];
261
+ return ['systemctl', '--user', 'show', SYSTEMD_UNIT, '-p', 'FragmentPath', '--value'];
262
+ };
263
+
264
+ // schtasks may answer in UTF-16 (BOM or NUL bytes) or in the console's code
265
+ // page; anything that did not decode cleanly is treated as no answer, so a
266
+ // non-ASCII user name never turns into a false "another account".
267
+ export const decodeCmdOutput = (buffer) => {
268
+ const bytes = Buffer.isBuffer(buffer) ? buffer : Buffer.from(String(buffer ?? ''));
269
+ const utf16 = (bytes[0] === 0xff && bytes[1] === 0xfe) || bytes.subarray(0, 64).includes(0);
270
+ return bytes.toString(utf16 ? 'utf16le' : 'utf8').replace(/^\uFEFF/, '');
271
+ };
272
+
273
+ const xmlUnescape = (value) => value
274
+ .replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>')
275
+ .replace(/&amp;/g, '&');
276
+
277
+ // The path in the query's answer, or null when the answer names none.
278
+ export const loadedServiceFile = (kind, stdout = '') => {
279
+ const text = String(stdout).replace(/\0/g, '');
280
+ let found;
281
+ if (kind === 'launchd') found = /^\s*path = (.+)$/m.exec(text)?.[1].trim();
282
+ // schtasks prints the definition it holds, whose action runs this HOME's launcher.
283
+ else if (kind === 'schtasks') found = /-File (?:"|&quot;)(.+?)(?:"|&quot;)/.exec(text)?.[1];
284
+ else found = text.trim();
285
+ if (!found) return null;
286
+ if (kind === 'schtasks') found = xmlUnescape(found);
287
+ return found.includes('\uFFFD') ? null : found;
288
+ };
289
+
290
+ // The same file under another spelling (a symlinked HOME) is not foreign.
291
+ // The file itself may not exist yet, so the nearest folder that does is resolved.
292
+ const canonicalPath = (p, platform) => {
293
+ let dir = resolve(p);
294
+ let rest = '';
295
+ let out = null;
296
+ while (out === null) {
297
+ try {
298
+ out = join(realpathSync(dir), rest);
299
+ } catch {
300
+ const up = dirname(dir);
301
+ if (up === dir) out = resolve(p);
302
+ else { rest = rest ? join(basename(dir), rest) : basename(dir); dir = up; }
303
+ }
304
+ }
305
+ return platform === 'win32' ? out.toLowerCase() : out;
306
+ };
307
+
308
+ export const foreignServiceRefusal = ({ target, loadedFile, platform = process.platform }) => {
309
+ if (!loadedFile) return null;
310
+ const own = target.kind === 'schtasks' ? target.launcher : target.file;
311
+ if (canonicalPath(loadedFile, platform) === canonicalPath(own, platform)) return null;
312
+ const head = `This computer already runs a Commonly daemon for another account (its service file is ${loadedFile}), `
313
+ + 'and installing here would stop it. To see it, run `commonly daemon status` as that account. ';
314
+ // The systemd user manager reads units only from its own account's folder,
315
+ // so a unit written under another HOME is never loaded: --replace can't help,
316
+ // and neither would uninstalling the other one first.
317
+ if (target.kind === 'systemd') {
318
+ return `${head}On Linux one computer account runs one Commonly daemon, from its own home folder. `
319
+ + 'To run another, sign in to this computer as a different user and set it up there.';
320
+ }
321
+ return `${head}To replace it with this one on purpose, run this command again with --replace.`;
322
+ };
323
+
252
324
  export const installSummary = ({ startsAtBoot }) => (startsAtBoot
253
325
  ? 'The daemon now starts at boot and is kept alive, so it survives reboots. Uninstall with: commonly daemon uninstall'
254
326
  : 'The daemon now starts at login and is kept alive. Uninstall with: commonly daemon uninstall');
@@ -277,8 +349,20 @@ export const installDaemonService = async ({
277
349
  lookupUsername = () => userInfo().username,
278
350
  log = () => {},
279
351
  warn = log,
352
+ // argv => stdout; rejects when the service manager has no such service.
353
+ // Absent, the owner check is skipped (callers that only test the writers).
354
+ readCmd,
355
+ uid = process.getuid?.(),
356
+ // Take over a daemon another HOME installed, on purpose. Not on Linux: the
357
+ // user manager loads units only from its own home, so the check still runs.
358
+ replace = false,
280
359
  }) => {
281
360
  const target = servicePaths(platform, home);
361
+ if (readCmd && (!replace || target.kind === 'systemd')) {
362
+ const loadedFile = loadedServiceFile(target.kind, await readCmd(serviceOwnerQuery(platform, uid)).catch(() => ''));
363
+ const refusal = foreignServiceRefusal({ target, loadedFile, platform });
364
+ if (refusal) throw new Error(refusal);
365
+ }
282
366
  mkdirp(dirname(target.file));
283
367
  mkdirp(dirname(daemonLogPath(home)));
284
368
  chmod(dirname(daemonLogPath(home)), 0o700);
package/src/lib/doctor.js CHANGED
@@ -15,6 +15,7 @@
15
15
  import { delimiter, join } from 'node:path';
16
16
  import { DAEMON_SETUP_LINE, runsFromStableInstall } from './stable-install.js';
17
17
  import { parseVersion, versionOlderThan } from './mcp-server-version.js';
18
+ import { signedOutHint } from './adapter-login.js';
18
19
 
19
20
  export const PASS = 'pass';
20
21
  export const FAIL = 'fail';
@@ -234,6 +235,20 @@ export const checkMacClaude = ({
234
235
  return result('macos-claude', PASS, 'Seatbelt runs, the login keychain and /usr/bin/security are present');
235
236
  };
236
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
+
237
252
  /** Every check, in the order the lines print. */
238
253
  export const runDoctor = async (deps) => {
239
254
  // An unreadable tokens dir is one fail line, not a doctor that prints nothing.
@@ -259,6 +274,7 @@ export const runDoctor = async (deps) => {
259
274
  : [
260
275
  ...(await checkAdapters({ agents, getAdapter: deps.getAdapter, unreadable })),
261
276
  checkMacClaude({ ...deps.macos, agents }),
277
+ await checkAdapterLogin({ agents, probe: deps.adapterLogin }),
262
278
  ]),
263
279
  ];
264
280
  };
@@ -7,8 +7,13 @@
7
7
  * enough to matter, start a fresh session instead, seeded with a short
8
8
  * restart note. Otherwise resume exactly as before.
9
9
  *
10
- * Thresholds are per-install: COMMONLY_SESSION_RECYCLE_IDLE_MINUTES and
11
- * COMMONLY_SESSION_RECYCLE_CONTEXT_TOKENS override the defaults below.
10
+ * F392: a seat woken every few minutes is never idle long enough for that
11
+ * rule, so its context grew without bound. Past a hard ceiling it starts fresh
12
+ * whatever the idle time.
13
+ *
14
+ * Thresholds are per-install: COMMONLY_SESSION_RECYCLE_IDLE_MINUTES,
15
+ * COMMONLY_SESSION_RECYCLE_CONTEXT_TOKENS and
16
+ * COMMONLY_SESSION_RECYCLE_MAX_CONTEXT_TOKENS override the defaults below.
12
17
  *
13
18
  * Context size is read from the transcript the child CLI wrote, under the env
14
19
  * the child ran with. Only the claude adapter reports one today; an adapter
@@ -22,6 +27,7 @@ import { homedir } from 'os';
22
27
  export const RECYCLE_DEFAULTS = Object.freeze({
23
28
  idleMinutes: 60,
24
29
  contextTokens: 128000,
30
+ maxContextTokens: 256000,
25
31
  });
26
32
 
27
33
  // Read this many bytes from the end of a transcript. The last assistant
@@ -37,23 +43,28 @@ const positiveNumber = (raw, fallback) => {
37
43
  export const recycleThresholds = (env = process.env) => ({
38
44
  idleMinutes: positiveNumber(env.COMMONLY_SESSION_RECYCLE_IDLE_MINUTES, RECYCLE_DEFAULTS.idleMinutes),
39
45
  contextTokens: positiveNumber(env.COMMONLY_SESSION_RECYCLE_CONTEXT_TOKENS, RECYCLE_DEFAULTS.contextTokens),
46
+ maxContextTokens: positiveNumber(env.COMMONLY_SESSION_RECYCLE_MAX_CONTEXT_TOKENS, RECYCLE_DEFAULTS.maxContextTokens),
40
47
  });
41
48
 
42
- // Pure decision. No evidence (no last turn, no measured context) means resume.
43
- export const shouldStartFreshSession = ({
49
+ // Pure decision: 'cold' (idle long enough AND large), 'size' (past the hard
50
+ // ceiling, however recent), or null to resume. No evidence (no last turn, no
51
+ // measured context) means resume.
52
+ export const recycleReason = ({
44
53
  lastTurn,
45
54
  contextTokens,
46
55
  now = Date.now(),
47
56
  thresholds = RECYCLE_DEFAULTS,
48
57
  }) => {
49
- if (!lastTurn || !Number.isFinite(contextTokens)) return false;
58
+ if (!lastTurn || !Number.isFinite(contextTokens)) return null;
50
59
  const last = Date.parse(lastTurn);
51
- if (!Number.isFinite(last)) return false;
52
- const idleMs = now - last;
53
- return idleMs >= thresholds.idleMinutes * 60_000
54
- && contextTokens >= thresholds.contextTokens;
60
+ if (!Number.isFinite(last)) return null;
61
+ if (now - last >= thresholds.idleMinutes * 60_000 && contextTokens >= thresholds.contextTokens) return 'cold';
62
+ const ceiling = thresholds.maxContextTokens ?? RECYCLE_DEFAULTS.maxContextTokens;
63
+ return contextTokens >= ceiling ? 'size' : null;
55
64
  };
56
65
 
66
+ export const shouldStartFreshSession = (args) => recycleReason(args) !== null;
67
+
57
68
  export const idleMinutesSince = (lastTurn, now = Date.now()) => {
58
69
  const last = Date.parse(lastTurn);
59
70
  return Number.isFinite(last) ? Math.floor((now - last) / 60_000) : null;
@@ -62,10 +73,15 @@ export const idleMinutesSince = (lastTurn, now = Date.now()) => {
62
73
  // The restart note. The memory head and the pod focus are NOT repeated here:
63
74
  // a fresh claude session already receives the full long_term memory through
64
75
  // its preamble, and the pod focus is already in the wake prompt.
65
- export const buildRecycleBriefing = ({ agentName, idleMinutes, contextTokens }) => [
76
+ export const buildRecycleBriefing = ({
77
+ agentName, reason = 'cold', idleMinutes, contextTokens, maxContextTokens = RECYCLE_DEFAULTS.maxContextTokens,
78
+ }) => [
66
79
  '=== Session restart ===',
67
- `This wake starts a fresh session. The previous session was idle ${idleMinutes} min`
68
- + ` with about ${contextTokens} context tokens, so it was not resumed.`,
80
+ reason === 'size'
81
+ ? `This wake starts a fresh session. The previous session had grown to about ${contextTokens}`
82
+ + ` context tokens, past the ${maxContextTokens}-token ceiling, so it was not resumed.`
83
+ : `This wake starts a fresh session. The previous session was idle ${idleMinutes} min`
84
+ + ` with about ${contextTokens} context tokens, so it was not resumed.`,
69
85
  `Role: ${agentName}. Your saved memory and the pod focus follow below.`,
70
86
  ].join('\n');
71
87
 
@@ -123,6 +123,11 @@ export const orchestrateDaemonSetup = async ({
123
123
  // the instance. Setup then skips login and register, so re-running it is the
124
124
  // way to update the CLI and restart the daemon.
125
125
  alreadyRegistered = async () => false,
126
+ // Resolves a refusal when this computer account already runs another HOME's
127
+ // daemon (daemon-service.js foreignServiceRefusal). Checked before login, so
128
+ // a refused setup registers nothing. --replace skips it and is forwarded.
129
+ foreignDaemon = async () => null,
130
+ replace = false,
126
131
  platform = process.platform,
127
132
  nodeVersion = process.version,
128
133
  ensureStable = ensureStableCliInstall,
@@ -132,6 +137,12 @@ export const orchestrateDaemonSetup = async ({
132
137
  const tooOld = nodeTooOld(nodeVersion);
133
138
  if (tooOld) throw new Error(tooOld);
134
139
  if (typeof runCli !== 'function') throw new Error('orchestrateDaemonSetup needs a runCli function');
140
+ // --replace can't take over a Linux daemon (daemon-service.js), so the
141
+ // check runs there either way.
142
+ if (!replace || platform === 'linux') {
143
+ const refusal = await foreignDaemon();
144
+ if (refusal) throw new Error(refusal);
145
+ }
135
146
  const { entry } = await ensureStable({ version, home, log });
136
147
  // One spelling for both steps: login saves the URL without trailing slashes,
137
148
  // so register must look it up the same way or it can't find the token.
@@ -148,7 +159,7 @@ export const orchestrateDaemonSetup = async ({
148
159
  }
149
160
  // --unsandboxed is forwarded to the install step. Without it, native Windows
150
161
  // clears the opt-in and the daemon's seats are refused at run time.
151
- const installArgs = ['daemon', 'install', ...(unsandboxed ? ['--unsandboxed'] : [])];
162
+ const installArgs = ['daemon', 'install', ...(unsandboxed ? ['--unsandboxed'] : []), ...(replace ? ['--replace'] : [])];
152
163
  try {
153
164
  await runCli(entry, installArgs);
154
165
  } catch (error) {