dsh-tg-bridge 1.51.2 → 1.52.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.
@@ -20,6 +20,7 @@ import { handleModelPress, MODEL_PREFIX, modelPressRouter } from '../control/mod
20
20
  import { runCommandFromButton } from '../core/run-command.mjs';
21
21
  import { handleCardPress } from '../profile/settings-press.mjs';
22
22
  import { cardBlocks, cardKeyboard, renderCardSettings, toggleCardBlock } from '../turn/card.mjs';
23
+ import { handleVoicePress, isVoicePress } from './voice-press.mjs';
23
24
  import { handleFilePress } from './file-press.mjs';
24
25
  import { handleMcpPress } from './mcp-press.mjs';
25
26
  import { handlePlanPress } from './plan-press.mjs';
@@ -89,6 +90,9 @@ export async function handleCallback(query) {
89
90
  return;
90
91
  }
91
92
 
93
+ // `/voice`'s button: flip the topic's setting and redraw the card that shows it.
94
+ if (isVoicePress(data)) { await handleVoicePress({ data, query, state, key, config, lang, saveState, answer }); guard.mark(); return; }
95
+
92
96
  // `/dsh`'s own two presses. Each types the command the card advertised, so the
93
97
  // install path and the confirmation in front of it exist exactly once — a
94
98
  // button that called npm itself would be a second way to replace the harness.
@@ -20,7 +20,7 @@ export const CONTROL_COMMANDS = [
20
20
  'prices', 'cost', 'balance', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
21
21
  'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
22
22
  'rewind', 'fork', 'branches', 'branch', 'history', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find', 'start', 'regen',
23
- 'ls', 'view', 'edit', 'subagents',
23
+ 'ls', 'view', 'edit', 'subagents', 'voice',
24
24
  ];
25
25
 
26
26
  /**
@@ -69,5 +69,5 @@ export const DOCUMENTED_COMMANDS = CONTROL_COMMANDS.filter((name) => !COMMAND_AL
69
69
  */
70
70
  export const MENU_COMMANDS = [
71
71
  'new', 'status', 'diff', 'sessions', 'goal', 'tasks', 'model', 'plugins',
72
- 'settings', 'menu', 'rewind', 'stop', 'help', 'update',
72
+ 'settings', 'menu', 'rewind', 'stop', 'help', 'update', 'voice',
73
73
  ];
package/chat/control.mjs CHANGED
@@ -49,6 +49,7 @@ import { handleEditCommands } from '../control/cmd-edit.mjs';
49
49
  import { handleFindCommands } from '../control/cmd-find.mjs';
50
50
  import { handleDshCommands } from '../control/cmd-dsh.mjs';
51
51
  import { handleCompactCommands } from '../control/cmd-compact.mjs';
52
+ import { handleVoiceCommands } from '../control/cmd-voice.mjs';
52
53
  import { APP, CLI_JS, DSH_CMD, DSH_HOME, EXE, HOME, PROFILES, THOUGHT_DIR } from '../core/paths.mjs';
53
54
  import { read, readJson, patchPath, pkgPath, OVERLAY_MARK, modelsOf, modelOf, windowOf, modelIndent, depthOf, modelsReport, setModel, disabledIds, setDisabled, writePatch } from '../control/models.mjs';
54
55
  import { listPids, waitForExit, waitForStart, pluginsOf, bundleRowIds, addBundle, removeBundle, createProfile, dshPlugin } from '../control/plugins.mjs';
