@xmanrui/dsh-im 5.3.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 (112) 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/THIRD_PARTY_NOTICES.md +209 -0
  6. package/docs/client-integration.md +2 -2
  7. package/lib/client.js +3737 -433
  8. package/lib/index.js +415 -344
  9. package/package.json +1 -1
  10. package/plugin-src/client/channel-card-meta.js +6 -2
  11. package/plugin-src/client/channels/shared/token-api.js +13 -0
  12. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  13. package/plugin-src/client/channels/telegram/styles.js +4 -0
  14. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  15. package/plugin-src/client/delivery-settings.js +23 -3
  16. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  17. package/plugin-src/client/ds-bot-avatar.js +55 -0
  18. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  19. package/plugin-src/client/ds-bot-settings.js +194 -0
  20. package/plugin-src/client/i18n-ru.js +1615 -0
  21. package/plugin-src/client/i18n.js +130 -1
  22. package/plugin-src/client/index.js +20 -2
  23. package/plugin-src/client/plugin-page.js +3 -8
  24. package/plugin-src/client/styles.js +25 -5
  25. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  26. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  27. package/plugin-src/host/channels/qq/production.mjs +2 -1
  28. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  29. package/plugin-src/host/channels/shared/production.mjs +12 -1
  30. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  31. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  32. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  33. package/plugin-src/host/channels/slack/production.mjs +2 -1
  34. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  35. package/plugin-src/host/channels/telegram/production.mjs +9 -0
  36. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  37. package/plugin-src/host/channels/wecom/production.mjs +4 -1
  38. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  39. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  40. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  41. package/plugin-src/host/delivery-adapter.mjs +129 -41
  42. package/plugin-src/host/delivery-rpc.mjs +33 -1
  43. package/plugin-src/host/delivery-service.mjs +112 -1
  44. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  45. package/plugin-src/host/ds-bot-client.mjs +87 -0
  46. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  47. package/plugin-src/host/index.mjs +8 -1
  48. package/plugin-src/host/modern-harness-api.mjs +53 -8
  49. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  50. package/scripts/verify-package.mjs +17 -5
  51. package/src/channels/feishu/bridge.mjs +83 -5
  52. package/src/channels/feishu/feishu-cards.mjs +11 -7
  53. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  54. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  55. package/src/channels/shared/AGENTS.md +19 -0
  56. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  57. package/src/channels/shared/clear-command.mjs +2 -1
  58. package/src/channels/shared/compact-command.mjs +2 -1
  59. package/src/channels/shared/conversation-queue.mjs +49 -0
  60. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  61. package/src/channels/shared/group-history-store.mjs +26 -0
  62. package/src/channels/shared/harness-client.mjs +5 -4
  63. package/src/channels/shared/history-command.mjs +2 -1
  64. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  65. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  66. package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
  67. package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
  68. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  69. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  70. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  71. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  72. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  73. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  74. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  75. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  76. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  77. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  78. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  79. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  80. package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
  81. package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
  82. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  83. package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
  84. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  85. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  86. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  87. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  88. package/src/channels/shared/i18n-ru.mjs +48 -0
  89. package/src/channels/shared/i18n.mjs +47 -12
  90. package/src/channels/shared/inbound-access.mjs +1 -1
  91. package/src/channels/shared/interface-language.mjs +3 -3
  92. package/src/channels/shared/message-failure.mjs +3 -2
  93. package/src/channels/shared/model-command.mjs +2 -1
  94. package/src/channels/shared/permission-command.mjs +2 -1
  95. package/src/channels/shared/send-limit.mjs +38 -0
  96. package/src/channels/shared/session-binding-lock.mjs +2 -0
  97. package/src/channels/shared/session-error.mjs +3 -0
  98. package/src/channels/shared/status-reaction.mjs +2 -0
  99. package/src/channels/shared/text-harness-bridge.mjs +4 -0
  100. package/src/channels/shared/thinking-cadence.mjs +36 -0
  101. package/src/channels/shared/workspace-command.mjs +2 -1
  102. package/src/channels/shared/workspace-session.mjs +5 -1
  103. package/src/channels/telegram/config-store.mjs +38 -1
  104. package/src/channels/telegram/group-triggers.mjs +229 -0
  105. package/src/channels/telegram/telegram-api.mjs +223 -32
  106. package/src/channels/telegram/telegram-bridge.mjs +4 -1
  107. package/src/channels/telegram/telegram-controller.mjs +139 -1
  108. package/src/channels/telegram/telegram-runtime.mjs +522 -178
  109. package/src/channels/telegram/voice.mjs +250 -0
  110. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  111. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  112. package/src/channels/wecom/wecom-runtime.mjs +12 -1
