@desplega.ai/agent-swarm 2.7.9 → 2.8.0

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 (355) hide show
  1. package/dist/acp-adapter-t949vbbp.js +15 -0
  2. package/dist/{actions-g563mbn2.js → actions-7e9czc7s.js} +19 -19
  3. package/dist/{amp-adapter-q61w05eb.js → amp-adapter-gv6cbb7d.js} +2 -3
  4. package/dist/app-b9fbkp9v.js +20 -0
  5. package/dist/{assistant-p477rjwj.js → assistant-wjb7v4c7.js} +22 -22
  6. package/dist/{boot-args-schema-h4qj462e.js → boot-args-schema-2t37e0fe.js} +1 -1
  7. package/dist/{boot-reembed-n1ehfbsw.js → boot-reembed-a35nkyr1.js} +1 -1
  8. package/dist/{boot-reembed-qw4mc0pt.js → boot-reembed-gka3zas7.js} +1 -1
  9. package/dist/{boot-scrub-sweep-9w9jp4sm.js → boot-scrub-sweep-65sdnp6c.js} +3 -3
  10. package/dist/{boot-seeds-qdaf3sdy.js → boot-seeds-x42tzytw.js} +4 -5
  11. package/dist/{claude-adapter-348p5hx9.js → claude-adapter-v221b2fd.js} +7 -8
  12. package/dist/{claude-managed-adapter-h74d06yz.js → claude-managed-adapter-29eq09wd.js} +2 -2
  13. package/dist/{claude-managed-setup-7787fxtp.js → claude-managed-setup-9m6450zk.js} +2 -2
  14. package/dist/{claude-sdk-session-hbszbt8a.js → claude-sdk-session-0q0ptaba.js} +9066 -8818
  15. package/dist/{cli-n5yexkdg.js → cli-0b4zam62.js} +1 -0
  16. package/dist/{cli-21159vea.js → cli-0jzra9ad.js} +2 -2
  17. package/dist/{cli-eqtfgfr6.js → cli-2gxeg5gr.js} +1 -1
  18. package/dist/{cli-k70e3x9e.js → cli-2wnq8jkz.js} +9 -9
  19. package/dist/{cli-cvs2r2vq.js → cli-2zp0et3v.js} +59 -6
  20. package/dist/{cli-650zv9q9.js → cli-334z18y3.js} +4 -4
  21. package/dist/{cli-12xyjhws.js → cli-3rkdne1h.js} +2 -2
  22. package/dist/{cli-2a8py3sx.js → cli-4txa0ter.js} +5 -7
  23. package/dist/{cli-jc1g9ndz.js → cli-5j88qqa8.js} +10 -5
  24. package/dist/{cli-xfjrc279.js → cli-5mrq3ake.js} +48 -14
  25. package/dist/{cli-v3cf1ts9.js → cli-6t09sdhy.js} +3 -3
  26. package/dist/{cli-qzt90yze.js → cli-6wxjceza.js} +8 -8
  27. package/dist/{cli-9aezs55w.js → cli-7b8sbmag.js} +8 -8
  28. package/dist/{cli-3xj33nrx.js → cli-7cp6aa1q.js} +10 -3
  29. package/dist/{cli-jfx48xrj.js → cli-7p1kvkck.js} +6 -6
  30. package/dist/{cli-b932gexn.js → cli-8aes17e4.js} +2 -2
  31. package/dist/{cli-3tqcamp6.js → cli-8fknbnhw.js} +14 -13
  32. package/dist/{cli-587857ys.js → cli-8kzasymh.js} +3 -3
  33. package/dist/{cli-sgs5k6yd.js → cli-a7wvp2km.js} +1 -1
  34. package/dist/{cli-varqt4d1.js → cli-abejgen1.js} +69 -22
  35. package/dist/{cli-rwymrnaz.js → cli-bsywb58a.js} +8 -8
  36. package/dist/{cli-btc9cb4c.js → cli-c55z5chy.js} +4 -6
  37. package/dist/{cli-ms5m5r1y.js → cli-deefvewm.js} +1 -1
  38. package/dist/{cli-p17970qv.js → cli-ee0b971j.js} +3 -3
  39. package/dist/cli-f3vq58d2.js +242 -0
  40. package/dist/{cli-3xcwp3z8.js → cli-ffhtssbp.js} +2 -2
  41. package/dist/{cli-hwprv9e4.js → cli-g70vxtjh.js} +2 -2
  42. package/dist/{cli-4t0fmf3z.js → cli-gxkx0zzp.js} +1 -1
  43. package/dist/{cli-neyag5p6.js → cli-h38x262p.js} +3365 -429
  44. package/dist/{cli-2ccpqyyf.js → cli-j790gp2w.js} +105 -22
  45. package/dist/{cli-f2zenhja.js → cli-kc7v1nfv.js} +1 -1
  46. package/dist/{cli-vxh6acp7.js → cli-m23zjcy2.js} +10 -10
  47. package/dist/{cli-y8nbefpb.js → cli-m28atx8q.js} +12 -10
  48. package/dist/{cli-serm8zrx.js → cli-m4dqmnbp.js} +1 -1
  49. package/dist/{cli-ybjdc978.js → cli-mrt48bx7.js} +7 -4
  50. package/dist/{cli-y5rbvxhc.js → cli-n515ex5z.js} +14 -14
  51. package/dist/{cli-ypff1qwp.js → cli-n9ftpys4.js} +7 -7
  52. package/dist/{cli-605nn699.js → cli-p1bq50aa.js} +894 -226
  53. package/dist/{cli-qkdmz8c8.js → cli-p1w18yhx.js} +1 -1
  54. package/dist/{cli-xk879m3k.js → cli-p2gfst4m.js} +52 -43
  55. package/dist/{cli-sya22y84.js → cli-pasjcnmj.js} +12 -12
  56. package/dist/{cli-0whpms1z.js → cli-qa4wdgsy.js} +5 -5
  57. package/dist/{cli-ejkvvqbe.js → cli-qfedvmcr.js} +50 -24
  58. package/dist/{cli-tqq0hspb.js → cli-qmqk2yc2.js} +1 -1
  59. package/dist/{cli-qmd3mse0.js → cli-qsnnd04k.js} +1 -1
  60. package/dist/{cli-agyaeef4.js → cli-qwca7s44.js} +3 -3
  61. package/dist/{cli-fayav105.js → cli-rfywm85n.js} +724 -792
  62. package/dist/{cli-zgv8gxgs.js → cli-rmmpt0wm.js} +6 -6
  63. package/dist/{cli-hae9j8sv.js → cli-rzsy6nc6.js} +12 -8
  64. package/dist/{cli-btf6fw39.js → cli-s7t6p9my.js} +1 -1
  65. package/dist/{cli-cseh6f8w.js → cli-sdtt3men.js} +1 -1
  66. package/dist/{cli-9r5gtwjr.js → cli-tk7cjj8h.js} +197 -2
  67. package/dist/{cli-q26b9wre.js → cli-tph5wt3y.js} +4 -4
  68. package/dist/{cli-gce09r66.js → cli-tqegb8eq.js} +3 -3
  69. package/dist/{cli-kf3pxxdg.js → cli-v1dv1r37.js} +1 -1
  70. package/dist/{cli-09kmfkmq.js → cli-wcg8x116.js} +1 -1
  71. package/dist/{cli-mnrkgg60.js → cli-wk18cm92.js} +5 -5
  72. package/dist/{cli-p0m0p34z.js → cli-x1wa213s.js} +3 -3
  73. package/dist/{cli-jrp1dt73.js → cli-xzm9vcfg.js} +1 -1
  74. package/dist/{cli-715t1gx6.js → cli-y97qxcfx.js} +9 -9
  75. package/dist/{cli-bc779n4v.js → cli-yq3zak69.js} +1 -1
  76. package/dist/cli.js +17 -17
  77. package/dist/{codex-adapter-ysq6bzha.js → codex-adapter-30j9bpzd.js} +5 -6
  78. package/dist/{codex-hook-fac6175r.js → codex-hook-h3vk6xzr.js} +1 -1
  79. package/dist/{codex-session-runner-qakzfx93.js → codex-session-runner-8vp57v8w.js} +5 -6
  80. package/dist/{commands-rs7hkv9r.js → commands-bngnz9g7.js} +3 -3
  81. package/dist/{controller-r5x9bg6e.js → controller-hxx8wwy1.js} +2 -2
  82. package/dist/{controllers-connect-498hrxvk.js → controllers-connect-e2b4gyxc.js} +20 -20
  83. package/dist/{cursor-adapter-d46qszer.js → cursor-adapter-n5nc3mfe.js} +1 -2
  84. package/dist/{db-s13dqhr6.js → db-bgm7vkc0.js} +3 -3
  85. package/dist/{db-pm96nhdb.js → db-c6np41ca.js} +12 -2
  86. package/dist/{devin-adapter-z46ep5ph.js → devin-adapter-xedz98zv.js} +1 -1
  87. package/dist/{dispatcher-j3h81t7m.js → dispatcher-jnybck15.js} +18 -18
  88. package/dist/{dsh-adapter-rw0d5rc4.js → dsh-adapter-nrhbrjz8.js} +1 -2
  89. package/dist/{easter-egg-3d-qtgfxgze.js → easter-egg-3d-533knw22.js} +1 -1
  90. package/dist/{embedding-space-xh8p4q4x.js → embedding-space-crsm2zp0.js} +6 -6
  91. package/dist/{embeddings-wp745m91.js → embeddings-e7z3f27f.js} +1 -1
  92. package/dist/{execute-2fzb9z74.js → execute-b3mrb1mv.js} +1 -1
  93. package/dist/{external-channel-ys21h3sy.js → external-channel-m77wf5z3.js} +2 -2
  94. package/dist/{fx-adapter-vz0b9z3g.js → fx-adapter-b6w0kf56.js} +7 -8
  95. package/dist/{google-generative-ai-ytpgncx9.js → google-generative-ai-h7s3e9kk.js} +1 -1
  96. package/dist/{google-vertex-tqhze5j7.js → google-vertex-fhxaafzw.js} +1 -1
  97. package/dist/{grok-adapter-spea7zkj.js → grok-adapter-4sqtebdk.js} +7 -8
  98. package/dist/handlers-kdjcyzdj.js +32 -0
  99. package/dist/heartbeat-xgb036sx.js +43 -0
  100. package/dist/{hook-amcj4s10.js → hook-5h02c9ga.js} +6 -6
  101. package/dist/{hook-bc6n49qn.js → hook-xsk1jbha.js} +5 -5
  102. package/dist/{http-7374brv5.js → http-txe7qhvn.js} +448 -165
  103. package/dist/{index-pxn30mse.js → index-0eny15vj.js} +8 -8
  104. package/dist/{index-5a9jtqde.js → index-0rvk3vd4.js} +46 -46
  105. package/dist/{index-fvzke5kx.js → index-1qw6f2dc.js} +10 -10
  106. package/dist/{index-q5cmtbz5.js → index-4a0670yh.js} +15939 -14244
  107. package/dist/index-835xdgnm.js +33 -0
  108. package/dist/index-d469300x.js +37 -0
  109. package/dist/{index-h7f61sy9.js → index-e5pfbsys.js} +3 -3
  110. package/dist/{index-hsad2t3r.js → index-m5gx1xd6.js} +38 -38
  111. package/dist/{index-5fx3b3kw.js → index-rvccek1w.js} +9 -9
  112. package/dist/index-rzqwp11g.js +32 -0
  113. package/dist/{index-w4m9z29z.js → index-tvfafeyy.js} +1 -1
  114. package/dist/{index-c9y31ytf.js → index-vk63emp7.js} +979 -35
  115. package/dist/{index-514d9pf6.js → index-w7em4ktq.js} +8 -8
  116. package/dist/{index-p4hjwbvw.js → index-ysvbhg5m.js} +1 -1
  117. package/dist/{keepalive-wy29kbrg.js → keepalive-4zsrce78.js} +3 -3
  118. package/dist/lead-yqt47dkr.js +70 -0
  119. package/dist/{maintenance-h2ds9w6c.js → maintenance-86jvartk.js} +1 -1
  120. package/dist/{oauth-refresh-sweep-q7mtbyp3.js → oauth-refresh-sweep-j52kg9pr.js} +2 -2
  121. package/dist/{onboard-vw8r2fdw.js → onboard-c2aj5p8q.js} +3 -3
  122. package/dist/{opencode-adapter-mtb0953j.js → opencode-adapter-dsagkhtw.js} +5 -6
  123. package/dist/{otel-impl-j42czw3r.js → otel-impl-yyy203z8.js} +1 -1
  124. package/dist/{pi-mono-adapter-zk8pg9jr.js → pi-mono-adapter-546cd1cc.js} +9 -9
  125. package/dist/{pricing-refresh-x7nhv23d.js → pricing-refresh-1rgzqyzz.js} +2 -3
  126. package/dist/{rbac-roles-9044425x.js → rbac-roles-e70xfeyj.js} +4 -6
  127. package/dist/{rbac-roles-bzvee6cf.js → rbac-roles-q89qe8er.js} +3 -3
  128. package/dist/{registry-hpjfmcfz.js → registry-32b1mft6.js} +1 -1
  129. package/dist/{render-v2-t7bn4skz.js → render-v2-k6tt107q.js} +9 -4
  130. package/dist/{resume-x94gemep.js → resume-cnnrjfxa.js} +6 -6
  131. package/dist/{runtime-breq6fmv.js → runtime-1hv06jsn.js} +1 -1
  132. package/dist/{session-access-q7dmqjvt.js → session-access-xkxkjw3n.js} +4 -4
  133. package/dist/{session-source-backfill-440ysamr.js → session-source-backfill-1d5pdwww.js} +2 -2
  134. package/dist/{setup-07n4727s.js → setup-se8q7gkc.js} +1 -1
  135. package/dist/{virtual-modules-z5h6mcyf.js → virtual-modules-gazyapte.js} +3 -3
  136. package/dist/{work-objects-pnq5y534.js → work-objects-1kxnbzy5.js} +22 -22
  137. package/dist/{worker-follow-up-7z1gfkr8.js → worker-follow-up-zqm8apt4.js} +18 -18
  138. package/dist/worker-j6xxtq7p.js +70 -0
  139. package/openapi.json +334 -7
  140. package/package.json +4 -4
  141. package/src/apps/catalog.generated.json +55 -0
  142. package/src/apps/definition.ts +11 -0
  143. package/src/apps/page-validator.ts +19 -0
  144. package/src/apps/store.ts +28 -8
  145. package/src/assets/key.ts +77 -4
  146. package/src/be/db/model-profiles.ts +147 -38
  147. package/src/be/db/session-labels.ts +57 -0
  148. package/src/be/db/session-tree.ts +51 -7
  149. package/src/be/db/slack-trees.ts +146 -0
  150. package/src/be/db/tasks/read.ts +107 -8
  151. package/src/be/db/workflow-run-definitions.ts +117 -0
  152. package/src/be/db-client.ts +8 -2
  153. package/src/be/db.ts +119 -87
  154. package/src/be/event-loop-lag.ts +146 -0
  155. package/src/be/mcp-overflow-sweep.ts +2 -1
  156. package/src/be/memory/constants.ts +14 -1
  157. package/src/be/memory/key-paths.ts +8 -0
  158. package/src/be/memory/providers/sqlite-store.ts +199 -18
  159. package/src/be/memory/task-learning.ts +79 -14
  160. package/src/be/memory/types.ts +24 -1
  161. package/src/be/migrations/278_slack_render_v2_reconcile.sql +108 -0
  162. package/src/be/migrations/279_backfill_learning_expiry.sql +15 -0
  163. package/src/be/migrations/281_model_profiles_pr2.sql +28 -0
  164. package/src/be/migrations/283_workflow_run_definitions.sql +14 -0
  165. package/src/be/model-profile-check.ts +284 -0
  166. package/src/be/model-tier-resolution.ts +112 -12
  167. package/src/be/multi-runtime.ts +27 -0
  168. package/src/be/runtime-pools/routing.ts +52 -4
  169. package/src/be/scripts/typecheck.ts +1 -0
  170. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +552 -0
  171. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +389 -14
  172. package/src/be/seed-scripts/catalog/dreaming-memtax.ts +6 -3
  173. package/src/be/seed-scripts/index.ts +9 -0
  174. package/src/be/steering.ts +8 -2
  175. package/src/be/swarm-config-guard.ts +2 -0
  176. package/src/commands/context-preamble.ts +258 -0
  177. package/src/commands/onboard/agent-fs-version.ts +1 -1
  178. package/src/commands/runner.ts +32 -1
  179. package/src/extensions/catalog.generated.json +3 -3
  180. package/src/fs/provider.ts +17 -3
  181. package/src/heartbeat/heartbeat.ts +17 -5
  182. package/src/heartbeat/index.ts +1 -0
  183. package/src/http/agents.ts +56 -4
  184. package/src/http/apps.ts +3 -1
  185. package/src/http/config.ts +2 -6
  186. package/src/http/core.ts +9 -3
  187. package/src/http/index.ts +12 -9
  188. package/src/http/memory.ts +9 -4
  189. package/src/http/model-profiles.ts +58 -10
  190. package/src/http/poll.ts +36 -3
  191. package/src/http/schedules.ts +42 -3
  192. package/src/http/sessions.ts +16 -3
  193. package/src/http/tasks.ts +37 -12
  194. package/src/http/utils.ts +18 -0
  195. package/src/http/webhooks.ts +48 -0
  196. package/src/http/workflows.ts +15 -2
  197. package/src/integrations/chat-sdk/commands.ts +167 -31
  198. package/src/integrations/chat-sdk/inbound.ts +10 -8
  199. package/src/integrations/chat-sdk/message-text.ts +117 -0
  200. package/src/prompts/session-templates.ts +1 -1
  201. package/src/providers/acp-targets.ts +11 -6
  202. package/src/providers/amp-adapter.ts +1 -1
  203. package/src/providers/claude-sdk-session.ts +132 -23
  204. package/src/providers/codex-skill-resolver.ts +10 -4
  205. package/src/providers/cursor-adapter.ts +1 -1
  206. package/src/providers/devin-skill-resolver.ts +5 -5
  207. package/src/providers/dsh-adapter.ts +1 -1
  208. package/src/scheduler/schedule-task.ts +1 -0
  209. package/src/scheduler/scheduler.ts +4 -1
  210. package/src/scripts-runtime/executors/quickjs-runner.ts +2 -0
  211. package/src/scripts-runtime/executors/quickjs-structured-clone.ts +180 -0
  212. package/src/scripts-runtime/quickjs-compat.ts +0 -1
  213. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  214. package/src/scripts-runtime/swarm-sdk.ts +18 -1
  215. package/src/scripts-runtime/types/stdlib.d.ts +1 -0
  216. package/src/scripts-runtime/types/swarm-sdk.d.ts +1 -0
  217. package/src/server.ts +2 -0
  218. package/src/slack/app.ts +425 -10
  219. package/src/slack/handlers.ts +9 -2
  220. package/src/slack/inbound-dispatch.ts +18 -1
  221. package/src/slack/index.ts +7 -1
  222. package/src/slack/lifecycle-lock.ts +29 -0
  223. package/src/slack/render-v2.ts +424 -212
  224. package/src/slack/socket-fence.ts +64 -0
  225. package/src/slack/watcher.ts +42 -8
  226. package/src/slack/workspace-guard.ts +345 -0
  227. package/src/tasks/task-terminal-effects.ts +4 -0
  228. package/src/tasks/worker-follow-up.ts +102 -2
  229. package/src/tests/acp-adapter.test.ts +82 -0
  230. package/src/tests/apps-icon.test.ts +120 -0
  231. package/src/tests/apps-schema-form.test.ts +151 -0
  232. package/src/tests/chained-task-follow-up.test.ts +248 -0
  233. package/src/tests/chat-sdk-commands.test.ts +359 -2
  234. package/src/tests/chat-sdk-inbound.test.ts +20 -0
  235. package/src/tests/chat-sdk-slack.test.ts +189 -1
  236. package/src/tests/check-pr-body.test.ts +40 -0
  237. package/src/tests/claude-sdk-lifecycle.test.ts +216 -1
  238. package/src/tests/claude-sdk-process.fixture.ts +57 -0
  239. package/src/tests/codex-skill-resolver.test.ts +31 -0
  240. package/src/tests/credentials-allowlist.test.ts +470 -0
  241. package/src/tests/db-client-busy-retry.test.ts +69 -18
  242. package/src/tests/db-client.test.ts +26 -1
  243. package/src/tests/db-task-read-contract.test.ts +7 -0
  244. package/src/tests/db-task-write-contract.test.ts +6 -0
  245. package/src/tests/deferred-wake-follow-up.test.ts +47 -0
  246. package/src/tests/docs-index-footprint.test.js +3 -3
  247. package/src/tests/dreaming-learnings.test.ts +1395 -0
  248. package/src/tests/dsh-adapter.test.ts +1 -1
  249. package/src/tests/event-loop-lag.test.ts +184 -0
  250. package/src/tests/explicit-model-validation.test.ts +2 -0
  251. package/src/tests/extensions-example-comms-adherence-gate.test.ts +115 -0
  252. package/src/tests/fs-provider.test.ts +42 -0
  253. package/src/tests/github-webhook-early-ack.test.ts +144 -0
  254. package/src/tests/heartbeat.test.ts +28 -1
  255. package/src/tests/http-api-integration.test.ts +2 -0
  256. package/src/tests/http-log-scrubbing.test.ts +68 -2
  257. package/src/tests/human-free-reclassify.test.ts +5 -1
  258. package/src/tests/kv-storage.test.ts +92 -1
  259. package/src/tests/list-endpoint-slimming.test.ts +17 -0
  260. package/src/tests/memory-key-paths.test.ts +57 -0
  261. package/src/tests/memory-retrieval-purge.test.ts +19 -0
  262. package/src/tests/migration-283-workflow-run-definitions.test.ts +69 -0
  263. package/src/tests/model-profile-check.test.ts +387 -0
  264. package/src/tests/model-profiles-api.test.ts +528 -1
  265. package/src/tests/profile-claim.test.ts +415 -3
  266. package/src/tests/profile-tier-alias.test.ts +382 -0
  267. package/src/tests/quickjs-compat.test.ts +1 -1
  268. package/src/tests/runner-context-preamble.test.ts +552 -0
  269. package/src/tests/schedule-profile.test.ts +359 -0
  270. package/src/tests/script-connections.test.ts +9 -0
  271. package/src/tests/script-executor-conformance.test.ts +188 -0
  272. package/src/tests/script-per-script-executor.test.ts +1 -0
  273. package/src/tests/scripts-sdk-bridge-tool-failure.test.ts +141 -0
  274. package/src/tests/seed-scripts.test.ts +2 -2
  275. package/src/tests/sessions-tree.test.ts +133 -2
  276. package/src/tests/slack-app-icon.test.ts +4 -0
  277. package/src/tests/slack-dm-implicit-mention.test.ts +236 -0
  278. package/src/tests/slack-file-tools-attachments.test.ts +1 -0
  279. package/src/tests/slack-inbound-receipts.test.ts +22 -2
  280. package/src/tests/slack-read-boundaries.test.ts +4 -3
  281. package/src/tests/slack-render-v2-query-plans.test.ts +262 -3
  282. package/src/tests/slack-render-v2-reconcile.test.ts +201 -0
  283. package/src/tests/slack-socket-ack.test.ts +16 -1
  284. package/src/tests/slack-socket-watchdog.test.ts +748 -0
  285. package/src/tests/slack-workspace-guard.test.ts +905 -0
  286. package/src/tests/steering-core.test.ts +40 -0
  287. package/src/tests/store-progress-learning.test.ts +605 -20
  288. package/src/tests/tool-annotations.test.ts +1 -1
  289. package/src/tests/vcs-identity-inheritance.test.ts +85 -0
  290. package/src/tests/workflow-convergence.test.ts +46 -40
  291. package/src/tests/workflow-definition-pinning-recovery.test.ts +552 -0
  292. package/src/tests/workflow-definition-pinning.test.ts +645 -0
  293. package/src/tests/workflow-executors.test.ts +16 -7
  294. package/src/tests/workflow-foreach.test.ts +43 -20
  295. package/src/tests/workflow-notify-slack-ready.test.ts +161 -0
  296. package/src/tests/workflow-profile.test.ts +328 -0
  297. package/src/tools/app-upsert.ts +1 -1
  298. package/src/tools/memory-edit.ts +2 -1
  299. package/src/tools/model-profiles/check-model-profile.ts +63 -0
  300. package/src/tools/schedules/create-schedule.ts +45 -4
  301. package/src/tools/schedules/patch-schedule.ts +50 -4
  302. package/src/tools/schedules/update-schedule.ts +50 -4
  303. package/src/tools/send-task.ts +17 -2
  304. package/src/tools/store-progress.ts +15 -3
  305. package/src/tools/task-action.ts +9 -1
  306. package/src/tools/templates.ts +13 -0
  307. package/src/tools/tool-config.ts +2 -1
  308. package/src/tools/utils.ts +77 -11
  309. package/src/tools/workflows/create-workflow.ts +1 -1
  310. package/src/tools/workflows/retry-workflow-run.ts +1 -1
  311. package/src/tools/workflows/update-workflow.ts +10 -1
  312. package/src/types.ts +56 -1
  313. package/src/utils/credentials.ts +89 -12
  314. package/src/workflows/engine.ts +10 -1
  315. package/src/workflows/executors/agent-task.ts +21 -2
  316. package/src/workflows/executors/foreach.ts +4 -1
  317. package/src/workflows/executors/notify.ts +62 -6
  318. package/src/workflows/executors/sub-workflow.ts +1 -1
  319. package/src/workflows/executors/swarm-script.ts +4 -1
  320. package/src/workflows/foreach-driver.ts +8 -5
  321. package/src/workflows/limits.ts +2 -1
  322. package/src/workflows/model-validation.ts +27 -2
  323. package/src/workflows/patch-definition.ts +3 -1
  324. package/src/workflows/recovery.ts +6 -6
  325. package/src/workflows/resume.ts +9 -9
  326. package/src/workflows/retry-poller.ts +2 -2
  327. package/templates/extensions/comms-adherence-gate/README.md +25 -0
  328. package/templates/extensions/comms-adherence-gate/hooks.ts +100 -11
  329. package/templates/extensions/comms-adherence-gate/manifest.json +1 -1
  330. package/templates/skills/apps/SKILL.md +9 -0
  331. package/templates/skills/apps/content.md +9 -0
  332. package/templates/skills/code-quality/content.md +12 -0
  333. package/templates/skills/memory/content.md +8 -0
  334. package/templates/skills/scheduling/config.json +1 -1
  335. package/templates/skills/scheduling/content.md +2 -2
  336. package/templates/skills/swarm-docs/content.md +4 -0
  337. package/templates/skills/swarm-extensions/content.md +1 -1
  338. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  339. package/templates/skills/swarm-scripts/content.md +1 -1
  340. package/templates/skills/work-on-task/SKILL.md +2 -0
  341. package/templates/skills/work-on-task/content.md +2 -0
  342. package/templates/workflows/dreaming/content.md +174 -7
  343. package/dist/acp-adapter-dn4gdsgr.js +0 -16
  344. package/dist/app-a66ssc4k.js +0 -17
  345. package/dist/cli-530hkwdy.js +0 -779
  346. package/dist/cli-a0657jmf.js +0 -339
  347. package/dist/cli-cyn9v8zr.js +0 -748
  348. package/dist/handlers-crckt5dq.js +0 -32
  349. package/dist/heartbeat-8phn1kdq.js +0 -41
  350. package/dist/index-4x08sjtk.js +0 -30
  351. package/dist/index-8ybffts4.js +0 -37
  352. package/dist/index-nfy4kkg5.js +0 -33
  353. package/dist/lead-zdqxsvjn.js +0 -71
  354. package/dist/worker-y62rvvq3.js +0 -71
  355. package/dist/{cli-gxy8y1dt.js → cli-8bpgbr8k.js} +3 -3
