telecoder 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
@@ -1,25 +0,0 @@
1
- /**
2
- * Terminal UI settings per chat.
3
- * Persists user preferences for terminal-style display mode.
4
- */
5
- import { z } from 'zod';
6
- import { config } from '../config.js';
7
- import { createKeyedSettings } from '../utils/keyed-settings.js';
8
- const store = createKeyedSettings({
9
- file: 'terminal-ui-settings.json',
10
- label: 'TerminalUI',
11
- entrySchema: z.object({ enabled: z.boolean().optional() }),
12
- normalize: (stored) => ({
13
- enabled: typeof stored?.enabled === 'boolean' ? stored.enabled : config.TERMINAL_UI_DEFAULT,
14
- }),
15
- });
16
- export function getTerminalUISettings(sessionKey) {
17
- return store.get(sessionKey);
18
- }
19
- export function setTerminalUIEnabled(sessionKey, enabled) {
20
- store.update(sessionKey, { enabled });
21
- }
22
- export function isTerminalUIEnabled(sessionKey) {
23
- return store.get(sessionKey).enabled;
24
- }
25
- //# sourceMappingURL=terminal-settings.js.map
@@ -1,62 +0,0 @@
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 DELETED
@@ -1,245 +0,0 @@
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
@@ -1,78 +0,0 @@
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
@@ -1,117 +0,0 @@
1
- #!/usr/bin/env npx tsx
2
- /**
3
- * Debug utility for testing long-running agent queries with watchdog.
4
- *
5
- * Usage:
6
- * # Basic test with default project
7
- * CLAUDE_SDK_LOG_LEVEL=basic npx tsx src/utils/debug-agent.ts
8
- *
9
- * # Test with specific project directory
10
- * CLAUDE_SDK_LOG_LEVEL=basic npx tsx src/utils/debug-agent.ts /path/to/project
11
- *
12
- * # Test with shorter warning threshold
13
- * AGENT_WATCHDOG_WARN_SECONDS=10 CLAUDE_SDK_LOG_LEVEL=basic npx tsx src/utils/debug-agent.ts
14
- *
15
- * # Test with hard timeout
16
- * AGENT_QUERY_TIMEOUT_MS=60000 CLAUDE_SDK_LOG_LEVEL=basic npx tsx src/utils/debug-agent.ts
17
- */
18
- import { query } from '@anthropic-ai/claude-agent-sdk';
19
- import { config } from '../config.js';
20
- import { AgentWatchdog } from '../claude/agent-watchdog.js';
21
- import { createAgentTimer, recordMessage, formatDuration, getElapsedMs, getTimingReport, } from './agent-timer.js';
22
- const TEST_PROMPTS = {
23
- quick: 'What is 2 + 2?',
24
- medium: 'List the files in the current directory and describe what this project does.',
25
- long: 'Explore this codebase thoroughly. Find all TypeScript files, identify the main entry points, and explain the architecture. Use the Task tool with subagents if needed to parallelize your exploration.',
26
- subagent: 'Use the Task tool to spawn an explore agent that finds all configuration files in this project.',
27
- };
28
- async function main() {
29
- const projectDir = process.argv[2] || process.cwd();
30
- const promptKey = process.argv[3] || 'medium';
31
- const prompt = TEST_PROMPTS[promptKey] || TEST_PROMPTS.medium;
32
- console.log('=== Debug Agent Test ===');
33
- console.log(`Project: ${projectDir}`);
34
- console.log(`Prompt: ${promptKey} — "${prompt.substring(0, 80)}..."`);
35
- console.log(`Watchdog enabled: ${config.AGENT_WATCHDOG_ENABLED}`);
36
- console.log(`Watchdog warn after: ${config.AGENT_WATCHDOG_WARN_SECONDS}s`);
37
- console.log(`Watchdog log interval: ${config.AGENT_WATCHDOG_LOG_SECONDS}s`);
38
- console.log(`Query timeout: ${config.AGENT_QUERY_TIMEOUT_MS}ms (0 = disabled)`);
39
- console.log('========================\n');
40
- const timer = createAgentTimer();
41
- const controller = new AbortController();
42
- // Initialize watchdog
43
- const watchdog = config.AGENT_WATCHDOG_ENABLED
44
- ? new AgentWatchdog({
45
- chatId: '0', // Debug session
46
- warnAfterSeconds: config.AGENT_WATCHDOG_WARN_SECONDS,
47
- logIntervalSeconds: config.AGENT_WATCHDOG_LOG_SECONDS,
48
- timeoutMs: config.AGENT_QUERY_TIMEOUT_MS > 0 ? config.AGENT_QUERY_TIMEOUT_MS : undefined,
49
- onWarning: (sinceMsg, total) => {
50
- console.log(`[DEBUG] WATCHDOG WARNING: No messages for ${formatDuration(sinceMsg)} (total: ${formatDuration(total)})`);
51
- },
52
- onTimeout: () => {
53
- console.log('[DEBUG] WATCHDOG TIMEOUT: Aborting query');
54
- controller.abort();
55
- },
56
- })
57
- : null;
58
- watchdog?.start();
59
- try {
60
- const response = query({
61
- prompt,
62
- options: {
63
- cwd: projectDir,
64
- tools: ['Bash', 'Read', 'Glob', 'Grep', 'Task'],
65
- allowedTools: ['Bash', 'Read', 'Glob', 'Grep', 'Task'],
66
- permissionMode: 'acceptEdits',
67
- abortController: controller,
68
- model: 'opus',
69
- },
70
- });
71
- let messageCount = 0;
72
- for await (const message of response) {
73
- recordMessage(timer);
74
- watchdog?.recordActivity(message.type);
75
- messageCount++;
76
- const elapsed = formatDuration(getElapsedMs(timer));
77
- if (message.type === 'assistant') {
78
- for (const block of message.message.content) {
79
- if (block.type === 'text') {
80
- console.log(`[${elapsed}] TEXT: ${block.text.substring(0, 200)}...`);
81
- }
82
- else if (block.type === 'tool_use') {
83
- const toolInput = 'input' in block ? block.input : {};
84
- console.log(`[${elapsed}] TOOL: ${block.name}`);
85
- if (block.name === 'Task') {
86
- console.log(` └─ SUBAGENT: ${toolInput.subagent_type || 'unknown'} — ${String(toolInput.description || toolInput.prompt || '').substring(0, 80)}`);
87
- }
88
- }
89
- }
90
- }
91
- else if (message.type === 'result') {
92
- console.log(`\n[${elapsed}] RESULT: ${message.subtype}`);
93
- if (message.subtype === 'success') {
94
- console.log(` └─ ${message.result?.substring(0, 200)}...`);
95
- }
96
- }
97
- else if (message.type === 'tool_use_summary') {
98
- console.log(`[${elapsed}] TOOL_SUMMARY`);
99
- }
100
- else if (message.type === 'system') {
101
- console.log(`[${elapsed}] SYSTEM: ${message.subtype}`);
102
- }
103
- }
104
- console.log(`\n=== Query Complete ===`);
105
- console.log(`${getTimingReport(timer)}`);
106
- console.log(`Raw messages: ${messageCount}`);
107
- }
108
- catch (error) {
109
- console.error('\n=== Query Error ===');
110
- console.error(error instanceof Error ? error.message : error);
111
- }
112
- finally {
113
- watchdog?.stop();
114
- }
115
- }
116
- main().catch(console.error);
117
- //# sourceMappingURL=debug-agent.js.map
@@ -1,121 +0,0 @@
1
- #!/usr/bin/env npx tsx
2
- /**
3
- * Reproduction harness for watchdog-vs-Monitor / backgrounded-task hangs.
4
- *
5
- * Goal: prove or disprove whether the AgentWatchdog fires `controller.abort()`
6
- * during a quiet period after a backgrounded tool call, which the SDK then
7
- * reports as "Request interrupted by user for tool use".
8
- *
9
- * Usage:
10
- * npx tsx src/utils/debug-watchdog.ts # default 20s timeouts, Monitor prompt
11
- * SILENCE_MS=10000 npx tsx src/utils/debug-watchdog.ts
12
- * PROMPT=bgsleep npx tsx src/utils/debug-watchdog.ts # background bash + idle wait
13
- */
14
- import { query } from '@anthropic-ai/claude-agent-sdk';
15
- import { AgentWatchdog } from '../claude/agent-watchdog.js';
16
- import { formatDuration } from './agent-timer.js';
17
- import { resolveBundledClaudeBin } from './resolve-claude-bin.js';
18
- const SILENCE_MS = parseInt(process.env.SILENCE_MS || '20000', 10);
19
- const STALE_MS = parseInt(process.env.STALE_MS || '20000', 10);
20
- const PROMPT_KEY = process.env.PROMPT || 'monitor';
21
- const PROMPTS = {
22
- // Try to force a Monitor call after a backgrounded bash.
23
- monitor: `Run \`sleep 45\` as a background bash command with run_in_background:true. Then use the Monitor tool to wait until that background task completes. Do NOT call BashOutput or any other tool while waiting — only Monitor. Once the sleep finishes, briefly report the result.`,
24
- // Plain backgrounded bash with no follow-up tool calls.
25
- bgsleep: `Run \`sleep 45\` as a background bash command with run_in_background:true. Then sit idle until it finishes — do not call any tools or write any text until you see the task complete. Then say "done".`,
26
- };
27
- const prompt = PROMPTS[PROMPT_KEY] || PROMPTS.monitor;
28
- console.log('=== Watchdog Repro Harness ===');
29
- console.log(`Silence timeout : ${SILENCE_MS}ms`);
30
- console.log(`Stale timeout : ${STALE_MS}ms`);
31
- console.log(`Prompt : ${PROMPT_KEY}`);
32
- console.log(`Prompt text : ${prompt.substring(0, 100)}...`);
33
- console.log('==============================\n');
34
- const start = Date.now();
35
- const elapsed = () => formatDuration(Date.now() - start);
36
- const controller = new AbortController();
37
- let watchdogFired = null;
38
- const watchdog = new AgentWatchdog({
39
- chatId: 'repro',
40
- warnAfterSeconds: 5,
41
- logIntervalSeconds: 2,
42
- silenceTimeoutMs: SILENCE_MS,
43
- staleToolTimeoutMs: STALE_MS,
44
- onWarning: (sinceMsg, total) => {
45
- console.log(`[${elapsed()}] !! WATCHDOG WARNING: ${formatDuration(sinceMsg)} since last meaningful msg (total ${formatDuration(total)})`);
46
- },
47
- onSilenceTimeout: () => {
48
- watchdogFired = 'silence';
49
- console.log(`[${elapsed()}] !! WATCHDOG SILENCE TIMEOUT — aborting`);
50
- controller.abort();
51
- },
52
- onStaleToolTimeout: () => {
53
- watchdogFired = 'stale-tool';
54
- console.log(`[${elapsed()}] !! WATCHDOG STALE-TOOL TIMEOUT — aborting`);
55
- controller.abort();
56
- },
57
- });
58
- watchdog.start();
59
- const messageTypeCounts = {};
60
- let lastLoggedMs = 0;
61
- try {
62
- const bundled = resolveBundledClaudeBin();
63
- const response = query({
64
- prompt,
65
- options: {
66
- cwd: process.cwd(),
67
- permissionMode: 'bypassPermissions',
68
- allowDangerouslySkipPermissions: true,
69
- settingSources: ['project'],
70
- abortController: controller,
71
- model: 'claude-opus-4-8',
72
- ...(bundled ? { pathToClaudeCodeExecutable: bundled } : {}),
73
- },
74
- });
75
- for await (const message of response) {
76
- watchdog.recordActivity(message.type);
77
- messageTypeCounts[message.type] = (messageTypeCounts[message.type] || 0) + 1;
78
- const now = Date.now();
79
- if (now - lastLoggedMs >= 500 || message.type === 'assistant' || message.type === 'result') {
80
- const typeLabel = 'subtype' in message ? `${message.type}/${message.subtype}` : message.type;
81
- console.log(`[${elapsed()}] msg: ${typeLabel}`);
82
- lastLoggedMs = now;
83
- }
84
- if (controller.signal.aborted) {
85
- console.log(`[${elapsed()}] aborted, breaking loop`);
86
- break;
87
- }
88
- if (message.type === 'assistant') {
89
- for (const block of message.message.content) {
90
- if (block.type === 'tool_use') {
91
- console.log(`[${elapsed()}] → tool: ${block.name}`);
92
- }
93
- else if (block.type === 'text') {
94
- console.log(`[${elapsed()}] → text: ${block.text.substring(0, 120).replace(/\n/g, ' ')}`);
95
- }
96
- }
97
- }
98
- if (message.type === 'result') {
99
- console.log(`[${elapsed()}] result subtype: ${message.subtype}`);
100
- // Match production behaviour (agent.ts:942) — stop watchdog on result.
101
- // Without this, the harness's watchdog keeps running and fires falsely
102
- // during the post-result silence while backgrounded tasks are armed.
103
- console.log(`[${elapsed()}] (stopping watchdog — production-faithful)`);
104
- watchdog.stop();
105
- }
106
- }
107
- }
108
- catch (err) {
109
- console.error(`[${elapsed()}] ERROR:`, err instanceof Error ? err.message : err);
110
- }
111
- finally {
112
- watchdog.stop();
113
- }
114
- console.log('\n=== Summary ===');
115
- console.log(`Total elapsed : ${elapsed()}`);
116
- console.log(`Watchdog fired : ${watchdogFired ?? 'no'}`);
117
- console.log(`Message types :`);
118
- for (const [t, n] of Object.entries(messageTypeCounts)) {
119
- console.log(` ${t}: ${n}`);
120
- }
121
- //# sourceMappingURL=debug-watchdog.js.map
@@ -1,33 +0,0 @@
1
- /**
2
- * TeleCoder's own folder inside a project: `<project>/.telecoder/`, holding
3
- * what the bot writes there for Claude to read — files sent in the chat
4
- * (`uploads/`) and conversation handoffs (`handoffs/`).
5
- *
6
- * The folder ignores itself: the first time it is made, it gets a `.gitignore`
7
- * of `*`. A project's own `.gitignore` can't be relied on to cover it — one
8
- * that ignores the pre-rename `.claudegram/` doesn't ignore `.telecoder/` — and
9
- * without this the photos someone sent would be one `git add -A` away from a
10
- * commit. Nothing in the project has to change for it.
11
- */
12
- import * as fs from 'fs';
13
- import * as path from 'path';
14
- /** The folder's name inside a project. */
15
- export const PROJECT_DATA_DIR = '.telecoder';
16
- const SELF_IGNORE = '# Written by TeleCoder: nothing in this folder belongs in git.\n*\n';
17
- /** Create `<projectDir>/.telecoder/<sub>` if needed, and return its path. */
18
- export function ensureProjectDataDir(projectDir, sub) {
19
- const root = path.join(projectDir, PROJECT_DATA_DIR);
20
- const dir = path.join(root, sub);
21
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
22
- try {
23
- // 'wx' leaves a .gitignore someone has edited alone.
24
- fs.writeFileSync(path.join(root, '.gitignore'), SELF_IGNORE, { flag: 'wx', mode: 0o600 });
25
- }
26
- catch (err) {
27
- if (err.code !== 'EEXIST') {
28
- console.warn(`[ProjectData] Couldn't write ${path.join(root, '.gitignore')}: ${err.message}`);
29
- }
30
- }
31
- return dir;
32
- }
33
- //# sourceMappingURL=project-data-dir.js.map