@xmanrui/dsh-im 5.4.0 → 5.6.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 (105) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +46 -5
  4. package/README.md +46 -5
  5. package/lib/client.js +2579 -664
  6. package/lib/index.js +406 -339
  7. package/package.json +4 -4
  8. package/plugin-src/client/channel-card-meta.js +6 -2
  9. package/plugin-src/client/channels/dingtalk/index.js +12 -9
  10. package/plugin-src/client/channels/feishu/group-settings.js +5 -5
  11. package/plugin-src/client/channels/feishu/index.js +33 -25
  12. package/plugin-src/client/channels/qq/index.js +5 -5
  13. package/plugin-src/client/channels/shared/token-api.js +25 -7
  14. package/plugin-src/client/channels/shared/token-channel.js +18 -11
  15. package/plugin-src/client/channels/telegram/styles.js +4 -0
  16. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  17. package/plugin-src/client/channels/wecom/index.js +5 -5
  18. package/plugin-src/client/channels/wecom-app/index.js +3 -3
  19. package/plugin-src/client/channels/weixin/index.js +2 -2
  20. package/plugin-src/client/channels/whatsapp/index.js +6 -6
  21. package/plugin-src/client/credential-binding.js +3 -2
  22. package/plugin-src/client/delivery-settings.js +4 -4
  23. package/plugin-src/client/ds-bot-settings.js +3 -3
  24. package/plugin-src/client/global-settings.js +5 -2
  25. package/plugin-src/client/i18n-ru.js +1637 -0
  26. package/plugin-src/client/i18n.js +281 -124
  27. package/plugin-src/client/index.js +8 -1
  28. package/plugin-src/host/channels/shared/production.mjs +5 -0
  29. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  30. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  31. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  32. package/plugin-src/host/channels/telegram/production.mjs +7 -0
  33. package/plugin-src/host/delivery-adapter.mjs +41 -33
  34. package/plugin-src/host/delivery-service.mjs +42 -0
  35. package/plugin-src/host/ds-bot-client.mjs +31 -18
  36. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  37. package/plugin-src/host/index.mjs +3 -0
  38. package/plugin-src/host/modern-harness-api.mjs +53 -8
  39. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  40. package/scripts/verify-package.mjs +18 -6
  41. package/src/channels/dingtalk/dingtalk-bridge.mjs +1 -0
  42. package/src/channels/feishu/bridge.mjs +107 -7
  43. package/src/channels/feishu/feishu-cards.mjs +1 -45
  44. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  45. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  46. package/src/channels/feishu/slash-command-panel.mjs +2 -5
  47. package/src/channels/qq/qq-bridge.mjs +1 -0
  48. package/src/channels/shared/AGENTS.md +19 -0
  49. package/src/channels/shared/bot-workspace-store.mjs +1 -1
  50. package/src/channels/shared/clear-command.mjs +2 -1
  51. package/src/channels/shared/command-catalog.mjs +8 -5
  52. package/src/channels/shared/compact-command.mjs +2 -1
  53. package/src/channels/shared/conversation-queue.mjs +49 -0
  54. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  55. package/src/channels/shared/delivery-failure-log.mjs +111 -0
  56. package/src/channels/shared/diagnostic-details.mjs +1 -0
  57. package/src/channels/shared/harness-client.mjs +16 -9
  58. package/src/channels/shared/history-command.mjs +2 -1
  59. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  60. package/src/channels/shared/i18n-en/shared-b.mjs +7 -2
  61. package/src/channels/shared/i18n-en/shared-c.mjs +6 -2
  62. package/src/channels/shared/i18n-en/telegram.mjs +6 -0
  63. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  64. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  65. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  66. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  67. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  68. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  69. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  70. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  71. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  72. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  73. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  74. package/src/channels/shared/i18n-ru/shared-b.mjs +262 -0
  75. package/src/channels/shared/i18n-ru/shared-c.mjs +176 -0
  76. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  77. package/src/channels/shared/i18n-ru/telegram.mjs +30 -0
  78. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  79. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  80. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  81. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  82. package/src/channels/shared/i18n-ru.mjs +48 -0
  83. package/src/channels/shared/i18n.mjs +47 -12
  84. package/src/channels/shared/inbound-access.mjs +1 -1
  85. package/src/channels/shared/interface-language.mjs +3 -3
  86. package/src/channels/shared/message-failure.mjs +8 -4
  87. package/src/channels/shared/model-command.mjs +2 -1
  88. package/src/channels/shared/permission-command.mjs +2 -1
  89. package/src/channels/shared/send-limit.mjs +38 -0
  90. package/src/channels/shared/session-error.mjs +11 -0
  91. package/src/channels/shared/status-reaction.mjs +2 -0
  92. package/src/channels/shared/text-harness-bridge.mjs +205 -3
  93. package/src/channels/shared/thinking-cadence.mjs +36 -0
  94. package/src/channels/shared/workspace-command.mjs +43 -17
  95. package/src/channels/shared/workspace-labels.mjs +65 -0
  96. package/src/channels/shared/workspace-session.mjs +24 -4
  97. package/src/channels/telegram/config-store.mjs +34 -1
  98. package/src/channels/telegram/telegram-api.mjs +240 -32
  99. package/src/channels/telegram/telegram-bridge.mjs +62 -1
  100. package/src/channels/telegram/telegram-controller.mjs +29 -0
  101. package/src/channels/telegram/telegram-runtime.mjs +592 -179
  102. package/src/channels/telegram/voice.mjs +250 -0
  103. package/src/channels/wecom/wecom-bridge.mjs +1 -0
  104. package/src/channels/wecom-app/wecom-app-bridge.mjs +1 -0
  105. package/src/channels/weixin/weixin-bridge.mjs +1 -0
