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