@xmanrui/dsh-im 5.5.0 → 5.7.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 (59) hide show
  1. package/README.en.md +24 -8
  2. package/README.md +24 -8
  3. package/assets/sponsors/88api.jpg +0 -0
  4. package/lib/client.js +328 -243
  5. package/lib/index.js +317 -317
  6. package/package.json +4 -4
  7. package/plugin-src/client/channels/dingtalk/index.js +12 -9
  8. package/plugin-src/client/channels/feishu/group-settings.js +5 -5
  9. package/plugin-src/client/channels/feishu/index.js +33 -25
  10. package/plugin-src/client/channels/qq/index.js +5 -5
  11. package/plugin-src/client/channels/shared/token-api.js +12 -7
  12. package/plugin-src/client/channels/shared/token-channel.js +18 -11
  13. package/plugin-src/client/channels/wecom/index.js +5 -5
  14. package/plugin-src/client/channels/wecom-app/index.js +3 -3
  15. package/plugin-src/client/channels/weixin/index.js +2 -2
  16. package/plugin-src/client/channels/whatsapp/index.js +6 -6
  17. package/plugin-src/client/credential-binding.js +3 -2
  18. package/plugin-src/client/delivery-settings.js +12 -3
  19. package/plugin-src/client/ds-bot-settings.js +3 -3
  20. package/plugin-src/client/global-settings.js +5 -2
  21. package/plugin-src/client/i18n-ru.js +57 -34
  22. package/plugin-src/client/i18n.js +211 -124
  23. package/plugin-src/client/session-channel-logos.js +8 -0
  24. package/plugin-src/host/delivery-suggestions.mjs +2 -0
  25. package/plugin-src/host/update-service.mjs +44 -13
  26. package/scripts/verify-package.mjs +1 -1
  27. package/src/channels/dingtalk/dingtalk-bridge.mjs +1 -0
  28. package/src/channels/feishu/bridge.mjs +25 -3
  29. package/src/channels/feishu/feishu-cards.mjs +1 -45
  30. package/src/channels/feishu/feishu-runtime.mjs +13 -1
  31. package/src/channels/feishu/slash-command-panel.mjs +2 -5
  32. package/src/channels/qq/markdown-reply.mjs +5 -2
  33. package/src/channels/qq/qq-bridge.mjs +42 -2
  34. package/src/channels/shared/bot-workspace-store.mjs +1 -1
  35. package/src/channels/shared/command-catalog.mjs +8 -5
  36. package/src/channels/shared/delivery-failure-log.mjs +111 -0
  37. package/src/channels/shared/diagnostic-details.mjs +1 -0
  38. package/src/channels/shared/harness-client.mjs +12 -6
  39. package/src/channels/shared/i18n-en/shared-b.mjs +5 -0
  40. package/src/channels/shared/i18n-en/shared-c.mjs +3 -0
  41. package/src/channels/shared/i18n-en/telegram.mjs +6 -0
  42. package/src/channels/shared/i18n-ru/shared-b.mjs +5 -0
  43. package/src/channels/shared/i18n-ru/shared-c.mjs +3 -0
  44. package/src/channels/shared/i18n-ru/telegram.mjs +5 -0
  45. package/src/channels/shared/message-failure.mjs +5 -2
  46. package/src/channels/shared/session-error.mjs +8 -0
  47. package/src/channels/shared/text-harness-bridge.mjs +201 -3
  48. package/src/channels/shared/workspace-command.mjs +41 -16
  49. package/src/channels/shared/workspace-labels.mjs +65 -0
  50. package/src/channels/shared/workspace-session.mjs +24 -4
  51. package/src/channels/slack/slack-api.mjs +21 -5
  52. package/src/channels/slack/slack-runtime.mjs +69 -20
  53. package/src/channels/telegram/telegram-api.mjs +31 -2
  54. package/src/channels/telegram/telegram-bridge.mjs +58 -0
  55. package/src/channels/telegram/telegram-runtime.mjs +85 -3
  56. package/src/channels/wecom/wecom-bridge.mjs +1 -0
  57. package/src/channels/wecom/wecom-controller.mjs +89 -1
  58. package/src/channels/wecom-app/wecom-app-bridge.mjs +1 -0
  59. package/src/channels/weixin/weixin-bridge.mjs +1 -0
@@ -10,6 +10,8 @@ import { createSlackBridgeStatus, SlackHarnessBridge } from './slack-bridge.mjs'
10
10
  const RECONNECT_DELAYS_MS = Object.freeze([1_000, 3_000, 5_000, 10_000, 30_000]);
11
11
  const SLACK_MESSAGE_LIMIT = 38_000;
