@commonlyai/cli 0.1.322 → 0.1.324

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.322",
3
+ "version": "0.1.324",
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,
@@ -36,7 +36,12 @@ import {
36
36
  restartDaemonService,
37
37
  daemonLogPath,
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
@@ -499,6 +516,17 @@ Examples:
499
516
  });
500
517
 
501
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
+
502
530
  const serviceDeps = () => ({
503
531
  // writeFile is deliberately NOT injected here: daemon-service.js's default
504
532
  // writer sets the 0600 mode at CREATION, and a bare `writeFileSync(file,
@@ -509,6 +537,7 @@ Examples:
509
537
  ensureFile: (path) => { const fd = openSync(path, 'a', 0o600); closeSync(fd); },
510
538
  existsFile: (file) => existsSync(file),
511
539
  removeFile: (file) => rmSync(file),
540
+ readCmd: readServiceCmd,
512
541
  execCmd: (argv) => new Promise((resolvePromise, rejectPromise) => {
513
542
  const child = spawn(argv[0], argv.slice(1), { stdio: 'ignore' });
514
543
  child.on('error', rejectPromise);
@@ -533,6 +562,7 @@ Examples:
533
562
  .command('install')
534
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')
535
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)
536
566
  .action(async (opts) => {
537
567
  try {
538
568
  if (opts.unsandboxed) {
@@ -562,6 +592,7 @@ Examples:
562
592
  try {
563
593
  installed = await installDaemonService({
564
594
  ...serviceDeps(),
595
+ replace: Boolean(opts.replace),
565
596
  providerKeyEnvNames: providerKeyEnvNames(),
566
597
  optionalEnvNames: [UPDATE_CHECK_OPT_OUT_ENV],
567
598
  });
@@ -87,6 +87,7 @@ import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
87
87
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
88
88
  import { startProviderProxy } from '../provider-proxy.js';
89
89
  import { resolveLaunch, resolveMcpCommand, resolveWindowsCommandWithReason } from '../windows-command.js';
90
+ import { codexContextTokens, codexHomeFor } from '../session-recycle.js';
90
91
 
91
92
  // Default timeout for a single codex spawn (exec mode).
92
93
  //
@@ -1316,13 +1317,20 @@ export default {
1316
1317
  // came in with > null. The wrapper persists whichever non-null value
1317
1318
  // we return so subsequent turns hit `codex exec resume <id>`.
1318
1319
  const newSessionId = threadId || ctx.sessionId || null;
1320
+ // F404: what the turn's last request was sent, from the rollout the child
1321
+ // wrote under its own CODEX_HOME. Null keeps resuming.
1322
+ const contextTokens = newSessionId
1323
+ ? (ctx._codexContextTokens || codexContextTokens)({ codexHome: codexHomeFor(childEnv), sessionId: newSessionId })
1324
+ : null;
1319
1325
  // D247: the reply receipt names the model and effort this spawn passed
1320
1326
  // (`--model`, `model_reasoning_effort`); codex's own stream does not
1321
1327
  // restate them.
1322
1328
  const effort = ctx.environment?.effort;
1323
1329
  const stats = { ...(seatModel ? { model: String(seatModel) } : {}),
1324
1330
  ...(typeof effort === 'string' && effort ? { effort } : {}) };
1325
- return { text, newSessionId, ...(Object.keys(stats).length ? { stats } : {}) };
1331
+ return {
1332
+ text, newSessionId, contextTokens, ...(Object.keys(stats).length ? { stats } : {}),
1333
+ };
1326
1334
  } finally {
1327
1335
  try { await providerProxy?.close(); } catch { /* ignore */ }
1328
1336
  try { await rm(dir, { recursive: true, force: true }); } catch { /* ignore */ }
@@ -32,6 +32,7 @@ import { describeMcpCommand } from '../mcp-server-version.js';
32
32
  import { writeCredentialFile } from '../credential-file.js';
33
33
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
34
34
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
35
+ import { promptTokens } from '../session-recycle.js';
35
36
 
36
37
  export const TESTED_DSH_VERSIONS = Object.freeze(['0.2.1-rc.2']);
37
38
  const PROXY_KEY_ENV = 'COMMONLY_DSH_PROXY_KEY';
@@ -269,6 +270,13 @@ const parseEvent = (line, state) => {
269
270
  try { event = JSON.parse(line); } catch { throw new Error('dsh emitted invalid JSON event'); }
270
271
  if (event.type === 'session' && typeof event.sessionId === 'string') state.sessionId = event.sessionId;
271
272
  if (event.type === 'final' && typeof event.text === 'string') state.final = event.text;
273
+ // F404: each step_end carries that request's usage, input apart from the cache.
274
+ if (event.type === 'status' && event.phase === 'step_end' && event.usage && typeof event.usage === 'object') {
275
+ const tokens = promptTokens({
276
+ input: event.usage.inputTokens, cacheRead: event.usage.cacheReadTokens, cacheWrite: event.usage.cacheWriteTokens,
277
+ });
278
+ if (tokens !== null) state.contextTokens = tokens;
279
+ }
272
280
  if (event.type === 'error') state.error = String(event.message || event.error || 'dsh error');
273
281
  if (event.type === 'tool_result'
274
282
  && /SANDBOX_UNAVAILABLE|sandbox_apply: Operation not permitted/.test(JSON.stringify(event))) {
@@ -281,7 +289,9 @@ export const runDsh = ({
281
289
  }) => new Promise((resolve, reject) => {
282
290
  const proc = spawnInOwnGroup(spawnImpl, binary, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] }, { ownGroup });
283
291
  observeSpawn(proc, onSpawn, controls);
284
- const state = { sessionId: null, final: null, error: null, buffer: '' };
292
+ const state = {
293
+ sessionId: null, final: null, error: null, buffer: '', contextTokens: null,
294
+ };
285
295
  let stderr = '';
286
296
  let timedOut = false;
287
297
  let parseFailure = null;
@@ -326,7 +336,7 @@ export const runDsh = ({
326
336
  || (code !== 0 ? stderr.trim() || `exit ${code}` : null)
327
337
  || (state.final === null ? 'no final event' : null);
328
338
  if (failure) return finish(adapterFailure('dsh', failure, { credentials, exitCode: code, limit: 500 }));
329
- return finish(null, { text: state.final.trim(), newSessionId: state.sessionId });
339
+ return finish(null, { text: state.final.trim(), newSessionId: state.sessionId, contextTokens: state.contextTokens });
330
340
  });
331
341
  });
332
342
 
@@ -72,6 +72,7 @@ import { resolvePublicSandboxMode } from '../sandbox/mode.js';
72
72
  import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
73
73
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
74
74
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
75
+ import { promptTokens } from '../session-recycle.js';
75
76
 
76
77
  const DEFAULT_TIMEOUT_MS = (() => {
77
78
  const fallback = 15 * 60 * 1000;
@@ -544,6 +545,7 @@ export const buildArgs = ({
544
545
  */
545
546
  export const extractReply = (stdout) => {
546
547
  let text = '';
548
+ let usage = null;
547
549
  let sawAssistant = false;
548
550
  let finished = false;
549
551
  let lastStop = null;
@@ -556,6 +558,8 @@ export const extractReply = (stdout) => {
556
558
  if (event?.type === 'message_end' && event.message?.role === 'assistant') {
557
559
  const parts = (event.message.content || []).filter((c) => c?.type === 'text').map((c) => c.text || '');
558
560
  if (parts.length) { text = parts.join('\n').trim(); sawAssistant = true; }
561
+ // F404: the last request's prompt, input counted apart from the cache.
562
+ if (event.message.usage && typeof event.message.usage === 'object') usage = event.message.usage;
559
563
  lastStop = event.message.stopReason;
560
564
  lastError = typeof event.message.errorMessage === 'string' ? event.message.errorMessage : undefined;
561
565
  finished = false;
@@ -564,7 +568,7 @@ export const extractReply = (stdout) => {
564
568
  if (event?.type === 'error') errors.push(String(event.message || event.error || 'error'));
565
569
  }
566
570
  return {
567
- text, sawAssistant, finished, lastStop, lastError, errors,
571
+ text, sawAssistant, finished, lastStop, lastError, errors, contextTokens: usage ? promptTokens(usage) : null,
568
572
  };
569
573
  };
570
574
 
@@ -976,6 +980,8 @@ export default {
976
980
  return {
977
981
  text: reply.text,
978
982
  newSessionId: sessionId,
983
+ // F404: the F392 ceiling and cold rule read this; null keeps resuming.
984
+ contextTokens: reply.contextTokens ?? null,
979
985
  upstream: reply.upstream ?? null,
980
986
  ...(reply.failure ? { failure: reply.failure } : {}),
981
987
  };
@@ -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);
@@ -7,21 +7,30 @@
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.
12
13
  *
13
- * Context size is read from the transcript the child CLI wrote, under the env
14
- * the child ran with. Only the claude adapter reports one today; an adapter
15
- * that reports nothing keeps resuming, as before this module existed.
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.
17
+ *
18
+ * Context size is what the last model request of the turn was sent: claude and
19
+ * codex from the transcript the child CLI wrote, under the env it ran with; pi
20
+ * and dsh from the usage on their own JSON stream (F404). An adapter that
21
+ * reports nothing keeps resuming, as before this module existed.
16
22
  */
17
23
 
18
- import { closeSync, existsSync, fstatSync, openSync, readSync } from 'fs';
24
+ import {
25
+ closeSync, existsSync, fstatSync, openSync, readdirSync, readSync,
26
+ } from 'fs';
19
27
  import { join } from 'path';
20
28
  import { homedir } from 'os';
21
29
 
22
30
  export const RECYCLE_DEFAULTS = Object.freeze({
23
31
  idleMinutes: 60,
24
32
  contextTokens: 128000,
33
+ maxContextTokens: 256000,
25
34
  });
26
35
 
27
36
  // Read this many bytes from the end of a transcript. The last assistant
@@ -37,23 +46,28 @@ const positiveNumber = (raw, fallback) => {
37
46
  export const recycleThresholds = (env = process.env) => ({
38
47
  idleMinutes: positiveNumber(env.COMMONLY_SESSION_RECYCLE_IDLE_MINUTES, RECYCLE_DEFAULTS.idleMinutes),
39
48
  contextTokens: positiveNumber(env.COMMONLY_SESSION_RECYCLE_CONTEXT_TOKENS, RECYCLE_DEFAULTS.contextTokens),
49
+ maxContextTokens: positiveNumber(env.COMMONLY_SESSION_RECYCLE_MAX_CONTEXT_TOKENS, RECYCLE_DEFAULTS.maxContextTokens),
40
50
  });
41
51
 
42
- // Pure decision. No evidence (no last turn, no measured context) means resume.
43
- export const shouldStartFreshSession = ({
52
+ // Pure decision: 'cold' (idle long enough AND large), 'size' (past the hard
53
+ // ceiling, however recent), or null to resume. No evidence (no last turn, no
54
+ // measured context) means resume.
55
+ export const recycleReason = ({
44
56
  lastTurn,
45
57
  contextTokens,
46
58
  now = Date.now(),
47
59
  thresholds = RECYCLE_DEFAULTS,
48
60
  }) => {
49
- if (!lastTurn || !Number.isFinite(contextTokens)) return false;
61
+ if (!lastTurn || !Number.isFinite(contextTokens)) return null;
50
62
  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;
63
+ if (!Number.isFinite(last)) return null;
64
+ if (now - last >= thresholds.idleMinutes * 60_000 && contextTokens >= thresholds.contextTokens) return 'cold';
65
+ const ceiling = thresholds.maxContextTokens ?? RECYCLE_DEFAULTS.maxContextTokens;
66
+ return contextTokens >= ceiling ? 'size' : null;
55
67
  };
56
68
 
69
+ export const shouldStartFreshSession = (args) => recycleReason(args) !== null;
70
+
57
71
  export const idleMinutesSince = (lastTurn, now = Date.now()) => {
58
72
  const last = Date.parse(lastTurn);
59
73
  return Number.isFinite(last) ? Math.floor((now - last) / 60_000) : null;
@@ -62,10 +76,15 @@ export const idleMinutesSince = (lastTurn, now = Date.now()) => {
62
76
  // The restart note. The memory head and the pod focus are NOT repeated here:
63
77
  // a fresh claude session already receives the full long_term memory through
64
78
  // its preamble, and the pod focus is already in the wake prompt.
65
- export const buildRecycleBriefing = ({ agentName, idleMinutes, contextTokens }) => [
79
+ export const buildRecycleBriefing = ({
80
+ agentName, reason = 'cold', idleMinutes, contextTokens, maxContextTokens = RECYCLE_DEFAULTS.maxContextTokens,
81
+ }) => [
66
82
  '=== 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.`,
83
+ reason === 'size'
84
+ ? `This wake starts a fresh session. The previous session had grown to about ${contextTokens}`
85
+ + ` context tokens, past the ${maxContextTokens}-token ceiling, so it was not resumed.`
86
+ : `This wake starts a fresh session. The previous session was idle ${idleMinutes} min`
87
+ + ` with about ${contextTokens} context tokens, so it was not resumed.`,
69
88
  `Role: ${agentName}. Your saved memory and the pod focus follow below.`,
70
89
  ].join('\n');
71
90
 
@@ -120,6 +139,75 @@ export const contextTokensFromTranscript = (text) => {
120
139
  return null;
121
140
  };
122
141
 
142
+ /**
143
+ * The prompt one request was sent, from a usage block that counts cached tokens
144
+ * apart from `input` (pi's message usage, dsh's step usage). Null when `input`
145
+ * is missing, so a stream without usage reads as unknown, not as zero.
146
+ */
147
+ export const promptTokens = ({ input, cacheRead, cacheWrite } = {}) => {
148
+ if (!Number.isFinite(input)) return null;
149
+ return input + (Number.isFinite(cacheRead) ? cacheRead : 0) + (Number.isFinite(cacheWrite) ? cacheWrite : 0);
150
+ };
151
+
152
+ // F404. codex keeps a session as <home>/sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl,
153
+ // dated by when it began; `exec resume` appends to that same file. Newest day
154
+ // first, so a live session is found after a few directory reads.
155
+ const newestFirst = (dir) => {
156
+ try {
157
+ return readdirSync(dir).sort().reverse();
158
+ } catch {
159
+ return [];
160
+ }
161
+ };
162
+
163
+ export const codexHomeFor = (env = process.env) => env?.CODEX_HOME || join(env?.HOME || homedir(), '.codex');
164
+
165
+ export const codexRolloutPath = ({ codexHome = codexHomeFor(), sessionId }) => {
166
+ if (!sessionId) return null;
167
+ const root = join(codexHome, 'sessions');
168
+ const suffix = `-${sessionId}.jsonl`;
169
+ for (const year of newestFirst(root)) {
170
+ for (const month of newestFirst(join(root, year))) {
171
+ for (const day of newestFirst(join(root, year, month))) {
172
+ const name = newestFirst(join(root, year, month, day)).find((file) => file.endsWith(suffix));
173
+ if (name) return join(root, year, month, day, name);
174
+ }
175
+ }
176
+ }
177
+ return null;
178
+ };
179
+
180
+ // The last request's prompt from codex's own `token_count` record. Its
181
+ // `input_tokens` already includes the cached part (`cached_input_tokens` is a
182
+ // subset), and `last_token_usage` is one request, where `total_token_usage` and
183
+ // the stream's `turn.completed` sum every request in the turn.
184
+ export const contextTokensFromCodexRollout = (text) => {
185
+ const lines = text.split('\n');
186
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
187
+ const line = lines[index].trim();
188
+ if (!line || !line.includes('token_count')) continue;
189
+ let record;
190
+ try {
191
+ record = JSON.parse(line);
192
+ } catch {
193
+ continue;
194
+ }
195
+ const input = record?.payload?.type === 'token_count'
196
+ ? record.payload.info?.last_token_usage?.input_tokens : undefined;
197
+ if (Number.isFinite(input)) return input;
198
+ }
199
+ return null;
200
+ };
201
+
202
+ export const codexContextTokens = ({ codexHome = codexHomeFor(), sessionId }) => {
203
+ try {
204
+ const file = codexRolloutPath({ codexHome, sessionId });
205
+ return file ? contextTokensFromCodexRollout(readTail(file)) : null;
206
+ } catch {
207
+ return null;
208
+ }
209
+ };
210
+
123
211
  export const claudeContextTokens = ({ cwd, sessionId, configDir = claudeConfigDirFor() }) => {
124
212
  const file = claudeTranscriptPath({ cwd, sessionId, configDir });
125
213
  if (!file || !existsSync(file)) return null;
@@ -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) {