@draht/mom 2026.3.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.
Files changed (67) hide show
  1. package/CHANGELOG.md +448 -0
  2. package/README.md +490 -0
  3. package/dist/agent.d.ts +24 -0
  4. package/dist/agent.d.ts.map +1 -0
  5. package/dist/agent.js +758 -0
  6. package/dist/agent.js.map +1 -0
  7. package/dist/context.d.ts +70 -0
  8. package/dist/context.d.ts.map +1 -0
  9. package/dist/context.js +221 -0
  10. package/dist/context.js.map +1 -0
  11. package/dist/download.d.ts +2 -0
  12. package/dist/download.d.ts.map +1 -0
  13. package/dist/download.js +89 -0
  14. package/dist/download.js.map +1 -0
  15. package/dist/events.d.ts +57 -0
  16. package/dist/events.d.ts.map +1 -0
  17. package/dist/events.js +310 -0
  18. package/dist/events.js.map +1 -0
  19. package/dist/log.d.ts +39 -0
  20. package/dist/log.d.ts.map +1 -0
  21. package/dist/log.js +222 -0
  22. package/dist/log.js.map +1 -0
  23. package/dist/main.d.ts +3 -0
  24. package/dist/main.d.ts.map +1 -0
  25. package/dist/main.js +271 -0
  26. package/dist/main.js.map +1 -0
  27. package/dist/sandbox.d.ts +34 -0
  28. package/dist/sandbox.d.ts.map +1 -0
  29. package/dist/sandbox.js +183 -0
  30. package/dist/sandbox.js.map +1 -0
  31. package/dist/slack.d.ts +128 -0
  32. package/dist/slack.d.ts.map +1 -0
  33. package/dist/slack.js +455 -0
  34. package/dist/slack.js.map +1 -0
  35. package/dist/store.d.ts +60 -0
  36. package/dist/store.d.ts.map +1 -0
  37. package/dist/store.js +180 -0
  38. package/dist/store.js.map +1 -0
  39. package/dist/tools/attach.d.ts +10 -0
  40. package/dist/tools/attach.d.ts.map +1 -0
  41. package/dist/tools/attach.js +34 -0
  42. package/dist/tools/attach.js.map +1 -0
  43. package/dist/tools/bash.d.ts +10 -0
  44. package/dist/tools/bash.d.ts.map +1 -0
  45. package/dist/tools/bash.js +78 -0
  46. package/dist/tools/bash.js.map +1 -0
  47. package/dist/tools/edit.d.ts +11 -0
  48. package/dist/tools/edit.d.ts.map +1 -0
  49. package/dist/tools/edit.js +131 -0
  50. package/dist/tools/edit.js.map +1 -0
  51. package/dist/tools/index.d.ts +5 -0
  52. package/dist/tools/index.d.ts.map +1 -0
  53. package/dist/tools/index.js +16 -0
  54. package/dist/tools/index.js.map +1 -0
  55. package/dist/tools/read.d.ts +11 -0
  56. package/dist/tools/read.d.ts.map +1 -0
  57. package/dist/tools/read.js +134 -0
  58. package/dist/tools/read.js.map +1 -0
  59. package/dist/tools/truncate.d.ts +57 -0
  60. package/dist/tools/truncate.d.ts.map +1 -0
  61. package/dist/tools/truncate.js +184 -0
  62. package/dist/tools/truncate.js.map +1 -0
  63. package/dist/tools/write.d.ts +10 -0
  64. package/dist/tools/write.d.ts.map +1 -0
  65. package/dist/tools/write.js +33 -0
  66. package/dist/tools/write.js.map +1 -0
  67. package/package.json +54 -0
