@gonzih/cc-tg 0.9.9 → 0.9.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/dist/bot.d.ts +0 -84
- package/dist/bot.js +0 -1293
- package/dist/claude.d.ts +0 -54
- package/dist/claude.js +0 -208
- package/dist/cron.d.ts +0 -39
- package/dist/cron.js +0 -148
- package/dist/formatter.d.ts +0 -25
- package/dist/formatter.js +0 -122
- package/dist/index.d.ts +0 -17
- package/dist/index.js +0 -179
- package/dist/notifier.d.ts +0 -37
- package/dist/notifier.js +0 -132
- package/dist/tokens.d.ts +0 -22
- package/dist/tokens.js +0 -56
- package/dist/usage-limit.d.ts +0 -7
- package/dist/usage-limit.js +0 -29
- package/dist/voice.d.ts +0 -13
- package/dist/voice.js +0 -124
package/dist/index.js
DELETED
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* cc-tg — Claude Code Telegram bot
|
|
4
|
-
*
|
|
5
|
-
* Usage:
|
|
6
|
-
* npx @gonzih/cc-tg
|
|
7
|
-
*
|
|
8
|
-
* Required env:
|
|
9
|
-
* TELEGRAM_BOT_TOKEN — from @BotFather
|
|
10
|
-
* CLAUDE_CODE_TOKEN — your Claude Code OAuth token (or ANTHROPIC_API_KEY)
|
|
11
|
-
*
|
|
12
|
-
* Optional env:
|
|
13
|
-
* ALLOWED_USER_IDS — comma-separated Telegram user IDs (leave empty to allow all)
|
|
14
|
-
* GROUP_CHAT_IDS — comma-separated Telegram group/supergroup chat IDs (leave empty to allow all groups)
|
|
15
|
-
* CWD — working directory for Claude Code (default: process.cwd())
|
|
16
|
-
*/
|
|
17
|
-
import { createServer, createConnection } from "net";
|
|
18
|
-
import { unlinkSync, readFileSync } from "fs";
|
|
19
|
-
import { tmpdir } from "os";
|
|
20
|
-
import os from "os";
|
|
21
|
-
import { join, dirname } from "path";
|
|
22
|
-
import { fileURLToPath } from "url";
|
|
23
|
-
import TelegramBot from "node-telegram-bot-api";
|
|
24
|
-
import { CcTgBot } from "./bot.js";
|
|
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`);
|
|
35
|
-
function acquireLock() {
|
|
36
|
-
return new Promise((resolve) => {
|
|
37
|
-
const server = createServer();
|
|
38
|
-
server.listen(LOCK_SOCKET, () => {
|
|
39
|
-
// Bound successfully — we own the lock. Socket auto-released on any exit incl. SIGKILL.
|
|
40
|
-
resolve(true);
|
|
41
|
-
});
|
|
42
|
-
server.on("error", (err) => {
|
|
43
|
-
if (err.code !== "EADDRINUSE") {
|
|
44
|
-
resolve(true); // unrelated error, proceed
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
// Socket path exists — probe if anything is actually listening
|
|
48
|
-
const probe = createConnection(LOCK_SOCKET);
|
|
49
|
-
probe.on("connect", () => {
|
|
50
|
-
probe.destroy();
|
|
51
|
-
console.error("[cc-tg] Another instance is already running. Exiting.");
|
|
52
|
-
resolve(false);
|
|
53
|
-
});
|
|
54
|
-
probe.on("error", () => {
|
|
55
|
-
// Nothing listening — stale socket, remove and retry
|
|
56
|
-
try {
|
|
57
|
-
unlinkSync(LOCK_SOCKET);
|
|
58
|
-
}
|
|
59
|
-
catch { }
|
|
60
|
-
const retry = createServer();
|
|
61
|
-
retry.listen(LOCK_SOCKET, () => resolve(true));
|
|
62
|
-
retry.on("error", () => resolve(true)); // give up on lock, just start
|
|
63
|
-
});
|
|
64
|
-
});
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
const lockAcquired = await acquireLock();
|
|
68
|
-
if (!lockAcquired) {
|
|
69
|
-
process.exit(1);
|
|
70
|
-
}
|
|
71
|
-
function required(name) {
|
|
72
|
-
const val = process.env[name];
|
|
73
|
-
if (!val) {
|
|
74
|
-
console.error(`
|
|
75
|
-
ERROR: ${name} is not set.
|
|
76
|
-
|
|
77
|
-
cc-tg requires:
|
|
78
|
-
TELEGRAM_BOT_TOKEN — get one from @BotFather on Telegram
|
|
79
|
-
CLAUDE_CODE_TOKEN — your Claude Code OAuth token
|
|
80
|
-
|
|
81
|
-
Set them and run again:
|
|
82
|
-
TELEGRAM_BOT_TOKEN=xxx CLAUDE_CODE_TOKEN=yyy npx @gonzih/cc-tg
|
|
83
|
-
|
|
84
|
-
Or add to your shell profile / .env file.
|
|
85
|
-
`);
|
|
86
|
-
process.exit(1);
|
|
87
|
-
}
|
|
88
|
-
return val;
|
|
89
|
-
}
|
|
90
|
-
const telegramToken = required("TELEGRAM_BOT_TOKEN");
|
|
91
|
-
// Accept CLAUDE_CODE_TOKEN, CLAUDE_CODE_OAUTH_TOKEN, or ANTHROPIC_API_KEY
|
|
92
|
-
const claudeToken = process.env.CLAUDE_CODE_TOKEN ??
|
|
93
|
-
process.env.CLAUDE_CODE_OAUTH_TOKEN ??
|
|
94
|
-
process.env.ANTHROPIC_API_KEY;
|
|
95
|
-
if (!claudeToken) {
|
|
96
|
-
console.error(`
|
|
97
|
-
ERROR: No Claude token set. Set one of: CLAUDE_CODE_TOKEN, CLAUDE_CODE_OAUTH_TOKEN, or ANTHROPIC_API_KEY.
|
|
98
|
-
|
|
99
|
-
Set one and run again:
|
|
100
|
-
TELEGRAM_BOT_TOKEN=xxx CLAUDE_CODE_TOKEN=yyy npx @gonzih/cc-tg
|
|
101
|
-
`);
|
|
102
|
-
process.exit(1);
|
|
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
|
-
}
|
|
109
|
-
const allowedUserIds = process.env.ALLOWED_USER_IDS
|
|
110
|
-
? process.env.ALLOWED_USER_IDS.split(",").map((s) => parseInt(s.trim(), 10)).filter(Boolean)
|
|
111
|
-
: [];
|
|
112
|
-
const groupChatIds = process.env.GROUP_CHAT_IDS
|
|
113
|
-
? process.env.GROUP_CHAT_IDS.split(",").map((s) => parseInt(s.trim(), 10)).filter(Boolean)
|
|
114
|
-
: [];
|
|
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
|
-
});
|
|
125
|
-
sharedRedis.once("ready", () => {
|
|
126
|
-
sharedRedis.set("cca:meta:cc-tg:version", pkg.version).catch((err) => {
|
|
127
|
-
console.warn("[redis] failed to write version:", err.message);
|
|
128
|
-
});
|
|
129
|
-
console.log(`[cc-tg] version:reported ${pkg.version}`);
|
|
130
|
-
});
|
|
131
|
-
const bot = new CcTgBot({
|
|
132
|
-
telegramToken,
|
|
133
|
-
claudeToken,
|
|
134
|
-
cwd,
|
|
135
|
-
allowedUserIds,
|
|
136
|
-
groupChatIds,
|
|
137
|
-
redis: sharedRedis,
|
|
138
|
-
namespace,
|
|
139
|
-
});
|
|
140
|
-
if (process.env.CC_AGENT_OPS_PORT) {
|
|
141
|
-
const botInfo = await bot.getMe();
|
|
142
|
-
const registry = new Registry(sharedRedis);
|
|
143
|
-
await registry.register({
|
|
144
|
-
namespace,
|
|
145
|
-
hostname: os.hostname(),
|
|
146
|
-
user: os.userInfo().username,
|
|
147
|
-
pid: String(process.pid),
|
|
148
|
-
version: pkg.version,
|
|
149
|
-
cwd: process.env.CWD || process.cwd(),
|
|
150
|
-
control_port: process.env.CC_AGENT_OPS_PORT,
|
|
151
|
-
bot_username: botInfo.username ?? "",
|
|
152
|
-
started_at: new Date().toISOString(),
|
|
153
|
-
});
|
|
154
|
-
setInterval(() => registry.heartbeat(namespace), 60_000);
|
|
155
|
-
startControlServer(Number(process.env.CC_AGENT_OPS_PORT), {
|
|
156
|
-
namespace,
|
|
157
|
-
version: pkg.version,
|
|
158
|
-
logFile: process.env.CC_AGENT_LOG_FILE || process.env.LOG_FILE,
|
|
159
|
-
});
|
|
160
|
-
console.log(`[ops] control server on port ${process.env.CC_AGENT_OPS_PORT}`);
|
|
161
|
-
}
|
|
162
|
-
// Notifier — always subscribe to cca:notify and cca:chat:incoming channels.
|
|
163
|
-
// CC_AGENT_NOTIFY_CHAT_ID pins a fixed Telegram chatId; without it the last
|
|
164
|
-
// active chatId is used dynamically for the chat bridge.
|
|
165
|
-
const notifyChatId = process.env.CC_AGENT_NOTIFY_CHAT_ID
|
|
166
|
-
? Number(process.env.CC_AGENT_NOTIFY_CHAT_ID)
|
|
167
|
-
: null;
|
|
168
|
-
const notifierBot = new TelegramBot(telegramToken, { polling: false });
|
|
169
|
-
startNotifier(notifierBot, notifyChatId, namespace, sharedRedis, (cid, text) => bot.handleUserMessage(cid, text), () => bot.getLastActiveChatId());
|
|
170
|
-
console.log(`[notifier] started for namespace=${namespace} chatId=${notifyChatId ?? "dynamic"}`);
|
|
171
|
-
process.on("SIGINT", () => {
|
|
172
|
-
console.log("\nShutting down...");
|
|
173
|
-
bot.stop();
|
|
174
|
-
process.exit(0);
|
|
175
|
-
});
|
|
176
|
-
process.on("SIGTERM", () => {
|
|
177
|
-
bot.stop();
|
|
178
|
-
process.exit(0);
|
|
179
|
-
});
|
package/dist/notifier.d.ts
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
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
|
-
const targetId = chatId ?? getActiveChatId?.();
|
|
81
|
-
if (targetId != null) {
|
|
82
|
-
bot.sendMessage(targetId, message).catch((err) => {
|
|
83
|
-
log("warn", "sendMessage failed:", err.message);
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
else {
|
|
87
|
-
log("warn", "notify: no chatId available, dropping notification");
|
|
88
|
-
}
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
if (channel === incomingChannel) {
|
|
92
|
-
let content = message;
|
|
93
|
-
let originalTimestamp;
|
|
94
|
-
try {
|
|
95
|
-
const parsed = JSON.parse(message);
|
|
96
|
-
if (parsed.content)
|
|
97
|
-
content = parsed.content;
|
|
98
|
-
if (parsed.timestamp)
|
|
99
|
-
originalTimestamp = parsed.timestamp;
|
|
100
|
-
}
|
|
101
|
-
catch {
|
|
102
|
-
// raw string message — use as-is
|
|
103
|
-
}
|
|
104
|
-
// Resolve the target chatId: prefer the fixed chatId, fall back to last active
|
|
105
|
-
const targetChatId = chatId ?? getActiveChatId?.();
|
|
106
|
-
if (targetChatId !== undefined) {
|
|
107
|
-
// Echo to Telegram so the user sees UI messages in the chat
|
|
108
|
-
bot.sendMessage(targetChatId, `📱 [from UI]: ${content}`).catch((err) => {
|
|
109
|
-
log("warn", "sendMessage (UI echo) failed:", err.message);
|
|
110
|
-
});
|
|
111
|
-
// Log the incoming message — preserve original timestamp from UI if present
|
|
112
|
-
const inMsg = {
|
|
113
|
-
id: `ui-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
114
|
-
source: "ui", // 'ui' distinguishes this from telegram/claude messages
|
|
115
|
-
role: "user",
|
|
116
|
-
content,
|
|
117
|
-
// ISO 8601 — matches cc-agent-ui /chat/send format; preserve original if present
|
|
118
|
-
timestamp: originalTimestamp ?? new Date().toISOString(),
|
|
119
|
-
chatId: targetChatId,
|
|
120
|
-
};
|
|
121
|
-
writeChatLog(redis, namespace, inMsg);
|
|
122
|
-
// Feed into active Claude session as if user typed it
|
|
123
|
-
if (handleUserMessage) {
|
|
124
|
-
handleUserMessage(targetChatId, content);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
else {
|
|
128
|
-
log("warn", "cca:chat:incoming: no active chatId to route message to");
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
});
|
|
132
|
-
}
|
package/dist/tokens.d.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
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/dist/usage-limit.d.ts
DELETED
package/dist/usage-limit.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
export function detectUsageLimit(text) {
|
|
2
|
-
const lower = text.toLowerCase();
|
|
3
|
-
if (lower.includes('extra usage') ||
|
|
4
|
-
lower.includes('usage has been disabled') ||
|
|
5
|
-
lower.includes('billing_error') ||
|
|
6
|
-
lower.includes('usage limit')) {
|
|
7
|
-
const wake = nextHourBoundary() + 5 * 60 * 1000;
|
|
8
|
-
return {
|
|
9
|
-
detected: true,
|
|
10
|
-
reason: 'usage_exhausted',
|
|
11
|
-
retryAfterMs: wake - Date.now(),
|
|
12
|
-
humanMessage: `⏸ Claude usage limit reached. Will auto-resume at ${new Date(wake).toUTCString()}. I'll message you when it's back.`,
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
if (lower.includes('rate limit') || lower.includes('overloaded')) {
|
|
16
|
-
return {
|
|
17
|
-
detected: true,
|
|
18
|
-
reason: 'rate_limit',
|
|
19
|
-
retryAfterMs: 2 * 60 * 1000,
|
|
20
|
-
humanMessage: `⏸ Rate limited. Retrying in 2 minutes...`,
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
return { detected: false, reason: 'rate_limit', retryAfterMs: 0, humanMessage: '' };
|
|
24
|
-
}
|
|
25
|
-
function nextHourBoundary() {
|
|
26
|
-
const d = new Date();
|
|
27
|
-
d.setHours(d.getHours() + 1, 0, 0, 0);
|
|
28
|
-
return d.getTime();
|
|
29
|
-
}
|
package/dist/voice.d.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Voice message transcription via whisper.cpp.
|
|
3
|
-
* Flow: Telegram OGG → ffmpeg convert to 16kHz WAV → whisper-cpp → text
|
|
4
|
-
*/
|
|
5
|
-
/**
|
|
6
|
-
* Transcribe a voice message from a Telegram file URL.
|
|
7
|
-
* Returns the transcribed text, or throws if whisper/ffmpeg not available.
|
|
8
|
-
*/
|
|
9
|
-
export declare function transcribeVoice(fileUrl: string): Promise<string>;
|
|
10
|
-
/**
|
|
11
|
-
* Check if voice transcription is available on this system.
|
|
12
|
-
*/
|
|
13
|
-
export declare function isVoiceAvailable(): boolean;
|
package/dist/voice.js
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Voice message transcription via whisper.cpp.
|
|
3
|
-
* Flow: Telegram OGG → ffmpeg convert to 16kHz WAV → whisper-cpp → text
|
|
4
|
-
*/
|
|
5
|
-
import { execFile } from "child_process";
|
|
6
|
-
import { promisify } from "util";
|
|
7
|
-
import { existsSync } from "fs";
|
|
8
|
-
import { unlink } from "fs/promises";
|
|
9
|
-
import { tmpdir } from "os";
|
|
10
|
-
import { join } from "path";
|
|
11
|
-
import https from "https";
|
|
12
|
-
import http from "http";
|
|
13
|
-
import { createWriteStream } from "fs";
|
|
14
|
-
const execFileAsync = promisify(execFile);
|
|
15
|
-
// Whisper model — small.en is fast and accurate enough for commands
|
|
16
|
-
// Falls back to base.en if small not found
|
|
17
|
-
const WHISPER_MODELS = [
|
|
18
|
-
"/opt/homebrew/share/whisper-cpp/ggml-small.en.bin",
|
|
19
|
-
"/opt/homebrew/share/whisper-cpp/ggml-small.bin",
|
|
20
|
-
"/opt/homebrew/share/whisper-cpp/ggml-base.en.bin",
|
|
21
|
-
"/opt/homebrew/share/whisper-cpp/ggml-base.bin",
|
|
22
|
-
// user-local
|
|
23
|
-
`${process.env.HOME}/.local/share/whisper-cpp/ggml-small.en.bin`,
|
|
24
|
-
`${process.env.HOME}/.local/share/whisper-cpp/ggml-base.en.bin`,
|
|
25
|
-
];
|
|
26
|
-
const WHISPER_BIN_CANDIDATES = [
|
|
27
|
-
"/opt/homebrew/bin/whisper-cli", // whisper-cpp brew formula installs as whisper-cli
|
|
28
|
-
"/opt/homebrew/bin/whisper-cpp",
|
|
29
|
-
"/usr/local/bin/whisper-cli",
|
|
30
|
-
"/usr/local/bin/whisper-cpp",
|
|
31
|
-
"/opt/homebrew/bin/whisper",
|
|
32
|
-
];
|
|
33
|
-
const FFMPEG_CANDIDATES = [
|
|
34
|
-
"/opt/homebrew/bin/ffmpeg",
|
|
35
|
-
"/usr/local/bin/ffmpeg",
|
|
36
|
-
"/usr/bin/ffmpeg",
|
|
37
|
-
];
|
|
38
|
-
function findBin(candidates) {
|
|
39
|
-
for (const p of candidates) {
|
|
40
|
-
if (existsSync(p))
|
|
41
|
-
return p;
|
|
42
|
-
}
|
|
43
|
-
return null;
|
|
44
|
-
}
|
|
45
|
-
function findModel() {
|
|
46
|
-
for (const p of WHISPER_MODELS) {
|
|
47
|
-
if (existsSync(p))
|
|
48
|
-
return p;
|
|
49
|
-
}
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
function downloadFile(url, dest) {
|
|
53
|
-
return new Promise((resolve, reject) => {
|
|
54
|
-
const file = createWriteStream(dest);
|
|
55
|
-
const getter = url.startsWith("https") ? https : http;
|
|
56
|
-
getter.get(url, (res) => {
|
|
57
|
-
if (res.statusCode !== 200) {
|
|
58
|
-
reject(new Error(`HTTP ${res.statusCode} downloading ${url}`));
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
res.pipe(file);
|
|
62
|
-
file.on("finish", () => file.close(() => resolve()));
|
|
63
|
-
file.on("error", reject);
|
|
64
|
-
}).on("error", reject);
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Transcribe a voice message from a Telegram file URL.
|
|
69
|
-
* Returns the transcribed text, or throws if whisper/ffmpeg not available.
|
|
70
|
-
*/
|
|
71
|
-
export async function transcribeVoice(fileUrl) {
|
|
72
|
-
const whisperBin = findBin(WHISPER_BIN_CANDIDATES);
|
|
73
|
-
if (!whisperBin)
|
|
74
|
-
throw new Error("whisper-cpp not found — install with: brew install whisper-cpp");
|
|
75
|
-
const ffmpegBin = findBin(FFMPEG_CANDIDATES);
|
|
76
|
-
if (!ffmpegBin)
|
|
77
|
-
throw new Error("ffmpeg not found — install with: brew install ffmpeg");
|
|
78
|
-
const model = findModel();
|
|
79
|
-
if (!model)
|
|
80
|
-
throw new Error("No whisper model found — run: whisper-cpp-download-ggml-model small.en");
|
|
81
|
-
const tmp = join(tmpdir(), `cc-tg-voice-${Date.now()}`);
|
|
82
|
-
const oggPath = `${tmp}.ogg`;
|
|
83
|
-
const wavPath = `${tmp}.wav`;
|
|
84
|
-
try {
|
|
85
|
-
// 1. Download OGG from Telegram
|
|
86
|
-
await downloadFile(fileUrl, oggPath);
|
|
87
|
-
// 2. Convert OGG → 16kHz mono WAV (whisper requirement)
|
|
88
|
-
await execFileAsync(ffmpegBin, [
|
|
89
|
-
"-y", "-i", oggPath,
|
|
90
|
-
"-ar", "16000",
|
|
91
|
-
"-ac", "1",
|
|
92
|
-
"-c:a", "pcm_s16le",
|
|
93
|
-
wavPath,
|
|
94
|
-
]);
|
|
95
|
-
// 3. Run whisper-cpp
|
|
96
|
-
const { stdout } = await execFileAsync(whisperBin, [
|
|
97
|
-
"-m", model,
|
|
98
|
-
"-f", wavPath,
|
|
99
|
-
"--no-timestamps",
|
|
100
|
-
"-l", "auto",
|
|
101
|
-
"--output-txt",
|
|
102
|
-
]);
|
|
103
|
-
// whisper outputs to stdout — strip leading/trailing whitespace and [BLANK_AUDIO] artifacts
|
|
104
|
-
const text = stdout
|
|
105
|
-
.replace(/\[BLANK_AUDIO\]/gi, "")
|
|
106
|
-
.replace(/\[.*?\]/g, "") // remove timestamp artifacts
|
|
107
|
-
.trim();
|
|
108
|
-
return text || "[empty transcription]";
|
|
109
|
-
}
|
|
110
|
-
finally {
|
|
111
|
-
// Cleanup temp files
|
|
112
|
-
await unlink(oggPath).catch(() => { });
|
|
113
|
-
await unlink(wavPath).catch(() => { });
|
|
114
|
-
await unlink(`${wavPath}.txt`).catch(() => { });
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* Check if voice transcription is available on this system.
|
|
119
|
-
*/
|
|
120
|
-
export function isVoiceAvailable() {
|
|
121
|
-
return (findBin(WHISPER_BIN_CANDIDATES) !== null &&
|
|
122
|
-
findBin(FFMPEG_CANDIDATES) !== null &&
|
|
123
|
-
findModel() !== null);
|
|
124
|
-
}
|