@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
@@ -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 { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
4
5
  import { dirname } from 'node:path';
@@ -17,6 +18,7 @@ export const DINGTALK_RECENT_OUTBOUND_LIMIT = 200;
17
18
  export const DINGTALK_RECENT_OUTBOUND_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
18
19
  export const DINGTALK_RECENT_OUTBOUND_TEXT_LIMIT = 8_000;
19
20
  export const DINGTALK_RECENT_OUTBOUND_MATCH_TOLERANCE_MS = 15_000;
21
+ const AUTHOR_LIMIT = 500;
20
22
 
21
23
  function nonEmptyString(value) {
22
24
  return typeof value === 'string' && value.trim() ? value.trim() : null;
@@ -85,6 +87,27 @@ function normalizePendingSender(value, fallbackRequestId) {
85
87
  };
86
88
  }
87
89
 
90
+ function normalizeAuthor(value) {
91
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
92
+ const senderId = typeof value.senderId === 'string' ? value.senderId : '';
93
+ if (!senderId) return null;
94
+ const author = { senderId, isBot: value.isBot === true };
95
+ if (typeof value.senderName === 'string' && value.senderName) author.senderName = value.senderName;
96
+ if (typeof value.senderUsername === 'string' && value.senderUsername) author.senderUsername = value.senderUsername;
97
+ if (typeof value.at === 'string' && value.at) author.at = value.at;
98
+ return author;
99
+ }
100
+
101
+ function normalizeAuthors(value) {
102
+ const authors = {};
103
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return authors;
104
+ for (const key of Object.keys(value).slice(-AUTHOR_LIMIT)) {
105
+ const author = normalizeAuthor(value[key]);
106
+ if (author) authors[key] = author;
107
+ }
108
+ return authors;
109
+ }
110
+
88
111
  function normalizeState(value) {
89
112
  if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
90
113
  const sessions = {};
@@ -112,15 +135,23 @@ function normalizeState(value) {
112
135
  }
113
136
  }
114
137
 
138
+ // A file written before the navigation ring existed loads unchanged: the keys
139
+ // are only added when they hold something.
140
+ const rings = normalizeSessionRings(value.rings);
141
+ const pendingTitles = normalizePendingTitles(value.pendingTitles);
142
+ const authors = normalizeAuthors(value.authors);
115
143
  return {
116
144
  version: 1,
117
145
  sessions,
146
+ ...(Object.keys(authors).length ? { authors } : {}),
118
147
  ...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
119
148
  seenMessageIds: Array.isArray(value.seenMessageIds)
120
149
  ? [...new Set(value.seenMessageIds.map(nonEmptyString).filter(Boolean))].slice(-1_000)
121
150
  : [],
122
151
  pendingSenders,
123
152
  recentOutboundMessages: recentOutboundMessages(value.recentOutboundMessages),
153
+ ...(Object.keys(rings).length ? { rings } : {}),
154
+ ...(Object.keys(pendingTitles).length ? { pendingTitles } : {}),
124
155
  };
125
156
  }
126
157
 
@@ -140,6 +171,12 @@ export class DingtalkStateStore {
140
171
  this.#path = path;
141
172
  this.#idFactory = idFactory;
142
173
  this.#now = now;
174
+ // The navigation ring is a view over this store's state, shared with the
175
+ // channels that inherit `ConversationStateStore`.
176
+ Object.assign(this, createSessionRingSupport({
177
+ state: () => this.#state,
178
+ persist: () => this.#persist(),
179
+ }));
143
180
  }
144
181
 
