@gonzih/cc-tg 0.6.4 → 0.6.6

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.
@@ -1,87 +0,0 @@
1
- /**
2
- * cc-agent Redis event subscriber.
3
- *
4
- * Listens to the `cca:events` pub/sub channel for job completion events,
5
- * asks Claude to decide what to do, and acts accordingly:
6
- * NOTIFY_ONLY — send a Telegram message to the configured chat
7
- * SPAWN_FOLLOWUP — spawn a follow-up cc-agent job via MCP + notify Telegram
8
- * SILENT — log and do nothing
9
- *
10
- * Controlled via CC_AGENT_EVENTS_ENABLED env var (default: true).
11
- * Requires CC_AGENT_NOTIFY_CHAT_ID to send Telegram notifications.
12
- */
13
- export interface JobEvent {
14
- jobId: string;
15
- status: "done" | "failed" | "interrupted" | "running" | "cancelled";
16
- title: string;
17
- repoUrl: string;
18
- lastLines: string[];
19
- score?: number;
20
- timestamp: number;
21
- }
22
- export interface CoordinatorPlan {
23
- nextStep?: {
24
- repo_url: string;
25
- task: string;
26
- };
27
- summary: string;
28
- }
29
- export interface DecisionResult {
30
- action: "NOTIFY_ONLY" | "SPAWN_FOLLOWUP" | "SILENT";
31
- message?: string;
32
- followup?: {
33
- repo_url: string;
34
- task: string;
35
- };
36
- }
37
- /** Injectable dependencies for testability */
38
- export interface HandlerDeps {
39
- askClaude: (prompt: string) => Promise<string>;
40
- sendTelegramMessage: (chatId: number, text: string) => Promise<void>;
41
- spawnFollowupAgent: (repoUrl: string, task: string) => Promise<void>;
42
- readJobOutput: (jobId: string) => Promise<string[]>;
43
- readCoordinatorPlan: (jobId: string) => Promise<CoordinatorPlan | null>;
44
- getRunningJobCount: () => Promise<number>;
45
- getActiveChatIds: () => Promise<number[]>;
46
- }
47
- export declare function buildDecisionPrompt(event: JobEvent, last40lines: string[], coordinatorPlan: CoordinatorPlan | null): string;
48
- export declare function parseDecision(raw: string): DecisionResult;
49
- /**
50
- * Ask Claude to make a decision about a completed job.
51
- * Returns the raw text response from Claude.
52
- */
53
- export declare function defaultAskClaude(prompt: string): Promise<string>;
54
- export declare function defaultSendTelegramMessage(chatId: number, text: string): Promise<void>;
55
- export declare function defaultSpawnFollowupAgent(repoUrl: string, task: string): Promise<void>;
56
- export declare function defaultReadJobOutput(jobId: string): Promise<string[]>;
57
- export declare function defaultReadCoordinatorPlan(jobId: string): Promise<CoordinatorPlan | null>;
58
- export declare function defaultGetRunningJobCount(): Promise<number>;
59
- /**
60
- * Returns chat IDs to notify about job events.
61
- * Reads unique chatIds from the cron jobs file (same users who set up cron jobs).
62
- * Falls back to CC_AGENT_NOTIFY_CHAT_ID env var for backward compatibility.
63
- */
64
- export declare function defaultGetActiveChatIds(): Promise<number[]>;
65
- /**
66
- * Write a coordinator plan for a job, so cc-tg knows what follow-up to spawn.
67
- * Call this when spawning a job that has a planned follow-up.
68
- * TTL: 7 days.
69
- */
70
- export declare function writeCoordinatorPlan(jobId: string, plan: {
71
- nextStep?: {
72
- repo_url: string;
73
- task: string;
74
- };
75
- summary: string;
76
- }): Promise<void>;
77
- /**
78
- * Handle a single job event message from Redis pub/sub.
79
- * Exported for testability — production code passes defaultDeps.
80
- */
81
- export declare function handleJobEvent(message: string, deps: HandlerDeps): Promise<void>;
82
- /**
83
- * Connect to Redis and subscribe to cca:events.
84
- * Reconnects automatically on disconnect.
85
- * Call once at startup.
86
- */
87
- export declare function connectEventSubscriber(): Promise<void>;
@@ -1,463 +0,0 @@
1
- /**
2
- * cc-agent Redis event subscriber.
3
- *
4
- * Listens to the `cca:events` pub/sub channel for job completion events,
5
- * asks Claude to decide what to do, and acts accordingly:
6
- * NOTIFY_ONLY — send a Telegram message to the configured chat
7
- * SPAWN_FOLLOWUP — spawn a follow-up cc-agent job via MCP + notify Telegram
8
- * SILENT — log and do nothing
9
- *
10
- * Controlled via CC_AGENT_EVENTS_ENABLED env var (default: true).
11
- * Requires CC_AGENT_NOTIFY_CHAT_ID to send Telegram notifications.
12
- */
13
- import { readFileSync } from "fs";
14
- import { join } from "path";
15
- import { Redis } from "ioredis";
16
- import TelegramBot from "node-telegram-bot-api";
17
- import { ClaudeProcess, extractText } from "./claude.js";
18
- function log(level, ...args) {
19
- const fn = level === "error"
20
- ? console.error
21
- : level === "warn"
22
- ? console.warn
23
- : console.log;
24
- fn("[cc-agent-events]", ...args);
25
- }
26
- export function buildDecisionPrompt(event, last40lines, coordinatorPlan) {
27
- const scoreStr = event.score !== undefined ? String(event.score) : "n/a";
28
- const planStr = coordinatorPlan ? JSON.stringify(coordinatorPlan, null, 2) : "none";
29
- return `A cc-agent job just completed.
30
-
31
- Job: ${event.title}
32
- Repo: ${event.repoUrl}
33
- Status: ${event.status}
34
- Score: ${scoreStr}
35
-
36
- Last output + LEARNINGS:
37
- ${last40lines.join("\n")}
38
-
39
- Coordinator plan for this job (if any):
40
- ${planStr}
41
-
42
- Decide what to do next:
43
- 1. SPAWN_FOLLOWUP — spawn a follow-up job (provide repo_url and task)
44
- 2. NOTIFY_ONLY — send Telegram message, no spawn needed
45
- 3. SILENT — routine completion, no action
46
-
47
- Rules:
48
- - If LEARNINGS has "Recommendations for next agent" with a clear actionable next step → consider SPAWN_FOLLOWUP
49
- - If coordinator plan has nextStep → SPAWN_FOLLOWUP with that task (prefer coordinator plan over LEARNINGS)
50
- - Failed jobs → NOTIFY_ONLY always
51
- - Score < 0.5 → NOTIFY_ONLY
52
- - Routine/expected completions → SILENT
53
-
54
- Reply in JSON:
55
- {
56
- "action": "SPAWN_FOLLOWUP" | "NOTIFY_ONLY" | "SILENT",
57
- "message": "brief telegram message (1-2 lines)",
58
- "followup": { "repo_url": "...", "task": "..." } | null
59
- }`;
60
- }
61
- function extractJson(text) {
62
- // Strip ```json ... ``` fences
63
- const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/);
64
- if (fenced)
65
- return fenced[1].trim();
66
- // Find first { ... } block
67
- const start = text.indexOf("{");
68
- const end = text.lastIndexOf("}");
69
- if (start !== -1 && end !== -1)
70
- return text.slice(start, end + 1);
71
- return "";
72
- }
73
- export function parseDecision(raw) {
74
- const extracted = extractJson(raw);
75
- if (!extracted)
76
- throw new Error(`No JSON found in Claude response: ${raw.slice(0, 200)}`);
77
- const parsed = JSON.parse(extracted);
78
- if (!["NOTIFY_ONLY", "SPAWN_FOLLOWUP", "SILENT"].includes(parsed.action)) {
79
- throw new Error(`Unknown action: ${parsed.action}`);
80
- }
81
- return parsed;
82
- }
83
- function formatSpawnMessage(event, followup, runningCount) {
84
- const scoreStr = event.score !== undefined ? ` (score: ${event.score})` : "";
85
- const repoShort = followup.repo_url.replace(/^https?:\/\/github\.com\//, "");
86
- const lines = [
87
- `✓ ${event.title} done${scoreStr}`,
88
- `→ spawned: ${followup.task} (${repoShort})`,
89
- ];
90
- if (runningCount > 0) {
91
- lines.push(`${runningCount} jobs running`);
92
- }
93
- return lines.join("\n");
94
- }
95
- function formatFailureMessage(event) {
96
- const lastLine = event.lastLines[event.lastLines.length - 1] ?? "";
97
- const repoShort = event.repoUrl.replace(/^https?:\/\/github\.com\//, "");
98
- return `✗ ${event.title} failed\n${repoShort} — exit 1\nLast line: ${lastLine}`;
99
- }
100
- /**
101
- * Ask Claude to make a decision about a completed job.
102
- * Returns the raw text response from Claude.
103
- */
104
- export function defaultAskClaude(prompt) {
105
- return new Promise((resolve, reject) => {
106
- const token = process.env.CLAUDE_CODE_TOKEN ??
107
- process.env.CLAUDE_CODE_OAUTH_TOKEN ??
108
- process.env.ANTHROPIC_API_KEY;
109
- if (!token) {
110
- reject(new Error("No Claude token configured"));
111
- return;
112
- }
113
- const claude = new ClaudeProcess({ token });
114
- let output = "";
115
- const timeout = setTimeout(() => {
116
- claude.kill();
117
- reject(new Error("Claude decision timed out after 60s"));
118
- }, 60_000);
119
- claude.on("message", (msg) => {
120
- if (msg.type === "result") {
121
- const text = extractText(msg);
122
- if (text)
123
- output += text;
124
- clearTimeout(timeout);
125
- claude.kill();
126
- resolve(output.trim());
127
- }
128
- else if (msg.type === "assistant") {
129
- const text = extractText(msg);
130
- if (text)
131
- output += text;
132
- }
133
- });
134
- claude.on("error", (err) => {
135
- clearTimeout(timeout);
136
- reject(err);
137
- });
138
- claude.on("exit", (code) => {
139
- clearTimeout(timeout);
140
- if (!output) {
141
- reject(new Error(`Claude exited with code ${code} and no output`));
142
- }
143
- else {
144
- resolve(output.trim());
145
- }
146
- });
147
- claude.sendPrompt(prompt);
148
- });
149
- }
150
- export async function defaultSendTelegramMessage(chatId, text) {
151
- const token = process.env.TELEGRAM_BOT_TOKEN;
152
- if (!token)
153
- throw new Error("TELEGRAM_BOT_TOKEN not set");
154
- const tg = new TelegramBot(token, { polling: false });
155
- await tg.sendMessage(chatId, text);
156
- }
157
- export async function defaultSpawnFollowupAgent(repoUrl, task) {
158
- const token = process.env.CLAUDE_CODE_TOKEN ??
159
- process.env.CLAUDE_CODE_OAUTH_TOKEN ??
160
- process.env.ANTHROPIC_API_KEY;
161
- const prompt = `Use the spawn_agent MCP tool to start a new cc-agent job with these parameters:
162
- repo_url: ${repoUrl}
163
- task: ${task}
164
-
165
- Call the spawn_agent tool now with these exact parameters. Report the job ID when done.`;
166
- return new Promise((resolve) => {
167
- const claude = new ClaudeProcess({ token: token ?? undefined });
168
- const timeout = setTimeout(() => {
169
- log("warn", "spawnFollowupAgent: timed out");
170
- claude.kill();
171
- resolve();
172
- }, 120_000);
173
- claude.on("message", (msg) => {
174
- if (msg.type === "result") {
175
- clearTimeout(timeout);
176
- claude.kill();
177
- resolve();
178
- }
179
- });
180
- claude.on("error", (err) => {
181
- log("error", "spawnFollowupAgent error:", err.message);
182
- clearTimeout(timeout);
183
- resolve();
184
- });
185
- claude.on("exit", () => {
186
- clearTimeout(timeout);
187
- resolve();
188
- });
189
- claude.sendPrompt(prompt);
190
- });
191
- }
192
- function makeRedisClient() {
193
- return new Redis(process.env.REDIS_URL || "redis://localhost:6379", {
194
- lazyConnect: true,
195
- enableOfflineQueue: false,
196
- });
197
- }
198
- export async function defaultReadJobOutput(jobId) {
199
- const redis = makeRedisClient();
200
- try {
201
- await redis.connect();
202
- const lines = await redis.lrange(`cca:job:${jobId}:output`, -40, -1);
203
- return lines;
204
- }
205
- finally {
206
- try {
207
- redis.disconnect();
208
- }
209
- catch { }
210
- }
211
- }
212
- export async function defaultReadCoordinatorPlan(jobId) {
213
- const redis = makeRedisClient();
214
- try {
215
- await redis.connect();
216
- const raw = await redis.get(`cca:coordinator:plan:${jobId}`);
217
- if (!raw)
218
- return null;
219
- return JSON.parse(raw);
220
- }
221
- finally {
222
- try {
223
- redis.disconnect();
224
- }
225
- catch { }
226
- }
227
- }
228
- export async function defaultGetRunningJobCount() {
229
- return 0;
230
- }
231
- /**
232
- * Returns chat IDs to notify about job events.
233
- * Reads unique chatIds from the cron jobs file (same users who set up cron jobs).
234
- * Falls back to CC_AGENT_NOTIFY_CHAT_ID env var for backward compatibility.
235
- */
236
- export async function defaultGetActiveChatIds() {
237
- const ids = new Set();
238
- // Backward compat: explicit env var
239
- const chatIdStr = process.env.CC_AGENT_NOTIFY_CHAT_ID;
240
- if (chatIdStr) {
241
- const chatId = Number(chatIdStr);
242
- if (!isNaN(chatId))
243
- ids.add(chatId);
244
- }
245
- // Read chatIds from cron jobs persistence file
246
- try {
247
- const cwd = process.env.CWD ?? process.cwd();
248
- const cronFile = join(cwd, ".cc-tg", "crons.json");
249
- const raw = readFileSync(cronFile, "utf-8");
250
- const jobs = JSON.parse(raw);
251
- for (const job of jobs) {
252
- if (typeof job.chatId === "number")
253
- ids.add(job.chatId);
254
- }
255
- }
256
- catch {
257
- // file doesn't exist or parse error — ignore
258
- }
259
- return Array.from(ids);
260
- }
261
- /**
262
- * Write a coordinator plan for a job, so cc-tg knows what follow-up to spawn.
263
- * Call this when spawning a job that has a planned follow-up.
264
- * TTL: 7 days.
265
- */
266
- export async function writeCoordinatorPlan(jobId, plan) {
267
- const redis = makeRedisClient();
268
- try {
269
- await redis.connect();
270
- const key = `cca:coordinator:plan:${jobId}`;
271
- const ttlSeconds = 7 * 24 * 60 * 60; // 7 days
272
- await redis.set(key, JSON.stringify(plan), "EX", ttlSeconds);
273
- }
274
- finally {
275
- try {
276
- redis.disconnect();
277
- }
278
- catch { }
279
- }
280
- }
281
- /**
282
- * Handle a single job event message from Redis pub/sub.
283
- * Exported for testability — production code passes defaultDeps.
284
- */
285
- export async function handleJobEvent(message, deps) {
286
- let event;
287
- try {
288
- event = JSON.parse(message);
289
- }
290
- catch (err) {
291
- log("error", "Failed to parse job event:", err.message);
292
- return;
293
- }
294
- // Only act on terminal states
295
- if (event.status !== "done" && event.status !== "failed") {
296
- log("info", `Ignoring ${event.status} event for job ${event.jobId}`);
297
- return;
298
- }
299
- log("info", `Processing ${event.status} event for job: ${event.title} (${event.jobId})`);
300
- // Read job output from Redis (fall back to event.lastLines on error)
301
- let last40lines = event.lastLines;
302
- try {
303
- const lines = await deps.readJobOutput(event.jobId);
304
- if (lines.length > 0)
305
- last40lines = lines;
306
- }
307
- catch (err) {
308
- log("warn", "Failed to read job output, using event.lastLines:", err.message);
309
- }
310
- // Read coordinator plan from Redis (fall back to null on error)
311
- let coordinatorPlan = null;
312
- try {
313
- coordinatorPlan = await deps.readCoordinatorPlan(event.jobId);
314
- }
315
- catch (err) {
316
- log("warn", "Failed to read coordinator plan:", err.message);
317
- }
318
- let decision;
319
- let rawResponse = "";
320
- try {
321
- rawResponse = await deps.askClaude(buildDecisionPrompt(event, last40lines, coordinatorPlan));
322
- decision = parseDecision(rawResponse);
323
- }
324
- catch (err) {
325
- if (rawResponse) {
326
- log("error", "[cc-agent-events] Claude raw response:", rawResponse.slice(0, 200));
327
- }
328
- log("error", "Claude decision failed, falling back to NOTIFY_ONLY:", err.message);
329
- const fallbackMsg = event.status === "failed"
330
- ? formatFailureMessage(event)
331
- : `Job completed: ${event.title}`;
332
- decision = { action: "NOTIFY_ONLY", message: fallbackMsg };
333
- }
334
- log("info", `Decision: ${decision.action} for job ${event.jobId}`);
335
- let chatIds = [];
336
- try {
337
- chatIds = await deps.getActiveChatIds();
338
- }
339
- catch (err) {
340
- log("warn", "Failed to get active chat IDs:", err.message);
341
- }
342
- try {
343
- if (decision.action === "NOTIFY_ONLY") {
344
- if (chatIds.length === 0) {
345
- log("warn", "NOTIFY_ONLY: no active chat IDs, skipping notification");
346
- return;
347
- }
348
- const msg = decision.message
349
- ?? (event.status === "failed" ? formatFailureMessage(event) : `Job completed: ${event.title}`);
350
- for (const chatId of chatIds) {
351
- await deps.sendTelegramMessage(chatId, msg);
352
- }
353
- }
354
- else if (decision.action === "SPAWN_FOLLOWUP") {
355
- if (!decision.followup) {
356
- log("warn", "SPAWN_FOLLOWUP: no followup details in response");
357
- return;
358
- }
359
- await deps.spawnFollowupAgent(decision.followup.repo_url, decision.followup.task);
360
- // Send Telegram notification about the spawn
361
- if (chatIds.length > 0) {
362
- let runningCount = 0;
363
- try {
364
- runningCount = await deps.getRunningJobCount();
365
- }
366
- catch { }
367
- const spawnMsg = formatSpawnMessage(event, decision.followup, runningCount);
368
- for (const chatId of chatIds) {
369
- await deps.sendTelegramMessage(chatId, spawnMsg);
370
- }
371
- }
372
- }
373
- else {
374
- // SILENT — log only
375
- log("info", `SILENT: no action taken for job ${event.jobId}`);
376
- }
377
- }
378
- catch (err) {
379
- log("error", `Action ${decision.action} failed:`, err.message);
380
- }
381
- }
382
- function makeDefaultDeps() {
383
- return {
384
- askClaude: defaultAskClaude,
385
- sendTelegramMessage: defaultSendTelegramMessage,
386
- spawnFollowupAgent: defaultSpawnFollowupAgent,
387
- readJobOutput: defaultReadJobOutput,
388
- readCoordinatorPlan: defaultReadCoordinatorPlan,
389
- getRunningJobCount: defaultGetRunningJobCount,
390
- getActiveChatIds: defaultGetActiveChatIds,
391
- };
392
- }
393
- let subscriberClient = null;
394
- /**
395
- * Connect to Redis and subscribe to cca:events.
396
- * Reconnects automatically on disconnect.
397
- * Call once at startup.
398
- */
399
- export async function connectEventSubscriber() {
400
- if (process.env.CC_AGENT_EVENTS_ENABLED === "false") {
401
- log("info", "CC_AGENT_EVENTS_ENABLED=false, skipping subscriber");
402
- return;
403
- }
404
- await connectWithBackoff(0);
405
- }
406
- async function connectWithBackoff(attempt) {
407
- const delay = Math.min(5_000 * Math.pow(2, attempt), 60_000);
408
- const sub = new Redis(process.env.REDIS_URL || "redis://localhost:6379", {
409
- lazyConnect: true,
410
- enableOfflineQueue: false,
411
- });
412
- subscriberClient = sub;
413
- sub.on("error", (err) => {
414
- log("warn", "subscriber error, reconnecting...", err.message);
415
- try {
416
- sub.disconnect();
417
- }
418
- catch { }
419
- setTimeout(() => connectWithBackoff(0), 5_000);
420
- });
421
- try {
422
- await sub.connect();
423
- }
424
- catch (err) {
425
- log("warn", `Redis connect failed (attempt ${attempt}), retrying in ${delay}ms:`, err.message);
426
- try {
427
- sub.disconnect();
428
- }
429
- catch { }
430
- setTimeout(() => connectWithBackoff(attempt + 1), delay);
431
- return;
432
- }
433
- const deps = makeDefaultDeps();
434
- sub.on("message", (channel, message) => {
435
- if (channel !== "cca:events")
436
- return;
437
- handleJobEvent(message, deps).catch((err) => {
438
- log("error", "handleJobEvent uncaught:", err.message);
439
- });
440
- });
441
- try {
442
- await sub.subscribe("cca:events");
443
- log("info", "Subscribed to cca:events");
444
- }
445
- catch (err) {
446
- log("warn", "subscribe failed, retrying...", err.message);
447
- try {
448
- sub.disconnect();
449
- }
450
- catch { }
451
- setTimeout(() => connectWithBackoff(attempt + 1), delay);
452
- return;
453
- }
454
- const cleanup = async () => {
455
- log("info", "SIGTERM received, shutting down event subscriber...");
456
- try {
457
- await sub.unsubscribe("cca:events");
458
- sub.disconnect();
459
- }
460
- catch { }
461
- };
462
- process.once("SIGTERM", () => { cleanup().catch(() => { }); });
463
- }
package/dist/claude.d.ts DELETED
@@ -1,54 +0,0 @@
1
- /**
2
- * Claude Code subprocess wrapper.
3
- * Mirrors ce_ce's mechanism: spawn `claude` CLI with stream-json I/O,
4
- * pipe prompts in, parse streaming JSON messages out.
5
- */
6
- import { EventEmitter } from "events";
7
- export type MessageType = "system" | "assistant" | "user" | "result";
8
- export interface ClaudeMessage {
9
- type: MessageType;
10
- session_id?: string;
11
- uuid?: string;
12
- payload: Record<string, unknown>;
13
- raw: Record<string, unknown>;
14
- }
15
- export interface ClaudeOptions {
16
- cwd?: string;
17
- systemPrompt?: string;
18
- /** OAuth token (sk-ant-oat01-...) or API key (sk-ant-api03-...) */
19
- token?: string;
20
- }
21
- export interface UsageEvent {
22
- inputTokens: number;
23
- outputTokens: number;
24
- cacheReadTokens: number;
25
- cacheWriteTokens: number;
26
- }
27
- export declare interface ClaudeProcess {
28
- on(event: "message", listener: (msg: ClaudeMessage) => void): this;
29
- on(event: "usage", listener: (usage: UsageEvent) => void): this;
30
- on(event: "error", listener: (err: Error) => void): this;
31
- on(event: "exit", listener: (code: number | null) => void): this;
32
- on(event: "stderr", listener: (data: string) => void): this;
33
- }
34
- export declare class ClaudeProcess extends EventEmitter {
35
- private proc;
36
- private buffer;
37
- private _exited;
38
- constructor(opts?: ClaudeOptions);
39
- sendPrompt(text: string): void;
40
- /**
41
- * Send an image (with optional text caption) to Claude via stream-json content blocks.
42
- * mediaType: image/jpeg | image/png | image/gif | image/webp
43
- */
44
- sendImage(base64Data: string, mediaType: string, caption?: string): void;
45
- kill(): void;
46
- get exited(): boolean;
47
- private drainBuffer;
48
- private parseMessage;
49
- }
50
- /**
51
- * Extract the text content from an assistant message payload.
52
- * Handles both simple string content and content-block arrays.
53
- */
54
- export declare function extractText(msg: ClaudeMessage): string;