@radnine/claude-session-daemon 0.8.3 → 0.9.3

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.
@@ -6,13 +6,23 @@ const path = require('node:path');
6
6
  const fs = require('node:fs').promises;
7
7
  const WebSocket = require('ws');
8
8
  const { BaseConnection } = require('./base-connection');
9
+ const { CommandReceipts } = require('./command-receipts');
9
10
  const { getGitContext } = require('../git-context');
10
11
  const { getClaudeAccount } = require('../claude-account');
11
12
  const { getMachineEffort } = require('../machine-effort');
12
- const { scanPersonas, readPersonaBody } = require('../persona-scanner');
13
+ const { scanPersonas, readPersonaBody, scanCrewMap, buildCrewHeader, personaSlugFromPath } = require('../persona-scanner');
13
14
  const { handleFsRequest } = require('../fs-bridge');
14
15
  const daemonPkg = require('../../package.json');
15
16
 
17
+ // #109: a session holds at most this many commands for its activation; the
18
+ // next one fails at once with ACTIVATION_QUEUE_FULL.
19
+ const MAX_HELD_COMMANDS_PER_SESSION = 20;
20
+ // #109: once a session_activate is being handled, its held commands wait the
21
+ // activation wait plus this long for it to finish, then fail with
22
+ // ACTIVATION_TIMEOUT. A slow git reset or persona read fits; a hung one
23
+ // doesn't hold them forever.
24
+ const ACTIVATION_IN_FLIGHT_ALLOWANCE_MS = 120 * 1000;
25
+
16
26
  /**
17
27
  * ActionCable WebSocket client that connects to a Rails server.
18
28
  *
@@ -40,6 +50,11 @@ class ActionCableClient extends BaseConnection {
40
50
  this._capabilities = config.capabilities || {};
41
51
  this._workingDir = config.workingDir || process.cwd();
42
52
 
53
+ // CREW-3 #181: whether the last heartbeat found .claude/crew.yml, and
54
+ // whether a {removed: true} for a lost file still has to go out.
55
+ this._crewMapSeen = false;
56
+ this._crewMapRemovalPending = false;
57
+
43
58
  // Connection state
44
59
  this._ws = null;
45
60
  this._connected = false;
@@ -47,6 +62,14 @@ class ActionCableClient extends BaseConnection {
47
62
  this._subscribed = false;
48
63
  this._shutdownRequested = false;
49
64
 
65
+ // #250: retain channel payloads until the next confirmed subscription.
66
+ // Heartbeats describe current state and are never queued.
67
+ this._outboundQueue = [];
68
+ this._outboundBytes = 0;
69
+ this._outboundDropped = 0;
70
+ this._outboundMaxMessages = config.outboundQueueMaxMessages ?? 10000;
71
+ this._outboundMaxBytes = config.outboundQueueMaxBytes ?? 16 * 1024 * 1024;
72
+
50
73
  // Reconnection backoff
51
74
  this._reconnectAttempts = 0;
52
75
  this._baseReconnectDelay = 1000;
@@ -54,6 +77,11 @@ class ActionCableClient extends BaseConnection {
54
77
  this._maxReconnectDelay = 30000;
55
78
  this._reconnectTimer = null;
56
79
 
80
+ // #23: a subscribe the server never confirms (or rejects) leaves the
81
+ // daemon half-connected and eating work. Give up on the socket after this.
82
+ this._subscriptionConfirmTimeoutMs = config.subscriptionConfirmTimeout ?? 15000;
83
+ this._subscriptionConfirmTimer = null;
84
+
57
85
  // Auth failure tracking — stop reconnecting after repeated rejections
58
86
  this._consecutiveRejections = 0;
59
87
  this._maxConsecutiveRejections = 3;
@@ -65,29 +93,47 @@ class ActionCableClient extends BaseConnection {
65
93
  this._pingWatchdogInterval = this._heartbeatInterval * 2; // 2x heartbeat = 60s default
66
94
 
67
95
  // Command tracking per session
96
+ this._commandReceipts = new CommandReceipts({ maxEntries: config.commandReceiptMaxEntries });
68
97
  this._activeCommands = new Map(); // sessionId -> commandId
69
98
  this._sequences = new Map(); // sessionId -> sequence counter
70
99
  this._cancelledSessions = new Set(); // sessionIds with pending cancel (suppress exit→complete)
71
100
 
72
- // Permission server reference (set externally via setPermissionServer)
73
- this._permissionServer = null;
101
+ // Commands for a session the daemon can't start on its own, held until
102
+ // Rails' session_activate arrives. The activation can land after its
103
+ // command (#88), and only the activation carries the model and persona.
104
+ this._activationsInFlight = new Set(); // sessionIds whose session_activate is being handled
105
+ this._awaitingActivation = new Map(); // sessionId -> { commands: [message], timer }
106
+ this._activationWaitMs = (config.activationWaitTimeout ?? 30) * 1000;
107
+
108
+ // #223: a cancel kills the CLI and respawns it (~450 ms with the real
109
+ // claude). Commands that land in between wait in _awaitingActivation and
110
+ // go to the new process once it is up.
111
+ this._cancelsInFlight = new Map(); // sessionId -> cancels between kill and respawn
112
+
113
+ // Permission broker reference (set externally via setPermissionBroker)
114
+ this._permissionBroker = null;
74
115
 
75
116
  // Store config for session activation
76
117
  this._config = config;
118
+
119
+ // #130: an agent's AskUserQuestion, held by its process until Chris
120
+ // answers. Reported to Rails as `ask_user_question` events.
121
+ this._daemon.on('session:ask_user_question', (question) => this._reportQuestion('held', question));
122
+ this._daemon.on('session:ask_user_question_released', (released) => this._reportQuestion('released', released));
77
123
  }
78
124
 
79
125
  /**
80
- * Attach a PermissionServer instance for forwarding permission requests.
81
- * @param {PermissionServer} server
126
+ * Attach a PermissionBroker instance for forwarding permission requests.
127
+ * @param {PermissionBroker} broker
82
128
  */
