@desplega.ai/agent-swarm 2.9.1 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (502) hide show
  1. package/dist/acp-adapter-weaaxey3.js +16 -0
  2. package/dist/{acp-targets-ny75x1qy.js → acp-targets-5wyy2b9m.js} +9 -9
  3. package/dist/{actions-b9qgrmeq.js → actions-4nxq386s.js} +54 -32
  4. package/dist/{agent-fs-provision-b5dhdsbd.js → agent-fs-provision-v6enh76w.js} +4 -4
  5. package/dist/{amp-adapter-vtax2c9s.js → amp-adapter-ze3x22qn.js} +3 -3
  6. package/dist/{anthropic-messages-r5xf5hqw.js → anthropic-messages-88b7s3n9.js} +189 -37
  7. package/dist/{app-g2z15hax.js → app-kyqt8ehw.js} +7 -6
  8. package/dist/{approval-notifications-yt13wp8r.js → approval-notifications-a0db0esw.js} +7 -6
  9. package/dist/{assistant-2cgfxsgk.js → assistant-9g5jzq25.js} +26 -25
  10. package/dist/{azure-openai-responses-590s1eea.js → azure-openai-responses-jeaas6x0.js} +18 -18
  11. package/dist/{boot-args-schema-3gwy0f60.js → boot-args-schema-d7fme4q1.js} +1 -1
  12. package/dist/{boot-reembed-92g7s5zp.js → boot-reembed-6wpazmpw.js} +1 -1
  13. package/dist/{boot-reembed-mywmyp4s.js → boot-reembed-jrwxeye2.js} +1 -1
  14. package/dist/boot-scrub-sweep-52h7yntp.js +9 -0
  15. package/dist/{boot-seeds-ce7rvgq1.js → boot-seeds-kb3dxjex.js} +4 -4
  16. package/dist/{boxd-wn235q80.js → boxd-jrrmkv3w.js} +2 -2
  17. package/dist/{claude-adapter-3m4q7735.js → claude-adapter-0c0y8fqp.js} +8 -8
  18. package/dist/{claude-managed-adapter-t8nfgcgz.js → claude-managed-adapter-w2es07qq.js} +4 -4
  19. package/dist/{claude-managed-setup-c217draw.js → claude-managed-setup-9ssb7ct4.js} +4 -4
  20. package/dist/{claude-sdk-session-7fbqm51z.js → claude-sdk-session-p6t0gyse.js} +10941 -10412
  21. package/dist/{cli-2czxfnvj.js → cli-075ccjh6.js} +961 -178
  22. package/dist/{cli-fkef327x.js → cli-0bgj4rh5.js} +3 -3
  23. package/dist/{cli-1jykg0py.js → cli-14xdms9a.js} +41 -28
  24. package/dist/{cli-rqx70rcz.js → cli-17qzb39j.js} +5 -2
  25. package/dist/{cli-bkjdknnp.js → cli-1h4njv9y.js} +177 -7
  26. package/dist/{cli-6ym4jhzp.js → cli-27fat7st.js} +7 -7
  27. package/dist/{cli-kxx4k2jw.js → cli-2aacfdcn.js} +5 -5
  28. package/dist/{cli-fh97xn30.js → cli-2gvdvsxj.js} +3 -3
  29. package/dist/{cli-f9gz2vyj.js → cli-2jtfm8kh.js} +10 -10
  30. package/dist/{cli-6ehs4mta.js → cli-2z2c4k6q.js} +18 -4
  31. package/dist/{cli-6237rnyr.js → cli-3bpr3wks.js} +1 -1
  32. package/dist/{cli-bnqncekd.js → cli-453497a0.js} +44 -17
  33. package/dist/{cli-jm0hvmz2.js → cli-4aswccje.js} +2 -2
  34. package/dist/{cli-4ymxrwg5.js → cli-4dyzzkfb.js} +2 -2
  35. package/dist/{cli-vyff45ve.js → cli-4g323fjh.js} +772 -515
  36. package/dist/{cli-3kd08rej.js → cli-4jjrhy48.js} +1 -1
  37. package/dist/{cli-gfy38pvt.js → cli-4kzp7r0q.js} +8 -8
  38. package/dist/{cli-kxn3747f.js → cli-4se3x6qm.js} +1 -26
  39. package/dist/{cli-mjw0yf82.js → cli-5ptj757f.js} +1 -1
  40. package/dist/{cli-pyjn0qhk.js → cli-6a3j25xd.js} +348 -196
  41. package/dist/{cli-hnamkvnc.js → cli-6c9ve77f.js} +2 -2
  42. package/dist/{cli-mw620q3n.js → cli-6n7y5ypy.js} +1 -1
  43. package/dist/{cli-g0vv9dg4.js → cli-6p8p2e6r.js} +19 -12
  44. package/dist/{cli-jwampxxq.js → cli-6tvh1fwq.js} +3 -3
  45. package/dist/{cli-p74md7t8.js → cli-7b7rxz22.js} +13 -15
  46. package/dist/{cli-5a6pqy45.js → cli-7e8sxqv5.js} +1 -1
  47. package/dist/{cli-p4kckx1z.js → cli-892y3vfp.js} +13 -13
  48. package/dist/cli-8mfdbdhe.js +43 -0
  49. package/dist/{cli-mkwkwq81.js → cli-8zmpwe79.js} +29 -16
  50. package/dist/{cli-zcfpsfzf.js → cli-96234j5w.js} +3 -3
  51. package/dist/{cli-1z4qggfe.js → cli-9fvk9mv8.js} +30 -21
  52. package/dist/{cli-7mv4h3sn.js → cli-9g12h1aq.js} +2 -2
  53. package/dist/{cli-f8x9drqr.js → cli-9knhkkgr.js} +19 -5
  54. package/dist/{cli-5mpy301f.js → cli-9t7syepg.js} +1 -1
  55. package/dist/{cli-qj39vrc6.js → cli-9yjhshah.js} +1 -1
  56. package/dist/{cli-zr6qy15y.js → cli-a02habn6.js} +427 -145
  57. package/dist/{cli-7evph51z.js → cli-a49frv85.js} +2 -2
  58. package/dist/{cli-h9yqfzx9.js → cli-a6q6x15h.js} +11 -10
  59. package/dist/{cli-bg63qmsx.js → cli-atm0hkes.js} +11 -11
  60. package/dist/{cli-m7zvgt57.js → cli-b82a13ga.js} +13 -13
  61. package/dist/{cli-7zm3b3f5.js → cli-bf0t77nf.js} +1 -1
  62. package/dist/{cli-2xv18ywz.js → cli-bmqp0ser.js} +2 -2
  63. package/dist/{cli-xag7btpe.js → cli-bq97k63w.js} +2 -2
  64. package/dist/{cli-pb2ay3sh.js → cli-cstggwq7.js} +5 -5
  65. package/dist/{cli-f3jyzq4g.js → cli-czvvnfr9.js} +3 -3
  66. package/dist/{cli-b6px1k1q.js → cli-dd2k2mcd.js} +1 -1
  67. package/dist/{cli-nafvvsp8.js → cli-djt6wmrc.js} +9 -9
  68. package/dist/{cli-tsa40663.js → cli-ebqx630g.js} +3 -3
  69. package/dist/{cli-8zh9nrew.js → cli-f7dhm7hh.js} +1 -1
  70. package/dist/cli-f8yhybxr.js +321 -0
  71. package/dist/{cli-5gpqgs8b.js → cli-fwjwkw66.js} +2 -2
  72. package/dist/{cli-gabsjg8x.js → cli-g56fxddf.js} +1 -1
  73. package/dist/{cli-w4n323t3.js → cli-h2qtafm4.js} +19 -19
  74. package/dist/{cli-psffsanb.js → cli-ha4ek2nb.js} +6 -1
  75. package/dist/{cli-dgs10ttj.js → cli-hnh8erra.js} +2 -2
  76. package/dist/{cli-w16kwbzw.js → cli-htymm48w.js} +1 -1
  77. package/dist/{cli-2xs8tsf7.js → cli-j2r1apqm.js} +152 -67
  78. package/dist/{cli-43ms35q9.js → cli-k3c13za2.js} +3 -3
  79. package/dist/{cli-54vrpgm0.js → cli-k3facve0.js} +8 -5
  80. package/dist/{cli-67mwzr35.js → cli-k4r5sfaj.js} +7 -7
  81. package/dist/{cli-rq5rpv6k.js → cli-kbm659dk.js} +2 -2
  82. package/dist/{cli-j7svy295.js → cli-m00c47q6.js} +114 -31
  83. package/dist/{cli-m7c2380k.js → cli-mhrr4d5b.js} +99 -14
  84. package/dist/{cli-xqdz5cqm.js → cli-mz7ycqn8.js} +1 -0
  85. package/dist/{cli-vt89089n.js → cli-n6ygvrrm.js} +4 -4
  86. package/dist/{cli-jaw5v1sy.js → cli-nbakg5xh.js} +3 -3
  87. package/dist/{cli-nbt14he0.js → cli-nc39ym5q.js} +8 -8
  88. package/dist/{cli-tvc4jag9.js → cli-p1a4khta.js} +8 -8
  89. package/dist/{cli-t9ga4qmb.js → cli-p8zqbbt1.js} +40 -33
  90. package/dist/{cli-fjggej24.js → cli-ph95yejc.js} +2 -2
  91. package/dist/{cli-m0cy2vyf.js → cli-q4z9s6zs.js} +5 -5
  92. package/dist/cli-q71g5q39.js +404 -0
  93. package/dist/{cli-vs9vdpy0.js → cli-qncx2r0s.js} +1 -1
  94. package/dist/{cli-hg42n3hx.js → cli-qrzq3hvg.js} +8 -8
  95. package/dist/{cli-x40a0w9j.js → cli-r813c7rb.js} +1 -1
  96. package/dist/{cli-kpgcm7xy.js → cli-ramn8jae.js} +1 -1
  97. package/dist/{cli-jkw6ptfw.js → cli-raqw9fw9.js} +28 -17
  98. package/dist/cli-rhsc2zyx.js +68 -0
  99. package/dist/{cli-sn650d7x.js → cli-rpmw4fsv.js} +68 -20
  100. package/dist/{boot-scrub-sweep-7dkdzqxx.js → cli-rwgwen5v.js} +9 -10
  101. package/dist/{cli-3j873zxq.js → cli-rytq7dm2.js} +261 -6
  102. package/dist/{cli-zh0e5x7p.js → cli-s9twe4x0.js} +71 -22
  103. package/dist/{cli-2dq9yv8p.js → cli-t2s7j5cy.js} +2 -2
  104. package/dist/{cli-wn13hhdt.js → cli-tb4j757d.js} +7 -7
  105. package/dist/{cli-q2d3e1k1.js → cli-thd3005a.js} +1 -1
  106. package/dist/cli-tsfkcd4v.js +30 -0
  107. package/dist/{cli-br0924pw.js → cli-v3zcnr8g.js} +1 -1
  108. package/dist/{cli-zfqg6fzn.js → cli-vbppqvte.js} +3 -3
  109. package/dist/{cli-ysvspf5e.js → cli-vy3fn0mz.js} +4 -4
  110. package/dist/{cli-7sf9sb0w.js → cli-w5dar1bk.js} +1 -1
  111. package/dist/{cli-2yjj3e31.js → cli-wz4e5am2.js} +12 -10
  112. package/dist/{cli-td9tb872.js → cli-xqbqwpxr.js} +14 -14
  113. package/dist/{cli-32djehja.js → cli-ynph3b70.js} +11137 -8332
  114. package/dist/{cli-mhapr559.js → cli-yvzxbztc.js} +9 -4
  115. package/dist/{cli-v57d7fmm.js → cli-yzxqwcvq.js} +25 -27
  116. package/dist/{cli-y2ewxhth.js → cli-zb1hff00.js} +16 -16
  117. package/dist/{cli-yab6sh8p.js → cli-zcghfsdg.js} +23 -4
  118. package/dist/{cli-ctx0b85j.js → cli-zhn4r1rz.js} +757 -157
  119. package/dist/{cli-6945ywhr.js → cli-zqq57pgx.js} +9 -7
  120. package/dist/cli.js +30 -29
  121. package/dist/{cloudflare-workers-ai-system-one-9y1zx3pt.js → cloudflare-workers-ai-system-one-w3m0fbf8.js} +2 -2
  122. package/dist/{codex-adapter-n656pvb8.js → codex-adapter-ssahg4h4.js} +8 -8
  123. package/dist/{codex-hook-59atdwd8.js → codex-hook-aqtj17yr.js} +1 -1
  124. package/dist/{codex-login-a239g1ah.js → codex-login-9c7aggxe.js} +1 -1
  125. package/dist/{codex-session-runner-p0fbv5y9.js → codex-session-runner-xn63q3h7.js} +9 -9
  126. package/dist/{commands-gwea8z5p.js → commands-ctey7tr5.js} +3 -3
  127. package/dist/{controller-t67c3grh.js → controller-rqhbppg9.js} +4 -4
  128. package/dist/{controllers-connect-ks155r0h.js → controllers-connect-w3qbpbt1.js} +22 -21
  129. package/dist/core-df1n049h.js +39 -0
  130. package/dist/{cursor-adapter-ygwrtmkv.js → cursor-adapter-r819hf1a.js} +2 -2
  131. package/dist/{db-kpmx06s9.js → db-2ah39cyx.js} +2 -2
  132. package/dist/{db-rb2xqdb1.js → db-p5drc1d1.js} +3 -3
  133. package/dist/{devin-adapter-zp4tqq53.js → devin-adapter-bc6g0x29.js} +1 -1
  134. package/dist/{dispatcher-31sm0ej2.js → dispatcher-x6w14pde.js} +19 -18
  135. package/dist/{docker-09tkkg0n.js → docker-6c4reetq.js} +51 -14
  136. package/dist/{dsh-adapter-qyxh0w31.js → dsh-adapter-h8qn14n4.js} +2 -2
  137. package/dist/{e2b-sm28k0k3.js → e2b-jg7kyyef.js} +6 -6
  138. package/dist/{e2b-3v1e745x.js → e2b-z4ec0qve.js} +3 -3
  139. package/dist/{easter-egg-3d-00wjscn6.js → easter-egg-3d-1y6r9gxy.js} +1 -1
  140. package/dist/{embedding-space-qhw4g68n.js → embedding-space-z6ptw3jk.js} +6 -6
  141. package/dist/{embeddings-zdv9ke6x.js → embeddings-0sxb1d2h.js} +1 -1
  142. package/dist/{event-bus-xr83x566.js → event-bus-swr88jg5.js} +1 -1
  143. package/dist/{execute-zna8wwr7.js → execute-6m1ex8ce.js} +8 -4
  144. package/dist/{external-channel-1ac6t56s.js → external-channel-ezer7pk0.js} +2 -2
  145. package/dist/fx-adapter-zwmps9re.js +19 -0
  146. package/dist/{google-generative-ai-maq6c9bf.js → google-generative-ai-sw77egmr.js} +13 -13
  147. package/dist/{google-vertex-2jgsw2nb.js → google-vertex-rrw93g8h.js} +13 -13
  148. package/dist/grok-adapter-q0avf919.js +19 -0
  149. package/dist/handlers-g5jq0e4q.js +36 -0
  150. package/dist/{heartbeat-2f6z4kdx.js → heartbeat-6c4fr49t.js} +22 -21
  151. package/dist/{hook-8y0gvtp1.js → hook-02rt5tvq.js} +8 -8
  152. package/dist/{hook-w1skzaqc.js → hook-t1c5avbv.js} +5 -5
  153. package/dist/{http-wghxvpef.js → http-qa3h32a1.js} +2659 -355
  154. package/dist/index-1f6m47mq.js +37 -0
  155. package/dist/index-1p1mpqda.js +36 -0
  156. package/dist/{index-rv89fvzf.js → index-akbgsdhh.js} +25 -24
  157. package/dist/{index-9zkchs9t.js → index-e42j998x.js} +190 -15
  158. package/dist/{index-b5wgnm78.js → index-kdmkfjt7.js} +4 -4
  159. package/dist/{index-s71ez27v.js → index-kqv9ebfj.js} +1 -1
  160. package/dist/{index-9myfj74s.js → index-kzdqn3dd.js} +3 -3
  161. package/dist/{index-4a0670yh.js → index-p2f5xg64.js} +6 -6
  162. package/dist/{index-8zn8nxn5.js → index-qpjk2hxk.js} +1 -1
  163. package/dist/index-tnkd410q.js +41 -0
  164. package/dist/k8s-7jrh5va2.js +276 -0
  165. package/dist/{keepalive-sh02349h.js → keepalive-jmf6pn8c.js} +4 -4
  166. package/dist/lead-m5e7xt93.js +75 -0
  167. package/dist/{llama-cpp-classify-nfgswa1m.js → llama-cpp-classify-yvb8vh7w.js} +2 -2
  168. package/dist/{maintenance-yj0dcjja.js → maintenance-g7v15tj1.js} +1 -1
  169. package/dist/{mistral-conversations-0c30em7t.js → mistral-conversations-w4bncwbt.js} +11 -11
  170. package/dist/{node-7qsx5kvm.js → node-z67yjre7.js} +19 -13
  171. package/dist/{oauth-refresh-sweep-d9xedk66.js → oauth-refresh-sweep-ywgf8tbr.js} +3 -3
  172. package/dist/{onboard-dpgjn03r.js → onboard-m3fedypq.js} +6 -6
  173. package/dist/{openai-codex-responses-bkcd8pjj.js → openai-codex-responses-70g39cgz.js} +24 -18
  174. package/dist/{openai-completions-f3n69rep.js → openai-completions-cv3hp4h5.js} +33 -26
  175. package/dist/{openai-decisions-q3hh60wr.js → openai-decisions-fyq1p9f9.js} +2 -2
  176. package/dist/{openai-responses-gbh0wfqe.js → openai-responses-trsvnks6.js} +24 -22
  177. package/dist/{opencode-adapter-2d31cpjc.js → opencode-adapter-19ktcbb9.js} +7 -7
  178. package/dist/{openrouter-images-xr9gme9x.js → openrouter-images-0jj12a2q.js} +6 -6
  179. package/dist/{otel-impl-1skarpfq.js → otel-impl-3ehm1hgc.js} +2 -2
  180. package/dist/{pending-bfmxtx0g.js → pending-fwj2fatd.js} +20 -19
  181. package/dist/{pi-messages-zebyt7gb.js → pi-messages-zk3g4esn.js} +6 -6
  182. package/dist/{pi-mono-adapter-gvppnasy.js → pi-mono-adapter-xdeesvc4.js} +18 -17
  183. package/dist/{pricing-refresh-c6b325mk.js → pricing-refresh-4j8dzvxg.js} +2 -2
  184. package/dist/{rbac-roles-h80qbdbs.js → rbac-roles-8msjr07m.js} +3 -3
  185. package/dist/{rbac-roles-zfcx68tx.js → rbac-roles-n7t2acv8.js} +2 -2
  186. package/dist/{render-v2-nx20t3rb.js → render-v2-j7qggj8h.js} +7 -6
  187. package/dist/{resume-5ep8agan.js → resume-hj1mn65y.js} +9 -8
  188. package/dist/{runtime-r3pj4mce.js → runtime-z31mdsgv.js} +2 -2
  189. package/dist/{session-access-n7p3m15b.js → session-access-w38fh09a.js} +4 -4
  190. package/dist/{session-source-backfill-v8mt0zwn.js → session-source-backfill-ax6qxv20.js} +3 -3
  191. package/dist/{setup-z1psaqhe.js → setup-dsqmpfcr.js} +1 -1
  192. package/dist/thread-buffer-nf55vwx3.js +39 -0
  193. package/dist/tree-visibility-6vqmnr71.js +24 -0
  194. package/dist/{typesafe-system-one-f2en2knd.js → typesafe-system-one-qkvkgrcz.js} +2 -2
  195. package/dist/user-merge-jobs-mvheb3ed.js +22 -0
  196. package/dist/{virtual-modules-rrbjdpxn.js → virtual-modules-w2qk2wew.js} +32 -10
  197. package/dist/{work-objects-4aghh73z.js → work-objects-4ahy5es5.js} +22 -21
  198. package/dist/worker-ews1nyhw.js +75 -0
  199. package/dist/{worker-follow-up-166zmex1.js → worker-follow-up-1gs4aw7y.js} +19 -18
  200. package/dist/{x-wg164ss9.js → x-3wr8c5sh.js} +2 -2
  201. package/openapi.json +2576 -388
  202. package/package.json +11 -10
  203. package/src/be/boot-seeds.ts +7 -1
  204. package/src/be/db/model-groups.ts +238 -0
  205. package/src/be/db/model-profiles.ts +26 -8
  206. package/src/be/db/request-composition.ts +190 -0
  207. package/src/be/db/runtime.ts +15 -0
  208. package/src/be/db/session-costs.ts +8 -2
  209. package/src/be/db/slack-trees.ts +220 -10
  210. package/src/be/db/tasks/human-free.ts +3 -2
  211. package/src/be/db/tasks/read.ts +3 -2
  212. package/src/be/db/tasks/write.ts +2 -1
  213. package/src/be/db/user-references.ts +75 -0
  214. package/src/be/db/users/references.ts +185 -0
  215. package/src/be/db/workflow-run-retention.ts +101 -0
  216. package/src/be/db-client.ts +93 -20
  217. package/src/be/db-retention-defaults.ts +46 -0
  218. package/src/be/db-retention.ts +55 -6
  219. package/src/be/db.ts +32 -57
  220. package/src/be/key-window-usage.ts +1 -0
  221. package/src/be/mcp-events/catalog.ts +108 -0
  222. package/src/be/mcp-events/dispatcher.ts +202 -0
  223. package/src/be/mcp-events/protocol.ts +296 -0
  224. package/src/be/mcp-events/store.ts +231 -0
  225. package/src/be/mcp-events/webhook.ts +226 -0
  226. package/src/be/memory/demotion-evidence.ts +34 -0
  227. package/src/be/memory/providers/sqlite-store.ts +110 -24
  228. package/src/be/memory/reranker.ts +34 -12
  229. package/src/be/memory/review-recall-filter.ts +105 -0
  230. package/src/be/memory/search-candidates.ts +16 -5
  231. package/src/be/memory/types.ts +16 -0
  232. package/src/be/migrations/312_task_ui_action_runs_repeatable.sql +6 -0
  233. package/src/be/migrations/314_model_groups.sql +85 -0
  234. package/src/be/migrations/318_superseded_workflow_cut_backfill.sql +22 -0
  235. package/src/be/migrations/319_user_fk_indexes.sql +153 -0
  236. package/src/be/migrations/320_session_costs_kind.sql +4 -0
  237. package/src/be/migrations/321_user_merge_jobs.sql +52 -0
  238. package/src/be/migrations/322_runtime_pool_workspace.sql +8 -0
  239. package/src/be/migrations/323_slack_task_tree_visibility.sql +9 -0
  240. package/src/be/migrations/326_slack_reconcile_pages.sql +13 -0
  241. package/src/be/migrations/327_mcp_event_subscriptions.sql +57 -0
  242. package/src/be/migrations/329_workflow_run_retention.sql +9 -0
  243. package/src/be/migrations/330_request_composition.sql +22 -0
  244. package/src/be/model-profile-check.ts +1 -1
  245. package/src/be/multi-runtime.ts +32 -4
  246. package/src/be/pricing-normalize.ts +2 -0
  247. package/src/be/rbac-roles.ts +6 -4
  248. package/src/be/runtime-pools/controllers.ts +18 -3
  249. package/src/be/runtime-pools/db.ts +35 -9
  250. package/src/be/runtime-pools/supervisor.ts +57 -3
  251. package/src/be/scripts/db.ts +11 -0
  252. package/src/be/scripts/typecheck.ts +2 -0
  253. package/src/be/seed-model-groups.ts +86 -0
  254. package/src/be/seed-model-profiles.ts +20 -13
  255. package/src/be/seed-scripts/catalog/dreaming-gather.ts +165 -1
  256. package/src/be/swarm-config-guard.ts +44 -2
  257. package/src/be/task-ui-spec.ts +102 -1
  258. package/src/be/user-merge-jobs.ts +564 -0
  259. package/src/be/users.ts +41 -23
  260. package/src/commands/context-preamble.ts +11 -4
  261. package/src/commands/credential-outcome-report.ts +33 -9
  262. package/src/commands/e2b-stack-wizard.tsx +12 -6
  263. package/src/commands/onboard/agent-fs-version.ts +1 -1
  264. package/src/commands/onboard/compose-generator.ts +1 -1
  265. package/src/commands/onboard/env-generator.ts +1 -1
  266. package/src/commands/provider-credentials.ts +1 -1
  267. package/src/commands/runner.ts +116 -12
  268. package/src/extensions/catalog.generated.json +1 -1
  269. package/src/extensions/contract-types.generated.ts +1 -1
  270. package/src/extensions/contract.ts +15 -0
  271. package/src/extensions/dispatcher.ts +14 -4
  272. package/src/github/app.ts +59 -14
  273. package/src/github/handlers.ts +57 -0
  274. package/src/github/types.ts +4 -0
  275. package/src/http/all-routes.ts +4 -0
  276. package/src/http/approval-requests.ts +5 -1
  277. package/src/http/auth.ts +3 -1
  278. package/src/http/config.ts +36 -2
  279. package/src/http/core.ts +2 -0
  280. package/src/http/github-token.ts +66 -0
  281. package/src/http/index.ts +34 -0
  282. package/src/http/mcp-user.ts +11 -8
  283. package/src/http/mcp.ts +58 -42
  284. package/src/http/memory.ts +19 -6
  285. package/src/http/model-groups.ts +277 -0
  286. package/src/http/model-profiles.ts +30 -13
  287. package/src/http/prompt-templates.ts +1 -0
  288. package/src/http/request-composition.ts +310 -0
  289. package/src/http/tasks.ts +46 -6
  290. package/src/http/tool-hooks.ts +140 -0
  291. package/src/http/tool-schema-estimate.ts +95 -0
  292. package/src/http/users.ts +142 -19
  293. package/src/http/workflows.ts +37 -1
  294. package/src/integrations/chat-sdk/inbound.ts +8 -2
  295. package/src/integrations/chat-sdk/limits.ts +8 -3
  296. package/src/prompts/base-prompt.ts +133 -7
  297. package/src/prompts/resolver.ts +41 -2
  298. package/src/providers/acp-targets.ts +2 -2
  299. package/src/providers/amp-adapter.ts +1 -1
  300. package/src/providers/opencode-adapter.ts +72 -1
  301. package/src/providers/opencode-swarm-plugin.ts +22 -3
  302. package/src/providers/pi-mono-adapter.ts +1 -0
  303. package/src/providers/pi-mono-extension.ts +71 -0
  304. package/src/providers/pricing-sources.md +13 -0
  305. package/src/providers/request-composition-hook.ts +312 -0
  306. package/src/providers/types.ts +5 -0
  307. package/src/rbac/legacy-policy.ts +1 -0
  308. package/src/rbac/permissions.ts +5 -0
  309. package/src/runtime-providers/controller-protocol.ts +7 -0
  310. package/src/runtime-providers/docker.ts +80 -12
  311. package/src/runtime-providers/index.ts +7 -5
  312. package/src/runtime-providers/k8s.ts +355 -0
  313. package/src/runtime-providers/types.ts +17 -0
  314. package/src/scheduler/scheduler.ts +1 -1
  315. package/src/scripts-runtime/types/stdlib.d.ts +2 -0
  316. package/src/scripts-runtime/types/swarm-extension.d.ts +16 -1
  317. package/src/scripts-runtime/types/swarm-sdk.d.ts +2 -0
  318. package/src/server-user.ts +16 -1
  319. package/src/slack/ack.ts +10 -5
  320. package/src/slack/actions.ts +36 -13
  321. package/src/slack/app.ts +2 -0
  322. package/src/slack/assistant.ts +4 -4
  323. package/src/slack/blocks.ts +26 -5
  324. package/src/slack/handlers.ts +3 -3
  325. package/src/slack/reaction-shortcode.ts +23 -2
  326. package/src/slack/render-v2.ts +344 -200
  327. package/src/slack/responses.ts +7 -5
  328. package/src/slack/thread-buffer.ts +3 -3
  329. package/src/slack/tree-visibility.ts +64 -0
  330. package/src/tasks/worker-follow-up.ts +127 -17
  331. package/src/tests/acp-adapter.test.ts +26 -0
  332. package/src/tests/azure-devops-outbound.test.ts +47 -14
  333. package/src/tests/base-prompt.test.ts +149 -1
  334. package/src/tests/chat-sdk-relay.test.ts +21 -1
  335. package/src/tests/check-playwright-version.test.ts +33 -0
  336. package/src/tests/check-pr-body.test.ts +43 -0
  337. package/src/tests/context-preamble-budget.test.ts +65 -0
  338. package/src/tests/credential-check.test.ts +14 -6
  339. package/src/tests/credential-outcome-report.test.ts +81 -1
  340. package/src/tests/db-client.test.ts +168 -0
  341. package/src/tests/db-retention-defaults.test.ts +244 -0
  342. package/src/tests/db-retention.test.ts +2 -1
  343. package/src/tests/db-runtime.test.ts +2 -1
  344. package/src/tests/deploy-guard.test.ts +7 -7
  345. package/src/tests/deploy-release-dispatch.test.ts +332 -0
  346. package/src/tests/deploy-select.test.ts +83 -0
  347. package/src/tests/dreaming-gather-corrections.test.ts +467 -0
  348. package/src/tests/e2b-stack-wizard.test.tsx +156 -0
  349. package/src/tests/entrypoint-chown-no-follow.test.ts +69 -0
  350. package/src/tests/entrypoint-repo-clone-target.test.ts +112 -0
  351. package/src/tests/env-flag.test.ts +4 -2
  352. package/src/tests/event-loop-lag.test.ts +16 -20
  353. package/src/tests/extensions-example-slack-reply-gate.test.ts +15 -0
  354. package/src/tests/fixtures/base-prompt-baseline-cases.ts +78 -0
  355. package/src/tests/fixtures/base-prompt-baseline.json +18 -0
  356. package/src/tests/fixtures/extensions/native-tool-recorder/hooks.ts +26 -0
  357. package/src/tests/fixtures/extensions/native-tool-recorder/manifest.json +10 -0
  358. package/src/tests/fixtures/onboard/content.compose.yml.txt +1 -1
  359. package/src/tests/fixtures/onboard/content.env.txt +1 -1
  360. package/src/tests/fixtures/onboard/dev.compose.yml.txt +1 -1
  361. package/src/tests/fixtures/onboard/dev.env.txt +1 -1
  362. package/src/tests/fixtures/onboard/full-all.compose.yml.txt +1 -1
  363. package/src/tests/fixtures/onboard/full-all.env.txt +1 -1
  364. package/src/tests/fixtures/onboard/full.compose.yml.txt +1 -1
  365. package/src/tests/fixtures/onboard/full.env.txt +1 -1
  366. package/src/tests/fixtures/onboard/research.compose.yml.txt +1 -1
  367. package/src/tests/fixtures/onboard/research.env.txt +1 -1
  368. package/src/tests/fixtures/onboard/solo.compose.yml.txt +1 -1
  369. package/src/tests/fixtures/onboard/solo.env.txt +1 -1
  370. package/src/tests/github-app-worker-auth-helper.test.ts +325 -0
  371. package/src/tests/github-event-filter.test.ts +8 -0
  372. package/src/tests/github-handlers-inline-comments.test.ts +2 -0
  373. package/src/tests/github-handlers-reactions.test.ts +4 -0
  374. package/src/tests/github-handlers.test.ts +3 -0
  375. package/src/tests/github-installation-token-route.test.ts +199 -0
  376. package/src/tests/github-sender-trust.test.ts +223 -0
  377. package/src/tests/http-users.test.ts +142 -41
  378. package/src/tests/k8s-pool-smoke.test.ts +190 -0
  379. package/src/tests/key-window-usage.test.ts +15 -0
  380. package/src/tests/mcp-user-events.test.ts +708 -0
  381. package/src/tests/memory-key-paths.test.ts +4 -1
  382. package/src/tests/memory-rater-store.test.ts +35 -1
  383. package/src/tests/memory-reranker.test.ts +39 -4
  384. package/src/tests/memory-review-recall-filter.test.ts +205 -0
  385. package/src/tests/memory-search-stall.test.ts +421 -0
  386. package/src/tests/migration-318-superseded-workflow-cut-backfill.test.ts +74 -0
  387. package/src/tests/migration-322-runtime-pool-workspace.test.ts +116 -0
  388. package/src/tests/migration-329-workflow-run-retention.test.ts +32 -0
  389. package/src/tests/model-groups-api.test.ts +415 -0
  390. package/src/tests/model-profile-fallbacks.test.ts +236 -2
  391. package/src/tests/model-profiles-api.test.ts +1 -0
  392. package/src/tests/opencode-adapter.test.ts +86 -0
  393. package/src/tests/operator-granted-credentials.test.ts +7 -2
  394. package/src/tests/operator-granted-role-wire.test.ts +2 -1
  395. package/src/tests/pi-mono-extension.test.ts +168 -0
  396. package/src/tests/preload-env.test.ts +61 -1
  397. package/src/tests/preload.ts +22 -0
  398. package/src/tests/prompt-template-resolver.test.ts +85 -0
  399. package/src/tests/rbac-engine.test.ts +1 -0
  400. package/src/tests/reload-config.test.ts +45 -0
  401. package/src/tests/request-composition.test.ts +447 -0
  402. package/src/tests/runner-max-concurrent.test.ts +86 -0
  403. package/src/tests/runtime-k8s-pools.test.ts +142 -0
  404. package/src/tests/runtime-pools-db.test.ts +122 -2
  405. package/src/tests/runtime-pools-http.test.ts +47 -2
  406. package/src/tests/runtime-provider-registration.test.ts +13 -14
  407. package/src/tests/runtime-providers-docker.test.ts +192 -1
  408. package/src/tests/runtime-providers-k8s.test.ts +430 -0
  409. package/src/tests/runtime-remote-controller.test.ts +64 -1
  410. package/src/tests/runtime-supervisor.test.ts +101 -0
  411. package/src/tests/script-connections.test.ts +21 -1
  412. package/src/tests/short-id.test.ts +23 -0
  413. package/src/tests/slack-blocks.test.ts +87 -0
  414. package/src/tests/slack-empty-icon-config.test.ts +113 -0
  415. package/src/tests/slack-reaction-config.test.ts +38 -2
  416. package/src/tests/slack-render-v2-query-plans.test.ts +100 -1
  417. package/src/tests/slack-render-v2-reconcile.test.ts +75 -4
  418. package/src/tests/slack-render-v2.test.ts +737 -11
  419. package/src/tests/spec-base-url.test.ts +13 -1
  420. package/src/tests/swarm-config-reserved-keys.test.ts +1 -0
  421. package/src/tests/system-one-decide-session-cost.test.ts +196 -0
  422. package/src/tests/task-session-prompts.test.ts +37 -0
  423. package/src/tests/task-ui-action-route.test.ts +59 -1
  424. package/src/tests/task-ui-script-actions.test.ts +517 -0
  425. package/src/tests/tool-hooks-http.test.ts +187 -0
  426. package/src/tests/ui-spec-script-actions-config.test.ts +196 -0
  427. package/src/tests/user-delete-perf.test.ts +348 -0
  428. package/src/tests/user-merge-jobs.test.ts +680 -0
  429. package/src/tests/vcs-provider.test.ts +25 -5
  430. package/src/tests/vendored-openapi.test.ts +13 -1
  431. package/src/tests/webhook-filter.test.ts +327 -0
  432. package/src/tests/workflow-agent-task-retry.test.ts +62 -0
  433. package/src/tests/workflow-async-v2.test.ts +19 -16
  434. package/src/tests/workflow-definition-telemetry.test.ts +15 -5
  435. package/src/tests/workflow-e2e.test.ts +1 -9
  436. package/src/tests/workflow-finalization-races.test.ts +553 -0
  437. package/src/tests/workflow-foreach-supersede-retry.test.ts +10 -0
  438. package/src/tests/workflow-foreach.test.ts +2 -0
  439. package/src/tests/workflow-hitl-routing.test.ts +26 -20
  440. package/src/tests/workflow-http-v2.test.ts +132 -2
  441. package/src/tests/workflow-idempotency.test.ts +41 -0
  442. package/src/tests/workflow-mcp-webhook-filter.test.ts +214 -0
  443. package/src/tests/workflow-parallel-park.test.ts +297 -0
  444. package/src/tests/workflow-replay.test.ts +10 -1
  445. package/src/tests/workflow-retry-v2.test.ts +57 -21
  446. package/src/tests/workflow-retry-validation.test.ts +13 -13
  447. package/src/tests/workflow-runs-retention.test.ts +533 -0
  448. package/src/tests/workflow-script-principal.test.ts +7 -2
  449. package/src/tests/workflow-tla-races.test.ts +7 -2
  450. package/src/tests/workflow-triggers-v2.test.ts +329 -0
  451. package/src/tests/workflow-wait-builtin-events.test.ts +3 -1
  452. package/src/tests/workflow-wait-event.test.ts +137 -3
  453. package/src/tests/workflow-wait-poller.test.ts +94 -0
  454. package/src/tests/workflow-wait-time.test.ts +7 -3
  455. package/src/tests/workflow-wait.test.ts +26 -0
  456. package/src/tests/workflow-wait.ts +44 -0
  457. package/src/tools/memory-search.ts +14 -3
  458. package/src/tools/store-progress.ts +26 -26
  459. package/src/tools/swarm-config/delete-config.ts +12 -1
  460. package/src/tools/swarm-config/set-config.ts +8 -0
  461. package/src/tools/system-one-decide.ts +113 -3
  462. package/src/tools/utils.ts +4 -1
  463. package/src/tools/workflows/create-workflow.ts +7 -1
  464. package/src/tools/workflows/update-workflow.ts +8 -2
  465. package/src/types.ts +284 -2
  466. package/src/ui-spec/actions.ts +30 -4
  467. package/src/ui-spec/schema.ts +38 -0
  468. package/src/ui-spec/script-actions.ts +340 -0
  469. package/src/ui-spec/script-allowlist.ts +48 -0
  470. package/src/utils/credentials.ts +7 -0
  471. package/src/utils/short-id.ts +20 -14
  472. package/src/utils/task-ui-spec.ts +16 -4
  473. package/src/vcs/index.ts +12 -2
  474. package/src/workflows/checkpoint.ts +18 -0
  475. package/src/workflows/engine.ts +38 -10
  476. package/src/workflows/executors/system-one-decision.ts +2 -2
  477. package/src/workflows/foreach-driver.ts +42 -4
  478. package/src/workflows/recovery.ts +6 -1
  479. package/src/workflows/resume.ts +14 -5
  480. package/src/workflows/retry-poller.ts +17 -4
  481. package/src/workflows/successor-routing.ts +108 -0
  482. package/src/workflows/task-step-routing.ts +35 -12
  483. package/src/workflows/triggers.ts +25 -8
  484. package/src/workflows/wait-poller.ts +6 -2
  485. package/src/workflows/webhook-filter.ts +203 -0
  486. package/templates/extensions/manifest.schema.json +13 -0
  487. package/templates/extensions/slack-reply-gate/hooks.ts +8 -4
  488. package/templates/skills/swarm-docs/content.md +4 -0
  489. package/templates/skills/ui-spec/content.md +7 -1
  490. package/templates/workflows/dreaming/content.md +1 -1
  491. package/dist/acp-adapter-g909b5hw.js +0 -16
  492. package/dist/cli-b91nz213.js +0 -93
  493. package/dist/fx-adapter-sk7n0fzc.js +0 -19
  494. package/dist/grok-adapter-sjbcm5ew.js +0 -19
  495. package/dist/handlers-yzy0c87x.js +0 -35
  496. package/dist/index-25pvya7q.js +0 -40
  497. package/dist/index-2t4859r5.js +0 -35
  498. package/dist/index-cxca2t8y.js +0 -36
  499. package/dist/lead-gk4h5eg7.js +0 -74
  500. package/dist/thread-buffer-a1re2r9r.js +0 -38
  501. package/dist/worker-3dyyb8ev.js +0 -74
  502. /package/dist/{node-dqm4xgxw.js → node-2wfcey7d.js} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  bedrockProviderModule
