@skillcdn/console 0.6.1 → 0.6.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 (147) hide show
  1. package/README.md +2 -2
  2. package/dist/agent-page.d.ts.map +1 -1
  3. package/dist/agent-page.js +38 -28
  4. package/dist/agent-page.js.map +1 -1
  5. package/dist/agent-usage.d.ts +9 -6
  6. package/dist/agent-usage.d.ts.map +1 -1
  7. package/dist/agent-usage.js +38 -8
  8. package/dist/agent-usage.js.map +1 -1
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.d.ts.map +1 -1
  11. package/dist/api.js +1 -1
  12. package/dist/api.js.map +1 -1
  13. package/dist/cli/cli.d.ts.map +1 -1
  14. package/dist/cli/cli.js +65 -0
  15. package/dist/cli/cli.js.map +1 -1
  16. package/dist/cli/help.js +3 -3
  17. package/dist/cli/help.js.map +1 -1
  18. package/dist/client.d.ts +7 -1
  19. package/dist/client.d.ts.map +1 -1
  20. package/dist/client.js +2 -1
  21. package/dist/client.js.map +1 -1
  22. package/dist/components/agent-page.d.ts +33 -8
  23. package/dist/components/agent-page.d.ts.map +1 -1
  24. package/dist/components/agent-page.js +98 -32
  25. package/dist/components/agent-page.js.map +1 -1
  26. package/dist/components/calendar.d.ts +24 -4
  27. package/dist/components/calendar.d.ts.map +1 -1
  28. package/dist/components/calendar.js +78 -35
  29. package/dist/components/calendar.js.map +1 -1
  30. package/dist/console.d.ts.map +1 -1
  31. package/dist/console.js +39 -11
  32. package/dist/console.js.map +1 -1
  33. package/dist/data.d.ts +2 -0
  34. package/dist/data.d.ts.map +1 -1
  35. package/dist/data.js +4 -0
  36. package/dist/data.js.map +1 -1
  37. package/dist/desk-page.js +5 -5
  38. package/dist/desk-page.js.map +1 -1
  39. package/dist/feed-words.js +6 -0
  40. package/dist/feed-words.js.map +1 -1
  41. package/dist/i18n/en.d.ts +6 -0
  42. package/dist/i18n/en.d.ts.map +1 -1
  43. package/dist/i18n/en.js +8 -1
  44. package/dist/i18n/en.js.map +1 -1
  45. package/dist/i18n/ko.d.ts.map +1 -1
  46. package/dist/i18n/ko.js +24 -17
  47. package/dist/i18n/ko.js.map +1 -1
  48. package/dist/index.d.ts +1 -1
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1 -1
  51. package/dist/index.js.map +1 -1
  52. package/dist/plugin/capabilities.d.ts +1 -1
  53. package/dist/plugin/capabilities.d.ts.map +1 -1
  54. package/dist/plugin/capabilities.js +6 -1
  55. package/dist/plugin/capabilities.js.map +1 -1
  56. package/dist/plugin/context.d.ts +62 -1
  57. package/dist/plugin/context.d.ts.map +1 -1
  58. package/dist/plugin/limits.d.ts +7 -0
  59. package/dist/plugin/limits.d.ts.map +1 -1
  60. package/dist/plugin/limits.js +7 -0
  61. package/dist/plugin/limits.js.map +1 -1
  62. package/dist/plugin/testing.d.ts +2 -0
  63. package/dist/plugin/testing.d.ts.map +1 -1
  64. package/dist/plugin/testing.js +2 -0
  65. package/dist/plugin/testing.js.map +1 -1
  66. package/dist/rules.js +1 -1
  67. package/dist/rules.js.map +1 -1
  68. package/dist/runner/claude.d.ts.map +1 -1
  69. package/dist/runner/claude.js +138 -9
  70. package/dist/runner/claude.js.map +1 -1
  71. package/dist/runner/desk.d.ts.map +1 -1
  72. package/dist/runner/desk.js +11 -4
  73. package/dist/runner/desk.js.map +1 -1
  74. package/dist/runner/message.d.ts +32 -2
  75. package/dist/runner/message.d.ts.map +1 -1
  76. package/dist/runner/message.js +163 -27
  77. package/dist/runner/message.js.map +1 -1
  78. package/dist/runner/runner.d.ts +15 -1
  79. package/dist/runner/runner.d.ts.map +1 -1
  80. package/dist/runner/runner.js +131 -15
  81. package/dist/runner/runner.js.map +1 -1
  82. package/dist/runner/slack.d.ts +17 -11
  83. package/dist/runner/slack.d.ts.map +1 -1
  84. package/dist/runner/slack.js +1007 -105
  85. package/dist/runner/slack.js.map +1 -1
  86. package/dist/runner/types.d.ts +110 -5
  87. package/dist/runner/types.d.ts.map +1 -1
  88. package/dist/runner/types.js.map +1 -1
  89. package/dist/runner.d.ts +4 -4
  90. package/dist/runner.d.ts.map +1 -1
  91. package/dist/runner.js +3 -3
  92. package/dist/runner.js.map +1 -1
  93. package/dist/schemas.d.ts +103 -0
  94. package/dist/schemas.d.ts.map +1 -1
  95. package/dist/schemas.js +55 -0
  96. package/dist/schemas.js.map +1 -1
  97. package/docs/specs/cli.md +2 -1
  98. package/docs/specs/plugins.md +7 -2
  99. package/docs/specs/rest.md +4 -2
  100. package/docs/specs/runner.md +50 -19
  101. package/package.json +1 -1
  102. package/skills/building-a-plugin/SKILL.md +3 -3
  103. package/skills/planning-the-board/references/setting-up.md +1 -1
  104. package/skills/running-an-agent/SKILL.md +10 -67
  105. package/skills/running-an-agent/references/preparing-the-machine.md +17 -0
  106. package/skills/running-an-agent/references/several-tasks.md +1 -1
  107. package/skills/running-an-agent/references/slack-app.md +36 -6
  108. package/skills/running-an-agent/references/the-account-and-the-invitation.md +5 -0
  109. package/skills/running-an-agent/references/what-was-not-seen-run-yet.md +3 -0
  110. package/skills/running-an-agent/references/when-the-agent-could-not-go-on.md +16 -0
  111. package/skills/running-an-agent/references/your-first-task.md +14 -0
  112. package/skills/working-the-board/SKILL.md +9 -13
  113. package/skills/working-the-board/references/a-pack-skills-questions.md +3 -0
  114. package/skills/working-the-board/references/a-plugins-commands.md +3 -0
  115. package/skills/working-the-board/references/a-review.md +3 -0
  116. package/skills/working-the-board/references/an-open-run.md +3 -0
  117. package/skills/working-the-board/references/requirements.md +7 -0
  118. package/skills/working-the-board/references/what-they-were-told.md +3 -0
  119. package/skills/working-the-board/references/work-given-in-chat.md +5 -0
  120. package/src/agent-page.tsx +41 -40
  121. package/src/agent-usage.ts +55 -12
  122. package/src/api.ts +7 -0
  123. package/src/cli/cli.ts +84 -0
  124. package/src/cli/help.ts +3 -3
  125. package/src/client.ts +11 -0
  126. package/src/components/agent-page.tsx +114 -36
  127. package/src/components/calendar.tsx +92 -36
  128. package/src/console.tsx +46 -10
  129. package/src/data.ts +6 -0
  130. package/src/desk-page.tsx +5 -5
  131. package/src/feed-words.ts +6 -0
  132. package/src/i18n/en.ts +11 -1
  133. package/src/i18n/ko.ts +30 -17
  134. package/src/index.ts +2 -0
  135. package/src/plugin/capabilities.ts +8 -1
  136. package/src/plugin/context.ts +63 -0
  137. package/src/plugin/limits.ts +7 -0
  138. package/src/plugin/testing.ts +4 -0
  139. package/src/rules.ts +1 -1
  140. package/src/runner/claude.ts +154 -9
  141. package/src/runner/desk.ts +13 -4
  142. package/src/runner/message.ts +176 -29
  143. package/src/runner/runner.ts +173 -15
  144. package/src/runner/slack.ts +1273 -124
  145. package/src/runner/types.ts +102 -2
  146. package/src/runner.ts +16 -1
  147. package/src/schemas.ts +64 -0
@@ -1,6 +1,8 @@
1
1
  import * as z from "zod/mini";
2
+ import { MAX_SIGNAL_LENGTH } from "../limits.js";
2
3
  import { withoutForbiddenCodePoints } from "../text.js";
3
- import type { WakeHost, WakeSource } from "./types.js";
4
+ import { wakeTextOf } from "./message.js";
5
+ import type { WakeAccount, WakeHost, WakePart, WakeRead, WakeSource, WakeWriter } from "./types.js";
4
6
 
5
7
  // The `slack` wake source (ADR-0085): one app for one agent account, which receives over its
6
8
  // Socket Mode connection the events the agent's own member of the workspace can see, and raises
@@ -8,16 +10,68 @@ import type { WakeHost, WakeSource } from "./types.js";
8
10
  // message that mentions it, and any message of a channel `runner.json` names. The wake names the
9
11
  // thread, so that what is said in one thread is one thing to the agent, and
10
12
  // carries the words as someone else's: what the message shows, a table, a list and code among
11
- // it, read from its blocks where it has them. Written from the messenger's own documentation of
12
- // Socket Mode, of the Events API and of its blocks; what an event holds is read by schema,
13
- // bounded, and never run.
13
+ // it, read from its blocks where it has them. Its first line is the source's own, and says of
14
+ // the account that wrote what the event says of it: its id, its workspace where that is
15
+ // another than the agent's (ADR-0160), that it wrote through an app where it did, and, where the
16
+ // console knows which member the account is (ADR-0164), that member and whether they supervise
17
+ // the agent. A wake is
18
+ // raised in parts (ADR-0163): the source's own lines, which nothing a message holds reaches,
19
+ // and what was written, a message someone passed on apart from the words of whoever passed it
20
+ // on. With the member's own token, where the account keeps it, the source reads what was said
21
+ // in the conversation before the message, and the wake carries what the agent missed of it,
22
+ // who else there writes as an agent account does, and what to judge by whether to answer.
23
+ // Written from the messenger's own documentation of Socket Mode, of the Events API, of its
24
+ // blocks and of the two methods that read a conversation; what an event or an answer holds is
25
+ // read by schema, bounded, and never run.
14
26
 
