@gonzih/cc-discord 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bot.d.ts +89 -0
- package/dist/bot.js +851 -0
- package/dist/claude.d.ts +54 -0
- package/dist/claude.js +208 -0
- package/dist/cron.d.ts +39 -0
- package/dist/cron.js +148 -0
- package/dist/formatter.d.ts +25 -0
- package/dist/formatter.js +100 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +107 -0
- package/dist/notifier.d.ts +59 -0
- package/dist/notifier.js +334 -0
- package/dist/router.d.ts +47 -0
- package/dist/router.js +165 -0
- package/dist/tokens.d.ts +24 -0
- package/dist/tokens.js +58 -0
- package/dist/voice.d.ts +13 -0
- package/dist/voice.js +142 -0
- package/package.json +1 -1
package/dist/index.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* cc-discord — Claude Code Discord bot
|
|
4
|
+
*
|
|
5
|
+
* Usage:
|
|
6
|
+
* npx @gonzih/cc-discord
|
|
7
|
+
*
|
|
8
|
+
* Required env:
|
|
9
|
+
* DISCORD_BOT_TOKEN — from Discord Developer Portal
|
|
10
|
+
* CLAUDE_CODE_OAUTH_TOKEN — your Claude Code OAuth token (or ANTHROPIC_API_KEY)
|
|
11
|
+
*
|
|
12
|
+
* Optional env:
|
|
13
|
+
* DISCORD_GUILD_IDS — comma-separated Discord guild/server IDs (for instant slash command registration)
|
|
14
|
+
* DISCORD_ALLOWED_USER_IDS — comma-separated Discord user IDs to whitelist (leave empty to allow all)
|
|
15
|
+
* DISCORD_NOTIFY_CHANNEL_ID — Discord channel ID for job notifications
|
|
16
|
+
* CC_AGENT_NAMESPACE — cc-agent namespace (default: money-brain)
|
|
17
|
+
* REDIS_URL — Redis connection URL (default: redis://localhost:6379)
|
|
18
|
+
* CWD — working directory for Claude Code (default: process.cwd())
|
|
19
|
+
* DEFAULT_GITHUB_ORG — default GitHub org for #repo routing (default: gonzih)
|
|
20
|
+
*/
|
|
21
|
+
import { Redis } from "ioredis";
|
|
22
|
+
import { CcDiscordBot } from "./bot.js";
|
|
23
|
+
import { startNotifier } from "./notifier.js";
|
|
24
|
+
import { loadTokens } from "./tokens.js";
|
|
25
|
+
function required(name) {
|
|
26
|
+
const val = process.env[name];
|
|
27
|
+
if (!val) {
|
|
28
|
+
console.error(`
|
|
29
|
+
ERROR: ${name} is not set.
|
|
30
|
+
|
|
31
|
+
cc-discord requires:
|
|
32
|
+
DISCORD_BOT_TOKEN — create a bot at https://discord.com/developers/applications
|
|
33
|
+
CLAUDE_CODE_OAUTH_TOKEN — your Claude Code OAuth token
|
|
34
|
+
|
|
35
|
+
Set them and run again:
|
|
36
|
+
DISCORD_BOT_TOKEN=xxx CLAUDE_CODE_OAUTH_TOKEN=yyy npx @gonzih/cc-discord
|
|
37
|
+
`);
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
return val;
|
|
41
|
+
}
|
|
42
|
+
const discordToken = required("DISCORD_BOT_TOKEN");
|
|
43
|
+
const claudeToken = process.env.CLAUDE_CODE_TOKEN ??
|
|
44
|
+
process.env.CLAUDE_CODE_OAUTH_TOKEN ??
|
|
45
|
+
process.env.ANTHROPIC_API_KEY;
|
|
46
|
+
if (!claudeToken) {
|
|
47
|
+
console.error(`
|
|
48
|
+
ERROR: No Claude token set. Set one of: CLAUDE_CODE_TOKEN, CLAUDE_CODE_OAUTH_TOKEN, or ANTHROPIC_API_KEY.
|
|
49
|
+
`);
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
// Load OAuth token pool
|
|
53
|
+
const tokenPool = loadTokens();
|
|
54
|
+
if (tokenPool.length > 1) {
|
|
55
|
+
console.log(`[cc-discord] Token pool loaded: ${tokenPool.length} tokens`);
|
|
56
|
+
}
|
|
57
|
+
const guildIds = process.env.DISCORD_GUILD_IDS
|
|
58
|
+
? process.env.DISCORD_GUILD_IDS.split(",").map((s) => s.trim()).filter(Boolean)
|
|
59
|
+
: [];
|
|
60
|
+
const allowedUserIds = process.env.DISCORD_ALLOWED_USER_IDS
|
|
61
|
+
? process.env.DISCORD_ALLOWED_USER_IDS.split(",").map((s) => s.trim()).filter(Boolean)
|
|
62
|
+
: [];
|
|
63
|
+
const cwd = process.env.CWD ?? process.cwd();
|
|
64
|
+
const redisUrl = process.env.REDIS_URL || "redis://localhost:6379";
|
|
65
|
+
const namespace = process.env.CC_AGENT_NAMESPACE || "money-brain";
|
|
66
|
+
const notifyChannelId = process.env.DISCORD_NOTIFY_CHANNEL_ID ?? null;
|
|
67
|
+
// Redis
|
|
68
|
+
const sharedRedis = new Redis(redisUrl);
|
|
69
|
+
sharedRedis.on("error", (err) => {
|
|
70
|
+
console.warn("[redis] connection error:", err.message);
|
|
71
|
+
});
|
|
72
|
+
sharedRedis.once("ready", () => {
|
|
73
|
+
// Announce this version on Redis so other services can discover cc-discord
|
|
74
|
+
sharedRedis.set(`cca:meta:cc-discord:version`, "0.1.0").catch((err) => {
|
|
75
|
+
console.warn("[redis] failed to write version:", err.message);
|
|
76
|
+
});
|
|
77
|
+
console.log("[cc-discord] version:reported 0.1.0");
|
|
78
|
+
});
|
|
79
|
+
// Mutable placeholder closures — filled in once `bot` is created below
|
|
80
|
+
let getLastActiveChannelIdFn = () => undefined;
|
|
81
|
+
let handleUserMessageFn;
|
|
82
|
+
let forwardNotificationFn;
|
|
83
|
+
const bot = new CcDiscordBot({
|
|
84
|
+
discordToken,
|
|
85
|
+
claudeToken,
|
|
86
|
+
cwd,
|
|
87
|
+
allowedUserIds,
|
|
88
|
+
guildIds,
|
|
89
|
+
redis: sharedRedis,
|
|
90
|
+
namespace,
|
|
91
|
+
registerRoutedChannelId: (ns, channelId) => notifier.registerRoutedChannelId(ns, channelId),
|
|
92
|
+
});
|
|
93
|
+
const notifier = startNotifier(bot, notifyChannelId, namespace, sharedRedis, (channelId, text) => handleUserMessageFn?.(channelId, text), (channelId, text) => forwardNotificationFn?.(channelId, text), () => getLastActiveChannelIdFn(), (n) => bot.reverseSnowflakeLookup(n));
|
|
94
|
+
console.log(`[notifier] started for namespace=${namespace} notifyChannelId=${notifyChannelId ?? "dynamic"}`);
|
|
95
|
+
// Wire closures now that bot is constructed
|
|
96
|
+
getLastActiveChannelIdFn = () => bot.getLastActiveChannelId();
|
|
97
|
+
handleUserMessageFn = (channelId, text) => { void bot.handleUserMessage(channelId, text); };
|
|
98
|
+
forwardNotificationFn = (channelId, text) => { bot.forwardNotification(channelId, text); };
|
|
99
|
+
process.on("SIGINT", () => {
|
|
100
|
+
console.log("\nShutting down...");
|
|
101
|
+
bot.stop();
|
|
102
|
+
process.exit(0);
|
|
103
|
+
});
|
|
104
|
+
process.on("SIGTERM", () => {
|
|
105
|
+
bot.stop();
|
|
106
|
+
process.exit(0);
|
|
107
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DiscordNotifier — subscribes to Redis pub/sub channels and bridges messages to Discord.
|
|
3
|
+
*
|
|
4
|
+
* Channels:
|
|
5
|
+
* cca:notify:{namespace} — job completion notifications from cc-agent → forward to DISCORD_NOTIFY_CHANNEL_ID
|
|
6
|
+
* cca:chat:incoming:{namespace} — messages from the web UI → echo to Discord + feed into Claude session
|
|
7
|
+
* cca:chat:outgoing:* — meta-agent stdout lines (source=claude) → buffer+debounce → Discord
|
|
8
|
+
*
|
|
9
|
+
* All messages (Discord incoming, Claude responses) are also written to:
|
|
10
|
+
* cca:chat:log:{namespace} — LPUSH + LTRIM 0 499 (last 500 messages)
|
|
11
|
+
* cca:chat:outgoing:{namespace} — PUBLISH for web UI to consume
|
|
12
|
+
*/
|
|
13
|
+
import { Redis } from "ioredis";
|
|
14
|
+
import type { CcDiscordBot } from "./bot.js";
|
|
15
|
+
export interface ChatMessage {
|
|
16
|
+
id: string;
|
|
17
|
+
source: "discord" | "ui" | "claude" | "cc-tg";
|
|
18
|
+
role: "user" | "assistant" | "tool";
|
|
19
|
+
content: string;
|
|
20
|
+
timestamp: string;
|
|
21
|
+
chatId: number;
|
|
22
|
+
}
|
|
23
|
+
export interface ParsedNotification {
|
|
24
|
+
text: string;
|
|
25
|
+
chatId?: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Parse a notification payload.
|
|
29
|
+
* Returns the display text plus an optional chatId for per-channel routing.
|
|
30
|
+
* Appends a [driver] or [driver:model] badge when present.
|
|
31
|
+
* Appends " cost: $X.XXX" if a numeric cost field is present.
|
|
32
|
+
*/
|
|
33
|
+
export declare function parseNotification(raw: string): ParsedNotification;
|
|
34
|
+
/**
|
|
35
|
+
* Write a message to the chat log in Redis.
|
|
36
|
+
* Fire-and-forget — errors are logged but not thrown.
|
|
37
|
+
*/
|
|
38
|
+
export declare function writeChatLog(redis: Redis, namespace: string, msg: ChatMessage): void;
|
|
39
|
+
export interface NotifierHandle {
|
|
40
|
+
/**
|
|
41
|
+
* Register the originating Discord channel ID for a routed namespace.
|
|
42
|
+
* When the meta-agent for `namespace` publishes a response, it will be
|
|
43
|
+
* forwarded to `channelId`.
|
|
44
|
+
*/
|
|
45
|
+
registerRoutedChannelId: (namespace: string, channelId: string) => void;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Start the Discord notifier.
|
|
49
|
+
*
|
|
50
|
+
* @param bot - CcDiscordBot instance (for sending messages)
|
|
51
|
+
* @param notifyChannelId - Discord channel ID to forward notifications to. Pass null to use getActiveChannelId.
|
|
52
|
+
* @param namespace - cc-agent namespace (used to build Redis channel names)
|
|
53
|
+
* @param redis - ioredis client in normal mode (will be duplicated for pub/sub)
|
|
54
|
+
* @param handleUserMessage - Optional callback to feed UI messages into the active Claude session
|
|
55
|
+
* @param forwardNotification - Optional callback to forward job notifications
|
|
56
|
+
* @param getActiveChannelId - Optional callback to resolve channelId dynamically
|
|
57
|
+
* @param reverseSnowflakeLookup - Optional callback to resolve a chatId integer to a Discord channelId
|
|
58
|
+
*/
|
|
59
|
+
export declare function startNotifier(bot: CcDiscordBot, notifyChannelId: string | null, namespace: string, redis: Redis, handleUserMessage?: (channelId: string, text: string) => void, forwardNotification?: (channelId: string, text: string) => void, getActiveChannelId?: () => string | undefined, reverseSnowflakeLookup?: (n: number) => string | undefined): NotifierHandle;
|
package/dist/notifier.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DiscordNotifier — subscribes to Redis pub/sub channels and bridges messages to Discord.
|
|
3
|
+
*
|
|
4
|
+
* Channels:
|
|
5
|
+
* cca:notify:{namespace} — job completion notifications from cc-agent → forward to DISCORD_NOTIFY_CHANNEL_ID
|
|
6
|
+
* cca:chat:incoming:{namespace} — messages from the web UI → echo to Discord + feed into Claude session
|
|
7
|
+
* cca:chat:outgoing:* — meta-agent stdout lines (source=claude) → buffer+debounce → Discord
|
|
8
|
+
*
|
|
9
|
+
* All messages (Discord incoming, Claude responses) are also written to:
|
|
10
|
+
* cca:chat:log:{namespace} — LPUSH + LTRIM 0 499 (last 500 messages)
|
|
11
|
+
* cca:chat:outgoing:{namespace} — PUBLISH for web UI to consume
|
|
12
|
+
*/
|
|
13
|
+
import { chatLogKey, chatOutgoingChannel, chatIncomingChannel, notifyChannel, metaAgentStatusKey, metaInputKey, } from "@gonzih/cc-wire";
|
|
14
|
+
import { splitLongMessage, stripAnsi } from "./formatter.js";
|
|
15
|
+
function log(level, ...args) {
|
|
16
|
+
const fn = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
|
|
17
|
+
fn("[notifier]", ...args);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Shorten a model name for display in a badge.
|
|
21
|
+
*/
|
|
22
|
+
function shortenModelName(model, driver) {
|
|
23
|
+
if (!model.trim())
|
|
24
|
+
return "";
|
|
25
|
+
const pfx = driver.toLowerCase() + "-";
|
|
26
|
+
if (model.toLowerCase().startsWith(pfx))
|
|
27
|
+
return model.slice(pfx.length);
|
|
28
|
+
const slashIdx = model.indexOf("/");
|
|
29
|
+
if (slashIdx >= 0)
|
|
30
|
+
return model.slice(slashIdx + 1);
|
|
31
|
+
return model;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Parse a notification payload.
|
|
35
|
+
* Returns the display text plus an optional chatId for per-channel routing.
|
|
36
|
+
* Appends a [driver] or [driver:model] badge when present.
|
|
37
|
+
* Appends " cost: $X.XXX" if a numeric cost field is present.
|
|
38
|
+
*/
|
|
39
|
+
export function parseNotification(raw) {
|
|
40
|
+
let text = raw;
|
|
41
|
+
let driver;
|
|
42
|
+
let model;
|
|
43
|
+
let cost;
|
|
44
|
+
let chatId;
|
|
45
|
+
try {
|
|
46
|
+
const parsed = JSON.parse(raw);
|
|
47
|
+
if (parsed.text)
|
|
48
|
+
text = parsed.text;
|
|
49
|
+
driver = parsed.driver;
|
|
50
|
+
model = parsed.model;
|
|
51
|
+
if (typeof parsed.cost === "number")
|
|
52
|
+
cost = parsed.cost;
|
|
53
|
+
if (typeof parsed.chat_id === "number" && parsed.chat_id !== 0)
|
|
54
|
+
chatId = parsed.chat_id;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return { text };
|
|
58
|
+
}
|
|
59
|
+
if (!driver)
|
|
60
|
+
return { text, chatId };
|
|
61
|
+
const shortModel = shortenModelName(model ?? "", driver);
|
|
62
|
+
const badge = shortModel ? `${driver}:${shortModel}` : driver;
|
|
63
|
+
const costStr = cost != null ? ` cost: $${cost.toFixed(3)}` : "";
|
|
64
|
+
return { text: `${text}\n[${badge}]${costStr}`, chatId };
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Write a message to the chat log in Redis.
|
|
68
|
+
* Fire-and-forget — errors are logged but not thrown.
|
|
69
|
+
*/
|
|
70
|
+
export function writeChatLog(redis, namespace, msg) {
|
|
71
|
+
const logKey = chatLogKey(namespace);
|
|
72
|
+
const outKey = chatOutgoingChannel(namespace);
|
|
73
|
+
const payload = JSON.stringify(msg);
|
|
74
|
+
redis.lpush(logKey, payload).catch((err) => {
|
|
75
|
+
log("warn", "writeChatLog lpush failed:", err.message);
|
|
76
|
+
});
|
|
77
|
+
redis.ltrim(logKey, 0, 499).catch((err) => {
|
|
78
|
+
log("warn", "writeChatLog ltrim failed:", err.message);
|
|
79
|
+
});
|
|
80
|
+
redis.publish(outKey, payload).catch((err) => {
|
|
81
|
+
log("warn", "writeChatLog publish failed:", err.message);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Resolve the target Discord channelId for a notification.
|
|
86
|
+
* When chatId is set and a reverse-lookup function is available, prefer the originating channel.
|
|
87
|
+
* Falls back to notifyChannelId, then getActiveChannelId.
|
|
88
|
+
*/
|
|
89
|
+
function resolveNotifyChannel(chatId, notifyChannelId, getActiveChannelId, reverseSnowflakeLookup) {
|
|
90
|
+
if (chatId != null && reverseSnowflakeLookup) {
|
|
91
|
+
const resolved = reverseSnowflakeLookup(chatId);
|
|
92
|
+
if (resolved)
|
|
93
|
+
return resolved;
|
|
94
|
+
}
|
|
95
|
+
return notifyChannelId ?? getActiveChannelId?.();
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Start the Discord notifier.
|
|
99
|
+
*
|
|
100
|
+
* @param bot - CcDiscordBot instance (for sending messages)
|
|
101
|
+
* @param notifyChannelId - Discord channel ID to forward notifications to. Pass null to use getActiveChannelId.
|
|
102
|
+
* @param namespace - cc-agent namespace (used to build Redis channel names)
|
|
103
|
+
* @param redis - ioredis client in normal mode (will be duplicated for pub/sub)
|
|
104
|
+
* @param handleUserMessage - Optional callback to feed UI messages into the active Claude session
|
|
105
|
+
* @param forwardNotification - Optional callback to forward job notifications
|
|
106
|
+
* @param getActiveChannelId - Optional callback to resolve channelId dynamically
|
|
107
|
+
* @param reverseSnowflakeLookup - Optional callback to resolve a chatId integer to a Discord channelId
|
|
108
|
+
*/
|
|
109
|
+
export function startNotifier(bot, notifyChannelId, namespace, redis, handleUserMessage, forwardNotification, getActiveChannelId, reverseSnowflakeLookup) {
|
|
110
|
+
// Per-namespace channelId registry
|
|
111
|
+
const routedChannelIds = new Map();
|
|
112
|
+
const sub = redis.duplicate({
|
|
113
|
+
retryStrategy: (times) => {
|
|
114
|
+
const delay = Math.min(1000 * Math.pow(2, times - 1), 30_000);
|
|
115
|
+
log("info", `subscriber reconnecting in ${delay}ms (attempt ${times})`);
|
|
116
|
+
return delay;
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
sub.on("error", (err) => {
|
|
120
|
+
log("warn", "subscriber error:", err.message);
|
|
121
|
+
});
|
|
122
|
+
sub.on("close", () => {
|
|
123
|
+
log("info", "subscriber disconnected, will reconnect with backoff");
|
|
124
|
+
});
|
|
125
|
+
// notifyChannel(namespace) — forward job completion notifications to Discord
|
|
126
|
+
sub.subscribe(notifyChannel(namespace), (err) => {
|
|
127
|
+
if (err) {
|
|
128
|
+
log("error", `subscribe ${notifyChannel(namespace)} failed:`, err.message);
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
log("info", `subscribed to ${notifyChannel(namespace)}`);
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
// chatIncomingChannel(namespace) — messages from UI
|
|
135
|
+
sub.subscribe(chatIncomingChannel(namespace), (err) => {
|
|
136
|
+
if (err) {
|
|
137
|
+
log("error", `subscribe ${chatIncomingChannel(namespace)} failed:`, err.message);
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
log("info", `subscribed to ${chatIncomingChannel(namespace)}`);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
// chatOutgoingChannel("*") — meta-agent stdout lines
|
|
144
|
+
sub.psubscribe(chatOutgoingChannel("*"), (err) => {
|
|
145
|
+
if (err) {
|
|
146
|
+
log("error", `psubscribe ${chatOutgoingChannel("*")} failed:`, err.message);
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
log("info", `psubscribed to ${chatOutgoingChannel("*")}`);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
// 1.5s silence buffer for meta-agent streaming
|
|
153
|
+
const META_AGENT_FLUSH_DELAY_MS = 1500;
|
|
154
|
+
const metaAgentBuffers = new Map();
|
|
155
|
+
function flushMetaAgentBuffer(ns, targetChannelId) {
|
|
156
|
+
const buf = metaAgentBuffers.get(ns);
|
|
157
|
+
if (!buf || !buf.text.trim())
|
|
158
|
+
return;
|
|
159
|
+
const text = `← [${ns}] ` + stripAnsi(buf.text.trim());
|
|
160
|
+
buf.text = "";
|
|
161
|
+
buf.timer = null;
|
|
162
|
+
const chunks = splitLongMessage(text);
|
|
163
|
+
for (const chunk of chunks) {
|
|
164
|
+
bot.sendToChannelById(targetChannelId, chunk).catch((err) => {
|
|
165
|
+
log("warn", `meta-agent flush sendToChannelById failed (ns=${ns}):`, err.message);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
sub.on("pmessage", (pattern, channel, message) => {
|
|
170
|
+
void pattern;
|
|
171
|
+
const ns = channel.slice(chatOutgoingChannel("").length);
|
|
172
|
+
let parsed = null;
|
|
173
|
+
try {
|
|
174
|
+
parsed = JSON.parse(message);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (parsed.source !== "claude")
|
|
180
|
+
return;
|
|
181
|
+
const content = parsed.content;
|
|
182
|
+
if (!content)
|
|
183
|
+
return;
|
|
184
|
+
const targetChannelId = routedChannelIds.get(ns) ?? notifyChannelId ?? getActiveChannelId?.();
|
|
185
|
+
if (targetChannelId == null) {
|
|
186
|
+
log("warn", `meta-agent output: no channelId for namespace=${ns}, dropping line`);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
let buf = metaAgentBuffers.get(ns);
|
|
190
|
+
if (!buf) {
|
|
191
|
+
buf = { text: "", timer: null };
|
|
192
|
+
metaAgentBuffers.set(ns, buf);
|
|
193
|
+
}
|
|
194
|
+
buf.text += (buf.text ? "\n" : "") + content;
|
|
195
|
+
if (buf.timer)
|
|
196
|
+
clearTimeout(buf.timer);
|
|
197
|
+
buf.timer = setTimeout(() => flushMetaAgentBuffer(ns, targetChannelId), META_AGENT_FLUSH_DELAY_MS);
|
|
198
|
+
});
|
|
199
|
+
// Poll the notifyChannel(namespace) LIST every 5 seconds
|
|
200
|
+
const notifyListKey = notifyChannel(namespace);
|
|
201
|
+
const MAX_PER_CYCLE = 20;
|
|
202
|
+
const pollNotifyList = async () => {
|
|
203
|
+
const targetId = notifyChannelId ?? getActiveChannelId?.();
|
|
204
|
+
if (targetId == null)
|
|
205
|
+
return;
|
|
206
|
+
const items = [];
|
|
207
|
+
try {
|
|
208
|
+
for (let i = 0; i < MAX_PER_CYCLE; i++) {
|
|
209
|
+
const item = await redis.rpop(notifyListKey);
|
|
210
|
+
if (item === null)
|
|
211
|
+
break;
|
|
212
|
+
items.push(item);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
catch (err) {
|
|
216
|
+
log("warn", "notify list rpop failed:", err.message);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (items.length === 0)
|
|
220
|
+
return;
|
|
221
|
+
let remaining = 0;
|
|
222
|
+
if (items.length === MAX_PER_CYCLE) {
|
|
223
|
+
try {
|
|
224
|
+
remaining = await redis.llen(notifyListKey);
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
log("warn", "notify list llen failed:", err.message);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
for (const raw of items) {
|
|
231
|
+
const notification = parseNotification(raw);
|
|
232
|
+
const destChannelId = resolveNotifyChannel(notification.chatId, notifyChannelId, getActiveChannelId, reverseSnowflakeLookup) ?? targetId;
|
|
233
|
+
bot.sendToChannelById(destChannelId, notification.text).catch((err) => {
|
|
234
|
+
log("warn", "notify list send failed:", err.message);
|
|
235
|
+
});
|
|
236
|
+
if (forwardNotification) {
|
|
237
|
+
forwardNotification(destChannelId, notification.text);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (remaining > 0) {
|
|
241
|
+
bot.sendToChannelById(targetId, `...and ${remaining} more notifications`).catch((err) => {
|
|
242
|
+
log("warn", "notify list summary send failed:", err.message);
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
setInterval(() => {
|
|
247
|
+
void pollNotifyList();
|
|
248
|
+
}, 5_000);
|
|
249
|
+
sub.on("message", (channel, message) => {
|
|
250
|
+
const notifyCh = notifyChannel(namespace);
|
|
251
|
+
const incomingCh = chatIncomingChannel(namespace);
|
|
252
|
+
if (channel === notifyCh) {
|
|
253
|
+
const notification = parseNotification(message);
|
|
254
|
+
const targetId = resolveNotifyChannel(notification.chatId, notifyChannelId, getActiveChannelId, reverseSnowflakeLookup);
|
|
255
|
+
if (targetId != null) {
|
|
256
|
+
bot.sendToChannelById(targetId, notification.text).catch((err) => {
|
|
257
|
+
log("warn", "notify send failed:", err.message);
|
|
258
|
+
});
|
|
259
|
+
if (forwardNotification) {
|
|
260
|
+
forwardNotification(targetId, notification.text);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
log("warn", "notify: no channelId available, dropping notification");
|
|
265
|
+
}
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (channel === incomingCh) {
|
|
269
|
+
let content = message;
|
|
270
|
+
let originalTimestamp;
|
|
271
|
+
try {
|
|
272
|
+
const parsed = JSON.parse(message);
|
|
273
|
+
if (parsed.content)
|
|
274
|
+
content = parsed.content;
|
|
275
|
+
if (parsed.timestamp)
|
|
276
|
+
originalTimestamp = parsed.timestamp;
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
// raw string message — use as-is
|
|
280
|
+
}
|
|
281
|
+
const targetChannelId = notifyChannelId ?? getActiveChannelId?.();
|
|
282
|
+
if (targetChannelId !== undefined) {
|
|
283
|
+
// Echo to Discord so the user sees UI messages
|
|
284
|
+
bot.sendToChannelById(targetChannelId, `[from UI]: ${content}`).catch((err) => {
|
|
285
|
+
log("warn", "sendToChannelById (UI echo) failed:", err.message);
|
|
286
|
+
});
|
|
287
|
+
// Log the incoming message
|
|
288
|
+
const inMsg = {
|
|
289
|
+
id: crypto.randomUUID(),
|
|
290
|
+
source: "ui",
|
|
291
|
+
role: "user",
|
|
292
|
+
content,
|
|
293
|
+
timestamp: originalTimestamp ?? new Date().toISOString(),
|
|
294
|
+
chatId: 0, // no numeric chatId for Discord — stored by channelId string
|
|
295
|
+
};
|
|
296
|
+
writeChatLog(redis, namespace, inMsg);
|
|
297
|
+
// Check if a meta-agent is running; if so, route there instead
|
|
298
|
+
void (async () => {
|
|
299
|
+
let routedToMetaAgent = false;
|
|
300
|
+
try {
|
|
301
|
+
const statusRaw = await redis.get(metaAgentStatusKey(namespace));
|
|
302
|
+
if (statusRaw) {
|
|
303
|
+
const status = JSON.parse(statusRaw);
|
|
304
|
+
if (status.status === "running") {
|
|
305
|
+
const entry = JSON.stringify({
|
|
306
|
+
id: crypto.randomUUID(),
|
|
307
|
+
content,
|
|
308
|
+
timestamp: new Date().toISOString(),
|
|
309
|
+
});
|
|
310
|
+
await redis.rpush(metaInputKey(namespace), entry);
|
|
311
|
+
log("info", `cca:chat:incoming: routed to meta-agent for namespace ${namespace}`);
|
|
312
|
+
routedToMetaAgent = true;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
catch (err) {
|
|
317
|
+
log("warn", "meta-agent status check failed:", err.message);
|
|
318
|
+
}
|
|
319
|
+
if (!routedToMetaAgent && handleUserMessage) {
|
|
320
|
+
handleUserMessage(targetChannelId, content);
|
|
321
|
+
}
|
|
322
|
+
})();
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
log("warn", "cca:chat:incoming: no active channelId to route message to");
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
});
|
|
329
|
+
return {
|
|
330
|
+
registerRoutedChannelId: (ns, channelId) => {
|
|
331
|
+
routedChannelIds.set(ns, channelId);
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
}
|
package/dist/router.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Routing helpers: channel-creation intent detection and meta-agent routing.
|
|
3
|
+
*/
|
|
4
|
+
import { Redis } from "ioredis";
|
|
5
|
+
/** Callback type matching CcDiscordBot.callCcAgentTool */
|
|
6
|
+
export type CallToolFn = (toolName: string, args?: Record<string, unknown>) => Promise<string | null>;
|
|
7
|
+
/**
|
|
8
|
+
* Ensure a meta-agent for the given namespace is running.
|
|
9
|
+
*
|
|
10
|
+
* Steps:
|
|
11
|
+
* 1. Check Redis for readiness via two keys (see below) — return early if already ready.
|
|
12
|
+
* 2. Verify the GitHub repo exists; create it (public) if not.
|
|
13
|
+
* 3. Call the start_meta_agent MCP tool via callTool.
|
|
14
|
+
* 4. Poll both Redis keys every 1s until ready or META_AGENT_TIMEOUT_MS expires.
|
|
15
|
+
*
|
|
16
|
+
* Two Redis keys are checked:
|
|
17
|
+
* cca:meta-agent:status:{namespace} — live-status key written by writeLiveStatus()
|
|
18
|
+
* (only populated after the first message is processed by messageMetaAgent)
|
|
19
|
+
* cca:meta:{namespace} — state key written by startMetaAgent() directly via saveState()
|
|
20
|
+
* (populated as soon as the workspace is created, with status:"idle")
|
|
21
|
+
*
|
|
22
|
+
* Bug context: start_meta_agent writes cca:meta:{namespace} but NOT cca:meta-agent:status:{namespace}.
|
|
23
|
+
* Polling only the status key caused a 10s timeout on every cold start.
|
|
24
|
+
*
|
|
25
|
+
* Throws on failure (repo creation error, tool call failure, or timeout).
|
|
26
|
+
*/
|
|
27
|
+
export declare function ensureMetaAgent(namespace: string, repoUrl: string, callTool: CallToolFn, redis: Redis): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* Detect a natural-language channel-creation request.
|
|
30
|
+
* Matches:
|
|
31
|
+
* "channel for https://github.com/org/repo"
|
|
32
|
+
* "create channel for https://github.com/org/repo"
|
|
33
|
+
* "add channel for https://github.com/org/repo"
|
|
34
|
+
*
|
|
35
|
+
* Returns { namespace, repoUrl } or null.
|
|
36
|
+
*/
|
|
37
|
+
export declare function parseChannelCreateIntent(text: string): {
|
|
38
|
+
namespace: string;
|
|
39
|
+
repoUrl: string;
|
|
40
|
+
} | null;
|
|
41
|
+
/**
|
|
42
|
+
* Route a message to a running meta-agent via Redis RPUSH.
|
|
43
|
+
* The cc-agent polls cca:meta:{namespace}:input every 3s (up to 3s delivery latency).
|
|
44
|
+
*
|
|
45
|
+
* No-op when strippedMessage is empty (user sent only the tag token).
|
|
46
|
+
*/
|
|
47
|
+
export declare function routeToMetaAgent(namespace: string, strippedMessage: string, redis: Redis): Promise<void>;
|