package/src/slack/app.ts CHANGED
@@ -1,19 +1,49 @@
1
1
  import { App, LogLevel, SocketModeReceiver } from "@slack/bolt";
2
2
  import { emitBuiltInIntegrationConnectedOnce, ensureSlackRenderV2Activation } from "../be/db";
3
3
  import { getNodeEnv } from "../utils/node-env";
4
+ import { scrubSecrets } from "../utils/secret-scrubber";
4
5
  import { getSlackConfiguration } from "./config";
5
- import { type SlackConnectionState, setSlackConnectionState } from "./connection-state";
6
+ import {
7
+ getSlackConnectionState,
8
+ type SlackConnectionState,
9
+ setSlackConnectionState,
10
+ } from "./connection-state";
6
11
  import { installSlackEgressScrub } from "./egress-scrub";
7
12
  import { installSlackExternalChannelGuard } from "./external-channel-egress";
8
13
  import { recoverSlackInboundAfterRestart, slackInboundOutcomeMiddleware } from "./inbound-dispatch";
14
+ import { isSlackLifecycleBusy, runSlackLifecycleExclusive } from "./lifecycle-lock";
9
15
  import { installSocketAckRecovery } from "./socket-ack";
16
+ import { fenceSocketModeClient, type SlackSocketFence } from "./socket-fence";
10
17
  import { getSlackSocketModeBlockReason, SLACK_DEV_SOCKET_MODE_OPT_IN } from "./socket-mode-guard";
