@christang/keel 5.84.0 → 5.85.0

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.
@@ -0,0 +1,808 @@
1
+ "use strict";
2
+
3
+ // The Slack bridge (issue #187, design D14–D16): one process per machine that
4
+ // relays every opted-in project on that machine to Slack and back, so sessions
5
+ // on other machines and the owner's phone take part in real time.
6
+ //
7
+ // The local store stays the only source of truth. Agents never talk to Slack;
8
+ // they run `keel chat`, and the bridge carries records out and in. Each
9
+ // machine has its own Slack app (Socket Mode delivers each event to one
10
+ // connection of an app, design F1) and posts only records that originated on
11
+ // it, carrying the exact record in message metadata so other machines rebuild
12
+ // it rather than re-parse prose.
13
+ //
14
+ // Bridge state lives in each project's store under `bridge/`, in the local
15
+ // layer: `bridge/posted/<id>.json` maps a record to its channel and ts.
16
+
17
+ const fs = require("fs");
18
+ const os = require("os");
19
+ const path = require("path");
20
+ const store = require("./store");
21
+ const { slackSettings } = require("./config");
22
+ const { redact } = require("./redact");
23
+ const slack = require("./slack");
24
+ const lifecycle = require("./lifecycle");
25
+
26
+ const { ChatError } = store;
27
+ const METADATA_TYPE = "keel_chat_record";
28
+ const TEXT_LIMIT = 3000;
29
+ const OUTBOUND_ORIGINS = new Set(["local", "migrated"]);
30
+
31
+ function keelHome() {
32
+ return process.env.KEEL_HOME || path.join(os.homedir(), ".keel");
33
+ }
34
+
35
+ function registryFile() {
36
+ return path.join(keelHome(), "chat", "projects.json");
37
+ }
38
+
39
+ function readRegistry() {
40
+ try {
41
+ const parsed = JSON.parse(fs.readFileSync(registryFile(), "utf8"));
42
+ return Array.isArray(parsed.projects) ? parsed.projects.filter((entry) => typeof entry === "string") : [];
43
+ } catch {
44
+ return [];
45
+ }
46
+ }
47
+
48
+ function writeRegistry(projects) {
49
+ const file = registryFile();
50
+ fs.mkdirSync(path.dirname(file), { recursive: true });
51
+ const temp = `${file}.${process.pid}.tmp`;
52
+ fs.writeFileSync(temp, `${JSON.stringify({ projects: [...new Set(projects)].sort() }, null, 2)}\n`);
53
+ fs.renameSync(temp, file);
54
+ }
55
+
56
+ // The registry holds paths only; each project's data stays in its own store.
57
+ function addProject(where) {
58
+ writeRegistry([...readRegistry(), where.worktree]);
59
+ return where.worktree;
60
+ }
61
+
62
+ function removeProject(where) {
63
+ writeRegistry(readRegistry().filter((entry) => entry !== where.worktree));
64
+ return where.worktree;
65
+ }
66
+
67
+ function requireWebSocket() {
68
+ if (typeof globalThis.WebSocket !== "function") {
69
+ throw new ChatError(
70
+ `keel chat bridge needs Node 22 or newer for its built-in WebSocket; this is Node ${process.versions.node}. `
71
+ + "The rest of keel chat works on this Node."
72
+ );
73
+ }
74
+ }
75
+
76
+ // --- served projects ----------------------------------------------------------
77
+
78
+ function servedProjects() {
79
+ const projects = [];
80
+ for (const entry of readRegistry()) {
81
+ const where = store.locate(entry);
82
+ if (!where) continue;
83
+ const settings = slackSettings(where.worktree);
84
+ if (!settings.enabled) continue;
85
+ projects.push({ where, settings });
86
+ }
87
+ // A channel mapped by more than one served project shows senders as
88
+ // `<project>/<role>` so readers can tell the projects apart (D3).
89
+ const mappers = new Map();
90
+ for (const project of projects) {
91
+ for (const channel of Object.values(project.settings.channels)) {
92
+ mappers.set(channel, (mappers.get(channel) || 0) + 1);
93
+ }
94
+ }
95
+ for (const project of projects) project.sharedChannels = new Set([...mappers].filter(([, n]) => n > 1).map(([c]) => c));
96
+ return projects;
97
+ }
98
+
99
+ // --- outbound -------------------------------------------------------------------
100
+
101
+ function postedFile(where, id) {
102
+ return path.join(where.root, "bridge", "posted", `${id}.json`);
103
+ }
104
+
105
+ function readPosted(where, id) {
106
+ try {
107
+ return JSON.parse(fs.readFileSync(postedFile(where, id), "utf8"));
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
113
+ function writePosted(where, id, value) {
114
+ store.writeJsonAtomic(where, postedFile(where, id), value);
115
+ }
116
+
117
+ function senderName(project, channel, role) {
118
+ return project.sharedChannels.has(channel) ? `${project.where.project}/${role}` : role;
119
+ }
120
+
121
+ function bodyText(record) {
122
+ switch (record.kind) {
123
+ case "todo":
124
+ return `☐ todo → ${record.assignee || "?"}${record.issue ? ` (${record.issue})` : ""}: ${record.text}`;
125
+ case "join":
126
+ return `${record.from} added ${record.target} to the group.`;
127
+ case "leave":
128
+ return `${record.from} removed ${record.target} from the group.`;
129
+ case "archive":
130
+ return `${record.from} archived the group; it takes no new messages.`;
131
+ default:
132
+ return record.text;
133
+ }
134
+ }
135
+
136
+ // Redact, then cut, then address: the cut must not split a `[redacted]`, and
137
+ // the owner mention must survive the cut.
138
+ function slackText(project, record, text) {
139
+ let result = redact(text);
140
+ if (result.length > TEXT_LIMIT) {
141
+ result = `${result.slice(0, TEXT_LIMIT)}… (cut; full text: \`keel chat show ${record.id}\`)`;
142
+ }
143
+ if ((record.mentions || []).includes(store.OWNER) && project.settings.owner) {
144
+ result = `<@${project.settings.owner}> ${result}`;
145
+ }
146
+ return result;
147
+ }
148
+
149
+ function metadataFor(project, record) {
150
+ const payload = { project: project.where.project, id: record.id, kind: record.kind, from: record.from, group: record.group };
151
+ for (const key of ["mentions", "reply_to", "assignee", "issue", "target"]) {
152
+ const value = record[key];
153
+ if (value !== undefined && value !== null && value !== "" && !(Array.isArray(value) && !value.length)) payload[key] = value;
154
+ }
155
+ return { event_type: METADATA_TYPE, event_payload: payload };
156
+ }
157
+
158
+ function iconFields(project, role) {
159
+ const icon = project.settings.icons[role];
160
+ if (!icon) return {};
161
+ return icon.startsWith(":") ? { icon_emoji: icon } : { icon_url: icon };
162
+ }
163
+
164
+ async function postRecord(ctx, project, record, channel) {
165
+ const { where } = project;
166
+ const call = (method, params) => slack.callWithRetry(method, params, ctx.token, {
167
+ onWait: (name, seconds) => ctx.log(`Slack asked to wait ${seconds}s before ${name}.`),
168
+ });
169
+ if (record.kind === "done" || record.kind === "edit" || record.kind === "retract") {
170
+ const target = readPosted(where, record.target);
171
+ if (!target || !target.ts) {
172
+ // The target never reached Slack (it predates the mapping): nothing to
173
+ // change there, and nothing to retry.
174
+ writePosted(where, record.id, { skipped: "target not on Slack" });
175
+ return;
176
+ }
177
+ if (record.kind === "done") {
178
+ await call("reactions.add", { channel: target.channel, timestamp: target.ts, name: "white_check_mark" });
179
+ } else if (record.kind === "edit") {
180
+ const original = store.findRecord(where, record.target) || {};
181
+ await call("chat.update", { channel: target.channel, ts: target.ts, text: slackText(project, original, bodyText({ ...original, text: record.text })) });
182
+ } else {
183
+ await call("chat.delete", { channel: target.channel, ts: target.ts });
184
+ }
185
+ writePosted(where, record.id, { channel: target.channel, ts: target.ts, kind: record.kind });
186
+ return;
187
+ }
188
+ const params = {
189
+ channel,
190
+ text: slackText(project, record, bodyText(record)),
191
+ username: senderName(project, channel, record.from),
192
+ metadata: metadataFor(project, record),
193
+ unfurl_links: false,
194
+ ...iconFields(project, record.from),
195
+ };
196
+ if (record.reply_to) {
197
+ const parent = readPosted(where, record.reply_to);
198
+ if (parent && parent.ts) params.thread_ts = parent.thread_ts || parent.ts;
199
+ else params.text = `↳ reply to ${record.reply_to}\n${params.text}`;
200
+ }
201
+ const response = await call("chat.postMessage", params);
202
+ const posted = { channel, ts: response.ts, thread_ts: params.thread_ts || null };
203
+ writePosted(where, record.id, posted);
204
+ rememberTs(project, channel, response.ts, record.id);
205
+ // Another project on this machine that maps the same channel gets the
206
+ // record now, without waiting for Slack to echo it back (D16).
207
+ for (const other of ctx.projects) {
208
+ if (other === project || !other.channelGroups.has(channel)) continue;
209
+ importKeelRecord(ctx, other, channel, params.metadata.event_payload, { ts: response.ts, text: record.text, thread_ts: params.thread_ts });
210
+ }
211
+ }
212
+
213
+ // Every record that originated on this machine, in a mapped group, and not yet
214
+ // posted, in id order. The queue is derived, so it survives any restart.
215
+ function pendingOutbound(project) {
216
+ const { where, settings } = project;
217
+ const pending = [];
218
+ for (const [group, channel] of Object.entries(settings.channels)) {
219
+ for (const record of store.readLog(where, group)) {
220
+ if (!OUTBOUND_ORIGINS.has(record.origin || "local")) continue;
221
+ if (readPosted(where, record.id)) continue;
222
+ pending.push({ record, channel });
223
+ }
224
+ }
225
+ return pending.sort((a, b) => (a.record.id < b.record.id ? -1 : 1));
226
+ }
227
+
228
+ async function flushOutbound(ctx) {
229
+ let posted = 0;
230
+ for (const project of ctx.projects) {
231
+ for (const { record, channel } of pendingOutbound(project)) {
232
+ await postRecord(ctx, project, record, channel);
233
+ posted += 1;
234
+ }
235
+ }
236
+ return posted;
237
+ }
238
+
239
+ function unpostedCount(projects) {
240
+ return projects.reduce((sum, project) => sum + pendingOutbound(project).length, 0);
241
+ }
242
+
243
+ // --- inbound --------------------------------------------------------------------
244
+
245
+ // channel|ts -> record id, for threads, edits, deletions, and reactions.
246
+ function buildTsIndex(project) {
247
+ project.tsIndex = new Map();
248
+ const dir = path.join(project.where.root, "bridge", "posted");
249
+ let names = [];
250
+ try {
251
+ names = fs.readdirSync(dir).filter((name) => name.endsWith(".json"));
252
+ } catch {
253
+ return;
254
+ }
255
+ for (const name of names) {
256
+ const posted = readPosted(project.where, name.slice(0, -5));
257
+ if (posted && posted.ts && posted.channel && !posted.kind) {
258
+ project.tsIndex.set(`${posted.channel}|${posted.ts}`, name.slice(0, -5));
259
+ }
260
+ }
261
+ }
262
+
263
+ function rememberTs(project, channel, ts, id) {
264
+ if (project.tsIndex) project.tsIndex.set(`${channel}|${ts}`, id);
265
+ }
266
+
267
+ function recordAt(project, channel, ts) {
268
+ return ts ? project.tsIndex.get(`${channel}|${ts}`) || null : null;
269
+ }
270
+
271
+ function tsToIso(ts) {
272
+ return store.isoLocal(new Date(Math.round(Number(ts) * 1000)));
273
+ }
274
+
275
+ // Undo what outbound added around a Keel record's text, so a rebuilt record
276
+ // reads like the original.
277
+ function unwrapText(project, text, kind) {
278
+ let result = String(text || "");
279
+ if (project.settings.owner) result = result.replace(new RegExp(`^<@${project.settings.owner}> `), "");
280
+ result = result.replace(/^↳ reply to \S+\n/, "");
281
+ if (kind === "todo") result = result.replace(/^☐ todo → [^:]*: /, "");
282
+ return result;
283
+ }
284
+
285
+ function importKeelRecord(ctx, project, channel, payload, message) {
286
+ const { where } = project;
287
+ if (!payload || !payload.id || store.findRecord(where, payload.id)) return false;
288
+ const same = payload.project === where.project;
289
+ // Membership and archive belong to each project; another project's are not
290
+ // imported into this one.
291
+ if (!same && !store.READABLE_KINDS.has(payload.kind)) return false;
292
+ const group = project.channelGroups.get(channel);
293
+ if (!group) return false;
294
+ store.writeRecord(where, {
295
+ id: payload.id,
296
+ group,
297
+ kind: payload.kind || "message",
298
+ from: same ? payload.from : `${payload.project}/${payload.from}`,
299
+ created: tsToIso(message.ts),
300
+ mentions: Array.isArray(payload.mentions) ? payload.mentions : [],
301
+ reply_to: payload.reply_to || null,
302
+ assignee: payload.assignee || null,
303
+ issue: payload.issue || null,
304
+ target: payload.target || null,
305
+ origin: same ? "slack" : `remote:${payload.project}`,
306
+ text: unwrapText(project, message.text, payload.kind),
307
+ });
308
+ writePosted(where, payload.id, { channel, ts: message.ts, thread_ts: message.thread_ts || null, origin: "slack" });
309
+ rememberTs(project, channel, message.ts, payload.id);
310
+ return true;
311
+ }
312
+
313
+ async function metadataOf(ctx, channel, event) {
314
+ if (event.metadata && event.metadata.event_type) return event.metadata;
315
+ const history = await slack.callWithRetry("conversations.history", {
316
+ channel, latest: event.ts, inclusive: true, limit: 1, include_all_metadata: true,
317
+ }, ctx.token);
318
+ const found = (history.messages || []).find((message) => message.ts === event.ts);
319
+ return (found && found.metadata) || null;
320
+ }
321
+
322
+ async function handleBotMessage(ctx, channel, event) {
323
+ // This bridge's own posts without a record — its online and stopped
324
+ // notices — carry nothing to import.
325
+ if (event.bot_id && event.bot_id === ctx.self.bot_id && !event.metadata) return;
326
+ const metadata = await metadataOf(ctx, channel, event);
327
+ if (!metadata || metadata.event_type !== METADATA_TYPE) return;
328
+ const payload = metadata.event_payload || {};
329
+ for (const project of projectsFor(ctx, channel)) {
330
+ // This bridge's own post, for this project, is already the local record.
331
+ if (event.bot_id === ctx.self.bot_id && payload.project === project.where.project) continue;
332
+ importKeelRecord(ctx, project, channel, payload, event);
333
+ }
334
+ }
335
+
336
+ const MENTION = /(^|[^\w@/])@([A-Za-z0-9][A-Za-z0-9/-]*)/g;
337
+
338
+ // A person typing in Slack gets no autocomplete, so an `@word` that names no
339
+ // member is left as text rather than refused (D16).
340
+ function lenientMentions(project, group, text) {
341
+ const state = store.groupState(store.readLog(project.where, group));
342
+ const aliases = store.aliasMap(project.where.root);
343
+ const mentions = [];
344
+ for (const match of String(text).matchAll(MENTION)) {
345
+ const token = match[2].replace(/[-/]+$/, "").toLowerCase();
346
+ let role = null;
347
+ if (token === store.ALL || token === store.OWNER || token.includes("/") || state.members.has(token)) role = token;
348
+ else if (aliases[token] && state.members.has(aliases[token])) role = aliases[token];
349
+ if (role && !mentions.includes(role)) mentions.push(role);
350
+ }
351
+ return mentions;
352
+ }
353
+
354
+ function humanText(project, event) {
355
+ let text = String(event.text || "").replace(/<@([A-Z0-9]+)(\|[^>]*)?>/g, (match, user) => {
356
+ const role = project.settings.members[user];
357
+ return role ? `@${role}` : match;
358
+ });
359
+ for (const file of event.files || []) {
360
+ const link = file.permalink || file.url_private || "";
361
+ text += `${text ? "\n" : ""}📎 ${file.name || file.title || "file"}${link ? `: ${link}` : ""}`;
362
+ }
363
+ return text;
364
+ }
365
+
366
+ function handleHumanMessage(ctx, channel, event) {
367
+ let imported = false;
368
+ let registered = false;
369
+ for (const project of projectsFor(ctx, channel)) {
370
+ const role = project.settings.members[event.user];
371
+ if (!role) continue;
372
+ registered = true;
373
+ if (recordAt(project, channel, event.ts)) continue;
374
+ const group = project.channelGroups.get(channel);
375
+ let text = humanText(project, event);
376
+ let replyTo = null;
377
+ if (event.thread_ts && event.thread_ts !== event.ts) {
378
+ replyTo = recordAt(project, channel, event.thread_ts);
379
+ if (!replyTo) text = `↳ reply to Slack message ${event.thread_ts}\n${text}`;
380
+ }
381
+ const record = store.writeRecord(project.where, {
382
+ group,
383
+ kind: "message",
384
+ from: role,
385
+ created: tsToIso(event.ts),
386
+ mentions: lenientMentions(project, group, text),
387
+ reply_to: replyTo,
388
+ origin: "slack",
389
+ text,
390
+ }, new Date(Math.round(Number(event.ts) * 1000)));
391
+ writePosted(project.where, record.id, { channel, ts: event.ts, thread_ts: event.thread_ts || null, origin: "slack" });
392
+ rememberTs(project, channel, event.ts, record.id);
393
+ imported = true;
394
+ }
395
+ // Someone no project registered: never relayed, only counted (D16).
396
+ if (!registered && event.user !== ctx.self.user_id) ctx.stats.ignored += 1;
397
+ return imported;
398
+ }
399
+
400
+ function authorOf(project, message) {
401
+ if (message.user && project.settings.members[message.user]) return project.settings.members[message.user];
402
+ return null;
403
+ }
404
+
405
+ function handleChanged(ctx, channel, event) {
406
+ const message = event.message || {};
407
+ if (message.bot_id && message.bot_id === ctx.self.bot_id) return;
408
+ for (const project of projectsFor(ctx, channel)) {
409
+ const id = recordAt(project, channel, message.ts);
410
+ if (!id) continue;
411
+ const record = store.findRecord(project.where, id);
412
+ if (!record) continue;
413
+ const author = message.bot_id ? record.from : authorOf(project, message);
414
+ if (!author || author !== record.from) continue;
415
+ const text = message.bot_id ? unwrapText(project, message.text, record.kind) : humanText(project, message);
416
+ const { displayRecords } = require("./view");
417
+ const current = displayRecords(store.readLog(project.where, record.group)).find((r) => r.id === id);
418
+ if (current && current.text === text) continue;
419
+ store.writeRecord(project.where, { group: record.group, kind: "edit", from: record.from, target: id, origin: "slack", text });
420
+ }
421
+ }
422
+
423
+ function handleDeleted(ctx, channel, event) {
424
+ const previous = event.previous_message || {};
425
+ if (previous.bot_id && previous.bot_id === ctx.self.bot_id) return;
426
+ const ts = event.deleted_ts || previous.ts;
427
+ for (const project of projectsFor(ctx, channel)) {
428
+ const id = recordAt(project, channel, ts);
429
+ if (!id) continue;
430
+ const record = store.findRecord(project.where, id);
431
+ if (!record) continue;
432
+ const already = store.readLog(project.where, record.group).some((r) => r.kind === "retract" && r.target === id);
433
+ if (already) continue;
434
+ store.writeRecord(project.where, { group: record.group, kind: "retract", from: record.from, target: id, origin: "slack", text: "" });
435
+ }
436
+ }
437
+
438
+ function handleReaction(ctx, event) {
439
+ if (event.reaction !== "white_check_mark" || !event.item || event.user === ctx.self.user_id) return;
440
+ const channel = event.item.channel;
441
+ for (const project of projectsFor(ctx, channel)) {
442
+ const role = project.settings.members[event.user];
443
+ if (!role) continue;
444
+ const id = recordAt(project, channel, event.item.ts);
445
+ const record = id ? store.findRecord(project.where, id) : null;
446
+ if (!record || record.kind !== "todo") continue;
447
+ const log = store.readLog(project.where, record.group);
448
+ if (log.some((r) => r.kind === "done" && r.target === id)) continue;
449
+ store.writeRecord(project.where, { group: record.group, kind: "done", from: role, target: id, origin: "slack" });
450
+ }
451
+ }
452
+
453
+ function projectsFor(ctx, channel) {
454
+ return ctx.projects.filter((project) => project.channelGroups.has(channel));
455
+ }
456
+
457
+ async function handleEvent(ctx, event) {
458
+ if (!event) return;
459
+ ctx.stats.last_event = store.isoLocal(new Date());
460
+ if (event.type === "reaction_added") {
461
+ handleReaction(ctx, event);
462
+ return;
463
+ }
464
+ if (event.type !== "message") return;
465
+ const channel = event.channel;
466
+ if (!projectsFor(ctx, channel).length) return;
467
+ switch (event.subtype) {
468
+ case "message_changed":
469
+ handleChanged(ctx, channel, event);
470
+ break;
471
+ case "message_deleted":
472
+ handleDeleted(ctx, channel, event);
473
+ break;
474
+ case undefined:
475
+ case "file_share":
476
+ case "thread_broadcast":
477
+ case "bot_message":
478
+ if (event.bot_id || event.subtype === "bot_message") await handleBotMessage(ctx, channel, event);
479
+ else handleHumanMessage(ctx, channel, event);
480
+ break;
481
+ default:
482
+ break; // channel_join and the like carry nothing for the chat
483
+ }
484
+ for (const project of projectsFor(ctx, channel)) noteSeen(project, channel, event.ts);
485
+ }
486
+
487
+ // --- catch-up -------------------------------------------------------------------
488
+
489
+ function seenFile(project, channel) {
490
+ return path.join(project.where.root, "bridge", "seen", `${channel}.json`);
491
+ }
492
+
493
+ function lastSeen(project, channel) {
494
+ return store.readJsonFile(seenFile(project, channel)).ts || null;
495
+ }
496
+
497
+ function noteSeen(project, channel, ts) {
498
+ if (!ts) return;
499
+ const current = lastSeen(project, channel);
500
+ if (current && Number(current) >= Number(ts)) return;
501
+ store.writeJsonAtomic(project.where, seenFile(project, channel), { ts });
502
+ }
503
+
504
+ // Pages each mapped channel's history (and threads with new replies) from the
505
+ // last ts this machine processed, oldest first, through the same handlers as
506
+ // live events. Internal apps keep the higher history limits (design F2).
507
+ async function catchUp(ctx) {
508
+ const channels = new Set(ctx.projects.flatMap((project) => [...project.channelGroups.keys()]));
509
+ for (const channel of channels) {
510
+ const seen = projectsFor(ctx, channel).map((project) => lastSeen(project, channel));
511
+ const oldest = seen.some((ts) => !ts) ? null : seen.reduce((a, b) => (Number(a) < Number(b) ? a : b));
512
+ const messages = [];
513
+ let cursor = null;
514
+ do {
515
+ const page = await slack.callWithRetry("conversations.history", {
516
+ channel, oldest: oldest || undefined, include_all_metadata: true, limit: 200, cursor: cursor || undefined,
517
+ }, ctx.token);
518
+ messages.push(...(page.messages || []));
519
+ cursor = page.response_metadata && page.response_metadata.next_cursor;
520
+ } while (cursor);
521
+ for (const message of messages.reverse()) {
522
+ await handleEvent(ctx, { type: "message", channel, ...message });
523
+ if (message.reply_count && (!oldest || Number(message.latest_reply || 0) > Number(oldest))) {
524
+ const replies = await slack.callWithRetry("conversations.replies", {
525
+ channel, ts: message.ts, oldest: oldest || undefined, include_all_metadata: true,
526
+ }, ctx.token);
527
+ for (const reply of replies.messages || []) {
528
+ if (reply.ts !== message.ts) await handleEvent(ctx, { type: "message", channel, ...reply });
529
+ }
530
+ }
531
+ }
532
+ }
533
+ }
534
+
535
+ // --- the running process --------------------------------------------------------
536
+
537
+ function statusFile() {
538
+ return path.join(keelHome(), "chat", "bridge", "status.json");
539
+ }
540
+
541
+ function machineName() {
542
+ return (process.env.KEEL_CHAT_MACHINE || os.hostname().split(".")[0] || "this-machine").trim();
543
+ }
544
+
545
+ function writeStatus(ctx) {
546
+ const status = {
547
+ pid: process.pid,
548
+ machine: machineName(),
549
+ connected: Boolean(ctx.connected),
550
+ projects: ctx.projects.map((project) => project.where.worktree),
551
+ last_event: ctx.stats.last_event,
552
+ ignored: ctx.stats.ignored,
553
+ unposted: unpostedCount(ctx.projects),
554
+ updated: store.isoLocal(new Date()),
555
+ };
556
+ const file = statusFile();
557
+ try {
558
+ fs.mkdirSync(path.dirname(file), { recursive: true });
559
+ const temp = `${file}.${process.pid}.tmp`;
560
+ fs.writeFileSync(temp, `${JSON.stringify(status, null, 2)}\n`);
561
+ fs.renameSync(temp, file);
562
+ } catch {
563
+ // Status is for people; failing to write it must not stop the relay.
564
+ }
565
+ }
566
+
567
+ function readStatus() {
568
+ let status = {};
569
+ try {
570
+ status = JSON.parse(fs.readFileSync(statusFile(), "utf8"));
571
+ } catch {
572
+ return { running: false };
573
+ }
574
+ let running = false;
575
+ try {
576
+ process.kill(status.pid, 0);
577
+ running = true;
578
+ } catch {
579
+ running = false;
580
+ }
581
+ return { ...status, running, connected: running && Boolean(status.connected) };
582
+ }
583
+
584
+ function fullStatus() {
585
+ const status = readStatus();
586
+ const until = lifecycle.pausedUntil();
587
+ return {
588
+ installed: lifecycle.installed(),
589
+ running: false,
590
+ connected: false,
591
+ projects: [],
592
+ last_event: null,
593
+ ignored: 0,
594
+ unposted: 0,
595
+ ...status,
596
+ paused: Boolean(until),
597
+ paused_until: until ? new Date(until).toISOString() : null,
598
+ };
599
+ }
600
+
601
+ function prepareProjects() {
602
+ const projects = servedProjects();
603
+ for (const project of projects) {
604
+ project.channelGroups = new Map();
605
+ for (const [group, channel] of Object.entries(project.settings.channels)) {
606
+ if (!project.channelGroups.has(channel)) project.channelGroups.set(channel, group);
607
+ }
608
+ buildTsIndex(project);
609
+ }
610
+ return projects;
611
+ }
612
+
613
+ async function createContext(log, { needApp }) {
614
+ requireWebSocket();
615
+ const { bot, app } = lifecycle.tokens();
616
+ if (needApp && !app) throw lifecycle.missingTokens("app-level token");
617
+ if (!bot) throw lifecycle.missingTokens("bot token");
618
+ const ctx = {
619
+ log,
620
+ token: bot,
621
+ appToken: app,
622
+ projects: prepareProjects(),
623
+ stats: { ignored: 0, last_event: null },
624
+ connected: false,
625
+ stopping: false,
626
+ self: {},
627
+ };
628
+ const auth = await slack.callWithRetry("auth.test", {}, bot);
629
+ ctx.self = { bot_id: auth.bot_id || null, user_id: auth.user_id || null };
630
+ return ctx;
631
+ }
632
+
633
+ async function runOnce(log) {
634
+ const ctx = await createContext(log, { needApp: false });
635
+ const posted = await flushOutbound(ctx);
636
+ writeStatus(ctx);
637
+ log(`Bridge pass done: ${ctx.projects.length} project${ctx.projects.length === 1 ? "" : "s"} served, ${posted} record${posted === 1 ? "" : "s"} sent.`);
638
+ return 0;
639
+ }
640
+
641
+ // Events are handled one at a time, in arrival order, so a reply never lands
642
+ // before the message it answers.
643
+ function socketSession(ctx) {
644
+ return new Promise((resolve) => {
645
+ let queue = Promise.resolve();
646
+ slack.callWithRetry("apps.connections.open", {}, ctx.appToken).then((opened) => {
647
+ if (ctx.stopping) return resolve();
648
+ const socket = new WebSocket(opened.url);
649
+ ctx.socket = socket;
650
+ socket.onmessage = (message) => {
651
+ let data = null;
652
+ try {
653
+ data = JSON.parse(typeof message.data === "string" ? message.data : String(message.data));
654
+ } catch {
655
+ return;
656
+ }
657
+ if (data.envelope_id) socket.send(JSON.stringify({ envelope_id: data.envelope_id }));
658
+ if (data.type === "hello") {
659
+ ctx.connected = true;
660
+ writeStatus(ctx);
661
+ queue = queue.then(() => catchUp(ctx)).then(() => writeStatus(ctx)).catch((error) => ctx.log(`catch-up failed: ${error.message}`));
662
+ return;
663
+ }
664
+ if (data.type === "disconnect") {
665
+ socket.close();
666
+ return;
667
+ }
668
+ if (data.type === "events_api" && data.payload) {
669
+ queue = queue
670
+ .then(() => handleEvent(ctx, data.payload.event))
671
+ .then(() => writeStatus(ctx))
672
+ .catch((error) => ctx.log(`event failed: ${error.message}`));
673
+ }
674
+ };
675
+ socket.onclose = () => {
676
+ ctx.connected = false;
677
+ ctx.socket = null;
678
+ writeStatus(ctx);
679
+ resolve();
680
+ };
681
+ socket.onerror = () => {};
682
+ }, (error) => {
683
+ ctx.log(`could not open a Socket Mode connection: ${error.message}`);
684
+ resolve();
685
+ });
686
+ });
687
+ }
688
+
689
+ function packageVersion() {
690
+ try {
691
+ return JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "..", "..", "package.json"), "utf8")).version || null;
692
+ } catch {
693
+ return null;
694
+ }
695
+ }
696
+
697
+ // One line to every mapped channel, so the people in it know whether this
698
+ // machine's sessions can hear them (D18).
699
+ async function announce(ctx, text) {
700
+ const channels = new Set(ctx.projects.flatMap((project) => [...project.channelGroups.keys()]));
701
+ for (const channel of channels) {
702
+ try {
703
+ await slack.call("chat.postMessage", { channel, text, username: "keel bridge", unfurl_links: false }, ctx.token);
704
+ } catch (error) {
705
+ ctx.log(`could not announce in ${channel}: ${error.message}`);
706
+ }
707
+ }
708
+ }
709
+
710
+ const RESTART_EXIT = 75;
711
+
712
+ async function run(log) {
713
+ const ctx = await createContext(log, { needApp: true });
714
+ const machine = machineName();
715
+ const version = packageVersion();
716
+ let exitCode = 0;
717
+ let flushing = false;
718
+ const flush = async () => {
719
+ if (flushing || ctx.stopping || lifecycle.pausedUntil()) return;
720
+ flushing = true;
721
+ try {
722
+ await flushOutbound(ctx);
723
+ } catch (error) {
724
+ log(`sending failed, will retry: ${error.message}`);
725
+ } finally {
726
+ flushing = false;
727
+ }
728
+ };
729
+ let stopped = null;
730
+ const stop = (reason) => {
731
+ if (stopped) return stopped;
732
+ ctx.stopping = true;
733
+ clearInterval(timer);
734
+ clearInterval(archiveTimer);
735
+ stopped = (async () => {
736
+ if (reason) await Promise.race([announce(ctx, `:red_circle: ${machine} bridge stopped${reason === "signal" ? "" : ` (${reason})`}; this machine's sessions will catch up when it restarts.`), slack.sleep(5000)]);
737
+ if (ctx.socket) ctx.socket.close();
738
+ })();
739
+ return stopped;
740
+ };
741
+ // Every ten minutes while connected, each project with archiving on is
742
+ // synced to its keel-chat branch (D19).
743
+ const archiveTimer = setInterval(() => {
744
+ if (!ctx.connected || ctx.stopping) return;
745
+ const archive = require("./archive");
746
+ for (const project of ctx.projects) {
747
+ if (!archive.archiveSettings(project.where.worktree).automatic) continue;
748
+ try {
749
+ const result = archive.sync(project.where);
750
+ if (result.refused) log(`${project.where.project}: ${result.refused}`);
751
+ } catch (error) {
752
+ log(`${project.where.project}: archive sync failed: ${error.message}`);
753
+ }
754
+ }
755
+ }, 10 * 60 * 1000);
756
+ archiveTimer.unref();
757
+ // Each second: honor a pause, notice a Keel upgrade, and send what is new.
758
+ const timer = setInterval(() => {
759
+ const current = packageVersion();
760
+ if (version && current && current !== version) {
761
+ log(`Keel changed from ${version} to ${current}; exiting so launchd restarts the bridge on the new version.`);
762
+ exitCode = RESTART_EXIT;
763
+ stop(`restarting for Keel ${current}`);
764
+ return;
765
+ }
766
+ if (lifecycle.pausedUntil()) {
767
+ if (ctx.socket) ctx.socket.close();
768
+ return;
769
+ }
770
+ flush();
771
+ }, 1000);
772
+ process.once("SIGTERM", () => stop("signal"));
773
+ process.once("SIGINT", () => stop("signal"));
774
+ await announce(ctx, `:large_green_circle: ${machine} bridge online, relaying ${ctx.projects.length} project${ctx.projects.length === 1 ? "" : "s"}.`);
775
+ await flush();
776
+ let backoff = 1000;
777
+ while (!ctx.stopping) {
778
+ if (lifecycle.pausedUntil()) {
779
+ await slack.sleep(500);
780
+ continue;
781
+ }
782
+ const opened = Date.now();
783
+ await socketSession(ctx);
784
+ if (ctx.stopping || lifecycle.pausedUntil()) continue;
785
+ backoff = Date.now() - opened > 30000 ? 1000 : Math.min(backoff * 2, 30000);
786
+ await slack.sleep(backoff);
787
+ }
788
+ if (stopped) await stopped;
789
+ ctx.connected = false;
790
+ writeStatus(ctx);
791
+ return exitCode;
792
+ }
793
+
794
+ module.exports = {
795
+ METADATA_TYPE,
796
+ addProject,
797
+ keelHome,
798
+ readPosted,
799
+ readRegistry,
800
+ fullStatus,
801
+ readStatus,
802
+ removeProject,
803
+ requireWebSocket,
804
+ run,
805
+ runOnce,
806
+ servedProjects,
807
+ writePosted,
808
+ };