83
- setPermissionServer(server) {
84
- this._permissionServer = server;
129
+ setPermissionBroker(broker) {
130
+ this._permissionBroker = broker;
85
131
 
86
- server.on('permission_request', (req) => {
132
+ broker.on('permission_request', (req) => {
87
133
  this._forwardPermissionRequest(req);
88
134
  });
89
135
 
90
- server.on('permission_timeout', ({ requestId, sessionId }) => {
136
+ broker.on('permission_timeout', ({ requestId, sessionId }) => {
91
137
  this.sendDaemonMessage({
92
138
  type: 'permission_timeout',
93
139
  request_id: requestId,
@@ -131,11 +177,23 @@ class ActionCableClient extends BaseConnection {
131
177
  async stop() {
132
178
  this._shutdownRequested = true;
133
179
 
180
+ // #109: told while the socket is still up, so Rails marks each one
181
+ // "Not delivered".
182
+ for (const sessionId of [...this._awaitingActivation.keys()]) {
183
+ this._failAwaitingCommands(
184
+ sessionId,
185
+ 'DAEMON_STOPPING',
186
+ `The daemon stopped before session ${sessionId} was activated; the command was not run.`,
187
+ );
188
+ }
189
+
134
190
  if (this._reconnectTimer) {
135
191
  clearTimeout(this._reconnectTimer);
136
192
  this._reconnectTimer = null;
137
193
  }
138
194
 
195
+ this._clearSubscriptionConfirmTimer();
196
+
139
197
  if (this._heartbeatTimer) {
140
198
  clearInterval(this._heartbeatTimer);
141
199
  this._heartbeatTimer = null;
@@ -173,17 +231,20 @@ class ActionCableClient extends BaseConnection {
173
231
  * Tracks sequence numbers per session for ordering.
174
232
  *
175
233
  * @param {string} sessionId
176
- * @param {string|null} commandId
234
+ * @param {string|null} commandId - the command whose turn produced the line
235
+ * (#175, from the process's TurnTracker); null falls back to the newest
236
+ * command_execute, as before #175
177
237
  * @param {string} data
238
+ * @param {object} [extra]
239
+ * @param {Array} [extra.turnCommandIds] - on a turn's result: every command the turn read
178
240
  */
179
- sendOutput(sessionId, commandId, data) {
241
+ sendOutput(sessionId, commandId, data, extra = {}) {
180
242
  const seq = (this._sequences.get(sessionId) || 0) + 1;
181
243
  this._sequences.set(sessionId, seq);
182
244
 
183
- // Use tracked commandId if none provided
184
245
  const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
185
246
 
186
- this.sendDaemonMessage({
247
+ const message = {
187
248
  type: 'command_output',
188
249
  session_id: sessionId,
189
250
  command_id: resolvedCommandId,
@@ -192,7 +253,12 @@ class ActionCableClient extends BaseConnection {
192
253
  sequence: seq,
193
254
  is_complete: true,
194
255
  timestamp: new Date().toISOString(),
195
- });
256
+ };
257
+ // #175: Rails ignores it today. A merged turn's result names every command
258
+ // it ended, so Rails can tell "ran, folded into a later result" from "killed".
259
+ if (Array.isArray(extra.turnCommandIds)) message.turn_command_ids = extra.turnCommandIds;
260
+
261
+ this.sendDaemonMessage(message);
196
262
  }
197
263
 
198
264
  /**
@@ -202,8 +268,11 @@ class ActionCableClient extends BaseConnection {
202
268
  * @param {string|null} commandId
203
269
  * @param {number} exitCode
204
270
  * @param {number} durationMs
271
+ * @param {object} [extra]
272
+ * @param {Array} [extra.unfinishedCommandIds] - commands the exiting process never ended (#175)
273
+ * @param {Array} [extra.readCommandIds] - the unfinished ones its CLI had taken (#224)
205
274
  */
206
- sendComplete(sessionId, commandId, exitCode, durationMs) {
275
+ sendComplete(sessionId, commandId, exitCode, durationMs, extra = {}) {
207
276
  // Suppress the exit→complete event for sessions that were cancelled.
208
277
  // The command_cancelled message is sent separately by _handleCommandCancel.
209
278
  if (this._cancelledSessions && this._cancelledSessions.has(sessionId)) {
@@ -213,14 +282,20 @@ class ActionCableClient extends BaseConnection {
213
282
 
214
283
  const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
215
284
 
216
- this.sendDaemonMessage({
285
+ const message = {
217
286
  type: 'command_complete',
218
287
  session_id: sessionId,
219
288
  command_id: resolvedCommandId,
220
289
  exit_code: exitCode,
221
290
  execution_time_ms: durationMs,
222
291
  timestamp: new Date().toISOString(),
223
- });
292
+ };
293
+ // #175: what the exit left without a result. #224: which of those the CLI
294
+ // had taken; Rails marks the rest "Not delivered".
295
+ if (Array.isArray(extra.unfinishedCommandIds)) message.unfinished_command_ids = extra.unfinishedCommandIds;
296
+ if (Array.isArray(extra.readCommandIds)) message.read_command_ids = extra.readCommandIds;
297
+
298
+ this.sendDaemonMessage(message);
224
299
 
225
300
  // Clear active command on completion
226
301
  this._activeCommands.delete(sessionId);
@@ -266,7 +341,34 @@ class ActionCableClient extends BaseConnection {
266
341
  data: JSON.stringify(messageData),
267
342
  };
268
343
 
269
- this._send(envelope);
344
+ if (messageData.type === 'heartbeat') {
345
+ return this._subscribed && this._send(envelope);
346
+ }
347
+ if (this._subscribed && this._outboundQueue.length === 0 && this._send(envelope)) return true;
348
+
349
+ const bytes = Buffer.byteLength(JSON.stringify(envelope));
350
+ if (this._outboundQueue.length >= this._outboundMaxMessages ||
351
+ this._outboundBytes + bytes > this._outboundMaxBytes) {
352
+ this._outboundDropped += 1;
353
+ this._logger.error('Outbound reconnect queue overflow', {
354
+ dropped: this._outboundDropped, type: messageData.type,
355
+ queuedMessages: this._outboundQueue.length, queuedBytes: this._outboundBytes,
356
+ });
357
+ return false;
358
+ }
359
+ this._outboundQueue.push({ envelope, bytes });
360
+ this._outboundBytes += bytes;
361
+ if (this._subscribed) this._flushOutboundQueue();
362
+ return true;
363
+ }
364
+
365
+ _flushOutboundQueue() {
366
+ while (this._subscribed && this._outboundQueue.length) {
367
+ const entry = this._outboundQueue[0];
368
+ if (!this._send(entry.envelope)) break;
369
+ this._outboundQueue.shift();
370
+ this._outboundBytes -= entry.bytes;
371
+ }
270
372
  }
271
373
 
272
374
  // ---------------------------------------------------------------------------
@@ -290,6 +392,8 @@ class ActionCableClient extends BaseConnection {
290
392
  _connect() {
291
393
  if (this._shutdownRequested) return;
292
394
 
395
+ this._clearSubscriptionConfirmTimer();
396
+
293
397
  // Close any prior socket before opening a new one. Some reconnect paths
294
398
  // (e.g. subscription rejection) schedule a reconnect while the existing
295
399
  // socket is still OPEN — without this, the old socket leaks with its
@@ -399,6 +503,8 @@ class ActionCableClient extends BaseConnection {
399
503
  this._authenticated = false;
400
504
  this._subscribed = false;
401
505
 
506
+ this._clearSubscriptionConfirmTimer();
507
+
402
508
  if (this._heartbeatTimer) {
403
509
  clearInterval(this._heartbeatTimer);
404
510
  this._heartbeatTimer = null;
@@ -433,22 +539,26 @@ class ActionCableClient extends BaseConnection {
433
539
  // ---------------------------------------------------------------------------
434
540
 
435
541
  /**
436
- * Welcome received — subscribe to PilotChannel.
542
+ * Welcome received — subscribe to PilotChannel and start timing the
543
+ * confirmation.
437
544
  */
438
545
  _handleWelcome() {
439
546
  this._logger.info('Received welcome, subscribing to PilotChannel');
440
547
  this._subscribeToDaemonChannel();
548
+ this._startSubscriptionConfirmTimer();
441
549
  }
442
550
 
443
551
  /**
444
552
  * Subscription confirmed — mark subscribed, send registration, and emit event.
445
553
  */
446
554
  _handleSubscriptionConfirmed(msg) {
555
+ this._clearSubscriptionConfirmTimer();
447
556
  this._subscribed = true;
448
557
  this._reconnectAttempts = 0; // Backoff resets only after full connect+subscribe success
449
558
  this._consecutiveRejections = 0; // Auth is valid — reset rejection counter
450
559
  this._lastPingAt = Date.now(); // Initialize so watchdog doesn't fire immediately
451
560
  this._logger.info('PilotChannel subscription confirmed');
561
+ this._flushOutboundQueue();
452
562
  this.emit('subscribed');
453
563
  this._sendDaemonRegistration();
454
564
  this._startPingWatchdog();
@@ -458,6 +568,7 @@ class ActionCableClient extends BaseConnection {
458
568
  * Subscription rejected — log and schedule reconnect.
459
569
  */
460
570
  _handleSubscriptionRejected(msg) {
571
+ this._clearSubscriptionConfirmTimer(); // the rejection path decides what happens next
461
572
  this._subscribed = false;
462
573
  this._consecutiveRejections += 1;
463
574
  const reason = (msg && msg.reason) || 'unknown';
@@ -477,6 +588,42 @@ class ActionCableClient extends BaseConnection {
477
588
  this._scheduleReconnect();
478
589
  }
479
590
 
591
+ /**
592
+ * #23: if neither confirm_subscription nor reject_subscription arrives in
593
+ * time, log at ERROR and drop the socket. Its close event schedules the
594
+ * reconnect through the normal backoff, which only a confirmation resets.
595
+ * terminate() rather than close(): a server that ignores the subscribe may
596
+ * ignore the close handshake too, and ws would wait 30 s for it.
597
+ */
598
+ _startSubscriptionConfirmTimer() {
599
+ this._clearSubscriptionConfirmTimer();
600
+ const ws = this._ws;
601
+ this._subscriptionConfirmTimer = setTimeout(() => {
602
+ this._subscriptionConfirmTimer = null;
603
+ if (this._shutdownRequested || this._subscribed || this._ws !== ws) return;
604
+ this._logger.error(
605
+ `PilotChannel subscription not confirmed within ${this._subscriptionConfirmTimeoutMs / 1000}s. ` +
606
+ 'Closing the socket and reconnecting.'
607
+ );
608
+ try {
609
+ ws.terminate();
610
+ } catch (_) {
611
+ // already closed — its close event has run or will run
612
+ }
613
+ }, this._subscriptionConfirmTimeoutMs);
614
+
615
+ if (this._subscriptionConfirmTimer.unref) {
616
+ this._subscriptionConfirmTimer.unref();
617
+ }
618
+ }
619
+
620
+ _clearSubscriptionConfirmTimer() {
621
+ if (this._subscriptionConfirmTimer) {
622
+ clearTimeout(this._subscriptionConfirmTimer);
623
+ this._subscriptionConfirmTimer = null;
624
+ }
625
+ }
626
+
480
627
  /**
481
628
  * Ping received — track freshness timestamp for watchdog monitoring.
482
629
  */
@@ -529,6 +676,9 @@ class ActionCableClient extends BaseConnection {
529
676
  case 'permission_response':
530
677
  this._handlePermissionResponse(inner);
531
678
  break;
679
+ case 'ask_user_question_answer':
680
+ this._handleQuestionAnswer(inner);
681
+ break;
532
682
  case 'auth_error':
533
683
  this._handleAuthError(inner);
534
684
  break;
@@ -583,7 +733,7 @@ class ActionCableClient extends BaseConnection {
583
733
  token: this._authToken,
584
734
  pilot_id: this._daemonId,
585
735
  },
586
- capabilities: this._capabilities,
736
+ capabilities: this._reportedCapabilities(),
587
737
  system_info: {
588
738
  hostname: os.hostname(),
589
739
  platform: process.platform,
@@ -603,6 +753,15 @@ class ActionCableClient extends BaseConnection {
603
753
  this._authenticated = true;
604
754
  this._logger.info('Successfully registered with server');
605
755
 
756
+ // #436: run no more sessions than Rails assigned, and never more than
757
+ // our own ceiling.
758
+ this._daemon.setAssignedMaxSessions(message.assigned_capabilities?.max_concurrent_sessions);
759
+ this._logger.info('Session cap', {
760
+ assigned: message.assigned_capabilities?.max_concurrent_sessions ?? null,
761
+ ceiling: this._daemon.maxSessionsCeiling,
762
+ effective: this._daemon.maxSessions,
763
+ });
764
+
606
765
  if (message.server_config) {
607
766
  const hbMs = message.server_config.heartbeat_interval || 30000;
608
767
  this._heartbeatInterval = hbMs;
@@ -610,6 +769,10 @@ class ActionCableClient extends BaseConnection {
610
769
  this._logger.info(`Updated server config - heartbeat: ${hbMs / 1000}s`);
611
770
  }
612
771
 
772
+ // #130: Rails may have missed a held question while we were away. Report
773
+ // every one still held; Rails treats a repeat as the same question.
774
+ this._replayHeldQuestions();
775
+
613
776
  // Send an immediate heartbeat so Rails can reconcile zombie sessions right away
614
777
  // instead of waiting up to one heartbeat interval (30s) after reconnect.
615
778
  this._sendHeartbeat().catch((err) => {
@@ -654,6 +817,20 @@ class ActionCableClient extends BaseConnection {
654
817
  * @param {object} message
655
818
  */
656
819
  async _handleSessionActivation(message) {
820
+ const sessionId = message.session_id;
821
+ // Marked before the first await, so a command arriving while the persona
822
+ // file is read or the git state is reset waits for this spawn.
823
+ const key = String(sessionId);
824
+ this._activationsInFlight.add(key);
825
+ this._restartActivationWaitTimer(key);
826
+ try {
827
+ await this._activateFromRails(message);
828
+ } finally {
829
+ this._activationsInFlight.delete(key);
830
+ }
831
+ }
832
+
833
+ async _activateFromRails(message) {
657
834
  const sessionId = message.session_id;
658
835
  const userId = message.user_id;
659
836
  const claudeSessionId = message.claude_session_id || undefined;
@@ -668,6 +845,7 @@ class ActionCableClient extends BaseConnection {
668
845
  // Re-read every activation — authors edit persona files mid-session
669
846
  // and we want the next session to pick that up without a daemon restart.
670
847
  systemPrompt = await readPersonaBody(this._config.workingDir, systemPromptPath);
848
+ systemPrompt = (await this._crewHeader(systemPromptPath)) + systemPrompt;
671
849
  } catch (err) {
672
850
  this._logger.error('Persona resolution failed', { sessionId, systemPromptPath, code: err.code, error: err.message });
673
851
  this._sendError('SESSION_ACTIVATION_FAILED', err.message, {
@@ -675,6 +853,7 @@ class ActionCableClient extends BaseConnection {
675
853
  system_prompt_path: systemPromptPath,
676
854
  reason: err.code || 'PERSONA_RESOLUTION_FAILED',
677
855
  });
856
+ this._failAwaitingCommands(sessionId, 'ACTIVATION_FAILED', `Session activation failed: ${err.message}`);
678
857
  return;
679
858
  }
680
859
  }
@@ -717,7 +896,22 @@ class ActionCableClient extends BaseConnection {
717
896
  } catch (err) {
718
897
  this._logger.error('Failed to activate session', { sessionId, error: err.message });
719
898
  this._sendError('SESSION_ACTIVATION_FAILED', err.message, { session_id: sessionId });
899
+ this._failAwaitingCommands(sessionId, 'ACTIVATION_FAILED', `Session activation failed: ${err.message}`);
900
+ return;
720
901
  }
902
+
903
+ this._releaseAwaitingCommands(sessionId);
904
+ }
905
+
906
+ /**
907
+ * #175: the command whose turn is running in the session's CLI, falling
908
+ * back to the newest command_execute when the process can't tell.
909
+ */
910
+ _currentCommandId(sessionId) {
911
+ const current = typeof this._daemon.currentCommandId === 'function'
912
+ ? this._daemon.currentCommandId(sessionId)
913
+ : undefined;
914
+ return current || this._activeCommands.get(sessionId) || null;
721
915
  }
722
916
 
723
917
  /**
@@ -725,10 +919,23 @@ class ActionCableClient extends BaseConnection {
725
919
  * @param {object} message
726
920
  */
727
921
  async _handleCommandExecution(message) {
728
- const sessionId = message.session_id;
922
+ // PilotChannel sends session_id as an integer; every id the daemon's own
923
+ // events carry is a string, and Map keys compare with ===. Without this the
924
+ // _activeCommands entry written here can never be read back, so command_id
925
+ // is null on every output, completion and permission request.
926
+ const sessionId = String(message.session_id);
729
927
  const commandId = message.command_id;
730
928
  const command = message.command;
731
929
 
930
+ if (message.delivery_epoch) {
931
+ const receipt = this._commandReceipts.accept(message);
932
+ this.sendDaemonMessage({
933
+ type: 'command_receipt', session_id: sessionId, command_id: String(commandId),
934
+ delivery_epoch: this._commandReceipts.epoch, receipt,
935
+ });
936
+ if (receipt !== 'accepted') return;
937
+ }
938
+
732
939
  this._logger.info('Executing command', { sessionId, commandId });
733
940
 
734
941
  // Track active command for this session
@@ -736,26 +943,176 @@ class ActionCableClient extends BaseConnection {
736
943
  this._activeCommands.set(sessionId, commandId);
737
944
  }
738
945
 
946
+ // Commands already waiting for this session's activation keep their order.
947
+ if (this._awaitingActivation.has(sessionId) || this._activationsInFlight.has(sessionId) ||
948
+ this._cancelsInFlight.has(sessionId)) {
949
+ this._awaitActivation(sessionId, message);
950
+ return;
951
+ }
952
+
953
+ if (this._daemon.getProcess(sessionId)) {
954
+ this._sendCommand(sessionId, commandId, command);
955
+ return;
956
+ }
957
+
958
+ // No live process. Spawning here with no options would start the chat on
959
+ // the default model with no persona (#88), or start a fresh transcript for
960
+ // a chat Rails has a claude_session_id for (#80). Only resume a chat whose
961
+ // CLI session id this daemon knows; anything else waits for Rails.
962
+ const claudeSessionId = this._daemon.knownClaudeSessionId(sessionId);
963
+ if (!claudeSessionId) {
964
+ this._awaitActivation(sessionId, message);
965
+ return;
966
+ }
967
+
968
+ this._logger.warn('No live process for command, resuming session', { sessionId, claudeSessionId });
739
969
  try {
740
- this._daemon.sendMessage(sessionId, command);
970
+ await this._daemon.activateSession(sessionId, {
971
+ workingDir: this._config.workingDir,
972
+ claudeSessionId,
973
+ });
741
974
  } catch (err) {
742
- // Session process may be dead (e.g. after cancel). Try to re-activate
743
- // and retry once before giving up.
744
- this._logger.warn('Command execution failed, attempting re-activation', { sessionId, error: err.message });
745
- try {
746
- await this._daemon.activateSession(sessionId);
747
- this._daemon.sendMessage(sessionId, command);
748
- this._logger.info('Command sent after re-activation', { sessionId, commandId });
749
- } catch (retryErr) {
750
- this._logger.error('Command execution failed after re-activation', { sessionId, error: retryErr.message });
751
- this._sendError('COMMAND_EXECUTION_FAILED', retryErr.message, {
752
- session_id: sessionId,
753
- command_id: commandId,
754
- command: command,
755
- });
756
- // Clear active command on failure
757
- this._activeCommands.delete(sessionId);
975
+ this._logger.error('Resume for command failed', { sessionId, error: err.message });
976
+ this._failCommand(sessionId, commandId, command, err.message);
977
+ return;
978
+ }
979
+ this._sendCommand(sessionId, commandId, command);
980
+ }
981
+
982
+ /**
983
+ * Write a command to the session's process, reporting a failure to Rails.
984
+ */
985
+ _sendCommand(sessionId, commandId, command) {
986
+ try {
987
+ if (this._daemon.sendMessage(sessionId, command, commandId) === false) {
988
+ throw new Error(`Session process is not running: "${sessionId}"`);
758
989
  }
990
+ } catch (err) {
991
+ this._logger.error('Command execution failed', { sessionId, error: err.message });
992
+ this._failCommand(sessionId, commandId, command, err.message);
993
+ }
994
+ }
995
+
996
+ _failCommand(sessionId, commandId, command, errorMessage, reason) {
997
+ const context = { session_id: sessionId, command_id: commandId, command };
998
+ if (reason) context.reason = reason;
999
+ this._sendError('COMMAND_EXECUTION_FAILED', errorMessage, context);
1000
+ if (this._activeCommands.get(sessionId) === commandId) {
1001
+ this._activeCommands.delete(sessionId);
1002
+ }
1003
+ }
1004
+
1005
+ /**
1006
+ * Hold a command until the session's session_activate spawns it. With no
1007
+ * activation in flight the command waits the activation wait; once one is
1008
+ * being handled, the wait plus ACTIVATION_IN_FLIGHT_ALLOWANCE_MS, so a slow
1009
+ * git reset or persona read doesn't time it out and a hung one does (#109).
1010
+ */
1011
+ _awaitActivation(sessionId, message) {
1012
+ let entry = this._awaitingActivation.get(sessionId);
1013
+ if (!entry) {
1014
+ entry = { commands: [], timer: null };
1015
+ this._awaitingActivation.set(sessionId, entry);
1016
+ }
1017
+ if (entry.commands.length >= MAX_HELD_COMMANDS_PER_SESSION) {
1018
+ this._logger.error('Activation queue full, failing command', { sessionId, commandId: message.command_id });
1019
+ this._failCommand(
1020
+ sessionId, message.command_id, message.command,
1021
+ `Session ${sessionId} already has ${MAX_HELD_COMMANDS_PER_SESSION} commands waiting for its activation; ` +
1022
+ 'the command was not run.',
1023
+ 'ACTIVATION_QUEUE_FULL',
1024
+ );
1025
+ return;
1026
+ }
1027
+ entry.commands.push(message);
1028
+
1029
+ if (!entry.timer) this._startActivationWaitTimer(sessionId, entry);
1030
+
1031
+ this._logger.info('Command waiting for session activation', {
1032
+ sessionId, commandId: message.command_id, waiting: entry.commands.length,
1033
+ });
1034
+ }
1035
+
1036
+ _startActivationWaitTimer(sessionId, entry) {
1037
+ const inFlight = this._activationsInFlight.has(sessionId) || this._cancelsInFlight.has(sessionId);
1038
+ const waitMs = this._activationWaitMs + (inFlight ? ACTIVATION_IN_FLIGHT_ALLOWANCE_MS : 0);
1039
+ const errorMessage = inFlight
1040
+ ? `Activation of session ${sessionId} did not finish within ${waitMs / 1000}s; the command was not run.`
1041
+ : `No session_activate for session ${sessionId} within ${waitMs / 1000}s; ` +
1042
+ 'the command was not run, and no session was started without its model, persona or claude_session_id.';
1043
+ entry.timer = setTimeout(() => {
1044
+ this._failAwaitingCommands(sessionId, 'ACTIVATION_TIMEOUT', errorMessage);
1045
+ }, waitMs);
1046
+ if (entry.timer.unref) entry.timer.unref();
1047
+ }
1048
+
1049
+ // An activation started: commands already held get the in-flight wait.
1050
+ _restartActivationWaitTimer(sessionId) {
1051
+ const entry = this._awaitingActivation.get(sessionId);
1052
+ if (!entry) return;
1053
+ if (entry.timer) clearTimeout(entry.timer);
1054
+ this._startActivationWaitTimer(sessionId, entry);
1055
+ }
1056
+
1057
+ _releaseAwaitingCommands(sessionId) {
1058
+ sessionId = String(sessionId);
1059
+ const entry = this._awaitingActivation.get(sessionId);
1060
+ if (!entry) return;
1061
+ this._awaitingActivation.delete(sessionId);
1062
+ if (entry.timer) clearTimeout(entry.timer);
1063
+
1064
+ for (const msg of entry.commands) {
1065
+ this._logger.info('Sending command held for activation', { sessionId, commandId: msg.command_id });
1066
+ if (msg.command_id) this._activeCommands.set(sessionId, msg.command_id);
1067
+ this._sendCommand(sessionId, msg.command_id, msg.command);
1068
+ }
1069
+ }
1070
+
1071
+ /**
1072
+ * #223: hold this session's commands until the cancel's kill and respawn
1073
+ * are done. Only a live process is killed, so nothing else waits.
1074
+ */
1075
+ _startCancelHold(sessionId) {
1076
+ this._cancelsInFlight.set(sessionId, (this._cancelsInFlight.get(sessionId) || 0) + 1);
1077
+ }
1078
+
1079
+ /**
1080
+ * #223: the cancel is done. Held commands go to the new process in order.
1081
+ * With no process, each fails as "not running" (Rails' #221 restore
1082
+ * matches that) with the respawn error, and none is sent later.
1083
+ */
1084
+ _endCancelHold(sessionId, error) {
1085
+ const count = (this._cancelsInFlight.get(sessionId) || 0) - 1;
1086
+ if (count > 0) {
1087
+ this._cancelsInFlight.set(sessionId, count);
1088
+ return;
1089
+ }
1090
+ this._cancelsInFlight.delete(sessionId);
1091
+ // A session_activate in flight sends or fails them itself.
1092
+ if (this._activationsInFlight.has(sessionId)) return;
1093
+
1094
+ if (this._daemon.getProcess(sessionId)) {
1095
+ this._releaseAwaitingCommands(sessionId);
1096
+ return;
1097
+ }
1098
+ const why = error ? error.message : 'no process after the cancel';
1099
+ this._failAwaitingCommands(
1100
+ sessionId,
1101
+ 'RESPAWN_FAILED',
1102
+ `Session process is not running: "${sessionId}" (restart after cancel failed: ${why})`,
1103
+ );
1104
+ }
1105
+
1106
+ _failAwaitingCommands(sessionId, reason, errorMessage) {
1107
+ sessionId = String(sessionId);
1108
+ const entry = this._awaitingActivation.get(sessionId);
1109
+ if (!entry) return;
1110
+ this._awaitingActivation.delete(sessionId);
1111
+ if (entry.timer) clearTimeout(entry.timer);
1112
+
1113
+ this._logger.error('Failing commands held for activation', { sessionId, reason, count: entry.commands.length });
1114
+ for (const msg of entry.commands) {
1115
+ this._failCommand(sessionId, msg.command_id, msg.command, errorMessage, reason);
759
1116
  }
760
1117
  }
761
1118
 
@@ -773,8 +1130,8 @@ class ActionCableClient extends BaseConnection {
773
1130
  }
774
1131
 
775
1132
  /**
776
- * Forward a permission request from the PermissionServer to Rails.
777
- * @param {object} req - Permission request from PermissionServer
1133
+ * Forward a permission request from the PermissionBroker to Rails.
1134
+ * @param {object} req - Permission request from PermissionBroker
778
1135
  */
779
1136
  _forwardPermissionRequest(req) {
780
1137
  this._logger.info('Forwarding permission request to Rails', {
@@ -787,19 +1144,69 @@ class ActionCableClient extends BaseConnection {
787
1144
  type: 'permission_request',
788
1145
  request_id: req.requestId,
789
1146
  session_id: req.sessionId,
790
- command_id: this._activeCommands.get(req.sessionId) || null,
1147
+ command_id: this._currentCommandId(req.sessionId),
791
1148
  tool_name: req.toolName,
792
1149
  tool_input: req.toolInput,
793
1150
  file_path: req.filePath,
794
1151
  description: req.description,
795
1152
  risk_level: req.riskLevel,
1153
+ // Why the operator is being asked: a matched ask rule, versus auto mode
1154
+ // pausing after repeated classifier blocks. Rails ignores it today; it is
1155
+ // on the wire so persisting it is a Rails-only change.
1156
+ decision_reason_type: req.decisionReasonType,
796
1157
  timeout_seconds: req.timeoutSeconds,
797
1158
  timestamp: new Date().toISOString(),
798
1159
  });
799
1160
  }
800
1161
 
801
1162
  /**
802
- * Handle permission_response from Rails — route to PermissionServer.
1163
+ * #130: tell Rails about a held AskUserQuestion.
1164
+ * event: 'held' (with questions), 'released' (the process can't answer it
1165
+ * any more), 'answered' or 'failed' (the result of an answer Rails sent).
1166
+ */
1167
+ _reportQuestion(event, { sessionId, controlRequestId, toolUseId, questions, reason, deliveryId }) {
1168
+ const message = {
1169
+ type: 'ask_user_question',
1170
+ event,
1171
+ session_id: sessionId,
1172
+ request_id: controlRequestId,
1173
+ tool_use_id: toolUseId || null,
1174
+ timestamp: new Date().toISOString(),
1175
+ };
1176
+ if (event === 'held') message.questions = questions || [];
1177
+ if (reason) message.reason = reason;
1178
+ if (deliveryId !== undefined) message.delivery_id = deliveryId;
1179
+
1180
+ this._logger.info('Reporting AskUserQuestion to Rails', { event, sessionId, controlRequestId });
1181
+ this.sendDaemonMessage(message);
1182
+ }
1183
+
1184
+ _replayHeldQuestions() {
1185
+ if (typeof this._daemon.heldQuestions !== 'function') return;
1186
+ for (const question of this._daemon.heldQuestions()) this._reportQuestion('held', question);
1187
+ }
1188
+
1189
+ /**
1190
+ * #130: Rails sends Chris's answer (or a marked discussion note) for a held
1191
+ * AskUserQuestion. The result goes back as an 'answered' or 'failed' event,
1192
+ * so Rails can fall back to text delivery.
1193
+ */
1194
+ _handleQuestionAnswer(message) {
1195
+ const sessionId = String(message.session_id);
1196
+ const controlRequestId = message.request_id;
1197
+ const answered = this._daemon.answerQuestion(sessionId, controlRequestId, message.answers || {});
1198
+
1199
+ this._reportQuestion(answered ? 'answered' : 'failed', {
1200
+ sessionId,
1201
+ controlRequestId,
1202
+ toolUseId: message.tool_use_id,
1203
+ reason: answered ? undefined : 'not_held',
1204
+ deliveryId: message.delivery_id,
1205
+ });
1206
+ }
1207
+
1208
+ /**
1209
+ * Handle permission_response from Rails — route to PermissionBroker.
803
1210
  * @param {object} message
804
1211
  */
805
1212
  _handlePermissionResponse(message) {
@@ -808,10 +1215,10 @@ class ActionCableClient extends BaseConnection {
808
1215
 
809
1216
  this._logger.info('Permission response received from Rails', { requestId, decision });
810
1217
 
811
- if (this._permissionServer) {
812
- this._permissionServer.resolve(requestId, decision, message.reason);
1218
+ if (this._permissionBroker) {
1219
+ this._permissionBroker.resolve(requestId, decision, message.reason);
813
1220
  } else {
814
- this._logger.warn('No permission server to route response to', { requestId });
1221
+ this._logger.warn('No permission broker to route response to', { requestId });
815
1222
  }
816
1223
  }
817
1224
 
@@ -826,10 +1233,24 @@ class ActionCableClient extends BaseConnection {
826
1233
  * @param {object} message
827
1234
  */
828
1235
  async _handleCommandCancel(message) {
829
- const sessionId = message.session_id;
1236
+ // Normalised for the same reason as _handleCommandExecution — this one also
1237
+ // gates _cancelledSessions, which suppresses the exit→complete event.
1238
+ const sessionId = String(message.session_id);
830
1239
  const commandId = message.command_id;
831
1240
  this._logger.info('Interrupting command (kill + immediate respawn)', { sessionId, commandId });
832
1241
 
1242
+ // #175: what the kill ends, read before the process goes: the running
1243
+ // turn and every command it hadn't read yet.
1244
+ const unfinished = typeof this._daemon.unfinishedCommandIds === 'function'
1245
+ ? this._daemon.unfinishedCommandIds(sessionId)
1246
+ : undefined;
1247
+ // #224: which of those the CLI took, read once it is dead, so a turn it
1248
+ // opened during the kill counts as read.
1249
+ const proc = typeof this._daemon.getProcess === 'function' ? this._daemon.getProcess(sessionId) : undefined;
1250
+ // #223: commands that arrive from here until the respawn wait for it.
1251
+ if (proc) this._startCancelHold(sessionId);
1252
+ let holdError = null;
1253
+
833
1254
  try {
834
1255
  // Suppress the exit→complete event for this session
835
1256
  this._cancelledSessions.add(sessionId);
@@ -849,20 +1270,27 @@ class ActionCableClient extends BaseConnection {
849
1270
  });
850
1271
  this._logger.info('Session respawned after interrupt', { sessionId });
851
1272
  } catch (respawnErr) {
852
- // Non-fatal — the next command will trigger lazy re-activation
1273
+ // Non-fatal — the next command will trigger lazy re-activation.
1274
+ // Commands held during the kill fail with this error (#223).
1275
+ holdError = respawnErr;
853
1276
  this._logger.warn('Immediate respawn failed (will retry on next command)', {
854
1277
  sessionId,
855
1278
  error: respawnErr.message,
856
1279
  });
857
1280
  }
858
1281
 
859
- this.sendDaemonMessage({
1282
+ const cancelled = {
860
1283
  type: 'command_cancelled',
861
1284
  session_id: sessionId,
862
1285
  command_id: commandId,
863
1286
  timestamp: new Date().toISOString(),
864
- });
1287
+ };
1288
+ if (Array.isArray(unfinished)) cancelled.unfinished_command_ids = unfinished;
1289
+ const read = proc && typeof proc.readCommandIds === 'function' ? proc.readCommandIds() : undefined;
1290
+ if (Array.isArray(unfinished) && Array.isArray(read)) cancelled.read_command_ids = read;
1291
+ this.sendDaemonMessage(cancelled);
865
1292
  } else {
1293
+ holdError = new Error(result.message);
866
1294
  this._cancelledSessions.delete(sessionId);
867
1295
  this._sendError('CANCEL_FAILED', result.message, {
868
1296
  session_id: sessionId,
@@ -870,6 +1298,7 @@ class ActionCableClient extends BaseConnection {
870
1298
  });
871
1299
  }
872
1300
  } catch (err) {
1301
+ holdError = err;
873
1302
  this._cancelledSessions.delete(sessionId);
874
1303
  this._logger.error('Failed to cancel command', { sessionId, error: err.message });
875
1304
  this._sendError('CANCEL_FAILED', err.message, {
@@ -877,6 +1306,9 @@ class ActionCableClient extends BaseConnection {
877
1306
  command_id: commandId,
878
1307
  });
879
1308
  }
1309
+
1310
+ // After command_cancelled, so a held command's output follows it.
1311
+ if (proc) this._endCancelHold(sessionId, holdError);
880
1312
  }
881
1313
 
882
1314
  /**
@@ -1198,26 +1630,95 @@ class ActionCableClient extends BaseConnection {
1198
1630
  * Send a heartbeat message to the server.
1199
1631
  */
1200
1632
  async _sendHeartbeat() {
1201
- const [gitContext, claudeAccount, personas, machineEffort] = await Promise.all([
1633
+ const [gitContext, claudeAccount, personas, machineEffort, crewMap] = await Promise.all([
1202
1634
  this._getGitContext(),
1203
1635
  this._getClaudeAccount(),
1204
1636
  this._getPersonas(),
1205
1637
  this._getMachineEffort(),
1638
+ this._getCrewMap(),
1206
1639
  ]);
1207
1640
 
1208
- this.sendDaemonMessage({
1641
+ const crewMapField = this._crewMapField(crewMap);
1642
+ const sent = this.sendDaemonMessage({
1209
1643
  type: 'heartbeat',
1644
+ delivery_epoch: this._commandReceipts.epoch,
1645
+ outbound_dropped: this._outboundDropped,
1210
1646
  pilot_id: this._daemonId,
1211
1647
  version: daemonPkg.version,
1212
1648
  status: 'healthy',
1649
+ capabilities: this._reportedCapabilities(),
1213
1650
  session_summary: this._getSessionSummary(),
1214
1651
  resource_usage: this._getResourceUsage(),
1215
1652
  git_context: gitContext,
1216
1653
  claude_account: claudeAccount,
1654
+ claude_usage: this._getClaudeUsage(claudeAccount),
1217
1655
  machine_effort: machineEffort,
1218
1656
  personas,
1657
+ ...crewMapField,
1219
1658
  timestamp: new Date().toISOString(),
1220
1659
  });
1660
+ if (sent && crewMapField.crew_map && crewMapField.crew_map.removed) this._crewMapRemovalPending = false;
1661
+ }
1662
+
1663
+ /**
1664
+ * The capabilities registration and heartbeats report. Carries the
1665
+ * daemon's own session ceiling so Rails can clamp the pilot's cap to it
1666
+ * (#436).
1667
+ */
1668
+ _reportedCapabilities() {
1669
+ return { ...this._capabilities, max_concurrent_sessions: this._daemon.maxSessionsCeiling };
1670
+ }
1671
+
1672
+ /**
1673
+ * The repo's .claude/crew.yml in the heartbeat's shape (CREW-3 #181), or
1674
+ * null when there is none. Never throws: the heartbeat must go out.
1675
+ */
1676
+ async _getCrewMap() {
1677
+ try {
1678
+ return await scanCrewMap(this._workingDir, { logger: this._logger });
1679
+ } catch (err) {
1680
+ this._logger.warn('Crew map scan failed; reporting none', { error: err.message });
1681
+ return null;
1682
+ }
1683
+ }
1684
+
1685
+ /**
1686
+ * The heartbeat's crew_map field. With a file: the parsed map, every beat.
1687
+ * With no file: no field at all, as before CREW-3, except that a file this
1688
+ * daemon saw and then lost sends `crew_map: {removed: true}` until one
1689
+ * heartbeat carrying it is sent, so FlightDeck clears the stale names.
1690
+ */
1691
+ _crewMapField(crewMap) {
1692
+ if (crewMap) {
1693
+ this._crewMapSeen = true;
1694
+ this._crewMapRemovalPending = false;
1695
+ return { crew_map: crewMap };
1696
+ }
1697
+ if (this._crewMapSeen) {
1698
+ this._crewMapSeen = false;
1699
+ this._crewMapRemovalPending = true;
1700
+ this._logger.info('Crew map .claude/crew.yml is gone; telling FlightDeck once');
1701
+ }
1702
+ return this._crewMapRemovalPending ? { crew_map: { removed: true } } : {};
1703
+ }
1704
+
1705
+ /**
1706
+ * The crew identity header for a file-backed persona's spawn (crew ADR
1707
+ * §1.3), read fresh so a rename takes effect on the next spawn. '' when
1708
+ * the repo has no map or the map has no entry for the persona, so the
1709
+ * system prompt is exactly the persona body, as before CREW-3.
1710
+ */
1711
+ async _crewHeader(systemPromptPath) {
1712
+ const slug = personaSlugFromPath(systemPromptPath);
1713
+ if (!slug) return '';
1714
+ try {
1715
+ const header = buildCrewHeader(await scanCrewMap(this._config.workingDir, { logger: this._logger }), slug);
1716
+ if (header) this._logger.info('Adding crew identity header', { slug });
1717
+ return header || '';
1718
+ } catch (err) {
1719
+ this._logger.warn('Crew header failed; spawning without it', { slug, error: err.message });
1720
+ return '';
1721
+ }
1221
1722
  }
1222
1723
 
1223
1724
  /**
@@ -1265,6 +1766,15 @@ class ActionCableClient extends BaseConnection {
1265
1766
  }
1266
1767
  }
1267
1768
 
1769
+ /**
1770
+ * The account usage the daemon last saw on a CLI child (#258), or null.
1771
+ * Null too when it was taken under a different account than this one.
1772
+ */
1773
+ _getClaudeUsage(claudeAccount) {
1774
+ if (!this._daemon || typeof this._daemon.claudeUsage !== 'function') return null;
1775
+ return this._daemon.claudeUsage(claudeAccount?.account_uuid || null);
1776
+ }
1777
+
1268
1778
  /**
1269
1779
  * Get this machine's effective default reasoning effort (CLAUDE_EFFORT env or
1270
1780
  * ~/.claude/settings.json `effort`). Returns null when unknown. 60s cache.
@@ -1396,10 +1906,23 @@ class ActionCableClient extends BaseConnection {
1396
1906
  _send(msg) {
1397
1907
  if (!this._ws || this._ws.readyState !== WebSocket.OPEN) {
1398
1908
  this._logger.warn('Cannot send: WebSocket not open');
1399
- return;
1909
+ return false;
1910
+ }
1911
+ try {
1912
+ this._ws.send(JSON.stringify(msg), (err) => {
1913
+ if (!err) return;
1914
+ // A callback error is ambiguous after enqueueing bytes. Do not replay
1915
+ // output blindly; report the gap on the next heartbeat. Commands have
1916
+ // their own receipt-based retry protocol.
1917
+ if (msg.command === 'message' && JSON.parse(msg.data).type !== 'heartbeat') this._outboundDropped += 1;
1918
+ this._logger.error('WebSocket write failed after enqueue', { error: err.message, dropped: this._outboundDropped });
1919
+ });
1920
+ return true;
1921
+ } catch (err) {
1922
+ this._logger.warn('WebSocket rejected send', { error: err.message });
1923
+ return false;
1400
1924
  }
1401
- this._ws.send(JSON.stringify(msg));
1402
1925
  }
1403
1926
  }
1404
1927
 
1405
- module.exports = { ActionCableClient };
1928
+ module.exports = { ActionCableClient, MAX_HELD_COMMANDS_PER_SESSION, ACTIVATION_IN_FLIGHT_ALLOWANCE_MS };