@desplega.ai/agent-swarm 2.10.0 → 2.11.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 (378) hide show
  1. package/dist/acp-adapter-weaaxey3.js +16 -0
  2. package/dist/{acp-targets-arrwv4f0.js → acp-targets-5wyy2b9m.js} +9 -9
  3. package/dist/{actions-y0d2n1c2.js → actions-4nxq386s.js} +24 -23
  4. package/dist/{agent-fs-provision-tpj7sktd.js → agent-fs-provision-v6enh76w.js} +4 -4
  5. package/dist/{amp-adapter-vmmnmw8d.js → amp-adapter-ze3x22qn.js} +3 -3
  6. package/dist/{anthropic-messages-zdca3gv1.js → anthropic-messages-88b7s3n9.js} +177 -25
  7. package/dist/{app-wb7w45dq.js → app-kyqt8ehw.js} +7 -6
  8. package/dist/{approval-notifications-7mqr6vbd.js → approval-notifications-a0db0esw.js} +7 -6
  9. package/dist/{assistant-gf60454p.js → assistant-9g5jzq25.js} +26 -25
  10. package/dist/{azure-openai-responses-b3y7fz36.js → azure-openai-responses-jeaas6x0.js} +10 -10
  11. package/dist/{boot-args-schema-qxmd59sr.js → boot-args-schema-d7fme4q1.js} +1 -1
  12. package/dist/{boot-reembed-wb44vc3s.js → boot-reembed-6wpazmpw.js} +1 -1
  13. package/dist/{boot-reembed-5tmeskj2.js → boot-reembed-jrwxeye2.js} +1 -1
  14. package/dist/{boot-scrub-sweep-25bxhnw4.js → boot-scrub-sweep-52h7yntp.js} +2 -2
  15. package/dist/{boot-seeds-nj9za0vk.js → boot-seeds-kb3dxjex.js} +4 -4
  16. package/dist/{boxd-wn235q80.js → boxd-jrrmkv3w.js} +2 -2
  17. package/dist/{claude-adapter-d3krpdyb.js → claude-adapter-0c0y8fqp.js} +8 -8
  18. package/dist/{claude-managed-adapter-t8nfgcgz.js → claude-managed-adapter-w2es07qq.js} +4 -4
  19. package/dist/{claude-managed-setup-7y4pwd81.js → claude-managed-setup-9ssb7ct4.js} +4 -4
  20. package/dist/{claude-sdk-session-d138zy0e.js → claude-sdk-session-p6t0gyse.js} +10941 -10412
  21. package/dist/{cli-p0n7b5rz.js → cli-075ccjh6.js} +344 -130
  22. package/dist/{cli-3caf7pmg.js → cli-0bgj4rh5.js} +3 -3
  23. package/dist/{cli-7r162fxe.js → cli-14xdms9a.js} +23 -17
  24. package/dist/{cli-rqx70rcz.js → cli-17qzb39j.js} +5 -2
  25. package/dist/{cli-y4ccxtz5.js → cli-1h4njv9y.js} +144 -6
  26. package/dist/{cli-6ym4jhzp.js → cli-27fat7st.js} +7 -7
  27. package/dist/{cli-k3q2va86.js → cli-2aacfdcn.js} +5 -5
  28. package/dist/{cli-vq2eg24x.js → cli-2gvdvsxj.js} +3 -3
  29. package/dist/{cli-sb4426be.js → cli-2jtfm8kh.js} +5 -5
  30. package/dist/{cli-6ehs4mta.js → cli-2z2c4k6q.js} +18 -4
  31. package/dist/{cli-6237rnyr.js → cli-3bpr3wks.js} +1 -1
  32. package/dist/{cli-5qhfv9rw.js → cli-453497a0.js} +44 -17
  33. package/dist/{cli-2rnd5j3t.js → cli-4aswccje.js} +2 -2
  34. package/dist/{cli-4ymxrwg5.js → cli-4dyzzkfb.js} +2 -2
  35. package/dist/{cli-p0c3vtch.js → cli-4g323fjh.js} +772 -515
  36. package/dist/{cli-3kd08rej.js → cli-4jjrhy48.js} +1 -1
  37. package/dist/{cli-fcfbct2j.js → cli-4kzp7r0q.js} +5 -5
  38. package/dist/{cli-kxn3747f.js → cli-4se3x6qm.js} +1 -26
  39. package/dist/{cli-zeh2mhkg.js → cli-5ptj757f.js} +1 -1
  40. package/dist/{cli-539h29es.js → cli-6a3j25xd.js} +224 -189
  41. package/dist/{cli-hnamkvnc.js → cli-6c9ve77f.js} +2 -2
  42. package/dist/{cli-3et6fmfe.js → cli-6n7y5ypy.js} +1 -1
  43. package/dist/{cli-8y43jx2r.js → cli-6p8p2e6r.js} +16 -9
  44. package/dist/{cli-zk7v5s89.js → cli-6tvh1fwq.js} +3 -3
  45. package/dist/{cli-p74md7t8.js → cli-7b7rxz22.js} +13 -15
  46. package/dist/{cli-5a6pqy45.js → cli-7e8sxqv5.js} +1 -1
  47. package/dist/{cli-6037prsx.js → cli-892y3vfp.js} +13 -13
  48. package/dist/cli-8mfdbdhe.js +43 -0
  49. package/dist/{cli-s1zqk1aj.js → cli-8zmpwe79.js} +15 -9
  50. package/dist/{cli-zcfpsfzf.js → cli-96234j5w.js} +3 -3
  51. package/dist/{cli-1z4qggfe.js → cli-9fvk9mv8.js} +30 -21
  52. package/dist/{cli-7mv4h3sn.js → cli-9g12h1aq.js} +2 -2
  53. package/dist/{cli-aw83sr40.js → cli-9knhkkgr.js} +3 -3
  54. package/dist/{cli-5mpy301f.js → cli-9t7syepg.js} +1 -1
  55. package/dist/{cli-qj39vrc6.js → cli-9yjhshah.js} +1 -1
  56. package/dist/{cli-6cwr32fe.js → cli-a02habn6.js} +422 -140
  57. package/dist/{cli-7evph51z.js → cli-a49frv85.js} +2 -2
  58. package/dist/{cli-3f8zbtqa.js → cli-a6q6x15h.js} +9 -8
  59. package/dist/{cli-j6te8keb.js → cli-atm0hkes.js} +8 -8
  60. package/dist/{cli-9fjr27ez.js → cli-b82a13ga.js} +13 -13
  61. package/dist/{cli-7zm3b3f5.js → cli-bf0t77nf.js} +1 -1
  62. package/dist/{cli-2xv18ywz.js → cli-bmqp0ser.js} +2 -2
  63. package/dist/{cli-mk7c5ac4.js → cli-bq97k63w.js} +2 -2
  64. package/dist/{cli-vfqvrd82.js → cli-cstggwq7.js} +2 -2
  65. package/dist/{cli-md50mj0r.js → cli-czvvnfr9.js} +3 -3
  66. package/dist/{cli-b6px1k1q.js → cli-dd2k2mcd.js} +1 -1
  67. package/dist/{cli-fq2rr3jb.js → cli-djt6wmrc.js} +6 -6
  68. package/dist/{cli-tsa40663.js → cli-ebqx630g.js} +3 -3
  69. package/dist/{cli-z0m452jr.js → cli-f7dhm7hh.js} +1 -1
  70. package/dist/{cli-mys27d03.js → cli-f8yhybxr.js} +3 -3
  71. package/dist/{cli-5gpqgs8b.js → cli-fwjwkw66.js} +2 -2
  72. package/dist/{cli-gabsjg8x.js → cli-g56fxddf.js} +1 -1
  73. package/dist/{cli-y8p78ekx.js → cli-h2qtafm4.js} +18 -18
  74. package/dist/{cli-psffsanb.js → cli-ha4ek2nb.js} +6 -1
  75. package/dist/{cli-th1dkc2v.js → cli-hnh8erra.js} +2 -2
  76. package/dist/{cli-w16kwbzw.js → cli-htymm48w.js} +1 -1
  77. package/dist/{cli-124ntmf0.js → cli-j2r1apqm.js} +138 -59
  78. package/dist/{cli-43ms35q9.js → cli-k3c13za2.js} +3 -3
  79. package/dist/{cli-54vrpgm0.js → cli-k3facve0.js} +8 -5
  80. package/dist/{cli-v8z0yga9.js → cli-k4r5sfaj.js} +4 -4
  81. package/dist/{cli-91pkxres.js → cli-kbm659dk.js} +2 -2
  82. package/dist/{cli-q5srsxq2.js → cli-m00c47q6.js} +110 -27
  83. package/dist/{cli-3aaeb78m.js → cli-mhrr4d5b.js} +95 -10
  84. package/dist/{cli-xqdz5cqm.js → cli-mz7ycqn8.js} +1 -0
  85. package/dist/{cli-qrta34nb.js → cli-n6ygvrrm.js} +4 -4
  86. package/dist/{cli-k5yewqgd.js → cli-nbakg5xh.js} +3 -3
  87. package/dist/{cli-nstkanmx.js → cli-nc39ym5q.js} +8 -8
  88. package/dist/{cli-01k6wpr9.js → cli-p1a4khta.js} +7 -7
  89. package/dist/{cli-t9ga4qmb.js → cli-p8zqbbt1.js} +40 -33
  90. package/dist/{cli-v46zsvqk.js → cli-ph95yejc.js} +2 -2
  91. package/dist/{cli-k6nejceb.js → cli-q4z9s6zs.js} +2 -2
  92. package/dist/{cli-kbtzfrxj.js → cli-q71g5q39.js} +3 -3
  93. package/dist/{cli-vs9vdpy0.js → cli-qncx2r0s.js} +1 -1
  94. package/dist/{cli-hg42n3hx.js → cli-qrzq3hvg.js} +8 -8
  95. package/dist/{cli-x40a0w9j.js → cli-r813c7rb.js} +1 -1
  96. package/dist/{cli-kpgcm7xy.js → cli-ramn8jae.js} +1 -1
  97. package/dist/{cli-cc93xzes.js → cli-raqw9fw9.js} +28 -17
  98. package/dist/cli-rhsc2zyx.js +68 -0
  99. package/dist/{cli-8st34zhr.js → cli-rpmw4fsv.js} +57 -19
  100. package/dist/{cli-had1p04a.js → cli-rwgwen5v.js} +4 -4
  101. package/dist/{cli-tr27kwyg.js → cli-rytq7dm2.js} +261 -6
  102. package/dist/{cli-s1khw52h.js → cli-s9twe4x0.js} +66 -17
  103. package/dist/{cli-2v2zdm0a.js → cli-t2s7j5cy.js} +2 -2
  104. package/dist/{cli-nv4xsvmk.js → cli-tb4j757d.js} +7 -7
  105. package/dist/{cli-q2d3e1k1.js → cli-thd3005a.js} +1 -1
  106. package/dist/cli-tsfkcd4v.js +30 -0
  107. package/dist/{cli-jrbq4djp.js → cli-v3zcnr8g.js} +1 -1
  108. package/dist/{cli-zfqg6fzn.js → cli-vbppqvte.js} +3 -3
  109. package/dist/{cli-qx4f057j.js → cli-vy3fn0mz.js} +4 -4
  110. package/dist/{cli-7sf9sb0w.js → cli-w5dar1bk.js} +1 -1
  111. package/dist/{cli-w1q68d8x.js → cli-wz4e5am2.js} +9 -9
  112. package/dist/{cli-m9cvf7vs.js → cli-xqbqwpxr.js} +14 -14
  113. package/dist/{cli-2spnz7ye.js → cli-ynph3b70.js} +11137 -8332
  114. package/dist/{cli-43evxwj4.js → cli-yvzxbztc.js} +9 -4
  115. package/dist/{cli-vsw91x06.js → cli-yzxqwcvq.js} +3 -6
  116. package/dist/{cli-wafmk3fn.js → cli-zb1hff00.js} +12 -12
  117. package/dist/{cli-yab6sh8p.js → cli-zcghfsdg.js} +23 -4
  118. package/dist/{cli-wwp1bd3n.js → cli-zhn4r1rz.js} +519 -75
  119. package/dist/{cli-tvgqesec.js → cli-zqq57pgx.js} +4 -4
  120. package/dist/cli.js +28 -27
  121. package/dist/{cloudflare-workers-ai-system-one-4aysy6rh.js → cloudflare-workers-ai-system-one-w3m0fbf8.js} +2 -2
  122. package/dist/{codex-adapter-exfdbj73.js → codex-adapter-ssahg4h4.js} +8 -8
  123. package/dist/{codex-hook-59atdwd8.js → codex-hook-aqtj17yr.js} +1 -1
  124. package/dist/{codex-login-a239g1ah.js → codex-login-9c7aggxe.js} +1 -1
  125. package/dist/{codex-session-runner-xhznc4g3.js → codex-session-runner-xn63q3h7.js} +9 -9
  126. package/dist/{commands-d8g349v4.js → commands-ctey7tr5.js} +3 -3
  127. package/dist/{controller-mwgdmb8y.js → controller-rqhbppg9.js} +4 -4
  128. package/dist/{controllers-connect-5v7qx04j.js → controllers-connect-w3qbpbt1.js} +22 -21
  129. package/dist/{core-sxy4epp2.js → core-df1n049h.js} +19 -18
  130. package/dist/{cursor-adapter-p2q5h35d.js → cursor-adapter-r819hf1a.js} +2 -2
  131. package/dist/{db-wcw0b2j8.js → db-2ah39cyx.js} +2 -2
  132. package/dist/{db-qpganbeb.js → db-p5drc1d1.js} +3 -3
  133. package/dist/{devin-adapter-zp4tqq53.js → devin-adapter-bc6g0x29.js} +1 -1
  134. package/dist/{dispatcher-8d8s49yz.js → dispatcher-x6w14pde.js} +19 -18
  135. package/dist/{docker-09tkkg0n.js → docker-6c4reetq.js} +51 -14
  136. package/dist/{dsh-adapter-me0twn13.js → dsh-adapter-h8qn14n4.js} +2 -2
  137. package/dist/{e2b-sm28k0k3.js → e2b-jg7kyyef.js} +6 -6
  138. package/dist/{e2b-3v1e745x.js → e2b-z4ec0qve.js} +3 -3
  139. package/dist/{easter-egg-3d-wv7w5ty6.js → easter-egg-3d-1y6r9gxy.js} +1 -1
  140. package/dist/{embedding-space-e48xchqa.js → embedding-space-z6ptw3jk.js} +6 -6
  141. package/dist/{embeddings-tgq2afbq.js → embeddings-0sxb1d2h.js} +1 -1
  142. package/dist/{event-bus-xr83x566.js → event-bus-swr88jg5.js} +1 -1
  143. package/dist/{execute-8rhwrk7f.js → execute-6m1ex8ce.js} +8 -4
  144. package/dist/{external-channel-8bt3j2pm.js → external-channel-ezer7pk0.js} +2 -2
  145. package/dist/fx-adapter-zwmps9re.js +19 -0
  146. package/dist/{google-generative-ai-bh0djqjp.js → google-generative-ai-sw77egmr.js} +9 -9
  147. package/dist/{google-vertex-prjbw8dj.js → google-vertex-rrw93g8h.js} +9 -9
  148. package/dist/grok-adapter-q0avf919.js +19 -0
  149. package/dist/handlers-g5jq0e4q.js +36 -0
  150. package/dist/{heartbeat-x0056ra5.js → heartbeat-6c4fr49t.js} +22 -21
  151. package/dist/{hook-mrd2ayxv.js → hook-02rt5tvq.js} +8 -8
  152. package/dist/{hook-a7vmn2st.js → hook-t1c5avbv.js} +5 -5
  153. package/dist/{http-ym9c5svp.js → http-qa3h32a1.js} +2049 -148
  154. package/dist/index-1f6m47mq.js +37 -0
  155. package/dist/index-1p1mpqda.js +36 -0
  156. package/dist/{index-p46tvwtx.js → index-akbgsdhh.js} +25 -24
  157. package/dist/{index-ny60jcat.js → index-e42j998x.js} +16 -13
  158. package/dist/{index-b5wgnm78.js → index-kdmkfjt7.js} +4 -4
  159. package/dist/{index-01ns1pkw.js → index-kqv9ebfj.js} +1 -1
  160. package/dist/{index-9myfj74s.js → index-kzdqn3dd.js} +3 -3
  161. package/dist/{index-4a0670yh.js → index-p2f5xg64.js} +6 -6
  162. package/dist/{index-x6azjwm8.js → index-qpjk2hxk.js} +1 -1
  163. package/dist/index-tnkd410q.js +41 -0
  164. package/dist/{k8s-m56sw868.js → k8s-7jrh5va2.js} +73 -14
  165. package/dist/{keepalive-7yxg8z4c.js → keepalive-jmf6pn8c.js} +4 -4
  166. package/dist/lead-m5e7xt93.js +75 -0
  167. package/dist/{llama-cpp-classify-nfgswa1m.js → llama-cpp-classify-yvb8vh7w.js} +2 -2
  168. package/dist/{maintenance-6tefxmk1.js → maintenance-g7v15tj1.js} +1 -1
  169. package/dist/{mistral-conversations-tm2vd4gc.js → mistral-conversations-w4bncwbt.js} +7 -7
  170. package/dist/{node-7qsx5kvm.js → node-z67yjre7.js} +19 -13
  171. package/dist/{oauth-refresh-sweep-70cavc3a.js → oauth-refresh-sweep-ywgf8tbr.js} +3 -3
  172. package/dist/{onboard-fja65z08.js → onboard-m3fedypq.js} +3 -3
  173. package/dist/{openai-codex-responses-sxjv60xx.js → openai-codex-responses-70g39cgz.js} +20 -14
  174. package/dist/{openai-completions-0c7qnhsx.js → openai-completions-cv3hp4h5.js} +18 -11
  175. package/dist/{openai-decisions-ytp6w6xh.js → openai-decisions-fyq1p9f9.js} +2 -2
  176. package/dist/{openai-responses-a7h29chp.js → openai-responses-trsvnks6.js} +13 -11
  177. package/dist/{opencode-adapter-hakkm7yh.js → opencode-adapter-19ktcbb9.js} +7 -7
  178. package/dist/{openrouter-images-xr9gme9x.js → openrouter-images-0jj12a2q.js} +6 -6
  179. package/dist/{otel-impl-7zhnt6gj.js → otel-impl-3ehm1hgc.js} +2 -2
  180. package/dist/{pending-h01yzpx4.js → pending-fwj2fatd.js} +20 -19
  181. package/dist/{pi-messages-2j0fpqwq.js → pi-messages-zk3g4esn.js} +1 -1
  182. package/dist/{pi-mono-adapter-f52hz743.js → pi-mono-adapter-xdeesvc4.js} +18 -17
  183. package/dist/{pricing-refresh-fzxvk2zf.js → pricing-refresh-4j8dzvxg.js} +2 -2
  184. package/dist/{rbac-roles-9v6vhgbs.js → rbac-roles-8msjr07m.js} +3 -3
  185. package/dist/{rbac-roles-hfgh8sba.js → rbac-roles-n7t2acv8.js} +2 -2
  186. package/dist/{render-v2-1rgspxzf.js → render-v2-j7qggj8h.js} +7 -6
  187. package/dist/{resume-tqy61x24.js → resume-hj1mn65y.js} +9 -8
  188. package/dist/{runtime-exkxyx5f.js → runtime-z31mdsgv.js} +2 -2
  189. package/dist/{session-access-3act7vt4.js → session-access-w38fh09a.js} +4 -4
  190. package/dist/{session-source-backfill-82qe7fqq.js → session-source-backfill-ax6qxv20.js} +3 -3
  191. package/dist/{setup-ry1vfdef.js → setup-dsqmpfcr.js} +1 -1
  192. package/dist/thread-buffer-nf55vwx3.js +39 -0
  193. package/dist/tree-visibility-6vqmnr71.js +24 -0
  194. package/dist/{typesafe-system-one-vcfj2ak8.js → typesafe-system-one-qkvkgrcz.js} +2 -2
  195. package/dist/{user-merge-jobs-bx6bf7db.js → user-merge-jobs-mvheb3ed.js} +3 -3
  196. package/dist/{virtual-modules-s0rjzcqq.js → virtual-modules-w2qk2wew.js} +32 -10
  197. package/dist/{work-objects-z2e5tv03.js → work-objects-4ahy5es5.js} +22 -21
  198. package/dist/worker-ews1nyhw.js +75 -0
  199. package/dist/{worker-follow-up-y3xeg89w.js → worker-follow-up-1gs4aw7y.js} +19 -18
  200. package/dist/{x-wg164ss9.js → x-3wr8c5sh.js} +2 -2
  201. package/openapi.json +995 -49
  202. package/package.json +9 -8
  203. package/src/be/db/request-composition.ts +190 -0
  204. package/src/be/db/runtime.ts +15 -0
  205. package/src/be/db/slack-trees.ts +220 -10
  206. package/src/be/db/tasks/human-free.ts +3 -2
  207. package/src/be/db/workflow-run-retention.ts +101 -0
  208. package/src/be/db-client.ts +23 -1
  209. package/src/be/db-retention-defaults.ts +46 -0
  210. package/src/be/db-retention.ts +55 -6
  211. package/src/be/mcp-events/catalog.ts +108 -0
  212. package/src/be/mcp-events/dispatcher.ts +202 -0
  213. package/src/be/mcp-events/protocol.ts +296 -0
  214. package/src/be/mcp-events/store.ts +231 -0
  215. package/src/be/mcp-events/webhook.ts +226 -0
  216. package/src/be/memory/providers/sqlite-store.ts +110 -24
  217. package/src/be/memory/review-recall-filter.ts +22 -0
  218. package/src/be/memory/search-candidates.ts +5 -7
  219. package/src/be/memory/types.ts +5 -0
  220. package/src/be/migrations/322_runtime_pool_workspace.sql +8 -0
  221. package/src/be/migrations/323_slack_task_tree_visibility.sql +9 -0
  222. package/src/be/migrations/326_slack_reconcile_pages.sql +13 -0
  223. package/src/be/migrations/327_mcp_event_subscriptions.sql +57 -0
  224. package/src/be/migrations/329_workflow_run_retention.sql +9 -0
  225. package/src/be/migrations/330_request_composition.sql +22 -0
  226. package/src/be/model-profile-check.ts +1 -1
  227. package/src/be/multi-runtime.ts +32 -4
  228. package/src/be/runtime-pools/controllers.ts +18 -3
  229. package/src/be/runtime-pools/db.ts +15 -4
  230. package/src/be/runtime-pools/supervisor.ts +42 -2
  231. package/src/be/swarm-config-guard.ts +10 -2
  232. package/src/commands/context-preamble.ts +11 -4
  233. package/src/commands/credential-outcome-report.ts +33 -9
  234. package/src/commands/e2b-stack-wizard.tsx +12 -6
  235. package/src/commands/runner.ts +116 -12
  236. package/src/extensions/catalog.generated.json +1 -1
  237. package/src/github/app.ts +59 -14
  238. package/src/http/all-routes.ts +2 -0
  239. package/src/http/config.ts +2 -1
  240. package/src/http/core.ts +2 -0
  241. package/src/http/github-token.ts +66 -0
  242. package/src/http/index.ts +21 -0
  243. package/src/http/mcp-user.ts +11 -8
  244. package/src/http/mcp.ts +58 -42
  245. package/src/http/prompt-templates.ts +1 -0
  246. package/src/http/request-composition.ts +310 -0
  247. package/src/http/tasks.ts +6 -1
  248. package/src/http/tool-schema-estimate.ts +95 -0
  249. package/src/http/workflows.ts +29 -11
  250. package/src/integrations/chat-sdk/inbound.ts +2 -2
  251. package/src/prompts/base-prompt.ts +133 -7
  252. package/src/prompts/resolver.ts +41 -2
  253. package/src/providers/amp-adapter.ts +1 -1
  254. package/src/providers/opencode-adapter.ts +72 -1
  255. package/src/providers/opencode-swarm-plugin.ts +22 -3
  256. package/src/providers/pi-mono-adapter.ts +1 -0
  257. package/src/providers/pi-mono-extension.ts +71 -0
  258. package/src/providers/pricing-sources.md +4 -0
  259. package/src/providers/request-composition-hook.ts +312 -0
  260. package/src/providers/types.ts +5 -0
  261. package/src/runtime-providers/controller-protocol.ts +7 -0
  262. package/src/runtime-providers/docker.ts +80 -12
  263. package/src/runtime-providers/k8s.ts +111 -6
  264. package/src/runtime-providers/types.ts +17 -0
  265. package/src/scheduler/scheduler.ts +1 -1
  266. package/src/server-user.ts +16 -1
  267. package/src/slack/ack.ts +10 -5
  268. package/src/slack/actions.ts +3 -3
  269. package/src/slack/app.ts +2 -0
  270. package/src/slack/assistant.ts +4 -4
  271. package/src/slack/blocks.ts +3 -3
  272. package/src/slack/handlers.ts +3 -3
  273. package/src/slack/reaction-shortcode.ts +23 -2
  274. package/src/slack/render-v2.ts +297 -200
  275. package/src/slack/responses.ts +7 -5
  276. package/src/slack/thread-buffer.ts +3 -3
  277. package/src/slack/tree-visibility.ts +64 -0
  278. package/src/tasks/worker-follow-up.ts +127 -17
  279. package/src/tests/azure-devops-outbound.test.ts +47 -14
  280. package/src/tests/base-prompt.test.ts +149 -1
  281. package/src/tests/check-playwright-version.test.ts +33 -0
  282. package/src/tests/context-preamble-budget.test.ts +65 -0
  283. package/src/tests/credential-outcome-report.test.ts +81 -1
  284. package/src/tests/db-client.test.ts +22 -0
  285. package/src/tests/db-retention-defaults.test.ts +244 -0
  286. package/src/tests/db-retention.test.ts +2 -1
  287. package/src/tests/db-runtime.test.ts +2 -1
  288. package/src/tests/deploy-release-dispatch.test.ts +332 -0
  289. package/src/tests/e2b-stack-wizard.test.tsx +156 -0
  290. package/src/tests/entrypoint-chown-no-follow.test.ts +69 -0
  291. package/src/tests/entrypoint-repo-clone-target.test.ts +112 -0
  292. package/src/tests/env-flag.test.ts +4 -2
  293. package/src/tests/event-loop-lag.test.ts +12 -18
  294. package/src/tests/extensions-example-slack-reply-gate.test.ts +15 -0
  295. package/src/tests/fixtures/base-prompt-baseline-cases.ts +78 -0
  296. package/src/tests/fixtures/base-prompt-baseline.json +18 -0
  297. package/src/tests/github-app-worker-auth-helper.test.ts +325 -0
  298. package/src/tests/github-installation-token-route.test.ts +199 -0
  299. package/src/tests/mcp-user-events.test.ts +708 -0
  300. package/src/tests/memory-key-paths.test.ts +4 -1
  301. package/src/tests/memory-search-stall.test.ts +421 -0
  302. package/src/tests/migration-322-runtime-pool-workspace.test.ts +116 -0
  303. package/src/tests/migration-329-workflow-run-retention.test.ts +32 -0
  304. package/src/tests/model-profile-fallbacks.test.ts +236 -2
  305. package/src/tests/opencode-adapter.test.ts +86 -0
  306. package/src/tests/pi-mono-extension.test.ts +168 -0
  307. package/src/tests/preload-env.test.ts +61 -1
  308. package/src/tests/preload.ts +22 -0
  309. package/src/tests/prompt-template-resolver.test.ts +85 -0
  310. package/src/tests/reload-config.test.ts +45 -0
  311. package/src/tests/request-composition.test.ts +447 -0
  312. package/src/tests/runner-max-concurrent.test.ts +86 -0
  313. package/src/tests/runtime-pools-db.test.ts +80 -0
  314. package/src/tests/runtime-provider-registration.test.ts +8 -0
  315. package/src/tests/runtime-providers-docker.test.ts +192 -1
  316. package/src/tests/runtime-providers-k8s.test.ts +127 -0
  317. package/src/tests/runtime-remote-controller.test.ts +64 -1
  318. package/src/tests/runtime-supervisor.test.ts +101 -0
  319. package/src/tests/script-connections.test.ts +8 -0
  320. package/src/tests/slack-blocks.test.ts +18 -0
  321. package/src/tests/slack-empty-icon-config.test.ts +113 -0
  322. package/src/tests/slack-reaction-config.test.ts +38 -2
  323. package/src/tests/slack-render-v2-query-plans.test.ts +100 -1
  324. package/src/tests/slack-render-v2-reconcile.test.ts +75 -4
  325. package/src/tests/slack-render-v2.test.ts +683 -11
  326. package/src/tests/swarm-config-reserved-keys.test.ts +1 -0
  327. package/src/tests/task-session-prompts.test.ts +37 -0
  328. package/src/tests/user-delete-perf.test.ts +36 -9
  329. package/src/tests/webhook-filter.test.ts +327 -0
  330. package/src/tests/workflow-async-v2.test.ts +19 -16
  331. package/src/tests/workflow-definition-telemetry.test.ts +15 -5
  332. package/src/tests/workflow-e2e.test.ts +1 -9
  333. package/src/tests/workflow-finalization-races.test.ts +553 -0
  334. package/src/tests/workflow-foreach.test.ts +2 -0
  335. package/src/tests/workflow-hitl-routing.test.ts +26 -20
  336. package/src/tests/workflow-http-v2.test.ts +105 -2
  337. package/src/tests/workflow-idempotency.test.ts +41 -0
  338. package/src/tests/workflow-mcp-webhook-filter.test.ts +214 -0
  339. package/src/tests/workflow-parallel-park.test.ts +297 -0
  340. package/src/tests/workflow-retry-v2.test.ts +57 -21
  341. package/src/tests/workflow-retry-validation.test.ts +13 -13
  342. package/src/tests/workflow-runs-retention.test.ts +533 -0
  343. package/src/tests/workflow-script-principal.test.ts +7 -2
  344. package/src/tests/workflow-tla-races.test.ts +7 -2
  345. package/src/tests/workflow-triggers-v2.test.ts +201 -0
  346. package/src/tests/workflow-wait-builtin-events.test.ts +3 -1
  347. package/src/tests/workflow-wait-event.test.ts +28 -2
  348. package/src/tests/workflow-wait-poller.test.ts +94 -0
  349. package/src/tests/workflow-wait-time.test.ts +7 -3
  350. package/src/tests/workflow-wait.test.ts +26 -0
  351. package/src/tests/workflow-wait.ts +44 -0
  352. package/src/tools/workflows/create-workflow.ts +7 -3
  353. package/src/tools/workflows/update-workflow.ts +7 -3
  354. package/src/types.ts +200 -2
  355. package/src/utils/credentials.ts +7 -0
  356. package/src/workflows/checkpoint.ts +18 -0
  357. package/src/workflows/engine.ts +38 -10
  358. package/src/workflows/foreach-driver.ts +42 -4
  359. package/src/workflows/recovery.ts +6 -1
  360. package/src/workflows/resume.ts +11 -3
  361. package/src/workflows/retry-poller.ts +17 -4
  362. package/src/workflows/successor-routing.ts +108 -0
  363. package/src/workflows/task-step-routing.ts +5 -2
  364. package/src/workflows/triggers.ts +21 -36
  365. package/src/workflows/wait-poller.ts +6 -2
  366. package/src/workflows/webhook-filter.ts +203 -0
  367. package/templates/extensions/slack-reply-gate/hooks.ts +8 -4
  368. package/templates/skills/swarm-docs/content.md +2 -0
  369. package/dist/acp-adapter-bht22g3k.js +0 -16
  370. package/dist/fx-adapter-adtdb3jb.js +0 -19
  371. package/dist/grok-adapter-accnn9km.js +0 -19
  372. package/dist/handlers-1x77561e.js +0 -35
  373. package/dist/index-48qzcqzj.js +0 -35
  374. package/dist/index-rkvaambe.js +0 -36
  375. package/dist/index-xj1mq27m.js +0 -40
  376. package/dist/lead-enzn86bz.js +0 -74
  377. package/dist/thread-buffer-3x93yexa.js +0 -38
  378. package/dist/worker-zfcv2wbf.js +0 -74
