@xmanrui/dsh-im 5.4.0 → 5.5.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 (79) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +44 -3
  4. package/README.md +44 -3
  5. package/lib/client.js +2293 -444
  6. package/lib/index.js +402 -335
  7. package/package.json +1 -1
  8. package/plugin-src/client/channel-card-meta.js +6 -2
  9. package/plugin-src/client/channels/shared/token-api.js +13 -0
  10. package/plugin-src/client/channels/telegram/styles.js +4 -0
  11. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  12. package/plugin-src/client/delivery-settings.js +2 -2
  13. package/plugin-src/client/i18n-ru.js +1615 -0
  14. package/plugin-src/client/i18n.js +71 -0
  15. package/plugin-src/client/index.js +8 -1
  16. package/plugin-src/host/channels/shared/production.mjs +5 -0
  17. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  18. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  19. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  20. package/plugin-src/host/channels/telegram/production.mjs +7 -0
  21. package/plugin-src/host/delivery-adapter.mjs +41 -33
  22. package/plugin-src/host/delivery-service.mjs +42 -0
  23. package/plugin-src/host/ds-bot-client.mjs +31 -18
  24. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  25. package/plugin-src/host/index.mjs +3 -0
  26. package/plugin-src/host/modern-harness-api.mjs +53 -8
  27. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  28. package/scripts/verify-package.mjs +17 -5
  29. package/src/channels/feishu/bridge.mjs +83 -5
  30. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  31. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  32. package/src/channels/shared/AGENTS.md +19 -0
  33. package/src/channels/shared/clear-command.mjs +2 -1
  34. package/src/channels/shared/compact-command.mjs +2 -1
  35. package/src/channels/shared/conversation-queue.mjs +49 -0
  36. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  37. package/src/channels/shared/harness-client.mjs +5 -4
  38. package/src/channels/shared/history-command.mjs +2 -1
  39. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  40. package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
  41. package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
  42. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  43. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  44. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  45. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  46. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  47. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  48. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  49. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  50. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  51. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  52. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  53. package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
  54. package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
  55. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  56. package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
  57. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  58. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  59. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  60. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  61. package/src/channels/shared/i18n-ru.mjs +48 -0
  62. package/src/channels/shared/i18n.mjs +47 -12
  63. package/src/channels/shared/inbound-access.mjs +1 -1
  64. package/src/channels/shared/interface-language.mjs +3 -3
  65. package/src/channels/shared/message-failure.mjs +3 -2
  66. package/src/channels/shared/model-command.mjs +2 -1
  67. package/src/channels/shared/permission-command.mjs +2 -1
  68. package/src/channels/shared/send-limit.mjs +38 -0
  69. package/src/channels/shared/session-error.mjs +3 -0
  70. package/src/channels/shared/status-reaction.mjs +2 -0
  71. package/src/channels/shared/text-harness-bridge.mjs +4 -0
  72. package/src/channels/shared/thinking-cadence.mjs +36 -0
  73. package/src/channels/shared/workspace-command.mjs +2 -1
  74. package/src/channels/telegram/config-store.mjs +34 -1
  75. package/src/channels/telegram/telegram-api.mjs +211 -32
  76. package/src/channels/telegram/telegram-bridge.mjs +4 -1
  77. package/src/channels/telegram/telegram-controller.mjs +29 -0
  78. package/src/channels/telegram/telegram-runtime.mjs +507 -176
  79. package/src/channels/telegram/voice.mjs +250 -0