package/dist/slack.js ADDED
@@ -0,0 +1,455 @@
1
+ import { SocketModeClient } from "@slack/socket-mode";
2
+ import { WebClient } from "@slack/web-api";
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
4
+ import { basename, join } from "path";
5
+ import * as log from "./log.js";
6
+ class ChannelQueue {
7
+ queue = [];
8
+ processing = false;
9
+ enqueue(work) {
10
+ this.queue.push(work);
11
+ this.processNext();
12
+ }
13
+ size() {
14
+ return this.queue.length;
15
+ }
16
+ async processNext() {
17
+ if (this.processing || this.queue.length === 0)
18
+ return;
19
+ this.processing = true;
20
+ const work = this.queue.shift();
21
+ try {
22
+ await work();
23
+ }
24
+ catch (err) {
25
+ log.logWarning("Queue error", err instanceof Error ? err.message : String(err));
26
+ }
27
+ this.processing = false;
28
+ this.processNext();
29
+ }
30
+ }
31
+ // ============================================================================
32
+ // SlackBot
33
+ // ============================================================================
34
+ export class SlackBot {
35
+ socketClient;
36
+ webClient;
37
+ handler;
38
+ workingDir;
39
+ store;
40
+ botUserId = null;
41
+ startupTs = null; // Messages older than this are just logged, not processed
42
+ users = new Map();
43
+ channels = new Map();
44
+ queues = new Map();
45
+ constructor(handler, config) {
46
+ this.handler = handler;
47
+ this.workingDir = config.workingDir;
48
+ this.store = config.store;
49
+ this.socketClient = new SocketModeClient({ appToken: config.appToken });
50
+ this.webClient = new WebClient(config.botToken);
51
+ }
52
+ // ==========================================================================
53
+ // Public API
54
+ // ==========================================================================
55
+ async start() {
56
+ const auth = await this.webClient.auth.test();
57
+ this.botUserId = auth.user_id;
58
+ await Promise.all([this.fetchUsers(), this.fetchChannels()]);
59
+ log.logInfo(`Loaded ${this.channels.size} channels, ${this.users.size} users`);
60
+ await this.backfillAllChannels();
61
+ this.setupEventHandlers();
62
+ await this.socketClient.start();
63
+ // Record startup time - messages older than this are just logged, not processed
64
+ this.startupTs = (Date.now() / 1000).toFixed(6);
65
+ log.logConnected();
66
+ }
67
+ getUser(userId) {
68
+ return this.users.get(userId);
69
+ }
70
+ getChannel(channelId) {
71
+ return this.channels.get(channelId);
72
+ }
73
+ getAllUsers() {
74
+ return Array.from(this.users.values());
75
+ }
76
+ getAllChannels() {
77
+ return Array.from(this.channels.values());
78
+ }
79
+ async postMessage(channel, text) {
80
+ const result = await this.webClient.chat.postMessage({ channel, text });
81
+ return result.ts;
82
+ }
83
+ async updateMessage(channel, ts, text) {
84
+ await this.webClient.chat.update({ channel, ts, text });
85
+ }
86
+ async deleteMessage(channel, ts) {
87
+ await this.webClient.chat.delete({ channel, ts });
88
+ }
89
+ async postInThread(channel, threadTs, text) {
90
+ const result = await this.webClient.chat.postMessage({ channel, thread_ts: threadTs, text });
91
+ return result.ts;
92
+ }
93
+ async uploadFile(channel, filePath, title) {
94
+ const fileName = title || basename(filePath);
95
+ const fileContent = readFileSync(filePath);
96
+ await this.webClient.files.uploadV2({
97
+ channel_id: channel,
98
+ file: fileContent,
99
+ filename: fileName,
100
+ title: fileName,
101
+ });
102
+ }
103
+ /**
104
+ * Log a message to log.jsonl (SYNC)
105
+ * This is the ONLY place messages are written to log.jsonl
106
+ */
107
+ logToFile(channel, entry) {
108
+ const dir = join(this.workingDir, channel);
109
+ if (!existsSync(dir))
110
+ mkdirSync(dir, { recursive: true });
111
+ appendFileSync(join(dir, "log.jsonl"), `${JSON.stringify(entry)}\n`);
112
+ }
113
+ /**
114
+ * Log a bot response to log.jsonl
115
+ */
116
+ logBotResponse(channel, text, ts) {
117
+ this.logToFile(channel, {
118
+ date: new Date().toISOString(),
119
+ ts,
120
+ user: "bot",
121
+ text,
122
+ attachments: [],
123
+ isBot: true,
124
+ });
125
+ }
126
+ // ==========================================================================
127
+ // Events Integration
128
+ // ==========================================================================
129
+ /**
130
+ * Enqueue an event for processing. Always queues (no "already working" rejection).
131
+ * Returns true if enqueued, false if queue is full (max 5).
132
+ */
133
+ enqueueEvent(event) {
134
+ const queue = this.getQueue(event.channel);
135
+ if (queue.size() >= 5) {
136
+ log.logWarning(`Event queue full for ${event.channel}, discarding: ${event.text.substring(0, 50)}`);
137
+ return false;
138
+ }
139
+ log.logInfo(`Enqueueing event for ${event.channel}: ${event.text.substring(0, 50)}`);
140
+ queue.enqueue(() => this.handler.handleEvent(event, this, true));
141
+ return true;
142
+ }
143
+ // ==========================================================================
144
+ // Private - Event Handlers
145
+ // ==========================================================================
146
+ getQueue(channelId) {
147
+ let queue = this.queues.get(channelId);
148
+ if (!queue) {
149
+ queue = new ChannelQueue();
150
+ this.queues.set(channelId, queue);
151
+ }
152
+ return queue;
153
+ }
154
+ setupEventHandlers() {
155
+ // Channel @mentions
156
+ this.socketClient.on("app_mention", ({ event, ack }) => {
157
+ const e = event;
158
+ // Skip DMs (handled by message event)
159
+ if (e.channel.startsWith("D")) {
160
+ ack();
161
+ return;
162
+ }
163
+ const slackEvent = {
164
+ type: "mention",
165
+ channel: e.channel,
166
+ ts: e.ts,
167
+ user: e.user,
168
+ text: e.text.replace(/<@[A-Z0-9]+>/gi, "").trim(),
169
+ files: e.files,
170
+ };
171
+ // SYNC: Log to log.jsonl (ALWAYS, even for old messages)
172
+ // Also downloads attachments in background and stores local paths
173
+ slackEvent.attachments = this.logUserMessage(slackEvent);
174
+ // Only trigger processing for messages AFTER startup (not replayed old messages)
175
+ if (this.startupTs && e.ts < this.startupTs) {
176
+ log.logInfo(`[${e.channel}] Logged old message (pre-startup), not triggering: ${slackEvent.text.substring(0, 30)}`);
177
+ ack();
178
+ return;
179
+ }
180
+ // Check for stop command - execute immediately, don't queue!
181
+ if (slackEvent.text.toLowerCase().trim() === "stop") {
182
+ if (this.handler.isRunning(e.channel)) {
183
+ this.handler.handleStop(e.channel, this); // Don't await, don't queue
184
+ }
185
+ else {
186
+ this.postMessage(e.channel, "_Nothing running_");
187
+ }
188
+ ack();
189
+ return;
190
+ }
191
+ // SYNC: Check if busy
192
+ if (this.handler.isRunning(e.channel)) {
193
+ this.postMessage(e.channel, "_Already working. Say `@mom stop` to cancel._");
194
+ }
195
+ else {
196
+ this.getQueue(e.channel).enqueue(() => this.handler.handleEvent(slackEvent, this));
197
+ }
198
+ ack();
199
+ });
200
+ // All messages (for logging) + DMs (for triggering)
201
+ this.socketClient.on("message", ({ event, ack }) => {
202
+ const e = event;
203
+ // Skip bot messages, edits, etc.
204
+ if (e.bot_id || !e.user || e.user === this.botUserId) {
205
+ ack();
206
+ return;
207
+ }
208
+ if (e.subtype !== undefined && e.subtype !== "file_share") {
209
+ ack();
210
+ return;
211
+ }
212
+ if (!e.text && (!e.files || e.files.length === 0)) {
213
+ ack();
214
+ return;
215
+ }
216
+ const isDM = e.channel_type === "im";
217
+ const isBotMention = e.text?.includes(`<@${this.botUserId}>`);
218
+ // Skip channel @mentions - already handled by app_mention event
219
+ if (!isDM && isBotMention) {
220
+ ack();
221
+ return;
222
+ }
223
+ const slackEvent = {
224
+ type: isDM ? "dm" : "mention",
225
+ channel: e.channel,
226
+ ts: e.ts,
227
+ user: e.user,
228
+ text: (e.text || "").replace(/<@[A-Z0-9]+>/gi, "").trim(),
229
+ files: e.files,
230
+ };
231
+ // SYNC: Log to log.jsonl (ALL messages - channel chatter and DMs)
232
+ // Also downloads attachments in background and stores local paths
233
+ slackEvent.attachments = this.logUserMessage(slackEvent);
234
+ // Only trigger processing for messages AFTER startup (not replayed old messages)
235
+ if (this.startupTs && e.ts < this.startupTs) {
236
+ log.logInfo(`[${e.channel}] Skipping old message (pre-startup): ${slackEvent.text.substring(0, 30)}`);
237
+ ack();
238
+ return;
239
+ }
240
+ // Only trigger handler for DMs
241
+ if (isDM) {
242
+ // Check for stop command - execute immediately, don't queue!
243
+ if (slackEvent.text.toLowerCase().trim() === "stop") {
244
+ if (this.handler.isRunning(e.channel)) {
245
+ this.handler.handleStop(e.channel, this); // Don't await, don't queue
246
+ }
247
+ else {
248
+ this.postMessage(e.channel, "_Nothing running_");
249
+ }
250
+ ack();
251
+ return;
252
+ }
253
+ if (this.handler.isRunning(e.channel)) {
254
+ this.postMessage(e.channel, "_Already working. Say `stop` to cancel._");
255
+ }
256
+ else {
257
+ this.getQueue(e.channel).enqueue(() => this.handler.handleEvent(slackEvent, this));
258
+ }
259
+ }
260
+ ack();
261
+ });
262
+ }
263
+ /**
264
+ * Log a user message to log.jsonl (SYNC)
265
+ * Downloads attachments in background via store
266
+ */
267
+ logUserMessage(event) {
268
+ const user = this.users.get(event.user);
269
+ // Process attachments - queues downloads in background
270
+ const attachments = event.files ? this.store.processAttachments(event.channel, event.files, event.ts) : [];
271
+ this.logToFile(event.channel, {
272
+ date: new Date(parseFloat(event.ts) * 1000).toISOString(),
273
+ ts: event.ts,
274
+ user: event.user,
275
+ userName: user?.userName,
276
+ displayName: user?.displayName,
277
+ text: event.text,
278
+ attachments,
279
+ isBot: false,
280
+ });
281
+ return attachments;
282
+ }
283
+ // ==========================================================================
284
+ // Private - Backfill
285
+ // ==========================================================================
286
+ getExistingTimestamps(channelId) {
287
+ const logPath = join(this.workingDir, channelId, "log.jsonl");
288
+ const timestamps = new Set();
289
+ if (!existsSync(logPath))
290
+ return timestamps;
291
+ const content = readFileSync(logPath, "utf-8");
292
+ const lines = content.trim().split("\n").filter(Boolean);
293
+ for (const line of lines) {
294
+ try {
295
+ const entry = JSON.parse(line);
296
+ if (entry.ts)
297
+ timestamps.add(entry.ts);
298
+ }
299
+ catch { }
300
+ }
301
+ return timestamps;
302
+ }
303
+ async backfillChannel(channelId) {
304
+ const existingTs = this.getExistingTimestamps(channelId);
305
+ // Find the biggest ts in log.jsonl
306
+ let latestTs;
307
+ for (const ts of existingTs) {
308
+ if (!latestTs || parseFloat(ts) > parseFloat(latestTs))
309
+ latestTs = ts;
310
+ }
311
+ const allMessages = [];
312
+ let cursor;
313
+ let pageCount = 0;
314
+ const maxPages = 3;
315
+ do {
316
+ const result = await this.webClient.conversations.history({
317
+ channel: channelId,
318
+ oldest: latestTs, // Only fetch messages newer than what we have
319
+ inclusive: false,
320
+ limit: 1000,
321
+ cursor,
322
+ });
323
+ if (result.messages) {
324
+ allMessages.push(...result.messages);
325
+ }
326
+ cursor = result.response_metadata?.next_cursor;
327
+ pageCount++;
328
+ } while (cursor && pageCount < maxPages);
329
+ // Filter: include mom's messages, exclude other bots, skip already logged
330
+ const relevantMessages = allMessages.filter((msg) => {
331
+ if (!msg.ts || existingTs.has(msg.ts))
332
+ return false; // Skip duplicates
333
+ if (msg.user === this.botUserId)
334
+ return true;
335
+ if (msg.bot_id)
336
+ return false;
337
+ if (msg.subtype !== undefined && msg.subtype !== "file_share")
338
+ return false;
339
+ if (!msg.user)
340
+ return false;
341
+ if (!msg.text && (!msg.files || msg.files.length === 0))
342
+ return false;
343
+ return true;
344
+ });
345
+ // Reverse to chronological order
346
+ relevantMessages.reverse();
347
+ // Log each message to log.jsonl
348
+ for (const msg of relevantMessages) {
349
+ const isMomMessage = msg.user === this.botUserId;
350
+ const user = this.users.get(msg.user);
351
+ // Strip @mentions from text (same as live messages)
352
+ const text = (msg.text || "").replace(/<@[A-Z0-9]+>/gi, "").trim();
353
+ // Process attachments - queues downloads in background
354
+ const attachments = msg.files ? this.store.processAttachments(channelId, msg.files, msg.ts) : [];
355
+ this.logToFile(channelId, {
356
+ date: new Date(parseFloat(msg.ts) * 1000).toISOString(),
357
+ ts: msg.ts,
358
+ user: isMomMessage ? "bot" : msg.user,
359
+ userName: isMomMessage ? undefined : user?.userName,
360
+ displayName: isMomMessage ? undefined : user?.displayName,
361
+ text,
362
+ attachments,
363
+ isBot: isMomMessage,
364
+ });
365
+ }
366
+ return relevantMessages.length;
367
+ }
368
+ async backfillAllChannels() {
369
+ const startTime = Date.now();
370
+ // Only backfill channels that already have a log.jsonl (mom has interacted with them before)
371
+ const channelsToBackfill = [];
372
+ for (const [channelId, channel] of this.channels) {
373
+ const logPath = join(this.workingDir, channelId, "log.jsonl");
374
+ if (existsSync(logPath)) {
375
+ channelsToBackfill.push([channelId, channel]);
376
+ }
377
+ }
378
+ log.logBackfillStart(channelsToBackfill.length);
379
+ let totalMessages = 0;
380
+ for (const [channelId, channel] of channelsToBackfill) {
381
+ try {
382
+ const count = await this.backfillChannel(channelId);
383
+ if (count > 0)
384
+ log.logBackfillChannel(channel.name, count);
385
+ totalMessages += count;
386
+ }
387
+ catch (error) {
388
+ log.logWarning(`Failed to backfill #${channel.name}`, String(error));
389
+ }
390
+ }
391
+ const durationMs = Date.now() - startTime;
392
+ log.logBackfillComplete(totalMessages, durationMs);
393
+ }
394
+ // ==========================================================================
395
+ // Private - Fetch Users/Channels
396
+ // ==========================================================================
397
+ async fetchUsers() {
398
+ let cursor;
399
+ do {
400
+ const result = await this.webClient.users.list({ limit: 200, cursor });
401
+ const members = result.members;
402
+ if (members) {
403
+ for (const u of members) {
404
+ if (u.id && u.name && !u.deleted) {
405
+ this.users.set(u.id, { id: u.id, userName: u.name, displayName: u.real_name || u.name });
406
+ }
407
+ }
408
+ }
409
+ cursor = result.response_metadata?.next_cursor;
410
+ } while (cursor);
411
+ }
412
+ async fetchChannels() {
413
+ // Fetch public/private channels
414
+ let cursor;
415
+ do {
416
+ const result = await this.webClient.conversations.list({
417
+ types: "public_channel,private_channel",
418
+ exclude_archived: true,
419
+ limit: 200,
420
+ cursor,
421
+ });
422
+ const channels = result.channels;
423
+ if (channels) {
424
+ for (const c of channels) {
425
+ if (c.id && c.name && c.is_member) {
426
+ this.channels.set(c.id, { id: c.id, name: c.name });
427
+ }
428
+ }
429
+ }
430
+ cursor = result.response_metadata?.next_cursor;
431
+ } while (cursor);
432
+ // Also fetch DM channels (IMs)
433
+ cursor = undefined;
434
+ do {
435
+ const result = await this.webClient.conversations.list({
436
+ types: "im",
437
+ limit: 200,
438
+ cursor,
439
+ });
440
+ const ims = result.channels;
441
+ if (ims) {
442
+ for (const im of ims) {
443
+ if (im.id) {
444
+ // Use user's name as channel name for DMs
445
+ const user = im.user ? this.users.get(im.user) : undefined;
446
+ const name = user ? `DM:${user.userName}` : `DM:${im.id}`;
447
+ this.channels.set(im.id, { id: im.id, name });
448
+ }
449
+ }
450
+ }
451
+ cursor = result.response_metadata?.next_cursor;
452
+ } while (cursor);
453
+ }
454
+ }
455
+ //# sourceMappingURL=slack.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slack.js","sourceRoot":"","sources":["../src/slack.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACtC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAyFhC,MAAM,YAAY;IACT,KAAK,GAAiB,EAAE,CAAC;IACzB,UAAU,GAAG,KAAK,CAAC;IAE3B,OAAO,CAAC,IAAgB,EAAQ;QAC/B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,IAAI,CAAC,WAAW,EAAE,CAAC;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port { appendFileSync, existsSync, mkdirSync, readFileSync } from \"fs\";\nimport { basename, join } from \"path\";\nimport * as log from \"./log.js\";\nimport type { Attachment, ChannelStore } from \"./store.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface SlackEvent {\n\ttype: \"mention\" | \"dm\";\n\tchannel: string;\n\tts: string;\n\tuser: string;\n\ttext: string;\n\tfiles?: Array<{ name?: string; url_private_download?: string; url_private?: string }>;\n\t/** Processed attachments with local paths (populated after logUserMessage) */\n\tattachments?: Attachment[];\n}\n\nexport interface SlackUser {\n\tid: string;\n\tuserName: string;\n\tdisplayName: string;\n}\n\nexport interface SlackChannel {\n\tid: string;\n\tname: string;\n}\n\n// Types used by agent.ts\nexport interface ChannelInfo {\n\tid: string;\n\tname: string;\n}\n\nexport interface UserInfo {\n\tid: string;\n\tuserName: string;\n\tdisplayName: string;\n}\n\nexport interface SlackContext {\n\tmessage: {\n\t\ttext: string;\n\t\trawText: string;\n\t\tuser: string;\n\t\tuserName?: string;\n\t\tchannel: string;\n\t\tts: string;\n\t\tattachments: Array<{ local: string }>;\n\t};\n\tchannelName?: string;\n\tchannels: ChannelInfo[];\n\tusers: UserInfo[];\n\trespond: (text: string, shouldLog?: boolean) => Promise<void>;\n\treplaceMessage: (text: string) => Promise<void>;\n\trespondInThread: (text: string) => Promise<void>;\n\tsetTyping: (isTyping: boolean) => Promise<void>;\n\tuploadFile: (filePath: string, title?: string) => Promise<void>;\n\tsetWorking: (working: boolean) => Promise<void>;\n\tdeleteMessage: () => Promise<void>;\n}\n\nexport interface MomHandler {\n\t/**\n\t * Check if channel is currently running (SYNC)\n\t */\n\tisRunning(channelId: string): boolean;\n\n\t/**\n\t * Handle an event that triggers mom (ASYNC)\n\t * Called only when isRunning() returned false for user messages.\n\t * Events always queue and pass isEvent=true.\n\t */\n\thandleEvent(event: SlackEvent, slack: SlackBot, isEvent?: boolean): Promise<void>;\n\n\t/**\n\t * Handle stop command (ASYNC)\n\t * Called when user says \"stop\" while mom is running\n\t */\n\thandleStop(channelId: string, slack: SlackBot): Promise<void>;\n}\n\n// ============================================================================\n// Per-channel queue for sequential processing\n// ============================================================================\n\ntype QueuedWork = () => Promise<void>;\n\nclass ChannelQueue {\n\tprivate queue: QueuedWork[] = [];\n\tprivate processing = false;\n\n\tenqueue(work: QueuedWork): void {\n\t\tthis.queue.push(work);\n\t\tthis.processNext();\n\t}\n\n\tsize(): number {\n\t\treturn this.queue.length;\n\t}\n\n\tprivate async processNext(): Promise<void> {\n\t\tif (this.processing || this.queue.length === 0) return;\n\t\tthis.processing = true;\n\t\tconst work = this.queue.shift()!;\n\t\ttry {\n\t\t\tawait work();\n\t\t} catch (err) {\n\t\t\tlog.logWarning(\"Queue error\", err instanceof Error ? err.message : String(err));\n\t\t}\n\t\tthis.processing = false;\n\t\tthis.processNext();\n\t}\n}\n\n// ============================================================================\n// SlackBot\n// ============================================================================\n\nexport class SlackBot {\n\tprivate socketClient: SocketModeClient;\n\tprivate webClient: WebClient;\n\tprivate handler: MomHandler;\n\tprivate workingDir: string;\n\tprivate store: ChannelStore;\n\tprivate botUserId: string | null = null;\n\tprivate startupTs: string | null = null; // Messages older than this are just logged, not processed\n\n\tprivate users = new Map<string, SlackUser>();\n\tprivate channels = new Map<string, SlackChannel>();\n\tprivate queues = new Map<string, ChannelQueue>();\n\n\tconstructor(\n\t\thandler: MomHandler,\n\t\tconfig: { appToken: string; botToken: string; workingDir: string; store: ChannelStore },\n\t) {\n\t\tthis.handler = handler;\n\t\tthis.workingDir = config.workingDir;\n\t\tthis.store = config.store;\n\t\tthis.socketClient = new SocketModeClient({ appToken: config.appToken });\n\t\tthis.webClient = new WebClient(config.botToken);\n\t}\n\n\t// ==========================================================================\n\t// Public API\n\t// ==========================================================================\n\n\tasync start(): Promise<void> {\n\t\tconst auth = await this.webClient.auth.test();\n\t\tthis.botUserId = auth.user_id as string;\n\n\t\tawait Promise.all([this.fetchUsers(), this.fetchChannels()]);\n\t\tlog.logInfo(`Loaded ${this.channels.size} channels, ${this.users.size} users`);\n\n\t\tawait this.backfillAllChannels();\n\n\t\tthis.setupEventHandlers();\n\t\tawait this.socketClient.start();\n\n\t\t// Record startup time - messages older than this are just logged, not processed\n\t\tthis.startupTs = (Date.now() / 1000).toFixed(6);\n\n\t\tlog.logConnected();\n\t}\n\n\tgetUser(userId: string): SlackUser | undefined {\n\t\treturn this.users.get(userId);\n\t}\n\n\tgetChannel(channelId: string): SlackChannel | undefined {\n\t\treturn this.channels.get(channelId);\n\t}\n\n\tgetAllUsers(): SlackUser[] {\n\t\treturn Array.from(this.users.values());\n\t}\n\n\tgetAllChannels(): SlackChannel[] {\n\t\treturn Array.from(this.channels.values());\n\t}\n\n\tasync postMessage(channel: string, text: string): Promise<string> {\n\t\tconst result = await this.webClient.chat.postMessage({ channel, text });\n\t\treturn result.ts as string;\n\t}\n\n\tasync updateMessage(channel: string, ts: string, text: string): Promise<void> {\n\t\tawait this.webClient.chat.update({ channel, ts, text });\n\t}\n\n\tasync deleteMessage(channel: string, ts: string): Promise<void> {\n\t\tawait this.webClient.chat.delete({ channel, ts });\n\t}\n\n\tasync postInThread(channel: string, threadTs: string, text: string): Promise<string> {\n\t\tconst result = await this.webClient.chat.postMessage({ channel, thread_ts: threadTs, text });\n\t\treturn result.ts as string;\n\t}\n\n\tasync uploadFile(channel: string, filePath: string, title?: string): Promise<void> {\n\t\tconst fileName = title || basename(filePath);\n\t\tconst fileContent = readFileSync(filePath);\n\t\tawait this.webClient.files.uploadV2({\n\t\t\tchannel_id: channel,\n\t\t\tfile: fileContent,\n\t\t\tfilename: fileName,\n\t\t\ttitle: fileName,\n\t\t});\n\t}\n\n\t/**\n\t * Log a message to log.jsonl (SYNC)\n\t * This is the ONLY place messages are written to log.jsonl\n\t */\n\tlogToFile(channel: string, entry: object): void {\n\t\tconst dir = join(this.workingDir, channel);\n\t\tif (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\t\tappendFileSync(join(dir, \"log.jsonl\"), `${JSON.stringify(entry)}\\n`);\n\t}\n\n\t/**\n\t * Log a bot response to log.jsonl\n\t */\n\tlogBotResponse(channel: string, text: string, ts: string): void {\n\t\tthis.logToFile(channel, {\n\t\t\tdate: new Date().toISOString(),\n\t\t\tts,\n\t\t\tuser: \"bot\",\n\t\t\ttext,\n\t\t\tattachments: [],\n\t\t\tisBot: true,\n\t\t});\n\t}\n\n\t// ==========================================================================\n\t// Events Integration\n\t// ==========================================================================\n\n\t/**\n\t * Enqueue an event for processing. Always queues (no \"already working\" rejection).\n\t * Returns true if enqueued, false if queue is full (max 5).\n\t */\n\tenqueueEvent(event: SlackEvent): boolean {\n\t\tconst queue = this.getQueue(event.channel);\n\t\tif (queue.size() >= 5) {\n\t\t\tlog.logWarning(`Event queue full for ${event.channel}, discarding: ${event.text.substring(0, 50)}`);\n\t\t\treturn false;\n\t\t}\n\t\tlog.logInfo(`Enqueueing event for ${event.channel}: ${event.text.substring(0, 50)}`);\n\t\tqueue.enqueue(() => this.handler.handleEvent(event, this, true));\n\t\treturn true;\n\t}\n\n\t// ==========================================================================\n\t// Private - Event Handlers\n\t// ==========================================================================\n\n\tprivate getQueue(channelId: string): ChannelQueue {\n\t\tlet queue = this.queues.get(channelId);\n\t\tif (!queue) {\n\t\t\tqueue = new ChannelQueue();\n\t\t\tthis.queues.set(channelId, queue);\n\t\t}\n\t\treturn queue;\n\t}\n\n\tprivate setupEventHandlers(): void {\n\t\t// Channel @mentions\n\t\tthis.socketClient.on(\"app_mention\", ({ event, ack }) => {\n\t\t\tconst e = event as {\n\t\t\t\ttext: string;\n\t\t\t\tchannel: string;\n\t\t\t\tuser: string;\n\t\t\t\tts: string;\n\t\t\t\tfiles?: Array<{ name: string; url_private_download?: string; url_private?: string }>;\n\t\t\t};\n\n\t\t\t// Skip DMs (handled by message event)\n\t\t\tif (e.channel.startsWith(\"D\")) {\n\t\t\t\tack();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst slackEvent: SlackEvent = {\n\t\t\t\ttype: \"mention\",\n\t\t\t\tchannel: e.channel,\n\t\t\t\tts: e.ts,\n\t\t\t\tuser: e.user,\n\t\t\t\ttext: e.text.replace(/<@[A-Z0-9]+>/gi, \"\").trim(),\n\t\t\t\tfiles: e.files,\n\t\t\t};\n\n\t\t\t// SYNC: Log to log.jsonl (ALWAYS, even for old messages)\n\t\t\t// Also downloads attachments in background and stores local paths\n\t\t\tslackEvent.attachments = this.logUserMessage(slackEvent);\n\n\t\t\t// Only trigger processing for messages AFTER startup (not replayed old messages)\n\t\t\tif (this.startupTs && e.ts < this.startupTs) {\n\t\t\t\tlog.logInfo(\n\t\t\t\t\t`[${e.channel}] Logged old message (pre-startup), not triggering: ${slackEvent.text.substring(0, 30)}`,\n\t\t\t\t);\n\t\t\t\tack();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for stop command - execute immediately, don't queue!\n\t\t\tif (slackEvent.text.toLowerCase().trim() === \"stop\") {\n\t\t\t\tif (this.handler.isRunning(e.channel)) {\n\t\t\t\t\tthis.handler.handleStop(e.channel, this); // Don't await, don't queue\n\t\t\t\t} else {\n\t\t\t\t\tthis.postMessage(e.channel, \"_Nothing running_\");\n\t\t\t\t}\n\t\t\t\tack();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// SYNC: Check if busy\n\t\t\tif (this.handler.isRunning(e.channel)) {\n\t\t\t\tthis.postMessage(e.channel, \"_Already working. Say `@mom stop` to cancel._\");\n\t\t\t} else {\n\t\t\t\tthis.getQueue(e.channel).enqueue(() => this.handler.handleEvent(slackEvent, this));\n\t\t\t}\n\n\t\t\tack();\n\t\t});\n\n\t\t// All messages (for logging) + DMs (for triggering)\n\t\tthis.socketClient.on(\"message\", ({ event, ack }) => {\n\t\t\tconst e = event as {\n\t\t\t\ttext?: string;\n\t\t\t\tchannel: string;\n\t\t\t\tuser?: string;\n\t\t\t\tts: string;\n\t\t\t\tchannel_type?: string;\n\t\t\t\tsubtype?: string;\n\t\t\t\tbot_id?: string;\n\t\t\t\tfiles?: Array<{ name: string; url_private_download?: string; url_private?: string }>;\n\t\t\t};\n\n\t\t\t// Skip bot messages, edits, etc.\n\t\t\tif (e.bot_id || !e.user || e.user === this.botUserId) {\n\t\t\t\tack();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.subtype !== undefined && e.subtype !== \"file_share\") {\n\t\t\t\tack();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!e.text && (!e.files || e.files.length === 0)) {\n\t\t\t\tack();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst isDM = e.channel_type === \"im\";\n\t\t\tconst isBotMention = e.text?.includes(`<@${this.botUserId}>`);\n\n\t\t\t// Skip channel @mentions - already handled by app_mention event\n\t\t\tif (!isDM && isBotMention) {\n\t\t\t\tack();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst slackEvent: SlackEvent = {\n\t\t\t\ttype: isDM ? \"dm\" : \"mention\",\n\t\t\t\tchannel: e.channel,\n\t\t\t\tts: e.ts,\n\t\t\t\tuser: e.user,\n\t\t\t\ttext: (e.text || \"\").replace(/<@[A-Z0-9]+>/gi, \"\").trim(),\n\t\t\t\tfiles: e.files,\n\t\t\t};\n\n\t\t\t// SYNC: Log to log.jsonl (ALL messages - channel chatter and DMs)\n\t\t\t// Also downloads attachments in background and stores local paths\n\t\t\tslackEvent.attachments = this.logUserMessage(slackEvent);\n\n\t\t\t// Only trigger processing for messages AFTER startup (not replayed old messages)\n\t\t\tif (this.startupTs && e.ts < this.startupTs) {\n\t\t\t\tlog.logInfo(`[${e.channel}] Skipping old message (pre-startup): ${slackEvent.text.substring(0, 30)}`);\n\t\t\t\tack();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Only trigger handler for DMs\n\t\t\tif (isDM) {\n\t\t\t\t// Check for stop command - execute immediately, don't queue!\n\t\t\t\tif (slackEvent.text.toLowerCase().trim() === \"stop\") {\n\t\t\t\t\tif (this.handler.isRunning(e.channel)) {\n\t\t\t\t\t\tthis.handler.handleStop(e.channel, this); // Don't await, don't queue\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.postMessage(e.channel, \"_Nothing running_\");\n\t\t\t\t\t}\n\t\t\t\t\tack();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (this.handler.isRunning(e.channel)) {\n\t\t\t\t\tthis.postMessage(e.channel, \"_Already working. Say `stop` to cancel._\");\n\t\t\t\t} else {\n\t\t\t\t\tthis.getQueue(e.channel).enqueue(() => this.handler.handleEvent(slackEvent, this));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tack();\n\t\t});\n\t}\n\n\t/**\n\t * Log a user message to log.jsonl (SYNC)\n\t * Downloads attachments in background via store\n\t */\n\tprivate logUserMessage(event: SlackEvent): Attachment[] {\n\t\tconst user = this.users.get(event.user);\n\t\t// Process attachments - queues downloads in background\n\t\tconst attachments = event.files ? this.store.processAttachments(event.channel, event.files, event.ts) : [];\n\t\tthis.logToFile(event.channel, {\n\t\t\tdate: new Date(parseFloat(event.ts) * 1000).toISOString(),\n\t\t\tts: event.ts,\n\t\t\tuser: event.user,\n\t\t\tuserName: user?.userName,\n\t\t\tdisplayName: user?.displayName,\n\t\t\ttext: event.text,\n\t\t\tattachments,\n\t\t\tisBot: false,\n\t\t});\n\t\treturn attachments;\n\t}\n\n\t// ==========================================================================\n\t// Private - Backfill\n\t// ==========================================================================\n\n\tprivate getExistingTimestamps(channelId: string): Set<string> {\n\t\tconst logPath = join(this.workingDir, channelId, \"log.jsonl\");\n\t\tconst timestamps = new Set<string>();\n\t\tif (!existsSync(logPath)) return timestamps;\n\n\t\tconst content = readFileSync(logPath, \"utf-8\");\n\t\tconst lines = content.trim().split(\"\\n\").filter(Boolean);\n\t\tfor (const line of lines) {\n\t\t\ttry {\n\t\t\t\tconst entry = JSON.parse(line);\n\t\t\t\tif (entry.ts) timestamps.add(entry.ts);\n\t\t\t} catch {}\n\t\t}\n\t\treturn timestamps;\n\t}\n\n\tprivate async backfillChannel(channelId: string): Promise<number> {\n\t\tconst existingTs = this.getExistingTimestamps(channelId);\n\n\t\t// Find the biggest ts in log.jsonl\n\t\tlet latestTs: string | undefined;\n\t\tfor (const ts of existingTs) {\n\t\t\tif (!latestTs || parseFloat(ts) > parseFloat(latestTs)) latestTs = ts;\n\t\t}\n\n\t\ttype Message = {\n\t\t\tuser?: string;\n\t\t\tbot_id?: string;\n\t\t\ttext?: string;\n\t\t\tts?: string;\n\t\t\tsubtype?: string;\n\t\t\tfiles?: Array<{ name: string }>;\n\t\t};\n\t\tconst allMessages: Message[] = [];\n\n\t\tlet cursor: string | undefined;\n\t\tlet pageCount = 0;\n\t\tconst maxPages = 3;\n\n\t\tdo {\n\t\t\tconst result = await this.webClient.conversations.history({\n\t\t\t\tchannel: channelId,\n\t\t\t\toldest: latestTs, // Only fetch messages newer than what we have\n\t\t\t\tinclusive: false,\n\t\t\t\tlimit: 1000,\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tif (result.messages) {\n\t\t\t\tallMessages.push(...(result.messages as Message[]));\n\t\t\t}\n\t\t\tcursor = result.response_metadata?.next_cursor;\n\t\t\tpageCount++;\n\t\t} while (cursor && pageCount < maxPages);\n\n\t\t// Filter: include mom's messages, exclude other bots, skip already logged\n\t\tconst relevantMessages = allMessages.filter((msg) => {\n\t\t\tif (!msg.ts || existingTs.has(msg.ts)) return false; // Skip duplicates\n\t\t\tif (msg.user === this.botUserId) return true;\n\t\t\tif (msg.bot_id) return false;\n\t\t\tif (msg.subtype !== undefined && msg.subtype !== \"file_share\") return false;\n\t\t\tif (!msg.user) return false;\n\t\t\tif (!msg.text && (!msg.files || msg.files.length === 0)) return false;\n\t\t\treturn true;\n\t\t});\n\n\t\t// Reverse to chronological order\n\t\trelevantMessages.reverse();\n\n\t\t// Log each message to log.jsonl\n\t\tfor (const msg of relevantMessages) {\n\t\t\tconst isMomMessage = msg.user === this.botUserId;\n\t\t\tconst user = this.users.get(msg.user!);\n\t\t\t// Strip @mentions from text (same as live messages)\n\t\t\tconst text = (msg.text || \"\").replace(/<@[A-Z0-9]+>/gi, \"\").trim();\n\t\t\t// Process attachments - queues downloads in background\n\t\t\tconst attachments = msg.files ? this.store.processAttachments(channelId, msg.files, msg.ts!) : [];\n\n\t\t\tthis.logToFile(channelId, {\n\t\t\t\tdate: new Date(parseFloat(msg.ts!) * 1000).toISOString(),\n\t\t\t\tts: msg.ts!,\n\t\t\t\tuser: isMomMessage ? \"bot\" : msg.user!,\n\t\t\t\tuserName: isMomMessage ? undefined : user?.userName,\n\t\t\t\tdisplayName: isMomMessage ? undefined : user?.displayName,\n\t\t\t\ttext,\n\t\t\t\tattachments,\n\t\t\t\tisBot: isMomMessage,\n\t\t\t});\n\t\t}\n\n\t\treturn relevantMessages.length;\n\t}\n\n\tprivate async backfillAllChannels(): Promise<void> {\n\t\tconst startTime = Date.now();\n\n\t\t// Only backfill channels that already have a log.jsonl (mom has interacted with them before)\n\t\tconst channelsToBackfill: Array<[string, SlackChannel]> = [];\n\t\tfor (const [channelId, channel] of this.channels) {\n\t\t\tconst logPath = join(this.workingDir, channelId, \"log.jsonl\");\n\t\t\tif (existsSync(logPath)) {\n\t\t\t\tchannelsToBackfill.push([channelId, channel]);\n\t\t\t}\n\t\t}\n\n\t\tlog.logBackfillStart(channelsToBackfill.length);\n\n\t\tlet totalMessages = 0;\n\t\tfor (const [channelId, channel] of channelsToBackfill) {\n\t\t\ttry {\n\t\t\t\tconst count = await this.backfillChannel(channelId);\n\t\t\t\tif (count > 0) log.logBackfillChannel(channel.name, count);\n\t\t\t\ttotalMessages += count;\n\t\t\t} catch (error) {\n\t\t\t\tlog.logWarning(`Failed to backfill #${channel.name}`, String(error));\n\t\t\t}\n\t\t}\n\n\t\tconst durationMs = Date.now() - startTime;\n\t\tlog.logBackfillComplete(totalMessages, durationMs);\n\t}\n\n\t// ==========================================================================\n\t// Private - Fetch Users/Channels\n\t// ==========================================================================\n\n\tprivate async fetchUsers(): Promise<void> {\n\t\tlet cursor: string | undefined;\n\t\tdo {\n\t\t\tconst result = await this.webClient.users.list({ limit: 200, cursor });\n\t\t\tconst members = result.members as\n\t\t\t\t| Array<{ id?: string; name?: string; real_name?: string; deleted?: boolean }>\n\t\t\t\t| undefined;\n\t\t\tif (members) {\n\t\t\t\tfor (const u of members) {\n\t\t\t\t\tif (u.id && u.name && !u.deleted) {\n\t\t\t\t\t\tthis.users.set(u.id, { id: u.id, userName: u.name, displayName: u.real_name || u.name });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcursor = result.response_metadata?.next_cursor;\n\t\t} while (cursor);\n\t}\n\n\tprivate async fetchChannels(): Promise<void> {\n\t\t// Fetch public/private channels\n\t\tlet cursor: string | undefined;\n\t\tdo {\n\t\t\tconst result = await this.webClient.conversations.list({\n\t\t\t\ttypes: \"public_channel,private_channel\",\n\t\t\t\texclude_archived: true,\n\t\t\t\tlimit: 200,\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst channels = result.channels as Array<{ id?: string; name?: string; is_member?: boolean }> | undefined;\n\t\t\tif (channels) {\n\t\t\t\tfor (const c of channels) {\n\t\t\t\t\tif (c.id && c.name && c.is_member) {\n\t\t\t\t\t\tthis.channels.set(c.id, { id: c.id, name: c.name });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcursor = result.response_metadata?.next_cursor;\n\t\t} while (cursor);\n\n\t\t// Also fetch DM channels (IMs)\n\t\tcursor = undefined;\n\t\tdo {\n\t\t\tconst result = await this.webClient.conversations.list({\n\t\t\t\ttypes: \"im\",\n\t\t\t\tlimit: 200,\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst ims = result.channels as Array<{ id?: string; user?: string }> | undefined;\n\t\t\tif (ims) {\n\t\t\t\tfor (const im of ims) {\n\t\t\t\t\tif (im.id) {\n\t\t\t\t\t\t// Use user's name as channel name for DMs\n\t\t\t\t\t\tconst user = im.user ? this.users.get(im.user) : undefined;\n\t\t\t\t\t\tconst name = user ? `DM:${user.userName}` : `DM:${im.id}`;\n\t\t\t\t\t\tthis.channels.set(im.id, { id: im.id, name });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcursor = result.response_metadata?.next_cursor;\n\t\t} while (cursor);\n\t}\n}\n"]}
@@ -0,0 +1,60 @@
1
+ export interface Attachment {
2
+ original: string;
3
+ local: string;
4
+ }
5
+ export interface LoggedMessage {
6
+ date: string;
7
+ ts: string;
8
+ user: string;
9
+ userName?: string;
10
+ displayName?: string;
11
+ text: string;
12
+ attachments: Attachment[];
13
+ isBot: boolean;
14
+ }
15
+ export interface ChannelStoreConfig {
16
+ workingDir: string;
17
+ botToken: string;
18
+ }
19
+ export declare class ChannelStore {
20
+ private workingDir;
21
+ private botToken;
22
+ private pendingDownloads;
23
+ private isDownloading;
24
+ private recentlyLogged;
25
+ constructor(config: ChannelStoreConfig);
26
+ /**
27
+ * Get or create the directory for a channel/DM
28
+ */
29
+ getChannelDir(channelId: string): string;
30
+ /**
31
+ * Generate a unique local filename for an attachment
32
+ */
33
+ generateLocalFilename(originalName: string, timestamp: string): string;
34
+ /**
35
+ * Process attachments from a Slack message event
36
+ * Returns attachment metadata and queues downloads
37
+ */
38
+ processAttachments(channelId: string, files: Array<{
39
+ name?: string;
40
+ url_private_download?: string;
41
+ url_private?: string;
42
+ }>, timestamp: string): Attachment[];
43
+ /**
44
+ * Log a message to the channel's log.jsonl
45
+ * Returns false if message was already logged (duplicate)
46
+ */
47
+ logMessage(channelId: string, message: LoggedMessage): Promise<boolean>;
48
+ /**
49
+ * Log a bot response
50
+ */
51
+ logBotResponse(channelId: string, text: string, ts: string): Promise<void>;
52
+ /**
53
+ * Get the timestamp of the last logged message for a channel
54
+ * Returns null if no log exists
55
+ */
56
+ getLastTimestamp(channelId: string): string | null;
57
+ private processDownloadQueue;
58
+ private downloadAttachment;
59
+ }
60
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","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A8B5E;IAED;;OAEG;IACG,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAS/E;IAED;;;OAGG;IACH,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAkBjD;YAKa,oBAAoB;YAwBpB,kBAAkB;CAsBhC","sourcesContent":["import { existsSync, mkdirSync, readFileSync } from \"fs\";\nimport { appendFile, writeFile } from \"fs/promises\";\nimport { join } from \"path\";\nimport * as log from \"./log.js\";\n\nexport interface Attachment {\n\toriginal: string; // original filename from uploader\n\tlocal: string; // path relative to working dir (e.g., \"C12345/attachments/1732531234567_file.png\")\n}\n\nexport interface LoggedMessage {\n\tdate: string; // ISO 8601 date (e.g., \"2025-11-26T10:44:00.000Z\") for easy grepping\n\tts: string; // slack timestamp or epoch ms\n\tuser: string; // user ID (or \"bot\" for bot responses)\n\tuserName?: string; // handle (e.g., \"mario\")\n\tdisplayName?: string; // display name (e.g., \"Mario Zechner\")\n\ttext: string;\n\tattachments: Attachment[];\n\tisBot: boolean;\n}\n\nexport interface ChannelStoreConfig {\n\tworkingDir: string;\n\tbotToken: string; // needed for authenticated file downloads\n}\n\ninterface PendingDownload {\n\tchannelId: string;\n\tlocalPath: string; // relative path\n\turl: string;\n}\n\nexport class ChannelStore {\n\tprivate workingDir: string;\n\tprivate botToken: string;\n\tprivate pendingDownloads: PendingDownload[] = [];\n\tprivate isDownloading = false;\n\t// Track recently logged message timestamps to prevent duplicates\n\t// Key: \"channelId:ts\", automatically cleaned up after 60 seconds\n\tprivate recentlyLogged = new Map<string, number>();\n\n\tconstructor(config: ChannelStoreConfig) {\n\t\tthis.workingDir = config.workingDir;\n\t\tthis.botToken = config.botToken;\n\n\t\t// Ensure working directory exists\n\t\tif (!existsSync(this.workingDir)) {\n\t\t\tmkdirSync(this.workingDir, { recursive: true });\n\t\t}\n\t}\n\n\t/**\n\t * Get or create the directory for a channel/DM\n\t */\n\tgetChannelDir(channelId: string): string {\n\t\tconst dir = join(this.workingDir, channelId);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\t\treturn dir;\n\t}\n\n\t/**\n\t * Generate a unique local filename for an attachment\n\t */\n\tgenerateLocalFilename(originalName: string, timestamp: string): string {\n\t\t// Convert slack timestamp (1234567890.123456) to milliseconds\n\t\tconst ts = Math.floor(parseFloat(timestamp) * 1000);\n\t\t// Sanitize original name (remove problematic characters)\n\t\tconst sanitized = originalName.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n\t\treturn `${ts}_${sanitized}`;\n\t}\n\n\t/**\n\t * Process attachments from a Slack message event\n\t * Returns attachment metadata and queues downloads\n\t */\n\tprocessAttachments(\n\t\tchannelId: string,\n\t\tfiles: Array<{ name?: string; url_private_download?: string; url_private?: string }>,\n\t\ttimestamp: string,\n\t): Attachment[] {\n\t\tconst attachments: Attachment[] = [];\n\n\t\tfor (const file of files) {\n\t\t\tconst url = file.url_private_download || file.url_private;\n\t\t\tif (!url) continue;\n\t\t\tif (!file.name) {\n\t\t\t\tlog.logWarning(\"Attachment missing name, skipping\", url);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst filename = this.generateLocalFilename(file.name, timestamp);\n\t\t\tconst localPath = `${channelId}/attachments/${filename}`;\n\n\t\t\tattachments.push({\n\t\t\t\toriginal: file.name,\n\t\t\t\tlocal: localPath,\n\t\t\t});\n\n\t\t\t// Queue for background download\n\t\t\tthis.pendingDownloads.push({ channelId, localPath, url });\n\t\t}\n\n\t\t// Trigger background download\n\t\tthis.processDownloadQueue();\n\n\t\treturn attachments;\n\t}\n\n\t/**\n\t * Log a message to the channel's log.jsonl\n\t * Returns false if message was already logged (duplicate)\n\t */\n\tasync logMessage(channelId: string, message: LoggedMessage): Promise<boolean> {\n\t\t// Check for duplicate (same channel + timestamp)\n\t\tconst dedupeKey = `${channelId}:${message.ts}`;\n\t\tif (this.recentlyLogged.has(dedupeKey)) {\n\t\t\treturn false; // Already logged\n\t\t}\n\n\t\t// Mark as logged and schedule cleanup after 60 seconds\n\t\tthis.recentlyLogged.set(dedupeKey, Date.now());\n\t\tsetTimeout(() => this.recentlyLogged.delete(dedupeKey), 60000);\n\n\t\tconst logPath = join(this.getChannelDir(channelId), \"log.jsonl\");\n\n\t\t// Ensure message has a date field\n\t\tif (!message.date) {\n\t\t\t// Parse timestamp to get date\n\t\t\tlet date: Date;\n\t\t\tif (message.ts.includes(\".\")) {\n\t\t\t\t// Slack timestamp format (1234567890.123456)\n\t\t\t\tdate = new Date(parseFloat(message.ts) * 1000);\n\t\t\t} else {\n\t\t\t\t// Epoch milliseconds\n\t\t\t\tdate = new Date(parseInt(message.ts, 10));\n\t\t\t}\n\t\t\tmessage.date = date.toISOString();\n\t\t}\n\n\t\tconst line = `${JSON.stringify(message)}\\n`;\n\t\tawait appendFile(logPath, line, \"utf-8\");\n\t\treturn true;\n\t}\n\n\t/**\n\t * Log a bot response\n\t */\n\tasync logBotResponse(channelId: string, text: string, ts: string): Promise<void> {\n\t\tawait this.logMessage(channelId, {\n\t\t\tdate: new Date().toISOString(),\n\t\t\tts,\n\t\t\tuser: \"bot\",\n\t\t\ttext,\n\t\t\tattachments: [],\n\t\t\tisBot: true,\n\t\t});\n\t}\n\n\t/**\n\t * Get the timestamp of the last logged message for a channel\n\t * Returns null if no log exists\n\t */\n\tgetLastTimestamp(channelId: string): string | null {\n\t\tconst logPath = join(this.workingDir, channelId, \"log.jsonl\");\n\t\tif (!existsSync(logPath)) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(logPath, \"utf-8\");\n\t\t\tconst lines = content.trim().split(\"\\n\");\n\t\t\tif (lines.length === 0 || lines[0] === \"\") {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst lastLine = lines[lines.length - 1];\n\t\t\tconst message = JSON.parse(lastLine) as LoggedMessage;\n\t\t\treturn message.ts;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Process the download queue in the background\n\t */\n\tprivate async processDownloadQueue(): Promise<void> {\n\t\tif (this.isDownloading || this.pendingDownloads.length === 0) return;\n\n\t\tthis.isDownloading = true;\n\n\t\twhile (this.pendingDownloads.length > 0) {\n\t\t\tconst item = this.pendingDownloads.shift();\n\t\t\tif (!item) break;\n\n\t\t\ttry {\n\t\t\t\tawait this.downloadAttachment(item.localPath, item.url);\n\t\t\t\t// Success - could add success logging here if we have context\n\t\t\t} catch (error) {\n\t\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\t\tlog.logWarning(`Failed to download attachment`, `${item.localPath}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\n\t\tthis.isDownloading = false;\n\t}\n\n\t/**\n\t * Download a single attachment\n\t */\n\tprivate async downloadAttachment(localPath: string, url: string): Promise<void> {\n\t\tconst filePath = join(this.workingDir, localPath);\n\n\t\t// Ensure directory exists\n\t\tconst dir = join(this.workingDir, localPath.substring(0, localPath.lastIndexOf(\"/\")));\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\n\t\tconst response = await fetch(url, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${this.botToken}`,\n\t\t\t},\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`HTTP ${response.status}: ${response.statusText}`);\n\t\t}\n\n\t\tconst buffer = await response.arrayBuffer();\n\t\tawait writeFile(filePath, Buffer.from(buffer));\n\t}\n}\n"]}