@gonzih/cc-tg 0.9.16 → 0.9.17

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/dist/bot.js ADDED
@@ -0,0 +1,1421 @@
1
+ /**
2
+ * Telegram bot that routes messages to/from a Claude Code subprocess.
3
+ * One ClaudeProcess per chat_id — sessions are isolated per user.
4
+ */
5
+ import TelegramBot from "node-telegram-bot-api";
6
+ import { existsSync, createWriteStream, mkdirSync, statSync, readdirSync, readFileSync, writeFileSync } from "fs";
7
+ import { resolve, basename, join } from "path";
8
+ import os from "os";
9
+ import { execSync, spawn } from "child_process";
10
+ import https from "https";
11
+ import http from "http";
12
+ import { ClaudeProcess, extractText } from "./claude.js";
13
+ import { transcribeVoice, isVoiceAvailable } from "./voice.js";
14
+ import { formatForTelegram, splitLongMessage } from "./formatter.js";
15
+ import { detectUsageLimit } from "./usage-limit.js";
16
+ import { getCurrentToken, rotateToken, getTokenIndex, getTokenCount } from "./tokens.js";
17
+ import { writeChatLog } from "./notifier.js";
18
+ import { CronManager } from "./cron.js";
19
+ const BOT_COMMANDS = [
20
+ { command: "start", description: "Reset session and start fresh" },
21
+ { command: "reset", description: "Reset Claude session" },
22
+ { command: "stop", description: "Stop the current Claude task" },
23
+ { command: "status", description: "Check if a session is active" },
24
+ { command: "help", description: "Show all available commands" },
25
+ { command: "reload_mcp", description: "Restart the cc-agent MCP server process" },
26
+ { command: "mcp_status", description: "Check MCP server connection status" },
27
+ { command: "mcp_version", description: "Show cc-agent npm version and npx cache info" },
28
+ { command: "clear_npx_cache", description: "Clear npx cache and restart MCP to pick up latest version" },
29
+ { command: "restart", description: "Restart the bot process in-place" },
30
+ { command: "get_file", description: "Send a file from the server to this chat" },
31
+ { command: "cost", description: "Show session token usage and cost" },
32
+ { command: "skills", description: "List available Claude skills with descriptions" },
33
+ { command: "cron", description: "Manage cron jobs — add/list/edit/remove/clear" },
34
+ { command: "voice_retry", description: "Retry failed voice message transcriptions" },
35
+ ];
36
+ const FLUSH_DELAY_MS = 800; // debounce streaming chunks into one Telegram message
37
+ const TYPING_INTERVAL_MS = 4000; // re-send typing action before Telegram's 5s expiry
38
+ // Claude Sonnet 4.6 pricing (per 1M tokens)
39
+ const PRICING = {
40
+ inputPerM: 3.00,
41
+ outputPerM: 15.00,
42
+ cacheReadPerM: 0.30,
43
+ cacheWritePerM: 3.75,
44
+ };
45
+ function computeCostUsd(usage) {
46
+ return (usage.inputTokens * PRICING.inputPerM / 1_000_000 +
47
+ usage.outputTokens * PRICING.outputPerM / 1_000_000 +
48
+ usage.cacheReadTokens * PRICING.cacheReadPerM / 1_000_000 +
49
+ usage.cacheWriteTokens * PRICING.cacheWritePerM / 1_000_000);
50
+ }
51
+ function formatTokens(n) {
52
+ if (n >= 1000)
53
+ return `${(n / 1000).toFixed(1)}k`;
54
+ return String(n);
55
+ }
56
+ function formatCostReport(cost) {
57
+ const inputCost = cost.totalInputTokens * PRICING.inputPerM / 1_000_000;
58
+ const outputCost = cost.totalOutputTokens * PRICING.outputPerM / 1_000_000;
59
+ const cacheReadCost = cost.totalCacheReadTokens * PRICING.cacheReadPerM / 1_000_000;
60
+ const cacheWriteCost = cost.totalCacheWriteTokens * PRICING.cacheWritePerM / 1_000_000;
61
+ return [
62
+ "📊 Session cost",
63
+ `Messages: ${cost.messageCount}`,
64
+ `Total: $${cost.totalCostUsd.toFixed(3)}`,
65
+ ` Input: ${formatTokens(cost.totalInputTokens)} tokens ($${inputCost.toFixed(3)})`,
66
+ ` Output: ${formatTokens(cost.totalOutputTokens)} tokens ($${outputCost.toFixed(3)})`,
67
+ ` Cache read: ${formatTokens(cost.totalCacheReadTokens)} tokens ($${cacheReadCost.toFixed(3)})`,
68
+ ` Cache write: ${formatTokens(cost.totalCacheWriteTokens)} tokens ($${cacheWriteCost.toFixed(3)})`,
69
+ ].join("\n");
70
+ }
71
+ function formatAgentCostSummary(text) {
72
+ try {
73
+ const data = JSON.parse(text);
74
+ const totalCost = (data.total_cost_usd ?? data.total_cost ?? 0);
75
+ const totalJobs = (data.total_jobs ?? data.job_count ?? 0);
76
+ const byRepo = (data.by_repo ?? []);
77
+ const lines = [
78
+ "🤖 Agent jobs (all time)",
79
+ `Total: $${totalCost.toFixed(2)} across ${totalJobs} jobs`,
80
+ ];
81
+ for (const entry of byRepo) {
82
+ const repo = (entry.repo ?? entry.repository ?? "unknown");
83
+ const cost = (entry.cost_usd ?? entry.cost ?? 0);
84
+ const jobs = (entry.job_count ?? entry.jobs ?? 0);
85
+ lines.push(` ${repo}: $${cost.toFixed(2)} (${jobs} jobs)`);
86
+ }
87
+ return lines.join("\n");
88
+ }
89
+ catch {
90
+ return `🤖 Agent jobs (all time)\n${text}`;
91
+ }
92
+ }
93
+ class CostStore {
94
+ costs = new Map();
95
+ storePath;
96
+ constructor(cwd) {
97
+ this.storePath = join(cwd, ".cc-tg", "costs.json");
98
+ this.load();
99
+ }
100
+ get(chatId) {
101
+ let cost = this.costs.get(chatId);
102
+ if (!cost) {
103
+ cost = { totalInputTokens: 0, totalOutputTokens: 0, totalCacheReadTokens: 0, totalCacheWriteTokens: 0, totalCostUsd: 0, messageCount: 0 };
104
+ this.costs.set(chatId, cost);
105
+ }
106
+ return cost;
107
+ }
108
+ addUsage(chatId, usage) {
109
+ const cost = this.get(chatId);
110
+ cost.totalInputTokens += usage.inputTokens;
111
+ cost.totalOutputTokens += usage.outputTokens;
112
+ cost.totalCacheReadTokens += usage.cacheReadTokens;
113
+ cost.totalCacheWriteTokens += usage.cacheWriteTokens;
114
+ cost.totalCostUsd += computeCostUsd(usage);
115
+ this.persist();
116
+ }
117
+ incrementMessages(chatId) {
118
+ const cost = this.get(chatId);
119
+ cost.messageCount++;
120
+ this.persist();
121
+ }
122
+ persist() {
123
+ try {
124
+ const dir = join(this.storePath, "..");
125
+ if (!existsSync(dir))
126
+ mkdirSync(dir, { recursive: true });
127
+ const data = {};
128
+ for (const [chatId, cost] of this.costs) {
129
+ data[String(chatId)] = cost;
130
+ }
131
+ writeFileSync(this.storePath, JSON.stringify(data, null, 2));
132
+ }
133
+ catch (err) {
134
+ console.error("[costs] persist error:", err.message);
135
+ }
136
+ }
137
+ load() {
138
+ if (!existsSync(this.storePath))
139
+ return;
140
+ try {
141
+ const data = JSON.parse(readFileSync(this.storePath, "utf8"));
142
+ for (const [key, cost] of Object.entries(data)) {
143
+ this.costs.set(Number(key), cost);
144
+ }
145
+ console.log(`[costs] loaded ${this.costs.size} session costs from disk`);
146
+ }
147
+ catch (err) {
148
+ console.error("[costs] load error:", err.message);
149
+ }
150
+ }
151
+ }
152
+ export class CcTgBot {
153
+ bot;
154
+ sessions = new Map();
155
+ pendingRetries = new Map();
156
+ opts;
157
+ costStore;
158
+ botUsername = "";
159
+ botId = 0;
160
+ redis;
161
+ namespace;
162
+ lastActiveChatId;
163
+ cron;
164
+ constructor(opts) {
165
+ this.opts = opts;
166
+ this.redis = opts.redis;
167
+ this.namespace = opts.namespace ?? "default";
168
+ this.bot = new TelegramBot(opts.telegramToken, { polling: true });
169
+ this.bot.on("message", (msg) => this.handleTelegram(msg));
170
+ this.bot.on("polling_error", (err) => console.error("[tg]", err.message));
171
+ this.bot.getMe().then((me) => {
172
+ this.botUsername = me.username ?? "";
173
+ this.botId = me.id;
174
+ console.log(`[tg] bot identity: @${this.botUsername} (id=${this.botId})`);
175
+ }).catch((err) => console.error("[tg] getMe failed:", err.message));
176
+ this.costStore = new CostStore(opts.cwd ?? process.cwd());
177
+ this.cron = new CronManager(opts.cwd ?? process.cwd(), (chatId, prompt, _jobId, done) => {
178
+ this.runCronTask(chatId, prompt, done);
179
+ });
180
+ this.registerBotCommands();
181
+ console.log("cc-tg bot started");
182
+ console.log(`[voice] whisper available: ${isVoiceAvailable()}`);
183
+ }
184
+ registerBotCommands() {
185
+ this.bot.setMyCommands(BOT_COMMANDS)
186
+ .then(() => console.log("[tg] bot commands registered"))
187
+ .catch((err) => console.error("[tg] setMyCommands failed:", err.message));
188
+ }
189
+ /** Write a message to the Redis chat log. Fire-and-forget — no-op if Redis is not configured. */
190
+ writeChatMessage(role, source, content, chatId) {
191
+ if (!this.redis)
192
+ return;
193
+ const msg = {
194
+ id: `${source}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
195
+ source,
196
+ role,
197
+ content,
198
+ timestamp: new Date().toISOString(),
199
+ chatId,
200
+ };
201
+ writeChatLog(this.redis, this.namespace, msg);
202
+ }
203
+ /** Returns the last chatId that sent a message — used by the chat bridge when no fixed chatId is configured. */
204
+ getLastActiveChatId() {
205
+ return this.lastActiveChatId;
206
+ }
207
+ /** Session key: "chatId:threadId" for topics, "chatId:main" for DMs/non-topic groups */
208
+ sessionKey(chatId, threadId) {
209
+ return `${chatId}:${threadId ?? 'main'}`;
210
+ }
211
+ /**
212
+ * Send a message back to the correct thread (or plain chat if no thread).
213
+ * When threadId is undefined, calls sendMessage with exactly 2 args to preserve
214
+ * backward-compatible call signatures (no extra options object).
215
+ */
216
+ replyToChat(chatId, text, threadId, opts) {
217
+ if (threadId !== undefined) {
218
+ return this.bot.sendMessage(chatId, text, { ...opts, message_thread_id: threadId });
219
+ }
220
+ if (opts) {
221
+ return this.bot.sendMessage(chatId, text, opts);
222
+ }
223
+ return this.bot.sendMessage(chatId, text);
224
+ }
225
+ /** Parse THREAD_CWD_MAP env var — maps thread name or thread_id to a CWD path */
226
+ getThreadCwdMap() {
227
+ const raw = process.env.THREAD_CWD_MAP;
228
+ if (!raw)
229
+ return {};
230
+ try {
231
+ return JSON.parse(raw);
232
+ }
233
+ catch {
234
+ console.warn('[cc-tg] THREAD_CWD_MAP is not valid JSON, ignoring');
235
+ return {};
236
+ }
237
+ }
238
+ isAllowed(userId) {
239
+ if (!this.opts.allowedUserIds?.length)
240
+ return true;
241
+ return this.opts.allowedUserIds.includes(userId);
242
+ }
243
+ async handleTelegram(msg) {
244
+ const chatId = msg.chat.id;
245
+ const userId = msg.from?.id ?? chatId;
246
+ // Forum topic thread_id — undefined for DMs and non-topic group messages
247
+ const threadId = msg.message_thread_id;
248
+ // Thread name is available on the service message that creates a new topic.
249
+ // forum_topic_created is not in older @types/node-telegram-bot-api versions, so cast via unknown.
250
+ const rawMsg = msg;
251
+ const threadName = rawMsg.forum_topic_created
252
+ ? rawMsg.forum_topic_created.name
253
+ : undefined;
254
+ if (!this.isAllowed(userId)) {
255
+ await this.replyToChat(chatId, "Not authorized.", threadId);
256
+ return;
257
+ }
258
+ // Track the last chat that sent us a message for the chat bridge
259
+ this.lastActiveChatId = chatId;
260
+ // Group chat handling
261
+ const isGroup = msg.chat.type === "group" || msg.chat.type === "supergroup";
262
+ if (isGroup) {
263
+ // If GROUP_CHAT_IDS allowlist is set, only respond in those chats
264
+ if (this.opts.groupChatIds?.length && !this.opts.groupChatIds.includes(chatId)) {
265
+ return;
266
+ }
267
+ // Only respond if: bot is @mentioned, message is a reply to the bot, or text starts with /
268
+ const text = msg.text?.trim() ?? "";
269
+ const isMentioned = this.botUsername && text.includes(`@${this.botUsername}`);
270
+ const isReplyToBot = msg.reply_to_message?.from?.id === this.botId;
271
+ const isCommand = text.startsWith("/");
272
+ if (!isMentioned && !isReplyToBot && !isCommand) {
273
+ return;
274
+ }
275
+ }
276
+ // Voice message — transcribe then feed as text
277
+ if (msg.voice || msg.audio) {
278
+ await this.handleVoice(chatId, msg, threadId, threadName);
279
+ return;
280
+ }
281
+ // Photo — send as base64 image content block to Claude
282
+ if (msg.photo?.length) {
283
+ await this.handlePhoto(chatId, msg, threadId, threadName);
284
+ return;
285
+ }
286
+ // Document — download to CWD/.cc-tg/uploads/, tell Claude the path
287
+ if (msg.document) {
288
+ await this.handleDocument(chatId, msg, threadId, threadName);
289
+ return;
290
+ }
291
+ let text = msg.text?.trim();
292
+ if (!text)
293
+ return;
294
+ // Strip @botname mention prefix in group chats
295
+ if (this.botUsername) {
296
+ text = text.replace(new RegExp(`@${this.botUsername}\\s*`, "g"), "").trim();
297
+ }
298
+ const sessionKey = this.sessionKey(chatId, threadId);
299
+ // /start or /reset — kill existing session and ack
300
+ if (text === "/start" || text === "/reset") {
301
+ this.killSession(chatId, true, threadId);
302
+ await this.replyToChat(chatId, "Session reset. Send a message to start.", threadId);
303
+ return;
304
+ }
305
+ // /stop — kill active session (interrupt running Claude task)
306
+ if (text === "/stop") {
307
+ const has = this.sessions.has(sessionKey);
308
+ this.killSession(chatId, true, threadId);
309
+ await this.replyToChat(chatId, has ? "Stopped." : "No active session.", threadId);
310
+ return;
311
+ }
312
+ // /help — list all commands
313
+ if (text === "/help") {
314
+ const lines = BOT_COMMANDS.map((c) => `/${c.command} — ${c.description}`);
315
+ await this.replyToChat(chatId, lines.join("\n"), threadId);
316
+ return;
317
+ }
318
+ // /status
319
+ if (text === "/status") {
320
+ const has = this.sessions.has(sessionKey);
321
+ let status = has ? "Session active." : "No active session.";
322
+ const sleeping = this.pendingRetries.size;
323
+ if (sleeping > 0)
324
+ status += `\n⏸ ${sleeping} request(s) sleeping (usage limit).`;
325
+ await this.replyToChat(chatId, status, threadId);
326
+ return;
327
+ }
328
+ // /reload_mcp — kill cc-agent process so Claude Code auto-restarts it
329
+ if (text === "/reload_mcp") {
330
+ await this.handleReloadMcp(chatId, threadId);
331
+ return;
332
+ }
333
+ // /mcp_status — run `claude mcp list` and show connection status
334
+ if (text === "/mcp_status") {
335
+ await this.handleMcpStatus(chatId, threadId);
336
+ return;
337
+ }
338
+ // /mcp_version — show published npm version and cached npx entries
339
+ if (text === "/mcp_version") {
340
+ await this.handleMcpVersion(chatId, threadId);
341
+ return;
342
+ }
343
+ // /clear_npx_cache — wipe ~/.npm/_npx/ then restart cc-agent
344
+ if (text === "/clear_npx_cache") {
345
+ await this.handleClearNpxCache(chatId, threadId);
346
+ return;
347
+ }
348
+ // /restart — restart the bot process in-place
349
+ if (text === "/restart") {
350
+ await this.handleRestart(chatId, threadId);
351
+ return;
352
+ }
353
+ // /cron <schedule> <prompt> | /cron list | /cron clear | /cron remove <id>
354
+ if (text.startsWith("/cron")) {
355
+ await this.handleCron(chatId, text, threadId);
356
+ return;
357
+ }
358
+ // /get_file <path> — send a file from the server to the user
359
+ if (text.startsWith("/get_file")) {
360
+ await this.handleGetFile(chatId, text, threadId);
361
+ return;
362
+ }
363
+ // /cost — show session token usage and cost
364
+ if (text === "/cost") {
365
+ const cost = this.costStore.get(chatId);
366
+ let reply = formatCostReport(cost);
367
+ try {
368
+ const rawSummary = await this.callCcAgentTool("cost_summary");
369
+ if (rawSummary) {
370
+ reply += "\n\n" + formatAgentCostSummary(rawSummary);
371
+ }
372
+ }
373
+ catch (err) {
374
+ console.error("[cost] cc-agent cost_summary failed:", err.message);
375
+ }
376
+ await this.replyToChat(chatId, reply, threadId);
377
+ return;
378
+ }
379
+ // /skills — list available Claude skills from ~/.claude/skills/
380
+ if (text === "/skills") {
381
+ await this.replyToChat(chatId, listSkills(), threadId);
382
+ return;
383
+ }
384
+ // /voice_retry — retry failed voice message transcriptions
385
+ if (text === "/voice_retry") {
386
+ await this.handleVoiceRetry(chatId, threadId);
387
+ return;
388
+ }
389
+ const session = this.getOrCreateSession(chatId, threadId, threadName);
390
+ try {
391
+ const enriched = await enrichPromptWithUrls(text);
392
+ const prompt = buildPromptWithReplyContext(enriched, msg);
393
+ session.currentPrompt = prompt;
394
+ session.claude.sendPrompt(prompt);
395
+ this.startTyping(chatId, session);
396
+ this.writeChatMessage("user", "telegram", text, chatId);
397
+ }
398
+ catch (err) {
399
+ await this.replyToChat(chatId, `Error sending to Claude: ${err.message}`, threadId);
400
+ this.killSession(chatId, true, threadId);
401
+ }
402
+ }
403
+ /**
404
+ * Feed a text message into the active Claude session for the given chat.
405
+ * Called by the notifier when a UI message arrives via Redis pub/sub.
406
+ */
407
+ async handleUserMessage(chatId, text) {
408
+ const session = this.getOrCreateSession(chatId);
409
+ try {
410
+ const enriched = await enrichPromptWithUrls(text);
411
+ session.currentPrompt = enriched;
412
+ session.claude.sendPrompt(enriched);
413
+ this.startTyping(chatId, session);
414
+ this.writeChatMessage("user", "ui", text, chatId);
415
+ }
416
+ catch (err) {
417
+ await this.replyToChat(chatId, `Error sending to Claude: ${err.message}`);
418
+ this.killSession(chatId, true);
419
+ }
420
+ }
421
+ async handleVoice(chatId, msg, threadId, threadName) {
422
+ const fileId = msg.voice?.file_id ?? msg.audio?.file_id;
423
+ if (!fileId)
424
+ return;
425
+ console.log(`[voice:${chatId}] received voice message, transcribing...`);
426
+ this.bot.sendChatAction(chatId, "typing", threadId !== undefined ? { message_thread_id: threadId } : undefined).catch(() => { });
427
+ // Store in Redis before transcription so we can retry on failure
428
+ const pendingEntry = JSON.stringify({
429
+ file_id: fileId,
430
+ chat_id: chatId,
431
+ message_id: msg.message_id,
432
+ timestamp: Date.now(),
433
+ });
434
+ if (this.redis) {
435
+ await this.redis.rpush("voice:pending", pendingEntry).catch((err) => console.warn("[voice] redis rpush voice:pending failed:", err.message));
436
+ }
437
+ try {
438
+ const fileLink = await this.bot.getFileLink(fileId);
439
+ const transcript = await transcribeVoice(fileLink);
440
+ console.log(`[voice:${chatId}] transcribed: ${transcript}`);
441
+ // Remove from pending on success
442
+ if (this.redis) {
443
+ await this.redis.lrem("voice:pending", 0, pendingEntry).catch((err) => console.warn("[voice] redis lrem voice:pending failed:", err.message));
444
+ }
445
+ if (!transcript || transcript === "[empty transcription]") {
446
+ await this.replyToChat(chatId, "Could not transcribe voice message.", threadId);
447
+ return;
448
+ }
449
+ // Feed transcript into Claude as if user typed it
450
+ const session = this.getOrCreateSession(chatId, threadId, threadName);
451
+ try {
452
+ const prompt = buildPromptWithReplyContext(transcript, msg);
453
+ this.writeChatMessage("user", "telegram", transcript, chatId);
454
+ session.currentPrompt = prompt;
455
+ session.claude.sendPrompt(prompt);
456
+ this.startTyping(chatId, session);
457
+ }
458
+ catch (err) {
459
+ await this.replyToChat(chatId, `Error sending to Claude: ${err.message}`, threadId);
460
+ this.killSession(chatId, true, threadId);
461
+ }
462
+ }
463
+ catch (err) {
464
+ const errMsg = err.message;
465
+ console.error(`[voice:${chatId}] error:`, errMsg);
466
+ // Push to voice:failed on failure (entry stays in voice:pending for retry)
467
+ if (this.redis) {
468
+ const failedEntry = JSON.stringify({
469
+ file_id: fileId,
470
+ chat_id: chatId,
471
+ message_id: msg.message_id,
472
+ timestamp: Date.now(),
473
+ error: errMsg,
474
+ failed_at: Date.now(),
475
+ });
476
+ this.redis.rpush("voice:failed", failedEntry)
477
+ .then(() => this.redis.expire("voice:failed", 48 * 60 * 60))
478
+ .catch((redisErr) => console.warn("[voice] redis write voice:failed failed:", redisErr.message));
479
+ }
480
+ // User-friendly error messages
481
+ let userMsg;
482
+ if (errMsg.includes("whisper-cpp not found") || errMsg.includes("whisper not found")) {
483
+ userMsg = "Voice transcription unavailable — whisper-cpp not installed";
484
+ }
485
+ else if (errMsg.includes("No whisper model found")) {
486
+ userMsg = "Voice transcription unavailable — no whisper model found";
487
+ }
488
+ else if (errMsg.includes("HTTP") && errMsg.includes("downloading")) {
489
+ userMsg = "Could not download voice file from Telegram";
490
+ }
491
+ else {
492
+ userMsg = `Voice transcription failed: ${errMsg}`;
493
+ }
494
+ await this.replyToChat(chatId, userMsg, threadId);
495
+ }
496
+ }
497
+ async handleVoiceRetry(chatId, threadId) {
498
+ if (!this.redis) {
499
+ await this.replyToChat(chatId, "Redis not configured — voice retry unavailable.", threadId);
500
+ return;
501
+ }
502
+ const [pendingRaw, failedRaw] = await Promise.all([
503
+ this.redis.lrange("voice:pending", 0, -1).catch(() => []),
504
+ this.redis.lrange("voice:failed", 0, -1).catch(() => []),
505
+ ]);
506
+ // Deduplicate by file_id across both lists
507
+ const allEntries = new Map();
508
+ for (const raw of [...pendingRaw, ...failedRaw]) {
509
+ try {
510
+ const entry = JSON.parse(raw);
511
+ if (entry.file_id)
512
+ allEntries.set(entry.file_id, entry);
513
+ }
514
+ catch { /* skip malformed entries */ }
515
+ }
516
+ if (allEntries.size === 0) {
517
+ await this.replyToChat(chatId, "No pending voice messages to retry.", threadId);
518
+ return;
519
+ }
520
+ await this.replyToChat(chatId, `Retrying ${allEntries.size} voice message(s)...`, threadId);
521
+ let succeeded = 0;
522
+ let failed = 0;
523
+ const errors = [];
524
+ for (const [fileId, entry] of allEntries) {
525
+ try {
526
+ const fileLink = await this.bot.getFileLink(fileId);
527
+ const transcript = await transcribeVoice(fileLink);
528
+ if (transcript && transcript !== "[empty transcription]") {
529
+ const session = this.getOrCreateSession(entry.chat_id, threadId, undefined);
530
+ session.claude.sendPrompt(transcript);
531
+ this.writeChatMessage("user", "telegram", transcript, entry.chat_id);
532
+ // Remove from both lists
533
+ const matchPending = pendingRaw.find((r) => r.includes(`"${fileId}"`));
534
+ const matchFailed = failedRaw.find((r) => r.includes(`"${fileId}"`));
535
+ if (matchPending)
536
+ await this.redis.lrem("voice:pending", 0, matchPending).catch(() => { });
537
+ if (matchFailed)
538
+ await this.redis.lrem("voice:failed", 0, matchFailed).catch(() => { });
539
+ succeeded++;
540
+ }
541
+ else {
542
+ failed++;
543
+ errors.push(`${fileId}: empty transcription`);
544
+ }
545
+ }
546
+ catch (err) {
547
+ const errMsg = err.message;
548
+ failed++;
549
+ errors.push(`${fileId}: ${errMsg}`);
550
+ // Permanently unretryable (expired Telegram link) — remove from voice:pending
551
+ if (errMsg.includes("Bad Request") || errMsg.includes("file_id")) {
552
+ const matchPending = pendingRaw.find((r) => r.includes(`"${fileId}"`));
553
+ if (matchPending)
554
+ await this.redis.lrem("voice:pending", 0, matchPending).catch(() => { });
555
+ }
556
+ }
557
+ }
558
+ // Purge stale entries from voice:pending older than 48h
559
+ const staleThreshold = 48 * 60 * 60 * 1000;
560
+ let purged = 0;
561
+ for (const raw of pendingRaw) {
562
+ try {
563
+ const entry = JSON.parse(raw);
564
+ if (entry.timestamp && Date.now() - entry.timestamp > staleThreshold) {
565
+ await this.redis.lrem("voice:pending", 0, raw).catch(() => { });
566
+ purged++;
567
+ }
568
+ }
569
+ catch { /* skip malformed entries */ }
570
+ }
571
+ const lines = [`Voice retry complete: ${succeeded} succeeded, ${failed} failed, ${purged} stale entries purged.`];
572
+ if (errors.length > 0)
573
+ lines.push(...errors.map((e) => `• ${e}`));
574
+ await this.replyToChat(chatId, lines.join("\n"), threadId);
575
+ }
576
+ async handlePhoto(chatId, msg, threadId, threadName) {
577
+ // Pick highest resolution photo
578
+ const photos = msg.photo;
579
+ const best = photos[photos.length - 1];
580
+ const caption = msg.caption?.trim();
581
+ console.log(`[photo:${chatId}] received image file_id=${best.file_id}`);
582
+ this.bot.sendChatAction(chatId, "typing", threadId !== undefined ? { message_thread_id: threadId } : undefined).catch(() => { });
583
+ try {
584
+ const fileLink = await this.bot.getFileLink(best.file_id);
585
+ const imageData = await fetchAsBase64(fileLink);
586
+ // Telegram photos are always JPEG
587
+ const session = this.getOrCreateSession(chatId, threadId, threadName);
588
+ session.claude.sendImage(imageData, "image/jpeg", caption);
589
+ this.startTyping(chatId, session);
590
+ }
591
+ catch (err) {
592
+ console.error(`[photo:${chatId}] error:`, err.message);
593
+ await this.replyToChat(chatId, `Failed to process image: ${err.message}`, threadId);
594
+ }
595
+ }
596
+ async handleDocument(chatId, msg, threadId, threadName) {
597
+ const doc = msg.document;
598
+ const caption = msg.caption?.trim();
599
+ const fileName = doc.file_name ?? `file_${doc.file_id}`;
600
+ console.log(`[doc:${chatId}] received document file_name=${fileName} mime=${doc.mime_type}`);
601
+ this.bot.sendChatAction(chatId, "typing", threadId !== undefined ? { message_thread_id: threadId } : undefined).catch(() => { });
602
+ try {
603
+ const uploadsDir = join(this.opts.cwd ?? process.cwd(), ".cc-tg", "uploads");
604
+ mkdirSync(uploadsDir, { recursive: true });
605
+ const destPath = join(uploadsDir, fileName);
606
+ const fileLink = await this.bot.getFileLink(doc.file_id);
607
+ await downloadToFile(fileLink, destPath);
608
+ console.log(`[doc:${chatId}] saved to ${destPath}`);
609
+ const prompt = caption
610
+ ? `${caption}\n\nATTACHMENTS: [${fileName}](${destPath})`
611
+ : `ATTACHMENTS: [${fileName}](${destPath})`;
612
+ const session = this.getOrCreateSession(chatId, threadId, threadName);
613
+ session.claude.sendPrompt(prompt);
614
+ this.startTyping(chatId, session);
615
+ }
616
+ catch (err) {
617
+ console.error(`[doc:${chatId}] error:`, err.message);
618
+ await this.replyToChat(chatId, `Failed to receive document: ${err.message}`, threadId);
619
+ }
620
+ }
621
+ getOrCreateSession(chatId, threadId, threadName) {
622
+ const key = this.sessionKey(chatId, threadId);
623
+ const existing = this.sessions.get(key);
624
+ if (existing && !existing.claude.exited)
625
+ return existing;
626
+ // Determine CWD for this thread — check THREAD_CWD_MAP by name then by ID
627
+ let sessionCwd = this.opts.cwd;
628
+ const threadCwdMap = this.getThreadCwdMap();
629
+ if (threadName && threadCwdMap[threadName]) {
630
+ sessionCwd = threadCwdMap[threadName];
631
+ console.log(`[cc-tg] thread "${threadName}" → cwd: ${sessionCwd}`);
632
+ }
633
+ else if (threadId !== undefined && threadCwdMap[String(threadId)]) {
634
+ sessionCwd = threadCwdMap[String(threadId)];
635
+ console.log(`[cc-tg] thread ${threadId} → cwd: ${sessionCwd}`);
636
+ }
637
+ const claude = new ClaudeProcess({
638
+ cwd: sessionCwd,
639
+ token: getCurrentToken() || this.opts.claudeToken,
640
+ });
641
+ const session = {
642
+ claude,
643
+ pendingText: "",
644
+ flushTimer: null,
645
+ typingTimer: null,
646
+ writtenFiles: new Set(),
647
+ currentPrompt: "",
648
+ isRetry: false,
649
+ threadId,
650
+ };
651
+ claude.on("usage", (usage) => {
652
+ this.costStore.addUsage(chatId, usage);
653
+ });
654
+ claude.on("message", (msg) => {
655
+ // Verbose logging — log every message type and subtype
656
+ const subtype = msg.payload.subtype ?? "";
657
+ const toolName = this.extractToolName(msg);
658
+ const logParts = [`[claude:${key}] msg=${msg.type}`];
659
+ if (subtype)
660
+ logParts.push(`subtype=${subtype}`);
661
+ if (toolName)
662
+ logParts.push(`tool=${toolName}`);
663
+ console.log(logParts.join(" "));
664
+ // Track files written by Write/Edit tool calls
665
+ this.trackWrittenFiles(msg, session, sessionCwd);
666
+ // Publish tool call events to the chat log
667
+ if (msg.type === "assistant") {
668
+ const message = msg.payload.message;
669
+ const content = message?.content;
670
+ if (Array.isArray(content)) {
671
+ for (const block of content) {
672
+ if (block.type !== "tool_use")
673
+ continue;
674
+ const name = block.name;
675
+ const input = block.input;
676
+ this.writeChatMessage("tool", "cc-tg", `[tool] ${name}: ${JSON.stringify(input ?? {})}`, chatId);
677
+ }
678
+ }
679
+ }
680
+ this.handleClaudeMessage(chatId, session, msg);
681
+ });
682
+ claude.on("stderr", (data) => {
683
+ const line = data.trim();
684
+ if (line)
685
+ console.error(`[claude:${key}:stderr]`, line);
686
+ });
687
+ claude.on("exit", (code) => {
688
+ console.log(`[claude:${key}] exited code=${code}`);
689
+ this.stopTyping(session);
690
+ this.sessions.delete(key);
691
+ });
692
+ claude.on("error", (err) => {
693
+ console.error(`[claude:${key}] process error: ${err.message}`);
694
+ this.bot.sendMessage(chatId, `Claude process error: ${err.message}`).catch(() => { });
695
+ this.stopTyping(session);
696
+ this.sessions.delete(key);
697
+ });
698
+ this.sessions.set(key, session);
699
+ return session;
700
+ }
701
+ handleClaudeMessage(chatId, session, msg) {
702
+ // Use only the final `result` message — it contains the complete response text.
703
+ // Ignore `assistant` streaming chunks to avoid duplicates.
704
+ if (msg.type !== "result")
705
+ return;
706
+ this.stopTyping(session);
707
+ this.costStore.incrementMessages(chatId);
708
+ const text = extractText(msg);
709
+ if (!text)
710
+ return;
711
+ // Check for usage/rate limit signals before forwarding to Telegram
712
+ const sig = detectUsageLimit(text);
713
+ if (sig.detected) {
714
+ const threadId = session.threadId;
715
+ const retryKey = this.sessionKey(chatId, threadId);
716
+ const lastPrompt = session.currentPrompt;
717
+ const prevRetry = this.pendingRetries.get(retryKey);
718
+ const attempt = (prevRetry?.attempt ?? 0) + 1;
719
+ if (prevRetry)
720
+ clearTimeout(prevRetry.timer);
721
+ this.replyToChat(chatId, sig.humanMessage, threadId).catch(() => { });
722
+ this.killSession(chatId, true, threadId);
723
+ // Token rotation: if this is a usage_exhausted signal and we have multiple
724
+ // tokens, rotate to the next one and retry immediately instead of sleeping.
725
+ // Only rotate if we haven't yet cycled through all tokens (attempt <= count-1).
726
+ if (sig.reason === "usage_exhausted" && getTokenCount() > 1 && attempt <= getTokenCount() - 1) {
727
+ const prevIdx = getTokenIndex();
728
+ rotateToken();
729
+ const newIdx = getTokenIndex();
730
+ const total = getTokenCount();
731
+ console.log(`[cc-tg] Token ${prevIdx + 1}/${total} exhausted, rotating to token ${newIdx + 1}/${total}`);
732
+ this.replyToChat(chatId, `🔄 Token ${prevIdx + 1}/${total} exhausted, switching to token ${newIdx + 1}/${total}...`, threadId).catch(() => { });
733
+ this.pendingRetries.set(retryKey, { text: lastPrompt, attempt, timer: setTimeout(() => { }, 0) });
734
+ try {
735
+ const retrySession = this.getOrCreateSession(chatId, threadId);
736
+ retrySession.currentPrompt = lastPrompt;
737
+ retrySession.isRetry = true;
738
+ retrySession.claude.sendPrompt(lastPrompt);
739
+ this.startTyping(chatId, retrySession);
740
+ }
741
+ catch (err) {
742
+ this.replyToChat(chatId, `❌ Failed to retry with rotated token: ${err.message}`, threadId).catch(() => { });
743
+ }
744
+ return;
745
+ }
746
+ if (attempt > 3) {
747
+ this.replyToChat(chatId, "❌ Claude usage limit persists after 3 retries. Please try again later.", threadId).catch(() => { });
748
+ this.pendingRetries.delete(retryKey);
749
+ return;
750
+ }
751
+ console.log(`[usage-limit:${retryKey}] ${sig.reason} — scheduling retry attempt=${attempt} in ${sig.retryAfterMs}ms`);
752
+ const timer = setTimeout(() => {
753
+ this.pendingRetries.delete(retryKey);
754
+ try {
755
+ const retrySession = this.getOrCreateSession(chatId, threadId);
756
+ retrySession.currentPrompt = lastPrompt;
757
+ retrySession.isRetry = true;
758
+ retrySession.claude.sendPrompt(lastPrompt);
759
+ this.startTyping(chatId, retrySession);
760
+ }
761
+ catch (err) {
762
+ this.replyToChat(chatId, `❌ Failed to retry: ${err.message}`, threadId).catch(() => { });
763
+ }
764
+ }, sig.retryAfterMs);
765
+ this.pendingRetries.set(retryKey, { text: lastPrompt, attempt, timer });
766
+ return;
767
+ }
768
+ // Accumulate text and debounce — Claude streams chunks rapidly
769
+ session.pendingText += text;
770
+ if (session.flushTimer)
771
+ clearTimeout(session.flushTimer);
772
+ session.flushTimer = setTimeout(() => this.flushPending(chatId, session), FLUSH_DELAY_MS);
773
+ }
774
+ startTyping(chatId, session) {
775
+ this.stopTyping(session);
776
+ // Send immediately, then keep alive every 4s
777
+ // Pass message_thread_id so typing appears in the correct forum topic thread
778
+ const threadOpts = session.threadId !== undefined ? { message_thread_id: session.threadId } : undefined;
779
+ this.bot.sendChatAction(chatId, "typing", threadOpts).catch(() => { });
780
+ session.typingTimer = setInterval(() => {
781
+ this.bot.sendChatAction(chatId, "typing", threadOpts).catch(() => { });
782
+ }, TYPING_INTERVAL_MS);
783
+ }
784
+ stopTyping(session) {
785
+ if (session.typingTimer) {
786
+ clearInterval(session.typingTimer);
787
+ session.typingTimer = null;
788
+ }
789
+ }
790
+ flushPending(chatId, session) {
791
+ const raw = session.pendingText.trim();
792
+ session.pendingText = "";
793
+ session.flushTimer = null;
794
+ if (!raw)
795
+ return;
796
+ this.writeChatMessage("assistant", "cc-tg", raw, chatId);
797
+ const text = session.isRetry ? `✅ Claude is back!\n\n${raw}` : raw;
798
+ session.isRetry = false;
799
+ // Format for Telegram HTML and split if needed (max 4096 chars)
800
+ const formatted = formatForTelegram(text);
801
+ const chunks = splitLongMessage(formatted);
802
+ const threadId = session.threadId;
803
+ for (const chunk of chunks) {
804
+ this.replyToChat(chatId, chunk, threadId, { parse_mode: "HTML" }).catch(() => {
805
+ // HTML parse failed — retry as plain text
806
+ this.replyToChat(chatId, chunk, threadId).catch((err) => console.error(`[tg:${chatId}] send failed:`, err.message));
807
+ });
808
+ }
809
+ // Hybrid file upload: find files mentioned in result text that Claude actually wrote
810
+ try {
811
+ this.uploadMentionedFiles(chatId, text, session);
812
+ }
813
+ catch (err) {
814
+ console.error(`[tg:${chatId}] uploadMentionedFiles error:`, err.message);
815
+ }
816
+ }
817
+ trackWrittenFiles(msg, session, cwd) {
818
+ // Only look at assistant messages with tool_use blocks
819
+ if (msg.type !== "assistant")
820
+ return;
821
+ const message = msg.payload.message;
822
+ if (!message)
823
+ return;
824
+ const content = message.content;
825
+ if (!Array.isArray(content))
826
+ return;
827
+ for (const block of content) {
828
+ if (block.type !== "tool_use")
829
+ continue;
830
+ const name = block.name;
831
+ const input = block.input;
832
+ if (!input)
833
+ continue;
834
+ if (["Write", "Edit", "NotebookEdit"].includes(name)) {
835
+ // Write tool uses file_path, Edit uses file_path
836
+ const filePath = input.file_path ?? input.path;
837
+ if (!filePath)
838
+ continue;
839
+ // Resolve relative paths against cwd
840
+ const resolved = filePath.startsWith("/")
841
+ ? filePath
842
+ : resolve(cwd ?? process.cwd(), filePath);
843
+ console.log(`[claude:files] tracked written file: ${resolved}`);
844
+ session.writtenFiles.add(resolved);
845
+ }
846
+ else if (name === "Bash") {
847
+ const cmd = input.command ?? "";
848
+ if (/\byt-dlp\b|\bffmpeg\b/.test(cmd)) {
849
+ // Scan output dir for recently modified media files (template paths like /tmp/%(title)s.%(ext)s
850
+ // make the actual filename unknowable at tracking time)
851
+ const oFlagMatch = cmd.match(/-o\s+["']?([^\s"']+)/);
852
+ let scanDir = "/tmp/";
853
+ if (oFlagMatch) {
854
+ const oPath = oFlagMatch[1].replace(/["'].*$/, "");
855
+ const dirEnd = oPath.lastIndexOf("/");
856
+ if (dirEnd > 0)
857
+ scanDir = oPath.slice(0, dirEnd + 1);
858
+ }
859
+ const MEDIA_EXTS = new Set([".mp3", ".mp4", ".wav", ".ogg", ".flac", ".webm", ".m4a", ".aac"]);
860
+ const nowMs = Date.now();
861
+ try {
862
+ for (const entry of readdirSync(scanDir)) {
863
+ const dotIdx = entry.lastIndexOf(".");
864
+ if (dotIdx < 0)
865
+ continue;
866
+ const ext = entry.slice(dotIdx).toLowerCase();
867
+ if (!MEDIA_EXTS.has(ext))
868
+ continue;
869
+ const full = join(scanDir, entry);
870
+ try {
871
+ if (nowMs - statSync(full).mtimeMs <= 90_000) {
872
+ console.log(`[claude:files] tracked yt-dlp/ffmpeg output: ${full}`);
873
+ session.writtenFiles.add(full);
874
+ }
875
+ }
876
+ catch { /* skip unreadable entries */ }
877
+ }
878
+ }
879
+ catch { /* scanDir doesn't exist or unreadable */ }
880
+ }
881
+ else {
882
+ // Other bash commands: try to extract output path from -o flag
883
+ const oFlag = cmd.match(/-o\s+["']?([^\s"']+\.[\w]{1,10})["']?/);
884
+ if (oFlag)
885
+ session.writtenFiles.add(resolve(cwd ?? process.cwd(), oFlag[1]));
886
+ }
887
+ // mv source dest — track dest
888
+ const mvMatch = cmd.match(/\bmv\s+\S+\s+["']?([^\s"']+)["']?$/);
889
+ if (mvMatch)
890
+ session.writtenFiles.add(resolve(cwd ?? process.cwd(), mvMatch[1]));
891
+ // cp source dest — track dest
892
+ const cpMatch = cmd.match(/\bcp\s+\S+\s+["']?([^\s"']+)["']?$/);
893
+ if (cpMatch)
894
+ session.writtenFiles.add(resolve(cwd ?? process.cwd(), cpMatch[1]));
895
+ // curl -o path or wget -O path
896
+ const curlMatch = cmd.match(/curl\s+.*?-o\s+["']?([^\s"']+)["']?/);
897
+ if (curlMatch)
898
+ session.writtenFiles.add(resolve(cwd ?? process.cwd(), curlMatch[1]));
899
+ // wget -O path
900
+ const wgetMatch = cmd.match(/wget\s+.*?-O\s+["']?([^\s"']+)["']?/);
901
+ if (wgetMatch)
902
+ session.writtenFiles.add(resolve(cwd ?? process.cwd(), wgetMatch[1]));
903
+ }
904
+ }
905
+ }
906
+ isSensitiveFile(filePath) {
907
+ const name = basename(filePath).toLowerCase();
908
+ const sensitivePatterns = [
909
+ /credential/i, /secret/i, /password/i, /passwd/i, /\.env/i,
910
+ /api[_-]?key/i, /token/i, /private[_-]?key/i, /id_rsa/i,
911
+ /\.pem$/i, /\.key$/i, /\.pfx$/i, /\.p12$/i,
912
+ /gmail/i, /oauth/i, /\bauth\b/i,
913
+ ];
914
+ return sensitivePatterns.some((p) => p.test(name));
915
+ }
916
+ uploadMentionedFiles(chatId, resultText, session) {
917
+ // Extract file path candidates from result text
918
+ // Match: /absolute/path/file.ext or relative like ./foo/bar.csv or just foo.pdf
919
+ const pathPattern = /(?:^|[\s`'"(])(\/?[\w.\-/]+\.[\w]{1,10})(?:[\s`'")\n]|$)/gm;
920
+ const quotedPattern = /"([^"]+\.[a-zA-Z0-9]{1,10})"|'([^']+\.[a-zA-Z0-9]{1,10})'/g;
921
+ const candidates = new Set();
922
+ let match;
923
+ while ((match = pathPattern.exec(resultText)) !== null) {
924
+ candidates.add(match[1]);
925
+ }
926
+ while ((match = quotedPattern.exec(resultText)) !== null) {
927
+ candidates.add(match[1] ?? match[2]);
928
+ }
929
+ const safeDirs = ["/tmp/", "/var/folders/", os.homedir() + "/Downloads/"];
930
+ const isSafeDir = (p) => safeDirs.some(d => p.startsWith(d)) || p.startsWith(this.opts.cwd ?? process.cwd());
931
+ const toUpload = [];
932
+ if (session.writtenFiles.size > 0) {
933
+ for (const candidate of candidates) {
934
+ // Try as-is (absolute), or resolve against cwd
935
+ const resolved = candidate.startsWith("/")
936
+ ? candidate
937
+ : resolve(this.opts.cwd ?? process.cwd(), candidate);
938
+ if (session.writtenFiles.has(resolved) && existsSync(resolved)) {
939
+ toUpload.push(resolved);
940
+ }
941
+ else {
942
+ // Also check by basename — result might mention just the filename
943
+ for (const written of session.writtenFiles) {
944
+ if (basename(written) === basename(candidate) && existsSync(written)) {
945
+ toUpload.push(written);
946
+ break;
947
+ }
948
+ }
949
+ }
950
+ }
951
+ }
952
+ // Also upload files mentioned in result text that exist in safe dirs
953
+ // even if not tracked via Write tool
954
+ for (const candidate of candidates) {
955
+ const resolved = candidate.startsWith("/")
956
+ ? candidate
957
+ : resolve(this.opts.cwd ?? process.cwd(), candidate);
958
+ if (existsSync(resolved) && isSafeDir(resolved) && !toUpload.includes(resolved)) {
959
+ toUpload.push(resolved);
960
+ }
961
+ }
962
+ // Deduplicate and filter sensitive files
963
+ const unique = [...new Set(toUpload)];
964
+ for (const filePath of unique) {
965
+ if (this.isSensitiveFile(filePath)) {
966
+ console.log(`[claude:files] skipping sensitive file: ${filePath}`);
967
+ continue;
968
+ }
969
+ let fileSize;
970
+ try {
971
+ fileSize = statSync(filePath).size;
972
+ }
973
+ catch {
974
+ continue; // file disappeared between existsSync and statSync
975
+ }
976
+ const MAX_TG_FILE_BYTES = 50 * 1024 * 1024;
977
+ if (fileSize > MAX_TG_FILE_BYTES) {
978
+ const mb = (fileSize / (1024 * 1024)).toFixed(1);
979
+ this.replyToChat(chatId, `File too large for Telegram (${mb}mb). Find it at: ${filePath}`, session.threadId).catch(() => { });
980
+ continue;
981
+ }
982
+ console.log(`[claude:files] uploading to telegram: ${filePath}`);
983
+ const docOpts = session.threadId ? { message_thread_id: session.threadId } : undefined;
984
+ this.bot.sendDocument(chatId, filePath, docOpts).catch((err) => console.error(`[tg:${chatId}] sendDocument failed for ${filePath}:`, err.message));
985
+ }
986
+ // Clear written files for next turn
987
+ session.writtenFiles.clear();
988
+ }
989
+ extractToolName(msg) {
990
+ const message = msg.payload.message;
991
+ if (!message)
992
+ return "";
993
+ const content = message.content;
994
+ if (!Array.isArray(content))
995
+ return "";
996
+ const toolUse = content.find((b) => b.type === "tool_use");
997
+ return toolUse?.name ?? "";
998
+ }
999
+ /** Find cc-agent PIDs via pgrep. Returns array of numeric PIDs. */
1000
+ findCcAgentPids() {
1001
+ try {
1002
+ const out = execSync("pgrep -f cc-agent", { encoding: "utf8" }).trim();
1003
+ return out.split("\n").map((s) => parseInt(s.trim(), 10)).filter((n) => !isNaN(n) && n > 0);
1004
+ }
1005
+ catch {
1006
+ // pgrep exits with code 1 when no match — that's fine
1007
+ return [];
1008
+ }
1009
+ }
1010
+ /** Kill cc-agent PIDs with SIGTERM. Returns the list of killed PIDs. */
1011
+ killCcAgent() {
1012
+ const pids = this.findCcAgentPids();
1013
+ for (const pid of pids) {
1014
+ try {
1015
+ process.kill(pid, "SIGTERM");
1016
+ console.log(`[mcp] sent SIGTERM to cc-agent pid=${pid}`);
1017
+ }
1018
+ catch (err) {
1019
+ console.warn(`[mcp] failed to kill pid=${pid}:`, err.message);
1020
+ }
1021
+ }
1022
+ return pids;
1023
+ }
1024
+ async handleReloadMcp(chatId, threadId) {
1025
+ await this.replyToChat(chatId, "Clearing npx cache and reloading MCP...", threadId);
1026
+ try {
1027
+ const home = process.env.HOME ?? "~";
1028
+ execSync(`rm -rf "${home}/.npm/_npx/"`, { encoding: "utf8", shell: "/bin/sh" });
1029
+ console.log("[mcp] cleared ~/.npm/_npx/");
1030
+ }
1031
+ catch (err) {
1032
+ await this.replyToChat(chatId, `Warning: failed to clear npx cache: ${err.message}`, threadId);
1033
+ }
1034
+ const pids = this.killCcAgent();
1035
+ if (pids.length === 0) {
1036
+ await this.replyToChat(chatId, "NPX cache cleared. No cc-agent process found — MCP will start fresh on the next agent call.", threadId);
1037
+ return;
1038
+ }
1039
+ await this.replyToChat(chatId, `NPX cache cleared. Sent SIGTERM to cc-agent (pid${pids.length > 1 ? "s" : ""}: ${pids.join(", ")}).\nMCP restarted. New process will load on next agent call.`, threadId);
1040
+ }
1041
+ async handleMcpStatus(chatId, threadId) {
1042
+ try {
1043
+ const output = execSync("claude mcp list", { encoding: "utf8", shell: "/bin/sh" }).trim();
1044
+ await this.replyToChat(chatId, `MCP server status:\n\n${output || "(no output)"}`, threadId);
1045
+ }
1046
+ catch (err) {
1047
+ await this.replyToChat(chatId, `Failed to run claude mcp list: ${err.message}`, threadId);
1048
+ }
1049
+ }
1050
+ async handleMcpVersion(chatId, threadId) {
1051
+ let npmVersion = "unknown";
1052
+ let cacheEntries = "(unavailable)";
1053
+ try {
1054
+ npmVersion = execSync("npm view @gonzih/cc-agent version", { encoding: "utf8" }).trim();
1055
+ }
1056
+ catch (err) {
1057
+ npmVersion = `error: ${err.message.split("\n")[0]}`;
1058
+ }
1059
+ try {
1060
+ const home = process.env.HOME ?? "~";
1061
+ const cacheOut = execSync(`ls "${home}/.npm/_npx/" 2>/dev/null | head -5`, { encoding: "utf8", shell: "/bin/sh" }).trim();
1062
+ cacheEntries = cacheOut || "(empty)";
1063
+ }
1064
+ catch {
1065
+ cacheEntries = "(empty or not found)";
1066
+ }
1067
+ await this.replyToChat(chatId, `cc-agent npm version: ${npmVersion}\n\nnpx cache (~/.npm/_npx/):\n${cacheEntries}`, threadId);
1068
+ }
1069
+ async handleClearNpxCache(chatId, threadId) {
1070
+ const home = process.env.HOME ?? "/tmp";
1071
+ const cleared = [];
1072
+ const failed = [];
1073
+ // Clear both npx execution cache and full npm package cache
1074
+ for (const dir of [`${home}/.npm/_npx`, `${home}/.npm/cache`]) {
1075
+ try {
1076
+ execSync(`rm -rf "${dir}"`, { encoding: "utf8", shell: "/bin/sh" });
1077
+ cleared.push(dir.replace(home, "~"));
1078
+ console.log(`[cache] cleared ${dir}`);
1079
+ }
1080
+ catch (err) {
1081
+ failed.push(dir.replace(home, "~"));
1082
+ console.warn(`[cache] failed to clear ${dir}:`, err.message);
1083
+ }
1084
+ }
1085
+ const pids = this.killCcAgent();
1086
+ const pidNote = pids.length > 0
1087
+ ? ` Sent SIGTERM to cc-agent pid${pids.length > 1 ? "s" : ""}: ${pids.join(", ")}.`
1088
+ : " No cc-agent running.";
1089
+ const clearNote = failed.length
1090
+ ? `Cleared: ${cleared.join(", ")}. Failed: ${failed.join(", ")}.`
1091
+ : `Cleared: ${cleared.join(", ")}.`;
1092
+ await this.replyToChat(chatId, `${clearNote}${pidNote} Next call picks up latest npm version.`, threadId);
1093
+ }
1094
+ async handleRestart(chatId, threadId) {
1095
+ await this.replyToChat(chatId, "Clearing cache and restarting... brb.", threadId);
1096
+ await new Promise(resolve => setTimeout(resolve, 300));
1097
+ // Clear npm caches before restart so launchd brings up fresh version
1098
+ const home = process.env.HOME ?? "/tmp";
1099
+ for (const dir of [`${home}/.npm/_npx`, `${home}/.npm/cache`]) {
1100
+ try {
1101
+ execSync(`rm -rf "${dir}"`, { shell: "/bin/sh" });
1102
+ }
1103
+ catch { }
1104
+ }
1105
+ // Kill all active Claude sessions cleanly
1106
+ for (const session of this.sessions.values()) {
1107
+ this.stopTyping(session);
1108
+ session.claude.kill();
1109
+ }
1110
+ this.sessions.clear();
1111
+ await new Promise(resolve => setTimeout(resolve, 200));
1112
+ process.exit(0);
1113
+ }
1114
+ async handleCron(chatId, text, threadId) {
1115
+ const args = text.slice("/cron".length).trim();
1116
+ if (args === "list" || args === "") {
1117
+ const jobs = this.cron.list(chatId);
1118
+ if (!jobs.length) {
1119
+ await this.replyToChat(chatId, "No cron jobs.", threadId);
1120
+ return;
1121
+ }
1122
+ const lines = jobs.map((j, i) => {
1123
+ const short = j.prompt.length > 50 ? j.prompt.slice(0, 50) + "…" : j.prompt;
1124
+ return `#${i + 1} ${j.schedule} — "${short}"`;
1125
+ });
1126
+ await this.replyToChat(chatId, `Cron jobs (${jobs.length}):\n${lines.join("\n")}`, threadId);
1127
+ return;
1128
+ }
1129
+ if (args === "clear") {
1130
+ const n = this.cron.clearAll(chatId);
1131
+ await this.replyToChat(chatId, `Cleared ${n} cron job(s).`, threadId);
1132
+ return;
1133
+ }
1134
+ if (args.startsWith("remove ")) {
1135
+ const id = args.slice("remove ".length).trim();
1136
+ const ok = this.cron.remove(chatId, id);
1137
+ await this.replyToChat(chatId, ok ? `Removed ${id}.` : `Not found: ${id}`, threadId);
1138
+ return;
1139
+ }
1140
+ const scheduleMatch = args.match(/^(every\s+\d+[mhd])\s+(.+)$/i);
1141
+ if (!scheduleMatch) {
1142
+ await this.replyToChat(chatId, "Usage:\n/cron every 1h <prompt>\n/cron list\n/cron remove <id>\n/cron clear", threadId);
1143
+ return;
1144
+ }
1145
+ const schedule = scheduleMatch[1];
1146
+ const prompt = scheduleMatch[2];
1147
+ const job = this.cron.add(chatId, schedule, prompt);
1148
+ if (!job) {
1149
+ await this.replyToChat(chatId, "Invalid schedule. Use: every 30m / every 2h / every 1d", threadId);
1150
+ return;
1151
+ }
1152
+ await this.replyToChat(chatId, `Cron set [${job.id}]: ${schedule} — "${prompt}"`, threadId);
1153
+ }
1154
+ runCronTask(chatId, prompt, done = () => { }) {
1155
+ const cronProcess = new ClaudeProcess({ cwd: this.opts.cwd ?? process.cwd() });
1156
+ cronProcess.sendPrompt(prompt);
1157
+ cronProcess.on("message", (msg) => {
1158
+ const result = extractText(msg);
1159
+ if (result) {
1160
+ const formatted = formatForTelegram(`🕐 ${result}`);
1161
+ const chunks = splitLongMessage(formatted);
1162
+ for (const chunk of chunks) {
1163
+ this.replyToChat(chatId, chunk).catch((err) => console.error("[cron] send failed:", err.message));
1164
+ }
1165
+ }
1166
+ });
1167
+ cronProcess.on("exit", () => done());
1168
+ }
1169
+ async handleGetFile(chatId, text, threadId) {
1170
+ const arg = text.slice("/get_file".length).trim();
1171
+ if (!arg) {
1172
+ await this.replyToChat(chatId, "Usage: /get_file <path>", threadId);
1173
+ return;
1174
+ }
1175
+ const filePath = resolve(arg);
1176
+ const safeDirs = ["/tmp/", "/var/folders/", os.homedir() + "/Downloads/", this.opts.cwd ?? process.cwd()];
1177
+ const inSafeDir = safeDirs.some(d => filePath.startsWith(d));
1178
+ if (!inSafeDir) {
1179
+ await this.replyToChat(chatId, "Access denied: path not in allowed directories", threadId);
1180
+ return;
1181
+ }
1182
+ if (!existsSync(filePath)) {
1183
+ await this.replyToChat(chatId, `File not found: ${filePath}`, threadId);
1184
+ return;
1185
+ }
1186
+ if (!statSync(filePath).isFile()) {
1187
+ await this.replyToChat(chatId, `Not a file: ${filePath}`, threadId);
1188
+ return;
1189
+ }
1190
+ if (this.isSensitiveFile(filePath)) {
1191
+ await this.replyToChat(chatId, "Access denied: sensitive file", threadId);
1192
+ return;
1193
+ }
1194
+ const MAX_TG_FILE_BYTES = 50 * 1024 * 1024;
1195
+ const fileSize = statSync(filePath).size;
1196
+ if (fileSize > MAX_TG_FILE_BYTES) {
1197
+ const mb = (fileSize / (1024 * 1024)).toFixed(1);
1198
+ await this.replyToChat(chatId, `File too large for Telegram (${mb}mb). Find it at: ${filePath}`, threadId);
1199
+ return;
1200
+ }
1201
+ const docOpts = threadId ? { message_thread_id: threadId } : undefined;
1202
+ await this.bot.sendDocument(chatId, filePath, docOpts);
1203
+ }
1204
+ callCcAgentTool(toolName, args = {}) {
1205
+ return new Promise((resolve) => {
1206
+ let settled = false;
1207
+ const done = (val) => {
1208
+ if (!settled) {
1209
+ settled = true;
1210
+ resolve(val);
1211
+ }
1212
+ };
1213
+ let proc;
1214
+ try {
1215
+ proc = spawn("npx", ["-y", "@gonzih/cc-agent@latest"], {
1216
+ env: { ...process.env },
1217
+ stdio: ["pipe", "pipe", "pipe"],
1218
+ });
1219
+ }
1220
+ catch (err) {
1221
+ console.error("[mcp] failed to spawn cc-agent:", err.message);
1222
+ done(null);
1223
+ return;
1224
+ }
1225
+ const timeout = setTimeout(() => {
1226
+ console.warn("[mcp] cc-agent tool call timed out");
1227
+ proc.kill();
1228
+ done(null);
1229
+ }, 30_000);
1230
+ let buffer = "";
1231
+ const sendMsg = (msg) => { proc.stdin.write(JSON.stringify(msg) + "\n"); };
1232
+ sendMsg({
1233
+ jsonrpc: "2.0", id: 1, method: "initialize",
1234
+ params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "cc-tg", version: "1.0.0" } },
1235
+ });
1236
+ proc.stdout.on("data", (chunk) => {
1237
+ buffer += chunk.toString();
1238
+ const lines = buffer.split("\n");
1239
+ buffer = lines.pop() ?? "";
1240
+ for (const line of lines) {
1241
+ if (!line.trim())
1242
+ continue;
1243
+ try {
1244
+ const msg = JSON.parse(line);
1245
+ if (msg.id === 1 && "result" in msg) {
1246
+ sendMsg({ jsonrpc: "2.0", method: "notifications/initialized" });
1247
+ sendMsg({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: toolName, arguments: args } });
1248
+ }
1249
+ else if (msg.id === 2) {
1250
+ clearTimeout(timeout);
1251
+ if (msg.error) {
1252
+ console.error("[mcp] cost_summary error:", JSON.stringify(msg.error));
1253
+ proc.kill();
1254
+ done(null);
1255
+ return;
1256
+ }
1257
+ const result = msg.result;
1258
+ const content = result?.content;
1259
+ const text = (content ?? []).filter((b) => b.type === "text").map((b) => b.text).join("");
1260
+ proc.kill();
1261
+ done(text || null);
1262
+ }
1263
+ }
1264
+ catch { /* ignore non-JSON lines */ }
1265
+ }
1266
+ });
1267
+ proc.on("error", (err) => {
1268
+ console.error("[mcp] cc-agent spawn error:", err.message);
1269
+ clearTimeout(timeout);
1270
+ done(null);
1271
+ });
1272
+ proc.on("exit", () => { clearTimeout(timeout); done(null); });
1273
+ });
1274
+ }
1275
+ killSession(chatId, _keepCrons = true, threadId) {
1276
+ const key = this.sessionKey(chatId, threadId);
1277
+ const session = this.sessions.get(key);
1278
+ if (session) {
1279
+ this.stopTyping(session);
1280
+ session.claude.kill();
1281
+ this.sessions.delete(key);
1282
+ }
1283
+ }
1284
+ getMe() {
1285
+ return this.bot.getMe();
1286
+ }
1287
+ stop() {
1288
+ this.bot.stopPolling();
1289
+ for (const session of this.sessions.values()) {
1290
+ this.stopTyping(session);
1291
+ session.claude.kill();
1292
+ }
1293
+ this.sessions.clear();
1294
+ }
1295
+ }
1296
+ function buildPromptWithReplyContext(text, msg) {
1297
+ const reply = msg.reply_to_message;
1298
+ if (!reply)
1299
+ return text;
1300
+ const quotedText = reply.text || reply.caption || null;
1301
+ if (!quotedText)
1302
+ return text;
1303
+ const truncated = quotedText.length > 500
1304
+ ? quotedText.slice(0, 500) + "... [truncated]"
1305
+ : quotedText;
1306
+ return `[Replying to: "${truncated}"]\n\n${text}`;
1307
+ }
1308
+ /** Download a URL and return its contents as a base64 string */
1309
+ function fetchAsBase64(url) {
1310
+ return new Promise((resolve, reject) => {
1311
+ const client = url.startsWith("https") ? https : http;
1312
+ client.get(url, (res) => {
1313
+ const chunks = [];
1314
+ res.on("data", (chunk) => chunks.push(chunk));
1315
+ res.on("end", () => resolve(Buffer.concat(chunks).toString("base64")));
1316
+ res.on("error", reject);
1317
+ }).on("error", reject);
1318
+ });
1319
+ }
1320
+ /** Download a URL to a local file path */
1321
+ function downloadToFile(url, destPath) {
1322
+ return new Promise((resolve, reject) => {
1323
+ const client = url.startsWith("https") ? https : http;
1324
+ const file = createWriteStream(destPath);
1325
+ client.get(url, (res) => {
1326
+ res.pipe(file);
1327
+ file.on("finish", () => file.close(() => resolve()));
1328
+ file.on("error", reject);
1329
+ }).on("error", reject);
1330
+ });
1331
+ }
1332
+ /** Fetch URL via Jina Reader and return first maxChars characters */
1333
+ function fetchUrlViaJina(url, maxChars = 2000) {
1334
+ const jinaUrl = `https://r.jina.ai/${url}`;
1335
+ return new Promise((resolve, reject) => {
1336
+ https.get(jinaUrl, (res) => {
1337
+ const chunks = [];
1338
+ res.on("data", (chunk) => chunks.push(chunk));
1339
+ res.on("end", () => {
1340
+ const text = Buffer.concat(chunks).toString("utf8");
1341
+ resolve(text.slice(0, maxChars));
1342
+ });
1343
+ res.on("error", reject);
1344
+ }).on("error", reject);
1345
+ });
1346
+ }
1347
+ /** Detect URLs in text, fetch each via Jina Reader, and prepend content to the prompt */
1348
+ export async function enrichPromptWithUrls(text) {
1349
+ const urlRegex = /https?:\/\/[^\s]+/g;
1350
+ const urls = text.match(urlRegex);
1351
+ if (!urls || urls.length === 0)
1352
+ return text;
1353
+ const prefixes = [];
1354
+ for (const url of urls) {
1355
+ // Skip jina.ai URLs to avoid recursion
1356
+ if (url.includes("r.jina.ai"))
1357
+ continue;
1358
+ try {
1359
+ const content = await fetchUrlViaJina(url);
1360
+ if (content.trim()) {
1361
+ prefixes.push(`[Web content from ${url}]:\n${content}`);
1362
+ }
1363
+ }
1364
+ catch (err) {
1365
+ console.warn(`[url-fetch] failed to fetch ${url}:`, err.message);
1366
+ }
1367
+ }
1368
+ if (prefixes.length === 0)
1369
+ return text;
1370
+ return prefixes.join("\n\n") + "\n\n" + text;
1371
+ }
1372
+ /** Parse frontmatter description from a skill markdown file */
1373
+ function parseSkillDescription(content) {
1374
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
1375
+ if (!match)
1376
+ return null;
1377
+ const frontmatter = match[1];
1378
+ const descMatch = frontmatter.match(/^description:\s*(.+)$/m);
1379
+ return descMatch ? descMatch[1].trim() : null;
1380
+ }
1381
+ /** List available skills from ~/.claude/skills/ */
1382
+ export function listSkills() {
1383
+ const skillsDir = join(os.homedir(), ".claude", "skills");
1384
+ if (!existsSync(skillsDir)) {
1385
+ return "No skills directory found at ~/.claude/skills/";
1386
+ }
1387
+ let files;
1388
+ try {
1389
+ files = readdirSync(skillsDir).filter((f) => f.endsWith(".md"));
1390
+ }
1391
+ catch {
1392
+ return "Could not read skills directory.";
1393
+ }
1394
+ if (files.length === 0) {
1395
+ return "No skills found in ~/.claude/skills/";
1396
+ }
1397
+ const lines = ["Available skills:"];
1398
+ for (const file of files.sort()) {
1399
+ const name = "/" + file.replace(/\.md$/, "");
1400
+ try {
1401
+ const content = readFileSync(join(skillsDir, file), "utf8");
1402
+ const description = parseSkillDescription(content);
1403
+ lines.push(description ? `${name} — ${description}` : name);
1404
+ }
1405
+ catch {
1406
+ lines.push(name);
1407
+ }
1408
+ }
1409
+ return lines.join("\n");
1410
+ }
1411
+ export function splitMessage(text, maxLen = 4096) {
1412
+ if (text.length <= maxLen)
1413
+ return [text];
1414
+ const chunks = [];
1415
+ let i = 0;
1416
+ while (i < text.length) {
1417
+ chunks.push(text.slice(i, i + maxLen));
1418
+ i += maxLen;
1419
+ }
1420
+ return chunks;
1421
+ }