@xmanrui/dsh-im 5.10.0 → 5.11.0

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 (114) hide show
  1. package/README.en.md +39 -5
  2. package/README.md +42 -5
  3. package/bin/dsh-im.mjs +65 -0
  4. package/docs/client-integration.md +4 -0
  5. package/lib/client.js +1202 -95
  6. package/lib/index.js +365 -339
  7. package/package.json +7 -6
  8. package/plugin-src/client/access-policy-settings.js +210 -12
  9. package/plugin-src/client/bot-general-settings.js +44 -3
  10. package/plugin-src/client/i18n-ru.js +85 -0
  11. package/plugin-src/client/i18n.js +83 -0
  12. package/plugin-src/client/im-channels.js +419 -0
  13. package/plugin-src/client/index.js +33 -1
  14. package/plugin-src/client/styles.js +7 -7
  15. package/plugin-src/client/update-panel.js +2 -1
  16. package/plugin-src/host/channel-list-rpc.mjs +280 -0
  17. package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
  18. package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
  19. package/plugin-src/host/channels/feishu/production.mjs +39 -10
  20. package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
  21. package/plugin-src/host/channels/matrix/production.mjs +28 -10
  22. package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
  23. package/plugin-src/host/channels/qq/production.mjs +30 -11
  24. package/plugin-src/host/channels/qq/rpc.mjs +10 -1
  25. package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
  26. package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
  27. package/plugin-src/host/channels/shared/production.mjs +14 -1
  28. package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
  29. package/plugin-src/host/channels/shared/rpc.mjs +9 -0
  30. package/plugin-src/host/channels/slack/production.mjs +28 -10
  31. package/plugin-src/host/channels/slack/rpc.mjs +10 -0
  32. package/plugin-src/host/channels/telegram/production.mjs +5 -0
  33. package/plugin-src/host/channels/wecom/production.mjs +28 -10
  34. package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
  35. package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
  36. package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
  37. package/plugin-src/host/channels/weixin/production.mjs +28 -10
  38. package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
  39. package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
  40. package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
  41. package/plugin-src/host/delivery-service.mjs +3 -4
  42. package/plugin-src/host/delivery-suggestions.mjs +3 -1
  43. package/plugin-src/host/harness-connection.mjs +2 -1
  44. package/plugin-src/host/harness-peer.mjs +3 -1
  45. package/plugin-src/host/index.mjs +8 -1
  46. package/plugin-src/host/modern-harness-api.mjs +5 -1
  47. package/plugin-src/host/root-scope.mjs +32 -0
  48. package/plugin-src/host/session-sync-coordinator.mjs +2 -1
  49. package/plugin-src/management-rpc.mjs +18 -2
  50. package/scripts/verify-package.mjs +36 -7
  51. package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
  52. package/src/channels/dingtalk/state-store.mjs +56 -0
  53. package/src/channels/discord/discord-api.mjs +2 -1
  54. package/src/channels/feishu/bridge.mjs +154 -58
  55. package/src/channels/feishu/feishu-cards.mjs +10 -4
  56. package/src/channels/feishu/feishu-runtime.mjs +11 -3
  57. package/src/channels/feishu/message-utils.mjs +106 -30
  58. package/src/channels/feishu/slash-command-panel.mjs +26 -0
  59. package/src/channels/feishu/state-store.mjs +14 -0
  60. package/src/channels/matrix/matrix-api.mjs +2 -1
  61. package/src/channels/qq/qq-bridge.mjs +105 -14
  62. package/src/channels/qq/state-store.mjs +13 -1
  63. package/src/channels/shared/access-policy.mjs +60 -7
  64. package/src/channels/shared/bot-workspace-store.mjs +155 -3
  65. package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
  66. package/src/channels/shared/channel-capabilities.mjs +44 -0
  67. package/src/channels/shared/command-catalog.mjs +68 -3
  68. package/src/channels/shared/command-permission.mjs +6 -2
  69. package/src/channels/shared/conversation-state-store.mjs +16 -0
  70. package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
  71. package/src/channels/shared/deferred-delivery.mjs +4 -0
  72. package/src/channels/shared/diagnostic-details.mjs +6 -1
  73. package/src/channels/shared/failure-log-file.mjs +79 -0
  74. package/src/channels/shared/harness-client.mjs +111 -6
  75. package/src/channels/shared/i18n-en/feishu.mjs +2 -2
  76. package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
  77. package/src/channels/shared/i18n-en/shared-b.mjs +67 -4
  78. package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
  79. package/src/channels/shared/i18n-en/weixin.mjs +4 -0
  80. package/src/channels/shared/i18n-en.mjs +2 -0
  81. package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
  82. package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
  83. package/src/channels/shared/i18n-ru/shared-b.mjs +67 -4
  84. package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
  85. package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
  86. package/src/channels/shared/i18n-ru.mjs +2 -0
  87. package/src/channels/shared/inbound-access.mjs +10 -0
  88. package/src/channels/shared/markdown-chunks.mjs +5 -0
  89. package/src/channels/shared/message-failure.mjs +22 -1
  90. package/src/channels/shared/new-command.mjs +158 -4
  91. package/src/channels/shared/plan-goal-command.mjs +132 -0
  92. package/src/channels/shared/qrcode.mjs +5 -0
  93. package/src/channels/shared/reply-content.mjs +102 -0
  94. package/src/channels/shared/reset-command.mjs +46 -0
  95. package/src/channels/shared/semantic/artifact.mjs +133 -29
  96. package/src/channels/shared/semantic/reply-reference.mjs +18 -3
  97. package/src/channels/shared/session-nav-command.mjs +999 -0
  98. package/src/channels/shared/session-ring-support.mjs +184 -0
  99. package/src/channels/shared/session-ring.mjs +202 -0
  100. package/src/channels/shared/session-title.mjs +11 -0
  101. package/src/channels/shared/status-command.mjs +2 -1
  102. package/src/channels/shared/text-harness-bridge.mjs +166 -7
  103. package/src/channels/shared/workspace-command.mjs +567 -31
  104. package/src/channels/shared/workspace-session.mjs +39 -3
  105. package/src/channels/slack/slack-api.mjs +2 -1
  106. package/src/channels/telegram/config-store.mjs +10 -2
  107. package/src/channels/telegram/telegram-rich-message.mjs +17 -5
  108. package/src/channels/telegram/telegram-runtime.mjs +14 -1
  109. package/src/channels/wecom/state-store.mjs +13 -1
  110. package/src/channels/wecom/wecom-bridge.mjs +183 -26
  111. package/src/channels/wecom-app/state-store.mjs +13 -1
  112. package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
  113. package/src/channels/weixin/state-store.mjs +13 -1
  114. package/src/channels/weixin/weixin-bridge.mjs +71 -4
