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