@@ -120,7 +121,7 @@ export async function handleControl(ctx) {
120
121
  // that is not its job. The order is alphabetical, not meaningful: no two
121
122
  // groups claim the same command, so a miss falls through to `default` below.
122
123
  const child = { ...ctx, effective, command, arg: effectiveArgText, send, reply, log, profile, state, key, config, lang };
123
- for (const handler of [handleAgentCommands, handleBridgeCommands, handleCardCommands, handleCompactCommands, handleDiffCommands, handleEditCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleFileCommands, handleFindCommands, handleLoadCommands, handleMcpCommands, handlePlanCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleStartCommands, handleSubagentCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
124
+ for (const handler of [handleAgentCommands, handleBridgeCommands, handleCardCommands, handleCompactCommands, handleDiffCommands, handleEditCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleFileCommands, handleFindCommands, handleLoadCommands, handleMcpCommands, handlePlanCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleStartCommands, handleSubagentCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands, handleVoiceCommands]) {
124
125
  if (await handler(child)) return true;
125
126
  }
126
127
  // Nothing claimed it: the bridge answers an unknown `/` command itself, with
@@ -20,7 +20,7 @@ import { holdIfLoaded } from '../work/load-guard.mjs';
20
20
  import { guardOf } from '../core/machine.mjs';
21
21
  import { mediaPrompt } from './media.mjs';
22
22
  import { keyboardCommand } from './menu-card.mjs';
23
- import { replyText } from './reply-guard.mjs';
23
+ import { deliverAnswer, replyText } from './reply-guard.mjs';
24
24
  import { QUIET_MS, quietGuard } from './quiet-guard.mjs';
25
25
  import { DIR, GOAL_CMD, SAY, THOUGHT_DIR } from '../core/paths.mjs';
26
26
  import { renderPrices } from '../model/prices.mjs';
@@ -484,7 +484,7 @@ ${helpLines((k, vars) => t(lang, k, vars)).join('\n')}`,
484
484
  await send(chatId, t(lang, 'bridge.progress.reasoningOnly'), threadId);
485
485
  return;
486
486
  }
487
- await send(chatId, reply.text || t(lang, 'bridge.progress.emptyReply'), threadId);
487
+ await deliverAnswer({ send, chatId, threadId, state, key, text: reply.text, empty: t(lang, 'bridge.progress.emptyReply'), config, lang, log });
488
488
  // The card under a plan: the only way out of plan mode, and the reason the
489
489
  // request is kept — Approve replays it with the flag already cleared.
490
490
  if (!result.error && planOf(state, key)) await planFollowUp({ state, key, lang, request, saveState, send: (body, kb) => sendWithMarkup(chatId, threadId, body, { reply_markup: kb }) });
@@ -26,7 +26,7 @@ export const HELP_SECTIONS = [
26
26
  { id: 'tuning', commands: ['jobs', 'remind', 'every'] },
27
27
  { id: 'extensions', commands: ['skills', 'plugins', 'mcp', 'soul', 'remember'] },
28
28
  { id: 'versions', commands: ['update', 'subscribe', 'dsh'] },
29
- { id: 'settings', commands: ['settings', 'lang', 'reasoning', 'pin'] },
29
+ { id: 'settings', commands: ['settings', 'lang', 'reasoning', 'pin', 'voice'] },
30
30
  { id: 'panels', commands: ['menu', 'help'] },
31
31
  { id: 'health', commands: ['doctor', 'logs', 'report', 'app', 'restart'] },
32
32
  ];
@@ -18,7 +18,7 @@ const SECTIONS = {
18
18
  work: ['cd', 'ls', 'view', 'edit', 'seed', 'send', 'diff'],
19
19
  session: ['sessions', 'rewind', 'regen', 'branch', 'history', 'profile', 'agents', 'subagents'],
20
20
  goals: ['goal', 'task', 'tasks', 'plan', 'jobs', 'remind', 'every'],
21
- talk: ['effort', 'reasoning', 'pin', 'thoughts', 'prices', 'cost', 'balance', 'lang', 'endpoint', 'fallback'],
21
+ talk: ['effort', 'reasoning', 'pin', 'thoughts', 'prices', 'cost', 'balance', 'lang', 'endpoint', 'fallback', 'voice'],
22
22
  ext: ['plugins', 'mcp', 'skills', 'soul', 'remember', 'preset', 'permissions', 'crew'],
23
23
  house: ['load', 'settings', 'card', 'find', 'update', 'dsh', 'compact', 'subscribe', 'doctor', 'logs', 'report', 'restart', 'app', 'start', 'help'],
24
24
  };
@@ -11,8 +11,23 @@
11
11
  // subject is "one incoming message becomes one turn", not "what a reply is".
12
12
  import { languageRequest, scrubReply } from './answer-shape.mjs';
13
13
  import { LANG_NUDGE, looksLikeReasoning, REPLY_NUDGE, stripThinkingBlocks } from './panel.mjs';
14
+ import { speak } from './speech.mjs';
14
15
  import { turnAttempt } from '../turn/turn.mjs';
15
16
 
17
+ /**
18
+ * Send the finished answer: words first, sound after.
19
+ *
20
+ * Both live here because "what the chat gets" is this module's subject, and the
21
+ * order is the promise: a voice that hangs, a missing engine or an outage costs
22
+ * the sound and never the answer. `speak` decides for itself whether this topic
23
+ * asked for sound, and returns without a call when it did not.
24
+ */
25
+ export async function deliverAnswer({ send, chatId, threadId, state, key, text, empty, config, lang, log, say = speak }) {
26
+ const shown = text || empty;
27
+ await send(chatId, shown, threadId);
28
+ void say({ chatId, threadId, state, key, text: shown, config, lang, log });
29
+ }
30
+
16
31
  /** Is this text the reasoning the panel already holds, markers included? */
17
32
  export function isReasoningEcho(value, reasoning) {
18
33
  return looksLikeReasoning(value, reasoning);
@@ -0,0 +1,145 @@
1
+ // Speaking an answer out loud, when the person cannot read right now.
2
+ //
3
+ // The text always goes first and never waits for the voice: a TTS that hangs,
4
+ // a missing engine or a provider outage must cost the sound, not the answer.
5
+ // Every failure here is logged and swallowed for that reason.
6
+ //
7
+ // The engine is not built in. `speech.provider` names what to run and
8
+ // `speech.args` carries its arguments, so a local Piper model and a network
9
+ // voice are the same code path — the project already decided (task 83) that
10
+ // voice is a door, not a feature of the bridge.
11
+ import { execFile } from 'node:child_process';
12
+ import { promisify } from 'node:util';
13
+ import { mkdtempSync, rmSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { sendVoice } from './telegram.mjs';
17
+
18
+ const run = promisify(execFile);
19
+
20
+ /**
21
+ * A male voice per language, used when the config names none.
22
+ *
23
+ * The person's own requirement: "мужской голос, хороший". These are the
24
+ * voices that were actually checked on this machine; an unknown language
25
+ * falls back to the first entry, not to silence.
26
+ */
27
+ export const DEFAULT_VOICES = {
28
+ ru: 'ru-RU-DmitryNeural',
29
+ en: 'en-US-GuyNeural',
30
+ zh: 'zh-CN-YunjianNeural',
31
+ };
32
+
33
+ /** Longer than this is not a message to listen to, it is a document. */
34
+ export const MAX_SPEECH_CHARS = 1200;
35
+
36
+ /** The config block, with the defaults this module promises. */
37
+ export function speechConfig(config) {
38
+ const raw = config?.speech || {};
39
+ return {
40
+ provider: raw.provider || 'edge-tts',
41
+ python: raw.python || 'python',
42
+ ffmpeg: raw.ffmpeg || 'ffmpeg',
43
+ maxChars: Number(raw.maxChars) > 0 ? Number(raw.maxChars) : MAX_SPEECH_CHARS,
44
+ timeoutMs: Number(raw.timeoutMs) > 0 ? Number(raw.timeoutMs) : 120000,
45
+ voices: { ...DEFAULT_VOICES, ...(raw.voices || {}) },
46
+ };
47
+ }
48
+
49
+ /** Is the voice on for this topic, and in which voice? */
50
+ export function speechOf(state, key, config, lang = 'ru') {
51
+ const settings = (state?.speech && state.speech[key]) || {};
52
+ const cfg = speechConfig(config);
53
+ return {
54
+ on: settings.on === true,
55
+ voice: settings.voice || cfg.voices[lang] || cfg.voices.ru,
56
+ };
57
+ }
58
+
59
+ /** Turn the voice on or off for one topic. Returns the new setting. */
60
+ export function setSpeech(state, key, patch, config, lang = 'ru') {
61
+ if (!state.speech) state.speech = {};
62
+ const before = speechOf(state, key, config, lang);
63
+ const next = { ...before, ...patch };
64
+ state.speech[key] = next;
65
+ return next;
66
+ }
67
+
68
+ /**
69
+ * What the ear gets, from what the eye got.
70
+ *
71
+ * Code blocks, markup and tables are not speech: reading `**` aloud or spelling
72
+ * out a pipe-separated row makes the message worse than silence. Emoji are
73
+ * dropped for the same reason; a voice model pronounces "🙂" as a pause.
74
+ */
75
+ export function forSpeech(text, maxChars = MAX_SPEECH_CHARS) {
76
+ let out = String(text || '');
77
+ // A fenced block is a document the person will read, not listen to.
78
+ out = out.replace(/```[\s\S]*?```/g, ' ');
79
+ out = out.replace(/`([^`]*)`/g, '$1');
80
+ // Links keep their words, lose their address: nobody wants a URL spelled out.
81
+ out = out.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1');
82
+ out = out.replace(/https?:\/\/\S+/g, ' ');
83
+ out = out.replace(/^\s*\|.*\|\s*$/gm, ' ');
84
+ out = out.replace(/[*_~#>]+/g, ' ');
85
+ out = out.replace(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{FE0F}\u{200D}]/gu, ' ');
86
+ out = out.replace(/\s+/g, ' ').trim();
87
+ if (out.length <= maxChars) return out;
88
+ // Cut at a sentence, not mid-word: a stopped voice sounds like a fault.
89
+ const cut = out.slice(0, maxChars);
90
+ const stop = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf('! '), cut.lastIndexOf('? '));
91
+ return (stop > maxChars * 0.5 ? cut.slice(0, stop + 1) : cut).trim();
92
+ }
93
+
94
+ /** The arguments for one provider run. Kept separate so a test can read them. */
95
+ export function providerArgs(cfg, { text, mp3 }) {
96
+ if (cfg.provider === 'edge-tts') {
97
+ return {
98
+ command: cfg.python,
99
+ args: ['-m', 'edge_tts', '--voice', cfg.voice || DEFAULT_VOICES.ru, '--text', text, '--write-media', mp3],
100
+ };
101
+ }
102
+ // Any other provider receives the text and the target file through the same
103
+ // two placeholders, so a local Piper install is config, not a code change.
104
+ const args = (cfg.args || ['{text}', '{out}']).map((part) =>
105
+ String(part).replace('{text}', text).replace('{out}', mp3));
106
+ return { command: cfg.command || cfg.provider, args };
107
+ }
108
+
109
+ /**
110
+ * Say the answer out loud, if this topic asked for it.
111
+ *
112
+ * @returns {Promise<boolean>} whether a voice note was sent
113
+ */
114
+ export async function speak({ chatId, threadId, state, key, text, config, lang = 'ru', log = () => {} }) {
115
+ const setting = speechOf(state, key, config, lang);
116
+ if (!setting.on) return false;
117
+ const cfg = speechConfig(config);
118
+ const said = forSpeech(text, cfg.maxChars);
119
+ if (!said) return false;
120
+
121
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-speech-'));
122
+ const mp3 = join(dir, 'say.mp3');
123
+ const ogg = join(dir, 'say.ogg');
124
+ try {
125
+ // The provider writes `mp3`; a provider that already speaks OGG/Opus
126
+ // (`speech.ogg: true`) skips the conversion and its ffmpeg dependency.
127
+ const target = cfg.ogg ? ogg : mp3;
128
+ const { command, args } = providerArgs({ ...cfg, voice: setting.voice }, { text: said, mp3: target });
129
+ await run(command, args, { timeout: cfg.timeoutMs, windowsHide: true, maxBuffer: 8 << 20 });
130
+ if (!cfg.ogg) {
131
+ await run(cfg.ffmpeg, ['-y', '-hide_banner', '-loglevel', 'error', '-i', mp3,
132
+ '-c:a', 'libopus', '-b:a', '48k', '-ar', '48000', '-ac', '1', ogg],
133
+ { timeout: cfg.timeoutMs, windowsHide: true });
134
+ }
135
+ await sendVoice(chatId, threadId, ogg);
136
+ log(`spoke ${said.length} chars in ${setting.voice} chat=${chatId}`);
137
+ return true;
138
+ } catch (error) {
139
+ // Loud in the log, silent in the chat: the text already arrived.
140
+ log(`speech failed for chat=${chatId}: ${String(error?.message ?? error).slice(0, 200)}`);
141
+ return false;
142
+ } finally {
143
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* temp dir, best effort */ }
144
+ }
145
+ }
package/chat/telegram.mjs CHANGED
@@ -75,6 +75,27 @@ export async function sendFile(chatId, threadId, filePath, caption = '') {
75
75
  return json.result;
76
76
  }
77
77
 
78
+ /**
79
+ * Upload a spoken answer as a voice note: the bubble a person plays with one tap.
80
+ *
81
+ * Deliberately not `sendAudio`: that arrives as a file with a player, a name and
82
+ * a duration to open, which is the wrong shape for "I cannot read right now".
83
+ * Telegram wants OGG/Opus in the `voice` field, so the caller converts first.
84
+ */
85
+ export async function sendVoice(chatId, threadId, filePath, caption = '') {
86
+ const buf = readFileSync(filePath);
87
+ const form = new FormData();
88
+ form.set('chat_id', String(chatId));
89
+ if (threadId > 0) form.set('message_thread_id', String(threadId));
90
+ if (caption) form.set('caption', caption.slice(0, 1000));
91
+ form.set('voice', new Blob([buf], { type: 'audio/ogg' }), basename(filePath));
92
+ const res = await fetch(`https://api.telegram.org/bot${token}/sendVoice`, { method: 'POST', body: form });
93
+ const json = await res.json().catch(() => ({}));
94
+ if (!json.ok) throw new Error(`sendVoice: ${json.description || res.status}`);
95
+ log(`sent voice ${basename(filePath)} (${buf.length} B) chat=${chatId}`);
96
+ return json.result;
97
+ }
98
+
78
99
  /**
79
100
  * Download a Telegram file into the bridge dir under a stable name.
80
101
  * Voice notes arrive as OGG/Opus, which the local ASR CLI does not decode,
@@ -0,0 +1,36 @@
1
+ // The one button `/voice` draws.
2
+ //
3
+ // Its own module because `callbacks.mjs` is at the ceiling and this press has a
4
+ // subject of its own: a tap changes one setting and redraws the card that shows
5
+ // it. A tap that toggled silently would leave the old words on screen, and the
6
+ // person would learn the truth only from the next answer's sound.
7
+ import { t } from '../core/i18n.mjs';
8
+ import { tgFast } from './telegram.mjs';
9
+ import { setSpeech, speechConfig } from './speech.mjs';
10
+ import { renderVoice, voiceKeyboard } from '../control/cmd-voice.mjs';
11
+
12
+ export function isVoicePress(data) {
13
+ return data === 'v:on' || data === 'v:off';
14
+ }
15
+
16
+ /**
17
+ * Flip the setting, answer the tap, redraw the card.
18
+ *
19
+ * `answer` is the caller's `answerCallbackQuery` wrapper: the press must stop
20
+ * spinning, and only the caller owns the query id.
21
+ */
22
+ export async function handleVoicePress({ data, query, state, key, config, lang, saveState, answer }) {
23
+ const chatId = query.message?.chat?.id;
24
+ const messageId = query.message?.message_id;
25
+ const on = data === 'v:on';
26
+ const next = setSpeech(state, key, { on }, config, lang);
27
+ saveState();
28
+ await answer(t(lang, on ? 'ctrl.voice.tapOn' : 'ctrl.voice.tapOff'));
29
+ await tgFast('editMessageText', {
30
+ chat_id: chatId,
31
+ message_id: messageId,
32
+ text: renderVoice({ lang, ...next, voices: speechConfig(config).voices }),
33
+ reply_markup: { inline_keyboard: voiceKeyboard(lang, next.on) },
34
+ }).catch(() => {});
35
+ return next;
36
+ }
@@ -31,5 +31,18 @@
31
31
  "vision": {
32
32
  "patch": "",
33
33
  "model": ""
34
+ },
35
+ "speech": {
36
+ "_comment": "Answers as voice notes after the text, when a topic turns it on with /voice on. Needs edge-tts in the python below, and ffmpeg for the OGG conversion.",
37
+ "provider": "edge-tts",
38
+ "python": "python",
39
+ "ffmpeg": "ffmpeg",
40
+ "maxChars": 1200,
41
+ "timeoutMs": 120000,
42
+ "voices": {
43
+ "ru": "ru-RU-DmitryNeural",
44
+ "en": "en-US-GuyNeural",
45
+ "zh": "zh-CN-YunjianNeural"
46
+ }
34
47
  }
35
48
  }
@@ -29,7 +29,11 @@ export async function handleModelCommand(ctx) {
29
29
  routes,
30
30
  current: routes.length ? { provider: topic.provider, model: topic.model } : null,
31
31
  topic: topic.source === 'topic',
32
- fallback: topic.source === 'topic' ? modelOf(activeProfile) : null,
32
+ // Read from the profile the commands EDIT, not from `activeProfile`: for a
33
+ // topic that chose a model, `activeProfile` is the generated copy whose one
34
+ // rewritten row IS that choice, so the card would name the topic's own route
35
+ // as "the default it falls back to".
36
+ fallback: topic.source === 'topic' ? modelOf(topic.base) : null,
33
37
  answered: state.answered?.[key] || null,
34
38
  t: (k, v) => t(lang, k, v),
35
39
  });