@@ -18,6 +18,7 @@ import {
18
18
  import {
19
19
  type BasePromptArgs,
20
20
  getBasePrompt,
21
+ getBasePromptWithParts,
21
22
  getTaskContextPrompt,
22
23
  type RepoContext,
23
24
  type SlackTaskContext,
@@ -74,6 +75,8 @@ import {
74
75
  parseWorkerModelTierOverrides,
75
76
  type ReasoningEffort,
76
77
  type RepoGuidelines,
78
+ type RequestCompositionPartInput,
79
+ type RequestCompositionToolLoading,
77
80
  resolveTaskModelSelection,
78
81
  type SteeringMessage,
79
82
  } from "../types.ts";
@@ -1361,9 +1364,9 @@ function resolveMaxConcurrent(
1361
1364
  defaultMaxTasks: number,
1362
1365
  ): number {
1363
1366
  const raw = env.MAX_CONCURRENT_TASKS;
1364
- if (raw) {
1365
- const parsed = parseInt(raw, 10);
1366
- if (Number.isFinite(parsed) && parsed > 0) return parsed;
1367
+ if (raw && /^\d+$/.test(raw)) {
1368
+ const parsed = Number(raw);
1369
+ if (Number.isSafeInteger(parsed) && parsed > 0) return parsed;
1367
1370
  }
1368
1371
  return templateMax ?? defaultMaxTasks;
1369
1372
  }
@@ -2373,8 +2376,9 @@ export async function createSessionReportingAuthFailure(
2373
2376
  * the API is older than the worker).
2374
2377
  */
2375
2378
  /**
2376
- * Ask the API to move a task that hit a provider error to its next fallback
2377
- * profile (runbooks/model-tiers.md § Fallbacks on provider errors). Only a
2379
+ * Ask the API to move a task that hit a provider error to another key of its
2380
+ * profile's pool, or to its next fallback profile
2381
+ * (runbooks/model-tiers.md § Fallbacks on provider errors). Only a
2378
2382
  * task claim gave a profile (`resolvedProfile`) can hop. `superseded`: the
2379
2383
  * task is terminal and its resume runs the fallback, so the caller must not
2380
2384
  * finish it. Otherwise the caller fails it as usual, led by `failureReason`
@@ -2398,7 +2402,7 @@ export async function requestProviderFallback(
2398
2402
  if (!outcome.ok) return { superseded: false };
2399
2403
  if (outcome.kind === "resumed") {
2400
2404
  console.log(
2401
- `[${role}] Task ${taskId.slice(0, 8)} hit ${input.errorClass} on ${input.resolvedProfile}; resuming on the next fallback profile`,
2405
+ `[${role}] Task ${taskId.slice(0, 8)} hit ${input.errorClass} on ${input.resolvedProfile}; resuming on another key or the next fallback profile`,
2402
2406
  );
2403
2407
  return { superseded: true };
2404
2408
  }
@@ -3736,9 +3740,11 @@ export async function buildTaskSessionPrompts(input: {
3736
3740
  additionalSystemPrompt?: string;
3737
3741
  taskPrompt: string;
3738
3742
  context: TaskSessionContext;
3739
- }): Promise<{ systemPrompt: string; prompt: string }> {
3743
+ /** Chars of the recalled-memories block inside `taskPrompt`, for the manifest. */
3744
+ memoryChars?: number;
3745
+ }): Promise<{ systemPrompt: string; prompt: string; parts: RequestCompositionPartInput[] }> {
3740
3746
  const { basePromptArgs, additionalSystemPrompt, context } = input;
3741
- const basePrompt = await getBasePrompt(basePromptArgs);
3747
+ const { prompt: basePrompt, parts: baseParts } = await getBasePromptWithParts(basePromptArgs);
3742
3748
  const systemPrompt = additionalSystemPrompt
3743
3749
  ? `${basePrompt}\n\n${additionalSystemPrompt}`
3744
3750
  : basePrompt;
@@ -3757,10 +3763,33 @@ export async function buildTaskSessionPrompts(input: {
3757
3763
  .filter((part): part is string => Boolean(part))
3758
3764
  .join("\n\n");
3759
3765
 
3760
- return {
3761
- systemPrompt,
3762
- prompt: taskContext ? `${input.taskPrompt}\n\n${taskContext}` : input.taskPrompt,
3763
- };
3766
+ const prompt = taskContext ? `${input.taskPrompt}\n\n${taskContext}` : input.taskPrompt;
3767
+ const parts = [...baseParts];
3768
+ if (additionalSystemPrompt) {
3769
+ parts.push({
3770
+ kind: "operator_prompt",
3771
+ id: "operator_prompt",
3772
+ label: "operator SYSTEM_PROMPT",
3773
+ chars: systemPrompt.length - basePrompt.length,
3774
+ });
3775
+ }
3776
+ const memoryChars = Math.min(input.memoryChars ?? 0, prompt.length);
3777
+ if (memoryChars > 0) {
3778
+ parts.push({
3779
+ kind: "memories",
3780
+ id: "memories",
3781
+ label: "recalled memories",
3782
+ chars: memoryChars,
3783
+ });
3784
+ }
3785
+ parts.push({
3786
+ kind: "task_prompt",
3787
+ id: "task_prompt",
3788
+ label: "task prompt",
3789
+ chars: prompt.length - memoryChars,
3790
+ });
3791
+
3792
+ return { systemPrompt, prompt, parts };
3764
3793
  }
3765
3794
 
3766
3795
  /** A non-2xx answer from `POST /api/agents`; carries the status for retry triage. */
@@ -4202,6 +4231,61 @@ async function fetchRelevantMemories(
4202
4231
  }
4203
4232
  }
4204
4233
 
4234
+ /**
4235
+ * Which swarm tool schemas the harness sends with every call. Claude runs
4236
+ * ToolSearch over every MCP tool, so only server-preloaded tools ride up front.
4237
+ * Pi with PI_TOOL_DEFERRAL keeps the core set plus preloaded tools. The server
4238
+ * cannot see either fact, so the worker reports it.
4239
+ */
4240
+ export function requestToolLoading(
4241
+ provider: string,
4242
+ traits: { hasMcp?: boolean; hasToolSearch?: boolean },
4243
+ ): RequestCompositionToolLoading {
4244
+ if (traits.hasMcp === false) return "none";
4245
+ if (provider === "claude" && traits.hasToolSearch) return "preloaded";
4246
+ if (provider === "pi" && traits.hasToolSearch) return "core";
4247
+ return "all";
4248
+ }
4249
+
4250
+ /**
4251
+ * Post the session's request composition manifest. Fire and forget: a lost
4252
+ * manifest only blanks a dashboard panel, so it never delays or fails a task.
4253
+ */
4254
+ export function postRequestComposition(
4255
+ apiUrl: string,
4256
+ apiKey: string,
4257
+ agentId: string,
4258
+ taskId: string,
4259
+ body: {
4260
+ sessionId: string;
4261
+ provider: string;
4262
+ model?: string;
4263
+ toolLoading: RequestCompositionToolLoading;
4264
+ parts: RequestCompositionPartInput[];
4265
+ },
4266
+ ): void {
4267
+ const headers: Record<string, string> = {
4268
+ "Content-Type": "application/json",
4269
+ "X-Agent-ID": agentId,
4270
+ };
4271
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
4272
+ fetch(`${apiUrl}/api/tasks/${taskId}/request-composition`, {
4273
+ method: "POST",
4274
+ headers,
4275
+ body: JSON.stringify(body),
4276
+ })
4277
+ .then((response) => {
4278
+ if (!response.ok) {
4279
+ console.warn(`[runner] Request composition POST returned ${response.status}`);
4280
+ }
4281
+ })
4282
+ .catch((err) => {
4283
+ console.warn(
4284
+ `[runner] Failed to post request composition: ${err instanceof Error ? err.message : err}`,
4285
+ );
4286
+ });
4287
+ }
4288
+
4205
4289
  /** Spawn a provider session without blocking - returns immediately with tracking info */
4206
4290
  /**
4207
4291
  * Extract a key field from tool arguments for event tracking.
@@ -4491,6 +4575,8 @@ export async function spawnProviderProcess(
4491
4575
  contextKey?: string;
4492
4576
  /** Forwarded to fetchResolvedEnv → resolveCredentialPools — see RunnerState.modelWindowBlocks. */
4493
4577
  localBlocks?: Map<string, number>;
4578
+ /** Prompt part sizes from buildTaskSessionPrompts, posted as the session's manifest. */
4579
+ compositionParts?: RequestCompositionPartInput[];
4494
4580
  /** Claim-time profile (task.resolvedProfile) and its pooled-key allowlist. */
4495
4581
  resolvedProfile?: string;
4496
4582
  credentialAllowlist?: Record<string, string[]>;
@@ -4722,6 +4808,7 @@ export async function spawnProviderProcess(
4722
4808
  additionalArgs: opts.additionalArgs,
4723
4809
  resumeSessionId: opts.resumeSessionId,
4724
4810
  iteration: opts.iteration,
4811
+ runnerSessionId: opts.runnerSessionId,
4725
4812
  env: withHarnessTelemetryEnv(freshEnv) as Record<string, string>,
4726
4813
  // Propagate the selected OAuth slot so the adapter refreshes back to the
4727
4814
  // correct pool key. Undefined for non-codex providers and single-cred
@@ -4811,6 +4898,15 @@ export async function spawnProviderProcess(
4811
4898
  console.warn(`[runner] Failed to report latest model: ${err}`),
4812
4899
  );
4813
4900
  }
4901
+ if (realTaskId && opts.compositionParts) {
4902
+ postRequestComposition(opts.apiUrl, opts.apiKey, opts.agentId, realTaskId, {
4903
+ sessionId: opts.runnerSessionId,
4904
+ provider: adapter.name,
4905
+ model: model || undefined,
4906
+ toolLoading: requestToolLoading(adapter.name, adapter.traits),
4907
+ parts: opts.compositionParts,
4908
+ });
4909
+ }
4814
4910
 
4815
4911
  // Set up log streaming
4816
4912
  const logBuffer: LogBuffer = { lines: [], lastFlush: Date.now(), partialLine: "" };
@@ -7153,6 +7249,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7153
7249
  }
7154
7250
 
7155
7251
  // Build prompt with resume context + memory injection
7252
+ let resumeMemoryChars = 0;
7156
7253
  let resumePrompt = await buildResumePrompt(task, adapter.formatCommand.bind(adapter), {
7157
7254
  hasMcp: adapter.traits.hasMcp,
7158
7255
  });
@@ -7168,6 +7265,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7168
7265
  );