@@ -484,6 +484,48 @@ function feishuReplyAttachments(messageType, parsed, post) {
484
484
  return [];
485
485
  }
486
486
 
487
+ /**
488
+ * A card can reach the bot in two shapes:
489
+ * - a quoted card, whose payload is re-read when the reply is resolved;
490
+ * - an inbound `interactive` event, whose `message.content` carries only the
491
+ * card header title (`⚙️ 任务过程`) while the body stays behind the same
492
+ * `im.v1.message.get` call.
493
+ * Reading with `card_msg_content_type: raw_card_content` yields the full card
494
+ * for both, so the two paths share one implementation.
495
+ */
496
+ async function loadCardMessage(messageId, client, { signal } = {}) {
497
+ signal?.throwIfAborted();
498
+ let response;
499
+ try {
500
+ response = await client?.im?.v1?.message?.get?.({
501
+ path: { message_id: messageId },
502
+ params: {
503
+ with_sender_name: true,
504
+ card_msg_content_type: FEISHU_CARD_MESSAGE_CONTENT_TYPE,
505
+ },
506
+ });
507
+ } catch (error) {
508
+ signal?.throwIfAborted();
509
+ if (await feishuProviderCode(error, signal) === FEISHU_MISSING_MESSAGE_SCOPE_CODE) {
510
+ return { unavailableReason: 'permission-denied' };
511
+ }
512
+ throw error;
513
+ }
514
+ signal?.throwIfAborted();
515
+ if (providerCode(response) === FEISHU_MISSING_MESSAGE_SCOPE_CODE) {
516
+ return { unavailableReason: 'permission-denied' };
517
+ }
518
+ if (providerCode(response) !== null && providerCode(response) !== 0) {
519
+ return { unavailableReason: 'not-delivered' };
520
+ }
521
+ const item = response?.data?.items?.find?.(
522
+ (candidate) => nonEmptyString(candidate?.message_id) === messageId,
523
+ );
524
+ if (!item) return { unavailableReason: 'not-found' };
525
+ if (item.deleted) return { unavailableReason: 'deleted' };
526
+ return { item, messageType: nonEmptyString(item.msg_type) ?? '' };
527
+ }
528
+
487
529
  function feishuReplyReference(event, client) {
488
530
  const messageId = feishuReplyTargetId(event);
489
531
  if (!messageId) return null;
@@ -491,41 +533,14 @@ function feishuReplyReference(event, client) {
491
533
  return {
492
534
  messageId,
493
535
  async load({ signal } = {}) {
494
- signal?.throwIfAborted();
495
- let response;
496
- try {
497
- response = await client?.im?.v1?.message?.get?.({
498
- path: { message_id: messageId },
499
- params: {
500
- with_sender_name: true,
501
- card_msg_content_type: FEISHU_CARD_MESSAGE_CONTENT_TYPE,
502
- },
503
- });
504
- } catch (error) {
505
- signal?.throwIfAborted();
506
- if (await feishuProviderCode(error, signal) === FEISHU_MISSING_MESSAGE_SCOPE_CODE) {
507
- return { messageId, unavailableReason: 'permission-denied' };
508
- }
509
- throw error;
510
- }
511
- signal?.throwIfAborted();
512
- if (providerCode(response) === FEISHU_MISSING_MESSAGE_SCOPE_CODE) {
513
- return { messageId, unavailableReason: 'permission-denied' };
514
- }
515
- if (providerCode(response) !== null && providerCode(response) !== 0) {
516
- return { messageId, unavailableReason: 'not-delivered' };
517
- }
518
- const item = response?.data?.items?.find?.(
519
- (candidate) => nonEmptyString(candidate?.message_id) === messageId,
520
- );
521
- if (!item) return { messageId, unavailableReason: 'not-found' };
522
- if (item.deleted) return { messageId, unavailableReason: 'deleted' };
536
+ const loaded = await loadCardMessage(messageId, client, { signal });
537
+ if (!loaded.item) return { messageId, unavailableReason: loaded.unavailableReason };
538
+ const { item, messageType } = loaded;
523
539
  const itemChatId = nonEmptyString(item.chat_id);
524
540
  if (!chatId || !itemChatId || itemChatId !== chatId) {
525
541
  return { messageId, unavailableReason: 'not-found' };
526
542
  }
527
543
 
528
- const messageType = nonEmptyString(item.msg_type) ?? '';
529
544
  const quotedEvent = {
530
545
  message: {
531
546
  message_id: messageId,
@@ -558,6 +573,13 @@ function feishuReplyReference(event, client) {
558
573
  };
559
574
  }
560
575
 
576
+ /**
577
+ * Inbound cards need the same second read as quoted ones: the delivered event
578
+ * only carries the card header title, so `content` would be `⚙️ 任务过程`
579
+ * instead of the body. The text parsed from the event stays the synchronous
580
+ * answer, and `card.load()` re-reads the full payload on demand — mirroring
581
+ * how `replyTo.load()` resolves a quoted card.
582
+ */
561
583
  export function extractInboundMessage(event, client) {
562
584
  const messageType = event?.message?.message_type;
563
585
  const parsed = parsedMessageContent(event);
@@ -573,6 +595,26 @@ export function extractInboundMessage(event, client) {
573
595
  // "text, image and file only" notice — even though the same extraction is
574
596
  // already trusted for quoted cards (`feishuReplyReference`).
575
597
  const cardText = messageType === 'interactive' ? interactiveCardText(parsed) : '';
598
+ const messageId = nonEmptyString(event?.message?.message_id);
599
+ const card = messageType === 'interactive' && messageId
600
+ ? {
601
+ messageId,
602
+ async load({ signal } = {}) {
603
+ const loaded = await loadCardMessage(messageId, client, { signal });
604
+ if (!loaded.item) return { messageId, unavailableReason: loaded.unavailableReason };
605
+ return {
606
+ messageId,
607
+ content: interactiveCardText(parsedMessageContent({
608
+ message: {
609
+ message_id: messageId,
610
+ message_type: 'interactive',
611
+ content: loaded.item.body?.content,
612
+ },
613
+ })),
614
+ };
615
+ },
616
+ }
617
+ : null;
576
618
  return {
577
619
  content: messageType === 'text'
578
620
  ? extractText(event) ?? ''
@@ -582,6 +624,7 @@ export function extractInboundMessage(event, client) {
582
624
  images: imageKeys.map((key) => feishuImageSource(event, client, key)),
583
625
  files: file ? [file] : [],
584
626
  ...(replyTo ? { replyTo } : {}),
627
+ ...(card ? { card } : {}),
585
628
  };
586
629
  }
587
630
 
@@ -599,6 +642,39 @@ export function splitText(text, maxChars = 9000) {
599
642
  return chunks;
600
643
  }
601
644
 
645
+ // Feishu cards parse Markdown images into `img` elements whose key must be an
646
+ // uploaded Feishu image key. A local path (macOS `/tmp/x.png`, `~/x.png`,
647
+ // `file:///x.png`, Windows `C:\\x.png`) is not one, and the whole card update is
648
+ // rejected with 230099 / 200570 "card contains invalid image keys" — which
649
+ // silently freezes a step card. Degrade those images to their alt text.
650
+ // Feishu renders an image element only from a hosted URL or an uploaded
651
+ // `img_key`. Everything else — absolute paths, `file:` URLs, Windows drives,
652
+ // bare relative paths such as `06-log/shot.png`, `data:` URIs — reaches the
653
+ // card as an invalid image key: the whole card is rejected and the answer
654
+ // degrades to plain text, so those targets become their alt text instead.
655
+ const REMOTE_IMAGE_TARGET = /^(?:https?:)?\/\//i;
656
+ const FEISHU_IMAGE_KEY = /^img_[A-Za-z0-9_-]+$/;
657
+
658
+ export function isLocalImageTarget(target) {
659
+ if (typeof target !== 'string') return false;
660
+ const trimmed = target.trim();
661
+ if (!trimmed) return false;
662
+ return !REMOTE_IMAGE_TARGET.test(trimmed) && !FEISHU_IMAGE_KEY.test(trimmed);
663
+ }
664
+
665
+ export function stripLocalImageMarkdown(text) {
666
+ if (typeof text !== 'string' || !text.includes('![')) return text;
667
+ return text.replace(/!\[([^\]]*)\]\(([^)\n]*)\)/g, (match, rawAlt, rawTarget) => {
668
+ const target = rawTarget.trim()
669
+ .replace(/\s+"[^"]*"\s*$/, '')
670
+ .trim()
671
+ .replace(/^<(.*)>$/, '$1')
672
+ .trim();
673
+ if (!isLocalImageTarget(target)) return match;
674
+ return rawAlt.trim() || target;
675
+ });
676
+ }
677
+
602
678
  export function isBotSender(event) {
603
679
  return event?.sender?.sender_type === 'bot';
604
680
  }
@@ -27,6 +27,8 @@ export const DEFAULT_SLASH_COMMAND_ICON = 'ai-agent_outlined';
27
27
  export const SLASH_COMMAND_MANIFEST = Object.freeze([
28
28
  { command: 'menu', icon: 'skill_outlined', default: '打开功能菜单', en_us: 'Open the feature menu' },
29
29
  { command: 'new', icon: 'ai-deepthink_outlined', default: '开启全新会话', en_us: 'Start a fresh session' },
30
+ { command: 'fork', icon: 'ai-deepthink_outlined', default: '从当前会话分支一个新会话', en_us: 'Branch a new session from the current one' },
31
+ { command: 'reset', icon: 'ai-deepthink_outlined', default: '重置当前会话上下文(保留会话编号)', en_us: 'Reset the current session context (keep the number)' },
30
32
  { command: 'help', icon: 'promptword_outlined', default: '查看帮助', en_us: 'Show help' },
31
33
  { command: 'status', icon: 'ai-functions_outlined', default: '查看机器人状态', en_us: 'Show bot status' },
32
34
  { command: 'compact', icon: 'ai-block_outlined', default: '压缩当前会话上下文', en_us: 'Compact the current session' },
@@ -41,6 +43,14 @@ export const SLASH_COMMAND_MANIFEST = Object.freeze([
41
43
  { command: 'workspace', icon: 'folder_outlined', default: '查看并切换工作区', en_us: 'View and switch workspace' },
42
44
  { command: 'conv', icon: 'folder_outlined', default: '设置当前对话专属工作区', en_us: 'Set the workspace for this conversation' },
43
45
  { command: 'session', icon: 'chat-ai_outlined', default: '绑定已有会话', en_us: 'Bind an existing session' },
46
+ { command: 'sessionarchive', icon: 'folder_outlined', default: '归档一个会话', en_us: 'Archive a session' },
47
+ { command: 'ls', icon: 'chat-ai_outlined', default: '列出本聊天使用过的会话(按聊天/话题隔离)', en_us: "List this chat's sessions (per chat / per topic)" },
48
+ { command: 'go', icon: 'chat-ai_outlined', default: '切换到指定编号的会话', en_us: 'Switch to a session by number' },
49
+ { command: 'prev', icon: 'chat-ai_outlined', default: '回到上一个会话', en_us: 'Go back to the previous session' },
50
+ { command: 'next', icon: 'chat-ai_outlined', default: '前进到下一个会话', en_us: 'Go forward to the next session' },
51
+ { command: 'drop', icon: 'chat-ai_outlined', default: '从会话列表移除一条记录', en_us: 'Remove one entry from the session list' },
52
+ { command: 'title', icon: 'chat-ai_outlined', default: '查看或重命名会话标题', en_us: 'Show or rename a session title' },
53
+ { command: 'tail', icon: 'chat-ai_outlined', default: '预览或导出会话内容', en_us: 'Preview or export session content' },
44
54
  { command: 'models', icon: 'ai-functions_outlined', default: '列出可用模型', en_us: 'List available models' },
45
55
  { command: 'model', icon: 'ai-agent_outlined', default: '查看或切换当前模型', en_us: 'Show or switch the current model' },
46
56
  { command: 'reasoninglist', icon: 'ai-deepthink_outlined', default: '列出可用推理等级', en_us: 'List available reasoning efforts' },
@@ -153,3 +163,19 @@ export function resolveSlashPanelManifest(config, manifest = SLASH_COMMAND_MANIF
153
163
  const byName = new Map(manifest.map((entry) => [entry.command, entry]));
154
164
  return normalized.order.map((name) => byName.get(name)).filter(Boolean);
155
165
  }
166
+
167
+ /**
168
+ * The manifest a bot should actually register, narrowed by what the Host and
169
+ * channel can do: /fork is dropped when the Host cannot fork, and /tail is
170
+ * described as preview-only when the channel cannot send files.
171
+ */
172
+ export function feishuSlashManifest({ supportsFork = true, fileSend = false } = {}) {
173
+ const entries = SLASH_COMMAND_MANIFEST
174
+ .filter((entry) => entry.command !== 'fork' || supportsFork)
175
+ .map((entry) => (
176
+ entry.command === 'tail' && !fileSend
177
+ ? { ...entry, default: '预览会话内容', en_us: 'Preview session content' }
178
+ : entry
179
+ ));
180
+ return Object.freeze(entries);
181
+ }
@@ -1,4 +1,5 @@
1
1
  import { deferredStateAccess, normalizeDeferredState } from '../shared/deferred-state.mjs';
2
+ import { createSessionRingSupport, normalizePendingTitles, normalizeSessionRings } from '../shared/session-ring-support.mjs';
2
3
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
4
  import { dirname } from 'node:path';
4
5
 
@@ -32,6 +33,12 @@ export class StateStore {
32
33
 
33
34
  constructor(path) {
34
35
  this.#path = path;
36
+ // The navigation ring is a view over this store's state, shared with the
37
+ // channels that inherit `ConversationStateStore`.
38
+ Object.assign(this, createSessionRingSupport({
39
+ state: () => this.#state,
40
+ persist: () => this.#persist(),
41
+ }));
35
42
  }
36
43
 
37
44
  async load() {
@@ -48,6 +55,13 @@ export class StateStore {
48
55
  : false,
49
56
  topics: parsed.topics && typeof parsed.topics === 'object' ? parsed.topics : {},
50
57
  mirrors: parsed.mirrors && typeof parsed.mirrors === 'object' ? parsed.mirrors : {},
58
+ // A state file written before the navigation ring existed loads unchanged.
59
+ ...(Object.keys(normalizeSessionRings(parsed.rings)).length
60
+ ? { rings: normalizeSessionRings(parsed.rings) }
61
+ : {}),
62
+ ...(Object.keys(normalizePendingTitles(parsed.pendingTitles)).length
63
+ ? { pendingTitles: normalizePendingTitles(parsed.pendingTitles) }
64
+ : {}),
51
65
  };
52
66
  } catch (error) {
53
67
  if (error?.code !== 'ENOENT') throw error;
@@ -26,8 +26,9 @@ function abortReason(signal) {
26
26
 
27
27
  function delay(ms, signal) {
28
28
  return new Promise((resolve, reject) => {
29
+ // Deliberately NOT unref'd: a rate-limit backoff is the only thing the caller
30
+ // is waiting for, so the timer must keep the loop alive until it fires.
29
31
  const timer = setTimeout(resolve, Math.min(Math.max(ms, 0), 60_000));
30
- timer.unref?.();
31
32
  const rejectAbort = () => {
32
33
  clearTimeout(timer);
33
34
  reject(abortReason(signal));
@@ -1,10 +1,12 @@
1
1
  import { captureGroupHistory } from '../shared/group-history.mjs';
2
+ import { SESSION_NAV_HELP_LINES } from '../shared/command-catalog.mjs';
2
3
  import { BusyMessageDispatcher, canAutomaticallySteer } from '../shared/busy-message-dispatcher.mjs';
3
4
  import { isPermissionCommand, runPermissionCommand } from '../shared/permission-command.mjs';
4
5
  import { createDeferredDeliveryCoordinator, deferredOutcomeText } from '../shared/deferred-delivery-coordinator.mjs';
5
6
  import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
6
7
  import { runCompactCommand } from '../shared/compact-command.mjs';
7
8
  import { isClearCommand, runClearCommand } from '../shared/clear-command.mjs';
9
+ import { isResetCommand, runResetCommand } from '../shared/reset-command.mjs';
8
10
  import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
9
11
  import {
10
12
  isControlCommand,
@@ -26,6 +28,11 @@ import {
26
28
  runPresetCommand,
27
29
  } from '../shared/preset-command.mjs';
28
30
  import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
31
+ import {
32
+ isSessionNavCommand,
33
+ runSessionNavTextCommand,
34
+ } from '../shared/session-nav-command.mjs';
35
+ import { createConversationSession, isNewCommand, newCommandTitle } from '../shared/new-command.mjs';
29
36
  import {
30
37
  captureContextEnhancement,
31
38
  captureContextEnhancementSource,
@@ -118,8 +125,10 @@ function helpText() {
118
125
  t('/workspacelist 列出工作区绝对路径'),
119
126
  t('/ws、/wsl、/workspaces 工作区命令别名'),
120
127
  t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'),
128
+ t('/sessionlist --all 跨工作区汇总会话(每个工作区默认显示 10 个,可用 --limit N 调整)'),
121
129
  t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'),
122
- t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'),
130
+ t('/session Session ID、当前工作区序号或标题关键词 将当前聊天绑定到指定会话'),
131
+ ...SESSION_NAV_HELP_LINES.map((line) => t(line)),
123
132
  t('/models 按序号列出所有可用模型'),
124
133
  t('/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级'),
125
134
  t('/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级'),
@@ -187,7 +196,11 @@ function qqAttachmentKind(attachment) {
187
196
  return 'file';
188
197
  }
189
198
 
190
- function qqReplyReference(message) {
199
+ // A quoted image or file arrives in msgElements[0] with its own download URL,
200
+ // so it can be read exactly like an attachment of the current message. Keep the
201
+ // sources on the reply reference (not on message.images/files) so local command
202
+ // and interaction routing keeps seeing only what the user sent just now.
203
+ function qqReplyReference(message, { fetchImpl } = {}) {
191
204
  const refMsgIdx = nonEmptyString(message?.refMsgIdx);
192
205
  if (!refMsgIdx) return null;
193
206
  const element = Array.isArray(message?.msgElements) ? message.msgElements[0] : null;
@@ -196,6 +209,7 @@ function qqReplyReference(message) {
196
209
  const name = nonEmptyString(attachment?.filename);
197
210
  return { kind: qqAttachmentKind(attachment), ...(name ? { name } : {}) };
198
211
  });
212
+ const media = qqQuotedMediaSources(sourceAttachments, { fetchImpl });
199
213
  const asrText = sourceAttachments
200
214
  .filter((attachment) => qqAttachmentKind(attachment) === 'audio')
201
215
  .map((attachment) => nonEmptyString(attachment?.asr_refer_text))
@@ -206,6 +220,8 @@ function qqReplyReference(message) {
206
220
  messageId: refMsgIdx,
207
221
  ...(content ? { content } : {}),
208
222
  ...(attachments.length > 0 ? { attachments } : {}),
223
+ ...(media.images.length > 0 ? { images: media.images } : {}),
224
+ ...(media.files.length > 0 ? { files: media.files } : {}),
209
225
  ...(!content && attachments.length === 0 ? { unavailableReason: 'not-delivered' } : {}),
210
226
  };
211
227
  }
@@ -224,12 +240,11 @@ async function fetchQqFileBuffer(url, { fetchImpl, signal }) {
224
240
  return Buffer.from(await response.arrayBuffer());
225
241
  }
226
242
 
227
- /** Convert QQ's attachment metadata into lazily downloaded image references. */
228
- export function qqInboundMessage(message, { fetchImpl = fetch } = {}) {
229
- if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
243
+ /** Convert QQ attachment metadata into lazily downloaded image and file sources. */
244
+ function qqAttachmentSources(attachments, { fetchImpl } = {}) {
230
245
  const images = [];
231
246
  const files = [];
232
- for (const attachment of message?.attachments ?? []) {
247
+ for (const attachment of attachments ?? []) {
233
248
  const url = nonEmptyString(attachment?.url);
234
249
  const name = nonEmptyString(attachment?.filename) ?? undefined;
235
250
  const mediaType = attachmentMediaType(attachment);
@@ -261,7 +276,43 @@ export function qqInboundMessage(message, { fetchImpl = fetch } = {}) {
261
276
  },
262
277
  });
263
278
  }
264
- const replyTo = qqReplyReference(message);
279
+ return { images, files };
280
+ }
281
+
282
+ // Only quoted attachments that still carry a download URL can be fetched; the
283
+ // rest stay visible by name in <dsh_im_reply_to> and never reach a download path.
284
+ // Quoted audio/video stay text-only too: a voice quote already contributes its
285
+ // ASR transcript, and staging the raw .silk would give the model nothing to read.
286
+ const QUOTED_MEDIA_LIMIT = 4;
287
+ const QUOTED_MEDIA_KINDS = new Set(['image', 'file']);
288
+
289
+ function qqQuotedMediaSources(attachments, { fetchImpl } = {}) {
290
+ const usable = (attachments ?? [])
291
+ .filter((attachment) => nonEmptyString(attachment?.url)
292
+ && QUOTED_MEDIA_KINDS.has(qqAttachmentKind(attachment)))
293
+ .slice(0, QUOTED_MEDIA_LIMIT);
294
+ return qqAttachmentSources(usable, { fetchImpl });
295
+ }
296
+
297
+ // A quoted file's download URL is signed for the quote snapshot, and a queued
298
+ // turn can outlive it, so start that download when the message is accepted.
299
+ // Quoted images deliberately stay lazy: the Host fetches them while building the
300
+ // ask, where it applies the model's image budget and the non-vision fallback —
301
+ // downloading them at enqueue time would defeat both.
302
+ function prefetchQuotedMedia(message, { signal } = {}) {
303
+ const files = message?.replyTo?.files;
304
+ if (!Array.isArray(files) || files.length === 0) return message;
305
+ return {
306
+ ...message,
307
+ replyTo: { ...message.replyTo, files: prefetchInboundFiles({ files }, { signal }).files },
308
+ };
309
+ }
310
+
311
+ /** Normalize a QQ message, turning its own and quoted attachments into lazy sources. */
312
+ export function qqInboundMessage(message, { fetchImpl = fetch } = {}) {
313
+ if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
314
+ const { images, files } = qqAttachmentSources(message?.attachments, { fetchImpl });
315
+ const replyTo = qqReplyReference(message, { fetchImpl });
265
316
  return {
266
317
  content: safeText(message),
267
318
  images,
@@ -658,6 +709,7 @@ export class QqHarnessBridge {
658
709
  const commandRunner = explicitMenu || numericMenu
659
710
  ? () => this.#runMenuCommand(message, menuInput, key)
660
711
  : isClearCommand(commandText) ? runClearCommand
712
+ : isResetCommand(commandText) ? runResetCommand
661
713
  : isHistoryCommand(commandText) ? runHistoryCommand
662
714
  : isPermissionCommand(commandText) ? runPermissionCommand
663
715
  : hasQqFileAttachments(message) ? null : isControlCommand(commandText)
@@ -773,8 +825,11 @@ export class QqHarnessBridge {
773
825
  const pending = this.#recordPendingMessage(message, messageId, key);
774
826
  const addressed = isQqMessageAddressed(message);
775
827
  const preparedMessage = addressed
776
- ? prefetchInboundFiles(
777
- qqInboundMessage(message, { fetchImpl: this.#fetchImpl }),
828
+ ? prefetchQuotedMedia(
829
+ prefetchInboundFiles(
830
+ qqInboundMessage(message, { fetchImpl: this.#fetchImpl }),
831
+ { signal: this.#signal },
832
+ ),
778
833
  { signal: this.#signal },
779
834
  )
780
835
  : undefined;
@@ -1022,10 +1077,11 @@ export class QqHarnessBridge {
1022
1077
  || locked.sessionId !== choice.context.sessionId) {
1023
1078
  return { message: t('会话或工作区已变化,请重新发送 /m。') };
1024
1079
  }
1025
- await this.#state.clearSession(key);
1026
- return { message: t('已开启新会话。请发送你的问题。') };
1080
+ const created = await createConversationSession({ state: this.#state, harness: this.#harness, key });
1081
+ return { message: created.failed ? t('暂时无法创建新会话,请稍后重试。') : t('已开启新会话。请发送你的问题。') };
1027
1082
  });
1028
1083
  if (isClearCommand(command)) return runClearCommand(command, this.#harness, this.#state, key, options);
1084
+ if (isResetCommand(command)) return runResetCommand(command, this.#harness, this.#state, key, options);
1029
1085
  if (command === '/compact') return runCompactCommand(command, this.#harness, this.#state, key, options);
1030
1086
  return runWorkspaceCommand(command, this.#harness, key);
1031
1087
  };
@@ -1238,9 +1294,32 @@ export class QqHarnessBridge {
1238
1294
  await markMessageSeen();
1239
1295
  return;
1240
1296
  }
1241
- if (!hasImages && !hasFiles && command === '/new') {
1242
- await this.#state.clearSession(key);
1243
- await this.#bot.sendText(target, t('已开启新会话。请发送你的问题。'));
1297
+ if (!hasImages && !hasFiles && isNewCommand(text)) {
1298
+ const created = await createConversationSession({ state: this.#state, harness: this.#harness, key, title: newCommandTitle(text) });
1299
+ await this.#bot.sendText(target, created.failed ? t('暂时无法创建新会话,请稍后重试。') : t('已开启新会话。请发送你的问题。'));
1300
+ await markMessageSeen();
1301
+ return;
1302
+ }
1303
+ if (!hasImages && !hasFiles && isSessionNavCommand(text)) {
1304
+ const nav = await runSessionNavTextCommand(text, this.#harness, this.#state, key, {
1305
+ signal: this.#signal,
1306
+ });
1307
+ if (nav) {
1308
+ for (const reply of nav.messages ?? [nav.message]) {
1309
+ await this.#bot.sendText(target, reply);
1310
+ }
1311
+ if (nav.askText) {
1312
+ const followUp = this.#enqueueMessage(
1313
+ { ...message, content: nav.askText, attachments: [] },
1314
+ `${messageId}-ask`,
1315
+ key,
1316
+ );
1317
+ followUp.catch((error) => {
1318
+ this.#logger.warn?.(`[dsh-im:qq] follow-up ask after a nav command failed:`, error?.message ?? error);
1319
+ this.#bot.sendText(target, t('切换后的提问发送失败,请重试。')).catch(() => undefined);
1320
+ });
1321
+ }
1322
+ }
1244
1323
  await markMessageSeen();
1245
1324
  return;
1246
1325
  }
@@ -1256,6 +1335,18 @@ export class QqHarnessBridge {
1256
1335
  await markMessageSeen();
1257
1336
  return;
1258
1337
  }
1338
+ const resetCommand = await runResetCommand(text, this.#harness, this.#state, key, {
1339
+ signal: this.#signal,
1340
+ hasImages,
1341
+ hasFiles,
1342
+ pendingInteraction: this.#pendingInteractions.has(key) || this.#approvals.hasPending(key),
1343
+ busy: this.#queues.has(key),
1344
+ });
1345
+ if (resetCommand) {
1346
+ await this.#bot.sendText(target, resetCommand.message);
1347
+ await markMessageSeen();
1348
+ return;
1349
+ }
1259
1350
  const workspaceCommand = hasImages || hasFiles
1260
1351
  ? null
1261
1352
  : await runWorkspaceCommand(text, this.#harness, key);
@@ -1,4 +1,5 @@
1
1
  import { deferredStateAccess, normalizeDeferredState } from '../shared/deferred-state.mjs';
2
+ import { createSessionRingSupport, normalizePendingTitles, normalizeSessionRings } from '../shared/session-ring-support.mjs';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import fs from 'node:fs/promises';
4
5
  import { dirname } from 'node:path';
@@ -81,6 +82,10 @@ function normalizeState(value) {
81
82
  // An empty queue leaves no key behind, so an untouched state file keeps the
82
83
  // shape earlier versions wrote.
83
84
  const pendingMessages = normalizePendingMessages(value.pendingMessages);
85
+ // A file written before the navigation ring existed loads unchanged: the keys
86
+ // are only added when they hold something.
87
+ const rings = normalizeSessionRings(value.rings);
88
+ const pendingTitles = normalizePendingTitles(value.pendingTitles);
84
89
  return {
85
90
  version: 1,
86
91
  sessions,
@@ -91,6 +96,8 @@ function normalizeState(value) {
91
96
  seenMessageIds: Array.isArray(value.seenMessageIds)
92
97
  ? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000)
93
98
  : [],
99
+ ...(Object.keys(rings).length ? { rings } : {}),
100
+ ...(Object.keys(pendingTitles).length ? { pendingTitles } : {}),
94
101
  };
95
102
  }
96
103
 
@@ -104,8 +111,13 @@ export class QqStateStore {
104
111
  constructor(path, { logger = console } = {}) {
105
112
  this.#path = path;
106
113
  this.#logger = logger;
114
+ // The navigation ring is a view over this store's state, shared with the
115
+ // channels that inherit `ConversationStateStore`.
116
+ Object.assign(this, createSessionRingSupport({
117
+ state: () => this.#state,
118
+ persist: () => this.#persist(),
119
+ }));
107
120
  }
108
-
109
121
  async load() {
110
122
  let bytes;
111
123
  try {
@@ -5,9 +5,12 @@ export const ACCESS_POLICY_USER_ID_MAX_LENGTH = 256;
5
5
 
6
6
  const POLICY_KEYS = ['direct', 'group'];
7
7
  const SCOPE_KEYS = ['mode', 'open', 'allowlist'];
8
- const OPEN_KEYS = ['defaultCanExecuteCommands', 'commandPermissionOverrides'];
8
+ const OPEN_KEYS = ['defaultCanExecuteCommands', 'commandPermissionOverrides', 'commandAllowlist'];
9
+ const OPEN_REQUIRED_KEYS = ['defaultCanExecuteCommands', 'commandPermissionOverrides'];
9
10
  const ALLOWLIST_KEYS = ['users'];
10
- const USER_KEYS = ['id', 'canExecuteCommands'];
11
+ const USER_KEYS = ['id', 'canExecuteCommands', 'commandAllowlist'];
12
+ const USER_REQUIRED_KEYS = ['id', 'canExecuteCommands'];
13
+ const COMMAND_ALLOWLIST_LIMIT = 100;
11
14
  const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;
12
15
 
13
16
  function invalidAccessPolicy(message) {
@@ -23,6 +26,41 @@ function hasExactKeys(input, keys) {
23
26
  && keys.every((key) => Object.hasOwn(input, key));
24
27
  }
25
28
 
29
+ /** Accept required keys plus a bounded set of optional keys. */
30
+ function hasAllowedKeys(input, required, optional = []) {
31
+ if (!input || typeof input !== 'object' || Array.isArray(input)
32
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(input))) return false;
33
+ const keys = Reflect.ownKeys(input);
34
+ return required.every((key) => Object.hasOwn(input, key))
35
+ && keys.every((key) => required.includes(key) || optional.includes(key));
36
+ }
37
+
38
+ /**
39
+ * Canonical command name: first token, optional leading slash, lower case.
40
+ * `/sessionlist --limit 5` and `/SessionList` both become `sessionlist`.
41
+ */
42
+ export function normalizeCommandName(value) {
43
+ if (typeof value !== 'string') return null;
44
+ const first = value.trim().split(/\s+/u)[0];
45
+ if (!first) return null;
46
+ const name = (first.startsWith('/') ? first.slice(1) : first).toLowerCase();
47
+ return /^[a-z0-9][a-z0-9:_-]{0,63}$/u.test(name) ? name : null;
48
+ }
49
+
50
+ function validateCommandAllowlist(input, label) {
51
+ if (input === undefined) return null;
52
+ if (!Array.isArray(input)) throw invalidAccessPolicy(`${label}必须是命令名数组。`);
53
+ if (input.length > COMMAND_ALLOWLIST_LIMIT) {
54
+ throw invalidAccessPolicy(`${label}最多包含 ${COMMAND_ALLOWLIST_LIMIT} 个命令。`);
55
+ }
56
+ const names = input.map((value) => {
57
+ const name = normalizeCommandName(value);
58
+ if (!name) throw invalidAccessPolicy(`${label}包含无效命令名。`);
59
+ return name;
60
+ });
61
+ return Object.freeze([...new Set(names)]);
62
+ }
63
+
26
64
  /** Normalize one opaque channel identity without interpreting its contents. */
27
65
  export function normalizeAccessPolicyUserId(value) {
28
66
  if (typeof value === 'number') {
@@ -40,15 +78,17 @@ export function normalizeAccessPolicyUserId(value) {
40
78
  }
41
79
 
42
80
  function validateAccessPolicyUser(input) {
43
- if (!hasExactKeys(input, USER_KEYS)) {
44
- throw invalidAccessPolicy('用户条目必须包含用户标识和命令权限。');
81
+ if (!hasAllowedKeys(input, USER_REQUIRED_KEYS, USER_KEYS)) {
82
+ throw invalidAccessPolicy('用户条目必须包含用户标识、命令权限和可选的命令白名单。');
45
83
  }
46
84
  if (typeof input.canExecuteCommands !== 'boolean') {
47
85
  throw invalidAccessPolicy('命令权限必须是布尔值。');
48
86
  }
87
+ const commandAllowlist = validateCommandAllowlist(input.commandAllowlist, '用户命令白名单');
49
88
  return Object.freeze({
50
89
  id: normalizeAccessPolicyUserId(input.id),
51
90
  canExecuteCommands: input.canExecuteCommands,
91
+ ...(commandAllowlist === null ? {} : { commandAllowlist }),
52
92
  });
53
93
  }
54
94
 
@@ -62,8 +102,8 @@ function validateUsers(input, { listMessage, duplicateMessage }) {
62
102
  }
63
103
 
64
104
  function validateOpenSettings(input) {
65
- if (!hasExactKeys(input, OPEN_KEYS)) {
66
- throw invalidAccessPolicy('开放模式设置必须完整。');
105
+ if (!hasAllowedKeys(input, OPEN_REQUIRED_KEYS, OPEN_KEYS)) {
106
+ throw invalidAccessPolicy('开放模式设置必须完整(可选的 commandAllowlist 除外)。');
67
107
  }
68
108
  if (typeof input.defaultCanExecuteCommands !== 'boolean') {
69
109
  throw invalidAccessPolicy('开放模式默认命令权限必须是布尔值。');
@@ -74,6 +114,9 @@ function validateOpenSettings(input) {
74
114
  listMessage: '开放模式命令权限覆盖用户必须是数组。',
75
115
  duplicateMessage: '开放模式命令权限覆盖用户不能包含重复的用户标识。',
76
116
  }),
117
+ ...(input.commandAllowlist === undefined
118
+ ? {}
119
+ : { commandAllowlist: validateCommandAllowlist(input.commandAllowlist, '开放模式命令白名单') }),
77
120
  });
78
121
  }
79
122
 
@@ -167,6 +210,7 @@ export function evaluateAccessPolicy(policy, {
167
210
  conversationType,
168
211
  senderIds,
169
212
  isCommand = false,
213
+ command = null,
170
214
  equals = (left, right) => left === right,
171
215
  } = {}) {
172
216
  const normalizedPolicy = normalizeAccessPolicy(policy);
@@ -175,6 +219,7 @@ export function evaluateAccessPolicy(policy, {
175
219
  || typeof isCommand !== 'boolean' || typeof equals !== 'function') {
176
220
  return INVALID_CONTEXT;
177
221
  }
222
+ const normalizedCommand = normalizeCommandName(command);
178
223
  const candidates = (Array.isArray(senderIds) ? senderIds : [senderIds])
179
224
  .flatMap((candidate) => {
180
225
  try {
@@ -204,7 +249,15 @@ export function evaluateAccessPolicy(policy, {
204
249
  ? matchedUsers.every((user) => user.canExecuteCommands)
205
250
  : scope.open.defaultCanExecuteCommands)
206
251
  : matchedUsers.every((user) => user.canExecuteCommands);
207
- if (!canExecuteCommands) return COMMAND_NOT_ALLOWED;
252
+ if (!canExecuteCommands) {
253
+ const scopeAllowsCommand = scope.mode === 'open'
254
+ && normalizedCommand !== null
255
+ && (scope.open.commandAllowlist ?? []).includes(normalizedCommand);
256
+ const usersAllowCommand = matchedUsers.length > 0
257
+ && normalizedCommand !== null
258
+ && matchedUsers.every((user) => user.commandAllowlist?.includes(normalizedCommand) === true);
259
+ if (!scopeAllowsCommand && !usersAllowCommand) return COMMAND_NOT_ALLOWED;
260
+ }
208
261
  }
209
262
  return ALLOWED;
210
263
  }