@desplega.ai/agent-swarm 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (378) hide show
  1. package/dist/acp-adapter-weaaxey3.js +16 -0
  2. package/dist/{acp-targets-arrwv4f0.js → acp-targets-5wyy2b9m.js} +9 -9
  3. package/dist/{actions-y0d2n1c2.js → actions-4nxq386s.js} +24 -23
  4. package/dist/{agent-fs-provision-tpj7sktd.js → agent-fs-provision-v6enh76w.js} +4 -4
  5. package/dist/{amp-adapter-vmmnmw8d.js → amp-adapter-ze3x22qn.js} +3 -3
  6. package/dist/{anthropic-messages-zdca3gv1.js → anthropic-messages-88b7s3n9.js} +177 -25
  7. package/dist/{app-wb7w45dq.js → app-kyqt8ehw.js} +7 -6
  8. package/dist/{approval-notifications-7mqr6vbd.js → approval-notifications-a0db0esw.js} +7 -6
  9. package/dist/{assistant-gf60454p.js → assistant-9g5jzq25.js} +26 -25
  10. package/dist/{azure-openai-responses-b3y7fz36.js → azure-openai-responses-jeaas6x0.js} +10 -10
  11. package/dist/{boot-args-schema-qxmd59sr.js → boot-args-schema-d7fme4q1.js} +1 -1
  12. package/dist/{boot-reembed-wb44vc3s.js → boot-reembed-6wpazmpw.js} +1 -1
  13. package/dist/{boot-reembed-5tmeskj2.js → boot-reembed-jrwxeye2.js} +1 -1
  14. package/dist/{boot-scrub-sweep-25bxhnw4.js → boot-scrub-sweep-52h7yntp.js} +2 -2
  15. package/dist/{boot-seeds-nj9za0vk.js → boot-seeds-kb3dxjex.js} +4 -4
  16. package/dist/{boxd-wn235q80.js → boxd-jrrmkv3w.js} +2 -2
  17. package/dist/{claude-adapter-d3krpdyb.js → claude-adapter-0c0y8fqp.js} +8 -8
  18. package/dist/{claude-managed-adapter-t8nfgcgz.js → claude-managed-adapter-w2es07qq.js} +4 -4
  19. package/dist/{claude-managed-setup-7y4pwd81.js → claude-managed-setup-9ssb7ct4.js} +4 -4
  20. package/dist/{claude-sdk-session-d138zy0e.js → claude-sdk-session-p6t0gyse.js} +10941 -10412
  21. package/dist/{cli-p0n7b5rz.js → cli-075ccjh6.js} +344 -130
  22. package/dist/{cli-3caf7pmg.js → cli-0bgj4rh5.js} +3 -3
  23. package/dist/{cli-7r162fxe.js → cli-14xdms9a.js} +23 -17
  24. package/dist/{cli-rqx70rcz.js → cli-17qzb39j.js} +5 -2
  25. package/dist/{cli-y4ccxtz5.js → cli-1h4njv9y.js} +144 -6
  26. package/dist/{cli-6ym4jhzp.js → cli-27fat7st.js} +7 -7
  27. package/dist/{cli-k3q2va86.js → cli-2aacfdcn.js} +5 -5
  28. package/dist/{cli-vq2eg24x.js → cli-2gvdvsxj.js} +3 -3
  29. package/dist/{cli-sb4426be.js → cli-2jtfm8kh.js} +5 -5
  30. package/dist/{cli-6ehs4mta.js → cli-2z2c4k6q.js} +18 -4
  31. package/dist/{cli-6237rnyr.js → cli-3bpr3wks.js} +1 -1
  32. package/dist/{cli-5qhfv9rw.js → cli-453497a0.js} +44 -17
  33. package/dist/{cli-2rnd5j3t.js → cli-4aswccje.js} +2 -2
  34. package/dist/{cli-4ymxrwg5.js → cli-4dyzzkfb.js} +2 -2
  35. package/dist/{cli-p0c3vtch.js → cli-4g323fjh.js} +772 -515
  36. package/dist/{cli-3kd08rej.js → cli-4jjrhy48.js} +1 -1
  37. package/dist/{cli-fcfbct2j.js → cli-4kzp7r0q.js} +5 -5
  38. package/dist/{cli-kxn3747f.js → cli-4se3x6qm.js} +1 -26
  39. package/dist/{cli-zeh2mhkg.js → cli-5ptj757f.js} +1 -1
  40. package/dist/{cli-539h29es.js → cli-6a3j25xd.js} +224 -189
  41. package/dist/{cli-hnamkvnc.js → cli-6c9ve77f.js} +2 -2
  42. package/dist/{cli-3et6fmfe.js → cli-6n7y5ypy.js} +1 -1
  43. package/dist/{cli-8y43jx2r.js → cli-6p8p2e6r.js} +16 -9
  44. package/dist/{cli-zk7v5s89.js → cli-6tvh1fwq.js} +3 -3
  45. package/dist/{cli-p74md7t8.js → cli-7b7rxz22.js} +13 -15
  46. package/dist/{cli-5a6pqy45.js → cli-7e8sxqv5.js} +1 -1
  47. package/dist/{cli-6037prsx.js → cli-892y3vfp.js} +13 -13
  48. package/dist/cli-8mfdbdhe.js +43 -0
  49. package/dist/{cli-s1zqk1aj.js → cli-8zmpwe79.js} +15 -9
  50. package/dist/{cli-zcfpsfzf.js → cli-96234j5w.js} +3 -3
  51. package/dist/{cli-1z4qggfe.js → cli-9fvk9mv8.js} +30 -21
  52. package/dist/{cli-7mv4h3sn.js → cli-9g12h1aq.js} +2 -2
  53. package/dist/{cli-aw83sr40.js → cli-9knhkkgr.js} +3 -3
  54. package/dist/{cli-5mpy301f.js → cli-9t7syepg.js} +1 -1
  55. package/dist/{cli-qj39vrc6.js → cli-9yjhshah.js} +1 -1
  56. package/dist/{cli-6cwr32fe.js → cli-a02habn6.js} +422 -140
  57. package/dist/{cli-7evph51z.js → cli-a49frv85.js} +2 -2
  58. package/dist/{cli-3f8zbtqa.js → cli-a6q6x15h.js} +9 -8
  59. package/dist/{cli-j6te8keb.js → cli-atm0hkes.js} +8 -8
  60. package/dist/{cli-9fjr27ez.js → cli-b82a13ga.js} +13 -13
  61. package/dist/{cli-7zm3b3f5.js → cli-bf0t77nf.js} +1 -1
  62. package/dist/{cli-2xv18ywz.js → cli-bmqp0ser.js} +2 -2
  63. package/dist/{cli-mk7c5ac4.js → cli-bq97k63w.js} +2 -2
  64. package/dist/{cli-vfqvrd82.js → cli-cstggwq7.js} +2 -2
  65. package/dist/{cli-md50mj0r.js → cli-czvvnfr9.js} +3 -3
  66. package/dist/{cli-b6px1k1q.js → cli-dd2k2mcd.js} +1 -1
  67. package/dist/{cli-fq2rr3jb.js → cli-djt6wmrc.js} +6 -6
  68. package/dist/{cli-tsa40663.js → cli-ebqx630g.js} +3 -3
  69. package/dist/{cli-z0m452jr.js → cli-f7dhm7hh.js} +1 -1
  70. package/dist/{cli-mys27d03.js → cli-f8yhybxr.js} +3 -3
  71. package/dist/{cli-5gpqgs8b.js → cli-fwjwkw66.js} +2 -2
  72. package/dist/{cli-gabsjg8x.js → cli-g56fxddf.js} +1 -1
  73. package/dist/{cli-y8p78ekx.js → cli-h2qtafm4.js} +18 -18
  74. package/dist/{cli-psffsanb.js → cli-ha4ek2nb.js} +6 -1
  75. package/dist/{cli-th1dkc2v.js → cli-hnh8erra.js} +2 -2
  76. package/dist/{cli-w16kwbzw.js → cli-htymm48w.js} +1 -1
  77. package/dist/{cli-124ntmf0.js → cli-j2r1apqm.js} +138 -59
  78. package/dist/{cli-43ms35q9.js → cli-k3c13za2.js} +3 -3
  79. package/dist/{cli-54vrpgm0.js → cli-k3facve0.js} +8 -5
  80. package/dist/{cli-v8z0yga9.js → cli-k4r5sfaj.js} +4 -4
  81. package/dist/{cli-91pkxres.js → cli-kbm659dk.js} +2 -2
  82. package/dist/{cli-q5srsxq2.js → cli-m00c47q6.js} +110 -27
  83. package/dist/{cli-3aaeb78m.js → cli-mhrr4d5b.js} +95 -10
  84. package/dist/{cli-xqdz5cqm.js → cli-mz7ycqn8.js} +1 -0
  85. package/dist/{cli-qrta34nb.js → cli-n6ygvrrm.js} +4 -4
  86. package/dist/{cli-k5yewqgd.js → cli-nbakg5xh.js} +3 -3
  87. package/dist/{cli-nstkanmx.js → cli-nc39ym5q.js} +8 -8
  88. package/dist/{cli-01k6wpr9.js → cli-p1a4khta.js} +7 -7
  89. package/dist/{cli-t9ga4qmb.js → cli-p8zqbbt1.js} +40 -33
  90. package/dist/{cli-v46zsvqk.js → cli-ph95yejc.js} +2 -2
  91. package/dist/{cli-k6nejceb.js → cli-q4z9s6zs.js} +2 -2
  92. package/dist/{cli-kbtzfrxj.js → cli-q71g5q39.js} +3 -3
  93. package/dist/{cli-vs9vdpy0.js → cli-qncx2r0s.js} +1 -1
  94. package/dist/{cli-hg42n3hx.js → cli-qrzq3hvg.js} +8 -8
  95. package/dist/{cli-x40a0w9j.js → cli-r813c7rb.js} +1 -1
  96. package/dist/{cli-kpgcm7xy.js → cli-ramn8jae.js} +1 -1
  97. package/dist/{cli-cc93xzes.js → cli-raqw9fw9.js} +28 -17
  98. package/dist/cli-rhsc2zyx.js +68 -0
  99. package/dist/{cli-8st34zhr.js → cli-rpmw4fsv.js} +57 -19
  100. package/dist/{cli-had1p04a.js → cli-rwgwen5v.js} +4 -4
  101. package/dist/{cli-tr27kwyg.js → cli-rytq7dm2.js} +261 -6
  102. package/dist/{cli-s1khw52h.js → cli-s9twe4x0.js} +66 -17
  103. package/dist/{cli-2v2zdm0a.js → cli-t2s7j5cy.js} +2 -2
  104. package/dist/{cli-nv4xsvmk.js → cli-tb4j757d.js} +7 -7
  105. package/dist/{cli-q2d3e1k1.js → cli-thd3005a.js} +1 -1
  106. package/dist/cli-tsfkcd4v.js +30 -0
  107. package/dist/{cli-jrbq4djp.js → cli-v3zcnr8g.js} +1 -1
  108. package/dist/{cli-zfqg6fzn.js → cli-vbppqvte.js} +3 -3
  109. package/dist/{cli-qx4f057j.js → cli-vy3fn0mz.js} +4 -4
  110. package/dist/{cli-7sf9sb0w.js → cli-w5dar1bk.js} +1 -1
  111. package/dist/{cli-w1q68d8x.js → cli-wz4e5am2.js} +9 -9
  112. package/dist/{cli-m9cvf7vs.js → cli-xqbqwpxr.js} +14 -14
  113. package/dist/{cli-2spnz7ye.js → cli-ynph3b70.js} +11137 -8332
  114. package/dist/{cli-43evxwj4.js → cli-yvzxbztc.js} +9 -4
  115. package/dist/{cli-vsw91x06.js → cli-yzxqwcvq.js} +3 -6
  116. package/dist/{cli-wafmk3fn.js → cli-zb1hff00.js} +12 -12
  117. package/dist/{cli-yab6sh8p.js → cli-zcghfsdg.js} +23 -4
  118. package/dist/{cli-wwp1bd3n.js → cli-zhn4r1rz.js} +519 -75
  119. package/dist/{cli-tvgqesec.js → cli-zqq57pgx.js} +4 -4
  120. package/dist/cli.js +28 -27
  121. package/dist/{cloudflare-workers-ai-system-one-4aysy6rh.js → cloudflare-workers-ai-system-one-w3m0fbf8.js} +2 -2
  122. package/dist/{codex-adapter-exfdbj73.js → codex-adapter-ssahg4h4.js} +8 -8
  123. package/dist/{codex-hook-59atdwd8.js → codex-hook-aqtj17yr.js} +1 -1
  124. package/dist/{codex-login-a239g1ah.js → codex-login-9c7aggxe.js} +1 -1
  125. package/dist/{codex-session-runner-xhznc4g3.js → codex-session-runner-xn63q3h7.js} +9 -9
  126. package/dist/{commands-d8g349v4.js → commands-ctey7tr5.js} +3 -3
  127. package/dist/{controller-mwgdmb8y.js → controller-rqhbppg9.js} +4 -4
  128. package/dist/{controllers-connect-5v7qx04j.js → controllers-connect-w3qbpbt1.js} +22 -21
  129. package/dist/{core-sxy4epp2.js → core-df1n049h.js} +19 -18
  130. package/dist/{cursor-adapter-p2q5h35d.js → cursor-adapter-r819hf1a.js} +2 -2
  131. package/dist/{db-wcw0b2j8.js → db-2ah39cyx.js} +2 -2
  132. package/dist/{db-qpganbeb.js → db-p5drc1d1.js} +3 -3
  133. package/dist/{devin-adapter-zp4tqq53.js → devin-adapter-bc6g0x29.js} +1 -1
  134. package/dist/{dispatcher-8d8s49yz.js → dispatcher-x6w14pde.js} +19 -18
  135. package/dist/{docker-09tkkg0n.js → docker-6c4reetq.js} +51 -14
  136. package/dist/{dsh-adapter-me0twn13.js → dsh-adapter-h8qn14n4.js} +2 -2
  137. package/dist/{e2b-sm28k0k3.js → e2b-jg7kyyef.js} +6 -6
  138. package/dist/{e2b-3v1e745x.js → e2b-z4ec0qve.js} +3 -3
  139. package/dist/{easter-egg-3d-wv7w5ty6.js → easter-egg-3d-1y6r9gxy.js} +1 -1
  140. package/dist/{embedding-space-e48xchqa.js → embedding-space-z6ptw3jk.js} +6 -6
  141. package/dist/{embeddings-tgq2afbq.js → embeddings-0sxb1d2h.js} +1 -1
  142. package/dist/{event-bus-xr83x566.js → event-bus-swr88jg5.js} +1 -1
  143. package/dist/{execute-8rhwrk7f.js → execute-6m1ex8ce.js} +8 -4
  144. package/dist/{external-channel-8bt3j2pm.js → external-channel-ezer7pk0.js} +2 -2
  145. package/dist/fx-adapter-zwmps9re.js +19 -0
  146. package/dist/{google-generative-ai-bh0djqjp.js → google-generative-ai-sw77egmr.js} +9 -9
  147. package/dist/{google-vertex-prjbw8dj.js → google-vertex-rrw93g8h.js} +9 -9
  148. package/dist/grok-adapter-q0avf919.js +19 -0
  149. package/dist/handlers-g5jq0e4q.js +36 -0
  150. package/dist/{heartbeat-x0056ra5.js → heartbeat-6c4fr49t.js} +22 -21
  151. package/dist/{hook-mrd2ayxv.js → hook-02rt5tvq.js} +8 -8
  152. package/dist/{hook-a7vmn2st.js → hook-t1c5avbv.js} +5 -5
  153. package/dist/{http-ym9c5svp.js → http-qa3h32a1.js} +2049 -148
  154. package/dist/index-1f6m47mq.js +37 -0
  155. package/dist/index-1p1mpqda.js +36 -0
  156. package/dist/{index-p46tvwtx.js → index-akbgsdhh.js} +25 -24
  157. package/dist/{index-ny60jcat.js → index-e42j998x.js} +16 -13
  158. package/dist/{index-b5wgnm78.js → index-kdmkfjt7.js} +4 -4
  159. package/dist/{index-01ns1pkw.js → index-kqv9ebfj.js} +1 -1
  160. package/dist/{index-9myfj74s.js → index-kzdqn3dd.js} +3 -3
  161. package/dist/{index-4a0670yh.js → index-p2f5xg64.js} +6 -6
  162. package/dist/{index-x6azjwm8.js → index-qpjk2hxk.js} +1 -1
  163. package/dist/index-tnkd410q.js +41 -0
  164. package/dist/{k8s-m56sw868.js → k8s-7jrh5va2.js} +73 -14
  165. package/dist/{keepalive-7yxg8z4c.js → keepalive-jmf6pn8c.js} +4 -4
  166. package/dist/lead-m5e7xt93.js +75 -0
  167. package/dist/{llama-cpp-classify-nfgswa1m.js → llama-cpp-classify-yvb8vh7w.js} +2 -2
  168. package/dist/{maintenance-6tefxmk1.js → maintenance-g7v15tj1.js} +1 -1
  169. package/dist/{mistral-conversations-tm2vd4gc.js → mistral-conversations-w4bncwbt.js} +7 -7
  170. package/dist/{node-7qsx5kvm.js → node-z67yjre7.js} +19 -13
  171. package/dist/{oauth-refresh-sweep-70cavc3a.js → oauth-refresh-sweep-ywgf8tbr.js} +3 -3
  172. package/dist/{onboard-fja65z08.js → onboard-m3fedypq.js} +3 -3
  173. package/dist/{openai-codex-responses-sxjv60xx.js → openai-codex-responses-70g39cgz.js} +20 -14
  174. package/dist/{openai-completions-0c7qnhsx.js → openai-completions-cv3hp4h5.js} +18 -11
  175. package/dist/{openai-decisions-ytp6w6xh.js → openai-decisions-fyq1p9f9.js} +2 -2
  176. package/dist/{openai-responses-a7h29chp.js → openai-responses-trsvnks6.js} +13 -11
  177. package/dist/{opencode-adapter-hakkm7yh.js → opencode-adapter-19ktcbb9.js} +7 -7
  178. package/dist/{openrouter-images-xr9gme9x.js → openrouter-images-0jj12a2q.js} +6 -6
  179. package/dist/{otel-impl-7zhnt6gj.js → otel-impl-3ehm1hgc.js} +2 -2
  180. package/dist/{pending-h01yzpx4.js → pending-fwj2fatd.js} +20 -19
  181. package/dist/{pi-messages-2j0fpqwq.js → pi-messages-zk3g4esn.js} +1 -1
  182. package/dist/{pi-mono-adapter-f52hz743.js → pi-mono-adapter-xdeesvc4.js} +18 -17
  183. package/dist/{pricing-refresh-fzxvk2zf.js → pricing-refresh-4j8dzvxg.js} +2 -2
  184. package/dist/{rbac-roles-9v6vhgbs.js → rbac-roles-8msjr07m.js} +3 -3
  185. package/dist/{rbac-roles-hfgh8sba.js → rbac-roles-n7t2acv8.js} +2 -2
  186. package/dist/{render-v2-1rgspxzf.js → render-v2-j7qggj8h.js} +7 -6
  187. package/dist/{resume-tqy61x24.js → resume-hj1mn65y.js} +9 -8
  188. package/dist/{runtime-exkxyx5f.js → runtime-z31mdsgv.js} +2 -2
  189. package/dist/{session-access-3act7vt4.js → session-access-w38fh09a.js} +4 -4
  190. package/dist/{session-source-backfill-82qe7fqq.js → session-source-backfill-ax6qxv20.js} +3 -3
  191. package/dist/{setup-ry1vfdef.js → setup-dsqmpfcr.js} +1 -1
  192. package/dist/thread-buffer-nf55vwx3.js +39 -0
  193. package/dist/tree-visibility-6vqmnr71.js +24 -0
  194. package/dist/{typesafe-system-one-vcfj2ak8.js → typesafe-system-one-qkvkgrcz.js} +2 -2
  195. package/dist/{user-merge-jobs-bx6bf7db.js → user-merge-jobs-mvheb3ed.js} +3 -3
  196. package/dist/{virtual-modules-s0rjzcqq.js → virtual-modules-w2qk2wew.js} +32 -10
  197. package/dist/{work-objects-z2e5tv03.js → work-objects-4ahy5es5.js} +22 -21
  198. package/dist/worker-ews1nyhw.js +75 -0
  199. package/dist/{worker-follow-up-y3xeg89w.js → worker-follow-up-1gs4aw7y.js} +19 -18
  200. package/dist/{x-wg164ss9.js → x-3wr8c5sh.js} +2 -2
  201. package/openapi.json +995 -49
  202. package/package.json +9 -8
  203. package/src/be/db/request-composition.ts +190 -0
  204. package/src/be/db/runtime.ts +15 -0
  205. package/src/be/db/slack-trees.ts +220 -10
  206. package/src/be/db/tasks/human-free.ts +3 -2
  207. package/src/be/db/workflow-run-retention.ts +101 -0
  208. package/src/be/db-client.ts +23 -1
  209. package/src/be/db-retention-defaults.ts +46 -0
  210. package/src/be/db-retention.ts +55 -6
  211. package/src/be/mcp-events/catalog.ts +108 -0
  212. package/src/be/mcp-events/dispatcher.ts +202 -0
  213. package/src/be/mcp-events/protocol.ts +296 -0
  214. package/src/be/mcp-events/store.ts +231 -0
  215. package/src/be/mcp-events/webhook.ts +226 -0
  216. package/src/be/memory/providers/sqlite-store.ts +110 -24
  217. package/src/be/memory/review-recall-filter.ts +22 -0
  218. package/src/be/memory/search-candidates.ts +5 -7
  219. package/src/be/memory/types.ts +5 -0
  220. package/src/be/migrations/322_runtime_pool_workspace.sql +8 -0
  221. package/src/be/migrations/323_slack_task_tree_visibility.sql +9 -0
  222. package/src/be/migrations/326_slack_reconcile_pages.sql +13 -0
  223. package/src/be/migrations/327_mcp_event_subscriptions.sql +57 -0
  224. package/src/be/migrations/329_workflow_run_retention.sql +9 -0
  225. package/src/be/migrations/330_request_composition.sql +22 -0
  226. package/src/be/model-profile-check.ts +1 -1
  227. package/src/be/multi-runtime.ts +32 -4
  228. package/src/be/runtime-pools/controllers.ts +18 -3
  229. package/src/be/runtime-pools/db.ts +15 -4
  230. package/src/be/runtime-pools/supervisor.ts +42 -2
  231. package/src/be/swarm-config-guard.ts +10 -2
  232. package/src/commands/context-preamble.ts +11 -4
  233. package/src/commands/credential-outcome-report.ts +33 -9
  234. package/src/commands/e2b-stack-wizard.tsx +12 -6
  235. package/src/commands/runner.ts +116 -12
  236. package/src/extensions/catalog.generated.json +1 -1
  237. package/src/github/app.ts +59 -14
  238. package/src/http/all-routes.ts +2 -0
  239. package/src/http/config.ts +2 -1
  240. package/src/http/core.ts +2 -0
  241. package/src/http/github-token.ts +66 -0
  242. package/src/http/index.ts +21 -0
  243. package/src/http/mcp-user.ts +11 -8
  244. package/src/http/mcp.ts +58 -42
  245. package/src/http/prompt-templates.ts +1 -0
  246. package/src/http/request-composition.ts +310 -0
  247. package/src/http/tasks.ts +6 -1
  248. package/src/http/tool-schema-estimate.ts +95 -0
  249. package/src/http/workflows.ts +29 -11
  250. package/src/integrations/chat-sdk/inbound.ts +2 -2
  251. package/src/prompts/base-prompt.ts +133 -7
  252. package/src/prompts/resolver.ts +41 -2
  253. package/src/providers/amp-adapter.ts +1 -1
  254. package/src/providers/opencode-adapter.ts +72 -1
  255. package/src/providers/opencode-swarm-plugin.ts +22 -3
  256. package/src/providers/pi-mono-adapter.ts +1 -0
  257. package/src/providers/pi-mono-extension.ts +71 -0
  258. package/src/providers/pricing-sources.md +4 -0
  259. package/src/providers/request-composition-hook.ts +312 -0
  260. package/src/providers/types.ts +5 -0
  261. package/src/runtime-providers/controller-protocol.ts +7 -0
  262. package/src/runtime-providers/docker.ts +80 -12
  263. package/src/runtime-providers/k8s.ts +111 -6
  264. package/src/runtime-providers/types.ts +17 -0
  265. package/src/scheduler/scheduler.ts +1 -1
  266. package/src/server-user.ts +16 -1
  267. package/src/slack/ack.ts +10 -5
  268. package/src/slack/actions.ts +3 -3
  269. package/src/slack/app.ts +2 -0
  270. package/src/slack/assistant.ts +4 -4
  271. package/src/slack/blocks.ts +3 -3
  272. package/src/slack/handlers.ts +3 -3
  273. package/src/slack/reaction-shortcode.ts +23 -2
  274. package/src/slack/render-v2.ts +297 -200
  275. package/src/slack/responses.ts +7 -5
  276. package/src/slack/thread-buffer.ts +3 -3
  277. package/src/slack/tree-visibility.ts +64 -0
  278. package/src/tasks/worker-follow-up.ts +127 -17
  279. package/src/tests/azure-devops-outbound.test.ts +47 -14
  280. package/src/tests/base-prompt.test.ts +149 -1
  281. package/src/tests/check-playwright-version.test.ts +33 -0
  282. package/src/tests/context-preamble-budget.test.ts +65 -0
  283. package/src/tests/credential-outcome-report.test.ts +81 -1
  284. package/src/tests/db-client.test.ts +22 -0
  285. package/src/tests/db-retention-defaults.test.ts +244 -0
  286. package/src/tests/db-retention.test.ts +2 -1
  287. package/src/tests/db-runtime.test.ts +2 -1
  288. package/src/tests/deploy-release-dispatch.test.ts +332 -0
  289. package/src/tests/e2b-stack-wizard.test.tsx +156 -0
  290. package/src/tests/entrypoint-chown-no-follow.test.ts +69 -0
  291. package/src/tests/entrypoint-repo-clone-target.test.ts +112 -0
  292. package/src/tests/env-flag.test.ts +4 -2
  293. package/src/tests/event-loop-lag.test.ts +12 -18
  294. package/src/tests/extensions-example-slack-reply-gate.test.ts +15 -0
  295. package/src/tests/fixtures/base-prompt-baseline-cases.ts +78 -0
  296. package/src/tests/fixtures/base-prompt-baseline.json +18 -0
  297. package/src/tests/github-app-worker-auth-helper.test.ts +325 -0
  298. package/src/tests/github-installation-token-route.test.ts +199 -0
  299. package/src/tests/mcp-user-events.test.ts +708 -0
  300. package/src/tests/memory-key-paths.test.ts +4 -1
  301. package/src/tests/memory-search-stall.test.ts +421 -0
  302. package/src/tests/migration-322-runtime-pool-workspace.test.ts +116 -0
  303. package/src/tests/migration-329-workflow-run-retention.test.ts +32 -0
  304. package/src/tests/model-profile-fallbacks.test.ts +236 -2
  305. package/src/tests/opencode-adapter.test.ts +86 -0
  306. package/src/tests/pi-mono-extension.test.ts +168 -0
  307. package/src/tests/preload-env.test.ts +61 -1
  308. package/src/tests/preload.ts +22 -0
  309. package/src/tests/prompt-template-resolver.test.ts +85 -0
  310. package/src/tests/reload-config.test.ts +45 -0
  311. package/src/tests/request-composition.test.ts +447 -0
  312. package/src/tests/runner-max-concurrent.test.ts +86 -0
  313. package/src/tests/runtime-pools-db.test.ts +80 -0
  314. package/src/tests/runtime-provider-registration.test.ts +8 -0
  315. package/src/tests/runtime-providers-docker.test.ts +192 -1
  316. package/src/tests/runtime-providers-k8s.test.ts +127 -0
  317. package/src/tests/runtime-remote-controller.test.ts +64 -1
  318. package/src/tests/runtime-supervisor.test.ts +101 -0
  319. package/src/tests/script-connections.test.ts +8 -0
  320. package/src/tests/slack-blocks.test.ts +18 -0
  321. package/src/tests/slack-empty-icon-config.test.ts +113 -0
  322. package/src/tests/slack-reaction-config.test.ts +38 -2
  323. package/src/tests/slack-render-v2-query-plans.test.ts +100 -1
  324. package/src/tests/slack-render-v2-reconcile.test.ts +75 -4
  325. package/src/tests/slack-render-v2.test.ts +683 -11
  326. package/src/tests/swarm-config-reserved-keys.test.ts +1 -0
  327. package/src/tests/task-session-prompts.test.ts +37 -0
  328. package/src/tests/user-delete-perf.test.ts +36 -9
  329. package/src/tests/webhook-filter.test.ts +327 -0
  330. package/src/tests/workflow-async-v2.test.ts +19 -16
  331. package/src/tests/workflow-definition-telemetry.test.ts +15 -5
  332. package/src/tests/workflow-e2e.test.ts +1 -9
  333. package/src/tests/workflow-finalization-races.test.ts +553 -0
  334. package/src/tests/workflow-foreach.test.ts +2 -0
  335. package/src/tests/workflow-hitl-routing.test.ts +26 -20
  336. package/src/tests/workflow-http-v2.test.ts +105 -2
  337. package/src/tests/workflow-idempotency.test.ts +41 -0
  338. package/src/tests/workflow-mcp-webhook-filter.test.ts +214 -0
  339. package/src/tests/workflow-parallel-park.test.ts +297 -0
  340. package/src/tests/workflow-retry-v2.test.ts +57 -21
  341. package/src/tests/workflow-retry-validation.test.ts +13 -13
  342. package/src/tests/workflow-runs-retention.test.ts +533 -0
  343. package/src/tests/workflow-script-principal.test.ts +7 -2
  344. package/src/tests/workflow-tla-races.test.ts +7 -2
  345. package/src/tests/workflow-triggers-v2.test.ts +201 -0
  346. package/src/tests/workflow-wait-builtin-events.test.ts +3 -1
  347. package/src/tests/workflow-wait-event.test.ts +28 -2
  348. package/src/tests/workflow-wait-poller.test.ts +94 -0
  349. package/src/tests/workflow-wait-time.test.ts +7 -3
  350. package/src/tests/workflow-wait.test.ts +26 -0
  351. package/src/tests/workflow-wait.ts +44 -0
  352. package/src/tools/workflows/create-workflow.ts +7 -3
  353. package/src/tools/workflows/update-workflow.ts +7 -3
  354. package/src/types.ts +200 -2
  355. package/src/utils/credentials.ts +7 -0
  356. package/src/workflows/checkpoint.ts +18 -0
  357. package/src/workflows/engine.ts +38 -10
  358. package/src/workflows/foreach-driver.ts +42 -4
  359. package/src/workflows/recovery.ts +6 -1
  360. package/src/workflows/resume.ts +11 -3
  361. package/src/workflows/retry-poller.ts +17 -4
  362. package/src/workflows/successor-routing.ts +108 -0
  363. package/src/workflows/task-step-routing.ts +5 -2
  364. package/src/workflows/triggers.ts +21 -36
  365. package/src/workflows/wait-poller.ts +6 -2
  366. package/src/workflows/webhook-filter.ts +203 -0
  367. package/templates/extensions/slack-reply-gate/hooks.ts +8 -4
  368. package/templates/skills/swarm-docs/content.md +2 -0
  369. package/dist/acp-adapter-bht22g3k.js +0 -16
  370. package/dist/fx-adapter-adtdb3jb.js +0 -19
  371. package/dist/grok-adapter-accnn9km.js +0 -19
  372. package/dist/handlers-1x77561e.js +0 -35
  373. package/dist/index-48qzcqzj.js +0 -35
  374. package/dist/index-rkvaambe.js +0 -36
  375. package/dist/index-xj1mq27m.js +0 -40
  376. package/dist/lead-enzn86bz.js +0 -74
  377. package/dist/thread-buffer-3x93yexa.js +0 -38
  378. package/dist/worker-zfcv2wbf.js +0 -74
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  bedrockProviderModule
3
- } from "./cli-8y43jx2r.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,
@@ -298,6 +303,7 @@ import {
298
303
  triageSessionList,
299
304
  init_session_tree,
300
305
  setHumanFreeQueueListener,
306
+ reclassifyTaskHumanFree,
301
307
  drainHumanFreeReclassifyQueue,
302
308
  init_human_free,
303
309
  channelTopic,
@@ -332,6 +338,8 @@ import {
332
338
  assertWorkflowIdempotencyKeyUnused,
333
339
  recordAcceptedWorkflowOperation,
334
340
  init_workflow_idempotency,
341
+ deleteOrphanedRunDefinitions,
342
+ init_workflow_run_definitions,
335
343
  recordKeySeatMismatch2,
336
344
  recordKeyValidation2,
337
345
  retirePoolKeyStatus,
@@ -542,7 +550,7 @@ import {
542
550
  countScriptRunJournalSteps2,
543
551
  countScriptRunJournalAgentTaskSteps2,
544
552
  init_db4
545
- } from "./cli-wwp1bd3n.js";
553
+ } from "./cli-zhn4r1rz.js";
546
554
  import {
547
555
  PRIMARY_ROLE_NAMES2,
548
556
  OperatorGrantedTargetError2,
@@ -556,7 +564,7 @@ import {
556
564
  assertNotLastAdmin2,
557
565
  setUserRoles2,
558
566
  init_rbac_roles
559
- } from "./cli-vfqvrd82.js";
567
+ } from "./cli-cstggwq7.js";
560
568
  import {
561
569
  MAX_MODEL_GROUP_MEMBERS,
562
570
  listModelGroups,
@@ -566,16 +574,17 @@ import {
566
574
  modelGroupReferences,
567
575
  deleteModelGroup,
568
576
  init_model_groups
569
- } from "./cli-mys27d03.js";
577
+ } from "./cli-f8yhybxr.js";
570
578
  import {
571
579
  requestModelCatalogRefresh2,
572
580
  init_pricing_refresh
573
- } from "./cli-th1dkc2v.js";
581
+ } from "./cli-hnh8erra.js";
574
582
  import {
575
583
  workflowEventBus2,
576
584
  init_event_bus
577
- } from "./cli-q2d3e1k1.js";
578
- import"./cli-mk7c5ac4.js";
585
+ } from "./cli-thd3005a.js";
586
+ import"./cli-bq97k63w.js";
587
+ import"./cli-rhsc2zyx.js";
579
588
  import"./cli-9w8712tq.js";
