telecoder 0.0.0-stage → 1.2.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.
- package/.env.example +363 -0
- package/CHANGELOG.md +1186 -0
- package/LICENSE +22 -0
- package/README.md +126 -2
- package/dist/audio/transcribe.js +50 -0
- package/dist/bin/mcp-server.js +378 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +592 -0
- package/dist/bot/file-access.js +141 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +827 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/btw.js +224 -0
- package/dist/bot/handlers/command/cost.js +409 -0
- package/dist/bot/handlers/command/media.js +197 -0
- package/dist/bot/handlers/command/model.js +305 -0
- package/dist/bot/handlers/command/prefs-scope.js +197 -0
- package/dist/bot/handlers/command/project.js +536 -0
- package/dist/bot/handlers/command/resume.js +321 -0
- package/dist/bot/handlers/command/session.js +438 -0
- package/dist/bot/handlers/command/settings.js +1012 -0
- package/dist/bot/handlers/command/shared.js +210 -0
- package/dist/bot/handlers/command/streaming-mode.js +16 -0
- package/dist/bot/handlers/command/tasks.js +513 -0
- package/dist/bot/handlers/command/topic-store.js +113 -0
- package/dist/bot/handlers/command/topic.js +80 -0
- package/dist/bot/handlers/command.handler.js +772 -0
- package/dist/bot/handlers/fork.handler.js +1109 -0
- package/dist/bot/handlers/media-fallback.js +121 -0
- package/dist/bot/handlers/message/replies.js +133 -0
- package/dist/bot/handlers/message/shared.js +117 -0
- package/dist/bot/handlers/message/throttle.js +49 -0
- package/dist/bot/handlers/message/turn-notify.js +169 -0
- package/dist/bot/handlers/message/turn-runner.js +141 -0
- package/dist/bot/handlers/message.handler.js +107 -0
- package/dist/bot/handlers/newbot.handler.js +221 -0
- package/dist/bot/handlers/photo.handler.js +327 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/schedule.handler.js +303 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +209 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +139 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +971 -0
- package/dist/bot/middleware/stale-filter.js +31 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/agent-watchdog.js +162 -0
- package/dist/claude/agent.js +1458 -0
- package/dist/claude/ask-user.js +295 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +126 -0
- package/dist/claude/available-commands.js +153 -0
- package/dist/claude/carry-over.js +27 -0
- package/dist/claude/ccr-shim.js +46 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +121 -0
- package/dist/claude/command-parser.js +200 -0
- package/dist/claude/cost-overlay-scraper.js +129 -0
- package/dist/claude/enabled-plugins.js +56 -0
- package/dist/claude/fork-tree.js +393 -0
- package/dist/claude/held-query.js +190 -0
- package/dist/claude/in-flight-tracker.js +61 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +453 -0
- package/dist/claude/mcp-tools.js +354 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +450 -0
- package/dist/claude/model-catalog.js +85 -0
- package/dist/claude/monitor-relay.js +597 -0
- package/dist/claude/pending-forks.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +337 -0
- package/dist/claude/permission-mode.js +178 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-provider.js +2214 -0
- package/dist/claude/pty-spawn-config.js +296 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/request-queue.js +135 -0
- package/dist/claude/scheduled-runner.js +91 -0
- package/dist/claude/scheduler.js +237 -0
- package/dist/claude/scope-guard.js +274 -0
- package/dist/claude/sdk-permission-gate.js +77 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-cost.js +41 -0
- package/dist/claude/session-history.js +286 -0
- package/dist/claude/session-jsonl.js +920 -0
- package/dist/claude/session-manager.js +195 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +249 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/system-prompt.js +162 -0
- package/dist/claude/tasks-overlay-scraper.js +94 -0
- package/dist/claude/tip-scraper.js +78 -0
- package/dist/claude/tui-modal.js +501 -0
- package/dist/claude/tui-state.js +384 -0
- package/dist/claude/turn-end.js +91 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +305 -0
- package/dist/cli/commands/help.js +25 -0
- package/dist/cli/commands/init.js +123 -0
- package/dist/cli/commands/service.js +678 -0
- package/dist/cli/commands/start.js +53 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/dispatch.js +79 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +638 -0
- package/dist/cli/init/prompter.js +116 -0
- package/dist/cli/init/telegram.js +94 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +500 -0
- package/dist/index.js +367 -0
- package/dist/launcher.js +933 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +149 -0
- package/dist/providers/ccr-provider.js +60 -0
- package/dist/providers/claude-provider.js +63 -0
- package/dist/providers/prefs-sync.js +164 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +127 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/sdk-provider.js +37 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +214 -0
- package/dist/restart-when-idle.js +153 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +173 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +684 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +336 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +27 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +57 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1287 -0
- package/dist/telegram/prompt-label.js +142 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +105 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +209 -0
- package/dist/telegram/telegraph-settings.js +31 -0
- package/dist/telegram/telegraph.js +453 -0
- package/dist/telegram/terminal-renderer.js +671 -0
- package/dist/telegram/terminal-settings.js +25 -0
- package/dist/telegram/thread-titles.js +190 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/tts/tts-settings.js +62 -0
- package/dist/tts/tts.js +245 -0
- package/dist/tts/voice-reply.js +78 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-token.js +74 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +50 -0
- package/dist/utils/claude-env.js +54 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/debug-agent.js +117 -0
- package/dist/utils/debug-watchdog.js +121 -0
- package/dist/utils/download.js +111 -0
- package/dist/utils/exit-codes.js +48 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +81 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/project-data-dir.js +33 -0
- package/dist/utils/reasoning-summary.js +12 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +63 -0
- package/dist/utils/respawn-backoff.js +19 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- package/package.json +76 -4
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Naming the threads of a private chat after what they're about.
|
|
3
|
+
*
|
|
4
|
+
* A message sent from a bot's "All" view starts a new thread, and Telegram
|
|
5
|
+
* names it "New chat" and flags the name as implicit: one the bot is expected
|
|
6
|
+
* to replace. The session topic (Haiku's summary, or what the agent set with
|
|
7
|
+
* telecoder_set_topic) already says what the thread is about, so every topic
|
|
8
|
+
* change is passed on to the thread with editForumTopic. Only the topic's
|
|
9
|
+
* first half goes in: the broad area, which stays put while the second half,
|
|
10
|
+
* the task of the moment, changes with every message. The project's folder
|
|
11
|
+
* name goes in front, since one bot's threads can each be in another project.
|
|
12
|
+
*
|
|
13
|
+
* A name the user gave the thread is theirs, and is never overwritten: one
|
|
14
|
+
* typed when creating the thread, or a rename seen afterwards. Group forum
|
|
15
|
+
* topics are left alone entirely; people name those for each other.
|
|
16
|
+
*
|
|
17
|
+
* Who owns each thread's name, and what we last set it to, is kept per bot
|
|
18
|
+
* so a restart neither forgets a user's rename nor re-sends the same name.
|
|
19
|
+
*/
|
|
20
|
+
import * as path from 'path';
|
|
21
|
+
import { z } from 'zod';
|
|
22
|
+
import { BOT_ID } from '../config.js';
|
|
23
|
+
import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
|
|
24
|
+
import { buildSessionKey, parseSessionKey } from '../utils/session-key.js';
|
|
25
|
+
import { TOPIC_PART_SEPARATOR } from '../claude/auto-topic-haiku.js';
|
|
26
|
+
/** Telegram's limit on a topic name. */
|
|
27
|
+
const MAX_NAME_LENGTH = 128;
|
|
28
|
+
/**
|
|
29
|
+
* At most one rename per thread per this long. The topic can change several
|
|
30
|
+
* times in a few seconds (Haiku's guess, then the agent's own), and each
|
|
31
|
+
* rename leaves a service message in the thread; only the last one matters.
|
|
32
|
+
*/
|
|
33
|
+
const RENAME_COOLDOWN_MS = 60_000;
|
|
34
|
+
const titleSchema = z.object({
|
|
35
|
+
/** 'user' names are never touched; 'implicit' and 'bot' ones are ours to replace. */
|
|
36
|
+
owner: z.enum(['implicit', 'bot', 'user']),
|
|
37
|
+
name: z.string().optional(),
|
|
38
|
+
/** Goes in front of every name we give the thread, e.g. 🍴 for a fork's. */
|
|
39
|
+
prefix: z.string().optional(),
|
|
40
|
+
});
|
|
41
|
+
const fileSchema = z.object({ threads: z.record(z.string(), titleSchema) });
|
|
42
|
+
const STATE_DIR = getStateDir();
|
|
43
|
+
const STATE_FILE = path.join(STATE_DIR, `thread-titles-${BOT_ID}.json`);
|
|
44
|
+
let threads;
|
|
45
|
+
let api;
|
|
46
|
+
const lastRenameAt = new Map();
|
|
47
|
+
const pending = new Map();
|
|
48
|
+
function state() {
|
|
49
|
+
if (!threads) {
|
|
50
|
+
ensureStateDir(STATE_DIR, 'ThreadTitles');
|
|
51
|
+
threads = { ...(readJsonFile(STATE_FILE, fileSchema, 'ThreadTitles')?.threads ?? {}) };
|
|
52
|
+
}
|
|
53
|
+
return threads;
|
|
54
|
+
}
|
|
55
|
+
function record(sessionKey, title) {
|
|
56
|
+
state()[sessionKey] = title;
|
|
57
|
+
writeJsonFile(STATE_FILE, { threads: state() }, 'ThreadTitles');
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The name a topic gives a thread: its first half, the broad area, which
|
|
61
|
+
* holds still while the second half follows each message. A topic set by
|
|
62
|
+
* hand or by the agent has no halves and goes in whole.
|
|
63
|
+
*
|
|
64
|
+
* The project leads, so it survives the thread list cutting names short. It
|
|
65
|
+
* is left out when the topic already names it, as Haiku's often does, and is
|
|
66
|
+
* the whole name while there is no topic yet, as just after a project switch.
|
|
67
|
+
*/
|
|
68
|
+
export function threadName(topic, prefix = '', project = '') {
|
|
69
|
+
const general = topic.split(TOPIC_PART_SEPARATOR)[0].trim();
|
|
70
|
+
const showProject = project && !general.toLowerCase().includes(project.toLowerCase());
|
|
71
|
+
const name = [showProject ? project : '', general].filter(Boolean).join(TOPIC_PART_SEPARATOR);
|
|
72
|
+
if (!name)
|
|
73
|
+
return '';
|
|
74
|
+
return `${prefix}${name}`.slice(0, MAX_NAME_LENGTH);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Take on a thread the bot created itself, under the name it was created
|
|
78
|
+
* with, so the topic it inherits isn't sent straight back as a rename.
|
|
79
|
+
*/
|
|
80
|
+
export function adoptThread(sessionKey, name, prefix) {
|
|
81
|
+
record(sessionKey, { owner: 'bot', name, ...(prefix ? { prefix } : {}) });
|
|
82
|
+
}
|
|
83
|
+
/** A thread of a private chat, which is the only kind we name. */
|
|
84
|
+
function isPrivateThread(sessionKey) {
|
|
85
|
+
const { chatId, threadId } = parseSessionKey(sessionKey);
|
|
86
|
+
return threadId !== undefined && chatId > 0;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Whether a topic for this session would end up as a thread name — for the
|
|
90
|
+
* auto-topic side call, which otherwise only runs when something displays it.
|
|
91
|
+
*/
|
|
92
|
+
export function namesThread(sessionKey) {
|
|
93
|
+
return api !== undefined && isPrivateThread(sessionKey) && state()[sessionKey]?.owner !== 'user';
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Learn who named each thread from the messages that pass by: the creation
|
|
97
|
+
* notice every thread message replies to says whether its name was implicit,
|
|
98
|
+
* and a rename notice is the user's (the bot gets no updates for its own).
|
|
99
|
+
*/
|
|
100
|
+
function observe(ctx) {
|
|
101
|
+
const msg = ctx.message;
|
|
102
|
+
if (!msg?.is_topic_message || msg.message_thread_id === undefined)
|
|
103
|
+
return;
|
|
104
|
+
const sessionKey = buildSessionKey(msg.chat.id, msg.message_thread_id);
|
|
105
|
+
if (!isPrivateThread(sessionKey))
|
|
106
|
+
return;
|
|
107
|
+
const edited = msg.forum_topic_edited;
|
|
108
|
+
if (edited?.name !== undefined && msg.from?.id !== ctx.me.id) {
|
|
109
|
+
// Logged in full while it's new: whether Telegram's own names for threads
|
|
110
|
+
// arrive this way, as the user's, is not documented.
|
|
111
|
+
console.log(`[ThreadTitles] ${sessionKey} renamed to "${edited.name}" by ${msg.from?.is_bot ? 'bot' : 'user'} ${msg.from?.id}`);
|
|
112
|
+
if (edited.name === state()[sessionKey]?.name)
|
|
113
|
+
return;
|
|
114
|
+
record(sessionKey, { owner: 'user', name: edited.name });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (state()[sessionKey])
|
|
118
|
+
return;
|
|
119
|
+
const created = msg.forum_topic_created ?? msg.reply_to_message?.forum_topic_created;
|
|
120
|
+
if (!created)
|
|
121
|
+
return;
|
|
122
|
+
record(sessionKey, { owner: created.is_name_implicit ? 'implicit' : 'user', name: created.name });
|
|
123
|
+
}
|
|
124
|
+
async function rename(sessionKey, name) {
|
|
125
|
+
const current = state()[sessionKey];
|
|
126
|
+
if (!api || current?.owner === 'user')
|
|
127
|
+
return;
|
|
128
|
+
if (current?.name === name)
|
|
129
|
+
return;
|
|
130
|
+
const { chatId, threadId } = parseSessionKey(sessionKey);
|
|
131
|
+
lastRenameAt.set(sessionKey, Date.now());
|
|
132
|
+
try {
|
|
133
|
+
await api.editForumTopic(chatId, threadId, { name });
|
|
134
|
+
record(sessionKey, { owner: 'bot', name, ...(current?.prefix ? { prefix: current.prefix } : {}) });
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
console.debug(`[ThreadTitles] Failed to rename ${sessionKey}:`, err instanceof Error ? err.message : err);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Pass a new session topic on to the thread's name. A no-op outside private
|
|
142
|
+
* threads, for an empty topic in no known project, and for a name the user
|
|
143
|
+
* chose. Renames inside the cooldown are held and only the latest one is sent
|
|
144
|
+
* when it runs out.
|
|
145
|
+
*/
|
|
146
|
+
export function syncThreadTitle(sessionKey, topic, project) {
|
|
147
|
+
if (!namesThread(sessionKey))
|
|
148
|
+
return;
|
|
149
|
+
const name = threadName(topic, state()[sessionKey]?.prefix, project);
|
|
150
|
+
if (!name)
|
|
151
|
+
return;
|
|
152
|
+
const held = pending.get(sessionKey);
|
|
153
|
+
if (held)
|
|
154
|
+
clearTimeout(held.timer);
|
|
155
|
+
pending.delete(sessionKey);
|
|
156
|
+
const wait = (lastRenameAt.get(sessionKey) ?? 0) + RENAME_COOLDOWN_MS - Date.now();
|
|
157
|
+
if (wait <= 0) {
|
|
158
|
+
void rename(sessionKey, name);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const timer = setTimeout(() => {
|
|
162
|
+
pending.delete(sessionKey);
|
|
163
|
+
void rename(sessionKey, name);
|
|
164
|
+
}, wait);
|
|
165
|
+
timer.unref?.();
|
|
166
|
+
pending.set(sessionKey, { name, timer });
|
|
167
|
+
}
|
|
168
|
+
/** Start naming threads on `bot`. Call once, after auth, before the handlers. */
|
|
169
|
+
export function initThreadTitles(bot) {
|
|
170
|
+
api = bot.api;
|
|
171
|
+
bot.use((ctx, next) => {
|
|
172
|
+
try {
|
|
173
|
+
observe(ctx);
|
|
174
|
+
}
|
|
175
|
+
catch (err) {
|
|
176
|
+
console.debug('[ThreadTitles] Failed to read a thread notice:', err instanceof Error ? err.message : err);
|
|
177
|
+
}
|
|
178
|
+
return next();
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/** Test hook: forget the module state between cases. */
|
|
182
|
+
export function resetThreadTitlesForTest(testApi) {
|
|
183
|
+
threads = undefined;
|
|
184
|
+
api = testApi;
|
|
185
|
+
lastRenameAt.clear();
|
|
186
|
+
for (const { timer } of pending.values())
|
|
187
|
+
clearTimeout(timer);
|
|
188
|
+
pending.clear();
|
|
189
|
+
}
|
|
190
|
+
//# sourceMappingURL=thread-titles.js.map
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Walking the owner of a project bot through turning its threads on.
|
|
3
|
+
*
|
|
4
|
+
* Telegram has no API for it: a bot can read has_topics_enabled but not set
|
|
5
|
+
* it, for itself or for a bot it manages, so every bot /newbot creates starts
|
|
6
|
+
* without threads until its owner flips Threaded Mode in BotFather's Mini App.
|
|
7
|
+
* A bot can't message someone who hasn't written to it, so the steps go out
|
|
8
|
+
* with the first message an admin sends it. From then on it checks getMe once
|
|
9
|
+
* a minute, says so when threads are on, and takes the new setting into
|
|
10
|
+
* bot.botInfo (what ctx.me reads), so nothing waits for a restart.
|
|
11
|
+
*
|
|
12
|
+
* Only bots with a HOME_PROJECT, the ones /newbot makes: the numbered bots
|
|
13
|
+
* are deliberately one conversation each, and shouldn't be told otherwise.
|
|
14
|
+
*/
|
|
15
|
+
import * as path from 'path';
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
import { BOT_ID, config } from '../config.js';
|
|
18
|
+
import { isAdmin } from '../utils/admins.js';
|
|
19
|
+
import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
|
|
20
|
+
const CHECK_EVERY_MS = 60_000;
|
|
21
|
+
/** How long after the steps went out it keeps checking; a restart checks once more anyway. */
|
|
22
|
+
const CHECK_FOR_MS = 24 * 60 * 60_000;
|
|
23
|
+
const stateSchema = z.object({
|
|
24
|
+
/** When the steps were sent, and where to. */
|
|
25
|
+
notifiedAt: z.number().optional(),
|
|
26
|
+
chatId: z.number().optional(),
|
|
27
|
+
/** Threads are on; nothing more to say. */
|
|
28
|
+
done: z.boolean().optional(),
|
|
29
|
+
});
|
|
30
|
+
const STATE_DIR = getStateDir();
|
|
31
|
+
const stateFile = () => path.join(STATE_DIR, `threads-setup-${BOT_ID}.json`);
|
|
32
|
+
let state = {};
|
|
33
|
+
let timer;
|
|
34
|
+
function save(next) {
|
|
35
|
+
state = next;
|
|
36
|
+
ensureStateDir(STATE_DIR, 'ThreadsSetup');
|
|
37
|
+
writeJsonFile(stateFile(), state, 'ThreadsSetup');
|
|
38
|
+
}
|
|
39
|
+
/** The steps, for the bot's own chat. */
|
|
40
|
+
export function threadsSetupSteps(username) {
|
|
41
|
+
return '🧵 Threads are off for this bot, and Telegram only lets you turn them on yourself:\n\n' +
|
|
42
|
+
`1. Open @BotFather and tap Open to start its Mini App\n2. Pick @${username}\n3. Turn on Threaded Mode\n\n` +
|
|
43
|
+
'I\'ll say so here once they\'re on. Until then this chat is one conversation.';
|
|
44
|
+
}
|
|
45
|
+
async function check(bot) {
|
|
46
|
+
const me = await bot.api.getMe();
|
|
47
|
+
if (!me.has_topics_enabled) {
|
|
48
|
+
if (state.notifiedAt !== undefined && Date.now() - state.notifiedAt > CHECK_FOR_MS)
|
|
49
|
+
stop();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
bot.botInfo = me;
|
|
53
|
+
stop();
|
|
54
|
+
save({ ...state, done: true });
|
|
55
|
+
console.log('[ThreadsSetup] Threads are on');
|
|
56
|
+
if (state.chatId !== undefined) {
|
|
57
|
+
await bot.api.sendMessage(state.chatId, '✅ Threads are on. Start one from the bot\'s "All" view, or with 🍴 Fork; each is its own conversation, named after what it\'s about.');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function watch(bot) {
|
|
61
|
+
if (timer)
|
|
62
|
+
return;
|
|
63
|
+
timer = setInterval(() => {
|
|
64
|
+
check(bot).catch((err) => console.debug('[ThreadsSetup] Check failed:', err instanceof Error ? err.message : err));
|
|
65
|
+
}, CHECK_EVERY_MS);
|
|
66
|
+
timer.unref?.();
|
|
67
|
+
}
|
|
68
|
+
function stop() {
|
|
69
|
+
if (timer)
|
|
70
|
+
clearInterval(timer);
|
|
71
|
+
timer = undefined;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Send the steps with an admin's first private message. Call once in
|
|
75
|
+
* createBot, before the handlers; it reads the setting from ctx.me.
|
|
76
|
+
*/
|
|
77
|
+
export function initThreadsSetup(bot) {
|
|
78
|
+
if (!config.HOME_PROJECT)
|
|
79
|
+
return;
|
|
80
|
+
state = readJsonFile(stateFile(), stateSchema, 'ThreadsSetup') ?? {};
|
|
81
|
+
bot.use(async (ctx, next) => {
|
|
82
|
+
if (!state.done && state.notifiedAt === undefined && !ctx.me.has_topics_enabled
|
|
83
|
+
&& ctx.chat?.type === 'private' && isAdmin(ctx.from?.id)) {
|
|
84
|
+
save({ notifiedAt: Date.now(), chatId: ctx.chat.id });
|
|
85
|
+
try {
|
|
86
|
+
await ctx.reply(threadsSetupSteps(ctx.me.username), {
|
|
87
|
+
reply_markup: { inline_keyboard: [[{ text: 'Open @BotFather', url: 'https://t.me/BotFather' }]] },
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
console.debug('[ThreadsSetup] Failed to send the steps:', err instanceof Error ? err.message : err);
|
|
92
|
+
}
|
|
93
|
+
watch(bot);
|
|
94
|
+
}
|
|
95
|
+
return next();
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* After bot.init(): note threads that are on already, or pick the checking
|
|
100
|
+
* back up after a restart if the steps went out and they still aren't.
|
|
101
|
+
*/
|
|
102
|
+
export function resumeThreadsSetup(bot) {
|
|
103
|
+
if (!config.HOME_PROJECT || state.done)
|
|
104
|
+
return;
|
|
105
|
+
if (bot.botInfo.has_topics_enabled) {
|
|
106
|
+
save({ ...state, done: true });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (state.notifiedAt !== undefined && Date.now() - state.notifiedAt < CHECK_FOR_MS)
|
|
110
|
+
watch(bot);
|
|
111
|
+
}
|
|
112
|
+
/** Test hook. */
|
|
113
|
+
export function resetThreadsSetupForTest() {
|
|
114
|
+
stop();
|
|
115
|
+
state = {};
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=threads-setup.js.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-chat text-to-speech settings — whether voice replies are on, which voice
|
|
3
|
+
* to use, and whether they autoplay.
|
|
4
|
+
*/
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { config } from '../config.js';
|
|
7
|
+
import { createKeyedSettings } from '../utils/keyed-settings.js';
|
|
8
|
+
const GROQ_TTS_VOICES = ['autumn', 'diana', 'hannah', 'austin', 'daniel', 'troy'];
|
|
9
|
+
const OPENAI_TTS_VOICES = [
|
|
10
|
+
'alloy', 'ash', 'ballad', 'coral',
|
|
11
|
+
'echo', 'fable', 'nova', 'onyx',
|
|
12
|
+
'sage', 'shimmer', 'verse', 'marin', 'cedar',
|
|
13
|
+
];
|
|
14
|
+
function getDefaultVoice() {
|
|
15
|
+
if (config.TTS_PROVIDER === 'groq') {
|
|
16
|
+
// If the configured TTS_VOICE is valid for Groq, use it; otherwise default to 'troy'
|
|
17
|
+
const voices = GROQ_TTS_VOICES;
|
|
18
|
+
return voices.includes(config.TTS_VOICE) ? config.TTS_VOICE : 'troy';
|
|
19
|
+
}
|
|
20
|
+
return config.TTS_VOICE;
|
|
21
|
+
}
|
|
22
|
+
function isValidVoiceForProvider(voice) {
|
|
23
|
+
const voices = config.TTS_PROVIDER === 'groq' ? GROQ_TTS_VOICES : OPENAI_TTS_VOICES;
|
|
24
|
+
return voices.includes(voice);
|
|
25
|
+
}
|
|
26
|
+
const store = createKeyedSettings({
|
|
27
|
+
file: 'tts-settings.json',
|
|
28
|
+
label: 'TTS',
|
|
29
|
+
entrySchema: z.object({
|
|
30
|
+
enabled: z.boolean().optional(),
|
|
31
|
+
voice: z.string().optional(),
|
|
32
|
+
autoplay: z.boolean().optional(),
|
|
33
|
+
}),
|
|
34
|
+
normalize: (stored) => {
|
|
35
|
+
const voice = typeof stored?.voice === 'string' && stored.voice.length > 0
|
|
36
|
+
? stored.voice
|
|
37
|
+
: getDefaultVoice();
|
|
38
|
+
return {
|
|
39
|
+
enabled: typeof stored?.enabled === 'boolean' ? stored.enabled : false,
|
|
40
|
+
// A voice saved under a different TTS_PROVIDER won't exist for the
|
|
41
|
+
// current one — fall back rather than sending an unknown voice id.
|
|
42
|
+
voice: isValidVoiceForProvider(voice) ? voice : getDefaultVoice(),
|
|
43
|
+
autoplay: typeof stored?.autoplay === 'boolean' ? stored.autoplay : true,
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
export function getTTSSettings(sessionKey) {
|
|
48
|
+
return store.get(sessionKey);
|
|
49
|
+
}
|
|
50
|
+
export function setTTSEnabled(sessionKey, enabled) {
|
|
51
|
+
store.update(sessionKey, { enabled });
|
|
52
|
+
}
|
|
53
|
+
export function setTTSVoice(sessionKey, voice) {
|
|
54
|
+
store.update(sessionKey, { voice });
|
|
55
|
+
}
|
|
56
|
+
export function setTTSAutoplay(sessionKey, autoplay) {
|
|
57
|
+
store.update(sessionKey, { autoplay });
|
|
58
|
+
}
|
|
59
|
+
export function isTTSEnabled(sessionKey) {
|
|
60
|
+
return store.get(sessionKey).enabled;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=tts-settings.js.map
|
package/dist/tts/tts.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import OpenAI from 'openai';
|
|
2
|
+
import { config } from '../config.js';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
import * as path from 'path';
|
|
5
|
+
import * as os from 'os';
|
|
6
|
+
import { execFile } from 'child_process';
|
|
7
|
+
import { resolveBin } from '../utils/resolve-bin.js';
|
|
8
|
+
// ── OpenAI provider ────────────────────────────────────────────────
|
|
9
|
+
let openai = null;
|
|
10
|
+
function clampSpeed(speed) {
|
|
11
|
+
if (!Number.isFinite(speed))
|
|
12
|
+
return 1.0;
|
|
13
|
+
return Math.min(4.0, Math.max(0.25, speed));
|
|
14
|
+
}
|
|
15
|
+
async function generateSpeechOpenAI(text, voice) {
|
|
16
|
+
if (!config.OPENAI_API_KEY) {
|
|
17
|
+
throw new Error('OPENAI_API_KEY not configured.');
|
|
18
|
+
}
|
|
19
|
+
if (!openai) {
|
|
20
|
+
openai = new OpenAI({ apiKey: config.OPENAI_API_KEY });
|
|
21
|
+
}
|
|
22
|
+
const model = config.TTS_MODEL;
|
|
23
|
+
const client = openai;
|
|
24
|
+
const payload = {
|
|
25
|
+
model,
|
|
26
|
+
voice: (voice || config.TTS_VOICE),
|
|
27
|
+
input: text,
|
|
28
|
+
response_format: config.TTS_RESPONSE_FORMAT,
|
|
29
|
+
speed: clampSpeed(config.TTS_SPEED),
|
|
30
|
+
};
|
|
31
|
+
if (model.startsWith('gpt-4o-mini-tts')) {
|
|
32
|
+
payload.instructions = config.TTS_INSTRUCTIONS;
|
|
33
|
+
}
|
|
34
|
+
const response = await client.audio.speech.create(payload);
|
|
35
|
+
return Buffer.from(await response.arrayBuffer());
|
|
36
|
+
}
|
|
37
|
+
// ── Groq Orpheus provider ──────────────────────────────────────────
|
|
38
|
+
const GROQ_TTS_ENDPOINT = 'https://api.groq.com/openai/v1/audio/speech';
|
|
39
|
+
const GROQ_TTS_MODEL = 'canopylabs/orpheus-v1-english';
|
|
40
|
+
const GROQ_MAX_CHARS = 200;
|
|
41
|
+
/**
|
|
42
|
+
* Split text into chunks of at most maxLen characters, breaking at sentence
|
|
43
|
+
* boundaries (.!?) first, then word boundaries, then hard-cutting.
|
|
44
|
+
*/
|
|
45
|
+
export function chunkText(text, maxLen = GROQ_MAX_CHARS) {
|
|
46
|
+
if (text.length <= maxLen)
|
|
47
|
+
return [text];
|
|
48
|
+
// Split into sentences: split on .!? followed by whitespace or end-of-string
|
|
49
|
+
const sentences = [];
|
|
50
|
+
const sentenceRe = /[^.!?]*[.!?]+(?:\s+|$)|[^.!?]+$/g;
|
|
51
|
+
let match;
|
|
52
|
+
while ((match = sentenceRe.exec(text)) !== null) {
|
|
53
|
+
const s = match[0].trim();
|
|
54
|
+
if (s)
|
|
55
|
+
sentences.push(s);
|
|
56
|
+
}
|
|
57
|
+
const chunks = [];
|
|
58
|
+
let current = '';
|
|
59
|
+
for (const sentence of sentences) {
|
|
60
|
+
if (sentence.length > maxLen) {
|
|
61
|
+
// Flush current buffer
|
|
62
|
+
if (current) {
|
|
63
|
+
chunks.push(current.trim());
|
|
64
|
+
current = '';
|
|
65
|
+
}
|
|
66
|
+
// Split long sentence at word boundaries
|
|
67
|
+
const words = sentence.split(/\s+/);
|
|
68
|
+
let wordBuf = '';
|
|
69
|
+
for (const word of words) {
|
|
70
|
+
if (word.length > maxLen) {
|
|
71
|
+
// Hard-cut oversized word
|
|
72
|
+
if (wordBuf) {
|
|
73
|
+
chunks.push(wordBuf.trim());
|
|
74
|
+
wordBuf = '';
|
|
75
|
+
}
|
|
76
|
+
for (let i = 0; i < word.length; i += maxLen) {
|
|
77
|
+
chunks.push(word.slice(i, i + maxLen));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
else if (wordBuf.length + 1 + word.length > maxLen) {
|
|
81
|
+
chunks.push(wordBuf.trim());
|
|
82
|
+
wordBuf = word;
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
wordBuf = wordBuf ? `${wordBuf} ${word}` : word;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (wordBuf) {
|
|
89
|
+
current = wordBuf;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
else if (current.length + 1 + sentence.length > maxLen) {
|
|
93
|
+
chunks.push(current.trim());
|
|
94
|
+
current = sentence;
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
current = current ? `${current} ${sentence}` : sentence;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (current.trim()) {
|
|
101
|
+
chunks.push(current.trim());
|
|
102
|
+
}
|
|
103
|
+
return chunks.filter(Boolean);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Call the Groq Orpheus TTS API for a single chunk (≤200 chars).
|
|
107
|
+
* Returns a WAV Buffer.
|
|
108
|
+
*/
|
|
109
|
+
async function groqTTSSingle(text, voice) {
|
|
110
|
+
if (!config.GROQ_API_KEY) {
|
|
111
|
+
throw new Error('GROQ_API_KEY not configured.');
|
|
112
|
+
}
|
|
113
|
+
const response = await fetch(GROQ_TTS_ENDPOINT, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
headers: {
|
|
116
|
+
'Authorization': `Bearer ${config.GROQ_API_KEY}`,
|
|
117
|
+
'Content-Type': 'application/json',
|
|
118
|
+
},
|
|
119
|
+
body: JSON.stringify({
|
|
120
|
+
model: GROQ_TTS_MODEL,
|
|
121
|
+
input: text,
|
|
122
|
+
voice,
|
|
123
|
+
response_format: 'wav',
|
|
124
|
+
}),
|
|
125
|
+
});
|
|
126
|
+
if (!response.ok) {
|
|
127
|
+
const body = await response.text().catch(() => '');
|
|
128
|
+
throw new Error(`Groq TTS API error ${response.status}: ${body.slice(0, 300)}`);
|
|
129
|
+
}
|
|
130
|
+
return Buffer.from(await response.arrayBuffer());
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Concatenate multiple WAV buffers and convert to OGG/Opus using ffmpeg.
|
|
134
|
+
*/
|
|
135
|
+
async function concatAndConvertAudio(wavBuffers) {
|
|
136
|
+
if (wavBuffers.length === 0) {
|
|
137
|
+
throw new Error('No audio buffers to concatenate.');
|
|
138
|
+
}
|
|
139
|
+
// Single buffer — just convert to ogg
|
|
140
|
+
if (wavBuffers.length === 1) {
|
|
141
|
+
return convertWavToOgg(wavBuffers[0]);
|
|
142
|
+
}
|
|
143
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'telecoder-tts-'));
|
|
144
|
+
try {
|
|
145
|
+
// Write each WAV chunk
|
|
146
|
+
const chunkPaths = [];
|
|
147
|
+
for (let i = 0; i < wavBuffers.length; i++) {
|
|
148
|
+
const chunkPath = path.join(tmpDir, `chunk_${String(i).padStart(3, '0')}.wav`);
|
|
149
|
+
fs.writeFileSync(chunkPath, wavBuffers[i], { mode: 0o600 });
|
|
150
|
+
chunkPaths.push(chunkPath);
|
|
151
|
+
}
|
|
152
|
+
// Write concat list
|
|
153
|
+
const concatListPath = path.join(tmpDir, 'concat.txt');
|
|
154
|
+
const concatContent = chunkPaths.map((p) => `file '${p}'`).join('\n');
|
|
155
|
+
fs.writeFileSync(concatListPath, concatContent, { mode: 0o600 });
|
|
156
|
+
// Run ffmpeg
|
|
157
|
+
const outputPath = path.join(tmpDir, 'output.ogg');
|
|
158
|
+
await runFfmpeg([
|
|
159
|
+
'-y',
|
|
160
|
+
'-f', 'concat',
|
|
161
|
+
'-safe', '0',
|
|
162
|
+
'-i', concatListPath,
|
|
163
|
+
'-c:a', 'libopus',
|
|
164
|
+
'-b:a', '64k',
|
|
165
|
+
outputPath,
|
|
166
|
+
]);
|
|
167
|
+
return fs.readFileSync(outputPath);
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
// Cleanup temp dir
|
|
171
|
+
try {
|
|
172
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
// ignore cleanup errors
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Convert a single WAV buffer to OGG/Opus.
|
|
181
|
+
*/
|
|
182
|
+
async function convertWavToOgg(wavBuffer) {
|
|
183
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'telecoder-tts-'));
|
|
184
|
+
try {
|
|
185
|
+
const inputPath = path.join(tmpDir, 'input.wav');
|
|
186
|
+
const outputPath = path.join(tmpDir, 'output.ogg');
|
|
187
|
+
fs.writeFileSync(inputPath, wavBuffer, { mode: 0o600 });
|
|
188
|
+
await runFfmpeg([
|
|
189
|
+
'-y',
|
|
190
|
+
'-i', inputPath,
|
|
191
|
+
'-c:a', 'libopus',
|
|
192
|
+
'-b:a', '64k',
|
|
193
|
+
outputPath,
|
|
194
|
+
]);
|
|
195
|
+
return fs.readFileSync(outputPath);
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
try {
|
|
199
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
// ignore cleanup errors
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function runFfmpeg(args) {
|
|
207
|
+
return new Promise((resolve, reject) => {
|
|
208
|
+
execFile(resolveBin('ffmpeg'), args, { timeout: 60_000 }, (error, _stdout, stderr) => {
|
|
209
|
+
if (error) {
|
|
210
|
+
reject(new Error(`ffmpeg failed: ${(stderr || error.message).slice(0, 500)}`));
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
resolve();
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Generate speech using Groq Orpheus TTS.
|
|
219
|
+
* Handles chunking for long text and converts WAV→OGG/Opus.
|
|
220
|
+
*/
|
|
221
|
+
async function generateSpeechGroq(text, voice) {
|
|
222
|
+
const selectedVoice = voice || config.TTS_VOICE;
|
|
223
|
+
const chunks = chunkText(text, GROQ_MAX_CHARS);
|
|
224
|
+
console.log(`[TTS/Groq] Generating speech: ${chunks.length} chunk(s), voice=${selectedVoice}`);
|
|
225
|
+
const wavBuffers = [];
|
|
226
|
+
for (const chunk of chunks) {
|
|
227
|
+
const wav = await groqTTSSingle(chunk, selectedVoice);
|
|
228
|
+
wavBuffers.push(wav);
|
|
229
|
+
}
|
|
230
|
+
return concatAndConvertAudio(wavBuffers);
|
|
231
|
+
}
|
|
232
|
+
// ── Public API ─────────────────────────────────────────────────────
|
|
233
|
+
/**
|
|
234
|
+
* Generate speech using the configured TTS provider.
|
|
235
|
+
* Returns an audio Buffer (format depends on provider:
|
|
236
|
+
* - groq: OGG/Opus
|
|
237
|
+
* - openai: format from TTS_RESPONSE_FORMAT config)
|
|
238
|
+
*/
|
|
239
|
+
export async function generateSpeech(text, voice) {
|
|
240
|
+
if (config.TTS_PROVIDER === 'groq') {
|
|
241
|
+
return generateSpeechGroq(text, voice);
|
|
242
|
+
}
|
|
243
|
+
return generateSpeechOpenAI(text, voice);
|
|
244
|
+
}
|
|
245
|
+
//# sourceMappingURL=tts.js.map
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { InputFile } from 'grammy';
|
|
2
|
+
import { config } from '../config.js';
|
|
3
|
+
import { generateSpeech } from './tts.js';
|
|
4
|
+
import { getTTSSettings, isTTSEnabled } from './tts-settings.js';
|
|
5
|
+
import { getSessionKeyFromCtx } from '../utils/session-key.js';
|
|
6
|
+
function stripMarkdown(input) {
|
|
7
|
+
let text = input;
|
|
8
|
+
// Remove code blocks
|
|
9
|
+
text = text.replace(/```[\s\S]*?```/g, '');
|
|
10
|
+
// Inline code
|
|
11
|
+
text = text.replace(/`([^`]*)`/g, '$1');
|
|
12
|
+
// Links [text](url)
|
|
13
|
+
text = text.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
|
|
14
|
+
// Bold/italic/strikethrough markers
|
|
15
|
+
text = text.replace(/[\*_~]/g, '');
|
|
16
|
+
// Headers
|
|
17
|
+
text = text.replace(/^#+\s+/gm, '');
|
|
18
|
+
// Blockquotes
|
|
19
|
+
text = text.replace(/^>\s?/gm, '');
|
|
20
|
+
// List markers
|
|
21
|
+
text = text.replace(/^\s*[-*+]\s+/gm, '');
|
|
22
|
+
text = text.replace(/^\s*\d+\.\s+/gm, '');
|
|
23
|
+
// Collapse extra whitespace
|
|
24
|
+
text = text.replace(/\n{2,}/g, '\n');
|
|
25
|
+
return text.trim();
|
|
26
|
+
}
|
|
27
|
+
function looksLikeError(text) {
|
|
28
|
+
return /^(❌|⚠️|Error:)/.test(text.trim());
|
|
29
|
+
}
|
|
30
|
+
function truncateToMax(text, maxChars) {
|
|
31
|
+
if (text.length <= maxChars)
|
|
32
|
+
return text;
|
|
33
|
+
const truncated = text.slice(0, maxChars);
|
|
34
|
+
const lastPeriod = Math.max(truncated.lastIndexOf('.'), truncated.lastIndexOf('!'), truncated.lastIndexOf('?'));
|
|
35
|
+
if (lastPeriod > 200) {
|
|
36
|
+
return truncated.slice(0, lastPeriod + 1);
|
|
37
|
+
}
|
|
38
|
+
return truncated;
|
|
39
|
+
}
|
|
40
|
+
export async function maybeSendVoiceReply(ctx, text) {
|
|
41
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
42
|
+
if (!keyInfo)
|
|
43
|
+
return;
|
|
44
|
+
const { sessionKey } = keyInfo;
|
|
45
|
+
if (!isTTSEnabled(sessionKey))
|
|
46
|
+
return;
|
|
47
|
+
const hasKey = config.TTS_PROVIDER === 'groq' ? !!config.GROQ_API_KEY : !!config.OPENAI_API_KEY;
|
|
48
|
+
if (!hasKey)
|
|
49
|
+
return;
|
|
50
|
+
if (looksLikeError(text))
|
|
51
|
+
return;
|
|
52
|
+
const cleaned = stripMarkdown(text);
|
|
53
|
+
if (cleaned.length < 5)
|
|
54
|
+
return;
|
|
55
|
+
const safeText = truncateToMax(cleaned, config.TTS_MAX_CHARS);
|
|
56
|
+
if (!safeText)
|
|
57
|
+
return;
|
|
58
|
+
try {
|
|
59
|
+
const settings = getTTSSettings(sessionKey);
|
|
60
|
+
const audioBuffer = await generateSpeech(safeText, settings.voice);
|
|
61
|
+
const format = config.TTS_PROVIDER === 'groq'
|
|
62
|
+
? 'ogg'
|
|
63
|
+
: config.TTS_RESPONSE_FORMAT === 'opus' ? 'ogg' : config.TTS_RESPONSE_FORMAT;
|
|
64
|
+
const file = new InputFile(audioBuffer, `response.${format}`);
|
|
65
|
+
if (settings.autoplay) {
|
|
66
|
+
// Voice message: plays inline automatically in Telegram
|
|
67
|
+
await ctx.replyWithVoice(file);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
// Audio file: doesn't autoplay, shows as downloadable attachment
|
|
71
|
+
await ctx.replyWithAudio(file);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
console.error('[TTS] Failed to generate or send voice reply:', error);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=voice-reply.js.map
|