11
18
  import { startTaskWatcher, stopTaskWatcher } from "./watcher";
19
+ import {
20
+ getSlackWorkspaceIdentity,
21
+ installSocketWorkspaceGate,
22
+ isSlackEnterpriseInstall,
23
+ resolveSlackIdentity,
24
+ setSlackWorkspaceIdentitySource,
25
+ } from "./workspace-guard";
12
26
 
13
27
  let app: App | null = null;
14
28
  let receiver: SocketModeReceiver | null = null;
15
29
  let initialized = false;
16
30
  let inboundDrain: ReturnType<typeof installSocketAckRecovery> | null = null;
31
+ // Retires the current client at teardown, so a reconnect it still has in
32
+ // flight cannot open a socket next to the replacement.
33
+ let socketFence: SlackSocketFence | null = null;
34
+ // Bumped at each teardown. A start that sees a new generation was abandoned
35
+ // by the watchdog (or overtaken by a stop) and must not touch shared state.
36
+ let lifecycleGeneration = 0;
37
+ // Last sign of life on the current socket: Slack's hello or any envelope.
38
+ let lastSocketActivityAt: number | null = null;
39
+
40
+ /** Backoff between start attempts while this swarm's workspace is unknown. */
41
+ const DEFAULT_START_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000, 120_000, 300_000];
42
+ let startRetryDelaysMs = DEFAULT_START_RETRY_DELAYS_MS;
43
+ let startRetryTimer: ReturnType<typeof setTimeout> | null = null;
44
+ let startRetryAttempt = 0;
45
+ /** Bolt's deferred init (its own auth.test) succeeded for the current app. */
46
+ let boltInitialized = false;
17
47
 