15
27
  /** The secret of the account's store that holds the app's token for the socket (`xapp-...`). */
16
28
  export const SLACK_APP_TOKEN = "slack.app_token";
29
+ /**
30
+ * The secret that holds the member's own token (`xoxp-...`), which the agent sends with: with it
31
+ * the source reads the conversation a wake is raised in, as the scopes the events ask for allow.
32
+ */
33
+ export const SLACK_USER_TOKEN = "slack.user_token";
17
34
  /** Where a connection is asked for. */
18
35
  const OPEN_URL = "https://slack.com/api/apps.connections.open";
19
- /** The most of a message a wake carries: the agent reads the thread with the messenger's own tool. */
36
+ /** Where a conversation is read outside its threads, the newest first, and where a thread is, the oldest first. */
37
+ const HISTORY_URL = "https://slack.com/api/conversations.history";
38
+ const REPLIES_URL = "https://slack.com/api/conversations.replies";
39
+ /** The most of a message a wake carries: the agent reads the rest with the messenger's own tool. */
20
40
  const MAX_WAKE_TEXT = 4000;
41
+ /**
42
+ * The most the message itself takes of the text a signal carries, its lines begun as that text
43
+ * begins them: what is left is for what was said before it and for who else is there. A message of a
44
+ * great many short lines comes to more than this within `MAX_WAKE_TEXT`, and is cut shorter.
45
+ */
46
+ const MAX_LEAD_LENGTH = MAX_SIGNAL_LENGTH - 2500;
47
+ /** How many of the things that hang under a message a wake carries apart, as it names so many files. */
48
+ const MAX_UNDER = 5;
49
+ /**
50
+ * What a wake carries of what was said before the message that raised it: so many messages at
51
+ * the most, so much of each, and so much of them together as the text a signal carries holds.
52
+ */
53
+ const MAX_BEFORE = 10;
54
+ const MAX_BEFORE_TEXT = 500;
55
+ const MAX_BEFORE_LENGTH = 3000;
56
+ /** How many messages a wake reads of a conversation, and of a thread: a page of so many, so many pages. */
57
+ const READ_MESSAGES = 50;
58
+ const READ_THREAD_PAGE = 200;
59
+ const READ_THREAD_PAGES = 5;
60
+ /** How long all that one wake reads is waited for, however many requests it takes, before the wake goes without. */
61
+ const READ_WAIT_MS = 5000;
62
+ /** How many wakes may wait behind one whose conversation is read: with more, it goes with nothing read. */
63
+ const MAX_WAITING = 5;
64
+ /** How long the source waits before it opens the connection the messenger asked for in place of the one it ended. */
65
+ const REOPEN_WAIT_MS = 1000;
66
+ /** How many others that write through an app a wake names. */
67
+ const MAX_OTHERS = 5;
68
+ /** Of so many accounts the console is asked at once who they are: what one asking takes. */
69
+ const MAX_WRITERS_ASKED = 100;
70
+ /** What the command reads of a conversation where nothing says how much, and at the most. */
71
+ export const SLACK_READ_DEFAULT = 20;
72
+ export const SLACK_READ_MOST = 100;
73
+ /** How long what the command reads is at the most, every message of it together: the newest are kept. */
74
+ const MAX_READ_LENGTH = 12_000;
21
75
  /** The deepest a list of a message is indented in a wake. */
22
76
  const MAX_LIST_DEPTH = 8;
23
77
  /** How many files of a message a wake names, and how much of a name. */
@@ -60,14 +114,67 @@ const eventSchema = z.object({
60
114
  files: z.optional(z.unknown()),
61
115
  ts: z.optional(stamp),
62
116
  thread_ts: z.optional(stamp),
117
+ /**
118
+ * The workspace the message came from, and in a conversation shared between workspaces the
119
+ * one its writer is a member of. Read loosely (`workspaceOf`): one that is not spelled as the
120
+ * messenger spells an id says nothing, and never lets go of the wake.
121
+ */
122
+ team: z.optional(z.unknown()),
123
+ user_team: z.optional(z.unknown()),
63
124
  });
64
125
 
65
126
  const payloadSchema = z.object({
66
127
  event: z.optional(eventSchema),
67
- /** The installation the event was delivered for: the member the app acts for. */
128
+ /**
129
+ * The installation the event was delivered for: the member the app acts for, with the
130
+ * workspace that member is of and, where the workspace is one of several of an organization,
131
+ * the organization. The two are read loosely, as an event's own workspace is.
132
+ */
68
133
  authorizations: z.optional(
69
- z.array(z.object({ user_id: z.optional(z.nullable(id)) })).check(z.maxLength(20)),
134
+ z
135
+ .array(
136
+ z.object({
137
+ user_id: z.optional(z.nullable(id)),
138
+ team_id: z.optional(z.unknown()),
139
+ enterprise_id: z.optional(z.unknown()),
140
+ }),
141
+ )
142
+ .check(z.maxLength(20)),
70
143
  ),
144
+ /** Whether the conversation is shared with another organization, as the messenger says it. */
145
+ is_ext_shared_channel: z.optional(z.unknown()),
146
+ });
147
+
148
+ /** A workspace's id, or an organization's, as the messenger spells one; nothing for anything else. */
149
+ const workspaceOf = (value: unknown): string | undefined =>
150
+ typeof value === "string" && /^[A-Z0-9]{1,24}$/.test(value) ? value : undefined;
151
+
152
+ /**
153
+ * A message as a read of a conversation answers one: what the source reads of it, and nothing
154
+ * else. Its blocks and what hangs under it are read loosely, as an event's are.
155
+ */
156
+ const heardSchema = z.object({
157
+ subtype: z.optional(z.string().check(z.maxLength(60))),
158
+ user: z.optional(id),
159
+ bot_id: z.optional(z.string().check(z.maxLength(40))),
160
+ text: z.optional(z.string().check(z.maxLength(100_000))),
161
+ blocks: z.optional(z.unknown()),
162
+ attachments: z.optional(z.unknown()),
163
+ files: z.optional(z.unknown()),
164
+ ts: stamp,
165
+ thread_ts: z.optional(stamp),
166
+ team: z.optional(z.unknown()),
167
+ user_team: z.optional(z.unknown()),
168
+ });
169
+ type HeardMessage = z.infer<typeof heardSchema>;
170
+
171
+ /** What a read of a conversation answers: its messages, each read by itself, and whether there are more. */
172
+ const readSchema = z.object({
173
+ ok: z.boolean(),
174
+ error: z.optional(z.string().check(z.maxLength(200))),
175
+ messages: z.optional(z.array(z.unknown()).check(z.maxLength(1000))),
176
+ has_more: z.optional(z.unknown()),
177
+ response_metadata: z.optional(z.unknown()),
71
178
  });
72
179
 
