@kana-ai/edgar-ext-slack 0.1.2 → 0.1.3

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.
@@ -1,9 +1,28 @@
1
1
  import { attempt, done, ok, } from "@kana-ai/edgar-sdk";
2
2
  import { slack } from "#api/client";
3
+ import { sharedFiles } from "#inbound/files";
3
4
  import { boundCard, listed, mark, newestMarked, post, runOf, status, threadStatus, waitingRelays, } from "#outbound/messages";
4
5
  import { cutEscaped, escape } from "#outbound/tools";
5
6
  import { CONTEXT, REPLY } from "#outbound/words";
6
- import { answer, answerValue, channelInfo, messages, permalink, pressed, said, stopped, userInfo, } from "#schemas/slack";
7
+ import { answer, answerValue, channelInfo, home, messages, permalink, pressed, said, stopped, userInfo, } from "#schemas/slack";
8
+ /** The metadata fields that tie a message EDGAR writes to the delivery it answers. */
9
+ function keyed(delivery) {
10
+ return delivery === undefined ? {} : { delivery: delivery.id };
11
+ }
12
+ /** Whether routing `delivery` again finds what it wrote the first time among `all`: a message that carries its id. Such a delivery is not routed again, so nothing is said or put on a card twice. */
13
+ function routedBefore(delivery, all) {
14
+ return (delivery?.again === true &&
15
+ all.some((m) => m.metadata?.event_payload["delivery"] === delivery.id));
16
+ }
17
+ /** Whether the thread at `ts` holds a message that carries `delivery`, when it is routed again. A thread that does not read counts as not routed, so the event is routed rather than lost. */
18
+ async function threadRouted(ctx, channel, ts, delivery) {
19
+ if (delivery?.again !== true)
20
+ return false;
21
+ const all = await listed(ctx, channel, ts);
22
+ if (!all.ok)
23
+ ctx.log(`conversations.replies: ${all.error.message}`);
24
+ return all.ok && routedBefore(delivery, all.value);
25
+ }
7
26
  const TITLE_LENGTH = 120;
8
27
  /** The most characters of one Slack message quoted on a card. */
9
28
  const QUOTE_CHARS = 1000;
@@ -23,9 +42,16 @@ export function clean(text) {
23
42
  .replaceAll("&", "&")
24
43
  .trim();
25
44
  }