580
589
  import"./cli-47hz21se.js";
581
590
  import {
@@ -612,8 +621,8 @@ import {
612
621
  getSlackHttpReceiver2,
613
622
  startSlackApp2,
614
623
  stopSlackApp2,
615
- init_app3
616
- } from "./cli-539h29es.js";
624
+ init_app4
625
+ } from "./cli-6a3j25xd.js";
617
626
  import {
618
627
  AGENT_MAX_TASKS_CONFIG_KEY,
619
628
  reconcileAgentMaxTasksPolicy,
@@ -641,21 +650,56 @@ import {
641
650
  dispatchApprovalNotifications2,
642
651
  createApprovalFollowUpTask2,
643
652
  init_approval_notifications
644
- } from "./cli-cc93xzes.js";
653
+ } from "./cli-raqw9fw9.js";
645
654
  import {
646
655
  retryFailedRun2,
647
656
  cancelWorkflowRun2,
648
657
  init_resume
649
- } from "./cli-7r162fxe.js";
658
+ } from "./cli-14xdms9a.js";
650
659
  import {
660
+ safeParse,
661
+ getObjectShape,
662
+ getLiteralValue,
663
+ init_zod_compat,
664
+ LATEST_PROTOCOL_VERSION,
651
665
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
652
666
  SUPPORTED_PROTOCOL_VERSIONS,
653
667
  isJSONRPCRequest,
654
668
  isJSONRPCResultResponse,
669
+ ErrorCode,
655
670
  isJSONRPCErrorResponse,
656
671
  JSONRPCMessageSchema,
672
+ EmptyResultSchema,
657
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,
658
694
  init_types,
695
+ Protocol,
696
+ mergeCapabilities,
697
+ init_protocol,
698
+ AjvJsonSchemaValidator,
699
+ init_ajv_provider,
700
+ assertToolsCallTaskCapability,
701
+ assertClientRequestTaskCapability,
702
+ init_helpers,
659
703
  McpServer,
660
704
  init_mcp,
661
705
  referencedBundlePaths,
@@ -797,6 +841,8 @@ import {
797
841
  isGitHubEnabled,
798
842
  initGitHub,
799
843
  verifyWebhookSignature,
844
+ getWorkerInstallationToken,
845
+ init_app,
800
846
  handlePullRequest,
801
847
  handleIssue,
802
848
  handleComment,
@@ -847,7 +893,7 @@ import {
847
893
  init_webhook_lifecycle,
848
894
  isJiraEnabled,
849
895
  initJira,
850
- init_app,
896
+ init_app2,
851
897
  handleJiraWebhook,
852
898
  init_webhook,
853
899
  init_jira,
@@ -858,7 +904,7 @@ import {
858
904
  init_sync,
859
905
  isLinearEnabled,
860
906
  initLinear,
861
- init_app2,
907
+ init_app3,
862
908
  init_linear,
863
909
  init_slack,
864
910
  verifyPageSession,
@@ -1083,7 +1129,7 @@ import {
1083
1129
  getEnabledCapabilities,
1084
1130
  createServer,
1085
1131
  init_server
1086
- } from "./cli-p0n7b5rz.js";
1132
+ } from "./cli-075ccjh6.js";
1087
1133
  import {
1088
1134
  FilesError,
1089
1135
  normalizeFilesError,
@@ -1115,7 +1161,7 @@ import {
1115
1161
  resolvePoolDelivery2,
1116
1162
  createPoolAgent2,
1117
1163
  init_db2
1118
- } from "./cli-s1zqk1aj.js";
1164
+ } from "./cli-8zmpwe79.js";
1119
1165
  import {
1120
1166
  duplicateGuardedQueryKey,
1121
1167
  warnIfCorsAllowsAnyOrigin,
@@ -1172,7 +1218,7 @@ import {
1172
1218
  describeRequestRoute,
1173
1219
  route,
1174
1220
  init_route_def
1175
- } from "./cli-nstkanmx.js";
1221
+ } from "./cli-nc39ym5q.js";
1176
1222
  import {
1177
1223
  startPoolRouting,
1178
1224
  stopPoolRouting,
@@ -1185,28 +1231,28 @@ import {
1185
1231
  checkHeartbeatChecklist2,
1186
1232
  runHeartbeatSweep2,
1187
1233
  stopHeartbeat2
1188
- } from "./cli-9fjr27ez.js";
1189
- import"./cli-43evxwj4.js";
1234
+ } from "./cli-b82a13ga.js";
1235
+ import"./cli-yvzxbztc.js";
1190
1236
  import {
1191
1237
  runtimeSupervisorStatus,
1192
1238
  startRuntimeSupervisor,
1193
1239
  stopRuntimeSupervisor
1194
- } from "./cli-8st34zhr.js";
1240
+ } from "./cli-rpmw4fsv.js";
1195
1241
  import {
1196
1242
  TASK_TITLE_TIMEOUT_MS,
1197
1243
  generateTaskTitle
1198
- } from "./cli-fcfbct2j.js";
1244
+ } from "./cli-4kzp7r0q.js";
1199
1245
  import"./cli-ns59dc6r.js";
1200
1246
  import {
1201
1247
  ACP_TARGET_IDS
1202
- } from "./cli-x40a0w9j.js";
1248
+ } from "./cli-r813c7rb.js";
1203
1249
  import {
1204
1250
  reasoningCapability,
1205
1251
  supportedReasoningLevels
1206
- } from "./cli-5gpqgs8b.js";
1252
+ } from "./cli-fwjwkw66.js";
1207
1253
  import {
1208
1254
  MAX_RATE_LIMIT_RESET_MS
1209
- } from "./cli-kpgcm7xy.js";
1255
+ } from "./cli-ramn8jae.js";
1210
1256
  import {
1211
1257
  isLeadChannelMonitoringEnabled,
1212
1258
  ORG_IDENTITY_KEYS,
@@ -1216,7 +1262,7 @@ import {
1216
1262
  isUnknownModelError,
1217
1263
  checkProviderPoolKey,
1218
1264
  writeSkillsToFilesystem
1219
- } from "./cli-sb4426be.js";
1265
+ } from "./cli-2jtfm8kh.js";
1220
1266
  import {
1221
1267
  AgentFsRequestError2,
1222
1268
  resolveAgentFsSharedContext2,
@@ -1226,11 +1272,11 @@ import {
1226
1272
  roleRank2,
1227
1273
  agentFsRequest2,
1228
1274
  resolveApiUrl2
1229
- } from "./cli-vq2eg24x.js";
1275
+ } from "./cli-2gvdvsxj.js";
1230
1276
  import {
1231
1277
  Anthropic
1232
- } from "./cli-t9ga4qmb.js";
1233
- import"./cli-had1p04a.js";
1278
+ } from "./cli-p8zqbbt1.js";
1279
+ import"./cli-rwgwen5v.js";
1234
1280
  import {
1235
1281
  createUserMergeJob2,
1236
1282
  getUserMergeJob2,
@@ -1239,7 +1285,7 @@ import {
1239
1285
  findFailedUserMergeJob2,
1240
1286
  requeueUserMergeJob2,
1241
1287
  runUserMergeJobs2
1242
- } from "./cli-kbtzfrxj.js";
1288
+ } from "./cli-q71g5q39.js";
1243
1289
  import {
1244
1290
  isCodexOAuthConfigKey
1245
1291
  } from "./cli-j4bwnpkm.js";