18
48
  const SOCKET_EVENT_STATES: Record<string, SlackConnectionState> = {
19
49
  connecting: "connecting",
@@ -27,9 +57,240 @@ function trackConnectionState(owner: SocketModeReceiver): void {
27
57
  for (const [event, state] of Object.entries(SOCKET_EVENT_STATES)) {
28
58
  owner.client.on(event, () => {
29
59
  // Ignore late events from a receiver that stopSlackApp() already replaced.
30
- if (receiver === owner) setSlackConnectionState(state);
60
+ if (receiver !== owner) return;
61
+ setSlackConnectionState(state);
62
+ if (state === "connected") lastSocketActivityAt = Date.now();
31
63
  });
32
64
  }
65
+ owner.client.on("slack_event", () => {
66
+ if (receiver === owner) lastSocketActivityAt = Date.now();
67
+ });
68
+ }
69
+
70
+ // ─── Socket watchdog ──────────────────────────────────────────────────────────
71
+ // @slack/socket-mode treats a RequestError/HTTPError from apps.connections.open
72
+ // as unrecoverable during a reconnect, and its reconnect promise has no catch.
73
+ // The client then stops retrying for good and the state sticks in
74
+ // `connecting`. Upstream will not fix it (slackapi/node-slack-sdk#2656), so the
75
+ // watchdog rebuilds the whole Slack app when the socket stays down.
76
+
77
+ export interface SlackSocketWatchdogOptions {
78
+ /** How often the watchdog checks the socket. */
79
+ tickMs: number;
80
+ /** How long the socket must be down before the first restart. */
81
+ downAfterMs: number;
82
+ /** With no hello or envelope for this long, a `connected` socket also needs `isActive()`. */
83
+ staleActivityMs: number;
84
+ /** Delay after the first restart; it doubles after each further attempt. */
85
+ backoffBaseMs: number;
86
+ /** Cap on the delay between restarts. */
87
+ backoffMaxMs: number;
88
+ /**
89
+ * Bound on one restart (teardown + start) under the lifecycle lock. A
90
+ * restart still running then is abandoned, so a config reload or a shutdown
91
+ * waiting on the lock gets it.
92
+ */
93
+ restartTimeoutMs: number;
94
+ /**
95
+ * Bound on stopSlackApp()'s wait for the lifecycle lock. Shutdown must
96
+ * finish inside the pod's termination grace, which is shorter than
97
+ * `restartTimeoutMs`.
98
+ */
99
+ stopLockWaitMs: number;
100
+ }
101
+
102
+ export const SLACK_SOCKET_WATCHDOG_DEFAULTS: SlackSocketWatchdogOptions = {
103
+ tickMs: 5_000,
104
+ downAfterMs: 60_000,
105
+ staleActivityMs: 10 * 60_000,
106
+ backoffBaseMs: 30_000,
107
+ backoffMaxMs: 5 * 60_000,
108
+ restartTimeoutMs: 2 * 60_000,
109
+ stopLockWaitMs: 10_000,
110
+ };
111
+
112
+ export interface SlackSocketWatchdogDeps {
113
+ now: () => number;
114
+ getState: () => SlackConnectionState;
115
+ /** Last hello or envelope on the current socket, in epoch ms. */
116
+ getLastActivityAt: () => number | null;
117
+ /** The socket-mode client's own view: is its websocket open? */
118
+ isSocketActive: () => boolean;
119
+ /** True while a config reload (or another restart) holds the Slack lifecycle lock. */
120
+ isLifecycleBusy: () => boolean;
121
+ restart: () => Promise<void>;
122
+ log: (line: string) => void;
123
+ }
124
+
125
+ export interface SlackSocketWatchdog {
126
+ tick: () => Promise<void>;
127
+ /** Restart attempts since the socket was last healthy. */
128
+ attempts: () => number;
129
+ }
130
+
131
+ /** Delay before restart attempt `attempt + 1`: base * 2^(attempt-1), capped. */
132
+ export function slackWatchdogBackoffMs(
133
+ attempt: number,
134
+ options: SlackSocketWatchdogOptions,
135
+ ): number {
136
+ return Math.min(options.backoffBaseMs * 2 ** Math.max(0, attempt - 1), options.backoffMaxMs);
137
+ }
138
+
139
+ /**
140
+ * The watchdog state machine, with no timers of its own: the caller drives
141
+ * `tick()`. Operators search the two log lines, so keep their
142
+ * text stable.
143
+ */
144
+ export function createSlackSocketWatchdog(
145
+ deps: SlackSocketWatchdogDeps,
146
+ options: SlackSocketWatchdogOptions = SLACK_SOCKET_WATCHDOG_DEFAULTS,
147
+ ): SlackSocketWatchdog {
148
+ let downSince: number | null = null;
149
+ let attempts = 0;
150
+ let nextAttemptAt = 0;
151
+ let restarting = false;
152
+
153
+ function isHealthy(now: number): boolean {
154
+ if (deps.getState() !== "connected") return false;
155
+ // A quiet night is normal. Only a quiet socket that the client itself
156
+ // reports as closed counts as down.
157
+ const lastActivityAt = deps.getLastActivityAt();
158
+ if (lastActivityAt === null || now - lastActivityAt < options.staleActivityMs) return true;
159
+ return deps.isSocketActive();
160
+ }
161
+
162
+ async function tick(): Promise<void> {
163
+ if (restarting || deps.isLifecycleBusy()) return;
164
+ const now = deps.now();
165
+ if (isHealthy(now)) {
166
+ if (attempts > 0 && downSince !== null) {
167
+ deps.log(`[Slack] watchdog: recovered after ${seconds(now - downSince)}s`);
168
+ }
169
+ downSince = null;
170
+ attempts = 0;
171
+ nextAttemptAt = 0;
172
+ return;
173
+ }
174
+ downSince ??= now;
175
+ if (now - downSince < options.downAfterMs || now < nextAttemptAt) return;
176
+ attempts += 1;
177
+ nextAttemptAt = now + slackWatchdogBackoffMs(attempts, options);
178
+ deps.log(
179
+ `[Slack] watchdog: socket down for ${seconds(now - downSince)}s, restarting (attempt ${attempts})`,
180
+ );
181
+ restarting = true;
182
+ try {
183
+ await deps.restart();
184
+ } catch (error) {
185
+ // The error can carry request config or a token; scrub before it leaves.
186
+ const message = error instanceof Error ? error.message : String(error);
187
+ console.error(`[Slack] watchdog: restart failed: ${scrubSecrets(message)}`);
188
+ } finally {
189
+ restarting = false;
190
+ }
191
+ }
192
+
193
+ return { tick, attempts: () => attempts };
194
+ }
195
+
196
+ function seconds(ms: number): number {
197
+ return Math.round(ms / 1000);
198
+ }
199
+
200
+ function isLiveSocketActive(): boolean {
201
+ return receiver?.client.websocket?.isActive() ?? false;
202
+ }
203
+
204
+ let watchdogTimer: ReturnType<typeof setInterval> | null = null;
205
+ let watchdogOptions: SlackSocketWatchdogOptions = SLACK_SOCKET_WATCHDOG_DEFAULTS;
206
+
207
+ /**
208
+ * Rebuild the Slack app under the lifecycle lock, bounded by
209
+ * `restartTimeoutMs`. The web client can retry apps.connections.open for many
210
+ * minutes, and every config reload waits on the lock meanwhile. A restart
211
+ * that runs out of time is abandoned: its client is retired first, so it can
212
+ * never open a socket later, and the watchdog tries again after its backoff.
213
+ */
214
+ async function restartSlackAppForWatchdog(owner: ReturnType<typeof setInterval>): Promise<void> {
215
+ await runSlackLifecycleExclusive(async () => {
216
+ // stopSlackApp() won the lock first and disarmed this watchdog (shutdown,
217
+ // or a reload that armed a new one). Restarting now would bring back an
218
+ // app that the caller already stopped.
219
+ if (watchdogTimer !== owner) return;
220
+ // A config reload that won the lock may have just brought the socket back.
221
+ if (getSlackConnectionState() === "connected" && isLiveSocketActive()) return;
222
+ let abandoned = false;
223
+ const restart = (async () => {
224
+ await teardownSlackApp();
225
+ // A teardown that outlived the timeout must not start an app outside the
226
+ // lock, and one that a forced stopSlackApp() disarmed must not start one at all.
227
+ if (!abandoned && watchdogTimer === owner) await startSlackApp();
228
+ })();
229
+ const timeoutMs = watchdogOptions.restartTimeoutMs;
230
+ let timer: ReturnType<typeof setTimeout> | undefined;
231
+ const timedOut = new Promise<true>((resolve) => {
232
+ timer = setTimeout(() => resolve(true), timeoutMs);
233
+ });
234
+ try {
235
+ const outcome = await Promise.race([restart.then(() => false as const), timedOut]);
236
+ if (!outcome) return;
237
+ } finally {
238
+ clearTimeout(timer);
239
+ }
240
+ abandoned = true;
241
+ // The abandoned restart settles later, if ever; its error is no longer news.
242
+ void restart.catch(() => {});
243
+ abandonSlackApp();
244
+ throw new Error(`restart did not finish within ${seconds(timeoutMs)}s; abandoned it`);
245
+ });
246
+ }
247
+
248
+ function startSocketWatchdog(): void {
249
+ if (watchdogTimer) return;
250
+ let timer: ReturnType<typeof setInterval> | null = null;
251
+ const watchdog = createSlackSocketWatchdog(
252
+ {
253
+ now: Date.now,
254
+ getState: getSlackConnectionState,
255
+ getLastActivityAt: () => lastSocketActivityAt,
256
+ isSocketActive: isLiveSocketActive,
257
+ isLifecycleBusy: isSlackLifecycleBusy,
258
+ restart: () => (timer ? restartSlackAppForWatchdog(timer) : Promise.resolve()),
259
+ log: (line) => console.log(line),
260
+ },
261
+ watchdogOptions,
262
+ );
263
+ timer = setInterval(() => {
264
+ if (getSlackConfiguration().mode !== "socket") {
265
+ stopSocketWatchdog();
266
+ return;
267
+ }
268
+ void watchdog.tick();
269
+ }, watchdogOptions.tickMs);
270
+ // Never keep the process (or a test run) alive for the watchdog alone.
271
+ timer.unref?.();
272
+ watchdogTimer = timer;
273
+ }
274
+
275
+ function stopSocketWatchdog(): void {
276
+ if (watchdogTimer) clearInterval(watchdogTimer);
277
+ watchdogTimer = null;
278
+ }
279
+
280
+ /** Test hook: shorter thresholds for the next watchdog start. Pass nothing to reset. */
281
+ export function _setSlackSocketWatchdogOptionsForTests(
282
+ options?: Partial<SlackSocketWatchdogOptions>,
283
+ ): void {
284
+ watchdogOptions = { ...SLACK_SOCKET_WATCHDOG_DEFAULTS, ...options };
285
+ }
286
+
287
+ /** Test hook: the live socket-mode client, to inject reconnect faults. */
288
+ export function _getSlackSocketClientForTests(): SocketModeReceiver["client"] | null {
289
+ return receiver?.client ?? null;
290
+ }
291
+
292
+ export function isSlackSocketWatchdogRunning(): boolean {
293
+ return watchdogTimer !== null;
33
294
  }
34
295
 
35
296
  export function getSlackApp(): App | null {
@@ -99,11 +360,15 @@ export async function initSlackApp(): Promise<App | null> {
99
360
  installerOptions: clientOptions ? { clientOptions } : {},
100
361
  });
101
362
  trackConnectionState(receiver);
363
+ socketFence = fenceSocketModeClient(receiver.client);
102
364
  app = new App({
103
365
  token: botToken,
104
366
  receiver,
105
367
  socketMode: true,
106
368
  logLevel,
369
+ // Bolt's auth.test runs in startSlackApp(), where a failure is retried
370
+ // instead of being cached as a rejected promise for the app's lifetime.
371
+ deferInitialization: true,
107
372
  ...(clientOptions ? { clientOptions } : {}),
108
373
  });
109
374
 
@@ -111,6 +376,14 @@ export async function initSlackApp(): Promise<App | null> {
111
376
  // them back to Bolt, so a crash or a failing listener leaves recoverable work.
112
377
  inboundDrain = installSocketAckRecovery(receiver.client, app);
113
378
 
379
+ // This swarm's installation. Installed last, the gate runs before the ack
380
+ // recovery wrapper and Bolt: a delivery for any other installation sharing
381
+ // this Slack app is never acked, stored or dispatched, so Slack redelivers it.
382
+ const authClient = app.client;
383
+ const enterpriseInstall = isSlackEnterpriseInstall();
384
+ setSlackWorkspaceIdentitySource(() => resolveSlackIdentity(authClient, enterpriseInstall));
385
+ installSocketWorkspaceGate(receiver.client);
386
+
114
387
  // Failed validation must remain retryable without requiring stopSlackApp().
115
388
  initialized = true;
116
389
 
@@ -145,21 +418,46 @@ export async function initSlackApp(): Promise<App | null> {
145
418
  }
146
419
 
147
420
  export async function startSlackApp(): Promise<boolean> {
421
+ const generation = lifecycleGeneration;
148
422
  if (!app) {
149
423
  await initSlackApp();
150
424
  }
151
425
 
152
- if (app) {
426
+ const current = app;
427
+ if (current && generation === lifecycleGeneration) {
428
+ clearStartRetry();
429
+ // Fail closed: without this swarm's identity the gate admits nothing, so
430
+ // the socket stays closed and other swarms sharing the app keep receiving.
431
+ // The start retry, not the watchdog, owns this case: the socket never opened.
432
+ const verified = await verifySlackIdentity(current);
433
+ if (generation !== lifecycleGeneration) return false;
434
+ if (!verified) {
435
+ const delay = scheduleStartRetry();
436
+ setSlackConnectionState("disconnected");
437
+ console.error(
438
+ `[Slack] Socket Mode not started: this swarm's workspace is unknown. Retrying in ${seconds(delay)}s`,
439
+ );
440
+ return false;
441
+ }
442
+ startRetryAttempt = 0;
443
+ // Arm before app.start(): a start that throws is retried by the watchdog.
444
+ startSocketWatchdog();
153
445
  // Establish the durable cutoff before Socket Mode can deliver new asks.
154
446
  const { isSlackRenderV2Enabled } = await import("./render-v2");
155
447
  if (isSlackRenderV2Enabled()) await ensureSlackRenderV2Activation();
156
448
  // Receipts stored before the last restart: interrupted ones turn uncertain,
157
449
  // pending ones are processed once the app can dispatch them.
158
450
  await recoverSlackInboundAfterRestart();
159
- await app.start();
451
+ if (generation !== lifecycleGeneration) return false;
452
+ await current.start();
453
+ // Abandoned while it waited: the app was already detached and retired.
454
+ if (generation !== lifecycleGeneration) return false;
160
455
  console.log("[Slack] Bot connected via Socket Mode");
161
456
  void inboundDrain?.wake();
162
457
  await emitBuiltInIntegrationConnectedOnce("slack");
458
+ // Abandoned or stopped while telemetry was pending: a watcher started now
459
+ // would outlive the stop and leak its timer.
460
+ if (generation !== lifecycleGeneration) return false;
163
461
 
164
462
  // Start watching for task completions
165
463
  await startTaskWatcher();
@@ -169,17 +467,134 @@ export async function startSlackApp(): Promise<boolean> {
169
467
  return false;
170
468
  }
171
469
 
470
+ /** Resolve this swarm's identity, then Bolt's own authorization. False on any failure. */
471
+ async function verifySlackIdentity(current: App): Promise<boolean> {
472
+ if (!(await getSlackWorkspaceIdentity())) return false;
473
+ if (boltInitialized) return true;
474
+ try {
475
+ await current.init();
476
+ } catch (error) {
477
+ const message = error instanceof Error ? error.message : String(error);
478
+ console.error(`[Slack] Bolt initialization failed: ${message}`);
479
+ return false;
480
+ }
481
+ boltInitialized = true;
482
+ return true;
483
+ }
484
+
485
+ function clearStartRetry(): void {
486
+ if (startRetryTimer) clearTimeout(startRetryTimer);
487
+ startRetryTimer = null;
488
+ }
489
+
490
+ /**
491
+ * Retry the start after a backoff, under the lifecycle lock like every other
492
+ * rebuild. Any teardown in between bumps the generation and cancels it.
493
+ * Returns the delay.
494
+ */
495
+ function scheduleStartRetry(): number {
496
+ const delay = startRetryDelaysMs[Math.min(startRetryAttempt, startRetryDelaysMs.length - 1)]!;
497
+ startRetryAttempt += 1;
498
+ const generation = lifecycleGeneration;
499
+ startRetryTimer = setTimeout(() => {
500
+ startRetryTimer = null;
501
+ void runSlackLifecycleExclusive(async () => {
502
+ if (generation !== lifecycleGeneration) return;
503
+ await startSlackApp();
504
+ }).catch((error: unknown) => {
505
+ const message = error instanceof Error ? error.message : String(error);
506
+ console.error(`[Slack] Start retry failed: ${scrubSecrets(message)}`);
507
+ });
508
+ }, delay);
509
+ startRetryTimer.unref?.();
510
+ return delay;
511
+ }
512
+
513
+ /**
514
+ * Stop the app and disarm the watchdog. Takes the Slack lifecycle lock, so a
515
+ * watchdog restart in flight finishes first and cannot bring the app back
516
+ * after this returns. The wait for the lock is bounded by `stopLockWaitMs`:
517
+ * after that, the stop disarms the watchdog and drops the app without the
518
+ * lock, and stops again once the lock frees.
519
+ */
172
520
  export async function stopSlackApp(): Promise<void> {
173
- stopTaskWatcher();
174
- inboundDrain?.stop();
175
- inboundDrain = null;
521
+ const locked = runSlackLifecycleExclusive(stopSlackAppUnderLifecycleLock);
522
+ const waitMs = watchdogOptions.stopLockWaitMs;
523
+ let timer: ReturnType<typeof setTimeout> | undefined;
524
+ const timedOut = new Promise<true>((resolve) => {
525
+ timer = setTimeout(() => resolve(true), waitMs);
526
+ });
527
+ try {
528
+ const outcome = await Promise.race([locked.then(() => false as const), timedOut]);
529
+ if (!outcome) return;
530
+ } finally {
531
+ clearTimeout(timer);
532
+ }
533
+ // The late stop under the lock still runs; its error is no longer news.
534
+ void locked.catch(() => {});
535
+ console.error(
536
+ `[Slack] stop: lifecycle lock still held after ${seconds(waitMs)}s; stopping without it`,
537
+ );
538
+ // The restart holding the lock sees the disarmed watchdog and starts nothing.
539
+ stopSocketWatchdog();
540
+ abandonSlackApp();
541
+ }
176
542
 
177
- if (app) {
178
- await app.stop();
179
- app = null;
543
+ /**
544
+ * stopSlackApp() for a caller that already holds the lifecycle lock (the
545
+ * config reload). The lock is not reentrant: taking it again would deadlock.
546
+ */
547
+ export async function stopSlackAppUnderLifecycleLock(): Promise<void> {
548
+ stopSocketWatchdog();
549
+ await teardownSlackApp();
550
+ }
551
+
552
+ /** Stop the app but keep the watchdog armed; the watchdog restart uses this. */
553
+ async function teardownSlackApp(): Promise<void> {
554
+ const stopping = detachSlackApp();
555
+ if (stopping) {
556
+ await stopping.stop();
180
557
  console.log("[Slack] Bot disconnected");
181
558
  }
559
+ }
560
+
561
+ /**
562
+ * Drop a restart that ran out of time, without waiting: app.stop() can block
563
+ * on the stalled client too. The retired client opens no socket, and the
564
+ * detached stop closes any socket it already has.
565
+ */
566
+ function abandonSlackApp(): void {
567
+ const stalled = detachSlackApp();
568
+ void stalled?.stop().catch((error: unknown) => {
569
+ const message = error instanceof Error ? error.message : String(error);
570
+ console.error(`[Slack] watchdog: stopping the abandoned app failed: ${scrubSecrets(message)}`);
571
+ });
572
+ }
573
+
574
+ /** Clear the module state synchronously and return the app to stop. */
575
+ function detachSlackApp(): App | null {
576
+ // Retire the client first: app.stop() cannot cancel a start that is still
577
+ // waiting for apps.connections.open.
578
+ socketFence?.retire();
579
+ socketFence = null;
580
+ lifecycleGeneration += 1;
581
+ clearStartRetry();
582
+ startRetryAttempt = 0;
583
+ boltInitialized = false;
584
+ stopTaskWatcher();
585
+ inboundDrain?.stop();
586
+ inboundDrain = null;
587
+ const detached = app;
588
+ app = null;
182
589
  receiver = null;
590
+ setSlackWorkspaceIdentitySource(null);
591
+ lastSocketActivityAt = null;
183
592
  setSlackConnectionState("disconnected");
184
593
  initialized = false;
594
+ return detached;
595
+ }
596
+
597
+ /** Test-only: shorten the start retry backoff; null restores the default. */
598
+ export function setSlackStartRetryDelaysForTests(delaysMs: number[] | null): void {
599
+ startRetryDelaysMs = delaysMs ?? DEFAULT_START_RETRY_DELAYS_MS;
185
600
  }
@@ -187,6 +187,7 @@ interface MessageEvent {
187
187
  channel: string;
188
188
  ts: string;
189
189
  thread_ts?: string;
190
+ channel_type?: string;
190
191
  files?: SlackFile[];
191
192
  assistant_thread?: Record<string, unknown>;
192
193
  }
@@ -572,11 +573,17 @@ export function registerMessageHandler(app: App): void {
572
573
  // those — file uploads included — are handled in assistant.ts. An assistant-thread
573
574
  // message that still lands here is treated as an implicit mention so it routes to
574
575
  // the lead agent rather than being silently dropped.
576
+ // A top-level message in a 1:1 DM with the bot is addressed to the bot too: it has no
577
+ // `thread_ts`, so the Assistant middleware lets it through to this handler. Group DMs
578
+ // (`mpim`) and DM thread replies keep their existing rules.
575
579
  // Guard: suppress implicit mention when the message @-mentions someone else but NOT us —
576
580
  // those messages are addressed to a different agent/user (e.g. Devin) and must not spawn.
577
581
  const isAssistantThread = !!msg.assistant_thread;
582
+ const isTopLevelDirectMessage = msg.channel_type === "im" && !msg.thread_ts;
578
583
  const isImplicitMention =
579
- isAssistantThread && !botMentioned && !isAddressedToOtherUser(effectiveText, botUserId);
584
+ (isAssistantThread || isTopLevelDirectMessage) &&
585
+ !botMentioned &&
586
+ !isAddressedToOtherUser(effectiveText, botUserId);
580
587
 
581
588
  // ADDITIVE_SLACK: Check for !now command in threads
582
589
  const additiveSlack = isEnvFlagEnabled("ADDITIVE_SLACK", false);
@@ -749,7 +756,7 @@ export function registerMessageHandler(app: App): void {
749
756
  if (matches.length === 0) {
750
757
  if (!botMentioned && !isImplicitMention) return ignoreSlackInbound("not_addressed");
751
758
 
752
- // Bot was mentioned (or message is in assistant thread) but no online agents matched — queue the request
759
+ // Bot was mentioned (or implicitly addressed) but no online agents matched — queue the request
753
760
  if (!checkRateLimit(msg.user)) {
754
761
  if (!isSlackRenderV2Enabled()) {
755
762
  await say({
@@ -21,6 +21,7 @@ import {
21
21
  } from "../be/db-queries/slack-inbound";
22
22
  import { scrubSecrets } from "../utils/secret-scrubber";
23
23
  import { getSlackConfiguration, type SlackMode } from "./config";
24
+ import { checkInboundWorkspace, getCachedSlackWorkspaceIdentity } from "./workspace-guard";
24
25
 
25
26
  /**
26
27
  * Explicit outcomes for inbound Slack deliveries.
@@ -182,13 +183,24 @@ export function resetSlackInboundCountersForTests(): void {
182
183
  * here and rethrown unchanged.
183
184
  */
184
185
  export function slackInboundOutcomeMiddleware(): Middleware<AnyMiddlewareArgs> {
185
- return async ({ next }) => {
186
+ return async ({ next, body }) => {
187
+ // The socket gate withholds deliveries that are not ours before Bolt acks
188
+ // them. This check covers what reaches Bolt another way (receipt replay)
189
+ // and fails closed: no listener runs for a delivery we cannot attribute.
190
+ const identity = getCachedSlackWorkspaceIdentity();
191
+ const ownership = checkInboundWorkspace(body, identity);
186
192
  const existing = deliveryStorage.getStore();
187
193
  if (existing) {
188
194
  // A durable delivery: the drain resolves and stores the outcome. Record
189
195
  // the error here too, because Bolt's error handler may swallow it before
190
196
  // App.processEvent() returns to the drain.
191
197
  existing.dispatched = true;
198
+ if (!ownership.own) {
199
+ // No identity yet: a retryable failure, so the receipt waits for one.
200
+ if (!identity) existing.failures.push("workspace_identity_unavailable");
201
+ else existing.ignoredReasons.push(ownership.reason);
202
+ return;
203
+ }
192
204
  try {
193
205
  await next();
194
206
  } catch (error) {
@@ -200,6 +212,11 @@ export function slackInboundOutcomeMiddleware(): Middleware<AnyMiddlewareArgs> {
200
212
 
201
213
  const state = newDeliveryState("socket", false);
202
214
  state.dispatched = true;
215
+ if (!ownership.own) {
216
+ state.ignoredReasons.push(ownership.reason);
217
+ recordOutcome("socket", resolveSlackInboundOutcome(state));
218
+ return;
219
+ }
203
220
  await deliveryStorage.run(state, async () => {
204
221
  try {
205
222
  await next();
@@ -1,4 +1,10 @@
1
- export { getSlackApp, initSlackApp, startSlackApp, stopSlackApp } from "./app";
1
+ export {
2
+ getSlackApp,
3
+ initSlackApp,
4
+ startSlackApp,
5
+ stopSlackApp,
6
+ stopSlackAppUnderLifecycleLock,
7
+ } from "./app";
2
8
  export type {
3
9
  DownloadFileOptions,
4
10
  DownloadFileResult,
@@ -0,0 +1,29 @@
1
+ /**
2
+ * One mutex for every path that tears down and rebuilds the Slack app: the
3
+ * config reload in `http/core.ts` and the socket watchdog in `app.ts`. A leaf
4
+ * module, because `http/core.ts` imports `app.ts` (an import back would cycle).
5
+ */
6
+ let tail: Promise<void> = Promise.resolve();
7
+ let holders = 0;
8
+
9
+ /** Run `fn` after every earlier holder has finished. */
10
+ export async function runSlackLifecycleExclusive<T>(fn: () => Promise<T>): Promise<T> {
11
+ holders += 1;
12
+ const previous = tail;
13
+ let release!: () => void;
14
+ tail = new Promise<void>((resolve) => {
15
+ release = resolve;
16
+ });
17
+ try {
18
+ await previous;
19
+ return await fn();
20
+ } finally {
21
+ holders -= 1;
22
+ release();
23
+ }
24
+ }
25
+
26
+ /** True while a holder runs or waits. The watchdog skips its tick then. */
27
+ export function isSlackLifecycleBusy(): boolean {
28
+ return holders > 0;
29
+ }