@gonzih/cc-tg 0.8.0 → 0.8.2

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