@radnine/claude-session-daemon 0.9.3 → 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.3",
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
  *
@@ -90,6 +90,7 @@ class CodexProcess extends EventEmitter {
90
90
  this._child = null;
91
91
  this._pid = null;
92
92
  this._startedAt = null;
93
+ this._lastActivityAt = null; // #488: last message in, or stdout/stderr line out
93
94
 
94
95
  this._nextRequestId = 0;
95
96
  this._pending = new Map(); // request id -> { resolve, reject, timer, method }
@@ -154,6 +155,7 @@ class CodexProcess extends EventEmitter {
154
155
 
155
156
  this._pid = this._child.pid;
156
157
  this._startedAt = Date.now();
158
+ this._lastActivityAt = this._startedAt;
157
159
  this._state = 'running';
158
160
 
159
161
  this._setupStdout();
@@ -185,6 +187,7 @@ class CodexProcess extends EventEmitter {
185
187
  }
186
188
 
187
189
  this._turns.written(commandId, text);
190
+ this._lastActivityAt = Date.now();
188
191
  this._inbox.push(text);
189
192
  this._logger.debug('Queued message for Codex', { length: text.length, commandId });
190
193
  this._pump();
@@ -270,8 +273,16 @@ class CodexProcess extends EventEmitter {
270
273
  /** The Codex thread id: what Rails stores and passes back to resume. */
271
274
  get claudeSessionId() { return this._threadId || this._resumeThreadId; }
272
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; }
273
278
  get workingDir() { return this._workingDir; }
274
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; }
275
286
  unfinishedCommandIds() { return this._turns.unfinishedCommandIds(); }
276
287
  readCommandIds() { return this._turns.readCommandIds(); }
277
288
 
@@ -499,6 +510,7 @@ class CodexProcess extends EventEmitter {
499
510
 
500
511
  rl.on('line', (line) => {
501
512
  if (!line) return;
513
+ this._lastActivityAt = Date.now();
502
514
 
503
515
  let message;
504
516
  try {
@@ -537,6 +549,7 @@ class CodexProcess extends EventEmitter {
537
549
 
538
550
  rl.on('line', (line) => {
539
551
  if (!line) return;
552
+ this._lastActivityAt = Date.now();
540
553
  this._logger.warn('Codex stderr', { line });
541
554
  this.emit('stderr', line);
542
555
  });
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 = [