@radnine/claude-session-daemon 0.9.2 → 0.9.4

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/README.md CHANGED
@@ -229,7 +229,8 @@ In Docker mode, `CLAUDE_WORKING_DIR` should point to your mounted workspace (e.g
229
229
  | `CLAUDE_LOG_LEVEL` | `info` | Log level (`debug`, `info`, `warn`, `error`) |
230
230
  | `CLAUDE_HEARTBEAT_INTERVAL` | `30` | Seconds between the daemon's health checks. In `actioncable` mode FlightDeck sets the heartbeat interval when the pilot registers (currently 30s) |
231
231
  | `CLAUDE_CLEANUP_INTERVAL` | `300` | Seconds between sweeps that remove dead sessions and kill stale ones |
232
- | `CLAUDE_STALE_SESSION_TIMEOUT` | `1800` | Seconds a running session can go without activity before the cleanup sweep kills it. `0` disables |
232
+ | `CLAUDE_STALE_SESSION_TIMEOUT` | `0` (off) | Seconds an idle session can go without activity before the cleanup sweep stops it; its chat resumes on its next message. Never a session mid-turn or waiting on a permission answer. `0` disables |
233
+ | `CLAUDE_EVICT_IDLE_AFTER` | `300` | At `CLAUDE_MAX_SESSIONS`, a new chat stops the session idle longest, if it has been idle this many seconds; the stopped chat resumes on its next message. Never a session mid-turn, waiting on a permission answer, never written to (no transcript to resume), or running background work (any task the CLI lists in `background_tasks_changed`, such as a background shell or subagent, plus a Monitor, CronCreate or ScheduleWakeup). The heartbeat reports how many qualify (`session_summary.evictable_sessions`) and FlightDeck leaves their slots free. `0` refuses instead (#488) |
233
234
  | `CLAUDE_STARTUP_TIMEOUT` | `5` | Parsed at startup, but no daemon code uses it yet |
234
235
  | `CLAUDE_COMMAND` | `claude` | Claude CLI binary to spawn. Also used for `claude auth status` |
235
236
  | `CLAUDE_EFFORT` | — | Machine default reasoning effort (`low`, `medium`, `high`, `xhigh`, `max`) that the daemon reports to FlightDeck. Overrides the `effort` key in `~/.claude/settings.json` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@radnine/claude-session-daemon",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "description": "Node.js daemon for managing Claude CLI sessions",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -7,6 +7,10 @@ const { randomUUID } = require('node:crypto');
7
7
  const fs = require('node:fs');
8
8
  const path = require('node:path');
9
9
  const { TurnTracker } = require('./turn-tracker');
10
+
11
+ // #488: tools whose work lasts as long as the CLI process. Stopping the
12
+ // process ends it, and a resumed chat never hears from it.
13
+ const LIFELONG_BACKGROUND_TOOLS = new Set(['Monitor', 'CronCreate', 'ScheduleWakeup']);
10
14
  const { stripDaemonSecrets } = require('./harness');
11
15
 
12
16
  const MAX_CHUNK_SIZE = 50000; // 50KB — lines larger than this get flagged
@@ -60,6 +64,7 @@ class ClaudeProcess extends EventEmitter {
60
64
  this._child = null;
61
65
  this._pid = null;
62
66
  this._startedAt = null;
67
+ this._lastActivityAt = null; // #488: last write, stdout or stderr line
63
68
 
64
69
  // Map of the CLI's control request_id -> the tool input it asked about.
65
70
  // An allow response has to echo the input back as `updatedInput`.
@@ -75,6 +80,15 @@ class ClaudeProcess extends EventEmitter {
75
80
 
76
81
  // #175: which command each stdout line belongs to.
77
82
  this._turns = new TurnTracker();
83
+
84
+ // #488: work the CLI runs between turns, which dies with the process.
85
+ // The CLI's own list of live background tasks (background_tasks_changed,
86
+ // 2.1.308; null until it sends one), a fallback count of
87
+ // run_in_background launches for a CLI that never does, and whether a
88
+ // tool that lasts the life of the process (a Monitor, a cron, a wakeup) ran.
89
+ this._backgroundTasks = null;
90
+ this._backgroundLaunches = 0;
91
+ this._lifelongBackground = false;
78
92
  }
79
93
 
80
94
  // -------------------------------------------------------------------------
@@ -170,6 +184,7 @@ class ClaudeProcess extends EventEmitter {
170
184
 
171
185
  this._pid = this._child.pid;
172
186
  this._startedAt = Date.now();
187
+ this._lastActivityAt = this._startedAt;
173
188
  this._state = 'running';
174
189
 
175
190
  this._setupStdout();
@@ -195,7 +210,10 @@ class ClaudeProcess extends EventEmitter {
195
210
  type: 'user',
196
211
  message: { role: 'user', content: text },
197
212
  });
198
- if (written > 0) this._turns.written(commandId, text);
213
+ if (written > 0) {
214
+ this._turns.written(commandId, text);
215
+ this._lastActivityAt = Date.now();
216
+ }
199
217
  this._logger.debug('Sent message to stdin', { length: written, commandId });
200
218
  return true;
201
219
  }
@@ -391,7 +409,27 @@ class ClaudeProcess extends EventEmitter {
391
409
  get claudeSessionId() { return this._claudeSessionId; }
392
410
  get sessionId() { return this._sessionId; }
393
411
  get startedAt() { return this._startedAt; }
412
+ /** #488: when the CLI last wrote a line or was written to; null before spawn. */
413
+ get lastActivityAt() { return this._lastActivityAt; }
394
414
  get workingDir() { return this._workingDir; }
415
+ /**
416
+ * #488: a turn is running or queued, or a permission prompt or
417
+ * AskUserQuestion waits on an answer. A full pilot never stops it.
418
+ */
419
+ isBusy() {
420
+ return this._turns.busy || this._pendingControl.size > 0 || this._heldQuestions.size > 0;
421
+ }
422
+ /**
423
+ * #488: `--resume` can reopen this chat. The CLI writes a transcript only
424
+ * once it takes a message; resuming an untouched chat exits 1 with "No
425
+ * conversation found".
426
+ */
427
+ canResume() { return this._resume || this._turns.tookMessage; }
428
+ /** #488: something the CLI started keeps running between turns. */
429
+ hasBackgroundWork() {
430
+ if (this._lifelongBackground) return true;
431
+ return this._backgroundTasks === null ? this._backgroundLaunches > 0 : this._backgroundTasks > 0;
432
+ }
395
433
  /** #175: the command the CLI read last, or undefined before it has read one. */
396
434
  get currentCommandId() { return this._turns.currentCommandId; }
397
435
  /** #175: commands written to this process that no result has ended yet. */
@@ -504,6 +542,7 @@ class ClaudeProcess extends EventEmitter {
504
542
 
505
543
  rl.on('line', (line) => {
506
544
  if (!line) return;
545
+ this._lastActivityAt = Date.now();
507
546
 
508
547
  try {
509
548
  const data = JSON.parse(line);
@@ -526,6 +565,7 @@ class ClaudeProcess extends EventEmitter {
526
565
  data._originalSize = line.length;
527
566
  }
528
567
 
568
+ this._trackBackgroundWork(data);
529
569
  this.emit('output', data, this._turns.observe(data));
530
570
  } catch (_) {
531
571
  // Not valid JSON — emit as error
@@ -535,6 +575,28 @@ class ClaudeProcess extends EventEmitter {
535
575
  });
536
576
  }
537
577
 
578
+ /**
579
+ * #488: what runs between turns. The CLI lists every live background task
580
+ * on each change, including ones no tool call flags: a default Agent call
581
+ * (task_type local_agent) and a Bash call its timeout moved to the
582
+ * background. The latest list is the answer. The run_in_background count
583
+ * from the tool calls (a subagent's too) only stands in for a CLI that
584
+ * never sends the list, and it never settles.
585
+ */
586
+ _trackBackgroundWork(data) {
587
+ if (data.type === 'system' && data.subtype === 'background_tasks_changed') {
588
+ this._backgroundTasks = Array.isArray(data.tasks) ? data.tasks.length : 0;
589
+ return;
590
+ }
591
+ if (data.type !== 'assistant' || !Array.isArray(data.message?.content)) return;
592
+
593
+ for (const block of data.message.content) {
594
+ if (!block || block.type !== 'tool_use') continue;
595
+ if (LIFELONG_BACKGROUND_TOOLS.has(block.name)) this._lifelongBackground = true;
596
+ else if (block.input?.run_in_background === true) this._backgroundLaunches += 1;
597
+ }
598
+ }
599
+
538
600
  /**
539
601
  * Dispatch a control request from the CLI.
540
602
  *
@@ -22,6 +22,22 @@ const NO_CHATGPT_EXTRAS = ['apps', 'plugins', 'remote_plugin'];
22
22
  // four; CLAUDE_SESSION_ID is the chat's own session id.
23
23
  const RAD_ENV_VARS = ['CLAUDE_SESSION_ID', 'FLIGHTDECK_URL', 'RAD_URL', 'RAD_TOKEN'];
24
24
 
25
+ // Names an MCP entry's env map may not change in the child's env, because Codex
26
+ // itself, and every shell command a chat runs, runs with them. CLAUDE_SESSION_ID
27
+ // is the chat's own id. The proxy names match in any case, as tools read both.
28
+ const GUARDED_ENV_VARS = new Set(['PATH', 'HOME', 'CLAUDE_SESSION_ID', 'NODE_OPTIONS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'NODE_EXTRA_CA_CERTS']);
29
+ const GUARDED_ENV_PREFIXES = ['CODEX_', 'OPENAI_', 'ANTHROPIC_', 'LD_', 'DYLD_'];
30
+ const PROXY_ENV_VARS = new Set(['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY']);
31
+
32
+ function isGuardedEnvVar(name) {
33
+ return GUARDED_ENV_VARS.has(name)
34
+ || PROXY_ENV_VARS.has(name.toUpperCase())
35
+ || GUARDED_ENV_PREFIXES.some((prefix) => name.startsWith(prefix));
36
+ }
37
+
38
+ // Codex server names become a dotted config key (mcp_servers.<name>.command).
39
+ const MCP_SERVER_NAME = /^[A-Za-z0-9_-]+$/;
40
+
25
41
  /**
26
42
  * Wraps one `codex app-server` child (JSON-RPC over stdio) for one FlightDeck
27
43
  * chat, and keeps one Codex thread alive across turns. It follows the harness
@@ -47,6 +63,8 @@ class CodexProcess extends EventEmitter {
47
63
  * @param {string} [options.effort] - reasoning effort for each turn
48
64
  * @param {object} [options.sessionEnv] - extra env for the child
49
65
  * @param {{command: string, args: string[], env?: object}} [options.radMcp] - how to start the rad MCP server
66
+ * @param {Array<{name: string, command: string, args: string[], env?: object}>} [options.mcpServers] - the other
67
+ * MCP servers; by default the stdio servers a Claude chat in workingDir gets (findMcpServers)
50
68
  * @param {Function} [options._spawnFn] - tests: replacement for child_process.spawn
51
69
  */
52
70
  constructor(sessionId, options = {}) {
@@ -64,11 +82,15 @@ class CodexProcess extends EventEmitter {
64
82
  this._model = options.model || null;
65
83
  this._effort = options.effort || null;
66
84
  this._radMcp = options.radMcp;
85
+ this._mcpServers = options.mcpServers;
86
+ this._skillRoots = [];
87
+ this._memoryIndex = null;
67
88
 
68
89
  this._state = 'idle';
69
90
  this._child = null;
70
91
  this._pid = null;
71
92
  this._startedAt = null;
93
+ this._lastActivityAt = null; // #488: last message in, or stdout/stderr line out
72
94
 
73
95
  this._nextRequestId = 0;
74
96
  this._pending = new Map(); // request id -> { resolve, reject, timer, method }
@@ -95,9 +117,20 @@ class CodexProcess extends EventEmitter {
95
117
 
96
118
  this._state = 'spawning';
97
119
 
98
- const env = buildCodexEnv(process.env, this._sessionEnv, this._sessionId);
99
- env.CODEX_HOME = prepareCodexHome(env);
100
- const args = buildCodexArgs({ env, radMcp: this._radMcp, writableRoots: gitWritableRoots(this._workingDir) });
120
+ const baseEnv = buildCodexEnv(process.env, this._sessionEnv, this._sessionId);
121
+ baseEnv.CODEX_HOME = prepareCodexHome(baseEnv);
122
+ const mcpServers = this._mcpServers === undefined
123
+ ? findMcpServers({ env: baseEnv, workingDir: this._workingDir, logger: this._logger })
124
+ : this._mcpServers;
125
+ const { args, env } = buildCodexLaunch({
126
+ env: baseEnv,
127
+ radMcp: this._radMcp,
128
+ mcpServers,
129
+ writableRoots: gitWritableRoots(this._workingDir),
130
+ logger: this._logger,
131
+ });
132
+ this._skillRoots = claudeSkillRoots(env, this._workingDir);
133
+ this._memoryIndex = memoryIndexPath(env, this._workingDir);
101
134
 
102
135
  this._logger.info(`Spawning Codex app-server: ${this._codexCommand}`, {
103
136
  sessionId: this._sessionId,
@@ -122,6 +155,7 @@ class CodexProcess extends EventEmitter {
122
155
 
123
156
  this._pid = this._child.pid;
124
157
  this._startedAt = Date.now();
158
+ this._lastActivityAt = this._startedAt;
125
159
  this._state = 'running';
126
160
 
127
161
  this._setupStdout();
@@ -153,6 +187,7 @@ class CodexProcess extends EventEmitter {
153
187
  }
154
188
 
155
189
  this._turns.written(commandId, text);
190
+ this._lastActivityAt = Date.now();
156
191
  this._inbox.push(text);
157
192
  this._logger.debug('Queued message for Codex', { length: text.length, commandId });
158
193
  this._pump();
@@ -238,8 +273,16 @@ class CodexProcess extends EventEmitter {
238
273
  /** The Codex thread id: what Rails stores and passes back to resume. */
239
274
  get claudeSessionId() { return this._threadId || this._resumeThreadId; }
240
275
  get startedAt() { return this._startedAt; }
276
+ /** #488: when Codex last wrote a line or was handed a message; null before spawn. */
277
+ get lastActivityAt() { return this._lastActivityAt; }
241
278
  get workingDir() { return this._workingDir; }
242
279
  get currentCommandId() { return this._turns.currentCommandId; }
280
+ /** #488: a turn is starting or running, or a message waits for one. */
281
+ isBusy() { return this._busy || this._inbox.length > 0 || this._turns.busy; }
282
+ /** #488: a resumed thread, or one a turn has taken a message on. */
283
+ canResume() { return !!this._resumeThreadId || this._turns.tookMessage; }
284
+ /** #488: Codex runs nothing between turns. */
285
+ hasBackgroundWork() { return false; }
243
286
  unfinishedCommandIds() { return this._turns.unfinishedCommandIds(); }
244
287
  readCommandIds() { return this._turns.readCommandIds(); }
245
288
 
@@ -254,6 +297,17 @@ class CodexProcess extends EventEmitter {
254
297
  });
255
298
  this._notify('initialized');
256
299
 
300
+ // Codex loads repo skills only from .agents/skills and .codex/skills. Add
301
+ // the Claude skills folders before the thread starts, so its first turn
302
+ // sees them. A Codex without this call still gets a working chat.
303
+ if (this._skillRoots.length) {
304
+ try {
305
+ await this._request('skills/extraRoots/set', { extraRoots: this._skillRoots });
306
+ } catch (err) {
307
+ this._logger.warn('Codex did not take the Claude skills folders', { roots: this._skillRoots, error: err.message });
308
+ }
309
+ }
310
+
257
311
  // workspace-write with network (set in buildCodexArgs): git commit works in
258
312
  // a worktree, and git push / package installs reach the network.
259
313
  const params = {
@@ -262,7 +316,8 @@ class CodexProcess extends EventEmitter {
262
316
  sandbox: 'workspace-write',
263
317
  };
264
318
  if (this._model) params.model = this._model;
265
- if (this._systemPrompt) params.developerInstructions = this._systemPrompt;
319
+ const instructions = developerInstructions(this._systemPrompt, this._memoryIndex);
320
+ if (instructions) params.developerInstructions = instructions;
266
321
 
267
322
  let response;
268
323
  if (this._resumeThreadId) {
@@ -455,6 +510,7 @@ class CodexProcess extends EventEmitter {
455
510
 
456
511
  rl.on('line', (line) => {
457
512
  if (!line) return;
513
+ this._lastActivityAt = Date.now();
458
514
 
459
515
  let message;
460
516
  try {
@@ -493,6 +549,7 @@ class CodexProcess extends EventEmitter {
493
549
 
494
550
  rl.on('line', (line) => {
495
551
  if (!line) return;
552
+ this._lastActivityAt = Date.now();
496
553
  this._logger.warn('Codex stderr', { line });
497
554
  this.emit('stderr', line);
498
555
  });
@@ -596,23 +653,218 @@ function buildCodexEnv(baseEnv, sessionEnv, sessionId) {
596
653
  * @returns {{command: string, args: string[], env?: object}|null}
597
654
  */
598
655
  function findRadMcp(env = process.env, home = os.homedir()) {
599
- const configDir = env.CLAUDE_CONFIG_DIR;
600
- const claudeConfig = configDir ? path.join(configDir, '.claude.json') : path.join(home, '.claude.json');
601
- try {
602
- const rad = JSON.parse(fs.readFileSync(claudeConfig, 'utf8')).mcpServers?.rad;
603
- if (rad && typeof rad.command === 'string' && Array.isArray(rad.args)) {
604
- const found = { command: rad.command, args: rad.args.map(String) };
605
- const radEnv = stringEnv(rad.env);
606
- if (radEnv) found.env = radEnv;
607
- return found;
608
- }
609
- } catch (_) { /* no Claude config, or not JSON */ }
656
+ const rad = readJson(claudeConfigFile(env, home))?.mcpServers?.rad;
657
+ if (rad && typeof rad.command === 'string' && Array.isArray(rad.args)) {
658
+ const found = { command: rad.command, args: rad.args.map(String) };
659
+ const radEnv = stringEnv(rad.env);
660
+ if (radEnv) found.env = radEnv;
661
+ return found;
662
+ }
610
663
 
611
664
  const launcher = path.join(home, '.flightdeck', 'rad-mcp');
612
665
  if (fs.existsSync(launcher)) return { command: 'ruby', args: [launcher] };
613
666
  return null;
614
667
  }
615
668
 
669
+ // ---------------------------------------------------------------------------
670
+ // What a Claude chat in the same directory gets (#491)
671
+ // ---------------------------------------------------------------------------
672
+
673
+ // The Claude CLI's config directory (global CLAUDE.md, skills, project memory)
674
+ // and its main config file (MCP servers), the way the CLI finds them.
675
+ function claudeConfigDir(env = process.env, home = os.homedir()) {
676
+ return env.CLAUDE_CONFIG_DIR || path.join(home, '.claude');
677
+ }
678
+
679
+ function claudeConfigFile(env = process.env, home = os.homedir()) {
680
+ return env.CLAUDE_CONFIG_DIR ? path.join(env.CLAUDE_CONFIG_DIR, '.claude.json') : path.join(home, '.claude.json');
681
+ }
682
+
683
+ function readJson(file) {
684
+ try {
685
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
686
+ } catch (_) {
687
+ return null; // missing, or not JSON
688
+ }
689
+ }
690
+
691
+ function isDirectory(dir) {
692
+ try {
693
+ return fs.statSync(dir).isDirectory();
694
+ } catch (_) {
695
+ return false;
696
+ }
697
+ }
698
+
699
+ /**
700
+ * The Claude skills folders for a chat in `workingDir`: the repo's
701
+ * `.claude/skills` and the user's Claude skills folder, the ones that exist.
702
+ * Codex follows symlinked skill folders (checked on 0.162.1).
703
+ *
704
+ * A folder Codex already loads by itself (`.agents/skills` and `.codex/skills`
705
+ * in the repo, `~/.agents/skills`, `$CODEX_HOME/skills`), or one already in
706
+ * this list, is left out, compared by real path. A repo whose `.claude/skills`
707
+ * is a symlink to `.agents/skills` would otherwise get its skills relabelled
708
+ * from repo to user: Codex lists a folder once, under the scope of the last
709
+ * root that named it.
710
+ */
711
+ function claudeSkillRoots(env = process.env, workingDir = process.cwd(), home = os.homedir()) {
712
+ const native = [
713
+ path.join(workingDir, '.agents', 'skills'),
714
+ path.join(workingDir, '.codex', 'skills'),
715
+ path.join(home, '.agents', 'skills'),
716
+ ];
717
+ if (env.CODEX_HOME) native.push(path.join(env.CODEX_HOME, 'skills'));
718
+ const seen = new Set(native.filter(isDirectory).map(realPath));
719
+
720
+ const roots = [];
721
+ for (const root of [path.join(workingDir, '.claude', 'skills'), path.join(claudeConfigDir(env, home), 'skills')]) {
722
+ if (!isDirectory(root)) continue;
723
+ const real = realPath(root);
724
+ if (seen.has(real)) continue;
725
+ seen.add(real);
726
+ roots.push(root);
727
+ }
728
+ return roots;
729
+ }
730
+
731
+ function realPath(dir) {
732
+ try {
733
+ return fs.realpathSync(dir);
734
+ } catch (_) {
735
+ return path.resolve(dir);
736
+ }
737
+ }
738
+
739
+ /**
740
+ * The Claude project memory index for `workingDir`, or null. Claude names the
741
+ * project folder after the cwd with every character other than a letter or
742
+ * digit turned into "-".
743
+ */
744
+ function memoryIndexPath(env = process.env, workingDir = process.cwd(), home = os.homedir()) {
745
+ const project = workingDir.replace(/[^a-zA-Z0-9]/g, '-');
746
+ const index = path.join(claudeConfigDir(env, home), 'projects', project, 'memory', 'MEMORY.md');
747
+ return fs.existsSync(index) ? index : null;
748
+ }
749
+
750
+ // The persona prompt, plus one line pointing at the memory index when there is one.
751
+ function developerInstructions(systemPrompt, memoryIndex) {
752
+ if (!memoryIndex) return systemPrompt || null;
753
+ const line = `Before you start, read your memory index at ${memoryIndex}. It lists what earlier chats in this repo learned; open the files it links to when they bear on your task.`;
754
+ return systemPrompt ? `${systemPrompt}\n\n${line}` : line;
755
+ }
756
+
757
+ /**
758
+ * Expand `${VAR}` and `${VAR:-default}` against `env`, as Claude does for MCP
759
+ * entries. Null when a variable is unset and has no default.
760
+ */
761
+ function expandEnvRefs(value, env) {
762
+ return expandRefs(value, env).value;
763
+ }
764
+
765
+ // { value, missing }: missing names the first unset variable with no default.
766
+ function expandRefs(value, env) {
767
+ let missing = null;
768
+ const out = String(value).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_, name, fallback) => {
769
+ const set = env[name];
770
+ if (set !== undefined && (set !== '' || fallback === undefined)) return set;
771
+ if (fallback !== undefined) return fallback;
772
+ if (!missing) missing = name;
773
+ return '';
774
+ });
775
+ return { value: missing ? null : out, missing };
776
+ }
777
+
778
+ function mcpMap(servers) {
779
+ return servers && typeof servers === 'object' && !Array.isArray(servers) ? servers : {};
780
+ }
781
+
782
+ // One Claude MCP entry as a server Codex can start, or null (logged once).
783
+ function stdioServer(name, entry, env, logger) {
784
+ const type = entry && (entry.type || (entry.url ? 'http' : 'stdio'));
785
+ if (!MCP_SERVER_NAME.test(name) || type !== 'stdio' || typeof entry.command !== 'string') {
786
+ logger.warn('Skipping MCP server for Codex: only stdio servers with a plain name can run there', { server: name, type });
787
+ return null;
788
+ }
789
+
790
+ const unset = [];
791
+ const expand = (value) => {
792
+ const { value: out, missing } = expandRefs(value, env);
793
+ if (missing) unset.push(missing);
794
+ return out;
795
+ };
796
+ const server = { name, command: expand(entry.command), args: (Array.isArray(entry.args) ? entry.args : []).map(expand) };
797
+ const serverEnv = stringEnv(entry.env);
798
+ if (serverEnv) {
799
+ for (const key of Object.keys(serverEnv)) serverEnv[key] = expand(serverEnv[key]);
800
+ server.env = serverEnv;
801
+ }
802
+ if (unset.length) {
803
+ logger.warn('Skipping MCP server for Codex: it needs an environment variable that is not set', { server: name, variable: unset[0] });
804
+ return null;
805
+ }
806
+ return server;
807
+ }
808
+
809
+ function stringList(value) {
810
+ return Array.isArray(value) ? value.filter((v) => typeof v === 'string') : [];
811
+ }
812
+
813
+ /**
814
+ * The stdio MCP servers a Claude chat in `workingDir` gets, besides rad: the
815
+ * user's `mcpServers`, the repo's `.mcp.json`, and this directory's entry under
816
+ * `projects` in the Claude config, in Claude's scope order (the project entry
817
+ * wins, then .mcp.json, then the user's). HTTP, SSE and OAuth servers are
818
+ * skipped with one log line each. A `rad` entry is left to findRadMcp, so a
819
+ * chat always reaches its own FlightDeck the way it does today.
820
+ *
821
+ * Claude's disable state applies too, each skip with one log line: a server
822
+ * named in this directory's `disabledMcpServers` (any scope, what `/mcp`
823
+ * disable writes), and a .mcp.json server named in `disabledMcpjsonServers`
824
+ * there or in a Claude settings file. `enabledMcpjsonServers` is not a gate:
825
+ * .mcp.json stdio servers load without approval.
826
+ *
827
+ * @returns {Array<{name: string, command: string, args: string[], env?: object}>}
828
+ */
829
+ function findMcpServers({ env = process.env, workingDir = process.cwd(), logger = _defaultLogger(), home = os.homedir() } = {}) {
830
+ const config = readJson(claudeConfigFile(env, home)) || {};
831
+ const projects = mcpMap(config.projects);
832
+ let real = workingDir;
833
+ try { real = fs.realpathSync(workingDir); } catch (_) { /* keep as given */ }
834
+ const project = projects[workingDir] || projects[real] || {};
835
+ const repo = (readJson(path.join(workingDir, '.mcp.json')) || {}).mcpServers;
836
+
837
+ const disabled = new Set(stringList(project.disabledMcpServers));
838
+ const settingsFiles = [
839
+ path.join(claudeConfigDir(env, home), 'settings.json'),
840
+ path.join(workingDir, '.claude', 'settings.json'),
841
+ path.join(workingDir, '.claude', 'settings.local.json'),
842
+ ];
843
+ const disabledJson = new Set([
844
+ ...stringList(project.disabledMcpjsonServers),
845
+ ...settingsFiles.flatMap((file) => stringList((readJson(file) || {}).disabledMcpjsonServers)),
846
+ ]);
847
+
848
+ const merged = new Map(); // name -> { scope, entry }; a later scope wins
849
+ for (const [scope, map] of [['user', config.mcpServers], ['project', repo], ['local', project.mcpServers]]) {
850
+ for (const [name, entry] of Object.entries(mcpMap(map))) merged.set(name, { scope, entry });
851
+ }
852
+
853
+ const servers = [];
854
+ for (const [name, { scope, entry }] of merged) {
855
+ if (name === 'rad') continue;
856
+ const reason = disabled.has(name) ? 'disabledMcpServers'
857
+ : scope === 'project' && disabledJson.has(name) ? 'disabledMcpjsonServers' : null;
858
+ if (reason) {
859
+ logger.warn('Skipping MCP server for Codex: it is disabled for this directory in Claude', { server: name, reason });
860
+ continue;
861
+ }
862
+ const server = stdioServer(name, entry, env, logger);
863
+ if (server) servers.push(server);
864
+ }
865
+ return servers;
866
+ }
867
+
616
868
  // Keep only string-valued entries of an MCP `env` map; null when none are left.
617
869
  function stringEnv(map) {
618
870
  if (!map || typeof map !== 'object' || Array.isArray(map)) return null;
@@ -645,33 +897,40 @@ function userCodexHome(env = process.env, home = os.homedir()) {
645
897
  }
646
898
 
647
899
  /**
648
- * Create the dedicated Codex home and link the user's login into it.
649
- * Codex rewrites auth.json in place (open with truncate, no temp file and
650
- * rename; codex-rs/login/src/auth/storage.rs, rust-v0.162.1), so a refreshed
651
- * token is written through the symlink to the user's file and the two never
652
- * drift. Nothing in the user's Codex home is modified, copied or removed; only
653
- * the symlink in the FlightDeck home is created or repaired. A regular file
654
- * already at that path (a login done in this home) is left alone.
900
+ * Create the dedicated Codex home and link two files into it:
901
+ * - auth.json, the user's Codex login. Codex rewrites auth.json in place (open
902
+ * with truncate, no temp file and rename; codex-rs/login/src/auth/storage.rs,
903
+ * rust-v0.162.1), so a refreshed token is written through the symlink to the
904
+ * user's file and the two never drift.
905
+ * - AGENTS.md, the user's Claude global CLAUDE.md, which Codex reads as the
906
+ * global rules for every chat (#491).
907
+ * Nothing in the user's Codex or Claude folders is modified, copied or
908
+ * removed; only the symlinks in the FlightDeck home are created or repaired.
909
+ * A regular file already at either path (a login done in this home, rules
910
+ * written for it) is left alone.
655
911
  *
656
912
  * @returns {string} the CODEX_HOME to give the child
657
913
  */
658
914
  function prepareCodexHome(env = process.env, home = os.homedir()) {
659
915
  const codexHome = flightdeckCodexHome(env, home);
660
916
  fs.mkdirSync(codexHome, { recursive: true, mode: 0o700 });
917
+ linkInto(path.join(userCodexHome(env, home), 'auth.json'), path.join(codexHome, 'auth.json'));
918
+ linkInto(path.join(claudeConfigDir(env, home), 'CLAUDE.md'), path.join(codexHome, 'AGENTS.md'));
919
+ return codexHome;
920
+ }
661
921
 
662
- const source = path.join(userCodexHome(env, home), 'auth.json');
663
- const link = path.join(codexHome, 'auth.json');
664
- if (!fs.existsSync(source)) return codexHome;
922
+ // Point `link` at `source` when the source exists, unless a regular file is there.
923
+ function linkInto(source, link) {
924
+ if (!fs.existsSync(source)) return;
665
925
 
666
926
  let existing = null;
667
927
  try { existing = fs.lstatSync(link); } catch (_) { /* absent */ }
668
928
  if (existing) {
669
- if (!existing.isSymbolicLink()) return codexHome;
670
- if (fs.readlinkSync(link) === source) return codexHome;
929
+ if (!existing.isSymbolicLink()) return;
930
+ if (fs.readlinkSync(link) === source) return;
671
931
  fs.unlinkSync(link);
672
932
  }
673
933
  fs.symlinkSync(source, link);
674
- return codexHome;
675
934
  }
676
935
 
677
936
  /**
@@ -707,19 +966,35 @@ function gitWritableRoots(workingDir, exec = childProcess.execFileSync) {
707
966
  }
708
967
 
709
968
  /**
710
- * Arguments for `codex app-server`. Per-process `-c` overrides, so no config
711
- * file is written:
969
+ * Arguments and env for `codex app-server`. Per-process `-c` overrides, so no
970
+ * config file is written:
712
971
  * - sandbox_workspace_write.network_access: workspace-write blocks the network
713
972
  * by default, which breaks git push and installs.
973
+ * - project_doc_fallback_filenames: Codex reads CLAUDE.md in a directory with
974
+ * no AGENTS.md, so a chat gets the repo's Claude rules (#491).
714
975
  * - mcp_servers.rad: the command a Claude chat uses, plus env_vars so that
715
- * CLAUDE_SESSION_ID (and the URL and token, when set) reach the server, plus
716
- * the rad entry's own env map (it wins over the daemon's env, as in Claude).
976
+ * CLAUDE_SESSION_ID (and the URL and token, when set) reach the server.
977
+ * - mcp_servers.<name>: every other stdio server a Claude chat gets
978
+ * (findMcpServers), enabled and approved like rad.
979
+ *
980
+ * No MCP env value goes on argv, where `ps` shows it. Each one is set in the
981
+ * child's env and its name listed in that server's env_vars, so Codex hands
982
+ * it to the server. A server's own `args` (as written, or after ${VAR}
983
+ * expansion) do go on argv, as they do on the server's command line in a
984
+ * Claude chat. The rad entry's map wins over the daemon's env, as in Claude.
985
+ * Two servers that need different values under one name cannot share the
986
+ * child's env: the later one is skipped with a log line. So is a server that
987
+ * would change a name Codex itself runs with (isGuardedEnvVar) to a value the
988
+ * daemon's env does not already have; the rad entry drops such a name with a
989
+ * log line instead. Log lines name the variable, never its value.
717
990
  *
718
- * The user's MCP servers and plugins are not an argument concern: the child
719
- * runs in the dedicated CODEX_HOME (prepareCodexHome), whose config.toml is
720
- * empty, so only the `rad` server above exists.
991
+ * The user's own Codex MCP servers and plugins never load: the child runs in
992
+ * the dedicated CODEX_HOME (prepareCodexHome), which has no config.toml.
993
+ *
994
+ * @returns {{args: string[], env: object}} env is a new object
721
995
  */
722
- function buildCodexArgs({ env, radMcp, writableRoots } = {}) {
996
+ function buildCodexLaunch({ env = {}, radMcp, mcpServers = [], writableRoots, logger = _defaultLogger() } = {}) {
997
+ const childEnv = { ...env };
723
998
  const args = ['app-server', '-c', 'sandbox_workspace_write.network_access=true'];
724
999
  if (Array.isArray(writableRoots) && writableRoots.length) {
725
1000
  args.push('-c', `sandbox_workspace_write.writable_roots=${JSON.stringify(writableRoots)}`);
@@ -728,27 +1003,68 @@ function buildCodexArgs({ env, radMcp, writableRoots } = {}) {
728
1003
  // ChatGPT account's connectors, 100+ tools) and the curated plugin catalog
729
1004
  // whenever the login is a ChatGPT login. Turn both features off.
730
1005
  for (const feature of NO_CHATGPT_EXTRAS) args.push('-c', `features.${feature}=false`);
1006
+ args.push('-c', 'project_doc_fallback_filenames=["CLAUDE.md"]');
731
1007
 
732
- const rad = radMcp === undefined ? findRadMcp(env) : radMcp;
733
- if (rad) {
1008
+ const addServer = (name, server, envVars) => {
734
1009
  args.push(
735
- '-c', `mcp_servers.rad.command=${JSON.stringify(rad.command)}`,
736
- '-c', `mcp_servers.rad.args=${JSON.stringify(rad.args)}`,
737
- '-c', `mcp_servers.rad.env_vars=${JSON.stringify(RAD_ENV_VARS)}`,
738
- '-c', 'mcp_servers.rad.enabled=true',
1010
+ '-c', `mcp_servers.${name}.command=${JSON.stringify(server.command)}`,
1011
+ '-c', `mcp_servers.${name}.args=${JSON.stringify(server.args)}`,
1012
+ );
1013
+ if (envVars.length) args.push('-c', `mcp_servers.${name}.env_vars=${JSON.stringify(envVars)}`);
1014
+ args.push(
1015
+ '-c', `mcp_servers.${name}.enabled=true`,
739
1016
  // approval_policy "never" refuses any MCP tool the server does not mark
740
- // read-only. rad's tools are the chat's own FlightDeck calls.
741
- '-c', 'mcp_servers.rad.default_tools_approval_mode="approve"',
1017
+ // read-only. These are the tools a Claude chat in this repo has.
1018
+ '-c', `mcp_servers.${name}.default_tools_approval_mode="approve"`,
742
1019
  );
743
- const radEnv = stringEnv(rad.env);
744
- if (radEnv) {
745
- // CLAUDE_SESSION_ID is the chat's own id; an entry cannot override it.
746
- delete radEnv.CLAUDE_SESSION_ID;
747
- const pairs = Object.entries(radEnv).map(([k, v]) => `${JSON.stringify(k)} = ${JSON.stringify(v)}`);
748
- if (pairs.length) args.push('-c', `mcp_servers.rad.env={ ${pairs.join(', ')} }`);
1020
+ };
1021
+
1022
+ const claimed = new Map(); // env name -> the value an MCP server needs
1023
+ const rad = radMcp === undefined ? findRadMcp(env) : radMcp;
1024
+ if (rad) {
1025
+ const applied = [];
1026
+ for (const [key, value] of Object.entries(stringEnv(rad.env) || {})) {
1027
+ if (isGuardedEnvVar(key) && childEnv[key] !== value) {
1028
+ logger.warn('Ignoring a variable in the rad MCP entry env: Codex itself runs with it', { server: 'rad', variable: key });
1029
+ continue;
1030
+ }
1031
+ childEnv[key] = value;
1032
+ applied.push(key);
1033
+ }
1034
+ const envVars = [...new Set([...RAD_ENV_VARS, ...applied])];
1035
+ for (const key of envVars) claimed.set(key, childEnv[key]);
1036
+ addServer('rad', { command: rad.command, args: rad.args }, envVars);
1037
+ }
1038
+
1039
+ for (const server of mcpServers) {
1040
+ const serverEnv = stringEnv(server.env) || {};
1041
+ const guarded = Object.entries(serverEnv).find(([key, value]) => isGuardedEnvVar(key) && childEnv[key] !== value);
1042
+ if (guarded) {
1043
+ logger.warn('Skipping MCP server for Codex: its env would change a variable Codex itself runs with', {
1044
+ server: server.name, variable: guarded[0],
1045
+ });
1046
+ continue;
749
1047
  }
1048
+ const clash = Object.entries(serverEnv).find(([key, value]) => claimed.has(key) && claimed.get(key) !== value);
1049
+ if (clash) {
1050
+ logger.warn('Skipping MCP server for Codex: another server needs a different value for one of its env variables', {
1051
+ server: server.name, variable: clash[0],
1052
+ });
1053
+ continue;
1054
+ }
1055
+ for (const [key, value] of Object.entries(serverEnv)) {
1056
+ childEnv[key] = value;
1057
+ claimed.set(key, value);
1058
+ }
1059
+ addServer(server.name, server, Object.keys(serverEnv));
750
1060
  }
751
- return args;
1061
+
1062
+ return { args, env: childEnv };
1063
+ }
1064
+
1065
+ // The `codex app-server` arguments alone (see buildCodexLaunch).
1066
+ function buildCodexArgs(options = {}) {
1067
+ return buildCodexLaunch(options).args;
752
1068
  }
753
1069
 
754
1070
  function _defaultLogger() {
@@ -770,3 +1086,9 @@ module.exports.prepareCodexHome = prepareCodexHome;
770
1086
  module.exports.flightdeckCodexHome = flightdeckCodexHome;
771
1087
  module.exports.codexAuthMode = codexAuthMode;
772
1088
  module.exports.RAD_ENV_VARS = RAD_ENV_VARS;
1089
+ module.exports.buildCodexLaunch = buildCodexLaunch;
1090
+ module.exports.findMcpServers = findMcpServers;
1091
+ module.exports.claudeSkillRoots = claudeSkillRoots;
1092
+ module.exports.memoryIndexPath = memoryIndexPath;
1093
+ module.exports.developerInstructions = developerInstructions;
1094
+ module.exports.expandEnvRefs = expandEnvRefs;
package/src/config.js CHANGED
@@ -167,13 +167,20 @@ function loadConfig() {
167
167
 
168
168
  // Stale session timeout in seconds — kill alive processes with no activity beyond this threshold.
169
169
  // Safety net for when WebSocket-based deactivation messages are lost.
170
- // Default: 30 minutes (1800s). Set to 0 to disable.
171
- staleSessionTimeout: intEnv(env.CLAUDE_STALE_SESSION_TIMEOUT, 1800),
170
+ // Default: off (0). It never ran on a real process before #488 restored
171
+ // lastActivityAt, so turning it on is a change of its own; 1800 was the
172
+ // old nominal value.
173
+ staleSessionTimeout: intEnv(env.CLAUDE_STALE_SESSION_TIMEOUT, 0),
172
174
 
173
175
  // Seconds a command for a session with no process waits for Rails'
174
176
  // session_activate before it fails. The activation carries the model and
175
177
  // persona, and can arrive just after its command.
176
178
  activationWaitTimeout: intEnv(env.CLAUDE_ACTIVATION_WAIT_TIMEOUT, 30),
179
+
180
+ // #488: seconds a process must sit idle before a pilot at its cap may
181
+ // stop it to start a new chat. The stopped chat resumes on its next
182
+ // message. 0 never stops one early.
183
+ evictIdleAfter: intEnv(env.CLAUDE_EVICT_IDLE_AFTER, 300),
177
184
  };
178
185
 
179
186
  // Validate mode
@@ -194,6 +201,10 @@ function loadConfig() {
194
201
  throw new Error(`CLAUDE_ACTIVATION_WAIT_TIMEOUT must be >= 1, got ${config.activationWaitTimeout}`);
195
202
  }
196
203
 
204
+ if (config.evictIdleAfter < 0) {
205
+ throw new Error(`CLAUDE_EVICT_IDLE_AFTER must be >= 0, got ${config.evictIdleAfter}`);
206
+ }
207
+
197
208
  if (config.staleSessionTimeout < 0) {
198
209
  throw new Error(`CLAUDE_STALE_SESSION_TIMEOUT must be >= 0, got ${config.staleSessionTimeout}`);
199
210
  }
@@ -280,7 +280,13 @@ class ActionCableClient extends BaseConnection {
280
280
  return;
281
281
  }
282
282
 
283
- const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
283
+ // #488: an idle stop ended no turn. A complete would show "exit code
284
+ // null" on an open chat page and run Rails' after-turn steps.
285
+ if (extra.idleStop && !(extra.unfinishedCommandIds?.length > 0)) return;
286
+
287
+ // #488: after an idle stop, the active command is one waiting for the
288
+ // resume, not one this process ran.
289
+ const resolvedCommandId = commandId || (extra.idleStop ? null : this._activeCommands.get(sessionId)) || null;
284
290
 
285
291
  const message = {
286
292
  type: 'command_complete',
@@ -298,7 +304,7 @@ class ActionCableClient extends BaseConnection {
298
304
  this.sendDaemonMessage(message);
299
305
 
300
306
  // Clear active command on completion
301
- this._activeCommands.delete(sessionId);
307
+ if (!extra.idleStop) this._activeCommands.delete(sessionId);
302
308
  }
303
309
 
304
310
  /**
@@ -1805,6 +1811,8 @@ class ActionCableClient extends BaseConnection {
1805
1811
  active_sessions: active,
1806
1812
  idle_sessions: healthResults.length - active,
1807
1813
  session_ids: healthResults.map((h) => String(h.sessionId)),
1814
+ // #488: processes a new chat could stop; Rails leaves their slots free.
1815
+ evictable_sessions: typeof this._daemon.evictableCount === 'function' ? this._daemon.evictableCount() : 0,
1808
1816
  };
1809
1817
  } catch (_) {
1810
1818
  return { total_sessions: 0, active_sessions: 0, idle_sessions: 0 };
@@ -29,8 +29,8 @@ class BaseConnection extends EventEmitter {
29
29
  this.sendOutput(sessionId, commandId ?? null, data, { turnCommandIds });
30
30
  });
31
31
 
32
- this._daemon.on('session:exit', ({ sessionId, code, signal, commandId, unfinishedCommandIds, readCommandIds }) => {
33
- this.sendComplete(sessionId, commandId ?? null, code, 0, { unfinishedCommandIds, readCommandIds });
32
+ this._daemon.on('session:exit', ({ sessionId, code, signal, commandId, unfinishedCommandIds, readCommandIds, idleStop }) => {
33
+ this.sendComplete(sessionId, commandId ?? null, code, 0, { unfinishedCommandIds, readCommandIds, idleStop });
34
34
  });
35
35
 
36
36
  this._daemon.on('session:error', ({ sessionId, data }) => {
package/src/daemon.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { EventEmitter } = require('node:events');
4
+ const os = require('node:os');
4
5
  const { createHarnessProcess } = require('./harness');
5
6
  const { resetGitState } = require('./git-reset');
6
7
  const { usageFromRateLimitEvent } = require('./claude-usage');
@@ -16,6 +17,15 @@ const STOP_WAIT_MS = 8000;
16
17
  // session_activate carries them instead.
17
18
  const MAX_EXITED_SPAWN_OPTIONS = 100;
18
19
 
20
+ // #488: seconds a process must sit idle before a full pilot may stop it to
21
+ // start a new chat (CLAUDE_EVICT_IDLE_AFTER). Matches loadConfig's default.
22
+ const EVICT_IDLE_AFTER = 300;
23
+
24
+ // #488: after kill() returns, the longest an idle stop waits for the CLI's
25
+ // exit before it lets the slot go anyway (config idleStopExitWaitMs).
26
+ // kill() itself gives up after about 7 s.
27
+ const IDLE_STOP_EXIT_WAIT_MS = 10000;
28
+
19
29
  /**
20
30
  * Process pool manager for Claude CLI sessions.
21
31
  *
@@ -47,6 +57,10 @@ class Daemon extends EventEmitter {
47
57
  this._spawnOptions = new Map(); // sessionId -> options of its last spawn (for a resume without Rails)
48
58
  this._exitedSessions = new Set(); // sessionIds in _spawnOptions with no running process, oldest exit first (#109)
49
59
  this._stopping = new Map(); // sessionId -> { proc, done } while terminateSession kills it (#348)
60
+ this._idleStopping = new Map(); // sessionId -> proc an idle stop took out of the pool, until it exits (#488)
61
+ this._idleStopped = new WeakSet(); // every proc an idle stop ended, for its exit event however late (#488)
62
+ this._activations = new Map(); // sessionId -> the activation in flight; one at a time per session (#488)
63
+ this._reservedSlots = 0; // activations past the capacity check that have not joined the pool yet (#488)
50
64
  this._config = config;
51
65
  this._logger = logger;
52
66
  this._running = false;
@@ -161,6 +175,20 @@ class Daemon extends EventEmitter {
161
175
  */
162
176
  async activateSession(sessionId, options = {}) {
163
177
  sessionId = String(sessionId); // Normalize — Rails sends integers, Map keys must match
178
+ // #488: an activation can now wait on an idle stop. A second one for the
179
+ // same session waits its turn, then reuses the process the first spawned.
180
+ const previous = this._activations.get(sessionId);
181
+ const run = (previous ? previous.catch(() => {}) : Promise.resolve())
182
+ .then(() => this._activate(sessionId, options));
183
+ this._activations.set(sessionId, run);
184
+ try {
185
+ return await run;
186
+ } finally {
187
+ if (this._activations.get(sessionId) === run) this._activations.delete(sessionId);
188
+ }
189
+ }
190
+
191
+ async _activate(sessionId, options) {
164
192
  // #348: a process being stopped still reports alive until it exits.
165
193
  // Reusing it would hand back a process that is about to die, so wait for
166
194
  // the stop to finish, then spawn.
@@ -196,19 +224,50 @@ class Daemon extends EventEmitter {
196
224
  // milliseconds apart, and the process being stopped counts until it
197
225
  // exits. At capacity, wait (bounded) for the stops in flight, then check
198
226
  // again.
227
+ //
228
+ // #488: still full, stop the longest-idle process and take its slot. The
229
+ // slot is reserved before the first await, so two activations at once
230
+ // never take one slot twice.
199
231
  const maxSessions = this.maxSessions;
200
- if (this.activeCount >= maxSessions && this._stopping.size > 0) {
232
+ if (this._slotsTaken() >= maxSessions && this._stopping.size > 0) {
201
233
  this._logger.info('At capacity with stops in flight, waiting for them', {
202
234
  sessionId, stopping: this._stopping.size,
203
235
  });
204
236
  await this._waitForStops(this._config.stopWaitMs ?? STOP_WAIT_MS);
205
237
  }
206
- if (this.activeCount >= maxSessions) {
207
- throw new Error(
208
- `Max session capacity reached (${maxSessions}). Cannot create session "${sessionId}".`
209
- );
238
+ let victim = null;
239
+ if (this._slotsTaken() >= maxSessions) {
240
+ victim = this._longestIdle(sessionId);
241
+ if (!victim) throw new Error(this._capacityRefusal(sessionId, maxSessions));
242
+ }
243
+ let reserved = false;
244
+ const reserveSlot = () => {
245
+ if (!reserved) this._reservedSlots += 1;
246
+ reserved = true;
247
+ };
248
+ const releaseSlot = () => {
249
+ if (reserved) this._reservedSlots -= 1;
250
+ reserved = false;
251
+ };
252
+ // The victim holds its slot until its CLI has exited, then hands it
253
+ // straight to this activation.
254
+ if (!victim) reserveSlot();
255
+
256
+ try {
257
+ if (victim) {
258
+ this._logger.info('At capacity, stopping the longest-idle session for a new one', {
259
+ sessionId, stopped: victim.sessionId, pid: victim.proc.pid,
260
+ idleSeconds: Math.round(victim.idleMs / 1000),
261
+ });
262
+ await this._stopIdle(victim.sessionId, victim.proc, reserveSlot);
263
+ }
264
+ return await this._spawnSession(sessionId, options, releaseSlot);
265
+ } finally {
266
+ releaseSlot();
210
267
  }
268
+ }
211
269
 
270
+ async _spawnSession(sessionId, options, releaseSlot) {
212
271
  // Reuse the Claude CLI session ID from a cancelled session to preserve
213
272
  // conversation context, or use the one provided in options (e.g. from Rails DB
214
273
  // after daemon restart), or generate new.
@@ -258,6 +317,7 @@ class Daemon extends EventEmitter {
258
317
  // Store in pool
259
318
  this._processes.set(sessionId, proc);
260
319
  this._exitedSessions.delete(sessionId);
320
+ releaseSlot(); // the process holds the slot now
261
321
 
262
322
  // #480: a harness that learns its vendor session id after the child
263
323
  // starts (Codex: the thread id) says so with ready(). The id is what Rails
@@ -410,7 +470,22 @@ class Daemon extends EventEmitter {
410
470
  async terminateSession(sessionId) {
411
471
  sessionId = String(sessionId);
412
472
  const proc = this._processes.get(sessionId);
413
- if (!proc) return;
473
+ if (!proc) {
474
+ // #488: an idle stop already has it; Rails ending the chat means it
475
+ // will not resume, so drop what a resume would use.
476
+ // A resume waiting on the same stop goes first, with the chat's model
477
+ // and persona; then its process is stopped like any other.
478
+ if (this._idleStopping.has(sessionId)) {
479
+ await this._stopping.get(sessionId)?.done;
480
+ const resume = this._activations.get(sessionId);
481
+ if (resume) {
482
+ await resume.catch(() => {});
483
+ return this.terminateSession(sessionId);
484
+ }
485
+ if (!this._processes.has(sessionId)) this._forgetSession(sessionId);
486
+ }
487
+ return;
488
+ }
414
489
 
415
490
  const inFlight = this._stopping.get(sessionId);
416
491
  if (inFlight && inFlight.proc === proc) return inFlight.done;
@@ -422,9 +497,147 @@ class Daemon extends EventEmitter {
422
497
  // remove only the one this call stopped.
423
498
  if (this._processes.get(sessionId) === proc) {
424
499
  this._processes.delete(sessionId);
425
- this._cancelledSessionIds.delete(sessionId);
426
- this._spawnOptions.delete(sessionId);
427
- this._exitedSessions.delete(sessionId);
500
+ this._forgetSession(sessionId);
501
+ }
502
+ })();
503
+ this._stopping.set(sessionId, { proc, done });
504
+ try {
505
+ await done;
506
+ } finally {
507
+ if (this._stopping.get(sessionId)?.done === done) this._stopping.delete(sessionId);
508
+ }
509
+ }
510
+
511
+ _forgetSession(sessionId) {
512
+ this._cancelledSessionIds.delete(sessionId);
513
+ this._spawnOptions.delete(sessionId);
514
+ this._exitedSessions.delete(sessionId);
515
+ }
516
+
517
+ /**
518
+ * #488: every slot in use: live processes, idle stops still exiting, and
519
+ * activations past the capacity check that have not spawned yet.
520
+ * @returns {number}
521
+ */
522
+ _slotsTaken() {
523
+ return this.activeCount + this._idleStopping.size + this._reservedSlots;
524
+ }
525
+
526
+ /**
527
+ * #488: true when nothing waits on the process: no turn running or queued,
528
+ * no permission prompt or question waiting on an answer. A harness that
529
+ * can't tell is never idle.
530
+ */
531
+ _isIdle(sessionId, proc) {
532
+ if (typeof proc.isBusy !== 'function' || proc.isBusy()) return false;
533
+ if (this._permissionBroker?.hasPendingForSession?.(sessionId)) return false;
534
+ return !this._stopping.has(sessionId);
535
+ }
536
+
537
+ /**
538
+ * #488: stopping the process loses nothing. Its chat resumes on its next
539
+ * message (the CLI has a transcript), and nothing the CLI started runs on
540
+ * between turns (background shells, subagents, monitors, timers). A
541
+ * harness that can't tell is never stopped.
542
+ */
543
+ _safeToStop(sessionId, proc) {
544
+ if (!this._isIdle(sessionId, proc)) return false;
545
+ if (typeof proc.canResume !== 'function' || !proc.canResume()) return false;
546
+ if (typeof proc.hasBackgroundWork !== 'function' || proc.hasBackgroundWork()) return false;
547
+ return !!proc.claudeSessionId;
548
+ }
549
+
550
+ /**
551
+ * #488: every process a full pilot may stop for a new chat, longest idle
552
+ * first: alive, safe to stop, and idle at least evictIdleAfter seconds.
553
+ *
554
+ * @param {string} [forSessionId] - the session being activated; never chosen
555
+ * @returns {Array<{sessionId: string, proc: object, idleMs: number}>}
556
+ */
557
+ _evictable(forSessionId = null) {
558
+ const floorMs = (this._config.evictIdleAfter ?? EVICT_IDLE_AFTER) * 1000;
559
+ if (!(floorMs > 0)) return [];
560
+
561
+ const now = Date.now();
562
+ const found = [];
563
+ for (const [sessionId, proc] of this._processes) {
564
+ if (sessionId === forSessionId || !proc.isAlive() || !proc.lastActivityAt) continue;
565
+ const idleMs = now - proc.lastActivityAt;
566
+ if (idleMs < floorMs || !this._safeToStop(sessionId, proc)) continue;
567
+ found.push({ sessionId, proc, idleMs });
568
+ }
569
+ return found.sort((a, b) => b.idleMs - a.idleMs);
570
+ }
571
+
572
+ _longestIdle(forSessionId) {
573
+ return this._evictable(forSessionId)[0] || null;
574
+ }
575
+
576
+ /**
577
+ * #488: how many running processes a new chat could stop. The heartbeat
578
+ * reports it (session_summary.evictable_sessions), so Rails doesn't call a
579
+ * pilot full while it could make room.
580
+ * @returns {number}
581
+ */
582
+ evictableCount() {
583
+ return this._evictable().length;
584
+ }
585
+
586
+ /**
587
+ * #488: Rails reads the cap from the prefix (SessionPreparationService::
588
+ * CAPACITY_REFUSAL); the rest is for Chris.
589
+ */
590
+ _capacityRefusal(sessionId, maxSessions) {
591
+ const pilot = this._config.daemonId || os.hostname();
592
+ const running = this.activeCount + this._idleStopping.size;
593
+ const starting = this._reservedSlots;
594
+ const floor = this._config.evictIdleAfter ?? EVICT_IDLE_AFTER;
595
+ let state = `running ${running} of ${maxSessions} sessions`;
596
+ if (starting > 0) state += ` with ${starting} more starting`;
597
+ if (floor > 0) state += `${starting > 0 ? ',' : ''} and none has been idle for ${_duration(floor)}`;
598
+ return `Max session capacity reached (${maxSessions}). Pilot "${pilot}" is ${state}. ` +
599
+ `Cannot create session "${sessionId}".`;
600
+ }
601
+
602
+ /**
603
+ * Stop an idle process and keep what its chat needs to resume: its
604
+ * _spawnOptions (claude session id, model, persona). The stale reap and
605
+ * #488's eviction both stop processes this way.
606
+ *
607
+ * The process leaves the pool at once, so a command for it takes the resume
608
+ * path (activateSession, which waits for this stop) and is never written to
609
+ * a CLI that is exiting. It holds its slot until its CLI has exited, or
610
+ * idleStopExitWaitMs after kill() returns; kill() can give up first.
611
+ *
612
+ * @param {string} sessionId
613
+ * @param {object} proc
614
+ * @param {Function} [takeSlot] - called as the slot is freed, so the
615
+ * activation that made the stop holds it with no gap
616
+ * @returns {Promise<void>}
617
+ */
618
+ async _stopIdle(sessionId, proc, takeSlot = null) {
619
+ if (this._processes.get(sessionId) === proc) this._processes.delete(sessionId);
620
+ this._cancelledSessionIds.delete(sessionId);
621
+ this._idleStopping.set(sessionId, proc);
622
+ this._idleStopped.add(proc);
623
+ const exited = proc.isAlive() ? new Promise((resolve) => proc.once('exit', () => resolve(true))) : Promise.resolve(true);
624
+
625
+ const done = (async () => {
626
+ try {
627
+ await proc.kill();
628
+ let timer;
629
+ const waitMs = this._config.idleStopExitWaitMs ?? IDLE_STOP_EXIT_WAIT_MS;
630
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(false), waitMs); });
631
+ const sawExit = await Promise.race([exited, timeout]);
632
+ clearTimeout(timer);
633
+ if (!sawExit) {
634
+ this._logger.warn('Stopped idle session has not exited; freeing its slot', { sessionId, pid: proc.pid, waitMs });
635
+ }
636
+ } catch (err) {
637
+ this._logger.error('Failed to stop idle session', { sessionId, error: err.message });
638
+ } finally {
639
+ if (this._idleStopping.get(sessionId) === proc) this._idleStopping.delete(sessionId);
640
+ if (takeSlot) takeSlot();
428
641
  }
429
642
  })();
430
643
  this._stopping.set(sessionId, { proc, done });
@@ -620,6 +833,11 @@ class Daemon extends EventEmitter {
620
833
  for (const [sessionId, proc] of this._processes) {
621
834
  if (!proc.isAlive()) {
622
835
  deadSessions.push(sessionId);
836
+ } else if (this._stopping.has(sessionId) || (typeof proc.isBusy === 'function' && !this._isIdle(sessionId, proc)) ||
837
+ proc.canResume?.() === false || proc.hasBackgroundWork?.() === true) {
838
+ // #488: never mid-turn, waiting on an answer, untouched (nothing to
839
+ // resume) or running background work.
840
+ continue;
623
841
  } else if (staleTimeoutMs > 0 && proc.lastActivityAt) {
624
842
  const idleMs = now - proc.lastActivityAt;
625
843
  if (idleMs > staleTimeoutMs) {
@@ -644,15 +862,7 @@ class Daemon extends EventEmitter {
644
862
  threshold: this._config.staleSessionTimeout,
645
863
  });
646
864
  const proc = this._processes.get(sessionId);
647
- if (proc) {
648
- try {
649
- await proc.kill();
650
- } catch (err) {
651
- this._logger.error('Failed to kill stale session', { sessionId, error: err.message });
652
- }
653
- this._processes.delete(sessionId);
654
- this._cancelledSessionIds.delete(sessionId);
655
- }
865
+ if (proc) await this._stopIdle(sessionId, proc);
656
866
  }
657
867
 
658
868
  const removed = deadSessions.length + staleSessions.length;
@@ -831,16 +1041,31 @@ class Daemon extends EventEmitter {
831
1041
  });
832
1042
 
833
1043
  proc.on('exit', (code, signal, turns = {}) => {
834
- this._permissionBroker?.denyAllForSession(sessionId, 'Session ended');
1044
+ // #488: an idle stop's process held no prompt; one that exits late
1045
+ // must not deny the resumed process's.
1046
+ const idleStop = this._idleStopped.has(proc);
1047
+ if (!idleStop) this._permissionBroker?.denyAllForSession(sessionId, 'Session ended');
835
1048
  this._recordExit(sessionId);
836
1049
  this.emit('session:exit', {
837
1050
  sessionId, code, signal,
838
1051
  commandId: turns.commandId, unfinishedCommandIds: turns.unfinishedCommandIds,
839
1052
  readCommandIds: turns.readCommandIds,
1053
+ // #488: stopped while idle. Any command for the session now waits for
1054
+ // its resume, so the exit closes none of them.
1055
+ idleStop,
840
1056
  });
841
1057
  });
842
1058
  }
843
1059
  }
844
1060
 
1061
+ // 300 -> "5 minutes", 60 -> "1 minute", 90 -> "90 seconds"
1062
+ function _duration(seconds) {
1063
+ if (seconds % 60 === 0) {
1064
+ const minutes = seconds / 60;
1065
+ return `${minutes} minute${minutes === 1 ? '' : 's'}`;
1066
+ }
1067
+ return `${seconds} second${seconds === 1 ? '' : 's'}`;
1068
+ }
1069
+
845
1070
  module.exports = Daemon;
846
1071
  module.exports.MAX_EXITED_SPAWN_OPTIONS = MAX_EXITED_SPAWN_OPTIONS;
package/src/harness.js CHANGED
@@ -33,6 +33,9 @@
33
33
  * (code, signal, turns), 'spawned'. Optional: 'permission_request',
34
34
  * 'permission_cancelled', 'ask_user_question', 'ask_user_question_released'
35
35
  * with respondToPermission / answerQuestion / heldQuestions.
36
+ * Optional (#488): isBusy() and a lastActivityAt getter. A pilot at its cap
37
+ * stops the longest-idle process that is not busy to start a new chat; a
38
+ * harness without them is never stopped early.
36
39
  */
37
40
  const HARNESS_CONTRACT = Object.freeze({
38
41
  methods: ['spawn', 'sendMessage', 'interrupt', 'kill', 'isAlive', 'unfinishedCommandIds', 'readCommandIds', 'on', 'emit'],
@@ -135,6 +135,18 @@ class PermissionBroker extends EventEmitter {
135
135
  }
136
136
  }
137
137
 
138
+ /**
139
+ * #488: a prompt the session raised still waits for an answer.
140
+ * @param {string} sessionId
141
+ * @returns {boolean}
142
+ */
143
+ hasPendingForSession(sessionId) {
144
+ for (const pending of this._pending.values()) {
145
+ if (pending.sessionId === sessionId) return true;
146
+ }
147
+ return false;
148
+ }
149
+
138
150
  /**
139
151
  * Find the request id a session raised for a given CLI control request.
140
152
  * @param {string} sessionId
@@ -42,6 +42,7 @@ class TurnTracker {
42
42
  this._current = undefined; // commandId read last; undefined until one is read
43
43
  this._newestWritten = null;
44
44
  this._takenAtInit = null; // #224: the written entry a turn's init took, until the turn ends
45
+ this._tookMessage = false; // #488: the CLI echoed a message it took, so it has a transcript
45
46
  }
46
47
 
47
48
  /** A message was written to the CLI's stdin. */
@@ -68,6 +69,7 @@ class TurnTracker {
68
69
  }
69
70
 
70
71
  if (data.type === 'user' && data.isReplay === true) {
72
+ this._tookMessage = true;
71
73
  if (!this._turn) this._turn = { commandIds: [] };
72
74
  const index = this._written.findIndex((entry) => entry.text === _textOf(data.message));
73
75
  // Stdin is read in order, so anything written before it was read too.
@@ -102,6 +104,22 @@ class TurnTracker {
102
104
  return this._newestWritten;
103
105
  }
104
106
 
107
+ /**
108
+ * #488: the CLI has taken a message (it echoed one), so it has written a
109
+ * transcript that `--resume` can open. A slash command alone writes none.
110
+ */
111
+ get tookMessage() {
112
+ return this._tookMessage;
113
+ }
114
+
115
+ /**
116
+ * #488: a turn is running, or a written message waits for one. A full
117
+ * pilot never stops a busy process to make room.
118
+ */
119
+ get busy() {
120
+ return !!this._turn || this._written.length > 0;
121
+ }
122
+
105
123
  /** Every command written to this process that no result has ended yet. */
106
124
  unfinishedCommandIds() {
107
125
  const ids = [