@yu_robotics/remote-cli-router 1.6.267 → 1.6.269

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.
@@ -48,6 +48,7 @@ const fs = __importStar(require("fs"));
48
48
  const os = __importStar(require("os"));
49
49
  const path = __importStar(require("path"));
50
50
  const crypto_1 = require("crypto");
51
+ const CommandMenu_1 = require("./CommandMenu");
51
52
  const CardTables_1 = require("../utils/CardTables");
52
53
  function escapeCardText(value) {
53
54
  return String(value ?? '')
@@ -107,6 +108,7 @@ class FeishuLongConnHandler {
107
108
  // Pattern to match tool use separator lines
108
109
  TOOL_USE_PATTERN = /─+ TOOL USE ─+/;
109
110
  TOOL_SEPARATOR_PATTERN = /─{20,}/;
111
+ commandMenus = new Map();
110
112
  constructor(config) {
111
113
  this.appId = config.appId;
112
114
  this.appSecret = config.appSecret;
@@ -399,9 +401,18 @@ class FeishuLongConnHandler {
399
401
  * Handle command
400
402
  */
401
403
  async handleCommand(openId, messageId, content, threadId, threadName, sourceDeviceId, useActiveThread = false) {
402
- const parts = content.split(/\s+/);
404
+ const parts = content.trim().split(/\s+/);
403
405
  const command = parts[0].toLowerCase();
404
406
  switch (command) {
407
+ case '/skills':
408
+ if (parts.length === 1) {
409
+ await this.openCommandMenu(openId, messageId, threadId, threadName, sourceDeviceId, useActiveThread);
410
+ break;
411
+ }
412
+ if (content.trim() === '/skills list')
413
+ content = '/skills';
414
+ await this.handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName, sourceDeviceId, useActiveThread);
415
+ break;
405
416
  case '/bind':
406
417
  if (parts.length >= 2) {
407
418
  await this.handleBindCommand(openId, messageId, parts[1]);
@@ -435,7 +446,7 @@ class FeishuLongConnHandler {
435
446
  * Handle slash command passthrough to client
436
447
  * Passes unknown slash commands to the local Claude Code instance
437
448
  */
438
- async handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName, sourceDeviceId, useActiveThread = false) {
449
+ async handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName, sourceDeviceId, useActiveThread = false, originalFence) {
439
450
  try {
440
451
  // Find user binding
441
452
  const binding = await this.bindingManager.getUserBinding(openId);
@@ -478,7 +489,11 @@ class FeishuLongConnHandler {
478
489
  throw error;
479
490
  }
480
491
  }
481
- const selectionFence = this.onCaptureSelection?.(openId, activeDevice.deviceId);
492
+ const selectionFence = originalFence ?? this.onCaptureSelection?.(openId, activeDevice.deviceId);
493
+ if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
494
+ await this.replyToMessage(messageId, 'The device or thread selection changed. Reopen /skills.');
495
+ return;
496
+ }
482
497
  console.log(`[FeishuHandler] Passing through slash command: ${command}${threadId ? ` (threadId=${threadId})` : ''}`);
483
498
  // Generate message ID first
484
499
  const commandMessageId = (0, uuid_1.v4)();
@@ -671,7 +686,7 @@ class FeishuLongConnHandler {
671
686
  * Handle /device switch <device-id-or-index>
672
687
  * Also handles quick switch: /device <device-id-or-index>
673
688
  */
674
- async handleDeviceSwitch(openId, messageId, identifier, binding) {
689
+ async handleDeviceSwitch(openId, messageId, identifier, binding, expectedEpoch) {
675
690
  try {
676
691
  // Get binding if not provided
677
692
  const userBinding = binding || await this.bindingManager.getUserBinding(openId);
@@ -682,13 +697,17 @@ class FeishuLongConnHandler {
682
697
  // Capture old device ID before switching so we can clear stale thread state
683
698
  const oldDeviceId = userBinding.activeDeviceId;
684
699
  // Resolve identifier to device ID
685
- const deviceId = this.resolveDeviceIdentifier(identifier, userBinding);
700
+ const deviceId = expectedEpoch !== undefined ? identifier
701
+ : this.resolveDeviceIdentifier(identifier, userBinding);
686
702
  if (!deviceId) {
687
703
  await this.replyToMessage(messageId, `❌ Device "${identifier}" not found. Use /device to see available devices and their indices.`);
688
704
  return;
689
705
  }
690
- this.onDeviceSwitchIntent?.(openId, deviceId);
691
- const result = await this.bindingManager.switchActiveDevice(openId, deviceId);
706
+ const beginSwitch = () => this.onDeviceSwitchIntent?.(openId, deviceId);
707
+ if (expectedEpoch === undefined)
708
+ beginSwitch();
709
+ const result = expectedEpoch === undefined ? await this.bindingManager.switchActiveDevice(openId, deviceId)
710
+ : await this.bindingManager.switchActiveDevice(openId, deviceId, expectedEpoch, beginSwitch);
692
711
  if (!result) {
693
712
  await this.replyToMessage(messageId, '❌ Device switch failed');
694
713
  return;
@@ -700,7 +719,8 @@ class FeishuLongConnHandler {
700
719
  }
701
720
  // Notify RouterServer to clear stale thread state for the old device
702
721
  await this.onDeviceSwitch?.(openId, oldDeviceId, deviceId);
703
- await this.replyToMessage(messageId, `✅ Switched to device: **${device.deviceName}**\n\nDevice ID: \`${device.deviceId}\``);
722
+ await this.replyToMessage(messageId, `✅ Switched to device: **${device.deviceName}**\n\nDevice ID: \`${device.deviceId}\`` +
723
+ (expectedEpoch === undefined ? '' : '\nOpen /skills for this device.'));
704
724
  }
705
725
  catch (error) {
706
726
  console.error('Error switching device:', error);
@@ -710,7 +730,7 @@ class FeishuLongConnHandler {
710
730
  /**
711
731
  * Handle /device unbind <device-id-or-index>
712
732
  */
713
- async handleDeviceUnbind(openId, messageId, identifier, binding) {
733
+ async handleDeviceUnbind(openId, messageId, identifier, binding, expectedEpoch) {
714
734
  try {
715
735
  // Get binding if not provided
716
736
  const userBinding = binding || await this.bindingManager.getUserBinding(openId);
@@ -719,7 +739,8 @@ class FeishuLongConnHandler {
719
739
  return;
720
740
  }
721
741
  // Resolve identifier to device ID
722
- const deviceId = this.resolveDeviceIdentifier(identifier, userBinding);
742
+ const deviceId = expectedEpoch !== undefined ? identifier
743
+ : this.resolveDeviceIdentifier(identifier, userBinding);
723
744
  if (!deviceId) {
724
745
  await this.replyToMessage(messageId, `❌ Device "${identifier}" not found. Use /device to see available devices and their indices.`);
725
746
  return;
@@ -730,12 +751,16 @@ class FeishuLongConnHandler {
730
751
  return;
731
752
  }
732
753
  const wasActive = device.isActive;
733
- const result = await this.bindingManager.unbindDevice(openId, deviceId, async (id) => { await this.onRevokeDevice?.(id); });
754
+ const revoke = async (id) => { await this.onRevokeDevice?.(id); };
755
+ const result = expectedEpoch === undefined ? await this.bindingManager.unbindDevice(openId, deviceId, revoke)
756
+ : await this.bindingManager.unbindDevice(openId, deviceId, revoke, expectedEpoch);
734
757
  if (!result) {
735
758
  await this.replyToMessage(messageId, '❌ Failed to unbind device');
736
759
  return;
737
760
  }
738
761
  let responseMessage = `✅ Device **${device.deviceName}** has been unbound`;
762
+ if (expectedEpoch !== undefined)
763
+ responseMessage += '\nOpen /skills for a fresh device menu.';
739
764
  // If we unbound the active device, inform about the new active device
740
765
  if (wasActive) {
741
766
  const newActiveDevice = await this.bindingManager.getActiveDevice(openId);
@@ -756,6 +781,81 @@ class FeishuLongConnHandler {
756
781
  /**
757
782
  * Handle help command
758
783
  */
784
+ async openCommandMenu(openId, messageId, threadId, threadName, sourceDeviceId, topLevel = true, eventId) {
785
+ try {
786
+ const devices = await this.bindingManager.getUserDevices(openId);
787
+ const device = sourceDeviceId
788
+ ? devices.find(candidate => candidate.deviceId === sourceDeviceId)
789
+ : await this.bindingManager.getActiveDevice(openId);
790
+ if (sourceDeviceId && !device)
791
+ throw new Error('Device binding expired.');
792
+ const deviceId = device?.deviceId;
793
+ const fence = deviceId ? this.onCaptureSelection?.(openId, deviceId) : undefined;
794
+ if (topLevel && deviceId) {
795
+ const selected = await this.onResolveActiveThread?.(openId, deviceId);
796
+ threadId = selected?.threadId;
797
+ threadName = selected?.threadName;
798
+ }
799
+ const deviceEpochs = new Map(devices.map(item => [item.deviceId, this.bindingManager.getCardThreadEpoch(openId, item.deviceId)]));
800
+ const menu = new CommandMenu_1.CommandMenu(device ? device.deviceName + ' / ' + (threadName || threadId || 'default') : 'No device bound', devices);
801
+ const result = await this.client.im.message.create({ params: { receive_id_type: 'open_id' },
802
+ data: { receive_id: openId, msg_type: 'interactive', uuid: eventId || messageId
803
+ ? (0, crypto_1.createHash)('sha256').update(JSON.stringify([openId, eventId || messageId])).digest('hex').slice(0, 40) : (0, uuid_1.v4)(),
804
+ content: JSON.stringify({ schema: '2.0', header: CommandMenu_1.commandMenuHeader, body: { elements: menu.render() } }) } });
805
+ const cardId = result?.data?.message_id;
806
+ if (result.code || !cardId)
807
+ throw new Error('Menu delivery failed.');
808
+ if (this.commandMenus.has(cardId))
809
+ return;
810
+ if (this.commandMenus.size >= 1000)
811
+ this.commandMenus.delete(this.commandMenus.keys().next().value);
812
+ this.commandMenus.set(cardId, { openId, deviceId, threadId, threadName, fence, menu, topLevel, deviceEpochs, expires: Date.now() + 3_600_000 });
813
+ }
814
+ catch {
815
+ const fallback = 'Could not open the command menu. Use /help for commands or /skills list for backend skills.';
816
+ if (messageId)
817
+ await this.replyToMessage(messageId, fallback);
818
+ else
819
+ await this.sendMessage(openId, fallback);
820
+ }
821
+ }
822
+ async clickCommandMenu(openId, cardId, action, form) {
823
+ const state = this.commandMenus.get(cardId);
824
+ if (!state || state.openId !== openId || state.expires <= Date.now())
825
+ throw new Error('Reopen /skills for a fresh menu.');
826
+ return state.menu.click(action, form, async (elements) => {
827
+ const result = await this.client.im.message.patch({ path: { message_id: cardId },
828
+ data: { content: JSON.stringify({ schema: '2.0', header: CommandMenu_1.commandMenuHeader, body: { elements } }) } });
829
+ if (result.code)
830
+ throw new Error('Menu update failed.');
831
+ }, async (content) => {
832
+ const [command, operation, target] = content.split(/\s+/);
833
+ if (state.fence && !this.onValidateSelection?.(state.fence))
834
+ throw new Error('Selection changed. Reopen /skills.');
835
+ if (command === '/device' && (operation === 'switch' || operation === 'unbind')) {
836
+ const binding = await this.bindingManager.getUserBinding(openId);
837
+ const epoch = state.deviceEpochs.get(target);
838
+ if (!binding || !epoch || this.bindingManager.getCardThreadEpoch(openId, target) !== epoch
839
+ || !binding.devices.some(device => device.deviceId === target))
840
+ throw new Error('Device binding changed. Reopen /skills.');
841
+ if (operation === 'switch')
842
+ await this.handleDeviceSwitch(openId, cardId, target, binding, epoch);
843
+ else
844
+ await this.handleDeviceUnbind(openId, cardId, target, binding, epoch);
845
+ return;
846
+ }
847
+ if (['/bind', '/device', '/unbind', '/tips', '/help'].includes(command)) {
848
+ await this.handleCommand(openId, cardId, content);
849
+ return;
850
+ }
851
+ if (!state.deviceId)
852
+ throw new Error('Bind a device and reopen /skills.');
853
+ if (command === '/thread' && content === '/thread list' && state.topLevel
854
+ && await this.onRecoverThreads?.(openId, state.deviceId, cardId, state.fence))
855
+ return;
856
+ await this.handleSlashCommandPassthrough(openId, cardId, content, command, state.threadId, state.threadName, state.deviceId, false, state.fence);
857
+ });
858
+ }
759
859
  async handleHelpCommand(openId, messageId) {
760
860
  const helpMessage = `📖 Feishu Remote Control Help
761
861
 
@@ -775,7 +875,8 @@ Backend and session commands (sent to active device):
775
875
  /clear - Clear conversation context and start fresh session
776
876
  /status - Show backend, model, effort, queue, and thread status
777
877
  /context - Show current session context and queue diagnostics
778
- /skills - List available skills for the active backend
878
+ /skills - Open the interactive command menu
879
+ /skills list - List installed skills for the active backend
779
880
  /abort - Abort the currently executing command
780
881
  /queue - Inspect or manage confirmed messages for busy threads
781
882
  /schedule - Manage one-shot and cron tasks in this thread. Use /schedule help for commands.
@@ -2018,6 +2119,29 @@ Examples:
2018
2119
  if (!parsed || typeof parsed !== 'object')
2019
2120
  return;
2020
2121
  this.recordUserActivity(openId);
2122
+ if (parsed.action === 'command_menu') {
2123
+ const click = this.clickCommandMenu(openId, data.context?.open_message_id, parsed, data.action.form_value)
2124
+ .then(content => ({ type: 'info', content }), error => ({
2125
+ type: 'error', content: error instanceof Error ? error.message : 'Reopen /skills.',
2126
+ }));
2127
+ // Feishu requires an acknowledgement within three seconds, including network time.
2128
+ let timer;
2129
+ try {
2130
+ const toast = await Promise.race([click, new Promise(resolve => {
2131
+ timer = setTimeout(() => resolve(undefined), 1200);
2132
+ })]);
2133
+ if (toast)
2134
+ return { toast };
2135
+ void click.then(result => {
2136
+ if (result.type === 'error')
2137
+ return this.sendMessage(openId, result.content);
2138
+ }).catch(() => { });
2139
+ return { toast: { type: 'info', content: 'Processing your selection.' } };
2140
+ }
2141
+ finally {
2142
+ clearTimeout(timer);
2143
+ }
2144
+ }
2021
2145
  if (parsed.action === 'automatic_file_enrollment') {
2022
2146
  const cardId = data?.context?.open_message_id;
2023
2147
  if (typeof cardId !== 'string' || !this.onAutomaticFileEnrollment)
@@ -2318,6 +2442,12 @@ Examples:
2318
2442
  'card.action.trigger': async (data) => {
2319
2443
  return this.handleCardAction(data);
2320
2444
  },
2445
+ 'application.bot.menu_v6': async (data) => {
2446
+ const openId = data.operator?.operator_id?.open_id;
2447
+ if (openId && (data.event_key === 'skills' || data.event_key === '/skills')) {
2448
+ await this.openCommandMenu(openId, undefined, undefined, undefined, undefined, true, data.event_id || data.uuid);
2449
+ }
2450
+ },
2321
2451
  })
2322
2452
  });
2323
2453
  console.log('✅ Feishu WebSocket long connection established');