@desplega.ai/agent-swarm 2.8.3 → 2.9.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 (491) hide show
  1. package/dist/acp-adapter-jqn86aam.js +16 -0
  2. package/dist/acp-targets-swxq55dr.js +23 -0
  3. package/dist/{actions-ewz7bp4g.js → actions-pb678g3e.js} +20 -19
  4. package/dist/agent-fs-provision-dmhnc38q.js +27 -0
  5. package/dist/{amp-adapter-f25tqhnf.js → amp-adapter-3pa66q27.js} +3 -3
  6. package/dist/{anthropic-messages-jkva0zps.js → anthropic-messages-x2cp5fvf.js} +41 -41
  7. package/dist/{app-mkptw0k7.js → app-17d12ev4.js} +6 -4
  8. package/dist/approval-notifications-h7vd9pmg.js +20 -0
  9. package/dist/{assistant-c47rfe77.js → assistant-t7k39ree.js} +54 -33
  10. package/dist/{azure-openai-responses-wgtqkbr3.js → azure-openai-responses-590s1eea.js} +10 -10
  11. package/dist/{boot-args-schema-4vb0xsat.js → boot-args-schema-0gqmkfbe.js} +1 -1
  12. package/dist/{boot-reembed-1ghy2sab.js → boot-reembed-f064w382.js} +1 -1
  13. package/dist/{boot-reembed-htr73hbs.js → boot-reembed-n6anc01d.js} +1 -1
  14. package/dist/{boot-scrub-sweep-yrytg42z.js → boot-scrub-sweep-ejd5dnrz.js} +84 -13
  15. package/dist/{boot-seeds-n2b3dx4e.js → boot-seeds-f99fjs5q.js} +4 -4
  16. package/dist/{boxd-jmfqgkqa.js → boxd-wn235q80.js} +7 -7
  17. package/dist/claude-adapter-gvznwxgc.js +28 -0
  18. package/dist/{claude-managed-adapter-hddmxjyj.js → claude-managed-adapter-pbrbvc64.js} +4 -4
  19. package/dist/{claude-managed-setup-hfvry1bd.js → claude-managed-setup-kdxttvc3.js} +10 -10
  20. package/dist/{claude-sdk-session-0hamqzc7.js → claude-sdk-session-0t2teq6n.js} +9386 -9196
  21. package/dist/{cli-yjdgea32.js → cli-1jx0srjt.js} +17 -17
  22. package/dist/{cli-s8p8hhty.js → cli-1tvdx9t5.js} +2 -2
  23. package/dist/{cli-s7zz734a.js → cli-25nstr34.js} +1 -1
  24. package/dist/{cli-kw44j53p.js → cli-2kg31ted.js} +45 -38
  25. package/dist/{cli-mwwmka77.js → cli-2tnbc3gw.js} +375 -127
  26. package/dist/{cli-4dpkjc2e.js → cli-3zxdz9r7.js} +9 -9
  27. package/dist/{cli-mdpbjnzq.js → cli-4ghh072d.js} +14 -14
  28. package/dist/{cli-54qr8mcd.js → cli-57pvhnyt.js} +4 -4
  29. package/dist/{cli-f1kwb5fc.js → cli-5a6pqy45.js} +333 -21
  30. package/dist/{cli-93t5s4zq.js → cli-5gpqgs8b.js} +2 -2
  31. package/dist/{cli-4ax9mvvg.js → cli-5gygrr67.js} +9 -9
  32. package/dist/{cli-t5ys4ebm.js → cli-5kcmxwxv.js} +3 -3
  33. package/dist/{cli-k96cecs7.js → cli-5ntc4we6.js} +2948 -316
  34. package/dist/{cli-15204js0.js → cli-6237rnyr.js} +1 -1
  35. package/dist/cli-6dp0jkfj.js +754 -0
  36. package/dist/{cli-k2rw11py.js → cli-7831nhaw.js} +5 -5
  37. package/dist/{cli-7c5tgqhf.js → cli-7cgf614g.js} +10 -10
  38. package/dist/{cli-z8cvws4c.js → cli-7fx9jyfs.js} +852 -55
  39. package/dist/{cli-pe4d96rb.js → cli-7zm3b3f5.js} +1 -1
  40. package/dist/{cli-0bcgyj5b.js → cli-812paz57.js} +69 -6
  41. package/dist/{cli-ztq5z4e1.js → cli-8axx8vnw.js} +4 -4
  42. package/dist/cli-8x8y70av.js +103 -0
  43. package/dist/{cli-6yygkr0w.js → cli-95930z69.js} +15 -7
  44. package/dist/{cli-sdvcrq5x.js → cli-9a2rtd77.js} +16 -14
  45. package/dist/cli-9ttx00s3.js +137 -0
  46. package/dist/{cli-6ek0hff4.js → cli-a9hfzg2r.js} +3 -3
  47. package/dist/{cli-am1ptset.js → cli-aa8s22gn.js} +19 -14
  48. package/dist/{cli-4e1hfbpq.js → cli-bk9v1xrv.js} +19 -19
  49. package/dist/{cli-e2w34h6z.js → cli-c07v0qfa.js} +98 -54
  50. package/dist/{cli-dpsfwh7n.js → cli-c5cspahx.js} +24 -24
  51. package/dist/{cli-gpz1d0t2.js → cli-cw7mc1je.js} +4 -4
  52. package/dist/{cli-qmqt520k.js → cli-dd37e0cm.js} +2 -2
  53. package/dist/cli-dqgnbnxs.js +132 -0
  54. package/dist/{cli-tnzebztn.js → cli-dx439zpg.js} +1 -1
  55. package/dist/{cli-q6mfk1ej.js → cli-dzzh58sy.js} +2 -2
  56. package/dist/{cli-knva3nmx.js → cli-e9973bf0.js} +8 -6
  57. package/dist/{cli-2znm3dzj.js → cli-eds5xnsz.js} +2 -2
  58. package/dist/{cli-crpf163n.js → cli-eepnpee7.js} +16 -26
  59. package/dist/{cli-nx2n3z6p.js → cli-eg437b5p.js} +1 -1
  60. package/dist/{cli-zdaypkq9.js → cli-faf46gdq.js} +285 -97
  61. package/dist/{cli-tas6ckky.js → cli-fgphc007.js} +2 -2
  62. package/dist/{cli-sg27rk2t.js → cli-fnh4b12r.js} +24 -18
  63. package/dist/{cli-fsgttth8.js → cli-g0vv9dg4.js} +13 -13
  64. package/dist/{cli-rqfvkx5t.js → cli-g3zzby8t.js} +13 -13
  65. package/dist/{cli-kd56bmk4.js → cli-gabsjg8x.js} +3 -1
  66. package/dist/{cli-tf79ryyy.js → cli-gddgcnav.js} +3 -3
  67. package/dist/{cli-rjvsf9qa.js → cli-h474mvp5.js} +11 -11
  68. package/dist/{cli-5a7szzfh.js → cli-hnamkvnc.js} +2 -2
  69. package/dist/{cli-8bpgbr8k.js → cli-j49yqpvh.js} +6 -6
  70. package/dist/{cli-awwptga4.js → cli-jd3kxppb.js} +1 -1
  71. package/dist/{cli-1m96dc36.js → cli-js8zrfyg.js} +3 -3
  72. package/dist/{cli-vx421edw.js → cli-k09cxm6m.js} +9 -7
  73. package/dist/{cli-n5t077me.js → cli-k7pt28ad.js} +10 -3
  74. package/dist/{cli-922z7gwm.js → cli-kaa4bd7x.js} +9 -6
  75. package/dist/cli-kj0hyr43.js +51 -0
  76. package/dist/{cli-c0xjnr8z.js → cli-kmvcm34h.js} +2 -2
  77. package/dist/{cli-0vksaxvr.js → cli-kqh27v2y.js} +2 -2
  78. package/dist/{cli-bj6qhgte.js → cli-m1fbz2wj.js} +30 -37
  79. package/dist/{cli-me0r8gzr.js → cli-mc1fx4xd.js} +27 -25
  80. package/dist/{cli-qps8je6j.js → cli-me4maa4j.js} +46 -6
  81. package/dist/{cli-504akrp9.js → cli-meydjstb.js} +3 -3
  82. package/dist/{cli-n30e0hcp.js → cli-mna6pmfx.js} +2 -2
  83. package/dist/{cli-yss07azk.js → cli-nhq5js1b.js} +3 -3
  84. package/dist/cli-nmcpzbty.js +296 -0
  85. package/dist/cli-nr46j5pw.js +78 -0
  86. package/dist/{cli-t4dv07kr.js → cli-pn1v1pb0.js} +1 -1
  87. package/dist/{cli-c71n3bxq.js → cli-pwsax0vp.js} +2 -2
  88. package/dist/{cli-9zmb7ptc.js → cli-pz1c00aa.js} +8 -753
  89. package/dist/{cli-emekyyhr.js → cli-q2d3e1k1.js} +1 -1
  90. package/dist/{cli-zeaehgyd.js → cli-q8cfh1t9.js} +2 -2
  91. package/dist/{cli-vqva1teb.js → cli-qe909n63.js} +2 -2
  92. package/dist/{cli-2d0cghfn.js → cli-qj39vrc6.js} +1 -1
  93. package/dist/{cli-0agcv1v5.js → cli-rqx70rcz.js} +2 -2
  94. package/dist/{cli-gn9y6fn7.js → cli-rts1qvb4.js} +2 -2
  95. package/dist/{cli-pxwtcgcp.js → cli-sn4pc4qx.js} +2 -2
  96. package/dist/{cli-98rwmcyc.js → cli-snxhtehz.js} +3 -3
  97. package/dist/{cli-d829z3xc.js → cli-spfz393q.js} +6 -6
  98. package/dist/{cli-6wj7p986.js → cli-spzkdgtg.js} +3 -3
  99. package/dist/{cli-m2z8jagn.js → cli-srtkr1h2.js} +18 -18
  100. package/dist/{cli-8476gtwf.js → cli-ssvdrk4y.js} +1 -1
  101. package/dist/{cli-c3ng0mb4.js → cli-svc803vq.js} +69 -816
  102. package/dist/{cli-500c09j9.js → cli-t9ga4qmb.js} +14 -14
  103. package/dist/{cli-j8cjdzan.js → cli-vs9vdpy0.js} +1 -1
  104. package/dist/{cli-bhsfbmk8.js → cli-vvgaz8t6.js} +93 -44
  105. package/dist/{cli-kmemts3w.js → cli-vw5x18yj.js} +39 -69
  106. package/dist/{cli-x3ex5bqf.js → cli-w16kwbzw.js} +1 -1
  107. package/dist/cli-w7dxb2fj.js +921 -0
  108. package/dist/{cli-x6t50dmw.js → cli-wr1h0k28.js} +3 -3
  109. package/dist/{cli-skmhsnqh.js → cli-x40a0w9j.js} +1 -1
  110. package/dist/{cli-k28wkapa.js → cli-xf1wn5ns.js} +2 -2
  111. package/dist/{cli-rh15cakt.js → cli-xwsm6xkr.js} +1 -1
  112. package/dist/{cli-h9yy18gy.js → cli-ymct0ycy.js} +262 -100
  113. package/dist/{cli-dtdht77h.js → cli-zg3z63x3.js} +2 -2
  114. package/dist/cli.js +27 -24
  115. package/dist/{codex-adapter-2brxx5ta.js → codex-adapter-44yq2fkn.js} +9 -8
  116. package/dist/{codex-hook-c930c3ea.js → codex-hook-h1zb7cfk.js} +6 -6
  117. package/dist/{codex-login-cbrs1h5w.js → codex-login-cdyrr5y1.js} +1 -1
  118. package/dist/{codex-session-runner-y9anfj0r.js → codex-session-runner-zbh26gbw.js} +10 -9
  119. package/dist/{commands-wn9q06qr.js → commands-54f02v5b.js} +3 -3
  120. package/dist/{controller-fw608czd.js → controller-9gpwcdek.js} +6 -6
  121. package/dist/{controllers-connect-63j5rdcm.js → controllers-connect-61re6k1n.js} +26 -25
  122. package/dist/{cursor-adapter-6mb9jme8.js → cursor-adapter-7e4g81vd.js} +2 -2
  123. package/dist/{db-y4wfrzbm.js → db-dg2gc7fd.js} +15 -13
  124. package/dist/{db-0m6v5tq4.js → db-wnh0qjy1.js} +3 -3
  125. package/dist/{devin-adapter-r0yx3gv8.js → devin-adapter-zp4tqq53.js} +1 -1
  126. package/dist/{dispatcher-9tq2zzdj.js → dispatcher-jrm24r43.js} +19 -18
  127. package/dist/{docker-j75atvpt.js → docker-9aq30pp2.js} +5 -5
  128. package/dist/{dsh-adapter-t09sv4tq.js → dsh-adapter-1yqk267c.js} +2 -2
  129. package/dist/{e2b-a7vzs2vj.js → e2b-3v1e745x.js} +6 -6
  130. package/dist/{e2b-7s9dscap.js → e2b-sm28k0k3.js} +6 -6
  131. package/dist/{easter-egg-3d-fbwvmwhe.js → easter-egg-3d-r4h9cs9m.js} +1 -1
  132. package/dist/{embedding-space-wh8de1t9.js → embedding-space-bafjr5f7.js} +6 -6
  133. package/dist/{embeddings-3hpbdtjr.js → embeddings-7xmgqe0e.js} +1 -1
  134. package/dist/{event-bus-tr6h3gv8.js → event-bus-xr83x566.js} +1 -1
  135. package/dist/{execute-4bdf8sdy.js → execute-d6jg5ns0.js} +1 -1
  136. package/dist/{external-channel-ts2fwqh0.js → external-channel-frq1xvq2.js} +2 -2
  137. package/dist/fx-adapter-0zrkfbkd.js +19 -0
  138. package/dist/{getMachineId-bsd-nfgrzarv.js → getMachineId-bsd-637a7rbk.js} +3 -3
  139. package/dist/{getMachineId-darwin-wz886dsk.js → getMachineId-darwin-9vytrcnn.js} +3 -3
  140. package/dist/{getMachineId-linux-1nng3p1p.js → getMachineId-linux-mkzsvyyz.js} +3 -3
  141. package/dist/{getMachineId-unsupported-a0428vw9.js → getMachineId-unsupported-4cfs2n11.js} +3 -3
  142. package/dist/{getMachineId-win-h45922nq.js → getMachineId-win-154s3qma.js} +3 -3
  143. package/dist/{google-generative-ai-h7s3e9kk.js → google-generative-ai-hh7strj3.js} +1 -1
  144. package/dist/{google-vertex-fhxaafzw.js → google-vertex-fy5bw2pm.js} +5 -5
  145. package/dist/grok-adapter-3db1c538.js +19 -0
  146. package/dist/handlers-k22n8mnn.js +33 -0
  147. package/dist/{heartbeat-2ze5fzpc.js → heartbeat-6bpa611t.js} +22 -21
  148. package/dist/{hook-ca54yd4s.js → hook-hvm5nf46.js} +5 -5
  149. package/dist/{hook-gaehe2w5.js → hook-w12k146y.js} +14 -14
  150. package/dist/{http-jfg8t2yk.js → http-43tthdvs.js} +1684 -509
  151. package/dist/{index-d6wkh8ar.js → index-1f0vypbg.js} +2 -2
  152. package/dist/{index-enn321kd.js → index-42jq9yy3.js} +3 -3
  153. package/dist/{index-khe3gp0k.js → index-4b1q8kan.js} +20 -20
  154. package/dist/{index-hjhfk3ra.js → index-585gyczt.js} +1 -1
  155. package/dist/index-8xcyd3mc.js +33 -0
  156. package/dist/index-9sy2bh6n.js +38 -0
  157. package/dist/{index-2skqtd76.js → index-b24j7t2m.js} +30 -28
  158. package/dist/{index-gjwaqaq8.js → index-cret47a5.js} +6 -6
  159. package/dist/{index-qwj6ntem.js → index-e3krvkh2.js} +4 -4
  160. package/dist/{index-csgrxedz.js → index-fn054vsf.js} +1 -1
  161. package/dist/{index-3yvzbhxd.js → index-ftywhyr0.js} +129 -142
  162. package/dist/{index-3gv6sc4z.js → index-mhq4sh5w.js} +1 -1
  163. package/dist/index-tx9mc2ap.js +570 -0
  164. package/dist/index-wjd56k1v.js +34 -0
  165. package/dist/{keepalive-k2a3qe73.js → keepalive-rk0j0jvh.js} +4 -4
  166. package/dist/lead-atxf3q6e.js +72 -0
  167. package/dist/{maintenance-gb5sd5nc.js → maintenance-g6z6kaxw.js} +1 -1
  168. package/dist/{node-252anz2h.js → node-jftbyawr.js} +4 -4
  169. package/dist/{node-ray25snp.js → node-zd6shky9.js} +3 -3
  170. package/dist/{oauth-refresh-sweep-y7rm6bkb.js → oauth-refresh-sweep-2k3g2q4w.js} +3 -3
  171. package/dist/{onboard-jmc5qerv.js → onboard-6fdbvh3v.js} +8 -8
  172. package/dist/{openai-codex-responses-k9gapdze.js → openai-codex-responses-bkcd8pjj.js} +9 -9
  173. package/dist/{openai-responses-4d5dx3c7.js → openai-responses-gbh0wfqe.js} +13 -13
  174. package/dist/{opencode-adapter-7eade9ev.js → opencode-adapter-fdbsvts7.js} +7 -6
  175. package/dist/{otel-impl-8j1xhxqd.js → otel-impl-rvwtc09q.js} +110 -110
  176. package/dist/pending-sqkrb836.js +80 -0
  177. package/dist/{pi-mono-adapter-yqmaf32x.js → pi-mono-adapter-asqayqcg.js} +12 -12
  178. package/dist/{pricing-refresh-1nj722h6.js → pricing-refresh-f5tkgmw2.js} +2 -2
  179. package/dist/{rbac-roles-b1mtr6dr.js → rbac-roles-06s555fa.js} +3 -3
  180. package/dist/{rbac-roles-n1f3frk1.js → rbac-roles-szxsg8t1.js} +10 -3
  181. package/dist/{render-v2-1gfpd8rj.js → render-v2-103p266q.js} +4 -4
  182. package/dist/{resume-w1s1eh5v.js → resume-v7kjewt9.js} +8 -7
  183. package/dist/{runtime-84g5egsc.js → runtime-f1gmk0b7.js} +1 -1
  184. package/dist/{session-access-y6z1txk4.js → session-access-6shev8ts.js} +4 -4
  185. package/dist/{session-source-backfill-gxxwfh12.js → session-source-backfill-bd7spzjd.js} +3 -3
  186. package/dist/{setup-r91gstyk.js → setup-kmxmztdb.js} +1 -1
  187. package/dist/thread-buffer-4yz236d0.js +36 -0
  188. package/dist/{virtual-modules-cgnj6kme.js → virtual-modules-57eje5wy.js} +5 -5
  189. package/dist/{work-objects-qcxzg61c.js → work-objects-zr47ygmf.js} +23 -21
  190. package/dist/{worker-follow-up-y2d2h7km.js → worker-follow-up-grrr3fda.js} +19 -18
  191. package/dist/worker-p4hbtcy3.js +72 -0
  192. package/dist/{x-qhxq2ama.js → x-wg164ss9.js} +2 -2
  193. package/openapi.json +1211 -155
  194. package/package.json +9 -6
  195. package/plugin/commands/create-pr.md +1 -1
  196. package/plugin/pi-skills/create-pr/SKILL.md +1 -1
  197. package/src/apps/action-runner.ts +21 -1
  198. package/src/apps/catalog.generated.json +626 -17
  199. package/src/apps/page-validator.ts +314 -8
  200. package/src/assets/key.ts +6 -0
  201. package/src/be/agent-fs-user-keys.ts +186 -0
  202. package/src/be/audit-user.ts +27 -13
  203. package/src/be/automation-preflight.test.ts +14 -14
  204. package/src/be/automation-preflight.ts +24 -16
  205. package/src/be/boot-scrub-sweep.ts +143 -14
  206. package/src/be/caller-session-group.ts +86 -0
  207. package/src/be/checklist.ts +375 -0
  208. package/src/be/db/agents.ts +12 -1
  209. package/src/be/db/approvals.ts +26 -0
  210. package/src/be/db/session-moves.ts +23 -0
  211. package/src/be/db/session-tree.ts +78 -19
  212. package/src/be/db/tasks/eligibility-scan.ts +14 -0
  213. package/src/be/db/tasks/slack-fold.ts +116 -0
  214. package/src/be/db/tasks/write.ts +34 -0
  215. package/src/be/db-queries/mcp-servers.ts +13 -0
  216. package/src/be/db-queries/oauth.ts +6 -0
  217. package/src/be/db-queries/task-artifacts.ts +10 -8
  218. package/src/be/db.ts +42 -15
  219. package/src/be/extensions/assets.ts +17 -13
  220. package/src/be/import/config.ts +54 -0
  221. package/src/be/import/dir-source.ts +372 -0
  222. package/src/be/import/index.ts +149 -0
  223. package/src/be/import/pending.ts +71 -0
  224. package/src/be/import/schema.ts +137 -0
  225. package/src/be/import/seeders.ts +462 -0
  226. package/src/be/migrations/297_import_ownership.sql +34 -0
  227. package/src/be/migrations/301_favorites_key_type.sql +36 -0
  228. package/src/be/migrations/302_checklist_items.sql +23 -0
  229. package/src/be/multi-runtime.ts +8 -1
  230. package/src/be/rbac-roles.ts +8 -1
  231. package/src/be/runtime-pools/demand.ts +20 -2
  232. package/src/be/runtime-pools/reachability.ts +31 -0
  233. package/src/be/runtime-pools/routing.ts +8 -1
  234. package/src/be/runtime-pools/supervisor.ts +6 -7
  235. package/src/be/savings/read.ts +8 -6
  236. package/src/be/script-credential-broker.ts +2 -2
  237. package/src/be/scripts/typecheck.ts +4 -4
  238. package/src/be/seed/agent-fs-provision.ts +104 -19
  239. package/src/be/seed/index.ts +1 -1
  240. package/src/be/seed/registry.ts +27 -8
  241. package/src/be/seed/runner.ts +1 -1
  242. package/src/be/seed/schedules-seeder.ts +24 -6
  243. package/src/be/seed/seed-toggle.ts +32 -0
  244. package/src/be/seed/types.ts +6 -0
  245. package/src/be/seed-scripts/catalog/dreaming-gather.ts +2 -2
  246. package/src/be/steering.ts +27 -4
  247. package/src/be/swarm-config-guard.ts +30 -0
  248. package/src/be/task-citations.ts +8 -5
  249. package/src/commands/onboard/agent-fs-version.ts +1 -1
  250. package/src/commands/runner.ts +61 -2
  251. package/src/e2b/env.ts +2 -0
  252. package/src/extensions/catalog.generated.json +17 -0
  253. package/src/extensions/contract-types.generated.ts +1 -1
  254. package/src/github/app.ts +10 -1
  255. package/src/github/handlers.ts +6 -3
  256. package/src/github/reactions.ts +12 -14
  257. package/src/heartbeat/heartbeat.ts +14 -4
  258. package/src/http/agents.ts +19 -10
  259. package/src/http/all-routes.ts +2 -0
  260. package/src/http/approval-requests.ts +24 -4
  261. package/src/http/apps.ts +69 -5
  262. package/src/http/checklist.ts +176 -0
  263. package/src/http/db-query-bounded.ts +256 -11
  264. package/src/http/db-query-shared.ts +9 -0
  265. package/src/http/favorites.ts +14 -2
  266. package/src/http/fs.ts +346 -1
  267. package/src/http/index.ts +29 -1
  268. package/src/http/kv.ts +13 -0
  269. package/src/http/mcp-oauth.ts +1 -1
  270. package/src/http/mcp-servers.ts +15 -2
  271. package/src/http/onboarding.ts +2 -9
  272. package/src/http/poll.ts +45 -0
  273. package/src/http/script-connections.ts +1 -0
  274. package/src/http/sessions.ts +17 -0
  275. package/src/http/slack-events.ts +101 -0
  276. package/src/http/status.ts +25 -7
  277. package/src/http/task-requester.ts +46 -0
  278. package/src/http/tasks.ts +64 -37
  279. package/src/http/users.ts +14 -0
  280. package/src/http/webhooks.ts +15 -0
  281. package/src/integrations/cards/index.ts +151 -0
  282. package/src/integrations/chat-sdk/outbound.ts +39 -13
  283. package/src/integrations/chat-sdk/runtime.ts +7 -1
  284. package/src/integrations/chat-sdk/status.ts +17 -0
  285. package/src/integrations/chat-sdk/telegram-api.ts +6 -1
  286. package/src/kv-reserved-namespaces.ts +17 -2
  287. package/src/oauth/presets.ts +29 -2
  288. package/src/prompts/base-prompt.ts +17 -4
  289. package/src/prompts/session-templates.ts +83 -6
  290. package/src/providers/acp-targets.ts +1 -1
  291. package/src/providers/amp-adapter.ts +1 -1
  292. package/src/providers/claude-managed-adapter.ts +5 -1
  293. package/src/providers/codex-adapter.ts +1 -1
  294. package/src/providers/codex-app-server.ts +2 -11
  295. package/src/providers/opencode-adapter.ts +7 -19
  296. package/src/providers/runtime-dependencies.ts +158 -0
  297. package/src/rbac/legacy-policy.ts +2 -0
  298. package/src/rbac/permissions.ts +10 -1
  299. package/src/scripts-runtime/credential-broker/default-bindings.ts +19 -11
  300. package/src/scripts-runtime/credential-broker/index.ts +1 -1
  301. package/src/scripts-runtime/egress-secrets.ts +2 -2
  302. package/src/scripts-runtime/swarm-sdk.ts +3 -2
  303. package/src/scripts-runtime/types/stdlib.d.ts +11 -4
  304. package/src/scripts-runtime/types/swarm-extension.d.ts +1 -1
  305. package/src/scripts-runtime/types/swarm-sdk.d.ts +11 -4
  306. package/src/server.ts +4 -4
  307. package/src/slack/app.ts +87 -46
  308. package/src/slack/assistant.ts +33 -7
  309. package/src/slack/handlers.ts +6 -4
  310. package/src/slack/http-receiver.ts +284 -0
  311. package/src/slack/inbound-dispatch.ts +43 -7
  312. package/src/slack/inbound-files.ts +33 -14
  313. package/src/slack/message-text.ts +47 -4
  314. package/src/slack/render-v2.ts +2 -1
  315. package/src/slack/socket-ack.ts +17 -10
  316. package/src/slack/steering.ts +5 -0
  317. package/src/slack/thread-buffer-store.ts +58 -0
  318. package/src/slack/thread-buffer.ts +341 -57
  319. package/src/tasks/context-key.ts +24 -0
  320. package/src/tasks/sibling-awareness.ts +13 -1
  321. package/src/tests/agent-fs-live-url.test.ts +15 -0
  322. package/src/tests/agent-fs-provision-seeder.test.ts +140 -0
  323. package/src/tests/agent-fs-user-keys.test.ts +483 -0
  324. package/src/tests/agentfs-proxy.test.ts +8 -8
  325. package/src/tests/approval-card-resolution.test.ts +396 -0
  326. package/src/tests/approval-requests-notifications.test.ts +1 -1
  327. package/src/tests/approval-respond-auth.test.ts +28 -0
  328. package/src/tests/apps-action-parent-task.test.ts +140 -0
  329. package/src/tests/apps-catalog-additions.test.ts +315 -0
  330. package/src/tests/apps-catalog-files.test.ts +114 -0
  331. package/src/tests/apps-catalog-hitl.test.ts +117 -0
  332. package/src/tests/apps-catalog-inputs.test.ts +86 -0
  333. package/src/tests/apps-catalog-table.test.ts +47 -0
  334. package/src/tests/apps-chart-shell.test.ts +1 -1
  335. package/src/tests/apps-element-assembly.test.ts +52 -3
  336. package/src/tests/apps-session-thread.test.ts +182 -0
  337. package/src/tests/asset-key-invariants.test.ts +14 -0
  338. package/src/tests/base-prompt.test.ts +107 -23
  339. package/src/tests/boot-scrub-sweep.test.ts +172 -0
  340. package/src/tests/caller-session-group.test.ts +199 -0
  341. package/src/tests/cards.test.ts +169 -0
  342. package/src/tests/chat-sdk-status-route.test.ts +16 -3
  343. package/src/tests/chat-sdk-telegram-token.test.ts +76 -0
  344. package/src/tests/chat-sdk-tools.test.ts +147 -0
  345. package/src/tests/checklist-nudge.test.ts +208 -0
  346. package/src/tests/checklist.test.ts +686 -0
  347. package/src/tests/codex-app-server.test.ts +16 -0
  348. package/src/tests/comb-config-guard.test.ts +21 -0
  349. package/src/tests/comb-default.test.ts +59 -97
  350. package/src/tests/comb-links.test.ts +86 -16
  351. package/src/tests/comb-status.test.ts +24 -27
  352. package/src/tests/create-page-tool.test.ts +101 -1
  353. package/src/tests/create-schedule-key.test.ts +105 -0
  354. package/src/tests/credential-broker.test.ts +2 -2
  355. package/src/tests/db-query.test.ts +87 -1
  356. package/src/tests/db-task-read-contract.test.ts +1 -0
  357. package/src/tests/db-task-write-contract.test.ts +2 -1
  358. package/src/tests/docs-index-footprint.test.js +3 -3
  359. package/src/tests/entrypoint-github-enterprise.test.ts +158 -0
  360. package/src/tests/extensions-assets.test.ts +7 -3
  361. package/src/tests/extensions-catalog.test.ts +1 -0
  362. package/src/tests/extensions-example-sql-admin-only.test.ts +198 -0
  363. package/src/tests/extensions-pre-task.test.ts +3 -3
  364. package/src/tests/extensions-steering.test.ts +14 -2
  365. package/src/tests/favorites-agent-fs-path.test.ts +124 -0
  366. package/src/tests/fetch-resolved-env.test.ts +68 -0
  367. package/src/tests/fixtures/import-package.ts +32 -0
  368. package/src/tests/fixtures/runner-missing-dependency.ts +129 -0
  369. package/src/tests/fs-routes.test.ts +505 -2
  370. package/src/tests/github-ghes-mock.test.ts +196 -0
  371. package/src/tests/github-host.test.ts +285 -0
  372. package/src/tests/heartbeat-supersede-resume.test.ts +73 -0
  373. package/src/tests/heartbeat.test.ts +56 -0
  374. package/src/tests/import-config.test.ts +209 -0
  375. package/src/tests/import.test.ts +464 -0
  376. package/src/tests/invites-http.test.ts +144 -1
  377. package/src/tests/kv-http.test.ts +11 -0
  378. package/src/tests/literal-matcher.test.ts +58 -0
  379. package/src/tests/mcp-oauth-manual-client.test.ts +1 -1
  380. package/src/tests/oauth-presets.test.ts +12 -0
  381. package/src/tests/pool-affinity.test.ts +50 -0
  382. package/src/tests/prompt-template-session.test.ts +52 -5
  383. package/src/tests/provider-registration.test.ts +2 -55
  384. package/src/tests/provider-runtime-dependencies.test.ts +212 -0
  385. package/src/tests/rbac-admission.test.ts +19 -0
  386. package/src/tests/rbac-charact-misc-tools.test.ts +31 -0
  387. package/src/tests/rbac-engine.test.ts +2 -0
  388. package/src/tests/rbac-roles.test.ts +2 -0
  389. package/src/tests/runner-missing-dependency.test.ts +61 -0
  390. package/src/tests/runtime-pool-reachability.test.ts +135 -1
  391. package/src/tests/runtime-pool-routing.test.ts +52 -0
  392. package/src/tests/runtime-stale-threshold.test.ts +40 -0
  393. package/src/tests/savings-fleet-slices.test.ts +122 -0
  394. package/src/tests/savings-read.test.ts +41 -0
  395. package/src/tests/savings-scripts.test.ts +9 -3
  396. package/src/tests/script-connections.test.ts +2 -0
  397. package/src/tests/script-executor-conformance.test.ts +41 -4
  398. package/src/tests/secret-scrub-gate.test.ts +257 -0
  399. package/src/tests/seed-registry.test.ts +142 -9
  400. package/src/tests/session-source-keys.test.ts +42 -1
  401. package/src/tests/sessions-move.test.ts +70 -0
  402. package/src/tests/sessions-tree.test.ts +98 -0
  403. package/src/tests/sessions.test.ts +69 -0
  404. package/src/tests/slack-config.test.ts +4 -18
  405. package/src/tests/slack-http-receiver.test.ts +472 -0
  406. package/src/tests/slack-inbound-logging.test.ts +64 -0
  407. package/src/tests/slack-leave-thread.test.ts +1 -1
  408. package/src/tests/slack-message-text.test.ts +104 -0
  409. package/src/tests/slack-mode-lifecycle.test.ts +6 -4
  410. package/src/tests/slack-render-v2.test.ts +48 -0
  411. package/src/tests/slack-skip-reaction.test.ts +2 -2
  412. package/src/tests/slack-steering.test.ts +22 -10
  413. package/src/tests/slack-thread-buffer-context.test.ts +1 -1
  414. package/src/tests/slack-thread-buffer-fold.test.ts +417 -0
  415. package/src/tests/slack-thread-buffer-restore.test.ts +198 -0
  416. package/src/tests/slack-thread-buffer-startup-restore.test.ts +86 -0
  417. package/src/tests/slack-thread-buffer.test.ts +34 -34
  418. package/src/tests/slack-thread-participants.test.ts +23 -5
  419. package/src/tests/slack-tool-blocks.test.ts +167 -0
  420. package/src/tests/status.test.ts +32 -6
  421. package/src/tests/steering-core.test.ts +13 -0
  422. package/src/tests/steering-enabled.test.ts +7 -1
  423. package/src/tests/steering-promotion.test.ts +24 -0
  424. package/src/tests/swarm-config-reserved-keys.test.ts +17 -0
  425. package/src/tests/system-one-hosts-ui-mirror.test.ts +67 -0
  426. package/src/tests/task-artifacts.test.ts +50 -0
  427. package/src/tests/task-session-prompts.test.ts +95 -1
  428. package/src/tests/workflow-system-one-extraction.test.ts +149 -1
  429. package/src/tools/chat-post.ts +19 -4
  430. package/src/tools/chat-reply.ts +20 -4
  431. package/src/tools/create-page.ts +21 -4
  432. package/src/tools/get-swarm.ts +18 -2
  433. package/src/tools/join-swarm.ts +2 -1
  434. package/src/tools/kv/kv-write-auth.ts +17 -1
  435. package/src/tools/schedules/create-schedule.ts +22 -4
  436. package/src/tools/slack-post.ts +40 -7
  437. package/src/tools/slack-reply.ts +50 -14
  438. package/src/types.ts +43 -2
  439. package/src/utils/constants.ts +60 -138
  440. package/src/utils/github-host.ts +217 -0
  441. package/src/utils/github-pull-request.ts +8 -5
  442. package/src/utils/literal-matcher.ts +118 -0
  443. package/src/utils/secret-scrubber.ts +331 -25
  444. package/src/utils/task-attachment-links.ts +9 -12
  445. package/src/vcs/index.ts +3 -0
  446. package/src/workflows/approval-notifications.ts +188 -12
  447. package/src/workflows/executors/system-one-extraction.ts +14 -7
  448. package/src/workflows/executors/system-one-providers.ts +22 -1
  449. package/templates/community/open-prompt-showreel/PLAYBOOK.md +1 -1
  450. package/templates/community/open-prompt-showreel/skills/open-prompt-showreel/SKILL.md +1 -1
  451. package/templates/extensions/README.md +1 -0
  452. package/templates/extensions/sql-admin-only/README.md +19 -0
  453. package/templates/extensions/sql-admin-only/hooks.ts +96 -0
  454. package/templates/extensions/sql-admin-only/manifest.json +8 -0
  455. package/templates/import/manifest.schema.json +136 -0
  456. package/templates/import/sources.schema.json +44 -0
  457. package/templates/skills/agent-browser/SKILL.md +1 -1
  458. package/templates/skills/agent-browser/content.md +1 -1
  459. package/templates/skills/apps/SKILL.md +122 -12
  460. package/templates/skills/apps/content.md +122 -12
  461. package/templates/skills/asset-namespaces/content.md +2 -1
  462. package/templates/skills/chat-sdk/content.md +17 -0
  463. package/templates/skills/db-query-guidance/content.md +2 -1
  464. package/templates/skills/scheduling/content.md +27 -0
  465. package/templates/skills/slack-interaction/content.md +12 -2
  466. package/templates/skills/swarm-docs/content.md +1 -0
  467. package/templates/skills/swarm-extensions/config.json +1 -1
  468. package/templates/skills/swarm-extensions/content.md +33 -23
  469. package/templates/skills/swarm-scripts/SKILL.md +13 -0
  470. package/templates/skills/swarm-scripts/content.md +13 -0
  471. package/templates/skills/work-on-task/SKILL.md +1 -1
  472. package/templates/skills/work-on-task/content.md +1 -1
  473. package/templates/skills/workflow-iterate/content.md +4 -7
  474. package/templates/workflows/dreaming/content.md +2 -2
  475. package/dist/acp-adapter-xq6s2z6t.js +0 -14
  476. package/dist/claude-adapter-r33pqnzx.js +0 -24
  477. package/dist/cli-dns0y538.js +0 -194
  478. package/dist/fx-adapter-1rnxnf56.js +0 -17
  479. package/dist/grok-adapter-efhmf1r8.js +0 -17
  480. package/dist/handlers-anrr3py9.js +0 -32
  481. package/dist/index-8w2aznds.js +0 -33
  482. package/dist/index-qnjvr362.js +0 -37
  483. package/dist/index-yzxd3sn9.js +0 -32
  484. package/dist/lead-zhxqbfdv.js +0 -69
  485. package/dist/worker-7j2907g6.js +0 -69
  486. package/src/tests/entrypoint-acp-target-binary.test.ts +0 -439
  487. package/dist/{cli-4caa1x7d.js → cli-tsa40663.js} +4 -4
  488. package/dist/{index-0rvk3vd4.js → index-bs7gw5fd.js} +3 -3
  489. package/dist/{mistral-conversations-a45tx39a.js → mistral-conversations-0c30em7t.js} +4 -4
  490. package/dist/{openai-completions-xd579js7.js → openai-completions-f3n69rep.js} +18 -18
  491. package/dist/{pi-messages-hjbv8v10.js → pi-messages-zebyt7gb.js} +5 -5
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  bedrockProviderModule
3
- } from "./cli-fsgttth8.js";
3
+ } from "./cli-g0vv9dg4.js";
4
4
  import {
5
5
  chatThreadOfContextKey,
6
6
  agentContextKey,
@@ -139,11 +139,68 @@ import {
139
139
  hasCapacity2,
140
140
  updateAgentStatusFromCapacity2,
141
141
  getAgentDailyTaskCounts2,
142
- listApprovalRequestSummaries2,
143
- getPendingApprovalVoteState2,
144
- recordApprovalVotes2,
145
- getPendingApprovalsForTasks2,
146
- computeContentHash2,
142
+ getWorkflowRunSummary,
143
+ getWorkflowRunStepsSlimByRunId,
144
+ WORKFLOW_RUN_TREE_MAX_DEPTH,
145
+ WorkflowRunTreeError,
146
+ getWorkflowRunTree,
147
+ getWorkflowRunParent,
148
+ init_workflow_runs,
149
+ OpenAI2,
150
+ init_openai2,
151
+ CANDIDATE_SET_MULTIPLIER,
152
+ EMBEDDING_DIMENSIONS,
153
+ init_constants2,
154
+ MEMORY_KEY_MAX_LENGTH,
155
+ init_key_paths,
156
+ rerank,
157
+ init_reranker,
158
+ searchMemoryCandidates,
159
+ init_search_candidates,
160
+ getEmbeddingProvider2,
161
+ resetEmbeddingProvider2,
162
+ getMemoryStore2,
163
+ init_memory,
164
+ searchScripts2,
165
+ init_embeddings,
166
+ upsertScriptByName,
167
+ getScript,
168
+ getScriptById,
169
+ listScripts,
170
+ listScriptVersions,
171
+ deleteScript,
172
+ touchScratchScriptLastUsed,
173
+ restoreScratchScriptLastUsedIfUnchanged,
174
+ createScriptApi,
175
+ listScriptApisForScript,
176
+ getScriptApiById,
177
+ getScriptApiSecret,
178
+ updateScriptApi,
179
+ rotateScriptApiSecret,
180
+ deleteScriptApi,
181
+ recordScriptApiUsage,
182
+ init_db3,
183
+ loadSecretRegistry,
184
+ init_secret_registry,
185
+ getDefaultAuthorizationIdForProvider,
186
+ getOAuthApp,
187
+ getOAuthAppById,
188
+ createOAuthApp,
189
+ updateOAuthAppById,
190
+ listAuthorizationsForApp,
191
+ getAuthorizationById,
192
+ upsertAuthorization,
193
+ updateAuthorizationIdentity,
194
+ deleteAuthorizationById,
195
+ deleteAuthorizationsForApp,
196
+ consumeOAuthPending,
197
+ gcOAuthPending,
198
+ hasOAuthTokens,
199
+ getOAuthTokens,
200
+ deleteOAuthTokens,
201
+ acquireOAuthRefreshLock,
202
+ releaseOAuthRefreshLock,
203
+ init_oauth,
147
204
  normalizeVcsRepo,
148
205
  vcsRepoUrlMatches,
149
206
  init_vcs_repo_match,
@@ -203,13 +260,29 @@ import {
203
260
  taskProfileError,
204
261
  scheduleProfileUpdate,
205
262
  init_model_profiles,
263
+ refreshActiveSessionOnActivity2,
264
+ STEERING_MOVED_ERROR,
265
+ SteeringRequestError,
266
+ isSteeringEnabled,
267
+ getTaskSteeringFields,
268
+ getTaskSteeringFieldsForTasks,
269
+ markSteeringUndeliverable,
270
+ requestSteering,
271
+ init_steering2,
272
+ listApprovalRequestSummaries2,
273
+ getPendingApprovalVoteState2,
274
+ recordApprovalVotes2,
275
+ getPendingApprovalsForTasks2,
276
+ computeContentHash2,
206
277
  AssetKeyMovesBlockedError2,
207
278
  assertAssetKeyMovesAllowed2,
208
279
  moveSessionChains,
280
+ moveKeyFavorites,
209
281
  listPrefixRoots,
210
282
  listSharedPrefixRoots,
211
283
  init_session_moves,
212
284
  getSessionGroupKey,
285
+ sessionSummaryQuery,
213
286
  getSessionReadState,
214
287
  getSessionTree,
215
288
  triageSessionList,
@@ -224,81 +297,12 @@ import {
224
297
  init_channels,
225
298
  publishWorkerNudge,
226
299
  init_worker_nudges,
227
- getDefaultAuthorizationIdForProvider,
228
- getOAuthApp,
229
- getOAuthAppById,
230
- createOAuthApp,
231
- updateOAuthAppById,
232
- listAuthorizationsForApp,
233
- getAuthorizationById,
234
- upsertAuthorization,
235
- updateAuthorizationIdentity,
236
- deleteAuthorizationById,
237
- deleteAuthorizationsForApp,
238
- consumeOAuthPending,
239
- gcOAuthPending,
240
- getOAuthTokens,
241
- deleteOAuthTokens,
242
- acquireOAuthRefreshLock,
243
- releaseOAuthRefreshLock,
244
- init_oauth,
245
- OpenAI2,
246
- init_openai2,
247
- CANDIDATE_SET_MULTIPLIER,
248
- EMBEDDING_DIMENSIONS,
249
- init_constants2,
250
- MEMORY_KEY_MAX_LENGTH,
251
- init_key_paths,
252
- rerank,
253
- init_reranker,
254
- searchMemoryCandidates,
255
- init_search_candidates,
256
- getEmbeddingProvider2,
257
- resetEmbeddingProvider2,
258
- getMemoryStore2,
259
- init_memory,
260
- searchScripts2,
261
- init_embeddings,
262
- upsertScriptByName,
263
- getScript,
264
- getScriptById,
265
- listScripts,
266
- listScriptVersions,
267
- deleteScript,
268
- touchScratchScriptLastUsed,
269
- restoreScratchScriptLastUsedIfUnchanged,
270
- createScriptApi,
271
- listScriptApisForScript,
272
- getScriptApiById,
273
- getScriptApiSecret,
274
- updateScriptApi,
275
- rotateScriptApiSecret,
276
- deleteScriptApi,
277
- recordScriptApiUsage,
278
- init_db3,
279
- loadSecretRegistry,
280
- init_secret_registry,
281
- getWorkflowRunSummary,
282
- getWorkflowRunStepsSlimByRunId,
283
- WORKFLOW_RUN_TREE_MAX_DEPTH,
284
- WorkflowRunTreeError,
285
- getWorkflowRunTree,
286
- getWorkflowRunParent,
287
- init_workflow_runs,
288
- refreshActiveSessionOnActivity2,
289
- STEERING_MOVED_ERROR,
290
- SteeringRequestError,
291
- isSteeringEnabled,
292
- getTaskSteeringFields,
293
- getTaskSteeringFieldsForTasks,
294
- markSteeringUndeliverable,
295
- requestSteering,
296
- init_steering2,
297
300
  getPendingTaskForAgent2,
298
301
  startTask2,
299
302
  updateTaskClaudeSessionId2,
300
303
  recordTaskProviderIfUnset2,
301
304
  updateTaskTitle2,
305
+ updateTaskTags2,
302
306
  setTaskTitleIfUnset2,
303
307
  completeTask2,
304
308
  failTask2,
@@ -530,7 +534,7 @@ import {
530
534
  countScriptRunJournalSteps2,
531
535
  countScriptRunJournalAgentTaskSteps2,
532
536
  init_db4
533
- } from "./cli-h9yy18gy.js";
537
+ } from "./cli-ymct0ycy.js";
534
538
  import {
535
539
  PRIMARY_ROLE_NAMES2,
536
540
  OperatorGrantedTargetError2,
@@ -544,17 +548,17 @@ import {
544
548
  assertNotLastAdmin2,
545
549
  setUserRoles2,
546
550
  init_rbac_roles
547
- } from "./cli-n5t077me.js";
548
- import"./cli-k2rw11py.js";
551
+ } from "./cli-k7pt28ad.js";
552
+ import"./cli-7831nhaw.js";
549
553
  import {
550
554
  requestModelCatalogRefresh2,
551
555
  init_pricing_refresh
552
- } from "./cli-0vksaxvr.js";
556
+ } from "./cli-kqh27v2y.js";
553
557
  import {
554
558
  workflowEventBus2,
555
559
  init_event_bus
556
- } from "./cli-emekyyhr.js";
557
- import"./cli-zeaehgyd.js";
560
+ } from "./cli-q2d3e1k1.js";
561
+ import"./cli-q8cfh1t9.js";
558
562
  import {
559
563
  require_dist4,
560
564
  getSlackConnectionState,
@@ -582,15 +586,44 @@ import {
582
586
  slackErrorCode2,
583
587
  init_render_v2,
584
588
  getSlackApp2,
589
+ getSlackHttpReceiver2,
585
590
  startSlackApp2,
586
591
  stopSlackApp2,
587
592
  init_app3
588
- } from "./cli-mwwmka77.js";
593
+ } from "./cli-2tnbc3gw.js";
594
+ import {
595
+ AGENT_MAX_TASKS_CONFIG_KEY,
596
+ reconcileAgentMaxTasksPolicy,
597
+ resetAgentMaxTasksMirror,
598
+ upsertSwarmConfigWithPolicyMirror,
599
+ runtimeStaleThresholdMinutes,
600
+ upsertRuntimeInstance,
601
+ getRuntimeInstanceById,
602
+ touchRuntimeInstance,
603
+ listRuntimeInstancesForAgent,
604
+ setRuntimeCredentialReady,
605
+ reconcileAgentStatusFromRuntimes,
606
+ listRuntimeInstancesForPool,
607
+ init_multi_runtime,
608
+ ConfigQuestionSettingsSchema,
609
+ ConfigStateSchema,
610
+ readConfigState,
611
+ normalizeApprovalQuestions,
612
+ isConfigQuestion,
613
+ parseConfigAnswer,
614
+ skippedConfigResult,
615
+ keptConfigResult,
616
+ applyConfigAnswer,
617
+ init_approval_config_question,
618
+ dispatchApprovalNotifications2,
619
+ createApprovalFollowUpTask2,
620
+ init_approval_notifications
621
+ } from "./cli-w7dxb2fj.js";
589
622
  import {
590
623
  retryFailedRun2,
591
624
  cancelWorkflowRun2,
592
625
  init_resume
593
- } from "./cli-sdvcrq5x.js";
626
+ } from "./cli-9a2rtd77.js";
594
627
  import {
595
628
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
596
629
  SUPPORTED_PROTOCOL_VERSIONS,
@@ -605,30 +638,14 @@ import {
605
638
  referencedBundlePaths,
606
639
  skillDirs,
607
640
  init_manifest_format,
608
- TaskCreationBlockedError,
609
- init_errors2,
610
- resolveIdentity,
611
- renderIdentity,
612
- init_identity,
613
- recordUnmappedIdentity,
614
- init_unmapped_identities,
615
- MAX_TASK_ATTACHMENT_BYTES,
616
- recordTaskAttachmentUpload,
617
- scopeFromAttachment,
618
- backingProviderId,
619
- init_task_attachment_store,
620
- stripSiblingBlock,
621
- init_sibling_block,
622
- createTaskWithSiblingAwareness,
623
- init_sibling_awareness,
624
- transcribeAudioNotes,
625
- init_transcription,
626
641
  handleWebhookTrigger,
627
642
  verifyHmacSignature,
628
643
  WebhookError,
629
644
  init_triggers,
630
645
  snapshotAndUpdateWorkflow,
631
646
  init_version,
647
+ TaskCreationBlockedError,
648
+ init_errors,
632
649
  RawLlmConfigSchema,
633
650
  RawLlmOutputSchema,
634
651
  executeRawLlm,
@@ -636,6 +653,10 @@ import {
636
653
  getExecutorRegistry2,
637
654
  initWorkflows2,
638
655
  init_workflows,
656
+ stripSiblingBlock,
657
+ init_sibling_block,
658
+ createTaskWithSiblingAwareness,
659
+ init_sibling_awareness,
639
660
  dispatchScheduleTarget,
640
661
  calculateNextRun2,
641
662
  init_scheduler,
@@ -688,6 +709,20 @@ import {
688
709
  loadEnabledExtensions,
689
710
  stopExtensionRuntime,
690
711
  init_lifecycle,
712
+ resolveIdentity,
713
+ renderIdentity,
714
+ init_identity,
715
+ recordUnmappedIdentity,
716
+ init_unmapped_identities,
717
+ MAX_TASK_ATTACHMENT_BYTES,
718
+ recordTaskAttachmentUpload,
719
+ scopeFromAttachment,
720
+ backingProviderId,
721
+ init_task_attachment_store,
722
+ transcribeAudioNotes,
723
+ init_transcription,
724
+ isAgentOnDemand,
725
+ init_reachability,
691
726
  nextFallback2,
692
727
  createWorkerTaskFollowUp2,
693
728
  createResumeFollowUp2,
@@ -828,11 +863,14 @@ import {
828
863
  init_mcp_limits,
829
864
  userCtx,
830
865
  init_task_tool_ctx,
866
+ resolveRequestPrincipal,
831
867
  requestPrincipal,
832
868
  agentFirstPrincipal,
833
869
  requireAuthKind,
834
870
  rejectGuest,
835
871
  init_request_principal,
872
+ resolveTaskRequester,
873
+ init_task_requester,
836
874
  handleApps,
837
875
  init_apps,
838
876
  cancelApprovalRequest,
@@ -903,6 +941,7 @@ import {
903
941
  getTasksOutputSchema,
904
942
  getTasksHandler,
905
943
  init_get_tasks,
944
+ requiresLeadToWrite,
906
945
  reservedNamespaceError,
907
946
  privateNamespaceError,
908
947
  reservedRoomKeyError,
@@ -1016,7 +1055,7 @@ import {
1016
1055
  getEnabledCapabilities,
1017
1056
  createServer,
1018
1057
  init_server
1019
- } from "./cli-k96cecs7.js";
1058
+ } from "./cli-5ntc4we6.js";
1020
1059
  import {
1021
1060
  FilesError,
1022
1061
  normalizeFilesError,
@@ -1027,7 +1066,7 @@ import {
1027
1066
  getFileStorageProvider2,
1028
1067
  init_registry2
1029
1068
  } from "./cli-7cp6aa1q.js";
1030
- import"./cli-x6t50dmw.js";
1069
+ import"./cli-wr1h0k28.js";
1031
1070
  import {
1032
1071
  RuntimePoolError2,
1033
1072
  mintControllerToken,
@@ -1049,7 +1088,7 @@ import {
1049
1088
  resolvePoolDelivery2,
1050
1089
  createPoolAgent2,
1051
1090
  init_db2
1052
- } from "./cli-rjvsf9qa.js";
1091
+ } from "./cli-h474mvp5.js";
1053
1092
  import {
1054
1093
  duplicateGuardedQueryKey,
1055
1094
  warnIfCorsAllowsAnyOrigin,
@@ -1106,7 +1145,7 @@ import {
1106
1145
  describeRequestRoute,
1107
1146
  route,
1108
1147
  init_route_def
1109
- } from "./cli-sg27rk2t.js";
1148
+ } from "./cli-fnh4b12r.js";
1110
1149
  import {
1111
1150
  startPoolRouting,
1112
1151
  stopPoolRouting,
@@ -1119,28 +1158,28 @@ import {
1119
1158
  checkHeartbeatChecklist2,
1120
1159
  runHeartbeatSweep2,
1121
1160
  stopHeartbeat2
1122
- } from "./cli-kw44j53p.js";
1123
- import"./cli-54qr8mcd.js";
1161
+ } from "./cli-2kg31ted.js";
1162
+ import"./cli-57pvhnyt.js";
1124
1163
  import {
1125
1164
  runtimeSupervisorStatus,
1126
1165
  startRuntimeSupervisor,
1127
1166
  stopRuntimeSupervisor
1128
- } from "./cli-kmemts3w.js";
1167
+ } from "./cli-vw5x18yj.js";
1129
1168
  import {
1130
1169
  TASK_TITLE_TIMEOUT_MS,
1131
1170
  generateTaskTitle
1132
- } from "./cli-1m96dc36.js";
1171
+ } from "./cli-js8zrfyg.js";
1133
1172
  import"./cli-ns59dc6r.js";
1134
1173
  import {
1135
1174
  ACP_TARGET_IDS
1136
- } from "./cli-skmhsnqh.js";
1175
+ } from "./cli-x40a0w9j.js";
1137
1176
  import {
1138
1177
  reasoningCapability,
1139
1178
  supportedReasoningLevels
1140
- } from "./cli-93t5s4zq.js";
1179
+ } from "./cli-5gpqgs8b.js";
1141
1180
  import {
1142
1181
  MAX_RATE_LIMIT_RESET_MS
1143
- } from "./cli-tnzebztn.js";
1182
+ } from "./cli-dx439zpg.js";
1144
1183
  import {
1145
1184
  isLeadChannelMonitoringEnabled,
1146
1185
  ORG_IDENTITY_KEYS,
@@ -1150,14 +1189,20 @@ import {
1150
1189
  isUnknownModelError,
1151
1190
  checkProviderPoolKey,
1152
1191
  writeSkillsToFilesystem
1153
- } from "./cli-ztq5z4e1.js";
1192
+ } from "./cli-8axx8vnw.js";
1154
1193
  import {
1155
- inviteEmailToSharedOrg,
1156
- ensureAgentFsCredentialsForAgent
1157
- } from "./cli-bhsfbmk8.js";
1194
+ AgentFsRequestError2,
1195
+ resolveAgentFsSharedContext2,
1196
+ inviteEmailToSharedOrg2,
1197
+ ensureAgentFsCredentialsForAgent2,
1198
+ getCurrentOrgMembers2,
1199
+ roleRank2,
1200
+ agentFsRequest2,
1201
+ resolveApiUrl2
1202
+ } from "./cli-vvgaz8t6.js";
1158
1203
  import {
1159
1204
  Anthropic
1160
- } from "./cli-500c09j9.js";
1205
+ } from "./cli-t9ga4qmb.js";
1161
1206
  import {
1162
1207
  isCodexOAuthConfigKey
1163
1208
  } from "./cli-j4bwnpkm.js";