12
12
  const SLACK_STREAM_CHUNK_LIMIT = 11_000;
13
+ const SLACK_MARKDOWN_BLOCK_REJECTION = Object.freeze(['invalid_blocks', 'invalid_blocks_format']);
14
+ const SLACK_MARKDOWN_REJECTION = Object.freeze([...SLACK_MARKDOWN_BLOCK_REJECTION, 'invalid_markdown']);
13
15
  const IMAGE_MEDIA_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
14
16
 
15
17
  function addSocketListener(socket, event, listener) {
@@ -304,18 +306,40 @@ async function createSlackMessageStream({ api, target, signal, logger }) {
304
306
  if (!broken && first.startsWith(appended)) {
305
307
  await appendInChunks(api, target, ts, first.slice(appended.length), signal);
306
308
  await api.stopStream({ channelId: target.channelId, ts, signal });
309
+ for (const chunk of chunks.slice(1)) {
310
+ const result = await api.postMessage({
311
+ channelId: target.channelId,
312
+ threadTs: target.threadTs,
313
+ text: chunk,
314
+ signal,
315
+ });
316
+ if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
317
+ }
307
318
  } else {
319
+ const reason = broken ? 'broken' : 'prefix-mismatch';
308
320
  await api.stopStream({ channelId: target.channelId, ts, signal }).catch(() => undefined);
309
- await api.updateMessage({ channelId: target.channelId, ts, text: first, signal });
310
- }
311
- for (const chunk of chunks.slice(1)) {
312
- const result = await api.postMessage({
321
+ const source = typeof text === 'string' && text.trim() ? text.trim() : t('处理完成。');
322
+ const parts = chunkMarkdownParts(source, SLACK_STREAM_CHUNK_LIMIT);
323
+ const markdownParts = parts.length > 0 ? parts : [{ markdown: source }];
324
+ logger?.warn?.(
325
+ `[dsh-im:slack] stream finalize fell back to chat.update (${reason}, length ${markdownParts[0].markdown.length})`,
326
+ );
327
+ await api.updateMessage({
313
328
  channelId: target.channelId,
314
- threadTs: target.threadTs,
315
- text: chunk,
329
+ ts,
330
+ text: markdownParts[0].markdown,
316
331
  signal,
317
332
  });
318
- if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
333
+ for (const chunk of markdownParts.slice(1)) {
334
+ const result = await api.postMessage({
335
+ channelId: target.channelId,
336
+ threadTs: target.threadTs,
337
+ text: chunk.markdown,
338
+ format: 'markdown_text',
339
+ signal,
340
+ });
341
+ if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
342
+ }
319
343
  }
320
344
  },
321
345
  cancel() {
@@ -339,6 +363,41 @@ export class SlackBotClient {
339
363
  this.#logger = logger;
340
364
  }
341
365
 
366
+ #postMarkdown(target, text, format) {
367
+ return this.#api.postMessage({
368
+ channelId: target.channelId,
369
+ threadTs: target.threadTs,
370
+ text,
371
+ format,
372
+ signal: this.#signal,
373
+ });
374
+ }
375
+
376
+ async #recoverRejectedMarkdown(target, chunk, error) {
377
+ // Retry only a definite formatting rejection, never an ambiguous send.
378
+ if (this.#signal?.aborted || Number(error?.status) >= 500
379
+ || !SLACK_MARKDOWN_REJECTION.includes(error?.providerCode)) throw error;
380
+ if (SLACK_MARKDOWN_BLOCK_REJECTION.includes(error.providerCode)) {
381
+ this.#logger?.warn?.(
382
+ `[dsh-im:slack] Markdown block rejected (${error.providerCode}); retrying markdown_text, length ${chunk.markdown.length}`,
383
+ );
384
+ try {
385
+ const result = await this.#postMarkdown(target, chunk.markdown, 'markdown_text');
386
+ return typeof result?.ts === 'string' && result.ts ? [result.ts] : [];
387
+ } catch (retryError) {
388
+ if (this.#signal?.aborted || Number(retryError?.status) >= 500
389
+ || retryError?.providerCode !== 'invalid_markdown') throw retryError;
390
+ error = retryError;
391
+ }
392
+ }
393
+ this.#logger?.warn?.(
394
+ `[dsh-im:slack] Markdown rejected (${error.providerCode}); sending this chunk as literal text, length ${chunk.plain?.length ?? 0}`,
395
+ );
396
+ if (!chunk.plain) return [];
397
+ const result = await this.#postMarkdown(target, chunk.plain, 'literal');
398
+ return typeof result?.ts === 'string' && result.ts ? [result.ts] : [];
399
+ }
400
+
342
401
  async sendText(target, text) {
343
402
  const chunks = splitMessageText(text, SLACK_MESSAGE_LIMIT);
344
403
  const providerMessageIds = [];
@@ -362,21 +421,11 @@ export class SlackBotClient {
362
421
  for (const chunk of chunkMarkdownParts(block.text, SLACK_STREAM_CHUNK_LIMIT)) {
363
422
  this.#signal?.throwIfAborted();
364
423
  try {
365
- const result = await this.#api.postMessage({
366
- channelId: target.channelId, threadTs: target.threadTs,
367
- text: chunk.markdown, format: 'markdown', signal: this.#signal,
368
- });
424
+ const result = await this.#postMarkdown(target, chunk.markdown, 'markdown');
369
425
  if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
370
426
  } catch (error) {
371
- // Retry only a definite formatting rejection, never an ambiguous send.
372
- if (this.#signal?.aborted || Number(error?.status) >= 500
373
- || !['invalid_blocks', 'invalid_blocks_format', 'invalid_markdown']
374
- .includes(error?.providerCode)) throw error;
375
- this.#logger?.warn?.('[dsh-im:slack] Markdown rejected; sending this chunk as text');
376
- if (chunk.plain) {
377
- const result = await this.sendText(target, chunk.plain);
378
- providerMessageIds.push(...result.providerMessageIds);
379
- }
427
+ const delivered = await this.#recoverRejectedMarkdown(target, chunk, error);
428
+ providerMessageIds.push(...delivered);
380
429
  }
381
430
  }
