@yu_robotics/remote-cli-router 1.6.111 โ†’ 1.6.114

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 (36) hide show
  1. package/dist/binding/BindingManager.d.ts +2 -1
  2. package/dist/binding/BindingManager.d.ts.map +1 -1
  3. package/dist/binding/BindingManager.js +7 -2
  4. package/dist/binding/BindingManager.js.map +1 -1
  5. package/dist/feishu/FeishuLongConnHandler.d.ts +16 -3
  6. package/dist/feishu/FeishuLongConnHandler.d.ts.map +1 -1
  7. package/dist/feishu/FeishuLongConnHandler.js +112 -19
  8. package/dist/feishu/FeishuLongConnHandler.js.map +1 -1
  9. package/dist/files/DeviceAuth.d.ts +29 -0
  10. package/dist/files/DeviceAuth.d.ts.map +1 -0
  11. package/dist/files/DeviceAuth.js +117 -0
  12. package/dist/files/DeviceAuth.js.map +1 -0
  13. package/dist/files/FileIO.d.ts +21 -0
  14. package/dist/files/FileIO.d.ts.map +1 -0
  15. package/dist/files/FileIO.js +134 -0
  16. package/dist/files/FileIO.js.map +1 -0
  17. package/dist/files/FileTransfers.d.ts +77 -0
  18. package/dist/files/FileTransfers.d.ts.map +1 -0
  19. package/dist/files/FileTransfers.js +414 -0
  20. package/dist/files/FileTransfers.js.map +1 -0
  21. package/dist/server.d.ts +4 -3
  22. package/dist/server.d.ts.map +1 -1
  23. package/dist/server.js +174 -23
  24. package/dist/server.js.map +1 -1
  25. package/dist/types/config.d.ts +8 -0
  26. package/dist/types/config.d.ts.map +1 -1
  27. package/dist/types/config.js +3 -0
  28. package/dist/types/config.js.map +1 -1
  29. package/dist/types/index.d.ts +3 -0
  30. package/dist/types/index.d.ts.map +1 -1
  31. package/dist/types/index.js.map +1 -1
  32. package/dist/websocket/ConnectionHub.d.ts +10 -0
  33. package/dist/websocket/ConnectionHub.d.ts.map +1 -1
  34. package/dist/websocket/ConnectionHub.js +14 -0
  35. package/dist/websocket/ConnectionHub.js.map +1 -1
  36. package/package.json +1 -1
package/dist/server.js CHANGED
@@ -5,6 +5,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.RouterServer = void 0;
7
7
  const ApprovalCards_1 = require("./feishu/ApprovalCards");
8
+ const DeviceAuth_1 = require("./files/DeviceAuth");
9
+ const FileTransfers_1 = require("./files/FileTransfers");
10
+ const path_1 = __importDefault(require("path"));
11
+ const os_1 = __importDefault(require("os"));
12
+ const crypto_1 = require("crypto");
8
13
  const koa_1 = __importDefault(require("koa"));
9
14
  const koa_bodyparser_1 = __importDefault(require("koa-bodyparser"));
10
15
  const router_1 = __importDefault(require("@koa/router"));
