@xmanrui/dsh-im 5.6.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xmanrui/dsh-im",
3
- "version": "5.6.0",
3
+ "version": "5.7.0",
4
4
  "icon": "./assets/logo-plugin-message-link-gradient.webp",
5
5
  "description": "把微信、飞书、企微、钉钉、QQ、Telegram、WhatsApp、Slack、Discord、Matrix接入DSH。 Connect Telegram, WhatsApp, Slack, Discord, Matrix, WeChat, Feishu, WeCom, DingTalk, and QQ to DSH.",
6
6
  "keywords": [
@@ -137,6 +137,15 @@ const CHANNEL_DEFINITIONS = Object.freeze({
137
137
  kinds: [{ value: 'user', label: '私聊' }],
138
138
  fields: { user: [{ key: 'chatGuid', label: 'Chat GUID', placeholder: 'iMessage;+;chat123' }] },
139
139
  },
140
+ // 邮箱渠道在 Host 侧(delivery-adapter 的 case 'email')早于投递设置页面支持,
141
+ // route 只有 address 一个字段,kind 固定为 user,这里补齐表单定义让投递目标可选。
142
+ email: {
143
+ label: '邮箱',
144
+ kinds: [{ value: 'user', label: '收件人' }],
145
+ fields: {
146
+ user: [{ key: 'address', label: '邮箱地址', placeholder: 'name@example.com', inputMode: 'email' }],
147
+ },
148
+ },
140
149
  });
141
150
 
142
151
  export const DELIVERY_CHANNEL_DEFINITIONS = CHANNEL_DEFINITIONS;