26
- /** What a person who is not an operator is told; with no operator set at all, how to become one, since a new project meets its first button that way. */
27
- function notOperator(settings, user, text) {
28
- return Object.keys(settings.operators).length === 0 ? REPLY.noOperators(user) : text;
45
+ /** Who a move of `user` is made by, or what they are told when they may not make it. With the deprecated `operators` table, their name in it, as before. Without it, their Slack user id: EDGAR signs it with their name in `[people]` and decides by `[roles] operator`, so the extension keeps no list of its own. `refused` is what a person who may not is told. */
46
+ async function moverOf(ctx, settings, user, refused) {
47
+ if (Object.keys(settings.operators).length > 0) {
48
+ const name = settings.operators[user];
49
+ return name === undefined ? { told: refused } : { by: name };
50
+ }
51
+ const allowed = await ctx.moves.allowed(user);
52
+ if (!allowed.ok)
53
+ return { told: REPLY.notChecked(allowed.error.message) };
54
+ return allowed.value.applied ? { by: user } : { told: `${refused} ${REPLY.toBeLetIn(user)}` };
29
55
  }
30
56
  /** Tells one person, and only them, why nothing happened. The text can hold a failure's words, so its markup is made plain. */
31
57
  async function tell(ctx, where, user, text) {
@@ -45,17 +71,17 @@ function refusal(moved) {
45
71
  return moved.error.message;
46
72
  return moved.value.applied ? undefined : (moved.value.message ?? "the engine refused the move");
47
73
  }
48
- /** Whether `[extensions.slack] allow` lets this person open a card: no bot, a guest only when `guests`, and an email in `domains` when it lists any. */
49
- async function allowed(ctx, settings, user) {
50
- const rule = settings.allow;
51
- if (rule === undefined)
52
- return true;
53
- const found = await slack(ctx, "users.info", { user }, userInfo);
54
- if (!found.ok) {
55
- ctx.log(`users.info ${user}: ${found.error.message}`);
56
- return false;
57
- }
58
- const person = found.value.user;
74
+ /** Whether `person` is on the team: a member of the app's workspace, or of its organization on Enterprise Grid. A bot, a guest and a person of another workspace, such as in a channel shared with it, are outside. */
75
+ export function trustOf(person, home) {
76
+ const guest = person.is_restricted === true || person.is_ultra_restricted === true;
77
+ if (person.is_bot === true || guest || person.is_stranger === true)
78
+ return "outside";
79
+ const workspace = home.team !== undefined && person.team_id === home.team;
80
+ const organization = home.enterprise !== undefined && person.enterprise_user?.enterprise_id === home.enterprise;
81
+ return workspace || organization ? "team" : "outside";
82
+ }
83
+ /** Whether `[extensions.slack] allow` lets `person` open a card: no bot, a guest only when `guests`, and an email in `domains` when it lists any. */
84
+ function allows(rule, person) {
59
85
  if (person.is_bot === true)
60
86
  return false;
61
87
  if (!rule.guests && (person.is_restricted === true || person.is_ultra_restricted === true)) {
@@ -64,8 +90,19 @@ async function allowed(ctx, settings, user) {
64
90
  const domain = person.profile?.email?.split("@").at(-1);
65
91
  return rule.domains.length === 0 || (domain !== undefined && rule.domains.includes(domain));
66
92
  }
93
+ /** Whether `[extensions.slack] allow` lets the writer of `message` in, and their trust. A person Slack does not answer for is outside, and let in only when `allow` is not set. */
94
+ async function writer(ctx, settings, message) {
95
+ const found = await slack(ctx, "users.info", { user: message.user }, userInfo);
96
+ if (!found.ok) {
97
+ ctx.log(`users.info ${message.user}: ${found.error.message}`);
98
+ return { allowed: settings.allow === undefined, trust: "outside" };
99
+ }
100
+ const person = found.value.user;
101
+ const allowed = settings.allow === undefined || allows(settings.allow, person);
102
+ return { allowed, trust: trustOf(person, message.home) };
103
+ }
67
104
  /** One message of Slack as a line of a card: who wrote it, EDGAR for EDGAR's own, and its words on one line. */
68
- function quote(message) {
105
+ export function quote(message) {
69
106
  const who = message.metadata?.event_type.startsWith("edgar_")
70
107
  ? CONTEXT.edgar
71
108
  : `<@${message.user ?? message.bot_id ?? "someone"}>`;
@@ -76,8 +113,8 @@ function quote(message) {
76
113
  function before(all, ts, count) {
77
114
  return count === 0 ? [] : all.filter((m) => m.ts !== ts && m.text !== undefined).slice(-count);
78
115
  }
79
- /** The card a message opens, with its permalink and, in a thread, the thread's newest messages before it. */
80
- async function cardOf(ctx, settings, message, thread, all) {
116
+ /** The card a message opens, with its permalink and, in a thread, the thread's newest messages before it. The block says when its writer is outside the team, since the tracker sees EDGAR's account as the card's writer. */
117
+ async function cardOf(ctx, settings, message, thread, all, trust) {
81
118
  const text = clean(message.text);
82
119
  const title = (text.split("\n")[0] ?? "").slice(0, TITLE_LENGTH) || "A message from Slack";
83
120
  const link = await slack(ctx, "chat.getPermalink", { channel: message.channel, message_ts: message.ts }, permalink);
@@ -94,7 +131,8 @@ async function cardOf(ctx, settings, message, thread, all) {
94
131
  channel: message.channel,
95
132
  thread: thread ?? message.ts,
96
133
  };
97
- return { title, description, column: settings.card_column, block: { kind: "request", origin } };
134
+ const block = { kind: "request", origin, ...(trust === "outside" ? { trust } : {}) };
135
+ return { title, description, column: settings.card_column, block };
98
136
  }
99
137
  /** Opens `card` for a message, says so in its thread, then shows the session as processing. */
100
138
  async function open(ctx, message, card) {
@@ -112,15 +150,17 @@ async function open(ctx, message, card) {
112
150
  await tell(ctx, where, message.user, REPLY.notOpened(why));
113
151
  return;
114
152
  }
115
- const noted = await post(ctx, message.channel, root, REPLY.opened(made.output.id));
153
+ const keys = keyed(message.delivery);
154
+ const extra = Object.keys(keys).length === 0 ? {} : { metadata: mark("edgar_post", keys) };
155
+ const noted = await post(ctx, message.channel, root, REPLY.opened(made.output.id), extra);
116
156
  if (!noted.ok)
117
157
  ctx.log(`chat.postMessage: ${noted.error.message}`);
118
158
  if (origin !== undefined)
119
159
  await status(ctx, origin, "processing", card.title);
120
160
  }
121
- /** A message with no card: the workflow `chat` answers a question in its thread, with the thread's newest messages before it, and opens the message's card when it asks for work. A chat that the engine does not start, such as in a project with no `chat` workflow, opens the card at once, as a message did before chats. */
122
- async function chat(ctx, settings, message, thread, all) {
123
- const card = await cardOf(ctx, settings, message, thread, all);
161
+ /** A message with no card: the workflow `chat` answers a question in its thread, with the thread's newest messages before it and the files the message shares, and opens the message's card when it asks for work. A file of a kind it does not read gets one short reply to the person. A chat that the engine does not start, such as in a project with no `chat` workflow, opens the card at once, as a message did before chats. */
162
+ async function chat(ctx, settings, message, thread, all, trust) {
163
+ const card = await cardOf(ctx, settings, message, thread, all, trust);
124
164
  const text = clean(message.text);
125
165
  const origin = card.block.origin;
126
166
  if (text === "" || origin === undefined) {
@@ -131,7 +171,10 @@ async function chat(ctx, settings, message, thread, all) {
131
171
  const words = earlier.length === 0
132
172
  ? text
133
173
  : `${text}\n\n${[CONTEXT.earlier, ...earlier.map(quote)].join("\n")}`;
134
- const why = refusal(await ctx.runs.chat(words, message.user, origin, card));
174
+ const shared = sharedFiles(message.files ?? []);
175
+ if (shared.refused.length > 0)
176
+ await tell(ctx, origin, message.user, REPLY.filesNotRead(shared.refused));
177
+ const why = refusal(await ctx.runs.chat(words, message.user, origin, card, shared.files));
135
178
  if (why === undefined) {
136
179
  await threadStatus(ctx, origin.channel, origin.thread, REPLY.readingMessage);
137
180
  return;
@@ -140,8 +183,8 @@ async function chat(ctx, settings, message, thread, all) {
140
183
  await open(ctx, message, card);
141
184
  }
142
185
  /** Marks a question answered, or closed when the engine no longer waits on it, so the next reply goes to a question that still waits. */
143
- async function settle(ctx, channel, ts, kind, key, text) {
144
- const args = { channel, ts, text, blocks: [], metadata: mark(kind, { key }) };
186
+ async function settle(ctx, channel, ts, kind, key, text, delivery) {
187
+ const args = { channel, ts, text, blocks: [], metadata: mark(kind, { key, ...keyed(delivery) }) };
145
188
  const updated = await slack(ctx, "chat.update", args, answer);
146
189
  if (!updated.ok)
147
190
  ctx.log(`chat.update: ${updated.error.message}`);
@@ -149,22 +192,23 @@ async function settle(ctx, channel, ts, kind, key, text) {
149
192
  /** A reply to a question of `ask` completes its waiting key, when an operator wrote it. The engine refuses a key it no longer waits on, after a timeout or the run's end, and the question is closed, so the thread's next reply or mention goes past it. */
150
193
  async function reply(ctx, settings, message, question, key) {
151
194
  const where = { channel: message.channel, thread: message.thread_ts };
152
- const by = settings.operators[message.user];
153
- if (by === undefined) {
154
- await tell(ctx, where, message.user, notOperator(settings, message.user, REPLY.operatorsAnswer));
195
+ const mover = await moverOf(ctx, settings, message.user, REPLY.operatorsAnswer);
196
+ if ("told" in mover) {
197
+ await tell(ctx, where, message.user, mover.told);
155
198
  return { kind: "handled" };
156
199
  }
157
200
  const text = clean(message.text);
158
- const moved = await ctx.moves.complete(key, done({ answer: text, by }), by);
201
+ const answered = done({ answer: text, by: await nameOf(ctx, settings, message.user) });
202
+ const moved = await ctx.moves.complete(key, answered, mover.by);
159
203
  if (!moved.ok)
160
204
  return { kind: "failed", why: moved.error.message };
161
205
  const asked = question.text ?? "";
162
206
  if (!moved.value.applied) {
163
- await settle(ctx, message.channel, question.ts, "edgar_closed", key, `${asked}\n\n${REPLY.closed}`);
207
+ await settle(ctx, message.channel, question.ts, "edgar_closed", key, `${asked}\n\n${REPLY.closed}`, message.delivery);
164
208
  return { kind: "closed", why: moved.value.message ?? "the engine refused the answer" };
165
209
  }
166
210
  const thanks = `${asked}\n\n${REPLY.answered(message.user)}`;
167
- await settle(ctx, message.channel, question.ts, "edgar_answered", key, thanks);
211
+ await settle(ctx, message.channel, question.ts, "edgar_answered", key, thanks, message.delivery);
168
212
  return { kind: "handled" };
169
213
  }
170
214
  /** The newest question of `ask` that waits among `all`. */
@@ -183,7 +227,7 @@ async function nameOf(ctx, settings, user) {
183
227
  return name?.replaceAll(/\s+/g, " ").trim() || user;
184
228
  }
185
229
  /** The Slack threads that `text` links, the first `LINKS` of them. A permalink's `p` part is its message's `ts` with no dot, and its `thread_ts` names the thread of a reply. */
186
- function linked(text) {
230
+ export function linked(text) {
187
231
  const found = text.matchAll(/https:\/\/[a-z0-9-]+\.slack\.com\/archives\/([A-Z0-9]+)\/p(\d{10})(\d{6})(?:\?[\w.=&%-]+)?/g);
188
232
  return [...found].slice(0, LINKS).map(([url, channel = "", seconds, part]) => ({
189
233
  channel,
@@ -192,7 +236,7 @@ function linked(text) {
192
236
  }));
193
237
  }
194
238
  /** The newest `THREAD_MESSAGES` messages of a thread, oldest first, read at most `THREAD_PAGES` pages of `conversations.replies` deep. */
195
- async function threadAt(ctx, channel, ts) {
239
+ export async function threadAt(ctx, channel, ts) {
196
240
  const all = [];
197
241
  let cursor;
198
242
  for (let page = 0; page < THREAD_PAGES; page += 1) {
@@ -215,7 +259,7 @@ function unread(failure) {
215
259
  : REPLY.threadScope(scope);
216
260
  }
217
261
  /** Whether a linked thread may go on a card, which everyone who reads the card sees: only one in `own` channel or in a public channel. A failed `conversations.info` counts as not public. */
218
- async function shareable(ctx, channel, own) {
262
+ export async function shareable(ctx, channel, own) {
219
263
  if (channel === own)
220
264
  return true;
221
265
  const info = await slack(ctx, "conversations.info", { channel }, channelInfo);
@@ -261,7 +305,8 @@ async function relay(ctx, settings, message, thread, targets, all, bind = false)
261
305
  await tell(ctx, where, message.user, REPLY.fileOnly);
262
306
  return { kind: "told" };
263
307
  }
264
- if (!(await allowed(ctx, settings, message.user))) {
308
+ const who = await writer(ctx, settings, message);
309
+ if (!who.allowed) {
265
310
  await tell(ctx, where, message.user, REPLY.notAllowed);
266
311
  return { kind: "told" };
267
312
  }
@@ -272,7 +317,7 @@ async function relay(ctx, settings, message, thread, targets, all, bind = false)
272
317
  let why = "no card to put it on";
273
318
  let taken;
274
319
  for (const target of targets) {
275
- const refused = refusal(await ctx.cards.reply(target, words, by, origin));
320
+ const refused = refusal(await ctx.cards.reply(target, words, by, who.trust, origin));
276
321
  if (refused === undefined) {
277
322
  taken = target;
278
323
  break;
@@ -294,6 +339,7 @@ async function relay(ctx, settings, message, thread, targets, all, bind = false)
294
339
  ? REPLY.relayedNoFile
295
340
  : REPLY.relayed;
296
341
  const metadata = mark("edgar_relayed", {
342
+ ...keyed(message.delivery),
297
343
  user: message.user,
298
344
  ...(card === undefined ? {} : { card }),
299
345
  ...(busy ? { busy } : {}),
@@ -304,7 +350,7 @@ async function relay(ctx, settings, message, thread, targets, all, bind = false)
304
350
  await threadStatus(ctx, message.channel, thread, REPLY.reading);
305
351
  return { kind: "relayed" };
306
352
  }
307
- /** The keys of the cards that `text` names, such as `EDG-2422` alone or in a tracker link, the first `KEYS` of them. A word of the same shape that is no card, such as `UTF-8`, is refused by the tracker and passed over. */
353
+ /** The keys of the cards that `text` names, such as `ENG-42` alone or in a tracker link, the first `KEYS` of them. A word of the same shape that is no card, such as `UTF-8`, is refused by the tracker and passed over. */
308
354
  function cardsNamed(text) {
309
355
  const keys = text.match(/\b[A-Z][A-Z0-9]{1,9}-[1-9][0-9]{0,6}\b/g) ?? [];
310
356
  return [...new Set(keys)].slice(0, KEYS);
@@ -330,6 +376,8 @@ async function heard(ctx, settings, message) {
330
376
  return;
331
377
  }
332
378
  talk = all.value;
379
+ if (routedBefore(message.delivery, all.value))
380
+ return;
333
381
  const waiting = questionIn(all.value);
334
382
  if (waiting !== undefined) {
335
383
  if (message.type !== "message")
@@ -357,8 +405,9 @@ async function heard(ctx, settings, message) {
357
405
  if ((run !== undefined || card !== undefined || chatted) && (mention || !toSomeone)) {
358
406
  const target = run !== undefined ? { run } : card !== undefined ? { card } : undefined;
359
407
  if (target === undefined) {
360
- if (await allowed(ctx, settings, message.user))
361
- await chat(ctx, settings, message, thread, all.value);
408
+ const who = await writer(ctx, settings, message);
409
+ if (who.allowed)
410
+ await chat(ctx, settings, message, thread, all.value, who.trust);
362
411
  return;
363
412
  }
364
413
  const relayed = await relay(ctx, settings, message, thread, [target], all.value);
@@ -369,12 +418,17 @@ async function heard(ctx, settings, message) {
369
418
  if (!mention && keys.length === 0)
370
419
  return;
371
420
  }
421
+ else if (await threadRouted(ctx, message.channel, message.ts, message.delivery)) {
422
+ return;
423
+ }
372
424
  else if (message.type === "message" && message.channel_type === "im") {
373
425
  const all = await listed(ctx, message.channel, undefined);
374
426
  if (!all.ok) {
375
427
  ctx.log(`conversations.history: ${all.error.message}`);
376
428
  return;
377
429
  }
430
+ if (routedBefore(message.delivery, all.value))
431
+ return;
378
432
  const waiting = questionIn(all.value);
379
433
  if (waiting !== undefined) {
380
434
  const answered = await reply(ctx, settings, message, waiting.question, waiting.key);
@@ -396,36 +450,43 @@ async function heard(ctx, settings, message) {
396
450
  return;
397
451
  ctx.log(`no card of ${keys.join(", ")} took the message (${bound.why}), so it is a chat`);
398
452
  }
399
- if (await allowed(ctx, settings, message.user))
400
- await chat(ctx, settings, message, thread, talk);
453
+ const who = await writer(ctx, settings, message);
454
+ if (who.allowed)
455
+ await chat(ctx, settings, message, thread, talk, who.trust);
401
456
  }
402
457
  /** The stop button cancels the runs of the thread's card, then the session goes back to active. */
403
458
  async function stop(ctx, settings, event) {
404
459
  const where = { channel: event.channel, thread: event.thread_ts };
405
460
  const origin = { extension: "slack", channel: event.channel, thread: event.thread_ts };
406
- const by = settings.operators[event.user];
407
- if (by === undefined) {
408
- await tell(ctx, where, event.user, notOperator(settings, event.user, REPLY.operatorsStop));
461
+ const mover = await moverOf(ctx, settings, event.user, REPLY.operatorsStop);
462
+ if ("told" in mover) {
463
+ await tell(ctx, where, event.user, mover.told);
409
464
  return;
410
465
  }
411
- const why = refusal(await ctx.runs.cancel(origin, by, "stopped in Slack"));
466
+ const why = refusal(await ctx.runs.cancel(origin, mover.by, "stopped in Slack"));
412
467
  if (why !== undefined)
413
468
  await tell(ctx, where, event.user, REPLY.notStopped(why));
414
469
  await status(ctx, origin, "active");
415
470
  }
416
471
  /** A press on Approve, Deny or an answer button, by an operator. */
417
- async function press(ctx, settings, payload) {
472
+ async function press(ctx, settings, payload, delivery) {
418
473
  const channel = payload.channel?.id;
419
474
  const ts = payload.message?.ts;
475
+ const thread = payload.message?.thread_ts ?? ts;
476
+ if (channel !== undefined &&
477
+ thread !== undefined &&
478
+ (await threadRouted(ctx, channel, thread, delivery)))
479
+ return;
420
480
  const where = { channel: channel ?? payload.user.id, thread: payload.message?.thread_ts ?? ts };
421
481
  const [action] = payload.actions;
422
- const by = settings.operators[payload.user.id];
423
482
  if (action === undefined || action.value === undefined)
424
483
  return;
425
- if (by === undefined) {
426
- await tell(ctx, where, payload.user.id, notOperator(settings, payload.user.id, REPLY.operatorsChoose));
484
+ const mover = await moverOf(ctx, settings, payload.user.id, REPLY.operatorsChoose);
485
+ if ("told" in mover) {
486
+ await tell(ctx, where, payload.user.id, mover.told);
427
487
  return;
428
488
  }
489
+ const { by } = mover;
429
490
  let moved;
430
491
  let said = "";
431
492
  let answered;
@@ -443,7 +504,8 @@ async function press(ctx, settings, payload) {
443
504
  if (!parsed.ok || parsed.value?.success !== true)
444
505
  return;
445
506
  const { key, answer: chosen } = parsed.value.data;
446
- moved = await ctx.moves.complete(key, done({ answer: chosen, by }), by);
507
+ const named = await nameOf(ctx, settings, payload.user.id);
508
+ moved = await ctx.moves.complete(key, done({ answer: chosen, by: named }), by);
447
509
  said = REPLY.chose(escape(chosen));
448
510
  answered = key;
449
511
  }
@@ -452,24 +514,26 @@ async function press(ctx, settings, payload) {
452
514
  const why = refusal(moved);
453
515
  if (why !== undefined) {
454
516
  if (answered !== undefined && moved.ok && channel !== undefined && ts !== undefined)
455
- await settle(ctx, channel, ts, "edgar_closed", answered, REPLY.closed);
517
+ await settle(ctx, channel, ts, "edgar_closed", answered, REPLY.closed, delivery);
456
518
  await tell(ctx, where, payload.user.id, REPLY.notRecorded(why));
457
519
  return;
458
520
  }
459
521
  if (channel === undefined || ts === undefined)
460
522
  return;
461
523
  const text = `<@${payload.user.id}> ${said}`;
462
- const metadata = answered === undefined ? {} : { metadata: mark("edgar_answered", { key: answered }) };
524
+ const metadata = answered === undefined
525
+ ? {}
526
+ : { metadata: mark("edgar_answered", { key: answered, ...keyed(delivery) }) };
463
527
  const updated = await slack(ctx, "chat.update", { channel, ts, text, blocks: [], ...metadata }, answer);
464
528
  if (!updated.ok)
465
529
  ctx.log(`chat.update: ${updated.error.message}`);
466
530
  }
467
- /** Routes one Socket Mode envelope's payload. Each failure is told to the person or logged, so one bad event never stops the service. */
468
- export async function route(ctx, settings, type, payload) {
531
+ /** Routes one Socket Mode envelope's payload, of the inbox `delivery` when it came through the inbox. Each failure is told to the person or logged, so one bad event never stops the service. An event routed again finds what its first routing wrote by the delivery id, and is then not routed again: a stop between routing it and marking it handled does not answer a person twice. */
532
+ export async function route(ctx, settings, type, payload, delivery) {
469
533
  if (type === "interactive") {
470
534
  const parsed = pressed.safeParse(payload);
471
535
  if (parsed.success)
472
- await press(ctx, settings, parsed.data);
536
+ await press(ctx, settings, parsed.data, delivery);
473
537
  return;
474
538
  }
475
539
  if (type !== "events_api" || typeof payload !== "object" || payload === null)
@@ -481,6 +545,12 @@ export async function route(ctx, settings, type, payload) {
481
545
  return;
482
546
  }
483
547
  const message = said.safeParse(event);
484
- if (message.success)
485
- await heard(ctx, settings, message.data);
548
+ if (!message.success)
549
+ return;
550
+ const envelope = home.safeParse(payload);
551
+ const where = {
552
+ team: envelope.data?.team_id,
553
+ enterprise: envelope.data?.enterprise_id ?? undefined,
554
+ };
555
+ await heard(ctx, settings, { ...message.data, home: where, delivery });
486
556
  }
@@ -11,5 +11,5 @@ export interface Connection {
11
11
  export type Connect = (url: string) => Connection;
12
12
  /** A connection over the global `WebSocket`, which the runtime's network policy has replaced with one that keeps to the extension's hosts. */
13
13
  export declare const webSocket: Connect;
14
- /** The Socket Mode service: it opens a connection with the app token, serves it, and opens the next one when Slack closes it, until `ctx.signal` aborts. A connection that ends within `SHORT_SESSION_MS` is logged with its close code, and the next waits twice as long as the last, up to a minute. A refused app token ends it as a permanent failure. With `inbound = "events"` it only waits, since Slack posts to the engine instead. */
14
+ /** The Socket Mode service: it opens a connection with the app token, serves it, and opens the next one when Slack closes it, until `ctx.signal` aborts. A connection that ends within `SHORT_SESSION_MS` is logged with its close code, and the next waits twice as long as the last, up to a minute. It first runs `checkSetup`: a refused bot token ends it as a permanent failure, and each warning goes to the log. A refused app token ends it as a permanent failure too. With `inbound = "events"` it only waits, since Slack posts to the engine instead. With `inbound = "socket"` it routes what the inbox still holds before it opens the first connection. */
15
15
  export declare function listen(ctx: ServiceCtx, connect: Connect): Promise<Outcome>;
@@ -1,9 +1,10 @@
1
1
  import { setTimeout as sleep } from "node:timers/promises";
2
2
  import { attempt, attemptAsync, done } from "@kana-ai/edgar-sdk";
3
3
  import { APP, call } from "#api/client";
4
+ import { checkSetup } from "#api/setup";
4
5
  import { route } from "#inbound/route";
5
6
  import { settingsOf } from "#schemas/config";
6
- import { connection, envelope } from "#schemas/slack";
7
+ import { connection, delivered, envelope } from "#schemas/slack";
7
8
  const FIRST_PAUSE_MS = 1_000;
8
9
  const LONGEST_PAUSE_MS = 60_000;
9
10
  /** A connection that ends sooner than this after it opened did not work, such as one the network policy refused, so the next waits longer. */
@@ -60,23 +61,76 @@ export const webSocket = (url) => {
60
61
  code: () => code,
61
62
  };
62
63
  };
63
- /** Reads one connection until Slack asks to reconnect, the socket closes or the service stops. Each envelope is acknowledged before it is routed, inside Slack's 3 s. */
64
+ /** The envelope in `text`, or `undefined` when it is not one. */
65
+ function envelopeOf(text) {
66
+ const read = attempt(() => JSON.parse(text), () => undefined);
67
+ const parsed = envelope.safeParse(read.ok ? read.value : undefined);
68
+ return parsed.success ? parsed.data : undefined;
69
+ }
70
+ /** The inbox key of an envelope, Slack's `event_id` when it has one so a redelivery keeps it, and the envelope as stored, without the payload's verification token. */
71
+ function keep(type, envelope_id, payload) {
72
+ const read = delivered.safeParse(payload);
73
+ if (!read.success)
74
+ return { delivery: envelope_id, text: JSON.stringify({ type, envelope_id, payload }) };
75
+ const kept = Object.fromEntries(Object.entries(read.data).filter(([key]) => key !== "token"));
76
+ return {
77
+ delivery: read.data.event_id ?? envelope_id,
78
+ text: JSON.stringify({ type, envelope_id, payload: kept }),
79
+ };
80
+ }
81
+ /** Routes a stored envelope, then marks it handled; one that is not marked is routed `again` at the next start, where `route` finds what it wrote the first time and does not write it twice. */
82
+ async function deliver(ctx, settings, delivery, type, payload, again) {
83
+ await route(ctx, settings, type, payload, { id: delivery, again });
84
+ const handled = await ctx.inbox.handled(delivery);
85
+ if (!handled.ok)
86
+ ctx.log(`inbox.handled ${delivery}: ${handled.error.message}`);
87
+ return handled.ok;
88
+ }
89
+ /** Routes what the inbox still holds, oldest first: envelopes stored before a stop and those a person replayed. */
90
+ async function replay(ctx, settings) {
91
+ for (;;) {
92
+ const pending = await ctx.inbox.pending();
93
+ if (!pending.ok) {
94
+ ctx.log(`inbox.pending: ${pending.error.message}`);
95
+ return;
96
+ }
97
+ if (pending.value.deliveries.length === 0)
98
+ return;
99
+ for (const { delivery, payload } of pending.value.deliveries) {
100
+ const stored = envelopeOf(payload);
101
+ const handled = await deliver(ctx, settings, delivery, stored?.type ?? "", stored?.payload, true);
102
+ if (!handled)
103
+ return;
104
+ }
105
+ }
106
+ }
107
+ /** Reads one connection until Slack asks to reconnect, the socket closes or the service stops. Each envelope is stored in the engine's inbox first and acknowledged after, inside Slack's 3 s, then routed: an envelope the inbox cannot take is not acknowledged, so Slack sends it again, and one it held already is not routed again. */
64
108
  async function session(ctx, settings, link) {
65
109
  const close = () => link.close();
66
110
  ctx.signal.addEventListener("abort", close, { once: true });
67
111
  const routed = [];
68
112
  try {
69
113
  for await (const text of link.messages) {
70
- const read = attempt(() => JSON.parse(text), () => undefined);
71
- const parsed = envelope.safeParse(read.ok ? read.value : undefined);
72
- if (!parsed.success)
114
+ const parsed = envelopeOf(text);
115
+ if (parsed === undefined)
116
+ continue;
117
+ const { type, envelope_id, payload } = parsed;
118
+ if (type === "disconnect" || envelope_id === undefined) {
119
+ if (envelope_id !== undefined)
120
+ link.send(JSON.stringify({ envelope_id }));
121
+ if (type === "disconnect")
122
+ break;
73
123
  continue;
74
- const { type, envelope_id, payload } = parsed.data;
75
- if (envelope_id !== undefined)
76
- link.send(JSON.stringify({ envelope_id }));
77
- if (type === "disconnect")
78
- break;
79
- routed.push(route(ctx, settings, type, payload));
124
+ }
125
+ const { delivery, text: stored } = keep(type, envelope_id, payload);
126
+ const kept = await ctx.inbox.receive(delivery, stored);
127
+ if (!kept.ok) {
128
+ ctx.log(`an event could not be stored, so Slack sends it again: ${kept.error.message}`);
129
+ continue;
130
+ }
131
+ link.send(JSON.stringify({ envelope_id }));
132
+ if (kept.value.stored)
133
+ routed.push(deliver(ctx, settings, delivery, type, payload, false));
80
134
  }
81
135
  }
82
136
  finally {
@@ -85,11 +139,16 @@ async function session(ctx, settings, link) {
85
139
  }
86
140
  await Promise.all(routed);
87
141
  }
88
- /** The Socket Mode service: it opens a connection with the app token, serves it, and opens the next one when Slack closes it, until `ctx.signal` aborts. A connection that ends within `SHORT_SESSION_MS` is logged with its close code, and the next waits twice as long as the last, up to a minute. A refused app token ends it as a permanent failure. With `inbound = "events"` it only waits, since Slack posts to the engine instead. */
142
+ /** The Socket Mode service: it opens a connection with the app token, serves it, and opens the next one when Slack closes it, until `ctx.signal` aborts. A connection that ends within `SHORT_SESSION_MS` is logged with its close code, and the next waits twice as long as the last, up to a minute. It first runs `checkSetup`: a refused bot token ends it as a permanent failure, and each warning goes to the log. A refused app token ends it as a permanent failure too. With `inbound = "events"` it only waits, since Slack posts to the engine instead. With `inbound = "socket"` it routes what the inbox still holds before it opens the first connection. */
89
143
  export async function listen(ctx, connect) {
90
144
  const settings = settingsOf(ctx.config);
91
145
  if (!settings.ok)
92
146
  return settings.error;
147
+ const checked = await checkSetup(ctx, settings.value);
148
+ if (!checked.ok)
149
+ return checked.error;
150
+ for (const line of checked.value)
151
+ ctx.log(line);
93
152
  const nap = async (ms) => {
94
153
  await attemptAsync(async () => await sleep(ms, undefined, { signal: ctx.signal }), () => undefined);
95
154
  };
@@ -102,6 +161,7 @@ export async function listen(ctx, connect) {
102
161
  });
103
162
  return done({});
104
163
  }
164
+ await replay(ctx, settings.value);
105
165
  let pause = FIRST_PAUSE_MS;
106
166
  while (!ctx.signal.aborted) {
107
167
  const opened = await call(ctx, ctx.secrets.get(APP), "apps.connections.open", {}, connection);
@@ -1,3 +1,3 @@
1
- /** The Slack extension: a DM or a mention opens a card, the thread shows each stage, and tools post the summary, send a DM, ask a person and delete a message. */
1
+ /** The Slack extension: a DM or a mention opens a card, the thread shows each stage, tools post the summary, send a DM, ask a person and delete a message, and a thread that a card links is read for the run. */
2
2
  declare const _default: import("@kana-ai/edgar-sdk").Extension;
3
3
  export default _default;
package/dist/src/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { defineExtension, defineService } from "@kana-ai/edgar-sdk";
2
2
  import { APP, BOT, HOST } from "#api/client";
3
+ import { readLink } from "#inbound/read-link";
3
4
  import { listen, webSocket } from "#inbound/socket";
4
5
  import { progress } from "#outbound/progress";
5
6
  import { tools } from "#outbound/tools";
6
7
  import { config } from "#schemas/config";
7
8
  const app = "Create the Slack app from `node_modules/@kana-ai/edgar-ext-slack/slack-app.json` and install it.";
8
- /** The Slack extension: a DM or a mention opens a card, the thread shows each stage, and tools post the summary, send a DM, ask a person and delete a message. */
9
+ /** The Slack extension: a DM or a mention opens a card, the thread shows each stage, tools post the summary, send a DM, ask a person and delete a message, and a thread that a card links is read for the run. */
9
10
  export default defineExtension({
10
11
  name: "slack",
11
12
  config,
@@ -22,6 +23,8 @@ export default defineExtension({
22
23
  capabilities: [`network:${HOST}`, `network:*.${HOST}`, "runs:read"],
23
24
  tools,
24
25
  hooks: { progress },
26
+ readLink,
27
+ chatFiles: { hosts: [`files.${HOST}`], secret: BOT },
25
28
  service: defineService({
26
29
  secrets: [BOT, APP],
27
30
  capabilities: [`network:${HOST}`, `network:*.${HOST}`],
@@ -1,4 +1,4 @@
1
- import { cardLine } from "@kana-ai/edgar-sdk";
1
+ import { cardLine, cardMention, } from "@kana-ai/edgar-sdk";
2
2
  import { SECTION_CHARS, cutEscaped, escape, link } from "#outbound/tools";
3
3
  import { EMOJI, NOTE, PLAN, SAYS, STAGE, WAITS } from "#outbound/words";
4
4
  /** How Slack writes a link and a text that came from a card, a model or a failure. */
@@ -107,7 +107,8 @@ function rowOf({ stage, state, label }) {
107
107
  /** The progress of a run as one message that changes in place. The first line is the status and the card as a link. Then one short line per step that has started, in the order of its start, with the emoji of its state and its label of `stageLabel`; more than `FOLD` done steps are one line with their count, and a step that says what people decided on the pull request keeps its own line. A stage that was skipped or never started is not in the plan, and a plan that is over leaves out each step that never ended. The last line links the run's page, when the console has an address, and each pull request the run opened. The blocks are the first line in small text, so that its emoji is small too, Slack's plan block with one task card per line, and the links in small text. */
108
108
  export function planLayout(plan, settings) {
109
109
  const over = plan.ended !== undefined;
110
- const state = !over ? "working" : plan.ended === "done" ? "done" : "failed";
110
+ const queued = over || plan.tasks.length > 0 ? undefined : plan.queued;
111
+ const state = queued !== undefined ? "queued" : !over ? "working" : plan.ended === "done" ? "done" : "failed";
111
112
  const shown = plan.tasks.filter((task) => !(over && task.state === "working"));
112
113
  const plain = (task) => task.state === "done" && task.label === undefined;
113
114
  const done = shown.filter(plain);
@@ -127,11 +128,15 @@ export function planLayout(plan, settings) {
127
128
  url,
128
129
  })),
129
130
  ];
130
- const head = headline(state, PLAN.title[state], plan.card ?? `run ${plan.run}`);
131
+ const head = headline(state === "queued" ? "waits" : state, PLAN.title[state], plan.card ?? `run ${plan.run}`);
131
132
  const links = linksOf(targets);
132
- const lines = rows.length === 0 && !over
133
- ? [PLAN.started]
134
- : rows.map((row) => `${EMOJI[row.status]} ${escape(row.label)}`);
133
+ const lines = queued !== undefined
134
+ ? [
135
+ PLAN.queued(queued.key, queued.value === undefined ? undefined : escape(queued.value), queued.limit),
136
+ ]
137
+ : rows.length === 0 && !over
138
+ ? [PLAN.started]
139
+ : rows.map((row) => `${EMOJI[row.status]} ${escape(row.label)}`);
135
140
  const tasks = rows.map((row) => ({
136
141
  task_id: row.id.slice(0, 255),
137
142
  title: row.label,
@@ -233,6 +238,9 @@ export function noteLayout(run, note, user) {
233
238
  : what === "opened" || what === "failed"
234
239
  ? opened
235
240
  : facts.pulls.length;
241
+ const linked = (text) => card?.id === undefined
242
+ ? text
243
+ : text.replaceAll(cardMention(card.id), () => link(card.url, card.id ?? ""));
236
244
  const summary = SUMMED.has(what) && facts.summary !== undefined ? lead(facts.summary) : undefined;
237
245
  const why = what !== "failed"
238
246
  ? undefined
@@ -254,14 +262,14 @@ export function noteLayout(run, note, user) {
254
262
  : [SAYS.approvedBy(escape(names.format(facts.approvedBy)))]),
255
263
  ...(facts.commit === undefined ? [] : [SAYS.commit(escape(facts.commit))]),
256
264
  ...(why === undefined ? [] : [why]),
257
- ...(summary === undefined ? [] : [summary.text]),
265
+ ...(summary === undefined ? [] : [linked(summary.text)]),
258
266
  ...(what === "opened" && facts.risk !== undefined ? [escape(facts.risk)] : []),
259
267
  ...(summary?.cut === true && targets.length > 0 ? [SAYS.more] : []),
260
268
  ].join(" ");
261
269
  const options = what === "decision"
262
270
  ? facts.options
263
271
  .slice(0, MAX_OPTIONS)
264
- .map((option, at) => `${String(at + 1)}. ${lead(option, 300).text}`)
272
+ .map((option, at) => `${String(at + 1)}. ${linked(lead(option, 300).text)}`)
265
273
  : [];
266
274
  const told = what === "failed" && facts.next !== undefined
267
275
  ? SAYS.replay(facts.next, run)