@yu_robotics/remote-cli-router 1.6.219 → 1.6.221

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -4,6 +4,8 @@ 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 OutputTransfers_1 = require("./output/OutputTransfers");
8
+ const DeliveryDiagnostics_1 = require("./utils/DeliveryDiagnostics");
7
9
  const IngressAdmission_1 = require("./security/IngressAdmission");
8
10
  const ApprovalCards_1 = require("./feishu/ApprovalCards");
9
11
  const WorkerContextCards_1 = require("./feishu/WorkerContextCards");
@@ -78,6 +80,9 @@ class RouterServer {
78
80
  threadInventoryRequests = new Map();
79
81
  deviceAuth;
80
82
  fileTransfers;
83
+ outputTransfers;
84
+ outputsAvailable = false;
85
+ outputSessions = new Map();
81
86
  constructor(config, store) {
82
87
  this.config = config;
83
88
  this.store = store;
@@ -143,6 +148,18 @@ class RouterServer {
143
148
  return await this.feishuLongConnHandler.sendTaskNotificationCard(record.openId, elements, header) ?? undefined;
144
149
  },
145
150
  });
151
+ this.outputTransfers = new OutputTransfers_1.OutputTransfers(path_1.default.join(path_1.default.dirname(config.getConfigPath()
152
+ || path_1.default.join(os_1.default.homedir(), '.remote-cli-router', 'config.json')), 'output-files'), {
153
+ session: deviceId => this.outputSessions.get(deviceId),
154
+ owns: async (openId, deviceId, epoch) => this.selections.isOwnershipCurrent(openId, deviceId, epoch)
155
+ && (await this.bindingManager.getDeviceBinding(deviceId))?.openId === openId,
156
+ send: (deviceId, message) => this.connectionHub.sendToDevice(deviceId, message),
157
+ create: (openId, content, uuid) => this.feishuLongConnHandler.createOutputCard(openId, content, uuid),
158
+ patch: (cardId, content) => this.feishuLongConnHandler.patchOutputCard(cardId, content),
159
+ upload: (filename, name) => this.feishuLongConnHandler.uploadOutputFile(filename, name),
160
+ sendFile: (openId, content, uuid) => this.feishuLongConnHandler.sendOutputFile(openId, content, uuid),
161
+ });
162
+ this.feishuLongConnHandler.onOutputFileAction = (openId, cardId, payload) => this.outputTransfers.click(openId, cardId, payload);
146
163
  this.feishuLongConnHandler.onFileMessage = input => this.fileTransfers.receive(input);
147
164
  this.feishuLongConnHandler.onResolveFile = (openId, sourceId) => this.fileTransfers.resolve(openId, sourceId);