@@ -1172,7 +1217,7 @@ import {
1172
1217
  init_types2
1173
1218
  } from "./cli-2xv18ywz.js";
1174
1219
  import {
1175
- require_dist2,
1220
+ require_dist,
1176
1221
  getMcpOAuthToken,
1177
1222
  findReusableMcpOAuthClient,
1178
1223
  invalidateMcpOAuthClient,
@@ -1259,7 +1304,7 @@ import {
1259
1304
  init_typecheck,
1260
1305
  parseSkillContent,
1261
1306
  init_skill_parser
1262
- } from "./cli-z8cvws4c.js";
1307
+ } from "./cli-7fx9jyfs.js";
1263
1308
  import {
1264
1309
  signalProcessGroup,
1265
1310
  detachedProcessGroup,
@@ -1276,39 +1321,15 @@ import {
1276
1321
  forceRefreshAuthorizationOrThrow,
1277
1322
  forceRefreshTokenOrThrow,
1278
1323
  init_ensure_token
1279
- } from "./cli-s8p8hhty.js";
1324
+ } from "./cli-1tvdx9t5.js";
1325
+ import"./cli-25nstr34.js";
1280
1326
  import {
1281
1327
  automationIntegrationFixUrl,
1282
1328
  preflightAutomation,
1283
1329
  getAutomationSetupStates,
1284
1330
  listEnabledAutomationPreflightInputs,
1331
+ setupIntegrationFlags,
1285
1332
  init_automation_preflight,
1286
- AGENT_MAX_TASKS_CONFIG_KEY,
1287
- reconcileAgentMaxTasksPolicy,
1288
- resetAgentMaxTasksMirror,
1289
- upsertSwarmConfigWithPolicyMirror,
1290
- runtimeStaleThresholdMinutes,
1291
- upsertRuntimeInstance,
1292
- getRuntimeInstanceById,
1293
- touchRuntimeInstance,
1294
- listRuntimeInstancesForAgent,
1295
- setRuntimeCredentialReady,
1296
- reconcileAgentStatusFromRuntimes,
1297
- listRuntimeInstancesForPool,
1298
- init_multi_runtime,
1299
- ConfigQuestionSettingsSchema,
1300
- ConfigStateSchema,
1301
- readConfigState,
1302
- normalizeApprovalQuestions,
1303
- isConfigQuestion,
1304
- parseConfigAnswer,
1305
- skippedConfigResult,
1306
- keptConfigResult,
1307
- applyConfigAnswer,
1308
- init_approval_config_question,
1309
- dispatchApprovalNotifications,
1310
- createApprovalFollowUpTask,
1311
- init_approval_notifications,
1312
1333
  validateJsonSchema,
1313
1334
  init_json_schema_validator,
1314
1335
  workflowSaveWarnings,
@@ -1320,7 +1341,7 @@ import {
1320
1341
  definitionNodeIds,
1321
1342
  validateDefinition,
1322
1343
  init_definition2
1323
- } from "./cli-c3ng0mb4.js";
1344
+ } from "./cli-svc803vq.js";
1324
1345
  import {
1325
1346
  _fetchHolder,
1326
1347
  CLIENT_ID,
@@ -1336,15 +1357,22 @@ import {
1336
1357
  loadAllCodexOAuthSlots,
1337
1358
  getValidCodexOAuth,
1338
1359
  init_storage
1339
- } from "./cli-nx2n3z6p.js";
1360
+ } from "./cli-eg437b5p.js";
1340
1361
  import {
1341
1362
  isMultiRuntimeEnabled,
1342
1363
  init_multi_runtime2
1343
1364
  } from "./cli-mdb054w3.js";
