@gonzih/cc-tg 0.9.8 → 0.9.10

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