7169
7266
  if (resumeMemoryContext) {
7170
7267
  resumePrompt += resumeMemoryContext;
7268
+ resumeMemoryChars = resumeMemoryContext.length;
7171
7269
  console.log(`[${role}] Injected relevant memories into resumed task prompt`);
7172
7270
  }
7173
7271
 
@@ -7282,6 +7380,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7282
7380
  basePromptArgs: basePromptArgs(),
7283
7381
  additionalSystemPrompt,
7284
7382
  taskPrompt: resumePrompt,
7383
+ memoryChars: resumeMemoryChars,
7285
7384
  context: {
7286
7385
  repoContext: resumeRepoContext,
7287
7386
  slackContext: resumeSlackChannelId
@@ -7342,6 +7441,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7342
7441
  vcsRepo: task.vcsRepo,
7343
7442
  contextKey: (task as { contextKey?: string }).contextKey,
7344
7443
  localBlocks: state.modelWindowBlocks,
7444
+ compositionParts: resumeSession.parts,
7345
7445
  resolvedProfile: task.resolvedProfile,
7346
7446
  credentialAllowlist: task.credentialAllowlist,
7347
7447
  },
@@ -7635,6 +7735,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7635
7735
  }
7636
7736
 
7637
7737
  // Build prompt based on trigger
