@yu_robotics/remote-cli-router 1.6.172 → 1.6.176

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
@@ -14,6 +14,7 @@ const FileTransfers_1 = require("./files/FileTransfers");
14
14
  const path_1 = __importDefault(require("path"));
15
15
  const os_1 = __importDefault(require("os"));
16
16
  const crypto_1 = require("crypto");
17
+ const ImageLifecycle_1 = require("./utils/ImageLifecycle");
17
18
  const ActivityProgress_1 = require("./utils/ActivityProgress");
18
19
  const ExecutionMetadata_1 = require("./utils/ExecutionMetadata");
19
20
  const koa_1 = __importDefault(require("koa"));
@@ -58,6 +59,8 @@ class RouterServer {
58
59
  completedTasks = new Map();
59
60
  queueMessageOperations = new Map();
60
61
  startedQueueMessages = new Map();
62
+ images = new ImageLifecycle_1.ImageLifecycle();
63
+ imageReplies = new Map();
61
64
  STREAMING_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes timeout
62
65
  DELEGATION_PROGRESS_HEARTBEAT_MS = 30 * 1000;
63
66
  // TTL for cardThreadMap entries: 7 days (allows users to reply to old cards)
@@ -142,6 +145,7 @@ class RouterServer {
142
145
  this.settingsCards = new SettingsCards_1.SettingsCards({
143
146
  ownsDevice: async (openId, deviceId) => (await this.bindingManager.getDeviceBinding(deviceId))?.openId === openId,
144
147
  available: (deviceId, kind) => this.settingsConnections.get(deviceId)?.(kind) === true,
148
+ speedAvailable: deviceId => this.settingsConnections.get(deviceId)?.('speed') === true,
145
149
  send: (deviceId, message) => this.connectionHub.sendToDevice(deviceId, message),
146
150
  update: (cardId, elements, header) => this.feishuLongConnHandler.updateApprovalCard(cardId, elements, header),
147
151
  });
@@ -161,6 +165,7 @@ class RouterServer {
161
165
  // Register callback for streaming message start
162
166
  this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName) => {
163
167
  console.log(`[RouterServer] Registering streaming session: msgId=${messageId}, feishuMsgId=${feishuMessageId}, deviceId=${deviceId}, threadId=${threadId}, pendingNewThread=${pendingNewThread}`);
168
+ this.cancelImageReply(messageId);
164
169
  const previous = this.streamingMessages.get(messageId);
165
170
  if (previous)
166
171
  this.clearDelegationProgressTimers(previous);
@@ -354,12 +359,14 @@ class RouterServer {
354
359
  this.wss.on('connection', (ws, req) => {
355
360
  console.log('New WebSocket connection from:', req.socket.remoteAddress);
356
361
  let deviceId = null;
362
+ let socketClosed = false;
357
363
  let taskRecoveryEnabled = false;
358
364
  let approvalCardsEnabled = false;
359
365
  let delegationProgressEnabled = false;
360
366
  let delegationProgressTextEnabled = false;
361
367
  let workerContextResetEnabled = false;
362
368
  let settingsCardsEnabled = false;
369
+ let modelSpeedSettingsEnabled = false;
363
370
  let directoryCardsEnabled = false;
364
371
  let delegationCardsEnabled = false;
365
372
  let streamingContextEnabled = false;
@@ -434,8 +441,48 @@ class RouterServer {
434
441
  await this.approvalCards.resolve(message, deviceId);
435
442
  return;
436
443
  }
444
+ const imageDevice = deviceId;
445
+ const imageCurrent = () => !socketClosed && ws.readyState === ws_1.WebSocket.OPEN
446
+ && !!imageDevice && this.connectionHub.isCurrentConnection(imageDevice, ws);
447
+ // Establish routing before card creation awaits. Payload admission and
448
+ // response closure must occur before waiting for earlier operations.
449
+ if (imageDevice && taskRecoveryEnabled && message.type === 'task_resume') {
450
+ this.prepareImageReply(message.messageId, message.openId, imageDevice, imageCurrent, message.threadId, true);
451
+ }
452
+ if (imageDevice && message.type === types_1.MessageType.RESPONSE) {
453
+ const owner = message.openId || message.data?.openId;
454
+ const stream = this.streamingMessages.get(message.messageId);
455
+ const route = this.imageReplies.get(message.messageId);
456
+ if ((stream && (stream.openId !== owner || stream.deviceId !== imageDevice))
457
+ || (route && (route.openId !== owner || route.deviceId !== imageDevice)))
458
+ return;
459
+ if (route)
460
+ this.images.close(route.reply);
461
+ if (stream)
462
+ this.closeImageIntake(stream, route?.reply.deadline);
463
+ }
464
+ if (message.type === 'stream' && message.streamType === 'image') {
465
+ if (!imageDevice)
466
+ return;
467
+ const priorImageQueue = this.queueMessageOperations.get(message.messageId);
468
+ const operation = this.handleImage(message.messageId, message.openId, message.image, imageDevice, imageCurrent);
469
+ // Do not retain the parsed payload or raw frame in this async handler.
470
+ delete message.image;
471
+ data = Buffer.alloc(0);
472
+ if (this.startedQueueMessages.has(message.messageId)
473
+ && this.imageReplies.get(message.messageId)?.reply.tail === operation) {
474
+ const barrier = priorImageQueue ? priorImageQueue.then(() => operation, () => operation) : operation;
475
+ this.queueMessageOperations.set(message.messageId, barrier);
476
+ void barrier.then(() => {
477
+ if (this.queueMessageOperations.get(message.messageId) === barrier)
478
+ this.queueMessageOperations.delete(message.messageId);
479
+ });
480
+ }
481
+ await operation;
482
+ return;
483
+ }
437
484
  if (message.type === 'queue_started') {
438
- await this.handleQueueStarted(message, deviceId);
485
+ await this.handleQueueStarted(message, deviceId, imageCurrent);
439
486
  return;
440
487
  }
441
488
  // Serialize queued output through card creation, asynchronous tool/image
@@ -471,6 +518,8 @@ class RouterServer {
471
518
  catch (error) {
472
519
  console.error('[RouterServer] Failed to recover task card:', error);
473
520
  }
521
+ if (!success && current())
522
+ this.cancelImageReply(message.messageId);
474
523
  if (current())
475
524
  ws.send(JSON.stringify({ type: 'task_resume_ack', messageId: message.messageId,
476
525
  recoveryId: message.taskResume?.recoveryId, state: message.taskResume?.state, success, timestamp: Date.now() }));
@@ -536,6 +585,7 @@ class RouterServer {
536
585
  ws.close();
537
586
  break;
538
587
  }
588
+ this.cancelDeviceImages(deviceId);
539
589
  this.approvalCards.disconnect(deviceId);
540
590
  this.maintenanceCards.disconnect(deviceId);
541
591
  this.settingsCards.disconnect(deviceId);
@@ -570,11 +620,13 @@ class RouterServer {
570
620
  // Settings cards are negotiated only when the CLI requests them;
571
621
  // old peers keep plain text output and never see the capability.
572
622
  settingsCardsEnabled = message.data.capabilities?.settingsCards === true;
623
+ modelSpeedSettingsEnabled = settingsCardsEnabled && message.data.capabilities?.modelSpeedSettings === true;
573
624
  directoryCardsEnabled = settingsCardsEnabled && message.data.capabilities?.directoryCards === true;
574
625
  delegationCardsEnabled = settingsCardsEnabled && message.data.capabilities?.delegationCards === true;
575
626
  if (settingsCardsEnabled)
576
627
  this.settingsConnections.set(deviceId, kind => ws.readyState === ws_1.WebSocket.OPEN && this.connectionHub.isCurrentConnection(requestedId, ws)
577
- && (kind !== 'delegation' || delegationCardsEnabled) && (kind !== 'directory' || directoryCardsEnabled));
628
+ && (kind !== 'delegation' || delegationCardsEnabled) && (kind !== 'directory' || directoryCardsEnabled)
629
+ && (kind !== 'speed' || modelSpeedSettingsEnabled));
578
630
  else
579
631
  this.settingsConnections.delete(deviceId);
580
632
  // Send confirmation with version info for client-side version check
@@ -599,6 +651,7 @@ class RouterServer {
599
651
  ...(workerContextResetEnabled ? { workerContextReset: true } : {}),
600
652
  ...(streamingContextEnabled ? { streamingContext: true } : {}),
601
653
  ...(settingsCardsEnabled ? { settingsCards: true } : {}),
654
+ ...(modelSpeedSettingsEnabled ? { modelSpeedSettings: true } : {}),
602
655
  ...(directoryCardsEnabled ? { directoryCards: true } : {}),
603
656
  ...(delegationCardsEnabled ? { delegationCards: true } : {}),
604
657
  } } : {}),
@@ -757,11 +810,6 @@ class RouterServer {
757
810
  await this.handlePlanMode(message.messageId, message.openId, message.planContent);
758
811
  }
759
812
  break;
760
- case 'image':
761
- if (message.image) {
762
- await this.handleImage(message.messageId, message.openId, message.image);
763
- }
764
- break;
765
813
  }
766
814
  }
767
815
  break;
@@ -804,6 +852,11 @@ class RouterServer {
804
852
  });
805
853
  // Handle connection close
806
854
  ws.on('close', () => {
855
+ socketClosed = true;
856
+ for (const [id, route] of this.imageReplies) {
857
+ if (!route.current())
858
+ this.cancelImageReply(id);
859
+ }
807
860
  if (challengeTimer)
808
861
  clearTimeout(challengeTimer);
809
862
  if (heartbeatTimeout)
@@ -1394,34 +1447,117 @@ class RouterServer {
1394
1447
  streamData.hasUpdated = true;
1395
1448
  }
1396
1449
  }
1397
- async handleImage(messageId, openId, image) {
1398
- console.log(`[RouterServer] Received generated image for ${messageId}`);
1399
- const streamData = this.streamingMessages.get(messageId);
1400
- if (!streamData || streamData.finalizing)
1450
+ /** Response receipt closes admission; accepted jobs consult the mutable deadline. */
1451
+ closeImageIntake(stream, deadline = Date.now() + ImageLifecycle_1.IMAGE_LIMITS.drainMs) {
1452
+ stream.imageIntakeClosed = true;
1453
+ stream.imageDrainDeadline ??= deadline;
1454
+ }
1455
+ cancelImageReply(messageId) {
1456
+ const route = this.imageReplies.get(messageId);
1457
+ if (route) {
1458
+ const stream = this.streamingMessages.get(messageId);
1459
+ if (stream && stream === route.stream) {
1460
+ stream.imageAttempts = route.reply.attempts;
1461
+ stream.imageHashes = route.reply.hashes;
1462
+ }
1463
+ this.images.cancel(route.reply);
1464
+ }
1465
+ this.imageReplies.delete(messageId);
1466
+ }
1467
+ cancelDeviceImages(deviceId) {
1468
+ for (const [id, route] of this.imageReplies)
1469
+ if (route.deviceId === deviceId)
1470
+ this.cancelImageReply(id);
1471
+ }
1472
+ prepareImageReply(messageId, openId, deviceId, current, threadId, pendingCard = false) {
1473
+ if (typeof messageId !== 'string' || !messageId || messageId.length > 200
1474
+ || typeof openId !== 'string' || !openId || openId.length > 200
1475
+ || (threadId !== undefined && (typeof threadId !== 'string' || threadId.length > 200)))
1401
1476
  return;
1402
- if (!image || image.type !== 'image' || typeof image.data !== 'string' || typeof image.mimeType !== 'string')
1477
+ const stream = this.streamingMessages.get(messageId);
1478
+ if (stream && (stream.openId !== openId || stream.deviceId !== deviceId
1479
+ || (stream.threadId && threadId && stream.threadId !== threadId)))
1403
1480
  return;
1404
- const imageKey = await this.feishuLongConnHandler.uploadImage(image.data, image.mimeType);
1405
- if (streamData.finalizing || this.streamingMessages.get(messageId) !== streamData)
1481
+ const existing = this.imageReplies.get(messageId);
1482
+ if (existing) {
1483
+ if (existing.openId !== openId || existing.deviceId !== deviceId
1484
+ || (existing.threadId && threadId && existing.threadId !== threadId))
1485
+ return;
1486
+ return existing;
1487
+ }
1488
+ if ((!stream && !pendingCard) || stream?.finalizing || stream?.imageIntakeClosed
1489
+ || this.isCompletedTask(messageId, deviceId) || this.imageReplies.size >= 1024)
1406
1490
  return;
1407
- if (!imageKey) {
1408
- streamData.elements.push((0, ToolFormatter_1.createMarkdownElement)('⚠️ Generated image could not be uploaded to Feishu.'));
1491
+ const reply = this.images.createReply();
1492
+ reply.attempts = stream?.imageAttempts ?? 0;
1493
+ reply.hashes = stream?.imageHashes ?? new Set();
1494
+ const route = { reply, openId, deviceId, threadId, current,
1495
+ stream: pendingCard ? undefined : stream, createdAt: Date.now() };
1496
+ this.imageReplies.set(messageId, route);
1497
+ return route;
1498
+ }
1499
+ noteImageFailure(messageId, stream) {
1500
+ if (stream.imageFailureHinted || stream.finalizing || this.streamingMessages.get(messageId) !== stream)
1409
1501
  return;
1502
+ stream.imageFailureHinted = true;
1503
+ stream.elements.push((0, ToolFormatter_1.createMarkdownElement)('⚠️ Generated image could not be uploaded to Feishu.'));
1504
+ void this.refreshStreamCard(messageId, stream);
1505
+ }
1506
+ async refreshStreamCard(messageId, stream) {
1507
+ try {
1508
+ await this.updateStreamingText(messageId, stream.openId, stream);
1410
1509
  }
1411
- if (streamData.currentTextContent.trim()) {
1412
- streamData.elements.push(...this.renderCurrentText(streamData));
1413
- streamData.currentTextContent = '';
1414
- streamData.recoveryPlainText = false;
1415
- streamData.lastRenderedTextLength = 0;
1416
- }
1417
- streamData.updatePending = false;
1418
- streamData.elements.push((0, ToolFormatter_1.createImageElement)(imageKey));
1419
- streamData.createdAt = Date.now();
1420
- if (streamData.feishuMessageId) {
1421
- await this.feishuLongConnHandler.updateStreamingMessage(streamData.feishuMessageId, streamData.elements, openId, streamData.threadName, streamData.cwd);
1422
- streamData.hasUpdated = true;
1510
+ catch {
1511
+ console.warn('[RouterServer] Could not refresh the image result.');
1423
1512
  }
1424
1513
  }
1514
+ handleImage(messageId, openId, image, deviceId, connectionCurrent) {
1515
+ const route = this.prepareImageReply(messageId, openId, deviceId, connectionCurrent);
1516
+ if (!route || !route.current())
1517
+ return Promise.resolve();
1518
+ const previous = this.queueMessageOperations.get(messageId);
1519
+ const current = () => {
1520
+ const stream = this.streamingMessages.get(messageId);
1521
+ return this.imageReplies.get(messageId) === route && route.current() && !!stream
1522
+ && stream === route.stream && !stream.finalizing && stream.openId === route.openId
1523
+ && stream.deviceId === route.deviceId;
1524
+ };
1525
+ const failure = () => {
1526
+ if (current())
1527
+ this.noteImageFailure(messageId, route.stream);
1528
+ };
1529
+ return this.images.offer(route.reply, image, previous, {
1530
+ current,
1531
+ upload: (data, mimeType) => this.feishuLongConnHandler.uploadImage(data, mimeType),
1532
+ failure,
1533
+ publish: async (key) => {
1534
+ if (!current())
1535
+ return;
1536
+ const stream = route.stream;
1537
+ if (stream.currentTextContent.trim()) {
1538
+ stream.elements.push(...this.renderCurrentText(stream));
1539
+ stream.currentTextContent = '';
1540
+ stream.recoveryPlainText = false;
1541
+ stream.lastRenderedTextLength = 0;
1542
+ }
1543
+ stream.elements.push((0, ToolFormatter_1.createImageElement)(key));
1544
+ stream.createdAt = Date.now();
1545
+ await this.refreshStreamCard(messageId, stream);
1546
+ },
1547
+ });
1548
+ }
1549
+ /** Bind pre-card admissions only to the card produced by their original route. */
1550
+ bindImageStream(messageId) {
1551
+ const route = this.imageReplies.get(messageId);
1552
+ const stream = this.streamingMessages.get(messageId);
1553
+ if (!route || !stream || !route.current() || stream.deviceId !== route.deviceId || stream.openId !== route.openId)
1554
+ return;
1555
+ route.stream = stream;
1556
+ if (route.reply.closed)
1557
+ this.closeImageIntake(stream, route.reply.deadline);
1558
+ if (route.reply.failed)
1559
+ this.noteImageFailure(messageId, stream);
1560
+ }
1425
1561
  rememberCompletedTask(messageId, deviceId) {
1426
1562
  this.completedTasks.set(messageId, { deviceId, completedAt: Date.now() });
1427
1563
  for (const [id, receipt] of this.completedTasks) {
@@ -1530,6 +1666,7 @@ class RouterServer {
1530
1666
  });
1531
1667
  this.cardThreadMap.set(cardId, { threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1532
1668
  }
1669
+ this.bindImageStream(messageId);
1533
1670
  if (info.state !== 'running') {
1534
1671
  await this.finalizeStreamingMessage(messageId, info.state === 'completed', undefined, info.error, undefined, info.cwd, undefined, (0, ExecutionMetadata_1.parseExecutionMetadata)(info.executionMetadata));
1535
1672
  if (!isCurrent())
@@ -1539,7 +1676,7 @@ class RouterServer {
1539
1676
  return true;
1540
1677
  }
1541
1678
  /** Create a fresh card before accepting any output for a dequeued task. */
1542
- async handleQueueStarted(message, deviceId) {
1679
+ async handleQueueStarted(message, deviceId, isCurrent = () => true) {
1543
1680
  const info = message.queueStarted;
1544
1681
  const { messageId, openId, threadId } = message;
1545
1682
  if (!deviceId || typeof messageId !== 'string' || !messageId
@@ -1558,6 +1695,8 @@ class RouterServer {
1558
1695
  if (this.startedQueueMessages.has(messageId))
1559
1696
  return;
1560
1697
  this.startedQueueMessages.set(messageId, Date.now());
1698
+ this.cancelImageReply(messageId);
1699
+ const imageRoute = this.prepareImageReply(messageId, openId, deviceId, isCurrent, threadId, true);
1561
1700
  const operation = Promise.resolve().then(async () => {
1562
1701
  const intro = `▶️ **Queued task started**
1563
1702
 
@@ -1572,6 +1711,8 @@ class RouterServer {
1572
1711
  catch (error) {
1573
1712
  console.error('[RouterServer] Failed to create queued execution card:', error);
1574
1713
  }
1714
+ if (!isCurrent() || (imageRoute && this.imageReplies.get(messageId) !== imageRoute))
1715
+ return;
1575
1716
  const fallbackCardId = previous?.feishuMessageId || previous?.queueCardId || null;
1576
1717
  if (previous && this.streamingMessages.get(messageId) === previous) {
1577
1718
  this.clearDelegationProgressTimers(previous);
@@ -1595,6 +1736,7 @@ class RouterServer {
1595
1736
  queueStarted: info,
1596
1737
  threads: Array.isArray(message.threads) ? message.threads : undefined,
1597
1738
  });
1739
+ this.bindImageStream(messageId);
1598
1740
  if (cardId || fallbackCardId) {
1599
1741
  this.cardThreadMap.set((cardId || fallbackCardId), {
1600
1742
  threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
@@ -1603,6 +1745,8 @@ class RouterServer {
1603
1745
  if (cardId) {
1604
1746
  const oldCards = new Set([previous?.queueCardId, previous?.feishuMessageId]);
1605
1747
  for (const oldCard of oldCards) {
1748
+ if (!isCurrent())
1749
+ return;
1606
1750
  if (!oldCard || oldCard === cardId)
1607
1751
  continue;
1608
1752
  try {
@@ -1660,6 +1804,20 @@ class RouterServer {
1660
1804
  const streamData = this.streamingMessages.get(messageId);
1661
1805
  if (!streamData)
1662
1806
  return;
1807
+ const route = this.imageReplies.get(messageId);
1808
+ if (route)
1809
+ this.images.close(route.reply);
1810
+ this.closeImageIntake(streamData, route?.reply.deadline);
1811
+ // Snapshot accepted work before awaiting; intake is already closed.
1812
+ const accepted = route?.reply.tail;
1813
+ if (accepted)
1814
+ await accepted;
1815
+ if (this.streamingMessages.get(messageId) !== streamData
1816
+ || (route && (this.imageReplies.get(messageId) !== route || !route.current())))
1817
+ return;
1818
+ if (route?.reply.failed)
1819
+ this.noteImageFailure(messageId, streamData);
1820
+ this.cancelImageReply(messageId);
1663
1821
  streamData.finalizing = true;
1664
1822
  streamData.updatePending = false;
1665
1823
  this.clearDelegationProgressTimers(streamData);
@@ -1736,6 +1894,11 @@ class RouterServer {
1736
1894
  cleanupStaleStreamingSessions() {
1737
1895
  const now = Date.now();
1738
1896
  let cleanedCount = 0;
1897
+ for (const [messageId, route] of this.imageReplies) {
1898
+ if (!route.current() || (!this.streamingMessages.has(messageId)
1899
+ && now - route.createdAt > this.STREAMING_SESSION_TIMEOUT_MS))
1900
+ this.cancelImageReply(messageId);
1901
+ }
1739
1902
  for (const [messageId, session] of this.streamingMessages.entries()) {
1740
1903
  if (now - session.createdAt > this.STREAMING_SESSION_TIMEOUT_MS) {
1741
1904
  console.log(`[RouterServer] Cleaning up stale streaming session: ${messageId}`);
@@ -1745,6 +1908,7 @@ class RouterServer {
1745
1908
  this.cardThreadMap.delete(session.feishuMessageId);
1746
1909
  }
1747
1910
  this.clearDelegationProgressTimers(session);
1911
+ this.cancelImageReply(messageId);
1748
1912
  this.streamingMessages.delete(messageId);
1749
1913
  this.lastStreamUpdateTime.delete(messageId);
1750
1914
  cleanedCount++;
@@ -1770,6 +1934,7 @@ class RouterServer {
1770
1934
  * @param deviceId Device ID that disconnected
1771
1935
  */
1772
1936
  cleanupStreamingSessionsForDevice(deviceId) {
1937
+ this.cancelDeviceImages(deviceId);
1773
1938
  let cleanedCount = 0;
1774
1939
  for (const [messageId, session] of this.streamingMessages.entries()) {
1775
1940
  if (session.deviceId === deviceId) {
@@ -1779,6 +1944,7 @@ class RouterServer {
1779
1944
  this.cardThreadMap.delete(session.feishuMessageId);
1780
1945
  }
1781
1946
  this.clearDelegationProgressTimers(session);
1947
+ this.cancelImageReply(messageId);
1782
1948
  this.streamingMessages.delete(messageId);
1783
1949
  this.lastStreamUpdateTime.delete(messageId);
1784
1950
  cleanedCount++;
@@ -1799,6 +1965,8 @@ class RouterServer {
1799
1965
  */
1800
1966
  async stop() {
1801
1967
  console.log('Stopping router server...');
1968
+ for (const id of this.imageReplies.keys())
1969
+ this.cancelImageReply(id);
1802
1970
  this.approvalCards.destroy();
1803
1971
  this.workerContextCards.destroy();
1804
1972
  this.workerContextConnections.clear();