@desplega.ai/agent-swarm 2.7.10 → 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 (281) hide show
  1. package/dist/acp-adapter-t949vbbp.js +15 -0
  2. package/dist/{actions-b8aqhrsg.js → actions-7e9czc7s.js} +18 -19
  3. package/dist/{amp-adapter-4c165vgn.js → amp-adapter-gv6cbb7d.js} +2 -3
  4. package/dist/{app-m9khefrh.js → app-b9fbkp9v.js} +3 -3
  5. package/dist/{assistant-rh4v3ntz.js → assistant-wjb7v4c7.js} +20 -21
  6. package/dist/{boot-args-schema-hwkc8bzv.js → boot-args-schema-2t37e0fe.js} +1 -1
  7. package/dist/{boot-reembed-5y6yw9sj.js → boot-reembed-a35nkyr1.js} +1 -1
  8. package/dist/{boot-reembed-fdyk55h4.js → boot-reembed-gka3zas7.js} +1 -1
  9. package/dist/{boot-scrub-sweep-r5r8kqsn.js → boot-scrub-sweep-65sdnp6c.js} +3 -3
  10. package/dist/{boot-seeds-8f9zt5cm.js → boot-seeds-x42tzytw.js} +4 -5
  11. package/dist/{claude-adapter-s5df247c.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-9gsmwzyx.js → claude-managed-setup-9m6450zk.js} +2 -2
  14. package/dist/{claude-sdk-session-dq1j4nz9.js → claude-sdk-session-0q0ptaba.js} +9066 -8818
  15. package/dist/{cli-n5yexkdg.js → cli-0b4zam62.js} +1 -0
  16. package/dist/{cli-5wfz00be.js → cli-0jzra9ad.js} +2 -2
  17. package/dist/{cli-eqtfgfr6.js → cli-2gxeg5gr.js} +1 -1
  18. package/dist/{cli-eqk5p56g.js → cli-2wnq8jkz.js} +9 -9
  19. package/dist/{cli-hfkwwy1h.js → cli-2zp0et3v.js} +21 -2
  20. package/dist/{cli-rt0ag4x1.js → cli-334z18y3.js} +4 -4
  21. package/dist/{cli-6m6b4bep.js → cli-3rkdne1h.js} +2 -2
  22. package/dist/{cli-3xddv0rk.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-n07eecjs.js → cli-6t09sdhy.js} +3 -3
  26. package/dist/{cli-38yww4e9.js → cli-6wxjceza.js} +8 -8
  27. package/dist/{cli-5xcb8gxq.js → cli-7b8sbmag.js} +8 -8
  28. package/dist/{cli-3xj33nrx.js → cli-7cp6aa1q.js} +10 -3
  29. package/dist/{cli-mp9aa8g5.js → cli-7p1kvkck.js} +6 -6
  30. package/dist/{cli-w3bk0dgv.js → cli-8aes17e4.js} +2 -2
  31. package/dist/{cli-n9abj89w.js → cli-8fknbnhw.js} +8 -8
  32. package/dist/{cli-xd5ebp64.js → cli-8kzasymh.js} +3 -3
  33. package/dist/{cli-2tsfpc70.js → cli-a7wvp2km.js} +1 -1
  34. package/dist/{cli-kx4c8j05.js → cli-abejgen1.js} +63 -19
  35. package/dist/{cli-36wdfzgn.js → cli-bsywb58a.js} +8 -8
  36. package/dist/{cli-yz7v0sh4.js → cli-c55z5chy.js} +4 -6
  37. package/dist/{cli-18qt3few.js → cli-deefvewm.js} +1 -1
  38. package/dist/{cli-jg24scat.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-rjyghzg4.js → cli-g70vxtjh.js} +2 -2
  42. package/dist/{cli-g1px1g2e.js → cli-gxkx0zzp.js} +1 -1
  43. package/dist/{cli-j7d73g1y.js → cli-h38x262p.js} +3035 -354
  44. package/dist/{cli-zjphdj1a.js → cli-j790gp2w.js} +40 -18
  45. package/dist/{cli-f2zenhja.js → cli-kc7v1nfv.js} +1 -1
  46. package/dist/{cli-td33w98c.js → cli-m23zjcy2.js} +10 -10
  47. package/dist/{cli-8ewkreqd.js → cli-m28atx8q.js} +7 -9
  48. package/dist/{cli-x9exydey.js → cli-m4dqmnbp.js} +1 -1
  49. package/dist/{cli-ybjdc978.js → cli-mrt48bx7.js} +7 -4
  50. package/dist/{cli-mr97t7cc.js → cli-p1bq50aa.js} +263 -14
  51. package/dist/{cli-ttbqe3q4.js → cli-p1w18yhx.js} +1 -1
  52. package/dist/{cli-nj3x45rw.js → cli-p2gfst4m.js} +52 -43
  53. package/dist/{cli-z9cs5m0w.js → cli-pasjcnmj.js} +12 -12
  54. package/dist/{cli-an1knn2k.js → cli-qa4wdgsy.js} +5 -5
  55. package/dist/{cli-xncjscpm.js → cli-qfedvmcr.js} +50 -24
  56. package/dist/{cli-tmft5dz2.js → cli-qmqk2yc2.js} +1 -1
  57. package/dist/{cli-bxz823sz.js → cli-qsnnd04k.js} +1 -1
  58. package/dist/{cli-cr14kftt.js → cli-qwca7s44.js} +3 -3
  59. package/dist/{cli-7wz05bx3.js → cli-rfywm85n.js} +460 -737
  60. package/dist/{cli-v2fwbnsk.js → cli-rmmpt0wm.js} +6 -6
  61. package/dist/{cli-xbtq4d6s.js → cli-rzsy6nc6.js} +12 -8
  62. package/dist/{cli-0m7rtm11.js → cli-s7t6p9my.js} +1 -1
  63. package/dist/{cli-16phend6.js → cli-sdtt3men.js} +1 -1
  64. package/dist/{cli-pyrxt9gw.js → cli-tk7cjj8h.js} +1 -1
  65. package/dist/{cli-xvymtmv4.js → cli-tqegb8eq.js} +3 -3
  66. package/dist/{cli-kf3pxxdg.js → cli-v1dv1r37.js} +1 -1
  67. package/dist/{cli-h49ejvmc.js → cli-wcg8x116.js} +1 -1
  68. package/dist/{cli-q581b386.js → cli-wk18cm92.js} +5 -5
  69. package/dist/{cli-4vwxp550.js → cli-x1wa213s.js} +1 -1
  70. package/dist/{cli-jrp1dt73.js → cli-xzm9vcfg.js} +1 -1
  71. package/dist/{cli-eb2azq8n.js → cli-y97qxcfx.js} +9 -9
  72. package/dist/{cli-55bkx8hh.js → cli-yq3zak69.js} +1 -1
  73. package/dist/cli.js +17 -17
  74. package/dist/{codex-adapter-yr60sme6.js → codex-adapter-30j9bpzd.js} +5 -6
  75. package/dist/{codex-hook-fac6175r.js → codex-hook-h3vk6xzr.js} +1 -1
  76. package/dist/{codex-session-runner-pch8x584.js → codex-session-runner-8vp57v8w.js} +5 -6
  77. package/dist/{commands-phjfbkv0.js → commands-bngnz9g7.js} +3 -3
  78. package/dist/{controller-jkx994pz.js → controller-hxx8wwy1.js} +2 -2
  79. package/dist/{controllers-connect-c4448kwa.js → controllers-connect-e2b4gyxc.js} +19 -20
  80. package/dist/{cursor-adapter-ndebqnm8.js → cursor-adapter-n5nc3mfe.js} +1 -2
  81. package/dist/{db-ez6egt6v.js → db-bgm7vkc0.js} +3 -3
  82. package/dist/{db-ef32tbfc.js → db-c6np41ca.js} +10 -2
  83. package/dist/{devin-adapter-z46ep5ph.js → devin-adapter-xedz98zv.js} +1 -1
  84. package/dist/{dispatcher-g3tt9hs9.js → dispatcher-jnybck15.js} +17 -18
  85. package/dist/{dsh-adapter-tcyn3099.js → dsh-adapter-nrhbrjz8.js} +1 -2
  86. package/dist/{easter-egg-3d-e36hk5td.js → easter-egg-3d-533knw22.js} +1 -1
  87. package/dist/{embedding-space-4kyh5qqj.js → embedding-space-crsm2zp0.js} +6 -6
  88. package/dist/{embeddings-6a8v4a6t.js → embeddings-e7z3f27f.js} +1 -1
  89. package/dist/{execute-3cbg0twf.js → execute-b3mrb1mv.js} +1 -1
  90. package/dist/{external-channel-se646snz.js → external-channel-m77wf5z3.js} +2 -2
  91. package/dist/{fx-adapter-yw795hqq.js → fx-adapter-b6w0kf56.js} +7 -8
  92. package/dist/{grok-adapter-ttmcss2j.js → grok-adapter-4sqtebdk.js} +7 -8
  93. package/dist/handlers-kdjcyzdj.js +32 -0
  94. package/dist/heartbeat-xgb036sx.js +43 -0
  95. package/dist/{hook-g3nhexsy.js → hook-5h02c9ga.js} +6 -6
  96. package/dist/{hook-hq93y5ej.js → hook-xsk1jbha.js} +5 -5
  97. package/dist/{http-5a9p4h6y.js → http-txe7qhvn.js} +282 -140
  98. package/dist/{index-6haqt3v5.js → index-4a0670yh.js} +8917 -8476
  99. package/dist/index-835xdgnm.js +33 -0
  100. package/dist/index-d469300x.js +37 -0
  101. package/dist/index-rzqwp11g.js +32 -0
  102. package/dist/{index-s72rqgsx.js → index-tvfafeyy.js} +1 -1
  103. package/dist/{index-hgn3c961.js → index-vk63emp7.js} +978 -35
  104. package/dist/{index-3c5pxbge.js → index-ysvbhg5m.js} +1 -1
  105. package/dist/{keepalive-1j4n4dmk.js → keepalive-4zsrce78.js} +3 -3
  106. package/dist/lead-yqt47dkr.js +70 -0
  107. package/dist/{maintenance-dmghacy5.js → maintenance-86jvartk.js} +1 -1
  108. package/dist/{oauth-refresh-sweep-yy06c03c.js → oauth-refresh-sweep-j52kg9pr.js} +2 -2
  109. package/dist/{onboard-52f9t5dm.js → onboard-c2aj5p8q.js} +3 -3
  110. package/dist/{opencode-adapter-krnh9jkn.js → opencode-adapter-dsagkhtw.js} +5 -6
  111. package/dist/{otel-impl-xjqz6wjj.js → otel-impl-yyy203z8.js} +1 -1
  112. package/dist/{pi-mono-adapter-dbxyp0qv.js → pi-mono-adapter-546cd1cc.js} +9 -9
  113. package/dist/{pricing-refresh-ctdr74pd.js → pricing-refresh-1rgzqyzz.js} +2 -3
  114. package/dist/{rbac-roles-q0gr8eyj.js → rbac-roles-e70xfeyj.js} +4 -6
  115. package/dist/{rbac-roles-ehv8s10n.js → rbac-roles-q89qe8er.js} +3 -3
  116. package/dist/{registry-hpjfmcfz.js → registry-32b1mft6.js} +1 -1
  117. package/dist/{render-v2-5b6chvcq.js → render-v2-k6tt107q.js} +3 -3
  118. package/dist/{resume-5a5d2845.js → resume-cnnrjfxa.js} +6 -6
  119. package/dist/{runtime-khxszyfp.js → runtime-1hv06jsn.js} +1 -1
  120. package/dist/{session-access-gj0bjhqg.js → session-access-xkxkjw3n.js} +4 -4
  121. package/dist/{session-source-backfill-2sy0krfk.js → session-source-backfill-1d5pdwww.js} +2 -2
  122. package/dist/{setup-7ssfakk1.js → setup-se8q7gkc.js} +1 -1
  123. package/dist/{virtual-modules-pjj0knwf.js → virtual-modules-gazyapte.js} +3 -3
  124. package/dist/{work-objects-bf3syvhq.js → work-objects-1kxnbzy5.js} +20 -21
  125. package/dist/{worker-follow-up-38xevga6.js → worker-follow-up-zqm8apt4.js} +17 -18
  126. package/dist/worker-j6xxtq7p.js +70 -0
  127. package/openapi.json +334 -7
  128. package/package.json +4 -4
  129. package/src/apps/definition.ts +11 -0
  130. package/src/apps/store.ts +28 -8
  131. package/src/be/db/model-profiles.ts +147 -38
  132. package/src/be/db/tasks/read.ts +5 -1
  133. package/src/be/db/workflow-run-definitions.ts +117 -0
  134. package/src/be/db.ts +24 -3
  135. package/src/be/memory/constants.ts +14 -1
  136. package/src/be/memory/key-paths.ts +8 -0
  137. package/src/be/memory/providers/sqlite-store.ts +160 -10
  138. package/src/be/memory/task-learning.ts +79 -14
  139. package/src/be/memory/types.ts +24 -1
  140. package/src/be/migrations/279_backfill_learning_expiry.sql +15 -0
  141. package/src/be/migrations/281_model_profiles_pr2.sql +28 -0
  142. package/src/be/migrations/283_workflow_run_definitions.sql +14 -0
  143. package/src/be/model-profile-check.ts +284 -0
  144. package/src/be/model-tier-resolution.ts +112 -12
  145. package/src/be/multi-runtime.ts +27 -0
  146. package/src/be/runtime-pools/routing.ts +52 -4
  147. package/src/be/scripts/typecheck.ts +1 -0
  148. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +552 -0
  149. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +389 -14
  150. package/src/be/seed-scripts/catalog/dreaming-memtax.ts +6 -3
  151. package/src/be/seed-scripts/index.ts +9 -0
  152. package/src/be/steering.ts +8 -2
  153. package/src/commands/onboard/agent-fs-version.ts +1 -1
  154. package/src/commands/runner.ts +32 -1
  155. package/src/fs/provider.ts +17 -3
  156. package/src/heartbeat/heartbeat.ts +12 -1
  157. package/src/heartbeat/index.ts +1 -0
  158. package/src/http/agents.ts +56 -4
  159. package/src/http/apps.ts +3 -1
  160. package/src/http/config.ts +2 -6
  161. package/src/http/index.ts +2 -3
  162. package/src/http/model-profiles.ts +58 -10
  163. package/src/http/poll.ts +36 -3
  164. package/src/http/schedules.ts +42 -3
  165. package/src/http/tasks.ts +37 -12
  166. package/src/http/workflows.ts +15 -2
  167. package/src/prompts/session-templates.ts +1 -1
  168. package/src/providers/acp-targets.ts +11 -6
  169. package/src/providers/amp-adapter.ts +1 -1
  170. package/src/providers/claude-sdk-session.ts +132 -23
  171. package/src/providers/codex-skill-resolver.ts +10 -4
  172. package/src/providers/cursor-adapter.ts +1 -1
  173. package/src/providers/devin-skill-resolver.ts +5 -5
  174. package/src/providers/dsh-adapter.ts +1 -1
  175. package/src/scheduler/schedule-task.ts +1 -0
  176. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  177. package/src/scripts-runtime/swarm-sdk.ts +18 -1
  178. package/src/scripts-runtime/types/stdlib.d.ts +1 -0
  179. package/src/scripts-runtime/types/swarm-sdk.d.ts +1 -0
  180. package/src/server.ts +2 -0
  181. package/src/slack/app.ts +93 -0
  182. package/src/slack/inbound-dispatch.ts +18 -1
  183. package/src/slack/workspace-guard.ts +345 -0
  184. package/src/tasks/task-terminal-effects.ts +4 -0
  185. package/src/tasks/worker-follow-up.ts +102 -2
  186. package/src/tests/acp-adapter.test.ts +82 -0
  187. package/src/tests/apps-icon.test.ts +120 -0
  188. package/src/tests/chained-task-follow-up.test.ts +248 -0
  189. package/src/tests/check-pr-body.test.ts +40 -0
  190. package/src/tests/claude-sdk-lifecycle.test.ts +216 -1
  191. package/src/tests/claude-sdk-process.fixture.ts +57 -0
  192. package/src/tests/codex-skill-resolver.test.ts +31 -0
  193. package/src/tests/credentials-allowlist.test.ts +470 -0
  194. package/src/tests/db-task-read-contract.test.ts +5 -0
  195. package/src/tests/db-task-write-contract.test.ts +5 -0
  196. package/src/tests/deferred-wake-follow-up.test.ts +47 -0
  197. package/src/tests/docs-index-footprint.test.js +3 -3
  198. package/src/tests/dreaming-learnings.test.ts +1395 -0
  199. package/src/tests/dsh-adapter.test.ts +1 -1
  200. package/src/tests/explicit-model-validation.test.ts +2 -0
  201. package/src/tests/fs-provider.test.ts +42 -0
  202. package/src/tests/heartbeat.test.ts +28 -1
  203. package/src/tests/human-free-reclassify.test.ts +5 -1
  204. package/src/tests/list-endpoint-slimming.test.ts +17 -0
  205. package/src/tests/migration-283-workflow-run-definitions.test.ts +69 -0
  206. package/src/tests/model-profile-check.test.ts +387 -0
  207. package/src/tests/model-profiles-api.test.ts +528 -1
  208. package/src/tests/profile-claim.test.ts +415 -3
  209. package/src/tests/profile-tier-alias.test.ts +382 -0
  210. package/src/tests/schedule-profile.test.ts +359 -0
  211. package/src/tests/script-connections.test.ts +6 -0
  212. package/src/tests/script-per-script-executor.test.ts +1 -0
  213. package/src/tests/scripts-sdk-bridge-tool-failure.test.ts +141 -0
  214. package/src/tests/seed-scripts.test.ts +2 -2
  215. package/src/tests/slack-inbound-receipts.test.ts +22 -2
  216. package/src/tests/slack-socket-ack.test.ts +16 -1
  217. package/src/tests/slack-workspace-guard.test.ts +905 -0
  218. package/src/tests/steering-core.test.ts +40 -0
  219. package/src/tests/store-progress-learning.test.ts +605 -20
  220. package/src/tests/tool-annotations.test.ts +1 -1
  221. package/src/tests/workflow-convergence.test.ts +46 -40
  222. package/src/tests/workflow-definition-pinning-recovery.test.ts +552 -0
  223. package/src/tests/workflow-definition-pinning.test.ts +645 -0
  224. package/src/tests/workflow-executors.test.ts +16 -7
  225. package/src/tests/workflow-foreach.test.ts +43 -20
  226. package/src/tests/workflow-notify-slack-ready.test.ts +161 -0
  227. package/src/tests/workflow-profile.test.ts +328 -0
  228. package/src/tools/app-upsert.ts +1 -1
  229. package/src/tools/memory-edit.ts +2 -1
  230. package/src/tools/model-profiles/check-model-profile.ts +63 -0
  231. package/src/tools/schedules/create-schedule.ts +45 -4
  232. package/src/tools/schedules/patch-schedule.ts +50 -4
  233. package/src/tools/schedules/update-schedule.ts +50 -4
  234. package/src/tools/send-task.ts +17 -2
  235. package/src/tools/store-progress.ts +15 -3
  236. package/src/tools/task-action.ts +9 -1
  237. package/src/tools/templates.ts +13 -0
  238. package/src/tools/tool-config.ts +2 -1
  239. package/src/tools/utils.ts +61 -4
  240. package/src/tools/workflows/create-workflow.ts +1 -1
  241. package/src/tools/workflows/retry-workflow-run.ts +1 -1
  242. package/src/tools/workflows/update-workflow.ts +10 -1
  243. package/src/types.ts +56 -1
  244. package/src/utils/credentials.ts +89 -12
  245. package/src/workflows/engine.ts +10 -1
  246. package/src/workflows/executors/agent-task.ts +21 -2
  247. package/src/workflows/executors/foreach.ts +4 -1
  248. package/src/workflows/executors/notify.ts +62 -6
  249. package/src/workflows/executors/sub-workflow.ts +1 -1
  250. package/src/workflows/executors/swarm-script.ts +4 -1
  251. package/src/workflows/foreach-driver.ts +8 -5
  252. package/src/workflows/limits.ts +2 -1
  253. package/src/workflows/model-validation.ts +27 -2
  254. package/src/workflows/patch-definition.ts +3 -1
  255. package/src/workflows/recovery.ts +6 -6
  256. package/src/workflows/resume.ts +9 -9
  257. package/src/workflows/retry-poller.ts +2 -2
  258. package/templates/skills/apps/SKILL.md +2 -0
  259. package/templates/skills/apps/content.md +2 -0
  260. package/templates/skills/code-quality/content.md +12 -0
  261. package/templates/skills/memory/content.md +8 -0
  262. package/templates/skills/scheduling/config.json +1 -1
  263. package/templates/skills/scheduling/content.md +2 -2
  264. package/templates/skills/swarm-docs/content.md +4 -0
  265. package/templates/skills/swarm-extensions/content.md +1 -1
  266. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  267. package/templates/skills/swarm-scripts/content.md +1 -1
  268. package/templates/skills/work-on-task/SKILL.md +2 -0
  269. package/templates/skills/work-on-task/content.md +2 -0
  270. package/templates/workflows/dreaming/content.md +174 -7
  271. package/dist/acp-adapter-srfhs1s9.js +0 -16
  272. package/dist/cli-bzvs88tv.js +0 -339
  273. package/dist/cli-cyn9v8zr.js +0 -748
  274. package/dist/cli-ed6yqpf1.js +0 -779
  275. package/dist/handlers-17wha3ze.js +0 -33
  276. package/dist/heartbeat-gwewgdms.js +0 -42
  277. package/dist/index-8arwq8mw.js +0 -34
  278. package/dist/index-tpw054az.js +0 -38
  279. package/dist/index-waq75j2j.js +0 -31
  280. package/dist/lead-re73kdgc.js +0 -72
  281. package/dist/worker-r8mz7a65.js +0 -72