@@ -145,6 +145,8 @@ const UNWATCH_COMMAND = /^\/unwatch(?:\s+([^\s]+))?$/i;
145
145
  const WATCHLIST_COMMAND = /^\/watchlist$/i;
146
146
  const SESSION_LIST_PREFIX = /^\/(?:sessionlist|sessions)(?:\s|$)/i;
147
147
  const WORKSPACE_LIST_COMMAND = /^\/(?:workspacelist|workspaces|wsl)$/i;
148
+ // After the merge a bare /workspace or /ws opens the same picker card.
149
+ const BARE_WORKSPACE_COMMAND = /^\/(?:workspace|ws)$/i;
148
150
  const NUMBER_REPLY = /^\d{1,2}$/;
149
151
  /** A displayed menu stays number-tappable for this long. */
150
152
  const MENU_TTL_MS = 10 * 60_000;
@@ -1894,7 +1896,7 @@ export class FeishuHarnessBridge {
1894
1896
  );
1895
1897
  return;
1896
1898
  }
1897
- if (WORKSPACE_LIST_COMMAND.test(commandText)) {
1899
+ if (BARE_WORKSPACE_COMMAND.test(commandText) || WORKSPACE_LIST_COMMAND.test(commandText)) {
1898
1900
  await this.#showWorkspaces({ chatId: event.message.chat_id, key, replyTo: event.message.message_id });
1899
1901
  return;
1900
1902
  }
@@ -2016,7 +2018,12 @@ export class FeishuHarnessBridge {
2016
2018
  }
2017
2019
  throw error;
2018
2020
  } finally {
2019
- await this.#cancelPendingInteraction(key);
2021
+ // Synced questions (including DS Bot's ask_user) outlive the turn that
2022
+ // presented them. Only turn-owned questions belong to this cleanup;
2023
+ // their failed-delivery/error paths must still resolve by cancellation.
2024
+ if (this.#pendingInteractions.get(key)?.lifecycle !== 'session-sync') {
2025
+ await this.#cancelPendingInteraction(key);
2026
+ }
2020
2027
  await this.#approvals.closeRoute(key);
2021
2028
  this.#voiceTurns.delete(key);
2022
2029
  }