@@ -1250,13 +1296,13 @@ import {
1250
1296
  import {
1251
1297
  runTaskUiAction,
1252
1298
  init_actions
1253
- } from "./cli-aw83sr40.js";
1299
+ } from "./cli-9knhkkgr.js";
1254
1300
  import {
1255
1301
  RATING_MODEL_MAX_LENGTH,
1256
1302
  REFERENCES_SOURCE_MAX_LENGTH,
1257
1303
  sanitizeReferencesSource,
1258
1304
  init_types2
1259
- } from "./cli-2xv18ywz.js";
1305
+ } from "./cli-bmqp0ser.js";
1260
1306
  import {
1261
1307
  require_dist,
1262
1308
  getMcpOAuthToken,
@@ -1345,7 +1391,7 @@ import {
1345
1391
  init_typecheck,
1346
1392
  parseSkillContent,
1347
1393
  init_skill_parser
1348
- } from "./cli-w1q68d8x.js";
1394
+ } from "./cli-wz4e5am2.js";
1349
1395
  import {
1350
1396
  signalProcessGroup,
1351
1397
  detachedProcessGroup,
@@ -1362,8 +1408,8 @@ import {
1362
1408
  forceRefreshAuthorizationOrThrow,
1363
1409
  forceRefreshTokenOrThrow,
1364
1410
  init_ensure_token
1365
- } from "./cli-2rnd5j3t.js";
1366
- import"./cli-jrbq4djp.js";
1411
+ } from "./cli-4aswccje.js";
1412
+ import"./cli-v3zcnr8g.js";
1367
1413
  import {
1368
1414
  automationIntegrationFixUrl,
1369
1415
  preflightAutomation,
@@ -1382,7 +1428,7 @@ import {
1382
1428
  definitionNodeIds,
1383
1429
  validateDefinition,
1384
1430
  init_definition2
1385
- } from "./cli-q5srsxq2.js";
1431
+ } from "./cli-m00c47q6.js";
1386
1432
  import {
1387
1433
  _fetchHolder,
1388
1434
  CLIENT_ID,
@@ -1398,7 +1444,7 @@ import {
1398
1444
  loadAllCodexOAuthSlots,
1399
1445
  getValidCodexOAuth,
1400
1446
  init_storage
1401
- } from "./cli-7sf9sb0w.js";
1447
+ } from "./cli-w5dar1bk.js";
1402
1448
  import {
1403
1449
  isMultiRuntimeEnabled,
1404
1450
  init_multi_runtime2
@@ -1410,7 +1456,7 @@ import {
1410
1456
  import {
1411
1457
  createRuntimeProvider,
1412
1458
  init_runtime_providers
1413
- } from "./cli-tvgqesec.js";
1459
+ } from "./cli-zqq57pgx.js";
1414
1460
  import {
1415
1461
  require_content_type
1416
1462
  } from "./cli-1jx0srjt.js";
@@ -1432,12 +1478,12 @@ import {
1432
1478
  revokeMcpToken,
1433
1479
  computeExpiresAt,
1434
1480
  init_mcp_wrapper
1435
- } from "./cli-2v2zdm0a.js";
1481
+ } from "./cli-t2s7j5cy.js";
1436
1482
  import"./cli-v41kn3cd.js";