73
180
  const envelopeSchema = z.object({
@@ -90,10 +197,10 @@ class SlackError extends Error {
90
197
  }
91
198
  }
92
199
 
93
- /** A wake as a wake source raises one. */
94
- export interface RaisedWake {
200
+ /** A wake as this source raises one: its key, and its parts in the order the agent reads them. */
201
+ export interface SlackWake {
95
202
  readonly key: string;
96
- readonly text: string;
203
+ readonly parts: readonly WakePart[];
97
204
  }
98
205
 
99
206
  type Json = Record<string, unknown>;
@@ -265,40 +372,6 @@ function blockOf(block: Json): string[] {
265
372
  }
266
373
  }
267
374
 
268
- /**
269
- * A message's words as people read them. Where it has blocks they are what the messenger shows,
270
- * and its `text` is what a notification says in their place, which leaves a table out: the
271
- * words are read from the blocks, and from the `text` only where no block says anything. A
272
- * table may hang under the message instead, so what hangs under it is read after its own: its
273
- * blocks, or the words it has in their place, a message someone passed on say. A file of the
274
- * message is named and marked as not carried. Each is walked once and to the depth the
275
- * messenger gives a block, whatever it is nested with.
276
- */
277
- function wordsOf(event: {
278
- readonly text?: string | undefined;
279
- readonly blocks?: unknown;
280
- readonly attachments?: unknown;
281
- readonly files?: unknown;
282
- }): string {
283
- const shownBy = (blocks: readonly unknown[]): string =>
284
- blocks
285
- .flatMap((block) => (isObject(block) ? blockOf(block) : []))
286
- .filter((part) => part.trim() !== "")
287
- .join("\n");
288
- const shown = shownBy(listOf(event.blocks));
289
- const under = listOf(event.attachments).map((one) => {
290
- if (!isObject(one)) {
291
- return "";
292
- }
293
- const blocks = shownBy(listOf(one.blocks));
294
- const words = blocks === "" ? (textOf(one.text) ?? textOf(one.fallback) ?? "") : blocks;
295
- return words.trim() === "" ? leftOut("attachment") : words;
296
- });
297
- return [shown === "" ? (event.text ?? "") : shown, ...under, ...filesOf(event.files)]
298
- .filter((part) => part !== "")
299
- .join("\n");
300
- }
301
-
302
375
  /** A mark for each file of a message, by its name on one line: the first few, and how many more. */
303
376
  function filesOf(files: unknown): string[] {
304
377
  const all = listOf(files).filter(isObject);
@@ -313,12 +386,147 @@ function filesOf(files: unknown): string[] {
313
386
  return more > 0 ? [...marks, `[${more} more files, not carried in this wake]`] : marks;
314
387
  }
315
388
 
389
+ /** What a message shows, of the fields a wake reads: an event's, or a message's as a read answers it. */
390
+ interface Shown {
391
+ readonly text?: string | undefined;
392
+ readonly blocks?: unknown;
393
+ readonly attachments?: unknown;
394
+ readonly files?: unknown;
395
+ }
396
+
397
+ /** Something that hangs under a message: what the source says of it, and what it shows. */
398
+ interface Under {
399
+ readonly says: string;
400
+ readonly words: string;
401
+ /** Whether it is a message someone passed on, or one a link to it brought along. */
402
+ readonly passedOn: boolean;
403
+ }
404
+
405
+ /** A message as a wake carries it: its writer's own words, and what hangs under it, each apart. */
406
+ interface Said {
407
+ readonly words: string;
408
+ readonly under: readonly Under[];
409
+ }
410
+
411
+ /** What a member's id begins with, as the messenger spells one. */
412
+ const MEMBER_ID = /^[UW][A-Z0-9]{1,23}$/;
413
+
414
+ /**
415
+ * What the blocks of a message show, the parts one under another. Each is walked once and to the
416
+ * depth the messenger gives a block, whatever it is nested with.
417
+ */
418
+ const shownBy = (blocks: readonly unknown[]): string =>
419
+ blocks
420
+ .flatMap((block) => (isObject(block) ? blockOf(block) : []))
421
+ .filter((part) => part.trim() !== "")
422
+ .join("\n");
423
+
424
+ /**
425
+ * A message's words as people read them, and what hangs under it apart from them. Where it has
426
+ * blocks they are what the messenger shows, and its `text` is what a notification says in their
427
+ * place, which leaves a table out: the words are read from the blocks, and from the `text` only
428
+ * where no block says anything. A file of the message is named and marked as not carried.
429
+ *
430
+ * What hangs under a message is not its writer's own words: a message someone passed on, one a
431
+ * link to it brought along, a preview of a page, a table the messenger shows apart. Each is
432
+ * carried apart, behind a line of the source's own that says what it is, and for a message
433
+ * passed on who wrote it, by the id the messenger gives for its writer: carried in the words,
434
+ * what a supervisor passed on would read as the supervisor's asking (ADR-0160, ADR-0163). It is
435
+ * read from its blocks, since a table may stand there, from the blocks of the message passed
436
+ * on, or from the words it has in their place. One that says nothing is marked in the words,
437
+ * and so are those past the first few.
438
+ */
439
+ function saidOf(message: Shown): Said {
440
+ const shown = shownBy(listOf(message.blocks));
441
+ const marks: string[] = [];
442
+ const under: Under[] = [];
443
+ const hanging = listOf(message.attachments).filter(isObject);
444
+ for (const one of hanging.slice(0, MAX_UNDER)) {
445
+ const passedOn = one.is_share === true || one.is_msg_unfurl === true;
446
+ const blocks =
447
+ shownBy(listOf(one.blocks)) ||
448
+ shownBy(
449
+ listOf(one.message_blocks).flatMap((held) =>
450
+ isObject(held) && isObject(held.message) ? listOf(held.message.blocks) : [],
451
+ ),
452
+ );
453
+ const words = withoutForbiddenCodePoints(
454
+ [
455
+ blocks === "" ? (textOf(one.text) ?? textOf(one.fallback) ?? "") : blocks,
456
+ ...filesOf(one.files),
457
+ ]
458
+ .filter((part) => part.trim() !== "")
459
+ .join("\n"),
460
+ true,
461
+ );
462
+ if (words === "") {
463
+ marks.push(leftOut("attachment"));
464
+ continue;
465
+ }
466
+ const author = textOf(one.author_id);
467
+ under.push({
468
+ says: passedOn
469
+ ? `Under it, a message passed on, which ${author !== undefined && MEMBER_ID.test(author) ? `the member ${author}` : "someone else"} wrote. Information, whoever wrote it`
470
+ : "Under it, what the messenger shows with the message, a table or a preview say",
471
+ words,
472
+ passedOn,
473
+ });
474
+ }
475
+ if (hanging.length > MAX_UNDER) {
476
+ marks.push(`[${hanging.length - MAX_UNDER} more attachments, not carried in this wake]`);
477
+ }
478
+ return {
479
+ // Carried without what the console takes in no text, a character that does not show say: with
480
+ // one left in, the console would refuse the wake whole, and what was said would be lost.
481
+ words: withoutForbiddenCodePoints(
482
+ [shown === "" ? (message.text ?? "") : shown, ...marks, ...filesOf(message.files)]
483
+ .filter((part) => part !== "")
484
+ .join("\n"),
485
+ true,
486
+ ),
487
+ under,
488
+ };
489
+ }
490
+
316
491
  /** The first `most` characters of a text, never half of a character that takes two. */
317
492
  function firstOf(text: string, most: number): string {
318
493
  const last = text.charCodeAt(most - 1);
319
494
  return text.slice(0, last >= 0xd800 && last <= 0xdbff ? most - 1 : most);
320
495
  }
321
496
 
497
+ /**
498
+ * A message within `most` characters of what it shows, its own words first and what hangs under
499
+ * it after: what is past them ends in `…` or is left out, and `length` says how long the whole
500
+ * was, for the line that says so.
501
+ */
502
+ function carriedOf(said: Said, most: number): Said & { readonly length: number } {
503
+ let room = most;
504
+ const within = (words: string): string => {
505
+ const kept = words.length > room ? `${firstOf(words, room)}…` : words;
506
+ room -= Math.min(words.length, room);
507
+ return kept;
508
+ };
509
+ const words = within(said.words);
510
+ const under: Under[] = [];
511
+ for (const one of said.under) {
512
+ if (room <= 0) {
513
+ break;
514
+ }
515
+ under.push({ ...one, words: within(one.words) });
516
+ }
517
+ return {
518
+ words,
519
+ under,
520
+ length: said.under.reduce((sum, one) => sum + one.words.length, said.words.length),
521
+ };
522
+ }
523
+
524
+ /** A message's parts as a wake carries them, after the line of the source's own that leads them. */
525
+ const partsOf = (said: Said): WakePart[] => [
526
+ ...(said.words === "" ? [] : [{ words: said.words }]),
527
+ ...said.under.flatMap((one) => [{ says: one.says }, { words: one.words }]),
528
+ ];
529
+
322
530
  /**
323
531
  * How the messenger writes a call of everyone in a message's `text`: `<!here>`, `<!channel>`
324
532
  * and `<!everyone>`, with what it shows for it after a bar where it says so. What a person
@@ -326,24 +534,225 @@ function firstOf(text: string, most: number): string {
326
534
  */
327
535
  const EVERYONE_CALLED = /<!(here|channel|everyone)(?:\|[^<>]{0,40})?>/;
328
536
 
537
+ /**
538
+ * Who wrote a message, as a line of the source's says it: the account by the id the messenger
539
+ * gives it, its workspace where the message says that it is another than the agent's own, and
540
+ * that it wrote through an app where the message says so, which is how an agent account writes
541
+ * with its member's token, and an app that posts in a member's name. An app that posted in
542
+ * nobody's name is said as an app. The agent's own is the workspace the event was delivered
543
+ * for, and the organization that workspace is one of several of, either of which an
544
+ * installation may leave out. Where the message names no workspace for its writer, or nothing
545
+ * is known of the agent's own, nothing is said of it: a line that names no workspace is no
546
+ * proof of a colleague.
547
+ */
548
+ function writerOf(
549
+ message: Written,
550
+ own: readonly (string | undefined)[],
551
+ who: Who = NOBODY,
552
+ ): string {
553
+ if (message.user === undefined) {
554
+ const app = workspaceOf(message.bot_id);
555
+ return `an app${app === undefined ? "" : ` (${app})`}`;
556
+ }
557
+ const theirs = workspaceOf(message.user_team) ?? workspaceOf(message.team);
558
+ const elsewhere =
559
+ theirs === undefined || own.includes(theirs) || own.every((one) => one === undefined)
560
+ ? undefined
561
+ : theirs;
562
+ return `the member ${message.user}${elsewhere === undefined ? "" : ` of another workspace (${elsewhere})`}${message.bot_id === undefined ? "" : " through an app"}${who(message)}`;
563
+ }
564
+
565
+ /** What a message says of whoever wrote it. */
566
+ interface Written {
567
+ readonly user?: string | undefined;
568
+ readonly bot_id?: string | undefined;
569
+ readonly team?: unknown;
570
+ readonly user_team?: unknown;
571
+ }
572
+
573
+ /**
574
+ * What the console says of the account that wrote a message, as a line of the source's says it
575
+ * after the account (ADR-0164), or nothing where the console says nothing of it.
576
+ */
577
+ type Who = (message: Written) => string;
578
+ const NOBODY: Who = () => "";
579
+
580
+ /** Why what was asked came to nothing as the signal ended: by the word it was ended with, or because the wait for it was over. */
581
+ const endedBy = (until: AbortSignal): string =>
582
+ typeof until.reason === "string" ? until.reason : "no_answer";
583
+
584
+ /** What is answered before the signal ends, or that it ended: an answer that comes or fails after that is nobody's to hear. */
585
+ const ENDED = Symbol("ended");
586
+ async function unlessEnded<T>(until: AbortSignal, answer: Promise<T>): Promise<T | typeof ENDED> {
587
+ answer.catch(() => undefined);
588
+ let stop = (): void => undefined;
589
+ const ended = new Promise<typeof ENDED>((resolve) => {
590
+ stop = () => resolve(ENDED);
591
+ until.addEventListener("abort", stop, { once: true });
592
+ });
593
+ try {
594
+ return await Promise.race([answer, ended]);
595
+ } finally {
596
+ until.removeEventListener("abort", stop);
597
+ }
598
+ }
599
+
600
+ /** A login as a line of the source's carries one: a name of the console's, and never anything a line could be made of. */
601
+ const LOGIN = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,99}$/;
602
+
603
+ /**
604
+ * The account a message names as its writer, as the console is asked of it: with the workspace
605
+ * the message itself says the account is of, and none where it says none. The agent's own
606
+ * workspace is never taken for it: the same id at another workspace is another account, and an
607
+ * account whose workspace nothing says is nobody the console knows.
608
+ */
609
+ function accountOf(message: Written): WakeAccount | undefined {
610
+ const workspace = workspaceOf(message.user_team) ?? workspaceOf(message.team);
611
+ return message.user === undefined || workspace === undefined
612
+ ? undefined
613
+ : { workspace, account: message.user };
614
+ }
615
+
616
+ /**
617
+ * How a member stands to the agent, as a line says it after who they are: a supervisor of its
618
+ * own or none, and where the console says more, how: its manager, anyone above its manager or
619
+ * an administrator, who supervises from outside the line and may stand in it too; and of
620
+ * anyone below the agent in its line, that they report to it, themselves or through others.
621
+ * A console that says only whether a member supervises is said as it was.
622
+ */
623
+ function standsOf(member: NonNullable<WakeWriter["member"]>): string {
624
+ const reports =
625
+ member.line === "report"
626
+ ? "reports to you"
627
+ : member.line === "below"
628
+ ? "reports to you through others"
629
+ : undefined;
630
+ // A supervisor only where the console says so in so many words: how it is one says more of
631
+ // it, and never makes one.
632
+ if (member.supervisor !== true) {
633
+ return `no supervisor of yours${reports === undefined ? "" : `, ${reports}`}`;
634
+ }
635
+ const how = [
636
+ member.line === "manager"
637
+ ? "your manager"
638
+ : member.line === "above"
639
+ ? "above your manager"
640
+ : undefined,
641
+ member.administrator === true ? "an administrator" : undefined,
642
+ ].filter((one) => one !== undefined);
643
+ return `a supervisor of yours${how.length === 0 ? "" : `: ${how.join(" and ")}`}${reports === undefined ? "" : `, who ${reports}`}`;
644
+ }
645
+
646
+ /**
647
+ * Asks the console who wrote (ADR-0164), of so many messages at once, and answers what a line
648
+ * says of each writer after the account:
649
+ *
650
+ * - the member it is, by their login in the console, an agent account said as one, and whether
651
+ * they supervise the agent: `(@kim in the console, a supervisor of yours: your manager)`,
652
+ * with how, its manager, anyone above its manager or an administrator, and of anyone below
653
+ * the agent in its line that they report to it, themselves or through others (`standsOf`);
654
+ * - that it is no member the console knows, where the console is told the accounts of that
655
+ * workspace and not this one: what it is told may be short of one, so a supervisor's tell that
656
+ * names the account still tells whose it is;
657
+ * - nothing, where the console is told no account of that workspace, where it does not answer
658
+ * before the signal ends, or where it is older than the question: the line is then as the
659
+ * messenger alone has it. Where the signal has ended already, the console is not asked.
660
+ *
661
+ * It is the console's answer and nothing else's: no word of a message, no name the messenger
662
+ * shows and no id alone makes an account a supervisor's, and a login that is not shaped as one
663
+ * is left out. An agent takes a supervisor's own word at the messenger as an instruction
664
+ * (ADR-0160), and this is how a wake says that one wrote.
665
+ */
666
+ async function whoOf(
667
+ host: Pick<WakeHost, "writers">,
668
+ messages: readonly Written[],
669
+ until: AbortSignal,
670
+ ): Promise<Who> {
671
+ const keyOf = (one: WakeAccount): string => `${one.workspace} ${one.account}`;
672
+ const asked = new Map<string, WakeAccount>();
673
+ for (const message of messages) {
674
+ const one = accountOf(message);
675
+ if (one !== undefined && asked.size < MAX_WRITERS_ASKED) {
676
+ asked.set(keyOf(one), one);
677
+ }
678
+ }
679
+ if (host.writers === undefined || asked.size === 0 || until.aborted) {
680
+ return NOBODY;
681
+ }
682
+ try {
683
+ const answered = await unlessEnded(until, host.writers([...asked.values()], until));
684
+ if (answered === ENDED) {
685
+ return NOBODY;
686
+ }
687
+ const known = new Map<string, string>();
688
+ for (const one of answered) {
689
+ // Only what was asked of is heard, and only an answer of the shape one has.
690
+ if (!asked.has(keyOf(one)) || one.told !== true) {
691
+ continue;
692
+ }
693
+ const member = one.member;
694
+ // A login that is not shaped as one is not written into a line: the member is said, unnamed.
695
+ const named =
696
+ member !== null && typeof member.login === "string" && LOGIN.test(member.login)
697
+ ? `@${member.login} in the console`
698
+ : "a member of the console";
699
+ known.set(
700
+ keyOf(one),
701
+ member === null
702
+ ? " (no member the console knows)"
703
+ : ` (${named}${member.kind === "agent" ? ", an agent account" : ""}, ${standsOf(member)})`,
704
+ );
705
+ }
706
+ return (message) => {
707
+ const one = accountOf(message);
708
+ return one === undefined ? "" : (known.get(keyOf(one)) ?? "");
709
+ };
710
+ } catch {
711
+ return NOBODY;
712
+ }
713
+ }
714
+
715
+ /** What an event of the messenger means to the agent: the wake's key, its parts with nothing read of the conversation, and where it was said. */
716
+ interface Heard {
717
+ readonly key: string;
718
+ /** The line of the source's own, with what the console says of who wrote, then the message and what hangs under it. */
719
+ readonly saying: (who: Who) => readonly WakePart[];
720
+ readonly channel: string;
721
+ /** The message's own moment, and the thread it was written in where it was written in one. */
722
+ readonly ts: string;
723
+ readonly thread: string | undefined;
724
+ /** The account that wrote, and the member the event was delivered for, where the event says. */
725
+ readonly user: string;
726
+ readonly member: string | undefined;
727
+ /** Whether it was said in a direct conversation, where nobody else is, or in a group conversation. */
728
+ readonly direct: boolean;
729
+ readonly group: boolean;
730
+ /** The agent's own workspace and organization, as the event names them. */
731
+ readonly own: readonly (string | undefined)[];
732
+ /** What the event says of whoever wrote, for the console to be asked who that is. */
733
+ readonly from: Written;
734
+ }
735
+
329
736
  /**
330
737
  * The wake an event of the messenger means, or nothing: a message in a direct conversation, or
331
738
  * one that mentions the member the app acts for, from anyone but that member; and, mentioned or
332
739
  * not, a person's message in a group conversation the member is in or in one of the channels
333
740
  * `runner.json` names, and a call of everyone (`@here`, `@channel`, `@everyone`) in any
334
741
  * channel the member is in, whoever wrote it. A message that is an edit, a join or anything else
335
- * than someone's words wakes nobody.
742
+ * than someone's words wakes nobody. The wake's first line names the account that wrote by its
743
+ * id, and its workspace where the event says it is another than the agent's own; and it says
744
+ * that a conversation is shared with another organization where the messenger says so: an
745
+ * agent goes by the account and never by a name (ADR-0160), and the same name at another
746
+ * organization is another account.
336
747
  */
337
- export function slackWakeOf(
338
- payload: unknown,
339
- channels: readonly string[] = [],
340
- ): RaisedWake | undefined {
748
+ function heardOf(payload: unknown, channels: readonly string[]): Heard | undefined {
341
749
  const parsed = payloadSchema.safeParse(payload);
342
750
  if (!parsed.success) {
343
751
  return undefined;
344
752
  }
345
753
  const event = parsed.data.event;
346
- const member = parsed.data.authorizations?.[0]?.user_id ?? undefined;
754
+ const installed = parsed.data.authorizations?.[0];
755
+ const member = installed?.user_id ?? undefined;
347
756
  if (
348
757
  event === undefined ||
349
758
  (event.type !== "message" && event.type !== "app_mention") ||
@@ -382,34 +791,802 @@ export function slackWakeOf(
382
791
  return undefined;
383
792
  }
384
793
  const thread = event.thread_ts ?? event.ts;
385
- // Carried without what the console takes in no text, a character that does not show say: with
386
- // one left in, the console would refuse the wake whole, and what was said would be lost.
387
- const words = withoutForbiddenCodePoints(wordsOf(event), true);
388
- // A cut is said in the source's own line, with the message to read whole by its moment: said
389
- // after the words, it would read as theirs.
390
- const cut =
391
- words.length > MAX_WAKE_TEXT
392
- ? ` (cut in this wake after ${MAX_WAKE_TEXT} of its ${words.length} characters: read the message ${event.ts} whole with the messenger's own tool)`
393
- : "";
394
794
  // A message of a conversation outside any thread is said as one: named a thread, it is answered
395
795
  // in one, where whoever wrote it reads the conversation itself.
396
- const said = direct
796
+ const where = direct
397
797
  ? "A direct message at Slack"
398
798
  : group
399
799
  ? "A message in a group conversation at Slack"
400
800
  : undefined;
401
- const where =
402
- said === undefined
403
- ? `${mentioned ? "A mention" : called !== undefined ? `A call of everyone (@${called})` : "A message"} in the channel ${event.channel} at Slack, from the member ${event.user}, in the thread ${thread}`
404
- : event.thread_ts === undefined
405
- ? `${said}, from the member ${event.user}, in the conversation ${event.channel}`
406
- : `${said}, from the member ${event.user}, in the thread ${thread} of the conversation ${event.channel}`;
801
+ const own = [installed?.team_id, installed?.enterprise_id].map(workspaceOf);
802
+ // A conversation shared with another organization is said to be one, whoever wrote in it:
803
+ // what is said there, people outside read.
804
+ const shared = parsed.data.is_ext_shared_channel === true ? "externally shared " : "";
805
+ const whole = saidOf(event);
806
+ const saying = (who: Who): readonly WakePart[] => {
807
+ const from = `from ${writerOf(event, own, who)}`;
808
+ const first =
809
+ where === undefined
810
+ ? `${mentioned ? "A mention" : called !== undefined ? `A call of everyone (@${called})` : "A message"} in the ${shared}channel ${event.channel} at Slack, ${from}, in the thread ${thread}`
811
+ : event.thread_ts === undefined
812
+ ? `${where}, ${from}, in the ${shared}conversation ${event.channel}`
813
+ : `${where}, ${from}, in the thread ${thread} of the ${shared}conversation ${event.channel}`;
814
+ // A cut is said in the source's own line, with the message to read whole by its moment: said
815
+ // after the words, it would read as theirs.
816
+ const carried = (most: number): WakePart[] => {
817
+ const said = carriedOf(whole, most);
818
+ const cut =
819
+ said.length > most
820
+ ? ` (cut in this wake after ${most} of its ${said.length} characters: read the message ${event.ts} whole with the messenger's own tool)`
821
+ : "";
822
+ return [{ says: `${first}${cut}` }, ...partsOf(said)];
823
+ };
824
+ // So much of the message as a wake carries, and less where its lines are so many that, begun
825
+ // as a signal's text begins them, they would leave no room for anything else.
826
+ let most = MAX_WAKE_TEXT;
827
+ let parts = carried(most);
828
+ while (most > 250 && wakeTextOf(parts, Number.MAX_SAFE_INTEGER).length > MAX_LEAD_LENGTH) {
829
+ most = Math.floor(most / 2);
830
+ parts = carried(most);
831
+ }
832
+ return parts;
833
+ };
407
834
  return {
408
835
  key: `slack:${event.channel}:${thread}`,
409
- text: `${where}${cut}:\n${cut === "" ? words : `${firstOf(words, MAX_WAKE_TEXT)}…`}`,
836
+ saying,
837
+ channel: event.channel,
838
+ ts: event.ts,
839
+ thread: event.thread_ts,
840
+ user: event.user,
841
+ member,
842
+ direct,
843
+ group,
844
+ own,
845
+ from: {
846
+ user: event.user,
847
+ bot_id: event.bot_id,
848
+ team: event.team,
849
+ user_team: event.user_team,
850
+ },
410
851
  };
411
852
  }
412
853
 
854
+ /**
855
+ * The wake an event of the messenger means, with nothing read of the conversation it was said
856
+ * in, or nothing where the event wakes nobody (`heardOf`): its key, and its parts, the line of
857
+ * the source's own first, then the message's words, then what hangs under the message, each
858
+ * behind a line that says what it is.
859
+ */
860
+ export function slackWakeOf(
861
+ payload: unknown,
862
+ channels: readonly string[] = [],
863
+ ): SlackWake | undefined {
864
+ const heard = heardOf(payload, channels);
865
+ return heard === undefined ? undefined : { key: heard.key, parts: heard.saying(NOBODY) };
866
+ }
867
+
868
+ /** Whether one moment of the messenger's is before another: by the seconds, then by the counter. */
869
+ function before(one: string, other: string): boolean {
870
+ const [seconds = "", counter = ""] = one.split(".");
871
+ const [otherSeconds = "", otherCounter = ""] = other.split(".");
872
+ return Number(seconds) === Number(otherSeconds)
873
+ ? counter.padEnd(9, "0") < otherCounter.padEnd(9, "0")
874
+ : Number(seconds) < Number(otherSeconds);
875
+ }
876
+
877
+ /** A stretch of time as a line says it: whole seconds, minutes, hours or days, one at the least. */
878
+ function stretchOf(seconds: number): string {
879
+ const counted = (count: number, word: string): string =>
880
+ `${count} ${word}${count === 1 ? "" : "s"}`;
881
+ if (seconds < 60) {
882
+ return counted(Math.max(1, Math.floor(seconds)), "second");
883
+ }
884
+ if (seconds < 3600) {
885
+ return counted(Math.floor(seconds / 60), "minute");
886
+ }
887
+ return seconds < 86_400
888
+ ? counted(Math.floor(seconds / 3600), "hour")
889
+ : counted(Math.floor(seconds / 86_400), "day");
890
+ }
891
+
892
+ /** The seconds of a moment of the messenger's. */
893
+ const secondsOf = (moment: string): number => Number(moment.split(".")[0]);
894
+
895
+ /** What a read of a conversation came to: its messages that are someone's words, the oldest first, and whether there are more before them; or why none. */
896
+ type Read =
897
+ | { readonly ok: true; readonly messages: readonly HeardMessage[]; readonly more: boolean }
898
+ | { readonly ok: false; readonly why: string };
899
+
900
+ /** A short name of why a read came to nothing, as the messenger spells its errors; `refused` for anything else. */
901
+ const whyOf = (error: string | undefined): string =>
902
+ error !== undefined && /^[a-z_]{1,60}$/.test(error) ? error : "refused";
903
+
904
+ /**
905
+ * Whether a message a read answered is someone's words: a plain one, one with a file, a reply
906
+ * sent to its conversation too, each with the member that wrote it, and what an app posted in
907
+ * nobody's name. A join, an edit and a message that does not read are none.
908
+ */
909
+ function wordsOfSomeone(message: unknown): HeardMessage | undefined {
910
+ const parsed = heardSchema.safeParse(message);
911
+ if (!parsed.success) {
912
+ return undefined;
913
+ }
914
+ const one = parsed.data;
915
+ return (WORDS_OF_SOMEONE.includes(one.subtype) && one.user !== undefined) ||
916
+ (one.subtype === "bot_message" && one.bot_id !== undefined)
917
+ ? one
918
+ : undefined;
919
+ }
920
+
921
+ /**
922
+ * Does what one wake reads, all of it within one wait: the signal handed to the work ends once
923
+ * the wait is over (`no_answer`), or before that with the one given, and what is asked under it
924
+ * comes to nothing then. Where the one given has ended already, nothing is asked at all.
925
+ */
926
+ async function within<T>(
927
+ host: Pick<WakeHost, "wait">,
928
+ signal: AbortSignal,
929
+ read: (until: AbortSignal) => Promise<T>,
930
+ ): Promise<T> {
931
+ const control = new AbortController();
932
+ const stop = (): void => control.abort(signal.reason);
933
+ if (signal.aborted) {
934
+ stop();
935
+ } else {
936
+ signal.addEventListener("abort", stop, { once: true });
937
+ void host.wait(READ_WAIT_MS, control.signal).then(() => control.abort("no_answer"));
938
+ }
939
+ try {
940
+ return await read(control.signal);
941
+ } finally {
942
+ control.abort();
943
+ signal.removeEventListener("abort", stop);
944
+ }
945
+ }
946
+
947
+ /**
948
+ * Asks the messenger for a page of a conversation, with the member's own token in the
949
+ * `authorization` header and what is asked in the address, where no token ever is. Waited for
950
+ * until the signal ends and no longer: a wake is not held back for a messenger that does not
951
+ * answer.
952
+ */
953
+ async function pageOf(
954
+ host: Pick<WakeHost, "fetch">,
955
+ token: string,
956
+ url: string,
957
+ asked: Readonly<Record<string, string>>,
958
+ until: AbortSignal,
959
+ ): Promise<
960
+ | {
961
+ readonly ok: true;
962
+ readonly messages: readonly unknown[];
963
+ /** Whether there are more than these, and what the next page is asked for with, where the messenger says. */
964
+ readonly more: boolean;
965
+ readonly cursor: string | undefined;
966
+ }
967
+ | { readonly ok: false; readonly why: string }
968
+ > {
969
+ if (until.aborted) {
970
+ return { ok: false, why: endedBy(until) };
971
+ }
972
+ try {
973
+ const answered = await unlessEnded(
974
+ until,
975
+ host
976
+ .fetch(`${url}?${new URLSearchParams(asked).toString()}`, {
977
+ method: "GET",
978
+ headers: { authorization: `Bearer ${token}` },
979
+ signal: until,
980
+ })
981
+ .then((answered) => answered.json()),
982
+ );
983
+ if (answered === ENDED) {
984
+ return { ok: false, why: endedBy(until) };
985
+ }
986
+ const parsed = readSchema.safeParse(answered);
987
+ if (!parsed.success) {
988
+ return { ok: false, why: "unreadable" };
989
+ }
990
+ if (!parsed.data.ok) {
991
+ return { ok: false, why: whyOf(parsed.data.error) };
992
+ }
993
+ const meta = parsed.data.response_metadata;
994
+ const cursor = isObject(meta) ? textOf(meta.next_cursor) : undefined;
995
+ return {
996
+ ok: true,
997
+ messages: parsed.data.messages ?? [],
998
+ more: parsed.data.has_more === true,
999
+ cursor: cursor === undefined || cursor === "" || cursor.length > 1000 ? undefined : cursor,
1000
+ };
1001
+ } catch {
1002
+ return { ok: false, why: until.aborted ? endedBy(until) : "failed" };
1003
+ }
1004
+ }
1005
+
1006
+ /** The messages of a read that are someone's words, the oldest first, each once. */
1007
+ function inOrder(messages: readonly unknown[]): HeardMessage[] {
1008
+ const read = new Map<string, HeardMessage>();
1009
+ for (const message of messages) {
1010
+ const one = wordsOfSomeone(message);
1011
+ if (one !== undefined) {
1012
+ read.set(one.ts, one);
1013
+ }
1014
+ }
1015
+ return [...read.values()].sort((one, other) =>
1016
+ before(one.ts, other.ts) ? -1 : before(other.ts, one.ts) ? 1 : 0,
1017
+ );
1018
+ }
1019
+
1020
+ /**
1021
+ * The latest of a conversation outside its threads: so many messages, before a moment where one
1022
+ * is given. The messenger answers them the newest first.
1023
+ */
1024
+ async function conversationOf(
1025
+ host: Pick<WakeHost, "fetch">,
1026
+ token: string,
1027
+ channel: string,
1028
+ asked: { readonly limit: number; readonly before?: string | undefined },
1029
+ until: AbortSignal,
1030
+ ): Promise<Read> {
1031
+ const page = await pageOf(
1032
+ host,
1033
+ token,
1034
+ HISTORY_URL,
1035
+ {
1036
+ channel,
1037
+ limit: String(asked.limit),
1038
+ ...(asked.before === undefined ? {} : { latest: asked.before, inclusive: "false" }),
1039
+ },
1040
+ until,
1041
+ );
1042
+ return page.ok ? { ok: true, messages: inOrder(page.messages), more: page.more } : page;
1043
+ }
1044
+
1045
+ /**
1046
+ * A thread: the messenger answers it the oldest first, the message that began it ahead of all, a
1047
+ * page at a time, so it is read to its end, or to as many pages as a read takes. Where a moment
1048
+ * is given, what is asked for is what was written after it: from the first page on, or past the
1049
+ * first page alone (`beginning`), which a long thread is read by without being read through,
1050
+ * and its first page says who writes there. `more` says that the thread goes on past what was
1051
+ * read, and so that its latest messages are not among them.
1052
+ */
1053
+ async function threadOf(
1054
+ host: Pick<WakeHost, "fetch">,
1055
+ token: string,
1056
+ channel: string,
1057
+ thread: string,
1058
+ from: { readonly after?: string | undefined; readonly beginning?: boolean },
1059
+ until: AbortSignal,
1060
+ ): Promise<Read> {
1061
+ const messages: unknown[] = [];
1062
+ const asked: Record<string, string> = {
1063
+ channel,
1064
+ ts: thread,
1065
+ limit: String(READ_THREAD_PAGE),
1066
+ ...(from.after === undefined || from.beginning === true ? {} : { oldest: from.after }),
1067
+ };
1068
+ for (let pages = 0; pages < READ_THREAD_PAGES; pages += 1) {
1069
+ const page = await pageOf(host, token, REPLIES_URL, asked, until);
1070
+ if (!page.ok) {
1071
+ return page;
1072
+ }
1073
+ messages.push(...page.messages);
1074
+ if (!page.more) {
1075
+ return { ok: true, messages: inOrder(messages), more: false };
1076
+ }
1077
+ if (from.after !== undefined && asked.oldest === undefined) {
1078
+ asked.oldest = from.after;
1079
+ } else if (page.cursor === undefined) {
1080
+ break;
1081
+ } else {
1082
+ asked.cursor = page.cursor;
1083
+ }
1084
+ }
1085
+ return { ok: true, messages: inOrder(messages), more: true };
1086
+ }
1087
+
1088
+ /** The command that reads on where a wake was raised: the conversation, or the thread in it. */
1089
+ const readWith = (channel: string, thread: string | undefined, after?: string): string =>
1090
+ `console agent messages slack:${channel}${thread === undefined ? "" : `:${thread}`}${after === undefined ? "" : ` --after ${after}`}`;
1091
+
1092
+ /**
1093
+ * A message said before the one that raised a wake, as the wake carries it: who wrote it and how
1094
+ * long before, in a line of the source's own, and its writer's own words, so much of them. What
1095
+ * hangs under it is marked in the words and not carried: the agent reads it with the command.
1096
+ */
1097
+ function earlierOf(
1098
+ message: HeardMessage,
1099
+ heard: Pick<Heard, "ts" | "own">,
1100
+ who: Who = NOBODY,
1101
+ ): readonly [WakePart, WakePart] {
1102
+ const said = saidOf(message);
1103
+ const words = [
1104
+ said.words,
1105
+ ...said.under.map((one) =>
1106
+ one.passedOn ? "[a message passed on, not carried in this wake]" : leftOut("attachment"),
1107
+ ),
1108
+ ]
1109
+ .filter((part) => part !== "")
1110
+ .join("\n");
1111
+ const cut =
1112
+ words.length > MAX_BEFORE_TEXT
1113
+ ? `, cut after ${MAX_BEFORE_TEXT} of its ${words.length} characters`
1114
+ : "";
1115
+ return [
1116
+ {
1117
+ says: `${stretchOf(secondsOf(heard.ts) - secondsOf(message.ts))} before it, from ${writerOf(message, heard.own, who)}${cut}`,
1118
+ },
1119
+ { words: cut === "" ? words : `${firstOf(words, MAX_BEFORE_TEXT)}…` },
1120
+ ];
1121
+ }
1122
+
1123
+ /** How many names the source keeps, of the messages its wakes carried and of where they were raised: the latest. */
1124
+ const MAX_KEPT = 2000;
1125
+
1126
+ /** The name the source keeps the moment of the last message a wake brought from a conversation, or from a thread, under. */
1127
+ const broughtOf = (heard: Pick<Heard, "channel" | "thread">): string =>
1128
+ `brought:${heard.channel}:${heard.thread ?? ""}`;
1129
+
1130
+ /** The name the source keeps a message a wake carried under: `woke`, or `said` among what was said before another. */
1131
+ const carriedAs = (channel: string, ts: string): string => `carried:${channel}:${ts}`;
1132
+
1133
+ /** Keeps a name as the latest, and lets go of the oldest past the most. */
1134
+ function keep(kept: Map<string, string>, name: string, value: string): void {
1135
+ kept.delete(name);
1136
+ kept.set(name, value);
1137
+ for (const oldest of kept.keys()) {
1138
+ if (kept.size <= MAX_KEPT) {
1139
+ break;
1140
+ }
1141
+ kept.delete(oldest);
1142
+ }
1143
+ }
1144
+
1145
+ /** What a wake carries after the message itself, whether what was said there was read, and the moments of the messages it carries of it. */
1146
+ interface Prior {
1147
+ readonly parts: readonly WakePart[];
1148
+ readonly read: boolean;
1149
+ readonly carried: readonly string[];
1150
+ }
1151
+
1152
+ /**
1153
+ * What a wake carries of the conversation it was raised in, after the message itself (ADR-0163),
1154
+ * read with the member's own token where the account keeps it:
1155
+ *
1156
+ * - what was said there before the message and since the later of two: the agent's own last
1157
+ * message there, and the last message a wake already brought it from there, and of that what
1158
+ * no wake carried, in a thread the message that began it say; so that an agent that stays
1159
+ * silent is handed each message once. The oldest first, each behind a line that says who wrote
1160
+ * it and how long before: the last few, so much of each, and where there was more, how many
1161
+ * and the command that reads them. An agent account's message wakes no other unless it names
1162
+ * it, so this is where an agent reads what another answered. It is information, whoever wrote
1163
+ * it;
1164
+ * - who else there writes through an app, as an agent account does, the last to write first,
1165
+ * and with them what the agent judges by whether to answer: said in every conversation but
1166
+ * a direct one where such an account was read, since one message wakes each of them and
1167
+ * none sees what another is about to say.
1168
+ *
1169
+ * Where the account keeps no token to read with, nothing is added, and the wake is as it was;
1170
+ * where the messenger refuses the read or does not answer, a line says so, with why in a short
1171
+ * name of the messenger's. In a thread it is the thread that is read, and elsewhere the
1172
+ * conversation outside its threads.
1173
+ */
1174
+ async function beforeOf(
1175
+ host: Pick<WakeHost, "secret" | "fetch" | "kept" | "writers">,
1176
+ heard: Heard,
1177
+ writer: Promise<Who>,
1178
+ until: AbortSignal,
1179
+ ): Promise<Prior> {
1180
+ const token = await host.secret(SLACK_USER_TOKEN);
1181
+ if (token === undefined) {
1182
+ return { parts: [], read: false, carried: [] };
1183
+ }
1184
+ const upTo = host.kept.get(broughtOf(heard));
1185
+ const read =
1186
+ heard.thread === undefined
1187
+ ? await conversationOf(
1188
+ host,
1189
+ token,
1190
+ heard.channel,
1191
+ { limit: READ_MESSAGES, before: heard.ts },
1192
+ until,
1193
+ )
1194
+ : await threadOf(
1195
+ host,
1196
+ token,
1197
+ heard.channel,
1198
+ heard.thread,
1199
+ { after: upTo, beginning: true },
1200
+ until,
1201
+ );
1202
+ const command = readWith(heard.channel, heard.thread);
1203
+ if (!read.ok) {
1204
+ return {
1205
+ parts: [{ says: `What was said there before it could not be read (${read.why})` }],
1206
+ read: false,
1207
+ carried: [],
1208
+ };
1209
+ }
1210
+ if (heard.thread !== undefined && read.more) {
1211
+ // Its latest messages are past what was read. The line says so, and the next wake there is
1212
+ // carried what was said after this message.
1213
+ return {
1214
+ parts: [
1215
+ {
1216
+ says: `The thread is longer than a wake reads, so what was said there before it is not carried: ${command}`,
1217
+ },
1218
+ ],
1219
+ read: true,
1220
+ carried: [],
1221
+ };
1222
+ }
1223
+ const earlier = read.messages.filter((message) => before(message.ts, heard.ts));
1224
+ // Who else writes there as an agent account does, the last to write first, the agent itself
1225
+ // in its place among them: the account that wrote the message is not woken by it.
1226
+ const writers: string[] = [];
1227
+ for (const message of earlier.toReversed()) {
1228
+ if (
1229
+ message.user !== undefined &&
1230
+ message.bot_id !== undefined &&
1231
+ message.user !== heard.user &&
1232
+ !writers.includes(message.user)
1233
+ ) {
1234
+ writers.push(message.user);
1235
+ }
1236
+ }
1237
+ const others = writers.filter((one) => one !== heard.member);
1238
+ // Where the event does not say which member it was delivered for, the agent's own account
1239
+ // cannot be told from another's, and nobody is named: it would be told to leave it to itself.
1240
+ const shown =
1241
+ heard.direct || heard.member === undefined || others.length === 0
1242
+ ? []
1243
+ : writers.slice(0, MAX_OTHERS + 1);
1244
+ const wrote =
1245
+ heard.member === undefined
1246
+ ? -1
1247
+ : earlier.findLastIndex((message) => message.user === heard.member);
1248
+ // What a wake already brought of this conversation, as the message that woke or among what
1249
+ // was said before it, is not carried again: the agent has it, whether or not it answered. Nor
1250
+ // is what a wake brought from elsewhere, the message that began this thread from its channel.
1251
+ const brought =
1252
+ upTo === undefined ? -1 : earlier.findLastIndex((message) => !before(upTo, message.ts));
1253
+ const last = Math.max(wrote, brought);
1254
+ const since = earlier
1255
+ .slice(last + 1)
1256
+ .filter((message) => !host.kept.has(carriedAs(heard.channel, message.ts)));
1257
+ const latest = since.toReversed().slice(0, MAX_BEFORE);
1258
+ // Who wrote each, as the console says it (ADR-0164), asked at once for all whose account is
1259
+ // another than that of the message that woke, which is asked of beside the read: said of an
1260
+ // earlier message as of the one that woke, and information all the same, whoever wrote it;
1261
+ // and said of each of the others named, by a message of theirs, since how one stands to the
1262
+ // agent, a supervisor of its own say, is among what it judges by whether to answer.
1263
+ const theirs = new Map<string, Written>();
1264
+ for (const one of shown) {
1265
+ const written = earlier.findLast(
1266
+ (message) => message.user === one && message.bot_id !== undefined,
1267
+ );
1268
+ if (one !== heard.member && written !== undefined) {
1269
+ theirs.set(one, written);
1270
+ }
1271
+ }
1272
+ const first = await writer;
1273
+ const known = accountOf(heard.from);
1274
+ const rest = await whoOf(
1275
+ host,
1276
+ [...latest, ...theirs.values()].filter((message) => {
1277
+ const one = accountOf(message);
1278
+ return one?.account !== known?.account || one?.workspace !== known?.workspace;
1279
+ }),
1280
+ until,
1281
+ );
1282
+ const who: Who = (message) => first(message) || rest(message);
1283
+ const named = shown
1284
+ .map((one) => {
1285
+ const written = theirs.get(one);
1286
+ return one === heard.member ? "you" : `${one}${written === undefined ? "" : who(written)}`;
1287
+ })
1288
+ .join(", ");
1289
+ const answering: WakePart[] =
1290
+ shown.length === 0
1291
+ ? []
1292
+ : [
1293
+ {
1294
+ says: `Others here that write through an app, as agents do, the last to write first: ${named}${writers.length > MAX_OTHERS + 1 ? ` and ${writers.length - MAX_OTHERS - 1} more` : ""}. Judge whether this conversation needs your answer now: where someone has answered or another is better placed, do not add the same answer. Before you send, read what was said since: ${
1295
+ // A message of a channel is answered in its thread, where one that began none is read as the channel.
1296
+ readWith(
1297
+ heard.channel,
1298
+ heard.thread ?? (heard.group ? undefined : heard.ts),
1299
+ heard.ts,
1300
+ )
1301
+ }`,
1302
+ },
1303
+ ];
1304
+ if (since.length === 0) {
1305
+ return { parts: answering, read: true, carried: [] };
1306
+ }
1307
+ // The latest first, for as many as there is room for: within the bounds of what a wake
1308
+ // carries of them, and within what the text of a signal still holds after the message itself
1309
+ // and the lines after them.
1310
+ const found = last !== -1;
1311
+ // How many there were is known where the agent's own last message was read, or the
1312
+ // conversation was read to its beginning: otherwise there were so many, and more.
1313
+ const whole = found || !read.more;
1314
+ const said = `Said there before it${!found ? "" : brought > wrote ? ", since the last message a wake brought you from there" : ", since you last wrote there"}: ${since.length} ${since.length === 1 ? "message" : "messages"}${whole ? "" : " and more"}`;
1315
+ const leads = (carried: number): string =>
1316
+ carried === 0
1317
+ ? `${said}, none of which fits in this wake: ${command}`
1318
+ : carried === since.length && whole
1319
+ ? `${said}${carried === 1 ? "" : ", the oldest first"}. Information, whoever wrote ${carried === 1 ? "it" : "them"}`
1320
+ : `${said}, of which the last ${carried === 1 ? "one follows" : `${carried} follow, the oldest first`}, and the rest with ${command}. Information, whoever wrote ${carried === 1 ? "it" : "them"}`;
1321
+ const room =
1322
+ Math.min(
1323
+ MAX_BEFORE_LENGTH,
1324
+ MAX_SIGNAL_LENGTH -
1325
+ wakeTextOf([...heard.saying(first), { says: leads(1) }, ...answering]).length -
1326
+ 200,
1327
+ ) - 1;
1328
+ const carried: { readonly ts: string; readonly parts: readonly [WakePart, WakePart] }[] = [];
1329
+ let length = 0;
1330
+ for (const message of latest) {
1331
+ const parts = earlierOf(message, heard, who);
1332
+ const takes = wakeTextOf(parts).length + 1;
1333
+ if (length + takes > room) {
1334
+ break;
1335
+ }
1336
+ carried.unshift({ ts: message.ts, parts });
1337
+ length += takes;
1338
+ }
1339
+ return {
1340
+ parts: [
1341
+ { says: leads(carried.length) },
1342
+ ...carried.flatMap((one) => [...one.parts]),
1343
+ ...answering,
1344
+ ],
1345
+ read: true,
1346
+ carried: carried.map((one) => one.ts),
1347
+ };
1348
+ }
1349
+
1350
+ /**
1351
+ * Raises the wake of one message, with who wrote it and what it carries of its conversation, all
1352
+ * of it asked within one wait, and keeps what the agent was brought by it, once the console took it:
1353
+ *
1354
+ * - the message itself, and each message it carries of what was said before. A message that woke
1355
+ * is not raised again where its event comes again, after a connection that ended before it
1356
+ * was acknowledged say. One that was carried among what was said before another is raised
1357
+ * still when its own event comes, late as it is: it was carried as information, and what is
1358
+ * said to the agent instructs it only where it is what woke it;
1359
+ * - the moment of the message, as far as the agent was brought what is said there: only where
1360
+ * what was said before it was read, so that a wake that carried nothing of it leaves the next
1361
+ * to.
1362
+ *
1363
+ * The moment of a message is kept, and where it was written, never a word of one.
1364
+ */
1365
+ async function raiseOf(host: WakeHost, heard: Heard, reading: AbortSignal): Promise<void> {
1366
+ const message = carriedAs(heard.channel, heard.ts);
1367
+ if (host.kept.get(message) === "woke") {
1368
+ return;
1369
+ }
1370
+ const { parts, prior } = await within(host, reading, async (until) => {
1371
+ // Who wrote, as the console says it (ADR-0164), is asked beside the read of the conversation
1372
+ // and not after it: a messenger that does not answer costs the wake's first line nothing.
1373
+ const writer = whoOf(host, [heard.from], until);
1374
+ // A read that fails in a way of its own costs the wake nothing: it goes as it stands.
1375
+ const prior = await beforeOf(host, heard, writer, until).catch(
1376
+ (): Prior => ({
1377
+ parts: [{ says: "What was said there before it could not be read (failed)" }],
1378
+ read: false,
1379
+ carried: [],
1380
+ }),
1381
+ );
1382
+ return { parts: heard.saying(await writer), prior };
1383
+ });
1384
+ const taken = await host
1385
+ .raise({ key: heard.key, parts: [...parts, ...prior.parts] })
1386
+ .catch((error: unknown) => {
1387
+ host.log(
1388
+ `a wake from slack was not raised (${error instanceof Error ? error.name : "error"})`,
1389
+ );
1390
+ return false;
1391
+ });
1392
+ if (!taken) {
1393
+ return;
1394
+ }
1395
+ for (const ts of prior.carried) {
1396
+ keep(host.kept, carriedAs(heard.channel, ts), "said");
1397
+ }
1398
+ keep(host.kept, message, "woke");
1399
+ if (prior.read) {
1400
+ const place = broughtOf(heard);
1401
+ const was = host.kept.get(place);
1402
+ keep(host.kept, place, was !== undefined && before(heard.ts, was) ? was : heard.ts);
1403
+ }
1404
+ }
1405
+
1406
+ /** Where a read is asked for, as a wake's key names it after the source's name: the conversation, and the thread in it. */
1407
+ const NAMED = /^([A-Z0-9]{1,24})(?::([0-9]{1,12}\.[0-9]{1,9}))?$/;
1408
+
1409
+ /**
1410
+ * The latest of what was said in a conversation or in a thread of one, for the account's own
1411
+ * command: each message behind a line of the source's own that says how long ago it was
1412
+ * written, by whom and under which moment, its words as a wake carries them and what hangs
1413
+ * under it apart. After a moment alone, where one is given. Named as a wake's key names it,
1414
+ * `<conversation>` or `<conversation>:<thread>`; a thread that is none, the message of a wake
1415
+ * that was written in no thread, is read as its conversation. So much of it all together, the
1416
+ * newest kept, and the first line says how many were left out.
1417
+ */
1418
+ async function readOf(
1419
+ host: Pick<WakeHost, "secret" | "fetch" | "writers">,
1420
+ where: string,
1421
+ options: Parameters<NonNullable<WakeSource["read"]>>[2],
1422
+ ): Promise<WakeRead> {
1423
+ const named = NAMED.exec(where);
1424
+ const channel = named?.[1];
1425
+ if (channel === undefined) {
1426
+ return { ok: false, why: "not_a_conversation" };
1427
+ }
1428
+ const after = options.after;
1429
+ if (after !== undefined && !stamp.safeParse(after).success) {
1430
+ return { ok: false, why: "not_a_moment" };
1431
+ }
1432
+ const token = await host.secret(SLACK_USER_TOKEN);
1433
+ if (token === undefined) {
1434
+ return { ok: false, why: "no_token" };
1435
+ }
1436
+ const limit = Math.min(
1437
+ Math.max(Math.trunc(options.limit ?? SLACK_READ_DEFAULT), 1),
1438
+ SLACK_READ_MOST,
1439
+ );
1440
+ let thread = named?.[2];
1441
+ let read =
1442
+ thread === undefined
1443
+ ? await conversationOf(host, token, channel, { limit }, options.signal)
1444
+ : await threadOf(host, token, channel, thread, { after }, options.signal);
1445
+ // A message that began no thread is all a read of its thread answers: what is asked for is
1446
+ // then what was said around it, in its conversation.
1447
+ if (
1448
+ thread !== undefined &&
1449
+ read.ok &&
1450
+ read.messages.length <= 1 &&
1451
+ read.messages[0]?.thread_ts === undefined
1452
+ ) {
1453
+ thread = undefined;
1454
+ read = await conversationOf(host, token, channel, { limit }, options.signal);
1455
+ }
1456
+ if (!read.ok) {
1457
+ return read;
1458
+ }
1459
+ const said =
1460
+ after === undefined
1461
+ ? read.messages
1462
+ : read.messages.filter((message) => before(after, message.ts));
1463
+ const latest = said.slice(-limit);
1464
+ const now = Math.floor(options.now / 1000);
1465
+ const who = await whoOf(host, latest, options.signal);
1466
+ // The newest first, for as long as there is room: the oldest are what is left out.
1467
+ const shown: WakePart[][] = [];
1468
+ let length = 0;
1469
+ for (const message of latest.toReversed()) {
1470
+ const carried = carriedOf(saidOf(message), MAX_WAKE_TEXT);
1471
+ const parts: WakePart[] = [
1472
+ {
1473
+ says: `${stretchOf(Math.max(0, now - secondsOf(message.ts)))} ago, from ${writerOf(message, [], who)}, the message ${message.ts}${
1474
+ carried.length > MAX_WAKE_TEXT
1475
+ ? ` (cut after ${MAX_WAKE_TEXT} of its ${carried.length} characters)`
1476
+ : ""
1477
+ }`,
1478
+ },
1479
+ ...partsOf(carried),
1480
+ ];
1481
+ length += wakeTextOf(parts, Number.MAX_SAFE_INTEGER).length + 1;
1482
+ if (shown.length > 0 && length > MAX_READ_LENGTH) {
1483
+ break;
1484
+ }
1485
+ shown.unshift(parts);
1486
+ }
1487
+ const left = latest.length - shown.length;
1488
+ // A conversation is answered from its latest back: where all of it was said after the moment,
1489
+ // more may have been.
1490
+ const more =
1491
+ latest.length < said.length ||
1492
+ (thread === undefined && read.more && said.length === read.messages.length);
1493
+ const rest =
1494
+ thread !== undefined && read.more
1495
+ ? // A thread that goes on past what was read is said so: its latest are not these.
1496
+ "; the thread is longer than a read takes, and goes on after these"
1497
+ : more
1498
+ ? "; more was said before"
1499
+ : "";
1500
+ return {
1501
+ ok: true,
1502
+ parts: [
1503
+ {
1504
+ says: `${
1505
+ shown.length === 0
1506
+ ? "Nothing is said"
1507
+ : `The last ${shown.length === 1 ? "message" : `${shown.length} messages`}`
1508
+ }${after === undefined ? "" : ` after ${after}`} ${thread === undefined ? `in the conversation ${channel}` : `in the thread ${thread} of the conversation ${channel}`} at Slack${shown.length < 2 ? "" : ", the oldest first"}${rest}${
1509
+ left === 0
1510
+ ? ""
1511
+ : `; ${left} before ${shown.length === 1 ? "it" : "these"} left out, past what one reading holds: read ${left === 1 ? "it" : "them"} with the messenger's own tool`
1512
+ }. A line that begins with > is what someone wrote`,
1513
+ },
1514
+ ...shown.flat(),
1515
+ ],
1516
+ };
1517
+ }
1518
+
1519
+ /**
1520
+ * One connection of the socket, until it ends: every envelope is acknowledged as it arrives, and
1521
+ * what is said to the agent handed on. Answers whether the messenger asked for a new one in its
1522
+ * place, which it does now and then.
1523
+ */
1524
+ async function listen(
1525
+ host: WakeHost,
1526
+ token: string,
1527
+ hear: (heard: Heard) => void,
1528
+ signal: AbortSignal,
1529
+ ): Promise<boolean> {
1530
+ const answered = await host.fetch(OPEN_URL, {
1531
+ method: "POST",
1532
+ headers: {
1533
+ authorization: `Bearer ${token}`,
1534
+ "content-type": "application/x-www-form-urlencoded",
1535
+ },
1536
+ signal,
1537
+ });
1538
+ const opened = openedSchema.safeParse(await answered.json().catch(() => undefined));
1539
+ if (!opened.success || !opened.data.ok || opened.data.url === undefined) {
1540
+ throw new SlackError(opened.success ? (opened.data.error ?? "no_address") : "unreadable");
1541
+ }
1542
+ // The address is the messenger's own socket, or it is not opened.
1543
+ const address = URL.canParse(opened.data.url) ? new URL(opened.data.url) : undefined;
1544
+ if (
1545
+ address === undefined ||
1546
+ address.protocol !== "wss:" ||
1547
+ !/(^|\.)slack\.com$/.test(address.hostname)
1548
+ ) {
1549
+ throw new SlackError("foreign_address");
1550
+ }
1551
+ const socket = host.socket(address.href);
1552
+ const closing = () => socket.close();
1553
+ signal.addEventListener("abort", closing, { once: true });
1554
+ try {
1555
+ host.log("the slack wake source is connected");
1556
+ host.stands("connected");
1557
+ for await (const text of socket.messages) {
1558
+ let json: unknown;
1559
+ try {
1560
+ json = JSON.parse(text);
1561
+ } catch {
1562
+ continue;
1563
+ }
1564
+ const envelope = envelopeSchema.safeParse(json);
1565
+ if (!envelope.success) {
1566
+ continue;
1567
+ }
1568
+ if (envelope.data.type === "disconnect") {
1569
+ return true;
1570
+ }
1571
+ // Acknowledged first, whatever it holds: an event nobody acknowledged is sent again.
1572
+ if (envelope.data.envelope_id !== undefined) {
1573
+ socket.send(JSON.stringify({ envelope_id: envelope.data.envelope_id }));
1574
+ }
1575
+ if (envelope.data.type !== "events_api") {
1576
+ continue;
1577
+ }
1578
+ const heard = heardOf(envelope.data.payload, host.channels);
1579
+ if (heard !== undefined) {
1580
+ hear(heard);
1581
+ }
1582
+ }
1583
+ return false;
1584
+ } finally {
1585
+ signal.removeEventListener("abort", closing);
1586
+ socket.close();
1587
+ }
1588
+ }
1589
+
413
1590
  export const slack: WakeSource = {
414
1591
  name: "slack",
415
1592
  async run(host: WakeHost, signal: AbortSignal): Promise<void> {
@@ -420,68 +1597,40 @@ export const slack: WakeSource = {
420
1597
  await host.wait(NO_TOKEN_WAIT_MS, signal);
421
1598
  return;
422
1599
  }
423
- const answered = await host.fetch(OPEN_URL, {
424
- method: "POST",
425
- headers: {
426
- authorization: `Bearer ${token}`,
427
- "content-type": "application/x-www-form-urlencoded",
428
- },
429
- signal,
430
- });
431
- const opened = openedSchema.safeParse(await answered.json().catch(() => undefined));
432
- if (!opened.success || !opened.data.ok || opened.data.url === undefined) {
433
- throw new SlackError(opened.success ? (opened.data.error ?? "no_address") : "unreadable");
434
- }
435
- // The address is the messenger's own socket, or it is not opened.
436
- const address = URL.canParse(opened.data.url) ? new URL(opened.data.url) : undefined;
437
- if (
438
- address === undefined ||
439
- address.protocol !== "wss:" ||
440
- !/(^|\.)slack\.com$/.test(address.hostname)
441
- ) {
442
- throw new SlackError("foreign_address");
443
- }
444
- const socket = host.socket(address.href);
445
- const closing = () => socket.close();
446
- signal.addEventListener("abort", closing, { once: true });
1600
+ // What is raised, one wake after another in the order the events arrived: the conversation
1601
+ // is read for each before it is raised, and the socket is not kept waiting for that, since
1602
+ // an event that is not acknowledged within a few seconds is sent again. Where too many
1603
+ // wait, the one whose turn it is goes with nothing read: the latest say what was said before.
1604
+ const reading = new AbortController();
1605
+ let raising: Promise<void> = Promise.resolve();
1606
+ let waiting = 0;
1607
+ const hear = (heard: Heard): void => {
1608
+ waiting += 1;
1609
+ raising = raising.then(() => {
1610
+ waiting -= 1;
1611
+ return raiseOf(
1612
+ host,
1613
+ heard,
1614
+ waiting > MAX_WAITING ? AbortSignal.abort("too_many_waiting") : reading.signal,
1615
+ );
1616
+ });
1617
+ };
447
1618
  try {
448
- host.log("the slack wake source is connected");
449
- host.stands("connected");
450
- for await (const text of socket.messages) {
451
- let json: unknown;
452
- try {
453
- json = JSON.parse(text);
454
- } catch {
455
- continue;
456
- }
457
- const envelope = envelopeSchema.safeParse(json);
458
- if (!envelope.success) {
459
- continue;
460
- }
461
- // The messenger asks for a new connection now and then: this one ends, and the runner
462
- // starts the source again.
463
- if (envelope.data.type === "disconnect") {
1619
+ // The messenger asks for a new connection now and then: it is opened with what is still
1620
+ // being raised carried over, which nothing of it waits for.
1621
+ while (await listen(host, token, hear, signal)) {
1622
+ host.stands("waiting");
1623
+ await host.wait(REOPEN_WAIT_MS, signal);
1624
+ if (signal.aborted) {
464
1625
  return;
465
1626
  }
466
- // Acknowledged first, whatever it holds: an event nobody acknowledged is sent again.
467
- if (envelope.data.envelope_id !== undefined) {
468
- socket.send(JSON.stringify({ envelope_id: envelope.data.envelope_id }));
469
- }
470
- if (envelope.data.type !== "events_api") {
471
- continue;
472
- }
473
- const wake = slackWakeOf(envelope.data.payload, host.channels);
474
- if (wake !== undefined) {
475
- await host.raise(wake).catch((error: unknown) => {
476
- host.log(
477
- `a wake from slack was not raised (${error instanceof Error ? error.name : "error"})`,
478
- );
479
- });
480
- }
481
1627
  }
482
1628
  } finally {
483
- signal.removeEventListener("abort", closing);
484
- socket.close();
1629
+ // What was heard before the source ended is raised still, with nothing more read for it:
1630
+ // neither the next connection nor a stop of the runner waits for a messenger to answer.
1631
+ reading.abort("stopped");
1632
+ await raising;
485
1633
  }
486
1634
  },
1635
+ read: (host, where, options) => readOf(host, where, options),
487
1636
  };