1365
+ import {
1366
+ getApiKey,
1367
+ init_api_key
1368
+ } from "./cli-pax9q4ff.js";
1369
+ import {
1370
+ createRuntimeProvider,
1371
+ init_runtime_providers
1372
+ } from "./cli-5kcmxwxv.js";
1344
1373
  import {
1345
1374
  require_content_type
1346
- } from "./cli-yjdgea32.js";
1347
- import"./cli-s7zz734a.js";
1375
+ } from "./cli-1jx0srjt.js";
1348
1376
  import {
1349
1377
  isInvalidClientError,
1350
1378
  publicEndpointSsrfOptions,
@@ -1362,11 +1390,7 @@ import {
1362
1390
  revokeMcpToken,
1363
1391
  computeExpiresAt,
1364
1392
  init_mcp_wrapper
1365
- } from "./cli-qmqt520k.js";
1366
- import {
1367
- createRuntimeProvider,
1368
- init_runtime_providers
1369
- } from "./cli-t5ys4ebm.js";
1393
+ } from "./cli-dd37e0cm.js";
1370
1394
  import"./cli-v41kn3cd.js";
1371
1395
  import {
1372
1396
  setBedrockProviderModule,
@@ -1403,17 +1427,25 @@ import {
1403
1427
  revokeAgentTokens,
1404
1428
  fingerprintApiKey,
1405
1429
  init_users
1406
- } from "./cli-c71n3bxq.js";
1430
+ } from "./cli-pwsax0vp.js";
1407
1431
  import {
1408
1432
  AMP_ESTIMATE_MODELS,
1409
1433
  ampBillsCacheWrites,
1410
1434
  resolveAmpModel,
1411
1435
  init_amp_models
1412
- } from "./cli-tf79ryyy.js";
1436
+ } from "./cli-gddgcnav.js";
1437
+ import {
1438
+ CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1439
+ CODEX_AUTH_WATCH_NAMESPACE,
1440
+ codexAuthBenchMarkerKey,
1441
+ init_codex_auth_failure
1442
+ } from "./cli-fw2w0kva.js";
1413
1443
  import {
1414
1444
  ASSET_KEY_MAX_LENGTH,
1445
+ AssetKeyError,
1415
1446
  normalizeAssetKey,
1416
1447
  defaultAssetKey,
1448
+ isGroupKey,
1417
1449
  isResourceGroupPrefix,
1418
1450
  RESOURCE_GROUPS_READ_ONLY,
1419
1451
  parseAssetKey,
@@ -1463,6 +1495,7 @@ import {
1463
1495
  InboxItemTypeSchema,
1464
1496
  InboxItemStatusSchema,
1465
1497
  InboxItemStateSchema,
1498
+ ChecklistItemSchema,
1466
1499
  FavoriteItemTypeSchema,
1467
1500
  UserFavoriteSchema,
1468
1501
  TaskTemplateKindSchema,
@@ -1572,19 +1605,17 @@ import {
1572
1605
  KvNamespaceSchema,
1573
1606
  KvKeySchema,
1574
1607
  KvEntrySchema,
1575
- init_types4
1576
- } from "./cli-qps8je6j.js";
1608
+ init_types5
1609
+ } from "./cli-me4maa4j.js";
1577
1610
  import {
1578
- CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1579
- CODEX_AUTH_WATCH_NAMESPACE,
1580
- codexAuthBenchMarkerKey,
1581
- init_codex_auth_failure
1582
- } from "./cli-fw2w0kva.js";
1611
+ resolveGitHubHost,
1612
+ init_github_host
1613
+ } from "./cli-9ttx00s3.js";
1583
1614
  import {
1584
1615
  IDENTITY_FIELD_BUDGETS,
1585
1616
  IdentityFieldBudgetError,
1586
1617
  init_identity_field_budget
1587
- } from "./cli-am1ptset.js";
1618
+ } from "./cli-aa8s22gn.js";
1588
1619
  import {
1589
1620
  getSlackConfiguration,
1590
1621
  init_config4
@@ -1613,7 +1644,7 @@ import {
1613
1644
  splitCredentialPool,
1614
1645
  selectCredential,
1615
1646
  init_credentials2
1616
- } from "./cli-t4dv07kr.js";
1647
+ } from "./cli-pn1v1pb0.js";
1617
1648
  import {
1618
1649
  interpolate,
1619
1650
  init_template2,
@@ -1623,7 +1654,7 @@ import {
1623
1654
  resolveTemplate,
1624
1655
  init_resolver,
1625
1656
  init_session_templates
1626
- } from "./cli-0bcgyj5b.js";
1657
+ } from "./cli-812paz57.js";
1627
1658
  import {
1628
1659
  init_zod
1629
1660
  } from "./cli-zcfpsfzf.js";
@@ -1634,6 +1665,7 @@ import {
1634
1665
  string2,
1635
1666
  email,
1636
1667
  uuid,
1668
+ url,
1637
1669
  number2,
1638
1670
  boolean,
1639
1671
  _null,
@@ -1653,14 +1685,6 @@ import {
1653
1685
  exports_iso,
1654
1686
  exports_coerce
1655
1687
  } from "./cli-hg42n3hx.js";
1656
- import {
1657
- init_package,
1658
- package_default
1659
- } from "./cli-922z7gwm.js";
1660
- import {
1661
- realtimeBus,
1662
- init_bus
1663
- } from "./cli-syfdvhkc.js";
1664
1688
  import {
1665
1689
  MAX_PROFILE_FILE_LENGTH,
1666
1690
  DEFAULT_APP_URL,
@@ -1669,20 +1693,25 @@ import {
1669
1693
  getLocalDevAppOrigins,
1670
1694
  getMcpBaseUrl,
1671
1695
  getPublicMcpBaseUrl,
1696
+ getAgentFsLiveUrl,
1672
1697
  agentFsFileRoute,
1673
1698
  isCombEnabled,
1674
1699
  isAgentFsProxyEnabled,
1675
1700
  init_constants3
1676
- } from "./cli-dns0y538.js";
1701
+ } from "./cli-dqgnbnxs.js";
1677
1702
  import {
1678
1703
  parseEnvFlag,
1679
1704
  isEnvFlagEnabled,
1680
1705
  init_env_flag
1681
1706
  } from "./cli-cebvbc9t.js";
1682
1707
  import {
1683
- getApiKey,
1684
- init_api_key
1685
- } from "./cli-pax9q4ff.js";
1708
+ init_package,
1709
+ package_default
1710
+ } from "./cli-kaa4bd7x.js";
1711
+ import {
1712
+ realtimeBus,
1713
+ init_bus
1714
+ } from "./cli-syfdvhkc.js";
1686
1715
  import {
1687
1716
  isAlias,
1688
1717
  baseUrlEnvVar,
@@ -1694,7 +1723,7 @@ import {
1694
1723
  registerVolatileSecret,
1695
1724
  registerEnvSecrets,
1696
1725
  init_secret_scrubber
1697
- } from "./cli-f1kwb5fc.js";
1726
+ } from "./cli-5a6pqy45.js";
1698
1727
  import {
1699
1728
  __toESM
1700
1729
  } from "./cli-242037k3.js";
@@ -1758,7 +1787,7 @@ import {
1758
1787
 
1759
1788
  // src/be/db-retention.ts
1760
1789
  init_otel();
1761
- init_types4();
1790
+ init_types5();
1762
1791
  init_env_flag();
1763
1792
  init_secret_scrubber();
1764
1793
  init_db4();
@@ -6142,7 +6171,7 @@ init_workflows();
6142
6171
  // src/http/active-sessions.ts
6143
6172
  init_zod();
6144
6173
  init_db4();
6145
- init_types4();
6174
+ init_types5();
6146
6175
  init_multi_runtime2();
6147
6176
  init_route_def();
6148
6177
  init_session_access();
@@ -6714,9 +6743,10 @@ init_model_tier_resolution();
6714
6743
  init_model_validation2();
6715
6744
  init_multi_runtime();
6716
6745
  init_db2();
6746
+ init_reachability();
6717
6747
  init_server();
6718
6748
  init_telemetry();
6719
- init_types4();
6749
+ init_types5();
6720
6750
  init_business_use();
6721
6751
  init_constants3();
6722
6752
  init_heartbeat_expiry();
@@ -6931,8 +6961,16 @@ async function resolveListClaudeTransports(agents) {
6931
6961
  return result;
6932
6962
  }
6933
6963
  var AgentListItemSchema = AgentWithCapacityAndTasksSchema.extend({
6934
- claudeTransport: ClaudeTransportSchema.optional()
6964
+ claudeTransport: ClaudeTransportSchema.optional(),
6965
+ onDemand: boolean().optional()
6935
6966
  });
6967
+ async function withListExtras(agent, claudeTransport) {
6968
+ return {
6969
+ ...agent,
6970
+ ...claudeTransport ? { claudeTransport } : {},
6971
+ ...await isAgentOnDemand(agent) ? { onDemand: true } : {}
6972
+ };
6973
+ }
6936
6974
  function searchAgents(agents, q, limit) {
6937
6975
  const needle = q?.toLowerCase();
6938
6976
  const matching = needle ? agents.filter((agent) => [agent.name, agent.role ?? "", agent.id].some((field) => field.toLowerCase().includes(needle))) : agents;
@@ -7326,10 +7364,7 @@ async function handleAgentsRest(req, res, pathSegments, queryParams, myAgentId)
7326
7364
  resolveListClaudeTransports(agents)
7327
7365
  ]);
7328
7366
  listAgents.respond(res, 200, {
7329
- agents: agentsWithCapacity.map((agent) => {
7330
- const claudeTransport = transports.get(agent.id);
7331
- return claudeTransport ? { ...agent, claudeTransport } : agent;
7332
- })
7367
+ agents: await Promise.all(agentsWithCapacity.map((agent) => withListExtras(agent, transports.get(agent.id))))
7333
7368
  });
7334
7369
  return true;
7335
7370
  }
@@ -7900,8 +7935,7 @@ async function handleAgentsRest(req, res, pathSegments, queryParams, myAgentId)
7900
7935
  agentWithCapacity(agent),
7901
7936
  resolveListClaudeTransports([agent])
7902
7937
  ]);
7903
- const claudeTransport = transports.get(agent.id);
7904
- getAgent.respond(res, 200, claudeTransport ? { ...agentWithCap, claudeTransport } : agentWithCap);
7938
+ getAgent.respond(res, 200, await withListExtras(agentWithCap, transports.get(agent.id)));
7905
7939
  return true;
7906
7940
  }
7907
7941
  return false;
@@ -8664,7 +8698,7 @@ init_rbac_roles();
8664
8698
  init_swarm_config_guard();
8665
8699
  init_users();
8666
8700
  init_rbac();
8667
- init_types4();
8701
+ init_types5();
8668
8702
  init_request_auth_context();
8669
8703
  init_secret_scrubber();
8670
8704
  init_core();
@@ -9616,7 +9650,10 @@ var ApprovalRequestSummarySchema = ApprovalRequestSchema.omit({
9616
9650
  resolutionReason: true,
9617
9651
  notificationChannels: true,
9618
9652
  configState: true
9619
- }).extend({ questionCount: number2().int() });
9653
+ }).extend({
9654
+ questionCount: number2().int(),
9655
+ viewerCanRespond: boolean().optional().describe("Pending rows only: whether the caller may answer, by the same rule as the respond route (a listed user or role, or no users and roles listed).")
9656
+ });
9620
9657
  async function toApprovalRequestResponse(request, options = {}) {
9621
9658
  const approvers = request.approvers;
9622
9659
  const approvals = request.approvals ?? null;
@@ -9632,14 +9669,17 @@ async function toApprovalRequestResponse(request, options = {}) {
9632
9669
  notificationChannels: request.notificationChannels
9633
9670
  };
9634
9671
  }
9635
- async function withApprovalProgress(rows) {
9672
+ async function withApprovalProgress(rows, viewer) {
9636
9673
  const pendingIds = rows.filter((row) => row.status === "pending").map((row) => row.id);
9637
9674
  const state = new Map((await getPendingApprovalVoteState2(pendingIds)).map((entry) => [entry.id, entry]));
9638
9675
  return Promise.all(rows.map(async (row) => {
9639
9676
  const entry = state.get(row.id);
9640
9677
  return {
9641
9678
  ...row,
9642
- approvalProgress: entry ? await approvalProgress(entry.approvers, entry.approvals ?? []) : null
9679
+ approvalProgress: entry ? await approvalProgress(entry.approvers, entry.approvals ?? []) : null,
9680
+ ...entry && {
9681
+ viewerCanRespond: viewer !== null && isListedApprover(entry.approvers, viewer)
9682
+ }
9643
9683
  };
9644
9684
  }));
9645
9685
  }
@@ -9833,7 +9873,7 @@ var listRoute = route({
9833
9873
  path: "/api/approval-requests",
9834
9874
  pattern: ["api", "approval-requests"],
9835
9875
  summary: "List approval requests with optional filters",
9836
- description: "Returns full approval requests by default. Pass `fields=slim` for the list-view shape: `questions`, `approvers`, `responses`, `resolutionReason` and `notificationChannels` are dropped and `questionCount` is added. Fetch one request in full via `GET /api/approval-requests/{id}`.",
9876
+ description: "Returns full approval requests by default. Pass `fields=slim` for the list-view shape: `questions`, `approvers`, `responses`, `resolutionReason` and `notificationChannels` are dropped and `questionCount` is added, plus `viewerCanRespond` on pending rows. Fetch one request in full via `GET /api/approval-requests/{id}`.",
9837
9877
  tags: ["ApprovalRequests"],
9838
9878
  query: object2({
9839
9879
  status: string2().optional(),
@@ -9881,7 +9921,7 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
9881
9921
  resolutionReason: `Timed out: the answer arrived after the deadline ${existing.expiresAt}`
9882
9922
  });
9883
9923
  if (timedOut && !existing.workflowRunId) {
9884
- await createApprovalFollowUpTask(timedOut, "hitl.timeout");
9924
+ await createApprovalFollowUpTask2(timedOut, "hitl.timeout");
9885
9925
  }
9886
9926
  });
9887
9927
  jsonError(res, `Approval request expired at ${existing.expiresAt}`, 409);
@@ -10027,7 +10067,7 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
10027
10067
  workflowRunStepId: updated.workflowRunStepId ?? undefined,
10028
10068
  sourceTaskId: updated.sourceTaskId ?? undefined
10029
10069
  });
10030
- await createApprovalFollowUpTask(updated, "hitl.follow_up");
10070
+ await createApprovalFollowUpTask2(updated, "hitl.follow_up");
10031
10071
  respondRoute.respond(res, 200, {
10032
10072
  approvalRequest: await toApprovalRequestResponse(updated, { withConfigState: true })
10033
10073
  });