@@ -43,7 +47,11 @@ export async function handleModelCommand(ctx) {
43
47
  if (/^(auto|off|default|profile)$/i.test(wanted)) {
44
48
  const cleared = clearTopicRoute(state, key);
45
49
  save();
46
- const head = modelOf(activeProfile);
50
+ // The answer names where the topic lands, so it must read the profile the
51
+ // commands edit. `activeProfile` here is the route copy the topic boots, and
52
+ // its default is the very route that was just cleared — that is why `auto`
53
+ // used to answer "back to unorouter" after un-pinning the route to it.
54
+ const head = modelOf(topic.base);
47
55
  say(t(lang, cleared ? 'ctrl.model.topicCleared' : 'ctrl.model.topicNone', {
48
56
  route: `${head.provider}/${head.model}`,
49
57
  }));
@@ -92,7 +100,9 @@ export async function handleModelCommand(ctx) {
92
100
  setTopicRoute(state, key, route);
93
101
  save();
94
102
  const now = topicRoute({ state, config, key });
95
- const head = modelOf(activeProfile);
103
+ // Same reason as above: `activeProfile` is this topic's copy, and once the route
104
+ // is written into it, its default and the route are the same string.
105
+ const head = modelOf(topic.base);
96
106
  const said = t(lang, 'ctrl.model.topicSet', {
97
107
  route: `${now.provider}/${now.model}`,
98
108
  default: `${head.provider}/${head.model}`,
@@ -0,0 +1,78 @@
1
+ // `/voice` — читать ответы вслух или молчать.
2
+ //
3
+ // Просьба человека: «иногда я не могу читать, буду слушать» — то есть это
4
+ // переключатель на тему, а не настройка установки. Живёт рядом с `state.lang`:
5
+ // у каждой темы свой ответ, потому что в одной человек слушает, а в другой
6
+ // смотрит код.
7
+ //
8
+ // Ответ на команду сразу говорит две вещи: включено ли и каким голосом. Голос
9
+ // можно назвать словом (`/voice on ru-RU-DmitryNeural`) — движок берётся из
10
+ // конфига, поэтому список голосов задаёт провайдер, а не мы.
11
+ import { t } from '../core/i18n.mjs';
12
+ import { inlineKeyboard } from '../chat/telegram.mjs';
13
+ import { DEFAULT_VOICES, setSpeech, speechConfig, speechOf } from '../chat/speech.mjs';
14
+
15
+ /**
16
+ * Кнопки карточки. `v:on` / `v:off` ловит `callbacks.mjs`, чтобы нажатие не
17
+ * стоило хода модели.
18
+ */
19
+ export function voiceKeyboard(lang, on) {
20
+ return inlineKeyboard([
21
+ [{ text: t(lang, on ? 'ctrl.voice.off' : 'ctrl.voice.on'), data: on ? 'v:off' : 'v:on' }],
22
+ ]);
23
+ }
24
+
25
+ /** Текст карточки: состояние, голос, как позвать. */
26
+ export function renderVoice({ lang, on, voice, voices }) {
27
+ const lines = [
28
+ t(lang, 'ctrl.voice.head'),
29
+ t(lang, on ? 'ctrl.voice.stateOn' : 'ctrl.voice.stateOff'),
30
+ t(lang, 'ctrl.voice.voice', { voice }),
31
+ ];
32
+ // Полный список — только когда его просят: три строки в карточке лучше, чем
33
+ // стена имён, которую никто не читает.
34
+ const known = Object.values(voices).filter(Boolean);
35
+ if (known.length > 1) lines.push(t(lang, 'ctrl.voice.byLang', { list: known.join(', ') }));
36
+ lines.push(t(lang, 'ctrl.voice.hint'));
37
+ return lines.join(String.fromCharCode(10));
38
+ }
39
+
40
+ /**
41
+ * Переключить голос и вернуть новое состояние. Одна функция на команду и на
42
+ * кнопку: два пути к одной настройке разошлись бы в первый же месяц.
43
+ */
44
+ export function toggleSpeech(state, key, config, lang, on) {
45
+ return setSpeech(state, key, { on }, config, lang);
46
+ }
47
+
48
+ export async function handleVoiceCommands(ctx) {
49
+ const { effective, arg, lang, reply, state, key, config } = ctx;
50
+ if (effective !== '/voice') return false;
51
+ const cfg = speechConfig(config);
52
+ const current = speechOf(state, key, config, lang);
53
+ const word = String(arg || '').trim();
54
+ const lower = word.toLowerCase();
55
+
56
+ if (!word || lower === 'status') {
57
+ await reply(renderVoice({ lang, ...current, voices: cfg.voices }), {
58
+ keyboard: voiceKeyboard(lang, current.on),
59
+ });
60
+ return true;
61
+ }
62
+ if (lower === 'on' || lower === 'off') {
63
+ const next = toggleSpeech(state, key, config, lang, lower === 'on');
64
+ await reply(renderVoice({ lang, ...next, voices: cfg.voices }), {
65
+ keyboard: voiceKeyboard(lang, next.on),
66
+ });
67
+ return true;
68
+ }
69
+ // Любое другое слово — имя голоса: так человек меняет голос, не открывая
70
+ // конфиг, и опечатка не выключает звук молча.
71
+ const next = setSpeech(state, key, { voice: word, on: true }, config, lang);
72
+ await reply(renderVoice({ lang, ...next, voices: cfg.voices }), {
73
+ keyboard: voiceKeyboard(lang, next.on),
74
+ });
75
+ return true;
76
+ }
77
+
78
+ export { DEFAULT_VOICES };
@@ -121,7 +121,10 @@ function splitRoute(text) {
121
121
  if (cut <= 0 || cut === text.length - 1) return null;
122
122
  const provider = text.slice(0, cut);
123
123
  const model = text.slice(cut + 1);
124
- if (!/^[\w.-]+$/.test(provider) || !/^[\w.:-]+$/.test(model)) return null;
124
+ // A model id may itself carry a provider prefix — subscription gateways name
125
+ // their models `gateway/model`, and the card of such a route drew a button
126
+ // whose tap this `/` silently rejected. The provider half stays prefix-free.
127
+ if (!/^[\w.-]+$/.test(provider) || !/^[\w./:-]+$/.test(model)) return null;
125
128
  return { provider, model };
126
129
  }
127
130
 
package/docs/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # CHANGELOG — DSH Telegram bridge
2
2
 
3
+ ## 1.52.0
4
+
5
+ - **`/voice` — the answer can be listened to.** `/voice on` makes the topic send
6
+ each finished answer as a voice note after the text, `/voice off` returns to
7
+ text, `/voice <name>` sets the voice for that topic, and the card's button does
8
+ the same as the command. The switch is per topic: one chat can be listened to
9
+ while another stays quiet, and a fresh install is silent until asked — audio
10
+ nobody asked for is the one failure a person cannot undo by reading.
11
+ The engine is config, not code: `speech.provider` runs with `{text}` and `{out}`
12
+ placeholders, `edge-tts` (male voice per topic language) is the default shape and
13
+ a local Piper install is a config block, not a new module. The text is always
14
+ sent first and is never delayed by the engine: a missing interpreter, a hang or
15
+ an outage costs the sound, is logged, and never costs the answer. Markup, code
16
+ blocks, tables, links and emoji are stripped before speaking, and a long answer
17
+ is cut at a sentence — a voice that stops mid-word sounds like a fault.
18
+ `docs/VOICE.md` has the block and both shapes; `docs/COMMANDS.md` the command.
19
+ 13 tests, and one pre-existing flaky test fixed: `active-sweep` compared a
20
+ sorted directory listing against an unsorted expectation, so it passed only
21
+ while the runner's pid sorted before `333`.
22
+
3
23
  ## 1.51.2
4
24
 
5
25
  - **`say.mjs` sweeps stale markers too.** 1.51.1 taught the bridge to sweep, but
package/docs/COMMANDS.md CHANGED
@@ -87,6 +87,7 @@ Built from the same code as `/help`: the list, the sections and the sentences ar
87
87
  - `/lang` — The language of the bot in this topic: /lang en|ru|zh.
88
88
  - `/reasoning` — Working notes: off, in the progress card, or as messages in the chat — /reasoning off|card|chat.
89
89
  - `/pin` — Holds the progress card pinned while its turn runs, so the clock and the steps are one tap away — /pin on|off.
90
+ - `/voice` — Read answers out loud: /voice on turns sound on for this topic, /voice off turns it off, /voice <name> changes the voice.
90
91
 
91
92
  ### Panels and help
92
93
 
@@ -191,6 +192,7 @@ Inline: type @bot rew in any chat to see the commands that start with rew. Switc
191
192
  - `/lang` — Язык бота в теме: /lang en|ru|zh.
192
193
  - `/reasoning` — Заметки о ходе работы: выкл, в карточке прогресса или отдельными сообщениями в чат — /reasoning off|card|chat.
193
194
  - `/pin` — Держит карточку прогресса закреплённой на время хода, чтобы часы и шаги были в одно касание — /pin on|off.
195
+ - `/voice` — Читать ответы вслух: /voice on включает голос в этой теме, /voice off выключает, /voice <имя> меняет голос.
194
196
 
195
197
  ### Панели и справка
196
198
 
@@ -295,6 +297,7 @@ Inline: type @bot rew in any chat to see the commands that start with rew. Switc
295
297
  - `/lang` — 本话题中机器人的语言:/lang en|ru|zh。
296
298
  - `/reasoning` — 工作记录:关闭、放在进度卡片里,或作为消息发到聊天——/reasoning off|card|chat。
297
299
  - `/pin` — 让进度卡片在本次运行期间保持置顶,时间和步骤一按就到——/pin on|off。
300
+ - `/voice` — 朗读回答:/voice on 为本话题打开声音,/voice off 关闭,/voice <名称> 换声音。
298
301
 
299
302
  ### 面板与帮助
300
303
 
package/docs/VOICE.md CHANGED
@@ -95,6 +95,52 @@ saved under `inbox/` and handed over as a path, with text-like files pasted in s
95
95
  a mid-turn steer can read them too. That part works on a fresh install with an
96
96
  empty `voice` block.
97
97
 
98
+ ## Speaking the answer back: `/voice`
99
+
100
+ The opposite direction, for the days a person cannot read: `/voice on` makes the
101
+ bridge send each finished answer as a voice note after the text. `/voice off`
102
+ returns to text only. The switch is **per topic** — one topic can be listened to
103
+ while another stays quiet — and the button on the card does the same thing as the
104
+ command, so the chat and the command line never disagree.
105
+
106
+ The text always goes first and is never delayed by the engine. A missing
107
+ interpreter, an engine that hangs or a provider outage costs the sound and is
108
+ logged; it never costs the answer.
109
+
110
+ Everything lives in the `speech` block of `config.json`:
111
+
112
+ ```json
113
+ { "speech": { "provider": "edge-tts", "python": "python", "ffmpeg": "ffmpeg",
114
+ "maxChars": 1200, "timeoutMs": 120000,
115
+ "voices": { "ru": "ru-RU-DmitryNeural", "en": "en-US-GuyNeural", "zh": "zh-CN-YunjianNeural" } } }
116
+ ```
117
+
118
+ | `speech.provider` | What it runs | Needs |
119
+ | --- | --- | --- |
120
+ | `edge-tts` (default) | `python -m edge_tts --voice … --text … --write-media …` | `speech.python` with `edge-tts` installed, `speech.ffmpeg` |
121
+ | anything else | `speech.command` + `speech.args`, with `{text}` and `{out}` placeholders | an engine that writes audio to `{out}` |
122
+
123
+ `voices` is one male voice per topic language; a language without an entry uses
124
+ the `ru` one rather than going silent. `/voice <name>` sets a voice for that topic
125
+ without touching the config, which is how a person tries one out.
126
+
127
+ The answer is spoken, not the thinking and not the progress lines: code blocks,
128
+ tables, links and emoji are stripped first, and anything longer than `maxChars` is
129
+ cut at a sentence. The engine writes MP3 and `ffmpeg` converts it to OGG/Opus,
130
+ because Telegram draws a voice bubble only for that container. A provider that
131
+ already speaks OGG sets `speech.ogg: true` and needs no ffmpeg.
132
+
133
+ A local Piper install is the same shape:
134
+
135
+ ```json
136
+ { "speech": { "provider": "piper", "command": "C:/piper/piper.exe",
137
+ "args": ["--model", "C:/piper/ru_RU-ruslan-medium.onnx", "--output_file", "{out}"],
138
+ "ogg": false, "voices": { "ru": "ruslan" } } }
139
+ ```
140
+
141
+ `/voice` on a topic with no engine answers with the state it is in and the reason
142
+ in `bridge.log` — a switch that turns nothing on would be a promise, not a feature.
143
+
98
144
  ## Checking your setup
99
145
 
100
146
  Send the bridge a voice note. A misconfiguration answers in the chat with the
package/i18n/en/ctrl.mjs CHANGED
@@ -122,6 +122,7 @@ export default {
122
122
  'menu.cmd.stop': "Stop the current turn",
123
123
  'menu.cmd.help': "Every command with an explanation: /help <command>",
124
124
  'menu.cmd.update': "Version and update: /update confirm",
125
+ 'menu.cmd.voice': "Read answers out loud: /voice on, /voice off",
125
126
  'ctrl.settings.usage': 'Settings as buttons: /settings, /settings agent, /settings updates',
126
127
  'ctrl.profile.title': '🧩 Profile {name}',
127
128
  'ctrl.profile.model': 'Model: {route}',
@@ -0,0 +1,14 @@
1
+ // `/voice` — spoken answers. A per-topic switch, so the words describe "now".
2
+ export default {
3
+ 'ctrl.voice.head': '🔊 Voice',
4
+ 'ctrl.voice.stateOn': 'Now: sound on — each answer arrives as text and as a voice note.',
5
+ 'ctrl.voice.stateOff': 'Now: sound off — text only.',
6
+ 'ctrl.voice.voice': 'Voice: {voice}',
7
+ 'ctrl.voice.byLang': 'Per topic language: {list}',
8
+ 'ctrl.voice.hint': 'Turn on: /voice on. Turn off: /voice off. Another voice: /voice <name>.',
9
+ 'ctrl.voice.on': '🔊 Turn on',
10
+ 'ctrl.voice.off': '🔇 Turn off',
11
+ 'ctrl.voice.tapOn': 'Sound on',
12
+ 'ctrl.voice.tapOff': 'Sound off',
13
+ 'ctrl.help.about.voice': 'Read answers out loud: /voice on turns sound on for this topic, /voice off turns it off, /voice <name> changes the voice.',
14
+ };
package/i18n/en.mjs CHANGED
@@ -22,4 +22,5 @@ import branch from './en/branch.mjs';
22
22
  import history from './en/history.mjs';
23
23
  import remember from './en/remember.mjs';
24
24
  import regen from './en/regen.mjs';
25
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen };
25
+ import voice from './en/voice.mjs';
26
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen, ...voice };
package/i18n/ru/ctrl.mjs CHANGED
@@ -122,6 +122,7 @@ export default {
122
122
  'menu.cmd.stop': "Остановить текущий ход",
123
123
  'menu.cmd.help': "Все команды с пояснением: /help <команда>",
124
124
  'menu.cmd.update': "Версия и обновление: /update confirm",
125
+ 'menu.cmd.voice': "Читать ответы вслух: /voice on, /voice off",
125
126
  'ctrl.settings.usage': 'Настройки кнопками: /settings, /settings agent, /settings updates',
126
127
  'ctrl.profile.title': '🧩 Профиль {name}',
127
128
  'ctrl.profile.model': 'Модель: {route}',
@@ -0,0 +1,15 @@
1
+ // `/voice` — ответы вслух. Переключатель на тему, поэтому и слова здесь про
2
+ // «сейчас», а не про установку.
3
+ export default {
4
+ 'ctrl.voice.head': '🔊 Голос',
5
+ 'ctrl.voice.stateOn': 'Сейчас: звук включён — ответ приходит текстом и голосом.',
6
+ 'ctrl.voice.stateOff': 'Сейчас: звук выключен — только текст.',
7
+ 'ctrl.voice.voice': 'Голос: {voice}',
8
+ 'ctrl.voice.byLang': 'По языку темы: {list}',
9
+ 'ctrl.voice.hint': 'Включить: /voice on. Выключить: /voice off. Другой голос: /voice <имя>.',
10
+ 'ctrl.voice.on': '🔊 Включить',
11
+ 'ctrl.voice.off': '🔇 Выключить',
12
+ 'ctrl.voice.tapOn': 'Звук включён',
13
+ 'ctrl.voice.tapOff': 'Звук выключен',
14
+ 'ctrl.help.about.voice': 'Читать ответы вслух: /voice on включает голос в этой теме, /voice off выключает, /voice <имя> меняет голос.',
15
+ };
package/i18n/ru.mjs CHANGED
@@ -22,4 +22,5 @@ import branch from './ru/branch.mjs';
22
22
  import history from './ru/history.mjs';
23
23
  import remember from './ru/remember.mjs';
24
24
  import regen from './ru/regen.mjs';
25
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen };
25
+ import voice from './ru/voice.mjs';
26
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen, ...voice };
package/i18n/zh/ctrl.mjs CHANGED
@@ -122,6 +122,7 @@ export default {
122
122
  'menu.cmd.stop': "停止当前轮次",
123
123
  'menu.cmd.help': "所有命令及说明:/help <命令>",
124
124
  'menu.cmd.update': "版本与更新:/update confirm",
125
+ 'menu.cmd.voice': "朗读回答:/voice on、/voice off",
125
126
  'ctrl.settings.usage': '用按钮调设置:/settings、/settings agent、/settings updates',
126
127
  'ctrl.profile.title': '🧩 配置档 {name}',
127
128
  'ctrl.profile.model': '模型:{route}',
@@ -0,0 +1,14 @@
1
+ // `/voice` —— 朗读回答。按话题开关,所以措辞说的是「现在」。
2
+ export default {
3
+ 'ctrl.voice.head': '🔊 语音',
4
+ 'ctrl.voice.stateOn': '现在:声音已开 —— 回答以文字和语音一起送达。',
5
+ 'ctrl.voice.stateOff': '现在:声音已关 —— 只有文字。',
6
+ 'ctrl.voice.voice': '声音:{voice}',
7
+ 'ctrl.voice.byLang': '按话题语言:{list}',
8
+ 'ctrl.voice.hint': '打开:/voice on。关闭:/voice off。换声音:/voice <名称>。',
9
+ 'ctrl.voice.on': '🔊 打开',
10
+ 'ctrl.voice.off': '🔇 关闭',
11
+ 'ctrl.voice.tapOn': '声音已开',
12
+ 'ctrl.voice.tapOff': '声音已关',
13
+ 'ctrl.help.about.voice': '朗读回答:/voice on 为本话题打开声音,/voice off 关闭,/voice <名称> 换声音。',
14
+ };
package/i18n/zh.mjs CHANGED
@@ -22,4 +22,5 @@ import branch from './zh/branch.mjs';
22
22
  import history from './zh/history.mjs';
23
23
  import remember from './zh/remember.mjs';
24
24
  import regen from './zh/regen.mjs';
25
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen };
25
+ import voice from './zh/voice.mjs';
26
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen, ...voice };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.51.2",
3
+ "version": "1.52.0",
4
4
  "description": "Drive DeepSeek Harness from Telegram: one project, model and session per forum topic",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",