@skillcdn/console 0.6.0 → 0.6.2

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