@xmanrui/dsh-im 5.4.0 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +44 -3
  4. package/README.md +44 -3
  5. package/lib/client.js +2293 -444
  6. package/lib/index.js +402 -335
  7. package/package.json +1 -1
  8. package/plugin-src/client/channel-card-meta.js +6 -2
  9. package/plugin-src/client/channels/shared/token-api.js +13 -0
  10. package/plugin-src/client/channels/telegram/styles.js +4 -0
  11. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  12. package/plugin-src/client/delivery-settings.js +2 -2
  13. package/plugin-src/client/i18n-ru.js +1615 -0
  14. package/plugin-src/client/i18n.js +71 -0
  15. package/plugin-src/client/index.js +8 -1
  16. package/plugin-src/host/channels/shared/production.mjs +5 -0
  17. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  18. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  19. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  20. package/plugin-src/host/channels/telegram/production.mjs +7 -0
  21. package/plugin-src/host/delivery-adapter.mjs +41 -33
  22. package/plugin-src/host/delivery-service.mjs +42 -0
  23. package/plugin-src/host/ds-bot-client.mjs +31 -18
  24. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  25. package/plugin-src/host/index.mjs +3 -0
  26. package/plugin-src/host/modern-harness-api.mjs +53 -8
  27. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  28. package/scripts/verify-package.mjs +17 -5
  29. package/src/channels/feishu/bridge.mjs +83 -5
  30. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  31. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  32. package/src/channels/shared/AGENTS.md +19 -0
  33. package/src/channels/shared/clear-command.mjs +2 -1
  34. package/src/channels/shared/compact-command.mjs +2 -1
  35. package/src/channels/shared/conversation-queue.mjs +49 -0
  36. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  37. package/src/channels/shared/harness-client.mjs +5 -4
  38. package/src/channels/shared/history-command.mjs +2 -1
  39. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  40. package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
  41. package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
  42. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  43. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  44. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  45. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  46. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  47. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  48. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  49. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  50. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  51. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  52. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  53. package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
  54. package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
  55. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  56. package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
  57. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  58. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  59. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  60. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  61. package/src/channels/shared/i18n-ru.mjs +48 -0
  62. package/src/channels/shared/i18n.mjs +47 -12
  63. package/src/channels/shared/inbound-access.mjs +1 -1
  64. package/src/channels/shared/interface-language.mjs +3 -3
  65. package/src/channels/shared/message-failure.mjs +3 -2
  66. package/src/channels/shared/model-command.mjs +2 -1
  67. package/src/channels/shared/permission-command.mjs +2 -1
  68. package/src/channels/shared/send-limit.mjs +38 -0
  69. package/src/channels/shared/session-error.mjs +3 -0
  70. package/src/channels/shared/status-reaction.mjs +2 -0
  71. package/src/channels/shared/text-harness-bridge.mjs +4 -0
  72. package/src/channels/shared/thinking-cadence.mjs +36 -0
  73. package/src/channels/shared/workspace-command.mjs +2 -1
  74. package/src/channels/telegram/config-store.mjs +34 -1
  75. package/src/channels/telegram/telegram-api.mjs +211 -32
  76. package/src/channels/telegram/telegram-bridge.mjs +4 -1
  77. package/src/channels/telegram/telegram-controller.mjs +29 -0
  78. package/src/channels/telegram/telegram-runtime.mjs +507 -176
  79. package/src/channels/telegram/voice.mjs +250 -0
@@ -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
+ }