@@ -52,12 +57,15 @@ class RouterServer {
52
57
  // Map from openId to the user's currently active thread (set by card button click).
53
58
  // New top-level messages (no parent_id) are routed to this thread.
54
59
  activeThreadMap = new Map();
60
+ deviceAuth;
61
+ fileTransfers;
55
62
  constructor(config, store) {
56
63
  this.config = config;
57
64
  this.store = store;
58
65
  this.app = new koa_1.default();
59
66
  this.connectionHub = new ConnectionHub_1.ConnectionHub();
60
67
  this.bindingManager = new BindingManager_1.BindingManager(store);
68
+ this.deviceAuth = new DeviceAuth_1.DeviceAuth(path_1.default.join(path_1.default.dirname(config.getConfigPath() || path_1.default.join(os_1.default.homedir(), '.remote-cli-router', 'config.json')), 'device-auth.json'));
61
69
  // Initialize FeishuLongConnHandler (WebSocket mode)
62
70
  this.feishuLongConnHandler = new FeishuLongConnHandler_1.FeishuLongConnHandler({
63
71
  appId: config.get('feishu', 'appId'),
@@ -66,6 +74,42 @@ class RouterServer {
66
74
  });
67
75
  // Share ConnectionHub with Feishu handler
68
76
  this.feishuLongConnHandler.setConnectionHub(this.connectionHub);
77
+ const fileConfig = config.get('files');
78
+ this.fileTransfers = new FileTransfers_1.FileTransfers(path_1.default.join(path_1.default.dirname(config.getConfigPath() || path_1.default.join(os_1.default.homedir(), '.remote-cli-router', 'config.json')), 'attachments'), fileConfig?.enabled, fileConfig?.maxBytes, {
79
+ session: deviceId => this.connectionHub.getFileSession(deviceId),
80
+ owns: async (openId, deviceId) => (await this.bindingManager.getDeviceBinding(deviceId))?.openId === openId,
81
+ send: (deviceId, message) => this.connectionHub.sendToDevice(deviceId, message),
82
+ download: (messageId, fileKey, signal) => this.feishuLongConnHandler.downloadFileResource(messageId, fileKey, signal),
83
+ notify: async (record) => {
84
+ const failed = record.state === 'failed';
85
+ const ready = ['saved', 'parsed', 'partial', 'unsupported'].includes(record.state);
86
+ const header = { title: { tag: 'plain_text', content: `๐Ÿ“Ž File ยท ${record.state}` }, template: failed ? 'red' : ready ? 'green' : 'blue' };
87
+ const details = [record.name, record.size === undefined ? 'Limit: 20 MiB' : `${(record.size / 1024 / 1024).toFixed(2)} MiB`,
88
+ `Device: ${record.deviceId}`,
89
+ record.threadId ? `Thread: ${record.threadId}` : 'Waiting for thread admission', record.detail,
90
+ ready ? 'Send your instructions in this thread, or reply to this card. Saving a file does not start a model task.' : undefined].filter(Boolean).join('\n');
91
+ const elements = [{ tag: 'div', text: { tag: 'plain_text', content: details } }];
92
+ if (record.cardId) {
93
+ await this.feishuLongConnHandler.updateApprovalCard(record.cardId, elements, header);
94
+ return record.cardId;
95
+ }
96
+ return await this.feishuLongConnHandler.sendTaskNotificationCard(record.openId, elements, header) ?? undefined;
97
+ },
98
+ });
99
+ this.feishuLongConnHandler.onFileMessage = input => this.fileTransfers.receive(input);
100
+ this.feishuLongConnHandler.onResolveFile = (openId, sourceId) => this.fileTransfers.resolve(openId, sourceId);
101
+ this.feishuLongConnHandler.onApproveDeviceKey = async (openId, deviceId, publicKey) => {
102
+ if ((await this.bindingManager.getDeviceBinding(deviceId))?.openId !== openId)
103
+ throw new Error('Device ownership changed.');
104
+ await this.deviceAuth.enroll(deviceId, openId, publicKey);
105
+ this.connectionHub.disconnectDevice(deviceId);
106
+ this.fileTransfers.disconnect(deviceId);
107
+ };
108
+ this.feishuLongConnHandler.onRevokeDevice = async (deviceId) => {
109
+ await this.deviceAuth.revoke(deviceId);
110
+ this.connectionHub.disconnectDevice(deviceId);
111
+ this.fileTransfers.disconnect(deviceId);
112
+ };
69
113
  this.approvalCards = new ApprovalCards_1.ApprovalCards({
70
114
  ownsDevice: async (openId, deviceId) => (await this.bindingManager.getDeviceBinding(deviceId))?.openId === openId,
71
115
  sendToDevice: (deviceId, message) => this.connectionHub.sendToDevice(deviceId, message),
@@ -77,7 +121,7 @@ class RouterServer {
77
121
  });
78
122
  this.feishuLongConnHandler.onApprovalAction = (openId, requestId, cardId, decision) => this.approvalCards.click(openId, requestId, cardId, decision);
79
123
  // Register callback for streaming message start
80
- this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId) => {
124
+ this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName) => {
81
125
  console.log(`[RouterServer] Registering streaming session: msgId=${messageId}, feishuMsgId=${feishuMessageId}, deviceId=${deviceId}, threadId=${threadId}, pendingNewThread=${pendingNewThread}`);
82
126
  const previous = this.streamingMessages.get(messageId);
83
127
  if (previous)
@@ -91,6 +135,7 @@ class RouterServer {
91
135
  createdAt: Date.now(),
92
136
  deviceId,
93
137
  threadId,
138
+ threadName,
94
139
  pendingNewThread,
95
140
  queueCardId,
96
141
  updatePending: false,
@@ -202,11 +247,12 @@ class RouterServer {
202
247
  minSupportedCliVersion: types_1.MIN_SUPPORTED_CLI_VERSION,
203
248
  };
204
249
  });
250
+ router.get('/api/files/:id', async (ctx) => { await this.fileTransfers.serve(ctx, ctx.params.id); });
205
251
  // Binding code request endpoint
206
252
  router.post('/api/bind/request', async (ctx) => {
207
253
  const { deviceId, deviceName, platform } = ctx.request.body;
208
254
  // Validate required fields
209
- if (!deviceId) {
255
+ if (typeof deviceId !== 'string' || !/^[a-zA-Z0-9_-]{1,200}$/.test(deviceId)) {
210
256
  ctx.status = 400;
211
257
  ctx.body = {
212
258
  success: false,
@@ -215,11 +261,24 @@ class RouterServer {
215
261
  return;
216
262
  }
217
263
  try {
264
+ const { devicePublicKey, nonce, signature } = ctx.request.body;
265
+ if (devicePublicKey && !this.fileTransfers.enabled) {
266
+ ctx.status = 400;
267
+ ctx.body = { success: false, error: 'File reception is disabled by the Router administrator (files.enabled=false).' };
268
+ return;
269
+ }
270
+ if (devicePublicKey !== undefined && (!DeviceAuth_1.DeviceAuth.validKey(devicePublicKey)
271
+ || !DeviceAuth_1.DeviceAuth.verifyProof(devicePublicKey, deviceId, nonce, signature))) {
272
+ ctx.status = 400;
273
+ ctx.body = { success: false, error: 'Invalid device enrollment proof.' };
274
+ return;
275
+ }
218
276
  // Generate binding code
219
- const bindingCode = await this.bindingManager.generateBindingCode(deviceId, deviceName || 'Unknown Device');
277
+ const bindingCode = await this.bindingManager.generateBindingCode(deviceId, deviceName || 'Unknown Device', ...(devicePublicKey ? [devicePublicKey] : []));
220
278
  ctx.body = {
221
279
  success: true,
222
280
  bindingCode: bindingCode.code,
281
+ ...(devicePublicKey ? { deviceAuth: true } : {}),
223
282
  expiresAt: bindingCode.expiresAt,
224
283
  expiresIn: Math.floor((bindingCode.expiresAt - Date.now()) / 1000) // seconds
225
284
  };
@@ -260,6 +319,9 @@ class RouterServer {
260
319
  let approvalCardsEnabled = false;
261
320
  let delegationProgressEnabled = false;
262
321
  let delegationProgressTextEnabled = false;
322
+ let streamingContextEnabled = false;
323
+ let authenticationPending = false;
324
+ let challengeTimer;
263
325
  let heartbeatTimeout = null;
264
326
  // Reset heartbeat timeout
265
327
  const resetHeartbeat = () => {
@@ -278,11 +340,18 @@ class RouterServer {
278
340
  let finishQueueMessage;
279
341
  try {
280
342
  const message = JSON.parse(data.toString());
343
+ if (!deviceId && message.type !== types_1.MessageType.BINDING_REQUEST && message.type !== types_1.MessageType.HEARTBEAT)
344
+ return;
281
345
  if (deviceId && message.type !== types_1.MessageType.BINDING_REQUEST
282
346
  && !this.connectionHub.isCurrentConnection(deviceId, ws))
283
347
  return;
284
348
  // Update heartbeat on any message
285
349
  resetHeartbeat();
350
+ if (message.type === 'file_status') {
351
+ if (deviceId)
352
+ await this.fileTransfers.handleStatus(deviceId, message);
353
+ return;
354
+ }
286
355
  if (message.type === 'approval_request' || message.type === 'approval_resolved') {
287
356
  if (!approvalCardsEnabled || !deviceId)
288
357
  return;
@@ -337,8 +406,46 @@ class RouterServer {
337
406
  }
338
407
  case types_1.MessageType.BINDING_REQUEST:
339
408
  // Device sends binding request with deviceId and optional protocolVersion
340
- deviceId = message.data.deviceId;
341
- if (deviceId) {
409
+ if (authenticationPending || deviceId)
410
+ break;
411
+ if (typeof message.data?.deviceId === 'string' && /^[a-zA-Z0-9_-]{1,200}$/.test(message.data.deviceId)) {
412
+ authenticationPending = true;
413
+ const requestedId = message.data.deviceId;
414
+ let authenticatedOwner;
415
+ try {
416
+ const enrolled = await this.deviceAuth.get(requestedId);
417
+ if (enrolled) {
418
+ if (!message.data.deviceSignature && !enrolled.revoked) {
419
+ const nonce = this.deviceAuth.challenge(ws, requestedId);
420
+ ws.send(JSON.stringify({ type: 'device_challenge', data: { nonce } }));
421
+ if (challengeTimer)
422
+ clearTimeout(challengeTimer);
423
+ challengeTimer = setTimeout(() => ws.close(), 15_000);
424
+ break;
425
+ }
426
+ const proof = await this.deviceAuth.verify(ws, requestedId, message.data.deviceSignature);
427
+ if (!proof || (await this.bindingManager.getDeviceBinding(requestedId))?.openId !== proof.openId
428
+ || !this.deviceAuth.isCurrent(requestedId, proof)) {
429
+ ws.send(JSON.stringify({ type: 'error', data: { code: 'DEVICE_AUTH_REQUIRED', message: 'Device authentication failed. Approve a new key using remote-cli files enable --rotate.' } }));
430
+ ws.close();
431
+ break;
432
+ }
433
+ authenticatedOwner = proof.openId;
434
+ }
435
+ if (ws.readyState !== ws_1.WebSocket.OPEN)
436
+ break;
437
+ }
438
+ catch {
439
+ ws.send(JSON.stringify({ type: 'error', data: { code: 'DEVICE_AUTH_REQUIRED', message: 'Device authentication is unavailable. Ask the Router administrator to check the authentication store.' } }));
440
+ ws.close();
441
+ break;
442
+ }
443
+ finally {
444
+ authenticationPending = false;
445
+ }
446
+ if (challengeTimer)
447
+ clearTimeout(challengeTimer);
448
+ deviceId = requestedId;
342
449
  // Version check: missing protocolVersion defaults to 1 (current baseline)
343
450
  const clientVersion = message.data?.protocolVersion ?? 1;
344
451
  if (clientVersion < types_1.MIN_SUPPORTED_CLI_VERSION) {
@@ -365,8 +472,13 @@ class RouterServer {
365
472
  this.connectionHub.registerConnection(deviceId, ws);
366
473
  }
367
474
  console.log(`Device registered: ${deviceId} (protocol v${clientVersion})`);
475
+ const filesEnabled = Boolean(this.fileTransfers.enabled && authenticatedOwner && message.data.capabilities?.fileTransferV1 === true);
476
+ if (filesEnabled)
477
+ this.connectionHub.setFileSession(deviceId, { id: (0, crypto_1.randomUUID)(), openId: authenticatedOwner });
478
+ this.fileTransfers.disconnect(deviceId);
368
479
  taskRecoveryEnabled = message.data.capabilities?.taskRecovery === true;
369
480
  approvalCardsEnabled = message.data.capabilities?.approvalCards === true;
481
+ streamingContextEnabled = message.data.capabilities?.streamingContext === true;
370
482
  delegationProgressEnabled = message.data.capabilities?.delegationProgress === true;
371
483
  delegationProgressTextEnabled = delegationProgressEnabled
372
484
  && message.data.capabilities?.delegationProgressText === true;
@@ -379,11 +491,13 @@ class RouterServer {
379
491
  success: true,
380
492
  routerVersion: types_1.ROUTER_VERSION,
381
493
  minCliVersion: types_1.MIN_SUPPORTED_CLI_VERSION,
382
- ...((taskRecoveryEnabled || approvalCardsEnabled || delegationProgressEnabled) ? { capabilities: {
494
+ ...((taskRecoveryEnabled || approvalCardsEnabled || delegationProgressEnabled || streamingContextEnabled || filesEnabled) ? { capabilities: {
495
+ ...(filesEnabled ? { fileTransferV1: true } : {}),
383
496
  ...(taskRecoveryEnabled ? { taskRecovery: true } : {}),
384
497
  ...(approvalCardsEnabled ? { approvalCards: true } : {}),
385
498
  ...(delegationProgressEnabled ? { delegationProgress: true } : {}),
386
499
  ...(delegationProgressTextEnabled ? { delegationProgressText: true } : {}),
500
+ ...(streamingContextEnabled ? { streamingContext: true } : {}),
387
501
  } } : {}),
388
502
  }
389
503
  }));
@@ -412,7 +526,8 @@ class RouterServer {
412
526
  const responseMessageId = message.messageId;
413
527
  const sessionAbbr = message.sessionAbbr || message.data?.sessionAbbr;
414
528
  const cwd = message.cwd || message.data?.cwd || this.streamingMessages.get(message.messageId)?.queueStarted?.cwd
415
- || this.streamingMessages.get(message.messageId)?.recoveryCwd;
529
+ || this.streamingMessages.get(message.messageId)?.recoveryCwd
530
+ || this.streamingMessages.get(message.messageId)?.cwd;
416
531
  const responseThreadId = message.threadId || message.data?.threadId;
417
532
  const responseThreads = message.threads || message.data?.threads;
418
533
  const queueConfirmation = message.queueConfirmation || message.data?.queueConfirmation;
@@ -421,12 +536,12 @@ class RouterServer {
421
536
  if (responseThreadId && responseMessageId) {
422
537
  const session = this.streamingMessages.get(responseMessageId);
423
538
  if (session) {
424
- if (session.feishuMessageId && !session.threadId) {
539
+ if (session.feishuMessageId && session.threadId !== responseThreadId) {
425
540
  session.threadId = responseThreadId;
426
541
  this.cardThreadMap.set(session.feishuMessageId, { threadId: responseThreadId, deviceId: session.deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
427
542
  }
428
543
  // Resolve thread name from the threads summary array
429
- if (!session.threadName && responseThreads) {
544
+ if (responseThreads) {
430
545
  const match = responseThreads.find(t => t.id === responseThreadId);
431
546
  if (match)
432
547
  session.threadName = match.name;
@@ -478,6 +593,10 @@ class RouterServer {
478
593
  }
479
594
  }
480
595
  break;
596
+ case 'stream_context':
597
+ if (streamingContextEnabled)
598
+ await this.handleStreamContext(message, deviceId);
599
+ break;
481
600
  case 'stream':
482
601
  // Handle streaming output from device
483
602
  if (message.messageId && message.openId) {
@@ -566,9 +685,12 @@ class RouterServer {
566
685
  });
567
686
  // Handle connection close
568
687
  ws.on('close', () => {
688
+ if (challengeTimer)
689
+ clearTimeout(challengeTimer);
569
690
  if (heartbeatTimeout)
570
691
  clearTimeout(heartbeatTimeout);
571
692
  if (deviceId && this.connectionHub.unregisterConnection(deviceId, ws)) {
693
+ this.fileTransfers.disconnect(deviceId);
572
694
  // Clean up any streaming sessions for this device
573
695
  this.approvalCards.disconnect(deviceId);
574
696
  this.cleanupStreamingSessionsForDevice(deviceId);
@@ -586,6 +708,7 @@ class RouterServer {
586
708
  * Start the server
587
709
  */
588
710
  async start() {
711
+ await this.fileTransfers.initialize();
589
712
  const port = this.config.get('server', 'port');
590
713
  const host = this.config.get('server', 'host');
591
714
  // Create HTTP server
@@ -618,9 +741,30 @@ class RouterServer {
618
741
  lastStreamUpdateTime = new Map();
619
742
  STREAM_UPDATE_INTERVAL_MS = 500; // Update at least every 500ms
620
743
  STREAM_UPDATE_MIN_LENGTH = 10; // Update every 10 characters
621
- /**
622
- * Handle streaming chunk from device
623
- */
744
+ /** Resolve the card header without waiting for backend text or completion. */
745
+ async handleStreamContext(message, deviceId) {
746
+ const { messageId, openId, threadId, threadName, cwd } = message;
747
+ if (!deviceId || typeof messageId !== 'string' || typeof openId !== 'string'
748
+ || typeof threadId !== 'string' || !threadId || threadId.length > 200
749
+ || typeof threadName !== 'string' || !threadName.trim() || threadName.length > 100
750
+ || typeof cwd !== 'string' || cwd.length > 4096)
751
+ return;
752
+ const stream = this.streamingMessages.get(messageId);
753
+ if (!stream || stream.finalizing || stream.deviceId !== deviceId || stream.openId !== openId
754
+ || (stream.threadId && stream.threadId !== threadId))
755
+ return;
756
+ if (stream.threadId === threadId && stream.threadName === threadName && stream.cwd === cwd)
757
+ return;
758
+ stream.threadId = threadId;
759
+ stream.threadName = threadName;
760
+ stream.cwd = cwd;
761
+ if (stream.feishuMessageId) {
762
+ this.cardThreadMap.set(stream.feishuMessageId, {
763
+ threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
764
+ });
765
+ await this.updateStreamingText(messageId, openId, stream);
766
+ }
767
+ }
624
768
  /**
625
769
  * Handle text streaming chunk
626
770
  */
@@ -688,9 +832,13 @@ class RouterServer {
688
832
  elements.push(...this.renderCurrentText(streamData));
689
833
  }
690
834
  streamData.lastRenderedTextLength = streamData.currentTextContent.length;
691
- streamData.hasUpdated = true;
835
+ // A metadata-only patch must not delay the first actual text token.
836
+ if (elements.length > 0)
837
+ streamData.hasUpdated = true;
838
+ else
839
+ elements.push((0, ToolFormatter_1.createMarkdownElement)('๐Ÿค” Processing...'));
692
840
  this.lastStreamUpdateTime.set(messageId, Date.now());
693
- await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, elements, openId, streamData.threadName);
841
+ await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, elements, openId, streamData.threadName, streamData.cwd);
694
842
  } while (streamData.updatePending);
695
843
  }
696
844
  /**
@@ -717,7 +865,7 @@ class RouterServer {
717
865
  streamData.createdAt = Date.now();
718
866
  // Immediately update card to show tool use
719
867
  if (streamData.feishuMessageId) {
720
- await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName);
868
+ await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName, streamData.cwd);
721
869
  streamData.hasUpdated = true;
722
870
  }
723
871
  }
@@ -745,7 +893,7 @@ class RouterServer {
745
893
  streamData.createdAt = Date.now();
746
894
  // Immediately update card to show tool result
747
895
  if (streamData.feishuMessageId) {
748
- await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName);
896
+ await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName, streamData.cwd);
749
897
  streamData.hasUpdated = true;
750
898
  }
751
899
  }
@@ -1023,7 +1171,7 @@ class RouterServer {
1023
1171
  streamData.createdAt = Date.now();
1024
1172
  // Immediately update card to show redacted thinking notification
1025
1173
  if (streamData.feishuMessageId) {
1026
- await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName);
1174
+ await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName, streamData.cwd);
1027
1175
  streamData.hasUpdated = true;
1028
1176
  }
1029
1177
  }
@@ -1050,7 +1198,7 @@ class RouterServer {
1050
1198
  streamData.createdAt = Date.now();
1051
1199
  // Immediately update card to show the plan section
1052
1200
  if (streamData.feishuMessageId) {
1053
- await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName);
1201
+ await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName, streamData.cwd);
1054
1202
  streamData.hasUpdated = true;
1055
1203
  }
1056
1204
  }
@@ -1076,7 +1224,7 @@ class RouterServer {
1076
1224
  streamData.elements.push((0, ToolFormatter_1.createImageElement)(imageKey));
1077
1225
  streamData.createdAt = Date.now();
1078
1226
  if (streamData.feishuMessageId) {
1079
- await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName);
1227
+ await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName, streamData.cwd);
1080
1228
  streamData.hasUpdated = true;
1081
1229
  }
1082
1230
  }
@@ -1145,6 +1293,7 @@ class RouterServer {
1145
1293
  previous.recoveryId = info.recoveryId;
1146
1294
  previous.recoveryCardPending = true;
1147
1295
  previous.recoveryCwd = info.cwd;
1296
+ previous.cwd = info.cwd;
1148
1297
  previous.threadId = previous.threadId ?? threadId;
1149
1298
  previous.threadName = previous.threadName ?? info.threadName;
1150
1299
  previous.createdAt = Date.now();
@@ -1154,7 +1303,7 @@ class RouterServer {
1154
1303
  if (previous.currentTextContent.trim())
1155
1304
  elements.push(...this.renderCurrentText(previous));
1156
1305
  const textLength = previous.currentTextContent.length;
1157
- const updated = await this.feishuLongConnHandler.updateStreamingMessage(previous.feishuMessageId, elements, openId, previous.threadName);
1306
+ const updated = await this.feishuLongConnHandler.updateStreamingMessage(previous.feishuMessageId, elements, openId, previous.threadName, previous.cwd);
1158
1307
  if (!updated || !isCurrent() || this.streamingMessages.get(messageId) !== previous)
1159
1308
  return false;
1160
1309
  // Keep the staged recovery notice on failure so the same round can retry
@@ -1172,13 +1321,13 @@ class RouterServer {
1172
1321
  + `Output before this card, including output during disconnection, was not retained.\n\n`
1173
1322
  + `**Thread:** <raw>${escape(info.threadName)}</raw> ยท **Backend:** <raw>${escape(info.backend)}</raw>\n`
1174
1323
  + `**Working directory:** <raw>${escape(info.cwd)}</raw>\n**Task:** <raw>${escape(info.preview)}</raw>`;
1175
- const cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName);
1324
+ const cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd);
1176
1325
  if (!cardId || !isCurrent())
1177
1326
  return false;
1178
1327
  if (previous)
1179
1328
  this.clearDelegationProgressTimers(previous);
1180
1329
  this.streamingMessages.set(messageId, {
1181
- openId, deviceId, threadId, threadName: info.threadName, feishuMessageId: cardId,
1330
+ openId, deviceId, threadId, threadName: info.threadName, cwd: info.cwd, feishuMessageId: cardId,
1182
1331
  elements: [(0, ToolFormatter_1.createMarkdownElement)(intro)], currentTextContent: '', hasUpdated: false,
1183
1332
  createdAt: Date.now(), updatePending: false, finalizing: false, lastRenderedTextLength: 0,
1184
1333
  delegationProgress: new Map(),
@@ -1223,7 +1372,7 @@ class RouterServer {
1223
1372
  **Remaining in queue:** ${info.remainingCount}`;
1224
1373
  let cardId = null;
1225
1374
  try {
1226
- cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName);
1375
+ cardId = await this.feishuLongConnHandler.sendStreamingStart(openId, intro, info.threadName, info.cwd);
1227
1376
  }
1228
1377
  catch (error) {
1229
1378
  console.error('[RouterServer] Failed to create queued execution card:', error);
@@ -1237,6 +1386,7 @@ class RouterServer {
1237
1386
  deviceId,
1238
1387
  threadId,
1239
1388
  threadName: info.threadName,
1389
+ cwd: info.cwd,
1240
1390
  feishuMessageId: cardId || fallbackCardId,
1241
1391
  elements: [(0, ToolFormatter_1.createMarkdownElement)(intro)],
1242
1392
  currentTextContent: '',
@@ -1436,6 +1586,7 @@ class RouterServer {
1436
1586
  async stop() {
1437
1587
  console.log('Stopping router server...');
1438
1588
  this.approvalCards.destroy();
1589
+ await this.fileTransfers.destroy();
1439
1590
  // Stop cleanup interval
1440
1591
  if (this.cleanupInterval) {
1441
1592
  clearInterval(this.cleanupInterval);