dsh-tg-bridge 1.38.4 → 1.38.6
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/chat/media.mjs +50 -13
- package/docs/CHANGELOG.md +31 -0
- package/i18n/en/core.mjs +2 -0
- package/i18n/ru/core.mjs +2 -0
- package/i18n/zh/core.mjs +2 -0
- package/package.json +1 -1
- package/profile/settings-press.mjs +25 -9
- package/turn/progress.mjs +15 -0
package/chat/media.mjs
CHANGED
|
@@ -54,7 +54,20 @@ export function transcribe(file, voice = {}) {
|
|
|
54
54
|
const provider = voiceProvider(voice);
|
|
55
55
|
if (provider === 'openai') return transcribeHttp(file, voice);
|
|
56
56
|
if (provider === 'script' || provider === 'command') return transcribeLocal(file, voice, provider === 'script');
|
|
57
|
-
return Promise.resolve({ text: '', error: 'no speech backend: set voice.provider to script, command or openai' });
|
|
57
|
+
return Promise.resolve({ text: '', error: 'no speech backend: set voice.provider to script, command or openai', fatal: true });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Is another attempt pointless?
|
|
62
|
+
*
|
|
63
|
+
* A refused key, a model the server does not have and a rejected request answer
|
|
64
|
+
* the same way on the tenth try, and every try costs a download and, in a batch
|
|
65
|
+
* of clips, a separate failure line in the chat. Load is the opposite: 429 and
|
|
66
|
+
* 5xx are worth the retry, and so is a timeout that named no status at all.
|
|
67
|
+
*/
|
|
68
|
+
export function voiceRefused(status) {
|
|
69
|
+
const code = Number(status);
|
|
70
|
+
return code === 400 || code === 401 || code === 403 || code === 404;
|
|
58
71
|
}
|
|
59
72
|
|
|
60
73
|
/**
|
|
@@ -65,12 +78,12 @@ async function transcribeHttp(file, voice) {
|
|
|
65
78
|
const base = String(voice.baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
|
|
66
79
|
const key = voice.apiKey || process.env[voice.apiKeyEnv || ''] || '';
|
|
67
80
|
// The message goes into the chat, so it names the setting, never the value.
|
|
68
|
-
if (!key) return { text: '', error: `no key for ${base}: set voice.apiKey or voice.apiKeyEnv
|
|
81
|
+
if (!key) return { text: '', error: `no key for ${base}: set voice.apiKey or voice.apiKeyEnv`, fatal: true };
|
|
69
82
|
let audio;
|
|
70
83
|
try {
|
|
71
84
|
audio = readFileSync(file);
|
|
72
85
|
} catch (error) {
|
|
73
|
-
return { text: '', error: `cannot read the audio: ${error.code || error.message}
|
|
86
|
+
return { text: '', error: `cannot read the audio: ${error.code || error.message}`, fatal: true };
|
|
74
87
|
}
|
|
75
88
|
const form = new FormData();
|
|
76
89
|
form.set('file', new Blob([audio]), basename(file));
|
|
@@ -93,7 +106,7 @@ async function transcribeHttp(file, voice) {
|
|
|
93
106
|
// Some providers put a readable reason in the body ("model not found", "bad
|
|
94
107
|
// key"); keep it short and log it without the key or the audio.
|
|
95
108
|
log(`voice http ${res.status} from ${base}: ${raw.slice(0, 200)}`);
|
|
96
|
-
return { text: '', error: `the speech endpoint answered ${res.status}
|
|
109
|
+
return { text: '', error: `the speech endpoint answered ${res.status}`, status: res.status, fatal: voiceRefused(res.status) };
|
|
97
110
|
}
|
|
98
111
|
let text = '';
|
|
99
112
|
try {
|
|
@@ -116,7 +129,7 @@ function transcribeLocal(file, voice, useScript) {
|
|
|
116
129
|
// way to install it, and it is not an interpreter that will run our script.
|
|
117
130
|
if (useScript && (!isAbsolute(command) || !isAbsolute(voice.script))) {
|
|
118
131
|
log(`voice: python=${command} script=${voice.script} — both must be absolute`);
|
|
119
|
-
return Promise.resolve({ text: '', error: 'voice.python and voice.script must be absolute paths' });
|
|
132
|
+
return Promise.resolve({ text: '', error: 'voice.python and voice.script must be absolute paths', fatal: true });
|
|
120
133
|
}
|
|
121
134
|
const cwd = voice.cwd || (existsSync(DIR) ? DIR : tmpdir());
|
|
122
135
|
// `DIR` is the live install, and it exists on every machine that finished
|
|
@@ -128,7 +141,7 @@ function transcribeLocal(file, voice, useScript) {
|
|
|
128
141
|
// than the setting that is actually wrong.
|
|
129
142
|
if (voice.cwd && !(existsSync(cwd) && statSync(cwd).isDirectory())) {
|
|
130
143
|
log(`voice: cwd=${cwd} is not a directory`);
|
|
131
|
-
return Promise.resolve({ text: '', error: 'voice.cwd is not a directory' });
|
|
144
|
+
return Promise.resolve({ text: '', error: 'voice.cwd is not a directory', fatal: true });
|
|
132
145
|
}
|
|
133
146
|
// `{out}` is a temp path the engine may write to: whisper.cpp is not the only
|
|
134
147
|
// program people run — Vosk, WhisperX, GigaAM wrappers and plain ffmpeg chains
|
|
@@ -257,22 +270,33 @@ export async function readVoiceIntoText(msg, chatId, threadId, lang) {
|
|
|
257
270
|
};
|
|
258
271
|
let heard = '';
|
|
259
272
|
let error = '';
|
|
273
|
+
let fatal = false;
|
|
274
|
+
let status = 0;
|
|
260
275
|
try {
|
|
261
|
-
|
|
276
|
+
const got = await voiceToText(msg, config.voice);
|
|
277
|
+
heard = got.text;
|
|
278
|
+
error = got.error;
|
|
279
|
+
fatal = Boolean(got.fatal);
|
|
280
|
+
status = Number(got.status) || 0;
|
|
262
281
|
} catch (err) {
|
|
263
282
|
const fail = t(lang, 'msg.voiceDownloadFailed', { err: err.message });
|
|
264
283
|
await editOrSend(`⚠️ ${fail}`, fail);
|
|
265
|
-
return '';
|
|
284
|
+
return { text: '', fatal: false };
|
|
266
285
|
}
|
|
267
286
|
if (!heard) {
|
|
268
|
-
|
|
287
|
+
// A refused key is not a misheard word: "не распознал голосовое" would send
|
|
288
|
+
// the person to re-record something the engine never listened to, and the
|
|
289
|
+
// fix is in `voice.apiKey`, which the refusal line names.
|
|
290
|
+
const fail = fatal && status
|
|
291
|
+
? t(lang, 'msg.voiceRefused', { status })
|
|
292
|
+
: t(lang, 'msg.voiceNotRecognized', { detail: error ? `: ${error}` : '' });
|
|
269
293
|
await editOrSend(`⚠️ ${fail}`, fail);
|
|
270
|
-
return '';
|
|
294
|
+
return { text: '', fatal };
|
|
271
295
|
}
|
|
272
296
|
log(`voice -> text len=${heard.length}${error ? ` (warn: ${error})` : ''}`);
|
|
273
297
|
const preview = heard.length > 1200 ? `${heard.slice(0, 1200)}…` : heard;
|
|
274
298
|
if (statusId || config.voice?.echo !== false) await editOrSend(`🎤 ${preview}`, `🎤 ${preview}`);
|
|
275
|
-
return heard;
|
|
299
|
+
return { text: heard, fatal: false };
|
|
276
300
|
}
|
|
277
301
|
|
|
278
302
|
/**
|
|
@@ -314,6 +338,12 @@ export async function mediaPrompt(msgs, chatId, threadId, lang, opts = {}) {
|
|
|
314
338
|
// saw the bot ignore them, and nothing said the engine was missing. Once per
|
|
315
339
|
// batch is enough — an album of clips must not repeat the same line.
|
|
316
340
|
let voiceTold = false;
|
|
341
|
+
// A refused key or a model the engine does not have answers the same way for
|
|
342
|
+
// every clip in the batch. Sending the next one would cost another download
|
|
343
|
+
// and print an identical warning, so the rest are counted, not sent, and one
|
|
344
|
+
// line at the end says so.
|
|
345
|
+
let voiceRefused = false;
|
|
346
|
+
let voiceSkipped = 0;
|
|
317
347
|
for (const msg of list) {
|
|
318
348
|
if (!caption && (msg.caption || '').trim()) caption = msg.caption.trim();
|
|
319
349
|
if (msg.voice || msg.audio) {
|
|
@@ -325,15 +355,19 @@ export async function mediaPrompt(msgs, chatId, threadId, lang, opts = {}) {
|
|
|
325
355
|
}
|
|
326
356
|
continue;
|
|
327
357
|
}
|
|
358
|
+
if (voiceRefused) { voiceSkipped += 1; continue; }
|
|
328
359
|
const heard = await readVoiceIntoText(msg, chatId, threadId, lang);
|
|
329
|
-
if (heard)
|
|
360
|
+
if (heard.fatal) { voiceRefused = true; continue; }
|
|
361
|
+
if (heard.text) parts.push(voicePromptText(heard.text, lang));
|
|
330
362
|
continue;
|
|
331
363
|
}
|
|
332
364
|
// An audio file sent as a document is a voice note with a different
|
|
333
365
|
// wrapper: transcribe it instead of handing over a path nobody can listen to.
|
|
334
366
|
if (msg.document?.mime_type?.startsWith('audio/') && voiceOn) {
|
|
367
|
+
if (voiceRefused) { voiceSkipped += 1; continue; }
|
|
335
368
|
const heard = await readVoiceIntoText({ ...msg, audio: msg.document }, chatId, threadId, lang);
|
|
336
|
-
if (heard)
|
|
369
|
+
if (heard.fatal) { voiceRefused = true; continue; }
|
|
370
|
+
if (heard.text) parts.push(voicePromptText(heard.text, lang));
|
|
337
371
|
continue;
|
|
338
372
|
}
|
|
339
373
|
// Photo handling: the turn's own model reads the file through `read_image`.
|
|
@@ -392,6 +426,9 @@ export async function mediaPrompt(msgs, chatId, threadId, lang, opts = {}) {
|
|
|
392
426
|
const liveNow = opts.stillRunning ? opts.stillRunning() : true;
|
|
393
427
|
if (text && photo && opts.steer && liveNow) text += `\n\n${t(lang, 'prompt.photoMidTurn')}`;
|
|
394
428
|
if (text && caption) text += `\n\n${t(lang, 'prompt.note', { note: caption })}`;
|
|
429
|
+
// Said once, after the batch: the first clip already explained the refusal,
|
|
430
|
+
// and silence about the rest would look like they were ignored.
|
|
431
|
+
if (voiceSkipped) await send(chatId, t(lang, 'msg.voiceRefusedRest'), threadId);
|
|
395
432
|
return { text, extraArgs, profile };
|
|
396
433
|
}
|
|
397
434
|
|
package/docs/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# CHANGELOG — DSH Telegram bridge
|
|
2
2
|
|
|
3
|
+
## 1.38.6
|
|
4
|
+
|
|
5
|
+
- **A refused key is no longer reported as an unrecognised voice message.** A
|
|
6
|
+
speech engine answering 401 or 404 says the same thing on every attempt, but
|
|
7
|
+
the chat got «Не распознал голосовое» — the same sentence a mumbled clip gets —
|
|
8
|
+
and the batch sent every clip through the same doomed request. The transcript
|
|
9
|
+
result now carries `fatal` and the status: a refused key, a model the server
|
|
10
|
+
does not have, a rejected request, a missing key, a broken `voice.cwd` or a
|
|
11
|
+
non-absolute `voice.python` all stop the batch at the first clip and say which
|
|
12
|
+
setting to fix. Load is left retryable, because 429 and 5xx do change their
|
|
13
|
+
mind: those keep the old line, with the status in it.
|
|
14
|
+
- **The rest of a batch is counted, not sent.** One refusal explained, the
|
|
15
|
+
remaining clips are skipped and one line at the end says how many were left
|
|
16
|
+
out — previously each clip cost a download and printed the identical warning.
|
|
17
|
+
|
|
18
|
+
## 1.38.5
|
|
19
|
+
|
|
20
|
+
- **The settings card opens the thing it names.** A row like «Модель» runs
|
|
21
|
+
`/model`, whose answer is a card with buttons. The press handler kept only the
|
|
22
|
+
text of whatever the command answered, so the model card arrived as a plain
|
|
23
|
+
message: it named the current model and gave no way to change it — the settings
|
|
24
|
+
screen could describe the install but not edit it. A card-shaped answer is now
|
|
25
|
+
sent under the settings card with its keyboard, in the topic it was asked in,
|
|
26
|
+
and a plain answer still comes as one line. `/fallback`, `/permissions`,
|
|
27
|
+
`/preset` and `/cd` sit behind the same door and open the same way.
|
|
28
|
+
- **The last thought of a turn reaches the card.** The progress card re-reads the
|
|
29
|
+
decision trail every three seconds, so a line written in the final seconds —
|
|
30
|
+
"the result is checked", the one that says how the turn ended — landed between
|
|
31
|
+
two ticks and never appeared at all. The card now reads the trail once more
|
|
32
|
+
before it is finished, and only while `/thoughts` is not off.
|
|
33
|
+
|
|
3
34
|
## 1.38.4
|
|
4
35
|
|
|
5
36
|
- **A rewind button no longer answers "undefined".** `answerRewindPress()` was
|
package/i18n/en/core.mjs
CHANGED
|
@@ -205,6 +205,8 @@ export default {
|
|
|
205
205
|
'menu.lang': 'Interface language: en, ru, zh',
|
|
206
206
|
'msg.voiceDownloadFailed': 'Could not download the voice message: {err}',
|
|
207
207
|
'msg.voiceNotRecognized': 'Could not make out the voice message{detail}',
|
|
208
|
+
'msg.voiceRefused': 'The speech engine refused the request (status {status}) — the key was not accepted. Check voice.apiKey or voice.apiKeyEnv.',
|
|
209
|
+
'msg.voiceRefusedRest': 'The rest of the clips in this batch were not sent: the engine would answer the same way.',
|
|
208
210
|
'msg.voiceOff': '🎤 Voice transcription is not set up here. `voice` takes any engine: a local script (`voice.python` + `voice.script`), any CLI (`voice.command` + `voice.args`), or an OpenAI-compatible API (`voice.baseUrl` + `voice.model` + a key). Ready-made blocks are in docs/VOICE.md.',
|
|
209
211
|
'prompt.photo': 'Look at the image at {path} and describe it in detail: text (verbatim, keeping its language), interface elements, objects.',
|
|
210
212
|
'prompt.file': 'The user sent a file: {path} ({type}, {size} bytes).',
|
package/i18n/ru/core.mjs
CHANGED
|
@@ -205,6 +205,8 @@ export default {
|
|
|
205
205
|
'menu.lang': 'Язык интерфейса: en, ru, zh',
|
|
206
206
|
'msg.voiceDownloadFailed': 'Не смог скачать голосовое: {err}',
|
|
207
207
|
'msg.voiceNotRecognized': 'Не распознал голосовое{detail}',
|
|
208
|
+
'msg.voiceRefused': 'Движок распознавания отказал (код {status}) — ключ не принят. Проверьте voice.apiKey или voice.apiKeyEnv.',
|
|
209
|
+
'msg.voiceRefusedRest': 'Остальные голосовые из этой пачки не отправлял: ответ движка был бы тот же.',
|
|
208
210
|
'msg.voiceOff': '🎤 Расшифровка голоса здесь не настроена. В `voice` подойдёт любой движок: локальный скрипт (`voice.python` + `voice.script`), любая CLI (`voice.command` + `voice.args`) или OpenAI-совместимый API (`voice.baseUrl` + `voice.model` + ключ). Готовые блоки — в docs/VOICE.md.',
|
|
209
211
|
'prompt.photo': 'Посмотри изображение по пути {path} и подробно опиши, что на нём: текст (дословно, с сохранением языка), элементы интерфейса, объекты.',
|
|
210
212
|
'prompt.file': 'Пользователь прислал файл: {path} ({type}, {size} байт).',
|
package/i18n/zh/core.mjs
CHANGED
|
@@ -205,6 +205,8 @@ export default {
|
|
|
205
205
|
'menu.lang': '界面语言:en、ru、zh',
|
|
206
206
|
'msg.voiceDownloadFailed': '语音下载失败:{err}',
|
|
207
207
|
'msg.voiceNotRecognized': '没能识别这条语音{detail}',
|
|
208
|
+
'msg.voiceRefused': '语音引擎拒绝了请求(状态码 {status})——密钥未被接受。请检查 voice.apiKey 或 voice.apiKeyEnv。',
|
|
209
|
+
'msg.voiceRefusedRest': '这批里其余语音没有发送:引擎的答复会一样。',
|
|
208
210
|
'msg.voiceOff': '🎤 这里还没有配置语音转写。`voice` 可以接任意引擎:本地脚本(`voice.python` + `voice.script`)、任意命令行(`voice.command` + `voice.args`),或 OpenAI 兼容接口(`voice.baseUrl` + `voice.model` + 密钥)。现成配置见 docs/VOICE.md。',
|
|
209
211
|
'prompt.photo': '查看路径 {path} 的图片并详细描述:文字(逐字,保留原语言)、界面元素、物体。',
|
|
210
212
|
'prompt.file': '用户发来文件:{path}({type},{size} 字节)。',
|
package/package.json
CHANGED
|
@@ -21,7 +21,7 @@ import { DIR } from '../core/paths.mjs';
|
|
|
21
21
|
import { maxParallel } from '../turn/queue.mjs';
|
|
22
22
|
import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
|
|
23
23
|
import { config, log, saveConfig, saveState, state } from '../core/state.mjs';
|
|
24
|
-
import { inlineKeyboard, send, tg, tgFast } from '../chat/telegram.mjs';
|
|
24
|
+
import { inlineKeyboard, send, sendWithMarkup, tg, tgFast } from '../chat/telegram.mjs';
|
|
25
25
|
import { activeTurns, baseProfileOf } from '../turn/turn.mjs';
|
|
26
26
|
import { join } from 'node:path';
|
|
27
27
|
|
|
@@ -92,6 +92,17 @@ export async function handleCardPress(query, ctx) {
|
|
|
92
92
|
// in the chat: the one line below is the chat's share of this press. Only a
|
|
93
93
|
// command that failed says more than that.
|
|
94
94
|
const replies = [];
|
|
95
|
+
// A command may answer with buttons — `/model` and `/fallback` are cards whose
|
|
96
|
+
// whole point is their keyboard. The adapters below used to keep only the text,
|
|
97
|
+
// so the settings door to the model picker opened onto a message that named the
|
|
98
|
+
// current model and offered no way to change it.
|
|
99
|
+
const cards = [];
|
|
100
|
+
const collect = (text, extra = {}) => {
|
|
101
|
+
const body = String(text ?? '');
|
|
102
|
+
if (extra?.keyboard || extra?.reply_markup) cards.push({ body, extra });
|
|
103
|
+
else replies.push(body);
|
|
104
|
+
return Promise.resolve(0);
|
|
105
|
+
};
|
|
95
106
|
// A press that fails has to say so: the card is redrawn either way, and a
|
|
96
107
|
// redraw alone looks exactly like success. The old path hid failures behind a
|
|
97
108
|
// line the person read as a confirmation.
|
|
@@ -113,14 +124,8 @@ export async function handleCardPress(query, ctx) {
|
|
|
113
124
|
// and vanish on restart, which is the worst of both answers.
|
|
114
125
|
saveConfig,
|
|
115
126
|
log,
|
|
116
|
-
send:
|
|
117
|
-
|
|
118
|
-
return Promise.resolve(0);
|
|
119
|
-
},
|
|
120
|
-
reply: (text) => {
|
|
121
|
-
replies.push(String(text ?? ''));
|
|
122
|
-
return Promise.resolve(0);
|
|
123
|
-
},
|
|
127
|
+
send: collect,
|
|
128
|
+
reply: collect,
|
|
124
129
|
jobs: () => ({ active: [], queued: 0, max: maxParallel() }),
|
|
125
130
|
api: tg,
|
|
126
131
|
sendFile: () => Promise.resolve(0),
|
|
@@ -151,6 +156,17 @@ export async function handleCardPress(query, ctx) {
|
|
|
151
156
|
// a failure is on the card too, so it is not repeated below it.
|
|
152
157
|
if (!handled) log(`settings press ${data}: no handler answered`);
|
|
153
158
|
const notLine = replies.filter(Boolean).filter((r) => r !== wanted.command);
|
|
159
|
+
// A card-shaped answer goes under the settings card, with its buttons: the press
|
|
160
|
+
// asked to go somewhere, and swallowing the keyboard is what made
|
|
161
|
+
// `/settings → Модель` a screen you could read but not act on.
|
|
162
|
+
if (cards.length > 0 && !failed) {
|
|
163
|
+
const card = cards[0];
|
|
164
|
+
await sendWithMarkup(chatId, threadId, card.body, card.extra).catch((error) => {
|
|
165
|
+
log(`settings press ${data}: card with buttons failed (${error.message})`);
|
|
166
|
+
return send(chatId, card.body, threadId).catch(() => {});
|
|
167
|
+
});
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
154
170
|
if (notLine.length > 0 && !changed && !failed) {
|
|
155
171
|
await send(chatId, notLine[0], threadId).catch(() => {});
|
|
156
172
|
}
|
package/turn/progress.mjs
CHANGED
|
@@ -371,6 +371,21 @@ export async function startProgress(chatId, threadId, lang = config.lang || 'en'
|
|
|
371
371
|
async finish(result) {
|
|
372
372
|
clearTimeout(timer);
|
|
373
373
|
clearInterval(thoughtTimer);
|
|
374
|
+
// One last read before the card is finished. A thought written in the last
|
|
375
|
+
// seconds of a turn — "the result is checked", usually, the line that matters
|
|
376
|
+
// most — used to land between two ticks of the loop above and never reach the
|
|
377
|
+
// card at all. The trail is written until the turn ends, so the last read has
|
|
378
|
+
// to happen at the end too.
|
|
379
|
+
if (reasoningMode(state, config, panelKey) !== 'off') {
|
|
380
|
+
try {
|
|
381
|
+
const rows = thoughtRows([notes, topicNotes], started);
|
|
382
|
+
const merged = rows.slice(-2).map((row) => row.text);
|
|
383
|
+
if (merged.join('\n') !== thoughts.join('\n')) thoughts = merged;
|
|
384
|
+
} catch {
|
|
385
|
+
// An unreadable file leaves the last known lines in place: the card is
|
|
386
|
+
// worth more than an empty promise of a trail.
|
|
387
|
+
}
|
|
388
|
+
}
|
|
374
389
|
if (result?.stopped) {
|
|
375
390
|
// The person pressed Стоп. The card says so in their words, not with a
|
|
376
391
|
// ⚠️ and not with a retry button: nothing failed, and the session is
|