@@ -0,0 +1,250 @@
1
+ // voice.mjs — Telegram voice input as a speechToText consumer.
2
+ //
3
+ // The recognizer is not a channel concern: `ctx.speechToText`
4
+ // (@deepseek-ai/dsh-experimental-speech-to-text) owns a registry of named
5
+ // providers and validates the recording format, so this module only turns a
6
+ // downloaded Telegram attachment into the canonical 16 kHz mono PCM16 WAV and
7
+ // forwards the transcript. No endpoint, model or key is configured here.
8
+ //
9
+ // Without the service — or with no provider selected — voice messages keep
10
+ // their previous behaviour and arrive without text.
11
+ import { spawn } from 'node:child_process';
12
+ import { randomUUID } from 'node:crypto';
13
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+
17
+ /** Sample rate every speechToText provider accepts. */
18
+ export const VOICE_SAMPLE_RATE = 16_000;
19
+
20
+ /** Telegram caps bot downloads at 20 MB, so a recording never exceeds it. */
21
+ export const VOICE_MAX_BYTES = 20 * 1024 * 1024;
22
+
23
+ const EXTENSIONS = Object.freeze({
24
+ 'audio/ogg': 'ogg',
25
+ 'audio/oga': 'ogg',
26
+ 'audio/opus': 'opus',
27
+ 'audio/mpeg': 'mp3',
28
+ 'audio/mp3': 'mp3',
29
+ 'audio/mp4': 'm4a',
30
+ 'audio/x-m4a': 'm4a',
31
+ 'audio/aac': 'aac',
32
+ 'audio/wav': 'wav',
33
+ 'audio/x-wav': 'wav',
34
+ 'audio/webm': 'webm',
35
+ 'audio/flac': 'flac',
36
+ });
37
+
38
+ function extensionFor(mimeType) {
39
+ const key = typeof mimeType === 'string' ? mimeType.toLowerCase().split(';')[0].trim() : '';
40
+ return EXTENSIONS[key] ?? 'audio';
41
+ }
42
+
43
+ /**
44
+ * The voice or audio attachment of one Telegram message, or null.
45
+ *
46
+ * `voice` is a recorded voice note (OGG/Opus); `audio` is a music-like file
47
+ * sent as audio. Both carry a `file_id` the Bot API can download.
48
+ */
49
+ export function telegramVoiceSource(message) {
50
+ const voice = message?.voice;
51
+ if (typeof voice?.file_id === 'string' && voice.file_id) {
52
+ return Object.freeze({
53
+ kind: 'voice',
54
+ fileId: voice.file_id,
55
+ fileName: typeof voice.file_name === 'string' && voice.file_name ? voice.file_name : 'voice.ogg',
56
+ mimeType: typeof voice.mime_type === 'string' && voice.mime_type ? voice.mime_type : 'audio/ogg',
57
+ seconds: Number.isFinite(voice.duration) ? voice.duration : null,
58
+ });
59
+ }
60
+ const audio = message?.audio;
61
+ if (typeof audio?.file_id === 'string' && audio.file_id) {
62
+ return Object.freeze({
63
+ kind: 'audio',
64
+ fileId: audio.file_id,
65
+ fileName: typeof audio.file_name === 'string' && audio.file_name ? audio.file_name : 'audio.mp3',
66
+ mimeType: typeof audio.mime_type === 'string' && audio.mime_type ? audio.mime_type : 'audio/mpeg',
67
+ seconds: Number.isFinite(audio.duration) ? audio.duration : null,
68
+ });
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /** Human-readable recording length (`0:07`), or `unknown duration`. */
74
+ export function formatVoiceDuration(seconds) {
75
+ if (!Number.isFinite(seconds) || seconds <= 0) return 'unknown duration';
76
+ const total = Math.round(seconds);
77
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
78
+ }
79
+
80
+ function shorten(text, limit = 120) {
81
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
82
+ return flat.length > limit ? `${flat.slice(0, limit)}…` : flat;
83
+ }
84
+
85
+ /**
86
+ * Transcript substitute handed to the model when a recording stays textless.
87
+ *
88
+ * The channel never answers the user on its own: the model reads this note and
89
+ * decides what to say, in the user's language, without inventing the content.
90
+ */
91
+ export function voiceNote({ voice, reason }) {
92
+ return `[voice message, ${formatVoiceDuration(voice?.seconds ?? null)}; ${reason}]`;
93
+ }
94
+
95
+ /** Short cause text for a failed transcription. */
96
+ export function voiceFailureReason(error) {
97
+ const message = String(error?.message ?? error ?? '');
98
+ if (error?.code === 'ENOENT' || /\bENOENT\b/.test(message)) return 'ffmpeg is not installed';
99
+ if (/Voice recording is larger than/.test(message)) return 'recording is too large';
100
+ const exit = message.match(/ffmpeg exited with code (\d+)/);
101
+ if (exit) return `ffmpeg failed with code ${exit[1]}`;
102
+ if (error?.code === 'speech-provider') return `speech provider failed: ${shorten(message)}`;
103
+ return `transcription failed: ${shorten(message)}`;
104
+ }
105
+
106
+ /** Tag provider failures so the reason text tells them apart from ffmpeg. */
107
+ function providerFailure(error) {
108
+ if (error && typeof error === 'object' && !error.code) error.code = 'speech-provider';
109
+ return error;
110
+ }
111
+
112
+ const WAV_HEADER_BYTES = 44;
113
+ const PCM_BYTES_PER_SAMPLE = 2;
114
+
115
+ /**
116
+ * True only for the layout the Host validator accepts: RIFF/WAVE, a 16-byte
117
+ * PCM `fmt ` chunk, and a `data` chunk starting at byte 36.
118
+ *
119
+ * A `audio/wav` MIME type says nothing about rate, channels or container, so
120
+ * the shortcut has to look at the bytes.
121
+ */
122
+ export function isCanonicalWav(audio) {
123
+ if (!audio || audio.length < WAV_HEADER_BYTES) return false;
124
+ const view = new DataView(audio.buffer, audio.byteOffset, audio.byteLength);
125
+ const tag = (offset) => String.fromCharCode(
126
+ view.getUint8(offset), view.getUint8(offset + 1), view.getUint8(offset + 2), view.getUint8(offset + 3),
127
+ );
128
+ if (tag(0) !== 'RIFF' || tag(8) !== 'WAVE' || tag(12) !== 'fmt ' || tag(36) !== 'data') return false;
129
+ if (view.getUint32(4, true) !== audio.length - 8) return false;
130
+ if (view.getUint32(16, true) !== 16) return false;
131
+ if (view.getUint16(20, true) !== 1) return false; // PCM
132
+ if (view.getUint16(22, true) !== 1) return false; // mono
133
+ if (view.getUint32(24, true) !== VOICE_SAMPLE_RATE) return false;
134
+ if (view.getUint16(34, true) !== 16) return false; // PCM16
135
+ const dataBytes = view.getUint32(40, true);
136
+ return audio.length === WAV_HEADER_BYTES + dataBytes
137
+ && dataBytes % PCM_BYTES_PER_SAMPLE === 0;
138
+ }
139
+
140
+ /**
141
+ * Wrap raw PCM16 samples in the canonical container.
142
+ *
143
+ * ffmpeg writes its own `LIST`/`INFO` chunk after `fmt `, which the Host
144
+ * validator rejects, so the container is built here instead of trusting the
145
+ * muxer's metadata layout.
146
+ */
147
+ export function wrapCanonicalWav(pcm) {
148
+ const dataBytes = pcm.length;
149
+ const buffer = Buffer.alloc(WAV_HEADER_BYTES + dataBytes);
150
+ buffer.write('RIFF', 0, 'ascii');
151
+ buffer.writeUInt32LE(WAV_HEADER_BYTES - 8 + dataBytes, 4);
152
+ buffer.write('WAVE', 8, 'ascii');
153
+ buffer.write('fmt ', 12, 'ascii');
154
+ buffer.writeUInt32LE(16, 16);
155
+ buffer.writeUInt16LE(1, 20);
156
+ buffer.writeUInt16LE(1, 22);
157
+ buffer.writeUInt32LE(VOICE_SAMPLE_RATE, 24);
158
+ buffer.writeUInt32LE(VOICE_SAMPLE_RATE * PCM_BYTES_PER_SAMPLE, 28);
159
+ buffer.writeUInt16LE(PCM_BYTES_PER_SAMPLE, 32);
160
+ buffer.writeUInt16LE(16, 34);
161
+ buffer.write('data', 36, 'ascii');
162
+ buffer.writeUInt32LE(dataBytes, 40);
163
+ pcm.copy(buffer, WAV_HEADER_BYTES);
164
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
165
+ }
166
+
167
+ /** Convert one recording into the canonical transcript container. */
168
+ function defaultRunFfmpeg(bin, args, { signal } = {}) {
169
+ return new Promise((resolve, reject) => {
170
+ const child = spawn(bin, args, { signal });
171
+ let stderr = '';
172
+ child.stderr?.on('data', (chunk) => {
173
+ stderr += chunk;
174
+ if (stderr.length > 2_000) stderr = stderr.slice(-2_000);
175
+ });
176
+ // A missing binary rejects through 'error', not a non-zero exit code.
177
+ child.on('error', reject);
178
+ child.on('close', (code) => (code === 0
179
+ ? resolve()
180
+ : reject(new Error(`ffmpeg exited with code ${code}: ${stderr.slice(-300)}`))));
181
+ });
182
+ }
183
+
184
+ /**
185
+ * Build a transcriber, or null when no speech service is mounted.
186
+ *
187
+ * The runtime treats null as "voice is not transcribable here" and keeps the
188
+ * message text empty, exactly as it behaved before this module existed.
189
+ */
190
+ export function createTelegramVoiceTranscriber({
191
+ speechToText,
192
+ ffmpeg = process.env.DSH_IM_FFMPEG || 'ffmpeg',
193
+ language,
194
+ maxBytes = VOICE_MAX_BYTES,
195
+ runFfmpeg = defaultRunFfmpeg,
196
+ workspace = (prefix) => mkdtempSync(join(tmpdir(), prefix)),
197
+ removeDir = (path) => rmSync(path, { recursive: true, force: true }),
198
+ } = {}) {
199
+ if (typeof speechToText?.resolve !== 'function' || typeof speechToText?.transcribe !== 'function') {
200
+ return null;
201
+ }
202
+ return Object.freeze({
203
+ /** Transcript text for one downloaded recording; throws when it cannot run. */
204
+ async transcribe({ audio, voice, signal } = {}) {
205
+ if (!audio || typeof audio.length !== 'number' || audio.length === 0) {
206
+ throw new TypeError('Telegram voice transcription needs audio bytes');
207
+ }
208
+ if (audio.length > maxBytes) {
209
+ throw new Error(`Voice recording is larger than ${maxBytes} bytes`);
210
+ }
211
+ // A recording that already is canonical WAV skips the converter; a WAV
212
+ // that is 44.1 kHz stereo still has to be resampled.
213
+ const wavBytes = new Uint8Array(audio);
214
+ let wav;
215
+ if (isCanonicalWav(wavBytes)) {
216
+ wav = wavBytes;
217
+ } else {
218
+ const directory = workspace(`dsh-telegram-voice-${randomUUID()}-`);
219
+ try {
220
+ const input = join(directory, `in.${extensionFor(voice?.mimeType)}`);
221
+ const output = join(directory, 'out.pcm');
222
+ writeFileSync(input, audio);
223
+ // Raw PCM out, so the container is ours and carries no extra chunks.
224
+ await runFfmpeg(ffmpeg, [
225
+ '-hide_banner', '-loglevel', 'error', '-y',
226
+ '-i', input,
227
+ '-ar', String(VOICE_SAMPLE_RATE), '-ac', '1', '-f', 's16le', '-c:a', 'pcm_s16le',
228
+ output,
229
+ ], { signal });
230
+ wav = wrapCanonicalWav(readFileSync(output));
231
+ } finally {
232
+ removeDir(directory);
233
+ }
234
+ }
235
+ let spec;
236
+ try {
237
+ spec = speechToText.resolve({ audio: wav, ...(language ? { language } : {}) });
238
+ } catch (error) {
239
+ throw providerFailure(error);
240
+ }
241
+ let transcript;
242
+ try {
243
+ transcript = await speechToText.transcribe(spec, signal ?? new AbortController().signal);
244
+ } catch (error) {
245
+ throw providerFailure(error);
246
+ }
247
+ return typeof transcript?.text === 'string' ? transcript.text.trim() : '';
248
+ },
249
+ });
250
+ }
@@ -0,0 +1,184 @@
1
+ import { t } from '../shared/i18n.mjs';
2
+
3
+ // WeCom closes a streaming card 10 minutes after its FIRST frame; refreshes do
4
+ // not extend the window (verified against the provider: errcode 846608
5
+ // "stream message update expired (>10 minutes), cannot update"). A long or
6
+ // silent turn therefore outlives its card, and every later frame plus the
7
+ // final finish are rejected — the reply is lost.
8
+ //
9
+ // The supervisor keeps a turn deliverable by rotating cards before the wall:
10
+ // each rotation finishes the current card with a pointer note and opens a
11
+ // fresh stream that carries the same preview content. It also probes silent
12
+ // stretches (no frames to send) so the card stays informative, and rebuilds
13
+ // immediately after back-to-back rejected updates in case a card dies early.
14
+ //
15
+ // Concurrency rules:
16
+ // - Every send (rotation, probe, progress, finalization) runs on one serial
17
+ // queue, so a rotation already in flight completes — and publishes its new
18
+ // card — before the final finish is sent. The final answer always targets
19
+ // the newest live card.
20
+ // - stop() forbids opening further cards: an interrupted rotation closes its
21
+ // old card but never leaves an unfinished "continuing" orphan behind.
22
+ // - Finalization is terminal: once finishStream is called the timer stops and
23
+ // probes/rotations are suppressed, so slow follow-up delivery (remaining
24
+ // text chunks, attachments) can never touch or replace the finished card.
25
+ // A failed finish still falls through to the caller's active-message path.
26
+ export function createWecomStreamSupervisor({
27
+ client,
28
+ frame,
29
+ chatId,
30
+ generateStreamId,
31
+ previewText = () => '',
32
+ logger = console,
33
+ rotateAfterMs = 8 * 60 * 1000 + 30 * 1000,
34
+ silentProbeMs = 2 * 60 * 1000,
35
+ tickMs = 60 * 1000,
36
+ }) {
37
+ if (!client || typeof client.replyStream !== 'function') {
38
+ throw new TypeError('createWecomStreamSupervisor requires a client with replyStream');
39
+ }
40
+ if (typeof generateStreamId !== 'function') {
41
+ throw new TypeError('createWecomStreamSupervisor requires a generateStreamId function');
42
+ }
43
+ let currentStreamId = null;
44
+ let cardStartedAt = Date.now();
45
+ let lastFrameAt = Date.now();
46
+ let segmentNo = 1;
47
+ let alive = true;
48
+ let rejects = 0;
49
+ let stopped = false;
50
+ let delivering = false;
51
+ let timer = null;
52
+
53
+ // One serial queue for every provider interaction; a failed operation never
54
+ // blocks the next one.
55
+ let chain = Promise.resolve();
56
+ const enqueue = (operation) => {
57
+ const run = chain.then(operation, operation);
58
+ chain = run.catch(() => undefined);
59
+ return run;
60
+ };
61
+
62
+ // The SDK rejects send promises with the raw ack frame, which carries
63
+ // errcode/errmsg but no .message; wrap it so every caller sees an Error.
64
+ const normalize = (error) => {
65
+ if (error instanceof Error) return error;
66
+ const errcode = error?.errcode ?? error?.body?.errcode ?? error?.header?.errcode;
67
+ const wrapped = new Error(
68
+ `${error?.errmsg ?? error?.body?.errmsg ?? 'wecom stream update rejected'} (errcode=${errcode ?? 'unknown'})`,
69
+ );
70
+ if (errcode !== undefined) wrapped.errcode = Number(errcode);
71
+ if (typeof error?.errmsg === 'string') wrapped.errmsg = error.errmsg;
72
+ return wrapped;
73
+ };
74
+
75
+ const reply = (streamId, text, finish) => client.replyStream(frame, streamId, text, finish);
76
+
77
+ // Runs on the serial queue. Closes the current card, then — unless the
78
+ // supervisor was stopped or finalization began meanwhile — opens a fresh
79
+ // card seeded with the pending preview.
80
+ const rotateCore = async (headText) => {
81
+ const closedSegment = segmentNo;
82
+ segmentNo += 1;
83
+ if (currentStreamId) {
84
+ await reply(
85
+ currentStreamId,
86
+ t('▣ 第 {segment} 段 · 任务仍在进行,继续见下一条 ↓', { segment: closedSegment }),
87
+ true,
88
+ ).catch(() => undefined);
89
+ }
90
+ if (stopped) {
91
+ // Shutdown raced the rotation: closing the old card is still correct,
92
+ // but a new "continuing" card must never appear after stop(). A queued
93
+ // finalization is NOT a reason to abort — it runs after this rotation
94
+ // on the serial queue and needs the fresh card this rotation opens.
95
+ alive = false;
96
+ logger.warn?.('[dsh-im:wecom] stream rotation skipped after shutdown');
97
+ return currentStreamId;
98
+ }
99
+ const nextId = generateStreamId();
100
+ try {
101
+ await reply(nextId, headText || t('继续执行中…'), false);
102
+ currentStreamId = nextId;
103
+ cardStartedAt = Date.now();
104
+ lastFrameAt = Date.now();
105
+ rejects = 0;
106
+ alive = true;
107
+ logger.warn?.(`[dsh-im:wecom] stream card rotated to segment ${segmentNo} for chat ${chatId}`);
108
+ } catch (error) {
109
+ // Without a live card the final reply must go through an active message
110
+ // instead; keep alive=false so callers skip the stream.
111
+ alive = false;
112
+ logger.warn?.(
113
+ '[dsh-im:wecom] stream rotation failed; final delivery will use an active message:',
114
+ normalize(error),
115
+ );
116
+ }
117
+ return currentStreamId;
118
+ };
119
+
120
+ const sendCore = async (preview) => {
121
+ if (!alive || !currentStreamId) return;
122
+ try {
123
+ await client.replyStreamNonBlocking(frame, currentStreamId, preview, false);
124
+ rejects = 0;
125
+ lastFrameAt = Date.now();
126
+ } catch (error) {
127
+ const normalized = normalize(error);
128
+ if (Number.isFinite(normalized.errcode) && normalized.errcode !== 0) {
129
+ rejects += 1;
130
+ logger.warn?.(`[dsh-im:wecom] stream update rejected (${rejects}x): ${normalized.message}`);
131
+ if (rejects >= 2) {
132
+ alive = false;
133
+ await rotateCore(preview);
134
+ }
135
+ } else {
136
+ logger.warn?.('[dsh-im:wecom] stream update failed:', normalized.message);
137
+ }
138
+ }
139
+ };
140
+
141
+ const backgroundAction = () => {
142
+ if (delivering || stopped || !alive || !currentStreamId) return;
143
+ if (Date.now() - cardStartedAt >= rotateAfterMs) {
144
+ return enqueue(() => (delivering || stopped ? undefined : rotateCore(previewText())));
145
+ }
146
+ if (Date.now() - lastFrameAt >= silentProbeMs) {
147
+ return enqueue(() => (delivering || stopped ? undefined : sendCore(previewText() || t('仍在执行中…'))));
148
+ }
149
+ return undefined;
150
+ };
151
+
152
+ if (tickMs > 0) {
153
+ timer = setInterval(() => {
154
+ Promise.resolve(backgroundAction()).catch(() => undefined);
155
+ }, tickMs);
156
+ }
157
+
158
+ return {
159
+ start(streamId) { currentStreamId = streamId; },
160
+ currentId: () => currentStreamId,
161
+ isAlive: () => alive,
162
+ progress(preview) {
163
+ if (delivering || stopped || !alive || !currentStreamId || !preview) return Promise.resolve();
164
+ if (Date.now() - cardStartedAt >= rotateAfterMs) {
165
+ return enqueue(() => (delivering || stopped ? undefined : rotateCore(preview)));
166
+ }
167
+ return enqueue(() => (delivering || stopped ? undefined : sendCore(preview)));
168
+ },
169
+ finishStream(text) {
170
+ delivering = true;
171
+ if (timer) clearInterval(timer);
172
+ return enqueue(async () => {
173
+ if (!alive || !currentStreamId) throw new Error('wecom stream unavailable');
174
+ return reply(currentStreamId, text, true);
175
+ });
176
+ },
177
+ stop() {
178
+ stopped = true;
179
+ if (timer) clearInterval(timer);
180
+ },
181
+ // Exposed for tests and diagnostics: is a finalization in progress?
182
+ isDelivering: () => delivering,
183
+ };
184
+ }
@@ -74,6 +74,7 @@ import {
74
74
  evaluateInboundAccess,
75
75
  } from '../shared/inbound-access.mjs';
76
76
  import { t } from '../shared/i18n.mjs';
77
+ import { createWecomStreamSupervisor } from './stream-supervisor.mjs';
77
78
 
78
79
  const DEFAULT_FILE_UPLOAD_TIMEOUT_MS = 120_000;
79
80
 
@@ -586,6 +587,8 @@ export class WecomHarnessBridge {
586
587
  #status;
587
588
  #logger;
588
589
  #replyTimeoutMs;
590
+ #streamRotateAfterMs;
591
+ #streamSilentProbeMs;
589
592
  #generateReqId;
590
593
  #signal;
591
594
  #fileUploadTimeoutMs;
@@ -613,6 +616,8 @@ export class WecomHarnessBridge {
613
616
  status = createWecomBridgeStatus(),
614
617
  logger = console,
615
618
  replyTimeoutMs = 600_000,
619
+ streamRotateAfterMs = 510_000,
620
+ streamSilentProbeMs = 120_000,
616
621
  generateStreamId = generateReqId,
617
622
  fileUploadTimeoutMs = DEFAULT_FILE_UPLOAD_TIMEOUT_MS,
618
623
  signal,
@@ -632,6 +637,8 @@ export class WecomHarnessBridge {
632
637
  this.#status = status;
633
638
  this.#logger = logger;
634
639
  this.#replyTimeoutMs = replyTimeoutMs;
640
+ this.#streamRotateAfterMs = streamRotateAfterMs;
641
+ this.#streamSilentProbeMs = streamSilentProbeMs;
635
642
  this.#generateReqId = generateStreamId;
636
643
  this.#fileUploadTimeoutMs = Math.min(fileUploadTimeoutMs, DEFAULT_FILE_UPLOAD_TIMEOUT_MS);
637
644
  this.#signal = signal;
@@ -1359,6 +1366,7 @@ export class WecomHarnessBridge {
1359
1366
  const key = conversationKey(frame);
1360
1367
  let streamId = null;
1361
1368
  let streamStarted = false;
1369
+ let streamCtl = null;
1362
1370
  let streamThinkingText = t('正在思考中…');
1363
1371
  let streamAnswerText = '';
1364
1372
  let batchSettled = batchSubmission === null;
@@ -1424,6 +1432,17 @@ export class WecomHarnessBridge {
1424
1432
  } catch (error) {
1425
1433
  this.#logger.warn?.('[dsh-im:wecom] unable to start a stream; using an active reply:', error);
1426
1434
  }
1435
+ streamCtl = createWecomStreamSupervisor({
1436
+ client: this.#client,
1437
+ frame,
1438
+ chatId,
1439
+ generateStreamId: () => this.#generateReqId('stream'),
1440
+ previewText: () => splitUtf8(streamContent(streamThinkingText, streamAnswerText))[0],
1441
+ logger: this.#logger,
1442
+ rotateAfterMs: this.#streamRotateAfterMs,
1443
+ silentProbeMs: this.#streamSilentProbeMs,
1444
+ });
1445
+ if (streamStarted) streamCtl.start(streamId);
1427
1446
 
1428
1447
  let content = hasImages || hasReply
1429
1448
  ? await promptContentForInboundMessage(message, { signal: this.#signal, deferImages: true })
@@ -1469,7 +1488,7 @@ export class WecomHarnessBridge {
1469
1488
  const preview = splitUtf8(
1470
1489
  streamContent(streamThinkingText, streamAnswerText),
1471
1490
  )[0];
1472
- if (preview) await this.#client.replyStreamNonBlocking(frame, streamId, preview, false);
1491
+ if (preview) await streamCtl.progress(preview);
1473
1492
  }
1474
1493
  : undefined,
1475
1494
  onInteraction: (interaction) => this.#handleInteraction(interaction, {
@@ -1500,7 +1519,7 @@ export class WecomHarnessBridge {
1500
1519
  if (streamStarted && streamChunks.length > 0) {
1501
1520
  try {
1502
1521
  const providerMessageIds = [];
1503
- const streamed = await this.#client.replyStream(frame, streamId, streamChunks[0], true);
1522
+ const streamed = await streamCtl.finishStream(streamChunks[0]);
1504
1523
  const streamedMessageId = providerMessageId(streamed);
1505
1524
  if (streamedMessageId) providerMessageIds.push(streamedMessageId);
1506
1525
  for (const chunk of streamChunks.slice(1)) {
@@ -1566,11 +1585,8 @@ export class WecomHarnessBridge {
1566
1585
  }
1567
1586
  if (error?.code === 'turn-stopped') {
1568
1587
  if (streamStarted && streamId) {
1569
- await this.#client.replyStream(
1570
- frame,
1571
- streamId,
1588
+ await streamCtl.finishStream(
1572
1589
  streamContent(streamThinkingText, t('已停止。'), { finish: true }),
1573
- true,
1574
1590
  )
1575
1591
  .catch(() => undefined);
1576
1592
  }
@@ -1594,12 +1610,9 @@ export class WecomHarnessBridge {
1594
1610
  ? `${errorText}\n\n${batchFailureMessage}`
1595
1611
  : errorText;
1596
1612
  try {
1597
- if (streamStarted && streamId) {
1598
- await this.#client.replyStream(
1599
- frame,
1600
- streamId,
1613
+ if (streamStarted && streamId && streamCtl.isAlive()) {
1614
+ await streamCtl.finishStream(
1601
1615
  streamContent(streamThinkingText, visibleError, { finish: true }),
1602
- true,
1603
1616
  );
1604
1617
  } else {
1605
1618
  await this.#sendImmediate(frame, chatId, visibleError);
@@ -1609,6 +1622,7 @@ export class WecomHarnessBridge {
1609
1622
  this.#logger.error?.('[dsh-im:wecom] failed to send the safe error reply');
1610
1623
  }
1611
1624
  } finally {
1625
+ streamCtl?.stop();
1612
1626
  await Promise.allSettled([
1613
1627
  this.#cancelPendingInteraction(key),
1614
1628
  this.#approvals.closeRoute(key),
@@ -35,9 +35,12 @@ export class WecomRuntime {
35
35
  #logger;
36
36
  #diagnostics;
37
37
  #replyTimeoutMs;
38
+ #streamRotateAfterMs;
39
+ #streamSilentProbeMs;
38
40
  #connectTimeoutMs;
39
41
  #maxReconnectAttempts;
40
42
  #createClient;
43
+ #createBridge;
41
44
  #status = createWecomRuntimeStatus();
42
45
  #client = null;
43
46
  #bridge = null;
@@ -54,9 +57,12 @@ export class WecomRuntime {
54
57
  accessPolicy,
55
58
  logger = console,
56
59
  replyTimeoutMs = 600_000,
60
+ streamRotateAfterMs = 510_000,
61
+ streamSilentProbeMs = 120_000,
57
62
  connectTimeoutMs = 20_000,
58
63
  maxReconnectAttempts = 10,
59
64
  createClient = (options) => new WSClient(options),
65
+ createBridge = (options) => new WecomHarnessBridge(options),
60
66
  }) {
61
67
  if (!config || !secret || !harness || !state) {
62
68
  throw new TypeError('WecomRuntime requires config, secret, Harness, and state');
@@ -68,7 +74,10 @@ export class WecomRuntime {
68
74
  this.#contextEnhancement = contextEnhancement;
69
75
  this.#accessPolicy = accessPolicy;
70
76
  this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'wecom', logger });
77
+ this.#createBridge = createBridge;
71
78
  this.#replyTimeoutMs = replyTimeoutMs;
79
+ this.#streamRotateAfterMs = streamRotateAfterMs;
80
+ this.#streamSilentProbeMs = streamSilentProbeMs;
72
81
  this.#connectTimeoutMs = connectTimeoutMs;
73
82
  this.#maxReconnectAttempts = maxReconnectAttempts;
74
83
  this.#createClient = createClient;
@@ -119,7 +128,7 @@ export class WecomRuntime {
119
128
  throw new TypeError('Enterprise WeChat client factory returned an invalid client');
120
129
  }
121
130
  this.#client = client;
122
- this.#bridge = new WecomHarnessBridge({
131
+ this.#bridge = this.#createBridge({
123
132
  client,
124
133
  harness: this.#harness,
125
134
  state: this.#state,
@@ -128,6 +137,8 @@ export class WecomRuntime {
128
137
  status: this.#status,
129
138
  logger: this.#logger,
130
139
  replyTimeoutMs: this.#replyTimeoutMs,
140
+ streamRotateAfterMs: this.#streamRotateAfterMs,
141
+ streamSilentProbeMs: this.#streamSilentProbeMs,
131
142
  signal,
132
143
  });
133
144