@@ -1400,6 +1400,7 @@ const CLIENT = Object.freeze({
1400
1400
  'DeepSeek Harness читает новые письма в этом ящике как команды и отвечает результатом в той же цепочке писем.',
1401
1401
  '邮箱服务商': 'Почтовый провайдер',
1402
1402
  '邮箱地址': 'Адрес почты',
1403
+ '收件人': 'Получатель',
1403
1404
  '应用密码 / 授权码': 'Пароль приложения / код авторизации',
1404
1405
  'IMAP/SMTP 授权码': 'Код авторизации IMAP/SMTP',
1405
1406
  '不是邮箱登录密码;请在邮箱设置中单独生成。':
@@ -1254,6 +1254,7 @@ const EN = Object.freeze({
1254
1254
  'DeepSeek Harness 会读取该邮箱的新邮件作为指令,并在同一邮件线程内回复处理结果。': 'DeepSeek Harness reads new mail in this mailbox as instructions and replies with the result inside the same mail thread.',
1255
1255
  '邮箱服务商': 'Mail provider',
1256
1256
  '邮箱地址': 'Email address',
1257
+ '收件人': 'Recipient',
1257
1258
  '应用密码 / 授权码': 'App password / authorization code',
1258
1259
  'IMAP/SMTP 授权码': 'IMAP/SMTP authorization code',
1259
1260
  '不是邮箱登录密码;请在邮箱设置中单独生成。': 'This is not your login password; generate it separately in your mailbox settings.',
@@ -108,6 +108,14 @@ ${MARKED}[${TITLE_ATTR}]::after {
108
108
  text-overflow: ellipsis;
109
109
  pointer-events: none;
110
110
  }
111
+ /* The Host scrolls the original span and publishes these marquee fade hooks.
112
+ Let the replacement travel as complete text, not a pre-clipped viewport. */
113
+ ${MARKED}[${TITLE_ATTR}]:is([data-scrolled], [data-clipped])::after {
114
+ inset-inline-end: auto;
115
+ width: max-content;
116
+ overflow: visible;
117
+ text-overflow: clip;
118
+ }
111
119
  ${Object.entries(uris).map(([channel, uri]) => `[${CHANNEL_ATTR}="${channel}"] { --dsh-im-session-logo: url("${uri}"); }`).join('\n')}
112
120
  `;
113
121
  document.head.appendChild(style);
@@ -1,3 +1,5 @@
1
+ // Email conversation keys contain Message-IDs or bound Session IDs, not
2
+ // recipient addresses. Keep email targets explicit until a mapping is stored.
1
3
  const CHANNELS = new Set([
2
4
  'weixin',
3
5
  'feishu',
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, open, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
3
- import { isAbsolute, join } from 'node:path';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+ import { setTimeout as delay } from 'node:timers/promises';
4
5
  import semver from 'semver';
5
6
 
6
7
  import manifest from '../../package.json' with { type: 'json' };
@@ -12,6 +13,8 @@ const JOB_STATES = new Set([...ACTIVE_STATES, 'restart-required', 'completed', '
12
13
  const MAX_METADATA_BYTES = 256 * 1024;
13
14
  const SNAPSHOT_FILES = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'];
14
15
  const NO_LOCK = Symbol('no update lock');
16
+ // Shared across Host instances; keep network and installer work outside these transactions.
17
+ const stateIoQueue = {};
15
18
 
16
19
  export function updateError(code) {
17
20
  return Object.assign(new Error(code), { code });
@@ -76,7 +79,17 @@ function pathsFor(environment) {
76
79
  };
77
80
  }
78
81
 
79
- async function readJson(path, missing = null) {
82
+ function withStateIo(path, operation) {
83
+ const absolute = resolve(path);
84
+ const key = process.platform === 'win32' ? absolute.toLowerCase() : absolute;
85
+ return withSessionBindingLock(stateIoQueue, key, operation);
86
+ }
87
+
88
+ function readJson(path, missing = null) {
89
+ return withStateIo(path, () => readJsonUnlocked(path, missing));
90
+ }
91
+
92
+ async function readJsonUnlocked(path, missing = null) {
80
93
  try {
81
94
  if ((await stat(path)).size > 10 * 1024 * 1024) throw updateError('state-unavailable');
82
95
  return JSON.parse(await readFile(path, 'utf8'));
@@ -86,11 +99,25 @@ async function readJson(path, missing = null) {
86
99
  }
87
100
  }
88
101
 
89
- async function writeJson(path, value) {
102
+ function writeJson(path, value) {
103
+ return withStateIo(path, () => writeJsonUnlocked(path, value));
104
+ }
105
+
106
+ async function writeJsonUnlocked(path, value) {
90
107
  const temporary = `${path}.${randomUUID()}.tmp`;
91
108
  try {
92
109
  await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
93
- await rename(temporary, path);
110
+ for (let retry = 0; ; retry++) {
111
+ try {
112
+ await rename(temporary, path);
113
+ break;
114
+ } catch (error) {
115
+ // Windows readers can temporarily deny replacement. Keep the old journal
116
+ // and retry the same atomic rename; never remove the destination first.
117
+ if (process.platform !== 'win32' || error.code !== 'EPERM' || retry >= 5) throw error;
118
+ await delay(10 * 2 ** retry);
119
+ }
120
+ }
94
121
  } catch {
95
122
  throw updateError('state-unavailable');
96
123
  } finally {
@@ -255,8 +282,10 @@ export function createUpdateService({
255
282
  }
256
283
 
257
284
  async function releaseLock(paths, id) {
258
- const lock = await readJson(paths.lock);
259
- if (lock?.id === id) await unlink(paths.lock);
285
+ await withStateIo(paths.lock, async () => {
286
+ const lock = await readJsonUnlocked(paths.lock);
287
+ if (lock?.id === id) await unlink(paths.lock);
288
+ });
260
289
  }
261
290
 
262
291
  async function backupProfile(environment, paths, job) {
@@ -348,13 +377,15 @@ export function createUpdateService({
348
377
  let locked = false;
349
378
  try {
350
379
  await mkdir(paths.directory, { recursive: true, mode: 0o700 });
351
- const lock = await open(paths.lock, 'wx', 0o600);
352
- locked = true;
353
- try {
354
- await lock.writeFile(JSON.stringify({ id: job.id, pid: process.pid, startedAt: now() }));
355
- } finally {
356
- await lock.close();
357
- }
380
+ await withStateIo(paths.lock, async () => {
381
+ const lock = await open(paths.lock, 'wx', 0o600);
382
+ locked = true;
383
+ try {
384
+ await lock.writeFile(JSON.stringify({ id: job.id, pid: process.pid, startedAt: now() }));
385
+ } finally {
386
+ await lock.close();
387
+ }
388
+ });
358
389
  const currentRelease = await fetchNpmRelease(fetchImpl, checkTimeoutMs);
359
390
  if (JSON.stringify(currentRelease) !== JSON.stringify(confirmation.release)) throw updateError('check-expired');
360
391
  environment = await runtime.inspect({ preflight: true });
@@ -948,7 +948,19 @@ export class FeishuRuntime {
948
948
  wsClient?.close({ force: true });
949
949
  const bridge = this.#bridge;
950
950
  this.#bridge = null;
951
- if (bridge) await bridge.waitForIdle();
951
+ let timer;
952
+ try {
953
+ const idle = await Promise.race([
954
+ (bridge?.waitForIdle() ?? Promise.resolve()).then(() => true),
955
+ new Promise((resolve) => {
956
+ timer = setTimeout(() => resolve(false), 2_000);
957
+ timer.unref?.();
958
+ }),
959
+ ]);
960
+ if (!idle) this.#logger.warn?.('[dsh-feishu] bridge idle wait timed out after 2000ms; continuing cleanup');
961
+ } finally {
962
+ clearTimeout(timer);
963
+ }
952
964
  this.#client = null;
953
965
  this.#status.feishuLongConnectionState = preserveError ? 'failed' : 'idle';
954
966
  this.#status.slashCommandRegistration = 'idle';
@@ -42,11 +42,14 @@ function sendPlainText(bot, target, content, msgSeq) {
42
42
  * 以 markdown(msg_type=2)发送回复;单条被平台拒绝时回退纯文本(msg_type=0)。
43
43
  * 返回每条消息的平台响应,供调用方提取 provider message ids。
44
44
  */
45
- export async function sendMarkdownReply(bot, target, text, { logger, signal, requireComplete = false } = {}) {
45
+ export async function sendMarkdownReply(bot, target, text, { logger, signal, requireComplete = false, passiveRepliesUsed = 0 } = {}) {
46
46
  const chunks = chunkMarkdownParts(text);
47
47
  const results = [];
48
48
  const firstMsgSeq = nextMsgSeq();
49
- const passiveLimit = target?.msgId ? PASSIVE_REPLY_LIMIT[target.scope] : null;
49
+ // Earlier replies to the same msg_id (for example a timeout notice) spend
50
+ // part of QQ's passive budget; at least one slot is kept for this reply.
51
+ const passiveLimit = target?.msgId
52
+ ? Math.max(1, PASSIVE_REPLY_LIMIT[target.scope] - passiveRepliesUsed) : null;
50
53
  const overflow = passiveLimit !== null && chunks.length > passiveLimit;
51
54
  const passiveContentCount = overflow ? passiveLimit - 1 : chunks.length;
52
55
  const proactiveTarget = target?.msgId
@@ -71,6 +71,7 @@ import {
71
71
  COMMAND_PERMISSION_DENIED_MESSAGE,
72
72
  evaluateInboundAccess,
73
73
  } from '../shared/inbound-access.mjs';
74
+ import { ApiError } from '@tencent-connect/qqbot-nodejs';
74
75
  import { sendMarkdownReply } from './markdown-reply.mjs';
75
76
  import {
76
77
  isQqMenuCommand, parseQqMenuCommand, QqMenuStore,
@@ -269,6 +270,28 @@ export function qqInboundMessage(message, { fetchImpl = fetch } = {}) {
269
270
  };
270
271
  }
271
272
 
273
+ // QQ accepts passive replies to an inbound msg_id for a bounded window
274
+ // (C2C 60 min, group 5 min). Proactive C2C/group sends are quota-limited and
275
+ // are often refused, so a late result keeps the passive route while the
276
+ // window is still open and only falls back to proactive delivery after it.
277
+ const PASSIVE_REPLY_WINDOW_MS = Object.freeze({ c2c: 60 * 60_000, group: 5 * 60_000 });
278
+ const PASSIVE_REPLY_MARGIN_MS = 30_000;
279
+
280
+ function deferredQqTarget(message, target, acceptedAt) {
281
+ const route = { scope: target.scope, targetId: target.targetId };
282
+ const msgId = nonEmptyString(target.msgId);
283
+ if (!msgId || !PASSIVE_REPLY_WINDOW_MS[target.scope]) return route;
284
+ const sentAt = Date.parse(message?.timestamp ?? '');
285
+ return { ...route, msgId, receivedAt: Number.isFinite(sentAt) ? Math.min(sentAt, acceptedAt) : acceptedAt };
286
+ }
287
+
288
+ export function deferredDeliveryTarget(target, now = Date.now()) {
289
+ const route = { scope: target?.scope, targetId: target?.targetId };
290
+ const window = PASSIVE_REPLY_WINDOW_MS[target?.scope];
291
+ if (!nonEmptyString(target?.msgId) || !window || !Number.isFinite(target?.receivedAt)) return route;
292
+ return now - target.receivedAt < window - PASSIVE_REPLY_MARGIN_MS ? { ...route, msgId: target.msgId } : route;
293
+ }
294
+
272
295
  function nonEmptyString(value) {
273
296
  return typeof value === 'string' && value.trim() ? value.trim() : null;
274
297
  }
@@ -896,7 +919,22 @@ export class QqHarnessBridge {
896
919
  }
897
920
 
898
921
  async #deliverDeferredOutcome(entry, outcome) {
899
- await sendMarkdownReply(this.#bot, entry.target, deferredOutcomeText(outcome), { logger: this.#logger });
922
+ const text = deferredOutcomeText(outcome);
923
+ const target = deferredDeliveryTarget(entry.target);
924
+ if (!target.msgId) {
925
+ await sendMarkdownReply(this.#bot, target, text, { logger: this.#logger });
926
+ return true;
927
+ }
928
+ try {
929
+ // The timeout notice already answered this msg_id once.
930
+ await sendMarkdownReply(this.#bot, target, text, { logger: this.#logger, passiveRepliesUsed: 1 });
931
+ } catch (error) {
932
+ // Nothing was sent and QQ definitely refused the passive reply (window
933
+ // closed early or budget spent), so the proactive route cannot duplicate it.
934
+ if (!(error instanceof ApiError) || !(error.httpStatus >= 400 && error.httpStatus < 500)) throw error;
935
+ this.#logger.warn?.('[dsh-im:qq] passive deferred reply was refused; retrying proactively:', error);
936
+ await sendMarkdownReply(this.#bot, { scope: target.scope, targetId: target.targetId }, text, { logger: this.#logger });
937
+ }
900
938
  return true;
901
939
  }
902
940
 
@@ -1155,6 +1193,7 @@ export class QqHarnessBridge {
1155
1193
  batchSubmission = null,
1156
1194
  } = {}) {
1157
1195
  if (this.#signal?.aborted) return;
1196
+ const acceptedAt = Date.now();
1158
1197
  const messageId = nonEmptyString(message?.messageId);
1159
1198
  const sender = nonEmptyString(message?.senderId);
1160
1199
  if (!messageId || !sender || message.senderIsBot === true) return;
@@ -1273,7 +1312,7 @@ export class QqHarnessBridge {
1273
1312
  await this.#markPendingSubmitted(key, messageId);
1274
1313
  ({ answer, artifacts = [] } = await askInWorkspaceSession({
1275
1314
  onNotice: (notice) => this.#bot.sendText(target, notice),
1276
- deferredDelivery: () => ({ coordinator: this.#deferred, target: { scope: target.scope, targetId: target.targetId } }),
1315
+ deferredDelivery: () => ({ coordinator: this.#deferred, target: deferredQqTarget(message, target, acceptedAt) }),
1277
1316
  harness: this.#harness,
1278
1317
  state: this.#state,
1279
1318
  key,
@@ -155,6 +155,8 @@ function requiredString(value, name) {
155
155
  return result;
156
156
  }
157
157
 
158
+ const SLACK_MARKDOWN_TEXT_LIMIT = 12_000;
159
+
158
160
  function safeOutgoingText(value, { trim = true } = {}) {
159
161
  const raw = typeof value === 'string' ? value : '';
160
162
  const text = trim ? raw.trim() : raw;
@@ -164,6 +166,14 @@ function safeOutgoingText(value, { trim = true } = {}) {
164
166
  .replace(/<!(channel|here|everyone)(?:\^[^>]*)?>/gi, '@$1');
165
167
  }
166
168
 
169
+ function markdownTextField(value) {
170
+ const text = safeOutgoingText(value);
171
+ if (text.length > SLACK_MARKDOWN_TEXT_LIMIT) {
172
+ throw new TypeError(`Slack markdown_text exceeds ${SLACK_MARKDOWN_TEXT_LIMIT} characters`);
173
+ }
174
+ return text;
175
+ }
176
+
167
177
  function apiFailure(method, payload, tokenKind) {
168
178
  const reason = cleanString(payload?.error) ?? 'unknown_error';
169
179
  const error = new Error(`Slack ${method} failed: ${reason.replaceAll('_', ' ')}`);
@@ -272,15 +282,22 @@ export class SlackApi {
272
282
  }
273
283
 
274
284
  postMessage({ channelId, text, threadTs, signal, format = 'plain' }) {
285
+ const outgoing = format === 'markdown_text' ? markdownTextField(text) : safeOutgoingText(text);
286
+ const markdownText = format === 'markdown_text';
275
287
  return this.#request('chat.postMessage', {
276
288
  tokenKind: 'bot',
277
289
  signal,
278
290
  body: {
279
291
  channel: slackId(channelId, 'channel id'),
280
- text: safeOutgoingText(text),
281
- ...(format === 'markdown' ? { blocks: [{ type: 'markdown', text: safeOutgoingText(text) }] } : {}),
292
+ // markdown_text cannot be combined with text or blocks.
293
+ ...(markdownText
294
+ ? { markdown_text: outgoing }
295
+ : {
296
+ text: outgoing,
297
+ ...(format === 'markdown' ? { blocks: [{ type: 'markdown', text: outgoing }] } : {}),
298
+ mrkdwn: format !== 'literal',
299
+ }),
282
300
  ...(threadTs ? { thread_ts: cleanString(threadTs) } : {}),
283
- mrkdwn: true,
284
301
  link_names: false,
285
302
  unfurl_links: false,
286
303
  unfurl_media: false,
@@ -295,8 +312,7 @@ export class SlackApi {
295
312
  body: {
296
313
  channel: slackId(channelId, 'channel id'),
297
314
  ts: requiredString(ts, 'message timestamp'),
298
- text: safeOutgoingText(text),
299
- parse: 'none',
315
+ markdown_text: markdownTextField(text),
300
316
  link_names: false,
301
317
  },
302
318
  });
@@ -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 };
@@ -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);