7738
+ let taskMemoryChars = 0;
7638
7739
  let triggerPrompt = await buildPromptForTrigger(
7639
7740
  trigger,
7640
7741
  prompt,
@@ -7703,6 +7804,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7703
7804
  // Enrich prompt with relevant memories from past sessions
7704
7805
  if (memoryContext) {
7705
7806
  triggerPrompt += memoryContext;
7807
+ taskMemoryChars = memoryContext.length;
7706
7808
  console.log(`[${role}] Injected relevant memories into task prompt`);
7707
7809
  }
7708
7810
 
@@ -7871,6 +7973,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7871
7973
  basePromptArgs: basePromptArgs(),
7872
7974
  additionalSystemPrompt,
7873
7975
  taskPrompt: triggerPrompt,
7976
+ memoryChars: taskMemoryChars,
7874
7977
  context: {
7875
7978
  repoContext: currentRepoContext,
7876
7979
  slackContext: taskSlackContext,
@@ -7969,6 +8072,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7969
8072
  vcsRepo: taskVcsRepo,
7970
8073
  contextKey: taskContextKey,
7971
8074
  localBlocks: state.modelWindowBlocks,
8075
+ compositionParts: taskSession.parts,
7972
8076
  resolvedProfile: (trigger.task as { resolvedProfile?: string } | undefined)
7973
8077
  ?.resolvedProfile,
7974
8078
  credentialAllowlist: (
@@ -114,7 +114,7 @@
114
114
  }
115
115
  },
116
116
  "files": {
117
- "hooks.ts": "import { type ApiCtx, block, type SwarmExtension } from \"swarm-extension\";\nimport { z } from \"zod\";\n\n/**\n * slack-reply-gate\n *\n * Every human message in a Slack thread the swarm takes part in is buffered and\n * flushed into a Lead task (\"[Thread follow-up — N message(s) buffered]\"), even\n * \"lol\", \":joy:\" or two people bantering. This hook asks a SystemOne decision\n * model (Jev or Clef) whether Lead should answer, and drops the wake-up when the\n * answer is no.\n *\n * Hook: `pre.task.create`, origin \"slack\", description carrying the\n * thread-buffer header. `pre.slack.route` cannot be used: the buffered thread\n * path returns before that hook is dispatched, and its result can only\n * re-target a message, never drop it.\n *\n * Rules:\n * - A message that @mentions Lead passes without a decision call.\n * - Otherwise one `choice` question classifies the message into a reason;\n * reply=false only for reaction_only | banter_between_others |\n * not_addressed_to_lead, and only when the summed probability of those\n * three labels is >= minConfidence (a banter/reaction split is still a skip).\n * - Fails OPEN on every error, timeout or missing key.\n *\n * Provider (config.provider): the decision is made server-side by the\n * `system-one-decide` tool (`ctx.swarm.systemOne_decide`), the same path as a\n * `system-one-decision` workflow node, so every SystemOne host works and no key\n * enters this hook. `auto` picks the first host with a configured credential:\n * typesafe (Jev, TYPESAFE_API_KEY), openrouter (Jev, OPENROUTER_API_KEY), then\n * cloudflare (Clef, CLOUDFLARE_API_TOKEN or CLOUDFLARE_API_KEY, plus\n * CLOUDFLARE_ACCOUNT_ID). laya and openai are explicit choices only.\n *\n * modes (config.mode):\n * off -> never evaluate\n * shadow -> evaluate + record, never block (default)\n * enforce -> record, block the task when reply=false, and mark the\n * triggering Slack message with :mute: (config.muteReaction)\n *\n * Muting: no swarm tool or ctx method adds a Slack reaction, so the hook calls\n * the Slack Web API (reactions.remove / reactions.add) with the bot token. It\n * first removes the bot's own acceptance reactions (:eyes:, :heavy_plus_sign:,\n * :zap:, :speech_balloon:, or their SLACK_REACTION_* overrides), the same set\n * the engine clears when it finalizes a task, then adds :mute:. With\n * muteReaction \"\" it only removes them: a true no-op on the message. It runs after\n * the block decision returns, so a slow or failing Slack call never delays or\n * changes the drop; its errors go to the same KV namespace.\n *\n * Every decision lands in KV namespace `ext:slack-reply-gate`.\n */\n\nexport const config = z.object({\n mode: z.enum([\"off\", \"shadow\", \"enforce\"]).default(\"shadow\"),\n timeoutMs: z.number().int().positive().default(3000),\n provider: z\n .enum([\"auto\", \"typesafe\", \"openrouter\", \"cloudflare\", \"laya\", \"openai\"])\n .default(\"auto\"),\n /** Jev model on TypeSafe. */\n model: z.string().default(\"jev-latest\"),\n /** Jev model on OpenRouter. */\n openrouterModel: z.string().default(\"typesafe/jev-1.13\"),\n /** Clef model on Cloudflare Workers AI: clef or clef-flash. */\n cloudflareModel: z.string().default(\"clef\"),\n minConfidence: z.number().min(0).max(1).default(0.55),\n contextMessages: z.number().int().min(0).max(20).default(6),\n leadAliases: z.array(z.string()).default([\"lead\"]),\n botSlackUserIds: z.array(z.string()).default([]),\n /**\n * Reaction for a dropped message in enforce mode. \"\" only removes the bot's\n * acceptance reaction(s) and adds nothing.\n */\n muteReaction: z.string().default(\"mute\"),\n slackTimeoutMs: z.number().int().positive().default(5000),\n});\n\ntype Cfg = z.infer<typeof config>;\ntype Swarm = ApiCtx[\"swarm\"];\n\nconst NS = \"ext:slack-reply-gate\";\nconst HEADER_LINE_RE = /(?:^|\\n)\\[Thread follow-up — \\d+ message\\(s\\) buffered\\]\\n/g;\nconst CTX_OPEN = \"<thread_context>\";\nconst CTX_CLOSE = \"</thread_context>\";\n// The dispatcher cancels a handler after 5 s; leave room for the KV writes.\nconst MAX_TIMEOUT_MS = 4000;\n// The smallest time budget system-one-decide accepts.\nconst MIN_DECIDE_TIMEOUT_MS = 1000;\n\nexport const REASONS = {\n direct_ask:\n \"Asks Lead (or the swarm, the bot, 'you' meaning the AI) a question or for something, explicitly or clearly implied.\",\n followup_to_lead:\n \"Answers, confirms, corrects or continues something Lead or another swarm agent ([Agent]) just said or asked, so Lead needs it to proceed.\",\n instruction_to_lead:\n \"Gives a task, instruction, request or decision for the AI to act on, even without naming it (for example 'can you create X', 'ship it', 'do it').\",\n reaction_only:\n \"Only a reaction: emoji, laughter (lol, haha, jaja), 'boom!', 'nice', 'thanks', '+1', with no request and nothing new for Lead.\",\n banter_between_others:\n \"Chat between the humans, or between other people and other bots, that is not aimed at Lead.\",\n not_addressed_to_lead:\n \"Addressed to a specific other person or another assistant, or an FYI that needs no answer from Lead.\",\n other: \"None of the above, or unclear.\",\n} as const;\n\nexport type Reason = keyof typeof REASONS;\nconst SKIP_REASONS: ReadonlySet<string> = new Set([\n \"reaction_only\",\n \"banter_between_others\",\n \"not_addressed_to_lead\",\n]);\n\nconst cfgOf = (raw: unknown): Cfg => {\n const parsed = config.safeParse(raw ?? {});\n return parsed.success ? parsed.data : config.parse({});\n};\n\n// kv keys accept [a-zA-Z0-9._:/%-]\nconst safeKey = (raw: string | undefined | null): string =>\n (raw && raw.length > 0 ? raw : \"unknown\").replace(/[^a-zA-Z0-9._:-]/g, \"_\").slice(0, 120);\n\nconst escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * Locate the engine's follow-up header (src/slack/thread-buffer.ts): at the start of the\n * description, or right after the closing `</thread_context>`. Thread context quotes old\n * messages verbatim, so a header (or a `</thread_context>`) quoted inside it is skipped.\n */\nconst findHeader = (description: string): { index: number; end: number } | null => {\n for (const m of description.matchAll(HEADER_LINE_RE)) {\n const index = m.index! + (m[0].startsWith(\"\\n\") ? 1 : 0);\n const before = description.slice(0, index);\n const open = before.indexOf(CTX_OPEN);\n if (open < 0 || before.trimEnd().endsWith(CTX_CLOSE)) {\n return { index, end: m.index! + m[0].length };\n }\n }\n return null;\n};\n\n/**\n * Split a buffered follow-up description into thread context and new messages, or null\n * when the description is not a buffered follow-up. Only `messages` is new text.\n */\nexport const parseFollowUp = (\n description: string,\n): { context: string[]; messages: string[] } | null => {\n const header = findHeader(description);\n if (!header) return null;\n const before = description.slice(0, header.index).trimEnd();\n const open = before.indexOf(CTX_OPEN);\n const context =\n open >= 0\n ? before\n .slice(open + CTX_OPEN.length, before.length - CTX_CLOSE.length)\n .split(/\\n(?=<@[A-Z0-9]+[|>]|\\[Agent\\]:)/)\n .map((m) => m.trim())\n .filter(Boolean)\n : [];\n const messages = description\n .slice(header.end)\n .split(\"\\n---\\n\")\n .map((m) => m.trim())\n .filter(Boolean);\n return { context, messages };\n};\n\n/** True when the new text addresses Lead with an @mention. */\nexport const mentionsLead = (text: string, aliases: readonly string[]): boolean => {\n // The buffer rewrites a mention of the swarm's own bot to `<@U…> (that's you)`.\n if (/<@[A-Z0-9]+>\\s*\\(that's you\\)/.test(text)) return true;\n const names = aliases\n .map((a) => a.trim())\n .filter(Boolean)\n .map(escapeRe);\n if (names.length === 0) return false;\n const alt = names.join(\"|\");\n return (\n new RegExp(`(^|[^\\\\w@])@(${alt})\\\\b`, \"i\").test(text) ||\n new RegExp(`<@[A-Z0-9]+\\\\|(${alt})>`, \"i\").test(text)\n );\n};\n\nconst secretCache = new Map<string, { value: string; at: number }>();\nconst KEY_TTL_MS = 5 * 60 * 1000;\nconst usable = (v: string): boolean => Boolean(v) && !v.startsWith(\"[REDACTED\");\nconst envOf = (name: string): string => String(process.env[name] ?? \"\");\n\n/**\n * Resolve a secret from the API process env. The API process loads global\n * swarm_config rows into process.env at boot and on config reload.\n * ctx.swarm.config_get cannot serve it: the SDK scrubs secrets to \"[REDACTED:<name>]\".\n */\nconst secret = (name: string): string => {\n const cached = secretCache.get(name);\n if (cached && Date.now() - cached.at < KEY_TTL_MS) return cached.value;\n const value = usable(envOf(name)) ? envOf(name) : \"\";\n if (usable(value)) secretCache.set(name, { value, at: Date.now() });\n return value;\n};\n\n/** Test hook: forget cached secrets. */\nexport const resetKeyCache = (): void => {\n secretCache.clear();\n};\n\nexport type ProviderId = Exclude<Cfg[\"provider\"], \"auto\">;\n\n/** Where the decision is made. No model means the provider's own default. */\nexport type DecisionTarget = { provider: ProviderId; model?: string };\n\n/** What `auto` needs per provider: every group must have one usable value. */\nconst AUTO_CREDENTIALS: ReadonlyArray<[ProviderId, string[][]]> = [\n [\"typesafe\", [[\"TYPESAFE_API_KEY\"]]],\n [\"openrouter\", [[\"OPENROUTER_API_KEY\"]]],\n [\"cloudflare\", [[\"CLOUDFLARE_API_TOKEN\", \"CLOUDFLARE_API_KEY\"], [\"CLOUDFLARE_ACCOUNT_ID\"]]],\n];\n\nconst modelFor = (provider: ProviderId, cfg: Cfg): string | undefined =>\n provider === \"typesafe\"\n ? cfg.model\n : provider === \"openrouter\"\n ? cfg.openrouterModel\n : provider === \"cloudflare\"\n ? cfg.cloudflareModel\n : undefined;\n\n/**\n * The decision providers to try, in order. An explicit one is used as is: the\n * server checks its credential. `auto` lists every provider in `AUTO_CREDENTIALS`\n * whose credential is set and throws when none is; the handler then fails open.\n */\nexport const resolveProviders = (cfg: Cfg): DecisionTarget[] => {\n if (cfg.provider !== \"auto\") {\n return [{ provider: cfg.provider, model: modelFor(cfg.provider, cfg) }];\n }\n const targets = AUTO_CREDENTIALS.filter(([, groups]) =>\n groups.every((keys) => keys.some((key) => usable(secret(key)))),\n ).map(([provider]) => ({ provider, model: modelFor(provider, cfg) }));\n if (targets.length > 0) return targets;\n throw new Error(\n \"no TYPESAFE_API_KEY, OPENROUTER_API_KEY, or CLOUDFLARE_API_TOKEN with CLOUDFLARE_ACCOUNT_ID\",\n );\n};\n\n/** The first provider `resolveProviders` would try. */\nexport const resolveProvider = (cfg: Cfg): DecisionTarget => resolveProviders(cfg)[0]!;\n\n/** The server refused the provider for a deployment setting and sent nothing. */\nexport class ProviderUnavailableError extends Error {}\n\nconst SLACK_API = \"https://slack.com/api\";\n// The engine's acceptance reactions (src/slack/reaction-shortcode.ts), by config key.\nconst ACCEPTANCE_REACTIONS: ReadonlyArray<[string, string]> = [\n [\"SLACK_REACTION_ACCEPTED\", \"eyes\"],\n [\"SLACK_REACTION_BUFFERED\", \"heavy_plus_sign\"],\n [\"SLACK_REACTION_NOW\", \"zap\"],\n [\"SLACK_REACTION_STEERED\", \"speech_balloon\"],\n];\nconst SHORTCODE_RE = /^[a-z0-9_+'-]+(::skin-tone-[2-6])?$/;\nconst shortcode = (raw: string): string | null => {\n const s = raw.trim().replace(/^:/, \"\").replace(/:$/, \"\").toLowerCase();\n return s && SHORTCODE_RE.test(s) ? s : null;\n};\n\n/** The acceptance reactions the engine may have put on the message, deduplicated. */\nexport const acceptanceReactions = (): string[] => [\n ...new Set(ACCEPTANCE_REACTIONS.map(([key, fallback]) => shortcode(envOf(key)) ?? fallback)),\n];\n\nconst slackCall = async (\n method: string,\n token: string,\n body: Record<string, string>,\n timeoutMs: number,\n): Promise<{ ok: boolean; error?: string }> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(`${SLACK_API}/${method}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n if (!res.ok) return { ok: false, error: `http_${res.status}` };\n const data = (await res.json()) as { ok?: boolean; error?: string };\n return { ok: data?.ok === true, error: data?.error };\n } finally {\n clearTimeout(timer);\n }\n};\n\nexport type MuteResult = { removed: string[]; added: boolean; errors: string[] };\n\n/**\n * Replace the bot's acceptance reaction(s) on one message with `name`, or only\n * remove them when `name` is \"\". `reactions.remove` only removes the calling\n * bot's own reaction, so a human's :eyes: stays. Never throws: every failure\n * lands in `errors`.\n */\nexport const muteMessage = async (\n token: string,\n channel: string,\n timestamp: string,\n name: string,\n timeoutMs: number,\n): Promise<MuteResult> => {\n const result: MuteResult = { removed: [], added: false, errors: [] };\n const call = (method: string, reaction: string) =>\n slackCall(method, token, { channel, timestamp, name: reaction }, timeoutMs).catch(\n (err): { ok: boolean; error?: string } => ({ ok: false, error: String(err).slice(0, 120) }),\n );\n const removals = acceptanceReactions().filter((r) => r !== name);\n const removed = await Promise.all(removals.map((r) => call(\"reactions.remove\", r)));\n removed.forEach((res, i) => {\n const reaction = removals[i]!;\n if (res.ok) result.removed.push(reaction);\n else if (res.error !== \"no_reaction\" && res.error !== \"invalid_name\")\n result.errors.push(`remove ${reaction}: ${res.error ?? \"unknown\"}`);\n });\n if (!name) return result;\n const added = await call(\"reactions.add\", name);\n if (added.ok || added.error === \"already_reacted\") result.added = true;\n else result.errors.push(`add ${name}: ${added.error ?? \"unknown\"}`);\n return result;\n};\n\n// In-flight mutes, so tests can await the work the handler does not wait for.\nconst pendingMutes = new Set<Promise<void>>();\n/** Test hook: wait for every in-flight mute. */\nexport const settleMutes = async (): Promise<void> => {\n await Promise.allSettled([...pendingMutes]);\n};\n\nexport type Verdict = {\n reason: string;\n confidence: number | null;\n probabilities: Record<string, number> | null;\n latencyMs: number;\n};\n\n/**\n * One decision: classify the newest message into a reason. Throws on any failure.\n * The server makes the call (`system-one-decide`), so every provider returns the\n * same `answers` shape. The time budget is enforced here and on the server.\n */\nexport const askModel = async (\n swarm: Swarm,\n input: {\n messages: string[];\n context: string[];\n sender: string;\n leadNames: readonly string[];\n },\n target: DecisionTarget,\n cfg: Cfg,\n outer?: AbortSignal,\n): Promise<Verdict> => {\n const budgetMs = Math.min(cfg.timeoutMs, MAX_TIMEOUT_MS);\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onOuterAbort: (() => void) | undefined;\n const stop = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`timed out after ${budgetMs}ms`)), budgetMs);\n onOuterAbort = () => reject(new Error(\"aborted\"));\n outer?.addEventListener(\"abort\", onOuterAbort);\n });\n const t0 = Date.now();\n try {\n const call = swarm.systemOne_decide({\n provider: target.provider,\n ...(target.model ? { model: target.model } : {}),\n state: {\n role: \"Decide whether Lead, the coordinating AI agent of a team's agent swarm, should answer a new Slack message in a thread it takes part in. Lead is woken by every message in the thread, including ones not meant for it. Answering noise wastes everyone's time; missing a real ask is worse.\",\n lead_names: [...input.leadNames],\n recent_thread_messages: input.context,\n new_message: input.messages.join(\"\\n---\\n\"),\n new_message_sender: input.sender,\n },\n questions: {\n reason: {\n type: \"choice\",\n instructions:\n \"Which label best describes new_message from Lead's point of view? Use recent_thread_messages to tell who it is talking to. Lines starting with [Agent] are swarm bots.\",\n criteria: REASONS,\n },\n },\n timeoutMs: Math.max(budgetMs, MIN_DECIDE_TIMEOUT_MS),\n maxRetries: 0,\n });\n // After a timeout nobody awaits the call; its late failure must not go unhandled.\n call.catch(() => {});\n const res = (await Promise.race([call, stop])) as {\n success?: boolean;\n status?: number;\n data?: unknown;\n } | null;\n const body = (res?.data ?? res) as {\n success?: boolean;\n message?: unknown;\n error?: unknown;\n providerUnavailable?: unknown;\n answers?: { reason?: { choice?: unknown; confidence?: unknown; probabilities?: unknown } };\n } | null;\n if (res?.success === false || body?.success === false) {\n const why = `${target.provider}: ${String(body?.message ?? body?.error ?? `HTTP ${res?.status}`).slice(0, 200)}`;\n throw body?.providerUnavailable === true\n ? new ProviderUnavailableError(why)\n : new Error(why);\n }\n const answer = body?.answers?.reason;\n const reason = typeof answer?.choice === \"string\" ? answer.choice : \"\";\n if (!(reason in REASONS)) throw new Error(`unexpected choice: ${String(reason).slice(0, 60)}`);\n const confidence = typeof answer?.confidence === \"number\" ? answer.confidence : null;\n const probabilities =\n answer?.probabilities && typeof answer.probabilities === \"object\"\n ? (answer.probabilities as Record<string, number>)\n : null;\n return { reason, confidence, probabilities, latencyMs: Date.now() - t0 };\n } finally {\n clearTimeout(timer);\n if (onOuterAbort) outer?.removeEventListener(\"abort\", onOuterAbort);\n }\n};\n\n/**\n * `askModel` on each target in turn, moving on only when the server refused the\n * provider for a deployment setting (no request was sent). Any other failure, or\n * a refusal of the last target, throws.\n */\nexport const askFirstAvailable = async (\n swarm: Swarm,\n input: Parameters<typeof askModel>[1],\n targets: readonly DecisionTarget[],\n cfg: Cfg,\n outer?: AbortSignal,\n): Promise<{ verdict: Verdict; target: DecisionTarget }> => {\n for (const [i, target] of targets.entries()) {\n try {\n return { verdict: await askModel(swarm, input, target, cfg, outer), target };\n } catch (err) {\n if (!(err instanceof ProviderUnavailableError) || i === targets.length - 1) throw err;\n }\n }\n throw new Error(\"no decision provider\");\n};\n\n/** Probability that the message needs no reply: the summed mass of the skip labels. */\nexport const skipProbability = (verdict: Verdict): number | null => {\n if (verdict.probabilities) {\n let sum = 0;\n for (const [label, p] of Object.entries(verdict.probabilities)) {\n if (SKIP_REASONS.has(label) && typeof p === \"number\") sum += p;\n }\n return sum;\n }\n return verdict.confidence;\n};\n\n/** Map a verdict to the typed decision. An unsure skip verdict replies. */\nexport const decide = (\n verdict: Verdict,\n minConfidence: number,\n): { reply: boolean; reason: Reason; skipP: number | null; lowConfidence: boolean } => {\n const reason = verdict.reason as Reason;\n const skipP = skipProbability(verdict);\n if (!SKIP_REASONS.has(reason)) return { reply: true, reason, skipP, lowConfidence: false };\n const lowConfidence = skipP !== null && skipP < minConfidence;\n return { reply: lowConfidence, reason, skipP, lowConfidence };\n};\n\nconst record = async (\n swarm: Swarm,\n entry: Record<string, unknown>,\n counters: string[],\n prefix: \"d\" | \"m\" = \"d\",\n) => {\n const at = new Date().toISOString();\n const thread = safeKey(`${entry.channelId ?? \"\"}_${entry.threadTs ?? \"\"}`);\n const value = { at, ...entry };\n await Promise.allSettled([\n swarm.kv_set({ namespace: NS, key: `${prefix}:${Date.now()}:${thread}`, value }),\n // `last` stays the latest decision; mute outcomes only get their own row.\n ...(prefix === \"d\" ? [swarm.kv_set({ namespace: NS, key: \"last\", value })] : []),\n ...counters.map((c) => swarm.kv_incr({ namespace: NS, key: safeKey(c) })),\n ]);\n};\n\n/** Mute the triggering message and log the outcome. Never throws. */\nconst muteTrigger = async (\n swarm: Swarm,\n cfg: Cfg,\n base: Record<string, unknown>,\n): Promise<void> => {\n try {\n const channel = String(base.channelId ?? \"\");\n const ts = String(base.triggerTs ?? \"\");\n if (!channel || !ts) throw new Error(\"no slackChannelId or slackTriggerMessageTs\");\n const token = secret(\"SLACK_BOT_TOKEN\");\n if (!usable(token)) throw new Error(\"no SLACK_BOT_TOKEN\");\n const result = await muteMessage(token, channel, ts, cfg.muteReaction, cfg.slackTimeoutMs);\n // \"\" adds nothing: success is clearing the acceptance reaction(s).\n const done = cfg.muteReaction ? \"muted\" : \"unreacted\";\n const ok = (result.added || !cfg.muteReaction) && result.errors.length === 0;\n const action = ok ? done : \"mute-error\";\n await record(swarm, { ...base, action, ...result }, [action], \"m\");\n } catch (err) {\n await record(\n swarm,\n { ...base, action: \"mute-error\", errors: [String(err).slice(0, 300)] },\n [\"mute-error\"],\n \"m\",\n ).catch(() => {});\n }\n};\n\nconst extension: SwarmExtension = (api) => {\n api.on(\"pre.task.create\", async (event, ctx) => {\n if (event.origin !== \"slack\") return;\n // Only buffered follow-ups. A direct @mention task never carries the header outside\n // its thread context.\n const followUp = parseFollowUp(event.description);\n if (!followUp) return;\n\n const cfg = cfgOf(ctx.config);\n if (cfg.mode === \"off\") return;\n\n const opts = event.options;\n const base = {\n mode: cfg.mode,\n channelId: opts.slackChannelId,\n threadTs: opts.slackThreadTs,\n triggerTs: opts.slackTriggerMessageTs,\n senderSlackId: opts.slackUserId,\n };\n\n try {\n // A draft follow-up carries downloaded files: always let Lead see them.\n if (opts.status === \"draft\") {\n await record(ctx.swarm, { ...base, action: \"pass\", reason: \"has_files\" }, [\n \"total\",\n \"files\",\n ]);\n return;\n }\n\n // The mention check reads only the new messages, never the thread context.\n const { context, messages } = followUp;\n const preview = messages.join(\" | \").slice(0, 300);\n\n if (messages.some((m) => mentionsLead(m, cfg.leadAliases))) {\n await record(ctx.swarm, { ...base, action: \"pass\", reason: \"mention\", preview }, [\n \"total\",\n \"mention\",\n ]);\n return;\n }\n\n const targets = resolveProviders(cfg);\n\n const sender =\n opts.slackUserId && cfg.botSlackUserIds.includes(opts.slackUserId)\n ? \"bot\"\n : opts.requestedByUserId\n ? \"human (known teammate)\"\n : \"unknown (not a known teammate; may be a bot or an external person)\";\n\n const { verdict, target } = await askFirstAvailable(\n ctx.swarm,\n {\n messages,\n context: context.slice(-cfg.contextMessages).map((m) => m.slice(0, 500)),\n sender,\n leadNames: cfg.leadAliases,\n },\n targets,\n cfg,\n ctx.signal,\n );\n const decision = decide(verdict, cfg.minConfidence);\n\n const skip = !decision.reply;\n const action = skip ? (cfg.mode === \"enforce\" ? \"skipped\" : \"shadow-skip\") : \"pass\";\n await record(\n ctx.swarm,\n {\n ...base,\n action,\n reply: decision.reply,\n reason: decision.reason,\n confidence: verdict.confidence,\n skipP: decision.skipP,\n lowConfidence: decision.lowConfidence,\n latencyMs: verdict.latencyMs,\n provider: target.provider,\n sender,\n preview,\n },\n [\"total\", skip ? action : \"reply\", `reason:${decision.reason}`],\n );\n\n if (skip && cfg.mode === \"enforce\") {\n // Not awaited: the block must return inside the dispatcher's 5 s budget\n // whatever Slack does, and a failed reaction never changes the drop.\n // An empty (or invalid) muteReaction still clears the acceptance reaction(s).\n const muteReaction = shortcode(cfg.muteReaction) ?? \"\";\n const pending = muteTrigger(ctx.swarm, { ...cfg, muteReaction }, base);\n pendingMutes.add(pending);\n void pending.finally(() => pendingMutes.delete(pending));\n return block(\n `slack-reply-gate: no reply needed (${decision.reason}${decision.skipP !== null ? `, p(skip) ${decision.skipP.toFixed(2)}` : \"\"})`,\n );\n }\n return;\n } catch (err) {\n // Fail open, always.\n try {\n await record(\n ctx.swarm,\n { ...base, action: \"fail-open\", error: String(err).slice(0, 300) },\n [\"total\", \"error\"],\n );\n } catch {\n /* ignore */\n }\n ctx.log.warn(\"slack-reply-gate: failing open\", { error: String(err) });\n return;\n }\n });\n};\n\nexport default extension;\n"
117
+ "hooks.ts": "import { type ApiCtx, block, type SwarmExtension } from \"swarm-extension\";\nimport { z } from \"zod\";\n\n/**\n * slack-reply-gate\n *\n * Every human message in a Slack thread the swarm takes part in is buffered and\n * flushed into a Lead task (\"[Thread follow-up — N message(s) buffered]\"), even\n * \"lol\", \":joy:\" or two people bantering. This hook asks a SystemOne decision\n * model (Jev or Clef) whether Lead should answer, and drops the wake-up when the\n * answer is no.\n *\n * Hook: `pre.task.create`, origin \"slack\", description carrying the\n * thread-buffer header. `pre.slack.route` cannot be used: the buffered thread\n * path returns before that hook is dispatched, and its result can only\n * re-target a message, never drop it.\n *\n * Rules:\n * - A message that @mentions Lead passes without a decision call.\n * - Otherwise one `choice` question classifies the message into a reason;\n * reply=false only for reaction_only | banter_between_others |\n * not_addressed_to_lead, and only when the summed probability of those\n * three labels is >= minConfidence (a banter/reaction split is still a skip).\n * - Fails OPEN on every error, timeout or missing key.\n *\n * Provider (config.provider): the decision is made server-side by the\n * `system-one-decide` tool (`ctx.swarm.systemOne_decide`), the same path as a\n * `system-one-decision` workflow node, so every SystemOne host works and no key\n * enters this hook. `auto` picks the first host with a configured credential:\n * typesafe (Jev, TYPESAFE_API_KEY), openrouter (Jev, OPENROUTER_API_KEY), then\n * cloudflare (Clef, CLOUDFLARE_API_TOKEN or CLOUDFLARE_API_KEY, plus\n * CLOUDFLARE_ACCOUNT_ID). laya and openai are explicit choices only.\n *\n * modes (config.mode):\n * off -> never evaluate\n * shadow -> evaluate + record, never block (default)\n * enforce -> record, block the task when reply=false, and mark the\n * triggering Slack message with :mute: (config.muteReaction)\n *\n * Muting: no swarm tool or ctx method adds a Slack reaction, so the hook calls\n * the Slack Web API (reactions.remove / reactions.add) with the bot token. It\n * first removes the bot's own acceptance reactions (:eyes:, :heavy_plus_sign:,\n * :zap:, :speech_balloon:, or their SLACK_REACTION_* overrides), the same set\n * the engine clears when it finalizes a task, then adds :mute:. With\n * muteReaction \"\" it only removes them: a true no-op on the message. It runs after\n * the block decision returns, so a slow or failing Slack call never delays or\n * changes the drop; its errors go to the same KV namespace.\n *\n * Every decision lands in KV namespace `ext:slack-reply-gate`.\n */\n\nexport const config = z.object({\n mode: z.enum([\"off\", \"shadow\", \"enforce\"]).default(\"shadow\"),\n timeoutMs: z.number().int().positive().default(3000),\n provider: z\n .enum([\"auto\", \"typesafe\", \"openrouter\", \"cloudflare\", \"laya\", \"openai\"])\n .default(\"auto\"),\n /** Jev model on TypeSafe. */\n model: z.string().default(\"jev-latest\"),\n /** Jev model on OpenRouter. */\n openrouterModel: z.string().default(\"typesafe/jev-1.13\"),\n /** Clef model on Cloudflare Workers AI: clef or clef-flash. */\n cloudflareModel: z.string().default(\"clef\"),\n minConfidence: z.number().min(0).max(1).default(0.55),\n contextMessages: z.number().int().min(0).max(20).default(6),\n leadAliases: z.array(z.string()).default([\"lead\"]),\n botSlackUserIds: z.array(z.string()).default([]),\n /**\n * Reaction for a dropped message in enforce mode. \"\" only removes the bot's\n * acceptance reaction(s) and adds nothing.\n */\n muteReaction: z.string().default(\"mute\"),\n slackTimeoutMs: z.number().int().positive().default(5000),\n});\n\ntype Cfg = z.infer<typeof config>;\ntype Swarm = ApiCtx[\"swarm\"];\n\nconst NS = \"ext:slack-reply-gate\";\nconst HEADER_LINE_RE = /(?:^|\\n)\\[Thread follow-up — \\d+ message\\(s\\) buffered\\]\\n/g;\nconst CTX_OPEN = \"<thread_context>\";\nconst CTX_CLOSE = \"</thread_context>\";\n// The dispatcher cancels a handler after 5 s; leave room for the KV writes.\nconst MAX_TIMEOUT_MS = 4000;\n// The smallest time budget system-one-decide accepts.\nconst MIN_DECIDE_TIMEOUT_MS = 1000;\n\nexport const REASONS = {\n direct_ask:\n \"Asks Lead (or the swarm, the bot, 'you' meaning the AI) a question or for something, explicitly or clearly implied.\",\n followup_to_lead:\n \"Answers, confirms, corrects or continues something Lead or another swarm agent ([Agent]) just said or asked, so Lead needs it to proceed.\",\n instruction_to_lead:\n \"Gives a task, instruction, request or decision for the AI to act on, even without naming it (for example 'can you create X', 'ship it', 'do it').\",\n reaction_only:\n \"Only a reaction: emoji, laughter (lol, haha, jaja), 'boom!', 'nice', 'thanks', '+1', with no request and nothing new for Lead.\",\n banter_between_others:\n \"Chat between the humans, or between other people and other bots, that is not aimed at Lead.\",\n not_addressed_to_lead:\n \"Addressed to a specific other person or another assistant, or an FYI that needs no answer from Lead.\",\n other: \"None of the above, or unclear.\",\n} as const;\n\nexport type Reason = keyof typeof REASONS;\nconst SKIP_REASONS: ReadonlySet<string> = new Set([\n \"reaction_only\",\n \"banter_between_others\",\n \"not_addressed_to_lead\",\n]);\n\nconst cfgOf = (raw: unknown): Cfg => {\n const parsed = config.safeParse(raw ?? {});\n return parsed.success ? parsed.data : config.parse({});\n};\n\n// kv keys accept [a-zA-Z0-9._:/%-]\nconst safeKey = (raw: string | undefined | null): string =>\n (raw && raw.length > 0 ? raw : \"unknown\").replace(/[^a-zA-Z0-9._:-]/g, \"_\").slice(0, 120);\n\nconst escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * Locate the engine's follow-up header (src/slack/thread-buffer.ts): at the start of the\n * description, or right after the closing `</thread_context>`. Thread context quotes old\n * messages verbatim, so a header (or a `</thread_context>`) quoted inside it is skipped.\n */\nconst findHeader = (description: string): { index: number; end: number } | null => {\n for (const m of description.matchAll(HEADER_LINE_RE)) {\n const index = m.index! + (m[0].startsWith(\"\\n\") ? 1 : 0);\n const before = description.slice(0, index);\n const open = before.indexOf(CTX_OPEN);\n if (open < 0 || before.trimEnd().endsWith(CTX_CLOSE)) {\n return { index, end: m.index! + m[0].length };\n }\n }\n return null;\n};\n\n/**\n * Split a buffered follow-up description into thread context and new messages, or null\n * when the description is not a buffered follow-up. Only `messages` is new text.\n */\nexport const parseFollowUp = (\n description: string,\n): { context: string[]; messages: string[] } | null => {\n const header = findHeader(description);\n if (!header) return null;\n const before = description.slice(0, header.index).trimEnd();\n const open = before.indexOf(CTX_OPEN);\n const context =\n open >= 0\n ? before\n .slice(open + CTX_OPEN.length, before.length - CTX_CLOSE.length)\n .split(/\\n(?=<@[A-Z0-9]+[|>]|\\[Agent\\]:)/)\n .map((m) => m.trim())\n .filter(Boolean)\n : [];\n const messages = description\n .slice(header.end)\n .split(\"\\n---\\n\")\n .map((m) => m.trim())\n .filter(Boolean);\n return { context, messages };\n};\n\n/** True when the new text addresses Lead with an @mention. */\nexport const mentionsLead = (text: string, aliases: readonly string[]): boolean => {\n // The buffer rewrites a mention of the swarm's own bot to `<@U…> (that's you)`.\n if (/<@[A-Z0-9]+>\\s*\\(that's you\\)/.test(text)) return true;\n const names = aliases\n .map((a) => a.trim())\n .filter(Boolean)\n .map(escapeRe);\n if (names.length === 0) return false;\n const alt = names.join(\"|\");\n return (\n new RegExp(`(^|[^\\\\w@])@(${alt})\\\\b`, \"i\").test(text) ||\n new RegExp(`<@[A-Z0-9]+\\\\|(${alt})>`, \"i\").test(text)\n );\n};\n\nconst secretCache = new Map<string, { value: string; at: number }>();\nconst KEY_TTL_MS = 5 * 60 * 1000;\nconst usable = (v: string): boolean => Boolean(v) && !v.startsWith(\"[REDACTED\");\nconst envOf = (name: string): string => String(process.env[name] ?? \"\");\n\n/**\n * Resolve a secret from the API process env. The API process loads global\n * swarm_config rows into process.env at boot and on config reload.\n * ctx.swarm.config_get cannot serve it: the SDK scrubs secrets to \"[REDACTED:<name>]\".\n */\nconst secret = (name: string): string => {\n const cached = secretCache.get(name);\n if (cached && Date.now() - cached.at < KEY_TTL_MS) return cached.value;\n const value = usable(envOf(name)) ? envOf(name) : \"\";\n if (usable(value)) secretCache.set(name, { value, at: Date.now() });\n return value;\n};\n\n/** Test hook: forget cached secrets. */\nexport const resetKeyCache = (): void => {\n secretCache.clear();\n};\n\nexport type ProviderId = Exclude<Cfg[\"provider\"], \"auto\">;\n\n/** Where the decision is made. No model means the provider's own default. */\nexport type DecisionTarget = { provider: ProviderId; model?: string };\n\n/** What `auto` needs per provider: every group must have one usable value. */\nconst AUTO_CREDENTIALS: ReadonlyArray<[ProviderId, string[][]]> = [\n [\"typesafe\", [[\"TYPESAFE_API_KEY\"]]],\n [\"openrouter\", [[\"OPENROUTER_API_KEY\"]]],\n [\"cloudflare\", [[\"CLOUDFLARE_API_TOKEN\", \"CLOUDFLARE_API_KEY\"], [\"CLOUDFLARE_ACCOUNT_ID\"]]],\n];\n\nconst modelFor = (provider: ProviderId, cfg: Cfg): string | undefined =>\n provider === \"typesafe\"\n ? cfg.model\n : provider === \"openrouter\"\n ? cfg.openrouterModel\n : provider === \"cloudflare\"\n ? cfg.cloudflareModel\n : undefined;\n\n/**\n * The decision providers to try, in order. An explicit one is used as is: the\n * server checks its credential. `auto` lists every provider in `AUTO_CREDENTIALS`\n * whose credential is set and throws when none is; the handler then fails open.\n */\nexport const resolveProviders = (cfg: Cfg): DecisionTarget[] => {\n if (cfg.provider !== \"auto\") {\n return [{ provider: cfg.provider, model: modelFor(cfg.provider, cfg) }];\n }\n const targets = AUTO_CREDENTIALS.filter(([, groups]) =>\n groups.every((keys) => keys.some((key) => usable(secret(key)))),\n ).map(([provider]) => ({ provider, model: modelFor(provider, cfg) }));\n if (targets.length > 0) return targets;\n throw new Error(\n \"no TYPESAFE_API_KEY, OPENROUTER_API_KEY, or CLOUDFLARE_API_TOKEN with CLOUDFLARE_ACCOUNT_ID\",\n );\n};\n\n/** The first provider `resolveProviders` would try. */\nexport const resolveProvider = (cfg: Cfg): DecisionTarget => resolveProviders(cfg)[0]!;\n\n/** The server refused the provider for a deployment setting and sent nothing. */\nexport class ProviderUnavailableError extends Error {}\n\nconst SLACK_API = \"https://slack.com/api\";\n// The engine's acceptance reactions (src/slack/reaction-shortcode.ts), by config key.\nconst ACCEPTANCE_REACTIONS: ReadonlyArray<[string, string]> = [\n [\"SLACK_REACTION_ACCEPTED\", \"eyes\"],\n [\"SLACK_REACTION_BUFFERED\", \"heavy_plus_sign\"],\n [\"SLACK_REACTION_NOW\", \"zap\"],\n [\"SLACK_REACTION_STEERED\", \"speech_balloon\"],\n];\nconst SHORTCODE_RE = /^[a-z0-9_+'-]+(::skin-tone-[2-6])?$/;\nconst shortcode = (raw: string): string | null => {\n const s = raw.trim().replace(/^:/, \"\").replace(/:$/, \"\").toLowerCase();\n return s && SHORTCODE_RE.test(s) ? s : null;\n};\n\n/** The acceptance reactions the engine may have put on the message, deduplicated. */\nexport const acceptanceReactions = (): string[] => [\n ...new Set(\n ACCEPTANCE_REACTIONS.flatMap(([key, fallback]) => {\n const raw = process.env[key];\n if (raw !== undefined && raw.trim() === \"\") return [];\n return [shortcode(raw ?? \"\") ?? fallback];\n }),\n ),\n];\n\nconst slackCall = async (\n method: string,\n token: string,\n body: Record<string, string>,\n timeoutMs: number,\n): Promise<{ ok: boolean; error?: string }> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(`${SLACK_API}/${method}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n if (!res.ok) return { ok: false, error: `http_${res.status}` };\n const data = (await res.json()) as { ok?: boolean; error?: string };\n return { ok: data?.ok === true, error: data?.error };\n } finally {\n clearTimeout(timer);\n }\n};\n\nexport type MuteResult = { removed: string[]; added: boolean; errors: string[] };\n\n/**\n * Replace the bot's acceptance reaction(s) on one message with `name`, or only\n * remove them when `name` is \"\". `reactions.remove` only removes the calling\n * bot's own reaction, so a human's :eyes: stays. Never throws: every failure\n * lands in `errors`.\n */\nexport const muteMessage = async (\n token: string,\n channel: string,\n timestamp: string,\n name: string,\n timeoutMs: number,\n): Promise<MuteResult> => {\n const result: MuteResult = { removed: [], added: false, errors: [] };\n const call = (method: string, reaction: string) =>\n slackCall(method, token, { channel, timestamp, name: reaction }, timeoutMs).catch(\n (err): { ok: boolean; error?: string } => ({ ok: false, error: String(err).slice(0, 120) }),\n );\n const removals = acceptanceReactions().filter((r) => r !== name);\n const removed = await Promise.all(removals.map((r) => call(\"reactions.remove\", r)));\n removed.forEach((res, i) => {\n const reaction = removals[i]!;\n if (res.ok) result.removed.push(reaction);\n else if (res.error !== \"no_reaction\" && res.error !== \"invalid_name\")\n result.errors.push(`remove ${reaction}: ${res.error ?? \"unknown\"}`);\n });\n if (!name) return result;\n const added = await call(\"reactions.add\", name);\n if (added.ok || added.error === \"already_reacted\") result.added = true;\n else result.errors.push(`add ${name}: ${added.error ?? \"unknown\"}`);\n return result;\n};\n\n// In-flight mutes, so tests can await the work the handler does not wait for.\nconst pendingMutes = new Set<Promise<void>>();\n/** Test hook: wait for every in-flight mute. */\nexport const settleMutes = async (): Promise<void> => {\n await Promise.allSettled([...pendingMutes]);\n};\n\nexport type Verdict = {\n reason: string;\n confidence: number | null;\n probabilities: Record<string, number> | null;\n latencyMs: number;\n};\n\n/**\n * One decision: classify the newest message into a reason. Throws on any failure.\n * The server makes the call (`system-one-decide`), so every provider returns the\n * same `answers` shape. The time budget is enforced here and on the server.\n */\nexport const askModel = async (\n swarm: Swarm,\n input: {\n messages: string[];\n context: string[];\n sender: string;\n leadNames: readonly string[];\n },\n target: DecisionTarget,\n cfg: Cfg,\n outer?: AbortSignal,\n): Promise<Verdict> => {\n const budgetMs = Math.min(cfg.timeoutMs, MAX_TIMEOUT_MS);\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onOuterAbort: (() => void) | undefined;\n const stop = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`timed out after ${budgetMs}ms`)), budgetMs);\n onOuterAbort = () => reject(new Error(\"aborted\"));\n outer?.addEventListener(\"abort\", onOuterAbort);\n });\n const t0 = Date.now();\n try {\n const call = swarm.systemOne_decide({\n provider: target.provider,\n ...(target.model ? { model: target.model } : {}),\n state: {\n role: \"Decide whether Lead, the coordinating AI agent of a team's agent swarm, should answer a new Slack message in a thread it takes part in. Lead is woken by every message in the thread, including ones not meant for it. Answering noise wastes everyone's time; missing a real ask is worse.\",\n lead_names: [...input.leadNames],\n recent_thread_messages: input.context,\n new_message: input.messages.join(\"\\n---\\n\"),\n new_message_sender: input.sender,\n },\n questions: {\n reason: {\n type: \"choice\",\n instructions:\n \"Which label best describes new_message from Lead's point of view? Use recent_thread_messages to tell who it is talking to. Lines starting with [Agent] are swarm bots.\",\n criteria: REASONS,\n },\n },\n timeoutMs: Math.max(budgetMs, MIN_DECIDE_TIMEOUT_MS),\n maxRetries: 0,\n });\n // After a timeout nobody awaits the call; its late failure must not go unhandled.\n call.catch(() => {});\n const res = (await Promise.race([call, stop])) as {\n success?: boolean;\n status?: number;\n data?: unknown;\n } | null;\n const body = (res?.data ?? res) as {\n success?: boolean;\n message?: unknown;\n error?: unknown;\n providerUnavailable?: unknown;\n answers?: { reason?: { choice?: unknown; confidence?: unknown; probabilities?: unknown } };\n } | null;\n if (res?.success === false || body?.success === false) {\n const why = `${target.provider}: ${String(body?.message ?? body?.error ?? `HTTP ${res?.status}`).slice(0, 200)}`;\n throw body?.providerUnavailable === true ? new ProviderUnavailableError(why) : new Error(why);\n }\n const answer = body?.answers?.reason;\n const reason = typeof answer?.choice === \"string\" ? answer.choice : \"\";\n if (!(reason in REASONS)) throw new Error(`unexpected choice: ${String(reason).slice(0, 60)}`);\n const confidence = typeof answer?.confidence === \"number\" ? answer.confidence : null;\n const probabilities =\n answer?.probabilities && typeof answer.probabilities === \"object\"\n ? (answer.probabilities as Record<string, number>)\n : null;\n return { reason, confidence, probabilities, latencyMs: Date.now() - t0 };\n } finally {\n clearTimeout(timer);\n if (onOuterAbort) outer?.removeEventListener(\"abort\", onOuterAbort);\n }\n};\n\n/**\n * `askModel` on each target in turn, moving on only when the server refused the\n * provider for a deployment setting (no request was sent). Any other failure, or\n * a refusal of the last target, throws.\n */\nexport const askFirstAvailable = async (\n swarm: Swarm,\n input: Parameters<typeof askModel>[1],\n targets: readonly DecisionTarget[],\n cfg: Cfg,\n outer?: AbortSignal,\n): Promise<{ verdict: Verdict; target: DecisionTarget }> => {\n for (const [i, target] of targets.entries()) {\n try {\n return { verdict: await askModel(swarm, input, target, cfg, outer), target };\n } catch (err) {\n if (!(err instanceof ProviderUnavailableError) || i === targets.length - 1) throw err;\n }\n }\n throw new Error(\"no decision provider\");\n};\n\n/** Probability that the message needs no reply: the summed mass of the skip labels. */\nexport const skipProbability = (verdict: Verdict): number | null => {\n if (verdict.probabilities) {\n let sum = 0;\n for (const [label, p] of Object.entries(verdict.probabilities)) {\n if (SKIP_REASONS.has(label) && typeof p === \"number\") sum += p;\n }\n return sum;\n }\n return verdict.confidence;\n};\n\n/** Map a verdict to the typed decision. An unsure skip verdict replies. */\nexport const decide = (\n verdict: Verdict,\n minConfidence: number,\n): { reply: boolean; reason: Reason; skipP: number | null; lowConfidence: boolean } => {\n const reason = verdict.reason as Reason;\n const skipP = skipProbability(verdict);\n if (!SKIP_REASONS.has(reason)) return { reply: true, reason, skipP, lowConfidence: false };\n const lowConfidence = skipP !== null && skipP < minConfidence;\n return { reply: lowConfidence, reason, skipP, lowConfidence };\n};\n\nconst record = async (\n swarm: Swarm,\n entry: Record<string, unknown>,\n counters: string[],\n prefix: \"d\" | \"m\" = \"d\",\n) => {\n const at = new Date().toISOString();\n const thread = safeKey(`${entry.channelId ?? \"\"}_${entry.threadTs ?? \"\"}`);\n const value = { at, ...entry };\n await Promise.allSettled([\n swarm.kv_set({ namespace: NS, key: `${prefix}:${Date.now()}:${thread}`, value }),\n // `last` stays the latest decision; mute outcomes only get their own row.\n ...(prefix === \"d\" ? [swarm.kv_set({ namespace: NS, key: \"last\", value })] : []),\n ...counters.map((c) => swarm.kv_incr({ namespace: NS, key: safeKey(c) })),\n ]);\n};\n\n/** Mute the triggering message and log the outcome. Never throws. */\nconst muteTrigger = async (\n swarm: Swarm,\n cfg: Cfg,\n base: Record<string, unknown>,\n): Promise<void> => {\n try {\n const channel = String(base.channelId ?? \"\");\n const ts = String(base.triggerTs ?? \"\");\n if (!channel || !ts) throw new Error(\"no slackChannelId or slackTriggerMessageTs\");\n const token = secret(\"SLACK_BOT_TOKEN\");\n if (!usable(token)) throw new Error(\"no SLACK_BOT_TOKEN\");\n const result = await muteMessage(token, channel, ts, cfg.muteReaction, cfg.slackTimeoutMs);\n // \"\" adds nothing: success is clearing the acceptance reaction(s).\n const done = cfg.muteReaction ? \"muted\" : \"unreacted\";\n const ok = (result.added || !cfg.muteReaction) && result.errors.length === 0;\n const action = ok ? done : \"mute-error\";\n await record(swarm, { ...base, action, ...result }, [action], \"m\");\n } catch (err) {\n await record(\n swarm,\n { ...base, action: \"mute-error\", errors: [String(err).slice(0, 300)] },\n [\"mute-error\"],\n \"m\",\n ).catch(() => {});\n }\n};\n\nconst extension: SwarmExtension = (api) => {\n api.on(\"pre.task.create\", async (event, ctx) => {\n if (event.origin !== \"slack\") return;\n // Only buffered follow-ups. A direct @mention task never carries the header outside\n // its thread context.\n const followUp = parseFollowUp(event.description);\n if (!followUp) return;\n\n const cfg = cfgOf(ctx.config);\n if (cfg.mode === \"off\") return;\n\n const opts = event.options;\n const base = {\n mode: cfg.mode,\n channelId: opts.slackChannelId,\n threadTs: opts.slackThreadTs,\n triggerTs: opts.slackTriggerMessageTs,\n senderSlackId: opts.slackUserId,\n };\n\n try {\n // A draft follow-up carries downloaded files: always let Lead see them.\n if (opts.status === \"draft\") {\n await record(ctx.swarm, { ...base, action: \"pass\", reason: \"has_files\" }, [\n \"total\",\n \"files\",\n ]);\n return;\n }\n\n // The mention check reads only the new messages, never the thread context.\n const { context, messages } = followUp;\n const preview = messages.join(\" | \").slice(0, 300);\n\n if (messages.some((m) => mentionsLead(m, cfg.leadAliases))) {\n await record(ctx.swarm, { ...base, action: \"pass\", reason: \"mention\", preview }, [\n \"total\",\n \"mention\",\n ]);\n return;\n }\n\n const targets = resolveProviders(cfg);\n\n const sender =\n opts.slackUserId && cfg.botSlackUserIds.includes(opts.slackUserId)\n ? \"bot\"\n : opts.requestedByUserId\n ? \"human (known teammate)\"\n : \"unknown (not a known teammate; may be a bot or an external person)\";\n\n const { verdict, target } = await askFirstAvailable(\n ctx.swarm,\n {\n messages,\n context: context.slice(-cfg.contextMessages).map((m) => m.slice(0, 500)),\n sender,\n leadNames: cfg.leadAliases,\n },\n targets,\n cfg,\n ctx.signal,\n );\n const decision = decide(verdict, cfg.minConfidence);\n\n const skip = !decision.reply;\n const action = skip ? (cfg.mode === \"enforce\" ? \"skipped\" : \"shadow-skip\") : \"pass\";\n await record(\n ctx.swarm,\n {\n ...base,\n action,\n reply: decision.reply,\n reason: decision.reason,\n confidence: verdict.confidence,\n skipP: decision.skipP,\n lowConfidence: decision.lowConfidence,\n latencyMs: verdict.latencyMs,\n provider: target.provider,\n sender,\n preview,\n },\n [\"total\", skip ? action : \"reply\", `reason:${decision.reason}`],\n );\n\n if (skip && cfg.mode === \"enforce\") {\n // Not awaited: the block must return inside the dispatcher's 5 s budget\n // whatever Slack does, and a failed reaction never changes the drop.\n // An empty (or invalid) muteReaction still clears the acceptance reaction(s).\n const muteReaction = shortcode(cfg.muteReaction) ?? \"\";\n const pending = muteTrigger(ctx.swarm, { ...cfg, muteReaction }, base);\n pendingMutes.add(pending);\n void pending.finally(() => pendingMutes.delete(pending));\n return block(\n `slack-reply-gate: no reply needed (${decision.reason}${decision.skipP !== null ? `, p(skip) ${decision.skipP.toFixed(2)}` : \"\"})`,\n );\n }\n return;\n } catch (err) {\n // Fail open, always.\n try {\n await record(\n ctx.swarm,\n { ...base, action: \"fail-open\", error: String(err).slice(0, 300) },\n [\"total\", \"error\"],\n );\n } catch {\n /* ignore */\n }\n ctx.log.warn(\"slack-reply-gate: failing open\", { error: String(err) });\n return;\n }\n });\n};\n\nexport default extension;\n"
118
118
  },
119
119
  "readme": "# slack-reply-gate\n\nLead is woken by every human message in a Slack thread the swarm takes part in, including \"lol\", an emoji, or two people chatting with each other. This extension asks a SystemOne decision model, Jev ([TypeSafe](https://typesafe.ai)) or Clef (Cloudflare Workers AI), whether Lead should answer a new thread message, and drops the wake-up when it should not.\n\nInstall config:\n\n```json\n{ \"mode\": \"shadow\" }\n```\n\nStart in `shadow`, read the decisions in KV for a few days, then switch to `enforce`.\n\n## Modes\n\n| `mode` | Effect |\n|---|---|\n| `off` | Never evaluates. |\n| `shadow` (default) | Asks the model and records the verdict. Never blocks. |\n| `enforce` | Asks the model, records the verdict, and blocks the Lead task when the answer is no. The message gets :mute: instead: no Lead task, no reply, no outcome card. |\n\n## What it gates\n\nHook: `pre.task.create`, for tasks with origin `slack` whose description carries the thread buffer's header `[Thread follow-up — N message(s) buffered]`. Those are the non-mention thread replies that `src/slack/thread-buffer.ts` batches into a Lead task. A direct @mention of the bot creates a task without that header and is never gated.\n\nThe header counts only at the start of the description or right after the closing `</thread_context>`. Thread context quotes old messages verbatim, and an older Lead reply can quote the header itself, so a header inside the context is ignored. Only the text after the real header is treated as new.\n\n## Decision\n\n1. A follow-up with downloaded files (status `draft`) passes without a decision call.\n2. **@mention pass-through.** A new message that @mentions Lead passes without a decision call. A mention is the bot mention the engine rewrites to `<@U…> (that's you)`, a resolved `<@U…|lead>`, or a literal `@lead` (any name in `leadAliases`). Only the new messages are scanned, never the thread context, so an old mention earlier in the thread does not pass later banter.\n3. Otherwise one decision call (one `choice` question, see [Provider](#provider)) with the new message(s), the sender kind, and the last `contextMessages` thread messages. Labels: `direct_ask`, `followup_to_lead`, `instruction_to_lead`, `reaction_only`, `banter_between_others`, `not_addressed_to_lead`, `other`.\n4. The answer is no only when the top label is `reaction_only`, `banter_between_others`, or `not_addressed_to_lead`, and the summed probability of those three labels is at least `minConfidence`. A split between two skip labels is still a skip. A skip label below the threshold replies. With no probabilities, the top label's confidence stands in for the sum. With neither probabilities nor a confidence, the threshold is not applied and a skip label skips (in `enforce`, the message is dropped).\n\nSeveral buffered messages are judged together. One mention in any of them passes the batch.\n\n## Provider\n\nThe decision is made on the API server by the `system-one-decide` tool (`ctx.swarm.systemOne_decide`), the same path a `system-one-decision` workflow node takes. The server reads the provider's credential, sends the request, and validates the answer, so every SystemOne host works and no key enters the hook.\n\n| `provider` | Model | Credential |\n|---|---|---|\n| `typesafe` | Jev, `model` (default `jev-latest`) | `TYPESAFE_API_KEY` |\n| `openrouter` | Jev, `openrouterModel` (default `typesafe/jev-1.13`) | `OPENROUTER_API_KEY` |\n| `cloudflare` | Clef, `cloudflareModel` (default `clef`, or `clef-flash`) | `CLOUDFLARE_API_TOKEN` (or `CLOUDFLARE_API_KEY`) and `CLOUDFLARE_ACCOUNT_ID` |\n| `laya`, `openai` | The host's default model | See the workflows guide |\n| `auto` (default) | The first of typesafe, openrouter, cloudflare whose credential is set. A provider the server refuses for a deployment setting (openrouter when `OPENROUTER_BASE_URL` points at a gateway) is skipped for the next one | |\n\nWith no credential for `auto`, every message fails open and the KV row names the secrets. Each decision row records the `provider` that answered. `minConfidence` was tuned on Jev; check Clef's verdicts in `shadow` before you enforce on it.\n\n## Fail open\n\nEvery error lets the task through: a missing key, a provider error relayed by the server, a network error, a timeout, a malformed answer, or an unknown label. The handler never throws, so an outage cannot auto-disable the extension. Each failure is recorded as `fail-open` in KV and logged as a warning.\n\n## :mute: on drop (enforce)\n\nNo swarm tool or extension `ctx` method adds a Slack reaction, so the hook calls the Slack Web API with the bot token. It needs the `reactions:write` scope, which the Slack app already uses for its acceptance reactions.\n\n1. `reactions.remove` for each acceptance reaction the engine may have put on the triggering message: `eyes`, `heavy_plus_sign`, `zap`, `speech_balloon`, or their `SLACK_REACTION_ACCEPTED`, `SLACK_REACTION_BUFFERED`, `SLACK_REACTION_NOW`, and `SLACK_REACTION_STEERED` overrides. Slack only removes the bot's own reaction, so a human's :eyes: stays.\n2. `reactions.add` with `muteReaction` (default `mute`). `already_reacted` counts as success. Skipped when `muteReaction` is `\"\"`.\n\nThe block returns first and the Slack calls run after it. A slow or failing Slack call never delays the drop or turns it back into a task. Set `muteReaction` to `\"\"` for a true no-op: step 1 still clears the bot's acceptance reaction(s), and nothing is added.\n\n## Config\n\n| Key | Default | Notes |\n|---|---|---|\n| `mode` | `shadow` | `off`, `shadow`, or `enforce` |\n| `timeoutMs` | `3000` | Decision call timeout, capped at 4000 (the dispatcher cancels a handler at 5 s) |\n| `provider` | `auto` | `auto`, `typesafe`, `openrouter`, `cloudflare`, `laya`, or `openai`. See [Provider](#provider) |\n| `model` | `jev-latest` | Jev model on TypeSafe |\n| `openrouterModel` | `typesafe/jev-1.13` | Jev model on OpenRouter |\n| `cloudflareModel` | `clef` | Clef model on Cloudflare Workers AI |\n| `minConfidence` | `0.55` | Minimum summed skip probability to skip |\n| `contextMessages` | `6` | Thread messages sent to the model, 0 to 20 |\n| `leadAliases` | `[\"lead\"]` | A literal `@alias` in a new message counts as a mention |\n| `botSlackUserIds` | `[]` | Slack user ids labelled `bot` as the sender for the model |\n| `muteReaction` | `mute` | Reaction for a dropped message; `\"\"` only removes the acceptance reaction(s) |\n| `slackTimeoutMs` | `5000` | Timeout per Slack call |\n\n## Required secrets\n\nSet them as global `swarm_config` values. The server reads the provider credential from the global row when it makes the decision. `auto` and the Slack token read the API process environment, which loads global rows at boot and on config reload.\n\n- One provider credential from the [Provider](#provider) table is required for any evaluation. Without one, every message fails open. The `apiKey` config field of earlier versions is gone: the hook never holds a key, so store it as the global `TYPESAFE_API_KEY` secret.\n- `SLACK_BOT_TOKEN`: the Slack app's bot token. A swarm with Slack connected already has it. Without it, `enforce` still drops the message but cannot touch its reactions, and logs a `mute-error`.\n\nNo key is written to config, KV, logs, or a description.\n\n## KV namespace `ext:slack-reply-gate`\n\n- `d:<epochMs>:<channel>_<threadTs>`: one row per decision, with `action` (`pass`, `shadow-skip`, `skipped`, `fail-open`), `provider`, `reason`, `confidence`, `skipP`, `latencyMs`, `sender`, and a 300-character `preview`.\n- `m:<epochMs>:<channel>_<threadTs>`: one row per mute attempt, with `action` (`muted`, `unreacted` when `muteReaction` is `\"\"`, `mute-error`), `removed`, `added`, and `errors`.\n- `last`: the latest decision. Mute rows never overwrite it.\n- Counters: `total`, `mention`, `files`, `reply`, `shadow-skip`, `skipped`, `error`, `muted`, `unreacted`, `mute-error`, and `reason:<label>`.\n\n## Known limits\n\n- When Lead already has an active task in the thread, the buffer steers that task instead of creating one, so `pre.task.create` does not fire and the gate does not run.\n- A blocked flush makes the thread buffer log a `TaskCreationBlockedError`. Nothing is lost: the next follow-up's `<thread_context>` carries the earlier messages.\n- A flush of several messages mutes only the triggering (last) message. The others keep their acceptance reaction.\n"
120
120
  },
