@yu_robotics/remote-cli-router 1.6.217 → 1.6.220

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.
Files changed (34) hide show
  1. package/README.md +10 -4
  2. package/dist/binding/BindingManager.d.ts +3 -1
  3. package/dist/binding/BindingManager.d.ts.map +1 -1
  4. package/dist/binding/BindingManager.js +9 -2
  5. package/dist/binding/BindingManager.js.map +1 -1
  6. package/dist/binding/ThreadSelectionManager.d.ts +9 -4
  7. package/dist/binding/ThreadSelectionManager.d.ts.map +1 -1
  8. package/dist/binding/ThreadSelectionManager.js +21 -7
  9. package/dist/binding/ThreadSelectionManager.js.map +1 -1
  10. package/dist/feishu/ApprovalCards.d.ts +2 -1
  11. package/dist/feishu/ApprovalCards.d.ts.map +1 -1
  12. package/dist/feishu/ApprovalCards.js +2 -1
  13. package/dist/feishu/ApprovalCards.js.map +1 -1
  14. package/dist/feishu/FeishuLongConnHandler.d.ts +9 -5
  15. package/dist/feishu/FeishuLongConnHandler.d.ts.map +1 -1
  16. package/dist/feishu/FeishuLongConnHandler.js +77 -54
  17. package/dist/feishu/FeishuLongConnHandler.js.map +1 -1
  18. package/dist/server.d.ts +9 -7
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/server.js +344 -218
  21. package/dist/server.js.map +1 -1
  22. package/dist/storage/CardThreadState.d.ts +23 -0
  23. package/dist/storage/CardThreadState.d.ts.map +1 -0
  24. package/dist/storage/CardThreadState.js +58 -0
  25. package/dist/storage/CardThreadState.js.map +1 -0
  26. package/dist/storage/JsonStore.d.ts +13 -0
  27. package/dist/storage/JsonStore.d.ts.map +1 -1
  28. package/dist/storage/JsonStore.js +104 -7
  29. package/dist/storage/JsonStore.js.map +1 -1
  30. package/dist/utils/DeliveryDiagnostics.d.ts +46 -0
  31. package/dist/utils/DeliveryDiagnostics.d.ts.map +1 -0
  32. package/dist/utils/DeliveryDiagnostics.js +322 -0
  33. package/dist/utils/DeliveryDiagnostics.js.map +1 -0
  34. package/package.json +1 -1
package/dist/server.js CHANGED
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.RouterServer = void 0;
7
+ const DeliveryDiagnostics_1 = require("./utils/DeliveryDiagnostics");
7
8
  const IngressAdmission_1 = require("./security/IngressAdmission");
8
9
  const ApprovalCards_1 = require("./feishu/ApprovalCards");
9
10
  const WorkerContextCards_1 = require("./feishu/WorkerContextCards");
@@ -25,6 +26,7 @@ const koa_1 = __importDefault(require("koa"));
25
26
  const koa_bodyparser_1 = __importDefault(require("koa-bodyparser"));
26
27
  const router_1 = __importDefault(require("@koa/router"));
27
28
  const ws_1 = require("ws");
29
+ const CardThreadState_1 = require("./storage/CardThreadState");
28
30
  const FeishuLongConnHandler_1 = require("./feishu/FeishuLongConnHandler");
29
31
  const ConnectionHub_1 = require("./websocket/ConnectionHub");
30
32
  const BindingManager_1 = require("./binding/BindingManager");
