@yu_robotics/remote-cli-router 1.6.187 → 1.6.189

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.
@@ -110,9 +110,17 @@ class FeishuLongConnHandler {
110
110
  /**
111
111
  * Callback to register streaming message with RouterServer.
112
112
  * pendingNewThread=true signals that this command will create a new thread,
113
- * so the server should update activeThreadMap when the response arrives.
113
+ * so the server can persist its selection when the correlated response arrives.
114
114
  */
115
115
  onStartStreaming;
116
+ onCaptureSelection;
117
+ onValidateSelection;
118
+ setOnValidateSelection(callback) {
119
+ this.onValidateSelection = callback;
120
+ }
121
+ setOnCaptureSelection(callback) {
122
+ this.onCaptureSelection = callback;
123
+ }
116
124
  /**
117
125
  * Set streaming start callback
118
126
  */
@@ -150,6 +158,7 @@ class FeishuLongConnHandler {
150
158
  * Callback invoked after a user switches to a different device.
151
159
  * RouterServer uses this to clear stale thread state tied to the old device.
152
160
  */
161
+ onDeviceSwitchIntent;
153
162
  onDeviceSwitch;
154
163
  onApproveDeviceKey;
155
164
  onRevokeDevice;
@@ -161,6 +170,7 @@ class FeishuLongConnHandler {
161
170
  * that have no parent_id).
162
171
  */
163
172
  onResolveActiveThread;
173
+ onRecoverThreads;
164
174
  /**
165
175
  * Set active thread resolution callback
166
176
  */
@@ -186,23 +196,42 @@ class FeishuLongConnHandler {
186
196
  const parentId = message.parent_id || undefined;
187
197
  let fileReference = parentId ? this.onResolveFile?.(openId, parentId) : undefined;
188
198
  if (message.message_type === 'file') {
189
- const resolved = parentId ? this.onResolveThread?.(parentId) : this.onResolveActiveThread?.(openId);
190
- const selectedThread = fileReference?.threadId ?? resolved?.threadId;
191
- const referencedDevice = fileReference?.deviceId ?? (resolved && 'deviceId' in resolved ? resolved.deviceId : undefined);
192
- const selectedDevice = referencedDevice
193
- ? this.bindingManager.getUserDevices(openId).then(devices => devices.find(device => device.deviceId === referencedDevice))
194
- : this.bindingManager.getActiveDevice(openId);
199
+ const resolved = parentId ? await this.onResolveThread?.(parentId, openId) : undefined;
200
+ if (parentId && !fileReference && !resolved) {
201
+ await this.replyToMessage(messageId, '❌ This card\'s thread link has expired. Choose a thread and resend the file.');
202
+ return;
203
+ }
204
+ const referencedDevice = fileReference?.deviceId ?? resolved?.deviceId;
195
205
  const previous = this.fileAdmissions.get(openId) ?? Promise.resolve();
206
+ const destination = (async () => {
207
+ const device = referencedDevice
208
+ ? (await this.bindingManager.getUserDevices(openId)).find(item => item.deviceId === referencedDevice)
209
+ : await this.bindingManager.getActiveDevice(openId);
210
+ if (!device)
211
+ throw new Error('File reception requires an active, authenticated CLI.');
212
+ const fence = this.onCaptureSelection?.(openId, device.deviceId);
213
+ const active = parentId ? undefined : await this.onResolveActiveThread?.(openId, device.deviceId);
214
+ return { deviceId: device.deviceId, threadId: fileReference?.threadId ?? resolved?.threadId ?? active?.threadId, fence };
215
+ })().then(route => ({ route }), error => ({ error }));
196
216
  const admission = previous.catch(() => { }).then(async () => {
197
217
  try {
198
218
  const file = JSON.parse(message.content);
199
- const device = await selectedDevice;
200
- if (!device || !this.onFileMessage)
219
+ const captured = await destination;
220
+ if ('error' in captured)
221
+ throw captured.error;
222
+ const { deviceId, threadId, fence } = captured.route;
223
+ if (!this.onFileMessage)
201
224
  throw new Error('File reception requires an upgraded Router and an active, authenticated CLI.');
202
225
  if (typeof file.file_key !== 'string' || !/^[a-zA-Z0-9_-]{1,512}$/.test(file.file_key)
203
226
  || typeof messageId !== 'string' || !/^[a-zA-Z0-9_-]{1,200}$/.test(messageId))
204
227
  throw new Error('Invalid file attachment.');
205
- await this.onFileMessage({ openId, deviceId: device.deviceId, threadId: selectedThread,
228
+ if (fence && this.onValidateSelection) {
229
+ const devices = await this.bindingManager.getUserDevices(openId);
230
+ if (!this.onValidateSelection(fence) || !devices.some(device => device.deviceId === deviceId)) {
231
+ throw new Error('This file was superseded or the device changed before reception.');
232
+ }
233
+ }
234
+ await this.onFileMessage({ openId, deviceId, threadId,
206
235
  messageId, fileKey: file.file_key, name: file.file_name });
207
236
  }
208
237
  catch (error) {
@@ -265,21 +294,20 @@ class FeishuLongConnHandler {
265
294
  console.log(`[FeishuHandler] Empty content and no attachments, ignoring message`);
266
295
  return;
267
296
  }
297
+ const resolved = parentId ? await this.onResolveThread?.(parentId, openId) : undefined;
298
+ if (parentId && !fileReference && !resolved) {
299
+ await this.replyToMessage(messageId, '❌ This card\'s thread link has expired. Choose a thread and resend your message.');
300
+ return;
301
+ }
302
+ const targetThreadId = fileReference?.threadId ?? resolved?.threadId;
303
+ const sourceDeviceId = fileReference?.deviceId ?? resolved?.deviceId;
268
304
  // Check if it's a command (only for text messages)
269
305
  if (message.message_type !== 'image' && this.isCommand(content)) {
270
- // parent_id → resolve thread from card; otherwise check active thread for this user
271
- const resolved = parentId
272
- ? { threadId: this.onResolveThread?.(parentId)?.threadId, threadName: undefined }
273
- : this.onResolveActiveThread?.(openId);
274
- await this.handleCommand(openId, messageId, content, resolved?.threadId, resolved?.threadName);
306
+ await this.handleCommand(openId, messageId, content, targetThreadId, undefined, sourceDeviceId, !parentId);
275
307
  }
276
308
  else {
277
309
  console.log(`[FeishuHandler] Handling regular command, msgId=${messageId}`);
278
- // parent_id → resolve thread from card; otherwise check active thread for this user
279
- const resolved = parentId
280
- ? { threadId: this.onResolveThread?.(parentId)?.threadId, threadName: undefined }
281
- : this.onResolveActiveThread?.(openId);
282
- await this.handleRegularCommand(openId, messageId, content, fileReference?.threadId ?? resolved?.threadId, false, resolved?.threadName, attachments, ...(fileReference ? [fileReference] : []));
310
+ await this.handleRegularCommand(openId, messageId, content, targetThreadId, false, undefined, attachments, fileReference, sourceDeviceId, !parentId);
283
311
  console.log(`[FeishuHandler] Finished handling regular command, msgId=${messageId}`);
284
312
  }
285
313
  }
@@ -345,7 +373,7 @@ class FeishuLongConnHandler {
345
373
  /**
346
374
  * Handle command
347
375
  */
348
- async handleCommand(openId, messageId, content, threadId, threadName) {
376
+ async handleCommand(openId, messageId, content, threadId, threadName, sourceDeviceId, useActiveThread = false) {
349
377
  const parts = content.split(/\s+/);
350
378
  const command = parts[0].toLowerCase();
351
379
  switch (command) {
@@ -375,14 +403,14 @@ class FeishuLongConnHandler {
375
403
  default:
376
404
  // Pass through unknown slash commands to the client
377
405
  // This allows users to use their local Claude Code custom commands
378
- await this.handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName);
406
+ await this.handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName, sourceDeviceId, useActiveThread);
379
407
  }
380
408
  }
381
409
  /**
382
410
  * Handle slash command passthrough to client
383
411
  * Passes unknown slash commands to the local Claude Code instance
384
412
  */
385
- async handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName) {
413
+ async handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName, sourceDeviceId, useActiveThread = false) {
386
414
  try {
387
415
  // Find user binding
388
416
  const binding = await this.bindingManager.getUserBinding(openId);
@@ -390,8 +418,10 @@ class FeishuLongConnHandler {
390
418
  await this.replyToMessage(messageId, '❌ You have not bound a device yet, please send /bind <binding-code> to bind first');
391
419
  return;
392
420
  }
393
- // Get active device
394
- const activeDevice = await this.bindingManager.getActiveDevice(openId);
421
+ // Resolve the destination and selection together.
422
+ const activeDevice = sourceDeviceId
423
+ ? binding.devices.find((device) => device.deviceId === sourceDeviceId)
424
+ : await this.bindingManager.getActiveDevice(openId);
395
425
  if (!activeDevice) {
396
426
  await this.replyToMessage(messageId, '❌ No active device found. Please use /device list to view your devices');
397
427
  return;
@@ -406,14 +436,39 @@ class FeishuLongConnHandler {
406
436
  await this.replyToMessage(messageId, `❌ Device ${activeDevice.deviceName} is currently offline, please ensure the device is started and connected to the server`);
407
437
  return;
408
438
  }
439
+ if (useActiveThread && (content.trim() === '/thread' || content.trim() === '/thread list')
440
+ && await this.onRecoverThreads?.(openId, activeDevice.deviceId, messageId))
441
+ return;
442
+ if (useActiveThread) {
443
+ try {
444
+ const selected = await this.onResolveActiveThread?.(openId, activeDevice.deviceId);
445
+ threadId = selected?.threadId;
446
+ threadName = selected?.threadName;
447
+ }
448
+ catch (error) {
449
+ if (error instanceof Error && error.message.startsWith('Saved thread selection is invalid')) {
450
+ await this.replyToMessage(messageId, `❌ ${error.message}`);
451
+ return;
452
+ }
453
+ throw error;
454
+ }
455
+ }
456
+ const selectionFence = this.onCaptureSelection?.(openId, activeDevice.deviceId);
409
457
  console.log(`[FeishuHandler] Passing through slash command: ${command}${threadId ? ` (threadId=${threadId})` : ''}`);
410
458
  // Generate message ID first
411
459
  const commandMessageId = (0, uuid_1.v4)();
412
460
  // Register streaming session BEFORE sending command
413
461
  const feishuMessageId = await this.sendStreamingStart(openId, `🤔 Executing ${command}...`, threadName);
462
+ const currentBinding = await this.bindingManager.getUserBinding(openId);
463
+ if (!currentBinding?.devices.some((device) => device.deviceId === activeDevice.deviceId)) {
464
+ throw new Error('Device ownership changed before the command could be sent.');
465
+ }
466
+ if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
467
+ throw new Error('This command was superseded or the device changed before it could be sent.');
468
+ }
414
469
  console.log(`[FeishuHandler] Created card ${feishuMessageId} for slash command ${commandMessageId}`);
415
470
  if (this.onStartStreaming) {
416
- this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, false, undefined, threadName);
471
+ this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, false, undefined, threadName, selectionFence);
417
472
  }
418
473
  // Send slash command to device - the client will execute it locally
419
474
  const success = await this.connectionHub.sendToDevice(activeDevice.deviceId, {
@@ -595,6 +650,7 @@ class FeishuLongConnHandler {
595
650
  await this.replyToMessage(messageId, `❌ Device "${identifier}" not found. Use /device to see available devices and their indices.`);
596
651
  return;
597
652
  }
653
+ this.onDeviceSwitchIntent?.(openId, deviceId);
598
654
  const result = await this.bindingManager.switchActiveDevice(openId, deviceId);
599
655
  if (!result) {
600
656
  await this.replyToMessage(messageId, '❌ Device switch failed');
@@ -606,7 +662,7 @@ class FeishuLongConnHandler {
606
662
  return;
607
663
  }
608
664
  // Notify RouterServer to clear stale thread state for the old device
609
- this.onDeviceSwitch?.(openId, oldDeviceId);
665
+ this.onDeviceSwitch?.(openId, oldDeviceId, deviceId);
610
666
  await this.replyToMessage(messageId, `✅ Switched to device: **${device.deviceName}**\n\nDevice ID: \`${device.deviceId}\``);
611
667
  }
612
668
  catch (error) {
@@ -718,7 +774,7 @@ Examples:
718
774
  /**
719
775
  * Handle regular command (non-slash commands)
720
776
  */
721
- async handleRegularCommand(openId, messageId, content, threadId, pendingNewThread = false, threadName, attachments, fileReference) {
777
+ async handleRegularCommand(openId, messageId, content, threadId, pendingNewThread = false, threadName, attachments, fileReference, sourceDeviceId, useActiveThread = false, selectionIntent) {
722
778
  try {
723
779
  // Find user binding
724
780
  const binding = await this.bindingManager.getUserBinding(openId);
@@ -727,8 +783,9 @@ Examples:
727
783
  return;
728
784
  }
729
785
  // Get active device
730
- const activeDevice = fileReference
731
- ? (await this.bindingManager.getUserDevices(openId)).find(device => device.deviceId === fileReference.deviceId)
786
+ const destinationDeviceId = fileReference?.deviceId ?? sourceDeviceId;
787
+ const activeDevice = destinationDeviceId
788
+ ? binding.devices.find((device) => device.deviceId === destinationDeviceId)
732
789
  : await this.bindingManager.getActiveDevice(openId);
733
790
  if (!activeDevice) {
734
791
  await this.replyToMessage(messageId, '❌ No active device found. Please use /device list to view your devices');
@@ -744,15 +801,40 @@ Examples:
744
801
  await this.replyToMessage(messageId, `❌ Device ${activeDevice.deviceName} is currently offline, please ensure the device is started and connected to the server`);
745
802
  return;
746
803
  }
804
+ if (useActiveThread) {
805
+ try {
806
+ const selected = await this.onResolveActiveThread?.(openId, activeDevice.deviceId);
807
+ threadId = selected?.threadId;
808
+ threadName = selected?.threadName;
809
+ }
810
+ catch (error) {
811
+ if (error instanceof Error && error.message.startsWith('Saved thread selection is invalid')) {
812
+ if (useActiveThread && (content.trim() === '/thread' || content.trim() === '/thread list')
813
+ && await this.onRecoverThreads?.(openId, activeDevice.deviceId, messageId))
814
+ return;
815
+ await this.replyToMessage(messageId, `❌ ${error.message}`);
816
+ return;
817
+ }
818
+ throw error;
819
+ }
820
+ }
821
+ const selectionFence = selectionIntent ?? this.onCaptureSelection?.(openId, activeDevice.deviceId);
747
822
  // Generate message ID first
748
823
  const commandMessageId = (0, uuid_1.v4)();
749
824
  console.log(`[FeishuHandler] Creating streaming card for command ${commandMessageId}${threadId ? ` (threadId=${threadId})` : ''}${pendingNewThread ? ' (pendingNewThread)' : ''}`);
750
825
  // Register streaming session BEFORE sending command to avoid race condition
751
826
  // where stream chunks arrive before registration
752
827
  const feishuMessageId = await this.sendStreamingStart(openId, attachments ? '🖼️ Processing image...' : '🤔 Processing...', threadName);
828
+ const currentBinding = await this.bindingManager.getUserBinding(openId);
829
+ if (!currentBinding?.devices.some((device) => device.deviceId === activeDevice.deviceId)) {
830
+ throw new Error('Device ownership changed before the command could be sent.');
831
+ }
832
+ if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
833
+ throw new Error('This command was superseded or the device changed before it could be sent.');
834
+ }
753
835
  console.log(`[FeishuHandler] Created card ${feishuMessageId} for command ${commandMessageId}`);
754
836
  if (this.onStartStreaming) {
755
- this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, pendingNewThread, undefined, threadName);
837
+ this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, pendingNewThread, undefined, threadName, selectionFence);
756
838
  }
757
839
  // Send command to device
758
840
  const success = await this.connectionHub.sendToDevice(activeDevice.deviceId, {
@@ -1518,8 +1600,14 @@ Examples:
1518
1600
  // Append thread switch buttons when at least one thread exists
1519
1601
  let threadSwitchElements = [];
1520
1602
  // The reply's owner and the destination of new messages are independent.
1521
- const activeThreadId = (openId ? this.onResolveActiveThread?.(openId)?.threadId : undefined)
1522
- ?? threads?.find(thread => thread.name === 'default')?.id;
1603
+ let activeThreadId;
1604
+ try {
1605
+ const activeDevice = openId ? await this.bindingManager.getActiveDevice(openId) : null;
1606
+ const selected = openId && activeDevice ? await this.onResolveActiveThread?.(openId, activeDevice.deviceId) : undefined;
1607
+ activeThreadId = selected?.threadId;
1608
+ }
1609
+ catch { /* Invalid preferences are handled at command admission, not by failing a response card. */ }
1610
+ activeThreadId ??= threads?.find(thread => thread.name === 'default')?.id;
1523
1611
  const replyThread = threads?.find(thread => thread.id === replyThreadId);
1524
1612
  const replyThreadName = threadName ?? replyThread?.name;
1525
1613
  const replyWorkspace = cwd ? path.posix.basename(cwd.replace(/\\/g, '/')) || cwd : replyThread?.workspaceName;
@@ -1835,24 +1923,29 @@ Examples:
1835
1923
  }
1836
1924
  if (parsed.action === 'switch_thread' && parsed.threadId) {
1837
1925
  const openMessageId = data?.context?.open_message_id;
1926
+ if (typeof openMessageId !== 'string')
1927
+ return { toast: { type: 'error', content: 'This thread card has expired. Run /thread list for a fresh card.' } };
1838
1928
  try {
1839
- await this.onCardSwitchThread?.(openId, parsed.threadId, parsed.threadName ?? parsed.threadId);
1840
- if (openMessageId) {
1841
- this.refreshThreadSwitchButtons(openMessageId, parsed.threadId).catch((err) => console.error('[FeishuLongConnHandler] Failed to refresh thread switch buttons:', err));
1842
- }
1929
+ await this.onCardSwitchThread?.(openId, openMessageId, parsed.threadId, parsed.threadName ?? parsed.threadId);
1930
+ this.refreshThreadSwitchButtons(openMessageId, parsed.threadId).catch((err) => console.error('[FeishuLongConnHandler] Failed to refresh thread switch buttons:', err));
1843
1931
  return { toast: { type: 'success', content: `Switched to: ${parsed.threadName ?? parsed.threadId}` } };
1844
1932
  }
1845
1933
  catch (error) {
1846
1934
  console.error('[FeishuLongConnHandler] Card action switch_thread failed:', error);
1935
+ return { toast: { type: 'error', content: error instanceof Error ? error.message : 'Thread selection failed.' } };
1847
1936
  }
1848
1937
  }
1849
1938
  if (parsed.action === 'new_thread') {
1939
+ const openMessageId = data?.context?.open_message_id;
1940
+ if (typeof openMessageId !== 'string')
1941
+ return { toast: { type: 'error', content: 'This thread card has expired. Run /thread list for a fresh card.' } };
1850
1942
  try {
1851
- await this.onCardNewThread?.(openId);
1943
+ await this.onCardNewThread?.(openId, openMessageId);
1852
1944
  return { toast: { type: 'info', content: 'Creating new thread...' } };
1853
1945
  }
1854
1946
  catch (error) {
1855
1947
  console.error('[FeishuLongConnHandler] Card action new_thread failed:', error);
1948
+ return { toast: { type: 'error', content: error instanceof Error ? error.message : 'Could not create a thread.' } };
1856
1949
  }
1857
1950
  }
1858
1951
  if ((parsed.action === 'queue_confirm' || parsed.action === 'queue_cancel') && parsed.queueId && parsed.threadId) {
@@ -1873,11 +1966,11 @@ Examples:
1873
1966
  * Send a command triggered by a card button action (no real Feishu messageId).
1874
1967
  * Reuses handleRegularCommand flow: creates streaming card, sends command to device.
1875
1968
  */
1876
- async sendCommandFromCardAction(openId, content, pendingNewThread = false) {
1969
+ async sendCommandFromCardAction(openId, content, pendingNewThread = false, sourceDeviceId, selectionIntent) {
1877
1970
  // Generate a synthetic message ID — card actions don't have a Feishu message to reply to,
1878
1971
  // so error replies fall back to sendMessage (plain text, not threaded).
1879
1972
  const syntheticMessageId = (0, uuid_1.v4)();
1880
- await this.handleRegularCommand(openId, syntheticMessageId, content, undefined, pendingNewThread);
1973
+ await this.handleRegularCommand(openId, syntheticMessageId, content, undefined, pendingNewThread, undefined, undefined, undefined, sourceDeviceId, false, selectionIntent);
1881
1974
  }
1882
1975
  /** Register confirmed work; capable clients request a card when execution starts. */
1883
1976
  async sendQueueActionFromCardAction(openId, action, queueId, threadId, cardMessageId) {