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