@@ -510,7 +510,9 @@ class ModernHarnessApi {
510
510
  let subscription;
511
511
  subscription = new MuxSubscription(signal, () => this.#mux.delete(subscription));
512
512
  this.#mux.add(subscription);
513
- for (const pending of this.#pendingQuestions.values()) subscription.push(this.#questionFrame(pending));
513
+ for (const pending of this.#pendingQuestions.values()) {
514
+ if (pending.broadcast) subscription.push(this.#questionFrame(pending));
515
+ }
514
516
  for (const pending of this.#pendingApprovals.values()) {
515
517
  if (pending.broadcast !== false && pending.imAvailable !== false) subscription.push(this.#approvalFrame(pending));
516
518
  }
@@ -547,7 +549,9 @@ class ModernHarnessApi {
547
549
 
548
550
  #requestQuestion(request, next) {
549
551
  const owner = this.#claimableAgent(request?.agent);
550
- if (!owner) return next();
552
+ const sessionId = owner?.sessionId ?? request?.agent?.session?.id ?? request?.agent?.id;
553
+ if (typeof sessionId !== 'string'
554
+ || (!owner && typeof this.#deliveryService?.presentSessionSyncQuestion !== 'function')) return next();
551
555
  const turnSignal = request.signal;
552
556
  if (turnSignal?.aborted) {
553
557
  return Promise.reject(questionError(
@@ -581,11 +585,21 @@ class ModernHarnessApi {
581
585
  // request exclusively used to keep the question out of Web entirely, leaving
582
586
  // whoever happened to be looking at that Session with a card they could not
583
587
  // answer. Racing keeps both surfaces usable: the first answer wins.
584
- const im = this.#askThroughIm(request, owner);
588
+ const im = this.#askThroughIm(request, { sessionId }, { broadcast: Boolean(owner) });
589
+ let imAvailable = true;
590
+ let nativeError;
591
+ const withdraw = () => {
592
+ imAvailable = false;
593
+ im.withdraw();
594
+ // No binding/provider must preserve the native error, not leave the tool waiting forever.
595
+ if (nativeError) im.dismiss(nativeError);
596
+ };
585
597
  let answeredByIm = false;
586
598
  const native = Promise.resolve()
587
599
  .then(() => next())
588
600
  .catch((error) => {
601
+ nativeError = error;
602
+ if (!imAvailable) throw error;
589
603
  // A pure-IM session has no client connected, so the host rejects with
590
604
  // NO_PROVIDER — an expected state rather than a failure — and ASK_ABORTED
591
605
  // is this adapter's own retire signal below. Any other error is real, so
@@ -599,7 +613,7 @@ class ModernHarnessApi {
599
613
  }
600
614
  return new Promise(() => {});
601
615
  });
602
- return Promise.race([
616
+ const result = Promise.race([
603
617
  native,
604
618
  im.promise.then((value) => {
605
619
  answeredByIm = true;
@@ -627,26 +641,45 @@ class ModernHarnessApi {
627
641
  // rejecting alongside us stays an expected retirement rather than a logged
628
642
  // failure.
629
643
  question.abort(questionError('the question was answered on IM', 'ASK_ABORTED'));
644
+ } else if (!owner) {
645
+ // Also stop a bound-chat lookup/delivery still in flight when the Host wins.
646
+ question.abort(questionError('the question ended', 'ASK_ABORTED'));
630
647
  }
631
648
  });
649
+ if (!owner) {
650
+ Promise.resolve().then(() => {
651
+ if (question.signal.aborted) return false;
652
+ return this.#deliveryService.presentSessionSyncQuestion(sessionId, {
653
+ ...im.interaction, withdraw,
654
+ }, { signal: question.signal, completion: result });
655
+ }).then((available) => {
656
+ if (!available) withdraw();
657
+ }, (error) => {
658
+ if (!question.signal.aborted) console.warn('[dsh-im] synced question delivery unavailable:', error?.code ?? error?.name);
659
+ withdraw();
660
+ });
661
+ }
662
+ return result;
632
663
  }
633
664
 
634
665
  /**
635
666
  * Present one question to IM clients. Returns the answer promise plus a
636
667
  * `dismiss` used to retire the pending when the host answers first.
637
668
  */
638
- #askThroughIm(request, owner) {
669
+ #askThroughIm(request, owner, { broadcast = true } = {}) {
639
670
  let pending = null;
640
671
  const promise = new Promise((resolve, reject) => {
641
672
  pending = {
642
673
  rpcId: randomUUID(),
643
674
  sessionId: owner.sessionId,
644
675
  questions: request.questions,
676
+ broadcast,
677
+ imAvailable: true,
645
678
  signal: request.signal,
646
679
  settle: (outcome, value) => {
647
680
  if (!this.#pendingQuestions.delete(pending.rpcId)) return;
648
681
  request.signal?.removeEventListener('abort', onAbort);
649
- this.#broadcast({
682
+ if (broadcast) this.#broadcast({
650
683
  type: 'question/resolved',
651
684
  sessionId: pending.sessionId,
652
685
  questionRpcId: pending.rpcId,
@@ -661,11 +694,23 @@ class ModernHarnessApi {
661
694
  ));
662
695
  this.#pendingQuestions.set(pending.rpcId, pending);
663
696
  request.signal?.addEventListener('abort', onAbort, { once: true });
664
- this.#broadcast(this.#questionFrame(pending).payload, pending.rpcId);
697
+ if (broadcast) this.#broadcast(this.#questionFrame(pending).payload, pending.rpcId);
665
698
  });
666
699
  return {
667
700
  promise,
668
701
  dismiss: (reason) => pending?.settle('cancelled', reason),
702
+ withdraw: () => { pending.imAvailable = false; },
703
+ interaction: {
704
+ kind: 'question', interactionId: pending.rpcId, rpcId: pending.rpcId,
705
+ sessionId: pending.sessionId, payload: this.#questionFrame(pending).payload,
706
+ respond: async (response) => {
707
+ const receipt = this.#respond({ rpcId: pending.rpcId, result: response });
708
+ if (!receipt.accepted) throw new HarnessInteractionError(
709
+ `interaction-${receipt.reason}`, 'This question is no longer answerable',
710
+ );
711
+ return receipt;
712
+ },
713
+ },
669
714
  };
670
715
  }
671
716
 
@@ -869,7 +914,7 @@ class ModernHarnessApi {
869
914
  return { accepted: true };
870
915
  }
871
916
  const question = this.#pendingQuestions.get(message?.rpcId);
872
- if (!question) return { accepted: false, reason: 'not-pending' };
917
+ if (!question || !question.imAvailable) return { accepted: false, reason: 'not-pending' };
873
918
  if (message?.result?.ok !== true) {
874
919
  if (message?.result?.error?.code !== 'cancelled') {
875
920
  return { accepted: false, reason: 'bad-response' };
@@ -23,7 +23,7 @@ function sessionIdOf(session) {
23
23
 
24
24
  function userInputOrigin(scope, event) {
25
25
  const source = event?.data?.source;
26
- if (source?.kind === 'schedule') return 'dsh';
26
+ if (source?.kind === 'schedule' || source?.kind === 'user-question-reply') return 'dsh';
27
27
  if (source?.kind !== 'user' || typeof source.rpcId !== 'string' || !source.rpcId) {
28
28
  return 'other';
29
29
  }
@@ -116,9 +116,9 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
116
116
  if (event.surfaceOp !== 'append') return;
117
117
  if (state.origin === 'unknown') state.origin = origin;
118
118
  if (state.origin !== 'dsh' || origin !== 'dsh') return;
119
- const scheduled = event.data?.source?.kind === 'schedule';
119
+ const internalInput = ['schedule', 'user-question-reply'].includes(event.data?.source?.kind);
120
120
  const text = textFromHarnessContent(event.data?.content);
121
- if (!text && !scheduled) return;
121
+ if (!text && !internalInput) return;
122
122
 
123
123
  let targets;
124
124
  try {
@@ -127,9 +127,9 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
127
127
  logFailure('lookup', null, error);
128
128
  targets = [];
129
129
  }
130
- // Scheduled framing is internal: select its recipients without echoing it.
130
+ // Reminder/question-answer framing is internal: select recipients without echoing it.
131
131
  // Direct DSH input still requires a successful echo before the final answer.
132
- const recipients = scheduled
132
+ const recipients = internalInput
133
133
  ? new Map(targets.filter(validRecipient).map((target) => [recipientKey(target), target]))
134
134
  : await deliver(sessionId, targets, `${DSH_USER_PREFIX}${text}`, 'user delivery');
135
135
  if (state.recipients === null) {
@@ -151,8 +151,9 @@ if (client.includes('settings.plugins.tab') || clientSources.includes('settings.
151
151
  // email settings, the Telegram thinking-traces block, and Feishu panel settings.
152
152
  // The context editor contains one switch template and one mapped field-input
153
153
  // template; the delivery target adds one ordinary checkbox template; the
154
- // Telegram thinking-traces block adds one ordinary checkbox template. General
155
- // settings adds one mapped switch template for the two Feishu panel preferences.
154
+ // Telegram thinking-traces block adds two ordinary checkbox templates (traces
155
+ // and frame numbering). General settings adds one mapped switch template for
156
+ // the two Feishu panel preferences.
156
157
  const contextEditorSource = await readFile(resolve(root, 'plugin-src/client/context-enhancement.js'), 'utf8');
157
158
  const deliverySettingsSource = await readFile(resolve(root, 'plugin-src/client/delivery-settings.js'), 'utf8');
158
159
  const emailSettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/email/index.js'), 'utf8');
@@ -167,12 +168,12 @@ const otherClientSources = clientSources
167
168
  if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
168
169
  || (deliverySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
169
170
  || /role:\s*["']switch["']/u.test(deliverySettingsSource)
170
- || (thinkingTracesSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
171
+ || (thinkingTracesSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 2
171
172
  || /role:\s*["']switch["']/u.test(thinkingTracesSource)
172
173
  || (botGeneralSettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
173
174
  || (botGeneralSettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
174
175
  || (client.match(/role:\s*["']switch["']/g) ?? []).length !== 2
175
- || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 5) {
176
+ || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 6) {
176
177
  throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, and Feishu panel settings');
177
178
  }
178
179
  for (const marker of ['bot.context-enhancement.set', '<dsh_im_source>', '<dsh_im_source_guidance>']) {
@@ -262,6 +263,17 @@ if (process.platform !== 'win32' && (executable.mode & 0o111) === 0) {
262
263
  if (/private-bot-token|must-be-rolled-back|DEEPSEEK_API_KEY=/.test(client + host)) {
263
264
  throw new Error('built artifacts contain a test or environment secret marker');
264
265
  }
265
- await import(pathToFileURL(resolve(root, 'lib/index.js')).href);
266
+ const { createImHostPlugin } = await import(pathToFileURL(resolve(root, 'lib/index.js')).href);
267
+ let deliveryApi;
268
+ await createImHostPlugin().apply({
269
+ provide(name, service) {
270
+ if (name === 'dshIm') deliveryApi = service;
271
+ },
272
+ // Inspect the published service without starting channels or opening connections.
273
+ inject() {},
274
+ });
275
+ if (typeof deliveryApi?.createTarget !== 'function') {
276
+ throw new Error('host bundle must expose dshIm.createTarget; rebuild before publishing');
277
+ }
266
278
 
267
279
  console.log('Verified dsh-im package artifacts.');
@@ -6078,6 +6078,7 @@ export class FeishuHarnessBridge {
6078
6078
  });
6079
6079
  }
6080
6080
  pending.chatId = event.message.chat_id;
6081
+ pending.receiveIdType = 'chat_id';
6081
6082
  if (pending.needsPresentation) {
6082
6083
  try {
6083
6084
  await this.#presentInteraction(pending);
@@ -6133,9 +6134,17 @@ export class FeishuHarnessBridge {
6133
6134
  }
6134
6135
 
6135
6136
  async #submitQuestionAnswer(pending, answerText, { chatId, messageId, questionMessageId } = {}) {
6137
+ const expectedIndex = pending.index;
6138
+ try { if (pending.validate) await pending.validate(); }
6139
+ catch {
6140
+ if (chatId) await this.#send(chatId, INTERACTION_RESOLVED_TEXT(), { replyTo: messageId }).catch(() => undefined);
6141
+ return;
6142
+ }
6143
+ if (pending.inactive || pending.submitting || pending.index !== expectedIndex) return;
6136
6144
  const question = pending.questions[pending.index];
6137
6145
  if (!question) return;
6138
6146
  pending.chatId = chatId ?? pending.chatId;
6147
+ if (chatId) pending.receiveIdType = 'chat_id';
6139
6148
 
6140
6149
  // issue #162:已答状态卡以推进前的题号渲染,并整卡替换原提问卡。
6141
6150
  const answeredIndex = pending.index;
@@ -6270,12 +6279,69 @@ export class FeishuHarnessBridge {
6270
6279
  });
6271
6280
  }
6272
6281
 
6282
+ /** Use the normal question/reply state machine without submitting a new IM prompt. */
6283
+ async presentSessionSyncQuestion(interaction, context, { signal, completion } = {}) {
6284
+ if (signal?.aborted || this.#signal?.aborted || this.#hasPendingInteraction(context.key)) return false;
6285
+ let finished = false;
6286
+ const cleanup = () => {
6287
+ finished = true;
6288
+ signal?.removeEventListener('abort', finish);
6289
+ this.#signal?.removeEventListener('abort', onStop);
6290
+ };
6291
+ const finish = () => {
6292
+ const pending = this.#pendingInteractions.get(context.key);
6293
+ if (pending?.interactionId === interaction.interactionId) {
6294
+ this.#rememberResolvedInteraction(context.key, pending);
6295
+ this.#clearPendingInteraction(context.key, pending.interactionId);
6296
+ }
6297
+ cleanup();
6298
+ };
6299
+ const withdraw = async () => {
6300
+ finish();
6301
+ await interaction.withdraw?.();
6302
+ };
6303
+ const onStop = () => {
6304
+ void withdraw().catch((error) => this.#logger.warn?.('[dsh-feishu] question withdrawal failed:', error?.code));
6305
+ };
6306
+ const validate = async () => {
6307
+ try {
6308
+ await context.validate?.();
6309
+ if (finished || signal?.aborted || this.#signal?.aborted
6310
+ || (!this.#accessPolicy && !this.#allowedSenderOpenIds.has('*')
6311
+ && !this.#allowedSenderOpenIds.has(context.actor))
6312
+ || !context.actor || !evaluateInboundAccess(this.#accessPolicy, {
6313
+ conversationType: 'direct', senderIds: [context.actor], text: 'yes',
6314
+ }).allowed) throw new Error('Question recipient is no longer available');
6315
+ } catch (cause) {
6316
+ await withdraw();
6317
+ throw Object.assign(new Error('Question is no longer answerable', { cause }), { code: 'interaction-not-pending' });
6318
+ }
6319
+ };
6320
+ signal?.addEventListener('abort', finish, { once: true });
6321
+ this.#signal?.addEventListener('abort', onStop, { once: true });
6322
+ Promise.resolve(completion).then(finish, finish);
6323
+ try {
6324
+ await validate();
6325
+ await this.#handleInteraction(interaction, { ...context, validate, onClear: cleanup });
6326
+ if (finished) finish(); // A completion during delivery must not leave a pending behind.
6327
+ const available = !finished && this.#pendingInteractions.get(context.key)?.interactionId === interaction.interactionId;
6328
+ if (!available) cleanup();
6329
+ return available;
6330
+ } catch (error) {
6331
+ await withdraw();
6332
+ throw error;
6333
+ }
6334
+ }
6335
+
6273
6336
  async #handleInteraction(interaction, {
6274
6337
  key,
6275
6338
  actor,
6276
6339
  chatId,
6277
6340
  requiresMention,
6278
6341
  replyToMessageId,
6342
+ receiveIdType,
6343
+ validate,
6344
+ onClear,
6279
6345
  }) {
6280
6346
  if (await this.#approvals.handleRequested(interaction, this.#approvalContext({
6281
6347
  key, actor, chatId, requiresMention, replyToMessageId,
@@ -6322,6 +6388,10 @@ export class FeishuHarnessBridge {
6322
6388
  }
6323
6389
  if (this.#interactionKeys.has(interactionId)) return;
6324
6390
  if (existing) {
6391
+ if (interaction.withdraw) {
6392
+ await interaction.withdraw();
6393
+ return;
6394
+ }
6325
6395
  await interaction.respond({
6326
6396
  ok: false,
6327
6397
  error: {
@@ -6346,6 +6416,9 @@ export class FeishuHarnessBridge {
6346
6416
  index: 0,
6347
6417
  chatId,
6348
6418
  replyToMessageId,
6419
+ receiveIdType,
6420
+ validate,
6421
+ onClear,
6349
6422
  queue: null,
6350
6423
  claimedReplyMessageId: null,
6351
6424
  submitting: false,
@@ -6371,6 +6444,8 @@ export class FeishuHarnessBridge {
6371
6444
  }
6372
6445
 
6373
6446
  async #presentInteraction(pending) {
6447
+ if (pending.validate) await pending.validate();
6448
+ if (pending.inactive) return;
6374
6449
  const question = pending.questions[pending.index];
6375
6450
  if (!question) return;
6376
6451
  const options = Array.isArray(question?.options) ? question.options : [];
@@ -6398,7 +6473,7 @@ export class FeishuHarnessBridge {
6398
6473
  index: pending.index,
6399
6474
  total: pending.questions.length,
6400
6475
  }),
6401
- { key: pending.key, replyTo: pending.replyToMessageId },
6476
+ { key: pending.key, replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6402
6477
  ).then((sent) => {
6403
6478
  presentedAsCard = true;
6404
6479
  return sent;
@@ -6406,12 +6481,14 @@ export class FeishuHarnessBridge {
6406
6481
  // Fall back to the plain-text question if the card cannot be sent.
6407
6482
  // If the text send also fails, let the error propagate so the pending
6408
6483
  // question is not marked as presented and the existing retry logic runs.
6484
+ if (pending.inactive) return null;
6485
+ if (pending.validate) await pending.validate();
6409
6486
  return this.#send(
6410
6487
  pending.chatId,
6411
6488
  harnessQuestionText(question, pending.index, pending.questions.length, {
6412
6489
  requiresMention: pending.requiresMention,
6413
6490
  }),
6414
- { replyTo: pending.replyToMessageId },
6491
+ { replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6415
6492
  );
6416
6493
  });
6417
6494
  } else {
@@ -6424,7 +6501,7 @@ export class FeishuHarnessBridge {
6424
6501
  pending.questions.length,
6425
6502
  { requiresMention: pending.requiresMention },
6426
6503
  ),
6427
- { replyTo: pending.replyToMessageId },
6504
+ { replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6428
6505
  );
6429
6506
  }
6430
6507
  if (messageId) {
@@ -6478,6 +6555,7 @@ export class FeishuHarnessBridge {
6478
6555
  this.#pendingInteractions.delete(key);
6479
6556
  this.#interactionKeys.delete(pending.interactionId);
6480
6557
  pending.inactive = true;
6558
+ pending.onClear?.();
6481
6559
  return pending;
6482
6560
  }
6483
6561
 
@@ -6534,7 +6612,7 @@ export class FeishuHarnessBridge {
6534
6612
  else processingReaction.success();
6535
6613
  }
6536
6614
 
6537
- async #send(chatId, text, { replyTo } = {}) {
6615
+ async #send(chatId, text, { replyTo, receiveIdType = 'chat_id' } = {}) {
6538
6616
  const content = JSON.stringify({ text });
6539
6617
  if (replyTo) {
6540
6618
  try {
@@ -6563,7 +6641,7 @@ export class FeishuHarnessBridge {
6563
6641
  }
6564
6642
  }
6565
6643
  const response = await this.#client.im.v1.message.create({
6566
- params: { receive_id_type: 'chat_id' },
6644
+ params: { receive_id_type: receiveIdType },
6567
6645
  data: {
6568
6646
  receive_id: chatId,
6569
6647
  msg_type: 'text',
@@ -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
@@ -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.
@@ -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') {
@@ -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) {
@@ -25,6 +25,7 @@ import { t } from './i18n.mjs';
25
25
  import { watchHarnessMux } from './harness-mux.mjs';
26
26
  import { extractConnectionEvidence, messageDiagnosticError } from './connection-error.mjs';
27
27
  import { PromptFailureTracker } from './prompt-failure-tracker.mjs';
28
+ import { isSessionNotFound } from './session-error.mjs';
28
29
 
29
30
  // Every channel plugin runs in the same Host process. Sharing ownership by
30
31
  // Host identity (or an explicitly configured HTTP origin) prevents clients
@@ -1420,7 +1421,7 @@ export class HarnessClient {
1420
1421
  } catch (error) {
1421
1422
  if (options?.signal?.aborted) throw options.signal.reason ?? error;
1422
1423
  if (error instanceof HarnessRpcError
1423
- && ['internal', 'gateway/internal', 'session-not-found', 'session/not-found'].includes(error.code)) {
1424
+ && (['internal', 'gateway/internal'].includes(error.code) || isSessionNotFound(error.code))) {
1424
1425
  throw await this.#confirmedArchiveError(payload.sessionId, { signal: options?.signal }, error) ?? error;
1425
1426
  }
1426
1427
  throw error;
@@ -1436,7 +1437,7 @@ export class HarnessClient {
1436
1437
  return true;
1437
1438
  } catch (error) {
1438
1439
  if (error.code === 'session-archived') return true;
1439
- if (error instanceof HarnessRpcError && error.code === 'session-not-found') return false;
1440
+ if (error instanceof HarnessRpcError && isSessionNotFound(error.code)) return false;
1440
1441
  throw error;
1441
1442
  }
1442
1443
  }
@@ -1610,7 +1611,7 @@ export class HarnessClient {
1610
1611
  );
1611
1612
  this.#consumeInteractionOwnerships(sessionId, history.events ?? []);
1612
1613
  } catch (error) {
1613
- if (!(error instanceof HarnessRpcError) || error.code !== 'session-not-found') throw error;
1614
+ if (!(error instanceof HarnessRpcError) || !isSessionNotFound(error.code)) throw error;
1614
1615
  for (const ownership of candidates) {
1615
1616
  ownership.active = false;
1616
1617
  ownership.completed = true;
@@ -1681,7 +1682,7 @@ export class HarnessClient {
1681
1682
  if (this.#activeControlOwnership(sessionId, control) === ownership) {
1682
1683
  ownership.stopRequested = false;
1683
1684
  }
1684
- if (error instanceof HarnessRpcError && error.code === 'session-not-found') return false;
1685
+ if (error instanceof HarnessRpcError && isSessionNotFound(error.code)) return false;
1685
1686
  throw error;
1686
1687
  }
1687
1688
  }
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { isDeepStrictEqual } from 'node:util';
2
3
 
3
4
  import { t } from './i18n.mjs';
@@ -90,7 +91,7 @@ function formatHistory(sessionId, records, requested, hasMore) {
90
91
 
91
92
  function historyErrorMessage(error) {
92
93
  const code = error?.code ?? error?.failure?.code;
93
- if (code === 'session-not-found') return t('当前聊天绑定的会话已不存在,请重新绑定会话。');
94
+ if (isSessionNotFound(code)) return t('当前聊天绑定的会话已不存在,请重新绑定会话。');
94
95
  if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found'
95
96
  || code === 'session-binding-changed') return t('会话、工作区或机器人状态已发生变化,请重新执行 /history。');
96
97
  if (code === 'harness-api-not-found') return t('当前 Harness 暂不支持读取会话历史。');
@@ -80,8 +80,8 @@ export default {
80
80
  'The model reached its output limit without producing a displayable result. Reduce the task scope and try again.',
81
81
  '本轮处理被阻止,未能完成。请在 DSH 中查看会话状态和相关提示。':
82
82
  'This turn was blocked and did not finish. Check the Session status and related notices in DSH.',
83
- '当前会话已归档,无法继续处理。请在 DSH 中取消归档,或发送 /new 创建新会话。':
84
- 'The current Session is archived and cannot continue. Unarchive it in DSH, or send /new to create a new Session.',
83
+ '当前会话已归档,无法继续处理。有命令权限时可发送 /new 创建新会话;否则请联系管理员在 DSH 中取消归档,或为你开启命令权限。':
84
+ 'The current Session is archived and cannot continue. If you have command permission, send /new to create a new Session. Otherwise, ask an administrator to unarchive it in DSH or grant you command permission.',
85
85
  '本条消息可能仍在会话队列中,请先到 DSH 查看状态,避免重复提交。':
86
86
  'This message may still be queued in the Session. Check its status in DSH before submitting it again.',
87
87
  '任务被意外中断,本次未完成。请重试。':
@@ -3,8 +3,8 @@ export default {
3
3
  // workspace-command.mjs
4
4
  '用法:/session Session ID 或当前工作区序号(/session N)':
5
5
  'Usage: /session Session ID or the session index in the current Workspace (/session N)',
6
- '用法:\n/sessionlist 列出当前工作区会话\n/sessionlist --limit N 列出当前工作区前 N 个会话(N 为正整数)\n/sessionlist 工作区序号 按 /workspacelist 序号列出会话\n/sessionlist 工作区绝对路径 列出指定工作区会话':
7
- 'Usage:\n/sessionlist List Sessions in the current Workspace\n/sessionlist --limit N List the first N Sessions in the current Workspace (N must be a positive integer)\n/sessionlist Workspace index List Sessions by /workspacelist index\n/sessionlist Workspace absolute path List Sessions in the given Workspace',
6
+ '用法:\n/sessionlist 列出当前工作区会话\n/sessionlist --limit N 列出当前工作区前 N 个会话(N 为正整数)\n/sessionlist 工作区序号 按 /workspacelist 序号列出会话\n/sessionlist 工作区绝对路径 列出指定工作区会话\n不带工作区参数时,默认列出当前对话的有效工作区(未设置对话专属工作区时即 bot 默认工作区)。':
7
+ 'Usage:\n/sessionlist List Sessions in the current Workspace\n/sessionlist --limit N List the first N Sessions in the current Workspace (N must be a positive integer)\n/sessionlist Workspace index List Sessions by /workspacelist index\n/sessionlist Workspace absolute path List Sessions in the given Workspace\nWithout a workspace argument it lists the workspace this conversation effectively uses (the bot default when no conversation workspace is set).',
8
8
  '工作区必须是绝对路径。\n{usage}': 'The Workspace must be an absolute path.\n{usage}',
9
9
  '工作区路径包含不支持的字符或长度超过限制。\n{usage}':
10
10
  'The Workspace path contains unsupported characters or exceeds the length limit.\n{usage}',
@@ -77,6 +77,7 @@ export default {
77
77
  '机器人端无法处理这次审批,请到 Web 查看。': 'The bot cannot handle this approval. Please check the Web interface.',
78
78
  '未找到可处理端,本次操作未获批准。': 'No approval interface is available. This operation was not approved.',
79
79
  '有操作在等待审批:{tool},请到 Web 处理。': 'An operation is awaiting approval: {tool}. Please handle it in the Web interface.',
80
+ '本会话有问题等待回答,请在桌面端回答。': 'This session has a pending question. Please answer it in the desktop app.',
80
81
  '无法完整展示这次操作,已安全拒绝此次审批。':
81
82
  'The operation could not be displayed in full, so this approval was safely rejected.',
82
83
  '审批提交失败,请重新回复「批准」或「拒绝」。':
@@ -205,6 +206,6 @@ export default {
205
206
  'Collected {count}/{limit} messages. The batch is full; send /send or /cancel.',
206
207
  '批量内容提交失败,已保留 {count} 条消息。\n请再次发送 /send 重试或 /cancel 取消。':
207
208
  'Batch submission failed; {count} messages were retained.\nSend /send to retry or /cancel to cancel.',
208
- '你可以发送普通消息,但没有执行命令的权限。':
209
- 'You can send regular messages, but you do not have permission to run commands.',
209
+ '你可以发送普通消息,但没有执行命令的权限。请联系管理员在 DSH 设置 → IM机器人 → 对应机器人 → 访问设置中,为你开启当前私聊或群聊场景的命令权限后重试。':
210
+ 'You can send regular messages, but you do not have permission to run commands. Ask an administrator to grant you command permission for the current direct or group chat under DSH Settings → IM Bots → the relevant bot → Access Settings, then try again.',
210
211
  };