@yu_robotics/remote-cli-router 1.6.170 → 1.6.173

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)
@@ -161,6 +164,7 @@ class RouterServer {
161
164
  // Register callback for streaming message start
162
165
  this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName) => {
163
166
  console.log(`[RouterServer] Registering streaming session: msgId=${messageId}, feishuMsgId=${feishuMessageId}, deviceId=${deviceId}, threadId=${threadId}, pendingNewThread=${pendingNewThread}`);
167
+ this.cancelImageReply(messageId);
164
168
  const previous = this.streamingMessages.get(messageId);
165
169
  if (previous)
166
170
  this.clearDelegationProgressTimers(previous);
@@ -354,6 +358,7 @@ class RouterServer {
354
358
  this.wss.on('connection', (ws, req) => {
355
359
  console.log('New WebSocket connection from:', req.socket.remoteAddress);
356
360
  let deviceId = null;
361
+ let socketClosed = false;
357
362
  let taskRecoveryEnabled = false;
358
363
  let approvalCardsEnabled = false;
359
364
  let delegationProgressEnabled = false;
@@ -434,8 +439,48 @@ class RouterServer {
434
439
  await this.approvalCards.resolve(message, deviceId);
435
440
  return;
436
441
  }
442
+ const imageDevice = deviceId;
443
+ const imageCurrent = () => !socketClosed && ws.readyState === ws_1.WebSocket.OPEN
444
+ && !!imageDevice && this.connectionHub.isCurrentConnection(imageDevice, ws);
445
+ // Establish routing before card creation awaits. Payload admission and
446
+ // response closure must occur before waiting for earlier operations.
447
+ if (imageDevice && taskRecoveryEnabled && message.type === 'task_resume') {
448
+ this.prepareImageReply(message.messageId, message.openId, imageDevice, imageCurrent, message.threadId, true);
449
+ }
450
+ if (imageDevice && message.type === types_1.MessageType.RESPONSE) {
451
+ const owner = message.openId || message.data?.openId;
452
+ const stream = this.streamingMessages.get(message.messageId);
453
+ const route = this.imageReplies.get(message.messageId);
454
+ if ((stream && (stream.openId !== owner || stream.deviceId !== imageDevice))
455
+ || (route && (route.openId !== owner || route.deviceId !== imageDevice)))
456
+ return;
457
+ if (route)
458
+ this.images.close(route.reply);
459
+ if (stream)
460
+ this.closeImageIntake(stream, route?.reply.deadline);
461
+ }
462
+ if (message.type === 'stream' && message.streamType === 'image') {
463
+ if (!imageDevice)
464
+ return;
465
+ const priorImageQueue = this.queueMessageOperations.get(message.messageId);
466
+ const operation = this.handleImage(message.messageId, message.openId, message.image, imageDevice, imageCurrent);
467
+ // Do not retain the parsed payload or raw frame in this async handler.
468
+ delete message.image;
469
+ data = Buffer.alloc(0);
470
+ if (this.startedQueueMessages.has(message.messageId)
471
+ && this.imageReplies.get(message.messageId)?.reply.tail === operation) {
472
+ const barrier = priorImageQueue ? priorImageQueue.then(() => operation, () => operation) : operation;
473
+ this.queueMessageOperations.set(message.messageId, barrier);
474
+ void barrier.then(() => {
475
+ if (this.queueMessageOperations.get(message.messageId) === barrier)
476
+ this.queueMessageOperations.delete(message.messageId);
477
+ });
478
+ }
479
+ await operation;
480
+ return;
481
+ }
437
482
  if (message.type === 'queue_started') {
438
- await this.handleQueueStarted(message, deviceId);
483
+ await this.handleQueueStarted(message, deviceId, imageCurrent);
439
484
  return;
440
485
  }
441
486
  // Serialize queued output through card creation, asynchronous tool/image
@@ -471,6 +516,8 @@ class RouterServer {
471
516
  catch (error) {
472
517
  console.error('[RouterServer] Failed to recover task card:', error);
473
518
  }
519
+ if (!success && current())
520
+ this.cancelImageReply(message.messageId);
474
521
  if (current())
475
522
  ws.send(JSON.stringify({ type: 'task_resume_ack', messageId: message.messageId,
476
523
  recoveryId: message.taskResume?.recoveryId, state: message.taskResume?.state, success, timestamp: Date.now() }));
@@ -536,6 +583,7 @@ class RouterServer {
536
583
  ws.close();
537
584
  break;
538
585
  }
586
+ this.cancelDeviceImages(deviceId);
539
587
  this.approvalCards.disconnect(deviceId);
540
588
  this.maintenanceCards.disconnect(deviceId);
541
589
  this.settingsCards.disconnect(deviceId);
@@ -757,11 +805,6 @@ class RouterServer {
757
805
  await this.handlePlanMode(message.messageId, message.openId, message.planContent);
758
806
  }
759
807
  break;
760
- case 'image':
761
- if (message.image) {
762
- await this.handleImage(message.messageId, message.openId, message.image);
763
- }
764
- break;
765
808
  }
766
809
  }
767
810
  break;
@@ -804,6 +847,11 @@ class RouterServer {
804
847
  });
805
848
  // Handle connection close
806
849
  ws.on('close', () => {
850
+ socketClosed = true;
851
+ for (const [id, route] of this.imageReplies) {
852
+ if (!route.current())
853
+ this.cancelImageReply(id);
854
+ }
807
855
  if (challengeTimer)
808
856
  clearTimeout(challengeTimer);
809
857
  if (heartbeatTimeout)
@@ -1394,34 +1442,117 @@ class RouterServer {
1394
1442
  streamData.hasUpdated = true;
1395
1443
  }
1396
1444
  }
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)
1445
+ /** Response receipt closes admission; accepted jobs consult the mutable deadline. */
1446
+ closeImageIntake(stream, deadline = Date.now() + ImageLifecycle_1.IMAGE_LIMITS.drainMs) {
1447
+ stream.imageIntakeClosed = true;
1448
+ stream.imageDrainDeadline ??= deadline;
1449
+ }
1450
+ cancelImageReply(messageId) {
1451
+ const route = this.imageReplies.get(messageId);
1452
+ if (route) {
1453
+ const stream = this.streamingMessages.get(messageId);
1454
+ if (stream && stream === route.stream) {
1455
+ stream.imageAttempts = route.reply.attempts;
1456
+ stream.imageHashes = route.reply.hashes;
1457
+ }
1458
+ this.images.cancel(route.reply);
1459
+ }
1460
+ this.imageReplies.delete(messageId);
1461
+ }
1462
+ cancelDeviceImages(deviceId) {
1463
+ for (const [id, route] of this.imageReplies)
1464
+ if (route.deviceId === deviceId)
1465
+ this.cancelImageReply(id);
1466
+ }
1467
+ prepareImageReply(messageId, openId, deviceId, current, threadId, pendingCard = false) {
1468
+ if (typeof messageId !== 'string' || !messageId || messageId.length > 200
1469
+ || typeof openId !== 'string' || !openId || openId.length > 200
1470
+ || (threadId !== undefined && (typeof threadId !== 'string' || threadId.length > 200)))
1401
1471
  return;
1402
- if (!image || image.type !== 'image' || typeof image.data !== 'string' || typeof image.mimeType !== 'string')
1472
+ const stream = this.streamingMessages.get(messageId);
1473
+ if (stream && (stream.openId !== openId || stream.deviceId !== deviceId
1474
+ || (stream.threadId && threadId && stream.threadId !== threadId)))
1403
1475
  return;
1404
- const imageKey = await this.feishuLongConnHandler.uploadImage(image.data, image.mimeType);
1405
- if (streamData.finalizing || this.streamingMessages.get(messageId) !== streamData)
1476
+ const existing = this.imageReplies.get(messageId);
1477
+ if (existing) {
1478
+ if (existing.openId !== openId || existing.deviceId !== deviceId
1479
+ || (existing.threadId && threadId && existing.threadId !== threadId))
1480
+ return;
1481
+ return existing;
1482
+ }
1483
+ if ((!stream && !pendingCard) || stream?.finalizing || stream?.imageIntakeClosed
1484
+ || this.isCompletedTask(messageId, deviceId) || this.imageReplies.size >= 1024)
1406
1485
  return;
1407
- if (!imageKey) {
1408
- streamData.elements.push((0, ToolFormatter_1.createMarkdownElement)('⚠️ Generated image could not be uploaded to Feishu.'));
1486
+ const reply = this.images.createReply();
1487
+ reply.attempts = stream?.imageAttempts ?? 0;
1488
+ reply.hashes = stream?.imageHashes ?? new Set();
1489
+ const route = { reply, openId, deviceId, threadId, current,
1490
+ stream: pendingCard ? undefined : stream, createdAt: Date.now() };
1491
+ this.imageReplies.set(messageId, route);
1492
+ return route;
1493
+ }
1494
+ noteImageFailure(messageId, stream) {
1495
+ if (stream.imageFailureHinted || stream.finalizing || this.streamingMessages.get(messageId) !== stream)
1409
1496
  return;
1497
+ stream.imageFailureHinted = true;
1498
+ stream.elements.push((0, ToolFormatter_1.createMarkdownElement)('⚠️ Generated image could not be uploaded to Feishu.'));
1499
+ void this.refreshStreamCard(messageId, stream);
1500
+ }
1501
+ async refreshStreamCard(messageId, stream) {
1502
+ try {
1503
+ await this.updateStreamingText(messageId, stream.openId, stream);
1410
1504
  }
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;
1505
+ catch {
1506
+ console.warn('[RouterServer] Could not refresh the image result.');
1423
1507
  }
1424
1508
  }
1509
+ handleImage(messageId, openId, image, deviceId, connectionCurrent) {
1510
+ const route = this.prepareImageReply(messageId, openId, deviceId, connectionCurrent);
1511
+ if (!route || !route.current())
1512
+ return Promise.resolve();
1513
+ const previous = this.queueMessageOperations.get(messageId);
1514
+ const current = () => {
1515
+ const stream = this.streamingMessages.get(messageId);
1516
+ return this.imageReplies.get(messageId) === route && route.current() && !!stream
1517
+ && stream === route.stream && !stream.finalizing && stream.openId === route.openId
1518
+ && stream.deviceId === route.deviceId;
1519
+ };
1520
+ const failure = () => {
1521
+ if (current())
1522
+ this.noteImageFailure(messageId, route.stream);
1523
+ };
1524
+ return this.images.offer(route.reply, image, previous, {
1525
+ current,
1526
+ upload: (data, mimeType) => this.feishuLongConnHandler.uploadImage(data, mimeType),
1527
+ failure,
1528
+ publish: async (key) => {
1529
+ if (!current())
1530
+ return;
1531
+ const stream = route.stream;
1532
+ if (stream.currentTextContent.trim()) {
1533
+ stream.elements.push(...this.renderCurrentText(stream));
1534
+ stream.currentTextContent = '';
1535
+ stream.recoveryPlainText = false;
1536
+ stream.lastRenderedTextLength = 0;
1537
+ }
1538
+ stream.elements.push((0, ToolFormatter_1.createImageElement)(key));
1539
+ stream.createdAt = Date.now();
1540
+ await this.refreshStreamCard(messageId, stream);
1541
+ },
1542
+ });
1543
+ }
1544
+ /** Bind pre-card admissions only to the card produced by their original route. */
1545
+ bindImageStream(messageId) {
1546
+ const route = this.imageReplies.get(messageId);
1547
+ const stream = this.streamingMessages.get(messageId);
1548
+ if (!route || !stream || !route.current() || stream.deviceId !== route.deviceId || stream.openId !== route.openId)
1549
+ return;
1550
+ route.stream = stream;
1551
+ if (route.reply.closed)
1552
+ this.closeImageIntake(stream, route.reply.deadline);
1553
+ if (route.reply.failed)
1554
+ this.noteImageFailure(messageId, stream);
1555
+ }
1425
1556
  rememberCompletedTask(messageId, deviceId) {
1426
1557
  this.completedTasks.set(messageId, { deviceId, completedAt: Date.now() });
1427
1558
  for (const [id, receipt] of this.completedTasks) {
@@ -1530,6 +1661,7 @@ class RouterServer {
1530
1661
  });
1531
1662
  this.cardThreadMap.set(cardId, { threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1532
1663
  }
1664
+ this.bindImageStream(messageId);
1533
1665
  if (info.state !== 'running') {
1534
1666
  await this.finalizeStreamingMessage(messageId, info.state === 'completed', undefined, info.error, undefined, info.cwd, undefined, (0, ExecutionMetadata_1.parseExecutionMetadata)(info.executionMetadata));
1535
1667
  if (!isCurrent())
@@ -1539,7 +1671,7 @@ class RouterServer {
1539
1671
  return true;
1540
1672
  }
1541
1673
  /** Create a fresh card before accepting any output for a dequeued task. */
1542
- async handleQueueStarted(message, deviceId) {
1674
+ async handleQueueStarted(message, deviceId, isCurrent = () => true) {
1543
1675
  const info = message.queueStarted;
1544
1676
  const { messageId, openId, threadId } = message;
1545
1677
  if (!deviceId || typeof messageId !== 'string' || !messageId
@@ -1558,6 +1690,8 @@ class RouterServer {
1558
1690
  if (this.startedQueueMessages.has(messageId))
1559
1691
  return;
1560
1692
  this.startedQueueMessages.set(messageId, Date.now());
1693
+ this.cancelImageReply(messageId);
1694
+ const imageRoute = this.prepareImageReply(messageId, openId, deviceId, isCurrent, threadId, true);
1561
1695
  const operation = Promise.resolve().then(async () => {
1562
1696
  const intro = `▶️ **Queued task started**
1563
1697
 
@@ -1572,6 +1706,8 @@ class RouterServer {
1572
1706
  catch (error) {
1573
1707
  console.error('[RouterServer] Failed to create queued execution card:', error);
1574
1708
  }
1709
+ if (!isCurrent() || (imageRoute && this.imageReplies.get(messageId) !== imageRoute))
1710
+ return;
1575
1711
  const fallbackCardId = previous?.feishuMessageId || previous?.queueCardId || null;
1576
1712
  if (previous && this.streamingMessages.get(messageId) === previous) {
1577
1713
  this.clearDelegationProgressTimers(previous);
@@ -1595,6 +1731,7 @@ class RouterServer {
1595
1731
  queueStarted: info,
1596
1732
  threads: Array.isArray(message.threads) ? message.threads : undefined,
1597
1733
  });
1734
+ this.bindImageStream(messageId);
1598
1735
  if (cardId || fallbackCardId) {
1599
1736
  this.cardThreadMap.set((cardId || fallbackCardId), {
1600
1737
  threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
@@ -1603,6 +1740,8 @@ class RouterServer {
1603
1740
  if (cardId) {
1604
1741
  const oldCards = new Set([previous?.queueCardId, previous?.feishuMessageId]);
1605
1742
  for (const oldCard of oldCards) {
1743
+ if (!isCurrent())
1744
+ return;
1606
1745
  if (!oldCard || oldCard === cardId)
1607
1746
  continue;
1608
1747
  try {
@@ -1660,6 +1799,20 @@ class RouterServer {
1660
1799
  const streamData = this.streamingMessages.get(messageId);
1661
1800
  if (!streamData)
1662
1801
  return;
1802
+ const route = this.imageReplies.get(messageId);
1803
+ if (route)
1804
+ this.images.close(route.reply);
1805
+ this.closeImageIntake(streamData, route?.reply.deadline);
1806
+ // Snapshot accepted work before awaiting; intake is already closed.
1807
+ const accepted = route?.reply.tail;
1808
+ if (accepted)
1809
+ await accepted;
1810
+ if (this.streamingMessages.get(messageId) !== streamData
1811
+ || (route && (this.imageReplies.get(messageId) !== route || !route.current())))
1812
+ return;
1813
+ if (route?.reply.failed)
1814
+ this.noteImageFailure(messageId, streamData);
1815
+ this.cancelImageReply(messageId);
1663
1816
  streamData.finalizing = true;
1664
1817
  streamData.updatePending = false;
1665
1818
  this.clearDelegationProgressTimers(streamData);
@@ -1736,6 +1889,11 @@ class RouterServer {
1736
1889
  cleanupStaleStreamingSessions() {
1737
1890
  const now = Date.now();
1738
1891
  let cleanedCount = 0;
1892
+ for (const [messageId, route] of this.imageReplies) {
1893
+ if (!route.current() || (!this.streamingMessages.has(messageId)
1894
+ && now - route.createdAt > this.STREAMING_SESSION_TIMEOUT_MS))
1895
+ this.cancelImageReply(messageId);
1896
+ }
1739
1897
  for (const [messageId, session] of this.streamingMessages.entries()) {
1740
1898
  if (now - session.createdAt > this.STREAMING_SESSION_TIMEOUT_MS) {
1741
1899
  console.log(`[RouterServer] Cleaning up stale streaming session: ${messageId}`);
@@ -1745,6 +1903,7 @@ class RouterServer {
1745
1903
  this.cardThreadMap.delete(session.feishuMessageId);
1746
1904
  }
1747
1905
  this.clearDelegationProgressTimers(session);
1906
+ this.cancelImageReply(messageId);
1748
1907
  this.streamingMessages.delete(messageId);
1749
1908
  this.lastStreamUpdateTime.delete(messageId);
1750
1909
  cleanedCount++;
@@ -1770,6 +1929,7 @@ class RouterServer {
1770
1929
  * @param deviceId Device ID that disconnected
1771
1930
  */
1772
1931
  cleanupStreamingSessionsForDevice(deviceId) {
1932
+ this.cancelDeviceImages(deviceId);
1773
1933
  let cleanedCount = 0;
1774
1934
  for (const [messageId, session] of this.streamingMessages.entries()) {
1775
1935
  if (session.deviceId === deviceId) {
@@ -1779,6 +1939,7 @@ class RouterServer {
1779
1939
  this.cardThreadMap.delete(session.feishuMessageId);
1780
1940
  }
1781
1941
  this.clearDelegationProgressTimers(session);
1942
+ this.cancelImageReply(messageId);
1782
1943
  this.streamingMessages.delete(messageId);
1783
1944
  this.lastStreamUpdateTime.delete(messageId);
1784
1945
  cleanedCount++;
@@ -1799,6 +1960,8 @@ class RouterServer {
1799
1960
  */
1800
1961
  async stop() {
1801
1962
  console.log('Stopping router server...');
1963
+ for (const id of this.imageReplies.keys())
1964
+ this.cancelImageReply(id);
1802
1965
  this.approvalCards.destroy();
1803
1966
  this.workerContextCards.destroy();
1804
1967
  this.workerContextConnections.clear();