@@ -72,12 +74,7 @@ class RouterServer {
72
74
  imageReplies = new Map();
73
75
  STREAMING_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes timeout
74
76
  DELEGATION_PROGRESS_HEARTBEAT_MS = 30 * 1000;
75
- // TTL for cardThreadMap entries: 7 days (allows users to reply to old cards)
76
- CARD_THREAD_MAP_TTL_MS = 7 * 24 * 60 * 60 * 1000;
77
- // Map from Feishu card message_id to threadId for parent_id-based routing.
78
- // Entries are NOT removed on finalize so users can reply to completed cards.
79
- // Each entry carries an expiresAt timestamp for TTL-based eviction.
80
- cardThreadMap = new Map();
77
+ CARD_THREAD_MAP_TTL_MS = CardThreadState_1.CARD_THREAD_TTL_MS;
81
78
  selections;
82
79
  threadInventoryRequests = new Map();
83
80
  deviceAuth;
@@ -152,18 +149,18 @@ class RouterServer {
152
149
  this.feishuLongConnHandler.onApproveDeviceKey = async (openId, deviceId, publicKey) => {
153
150
  if ((await this.bindingManager.getDeviceBinding(deviceId))?.openId !== openId)
154
151
  throw new Error('Device ownership changed.');
152
+ await this.selections.invalidateDevice(openId, deviceId);
155
153
  await this.deviceAuth.enroll(deviceId, openId, publicKey);
156
- this.selections.invalidateDevice(openId, deviceId);
157
- this.expireDeviceCards(deviceId);
154
+ this.cancelThreadInventories(deviceId);
158
155
  this.connectionHub.disconnectDevice(deviceId);
159
156
  this.fileTransfers.disconnect(deviceId);
160
157
  };
161
158
  this.feishuLongConnHandler.onRevokeDevice = async (deviceId) => {
162
159
  const owner = await this.bindingManager.getDeviceBinding(deviceId);
163
160
  if (owner?.openId)
164
- this.selections.invalidateDevice(owner.openId, deviceId);
165
- this.expireDeviceCards(deviceId);
161
+ await this.selections.invalidateDevice(owner.openId, deviceId);
166
162
  await this.deviceAuth.revoke(deviceId);
163
+ this.cancelThreadInventories(deviceId);
167
164
  this.connectionHub.disconnectDevice(deviceId);
168
165
  this.fileTransfers.disconnect(deviceId);
169
166
  };
@@ -172,8 +169,12 @@ class RouterServer {
172
169
  sendToDevice: (deviceId, message) => this.connectionHub.sendToDevice(deviceId, message),
173
170
  create: (openId, elements, header) => this.feishuLongConnHandler.sendTaskNotificationCard(openId, elements, header),
174
171
  update: (cardId, elements, header) => this.feishuLongConnHandler.updateApprovalCard(cardId, elements, header),
175
- registerReplyRoute: (cardId, threadId, deviceId, openId) => {
176
- this.cardThreadMap.set(cardId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
172
+ registerReplyRoute: async (cardId, threadId, deviceId, openId, current) => {
173
+ await this.registerCardThread(cardId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, current);
174
+ },
175
+ captureReplyRoute: (openId, deviceId) => {
176
+ const fence = this.selections.capture(openId, deviceId);
177
+ return () => this.selections.isOwnershipCurrent(openId, deviceId, fence.epoch);
177
178
  },
178
179
  });
179
180
  this.feishuLongConnHandler.onApprovalAction = (openId, requestId, cardId, decision) => this.approvalCards.click(openId, requestId, cardId, decision);
@@ -207,7 +208,9 @@ class RouterServer {
207
208
  // Register callback for streaming message start
208
209
  this.feishuLongConnHandler.setOnCaptureSelection((openId, deviceId) => this.selections.capture(openId, deviceId));
209
210
  this.feishuLongConnHandler.setOnValidateSelection(fence => this.selections.isCurrent(fence));
210
- this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName, selectionIntent) => {
211
+ this.feishuLongConnHandler.setOnStartStreaming(async (messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName, selectionIntent) => {
212
+ if (feishuMessageId)
213
+ this.feishuLongConnHandler.bindDiagnosticTask?.(feishuMessageId, messageId);
211
214
  console.log(`[RouterServer] Registering streaming session: msgId=${messageId}, feishuMsgId=${feishuMessageId}, deviceId=${deviceId}, threadId=${threadId}, pendingNewThread=${pendingNewThread}`);
212
215
  this.cancelImageReply(messageId);
213
216
  const previous = this.streamingMessages.get(messageId);
@@ -233,9 +236,9 @@ class RouterServer {
233
236
  delegationProgress: new Map(),
234
237
  toolCalls: new Map(),
235
238
  });
236
- // Populate cardThreadMap for parent_id-based routing
239
+ // Populate card associations for parent_id-based routing
237
240
  if (feishuMessageId && threadId) {
238
- this.cardThreadMap.set(feishuMessageId, { threadId, deviceId, openId, epoch: selectionIntent?.epoch ?? this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
241
+ await this.registerCardThread(feishuMessageId, { threadId, deviceId, openId, epoch: selectionIntent?.epoch ?? this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, () => this.streamingMessages.get(messageId)?.feishuMessageId === feishuMessageId);
239
242
  }
240
243
  console.log(`[RouterServer] Total streaming sessions: ${this.streamingMessages.size}`);
241
244
  });
@@ -248,6 +251,10 @@ class RouterServer {
248
251
  return this.selections.resolve(openId, deviceId);
249
252
  });
250
253
  this.feishuLongConnHandler.onRecoverThreads = async (openId, deviceId) => {
254
+ if (this.stopping || this.threadInventoryRequests.size >= 100) {
255
+ await this.feishuLongConnHandler.sendMessage(openId, 'Thread controls are busy. Retry shortly.');
256
+ return true;
257
+ }
251
258
  const messageId = (0, crypto_1.randomUUID)();
252
259
  const fence = this.selections.beginIntent(openId, deviceId);
253
260
  const timer = setTimeout(() => {
@@ -266,20 +273,35 @@ class RouterServer {
266
273
  return true;
267
274
  };
268
275
  // Register callback for card button thread switching
269
- this.feishuLongConnHandler.onCardSwitchThread = async (openId, cardId, threadId, threadName) => {
276
+ this.feishuLongConnHandler.onCardSwitchThread = async (openId, cardId, threadId) => {
270
277
  const revision = this.selections.reserveIntent(openId);
271
278
  const source = await this.requireCurrentCardDevice(cardId, openId);
272
- const intent = this.selections.intent(openId, source.deviceId, revision);
273
- const selected = await this.selections.select(openId, source.deviceId, threadId, threadName, intent);
274
- if (selected !== 'selected')
275
- throw new Error('This selection was superseded or the device changed. Use a fresh thread card.');
276
- console.log(`[RouterServer] Durable thread selection saved for ${openId}: ${threadName} (${threadId})`);
279
+ const fence = { ...this.selections.intent(openId, source.deviceId, revision), epoch: source.epoch };
280
+ if (!this.selections.isCurrent(fence))
281
+ throw new Error('This selection was superseded. Use a fresh thread card.');
282
+ if (typeof threadId !== 'string' || !threadId || threadId.length > 200)
283
+ throw new Error('Invalid target thread.');
284
+ if (this.stopping || this.threadInventoryRequests.size >= 100)
285
+ throw new Error('Thread controls are busy. Retry shortly.');
286
+ const messageId = (0, crypto_1.randomUUID)();
287
+ return new Promise((resolve, reject) => {
288
+ const fail = () => {
289
+ this.cancelThreadInventory(messageId, new Error('Could not verify the target thread. Reconnect the device and retry /thread list.'));
290
+ };
291
+ const timer = setTimeout(fail, 2000);
292
+ timer.unref?.();
293
+ this.threadInventoryRequests.set(messageId, { openId, deviceId: source.deviceId, fence, timer,
294
+ selection: { cardId, threadId, resolve, reject } });
295
+ void this.connectionHub.sendToDevice(source.deviceId, { type: 'status', messageId, timestamp: Date.now() })
296
+ .then(sent => { if (!sent)
297
+ fail(); }, fail);
298
+ });
277
299
  };
278
300
  // Register callback for creating a new thread via card button
279
301
  this.feishuLongConnHandler.onCardNewThread = async (openId, cardId) => {
280
302
  const revision = this.selections.reserveIntent(openId);
281
303
  const source = await this.requireCurrentCardDevice(cardId, openId);
282
- const intent = this.selections.intent(openId, source.deviceId, revision);
304
+ const intent = { ...this.selections.intent(openId, source.deviceId, revision), epoch: source.epoch };
283
305
  console.log(`[RouterServer] Creating new thread for ${openId} via card button`);
284
306
  await this.feishuLongConnHandler.sendCommandFromCardAction(openId, '/thread new', true, source.deviceId, intent);
285
307
  };
@@ -289,52 +311,38 @@ class RouterServer {
289
311
  this.feishuLongConnHandler.onDeviceSwitchIntent = (openId, newDeviceId) => {
290
312
  this.selections.beginIntent(openId, newDeviceId);
291
313
  };
292
- // Device switches retain independent durable selections and invalidate older intents.
293
- this.feishuLongConnHandler.onDeviceSwitch = (openId, oldDeviceId, newDeviceId) => {
294
- if (oldDeviceId) {
295
- for (const [feishuMessageId, entry] of this.cardThreadMap.entries()) {
296
- if (entry.deviceId === oldDeviceId)
297
- this.cardThreadMap.delete(feishuMessageId);
298
- }
299
- console.log(`[RouterServer] Cleared cardThreadMap entries for old device ${oldDeviceId}`);
300
- }
301
- };
314
+ // JsonStore invalidates both devices atomically with the binding switch. Do not
315
+ // invalidate again in an asynchronous notification: a later switch may have won.
302
316
  this.setupMiddleware();
303
317
  this.setupRoutes();
304
318
  }
305
- expireDeviceCards(deviceId) {
306
- for (const [cardId, entry] of this.cardThreadMap) {
307
- if (entry.deviceId === deviceId)
308
- this.cardThreadMap.delete(cardId);
309
- }
319
+ async registerCardThread(cardId, entry, current = () => true) {
320
+ await this.store.setCardThread(cardId, entry, () => current()
321
+ && this.selections.isOwnershipCurrent(entry.openId, entry.deviceId, entry.epoch));
310
322
  }
311
323
  async resolveCardThread(cardId, openId) {
312
- const entry = this.cardThreadMap.get(cardId);
324
+ const entry = this.store.getCardThread(cardId);
313
325
  if (!entry)
314
326
  return undefined;
315
- if (Date.now() > entry.expiresAt) {
316
- this.cardThreadMap.delete(cardId);
317
- return undefined;
318
- }
319
327
  if (entry.openId !== openId || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch))
320
328
  return undefined;
321
329
  if ((await this.bindingManager.getDeviceBinding(entry.deviceId))?.openId !== openId
322
- || this.cardThreadMap.get(cardId) !== entry
330
+ || this.store.getCardThread(cardId) !== entry
323
331
  || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch))
324
332
  return undefined;
325
333
  return { threadId: entry.threadId, deviceId: entry.deviceId };
326
334
  }
327
335
  async requireCurrentCardDevice(cardId, openId) {
328
- const entry = this.cardThreadMap.get(cardId);
336
+ const entry = this.store.getCardThread(cardId);
329
337
  const source = await this.resolveCardThread(cardId, openId);
330
338
  if (!source)
331
339
  throw new Error('This thread card has expired. Run /thread list for a fresh card.');
332
340
  const active = await this.bindingManager.getActiveDevice(openId);
333
- if (!active || active.deviceId !== source.deviceId || !entry || this.cardThreadMap.get(cardId) !== entry
341
+ if (!active || active.deviceId !== source.deviceId || !entry || this.store.getCardThread(cardId) !== entry
334
342
  || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch)) {
335
343
  throw new Error('This card belongs to a different device. Switch back to that device or use a fresh card.');
336
344
  }
337
- return source;
345
+ return { ...source, epoch: entry.epoch };
338
346
  }
339
347
  /**
340
348
  * Setup Koa middleware
@@ -466,6 +474,7 @@ class RouterServer {
466
474
  this.app.use(router.routes());
467
475
  this.app.use(router.allowedMethods());
468
476
  }
477
+ diagnosticConnectionEpoch = 0;
469
478
  /**
470
479
  * Setup WebSocket server
471
480
  */
@@ -476,6 +485,7 @@ class RouterServer {
476
485
  maxPayload: IngressAdmission_1.INGRESS_LIMITS.payloadBytes
477
486
  });
478
487
  this.wss.on('connection', (ws, req) => {
488
+ const connectionEpoch = ++this.diagnosticConnectionEpoch;
479
489
  const admission = this.stopping ? undefined : this.ingress.admit(req.socket.remoteAddress ?? 'unknown');
480
490
  if (!admission) {
481
491
  ws.on('error', () => { });
@@ -532,7 +542,7 @@ class RouterServer {
532
542
  // If no heartbeat received within 3x interval, consider connection dead
533
543
  const interval = this.config.get('websocket', 'heartbeatInterval');
534
544
  heartbeatTimeout = setTimeout(() => {
535
- console.log('Heartbeat timeout for device:', deviceId);
545
+ (0, DeliveryDiagnostics_1.deliveryEvent)('socket_heartbeat_timeout', { connectionEpoch });
536
546
  ws.close();
537
547
  }, interval * 3);
538
548
  };
@@ -676,17 +686,20 @@ class RouterServer {
676
686
  break;
677
687
  const current = imageCurrent;
678
688
  let success = false;
689
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_resume_received', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch });
679
690
  try {
680
691
  success = await this.handleTaskResume(message, deviceId, current);
681
692
  }
682
693
  catch (error) {
683
- console.error('[RouterServer] Failed to recover task card:', error);
694
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_resume_failed', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch, ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
684
695
  }
685
696
  if (!success && current())
686
697
  this.cancelImageReply(message.messageId);
687
- if (current())
698
+ if (current()) {
688
699
  ws.send(JSON.stringify({ type: 'task_resume_ack', messageId: message.messageId,
689
700
  recoveryId: message.taskResume?.recoveryId, state: message.taskResume?.state, success, timestamp: Date.now() }));
701
+ (0, DeliveryDiagnostics_1.deliveryEvent)('resume_ack_send', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch, success, acceptedLocally: true });
702
+ }
690
703
  break;
691
704
  }
692
705
  case types_1.MessageType.BINDING_REQUEST:
@@ -757,6 +770,8 @@ class RouterServer {
757
770
  this.approvalCards.disconnect(deviceId);
758
771
  this.maintenanceCards.disconnect(deviceId);
759
772
  this.settingsCards.disconnect(deviceId);
773
+ if (!this.connectionHub.isCurrentConnection(deviceId, ws))
774
+ this.cancelThreadInventories(deviceId);
760
775
  if (message.data.capabilities?.queueStarted === true) {
761
776
  this.connectionHub.registerConnection(deviceId, ws, { queueStarted: true });
762
777
  }
@@ -841,8 +856,10 @@ class RouterServer {
841
856
  }));
842
857
  break;
843
858
  case types_1.MessageType.RESPONSE:
859
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_result_received', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch });
844
860
  if (taskRecoveryEnabled && deviceId && this.isCompletedTask(message.messageId, deviceId)) {
845
861
  ws.send(JSON.stringify({ type: 'task_result_ack', messageId: message.messageId, timestamp: Date.now() }));
862
+ (0, DeliveryDiagnostics_1.deliveryEvent)('result_ack_send', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch, acceptedLocally: true, duplicate: true });
846
863
  break;
847
864
  }
848
865
  // Device sends response to command - forward to Feishu via long connection
@@ -871,7 +888,7 @@ class RouterServer {
871
888
  if (responseThreadId) {
872
889
  if (responseSession.feishuMessageId && responseSession.threadId !== responseThreadId) {
873
890
  responseSession.threadId = responseThreadId;
874
- this.cardThreadMap.set(responseSession.feishuMessageId, { threadId: responseThreadId, deviceId: responseSession.deviceId, openId: responseSession.openId, epoch: responseSession.selectionFence?.epoch ?? this.selections.capture(responseSession.openId, responseSession.deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
891
+ await this.registerCardThread(responseSession.feishuMessageId, { threadId: responseThreadId, deviceId: responseSession.deviceId, openId: responseSession.openId, epoch: responseSession.selectionFence?.epoch ?? this.selections.capture(responseSession.openId, responseSession.deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, () => this.streamingMessages.get(responseMessageId) === responseSession && imageCurrent());
875
892
  }
876
893
  if (responseThreads) {
877
894
  const match = responseThreads.find(t => t.id === responseThreadId);
@@ -938,6 +955,7 @@ class RouterServer {
938
955
  this.rememberCompletedTask(responseMessageId, deviceId);
939
956
  if (this.connectionHub.isCurrentConnection(deviceId, ws)) {
940
957
  ws.send(JSON.stringify({ type: 'task_result_ack', messageId: responseMessageId, timestamp: Date.now() }));
958
+ (0, DeliveryDiagnostics_1.deliveryEvent)('result_ack_send', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(responseMessageId), connectionEpoch, acceptedLocally: true, duplicate: false });
941
959
  }
942
960
  }
943
961
  break;
@@ -961,7 +979,7 @@ class RouterServer {
961
979
  // Text is accumulated synchronously. Let subsequent deltas
962
980
  // coalesce while the card patch runs; finalization still
963
981
  // waits for updateInFlight before rendering the result.
964
- void update.catch(error => console.error('[RouterServer] Failed to update queued text:', error));
982
+ void update.catch(error => (0, DeliveryDiagnostics_1.deliveryEvent)('queued_text_failed', (0, DeliveryDiagnostics_1.safeCardError)(error)));
965
983
  }
966
984
  else {
967
985
  await update;
@@ -1016,7 +1034,7 @@ class RouterServer {
1016
1034
  // Background task terminal-state event (Claude Code 2.x).
1017
1035
  // Not tied to any streaming session — rendered as a standalone card.
1018
1036
  if (message.openId && message.taskNotification) {
1019
- await this.handleTaskNotification(message.openId, message.taskNotification, message.threadId, deviceId, message.threadName);
1037
+ await this.handleTaskNotification(message.openId, message.taskNotification, message.threadId, deviceId, message.threadName, imageCurrent);
1020
1038
  }
1021
1039
  else {
1022
1040
  console.log('[RouterServer] Ignoring task_notification with missing openId or payload');
@@ -1027,7 +1045,7 @@ class RouterServer {
1027
1045
  }
1028
1046
  }
1029
1047
  catch (error) {
1030
- console.error('Error processing message:', error);
1048
+ (0, DeliveryDiagnostics_1.deliveryEvent)('router_message_failed', { connectionEpoch, ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
1031
1049
  }
1032
1050
  finally {
1033
1051
  finishQueueMessage?.();
@@ -1043,7 +1061,8 @@ class RouterServer {
1043
1061
  }
1044
1062
  });
1045
1063
  // Handle connection close
1046
- ws.on('close', () => {
1064
+ ws.on('close', (code, reason) => {
1065
+ (0, DeliveryDiagnostics_1.deliveryEvent)('socket_close', { connectionEpoch, code, reasonBytes: reason?.length, registered });
1047
1066
  socketClosed = true;
1048
1067
  releaseAdmission();
1049
1068
  for (const [id, route] of this.imageReplies) {
@@ -1063,8 +1082,8 @@ class RouterServer {
1063
1082
  this.settingsConnections.delete(deviceId);
1064
1083
  this.maintenanceConnections.delete(deviceId);
1065
1084
  this.workerContextConnections.delete(deviceId);
1066
- this.cleanupStreamingSessionsForDevice(deviceId);
1067
- console.log('Device disconnected:', deviceId);
1085
+ void this.cleanupStreamingSessionsForDevice(deviceId).catch(() => console.error('Failed to expire disconnected streaming cards.'));
1086
+ (0, DeliveryDiagnostics_1.deliveryEvent)('registered_socket_removed', { connectionEpoch });
1068
1087
  }
1069
1088
  });
1070
1089
  // Handle errors
@@ -1080,7 +1099,7 @@ class RouterServer {
1080
1099
  if (!registered || (ws.readyState !== ws_1.WebSocket.CLOSING && ws.readyState !== ws_1.WebSocket.CLOSED)) {
1081
1100
  ws.terminate();
1082
1101
  }
1083
- console.error('WebSocket error:', error);
1102
+ (0, DeliveryDiagnostics_1.deliveryEvent)('socket_error', { connectionEpoch, ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
1084
1103
  });
1085
1104
  });
1086
1105
  console.log('WebSocket server listening on /ws');
@@ -1113,7 +1132,7 @@ class RouterServer {
1113
1132
  // Cleanup connections that haven't sent heartbeat in 3x interval
1114
1133
  this.connectionHub.cleanupStaleConnections(heartbeatInterval * 3);
1115
1134
  // Cleanup stale streaming sessions
1116
- this.cleanupStaleStreamingSessions();
1135
+ void this.cleanupStaleStreamingSessions().catch(() => console.error('Failed to expire stale streaming cards.'));
1117
1136
  }, heartbeatInterval);
1118
1137
  console.log(`\n🚀 Router server started successfully!`);
1119
1138
  console.log(` HTTP: http://${host}:${port}`);
@@ -1161,40 +1180,124 @@ class RouterServer {
1161
1180
  return this.streamingMessages.get(messageId) === stream && binding?.openId === stream.openId
1162
1181
  && (!current || current());
1163
1182
  }
1164
- async handleThreadInventoryResponse(message, deviceId, ws) {
1165
- const pending = this.threadInventoryRequests.get(message.messageId);
1183
+ /** Cancellation is definitive only before the storage FIFO admits the guarded draft. */
1184
+ cancelThreadInventory(id, error) {
1185
+ const pending = this.threadInventoryRequests.get(id);
1166
1186
  if (!pending)
1167
1187
  return;
1168
- const current = () => deviceId === pending.deviceId && this.connectionHub.isCurrentConnection(pending.deviceId, ws)
1169
- && this.selections.isCurrent(pending.fence);
1170
- if (!current())
1171
- return;
1172
- const binding = await this.bindingManager.getDeviceBinding(pending.deviceId);
1173
- if (!current() || binding?.openId !== pending.openId)
1174
- return;
1175
1188
  clearTimeout(pending.timer);
1176
- this.threadInventoryRequests.delete(message.messageId);
1177
- const threads = message.status?.threads;
1178
- if (!(0, ThreadSelectionManager_1.isCompleteThreadCatalog)(threads)) {
1179
- await this.feishuLongConnHandler.sendMessage(pending.openId, 'The device returned an invalid thread inventory. Retry /thread list.');
1189
+ if (pending.selection?.commitAdmitted) {
1190
+ pending.selection.acknowledgedPending = true;
1191
+ pending.selection.resolve({ notice: 'The thread selection is still being saved. Do not retry; wait for confirmation or check /thread list after Router recovery.' });
1192
+ // Retain the bounded request slot and its completion handler until I/O settles.
1180
1193
  return;
1181
1194
  }
1182
- const defaultThread = threads.find((thread) => thread.name === 'default');
1195
+ this.threadInventoryRequests.delete(id);
1196
+ pending.selection?.reject(error);
1197
+ }
1198
+ cancelThreadInventories(deviceId) {
1199
+ for (const [id, pending] of this.threadInventoryRequests) {
1200
+ if (pending.deviceId === deviceId)
1201
+ this.cancelThreadInventory(id, new Error('Device connection changed. Retry /thread list.'));
1202
+ }
1203
+ }
1204
+ async sendSelectionOutcome(openId, message) {
1183
1205
  try {
1184
- const reconciled = await this.selections.observeCatalog(pending.openId, pending.deviceId, pending.fence, threads, current);
1185
- if (reconciled === 'stale' || reconciled === 'failed' || !current())
1206
+ await this.feishuLongConnHandler.sendMessage(openId, message);
1207
+ }
1208
+ catch {
1209
+ console.error('Could not deliver the thread selection outcome notice.');
1210
+ }
1211
+ }
1212
+ async handleThreadInventoryResponse(message, deviceId, ws) {
1213
+ const pending = this.threadInventoryRequests.get(message.messageId);
1214
+ if (!pending || pending.processing || deviceId !== pending.deviceId
1215
+ || !this.connectionHub.isCurrentConnection(pending.deviceId, ws))
1216
+ return;
1217
+ pending.processing = true;
1218
+ const current = () => !this.stopping && this.threadInventoryRequests.get(message.messageId) === pending
1219
+ && this.connectionHub.isCurrentConnection(pending.deviceId, ws) && this.selections.isCurrent(pending.fence);
1220
+ try {
1221
+ if (pending.selection) {
1222
+ const { selection } = pending;
1223
+ try {
1224
+ if (!current())
1225
+ throw new Error('This selection was superseded or the device changed.');
1226
+ await this.requireCurrentCardDevice(selection.cardId, pending.openId);
1227
+ const entry = this.store.getCardThread(selection.cardId);
1228
+ const threads = message.status?.threads;
1229
+ if (!(0, ThreadSelectionManager_1.isCompleteThreadCatalog)(threads))
1230
+ throw new Error('The device returned an invalid thread inventory. Retry /thread list.');
1231
+ const target = threads.find(thread => thread.id === selection.threadId);
1232
+ if (!target) {
1233
+ await this.selections.observeCatalog(pending.openId, pending.deviceId, pending.fence, threads, current);
1234
+ throw new Error('This thread no longer exists. Run /thread list for a fresh card.');
1235
+ }
1236
+ const selected = await this.selections.select(pending.openId, pending.deviceId, target.id, target.name, pending.fence, () => current() && !!entry && this.store.getCardThread(selection.cardId) === entry, () => { selection.commitAdmitted = true; });
1237
+ // A stale post-write guard cannot undo a committed snapshot. Report the
1238
+ // historical save without claiming it is still the user's active choice.
1239
+ if (selection.commitAdmitted) {
1240
+ const notice = `Thread preference was saved: ${target.name}. Check /thread list before sending work if the connection or selection changed.`;
1241
+ if (selection.acknowledgedPending)
1242
+ await this.sendSelectionOutcome(pending.openId, notice);
1243
+ else if (selected !== 'selected' || !current())
1244
+ selection.resolve({ notice });
1245
+ else
1246
+ selection.resolve(target.name);
1247
+ }
1248
+ else {
1249
+ if (selected !== 'selected')
1250
+ throw new Error('This selection was superseded or the device changed.');
1251
+ selection.resolve(target.name);
1252
+ }
1253
+ }
1254
+ catch (error) {
1255
+ if (selection.acknowledgedPending)
1256
+ await this.sendSelectionOutcome(pending.openId, 'The thread selection could not be confirmed durably. Do not assume it changed or remained unchanged. Check /thread list after Router storage recovers; no action was replayed.');
1257
+ else
1258
+ selection.reject(error instanceof Error ? error : new Error('Could not save the thread selection.'));
1259
+ }
1186
1260
  return;
1187
- const cardId = await this.feishuLongConnHandler.sendStreamingStart(pending.openId, '🗂️ Thread controls refreshed. Choose a thread for future top-level messages.');
1188
- if (!cardId || !current())
1261
+ }
1262
+ if (!current())
1189
1263
  return;
1190
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(cardId, [], undefined, pending.openId, undefined, 'Thread selection', threads, defaultThread.id);
1191
- if (!finalized || !current())
1264
+ const binding = await this.bindingManager.getDeviceBinding(pending.deviceId);
1265
+ if (!current() || binding?.openId !== pending.openId)
1192
1266
  return;
1193
- this.cardThreadMap.set(cardId, { threadId: defaultThread.id, deviceId: pending.deviceId,
1194
- openId: pending.openId, epoch: pending.fence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1267
+ const threads = message.status?.threads;
1268
+ if (!(0, ThreadSelectionManager_1.isCompleteThreadCatalog)(threads)) {
1269
+ await this.feishuLongConnHandler.sendMessage(pending.openId, 'The device returned an invalid thread inventory. Retry /thread list.');
1270
+ return;
1271
+ }
1272
+ const defaultThread = threads.find((thread) => thread.name === 'default');
1273
+ try {
1274
+ const reconciled = await this.selections.observeCatalog(pending.openId, pending.deviceId, pending.fence, threads, current);
1275
+ if (reconciled === 'stale' || reconciled === 'failed' || !current())
1276
+ return;
1277
+ const cardId = await this.feishuLongConnHandler.sendStreamingStart(pending.openId, '🗂️ Thread controls refreshed. Choose a thread for future top-level messages.');
1278
+ if (!cardId || !current())
1279
+ return;
1280
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(cardId, [], undefined, pending.openId, undefined, 'Thread selection', threads, defaultThread.id, undefined, undefined, true, { onDelivered: async (cardIds) => {
1281
+ for (const deliveredId of cardIds)
1282
+ await this.registerCardThread(deliveredId, {
1283
+ threadId: defaultThread.id, deviceId: pending.deviceId, openId: pending.openId,
1284
+ epoch: pending.fence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
1285
+ }, current);
1286
+ } });
1287
+ if (!finalized || !current())
1288
+ return;
1289
+ await this.registerCardThread(cardId, { threadId: defaultThread.id, deviceId: pending.deviceId,
1290
+ openId: pending.openId, epoch: pending.fence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, current);
1291
+ }
1292
+ catch {
1293
+ if (current())
1294
+ await this.feishuLongConnHandler.sendMessage(pending.openId, 'Could not create thread controls. Retry /thread list.');
1295
+ }
1195
1296
  }
1196
- catch {
1197
- await this.feishuLongConnHandler.sendMessage(pending.openId, 'Could not create thread controls. Retry /thread list.');
1297
+ finally {
1298
+ clearTimeout(pending.timer);
1299
+ if (this.threadInventoryRequests.get(message.messageId) === pending)
1300
+ this.threadInventoryRequests.delete(message.messageId);
1198
1301
  }
1199
1302
  }
1200
1303
  matchesActivityStream(message, deviceId) {
@@ -1234,9 +1337,9 @@ class RouterServer {
1234
1337
  stream.threadName = threadName;
1235
1338
  stream.cwd = cwd;
1236
1339
  if (stream.feishuMessageId) {
1237
- this.cardThreadMap.set(stream.feishuMessageId, {
1340
+ await this.registerCardThread(stream.feishuMessageId, {
1238
1341
  threadId, deviceId, openId: stream.openId, epoch: stream.selectionFence?.epoch ?? this.selections.capture(stream.openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
1239
- });
1342
+ }, () => this.streamingMessages.get(messageId) === stream);
1240
1343
  await this.updateStreamingText(messageId, openId, stream);
1241
1344
  }
1242
1345
  }
@@ -1508,7 +1611,7 @@ class RouterServer {
1508
1611
  await this.updateStreamingText(messageId, streamData.openId, streamData);
1509
1612
  }
1510
1613
  catch (error) {
1511
- console.error('[RouterServer] Failed to refresh delegated worker progress:', error);
1614
+ (0, DeliveryDiagnostics_1.deliveryEvent)('worker_progress_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1512
1615
  }
1513
1616
  finally {
1514
1617
  if (this.isLiveDelegationProgress(messageId, streamData, state)) {
@@ -1878,6 +1981,7 @@ class RouterServer {
1878
1981
  return false;
1879
1982
  if (this.isCompletedTask(messageId, deviceId))
1880
1983
  return true;
1984
+ const selectionFence = this.selections.capture(openId, deviceId);
1881
1985
  const previous = this.streamingMessages.get(messageId);
1882
1986
  if (previous && (previous.deviceId !== deviceId || previous.openId !== openId
1883
1987
  || (previous.threadId && previous.threadId !== threadId)))
@@ -1887,6 +1991,8 @@ class RouterServer {
1887
1991
  const reusable = previous?.feishuMessageId && (!previous.finalizing
1888
1992
  || (previous.recoveryId === info.recoveryId && info.state !== 'running'));
1889
1993
  if (previous && reusable) {
1994
+ (0, DeliveryDiagnostics_1.deliveryEvent)('resume_card_reused', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(messageId), card: (0, DeliveryDiagnostics_1.taskCorrelation)(previous.feishuMessageId),
1995
+ reason: previous.finalizing ? 'same_recovery_terminal_retry' : 'existing_active_card' });
1890
1996
  if (previous.recoveryId !== info.recoveryId) {
1891
1997
  await previous.updateInFlight;
1892
1998
  if (!isCurrent() || this.streamingMessages.get(messageId) !== previous || previous.finalizing)
@@ -1922,7 +2028,7 @@ class RouterServer {
1922
2028
  previous.lastRenderedTextLength = textLength;
1923
2029
  this.lastStreamUpdateTime.set(messageId, Date.now());
1924
2030
  }
1925
- this.cardThreadMap.set(previous.feishuMessageId, { threadId, deviceId, openId, epoch: previous.selectionFence?.epoch ?? this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
2031
+ await this.registerCardThread(previous.feishuMessageId, { threadId, deviceId, openId, epoch: previous.selectionFence?.epoch ?? this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, () => isCurrent() && this.streamingMessages.get(messageId) === previous);
1926
2032
  }
1927
2033
  else {
1928
2034
  const escape = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -1930,9 +2036,12 @@ class RouterServer {
1930
2036
  + `Output before this card, including output during disconnection, was not retained.\n\n`
1931
2037
  + `**Thread:** <raw>${escape(info.threadName)}</raw> · **Backend:** <raw>${escape(info.backend)}</raw>\n`
1932
2038
  + `**Working directory:** <raw>${escape(info.cwd)}</raw>\n**Task:** <raw>${escape(info.preview)}</raw>`;
1933
- const cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd);
2039
+ const cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd, messageId);
1934
2040
  if (!cardId || !isCurrent())
1935
2041
  return false;
2042
+ this.feishuLongConnHandler.bindDiagnosticTask?.(cardId, messageId);
2043
+ (0, DeliveryDiagnostics_1.deliveryEvent)('resume_card_created', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(messageId), card: (0, DeliveryDiagnostics_1.taskCorrelation)(cardId),
2044
+ reason: previous?.finalizing ? 'previous_card_finalizing' : previous ? 'previous_card_missing' : 'no_previous_stream' });
1936
2045
  if (previous)
1937
2046
  this.clearDelegationProgressTimers(previous);
1938
2047
  this.streamingMessages.set(messageId, {
@@ -1941,9 +2050,9 @@ class RouterServer {
1941
2050
  createdAt: Date.now(), updatePending: false, finalizing: false, lastRenderedTextLength: 0,
1942
2051
  delegationProgress: new Map(),
1943
2052
  toolCalls: new Map(),
1944
- recoveryId: info.recoveryId, recoveryPlainText: true, recoveryCwd: info.cwd,
2053
+ recoveryId: info.recoveryId, recoveryPlainText: true, recoveryCwd: info.cwd, selectionFence,
1945
2054
  });
1946
- this.cardThreadMap.set(cardId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
2055
+ await this.registerCardThread(cardId, { threadId, deviceId, openId, epoch: selectionFence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, isCurrent);
1947
2056
  }
1948
2057
  this.bindImageStream(messageId);
1949
2058
  if (info.state !== 'running') {
@@ -1964,6 +2073,7 @@ class RouterServer {
1964
2073
  || typeof info.cwd !== 'string' || typeof info.preview !== 'string'
1965
2074
  || !Number.isInteger(info.remainingCount) || info.remainingCount < 0)
1966
2075
  return;
2076
+ const selectionFence = this.selections.capture(openId, deviceId);
1967
2077
  const previous = this.streamingMessages.get(messageId);
1968
2078
  if (previous && (previous.deviceId !== deviceId || previous.openId !== openId
1969
2079
  || (previous.threadId && previous.threadId !== threadId)))
@@ -1985,10 +2095,12 @@ class RouterServer {
1985
2095
  **Remaining in queue:** ${info.remainingCount}`;
1986
2096
  let cardId = null;
1987
2097
  try {
1988
- cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd);
2098
+ cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd, messageId);
2099
+ if (cardId)
2100
+ this.feishuLongConnHandler.bindDiagnosticTask?.(cardId, messageId);
1989
2101
  }
1990
2102
  catch (error) {
1991
- console.error('[RouterServer] Failed to create queued execution card:', error);
2103
+ (0, DeliveryDiagnostics_1.deliveryEvent)('queued_card_create_failed', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(messageId), ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
1992
2104
  }
1993
2105
  if (!isCurrent() || (imageRoute && this.imageReplies.get(messageId) !== imageRoute))
1994
2106
  return;
@@ -2013,13 +2125,14 @@ class RouterServer {
2013
2125
  delegationProgress: new Map(),
2014
2126
  toolCalls: new Map(),
2015
2127
  queueStarted: info,
2128
+ selectionFence,
2016
2129
  threads: Array.isArray(message.threads) ? message.threads : undefined,
2017
2130
  });
2018
2131
  this.bindImageStream(messageId);
2019
2132
  if (cardId || fallbackCardId) {
2020
- this.cardThreadMap.set((cardId || fallbackCardId), {
2021
- threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
2022
- });
2133
+ await this.registerCardThread((cardId || fallbackCardId), {
2134
+ threadId, deviceId, openId, epoch: selectionFence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
2135
+ }, isCurrent);
2023
2136
  }
2024
2137
  if (cardId) {
2025
2138
  const oldCards = new Set([previous?.queueCardId, previous?.feishuMessageId]);
@@ -2033,7 +2146,7 @@ class RouterServer {
2033
2146
  }
2034
2147
  catch (error) {
2035
2148
  // The new execution card remains usable if its old receipt expired.
2036
- console.error('[RouterServer] Failed to update queue receipt:', error);
2149
+ (0, DeliveryDiagnostics_1.deliveryEvent)('queue_receipt_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
2037
2150
  }
2038
2151
  }
2039
2152
  }
@@ -2054,10 +2167,10 @@ class RouterServer {
2054
2167
  * Sent as a standalone one-shot card — the event may arrive while no
2055
2168
  * streaming session exists (the originating command's card is often
2056
2169
  * already finalized), so it deliberately never touches streamingMessages.
2057
- * The new card is registered in cardThreadMap so the user can reply to it
2170
+ * The new card has a durable association so the user can reply to it
2058
2171
  * to continue working in the originating thread.
2059
2172
  */
2060
- async handleTaskNotification(openId, info, threadId, deviceId, threadName) {
2173
+ async handleTaskNotification(openId, info, threadId, deviceId, threadName, current = () => true) {
2061
2174
  // Boundary validation — the WS message is external data, never trust it.
2062
2175
  // Required for rendering: a non-empty taskId and a string summary.
2063
2176
  // Unknown status values are allowed through (forward compatibility);
@@ -2069,17 +2182,18 @@ class RouterServer {
2069
2182
  console.log(`[RouterServer] Task notification for ${openId}: task=${info.taskId} status=${info.status} thread=${threadId || 'default'}`);
2070
2183
  const threadLabel = typeof threadName === 'string' && threadName.trim()
2071
2184
  ? threadName : typeof threadId === 'string' && threadId.trim() ? threadId : undefined;
2185
+ const selectionFence = deviceId ? this.selections.capture(openId, deviceId) : undefined;
2072
2186
  const elements = (0, ToolFormatter_1.createTaskNotificationElement)(info, threadLabel);
2073
2187
  const feishuMessageId = await this.feishuLongConnHandler.sendTaskNotificationCard(openId, elements);
2074
- if (feishuMessageId && threadId && deviceId) {
2075
- this.cardThreadMap.set(feishuMessageId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
2188
+ if (feishuMessageId && threadId && deviceId && selectionFence) {
2189
+ await this.registerCardThread(feishuMessageId, { threadId, deviceId, openId, epoch: selectionFence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, current);
2076
2190
  console.log(`[RouterServer] Registered task notification card ${feishuMessageId} for thread ${threadId}`);
2077
2191
  }
2078
2192
  }
2079
2193
  /**
2080
2194
  * Finalize streaming message
2081
2195
  */
2082
- registerDeliveredThreadCards(messageId, streamData, cardIds) {
2196
+ async registerDeliveredThreadCards(messageId, streamData, cardIds) {
2083
2197
  if (!streamData.threadId || this.streamingMessages.get(messageId) !== streamData)
2084
2198
  return;
2085
2199
  const fence = streamData.selectionFence;
@@ -2088,111 +2202,126 @@ class RouterServer {
2088
2202
  const epoch = fence?.epoch ?? this.selections.capture(streamData.openId, streamData.deviceId).epoch;
2089
2203
  if (!this.selections.isOwnershipCurrent(streamData.openId, streamData.deviceId, epoch))
2090
2204
  return;
2091
- for (const cardId of cardIds) {
2092
- if (typeof cardId !== 'string' || !cardId)
2093
- continue;
2094
- this.cardThreadMap.set(cardId, { threadId: streamData.threadId, deviceId: streamData.deviceId,
2095
- openId: streamData.openId, epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
2205
+ const delivered = cardIds.filter(id => typeof id === 'string' && id.length > 0);
2206
+ streamData.deliveredCardIds ??= new Set();
2207
+ // Track the whole batch before disk I/O so interruption revokes pending writes too.
2208
+ for (const cardId of delivered)
2209
+ streamData.deliveredCardIds.add(cardId);
2210
+ for (const cardId of delivered) {
2211
+ await this.registerCardThread(cardId, { threadId: streamData.threadId, deviceId: streamData.deviceId,
2212
+ openId: streamData.openId, epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, () => this.streamingMessages.get(messageId) === streamData && (!streamData.currentConnection || streamData.currentConnection()));
2096
2213
  }
2097
2214
  }
2098
2215
  async finalizeStreamingMessage(messageId, success, output, error, sessionAbbr, cwd, queueConfirmation, executionMetadata, settingsMenu) {
2099
2216
  const streamData = this.streamingMessages.get(messageId);
2100
2217
  if (!streamData)
2101
2218
  return;
2102
- const route = this.imageReplies.get(messageId);
2103
- if (route)
2104
- this.images.close(route.reply);
2105
- this.closeImageIntake(streamData, route?.reply.deadline);
2106
- // Snapshot accepted work before awaiting; intake is already closed.
2107
- const accepted = route?.reply.tail;
2108
- if (accepted)
2109
- await accepted;
2110
- if (this.streamingMessages.get(messageId) !== streamData
2111
- || (route && (this.imageReplies.get(messageId) !== route || !route.current())))
2112
- return;
2113
- if (route?.reply.failed)
2114
- this.noteImageFailure(messageId, streamData);
2115
- this.cancelImageReply(messageId);
2116
- streamData.finalizing = true;
2117
- streamData.updatePending = false;
2118
- this.clearDelegationProgressTimers(streamData);
2119
- await streamData.updateInFlight;
2120
- if (!await this.canDispatchStreamOutput(messageId, streamData))
2121
- return;
2122
- const { feishuMessageId, openId } = streamData;
2123
- if (feishuMessageId) {
2124
- // Flush any remaining text content
2125
- if (streamData.currentTextContent.trim()) {
2126
- streamData.elements.push(...this.renderCurrentText(streamData));
2127
- streamData.currentTextContent = '';
2128
- streamData.recoveryPlainText = false;
2129
- }
2130
- // If there are no elements at all, use the output parameter as fallback
2131
- if (streamData.elements.length === 0 && output) {
2132
- streamData.elements.push((0, ToolFormatter_1.createMarkdownElement)(output));
2133
- }
2134
- // A capable CLI's settings menu replaces the placeholder with a dedicated
2135
- // interactive card bound to the original user/device/thread/request. The
2136
- // text output is for incapable peers or delivery failure only: including
2137
- // its complete catalog here would defeat pagination and its node/byte budget.
2138
- const prepared = settingsMenu && success
2139
- ? this.settingsCards.present({ openId: streamData.openId, deviceId: streamData.deviceId, menu: settingsMenu, requestMessageId: messageId, expectedThreadId: streamData.threadId })
2140
- : undefined;
2141
- if (prepared) {
2142
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, prepared.elements, undefined, openId, cwd, streamData.threadName, undefined, streamData.threadId, undefined, undefined, true, { bare: true, onDelivered: cardIds => prepared.deliver(cardIds) });
2143
- if (!finalized) {
2144
- prepared.discard();
2145
- if (!await this.canDispatchStreamOutput(messageId, streamData))
2146
- return;
2147
- const delivered = await this.feishuLongConnHandler.sendMessage(openId, output || '⚙️ Settings are unavailable as a card. Use the text command.');
2148
- if (delivered === false)
2149
- throw new Error('Failed to deliver settings result');
2219
+ const task = (0, DeliveryDiagnostics_1.taskCorrelation)(messageId);
2220
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_finalization_started', { task, card: (0, DeliveryDiagnostics_1.taskCorrelation)(streamData.feishuMessageId) });
2221
+ try {
2222
+ const route = this.imageReplies.get(messageId);
2223
+ if (route)
2224
+ this.images.close(route.reply);
2225
+ this.closeImageIntake(streamData, route?.reply.deadline);
2226
+ // Snapshot accepted work before awaiting; intake is already closed.
2227
+ const accepted = route?.reply.tail;
2228
+ if (accepted)
2229
+ await accepted;
2230
+ if (this.streamingMessages.get(messageId) !== streamData
2231
+ || (route && (this.imageReplies.get(messageId) !== route || !route.current())))
2232
+ return;
2233
+ if (route?.reply.failed)
2234
+ this.noteImageFailure(messageId, streamData);
2235
+ this.cancelImageReply(messageId);
2236
+ streamData.finalizing = true;
2237
+ streamData.updatePending = false;
2238
+ this.clearDelegationProgressTimers(streamData);
2239
+ await streamData.updateInFlight;
2240
+ if (!await this.canDispatchStreamOutput(messageId, streamData))
2241
+ return;
2242
+ const { feishuMessageId, openId } = streamData;
2243
+ if (feishuMessageId) {
2244
+ // Flush any remaining text content
2245
+ if (streamData.currentTextContent.trim()) {
2246
+ streamData.elements.push(...this.renderCurrentText(streamData));
2247
+ streamData.currentTextContent = '';
2248
+ streamData.recoveryPlainText = false;
2249
+ }
2250
+ // If there are no elements at all, use the output parameter as fallback
2251
+ if (streamData.elements.length === 0 && output) {
2252
+ streamData.elements.push((0, ToolFormatter_1.createMarkdownElement)(output));
2253
+ }
2254
+ // A capable CLI's settings menu replaces the placeholder with a dedicated
2255
+ // interactive card bound to the original user/device/thread/request. The
2256
+ // text output is for incapable peers or delivery failure only: including
2257
+ // its complete catalog here would defeat pagination and its node/byte budget.
2258
+ const prepared = settingsMenu && success
2259
+ ? this.settingsCards.present({ openId: streamData.openId, deviceId: streamData.deviceId, menu: settingsMenu, requestMessageId: messageId, expectedThreadId: streamData.threadId })
2260
+ : undefined;
2261
+ if (prepared) {
2262
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, prepared.elements, undefined, openId, cwd, streamData.threadName, undefined, streamData.threadId, undefined, undefined, true, { bare: true, onDelivered: cardIds => prepared.deliver(cardIds) });
2263
+ if (!finalized) {
2264
+ prepared.discard();
2265
+ if (!await this.canDispatchStreamOutput(messageId, streamData))
2266
+ return;
2267
+ const delivered = await this.feishuLongConnHandler.sendMessage(openId, output || '⚙️ Settings are unavailable as a card. Use the text command.');
2268
+ if (delivered === false)
2269
+ throw new Error('Failed to deliver settings result');
2270
+ }
2271
+ }
2272
+ else if (success) {
2273
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, streamData.elements, sessionAbbr, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata, true, { onDelivered: cardIds => this.registerDeliveredThreadCards(messageId, streamData, cardIds) });
2274
+ if (finalized === false)
2275
+ throw new Error('Failed to finalize task card');
2276
+ }
2277
+ else {
2278
+ // Add error message to elements
2279
+ const finalElements = [...streamData.elements];
2280
+ if (!queueConfirmation) {
2281
+ const errorMsg = error || 'Command failed';
2282
+ finalElements.push((0, ToolFormatter_1.createMarkdownElement)(`\n\n❌ **Error:** ${errorMsg}`));
2283
+ }
2284
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, finalElements, undefined, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata, false, { onDelivered: cardIds => this.registerDeliveredThreadCards(messageId, streamData, cardIds) });
2285
+ if (finalized === false)
2286
+ throw new Error('Failed to finalize task card');
2150
2287
  }
2151
2288
  }
2152
- else if (success) {
2153
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, streamData.elements, sessionAbbr, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata, true, { onDelivered: cardIds => this.registerDeliveredThreadCards(messageId, streamData, cardIds) });
2154
- if (finalized === false)
2155
- throw new Error('Failed to finalize task card');
2289
+ else if (streamData.queueStarted) {
2290
+ // If card creation failed after session recovery, retain a text result
2291
+ // rather than silently losing the completed queued task's output.
2292
+ const text = streamData.elements
2293
+ .filter((element) => element.tag === 'markdown')
2294
+ .map((element) => element.content)
2295
+ .concat(streamData.currentTextContent, output || '')
2296
+ .filter(Boolean)
2297
+ .join('\n\n');
2298
+ const delivered = await this.feishuLongConnHandler.sendMessage(openId, `${text}\n\n${success ? '✅ Completed' : `❌ Error: ${error || 'Command failed'}`}`);
2299
+ if (delivered === false)
2300
+ throw new Error('Failed to deliver task result');
2156
2301
  }
2157
- else {
2158
- // Add error message to elements
2159
- const finalElements = [...streamData.elements];
2160
- if (!queueConfirmation) {
2161
- const errorMsg = error || 'Command failed';
2162
- finalElements.push((0, ToolFormatter_1.createMarkdownElement)(`\n\n❌ **Error:** ${errorMsg}`));
2163
- }
2164
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, finalElements, undefined, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata, false, { onDelivered: cardIds => this.registerDeliveredThreadCards(messageId, streamData, cardIds) });
2165
- if (finalized === false)
2166
- throw new Error('Failed to finalize task card');
2302
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_finalization_complete', { task });
2303
+ // Keep durable card associations after removing the completed streaming session.
2304
+ if (this.streamingMessages.get(messageId) === streamData) {
2305
+ this.streamingMessages.delete(messageId);
2306
+ this.lastStreamUpdateTime.delete(messageId);
2167
2307
  }
2168
2308
  }
2169
- else if (streamData.queueStarted) {
2170
- // If card creation failed after session recovery, retain a text result
2171
- // rather than silently losing the completed queued task's output.
2172
- const text = streamData.elements
2173
- .filter((element) => element.tag === 'markdown')
2174
- .map((element) => element.content)
2175
- .concat(streamData.currentTextContent, output || '')
2176
- .filter(Boolean)
2177
- .join('\n\n');
2178
- const delivered = await this.feishuLongConnHandler.sendMessage(openId, `${text}\n\n${success ? '✅ Completed' : `❌ Error: ${error || 'Command failed'}`}`);
2179
- if (delivered === false)
2180
- throw new Error('Failed to deliver task result');
2181
- }
2182
- // Clean up streaming session state (but NOT cardThreadMap — keep it alive
2183
- // so users can reply to the completed card and route to the same thread).
2184
- if (this.streamingMessages.get(messageId) === streamData) {
2185
- this.streamingMessages.delete(messageId);
2186
- this.lastStreamUpdateTime.delete(messageId);
2309
+ catch (failure) {
2310
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_finalization_failed', { task, ...(0, DeliveryDiagnostics_1.safeCardError)(failure) });
2311
+ throw failure;
2187
2312
  }
2188
2313
  }
2189
- /**
2190
- * Cleanup stale streaming sessions that have timed out
2191
- * This prevents memory leaks when devices disconnect without sending a response
2192
- */
2193
- cleanupStaleStreamingSessions() {
2314
+ removeActiveCardRoutes(session) {
2315
+ const ids = new Set(session.deliveredCardIds);
2316
+ if (session.feishuMessageId)
2317
+ ids.add(session.feishuMessageId);
2318
+ return [...ids].map(id => this.store.removeCardThread(id));
2319
+ }
2320
+ /** Clean up timed-out executions without discarding completed card routes. */
2321
+ async cleanupStaleStreamingSessions() {
2194
2322
  const now = Date.now();
2195
2323
  let cleanedCount = 0;
2324
+ const removals = [];
2196
2325
  for (const [messageId, route] of this.imageReplies) {
2197
2326
  if (!route.current() || (!this.streamingMessages.has(messageId)
2198
2327
  && now - route.createdAt > this.STREAMING_SESSION_TIMEOUT_MS))
@@ -2201,14 +2330,12 @@ class RouterServer {
2201
2330
  for (const [messageId, session] of this.streamingMessages.entries()) {
2202
2331
  if (now - session.createdAt > this.STREAMING_SESSION_TIMEOUT_MS) {
2203
2332
  console.log(`[RouterServer] Cleaning up stale streaming session: ${messageId}`);
2204
- // Stale in-flight sessions have their cardThreadMap entry removed;
2333
+ // Stale in-flight sessions lose their card association;
2205
2334
  // completed sessions deliberately keep theirs (see finalizeStreamingMessage).
2206
- if (session.feishuMessageId) {
2207
- this.cardThreadMap.delete(session.feishuMessageId);
2208
- }
2335
+ this.streamingMessages.delete(messageId);
2336
+ removals.push(...this.removeActiveCardRoutes(session));
2209
2337
  this.clearDelegationProgressTimers(session);
2210
2338
  this.cancelImageReply(messageId);
2211
- this.streamingMessages.delete(messageId);
2212
2339
  this.lastStreamUpdateTime.delete(messageId);
2213
2340
  cleanedCount++;
2214
2341
  }
@@ -2218,12 +2345,11 @@ class RouterServer {
2218
2345
  this.startedQueueMessages.delete(messageId);
2219
2346
  }
2220
2347
  }
2221
- // Evict expired cardThreadMap entries (TTL-based, independent of streaming sessions)
2222
- for (const [feishuMessageId, entry] of this.cardThreadMap.entries()) {
2223
- if (now > entry.expiresAt) {
2224
- this.cardThreadMap.delete(feishuMessageId);
2225
- }
2226
- }
2348
+ const results = await Promise.allSettled(removals);
2349
+ await this.store.pruneCardThreads();
2350
+ const failed = results.find(result => result.status === 'rejected');
2351
+ if (failed?.status === 'rejected')
2352
+ throw failed.reason;
2227
2353
  if (cleanedCount > 0) {
2228
2354
  console.log(`[RouterServer] Cleaned up ${cleanedCount} stale streaming sessions, remaining: ${this.streamingMessages.size}`);
2229
2355
  }
@@ -2232,31 +2358,30 @@ class RouterServer {
2232
2358
  * Cleanup streaming sessions for a specific device when it disconnects
2233
2359
  * @param deviceId Device ID that disconnected
2234
2360
  */
2235
- cleanupStreamingSessionsForDevice(deviceId) {
2361
+ async cleanupStreamingSessionsForDevice(deviceId) {
2362
+ this.cancelThreadInventories(deviceId);
2236
2363
  this.cancelDeviceImages(deviceId);
2237
2364
  let cleanedCount = 0;
2365
+ const removals = [];
2238
2366
  for (const [messageId, session] of this.streamingMessages.entries()) {
2239
2367
  if (session.deviceId === deviceId) {
2240
2368
  console.log(`[RouterServer] Cleaning up streaming session for disconnected device: ${messageId}`);
2241
- // Also clean up any cardThreadMap entries associated with this session's feishuMessageId
2242
- if (session.feishuMessageId) {
2243
- this.cardThreadMap.delete(session.feishuMessageId);
2244
- }
2369
+ // Remove the session identity before awaiting durable card removal.
2370
+ this.streamingMessages.delete(messageId);
2371
+ removals.push(...this.removeActiveCardRoutes(session));
2245
2372
  this.clearDelegationProgressTimers(session);
2246
2373
  this.cancelImageReply(messageId);
2247
- this.streamingMessages.delete(messageId);
2248
2374
  this.lastStreamUpdateTime.delete(messageId);
2249
2375
  cleanedCount++;
2250
2376
  }
2251
2377
  }
2252
- // Clean up any orphaned cardThreadMap entries for this device
2253
- for (const [feishuMessageId, entry] of this.cardThreadMap.entries()) {
2254
- if (entry.deviceId === deviceId) {
2255
- this.cardThreadMap.delete(feishuMessageId);
2256
- }
2257
- }
2378
+ // Completed cards survive ordinary disconnects and Router shutdown.
2379
+ const results = await Promise.allSettled(removals);
2380
+ const failed = results.find(result => result.status === 'rejected');
2381
+ if (failed?.status === 'rejected')
2382
+ throw failed.reason;
2258
2383
  if (cleanedCount > 0) {
2259
- console.log(`[RouterServer] Cleaned up ${cleanedCount} streaming sessions for device ${deviceId}, remaining: ${this.streamingMessages.size}`);
2384
+ (0, DeliveryDiagnostics_1.deliveryEvent)('disconnected_streams_cleaned', { count: cleanedCount, remaining: this.streamingMessages.size });
2260
2385
  }
2261
2386
  }
2262
2387
  /**
@@ -2283,9 +2408,9 @@ class RouterServer {
2283
2408
  };
2284
2409
  // Drain accepted binding writes before any slow card or transfer cleanup.
2285
2410
  // A failure must not skip the remaining resource cleanup or be hidden.
2286
- for (const pending of this.threadInventoryRequests.values())
2287
- clearTimeout(pending.timer);
2288
- this.threadInventoryRequests.clear();
2411
+ for (const id of this.threadInventoryRequests.keys()) {
2412
+ this.cancelThreadInventory(id, new Error('Router is stopping. Retry the thread selection.'));
2413
+ }
2289
2414
  await attempt('Error flushing bindings during shutdown', () => this.store.flush());
2290
2415
  await attempt('Error stopping Tips scheduler', () => this.tips.stop());
2291
2416
  for (const id of this.imageReplies.keys())
@@ -2312,7 +2437,7 @@ class RouterServer {
2312
2437
  catch (error) {
2313
2438
  failed = true;
2314
2439
  firstError ??= error;
2315
- console.error(`[RouterServer] Failed to finalize streaming card ${messageId} during shutdown:`, error);
2440
+ (0, DeliveryDiagnostics_1.deliveryEvent)('shutdown_card_finalize_failed', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(messageId), ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
2316
2441
  }
2317
2442
  }
2318
2443
  this.streamingMessages.clear();
@@ -2345,6 +2470,7 @@ class RouterServer {
2345
2470
  });
2346
2471
  });
2347
2472
  }
2473
+ await attempt('Error flushing card routes during shutdown', () => this.store.flush());
2348
2474
  if (failed)
2349
2475
  throw firstError;
2350
2476
  console.log('✅ Router server stopped');