@gonzih/cc-tg 0.9.2 → 0.9.4
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/dist/bot.d.ts +31 -4
- package/dist/bot.js +335 -312
- package/dist/formatter.d.ts +14 -12
- package/dist/formatter.js +72 -36
- package/dist/index.js +62 -3
- package/dist/notifier.d.ts +37 -0
- package/dist/notifier.js +124 -0
- package/dist/tokens.d.ts +22 -0
- package/dist/tokens.js +56 -0
- package/package.json +6 -5
- package/dist/cron.d.ts +0 -33
- package/dist/cron.js +0 -127
package/dist/formatter.d.ts
CHANGED
|
@@ -1,23 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Telegram
|
|
3
|
-
* Converts standard markdown to Telegram's
|
|
2
|
+
* Telegram HTML post-processor.
|
|
3
|
+
* Converts standard markdown to Telegram's HTML parse mode format.
|
|
4
4
|
*/
|
|
5
5
|
/**
|
|
6
|
-
* Convert standard markdown text to Telegram
|
|
6
|
+
* Convert standard markdown text to Telegram HTML format.
|
|
7
7
|
*
|
|
8
8
|
* Processing order:
|
|
9
|
-
* 1. Extract code blocks (
|
|
10
|
-
* 2.
|
|
11
|
-
* 3.
|
|
12
|
-
* 4. Convert
|
|
13
|
-
* 5. Convert
|
|
14
|
-
* 6. Convert
|
|
15
|
-
* 7.
|
|
16
|
-
* 8.
|
|
9
|
+
* 1. Extract fenced code blocks (``` ... ```) → <pre>, protect from further processing
|
|
10
|
+
* 2. Extract inline code (`...`) → <code>, protect from further processing
|
|
11
|
+
* 3. HTML-escape remaining text: & → & < → < > → >
|
|
12
|
+
* 4. Convert --- → blank line
|
|
13
|
+
* 5. Convert ## headings → <b>Heading</b>
|
|
14
|
+
* 6. Convert **bold** → <b>bold</b>
|
|
15
|
+
* 7. Convert - item / * item → • item
|
|
16
|
+
* 8. Convert *bold* → <b>bold</b>
|
|
17
|
+
* 9. Convert _italic_ → <i>italic</i>
|
|
18
|
+
* 10. Reinsert code blocks
|
|
17
19
|
*/
|
|
18
20
|
export declare function formatForTelegram(text: string): string;
|
|
19
21
|
/**
|
|
20
22
|
* Split a long message at natural boundaries (paragraph > line > word).
|
|
21
|
-
* Never splits mid-word. Chunks are at most maxLen characters.
|
|
23
|
+
* Never splits mid-word or inside <pre> blocks. Chunks are at most maxLen characters.
|
|
22
24
|
*/
|
|
23
25
|
export declare function splitLongMessage(text: string, maxLen?: number): string[];
|
package/dist/formatter.js
CHANGED
|
@@ -1,54 +1,82 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Telegram
|
|
3
|
-
* Converts standard markdown to Telegram's
|
|
2
|
+
* Telegram HTML post-processor.
|
|
3
|
+
* Converts standard markdown to Telegram's HTML parse mode format.
|
|
4
4
|
*/
|
|
5
|
+
function htmlEscape(text) {
|
|
6
|
+
return text
|
|
7
|
+
.replace(/&/g, "&")
|
|
8
|
+
.replace(/</g, "<")
|
|
9
|
+
.replace(/>/g, ">");
|
|
10
|
+
}
|
|
5
11
|
/**
|
|
6
|
-
* Convert standard markdown text to Telegram
|
|
12
|
+
* Convert standard markdown text to Telegram HTML format.
|
|
7
13
|
*
|
|
8
14
|
* Processing order:
|
|
9
|
-
* 1. Extract code blocks (
|
|
10
|
-
* 2.
|
|
11
|
-
* 3.
|
|
12
|
-
* 4. Convert
|
|
13
|
-
* 5. Convert
|
|
14
|
-
* 6. Convert
|
|
15
|
-
* 7.
|
|
16
|
-
* 8.
|
|
15
|
+
* 1. Extract fenced code blocks (``` ... ```) → <pre>, protect from further processing
|
|
16
|
+
* 2. Extract inline code (`...`) → <code>, protect from further processing
|
|
17
|
+
* 3. HTML-escape remaining text: & → & < → < > → >
|
|
18
|
+
* 4. Convert --- → blank line
|
|
19
|
+
* 5. Convert ## headings → <b>Heading</b>
|
|
20
|
+
* 6. Convert **bold** → <b>bold</b>
|
|
21
|
+
* 7. Convert - item / * item → • item
|
|
22
|
+
* 8. Convert *bold* → <b>bold</b>
|
|
23
|
+
* 9. Convert _italic_ → <i>italic</i>
|
|
24
|
+
* 10. Reinsert code blocks
|
|
17
25
|
*/
|
|
18
26
|
export function formatForTelegram(text) {
|
|
19
|
-
// Step 1: Extract code blocks and inline code to protect them
|
|
20
27
|
const placeholders = [];
|
|
21
|
-
//
|
|
22
|
-
let out = text.replace(/```[\s\S]
|
|
23
|
-
placeholders.push(
|
|
28
|
+
// Step 1: Extract fenced code blocks (``` ... ```) → <pre>
|
|
29
|
+
let out = text.replace(/```(?:\w*)\n?([\s\S]*?)```/g, (_, content) => {
|
|
30
|
+
placeholders.push(`<pre>${htmlEscape(content)}</pre>`);
|
|
24
31
|
return `\x00P${placeholders.length - 1}\x00`;
|
|
25
32
|
});
|
|
26
|
-
//
|
|
27
|
-
out = out.replace(/`[^`\n]
|
|
28
|
-
placeholders.push(
|
|
33
|
+
// Step 2: Extract inline code (`...`) → <code>
|
|
34
|
+
out = out.replace(/`([^`\n]+)`/g, (_, content) => {
|
|
35
|
+
placeholders.push(`<code>${htmlEscape(content)}</code>`);
|
|
29
36
|
return `\x00P${placeholders.length - 1}\x00`;
|
|
30
37
|
});
|
|
31
|
-
// Step
|
|
32
|
-
out = out
|
|
33
|
-
// Step
|
|
38
|
+
// Step 3: HTML-escape remaining text
|
|
39
|
+
out = htmlEscape(out);
|
|
40
|
+
// Step 4: Convert --- → blank line
|
|
34
41
|
out = out.replace(/^-{3,}$/gm, "");
|
|
35
|
-
// Step
|
|
36
|
-
out = out.replace(/^#{1,6}\s+(.+)$/gm, "
|
|
37
|
-
// Step
|
|
38
|
-
out = out.replace(/\*\*(.+?)\*\*/gs, "
|
|
39
|
-
// Step
|
|
42
|
+
// Step 5: Convert ## headings → <b>Heading</b>
|
|
43
|
+
out = out.replace(/^#{1,6}\s+(.+)$/gm, "<b>$1</b>");
|
|
44
|
+
// Step 6: Convert **bold** → <b>bold</b>
|
|
45
|
+
out = out.replace(/\*\*(.+?)\*\*/gs, "<b>$1</b>");
|
|
46
|
+
// Step 7: Convert - item / * item → • item
|
|
40
47
|
out = out.replace(/^[ \t]*[-*]\s+(.+)$/gm, "• $1");
|
|
41
|
-
// Step
|
|
42
|
-
|
|
43
|
-
//
|
|
44
|
-
|
|
45
|
-
|
|
48
|
+
// Step 8: Convert *bold* → <b>bold</b> (single asterisk, after bullets handled)
|
|
49
|
+
out = out.replace(/\*([^*\n]+)\*/g, "<b>$1</b>");
|
|
50
|
+
// Step 9: Convert _italic_ → <i>italic</i>
|
|
51
|
+
// Use word-boundary guards to avoid mangling snake_case identifiers
|
|
52
|
+
out = out.replace(/(?<![a-zA-Z0-9])_([^_\n]+?)_(?![a-zA-Z0-9])/g, "<i>$1</i>");
|
|
53
|
+
// Step 10: Reinsert code blocks
|
|
46
54
|
out = out.replace(/\x00P(\d+)\x00/g, (_, i) => placeholders[parseInt(i, 10)]);
|
|
47
55
|
return out;
|
|
48
56
|
}
|
|
57
|
+
function findPreRanges(text) {
|
|
58
|
+
const ranges = [];
|
|
59
|
+
const open = "<pre>";
|
|
60
|
+
const close = "</pre>";
|
|
61
|
+
let i = 0;
|
|
62
|
+
while (i < text.length) {
|
|
63
|
+
const start = text.indexOf(open, i);
|
|
64
|
+
if (start === -1)
|
|
65
|
+
break;
|
|
66
|
+
const end = text.indexOf(close, start);
|
|
67
|
+
if (end === -1)
|
|
68
|
+
break;
|
|
69
|
+
ranges.push([start, end + close.length]);
|
|
70
|
+
i = end + close.length;
|
|
71
|
+
}
|
|
72
|
+
return ranges;
|
|
73
|
+
}
|
|
74
|
+
function isInsidePre(pos, ranges) {
|
|
75
|
+
return ranges.some(([start, end]) => pos > start && pos < end);
|
|
76
|
+
}
|
|
49
77
|
/**
|
|
50
78
|
* Split a long message at natural boundaries (paragraph > line > word).
|
|
51
|
-
* Never splits mid-word. Chunks are at most maxLen characters.
|
|
79
|
+
* Never splits mid-word or inside <pre> blocks. Chunks are at most maxLen characters.
|
|
52
80
|
*/
|
|
53
81
|
export function splitLongMessage(text, maxLen = 4096) {
|
|
54
82
|
if (text.length <= maxLen)
|
|
@@ -57,6 +85,7 @@ export function splitLongMessage(text, maxLen = 4096) {
|
|
|
57
85
|
let remaining = text;
|
|
58
86
|
while (remaining.length > maxLen) {
|
|
59
87
|
const slice = remaining.slice(0, maxLen);
|
|
88
|
+
const preRanges = findPreRanges(remaining);
|
|
60
89
|
// Prefer paragraph boundary (\n\n)
|
|
61
90
|
const lastPara = slice.lastIndexOf("\n\n");
|
|
62
91
|
// Then line boundary (\n)
|
|
@@ -64,17 +93,24 @@ export function splitLongMessage(text, maxLen = 4096) {
|
|
|
64
93
|
// Then word boundary (space)
|
|
65
94
|
const lastSpace = slice.lastIndexOf(" ");
|
|
66
95
|
let splitAt;
|
|
67
|
-
if (lastPara > 0) {
|
|
96
|
+
if (lastPara > 0 && !isInsidePre(lastPara, preRanges)) {
|
|
68
97
|
splitAt = lastPara + 2;
|
|
69
98
|
}
|
|
70
|
-
else if (lastLine > 0) {
|
|
99
|
+
else if (lastLine > 0 && !isInsidePre(lastLine, preRanges)) {
|
|
71
100
|
splitAt = lastLine + 1;
|
|
72
101
|
}
|
|
73
|
-
else if (lastSpace > 0) {
|
|
102
|
+
else if (lastSpace > 0 && !isInsidePre(lastSpace, preRanges)) {
|
|
74
103
|
splitAt = lastSpace + 1;
|
|
75
104
|
}
|
|
76
105
|
else {
|
|
77
|
-
|
|
106
|
+
// If all candidate split points are inside a <pre> block, split after it
|
|
107
|
+
const coveringPre = preRanges.find(([start, end]) => start < maxLen && end > maxLen);
|
|
108
|
+
if (coveringPre) {
|
|
109
|
+
splitAt = coveringPre[1];
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
splitAt = maxLen;
|
|
113
|
+
}
|
|
78
114
|
}
|
|
79
115
|
chunks.push(remaining.slice(0, splitAt).trimEnd());
|
|
80
116
|
remaining = remaining.slice(splitAt).trimStart();
|
package/dist/index.js
CHANGED
|
@@ -15,11 +15,23 @@
|
|
|
15
15
|
* CWD — working directory for Claude Code (default: process.cwd())
|
|
16
16
|
*/
|
|
17
17
|
import { createServer, createConnection } from "net";
|
|
18
|
-
import { unlinkSync } from "fs";
|
|
18
|
+
import { unlinkSync, readFileSync } from "fs";
|
|
19
19
|
import { tmpdir } from "os";
|
|
20
|
-
import
|
|
20
|
+
import os from "os";
|
|
21
|
+
import { join, dirname } from "path";
|
|
22
|
+
import { fileURLToPath } from "url";
|
|
23
|
+
import TelegramBot from "node-telegram-bot-api";
|
|
21
24
|
import { CcTgBot } from "./bot.js";
|
|
22
|
-
|
|
25
|
+
import { loadTokens } from "./tokens.js";
|
|
26
|
+
import { Registry, startControlServer } from "@gonzih/agent-ops";
|
|
27
|
+
import { Redis } from "ioredis";
|
|
28
|
+
import { startNotifier } from "./notifier.js";
|
|
29
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
30
|
+
const __dirname = dirname(__filename);
|
|
31
|
+
const pkg = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8"));
|
|
32
|
+
// Make lock socket unique per bot token so multiple users on the same machine don't collide
|
|
33
|
+
const _tokenHash = Buffer.from(process.env.TELEGRAM_BOT_TOKEN ?? "default").toString("base64").replace(/[^a-z0-9]/gi, "").slice(0, 16);
|
|
34
|
+
const LOCK_SOCKET = join(tmpdir(), `cc-tg-${_tokenHash}.sock`);
|
|
23
35
|
function acquireLock() {
|
|
24
36
|
return new Promise((resolve) => {
|
|
25
37
|
const server = createServer();
|
|
@@ -89,6 +101,11 @@ Set one and run again:
|
|
|
89
101
|
`);
|
|
90
102
|
process.exit(1);
|
|
91
103
|
}
|
|
104
|
+
// Load OAuth token pool (supports CLAUDE_CODE_OAUTH_TOKENS for multi-account rotation)
|
|
105
|
+
const tokenPool = loadTokens();
|
|
106
|
+
if (tokenPool.length > 1) {
|
|
107
|
+
console.log(`[cc-tg] Token pool loaded: ${tokenPool.length} tokens — will rotate on usage limit`);
|
|
108
|
+
}
|
|
92
109
|
const allowedUserIds = process.env.ALLOWED_USER_IDS
|
|
93
110
|
? process.env.ALLOWED_USER_IDS.split(",").map((s) => parseInt(s.trim(), 10)).filter(Boolean)
|
|
94
111
|
: [];
|
|
@@ -96,13 +113,55 @@ const groupChatIds = process.env.GROUP_CHAT_IDS
|
|
|
96
113
|
? process.env.GROUP_CHAT_IDS.split(",").map((s) => parseInt(s.trim(), 10)).filter(Boolean)
|
|
97
114
|
: [];
|
|
98
115
|
const cwd = process.env.CWD ?? process.cwd();
|
|
116
|
+
// agent-ops / chat bridge — Redis is always initialized so the chat bridge works
|
|
117
|
+
// regardless of whether CC_AGENT_OPS_PORT or CC_AGENT_NOTIFY_CHAT_ID are set.
|
|
118
|
+
const redisUrl = process.env.REDIS_URL || "redis://localhost:6379";
|
|
119
|
+
const namespace = process.env.CC_AGENT_NAMESPACE || "default";
|
|
120
|
+
const sharedRedis = new Redis(redisUrl);
|
|
121
|
+
sharedRedis.on("error", (err) => {
|
|
122
|
+
// Non-fatal — Redis features (chat bridge, ops) degrade gracefully
|
|
123
|
+
console.warn("[redis] connection error:", err.message);
|
|
124
|
+
});
|
|
99
125
|
const bot = new CcTgBot({
|
|
100
126
|
telegramToken,
|
|
101
127
|
claudeToken,
|
|
102
128
|
cwd,
|
|
103
129
|
allowedUserIds,
|
|
104
130
|
groupChatIds,
|
|
131
|
+
redis: sharedRedis,
|
|
132
|
+
namespace,
|
|
105
133
|
});
|
|
134
|
+
if (process.env.CC_AGENT_OPS_PORT) {
|
|
135
|
+
const botInfo = await bot.getMe();
|
|
136
|
+
const registry = new Registry(sharedRedis);
|
|
137
|
+
await registry.register({
|
|
138
|
+
namespace,
|
|
139
|
+
hostname: os.hostname(),
|
|
140
|
+
user: os.userInfo().username,
|
|
141
|
+
pid: String(process.pid),
|
|
142
|
+
version: pkg.version,
|
|
143
|
+
cwd: process.env.CWD || process.cwd(),
|
|
144
|
+
control_port: process.env.CC_AGENT_OPS_PORT,
|
|
145
|
+
bot_username: botInfo.username ?? "",
|
|
146
|
+
started_at: new Date().toISOString(),
|
|
147
|
+
});
|
|
148
|
+
setInterval(() => registry.heartbeat(namespace), 60_000);
|
|
149
|
+
startControlServer(Number(process.env.CC_AGENT_OPS_PORT), {
|
|
150
|
+
namespace,
|
|
151
|
+
version: pkg.version,
|
|
152
|
+
logFile: process.env.CC_AGENT_LOG_FILE || process.env.LOG_FILE,
|
|
153
|
+
});
|
|
154
|
+
console.log(`[ops] control server on port ${process.env.CC_AGENT_OPS_PORT}`);
|
|
155
|
+
}
|
|
156
|
+
// Notifier — always subscribe to cca:notify and cca:chat:incoming channels.
|
|
157
|
+
// CC_AGENT_NOTIFY_CHAT_ID pins a fixed Telegram chatId; without it the last
|
|
158
|
+
// active chatId is used dynamically for the chat bridge.
|
|
159
|
+
const notifyChatId = process.env.CC_AGENT_NOTIFY_CHAT_ID
|
|
160
|
+
? Number(process.env.CC_AGENT_NOTIFY_CHAT_ID)
|
|
161
|
+
: null;
|
|
162
|
+
const notifierBot = new TelegramBot(telegramToken, { polling: false });
|
|
163
|
+
startNotifier(notifierBot, notifyChatId, namespace, sharedRedis, (cid, text) => bot.handleUserMessage(cid, text), () => bot.getLastActiveChatId());
|
|
164
|
+
console.log(`[notifier] started for namespace=${namespace} chatId=${notifyChatId ?? "dynamic"}`);
|
|
106
165
|
process.on("SIGINT", () => {
|
|
107
166
|
console.log("\nShutting down...");
|
|
108
167
|
bot.stop();
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notifier — subscribes to Redis pub/sub channels and bridges messages to Telegram.
|
|
3
|
+
*
|
|
4
|
+
* Channels:
|
|
5
|
+
* cca:notify:{namespace} — job completion notifications from cc-agent → forward to Telegram
|
|
6
|
+
* cca:chat:incoming:{namespace} — messages from the web UI → echo to Telegram + feed into Claude session
|
|
7
|
+
*
|
|
8
|
+
* All messages (Telegram incoming, Claude responses) are also written to:
|
|
9
|
+
* cca:chat:log:{namespace} — LPUSH + LTRIM 0 499 (last 500 messages)
|
|
10
|
+
* cca:chat:outgoing:{namespace} — PUBLISH for web UI to consume
|
|
11
|
+
*/
|
|
12
|
+
import { Redis } from "ioredis";
|
|
13
|
+
import TelegramBot from "node-telegram-bot-api";
|
|
14
|
+
export interface ChatMessage {
|
|
15
|
+
id: string;
|
|
16
|
+
source: "telegram" | "ui" | "claude" | "cc-tg";
|
|
17
|
+
role: "user" | "assistant" | "tool";
|
|
18
|
+
content: string;
|
|
19
|
+
timestamp: string;
|
|
20
|
+
chatId: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Write a message to the chat log in Redis.
|
|
24
|
+
* Fire-and-forget — errors are logged but not thrown.
|
|
25
|
+
*/
|
|
26
|
+
export declare function writeChatLog(redis: Redis, namespace: string, msg: ChatMessage): void;
|
|
27
|
+
/**
|
|
28
|
+
* Start the notifier.
|
|
29
|
+
*
|
|
30
|
+
* @param bot - Telegram bot instance (for sending messages)
|
|
31
|
+
* @param chatId - Telegram chat ID to forward notifications to. Pass null to use getActiveChatId.
|
|
32
|
+
* @param namespace - cc-agent namespace (used to build Redis channel names)
|
|
33
|
+
* @param redis - ioredis client in normal mode (will be duplicated for pub/sub)
|
|
34
|
+
* @param handleUserMessage - Optional callback to feed UI messages into the active Claude session
|
|
35
|
+
* @param getActiveChatId - Optional callback to resolve chatId dynamically (used when chatId is null)
|
|
36
|
+
*/
|
|
37
|
+
export declare function startNotifier(bot: TelegramBot, chatId: number | null, namespace: string, redis: Redis, handleUserMessage?: (chatId: number, text: string) => void, getActiveChatId?: () => number | undefined): void;
|
package/dist/notifier.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notifier — subscribes to Redis pub/sub channels and bridges messages to Telegram.
|
|
3
|
+
*
|
|
4
|
+
* Channels:
|
|
5
|
+
* cca:notify:{namespace} — job completion notifications from cc-agent → forward to Telegram
|
|
6
|
+
* cca:chat:incoming:{namespace} — messages from the web UI → echo to Telegram + feed into Claude session
|
|
7
|
+
*
|
|
8
|
+
* All messages (Telegram incoming, Claude responses) are also written to:
|
|
9
|
+
* cca:chat:log:{namespace} — LPUSH + LTRIM 0 499 (last 500 messages)
|
|
10
|
+
* cca:chat:outgoing:{namespace} — PUBLISH for web UI to consume
|
|
11
|
+
*/
|
|
12
|
+
function log(level, ...args) {
|
|
13
|
+
const fn = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
|
|
14
|
+
fn("[notifier]", ...args);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Write a message to the chat log in Redis.
|
|
18
|
+
* Fire-and-forget — errors are logged but not thrown.
|
|
19
|
+
*/
|
|
20
|
+
export function writeChatLog(redis, namespace, msg) {
|
|
21
|
+
const logKey = `cca:chat:log:${namespace}`;
|
|
22
|
+
const outKey = `cca:chat:outgoing:${namespace}`;
|
|
23
|
+
const payload = JSON.stringify(msg);
|
|
24
|
+
redis.lpush(logKey, payload).catch((err) => {
|
|
25
|
+
log("warn", "writeChatLog lpush failed:", err.message);
|
|
26
|
+
});
|
|
27
|
+
redis.ltrim(logKey, 0, 499).catch((err) => {
|
|
28
|
+
log("warn", "writeChatLog ltrim failed:", err.message);
|
|
29
|
+
});
|
|
30
|
+
redis.publish(outKey, payload).catch((err) => {
|
|
31
|
+
log("warn", "writeChatLog publish failed:", err.message);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Start the notifier.
|
|
36
|
+
*
|
|
37
|
+
* @param bot - Telegram bot instance (for sending messages)
|
|
38
|
+
* @param chatId - Telegram chat ID to forward notifications to. Pass null to use getActiveChatId.
|
|
39
|
+
* @param namespace - cc-agent namespace (used to build Redis channel names)
|
|
40
|
+
* @param redis - ioredis client in normal mode (will be duplicated for pub/sub)
|
|
41
|
+
* @param handleUserMessage - Optional callback to feed UI messages into the active Claude session
|
|
42
|
+
* @param getActiveChatId - Optional callback to resolve chatId dynamically (used when chatId is null)
|
|
43
|
+
*/
|
|
44
|
+
export function startNotifier(bot, chatId, namespace, redis, handleUserMessage, getActiveChatId) {
|
|
45
|
+
const sub = redis.duplicate({
|
|
46
|
+
retryStrategy: (times) => {
|
|
47
|
+
const delay = Math.min(1000 * Math.pow(2, times - 1), 30_000);
|
|
48
|
+
log("info", `subscriber reconnecting in ${delay}ms (attempt ${times})`);
|
|
49
|
+
return delay;
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
sub.on("error", (err) => {
|
|
53
|
+
log("warn", "subscriber error:", err.message);
|
|
54
|
+
});
|
|
55
|
+
sub.on("close", () => {
|
|
56
|
+
log("info", "subscriber disconnected, will reconnect with backoff");
|
|
57
|
+
});
|
|
58
|
+
// cca:notify:{namespace} — forward job completion notifications to Telegram
|
|
59
|
+
sub.subscribe(`cca:notify:${namespace}`, (err) => {
|
|
60
|
+
if (err) {
|
|
61
|
+
log("error", `subscribe cca:notify:${namespace} failed:`, err.message);
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
log("info", `subscribed to cca:notify:${namespace}`);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
// cca:chat:incoming:{namespace} — messages from UI
|
|
68
|
+
sub.subscribe(`cca:chat:incoming:${namespace}`, (err) => {
|
|
69
|
+
if (err) {
|
|
70
|
+
log("error", `subscribe cca:chat:incoming:${namespace} failed:`, err.message);
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
log("info", `subscribed to cca:chat:incoming:${namespace}`);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
sub.on("message", (channel, message) => {
|
|
77
|
+
const notifyChannel = `cca:notify:${namespace}`;
|
|
78
|
+
const incomingChannel = `cca:chat:incoming:${namespace}`;
|
|
79
|
+
if (channel === notifyChannel) {
|
|
80
|
+
if (chatId !== null) {
|
|
81
|
+
bot.sendMessage(chatId, message).catch((err) => {
|
|
82
|
+
log("warn", "sendMessage failed:", err.message);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (channel === incomingChannel) {
|
|
88
|
+
let content = message;
|
|
89
|
+
try {
|
|
90
|
+
const parsed = JSON.parse(message);
|
|
91
|
+
if (parsed.content)
|
|
92
|
+
content = parsed.content;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// raw string message — use as-is
|
|
96
|
+
}
|
|
97
|
+
// Resolve the target chatId: prefer the fixed chatId, fall back to last active
|
|
98
|
+
const targetChatId = chatId ?? getActiveChatId?.();
|
|
99
|
+
if (targetChatId !== undefined) {
|
|
100
|
+
// Echo to Telegram so the user sees UI messages in the chat
|
|
101
|
+
bot.sendMessage(targetChatId, `📱 [from UI]: ${content}`).catch((err) => {
|
|
102
|
+
log("warn", "sendMessage (UI echo) failed:", err.message);
|
|
103
|
+
});
|
|
104
|
+
// Log the incoming message
|
|
105
|
+
const inMsg = {
|
|
106
|
+
id: `ui-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
107
|
+
source: "ui",
|
|
108
|
+
role: "user",
|
|
109
|
+
content,
|
|
110
|
+
timestamp: new Date().toISOString(),
|
|
111
|
+
chatId: targetChatId,
|
|
112
|
+
};
|
|
113
|
+
writeChatLog(redis, namespace, inMsg);
|
|
114
|
+
// Feed into active Claude session as if user typed it
|
|
115
|
+
if (handleUserMessage) {
|
|
116
|
+
handleUserMessage(targetChatId, content);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
log("warn", "cca:chat:incoming: no active chatId to route message to");
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
}
|
package/dist/tokens.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth token pool management.
|
|
3
|
+
*
|
|
4
|
+
* Supports CLAUDE_CODE_OAUTH_TOKENS (comma-separated list of tokens).
|
|
5
|
+
* Falls back to CLAUDE_CODE_OAUTH_TOKEN for single-token / backwards compat.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Load tokens from env vars. Called on startup; also re-callable in tests.
|
|
9
|
+
* Priority: CLAUDE_CODE_OAUTH_TOKENS > CLAUDE_CODE_OAUTH_TOKEN > (empty)
|
|
10
|
+
*/
|
|
11
|
+
export declare function loadTokens(): string[];
|
|
12
|
+
/** Returns the current active token, or empty string if none configured. */
|
|
13
|
+
export declare function getCurrentToken(): string;
|
|
14
|
+
/**
|
|
15
|
+
* Advance to the next token (wraps around).
|
|
16
|
+
* Returns the new current token.
|
|
17
|
+
*/
|
|
18
|
+
export declare function rotateToken(): string;
|
|
19
|
+
/** Zero-based index of the current token. */
|
|
20
|
+
export declare function getTokenIndex(): number;
|
|
21
|
+
/** Total number of tokens in the pool. */
|
|
22
|
+
export declare function getTokenCount(): number;
|
package/dist/tokens.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth token pool management.
|
|
3
|
+
*
|
|
4
|
+
* Supports CLAUDE_CODE_OAUTH_TOKENS (comma-separated list of tokens).
|
|
5
|
+
* Falls back to CLAUDE_CODE_OAUTH_TOKEN for single-token / backwards compat.
|
|
6
|
+
*/
|
|
7
|
+
let tokens = [];
|
|
8
|
+
let currentIndex = 0;
|
|
9
|
+
let initialized = false;
|
|
10
|
+
/**
|
|
11
|
+
* Load tokens from env vars. Called on startup; also re-callable in tests.
|
|
12
|
+
* Priority: CLAUDE_CODE_OAUTH_TOKENS > CLAUDE_CODE_OAUTH_TOKEN > (empty)
|
|
13
|
+
*/
|
|
14
|
+
export function loadTokens() {
|
|
15
|
+
const multi = process.env.CLAUDE_CODE_OAUTH_TOKENS;
|
|
16
|
+
if (multi) {
|
|
17
|
+
tokens = multi.split(",").map((t) => t.trim()).filter(Boolean);
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
const single = process.env.CLAUDE_CODE_OAUTH_TOKEN;
|
|
21
|
+
tokens = single ? [single] : [];
|
|
22
|
+
}
|
|
23
|
+
currentIndex = 0;
|
|
24
|
+
initialized = true;
|
|
25
|
+
return tokens;
|
|
26
|
+
}
|
|
27
|
+
function ensureInitialized() {
|
|
28
|
+
if (!initialized)
|
|
29
|
+
loadTokens();
|
|
30
|
+
}
|
|
31
|
+
/** Returns the current active token, or empty string if none configured. */
|
|
32
|
+
export function getCurrentToken() {
|
|
33
|
+
ensureInitialized();
|
|
34
|
+
return tokens[currentIndex] ?? "";
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Advance to the next token (wraps around).
|
|
38
|
+
* Returns the new current token.
|
|
39
|
+
*/
|
|
40
|
+
export function rotateToken() {
|
|
41
|
+
ensureInitialized();
|
|
42
|
+
if (tokens.length === 0)
|
|
43
|
+
return "";
|
|
44
|
+
currentIndex = (currentIndex + 1) % tokens.length;
|
|
45
|
+
return tokens[currentIndex];
|
|
46
|
+
}
|
|
47
|
+
/** Zero-based index of the current token. */
|
|
48
|
+
export function getTokenIndex() {
|
|
49
|
+
ensureInitialized();
|
|
50
|
+
return currentIndex;
|
|
51
|
+
}
|
|
52
|
+
/** Total number of tokens in the pool. */
|
|
53
|
+
export function getTokenCount() {
|
|
54
|
+
ensureInitialized();
|
|
55
|
+
return tokens.length;
|
|
56
|
+
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gonzih/cc-tg",
|
|
3
|
-
"version": "0.9.
|
|
4
|
-
"description": "Claude Code Telegram bot
|
|
3
|
+
"version": "0.9.4",
|
|
4
|
+
"description": "Claude Code Telegram bot \u2014 chat with Claude Code via Telegram",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"cc-tg": "./dist/index.js"
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
|
-
"build": "tsc",
|
|
10
|
+
"build": "tsc && chmod +x dist/index.js",
|
|
11
11
|
"start": "node dist/index.js",
|
|
12
12
|
"dev": "node --loader ts-node/esm src/index.ts",
|
|
13
13
|
"test": "vitest run",
|
|
@@ -18,10 +18,11 @@
|
|
|
18
18
|
"dist/"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
+
"@gonzih/agent-ops": "^0.1.0",
|
|
21
22
|
"node-telegram-bot-api": "^0.66.0"
|
|
22
23
|
},
|
|
23
24
|
"devDependencies": {
|
|
24
|
-
"@types/node": "^22.
|
|
25
|
+
"@types/node": "^22.0.0",
|
|
25
26
|
"@types/node-telegram-bot-api": "^0.64.0",
|
|
26
27
|
"@vitest/coverage-v8": "^4.1.0",
|
|
27
28
|
"typescript": "^5.5.0",
|
|
@@ -43,4 +44,4 @@
|
|
|
43
44
|
"ai"
|
|
44
45
|
],
|
|
45
46
|
"license": "MIT"
|
|
46
|
-
}
|
|
47
|
+
}
|
package/dist/cron.d.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cron job manager for cc-tg.
|
|
3
|
-
* Persists jobs to <cwd>/.cc-tg/crons.json.
|
|
4
|
-
* Fires prompts into Claude sessions on schedule.
|
|
5
|
-
*/
|
|
6
|
-
export interface CronJob {
|
|
7
|
-
id: string;
|
|
8
|
-
chatId: number;
|
|
9
|
-
intervalMs: number;
|
|
10
|
-
prompt: string;
|
|
11
|
-
createdAt: string;
|
|
12
|
-
schedule: string;
|
|
13
|
-
}
|
|
14
|
-
type FireCallback = (chatId: number, prompt: string) => void;
|
|
15
|
-
export declare class CronManager {
|
|
16
|
-
private jobs;
|
|
17
|
-
private storePath;
|
|
18
|
-
private fire;
|
|
19
|
-
constructor(cwd: string, fire: FireCallback);
|
|
20
|
-
/** Parse "every 30m", "every 2h", "every 1d" → ms */
|
|
21
|
-
static parseSchedule(schedule: string): number | null;
|
|
22
|
-
add(chatId: number, schedule: string, prompt: string): CronJob | null;
|
|
23
|
-
remove(chatId: number, id: string): boolean;
|
|
24
|
-
clearAll(chatId: number): number;
|
|
25
|
-
list(chatId: number): CronJob[];
|
|
26
|
-
update(chatId: number, id: string, updates: {
|
|
27
|
-
schedule?: string;
|
|
28
|
-
prompt?: string;
|
|
29
|
-
}): CronJob | null | false;
|
|
30
|
-
private persist;
|
|
31
|
-
private load;
|
|
32
|
-
}
|
|
33
|
-
export {};
|