@radnine/claude-session-daemon 0.8.0 → 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.
@@ -6,12 +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');
14
+ const { handleFsRequest } = require('../fs-bridge');
13
15
  const daemonPkg = require('../../package.json');
14
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
+
15
26
  /**
16
27
  * ActionCable WebSocket client that connects to a Rails server.
17
28
  *
@@ -39,6 +50,11 @@ class ActionCableClient extends BaseConnection {
39
50
  this._capabilities = config.capabilities || {};
40
51
  this._workingDir = config.workingDir || process.cwd();
41
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
+
42
58
  // Connection state
43
59
  this._ws = null;
44
60
  this._connected = false;
@@ -46,6 +62,14 @@ class ActionCableClient extends BaseConnection {
46
62
  this._subscribed = false;
47
63
  this._shutdownRequested = false;
48
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
+
49
73
  // Reconnection backoff
50
74
  this._reconnectAttempts = 0;
51
75
  this._baseReconnectDelay = 1000;
@@ -53,6 +77,11 @@ class ActionCableClient extends BaseConnection {
53
77
  this._maxReconnectDelay = 30000;
54
78
  this._reconnectTimer = null;
55
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
+
56
85
  // Auth failure tracking — stop reconnecting after repeated rejections
57
86
  this._consecutiveRejections = 0;
58
87
  this._maxConsecutiveRejections = 3;
@@ -64,29 +93,47 @@ class ActionCableClient extends BaseConnection {
64
93
  this._pingWatchdogInterval = this._heartbeatInterval * 2; // 2x heartbeat = 60s default
65
94
 
66
95
  // Command tracking per session
96
+ this._commandReceipts = new CommandReceipts({ maxEntries: config.commandReceiptMaxEntries });
67
97
  this._activeCommands = new Map(); // sessionId -> commandId
68
98
  this._sequences = new Map(); // sessionId -> sequence counter
69
99
  this._cancelledSessions = new Set(); // sessionIds with pending cancel (suppress exit→complete)
70
100
 
71
- // Permission server reference (set externally via setPermissionServer)
72
- 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;
73
115
 
74
116
  // Store config for session activation
75
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));
76
123
  }
77
124
 
78
125
  /**
79
- * Attach a PermissionServer instance for forwarding permission requests.
80
- * @param {PermissionServer} server
126
+ * Attach a PermissionBroker instance for forwarding permission requests.
127
+ * @param {PermissionBroker} broker
81
128
  */