@@ -10107,7 +10147,7 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
10107
10147
  });
10108
10148
  const notifications = parsed.body.notifications;
10109
10149
  if (notifications?.length && request.status === "pending") {
10110
- dispatchApprovalNotifications({
10150
+ dispatchApprovalNotifications2({
10111
10151
  requestId: request.id,
10112
10152
  title: request.title,
10113
10153
  questions,
@@ -10132,8 +10172,9 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
10132
10172
  limit: parsed.query.limit || undefined
10133
10173
  };
10134
10174
  if (parsed.query.fields === "slim") {
10175
+ const viewer = await approvalResponder(req);
10135
10176
  listRoute.respond(res, 200, {
10136
- approvalRequests: await withApprovalProgress(await listApprovalRequestSummaries2(filters))
10177
+ approvalRequests: await withApprovalProgress(await listApprovalRequestSummaries2(filters), viewer.ok ? viewer.responder : null)
10137
10178
  });
10138
10179
  return true;
10139
10180
  }
@@ -10212,7 +10253,7 @@ init_db4();
10212
10253
  init_db3();
10213
10254
  init_session_shares();
10214
10255
  init_rbac();
10215
- init_types4();
10256
+ init_types5();
10216
10257
  init_request_principal();
10217
10258
  init_route_def();
10218
10259
  init_session_access();
@@ -10543,7 +10584,7 @@ async function handleAssets(req, res, pathSegments, queryParams, myAgentId) {
10543
10584
  // src/http/budgets.ts
10544
10585
  init_zod();
10545
10586
  init_db4();
10546
- init_types4();
10587
+ init_types5();
10547
10588
  init_secret_scrubber();
10548
10589
  init_route_def();
10549
10590
  init_utils2();
@@ -10704,6 +10745,596 @@ async function handleBudgets(req, res, pathSegments, queryParams, _myAgentId) {
10704
10745
  return false;
10705
10746
  }
10706
10747
 
10748
+ // src/http/checklist.ts
10749
+ init_zod();
10750
+
10751
+ // src/be/checklist.ts
10752
+ init_key();
10753
+
10754
+ // src/integrations/chat-sdk/status.ts
10755
+ init_zod();
10756
+ init_constants3();
10757
+ init_env_flag();
10758
+ init_secret_scrubber();
10759
+ init_adapters();
10760
+ init_config();
10761
+
10762
+ // src/integrations/chat-sdk/discord-api.ts
10763
+ init_secret_scrubber();
10764
+ init_adapters();
10765
+ init_logger();
10766
+ var DISCORD_TIMEOUT_MS = 5000;
10767
+ var GUILDS_CACHE_MS = 60000;
10768
+ var MAX_GUILD_NAMES = 10;
10769
+ var cache;
10770
+ async function fetchDiscordGuilds(token, now = Date.now()) {
10771
+ if (cache && cache.token === token && now - cache.at < GUILDS_CACHE_MS)
10772
+ return cache.guilds;
10773
+ let guilds;
10774
+ try {
10775
+ const response = await fetch(`${resolveAdapterApiUrl("discord")}/users/@me/guilds`, {
10776
+ headers: { authorization: `Bot ${token}` },
10777
+ signal: AbortSignal.timeout(DISCORD_TIMEOUT_MS)
10778
+ });
10779
+ if (!response.ok)
10780
+ throw new Error(`HTTP ${response.status}`);
10781
+ const payload = await response.json();
10782
+ if (!Array.isArray(payload))
10783
+ throw new Error("unexpected response shape");
10784
+ const names = payload.map((guild) => guild !== null && typeof guild === "object" && typeof guild.name === "string" ? guild.name : undefined).filter((name) => name !== undefined);
10785
+ guilds = { count: payload.length, names: names.slice(0, MAX_GUILD_NAMES) };
10786
+ } catch (error) {
10787
+ console.warn(scrubSecrets(`[chat-sdk] discord: could not list the bot's servers: ${errorMessage(error).replaceAll(token, "[REDACTED]")}`));
10788
+ }
10789
+ cache = { token, at: now, guilds };
10790
+ return guilds;
10791
+ }
10792
+
10793
+ // src/integrations/chat-sdk/status.ts
10794
+ init_runtime();
10795
+ init_schema();
10796
+ init_telegram_api();
10797
+ var ChatSdkStatusSchema = object2({
10798
+ enabled: boolean(),
10799
+ slackClash: boolean(),
10800
+ error: string2().optional(),
10801
+ adapters: array2(object2({
10802
+ name: _enum2(CHAT_SDK_ADAPTER_NAMES),
10803
+ configured: boolean(),
10804
+ enabled: boolean(),
10805
+ health: _enum2(["ok", "error", "disabled", "incomplete"]),
10806
+ connected: boolean(),
10807
+ error: string2().optional(),
10808
+ webhookUrl: string2(),
10809
+ mode: string2().optional(),
10810
+ gateway: object2({
10811
+ state: _enum2(["running", "backoff", "stopped"]),
10812
+ since: string2(),
10813
+ restarts: number2()
10814
+ }).optional(),
10815
+ guilds: object2({ count: number2(), names: array2(string2()) }).optional()
10816
+ }))
10817
+ });
10818
+ var DEFAULT_MODES = {
10819
+ telegram: "webhook",
10820
+ slack: "webhook"
10821
+ };
10822
+ var NOT_RUNNING = "The adapter is starting, or the last configuration save is still applying. Refresh in a few seconds.";
10823
+ var SLACK_CLASH_CAUSE = "the Slack adapter conflicts with the built-in Slack integration (set SLACK_DISABLE=true)";
10824
+ var MAX_STATUS_ERROR_CHARS = 300;
10825
+ function statusError(message) {
10826
+ return scrubSecrets(message).slice(0, MAX_STATUS_ERROR_CHARS);
10827
+ }
10828
+ function readRawAdapters() {
10829
+ const raw = process.env.CHAT_SDK_ADAPTERS?.trim();
10830
+ if (!raw)
10831
+ return {};
10832
+ try {
10833
+ const parsed = JSON.parse(raw);
10834
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
10835
+ return {};
10836
+ const out = {};
10837
+ for (const name of CHAT_SDK_ADAPTER_NAMES) {
10838
+ const value = parsed[name];
10839
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
10840
+ out[name] = value;
10841
+ }
10842
+ }
10843
+ return out;
10844
+ } catch {
10845
+ return {};
10846
+ }
10847
+ }
10848
+ function healthyChatSdkAdapters() {
10849
+ const raw = readRawAdapters();
10850
+ const health = getChatSdkHealth();
10851
+ return CHAT_SDK_ADAPTER_NAMES.filter((name) => raw[name] !== undefined && isAdapterEntryEnabled(raw[name]) && health[name]?.status === "ok");
10852
+ }
10853
+ function chatSdkWebhookUrl(name) {
10854
+ return `${getPublicMcpBaseUrl()}/api/integrations/chat/${name}/webhook`;
10855
+ }
10856
+ async function discordGuildsFor(config, health) {
10857
+ if (health?.status !== "ok" || health.gateway?.state !== "running")
10858
+ return;
10859
+ const raw = config.adapters.discord?.botToken;
10860
+ const token = typeof raw === "function" ? await raw() : raw;
10861
+ if (typeof token !== "string" || token.length === 0)
10862
+ return;
10863
+ return fetchDiscordGuilds(token);
10864
+ }
10865
+ async function getChatSdkStatus() {
10866
+ const config = await getChatSdkConfig();
10867
+ const raw = readRawAdapters();
10868
+ const runtimeHealth = getChatSdkHealth();
10869
+ const slackClash = raw.slack !== undefined && !isEnvFlagEnabled("SLACK_DISABLE", false);
10870
+ const blockedCause = config.error ?? (config.enabled && slackClash ? SLACK_CLASH_CAUSE : undefined);
10871
+ const discordGuilds = await discordGuildsFor(config, runtimeHealth.discord);
10872
+ const adapters = CHAT_SDK_ADAPTER_NAMES.map((name) => {
10873
+ const configured = raw[name] !== undefined;
10874
+ const enabled = isAdapterEntryEnabled(raw[name]);
10875
+ const current = runtimeHealth[name];
10876
+ const incomplete = config.incomplete?.[name];
10877
+ const rawMode = raw[name]?.mode;
10878
+ const mode = typeof rawMode === "string" ? rawMode : configured ? DEFAULT_MODES[name] : undefined;
10879
+ let health = "disabled";
10880
+ let error;
10881
+ if (current) {
10882
+ health = current.status;
10883
+ const showWarning = current.status === "error" || current.gateway?.state === "backoff";
10884
+ error = current.error ?? (showWarning ? current.lastWarning : undefined);
10885
+ } else if (incomplete) {
10886
+ health = "incomplete";
10887
+ error = incomplete;
10888
+ } else if (configured && !enabled) {
10889
+ error = "Turned off on the card. The configuration is kept.";
10890
+ } else if (config.enabled && configured) {
10891
+ error = blockedCause ? `Not started: ${blockedCause}` : NOT_RUNNING;
10892
+ }
10893
+ return {
10894
+ name,
10895
+ configured,
10896
+ enabled,
10897
+ health,
10898
+ connected: configured && enabled && health === "ok",
10899
+ ...error ? { error: statusError(error) } : {},
10900
+ webhookUrl: chatSdkWebhookUrl(name),
10901
+ ...mode ? { mode } : {},
10902
+ ...current?.gateway ? { gateway: current.gateway } : {},
10903
+ ...name === "discord" && discordGuilds ? { guilds: discordGuilds } : {}
10904
+ };
10905
+ });
10906
+ return {
10907
+ enabled: config.enabled,
10908
+ slackClash,
10909
+ ...config.error ? { error: statusError(config.error) } : {},
10910
+ adapters
10911
+ };
10912
+ }
10913
+
10914
+ class ChatSdkActionError extends Error {
10915
+ status;
10916
+ constructor(message, status) {
10917
+ super(message);
10918
+ this.status = status;
10919
+ this.name = "ChatSdkActionError";
10920
+ }
10921
+ }
10922
+ async function callBotApi(baseUrl, token, method, body) {
10923
+ try {
10924
+ return await callTelegramBotApi(baseUrl, token, method, body);
10925
+ } catch (error) {
10926
+ if (error instanceof TelegramBotApiError)
10927
+ throw new ChatSdkActionError(error.message, 502);
10928
+ throw error;
10929
+ }
10930
+ }
10931
+ async function registerTelegramWebhook() {
10932
+ const config = await getChatSdkConfig();
10933
+ if (!config.enabled) {
10934
+ throw new ChatSdkActionError("The Chat SDK channel is disabled (CHAT_SDK_ENABLED is not true). Enable it and restart the API first", 400);
10935
+ }
10936
+ if (config.error)
10937
+ throw new ChatSdkActionError(statusError(config.error), 400);
10938
+ const telegram = config.adapters.telegram;
10939
+ if (!telegram) {
10940
+ throw new ChatSdkActionError("Telegram is not configured in CHAT_SDK_ADAPTERS", 400);
10941
+ }
10942
+ if (telegram.mode !== "webhook") {
10943
+ throw new ChatSdkActionError("Telegram runs in polling mode; a registered webhook would stop polling", 400);
10944
+ }
10945
+ const secretToken = telegram.secretToken;
10946
+ if (typeof secretToken !== "string" || secretToken.length === 0) {
10947
+ throw new ChatSdkActionError("Telegram webhook mode needs a secretToken", 400);
10948
+ }
10949
+ const rawToken = telegram.botToken;
10950
+ const token = typeof rawToken === "function" ? await rawToken() : rawToken;
10951
+ if (typeof token !== "string" || token.length === 0) {
10952
+ throw new ChatSdkActionError("Telegram botToken is empty", 400);
10953
+ }
10954
+ const baseUrl = resolveAdapterApiUrl("telegram");
10955
+ const webhookUrl = chatSdkWebhookUrl("telegram");
10956
+ await callBotApi(baseUrl, token, "setWebhook", { url: webhookUrl, secret_token: secretToken });
10957
+ const info = await callBotApi(baseUrl, token, "getWebhookInfo", {});
10958
+ if (info === null || typeof info !== "object" || typeof info.url !== "string") {
10959
+ throw new ChatSdkActionError("Telegram getWebhookInfo returned an unexpected result", 502);
10960
+ }
10961
+ return { webhookUrl, webhookInfo: info };
10962
+ }
10963
+
10964
+ // src/be/checklist.ts
10965
+ init_rbac();
10966
+ init_secret_scrubber();
10967
+ init_automation_preflight();
10968
+ init_db4();
10969
+ init_session_tree();
10970
+ init_oauth();
10971
+ init_rbac_roles();
10972
+
10973
+ class ChecklistError extends Error {
10974
+ status;
10975
+ constructor(message, status) {
10976
+ super(message);
10977
+ this.status = status;
10978
+ }
10979
+ }
10980
+ var UNSTORED_DEFAULT_AT = "1970-01-01T00:00:00.000Z";
10981
+ async function userGrantCanEditSwarm(userId) {
10982
+ if (!isRbacEnabled())
10983
+ return null;
10984
+ const grant = await getUserGrant2(userId);
10985
+ return grant.grantsAll || grant.verbs.has("config.write.any");
10986
+ }
10987
+ function defaultRows(userId) {
10988
+ const row = (id, scope, kind, label, href, sortOrder) => ({
10989
+ id,
10990
+ scope,
10991
+ userId: scope === "user" ? userId : null,
10992
+ kind,
10993
+ label,
10994
+ href,
10995
+ meta: null,
10996
+ sortOrder,
10997
+ status: "open",
10998
+ statusChangedAt: null,
10999
+ statusChangedBy: null,
11000
+ statusChangedByName: null,
11001
+ statusReason: null,
11002
+ nudgedAt: null,
11003
+ nudgedTaskId: null,
11004
+ createdAt: UNSTORED_DEFAULT_AT,
11005
+ lastUpdatedAt: UNSTORED_DEFAULT_AT
11006
+ });
11007
+ return [
11008
+ row("swarm:channel", "swarm", "channel", "Connect a chat channel", "/integrations/channels", 0),
11009
+ row("swarm:tool", "swarm", "tool", "Connect work tools", "/integrations/tools", 1),
11010
+ ...userId ? [
11011
+ row(`user:${userId}:use_case`, "user", "use_case", "Plan your first use case", "/sessions", 2)
11012
+ ] : []
11013
+ ];
11014
+ }
11015
+ async function seedChecklist(userId) {
11016
+ const db = getDbClient2();
11017
+ await db.run(`INSERT OR IGNORE INTO checklist_items (id, scope, kind, label, href, sortOrder)
11018
+ VALUES ('swarm:channel', 'swarm', 'channel', 'Connect a chat channel', '/integrations/channels', 0),
11019
+ ('swarm:tool', 'swarm', 'tool', 'Connect work tools', '/integrations/tools', 1)`);
11020
+ if (userId) {
11021
+ await db.run(`INSERT OR IGNORE INTO checklist_items
11022
+ (id, scope, userId, kind, label, href, sortOrder, created_by, updated_by)
11023
+ VALUES (?, 'user', ?, 'use_case', 'Plan your first use case', '/sessions', 2, ?, ?)`, [`user:${userId}:use_case`, userId, userId, userId]);
11024
+ }
11025
+ }
11026
+ async function checklistRows(userId) {
11027
+ const rows = await getDbClient2().query(`SELECT c.*, CASE WHEN c.statusChangedBy LIKE 'lead:%' THEN 'Lead' ELSE u.name END AS statusChangedByName
11028
+ FROM checklist_items c LEFT JOIN users u ON u.id = c.statusChangedBy
11029
+ WHERE c.scope = 'swarm' OR (c.scope = 'user' AND c.userId = ?)`, [userId]);
11030
+ const stored = new Set(rows.map((row) => row.id));
11031
+ const all = [...rows, ...defaultRows(userId).filter((row) => !stored.has(row.id))];
11032
+ const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11033
+ return all.sort((a, b) => a.sortOrder - b.sortOrder || cmp(a.createdAt, b.createdAt) || cmp(a.id, b.id));
11034
+ }
11035
+ function parseMeta(raw) {
11036
+ if (!raw)
11037
+ return null;
11038
+ try {
11039
+ const value = JSON.parse(raw);
11040
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
11041
+ } catch {
11042
+ return null;
11043
+ }
11044
+ }
11045
+ async function getUseCaseSignal(userId) {
11046
+ if (!userId)
11047
+ return false;
11048
+ const keys = await getDbClient2().query(`SELECT "key", MAX(createdAt) AS newest FROM (
11049
+ SELECT "key", createdAt FROM scheduled_tasks WHERE created_by = ?
11050
+ UNION ALL SELECT "key", createdAt FROM pages WHERE created_by = ?
11051
+ UNION ALL SELECT "key", createdAt FROM workflows WHERE created_by = ?
11052
+ ) GROUP BY "key" ORDER BY newest DESC, "key" LIMIT 500`, [userId, userId, userId]);
11053
+ const groups = keys.map(({ key }) => key).filter(isGroupKey).slice(0, 100);
11054
+ if (groups.length === 0)
11055
+ return false;
11056
+ const query = sessionSummaryQuery({ keyPrefixes: groups, viewer: { userId, scope: "all" } });
11057
+ const read = await getDbClient2().get(`SELECT 1 AS found FROM (${query.sql}) WHERE readState = 'read' LIMIT 1`, query.params);
11058
+ return read !== null;
11059
+ }
11060
+ function lazySignals(userId) {
11061
+ const once = (fn) => {
11062
+ let value;
11063
+ return () => {
11064
+ value ??= fn();
11065
+ return value;
11066
+ };
11067
+ };
11068
+ const flags = once(async () => setupIntegrationFlags(await getAutomationSetupStates()));
11069
+ const adapters = once(async () => {
11070
+ const names = new Set(healthyChatSdkAdapters());
11071
+ if ((await flags()).slack)
11072
+ names.add("slack");
11073
+ return names;
11074
+ });
11075
+ const tool = once(async () => {
11076
+ const f = await flags();
11077
+ if (f.github || f.gitlab || f.bitbucket || f.linear || f.jira)
11078
+ return true;
11079
+ return await hasOAuthTokens("google") || await hasOAuthTokens("microsoft");
11080
+ });
11081
+ const plannedUseCase = once(() => getUseCaseSignal(userId));
11082
+ return async (row, meta) => {
11083
+ if (row.kind === "custom")
11084
+ return null;
11085
+ if (row.kind === "channel") {
11086
+ const names = await adapters();
11087
+ return typeof meta?.adapter === "string" ? names.has(meta.adapter) : names.size > 0;
11088
+ }
11089
+ return row.kind === "tool" ? tool() : plannedUseCase();
11090
+ };
11091
+ }
11092
+ function toItem(row, meta, signal, userId, canEditSwarm) {
11093
+ return {
11094
+ id: row.id,
11095
+ scope: row.scope,
11096
+ userId: row.userId,
11097
+ kind: row.kind,
11098
+ label: row.label,
11099
+ href: row.href,
11100
+ meta,
11101
+ sortOrder: row.sortOrder,
11102
+ status: row.status,
11103
+ statusChangedAt: row.statusChangedAt,
11104
+ statusChangedBy: row.statusChangedBy,
11105
+ statusChangedByName: row.statusChangedByName,
11106
+ statusReason: row.statusReason,
11107
+ nudgedAt: row.nudgedAt,
11108
+ nudgedTaskId: row.nudgedTaskId,
11109
+ signal,
11110
+ done: row.status === "done" || signal === true,
11111
+ editable: row.scope === "swarm" ? canEditSwarm : row.userId === userId,
11112
+ createdAt: row.createdAt,
11113
+ lastUpdatedAt: row.lastUpdatedAt
11114
+ };
11115
+ }
11116
+ async function listChecklist(userId, canEditSwarm = false) {
11117
+ const signalOf = lazySignals(userId);
11118
+ return Promise.all((await checklistRows(userId)).map(async (row) => {
11119
+ const meta = parseMeta(row.meta);
11120
+ const signal = row.status === "done" ? null : await signalOf(row, meta);
11121
+ return toItem(row, meta, signal, userId, canEditSwarm);
11122
+ }));
11123
+ }
11124
+ async function mutateChecklist(actor, action) {
11125
+ const id = await getDbClient2().transaction(async (tx) => {
11126
+ await seedChecklist(actor.userId);
11127
+ const id = action.action === "add" ? crypto.randomUUID() : action.id;
11128
+ const row = action.action === "add" ? action : await tx.get("SELECT * FROM checklist_items WHERE id = ?", [id]);
11129
+ if (!row)
11130
+ throw new ChecklistError("Checklist item not found", 404);
11131
+ if (row.scope === "swarm" && !actor.canEditSwarm) {
11132
+ throw new ChecklistError("Swarm checklist items require config.write.any", 403);
11133
+ }
11134
+ if (row.scope === "user") {
11135
+ if (!actor.userId)
11136
+ throw new ChecklistError("A user is required for user checklist items", action.action === "add" ? 400 : 403);
11137
+ if (action.action !== "add" && "userId" in row && row.userId !== actor.userId) {
11138
+ throw new ChecklistError("This checklist item belongs to another user", 403);
11139
+ }
11140
+ }
11141
+ const now = new Date().toISOString();
11142
+ if (action.action === "add") {
11143
+ const userId = action.scope === "user" ? actor.userId : null;
11144
+ const adapter = action.kind === "channel" ? action.meta?.adapter : undefined;
11145
+ if (typeof adapter === "string") {
11146
+ const open = await tx.get(`SELECT id FROM checklist_items
11147
+ WHERE kind = 'channel' AND status = 'open' AND scope = ? AND userId IS ?
11148
+ AND CASE WHEN json_valid(meta) THEN json_extract(meta, '$.adapter') END = ?`, [action.scope, userId, adapter]);
11149
+ if (open)
11150
+ throw new ChecklistError(`An open item already connects ${adapter}`, 409);
11151
+ }
11152
+ const max = await tx.get("SELECT COALESCE(MAX(sortOrder), -1) + 1 AS sortOrder FROM checklist_items WHERE scope = ? AND userId IS ?", [action.scope, userId]);
11153
+ await tx.run(`INSERT INTO checklist_items
11154
+ (id, scope, userId, kind, label, href, meta, sortOrder, createdAt, lastUpdatedAt, created_by, updated_by)
11155
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
11156
+ id,
11157
+ action.scope,
11158
+ userId,
11159
+ action.kind,
11160
+ scrubSecrets(action.label),
11161
+ action.href ? scrubSecrets(action.href) : null,
11162
+ action.meta ? scrubSecrets(JSON.stringify(action.meta)) : null,
11163
+ max.sortOrder,
11164
+ now,
11165
+ now,
11166
+ actor.id,
11167
+ actor.id
11168
+ ]);
11169
+ } else if (action.action === "reorder") {
11170
+ await tx.run("UPDATE checklist_items SET sortOrder = ?, lastUpdatedAt = ?, updated_by = ? WHERE id = ?", [action.sortOrder, now, actor.id, id]);
11171
+ } else {
11172
+ const status = action.action === "remove" ? "removed" : action.action === "done" ? "done" : "open";
11173
+ await tx.run(`UPDATE checklist_items SET status = ?, statusChangedAt = ?, statusChangedBy = ?,
11174
+ statusReason = ?, lastUpdatedAt = ?, updated_by = ? WHERE id = ?`, [
11175
+ status,
11176
+ now,
11177
+ actor.id,
11178
+ action.action === "restore" || !action.reason ? null : scrubSecrets(action.reason),
11179
+ now,
11180
+ actor.id,
11181
+ id
11182
+ ]);
11183
+ }
11184
+ return id;
11185
+ });
11186
+ const items = await listChecklist(actor.userId, actor.canEditSwarm);
11187
+ return items.find((item) => item.id === id);
11188
+ }
11189
+ async function firstOpenItem(userId, canEditSwarm) {
11190
+ const signalOf = lazySignals(userId);
11191
+ for (const row of await checklistRows(userId)) {
11192
+ const editable = row.scope === "swarm" ? canEditSwarm : row.userId === userId;
11193
+ if (!editable || row.status !== "open" || row.nudgedAt !== null)
11194
+ continue;
11195
+ const meta = parseMeta(row.meta);
11196
+ const signal = await signalOf(row, meta);
11197
+ if (signal === false)
11198
+ return toItem(row, meta, signal, userId, canEditSwarm);
11199
+ }
11200
+ return null;
11201
+ }
11202
+ async function markNudged(itemId, taskId, userId) {
11203
+ await seedChecklist(userId);
11204
+ const now = new Date().toISOString();
11205
+ await getDbClient2().run("UPDATE checklist_items SET nudgedAt = ?, nudgedTaskId = ?, lastUpdatedAt = ? WHERE id = ?", [now, taskId, now, itemId]);
11206
+ }
11207
+
11208
+ // src/http/checklist.ts
11209
+ init_rbac();
11210
+ init_types5();
11211
+ init_favorite_owner();
11212
+ init_request_principal();
11213
+ init_route_def();
11214
+ init_utils2();
11215
+ var getChecklist = route({
11216
+ method: "get",
11217
+ path: "/api/checklist",
11218
+ pattern: ["api", "checklist"],
11219
+ summary: "Read the post-onboarding checklist",
11220
+ tags: ["Checklist"],
11221
+ responses: {
11222
+ 200: {
11223
+ description: "Checklist items and swarm edit permission",
11224
+ schema: object2({ items: array2(ChecklistItemSchema), canEditSwarm: boolean() })
11225
+ }
11226
+ }
11227
+ });
11228
+ var addChecklistItem = route({
11229
+ method: "post",
11230
+ path: "/api/checklist/items",
11231
+ pattern: ["api", "checklist", "items"],
11232
+ summary: "Add a checklist item",
11233
+ tags: ["Checklist"],
11234
+ rbac: { permission: "checklist.write.own" },
11235
+ body: object2({
11236
+ kind: _enum2(["channel", "tool", "use_case", "custom"]),
11237
+ label: string2().min(1).max(200),
11238
+ href: string2().max(500).regex(/^\/(?!\/)/, "href must be an in-app path starting with /").optional(),
11239
+ scope: _enum2(["swarm", "user"]),
11240
+ meta: looseObject({ adapter: string2().min(1).max(64).optional() }).refine((meta) => JSON.stringify(meta).length <= 1024, {
11241
+ message: "meta must be at most 1024 characters as JSON"
11242
+ }).optional()
11243
+ }),
11244
+ responses: {
11245
+ 201: { description: "Added checklist item", schema: object2({ item: ChecklistItemSchema }) },
11246
+ 400: { description: "A user is required for user items" },
11247
+ 403: { description: "The caller cannot edit swarm items" },
11248
+ 409: { description: "An open channel item for the same adapter already exists" }
11249
+ }
11250
+ });
11251
+ var patchChecklistItem = route({
11252
+ method: "patch",
11253
+ path: "/api/checklist/items/{id}",
11254
+ pattern: ["api", "checklist", "items", null],
11255
+ summary: "Update a checklist item",
11256
+ tags: ["Checklist"],
11257
+ rbac: { permission: "checklist.write.own" },
11258
+ params: object2({ id: string2() }),
11259
+ body: object2({
11260
+ action: _enum2(["remove", "restore", "done", "reorder"]),
11261
+ reason: string2().max(500).optional(),
11262
+ sortOrder: number2().int().optional()
11263
+ }).refine((body) => body.action !== "reorder" || body.sortOrder !== undefined, {
11264
+ message: "Reorder requires sortOrder",
11265
+ path: ["sortOrder"]
11266
+ }),
11267
+ responses: {
11268
+ 200: { description: "Updated checklist item", schema: object2({ item: ChecklistItemSchema }) },
11269
+ 400: { description: "Invalid update" },
11270
+ 403: { description: "The caller cannot edit this item" },
11271
+ 404: { description: "Checklist item not found" }
11272
+ }
11273
+ });
11274
+ function decodePathId(raw) {
11275
+ try {
11276
+ return decodeURIComponent(raw);
11277
+ } catch {
11278
+ return raw;
11279
+ }
11280
+ }
11281
+ async function handleChecklist(req, res, pathSegments, queryParams, myAgentId) {
11282
+ if (!getChecklist.match(req.method, pathSegments) && !addChecklistItem.match(req.method, pathSegments) && !patchChecklistItem.match(req.method, pathSegments))
11283
+ return false;
11284
+ const owner = await resolveHttpFavoriteOwner(req, myAgentId);
11285
+ if (!owner) {
11286
+ jsonError(res, "An authenticated principal is required", 401);
11287
+ return true;
11288
+ }
11289
+ const principal = await resolveRequestPrincipal(req, myAgentId, { precedence: "agent-first" });
11290
+ if (!principal) {
11291
+ jsonError(res, "An authenticated principal is required", 401);
11292
+ return true;
11293
+ }
11294
+ if (principal.kind === "agent" && !getChecklist.match(req.method, pathSegments) && !can({ principal, verb: "checklist.write.agent", resource: { kind: "none" }, source: "http" }).allow) {
11295
+ jsonError(res, "Only the Lead agent can change the checklist", 403);
11296
+ return true;
11297
+ }
11298
+ const grantAllows = principal.kind !== "agent" && owner.userId ? await userGrantCanEditSwarm(owner.userId) : null;
11299
+ const canEditSwarm = grantAllows ?? (principal.kind === "operator" || can({ principal, verb: "config.write.any", resource: { kind: "none" }, source: "http" }).allow);
11300
+ const actor = {
11301
+ id: principal.kind === "agent" ? `lead:${principal.agentId}` : owner.actorId,
11302
+ userId: owner.userId,
11303
+ canEditSwarm
11304
+ };
11305
+ try {
11306
+ if (getChecklist.match(req.method, pathSegments)) {
11307
+ const parsed = await getChecklist.parse(req, res, pathSegments, queryParams);
11308
+ if (!parsed)
11309
+ return true;
11310
+ getChecklist.respond(res, 200, {
11311
+ items: await listChecklist(owner.userId, canEditSwarm),
11312
+ canEditSwarm
11313
+ });
11314
+ } else if (addChecklistItem.match(req.method, pathSegments)) {
11315
+ const parsed = await addChecklistItem.parse(req, res, pathSegments, queryParams);
11316
+ if (!parsed)
11317
+ return true;
11318
+ addChecklistItem.respond(res, 201, {
11319
+ item: await mutateChecklist(actor, { action: "add", ...parsed.body })
11320
+ });
11321
+ } else {
11322
+ const parsed = await patchChecklistItem.parse(req, res, pathSegments, queryParams);
11323
+ if (!parsed)
11324
+ return true;
11325
+ const { action, sortOrder, reason } = parsed.body;
11326
+ const id = decodePathId(parsed.params.id);
11327
+ const item = await mutateChecklist(actor, action === "reorder" ? { action, id, sortOrder } : { action, id, reason });
11328
+ patchChecklistItem.respond(res, 200, { item });
11329
+ }
11330
+ } catch (error) {
11331
+ if (!(error instanceof ChecklistError))
11332
+ throw error;
11333
+ jsonError(res, error.message, error.status);
11334
+ }
11335
+ return true;
11336
+ }
11337
+
10707
11338
  // src/http/codex-oauth-accounts.ts
10708
11339
  init_zod();
10709
11340
  init_crypto();
@@ -10895,7 +11526,7 @@ async function upsertCodexDeviceFlow(input) {
10895
11526
 
10896
11527
  // src/be/onboarding.ts
10897
11528
  init_telemetry();
10898
- init_types4();
11529
+ init_types5();
10899
11530
  init_request_auth_context();
10900
11531
  init_zod_openapi();
10901
11532
  init_db4();
@@ -12406,7 +13037,7 @@ function errorMessage2(error) {
12406
13037
 
12407
13038
  // src/http/comb.ts
12408
13039
  init_rbac();
12409
- init_errors2();
13040
+ init_errors();
12410
13041
  init_secret_scrubber();
12411
13042
  init_request_principal();
12412
13043
  init_route_def();
@@ -12507,7 +13138,7 @@ async function handleComb(req, res, pathSegments, queryParams, myAgentId) {
12507
13138
  // src/http/context.ts
12508
13139
  init_zod();
12509
13140
  init_db4();
12510
- init_types4();
13141
+ init_types5();
12511
13142
  init_route_def();
12512
13143
  init_utils2();
12513
13144
  var PostContextResponseSchema = object2({
@@ -12624,7 +13255,7 @@ init_db_query();
12624
13255
  // src/http/events.ts
12625
13256
  init_zod();
12626
13257
  init_events();
12627
- init_types4();
13258
+ init_types5();
12628
13259
  init_route_def();
12629
13260
  init_session_access();
12630
13261
  init_utils2();
@@ -13176,7 +13807,7 @@ declare module "swarm-extension" {
13176
13807
 
13177
13808
  export type SteerMode = "steer" | "queue";
13178
13809
 
13179
- export type SteeringSource = "chat" | "script" | "slack" | "mcp" | "api" | "ui";
13810
+ export type SteeringSource = "chat" | "script" | "slack" | "mcp" | "api" | "ui" | "app-page";
13180
13811
 
13181
13812
  export type RequestInfo = {
13182
13813
  sessionId: string | undefined;
@@ -13770,7 +14401,7 @@ declare module "swarm-extension" {
13770
14401
  // src/be/extensions/validate.ts
13771
14402
  init_manifest_format();
13772
14403
  init_import_allowlist();
13773
- init_types4();
14404
+ init_types5();
13774
14405
  init_typecheck();
13775
14406
  async function validateBundle(input) {
13776
14407
  const parsedManifest = ExtensionManifestSchema.safeParse(input.manifest);
@@ -15735,6 +16366,119 @@ export default extension;
15735
16366
  },
15736
16367
  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'
15737
16368
  },
16369
+ "sql-admin-only": {
16370
+ manifestFile: "manifest.json",
16371
+ manifest: {
16372
+ $schema: "../manifest.schema.json",
16373
+ name: "sql-admin-only",
16374
+ description: "Blocks db-query tool calls on tasks created by a non-admin user",
16375
+ version: "1.0.0",
16376
+ runtime: "api",
16377
+ assets: {
16378
+ hooks: "hooks.ts"
16379
+ }
16380
+ },
16381
+ files: {
16382
+ "hooks.ts": `import { block, type SwarmExtension } from "swarm-extension";
16383
+ import { z } from "zod";
16384
+
16385
+ export const config = z.object({});
16386
+
16387
+ /** MCP tools that run raw SQL. db-query is the only one today. */
16388
+ const SQL_TOOLS = new Set(["db-query"]);
16389
+
16390
+ const manifest = {
16391
+ name: "sql-admin-only",
16392
+ description: "Blocks db-query tool calls on tasks created by a non-admin user",
16393
+ version: "1.0.0",
16394
+ runtime: "api",
16395
+ assets: { hooks: "hooks.ts" },
16396
+ config,
16397
+ } as const;
16398
+
16399
+ /**
16400
+ * The task's creator and that user's \`users.role\`, the role the swarm shows for a
16401
+ * requester (for example "Alice (admin)"). RBAC roles do not work here: every user is
16402
+ * created with the RBAC \`admin\` role.
16403
+ */
16404
+ export const CREATOR_SQL = \`SELECT t.requestedByUserId, u.role
16405
+ FROM agent_tasks t
16406
+ LEFT JOIN users u ON u.id = t.requestedByUserId
16407
+ WHERE t.id = ?\`;
16408
+
16409
+ type Envelope = { success?: boolean; data?: { rows?: unknown[] }; rows?: unknown[] } | null;
16410
+
16411
+ const cell = (row: unknown, i: number, key: string): unknown =>
16412
+ Array.isArray(row) ? row[i] : (row as Record<string, unknown> | null)?.[key];
16413
+
16414
+ /**
16415
+ * The dispatcher fails a pre hook OPEN when it runs past
16416
+ * EXTENSION_HANDLER_TIMEOUT_MS (default 5s). Give the lookup a shorter budget so
16417
+ * a slow lookup ends in our own block, not in a silent allow.
16418
+ */
16419
+ const lookupBudgetMs = (): number => {
16420
+ const raw = Number(process.env.EXTENSION_HANDLER_TIMEOUT_MS);
16421
+ const handlerMs = Number.isFinite(raw) && raw > 0 ? raw : 5_000;
16422
+ return Math.floor(handlerMs * 0.6);
16423
+ };
16424
+
16425
+ const withDeadline = async <T>(work: Promise<T>, ms: number): Promise<T> => {
16426
+ let timer: ReturnType<typeof setTimeout> | undefined;
16427
+ try {
16428
+ return await Promise.race([
16429
+ work,
16430
+ new Promise<never>((_, reject) => {
16431
+ timer = setTimeout(() => reject(new Error(\`lookup timed out after \${ms}ms\`)), ms);
16432
+ }),
16433
+ ]);
16434
+ } finally {
16435
+ if (timer) clearTimeout(timer);
16436
+ }
16437
+ };
16438
+
16439
+ const extension: SwarmExtension<typeof manifest> = (api) => {
16440
+ api.on("pre.tool.call", async (event, ctx) => {
16441
+ const tool = event.tool;
16442
+ if (!SQL_TOOLS.has(tool)) return;
16443
+
16444
+ // No task context means no task creator: allow.
16445
+ const taskId = event.requestInfo?.sourceTaskId;
16446
+ if (!taskId) return;
16447
+
16448
+ // Creator lookup. Any failure blocks this SQL call only (fail closed).
16449
+ let creator: string;
16450
+ let role: string;
16451
+ try {
16452
+ const q = (await withDeadline(
16453
+ ctx.swarm.db_query({ sql: CREATOR_SQL, params: [taskId] }),
16454
+ lookupBudgetMs(),
16455
+ )) as Envelope;
16456
+ if (q?.success === false) throw new Error("db-query lookup returned success=false");
16457
+ const row = (q?.data?.rows ?? q?.rows ?? [])[0];
16458
+ if (!row) throw new Error(\`task \${taskId} not found\`);
16459
+ creator = String(cell(row, 0, "requestedByUserId") ?? "");
16460
+ role = String(cell(row, 1, "role") ?? "");
16461
+ } catch (err) {
16462
+ const message = err instanceof Error ? err.message : String(err);
16463
+ const reason = \`\${tool} is restricted to admin task creators, and the creator of task \${taskId} could not be verified (\${message}).\`;
16464
+ ctx.log.warn(reason, { tool, taskId });
16465
+ return block(reason);
16466
+ }
16467
+
16468
+ if (!creator) return;
16469
+ if (role.trim().toLowerCase() === "admin") return;
16470
+
16471
+ const reason = \`\${tool} is restricted to admin task creators. Task \${taskId} was created by user \${creator}, whose role is \${role ? \`"\${role}"\` : "not set"}.\`;
16472
+ ctx.log.warn(reason, { tool, taskId, requestedByUserId: creator });
16473
+ return block(reason);
16474
+ });
16475
+ };
16476
+
16477
+ export default extension;
16478
+ `
16479
+ },
16480
+ readme: "# sql-admin-only\n\nBlocks `db-query` tool calls made on a task whose creator (`requestedByUserId`) is not an admin. Every other tool call passes untouched.\n\n| Task creator | `db-query` |\n|---|---|\n| Not set, or the call has no task | Allowed |\n| Set, holds an admin role | Allowed |\n| Set, no admin role | Blocked |\n| Set, but the lookup fails, times out, or the task row is missing | Blocked |\n\nNo config. \"Admin\" means the creator's `users.role` is `admin` (case-insensitive), the role the swarm shows next to a requester's name. Only Lead (`manage-user`) and REST callers with `user.role.manage` can set it. RBAC roles are not used, because every user is created with the RBAC `admin` role. A creator whose user row is gone counts as non-admin.\n\nThe task comes from the call's `X-Source-Task-Id` header. The lookup gets 60% of `EXTENSION_HANDLER_TIMEOUT_MS` (default 5s), because the dispatcher lets a call through when a hook times out.\n\nCoverage limits:\n\n- Only agent MCP tool calls run `pre.tool.call`. Scripts calling `ctx.swarm.db_query`, extensions, and direct `POST /api/db-query` requests skip the hook.\n- A call without an `X-Source-Task-Id` header has no task, so it is allowed.\n"
16481
+ },
15738
16482
  "task-digest": {
15739
16483
  manifestFile: "manifest.yaml",
15740
16484
  manifest: {
@@ -15908,7 +16652,7 @@ function getCatalogEntry(name) {
15908
16652
  init_lifecycle();
15909
16653
  init_loader();
15910
16654
  init_rbac();
15911
- init_types4();
16655
+ init_types5();
15912
16656
  init_env_flag();
15913
16657
  init_secret_scrubber();
15914
16658
  init_request_principal();
@@ -16526,8 +17270,9 @@ async function handleExtensions(req, res, pathSegments, queryParams, agentId) {
16526
17270
 
16527
17271
  // src/http/favorites.ts
16528
17272
  init_zod();
17273
+ init_key();
16529
17274
  init_db4();
16530
- init_types4();
17275
+ init_types5();
16531
17276
  init_favorite_owner();
16532
17277
  init_route_def();
16533
17278
  init_utils2();
@@ -16574,6 +17319,7 @@ var putFavorite = route({
16574
17319
  row: UserFavoriteSchema.nullable()
16575
17320
  })
16576
17321
  },
17322
+ 400: { description: "Invalid asset key for a key favorite" },
16577
17323
  401: { description: "No authenticated principal context" }
16578
17324
  }
16579
17325
  });
@@ -16608,18 +17354,29 @@ async function handleFavorites(req, res, pathSegments, queryParams, myAgentId) {
16608
17354
  jsonError(res, "Authenticated principal required to update favorites", 401);
16609
17355
  return true;
16610
17356
  }
17357
+ let itemId = parsed.body.itemId;
17358
+ if (parsed.body.itemType === "key") {
17359
+ try {
17360
+ itemId = normalizeAssetKey(itemId);
17361
+ } catch (error) {
17362
+ if (!(error instanceof AssetKeyError))
17363
+ throw error;
17364
+ jsonError(res, error.message, 400);
17365
+ return true;
17366
+ }
17367
+ }
16611
17368
  const favorite = await setFavorite2({
16612
17369
  favoriteScope: owner.scope,
16613
17370
  userId: owner.userId,
16614
17371
  itemType: parsed.body.itemType,
16615
- itemId: parsed.body.itemId,
17372
+ itemId,
16616
17373
  favorite: parsed.body.favorite,
16617
17374
  actorId: owner.actorId
16618
17375
  });
16619
17376
  putFavorite.respond(res, 200, {
16620
17377
  favorite: parsed.body.favorite,
16621
17378
  itemType: parsed.body.itemType,
16622
- itemId: parsed.body.itemId,
17379
+ itemId,
16623
17380
  row: favorite
16624
17381
  });
16625
17382
  return true;
@@ -16918,6 +17675,142 @@ async function handleFleetBenchmark(req, res, pathSegments, queryParams) {
16918
17675
 
16919
17676
  // src/http/fs.ts
16920
17677
  init_zod();
17678
+
17679
+ // src/be/agent-fs-user-keys.ts
17680
+ init_secret_scrubber();
17681
+ init_rbac_roles();
17682
+ init_users();
17683
+
17684
+ class AgentFsKeyValidationError extends Error {
17685
+ }
17686
+ async function ensureUserAgentFsAccount(userId) {
17687
+ if (!await resolveApiUrl2()) {
17688
+ return { status: "off", reason: "AGENT_FS_API_URL is not configured" };
17689
+ }
17690
+ const user = await findUserById(userId);
17691
+ const email = user?.email?.trim() ?? "";
17692
+ if (!user || !email) {
17693
+ return { status: "pending", email, reason: "The swarm user is missing or has no email" };
17694
+ }
17695
+ const shared = await resolveAgentFsSharedContext2();
17696
+ if (!shared)
17697
+ return { status: "off", reason: "AGENT_FS_API_URL is not configured" };
17698
+ const pending = (reason) => ({
17699
+ status: "pending",
17700
+ email,
17701
+ orgId: shared.orgId,
17702
+ driveId: shared.driveId,
17703
+ reason: scrubSecrets(reason)
17704
+ });
17705
+ const grant = await getUserGrant2(userId);
17706
+ const role = grant.grantsAll || grant.verbs.has("task.fs.mutate") ? "editor" : "viewer";
17707
+ const members = await getCurrentOrgMembers2(shared.apiUrl, shared.authHeaders, shared.orgId);
17708
+ let member = members.find((candidate) => candidate.email === email.toLowerCase());
17709
+ let registeredKey;
17710
+ if (!member) {
17711
+ try {
17712
+ const registered = await agentFsRequest2(shared.apiUrl, "/auth/register", { method: "POST", body: { email } });
17713
+ if (typeof registered?.apiKey === "string" && registered.apiKey) {
17714
+ registeredKey = registered.apiKey;
17715
+ registerVolatileSecret(registeredKey, "AGENT_FS_USER_PRIMARY_KEY");
17716
+ }
17717
+ } catch (error) {
17718
+ if (!(error instanceof AgentFsRequestError2) || error.status >= 500)
17719
+ throw error;
17720
+ if (error.status !== 409)
17721
+ return pending(error.message);
17722
+ }
17723
+ }
17724
+ if (!member || roleRank2(member.role) < roleRank2(role)) {
17725
+ const invited = await inviteEmailToSharedOrg2(email, role);
17726
+ if (invited.status === "pending") {
17727
+ if (!registeredKey || !invited.token)
17728
+ return pending("The agent-fs org invite is pending");
17729
+ try {
17730
+ await agentFsRequest2(shared.apiUrl, `/invites/${encodeURIComponent(invited.token)}/accept`, {
17731
+ method: "POST",
17732
+ headers: { authorization: `Bearer ${registeredKey}` },
17733
+ allowConflict: true
17734
+ });
17735
+ } catch (error) {
17736
+ if (error instanceof AgentFsRequestError2 && error.status < 500) {
17737
+ return pending(`The agent-fs org invite could not be accepted: HTTP ${error.status}`);
17738
+ }
17739
+ throw new Error(`agent-fs invite accept failed${error instanceof AgentFsRequestError2 ? `: HTTP ${error.status}` : ""}`);
17740
+ }
17741
+ }
17742
+ member = (await getCurrentOrgMembers2(shared.apiUrl, shared.authHeaders, shared.orgId)).find((candidate) => candidate.email === email.toLowerCase());
17743
+ }
17744
+ if (!member?.userId || roleRank2(member.role) < roleRank2(role)) {
17745
+ return pending("The agent-fs org membership is not ready");
17746
+ }
17747
+ if (member.role !== "admin" && roleRank2(member.role) > roleRank2(role)) {
17748
+ try {
17749
+ await agentFsRequest2(shared.apiUrl, `/orgs/${encodeURIComponent(shared.orgId)}/members/${encodeURIComponent(member.userId)}`, { method: "PATCH", headers: shared.authHeaders, body: { role } });
17750
+ } catch (error) {
17751
+ if (!(error instanceof AgentFsRequestError2) || error.status >= 500)
17752
+ throw error;
17753
+ return pending(`The agent-fs org role could not be lowered to ${role}`);
17754
+ }
17755
+ }
17756
+ return {
17757
+ status: "ready",
17758
+ agentFsUserId: member.userId,
17759
+ email,
17760
+ displayName: user.name,
17761
+ orgId: shared.orgId,
17762
+ driveId: shared.driveId
17763
+ };
17764
+ }
17765
+ async function mintUserAgentFsKey(userId, label) {
17766
+ const sanitized = Array.from(label.replace(/\p{Cc}/gu, "").replace(/\s+/gu, " ").trim()).slice(0, 100).join("");
17767
+ if (!sanitized)
17768
+ throw new AgentFsKeyValidationError("The key label must contain visible text");
17769
+ const account = await ensureUserAgentFsAccount(userId);
17770
+ if (account.status !== "ready")
17771
+ return account;
17772
+ const shared = await resolveAgentFsSharedContext2();
17773
+ if (!shared)
17774
+ return { status: "off", reason: "AGENT_FS_API_URL is not configured" };
17775
+ try {
17776
+ const minted = await agentFsRequest2(shared.apiUrl, `/orgs/${encodeURIComponent(account.orgId)}/members/${encodeURIComponent(account.agentFsUserId)}/keys`, { method: "POST", headers: shared.authHeaders, body: { label: sanitized } });
17777
+ if (!minted.apiKey || !minted.id)
17778
+ throw new Error("agent-fs did not return a named key");
17779
+ registerVolatileSecret(minted.apiKey, `AGENT_FS_USER_KEY:${minted.id}`);
17780
+ return {
17781
+ status: "minted",
17782
+ apiKey: minted.apiKey,
17783
+ keyId: minted.id,
17784
+ label: minted.label,
17785
+ agentFsUserId: account.agentFsUserId,
17786
+ orgId: account.orgId,
17787
+ driveId: account.driveId
17788
+ };
17789
+ } catch (error) {
17790
+ if (error instanceof AgentFsRequestError2 && error.status === 404) {
17791
+ let memberMissing = false;
17792
+ try {
17793
+ memberMissing = JSON.parse(error.body)?.error === "NOT_FOUND";
17794
+ } catch {}
17795
+ if (memberMissing) {
17796
+ return {
17797
+ status: "pending",
17798
+ email: account.email,
17799
+ orgId: account.orgId,
17800
+ driveId: account.driveId,
17801
+ reason: scrubSecrets(error.message)
17802
+ };
17803
+ }
17804
+ return {
17805
+ status: "unsupported",
17806
+ reason: "Named user keys require agent-fs 0.18.17 or later"
17807
+ };
17808
+ }
17809
+ throw error;
17810
+ }
17811
+ }
17812
+
17813
+ // src/http/fs.ts
16921
17814
  init_db4();
16922
17815
 
16923
17816
  // src/be/db/tasks/draft-text.ts
@@ -16932,10 +17825,13 @@ ${block}`, new Date().toISOString(), taskId]);
16932
17825
  // src/http/fs.ts
16933
17826
  init_rbac_roles();
16934
17827
  init_task_attachment_store();
17828
+ init_users();
17829
+ init_config3();
16935
17830
  init_provider();
16936
17831
  init_registry2();
16937
17832
  init_rbac();
16938
- init_types4();
17833
+ init_types5();
17834
+ init_constants3();
16939
17835
 
16940
17836
  // src/utils/content-disposition.ts
16941
17837
  function attachmentContentDisposition(filename) {
@@ -16949,11 +17845,120 @@ function attachmentContentDisposition(filename) {
16949
17845
  init_request_auth_context();
16950
17846
  init_secret_scrubber();
16951
17847
  init_transcription();
17848
+ init_favorite_owner();
16952
17849
  init_request_principal();
16953
17850
  init_route_def();
16954
17851
  init_session_access();
16955
17852
  init_utils2();
16956
17853
  var SLOW_UPLOAD_LOG_MS = 3000;
17854
+ var fsKeyRateLimit = createIpRateLimiter({ capacity: 5, refillPerMs: 5 / 60000 });
17855
+ var fsContinueRateLimit = createIpRateLimiter({ capacity: 10, refillPerMs: 10 / 60000 });
17856
+ var fsMeRateLimit = createIpRateLimiter({ capacity: 20, refillPerMs: 20 / 60000 });
17857
+ var userAgentFsStateSchema = object2({
17858
+ status: _enum2(["ready", "pending", "off", "unsupported"]).describe("Account readiness in agent-fs."),
17859
+ agentFsUserId: string2().optional().describe("User ID in agent-fs when ready."),
17860
+ email: string2().optional().describe("Email of the swarm user, when available."),
17861
+ displayName: string2().optional().describe("Name of the swarm user when ready."),
17862
+ orgId: string2().optional().describe("Shared agent-fs org ID when configured."),
17863
+ driveId: string2().optional().describe("Shared agent-fs drive ID when configured."),
17864
+ reason: string2().optional().describe("Reason the account is not ready.")
17865
+ });
17866
+ var userAgentFsMeRoute = route({
17867
+ method: "get",
17868
+ path: "/api/fs/me",
17869
+ pattern: ["api", "fs", "me"],
17870
+ summary: "Ensure the current user's agent-fs account and shared membership",
17871
+ tags: ["FS"],
17872
+ responses: {
17873
+ 200: { description: "Account readiness", schema: userAgentFsStateSchema },
17874
+ 401: { description: "User identity required" },
17875
+ 403: { description: "Caller cannot join the shared org" },
17876
+ 429: { description: "Limit of twenty account checks per minute reached" },
17877
+ 502: { description: "agent-fs request failed" }
17878
+ }
17879
+ });
17880
+ var mintUserAgentFsKeyRoute = route({
17881
+ method: "post",
17882
+ path: "/api/fs/keys",
17883
+ pattern: ["api", "fs", "keys"],
17884
+ summary: "Mint a named agent-fs key for the current user",
17885
+ description: "The key is scoped to the shared org. The API returns it once and never stores it.",
17886
+ tags: ["FS"],
17887
+ body: object2({ label: string2().min(1).max(100) }),
17888
+ rbac: { permission: "fs.join.own" },
17889
+ responses: {
17890
+ 201: {
17891
+ description: "Named key returned once and never stored",
17892
+ schema: object2({
17893
+ apiKey: string2().describe("Plaintext key returned once. The API never stores this key."),
17894
+ keyId: string2(),
17895
+ label: string2(),
17896
+ agentFsUserId: string2(),
17897
+ orgId: string2(),
17898
+ driveId: string2()
17899
+ })
17900
+ },
17901
+ 400: { description: "Invalid key label" },
17902
+ 401: { description: "User identity required" },
17903
+ 403: { description: "Caller cannot join the shared org" },
17904
+ 409: { description: "agent-fs account or membership is pending" },
17905
+ 429: { description: "Limit of five keys per minute reached" },
17906
+ 501: { description: "agent_fs_too_old" },
17907
+ 502: { description: "agent-fs request failed" },
17908
+ 503: { description: "agent_fs_not_configured" }
17909
+ }
17910
+ });
17911
+ var continueToAgentFsRoute = route({
17912
+ method: "post",
17913
+ path: "/api/fs/continue",
17914
+ pattern: ["api", "fs", "continue"],
17915
+ summary: "Mint a named agent-fs key for the live agent-fs app and return the redirect URL",
17916
+ description: "Powers 'Continue with your swarm' on the live agent-fs app. The key travels only in the URL fragment of `redirectUrl`. The API never stores it.",
17917
+ tags: ["FS"],
17918
+ body: object2({ returnTo: url().max(4096) }),
17919
+ rbac: { permission: "fs.join.own" },
17920
+ responses: {
17921
+ 200: {
17922
+ description: "Redirect URL with the named key in the fragment",
17923
+ schema: object2({
17924
+ redirectUrl: string2().describe("`returnTo` with `#key=<af_...>&apiUrl=<browser-facing agent-fs API URL>` as its only fragment.")
17925
+ })
17926
+ },
17927
+ 400: {
17928
+ description: "invalid_return_to: the origin is not the live agent-fs app (AGENT_FS_LIVE_URL). org_mismatch: the `returnTo` path names an agent-fs org other than this swarm's shared org."
17929
+ },
17930
+ 401: { description: "User identity required" },
17931
+ 403: { description: "Caller cannot join the shared org" },
17932
+ 409: { description: "agent-fs account or membership is pending" },
17933
+ 429: { description: "Limit of ten continues per minute reached" },
17934
+ 501: { description: "agent_fs_too_old" },
17935
+ 502: { description: "agent-fs request failed" },
17936
+ 503: { description: "agent_fs_not_configured" }
17937
+ }
17938
+ });
17939
+ function allowedReturnOrigin() {
17940
+ try {
17941
+ const { origin } = new URL(getAgentFsLiveUrl());
17942
+ return origin === "null" ? null : origin;
17943
+ } catch {
17944
+ return null;
17945
+ }
17946
+ }
17947
+ var LIVE_APP_PATH = /^\/(?:|credentials|keys|files|(?:file|detail|page)\/~\/[^/]+\/[^/]+(?:\/.*)?|(?:sql|members|shares|webhooks)\/~\/[^/]+\/[^/]+\/?|orgs\/[^/]+\/files(?:\/.*)?)$/;
17948
+ function isLiveAppReturnPath(target) {
17949
+ return LIVE_APP_PATH.test(target.pathname);
17950
+ }
17951
+ function liveAppOrgId(target) {
17952
+ const segments = target.pathname.split("/").slice(1);
17953
+ const raw = segments[1] === "~" ? segments[2] : segments[0] === "orgs" ? segments[1] : undefined;
17954
+ if (!raw)
17955
+ return null;
17956
+ try {
17957
+ return decodeURIComponent(raw);
17958
+ } catch {
17959
+ return raw;
17960
+ }
17961
+ }
16957
17962
  var taskParams = object2({ taskId: uuid() });
16958
17963
  var attachmentParams = object2({ taskId: uuid(), attachmentId: uuid() });
16959
17964
  var uploadQuery = object2({
@@ -17165,7 +18170,161 @@ async function resolveInvite(req, body) {
17165
18170
  }
17166
18171
  return { email: ownEmail, role: grant.verbs.has("task.fs.mutate") ? "editor" : "viewer" };
17167
18172
  }
18173
+ async function denyFsJoin(userId) {
18174
+ const decision = can({
18175
+ principal: { kind: "user", userId },
18176
+ verb: "fs.join.own",
18177
+ resource: { kind: "none" },
18178
+ source: "http"
18179
+ });
18180
+ if (!decision.allow)
18181
+ return decision.reason;
18182
+ if (!isRbacEnabled())
18183
+ return null;
18184
+ const grant = await getUserGrant2(userId);
18185
+ return grant.grantsAll || grant.verbs.has("fs.join.own") ? null : "missing permission 'fs.join.own'";
18186
+ }
18187
+ async function resolveAgentFsUserId(req) {
18188
+ const auth = getRequestAuth(req);
18189
+ if (auth?.page)
18190
+ return null;
18191
+ const userId = authUserId(auth);
18192
+ if (userId)
18193
+ return userId;
18194
+ if (!isOperatorAuth(auth) || req.headers["x-agent-id"] !== undefined)
18195
+ return null;
18196
+ const pickedUserId = dashboardUserIdHeader(req);
18197
+ if (!pickedUserId)
18198
+ return null;
18199
+ const user = await findUserById(pickedUserId);
18200
+ return user?.status === "active" ? user.id : null;
18201
+ }
18202
+ function respondMintFailure(res, result) {
18203
+ switch (result.status) {
18204
+ case "pending":
18205
+ jsonError(res, scrubSecrets(`agent-fs account pending: ${result.reason}`), 409);
18206
+ break;
18207
+ case "unsupported":
18208
+ jsonError(res, "agent_fs_too_old", 501);
18209
+ break;
18210
+ case "off":
18211
+ jsonError(res, "agent_fs_not_configured", 503);
18212
+ break;
18213
+ }
18214
+ }
18215
+ function respondMintError(res, error) {
18216
+ jsonError(res, scrubSecrets(error instanceof Error ? error.message : String(error)), error instanceof AgentFsKeyValidationError ? 400 : 502);
18217
+ }
17168
18218
  async function handleFs(req, res, pathSegments, queryParams, myAgentId) {
18219
+ if (userAgentFsMeRoute.match(req.method, pathSegments)) {
18220
+ const userId = await resolveAgentFsUserId(req);
18221
+ if (!userId) {
18222
+ jsonError(res, "user identity required", 401);
18223
+ return true;
18224
+ }
18225
+ const denied = await denyFsJoin(userId);
18226
+ if (denied) {
18227
+ jsonError(res, denied, 403);
18228
+ return true;
18229
+ }
18230
+ if (!fsMeRateLimit.take(userId)) {
18231
+ jsonError(res, "Limit of twenty account checks per minute reached", 429);
18232
+ return true;
18233
+ }
18234
+ try {
18235
+ userAgentFsMeRoute.respond(res, 200, await ensureUserAgentFsAccount(userId));
18236
+ } catch (error) {
18237
+ jsonError(res, scrubSecrets(error instanceof Error ? error.message : String(error)), 502);
18238
+ }
18239
+ return true;
18240
+ }
18241
+ if (mintUserAgentFsKeyRoute.match(req.method, pathSegments)) {
18242
+ const userId = await resolveAgentFsUserId(req);
18243
+ if (!userId) {
18244
+ jsonError(res, "user identity required", 401);
18245
+ return true;
18246
+ }
18247
+ const parsed = await mintUserAgentFsKeyRoute.parse(req, res, pathSegments, queryParams);
18248
+ if (!parsed)
18249
+ return true;
18250
+ const denied = await denyFsJoin(userId);
18251
+ if (denied) {
18252
+ jsonError(res, denied, 403);
18253
+ return true;
18254
+ }
18255
+ if (!fsKeyRateLimit.take(userId)) {
18256
+ jsonError(res, "Limit of five keys per minute reached", 429);
18257
+ return true;
18258
+ }
18259
+ try {
18260
+ const result = await mintUserAgentFsKey(userId, parsed.body.label);
18261
+ if (result.status === "minted") {
18262
+ res.setHeader("Cache-Control", "no-store");
18263
+ const { status: _, ...key } = result;
18264
+ mintUserAgentFsKeyRoute.respond(res, 201, key);
18265
+ } else {
18266
+ respondMintFailure(res, result);
18267
+ }
18268
+ } catch (error) {
18269
+ respondMintError(res, error);
18270
+ }
18271
+ return true;
18272
+ }
18273
+ if (continueToAgentFsRoute.match(req.method, pathSegments)) {
18274
+ const userId = await resolveAgentFsUserId(req);
18275
+ if (!userId) {
18276
+ jsonError(res, "user identity required", 401);
18277
+ return true;
18278
+ }
18279
+ const parsed = await continueToAgentFsRoute.parse(req, res, pathSegments, queryParams);
18280
+ if (!parsed)
18281
+ return true;
18282
+ const denied = await denyFsJoin(userId);
18283
+ if (denied) {
18284
+ jsonError(res, denied, 403);
18285
+ return true;
18286
+ }
18287
+ const target = new URL(parsed.body.returnTo);
18288
+ if (target.origin !== allowedReturnOrigin() || !isLiveAppReturnPath(target)) {
18289
+ jsonError(res, "invalid_return_to", 400);
18290
+ return true;
18291
+ }
18292
+ if (!fsContinueRateLimit.take(userId)) {
18293
+ jsonError(res, "Limit of ten continues per minute reached", 429);
18294
+ return true;
18295
+ }
18296
+ const browserApiUrl = getCombConfig().apiUrl;
18297
+ if (!browserApiUrl) {
18298
+ jsonError(res, "agent_fs_not_configured", 503);
18299
+ return true;
18300
+ }
18301
+ try {
18302
+ const linkOrgId = liveAppOrgId(target);
18303
+ if (linkOrgId) {
18304
+ const shared = await resolveAgentFsSharedContext2();
18305
+ if (!shared) {
18306
+ jsonError(res, "agent_fs_not_configured", 503);
18307
+ return true;
18308
+ }
18309
+ if (shared.orgId !== linkOrgId) {
18310
+ jsonError(res, "org_mismatch", 400);
18311
+ return true;
18312
+ }
18313
+ }
18314
+ const date = new Date().toISOString().slice(0, 10);
18315
+ const result = await mintUserAgentFsKey(userId, `${target.host} · ${date}`);
18316
+ if (result.status === "minted") {
18317
+ target.hash = `key=${encodeURIComponent(result.apiKey)}&apiUrl=${encodeURIComponent(browserApiUrl)}`;
18318
+ res.setHeader("Cache-Control", "no-store");
18319
+ continueToAgentFsRoute.respond(res, 200, { redirectUrl: target.toString() });
18320
+ } else {
18321
+ respondMintFailure(res, result);
18322
+ }
18323
+ } catch (error) {
18324
+ respondMintError(res, error);
18325
+ }
18326
+ return true;
18327
+ }
17169
18328
  if (ensureAgentCredentialsRoute.match(req.method, pathSegments)) {
17170
18329
  const parsed = await ensureAgentCredentialsRoute.parse(req, res, pathSegments, queryParams);
17171
18330
  if (!parsed)
@@ -17177,7 +18336,7 @@ async function handleFs(req, res, pathSegments, queryParams, myAgentId) {
17177
18336
  return true;
17178
18337
  }
17179
18338
  try {
17180
- const result = await ensureAgentFsCredentialsForAgent(agentId);
18339
+ const result = await ensureAgentFsCredentialsForAgent2(agentId);
17181
18340
  ensureAgentCredentialsRoute.respond(res, 200, result);
17182
18341
  } catch (error) {
17183
18342
  const message = scrubSecrets(error instanceof Error ? error.message : String(error));
@@ -17195,7 +18354,7 @@ async function handleFs(req, res, pathSegments, queryParams, myAgentId) {
17195
18354
  return true;
17196
18355
  }
17197
18356
  try {
17198
- const result = await inviteEmailToSharedOrg(invite.email, invite.role);
18357
+ const result = await inviteEmailToSharedOrg2(invite.email, invite.role);
17199
18358
  inviteMemberRoute.respond(res, 200, result);
17200
18359
  } catch (error) {
17201
18360
  const message = scrubSecrets(error instanceof Error ? error.message : String(error));
@@ -17380,8 +18539,8 @@ async function sendSignedUrl(res, attachment, expiresIn) {
17380
18539
  return true;
17381
18540
  }
17382
18541
  try {
17383
- const url = await provider.url(scopeFromAttachment(attachment), { expiresIn });
17384
- signedUrlTaskFileRoute.respond(res, 200, { url, expiresIn: Math.min(expiresIn ?? 3600, 3600) });
18542
+ const url2 = await provider.url(scopeFromAttachment(attachment), { expiresIn });
18543
+ signedUrlTaskFileRoute.respond(res, 200, { url: url2, expiresIn: Math.min(expiresIn ?? 3600, 3600) });
17385
18544
  } catch (error) {
17386
18545
  return sendProviderError(res, error);
17387
18546
  }
@@ -17797,7 +18956,7 @@ init_zod();
17797
18956
  init_db4();
17798
18957
  init_rbac_roles();
17799
18958
  init_rbac();
17800
- init_types4();
18959
+ init_types5();
17801
18960
  init_request_auth_context();
17802
18961
  init_route_def();
17803
18962
  init_utils2();
@@ -17943,209 +19102,6 @@ async function handleInboxState(req, res, pathSegments, queryParams) {
17943
19102
  // src/http/integrations.ts
17944
19103
  init_zod();
17945
19104
 
17946
- // src/integrations/chat-sdk/status.ts
17947
- init_zod();
17948
- init_constants3();
17949
- init_env_flag();
17950
- init_secret_scrubber();
17951
- init_adapters();
17952
- init_config();
17953
-
17954
- // src/integrations/chat-sdk/discord-api.ts
17955
- init_secret_scrubber();
17956
- init_adapters();
17957
- init_logger();
17958
- var DISCORD_TIMEOUT_MS = 5000;
17959
- var GUILDS_CACHE_MS = 60000;
17960
- var MAX_GUILD_NAMES = 10;
17961
- var cache;
17962
- async function fetchDiscordGuilds(token, now = Date.now()) {
17963
- if (cache && cache.token === token && now - cache.at < GUILDS_CACHE_MS)
17964
- return cache.guilds;
17965
- let guilds;
17966
- try {
17967
- const response = await fetch(`${resolveAdapterApiUrl("discord")}/users/@me/guilds`, {
17968
- headers: { authorization: `Bot ${token}` },
17969
- signal: AbortSignal.timeout(DISCORD_TIMEOUT_MS)
17970
- });
17971
- if (!response.ok)
17972
- throw new Error(`HTTP ${response.status}`);
17973
- const payload = await response.json();
17974
- if (!Array.isArray(payload))
17975
- throw new Error("unexpected response shape");
17976
- const names = payload.map((guild) => guild !== null && typeof guild === "object" && typeof guild.name === "string" ? guild.name : undefined).filter((name) => name !== undefined);
17977
- guilds = { count: payload.length, names: names.slice(0, MAX_GUILD_NAMES) };
17978
- } catch (error) {
17979
- console.warn(scrubSecrets(`[chat-sdk] discord: could not list the bot's servers: ${errorMessage(error).replaceAll(token, "[REDACTED]")}`));
17980
- }
17981
- cache = { token, at: now, guilds };
17982
- return guilds;
17983
- }
17984
-
17985
- // src/integrations/chat-sdk/status.ts
17986
- init_runtime();
17987
- init_schema();
17988
- init_telegram_api();
17989
- var ChatSdkStatusSchema = object2({
17990
- enabled: boolean(),
17991
- slackClash: boolean(),
17992
- error: string2().optional(),
17993
- adapters: array2(object2({
17994
- name: _enum2(CHAT_SDK_ADAPTER_NAMES),
17995
- configured: boolean(),
17996
- enabled: boolean(),
17997
- health: _enum2(["ok", "error", "disabled", "incomplete"]),
17998
- error: string2().optional(),
17999
- webhookUrl: string2(),
18000
- mode: string2().optional(),
18001
- gateway: object2({
18002
- state: _enum2(["running", "backoff", "stopped"]),
18003
- since: string2(),
18004
- restarts: number2()
18005
- }).optional(),
18006
- guilds: object2({ count: number2(), names: array2(string2()) }).optional()
18007
- }))
18008
- });
18009
- var DEFAULT_MODES = {
18010
- telegram: "webhook",
18011
- slack: "webhook"
18012
- };
18013
- var NOT_RUNNING = "The adapter is starting, or the last configuration save is still applying. Refresh in a few seconds.";
18014
- var SLACK_CLASH_CAUSE = "the Slack adapter conflicts with the built-in Slack integration (set SLACK_DISABLE=true)";
18015
- var MAX_STATUS_ERROR_CHARS = 300;
18016
- function statusError(message) {
18017
- return scrubSecrets(message).slice(0, MAX_STATUS_ERROR_CHARS);
18018
- }
18019
- function readRawAdapters() {
18020
- const raw = process.env.CHAT_SDK_ADAPTERS?.trim();
18021
- if (!raw)
18022
- return {};
18023
- try {
18024
- const parsed = JSON.parse(raw);
18025
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
18026
- return {};
18027
- const out = {};
18028
- for (const name of CHAT_SDK_ADAPTER_NAMES) {
18029
- const value = parsed[name];
18030
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
18031
- out[name] = value;
18032
- }
18033
- }
18034
- return out;
18035
- } catch {
18036
- return {};
18037
- }
18038
- }
18039
- function chatSdkWebhookUrl(name) {
18040
- return `${getPublicMcpBaseUrl()}/api/integrations/chat/${name}/webhook`;
18041
- }
18042
- async function discordGuildsFor(config, health) {
18043
- if (health?.status !== "ok" || health.gateway?.state !== "running")
18044
- return;
18045
- const raw = config.adapters.discord?.botToken;
18046
- const token = typeof raw === "function" ? await raw() : raw;
18047
- if (typeof token !== "string" || token.length === 0)
18048
- return;
18049
- return fetchDiscordGuilds(token);
18050
- }
18051
- async function getChatSdkStatus() {
18052
- const config = await getChatSdkConfig();
18053
- const raw = readRawAdapters();
18054
- const runtimeHealth = getChatSdkHealth();
18055
- const slackClash = raw.slack !== undefined && !isEnvFlagEnabled("SLACK_DISABLE", false);
18056
- const blockedCause = config.error ?? (config.enabled && slackClash ? SLACK_CLASH_CAUSE : undefined);
18057
- const discordGuilds = await discordGuildsFor(config, runtimeHealth.discord);
18058
- const adapters = CHAT_SDK_ADAPTER_NAMES.map((name) => {
18059
- const configured = raw[name] !== undefined;
18060
- const enabled = isAdapterEntryEnabled(raw[name]);
18061
- const current = runtimeHealth[name];
18062
- const incomplete = config.incomplete?.[name];
18063
- const rawMode = raw[name]?.mode;
18064
- const mode = typeof rawMode === "string" ? rawMode : configured ? DEFAULT_MODES[name] : undefined;
18065
- let health = "disabled";
18066
- let error;
18067
- if (current) {
18068
- health = current.status;
18069
- const showWarning = current.status === "error" || current.gateway?.state === "backoff";
18070
- error = current.error ?? (showWarning ? current.lastWarning : undefined);
18071
- } else if (incomplete) {
18072
- health = "incomplete";
18073
- error = incomplete;
18074
- } else if (configured && !enabled) {
18075
- error = "Turned off on the card. The configuration is kept.";
18076
- } else if (config.enabled && configured) {
18077
- error = blockedCause ? `Not started: ${blockedCause}` : NOT_RUNNING;
18078
- }
18079
- return {
18080
- name,
18081
- configured,
18082
- enabled,
18083
- health,
18084
- ...error ? { error: statusError(error) } : {},
18085
- webhookUrl: chatSdkWebhookUrl(name),
18086
- ...mode ? { mode } : {},
18087
- ...current?.gateway ? { gateway: current.gateway } : {},
18088
- ...name === "discord" && discordGuilds ? { guilds: discordGuilds } : {}
18089
- };
18090
- });
18091
- return {
18092
- enabled: config.enabled,
18093
- slackClash,
18094
- ...config.error ? { error: statusError(config.error) } : {},
18095
- adapters
18096
- };
18097
- }
18098
-
18099
- class ChatSdkActionError extends Error {
18100
- status;
18101
- constructor(message, status) {
18102
- super(message);
18103
- this.status = status;
18104
- this.name = "ChatSdkActionError";
18105
- }
18106
- }
18107
- async function callBotApi(baseUrl, token, method, body) {
18108
- try {
18109
- return await callTelegramBotApi(baseUrl, token, method, body);
18110
- } catch (error) {
18111
- if (error instanceof TelegramBotApiError)
18112
- throw new ChatSdkActionError(error.message, 502);
18113
- throw error;
18114
- }
18115
- }
18116
- async function registerTelegramWebhook() {
18117
- const config = await getChatSdkConfig();
18118
- if (!config.enabled) {
18119
- throw new ChatSdkActionError("The Chat SDK channel is disabled (CHAT_SDK_ENABLED is not true). Enable it and restart the API first", 400);
18120
- }
18121
- if (config.error)
18122
- throw new ChatSdkActionError(statusError(config.error), 400);
18123
- const telegram = config.adapters.telegram;
18124
- if (!telegram) {
18125
- throw new ChatSdkActionError("Telegram is not configured in CHAT_SDK_ADAPTERS", 400);
18126
- }
18127
- if (telegram.mode !== "webhook") {
18128
- throw new ChatSdkActionError("Telegram runs in polling mode; a registered webhook would stop polling", 400);
18129
- }
18130
- const secretToken = telegram.secretToken;
18131
- if (typeof secretToken !== "string" || secretToken.length === 0) {
18132
- throw new ChatSdkActionError("Telegram webhook mode needs a secretToken", 400);
18133
- }
18134
- const rawToken = telegram.botToken;
18135
- const token = typeof rawToken === "function" ? await rawToken() : rawToken;
18136
- if (typeof token !== "string" || token.length === 0) {
18137
- throw new ChatSdkActionError("Telegram botToken is empty", 400);
18138
- }
18139
- const baseUrl = resolveAdapterApiUrl("telegram");
18140
- const webhookUrl = chatSdkWebhookUrl("telegram");
18141
- await callBotApi(baseUrl, token, "setWebhook", { url: webhookUrl, secret_token: secretToken });
18142
- const info = await callBotApi(baseUrl, token, "getWebhookInfo", {});
18143
- if (info === null || typeof info !== "object" || typeof info.url !== "string") {
18144
- throw new ChatSdkActionError("Telegram getWebhookInfo returned an unexpected result", 502);
18145
- }
18146
- return { webhookUrl, webhookInfo: info };
18147
- }
18148
-
18149
19105
  // src/slack/app-icon.ts
18150
19106
  init_app3();
18151
19107
  var import_web_api = __toESM(require_dist4(), 1);
@@ -18540,7 +19496,7 @@ init_kv_reserved_namespaces();
18540
19496
  init_kv_view();
18541
19497
  init_rbac();
18542
19498
  init_context_key();
18543
- init_types4();
19499
+ init_types5();
18544
19500
  init_route_def();
18545
19501
  init_utils2();
18546
19502
  var MAX_KV_BODY_BYTES = 2 * 1024 * 1024;
@@ -18780,6 +19736,16 @@ function authorizeWrite(namespace, ctx) {
18780
19736
  }
18781
19737
  return null;
18782
19738
  }
19739
+ if (requiresLeadToWrite(namespace)) {
19740
+ const allowed = ctx.callerAgentId != null && can({
19741
+ principal: { kind: "agent", agentId: ctx.callerAgentId, isLead: ctx.isLead },
19742
+ verb: "kv.write.any",
19743
+ resource: { kind: "kv-namespace", namespace },
19744
+ source: "http"
19745
+ }).allow;
19746
+ if (!allowed)
19747
+ return { status: 403, message: "writes to this namespace require lead" };
19748
+ }
18783
19749
  if (namespace.startsWith("task:agent:")) {
18784
19750
  const allowed = ctx.callerAgentId != null && can({
18785
19751
  principal: { kind: "agent", agentId: ctx.callerAgentId, isLead: ctx.isLead },
@@ -20747,7 +21713,7 @@ init_db4();
20747
21713
  init_mcp_oauth();
20748
21714
  init_ensure_mcp_token();
20749
21715
  init_mcp_wrapper();
20750
- init_types4();
21716
+ init_types5();
20751
21717
  init_constants3();
20752
21718
  init_route_def();
20753
21719
  init_utils2();
@@ -20758,7 +21724,7 @@ function dashboardBase() {
20758
21724
  return getAppUrl();
20759
21725
  }
20760
21726
  function defaultFinalRedirect(mcpServerId) {
20761
- return `${dashboardBase()}/mcp-servers/${mcpServerId}?oauth=success`;
21727
+ return `${dashboardBase()}/integrations/tools/mcp-servers/${mcpServerId}?oauth=success`;
20762
21728
  }
20763
21729
  var DiscoveryResultSchema = object2({
20764
21730
  resourceUrl: string2(),
@@ -21488,6 +22454,18 @@ async function handleMcpOAuth(req, res, pathSegments, queryParams) {
21488
22454
  // src/http/mcp-servers.ts
21489
22455
  init_zod();
21490
22456
  init_db4();
22457
+
22458
+ // src/be/db-queries/mcp-servers.ts
22459
+ init_db4();
22460
+ async function countMcpServerInstalls() {
22461
+ const rows = await getDbClient2().query(`SELECT mcpServerId, COUNT(*) AS installs
22462
+ FROM agent_mcp_servers
22463
+ WHERE isActive = 1
22464
+ GROUP BY mcpServerId`, []);
22465
+ return new Map(rows.map((row) => [row.mcpServerId, row.installs]));
22466
+ }
22467
+
22468
+ // src/http/mcp-servers.ts
21491
22469
  init_mcp_server_checked_update();
21492
22470
  init_mcp_server_stdio_gate();
21493
22471
  init_rbac_audit();
@@ -21495,7 +22473,7 @@ init_rbac_roles();
21495
22473
  init_ensure_mcp_token();
21496
22474
  init_mcp_wrapper();
21497
22475
  init_rbac();
21498
- init_types4();
22476
+ init_types5();
21499
22477
  init_request_auth_context();
21500
22478
  init_request_principal();
21501
22479
  init_route_def();
@@ -21522,7 +22500,12 @@ var listMcpServersRoute = route({
21522
22500
  responses: {
21523
22501
  200: {
21524
22502
  description: "MCP server list",
21525
- schema: object2({ servers: array2(McpServerSchema), total: number2() })
22503
+ schema: object2({
22504
+ servers: array2(McpServerSchema.extend({
22505
+ installCount: number2().optional()
22506
+ })),
22507
+ total: number2()
22508
+ })
21526
22509
  }
21527
22510
  }
21528
22511
  });
@@ -21837,7 +22820,11 @@ async function handleMcpServers(req, res, pathSegments, queryParams) {
21837
22820
  isEnabled: parsed.query.enabled !== undefined ? parsed.query.enabled === "true" : undefined,
21838
22821
  search: parsed.query.search
21839
22822
  });
21840
- listMcpServersRoute.respond(res, 200, { servers, total: servers.length });
22823
+ const installs = await countMcpServerInstalls();
22824
+ listMcpServersRoute.respond(res, 200, {
22825
+ servers: servers.map((server) => ({ ...server, installCount: installs.get(server.id) ?? 0 })),
22826
+ total: servers.length
22827
+ });
21841
22828
  return true;
21842
22829
  }
21843
22830
  if (getMcpServerRoute.match(req.method, pathSegments)) {
@@ -21981,7 +22968,7 @@ init_send_task();
21981
22968
  init_steer_task();
21982
22969
  init_task_tool_ctx();
21983
22970
  init_utils();
21984
- init_types4();
22971
+ init_types5();
21985
22972
  init_steering_enabled();
21986
22973
  var userSendTaskInputSchema = object2({
21987
22974
  task: string2().min(1).describe("The task description to send."),
@@ -22473,7 +23460,7 @@ function truncateUtf8(query, maxBytes) {
22473
23460
 
22474
23461
  // src/http/memory.ts
22475
23462
  init_rbac();
22476
- init_types4();
23463
+ init_types5();
22477
23464
  init_request_auth_context();
22478
23465
  init_secret_scrubber();
22479
23466
  init_request_principal();
@@ -23721,7 +24708,7 @@ function stopMemoryGc() {
23721
24708
  init_zod();
23722
24709
  init_db4();
23723
24710
  init_version2();
23724
- init_types4();
24711
+ init_types5();
23725
24712
  init_db_query();
23726
24713
  init_route_def();
23727
24714
  init_utils2();
@@ -24183,7 +25170,7 @@ init_db4();
24183
25170
  init_model_profiles();
24184
25171
  init_model_validation2();
24185
25172
  init_rbac();
24186
- init_types4();
25173
+ init_types5();
24187
25174
  init_credentials2();
24188
25175
  init_request_principal();
24189
25176
  init_route_def();
@@ -24468,7 +25455,7 @@ init_model_catalog_store();
24468
25455
  init_model_tier_resolution();
24469
25456
  init_pricing_refresh();
24470
25457
  init_rbac();
24471
- init_types4();
25458
+ init_types5();
24472
25459
  init_request_auth_context();
24473
25460
  init_request_principal();
24474
25461
  init_route_def();
@@ -25333,7 +26320,7 @@ init_db4();
25333
26320
  init_memory();
25334
26321
  init_constants2();
25335
26322
  init_mcp_wrapper();
25336
- init_types4();
26323
+ init_types5();
25337
26324
  init_constants3();
25338
26325
  init_credentials2();
25339
26326
  init_egress_guard();
@@ -25369,7 +26356,8 @@ init_registry2();
25369
26356
  init_config4();
25370
26357
  init_connection_state();
25371
26358
  init_telemetry();
25372
- init_types4();
26359
+ init_types5();
26360
+ init_github_host();
25373
26361
  init_runtime_pools_flag();
25374
26362
  init_route_def();
25375
26363
  init_utils2();
@@ -25462,6 +26450,10 @@ var AutomationStatusSchema = object2({
25462
26450
  fixUrl: string2()
25463
26451
  });
25464
26452
  var StatusHealthSchema = _enum2(["ok", "degraded", "broken"]);
26453
+ var StatusGitHubSchema = object2({
26454
+ web_url: string2(),
26455
+ enterprise: boolean()
26456
+ });
25465
26457
  var StatusRuntimePoolsSchema = object2({ enabled: boolean(), supervisor: string2() });
25466
26458
  var StatusResponseSchema = object2({
25467
26459
  runtime_pools: StatusRuntimePoolsSchema,
@@ -25472,7 +26464,8 @@ var StatusResponseSchema = object2({
25472
26464
  automations: array2(AutomationStatusSchema),
25473
26465
  health: StatusHealthSchema,
25474
26466
  telemetry: StatusTelemetrySchema.optional(),
25475
- instance: StatusInstanceSchema.optional()
26467
+ instance: StatusInstanceSchema.optional(),
26468
+ github: StatusGitHubSchema.optional()
25476
26469
  });
25477
26470
  var TestConnectionRequestSchema = object2({
25478
26471
  provider: ProviderNameSchema
@@ -25626,8 +26619,6 @@ function slackMilestone(state) {
25626
26619
  hint = "Slack is explicitly disabled (SLACK_DISABLE=true).";
25627
26620
  } else if (!config.mode) {
25628
26621
  hint = "Invalid SLACK_MODE. Use socket or http.";
25629
- } else if (config.mode === "http" && config.missingCredentials.length === 0) {
25630
- hint = "HTTP credentials are configured, but HTTP ingress is unavailable until the receiver is installed.";
25631
26622
  } else {
25632
26623
  hint = `Set ${config.missingCredentials.join(" + ")} for Slack ${config.mode} mode.`;
25633
26624
  }
@@ -25639,7 +26630,7 @@ function slackMilestone(state) {
25639
26630
  action_url: automationIntegrationFixUrl("slack")
25640
26631
  };
25641
26632
  }
25642
- if (config.mode === "socket" && getSlackConnectionState() === "connected") {
26633
+ if (getSlackConnectionState() === "connected") {
25643
26634
  return {
25644
26635
  id: "slack",
25645
26636
  label: "Slack configured",
@@ -25651,7 +26642,7 @@ function slackMilestone(state) {
25651
26642
  id: "slack",
25652
26643
  label: "Slack configured",
25653
26644
  state: "configured",
25654
- hint: config.mode === "http" ? "HTTP credentials are configured, but HTTP ingress is unavailable until the receiver is installed." : "Socket Mode credentials are configured, but the bot is not connected to Slack.",
26645
+ hint: config.mode === "http" ? "HTTP credentials are configured, but the receiver is not ready (workspace not verified yet)." : "Socket Mode credentials are configured, but the bot is not connected to Slack.",
25655
26646
  action_url: automationIntegrationFixUrl("slack")
25656
26647
  };
25657
26648
  }
@@ -25840,9 +26831,16 @@ async function buildStatusPayload() {
25840
26831
  automations,
25841
26832
  health: computeHealth(setup, readyLeads),
25842
26833
  telemetry: { enabled: isTelemetryEnabled() },
25843
- instance
26834
+ instance,
26835
+ ...githubStatus()
25844
26836
  };
25845
26837
  }
26838
+ function githubStatus() {
26839
+ const host = resolveGitHubHost();
26840
+ if (!host.ok)
26841
+ return {};
26842
+ return { github: { web_url: host.config.webUrl, enterprise: host.config.enterprise } };
26843
+ }
25846
26844
  function getCombStatus(serviceUserId) {
25847
26845
  const comb = getCombConfig();
25848
26846
  return {
@@ -25874,7 +26872,7 @@ var getStatus = route({
25874
26872
  path: "/status",
25875
26873
  pattern: ["status"],
25876
26874
  summary: "Identity + setup readiness + live activity for the swarm dashboard",
25877
- description: "Single source of truth consumed by the UI home page. Identity comes from SWARM_* envs; setup milestones each emit `unverified | configured | verified`; automations report `running | needs_setup` from the same runtime preflight used at dispatch; activity counts agents alive in the last 5 min, leads that can take work (status idle or busy), and tasks created in the last 24h; agent_fs reports whether AGENT_FS_API_URL is set, plus the Comb settings (whether Files is on and, when off, what is missing; the browser-facing agent-fs URL, the shared org and drive ids, and the agent-fs user id of the swarm service account); telemetry reports the effective ANONYMIZED_TELEMETRY opt-out state.",
26875
+ description: "Single source of truth consumed by the UI home page. Identity comes from SWARM_* envs; setup milestones each emit `unverified | configured | verified`; automations report `running | needs_setup` from the same runtime preflight used at dispatch; activity counts agents alive in the last 5 min, leads that can take work (status idle or busy), and tasks created in the last 24h; agent_fs reports whether AGENT_FS_API_URL is set, plus the Comb settings (whether Files is on and, when off, what is missing; the browser-facing agent-fs URL, the shared org and drive ids, and the agent-fs user id of the swarm service account); telemetry reports the effective ANONYMIZED_TELEMETRY opt-out state; github reports the GitHub web base (GITHUB_URL) for PR and repo links.",
25878
26876
  tags: ["Status"],
25879
26877
  responses: {
25880
26878
  200: { description: "Status payload", schema: StatusResponseSchema },
@@ -26024,14 +27022,7 @@ async function buildSignals(state) {
26024
27022
  provider: embeddingsOn ? embeddingsProvider(process.env.EMBEDDING_API_BASE_URL) : null,
26025
27023
  localDefault: localDefault()
26026
27024
  },
26027
- integrations: {
26028
- slack: integrations.slack === "configured",
26029
- github: Boolean(process.env.GITHUB_TOKEN?.trim()) || integrations.github === "verified",
26030
- gitlab: Boolean(process.env.GITLAB_TOKEN?.trim()),
26031
- bitbucket: Boolean(process.env.BITBUCKET_TOKEN?.trim()),
26032
- linear: integrations.linear === "verified",
26033
- jira: integrations.jira === "verified"
26034
- },
27025
+ integrations: setupIntegrationFlags(integrations),
26035
27026
  agents: {
26036
27027
  leadsOnline: agentCounts.leads,
26037
27028
  workersOnline: agentCounts.workers
@@ -26495,7 +27486,7 @@ init_session_templates();
26495
27486
  init_sibling_awareness();
26496
27487
  init_page_fields();
26497
27488
  init_presets();
26498
- init_types4();
27489
+ init_types5();
26499
27490
  init_constants3();
26500
27491
  init_page_session();
26501
27492
  init_request_auth_context();
@@ -26517,12 +27508,12 @@ init_task_citations2();
26517
27508
  init_users();
26518
27509
  init_rbac();
26519
27510
  init_context_key();
26520
- init_errors2();
27511
+ init_errors();
26521
27512
  init_sibling_awareness();
26522
27513
  init_task_skip();
26523
27514
  init_terminal_result_guard();
26524
27515
  init_worker_follow_up();
26525
- init_types4();
27516
+ init_types5();
26526
27517
  init_business_use();
26527
27518
  init_request_auth_context();
26528
27519
  init_secret_scrubber();
@@ -26570,7 +27561,7 @@ init_request_principal();
26570
27561
  init_zod();
26571
27562
  init_db4();
26572
27563
  init_identity();
26573
- init_types4();
27564
+ init_types5();
26574
27565
  init_requester_comms();
26575
27566
  var TaskRequestedBySchema = UserSchema.pick({
26576
27567
  id: true,
@@ -26669,6 +27660,7 @@ async function buildTaskThreadParticipants(task) {
26669
27660
  // src/http/tasks.ts
26670
27661
  init_route_def();
26671
27662
  init_session_access();
27663
+ init_task_requester();
26672
27664
  init_utils2();
26673
27665
  var AgentTaskSummarySchema = AgentTaskSchema.pick({
26674
27666
  id: true,
@@ -27260,6 +28252,30 @@ var updateTaskTitleRoute = route({
27260
28252
  auth: { apiKey: true },
27261
28253
  rbac: { permission: "task.action.own" }
27262
28254
  });
28255
+ var TaskTagListSchema = array2(string2().regex(/^ui:[a-z0-9][a-z0-9-]{0,60}$/, "Only ui: presentation tags can be changed here")).max(20);
28256
+ var updateTaskTagsRoute = route({
28257
+ method: "patch",
28258
+ path: "/api/tasks/{id}/tags",
28259
+ pattern: ["api", "tasks", null, "tags"],
28260
+ session: { taskParam: "id" },
28261
+ summary: "Add or remove task tags",
28262
+ description: "Adds the `add` tags and removes the `remove` tags. A tag in both lists is removed. Only `ui:` presentation tags are accepted (400 otherwise); tags that drive behaviour are server-owned. The dashboard uses `ui:dismissed` to hide a failed task from Home's Needs you. Does not change `lastUpdatedAt`.",
28263
+ tags: ["Tasks"],
28264
+ params: object2({ id: string2() }),
28265
+ body: object2({
28266
+ add: TaskTagListSchema.optional(),
28267
+ remove: TaskTagListSchema.optional()
28268
+ }).refine((body) => (body.add?.length ?? 0) + (body.remove?.length ?? 0) > 0, {
28269
+ message: "Give at least one tag to add or remove"
28270
+ }),
28271
+ responses: {
28272
+ 200: { description: "Tags updated", schema: object2({ task: AgentTaskSchema }) },
28273
+ 403: { description: "Task belongs to another user" },
28274
+ 404: { description: "Task not found" }
28275
+ },
28276
+ auth: { apiKey: true },
28277
+ rbac: { permission: "task.action.own" }
28278
+ });
27263
28279
  async function canSteerTask(req, myAgentId, task, sessionAccess = "none") {
27264
28280
  const userId = authUserId(getRequestAuth(req));
27265
28281
  const resource = {
@@ -27319,20 +28335,6 @@ async function deniesForeignContext(req, contextKey) {
27319
28335
  }
27320
28336
  return false;
27321
28337
  }
27322
- async function resolveTaskRequester(req, myAgentId, bodyUserId, trustedUserId) {
27323
- const trusted = trustedUserId === undefined ? await resolveHttpAuditUserId(req, myAgentId) : trustedUserId;
27324
- if (trusted)
27325
- return trusted;
27326
- if (process.env.TRUST_BODY_REQUESTED_BY_USER_ID === "false" || !bodyUserId)
27327
- return;
27328
- const mayAssign = can({
27329
- principal: await resolveTaskWritePrincipal(req, myAgentId),
27330
- verb: "task.requester.assign",
27331
- resource: { kind: "none" },
27332
- source: "http"
27333
- }).allow;
27334
- return mayAssign ? (await findUserById(bodyUserId))?.id : undefined;
27335
- }
27336
28338
  async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
27337
28339
  if (pathSegments[0] === "api" && pathSegments[1] === "tasks" && rejectGuest(req, res)) {
27338
28340
  return true;
@@ -28177,6 +29179,27 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
28177
29179
  updateTaskTitleRoute.respond(res, 200, { task });
28178
29180
  return true;
28179
29181
  }
29182
+ if (updateTaskTagsRoute.match(req.method, pathSegments)) {
29183
+ const parsed = await updateTaskTagsRoute.parse(req, res, pathSegments, queryParams);
29184
+ if (!parsed)
29185
+ return true;
29186
+ const existing = await getTaskById2(parsed.params.id);
29187
+ if (!existing) {
29188
+ jsonError(res, "Task not found", 404);
29189
+ return true;
29190
+ }
29191
+ if (await deniesNonOwnerTaskWrite2(req, existing)) {
29192
+ jsonError(res, NOT_YOUR_TASK_DENIED2, 403);
29193
+ return true;
29194
+ }
29195
+ const task = await updateTaskTags2(parsed.params.id, parsed.body);
29196
+ if (!task) {
29197
+ jsonError(res, "Task not found", 404);
29198
+ return true;
29199
+ }
29200
+ updateTaskTagsRoute.respond(res, 200, { task });
29201
+ return true;
29202
+ }
28180
29203
  if (resumeTaskRoute.match(req.method, pathSegments)) {
28181
29204
  const parsed = await resumeTaskRoute.parse(req, res, pathSegments, queryParams);
28182
29205
  if (!parsed)
@@ -31200,7 +32223,7 @@ ${PAGE_DESIGN_CSS}
31200
32223
  }
31201
32224
 
31202
32225
  // src/http/pages-public.ts
31203
- init_types4();
32226
+ init_types5();
31204
32227
  init_constants3();
31205
32228
  init_page_session();
31206
32229
  init_secret_scrubber();
@@ -31732,11 +32755,12 @@ async function fetchAllBotChannels(client) {
31732
32755
  // src/http/poll.ts
31733
32756
  init_model_pin();
31734
32757
  init_telemetry_trigger();
31735
- init_types4();
32758
+ init_types5();
31736
32759
  init_business_use();
31737
32760
  init_multi_runtime2();
31738
32761
  init_request_auth_context();
31739
32762
  init_runtime_pools_flag();
32763
+ init_secret_scrubber();
31740
32764
  init_route_def();
31741
32765
  init_utils2();
31742
32766
  function buildBudgetRefusedTrigger(refusal) {
@@ -31781,6 +32805,12 @@ var PollTaskAssignedTriggerSchema = object2({
31781
32805
  credentialAllowlist: ModelProfileCredentialsSchema.optional()
31782
32806
  }),
31783
32807
  requestedBy: TaskRequestedBySchema.optional(),
32808
+ checklistNudge: object2({
32809
+ itemId: string2(),
32810
+ kind: string2(),
32811
+ label: string2(),
32812
+ href: string2().optional()
32813
+ }).optional(),
31784
32814
  threadParticipants: TaskThreadParticipantsSchema.optional()
31785
32815
  });
31786
32816
  var PollUnreadMentionsTriggerSchema = object2({
@@ -31837,6 +32867,31 @@ async function attachmentsForTrigger(taskId) {
31837
32867
  sizeBytes: a.sizeBytes
31838
32868
  }));
31839
32869
  }
32870
+ async function buildChecklistNudge(task, agent) {
32871
+ const userId = task.requestedByUserId;
32872
+ if (!agent.isLead || !userId || !["ui", "slack", "chat", "comb"].includes(task.source ?? "")) {
32873
+ return;
32874
+ }
32875
+ try {
32876
+ return await getDbClient2().transaction(async () => {
32877
+ const canEditSwarm = await userGrantCanEditSwarm(userId) ?? true;
32878
+ const item = await firstOpenItem(userId, canEditSwarm);
32879
+ if (!item)
32880
+ return;
32881
+ await markNudged(item.id, task.id, userId);
32882
+ const appUrl = await resolveAppUrl();
32883
+ return {
32884
+ itemId: item.id,
32885
+ kind: item.kind,
32886
+ label: item.label,
32887
+ ...appUrl && { href: `${appUrl}${item.href ?? "/"}` }
32888
+ };
32889
+ });
32890
+ } catch (error) {
32891
+ console.warn("[/api/poll] Checklist nudge failed:", scrubSecrets(error instanceof Error ? error.message : String(error)));
32892
+ return;
32893
+ }
32894
+ }
31840
32895
  async function claimModelFields(task, agent, auth) {
31841
32896
  const pin = taskModelPin(task);
31842
32897
  const cleared = {
@@ -32024,6 +33079,7 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
32024
33079
  });
32025
33080
  });
32026
33081
  const assignedRequestedBy = await buildTaskRequestedBy(pendingTask);
33082
+ const nudge = await buildChecklistNudge(pendingTask, agent);
32027
33083
  const assignedThread = await buildTaskThreadParticipants(pendingTask);
32028
33084
  const assignedTriggerSurface = await resolveTriggerSurface(pendingTask.id, pendingTask.source);
32029
33085
  return {
@@ -32038,6 +33094,7 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
32038
33094
  attachments: await attachmentsForTrigger(pendingTask.id)
32039
33095
  },
32040
33096
  ...assignedRequestedBy && { requestedBy: assignedRequestedBy },
33097
+ ...nudge && { checklistNudge: nudge },
32041
33098
  ...assignedThread && { threadParticipants: assignedThread }
32042
33099
  }
32043
33100
  };
@@ -32515,7 +33572,7 @@ async function handlePoolKeys(req, res, pathSegments, queryParams) {
32515
33572
  // src/http/pricing.ts
32516
33573
  init_zod();
32517
33574
  init_db4();
32518
- init_types4();
33575
+ init_types5();
32519
33576
  init_secret_scrubber();
32520
33577
  init_route_def();
32521
33578
  init_utils2();
@@ -32696,7 +33753,7 @@ init_db4();
32696
33753
  init_default_drift();
32697
33754
  init_registry3();
32698
33755
  init_resolver();
32699
- init_types4();
33756
+ init_types5();
32700
33757
  init_template2();
32701
33758
  init_route_def();
32702
33759
  init_utils2();
@@ -33195,7 +34252,7 @@ init_repo_checked_update();
33195
34252
  init_repo_merge_policy();
33196
34253
  init_rbac();
33197
34254
  init_telemetry();
33198
- init_types4();
34255
+ init_types5();
33199
34256
  init_request_principal();
33200
34257
  init_route_def();
33201
34258
  init_utils2();
@@ -33413,7 +34470,7 @@ init_zod();
33413
34470
  init_auth2();
33414
34471
  init_document();
33415
34472
  init_rooms();
33416
- init_types4();
34473
+ init_types5();
33417
34474
  init_request_auth_context();
33418
34475
  init_request_principal();
33419
34476
  init_route_def();
@@ -33689,7 +34746,7 @@ init_multi_runtime();
33689
34746
  init_db2();
33690
34747
  init_tokens();
33691
34748
  init_rbac();
33692
- init_types4();
34749
+ init_types5();
33693
34750
  init_runtime_pools_flag();
33694
34751
  init_secret_scrubber();
33695
34752
  init_request_principal();
@@ -34300,8 +35357,8 @@ async function readWorkflowSavings(opts) {
34300
35357
  const client = getDbClient2();
34301
35358
  const { firstDay, lastDay, ...window } = savingsWindow(opts.days, opts.now);
34302
35359
  const calendarDays = daysBetween(firstDay, lastDay);
34303
- const marker = await client.get("SELECT count(*) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='workflow' AND modelVersion=? AND day>=? AND day<=?", [MODEL_VERSION, firstDay, lastDay]);
34304
- const complete = Number(marker?.n) >= calendarDays.length;
35360
+ const marker = await client.get("SELECT count(CASE WHEN day<? THEN 1 END) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='workflow' AND modelVersion=? AND day>=? AND day<=?", [lastDay, MODEL_VERSION, firstDay, lastDay]);
35361
+ const complete = Number(marker?.n) >= calendarDays.length - 1;
34305
35362
  const markerAt = marker?.at ?? null;
34306
35363
  const scope = {
34307
35364
  days: opts.days,
@@ -34543,10 +35600,10 @@ async function readScriptSavings(opts) {
34543
35600
  const { firstDay, lastDay, ...window } = savingsWindow(opts.days, opts.now);
34544
35601
  const calendarDays = daysBetween(firstDay, lastDay);
34545
35602
  const [marker, scheduledRows] = await Promise.all([
34546
- client.get("SELECT count(*) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='script' AND modelVersion=? AND day>=? AND day<=?", [MODEL_VERSION, firstDay, lastDay]),
35603
+ client.get("SELECT count(CASE WHEN day<? THEN 1 END) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='script' AND modelVersion=? AND day>=? AND day<=?", [lastDay, MODEL_VERSION, firstDay, lastDay]),
34547
35604
  client.query("SELECT DISTINCT scriptName FROM scheduled_tasks WHERE targetType='script' AND scriptName IS NOT NULL ORDER BY scriptName")
34548
35605
  ]);
34549
- const complete = Number(marker?.n) >= calendarDays.length;
35606
+ const complete = Number(marker?.n) >= calendarDays.length - 1;
34550
35607
  const scheduled = scheduledRows.map((r) => r.scriptName);
34551
35608
  const scope = {
34552
35609
  days: opts.days,
@@ -35962,12 +37019,12 @@ init_validate();
35962
37019
  init_db3();
35963
37020
  init_rbac();
35964
37021
  init_scheduler();
35965
- init_types4();
37022
+ init_types5();
35966
37023
  init_favorite_owner();
35967
37024
  init_request_principal();
35968
37025
  init_route_def();
35969
37026
  init_utils2();
35970
- var import_cron_parser = __toESM(require_dist2(), 1);
37027
+ var import_cron_parser = __toESM(require_dist(), 1);
35971
37028
  var scheduleUpdateBodySchema = object2({
35972
37029
  key: AssetKeySchema.optional(),
35973
37030
  name: string2().optional(),
@@ -37003,7 +38060,8 @@ var oauthPresetSchema = object2({
37003
38060
  tokenBodyFormat: _enum2(["form", "json"]).optional(),
37004
38061
  requiresRefreshTokenRotation: boolean().optional(),
37005
38062
  extraParams: record2(string2(), string2()).optional(),
37006
- setupHints: array2(string2())
38063
+ setupHints: array2(string2()),
38064
+ hiddenInCatalog: boolean().optional()
37007
38065
  });
37008
38066
  var sanitizedAuthorizationSchema = object2({
37009
38067
  id: string2(),
@@ -38748,7 +39806,7 @@ function lintWorkflowLabels(source) {
38748
39806
 
38749
39807
  // src/http/script-runs.ts
38750
39808
  init_follow_up_redelegation_guard();
38751
- init_types4();
39809
+ init_types5();
38752
39810
  init_constants3();
38753
39811
  init_secret_scrubber();
38754
39812
  init_raw_llm();
@@ -39440,7 +40498,7 @@ init_rbac();
39440
40498
  init_registry();
39441
40499
  init_extract_signature();
39442
40500
  init_quickjs_compat();
39443
- init_types4();
40501
+ init_types5();
39444
40502
  init_request_auth_context();
39445
40503
  init_secret_scrubber();
39446
40504
  init_route_def();
@@ -40357,7 +41415,7 @@ async function handleScripts(req, res, pathSegments, queryParams, agentId) {
40357
41415
  init_zod();
40358
41416
  init_db4();
40359
41417
  init_otel();
40360
- init_types4();
41418
+ init_types5();
40361
41419
  init_route_def();
40362
41420
  init_session_access();
40363
41421
 
@@ -40996,9 +42054,10 @@ function warmSlackChannelLabels(groupKeys) {
40996
42054
  }
40997
42055
 
40998
42056
  // src/http/sessions.ts
40999
- init_types4();
42057
+ init_types5();
41000
42058
  init_request_auth_context();
41001
42059
  init_runtime_pools_flag();
42060
+ init_favorite_owner();
41002
42061
  init_request_principal();
41003
42062
  init_route_def();
41004
42063
  init_session_access();
@@ -41862,6 +42921,11 @@ async function handleSessions(req, res, pathSegments, queryParams, myAgentId) {
41862
42921
  break;
41863
42922
  }
41864
42923
  const moved = await moveSessionChains({ moves, changedBy });
42924
+ if (key !== null && skipped.length === 0 && remaining === 0 && (await listPrefixRoots({ from, limit: 1 })).length === 0) {
42925
+ const scope = moved.length > 0 ? undefined : (await resolveHttpFavoriteOwner(req, myAgentId))?.scope;
42926
+ if (moved.length > 0 || scope)
42927
+ await moveKeyFavorites({ from, to: key, scope });
42928
+ }
41865
42929
  moveSessionPrefix.respond(res, 200, { moved, skipped, remaining });
41866
42930
  });
41867
42931
  return true;
@@ -42258,7 +43322,7 @@ async function getSkillUsageDetail(skillId, window, tzOffsetMinutes = 0, now = D
42258
43322
  }
42259
43323
 
42260
43324
  // src/http/skills.ts
42261
- init_types4();
43325
+ init_types5();
42262
43326
  init_route_def();
42263
43327
  init_utils2();
42264
43328
  var SYSTEM_DEFAULT_SKILL_LOCKED_MESSAGE = "This skill is system-managed and cannot be edited from the UI; it is re-seeded on each start. Fork it under a new name to customize.";
@@ -43164,6 +44228,92 @@ async function handleSkills(req, res, pathSegments, queryParams, myAgentId) {
43164
44228
  return false;
43165
44229
  }
43166
44230
 
44231
+ // src/http/slack-events.ts
44232
+ init_app3();
44233
+ init_config4();
44234
+ init_route_def();
44235
+ init_utils2();
44236
+ var slackEventsRoute = route({
44237
+ method: "post",
44238
+ path: "/api/integrations/slack/events",
44239
+ pattern: ["api", "integrations", "slack", "events"],
44240
+ summary: "Slack HTTP ingress (SLACK_MODE=http): Events API, slash commands and interactivity at one request URL",
44241
+ tags: ["Slack"],
44242
+ auth: { apiKey: false },
44243
+ rbac: {
44244
+ ungated: "Slack-signed request: HMAC v0 verified with SLACK_SIGNING_SECRET, with a 5-minute timestamp window, before any work"
44245
+ },
44246
+ responses: {
44247
+ 200: {
44248
+ description: "Accepted",
44249
+ unstructured: "Slack ack payload: empty, the url_verification challenge, or a command/interactivity response body"
44250
+ },
44251
+ 400: { description: "Malformed body after a valid signature" },
44252
+ 401: { description: "Missing or invalid signature, or timestamp outside the 5-minute window" },
44253
+ 403: { description: "Delivery for a workspace this swarm does not own" },
44254
+ 404: { description: "Slack is disabled or not in HTTP mode" },
44255
+ 413: { description: "Body exceeds 1 MiB" },
44256
+ 503: {
44257
+ description: "Receiver not ready, workspace unverified, or backlog full; Slack retries"
44258
+ }
44259
+ }
44260
+ });
44261
+ var SLACK_EVENTS_MAX_BODY_BYTES = 1024 * 1024;
44262
+ function header2(req, name) {
44263
+ const value = req.headers[name];
44264
+ return Array.isArray(value) ? value[0] : value;
44265
+ }
44266
+ async function handleSlackEvents(req, res, pathSegments) {
44267
+ if (!slackEventsRoute.match(req.method, pathSegments))
44268
+ return false;
44269
+ const config = getSlackConfiguration();
44270
+ if (config.disabled || config.mode !== "http" || config.missingCredentials.length > 0) {
44271
+ jsonError(res, "Slack HTTP mode is not enabled", 404);
44272
+ return true;
44273
+ }
44274
+ const receiver = getSlackHttpReceiver2();
44275
+ if (!receiver) {
44276
+ res.writeHead(503, { "Content-Type": "application/json", "Retry-After": "5" });
44277
+ res.end(JSON.stringify({ error: "Slack receiver is not ready" }));
44278
+ return true;
44279
+ }
44280
+ if (enforceContentLengthCap(req, res, SLACK_EVENTS_MAX_BODY_BYTES) === BODY_TOO_LARGE) {
44281
+ return true;
44282
+ }
44283
+ const chunks = [];
44284
+ let receivedBytes = 0;
44285
+ let tooLarge = false;
44286
+ for await (const chunk of req) {
44287
+ if (tooLarge)
44288
+ continue;
44289
+ receivedBytes += chunk.byteLength;
44290
+ if (receivedBytes > SLACK_EVENTS_MAX_BODY_BYTES) {
44291
+ tooLarge = true;
44292
+ chunks.length = 0;
44293
+ jsonError(res, `Payload too large (max ${SLACK_EVENTS_MAX_BODY_BYTES} bytes)`, 413);
44294
+ continue;
44295
+ }
44296
+ chunks.push(chunk);
44297
+ }
44298
+ if (tooLarge)
44299
+ return true;
44300
+ const result = await receiver.handle({
44301
+ rawBody: Buffer.concat(chunks),
44302
+ signature: header2(req, "x-slack-signature"),
44303
+ timestamp: header2(req, "x-slack-request-timestamp"),
44304
+ contentType: header2(req, "content-type"),
44305
+ retryNum: header2(req, "x-slack-retry-num"),
44306
+ retryReason: header2(req, "x-slack-retry-reason"),
44307
+ signingSecret: process.env.SLACK_SIGNING_SECRET
44308
+ });
44309
+ res.writeHead(result.status, {
44310
+ ...result.contentType ? { "Content-Type": result.contentType } : {},
44311
+ ...result.headers
44312
+ });
44313
+ res.end(result.body);
44314
+ return true;
44315
+ }
44316
+
43167
44317
  // src/http/slack-inbound.ts
43168
44318
  init_zod();
43169
44319
  init_inbound_dispatch();
@@ -43249,7 +44399,7 @@ async function handleSlackInbound(req, res, pathSegments) {
43249
44399
  init_zod();
43250
44400
  init_db4();
43251
44401
  init_steering2();
43252
- init_types4();
44402
+ init_types5();
43253
44403
  init_env_flag();
43254
44404
  init_multi_runtime2();
43255
44405
  init_favorite_owner();
@@ -43492,7 +44642,7 @@ async function handleStats(req, res, pathSegments, queryParams, myAgentId) {
43492
44642
  // src/http/task-templates.ts
43493
44643
  init_zod();
43494
44644
  init_db4();
43495
- init_types4();
44645
+ init_types5();
43496
44646
  init_route_def();
43497
44647
  var listTemplates = route({
43498
44648
  method: "get",
@@ -44443,7 +45593,7 @@ init_db4();
44443
45593
  init_rbac_roles();
44444
45594
  init_users();
44445
45595
  init_rbac();
44446
- init_types4();
45596
+ init_types5();
44447
45597
 
44448
45598
  // src/http/operator-actor.ts
44449
45599
  init_users();
@@ -44624,10 +45774,11 @@ init_db4();
44624
45774
  init_rbac_roles();
44625
45775
  init_users();
44626
45776
  init_rbac();
44627
- init_types4();
45777
+ init_types5();
44628
45778
  init_constants3();
44629
45779
  init_egress_guard();
44630
45780
  init_request_auth_context();
45781
+ init_secret_scrubber();
44631
45782
  init_route_def();
44632
45783
  init_session_access();
44633
45784
  init_utils2();
@@ -45604,6 +46755,13 @@ async function handleUsers(req, res, pathSegments, queryParams) {
45604
46755
  jsonError(res, "code_invalid", 404);
45605
46756
  return true;
45606
46757
  }
46758
+ getDbClient2().afterCommit(async () => {
46759
+ try {
46760
+ await ensureUserAgentFsAccount(result.userId);
46761
+ } catch (error) {
46762
+ console.warn(scrubSecrets(`[agent-fs] invite account ensure failed: ${error instanceof Error ? error.message : String(error)}`));
46763
+ }
46764
+ });
45607
46765
  exchangeInviteCodeRoute.respond(res, 200, result);
45608
46766
  } catch {
45609
46767
  jsonError(res, "Failed to exchange code", 500);
@@ -46083,8 +47241,9 @@ async function routeKapsoInbound(payload) {
46083
47241
  }
46084
47242
 
46085
47243
  // src/http/webhooks.ts
46086
- init_errors2();
47244
+ init_errors();
46087
47245
  init_constants3();
47246
+ init_github_host();
46088
47247
  init_secret_scrubber();
46089
47248
  init_azure_devops();
46090
47249
  init_workflows();
@@ -46357,6 +47516,11 @@ async function handleWebhooks(req, res, pathSegments) {
46357
47516
  res.end(JSON.stringify({ error: "Invalid signature" }));
46358
47517
  return true;
46359
47518
  }
47519
+ const enterpriseHost = req.headers["x-github-enterprise-host"];
47520
+ const configuredHost = resolveGitHubHost();
47521
+ if (enterpriseHost && configuredHost.ok && enterpriseHost.toLowerCase() !== configuredHost.config.host) {
47522
+ console.warn(`[GitHub] Webhook from GHES host ${enterpriseHost}, but GITHUB_URL resolves to ${configuredHost.config.host}`);
47523
+ }
46360
47524
  if (eventType === "ping") {
46361
47525
  console.log("[GitHub] Received ping event - webhook configured successfully");
46362
47526
  githubWebhook.respond(res, 200, { message: "pong" });
@@ -47047,7 +48211,7 @@ init_audit_user();
47047
48211
  init_db4();
47048
48212
  init_workflow_idempotency();
47049
48213
  init_workflow_runs();
47050
- init_types4();
48214
+ init_types5();
47051
48215
  init_workflows();
47052
48216
  init_definition2();
47053
48217
  init_engine();
@@ -48344,6 +49508,7 @@ var httpServer = createHttpServer(async (req, res) => {
48344
49508
  () => handleRealtimeTicket(req, res, pathSegments, queryParams),
48345
49509
  () => handleRealtimeAsset(req, res),
48346
49510
  () => handleIntegrations(req, res, pathSegments, queryParams),
49511
+ () => handleSlackEvents(req, res, pathSegments),
48347
49512
  () => handleSlackInbound(req, res, pathSegments),
48348
49513
  () => handlePromptTemplates(req, res, pathSegments, queryParams),
48349
49514
  () => handleDbQuery(req, res, pathSegments, queryParams),
@@ -48373,6 +49538,7 @@ var httpServer = createHttpServer(async (req, res) => {
48373
49538
  () => handleEvents(req, res, pathSegments, queryParams, myAgentId),
48374
49539
  () => handleRuntimePools(req, res, pathSegments, queryParams, myAgentId),
48375
49540
  () => handleExtensions(req, res, pathSegments, queryParams, myAgentId),
49541
+ () => handleChecklist(req, res, pathSegments, queryParams, myAgentId),
48376
49542
  () => handleFavorites(req, res, pathSegments, queryParams, myAgentId),
48377
49543
  () => handleUserRoles(req, res, pathSegments, queryParams),
48378
49544
  () => handleUsers(req, res, pathSegments, queryParams),
@@ -48411,7 +49577,7 @@ var httpServer = createHttpServer(async (req, res) => {
48411
49577
  });
48412
49578
  });
48413
49579
  var detachRealtime = attachRealtimeTransport(httpServer);
48414
- var { attachControllerTransport } = await import("./controllers-connect-63j5rdcm.js");
49580
+ var { attachControllerTransport } = await import("./controllers-connect-61re6k1n.js");
48415
49581
  var detachControllers = attachControllerTransport(httpServer);
48416
49582
  var stopWorkerNudges = startWorkerNudgeListener();
48417
49583
  var taskAutoTitles = startTaskAutoTitleListener();
@@ -48442,7 +49608,7 @@ async function shutdown() {
48442
49608
  sessionsProcessed: getServerSessionsProcessed()
48443
49609
  });
48444
49610
  if (hasCapability("scheduling")) {
48445
- const { stopScheduler } = await import("./index-8w2aznds.js");
49611
+ const { stopScheduler } = await import("./index-wjd56k1v.js");
48446
49612
  stopScheduler();
48447
49613
  }
48448
49614
  stopHeartbeat2();
@@ -48454,7 +49620,7 @@ async function shutdown() {
48454
49620
  await stopSlackApp2();
48455
49621
  await stopChatSdk();
48456
49622
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
48457
- const { stopOAuthKeepalive } = await import("./keepalive-k2a3qe73.js");
49623
+ const { stopOAuthKeepalive } = await import("./keepalive-rk0j0jvh.js");
48458
49624
  await stopOAuthKeepalive();
48459
49625
  }
48460
49626
  stopOAuthPendingGc();
@@ -48539,21 +49705,21 @@ try {
48539
49705
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
48540
49706
  }
48541
49707
  try {
48542
- const { ensurePricingSeeded } = await import("./boot-seeds-n2b3dx4e.js");
49708
+ const { ensurePricingSeeded } = await import("./boot-seeds-f99fjs5q.js");
48543
49709
  ensurePricingSeeded();
48544
- const { startPricingRefreshLoop } = await import("./pricing-refresh-1nj722h6.js");
49710
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-f5tkgmw2.js");
48545
49711
  startPricingRefreshLoop();
48546
49712
  } catch (err) {
48547
49713
  console.error("[startup] Failed to seed pricing rows:", err);
48548
49714
  }
48549
49715
  try {
48550
- const { ensureModelProfilesSeeded } = await import("./boot-seeds-n2b3dx4e.js");
49716
+ const { ensureModelProfilesSeeded } = await import("./boot-seeds-f99fjs5q.js");
48551
49717
  await ensureModelProfilesSeeded();
48552
49718
  } catch (err) {
48553
49719
  console.error("[startup] Failed to seed model profiles:", err);
48554
49720
  }
48555
49721
  try {
48556
- const { ensureRbacSeeded } = await import("./boot-seeds-n2b3dx4e.js");
49722
+ const { ensureRbacSeeded } = await import("./boot-seeds-f99fjs5q.js");
48557
49723
  ensureRbacSeeded();
48558
49724
  } catch (err) {
48559
49725
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -48561,11 +49727,17 @@ try {
48561
49727
  throw err;
48562
49728
  }
48563
49729
  try {
48564
- const { runAllSeeders } = await import("./index-3yvzbhxd.js");
49730
+ const { runAllSeeders } = await import("./index-ftywhyr0.js");
48565
49731
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
48566
49732
  } catch (err) {
48567
49733
  console.error("[startup] Failed to seed built-in entities:", err);
48568
49734
  }
49735
+ try {
49736
+ const { runImports } = await import("./index-tx9mc2ap.js");
49737
+ await runImports();
49738
+ } catch (err) {
49739
+ console.error("[startup] File import failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
49740
+ }
48569
49741
  try {
48570
49742
  await loadEnabledExtensions();
48571
49743
  } catch (err) {
@@ -48612,6 +49784,9 @@ httpServer.listen(port, async () => {
48612
49784
  startChatSdk().catch((err) => {
48613
49785
  console.error("[chat-sdk] Failed to start, continuing without Chat SDK:", scrubSecrets(err instanceof Error ? err.message : String(err)));
48614
49786
  });
49787
+ import("./agent-fs-provision-dmhnc38q.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
49788
+ console.warn("[agent-fs] Failed to set the org swarm URL:", scrubSecrets(err instanceof Error ? err.message : String(err)));
49789
+ });
48615
49790
  startQueueStallAlarm();
48616
49791
  initGitHub();
48617
49792
  initGitLab();
@@ -48624,25 +49799,25 @@ httpServer.listen(port, async () => {
48624
49799
  await initWorkflows2();
48625
49800
  await startScriptRunSupervisor(getMcpBaseUrl());
48626
49801
  if (hasCapability("scheduling")) {
48627
- const { startScheduler } = await import("./index-8w2aznds.js");
48628
- const { getExecutorRegistry } = await import("./index-qnjvr362.js");
49802
+ const { startScheduler } = await import("./index-wjd56k1v.js");
49803
+ const { getExecutorRegistry } = await import("./index-9sy2bh6n.js");
48629
49804
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
48630
49805
  startScheduler(getExecutorRegistry(), intervalMs, {
48631
49806
  runId: globalState.__runId
48632
49807
  });
48633
49808
  }
48634
49809
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
48635
- const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-yzxd3sn9.js");
49810
+ const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-8xcyd3mc.js");
48636
49811
  startHeartbeat(parseHeartbeatIntervalMs(process.env.HEARTBEAT_INTERVAL_MS));
48637
49812
  }
48638
49813
  startPoolRouting();
48639
49814
  startRuntimeSupervisor();
48640
49815
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
48641
- const { startOAuthKeepalive } = await import("./keepalive-k2a3qe73.js");
49816
+ const { startOAuthKeepalive } = await import("./keepalive-rk0j0jvh.js");
48642
49817
  startOAuthKeepalive();
48643
49818
  }
48644
49819
  if (!isEnvFlagEnabled("OAUTH_REFRESH_SWEEP_DISABLE", false)) {
48645
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-y7rm6bkb.js");
49820
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-2k3g2q4w.js");
48646
49821
  startOAuthRefreshSweep();
48647
49822
  }
48648
49823
  startOAuthPendingGc();
@@ -48652,19 +49827,19 @@ httpServer.listen(port, async () => {
48652
49827
  startSavingsRollup(savingsRollupSql);
48653
49828
  startHumanFreeDrain();
48654
49829
  startTaskSearchBackfill();
48655
- import("./embedding-space-wh8de1t9.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
49830
+ import("./embedding-space-bafjr5f7.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
48656
49831
  setDeploymentEnvReader(getDeploymentEnvValue);
48657
49832
  return runEmbeddingMaintenance({ backfill: true });
48658
49833
  }).catch((err) => {
48659
49834
  console.error("[embedding-space] startup maintenance failed (non-fatal):", err);
48660
49835
  });
48661
- import("./boot-args-schema-4vb0xsat.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
49836
+ import("./boot-args-schema-0gqmkfbe.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
48662
49837
  console.error("[boot-args-schema] startup backfill failed (non-fatal):", err);
48663
49838
  });
48664
- import("./boot-scrub-sweep-yrytg42z.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
49839
+ import("./boot-scrub-sweep-ejd5dnrz.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
48665
49840
  console.error("[boot-scrub-sweep] startup scrub failed (non-fatal):", err);
48666
49841
  });
48667
- import("./session-source-backfill-gxxwfh12.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
49842
+ import("./session-source-backfill-bd7spzjd.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
48668
49843
  console.error("[session-source-backfill] startup run failed (non-fatal):", err);
48669
49844
  });
48670
49845
  }).on("error", (err) => {