@@ -5564,6 +5571,7 @@ export class FeishuHarnessBridge {
5564
5571
  let completed;
5565
5572
  try {
5566
5573
  completed = await askInWorkspaceSession({
5574
+ onNotice: (notice) => this.#send(chatId, notice, { replyTo: messageId }),
5567
5575
  deferredDelivery: () => ({ coordinator: this.#deferred, chatId, replyToMessageId: messageId }),
5568
5576
  harness: this.#harness,
5569
5577
  state: this.#state,
@@ -5814,6 +5822,7 @@ export class FeishuHarnessBridge {
5814
5822
  const { content, contextEnhanced } = prompt;
5815
5823
  if (!this.#channel?.stream) {
5816
5824
  const { sessionId, answer, artifacts = [] } = await askInWorkspaceSession({
5825
+ onNotice: (notice) => this.#send(chatId, notice, { replyTo: messageId }),
5817
5826
  deferredDelivery: () => ({ coordinator: this.#deferred, chatId, replyToMessageId: messageId }),
5818
5827
  harness: this.#harness,
5819
5828
  state: this.#state,
@@ -5897,6 +5906,7 @@ export class FeishuHarnessBridge {
5897
5906
  },
5898
5907
  };
5899
5908
  const completed = await askInWorkspaceSession({
5909
+ onNotice: (notice) => this.#send(chatId, notice, { replyTo: messageId }),
5900
5910
  deferredDelivery: () => ({ coordinator: this.#deferred, chatId, replyToMessageId: messageId }),
5901
5911
  harness: this.#harness,
5902
5912
  state: this.#state,
@@ -5972,6 +5982,7 @@ export class FeishuHarnessBridge {
5972
5982
 
5973
5983
  this.#logger.warn?.('[dsh-feishu] native stream unavailable; using text fallback:', error.message);
5974
5984
  const { sessionId, answer, artifacts = [] } = await askInWorkspaceSession({
5985
+ onNotice: (notice) => this.#send(chatId, notice, { replyTo: messageId }),
5975
5986
  deferredDelivery: () => ({ coordinator: this.#deferred, chatId, replyToMessageId: messageId }),
5976
5987
  harness: this.#harness,
5977
5988
  state: this.#state,
@@ -6078,6 +6089,7 @@ export class FeishuHarnessBridge {
6078
6089
  });
6079
6090
  }
6080
6091
  pending.chatId = event.message.chat_id;
6092
+ pending.receiveIdType = 'chat_id';
6081
6093
  if (pending.needsPresentation) {
6082
6094
  try {
6083
6095
  await this.#presentInteraction(pending);
@@ -6133,9 +6145,17 @@ export class FeishuHarnessBridge {
6133
6145
  }
6134
6146
 
6135
6147
  async #submitQuestionAnswer(pending, answerText, { chatId, messageId, questionMessageId } = {}) {
6148
+ const expectedIndex = pending.index;
6149
+ try { if (pending.validate) await pending.validate(); }
6150
+ catch {
6151
+ if (chatId) await this.#send(chatId, INTERACTION_RESOLVED_TEXT(), { replyTo: messageId }).catch(() => undefined);
6152
+ return;
6153
+ }
6154
+ if (pending.inactive || pending.submitting || pending.index !== expectedIndex) return;
6136
6155
  const question = pending.questions[pending.index];
6137
6156
  if (!question) return;
6138
6157
  pending.chatId = chatId ?? pending.chatId;
6158
+ if (chatId) pending.receiveIdType = 'chat_id';
6139
6159
 
6140
6160
  // issue #162:已答状态卡以推进前的题号渲染,并整卡替换原提问卡。
6141
6161
  const answeredIndex = pending.index;
@@ -6270,12 +6290,72 @@ export class FeishuHarnessBridge {
6270
6290
  });
6271
6291
  }
6272
6292
 
6293
+ /** Use the normal question/reply state machine without submitting a new IM prompt. */
6294
+ async presentSessionSyncQuestion(interaction, context, { signal, completion } = {}) {
6295
+ if (signal?.aborted || this.#signal?.aborted || this.#hasPendingInteraction(context.key)) return false;
6296
+ let finished = false;
6297
+ const cleanup = () => {
6298
+ finished = true;
6299
+ signal?.removeEventListener('abort', finish);
6300
+ this.#signal?.removeEventListener('abort', onStop);
6301
+ };
6302
+ const finish = () => {
6303
+ const pending = this.#pendingInteractions.get(context.key);
6304
+ if (pending?.interactionId === interaction.interactionId) {
6305
+ this.#rememberResolvedInteraction(context.key, pending);
6306
+ this.#clearPendingInteraction(context.key, pending.interactionId);
6307
+ }
6308
+ cleanup();
6309
+ };
6310
+ const withdraw = async () => {
6311
+ finish();
6312
+ await interaction.withdraw?.();
6313
+ };
6314
+ const onStop = () => {
6315
+ void withdraw().catch((error) => this.#logger.warn?.('[dsh-feishu] question withdrawal failed:', error?.code));
6316
+ };
6317
+ const validate = async () => {
6318
+ try {
6319
+ await context.validate?.();
6320
+ if (finished || signal?.aborted || this.#signal?.aborted
6321
+ || (!this.#accessPolicy && !this.#allowedSenderOpenIds.has('*')
6322
+ && !this.#allowedSenderOpenIds.has(context.actor))
6323
+ || !context.actor || !evaluateInboundAccess(this.#accessPolicy, {
6324
+ conversationType: 'direct', senderIds: [context.actor], text: 'yes',
6325
+ }).allowed) throw new Error('Question recipient is no longer available');
6326
+ } catch (cause) {
6327
+ await withdraw();
6328
+ throw Object.assign(new Error('Question is no longer answerable', { cause }), { code: 'interaction-not-pending' });
6329
+ }
6330
+ };
6331
+ signal?.addEventListener('abort', finish, { once: true });
6332
+ this.#signal?.addEventListener('abort', onStop, { once: true });
6333
+ Promise.resolve(completion).then(finish, finish);
6334
+ try {
6335
+ await validate();
6336
+ await this.#handleInteraction(interaction, {
6337
+ ...context, validate, onClear: cleanup, lifecycle: 'session-sync',
6338
+ });
6339
+ if (finished) finish(); // A completion during delivery must not leave a pending behind.
6340
+ const available = !finished && this.#pendingInteractions.get(context.key)?.interactionId === interaction.interactionId;
6341
+ if (!available) cleanup();
6342
+ return available;
6343
+ } catch (error) {
6344
+ await withdraw();
6345
+ throw error;
6346
+ }
6347
+ }
6348
+
6273
6349
  async #handleInteraction(interaction, {
6274
6350
  key,
6275
6351
  actor,
6276
6352
  chatId,
6277
6353
  requiresMention,
6278
6354
  replyToMessageId,
6355
+ receiveIdType,
6356
+ validate,
6357
+ onClear,
6358
+ lifecycle = 'turn',
6279
6359
  }) {
6280
6360
  if (await this.#approvals.handleRequested(interaction, this.#approvalContext({
6281
6361
  key, actor, chatId, requiresMention, replyToMessageId,
@@ -6322,6 +6402,10 @@ export class FeishuHarnessBridge {
6322
6402
  }
6323
6403
  if (this.#interactionKeys.has(interactionId)) return;
6324
6404
  if (existing) {
6405
+ if (interaction.withdraw) {
6406
+ await interaction.withdraw();
6407
+ return;
6408
+ }
6325
6409
  await interaction.respond({
6326
6410
  ok: false,
6327
6411
  error: {
@@ -6346,6 +6430,10 @@ export class FeishuHarnessBridge {
6346
6430
  index: 0,
6347
6431
  chatId,
6348
6432
  replyToMessageId,
6433
+ receiveIdType,
6434
+ validate,
6435
+ onClear,
6436
+ lifecycle,
6349
6437
  queue: null,
6350
6438
  claimedReplyMessageId: null,
6351
6439
  submitting: false,
@@ -6371,6 +6459,8 @@ export class FeishuHarnessBridge {
6371
6459
  }
6372
6460
 
6373
6461
  async #presentInteraction(pending) {
6462
+ if (pending.validate) await pending.validate();
6463
+ if (pending.inactive) return;
6374
6464
  const question = pending.questions[pending.index];
6375
6465
  if (!question) return;
6376
6466
  const options = Array.isArray(question?.options) ? question.options : [];
@@ -6398,7 +6488,7 @@ export class FeishuHarnessBridge {
6398
6488
  index: pending.index,
6399
6489
  total: pending.questions.length,
6400
6490
  }),
6401
- { key: pending.key, replyTo: pending.replyToMessageId },
6491
+ { key: pending.key, replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6402
6492
  ).then((sent) => {
6403
6493
  presentedAsCard = true;
6404
6494
  return sent;
@@ -6406,12 +6496,14 @@ export class FeishuHarnessBridge {
6406
6496
  // Fall back to the plain-text question if the card cannot be sent.
6407
6497
  // If the text send also fails, let the error propagate so the pending
6408
6498
  // question is not marked as presented and the existing retry logic runs.
6499
+ if (pending.inactive) return null;
6500
+ if (pending.validate) await pending.validate();
6409
6501
  return this.#send(
6410
6502
  pending.chatId,
6411
6503
  harnessQuestionText(question, pending.index, pending.questions.length, {
6412
6504
  requiresMention: pending.requiresMention,
6413
6505
  }),
6414
- { replyTo: pending.replyToMessageId },
6506
+ { replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6415
6507
  );
6416
6508
  });
6417
6509
  } else {
@@ -6424,7 +6516,7 @@ export class FeishuHarnessBridge {
6424
6516
  pending.questions.length,
6425
6517
  { requiresMention: pending.requiresMention },
6426
6518
  ),
6427
- { replyTo: pending.replyToMessageId },
6519
+ { replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6428
6520
  );
6429
6521
  }
6430
6522
  if (messageId) {
@@ -6478,6 +6570,7 @@ export class FeishuHarnessBridge {
6478
6570
  this.#pendingInteractions.delete(key);
6479
6571
  this.#interactionKeys.delete(pending.interactionId);
6480
6572
  pending.inactive = true;
6573
+ pending.onClear?.();
6481
6574
  return pending;
6482
6575
  }
6483
6576
 
@@ -6490,6 +6583,13 @@ export class FeishuHarnessBridge {
6490
6583
  if (!pending || pending.kind !== 'question') return;
6491
6584
  this.#rememberResolvedInteraction(key, pending);
6492
6585
  try {
6586
+ // A synced question is owned by its upstream provider, not this IM turn.
6587
+ // Withdraw the IM route so the provider also releases its delivery state;
6588
+ // DS Bot's answer endpoint does not accept a Harness cancellation answer.
6589
+ if (pending.lifecycle === 'session-sync' && pending.interaction.withdraw) {
6590
+ await pending.interaction.withdraw();
6591
+ return;
6592
+ }
6493
6593
  await pending.interaction.respond({
6494
6594
  ok: false,
6495
6595
  error: {
@@ -6534,7 +6634,7 @@ export class FeishuHarnessBridge {
6534
6634
  else processingReaction.success();
6535
6635
  }
6536
6636
 
6537
- async #send(chatId, text, { replyTo } = {}) {
6637
+ async #send(chatId, text, { replyTo, receiveIdType = 'chat_id' } = {}) {
6538
6638
  const content = JSON.stringify({ text });
6539
6639
  if (replyTo) {
6540
6640
  try {
@@ -6563,7 +6663,7 @@ export class FeishuHarnessBridge {
6563
6663
  }
6564
6664
  }
6565
6665
  const response = await this.#client.im.v1.message.create({
6566
- params: { receive_id_type: 'chat_id' },
6666
+ params: { receive_id_type: receiveIdType },
6567
6667
  data: {
6568
6668
  receive_id: chatId,
6569
6669
  msg_type: 'text',
@@ -14,8 +14,8 @@
14
14
  * without button callbacks.
15
15
  */
16
16
 
17
- import { posix, win32 } from 'node:path';
18
17
  import { t } from '../shared/i18n.mjs';
18
+ import { workspaceLabels } from '../shared/workspace-labels.mjs';
19
19
  import { normalizeFeishuStepCardPanels } from './step-push-mode.mjs';
20
20
 
21
21
  export const MENU_PAGE_SIZE = 10;
@@ -97,50 +97,6 @@ function safeTitle(value) {
97
97
  return cleanTitle(value) || t('暂无标题');
98
98
  }
99
99
 
100
- const WORKSPACE_LABEL_LENGTH = 22;
101
-
102
- /** Display labels only: paths and their snapshot order remain the callback identity. */
103
- function workspaceLabels(paths, titles = {}) {
104
- const entries = paths.map((path) => {
105
- const api = /^[a-z]:[\\/]|^\\\\/iu.test(path) ? win32 : posix;
106
- const normalized = api.normalize(path);
107
- const name = cleanTitle(api.basename(normalized) || api.parse(normalized).root);
108
- const base = (typeof titles[path] === 'string' && cleanTitle(titles[path])) || name;
109
- return {
110
- api, base, label: base, parent: api.dirname(normalized),
111
- context: base === name ? '' : api.basename(normalized),
112
- };
113
- });
114
- const counts = () => {
115
- const result = new Map();
116
- for (const { label } of entries) result.set(label, (result.get(label) ?? 0) + 1);
117
- return result;
118
- };
119
- // Grow only ambiguous path suffixes; stop at the root even if display text collides.
120
- for (;;) {
121
- const repeated = counts();
122
- let changed = false;
123
- for (const entry of entries) {
124
- if (repeated.get(entry.label) < 2 || entry.parent === null) continue;
125
- const { api, parent } = entry;
126
- entry.context = api.join(api.basename(parent) || parent, entry.context);
127
- entry.label = `${entry.base} · ${cleanTitle(entry.context)}`;
128
- const next = api.dirname(parent);
129
- entry.parent = next === parent ? null : next;
130
- changed = true;
131
- }
132
- if (!changed) break;
133
- }
134
- for (const entry of entries) {
135
- const chars = Array.from(entry.label);
136
- if (chars.length > WORKSPACE_LABEL_LENGTH) {
137
- entry.label = `${chars.slice(0, 11).join('')}…${chars.slice(-10).join('')}`;
138
- }
139
- }
140
- const repeated = counts();
141
- return entries.map(({ label }) => ({ label, numbered: repeated.get(label) > 1 }));
142
- }
143
-
144
100
  function cardWith(headerText, elements) {
145
101
  return JSON.stringify({
146
102
  schema: '2.0',
@@ -713,6 +713,16 @@ export class FeishuRuntime {
713
713
  }, options);
714
714
  }
715
715
 
716
+ async presentSessionSyncQuestion(target, interaction, options = {}) {
717
+ if (!this.#status.ready || !this.#bridge || target?.kind !== 'user') return false;
718
+ const actor = nonEmptyString(target.route?.openId);
719
+ if (!actor) return false;
720
+ return this.#bridge.presentSessionSyncQuestion(interaction, {
721
+ key: options.key, actor, validate: options.validate,
722
+ chatId: actor, receiveIdType: 'open_id', requiresMention: false,
723
+ }, options);
724
+ }
725
+
716
726
  async sendProactiveText(target, text, { signal, format = 'plain', receipt = false } = {}) {
717
727
  if (!this.#status.ready || !this.#client) {
718
728
  const error = new Error('飞书机器人尚未连接');
@@ -731,6 +731,18 @@ export class MultiBotDshFeishuController {
731
731
  });
732
732
  }
733
733
 
734
+ async presentSessionSyncQuestion(botId, target, interaction, options = {}) {
735
+ this.#assertOpen();
736
+ return this.#withBotTransition(botId, async () => {
737
+ this.#assertOpen();
738
+ this.#requireBot(botId);
739
+ const runtime = this.#runtimes.get(botId);
740
+ if (!isConnected(connectionStatus(runtime))
741
+ || typeof runtime.presentSessionSyncQuestion !== 'function') return false;
742
+ return runtime.presentSessionSyncQuestion(target, interaction, options);
743
+ });
744
+ }
745
+
734
746
  async disconnectBot(botId) {
735
747
  this.#assertOpen();
736
748
  // An operational pause only: credentials/config remain durable, so the
@@ -32,16 +32,13 @@ export const SLASH_COMMAND_MANIFEST = Object.freeze([
32
32
  { command: 'compact', icon: 'ai-block_outlined', default: '压缩当前会话上下文', en_us: 'Compact the current session' },
33
33
  { command: 'clear', icon: 'clear_outlined', default: '清空当前会话上下文', en_us: 'Clear the current session context' },
34
34
  { command: 'sessionlist', icon: 'chat-ai_outlined', default: '列出会话', en_us: 'List sessions' },
35
- { command: 'workspacelist', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
36
- { command: 'workspaces', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
37
- { command: 'wsl', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
38
- { command: 'ws', icon: 'folder_outlined', default: '切换工作区', en_us: 'Switch workspace' },
35
+ { command: 'ws', icon: 'folder_outlined', default: '查看并切换工作区', en_us: 'View and switch workspace' },
39
36
  { command: 'watch', icon: 'flag_outlined', default: '关注一个会话', en_us: 'Watch a session' },
40
37
  { command: 'unwatch', icon: 'clear_outlined', default: '取消关注会话', en_us: 'Unwatch a session' },
41
38
  { command: 'watchlist', icon: 'flag_outlined', default: '查看关注列表', en_us: 'List watched sessions' },
42
39
  { command: 'archived', icon: 'folder_outlined', default: '设置归档会话显隐(on/off)', en_us: 'Show or hide archived sessions (on/off)' },
43
40
  { command: 'history', icon: 'chat-ai_outlined', default: '查看最近历史消息(仅私聊)', en_us: 'Show recent history (private chats only)' },
44
- { command: 'workspace', icon: 'folder_outlined', default: '切换工作区', en_us: 'Switch workspace' },
41
+ { command: 'workspace', icon: 'folder_outlined', default: '查看并切换工作区', en_us: 'View and switch workspace' },
45
42
  { command: 'conv', icon: 'folder_outlined', default: '设置当前对话专属工作区', en_us: 'Set the workspace for this conversation' },
46
43
  { command: 'session', icon: 'chat-ai_outlined', default: '绑定已有会话', en_us: 'Bind an existing session' },
47
44
  { command: 'models', icon: 'ai-functions_outlined', default: '列出可用模型', en_us: 'List available models' },
@@ -1272,6 +1272,7 @@ export class QqHarnessBridge {
1272
1272
  // already own.
1273
1273
  await this.#markPendingSubmitted(key, messageId);
1274
1274
  ({ answer, artifacts = [] } = await askInWorkspaceSession({
1275
+ onNotice: (notice) => this.#bot.sendText(target, notice),
1275
1276
  deferredDelivery: () => ({ coordinator: this.#deferred, target: { scope: target.scope, targetId: target.targetId } }),
1276
1277
  harness: this.#harness,
1277
1278
  state: this.#state,
@@ -0,0 +1,19 @@
1
+ # Translating host-side text
2
+
3
+ Host-side user-facing text is written inline in Chinese and passed to `t()` from
4
+ `i18n.mjs`. Chinese is the identity language, so the source literal itself is
5
+ the dictionary key: `t('中文')` renders that Chinese string unless a dictionary
6
+ carries the very same string.
7
+
8
+ - A new source string must be added to EVERY dictionary that exists here: each
9
+ `i18n-<lang>/` area module and the `i18n-<lang>.mjs` module that merges them.
10
+ A language added later inherits the same rule, no code change needed.
11
+ - The key must be the exact literal, byte for byte, including `\n` and the
12
+ names of `{placeholders}`.
13
+ - Placeholders stay byte-identical in the translation. Never rename, translate
14
+ or drop one.
15
+ - Product and channel names (DSH, Cordis, Feishu, Telegram, Slack, Discord,
16
+ WeCom, QQ, Weixin, WhatsApp, Matrix, DingTalk, email) are never translated.
17
+ - `test/channels/shared/i18n-coverage.test.mjs` enforces this rule: a literal
18
+ with no entry in a dictionary fails the build and names the file that added
19
+ it. A prose rule alone would not.
@@ -1651,7 +1651,7 @@ export function createBotWorkspaceScope(
1651
1651
  const dsBinding = (key) => workspaces.dsBotBindingFor?.(botId, key);
1652
1652
  const assertNoDsBinding = (key) => {
1653
1653
  if (dsBinding(key)) {
1654
- throw deliveryTargetError('ds-bot-bound', '请先在“绑定bot”中解除绑定,再切换会话或工作目录。');
1654
+ throw deliveryTargetError('ds-bot-bound', t('请先在“绑定 DS Bot”中解除绑定,再切换会话或工作目录。'));
1655
1655
  }
1656
1656
  };
1657
1657
  const presetSettings = async (catalog = agentPresetCatalog) => {
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { t } from './i18n.mjs';
2
3
  import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
3
4
 
@@ -10,7 +11,7 @@ function commandResult(message) {
10
11
 
11
12
  function clearErrorMessage(error) {
12
13
  const code = error?.code ?? error?.failure?.code;
13
- if (code === 'session-not-found') {
14
+ if (isSessionNotFound(code)) {
14
15
  return t('当前聊天绑定的会话已不存在,未清空上下文;请先发送新消息开启会话。');
15
16
  }
16
17
  if (code === 'agent-busy' || code === 'pending-interaction') {
@@ -35,18 +35,21 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
35
35
  defineCatalogCommand('history', '查看最近历史消息(仅私聊)', [
36
36
  '/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)',
37
37
  ], { privateOnly: true }),
38
- defineCatalogCommand('workspace', '切换工作区', [
38
+ // Merged listing+switch command: no argument opens the picker, an argument
39
+ // switches directly. /wsl and friends stay accepted but leave the menu so
40
+ // there is one workspace entry to choose from.
41
+ defineCatalogCommand('workspace', '查看或切换工作区', [
42
+ '/workspace 或 /ws 查看可切换的工作区(点按钮切换)',
39
43
  '/workspace 工作区序号或绝对路径 切换工作区',
40
- ], { aliases: ['ws'] }),
44
+ ], { aliases: [{ name: 'ws', menuVisible: false }] }),
41
45
  defineCatalogCommand('conv', '设置当前对话专属工作区', [
42
46
  '/conv 或 /conversation 查看当前对话工作区',
43
47
  '/conv 工作区绝对路径或序号 设置当前对话专属工作区',
44
48
  '/conv clear 清除专属工作区,回到 bot 默认工作区',
45
49
  ], { aliases: ['conversation', 'thread'] }),
46
50
  defineCatalogCommand('workspacelist', '列出工作区绝对路径', [
47
- '/workspacelist 列出工作区绝对路径',
48
- '/ws、/wsl、/workspaces 工作区命令别名',
49
- ], { aliases: ['workspaces', 'wsl'] }),
51
+ '/workspacelist、/wsl、/workspaces 工作区列表别名(等同 /ws)',
52
+ ], { aliases: ['workspaces', 'wsl'], menuVisible: false }),
50
53
  defineCatalogCommand('sessionlist', '列出会话 ID 和标题', [
51
54
  '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
52
55
  '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { t } from './i18n.mjs';
2
3
  import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
3
4
 
@@ -51,7 +52,7 @@ function compactResultText(result) {
51
52
 
52
53
  function compactErrorMessage(error) {
53
54
  const code = error?.code ?? error?.failure?.code;
54
- if (code === 'session-not-found') {
55
+ if (isSessionNotFound(code)) {
55
56
  return t('当前聊天绑定的会话已不存在,请发送新消息开启会话。');
56
57
  }
57
58
  if (code === 'agent-busy') return t('当前会话正在生成回复,请稍后重试。');
@@ -0,0 +1,49 @@
1
+ // conversation-queue.mjs — serialise work per conversation without blocking others.
2
+ //
3
+ // A channel may need to do expensive prep work (audio download and
4
+ // transcription, for example) before a message reaches the Harness. Awaiting it
5
+ // inside the transport loop stalls every other conversation and the update
6
+ // cursor alike, so the work is queued per conversation instead: ordering inside
7
+ // one chat is preserved, other chats and callbacks proceed immediately.
8
+
9
+ /**
10
+ * Create a per-key promise chain.
11
+ *
12
+ * @param {{ onError?: (error: unknown, key: string) => void }} options
13
+ * @returns {{ run: (key: string, task: () => Promise<unknown>) => Promise<unknown>,
14
+ * idle: (key?: string) => Promise<void>, size: () => number }}
15
+ */
16
+ export function createConversationQueue({ onError = null } = {}) {
17
+ /** @type {Map<string, Promise<unknown>>} */
18
+ const chains = new Map();
19
+
20
+ const run = (key, task) => {
21
+ const previous = chains.get(key) ?? Promise.resolve();
22
+ const next = previous
23
+ .catch(() => {})
24
+ .then(() => task())
25
+ .catch((error) => {
26
+ onError?.(error, key);
27
+ })
28
+ .finally(() => {
29
+ // The tail of the chain is dropped once it settles, so a quiet
30
+ // conversation holds no state.
31
+ if (chains.get(key) === next) chains.delete(key);
32
+ });
33
+ chains.set(key, next);
34
+ return next;
35
+ };
36
+
37
+ return {
38
+ run,
39
+ async idle(key) {
40
+ if (key === undefined) {
41
+ while (chains.size > 0) await Promise.all([...chains.values()]);
42
+ return;
43
+ }
44
+ const chain = chains.get(key);
45
+ if (chain) await chain;
46
+ },
47
+ size: () => chains.size,
48
+ };
49
+ }
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { createDeferredDeliveryRegistry, extractCompletedTurnAnswer } from './deferred-delivery.mjs';
2
3
  import { t } from './i18n.mjs';
3
4
  import { channelDeliveryFailure } from './message-failure.mjs';
@@ -159,7 +160,7 @@ export function createDeferredDeliveryCoordinator({
159
160
  return 'delivered';
160
161
  } catch (error) {
161
162
  if (activeSignal.aborted) return 'none';
162
- if (error?.code === 'session-not-found') { await remove(entry); return 'none'; }
163
+ if (isSessionNotFound(error?.code)) { await remove(entry); return 'none'; }
163
164
  const current = await pending(id);
164
165
  if (!current) return 'none';
165
166
  if (!sending) {
@@ -0,0 +1,111 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ /**
4
+ * One structured log line per failed or unconfirmed delivery.
5
+ *
6
+ * The reference id in the notice a user sees (`MF-…`) used to live only on
7
+ * screen: when a real `CHANNEL_DELIVERY_UNCERTAIN` notice appeared, nothing in
8
+ * the log explained it, so the id the user quoted back could not be traced.
9
+ * This module writes the same id, the attempt history and the full text of the
10
+ * part that failed into the local log, so the next occurrence is diagnosable.
11
+ *
12
+ * The line is a single string on purpose: a logger that pretty-prints an object
13
+ * would break it across many lines and make it impossible to grep by id.
14
+ */
15
+
16
+ /** `MF-` plus eight characters of a UUID: the id a user can quote back. */
17
+ export function createFailureReferenceId() {
18
+ return `MF-${randomUUID().slice(0, 8).toUpperCase()}`;
19
+ }
20
+
21
+ // A bot token looks like `1234:AA…` and must never reach a log line. Only
22
+ // platform descriptions pass through the scrubber; message text is logged
23
+ // verbatim because "what could not be sent" is the whole point of the record.
24
+ const TOKEN_SHAPE = /bot\d+:[A-Za-z0-9_-]{20,}/gu;
25
+
26
+ function safeText(value) {
27
+ return typeof value === 'string' && value ? value.replace(TOKEN_SHAPE, 'bot<redacted>') : null;
28
+ }
29
+
30
+ function attemptRecord(value) {
31
+ if (!value || typeof value !== 'object') return null;
32
+ const status = Number(value.status);
33
+ const retryAfter = Number(value.retry_after ?? value.retryAfter);
34
+ const attempt = Number(value.attempt);
35
+ return {
36
+ attempt: Number.isInteger(attempt) ? attempt : null,
37
+ method: typeof value.method === 'string' && value.method ? value.method : null,
38
+ status: Number.isInteger(status) ? status : null,
39
+ description: safeText(value.description ?? value.message),
40
+ retry_after: Number.isFinite(retryAfter) ? retryAfter : null,
41
+ };
42
+ }
43
+
44
+ function partRecord(value) {
45
+ if (!value || typeof value !== 'object') return null;
46
+ const index = Number(value.index);
47
+ const text = typeof value.text === 'string' ? value.text : null;
48
+ const length = Number(value.length);
49
+ const messageId = value.message_id ?? value.messageId ?? null;
50
+ return {
51
+ index: Number.isInteger(index) ? index : null,
52
+ length: Number.isInteger(length) ? length : (text?.length ?? 0),
53
+ message_id: messageId === null || messageId === undefined ? null : String(messageId),
54
+ // The text is kept for parts the platform never confirmed: those are the
55
+ // ones nobody can find in the chat afterwards.
56
+ ...(text ? { text } : {}),
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Build the log line for one failure object that carries a `referenceId`.
62
+ *
63
+ * `evidence` is what the channel could observe about the send itself (attempt
64
+ * history, per-part message ids, chat topic, markup mode). Channels without it
65
+ * still get a line, just a shorter one.
66
+ */
67
+ export function deliveryFailureLogLine(channelKey, failure, evidence = null) {
68
+ const detail = evidence && typeof evidence === 'object' ? evidence : {};
69
+ const attempts = (Array.isArray(detail.attempts) ? detail.attempts : [])
70
+ .map(attemptRecord)
71
+ .filter(Boolean);
72
+ const parts = (Array.isArray(detail.parts) ? detail.parts : [])
73
+ .map(partRecord)
74
+ .filter(Boolean);
75
+ const failedPart = Number(detail.failed_part ?? detail.failedPart);
76
+ const record = {
77
+ referenceId: failure?.referenceId ?? null,
78
+ code: failure?.code ?? null,
79
+ reason: failure?.reason ?? null,
80
+ provider_reason: safeText(detail.provider_reason ?? detail.reason),
81
+ deliveryOutcome: detail.deliveryOutcome ?? failure?.deliveryOutcome ?? null,
82
+ attempt_count: attempts.length,
83
+ attempts,
84
+ chat_id: detail.chat_id === undefined || detail.chat_id === null ? null : String(detail.chat_id),
85
+ message_thread_id: Number.isInteger(detail.message_thread_id) ? detail.message_thread_id : null,
86
+ parse_mode: detail.parse_mode ?? null,
87
+ failed_part: Number.isInteger(failedPart) ? failedPart : null,
88
+ parts,
89
+ };
90
+ return `[dsh-im:${channelKey}] delivery failed [${failure?.referenceId ?? 'unknown'}]: `
91
+ + JSON.stringify(record);
92
+ }
93
+
94
+ /** Failure codes that describe a send, not something that happened before it. */
95
+ const DELIVERY_FAILURE_CODES = new Set([
96
+ 'CHANNEL_DELIVERY',
97
+ 'CHANNEL_DELIVERY_UNCERTAIN',
98
+ 'CHANNEL_PERMISSION',
99
+ 'CHANNEL_RATE_LIMIT',
100
+ ]);
101
+
102
+ /** Emit the line through whatever logger the channel was given. */
103
+ export function logDeliveryFailure(logger, channelKey, failure, evidence = null) {
104
+ if (!failure?.referenceId) return null;
105
+ // Other failures already log their own diagnostics; this line exists for the
106
+ // notices whose reference id would otherwise never reach the log.
107
+ if (!evidence && !DELIVERY_FAILURE_CODES.has(failure.code)) return null;
108
+ const line = deliveryFailureLogLine(channelKey, failure, evidence);
109
+ (logger?.error ?? logger?.warn)?.call(logger, line);
110
+ return line;
111
+ }
@@ -13,6 +13,7 @@ const STAGES = new Set([
13
13
  'runtime.prepare', 'activation', 'harness.check', 'connection.start', 'connection.poll', 'connection.stop', 'status.read', 'rollback', 'management.request',
14
14
  ]);
15
15
  const REASONS = new Set([
16
+ 'session-log-corrupt',
16
17
  'stream-closed-before-open', 'stream-failed-before-open', 'stream-failed',
17
18
  'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT', 'EPIPE',
18
19
  'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_SOCKET',