@gonzih/cc-discord 0.2.0 → 0.2.2

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 CHANGED
@@ -64,6 +64,7 @@ export declare class CcDiscordBot {
64
64
  private sendToChannel;
65
65
  /** Send to a channel by ID — used by notifier callbacks. */
66
66
  sendToChannelById(channelId: string, text: string): Promise<void>;
67
+ sendAttachmentToChannelById(channelId: string, filePath: string): Promise<void>;
67
68
  private isAllowed;
68
69
  private handleMessage;
69
70
  private handleVoice;
package/dist/bot.js CHANGED
@@ -294,6 +294,15 @@ export class CcDiscordBot {
294
294
  }
295
295
  await this.sendToChannel(channel, text);
296
296
  }
297
+ async sendAttachmentToChannelById(channelId, filePath) {
298
+ const channel = await this.getChannel(channelId);
299
+ if (!channel) {
300
+ console.warn(`[bot] sendAttachmentToChannelById: channel ${channelId} not found`);
301
+ return;
302
+ }
303
+ const attachment = new AttachmentBuilder(filePath, { name: basename(filePath) });
304
+ await channel.send({ files: [attachment] });
305
+ }
297
306
  isAllowed(userId) {
298
307
  if (!this.opts.allowedUserIds?.length)
299
308
  return true;
@@ -1063,7 +1072,7 @@ export class CcDiscordBot {
1063
1072
  startMetaAgentPolling() {
1064
1073
  if (!this.wire)
1065
1074
  return;
1066
- this.metaAgentManager.startPolling(this.wire, () => Array.from(this.channelNamespaceMap.values()).map((v) => v.namespace));
1075
+ this.metaAgentManager.startPolling(this.wire, () => Array.from(this.channelNamespaceMap.values()));
1067
1076
  }
1068
1077
  stop() {
1069
1078
  for (const [key, session] of this.sessions) {
@@ -36,10 +36,14 @@ export declare function injectMcp(ns: string, wsPath: string, token: string): vo
36
36
  * Returns a Promise that resolves when the process exits.
37
37
  */
38
38
  export declare function spawnSession(ns: string, message: string, token: string, wire: Wire): Promise<void>;
39
+ export interface NamespaceEntry {
40
+ namespace: string;
41
+ repoUrl: string;
42
+ }
39
43
  export interface MetaAgentManager {
40
44
  ensureWorkspace: (ns: string, repoUrl: string) => Promise<void>;
41
45
  injectMcp: (ns: string, token: string) => void;
42
- startPolling: (wire: Wire, getNamespaces: () => string[]) => void;
46
+ startPolling: (wire: Wire, getNamespaceEntries: () => NamespaceEntry[]) => void;
43
47
  stop: () => void;
44
48
  }
45
49
  /**
@@ -183,14 +183,14 @@ export function createMetaAgentManager() {
183
183
  const wsPath = workspacePath(ns);
184
184
  injectMcp(ns, wsPath, token);
185
185
  },
186
- startPolling(wire, getNamespaces) {
186
+ startPolling(wire, getNamespaceEntries) {
187
187
  if (pollInterval)
188
188
  return; // already running
189
189
  pollInterval = setInterval(() => {
190
- const namespaces = getNamespaces();
191
- if (namespaces.length === 0)
190
+ const entries = getNamespaceEntries();
191
+ if (entries.length === 0)
192
192
  return;
193
- for (const ns of namespaces) {
193
+ for (const { namespace: ns, repoUrl } of entries) {
194
194
  if (activeNamespaces.has(ns))
195
195
  continue;
196
196
  wire.discord.dequeue(ns)
@@ -228,6 +228,24 @@ export function createMetaAgentManager() {
228
228
  });
229
229
  return;
230
230
  }
231
+ // Ensure workspace exists before spawning — clone happens once, no-op on repeat.
232
+ try {
233
+ await ensureWorkspace(ns, repoUrl);
234
+ injectMcp(ns, workspacePath(ns), token);
235
+ }
236
+ catch (wsErr) {
237
+ const msg = wsErr instanceof Error ? wsErr.message : String(wsErr);
238
+ console.error(`[meta-agent-manager] workspace setup failed (ns=${ns}):`, msg);
239
+ activeNamespaces.delete(ns);
240
+ await wire.discord.setStatus(ns, {
241
+ namespace: ns,
242
+ status: "idle",
243
+ isTyping: false,
244
+ turnCount: 0,
245
+ updatedAt: new Date().toISOString(),
246
+ }).catch(() => { });
247
+ return;
248
+ }
231
249
  spawnSession(ns, content, token, wire)
232
250
  .catch((err) => {
233
251
  console.error(`[meta-agent-manager] session error (ns=${ns}):`, err.message);
package/dist/notifier.js CHANGED
@@ -11,7 +11,22 @@
11
11
  * cca:discord:chat:outgoing:{ns} — PUBLISH for web UI to consume
12
12
  */
13
13
  import { discordChatLog, discordChatOutgoing, discordNotify, chatIncomingChannel, createCcWire, TIMING, } from "@gonzih/cc-wire";
14
+ import { existsSync, statSync } from "fs";
14
15
  import { splitLongMessage, stripAnsi } from "./formatter.js";
16
+ const SAFE_DIRS = ["/tmp/", "/var/folders/"];
17
+ const MAX_DISCORD_BYTES = 25 * 1024 * 1024; // 25 MB Discord file limit
18
+ /** Extract /tmp/ or /var/folders/ file paths mentioned in text that actually exist on disk. */
19
+ function extractAttachablePaths(text) {
20
+ const pattern = /(?:^|[\s`'"(])(\/(?:tmp|var\/folders)\/[\w.\-/]+\.[\w]{1,10})(?:[\s`'")\n]|$)/gm;
21
+ const quoted = /"(\/(?:tmp|var\/folders)\/[^"]+\.[a-zA-Z0-9]{1,10})"|'(\/(?:tmp|var\/folders)\/[^']+\.[a-zA-Z0-9]{1,10})'/g;
22
+ const candidates = new Set();
23
+ let m;
24
+ while ((m = pattern.exec(text)) !== null)
25
+ candidates.add(m[1]);
26
+ while ((m = quoted.exec(text)) !== null)
27
+ candidates.add(m[1] ?? m[2]);
28
+ return [...candidates].filter(p => SAFE_DIRS.some(d => p.startsWith(d)) && existsSync(p));
29
+ }
15
30
  function log(level, ...args) {
16
31
  const fn = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
17
32
  fn("[notifier]", ...args);
@@ -182,7 +197,8 @@ export function startNotifier(bot, notifyChannelId, namespace, redis, handleUser
182
197
  const buf = metaAgentBuffers.get(ns);
183
198
  if (!buf || !buf.text.trim())
184
199
  return;
185
- const text = `← [${ns}] ` + stripAnsi(buf.text.trim());
200
+ const rawText = stripAnsi(buf.text.trim());
201
+ const text = `← [${ns}] ` + rawText;
186
202
  buf.text = "";
187
203
  buf.timer = null;
188
204
  const chunks = splitLongMessage(text);
@@ -191,6 +207,25 @@ export function startNotifier(bot, notifyChannelId, namespace, redis, handleUser
191
207
  log("warn", `meta-agent flush sendToChannelById failed (ns=${ns}):`, err.message);
192
208
  });
193
209
  }
210
+ // Attach any /tmp/ files mentioned in the response
211
+ const paths = extractAttachablePaths(rawText);
212
+ for (const filePath of paths) {
213
+ let size;
214
+ try {
215
+ size = statSync(filePath).size;
216
+ }
217
+ catch {
218
+ continue;
219
+ }
220
+ if (size > MAX_DISCORD_BYTES) {
221
+ bot.sendToChannelById(targetChannelId, `File too large for Discord (${(size / 1024 / 1024).toFixed(1)} MB): ${filePath}`).catch(() => { });
222
+ continue;
223
+ }
224
+ log("info", `attaching file to Discord (ns=${ns}): ${filePath}`);
225
+ bot.sendAttachmentToChannelById(targetChannelId, filePath).catch((err) => {
226
+ log("warn", `attachment send failed (ns=${ns}, path=${filePath}):`, err.message);
227
+ });
228
+ }
194
229
  }
195
230
  sub.on("pmessage", (pattern, channel, message) => {
196
231
  void pattern;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gonzih/cc-discord",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Claude Code Discord bot — chat with Claude Code via Discord",
5
5
  "type": "module",
6
6
  "bin": {