3
- } from "./cli-g0vv9dg4.js";
3
+ } from "./cli-6p8p2e6r.js";
4
4
  import {
5
5
  auditAssetKeys,
6
6
  init_asset_key_audit,
@@ -8,6 +8,8 @@ import {
8
8
  placeholderForConfigKey,
9
9
  isPrivateAddress,
10
10
  assertUrlSafe,
11
+ EgressDeniedError,
12
+ createGuardedFetch,
11
13
  init_egress_guard,
12
14
  init_credential_broker,
13
15
  encryptSecret,
@@ -24,6 +26,7 @@ import {
24
26
  init_default_drift,
25
27
  init_templates2,
26
28
  init_templates3,
29
+ wasDbCreatedThisBoot,
27
30
  getDb2,
28
31
  closeDb2,
29
32
  getDbClient2,
@@ -89,6 +92,8 @@ import {
89
92
  rankingFormSchema,
90
93
  buildListing,
91
94
  init_telemetry_ranking,
95
+ isSlackIconConfigKey,
96
+ init_reaction_shortcode,
92
97
  API_DRAINING_HEADER,
93
98
  init_api_drain2,
94
99
  parseTaskToolManifest,
@@ -99,6 +104,9 @@ import {
99
104
  isApiOnlyConfigKey,
100
105
  isInternalConfigKey,
101
106
  internalConfigKeyError,
107
+ isHumanOnlyConfigKey,
108
+ humanOnlyConfigKeyError,
109
+ humanOnlyConfigKeyPageError,
102
110
  MAX_DB_RETENTION_DAYS,
103
111
  DB_RETENTION_TUNING_BOUNDS,
104
112
  CODEX_OAUTH_KEEP_WARM_MAX_AGE_HOURS_BOUNDS,
@@ -160,6 +168,9 @@ import {
160
168
  init_key_paths,
161
169
  rerank,
162
170
  init_reranker,
171
+ isReviewTaskId,
172
+ dropReviewTaskCompletions,
173
+ init_review_recall_filter,
163
174
  searchMemoryCandidates,
164
175
  init_search_candidates,
165
176
  getEmbeddingProvider2,
@@ -211,8 +222,6 @@ import {
211
222
  init_vcs_repo_match,
212
223
  taskModelPin,
213
224
  init_model_pin,
214
- normalizeModelKey,
215
- init_pricing_normalize,
216
225
  upsertModelCatalogOverlay,
217
226
  deleteModelCatalogOverlay,
218
227
  loadModelsCatalog,
@@ -259,6 +268,7 @@ import {
259
268
  updateModelProfile,
260
269
  modelProfileReferences,
261
270
  modelProfileRefError,
271
+ isModelNameTakenError,
262
272
  deleteModelProfile,
263
273
  MAX_MODEL_PROFILE_FALLBACKS,
264
274
  modelProfileFallbacksError,
@@ -293,6 +303,7 @@ import {
293
303
  triageSessionList,
294
304
  init_session_tree,
295
305
  setHumanFreeQueueListener,
306
+ reclassifyTaskHumanFree,
296
307
  drainHumanFreeReclassifyQueue,
297
308
  init_human_free,
298
309
  channelTopic,
@@ -327,6 +338,8 @@ import {
327
338
  assertWorkflowIdempotencyKeyUnused,
328
339
  recordAcceptedWorkflowOperation,
329
340
  init_workflow_idempotency,
341
+ deleteOrphanedRunDefinitions,
342
+ init_workflow_run_definitions,
330
343
  recordKeySeatMismatch2,
331
344
  recordKeyValidation2,
332
345
  retirePoolKeyStatus,
@@ -485,7 +498,6 @@ import {
485
498
  getAllUsers2,
486
499
  createUser2,
487
500
  updateUser2,
488
- deleteUser2,
489
501
  listInboxState2,
490
502
  upsertInboxState2,
491
503
  listFavorites2,
@@ -538,7 +550,7 @@ import {
538
550
  countScriptRunJournalSteps2,
539
551
  countScriptRunJournalAgentTaskSteps2,
540
552
  init_db4
541
- } from "./cli-ctx0b85j.js";
553
+ } from "./cli-zhn4r1rz.js";
542
554
  import {
543
555
  PRIMARY_ROLE_NAMES2,
544
556
  OperatorGrantedTargetError2,
@@ -552,17 +564,27 @@ import {
552
564
  assertNotLastAdmin2,
553
565
  setUserRoles2,
554
566
  init_rbac_roles
555
- } from "./cli-pb2ay3sh.js";
556
- import"./cli-b91nz213.js";
567
+ } from "./cli-cstggwq7.js";
568
+ import {
569
+ MAX_MODEL_GROUP_MEMBERS,
570
+ listModelGroups,
571
+ getModelGroupByName,
572
+ createModelGroup,
573
+ updateModelGroup,
574
+ modelGroupReferences,
575
+ deleteModelGroup,
576
+ init_model_groups
577
+ } from "./cli-f8yhybxr.js";
557
578
  import {
558
579
  requestModelCatalogRefresh2,
559
580
  init_pricing_refresh
560
- } from "./cli-dgs10ttj.js";
581
+ } from "./cli-hnh8erra.js";
561
582
  import {
562
583
  workflowEventBus2,
563
584
  init_event_bus
564
- } from "./cli-q2d3e1k1.js";
565
- import"./cli-xag7btpe.js";
585
+ } from "./cli-thd3005a.js";
586
+ import"./cli-bq97k63w.js";
587
+ import"./cli-rhsc2zyx.js";
566
588
  import"./cli-9w8712tq.js";
567
589
  import"./cli-47hz21se.js";
568
590
  import {
@@ -599,8 +621,8 @@ import {
599
621
  getSlackHttpReceiver2,
600
622
  startSlackApp2,
601
623
  stopSlackApp2,
602
- init_app3
603
- } from "./cli-pyjn0qhk.js";
624
+ init_app4
625
+ } from "./cli-6a3j25xd.js";
604
626
  import {
605
627
  AGENT_MAX_TASKS_CONFIG_KEY,
606
628
  reconcileAgentMaxTasksPolicy,
@@ -628,21 +650,56 @@ import {
628
650
  dispatchApprovalNotifications2,
629
651
  createApprovalFollowUpTask2,
630
652
  init_approval_notifications
631
- } from "./cli-jkw6ptfw.js";
653
+ } from "./cli-raqw9fw9.js";
632
654
  import {
633
655
  retryFailedRun2,
634
656
  cancelWorkflowRun2,
635
657
  init_resume
636
- } from "./cli-1jykg0py.js";
658
+ } from "./cli-14xdms9a.js";
637
659
  import {
660
+ safeParse,
661
+ getObjectShape,
662
+ getLiteralValue,
663
+ init_zod_compat,
664
+ LATEST_PROTOCOL_VERSION,
638
665
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
639
666
  SUPPORTED_PROTOCOL_VERSIONS,
640
667
  isJSONRPCRequest,
641
668
  isJSONRPCResultResponse,
669
+ ErrorCode,
642
670
  isJSONRPCErrorResponse,
643
671
  JSONRPCMessageSchema,
672
+ EmptyResultSchema,
644
673
  isInitializeRequest,
674
+ InitializeResultSchema,
675
+ CreateTaskResultSchema,
676
+ ListResourcesResultSchema,
677
+ ListResourceTemplatesResultSchema,
678
+ ReadResourceResultSchema,
679
+ ResourceListChangedNotificationSchema,
680
+ ListPromptsResultSchema,
681
+ GetPromptResultSchema,
682
+ PromptListChangedNotificationSchema,
683
+ ListToolsResultSchema,
684
+ CallToolResultSchema,
685
+ ToolListChangedNotificationSchema,
686
+ ListChangedOptionsBaseSchema,
687
+ CreateMessageRequestSchema,
688
+ CreateMessageResultSchema,
689
+ CreateMessageResultWithToolsSchema,
690
+ ElicitRequestSchema,
691
+ ElicitResultSchema,
692
+ CompleteResultSchema,
693
+ McpError,
645
694
  init_types,
695
+ Protocol,
696
+ mergeCapabilities,
697
+ init_protocol,
698
+ AjvJsonSchemaValidator,
699
+ init_ajv_provider,
700
+ assertToolsCallTaskCapability,
701
+ assertClientRequestTaskCapability,
702
+ init_helpers,
646
703
  McpServer,
647
704
  init_mcp,
648
705
  referencedBundlePaths,
@@ -717,6 +774,9 @@ import {
717
774
  loadEnabledExtensions,
718
775
  stopExtensionRuntime,
719
776
  init_lifecycle,
777
+ dispatchPre2,
778
+ dispatchPost2,
779
+ init_dispatcher,
720
780
  resolveIdentity,
721
781
  renderIdentity,
722
782
  init_identity,
@@ -731,13 +791,6 @@ import {
731
791
  init_transcription,
732
792
  isAgentOnDemand,
733
793
  init_reachability,
734
- nextFallback2,
735
- createWorkerTaskFollowUp2,
736
- createResumeFollowUp2,
737
- init_worker_follow_up,
738
- isGitHubEnabled,
739
- initGitHub,
740
- verifyWebhookSignature,
741
794
  isAgentMailEnabled,
742
795
  initAgentMail,
743
796
  verifyAgentMailWebhook,
@@ -785,6 +838,11 @@ import {
785
838
  handlePullRequestCommentCreated,
786
839
  handlePullRequestClosed,
787
840
  init_bitbucket,
841
+ isGitHubEnabled,
842
+ initGitHub,
843
+ verifyWebhookSignature,
844
+ getWorkerInstallationToken,
845
+ init_app,
788
846
  handlePullRequest,
789
847
  handleIssue,
790
848
  handleComment,
@@ -835,7 +893,7 @@ import {
835
893
  init_webhook_lifecycle,
836
894
  isJiraEnabled,
837
895
  initJira,
838
- init_app,
896
+ init_app2,
839
897
  handleJiraWebhook,
840
898
  init_webhook,
841
899
  init_jira,
@@ -846,7 +904,7 @@ import {
846
904
  init_sync,
847
905
  isLinearEnabled,
848
906
  initLinear,
849
- init_app2,
907
+ init_app3,
850
908
  init_linear,
851
909
  init_slack,
852
910
  verifyPageSession,
@@ -860,12 +918,16 @@ import {
860
918
  init_page_session,
861
919
  resolveHttpRequestAuth,
862
920
  init_auth,
863
- getDeploymentEnvValue,
864
- loadGlobalConfigsIntoEnv,
865
- reloadGlobalConfigsAndIntegrations,
866
- scheduleIntegrationsReload,
867
- handleCore,
921
+ getDeploymentEnvValue2,
922
+ loadGlobalConfigsIntoEnv2,
923
+ reloadGlobalConfigsAndIntegrations2,
924
+ scheduleIntegrationsReload2,
925
+ handleCore2,
868
926
  init_core,
927
+ nextFallback2,
928
+ createWorkerTaskFollowUp2,
929
+ createResumeFollowUp2,
930
+ init_worker_follow_up,
869
931
  MCP_MAX_TOOL_INPUT_ELEMENTS,
870
932
  MCP_MAX_REQUEST_BODY_BYTES,
871
933
  init_mcp_limits,
@@ -962,6 +1024,8 @@ import {
962
1024
  init_access,
963
1025
  getLinksForMemory,
964
1026
  init_links_store,
1027
+ attachDemotionEvidence,
1028
+ init_demotion_evidence,
965
1029
  expandCandidatesWithGraph,
966
1030
  init_graph_expansion,
967
1031
  isApiDraining,
@@ -1044,6 +1108,8 @@ import {
1044
1108
  discardImprovement,
1045
1109
  improvementLeakHints,
1046
1110
  init_improvements,
1111
+ recomputeSessionCost,
1112
+ init_session_cost_recompute,
1047
1113
  canClaim,
1048
1114
  init_budget_admission,
1049
1115
  emitBudgetRefusalSideEffects,
@@ -1063,7 +1129,7 @@ import {
1063
1129
  getEnabledCapabilities,
1064
1130
  createServer,
1065
1131
  init_server
1066
- } from "./cli-2czxfnvj.js";
1132
+ } from "./cli-075ccjh6.js";
1067
1133
  import {
1068
1134
  FilesError,
1069
1135
  normalizeFilesError,
@@ -1095,7 +1161,7 @@ import {
1095
1161
  resolvePoolDelivery2,
1096
1162
  createPoolAgent2,
1097
1163
  init_db2
1098
- } from "./cli-mkwkwq81.js";
1164
+ } from "./cli-8zmpwe79.js";
1099
1165
  import {
1100
1166
  duplicateGuardedQueryKey,
1101
1167
  warnIfCorsAllowsAnyOrigin,
@@ -1152,7 +1218,7 @@ import {
1152
1218
  describeRequestRoute,
1153
1219
  route,
1154
1220
  init_route_def
1155
- } from "./cli-nbt14he0.js";
1221
+ } from "./cli-nc39ym5q.js";
1156
1222
  import {
1157
1223
  startPoolRouting,
1158
1224
  stopPoolRouting,
@@ -1165,28 +1231,28 @@ import {
1165
1231
  checkHeartbeatChecklist2,
1166
1232
  runHeartbeatSweep2,
1167
1233
  stopHeartbeat2
1168
- } from "./cli-m7zvgt57.js";
1169
- import"./cli-mhapr559.js";
1234
+ } from "./cli-b82a13ga.js";
1235
+ import"./cli-yvzxbztc.js";
1170
1236
  import {
1171
1237
  runtimeSupervisorStatus,
1172
1238
  startRuntimeSupervisor,
1173
1239
  stopRuntimeSupervisor
1174
- } from "./cli-sn650d7x.js";
1240
+ } from "./cli-rpmw4fsv.js";
1175
1241
  import {
1176
1242
  TASK_TITLE_TIMEOUT_MS,
1177
1243
  generateTaskTitle
1178
- } from "./cli-gfy38pvt.js";
1244
+ } from "./cli-4kzp7r0q.js";
1179
1245
  import"./cli-ns59dc6r.js";
1180
1246
  import {
1181
1247
  ACP_TARGET_IDS
1182
- } from "./cli-x40a0w9j.js";
1248
+ } from "./cli-r813c7rb.js";
1183
1249
  import {
1184
1250
  reasoningCapability,
1185
1251
  supportedReasoningLevels
1186
- } from "./cli-5gpqgs8b.js";
1252
+ } from "./cli-fwjwkw66.js";
1187
1253
  import {
1188
1254
  MAX_RATE_LIMIT_RESET_MS
1189
- } from "./cli-kpgcm7xy.js";
1255
+ } from "./cli-ramn8jae.js";
1190
1256
  import {
1191
1257
  isLeadChannelMonitoringEnabled,
1192
1258
  ORG_IDENTITY_KEYS,
@@ -1196,7 +1262,7 @@ import {
1196
1262
  isUnknownModelError,
1197
1263
  checkProviderPoolKey,
1198
1264
  writeSkillsToFilesystem
1199
- } from "./cli-f9gz2vyj.js";
1265
+ } from "./cli-2jtfm8kh.js";
1200
1266
  import {
1201
1267
  AgentFsRequestError2,
1202
1268
  resolveAgentFsSharedContext2,
@@ -1206,10 +1272,20 @@ import {
1206
1272
  roleRank2,
1207
1273
  agentFsRequest2,
1208
1274
  resolveApiUrl2
1209
- } from "./cli-fh97xn30.js";
1275
+ } from "./cli-2gvdvsxj.js";
1210
1276
  import {
1211
1277
  Anthropic
1212
- } from "./cli-t9ga4qmb.js";
1278
+ } from "./cli-p8zqbbt1.js";
1279
+ import"./cli-rwgwen5v.js";
1280
+ import {
1281
+ createUserMergeJob2,
1282
+ getUserMergeJob2,
1283
+ listUserMergeJobs2,
1284
+ findActiveUserMergeJob2,
1285
+ findFailedUserMergeJob2,
1286
+ requeueUserMergeJob2,
1287
+ runUserMergeJobs2
1288
+ } from "./cli-q71g5q39.js";
1213
1289
  import {
1214
1290
  isCodexOAuthConfigKey
1215
1291
  } from "./cli-j4bwnpkm.js";
@@ -1220,13 +1296,13 @@ import {
1220
1296
  import {
1221
1297
  runTaskUiAction,
1222
1298
  init_actions
1223
- } from "./cli-f8x9drqr.js";
1299
+ } from "./cli-9knhkkgr.js";
1224
1300
  import {
1225
1301
  RATING_MODEL_MAX_LENGTH,
1226
1302
  REFERENCES_SOURCE_MAX_LENGTH,
1227
1303
  sanitizeReferencesSource,
1228
1304
  init_types2
1229
- } from "./cli-2xv18ywz.js";
1305
+ } from "./cli-bmqp0ser.js";
1230
1306
  import {
1231
1307
  require_dist,
1232
1308
  getMcpOAuthToken,
@@ -1315,7 +1391,7 @@ import {
1315
1391
  init_typecheck,
1316
1392
  parseSkillContent,
1317
1393
  init_skill_parser
1318
- } from "./cli-2yjj3e31.js";
1394
+ } from "./cli-wz4e5am2.js";
1319
1395
  import {
1320
1396
  signalProcessGroup,
1321
1397
  detachedProcessGroup,
@@ -1332,8 +1408,8 @@ import {
1332
1408
  forceRefreshAuthorizationOrThrow,
1333
1409
  forceRefreshTokenOrThrow,
1334
1410
  init_ensure_token
1335
- } from "./cli-jm0hvmz2.js";
1336
- import"./cli-br0924pw.js";
1411
+ } from "./cli-4aswccje.js";
1412
+ import"./cli-v3zcnr8g.js";
1337
1413
  import {
1338
1414
  automationIntegrationFixUrl,
1339
1415
  preflightAutomation,
@@ -1352,7 +1428,7 @@ import {
1352
1428
  definitionNodeIds,
1353
1429
  validateDefinition,
1354
1430
  init_definition2
1355
- } from "./cli-j7svy295.js";
1431
+ } from "./cli-m00c47q6.js";
1356
1432
  import {
1357
1433
  _fetchHolder,
1358
1434
  CLIENT_ID,
@@ -1368,7 +1444,7 @@ import {
1368
1444
  loadAllCodexOAuthSlots,
1369
1445
  getValidCodexOAuth,
1370
1446
  init_storage
1371
- } from "./cli-7sf9sb0w.js";
1447
+ } from "./cli-w5dar1bk.js";
1372
1448
  import {
1373
1449
  isMultiRuntimeEnabled,
1374
1450
  init_multi_runtime2
@@ -1380,7 +1456,7 @@ import {
1380
1456
  import {
1381
1457
  createRuntimeProvider,
1382
1458
  init_runtime_providers
1383
- } from "./cli-6945ywhr.js";
1459
+ } from "./cli-zqq57pgx.js";
1384
1460
  import {
1385
1461
  require_content_type
1386
1462
  } from "./cli-1jx0srjt.js";
@@ -1402,12 +1478,12 @@ import {
1402
1478
  revokeMcpToken,
1403
1479
  computeExpiresAt,
1404
1480
  init_mcp_wrapper
1405
- } from "./cli-2dq9yv8p.js";
1481
+ } from "./cli-t2s7j5cy.js";
1406
1482
  import"./cli-v41kn3cd.js";
1407
1483
  import {
1408
1484
  setBedrockProviderModule,
1409
1485
  init_bedrock_converse_stream_lazy
1410
- } from "./cli-54vrpgm0.js";
1486
+ } from "./cli-k3facve0.js";
1411
1487
  import {
1412
1488
  import_websocket,
1413
1489
  import_websocket_server,
@@ -1427,7 +1503,9 @@ import {
1427
1503
  unlinkIdentity,
1428
1504
  mintToken,
1429
1505
  revokeToken,
1430
- resolveUserByToken,
1506
+ revokeAllUserCredentials,
1507
+ resolveUserToken,
1508
+ isLiveUserToken,
1431
1509
  InvalidRuntimeTokenError,
1432
1510
  mintSessionToken,
1433
1511
  mintRuntimeToken,
@@ -1439,13 +1517,7 @@ import {
1439
1517
  revokeAgentTokens,
1440
1518
  fingerprintApiKey,
1441
1519
  init_users
1442
- } from "./cli-v57d7fmm.js";
1443
- import {
1444
- AMP_ESTIMATE_MODELS,
1445
- ampBillsCacheWrites,
1446
- resolveAmpModel,
1447
- init_amp_models
1448
- } from "./cli-mjw0yf82.js";
1520
+ } from "./cli-yzxqwcvq.js";
1449
1521
  import {
1450
1522
  MAX_PROVIDER_QUOTA_ENTRIES,
1451
1523
  ProviderQuotaCapacityError,
@@ -1454,7 +1526,15 @@ import {
1454
1526
  providerAccountTelemetrySchema,
1455
1527
  rateLimitReplacementSchema,
1456
1528
  init_provider_account_telemetry
1457
- } from "./cli-43ms35q9.js";
1529
+ } from "./cli-k3c13za2.js";
1530
+ import {
1531
+ resolveGitHubHost,
1532
+ init_github_host
1533
+ } from "./cli-9ttx00s3.js";
1534
+ import {
1535
+ CORE_TOOLS,
1536
+ init_tool_config
1537
+ } from "./cli-0b4zam62.js";
1458
1538
  import {
1459
1539
  CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1460
1540
  CODEX_AUTH_WATCH_NAMESPACE,
@@ -1495,6 +1575,7 @@ import {
1495
1575
  ModelProfileNameSchema,
1496
1576
  ModelProfileCredentialsSchema,
1497
1577
  ModelProfileSchema,
1578
+ ModelGroupSchema,
1498
1579
  ProviderErrorClassSchema,
1499
1580
  ProfileCheckResultSchema,
1500
1581
  SessionAccessSchema,
@@ -1510,6 +1591,8 @@ import {
1510
1591
  AgentTaskSchema,
1511
1592
  TaskAttachmentSchema,
1512
1593
  UserSchema,
1594
+ UserMergeJobStatusSchema,
1595
+ UserMergeJobSchema,
1513
1596
  RbacRoleSchema,
1514
1597
  UserRbacRolesSchema,
1515
1598
  UserCommsPrefsSchema,
@@ -1615,6 +1698,9 @@ import {
1615
1698
  ContextSnapshotEventTypeSchema,
1616
1699
  ContextFormulaSchema,
1617
1700
  ContextSnapshotSchema,
1701
+ RequestCompositionPartInputSchema,
1702
+ RequestCompositionToolLoadingSchema,
1703
+ RequestCompositionSchema,
1618
1704
  BudgetScopeSchema,
1619
1705
  BudgetSchema,
1620
1706
  PricingProviderSchema,
@@ -1627,34 +1713,26 @@ import {
1627
1713
  KvKeySchema,
1628
1714
  KvEntrySchema,
1629
1715
  init_types5
1630
- } from "./cli-bkjdknnp.js";
1631
- import {
1632
- resolveGitHubHost,
1633
- init_github_host
1634
- } from "./cli-9ttx00s3.js";
1716
+ } from "./cli-1h4njv9y.js";
1635
1717
  import {
1636
1718
  IDENTITY_FIELD_BUDGETS,
1637
1719
  IdentityFieldBudgetError,
1638
1720
  init_identity_field_budget
1639
- } from "./cli-m7c2380k.js";
1640
- import {
1641
- getSlackConfiguration,
1642
- init_config4
1643
- } from "./cli-eetzmsy5.js";
1721
+ } from "./cli-mhrr4d5b.js";
1644
1722
  import {
1645
1723
  isSteeringEnabled2,
1646
1724
  init_steering_enabled
1647
1725
  } from "./cli-4sydckyj.js";
1726
+ import {
1727
+ getSlackConfiguration,
1728
+ init_config4
1729
+ } from "./cli-eetzmsy5.js";
1648
1730
  import {
1649
1731
  SUBSCRIPTION_PLANS_CHECKED_AT,
1650
1732
  SUBSCRIPTION_PLANS,
1651
1733
  isSubscriptionPlanId,
1652
1734
  init_subscription_plans
1653
1735
  } from "./cli-nh7x3133.js";
1654
- import {
1655
- getOpenRouterAttributionHeaders,
1656
- init_openrouter_base_url
1657
- } from "./cli-dfyv0jdy.js";
1658
1736
  import {
1659
1737
  MODEL_SCOPED_WINDOWS,
1660
1738
  KEY_WIDE_WINDOWS,
@@ -1668,7 +1746,11 @@ import {
1668
1746
  splitCredentialPool,
1669
1747
  selectCredential,
1670
1748
  init_credentials2
1671
- } from "./cli-psffsanb.js";
1749
+ } from "./cli-ha4ek2nb.js";
1750
+ import {
1751
+ getOpenRouterAttributionHeaders,
1752
+ init_openrouter_base_url
1753
+ } from "./cli-dfyv0jdy.js";
1672
1754
  import {
1673
1755
  interpolate,
1674
1756
  init_template2,
@@ -1678,10 +1760,10 @@ import {
1678
1760
  resolveTemplate,
1679
1761
  init_resolver,
1680
1762
  init_session_templates
1681
- } from "./cli-6ehs4mta.js";
1763
+ } from "./cli-2z2c4k6q.js";
1682
1764
  import {
1683
1765
  init_zod
1684
- } from "./cli-zcfpsfzf.js";
1766
+ } from "./cli-96234j5w.js";
1685
1767
  import {
1686
1768
  NEVER,
1687
1769
  toJSONSchema,
@@ -1708,7 +1790,7 @@ import {
1708
1790
  ZodIssueCode,
1709
1791
  exports_iso,
1710
1792
  exports_coerce
1711
- } from "./cli-hg42n3hx.js";
1793
+ } from "./cli-qrzq3hvg.js";
1712
1794
  import {
1713
1795
  MAX_PROFILE_FILE_LENGTH,
1714
1796
  DEFAULT_APP_URL,
@@ -1731,7 +1813,7 @@ import {
1731
1813
  import {
1732
1814
  init_package,
1733
1815
  package_default
1734
- } from "./cli-h9yqfzx9.js";
1816
+ } from "./cli-a6q6x15h.js";
1735
1817
  import {
1736
1818
  realtimeBus,
1737
1819
  init_bus
@@ -1747,7 +1829,7 @@ import {
1747
1829
  registerVolatileSecret,
1748
1830
  registerEnvSecrets,
1749
1831
  init_secret_scrubber
1750
- } from "./cli-5a6pqy45.js";
1832
+ } from "./cli-7e8sxqv5.js";
1751
1833
  import {
1752
1834
  __toESM
1753
1835
  } from "./cli-242037k3.js";
@@ -1815,8 +1897,71 @@ init_types5();
1815
1897
  init_env_flag();
1816
1898
  init_secret_scrubber();
1817
1899
  init_db4();
1818
- init_swarm_config_guard();
1819
1900
  import { AsyncLocalStorage } from "node:async_hooks";
1901
+
1902
+ // src/be/db/workflow-run-retention.ts
1903
+ init_runtime2();
1904
+ init_human_free();
1905
+ init_workflow_run_definitions();
1906
+ init_workflow_runs();
1907
+ var TERMINAL_SQL = "('completed', 'failed', 'skipped', 'cancelled')";
1908
+ var ELIGIBLE_SQL = `r.status IN ${TERMINAL_SQL} AND r.finishedAt < ?1
1909
+ AND NOT EXISTS (SELECT 1 FROM workflow_run_steps parent WHERE parent.id = r.parentStepId)
1910
+ AND NOT EXISTS (
1911
+ WITH RECURSIVE descendants(id, status, finishedAt, depth) AS (
1912
+ SELECT r.id, r.status, r.finishedAt, 0
1913
+ UNION ALL
1914
+ SELECT child.id, child.status, child.finishedAt, descendants.depth + 1
1915
+ FROM descendants
1916
+ JOIN workflow_run_steps step ON step.runId = descendants.id
1917
+ JOIN workflow_runs child ON child.parentStepId = step.id
1918
+ WHERE descendants.depth < ${WORKFLOW_RUN_TREE_MAX_DEPTH}
1919
+ )
1920
+ SELECT 1 FROM descendants
1921
+ WHERE status NOT IN ${TERMINAL_SQL} OR finishedAt IS NULL OR finishedAt >= ?1
1922
+ OR depth = ${WORKFLOW_RUN_TREE_MAX_DEPTH}
1923
+ )`;
1924
+ var WORKFLOW_RETENTION_CANDIDATES_SQL = `SELECT r.id, r.definitionHash
1925
+ FROM workflow_runs r WHERE ${ELIGIBLE_SQL} ORDER BY r.finishedAt, r.id LIMIT ?2`;
1926
+ function workflowRunRetentionStatements(cutoff) {
1927
+ return {
1928
+ backlogSql: `SELECT COUNT(*) AS n FROM workflow_runs r WHERE ${ELIGIBLE_SQL}`,
1929
+ deleteSql: `DELETE FROM workflow_runs WHERE id IN (
1930
+ SELECT r.id FROM workflow_runs r WHERE ${ELIGIBLE_SQL}
1931
+ ORDER BY r.finishedAt, r.id LIMIT ?2
1932
+ )`,
1933
+ params: [cutoff]
1934
+ };
1935
+ }
1936
+ async function deleteWorkflowRunRetentionBatch(cutoff, limit, deadlineAt) {
1937
+ const client = getDbClient2();
1938
+ return await client.transaction(async (tx) => {
1939
+ const started = performance.now();
1940
+ const runs = await tx.query(WORKFLOW_RETENTION_CANDIDATES_SQL, [cutoff, limit]);
1941
+ if (runs.length === 0)
1942
+ return { changes: 0, executionMs: performance.now() - started };
1943
+ const ids = JSON.stringify(runs.map((run) => run.id));
1944
+ const runIds = "SELECT value FROM json_each(?)";
1945
+ const stepIds = `SELECT id FROM workflow_run_steps WHERE runId IN (${runIds})`;
1946
+ const taskWhere = `workflowRunId IN (${runIds}) OR workflowRunStepId IN (${stepIds})`;
1947
+ const tasks = await tx.query(`SELECT id FROM agent_tasks WHERE ${taskWhere}`, [ids, ids]);
1948
+ await tx.run(`UPDATE agent_tasks SET workflowRunId = NULL, workflowRunStepId = NULL WHERE ${taskWhere}`, [ids, ids]);
1949
+ for (const table of ["approval_requests", "wait_states"]) {
1950
+ await tx.run(`DELETE FROM ${table} WHERE workflowRunId IN (${runIds}) OR workflowRunStepId IN (${stepIds})`, [ids, ids]);
1951
+ }
1952
+ await tx.run(`DELETE FROM workflow_run_steps WHERE runId IN (${runIds})`, [ids]);
1953
+ await tx.run(`DELETE FROM workflow_runs WHERE id IN (${runIds})`, [ids]);
1954
+ await reclassifyTaskHumanFree(tasks.map((task) => task.id));
1955
+ await deleteOrphanedRunDefinitions([
1956
+ ...new Set(runs.flatMap((run) => run.definitionHash ? [run.definitionHash] : []))
1957
+ ]);
1958
+ return { changes: runs.length, executionMs: performance.now() - started };
1959
+ }, { deadlineAt });
1960
+ }
1961
+
1962
+ // src/be/db-retention.ts
1963
+ init_db_client();
1964
+ init_swarm_config_guard();
1820
1965
  var DAY_MS = 24 * 60 * 60 * 1000;
1821
1966
  var RETENTION_INTERVAL_MS = 60 * 60 * 1000;
1822
1967
  var DEFAULT_TICK_BUDGET_MS = 30000;
@@ -1832,6 +1977,7 @@ var DB_RETENTION_TABLES = [
1832
1977
  policy: "age",
1833
1978
  timeColumn: "createdAt",
1834
1979
  envKey: "SESSION_LOG_RETENTION_DAYS",
1980
+ newInstallDefault: 30,
1835
1981
  metricsKey: "sessionLogs"
1836
1982
  },
1837
1983
  {
@@ -1839,6 +1985,7 @@ var DB_RETENTION_TABLES = [
1839
1985
  policy: "age",
1840
1986
  timeColumn: "createdAt",
1841
1987
  envKey: "AGENT_LOG_RETENTION_DAYS",
1988
+ newInstallDefault: 90,
1842
1989
  metricsKey: "agentLog"
1843
1990
  },
1844
1991
  {
@@ -1846,6 +1993,7 @@ var DB_RETENTION_TABLES = [
1846
1993
  policy: "age",
1847
1994
  timeColumn: "createdAt",
1848
1995
  envKey: "EVENTS_RETENTION_DAYS",
1996
+ newInstallDefault: 90,
1849
1997
  metricsKey: "events"
1850
1998
  },
1851
1999
  {
@@ -1854,6 +2002,7 @@ var DB_RETENTION_TABLES = [
1854
2002
  partitionBy: "agentId, field",
1855
2003
  rankBy: "version",
1856
2004
  envKey: "CONTEXT_VERSIONS_KEEP_LATEST",
2005
+ newInstallDefault: 100,
1857
2006
  metricsKey: "contextVersions",
1858
2007
  initialBatchSize: 50,
1859
2008
  maxBatchSize: 100
@@ -1867,9 +2016,19 @@ var DB_RETENTION_TABLES = [
1867
2016
  terminalStatuses: TERMINAL_SCRIPT_RUN_STATUSES,
1868
2017
  keepWhenSet: "idempotencyKey",
1869
2018
  envKey: "SCRIPT_RUNS_RETENTION_DAYS",
2019
+ newInstallDefault: 30,
1870
2020
  metricsKey: "scriptRuns",
1871
2021
  initialBatchSize: 100,
1872
2022
  maxBatchSize: 500
2023
+ },
2024
+ {
2025
+ table: "workflow_runs",
2026
+ policy: "workflowRuns",
2027
+ envKey: "WORKFLOW_RUNS_RETENTION_DAYS",
2028
+ metricsKey: "workflowRuns",
2029
+ initialBatchSize: 10,
2030
+ minBatchSize: 1,
2031
+ maxBatchSize: 100
1873
2032
  }
1874
2033
  ];
1875
2034
 
@@ -1993,6 +2152,10 @@ function maxBatchSize(table) {
1993
2152
  return "maxBatchSize" in table ? table.maxBatchSize : MAX_BATCH_SIZE;
1994
2153
  }
1995
2154
  function sweepStatements(table, value, now) {
2155
+ if (table.policy === "workflowRuns") {
2156
+ const iso = new Date(now.getTime() - value * DAY_MS).toISOString();
2157
+ return workflowRunRetentionStatements(`${iso.slice(0, 10)} ${iso.slice(11, 19)}`);
2158
+ }
1996
2159
  if (table.policy === "keepLatest") {
1997
2160
  const ranked = `SELECT rowid AS rid, ROW_NUMBER() OVER (PARTITION BY ${table.partitionBy} ORDER BY ${table.rankBy} DESC) AS rn FROM ${table.table}`;
1998
2161
  return {
@@ -2053,21 +2216,30 @@ async function sweepTable(table, statements, dryRun, deadline, signal, maxStatem
2053
2216
  let slowestStatementMs = 0;
2054
2217
  let size = batchSizeByTable[table.metricsKey] ?? initialBatchSize(table);
2055
2218
  const ceiling = maxBatchSize(table);
2219
+ const floor = "minBatchSize" in table ? table.minBatchSize : MIN_BATCH_SIZE;
2056
2220
  try {
2057
2221
  while (!signal.aborted && Date.now() < deadline) {
2058
2222
  const limitUsed = size;
2059
- const result = await client.runTimed(statements.deleteSql, [...statements.params, limitUsed]);
2223
+ let result;
2224
+ try {
2225
+ result = table.policy === "workflowRuns" ? await deleteWorkflowRunRetentionBatch(String(statements.params[0]), limitUsed, deadline) : await client.runTimed(statements.deleteSql, [...statements.params, limitUsed]);
2226
+ } catch (err) {
2227
+ if (table.policy !== "workflowRuns" || !(err instanceof DbTransactionDeadlineError))
2228
+ throw err;
2229
+ size = Math.max(floor, Math.floor(size / 2));
2230
+ break;
2231
+ }
2060
2232
  const elapsed = result.executionMs;
2061
2233
  bestEffortRecordStatement(table.table, dryRun, elapsed);
2062
2234
  slowestStatementMs = Math.max(slowestStatementMs, elapsed);
2063
2235
  rowsDeleted += result.changes;
2064
2236
  batches += 1;
2065
2237
  if (elapsed > maxStatementMs) {
2066
- size = Math.max(MIN_BATCH_SIZE, Math.floor(size / 2));
2238
+ size = Math.max(floor, Math.floor(size / 2));
2067
2239
  } else if (elapsed < maxStatementMs / 5) {
2068
2240
  size = Math.min(ceiling, size * 2);
2069
2241
  }
2070
- if (result.changes < limitUsed)
2242
+ if (result.changes === 0 || table.policy !== "workflowRuns" && result.changes < limitUsed)
2071
2243
  break;
2072
2244
  if (signal.aborted || Date.now() >= deadline)
2073
2245
  break;
@@ -2335,6 +2507,35 @@ async function stopDbRetention() {
2335
2507
  await retentionTickPromise;
2336
2508
  }
2337
2509
 
2510
+ // src/be/db-retention-defaults.ts
2511
+ init_db4();
2512
+ init_runtime2();
2513
+ async function seedDbRetentionDefaults(isNewInstall = wasDbCreatedThisBoot()) {
2514
+ if (!isNewInstall)
2515
+ return [];
2516
+ const seeded = [];
2517
+ await getDbClient2().transaction(async () => {
2518
+ for (const table of DB_RETENTION_TABLES) {
2519
+ if (!("newInstallDefault" in table) || process.env[table.envKey] !== undefined)
2520
+ continue;
2521
+ const existing = await getSwarmConfigs2({ scope: "global", key: table.envKey });
2522
+ if (existing.length > 0)
2523
+ continue;
2524
+ await upsertSwarmConfig2({
2525
+ scope: "global",
2526
+ key: table.envKey,
2527
+ value: String(table.newInstallDefault),
2528
+ description: `New-install default: ${table.table} retention. Rows past it are permanently deleted. Delete this entry to turn the sweep off.`
2529
+ });
2530
+ seeded.push(`${table.envKey}=${table.newInstallDefault}`);
2531
+ }
2532
+ });
2533
+ if (seeded.length > 0) {
2534
+ console.log(`[startup] New database: stored default retention (${seeded.join(", ")}). Rows past these limits are permanently deleted; change or delete each key in Settings → Configuration.`);
2535
+ }
2536
+ return seeded;
2537
+ }
2538
+
2338
2539
  // src/http/index.ts
2339
2540
  init_event_loop_lag();
2340
2541
 
@@ -2394,6 +2595,489 @@ function stopHumanFreeDrain() {
2394
2595
  passTimer = null;
2395
2596
  }
2396
2597
 
2598
+ // src/be/mcp-events/dispatcher.ts
2599
+ init_db4();
2600
+ init_users();
2601
+ init_constants3();
2602
+ init_secret_scrubber();
2603
+ init_event_bus();
2604
+ import { createHash as createHash2 } from "node:crypto";
2605
+
2606
+ // src/be/mcp-events/catalog.ts
2607
+ init_env_flag();
2608
+ var EVENTS_EXTENSION_ID = "io.modelcontextprotocol/events";
2609
+ function isMcpUserEventsEnabled(env = process.env) {
2610
+ return parseEnvFlag(env.MCP_USER_EVENTS_ENABLED, true);
2611
+ }
2612
+ var EventsErrorCode = {
2613
+ InvalidParams: -32602,
2614
+ NotFound: -32023,
2615
+ Forbidden: -32024,
2616
+ ResourceExhausted: -32025,
2617
+ Unsupported: -32026,
2618
+ CallbackEndpointError: -32027
2619
+ };
2620
+ var ARGUMENTS_SCHEMA = {
2621
+ type: "object",
2622
+ properties: {
2623
+ taskId: {
2624
+ type: "string",
2625
+ description: "Only this task and the tasks created under it. Omit to receive every task you requested."
2626
+ }
2627
+ },
2628
+ additionalProperties: false
2629
+ };
2630
+ var BASE_PAYLOAD_PROPERTIES = {
2631
+ taskId: { type: "string" },
2632
+ parentTaskId: { type: ["string", "null"] },
2633
+ status: { type: "string" },
2634
+ task: { type: "string", description: "The task description, truncated." },
2635
+ url: { type: "string", description: "Dashboard link to the task." }
2636
+ };
2637
+ var EVENT_DESCRIPTORS = [
2638
+ {
2639
+ name: "task.completed",
2640
+ description: "Fires when a task you requested completes. Read the full result with get-task-details.",
2641
+ delivery: ["webhook"],
2642
+ inputSchema: ARGUMENTS_SCHEMA,
2643
+ payloadSchema: {
2644
+ type: "object",
2645
+ properties: {
2646
+ ...BASE_PAYLOAD_PROPERTIES,
2647
+ output: { type: "string", description: "The task output, truncated." },
2648
+ truncated: { type: "boolean" }
2649
+ },
2650
+ required: ["taskId", "status", "url"]
2651
+ }
2652
+ },
2653
+ {
2654
+ name: "task.failed",
2655
+ description: "Fires when a task you requested fails. Read the details with get-task-details.",
2656
+ delivery: ["webhook"],
2657
+ inputSchema: ARGUMENTS_SCHEMA,
2658
+ payloadSchema: {
2659
+ type: "object",
2660
+ properties: {
2661
+ ...BASE_PAYLOAD_PROPERTIES,
2662
+ failureReason: { type: "string", description: "Why the task failed, truncated." },
2663
+ truncated: { type: "boolean" }
2664
+ },
2665
+ required: ["taskId", "status", "url"]
2666
+ }
2667
+ }
2668
+ ];
2669
+ function isTaskEventName(name) {
2670
+ return name === "task.completed" || name === "task.failed";
2671
+ }
2672
+ function parseTaskEventArguments(raw) {
2673
+ if (raw === undefined || raw === null)
2674
+ return {};
2675
+ if (typeof raw !== "object" || Array.isArray(raw))
2676
+ return null;
2677
+ const entries = Object.entries(raw);
2678
+ const out = {};
2679
+ for (const [key, value] of entries) {
2680
+ if (key !== "taskId")
2681
+ return null;
2682
+ if (typeof value !== "string" || value.length === 0 || value.length > 200)
2683
+ return null;
2684
+ out.taskId = value;
2685
+ }
2686
+ return out;
2687
+ }
2688
+
2689
+ // src/be/mcp-events/store.ts
2690
+ init_crypto();
2691
+ init_db4();
2692
+ import { createHash } from "node:crypto";
2693
+ function canonicalJson(value) {
2694
+ if (value === null || typeof value !== "object")
2695
+ return JSON.stringify(value);
2696
+ if (Array.isArray(value))
2697
+ return `[${value.map(canonicalJson).join(",")}]`;
2698
+ const entries = Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2699
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
2700
+ }
2701
+ function subscriptionIdFor(userId, url, eventName, argumentsJson) {
2702
+ const digest = createHash("sha256").update(canonicalJson([userId, url, eventName, argumentsJson])).digest("hex");
2703
+ return `sub_${digest.slice(0, 32)}`;
2704
+ }
2705
+ function sealSecret(secret) {
2706
+ return encryptSecret(secret, getEncryptionKey());
2707
+ }
2708
+ function unsealSecret(sealed) {
2709
+ return decryptSecret(sealed, getEncryptionKey());
2710
+ }
2711
+ async function getSubscription(id) {
2712
+ return getDbClient2().get("SELECT * FROM mcp_event_subscriptions WHERE id = ?", [
2713
+ id
2714
+ ]);
2715
+ }
2716
+ async function countLiveSubscriptions(userId, nowIso) {
2717
+ const row = await getDbClient2().get("SELECT COUNT(*) AS n FROM mcp_event_subscriptions WHERE userId = ? AND expiresAt > ?", [userId, nowIso]);
2718
+ return row?.n ?? 0;
2719
+ }
2720
+ async function latestVerification(userId, url, sinceIso, nowIso) {
2721
+ const row = await getDbClient2().get(`SELECT MAX(verifiedAt) AS verifiedAt FROM mcp_event_subscriptions
2722
+ WHERE userId = ? AND url = ? AND verifiedAt > ? AND expiresAt > ?`, [userId, url, sinceIso, nowIso]);
2723
+ return row?.verifiedAt ?? null;
2724
+ }
2725
+ async function deleteExpiredSubscriptions(nowIso) {
2726
+ const result = await getDbClient2().run("DELETE FROM mcp_event_subscriptions WHERE expiresAt <= ?", [nowIso]);
2727
+ return result.changes;
2728
+ }
2729
+ async function upsertSubscription(input) {
2730
+ const sealed = sealSecret(input.secret);
2731
+ return getDbClient2().transaction(async (tx) => {
2732
+ const existing = await tx.get("SELECT * FROM mcp_event_subscriptions WHERE id = ?", [input.id]);
2733
+ if (!existing || existing.expiresAt <= input.nowIso) {
2734
+ const live = await tx.get(`SELECT COUNT(*) AS n FROM mcp_event_subscriptions
2735
+ WHERE userId = ? AND expiresAt > ? AND id != ?`, [input.userId, input.nowIso, input.id]);
2736
+ if ((live?.n ?? 0) >= input.maxActivePerUser)
2737
+ return "limit";
2738
+ }
2739
+ if (!existing) {
2740
+ await tx.run(`INSERT INTO mcp_event_subscriptions
2741
+ (id, userId, tokenId, eventName, argumentsJson, url, secretSealed, verifiedAt,
2742
+ expiresAt, createdAt, updatedAt, created_by, updated_by)
2743
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
2744
+ input.id,
2745
+ input.userId,
2746
+ input.tokenId,
2747
+ input.eventName,
2748
+ input.argumentsJson,
2749
+ input.url,
2750
+ sealed,
2751
+ input.verifiedAt,
2752
+ input.expiresAt,
2753
+ input.nowIso,
2754
+ input.nowIso,
2755
+ input.userId,
2756
+ input.userId
2757
+ ]);
2758
+ } else {
2759
+ const rotated = unsealSecret(existing.secretSealed) !== input.secret;
2760
+ await tx.run(`UPDATE mcp_event_subscriptions
2761
+ SET tokenId = ?,
2762
+ secretSealed = ?,
2763
+ previousSecretSealed = ?,
2764
+ previousSecretUntil = ?,
2765
+ verifiedAt = ?,
2766
+ expiresAt = ?,
2767
+ updatedAt = ?,
2768
+ updated_by = ?
2769
+ WHERE id = ?`, [
2770
+ input.tokenId,
2771
+ sealed,
2772
+ rotated ? existing.secretSealed : existing.previousSecretSealed,
2773
+ rotated ? input.rotationGraceUntil : existing.previousSecretUntil,
2774
+ input.verifiedAt,
2775
+ input.expiresAt,
2776
+ input.nowIso,
2777
+ input.userId,
2778
+ input.id
2779
+ ]);
2780
+ }
2781
+ const row = await tx.get("SELECT * FROM mcp_event_subscriptions WHERE id = ?", [input.id]);
2782
+ if (!row)
2783
+ throw new Error(`subscription ${input.id} vanished during upsert`);
2784
+ return row;
2785
+ });
2786
+ }
2787
+ async function deleteSubscription(id, userId) {
2788
+ const result = await getDbClient2().run("DELETE FROM mcp_event_subscriptions WHERE id = ? AND userId = ?", [id, userId]);
2789
+ return result.changes > 0;
2790
+ }
2791
+ async function listLiveSubscriptions(userId, eventName, nowIso) {
2792
+ return getDbClient2().query(`SELECT * FROM mcp_event_subscriptions
2793
+ WHERE userId = ? AND eventName = ? AND expiresAt > ?`, [userId, eventName, nowIso]);
2794
+ }
2795
+ async function recordDeliveryOutcome(id, outcome) {
2796
+ if (outcome.ok) {
2797
+ await getDbClient2().run(`UPDATE mcp_event_subscriptions
2798
+ SET lastDeliveryAt = ?, lastError = NULL, failedSince = NULL
2799
+ WHERE id = ?`, [outcome.atIso, id]);
2800
+ return;
2801
+ }
2802
+ await getDbClient2().run(`UPDATE mcp_event_subscriptions
2803
+ SET lastError = ?, failedSince = COALESCE(failedSince, ?)
2804
+ WHERE id = ?`, [outcome.category, outcome.atIso, id]);
2805
+ }
2806
+
2807
+ // src/be/mcp-events/webhook.ts
2808
+ init_egress_guard();
2809
+ init_env_flag();
2810
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2811
+ var SECRET_PREFIX = "whsec_";
2812
+ var MIN_SECRET_BYTES = 24;
2813
+ var MAX_SECRET_BYTES = 64;
2814
+ var BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
2815
+ var DELIVERY_TIMEOUT_MS = 1e4;
2816
+ var MAX_DELIVERY_BODY_BYTES = 256 * 1024;
2817
+ var MAX_CHALLENGE_RESPONSE_BYTES = 4096;
2818
+ var testOverrides = null;
2819
+ function allowPrivateCallbacks() {
2820
+ return parseEnvFlag(process.env.MCP_USER_EVENTS_ALLOW_PRIVATE_CALLBACKS, false);
2821
+ }
2822
+ function parseWebhookSecret(secret) {
2823
+ if (typeof secret !== "string" || !secret.startsWith(SECRET_PREFIX))
2824
+ return null;
2825
+ const encoded = secret.slice(SECRET_PREFIX.length);
2826
+ if (encoded.length === 0 || encoded.length % 4 !== 0 || !BASE64.test(encoded))
2827
+ return null;
2828
+ const bytes = Buffer.from(encoded, "base64");
2829
+ if (bytes.length < MIN_SECRET_BYTES || bytes.length > MAX_SECRET_BYTES)
2830
+ return null;
2831
+ return bytes;
2832
+ }
2833
+ function callbackUrlProblem(rawUrl) {
2834
+ if (typeof rawUrl !== "string" || rawUrl.length === 0)
2835
+ return "delivery.url is required";
2836
+ if (rawUrl.length > 2048)
2837
+ return "delivery.url is too long";
2838
+ let parsed;
2839
+ try {
2840
+ parsed = assertUrlSafe(rawUrl, {
2841
+ allowInsecure: allowPrivateCallbacks() || testOverrides?.allowInsecure === true,
2842
+ allowPrivateHosts: allowPrivateCallbacks() || testOverrides?.guard?.policy?.allowPrivate === true
2843
+ });
2844
+ } catch (error) {
2845
+ return error instanceof Error ? error.message : "delivery.url is not allowed";
2846
+ }
2847
+ if (parsed.username || parsed.password)
2848
+ return "delivery.url must not carry credentials";
2849
+ return null;
2850
+ }
2851
+ function signWebhook(secrets, webhookId, timestampSec, body) {
2852
+ const content = `${webhookId}.${timestampSec}.${body}`;
2853
+ return secrets.map((secret) => `v1,${createHmac("sha256", secret).update(content).digest("base64")}`).join(" ");
2854
+ }
2855
+ function guardedFetch() {
2856
+ return createGuardedFetch(testOverrides?.baseFetch ?? fetch, {
2857
+ policy: { allowPrivate: allowPrivateCallbacks(), allowlist: null },
2858
+ ...testOverrides?.guard
2859
+ });
2860
+ }
2861
+ function categorize(error) {
2862
+ if (error instanceof EgressDeniedError)
2863
+ return "connection_refused";
2864
+ const name = error instanceof Error ? error.name : "";
2865
+ const message = error instanceof Error ? `${error.message} ${String(error.cause ?? "")}` : "";
2866
+ if (name === "TimeoutError" || name === "AbortError" || /timed? ?out/i.test(message)) {
2867
+ return "timeout";
2868
+ }
2869
+ if (/certificate|tls|ssl|self.signed|handshake/i.test(message))
2870
+ return "tls_error";
2871
+ return "connection_refused";
2872
+ }
2873
+ async function readCapped(response, maxBytes) {
2874
+ const reader = response.body?.getReader();
2875
+ if (!reader)
2876
+ return "";
2877
+ const chunks = [];
2878
+ let total = 0;
2879
+ while (total < maxBytes) {
2880
+ const { done, value } = await reader.read();
2881
+ if (done)
2882
+ break;
2883
+ chunks.push(value);
2884
+ total += value.byteLength;
2885
+ }
2886
+ await reader.cancel().catch(() => {});
2887
+ return new TextDecoder().decode(Buffer.concat(chunks).subarray(0, maxBytes));
2888
+ }
2889
+ async function postSignedWebhook(input) {
2890
+ const timestampSec = Math.floor(Date.now() / 1000);
2891
+ let response;
2892
+ try {
2893
+ response = await guardedFetch()(input.url, {
2894
+ method: "POST",
2895
+ redirect: "error",
2896
+ signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),
2897
+ headers: {
2898
+ "Content-Type": "application/json",
2899
+ "webhook-id": input.webhookId,
2900
+ "webhook-timestamp": String(timestampSec),
2901
+ "webhook-signature": signWebhook(input.secrets, input.webhookId, timestampSec, input.body),
2902
+ "X-MCP-Subscription-Id": input.subscriptionId
2903
+ },
2904
+ body: input.body
2905
+ });
2906
+ } catch (error) {
2907
+ return { ok: false, category: categorize(error) };
2908
+ }
2909
+ if (response.status >= 200 && response.status < 300) {
2910
+ const text = input.readBody ? await readCapped(response, MAX_CHALLENGE_RESPONSE_BYTES).catch(() => "") : "";
2911
+ if (!input.readBody)
2912
+ await response.body?.cancel().catch(() => {});
2913
+ return { ok: true, status: response.status, text };
2914
+ }
2915
+ await response.body?.cancel().catch(() => {});
2916
+ return {
2917
+ ok: false,
2918
+ status: response.status,
2919
+ category: response.status >= 500 ? "http_5xx" : "http_4xx"
2920
+ };
2921
+ }
2922
+ async function verifyCallbackEndpoint(input) {
2923
+ const challenge = randomBytes(24).toString("base64url");
2924
+ const result = await postSignedWebhook({
2925
+ url: input.url,
2926
+ subscriptionId: input.subscriptionId,
2927
+ webhookId: `msg_verification_${randomBytes(12).toString("hex")}`,
2928
+ secrets: [input.secret],
2929
+ body: JSON.stringify({ type: "verification", challenge }),
2930
+ readBody: true
2931
+ });
2932
+ if (!result.ok)
2933
+ return result.category;
2934
+ let echoed;
2935
+ try {
2936
+ echoed = JSON.parse(result.text).challenge;
2937
+ } catch {
2938
+ return "challenge_failed";
2939
+ }
2940
+ if (typeof echoed !== "string")
2941
+ return "challenge_failed";
2942
+ const expected = Buffer.from(challenge);
2943
+ const actual = Buffer.from(echoed);
2944
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
2945
+ return "challenge_failed";
2946
+ }
2947
+ return null;
2948
+ }
2949
+
2950
+ // src/be/mcp-events/dispatcher.ts
2951
+ var DEFAULT_RETRY_DELAYS_MS = [1e4, 60000, 240000, 540000];
2952
+ var MAX_OUTPUT_CHARS = 16000;
2953
+ var MAX_TASK_CHARS = 2000;
2954
+ var MAX_ANCESTOR_HOPS = 32;
2955
+ var retryDelaysMs = DEFAULT_RETRY_DELAYS_MS;
2956
+ var pendingTimers = new Set;
2957
+ var listening = false;
2958
+ function truncate(text, max) {
2959
+ return text.length > max ? { text: text.slice(0, max), truncated: true } : { text, truncated: false };
2960
+ }
2961
+ async function isUnderTask(taskId, filterTaskId) {
2962
+ let current = taskId;
2963
+ for (let hop = 0;current && hop <= MAX_ANCESTOR_HOPS; hop++) {
2964
+ if (current === filterTaskId)
2965
+ return true;
2966
+ const row = await getDbClient2().get("SELECT parentTaskId FROM agent_tasks WHERE id = ?", [current]);
2967
+ current = row?.parentTaskId ?? null;
2968
+ }
2969
+ return false;
2970
+ }
2971
+ function signingSecrets(row, nowIso) {
2972
+ const secrets = [unsealSecret(row.secretSealed)];
2973
+ if (row.previousSecretSealed && row.previousSecretUntil && row.previousSecretUntil > nowIso) {
2974
+ secrets.push(unsealSecret(row.previousSecretSealed));
2975
+ }
2976
+ return secrets.map(parseWebhookSecret).filter((s) => s !== null);
2977
+ }
2978
+ async function attemptDelivery(subscriptionId, eventId, body, attempt) {
2979
+ const nowIso = new Date().toISOString();
2980
+ const row = await getSubscription(subscriptionId);
2981
+ if (!row || row.expiresAt <= nowIso)
2982
+ return;
2983
+ if (!await isLiveUserToken(row.tokenId, row.userId))
2984
+ return;
2985
+ const result = await postSignedWebhook({
2986
+ url: row.url,
2987
+ subscriptionId: row.id,
2988
+ webhookId: eventId,
2989
+ secrets: signingSecrets(row, nowIso),
2990
+ body
2991
+ });
2992
+ const atIso = new Date().toISOString();
2993
+ if (result.ok) {
2994
+ await recordDeliveryOutcome(row.id, { ok: true, atIso });
2995
+ return;
2996
+ }
2997
+ if (result.status === 410 || result.status === 413)
2998
+ return;
2999
+ await recordDeliveryOutcome(row.id, { ok: false, category: result.category, atIso });
3000
+ const delay = retryDelaysMs[attempt];
3001
+ if (delay === undefined)
3002
+ return;
3003
+ const timer = setTimeout(() => {
3004
+ pendingTimers.delete(timer);
3005
+ attemptDelivery(subscriptionId, eventId, body, attempt + 1).catch(logError);
3006
+ }, delay);
3007
+ timer.unref?.();
3008
+ pendingTimers.add(timer);
3009
+ }
3010
+ function logError(err) {
3011
+ console.error("[mcp-events] delivery failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
3012
+ }
3013
+ async function dispatchTaskEvent(name, payload) {
3014
+ if (!isMcpUserEventsEnabled())
3015
+ return;
3016
+ const { taskId, output, failureReason } = payload ?? {};
3017
+ if (typeof taskId !== "string")
3018
+ return;
3019
+ const task = await getTaskById2(taskId);
3020
+ if (!task?.requestedByUserId)
3021
+ return;
3022
+ const user = await getUserById2(task.requestedByUserId);
3023
+ if (!user || user.status !== "active")
3024
+ return;
3025
+ const now = new Date;
3026
+ const subscriptions = await listLiveSubscriptions(user.id, name, now.toISOString());
3027
+ if (subscriptions.length === 0)
3028
+ return;
3029
+ const rawDetail = name === "task.completed" ? output : failureReason;
3030
+ const detailText = scrubSecrets(typeof rawDetail === "string" ? rawDetail : "");
3031
+ const detail = truncate(detailText, MAX_OUTPUT_CHARS);
3032
+ const description = truncate(scrubSecrets(task.task ?? ""), MAX_TASK_CHARS);
3033
+ const data = {
3034
+ taskId: task.id,
3035
+ parentTaskId: task.parentTaskId ?? null,
3036
+ status: name === "task.completed" ? "completed" : "failed",
3037
+ task: description.text,
3038
+ url: `${getAppUrl()}/tasks/${encodeURIComponent(task.id)}`,
3039
+ [name === "task.completed" ? "output" : "failureReason"]: detail.text,
3040
+ truncated: detail.truncated || description.truncated
3041
+ };
3042
+ const timestamp = task.finishedAt ?? now.toISOString();
3043
+ const attempts = [];
3044
+ for (const subscription of subscriptions) {
3045
+ const args = parseTaskEventArguments(JSON.parse(subscription.argumentsJson));
3046
+ if (!args)
3047
+ continue;
3048
+ if (args.taskId && !await isUnderTask(task.id, args.taskId))
3049
+ continue;
3050
+ const eventId = `evt_${createHash2("sha256").update(`${subscription.id}
3051
+ ${name}
3052
+ ${task.id}`).digest("hex").slice(0, 32)}`;
3053
+ let body = JSON.stringify({ eventId, name, timestamp, data, cursor: null });
3054
+ if (Buffer.byteLength(body, "utf8") > MAX_DELIVERY_BODY_BYTES) {
3055
+ body = JSON.stringify({
3056
+ eventId,
3057
+ name,
3058
+ timestamp,
3059
+ data: { ...data, output: undefined, failureReason: undefined, truncated: true },
3060
+ cursor: null
3061
+ });
3062
+ }
3063
+ attempts.push(attemptDelivery(subscription.id, eventId, body, 0).catch(logError));
3064
+ }
3065
+ await Promise.all(attempts);
3066
+ }
3067
+ var onCompleted = (payload) => {
3068
+ dispatchTaskEvent("task.completed", payload).catch(logError);
3069
+ };
3070
+ var onFailed = (payload) => {
3071
+ dispatchTaskEvent("task.failed", payload).catch(logError);
3072
+ };
3073
+ function initMcpEventsDispatcher() {
3074
+ if (listening)
3075
+ return;
3076
+ listening = true;
3077
+ workflowEventBus2.on("task.completed", onCompleted);
3078
+ workflowEventBus2.on("task.failed", onFailed);
3079
+ }
3080
+
2397
3081
  // src/be/mcp-overflow-sweep.ts
2398
3082
  init_kv_overflow();
2399
3083
  init_db4();
@@ -4324,7 +5008,7 @@ init_otel();
4324
5008
 
4325
5009
  // src/queue-stall-alarm.ts
4326
5010
  init_db4();
4327
- init_app3();
5011
+ init_app4();
4328
5012
  init_secret_scrubber();
4329
5013
  var QUEUE_STALL_THRESHOLD_MS = 30 * 60 * 1000;
4330
5014
  var QUEUE_STALL_CHECK_INTERVAL_MS = 5 * 60 * 1000;
@@ -8090,6 +8774,7 @@ var KEY_WINDOW_USAGE_SQL = `
8090
8774
  SELECT NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, 0, 0, '', NULL, 0, sc.createdAt, NULL
8091
8775
  FROM session_costs sc
8092
8776
  WHERE (sc.credentialKeyType IS NULL OR sc.credentialKeySuffix IS NULL)
8777
+ AND sc.kind = 'harness'
8093
8778
  AND sc.createdAt >= ? AND sc.createdAt < ?
8094
8779
  LIMIT ${MAX_USAGE_ROWS + 1}`;
8095
8780
  var emptyTokens = () => Object.fromEntries(["uncachedInput", "output", "cacheRead", "cacheWrite", "reasoning", "thinking"].map((name) => [
@@ -9144,6 +9829,7 @@ init_rbac_roles();
9144
9829
  init_swarm_config_guard();
9145
9830
  init_users();
9146
9831
  init_rbac();
9832
+ init_reaction_shortcode();
9147
9833
  init_types5();
9148
9834
  init_request_auth_context();
9149
9835
  init_secret_scrubber();
@@ -9298,7 +9984,7 @@ async function handleUsedBy(req, res, pathSegments, queryParams, myAgentId) {
9298
9984
  });
9299
9985
  }
9300
9986
  });
9301
- scheduleIntegrationsReload();
9987
+ scheduleIntegrationsReload2();
9302
9988
  const owner = await resolveHttpFavoriteOwner(req, myAgentId);
9303
9989
  trackRelayed("used_by.consent_changed", {
9304
9990
  granted,
@@ -9545,7 +10231,7 @@ async function handleRanking(req, res, pathSegments, queryParams) {
9545
10231
  return true;
9546
10232
  }
9547
10233
  const { listing } = built;
9548
- scheduleIntegrationsReload();
10234
+ scheduleIntegrationsReload2();
9549
10235
  optIn.respond(res, 200, {
9550
10236
  domain: listing.domain,
9551
10237
  listing,
@@ -9563,7 +10249,7 @@ async function handleRanking(req, res, pathSegments, queryParams) {
9563
10249
  await setEnabled(false);
9564
10250
  if (listing)
9565
10251
  emitOptedOut(listing.domain);
9566
- scheduleIntegrationsReload();
10252
+ scheduleIntegrationsReload2();
9567
10253
  optOut.respond(res, 200, { enabled: false });
9568
10254
  return true;
9569
10255
  }
@@ -9646,13 +10332,27 @@ async function maskConfigRead(req, configs, includeSecrets) {
9646
10332
  async function ensureConfigAdmin(req, res, verb) {
9647
10333
  return ensureHttpPermission(req, res, verb, verb === "config.write.any" ? "Writing swarm config requires the lead agent" : "Deleting swarm config requires the lead agent");
9648
10334
  }
10335
+ async function ensureHumanOnlyConfigWrite(req, res, key) {
10336
+ if (!isHumanOnlyConfigKey(key))
10337
+ return true;
10338
+ const auth = getRequestAuth(req);
10339
+ if (auth?.page) {
10340
+ jsonError(res, humanOnlyConfigKeyPageError(key), 403);
10341
+ return false;
10342
+ }
10343
+ const userId = authUserId(auth);
10344
+ if (userId && (!isRbacEnabled() || (await getUserGrant2(userId)).grantsAll))
10345
+ return true;
10346
+ jsonError(res, humanOnlyConfigKeyError(key), 403);
10347
+ return false;
10348
+ }
9649
10349
  async function runConfigWriteSideEffects(scope, key, value) {
9650
10350
  if (scope !== "global")
9651
10351
  return;
9652
10352
  if (key === "SWARM_ORG_WEBSITE")
9653
10353
  await fillOrgLogoFromWebsite(value);
9654
10354
  await syncRankingAfterConfigChange(key, value);
9655
- scheduleIntegrationsReload();
10355
+ scheduleIntegrationsReload2();
9656
10356
  }
9657
10357
  async function ensureHttpPermission(req, res, verb, forbiddenMessage, callerAgentId) {
9658
10358
  const principal = await requestPrincipal(req, callerAgentId ?? singleHeader(req, "x-agent-id"), {
@@ -9860,14 +10560,14 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9860
10560
  const presence = {};
9861
10561
  for (const key of keys) {
9862
10562
  const value = key === "SWARM_ORG_NAME" ? process.env[key]?.trim() : process.env[key];
9863
- presence[key] = value !== undefined && value !== "";
10563
+ presence[key] = value !== undefined && (isSlackIconConfigKey(key) || value !== "");
9864
10564
  }
9865
10565
  envPresence.respond(res, 200, { presence });
9866
10566
  return true;
9867
10567
  }
9868
10568
  if (reloadConfigRoute.match(req.method, pathSegments)) {
9869
10569
  try {
9870
- const result = await reloadGlobalConfigsAndIntegrations();
10570
+ const result = await reloadGlobalConfigsAndIntegrations2();
9871
10571
  console.log(`[reload-config] Loaded ${result.configsLoaded} config(s), re-initialized: ${result.integrationsReinitialized.join(", ") || "none"}`);
9872
10572
  reloadConfigRoute.respond(res, 200, { success: true, ...result });
9873
10573
  } catch (e) {
@@ -9918,6 +10618,8 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9918
10618
  if (!await ensureConfigAdmin(req, res, "config.write.any"))
9919
10619
  return true;
9920
10620
  const { scope, scopeId, key, value, isSecret, envPath, description, exportToEnv } = parsed.body;
10621
+ if (!await ensureHumanOnlyConfigWrite(req, res, key))
10622
+ return true;
9921
10623
  const validationError = validateConfigEntry({ scope, scopeId, key, value, exportToEnv });
9922
10624
  if (validationError) {
9923
10625
  jsonError(res, validationError, 400);
@@ -9962,6 +10664,8 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9962
10664
  jsonError(res, internalConfigKeyError(existing.key).message, 400);
9963
10665
  return true;
9964
10666
  }
10667
+ if (!await ensureHumanOnlyConfigWrite(req, res, existing.key))
10668
+ return true;
9965
10669
  const deleted = await deleteSwarmConfig2(parsed.params.id);
9966
10670
  if (!deleted) {
9967
10671
  jsonError(res, "Config not found", 404);
@@ -9969,7 +10673,7 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9969
10673
  }
9970
10674
  if (existing.scope === "global") {
9971
10675
  await syncRankingAfterConfigChange(existing.key, null);
9972
- scheduleIntegrationsReload();
10676
+ scheduleIntegrationsReload2();
9973
10677
  }
9974
10678
  if (existing.scope === "agent" && existing.scopeId && existing.key === AGENT_MAX_TASKS_CONFIG_KEY) {
9975
10679
  await resetAgentMaxTasksMirror(existing.scopeId);
@@ -10407,6 +11111,12 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
10407
11111
  if ([...configAnswers.values()].some(({ answer }) => answer.action === "set")) {
10408
11112
  if (!await ensureConfigAdmin(req, res, "config.write.any"))
10409
11113
  return true;
11114
+ for (const { question, answer } of configAnswers.values()) {
11115
+ if (answer.action !== "set")
11116
+ continue;
11117
+ if (!await ensureHumanOnlyConfigWrite(req, res, question.config.key))
11118
+ return true;
11119
+ }
10410
11120
  const userId = authUserId(getRequestAuth(req));
10411
11121
  if (userId && isRbacEnabled()) {
10412
11122
  const grant = await getUserGrant2(userId);
@@ -11034,13 +11744,13 @@ init_types5();
11034
11744
  init_secret_scrubber();
11035
11745
  init_route_def();
11036
11746
  init_utils2();
11037
- import { createHash } from "node:crypto";
11747
+ import { createHash as createHash3 } from "node:crypto";
11038
11748
  function apiKeyFingerprint(req) {
11039
11749
  const authHeader = req.headers.authorization;
11040
11750
  const providedKey = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : "";
11041
11751
  if (!providedKey)
11042
11752
  return "";
11043
- const digest = createHash("sha256").update(providedKey).digest("hex").slice(0, 8);
11753
+ const digest = createHash3("sha256").update(providedKey).digest("hex").slice(0, 8);
11044
11754
  return scrubSecrets(digest);
11045
11755
  }
11046
11756
  var ScopeIdSchema = string2().max(255).describe("Scope identifier — empty string for global, agent UUID otherwise");
@@ -14261,7 +14971,8 @@ declare module "swarm-extension" {
14261
14971
  runtimeInstanceId: string | undefined;
14262
14972
  sourceTaskId: string | undefined;
14263
14973
  contextKey: string | undefined;
14264
- callOrigin: "mcp" | "extension" | "script-sdk";
14974
+ callOrigin: "mcp" | "native" | "extension" | "script-sdk";
14975
+ harness?: string | undefined;
14265
14976
  };
14266
14977
 
14267
14978
  import type { SwarmSdk } from "swarm-sdk";
@@ -14303,7 +15014,11 @@ declare module "swarm-extension" {
14303
15014
  };
14304
15015
  homepage?: string;
14305
15016
  author?: string;
15017
+ /** Tool-call sources this extension's tool handlers receive. Default \`["mcp"]\`. */
15018
+ toolSources?: readonly ToolSource[];
14306
15019
  }
15020
+ /** \`mcp\`: swarm MCP tools. \`native\`: harness built-ins reported by a worker shim. */
15021
+ export type ToolSource = "mcp" | "native";
14307
15022
  export interface HooksModule {
14308
15023
  default: SwarmExtension;
14309
15024
  config?: z.ZodTypeAny;
@@ -14575,8 +15290,16 @@ declare module "swarm-extension" {
14575
15290
  }
14576
15291
  export interface ToolCallEvent {
14577
15292
  tool: string;
15293
+ /** Secret-scrubbed on native calls: a secret reads as \`[REDACTED:<name>]\`. */
14578
15294
  args: unknown;
14579
15295
  requestInfo: RequestInfo;
15296
+ /** Native calls only: the harness's own tool name, such as \`Bash\`. */
15297
+ nativeTool?: string;
15298
+ /** Native calls only: the harness's own argument shape, secret-scrubbed. */
15299
+ rawArgs?: unknown;
15300
+ /** Native calls only: the harness's call id, and its parent for a nested call. */
15301
+ toolCallId?: string;
15302
+ parentToolCallId?: string;
14580
15303
  }
14581
15304
  export interface ToolCallModify {
14582
15305
  args: unknown;
@@ -14706,6 +15429,8 @@ declare module "swarm-extension" {
14706
15429
  export interface ToolCallCompletedEvent extends ToolCallEvent {
14707
15430
  result: unknown;
14708
15431
  durationMs: number;
15432
+ /** Native calls only: the harness reported the call as failed. */
15433
+ isError?: boolean;
14709
15434
  }
14710
15435
  export interface SwarmEventMap {
14711
15436
  "pre.task.create": {
@@ -16440,7 +17165,13 @@ const shortcode = (raw: string): string | null => {
16440
17165
 
16441
17166
  /** The acceptance reactions the engine may have put on the message, deduplicated. */
16442
17167
  export const acceptanceReactions = (): string[] => [
16443
- ...new Set(ACCEPTANCE_REACTIONS.map(([key, fallback]) => shortcode(envOf(key)) ?? fallback)),
17168
+ ...new Set(
17169
+ ACCEPTANCE_REACTIONS.flatMap(([key, fallback]) => {
17170
+ const raw = process.env[key];
17171
+ if (raw !== undefined && raw.trim() === "") return [];
17172
+ return [shortcode(raw ?? "") ?? fallback];
17173
+ }),
17174
+ ),
16444
17175
  ];
16445
17176
 
16446
17177
  const slackCall = async (
@@ -16582,9 +17313,7 @@ export const askModel = async (
16582
17313
  } | null;
16583
17314
  if (res?.success === false || body?.success === false) {
16584
17315
  const why = \`\${target.provider}: \${String(body?.message ?? body?.error ?? \`HTTP \${res?.status}\`).slice(0, 200)}\`;
16585
- throw body?.providerUnavailable === true
16586
- ? new ProviderUnavailableError(why)
16587
- : new Error(why);
17316
+ throw body?.providerUnavailable === true ? new ProviderUnavailableError(why) : new Error(why);
16588
17317
  }
16589
17318
  const answer = body?.answers?.reason;
16590
17319
  const reason = typeof answer?.choice === "string" ? answer.choice : "";
@@ -19071,6 +19800,65 @@ function sendProviderError(res, error) {
19071
19800
  return true;
19072
19801
  }
19073
19802
 
19803
+ // src/http/github-token.ts
19804
+ init_zod();
19805
+ init_app();
19806
+ init_request_auth_context();
19807
+ init_request_principal();
19808
+ init_route_def();
19809
+ init_utils2();
19810
+ var installationTokenRoute = route({
19811
+ method: "post",
19812
+ path: "/api/github/installation-token",
19813
+ pattern: ["api", "github", "installation-token"],
19814
+ summary: "Mint a GitHub App installation token for worker git and gh",
19815
+ description: "Internal worker endpoint. Returns a short-lived installation token for the installation in `GITHUB_APP_INSTALLATION_ID`, minted with the API server's GitHub App credentials. The caller cannot choose the installation. Only a registered agent (swarm API key plus X-Agent-ID, or an agent or runtime token) may call it; user, guest and ACP task tokens are refused. 404 when the App or the installation id is not configured, so workers fall back to `GITHUB_TOKEN`.",
19816
+ tags: ["GitHub"],
19817
+ body: object2({}).optional(),
19818
+ responses: {
19819
+ 200: {
19820
+ description: "Installation token and its expiry (ISO 8601)",
19821
+ schema: object2({ token: string2(), expiresAt: string2() })
19822
+ },
19823
+ 403: { description: "Caller is not a registered agent" },
19824
+ 404: { description: "GitHub App worker auth is not configured" },
19825
+ 502: { description: "GitHub refused or failed to mint the token" }
19826
+ },
19827
+ auth: { apiKey: true, agentId: true },
19828
+ rbac: {
19829
+ ungated: "the handler admits only registered agent principals and mints for one fixed installation"
19830
+ }
19831
+ });
19832
+ async function handleGitHubToken(req, res, pathSegments, myAgentId) {
19833
+ if (!installationTokenRoute.match(req.method, pathSegments))
19834
+ return false;
19835
+ const parsed = await installationTokenRoute.parse(req, res, pathSegments, new URLSearchParams);
19836
+ if (!parsed)
19837
+ return true;
19838
+ const principal = await resolveRequestPrincipal(req, myAgentId, {
19839
+ precedence: "agent-first",
19840
+ requireRegisteredAgent: true
19841
+ });
19842
+ const auth = getRequestAuth(req);
19843
+ const taskToken = auth?.kind === "agent" && auth.tokenKind === "task";
19844
+ if (principal?.kind !== "agent" || !principal.agentId || taskToken) {
19845
+ jsonError(res, "Only a registered agent may mint a GitHub installation token", 403);
19846
+ return true;
19847
+ }
19848
+ const result = await getWorkerInstallationToken();
19849
+ if (result.status === "unconfigured") {
19850
+ jsonError(res, "GitHub App worker auth is not configured", 404);
19851
+ return true;
19852
+ }
19853
+ if (result.status === "error") {
19854
+ jsonError(res, "GitHub did not mint an installation token", 502);
19855
+ return true;
19856
+ }
19857
+ res.setHeader("Cache-Control", "no-store");
19858
+ installationTokenRoute.respond(res, 200, { token: result.token, expiresAt: result.expiresAt });
19859
+ return true;
19860
+ }
19861
+
19074
19862
  // src/http/heartbeat.ts
19075
19863
  init_zod();
19076
19864
  init_route_def();
@@ -19553,7 +20341,7 @@ async function handleInboxState(req, res, pathSegments, queryParams) {
19553
20341
  init_zod();
19554
20342
 
19555
20343
  // src/slack/app-icon.ts
19556
- init_app3();
20344
+ init_app4();
19557
20345
  var import_web_api = __toESM(require_dist4(), 1);
19558
20346
  var TTL_MS = 60 * 60 * 1000;
19559
20347
  var REQUEST_TIMEOUT_MS = 2500;
@@ -22107,32 +22895,9 @@ async function handleMcp(req, res, transports, sessionActivity = {}, sessionAgen
22107
22895
  delete sessionActivity[transport.sessionId];
22108
22896
  }
22109
22897
  };
22110
- const configs = await getResolvedConfig2(agentId);
22111
- const configValue = configs.find((config) => config.key === "SCRIPTS_ONLY_MCP")?.value;
22112
- const preloadEnabled = parseEnvFlag(configs.find((config) => config.key === "TASK_TOOL_PRELOAD_ENABLED")?.value ?? process.env.TASK_TOOL_PRELOAD_ENABLED, true);
22113
- let preloadedTools = [];
22114
22898
  const sourceTaskId = headerValue(req.headers["x-source-task-id"]);
22115
22899
  const sourceTask = sourceTaskId ? await getTaskById2(sourceTaskId) : undefined;
22116
- const excludedTools = sourceTask && !isChatSdkTask(sourceTask) ? [...CHAT_TASK_ONLY_TOOLS] : [];
22117
- if (preloadEnabled) {
22118
- if (sourceTask?.agentId === agentId) {
22119
- const manifestValue = configs.find((config) => config.key === "TASK_TOOL_MANIFESTS")?.value ?? process.env.TASK_TOOL_MANIFESTS ?? "{}";
22120
- try {
22121
- preloadedTools = selectTaskTools(parseTaskToolManifest(manifestValue), sourceTask);
22122
- } catch {
22123
- console.warn("[MCP] Invalid TASK_TOOL_MANIFESTS; using ordinary tool discovery");
22124
- }
22125
- }
22126
- }
22127
- const server = await createServer({
22128
- preloadedTools,
22129
- excludedTools,
22130
- enabledTools: configs.find((config) => config.key === "SWARM_ENABLED_TOOLS")?.value ?? process.env.SWARM_ENABLED_TOOLS,
22131
- scriptsOnly: resolveScriptsOnlyMode({
22132
- env: process.env.SCRIPTS_ONLY_MCP,
22133
- configValue
22134
- })
22135
- });
22900
+ const server = await createServer(await resolveMcpSessionOptions(agentId, sourceTask));
22136
22901
  await server.connect(transport);
22137
22902
  } else {
22138
22903
  return respondNoMcpSession(res, sessionId);
@@ -22153,6 +22918,29 @@ async function handleMcp(req, res, transports, sessionActivity = {}, sessionAgen
22153
22918
  res.end("Method not allowed");
22154
22919
  return true;
22155
22920
  }
22921
+ async function resolveMcpSessionOptions(agentId, sourceTask) {
22922
+ const configs = await getResolvedConfig2(agentId);
22923
+ const configValue = configs.find((config) => config.key === "SCRIPTS_ONLY_MCP")?.value;
22924
+ const preloadEnabled = parseEnvFlag(configs.find((config) => config.key === "TASK_TOOL_PRELOAD_ENABLED")?.value ?? process.env.TASK_TOOL_PRELOAD_ENABLED, true);
22925
+ let preloadedTools = [];
22926
+ const excludedTools = sourceTask && !isChatSdkTask(sourceTask) ? [...CHAT_TASK_ONLY_TOOLS] : [];
22927
+ if (preloadEnabled) {
22928
+ if (sourceTask?.agentId === agentId) {
22929
+ const manifestValue = configs.find((config) => config.key === "TASK_TOOL_MANIFESTS")?.value ?? process.env.TASK_TOOL_MANIFESTS ?? "{}";
22930
+ try {
22931
+ preloadedTools = selectTaskTools(parseTaskToolManifest(manifestValue), sourceTask);
22932
+ } catch {
22933
+ console.warn("[MCP] Invalid TASK_TOOL_MANIFESTS; using ordinary tool discovery");
22934
+ }
22935
+ }
22936
+ }
22937
+ return {
22938
+ preloadedTools,
22939
+ excludedTools,
22940
+ enabledTools: configs.find((config) => config.key === "SWARM_ENABLED_TOOLS")?.value ?? process.env.SWARM_ENABLED_TOOLS,
22941
+ scriptsOnly: resolveScriptsOnlyMode({ env: process.env.SCRIPTS_ONLY_MCP, configValue })
22942
+ };
22943
+ }
22156
22944
 
22157
22945
  // src/http/index.ts
22158
22946
  init_mcp_bridge();
@@ -23407,6 +24195,198 @@ init_users();
23407
24195
  init_mcp();
23408
24196
  init_zod();
23409
24197
  init_package();
24198
+
24199
+ // src/be/mcp-events/protocol.ts
24200
+ init_zod();
24201
+ init_db4();
24202
+ var MAX_SUBSCRIPTIONS_PER_USER = 25;
24203
+ var DEFAULT_TTL_MS = 60 * 60 * 1000;
24204
+ var MIN_TTL_MS = 60 * 1000;
24205
+ var MAX_TTL_MS = 24 * 60 * 60 * 1000;
24206
+ var VERIFICATION_CACHE_MS = 24 * 60 * 60 * 1000;
24207
+ var ROTATION_GRACE_MS = 10 * 60 * 1000;
24208
+
24209
+ class EventsRpcError extends Error {
24210
+ code;
24211
+ data;
24212
+ constructor(code, message, data) {
24213
+ super(message);
24214
+ this.code = code;
24215
+ this.data = data;
24216
+ }
24217
+ }
24218
+ function invalidParams(message) {
24219
+ return new EventsRpcError(EventsErrorCode.InvalidParams, message);
24220
+ }
24221
+ function resourceExhausted() {
24222
+ return new EventsRpcError(EventsErrorCode.ResourceExhausted, "Too many subscriptions", {
24223
+ limit: "subscriptions",
24224
+ max: MAX_SUBSCRIPTIONS_PER_USER
24225
+ });
24226
+ }
24227
+ var EventsListRequestSchema = object2({
24228
+ method: literal2("events/list"),
24229
+ params: unknown().optional()
24230
+ });
24231
+ var EventsSubscribeRequestSchema = object2({
24232
+ method: literal2("events/subscribe"),
24233
+ params: unknown().optional()
24234
+ });
24235
+ var EventsUnsubscribeRequestSchema = object2({
24236
+ method: literal2("events/unsubscribe"),
24237
+ params: unknown().optional()
24238
+ });
24239
+ function asRecord(value) {
24240
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
24241
+ }
24242
+ function parseKey(rawParams) {
24243
+ const params = asRecord(rawParams);
24244
+ if (typeof params.name !== "string")
24245
+ throw invalidParams("name is required");
24246
+ if (!isTaskEventName(params.name)) {
24247
+ throw new EventsRpcError(EventsErrorCode.NotFound, `Unknown event: ${params.name}`, {
24248
+ kind: "event"
24249
+ });
24250
+ }
24251
+ const args = parseTaskEventArguments(params.arguments);
24252
+ if (!args)
24253
+ throw invalidParams("arguments do not match the event's inputSchema");
24254
+ const delivery = asRecord(params.delivery);
24255
+ if (delivery.mode !== undefined && delivery.mode !== "webhook") {
24256
+ throw new EventsRpcError(EventsErrorCode.Unsupported, "Only webhook delivery is offered", {
24257
+ feature: "deliveryMode",
24258
+ value: delivery.mode
24259
+ });
24260
+ }
24261
+ const urlProblem = callbackUrlProblem(delivery.url);
24262
+ if (urlProblem)
24263
+ throw invalidParams(urlProblem);
24264
+ return {
24265
+ name: params.name,
24266
+ arguments: args,
24267
+ argumentsJson: canonicalJson(args),
24268
+ url: delivery.url,
24269
+ delivery
24270
+ };
24271
+ }
24272
+ function grantTtlMs(raw) {
24273
+ if (raw === undefined)
24274
+ return DEFAULT_TTL_MS;
24275
+ if (raw === null)
24276
+ return MAX_TTL_MS;
24277
+ if (typeof raw !== "number" || !Number.isFinite(raw))
24278
+ throw invalidParams("ttlMs must be a number");
24279
+ return Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, Math.floor(raw)));
24280
+ }
24281
+ var VERIFICATIONS_PER_USER_PER_HOUR = 30;
24282
+ var VERIFICATIONS_PER_HOUR = 1000;
24283
+ var HOUR_MS = 60 * 60 * 1000;
24284
+ var verificationLog = new Map;
24285
+ function takeVerificationBudget(userId, now) {
24286
+ const recent = (key) => (verificationLog.get(key) ?? []).filter((at) => at > now - HOUR_MS);
24287
+ const mine = recent(userId);
24288
+ const all = recent("*");
24289
+ if (mine.length >= VERIFICATIONS_PER_USER_PER_HOUR || all.length >= VERIFICATIONS_PER_HOUR) {
24290
+ return false;
24291
+ }
24292
+ verificationLog.set(userId, [...mine, now]);
24293
+ verificationLog.set("*", [...all, now]);
24294
+ return true;
24295
+ }
24296
+ async function handleSubscribe(user, tokenId, authorize, rawParams) {
24297
+ const key = parseKey(rawParams);
24298
+ const secretText = key.delivery.secret;
24299
+ const secret = parseWebhookSecret(secretText);
24300
+ if (!secret) {
24301
+ throw invalidParams("delivery.secret must be whsec_ followed by base64 of 24 to 64 bytes");
24302
+ }
24303
+ const ttlMs = grantTtlMs(asRecord(rawParams).ttlMs);
24304
+ if (!await authorize("events/subscribe")) {
24305
+ throw new EventsRpcError(EventsErrorCode.Forbidden, "Forbidden");
24306
+ }
24307
+ if (key.arguments.taskId) {
24308
+ const task = await getTaskById2(key.arguments.taskId);
24309
+ if (!task || task.requestedByUserId !== user.id) {
24310
+ throw new EventsRpcError(EventsErrorCode.Forbidden, "taskId is not one of your tasks");
24311
+ }
24312
+ }
24313
+ const now = Date.now();
24314
+ const nowIso = new Date(now).toISOString();
24315
+ await deleteExpiredSubscriptions(nowIso);
24316
+ const id = subscriptionIdFor(user.id, key.url, key.name, key.argumentsJson);
24317
+ const previous = await getSubscription(id);
24318
+ const refreshing = previous !== null && previous.expiresAt > nowIso;
24319
+ if (!refreshing && await countLiveSubscriptions(user.id, nowIso) >= MAX_SUBSCRIPTIONS_PER_USER) {
24320
+ throw resourceExhausted();
24321
+ }
24322
+ let verifiedAt = await latestVerification(user.id, key.url, new Date(now - VERIFICATION_CACHE_MS).toISOString(), nowIso);
24323
+ if (!verifiedAt) {
24324
+ if (!takeVerificationBudget(user.id, now)) {
24325
+ throw new EventsRpcError(EventsErrorCode.ResourceExhausted, "Too many verifications", {
24326
+ limit: "verifications",
24327
+ max: VERIFICATIONS_PER_USER_PER_HOUR
24328
+ });
24329
+ }
24330
+ const failure = await verifyCallbackEndpoint({ url: key.url, subscriptionId: id, secret });
24331
+ if (failure) {
24332
+ throw new EventsRpcError(EventsErrorCode.CallbackEndpointError, "Callback endpoint verification failed", { reason: failure });
24333
+ }
24334
+ verifiedAt = nowIso;
24335
+ }
24336
+ const row = await upsertSubscription({
24337
+ id,
24338
+ userId: user.id,
24339
+ tokenId,
24340
+ eventName: key.name,
24341
+ argumentsJson: key.argumentsJson,
24342
+ url: key.url,
24343
+ secret: secretText,
24344
+ verifiedAt,
24345
+ expiresAt: new Date(now + ttlMs).toISOString(),
24346
+ nowIso,
24347
+ rotationGraceUntil: new Date(now + ROTATION_GRACE_MS).toISOString(),
24348
+ maxActivePerUser: MAX_SUBSCRIPTIONS_PER_USER
24349
+ });
24350
+ if (row === "limit")
24351
+ throw resourceExhausted();
24352
+ return {
24353
+ resultType: "complete",
24354
+ id: row.id,
24355
+ refreshBefore: row.expiresAt,
24356
+ cursor: null,
24357
+ truncated: false,
24358
+ ...refreshing ? {
24359
+ deliveryStatus: {
24360
+ active: true,
24361
+ lastDeliveryAt: row.lastDeliveryAt,
24362
+ lastError: row.lastError,
24363
+ ...row.failedSince ? { failedSince: row.failedSince } : {}
24364
+ }
24365
+ } : {}
24366
+ };
24367
+ }
24368
+ async function handleUnsubscribe(user, authorize, rawParams) {
24369
+ const key = parseKey(rawParams);
24370
+ if (!await authorize("events/unsubscribe")) {
24371
+ throw new EventsRpcError(EventsErrorCode.Forbidden, "Forbidden");
24372
+ }
24373
+ await deleteSubscription(subscriptionIdFor(user.id, key.url, key.name, key.argumentsJson), user.id);
24374
+ return { resultType: "complete" };
24375
+ }
24376
+ function registerUserEvents(server, user, tokenId, authorize) {
24377
+ server.server.registerCapabilities({
24378
+ events: {},
24379
+ extensions: { [EVENTS_EXTENSION_ID]: {} }
24380
+ });
24381
+ server.server.setRequestHandler(EventsListRequestSchema, async () => ({
24382
+ resultType: "complete",
24383
+ events: EVENT_DESCRIPTORS
24384
+ }));
24385
+ server.server.setRequestHandler(EventsSubscribeRequestSchema, async (request) => handleSubscribe(user, tokenId, authorize, request.params));
24386
+ server.server.setRequestHandler(EventsUnsubscribeRequestSchema, async (request) => handleUnsubscribe(user, authorize, request.params));
24387
+ }
24388
+
24389
+ // src/server-user.ts
23410
24390
  init_rbac_audit();
23411
24391
  init_rbac_roles();
23412
24392
  init_mcp_limits();
@@ -23453,7 +24433,7 @@ async function maybeDenyUserToolAdmission(user, toolName, config) {
23453
24433
  return;
23454
24434
  return toolErr(`Forbidden: ${decision.reason}`);
23455
24435
  }
23456
- function createUserServer(user) {
24436
+ function createUserServer(user, tokenId) {
23457
24437
  const server = new McpServer({
23458
24438
  name: `${package_default.name}-user`,
23459
24439
  version: package_default.version,
@@ -23465,6 +24445,13 @@ function createUserServer(user) {
23465
24445
  maxToolInputElements: MCP_MAX_TOOL_INPUT_ELEMENTS
23466
24446
  });
23467
24447
  const registerTool = createToolRegistrar(server);
24448
+ if (tokenId && isMcpUserEventsEnabled()) {
24449
+ const eventsAdmission = { annotations: { readOnlyHint: true } };
24450
+ registerUserEvents(server, user, tokenId, async (method) => {
24451
+ const denied = await maybeDenyUserToolAdmission(user, method, eventsAdmission);
24452
+ return denied === undefined;
24453
+ });
24454
+ }
23468
24455
  const sendTaskConfig = {
23469
24456
  title: "Send a task",
23470
24457
  annotations: { destructiveHint: false },
@@ -23563,19 +24550,20 @@ async function resolveActiveUser(req) {
23563
24550
  const token = extractBearer(req);
23564
24551
  if (!token)
23565
24552
  return null;
23566
- const user = await resolveUserByToken(token);
23567
- if (!user || user.status !== "active")
24553
+ const resolved = await resolveUserToken(token);
24554
+ if (!resolved?.user || resolved.user.status !== "active")
23568
24555
  return null;
23569
- return user;
24556
+ return { user: resolved.user, tokenId: resolved.tokenId };
23570
24557
  }
23571
24558
  async function handleMcpUser(req, res, transports, sessionUsers, sessionActivity = {}) {
23572
24559
  const sessionId = req.headers["mcp-session-id"];
23573
24560
  if (req.url !== "/mcp-user") {
23574
24561
  return false;
23575
24562
  }
23576
- const user = await resolveActiveUser(req);
23577
- if (!user)
24563
+ const resolved = await resolveActiveUser(req);
24564
+ if (!resolved)
23578
24565
  return unauthorized2(res);
24566
+ const { user, tokenId } = resolved;
23579
24567
  setRequestAuth(req, { kind: "user", userId: user.id, user });
23580
24568
  if (sessionId && transports[sessionId] && sessionUsers[sessionId] !== user.id) {
23581
24569
  return unauthorized2(res);
@@ -23609,7 +24597,7 @@ async function handleMcpUser(req, res, transports, sessionUsers, sessionActivity
23609
24597
  delete sessionActivity[transport.sessionId];
23610
24598
  }
23611
24599
  };
23612
- const server = createUserServer(user);
24600
+ const server = createUserServer(user, tokenId);
23613
24601
  await server.connect(transport);
23614
24602
  } else {
23615
24603
  return respondNoMcpSession(res, sessionId);
@@ -23647,6 +24635,7 @@ init_event_loop_lag();
23647
24635
  init_memory();
23648
24636
  init_access();
23649
24637
  init_constants2();
24638
+ init_demotion_evidence();
23650
24639
 
23651
24640
  // src/be/memory/edges-store.ts
23652
24641
  init_db4();
@@ -23737,6 +24726,7 @@ async function hasRetrievalForTask(taskId, memoryId) {
23737
24726
  }
23738
24727
 
23739
24728
  // src/http/memory.ts
24729
+ init_review_recall_filter();
23740
24730
  init_search_candidates();
23741
24731
 
23742
24732
  // src/be/memory/usefulness-stats.ts
@@ -24573,6 +25563,9 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
24573
25563
  const provider = getEmbeddingProvider2();
24574
25564
  const store = getMemoryStore2();
24575
25565
  const queryEmbedding = await provider.embed(query, { kind: "query" });
25566
+ const sourceTaskIdHeader = req.headers["x-source-task-id"];
25567
+ const sourceTaskId = Array.isArray(sourceTaskIdHeader) ? sourceTaskIdHeader[0] : sourceTaskIdHeader;
25568
+ const excludeReviewTaskCompletions = await isReviewTaskId(sourceTaskId);
24576
25569
  const candidateLimit = Math.min(limit, 20) * CANDIDATE_SET_MULTIPLIER;
24577
25570
  const candidates = await searchMemoryCandidates(store, queryEmbedding ?? new Float32Array(0), myAgentId, {
24578
25571
  scope,
@@ -24580,18 +25573,18 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
24580
25573
  source,
24581
25574
  isLead: false,
24582
25575
  queryText: query,
24583
- keyPrefix
25576
+ keyPrefix,
25577
+ excludeReviewTaskCompletions
24584
25578
  });
24585
- const expanded = await expandCandidatesWithGraph(candidates, myAgentId, {
25579
+ const graphExpanded = await expandCandidatesWithGraph(candidates, myAgentId, {
24586
25580
  scope,
24587
25581
  source,
24588
25582
  keyPrefix,
24589
25583
  isLead: false
24590
25584
  });
25585
+ const expanded = await attachDemotionEvidence(excludeReviewTaskCompletions ? await dropReviewTaskCompletions(graphExpanded) : graphExpanded);
24591
25586
  const resultLimit = Math.min(limit, 20);
24592
25587
  const ranked = consumptionMode === "prompt" ? rerank(expanded, { limit: expanded.length }).map((r) => ({ r, eligible: memoryRelevance(r) > SIMILARITY_THRESHOLD })).sort((a, b) => Number(b.eligible) - Number(a.eligible)).slice(0, resultLimit).map(({ r }) => r) : rerank(expanded, { limit: resultLimit });
24593
- const sourceTaskIdHeader = req.headers["x-source-task-id"];
24594
- const sourceTaskId = Array.isArray(sourceTaskIdHeader) ? sourceTaskIdHeader[0] : sourceTaskIdHeader;
24595
25588
  const contextKeyHeader = req.headers["x-context-key"];
24596
25589
  const contextKey = Array.isArray(contextKeyHeader) ? contextKeyHeader[0] : contextKeyHeader;
24597
25590
  if (sourceTaskId && intent) {
@@ -24668,7 +25661,9 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
24668
25661
  if (pathNeedle) {
24669
25662
  candidates = candidates.filter((c) => matchesPath(c.sourcePath));
24670
25663
  }
24671
- const ranked = rerank(candidates, { limit: candidates.length });
25664
+ const ranked = rerank(await attachDemotionEvidence(candidates), {
25665
+ limit: candidates.length
25666
+ });
24672
25667
  const page = ranked.slice(offset, offset + pageLimit);
24673
25668
  listMemory.respond(res, 200, {
24674
25669
  results: page.map((r) => ({
@@ -25612,6 +26607,224 @@ async function handleMetrics(req, res, pathSegments, queryParams, myAgentId) {
25612
26607
  return false;
25613
26608
  }
25614
26609
 
26610
+ // src/http/model-groups.ts
26611
+ init_zod();
26612
+ init_audit_user();
26613
+ init_model_groups();
26614
+ init_rbac();
26615
+ init_types5();
26616
+ init_request_principal();
26617
+ init_route_def();
26618
+ init_utils2();
26619
+ var MembersSchema = array2(ModelProfileNameSchema).min(1).max(MAX_MODEL_GROUP_MEMBERS).describe("Profile names in preference order, first preferred. Any harness; no repeats.");
26620
+ var listGroups = route({
26621
+ method: "get",
26622
+ path: "/api/model-groups",
26623
+ pattern: ["api", "model-groups"],
26624
+ summary: "List model groups",
26625
+ description: "Every model group with its member profiles in order, by name.",
26626
+ tags: ["Models"],
26627
+ responses: {
26628
+ 200: { description: "Model groups", schema: object2({ groups: array2(ModelGroupSchema) }) }
26629
+ }
26630
+ });
26631
+ var getGroup = route({
26632
+ method: "get",
26633
+ path: "/api/model-groups/{name}",
26634
+ pattern: ["api", "model-groups", null],
26635
+ summary: "Get one model group",
26636
+ tags: ["Models"],
26637
+ params: object2({ name: string2() }),
26638
+ responses: {
26639
+ 200: { description: "The model group", schema: ModelGroupSchema },
26640
+ 404: { description: "No group with that name" }
26641
+ }
26642
+ });
26643
+ var createGroup = route({
26644
+ method: "post",
26645
+ path: "/api/model-groups",
26646
+ pattern: ["api", "model-groups"],
26647
+ summary: "Create a model group",
26648
+ description: "A group is an ordered list of model profiles that may span harnesses. Every member must be an existing profile, listed once. The name may not be a model profile's (groups and profiles share one name space; 409). Lead, operator or dashboard user.",
26649
+ tags: ["Models"],
26650
+ rbac: { permission: "models.groups.write" },
26651
+ body: object2({
26652
+ name: ModelProfileNameSchema,
26653
+ description: string2().trim().max(500).nullable().optional(),
26654
+ members: MembersSchema
26655
+ }),
26656
+ responses: {
26657
+ 201: { description: "Group created", schema: ModelGroupSchema },
26658
+ 400: { description: "Validation error" },
26659
+ 403: { description: "Forbidden" },
26660
+ 409: { description: "A group or profile with that name exists" }
26661
+ }
26662
+ });
26663
+ var updateGroup = route({
26664
+ method: "patch",
26665
+ path: "/api/model-groups/{name}",
26666
+ pattern: ["api", "model-groups", null],
26667
+ summary: "Update a model group",
26668
+ description: "Changes the description (`null` clears it). The name is fixed; reorder or replace members with `PUT /api/model-groups/{name}/members`. Lead, operator or dashboard user.",
26669
+ tags: ["Models"],
26670
+ rbac: { permission: "models.groups.write" },
26671
+ params: object2({ name: string2() }),
26672
+ body: object2({ description: string2().trim().max(500).nullable() }),
26673
+ responses: {
26674
+ 200: { description: "Group updated", schema: ModelGroupSchema },
26675
+ 400: { description: "Validation error" },
26676
+ 403: { description: "Forbidden" },
26677
+ 404: { description: "No group with that name" }
26678
+ }
26679
+ });
26680
+ var setMembers = route({
26681
+ method: "put",
26682
+ path: "/api/model-groups/{name}/members",
26683
+ pattern: ["api", "model-groups", null, "members"],
26684
+ summary: "Replace a model group's members",
26685
+ description: "Replaces the whole ordered member list in one transaction; send the full list to reorder. Every member must be an existing profile, listed once. Lead, operator or dashboard user.",
26686
+ tags: ["Models"],
26687
+ rbac: { permission: "models.groups.write" },
26688
+ params: object2({ name: string2() }),
26689
+ body: object2({ members: MembersSchema }),
26690
+ responses: {
26691
+ 200: { description: "Members replaced", schema: ModelGroupSchema },
26692
+ 400: { description: "Validation error" },
26693
+ 403: { description: "Forbidden" },
26694
+ 404: { description: "No group with that name" }
26695
+ }
26696
+ });
26697
+ var deleteGroup = route({
26698
+ method: "delete",
26699
+ path: "/api/model-groups/{name}",
26700
+ pattern: ["api", "model-groups", null],
26701
+ summary: "Delete a model group",
26702
+ description: "Refused (409) for a shipped tier group (`smol`, `regular`, `smart`, `ultra`; edit it instead, it would come back at the next boot), and while a schedule names the group or a task holds it (unfinished, or superseded and still owed its resume). Lead, operator or dashboard user.",
26703
+ tags: ["Models"],
26704
+ rbac: { permission: "models.groups.write" },
26705
+ params: object2({ name: string2() }),
26706
+ responses: {
26707
+ 200: { description: "Group deleted", schema: object2({ deleted: literal2(true) }) },
26708
+ 403: { description: "Forbidden" },
26709
+ 404: { description: "No group with that name" },
26710
+ 409: { description: "The group is a seed or still in use" }
26711
+ }
26712
+ });
26713
+ async function canWriteGroups(req, res, myAgentId) {
26714
+ const decision = can({
26715
+ principal: await agentFirstPrincipal(req, myAgentId),
26716
+ verb: "models.groups.write",
26717
+ resource: { kind: "none" },
26718
+ source: "http"
26719
+ });
26720
+ if (!decision.allow) {
26721
+ jsonError(res, "Writing model groups requires the lead, the operator or a dashboard user", 403);
26722
+ return false;
26723
+ }
26724
+ return true;
26725
+ }
26726
+ var WRITE_FAILURE_STATUS = { invalid: 400, exists: 409, "name-taken": 409, missing: 404 };
26727
+ function writeFailed(res, result) {
26728
+ if (result.ok)
26729
+ return false;
26730
+ jsonError(res, result.error, WRITE_FAILURE_STATUS[result.reason]);
26731
+ return true;
26732
+ }
26733
+ async function handleModelGroups(req, res, pathSegments, queryParams, myAgentId) {
26734
+ if (listGroups.match(req.method, pathSegments)) {
26735
+ const parsed = await listGroups.parse(req, res, pathSegments, queryParams);
26736
+ if (!parsed)
26737
+ return true;
26738
+ listGroups.respond(res, 200, { groups: await listModelGroups() });
26739
+ return true;
26740
+ }
26741
+ if (getGroup.match(req.method, pathSegments)) {
26742
+ const parsed = await getGroup.parse(req, res, pathSegments, queryParams);
26743
+ if (!parsed)
26744
+ return true;
26745
+ const group = await getModelGroupByName(parsed.params.name);
26746
+ if (!group) {
26747
+ jsonError(res, "Model group not found", 404);
26748
+ return true;
26749
+ }
26750
+ getGroup.respond(res, 200, group);
26751
+ return true;
26752
+ }
26753
+ if (createGroup.match(req.method, pathSegments)) {
26754
+ const parsed = await createGroup.parse(req, res, pathSegments, queryParams);
26755
+ if (!parsed)
26756
+ return true;
26757
+ if (!await canWriteGroups(req, res, myAgentId))
26758
+ return true;
26759
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
26760
+ const result = await createModelGroup(parsed.body, { userId });
26761
+ if (writeFailed(res, result))
26762
+ return true;
26763
+ createGroup.respond(res, 201, result.group);
26764
+ return true;
26765
+ }
26766
+ if (updateGroup.match(req.method, pathSegments)) {
26767
+ const parsed = await updateGroup.parse(req, res, pathSegments, queryParams);
26768
+ if (!parsed)
26769
+ return true;
26770
+ if (!await canWriteGroups(req, res, myAgentId))
26771
+ return true;
26772
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
26773
+ const result = await updateModelGroup(parsed.params.name, { description: parsed.body.description }, { userId });
26774
+ if (writeFailed(res, result))
26775
+ return true;
26776
+ updateGroup.respond(res, 200, result.group);
26777
+ return true;
26778
+ }
26779
+ if (setMembers.match(req.method, pathSegments)) {
26780
+ const parsed = await setMembers.parse(req, res, pathSegments, queryParams);
26781
+ if (!parsed)
26782
+ return true;
26783
+ if (!await canWriteGroups(req, res, myAgentId))
26784
+ return true;
26785
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
26786
+ const result = await updateModelGroup(parsed.params.name, { members: parsed.body.members }, { userId });
26787
+ if (writeFailed(res, result))
26788
+ return true;
26789
+ setMembers.respond(res, 200, result.group);
26790
+ return true;
26791
+ }
26792
+ if (deleteGroup.match(req.method, pathSegments)) {
26793
+ const parsed = await deleteGroup.parse(req, res, pathSegments, queryParams);
26794
+ if (!parsed)
26795
+ return true;
26796
+ if (!await canWriteGroups(req, res, myAgentId))
26797
+ return true;
26798
+ const current = await getModelGroupByName(parsed.params.name);
26799
+ if (!current) {
26800
+ jsonError(res, "Model group not found", 404);
26801
+ return true;
26802
+ }
26803
+ if (current.seededFrom?.startsWith("tier:")) {
26804
+ jsonError(res, `"${current.name}" is a shipped tier group and comes back at the next boot; edit it instead.`, 409);
26805
+ return true;
26806
+ }
26807
+ const refs = await modelGroupReferences(current.name);
26808
+ if (refs.openTaskCount > 0 || refs.scheduleIds.length > 0) {
26809
+ const schedules = refs.scheduleIds.length > 0 ? ` (${refs.scheduleIds.join(", ")})` : "";
26810
+ jsonError(res, `"${current.name}" is in use: held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}.`, 409);
26811
+ return true;
26812
+ }
26813
+ const outcome = await deleteModelGroup(current.name);
26814
+ if (outcome === "in-use") {
26815
+ jsonError(res, `"${current.name}" is in use by a task or a schedule written just now.`, 409);
26816
+ return true;
26817
+ }
26818
+ if (outcome === "missing") {
26819
+ jsonError(res, "Model group not found", 404);
26820
+ return true;
26821
+ }
26822
+ deleteGroup.respond(res, 200, { deleted: true });
26823
+ return true;
26824
+ }
26825
+ return false;
26826
+ }
26827
+
25615
26828
  // src/http/model-profiles.ts
25616
26829
  init_src2();
25617
26830
  init_zod();
@@ -25657,7 +26870,7 @@ var createProfile = route({
25657
26870
  path: "/api/model-profiles",
25658
26871
  pattern: ["api", "model-profiles"],
25659
26872
  summary: "Create a model profile",
25660
- description: "A profile runs on one harness. `model` must run on that harness and be in the model catalog unless `allowCustomModel` is true (a gateway id, a fresh launch); a `latest:` alias is accepted and resolves at claim. `effort` must be a level the harness and model support. `credentials` pins which pooled keys the profile uses: per credential var of the harness, the last 5 characters of each allowed key (`CODEX_OAUTH` is not supported). `fallbacks` lists profiles on the same harness, in order, that a task on this profile hops to when a provider error (rate limit, seat, overload, auth, empty key pool) ends it; no repeats, no self, no cycle. Operator only (the shared API key).",
26873
+ description: "A profile runs on one harness. `model` must run on that harness and be in the model catalog unless `allowCustomModel` is true (a gateway id, a fresh launch); a `latest:` alias is accepted and resolves at claim. `effort` must be a level the harness and model support. `credentials` pins which pooled keys the profile uses: per credential var of the harness, the last 5 characters of each allowed key (`CODEX_OAUTH` is not supported). `fallbacks` lists profiles on the same harness, in order, that a task on this profile hops to when a provider error (rate limit, seat, overload, auth, empty key pool) ends it; no repeats, no self, no cycle. The name may not be a model group's (one name space; 409). Operator only (the shared API key).",
25661
26874
  tags: ["Models"],
25662
26875
  rbac: { permission: "models.profiles.write" },
25663
26876
  body: object2({
@@ -25674,7 +26887,7 @@ var createProfile = route({
25674
26887
  201: { description: "Profile created", schema: ModelProfileSchema },
25675
26888
  400: { description: "Validation error" },
25676
26889
  403: { description: "Forbidden" },
25677
- 409: { description: "A profile with that name exists" }
26890
+ 409: { description: "A profile or model group with that name exists" }
25678
26891
  }
25679
26892
  });
25680
26893
  var updateProfile = route({
@@ -25706,7 +26919,7 @@ var deleteProfile = route({
25706
26919
  path: "/api/model-profiles/{name}",
25707
26920
  pattern: ["api", "model-profiles", null],
25708
26921
  summary: "Delete a model profile",
25709
- description: "Refused (409) for a shipped `<harness>-<tier>` seed (edit it instead; it would come back at the next boot), and while an agent has the profile as its default, a schedule names it, another profile lists it as a fallback, or a task holds it (unfinished, or superseded and still owed its resume). Operator only (the shared API key).",
26922
+ description: "Refused (409) for a shipped `<harness>-<tier>` seed (edit it instead; it would come back at the next boot), and while an agent has the profile as its default, a schedule names it, another profile lists it as a fallback, a model group lists it as a member, or a task holds it (unfinished, or superseded and still owed its resume). Operator only (the shared API key).",
25710
26923
  tags: ["Models"],
25711
26924
  rbac: { permission: "models.profiles.write" },
25712
26925
  params: object2({ name: string2() }),
@@ -25805,7 +27018,15 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
25805
27018
  if (fallbackError)
25806
27019
  return { error: fallbackError };
25807
27020
  return { created: await createModelProfile(body, { userId }) };
27021
+ }).catch((error) => {
27022
+ if (isModelNameTakenError(error))
27023
+ return { nameTaken: true };
27024
+ throw error;
25808
27025
  });
27026
+ if ("nameTaken" in outcome) {
27027
+ jsonError(res, `"${body.name}" is a model group; profiles and groups share one name space.`, 409);
27028
+ return true;
27029
+ }
25809
27030
  if (typeof outcome.error === "string") {
25810
27031
  jsonError(res, outcome.error, 400);
25811
27032
  return true;
@@ -25876,15 +27097,16 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
25876
27097
  return true;
25877
27098
  }
25878
27099
  const refs = await modelProfileReferences(current.name);
25879
- if (refs.agentIds.length > 0 || refs.openTaskCount > 0 || refs.scheduleIds.length > 0 || refs.fallbackOf.length > 0) {
27100
+ if (refs.agentIds.length > 0 || refs.openTaskCount > 0 || refs.scheduleIds.length > 0 || refs.fallbackOf.length > 0 || refs.groups.length > 0) {
25880
27101
  const schedules = refs.scheduleIds.length > 0 ? ` (${refs.scheduleIds.join(", ")})` : "";
25881
27102
  const fallbackOf = refs.fallbackOf.length > 0 ? ` (${refs.fallbackOf.join(", ")})` : "";
25882
- jsonError(res, `"${current.name}" is in use: default of ${refs.agentIds.length} agent(s), held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}, a fallback of ${refs.fallbackOf.length} profile(s)${fallbackOf}.`, 409);
27103
+ const groups = refs.groups.length > 0 ? ` (${refs.groups.join(", ")})` : "";
27104
+ jsonError(res, `"${current.name}" is in use: default of ${refs.agentIds.length} agent(s), held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}, a fallback of ${refs.fallbackOf.length} profile(s)${fallbackOf}, a member of ${refs.groups.length} model group(s)${groups}.`, 409);
25883
27105
  return true;
25884
27106
  }
25885
27107
  const outcome = await deleteModelProfile(current.name);
25886
27108
  if (outcome === "in-use") {
25887
- jsonError(res, `"${current.name}" is in use by a task, a schedule, an agent default or a fallback list written just now.`, 409);
27109
+ jsonError(res, `"${current.name}" is in use by a task, a schedule, an agent default, a fallback list or a model group written just now.`, 409);
25888
27110
  return true;
25889
27111
  }
25890
27112
  if (outcome === "missing") {
@@ -27430,9 +28652,9 @@ function embeddingsProvider(baseUrl) {
27430
28652
  }
27431
28653
  function deploymentEmbeddings() {
27432
28654
  return {
27433
- baseUrl: getDeploymentEnvValue("EMBEDDING_API_BASE_URL"),
27434
- model: getDeploymentEnvValue("EMBEDDING_MODEL") ?? "text-embedding-3-small",
27435
- apiKey: getDeploymentEnvValue("EMBEDDING_API_KEY") ?? process.env.OPENAI_API_KEY
28655
+ baseUrl: getDeploymentEnvValue2("EMBEDDING_API_BASE_URL"),
28656
+ model: getDeploymentEnvValue2("EMBEDDING_MODEL") ?? "text-embedding-3-small",
28657
+ apiKey: getDeploymentEnvValue2("EMBEDDING_API_KEY") ?? process.env.OPENAI_API_KEY
27436
28658
  };
27437
28659
  }
27438
28660
  function localDefault() {
@@ -27580,14 +28802,14 @@ async function updateMemoryState(preset, result, change) {
27580
28802
  if (!configChanged)
27581
28803
  return;
27582
28804
  if (change?.kind === "restore") {
27583
- await loadGlobalConfigsIntoEnv(true);
28805
+ await loadGlobalConfigsIntoEnv2(true);
27584
28806
  resetEmbeddingProvider2();
27585
28807
  }
27586
- scheduleIntegrationsReload();
28808
+ scheduleIntegrationsReload2();
27587
28809
  }
27588
28810
  function prefixChanges(model) {
27589
- const sameModel = model === getDeploymentEnvValue("EMBEDDING_MODEL");
27590
- return EMBEDDING_PREFIX_KEYS.filter((key) => getDeploymentEnvValue(key)).map((key) => ({
28811
+ const sameModel = model === getDeploymentEnvValue2("EMBEDDING_MODEL");
28812
+ return EMBEDDING_PREFIX_KEYS.filter((key) => getDeploymentEnvValue2(key)).map((key) => ({
27591
28813
  key,
27592
28814
  value: sameModel ? null : ""
27593
28815
  }));
@@ -27599,7 +28821,7 @@ async function handleMemoryProbe(body) {
27599
28821
  const deployment = restore ? deploymentEmbeddings() : null;
27600
28822
  const baseUrl = body.preset === "existing" ? deployment ? deployment.baseUrl : process.env.EMBEDDING_API_BASE_URL : body.baseUrl ?? preset?.baseUrl ?? process.env.EMBEDDING_API_BASE_URL ?? "https://api.openai.com/v1";
27601
28823
  const model = body.preset === "existing" ? deployment?.model ?? process.env.EMBEDDING_MODEL ?? "text-embedding-3-small" : body.model ?? preset?.model ?? process.env.EMBEDDING_MODEL ?? "text-embedding-3-small";
27602
- const configuredEndpoint = body.preset === "existing" && !!baseUrl && baseUrl === getDeploymentEnvValue("EMBEDDING_API_BASE_URL");
28824
+ const configuredEndpoint = body.preset === "existing" && !!baseUrl && baseUrl === getDeploymentEnvValue2("EMBEDDING_API_BASE_URL");
27603
28825
  let endpoint;
27604
28826
  try {
27605
28827
  endpoint = configuredEndpoint ? new URL(baseUrl ?? "") : assertUrlSafe(baseUrl ?? "", publicEndpointSsrfOptions());
@@ -28648,20 +29870,29 @@ var runTaskUiActionRoute = route({
28648
29870
  session: { taskParam: "id" },
28649
29871
  rbac: { permission: "task.action.own" },
28650
29872
  summary: "Run the action a task card Button declares",
28651
- description: "Runs the task card action once per task and action. Only the task requester may run it: a user token, or the operator key with the requester in `X-Swarm-User-Id`. Agent callers, and operator calls with no picked user, get 403. Needs UI_SPEC_ACTIONS_ENABLED=true.",
29873
+ description: "Runs a task card action. Only the task requester may run it: a user token, or the operator key with the requester in `X-Swarm-User-Id`. Agent callers, and operator calls with no picked user, get 403. Needs UI_SPEC_ACTIONS_ENABLED=true. A `follow_up` action runs once per task and action. A `script` action re-runs its allowlisted script (UI_SPEC_SCRIPT_ACTIONS) and returns the new card; it can run again after a 30 s cooldown.",
28652
29874
  tags: ["Tasks"],
28653
29875
  params: object2({ id: string2(), actionId: string2() }),
28654
29876
  responses: {
28655
29877
  200: {
28656
- description: "The action started, or it already ran",
29878
+ description: "The follow-up started or already ran, or the script action replaced the card (`refreshed`, with the new `uiSpec`)",
28657
29879
  schema: object2({
28658
- status: _enum2(["started", "already_done"]),
28659
- taskId: string2().optional()
29880
+ status: _enum2(["started", "already_done", "refreshed"]),
29881
+ taskId: string2().optional(),
29882
+ uiSpec: TaskUiSpecSchema.optional()
28660
29883
  })
28661
29884
  },
28662
- 403: { description: "Only the task requester may run the action" },
29885
+ 403: {
29886
+ description: "Only the task requester may run the action, or the action's script is not allowlisted or changed since it was allowlisted"
29887
+ },
28663
29888
  404: { description: "Task or action not found" },
28664
- 409: { description: "Card actions are turned off (UI_SPEC_ACTIONS_ENABLED)" }
29889
+ 409: {
29890
+ description: "Card actions are turned off (UI_SPEC_ACTIONS_ENABLED), or the script action is already running (with `Retry-After`)"
29891
+ },
29892
+ 422: { description: "The script failed or returned an invalid card; the old card stays" },
29893
+ 429: {
29894
+ description: "The script action ran recently; `Retry-After` says when it can run again"
29895
+ }
28665
29896
  }
28666
29897
  });
28667
29898
  var supersedeTaskRoute = route({
@@ -28670,7 +29901,7 @@ var supersedeTaskRoute = route({
28670
29901
  pattern: ["api", "tasks", null, "supersede"],
28671
29902
  session: { taskParam: "id" },
28672
29903
  summary: "Supersede an in-progress task (terminate + spawn resume follow-up)",
28673
- description: "Marks the original task `superseded` (terminal) and creates a fresh `taskType=\"resume\"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine's retry/failure policy applies, and the task moves to `superseded` once the engine queues the step's retry. With `reason: provider_fallback` (and its `errorClass`), the resume runs on the same agent with the next fallback profile that passes the profile check; when none is left, or the task is a workflow step, nothing changes and `kind: noFallback` tells the worker to fail the task itself, led by `failureReason` when set.",
29904
+ description: "Marks the original task `superseded` (terminal) and creates a fresh `taskType=\"resume\"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine's retry/failure policy applies, and the task moves to `superseded` once the engine queues the step's retry or the step ends without failing. With `reason: provider_fallback` (and its `errorClass`), the resume runs on the same agent: on the same profile while a key-scoped error (`rate_limit`, `credits`) leaves another unbenched key in its pool, else on the next fallback profile that passes the profile check; when none is left, or the task is a workflow step, nothing changes and `kind: noFallback` tells the worker to fail the task itself, led by `failureReason` when set.",
28674
29905
  tags: ["Tasks"],
28675
29906
  params: object2({ id: string2() }),
28676
29907
  body: object2({ reason: ResumeReasonSchema, errorClass: ProviderErrorClassSchema.optional() }).refine((body) => body.reason === "provider_fallback" === (body.errorClass !== undefined), {
@@ -29725,8 +30956,27 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
29725
30956
  runTaskUiActionRoute.respond(res, 200, { status: "already_done" });
29726
30957
  return true;
29727
30958
  case "started":
30959
+ case "refreshed":
29728
30960
  runTaskUiActionRoute.respond(res, 200, result);
29729
30961
  return true;
30962
+ case "not_allowlisted":
30963
+ jsonError(res, "This action's script is not allowlisted (UI_SPEC_SCRIPT_ACTIONS)", 403);
30964
+ return true;
30965
+ case "script_changed":
30966
+ jsonError(res, "This action's script changed since it was allowlisted; an admin must re-pin it in UI_SPEC_SCRIPT_ACTIONS", 403);
30967
+ return true;
30968
+ case "running":
30969
+ res.setHeader("Retry-After", String(result.retryAfterSec));
30970
+ jsonError(res, "This action is already running", 409);
30971
+ return true;
30972
+ case "rate_limited":
30973
+ res.setHeader("Retry-After", String(result.retryAfterSec));
30974
+ jsonError(res, `This action ran recently; try again in ${result.retryAfterSec}s`, 429);
30975
+ return true;
30976
+ case "script_failed":
30977
+ case "invalid_output":
30978
+ jsonError(res, `Refresh failed: ${result.error}`, 422);
30979
+ return true;
29730
30980
  }
29731
30981
  }
29732
30982
  if (resumeTaskRoute.match(req.method, pathSegments)) {
@@ -29814,6 +31064,9 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
29814
31064
  return true;
29815
31065
  }
29816
31066
  fallback = { profile: pick.profile, hop: pick.hop };
31067
+ if (pick.hop.from === pick.profile) {
31068
+ console.log(`[Supersede] Task ${task.id.slice(0, 8)} hit ${pick.hop.errorClass} on ${pick.profile} (key ...${task.credentialKeySuffix ?? "?"}); retrying the profile on another key`);
31069
+ }
29817
31070
  }
29818
31071
  if (task.workflowRunStepId != null) {
29819
31072
  const failed = await failTask2(parsed.params.id, SUPERSEDED_WORKFLOW_TASK_REASON);
@@ -33176,7 +34429,7 @@ init_multi_runtime();
33176
34429
  init_server();
33177
34430
 
33178
34431
  // src/slack/channel-activity.ts
33179
- init_app3();
34432
+ init_app4();
33180
34433
  var cachedBotUserId = null;
33181
34434
  var channelCache = null;
33182
34435
  var CHANNEL_CACHE_TTL_MS = 5 * 60 * 1000;
@@ -33898,7 +35151,7 @@ var deletePoolKey = route({
33898
35151
  var ENV_POOL_ERROR = "These keys come from the deployment env. Change them there.";
33899
35152
  async function readPool(key) {
33900
35153
  const [row] = await getSwarmConfigs2({ scope: "global", key });
33901
- const envValue = getDeploymentEnvValue(key);
35154
+ const envValue = getDeploymentEnvValue2(key);
33902
35155
  const source = row ? "stored" : envValue ? "env" : "none";
33903
35156
  const value = row?.value ?? envValue ?? "";
33904
35157
  registerEnvSecrets({ [key]: value });
@@ -34105,13 +35358,13 @@ init_types5();
34105
35358
  init_secret_scrubber();
34106
35359
  init_route_def();
34107
35360
  init_utils2();
34108
- import { createHash as createHash2 } from "node:crypto";
35361
+ import { createHash as createHash4 } from "node:crypto";
34109
35362
  function apiKeyFingerprint2(req) {
34110
35363
  const authHeader = req.headers.authorization;
34111
35364
  const providedKey = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : "";
34112
35365
  if (!providedKey)
34113
35366
  return "";
34114
- const digest = createHash2("sha256").update(providedKey).digest("hex").slice(0, 8);
35367
+ const digest = createHash4("sha256").update(providedKey).digest("hex").slice(0, 8);
34115
35368
  return scrubSecrets(digest);
34116
35369
  }
34117
35370
  var PricingTriplePathParams = object2({
@@ -34311,7 +35564,8 @@ var ResolveResultSchema = object2({
34311
35564
  templateId: string2().optional(),
34312
35565
  scope: string2().optional(),
34313
35566
  skipped: boolean(),
34314
- unresolved: array2(string2())
35567
+ unresolved: array2(string2()),
35568
+ segments: array2(object2({ templateId: string2(), chars: number2().int() })).optional()
34315
35569
  });
34316
35570
  var DbResolveResultSchema = union3([
34317
35571
  object2({ template: PromptTemplateResponseSchema }),
@@ -34994,6 +36248,957 @@ async function handleRepos(req, res, pathSegments, queryParams, myAgentId) {
34994
36248
  return false;
34995
36249
  }
34996
36250
 
36251
+ // src/http/request-composition.ts
36252
+ init_zod();
36253
+ init_db4();
36254
+
36255
+ // src/be/db/request-composition.ts
36256
+ init_db4();
36257
+ init_runtime2();
36258
+ var MAX_REQUEST_COMPOSITIONS_PER_TASK = 100;
36259
+ async function createRequestComposition(input) {
36260
+ const id = crypto.randomUUID();
36261
+ const createdAt = new Date().toISOString();
36262
+ const staticEstTokens = input.parts.reduce((sum, part) => sum + part.estTokens, 0);
36263
+ const tokenRatio = input.tokenRatio ?? 1;
36264
+ const seq = await getDbClient2().transaction(async (tx) => {
36265
+ const stored = await tx.get("SELECT COUNT(*) AS count FROM request_composition WHERE taskId = ?", [input.taskId]);
36266
+ if ((stored?.count ?? 0) >= MAX_REQUEST_COMPOSITIONS_PER_TASK)
36267
+ return null;
36268
+ const last = await tx.get("SELECT MAX(seq) AS seq FROM request_composition WHERE sessionId = ?", [input.sessionId]);
36269
+ const next = last?.seq == null ? 0 : last.seq + 1;
36270
+ await tx.run(`INSERT INTO request_composition
36271
+ (id, taskId, agentId, sessionId, seq, provider, model, source, parts, staticEstTokens, tokenRatio, createdAt)
36272
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
36273
+ id,
36274
+ input.taskId,
36275
+ input.agentId,
36276
+ input.sessionId,
36277
+ next,
36278
+ input.provider,
36279
+ input.model ?? null,
36280
+ input.source,
36281
+ JSON.stringify(input.parts),
36282
+ staticEstTokens,
36283
+ tokenRatio,
36284
+ createdAt
36285
+ ]);
36286
+ return next;
36287
+ });
36288
+ if (seq === null)
36289
+ return null;
36290
+ return {
36291
+ id,
36292
+ taskId: input.taskId,
36293
+ agentId: input.agentId,
36294
+ sessionId: input.sessionId,
36295
+ seq,
36296
+ provider: input.provider,
36297
+ model: input.model ?? null,
36298
+ source: input.source,
36299
+ parts: input.parts,
36300
+ staticEstTokens,
36301
+ tokenRatio,
36302
+ createdAt
36303
+ };
36304
+ }
36305
+ async function getRequestCompositionsByTask(taskId, limit = MAX_REQUEST_COMPOSITIONS_PER_TASK) {
36306
+ const rows = await getDbClient2().query(`SELECT id, taskId, agentId, sessionId, seq, provider, model, source, parts, staticEstTokens, tokenRatio, createdAt
36307
+ FROM request_composition WHERE taskId = ? ORDER BY createdAt ASC, seq ASC LIMIT ?`, [taskId, limit]);
36308
+ return rows.map((row) => ({ ...row, parts: JSON.parse(row.parts) }));
36309
+ }
36310
+ async function getLatestWorkerComposition(sessionId) {
36311
+ const row = await getDbClient2().get(`SELECT id, taskId, agentId, sessionId, seq, provider, model, source, parts, staticEstTokens, tokenRatio, createdAt
36312
+ FROM request_composition WHERE sessionId = ? AND source = 'worker'
36313
+ ORDER BY seq DESC LIMIT 1`, [sessionId]);
36314
+ return row ? { ...row, parts: JSON.parse(row.parts) } : null;
36315
+ }
36316
+ var TOKEN_RATIO_KV_NAMESPACE = "swarm";
36317
+ var TOKEN_RATIO_MIN = 0.5;
36318
+ var TOKEN_RATIO_MAX = 2;
36319
+ var TOKEN_RATIO_ALPHA = 0.2;
36320
+ var tokenRatioKey = (provider) => `request-composition/token-ratio/${provider}`;
36321
+ function clampTokenRatio(ratio) {
36322
+ if (!Number.isFinite(ratio))
36323
+ return 1;
36324
+ return Math.min(TOKEN_RATIO_MAX, Math.max(TOKEN_RATIO_MIN, ratio));
36325
+ }
36326
+ function nextTokenRatio(prev, observed) {
36327
+ const obs = clampTokenRatio(observed);
36328
+ if (!prev || prev.samples <= 0)
36329
+ return { ratio: obs, samples: 1 };
36330
+ return {
36331
+ ratio: clampTokenRatio(prev.ratio + TOKEN_RATIO_ALPHA * (obs - prev.ratio)),
36332
+ samples: prev.samples + 1
36333
+ };
36334
+ }
36335
+ function parseTokenRatio(value) {
36336
+ if (typeof value === "number")
36337
+ return { ratio: clampTokenRatio(value), samples: 0 };
36338
+ if (value && typeof value === "object" && "ratio" in value) {
36339
+ const { ratio, samples } = value;
36340
+ if (typeof ratio !== "number")
36341
+ return null;
36342
+ return {
36343
+ ratio: clampTokenRatio(ratio),
36344
+ samples: typeof samples === "number" && samples > 0 ? Math.floor(samples) : 0
36345
+ };
36346
+ }
36347
+ return null;
36348
+ }
36349
+ async function getTokenRatio(provider) {
36350
+ const entry = await getKv2(TOKEN_RATIO_KV_NAMESPACE, tokenRatioKey(provider));
36351
+ return parseTokenRatio(entry?.value)?.ratio ?? 1;
36352
+ }
36353
+ async function recordTokenRatio(provider, observed) {
36354
+ return getDbClient2().transaction(async () => {
36355
+ const key = tokenRatioKey(provider);
36356
+ const entry = await getKv2(TOKEN_RATIO_KV_NAMESPACE, key);
36357
+ const next = nextTokenRatio(parseTokenRatio(entry?.value), observed);
36358
+ await upsertKv2({
36359
+ namespace: TOKEN_RATIO_KV_NAMESPACE,
36360
+ key,
36361
+ value: { ...next, updatedAt: new Date().toISOString() },
36362
+ valueType: "json"
36363
+ });
36364
+ return next;
36365
+ });
36366
+ }
36367
+
36368
+ // src/http/request-composition.ts
36369
+ init_key_browser();
36370
+ init_types5();
36371
+ init_route_def();
36372
+
36373
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
36374
+ init_protocol();
36375
+ init_types();
36376
+ init_ajv_provider();
36377
+ init_zod_compat();
36378
+
36379
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
36380
+ init_types();
36381
+
36382
+ class ExperimentalClientTasks {
36383
+ constructor(_client) {
36384
+ this._client = _client;
36385
+ }
36386
+ async* callToolStream(params, resultSchema = CallToolResultSchema, options) {
36387
+ const clientInternal = this._client;
36388
+ const optionsWithTask = {
36389
+ ...options,
36390
+ task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)
36391
+ };
36392
+ const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
36393
+ const validator = clientInternal.getToolOutputValidator(params.name);
36394
+ for await (const message of stream) {
36395
+ if (message.type === "result" && validator) {
36396
+ const result = message.result;
36397
+ if (!result.structuredContent && !result.isError) {
36398
+ yield {
36399
+ type: "error",
36400
+ error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
36401
+ };
36402
+ return;
36403
+ }
36404
+ if (result.structuredContent) {
36405
+ try {
36406
+ const validationResult = validator(result.structuredContent);
36407
+ if (!validationResult.valid) {
36408
+ yield {
36409
+ type: "error",
36410
+ error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
36411
+ };
36412
+ return;
36413
+ }
36414
+ } catch (error) {
36415
+ if (error instanceof McpError) {
36416
+ yield { type: "error", error };
36417
+ return;
36418
+ }
36419
+ yield {
36420
+ type: "error",
36421
+ error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
36422
+ };
36423
+ return;
36424
+ }
36425
+ }
36426
+ }
36427
+ yield message;
36428
+ }
36429
+ }
36430
+ async getTask(taskId, options) {
36431
+ return this._client.getTask({ taskId }, options);
36432
+ }
36433
+ async getTaskResult(taskId, resultSchema, options) {
36434
+ return this._client.getTaskResult({ taskId }, resultSchema, options);
36435
+ }
36436
+ async listTasks(cursor, options) {
36437
+ return this._client.listTasks(cursor ? { cursor } : undefined, options);
36438
+ }
36439
+ async cancelTask(taskId, options) {
36440
+ return this._client.cancelTask({ taskId }, options);
36441
+ }
36442
+ requestStream(request, resultSchema, options) {
36443
+ return this._client.requestStream(request, resultSchema, options);
36444
+ }
36445
+ }
36446
+
36447
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
36448
+ init_helpers();
36449
+ function applyElicitationDefaults(schema, data) {
36450
+ if (!schema || data === null || typeof data !== "object")
36451
+ return;
36452
+ if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
36453
+ const obj = data;
36454
+ const props = schema.properties;
36455
+ for (const key of Object.keys(props)) {
36456
+ const propSchema = props[key];
36457
+ if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
36458
+ obj[key] = propSchema.default;
36459
+ }
36460
+ if (obj[key] !== undefined) {
36461
+ applyElicitationDefaults(propSchema, obj[key]);
36462
+ }
36463
+ }
36464
+ }
36465
+ if (Array.isArray(schema.anyOf)) {
36466
+ for (const sub of schema.anyOf) {
36467
+ if (typeof sub !== "boolean") {
36468
+ applyElicitationDefaults(sub, data);
36469
+ }
36470
+ }
36471
+ }
36472
+ if (Array.isArray(schema.oneOf)) {
36473
+ for (const sub of schema.oneOf) {
36474
+ if (typeof sub !== "boolean") {
36475
+ applyElicitationDefaults(sub, data);
36476
+ }
36477
+ }
36478
+ }
36479
+ }
36480
+ function getSupportedElicitationModes(capabilities) {
36481
+ if (!capabilities) {
36482
+ return { supportsFormMode: false, supportsUrlMode: false };
36483
+ }
36484
+ const hasFormCapability = capabilities.form !== undefined;
36485
+ const hasUrlCapability = capabilities.url !== undefined;
36486
+ const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
36487
+ const supportsUrlMode = hasUrlCapability;
36488
+ return { supportsFormMode, supportsUrlMode };
36489
+ }
36490
+
36491
+ class Client extends Protocol {
36492
+ constructor(_clientInfo, options) {
36493
+ super(options);
36494
+ this._clientInfo = _clientInfo;
36495
+ this._cachedToolOutputValidators = new Map;
36496
+ this._cachedKnownTaskTools = new Set;
36497
+ this._cachedRequiredTaskTools = new Set;
36498
+ this._listChangedDebounceTimers = new Map;
36499
+ this._capabilities = options?.capabilities ?? {};
36500
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator;
36501
+ if (options?.listChanged) {
36502
+ this._pendingListChangedConfig = options.listChanged;
36503
+ }
36504
+ }
36505
+ _setupListChangedHandlers(config) {
36506
+ if (config.tools && this._serverCapabilities?.tools?.listChanged) {
36507
+ this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config.tools, async () => {
36508
+ const result = await this.listTools();
36509
+ return result.tools;
36510
+ });
36511
+ }
36512
+ if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {
36513
+ this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config.prompts, async () => {
36514
+ const result = await this.listPrompts();
36515
+ return result.prompts;
36516
+ });
36517
+ }
36518
+ if (config.resources && this._serverCapabilities?.resources?.listChanged) {
36519
+ this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config.resources, async () => {
36520
+ const result = await this.listResources();
36521
+ return result.resources;
36522
+ });
36523
+ }
36524
+ }
36525
+ get experimental() {
36526
+ if (!this._experimental) {
36527
+ this._experimental = {
36528
+ tasks: new ExperimentalClientTasks(this)
36529
+ };
36530
+ }
36531
+ return this._experimental;
36532
+ }
36533
+ registerCapabilities(capabilities) {
36534
+ if (this.transport) {
36535
+ throw new Error("Cannot register capabilities after connecting to transport");
36536
+ }
36537
+ this._capabilities = mergeCapabilities(this._capabilities, capabilities);
36538
+ }
36539
+ setRequestHandler(requestSchema, handler) {
36540
+ const shape = getObjectShape(requestSchema);
36541
+ const methodSchema = shape?.method;
36542
+ if (!methodSchema) {
36543
+ throw new Error("Schema is missing a method literal");
36544
+ }
36545
+ const methodValue = getLiteralValue(methodSchema);
36546
+ if (typeof methodValue !== "string") {
36547
+ throw new Error("Schema method literal must be a string");
36548
+ }
36549
+ const method = methodValue;
36550
+ if (method === "elicitation/create") {
36551
+ const wrappedHandler = async (request, extra) => {
36552
+ const validatedRequest = safeParse(ElicitRequestSchema, request);
36553
+ if (!validatedRequest.success) {
36554
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
36555
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
36556
+ }
36557
+ const { params } = validatedRequest.data;
36558
+ params.mode = params.mode ?? "form";
36559
+ const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
36560
+ if (params.mode === "form" && !supportsFormMode) {
36561
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
36562
+ }
36563
+ if (params.mode === "url" && !supportsUrlMode) {
36564
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
36565
+ }
36566
+ const result = await Promise.resolve(handler(request, extra));
36567
+ if (params.task) {
36568
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
36569
+ if (!taskValidationResult.success) {
36570
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
36571
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
36572
+ }
36573
+ return taskValidationResult.data;
36574
+ }
36575
+ const validationResult = safeParse(ElicitResultSchema, result);
36576
+ if (!validationResult.success) {
36577
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
36578
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
36579
+ }
36580
+ const validatedResult = validationResult.data;
36581
+ const requestedSchema = params.mode === "form" ? params.requestedSchema : undefined;
36582
+ if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
36583
+ if (this._capabilities.elicitation?.form?.applyDefaults) {
36584
+ try {
36585
+ applyElicitationDefaults(requestedSchema, validatedResult.content);
36586
+ } catch {}
36587
+ }
36588
+ }
36589
+ return validatedResult;
36590
+ };
36591
+ return super.setRequestHandler(requestSchema, wrappedHandler);
36592
+ }
36593
+ if (method === "sampling/createMessage") {
36594
+ const wrappedHandler = async (request, extra) => {
36595
+ const validatedRequest = safeParse(CreateMessageRequestSchema, request);
36596
+ if (!validatedRequest.success) {
36597
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
36598
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
36599
+ }
36600
+ const { params } = validatedRequest.data;
36601
+ const result = await Promise.resolve(handler(request, extra));
36602
+ if (params.task) {
36603
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
36604
+ if (!taskValidationResult.success) {
36605
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
36606
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
36607
+ }
36608
+ return taskValidationResult.data;
36609
+ }
36610
+ const hasTools = params.tools || params.toolChoice;
36611
+ const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
36612
+ const validationResult = safeParse(resultSchema, result);
36613
+ if (!validationResult.success) {
36614
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
36615
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
36616
+ }
36617
+ return validationResult.data;
36618
+ };
36619
+ return super.setRequestHandler(requestSchema, wrappedHandler);
36620
+ }
36621
+ return super.setRequestHandler(requestSchema, handler);
36622
+ }
36623
+ assertCapability(capability, method) {
36624
+ if (!this._serverCapabilities?.[capability]) {
36625
+ throw new Error(`Server does not support ${capability} (required for ${method})`);
36626
+ }
36627
+ }
36628
+ async connect(transport, options) {
36629
+ await super.connect(transport);
36630
+ if (transport.sessionId !== undefined) {
36631
+ return;
36632
+ }
36633
+ try {
36634
+ const result = await this.request({
36635
+ method: "initialize",
36636
+ params: {
36637
+ protocolVersion: LATEST_PROTOCOL_VERSION,
36638
+ capabilities: this._capabilities,
36639
+ clientInfo: this._clientInfo
36640
+ }
36641
+ }, InitializeResultSchema, options);
36642
+ if (result === undefined) {
36643
+ throw new Error(`Server sent invalid initialize result: ${result}`);
36644
+ }
36645
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
36646
+ throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
36647
+ }
36648
+ this._serverCapabilities = result.capabilities;
36649
+ this._serverVersion = result.serverInfo;
36650
+ if (transport.setProtocolVersion) {
36651
+ transport.setProtocolVersion(result.protocolVersion);
36652
+ }
36653
+ this._instructions = result.instructions;
36654
+ await this.notification({
36655
+ method: "notifications/initialized"
36656
+ });
36657
+ if (this._pendingListChangedConfig) {
36658
+ this._setupListChangedHandlers(this._pendingListChangedConfig);
36659
+ this._pendingListChangedConfig = undefined;
36660
+ }
36661
+ } catch (error) {
36662
+ this.close();
36663
+ throw error;
36664
+ }
36665
+ }
36666
+ getServerCapabilities() {
36667
+ return this._serverCapabilities;
36668
+ }
36669
+ getServerVersion() {
36670
+ return this._serverVersion;
36671
+ }
36672
+ getInstructions() {
36673
+ return this._instructions;
36674
+ }
36675
+ assertCapabilityForMethod(method) {
36676
+ switch (method) {
36677
+ case "logging/setLevel":
36678
+ if (!this._serverCapabilities?.logging) {
36679
+ throw new Error(`Server does not support logging (required for ${method})`);
36680
+ }
36681
+ break;
36682
+ case "prompts/get":
36683
+ case "prompts/list":
36684
+ if (!this._serverCapabilities?.prompts) {
36685
+ throw new Error(`Server does not support prompts (required for ${method})`);
36686
+ }
36687
+ break;
36688
+ case "resources/list":
36689
+ case "resources/templates/list":
36690
+ case "resources/read":
36691
+ case "resources/subscribe":
36692
+ case "resources/unsubscribe":
36693
+ if (!this._serverCapabilities?.resources) {
36694
+ throw new Error(`Server does not support resources (required for ${method})`);
36695
+ }
36696
+ if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
36697
+ throw new Error(`Server does not support resource subscriptions (required for ${method})`);
36698
+ }
36699
+ break;
36700
+ case "tools/call":
36701
+ case "tools/list":
36702
+ if (!this._serverCapabilities?.tools) {
36703
+ throw new Error(`Server does not support tools (required for ${method})`);
36704
+ }
36705
+ break;
36706
+ case "completion/complete":
36707
+ if (!this._serverCapabilities?.completions) {
36708
+ throw new Error(`Server does not support completions (required for ${method})`);
36709
+ }
36710
+ break;
36711
+ case "initialize":
36712
+ break;
36713
+ case "ping":
36714
+ break;
36715
+ }
36716
+ }
36717
+ assertNotificationCapability(method) {
36718
+ switch (method) {
36719
+ case "notifications/roots/list_changed":
36720
+ if (!this._capabilities.roots?.listChanged) {
36721
+ throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
36722
+ }
36723
+ break;
36724
+ case "notifications/initialized":
36725
+ break;
36726
+ case "notifications/cancelled":
36727
+ break;
36728
+ case "notifications/progress":
36729
+ break;
36730
+ }
36731
+ }
36732
+ assertRequestHandlerCapability(method) {
36733
+ if (!this._capabilities) {
36734
+ return;
36735
+ }
36736
+ switch (method) {
36737
+ case "sampling/createMessage":
36738
+ if (!this._capabilities.sampling) {
36739
+ throw new Error(`Client does not support sampling capability (required for ${method})`);
36740
+ }
36741
+ break;
36742
+ case "elicitation/create":
36743
+ if (!this._capabilities.elicitation) {
36744
+ throw new Error(`Client does not support elicitation capability (required for ${method})`);
36745
+ }
36746
+ break;
36747
+ case "roots/list":
36748
+ if (!this._capabilities.roots) {
36749
+ throw new Error(`Client does not support roots capability (required for ${method})`);
36750
+ }
36751
+ break;
36752
+ case "tasks/get":
36753
+ case "tasks/list":
36754
+ case "tasks/result":
36755
+ case "tasks/cancel":
36756
+ if (!this._capabilities.tasks) {
36757
+ throw new Error(`Client does not support tasks capability (required for ${method})`);
36758
+ }
36759
+ break;
36760
+ case "ping":
36761
+ break;
36762
+ }
36763
+ }
36764
+ assertTaskCapability(method) {
36765
+ assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
36766
+ }
36767
+ assertTaskHandlerCapability(method) {
36768
+ if (!this._capabilities) {
36769
+ return;
36770
+ }
36771
+ assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
36772
+ }
36773
+ async ping(options) {
36774
+ return this.request({ method: "ping" }, EmptyResultSchema, options);
36775
+ }
36776
+ async complete(params, options) {
36777
+ return this.request({ method: "completion/complete", params }, CompleteResultSchema, options);
36778
+ }
36779
+ async setLoggingLevel(level, options) {
36780
+ return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options);
36781
+ }
36782
+ async getPrompt(params, options) {
36783
+ return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options);
36784
+ }
36785
+ async listPrompts(params, options) {
36786
+ return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options);
36787
+ }
36788
+ async listResources(params, options) {
36789
+ return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options);
36790
+ }
36791
+ async listResourceTemplates(params, options) {
36792
+ return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options);
36793
+ }
36794
+ async readResource(params, options) {
36795
+ return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options);
36796
+ }
36797
+ async subscribeResource(params, options) {
36798
+ return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options);
36799
+ }
36800
+ async unsubscribeResource(params, options) {
36801
+ return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
36802
+ }
36803
+ async callTool(params, resultSchema = CallToolResultSchema, options) {
36804
+ if (this.isToolTaskRequired(params.name)) {
36805
+ throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
36806
+ }
36807
+ const result = await this.request({ method: "tools/call", params }, resultSchema, options);
36808
+ const validator = this.getToolOutputValidator(params.name);
36809
+ if (validator) {
36810
+ if (!result.structuredContent && !result.isError) {
36811
+ throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
36812
+ }
36813
+ if (result.structuredContent) {
36814
+ try {
36815
+ const validationResult = validator(result.structuredContent);
36816
+ if (!validationResult.valid) {
36817
+ throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
36818
+ }
36819
+ } catch (error) {
36820
+ if (error instanceof McpError) {
36821
+ throw error;
36822
+ }
36823
+ throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
36824
+ }
36825
+ }
36826
+ }
36827
+ return result;
36828
+ }
36829
+ isToolTask(toolName) {
36830
+ if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
36831
+ return false;
36832
+ }
36833
+ return this._cachedKnownTaskTools.has(toolName);
36834
+ }
36835
+ isToolTaskRequired(toolName) {
36836
+ return this._cachedRequiredTaskTools.has(toolName);
36837
+ }
36838
+ cacheToolMetadata(tools) {
36839
+ this._cachedToolOutputValidators.clear();
36840
+ this._cachedKnownTaskTools.clear();
36841
+ this._cachedRequiredTaskTools.clear();
36842
+ for (const tool of tools) {
36843
+ if (tool.outputSchema) {
36844
+ const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
36845
+ this._cachedToolOutputValidators.set(tool.name, toolValidator);
36846
+ }
36847
+ const taskSupport = tool.execution?.taskSupport;
36848
+ if (taskSupport === "required" || taskSupport === "optional") {
36849
+ this._cachedKnownTaskTools.add(tool.name);
36850
+ }
36851
+ if (taskSupport === "required") {
36852
+ this._cachedRequiredTaskTools.add(tool.name);
36853
+ }
36854
+ }
36855
+ }
36856
+ getToolOutputValidator(toolName) {
36857
+ return this._cachedToolOutputValidators.get(toolName);
36858
+ }
36859
+ async listTools(params, options) {
36860
+ const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
36861
+ this.cacheToolMetadata(result.tools);
36862
+ return result;
36863
+ }
36864
+ _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
36865
+ const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
36866
+ if (!parseResult.success) {
36867
+ throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
36868
+ }
36869
+ if (typeof options.onChanged !== "function") {
36870
+ throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
36871
+ }
36872
+ const { autoRefresh, debounceMs } = parseResult.data;
36873
+ const { onChanged } = options;
36874
+ const refresh = async () => {
36875
+ if (!autoRefresh) {
36876
+ onChanged(null, null);
36877
+ return;
36878
+ }
36879
+ try {
36880
+ const items = await fetcher();
36881
+ onChanged(null, items);
36882
+ } catch (e) {
36883
+ const error = e instanceof Error ? e : new Error(String(e));
36884
+ onChanged(error, null);
36885
+ }
36886
+ };
36887
+ const handler = () => {
36888
+ if (debounceMs) {
36889
+ const existingTimer = this._listChangedDebounceTimers.get(listType);
36890
+ if (existingTimer) {
36891
+ clearTimeout(existingTimer);
36892
+ }
36893
+ const timer = setTimeout(refresh, debounceMs);
36894
+ this._listChangedDebounceTimers.set(listType, timer);
36895
+ } else {
36896
+ refresh();
36897
+ }
36898
+ };
36899
+ this.setNotificationHandler(notificationSchema, handler);
36900
+ }
36901
+ async sendRootsListChanged() {
36902
+ return this.notification({ method: "notifications/roots/list_changed" });
36903
+ }
36904
+ }
36905
+
36906
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.js
36907
+ class InMemoryTransport {
36908
+ constructor() {
36909
+ this._messageQueue = [];
36910
+ }
36911
+ static createLinkedPair() {
36912
+ const clientTransport = new InMemoryTransport;
36913
+ const serverTransport = new InMemoryTransport;
36914
+ clientTransport._otherTransport = serverTransport;
36915
+ serverTransport._otherTransport = clientTransport;
36916
+ return [clientTransport, serverTransport];
36917
+ }
36918
+ async start() {
36919
+ while (this._messageQueue.length > 0) {
36920
+ const queuedMessage = this._messageQueue.shift();
36921
+ this.onmessage?.(queuedMessage.message, queuedMessage.extra);
36922
+ }
36923
+ }
36924
+ async close() {
36925
+ const other = this._otherTransport;
36926
+ this._otherTransport = undefined;
36927
+ await other?.close();
36928
+ this.onclose?.();
36929
+ }
36930
+ async send(message, options) {
36931
+ if (!this._otherTransport) {
36932
+ throw new Error("Not connected");
36933
+ }
36934
+ if (this._otherTransport.onmessage) {
36935
+ this._otherTransport.onmessage(message, { authInfo: options?.authInfo });
36936
+ } else {
36937
+ this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } });
36938
+ }
36939
+ }
36940
+ }
36941
+
36942
+ // src/http/tool-schema-estimate.ts
36943
+ init_server();
36944
+ init_tool_config();
36945
+ var isAlwaysLoad = (tool) => tool._meta?.["anthropic/alwaysLoad"] === true;
36946
+ function measureToolSchemas(tools, loading) {
36947
+ if (loading === "none")
36948
+ return { chars: 0, loadedCount: 0, deferredCount: 0 };
36949
+ const isLoaded = (tool) => {
36950
+ if (loading === "all")
36951
+ return true;
36952
+ if (loading === "core")
36953
+ return CORE_TOOLS.has(tool.name) || isAlwaysLoad(tool);
36954
+ return isAlwaysLoad(tool);
36955
+ };
36956
+ let chars = 0;
36957
+ let loadedCount = 0;
36958
+ for (const tool of tools) {
36959
+ if (isLoaded(tool)) {
36960
+ loadedCount++;
36961
+ chars += JSON.stringify({
36962
+ name: tool.name,
36963
+ description: tool.description ?? "",
36964
+ input_schema: tool.inputSchema
36965
+ }).length;
36966
+ } else {
36967
+ chars += tool.name.length + 1;
36968
+ }
36969
+ }
36970
+ return { chars, loadedCount, deferredCount: tools.length - loadedCount };
36971
+ }
36972
+ async function listSessionTools(opts) {
36973
+ const server = await createServer(opts);
36974
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
36975
+ await server.connect(serverTransport);
36976
+ const client = new Client({ name: "request-composition-estimate", version: "1" });
36977
+ try {
36978
+ await client.connect(clientTransport);
36979
+ return (await client.listTools()).tools;
36980
+ } finally {
36981
+ await client.close();
36982
+ await server.close();
36983
+ }
36984
+ }
36985
+ var MAX_MEMO_ENTRIES = 32;
36986
+ var toolListMemo = new Map;
36987
+ function listSessionToolsMemo(opts) {
36988
+ const key = JSON.stringify({
36989
+ opts,
36990
+ capabilities: process.env.CAPABILITIES ?? null,
36991
+ chatSdk: process.env.CHAT_SDK_ENABLED ?? null
36992
+ });
36993
+ const cached = toolListMemo.get(key);
36994
+ if (cached)
36995
+ return cached;
36996
+ if (toolListMemo.size >= MAX_MEMO_ENTRIES)
36997
+ toolListMemo.clear();
36998
+ const pending = listSessionTools(opts);
36999
+ toolListMemo.set(key, pending);
37000
+ pending.catch(() => toolListMemo.delete(key));
37001
+ return pending;
37002
+ }
37003
+
37004
+ // src/http/request-composition.ts
37005
+ init_utils2();
37006
+ var PostRequestCompositionResponseSchema = object2({
37007
+ ok: literal2(true),
37008
+ id: uuid(),
37009
+ seq: number2().int().min(0)
37010
+ });
37011
+ var GetRequestCompositionResponseSchema = object2({
37012
+ manifests: array2(RequestCompositionSchema)
37013
+ });
37014
+ var postRequestComposition = route({
37015
+ method: "post",
37016
+ path: "/api/tasks/{id}/request-composition",
37017
+ pattern: ["api", "tasks", null, "request-composition"],
37018
+ session: { taskParam: "id" },
37019
+ rbac: {
37020
+ ungated: "worker session telemetry, same posture as POST /api/tasks/{id}/context"
37021
+ },
37022
+ summary: "Record the request composition manifest of a task session",
37023
+ description: "The worker posts the size of each prompt part it assembled. The server adds the MCP tool-schema estimate for the agent's effective tool surface and stores the manifest as the session's next seq. A `harness-hook` post (pi, opencode) carries exact sizes measured from the request payload plus the call's prompt tokens: the server merges it with the session's worker manifest and folds the observed chars-to-tokens ratio into the provider's average. Only the agent assigned to the task may post, and a task keeps at most 100 manifests.",
37024
+ tags: ["Tasks"],
37025
+ params: object2({ id: string2() }),
37026
+ body: object2({
37027
+ sessionId: string2().min(1),
37028
+ provider: string2().min(1),
37029
+ model: string2().optional(),
37030
+ toolLoading: RequestCompositionToolLoadingSchema,
37031
+ parts: array2(RequestCompositionPartInputSchema).max(200),
37032
+ source: _enum2(["worker", "harness-hook"]).default("worker"),
37033
+ harness: object2({
37034
+ systemChars: number2().int().min(0),
37035
+ payloadChars: number2().int().min(0),
37036
+ promptTokens: number2().int().min(0),
37037
+ firstMessageChars: number2().int().min(0).optional()
37038
+ }).optional()
37039
+ }),
37040
+ responses: {
37041
+ 200: { description: "Manifest recorded", schema: PostRequestCompositionResponseSchema },
37042
+ 400: { description: "Validation error" },
37043
+ 403: { description: "Task is assigned to another agent" },
37044
+ 404: { description: "Task not found" },
37045
+ 429: { description: "The task already holds the maximum number of manifests" }
37046
+ },
37047
+ auth: { apiKey: true, agentId: true }
37048
+ });
37049
+ var getRequestComposition = route({
37050
+ method: "get",
37051
+ path: "/api/tasks/{id}/request-composition",
37052
+ pattern: ["api", "tasks", null, "request-composition"],
37053
+ session: { taskParam: "id" },
37054
+ summary: "Get the request composition manifests of a task",
37055
+ tags: ["Tasks"],
37056
+ params: object2({ id: string2() }),
37057
+ query: object2({
37058
+ limit: exports_coerce.number().int().min(1).max(MAX_REQUEST_COMPOSITIONS_PER_TASK).default(MAX_REQUEST_COMPOSITIONS_PER_TASK)
37059
+ }),
37060
+ responses: {
37061
+ 200: { description: "Manifests, oldest first", schema: GetRequestCompositionResponseSchema },
37062
+ 404: { description: "Task not found" }
37063
+ },
37064
+ auth: { apiKey: true }
37065
+ });
37066
+ var TOOL_SCHEMA_LABELS = {
37067
+ all: "swarm tool schemas",
37068
+ core: "swarm tool schemas (core + preloaded; deferred tools load into history)",
37069
+ preloaded: "swarm tool schemas (preloaded only; deferred tools load into history)"
37070
+ };
37071
+ async function toolSchemaPart(agentId, task, loading) {
37072
+ if (loading === "none")
37073
+ return null;
37074
+ try {
37075
+ const tools = await listSessionToolsMemo(await resolveMcpSessionOptions(agentId, task));
37076
+ const { chars } = measureToolSchemas(tools, loading);
37077
+ return {
37078
+ kind: "tool_schemas",
37079
+ id: "mcp:agent-swarm",
37080
+ label: TOOL_SCHEMA_LABELS[loading],
37081
+ chars,
37082
+ estTokens: estimateTokens(chars),
37083
+ fidelity: "estimate"
37084
+ };
37085
+ } catch (err) {
37086
+ console.warn(`[request-composition] Tool schema estimate failed: ${err instanceof Error ? err.message : err}`);
37087
+ return null;
37088
+ }
37089
+ }
37090
+ var SYSTEM_PROMPT_KINDS = new Set([
37091
+ "system_section",
37092
+ "persona",
37093
+ "claude_md",
37094
+ "operator_prompt"
37095
+ ]);
37096
+ function mergeHookParts(hookParts, harness, worker) {
37097
+ const exactPart = (id, label, chars) => ({
37098
+ kind: "system_section",
37099
+ id,
37100
+ label,
37101
+ chars,
37102
+ estTokens: estimateTokens(chars),
37103
+ fidelity: "exact"
37104
+ });
37105
+ const hookSkillsChars = hookParts.filter((part) => part.kind === "skills_listing").reduce((sum, part) => sum + part.chars, 0);
37106
+ const harnessSystemChars = Math.max(0, harness.systemChars - hookSkillsChars);
37107
+ if (!worker) {
37108
+ return [exactPart("harness:system", "system prompt as sent", harnessSystemChars), ...hookParts];
37109
+ }
37110
+ const carried = worker.parts.filter((part) => part.kind !== "tool_schemas" && !(part.kind === "skills_listing" && hookSkillsChars > 0));
37111
+ const ours = carried.filter((part) => SYSTEM_PROMPT_KINDS.has(part.kind)).reduce((sum, part) => sum + part.chars, 0);
37112
+ const baseChars = harnessSystemChars - ours;
37113
+ const messageExtraChars = harness.firstMessageChars === undefined ? 0 : harness.firstMessageChars - carried.filter((part) => part.kind === "task_prompt" || part.kind === "memories").reduce((sum, part) => sum + part.chars, 0);
37114
+ return [
37115
+ ...carried,
37116
+ ...baseChars > 0 ? [exactPart("harness:base", "harness base prompt", baseChars)] : [],
37117
+ ...messageExtraChars > 0 ? [exactPart("harness:messages", "harness context in the first message", messageExtraChars)] : [],
37118
+ ...hookParts
37119
+ ];
37120
+ }
37121
+ function observedTokenRatio(promptTokens, payloadChars) {
37122
+ if (!(promptTokens > 0) || !(payloadChars > 0))
37123
+ return null;
37124
+ return promptTokens / (payloadChars / 4);
37125
+ }
37126
+ async function handleRequestComposition(req, res, pathSegments, queryParams, myAgentId) {
37127
+ if (postRequestComposition.match(req.method, pathSegments)) {
37128
+ if (!myAgentId) {
37129
+ jsonError(res, "Missing X-Agent-ID header", 400);
37130
+ return true;
37131
+ }
37132
+ const parsed = await postRequestComposition.parse(req, res, pathSegments, queryParams);
37133
+ if (!parsed)
37134
+ return true;
37135
+ const task = await getTaskById2(parsed.params.id);
37136
+ if (!task) {
37137
+ jsonError(res, "Task not found", 404);
37138
+ return true;
37139
+ }
37140
+ if (task.agentId !== myAgentId) {
37141
+ jsonError(res, "Task is assigned to another agent", 403);
37142
+ return true;
37143
+ }
37144
+ const { body } = parsed;
37145
+ let parts = body.parts.map((part) => ({
37146
+ ...part,
37147
+ estTokens: estimateTokens(part.chars)
37148
+ }));
37149
+ let tokenRatio;
37150
+ if (body.source === "harness-hook") {
37151
+ if (!body.harness) {
37152
+ jsonError(res, "harness-hook manifests require `harness` totals", 400);
37153
+ return true;
37154
+ }
37155
+ parts = mergeHookParts(parts, body.harness, await getLatestWorkerComposition(body.sessionId));
37156
+ const observed = observedTokenRatio(body.harness.promptTokens, body.harness.payloadChars);
37157
+ if (observed === null) {
37158
+ tokenRatio = await getTokenRatio(body.provider);
37159
+ } else {
37160
+ tokenRatio = clampTokenRatio(observed);
37161
+ await recordTokenRatio(body.provider, observed);
37162
+ }
37163
+ } else {
37164
+ const toolPart = await toolSchemaPart(myAgentId, task, body.toolLoading);
37165
+ if (toolPart)
37166
+ parts.push(toolPart);
37167
+ tokenRatio = await getTokenRatio(body.provider);
37168
+ }
37169
+ const manifest = await createRequestComposition({
37170
+ taskId: task.id,
37171
+ agentId: myAgentId,
37172
+ sessionId: body.sessionId,
37173
+ provider: body.provider,
37174
+ model: body.model,
37175
+ source: body.source,
37176
+ parts,
37177
+ tokenRatio
37178
+ });
37179
+ if (!manifest) {
37180
+ jsonError(res, `Task already holds ${MAX_REQUEST_COMPOSITIONS_PER_TASK} request composition manifests`, 429);
37181
+ return true;
37182
+ }
37183
+ postRequestComposition.respond(res, 200, { ok: true, id: manifest.id, seq: manifest.seq });
37184
+ return true;
37185
+ }
37186
+ if (getRequestComposition.match(req.method, pathSegments)) {
37187
+ const parsed = await getRequestComposition.parse(req, res, pathSegments, queryParams);
37188
+ if (!parsed)
37189
+ return true;
37190
+ const task = await getTaskById2(parsed.params.id);
37191
+ if (!task) {
37192
+ jsonError(res, "Task not found", 404);
37193
+ return true;
37194
+ }
37195
+ const manifests = await getRequestCompositionsByTask(task.id, parsed.query.limit);
37196
+ getRequestComposition.respond(res, 200, { manifests });
37197
+ return true;
37198
+ }
37199
+ return false;
37200
+ }
37201
+
34997
37202
  // src/http/rooms.ts
34998
37203
  init_zod();
34999
37204
  init_auth2();
@@ -35744,8 +37949,8 @@ function daysBetween(firstDay, lastDay) {
35744
37949
  }
35745
37950
  var sliceCache = new Map;
35746
37951
  var SLICE_TTL_MS = 2 * MINUTE_MS;
35747
- var HOUR_MS = 60 * MINUTE_MS;
35748
- var FLEET_SLICE_TTL_MS = HOUR_MS + 2 * MINUTE_MS;
37952
+ var HOUR_MS2 = 60 * MINUTE_MS;
37953
+ var FLEET_SLICE_TTL_MS = HOUR_MS2 + 2 * MINUTE_MS;
35749
37954
  var FIRST_DAY_SCAN_CONCURRENCY = 2;
35750
37955
  var scansInFlight = 0;
35751
37956
  var scanWaiters = [];
@@ -36009,7 +38214,7 @@ async function clipFirstDay(buckets, window, firstDay, fleet, sql = (q, p) => ge
36009
38214
  const startMs = Date.parse(window.start);
36010
38215
  if (window.start === dayStartIso(firstDay))
36011
38216
  return false;
36012
- const sliceStart = fleet ? new Date(Math.floor(startMs / HOUR_MS) * HOUR_MS).toISOString() : window.start;
38217
+ const sliceStart = fleet ? new Date(Math.floor(startMs / HOUR_MS2) * HOUR_MS2).toISOString() : window.start;
36013
38218
  const first = buckets.filter((b) => b.day === firstDay);
36014
38219
  if (first.length === 0)
36015
38220
  return false;
@@ -36453,7 +38658,7 @@ async function clipScriptFirstDay(jobs, window, firstDay, opts) {
36453
38658
  const startMs = Date.parse(window.start);
36454
38659
  if (window.start === dayStartIso(firstDay))
36455
38660
  return false;
36456
- const sliceStart = fleet ? new Date(Math.floor(startMs / HOUR_MS) * HOUR_MS).toISOString() : window.start;
38661
+ const sliceStart = fleet ? new Date(Math.floor(startMs / HOUR_MS2) * HOUR_MS2).toISOString() : window.start;
36457
38662
  if (![...jobs.values()].some((j) => j.days.has(firstDay)))
36458
38663
  return false;
36459
38664
  const slice = { start: sliceStart, end: dayStartIso(utcDay(startMs + DAY_MS3)) };
@@ -41950,151 +44155,7 @@ init_request_auth_context();
41950
44155
  init_secret_scrubber();
41951
44156
  init_route_def();
41952
44157
  init_session_access();
41953
-
41954
- // src/http/session-cost-recompute.ts
41955
- init_pricing_normalize();
41956
- init_amp_models();
41957
- var PER_MILLION = 1e6;
41958
- var INCLUSIVE_INPUT_PROVIDERS = new Set(["codex"]);
41959
- function cacheWriteSplit(input) {
41960
- if (input.cacheWrite5mTokens == null || input.cacheWrite1hTokens == null)
41961
- return null;
41962
- const total = input.cacheWrite5mTokens + input.cacheWrite1hTokens;
41963
- if (total === 0)
41964
- return null;
41965
- return {
41966
- fiveMinuteRatio: input.cacheWrite5mTokens / total,
41967
- oneHourRatio: input.cacheWrite1hTokens / total
41968
- };
41969
- }
41970
- async function priceModel(provider, usage, split, atEpochMs, lookupRate) {
41971
- const lookupModel = normalizeModelKey(provider, usage.model);
41972
- const inputRate = await lookupRate(provider, lookupModel, "input", atEpochMs);
41973
- const outputRate = await lookupRate(provider, lookupModel, "output", atEpochMs);
41974
- if (inputRate == null || outputRate == null)
41975
- return null;
41976
- const cacheReadRate = await lookupRate(provider, lookupModel, "cached_input", atEpochMs) ?? 0;
41977
- const uncachedInputTokens = INCLUSIVE_INPUT_PROVIDERS.has(provider) ? Math.max(0, usage.inputTokens - usage.cacheReadTokens) : usage.inputTokens;
41978
- let cacheWriteCostUnits = 0;
41979
- if (split) {
41980
- const fiveMinuteTokens = usage.cacheWriteTokens * split.fiveMinuteRatio;
41981
- const oneHourTokens = usage.cacheWriteTokens * split.oneHourRatio;
41982
- const fiveMinuteRate = await lookupRate(provider, lookupModel, "cache_write", atEpochMs) ?? 0;
41983
- const oneHourRate = await lookupRate(provider, lookupModel, "cache_write_1h", atEpochMs);
41984
- if (oneHourTokens > 0 && oneHourRate == null)
41985
- return null;
41986
- cacheWriteCostUnits = fiveMinuteTokens * fiveMinuteRate + oneHourTokens * (oneHourRate ?? 0);
41987
- } else {
41988
- const cacheWriteRate = await lookupRate(provider, lookupModel, "cache_write", atEpochMs) ?? 0;
41989
- cacheWriteCostUnits = usage.cacheWriteTokens * cacheWriteRate;
41990
- }
41991
- return (uncachedInputTokens * inputRate + usage.cacheReadTokens * cacheReadRate + cacheWriteCostUnits + usage.outputTokens * outputRate) / PER_MILLION;
41992
- }
41993
- function unpricedResult(input, modelBreakdown) {
41994
- return {
41995
- totalCostUsd: input.harnessCostUsd,
41996
- costSource: "unpriced",
41997
- modelBreakdown
41998
- };
41999
- }
42000
- async function estimateAmpCost(input, lookupRate) {
42001
- let selection;
42002
- try {
42003
- selection = resolveAmpModel(input.model);
42004
- } catch {
42005
- selection = undefined;
42006
- }
42007
- const candidates = [
42008
- ...new Set([
42009
- selection?.pin,
42010
- selection ? AMP_ESTIMATE_MODELS[selection.baseMode] : undefined,
42011
- AMP_ESTIMATE_MODELS.medium
42012
- ])
42013
- ].filter((model) => !!model);
42014
- for (const model of candidates) {
42015
- const writes = ampBillsCacheWrites(model);
42016
- const costUsd = await priceModel("amp", {
42017
- model,
42018
- inputTokens: input.inputTokens + (writes ? 0 : input.cacheWriteTokens),
42019
- outputTokens: input.outputTokens,
42020
- cacheReadTokens: input.cacheReadTokens,
42021
- cacheWriteTokens: writes ? input.cacheWriteTokens : 0
42022
- }, null, input.atEpochMs, lookupRate);
42023
- if (costUsd != null)
42024
- return { totalCostUsd: costUsd, costSource: "estimated", modelBreakdown: undefined };
42025
- }
42026
- return unpricedResult(input, undefined);
42027
- }
42028
- async function recomputeSessionCost(input, lookupRate) {
42029
- const modelUsageEntries = input.models?.length ? input.models : undefined;
42030
- const modelBreakdown = modelUsageEntries?.map((model) => ({ ...model }));
42031
- if (!input.provider) {
42032
- return {
42033
- totalCostUsd: input.harnessCostUsd,
42034
- costSource: "harness",
42035
- modelBreakdown
42036
- };
42037
- }
42038
- if ((input.provider === "amp" || input.provider === "grok" || input.harnessCostBilled) && input.harnessCostUsd > 0) {
42039
- const priced = await recomputeSessionCost({ ...input, harnessCostUsd: 0, harnessCostBilled: false }, lookupRate);
42040
- return {
42041
- totalCostUsd: input.harnessCostUsd,
42042
- costSource: "harness",
42043
- modelBreakdown: priced.modelBreakdown
42044
- };
42045
- }
42046
- if (input.provider === "acp" && input.harnessCostUsd > 0) {
42047
- return { totalCostUsd: input.harnessCostUsd, costSource: "harness", modelBreakdown };
42048
- }
42049
- if (input.provider === "amp" && !modelUsageEntries)
42050
- return estimateAmpCost(input, lookupRate);
42051
- const split = cacheWriteSplit(input);
42052
- const usages = modelUsageEntries ? modelUsageEntries : input.model ? [
42053
- {
42054
- model: input.model,
42055
- inputTokens: input.inputTokens,
42056
- outputTokens: input.outputTokens,
42057
- cacheReadTokens: input.cacheReadTokens,
42058
- cacheWriteTokens: input.cacheWriteTokens
42059
- }
42060
- ] : [];
42061
- if (usages.length === 0) {
42062
- return {
42063
- totalCostUsd: input.harnessCostUsd,
42064
- costSource: "harness",
42065
- modelBreakdown
42066
- };
42067
- }
42068
- const pricedModels = [];
42069
- let pricedCostUsd = 0;
42070
- const hasWebSearchRequests = usages.some((usage) => (usage.webSearchRequests ?? 0) > 0);
42071
- const webSearchRate = hasWebSearchRequests ? await lookupRate(input.provider, "*", "web_search", input.atEpochMs) : null;
42072
- for (const usage of usages) {
42073
- const tokenCostUsd = await priceModel(input.provider, usage, split, input.atEpochMs, lookupRate);
42074
- if (tokenCostUsd == null)
42075
- return unpricedResult(input, modelBreakdown);
42076
- const webSearchCostUsd = (usage.webSearchRequests ?? 0) * (webSearchRate ?? 0) / PER_MILLION;
42077
- const costUsd = tokenCostUsd + webSearchCostUsd;
42078
- pricedCostUsd += costUsd;
42079
- if (modelUsageEntries)
42080
- pricedModels.push({ ...usage, costUsd });
42081
- }
42082
- let sessionFeesUsd = 0;
42083
- const durationMs = input.durationMs ?? 0;
42084
- if (input.provider === "claude-managed" && durationMs > 0) {
42085
- const runtimeRate = await lookupRate(input.provider, "*", "runtime_hour", input.atEpochMs);
42086
- if (runtimeRate == null)
42087
- return unpricedResult(input, modelBreakdown);
42088
- sessionFeesUsd += durationMs / 3600000 * (runtimeRate / PER_MILLION);
42089
- }
42090
- return {
42091
- totalCostUsd: pricedCostUsd + sessionFeesUsd,
42092
- costSource: "pricing-table",
42093
- modelBreakdown: modelUsageEntries ? pricedModels : undefined
42094
- };
42095
- }
42096
-
42097
- // src/http/session-data.ts
44158
+ init_session_cost_recompute();
42098
44159
  init_utils2();
42099
44160
  var SessionCostSummaryTotalsSchema = object2({
42100
44161
  totalCostUsd: number2(),
@@ -42552,7 +44613,7 @@ init_bus();
42552
44613
 
42553
44614
  // src/slack/channel-labels.ts
42554
44615
  init_session_labels();
42555
- init_app3();
44616
+ init_app4();
42556
44617
  init_render_v2();
42557
44618
  var LABEL_TTL_MS = 24 * 60 * 60 * 1000;
42558
44619
  var FAILURE_TTL_MS = 10 * 60 * 1000;
@@ -44798,7 +46859,7 @@ async function handleSkills(req, res, pathSegments, queryParams, myAgentId) {
44798
46859
  }
44799
46860
 
44800
46861
  // src/http/slack-events.ts
44801
- init_app3();
46862
+ init_app4();
44802
46863
  init_config4();
44803
46864
  init_route_def();
44804
46865
  init_utils2();
@@ -45385,7 +47446,7 @@ async function handleTelemetryUi(req, res, pathSegments, queryParams, myAgentId)
45385
47446
  await upsertSwarmConfig2({ scope: "global", key: "ANONYMIZED_TELEMETRY", value: "true" });
45386
47447
  process.env.ANONYMIZED_TELEMETRY = "true";
45387
47448
  await syncTelemetryEnabled(parsed.body.via);
45388
- scheduleIntegrationsReload();
47449
+ scheduleIntegrationsReload2();
45389
47450
  enableTelemetry.respond(res, 200, { enabled: isTelemetryEnabled() });
45390
47451
  return true;
45391
47452
  }
@@ -45414,10 +47475,120 @@ async function handleTelemetryUi(req, res, pathSegments, queryParams, myAgentId)
45414
47475
  return true;
45415
47476
  }
45416
47477
 
47478
+ // src/http/tool-hooks.ts
47479
+ init_zod();
47480
+ init_dispatcher();
47481
+ init_secret_scrubber();
47482
+ init_route_def();
47483
+ init_utils2();
47484
+ var REDACTION_MARKER = "[REDACTED:";
47485
+ var toolCallFields = {
47486
+ harness: string2().min(1).max(64).describe("Worker harness, such as `claude` or `pi`."),
47487
+ tool: string2().min(1).max(256).describe("Canonical tool name, such as `bash` or `edit`."),
47488
+ nativeTool: string2().min(1).max(256).optional().describe("The harness's own tool name."),
47489
+ args: unknown().describe("Canonical tool arguments."),
47490
+ rawArgs: unknown().optional().describe("The harness's own argument shape."),
47491
+ toolCallId: string2().max(256).optional(),
47492
+ parentToolCallId: string2().max(256).optional()
47493
+ };
47494
+ var toolHookBody = discriminatedUnion("phase", [
47495
+ object2({ phase: literal2("pre"), ...toolCallFields }),
47496
+ object2({
47497
+ phase: literal2("post"),
47498
+ ...toolCallFields,
47499
+ result: unknown(),
47500
+ isError: boolean().optional(),
47501
+ durationMs: number2().nonnegative()
47502
+ })
47503
+ ]);
47504
+ var toolHookDecision = discriminatedUnion("action", [
47505
+ object2({ action: literal2("continue") }),
47506
+ object2({ action: literal2("modify"), args: unknown() }),
47507
+ object2({ action: literal2("block"), reason: string2() })
47508
+ ]);
47509
+ var toolHookRoute = route({
47510
+ method: "post",
47511
+ path: "/api/tool-hooks",
47512
+ pattern: ["api", "tool-hooks"],
47513
+ summary: "Run extension tool hooks for a harness-native tool call",
47514
+ description: "A worker shim reports a harness built-in tool call (bash, read, write, edit). `phase: pre` " + "runs `pre.tool.call` with `callOrigin: native` and returns the decision. `phase: post` runs " + "`post.tool.call` observe-only and returns 202 at once. Only extensions whose manifest " + '`toolSources` includes `"native"` receive these calls. The server runs the secret scrubber ' + "over the body before any handler sees it, so handlers read `[REDACTED:<name>]` in place of " + "a secret. A `modify` whose args still carry that marker is rejected and the call continues " + "unchanged. Shims must also scrub worker-side before sending.",
47515
+ tags: ["Extensions"],
47516
+ auth: { apiKey: true, agentId: true },
47517
+ body: toolHookBody,
47518
+ maxBodyBytes: 2 * 1024 * 1024,
47519
+ rbac: { ungated: "self-scoped: an agent reports its own harness tool calls" },
47520
+ responses: {
47521
+ 200: { description: "Pre-call decision", schema: toolHookDecision },
47522
+ 202: {
47523
+ description: "Post-call event accepted",
47524
+ schema: object2({ accepted: literal2(true) })
47525
+ },
47526
+ 400: { description: "Invalid body or missing X-Agent-ID header" }
47527
+ }
47528
+ });
47529
+ function header3(req, name) {
47530
+ const raw = req.headers[name];
47531
+ return Array.isArray(raw) ? raw[0] : raw;
47532
+ }
47533
+ async function handleToolHooks(req, res, pathSegments, queryParams, myAgentId) {
47534
+ if (!toolHookRoute.match(req.method, pathSegments))
47535
+ return false;
47536
+ if (!myAgentId) {
47537
+ jsonError(res, "Missing X-Agent-ID header", 400);
47538
+ return true;
47539
+ }
47540
+ const parsed = await toolHookRoute.parse(req, res, pathSegments, queryParams);
47541
+ if (!parsed)
47542
+ return true;
47543
+ const body = scrubObject(parsed.body);
47544
+ const requestInfo = {
47545
+ sessionId: undefined,
47546
+ agentId: myAgentId,
47547
+ runtimeInstanceId: header3(req, "x-runtime-instance-id"),
47548
+ sourceTaskId: header3(req, "x-source-task-id"),
47549
+ contextKey: header3(req, "x-context-key"),
47550
+ callOrigin: "native",
47551
+ harness: body.harness
47552
+ };
47553
+ const event = {
47554
+ tool: body.tool,
47555
+ args: body.args,
47556
+ requestInfo,
47557
+ nativeTool: body.nativeTool,
47558
+ rawArgs: body.rawArgs,
47559
+ toolCallId: body.toolCallId,
47560
+ parentToolCallId: body.parentToolCallId
47561
+ };
47562
+ if (body.phase === "post") {
47563
+ toolHookRoute.respond(res, 202, { accepted: true });
47564
+ dispatchPost2("post.tool.call", {
47565
+ ...event,
47566
+ result: body.result,
47567
+ isError: body.isError,
47568
+ durationMs: body.durationMs
47569
+ });
47570
+ return true;
47571
+ }
47572
+ const result = await dispatchPre2("pre.tool.call", event, {
47573
+ validateModify: (data) => JSON.stringify(data.args ?? null).includes(REDACTION_MARKER) ? {
47574
+ success: false,
47575
+ error: new Error(`Modified arguments for native tool "${body.tool}" contain a redaction marker`)
47576
+ } : { success: true, data }
47577
+ });
47578
+ if (result.action === "block") {
47579
+ toolHookRoute.respond(res, 200, { action: "block", reason: result.reason });
47580
+ } else if (result.action === "modify") {
47581
+ toolHookRoute.respond(res, 200, { action: "modify", args: result.data.args });
47582
+ } else {
47583
+ toolHookRoute.respond(res, 200, { action: "continue" });
47584
+ }
47585
+ return true;
47586
+ }
47587
+
45417
47588
  // src/http/trackers/jira.ts
45418
47589
  init_zod();
45419
47590
  init_oauth();
45420
- init_app();
47591
+ init_app2();
45421
47592
  init_metadata();
45422
47593
  init_webhook();
45423
47594
  init_webhook_lifecycle();
@@ -45831,11 +48002,11 @@ async function handleJiraTracker(req, res, pathSegments) {
45831
48002
  // src/http/trackers/linear.ts
45832
48003
  init_zod();
45833
48004
  init_oauth();
45834
- init_app2();
48005
+ init_app3();
45835
48006
 
45836
48007
  // src/linear/webhook.ts
45837
48008
  init_sync();
45838
- import { createHmac, timingSafeEqual } from "node:crypto";
48009
+ import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
45839
48010
  var recentDeliveries = new Map;
45840
48011
  var DEDUP_TTL_MS = 5 * 60 * 1000;
45841
48012
  function cleanupDeliveries() {
@@ -45846,9 +48017,9 @@ function cleanupDeliveries() {
45846
48017
  }
45847
48018
  }
45848
48019
  function verifyLinearWebhook(rawBody, signature, secret) {
45849
- const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
48020
+ const expected = createHmac2("sha256", secret).update(rawBody).digest("hex");
45850
48021
  try {
45851
- return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
48022
+ return timingSafeEqual2(Buffer.from(signature), Buffer.from(expected));
45852
48023
  } catch {
45853
48024
  return false;
45854
48025
  }
@@ -46779,14 +48950,15 @@ var mergeUsersRoute = route({
46779
48950
  method: "post",
46780
48951
  path: "/api/users/{id}/merge",
46781
48952
  pattern: ["api", "users", null, "merge"],
46782
- summary: "Merge another user into this one — moves identities + email aliases, deletes source",
48953
+ summary: "Merge another user into this one: moves identities + email aliases, queues the rest",
48954
+ description: "Moves the source's identities and email aliases to the target, revokes the source's credentials and records a manual_merge event, all in one short transaction. The attribution rewrite across every table and the deletion of the source run as a background job; poll GET /api/users/merge-jobs/{jobId} until its status is done or failed. While the job runs, the source cannot authenticate and identity lookups resolve to the target.",
46783
48955
  tags: ["Users"],
46784
48956
  params: object2({ id: string2() }),
46785
48957
  body: object2({ sourceUserId: string2().min(1) }),
46786
48958
  responses: {
46787
- 200: {
46788
- description: "Merged user",
46789
- schema: object2({ user: ComposedUserSchema.nullable() })
48959
+ 202: {
48960
+ description: "The queued merge job",
48961
+ schema: object2({ job: UserMergeJobSchema })
46790
48962
  },
46791
48963
  400: { description: "Validation error (e.g. target == source)" },
46792
48964
  401: { description: "Unauthorized" },
@@ -46794,7 +48966,45 @@ var mergeUsersRoute = route({
46794
48966
  description: "Target holds an operator-granted role (auditor) and the caller is not the operator key"
46795
48967
  },
46796
48968
  404: { description: "Target or source user not found" },
46797
- 409: { description: "Source is the last active admin (last_admin)" }
48969
+ 409: {
48970
+ description: "Source is the last active admin (last_admin), or a merge job for the source or target is still running (merge_in_progress)"
48971
+ }
48972
+ },
48973
+ auth: { apiKey: true }
48974
+ });
48975
+ var listMergeJobsRoute = route({
48976
+ method: "get",
48977
+ path: "/api/users/merge-jobs",
48978
+ pattern: ["api", "users", "merge-jobs"],
48979
+ summary: "List background user merge jobs, newest first",
48980
+ tags: ["Users"],
48981
+ query: object2({
48982
+ status: UserMergeJobStatusSchema.optional(),
48983
+ limit: exports_coerce.number().int().min(1).max(200).optional()
48984
+ }),
48985
+ responses: {
48986
+ 200: {
48987
+ description: "Merge jobs",
48988
+ schema: object2({ jobs: array2(UserMergeJobSchema) })
48989
+ },
48990
+ 401: { description: "Unauthorized" }
48991
+ },
48992
+ auth: { apiKey: true }
48993
+ });
48994
+ var getMergeJobRoute = route({
48995
+ method: "get",
48996
+ path: "/api/users/merge-jobs/{jobId}",
48997
+ pattern: ["api", "users", "merge-jobs", null],
48998
+ summary: "A background user merge job (poll until status is done or failed)",
48999
+ tags: ["Users"],
49000
+ params: object2({ jobId: string2() }),
49001
+ responses: {
49002
+ 200: {
49003
+ description: "The merge job",
49004
+ schema: object2({ job: UserMergeJobSchema })
49005
+ },
49006
+ 401: { description: "Unauthorized" },
49007
+ 404: { description: "Job not found" }
46798
49008
  },
46799
49009
  auth: { apiKey: true }
46800
49010
  });
@@ -47416,6 +49626,29 @@ async function handleUsers(req, res, pathSegments, queryParams) {
47416
49626
  }
47417
49627
  return true;
47418
49628
  }
49629
+ if (listMergeJobsRoute.match(req.method, pathSegments)) {
49630
+ const parsed = await listMergeJobsRoute.parse(req, res, pathSegments, queryParams);
49631
+ if (!parsed)
49632
+ return true;
49633
+ const jobs = await listUserMergeJobs2({
49634
+ status: parsed.query.status,
49635
+ limit: parsed.query.limit
49636
+ });
49637
+ listMergeJobsRoute.respond(res, 200, { jobs });
49638
+ return true;
49639
+ }
49640
+ if (getMergeJobRoute.match(req.method, pathSegments)) {
49641
+ const parsed = await getMergeJobRoute.parse(req, res, pathSegments, queryParams);
49642
+ if (!parsed)
49643
+ return true;
49644
+ const job = await getUserMergeJob2(parsed.params.jobId);
49645
+ if (!job) {
49646
+ jsonError(res, "Merge job not found", 404);
49647
+ return true;
49648
+ }
49649
+ getMergeJobRoute.respond(res, 200, { job });
49650
+ return true;
49651
+ }
47419
49652
  if (mergeUsersRoute.match(req.method, pathSegments)) {
47420
49653
  const parsed = await mergeUsersRoute.parse(req, res, pathSegments, queryParams);
47421
49654
  if (!parsed)
@@ -47439,8 +49672,23 @@ async function handleUsers(req, res, pathSegments, queryParams) {
47439
49672
  jsonError(res, "Source user not found", 404);
47440
49673
  return true;
47441
49674
  }
49675
+ if (targetBefore.mergedIntoUserId || await findActiveUserMergeJob2(sourceId) || await findActiveUserMergeJob2(targetId)) {
49676
+ jsonError(res, "merge_in_progress", 409);
49677
+ return true;
49678
+ }
49679
+ if (sourceBefore.mergedIntoUserId) {
49680
+ const failed = await findFailedUserMergeJob2(sourceId, targetId);
49681
+ if (failed) {
49682
+ const requeued = await requeueUserMergeJob2(failed.id);
49683
+ if (requeued) {
49684
+ runUserMergeJobs2();
49685
+ mergeUsersRoute.respond(res, 202, { job: requeued });
49686
+ return true;
49687
+ }
49688
+ }
49689
+ }
47442
49690
  try {
47443
- const mergedUser = await getDbClient2().transaction(async () => {
49691
+ const job = await getDbClient2().transaction(async () => {
47444
49692
  await assertMayActOnOperatorGrantedTarget2(actor, targetId);
47445
49693
  for (const ident of sourceBefore.identities) {
47446
49694
  await unlinkIdentity(sourceId, ident.kind, ident.externalId, actor);
@@ -47469,7 +49717,8 @@ async function handleUsers(req, res, pathSegments, queryParams) {
47469
49717
  }
47470
49718
  }
47471
49719
  await assertNotLastAdmin2(sourceId);
47472
- await deleteUser2(sourceId, targetId);
49720
+ await revokeAllUserCredentials(sourceId, actor);
49721
+ await getDbClient2().run("UPDATE users SET mergedIntoUserId = ?, lastUpdatedAt = ? WHERE id = ?", [targetId, new Date().toISOString(), sourceId]);
47473
49722
  const targetAfter = await composeUser(targetId);
47474
49723
  await recordIdentityEvent(targetId, "manual_merge", actor, targetBefore, {
47475
49724
  ...targetAfter,
@@ -47479,9 +49728,17 @@ async function handleUsers(req, res, pathSegments, queryParams) {
47479
49728
  email: sourceBefore.email
47480
49729
  }
47481
49730
  });
47482
- return await composeUser(targetId);
49731
+ const queued = await createUserMergeJob2({
49732
+ sourceUserId: sourceId,
49733
+ targetUserId: targetId,
49734
+ createdBy: authUser(getRequestAuth(req))?.id ?? null
49735
+ });
49736
+ getDbClient2().afterCommit(() => {
49737
+ runUserMergeJobs2();
49738
+ });
49739
+ return queued;
47483
49740
  });
47484
- mergeUsersRoute.respond(res, 200, { user: mergedUser });
49741
+ mergeUsersRoute.respond(res, 202, { job });
47485
49742
  } catch (err) {
47486
49743
  if (respondOperatorGrantedRefusal(res, err))
47487
49744
  return true;
@@ -47623,11 +49880,11 @@ init_agentmail();
47623
49880
  // src/agentmail/inbound-archive.ts
47624
49881
  init_db4();
47625
49882
  init_secret_scrubber();
47626
- import { createHash as createHash3 } from "node:crypto";
49883
+ import { createHash as createHash5 } from "node:crypto";
47627
49884
  var INBOUND_ARCHIVE_NAMESPACE = "agentmail-inbound";
47628
49885
  var INBOUND_ARCHIVE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
47629
49886
  var text = (value, limit) => typeof value === "string" ? scrubSecrets(value).slice(0, limit) : "";
47630
- var inboundArchiveKey = (inboxId, messageId) => createHash3("sha256").update(JSON.stringify([inboxId, messageId])).digest("hex");
49887
+ var inboundArchiveKey = (inboxId, messageId) => createHash5("sha256").update(JSON.stringify([inboxId, messageId])).digest("hex");
47631
49888
  async function archiveInboundMessage(payload) {
47632
49889
  if (![
47633
49890
  "message.received",
@@ -49148,6 +51405,24 @@ var webhookTriggerRoute = route({
49148
51405
  params: object2({ workflowId: string2() }),
49149
51406
  auth: { apiKey: false },
49150
51407
  responses: {
51408
+ 200: {
51409
+ description: "Delivery skipped after signature verification and before a run was saved. event-not-allowed: the events allowlist missed. filter-not-matched: a header or JSON body field missed. The received value is not echoed for a filter miss.",
51410
+ schema: discriminatedUnion("reason", [
51411
+ object2({
51412
+ skipped: literal2(true),
51413
+ reason: literal2("event-not-allowed"),
51414
+ event: string2().nullable()
51415
+ }),
51416
+ object2({
51417
+ skipped: literal2(true),
51418
+ reason: literal2("filter-not-matched"),
51419
+ match: object2({
51420
+ source: _enum2(["header", "body"]),
51421
+ path: string2()
51422
+ })
51423
+ })
51424
+ ])
51425
+ },
49151
51426
  201: { description: "Webhook processed", schema: object2({ runId: string2() }) },
49152
51427
  401: { description: "Invalid signature" },
49153
51428
  404: { description: "Workflow not found" }
@@ -49219,7 +51494,23 @@ async function handleWorkflows(req, res, pathSegments, queryParams, myAgentId) {
49219
51494
  }
49220
51495
  return true;
49221
51496
  }
49222
- webhookTriggerRoute.respond(res, 201, result);
51497
+ if (result.skipped) {
51498
+ if (result.reason === "event-not-allowed") {
51499
+ webhookTriggerRoute.respond(res, 200, {
51500
+ skipped: true,
51501
+ reason: result.reason,
51502
+ event: result.event
51503
+ });
51504
+ } else {
51505
+ webhookTriggerRoute.respond(res, 200, {
51506
+ skipped: true,
51507
+ reason: result.reason,
51508
+ match: result.match
51509
+ });
51510
+ }
51511
+ } else {
51512
+ webhookTriggerRoute.respond(res, 201, { runId: result.runId });
51513
+ }
49223
51514
  return true;
49224
51515
  }
49225
51516
  if (getWorkflowVersionRoute.match(req.method, pathSegments)) {
@@ -49735,7 +52026,7 @@ init_secret_scrubber();
49735
52026
  init_json_schema_validator();
49736
52027
  init_route_def();
49737
52028
  init_utils2();
49738
- import { timingSafeEqual as timingSafeEqual2 } from "node:crypto";
52029
+ import { timingSafeEqual as timingSafeEqual3 } from "node:crypto";
49739
52030
  var DEFAULT_TIMEOUT_MS = 60000;
49740
52031
  var TIMEOUT_HEADER = "x-swarm-timeout-ms";
49741
52032
  var MAX_BODY_BYTES = 1 * 1024 * 1024;
@@ -49789,7 +52080,7 @@ function timingSafeEqualStr(a, b) {
49789
52080
  const bb = Buffer.from(b);
49790
52081
  if (ab.length !== bb.length)
49791
52082
  return false;
49792
- return timingSafeEqual2(ab, bb);
52083
+ return timingSafeEqual3(ab, bb);
49793
52084
  }
49794
52085
  function resolveTimeoutMs(req) {
49795
52086
  const raw = req.headers[TIMEOUT_HEADER];
@@ -50053,6 +52344,7 @@ var httpServer = createHttpServer(async (req, res) => {
50053
52344
  () => handleAgentsRest(req, res, pathSegments, queryParams, myAgentId),
50054
52345
  () => handleBudgets(req, res, pathSegments, queryParams, myAgentId),
50055
52346
  () => handleContext(req, res, pathSegments, queryParams, myAgentId),
52347
+ () => handleRequestComposition(req, res, pathSegments, queryParams, myAgentId),
50056
52348
  () => handleAssets(req, res, pathSegments, queryParams, myAgentId),
50057
52349
  () => handleTasks(req, res, pathSegments, queryParams, myAgentId),
50058
52350
  () => handleStats(req, res, pathSegments, queryParams, myAgentId),
@@ -50070,6 +52362,7 @@ var httpServer = createHttpServer(async (req, res) => {
50070
52362
  () => handlePoolKeys(req, res, pathSegments, queryParams),
50071
52363
  () => handleConfig(req, res, pathSegments, queryParams),
50072
52364
  () => handleFs(req, res, pathSegments, queryParams, myAgentId),
52365
+ () => handleGitHubToken(req, res, pathSegments, myAgentId),
50073
52366
  () => handleAgentFsProxy(req, res),
50074
52367
  () => handleComb(req, res, pathSegments, queryParams, myAgentId),
50075
52368
  () => handleKv(req, res, pathSegments, queryParams),
@@ -50084,6 +52377,7 @@ var httpServer = createHttpServer(async (req, res) => {
50084
52377
  () => handleMetrics(req, res, pathSegments, queryParams, myAgentId),
50085
52378
  () => handleModelsCatalog(req, res, pathSegments, queryParams),
50086
52379
  () => handleModelProfiles(req, res, pathSegments, queryParams, myAgentId),
52380
+ () => handleModelGroups(req, res, pathSegments, queryParams, myAgentId),
50087
52381
  () => handleRepos(req, res, pathSegments, queryParams, myAgentId),
50088
52382
  () => handleSkills(req, res, pathSegments, queryParams, myAgentId),
50089
52383
  () => handleScriptConnections(req, res, pathSegments, queryParams, myAgentId),
@@ -50107,6 +52401,7 @@ var httpServer = createHttpServer(async (req, res) => {
50107
52401
  () => handleEvents(req, res, pathSegments, queryParams, myAgentId),
50108
52402
  () => handleRuntimePools(req, res, pathSegments, queryParams, myAgentId),
50109
52403
  () => handleExtensions(req, res, pathSegments, queryParams, myAgentId),
52404
+ () => handleToolHooks(req, res, pathSegments, queryParams, myAgentId),
50110
52405
  () => handleChecklist(req, res, pathSegments, queryParams, myAgentId),
50111
52406
  () => handleFavorites(req, res, pathSegments, queryParams, myAgentId),
50112
52407
  () => handleUserRoles(req, res, pathSegments, queryParams),
@@ -50125,7 +52420,7 @@ var httpServer = createHttpServer(async (req, res) => {
50125
52420
  () => handleMcpUser(req, res, transportsUser, sessionUsers, transportActivityUser)
50126
52421
  ];
50127
52422
  try {
50128
- if (await handleCore(req, res, myAgentId, apiKey))
52423
+ if (await handleCore2(req, res, myAgentId, apiKey))
50129
52424
  return;
50130
52425
  myAgentId = req.headers["x-agent-id"];
50131
52426
  for (const handler of handlers) {
@@ -50146,7 +52441,7 @@ var httpServer = createHttpServer(async (req, res) => {
50146
52441
  });
50147
52442
  });
50148
52443
  var detachRealtime = attachRealtimeTransport(httpServer);
50149
- var { attachControllerTransport } = await import("./controllers-connect-ks155r0h.js");
52444
+ var { attachControllerTransport } = await import("./controllers-connect-w3qbpbt1.js");
50150
52445
  var detachControllers = attachControllerTransport(httpServer);
50151
52446
  var stopWorkerNudges = startWorkerNudgeListener();
50152
52447
  var taskAutoTitles = startTaskAutoTitleListener();
@@ -50177,7 +52472,7 @@ async function shutdown() {
50177
52472
  sessionsProcessed: getServerSessionsProcessed()
50178
52473
  });
50179
52474
  if (hasCapability("scheduling")) {
50180
- const { stopScheduler } = await import("./index-cxca2t8y.js");
52475
+ const { stopScheduler } = await import("./index-1f6m47mq.js");
50181
52476
  stopScheduler();
50182
52477
  }
50183
52478
  stopHeartbeat2();
@@ -50189,7 +52484,7 @@ async function shutdown() {
50189
52484
  await stopSlackApp2();
50190
52485
  await stopChatSdk();
50191
52486
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
50192
- const { stopOAuthKeepalive } = await import("./keepalive-sh02349h.js");
52487
+ const { stopOAuthKeepalive } = await import("./keepalive-jmf6pn8c.js");
50193
52488
  await stopOAuthKeepalive();
50194
52489
  }
50195
52490
  stopOAuthPendingGc();
@@ -50248,9 +52543,14 @@ if (!globalState.__runId) {
50248
52543
  }
50249
52544
  startApiGcInterval();
50250
52545
  startEventLoopLagProbe();
52546
+ try {
52547
+ await seedDbRetentionDefaults();
52548
+ } catch (err) {
52549
+ console.warn("[startup] Retention defaults seed failed (non-fatal):", scrubSecrets(err instanceof Error ? err.message : String(err)));
52550
+ }
50251
52551
  var startupConfigsInjected = [];
50252
52552
  try {
50253
- startupConfigsInjected = await loadGlobalConfigsIntoEnv(true);
52553
+ startupConfigsInjected = await loadGlobalConfigsIntoEnv2(true);
50254
52554
  } catch (err) {
50255
52555
  console.error("[startup] Failed to load global swarm configs before listen:", err);
50256
52556
  process.exitCode = 1;
@@ -50274,21 +52574,21 @@ try {
50274
52574
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
50275
52575
  }
50276
52576
  try {
50277
- const { ensurePricingSeeded } = await import("./boot-seeds-ce7rvgq1.js");
52577
+ const { ensurePricingSeeded } = await import("./boot-seeds-kb3dxjex.js");
50278
52578
  ensurePricingSeeded();
50279
- const { startPricingRefreshLoop } = await import("./pricing-refresh-c6b325mk.js");
52579
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-4j8dzvxg.js");
50280
52580
  startPricingRefreshLoop();
50281
52581
  } catch (err) {
50282
52582
  console.error("[startup] Failed to seed pricing rows:", err);
50283
52583
  }
50284
52584
  try {
50285
- const { ensureModelProfilesSeeded } = await import("./boot-seeds-ce7rvgq1.js");
52585
+ const { ensureModelProfilesSeeded } = await import("./boot-seeds-kb3dxjex.js");
50286
52586
  await ensureModelProfilesSeeded();
50287
52587
  } catch (err) {
50288
52588
  console.error("[startup] Failed to seed model profiles:", err);
50289
52589
  }
50290
52590
  try {
50291
- const { ensureRbacSeeded } = await import("./boot-seeds-ce7rvgq1.js");
52591
+ const { ensureRbacSeeded } = await import("./boot-seeds-kb3dxjex.js");
50292
52592
  ensureRbacSeeded();
50293
52593
  } catch (err) {
50294
52594
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -50296,13 +52596,13 @@ try {
50296
52596
  throw err;
50297
52597
  }
50298
52598
  try {
50299
- const { runAllSeeders } = await import("./index-9zkchs9t.js");
52599
+ const { runAllSeeders } = await import("./index-e42j998x.js");
50300
52600
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
50301
52601
  } catch (err) {
50302
52602
  console.error("[startup] Failed to seed built-in entities:", err);
50303
52603
  }
50304
52604
  try {
50305
- const { runImports } = await import("./index-rv89fvzf.js");
52605
+ const { runImports } = await import("./index-akbgsdhh.js");
50306
52606
  await runImports();
50307
52607
  } catch (err) {
50308
52608
  console.error("[startup] File import failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
@@ -50353,7 +52653,7 @@ httpServer.listen(port, async () => {
50353
52653
  startChatSdk().catch((err) => {
50354
52654
  console.error("[chat-sdk] Failed to start, continuing without Chat SDK:", scrubSecrets(err instanceof Error ? err.message : String(err)));
50355
52655
  });
50356
- import("./agent-fs-provision-b5dhdsbd.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
52656
+ import("./agent-fs-provision-v6enh76w.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
50357
52657
  console.warn("[agent-fs] Failed to set the org swarm URL:", scrubSecrets(err instanceof Error ? err.message : String(err)));
50358
52658
  });
50359
52659
  startQueueStallAlarm();
@@ -50361,6 +52661,7 @@ httpServer.listen(port, async () => {
50361
52661
  initGitLab();
50362
52662
  initAzureDevOps();
50363
52663
  initAzureDevOpsOutbound();
52664
+ initMcpEventsDispatcher();
50364
52665
  initBitbucket();
50365
52666
  initAgentMail();
50366
52667
  await initLinear();
@@ -50368,25 +52669,25 @@ httpServer.listen(port, async () => {
50368
52669
  await initWorkflows2();
50369
52670
  await startScriptRunSupervisor(getMcpBaseUrl());
50370
52671
  if (hasCapability("scheduling")) {
50371
- const { startScheduler } = await import("./index-cxca2t8y.js");
50372
- const { getExecutorRegistry } = await import("./index-25pvya7q.js");
52672
+ const { startScheduler } = await import("./index-1f6m47mq.js");
52673
+ const { getExecutorRegistry } = await import("./index-tnkd410q.js");
50373
52674
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
50374
52675
  startScheduler(getExecutorRegistry(), intervalMs, {
50375
52676
  runId: globalState.__runId
50376
52677
  });
50377
52678
  }
50378
52679
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
50379
- const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-2t4859r5.js");
52680
+ const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-1p1mpqda.js");
50380
52681
  startHeartbeat(parseHeartbeatIntervalMs(process.env.HEARTBEAT_INTERVAL_MS));
50381
52682
  }
50382
52683
  startPoolRouting();
50383
52684
  startRuntimeSupervisor();
50384
52685
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
50385
- const { startOAuthKeepalive } = await import("./keepalive-sh02349h.js");
52686
+ const { startOAuthKeepalive } = await import("./keepalive-jmf6pn8c.js");
50386
52687
  startOAuthKeepalive();
50387
52688
  }
50388
52689
  if (!isEnvFlagEnabled("OAUTH_REFRESH_SWEEP_DISABLE", false)) {
50389
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-d9xedk66.js");
52690
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-ywgf8tbr.js");
50390
52691
  startOAuthRefreshSweep();
50391
52692
  }
50392
52693
  startOAuthPendingGc();
@@ -50396,19 +52697,22 @@ httpServer.listen(port, async () => {
50396
52697
  startSavingsRollup(savingsRollupSql);
50397
52698
  startHumanFreeDrain();
50398
52699
  startTaskSearchBackfill();
50399
- import("./embedding-space-qhw4g68n.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
50400
- setDeploymentEnvReader(getDeploymentEnvValue);
52700
+ import("./embedding-space-z6ptw3jk.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
52701
+ setDeploymentEnvReader(getDeploymentEnvValue2);
50401
52702
  return runEmbeddingMaintenance({ backfill: true });
50402
52703
  }).catch((err) => {
50403
52704
  console.error("[embedding-space] startup maintenance failed (non-fatal):", err);
50404
52705
  });
50405
- import("./boot-args-schema-3gwy0f60.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
52706
+ import("./boot-args-schema-d7fme4q1.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
50406
52707
  console.error("[boot-args-schema] startup backfill failed (non-fatal):", err);
50407
52708
  });
50408
- import("./boot-scrub-sweep-7dkdzqxx.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
52709
+ import("./boot-scrub-sweep-52h7yntp.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
50409
52710
  console.error("[boot-scrub-sweep] startup scrub failed (non-fatal):", err);
50410
52711
  });
50411
- import("./session-source-backfill-v8mt0zwn.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
52712
+ import("./user-merge-jobs-mvheb3ed.js").then(({ resumeUserMergeJobs }) => resumeUserMergeJobs()).catch((err) => {
52713
+ console.error("[user-merge] startup resume failed (non-fatal):", err);
52714
+ });
52715
+ import("./session-source-backfill-ax6qxv20.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
50412
52716
  console.error("[session-source-backfill] startup run failed (non-fatal):", err);
50413
52717
  });
50414
52718
  }).on("error", (err) => {