1437
1483
  import {
1438
1484
  setBedrockProviderModule,
1439
1485
  init_bedrock_converse_stream_lazy
1440
- } from "./cli-54vrpgm0.js";
1486
+ } from "./cli-k3facve0.js";
1441
1487
  import {
1442
1488
  import_websocket,
1443
1489
  import_websocket_server,
@@ -1458,7 +1504,8 @@ import {
1458
1504
  mintToken,
1459
1505
  revokeToken,
1460
1506
  revokeAllUserCredentials,
1461
- resolveUserByToken,
1507
+ resolveUserToken,
1508
+ isLiveUserToken,
1462
1509
  InvalidRuntimeTokenError,
1463
1510
  mintSessionToken,
1464
1511
  mintRuntimeToken,
@@ -1470,11 +1517,7 @@ import {
1470
1517
  revokeAgentTokens,
1471
1518
  fingerprintApiKey,
1472
1519
  init_users
1473
- } from "./cli-vsw91x06.js";
1474
- import {
1475
- resolveGitHubHost,
1476
- init_github_host
1477
- } from "./cli-9ttx00s3.js";
1520
+ } from "./cli-yzxqwcvq.js";
1478
1521
  import {
1479
1522
  MAX_PROVIDER_QUOTA_ENTRIES,
1480
1523
  ProviderQuotaCapacityError,
@@ -1483,7 +1526,15 @@ import {
1483
1526
  providerAccountTelemetrySchema,
1484
1527
  rateLimitReplacementSchema,
1485
1528
  init_provider_account_telemetry
1486
- } 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";
1487
1538
  import {
1488
1539
  CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1489
1540
  CODEX_AUTH_WATCH_NAMESPACE,
@@ -1647,6 +1698,9 @@ import {
1647
1698
  ContextSnapshotEventTypeSchema,
1648
1699
  ContextFormulaSchema,
1649
1700
  ContextSnapshotSchema,
1701
+ RequestCompositionPartInputSchema,
1702
+ RequestCompositionToolLoadingSchema,
1703
+ RequestCompositionSchema,
1650
1704
  BudgetScopeSchema,
1651
1705
  BudgetSchema,
1652
1706
  PricingProviderSchema,
@@ -1659,12 +1713,12 @@ import {
1659
1713
  KvKeySchema,
1660
1714
  KvEntrySchema,
1661
1715
  init_types5
1662
- } from "./cli-y4ccxtz5.js";
1716
+ } from "./cli-1h4njv9y.js";
1663
1717
  import {
1664
1718
  IDENTITY_FIELD_BUDGETS,
1665
1719
  IdentityFieldBudgetError,
1666
1720
  init_identity_field_budget
1667
- } from "./cli-3aaeb78m.js";
1721
+ } from "./cli-mhrr4d5b.js";
1668
1722
  import {
1669
1723
  isSteeringEnabled2,
1670
1724
  init_steering_enabled
@@ -1692,7 +1746,7 @@ import {
1692
1746
  splitCredentialPool,
1693
1747
  selectCredential,
1694
1748
  init_credentials2
1695
- } from "./cli-psffsanb.js";
1749
+ } from "./cli-ha4ek2nb.js";
1696
1750
  import {
1697
1751
  getOpenRouterAttributionHeaders,
1698
1752
  init_openrouter_base_url
@@ -1706,10 +1760,10 @@ import {
1706
1760
  resolveTemplate,
1707
1761
  init_resolver,
1708
1762
  init_session_templates
1709
- } from "./cli-6ehs4mta.js";
1763
+ } from "./cli-2z2c4k6q.js";
1710
1764
  import {
1711
1765
  init_zod
1712
- } from "./cli-zcfpsfzf.js";
1766
+ } from "./cli-96234j5w.js";
1713
1767
  import {
1714
1768
  NEVER,
1715
1769
  toJSONSchema,
@@ -1736,7 +1790,7 @@ import {
1736
1790
  ZodIssueCode,
1737
1791
  exports_iso,
1738
1792
  exports_coerce
1739
- } from "./cli-hg42n3hx.js";
1793
+ } from "./cli-qrzq3hvg.js";
1740
1794
  import {
1741
1795
  MAX_PROFILE_FILE_LENGTH,
1742
1796
  DEFAULT_APP_URL,
@@ -1759,7 +1813,7 @@ import {
1759
1813
  import {
1760
1814
  init_package,
1761
1815
  package_default
1762
- } from "./cli-3f8zbtqa.js";
1816
+ } from "./cli-a6q6x15h.js";
1763
1817
  import {
1764
1818
  realtimeBus,
1765
1819
  init_bus
@@ -1775,7 +1829,7 @@ import {
1775
1829
  registerVolatileSecret,
1776
1830
  registerEnvSecrets,
1777
1831
  init_secret_scrubber
1778
- } from "./cli-5a6pqy45.js";
1832
+ } from "./cli-7e8sxqv5.js";
1779
1833
  import {
1780
1834
  __toESM
1781
1835
  } from "./cli-242037k3.js";
@@ -1843,8 +1897,71 @@ init_types5();
1843
1897
  init_env_flag();
1844
1898
  init_secret_scrubber();
1845
1899
  init_db4();
1846
- init_swarm_config_guard();
1847
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();
1848
1965
  var DAY_MS = 24 * 60 * 60 * 1000;
1849
1966
  var RETENTION_INTERVAL_MS = 60 * 60 * 1000;
1850
1967
  var DEFAULT_TICK_BUDGET_MS = 30000;
@@ -1860,6 +1977,7 @@ var DB_RETENTION_TABLES = [
1860
1977
  policy: "age",
1861
1978
  timeColumn: "createdAt",
1862
1979
  envKey: "SESSION_LOG_RETENTION_DAYS",
1980
+ newInstallDefault: 30,
1863
1981
  metricsKey: "sessionLogs"
1864
1982
  },
1865
1983
  {
@@ -1867,6 +1985,7 @@ var DB_RETENTION_TABLES = [
1867
1985
  policy: "age",
1868
1986
  timeColumn: "createdAt",
1869
1987
  envKey: "AGENT_LOG_RETENTION_DAYS",
1988
+ newInstallDefault: 90,
1870
1989
  metricsKey: "agentLog"
1871
1990
  },
1872
1991
  {
@@ -1874,6 +1993,7 @@ var DB_RETENTION_TABLES = [
1874
1993
  policy: "age",
1875
1994
  timeColumn: "createdAt",
1876
1995
  envKey: "EVENTS_RETENTION_DAYS",
1996
+ newInstallDefault: 90,
1877
1997
  metricsKey: "events"
1878
1998
  },
1879
1999
  {
@@ -1882,6 +2002,7 @@ var DB_RETENTION_TABLES = [
1882
2002
  partitionBy: "agentId, field",
1883
2003
  rankBy: "version",
1884
2004
  envKey: "CONTEXT_VERSIONS_KEEP_LATEST",
2005
+ newInstallDefault: 100,
1885
2006
  metricsKey: "contextVersions",
1886
2007
  initialBatchSize: 50,
1887
2008
  maxBatchSize: 100
@@ -1895,9 +2016,19 @@ var DB_RETENTION_TABLES = [
1895
2016
  terminalStatuses: TERMINAL_SCRIPT_RUN_STATUSES,
1896
2017
  keepWhenSet: "idempotencyKey",
1897
2018
  envKey: "SCRIPT_RUNS_RETENTION_DAYS",
2019
+ newInstallDefault: 30,
1898
2020
  metricsKey: "scriptRuns",
1899
2021
  initialBatchSize: 100,
1900
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
1901
2032
  }
1902
2033
  ];
1903
2034
 
@@ -2021,6 +2152,10 @@ function maxBatchSize(table) {
2021
2152
  return "maxBatchSize" in table ? table.maxBatchSize : MAX_BATCH_SIZE;
2022
2153
  }
2023
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
+ }
2024
2159
  if (table.policy === "keepLatest") {
2025
2160
  const ranked = `SELECT rowid AS rid, ROW_NUMBER() OVER (PARTITION BY ${table.partitionBy} ORDER BY ${table.rankBy} DESC) AS rn FROM ${table.table}`;
2026
2161
  return {
@@ -2081,21 +2216,30 @@ async function sweepTable(table, statements, dryRun, deadline, signal, maxStatem
2081
2216
  let slowestStatementMs = 0;
2082
2217
  let size = batchSizeByTable[table.metricsKey] ?? initialBatchSize(table);
2083
2218
  const ceiling = maxBatchSize(table);
2219
+ const floor = "minBatchSize" in table ? table.minBatchSize : MIN_BATCH_SIZE;
2084
2220
  try {
2085
2221
  while (!signal.aborted && Date.now() < deadline) {
2086
2222
  const limitUsed = size;
2087
- 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
+ }
2088
2232
  const elapsed = result.executionMs;
2089
2233
  bestEffortRecordStatement(table.table, dryRun, elapsed);
2090
2234
  slowestStatementMs = Math.max(slowestStatementMs, elapsed);
2091
2235
  rowsDeleted += result.changes;
2092
2236
  batches += 1;
2093
2237
  if (elapsed > maxStatementMs) {
2094
- size = Math.max(MIN_BATCH_SIZE, Math.floor(size / 2));
2238
+ size = Math.max(floor, Math.floor(size / 2));
2095
2239
  } else if (elapsed < maxStatementMs / 5) {
2096
2240
  size = Math.min(ceiling, size * 2);
2097
2241
  }
2098
- if (result.changes < limitUsed)
2242
+ if (result.changes === 0 || table.policy !== "workflowRuns" && result.changes < limitUsed)
2099
2243
  break;
2100
2244
  if (signal.aborted || Date.now() >= deadline)
2101
2245
  break;
@@ -2363,6 +2507,35 @@ async function stopDbRetention() {
2363
2507
  await retentionTickPromise;
2364
2508
  }
2365
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
+
2366
2539
  // src/http/index.ts
2367
2540
  init_event_loop_lag();
2368
2541
 
@@ -2422,6 +2595,489 @@ function stopHumanFreeDrain() {
2422
2595
  passTimer = null;
2423
2596
  }
2424
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
+
2425
3081
  // src/be/mcp-overflow-sweep.ts
2426
3082
  init_kv_overflow();
2427
3083
  init_db4();
@@ -4352,7 +5008,7 @@ init_otel();
4352
5008
 
4353
5009
  // src/queue-stall-alarm.ts
4354
5010
  init_db4();
4355
- init_app3();
5011
+ init_app4();
4356
5012
  init_secret_scrubber();
4357
5013
  var QUEUE_STALL_THRESHOLD_MS = 30 * 60 * 1000;
4358
5014
  var QUEUE_STALL_CHECK_INTERVAL_MS = 5 * 60 * 1000;
@@ -9173,6 +9829,7 @@ init_rbac_roles();
9173
9829
  init_swarm_config_guard();
9174
9830
  init_users();
9175
9831
  init_rbac();
9832
+ init_reaction_shortcode();
9176
9833
  init_types5();
9177
9834
  init_request_auth_context();
9178
9835
  init_secret_scrubber();
@@ -9903,7 +10560,7 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9903
10560
  const presence = {};
9904
10561
  for (const key of keys) {
9905
10562
  const value = key === "SWARM_ORG_NAME" ? process.env[key]?.trim() : process.env[key];
9906
- presence[key] = value !== undefined && value !== "";
10563
+ presence[key] = value !== undefined && (isSlackIconConfigKey(key) || value !== "");
9907
10564
  }
9908
10565
  envPresence.respond(res, 200, { presence });
9909
10566
  return true;
@@ -11087,13 +11744,13 @@ init_types5();
11087
11744
  init_secret_scrubber();
11088
11745
  init_route_def();
11089
11746
  init_utils2();
11090
- import { createHash } from "node:crypto";
11747
+ import { createHash as createHash3 } from "node:crypto";
11091
11748
  function apiKeyFingerprint(req) {
11092
11749
  const authHeader = req.headers.authorization;
11093
11750
  const providedKey = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : "";
11094
11751
  if (!providedKey)
11095
11752
  return "";
11096
- const digest = createHash("sha256").update(providedKey).digest("hex").slice(0, 8);
11753
+ const digest = createHash3("sha256").update(providedKey).digest("hex").slice(0, 8);
11097
11754
  return scrubSecrets(digest);
11098
11755
  }
11099
11756
  var ScopeIdSchema = string2().max(255).describe("Scope identifier — empty string for global, agent UUID otherwise");
@@ -16508,7 +17165,13 @@ const shortcode = (raw: string): string | null => {
16508
17165
 
16509
17166
  /** The acceptance reactions the engine may have put on the message, deduplicated. */
16510
17167
  export const acceptanceReactions = (): string[] => [
16511
- ...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
+ ),
16512
17175
  ];
16513
17176
 
16514
17177
  const slackCall = async (
@@ -16650,9 +17313,7 @@ export const askModel = async (
16650
17313
  } | null;
16651
17314
  if (res?.success === false || body?.success === false) {
16652
17315
  const why = \`\${target.provider}: \${String(body?.message ?? body?.error ?? \`HTTP \${res?.status}\`).slice(0, 200)}\`;
16653
- throw body?.providerUnavailable === true
16654
- ? new ProviderUnavailableError(why)
16655
- : new Error(why);
17316
+ throw body?.providerUnavailable === true ? new ProviderUnavailableError(why) : new Error(why);
16656
17317
  }
16657
17318
  const answer = body?.answers?.reason;
16658
17319
  const reason = typeof answer?.choice === "string" ? answer.choice : "";
@@ -19139,6 +19800,65 @@ function sendProviderError(res, error) {
19139
19800
  return true;
19140
19801
  }
19141
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
+
19142
19862
  // src/http/heartbeat.ts
19143
19863
  init_zod();
19144
19864
  init_route_def();
@@ -19621,7 +20341,7 @@ async function handleInboxState(req, res, pathSegments, queryParams) {
19621
20341
  init_zod();
19622
20342
 
19623
20343
  // src/slack/app-icon.ts
19624
- init_app3();
20344
+ init_app4();
19625
20345
  var import_web_api = __toESM(require_dist4(), 1);
19626
20346
  var TTL_MS = 60 * 60 * 1000;
19627
20347
  var REQUEST_TIMEOUT_MS = 2500;
@@ -22175,32 +22895,9 @@ async function handleMcp(req, res, transports, sessionActivity = {}, sessionAgen
22175
22895
  delete sessionActivity[transport.sessionId];
22176
22896
  }
22177
22897
  };
22178
- const configs = await getResolvedConfig2(agentId);
22179
- const configValue = configs.find((config) => config.key === "SCRIPTS_ONLY_MCP")?.value;
22180
- const preloadEnabled = parseEnvFlag(configs.find((config) => config.key === "TASK_TOOL_PRELOAD_ENABLED")?.value ?? process.env.TASK_TOOL_PRELOAD_ENABLED, true);
22181
- let preloadedTools = [];
22182
22898
  const sourceTaskId = headerValue(req.headers["x-source-task-id"]);
22183
22899
  const sourceTask = sourceTaskId ? await getTaskById2(sourceTaskId) : undefined;
22184
- const excludedTools = sourceTask && !isChatSdkTask(sourceTask) ? [...CHAT_TASK_ONLY_TOOLS] : [];
22185
- if (preloadEnabled) {
22186
- if (sourceTask?.agentId === agentId) {
22187
- const manifestValue = configs.find((config) => config.key === "TASK_TOOL_MANIFESTS")?.value ?? process.env.TASK_TOOL_MANIFESTS ?? "{}";
22188
- try {
22189
- preloadedTools = selectTaskTools(parseTaskToolManifest(manifestValue), sourceTask);
22190
- } catch {
22191
- console.warn("[MCP] Invalid TASK_TOOL_MANIFESTS; using ordinary tool discovery");
22192
- }
22193
- }
22194
- }
22195
- const server = await createServer({
22196
- preloadedTools,
22197
- excludedTools,
22198
- enabledTools: configs.find((config) => config.key === "SWARM_ENABLED_TOOLS")?.value ?? process.env.SWARM_ENABLED_TOOLS,
22199
- scriptsOnly: resolveScriptsOnlyMode({
22200
- env: process.env.SCRIPTS_ONLY_MCP,
22201
- configValue
22202
- })
22203
- });
22900
+ const server = await createServer(await resolveMcpSessionOptions(agentId, sourceTask));
22204
22901
  await server.connect(transport);
22205
22902
  } else {
22206
22903
  return respondNoMcpSession(res, sessionId);
@@ -22221,6 +22918,29 @@ async function handleMcp(req, res, transports, sessionActivity = {}, sessionAgen
22221
22918
  res.end("Method not allowed");
22222
22919
  return true;
22223
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
+ }
22224
22944
 
22225
22945
  // src/http/index.ts
22226
22946
  init_mcp_bridge();
@@ -23475,6 +24195,198 @@ init_users();
23475
24195
  init_mcp();
23476
24196
  init_zod();
23477
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
23478
24390
  init_rbac_audit();
23479
24391
  init_rbac_roles();
23480
24392
  init_mcp_limits();
@@ -23521,7 +24433,7 @@ async function maybeDenyUserToolAdmission(user, toolName, config) {
23521
24433
  return;
23522
24434
  return toolErr(`Forbidden: ${decision.reason}`);
23523
24435
  }
23524
- function createUserServer(user) {
24436
+ function createUserServer(user, tokenId) {
23525
24437
  const server = new McpServer({
23526
24438
  name: `${package_default.name}-user`,
23527
24439
  version: package_default.version,
@@ -23533,6 +24445,13 @@ function createUserServer(user) {
23533
24445
  maxToolInputElements: MCP_MAX_TOOL_INPUT_ELEMENTS
23534
24446
  });
23535
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
+ }
23536
24455
  const sendTaskConfig = {
23537
24456
  title: "Send a task",
23538
24457
  annotations: { destructiveHint: false },
@@ -23631,19 +24550,20 @@ async function resolveActiveUser(req) {
23631
24550
  const token = extractBearer(req);
23632
24551
  if (!token)
23633
24552
  return null;
23634
- const user = await resolveUserByToken(token);
23635
- if (!user || user.status !== "active")
24553
+ const resolved = await resolveUserToken(token);
24554
+ if (!resolved?.user || resolved.user.status !== "active")
23636
24555
  return null;
23637
- return user;
24556
+ return { user: resolved.user, tokenId: resolved.tokenId };
23638
24557
  }
23639
24558
  async function handleMcpUser(req, res, transports, sessionUsers, sessionActivity = {}) {
23640
24559
  const sessionId = req.headers["mcp-session-id"];
23641
24560
  if (req.url !== "/mcp-user") {
23642
24561
  return false;
23643
24562
  }
23644
- const user = await resolveActiveUser(req);
23645
- if (!user)
24563
+ const resolved = await resolveActiveUser(req);
24564
+ if (!resolved)
23646
24565
  return unauthorized2(res);
24566
+ const { user, tokenId } = resolved;
23647
24567
  setRequestAuth(req, { kind: "user", userId: user.id, user });
23648
24568
  if (sessionId && transports[sessionId] && sessionUsers[sessionId] !== user.id) {
23649
24569
  return unauthorized2(res);
@@ -23677,7 +24597,7 @@ async function handleMcpUser(req, res, transports, sessionUsers, sessionActivity
23677
24597
  delete sessionActivity[transport.sessionId];
23678
24598
  }
23679
24599
  };
23680
- const server = createUserServer(user);
24600
+ const server = createUserServer(user, tokenId);
23681
24601
  await server.connect(transport);
23682
24602
  } else {
23683
24603
  return respondNoMcpSession(res, sessionId);
@@ -28981,7 +29901,7 @@ var supersedeTaskRoute = route({
28981
29901
  pattern: ["api", "tasks", null, "supersede"],
28982
29902
  session: { taskParam: "id" },
28983
29903
  summary: "Supersede an in-progress task (terminate + spawn resume follow-up)",
28984
- 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 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.",
28985
29905
  tags: ["Tasks"],
28986
29906
  params: object2({ id: string2() }),
28987
29907
  body: object2({ reason: ResumeReasonSchema, errorClass: ProviderErrorClassSchema.optional() }).refine((body) => body.reason === "provider_fallback" === (body.errorClass !== undefined), {
@@ -30144,6 +31064,9 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
30144
31064
  return true;
30145
31065
  }
30146
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
+ }
30147
31070
  }
30148
31071
  if (task.workflowRunStepId != null) {
30149
31072
  const failed = await failTask2(parsed.params.id, SUPERSEDED_WORKFLOW_TASK_REASON);
@@ -33506,7 +34429,7 @@ init_multi_runtime();
33506
34429
  init_server();
33507
34430
 
33508
34431
  // src/slack/channel-activity.ts
33509
- init_app3();
34432
+ init_app4();
33510
34433
  var cachedBotUserId = null;
33511
34434
  var channelCache = null;
33512
34435
  var CHANNEL_CACHE_TTL_MS = 5 * 60 * 1000;
@@ -34435,13 +35358,13 @@ init_types5();
34435
35358
  init_secret_scrubber();
34436
35359
  init_route_def();
34437
35360
  init_utils2();
34438
- import { createHash as createHash2 } from "node:crypto";
35361
+ import { createHash as createHash4 } from "node:crypto";
34439
35362
  function apiKeyFingerprint2(req) {
34440
35363
  const authHeader = req.headers.authorization;
34441
35364
  const providedKey = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : "";
34442
35365
  if (!providedKey)
34443
35366
  return "";
34444
- const digest = createHash2("sha256").update(providedKey).digest("hex").slice(0, 8);
35367
+ const digest = createHash4("sha256").update(providedKey).digest("hex").slice(0, 8);
34445
35368
  return scrubSecrets(digest);
34446
35369
  }
34447
35370
  var PricingTriplePathParams = object2({
@@ -34641,7 +35564,8 @@ var ResolveResultSchema = object2({
34641
35564
  templateId: string2().optional(),
34642
35565
  scope: string2().optional(),
34643
35566
  skipped: boolean(),
34644
- unresolved: array2(string2())
35567
+ unresolved: array2(string2()),
35568
+ segments: array2(object2({ templateId: string2(), chars: number2().int() })).optional()
34645
35569
  });
34646
35570
  var DbResolveResultSchema = union3([
34647
35571
  object2({ template: PromptTemplateResponseSchema }),
@@ -35324,6 +36248,957 @@ async function handleRepos(req, res, pathSegments, queryParams, myAgentId) {
35324
36248
  return false;
35325
36249
  }
35326
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
+
35327
37202
  // src/http/rooms.ts
35328
37203
  init_zod();
35329
37204
  init_auth2();
@@ -36074,8 +37949,8 @@ function daysBetween(firstDay, lastDay) {
36074
37949
  }
36075
37950
  var sliceCache = new Map;
36076
37951
  var SLICE_TTL_MS = 2 * MINUTE_MS;
36077
- var HOUR_MS = 60 * MINUTE_MS;
36078
- 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;
36079
37954
  var FIRST_DAY_SCAN_CONCURRENCY = 2;
36080
37955
  var scansInFlight = 0;
36081
37956
  var scanWaiters = [];
@@ -36339,7 +38214,7 @@ async function clipFirstDay(buckets, window, firstDay, fleet, sql = (q, p) => ge
36339
38214
  const startMs = Date.parse(window.start);
36340
38215
  if (window.start === dayStartIso(firstDay))
36341
38216
  return false;
36342
- 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;
36343
38218
  const first = buckets.filter((b) => b.day === firstDay);
36344
38219
  if (first.length === 0)
36345
38220
  return false;
@@ -36783,7 +38658,7 @@ async function clipScriptFirstDay(jobs, window, firstDay, opts) {
36783
38658
  const startMs = Date.parse(window.start);
36784
38659
  if (window.start === dayStartIso(firstDay))
36785
38660
  return false;
36786
- 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;
36787
38662
  if (![...jobs.values()].some((j) => j.days.has(firstDay)))
36788
38663
  return false;
36789
38664
  const slice = { start: sliceStart, end: dayStartIso(utcDay(startMs + DAY_MS3)) };
@@ -42738,7 +44613,7 @@ init_bus();
42738
44613
 
42739
44614
  // src/slack/channel-labels.ts
42740
44615
  init_session_labels();
42741
- init_app3();
44616
+ init_app4();
42742
44617
  init_render_v2();
42743
44618
  var LABEL_TTL_MS = 24 * 60 * 60 * 1000;
42744
44619
  var FAILURE_TTL_MS = 10 * 60 * 1000;
@@ -44984,7 +46859,7 @@ async function handleSkills(req, res, pathSegments, queryParams, myAgentId) {
44984
46859
  }
44985
46860
 
44986
46861
  // src/http/slack-events.ts
44987
- init_app3();
46862
+ init_app4();
44988
46863
  init_config4();
44989
46864
  init_route_def();
44990
46865
  init_utils2();
@@ -45713,7 +47588,7 @@ async function handleToolHooks(req, res, pathSegments, queryParams, myAgentId) {
45713
47588
  // src/http/trackers/jira.ts
45714
47589
  init_zod();
45715
47590
  init_oauth();
45716
- init_app();
47591
+ init_app2();
45717
47592
  init_metadata();
45718
47593
  init_webhook();
45719
47594
  init_webhook_lifecycle();
@@ -46127,11 +48002,11 @@ async function handleJiraTracker(req, res, pathSegments) {
46127
48002
  // src/http/trackers/linear.ts
46128
48003
  init_zod();
46129
48004
  init_oauth();
46130
- init_app2();
48005
+ init_app3();
46131
48006
 
46132
48007
  // src/linear/webhook.ts
46133
48008
  init_sync();
46134
- import { createHmac, timingSafeEqual } from "node:crypto";
48009
+ import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
46135
48010
  var recentDeliveries = new Map;
46136
48011
  var DEDUP_TTL_MS = 5 * 60 * 1000;
46137
48012
  function cleanupDeliveries() {
@@ -46142,9 +48017,9 @@ function cleanupDeliveries() {
46142
48017
  }
46143
48018
  }
46144
48019
  function verifyLinearWebhook(rawBody, signature, secret) {
46145
- const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
48020
+ const expected = createHmac2("sha256", secret).update(rawBody).digest("hex");
46146
48021
  try {
46147
- return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
48022
+ return timingSafeEqual2(Buffer.from(signature), Buffer.from(expected));
46148
48023
  } catch {
46149
48024
  return false;
46150
48025
  }
@@ -48005,11 +49880,11 @@ init_agentmail();
48005
49880
  // src/agentmail/inbound-archive.ts
48006
49881
  init_db4();
48007
49882
  init_secret_scrubber();
48008
- import { createHash as createHash3 } from "node:crypto";
49883
+ import { createHash as createHash5 } from "node:crypto";
48009
49884
  var INBOUND_ARCHIVE_NAMESPACE = "agentmail-inbound";
48010
49885
  var INBOUND_ARCHIVE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
48011
49886
  var text = (value, limit) => typeof value === "string" ? scrubSecrets(value).slice(0, limit) : "";
48012
- 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");
48013
49888
  async function archiveInboundMessage(payload) {
48014
49889
  if (![
48015
49890
  "message.received",
@@ -49531,12 +51406,22 @@ var webhookTriggerRoute = route({
49531
51406
  auth: { apiKey: false },
49532
51407
  responses: {
49533
51408
  200: {
49534
- description: "Delivery skipped: its event is not in the trigger's `events` allowlist. No run was created.",
49535
- schema: object2({
49536
- skipped: literal2(true),
49537
- reason: literal2("event-not-allowed"),
49538
- event: string2().nullable()
49539
- })
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
+ ])
49540
51425
  },
49541
51426
  201: { description: "Webhook processed", schema: object2({ runId: string2() }) },
49542
51427
  401: { description: "Invalid signature" },
@@ -49610,11 +51495,19 @@ async function handleWorkflows(req, res, pathSegments, queryParams, myAgentId) {
49610
51495
  return true;
49611
51496
  }
49612
51497
  if (result.skipped) {
49613
- webhookTriggerRoute.respond(res, 200, {
49614
- skipped: true,
49615
- reason: result.reason,
49616
- event: result.event
49617
- });
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
+ }
49618
51511
  } else {
49619
51512
  webhookTriggerRoute.respond(res, 201, { runId: result.runId });
49620
51513
  }
@@ -50133,7 +52026,7 @@ init_secret_scrubber();
50133
52026
  init_json_schema_validator();
50134
52027
  init_route_def();
50135
52028
  init_utils2();
50136
- import { timingSafeEqual as timingSafeEqual2 } from "node:crypto";
52029
+ import { timingSafeEqual as timingSafeEqual3 } from "node:crypto";
50137
52030
  var DEFAULT_TIMEOUT_MS = 60000;
50138
52031
  var TIMEOUT_HEADER = "x-swarm-timeout-ms";
50139
52032
  var MAX_BODY_BYTES = 1 * 1024 * 1024;
@@ -50187,7 +52080,7 @@ function timingSafeEqualStr(a, b) {
50187
52080
  const bb = Buffer.from(b);
50188
52081
  if (ab.length !== bb.length)
50189
52082
  return false;
50190
- return timingSafeEqual2(ab, bb);
52083
+ return timingSafeEqual3(ab, bb);
50191
52084
  }
50192
52085
  function resolveTimeoutMs(req) {
50193
52086
  const raw = req.headers[TIMEOUT_HEADER];
@@ -50451,6 +52344,7 @@ var httpServer = createHttpServer(async (req, res) => {
50451
52344
  () => handleAgentsRest(req, res, pathSegments, queryParams, myAgentId),
50452
52345
  () => handleBudgets(req, res, pathSegments, queryParams, myAgentId),
50453
52346
  () => handleContext(req, res, pathSegments, queryParams, myAgentId),
52347
+ () => handleRequestComposition(req, res, pathSegments, queryParams, myAgentId),
50454
52348
  () => handleAssets(req, res, pathSegments, queryParams, myAgentId),
50455
52349
  () => handleTasks(req, res, pathSegments, queryParams, myAgentId),
50456
52350
  () => handleStats(req, res, pathSegments, queryParams, myAgentId),
@@ -50468,6 +52362,7 @@ var httpServer = createHttpServer(async (req, res) => {
50468
52362
  () => handlePoolKeys(req, res, pathSegments, queryParams),
50469
52363
  () => handleConfig(req, res, pathSegments, queryParams),
50470
52364
  () => handleFs(req, res, pathSegments, queryParams, myAgentId),
52365
+ () => handleGitHubToken(req, res, pathSegments, myAgentId),
50471
52366
  () => handleAgentFsProxy(req, res),
50472
52367
  () => handleComb(req, res, pathSegments, queryParams, myAgentId),
50473
52368
  () => handleKv(req, res, pathSegments, queryParams),
@@ -50546,7 +52441,7 @@ var httpServer = createHttpServer(async (req, res) => {
50546
52441
  });
50547
52442
  });
50548
52443
  var detachRealtime = attachRealtimeTransport(httpServer);
50549
- var { attachControllerTransport } = await import("./controllers-connect-5v7qx04j.js");
52444
+ var { attachControllerTransport } = await import("./controllers-connect-w3qbpbt1.js");
50550
52445
  var detachControllers = attachControllerTransport(httpServer);
50551
52446
  var stopWorkerNudges = startWorkerNudgeListener();
50552
52447
  var taskAutoTitles = startTaskAutoTitleListener();
@@ -50577,7 +52472,7 @@ async function shutdown() {
50577
52472
  sessionsProcessed: getServerSessionsProcessed()
50578
52473
  });
50579
52474
  if (hasCapability("scheduling")) {
50580
- const { stopScheduler } = await import("./index-rkvaambe.js");
52475
+ const { stopScheduler } = await import("./index-1f6m47mq.js");
50581
52476
  stopScheduler();
50582
52477
  }
50583
52478
  stopHeartbeat2();
@@ -50589,7 +52484,7 @@ async function shutdown() {
50589
52484
  await stopSlackApp2();
50590
52485
  await stopChatSdk();
50591
52486
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
50592
- const { stopOAuthKeepalive } = await import("./keepalive-7yxg8z4c.js");
52487
+ const { stopOAuthKeepalive } = await import("./keepalive-jmf6pn8c.js");
50593
52488
  await stopOAuthKeepalive();
50594
52489
  }
50595
52490
  stopOAuthPendingGc();
@@ -50648,6 +52543,11 @@ if (!globalState.__runId) {
50648
52543
  }
50649
52544
  startApiGcInterval();
50650
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
+ }
50651
52551
  var startupConfigsInjected = [];
50652
52552
  try {
50653
52553
  startupConfigsInjected = await loadGlobalConfigsIntoEnv2(true);
@@ -50674,21 +52574,21 @@ try {
50674
52574
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
50675
52575
  }
50676
52576
  try {
50677
- const { ensurePricingSeeded } = await import("./boot-seeds-nj9za0vk.js");
52577
+ const { ensurePricingSeeded } = await import("./boot-seeds-kb3dxjex.js");
50678
52578
  ensurePricingSeeded();
50679
- const { startPricingRefreshLoop } = await import("./pricing-refresh-fzxvk2zf.js");
52579
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-4j8dzvxg.js");
50680
52580
  startPricingRefreshLoop();
50681
52581
  } catch (err) {
50682
52582
  console.error("[startup] Failed to seed pricing rows:", err);
50683
52583
  }
50684
52584
  try {
50685
- const { ensureModelProfilesSeeded } = await import("./boot-seeds-nj9za0vk.js");
52585
+ const { ensureModelProfilesSeeded } = await import("./boot-seeds-kb3dxjex.js");
50686
52586
  await ensureModelProfilesSeeded();
50687
52587
  } catch (err) {
50688
52588
  console.error("[startup] Failed to seed model profiles:", err);
50689
52589
  }
50690
52590
  try {
50691
- const { ensureRbacSeeded } = await import("./boot-seeds-nj9za0vk.js");
52591
+ const { ensureRbacSeeded } = await import("./boot-seeds-kb3dxjex.js");
50692
52592
  ensureRbacSeeded();
50693
52593
  } catch (err) {
50694
52594
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -50696,13 +52596,13 @@ try {
50696
52596
  throw err;
50697
52597
  }
50698
52598
  try {
50699
- const { runAllSeeders } = await import("./index-ny60jcat.js");
52599
+ const { runAllSeeders } = await import("./index-e42j998x.js");
50700
52600
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
50701
52601
  } catch (err) {
50702
52602
  console.error("[startup] Failed to seed built-in entities:", err);
50703
52603
  }
50704
52604
  try {
50705
- const { runImports } = await import("./index-p46tvwtx.js");
52605
+ const { runImports } = await import("./index-akbgsdhh.js");
50706
52606
  await runImports();
50707
52607
  } catch (err) {
50708
52608
  console.error("[startup] File import failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
@@ -50753,7 +52653,7 @@ httpServer.listen(port, async () => {
50753
52653
  startChatSdk().catch((err) => {
50754
52654
  console.error("[chat-sdk] Failed to start, continuing without Chat SDK:", scrubSecrets(err instanceof Error ? err.message : String(err)));
50755
52655
  });
50756
- import("./agent-fs-provision-tpj7sktd.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
52656
+ import("./agent-fs-provision-v6enh76w.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
50757
52657
  console.warn("[agent-fs] Failed to set the org swarm URL:", scrubSecrets(err instanceof Error ? err.message : String(err)));
50758
52658
  });
50759
52659
  startQueueStallAlarm();
@@ -50761,6 +52661,7 @@ httpServer.listen(port, async () => {
50761
52661
  initGitLab();
50762
52662
  initAzureDevOps();
50763
52663
  initAzureDevOpsOutbound();
52664
+ initMcpEventsDispatcher();
50764
52665
  initBitbucket();
50765
52666
  initAgentMail();
50766
52667
  await initLinear();
@@ -50768,25 +52669,25 @@ httpServer.listen(port, async () => {
50768
52669
  await initWorkflows2();
50769
52670
  await startScriptRunSupervisor(getMcpBaseUrl());
50770
52671
  if (hasCapability("scheduling")) {
50771
- const { startScheduler } = await import("./index-rkvaambe.js");
50772
- const { getExecutorRegistry } = await import("./index-xj1mq27m.js");
52672
+ const { startScheduler } = await import("./index-1f6m47mq.js");
52673
+ const { getExecutorRegistry } = await import("./index-tnkd410q.js");
50773
52674
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
50774
52675
  startScheduler(getExecutorRegistry(), intervalMs, {
50775
52676
  runId: globalState.__runId
50776
52677
  });
50777
52678
  }
50778
52679
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
50779
- const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-48qzcqzj.js");
52680
+ const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-1p1mpqda.js");
50780
52681
  startHeartbeat(parseHeartbeatIntervalMs(process.env.HEARTBEAT_INTERVAL_MS));
50781
52682
  }
50782
52683
  startPoolRouting();
50783
52684
  startRuntimeSupervisor();
50784
52685
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
50785
- const { startOAuthKeepalive } = await import("./keepalive-7yxg8z4c.js");
52686
+ const { startOAuthKeepalive } = await import("./keepalive-jmf6pn8c.js");
50786
52687
  startOAuthKeepalive();
50787
52688
  }
50788
52689
  if (!isEnvFlagEnabled("OAUTH_REFRESH_SWEEP_DISABLE", false)) {
50789
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-70cavc3a.js");
52690
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-ywgf8tbr.js");
50790
52691
  startOAuthRefreshSweep();
50791
52692
  }
50792
52693
  startOAuthPendingGc();
@@ -50796,22 +52697,22 @@ httpServer.listen(port, async () => {
50796
52697
  startSavingsRollup(savingsRollupSql);
50797
52698
  startHumanFreeDrain();
50798
52699
  startTaskSearchBackfill();
50799
- import("./embedding-space-e48xchqa.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
52700
+ import("./embedding-space-z6ptw3jk.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
50800
52701
  setDeploymentEnvReader(getDeploymentEnvValue2);
50801
52702
  return runEmbeddingMaintenance({ backfill: true });
50802
52703
  }).catch((err) => {
50803
52704
  console.error("[embedding-space] startup maintenance failed (non-fatal):", err);
50804
52705
  });
50805
- import("./boot-args-schema-qxmd59sr.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
52706
+ import("./boot-args-schema-d7fme4q1.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
50806
52707
  console.error("[boot-args-schema] startup backfill failed (non-fatal):", err);
50807
52708
  });
50808
- import("./boot-scrub-sweep-25bxhnw4.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
52709
+ import("./boot-scrub-sweep-52h7yntp.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
50809
52710
  console.error("[boot-scrub-sweep] startup scrub failed (non-fatal):", err);
50810
52711
  });
50811
- import("./user-merge-jobs-bx6bf7db.js").then(({ resumeUserMergeJobs }) => resumeUserMergeJobs()).catch((err) => {
52712
+ import("./user-merge-jobs-mvheb3ed.js").then(({ resumeUserMergeJobs }) => resumeUserMergeJobs()).catch((err) => {
50812
52713
  console.error("[user-merge] startup resume failed (non-fatal):", err);
50813
52714
  });
50814
- import("./session-source-backfill-82qe7fqq.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
52715
+ import("./session-source-backfill-ax6qxv20.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
50815
52716
  console.error("[session-source-backfill] startup run failed (non-fatal):", err);
50816
52717
  });
50817
52718
  }).on("error", (err) => {