@gonzih/cc-tg 0.9.42 → 0.9.43

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # cc-tg
2
2
 
3
- <img src="assets/logo.png" alt="cc-tg" width="120">
3
+ <img src="assets/logo.png" alt="AMAI" width="120">
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@gonzih/cc-tg)](https://www.npmjs.com/package/@gonzih/cc-tg)
6
6
 
package/dist/bot.d.ts CHANGED
@@ -27,8 +27,6 @@ export declare class CcTgBot {
27
27
  private namespace;
28
28
  private lastActiveChatId?;
29
29
  private cron;
30
- /** In-memory cache of forum topic names: `${chatId}:${threadId}` → topic name */
31
- private topicNameCache;
32
30
  constructor(opts: BotOptions);
33
31
  private registerBotCommands;
34
32
  /** Write a message to the Redis chat log. Fire-and-forget — no-op if Redis is not configured. */
@@ -45,13 +43,6 @@ export declare class CcTgBot {
45
43
  private replyToChat;
46
44
  /** Parse THREAD_CWD_MAP env var — maps thread name or thread_id to a CWD path */
47
45
  private getThreadCwdMap;
48
- /**
49
- * Parse FORUM_META_AGENT_ROUTING env var.
50
- * "auto" (default) → route all forum topics to meta-agents
51
- * "off" → disable forum routing entirely
52
- * "topic-a,topic-b" → only route these named topics
53
- */
54
- private getForumRoutingConfig;
55
46
  private isAllowed;
56
47
  private handleTelegram;
57
48
  /**
@@ -94,15 +85,4 @@ export declare class CcTgBot {
94
85
  export declare function enrichPromptWithUrls(text: string): Promise<string>;
95
86
  /** List available skills from ~/.claude/skills/ */
96
87
  export declare function listSkills(): string;
97
- /**
98
- * Normalize a Telegram forum topic name into a meta-agent namespace.
99
- * Rules: strip leading #, lowercase, spaces → hyphens, non-alphanumeric → hyphens,
100
- * collapse and trim hyphens.
101
- *
102
- * Examples:
103
- * "CC Suite" → "cc-suite"
104
- * "#research" → "research"
105
- * "of-stack" → "of-stack"
106
- */
107
- export declare function normalizeTopicNamespace(name: string): string;
108
88
  export declare function splitMessage(text: string, maxLen?: number): string[];
package/dist/bot.js CHANGED
@@ -16,7 +16,6 @@ import { detectUsageLimit } from "./usage-limit.js";
16
16
  import { getCurrentToken, rotateToken, getTokenIndex, getTokenCount } from "./tokens.js";
17
17
  import { writeChatLog } from "./notifier.js";
18
18
  import { CronManager } from "./cron.js";
19
- import { parseRoutingTag, ensureMetaAgent, routeToMetaAgent } from "./router.js";
20
19
  const BOT_COMMANDS = [
21
20
  { command: "start", description: "Reset session and start fresh" },
22
21
  { command: "reset", description: "Reset Claude session" },
@@ -36,8 +35,7 @@ const BOT_COMMANDS = [
36
35
  { command: "drivers", description: "List available agent drivers" },
37
36
  { command: "agents", description: "Show running meta-agents and their live status" },
38
37
  ];
39
- // Debounces streaming chunks. Resets on each chunk. Fires 800ms after last chunk.
40
- const FLUSH_DELAY_MS = 800;
38
+ const FLUSH_DELAY_MS = 800; // debounce streaming chunks into one Telegram message
41
39
  const TYPING_INTERVAL_MS = 4000; // re-send typing action before Telegram's 5s expiry
42
40
  // Claude Sonnet 4.6 pricing (per 1M tokens)
43
41
  const PRICING = {
@@ -176,8 +174,6 @@ export class CcTgBot {
176
174
  namespace;
177
175
  lastActiveChatId;
178
176
  cron;
179
- /** In-memory cache of forum topic names: `${chatId}:${threadId}` → topic name */
180
- topicNameCache = new Map();
181
177
  constructor(opts) {
182
178
  this.opts = opts;
183
179
  this.redis = opts.redis;
@@ -208,7 +204,7 @@ export class CcTgBot {
208
204
  if (!this.redis)
209
205
  return;
210
206
  const msg = {
211
- id: crypto.randomUUID(),
207
+ id: `${source}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
212
208
  source,
213
209
  role,
214
210
  content,
@@ -252,20 +248,6 @@ export class CcTgBot {
252
248
  return {};
253
249
  }
254
250
  }
255
- /**
256
- * Parse FORUM_META_AGENT_ROUTING env var.
257
- * "auto" (default) → route all forum topics to meta-agents
258
- * "off" → disable forum routing entirely
259
- * "topic-a,topic-b" → only route these named topics
260
- */
261
- getForumRoutingConfig() {
262
- const raw = process.env.FORUM_META_AGENT_ROUTING;
263
- if (!raw || raw === "auto")
264
- return "auto";
265
- if (raw === "off")
266
- return "off";
267
- return new Set(raw.split(",").map((s) => s.trim()).filter(Boolean));
268
- }
269
251
  isAllowed(userId) {
270
252
  if (!this.opts.allowedUserIds?.length)
271
253
  return true;
@@ -282,26 +264,6 @@ export class CcTgBot {
282
264
  const threadName = rawMsg.forum_topic_created
283
265
  ? rawMsg.forum_topic_created.name
284
266
  : undefined;
285
- // Cache forum topic names from service messages so routing can look them up later
286
- if (threadId !== undefined) {
287
- if (threadName) {
288
- this.topicNameCache.set(`${chatId}:${threadId}`, threadName);
289
- }
290
- // forum_topic_edited carries name only when the name was changed
291
- const editedTopicName = rawMsg.forum_topic_edited?.name;
292
- if (editedTopicName) {
293
- this.topicNameCache.set(`${chatId}:${threadId}`, editedTopicName);
294
- }
295
- // Best-effort: first message in a topic often has reply_to_message pointing to the creation event
296
- if (!this.topicNameCache.has(`${chatId}:${threadId}`)) {
297
- const replyRaw = msg.reply_to_message;
298
- const replyCreated = replyRaw?.forum_topic_created;
299
- const replyName = replyCreated?.name;
300
- if (replyName) {
301
- this.topicNameCache.set(`${chatId}:${threadId}`, replyName);
302
- }
303
- }
304
- }
305
267
  if (!this.isAllowed(userId)) {
306
268
  await this.replyToChat(chatId, "Not authorized.", threadId);
307
269
  return;
@@ -447,48 +409,6 @@ export class CcTgBot {
447
409
  await this.handleAgents(chatId, threadId);
448
410
  return;
449
411
  }
450
- // #tag / #org/repo routing — delegate to meta-agent instead of local Claude session
451
- if (this.redis) {
452
- const routing = parseRoutingTag(text);
453
- if (routing) {
454
- // Acknowledge routing immediately so user knows the message was delegated
455
- await this.replyToChat(chatId, `→ #${routing.namespace}`, threadId);
456
- this.writeChatMessage("user", "telegram", text, chatId);
457
- try {
458
- await ensureMetaAgent(routing.namespace, routing.repoUrl, (toolName, args) => this.callCcAgentTool(toolName, args ?? {}), this.redis);
459
- await routeToMetaAgent(routing.namespace, routing.strippedMessage, this.redis);
460
- }
461
- catch (err) {
462
- await this.replyToChat(chatId, `Failed to route to #${routing.namespace}: ${err.message}`, threadId);
463
- }
464
- return;
465
- }
466
- }
467
- // Forum topic → meta-agent routing (runs after hashtag routing so explicit #tag wins)
468
- if (this.redis && threadId !== undefined) {
469
- const topicKey = `${chatId}:${threadId}`;
470
- const topicName = this.topicNameCache.get(topicKey);
471
- if (topicName) {
472
- const namespace = normalizeTopicNamespace(topicName);
473
- const routingConfig = this.getForumRoutingConfig();
474
- const shouldRoute = routingConfig === "auto" ||
475
- (routingConfig instanceof Set && (routingConfig.has(topicName) || routingConfig.has(namespace)));
476
- if (shouldRoute) {
477
- const defaultOrg = process.env.DEFAULT_GITHUB_ORG ?? "gonzih";
478
- const repoUrl = `https://github.com/${defaultOrg}/${namespace}`;
479
- await this.replyToChat(chatId, `→ #${namespace} (meta-agent)`, threadId);
480
- this.writeChatMessage("user", "telegram", text, chatId);
481
- try {
482
- await ensureMetaAgent(namespace, repoUrl, (toolName, args) => this.callCcAgentTool(toolName, args ?? {}), this.redis);
483
- await routeToMetaAgent(namespace, text, this.redis);
484
- }
485
- catch (err) {
486
- await this.replyToChat(chatId, `Failed to route to #${namespace}: ${err.message}`, threadId);
487
- }
488
- return;
489
- }
490
- }
491
- }
492
412
  const session = this.getOrCreateSession(chatId, threadId, threadName);
493
413
  try {
494
414
  const enriched = await enrichPromptWithUrls(text);
@@ -1584,25 +1504,6 @@ export function listSkills() {
1584
1504
  }
1585
1505
  return lines.join("\n");
1586
1506
  }
1587
- /**
1588
- * Normalize a Telegram forum topic name into a meta-agent namespace.
1589
- * Rules: strip leading #, lowercase, spaces → hyphens, non-alphanumeric → hyphens,
1590
- * collapse and trim hyphens.
1591
- *
1592
- * Examples:
1593
- * "CC Suite" → "cc-suite"
1594
- * "#research" → "research"
1595
- * "of-stack" → "of-stack"
1596
- */
1597
- export function normalizeTopicNamespace(name) {
1598
- return name
1599
- .replace(/^#+/, "") // strip leading # prefix
1600
- .toLowerCase()
1601
- .replace(/\s+/g, "-") // spaces → hyphens
1602
- .replace(/[^a-z0-9._-]/g, "-") // non-alphanumeric/non-safe → hyphens
1603
- .replace(/-+/g, "-") // collapse consecutive hyphens
1604
- .replace(/^-|-$/g, ""); // trim leading/trailing hyphens
1605
- }
1606
1507
  export function splitMessage(text, maxLen = 4096) {
1607
1508
  if (text.length <= maxLen)
1608
1509
  return [text];
package/dist/notifier.js CHANGED
@@ -79,7 +79,6 @@ export function writeChatLog(redis, namespace, msg) {
79
79
  const logKey = `cca:chat:log:${namespace}`;
80
80
  const outKey = `cca:chat:outgoing:${namespace}`;
81
81
  const payload = JSON.stringify(msg);
82
- // LIFO — newest first. Consumers must LRANGE 0 N then reverse for chronological order.
83
82
  redis.lpush(logKey, payload).catch((err) => {
84
83
  log("warn", "writeChatLog lpush failed:", err.message);
85
84
  });
@@ -142,9 +141,7 @@ export function startNotifier(bot, chatId, namespace, redis, handleUserMessage,
142
141
  log("info", "psubscribed to cca:chat:outgoing:*");
143
142
  }
144
143
  });
145
- // 1.5s silence buffer. Combined with cc-agent's 3s poll = up to 4.5s meta-agent response latency.
146
- const META_AGENT_FLUSH_DELAY_MS = 1500;
147
- // Per-namespace debounce buffer: accumulate streaming lines, flush after silence
144
+ // Per-namespace debounce buffer: accumulate streaming lines, flush after 1.5s silence
148
145
  const metaAgentBuffers = new Map();
149
146
  function flushMetaAgentBuffer(ns, targetChatId) {
150
147
  const buf = metaAgentBuffers.get(ns);
@@ -188,10 +185,17 @@ export function startNotifier(bot, chatId, namespace, redis, handleUserMessage,
188
185
  buf = { text: "", timer: null };
189
186
  metaAgentBuffers.set(ns, buf);
190
187
  }
191
- buf.text += (buf.text ? "\n" : "") + content;
188
+ // Prefix first line with when message comes from a different namespace (e.g. of-stack)
189
+ const isExternal = ns !== namespace;
190
+ if (!buf.text && isExternal) {
191
+ buf.text = "← " + content;
192
+ }
193
+ else {
194
+ buf.text += (buf.text ? "\n" : "") + content;
195
+ }
192
196
  if (buf.timer)
193
197
  clearTimeout(buf.timer);
194
- buf.timer = setTimeout(() => flushMetaAgentBuffer(ns, targetChatId), META_AGENT_FLUSH_DELAY_MS);
198
+ buf.timer = setTimeout(() => flushMetaAgentBuffer(ns, targetChatId), 1500);
195
199
  });
196
200
  // Poll the cca:notify:{namespace} LIST every 5 seconds.
197
201
  // Jobs push to this list via RPUSH; pub/sub alone won't deliver those messages.
@@ -230,9 +234,6 @@ export function startNotifier(bot, chatId, namespace, redis, handleUserMessage,
230
234
  bot.sendMessage(targetId, text).catch((err) => {
231
235
  log("warn", "notify list sendMessage failed:", err.message);
232
236
  });
233
- if (handleUserMessage) {
234
- handleUserMessage(targetId, text);
235
- }
236
237
  }
237
238
  if (remaining > 0) {
238
239
  bot.sendMessage(targetId, `...and ${remaining} more notifications`).catch((err) => {
@@ -253,9 +254,6 @@ export function startNotifier(bot, chatId, namespace, redis, handleUserMessage,
253
254
  bot.sendMessage(targetId, text).catch((err) => {
254
255
  log("warn", "sendMessage failed:", err.message);
255
256
  });
256
- if (handleUserMessage) {
257
- handleUserMessage(targetId, text);
258
- }
259
257
  }
260
258
  else {
261
259
  log("warn", "notify: no chatId available, dropping notification");
@@ -284,7 +282,7 @@ export function startNotifier(bot, chatId, namespace, redis, handleUserMessage,
284
282
  });
285
283
  // Log the incoming message — preserve original timestamp from UI if present
286
284
  const inMsg = {
287
- id: crypto.randomUUID(),
285
+ id: `ui-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
288
286
  source: "ui", // 'ui' distinguishes this from telegram/claude messages
289
287
  role: "user",
290
288
  content,
@@ -306,8 +304,7 @@ export function startNotifier(bot, chatId, namespace, redis, handleUserMessage,
306
304
  content,
307
305
  timestamp: new Date().toISOString(),
308
306
  });
309
- // Polled by cc-agent every 3s — up to 3s delivery latency
310
- await redis.rpush(`cca:meta:${namespace}:input`, entry);
307
+ await redis.lpush(`cca:meta:${namespace}:input`, entry);
311
308
  log("info", `cca:chat:incoming: routed to meta-agent for namespace ${namespace}`);
312
309
  routedToMetaAgent = true;
313
310
  }
package/dist/tokens.d.ts CHANGED
@@ -3,8 +3,6 @@
3
3
  *
4
4
  * Supports CLAUDE_CODE_OAUTH_TOKENS (comma-separated list of tokens).
5
5
  * Falls back to CLAUDE_CODE_OAUTH_TOKEN for single-token / backwards compat.
6
- *
7
- * cc-tg token pool rotates independently from cc-agent's pool. No coordination between them.
8
6
  */
9
7
  /**
10
8
  * Load tokens from env vars. Called on startup; also re-callable in tests.
package/dist/tokens.js CHANGED
@@ -3,8 +3,6 @@
3
3
  *
4
4
  * Supports CLAUDE_CODE_OAUTH_TOKENS (comma-separated list of tokens).
5
5
  * Falls back to CLAUDE_CODE_OAUTH_TOKEN for single-token / backwards compat.
6
- *
7
- * cc-tg token pool rotates independently from cc-agent's pool. No coordination between them.
8
6
  */
9
7
  let tokens = [];
10
8
  let currentIndex = 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gonzih/cc-tg",
3
- "version": "0.9.42",
3
+ "version": "0.9.43",
4
4
  "description": "Claude Code Telegram bot — chat with Claude Code via Telegram",
5
5
  "type": "module",
6
6
  "bin": {
package/LICENSE DELETED
@@ -1,203 +0,0 @@
1
- Copyright 2026 Maksim Soltan
2
-
3
- Apache License
4
- Version 2.0, January 2004
5
- http://www.apache.org/licenses/
6
-
7
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
-
9
- 1. Definitions.
10
-
11
- "License" shall mean the terms and conditions for use, reproduction,
12
- and distribution as defined by Sections 1 through 9 of this document.
13
-
14
- "Licensor" shall mean the copyright owner or entity authorized by
15
- the copyright owner that is granting the License.
16
-
17
- "Legal Entity" shall mean the union of the acting entity and all
18
- other entities that control, are controlled by, or are under common
19
- control with that entity. For the purposes of this definition,
20
- "control" means (i) the power, direct or indirect, to cause the
21
- direction or management of such entity, whether by contract or
22
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
- outstanding shares, or (iii) beneficial ownership of such entity.
24
-
25
- "You" (or "Your") shall mean an individual or Legal Entity
26
- exercising permissions granted by this License.
27
-
28
- "Source" form shall mean the preferred form for making modifications,
29
- including but not limited to software source code, documentation
30
- source, and configuration files.
31
-
32
- "Object" form shall mean any form resulting from mechanical
33
- transformation or translation of a Source form, including but
34
- not limited to compiled object code, generated documentation,
35
- and conversions to other media types.
36
-
37
- "Work" shall mean the work of authorship, whether in Source or
38
- Object form, made available under the License, as indicated by a
39
- copyright notice that is included in or attached to the work
40
- (an example is provided in the Appendix below).
41
-
42
- "Derivative Works" shall mean any work, whether in Source or Object
43
- form, that is based on (or derived from) the Work and for which the
44
- editorial revisions, annotations, elaborations, or other modifications
45
- represent, as a whole, an original work of authorship. For the purposes
46
- of this License, Derivative Works shall not include works that remain
47
- separable from, or merely link (or bind by name) to the interfaces of,
48
- the Work and Derivative Works thereof.
49
-
50
- "Contribution" shall mean any work of authorship, including
51
- the original version of the Work and any modifications or additions
52
- to that Work or Derivative Works thereof, that is intentionally
53
- submitted to Licensor for inclusion in the Work by the copyright owner
54
- or by an individual or Legal Entity authorized to submit on behalf of
55
- the copyright owner. For the purposes of this definition, "submitted"
56
- means any form of electronic, verbal, or written communication sent
57
- to the Licensor or its representatives, including but not limited to
58
- communication on electronic mailing lists, source code control systems,
59
- and issue tracking systems that are managed by, or on behalf of, the
60
- Licensor for the purpose of discussing and improving the Work, but
61
- excluding communication that is conspicuously marked or otherwise
62
- designated in writing by the copyright owner as "Not a Contribution."
63
-
64
- "Contributor" shall mean Licensor and any individual or Legal Entity
65
- on behalf of whom a Contribution has been received by Licensor and
66
- subsequently incorporated within the Work.
67
-
68
- 2. Grant of Copyright License. Subject to the terms and conditions of
69
- this License, each Contributor hereby grants to You a perpetual,
70
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
- copyright license to reproduce, prepare Derivative Works of,
72
- publicly display, publicly perform, sublicense, and distribute the
73
- Work and such Derivative Works in Source or Object form.
74
-
75
- 3. Grant of Patent License. Subject to the terms and conditions of
76
- this License, each Contributor hereby grants to You a perpetual,
77
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
- (except as stated in this section) patent license to make, have made,
79
- use, offer to sell, sell, import, and otherwise transfer the Work,
80
- where such license applies only to those patent claims licensable
81
- by such Contributor that are necessarily infringed by their
82
- Contribution(s) alone or by combination of their Contribution(s)
83
- with the Work to which such Contribution(s) was submitted. If You
84
- institute patent litigation against any entity (including a
85
- cross-claim or counterclaim in a lawsuit) alleging that the Work
86
- or a Contribution incorporated within the Work constitutes direct
87
- or contributory patent infringement, then any patent licenses
88
- granted to You under this License for that Work shall terminate
89
- as of the date such litigation is filed.
90
-
91
- 4. Redistribution. You may reproduce and distribute copies of the
92
- Work or Derivative Works thereof in any medium, with or without
93
- modifications, and in Source or Object form, provided that You
94
- meet the following conditions:
95
-
96
- (a) You must give any other recipients of the Work or
97
- Derivative Works a copy of this License; and
98
-
99
- (b) You must cause any modified files to carry prominent notices
100
- stating that You changed the files; and
101
-
102
- (c) You must retain, in the Source form of any Derivative Works
103
- that You distribute, all copyright, patent, trademark, and
104
- attribution notices from the Source form of the Work,
105
- excluding those notices that do not pertain to any part of
106
- the Derivative Works; and
107
-
108
- (d) If the Work includes a "NOTICE" text file as part of its
109
- distribution, then any Derivative Works that You distribute must
110
- include a readable copy of the attribution notices contained
111
- within such NOTICE file, excluding those notices that do not
112
- pertain to any part of the Derivative Works, in at least one
113
- of the following places: within a NOTICE text file distributed
114
- as part of the Derivative Works; within the Source form or
115
- documentation, if provided along with the Derivative Works; or,
116
- within a display generated by the Derivative Works, if and
117
- wherever such third-party notices normally appear. The contents
118
- of the NOTICE file are for informational purposes only and
119
- do not modify the License. You may add Your own attribution
120
- notices within Derivative Works that You distribute, alongside
121
- or as an addendum to the NOTICE text from the Work, provided
122
- that such additional attribution notices cannot be construed
123
- as modifying the License.
124
-
125
- You may add Your own copyright statement to Your modifications and
126
- may provide additional or different license terms and conditions
127
- for use, reproduction, or distribution of Your modifications, or
128
- for any such Derivative Works as a whole, provided Your use,
129
- reproduction, and distribution of the Work otherwise complies with
130
- the conditions stated in this License.
131
-
132
- 5. Submission of Contributions. Unless You explicitly state otherwise,
133
- any Contribution intentionally submitted for inclusion in the Work
134
- by You to the Licensor shall be under the terms and conditions of
135
- this License, without any additional terms or conditions.
136
- Notwithstanding the above, nothing herein shall supersede or modify
137
- the terms of any separate license agreement you may have executed
138
- with Licensor regarding such Contributions.
139
-
140
- 6. Trademarks. This License does not grant permission to use the trade
141
- names, trademarks, service marks, or product names of the Licensor,
142
- except as required for reasonable and customary use in describing the
143
- origin of the Work and reproducing the content of the NOTICE file.
144
-
145
- 7. Disclaimer of Warranty. Unless required by applicable law or
146
- agreed to in writing, Licensor provides the Work (and each
147
- Contributor provides its Contributions) on an "AS IS" BASIS,
148
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
- implied, including, without limitation, any warranties or conditions
150
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
- PARTICULAR PURPOSE. You are solely responsible for determining the
152
- appropriateness of using or redistributing the Work and assume any
153
- risks associated with Your exercise of permissions under this License.
154
-
155
- 8. Limitation of Liability. In no event and under no legal theory,
156
- whether in tort (including negligence), contract, or otherwise,
157
- unless required by applicable law (such as deliberate and grossly
158
- negligent acts) or agreed to in writing, shall any Contributor be
159
- liable to You for damages, including any direct, indirect, special,
160
- incidental, or exemplary damages of any character arising as a
161
- result of this License or out of the use or inability to use the
162
- Work (including but not limited to damages for loss of goodwill,
163
- work stoppage, computer failure or malfunction, or any and all
164
- other commercial damages or losses), even if such Contributor
165
- has been advised of the possibility of such damages.
166
-
167
- 9. Accepting Warranty or Additional Liability. While redistributing
168
- the Work or Derivative Works thereof, You may choose to offer,
169
- and charge a fee for, acceptance of support, warranty, indemnity,
170
- or other liability obligations and/or rights consistent with this
171
- License. However, in accepting such obligations, You may act only
172
- on Your own behalf and on Your sole responsibility, not on behalf
173
- of any other Contributor, and only if You agree to indemnify,
174
- defend, and hold each Contributor harmless for any liability
175
- incurred by, or claims asserted against, such Contributor by reason
176
- of your accepting any such warranty or additional liability.
177
-
178
- END OF TERMS AND CONDITIONS
179
-
180
- APPENDIX: How to apply the Apache License to your work.
181
-
182
- To apply the Apache License to your work, attach the following
183
- boilerplate notice, with the fields enclosed by brackets "[]"
184
- replaced with your own identifying information. (Don't include
185
- the brackets!) The text should be enclosed in the appropriate
186
- comment syntax for the file format. We also recommend that a
187
- file or class name and description of purpose be included on the
188
- same "printed page" as the copyright notice for easier
189
- identification within third-party archives.
190
-
191
- Copyright [yyyy] [name of copyright owner]
192
-
193
- Licensed under the Apache License, Version 2.0 (the "License");
194
- you may not use this file except in compliance with the License.
195
- You may obtain a copy of the License at
196
-
197
- http://www.apache.org/licenses/LICENSE-2.0
198
-
199
- Unless required by applicable law or agreed to in writing, software
200
- distributed under the License is distributed on an "AS IS" BASIS,
201
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
- See the License for the specific language governing permissions and
203
- limitations under the License.
package/dist/router.d.ts DELETED
@@ -1,59 +0,0 @@
1
- /**
2
- * Hashtag meta-agent routing.
3
- *
4
- * Parses #tag or #org/repo tokens from Telegram messages and routes them to
5
- * the appropriate cc-agent meta-agent instead of the local Claude session.
6
- *
7
- * Tag formats:
8
- * #repo-name → namespace=repo-name, repo=https://github.com/{DEFAULT_GITHUB_ORG}/repo-name (null if DEFAULT_GITHUB_ORG unset)
9
- * #org/repo → namespace=repo, repo=https://github.com/org/repo
10
- */
11
- import { Redis } from "ioredis";
12
- /** Callback type matching CcTgBot.callCcAgentTool */
13
- export type CallToolFn = (toolName: string, args?: Record<string, unknown>) => Promise<string | null>;
14
- export interface RoutingTag {
15
- namespace: string;
16
- repoUrl: string;
17
- /** Original message with the tag token stripped and whitespace collapsed */
18
- strippedMessage: string;
19
- }
20
- /**
21
- * Parse the first #tag or #org/repo token from a message.
22
- * Returns null when no routing tag is present, or when the short #repo format is used
23
- * without DEFAULT_GITHUB_ORG being set (operators must configure this explicitly).
24
- *
25
- * Examples:
26
- * "#cc-agent fix the bug" → null if DEFAULT_GITHUB_ORG unset; { namespace: "cc-agent", repoUrl: "…/{org}/cc-agent", … } if set
27
- * "#gonzih/of-stack deploy it" → { namespace: "of-stack", repoUrl: "…/gonzih/of-stack", … }
28
- * "#org/repo do something" → { namespace: "repo", repoUrl: "…/org/repo", … }
29
- * "please help #of-stack with this" → null if DEFAULT_GITHUB_ORG unset
30
- */
31
- export declare function parseRoutingTag(text: string): RoutingTag | null;
32
- /**
33
- * Ensure a meta-agent for the given namespace is running.
34
- *
35
- * Steps:
36
- * 1. Check Redis for readiness via two keys (see below) — return early if already ready.
37
- * 2. Verify the GitHub repo exists; create it (public) if not.
38
- * 3. Call the start_meta_agent MCP tool via callTool.
39
- * 4. Poll both Redis keys every 1s until ready or META_AGENT_TIMEOUT_MS expires.
40
- *
41
- * Two Redis keys are checked:
42
- * cca:meta-agent:status:{namespace} — live-status key written by writeLiveStatus()
43
- * (only populated after the first message is processed by messageMetaAgent)
44
- * cca:meta:{namespace} — state key written by startMetaAgent() directly via saveState()
45
- * (populated as soon as the workspace is created, with status:"idle")
46
- *
47
- * Bug context: start_meta_agent writes cca:meta:{namespace} but NOT cca:meta-agent:status:{namespace}.
48
- * Polling only the status key caused a 10s timeout on every cold start.
49
- *
50
- * Throws on failure (repo creation error, tool call failure, or timeout).
51
- */
52
- export declare function ensureMetaAgent(namespace: string, repoUrl: string, callTool: CallToolFn, redis: Redis): Promise<void>;
53
- /**
54
- * Route a message to a running meta-agent via Redis RPUSH.
55
- * The cc-agent polls cca:meta:{namespace}:input every 3s (up to 3s delivery latency).
56
- *
57
- * No-op when strippedMessage is empty (user sent only the tag token).
58
- */
59
- export declare function routeToMetaAgent(namespace: string, strippedMessage: string, redis: Redis): Promise<void>;
package/dist/router.js DELETED
@@ -1,192 +0,0 @@
1
- /**
2
- * Hashtag meta-agent routing.
3
- *
4
- * Parses #tag or #org/repo tokens from Telegram messages and routes them to
5
- * the appropriate cc-agent meta-agent instead of the local Claude session.
6
- *
7
- * Tag formats:
8
- * #repo-name → namespace=repo-name, repo=https://github.com/{DEFAULT_GITHUB_ORG}/repo-name (null if DEFAULT_GITHUB_ORG unset)
9
- * #org/repo → namespace=repo, repo=https://github.com/org/repo
10
- */
11
- import { execSync } from "child_process";
12
- /**
13
- * Parse the first #tag or #org/repo token from a message.
14
- * Returns null when no routing tag is present, or when the short #repo format is used
15
- * without DEFAULT_GITHUB_ORG being set (operators must configure this explicitly).
16
- *
17
- * Examples:
18
- * "#cc-agent fix the bug" → null if DEFAULT_GITHUB_ORG unset; { namespace: "cc-agent", repoUrl: "…/{org}/cc-agent", … } if set
19
- * "#gonzih/of-stack deploy it" → { namespace: "of-stack", repoUrl: "…/gonzih/of-stack", … }
20
- * "#org/repo do something" → { namespace: "repo", repoUrl: "…/org/repo", … }
21
- * "please help #of-stack with this" → null if DEFAULT_GITHUB_ORG unset
22
- */
23
- export function parseRoutingTag(text) {
24
- const defaultOrg = process.env.DEFAULT_GITHUB_ORG;
25
- // Match #word or #org/repo — each segment: starts with alphanumeric, allows ._- inside
26
- const match = text.match(/#([a-zA-Z0-9][a-zA-Z0-9._-]*)(?:\/([a-zA-Z0-9][a-zA-Z0-9._-]*))?/);
27
- if (!match)
28
- return null;
29
- const fullMatch = match[0]; // e.g. "#gonzih/of-stack"
30
- const part1 = match[1]; // org-or-repo
31
- const part2 = match[2]; // repo (only present in #org/repo format)
32
- let namespace;
33
- let repoUrl;
34
- if (part2) {
35
- // #org/repo format
36
- namespace = part2;
37
- repoUrl = `https://github.com/${part1}/${part2}`;
38
- }
39
- else {
40
- // #repo format — requires DEFAULT_GITHUB_ORG; return null if unset
41
- if (!defaultOrg)
42
- return null;
43
- namespace = part1;
44
- repoUrl = `https://github.com/${defaultOrg}/${part1}`;
45
- }
46
- // Strip the matched tag token and collapse whitespace
47
- const strippedMessage = text.replace(fullMatch, "").replace(/\s+/g, " ").trim();
48
- return { namespace, repoUrl, strippedMessage };
49
- }
50
- /**
51
- * Ensure a meta-agent for the given namespace is running.
52
- *
53
- * Steps:
54
- * 1. Check Redis for readiness via two keys (see below) — return early if already ready.
55
- * 2. Verify the GitHub repo exists; create it (public) if not.
56
- * 3. Call the start_meta_agent MCP tool via callTool.
57
- * 4. Poll both Redis keys every 1s until ready or META_AGENT_TIMEOUT_MS expires.
58
- *
59
- * Two Redis keys are checked:
60
- * cca:meta-agent:status:{namespace} — live-status key written by writeLiveStatus()
61
- * (only populated after the first message is processed by messageMetaAgent)
62
- * cca:meta:{namespace} — state key written by startMetaAgent() directly via saveState()
63
- * (populated as soon as the workspace is created, with status:"idle")
64
- *
65
- * Bug context: start_meta_agent writes cca:meta:{namespace} but NOT cca:meta-agent:status:{namespace}.
66
- * Polling only the status key caused a 10s timeout on every cold start.
67
- *
68
- * Throws on failure (repo creation error, tool call failure, or timeout).
69
- */
70
- export async function ensureMetaAgent(namespace, repoUrl, callTool, redis) {
71
- const timeoutMs = parseInt(process.env.META_AGENT_TIMEOUT_MS ?? "10000", 10);
72
- const statusKey = `cca:meta-agent:status:${namespace}`;
73
- // State key written by startMetaAgent() directly — the source of truth for workspace existence.
74
- const stateKey = `cca:meta:${namespace}`;
75
- console.log(`[router] ensureMetaAgent namespace=${namespace}`);
76
- // Fast path: check live-status key (written by messageMetaAgent after first message)
77
- const statusRaw = await redis.get(statusKey);
78
- if (statusRaw) {
79
- try {
80
- const status = JSON.parse(statusRaw);
81
- if (status.status === "running" || status.status === "idle") {
82
- console.log(`[router] meta-agent ${namespace} is already ready (status=${status.status})`);
83
- return;
84
- }
85
- }
86
- catch {
87
- // Corrupt status value — fall through
88
- }
89
- }
90
- // Fast path: also check state key (written by startMetaAgent, persists 30 days).
91
- // Presence of this key means the workspace was already created — no need to re-run start_meta_agent.
92
- const stateRaw = await redis.get(stateKey);
93
- if (stateRaw) {
94
- try {
95
- const state = JSON.parse(stateRaw);
96
- if (state.status === "idle" || state.status === "running") {
97
- console.log(`[router] meta-agent ${namespace} workspace exists (state.status=${state.status})`);
98
- return;
99
- }
100
- }
101
- catch {
102
- // Corrupt state — fall through and re-initialize
103
- }
104
- }
105
- // Derive "org/repo" from the full URL for gh CLI calls
106
- const orgRepo = repoUrl.replace(/^https:\/\/github\.com\//, "");
107
- // Verify / create the GitHub repo
108
- try {
109
- execSync(`gh repo view ${orgRepo}`, { stdio: "ignore" });
110
- }
111
- catch {
112
- // Repo not found — create it
113
- try {
114
- execSync(`gh repo create ${orgRepo} --public --description "Meta-agent workspace for ${namespace}"`, { stdio: "pipe" });
115
- console.log(`[router] created repo ${orgRepo} for namespace=${namespace}`);
116
- }
117
- catch (createErr) {
118
- throw new Error(`Failed to create repo ${orgRepo}: ${createErr.message}`);
119
- }
120
- }
121
- // Start the meta-agent via MCP (clones workspace if needed, writes cca:meta:{namespace})
122
- const result = await callTool("start_meta_agent", { namespace, repo_url: repoUrl });
123
- if (result === null) {
124
- throw new Error(`start_meta_agent returned null — tool may not be available in cc-agent`);
125
- }
126
- // Check for explicit failure payload (e.g. git clone error)
127
- try {
128
- const parsed = JSON.parse(result);
129
- if (parsed.ok === false) {
130
- throw new Error(`start_meta_agent failed: ${parsed.error ?? "unknown error"}`);
131
- }
132
- }
133
- catch (jsonErr) {
134
- if (!(jsonErr instanceof SyntaxError))
135
- throw jsonErr;
136
- // Non-JSON result (e.g. plain "ok") — not an error, continue to poll
137
- }
138
- // Poll until ready. Check both keys:
139
- // - statusKey: written by writeLiveStatus() during messageMetaAgent (may not exist yet on cold start)
140
- // - stateKey: written by startMetaAgent() above — will appear within 1s of the tool call returning
141
- const deadline = Date.now() + timeoutMs;
142
- while (Date.now() < deadline) {
143
- await new Promise((resolve) => setTimeout(resolve, 1000));
144
- const raw = await redis.get(statusKey);
145
- if (raw) {
146
- try {
147
- const s = JSON.parse(raw);
148
- console.log(`[router] waiting for meta-agent ${namespace} — status key: ${s.status}`);
149
- if (s.status === "running" || s.status === "idle")
150
- return;
151
- }
152
- catch {
153
- // ignore parse errors, keep polling
154
- }
155
- }
156
- // Also check state key — startMetaAgent writes this synchronously before responding
157
- const state = await redis.get(stateKey);
158
- if (state) {
159
- try {
160
- const s = JSON.parse(state);
161
- console.log(`[router] waiting for meta-agent ${namespace} — state key: ${s.status}`);
162
- if (s.status === "idle" || s.status === "running")
163
- return;
164
- }
165
- catch {
166
- // ignore parse errors, keep polling
167
- }
168
- }
169
- else {
170
- console.log(`[router] waiting for meta-agent ${namespace} — neither key present yet`);
171
- }
172
- }
173
- throw new Error(`Meta-agent for ${namespace} did not become ready within ${timeoutMs}ms`);
174
- }
175
- /**
176
- * Route a message to a running meta-agent via Redis RPUSH.
177
- * The cc-agent polls cca:meta:{namespace}:input every 3s (up to 3s delivery latency).
178
- *
179
- * No-op when strippedMessage is empty (user sent only the tag token).
180
- */
181
- export async function routeToMetaAgent(namespace, strippedMessage, redis) {
182
- if (!strippedMessage)
183
- return;
184
- const entry = JSON.stringify({
185
- id: crypto.randomUUID(),
186
- content: strippedMessage,
187
- timestamp: new Date().toISOString(),
188
- });
189
- // FIFO — cc-agent reads via LPOP
190
- await redis.rpush(`cca:meta:${namespace}:input`, entry);
191
- console.log(`[router] routed message to meta-agent namespace=${namespace}`);
192
- }