@gonzih/cc-tg 0.7.2 → 0.7.3

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