382
431
  return { providerMessageIds };
@@ -71,9 +71,36 @@ function preserveProviderMetadata(target, source) {
71
71
  target.retryAfter = source.retry_after;
72
72
  }
73
73
  if (Number.isInteger(source?.status)) target.status = source.status;
74
+ // A wrapped artifact error keeps the attempt history of the call it wraps.
75
+ if (Array.isArray(source?.sendAttempts)) target.sendAttempts = source.sendAttempts;
74
76
  return target;
75
77
  }
76
78
 
79
+ /**
80
+ * One record per attempt of a message-creating call.
81
+ *
82
+ * A delivery that ends up unconfirmed may have spent several attempts -- the
83
+ * 2026-10-22 Telegram notice appeared 41 seconds after the incoming message --
84
+ * so the interface status and Telegram's own description are kept for every
85
+ * try, not just the last one the caller finally sees.
86
+ */
87
+ function sendAttemptRecord(method, attempt, error) {
88
+ const status = Number(error?.status ?? error?.httpStatus);
89
+ const retryAfter = Number(error?.retry_after);
90
+ return {
91
+ attempt,
92
+ method,
93
+ status: Number.isInteger(status) ? status : null,
94
+ description: typeof error?.message === 'string' && error.message ? error.message : null,
95
+ retry_after: Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter : null,
96
+ };
97
+ }
98
+
99
+ function withSendAttempts(error, attempts) {
100
+ if (error && typeof error === 'object') error.sendAttempts = attempts;
101
+ return error;
102
+ }
103
+
77
104
  function inputRichMessage(value) {
78
105
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
79
106
  throw new TypeError('A Telegram rich message is required');
@@ -462,12 +489,14 @@ export class TelegramApi {
462
489
  const chatId = String(payload.chat_id ?? '');
463
490
  await this.#reserveSendSlot(method, chatId, signal);
464
491
  let waitedMs = 0;
492
+ const attempts = [];
465
493
  for (let attempt = 1; ; attempt += 1) {
466
494
  try {
467
495
  return await (dispatch ?? (() => this.#call(method, payload, options)))();
468
496
  } catch (error) {
497
+ attempts.push(sendAttemptRecord(method, attempt, error));
469
498
  const retryAfter = rateLimitRetryAfter(error);
470
- if (retryAfter === null) throw error;
499
+ if (retryAfter === null) throw withSendAttempts(error, attempts);
471
500
  const delayMs = Math.ceil(retryAfter * 1000);
472
501
  if (attempt >= MAX_SEND_ATTEMPTS || waitedMs + delayMs > MAX_RATE_LIMIT_WAIT_MS) {
473
502
  const limited = preserveProviderMetadata(new Error(
@@ -478,7 +507,7 @@ export class TelegramApi {
478
507
  // The caller still has to tell the user when the chat frees up.
479
508
  limited.retry_after = retryAfter;
480
509
  limited.retryAfter = retryAfter;
481
- throw limited;
510
+ throw withSendAttempts(limited, attempts);
482
511
  }
483
512
  waitedMs += delayMs;
484
513
  this.#log(
@@ -1,5 +1,7 @@
1
1
  import { harnessQuestionText } from '../shared/harness-question.mjs';
2
+ import { t } from '../shared/i18n.mjs';
2
3
  import { TextHarnessBridge, createTextBridgeStatus } from '../shared/text-harness-bridge.mjs';
4
+ import { workspaceLabels } from '../shared/workspace-labels.mjs';
3
5
 
4
6
  export const TELEGRAM_DESCRIPTOR = Object.freeze({
5
7
  key: 'telegram',
@@ -71,11 +73,67 @@ export const TELEGRAM_INTERACTION_CARD = Object.freeze({
71
73
  parse: parseTelegramCardCallback,
72
74
  });
73
75
 
76
+ /**
77
+ * One keyboard row per workspace. Rows stack with no pagination: beyond this
78
+ * the phone view becomes a wall of buttons, so the bridge falls back to the
79
+ * text list that already answers `/ws <index>` (explicit degradation).
80
+ */
81
+ const MAX_WORKSPACE_BUTTONS = 20;
82
+
83
+ /**
84
+ * Encode one workspace button. The path cannot ride in `callback_data` (64-byte
85
+ * budget), so the press carries a presentation nonce plus the index into the
86
+ * snapshot the bridge cached when it sent the card. A stale card therefore
87
+ * cannot switch to a workspace that a fresher list no longer contains.
88
+ */
89
+ function workspaceCardCallbackData(nonce, index) {
90
+ // Versioned namespace (upstream convention, cf. openclaw tga1:/tgq1:): a future
91
+ // payload change can tell an old card apart instead of mis-parsing it.
92
+ return `w1|${nonce}|${index}`;
93
+ }
94
+
95
+ /** Parse a press produced by {@link workspaceCardCallbackData}; null for foreign payloads. */
96
+ export function parseTelegramWorkspaceCallback(data) {
97
+ const match = typeof data === 'string'
98
+ ? /^w1\|([A-Za-z0-9_-]{1,16})\|(\d{1,3})$/u.exec(data)
99
+ : null;
100
+ if (!match) return null;
101
+ return { nonce: match[1], index: Number(match[2]) };
102
+ }
103
+
104
+ /**
105
+ * Inline-keyboard presentation for the merged `/ws` listing.
106
+ *
107
+ * The card text is deliberately state-free: after a press only the keyboard is
108
+ * replaced (`editMessageReplyMarkup`), so a "current: …" sentence in the body
109
+ * would immediately lie about which workspace is current.
110
+ */
111
+ export const TELEGRAM_WORKSPACE_CARD = Object.freeze({
112
+ render(listing, { nonce } = {}) {
113
+ if (typeof nonce !== 'string' || !nonce) return null;
114
+ const paths = Array.isArray(listing?.paths) ? listing.paths : [];
115
+ if (paths.length === 0 || paths.length > MAX_WORKSPACE_BUTTONS) return null;
116
+ const current = typeof listing?.current === 'string' ? listing.current : null;
117
+ const labels = workspaceLabels(paths, listing?.titles ?? {});
118
+ return {
119
+ text: t('选择要切换的工作区(共 {count} 个):', { count: paths.length }),
120
+ markup: {
121
+ inline_keyboard: paths.map((path, index) => [{
122
+ text: `${path === current ? '✓ ' : ''}${index + 1}. ${labels[index].label}`,
123
+ callback_data: workspaceCardCallbackData(nonce, index),
124
+ }]),
125
+ },
126
+ };
127
+ },
128
+ parse: parseTelegramWorkspaceCallback,
129
+ });
130
+
74
131
  export class TelegramHarnessBridge extends TextHarnessBridge {
75
132
  constructor(options) {
76
133
  super({
77
134
  descriptor: TELEGRAM_DESCRIPTOR,
78
135
  interactionCard: TELEGRAM_INTERACTION_CARD,
136
+ workspaceCard: TELEGRAM_WORKSPACE_CARD,
79
137
  ...options,
80
138
  });
81
139
  }
@@ -454,12 +454,56 @@ function telegramFailure(error) {
454
454
  };
455
455
  }
456
456
 
457
- function deliveryResult(presentation, providerMessageIds, deliveryOutcome = 'sent', reason) {
457
+ function deliveryResult(presentation, providerMessageIds, deliveryOutcome = 'sent', reason, evidence = null) {
458
458
  return {
459
459
  presentation,
460
460
  providerMessageIds: [...new Set(providerMessageIds)],
461
461
  deliveryOutcome,
462
462
  ...(reason ? { reason } : {}),
463
+ ...(evidence ? { deliveryEvidence: { ...evidence, deliveryOutcome } } : {}),
464
+ };
465
+ }
466
+
467
+ /**
468
+ * What the send itself observed, kept next to the delivery result.
469
+ *
470
+ * The notice a user sees carries a reference id that used to be the only trace
471
+ * of an unconfirmed delivery. This record travels with the result so the same
472
+ * id, the attempt history and the text that never got a `message_id` can be
473
+ * written to the local log in one line.
474
+ */
475
+ function deliveryEvidence({ target, parseMode, parts, error, reason = null, failedPart = null }) {
476
+ const attempts = Array.isArray(error?.sendAttempts) ? error.sendAttempts : [];
477
+ return {
478
+ chat_id: target?.chatId ?? null,
479
+ message_thread_id: Number.isInteger(target?.messageThreadId) ? target.messageThreadId : null,
480
+ // The Bot API request carries no `parse_mode` field: a part is either Rich
481
+ // Markdown or bare text, and that is what decides which path failed.
482
+ parse_mode: parseMode,
483
+ provider_reason: (typeof error?.code === 'string' && error.code) || reason || null,
484
+ failed_part: Number.isInteger(failedPart) ? failedPart : null,
485
+ attempts,
486
+ parts,
487
+ };
488
+ }
489
+
490
+ /** One part of an answer, keeping its text only when Telegram never confirmed it. */
491
+ function deliveryPart(index, text, messageId) {
492
+ return {
493
+ index,
494
+ length: typeof text === 'string' ? text.length : 0,
495
+ message_id: messageId ?? null,
496
+ ...(messageId ? {} : { text: typeof text === 'string' ? text : '' }),
497
+ };
498
+ }
499
+
500
+ /** A plain fallback after a rejected Rich part still belongs to the same answer. */
501
+ function mergeEvidence(primary, fallback) {
502
+ if (!primary || !fallback) return fallback ?? primary ?? null;
503
+ return {
504
+ ...fallback,
505
+ provider_reason: fallback.provider_reason ?? primary.provider_reason,
506
+ attempts: [...primary.attempts, ...fallback.attempts],
463
507
  };
464
508
  }
465
509
 
@@ -800,6 +844,7 @@ export class TelegramBotClient {
800
844
  async #sendPlain(target, text) {
801
845
  const chunks = splitTelegramRegularText(text);
802
846
  const providerMessageIds = [];
847
+ const parts = [];
803
848
  for (const [index, chunk] of chunks.entries()) {
804
849
  try {
805
850
  const result = await this.#api.sendMessage({
@@ -811,13 +856,18 @@ export class TelegramBotClient {
811
856
  });
812
857
  const id = telegramMessageId(result);
813
858
  if (id) providerMessageIds.push(id);
859
+ parts.push(deliveryPart(index, chunk, id));
814
860
  } catch (error) {
861
+ parts.push(deliveryPart(index, chunk, null));
815
862
  const failure = telegramFailure(error);
816
863
  return deliveryResult(
817
864
  'text-fallback',
818
865
  providerMessageIds,
819
866
  failure.outcome,
820
867
  failure.reason,
868
+ deliveryEvidence({
869
+ target, parseMode: 'none', parts, error, failedPart: index,
870
+ }),
821
871
  );
822
872
  }
823
873
  }
@@ -825,11 +875,19 @@ export class TelegramBotClient {
825
875
  // reader may still be staring at nothing, so the final answer claims only
826
876
  // what it can prove and lets the caller report the rest.
827
877
  if (providerMessageIds.length !== chunks.length) {
878
+ const unconfirmed = parts.find((part) => !part.message_id) ?? null;
828
879
  return deliveryResult(
829
880
  'text-fallback',
830
881
  providerMessageIds,
831
882
  'unknown',
832
883
  'telegram-message-id-missing',
884
+ deliveryEvidence({
885
+ target,
886
+ parseMode: 'none',
887
+ parts,
888
+ reason: 'telegram-message-id-missing',
889
+ failedPart: unconfirmed?.index ?? null,
890
+ }),
833
891
  );
834
892
  }
835
893
  return deliveryResult('text-fallback', providerMessageIds);
@@ -865,6 +923,7 @@ export class TelegramBotClient {
865
923
  return this.#sendPlain(target, block.text);
866
924
  }
867
925
  const providerMessageIds = [];
926
+ const parts = [];
868
927
  for (const [index, chunk] of chunks.entries()) {
869
928
  try {
870
929
  const result = await this.#api.sendRichMessage({
@@ -876,14 +935,20 @@ export class TelegramBotClient {
876
935
  });
877
936
  const id = telegramMessageId(result);
878
937
  if (id) providerMessageIds.push(id);
938
+ parts.push(deliveryPart(index, chunk.source ?? chunk.markdown, id));
879
939
  } catch (error) {
940
+ parts.push(deliveryPart(index, chunk.source ?? chunk.markdown, null));
880
941
  const failure = telegramFailure(error);
942
+ const evidence = deliveryEvidence({
943
+ target, parseMode: 'rich_markdown', parts, error, failedPart: index,
944
+ });
881
945
  if (failure.outcome === 'unknown') {
882
946
  return deliveryResult(
883
947
  'telegram-rich-final',
884
948
  providerMessageIds,
885
949
  'unknown',
886
950
  failure.reason,
951
+ evidence,
887
952
  );
888
953
  }
889
954
  const remaining = chunks.slice(index).map((part) => part.source).join('');
@@ -891,22 +956,35 @@ export class TelegramBotClient {
891
956
  ...target,
892
957
  replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
893
958
  }, remaining);
959
+ // A successful fallback is a delivered answer; only an unconfirmed one
960
+ // needs the Rich rejection in the log as well.
894
961
  return deliveryResult(
895
962
  fallback.presentation,
896
963
  [...providerMessageIds, ...fallback.providerMessageIds],
897
964
  fallback.deliveryOutcome,
898
965
  fallback.reason,
966
+ fallback.deliveryOutcome === 'sent'
967
+ ? null
968
+ : mergeEvidence(evidence, fallback.deliveryEvidence),
899
969
  );
900
970
  }
901
971
  }
902
972
  // Same proof as the plain path: a rich send that never returned an id
903
973
  // cannot be reported as delivered.
904
974
  if (providerMessageIds.length !== chunks.length) {
975
+ const unconfirmed = parts.find((part) => !part.message_id) ?? null;
905
976
  return deliveryResult(
906
977
  'telegram-rich-final',
907
978
  providerMessageIds,
908
979
  'unknown',
909
980
  'telegram-message-id-missing',
981
+ deliveryEvidence({
982
+ target,
983
+ parseMode: 'rich_markdown',
984
+ parts,
985
+ reason: 'telegram-message-id-missing',
986
+ failedPart: unconfirmed?.index ?? null,
987
+ }),
910
988
  );
911
989
  }
912
990
  return deliveryResult('telegram-rich-final', providerMessageIds);
@@ -1245,14 +1323,18 @@ export class TelegramBotClient {
1245
1323
  if (result?.deliveryOutcome === 'unknown') {
1246
1324
  // 结果未知(超时等):可能已送达,重发会造成重复,保留 unknown 状态。
1247
1325
  remember(result.providerMessageIds);
1248
- return deliveryResult('telegram-thinking', providerMessageIds, 'unknown', result.reason);
1326
+ return deliveryResult(
1327
+ 'telegram-thinking', providerMessageIds, 'unknown', result.reason, result.deliveryEvidence,
1328
+ );
1249
1329
  }
1250
1330
  // 明确失败:该分片确认未送达。纯文本分片再走一次 plain 重发
1251
1331
  // (markdown 分片的 plain 回退已在 #sendRich 内尝试过),只重发
1252
1332
  // 尚未发送的尾部内容,已成功的分片不重复。
1253
1333
  remember(result?.providerMessageIds);
1254
1334
  if (format === 'markdown') {
1255
- return deliveryResult('telegram-thinking', providerMessageIds, 'failed', result.reason);
1335
+ return deliveryResult(
1336
+ 'telegram-thinking', providerMessageIds, 'failed', result.reason, result.deliveryEvidence,
1337
+ );
1256
1338
  }
1257
1339
  warnFailure('final answer chunk', new Error('chunk definitively rejected'));
1258
1340
  try {
@@ -1463,6 +1463,7 @@ export class WecomHarnessBridge {
1463
1463
  await this.#state.markSeen(messageId);
1464
1464
  promptRecorded = true;
1465
1465
  const { answer, artifacts = [] } = await askInWorkspaceSession({
1466
+ onNotice: (notice) => this.#sendActive(chatId, notice),
1466
1467
  deferredDelivery: () => ({ coordinator: this.#deferred, target: { chatId } }),
1467
1468
  harness: this.#harness,
1468
1469
  state: this.#state,
@@ -12,6 +12,27 @@ import { publicMessageFailure } from '../shared/message-failure.mjs';
12
12
  const ACTIVE_ATTEMPT_STATES = new Set(['pending', 'connecting']);
13
13
  const TERMINAL_ATTEMPT_STATES = new Set(['connected', 'failed', 'cancelled', 'expired']);
14
14
 
15
+ // A runtime may legitimately sit in 'connecting' while the SDK retries with
16
+ // backoff: every retry emits 'reconnecting', which refreshes lastCheckedAt at
17
+ // least once per reconnect cycle. After a server-side disconnect, however, the
18
+ // SDK marks the close manual and stops for good without emitting anything
19
+ // else, so 'connecting' goes stale forever and initialize() below would keep
20
+ // skipping the bot on every supervisor pass. A 'connecting' status whose last
21
+ // transition is older than this grace is treated as stalled and restarted.
22
+ const STALLED_CONNECTING_GRACE_MS = 120_000;
23
+ // Two deployments holding the same credential keep kicking each other, and
24
+ // every restart authenticates successfully (so failure-based backoff never
25
+ // triggers) while only surviving one reconnect cycle. A connection that
26
+ // dropped again within this window of being established counts as short-lived
27
+ // and its restarts are paced; a connection that stays healthy this long
28
+ // proves the bot is not in a kick loop and clears the pacing.
29
+ const STABLE_CONNECTION_MS = 300_000;
30
+ // Automatic restarts are paced per bot: when the same credential is held by
31
+ // another connection, each side kicks the other, and restarting at supervisor
32
+ // cadence would storm the provider and fight the legitimate holder.
33
+ const RESTART_BACKOFF_INITIAL_MS = 60_000;
34
+ const RESTART_BACKOFF_MAX_MS = 600_000;
35
+
15
36
  function cleanString(value) {
16
37
  return typeof value === 'string' && value.trim() ? value.trim() : null;
17
38
  }
@@ -49,6 +70,8 @@ export class WecomController {
49
70
  #transitions = new Map();
50
71
  #revision = 0;
51
72
  #closed = false;
73
+ #now;
74
+ #restartBackoff = new Map();
52
75
 
53
76
  constructor({
54
77
  qrAuth,
@@ -57,6 +80,7 @@ export class WecomController {
57
80
  createRuntime,
58
81
  deleteState = async () => {},
59
82
  logger = console,
83
+ nowImpl = Date.now,
60
84
  }) {
61
85
  if (!qrAuth || typeof qrAuth.start !== 'function' || typeof qrAuth.poll !== 'function') {
62
86
  throw new TypeError('Enterprise WeChat QR auth is required');
@@ -70,12 +94,14 @@ export class WecomController {
70
94
  throw new TypeError('WecomController requires a config store');
71
95
  }
72
96
  if (typeof createRuntime !== 'function') throw new TypeError('createRuntime is required');
97
+ if (typeof nowImpl !== 'function') throw new TypeError('nowImpl must be a function');
73
98
  this.#qrAuth = qrAuth;
74
99
  this.#credentials = credentials;
75
100
  this.#configStore = configStore;
76
101
  this.#createRuntime = createRuntime;
77
102
  this.#deleteState = deleteState;
78
103
  this.#logger = logger;
104
+ this.#now = nowImpl;
79
105
  this.#diagnostics = createConnectionDiagnostics({ channel: 'wecom', logger });
80
106
  }
81
107
 
@@ -91,17 +117,47 @@ export class WecomController {
91
117
  for (const config of this.#configStore.list()) {
92
118
  await this.#withBotTransition(config.botId, async () => {
93
119
  const existing = this.#runtimes.get(config.botId)?.status;
94
- if (this.#closed || existing?.ready || existing?.wecomConnectionState === 'connecting') return;
120
+ if (this.#closed || existing?.ready) {
121
+ // A single successful authenticate does not prove the bot is back
122
+ // for good: in a kick loop every restart authenticates and is
123
+ // dropped again one cycle later. Only a connection that has now
124
+ // held healthy past the stability window clears the pacing.
125
+ if (existing?.ready && this.#connectionStable(existing)) this.#restartBackoff.delete(config.botId);
126
+ return;
127
+ }
128
+ if (existing?.wecomConnectionState === 'connecting' && !this.#stalledConnecting(existing)) return;
129
+ const stalled = this.#stalledConnecting(existing);
130
+ const shortLived = stalled && this.#shortLivedConnecting(existing);
131
+ const backoff = this.#restartBackoff.get(config.botId);
132
+ if (backoff && backoff.nextAttemptAt > this.#now()) return;
133
+ if (shortLived && !backoff) {
134
+ // First short-lived drop: schedule one pacing window before
135
+ // contending for the credential again, instead of grabbing it back
136
+ // at supervisor cadence and immediately kicking the other side.
137
+ this.#scheduleRestartBackoff(config.botId);
138
+ this.#logger.warn?.(`[dsh-im:wecom] bot ${config.botId} connection was short-lived; deferring reconnect`);
139
+ return;
140
+ }
95
141
  try {
96
142
  const secret = await this.#resolveSecret(config.secretRef);
97
143
  if (!secret) {
98
144
  this.#errors.set(config.botId, safeError('missing-secret', t('企业微信机器人凭据缺失,请移除后重新扫码。')));
99
145
  return;
100
146
  }
147
+ if (stalled) {
148
+ if (shortLived) {
149
+ // The pacing window has elapsed; contend again. The schedule
150
+ // above doubles the next window first, so a renewed kick loop
151
+ // slows down instead of cycling at supervisor cadence.
152
+ this.#scheduleRestartBackoff(config.botId);
153
+ }
154
+ this.#logger.warn?.(`[dsh-im:wecom] bot ${config.botId} connection stalled in 'connecting'; restarting`);
155
+ }
101
156
  await this.#startRuntime(config, secret);
102
157
  this.#errors.delete(config.botId);
103
158
  } catch (error) {
104
159
  this.#errors.set(config.botId, this.#failure(error, 'connection-failed', t('企业微信连接未就绪,插件会自动重试。')));
160
+ this.#scheduleRestartBackoff(config.botId);
105
161
  this.#logger.warn?.(`[dsh-im:wecom] bot ${config.botId} failed to initialize`);
106
162
  } finally {
107
163
  this.#touch();
@@ -111,6 +167,38 @@ export class WecomController {
111
167
  return this.status();
112
168
  }
113
169
 
170
+ #stalledConnecting(status) {
171
+ if (status?.wecomConnectionState !== 'connecting') return false;
172
+ const { lastCheckedAt } = status;
173
+ return typeof lastCheckedAt === 'number' && this.#now() - lastCheckedAt > STALLED_CONNECTING_GRACE_MS;
174
+ }
175
+
176
+ // Whether the connection that just went silent had been established for
177
+ // less than the stability window: the signature of a credential contested
178
+ // by another deployment, as opposed to an ordinary healthy connection that
179
+ // dropped. Based on the timestamps of the drop (lastCheckedAt) and of the
180
+ // last successful authenticate (lastConnectedAt), so it does not change as
181
+ // time passes without a new connection.
182
+ #shortLivedConnecting(status) {
183
+ const { lastCheckedAt, lastConnectedAt } = status ?? {};
184
+ return typeof lastCheckedAt === 'number' && typeof lastConnectedAt === 'number'
185
+ && lastCheckedAt > lastConnectedAt
186
+ && lastCheckedAt - lastConnectedAt < STABLE_CONNECTION_MS;
187
+ }
188
+
189
+ #connectionStable(status) {
190
+ const { lastConnectedAt } = status ?? {};
191
+ return typeof lastConnectedAt === 'number' && this.#now() - lastConnectedAt >= STABLE_CONNECTION_MS;
192
+ }
193
+
194
+ #scheduleRestartBackoff(botId) {
195
+ const entry = this.#restartBackoff.get(botId) ?? { consecutive: 0, nextAttemptAt: 0 };
196
+ entry.consecutive += 1;
197
+ entry.nextAttemptAt = this.#now()
198
+ + Math.min(RESTART_BACKOFF_INITIAL_MS * 2 ** (entry.consecutive - 1), RESTART_BACKOFF_MAX_MS);
199
+ this.#restartBackoff.set(botId, entry);
200
+ }
201
+
114
202
  async startProvisioning() {
115
203
  if (this.#closed) throw new Error('Enterprise WeChat controller is closed');
116
204
  if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
@@ -633,6 +633,7 @@ export class WecomAppBridge {
633
633
  await this.#state.markSeen(messageId);
634
634
  promptRecorded = true;
635
635
  ({ answer, artifacts = [] } = await askInWorkspaceSession({
636
+ onNotice: (notice) => this.#send(sender, notice),
636
637
  deferredDelivery: () => ({ coordinator: this.#deferred, target: { toUserId: sender } }),
637
638
  harness: this.#harness,
638
639
  state: this.#state,
@@ -869,6 +869,7 @@ export class WeixinHarnessBridge {
869
869
  await this.#state.markSeen(messageId);
870
870
  promptRecorded = true;
871
871
  ({ answer, artifacts = [] } = await askInWorkspaceSession({
872
+ onNotice: (notice) => this.#send(sender, notice, contextToken, runId, { stopTyping: false }),
872
873
  deferredDelivery: () => ({ coordinator: this.#deferred, target: { toUserId: sender } }),
873
874
  harness: this.#harness,
874
875
  state: this.#state,