@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
@@ -3,6 +3,7 @@ import { withSessionBindingLock } from './session-binding-lock.mjs';
3
3
  import { initialSessionTitle } from './session-title.mjs';
4
4
  import { extractConnectionEvidence, messageDiagnosticError } from './connection-error.mjs';
5
5
  import { t } from './i18n.mjs';
6
+ import { replyContentFinalAnswerOnly } from './reply-content.mjs';
6
7
 
7
8
  export const WORKSPACE_SESSION_STALE = 'workspace-session-stale';
8
9
 
@@ -169,9 +170,15 @@ export async function askInWorkspaceSession({
169
170
  // against a conversation switch that only commits after the bind.
170
171
  const conversationGeneration = readConversationGeneration(harness, key);
171
172
  session = workspaceSession(harness, sessionId, key);
172
- if (initialTitle && typeof session.renameTitle === 'function') {
173
+ // A title the user set with /title before any Session existed wins over
174
+ // the one derived from the first message, and is consumed exactly once.
175
+ const pendingTitle = typeof state.takePendingTitle === 'function'
176
+ ? await state.takePendingTitle(key).catch(() => null)
177
+ : null;
178
+ const effectiveTitle = pendingTitle || initialTitle;
179
+ if (effectiveTitle && typeof session.renameTitle === 'function') {
173
180
  try {
174
- await session.renameTitle(initialTitle, renameOptions);
181
+ await session.renameTitle(effectiveTitle, renameOptions);
175
182
  } catch (error) {
176
183
  if (error?.code === WORKSPACE_SESSION_STALE || renameOptions?.signal?.aborted) {
177
184
  throw error;
@@ -184,6 +191,17 @@ export async function askInWorkspaceSession({
184
191
  if (conversationGenerationMoved(harness, key, conversationGeneration)) {
185
192
  throw workspaceSessionStaleError();
186
193
  }
194
+ // Record the newly bound Session in the conversation's navigation ring
195
+ // so /ls, /go, /prev and /next can find it later. Optional: a state
196
+ // store without ring support simply skips this.
197
+ try {
198
+ const registered = await state.ensureSessionRing?.(key, sessionId, {
199
+ title: typeof effectiveTitle === 'string' && effectiveTitle ? effectiveTitle : undefined,
200
+ });
201
+ if (registered?.entry) await state.appendRing?.(key, registered.entry.n);
202
+ } catch (error) {
203
+ console.warn('[dsh-im] unable to record the session in the navigation ring:', error?.message ?? error);
204
+ }
187
205
  return { sessionId, session, recovered: replacingUnreadable };
188
206
  }
189
207
  return { sessionId, session };
@@ -202,6 +220,17 @@ export async function askInWorkspaceSession({
202
220
  const artifactOptions = typeof askOptions === 'number'
203
221
  ? { timeoutMs: askOptions }
204
222
  : { ...askOptions };
223
+ // One Harness-side filter serves every channel: the bot's content
224
+ // switches travel with the ask instead of being re-implemented per
225
+ // bridge. The answer itself is never switched off, but a bot that hides
226
+ // the process prose is asking for the text after the last tool call.
227
+ const replyContent = typeof harness?.currentReplyContent === 'function'
228
+ ? harness.currentReplyContent()
229
+ : null;
230
+ const finalAnswerOnly = replyContent !== null
231
+ && replyContentFinalAnswerOnly(replyContent);
232
+ if (replyContent !== null) artifactOptions.replyContent = replyContent;
233
+ if (finalAnswerOnly) artifactOptions.finalAnswerOnly = true;
205
234
  // The guidance the channel's captured settings applied, carried out of
206
235
  // band so the Host never has to read configuration out of the prompt.
207
236
  artifactOptions.sourceGuidance = sourceGuidance;
@@ -224,7 +253,14 @@ export async function askInWorkspaceSession({
224
253
  if (error?.code === 'harness-reply-timeout' && deferredDelivery) {
225
254
  try {
226
255
  const { coordinator, ...destination } = deferredDelivery();
227
- await coordinator.trackTimeout(error, { ...destination, key, sessionId: binding.sessionId });
256
+ // The background path must deliver what this turn would have
257
+ // delivered: a hidden process prose keeps the answer alone there too.
258
+ await coordinator.trackTimeout(error, {
259
+ ...destination,
260
+ key,
261
+ sessionId: binding.sessionId,
262
+ ...(finalAnswerOnly ? { finalAnswerOnly: true } : {}),
263
+ });
228
264
  } catch (registrationError) {
229
265
  console.warn('[dsh-im] unable to persist deferred delivery:', registrationError.message);
230
266
  }
@@ -132,8 +132,9 @@ function delay(ms, signal) {
132
132
  reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
133
133
  return;
134
134
  }
135
+ // Deliberately NOT unref'd: a rate-limit backoff is the only thing the caller
136
+ // is waiting for, so the timer must keep the loop alive until it fires.
135
137
  const timer = setTimeout(resolve, ms);
136
- timer?.unref?.();
137
138
  signal?.addEventListener('abort', () => {
138
139
  clearTimeout(timer);
139
140
  reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
@@ -70,6 +70,8 @@ export function normalizeTelegramAccessPolicy(value = {}) {
70
70
  }
71
71
 
72
72
  function normalizeTelegramBotExtension(value) {
73
+ // Written only for newly saved identities; absent on legacy disk records.
74
+ const senderAccessDefault = value.senderAccessDefault === 'allowlist' ? 'allowlist' : undefined;
73
75
  const hasAccessMode = Object.hasOwn(value, 'accessMode');
74
76
  const hasAllowedUsers = Object.hasOwn(value, 'allowedUsers');
75
77
  const hasThinkingTraces = Object.hasOwn(value, 'thinkingTraces');
@@ -78,10 +80,11 @@ function normalizeTelegramBotExtension(value) {
78
80
  const hasThinkingInterval = Object.hasOwn(value, 'thinkingIntervalSeconds');
79
81
  const hasSendLimit = Object.hasOwn(value, 'sendLimitPerMinute');
80
82
  if (!hasAccessMode && !hasAllowedUsers && !hasThinkingTraces && !hasGroupTriggers
81
- && !hasThinkingNumbering && !hasThinkingInterval && !hasSendLimit) return {};
83
+ && !hasThinkingNumbering && !hasThinkingInterval && !hasSendLimit && !senderAccessDefault) return {};
82
84
  try {
83
85
  const policy = normalizeTelegramAccessPolicy(value);
84
86
  return {
87
+ ...(senderAccessDefault ? { senderAccessDefault } : {}),
85
88
  ...(hasAccessMode ? { accessMode: policy.accessMode } : {}),
86
89
  ...(hasAllowedUsers || hasAccessMode ? { allowedUsers: policy.allowedUsers } : {}),
87
90
  // Explicit field is kept; an absent field stays absent.
@@ -121,6 +124,11 @@ export class TelegramConfigStore extends TokenBotConfigStore {
121
124
 
122
125
  async save(value) {
123
126
  const previous = value?.platformId ? this.getByPlatformId(String(value.platformId)) : null;
124
- return super.save({ ...previous, ...value });
127
+ return super.save({
128
+ ...previous, ...value,
129
+ // Persist before runtime/workspace initialization so an interrupted bind
130
+ // cannot be mistaken for a legacy bot at the next startup.
131
+ ...(!previous ? { senderAccessDefault: 'allowlist' } : {}),
132
+ });
125
133
  }
126
134
  }
@@ -8,9 +8,16 @@ function textValue(value) {
8
8
  return value;
9
9
  }
10
10
 
11
+ /**
12
+ * What one character costs after escaping.
13
+ *
14
+ * A backslash before an angle bracket, because that is how markdown — including Telegram's rich
15
+ * markdown — writes a literal `<`. HTML entities were tried first and shown on the screen as
16
+ * themselves: `&lt;dsh_say&gt;` instead of `<dsh_say>`, so the escape was visible and the text
17
+ * was not.
18
+ */
11
19
  function escapedCharacterLength(value) {
12
- if (value === '&') return 5;
13
- if (value === '<' || value === '>') return 4;
20
+ if (value === '<' || value === '>') return 2;
14
21
  return 1;
15
22
  }
16
23
 
@@ -63,11 +70,16 @@ function assertCompleteFences(markdown) {
63
70
  return markers;
64
71
  }
65
72
 
73
+ /**
74
+ * Neutralise the two characters markdown would read as a tag.
75
+ *
76
+ * `&` is left alone: no parser in the chain decodes HTML entities, so `&amp;` reached the screen
77
+ * as `&amp;`. Only `<` and `>` can open something, and a backslash is how markdown says "this is
78
+ * a character, not a tag".
79
+ */
66
80
  function escapedMarkdown(value) {
67
81
  return Array.from(value, (character) => {
68
- if (character === '&') return '&amp;';
69
- if (character === '<') return '&lt;';
70
- if (character === '>') return '&gt;';
82
+ if (character === '<' || character === '>') return `\\${character}`;
71
83
  return character;
72
84
  }).join('');
73
85
  }
@@ -1016,6 +1016,15 @@ export class TelegramBotClient {
1016
1016
  }
1017
1017
  }
1018
1018
 
1019
+ /** Delete one of the bot's own messages (used by the /tail "Hide" button). */
1020
+ async deleteMessage(target, messageId) {
1021
+ return this.#api.deleteMessage({
1022
+ chatId: target.chatId,
1023
+ messageId: Number(messageId),
1024
+ signal: this.#signal,
1025
+ });
1026
+ }
1027
+
1019
1028
  async #sendRich(target, block) {
1020
1029
  if (block.format === 'plain') return this.#sendPlain(target, block.text);
1021
1030
 
@@ -1819,9 +1828,13 @@ export class TelegramRuntime {
1819
1828
  logger: this.#logger,
1820
1829
  });
1821
1830
  accepted = true;
1831
+ // Pass the bot's steer/queue setting explicitly, matching DingTalk and
1832
+ // Discord; the bridge would otherwise fall back to the same scoped
1833
+ // harness getter, but an explicit value keeps the wiring visible.
1834
+ const busyMessageMode = this.#harness.currentBusyMessageMode?.() ?? 'queue';
1822
1835
  // The bridge owns turn ordering; awaiting it here would park the
1823
1836
  // conversation behind a turn that waits for the user.
1824
- void this.#bridge.accept(message, { contextSnapshot }).catch((error) => {
1837
+ void this.#bridge.accept(message, { contextSnapshot, busyMessageMode }).catch((error) => {
1825
1838
  if (signal.aborted) return;
1826
1839
  this.#logger.error?.(
1827
1840
  `[dsh-im:telegram] bot ${this.#config.botId} message handling failed:`,
@@ -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, unlink, writeFile } from 'node:fs/promises';
3
4
  import { dirname } from 'node:path';
4
5
 
@@ -12,6 +13,10 @@ function normalizeState(value) {
12
13
  if (typeof key === 'string' && typeof sessionId === 'string' && sessionId) sessions[key] = sessionId;
13
14
  }
14
15
  }
16
+ // A file written before the navigation ring existed loads unchanged: the keys
17
+ // are only added when they hold something.
18
+ const rings = normalizeSessionRings(value.rings);
19
+ const pendingTitles = normalizePendingTitles(value.pendingTitles);
15
20
  return {
16
21
  version: 1,
17
22
  sessions,
@@ -19,6 +24,8 @@ function normalizeState(value) {
19
24
  seenMessageIds: Array.isArray(value.seenMessageIds)
20
25
  ? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000)
21
26
  : [],
27
+ ...(Object.keys(rings).length ? { rings } : {}),
28
+ ...(Object.keys(pendingTitles).length ? { pendingTitles } : {}),
22
29
  };
23
30
  }
24
31
 
@@ -30,8 +37,13 @@ export class WecomStateStore {
30
37
 
31
38
  constructor(path) {
32
39
  this.#path = path;
40
+ // The navigation ring is a view over this store's state, shared with the
41
+ // channels that inherit `ConversationStateStore`.
42
+ Object.assign(this, createSessionRingSupport({
43
+ state: () => this.#state,
44
+ persist: () => this.#persist(),
45
+ }));
33
46
  }
34
-
35
47
  async load() {
36
48
  try {
37
49
  this.#state = normalizeState(JSON.parse(await readFile(this.#path, 'utf8')));
@@ -1,8 +1,9 @@
1
1
  import { BusyMessageDispatcher, canAutomaticallySteer } from '../shared/busy-message-dispatcher.mjs';
2
+ import { SESSION_NAV_HELP_LINES } from '../shared/command-catalog.mjs';
2
3
  import { imageInputLimits } from '../shared/image-input-policy.mjs';
3
4
  import { imageDownloadLimitMessage } from '../shared/image-prompt.mjs';
4
5
  import { createDeferredDeliveryCoordinator, deferredOutcomeText } from '../shared/deferred-delivery-coordinator.mjs';
5
- import { generateReqId } from '@wecom/aibot-node-sdk';
6
+ import { decryptFile, generateReqId } from '@wecom/aibot-node-sdk';
6
7
  import { randomUUID } from 'node:crypto';
7
8
  import { wecomSendDiagnostic, wecomSendError } from './send-error.mjs';
8
9
  import {
@@ -23,6 +24,7 @@ import {
23
24
  import { runCompactCommand } from '../shared/compact-command.mjs';
24
25
  import { isSharedLocalCommand } from '../shared/command-permission.mjs';
25
26
  import { isClearCommand, runClearCommand } from '../shared/clear-command.mjs';
27
+ import { isResetCommand, runResetCommand } from '../shared/reset-command.mjs';
26
28
  import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
27
29
  import { isPermissionCommand, runPermissionCommand } from '../shared/permission-command.mjs';
28
30
  import {
@@ -39,6 +41,11 @@ import {
39
41
  } from '../shared/preset-command.mjs';
40
42
  import { conversationSessionWorkspace, runWorkspaceCommand, workspacePathSnapshot } from '../shared/workspace-command.mjs';
41
43
  import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
44
+ import {
45
+ isSessionNavCommand,
46
+ runSessionNavTextCommand,
47
+ } from '../shared/session-nav-command.mjs';
48
+ import { createConversationSession, isNewCommand, newCommandTitle } from '../shared/new-command.mjs';
42
49
  import {
43
50
  captureContextEnhancement,
44
51
  captureContextEnhancementSource,
@@ -95,8 +102,10 @@ function helpText() {
95
102
  t('/workspacelist 列出工作区绝对路径'),
96
103
  t('/ws、/wsl、/workspaces 工作区命令别名'),
97
104
  t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'),
105
+ t('/sessionlist --all 跨工作区汇总会话(每个工作区默认显示 10 个,可用 --limit N 调整)'),
98
106
  t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'),
99
- t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'),
107
+ t('/session Session ID、当前工作区序号或标题关键词 将当前聊天绑定到指定会话'),
108
+ ...SESSION_NAV_HELP_LINES.map((line) => t(line)),
100
109
  t('/models 按序号列出所有可用模型'),
101
110
  t('/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级'),
102
111
  t('/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级'),
@@ -189,32 +198,122 @@ function quoteAttachments(quote) {
189
198
  .map(() => ({ kind: 'image' }));
190
199
  }
191
200
 
192
- function replyReferenceForBody(body) {
201
+ // A quoted file arrives with its own download url and aeskey (see
202
+ // QuoteContent.file in @wecom/aibot-node-sdk), so it can be read exactly like a
203
+ // file attached to the current message.
204
+ function quotedFileSources(client, quote, options = {}) {
205
+ if (quote?.msgtype !== 'file') return [];
206
+ const file = quote.file;
207
+ if (!file || typeof file !== 'object') return [];
208
+ const source = fileSource(client, file, options);
209
+ return source ? [source] : [];
210
+ }
211
+
212
+ function replyReferenceForBody(body, client, options = {}) {
193
213
  const quote = body?.quote;
194
214
  if (!quote || typeof quote !== 'object') return null;
195
215
  const content = messageContentText(quote);
196
216
  const attachments = quoteAttachments(quote);
217
+ const files = quotedFileSources(client, quote, options);
197
218
  const supported = ['text', 'image', 'mixed', 'voice', 'file'].includes(quote.msgtype);
198
219
  return {
199
220
  ...(content ? { content } : {}),
200
221
  ...(attachments.length > 0 ? { attachments } : {}),
222
+ ...(files.length > 0 ? { files } : {}),
201
223
  ...(!content && attachments.length === 0
202
224
  ? { unavailableReason: supported ? 'not-delivered' : 'unsupported' }
203
225
  : {}),
204
226
  };
205
227
  }
206
228
 
207
- function imageSource(client, image) {
229
+ // The WeCom SDK downloads media through axios. On Hosts where that request ends
230
+ // up on the Node HTTP client every https URL fails with
231
+ // 'Protocol "https:" not supported. Expected "http:"', which loses the whole
232
+ // inbound attachment. Keep the SDK path (it owns the AES key handling) and only
233
+ // take over when it reports that protocol mismatch.
234
+ const UNSUPPORTED_DOWNLOAD_PROTOCOL = /not supported\. Expected "http:"/u;
235
+
236
+ function isUnsupportedDownloadProtocol(error) {
237
+ const seen = new Set();
238
+ let current = error;
239
+ while (current && typeof current === 'object' && !seen.has(current)) {
240
+ seen.add(current);
241
+ if (current.code === 'ERR_INVALID_PROTOCOL') return true;
242
+ if (typeof current.message === 'string' && UNSUPPORTED_DOWNLOAD_PROTOCOL.test(current.message)) {
243
+ return true;
244
+ }
245
+ current = current.cause;
246
+ }
247
+ return false;
248
+ }
249
+
250
+ async function discardResponseBody(response) {
251
+ try {
252
+ await response?.body?.cancel?.();
253
+ } catch {
254
+ // Preserve the original download failure.
255
+ }
256
+ }
257
+
258
+ function contentDispositionName(header) {
259
+ const value = nonEmptyString(header);
260
+ if (!value) return undefined;
261
+ const raw = value.match(/filename\*=UTF-8''([^;\s]+)/iu)?.[1]
262
+ ?? value.match(/filename="?([^";\s]+)"?/iu)?.[1];
263
+ if (!raw) return undefined;
264
+ try {
265
+ return decodeURIComponent(raw);
266
+ } catch {
267
+ return raw;
268
+ }
269
+ }
270
+
271
+ async function fetchWecomMedia(url, { fetchImpl = fetch, signal } = {}) {
272
+ const target = new URL(url);
273
+ if (target.protocol !== 'https:') {
274
+ throw new Error('Enterprise WeChat media download must use HTTPS');
275
+ }
276
+ const response = await fetchImpl(target, { method: 'GET', signal, redirect: 'follow' });
277
+ if (!response?.ok) {
278
+ await discardResponseBody(response);
279
+ throw new Error(
280
+ `Enterprise WeChat media download failed with HTTP ${response?.status ?? 'unknown'}`,
281
+ );
282
+ }
283
+ return {
284
+ buffer: Buffer.from(await response.arrayBuffer()),
285
+ filename: contentDispositionName(response.headers?.get?.('content-disposition')),
286
+ };
287
+ }
288
+
289
+ async function downloadWecomMedia(client, url, aeskey, options = {}) {
290
+ if (typeof client?.downloadFile === 'function') {
291
+ try {
292
+ return await client.downloadFile(url, aeskey);
293
+ } catch (error) {
294
+ if (!isUnsupportedDownloadProtocol(error)) throw error;
295
+ options.logger?.warn?.(
296
+ '[wecom] SDK media download fell back to fetch:',
297
+ error?.message ?? error,
298
+ );
299
+ }
300
+ }
301
+ const downloaded = await fetchWecomMedia(url, options);
302
+ if (!aeskey) return downloaded;
303
+ return { ...downloaded, buffer: decryptFile(downloaded.buffer, aeskey) };
304
+ }
305
+
306
+ function imageSource(client, image, options = {}) {
208
307
  const url = nonEmptyString(image?.url);
209
308
  if (!url) return null;
210
309
  const aeskey = nonEmptyString(image?.aeskey) ?? undefined;
211
310
  return {
212
- async load({ signal, maxBytes }) {
311
+ async load({ signal, maxBytes } = {}) {
213
312
  signal?.throwIfAborted();
214
- if (typeof client?.downloadFile !== 'function') {
215
- throw new Error('Enterprise WeChat image download is unavailable');
216
- }
217
- const result = await client.downloadFile(url, aeskey);
313
+ const result = await downloadWecomMedia(client, url, aeskey, {
314
+ ...options,
315
+ signal,
316
+ });
218
317
  signal?.throwIfAborted();
219
318
  const raw = result?.buffer;
220
319
  if (!Buffer.isBuffer(raw) && !(raw instanceof Uint8Array)) {
@@ -233,7 +332,7 @@ function imageSource(client, image) {
233
332
  };
234
333
  }
235
334
 
236
- function fileSource(client, file) {
335
+ function fileSource(client, file, options = {}) {
237
336
  const url = nonEmptyString(file?.url);
238
337
  if (!url) return null;
239
338
  const aeskey = nonEmptyString(file?.aeskey) ?? undefined;
@@ -241,10 +340,10 @@ function fileSource(client, file) {
241
340
  name: nonEmptyString(file?.filename ?? file?.file_name ?? file?.name) ?? 'file',
242
341
  async load({ signal } = {}) {
243
342
  signal?.throwIfAborted();
244
- if (typeof client?.downloadFile !== 'function') {
245
- throw new Error('Enterprise WeChat file download is unavailable');
246
- }
247
- const result = await client.downloadFile(url, aeskey);
343
+ const result = await downloadWecomMedia(client, url, aeskey, {
344
+ ...options,
345
+ signal,
346
+ });
248
347
  signal?.throwIfAborted();
249
348
  const raw = result?.buffer ?? result?.data;
250
349
  if (!Buffer.isBuffer(raw) && !(raw instanceof Uint8Array)) {
@@ -258,13 +357,17 @@ function fileSource(client, file) {
258
357
  };
259
358
  }
260
359
 
261
- export function wecomInboundMessage(frame, client) {
360
+ export function wecomInboundMessage(frame, client, options = {}) {
262
361
  const body = bodyOf(frame);
263
- const replyTo = replyReferenceForBody(body);
362
+ const replyTo = replyReferenceForBody(body, client, options);
264
363
  return {
265
364
  content: messageText(frame),
266
- images: imageContents(body).map((image) => imageSource(client, image)).filter(Boolean),
267
- files: fileContents(frame).map((file) => fileSource(client, file)).filter(Boolean),
365
+ images: imageContents(body)
366
+ .map((image) => imageSource(client, image, options))
367
+ .filter(Boolean),
368
+ files: fileContents(frame)
369
+ .map((file) => fileSource(client, file, options))
370
+ .filter(Boolean),
268
371
  ...(replyTo ? { replyTo } : {}),
269
372
  };
270
373
  }
@@ -289,6 +392,15 @@ function prefetchInboundFiles(message, signal) {
289
392
  };
290
393
  }
291
394
 
395
+ function prefetchQuotedFiles(message, signal) {
396
+ const files = message?.replyTo?.files;
397
+ if (!Array.isArray(files) || files.length === 0) return message;
398
+ return {
399
+ ...message,
400
+ replyTo: { ...message.replyTo, files: prefetchInboundFiles({ files }, signal).files },
401
+ };
402
+ }
403
+
292
404
  function prefetchInboundImages(message, signal, limitsPromise) {
293
405
  if (!hasInboundImages(message)) return message;
294
406
  return {
@@ -606,6 +718,7 @@ export class WecomHarnessBridge {
606
718
  #menus = new Map();
607
719
  #eventIds = new Set();
608
720
  #cardFrames = new WeakSet();
721
+ #fetchImpl;
609
722
 
610
723
  constructor({
611
724
  client,
@@ -621,6 +734,7 @@ export class WecomHarnessBridge {
621
734
  generateStreamId = generateReqId,
622
735
  fileUploadTimeoutMs = DEFAULT_FILE_UPLOAD_TIMEOUT_MS,
623
736
  signal,
737
+ fetchImpl = globalThis.fetch,
624
738
  }) {
625
739
  if (!client || typeof client.replyStream !== 'function' || typeof client.sendMessage !== 'function') {
626
740
  throw new TypeError('Enterprise WeChat client is required');
@@ -642,6 +756,7 @@ export class WecomHarnessBridge {
642
756
  this.#generateReqId = generateStreamId;
643
757
  this.#fileUploadTimeoutMs = Math.min(fileUploadTimeoutMs, DEFAULT_FILE_UPLOAD_TIMEOUT_MS);
644
758
  this.#signal = signal;
759
+ this.#fetchImpl = fetchImpl;
645
760
  this.#deferred = createDeferredDeliveryCoordinator({ harness, state, signal, logger,
646
761
  deliver: (entry, outcome) => this.#deliverDeferredOutcome(entry, outcome),
647
762
  });
@@ -652,6 +767,13 @@ export class WecomHarnessBridge {
652
767
  return structuredClone(this.#status);
653
768
  }
654
769
 
770
+ #inboundMessage(frame) {
771
+ return wecomInboundMessage(frame, this.#client, {
772
+ fetchImpl: this.#fetchImpl,
773
+ logger: this.#logger,
774
+ });
775
+ }
776
+
655
777
  async #showMain(frame) {
656
778
  const previousFailure = this.#status.lastMessageError;
657
779
  const key = conversationKey(frame);
@@ -901,11 +1023,12 @@ export class WecomHarnessBridge {
901
1023
  return { message: t('当前任务仍在运行,请先停止任务或等待任务完成后再开启新会话。') };
902
1024
  }
903
1025
  if (command === '/new') {
904
- await this.#state.clearSession(key);
905
- return { message: t('已开启新会话。请发送你的问题。') };
1026
+ const created = await createConversationSession({ state: this.#state, harness: this.#harness, key });
1027
+ return { message: created.failed ? t('暂时无法创建新会话,请稍后重试。') : t('已开启新会话。请发送你的问题。') };
906
1028
  }
907
1029
  return await runWorkspaceCommand(text, this.#harness, key)
908
1030
  ?? await runClearCommand(text, this.#harness, this.#state, key, options)
1031
+ ?? await runResetCommand(text, this.#harness, this.#state, key, options)
909
1032
  ?? await runCompactCommand(text, this.#harness, this.#state, key, options);
910
1033
  }
911
1034
 
@@ -924,7 +1047,7 @@ export class WecomHarnessBridge {
924
1047
 
925
1048
  const key = conversationKey(frame);
926
1049
  const pending = this.#pendingInteractions.get(key);
927
- const commandMessage = wecomInboundMessage(frame, this.#client);
1050
+ const commandMessage = this.#inboundMessage(frame);
928
1051
  const commandText = nonEmptyString(commandMessage.content) ?? '';
929
1052
  const conversationType = body.chattype === 'single' ? 'direct' : 'group';
930
1053
  const access = evaluateInboundAccess(this.#accessPolicy, {
@@ -989,6 +1112,7 @@ export class WecomHarnessBridge {
989
1112
  && (parseWecomMenu(commandText) || ['/help', '/status', '/new'].includes(commandText.toLowerCase())
990
1113
  || this.#cardFrames.has(frame));
991
1114
  const commandRunner = isClearCommand(commandText) ? runClearCommand
1115
+ : isResetCommand(commandText) ? runResetCommand
992
1116
  : isPermissionCommand(commandText) ? runPermissionCommand
993
1117
  : isHistoryCommand(commandText) ? runHistoryCommand
994
1118
  : hasInboundFiles(commandMessage) ? null : isControlCommand(commandText)
@@ -1114,7 +1238,7 @@ export class WecomHarnessBridge {
1114
1238
  // WeCom image URLs expire after five minutes, while a conversation turn
1115
1239
  // may legally stay queued longer. Start the authenticated SDK download as
1116
1240
  // soon as the validated callback is accepted, then consume it in order.
1117
- const inboundMessage = wecomInboundMessage(frame, this.#client);
1241
+ const inboundMessage = prefetchQuotedFiles(this.#inboundMessage(frame), this.#signal);
1118
1242
  const directCount = inboundMessage.images.length;
1119
1243
  const quoteContents = isSharedLocalCommand(inboundMessage.content, {
1120
1244
  hasImages: hasInboundImages(inboundMessage),
@@ -1360,7 +1484,7 @@ export class WecomHarnessBridge {
1360
1484
  this.#status.messagesReceived += 1;
1361
1485
  this.#status.lastMessageAt = new Date().toISOString();
1362
1486
  }
1363
- const message = preparedMessage ?? wecomInboundMessage(frame, this.#client);
1487
+ const message = preparedMessage ?? this.#inboundMessage(frame);
1364
1488
  const text = message.content;
1365
1489
  const hasImages = hasInboundImages(message);
1366
1490
  const hasFiles = hasInboundFiles(message);
@@ -1391,9 +1515,42 @@ export class WecomHarnessBridge {
1391
1515
  await this.#state.markSeen(messageId);
1392
1516
  return;
1393
1517
  }
1394
- if (!hasImages && !hasFiles && command === '/new') {
1395
- await this.#state.clearSession(key);
1396
- await this.#sendImmediate(frame, chatId, t('已开启新会话。请发送你的问题。'));
1518
+ if (!hasImages && !hasFiles && isNewCommand(text)) {
1519
+ const created = await createConversationSession({ state: this.#state, harness: this.#harness, key, title: newCommandTitle(text) });
1520
+ await this.#sendImmediate(frame, chatId, created.failed ? t('暂时无法创建新会话,请稍后重试。') : t('已开启新会话。请发送你的问题。'));
1521
+ await this.#state.markSeen(messageId);
1522
+ return;
1523
+ }
1524
+ if (!hasImages && !hasFiles && isSessionNavCommand(text)) {
1525
+ const nav = await runSessionNavTextCommand(text, this.#harness, this.#state, key, {
1526
+ signal: this.#signal,
1527
+ });
1528
+ if (nav) {
1529
+ for (const reply of nav.messages ?? [nav.message]) {
1530
+ await this.#sendImmediate(frame, chatId, reply);
1531
+ }
1532
+ if (nav.askText) {
1533
+ const followUp = this.#enqueueMessage(
1534
+ {
1535
+ ...frame,
1536
+ body: {
1537
+ ...(frame?.body ?? {}),
1538
+ msgtype: 'text',
1539
+ text: { content: nav.askText },
1540
+ mixed: undefined,
1541
+ image: undefined,
1542
+ voice: undefined,
1543
+ },
1544
+ },
1545
+ `${messageId}-ask`,
1546
+ key,
1547
+ );
1548
+ followUp.catch((error) => {
1549
+ this.#logger.warn?.(`[dsh-im:wecom] follow-up ask after a nav command failed:`, error?.message ?? error);
1550
+ this.#sendImmediate(frame, chatId, t('切换后的提问发送失败,请重试。')).catch(() => undefined);
1551
+ });
1552
+ }
1553
+ }
1397
1554
  await this.#state.markSeen(messageId);
1398
1555
  return;
1399
1556
  }
@@ -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, unlink, writeFile } from 'node:fs/promises';
3
4
  import { dirname } from 'node:path';
4
5
 
@@ -12,6 +13,10 @@ function normalizeState(value) {
12
13
  if (typeof key === 'string' && typeof sessionId === 'string' && sessionId) sessions[key] = sessionId;
13
14
  }
14
15
  }
16
+ // A file written before the navigation ring existed loads unchanged: the keys
17
+ // are only added when they hold something.
18
+ const rings = normalizeSessionRings(value.rings);
19
+ const pendingTitles = normalizePendingTitles(value.pendingTitles);
15
20
  return {
16
21
  version: 1,
17
22
  sessions,
@@ -19,6 +24,8 @@ function normalizeState(value) {
19
24
  seenMessageIds: Array.isArray(value.seenMessageIds)
20
25
  ? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000)
21
26
  : [],
27
+ ...(Object.keys(rings).length ? { rings } : {}),
28
+ ...(Object.keys(pendingTitles).length ? { pendingTitles } : {}),
22
29
  };
23
30
  }
24
31
 
@@ -30,8 +37,13 @@ export class WecomAppStateStore {
30
37
 
31
38
  constructor(path) {
32
39
  this.#path = path;
40
+ // The navigation ring is a view over this store's state, shared with the
41
+ // channels that inherit `ConversationStateStore`.
42
+ Object.assign(this, createSessionRingSupport({
43
+ state: () => this.#state,
44
+ persist: () => this.#persist(),
45
+ }));
33
46
  }
34
-
35
47
  async load() {
36
48
  try {
37
49
  this.#state = normalizeState(JSON.parse(await readFile(this.#path, 'utf8')));