@gonzih/cc-tg 0.4.0 → 0.4.1

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