148
165
  this.feishuLongConnHandler.onApproveDeviceKey = async (openId, deviceId, publicKey) => {
@@ -153,6 +170,8 @@ class RouterServer {
153
170
  this.cancelThreadInventories(deviceId);
154
171
  this.connectionHub.disconnectDevice(deviceId);
155
172
  this.fileTransfers.disconnect(deviceId);
173
+ this.outputTransfers.disconnect(deviceId);
174
+ this.outputSessions.delete(deviceId);
156
175
  };
157
176
  this.feishuLongConnHandler.onRevokeDevice = async (deviceId) => {
158
177
  const owner = await this.bindingManager.getDeviceBinding(deviceId);
@@ -162,6 +181,8 @@ class RouterServer {
162
181
  this.cancelThreadInventories(deviceId);
163
182
  this.connectionHub.disconnectDevice(deviceId);
164
183
  this.fileTransfers.disconnect(deviceId);
184
+ this.outputTransfers.disconnect(deviceId);
185
+ this.outputSessions.delete(deviceId);
165
186
  };
166
187
  this.approvalCards = new ApprovalCards_1.ApprovalCards({
167
188
  ownsDevice: async (openId, deviceId) => (await this.bindingManager.getDeviceBinding(deviceId))?.openId === openId,
@@ -208,6 +229,8 @@ class RouterServer {
208
229
  this.feishuLongConnHandler.setOnCaptureSelection((openId, deviceId) => this.selections.capture(openId, deviceId));
209
230
  this.feishuLongConnHandler.setOnValidateSelection(fence => this.selections.isCurrent(fence));
210
231
  this.feishuLongConnHandler.setOnStartStreaming(async (messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName, selectionIntent) => {
232
+ if (feishuMessageId)
233
+ this.feishuLongConnHandler.bindDiagnosticTask?.(feishuMessageId, messageId);
211
234
  console.log(`[RouterServer] Registering streaming session: msgId=${messageId}, feishuMsgId=${feishuMessageId}, deviceId=${deviceId}, threadId=${threadId}, pendingNewThread=${pendingNewThread}`);
212
235
  this.cancelImageReply(messageId);
213
236
  const previous = this.streamingMessages.get(messageId);
@@ -233,6 +256,10 @@ class RouterServer {
233
256
  delegationProgress: new Map(),
234
257
  toolCalls: new Map(),
235
258
  });
259
+ if (this.outputSessions.has(deviceId)) {
260
+ await this.outputTransfers.admitSource({ messageId, openId, deviceId, threadId,
261
+ epoch: selectionIntent?.epoch ?? this.selections.capture(openId, deviceId).epoch }).catch(() => { });
262
+ }
236
263
  // Populate card associations for parent_id-based routing
237
264
  if (feishuMessageId && threadId) {
238
265
  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);
@@ -406,6 +433,10 @@ class RouterServer {
406
433
  minSupportedCliVersion: types_1.MIN_SUPPORTED_CLI_VERSION,
407
434
  };
408
435
  });
436
+ router.post('/api/output-files/:id', async (ctx) => { if (!this.outputsAvailable) {
437
+ ctx.status = 503;
438
+ return;
439
+ } await this.outputTransfers.receive(ctx, ctx.params.id); });
409
440
  router.get('/api/files/:id', async (ctx) => { await this.fileTransfers.serve(ctx, ctx.params.id); });
410
441
  // Binding code request endpoint
411
442
  router.post('/api/bind/request', async (ctx) => {
@@ -471,6 +502,7 @@ class RouterServer {
471
502
  this.app.use(router.routes());
472
503
  this.app.use(router.allowedMethods());
473
504
  }
505
+ diagnosticConnectionEpoch = 0;
474
506
  /**
475
507
  * Setup WebSocket server
476
508
  */
@@ -481,6 +513,7 @@ class RouterServer {
481
513
  maxPayload: IngressAdmission_1.INGRESS_LIMITS.payloadBytes
482
514
  });
483
515
  this.wss.on('connection', (ws, req) => {
516
+ const connectionEpoch = ++this.diagnosticConnectionEpoch;
484
517
  const admission = this.stopping ? undefined : this.ingress.admit(req.socket.remoteAddress ?? 'unknown');
485
518
  if (!admission) {
486
519
  ws.on('error', () => { });
@@ -537,7 +570,7 @@ class RouterServer {
537
570
  // If no heartbeat received within 3x interval, consider connection dead
538
571
  const interval = this.config.get('websocket', 'heartbeatInterval');
539
572
  heartbeatTimeout = setTimeout(() => {
540
- console.log('Heartbeat timeout for device:', deviceId);
573
+ (0, DeliveryDiagnostics_1.deliveryEvent)('socket_heartbeat_timeout', { connectionEpoch });
541
574
  ws.close();
542
575
  }, interval * 3);
543
576
  };
@@ -566,6 +599,24 @@ class RouterServer {
566
599
  await this.handleThreadInventoryResponse(message, deviceId, ws);
567
600
  return;
568
601
  }
602
+ if (message.type === 'output_offer' || message.type === 'output_transfer_failed' || message.type === 'output_discovery') {
603
+ if (!deviceId || !this.outputSessions.has(deviceId))
604
+ return;
605
+ if (message.type === 'output_transfer_failed')
606
+ this.outputTransfers.failed(deviceId, message.transferId);
607
+ else if (message.type === 'output_discovery')
608
+ await this.outputTransfers.discovery(deviceId, message);
609
+ else {
610
+ const stream = this.streamingMessages.get(message.reference?.messageId);
611
+ if (stream && stream.deviceId === deviceId) {
612
+ await this.outputTransfers.admitSource({ messageId: message.reference.messageId, deviceId,
613
+ openId: stream.openId, threadId: stream.threadId,
614
+ epoch: stream.selectionFence?.epoch ?? this.selections.capture(stream.openId, deviceId).epoch });
615
+ }
616
+ await this.outputTransfers.offer(deviceId, message.reference);
617
+ }
618
+ return;
619
+ }
569
620
  if (message.type === 'file_status') {
570
621
  if (deviceId)
571
622
  await this.fileTransfers.handleStatus(deviceId, message);
@@ -681,17 +732,20 @@ class RouterServer {
681
732
  break;
682
733
  const current = imageCurrent;
683
734
  let success = false;
735
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_resume_received', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch });
684
736
  try {
685
737
  success = await this.handleTaskResume(message, deviceId, current);
686
738
  }
687
739
  catch (error) {
688
- console.error('[RouterServer] Failed to recover task card:', error);
740
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_resume_failed', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch, ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
689
741
  }
690
742
  if (!success && current())
691
743
  this.cancelImageReply(message.messageId);
692
- if (current())
744
+ if (current()) {
693
745
  ws.send(JSON.stringify({ type: 'task_resume_ack', messageId: message.messageId,
694
746
  recoveryId: message.taskResume?.recoveryId, state: message.taskResume?.state, success, timestamp: Date.now() }));
747
+ (0, DeliveryDiagnostics_1.deliveryEvent)('resume_ack_send', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch, success, acceptedLocally: true });
748
+ }
695
749
  break;
696
750
  }
697
751
  case types_1.MessageType.BINDING_REQUEST:
@@ -771,6 +825,11 @@ class RouterServer {
771
825
  this.connectionHub.registerConnection(deviceId, ws);
772
826
  }
773
827
  console.log(`Device registered: ${deviceId} (protocol v${clientVersion})`);
828
+ this.outputTransfers.disconnect(deviceId);
829
+ this.outputSessions.delete(deviceId);
830
+ const outputsEnabled = Boolean(this.outputsAvailable && authenticatedOwner && message.data.capabilities?.outputFilesV1 === true);
831
+ if (outputsEnabled)
832
+ this.outputSessions.set(deviceId, { id: (0, crypto_1.randomUUID)(), openId: authenticatedOwner });
774
833
  const filesEnabled = Boolean(this.fileTransfers.enabled && authenticatedOwner && message.data.capabilities?.fileTransferV1 === true);
775
834
  if (filesEnabled)
776
835
  this.connectionHub.setFileSession(deviceId, { id: (0, crypto_1.randomUUID)(), openId: authenticatedOwner });
@@ -813,12 +872,13 @@ class RouterServer {
813
872
  success: true,
814
873
  routerVersion: types_1.ROUTER_VERSION,
815
874
  minCliVersion: types_1.MIN_SUPPORTED_CLI_VERSION,
816
- ...((taskRecoveryEnabled || approvalCardsEnabled || delegationProgressEnabled || streamingContextEnabled || activityProgressEnabled || filesEnabled || updateNoticeEnabled || subscriptionInspectionEnabled || settingsCardsEnabled) ? { capabilities: {
875
+ ...((taskRecoveryEnabled || approvalCardsEnabled || delegationProgressEnabled || streamingContextEnabled || activityProgressEnabled || filesEnabled || outputsEnabled || updateNoticeEnabled || subscriptionInspectionEnabled || settingsCardsEnabled) ? { capabilities: {
817
876
  ...(activityProgressEnabled ? { activityProgress: true } : {}),
818
877
  ...(updateNoticeEnabled ? { updateNotice: true } : {}),
819
878
  ...(subscriptionInspectionEnabled ? { subscriptionInspection: true } : {}),
820
879
  ...(bankedResetReminderEnabled ? { bankedResetReminder: true } : {}),
821
880
  ...(filesEnabled ? { fileTransferV1: true } : {}),
881
+ ...(outputsEnabled ? { outputFilesV1: true } : {}),
822
882
  ...(taskRecoveryEnabled ? { taskRecovery: true } : {}),
823
883
  ...(approvalCardsEnabled ? { approvalCards: true } : {}),
824
884
  ...(delegationProgressEnabled ? { delegationProgress: true } : {}),
@@ -848,8 +908,10 @@ class RouterServer {
848
908
  }));
849
909
  break;
850
910
  case types_1.MessageType.RESPONSE:
911
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_result_received', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch });
851
912
  if (taskRecoveryEnabled && deviceId && this.isCompletedTask(message.messageId, deviceId)) {
852
913
  ws.send(JSON.stringify({ type: 'task_result_ack', messageId: message.messageId, timestamp: Date.now() }));
914
+ (0, DeliveryDiagnostics_1.deliveryEvent)('result_ack_send', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(message.messageId), connectionEpoch, acceptedLocally: true, duplicate: true });
853
915
  break;
854
916
  }
855
917
  // Device sends response to command - forward to Feishu via long connection
@@ -945,6 +1007,7 @@ class RouterServer {
945
1007
  this.rememberCompletedTask(responseMessageId, deviceId);
946
1008
  if (this.connectionHub.isCurrentConnection(deviceId, ws)) {
947
1009
  ws.send(JSON.stringify({ type: 'task_result_ack', messageId: responseMessageId, timestamp: Date.now() }));
1010
+ (0, DeliveryDiagnostics_1.deliveryEvent)('result_ack_send', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(responseMessageId), connectionEpoch, acceptedLocally: true, duplicate: false });
948
1011
  }
949
1012
  }
950
1013
  break;
@@ -968,7 +1031,7 @@ class RouterServer {
968
1031
  // Text is accumulated synchronously. Let subsequent deltas
969
1032
  // coalesce while the card patch runs; finalization still
970
1033
  // waits for updateInFlight before rendering the result.
971
- void update.catch(error => console.error('[RouterServer] Failed to update queued text:', error));
1034
+ void update.catch(error => (0, DeliveryDiagnostics_1.deliveryEvent)('queued_text_failed', (0, DeliveryDiagnostics_1.safeCardError)(error)));
972
1035
  }
973
1036
  else {
974
1037
  await update;
@@ -1034,7 +1097,7 @@ class RouterServer {
1034
1097
  }
1035
1098
  }
1036
1099
  catch (error) {
1037
- console.error('Error processing message:', error);
1100
+ (0, DeliveryDiagnostics_1.deliveryEvent)('router_message_failed', { connectionEpoch, ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
1038
1101
  }
1039
1102
  finally {
1040
1103
  finishQueueMessage?.();
@@ -1050,7 +1113,8 @@ class RouterServer {
1050
1113
  }
1051
1114
  });
1052
1115
  // Handle connection close
1053
- ws.on('close', () => {
1116
+ ws.on('close', (code, reason) => {
1117
+ (0, DeliveryDiagnostics_1.deliveryEvent)('socket_close', { connectionEpoch, code, reasonBytes: reason?.length, registered });
1054
1118
  socketClosed = true;
1055
1119
  releaseAdmission();
1056
1120
  for (const [id, route] of this.imageReplies) {
@@ -1063,6 +1127,8 @@ class RouterServer {
1063
1127
  clearTimeout(heartbeatTimeout);
1064
1128
  if (deviceId && this.connectionHub.unregisterConnection(deviceId, ws)) {
1065
1129
  this.fileTransfers.disconnect(deviceId);
1130
+ this.outputTransfers.disconnect(deviceId);
1131
+ this.outputSessions.delete(deviceId);
1066
1132
  // Clean up any streaming sessions for this device
1067
1133
  this.approvalCards.disconnect(deviceId);
1068
1134
  this.maintenanceCards.disconnect(deviceId);
@@ -1071,7 +1137,7 @@ class RouterServer {
1071
1137
  this.maintenanceConnections.delete(deviceId);
1072
1138
  this.workerContextConnections.delete(deviceId);
1073
1139
  void this.cleanupStreamingSessionsForDevice(deviceId).catch(() => console.error('Failed to expire disconnected streaming cards.'));
1074
- console.log('Device disconnected:', deviceId);
1140
+ (0, DeliveryDiagnostics_1.deliveryEvent)('registered_socket_removed', { connectionEpoch });
1075
1141
  }
1076
1142
  });
1077
1143
  // Handle errors
@@ -1087,7 +1153,7 @@ class RouterServer {
1087
1153
  if (!registered || (ws.readyState !== ws_1.WebSocket.CLOSING && ws.readyState !== ws_1.WebSocket.CLOSED)) {
1088
1154
  ws.terminate();
1089
1155
  }
1090
- console.error('WebSocket error:', error);
1156
+ (0, DeliveryDiagnostics_1.deliveryEvent)('socket_error', { connectionEpoch, ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
1091
1157
  });
1092
1158
  });
1093
1159
  console.log('WebSocket server listening on /ws');
@@ -1097,6 +1163,15 @@ class RouterServer {
1097
1163
  */
1098
1164
  async start() {
1099
1165
  await this.fileTransfers.initialize();
1166
+ if (this.fileTransfers.enabled) {
1167
+ try {
1168
+ await this.outputTransfers.initialize();
1169
+ this.outputsAvailable = true;
1170
+ }
1171
+ catch {
1172
+ console.error('[OutputFiles] Receipt storage unavailable; output transfers are disabled.');
1173
+ }
1174
+ }
1100
1175
  const port = this.config.get('server', 'port');
1101
1176
  const host = this.config.get('server', 'host');
1102
1177
  // Create HTTP server
@@ -1599,7 +1674,7 @@ class RouterServer {
1599
1674
  await this.updateStreamingText(messageId, streamData.openId, streamData);
1600
1675
  }
1601
1676
  catch (error) {
1602
- console.error('[RouterServer] Failed to refresh delegated worker progress:', error);
1677
+ (0, DeliveryDiagnostics_1.deliveryEvent)('worker_progress_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1603
1678
  }
1604
1679
  finally {
1605
1680
  if (this.isLiveDelegationProgress(messageId, streamData, state)) {
@@ -1979,6 +2054,8 @@ class RouterServer {
1979
2054
  const reusable = previous?.feishuMessageId && (!previous.finalizing
1980
2055
  || (previous.recoveryId === info.recoveryId && info.state !== 'running'));
1981
2056
  if (previous && reusable) {
2057
+ (0, DeliveryDiagnostics_1.deliveryEvent)('resume_card_reused', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(messageId), card: (0, DeliveryDiagnostics_1.taskCorrelation)(previous.feishuMessageId),
2058
+ reason: previous.finalizing ? 'same_recovery_terminal_retry' : 'existing_active_card' });
1982
2059
  if (previous.recoveryId !== info.recoveryId) {
1983
2060
  await previous.updateInFlight;
1984
2061
  if (!isCurrent() || this.streamingMessages.get(messageId) !== previous || previous.finalizing)
@@ -2022,9 +2099,12 @@ class RouterServer {
2022
2099
  + `Output before this card, including output during disconnection, was not retained.\n\n`
2023
2100
  + `**Thread:** <raw>${escape(info.threadName)}</raw> · **Backend:** <raw>${escape(info.backend)}</raw>\n`
2024
2101
  + `**Working directory:** <raw>${escape(info.cwd)}</raw>\n**Task:** <raw>${escape(info.preview)}</raw>`;
2025
- const cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd);
2102
+ const cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd, messageId);
2026
2103
  if (!cardId || !isCurrent())
2027
2104
  return false;
2105
+ this.feishuLongConnHandler.bindDiagnosticTask?.(cardId, messageId);
2106
+ (0, DeliveryDiagnostics_1.deliveryEvent)('resume_card_created', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(messageId), card: (0, DeliveryDiagnostics_1.taskCorrelation)(cardId),
2107
+ reason: previous?.finalizing ? 'previous_card_finalizing' : previous ? 'previous_card_missing' : 'no_previous_stream' });
2028
2108
  if (previous)
2029
2109
  this.clearDelegationProgressTimers(previous);
2030
2110
  this.streamingMessages.set(messageId, {
@@ -2078,10 +2158,12 @@ class RouterServer {
2078
2158
  **Remaining in queue:** ${info.remainingCount}`;
2079
2159
  let cardId = null;
2080
2160
  try {
2081
- cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd);
2161
+ cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd, messageId);
2162
+ if (cardId)
2163
+ this.feishuLongConnHandler.bindDiagnosticTask?.(cardId, messageId);
2082
2164
  }
2083
2165
  catch (error) {
2084
- console.error('[RouterServer] Failed to create queued execution card:', error);
2166
+ (0, DeliveryDiagnostics_1.deliveryEvent)('queued_card_create_failed', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(messageId), ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
2085
2167
  }
2086
2168
  if (!isCurrent() || (imageRoute && this.imageReplies.get(messageId) !== imageRoute))
2087
2169
  return;
@@ -2127,7 +2209,7 @@ class RouterServer {
2127
2209
  }
2128
2210
  catch (error) {
2129
2211
  // The new execution card remains usable if its old receipt expired.
2130
- console.error('[RouterServer] Failed to update queue receipt:', error);
2212
+ (0, DeliveryDiagnostics_1.deliveryEvent)('queue_receipt_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
2131
2213
  }
2132
2214
  }
2133
2215
  }
@@ -2197,90 +2279,99 @@ class RouterServer {
2197
2279
  const streamData = this.streamingMessages.get(messageId);
2198
2280
  if (!streamData)
2199
2281
  return;
2200
- const route = this.imageReplies.get(messageId);
2201
- if (route)
2202
- this.images.close(route.reply);
2203
- this.closeImageIntake(streamData, route?.reply.deadline);
2204
- // Snapshot accepted work before awaiting; intake is already closed.
2205
- const accepted = route?.reply.tail;
2206
- if (accepted)
2207
- await accepted;
2208
- if (this.streamingMessages.get(messageId) !== streamData
2209
- || (route && (this.imageReplies.get(messageId) !== route || !route.current())))
2210
- return;
2211
- if (route?.reply.failed)
2212
- this.noteImageFailure(messageId, streamData);
2213
- this.cancelImageReply(messageId);
2214
- streamData.finalizing = true;
2215
- streamData.updatePending = false;
2216
- this.clearDelegationProgressTimers(streamData);
2217
- await streamData.updateInFlight;
2218
- if (!await this.canDispatchStreamOutput(messageId, streamData))
2219
- return;
2220
- const { feishuMessageId, openId } = streamData;
2221
- if (feishuMessageId) {
2222
- // Flush any remaining text content
2223
- if (streamData.currentTextContent.trim()) {
2224
- streamData.elements.push(...this.renderCurrentText(streamData));
2225
- streamData.currentTextContent = '';
2226
- streamData.recoveryPlainText = false;
2227
- }
2228
- // If there are no elements at all, use the output parameter as fallback
2229
- if (streamData.elements.length === 0 && output) {
2230
- streamData.elements.push((0, ToolFormatter_1.createMarkdownElement)(output));
2231
- }
2232
- // A capable CLI's settings menu replaces the placeholder with a dedicated
2233
- // interactive card bound to the original user/device/thread/request. The
2234
- // text output is for incapable peers or delivery failure only: including
2235
- // its complete catalog here would defeat pagination and its node/byte budget.
2236
- const prepared = settingsMenu && success
2237
- ? this.settingsCards.present({ openId: streamData.openId, deviceId: streamData.deviceId, menu: settingsMenu, requestMessageId: messageId, expectedThreadId: streamData.threadId })
2238
- : undefined;
2239
- if (prepared) {
2240
- 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) });
2241
- if (!finalized) {
2242
- prepared.discard();
2243
- if (!await this.canDispatchStreamOutput(messageId, streamData))
2244
- return;
2245
- const delivered = await this.feishuLongConnHandler.sendMessage(openId, output || '⚙️ Settings are unavailable as a card. Use the text command.');
2246
- if (delivered === false)
2247
- throw new Error('Failed to deliver settings result');
2282
+ const task = (0, DeliveryDiagnostics_1.taskCorrelation)(messageId);
2283
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_finalization_started', { task, card: (0, DeliveryDiagnostics_1.taskCorrelation)(streamData.feishuMessageId) });
2284
+ try {
2285
+ const route = this.imageReplies.get(messageId);
2286
+ if (route)
2287
+ this.images.close(route.reply);
2288
+ this.closeImageIntake(streamData, route?.reply.deadline);
2289
+ // Snapshot accepted work before awaiting; intake is already closed.
2290
+ const accepted = route?.reply.tail;
2291
+ if (accepted)
2292
+ await accepted;
2293
+ if (this.streamingMessages.get(messageId) !== streamData
2294
+ || (route && (this.imageReplies.get(messageId) !== route || !route.current())))
2295
+ return;
2296
+ if (route?.reply.failed)
2297
+ this.noteImageFailure(messageId, streamData);
2298
+ this.cancelImageReply(messageId);
2299
+ streamData.finalizing = true;
2300
+ streamData.updatePending = false;
2301
+ this.clearDelegationProgressTimers(streamData);
2302
+ await streamData.updateInFlight;
2303
+ if (!await this.canDispatchStreamOutput(messageId, streamData))
2304
+ return;
2305
+ const { feishuMessageId, openId } = streamData;
2306
+ if (feishuMessageId) {
2307
+ // Flush any remaining text content
2308
+ if (streamData.currentTextContent.trim()) {
2309
+ streamData.elements.push(...this.renderCurrentText(streamData));
2310
+ streamData.currentTextContent = '';
2311
+ streamData.recoveryPlainText = false;
2312
+ }
2313
+ // If there are no elements at all, use the output parameter as fallback
2314
+ if (streamData.elements.length === 0 && output) {
2315
+ streamData.elements.push((0, ToolFormatter_1.createMarkdownElement)(output));
2316
+ }
2317
+ // A capable CLI's settings menu replaces the placeholder with a dedicated
2318
+ // interactive card bound to the original user/device/thread/request. The
2319
+ // text output is for incapable peers or delivery failure only: including
2320
+ // its complete catalog here would defeat pagination and its node/byte budget.
2321
+ const prepared = settingsMenu && success
2322
+ ? this.settingsCards.present({ openId: streamData.openId, deviceId: streamData.deviceId, menu: settingsMenu, requestMessageId: messageId, expectedThreadId: streamData.threadId })
2323
+ : undefined;
2324
+ if (prepared) {
2325
+ 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) });
2326
+ if (!finalized) {
2327
+ prepared.discard();
2328
+ if (!await this.canDispatchStreamOutput(messageId, streamData))
2329
+ return;
2330
+ const delivered = await this.feishuLongConnHandler.sendMessage(openId, output || '⚙️ Settings are unavailable as a card. Use the text command.');
2331
+ if (delivered === false)
2332
+ throw new Error('Failed to deliver settings result');
2333
+ }
2334
+ }
2335
+ else if (success) {
2336
+ 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) });
2337
+ if (finalized === false)
2338
+ throw new Error('Failed to finalize task card');
2339
+ }
2340
+ else {
2341
+ // Add error message to elements
2342
+ const finalElements = [...streamData.elements];
2343
+ if (!queueConfirmation) {
2344
+ const errorMsg = error || 'Command failed';
2345
+ finalElements.push((0, ToolFormatter_1.createMarkdownElement)(`\n\n❌ **Error:** ${errorMsg}`));
2346
+ }
2347
+ 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) });
2348
+ if (finalized === false)
2349
+ throw new Error('Failed to finalize task card');
2248
2350
  }
2249
2351
  }
2250
- else if (success) {
2251
- 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) });
2252
- if (finalized === false)
2253
- throw new Error('Failed to finalize task card');
2352
+ else if (streamData.queueStarted) {
2353
+ // If card creation failed after session recovery, retain a text result
2354
+ // rather than silently losing the completed queued task's output.
2355
+ const text = streamData.elements
2356
+ .filter((element) => element.tag === 'markdown')
2357
+ .map((element) => element.content)
2358
+ .concat(streamData.currentTextContent, output || '')
2359
+ .filter(Boolean)
2360
+ .join('\n\n');
2361
+ const delivered = await this.feishuLongConnHandler.sendMessage(openId, `${text}\n\n${success ? '✅ Completed' : `❌ Error: ${error || 'Command failed'}`}`);
2362
+ if (delivered === false)
2363
+ throw new Error('Failed to deliver task result');
2254
2364
  }
2255
- else {
2256
- // Add error message to elements
2257
- const finalElements = [...streamData.elements];
2258
- if (!queueConfirmation) {
2259
- const errorMsg = error || 'Command failed';
2260
- finalElements.push((0, ToolFormatter_1.createMarkdownElement)(`\n\n❌ **Error:** ${errorMsg}`));
2261
- }
2262
- 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) });
2263
- if (finalized === false)
2264
- throw new Error('Failed to finalize task card');
2365
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_finalization_complete', { task });
2366
+ // Keep durable card associations after removing the completed streaming session.
2367
+ if (this.streamingMessages.get(messageId) === streamData) {
2368
+ this.streamingMessages.delete(messageId);
2369
+ this.lastStreamUpdateTime.delete(messageId);
2265
2370
  }
2266
2371
  }
2267
- else if (streamData.queueStarted) {
2268
- // If card creation failed after session recovery, retain a text result
2269
- // rather than silently losing the completed queued task's output.
2270
- const text = streamData.elements
2271
- .filter((element) => element.tag === 'markdown')
2272
- .map((element) => element.content)
2273
- .concat(streamData.currentTextContent, output || '')
2274
- .filter(Boolean)
2275
- .join('\n\n');
2276
- const delivered = await this.feishuLongConnHandler.sendMessage(openId, `${text}\n\n${success ? '✅ Completed' : `❌ Error: ${error || 'Command failed'}`}`);
2277
- if (delivered === false)
2278
- throw new Error('Failed to deliver task result');
2279
- }
2280
- // Keep durable card associations after removing the completed streaming session.
2281
- if (this.streamingMessages.get(messageId) === streamData) {
2282
- this.streamingMessages.delete(messageId);
2283
- this.lastStreamUpdateTime.delete(messageId);
2372
+ catch (failure) {
2373
+ (0, DeliveryDiagnostics_1.deliveryEvent)('task_finalization_failed', { task, ...(0, DeliveryDiagnostics_1.safeCardError)(failure) });
2374
+ throw failure;
2284
2375
  }
2285
2376
  }
2286
2377
  removeActiveCardRoutes(session) {
@@ -2353,7 +2444,7 @@ class RouterServer {
2353
2444
  if (failed?.status === 'rejected')
2354
2445
  throw failed.reason;
2355
2446
  if (cleanedCount > 0) {
2356
- console.log(`[RouterServer] Cleaned up ${cleanedCount} streaming sessions for device ${deviceId}, remaining: ${this.streamingMessages.size}`);
2447
+ (0, DeliveryDiagnostics_1.deliveryEvent)('disconnected_streams_cleaned', { count: cleanedCount, remaining: this.streamingMessages.size });
2357
2448
  }
2358
2449
  }
2359
2450
  /**
@@ -2394,6 +2485,7 @@ class RouterServer {
2394
2485
  this.settingsConnections.clear();
2395
2486
  this.maintenanceCards.destroy();
2396
2487
  this.maintenanceConnections.clear();
2488
+ await attempt('Error destroying output transfers', () => this.outputTransfers.destroy());
2397
2489
  await attempt('Error destroying file transfers', () => this.fileTransfers.destroy());
2398
2490
  if (this.cleanupInterval) {
2399
2491
  clearInterval(this.cleanupInterval);
@@ -2409,7 +2501,7 @@ class RouterServer {
2409
2501
  catch (error) {
2410
2502
  failed = true;
2411
2503
  firstError ??= error;
2412
- console.error(`[RouterServer] Failed to finalize streaming card ${messageId} during shutdown:`, error);
2504
+ (0, DeliveryDiagnostics_1.deliveryEvent)('shutdown_card_finalize_failed', { task: (0, DeliveryDiagnostics_1.taskCorrelation)(messageId), ...(0, DeliveryDiagnostics_1.safeCardError)(error) });
2413
2505
  }
2414
2506
  }
2415
2507
  this.streamingMessages.clear();