@xmanrui/dsh-im 5.1.0 → 5.3.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.
@@ -0,0 +1,113 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { registerManagementRpc } from '../management-rpc.mjs';
6
+
7
+ import { PluginConfigStore } from '../../src/channels/feishu/plugin-config-store.mjs';
8
+ import { WeixinConfigStore } from '../../src/channels/weixin/config-store.mjs';
9
+ import { DingtalkConfigStore } from '../../src/channels/dingtalk/config-store.mjs';
10
+ import { WecomConfigStore } from '../../src/channels/wecom/config-store.mjs';
11
+ import { WecomAppConfigStore } from '../../src/channels/wecom-app/config-store.mjs';
12
+ import { QqConfigStore } from '../../src/channels/qq/config-store.mjs';
13
+ import { SlackConfigStore } from '../../src/channels/slack/config-store.mjs';
14
+ import { TelegramConfigStore } from '../../src/channels/telegram/config-store.mjs';
15
+ import { DiscordConfigStore } from '../../src/channels/discord/config-store.mjs';
16
+ import { WhatsappConfigStore } from '../../src/channels/whatsapp/config-store.mjs';
17
+ import { IMessageConfigStore } from '../../src/channels/imessage/config-store.mjs';
18
+ import { EmailConfigStore } from '../../src/channels/email/config-store.mjs';
19
+ import { MatrixConfigStore } from '../../src/channels/matrix/matrix-config-store.mjs';
20
+ import { OfficeConfigStore } from '../../src/channels/office/config-store.mjs';
21
+
22
+ export const SIDEBAR_SETTINGS_RPC_CHANNEL = '/dsh-im-sidebar';
23
+ export const SIDEBAR_SETTINGS_ENDPOINTS = Object.freeze({
24
+ get: 'settings.sidebar-entry.get', set: 'settings.sidebar-entry.set',
25
+ });
26
+ const MODES = new Set(['auto', 'show', 'hide']);
27
+ const CHANNEL_STORES = [
28
+ ['feishu', PluginConfigStore], ['weixin', WeixinConfigStore],
29
+ ['dingtalk', DingtalkConfigStore], ['wecom', WecomConfigStore],
30
+ ['wecomApp', WecomAppConfigStore, 'wecom-app'], ['qq', QqConfigStore],
31
+ ['slack', SlackConfigStore], ['telegram', TelegramConfigStore],
32
+ ['discord', DiscordConfigStore], ['whatsapp', WhatsappConfigStore],
33
+ ['imessage', IMessageConfigStore], ['email', EmailConfigStore],
34
+ ['matrix', MatrixConfigStore], ['office', OfficeConfigStore],
35
+ ];
36
+
37
+ function dshHome(config) {
38
+ return resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
39
+ }
40
+
41
+ /** Read saved accounts, not connection state or workspace history. An offline
42
+ * bot still counts; an unfinished QR login does not. Reuse each channel's schema
43
+ * and the same per-channel path overrides as production. */
44
+ export async function hasConfiguredChannel(config = {}) {
45
+ const results = await Promise.allSettled(CHANNEL_STORES.map(async ([key, Store, channel = key]) => {
46
+ const options = { dshHome: dshHome(config), ...config[key] };
47
+ const root = resolve(options.dataDir ?? join(dshHome(options), 'integrations', `dsh-${channel}`));
48
+ const store = await new Store(resolve(options.configPath ?? join(root, 'config.json'))).load();
49
+ return key === 'office' ? store.get() !== null : store.list().length > 0;
50
+ }));
51
+ if (results.some((result) => result.status === 'fulfilled' && result.value)) return true;
52
+ // Unknown configuration must not be mistaken for deleting the last channel.
53
+ const failed = results.find((result) => result.status === 'rejected');
54
+ if (failed) throw failed.reason;
55
+ return false;
56
+ }
57
+
58
+ export class SidebarSettingsStore {
59
+ #path;
60
+ #writes = Promise.resolve();
61
+ constructor(path) { this.#path = path; }
62
+
63
+ async get() {
64
+ let raw;
65
+ try { raw = await readFile(this.#path, 'utf8'); }
66
+ catch (error) { if (error.code === 'ENOENT') return 'auto'; throw error; }
67
+ const value = JSON.parse(raw);
68
+ if (value?.version !== 1 || !MODES.has(value.mode)) throw new Error('Invalid sidebar settings');
69
+ return value.mode;
70
+ }
71
+
72
+ async set(mode) {
73
+ if (!MODES.has(mode)) throw new TypeError('Invalid sidebar mode');
74
+ const operation = this.#writes.catch(() => {}).then(async () => {
75
+ await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
76
+ const temporary = `${this.#path}.${randomUUID()}.tmp`;
77
+ try {
78
+ await writeFile(temporary, `${JSON.stringify({ version: 1, mode }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
79
+ await rename(temporary, this.#path);
80
+ } finally { await rm(temporary, { force: true }); }
81
+ return mode;
82
+ });
83
+ this.#writes = operation;
84
+ return operation;
85
+ }
86
+ }
87
+
88
+ export function createSidebarSettingsRpcHandler({ config = {}, store, configured } = {}) {
89
+ store ??= new SidebarSettingsStore(join(dshHome(config), 'integrations', 'dsh-im', 'sidebar-settings.json'));
90
+ configured ??= () => hasConfiguredChannel(config);
91
+ return async (endpoint, payload, signal) => {
92
+ const valid = payload && typeof payload === 'object' && !Array.isArray(payload)
93
+ && (endpoint === SIDEBAR_SETTINGS_ENDPOINTS.get ? Object.keys(payload).length === 0
94
+ : endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set && Object.keys(payload).length === 1 && MODES.has(payload.mode));
95
+ if (!valid) return { ok: false, error: { code: 'bad-request', message: 'Invalid sidebar settings.' } };
96
+ if (signal?.aborted) return { ok: false, error: { code: 'cancelled', message: 'Request cancelled.' } };
97
+ try {
98
+ const mode = endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set ? payload.mode : await store.get();
99
+ const visible = mode === 'show' || (mode === 'auto' && !await configured());
100
+ if (endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set) await store.set(mode);
101
+ return { ok: true, value: { mode, visible } };
102
+ } catch {
103
+ return { ok: false, error: { code: 'sidebar-settings-unavailable', message: '无法读取或保存侧边栏设置,请稍后重试。' } };
104
+ }
105
+ };
106
+ }
107
+
108
+ export function installSidebarSettingsRpc(ctx, { config = {} } = {}) {
109
+ // Visibility follows ordinary channel management authority. Keep it separate
110
+ // from the general settings route, whose TTL operations remain loopback-only.
111
+ return registerManagementRpc(ctx, SIDEBAR_SETTINGS_RPC_CHANNEL,
112
+ createSidebarSettingsRpcHandler({ config }), { authority: config.rpcAuthority });
113
+ }
@@ -53,6 +53,67 @@ function appleScriptString(value) {
53
53
  return JSON.stringify(String(value));
54
54
  }
55
55
 
56
+ // macOS 26 (Tahoe) stopped populating message.text for received iMessages: the
57
+ // body is only stored in message.attributedBody, an NSArchiver typedstream blob
58
+ // (`streamtyped` + archived NSAttributedString). These constants describe the
59
+ // inline-string run we need to read from that archive.
60
+ const ATTRIBUTED_BODY_STRING_CLASS = Buffer.from('NSString', 'utf8');
61
+ const ATTRIBUTED_BODY_STRING_TAG = 0x2b; // '+': inline NSString payload follows
62
+ // Attachment-only messages carry U+FFFC (object replacement character) instead
63
+ // of text. The channel is text-only, so such runs must keep normalizing to null.
64
+ const OBJECT_REPLACEMENT_CHARACTER = '\ufffc';
65
+
66
+ // Apple NXTypedStream integer encoding: a signed byte is a literal length,
67
+ // 0x81/0x82/0x83 introduce a little-endian 2/4/8-byte length.
68
+ function readTypedStreamLength(buffer, offset) {
69
+ if (offset >= buffer.length) return null;
70
+ const tag = buffer[offset];
71
+ let cursor = offset + 1;
72
+ let length;
73
+ if (tag === 0x81) {
74
+ if (cursor + 2 > buffer.length) return null;
75
+ length = buffer.readInt16LE(cursor);
76
+ cursor += 2;
77
+ } else if (tag === 0x82) {
78
+ if (cursor + 4 > buffer.length) return null;
79
+ length = buffer.readInt32LE(cursor);
80
+ cursor += 4;
81
+ } else if (tag === 0x83) {
82
+ if (cursor + 8 > buffer.length) return null;
83
+ const value = buffer.readBigInt64LE(cursor);
84
+ if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) return null;
85
+ length = Number(value);
86
+ cursor += 8;
87
+ } else {
88
+ length = tag > 0x7f ? tag - 0x100 : tag;
89
+ }
90
+ if (!Number.isInteger(length) || length < 0 || cursor + length > buffer.length) return null;
91
+ return { length, offset: cursor };
92
+ }
93
+
94
+ // Accepts either the hex string selected via hex(m.attributedBody) or the raw blob.
95
+ export function decodeAttributedBodyText(value) {
96
+ const buffer = Buffer.isBuffer(value)
97
+ ? value
98
+ : typeof value === 'string' && value.trim() ? Buffer.from(value.trim(), 'hex') : null;
99
+ if (!buffer?.length) return null;
100
+ const marker = buffer.indexOf(ATTRIBUTED_BODY_STRING_CLASS);
101
+ if (marker < 0) return null;
102
+ let tagIndex = marker + ATTRIBUTED_BODY_STRING_CLASS.length;
103
+ while (tagIndex < buffer.length && buffer[tagIndex] !== ATTRIBUTED_BODY_STRING_TAG) tagIndex += 1;
104
+ if (tagIndex >= buffer.length) return null;
105
+ const run = readTypedStreamLength(buffer, tagIndex + 1);
106
+ if (!run || run.length === 0) return null;
107
+ let text;
108
+ try {
109
+ text = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(run.offset, run.offset + run.length));
110
+ } catch {
111
+ return null;
112
+ }
113
+ const stripped = text.replaceAll(OBJECT_REPLACEMENT_CHARACTER, '').trim();
114
+ return stripped || null;
115
+ }
116
+
56
117
  export function normalizeIMessageTarget(value) {
57
118
  return normalizeChatGuid(value);
58
119
  }
@@ -62,7 +123,8 @@ export function normalizeIMessage(value, { botId } = {}) {
62
123
  if (value.serviceName !== undefined && value.serviceName !== 'iMessage') return null;
63
124
  const guid = cleanString(value.guid ?? value.id);
64
125
  const chatGuid = cleanString(value.chatGuid ?? value.chat_guid);
65
- const text = cleanString(value.text);
126
+ const text = cleanString(value.text)
127
+ ?? decodeAttributedBodyText(value.attributedBodyHex ?? value.attributedBody);
66
128
  const sender = cleanString(value.sender ?? value.handle_id);
67
129
  if (!guid || !chatGuid || !text || !sender) return null;
68
130
  if (text.startsWith(IMESSAGE_BOT_REPLY_PREFIX)) return null;
@@ -127,7 +189,10 @@ export class MacOSMessagesApi {
127
189
  const chatFilter = chatGuid ? ` AND c.guid = ${sqlString(normalizeChatGuid(chatGuid))}` : '';
128
190
  // Messages delivers self-chat back as an incoming copy. Read that copy once,
129
191
  // keeping all outgoing rows excluded, and filter bot replies by their marker.
192
+ // macOS 26 (Tahoe) stores received iMessage bodies only in attributedBody, so
193
+ // accept either text column and decode the blob when text is empty.
130
194
  const query = `SELECT m.ROWID AS rowid, m.guid AS guid, m.text AS text,
195
+ hex(m.attributedBody) AS attributedBodyHex,
131
196
  h.id AS sender, c.guid AS chatGuid, c.service_name AS serviceName,
132
197
  m.is_from_me AS isFromMe,
133
198
  datetime((m.date / 1000000000) + 978307200, 'unixepoch') AS receivedAt
@@ -136,7 +201,7 @@ export class MacOSMessagesApi {
136
201
  JOIN chat c ON c.ROWID = cmj.chat_id
137
202
  LEFT JOIN handle h ON h.ROWID = m.handle_id
138
203
  WHERE m.ROWID > ${cursor} AND m.is_from_me = 0
139
- AND m.text IS NOT NULL AND m.text != ''
204
+ AND ((m.text IS NOT NULL AND m.text != '') OR m.attributedBody IS NOT NULL)
140
205
  AND c.service_name = 'iMessage'${chatFilter}
141
206
  ORDER BY m.ROWID ASC LIMIT ${boundedLimit};`;
142
207
  try {
@@ -1,13 +1,12 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import packageInfo from '../../../package.json' with { type: 'json' };
3
- import { normalizeDiagnosticDetails } from './diagnostic-details.mjs';
3
+ import { DIAGNOSTIC_ERROR_TYPES, normalizeDiagnosticDetails } from './diagnostic-details.mjs';
4
4
  import { t } from './i18n.mjs';
5
5
 
6
6
  const reported = new WeakMap();
7
7
  const lastReport = new WeakMap();
8
8
  const stages = new WeakMap();
9
9
  const OWNED_REASONS = { 'harness-interaction-timeout': 'timeout', 'harness-response-invalid': 'invalid-response', 'connect-timeout': 'timeout', 'telegram-timeout': 'timeout', 'cli-timeout': 'timeout', 'provider-timeout': 'timeout', 'telegram-response-invalid': 'invalid-response', 'office-protocol-mismatch': 'invalid-response' };
10
- const STANDARD_NAMES = new Set(['Error', 'TypeError', 'SyntaxError', 'AggregateError', 'DOMException', 'AxiosError', 'TimeoutError', 'AbortError']);
11
10
  const KNOWN_MESSAGES = {
12
11
  'discord-401': 'Discord Bot Token 无效,请重新填写。',
13
12
  'discord-intents': 'Discord Gateway Intents 配置不正确,请检查 Developer Portal 的 Bot 设置。',
@@ -36,7 +35,7 @@ export function connectionErrorChain(error) {
36
35
  export function extractConnectionEvidence(error) {
37
36
  const { chain, truncated } = connectionErrorChain(error);
38
37
  const errors = chain.map(e => ({
39
- type: STANDARD_NAMES.has(e.name) ? e.name : 'Error',
38
+ type: DIAGNOSTIC_ERROR_TYPES.has(e.name) ? e.name : 'Error',
40
39
  // Host RPC adapters carry safe diagnostic facts without the original Error graph.
41
40
  ...normalizeDiagnosticDetails({
42
41
  reason: e.details?.reason, reasons: e.details?.reasons,
@@ -98,9 +97,9 @@ export async function atConnectionStage(stage, operation, resource) {
98
97
  catch (error) { throw connectionStageError(error, stage, resource); }
99
98
  }
100
99
 
101
- export function connectionStageError(cause, stage, resource) {
100
+ export function connectionStageError(cause, stage, resource, details = {}) {
102
101
  if (!cause || typeof cause !== 'object') cause = new Error('Operation failed');
103
- if (!stages.has(cause)) stages.set(cause, normalizeDiagnosticDetails({ stage, resource }));
102
+ if (!stages.has(cause)) stages.set(cause, normalizeDiagnosticDetails({ ...details, stage, resource }));
104
103
  return cause;
105
104
  }
106
105
 
@@ -117,6 +116,7 @@ export function diagnosticRpcResult(diagnostics, cause, result, context) {
117
116
  }
118
117
 
119
118
  export function connectionHint(details) {
119
+ if (details.stage === 'qr.encode') return t('本机二维码图片生成失败,请重试;若持续失败,请复制诊断信息并检查 DSH 运行环境。');
120
120
  const r = details.reason;
121
121
  if (r === 'multiple-causes') return t('检测到多个底层原因,请展开诊断详情逐项检查。');
122
122
  if (['ENOTFOUND', 'EAI_AGAIN'].includes(r)) return t('服务域名解析失败,请检查运行 DSH 的机器的 DNS 和网络设置。');
@@ -19,6 +19,10 @@ const REASONS = new Set([
19
19
  'CERT_HAS_EXPIRED', 'CERT_NOT_YET_VALID', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN',
20
20
  'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'ERR_TLS_CERT_ALTNAME_INVALID', 'ERR_SSL_WRONG_VERSION_NUMBER',
21
21
  'ENOENT', 'EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'ENOTDIR', 'EISDIR', 'EBUSY', 'EIO', 'EXDEV', 'EMFILE', 'ENFILE', 'EEXIST',
22
+ 'ERR_INVALID_ARG_TYPE', 'ERR_INVALID_ARG_VALUE', 'ERR_OUT_OF_RANGE', 'ERR_BUFFER_OUT_OF_BOUNDS',
23
+ 'ERR_ZLIB_INITIALIZATION_FAILED', 'ERR_STREAM_DESTROYED', 'ERR_STREAM_PREMATURE_CLOSE',
24
+ 'Z_STREAM_ERROR', 'Z_DATA_ERROR', 'Z_MEM_ERROR', 'Z_BUF_ERROR', 'Z_VERSION_ERROR',
25
+ 'MODULE_NOT_FOUND', 'ERR_MODULE_NOT_FOUND',
22
26
  'unknown', 'multiple-causes', 'timeout', 'http-error', 'provider-rejected', 'invalid-response', 'ERR_PROXY_CONNECTION_FAILED', 'ERR_TLS_HANDSHAKE_TIMEOUT', 'ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR', 'ERR_NETWORK_ACCESS_DENIED', 'AUTHENTICATIONFAILED', 'EAUTH', 'invalid-json', 'invalid-config', 'read-only',
23
27
  ]);
24
28
  const RESOURCES = new Set(['credential-store', 'account-config', 'account-state', 'workspace-config', 'workspace-directory']);
@@ -30,6 +34,10 @@ const RPC_METHODS = new Set([
30
34
  const TRANSPORTS = new Set(['host-api', 'http', 'websocket']);
31
35
  const SUBMISSION_STATES = new Set(['not-submitted', 'accepted', 'unknown']);
32
36
  const CONFIG_FILES = new Set(['config.json', 'workspaces.json']);
37
+ export const DIAGNOSTIC_ERROR_TYPES = new Set([
38
+ 'Error', 'TypeError', 'RangeError', 'ReferenceError', 'SyntaxError', 'AggregateError',
39
+ 'DOMException', 'AxiosError', 'TimeoutError', 'AbortError',
40
+ ]);
33
41
  export const CONFIG_ISSUE_LABELS = Object.freeze({
34
42
  'expected-object': '应为 JSON 对象。',
35
43
  'expected-array': '应为 JSON 数组。',
@@ -57,6 +65,12 @@ export function normalizeDiagnosticDetails(value) {
57
65
  if (allowed.has(value[field])) result[field] = value[field];
58
66
  }
59
67
  if (DIAGNOSTIC_CHANNELS.includes(value.channel)) result.channel = value.channel;
68
+ if (Array.isArray(value.errorTypes)) {
69
+ const errorTypes = [...new Set(value.errorTypes.filter(type => DIAGNOSTIC_ERROR_TYPES.has(type)))];
70
+ if (errorTypes.length) result.errorTypes = errorTypes;
71
+ }
72
+ if (value.qrEncoder === 'qrcode') result.qrEncoder = value.qrEncoder;
73
+ if (value.qrRenderer === 'png') result.qrRenderer = value.qrRenderer;
60
74
  if (Array.isArray(value.reasons)) {
61
75
  const reasons = [...new Set(value.reasons.filter(v => REASONS.has(v) && !['unknown', 'multiple-causes'].includes(v)))].slice(0, 16);
62
76
  if (reasons.length) result.reasons = reasons;
@@ -68,7 +82,7 @@ export function normalizeDiagnosticDetails(value) {
68
82
  if (['ilinkai.weixin.qq.com', 'oapi.dingtalk.com', 'api.dingtalk.com', 'api.telegram.org', 'discord.com', 'slack.com', 'open.feishu.cn', 'qyapi.weixin.qq.com'].includes(value.host)) result.host = value.host;
69
83
  if (value.dependencies && typeof value.dependencies === 'object') {
70
84
  const dependencies = {};
71
- for (const name of ['dingtalkStream', 'axios', 'httpsProxyAgent', 'agentBase']) {
85
+ for (const name of ['dingtalkStream', 'axios', 'httpsProxyAgent', 'agentBase', 'qrcode', 'pngjs', 'zlib']) {
72
86
  const version = value.dependencies[name];
73
87
  if (typeof version === 'string' && /^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(version) && version.length <= 80) dependencies[name] = version;
74
88
  }
@@ -1865,10 +1865,15 @@ export class HarnessClient {
1865
1865
  progressTail = progressTail
1866
1866
  .then(() => onUpdate(update))
1867
1867
  .catch((error) => {
1868
+ // The WeCom SDK rejects with the raw ack frame (no .message), so
1869
+ // surface errcode/errmsg explicitly instead of printing undefined.
1870
+ const detail = error instanceof Error
1871
+ ? error.message
1872
+ : `${error?.errmsg ?? error?.body?.errmsg ?? '(no message)'} (errcode=${error?.errcode ?? error?.body?.errcode ?? 'unknown'})`;
1868
1873
  console.warn(
1869
1874
  '[dsh-im] ignored a progress update failure:',
1870
1875
  this.#logPrefix,
1871
- error.message,
1876
+ detail,
1872
1877
  );
1873
1878
  });
1874
1879
  }
@@ -1,4 +1,9 @@
1
1
  export default Object.freeze({
2
+ '异常类型': 'Exception types',
3
+ '二维码编码器': 'QR encoder',
4
+ '二维码图片格式': 'QR image format',
5
+ '本机二维码图片生成失败,请重试;若持续失败,请复制诊断信息并检查 DSH 运行环境。':
6
+ 'The QR-code image could not be generated locally. Retry; if it keeps failing, copy the diagnostics and check the DSH runtime environment.',
2
7
  '准备会话': 'Prepare session',
3
8
  '准备消息': 'Prepare message',
4
9
  '建立交互通道': 'Open interaction channel',
@@ -0,0 +1,39 @@
1
+ import { createRequire } from 'node:module';
2
+ import { connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
3
+ import { normalizeDiagnosticDetails } from './diagnostic-details.mjs';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ let installedDependencies;
7
+
8
+ function resolvedPackage(name, from) {
9
+ try {
10
+ const path = from.resolve(`${name}/package.json`);
11
+ return { version: from(path)?.version, require: createRequire(path) };
12
+ } catch {
13
+ // Diagnostics must not replace the original encoding failure.
14
+ return undefined;
15
+ }
16
+ }
17
+
18
+ function dependencies() {
19
+ if (!installedDependencies) {
20
+ const qrcode = resolvedPackage('qrcode', require);
21
+ // Resolve from qrcode so nested installations report the PNG library it uses.
22
+ const pngjs = qrcode && resolvedPackage('pngjs', qrcode.require);
23
+ installedDependencies = Object.freeze(normalizeDiagnosticDetails({ dependencies: {
24
+ qrcode: qrcode?.version, pngjs: pngjs?.version, zlib: process.versions.zlib,
25
+ } }).dependencies ?? {});
26
+ }
27
+ return installedDependencies;
28
+ }
29
+
30
+ /** Attach only safe facts; never copy QR contents, exception text or stack traces. */
31
+ export function qrEncodingError(cause) {
32
+ if (cause?.name === 'AbortError') return cause;
33
+ const evidence = extractConnectionEvidence(cause);
34
+ return connectionStageError(new Error('QR encoding failed', { cause }), 'qr.encode', undefined, {
35
+ qrEncoder: 'qrcode', qrRenderer: 'png',
36
+ errorTypes: evidence.errors.map(error => error.type),
37
+ dependencies: dependencies(),
38
+ });
39
+ }
@@ -101,7 +101,14 @@ export class WecomRuntime {
101
101
  await atConnectionStage('harness.check', () => this.#harness.ensureRunning());
102
102
  this.#status.harnessReachable = true;
103
103
 
104
- const silentSdkLogger = { debug() {}, info() {}, warn() {}, error() {} };
104
+ // The SDK's own logger reports reply ack errors (errcode/errmsg) that are
105
+ // invisible otherwise; keep debug/info quiet but surface warn/error.
106
+ const silentSdkLogger = {
107
+ debug() {},
108
+ info() {},
109
+ warn: (...args) => this.#logger.warn?.('[dsh-im:wecom-sdk]', ...args),
110
+ error: (...args) => this.#logger.error?.('[dsh-im:wecom-sdk]', ...args),
111
+ };
105
112
  const client = this.#createClient({
106
113
  botId: this.#config.remoteBotId,
107
114
  secret: this.#secret,
@@ -105,6 +105,7 @@ export function weixinStageError(code, cause, stage) {
105
105
  }
106
106
 
107
107
  function hintFor(code, details) {
108
+ if (code === 'qr-encode-failed') return connectionHint(details);
108
109
  if (details.rollback === 'failed' || details.rollback === 'unknown') return t('原账号状态尚未确认,请重新读取状态,并反馈诊断信息。');
109
110
  if (details.rollback === 'succeeded') return t('操作未完成,已恢复之前的本机状态。请处理上述问题后重试。');
110
111
  if (code.startsWith('harness-')) return t('请确认当前 DSH 宿主已就绪,并检查 Harness 与插件实际运行版本及宿主日志。');
@@ -21,6 +21,7 @@ const ILINK_CLIENT_VERSION = (2 << 16) | (4 << 8) | 6;
21
21
  const DEFAULT_TIMEOUT_MS = 15_000;
22
22
  const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000;
23
23
  const WEIXIN_CDN_UPLOAD_RETRIES = 3;
24
+ const WEIXIN_TEXT_SEND_RETRY_DELAYS_MS = [400, 1_200];
24
25
  const WEIXIN_CDN_UPLOAD_IDLE_TIMEOUT_MS = 60_000;
25
26
  const WEIXIN_CDN_UPLOAD_CHUNK_BYTES = 64 * 1024;
26
27
  const WEIXIN_MESSAGE_ID_TIMESTAMP_SHIFT = 22n;
@@ -497,6 +498,24 @@ async function requestJson(fetchImpl, {
497
498
  }
498
499
  }
499
500
 
501
+ // A text reply is the only thing the user gets, so a single connection-level failure must not
502
+ // discard it. Only `network-error` is repeated: it means no HTTP response arrived at all, while
503
+ // `timeout`, `http-error` and `send-rejected` may already have been delivered. iLink does not
504
+ // deduplicate by `client_id`, so the caller keeps one id for every attempt of the same chunk and
505
+ // accepts that a request which reached the service just before the socket died can still arrive twice.
506
+ async function requestTextSend(fetchImpl, createRequest, { signal }) {
507
+ for (let attempt = 0; ; attempt += 1) {
508
+ try {
509
+ return await requestJson(fetchImpl, createRequest());
510
+ } catch (error) {
511
+ const retryDelayMs = WEIXIN_TEXT_SEND_RETRY_DELAYS_MS[attempt];
512
+ if (retryDelayMs === undefined || error?.code !== 'network-error' || signal?.aborted) throw error;
513
+ await new Promise((resolve) => { setTimeout(resolve, retryDelayMs); });
514
+ signal?.throwIfAborted?.();
515
+ }
516
+ }
517
+ }
518
+
500
519
  function validateLoginResponse(value) {
501
520
  if (!value || typeof value !== 'object' || !LOGIN_STATUSES.has(value.status)) {
502
521
  throw new WeixinApiError('invalid-login-status', '微信服务返回了无法识别的扫码状态。');
@@ -741,7 +760,7 @@ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl
741
760
  const content = nonEmptyString(text);
742
761
  if (!recipient || !content) throw new TypeError('toUserId and text are required');
743
762
  const clientId = `dsh-weixin-${randomUUID()}`;
744
- const response = await requestJson(fetchImpl, {
763
+ const response = await requestTextSend(fetchImpl, () => ({
745
764
  method: 'POST',
746
765
  baseUrl,
747
766
  endpoint: 'ilink/bot/sendmessage',
@@ -760,7 +779,7 @@ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl
760
779
  },
761
780
  base_info: baseInfo(),
762
781
  },
763
- });
782
+ }), { signal });
764
783
  const sendRejection = rejectedProviderResponse(response);
765
784
  if (sendRejection) {
766
785
  throw new WeixinApiError(