package/src/github/app.ts CHANGED
@@ -9,6 +9,13 @@ let privateKey: string | null = null;
9
9
  // Token cache: installationId -> { token, expiresAt }
10
10
  const tokenCache = new Map<number, { token: string; expiresAt: number }>();
11
11
 
12
+ /** Raw PEM (with literal `\\n` escapes) or base64-encoded PEM. */
13
+ function decodePrivateKey(raw: string): string {
14
+ return raw.startsWith("-----BEGIN")
15
+ ? raw.replace(/\\n/g, "\n")
16
+ : Buffer.from(raw, "base64").toString("utf-8");
17
+ }
18
+
12
19
  export function isGitHubEnabled(): boolean {
13
20
  // Check if GitHub is explicitly disabled
14
21
  if (isEnvFlagEnabled("GITHUB_DISABLE", false)) {
@@ -60,13 +67,7 @@ export function initGitHub(): boolean {
60
67
  const rawPrivateKey = process.env.GITHUB_APP_PRIVATE_KEY ?? null;
61
68
 
62
69
  if (appId && rawPrivateKey) {
63
- if (rawPrivateKey.startsWith("-----BEGIN")) {
64
- // Raw PEM format - convert \n escape sequences to actual newlines
65
- privateKey = rawPrivateKey.replace(/\\n/g, "\n");
66
- } else {
67
- // Base64 encoded - decode it
68
- privateKey = Buffer.from(rawPrivateKey, "base64").toString("utf-8");
69
- }
70
+ privateKey = decodePrivateKey(rawPrivateKey);
70
71
  console.log("[GitHub] App credentials loaded for bot reactions");
71
72
  } else {
72
73
  console.log("[GitHub] No App credentials, bot reactions disabled");
@@ -151,7 +152,10 @@ export async function verifyWebhookSignature(
151
152
  * Generate a JWT for GitHub App authentication
152
153
  * JWTs are valid for up to 10 minutes
153
154
  */
154
- async function generateAppJWT(): Promise<string | null> {
155
+ async function generateAppJWT(
156
+ creds: { appId: string | null; privateKey: string | null } = { appId, privateKey },
157
+ ): Promise<string | null> {
158
+ const { appId, privateKey } = creds;
155
159
  if (!appId || !privateKey) {
156
160
  return null;
157
161
  }
@@ -196,14 +200,23 @@ async function generateAppJWT(): Promise<string | null> {
196
200
  * Tokens are cached until they expire (typically 1 hour)
197
201
  */
198
202
  export async function getInstallationToken(installationId: number): Promise<string | null> {
203
+ return (
204
+ (await mintInstallationToken(installationId, { appId, privateKey }, 60_000))?.token ?? null
205
+ );
206
+ }
207
+
208
+ async function mintInstallationToken(
209
+ installationId: number,
210
+ creds: { appId: string | null; privateKey: string | null },
211
+ minValidityMs: number,
212
+ ): Promise<{ token: string; expiresAt: number } | null> {
199
213
  // Check cache first
200
214
  const cached = tokenCache.get(installationId);
201
- if (cached && cached.expiresAt > Date.now() + 60_000) {
202
- // Still valid for at least 1 minute
203
- return cached.token;
215
+ if (cached && cached.expiresAt > Date.now() + minValidityMs) {
216
+ return cached;
204
217
  }
205
218
 
206
- const jwt = await generateAppJWT();
219
+ const jwt = await generateAppJWT(creds);
207
220
  if (!jwt) {
208
221
  console.log("[GitHub] No JWT available, cannot get installation token");
209
222
  return null;
@@ -235,14 +248,46 @@ export async function getInstallationToken(installationId: number): Promise<stri
235
248
  const expiresAt = new Date(data.expires_at).getTime();
236
249
 
237
250
  // Cache the token
238
- tokenCache.set(installationId, { token: data.token, expiresAt });
251
+ const minted = { token: data.token, expiresAt };
252
+ tokenCache.set(installationId, minted);
239
253
 
240
254
  console.log(
241
255
  `[GitHub] Got installation token for ${installationId}, expires at ${data.expires_at}`,
242
256
  );
243
- return data.token;
257
+ return minted;
244
258
  } catch (error) {
245
259
  console.error("[GitHub] Error getting installation token:", error);
246
260
  return null;
247
261
  }
248
262
  }
263
+
264
+ export type WorkerInstallationToken =
265
+ | { status: "ok"; token: string; expiresAt: string }
266
+ | { status: "unconfigured" }
267
+ | { status: "error" };
268
+
269
+ /**
270
+ * Installation token for worker `git` / `gh`, minted for the one installation
271
+ * named by `GITHUB_APP_INSTALLATION_ID`. Callers never pick the installation, so
272
+ * no request can get a token for an installation the swarm is not configured for.
273
+ * Reads env on each call: it works without the webhook (`initGitHub` loads App
274
+ * credentials only when `GITHUB_WEBHOOK_SECRET` is set).
275
+ */
276
+ export async function getWorkerInstallationToken(): Promise<WorkerInstallationToken> {
277
+ if (isEnvFlagEnabled("GITHUB_DISABLE", false)) return { status: "unconfigured" };
278
+ const workerAppId = process.env.GITHUB_APP_ID?.trim();
279
+ const rawKey = process.env.GITHUB_APP_PRIVATE_KEY?.trim();
280
+ const rawInstallation = process.env.GITHUB_APP_INSTALLATION_ID?.trim() ?? "";
281
+ if (!workerAppId || !rawKey || !/^[1-9][0-9]{0,15}$/.test(rawInstallation)) {
282
+ return { status: "unconfigured" };
283
+ }
284
+ if (!resolveGitHubHost().ok) return { status: "error" };
285
+ // Hand out a token with at least 10 minutes left, so a worker can cache it.
286
+ const minted = await mintInstallationToken(
287
+ Number(rawInstallation),
288
+ { appId: workerAppId, privateKey: decodePrivateKey(rawKey) },
289
+ 10 * 60_000,
290
+ );
291
+ if (!minted) return { status: "error" };
292
+ return { status: "ok", token: minted.token, expiresAt: new Date(minted.expiresAt).toISOString() };
293
+ }
@@ -30,6 +30,7 @@ import "./extensions";
30
30
  import "./favorites";
31
31
  import "./checklist";
32
32
  import "./fs";
33
+ import "./github-token";
33
34
  import "./heartbeat";
34
35
  import "./inbox-state";
35
36
  import "./integrations";
@@ -51,6 +52,7 @@ import "./prompt-templates";
51
52
  import "./poll";
52
53
  import "./pricing";
53
54
  import "./repos";
55
+ import "./request-composition";
54
56
  import "./realtime";
55
57
  import "./rooms";
56
58
  import "./schedules";
@@ -28,6 +28,7 @@ import {
28
28
  } from "../be/swarm-config-guard";
29
29
  import { isScriptRunToken } from "../be/users";
30
30
  import { can, isRbacEnabled, type PermissionVerb } from "../rbac";
31
+ import { isSlackIconConfigKey } from "../slack/reaction-shortcode";
31
32
  import { type SwarmConfig, SwarmConfigSchema } from "../types";
32
33
  import { authUserId, getRequestAuth, type HttpRequestAuth } from "../utils/request-auth-context";
33
34
  import { registerVolatileSecret } from "../utils/secret-scrubber";
@@ -500,7 +501,7 @@ export async function handleConfig(
500
501
  // Organization identity is trimmed by both /status and telemetry.
501
502
  // Match that definition without changing presence semantics for secrets.
502
503
  const value = key === "SWARM_ORG_NAME" ? process.env[key]?.trim() : process.env[key];
503
- presence[key] = value !== undefined && value !== "";
504
+ presence[key] = value !== undefined && (isSlackIconConfigKey(key) || value !== "");
504
505
  }
505
506
  envPresence.respond(res, 200, { presence });
506
507
  return true;
package/src/http/core.ts CHANGED
@@ -153,6 +153,8 @@ export async function loadGlobalConfigsIntoEnv(override = false): Promise<string
153
153
  if (updated.length > 0) {
154
154
  refreshSecretScrubberCache();
155
155
  }
156
+ const { syncSlackTreeVisibility } = await import("../slack/tree-visibility");
157
+ await syncSlackTreeVisibility();
156
158
  return updated;
157
159
  }
158
160
 
@@ -0,0 +1,66 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { z } from "zod";
3
+ import { getWorkerInstallationToken } from "../github/app";
4
+ import { getRequestAuth } from "../utils/request-auth-context";
5
+ import { resolveRequestPrincipal } from "./request-principal";
6
+ import { route } from "./route-def";
7
+ import { jsonError } from "./utils";
8
+
9
+ const installationTokenRoute = route({
10
+ method: "post",
11
+ path: "/api/github/installation-token",
12
+ pattern: ["api", "github", "installation-token"],
13
+ summary: "Mint a GitHub App installation token for worker git and gh",
14
+ description:
15
+ "Internal worker endpoint. Returns a short-lived installation token for the installation in `GITHUB_APP_INSTALLATION_ID`, minted with the API server's GitHub App credentials. The caller cannot choose the installation. Only a registered agent (swarm API key plus X-Agent-ID, or an agent or runtime token) may call it; user, guest and ACP task tokens are refused. 404 when the App or the installation id is not configured, so workers fall back to `GITHUB_TOKEN`.",
16
+ tags: ["GitHub"],
17
+ body: z.object({}).optional(),
18
+ responses: {
19
+ 200: {
20
+ description: "Installation token and its expiry (ISO 8601)",
21
+ schema: z.object({ token: z.string(), expiresAt: z.string() }),
22
+ },
23
+ 403: { description: "Caller is not a registered agent" },
24
+ 404: { description: "GitHub App worker auth is not configured" },
25
+ 502: { description: "GitHub refused or failed to mint the token" },
26
+ },
27
+ auth: { apiKey: true, agentId: true },
28
+ rbac: {
29
+ ungated:
30
+ "the handler admits only registered agent principals and mints for one fixed installation",
31
+ },
32
+ });
33
+
34
+ export async function handleGitHubToken(
35
+ req: IncomingMessage,
36
+ res: ServerResponse,
37
+ pathSegments: string[],
38
+ myAgentId: string | undefined,
39
+ ): Promise<boolean> {
40
+ if (!installationTokenRoute.match(req.method, pathSegments)) return false;
41
+ const parsed = await installationTokenRoute.parse(req, res, pathSegments, new URLSearchParams());
42
+ if (!parsed) return true;
43
+ const principal = await resolveRequestPrincipal(req, myAgentId, {
44
+ precedence: "agent-first",
45
+ requireRegisteredAgent: true,
46
+ });
47
+ // Task tokens are ACP harness credentials (they read no secrets either): refuse them.
48
+ const auth = getRequestAuth(req);
49
+ const taskToken = auth?.kind === "agent" && auth.tokenKind === "task";
50
+ if (principal?.kind !== "agent" || !principal.agentId || taskToken) {
51
+ jsonError(res, "Only a registered agent may mint a GitHub installation token", 403);
52
+ return true;
53
+ }
54
+ const result = await getWorkerInstallationToken();
55
+ if (result.status === "unconfigured") {
56
+ jsonError(res, "GitHub App worker auth is not configured", 404);
57
+ return true;
58
+ }
59
+ if (result.status === "error") {
60
+ jsonError(res, "GitHub did not mint an installation token", 502);
61
+ return true;
62
+ }
63
+ res.setHeader("Cache-Control", "no-store");
64
+ installationTokenRoute.respond(res, 200, { token: result.token, expiresAt: result.expiresAt });
65
+ return true;
66
+ }