@gonzih/cc-tg 0.9.29 → 0.9.30

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