145
182
  async load() {
@@ -162,6 +199,25 @@ export class DingtalkStateStore {
162
199
  return this.#state.sessions[key] ?? null;
163
200
  }
164
201
 
202
+ authorFor(key) {
203
+ const author = this.#state.authors?.[key];
204
+ return author ? structuredClone(author) : null;
205
+ }
206
+
207
+ async rememberAuthor(key, value) {
208
+ const author = normalizeAuthor({ at: this.#now(), ...value });
209
+ if (typeof key !== 'string' || !key || !author) return null;
210
+ const authors = this.#state.authors ??= {};
211
+ delete authors[key];
212
+ authors[key] = author;
213
+ const keys = Object.keys(authors);
214
+ if (keys.length > AUTHOR_LIMIT) {
215
+ for (const stale of keys.slice(0, keys.length - AUTHOR_LIMIT)) delete authors[stale];
216
+ }
217
+ await this.#persist();
218
+ return structuredClone(author);
219
+ }
220
+
165
221
  async setSession(key, sessionId) {
166
222
  const normalizedKey = nonEmptyString(key);
167
223
  const normalizedSession = nonEmptyString(sessionId);
@@ -73,8 +73,9 @@ function delay(ms, signal) {
73
73
  reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
74
74
  return;
75
75
  }
76
+ // Deliberately NOT unref'd: a rate-limit backoff is the only thing the caller
77
+ // is waiting for, so the timer must keep the loop alive until it fires.
76
78
  const timer = setTimeout(resolve, ms);
77
- timer?.unref?.();
78
79
  signal?.addEventListener('abort', () => {
79
80
  clearTimeout(timer);
80
81
  reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
@@ -3,9 +3,9 @@ import { BusyMessageDispatcher, canAutomaticallySteer } from '../shared/busy-mes
3
3
  import { isPermissionCommand, runPermissionCommand } from '../shared/permission-command.mjs';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { chunkMarkdownText } from '../shared/markdown-chunks.mjs';
6
- import QRCode from 'qrcode';
6
+ import QRCode from '../shared/qrcode.mjs';
7
7
  import { waitForFeishuOperation } from './feishu-channel.mjs';
8
- import { startNewConversation } from '../shared/new-command.mjs';
8
+ import { startNewConversation, isNewCommand, newCommandTitle } from '../shared/new-command.mjs';
9
9
  import {
10
10
  conversationKey,
11
11
  conversationScope,
@@ -17,6 +17,7 @@ import {
17
17
  managedTopicKey,
18
18
  managedTopicRoot,
19
19
  splitText,
20
+ stripLocalImageMarkdown,
20
21
  } from './message-utils.mjs';
21
22
  import {
22
23
  hasInboundImages,
@@ -48,6 +49,7 @@ import {
48
49
  } from '../shared/batch-input.mjs';
49
50
  import { runCompactCommand } from '../shared/compact-command.mjs';
50
51
  import { isClearCommand, runClearCommand } from '../shared/clear-command.mjs';
52
+ import { isResetCommand, runResetCommand } from '../shared/reset-command.mjs';
51
53
  import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
52
54
  import {
53
55
  isControlCommand,
@@ -63,12 +65,17 @@ import {
63
65
  runPresetCommand,
64
66
  } from '../shared/preset-command.mjs';
65
67
  import {
68
+ boundSessionIdFor,
66
69
  parseSessionListArgument,
67
70
  resolveSessionListWorkspace,
68
71
  runWorkspaceCommand,
69
72
  workspacePathSnapshot,
70
73
  } from '../shared/workspace-command.mjs';
71
74
  import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
75
+ import {
76
+ isSessionNavCommand,
77
+ runSessionNavTextCommand,
78
+ } from '../shared/session-nav-command.mjs';
72
79
  import { createDeferredDeliveryCoordinator, deferredOutcomeText } from '../shared/deferred-delivery-coordinator.mjs';
73
80
  import {
74
81
  captureContextEnhancement,
@@ -128,6 +135,7 @@ import {
128
135
  normalizeFeishuStepPushMode,
129
136
  normalizeFeishuStepCardPanels,
130
137
  } from './step-push-mode.mjs';
138
+ import { normalizeReplyContent } from '../shared/reply-content.mjs';
131
139
  import { FeishuLiveCot } from './live-cot.mjs';
132
140
 
133
141
  // Lazily evaluated: t() must run after setImHostLanguage, not at import time.
@@ -251,51 +259,25 @@ const STEP_STREAM_PANEL_MAX_BYTES = 12_000;
251
259
  /** One thinking note is excerpted to this many characters inside its panel. */
252
260
  const STEP_STREAM_NOTE_MAX_CHARS = 500;
253
261
 
254
- /** Split one markdown answer into post-sized chunks at paragraph bounds,
255
- * budgeted by the encoded rich-text content rather than the source string.
256
- * This accounts for both CJK bytes and JSON escape expansion. */
262
+ /** Split independently rendered posts with the shared structure-aware splitter.
263
+ * Budget the serialized payload, including reopened fences and JSON escapes.
264
+ * Retry from the original source when lowering the character bound so that
265
+ * generated fences are never mistaken for source content on a second split. */
257
266
  function splitStepPostMarkdown(text, limit = STEP_PUSH_POST_CHUNK_MAX_BYTES) {
258
267
  const source = String(text ?? '');
259
268
  const encodedBytes = (markdown) => Buffer.byteLength(JSON.stringify({
260
269
  zh_cn: { content: [[{ tag: 'md', text: markdown }]] },
261
270
  }), 'utf8');
262
271
  if (encodedBytes(source) <= limit) return [source];
263
- const chunks = [];
264
- let remaining = source;
265
- while (encodedBytes(remaining) > limit) {
266
- let lo = 0;
267
- let hi = remaining.length;
268
- while (lo < hi) {
269
- const mid = (lo + hi + 1) >> 1;
270
- if (encodedBytes(remaining.slice(0, mid)) <= limit) lo = mid;
271
- else hi = mid - 1;
272
- }
273
- let cut = lo;
274
- const preferFrom = Math.floor(cut * 0.6);
275
- const softCut = remaining.lastIndexOf('\n\n', cut);
276
- if (softCut >= preferFrom) {
277
- cut = softCut;
278
- } else {
279
- const lineCut = remaining.lastIndexOf('\n', cut);
280
- if (lineCut >= preferFrom) cut = lineCut;
281
- }
282
- if (cut <= 0) cut = lo;
283
- // JavaScript indexes strings by UTF-16 code unit. Never split between a
284
- // high and low surrogate, which would turn one emoji into two replacement
285
- // characters across adjacent messages.
286
- const before = remaining.charCodeAt(cut - 1);
287
- const after = remaining.charCodeAt(cut);
288
- if (before >= 0xD800 && before <= 0xDBFF && after >= 0xDC00 && after <= 0xDFFF) {
289
- cut -= 1;
290
- }
291
- if (cut <= 0) {
292
- throw new RangeError('Feishu step push post byte limit is too small');
293
- }
294
- chunks.push(remaining.slice(0, cut));
295
- remaining = remaining.slice(cut).trimStart();
296
- }
297
- if (remaining) chunks.push(remaining);
298
- return chunks;
272
+ const overhead = encodedBytes('');
273
+ let bound = limit - overhead;
274
+ while (bound > 0) {
275
+ const chunks = chunkMarkdownText(source, bound);
276
+ const largest = chunks.reduce((size, chunk) => Math.max(size, encodedBytes(chunk)), 0);
277
+ if (largest <= limit) return chunks;
278
+ bound = Math.min(bound - 1, Math.floor(bound * (limit - overhead) / (largest - overhead)));
279
+ }
280
+ throw new RangeError('Feishu step push post byte limit is too small');
299
281
  }
300
282
  /** Salient tool-argument fields for the intent summary, in priority order. */
301
283
  const STEP_PUSH_INTENT_FIELDS = [
@@ -397,9 +379,10 @@ function isBareMentionMessage(event) {
397
379
  /** Canonical workspace/session help advertised by every bridge family. */
398
380
  const WORKSPACE_HELP_LINES = [
399
381
  '/workspace 工作区序号或绝对路径 切换工作区',
400
- '/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话',
382
+ '/session Session ID、当前工作区序号或标题关键词 将当前聊天绑定到指定会话',
401
383
  '/workspacelist 列出工作区绝对路径',
402
384
  '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
385
+ '/sessionlist --all 跨工作区汇总会话(每个工作区默认显示 10 个,可用 --limit N 调整)',
403
386
  '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
404
387
  ];
405
388
 
@@ -1800,6 +1783,22 @@ export class FeishuHarnessBridge {
1800
1783
  const message = extractInboundMessage(event, this.#client);
1801
1784
  let text = message.content;
1802
1785
  let voiceTurnReplyTo = null;
1786
+ // 入站卡片(interactive)在事件里只带卡片标题,正文要靠 raw_card_content
1787
+ // 再读一次——与引用卡片走同一条路径(feishuReplyReference)。把读到的正文
1788
+ // 并回 message.content 后,后续命令识别、访问判定与 #answerWithStream
1789
+ // 都从 content 取文本,与文字消息完全一致。
1790
+ if (message.card) {
1791
+ try {
1792
+ const loaded = await message.card.load({ signal: this.#signal });
1793
+ const cardBody = nonEmptyString(loaded?.content);
1794
+ if (cardBody && cardBody.length > (text?.length ?? 0)) {
1795
+ text = cardBody;
1796
+ message.content = cardBody;
1797
+ }
1798
+ } catch (error) {
1799
+ this.#logger.warn?.('[dsh-feishu-card] 卡片正文读取失败:', error?.message ?? String(error));
1800
+ }
1801
+ }
1803
1802
  // 语音输入(渠道能力):音频消息先转写成文字并写回 message.content——
1804
1803
  // 下方命令识别与 #answerWithStream 都从 content 取文本。转写失败(或返回
1805
1804
  // 空文本)时保持原语义,走"仅支持文字、图片和文件"的明确降级提示。
@@ -1889,7 +1888,7 @@ export class FeishuHarnessBridge {
1889
1888
  await this.#sendMenuCard(key, event.message.chat_id, { replyTo: event.message.message_id });
1890
1889
  return;
1891
1890
  }
1892
- if (commandText === '/new') {
1891
+ if (isNewCommand(commandText)) {
1893
1892
  if (this.#queues.has(key) || this.#hasPendingInteraction(key)) {
1894
1893
  await this.#send(
1895
1894
  event.message.chat_id,
@@ -1900,6 +1899,7 @@ export class FeishuHarnessBridge {
1900
1899
  }
1901
1900
  await this.#send(event.message.chat_id, await startNewConversation({
1902
1901
  state: this.#state, harness: this.#harness, key,
1902
+ title: newCommandTitle(commandText),
1903
1903
  }), { replyTo: event.message.message_id });
1904
1904
  await this.#sendMenuCard(key, event.message.chat_id, { replyTo: event.message.message_id });
1905
1905
  return;
@@ -1908,6 +1908,36 @@ export class FeishuHarnessBridge {
1908
1908
  await this.#showStatusText(key, event.message.chat_id, event.message.message_id);
1909
1909
  return;
1910
1910
  }
1911
+ if (isSessionNavCommand(commandText)) {
1912
+ const nav = await runSessionNavTextCommand(commandText, this.#harness, this.#state, key, {
1913
+ signal: this.#signal,
1914
+ });
1915
+ if (nav) {
1916
+ for (const reply of nav.messages ?? [nav.message]) {
1917
+ await this.#send(event.message.chat_id, reply, { replyTo: event.message.message_id });
1918
+ }
1919
+ if (nav.askText) {
1920
+ const followUp = this.#enqueueMessage(
1921
+ {
1922
+ ...event,
1923
+ message: {
1924
+ ...event.message,
1925
+ message_type: 'text',
1926
+ content: JSON.stringify({ text: nav.askText }),
1927
+ },
1928
+ },
1929
+ `${messageId}-ask`,
1930
+ key,
1931
+ null,
1932
+ );
1933
+ followUp.catch((error) => {
1934
+ this.#logger.warn?.(`[dsh-im:feishu] follow-up ask after a nav command failed:`, error?.message ?? error);
1935
+ this.#send(event.message.chat_id, t('切换后的提问发送失败,请重试。'), { replyTo: event.message.message_id }).catch(() => undefined);
1936
+ });
1937
+ }
1938
+ }
1939
+ return;
1940
+ }
1911
1941
  if (commandText === '/compact') {
1912
1942
  const compactCommand = await runCompactCommand(commandText, this.#harness, this.#state, key, { signal: this.#signal });
1913
1943
  if (compactCommand) {
@@ -1928,6 +1958,19 @@ export class FeishuHarnessBridge {
1928
1958
  }
1929
1959
  return;
1930
1960
  }
1961
+ if (isResetCommand(rawCommandText)) {
1962
+ const resetCommand = await runResetCommand(rawCommandText, this.#harness, this.#state, key, {
1963
+ signal: this.#signal,
1964
+ hasImages,
1965
+ hasFiles,
1966
+ pendingInteraction: this.#hasPendingInteraction(key),
1967
+ busy: this.#queues.has(key),
1968
+ });
1969
+ if (resetCommand) {
1970
+ await this.#send(event.message.chat_id, resetCommand.message, { replyTo: event.message.message_id });
1971
+ }
1972
+ return;
1973
+ }
1931
1974
  if (SESSION_LIST_PREFIX.test(commandText)) {
1932
1975
  const argument = commandText.replace(/^\/(?:sessionlist|sessions)/i, '').trim();
1933
1976
  const request = parseSessionListArgument(argument);
@@ -1935,6 +1978,13 @@ export class FeishuHarnessBridge {
1935
1978
  await this.#send(event.message.chat_id, request.error, { replyTo: event.message.message_id });
1936
1979
  return;
1937
1980
  }
1981
+ if (request.all) {
1982
+ const result = await runWorkspaceCommand(text, this.#harness, key);
1983
+ for (const reply of result.messages ?? [result.message]) {
1984
+ await this.#send(event.message.chat_id, reply, { replyTo: event.message.message_id });
1985
+ }
1986
+ return;
1987
+ }
1938
1988
  await this.#showSessions(
1939
1989
  { chatId: event.message.chat_id, key, replyTo: event.message.message_id },
1940
1990
  request.selector || null,
@@ -3224,7 +3274,7 @@ export class FeishuHarnessBridge {
3224
3274
  });
3225
3275
  await this.#sendCard(
3226
3276
  chatId,
3227
- sessionListCard(workspace, sessions, safePage, sessions.length, watchedSet),
3277
+ sessionListCard(workspace, sessions, safePage, sessions.length, watchedSet, boundSessionIdFor(this.#state, key)),
3228
3278
  {
3229
3279
  key,
3230
3280
  updateMessageId,
@@ -4681,10 +4731,21 @@ export class FeishuHarnessBridge {
4681
4731
  if (round.finished) return;
4682
4732
  round.finished = true;
4683
4733
  this.#goalRounds.delete(round.key);
4684
- await this.#finishStepCard(round.key, {
4734
+ const sealed = await this.#finishStepCard(round.key, {
4685
4735
  stopped: reason === 'stopped' || reason === 'aborted' || reason === 'cancelled',
4686
4736
  answerText: round.assistant.text,
4687
4737
  });
4738
+ // Unlike an IM turn, a continuation round has no second delivery path:
4739
+ // when the card cannot be sealed (broken render, lost message) the result
4740
+ // would vanish, so post it as a plain reply instead.
4741
+ if (sealed?.ok) return;
4742
+ const answer = stripLocalImageMarkdown(String(round.assistant.text ?? '')).trim();
4743
+ if (!answer) return;
4744
+ this.#logger.warn?.(
4745
+ '[dsh-feishu] goal round card seal failed; replying with the result:',
4746
+ mirrorErrorText(sealed?.error),
4747
+ );
4748
+ await this.#send(round.chatId, answer, { replyTo: round.replyToMessageId }).catch(() => undefined);
4688
4749
  }
4689
4750
 
4690
4751
  #onHarnessEvent({ sessionId, event }) {
@@ -4881,6 +4942,18 @@ export class FeishuHarnessBridge {
4881
4942
  });
4882
4943
  }
4883
4944
 
4945
+ async #sendAnswerMarkdown(chatId, answer, { deliveryId, presentation, replyTo }) {
4946
+ const providerMessageIds = [];
4947
+ // 最终答案保留 Markdown;复用富文本投递的限流重试、话题路由与纯文本兜底。
4948
+ for (const chunk of splitStepPostMarkdown(answer)) {
4949
+ this.#signal?.throwIfAborted();
4950
+ const result = await this.#sendStepPost(chatId, replyTo, [[{ tag: 'md', text: chunk }]], chunk);
4951
+ if (!result.ok) throw result.error ?? new Error('Feishu final answer delivery failed');
4952
+ if (result.messageId) providerMessageIds.push(result.messageId);
4953
+ }
4954
+ return createDeliveryReceipt({ deliveryId, presentation, providerMessageIds });
4955
+ }
4956
+
4884
4957
  // 语音回复(渠道能力):同回合转写过语音消息的会话,在完整答案投递后追加
4885
4958
  // 音频回复。回合按会话 key 登记并消费——同群不同话题各自只消费自己的
4886
4959
  // 回合;登记随消息处理结束(finally)清除,命令类回复(菜单、会话列表等)
@@ -5170,12 +5243,17 @@ export class FeishuHarnessBridge {
5170
5243
 
5171
5244
  /** Replace the draft interval with `text` chunked into splitter-safe blocks. */
5172
5245
  #writeStepCardAnswer(card, text) {
5246
+ // Feishu rejects the whole card update when a Markdown image points at a
5247
+ // local file (`![x](/tmp/x.png)` -> 230099 / 200570), which freezes the
5248
+ // card mid-turn. Images the reader must see are uploaded separately; the
5249
+ // text keeps their caption instead.
5250
+ const safeText = stripLocalImageMarkdown(text);
5173
5251
  // JSON can expand one UTF-16 unit to six bytes (for example a control
5174
5252
  // character). Leave room for the element wrapper, and let the existing
5175
5253
  // Markdown splitter reopen fences in each independently rendered block.
5176
- const chunks = Buffer.byteLength(JSON.stringify(text), 'utf8') + 128 <= STEP_STREAM_ANSWER_CHUNK_MAX_BYTES
5177
- ? [text]
5178
- : chunkMarkdownText(text, Math.floor((STEP_STREAM_ANSWER_CHUNK_MAX_BYTES - 128) / 6));
5254
+ const chunks = Buffer.byteLength(JSON.stringify(safeText), 'utf8') + 128 <= STEP_STREAM_ANSWER_CHUNK_MAX_BYTES
5255
+ ? [safeText]
5256
+ : chunkMarkdownText(safeText, Math.floor((STEP_STREAM_ANSWER_CHUNK_MAX_BYTES - 128) / 6));
5179
5257
  const blocks = chunks
5180
5258
  .map((chunk) => ({ kind: 'message', text: chunk }));
5181
5259
  if (card.answerStart !== null) {
@@ -5330,7 +5408,14 @@ export class FeishuHarnessBridge {
5330
5408
  try {
5331
5409
  await card.renderChain?.catch?.(() => {});
5332
5410
  } catch { /* the seal below decides what the user sees */ }
5333
- if (card.broken) return { ok: false, error: card.lastError };
5411
+ if (card.broken) {
5412
+ // The card froze on an earlier failed render; callers must fall back.
5413
+ this.#logger.warn?.(
5414
+ '[dsh-feishu] step streaming card is broken; the seal was skipped:',
5415
+ mirrorErrorText(card.lastError),
5416
+ );
5417
+ return { ok: false, error: card.lastError };
5418
+ }
5334
5419
  const status = stopped ? 'stopped' : 'completed';
5335
5420
  const body = typeof answerText === 'string' ? answerText : '';
5336
5421
  // Whether the answer was already visible from a streamed draft render —
@@ -5675,6 +5760,7 @@ export class FeishuHarnessBridge {
5675
5760
  async #preparePrompt(event, key, message) {
5676
5761
  const snapshot = this.#acceptedMessageIds.get(event.message.message_id);
5677
5762
  const originalFiles = Array.isArray(message.files) ? [...message.files] : [];
5763
+ const originalImages = Array.isArray(message.images) ? [...message.images] : [];
5678
5764
  const build = async (input) => {
5679
5765
  const rich = hasInboundImages(input) || hasReplyReference(input);
5680
5766
  const original = rich
@@ -5682,6 +5768,7 @@ export class FeishuHarnessBridge {
5682
5768
  signal: this.#signal,
5683
5769
  deferImages: true,
5684
5770
  originalFiles,
5771
+ originalImages,
5685
5772
  })
5686
5773
  : input.content;
5687
5774
  const enhanced = enhanceContextContent(original, snapshot, () => ({
@@ -5795,11 +5882,16 @@ export class FeishuHarnessBridge {
5795
5882
  // post 模式维持逐条直推。先预建卡片状态,纯问答回合也能在收尾时开卡。
5796
5883
  // 飞书原生思考过程按 chat_id 创建,不会落进话题(#244);话题内的回合改用
5797
5884
  // 实时过程卡(以 reply_in_thread 回复留在话题内),避免过程出现在话题外。
5885
+ // 只发最终回答的回合(三项内容全关)不能留下任何过程呈现:原生思考过程、
5886
+ // 实时过程卡与"思考中"心跳都是过程内容,答案出现即是唯一消息。
5887
+ const replyContent = normalizeReplyContent(this.#harness.currentReplyContent?.());
5888
+ const answerOnly = !replyContent.narration && !replyContent.tools && !replyContent.thinking;
5798
5889
  const liveCotInTopic = this.#stepPushMode === FEISHU_STEP_PUSH_MODES.LIVE_COT
5799
5890
  && this.#replyInThreadFor(messageId);
5800
- const streamingCard = this.#stepPushMode === FEISHU_STEP_PUSH_MODES.STREAMING_CARD
5801
- || liveCotInTopic;
5802
- const liveCot = this.#stepPushMode === FEISHU_STEP_PUSH_MODES.LIVE_COT
5891
+ const streamingCard = !answerOnly
5892
+ && (this.#stepPushMode === FEISHU_STEP_PUSH_MODES.STREAMING_CARD || liveCotInTopic);
5893
+ const liveCot = !answerOnly
5894
+ && this.#stepPushMode === FEISHU_STEP_PUSH_MODES.LIVE_COT
5803
5895
  && !liveCotInTopic
5804
5896
  && typeof this.#channel?.createCot === 'function'
5805
5897
  && typeof this.#channel?.writeCotEvents === 'function';
@@ -5827,14 +5919,18 @@ export class FeishuHarnessBridge {
5827
5919
 
5828
5920
  // 上下文注入动作在详细级别下也体现为一条步骤(注入细节可忽略)。
5829
5921
  // 不计入工具/助手消息的熔断计数(规格口径:熔断只管「工具 + 助手」)。
5830
- if (contextEnhanced || content) {
5922
+ // 只发最终回答的回合连这条过程提示也不发。
5923
+ if (!answerOnly && (contextEnhanced || content)) {
5831
5924
  if (streamingCard) {
5832
5925
  await this.#appendStepCardUpdate(
5833
5926
  key, chatId, messageId,
5834
5927
  { kind: 'message', text: t('📎 已注入会话上下文') },
5835
5928
  { billable: false },
5836
5929
  );
5837
- } else {
5930
+ } else if (!liveCot) {
5931
+ // 实时直播模式下过程由飞书原生思考面板承载,而该面板要等本轮第一个
5932
+ // 进度事件才创建,此刻还没有可写入的容器;单独发一条 post 会落在
5933
+ // 直播面板之外,用户看到孤零零一句「已注入会话上下文」。
5838
5934
  await this.#sendStepMessage(
5839
5935
  chatId, key,
5840
5936
  [[{ tag: 'text', text: t('📎 已注入会话上下文') }]],
@@ -5865,7 +5961,7 @@ export class FeishuHarnessBridge {
5865
5961
  messageId,
5866
5962
  );
5867
5963
  };
5868
- const watchdog = streamingCard || liveCot
5964
+ const watchdog = streamingCard || liveCot || answerOnly
5869
5965
  ? null
5870
5966
  : this.#startThinkingStatusWatchdog(key, chatId, messageId);
5871
5967
  let completed;
@@ -6141,7 +6237,7 @@ export class FeishuHarnessBridge {
6141
6237
  let textReceipt;
6142
6238
  let textSendError = null;
6143
6239
  try {
6144
- textReceipt = await this.#sendAnswerText(
6240
+ textReceipt = await this.#sendAnswerMarkdown(
6145
6241
  chatId,
6146
6242
  answerTextForDelivery(answer, artifacts),
6147
6243
  {
@@ -6243,7 +6339,7 @@ export class FeishuHarnessBridge {
6243
6339
  let textReceipt;
6244
6340
  let textSendError = null;
6245
6341
  try {
6246
- textReceipt = await this.#sendAnswerText(
6342
+ textReceipt = await this.#sendAnswerMarkdown(
6247
6343
  chatId,
6248
6344
  answerTextForDelivery(completedAnswer, completedArtifacts),
6249
6345
  {
@@ -6301,7 +6397,7 @@ export class FeishuHarnessBridge {
6301
6397
  let textReceipt;
6302
6398
  let textSendError = null;
6303
6399
  try {
6304
- textReceipt = await this.#sendAnswerText(
6400
+ textReceipt = await this.#sendAnswerMarkdown(
6305
6401
  chatId,
6306
6402
  answerTextForDelivery(answer, artifacts),
6307
6403
  {
@@ -15,6 +15,7 @@
15
15
  */
16
16
 
17
17
  import { t } from '../shared/i18n.mjs';
18
+ import { SESSION_NAV_HELP_LINES } from '../shared/command-catalog.mjs';
18
19
  import { workspaceLabels } from '../shared/workspace-labels.mjs';
19
20
  import { normalizeFeishuStepCardPanels } from './step-push-mode.mjs';
20
21
 
@@ -591,12 +592,14 @@ export function menuHelpText() {
591
592
  '',
592
593
  '📋 会话 / 工作区',
593
594
  '/sessionlist 或 /sessions 列出工作区会话',
595
+ '/sessionlist --all 跨工作区汇总会话(每个工作区默认显示 10 个,可用 --limit N 调整)',
594
596
  '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
595
- '/session ID 绑定已有会话',
597
+ '/session Session ID、当前工作区序号或标题关键词 将当前聊天绑定到指定会话',
596
598
  '/workspacelist 列出工作区',
597
599
  '/workspace 工作区序号或绝对路径 切换工作区',
598
600
  '/ws、/wsl、/workspaces 工作区命令别名',
599
601
  '/new 开启全新会话',
602
+ ...SESSION_NAV_HELP_LINES.map((line) => t(line)),
600
603
  '',
601
604
  '📊 状态 / 压缩',
602
605
  '/status 连接状态',
@@ -662,8 +665,9 @@ const HELP_TEXT_COMMANDS = [
662
665
  '',
663
666
  '`/m` — 打开菜单卡片',
664
667
  '`/new` — 开启全新会话',
665
- '`/session ID` — 绑定已有会话',
668
+ '`/session Session ID、当前工作区序号或标题关键词` — 绑定已有会话',
666
669
  '`/sessionlist [工作区]` 或 `/sessions [工作区]` — 列出会话',
670
+ '`/sessionlist --all` 或 `/sessions --all` — 跨工作区汇总会话(每个工作区默认显示 10 个,可用 --limit N 调整)',
667
671
  '`/sessionlist --limit N` 或 `/sessions --limit N` — 仅列出当前工作区前 N 个会话',
668
672
  '`/workspace 工作区序号或绝对路径` — 切换工作区',
669
673
  '`/workspacelist` — 列出工作区',
@@ -763,7 +767,7 @@ export function cardActionProbeCard(nonce) {
763
767
  * in the label. `watchedSessionIds` is a Set-like of ids this conversation
764
768
  * already watches.
765
769
  */
766
- export function sessionListCard(workspace, sessions, page, total, watchedSessionIds = new Set()) {
770
+ export function sessionListCard(workspace, sessions, page, total, watchedSessionIds = new Set(), boundSessionId = '') {
767
771
  const start = page * MENU_PAGE_SIZE;
768
772
  const slice = sessions.slice(start, start + MENU_PAGE_SIZE);
769
773
  const pageCount = Math.max(1, Math.ceil(total / MENU_PAGE_SIZE));
@@ -788,7 +792,9 @@ export function sessionListCard(workspace, sessions, page, total, watchedSession
788
792
  })) },
789
793
  ...slice.map((session, offset) => {
790
794
  // Page-local numbering: number replies resolve against this page.
791
- const label = `${offset + 1}. ${safeTitle(session.title)}${session.archived === true ? t('(已归档)') : ''}`;
795
+ const label = `${offset + 1}. ${safeTitle(session.title)}`
796
+ + `${session.archived === true ? t('(已归档)') : ''}`
797
+ + `${session.sessionId === boundSessionId ? t('(当前绑定)') : ''}`;
792
798
  const watching = watched(session.sessionId);
793
799
  return row(
794
800
  buttonElement(watching ? t('⭐ 取消关注') : t('☆ 关注'), watching ? `unwatch:${session.sessionId}` : `watch:${session.sessionId}`),
@@ -9,9 +9,9 @@ import { normalizeFeishuStepPushMode, normalizeFeishuStepCardPanels } from './st
9
9
  import { createVoice } from './voice.mjs';
10
10
  import {
11
11
  syncSlashCommands,
12
- SLASH_COMMAND_MANIFEST,
13
12
  } from './slash-command-registry.mjs';
14
- import { normalizeSlashPanelConfig } from './slash-command-panel.mjs';
13
+ import { normalizeSlashPanelConfig, feishuSlashManifest } from './slash-command-panel.mjs';
14
+ import { channelCapabilities } from '../shared/channel-capabilities.mjs';
15
15
  import {
16
16
  connectionTestTargetUnavailable,
17
17
  sendRememberedConnectionTest,
@@ -148,6 +148,8 @@ export class FeishuRuntime {
148
148
  #slashCommands = true;
149
149
  /** Which commands the "/" panel should offer, and in which order. */
150
150
  #slashPanel = null;
151
+ /** Capability-narrowed manifest (no /fork without fork, honest /tail). */
152
+ #slashManifest = null;
151
153
  /** HTTP instance kept for panel re-syncs after startup. */
152
154
  #slashHttpInstance = null;
153
155
  /**
@@ -239,6 +241,12 @@ export class FeishuRuntime {
239
241
  this.#requestTimeoutMs = requestTimeoutMs;
240
242
  this.#slashCommands = consumerMode !== 'external-consumer' && Boolean(slashCommands);
241
243
  this.#slashPanel = normalizeSlashPanelConfig(slashPanel);
244
+ this.#slashManifest = feishuSlashManifest({
245
+ supportsFork: typeof harness?.supportsSessionFork === 'function'
246
+ ? harness.supportsSessionFork()
247
+ : true,
248
+ fileSend: channelCapabilities('feishu').fileSend,
249
+ });
242
250
  this.#wsAgent = wsAgent;
243
251
  this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'feishu', logger });
244
252
  this.#status = createBridgeStatus({ allowedSenderCount: normalizedOwners.length });
@@ -872,7 +880,7 @@ export class FeishuRuntime {
872
880
  domain: this.#domain,
873
881
  httpInstance,
874
882
  signal,
875
- manifest: SLASH_COMMAND_MANIFEST,
883
+ manifest: this.#slashManifest,
876
884
  config: this.#slashPanel,
877
885
  });
878
886
  // A newer panel config took over while this sync was running: its own run