@@ -337,6 +337,7 @@ declare module "swarm-sdk" {
337
337
  }): Promise<unknown>;
338
338
  // --- model profiles ---
339
339
  modelProfile_list(args?: { harness?: string }): Promise<unknown>;
340
+ modelProfile_check(args: { agentId: string; profile: string }): Promise<unknown>;
340
341
  // --- slack ---
341
342
  slack_read(args?: {
342
343
  inboxMessageId?: string;
@@ -319,6 +319,7 @@ declare module "swarm-sdk" {
319
319
  }): Promise<unknown>;
320
320
  // --- model profiles ---
321
321
  modelProfile_list(args?: { harness?: string }): Promise<unknown>;
322
+ modelProfile_check(args: { agentId: string; profile: string }): Promise<unknown>;
322
323
  // --- slack ---
323
324
  slack_read(args?: {
324
325
  inboxMessageId?: string;
package/src/server.ts CHANGED
@@ -85,6 +85,7 @@ import {
85
85
  registerModelCatalogOverlayUpsertTool,
86
86
  registerModelCatalogRefreshTool,
87
87
  } from "./tools/model-catalog";
88
+ import { registerCheckModelProfileTool } from "./tools/model-profiles/check-model-profile";
88
89
  import { registerListModelProfilesTool } from "./tools/model-profiles/list-model-profiles";
89
90
  import { registerMyAgentInfoTool } from "./tools/my-agent-info";
90
91
  import { registerGetOauthAccessTokenTool } from "./tools/oauth-access-token";
@@ -492,6 +493,7 @@ export async function createServer(
492
493
  registerGetMetricsTool(server);
493
494
  registerSendTaskTool(server);
494
495
  registerListModelProfilesTool(server);
496
+ registerCheckModelProfileTool(server);
495
497
  registerGetTaskDetailsTool(server);
496
498
  registerStoreProgressTool(server);
497
499
  registerMyAgentInfoTool(server);
package/src/slack/app.ts CHANGED
@@ -16,6 +16,13 @@ import { installSocketAckRecovery } from "./socket-ack";
16
16
  import { fenceSocketModeClient, type SlackSocketFence } from "./socket-fence";
17
17
  import { getSlackSocketModeBlockReason, SLACK_DEV_SOCKET_MODE_OPT_IN } from "./socket-mode-guard";
18
18
  import { startTaskWatcher, stopTaskWatcher } from "./watcher";
19
+ import {
20
+ getSlackWorkspaceIdentity,
21
+ installSocketWorkspaceGate,
22
+ isSlackEnterpriseInstall,
23
+ resolveSlackIdentity,
24
+ setSlackWorkspaceIdentitySource,
25
+ } from "./workspace-guard";
19
26
 
20
27
  let app: App | null = null;
21
28
  let receiver: SocketModeReceiver | null = null;
@@ -30,6 +37,14 @@ let lifecycleGeneration = 0;
30
37
  // Last sign of life on the current socket: Slack's hello or any envelope.
31
38
  let lastSocketActivityAt: number | null = null;
32
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;
47
+
33
48
  const SOCKET_EVENT_STATES: Record<string, SlackConnectionState> = {
34
49
  connecting: "connecting",
35
50
  reconnecting: "connecting",
@@ -351,6 +366,9 @@ export async function initSlackApp(): Promise<App | null> {
351
366
  receiver,
352
367
  socketMode: true,
353
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,
354
372
  ...(clientOptions ? { clientOptions } : {}),
355
373
  });
356
374
 
@@ -358,6 +376,14 @@ export async function initSlackApp(): Promise<App | null> {
358
376
  // them back to Bolt, so a crash or a failing listener leaves recoverable work.
359
377
  inboundDrain = installSocketAckRecovery(receiver.client, app);
360
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
+
361
387
  // Failed validation must remain retryable without requiring stopSlackApp().
362
388
  initialized = true;
363
389
 
@@ -399,6 +425,21 @@ export async function startSlackApp(): Promise<boolean> {
399
425
 
400
426
  const current = app;
401
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;
402
443
  // Arm before app.start(): a start that throws is retried by the watchdog.
403
444
  startSocketWatchdog();
404
445
  // Establish the durable cutoff before Socket Mode can deliver new asks.
@@ -426,6 +467,49 @@ export async function startSlackApp(): Promise<boolean> {
426
467
  return false;
427
468
  }
428
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
+
429
513
  /**
430
514
  * Stop the app and disarm the watchdog. Takes the Slack lifecycle lock, so a
431
515
  * watchdog restart in flight finishes first and cannot bring the app back
@@ -494,14 +578,23 @@ function detachSlackApp(): App | null {
494
578
  socketFence?.retire();
495
579
  socketFence = null;
496
580
  lifecycleGeneration += 1;
581
+ clearStartRetry();
582
+ startRetryAttempt = 0;
583
+ boltInitialized = false;
497
584
  stopTaskWatcher();
498
585
  inboundDrain?.stop();
499
586
  inboundDrain = null;
500
587
  const detached = app;
501
588
  app = null;
502
589
  receiver = null;
590
+ setSlackWorkspaceIdentitySource(null);
503
591
  lastSocketActivityAt = null;
504
592
  setSlackConnectionState("disconnected");
505
593
  initialized = false;
506
594
  return detached;
507
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;
600
+ }
@@ -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();
@@ -0,0 +1,345 @@
1
+ import { isEnvFlagEnabled } from "../utils/env-flag";
2
+
3
+ /**
4
+ * Process only inbound Slack deliveries proven to belong to this swarm's
5
+ * installation.
6
+ *
7
+ * Socket Mode sends each payload to any one of the app's open connections,
8
+ * whatever workspace it came from. When several swarms share one Slack app
9
+ * (each with its own bot token but the same app-level token), a swarm receives
10
+ * other workspaces' deliveries, and Bolt does not filter them: with a single
11
+ * bot token its `authorize` returns that token for every source.
12
+ *
13
+ * Decisions:
14
+ * - The check runs on the raw socket envelope, before Bolt acks it
15
+ * (`installSocketWorkspaceGate`). A delivery that is not proven ours is
16
+ * neither acked nor dispatched. Slack retries an unacked Events API envelope,
17
+ * and each retry can land on another connection of the app, so the owner can
18
+ * still receive it. Acking and dropping would lose it for good. Interactive
19
+ * payloads and slash commands are not retried; the user sees an error instead
20
+ * of a silent drop.
21
+ * - Fail closed. The socket opens only after this swarm's identity resolved
22
+ * (`auth.test`). Without an identity, or for a payload with no installation
23
+ * field, nothing passes.
24
+ * - A workspace install owns a delivery only when the payload names its
25
+ * workspace (`team_id`) and does not mark the delivery as an org-wide
26
+ * install. An enterprise id alone never matches a workspace install.
27
+ * - Whether this swarm's token is an org-wide Enterprise install comes from the
28
+ * installation's OAuth metadata (`is_enterprise_install` in the
29
+ * `oauth.v2.access` response), set as `SLACK_ENTERPRISE_INSTALL`. `auth.test`
30
+ * supplies only the ids. An org install owns a delivery that names its
31
+ * enterprise and is marked as an org-wide install.
32
+ * - `is_enterprise_install` is optional on interactive payloads and on slash
33
+ * commands (Bolt's `SlashCommand` declares it as a string, and Bolt parses
34
+ * "true" for commands), though the docs' slash command example omits it.
35
+ * Without it, exactly one installation claims the delivery, the one Slack's
36
+ * own SDK would route it to:
37
+ * - A payload that names the bot it belongs to (`message.bot_id` on a button,
38
+ * `view.bot_id` on a view) belongs to the installation with that bot
39
+ * (`auth.test` `bot_id`). Each installation has its own bot.
40
+ * - Otherwise it belongs to the workspace it names, as Slack's own SDK reads
41
+ * it: Bolt (`isBodyWithTypeEnterpriseInstall`) treats a missing flag as a
42
+ * workspace install, and `@slack/oauth` resolves it to that workspace's
43
+ * installation. An org install claims a flag-less delivery only when it
44
+ * names no workspace. A swarm cannot see the other installations of a
45
+ * shared app, so any rule that also let an org install claim a named
46
+ * workspace would give some deliveries two owners.
47
+ */
48
+
49
+ export interface SlackWorkspaceIdentity {
50
+ teamId: string | null;
51
+ enterpriseId: string | null;
52
+ /** Org-wide Enterprise install, from trusted OAuth metadata. */
53
+ isEnterpriseInstall: boolean;
54
+ /** This installation's bot (`auth.test` `bot_id`). */
55
+ botId?: string;
56
+ }
57
+
58
+ /** One installation a payload says it was delivered for. */
59
+ export interface InboundInstallation {
60
+ teamId: string | null;
61
+ enterpriseId: string | null;
62
+ /** null when the payload does not say. */
63
+ isEnterpriseInstall: boolean | null;
64
+ /** The bot whose message or view the payload came from, when it names one. */
65
+ botId?: string;
66
+ }
67
+
68
+ export type InboundOwnership =
69
+ | { own: true }
70
+ | { own: false; reason: "foreign_workspace" | "unverified_workspace" };
71
+
72
+ type Body = Record<string, unknown>;
73
+
74
+ function asRecord(value: unknown): Body | undefined {
75
+ return value && typeof value === "object" ? (value as Body) : undefined;
76
+ }
77
+
78
+ function asId(value: unknown): string | null {
79
+ return typeof value === "string" && value.length > 0 ? value : null;
80
+ }
81
+
82
+ /** Interactive payloads carry a boolean; slash commands carry "true"/"false". */
83
+ function asFlag(value: unknown): boolean | null {
84
+ if (value === true || value === "true") return true;
85
+ if (value === false || value === "false") return false;
86
+ return null;
87
+ }
88
+
89
+ function toInstallation(
90
+ teamId: unknown,
91
+ enterpriseId: unknown,
92
+ flag: unknown,
93
+ ): InboundInstallation | null {
94
+ const installation = {
95
+ teamId: asId(teamId),
96
+ enterpriseId: asId(enterpriseId),
97
+ isEnterpriseInstall: asFlag(flag),
98
+ };
99
+ return installation.teamId || installation.enterpriseId ? installation : null;
100
+ }
101
+
102
+ /**
103
+ * Installations an inbound payload was delivered for.
104
+ *
105
+ * Events API envelopes carry `authorizations`, the installation the event was
106
+ * delivered to. They are the only source for events: in a Slack Connect channel
107
+ * the top-level `team_id` can name the partner workspace. Interactive, view and
108
+ * shortcut payloads carry `team.id` / `enterprise.id` (or `team.enterprise_id`)
109
+ * and an optional `is_enterprise_install`; `team` is null for an org-wide
110
+ * install. A view opened from a Slack Connect channel names the installing
111
+ * workspace in `view.app_installed_team_id`, as Bolt reads it. Slash commands
112
+ * carry `team_id` / `enterprise_id`, and the documented payload has no flag.
113
+ */
114
+ export function readInboundInstallations(body: unknown): InboundInstallation[] {
115
+ const record = asRecord(body);
116
+ if (!record) return [];
117
+
118
+ const authorizations = Array.isArray(record.authorizations) ? record.authorizations : [];
119
+ const fromAuthorizations: InboundInstallation[] = [];
120
+ for (const entry of authorizations) {
121
+ const authorization = asRecord(entry);
122
+ const installation = toInstallation(
123
+ authorization?.team_id,
124
+ authorization?.enterprise_id,
125
+ authorization?.is_enterprise_install,
126
+ );
127
+ if (installation) fromAuthorizations.push(installation);
128
+ }
129
+ // An Events API envelope without authorizations cannot be attributed.
130
+ if (fromAuthorizations.length > 0 || record.type === "event_callback") return fromAuthorizations;
131
+
132
+ const team = asRecord(record.team);
133
+ const view = asRecord(record.view);
134
+ const installation = toInstallation(
135
+ asId(view?.app_installed_team_id) ?? record.team_id ?? team?.id,
136
+ record.enterprise_id ?? asRecord(record.enterprise)?.id ?? team?.enterprise_id,
137
+ record.is_enterprise_install,
138
+ );
139
+ if (!installation) return [];
140
+ // A button's message, or a view, was posted or opened by one installation's
141
+ // bot. A message shortcut's message can be anyone's, so it proves nothing.
142
+ const botId =
143
+ asId(view?.bot_id) ??
144
+ (record.type === "block_actions" ? asId(asRecord(record.message)?.bot_id) : null);
145
+ return [botId ? { ...installation, botId } : installation];
146
+ }
147
+
148
+ /** Does this swarm's installation own the delivery? Anything unproven is not ours. */
149
+ export function classifyInboundOwnership(
150
+ identity: SlackWorkspaceIdentity | null,
151
+ installations: InboundInstallation[],
152
+ ): InboundOwnership {
153
+ if (!identity || installations.length === 0) {
154
+ return { own: false, reason: "unverified_workspace" };
155
+ }
156
+ // The two branches are complementary: a workspace install and an org install
157
+ // granted that workspace never both claim one delivery.
158
+ const owns = (installation: InboundInstallation): boolean => {
159
+ if (identity.isEnterpriseInstall) {
160
+ if (identity.enterpriseId === null || installation.enterpriseId !== identity.enterpriseId) {
161
+ return false;
162
+ }
163
+ if (installation.isEnterpriseInstall !== null) return installation.isEnterpriseInstall;
164
+ if (installation.botId) return installation.botId === identity.botId;
165
+ // A flag-less delivery naming a workspace is that workspace's install's.
166
+ return installation.teamId === null;
167
+ }
168
+ if (identity.teamId === null || installation.teamId !== identity.teamId) return false;
169
+ if (installation.isEnterpriseInstall !== null) return !installation.isEnterpriseInstall;
170
+ if (installation.botId) return installation.botId === identity.botId;
171
+ return true;
172
+ };
173
+ return installations.some(owns) ? { own: true } : { own: false, reason: "foreign_workspace" };
174
+ }
175
+
176
+ /** The type label logged for a withheld delivery. Never message text. */
177
+ export function inboundPayloadType(body: unknown): string {
178
+ const record = asRecord(body);
179
+ if (!record) return "unknown";
180
+ const eventType = asRecord(record.event)?.type;
181
+ if (typeof eventType === "string") return `event:${eventType}`;
182
+ if (typeof record.command === "string") return "command";
183
+ return typeof record.type === "string" ? record.type : "unknown";
184
+ }
185
+
186
+ // ─── Identity of this swarm's installation ───────────────────────────────────
187
+
188
+ /** Documented `auth.test` fields the guard reads. */
189
+ export interface SlackAuthTestResult {
190
+ team_id?: string;
191
+ enterprise_id?: string;
192
+ bot_id?: string;
193
+ }
194
+
195
+ /** The Web API call that resolves this swarm's identity. */
196
+ export interface SlackIdentityClient {
197
+ auth: { test(): Promise<SlackAuthTestResult> };
198
+ }
199
+
200
+ /** Resolve this swarm's identity from `auth.test`. Throws on any failure, so the socket stays closed. */
201
+ export async function resolveSlackIdentity(
202
+ client: SlackIdentityClient,
203
+ isEnterpriseInstall: boolean,
204
+ ): Promise<SlackWorkspaceIdentity> {
205
+ return identityFromAuthTest(await client.auth.test(), isEnterpriseInstall);
206
+ }
207
+
208
+ /** `SLACK_ENTERPRISE_INSTALL`: the bot token is an org-wide install (`oauth.v2.access`). */
209
+ export function isSlackEnterpriseInstall(env: NodeJS.ProcessEnv = process.env): boolean {
210
+ return isEnvFlagEnabled("SLACK_ENTERPRISE_INSTALL", false, env);
211
+ }
212
+
213
+ /** Build the identity, or throw when `auth.test` lacks the id the install mode needs. */
214
+ export function identityFromAuthTest(
215
+ result: SlackAuthTestResult,
216
+ isEnterpriseInstall: boolean,
217
+ ): SlackWorkspaceIdentity {
218
+ const teamId = asId(result.team_id);
219
+ const enterpriseId = asId(result.enterprise_id);
220
+ const botId = asId(result.bot_id);
221
+ if (isEnterpriseInstall && !enterpriseId) {
222
+ throw new Error("SLACK_ENTERPRISE_INSTALL is set but auth.test returned no enterprise_id");
223
+ }
224
+ if (!isEnterpriseInstall && !teamId) {
225
+ throw new Error("auth.test returned no team_id");
226
+ }
227
+ return {
228
+ teamId: isEnterpriseInstall ? null : teamId,
229
+ enterpriseId,
230
+ isEnterpriseInstall,
231
+ ...(botId ? { botId } : {}),
232
+ };
233
+ }
234
+
235
+ let resolveIdentity: (() => Promise<SlackWorkspaceIdentity>) | null = null;
236
+ let identity: SlackWorkspaceIdentity | null = null;
237
+ let pending: Promise<SlackWorkspaceIdentity | null> | null = null;
238
+
239
+ /** Register how to resolve this swarm's identity. Clears any cached identity. */
240
+ export function setSlackWorkspaceIdentitySource(
241
+ source: (() => Promise<SlackWorkspaceIdentity>) | null,
242
+ ): void {
243
+ resolveIdentity = source;
244
+ identity = null;
245
+ pending = null;
246
+ }
247
+
248
+ /** The resolved identity, or null. Never calls Slack. */
249
+ export function getCachedSlackWorkspaceIdentity(): SlackWorkspaceIdentity | null {
250
+ return identity;
251
+ }
252
+
253
+ /**
254
+ * Resolve this swarm's identity, or null when no source is registered or the
255
+ * lookup failed. A success is cached; a failure is retried on the next call.
256
+ */
257
+ export async function getSlackWorkspaceIdentity(): Promise<SlackWorkspaceIdentity | null> {
258
+ if (identity) return identity;
259
+ if (!resolveIdentity) return null;
260
+ if (pending) return pending;
261
+
262
+ const source = resolveIdentity;
263
+ pending = (async () => {
264
+ try {
265
+ const resolved = await source();
266
+ // A source swapped mid-call (stop/start) must not cache the old identity.
267
+ if (resolveIdentity !== source) return null;
268
+ identity = resolved;
269
+ console.log(
270
+ `[Slack] Workspace guard: team=${resolved.teamId ?? "none"} enterprise=${resolved.enterpriseId ?? "none"} enterpriseInstall=${resolved.isEnterpriseInstall}`,
271
+ );
272
+ return resolved;
273
+ } catch (error) {
274
+ const message = error instanceof Error ? error.message : String(error);
275
+ console.error(`[Slack] Workspace guard: identity lookup failed: ${message}`);
276
+ return null;
277
+ } finally {
278
+ // A source swapped mid-call already cleared or replaced `pending`.
279
+ if (resolveIdentity === source) pending = null;
280
+ }
281
+ })();
282
+ return pending;
283
+ }
284
+
285
+ const WITHHELD_LOG_INTERVAL_MS = 60_000;
286
+ const lastWithheldLogAt = new Map<string, number>();
287
+
288
+ /**
289
+ * Classify a delivery against `identity` and log the ones that are not ours:
290
+ * team, enterprise and payload type only, at most once a minute per key.
291
+ */
292
+ export function checkInboundWorkspace(
293
+ body: unknown,
294
+ own: SlackWorkspaceIdentity | null = identity,
295
+ ): InboundOwnership {
296
+ const installations = readInboundInstallations(body);
297
+ const ownership = classifyInboundOwnership(own, installations);
298
+ if (ownership.own) return ownership;
299
+
300
+ const team = installations.map((i) => i.teamId ?? "-").join(",") || "none";
301
+ const enterprise = installations.map((i) => i.enterpriseId ?? "-").join(",") || "none";
302
+ const type = inboundPayloadType(body);
303
+ const key = `${ownership.reason}|${team}|${enterprise}|${type}`;
304
+ const now = Date.now();
305
+ if (now - (lastWithheldLogAt.get(key) ?? 0) >= WITHHELD_LOG_INTERVAL_MS) {
306
+ if (lastWithheldLogAt.size >= 1_000) lastWithheldLogAt.clear();
307
+ lastWithheldLogAt.set(key, now);
308
+ console.warn(
309
+ `[Slack] Withheld inbound delivery (${ownership.reason}): team=${team} enterprise=${enterprise} type=${type}`,
310
+ );
311
+ }
312
+ return ownership;
313
+ }
314
+
315
+ /** Minimal surface of the Socket Mode client the gate wraps. */
316
+ interface SocketEventEmitter {
317
+ emit(event: string | symbol, ...args: unknown[]): boolean;
318
+ }
319
+
320
+ /**
321
+ * Wrap the Socket Mode client so a `slack_event` envelope reaches Bolt (which
322
+ * acks it) only when it belongs to `getIdentity()`'s installation. Any other
323
+ * envelope is left unacked and undispatched, so Slack redelivers it.
324
+ *
325
+ * Install it after every other `emit` wrapper: the last one installed runs
326
+ * first, so nothing downstream sees, stores or acks a withheld envelope.
327
+ */
328
+ export function installSocketWorkspaceGate(
329
+ client: SocketEventEmitter,
330
+ getIdentity: () => SlackWorkspaceIdentity | null = getCachedSlackWorkspaceIdentity,
331
+ ): void {
332
+ const emit = client.emit.bind(client);
333
+ client.emit = (event: string | symbol, ...args: unknown[]): boolean => {
334
+ if (event !== "slack_event") return emit(event, ...args);
335
+ const body = (args[0] as { body?: unknown } | undefined)?.body;
336
+ if (checkInboundWorkspace(body, getIdentity()).own) return emit(event, ...args);
337
+ return true;
338
+ };
339
+ }
340
+
341
+ /** Test-only. */
342
+ export function resetSlackWorkspaceGuardForTests(): void {
343
+ setSlackWorkspaceIdentitySource(null);
344
+ lastWithheldLogAt.clear();
345
+ }
@@ -31,6 +31,8 @@ export async function runTaskTerminalEffects(args: {
31
31
  failureReason?: string;
32
32
  agentId?: string;
33
33
  persistMemory?: boolean;
34
+ /** Passed through to `createWorkerTaskFollowUp`; see `store-progress`. */
35
+ chainedTaskId?: string;
34
36
  }): Promise<void> {
35
37
  const { task, status, agentId, persistMemory } = args;
36
38
  const taskId = task.id;
@@ -160,6 +162,8 @@ export async function runTaskTerminalEffects(args: {
160
162
  status,
161
163
  output: safeOutput,
162
164
  failureReason: safeFailureReason,
165
+ chainedTaskId: args.chainedTaskId,
166
+ completingAgentId: agentId,
163
167
  });
164
168
  if (followUp) {
165
169
  console.log(