82
- setPermissionServer(server) {
83
- this._permissionServer = server;
129
+ setPermissionBroker(broker) {
130
+ this._permissionBroker = broker;
84
131
 
85
- server.on('permission_request', (req) => {
132
+ broker.on('permission_request', (req) => {
86
133
  this._forwardPermissionRequest(req);
87
134
  });
88
135
 
89
- server.on('permission_timeout', ({ requestId, sessionId }) => {
136
+ broker.on('permission_timeout', ({ requestId, sessionId }) => {
90
137
  this.sendDaemonMessage({
91
138
  type: 'permission_timeout',
92
139
  request_id: requestId,
@@ -130,11 +177,23 @@ class ActionCableClient extends BaseConnection {
130
177
  async stop() {
131
178
  this._shutdownRequested = true;
132
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
+
133
190
  if (this._reconnectTimer) {
134
191
  clearTimeout(this._reconnectTimer);
135
192
  this._reconnectTimer = null;
136
193
  }
137
194
 
195
+ this._clearSubscriptionConfirmTimer();
196
+
138
197
  if (this._heartbeatTimer) {
139
198
  clearInterval(this._heartbeatTimer);
140
199
  this._heartbeatTimer = null;
@@ -172,17 +231,20 @@ class ActionCableClient extends BaseConnection {
172
231
  * Tracks sequence numbers per session for ordering.
173
232
  *
174
233
  * @param {string} sessionId
175
- * @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
176
237
  * @param {string} data
238
+ * @param {object} [extra]
239
+ * @param {Array} [extra.turnCommandIds] - on a turn's result: every command the turn read
177
240
  */
178
- sendOutput(sessionId, commandId, data) {
241
+ sendOutput(sessionId, commandId, data, extra = {}) {
179
242
  const seq = (this._sequences.get(sessionId) || 0) + 1;
180
243
  this._sequences.set(sessionId, seq);
181
244
 
182
- // Use tracked commandId if none provided
183
245
  const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
184
246
 
185
- this.sendDaemonMessage({
247
+ const message = {
186
248
  type: 'command_output',
187
249
  session_id: sessionId,
188
250
  command_id: resolvedCommandId,
@@ -191,7 +253,12 @@ class ActionCableClient extends BaseConnection {
191
253
  sequence: seq,
192
254
  is_complete: true,
193
255
  timestamp: new Date().toISOString(),
194
- });
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);
195
262
  }
196
263
 
197
264
  /**
@@ -201,8 +268,11 @@ class ActionCableClient extends BaseConnection {
201
268
  * @param {string|null} commandId
202
269
  * @param {number} exitCode
203
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)
204
274
  */
205
- sendComplete(sessionId, commandId, exitCode, durationMs) {
275
+ sendComplete(sessionId, commandId, exitCode, durationMs, extra = {}) {
206
276
  // Suppress the exit→complete event for sessions that were cancelled.
207
277
  // The command_cancelled message is sent separately by _handleCommandCancel.
208
278
  if (this._cancelledSessions && this._cancelledSessions.has(sessionId)) {
@@ -212,14 +282,20 @@ class ActionCableClient extends BaseConnection {
212
282
 
213
283
  const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
214
284
 
215
- this.sendDaemonMessage({
285
+ const message = {
216
286
  type: 'command_complete',
217
287
  session_id: sessionId,
218
288
  command_id: resolvedCommandId,
219
289
  exit_code: exitCode,
220
290
  execution_time_ms: durationMs,
221
291
  timestamp: new Date().toISOString(),
222
- });
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);
223
299
 
224
300
  // Clear active command on completion
225
301
  this._activeCommands.delete(sessionId);
@@ -265,7 +341,34 @@ class ActionCableClient extends BaseConnection {
265
341
  data: JSON.stringify(messageData),
266
342
  };
267
343
 
268
- 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
+ }
269
372
  }
270
373
 
271
374
  // ---------------------------------------------------------------------------
@@ -289,6 +392,8 @@ class ActionCableClient extends BaseConnection {
289
392
  _connect() {
290
393
  if (this._shutdownRequested) return;
291
394
 
395
+ this._clearSubscriptionConfirmTimer();
396
+
292
397
  // Close any prior socket before opening a new one. Some reconnect paths
293
398
  // (e.g. subscription rejection) schedule a reconnect while the existing
294
399
  // socket is still OPEN — without this, the old socket leaks with its
@@ -398,6 +503,8 @@ class ActionCableClient extends BaseConnection {
398
503
  this._authenticated = false;
399
504
  this._subscribed = false;
400
505
 
506
+ this._clearSubscriptionConfirmTimer();
507
+
401
508
  if (this._heartbeatTimer) {
402
509
  clearInterval(this._heartbeatTimer);
403
510
  this._heartbeatTimer = null;
@@ -432,22 +539,26 @@ class ActionCableClient extends BaseConnection {
432
539
  // ---------------------------------------------------------------------------
433
540
 
434
541
  /**
435
- * Welcome received — subscribe to PilotChannel.
542
+ * Welcome received — subscribe to PilotChannel and start timing the
543
+ * confirmation.
436
544
  */
437
545
  _handleWelcome() {
438
546
  this._logger.info('Received welcome, subscribing to PilotChannel');
439
547
  this._subscribeToDaemonChannel();
548
+ this._startSubscriptionConfirmTimer();
440
549
  }
441
550
 
442
551
  /**
443
552
  * Subscription confirmed — mark subscribed, send registration, and emit event.
444
553
  */
445
554
  _handleSubscriptionConfirmed(msg) {
555
+ this._clearSubscriptionConfirmTimer();
446
556
  this._subscribed = true;
447
557
  this._reconnectAttempts = 0; // Backoff resets only after full connect+subscribe success
448
558
  this._consecutiveRejections = 0; // Auth is valid — reset rejection counter
449
559
  this._lastPingAt = Date.now(); // Initialize so watchdog doesn't fire immediately
450
560
  this._logger.info('PilotChannel subscription confirmed');
561
+ this._flushOutboundQueue();
451
562
  this.emit('subscribed');
452
563
  this._sendDaemonRegistration();
453
564
  this._startPingWatchdog();
@@ -457,6 +568,7 @@ class ActionCableClient extends BaseConnection {
457
568
  * Subscription rejected — log and schedule reconnect.
458
569
  */
459
570
  _handleSubscriptionRejected(msg) {
571
+ this._clearSubscriptionConfirmTimer(); // the rejection path decides what happens next
460
572
  this._subscribed = false;
461
573
  this._consecutiveRejections += 1;
462
574
  const reason = (msg && msg.reason) || 'unknown';
@@ -476,6 +588,42 @@ class ActionCableClient extends BaseConnection {
476
588
  this._scheduleReconnect();
477
589
  }
478
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
+
479
627
  /**
480
628
  * Ping received — track freshness timestamp for watchdog monitoring.
481
629
  */
@@ -522,9 +670,15 @@ class ActionCableClient extends BaseConnection {
522
670
  case 'file_request':
523
671
  this._handleFileRequest(inner);
524
672
  break;
673
+ case 'fs_request':
674
+ this._handleFsRequest(inner);
675
+ break;
525
676
  case 'permission_response':
526
677
  this._handlePermissionResponse(inner);
527
678
  break;
679
+ case 'ask_user_question_answer':
680
+ this._handleQuestionAnswer(inner);
681
+ break;
528
682
  case 'auth_error':
529
683
  this._handleAuthError(inner);
530
684
  break;
@@ -579,7 +733,7 @@ class ActionCableClient extends BaseConnection {
579
733
  token: this._authToken,
580
734
  pilot_id: this._daemonId,
581
735
  },
582
- capabilities: this._capabilities,
736
+ capabilities: this._reportedCapabilities(),
583
737
  system_info: {
584
738
  hostname: os.hostname(),
585
739
  platform: process.platform,
@@ -599,6 +753,15 @@ class ActionCableClient extends BaseConnection {
599
753
  this._authenticated = true;
600
754
  this._logger.info('Successfully registered with server');
601
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
+
602
765
  if (message.server_config) {
603
766
  const hbMs = message.server_config.heartbeat_interval || 30000;
604
767
  this._heartbeatInterval = hbMs;
@@ -606,6 +769,10 @@ class ActionCableClient extends BaseConnection {
606
769
  this._logger.info(`Updated server config - heartbeat: ${hbMs / 1000}s`);
607
770
  }
608
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
+
609
776
  // Send an immediate heartbeat so Rails can reconcile zombie sessions right away
610
777
  // instead of waiting up to one heartbeat interval (30s) after reconnect.
611
778
  this._sendHeartbeat().catch((err) => {
@@ -650,6 +817,20 @@ class ActionCableClient extends BaseConnection {
650
817
  * @param {object} message
651
818
  */
652
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) {
653
834
  const sessionId = message.session_id;
654
835
  const userId = message.user_id;
655
836
  const claudeSessionId = message.claude_session_id || undefined;
@@ -664,6 +845,7 @@ class ActionCableClient extends BaseConnection {
664
845
  // Re-read every activation — authors edit persona files mid-session
665
846
  // and we want the next session to pick that up without a daemon restart.
666
847
  systemPrompt = await readPersonaBody(this._config.workingDir, systemPromptPath);
848
+ systemPrompt = (await this._crewHeader(systemPromptPath)) + systemPrompt;
667
849
  } catch (err) {
668
850
  this._logger.error('Persona resolution failed', { sessionId, systemPromptPath, code: err.code, error: err.message });
669
851
  this._sendError('SESSION_ACTIVATION_FAILED', err.message, {
@@ -671,6 +853,7 @@ class ActionCableClient extends BaseConnection {
671
853
  system_prompt_path: systemPromptPath,
672
854
  reason: err.code || 'PERSONA_RESOLUTION_FAILED',
673
855
  });
856
+ this._failAwaitingCommands(sessionId, 'ACTIVATION_FAILED', `Session activation failed: ${err.message}`);
674
857
  return;
675
858
  }
676
859
  }
@@ -713,7 +896,22 @@ class ActionCableClient extends BaseConnection {
713
896
  } catch (err) {
714
897
  this._logger.error('Failed to activate session', { sessionId, error: err.message });
715
898
  this._sendError('SESSION_ACTIVATION_FAILED', err.message, { session_id: sessionId });
899
+ this._failAwaitingCommands(sessionId, 'ACTIVATION_FAILED', `Session activation failed: ${err.message}`);
900
+ return;
716
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;
717
915
  }
718
916
 
719
917
  /**
@@ -721,10 +919,23 @@ class ActionCableClient extends BaseConnection {
721
919
  * @param {object} message
722
920
  */
723
921
  async _handleCommandExecution(message) {
724
- 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);
725
927
  const commandId = message.command_id;
726
928
  const command = message.command;
727
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
+
728
939
  this._logger.info('Executing command', { sessionId, commandId });
729
940
 
730
941
  // Track active command for this session
@@ -732,26 +943,176 @@ class ActionCableClient extends BaseConnection {
732
943
  this._activeCommands.set(sessionId, commandId);
733
944
  }
734
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 });
735
969
  try {
736
- this._daemon.sendMessage(sessionId, command);
970
+ await this._daemon.activateSession(sessionId, {
971
+ workingDir: this._config.workingDir,
972
+ claudeSessionId,
973
+ });
737
974
  } catch (err) {
738
- // Session process may be dead (e.g. after cancel). Try to re-activate
739
- // and retry once before giving up.
740
- this._logger.warn('Command execution failed, attempting re-activation', { sessionId, error: err.message });
741
- try {
742
- await this._daemon.activateSession(sessionId);
743
- this._daemon.sendMessage(sessionId, command);
744
- this._logger.info('Command sent after re-activation', { sessionId, commandId });
745
- } catch (retryErr) {
746
- this._logger.error('Command execution failed after re-activation', { sessionId, error: retryErr.message });
747
- this._sendError('COMMAND_EXECUTION_FAILED', retryErr.message, {
748
- session_id: sessionId,
749
- command_id: commandId,
750
- command: command,
751
- });
752
- // Clear active command on failure
753
- 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}"`);
754
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);
755
1116
  }
756
1117
  }
757
1118
 
@@ -769,8 +1130,8 @@ class ActionCableClient extends BaseConnection {
769
1130
  }
770
1131
 
771
1132
  /**
772
- * Forward a permission request from the PermissionServer to Rails.
773
- * @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
774
1135
  */
775
1136
  _forwardPermissionRequest(req) {
776
1137
  this._logger.info('Forwarding permission request to Rails', {
@@ -783,19 +1144,69 @@ class ActionCableClient extends BaseConnection {
783
1144
  type: 'permission_request',
784
1145
  request_id: req.requestId,
785
1146
  session_id: req.sessionId,
786
- command_id: this._activeCommands.get(req.sessionId) || null,
1147
+ command_id: this._currentCommandId(req.sessionId),
787
1148
  tool_name: req.toolName,
788
1149
  tool_input: req.toolInput,
789
1150
  file_path: req.filePath,
790
1151
  description: req.description,
791
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,
792
1157
  timeout_seconds: req.timeoutSeconds,
793
1158
  timestamp: new Date().toISOString(),
794
1159
  });
795
1160
  }
796
1161
 
797
1162
  /**
798
- * 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.
799
1210
  * @param {object} message
800
1211
  */
801
1212
  _handlePermissionResponse(message) {
@@ -804,10 +1215,10 @@ class ActionCableClient extends BaseConnection {
804
1215
 
805
1216
  this._logger.info('Permission response received from Rails', { requestId, decision });
806
1217
 
807
- if (this._permissionServer) {
808
- this._permissionServer.resolve(requestId, decision, message.reason);
1218
+ if (this._permissionBroker) {
1219
+ this._permissionBroker.resolve(requestId, decision, message.reason);
809
1220
  } else {
810
- this._logger.warn('No permission server to route response to', { requestId });
1221
+ this._logger.warn('No permission broker to route response to', { requestId });
811
1222
  }
812
1223
  }
813
1224
 
@@ -822,10 +1233,24 @@ class ActionCableClient extends BaseConnection {
822
1233
  * @param {object} message
823
1234
  */
824
1235
  async _handleCommandCancel(message) {
825
- 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);
826
1239
  const commandId = message.command_id;
827
1240
  this._logger.info('Interrupting command (kill + immediate respawn)', { sessionId, commandId });
828
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
+
829
1254
  try {
830
1255
  // Suppress the exit→complete event for this session
831
1256
  this._cancelledSessions.add(sessionId);
@@ -845,20 +1270,27 @@ class ActionCableClient extends BaseConnection {
845
1270
  });
846
1271
  this._logger.info('Session respawned after interrupt', { sessionId });
847
1272
  } catch (respawnErr) {
848
- // 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;
849
1276
  this._logger.warn('Immediate respawn failed (will retry on next command)', {
850
1277
  sessionId,
851
1278
  error: respawnErr.message,
852
1279
  });
853
1280
  }
854
1281
 
855
- this.sendDaemonMessage({
1282
+ const cancelled = {
856
1283
  type: 'command_cancelled',
857
1284
  session_id: sessionId,
858
1285
  command_id: commandId,
859
1286
  timestamp: new Date().toISOString(),
860
- });
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);
861
1292
  } else {
1293
+ holdError = new Error(result.message);
862
1294
  this._cancelledSessions.delete(sessionId);
863
1295
  this._sendError('CANCEL_FAILED', result.message, {
864
1296
  session_id: sessionId,
@@ -866,6 +1298,7 @@ class ActionCableClient extends BaseConnection {
866
1298
  });
867
1299
  }
868
1300
  } catch (err) {
1301
+ holdError = err;
869
1302
  this._cancelledSessions.delete(sessionId);
870
1303
  this._logger.error('Failed to cancel command', { sessionId, error: err.message });
871
1304
  this._sendError('CANCEL_FAILED', err.message, {
@@ -873,6 +1306,9 @@ class ActionCableClient extends BaseConnection {
873
1306
  command_id: commandId,
874
1307
  });
875
1308
  }
1309
+
1310
+ // After command_cancelled, so a held command's output follows it.
1311
+ if (proc) this._endCancelHold(sessionId, holdError);
876
1312
  }
877
1313
 
878
1314
  /**
@@ -988,6 +1424,48 @@ class ActionCableClient extends BaseConnection {
988
1424
  }
989
1425
  }
990
1426
 
1427
+ /**
1428
+ * Handle fs_request — generalized filesystem RPC (stat/read) secured by
1429
+ * realpath containment. See src/fs-bridge.js for the containment and op
1430
+ * logic; this method only does message dispatch and response transmission,
1431
+ * mirroring _handleFileRequest's conventions above. That older flow is
1432
+ * plan-doc-specific (.md/.markdown only, lexical containment) and is left
1433
+ * untouched — this is the generalized replacement path for new callers.
1434
+ * @param {object} message - { op, path, request_id, reply_stream }
1435
+ */
1436
+ async _handleFsRequest(message) {
1437
+ const requestId = message.request_id;
1438
+ const replyStream = message.reply_stream;
1439
+ const op = message.op;
1440
+ const requestedPath = message.path;
1441
+
1442
+ this._logger.info('Received fs_request', { op, path: requestedPath, requestId });
1443
+
1444
+ let result;
1445
+ try {
1446
+ result = await handleFsRequest(message, { workingDir: this._workingDir, logger: this._logger });
1447
+ } catch (err) {
1448
+ // handleFsRequest is designed not to throw, but never let an
1449
+ // unexpected exception leave the request unanswered.
1450
+ this._logger.error('fs_request handling threw unexpectedly', { path: requestedPath, error: err.message });
1451
+ result = { op, path: requestedPath, error: `Internal error: ${err.message}` };
1452
+ }
1453
+
1454
+ if (result.error) {
1455
+ this._logger.warn('fs_request failed', { op, path: requestedPath, error: result.error });
1456
+ } else {
1457
+ this._logger.info('fs_request fulfilled', { op, path: requestedPath, exists: result.exists });
1458
+ }
1459
+
1460
+ this.sendDaemonMessage({
1461
+ type: 'fs_response',
1462
+ request_id: requestId,
1463
+ reply_stream: replyStream,
1464
+ ...result,
1465
+ timestamp: new Date().toISOString(),
1466
+ });
1467
+ }
1468
+
991
1469
  // ---------------------------------------------------------------------------
992
1470
  // Outbound helper methods
993
1471
  // ---------------------------------------------------------------------------
@@ -1152,26 +1630,95 @@ class ActionCableClient extends BaseConnection {
1152
1630
  * Send a heartbeat message to the server.
1153
1631
  */
1154
1632
  async _sendHeartbeat() {
1155
- const [gitContext, claudeAccount, personas, machineEffort] = await Promise.all([
1633
+ const [gitContext, claudeAccount, personas, machineEffort, crewMap] = await Promise.all([
1156
1634
  this._getGitContext(),
1157
1635
  this._getClaudeAccount(),
1158
1636
  this._getPersonas(),
1159
1637
  this._getMachineEffort(),
1638
+ this._getCrewMap(),
1160
1639
  ]);
1161
1640
 
1162
- this.sendDaemonMessage({
1641
+ const crewMapField = this._crewMapField(crewMap);
1642
+ const sent = this.sendDaemonMessage({
1163
1643
  type: 'heartbeat',
1644
+ delivery_epoch: this._commandReceipts.epoch,
1645
+ outbound_dropped: this._outboundDropped,
1164
1646
  pilot_id: this._daemonId,
1165
1647
  version: daemonPkg.version,
1166
1648
  status: 'healthy',
1649
+ capabilities: this._reportedCapabilities(),
1167
1650
  session_summary: this._getSessionSummary(),
1168
1651
  resource_usage: this._getResourceUsage(),
1169
1652
  git_context: gitContext,
1170
1653
  claude_account: claudeAccount,
1654
+ claude_usage: this._getClaudeUsage(claudeAccount),
1171
1655
  machine_effort: machineEffort,
1172
1656
  personas,
1657
+ ...crewMapField,
1173
1658
  timestamp: new Date().toISOString(),
1174
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
+ }
1175
1722
  }
1176
1723
 
1177
1724
  /**
@@ -1219,6 +1766,15 @@ class ActionCableClient extends BaseConnection {
1219
1766
  }
1220
1767
  }
1221
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
+
1222
1778
  /**
1223
1779
  * Get this machine's effective default reasoning effort (CLAUDE_EFFORT env or
1224
1780
  * ~/.claude/settings.json `effort`). Returns null when unknown. 60s cache.
@@ -1350,10 +1906,23 @@ class ActionCableClient extends BaseConnection {
1350
1906
  _send(msg) {
1351
1907
  if (!this._ws || this._ws.readyState !== WebSocket.OPEN) {
1352
1908
  this._logger.warn('Cannot send: WebSocket not open');
1353
- 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;
1354
1924
  }
1355
- this._ws.send(JSON.stringify(msg));
1356
1925
  }
1357
1926
  }
1358
1927
 
1359
- module.exports = { ActionCableClient };
1928
+ module.exports = { ActionCableClient, MAX_HELD_COMMANDS_PER_SESSION, ACTIVATION_IN_FLIGHT_ALLOWANCE_MS };