@radnine/claude-session-daemon 0.8.3 → 0.9.2

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.
@@ -23,12 +23,14 @@ class BaseConnection extends EventEmitter {
23
23
 
24
24
  // Wire daemon events to the send methods so subclasses get
25
25
  // automatic forwarding without extra setup.
26
- this._daemon.on('session:output', ({ sessionId, data }) => {
27
- this.sendOutput(sessionId, null, data);
26
+ // #175: the process says which command a line or an exit belongs to.
27
+ // commandId is undefined when it can't tell; subclasses fall back then.
28
+ this._daemon.on('session:output', ({ sessionId, data, commandId, turnCommandIds }) => {
29
+ this.sendOutput(sessionId, commandId ?? null, data, { turnCommandIds });
28
30
  });
29
31
 
30
- this._daemon.on('session:exit', ({ sessionId, code, signal }) => {
31
- this.sendComplete(sessionId, null, code, 0);
32
+ this._daemon.on('session:exit', ({ sessionId, code, signal, commandId, unfinishedCommandIds, readCommandIds }) => {
33
+ this.sendComplete(sessionId, commandId ?? null, code, 0, { unfinishedCommandIds, readCommandIds });
32
34
  });
33
35
 
34
36
  this._daemon.on('session:error', ({ sessionId, data }) => {
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+ const crypto = require('node:crypto');
3
+
4
+ // Receipts survive Rails reconnects for this daemon process only. Rails retries
5
+ // for ten minutes; keeping receipts for an hour includes clock/transport margin.
6
+ const REPLAY_WINDOW_MS = 10 * 60 * 1000;
7
+ const RETENTION_MS = 60 * 60 * 1000;
8
+ class CommandReceipts {
9
+ constructor({ maxEntries = 10000, now = Date.now } = {}) {
10
+ this.epoch = crypto.randomUUID();
11
+ this.entries = new Map();
12
+ this.maxEntries = maxEntries;
13
+ this.now = now;
14
+ this.saturated = false;
15
+ }
16
+ accept(message) {
17
+ const key = `${String(message.session_id)}:${String(message.command_id)}`;
18
+ const now = this.now();
19
+ if (message.delivery_epoch !== this.epoch) return 'epoch_changed';
20
+ const prior = this.entries.get(key);
21
+ if (prior) return 'duplicate';
22
+ const attempted = Date.parse(message.delivery_attempted_at);
23
+ if (!Number.isFinite(attempted) || now - attempted > REPLAY_WINDOW_MS || attempted > now + 60000) {
24
+ return 'expired';
25
+ }
26
+ // A saturated epoch never admits new IDs again. This also remembers every
27
+ // rejection without an unbounded rejection-tombstone collection.
28
+ if (this.saturated) return 'capacity';
29
+ for (const [id, time] of this.entries) if (now - time > RETENTION_MS) this.entries.delete(id);
30
+ if (this.entries.size >= this.maxEntries) {
31
+ this.saturated = true;
32
+ return 'capacity';
33
+ }
34
+ this.entries.set(key, now); // synchronous, before activation or stdin awaits
35
+ return 'accepted';
36
+ }
37
+ }
38
+ module.exports = { CommandReceipts, REPLAY_WINDOW_MS, RETENTION_MS };
package/src/daemon.js CHANGED
@@ -1,8 +1,20 @@
1
1
  'use strict';
2
2
 
3
3
  const { EventEmitter } = require('node:events');
4
- const ClaudeProcess = require('./claude-process');
4
+ const { createHarnessProcess } = require('./harness');
5
5
  const { resetGitState } = require('./git-reset');
6
+ const { usageFromRateLimitEvent } = require('./claude-usage');
7
+
8
+ // #348: longest an activation at capacity waits for stops in flight. A
9
+ // ClaudeProcess kill takes up to 7 s (5 s after SIGTERM, then 2 s after
10
+ // SIGKILL).
11
+ const STOP_WAIT_MS = 8000;
12
+
13
+ // #109: most sessions whose CLI exited on its own that keep their
14
+ // _spawnOptions. A command for one resumes it with its model and persona
15
+ // (#80); past this many, the oldest exit is dropped and Rails' next
16
+ // session_activate carries them instead.
17
+ const MAX_EXITED_SPAWN_OPTIONS = 100;
6
18
 
7
19
  /**
8
20
  * Process pool manager for Claude CLI sessions.
@@ -30,6 +42,11 @@ class Daemon extends EventEmitter {
30
42
 
31
43
  this._processes = new Map(); // sessionId -> ClaudeProcess
32
44
  this._cancelledSessionIds = new Map(); // sessionId -> claudeSessionId (for resume after cancel)
45
+ this._claudeUsage = null; // #258: { usage, accountUuid } — latest account usage from any CLI child
46
+ this._claudeAccountUuid = null; // #258: the account the last heartbeat reported
47
+ this._spawnOptions = new Map(); // sessionId -> options of its last spawn (for a resume without Rails)
48
+ this._exitedSessions = new Set(); // sessionIds in _spawnOptions with no running process, oldest exit first (#109)
49
+ this._stopping = new Map(); // sessionId -> { proc, done } while terminateSession kills it (#348)
33
50
  this._config = config;
34
51
  this._logger = logger;
35
52
  this._running = false;
@@ -38,12 +55,26 @@ class Daemon extends EventEmitter {
38
55
  this._createProcess = options._createProcess || this._defaultCreateProcess.bind(this);
39
56
  this._shutdownHandler = null;
40
57
  this._cleanupRunning = false;
58
+ this._permissionBroker = null;
59
+ this._assignedMaxSessions = null; // #436: the cap Rails assigned on registration
41
60
  }
42
61
 
43
62
  // -------------------------------------------------------------------------
44
63
  // Public API
45
64
  // -------------------------------------------------------------------------
46
65
 
66
+ /**
67
+ * Attach the broker that holds permission prompts while an operator decides.
68
+ *
69
+ * Without one, a session that raises a prompt has nowhere to send it, and the
70
+ * CLI is denied immediately rather than blocking forever.
71
+ *
72
+ * @param {PermissionBroker} broker
73
+ */
74
+ setPermissionBroker(broker) {
75
+ this._permissionBroker = broker;
76
+ }
77
+
47
78
  /**
48
79
  * Start the daemon — begin cleanup/health timers, register signal handlers.
49
80
  */
@@ -130,6 +161,15 @@ class Daemon extends EventEmitter {
130
161
  */
131
162
  async activateSession(sessionId, options = {}) {
132
163
  sessionId = String(sessionId); // Normalize — Rails sends integers, Map keys must match
164
+ // #348: a process being stopped still reports alive until it exits.
165
+ // Reusing it would hand back a process that is about to die, so wait for
166
+ // the stop to finish, then spawn.
167
+ const stopping = this._stopping.get(sessionId);
168
+ if (stopping) {
169
+ this._logger.info('Waiting for session stop before activation', { sessionId });
170
+ await stopping.done.catch(() => {}); // terminateSession's caller hears of a failed kill
171
+ }
172
+
133
173
  // If process exists and alive, return it. Note: any updated options on this
134
174
  // call (including systemPrompt) are intentionally ignored — the Claude CLI's
135
175
  // system prompt is immutable post-spawn, so we'd be silently lying if we
@@ -146,10 +186,26 @@ class Daemon extends EventEmitter {
146
186
  this._processes.delete(sessionId);
147
187
  }
148
188
 
149
- // Check capacity
150
- if (this._processes.size >= this._config.maxSessions) {
189
+ // Check capacity. activeCount prunes processes that exited on their own
190
+ // first; until something touched them they kept their slot, so a pilot
191
+ // could refuse activations while running fewer than maxSessions (#348).
192
+ // Their resume ids live in _cancelledSessionIds and _spawnOptions, which
193
+ // are left alone (the newest MAX_EXITED_SPAWN_OPTIONS of them, #109).
194
+ //
195
+ // #348: Rails stops a rotated session and activates its replacement
196
+ // milliseconds apart, and the process being stopped counts until it
197
+ // exits. At capacity, wait (bounded) for the stops in flight, then check
198
+ // again.
199
+ const maxSessions = this.maxSessions;
200
+ if (this.activeCount >= maxSessions && this._stopping.size > 0) {
201
+ this._logger.info('At capacity with stops in flight, waiting for them', {
202
+ sessionId, stopping: this._stopping.size,
203
+ });
204
+ await this._waitForStops(this._config.stopWaitMs ?? STOP_WAIT_MS);
205
+ }
206
+ if (this.activeCount >= maxSessions) {
151
207
  throw new Error(
152
- `Max session capacity reached (${this._config.maxSessions}). Cannot create session "${sessionId}".`
208
+ `Max session capacity reached (${maxSessions}). Cannot create session "${sessionId}".`
153
209
  );
154
210
  }
155
211
 
@@ -161,6 +217,14 @@ class Daemon extends EventEmitter {
161
217
  const shouldResume = !!claudeSessionId;
162
218
  this._cancelledSessionIds.delete(sessionId);
163
219
 
220
+ // A resume the daemon starts on its own (cancel respawn, a command after
221
+ // the process died) carries no model or persona. Keep the chat's own.
222
+ const previous = this._spawnOptions.get(sessionId);
223
+ const inherited = shouldResume && previous ? previous : {};
224
+ const systemPrompt = options.systemPrompt || inherited.systemPrompt;
225
+ const model = options.model || inherited.model;
226
+ const effort = options.effort || inherited.effort;
227
+
164
228
  // Reset git state to clean main when requested (scheduled sessions).
165
229
  // Awaited so spawn waits for a clean tree, but async under the hood so the
166
230
  // event loop keeps servicing ActionCable pings during the git commands.
@@ -176,12 +240,12 @@ class Daemon extends EventEmitter {
176
240
  claudeSessionId,
177
241
  resume: shouldResume,
178
242
  claudeCommand: this._config.claudeCommand || 'claude',
179
- skipPermissions: this._config.skipPermissions,
180
- permissionPort: this._permissionPort || null,
243
+ codexCommand: this._config.codexCommand || 'codex',
244
+ permissionMode: this._config.permissionMode || 'auto',
181
245
  sessionEnv: options.sessionEnv || {},
182
- systemPrompt: options.systemPrompt,
183
- model: options.model,
184
- effort: options.effort,
246
+ systemPrompt,
247
+ model,
248
+ effort,
185
249
  logger: this._logger.child(`Session:${sessionId}`),
186
250
  });
187
251
 
@@ -193,12 +257,48 @@ class Daemon extends EventEmitter {
193
257
 
194
258
  // Store in pool
195
259
  this._processes.set(sessionId, proc);
260
+ this._exitedSessions.delete(sessionId);
261
+
262
+ // #480: a harness that learns its vendor session id after the child
263
+ // starts (Codex: the thread id) says so with ready(). The id is what Rails
264
+ // stores to resume the chat, so wait for it before reporting it.
265
+ if (typeof proc.ready === 'function') {
266
+ try {
267
+ await proc.ready();
268
+ } catch (err) {
269
+ this._processes.delete(sessionId);
270
+ await proc.kill().catch(() => {});
271
+ throw err;
272
+ }
273
+ }
274
+
275
+ this._spawnOptions.set(sessionId, {
276
+ claudeSessionId: proc.claudeSessionId,
277
+ systemPrompt,
278
+ model,
279
+ effort,
280
+ });
196
281
 
197
282
  this._logger.info('Session activated', { sessionId, activeCount: this._processes.size });
198
283
 
199
284
  return proc;
200
285
  }
201
286
 
287
+ /**
288
+ * The Claude CLI session id this daemon last ran the session with, or null
289
+ * if it has never spawned it (e.g. after a daemon restart). Only Rails can
290
+ * say how to start a session the daemon doesn't know.
291
+ *
292
+ * @param {string} sessionId
293
+ * @returns {string|null}
294
+ */
295
+ knownClaudeSessionId(sessionId) {
296
+ sessionId = String(sessionId);
297
+ return this._cancelledSessionIds.get(sessionId)
298
+ || this._spawnOptions.get(sessionId)?.claudeSessionId
299
+ || null;
300
+ }
301
+
202
302
  /**
203
303
  * Find process by session ID. Returns null if not found or dead.
204
304
  *
@@ -223,15 +323,83 @@ class Daemon extends EventEmitter {
223
323
  *
224
324
  * @param {string} sessionId
225
325
  * @param {string} text
326
+ * @param {string|null} [commandId] - the Rails command, so output can be tagged with it (#175)
226
327
  * @throws {Error} if session not found
227
328
  */
228
- sendMessage(sessionId, text) {
329
+ sendMessage(sessionId, text, commandId = null) {
229
330
  sessionId = String(sessionId);
230
331
  const proc = this.getProcess(sessionId);
231
332
  if (!proc) {
232
333
  throw new Error(`Session not found: "${sessionId}"`);
233
334
  }
234
- return proc.sendMessage(text);
335
+ return proc.sendMessage(text, commandId);
336
+ }
337
+
338
+ /**
339
+ * #175: the commands the session's CLI was handed that no result has
340
+ * ended yet (the running turn, then every one it hasn't read).
341
+ *
342
+ * @param {string} sessionId
343
+ * @returns {Array|undefined} undefined when there is no live process
344
+ */
345
+ unfinishedCommandIds(sessionId) {
346
+ const proc = this.getProcess(String(sessionId));
347
+ return proc && typeof proc.unfinishedCommandIds === 'function' ? proc.unfinishedCommandIds() : undefined;
348
+ }
349
+
350
+ /**
351
+ * #175: the command the session's CLI read last, or undefined when the
352
+ * daemon can't tell (no live process, or it hasn't read a message yet).
353
+ *
354
+ * @param {string} sessionId
355
+ * @returns {string|null|undefined}
356
+ */
357
+ currentCommandId(sessionId) {
358
+ const proc = this.getProcess(String(sessionId));
359
+ return proc ? proc.currentCommandId : undefined;
360
+ }
361
+
362
+ /**
363
+ * #130: answer an AskUserQuestion the session's process is holding.
364
+ *
365
+ * @param {string} sessionId
366
+ * @param {string} controlRequestId
367
+ * @param {Object<string,string>} answers - question text -> label(s) or discussion note
368
+ * @returns {boolean} false when the process or the held request is gone
369
+ */
370
+ answerQuestion(sessionId, controlRequestId, answers) {
371
+ const proc = this.getProcess(String(sessionId));
372
+ if (!proc || typeof proc.answerQuestion !== 'function') return false;
373
+ return proc.answerQuestion(controlRequestId, answers);
374
+ }
375
+
376
+ /**
377
+ * #130: every AskUserQuestion still held, across live sessions.
378
+ * @returns {Array<{sessionId: string, controlRequestId: string, toolUseId: string|null, questions: Array}>}
379
+ */
380
+ heldQuestions() {
381
+ const held = [];
382
+ for (const [sessionId, proc] of this._processes) {
383
+ if (!proc.isAlive() || typeof proc.heldQuestions !== 'function') continue;
384
+ for (const question of proc.heldQuestions()) held.push({ sessionId, ...question });
385
+ }
386
+ return held;
387
+ }
388
+
389
+ /**
390
+ * Resolves when every stop in flight has finished, or after `ms`.
391
+ * @param {number} ms
392
+ * @returns {Promise<void>}
393
+ */
394
+ async _waitForStops(ms) {
395
+ let timer;
396
+ const timeout = new Promise((resolve) => { timer = setTimeout(resolve, ms); });
397
+ const stops = Promise.allSettled([...this._stopping.values()].map((s) => s.done));
398
+ try {
399
+ await Promise.race([stops, timeout]);
400
+ } finally {
401
+ clearTimeout(timer);
402
+ }
235
403
  }
236
404
 
237
405
  /**
@@ -244,10 +412,27 @@ class Daemon extends EventEmitter {
244
412
  const proc = this._processes.get(sessionId);
245
413
  if (!proc) return;
246
414
 
415
+ const inFlight = this._stopping.get(sessionId);
416
+ if (inFlight && inFlight.proc === proc) return inFlight.done;
417
+
247
418
  this._logger.info('Terminating session', { sessionId });
248
- await proc.kill();
249
- this._processes.delete(sessionId);
250
- this._cancelledSessionIds.delete(sessionId);
419
+ const done = (async () => {
420
+ await proc.kill();
421
+ // #348: an activation may have put a new process here meanwhile;
422
+ // remove only the one this call stopped.
423
+ if (this._processes.get(sessionId) === proc) {
424
+ this._processes.delete(sessionId);
425
+ this._cancelledSessionIds.delete(sessionId);
426
+ this._spawnOptions.delete(sessionId);
427
+ this._exitedSessions.delete(sessionId);
428
+ }
429
+ })();
430
+ this._stopping.set(sessionId, { proc, done });
431
+ try {
432
+ await done;
433
+ } finally {
434
+ if (this._stopping.get(sessionId)?.done === done) this._stopping.delete(sessionId);
435
+ }
251
436
  }
252
437
 
253
438
  /**
@@ -317,6 +502,10 @@ class Daemon extends EventEmitter {
317
502
  };
318
503
  }
319
504
 
505
+ // Interrupting means "stop what you are doing", which includes any prompt
506
+ // still waiting on an answer.
507
+ this._permissionBroker?.denyAllForSession(sessionId, 'Turn interrupted');
508
+
320
509
  const sent = proc.interrupt();
321
510
  return {
322
511
  success: sent,
@@ -330,6 +519,35 @@ class Daemon extends EventEmitter {
330
519
  * Count of active processes.
331
520
  * @returns {number}
332
521
  */
522
+ /**
523
+ * The most sessions this daemon will run: its own CLAUDE_MAX_SESSIONS
524
+ * ceiling, lowered to the cap Rails assigned if that is smaller (#436).
525
+ * @returns {number}
526
+ */
527
+ get maxSessions() {
528
+ const ceiling = this._config.maxSessions;
529
+ return this._assignedMaxSessions ? Math.min(this._assignedMaxSessions, ceiling) : ceiling;
530
+ }
531
+
532
+ /**
533
+ * This daemon's own ceiling (CLAUDE_MAX_SESSIONS), which it reports to
534
+ * Rails so Rails never routes past it (#436).
535
+ * @returns {number}
536
+ */
537
+ get maxSessionsCeiling() {
538
+ return this._config.maxSessions;
539
+ }
540
+
541
+ /**
542
+ * Apply the cap Rails assigned on registration. Anything but a positive
543
+ * integer clears it, and the daemon falls back to its own ceiling.
544
+ * @param {*} value
545
+ */
546
+ setAssignedMaxSessions(value) {
547
+ const cap = Number(value);
548
+ this._assignedMaxSessions = Number.isInteger(cap) && cap > 0 ? cap : null;
549
+ }
550
+
333
551
  get activeCount() {
334
552
  // Remove only dead processes synchronously (stale reaping is async, handled by timer)
335
553
  for (const [sessionId, proc] of this._processes) {
@@ -371,7 +589,8 @@ class Daemon extends EventEmitter {
371
589
  return {
372
590
  running: this._running,
373
591
  activeProcesses: this._processes.size,
374
- maxSessions: this._config.maxSessions,
592
+ maxSessions: this.maxSessions,
593
+ maxSessionsCeiling: this.maxSessionsCeiling,
375
594
  mode: this._config.mode,
376
595
  };
377
596
  }
@@ -475,28 +694,99 @@ class Daemon extends EventEmitter {
475
694
  }
476
695
 
477
696
  /**
478
- * Default factory for creating ClaudeProcess instances.
697
+ * Default factory: the harness for the session's model (#480). A Codex model
698
+ * id gets the Codex wrapper; everything else gets ClaudeProcess, as before.
479
699
  */
480
700
  _defaultCreateProcess(sessionId, options) {
481
- return new ClaudeProcess(sessionId, options);
701
+ return createHarnessProcess(sessionId, options);
702
+ }
703
+
704
+ /**
705
+ * The account's latest 5-hour and 7-day usage seen on any CLI child, in the
706
+ * heartbeat's claude_usage shape, or null before the first reading (#258).
707
+ * Every session on a pilot runs as the pilot's account, so one is enough.
708
+ *
709
+ * The heartbeat passes the account_uuid it is about to report. A reading
710
+ * taken under a different account is dropped, so it is never shown on the
711
+ * new one; the next rate_limit_event brings a fresh reading. An unknown
712
+ * account (null) keeps the reading: Rails ignores usage without an account.
713
+ *
714
+ * @param {string|null} [accountUuid]
715
+ * @returns {object|null}
716
+ */
717
+ claudeUsage(accountUuid = null) {
718
+ if (accountUuid) {
719
+ this._claudeAccountUuid = accountUuid;
720
+ const cached = this._claudeUsage;
721
+ if (cached && !cached.accountUuid) cached.accountUuid = accountUuid;
722
+ if (cached && cached.accountUuid !== accountUuid) this._claudeUsage = null;
723
+ }
724
+ return this._claudeUsage?.usage ?? null;
725
+ }
726
+
727
+ _recordClaudeUsage(event) {
728
+ const usage = usageFromRateLimitEvent(event, this._claudeUsage?.usage);
729
+ if (usage) this._claudeUsage = { usage, accountUuid: this._claudeAccountUuid };
730
+ }
731
+
732
+ // A successful API turn's result with no new rate_limit_event confirms the
733
+ // reading: the CLI sends one whenever a window's rounded percentage or
734
+ // reset time moves. Errors, interrupts and local slash commands (no API
735
+ // time) confirm nothing; re-stamping them would let a pilot's old reading
736
+ // overwrite a newer one from another pilot on the same account.
737
+ _confirmClaudeUsage(result) {
738
+ const cached = this._claudeUsage;
739
+ if (!cached) return;
740
+ if (result.subtype !== 'success' || result.is_error !== false || !(result.duration_api_ms > 0)) return;
741
+ this._claudeUsage = { ...cached, usage: { ...cached.usage, observed_at: new Date().toISOString() } };
742
+ }
743
+
744
+ /**
745
+ * #109: a process exited. Its session keeps its _spawnOptions (#80), and
746
+ * only the newest MAX_EXITED_SPAWN_OPTIONS exits are kept. A session running
747
+ * again (a cancel's respawn, a resume) is never dropped.
748
+ *
749
+ * @param {string} sessionId
750
+ */
751
+ _recordExit(sessionId) {
752
+ if (this._isRunning(sessionId) || !this._spawnOptions.has(sessionId)) return;
753
+ this._exitedSessions.delete(sessionId);
754
+ this._exitedSessions.add(sessionId);
755
+
756
+ for (const oldest of this._exitedSessions) {
757
+ if (this._exitedSessions.size <= MAX_EXITED_SPAWN_OPTIONS) break;
758
+ this._exitedSessions.delete(oldest);
759
+ if (!this._isRunning(oldest)) this._spawnOptions.delete(oldest);
760
+ }
761
+ }
762
+
763
+ // Unlike getProcess, leaves a dead process in the pool for healthCheck.
764
+ _isRunning(sessionId) {
765
+ const proc = this._processes.get(sessionId);
766
+ return !!proc && proc.isAlive();
482
767
  }
483
768
 
484
769
  /**
485
770
  * Wire up event forwarding from a process to the daemon.
486
771
  */
487
772
  _forwardEvents(sessionId, proc) {
488
- proc.on('output', (data) => {
773
+ proc.on('output', (data, tag = {}) => {
489
774
  // Suppress informational rate_limit_event messages (status: "allowed")
490
775
  // These are not actual rate limits — only forward when truly rate-limited
491
776
  if (data?.type === 'rate_limit_event') {
777
+ // #258: every event, allowed or not, updates the usage the heartbeat reports.
778
+ this._recordClaudeUsage(data);
492
779
  const status = data?.rate_limit_info?.status;
493
780
  if (status === 'allowed') {
494
781
  this._logger.debug('Suppressing informational rate_limit_event', { sessionId, status });
495
782
  return;
496
783
  }
497
784
  }
785
+ if (data?.type === 'result') this._confirmClaudeUsage(data);
498
786
 
499
- this.emit('session:output', { sessionId, data });
787
+ this.emit('session:output', {
788
+ sessionId, data, commandId: tag.commandId, turnCommandIds: tag.turnCommandIds,
789
+ });
500
790
  });
501
791
 
502
792
  proc.on('error', (data) => {
@@ -507,10 +797,50 @@ class Daemon extends EventEmitter {
507
797
  this.emit('session:stderr', { sessionId, data });
508
798
  });
509
799
 
510
- proc.on('exit', (code, signal) => {
511
- this.emit('session:exit', { sessionId, code, signal });
800
+ proc.on('permission_request', (req) => {
801
+ if (!this._permissionBroker) {
802
+ // Nothing can reach an operator from here, so let the CLI move on
803
+ // instead of blocking on a prompt nobody will ever see.
804
+ this._logger.warn('Permission request with no broker attached — denying', {
805
+ sessionId,
806
+ toolName: req.toolName,
807
+ });
808
+ proc.respondToPermission(req.controlRequestId, 'deny', 'No permission handler attached');
809
+ return;
810
+ }
811
+
812
+ this._permissionBroker.register(
813
+ { ...req, sessionId },
814
+ (decision, reason) => proc.respondToPermission(req.controlRequestId, decision, reason)
815
+ );
816
+ });
817
+
818
+ proc.on('ask_user_question', (question) => {
819
+ this.emit('session:ask_user_question', { sessionId, ...question });
820
+ });
821
+
822
+ proc.on('ask_user_question_released', (released) => {
823
+ this.emit('session:ask_user_question_released', { sessionId, ...released });
824
+ });
825
+
826
+ proc.on('permission_cancelled', ({ controlRequestId }) => {
827
+ if (!this._permissionBroker) return;
828
+
829
+ const requestId = this._permissionBroker.findByControlRequestId(sessionId, controlRequestId);
830
+ if (requestId) this._permissionBroker.cancel(requestId, 'Cancelled by Claude');
831
+ });
832
+
833
+ proc.on('exit', (code, signal, turns = {}) => {
834
+ this._permissionBroker?.denyAllForSession(sessionId, 'Session ended');
835
+ this._recordExit(sessionId);
836
+ this.emit('session:exit', {
837
+ sessionId, code, signal,
838
+ commandId: turns.commandId, unfinishedCommandIds: turns.unfinishedCommandIds,
839
+ readCommandIds: turns.readCommandIds,
840
+ });
512
841
  });
513
842
  }
514
843
  }
515
844
 
516
845
  module.exports = Daemon;
846
+ module.exports.MAX_EXITED_SPAWN_OPTIONS = MAX_EXITED_SPAWN_OPTIONS;