@gonzih/cc-tg 0.9.16 → 0.9.18

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.
@@ -0,0 +1,30 @@
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 reached') ||
7
+ lower.includes('your usage limit')) {
8
+ const wake = nextHourBoundary() + 5 * 60 * 1000;
9
+ return {
10
+ detected: true,
11
+ reason: 'usage_exhausted',
12
+ retryAfterMs: wake - Date.now(),
13
+ humanMessage: `⏸ Claude usage limit reached. Will auto-resume at ${new Date(wake).toUTCString()}. I'll message you when it's back.`,
14
+ };
15
+ }
16
+ if (lower.includes('currently overloaded') || lower.includes('overloaded with requests')) {
17
+ return {
18
+ detected: true,
19
+ reason: 'rate_limit',
20
+ retryAfterMs: 2 * 60 * 1000,
21
+ humanMessage: `⏸ Rate limited. Retrying in 2 minutes...`,
22
+ };
23
+ }
24
+ return { detected: false, reason: 'rate_limit', retryAfterMs: 0, humanMessage: '' };
25
+ }
26
+ function nextHourBoundary() {
27
+ const d = new Date();
28
+ d.setHours(d.getHours() + 1, 0, 0, 0);
29
+ return d.getTime();
30
+ }
@@ -0,0 +1,13 @@
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 ADDED
@@ -0,0 +1,147 @@
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 (with one retry on signal-kill)
96
+ // Note: omit --output-txt — we read from stdout directly, no file write needed
97
+ const whisperArgs = [
98
+ "-m", model,
99
+ "-f", wavPath,
100
+ "--no-timestamps",
101
+ "-l", "auto",
102
+ "--no-prints", // suppress progress/timing logs from stdout so we get clean text
103
+ ];
104
+ let stdout = "";
105
+ for (let attempt = 1; attempt <= 2; attempt++) {
106
+ try {
107
+ const result = await execFileAsync(whisperBin, whisperArgs, {
108
+ timeout: 120000, // 2 min — large audio files can take a while
109
+ maxBuffer: 10 * 1024 * 1024, // 10 MB — generous for long transcriptions
110
+ });
111
+ stdout = result.stdout;
112
+ break;
113
+ }
114
+ catch (e) {
115
+ // On attempt 1: retry if killed by signal or empty message (OOM/SIGKILL)
116
+ if (attempt < 2 && (e.signal || !e.message)) {
117
+ console.warn(`[voice] whisper attempt ${attempt} killed (${e.signal || 'no message'}), retrying...`);
118
+ continue;
119
+ }
120
+ // Re-throw with stderr attached so caller can show useful diagnostics
121
+ const detail = (e.stderr || "").toString().trim().split("\n").slice(-5).join(" | ");
122
+ if (detail)
123
+ e.message = `${e.message || "whisper failed"} — ${detail}`;
124
+ throw e;
125
+ }
126
+ }
127
+ // whisper outputs to stdout — strip leading/trailing whitespace and [BLANK_AUDIO] artifacts
128
+ const text = stdout
129
+ .replace(/\[BLANK_AUDIO\]/gi, "")
130
+ .replace(/\[.*?\]/g, "") // remove timestamp artifacts
131
+ .trim();
132
+ return text || "[empty transcription]";
133
+ }
134
+ finally {
135
+ // Cleanup temp files
136
+ await unlink(oggPath).catch(() => { });
137
+ await unlink(wavPath).catch(() => { });
138
+ }
139
+ }
140
+ /**
141
+ * Check if voice transcription is available on this system.
142
+ */
143
+ export function isVoiceAvailable() {
144
+ return (findBin(WHISPER_BIN_CANDIDATES) !== null &&
145
+ findBin(FFMPEG_CANDIDATES) !== null &&
146
+ findModel() !== null);
147
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@gonzih/cc-tg",
3
- "version": "0.9.16",
3
+ "version": "0.9.18",
4
4
  "description": "Claude Code Telegram bot — 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 && chmod +x dist/index.js",
10
+ "build": "tsc",
11
11
  "start": "node dist/index.js",
12
12
  "dev": "node --loader ts-node/esm src/index.ts",
13
13
  "test": "vitest run",
@@ -18,11 +18,10 @@
18
18
  "dist/"
19
19
  ],
20
20
  "dependencies": {
21
- "@gonzih/agent-ops": "^0.1.0",
22
21
  "node-telegram-bot-api": "^0.66.0"
23
22
  },
24
23
  "devDependencies": {
25
- "@types/node": "^22.0.0",
24
+ "@types/node": "^22.19.15",
26
25
  "@types/node-telegram-bot-api": "^0.64.0",
27
26
  "@vitest/coverage-v8": "^4.1.0",
28
27
  "typescript": "^5.5.0",