@desplega.ai/agent-swarm 2.8.3 → 2.9.1

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 (597) hide show
  1. package/dist/acp-adapter-g909b5hw.js +16 -0
  2. package/dist/acp-targets-ny75x1qy.js +23 -0
  3. package/dist/{actions-ewz7bp4g.js → actions-b9qgrmeq.js} +82 -21
  4. package/dist/agent-fs-provision-b5dhdsbd.js +27 -0
  5. package/dist/{amp-adapter-f25tqhnf.js → amp-adapter-vtax2c9s.js} +3 -3
  6. package/dist/{anthropic-messages-jkva0zps.js → anthropic-messages-r5xf5hqw.js} +37 -37
  7. package/dist/{app-mkptw0k7.js → app-g2z15hax.js} +9 -4
  8. package/dist/approval-notifications-yt13wp8r.js +23 -0
  9. package/dist/{assistant-c47rfe77.js → assistant-2cgfxsgk.js} +56 -33
  10. package/dist/{azure-openai-responses-wgtqkbr3.js → azure-openai-responses-590s1eea.js} +10 -10
  11. package/dist/{boot-args-schema-4vb0xsat.js → boot-args-schema-3gwy0f60.js} +1 -1
  12. package/dist/{boot-reembed-htr73hbs.js → boot-reembed-92g7s5zp.js} +1 -1
  13. package/dist/{boot-reembed-1ghy2sab.js → boot-reembed-mywmyp4s.js} +1 -1
  14. package/dist/{boot-scrub-sweep-yrytg42z.js → boot-scrub-sweep-7dkdzqxx.js} +84 -13
  15. package/dist/{boot-seeds-n2b3dx4e.js → boot-seeds-ce7rvgq1.js} +4 -4
  16. package/dist/{boxd-jmfqgkqa.js → boxd-wn235q80.js} +7 -7
  17. package/dist/claude-adapter-3m4q7735.js +28 -0
  18. package/dist/{claude-managed-adapter-hddmxjyj.js → claude-managed-adapter-t8nfgcgz.js} +4 -4
  19. package/dist/{claude-managed-setup-hfvry1bd.js → claude-managed-setup-c217draw.js} +10 -10
  20. package/dist/{claude-sdk-session-0hamqzc7.js → claude-sdk-session-7fbqm51z.js} +9386 -9196
  21. package/dist/{cli-yjdgea32.js → cli-1jx0srjt.js} +17 -17
  22. package/dist/{cli-sdvcrq5x.js → cli-1jykg0py.js} +18 -14
  23. package/dist/{cli-k96cecs7.js → cli-2czxfnvj.js} +1221 -357
  24. package/dist/{cli-qmqt520k.js → cli-2dq9yv8p.js} +2 -2
  25. package/dist/{cli-e2w34h6z.js → cli-2xs8tsf7.js} +132 -85
  26. package/dist/{cli-z8cvws4c.js → cli-2yjj3e31.js} +907 -56
  27. package/dist/{cli-mdpbjnzq.js → cli-32djehja.js} +42 -42
  28. package/dist/{cli-gpz1d0t2.js → cli-3j873zxq.js} +4 -4
  29. package/dist/cli-43ms35q9.js +270 -0
  30. package/dist/cli-47hz21se.js +25584 -0
  31. package/dist/{cli-n515ex5z.js → cli-4ymxrwg5.js} +16 -16
  32. package/dist/{cli-f1kwb5fc.js → cli-5a6pqy45.js} +333 -21
  33. package/dist/{cli-93t5s4zq.js → cli-5gpqgs8b.js} +2 -2
  34. package/dist/{cli-15204js0.js → cli-6237rnyr.js} +1 -1
  35. package/dist/{cli-4ax9mvvg.js → cli-67mwzr35.js} +9 -9
  36. package/dist/{cli-t5ys4ebm.js → cli-6945ywhr.js} +3 -3
  37. package/dist/{cli-0bcgyj5b.js → cli-6ehs4mta.js} +87 -8
  38. package/dist/{cli-6yygkr0w.js → cli-6ym4jhzp.js} +15 -7
  39. package/dist/{cli-8bpgbr8k.js → cli-7evph51z.js} +5 -5
  40. package/dist/{cli-dtdht77h.js → cli-7mv4h3sn.js} +2 -2
  41. package/dist/{cli-nx2n3z6p.js → cli-7sf9sb0w.js} +3 -2
  42. package/dist/{cli-pe4d96rb.js → cli-7zm3b3f5.js} +1 -1
  43. package/dist/cli-8zh9nrew.js +78 -0
  44. package/dist/cli-9ttx00s3.js +137 -0
  45. package/dist/{cli-x6t50dmw.js → cli-9w8712tq.js} +620 -281
  46. package/dist/{cli-8476gtwf.js → cli-b6px1k1q.js} +1 -1
  47. package/dist/{cli-k2rw11py.js → cli-b91nz213.js} +5 -5
  48. package/dist/{cli-7c5tgqhf.js → cli-bg63qmsx.js} +10 -10
  49. package/dist/{cli-qps8je6j.js → cli-bkjdknnp.js} +54 -10
  50. package/dist/{cli-gn9y6fn7.js → cli-bnqncekd.js} +2 -2
  51. package/dist/{cli-s7zz734a.js → cli-br0924pw.js} +1 -1
  52. package/dist/{cli-h9yy18gy.js → cli-ctx0b85j.js} +5484 -5078
  53. package/dist/{cli-0vksaxvr.js → cli-dgs10ttj.js} +2 -2
  54. package/dist/cli-dqgnbnxs.js +132 -0
  55. package/dist/{cli-q6mfk1ej.js → cli-dzzh58sy.js} +2 -2
  56. package/dist/{cli-2znm3dzj.js → cli-eds5xnsz.js} +2 -2
  57. package/dist/{cli-c0xjnr8z.js → cli-f3jyzq4g.js} +2 -2
  58. package/dist/cli-f8x9drqr.js +84 -0
  59. package/dist/{cli-ztq5z4e1.js → cli-f9gz2vyj.js} +6 -6
  60. package/dist/{cli-bhsfbmk8.js → cli-fh97xn30.js} +93 -44
  61. package/dist/cli-fkef327x.js +103 -0
  62. package/dist/{cli-fsgttth8.js → cli-g0vv9dg4.js} +13 -13
  63. package/dist/{cli-kd56bmk4.js → cli-gabsjg8x.js} +3 -1
  64. package/dist/{cli-1m96dc36.js → cli-gfy38pvt.js} +3 -3
  65. package/dist/{cli-922z7gwm.js → cli-h9yqfzx9.js} +15 -11
  66. package/dist/{cli-5a7szzfh.js → cli-hnamkvnc.js} +2 -2
  67. package/dist/{cli-c3ng0mb4.js → cli-j7svy295.js} +71 -818
  68. package/dist/{cli-yss07azk.js → cli-jaw5v1sy.js} +3 -3
  69. package/dist/cli-jkw6ptfw.js +921 -0
  70. package/dist/{cli-s8p8hhty.js → cli-jm0hvmz2.js} +2 -2
  71. package/dist/{cli-knva3nmx.js → cli-jwampxxq.js} +8 -6
  72. package/dist/cli-kj0hyr43.js +51 -0
  73. package/dist/{cli-tnzebztn.js → cli-kpgcm7xy.js} +13 -1
  74. package/dist/{cli-9zmb7ptc.js → cli-kxx4k2jw.js} +8 -753
  75. package/dist/{cli-am1ptset.js → cli-m7c2380k.js} +208 -194
  76. package/dist/{cli-kw44j53p.js → cli-m7zvgt57.js} +45 -38
  77. package/dist/{cli-504akrp9.js → cli-meydjstb.js} +3 -3
  78. package/dist/{cli-54qr8mcd.js → cli-mhapr559.js} +4 -4
  79. package/dist/{cli-tf79ryyy.js → cli-mjw0yf82.js} +3 -3
  80. package/dist/{cli-rjvsf9qa.js → cli-mkwkwq81.js} +14 -11
  81. package/dist/{cli-n30e0hcp.js → cli-mna6pmfx.js} +2 -2
  82. package/dist/{cli-awwptga4.js → cli-mw620q3n.js} +1 -1
  83. package/dist/{cli-6wj7p986.js → cli-n3qe7tyr.js} +172 -168
  84. package/dist/{cli-4dpkjc2e.js → cli-nafvvsp8.js} +9 -9
  85. package/dist/{cli-sg27rk2t.js → cli-nbt14he0.js} +25 -19
  86. package/dist/{cli-7akn6ze9.js → cli-nh7x3133.js} +7 -28
  87. package/dist/{cli-zdaypkq9.js → cli-p4kckx1z.js} +285 -97
  88. package/dist/{cli-n5t077me.js → cli-pb2ay3sh.js} +10 -3
  89. package/dist/{cli-t4dv07kr.js → cli-psffsanb.js} +4 -3
  90. package/dist/{cli-mwwmka77.js → cli-pyjn0qhk.js} +2712 -268
  91. package/dist/{cli-emekyyhr.js → cli-q2d3e1k1.js} +1 -1
  92. package/dist/{cli-vqva1teb.js → cli-qe909n63.js} +2 -2
  93. package/dist/{cli-2d0cghfn.js → cli-qj39vrc6.js} +1 -1
  94. package/dist/{cli-tas6ckky.js → cli-rq5rpv6k.js} +2 -2
  95. package/dist/{cli-0agcv1v5.js → cli-rqx70rcz.js} +2 -2
  96. package/dist/{cli-kmemts3w.js → cli-sn650d7x.js} +39 -69
  97. package/dist/{cli-98rwmcyc.js → cli-snxhtehz.js} +3 -3
  98. package/dist/{cli-d829z3xc.js → cli-spfz393q.js} +6 -6
  99. package/dist/{cli-500c09j9.js → cli-t9ga4qmb.js} +14 -14
  100. package/dist/{cli-me0r8gzr.js → cli-td9tb872.js} +27 -25
  101. package/dist/cli-tvc4jag9.js +754 -0
  102. package/dist/{cli-6ek0hff4.js → cli-ty3gha1p.js} +4 -4
  103. package/dist/{cli-c71n3bxq.js → cli-v57d7fmm.js} +2 -2
  104. package/dist/{cli-j8cjdzan.js → cli-vs9vdpy0.js} +1 -1
  105. package/dist/cli-vt89089n.js +296 -0
  106. package/dist/{cli-pxwtcgcp.js → cli-vyff45ve.js} +2 -2
  107. package/dist/{cli-x3ex5bqf.js → cli-w16kwbzw.js} +1 -1
  108. package/dist/{cli-bj6qhgte.js → cli-w4n323t3.js} +197 -45
  109. package/dist/{cli-rqfvkx5t.js → cli-wn13hhdt.js} +13 -13
  110. package/dist/{cli-skmhsnqh.js → cli-x40a0w9j.js} +1 -1
  111. package/dist/{cli-zeaehgyd.js → cli-xag7btpe.js} +2 -2
  112. package/dist/{cli-k28wkapa.js → cli-xf1wn5ns.js} +2 -2
  113. package/dist/{cli-rh15cakt.js → cli-xwsm6xkr.js} +1 -1
  114. package/dist/{cli-dpsfwh7n.js → cli-y2ewxhth.js} +56 -31
  115. package/dist/{cli-vx421edw.js → cli-ysvspf5e.js} +9 -7
  116. package/dist/{cli-crpf163n.js → cli-zh0e5x7p.js} +16 -26
  117. package/dist/{cli-4e1hfbpq.js → cli-zr6qy15y.js} +24 -24
  118. package/dist/cli.js +33 -29
  119. package/dist/{codex-adapter-2brxx5ta.js → codex-adapter-n656pvb8.js} +9 -8
  120. package/dist/{codex-hook-c930c3ea.js → codex-hook-59atdwd8.js} +6 -6
  121. package/dist/{codex-login-cbrs1h5w.js → codex-login-a239g1ah.js} +1 -1
  122. package/dist/{codex-session-runner-y9anfj0r.js → codex-session-runner-p0fbv5y9.js} +10 -9
  123. package/dist/{commands-wn9q06qr.js → commands-gwea8z5p.js} +3 -3
  124. package/dist/{controller-fw608czd.js → controller-t67c3grh.js} +9 -6
  125. package/dist/{controllers-connect-63j5rdcm.js → controllers-connect-ks155r0h.js} +28 -25
  126. package/dist/{cursor-adapter-6mb9jme8.js → cursor-adapter-ygwrtmkv.js} +2 -2
  127. package/dist/{db-y4wfrzbm.js → db-kpmx06s9.js} +21 -13
  128. package/dist/{db-0m6v5tq4.js → db-rb2xqdb1.js} +3 -3
  129. package/dist/{devin-adapter-r0yx3gv8.js → devin-adapter-zp4tqq53.js} +1 -1
  130. package/dist/{dispatcher-9tq2zzdj.js → dispatcher-31sm0ej2.js} +21 -18
  131. package/dist/{docker-j75atvpt.js → docker-09tkkg0n.js} +47 -8
  132. package/dist/{dsh-adapter-t09sv4tq.js → dsh-adapter-qyxh0w31.js} +2 -2
  133. package/dist/{e2b-a7vzs2vj.js → e2b-3v1e745x.js} +6 -6
  134. package/dist/{e2b-7s9dscap.js → e2b-sm28k0k3.js} +6 -6
  135. package/dist/{easter-egg-3d-fbwvmwhe.js → easter-egg-3d-00wjscn6.js} +1 -1
  136. package/dist/{embedding-space-wh8de1t9.js → embedding-space-qhw4g68n.js} +6 -6
  137. package/dist/{embeddings-3hpbdtjr.js → embeddings-zdv9ke6x.js} +1 -1
  138. package/dist/{event-bus-tr6h3gv8.js → event-bus-xr83x566.js} +1 -1
  139. package/dist/{execute-4bdf8sdy.js → execute-zna8wwr7.js} +1 -1
  140. package/dist/{external-channel-ts2fwqh0.js → external-channel-1ac6t56s.js} +2 -2
  141. package/dist/fx-adapter-sk7n0fzc.js +19 -0
  142. package/dist/{getMachineId-bsd-nfgrzarv.js → getMachineId-bsd-637a7rbk.js} +3 -3
  143. package/dist/{getMachineId-darwin-wz886dsk.js → getMachineId-darwin-9vytrcnn.js} +3 -3
  144. package/dist/{getMachineId-linux-1nng3p1p.js → getMachineId-linux-mkzsvyyz.js} +3 -3
  145. package/dist/{getMachineId-unsupported-a0428vw9.js → getMachineId-unsupported-4cfs2n11.js} +3 -3
  146. package/dist/{getMachineId-win-h45922nq.js → getMachineId-win-154s3qma.js} +3 -3
  147. package/dist/{google-generative-ai-h7s3e9kk.js → google-generative-ai-maq6c9bf.js} +1 -1
  148. package/dist/{google-vertex-fhxaafzw.js → google-vertex-2jgsw2nb.js} +5 -5
  149. package/dist/grok-adapter-sjbcm5ew.js +19 -0
  150. package/dist/handlers-yzy0c87x.js +35 -0
  151. package/dist/{heartbeat-2ze5fzpc.js → heartbeat-2f6z4kdx.js} +24 -21
  152. package/dist/{hook-gaehe2w5.js → hook-8y0gvtp1.js} +14 -14
  153. package/dist/{hook-ca54yd4s.js → hook-w1skzaqc.js} +5 -5
  154. package/dist/{http-jfg8t2yk.js → http-wghxvpef.js} +2333 -589
  155. package/dist/{index-d6wkh8ar.js → index-0h6qd4p1.js} +34 -24
  156. package/dist/index-25pvya7q.js +40 -0
  157. package/dist/index-2t4859r5.js +35 -0
  158. package/dist/{index-enn321kd.js → index-42jq9yy3.js} +3 -3
  159. package/dist/{index-khe3gp0k.js → index-4k7m5dgj.js} +645 -370
  160. package/dist/index-620y7jzq.js +15 -0
  161. package/dist/{index-gjwaqaq8.js → index-8p0j4h4j.js} +506 -43
  162. package/dist/{index-3gv6sc4z.js → index-8zn8nxn5.js} +1 -1
  163. package/dist/{index-m5gx1xd6.js → index-9myfj74s.js} +40 -40
  164. package/dist/{index-3yvzbhxd.js → index-9zkchs9t.js} +336 -193
  165. package/dist/{index-0rvk3vd4.js → index-b5wgnm78.js} +47 -47
  166. package/dist/index-cxca2t8y.js +36 -0
  167. package/dist/{index-qwj6ntem.js → index-e3krvkh2.js} +4 -4
  168. package/dist/{index-hjhfk3ra.js → index-pe3d8jfy.js} +3 -3
  169. package/dist/index-rv89fvzf.js +572 -0
  170. package/dist/{index-csgrxedz.js → index-s71ez27v.js} +1 -1
  171. package/dist/{keepalive-k2a3qe73.js → keepalive-sh02349h.js} +4 -4
  172. package/dist/lead-gk4h5eg7.js +74 -0
  173. package/dist/{maintenance-gb5sd5nc.js → maintenance-yj0dcjja.js} +1 -1
  174. package/dist/{node-252anz2h.js → node-dqm4xgxw.js} +4 -4
  175. package/dist/{node-ray25snp.js → node-zd6shky9.js} +3 -3
  176. package/dist/{oauth-refresh-sweep-y7rm6bkb.js → oauth-refresh-sweep-d9xedk66.js} +3 -3
  177. package/dist/{onboard-jmc5qerv.js → onboard-dpgjn03r.js} +8 -8
  178. package/dist/{openai-codex-responses-k9gapdze.js → openai-codex-responses-bkcd8pjj.js} +9 -9
  179. package/dist/{openai-responses-4d5dx3c7.js → openai-responses-gbh0wfqe.js} +13 -13
  180. package/dist/{opencode-adapter-7eade9ev.js → opencode-adapter-2d31cpjc.js} +7 -6
  181. package/dist/{otel-impl-8j1xhxqd.js → otel-impl-1skarpfq.js} +110 -110
  182. package/dist/pending-bfmxtx0g.js +82 -0
  183. package/dist/{pi-mono-adapter-yqmaf32x.js → pi-mono-adapter-gvppnasy.js} +43 -16
  184. package/dist/{pricing-refresh-1nj722h6.js → pricing-refresh-c6b325mk.js} +2 -2
  185. package/dist/{rbac-roles-b1mtr6dr.js → rbac-roles-h80qbdbs.js} +3 -3
  186. package/dist/{rbac-roles-n1f3frk1.js → rbac-roles-zfcx68tx.js} +10 -3
  187. package/dist/{render-v2-1gfpd8rj.js → render-v2-nx20t3rb.js} +7 -4
  188. package/dist/{resume-w1s1eh5v.js → resume-5ep8agan.js} +11 -7
  189. package/dist/{runtime-84g5egsc.js → runtime-r3pj4mce.js} +1 -1
  190. package/dist/{session-access-y6z1txk4.js → session-access-n7p3m15b.js} +4 -4
  191. package/dist/{session-source-backfill-gxxwfh12.js → session-source-backfill-v8mt0zwn.js} +4 -4
  192. package/dist/{setup-r91gstyk.js → setup-z1psaqhe.js} +1 -1
  193. package/dist/thread-buffer-a1re2r9r.js +38 -0
  194. package/dist/{virtual-modules-cgnj6kme.js → virtual-modules-rrbjdpxn.js} +5 -5
  195. package/dist/{work-objects-qcxzg61c.js → work-objects-4aghh73z.js} +31 -23
  196. package/dist/worker-3dyyb8ev.js +74 -0
  197. package/dist/{worker-follow-up-y2d2h7km.js → worker-follow-up-166zmex1.js} +21 -18
  198. package/dist/{x-qhxq2ama.js → x-wg164ss9.js} +2 -2
  199. package/openapi.json +2561 -131
  200. package/package.json +15 -11
  201. package/plugin/commands/create-pr.md +1 -1
  202. package/plugin/pi-skills/create-pr/SKILL.md +1 -1
  203. package/src/apps/action-runner.ts +21 -1
  204. package/src/apps/catalog.generated.json +667 -18
  205. package/src/apps/page-validator.ts +341 -8
  206. package/src/assets/key.ts +6 -0
  207. package/src/be/agent-fs-user-keys.ts +186 -0
  208. package/src/be/audit-user.ts +27 -13
  209. package/src/be/automation-preflight.test.ts +14 -14
  210. package/src/be/automation-preflight.ts +24 -16
  211. package/src/be/boot-scrub-sweep.ts +143 -14
  212. package/src/be/caller-session-group.ts +86 -0
  213. package/src/be/checklist.ts +375 -0
  214. package/src/be/db/agents.ts +12 -1
  215. package/src/be/db/approvals.ts +26 -0
  216. package/src/be/db/model-profiles.ts +4 -1
  217. package/src/be/db/session-costs.ts +219 -0
  218. package/src/be/db/session-log-reasoning.ts +36 -0
  219. package/src/be/db/session-moves.ts +23 -0
  220. package/src/be/db/session-tree.ts +78 -19
  221. package/src/be/db/tasks/eligibility-scan.ts +14 -0
  222. package/src/be/db/tasks/read.ts +7 -3
  223. package/src/be/db/tasks/slack-fold.ts +116 -0
  224. package/src/be/db/tasks/write.ts +67 -1
  225. package/src/be/db-queries/mcp-servers.ts +13 -0
  226. package/src/be/db-queries/oauth.ts +6 -0
  227. package/src/be/db-queries/task-artifacts.ts +10 -8
  228. package/src/be/db.ts +242 -319
  229. package/src/be/extensions/assets.ts +17 -13
  230. package/src/be/import/config.ts +54 -0
  231. package/src/be/import/dir-source.ts +372 -0
  232. package/src/be/import/index.ts +149 -0
  233. package/src/be/import/pending.ts +71 -0
  234. package/src/be/import/schema.ts +137 -0
  235. package/src/be/import/seeders.ts +462 -0
  236. package/src/be/key-window-usage.ts +385 -0
  237. package/src/be/migrations/297_import_ownership.sql +34 -0
  238. package/src/be/migrations/301_favorites_key_type.sql +36 -0
  239. package/src/be/migrations/302_checklist_items.sql +23 -0
  240. package/src/be/migrations/303_task_ui_specs.sql +28 -0
  241. package/src/be/migrations/306_provider_account_telemetry.sql +1 -0
  242. package/src/be/migrations/307_session_cost_credential_attribution.sql +23 -0
  243. package/src/be/migrations/310_session_logs_reasoning.sql +12 -0
  244. package/src/be/multi-runtime.ts +8 -1
  245. package/src/be/rbac-roles.ts +8 -1
  246. package/src/be/runtime-pools/db.ts +3 -0
  247. package/src/be/runtime-pools/demand.ts +20 -2
  248. package/src/be/runtime-pools/reachability.ts +31 -0
  249. package/src/be/runtime-pools/routing.ts +8 -1
  250. package/src/be/runtime-pools/supervisor.ts +6 -7
  251. package/src/be/savings/read.ts +8 -6
  252. package/src/be/script-credential-broker.ts +2 -2
  253. package/src/be/scripts/typecheck.ts +4 -4
  254. package/src/be/seed/agent-fs-provision.ts +104 -19
  255. package/src/be/seed/index.ts +1 -1
  256. package/src/be/seed/registry.ts +27 -8
  257. package/src/be/seed/runner.ts +1 -1
  258. package/src/be/seed/schedules-seeder.ts +24 -6
  259. package/src/be/seed/seed-toggle.ts +32 -0
  260. package/src/be/seed/types.ts +6 -0
  261. package/src/be/seed-scripts/catalog/boot-triage.inline.ts +1 -0
  262. package/src/be/seed-scripts/catalog/boot-triage.ts +1 -0
  263. package/src/be/seed-scripts/catalog/dreaming-gather.ts +2 -2
  264. package/src/be/seed-scripts/catalog/wait-for-task.ts +5 -1
  265. package/src/be/seed-skills/index.ts +3 -0
  266. package/src/be/steering.ts +27 -4
  267. package/src/be/swarm-config-guard.ts +54 -1
  268. package/src/be/task-citations.ts +8 -5
  269. package/src/be/task-ui-spec.ts +158 -0
  270. package/src/commands/controller.ts +3 -0
  271. package/src/commands/credential-outcome-report.ts +13 -3
  272. package/src/commands/onboard/agent-fs-version.ts +1 -1
  273. package/src/commands/rate-limit-outcome.ts +6 -0
  274. package/src/commands/runner.ts +95 -55
  275. package/src/e2b/env.ts +2 -0
  276. package/src/extensions/catalog.generated.json +17 -0
  277. package/src/extensions/contract-types.generated.ts +1 -1
  278. package/src/github/app.ts +10 -1
  279. package/src/github/handlers.ts +6 -3
  280. package/src/github/reactions.ts +12 -14
  281. package/src/heartbeat/heartbeat.ts +14 -4
  282. package/src/http/agents.ts +19 -10
  283. package/src/http/all-routes.ts +2 -0
  284. package/src/http/api-keys.ts +258 -30
  285. package/src/http/approval-requests.ts +24 -4
  286. package/src/http/apps.ts +69 -5
  287. package/src/http/checklist.ts +176 -0
  288. package/src/http/db-query-bounded.ts +256 -11
  289. package/src/http/db-query-shared.ts +9 -0
  290. package/src/http/favorites.ts +14 -2
  291. package/src/http/fs.ts +346 -1
  292. package/src/http/index.ts +29 -1
  293. package/src/http/kv.ts +13 -0
  294. package/src/http/mcp-oauth.ts +1 -1
  295. package/src/http/mcp-servers.ts +15 -2
  296. package/src/http/onboarding.ts +2 -9
  297. package/src/http/poll.ts +45 -0
  298. package/src/http/script-connections.ts +1 -0
  299. package/src/http/session-data.ts +74 -23
  300. package/src/http/sessions.ts +23 -2
  301. package/src/http/slack-events.ts +101 -0
  302. package/src/http/status.ts +25 -7
  303. package/src/http/task-requester.ts +46 -0
  304. package/src/http/tasks.ts +169 -42
  305. package/src/http/users.ts +14 -0
  306. package/src/http/webhooks.ts +15 -0
  307. package/src/integrations/cards/index.ts +151 -0
  308. package/src/integrations/chat-sdk/outbound.ts +39 -13
  309. package/src/integrations/chat-sdk/relay.ts +87 -0
  310. package/src/integrations/chat-sdk/runtime.ts +7 -1
  311. package/src/integrations/chat-sdk/status.ts +17 -0
  312. package/src/integrations/chat-sdk/telegram-api.ts +6 -1
  313. package/src/jira/outbound.ts +5 -3
  314. package/src/kv-reserved-namespaces.ts +17 -2
  315. package/src/linear/outbound.ts +5 -1
  316. package/src/oauth/presets.ts +29 -2
  317. package/src/prompts/base-prompt.ts +25 -4
  318. package/src/prompts/session-templates.ts +102 -8
  319. package/src/providers/acp-targets.ts +1 -1
  320. package/src/providers/amp-adapter.ts +1 -1
  321. package/src/providers/claude-adapter.ts +27 -4
  322. package/src/providers/claude-flag-settings.ts +39 -1
  323. package/src/providers/claude-managed-adapter.ts +5 -1
  324. package/src/providers/codex-adapter.ts +86 -4
  325. package/src/providers/codex-app-server.ts +11 -16
  326. package/src/providers/codex-oauth/auth-json.ts +1 -0
  327. package/src/providers/opencode-adapter.ts +7 -19
  328. package/src/providers/pi-mono-adapter.ts +35 -2
  329. package/src/providers/pricing-sources.md +32 -0
  330. package/src/providers/runtime-dependencies.ts +158 -0
  331. package/src/providers/types.ts +11 -0
  332. package/src/rbac/legacy-policy.ts +2 -0
  333. package/src/rbac/permissions.ts +10 -1
  334. package/src/runtime-providers/docker.ts +65 -1
  335. package/src/scheduler/deferred-task-waits.ts +18 -5
  336. package/src/scripts-runtime/credential-broker/default-bindings.ts +19 -11
  337. package/src/scripts-runtime/credential-broker/index.ts +1 -1
  338. package/src/scripts-runtime/egress-secrets.ts +2 -2
  339. package/src/scripts-runtime/swarm-sdk.ts +3 -2
  340. package/src/scripts-runtime/types/stdlib.d.ts +11 -4
  341. package/src/scripts-runtime/types/swarm-extension.d.ts +9 -9
  342. package/src/scripts-runtime/types/swarm-sdk.d.ts +11 -4
  343. package/src/server.ts +4 -4
  344. package/src/slack/actions.ts +56 -0
  345. package/src/slack/app.ts +107 -59
  346. package/src/slack/assistant.ts +33 -7
  347. package/src/slack/handlers.ts +6 -4
  348. package/src/slack/http-receiver.ts +284 -0
  349. package/src/slack/inbound-dispatch.ts +43 -7
  350. package/src/slack/inbound-files.ts +35 -14
  351. package/src/slack/message-text.ts +47 -4
  352. package/src/slack/render-v2.ts +109 -24
  353. package/src/slack/responses.ts +3 -2
  354. package/src/slack/socket-ack.ts +17 -10
  355. package/src/slack/steering.ts +5 -0
  356. package/src/slack/thread-buffer-store.ts +58 -0
  357. package/src/slack/thread-buffer.ts +341 -57
  358. package/src/slack/work-objects.ts +4 -1
  359. package/src/tasks/context-key.ts +24 -0
  360. package/src/tasks/errors.ts +5 -0
  361. package/src/tasks/sibling-awareness.ts +13 -1
  362. package/src/tests/acp-adapter.test.ts +4 -6
  363. package/src/tests/agent-fs-live-url.test.ts +15 -0
  364. package/src/tests/agent-fs-provision-seeder.test.ts +140 -0
  365. package/src/tests/agent-fs-user-keys.test.ts +483 -0
  366. package/src/tests/agentfs-proxy.test.ts +8 -8
  367. package/src/tests/api-key-tracking.test.ts +0 -72
  368. package/src/tests/api-keys-status-model-limits.test.ts +93 -1
  369. package/src/tests/api-keys-validation.test.ts +42 -0
  370. package/src/tests/approval-card-resolution.test.ts +402 -0
  371. package/src/tests/approval-requests-notifications.test.ts +12 -2
  372. package/src/tests/approval-respond-auth.test.ts +28 -0
  373. package/src/tests/apps-action-parent-task.test.ts +140 -0
  374. package/src/tests/apps-catalog-additions.test.ts +315 -0
  375. package/src/tests/apps-catalog-files.test.ts +114 -0
  376. package/src/tests/apps-catalog-hitl.test.ts +117 -0
  377. package/src/tests/apps-catalog-inputs.test.ts +86 -0
  378. package/src/tests/apps-catalog-page-frame.test.ts +49 -0
  379. package/src/tests/apps-catalog-table.test.ts +47 -0
  380. package/src/tests/apps-chart-shell.test.ts +1 -1
  381. package/src/tests/apps-element-assembly.test.ts +52 -3
  382. package/src/tests/apps-session-thread.test.ts +261 -0
  383. package/src/tests/asset-key-invariants.test.ts +14 -0
  384. package/src/tests/base-prompt.test.ts +213 -23
  385. package/src/tests/boot-scrub-sweep.test.ts +172 -0
  386. package/src/tests/caller-session-group.test.ts +199 -0
  387. package/src/tests/cards.test.ts +169 -0
  388. package/src/tests/chat-sdk-relay.test.ts +149 -1
  389. package/src/tests/chat-sdk-status-route.test.ts +16 -3
  390. package/src/tests/chat-sdk-telegram-token.test.ts +76 -0
  391. package/src/tests/chat-sdk-tools.test.ts +147 -0
  392. package/src/tests/checklist-nudge.test.ts +208 -0
  393. package/src/tests/checklist.test.ts +686 -0
  394. package/src/tests/claude-adapter-binary.test.ts +67 -6
  395. package/src/tests/claude-flag-settings.test.ts +29 -0
  396. package/src/tests/claude-sdk-lifecycle.test.ts +5 -0
  397. package/src/tests/codex-adapter.test.ts +340 -2
  398. package/src/tests/codex-app-server.test.ts +32 -0
  399. package/src/tests/codex-oauth.test.ts +3 -1
  400. package/src/tests/codex-rate-limits.test.ts +384 -0
  401. package/src/tests/comb-config-guard.test.ts +21 -0
  402. package/src/tests/comb-default.test.ts +59 -97
  403. package/src/tests/comb-links.test.ts +86 -16
  404. package/src/tests/comb-status.test.ts +24 -27
  405. package/src/tests/create-page-tool.test.ts +101 -1
  406. package/src/tests/create-schedule-key.test.ts +105 -0
  407. package/src/tests/credential-broker.test.ts +2 -2
  408. package/src/tests/credential-outcome-report.test.ts +20 -0
  409. package/src/tests/db-query.test.ts +87 -1
  410. package/src/tests/db-task-read-contract.test.ts +4 -0
  411. package/src/tests/db-task-write-contract.test.ts +6 -1
  412. package/src/tests/deferred-task-wake.test.ts +63 -1
  413. package/src/tests/docker-isolation-config-guard.test.ts +29 -0
  414. package/src/tests/docs-index-footprint.test.js +11 -3
  415. package/src/tests/e2e-visuals-comment.test.ts +82 -0
  416. package/src/tests/e2e-visuals-verify-pr.test.ts +138 -0
  417. package/src/tests/entrypoint-github-enterprise.test.ts +158 -0
  418. package/src/tests/extensions-assets.test.ts +7 -3
  419. package/src/tests/extensions-catalog.test.ts +1 -0
  420. package/src/tests/extensions-example-sql-admin-only.test.ts +201 -0
  421. package/src/tests/extensions-pre-task.test.ts +3 -3
  422. package/src/tests/extensions-steering.test.ts +14 -2
  423. package/src/tests/favorites-agent-fs-path.test.ts +124 -0
  424. package/src/tests/fetch-resolved-env.test.ts +68 -0
  425. package/src/tests/fixtures/import-package.ts +32 -0
  426. package/src/tests/fixtures/runner-missing-dependency.ts +129 -0
  427. package/src/tests/fixtures/ui-spec-slack/deploys.json +121 -0
  428. package/src/tests/fixtures/ui-spec-slack/incident.json +183 -0
  429. package/src/tests/fixtures/ui-spec-slack/three-charts-stale.json +196 -0
  430. package/src/tests/fixtures/ui-spec-slack/video-rejected-by-slack.json +183 -0
  431. package/src/tests/fixtures/ui-spec-slack/video.json +446 -0
  432. package/src/tests/fs-routes.test.ts +505 -2
  433. package/src/tests/github-ghes-mock.test.ts +196 -0
  434. package/src/tests/github-host.test.ts +285 -0
  435. package/src/tests/gitleaks-download-retry.test.ts +85 -0
  436. package/src/tests/heartbeat-supersede-resume.test.ts +73 -0
  437. package/src/tests/heartbeat.test.ts +56 -0
  438. package/src/tests/human-thread-routing.test.ts +187 -0
  439. package/src/tests/import-config.test.ts +209 -0
  440. package/src/tests/import.test.ts +464 -0
  441. package/src/tests/invites-http.test.ts +144 -1
  442. package/src/tests/jira-outbound-sync.test.ts +33 -1
  443. package/src/tests/key-window-usage.test.ts +831 -0
  444. package/src/tests/kv-http.test.ts +11 -0
  445. package/src/tests/linear-outbound-sync.test.ts +30 -1
  446. package/src/tests/literal-matcher.test.ts +58 -0
  447. package/src/tests/mcp-oauth-manual-client.test.ts +1 -1
  448. package/src/tests/oauth-presets.test.ts +12 -0
  449. package/src/tests/pi-mono-adapter.test.ts +79 -0
  450. package/src/tests/pool-affinity.test.ts +50 -0
  451. package/src/tests/preload-env.test.ts +2 -0
  452. package/src/tests/preload.ts +3 -1
  453. package/src/tests/prompt-template-session.test.ts +53 -5
  454. package/src/tests/provider-quota-persistence.test.ts +362 -0
  455. package/src/tests/provider-registration.test.ts +2 -55
  456. package/src/tests/provider-runtime-dependencies.test.ts +212 -0
  457. package/src/tests/rate-limit-event.test.ts +22 -0
  458. package/src/tests/rbac-admission.test.ts +19 -0
  459. package/src/tests/rbac-charact-misc-tools.test.ts +31 -0
  460. package/src/tests/rbac-engine.test.ts +2 -0
  461. package/src/tests/rbac-roles.test.ts +2 -0
  462. package/src/tests/reasoning-events.test.ts +164 -0
  463. package/src/tests/routing-affinity-inventory.test.ts +22 -0
  464. package/src/tests/runner-missing-dependency.test.ts +61 -0
  465. package/src/tests/runtime-pool-reachability.test.ts +135 -1
  466. package/src/tests/runtime-pool-routing.test.ts +52 -0
  467. package/src/tests/runtime-providers-docker.test.ts +91 -0
  468. package/src/tests/runtime-stale-threshold.test.ts +40 -0
  469. package/src/tests/savings-fleet-slices.test.ts +122 -0
  470. package/src/tests/savings-read.test.ts +41 -0
  471. package/src/tests/savings-scripts.test.ts +9 -3
  472. package/src/tests/script-connections.test.ts +7 -0
  473. package/src/tests/script-executor-conformance.test.ts +41 -4
  474. package/src/tests/secret-canary-sweep.test.ts +41 -5
  475. package/src/tests/secret-scrub-gate.test.ts +257 -0
  476. package/src/tests/seed-registry.test.ts +142 -9
  477. package/src/tests/seed-scripts.test.ts +23 -0
  478. package/src/tests/session-cost-attribution.test.ts +748 -0
  479. package/src/tests/session-costs.test.ts +14 -15
  480. package/src/tests/session-logs.test.ts +83 -0
  481. package/src/tests/session-source-keys.test.ts +42 -1
  482. package/src/tests/sessions-detail-batch.test.ts +7 -0
  483. package/src/tests/sessions-move.test.ts +70 -0
  484. package/src/tests/sessions-tree.test.ts +98 -0
  485. package/src/tests/sessions.test.ts +69 -0
  486. package/src/tests/slack-config.test.ts +4 -18
  487. package/src/tests/slack-http-receiver.test.ts +472 -0
  488. package/src/tests/slack-inbound-logging.test.ts +64 -0
  489. package/src/tests/slack-leave-thread.test.ts +1 -1
  490. package/src/tests/slack-message-text.test.ts +104 -0
  491. package/src/tests/slack-mode-lifecycle.test.ts +6 -4
  492. package/src/tests/slack-render-v2.test.ts +405 -0
  493. package/src/tests/slack-skip-reaction.test.ts +2 -2
  494. package/src/tests/slack-start-reload-race.test.ts +67 -0
  495. package/src/tests/slack-steering.test.ts +22 -10
  496. package/src/tests/slack-thread-buffer-context.test.ts +1 -1
  497. package/src/tests/slack-thread-buffer-fold.test.ts +417 -0
  498. package/src/tests/slack-thread-buffer-restore.test.ts +198 -0
  499. package/src/tests/slack-thread-buffer-startup-restore.test.ts +86 -0
  500. package/src/tests/slack-thread-buffer.test.ts +34 -34
  501. package/src/tests/slack-thread-participants.test.ts +23 -5
  502. package/src/tests/slack-tool-blocks.test.ts +167 -0
  503. package/src/tests/status.test.ts +32 -6
  504. package/src/tests/steering-core.test.ts +13 -0
  505. package/src/tests/steering-enabled.test.ts +7 -1
  506. package/src/tests/steering-promotion.test.ts +24 -0
  507. package/src/tests/subscription-plans.test.ts +20 -1
  508. package/src/tests/swarm-config-reserved-keys.test.ts +17 -0
  509. package/src/tests/system-one-hosts-ui-mirror.test.ts +67 -0
  510. package/src/tests/task-artifacts.test.ts +50 -0
  511. package/src/tests/task-session-prompts.test.ts +95 -1
  512. package/src/tests/task-ui-action-route.test.ts +191 -0
  513. package/src/tests/task-ui-actions.test.ts +195 -0
  514. package/src/tests/task-ui-spec-fallback.test.ts +65 -0
  515. package/src/tests/task-ui-spec.test.ts +368 -0
  516. package/src/tests/workflow-agent-task-retry.test.ts +34 -1
  517. package/src/tests/workflow-system-one-extraction.test.ts +149 -1
  518. package/src/tools/chat-post.ts +19 -4
  519. package/src/tools/chat-reply.ts +20 -4
  520. package/src/tools/create-page.ts +21 -4
  521. package/src/tools/defer-task.ts +1 -1
  522. package/src/tools/get-swarm.ts +18 -2
  523. package/src/tools/join-swarm.ts +2 -1
  524. package/src/tools/kv/kv-write-auth.ts +17 -1
  525. package/src/tools/schedules/create-schedule.ts +22 -4
  526. package/src/tools/slack-post.ts +40 -7
  527. package/src/tools/slack-reply.ts +50 -14
  528. package/src/tools/store-progress.ts +69 -3
  529. package/src/types.ts +50 -4
  530. package/src/ui-spec/actions.ts +86 -0
  531. package/src/ui-spec/fallback.ts +19 -0
  532. package/src/ui-spec/slack.ts +17 -0
  533. package/src/ui-spec/validate.ts +169 -0
  534. package/src/utils/codex-rate-limits.ts +159 -0
  535. package/src/utils/constants.ts +60 -138
  536. package/src/utils/credentials.ts +2 -0
  537. package/src/utils/error-tracker.ts +19 -0
  538. package/src/utils/github-host.ts +217 -0
  539. package/src/utils/github-pull-request.ts +8 -5
  540. package/src/utils/literal-matcher.ts +118 -0
  541. package/src/utils/provider-account-telemetry.ts +331 -0
  542. package/src/utils/reasoning-events.ts +107 -0
  543. package/src/utils/secret-scrubber.ts +331 -25
  544. package/src/utils/subscription-plans.ts +11 -59
  545. package/src/utils/task-attachment-links.ts +9 -12
  546. package/src/utils/task-ui-spec.ts +67 -0
  547. package/src/vcs/index.ts +3 -0
  548. package/src/workflows/approval-notifications.ts +188 -12
  549. package/src/workflows/executors/system-one-extraction.ts +14 -7
  550. package/src/workflows/executors/system-one-providers.ts +22 -1
  551. package/src/workflows/task-step-routing.ts +8 -3
  552. package/templates/community/open-prompt-showreel/PLAYBOOK.md +1 -1
  553. package/templates/community/open-prompt-showreel/skills/open-prompt-showreel/SKILL.md +1 -1
  554. package/templates/extensions/README.md +1 -0
  555. package/templates/extensions/sql-admin-only/README.md +20 -0
  556. package/templates/extensions/sql-admin-only/hooks.ts +100 -0
  557. package/templates/extensions/sql-admin-only/manifest.json +8 -0
  558. package/templates/import/manifest.schema.json +136 -0
  559. package/templates/import/sources.schema.json +44 -0
  560. package/templates/skills/agent-browser/SKILL.md +1 -1
  561. package/templates/skills/agent-browser/content.md +1 -1
  562. package/templates/skills/apps/SKILL.md +151 -14
  563. package/templates/skills/apps/content.md +151 -14
  564. package/templates/skills/asset-namespaces/content.md +2 -1
  565. package/templates/skills/chat-sdk/content.md +17 -0
  566. package/templates/skills/db-query-guidance/content.md +2 -1
  567. package/templates/skills/scheduling/content.md +27 -0
  568. package/templates/skills/slack-interaction/content.md +12 -2
  569. package/templates/skills/swarm-docs/content.md +1 -0
  570. package/templates/skills/swarm-extensions/config.json +1 -1
  571. package/templates/skills/swarm-extensions/content.md +33 -23
  572. package/templates/skills/swarm-scripts/SKILL.md +13 -0
  573. package/templates/skills/swarm-scripts/content.md +13 -0
  574. package/templates/skills/ui-spec/config.json +14 -0
  575. package/templates/skills/ui-spec/content.md +127 -0
  576. package/templates/skills/work-on-task/SKILL.md +1 -1
  577. package/templates/skills/work-on-task/content.md +1 -1
  578. package/templates/skills/workflow-iterate/content.md +4 -7
  579. package/templates/workflows/dreaming/content.md +2 -2
  580. package/dist/acp-adapter-xq6s2z6t.js +0 -14
  581. package/dist/claude-adapter-r33pqnzx.js +0 -24
  582. package/dist/cli-dns0y538.js +0 -194
  583. package/dist/cli-m2z8jagn.js +0 -12078
  584. package/dist/fx-adapter-1rnxnf56.js +0 -17
  585. package/dist/grok-adapter-efhmf1r8.js +0 -17
  586. package/dist/handlers-anrr3py9.js +0 -32
  587. package/dist/index-2skqtd76.js +0 -12795
  588. package/dist/index-8w2aznds.js +0 -33
  589. package/dist/index-qnjvr362.js +0 -37
  590. package/dist/index-yzxd3sn9.js +0 -32
  591. package/dist/lead-zhxqbfdv.js +0 -69
  592. package/dist/worker-7j2907g6.js +0 -69
  593. package/src/tests/entrypoint-acp-target-binary.test.ts +0 -439
  594. package/dist/{cli-4caa1x7d.js → cli-tsa40663.js} +4 -4
  595. package/dist/{mistral-conversations-a45tx39a.js → mistral-conversations-0c30em7t.js} +4 -4
  596. package/dist/{openai-completions-xd579js7.js → openai-completions-f3n69rep.js} +18 -18
  597. package/dist/{pi-messages-hjbv8v10.js → pi-messages-zebyt7gb.js} +5 -5
@@ -1,7 +1,35 @@
1
1
  import {
2
2
  bedrockProviderModule
3
- } from "./cli-fsgttth8.js";
3
+ } from "./cli-g0vv9dg4.js";
4
4
  import {
5
+ auditAssetKeys,
6
+ init_asset_key_audit,
7
+ CredentialBindingSchema,
8
+ placeholderForConfigKey,
9
+ isPrivateAddress,
10
+ assertUrlSafe,
11
+ init_egress_guard,
12
+ init_credential_broker,
13
+ encryptSecret,
14
+ decryptSecret,
15
+ getEncryptionKey,
16
+ init_crypto,
17
+ withLoopPath,
18
+ startEventLoopLagProbe,
19
+ stopEventLoopLagProbe,
20
+ init_event_loop_lag,
21
+ DbTransactionDeadlineError,
22
+ init_db_client,
23
+ getPromptTemplateDefaultDrift,
24
+ init_default_drift,
25
+ init_templates2,
26
+ init_templates3,
27
+ getDb2,
28
+ closeDb2,
29
+ getDbClient2,
30
+ init_runtime2,
31
+ SessionCostConflictError2,
32
+ insertSessionCost2,
5
33
  chatThreadOfContextKey,
6
34
  agentContextKey,
7
35
  pageContextKey,
@@ -10,6 +38,9 @@ import {
10
38
  SOURCE_GROUPS_READ_ONLY,
11
39
  sourceMoveError,
12
40
  init_source_key,
41
+ TaskCreationBlockedError,
42
+ TaskRoutingAuthorizationError,
43
+ init_errors2,
13
44
  init_catalog,
14
45
  catalog_default,
15
46
  COMPANY_TEAM_SIZES,
@@ -41,32 +72,6 @@ import {
41
72
  telemetry,
42
73
  emitIntegrationConnected,
43
74
  init_telemetry,
44
- auditAssetKeys,
45
- init_asset_key_audit,
46
- CredentialBindingSchema,
47
- placeholderForConfigKey,
48
- isPrivateAddress,
49
- assertUrlSafe,
50
- init_egress_guard,
51
- init_credential_broker,
52
- encryptSecret,
53
- decryptSecret,
54
- getEncryptionKey,
55
- init_crypto,
56
- withLoopPath,
57
- startEventLoopLagProbe,
58
- stopEventLoopLagProbe,
59
- init_event_loop_lag,
60
- DbTransactionDeadlineError,
61
- init_db_client,
62
- getPromptTemplateDefaultDrift,
63
- init_default_drift,
64
- init_templates2,
65
- init_templates3,
66
- getDb2,
67
- closeDb2,
68
- getDbClient2,
69
- init_runtime2,
70
75
  isRbacEnabled,
71
76
  decideToolAdmission,
72
77
  LEGACY_RULES,
@@ -139,11 +144,68 @@ import {
139
144
  hasCapacity2,
140
145
  updateAgentStatusFromCapacity2,
141
146
  getAgentDailyTaskCounts2,
142
- listApprovalRequestSummaries2,
143
- getPendingApprovalVoteState2,
144
- recordApprovalVotes2,
145
- getPendingApprovalsForTasks2,
146
- computeContentHash2,
147
+ getWorkflowRunSummary,
148
+ getWorkflowRunStepsSlimByRunId,
149
+ WORKFLOW_RUN_TREE_MAX_DEPTH,
150
+ WorkflowRunTreeError,
151
+ getWorkflowRunTree,
152
+ getWorkflowRunParent,
153
+ init_workflow_runs,
154
+ OpenAI2,
155
+ init_openai2,
156
+ CANDIDATE_SET_MULTIPLIER,
157
+ EMBEDDING_DIMENSIONS,
158
+ init_constants2,
159
+ MEMORY_KEY_MAX_LENGTH,
160
+ init_key_paths,
161
+ rerank,
162
+ init_reranker,
163
+ searchMemoryCandidates,
164
+ init_search_candidates,
165
+ getEmbeddingProvider2,
166
+ resetEmbeddingProvider2,
167
+ getMemoryStore2,
168
+ init_memory,
169
+ searchScripts2,
170
+ init_embeddings,
171
+ upsertScriptByName,
172
+ getScript,
173
+ getScriptById,
174
+ listScripts,
175
+ listScriptVersions,
176
+ deleteScript,
177
+ touchScratchScriptLastUsed,
178
+ restoreScratchScriptLastUsedIfUnchanged,
179
+ createScriptApi,
180
+ listScriptApisForScript,
181
+ getScriptApiById,
182
+ getScriptApiSecret,
183
+ updateScriptApi,
184
+ rotateScriptApiSecret,
185
+ deleteScriptApi,
186
+ recordScriptApiUsage,
187
+ init_db3,
188
+ loadSecretRegistry,
189
+ init_secret_registry,
190
+ getDefaultAuthorizationIdForProvider,
191
+ getOAuthApp,
192
+ getOAuthAppById,
193
+ createOAuthApp,
194
+ updateOAuthAppById,
195
+ listAuthorizationsForApp,
196
+ getAuthorizationById,
197
+ upsertAuthorization,
198
+ updateAuthorizationIdentity,
199
+ deleteAuthorizationById,
200
+ deleteAuthorizationsForApp,
201
+ consumeOAuthPending,
202
+ gcOAuthPending,
203
+ hasOAuthTokens,
204
+ getOAuthTokens,
205
+ deleteOAuthTokens,
206
+ acquireOAuthRefreshLock,
207
+ releaseOAuthRefreshLock,
208
+ init_oauth,
147
209
  normalizeVcsRepo,
148
210
  vcsRepoUrlMatches,
149
211
  init_vcs_repo_match,
@@ -203,13 +265,29 @@ import {
203
265
  taskProfileError,
204
266
  scheduleProfileUpdate,
205
267
  init_model_profiles,
268
+ refreshActiveSessionOnActivity2,
269
+ STEERING_MOVED_ERROR,
270
+ SteeringRequestError,
271
+ isSteeringEnabled,
272
+ getTaskSteeringFields,
273
+ getTaskSteeringFieldsForTasks,
274
+ markSteeringUndeliverable,
275
+ requestSteering,
276
+ init_steering2,
277
+ listApprovalRequestSummaries2,
278
+ getPendingApprovalVoteState2,
279
+ recordApprovalVotes2,
280
+ getPendingApprovalsForTasks2,
281
+ computeContentHash2,
206
282
  AssetKeyMovesBlockedError2,
207
283
  assertAssetKeyMovesAllowed2,
208
284
  moveSessionChains,
285
+ moveKeyFavorites,
209
286
  listPrefixRoots,
210
287
  listSharedPrefixRoots,
211
288
  init_session_moves,
212
289
  getSessionGroupKey,
290
+ sessionSummaryQuery,
213
291
  getSessionReadState,
214
292
  getSessionTree,
215
293
  triageSessionList,
@@ -224,81 +302,12 @@ import {
224
302
  init_channels,
225
303
  publishWorkerNudge,
226
304
  init_worker_nudges,
227
- getDefaultAuthorizationIdForProvider,
228
- getOAuthApp,
229
- getOAuthAppById,
230
- createOAuthApp,
231
- updateOAuthAppById,
232
- listAuthorizationsForApp,
233
- getAuthorizationById,
234
- upsertAuthorization,
235
- updateAuthorizationIdentity,
236
- deleteAuthorizationById,
237
- deleteAuthorizationsForApp,
238
- consumeOAuthPending,
239
- gcOAuthPending,
240
- getOAuthTokens,
241
- deleteOAuthTokens,
242
- acquireOAuthRefreshLock,
243
- releaseOAuthRefreshLock,
244
- init_oauth,
245
- OpenAI2,
246
- init_openai2,
247
- CANDIDATE_SET_MULTIPLIER,
248
- EMBEDDING_DIMENSIONS,
249
- init_constants2,
250
- MEMORY_KEY_MAX_LENGTH,
251
- init_key_paths,
252
- rerank,
253
- init_reranker,
254
- searchMemoryCandidates,
255
- init_search_candidates,
256
- getEmbeddingProvider2,
257
- resetEmbeddingProvider2,
258
- getMemoryStore2,
259
- init_memory,
260
- searchScripts2,
261
- init_embeddings,
262
- upsertScriptByName,
263
- getScript,
264
- getScriptById,
265
- listScripts,
266
- listScriptVersions,
267
- deleteScript,
268
- touchScratchScriptLastUsed,
269
- restoreScratchScriptLastUsedIfUnchanged,
270
- createScriptApi,
271
- listScriptApisForScript,
272
- getScriptApiById,
273
- getScriptApiSecret,
274
- updateScriptApi,
275
- rotateScriptApiSecret,
276
- deleteScriptApi,
277
- recordScriptApiUsage,
278
- init_db3,
279
- loadSecretRegistry,
280
- init_secret_registry,
281
- getWorkflowRunSummary,
282
- getWorkflowRunStepsSlimByRunId,
283
- WORKFLOW_RUN_TREE_MAX_DEPTH,
284
- WorkflowRunTreeError,
285
- getWorkflowRunTree,
286
- getWorkflowRunParent,
287
- init_workflow_runs,
288
- refreshActiveSessionOnActivity2,
289
- STEERING_MOVED_ERROR,
290
- SteeringRequestError,
291
- isSteeringEnabled,
292
- getTaskSteeringFields,
293
- getTaskSteeringFieldsForTasks,
294
- markSteeringUndeliverable,
295
- requestSteering,
296
- init_steering2,
297
305
  getPendingTaskForAgent2,
298
306
  startTask2,
299
307
  updateTaskClaudeSessionId2,
300
308
  recordTaskProviderIfUnset2,
301
309
  updateTaskTitle2,
310
+ updateTaskTags2,
302
311
  setTaskTitleIfUnset2,
303
312
  completeTask2,
304
313
  failTask2,
@@ -354,7 +363,6 @@ import {
354
363
  claimMentions2,
355
364
  createSessionLogs2,
356
365
  getSessionLogsByTaskId2,
357
- createSessionCost2,
358
366
  getSessionCostsByTaskId2,
359
367
  getSessionCostsByAgentId2,
360
368
  getAllSessionCosts2,
@@ -530,7 +538,7 @@ import {
530
538
  countScriptRunJournalSteps2,
531
539
  countScriptRunJournalAgentTaskSteps2,
532
540
  init_db4
533
- } from "./cli-h9yy18gy.js";
541
+ } from "./cli-ctx0b85j.js";
534
542
  import {
535
543
  PRIMARY_ROLE_NAMES2,
536
544
  OperatorGrantedTargetError2,
@@ -544,17 +552,19 @@ import {
544
552
  assertNotLastAdmin2,
545
553
  setUserRoles2,
546
554
  init_rbac_roles
547
- } from "./cli-n5t077me.js";
548
- import"./cli-k2rw11py.js";
555
+ } from "./cli-pb2ay3sh.js";
556
+ import"./cli-b91nz213.js";
549
557
  import {
550
558
  requestModelCatalogRefresh2,
551
559
  init_pricing_refresh
552
- } from "./cli-0vksaxvr.js";
560
+ } from "./cli-dgs10ttj.js";
553
561
  import {
554
562
  workflowEventBus2,
555
563
  init_event_bus
556
- } from "./cli-emekyyhr.js";
557
- import"./cli-zeaehgyd.js";
564
+ } from "./cli-q2d3e1k1.js";
565
+ import"./cli-xag7btpe.js";
566
+ import"./cli-9w8712tq.js";
567
+ import"./cli-47hz21se.js";
558
568
  import {
559
569
  require_dist4,
560
570
  getSlackConnectionState,
@@ -575,6 +585,10 @@ import {
575
585
  getTaskCitations,
576
586
  getTaskCitationsForTasks,
577
587
  init_task_citations2,
588
+ TaskUiSpecSchema,
589
+ getTaskUiSpec,
590
+ getTaskUiSpecsForTasks,
591
+ init_task_ui_spec,
578
592
  initialize,
579
593
  ensure,
580
594
  init_business_use,
@@ -582,15 +596,44 @@ import {
582
596
  slackErrorCode2,
583
597
  init_render_v2,
584
598
  getSlackApp2,
599
+ getSlackHttpReceiver2,
585
600
  startSlackApp2,
586
601
  stopSlackApp2,
587
602
  init_app3
588
- } from "./cli-mwwmka77.js";
603
+ } from "./cli-pyjn0qhk.js";
604
+ import {
605
+ AGENT_MAX_TASKS_CONFIG_KEY,
606
+ reconcileAgentMaxTasksPolicy,
607
+ resetAgentMaxTasksMirror,
608
+ upsertSwarmConfigWithPolicyMirror,
609
+ runtimeStaleThresholdMinutes,
610
+ upsertRuntimeInstance,
611
+ getRuntimeInstanceById,
612
+ touchRuntimeInstance,
613
+ listRuntimeInstancesForAgent,
614
+ setRuntimeCredentialReady,
615
+ reconcileAgentStatusFromRuntimes,
616
+ listRuntimeInstancesForPool,
617
+ init_multi_runtime,
618
+ ConfigQuestionSettingsSchema,
619
+ ConfigStateSchema,
620
+ readConfigState,
621
+ normalizeApprovalQuestions,
622
+ isConfigQuestion,
623
+ parseConfigAnswer,
624
+ skippedConfigResult,
625
+ keptConfigResult,
626
+ applyConfigAnswer,
627
+ init_approval_config_question,
628
+ dispatchApprovalNotifications2,
629
+ createApprovalFollowUpTask2,
630
+ init_approval_notifications
631
+ } from "./cli-jkw6ptfw.js";
589
632
  import {
590
633
  retryFailedRun2,
591
634
  cancelWorkflowRun2,
592
635
  init_resume
593
- } from "./cli-sdvcrq5x.js";
636
+ } from "./cli-1jykg0py.js";
594
637
  import {
595
638
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
596
639
  SUPPORTED_PROTOCOL_VERSIONS,
@@ -605,24 +648,6 @@ import {
605
648
  referencedBundlePaths,
606
649
  skillDirs,
607
650
  init_manifest_format,
608
- TaskCreationBlockedError,
609
- init_errors2,
610
- resolveIdentity,
611
- renderIdentity,
612
- init_identity,
613
- recordUnmappedIdentity,
614
- init_unmapped_identities,
615
- MAX_TASK_ATTACHMENT_BYTES,
616
- recordTaskAttachmentUpload,
617
- scopeFromAttachment,
618
- backingProviderId,
619
- init_task_attachment_store,
620
- stripSiblingBlock,
621
- init_sibling_block,
622
- createTaskWithSiblingAwareness,
623
- init_sibling_awareness,
624
- transcribeAudioNotes,
625
- init_transcription,
626
651
  handleWebhookTrigger,
627
652
  verifyHmacSignature,
628
653
  WebhookError,
@@ -636,6 +661,10 @@ import {
636
661
  getExecutorRegistry2,
637
662
  initWorkflows2,
638
663
  init_workflows,
664
+ stripSiblingBlock,
665
+ init_sibling_block,
666
+ createTaskWithSiblingAwareness,
667
+ init_sibling_awareness,
639
668
  dispatchScheduleTarget,
640
669
  calculateNextRun2,
641
670
  init_scheduler,
@@ -688,6 +717,20 @@ import {
688
717
  loadEnabledExtensions,
689
718
  stopExtensionRuntime,
690
719
  init_lifecycle,
720
+ resolveIdentity,
721
+ renderIdentity,
722
+ init_identity,
723
+ recordUnmappedIdentity,
724
+ init_unmapped_identities,
725
+ MAX_TASK_ATTACHMENT_BYTES,
726
+ recordTaskAttachmentUpload,
727
+ scopeFromAttachment,
728
+ backingProviderId,
729
+ init_task_attachment_store,
730
+ transcribeAudioNotes,
731
+ init_transcription,
732
+ isAgentOnDemand,
733
+ init_reachability,
691
734
  nextFallback2,
692
735
  createWorkerTaskFollowUp2,
693
736
  createResumeFollowUp2,
@@ -828,11 +871,14 @@ import {
828
871
  init_mcp_limits,
829
872
  userCtx,
830
873
  init_task_tool_ctx,
874
+ resolveRequestPrincipal,
831
875
  requestPrincipal,
832
876
  agentFirstPrincipal,
833
877
  requireAuthKind,
834
878
  rejectGuest,
835
879
  init_request_principal,
880
+ resolveTaskRequester,
881
+ init_task_requester,
836
882
  handleApps,
837
883
  init_apps,
838
884
  cancelApprovalRequest,
@@ -903,6 +949,7 @@ import {
903
949
  getTasksOutputSchema,
904
950
  getTasksHandler,
905
951
  init_get_tasks,
952
+ requiresLeadToWrite,
906
953
  reservedNamespaceError,
907
954
  privateNamespaceError,
908
955
  reservedRoomKeyError,
@@ -1016,7 +1063,7 @@ import {
1016
1063
  getEnabledCapabilities,
1017
1064
  createServer,
1018
1065
  init_server
1019
- } from "./cli-k96cecs7.js";
1066
+ } from "./cli-2czxfnvj.js";
1020
1067
  import {
1021
1068
  FilesError,
1022
1069
  normalizeFilesError,
@@ -1027,7 +1074,6 @@ import {
1027
1074
  getFileStorageProvider2,
1028
1075
  init_registry2
1029
1076
  } from "./cli-7cp6aa1q.js";
1030
- import"./cli-x6t50dmw.js";
1031
1077
  import {
1032
1078
  RuntimePoolError2,
1033
1079
  mintControllerToken,
@@ -1049,7 +1095,7 @@ import {
1049
1095
  resolvePoolDelivery2,
1050
1096
  createPoolAgent2,
1051
1097
  init_db2
1052
- } from "./cli-rjvsf9qa.js";
1098
+ } from "./cli-mkwkwq81.js";
1053
1099
  import {
1054
1100
  duplicateGuardedQueryKey,
1055
1101
  warnIfCorsAllowsAnyOrigin,
@@ -1106,7 +1152,7 @@ import {
1106
1152
  describeRequestRoute,
1107
1153
  route,
1108
1154
  init_route_def
1109
- } from "./cli-sg27rk2t.js";
1155
+ } from "./cli-nbt14he0.js";
1110
1156
  import {
1111
1157
  startPoolRouting,
1112
1158
  stopPoolRouting,
@@ -1119,28 +1165,28 @@ import {
1119
1165
  checkHeartbeatChecklist2,
1120
1166
  runHeartbeatSweep2,
1121
1167
  stopHeartbeat2
1122
- } from "./cli-kw44j53p.js";
1123
- import"./cli-54qr8mcd.js";
1168
+ } from "./cli-m7zvgt57.js";
1169
+ import"./cli-mhapr559.js";
1124
1170
  import {
1125
1171
  runtimeSupervisorStatus,
1126
1172
  startRuntimeSupervisor,
1127
1173
  stopRuntimeSupervisor
1128
- } from "./cli-kmemts3w.js";
1174
+ } from "./cli-sn650d7x.js";
1129
1175
  import {
1130
1176
  TASK_TITLE_TIMEOUT_MS,
1131
1177
  generateTaskTitle
1132
- } from "./cli-1m96dc36.js";
1178
+ } from "./cli-gfy38pvt.js";
1133
1179
  import"./cli-ns59dc6r.js";
1134
1180
  import {
1135
1181
  ACP_TARGET_IDS
1136
- } from "./cli-skmhsnqh.js";
1182
+ } from "./cli-x40a0w9j.js";
1137
1183
  import {
1138
1184
  reasoningCapability,
1139
1185
  supportedReasoningLevels
1140
- } from "./cli-93t5s4zq.js";
1186
+ } from "./cli-5gpqgs8b.js";
1141
1187
  import {
1142
1188
  MAX_RATE_LIMIT_RESET_MS
1143
- } from "./cli-tnzebztn.js";
1189
+ } from "./cli-kpgcm7xy.js";
1144
1190
  import {
1145
1191
  isLeadChannelMonitoringEnabled,
1146
1192
  ORG_IDENTITY_KEYS,
@@ -1150,14 +1196,20 @@ import {
1150
1196
  isUnknownModelError,
1151
1197
  checkProviderPoolKey,
1152
1198
  writeSkillsToFilesystem
1153
- } from "./cli-ztq5z4e1.js";
1199
+ } from "./cli-f9gz2vyj.js";
1154
1200
  import {
1155
- inviteEmailToSharedOrg,
1156
- ensureAgentFsCredentialsForAgent
1157
- } from "./cli-bhsfbmk8.js";
1201
+ AgentFsRequestError2,
1202
+ resolveAgentFsSharedContext2,
1203
+ inviteEmailToSharedOrg2,
1204
+ ensureAgentFsCredentialsForAgent2,
1205
+ getCurrentOrgMembers2,
1206
+ roleRank2,
1207
+ agentFsRequest2,
1208
+ resolveApiUrl2
1209
+ } from "./cli-fh97xn30.js";
1158
1210
  import {
1159
1211
  Anthropic
1160
- } from "./cli-500c09j9.js";
1212
+ } from "./cli-t9ga4qmb.js";
1161
1213
  import {
1162
1214
  isCodexOAuthConfigKey
1163
1215
  } from "./cli-j4bwnpkm.js";
@@ -1165,6 +1217,10 @@ import {
1165
1217
  resolveClaudeTransport,
1166
1218
  isClaudeBridgeEffective
1167
1219
  } from "./cli-9fzgd3hg.js";
1220
+ import {
1221
+ runTaskUiAction,
1222
+ init_actions
1223
+ } from "./cli-f8x9drqr.js";
1168
1224
  import {
1169
1225
  RATING_MODEL_MAX_LENGTH,
1170
1226
  REFERENCES_SOURCE_MAX_LENGTH,
@@ -1172,7 +1228,7 @@ import {
1172
1228
  init_types2
1173
1229
  } from "./cli-2xv18ywz.js";
1174
1230
  import {
1175
- require_dist2,
1231
+ require_dist,
1176
1232
  getMcpOAuthToken,
1177
1233
  findReusableMcpOAuthClient,
1178
1234
  invalidateMcpOAuthClient,
@@ -1259,7 +1315,7 @@ import {
1259
1315
  init_typecheck,
1260
1316
  parseSkillContent,
1261
1317
  init_skill_parser
1262
- } from "./cli-z8cvws4c.js";
1318
+ } from "./cli-2yjj3e31.js";
1263
1319
  import {
1264
1320
  signalProcessGroup,
1265
1321
  detachedProcessGroup,
@@ -1276,39 +1332,15 @@ import {
1276
1332
  forceRefreshAuthorizationOrThrow,
1277
1333
  forceRefreshTokenOrThrow,
1278
1334
  init_ensure_token
1279
- } from "./cli-s8p8hhty.js";
1335
+ } from "./cli-jm0hvmz2.js";
1336
+ import"./cli-br0924pw.js";
1280
1337
  import {
1281
1338
  automationIntegrationFixUrl,
1282
1339
  preflightAutomation,
1283
1340
  getAutomationSetupStates,
1284
1341
  listEnabledAutomationPreflightInputs,
1342
+ setupIntegrationFlags,
1285
1343
  init_automation_preflight,
1286
- AGENT_MAX_TASKS_CONFIG_KEY,
1287
- reconcileAgentMaxTasksPolicy,
1288
- resetAgentMaxTasksMirror,
1289
- upsertSwarmConfigWithPolicyMirror,
1290
- runtimeStaleThresholdMinutes,
1291
- upsertRuntimeInstance,
1292
- getRuntimeInstanceById,
1293
- touchRuntimeInstance,
1294
- listRuntimeInstancesForAgent,
1295
- setRuntimeCredentialReady,
1296
- reconcileAgentStatusFromRuntimes,
1297
- listRuntimeInstancesForPool,
1298
- init_multi_runtime,
1299
- ConfigQuestionSettingsSchema,
1300
- ConfigStateSchema,
1301
- readConfigState,
1302
- normalizeApprovalQuestions,
1303
- isConfigQuestion,
1304
- parseConfigAnswer,
1305
- skippedConfigResult,
1306
- keptConfigResult,
1307
- applyConfigAnswer,
1308
- init_approval_config_question,
1309
- dispatchApprovalNotifications,
1310
- createApprovalFollowUpTask,
1311
- init_approval_notifications,
1312
1344
  validateJsonSchema,
1313
1345
  init_json_schema_validator,
1314
1346
  workflowSaveWarnings,
@@ -1320,7 +1352,7 @@ import {
1320
1352
  definitionNodeIds,
1321
1353
  validateDefinition,
1322
1354
  init_definition2
1323
- } from "./cli-c3ng0mb4.js";
1355
+ } from "./cli-j7svy295.js";
1324
1356
  import {
1325
1357
  _fetchHolder,
1326
1358
  CLIENT_ID,
@@ -1336,15 +1368,23 @@ import {
1336
1368
  loadAllCodexOAuthSlots,
1337
1369
  getValidCodexOAuth,
1338
1370
  init_storage
1339
- } from "./cli-nx2n3z6p.js";
1371
+ } from "./cli-7sf9sb0w.js";
1340
1372
  import {
1341
1373
  isMultiRuntimeEnabled,
1342
1374
  init_multi_runtime2
1343
1375
  } from "./cli-mdb054w3.js";
1376
+ import {
1377
+ getApiKey,
1378
+ init_api_key
1379
+ } from "./cli-pax9q4ff.js";
1380
+ import {
1381
+ createRuntimeProvider,
1382
+ init_runtime_providers
1383
+ } from "./cli-6945ywhr.js";
1344
1384
  import {
1345
1385
  require_content_type
1346
- } from "./cli-yjdgea32.js";
1347
- import"./cli-s7zz734a.js";
1386
+ } from "./cli-1jx0srjt.js";
1387
+ import"./cli-n3qe7tyr.js";
1348
1388
  import {
1349
1389
  isInvalidClientError,
1350
1390
  publicEndpointSsrfOptions,
@@ -1362,11 +1402,7 @@ import {
1362
1402
  revokeMcpToken,
1363
1403
  computeExpiresAt,
1364
1404
  init_mcp_wrapper
1365
- } from "./cli-qmqt520k.js";
1366
- import {
1367
- createRuntimeProvider,
1368
- init_runtime_providers
1369
- } from "./cli-t5ys4ebm.js";
1405
+ } from "./cli-2dq9yv8p.js";
1370
1406
  import"./cli-v41kn3cd.js";
1371
1407
  import {
1372
1408
  setBedrockProviderModule,
@@ -1403,17 +1439,34 @@ import {
1403
1439
  revokeAgentTokens,
1404
1440
  fingerprintApiKey,
1405
1441
  init_users
1406
- } from "./cli-c71n3bxq.js";
1442
+ } from "./cli-v57d7fmm.js";
1407
1443
  import {
1408
1444
  AMP_ESTIMATE_MODELS,
1409
1445
  ampBillsCacheWrites,
1410
1446
  resolveAmpModel,
1411
1447
  init_amp_models
1412
- } from "./cli-tf79ryyy.js";
1448
+ } from "./cli-mjw0yf82.js";
1449
+ import {
1450
+ MAX_PROVIDER_QUOTA_ENTRIES,
1451
+ ProviderQuotaCapacityError,
1452
+ windowFieldObservedAtSchema,
1453
+ codexWindowKey,
1454
+ providerAccountTelemetrySchema,
1455
+ rateLimitReplacementSchema,
1456
+ init_provider_account_telemetry
1457
+ } from "./cli-43ms35q9.js";
1458
+ import {
1459
+ CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1460
+ CODEX_AUTH_WATCH_NAMESPACE,
1461
+ codexAuthBenchMarkerKey,
1462
+ init_codex_auth_failure
1463
+ } from "./cli-fw2w0kva.js";
1413
1464
  import {
1414
1465
  ASSET_KEY_MAX_LENGTH,
1466
+ AssetKeyError,
1415
1467
  normalizeAssetKey,
1416
1468
  defaultAssetKey,
1469
+ isGroupKey,
1417
1470
  isResourceGroupPrefix,
1418
1471
  RESOURCE_GROUPS_READ_ONLY,
1419
1472
  parseAssetKey,
@@ -1463,6 +1516,7 @@ import {
1463
1516
  InboxItemTypeSchema,
1464
1517
  InboxItemStatusSchema,
1465
1518
  InboxItemStateSchema,
1519
+ ChecklistItemSchema,
1466
1520
  FavoriteItemTypeSchema,
1467
1521
  UserFavoriteSchema,
1468
1522
  TaskTemplateKindSchema,
@@ -1572,19 +1626,17 @@ import {
1572
1626
  KvNamespaceSchema,
1573
1627
  KvKeySchema,
1574
1628
  KvEntrySchema,
1575
- init_types4
1576
- } from "./cli-qps8je6j.js";
1629
+ init_types5
1630
+ } from "./cli-bkjdknnp.js";
1577
1631
  import {
1578
- CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1579
- CODEX_AUTH_WATCH_NAMESPACE,
1580
- codexAuthBenchMarkerKey,
1581
- init_codex_auth_failure
1582
- } from "./cli-fw2w0kva.js";
1632
+ resolveGitHubHost,
1633
+ init_github_host
1634
+ } from "./cli-9ttx00s3.js";
1583
1635
  import {
1584
1636
  IDENTITY_FIELD_BUDGETS,
1585
1637
  IdentityFieldBudgetError,
1586
1638
  init_identity_field_budget
1587
- } from "./cli-am1ptset.js";
1639
+ } from "./cli-m7c2380k.js";
1588
1640
  import {
1589
1641
  getSlackConfiguration,
1590
1642
  init_config4
@@ -1598,13 +1650,16 @@ import {
1598
1650
  SUBSCRIPTION_PLANS,
1599
1651
  isSubscriptionPlanId,
1600
1652
  init_subscription_plans
1601
- } from "./cli-7akn6ze9.js";
1653
+ } from "./cli-nh7x3133.js";
1602
1654
  import {
1603
1655
  getOpenRouterAttributionHeaders,
1604
1656
  init_openrouter_base_url
1605
1657
  } from "./cli-dfyv0jdy.js";
1606
1658
  import {
1607
1659
  MODEL_SCOPED_WINDOWS,
1660
+ KEY_WIDE_WINDOWS,
1661
+ modelFamilyOf,
1662
+ isModelScopedWindow,
1608
1663
  activeModelBlocks,
1609
1664
  init_model_rate_limit_windows,
1610
1665
  CREDENTIAL_POOL_VARS,
@@ -1613,7 +1668,7 @@ import {
1613
1668
  splitCredentialPool,
1614
1669
  selectCredential,
1615
1670
  init_credentials2
1616
- } from "./cli-t4dv07kr.js";
1671
+ } from "./cli-psffsanb.js";
1617
1672
  import {
1618
1673
  interpolate,
1619
1674
  init_template2,
@@ -1623,7 +1678,7 @@ import {
1623
1678
  resolveTemplate,
1624
1679
  init_resolver,
1625
1680
  init_session_templates
1626
- } from "./cli-0bcgyj5b.js";
1681
+ } from "./cli-6ehs4mta.js";
1627
1682
  import {
1628
1683
  init_zod
1629
1684
  } from "./cli-zcfpsfzf.js";
@@ -1634,6 +1689,7 @@ import {
1634
1689
  string2,
1635
1690
  email,
1636
1691
  uuid,
1692
+ url,
1637
1693
  number2,
1638
1694
  boolean,
1639
1695
  _null,
@@ -1653,14 +1709,6 @@ import {
1653
1709
  exports_iso,
1654
1710
  exports_coerce
1655
1711
  } from "./cli-hg42n3hx.js";
1656
- import {
1657
- init_package,
1658
- package_default
1659
- } from "./cli-922z7gwm.js";
1660
- import {
1661
- realtimeBus,
1662
- init_bus
1663
- } from "./cli-syfdvhkc.js";
1664
1712
  import {
1665
1713
  MAX_PROFILE_FILE_LENGTH,
1666
1714
  DEFAULT_APP_URL,
@@ -1669,20 +1717,25 @@ import {
1669
1717
  getLocalDevAppOrigins,
1670
1718
  getMcpBaseUrl,
1671
1719
  getPublicMcpBaseUrl,
1720
+ getAgentFsLiveUrl,
1672
1721
  agentFsFileRoute,
1673
1722
  isCombEnabled,
1674
1723
  isAgentFsProxyEnabled,
1675
1724
  init_constants3
1676
- } from "./cli-dns0y538.js";
1725
+ } from "./cli-dqgnbnxs.js";
1677
1726
  import {
1678
1727
  parseEnvFlag,
1679
1728
  isEnvFlagEnabled,
1680
1729
  init_env_flag
1681
1730
  } from "./cli-cebvbc9t.js";
1682
1731
  import {
1683
- getApiKey,
1684
- init_api_key
1685
- } from "./cli-pax9q4ff.js";
1732
+ init_package,
1733
+ package_default
1734
+ } from "./cli-h9yqfzx9.js";
1735
+ import {
1736
+ realtimeBus,
1737
+ init_bus
1738
+ } from "./cli-syfdvhkc.js";
1686
1739
  import {
1687
1740
  isAlias,
1688
1741
  baseUrlEnvVar,
@@ -1694,7 +1747,7 @@ import {
1694
1747
  registerVolatileSecret,
1695
1748
  registerEnvSecrets,
1696
1749
  init_secret_scrubber
1697
- } from "./cli-f1kwb5fc.js";
1750
+ } from "./cli-5a6pqy45.js";
1698
1751
  import {
1699
1752
  __toESM
1700
1753
  } from "./cli-242037k3.js";
@@ -1758,7 +1811,7 @@ import {
1758
1811
 
1759
1812
  // src/be/db-retention.ts
1760
1813
  init_otel();
1761
- init_types4();
1814
+ init_types5();
1762
1815
  init_env_flag();
1763
1816
  init_secret_scrubber();
1764
1817
  init_db4();
@@ -6142,7 +6195,7 @@ init_workflows();
6142
6195
  // src/http/active-sessions.ts
6143
6196
  init_zod();
6144
6197
  init_db4();
6145
- init_types4();
6198
+ init_types5();
6146
6199
  init_multi_runtime2();
6147
6200
  init_route_def();
6148
6201
  init_session_access();
@@ -6714,9 +6767,10 @@ init_model_tier_resolution();
6714
6767
  init_model_validation2();
6715
6768
  init_multi_runtime();
6716
6769
  init_db2();
6770
+ init_reachability();
6717
6771
  init_server();
6718
6772
  init_telemetry();
6719
- init_types4();
6773
+ init_types5();
6720
6774
  init_business_use();
6721
6775
  init_constants3();
6722
6776
  init_heartbeat_expiry();
@@ -6931,8 +6985,16 @@ async function resolveListClaudeTransports(agents) {
6931
6985
  return result;
6932
6986
  }
6933
6987
  var AgentListItemSchema = AgentWithCapacityAndTasksSchema.extend({
6934
- claudeTransport: ClaudeTransportSchema.optional()
6988
+ claudeTransport: ClaudeTransportSchema.optional(),
6989
+ onDemand: boolean().optional()
6935
6990
  });
6991
+ async function withListExtras(agent, claudeTransport) {
6992
+ return {
6993
+ ...agent,
6994
+ ...claudeTransport ? { claudeTransport } : {},
6995
+ ...await isAgentOnDemand(agent) ? { onDemand: true } : {}
6996
+ };
6997
+ }
6936
6998
  function searchAgents(agents, q, limit) {
6937
6999
  const needle = q?.toLowerCase();
6938
7000
  const matching = needle ? agents.filter((agent) => [agent.name, agent.role ?? "", agent.id].some((field) => field.toLowerCase().includes(needle))) : agents;
@@ -7326,10 +7388,7 @@ async function handleAgentsRest(req, res, pathSegments, queryParams, myAgentId)
7326
7388
  resolveListClaudeTransports(agents)
7327
7389
  ]);
7328
7390
  listAgents.respond(res, 200, {
7329
- agents: agentsWithCapacity.map((agent) => {
7330
- const claudeTransport = transports.get(agent.id);
7331
- return claudeTransport ? { ...agent, claudeTransport } : agent;
7332
- })
7391
+ agents: await Promise.all(agentsWithCapacity.map((agent) => withListExtras(agent, transports.get(agent.id))))
7333
7392
  });
7334
7393
  return true;
7335
7394
  }
@@ -7900,8 +7959,7 @@ async function handleAgentsRest(req, res, pathSegments, queryParams, myAgentId)
7900
7959
  agentWithCapacity(agent),
7901
7960
  resolveListClaudeTransports([agent])
7902
7961
  ]);
7903
- const claudeTransport = transports.get(agent.id);
7904
- getAgent.respond(res, 200, claudeTransport ? { ...agentWithCap, claudeTransport } : agentWithCap);
7962
+ getAgent.respond(res, 200, await withListExtras(agentWithCap, transports.get(agent.id)));
7905
7963
  return true;
7906
7964
  }
7907
7965
  return false;
@@ -7910,7 +7968,289 @@ async function handleAgentsRest(req, res, pathSegments, queryParams, myAgentId)
7910
7968
  // src/http/api-keys.ts
7911
7969
  init_zod();
7912
7970
  init_db4();
7971
+
7972
+ // src/be/key-window-usage.ts
7973
+ init_zod();
7974
+ init_types5();
7975
+ init_model_rate_limit_windows();
7976
+ init_provider_account_telemetry();
7977
+ init_db4();
7978
+ var MAX_USAGE_WINDOWS = 256;
7979
+ var MAX_USAGE_WINDOWS_PER_CREDENTIAL = 16;
7980
+ var MAX_USAGE_LOOKBACK_MS = 90 * 86400000;
7981
+ var MAX_USAGE_ROWS = 1e5;
7982
+
7983
+ class KeyWindowUsageLimitError extends Error {
7984
+ status;
7985
+ constructor(message, status = 422) {
7986
+ super(message);
7987
+ this.status = status;
7988
+ }
7989
+ }
7990
+ var counterSchema = object2({
7991
+ value: number2().nullable(),
7992
+ measuredSessions: number2().int(),
7993
+ missingSessions: number2().int()
7994
+ });
7995
+ var tokensSchema = object2({
7996
+ uncachedInput: counterSchema,
7997
+ output: counterSchema,
7998
+ cacheRead: counterSchema,
7999
+ cacheWrite: counterSchema,
8000
+ reasoning: counterSchema,
8001
+ thinking: counterSchema
8002
+ });
8003
+ var keyWindowUsageSchema = object2({
8004
+ statusId: string2(),
8005
+ keyType: string2(),
8006
+ keySuffix: string2(),
8007
+ scope: string2(),
8008
+ scopeId: string2().nullable(),
8009
+ windowKey: string2(),
8010
+ durationMins: number2().nullable(),
8011
+ startsAt: string2().nullable(),
8012
+ endsAt: string2().nullable(),
8013
+ dataThrough: string2(),
8014
+ observedAt: string2(),
8015
+ observationAgeMs: number2(),
8016
+ modelScope: object2({
8017
+ kind: _enum2(["account", "family", "unknown"]),
8018
+ model: string2().nullable()
8019
+ }),
8020
+ unavailableReason: _enum2(["missing_reset", "unknown_duration", "unknown_model_scope", "window_not_started"]).nullable(),
8021
+ usage: object2({
8022
+ sessions: number2().int(),
8023
+ errorSessions: number2().int(),
8024
+ completedTasks: number2().int(),
8025
+ tokens: tokensSchema,
8026
+ modelUnattributedSessions: number2().int(),
8027
+ swarmUnattributedSessions: number2().int()
8028
+ }).nullable()
8029
+ });
8030
+ function currentKeyWindows(statuses, nowMs) {
8031
+ const result = [];
8032
+ for (const key of statuses) {
8033
+ for (const [windowKey, window] of Object.entries(key.rateLimitWindows)) {
8034
+ const resetMs = window.resetsAt === undefined ? null : window.resetsAt * 1000;
8035
+ if (resetMs !== null && (!Number.isFinite(resetMs) || resetMs <= nowMs))
8036
+ continue;
8037
+ if (result.length >= MAX_USAGE_WINDOWS) {
8038
+ throw new KeyWindowUsageLimitError("Too many provider windows. Filter by credential or scope.");
8039
+ }
8040
+ const legacyClaude = window.source ? window.source === "claude" : key.provider === "claude";
8041
+ const family = legacyClaude ? MODEL_SCOPED_WINDOWS[windowKey] : undefined;
8042
+ const durationMins = window.durationMins ?? (legacyClaude ? windowKey === "five_hour" ? 300 : windowKey === "seven_day" || family ? 10080 : null : null);
8043
+ const accountWide = legacyClaude ? KEY_WIDE_WINDOWS.some((name) => name === windowKey) : [codexWindowKey("codex", "primary"), codexWindowKey("codex", "secondary")].includes(windowKey);
8044
+ const modelScope = family ? { kind: "family", model: family } : { kind: accountWide ? "account" : "unknown", model: null };
8045
+ const startMs = resetMs !== null && durationMins ? resetMs - durationMins * 60000 : null;
8046
+ const unavailableReason = resetMs === null ? "missing_reset" : startMs === null ? "unknown_duration" : startMs > nowMs ? "window_not_started" : modelScope.kind === "unknown" ? "unknown_model_scope" : null;
8047
+ result.push({
8048
+ statusId: key.id,
8049
+ keyType: key.keyType,
8050
+ keySuffix: key.keySuffix,
8051
+ scope: key.scope,
8052
+ scopeId: key.scopeId,
8053
+ windowKey,
8054
+ durationMins,
8055
+ startsAt: startMs === null ? null : new Date(startMs).toISOString(),
8056
+ endsAt: resetMs === null ? null : new Date(resetMs).toISOString(),
8057
+ dataThrough: new Date(Math.min(nowMs, resetMs ?? nowMs)).toISOString(),
8058
+ observedAt: window.lastSeenAt,
8059
+ observationAgeMs: Math.max(0, nowMs - Date.parse(window.lastSeenAt)),
8060
+ modelScope,
8061
+ unavailableReason,
8062
+ usage: null
8063
+ });
8064
+ }
8065
+ }
8066
+ return result;
8067
+ }
8068
+ var usageColumns = `sc.taskId, sc.credentialKeyType, sc.credentialKeySuffix, sc.harness,
8069
+ sc.inputTokens, sc.outputTokens, sc.cacheReadTokens, sc.cacheWriteTokens,
8070
+ sc.reasoningOutputTokens, sc.thinkingTokens, sc.model, sc.modelBreakdown,
8071
+ sc.isError, sc.createdAt`;
8072
+ var KEY_WINDOW_USAGE_SQL = `
8073
+ WITH requested_keys AS (
8074
+ SELECT json_extract(value, '$.keyType') AS keyType,
8075
+ json_extract(value, '$.keySuffix') AS keySuffix FROM json_each(?)
8076
+ )
8077
+ SELECT ${usageColumns}, CASE WHEN t.status = 'completed' THEN t.finishedAt END AS finishedAt
8078
+ FROM requested_keys k
8079
+ JOIN session_costs sc INDEXED BY idx_session_costs_credential_createdAt
8080
+ ON sc.credentialKeyType = k.keyType AND sc.credentialKeySuffix = k.keySuffix
8081
+ LEFT JOIN agent_tasks t ON t.id = sc.taskId
8082
+ WHERE sc.createdAt >= ? AND sc.createdAt < ?
8083
+ UNION ALL
8084
+ SELECT ${usageColumns}, t.finishedAt
8085
+ FROM agent_tasks t INDEXED BY idx_agent_tasks_status_finishedAt
8086
+ CROSS JOIN session_costs sc INDEXED BY idx_session_costs_taskId ON sc.taskId = t.id
8087
+ JOIN requested_keys k ON sc.credentialKeyType = k.keyType AND sc.credentialKeySuffix = k.keySuffix
8088
+ WHERE t.status = 'completed' AND t.finishedAt >= ? AND t.finishedAt < ? AND sc.createdAt < ?
8089
+ UNION ALL
8090
+ SELECT NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, 0, 0, '', NULL, 0, sc.createdAt, NULL
8091
+ FROM session_costs sc
8092
+ WHERE (sc.credentialKeyType IS NULL OR sc.credentialKeySuffix IS NULL)
8093
+ AND sc.createdAt >= ? AND sc.createdAt < ?
8094
+ LIMIT ${MAX_USAGE_ROWS + 1}`;
8095
+ var emptyTokens = () => Object.fromEntries(["uncachedInput", "output", "cacheRead", "cacheWrite", "reasoning", "thinking"].map((name) => [
8096
+ name,
8097
+ { value: null, measuredSessions: 0, missingSessions: 0 }
8098
+ ]));
8099
+ function add(tokens, name, value) {
8100
+ const counter = tokens[name];
8101
+ if (value === null)
8102
+ counter.missingSessions++;
8103
+ else {
8104
+ counter.value = (counter.value ?? 0) + value;
8105
+ counter.measuredSessions++;
8106
+ }
8107
+ }
8108
+ async function aggregateKeyWindowUsage(windows, through) {
8109
+ if (windows.length > MAX_USAGE_WINDOWS) {
8110
+ throw new KeyWindowUsageLimitError("Too many provider windows. Filter by credential or scope.");
8111
+ }
8112
+ const eligible = windows.filter((w) => w.unavailableReason === null && w.startsAt !== null && w.endsAt !== null);
8113
+ const first = eligible[0];
8114
+ if (!first)
8115
+ return [];
8116
+ const start = eligible.reduce((earliest, w) => w.startsAt < earliest ? w.startsAt : earliest, first.startsAt);
8117
+ if (Date.parse(start) < Date.parse(through) - MAX_USAGE_LOOKBACK_MS) {
8118
+ throw new KeyWindowUsageLimitError("Observed usage supports a maximum lookback of 90 days.");
8119
+ }
8120
+ const credentialKey = (key) => JSON.stringify([key.keyType, key.keySuffix]);
8121
+ const windowIdentity = (window) => JSON.stringify([window.startsAt, window.endsAt, window.modelScope]);
8122
+ const windowGroups = new Map;
8123
+ for (const window of eligible) {
8124
+ const key = credentialKey(window);
8125
+ const bounds = windowGroups.get(key) ?? new Set;
8126
+ bounds.add(windowIdentity(window));
8127
+ if (bounds.size > MAX_USAGE_WINDOWS_PER_CREDENTIAL) {
8128
+ throw new KeyWindowUsageLimitError("Too many distinct windows for one credential. Filter by scope.");
8129
+ }
8130
+ windowGroups.set(key, bounds);
8131
+ }
8132
+ const credentials = [
8133
+ ...new Map(eligible.map((w) => [
8134
+ JSON.stringify([w.keyType, w.keySuffix]),
8135
+ { keyType: w.keyType, keySuffix: w.keySuffix }
8136
+ ])).values()
8137
+ ];
8138
+ const rows = await getDbClient2().query(KEY_WINDOW_USAGE_SQL, [
8139
+ JSON.stringify(credentials),
8140
+ start,
8141
+ through,
8142
+ start,
8143
+ through,
8144
+ start,
8145
+ start,
8146
+ through
8147
+ ]);
8148
+ if (rows.length > MAX_USAGE_ROWS) {
8149
+ throw new KeyWindowUsageLimitError("Too many sessions for window usage. Filter by credential or scope.");
8150
+ }
8151
+ const rowsByCredential = new Map;
8152
+ const unattributedTimes = [];
8153
+ for (const row of rows) {
8154
+ if (row.credentialKeyType === null || row.credentialKeySuffix === null) {
8155
+ unattributedTimes.push(row.createdAt);
8156
+ continue;
8157
+ }
8158
+ const key = credentialKey({
8159
+ keyType: row.credentialKeyType,
8160
+ keySuffix: row.credentialKeySuffix
8161
+ });
8162
+ const group = rowsByCredential.get(key) ?? [];
8163
+ group.push(row);
8164
+ rowsByCredential.set(key, group);
8165
+ }
8166
+ unattributedTimes.sort();
8167
+ const unattributedSince = (start) => {
8168
+ let lower = 0;
8169
+ let upper = unattributedTimes.length;
8170
+ while (lower < upper) {
8171
+ const middle = Math.floor((lower + upper) / 2);
8172
+ if (unattributedTimes[middle] < start)
8173
+ lower = middle + 1;
8174
+ else
8175
+ upper = middle;
8176
+ }
8177
+ return unattributedTimes.length - lower;
8178
+ };
8179
+ const computed = new Map;
8180
+ return eligible.map((window) => {
8181
+ const identity = JSON.stringify([credentialKey(window), windowIdentity(window)]);
8182
+ const prior = computed.get(identity);
8183
+ if (prior)
8184
+ return {
8185
+ statusId: window.statusId,
8186
+ windowKey: window.windowKey,
8187
+ dataThrough: through,
8188
+ usage: prior
8189
+ };
8190
+ const usage = {
8191
+ sessions: 0,
8192
+ errorSessions: 0,
8193
+ completedTasks: 0,
8194
+ tokens: emptyTokens(),
8195
+ modelUnattributedSessions: 0,
8196
+ swarmUnattributedSessions: unattributedSince(window.startsAt)
8197
+ };
8198
+ const completed = new Set;
8199
+ for (const row of rowsByCredential.get(credentialKey(window)) ?? []) {
8200
+ const inReceiptWindow = row.createdAt >= window.startsAt && row.createdAt < through;
8201
+ let parts = [
8202
+ {
8203
+ model: row.model,
8204
+ inputTokens: row.inputTokens,
8205
+ outputTokens: row.outputTokens,
8206
+ cacheReadTokens: row.cacheReadTokens,
8207
+ cacheWriteTokens: row.cacheWriteTokens
8208
+ }
8209
+ ];
8210
+ const scoped = window.modelScope.kind !== "account";
8211
+ if (scoped) {
8212
+ parts = [];
8213
+ try {
8214
+ const parsed = SessionCostModelBreakdownSchema.array().safeParse(row.modelBreakdown ? JSON.parse(row.modelBreakdown) : null);
8215
+ parts = parsed.success ? parsed.data : [];
8216
+ } catch {
8217
+ parts = [];
8218
+ }
8219
+ }
8220
+ if (scoped) {
8221
+ const known = parts.length > 0 && parts.every((part) => part.model.length > 0);
8222
+ if (!known && inReceiptWindow)
8223
+ usage.modelUnattributedSessions++;
8224
+ parts = parts.filter((part) => modelFamilyOf(part.model) === window.modelScope.model);
8225
+ if (!parts.length)
8226
+ continue;
8227
+ }
8228
+ if (row.taskId && row.finishedAt && row.finishedAt >= window.startsAt && row.finishedAt < through)
8229
+ completed.add(row.taskId);
8230
+ if (!inReceiptWindow)
8231
+ continue;
8232
+ usage.sessions++;
8233
+ usage.errorSessions += row.isError ? 1 : 0;
8234
+ const sum = (field) => parts.some((part) => part[field] === null) ? null : parts.reduce((total, part) => total + (part[field] ?? 0), 0);
8235
+ const input = sum("inputTokens");
8236
+ const read = sum("cacheReadTokens");
8237
+ const knownInput = ["claude", "claude-managed", "pi", "opencode"].includes(row.harness ?? "");
8238
+ add(usage.tokens, "uncachedInput", row.harness === "codex" ? input !== null && read !== null ? Math.max(0, input - read) : null : knownInput ? input : null);
8239
+ add(usage.tokens, "output", sum("outputTokens"));
8240
+ add(usage.tokens, "cacheRead", read);
8241
+ add(usage.tokens, "cacheWrite", sum("cacheWriteTokens"));
8242
+ add(usage.tokens, "reasoning", !scoped && row.reasoningOutputTokens > 0 ? row.reasoningOutputTokens : null);
8243
+ add(usage.tokens, "thinking", !scoped && row.thinkingTokens > 0 ? row.thinkingTokens : null);
8244
+ }
8245
+ usage.completedTasks = completed.size;
8246
+ computed.set(identity, usage);
8247
+ return { statusId: window.statusId, windowKey: window.windowKey, dataThrough: through, usage };
8248
+ });
8249
+ }
8250
+
8251
+ // src/http/api-keys.ts
7913
8252
  init_model_rate_limit_windows();
8253
+ init_provider_account_telemetry();
7914
8254
  init_subscription_plans();
7915
8255
  init_route_def();
7916
8256
 
@@ -7964,6 +8304,7 @@ function clearUsageCache() {
7964
8304
 
7965
8305
  // src/http/api-keys.ts
7966
8306
  init_utils2();
8307
+ var windowUsageQueryRateLimit = createIpRateLimiter({ capacity: 8, refillPerMs: 1 / 1000 });
7967
8308
  var successMessageSchema = object2({
7968
8309
  success: literal2(true),
7969
8310
  message: string2()
@@ -7982,7 +8323,8 @@ var reportUsage = route({
7982
8323
  taskId: string2().uuid().optional(),
7983
8324
  scope: string2().optional(),
7984
8325
  scopeId: string2().optional(),
7985
- plan: string2().max(40).optional()
8326
+ plan: string2().max(40).optional(),
8327
+ planRaw: string2().min(1).max(80).optional()
7986
8328
  }),
7987
8329
  responses: {
7988
8330
  200: { description: "Usage recorded", schema: successMessageSchema },
@@ -8073,45 +8415,102 @@ var reportAuthFailure = route({
8073
8415
  }
8074
8416
  });
8075
8417
  var rateLimitWindowSchema = object2({
8076
- status: string2(),
8418
+ status: string2().max(256),
8077
8419
  utilization: number2().optional(),
8078
8420
  resetsAt: number2().finite().optional(),
8421
+ fieldObservedAt: windowFieldObservedAtSchema.optional(),
8422
+ durationMins: number2().int().positive().max(576000).optional(),
8423
+ source: _enum2(["claude", "codex"]).optional(),
8424
+ limitId: string2().min(1).max(128).optional(),
8425
+ label: string2().max(256).optional(),
8426
+ normalModelSlug: string2().max(256).optional(),
8427
+ overageStatus: string2().max(256).optional(),
8428
+ overageDisabledReason: string2().max(256).optional(),
8079
8429
  isUsingOverage: boolean().optional(),
8080
8430
  surpassedThreshold: number2().optional(),
8081
8431
  lastSeenAt: string2().datetime()
8082
8432
  });
8433
+ var MAX_DISPLAY_RESET_MS = 400 * 86400000;
8083
8434
  function sanitizeReportedWindowResets(windows) {
8084
- const nowSec = Math.floor(Date.now() / 1000);
8085
- const maxResetsAtSec = Math.floor((Date.now() + MAX_RATE_LIMIT_RESET_MS) / 1000);
8435
+ const nowMs = Date.now();
8436
+ const nowSec = Math.floor(nowMs / 1000);
8086
8437
  const sanitized = {};
8087
8438
  for (const [key, window] of Object.entries(windows)) {
8088
- sanitized[key] = window.resetsAt === undefined ? window : { ...window, resetsAt: Math.min(Math.max(window.resetsAt, nowSec), maxResetsAtSec) };
8439
+ const duration = window.durationMins ?? (key === "five_hour" ? 300 : key.startsWith("seven_day") ? 10080 : undefined);
8440
+ const horizonMs = isModelScopedWindow(key) ? MAX_RATE_LIMIT_RESET_MS : duration === undefined ? MAX_DISPLAY_RESET_MS : Math.min(MAX_DISPLAY_RESET_MS, Math.max(MAX_RATE_LIMIT_RESET_MS, duration * 60000 + 86400000));
8441
+ const maxResetsAtSec = Math.floor((nowMs + horizonMs) / 1000);
8442
+ sanitized[key] = window.resetsAt === undefined ? window : {
8443
+ ...window,
8444
+ resetsAt: Math.min(window.resetsAt < nowSec - MAX_DISPLAY_RESET_MS / 1000 ? nowSec : window.resetsAt, maxResetsAtSec)
8445
+ };
8089
8446
  }
8090
8447
  return sanitized;
8091
8448
  }
8449
+ function sanitizeReportedQuotaObservations(report, nowMs = Date.now()) {
8450
+ const bound = (at) => Date.parse(at) > nowMs + 60000 ? new Date(nowMs).toISOString() : at;
8451
+ const times = (values) => values && Object.fromEntries(Object.entries(values).map(([key, at]) => [key, bound(at)]));
8452
+ return {
8453
+ windows: Object.fromEntries(Object.entries(report.windows).map(([key, window]) => [
8454
+ key,
8455
+ {
8456
+ ...window,
8457
+ lastSeenAt: bound(window.lastSeenAt),
8458
+ ...window.fieldObservedAt ? { fieldObservedAt: times(window.fieldObservedAt) } : {}
8459
+ }
8460
+ ])),
8461
+ account: report.account && {
8462
+ ...report.account,
8463
+ observedAt: bound(report.account.observedAt),
8464
+ ...report.account.fieldObservedAt ? { fieldObservedAt: times(report.account.fieldObservedAt) } : {},
8465
+ ...report.account.limits ? {
8466
+ limits: Object.fromEntries(Object.entries(report.account.limits).map(([id, limit]) => [
8467
+ id,
8468
+ {
8469
+ ...limit,
8470
+ observedAt: bound(limit.observedAt),
8471
+ ...limit.fieldObservedAt ? { fieldObservedAt: times(limit.fieldObservedAt) } : {},
8472
+ ...limit.windowRemovedAt ? { windowRemovedAt: times(limit.windowRemovedAt) } : {}
8473
+ }
8474
+ ]))
8475
+ } : {}
8476
+ },
8477
+ replace: report.replace?.map((replacement) => ({
8478
+ ...replacement,
8479
+ observedAt: bound(replacement.observedAt)
8480
+ }))
8481
+ };
8482
+ }
8092
8483
  var reportRateLimitWindows = route({
8093
8484
  method: "post",
8094
8485
  path: "/api/keys/report-rate-limit-windows",
8095
8486
  pattern: ["api", "keys", "report-rate-limit-windows"],
8096
8487
  summary: "Record provider-emitted rate-limit window telemetry for an API key",
8488
+ description: "Reports accept up to 64 windows and 64 account limits within 256 KiB. Stored records have the same count limits.",
8097
8489
  tags: ["API Keys"],
8490
+ maxBodyBytes: 256 * 1024,
8098
8491
  body: object2({
8099
8492
  keyType: string2(),
8100
8493
  keySuffix: string2().min(1).max(10),
8101
8494
  keyIndex: number2().int().min(0),
8102
- windows: record2(string2(), rateLimitWindowSchema),
8495
+ windows: record2(string2().max(256), rateLimitWindowSchema),
8496
+ account: providerAccountTelemetrySchema.optional(),
8497
+ replace: array2(rateLimitReplacementSchema).max(128).optional(),
8103
8498
  scope: string2().optional(),
8104
8499
  scopeId: string2().optional()
8105
- }),
8500
+ }).refine((report) => Object.keys(report.windows).length <= MAX_PROVIDER_QUOTA_ENTRIES && Object.keys(report.account?.limits ?? {}).length <= MAX_PROVIDER_QUOTA_ENTRIES, "Reports support at most 64 windows and 64 account limits."),
8106
8501
  responses: {
8107
8502
  200: {
8108
8503
  description: "Rate-limit window telemetry recorded",
8109
8504
  schema: successMessageSchema
8110
8505
  },
8111
8506
  400: { description: "Validation error" },
8112
- 401: { description: "Unauthorized" }
8507
+ 401: { description: "Unauthorized" },
8508
+ 413: { description: "Telemetry report exceeds 256 KiB" }
8113
8509
  },
8114
- auth: { apiKey: true }
8510
+ auth: { apiKey: true },
8511
+ rbac: {
8512
+ ungated: "worker credential telemetry, same posture as POST /api/keys/report-rate-limit"
8513
+ }
8115
8514
  });
8116
8515
  var reportSeatMismatch = route({
8117
8516
  method: "post",
@@ -8189,8 +8588,10 @@ var ApiKeyStatusSchema = object2({
8189
8588
  name: string2().nullable(),
8190
8589
  provider: string2(),
8191
8590
  rateLimitWindows: record2(string2(), rateLimitWindowSchema),
8591
+ providerAccount: providerAccountTelemetrySchema.nullable(),
8192
8592
  plan: string2().nullable(),
8193
8593
  planSource: _enum2(["manual", "detected", "estimated"]).nullable(),
8594
+ detectedPlanRaw: string2().nullable(),
8194
8595
  lastSeatMismatchAt: string2().nullable(),
8195
8596
  lastSeatMismatchModel: string2().nullable(),
8196
8597
  consecutiveAuthFailures: number2().int(),
@@ -8253,6 +8654,36 @@ var listStatuses = route({
8253
8654
  },
8254
8655
  auth: { apiKey: true }
8255
8656
  });
8657
+ var getWindowUsage = route({
8658
+ method: "get",
8659
+ path: "/api/keys/window-usage",
8660
+ pattern: ["api", "keys", "window-usage"],
8661
+ summary: "Get Swarm-observed usage within current provider windows",
8662
+ description: "Usage calculations support 256 windows, 16 distinct windows per credential, 90 days, and 100,000 session rows. Oversized requests fail without partial totals.",
8663
+ tags: ["API Keys"],
8664
+ query: object2({
8665
+ keyType: string2().max(128).optional(),
8666
+ keySuffix: string2().min(1).max(10).optional(),
8667
+ scope: string2().max(64).optional(),
8668
+ scopeId: string2().max(128).optional()
8669
+ }),
8670
+ responses: {
8671
+ 200: {
8672
+ description: "Independent windows with receipt-time tokens and explicit measurement coverage",
8673
+ schema: object2({
8674
+ success: literal2(true),
8675
+ asOf: string2(),
8676
+ accounting: literal2("session_cost_receipt_time"),
8677
+ windows: array2(keyWindowUsageSchema)
8678
+ })
8679
+ },
8680
+ 400: { description: "Invalid filters" },
8681
+ 401: { description: "Unauthorized" },
8682
+ 422: { description: "Requested usage exceeds the aggregation bounds" },
8683
+ 429: { description: "Usage query budget exhausted. Retry after one second" }
8684
+ },
8685
+ auth: { apiKey: true }
8686
+ });
8256
8687
  var KeyCostSummarySchema = object2({
8257
8688
  keyType: string2(),
8258
8689
  keySuffix: string2(),
@@ -8392,9 +8823,9 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8392
8823
  const parsed = await reportUsage.parse(req, res, pathSegments, queryParams);
8393
8824
  if (!parsed)
8394
8825
  return true;
8395
- const { keyType, keySuffix, keyIndex, taskId, scope, scopeId, plan } = parsed.body;
8826
+ const { keyType, keySuffix, keyIndex, taskId, scope, scopeId, plan, planRaw } = parsed.body;
8396
8827
  try {
8397
- const { planChanged } = await recordKeyUsage2(keyType, keySuffix, keyIndex, taskId ?? null, scope, scopeId ?? null, plan && isSubscriptionPlanId(plan) ? plan : null);
8828
+ const { planChanged } = await recordKeyUsage2(keyType, keySuffix, keyIndex, taskId ?? null, scope, scopeId ?? null, plan && isSubscriptionPlanId(plan) ? plan : null, planRaw);
8398
8829
  if (planChanged)
8399
8830
  clearUsageCache();
8400
8831
  reportUsage.respond(res, 200, { success: true, message: "Key usage recorded" });
@@ -8451,17 +8882,20 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8451
8882
  const parsed = await reportRateLimitWindows.parse(req, res, pathSegments, queryParams);
8452
8883
  if (!parsed)
8453
8884
  return true;
8454
- const { keyType, keySuffix, keyIndex, windows, scope, scopeId } = parsed.body;
8885
+ const { keyType, keySuffix, keyIndex, scope, scopeId } = parsed.body;
8886
+ const { windows, account, replace } = sanitizeReportedQuotaObservations(parsed.body);
8455
8887
  try {
8456
- const { planChanged } = await recordKeyRateLimitWindows2(keyType, keySuffix, keyIndex, sanitizeReportedWindowResets(windows), scope, scopeId ?? null);
8457
- if (planChanged)
8458
- clearUsageCache();
8888
+ for (const limit of Object.values(account?.limits ?? {})) {
8889
+ if (limit.spend)
8890
+ limit.spend.resetsAt = Math.min(limit.spend.resetsAt, Math.floor(Date.now() / 1000) + 400 * 86400);
8891
+ }
8892
+ await recordKeyRateLimitWindows2(keyType, keySuffix, keyIndex, sanitizeReportedWindowResets(windows), scope, scopeId ?? null, account ?? undefined, replace);
8459
8893
  reportRateLimitWindows.respond(res, 200, {
8460
8894
  success: true,
8461
8895
  message: `Rate-limit windows recorded for ...${keySuffix}`
8462
8896
  });
8463
8897
  } catch (err) {
8464
- jsonError(res, err instanceof Error ? err.message : "Failed to record rate-limit windows", 500);
8898
+ jsonError(res, err instanceof Error ? err.message : "Failed to record rate-limit windows", err instanceof ProviderQuotaCapacityError ? 400 : 500);
8465
8899
  }
8466
8900
  return true;
8467
8901
  }
@@ -8507,6 +8941,52 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8507
8941
  }
8508
8942
  return true;
8509
8943
  }
8944
+ if (getWindowUsage.match(req.method, pathSegments)) {
8945
+ const parsed = await getWindowUsage.parse(req, res, pathSegments, queryParams);
8946
+ if (!parsed)
8947
+ return true;
8948
+ const { keyType, keySuffix, scope, scopeId } = parsed.query;
8949
+ try {
8950
+ const statuses = await getKeyStatuses2(keyType, scope, scope ? scopeId ?? null : undefined);
8951
+ const sampledAt = Date.now();
8952
+ const windows = currentKeyWindows(statuses.filter((key) => keySuffix === undefined || key.keySuffix === keySuffix), sampledAt);
8953
+ const bounds = windows.map((w) => [
8954
+ w.statusId,
8955
+ w.windowKey,
8956
+ w.startsAt,
8957
+ w.endsAt,
8958
+ w.modelScope,
8959
+ w.unavailableReason
8960
+ ]);
8961
+ const cached = await cachedUsageReport(`key-windows:${JSON.stringify([parsed.query, bounds])}`, () => {
8962
+ if (!windowUsageQueryRateLimit.take("window-usage")) {
8963
+ throw new KeyWindowUsageLimitError("Window usage is busy. Retry after one second.", 429);
8964
+ }
8965
+ return aggregateKeyWindowUsage(windows, new Date(sampledAt).toISOString());
8966
+ });
8967
+ const nowMs = Date.now();
8968
+ const byWindow = new Map(cached.map((item) => [JSON.stringify([item.statusId, item.windowKey]), item]));
8969
+ getWindowUsage.respond(res, 200, {
8970
+ success: true,
8971
+ asOf: new Date(nowMs).toISOString(),
8972
+ accounting: "session_cost_receipt_time",
8973
+ windows: windows.filter((w) => w.endsAt === null || Date.parse(w.endsAt) > nowMs).map((window) => {
8974
+ const aggregate = byWindow.get(JSON.stringify([window.statusId, window.windowKey]));
8975
+ return {
8976
+ ...window,
8977
+ observationAgeMs: Math.max(0, nowMs - Date.parse(window.observedAt)),
8978
+ ...aggregate ? { dataThrough: aggregate.dataThrough, usage: aggregate.usage } : {}
8979
+ };
8980
+ })
8981
+ });
8982
+ } catch (err) {
8983
+ const status = err instanceof KeyWindowUsageLimitError ? err.status : 500;
8984
+ if (status === 429)
8985
+ res.setHeader("Retry-After", "1");
8986
+ jsonError(res, err instanceof Error ? err.message : "Failed to get window usage", status);
8987
+ }
8988
+ return true;
8989
+ }
8510
8990
  if (getCosts.match(req.method, pathSegments)) {
8511
8991
  const parsed = await getCosts.parse(req, res, pathSegments, queryParams);
8512
8992
  if (!parsed)
@@ -8664,7 +9144,7 @@ init_rbac_roles();
8664
9144
  init_swarm_config_guard();
8665
9145
  init_users();
8666
9146
  init_rbac();
8667
- init_types4();
9147
+ init_types5();
8668
9148
  init_request_auth_context();
8669
9149
  init_secret_scrubber();
8670
9150
  init_core();
@@ -9616,7 +10096,10 @@ var ApprovalRequestSummarySchema = ApprovalRequestSchema.omit({
9616
10096
  resolutionReason: true,
9617
10097
  notificationChannels: true,
9618
10098
  configState: true
9619
- }).extend({ questionCount: number2().int() });
10099
+ }).extend({
10100
+ questionCount: number2().int(),
10101
+ viewerCanRespond: boolean().optional().describe("Pending rows only: whether the caller may answer, by the same rule as the respond route (a listed user or role, or no users and roles listed).")
10102
+ });
9620
10103
  async function toApprovalRequestResponse(request, options = {}) {
9621
10104
  const approvers = request.approvers;
9622
10105
  const approvals = request.approvals ?? null;
@@ -9632,14 +10115,17 @@ async function toApprovalRequestResponse(request, options = {}) {
9632
10115
  notificationChannels: request.notificationChannels
9633
10116
  };
9634
10117
  }
9635
- async function withApprovalProgress(rows) {
10118
+ async function withApprovalProgress(rows, viewer) {
9636
10119
  const pendingIds = rows.filter((row) => row.status === "pending").map((row) => row.id);
9637
10120
  const state = new Map((await getPendingApprovalVoteState2(pendingIds)).map((entry) => [entry.id, entry]));
9638
10121
  return Promise.all(rows.map(async (row) => {
9639
10122
  const entry = state.get(row.id);
9640
10123
  return {
9641
10124
  ...row,
9642
- approvalProgress: entry ? await approvalProgress(entry.approvers, entry.approvals ?? []) : null
10125
+ approvalProgress: entry ? await approvalProgress(entry.approvers, entry.approvals ?? []) : null,
10126
+ ...entry && {
10127
+ viewerCanRespond: viewer !== null && isListedApprover(entry.approvers, viewer)
10128
+ }
9643
10129
  };
9644
10130
  }));
9645
10131
  }
@@ -9833,7 +10319,7 @@ var listRoute = route({
9833
10319
  path: "/api/approval-requests",
9834
10320
  pattern: ["api", "approval-requests"],
9835
10321
  summary: "List approval requests with optional filters",
9836
- description: "Returns full approval requests by default. Pass `fields=slim` for the list-view shape: `questions`, `approvers`, `responses`, `resolutionReason` and `notificationChannels` are dropped and `questionCount` is added. Fetch one request in full via `GET /api/approval-requests/{id}`.",
10322
+ description: "Returns full approval requests by default. Pass `fields=slim` for the list-view shape: `questions`, `approvers`, `responses`, `resolutionReason` and `notificationChannels` are dropped and `questionCount` is added, plus `viewerCanRespond` on pending rows. Fetch one request in full via `GET /api/approval-requests/{id}`.",
9837
10323
  tags: ["ApprovalRequests"],
9838
10324
  query: object2({
9839
10325
  status: string2().optional(),
@@ -9881,7 +10367,7 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
9881
10367
  resolutionReason: `Timed out: the answer arrived after the deadline ${existing.expiresAt}`
9882
10368
  });
9883
10369
  if (timedOut && !existing.workflowRunId) {
9884
- await createApprovalFollowUpTask(timedOut, "hitl.timeout");
10370
+ await createApprovalFollowUpTask2(timedOut, "hitl.timeout");
9885
10371
  }
9886
10372
  });
9887
10373
  jsonError(res, `Approval request expired at ${existing.expiresAt}`, 409);
@@ -10027,7 +10513,7 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
10027
10513
  workflowRunStepId: updated.workflowRunStepId ?? undefined,
10028
10514
  sourceTaskId: updated.sourceTaskId ?? undefined
10029
10515
  });
10030
- await createApprovalFollowUpTask(updated, "hitl.follow_up");
10516
+ await createApprovalFollowUpTask2(updated, "hitl.follow_up");
10031
10517
  respondRoute.respond(res, 200, {
10032
10518
  approvalRequest: await toApprovalRequestResponse(updated, { withConfigState: true })
10033
10519
  });
@@ -10107,7 +10593,7 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
10107
10593
  });
10108
10594
  const notifications = parsed.body.notifications;
10109
10595
  if (notifications?.length && request.status === "pending") {
10110
- dispatchApprovalNotifications({
10596
+ dispatchApprovalNotifications2({
10111
10597
  requestId: request.id,
10112
10598
  title: request.title,
10113
10599
  questions,
@@ -10132,8 +10618,9 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
10132
10618
  limit: parsed.query.limit || undefined
10133
10619
  };
10134
10620
  if (parsed.query.fields === "slim") {
10621
+ const viewer = await approvalResponder(req);
10135
10622
  listRoute.respond(res, 200, {
10136
- approvalRequests: await withApprovalProgress(await listApprovalRequestSummaries2(filters))
10623
+ approvalRequests: await withApprovalProgress(await listApprovalRequestSummaries2(filters), viewer.ok ? viewer.responder : null)
10137
10624
  });
10138
10625
  return true;
10139
10626
  }
@@ -10212,7 +10699,7 @@ init_db4();
10212
10699
  init_db3();
10213
10700
  init_session_shares();
10214
10701
  init_rbac();
10215
- init_types4();
10702
+ init_types5();
10216
10703
  init_request_principal();
10217
10704
  init_route_def();
10218
10705
  init_session_access();
@@ -10543,7 +11030,7 @@ async function handleAssets(req, res, pathSegments, queryParams, myAgentId) {
10543
11030
  // src/http/budgets.ts
10544
11031
  init_zod();
10545
11032
  init_db4();
10546
- init_types4();
11033
+ init_types5();
10547
11034
  init_secret_scrubber();
10548
11035
  init_route_def();
10549
11036
  init_utils2();
@@ -10704,6 +11191,596 @@ async function handleBudgets(req, res, pathSegments, queryParams, _myAgentId) {
10704
11191
  return false;
10705
11192
  }
10706
11193
 
11194
+ // src/http/checklist.ts
11195
+ init_zod();
11196
+
11197
+ // src/be/checklist.ts
11198
+ init_key();
11199
+
11200
+ // src/integrations/chat-sdk/status.ts
11201
+ init_zod();
11202
+ init_constants3();
11203
+ init_env_flag();
11204
+ init_secret_scrubber();
11205
+ init_adapters();
11206
+ init_config();
11207
+
11208
+ // src/integrations/chat-sdk/discord-api.ts
11209
+ init_secret_scrubber();
11210
+ init_adapters();
11211
+ init_logger();
11212
+ var DISCORD_TIMEOUT_MS = 5000;
11213
+ var GUILDS_CACHE_MS = 60000;
11214
+ var MAX_GUILD_NAMES = 10;
11215
+ var cache;
11216
+ async function fetchDiscordGuilds(token, now = Date.now()) {
11217
+ if (cache && cache.token === token && now - cache.at < GUILDS_CACHE_MS)
11218
+ return cache.guilds;
11219
+ let guilds;
11220
+ try {
11221
+ const response = await fetch(`${resolveAdapterApiUrl("discord")}/users/@me/guilds`, {
11222
+ headers: { authorization: `Bot ${token}` },
11223
+ signal: AbortSignal.timeout(DISCORD_TIMEOUT_MS)
11224
+ });
11225
+ if (!response.ok)
11226
+ throw new Error(`HTTP ${response.status}`);
11227
+ const payload = await response.json();
11228
+ if (!Array.isArray(payload))
11229
+ throw new Error("unexpected response shape");
11230
+ const names = payload.map((guild) => guild !== null && typeof guild === "object" && typeof guild.name === "string" ? guild.name : undefined).filter((name) => name !== undefined);
11231
+ guilds = { count: payload.length, names: names.slice(0, MAX_GUILD_NAMES) };
11232
+ } catch (error) {
11233
+ console.warn(scrubSecrets(`[chat-sdk] discord: could not list the bot's servers: ${errorMessage(error).replaceAll(token, "[REDACTED]")}`));
11234
+ }
11235
+ cache = { token, at: now, guilds };
11236
+ return guilds;
11237
+ }
11238
+
11239
+ // src/integrations/chat-sdk/status.ts
11240
+ init_runtime();
11241
+ init_schema();
11242
+ init_telegram_api();
11243
+ var ChatSdkStatusSchema = object2({
11244
+ enabled: boolean(),
11245
+ slackClash: boolean(),
11246
+ error: string2().optional(),
11247
+ adapters: array2(object2({
11248
+ name: _enum2(CHAT_SDK_ADAPTER_NAMES),
11249
+ configured: boolean(),
11250
+ enabled: boolean(),
11251
+ health: _enum2(["ok", "error", "disabled", "incomplete"]),
11252
+ connected: boolean(),
11253
+ error: string2().optional(),
11254
+ webhookUrl: string2(),
11255
+ mode: string2().optional(),
11256
+ gateway: object2({
11257
+ state: _enum2(["running", "backoff", "stopped"]),
11258
+ since: string2(),
11259
+ restarts: number2()
11260
+ }).optional(),
11261
+ guilds: object2({ count: number2(), names: array2(string2()) }).optional()
11262
+ }))
11263
+ });
11264
+ var DEFAULT_MODES = {
11265
+ telegram: "webhook",
11266
+ slack: "webhook"
11267
+ };
11268
+ var NOT_RUNNING = "The adapter is starting, or the last configuration save is still applying. Refresh in a few seconds.";
11269
+ var SLACK_CLASH_CAUSE = "the Slack adapter conflicts with the built-in Slack integration (set SLACK_DISABLE=true)";
11270
+ var MAX_STATUS_ERROR_CHARS = 300;
11271
+ function statusError(message) {
11272
+ return scrubSecrets(message).slice(0, MAX_STATUS_ERROR_CHARS);
11273
+ }
11274
+ function readRawAdapters() {
11275
+ const raw = process.env.CHAT_SDK_ADAPTERS?.trim();
11276
+ if (!raw)
11277
+ return {};
11278
+ try {
11279
+ const parsed = JSON.parse(raw);
11280
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
11281
+ return {};
11282
+ const out = {};
11283
+ for (const name of CHAT_SDK_ADAPTER_NAMES) {
11284
+ const value = parsed[name];
11285
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
11286
+ out[name] = value;
11287
+ }
11288
+ }
11289
+ return out;
11290
+ } catch {
11291
+ return {};
11292
+ }
11293
+ }
11294
+ function healthyChatSdkAdapters() {
11295
+ const raw = readRawAdapters();
11296
+ const health = getChatSdkHealth();
11297
+ return CHAT_SDK_ADAPTER_NAMES.filter((name) => raw[name] !== undefined && isAdapterEntryEnabled(raw[name]) && health[name]?.status === "ok");
11298
+ }
11299
+ function chatSdkWebhookUrl(name) {
11300
+ return `${getPublicMcpBaseUrl()}/api/integrations/chat/${name}/webhook`;
11301
+ }
11302
+ async function discordGuildsFor(config, health) {
11303
+ if (health?.status !== "ok" || health.gateway?.state !== "running")
11304
+ return;
11305
+ const raw = config.adapters.discord?.botToken;
11306
+ const token = typeof raw === "function" ? await raw() : raw;
11307
+ if (typeof token !== "string" || token.length === 0)
11308
+ return;
11309
+ return fetchDiscordGuilds(token);
11310
+ }
11311
+ async function getChatSdkStatus() {
11312
+ const config = await getChatSdkConfig();
11313
+ const raw = readRawAdapters();
11314
+ const runtimeHealth = getChatSdkHealth();
11315
+ const slackClash = raw.slack !== undefined && !isEnvFlagEnabled("SLACK_DISABLE", false);
11316
+ const blockedCause = config.error ?? (config.enabled && slackClash ? SLACK_CLASH_CAUSE : undefined);
11317
+ const discordGuilds = await discordGuildsFor(config, runtimeHealth.discord);
11318
+ const adapters = CHAT_SDK_ADAPTER_NAMES.map((name) => {
11319
+ const configured = raw[name] !== undefined;
11320
+ const enabled = isAdapterEntryEnabled(raw[name]);
11321
+ const current = runtimeHealth[name];
11322
+ const incomplete = config.incomplete?.[name];
11323
+ const rawMode = raw[name]?.mode;
11324
+ const mode = typeof rawMode === "string" ? rawMode : configured ? DEFAULT_MODES[name] : undefined;
11325
+ let health = "disabled";
11326
+ let error;
11327
+ if (current) {
11328
+ health = current.status;
11329
+ const showWarning = current.status === "error" || current.gateway?.state === "backoff";
11330
+ error = current.error ?? (showWarning ? current.lastWarning : undefined);
11331
+ } else if (incomplete) {
11332
+ health = "incomplete";
11333
+ error = incomplete;
11334
+ } else if (configured && !enabled) {
11335
+ error = "Turned off on the card. The configuration is kept.";
11336
+ } else if (config.enabled && configured) {
11337
+ error = blockedCause ? `Not started: ${blockedCause}` : NOT_RUNNING;
11338
+ }
11339
+ return {
11340
+ name,
11341
+ configured,
11342
+ enabled,
11343
+ health,
11344
+ connected: configured && enabled && health === "ok",
11345
+ ...error ? { error: statusError(error) } : {},
11346
+ webhookUrl: chatSdkWebhookUrl(name),
11347
+ ...mode ? { mode } : {},
11348
+ ...current?.gateway ? { gateway: current.gateway } : {},
11349
+ ...name === "discord" && discordGuilds ? { guilds: discordGuilds } : {}
11350
+ };
11351
+ });
11352
+ return {
11353
+ enabled: config.enabled,
11354
+ slackClash,
11355
+ ...config.error ? { error: statusError(config.error) } : {},
11356
+ adapters
11357
+ };
11358
+ }
11359
+
11360
+ class ChatSdkActionError extends Error {
11361
+ status;
11362
+ constructor(message, status) {
11363
+ super(message);
11364
+ this.status = status;
11365
+ this.name = "ChatSdkActionError";
11366
+ }
11367
+ }
11368
+ async function callBotApi(baseUrl, token, method, body) {
11369
+ try {
11370
+ return await callTelegramBotApi(baseUrl, token, method, body);
11371
+ } catch (error) {
11372
+ if (error instanceof TelegramBotApiError)
11373
+ throw new ChatSdkActionError(error.message, 502);
11374
+ throw error;
11375
+ }
11376
+ }
11377
+ async function registerTelegramWebhook() {
11378
+ const config = await getChatSdkConfig();
11379
+ if (!config.enabled) {
11380
+ throw new ChatSdkActionError("The Chat SDK channel is disabled (CHAT_SDK_ENABLED is not true). Enable it and restart the API first", 400);
11381
+ }
11382
+ if (config.error)
11383
+ throw new ChatSdkActionError(statusError(config.error), 400);
11384
+ const telegram = config.adapters.telegram;
11385
+ if (!telegram) {
11386
+ throw new ChatSdkActionError("Telegram is not configured in CHAT_SDK_ADAPTERS", 400);
11387
+ }
11388
+ if (telegram.mode !== "webhook") {
11389
+ throw new ChatSdkActionError("Telegram runs in polling mode; a registered webhook would stop polling", 400);
11390
+ }
11391
+ const secretToken = telegram.secretToken;
11392
+ if (typeof secretToken !== "string" || secretToken.length === 0) {
11393
+ throw new ChatSdkActionError("Telegram webhook mode needs a secretToken", 400);
11394
+ }
11395
+ const rawToken = telegram.botToken;
11396
+ const token = typeof rawToken === "function" ? await rawToken() : rawToken;
11397
+ if (typeof token !== "string" || token.length === 0) {
11398
+ throw new ChatSdkActionError("Telegram botToken is empty", 400);
11399
+ }
11400
+ const baseUrl = resolveAdapterApiUrl("telegram");
11401
+ const webhookUrl = chatSdkWebhookUrl("telegram");
11402
+ await callBotApi(baseUrl, token, "setWebhook", { url: webhookUrl, secret_token: secretToken });
11403
+ const info = await callBotApi(baseUrl, token, "getWebhookInfo", {});
11404
+ if (info === null || typeof info !== "object" || typeof info.url !== "string") {
11405
+ throw new ChatSdkActionError("Telegram getWebhookInfo returned an unexpected result", 502);
11406
+ }
11407
+ return { webhookUrl, webhookInfo: info };
11408
+ }
11409
+
11410
+ // src/be/checklist.ts
11411
+ init_rbac();
11412
+ init_secret_scrubber();
11413
+ init_automation_preflight();
11414
+ init_db4();
11415
+ init_session_tree();
11416
+ init_oauth();
11417
+ init_rbac_roles();
11418
+
11419
+ class ChecklistError extends Error {
11420
+ status;
11421
+ constructor(message, status) {
11422
+ super(message);
11423
+ this.status = status;
11424
+ }
11425
+ }
11426
+ var UNSTORED_DEFAULT_AT = "1970-01-01T00:00:00.000Z";
11427
+ async function userGrantCanEditSwarm(userId) {
11428
+ if (!isRbacEnabled())
11429
+ return null;
11430
+ const grant = await getUserGrant2(userId);
11431
+ return grant.grantsAll || grant.verbs.has("config.write.any");
11432
+ }
11433
+ function defaultRows(userId) {
11434
+ const row = (id, scope, kind, label, href, sortOrder) => ({
11435
+ id,
11436
+ scope,
11437
+ userId: scope === "user" ? userId : null,
11438
+ kind,
11439
+ label,
11440
+ href,
11441
+ meta: null,
11442
+ sortOrder,
11443
+ status: "open",
11444
+ statusChangedAt: null,
11445
+ statusChangedBy: null,
11446
+ statusChangedByName: null,
11447
+ statusReason: null,
11448
+ nudgedAt: null,
11449
+ nudgedTaskId: null,
11450
+ createdAt: UNSTORED_DEFAULT_AT,
11451
+ lastUpdatedAt: UNSTORED_DEFAULT_AT
11452
+ });
11453
+ return [
11454
+ row("swarm:channel", "swarm", "channel", "Connect a chat channel", "/integrations/channels", 0),
11455
+ row("swarm:tool", "swarm", "tool", "Connect work tools", "/integrations/tools", 1),
11456
+ ...userId ? [
11457
+ row(`user:${userId}:use_case`, "user", "use_case", "Plan your first use case", "/sessions", 2)
11458
+ ] : []
11459
+ ];
11460
+ }
11461
+ async function seedChecklist(userId) {
11462
+ const db = getDbClient2();
11463
+ await db.run(`INSERT OR IGNORE INTO checklist_items (id, scope, kind, label, href, sortOrder)
11464
+ VALUES ('swarm:channel', 'swarm', 'channel', 'Connect a chat channel', '/integrations/channels', 0),
11465
+ ('swarm:tool', 'swarm', 'tool', 'Connect work tools', '/integrations/tools', 1)`);
11466
+ if (userId) {
11467
+ await db.run(`INSERT OR IGNORE INTO checklist_items
11468
+ (id, scope, userId, kind, label, href, sortOrder, created_by, updated_by)
11469
+ VALUES (?, 'user', ?, 'use_case', 'Plan your first use case', '/sessions', 2, ?, ?)`, [`user:${userId}:use_case`, userId, userId, userId]);
11470
+ }
11471
+ }
11472
+ async function checklistRows(userId) {
11473
+ const rows = await getDbClient2().query(`SELECT c.*, CASE WHEN c.statusChangedBy LIKE 'lead:%' THEN 'Lead' ELSE u.name END AS statusChangedByName
11474
+ FROM checklist_items c LEFT JOIN users u ON u.id = c.statusChangedBy
11475
+ WHERE c.scope = 'swarm' OR (c.scope = 'user' AND c.userId = ?)`, [userId]);
11476
+ const stored = new Set(rows.map((row) => row.id));
11477
+ const all = [...rows, ...defaultRows(userId).filter((row) => !stored.has(row.id))];
11478
+ const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11479
+ return all.sort((a, b) => a.sortOrder - b.sortOrder || cmp(a.createdAt, b.createdAt) || cmp(a.id, b.id));
11480
+ }
11481
+ function parseMeta(raw) {
11482
+ if (!raw)
11483
+ return null;
11484
+ try {
11485
+ const value = JSON.parse(raw);
11486
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
11487
+ } catch {
11488
+ return null;
11489
+ }
11490
+ }
11491
+ async function getUseCaseSignal(userId) {
11492
+ if (!userId)
11493
+ return false;
11494
+ const keys = await getDbClient2().query(`SELECT "key", MAX(createdAt) AS newest FROM (
11495
+ SELECT "key", createdAt FROM scheduled_tasks WHERE created_by = ?
11496
+ UNION ALL SELECT "key", createdAt FROM pages WHERE created_by = ?
11497
+ UNION ALL SELECT "key", createdAt FROM workflows WHERE created_by = ?
11498
+ ) GROUP BY "key" ORDER BY newest DESC, "key" LIMIT 500`, [userId, userId, userId]);
11499
+ const groups = keys.map(({ key }) => key).filter(isGroupKey).slice(0, 100);
11500
+ if (groups.length === 0)
11501
+ return false;
11502
+ const query = sessionSummaryQuery({ keyPrefixes: groups, viewer: { userId, scope: "all" } });
11503
+ const read = await getDbClient2().get(`SELECT 1 AS found FROM (${query.sql}) WHERE readState = 'read' LIMIT 1`, query.params);
11504
+ return read !== null;
11505
+ }
11506
+ function lazySignals(userId) {
11507
+ const once = (fn) => {
11508
+ let value;
11509
+ return () => {
11510
+ value ??= fn();
11511
+ return value;
11512
+ };
11513
+ };
11514
+ const flags = once(async () => setupIntegrationFlags(await getAutomationSetupStates()));
11515
+ const adapters = once(async () => {
11516
+ const names = new Set(healthyChatSdkAdapters());
11517
+ if ((await flags()).slack)
11518
+ names.add("slack");
11519
+ return names;
11520
+ });
11521
+ const tool = once(async () => {
11522
+ const f = await flags();
11523
+ if (f.github || f.gitlab || f.bitbucket || f.linear || f.jira)
11524
+ return true;
11525
+ return await hasOAuthTokens("google") || await hasOAuthTokens("microsoft");
11526
+ });
11527
+ const plannedUseCase = once(() => getUseCaseSignal(userId));
11528
+ return async (row, meta) => {
11529
+ if (row.kind === "custom")
11530
+ return null;
11531
+ if (row.kind === "channel") {
11532
+ const names = await adapters();
11533
+ return typeof meta?.adapter === "string" ? names.has(meta.adapter) : names.size > 0;
11534
+ }
11535
+ return row.kind === "tool" ? tool() : plannedUseCase();
11536
+ };
11537
+ }
11538
+ function toItem(row, meta, signal, userId, canEditSwarm) {
11539
+ return {
11540
+ id: row.id,
11541
+ scope: row.scope,
11542
+ userId: row.userId,
11543
+ kind: row.kind,
11544
+ label: row.label,
11545
+ href: row.href,
11546
+ meta,
11547
+ sortOrder: row.sortOrder,
11548
+ status: row.status,
11549
+ statusChangedAt: row.statusChangedAt,
11550
+ statusChangedBy: row.statusChangedBy,
11551
+ statusChangedByName: row.statusChangedByName,
11552
+ statusReason: row.statusReason,
11553
+ nudgedAt: row.nudgedAt,
11554
+ nudgedTaskId: row.nudgedTaskId,
11555
+ signal,
11556
+ done: row.status === "done" || signal === true,
11557
+ editable: row.scope === "swarm" ? canEditSwarm : row.userId === userId,
11558
+ createdAt: row.createdAt,
11559
+ lastUpdatedAt: row.lastUpdatedAt
11560
+ };
11561
+ }
11562
+ async function listChecklist(userId, canEditSwarm = false) {
11563
+ const signalOf = lazySignals(userId);
11564
+ return Promise.all((await checklistRows(userId)).map(async (row) => {
11565
+ const meta = parseMeta(row.meta);
11566
+ const signal = row.status === "done" ? null : await signalOf(row, meta);
11567
+ return toItem(row, meta, signal, userId, canEditSwarm);
11568
+ }));
11569
+ }
11570
+ async function mutateChecklist(actor, action) {
11571
+ const id = await getDbClient2().transaction(async (tx) => {
11572
+ await seedChecklist(actor.userId);
11573
+ const id = action.action === "add" ? crypto.randomUUID() : action.id;
11574
+ const row = action.action === "add" ? action : await tx.get("SELECT * FROM checklist_items WHERE id = ?", [id]);
11575
+ if (!row)
11576
+ throw new ChecklistError("Checklist item not found", 404);
11577
+ if (row.scope === "swarm" && !actor.canEditSwarm) {
11578
+ throw new ChecklistError("Swarm checklist items require config.write.any", 403);
11579
+ }
11580
+ if (row.scope === "user") {
11581
+ if (!actor.userId)
11582
+ throw new ChecklistError("A user is required for user checklist items", action.action === "add" ? 400 : 403);
11583
+ if (action.action !== "add" && "userId" in row && row.userId !== actor.userId) {
11584
+ throw new ChecklistError("This checklist item belongs to another user", 403);
11585
+ }
11586
+ }
11587
+ const now = new Date().toISOString();
11588
+ if (action.action === "add") {
11589
+ const userId = action.scope === "user" ? actor.userId : null;
11590
+ const adapter = action.kind === "channel" ? action.meta?.adapter : undefined;
11591
+ if (typeof adapter === "string") {
11592
+ const open = await tx.get(`SELECT id FROM checklist_items
11593
+ WHERE kind = 'channel' AND status = 'open' AND scope = ? AND userId IS ?
11594
+ AND CASE WHEN json_valid(meta) THEN json_extract(meta, '$.adapter') END = ?`, [action.scope, userId, adapter]);
11595
+ if (open)
11596
+ throw new ChecklistError(`An open item already connects ${adapter}`, 409);
11597
+ }
11598
+ const max = await tx.get("SELECT COALESCE(MAX(sortOrder), -1) + 1 AS sortOrder FROM checklist_items WHERE scope = ? AND userId IS ?", [action.scope, userId]);
11599
+ await tx.run(`INSERT INTO checklist_items
11600
+ (id, scope, userId, kind, label, href, meta, sortOrder, createdAt, lastUpdatedAt, created_by, updated_by)
11601
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
11602
+ id,
11603
+ action.scope,
11604
+ userId,
11605
+ action.kind,
11606
+ scrubSecrets(action.label),
11607
+ action.href ? scrubSecrets(action.href) : null,
11608
+ action.meta ? scrubSecrets(JSON.stringify(action.meta)) : null,
11609
+ max.sortOrder,
11610
+ now,
11611
+ now,
11612
+ actor.id,
11613
+ actor.id
11614
+ ]);
11615
+ } else if (action.action === "reorder") {
11616
+ await tx.run("UPDATE checklist_items SET sortOrder = ?, lastUpdatedAt = ?, updated_by = ? WHERE id = ?", [action.sortOrder, now, actor.id, id]);
11617
+ } else {
11618
+ const status = action.action === "remove" ? "removed" : action.action === "done" ? "done" : "open";
11619
+ await tx.run(`UPDATE checklist_items SET status = ?, statusChangedAt = ?, statusChangedBy = ?,
11620
+ statusReason = ?, lastUpdatedAt = ?, updated_by = ? WHERE id = ?`, [
11621
+ status,
11622
+ now,
11623
+ actor.id,
11624
+ action.action === "restore" || !action.reason ? null : scrubSecrets(action.reason),
11625
+ now,
11626
+ actor.id,
11627
+ id
11628
+ ]);
11629
+ }
11630
+ return id;
11631
+ });
11632
+ const items = await listChecklist(actor.userId, actor.canEditSwarm);
11633
+ return items.find((item) => item.id === id);
11634
+ }
11635
+ async function firstOpenItem(userId, canEditSwarm) {
11636
+ const signalOf = lazySignals(userId);
11637
+ for (const row of await checklistRows(userId)) {
11638
+ const editable = row.scope === "swarm" ? canEditSwarm : row.userId === userId;
11639
+ if (!editable || row.status !== "open" || row.nudgedAt !== null)
11640
+ continue;
11641
+ const meta = parseMeta(row.meta);
11642
+ const signal = await signalOf(row, meta);
11643
+ if (signal === false)
11644
+ return toItem(row, meta, signal, userId, canEditSwarm);
11645
+ }
11646
+ return null;
11647
+ }
11648
+ async function markNudged(itemId, taskId, userId) {
11649
+ await seedChecklist(userId);
11650
+ const now = new Date().toISOString();
11651
+ await getDbClient2().run("UPDATE checklist_items SET nudgedAt = ?, nudgedTaskId = ?, lastUpdatedAt = ? WHERE id = ?", [now, taskId, now, itemId]);
11652
+ }
11653
+
11654
+ // src/http/checklist.ts
11655
+ init_rbac();
11656
+ init_types5();
11657
+ init_favorite_owner();
11658
+ init_request_principal();
11659
+ init_route_def();
11660
+ init_utils2();
11661
+ var getChecklist = route({
11662
+ method: "get",
11663
+ path: "/api/checklist",
11664
+ pattern: ["api", "checklist"],
11665
+ summary: "Read the post-onboarding checklist",
11666
+ tags: ["Checklist"],
11667
+ responses: {
11668
+ 200: {
11669
+ description: "Checklist items and swarm edit permission",
11670
+ schema: object2({ items: array2(ChecklistItemSchema), canEditSwarm: boolean() })
11671
+ }
11672
+ }
11673
+ });
11674
+ var addChecklistItem = route({
11675
+ method: "post",
11676
+ path: "/api/checklist/items",
11677
+ pattern: ["api", "checklist", "items"],
11678
+ summary: "Add a checklist item",
11679
+ tags: ["Checklist"],
11680
+ rbac: { permission: "checklist.write.own" },
11681
+ body: object2({
11682
+ kind: _enum2(["channel", "tool", "use_case", "custom"]),
11683
+ label: string2().min(1).max(200),
11684
+ href: string2().max(500).regex(/^\/(?!\/)/, "href must be an in-app path starting with /").optional(),
11685
+ scope: _enum2(["swarm", "user"]),
11686
+ meta: looseObject({ adapter: string2().min(1).max(64).optional() }).refine((meta) => JSON.stringify(meta).length <= 1024, {
11687
+ message: "meta must be at most 1024 characters as JSON"
11688
+ }).optional()
11689
+ }),
11690
+ responses: {
11691
+ 201: { description: "Added checklist item", schema: object2({ item: ChecklistItemSchema }) },
11692
+ 400: { description: "A user is required for user items" },
11693
+ 403: { description: "The caller cannot edit swarm items" },
11694
+ 409: { description: "An open channel item for the same adapter already exists" }
11695
+ }
11696
+ });
11697
+ var patchChecklistItem = route({
11698
+ method: "patch",
11699
+ path: "/api/checklist/items/{id}",
11700
+ pattern: ["api", "checklist", "items", null],
11701
+ summary: "Update a checklist item",
11702
+ tags: ["Checklist"],
11703
+ rbac: { permission: "checklist.write.own" },
11704
+ params: object2({ id: string2() }),
11705
+ body: object2({
11706
+ action: _enum2(["remove", "restore", "done", "reorder"]),
11707
+ reason: string2().max(500).optional(),
11708
+ sortOrder: number2().int().optional()
11709
+ }).refine((body) => body.action !== "reorder" || body.sortOrder !== undefined, {
11710
+ message: "Reorder requires sortOrder",
11711
+ path: ["sortOrder"]
11712
+ }),
11713
+ responses: {
11714
+ 200: { description: "Updated checklist item", schema: object2({ item: ChecklistItemSchema }) },
11715
+ 400: { description: "Invalid update" },
11716
+ 403: { description: "The caller cannot edit this item" },
11717
+ 404: { description: "Checklist item not found" }
11718
+ }
11719
+ });
11720
+ function decodePathId(raw) {
11721
+ try {
11722
+ return decodeURIComponent(raw);
11723
+ } catch {
11724
+ return raw;
11725
+ }
11726
+ }
11727
+ async function handleChecklist(req, res, pathSegments, queryParams, myAgentId) {
11728
+ if (!getChecklist.match(req.method, pathSegments) && !addChecklistItem.match(req.method, pathSegments) && !patchChecklistItem.match(req.method, pathSegments))
11729
+ return false;
11730
+ const owner = await resolveHttpFavoriteOwner(req, myAgentId);
11731
+ if (!owner) {
11732
+ jsonError(res, "An authenticated principal is required", 401);
11733
+ return true;
11734
+ }
11735
+ const principal = await resolveRequestPrincipal(req, myAgentId, { precedence: "agent-first" });
11736
+ if (!principal) {
11737
+ jsonError(res, "An authenticated principal is required", 401);
11738
+ return true;
11739
+ }
11740
+ if (principal.kind === "agent" && !getChecklist.match(req.method, pathSegments) && !can({ principal, verb: "checklist.write.agent", resource: { kind: "none" }, source: "http" }).allow) {
11741
+ jsonError(res, "Only the Lead agent can change the checklist", 403);
11742
+ return true;
11743
+ }
11744
+ const grantAllows = principal.kind !== "agent" && owner.userId ? await userGrantCanEditSwarm(owner.userId) : null;
11745
+ const canEditSwarm = grantAllows ?? (principal.kind === "operator" || can({ principal, verb: "config.write.any", resource: { kind: "none" }, source: "http" }).allow);
11746
+ const actor = {
11747
+ id: principal.kind === "agent" ? `lead:${principal.agentId}` : owner.actorId,
11748
+ userId: owner.userId,
11749
+ canEditSwarm
11750
+ };
11751
+ try {
11752
+ if (getChecklist.match(req.method, pathSegments)) {
11753
+ const parsed = await getChecklist.parse(req, res, pathSegments, queryParams);
11754
+ if (!parsed)
11755
+ return true;
11756
+ getChecklist.respond(res, 200, {
11757
+ items: await listChecklist(owner.userId, canEditSwarm),
11758
+ canEditSwarm
11759
+ });
11760
+ } else if (addChecklistItem.match(req.method, pathSegments)) {
11761
+ const parsed = await addChecklistItem.parse(req, res, pathSegments, queryParams);
11762
+ if (!parsed)
11763
+ return true;
11764
+ addChecklistItem.respond(res, 201, {
11765
+ item: await mutateChecklist(actor, { action: "add", ...parsed.body })
11766
+ });
11767
+ } else {
11768
+ const parsed = await patchChecklistItem.parse(req, res, pathSegments, queryParams);
11769
+ if (!parsed)
11770
+ return true;
11771
+ const { action, sortOrder, reason } = parsed.body;
11772
+ const id = decodePathId(parsed.params.id);
11773
+ const item = await mutateChecklist(actor, action === "reorder" ? { action, id, sortOrder } : { action, id, reason });
11774
+ patchChecklistItem.respond(res, 200, { item });
11775
+ }
11776
+ } catch (error) {
11777
+ if (!(error instanceof ChecklistError))
11778
+ throw error;
11779
+ jsonError(res, error.message, error.status);
11780
+ }
11781
+ return true;
11782
+ }
11783
+
10707
11784
  // src/http/codex-oauth-accounts.ts
10708
11785
  init_zod();
10709
11786
  init_crypto();
@@ -10895,7 +11972,7 @@ async function upsertCodexDeviceFlow(input) {
10895
11972
 
10896
11973
  // src/be/onboarding.ts
10897
11974
  init_telemetry();
10898
- init_types4();
11975
+ init_types5();
10899
11976
  init_request_auth_context();
10900
11977
  init_zod_openapi();
10901
11978
  init_db4();
@@ -12507,7 +13584,7 @@ async function handleComb(req, res, pathSegments, queryParams, myAgentId) {
12507
13584
  // src/http/context.ts
12508
13585
  init_zod();
12509
13586
  init_db4();
12510
- init_types4();
13587
+ init_types5();
12511
13588
  init_route_def();
12512
13589
  init_utils2();
12513
13590
  var PostContextResponseSchema = object2({
@@ -12624,7 +13701,7 @@ init_db_query();
12624
13701
  // src/http/events.ts
12625
13702
  init_zod();
12626
13703
  init_events();
12627
- init_types4();
13704
+ init_types5();
12628
13705
  init_route_def();
12629
13706
  init_session_access();
12630
13707
  init_utils2();
@@ -12842,16 +13919,16 @@ declare module "swarm-extension" {
12842
13919
  | "schedule"
12843
13920
  | "slack"
12844
13921
  | "agentmail"
13922
+ | "mcp"
13923
+ | "api"
13924
+ | "ui"
12845
13925
  | "github"
12846
13926
  | "gitlab"
12847
13927
  | "azure-devops"
12848
13928
  | "bitbucket"
13929
+ | "system"
12849
13930
  | "linear"
12850
13931
  | "jira"
12851
- | "mcp"
12852
- | "api"
12853
- | "ui"
12854
- | "system"
12855
13932
  | "comb"
12856
13933
  | undefined;
12857
13934
  routingReason?:
@@ -12993,16 +14070,16 @@ declare module "swarm-extension" {
12993
14070
  | "schedule"
12994
14071
  | "slack"
12995
14072
  | "agentmail"
14073
+ | "mcp"
14074
+ | "api"
14075
+ | "ui"
12996
14076
  | "github"
12997
14077
  | "gitlab"
12998
14078
  | "azure-devops"
12999
14079
  | "bitbucket"
14080
+ | "system"
13000
14081
  | "linear"
13001
14082
  | "jira"
13002
- | "mcp"
13003
- | "api"
13004
- | "ui"
13005
- | "system"
13006
14083
  | "comb";
13007
14084
  tags: string[];
13008
14085
  priority: number;
@@ -13176,7 +14253,7 @@ declare module "swarm-extension" {
13176
14253
 
13177
14254
  export type SteerMode = "steer" | "queue";
13178
14255
 
13179
- export type SteeringSource = "chat" | "script" | "slack" | "mcp" | "api" | "ui";
14256
+ export type SteeringSource = "chat" | "script" | "slack" | "mcp" | "api" | "ui" | "app-page";
13180
14257
 
13181
14258
  export type RequestInfo = {
13182
14259
  sessionId: string | undefined;
@@ -13770,7 +14847,7 @@ declare module "swarm-extension" {
13770
14847
  // src/be/extensions/validate.ts
13771
14848
  init_manifest_format();
13772
14849
  init_import_allowlist();
13773
- init_types4();
14850
+ init_types5();
13774
14851
  init_typecheck();
13775
14852
  async function validateBundle(input) {
13776
14853
  const parsedManifest = ExtensionManifestSchema.safeParse(input.manifest);
@@ -15735,6 +16812,123 @@ export default extension;
15735
16812
  },
15736
16813
  readme: '# slack-reply-gate\n\nLead is woken by every human message in a Slack thread the swarm takes part in, including "lol", an emoji, or two people chatting with each other. This extension asks a SystemOne decision model, Jev ([TypeSafe](https://typesafe.ai)) or Clef (Cloudflare Workers AI), whether Lead should answer a new thread message, and drops the wake-up when it should not.\n\nInstall config:\n\n```json\n{ "mode": "shadow" }\n```\n\nStart in `shadow`, read the decisions in KV for a few days, then switch to `enforce`.\n\n## Modes\n\n| `mode` | Effect |\n|---|---|\n| `off` | Never evaluates. |\n| `shadow` (default) | Asks the model and records the verdict. Never blocks. |\n| `enforce` | Asks the model, records the verdict, and blocks the Lead task when the answer is no. The message gets :mute: instead: no Lead task, no reply, no outcome card. |\n\n## What it gates\n\nHook: `pre.task.create`, for tasks with origin `slack` whose description carries the thread buffer\'s header `[Thread follow-up — N message(s) buffered]`. Those are the non-mention thread replies that `src/slack/thread-buffer.ts` batches into a Lead task. A direct @mention of the bot creates a task without that header and is never gated.\n\nThe header counts only at the start of the description or right after the closing `</thread_context>`. Thread context quotes old messages verbatim, and an older Lead reply can quote the header itself, so a header inside the context is ignored. Only the text after the real header is treated as new.\n\n## Decision\n\n1. A follow-up with downloaded files (status `draft`) passes without a decision call.\n2. **@mention pass-through.** A new message that @mentions Lead passes without a decision call. A mention is the bot mention the engine rewrites to `<@U…> (that\'s you)`, a resolved `<@U…|lead>`, or a literal `@lead` (any name in `leadAliases`). Only the new messages are scanned, never the thread context, so an old mention earlier in the thread does not pass later banter.\n3. Otherwise one decision call (one `choice` question, see [Provider](#provider)) with the new message(s), the sender kind, and the last `contextMessages` thread messages. Labels: `direct_ask`, `followup_to_lead`, `instruction_to_lead`, `reaction_only`, `banter_between_others`, `not_addressed_to_lead`, `other`.\n4. The answer is no only when the top label is `reaction_only`, `banter_between_others`, or `not_addressed_to_lead`, and the summed probability of those three labels is at least `minConfidence`. A split between two skip labels is still a skip. A skip label below the threshold replies. With no probabilities, the top label\'s confidence stands in for the sum. With neither probabilities nor a confidence, the threshold is not applied and a skip label skips (in `enforce`, the message is dropped).\n\nSeveral buffered messages are judged together. One mention in any of them passes the batch.\n\n## Provider\n\nThe decision is made on the API server by the `system-one-decide` tool (`ctx.swarm.systemOne_decide`), the same path a `system-one-decision` workflow node takes. The server reads the provider\'s credential, sends the request, and validates the answer, so every SystemOne host works and no key enters the hook.\n\n| `provider` | Model | Credential |\n|---|---|---|\n| `typesafe` | Jev, `model` (default `jev-latest`) | `TYPESAFE_API_KEY` |\n| `openrouter` | Jev, `openrouterModel` (default `typesafe/jev-1.13`) | `OPENROUTER_API_KEY` |\n| `cloudflare` | Clef, `cloudflareModel` (default `clef`, or `clef-flash`) | `CLOUDFLARE_API_TOKEN` (or `CLOUDFLARE_API_KEY`) and `CLOUDFLARE_ACCOUNT_ID` |\n| `laya`, `openai` | The host\'s default model | See the workflows guide |\n| `auto` (default) | The first of typesafe, openrouter, cloudflare whose credential is set. A provider the server refuses for a deployment setting (openrouter when `OPENROUTER_BASE_URL` points at a gateway) is skipped for the next one | |\n\nWith no credential for `auto`, every message fails open and the KV row names the secrets. Each decision row records the `provider` that answered. `minConfidence` was tuned on Jev; check Clef\'s verdicts in `shadow` before you enforce on it.\n\n## Fail open\n\nEvery error lets the task through: a missing key, a provider error relayed by the server, a network error, a timeout, a malformed answer, or an unknown label. The handler never throws, so an outage cannot auto-disable the extension. Each failure is recorded as `fail-open` in KV and logged as a warning.\n\n## :mute: on drop (enforce)\n\nNo swarm tool or extension `ctx` method adds a Slack reaction, so the hook calls the Slack Web API with the bot token. It needs the `reactions:write` scope, which the Slack app already uses for its acceptance reactions.\n\n1. `reactions.remove` for each acceptance reaction the engine may have put on the triggering message: `eyes`, `heavy_plus_sign`, `zap`, `speech_balloon`, or their `SLACK_REACTION_ACCEPTED`, `SLACK_REACTION_BUFFERED`, `SLACK_REACTION_NOW`, and `SLACK_REACTION_STEERED` overrides. Slack only removes the bot\'s own reaction, so a human\'s :eyes: stays.\n2. `reactions.add` with `muteReaction` (default `mute`). `already_reacted` counts as success. Skipped when `muteReaction` is `""`.\n\nThe block returns first and the Slack calls run after it. A slow or failing Slack call never delays the drop or turns it back into a task. Set `muteReaction` to `""` for a true no-op: step 1 still clears the bot\'s acceptance reaction(s), and nothing is added.\n\n## Config\n\n| Key | Default | Notes |\n|---|---|---|\n| `mode` | `shadow` | `off`, `shadow`, or `enforce` |\n| `timeoutMs` | `3000` | Decision call timeout, capped at 4000 (the dispatcher cancels a handler at 5 s) |\n| `provider` | `auto` | `auto`, `typesafe`, `openrouter`, `cloudflare`, `laya`, or `openai`. See [Provider](#provider) |\n| `model` | `jev-latest` | Jev model on TypeSafe |\n| `openrouterModel` | `typesafe/jev-1.13` | Jev model on OpenRouter |\n| `cloudflareModel` | `clef` | Clef model on Cloudflare Workers AI |\n| `minConfidence` | `0.55` | Minimum summed skip probability to skip |\n| `contextMessages` | `6` | Thread messages sent to the model, 0 to 20 |\n| `leadAliases` | `["lead"]` | A literal `@alias` in a new message counts as a mention |\n| `botSlackUserIds` | `[]` | Slack user ids labelled `bot` as the sender for the model |\n| `muteReaction` | `mute` | Reaction for a dropped message; `""` only removes the acceptance reaction(s) |\n| `slackTimeoutMs` | `5000` | Timeout per Slack call |\n\n## Required secrets\n\nSet them as global `swarm_config` values. The server reads the provider credential from the global row when it makes the decision. `auto` and the Slack token read the API process environment, which loads global rows at boot and on config reload.\n\n- One provider credential from the [Provider](#provider) table is required for any evaluation. Without one, every message fails open. The `apiKey` config field of earlier versions is gone: the hook never holds a key, so store it as the global `TYPESAFE_API_KEY` secret.\n- `SLACK_BOT_TOKEN`: the Slack app\'s bot token. A swarm with Slack connected already has it. Without it, `enforce` still drops the message but cannot touch its reactions, and logs a `mute-error`.\n\nNo key is written to config, KV, logs, or a description.\n\n## KV namespace `ext:slack-reply-gate`\n\n- `d:<epochMs>:<channel>_<threadTs>`: one row per decision, with `action` (`pass`, `shadow-skip`, `skipped`, `fail-open`), `provider`, `reason`, `confidence`, `skipP`, `latencyMs`, `sender`, and a 300-character `preview`.\n- `m:<epochMs>:<channel>_<threadTs>`: one row per mute attempt, with `action` (`muted`, `unreacted` when `muteReaction` is `""`, `mute-error`), `removed`, `added`, and `errors`.\n- `last`: the latest decision. Mute rows never overwrite it.\n- Counters: `total`, `mention`, `files`, `reply`, `shadow-skip`, `skipped`, `error`, `muted`, `unreacted`, `mute-error`, and `reason:<label>`.\n\n## Known limits\n\n- When Lead already has an active task in the thread, the buffer steers that task instead of creating one, so `pre.task.create` does not fire and the gate does not run.\n- A blocked flush makes the thread buffer log a `TaskCreationBlockedError`. Nothing is lost: the next follow-up\'s `<thread_context>` carries the earlier messages.\n- A flush of several messages mutes only the triggering (last) message. The others keep their acceptance reaction.\n'
15737
16814
  },
16815
+ "sql-admin-only": {
16816
+ manifestFile: "manifest.json",
16817
+ manifest: {
16818
+ $schema: "../manifest.schema.json",
16819
+ name: "sql-admin-only",
16820
+ description: "Blocks db-query tool calls on tasks created by a non-admin user",
16821
+ version: "1.1.0",
16822
+ runtime: "api",
16823
+ assets: {
16824
+ hooks: "hooks.ts"
16825
+ }
16826
+ },
16827
+ files: {
16828
+ "hooks.ts": `import { block, type SwarmExtension } from "swarm-extension";
16829
+ import { z } from "zod";
16830
+
16831
+ export const config = z.object({});
16832
+
16833
+ /** MCP tools that run raw SQL. db-query is the only one today. */
16834
+ const SQL_TOOLS = new Set(["db-query"]);
16835
+
16836
+ const manifest = {
16837
+ name: "sql-admin-only",
16838
+ description: "Blocks db-query tool calls on tasks created by a non-admin user",
16839
+ version: "1.1.0",
16840
+ runtime: "api",
16841
+ assets: { hooks: "hooks.ts" },
16842
+ config,
16843
+ } as const;
16844
+
16845
+ /**
16846
+ * The task's creator and that user's \`users.role\`, the role the swarm shows for a
16847
+ * requester (for example "Alice (admin)"). RBAC roles do not work here: every user is
16848
+ * created with the RBAC \`admin\` role.
16849
+ */
16850
+ export const CREATOR_SQL = \`SELECT t.requestedByUserId, u.role
16851
+ FROM agent_tasks t
16852
+ LEFT JOIN users u ON u.id = t.requestedByUserId
16853
+ WHERE t.id = ?\`;
16854
+
16855
+ type Envelope = { success?: boolean; data?: { rows?: unknown[] }; rows?: unknown[] } | null;
16856
+
16857
+ const cell = (row: unknown, i: number, key: string): unknown =>
16858
+ Array.isArray(row) ? row[i] : (row as Record<string, unknown> | null)?.[key];
16859
+
16860
+ /**
16861
+ * The dispatcher fails a pre hook OPEN when it runs past
16862
+ * EXTENSION_HANDLER_TIMEOUT_MS (default 5s). Give the lookup a shorter budget so
16863
+ * a slow lookup ends in our own block, not in a silent allow.
16864
+ */
16865
+ const lookupBudgetMs = (): number => {
16866
+ const raw = Number(process.env.EXTENSION_HANDLER_TIMEOUT_MS);
16867
+ const handlerMs = Number.isFinite(raw) && raw > 0 ? raw : 5_000;
16868
+ return Math.floor(handlerMs * 0.6);
16869
+ };
16870
+
16871
+ const withDeadline = async <T>(work: Promise<T>, ms: number): Promise<T> => {
16872
+ let timer: ReturnType<typeof setTimeout> | undefined;
16873
+ try {
16874
+ return await Promise.race([
16875
+ work,
16876
+ new Promise<never>((_, reject) => {
16877
+ timer = setTimeout(() => reject(new Error(\`lookup timed out after \${ms}ms\`)), ms);
16878
+ }),
16879
+ ]);
16880
+ } finally {
16881
+ if (timer) clearTimeout(timer);
16882
+ }
16883
+ };
16884
+
16885
+ const extension: SwarmExtension<typeof manifest> = (api) => {
16886
+ api.on("pre.tool.call", async (event, ctx) => {
16887
+ const tool = event.tool;
16888
+ if (!SQL_TOOLS.has(tool)) return;
16889
+
16890
+ // No task context means no task creator: allow.
16891
+ const taskId = event.requestInfo?.sourceTaskId;
16892
+ if (!taskId) return;
16893
+
16894
+ // Creator lookup. A failed lookup blocks this SQL call only (fail closed).
16895
+ let creator: string;
16896
+ let role: string;
16897
+ try {
16898
+ const q = (await withDeadline(
16899
+ ctx.swarm.db_query({ sql: CREATOR_SQL, params: [taskId] }),
16900
+ lookupBudgetMs(),
16901
+ )) as Envelope;
16902
+ if (q?.success === false) throw new Error("db-query lookup returned success=false");
16903
+ const row = (q?.data?.rows ?? q?.rows ?? [])[0];
16904
+ // A successful lookup with no row: the id is not a task. The runner sends a
16905
+ // random correlation id for sessions with no task (pool or channel-message
16906
+ // triggers, src/commands/runner.ts effectiveTaskId). No task means no creator:
16907
+ // allow, the same as a missing header. Errors and timeouts above still block.
16908
+ if (!row) return;
16909
+ creator = String(cell(row, 0, "requestedByUserId") ?? "");
16910
+ role = String(cell(row, 1, "role") ?? "");
16911
+ } catch (err) {
16912
+ const message = err instanceof Error ? err.message : String(err);
16913
+ const reason = \`\${tool} is restricted to admin task creators, and the creator of task \${taskId} could not be verified (\${message}).\`;
16914
+ ctx.log.warn(reason, { tool, taskId });
16915
+ return block(reason);
16916
+ }
16917
+
16918
+ if (!creator) return;
16919
+ if (role.trim().toLowerCase() === "admin") return;
16920
+
16921
+ const reason = \`\${tool} is restricted to admin task creators. Task \${taskId} was created by user \${creator}, whose role is \${role ? \`"\${role}"\` : "not set"}.\`;
16922
+ ctx.log.warn(reason, { tool, taskId, requestedByUserId: creator });
16923
+ return block(reason);
16924
+ });
16925
+ };
16926
+
16927
+ export default extension;
16928
+ `
16929
+ },
16930
+ readme: "# sql-admin-only\n\nBlocks `db-query` tool calls made on a task whose creator (`requestedByUserId`) is not an admin. Every other tool call passes untouched.\n\n| Task creator | `db-query` |\n|---|---|\n| Not set, or the call has no task | Allowed |\n| The header's id has no task row (a session with no task) | Allowed |\n| Set, holds an admin role | Allowed |\n| Set, no admin role | Blocked |\n| Set, but the lookup fails or times out | Blocked |\n\nNo config. \"Admin\" means the creator's `users.role` is `admin` (case-insensitive), the role the swarm shows next to a requester's name. Only Lead (`manage-user`) and REST callers with `user.role.manage` can set it. RBAC roles are not used, because every user is created with the RBAC `admin` role. A creator whose user row is gone counts as non-admin.\n\nThe task comes from the call's `X-Source-Task-Id` header. The lookup gets 60% of `EXTENSION_HANDLER_TIMEOUT_MS` (default 5s), because the dispatcher lets a call through when a hook times out.\n\nCoverage limits:\n\n- Only agent MCP tool calls run `pre.tool.call`. Scripts calling `ctx.swarm.db_query`, extensions, and direct `POST /api/db-query` requests skip the hook.\n- A call without an `X-Source-Task-Id` header has no task, so it is allowed.\n"
16931
+ },
15738
16932
  "task-digest": {
15739
16933
  manifestFile: "manifest.yaml",
15740
16934
  manifest: {
@@ -15908,7 +17102,7 @@ function getCatalogEntry(name) {
15908
17102
  init_lifecycle();
15909
17103
  init_loader();
15910
17104
  init_rbac();
15911
- init_types4();
17105
+ init_types5();
15912
17106
  init_env_flag();
15913
17107
  init_secret_scrubber();
15914
17108
  init_request_principal();
@@ -16526,8 +17720,9 @@ async function handleExtensions(req, res, pathSegments, queryParams, agentId) {
16526
17720
 
16527
17721
  // src/http/favorites.ts
16528
17722
  init_zod();
17723
+ init_key();
16529
17724
  init_db4();
16530
- init_types4();
17725
+ init_types5();
16531
17726
  init_favorite_owner();
16532
17727
  init_route_def();
16533
17728
  init_utils2();
@@ -16574,6 +17769,7 @@ var putFavorite = route({
16574
17769
  row: UserFavoriteSchema.nullable()
16575
17770
  })
16576
17771
  },
17772
+ 400: { description: "Invalid asset key for a key favorite" },
16577
17773
  401: { description: "No authenticated principal context" }
16578
17774
  }
16579
17775
  });
@@ -16608,18 +17804,29 @@ async function handleFavorites(req, res, pathSegments, queryParams, myAgentId) {
16608
17804
  jsonError(res, "Authenticated principal required to update favorites", 401);
16609
17805
  return true;
16610
17806
  }
17807
+ let itemId = parsed.body.itemId;
17808
+ if (parsed.body.itemType === "key") {
17809
+ try {
17810
+ itemId = normalizeAssetKey(itemId);
17811
+ } catch (error) {
17812
+ if (!(error instanceof AssetKeyError))
17813
+ throw error;
17814
+ jsonError(res, error.message, 400);
17815
+ return true;
17816
+ }
17817
+ }
16611
17818
  const favorite = await setFavorite2({
16612
17819
  favoriteScope: owner.scope,
16613
17820
  userId: owner.userId,
16614
17821
  itemType: parsed.body.itemType,
16615
- itemId: parsed.body.itemId,
17822
+ itemId,
16616
17823
  favorite: parsed.body.favorite,
16617
17824
  actorId: owner.actorId
16618
17825
  });
16619
17826
  putFavorite.respond(res, 200, {
16620
17827
  favorite: parsed.body.favorite,
16621
17828
  itemType: parsed.body.itemType,
16622
- itemId: parsed.body.itemId,
17829
+ itemId,
16623
17830
  row: favorite
16624
17831
  });
16625
17832
  return true;
@@ -16918,6 +18125,142 @@ async function handleFleetBenchmark(req, res, pathSegments, queryParams) {
16918
18125
 
16919
18126
  // src/http/fs.ts
16920
18127
  init_zod();
18128
+
18129
+ // src/be/agent-fs-user-keys.ts
18130
+ init_secret_scrubber();
18131
+ init_rbac_roles();
18132
+ init_users();
18133
+
18134
+ class AgentFsKeyValidationError extends Error {
18135
+ }
18136
+ async function ensureUserAgentFsAccount(userId) {
18137
+ if (!await resolveApiUrl2()) {
18138
+ return { status: "off", reason: "AGENT_FS_API_URL is not configured" };
18139
+ }
18140
+ const user = await findUserById(userId);
18141
+ const email = user?.email?.trim() ?? "";
18142
+ if (!user || !email) {
18143
+ return { status: "pending", email, reason: "The swarm user is missing or has no email" };
18144
+ }
18145
+ const shared = await resolveAgentFsSharedContext2();
18146
+ if (!shared)
18147
+ return { status: "off", reason: "AGENT_FS_API_URL is not configured" };
18148
+ const pending = (reason) => ({
18149
+ status: "pending",
18150
+ email,
18151
+ orgId: shared.orgId,
18152
+ driveId: shared.driveId,
18153
+ reason: scrubSecrets(reason)
18154
+ });
18155
+ const grant = await getUserGrant2(userId);
18156
+ const role = grant.grantsAll || grant.verbs.has("task.fs.mutate") ? "editor" : "viewer";
18157
+ const members = await getCurrentOrgMembers2(shared.apiUrl, shared.authHeaders, shared.orgId);
18158
+ let member = members.find((candidate) => candidate.email === email.toLowerCase());
18159
+ let registeredKey;
18160
+ if (!member) {
18161
+ try {
18162
+ const registered = await agentFsRequest2(shared.apiUrl, "/auth/register", { method: "POST", body: { email } });
18163
+ if (typeof registered?.apiKey === "string" && registered.apiKey) {
18164
+ registeredKey = registered.apiKey;
18165
+ registerVolatileSecret(registeredKey, "AGENT_FS_USER_PRIMARY_KEY");
18166
+ }
18167
+ } catch (error) {
18168
+ if (!(error instanceof AgentFsRequestError2) || error.status >= 500)
18169
+ throw error;
18170
+ if (error.status !== 409)
18171
+ return pending(error.message);
18172
+ }
18173
+ }
18174
+ if (!member || roleRank2(member.role) < roleRank2(role)) {
18175
+ const invited = await inviteEmailToSharedOrg2(email, role);
18176
+ if (invited.status === "pending") {
18177
+ if (!registeredKey || !invited.token)
18178
+ return pending("The agent-fs org invite is pending");
18179
+ try {
18180
+ await agentFsRequest2(shared.apiUrl, `/invites/${encodeURIComponent(invited.token)}/accept`, {
18181
+ method: "POST",
18182
+ headers: { authorization: `Bearer ${registeredKey}` },
18183
+ allowConflict: true
18184
+ });
18185
+ } catch (error) {
18186
+ if (error instanceof AgentFsRequestError2 && error.status < 500) {
18187
+ return pending(`The agent-fs org invite could not be accepted: HTTP ${error.status}`);
18188
+ }
18189
+ throw new Error(`agent-fs invite accept failed${error instanceof AgentFsRequestError2 ? `: HTTP ${error.status}` : ""}`);
18190
+ }
18191
+ }
18192
+ member = (await getCurrentOrgMembers2(shared.apiUrl, shared.authHeaders, shared.orgId)).find((candidate) => candidate.email === email.toLowerCase());
18193
+ }
18194
+ if (!member?.userId || roleRank2(member.role) < roleRank2(role)) {
18195
+ return pending("The agent-fs org membership is not ready");
18196
+ }
18197
+ if (member.role !== "admin" && roleRank2(member.role) > roleRank2(role)) {
18198
+ try {
18199
+ await agentFsRequest2(shared.apiUrl, `/orgs/${encodeURIComponent(shared.orgId)}/members/${encodeURIComponent(member.userId)}`, { method: "PATCH", headers: shared.authHeaders, body: { role } });
18200
+ } catch (error) {
18201
+ if (!(error instanceof AgentFsRequestError2) || error.status >= 500)
18202
+ throw error;
18203
+ return pending(`The agent-fs org role could not be lowered to ${role}`);
18204
+ }
18205
+ }
18206
+ return {
18207
+ status: "ready",
18208
+ agentFsUserId: member.userId,
18209
+ email,
18210
+ displayName: user.name,
18211
+ orgId: shared.orgId,
18212
+ driveId: shared.driveId
18213
+ };
18214
+ }
18215
+ async function mintUserAgentFsKey(userId, label) {
18216
+ const sanitized = Array.from(label.replace(/\p{Cc}/gu, "").replace(/\s+/gu, " ").trim()).slice(0, 100).join("");
18217
+ if (!sanitized)
18218
+ throw new AgentFsKeyValidationError("The key label must contain visible text");
18219
+ const account = await ensureUserAgentFsAccount(userId);
18220
+ if (account.status !== "ready")
18221
+ return account;
18222
+ const shared = await resolveAgentFsSharedContext2();
18223
+ if (!shared)
18224
+ return { status: "off", reason: "AGENT_FS_API_URL is not configured" };
18225
+ try {
18226
+ const minted = await agentFsRequest2(shared.apiUrl, `/orgs/${encodeURIComponent(account.orgId)}/members/${encodeURIComponent(account.agentFsUserId)}/keys`, { method: "POST", headers: shared.authHeaders, body: { label: sanitized } });
18227
+ if (!minted.apiKey || !minted.id)
18228
+ throw new Error("agent-fs did not return a named key");
18229
+ registerVolatileSecret(minted.apiKey, `AGENT_FS_USER_KEY:${minted.id}`);
18230
+ return {
18231
+ status: "minted",
18232
+ apiKey: minted.apiKey,
18233
+ keyId: minted.id,
18234
+ label: minted.label,
18235
+ agentFsUserId: account.agentFsUserId,
18236
+ orgId: account.orgId,
18237
+ driveId: account.driveId
18238
+ };
18239
+ } catch (error) {
18240
+ if (error instanceof AgentFsRequestError2 && error.status === 404) {
18241
+ let memberMissing = false;
18242
+ try {
18243
+ memberMissing = JSON.parse(error.body)?.error === "NOT_FOUND";
18244
+ } catch {}
18245
+ if (memberMissing) {
18246
+ return {
18247
+ status: "pending",
18248
+ email: account.email,
18249
+ orgId: account.orgId,
18250
+ driveId: account.driveId,
18251
+ reason: scrubSecrets(error.message)
18252
+ };
18253
+ }
18254
+ return {
18255
+ status: "unsupported",
18256
+ reason: "Named user keys require agent-fs 0.18.17 or later"
18257
+ };
18258
+ }
18259
+ throw error;
18260
+ }
18261
+ }
18262
+
18263
+ // src/http/fs.ts
16921
18264
  init_db4();
16922
18265
 
16923
18266
  // src/be/db/tasks/draft-text.ts
@@ -16932,10 +18275,13 @@ ${block}`, new Date().toISOString(), taskId]);
16932
18275
  // src/http/fs.ts
16933
18276
  init_rbac_roles();
16934
18277
  init_task_attachment_store();
18278
+ init_users();
18279
+ init_config3();
16935
18280
  init_provider();
16936
18281
  init_registry2();
16937
18282
  init_rbac();
16938
- init_types4();
18283
+ init_types5();
18284
+ init_constants3();
16939
18285
 
16940
18286
  // src/utils/content-disposition.ts
16941
18287
  function attachmentContentDisposition(filename) {
@@ -16949,11 +18295,120 @@ function attachmentContentDisposition(filename) {
16949
18295
  init_request_auth_context();
16950
18296
  init_secret_scrubber();
16951
18297
  init_transcription();
18298
+ init_favorite_owner();
16952
18299
  init_request_principal();
16953
18300
  init_route_def();
16954
18301
  init_session_access();
16955
18302
  init_utils2();
16956
18303
  var SLOW_UPLOAD_LOG_MS = 3000;
18304
+ var fsKeyRateLimit = createIpRateLimiter({ capacity: 5, refillPerMs: 5 / 60000 });
18305
+ var fsContinueRateLimit = createIpRateLimiter({ capacity: 10, refillPerMs: 10 / 60000 });
18306
+ var fsMeRateLimit = createIpRateLimiter({ capacity: 20, refillPerMs: 20 / 60000 });
18307
+ var userAgentFsStateSchema = object2({
18308
+ status: _enum2(["ready", "pending", "off", "unsupported"]).describe("Account readiness in agent-fs."),
18309
+ agentFsUserId: string2().optional().describe("User ID in agent-fs when ready."),
18310
+ email: string2().optional().describe("Email of the swarm user, when available."),
18311
+ displayName: string2().optional().describe("Name of the swarm user when ready."),
18312
+ orgId: string2().optional().describe("Shared agent-fs org ID when configured."),
18313
+ driveId: string2().optional().describe("Shared agent-fs drive ID when configured."),
18314
+ reason: string2().optional().describe("Reason the account is not ready.")
18315
+ });
18316
+ var userAgentFsMeRoute = route({
18317
+ method: "get",
18318
+ path: "/api/fs/me",
18319
+ pattern: ["api", "fs", "me"],
18320
+ summary: "Ensure the current user's agent-fs account and shared membership",
18321
+ tags: ["FS"],
18322
+ responses: {
18323
+ 200: { description: "Account readiness", schema: userAgentFsStateSchema },
18324
+ 401: { description: "User identity required" },
18325
+ 403: { description: "Caller cannot join the shared org" },
18326
+ 429: { description: "Limit of twenty account checks per minute reached" },
18327
+ 502: { description: "agent-fs request failed" }
18328
+ }
18329
+ });
18330
+ var mintUserAgentFsKeyRoute = route({
18331
+ method: "post",
18332
+ path: "/api/fs/keys",
18333
+ pattern: ["api", "fs", "keys"],
18334
+ summary: "Mint a named agent-fs key for the current user",
18335
+ description: "The key is scoped to the shared org. The API returns it once and never stores it.",
18336
+ tags: ["FS"],
18337
+ body: object2({ label: string2().min(1).max(100) }),
18338
+ rbac: { permission: "fs.join.own" },
18339
+ responses: {
18340
+ 201: {
18341
+ description: "Named key returned once and never stored",
18342
+ schema: object2({
18343
+ apiKey: string2().describe("Plaintext key returned once. The API never stores this key."),
18344
+ keyId: string2(),
18345
+ label: string2(),
18346
+ agentFsUserId: string2(),
18347
+ orgId: string2(),
18348
+ driveId: string2()
18349
+ })
18350
+ },
18351
+ 400: { description: "Invalid key label" },
18352
+ 401: { description: "User identity required" },
18353
+ 403: { description: "Caller cannot join the shared org" },
18354
+ 409: { description: "agent-fs account or membership is pending" },
18355
+ 429: { description: "Limit of five keys per minute reached" },
18356
+ 501: { description: "agent_fs_too_old" },
18357
+ 502: { description: "agent-fs request failed" },
18358
+ 503: { description: "agent_fs_not_configured" }
18359
+ }
18360
+ });
18361
+ var continueToAgentFsRoute = route({
18362
+ method: "post",
18363
+ path: "/api/fs/continue",
18364
+ pattern: ["api", "fs", "continue"],
18365
+ summary: "Mint a named agent-fs key for the live agent-fs app and return the redirect URL",
18366
+ description: "Powers 'Continue with your swarm' on the live agent-fs app. The key travels only in the URL fragment of `redirectUrl`. The API never stores it.",
18367
+ tags: ["FS"],
18368
+ body: object2({ returnTo: url().max(4096) }),
18369
+ rbac: { permission: "fs.join.own" },
18370
+ responses: {
18371
+ 200: {
18372
+ description: "Redirect URL with the named key in the fragment",
18373
+ schema: object2({
18374
+ redirectUrl: string2().describe("`returnTo` with `#key=<af_...>&apiUrl=<browser-facing agent-fs API URL>` as its only fragment.")
18375
+ })
18376
+ },
18377
+ 400: {
18378
+ description: "invalid_return_to: the origin is not the live agent-fs app (AGENT_FS_LIVE_URL). org_mismatch: the `returnTo` path names an agent-fs org other than this swarm's shared org."
18379
+ },
18380
+ 401: { description: "User identity required" },
18381
+ 403: { description: "Caller cannot join the shared org" },
18382
+ 409: { description: "agent-fs account or membership is pending" },
18383
+ 429: { description: "Limit of ten continues per minute reached" },
18384
+ 501: { description: "agent_fs_too_old" },
18385
+ 502: { description: "agent-fs request failed" },
18386
+ 503: { description: "agent_fs_not_configured" }
18387
+ }
18388
+ });
18389
+ function allowedReturnOrigin() {
18390
+ try {
18391
+ const { origin } = new URL(getAgentFsLiveUrl());
18392
+ return origin === "null" ? null : origin;
18393
+ } catch {
18394
+ return null;
18395
+ }
18396
+ }
18397
+ var LIVE_APP_PATH = /^\/(?:|credentials|keys|files|(?:file|detail|page)\/~\/[^/]+\/[^/]+(?:\/.*)?|(?:sql|members|shares|webhooks)\/~\/[^/]+\/[^/]+\/?|orgs\/[^/]+\/files(?:\/.*)?)$/;
18398
+ function isLiveAppReturnPath(target) {
18399
+ return LIVE_APP_PATH.test(target.pathname);
18400
+ }
18401
+ function liveAppOrgId(target) {
18402
+ const segments = target.pathname.split("/").slice(1);
18403
+ const raw = segments[1] === "~" ? segments[2] : segments[0] === "orgs" ? segments[1] : undefined;
18404
+ if (!raw)
18405
+ return null;
18406
+ try {
18407
+ return decodeURIComponent(raw);
18408
+ } catch {
18409
+ return raw;
18410
+ }
18411
+ }
16957
18412
  var taskParams = object2({ taskId: uuid() });
16958
18413
  var attachmentParams = object2({ taskId: uuid(), attachmentId: uuid() });
16959
18414
  var uploadQuery = object2({
@@ -17165,7 +18620,161 @@ async function resolveInvite(req, body) {
17165
18620
  }
17166
18621
  return { email: ownEmail, role: grant.verbs.has("task.fs.mutate") ? "editor" : "viewer" };
17167
18622
  }
18623
+ async function denyFsJoin(userId) {
18624
+ const decision = can({
18625
+ principal: { kind: "user", userId },
18626
+ verb: "fs.join.own",
18627
+ resource: { kind: "none" },
18628
+ source: "http"
18629
+ });
18630
+ if (!decision.allow)
18631
+ return decision.reason;
18632
+ if (!isRbacEnabled())
18633
+ return null;
18634
+ const grant = await getUserGrant2(userId);
18635
+ return grant.grantsAll || grant.verbs.has("fs.join.own") ? null : "missing permission 'fs.join.own'";
18636
+ }
18637
+ async function resolveAgentFsUserId(req) {
18638
+ const auth = getRequestAuth(req);
18639
+ if (auth?.page)
18640
+ return null;
18641
+ const userId = authUserId(auth);
18642
+ if (userId)
18643
+ return userId;
18644
+ if (!isOperatorAuth(auth) || req.headers["x-agent-id"] !== undefined)
18645
+ return null;
18646
+ const pickedUserId = dashboardUserIdHeader(req);
18647
+ if (!pickedUserId)
18648
+ return null;
18649
+ const user = await findUserById(pickedUserId);
18650
+ return user?.status === "active" ? user.id : null;
18651
+ }
18652
+ function respondMintFailure(res, result) {
18653
+ switch (result.status) {
18654
+ case "pending":
18655
+ jsonError(res, scrubSecrets(`agent-fs account pending: ${result.reason}`), 409);
18656
+ break;
18657
+ case "unsupported":
18658
+ jsonError(res, "agent_fs_too_old", 501);
18659
+ break;
18660
+ case "off":
18661
+ jsonError(res, "agent_fs_not_configured", 503);
18662
+ break;
18663
+ }
18664
+ }
18665
+ function respondMintError(res, error) {
18666
+ jsonError(res, scrubSecrets(error instanceof Error ? error.message : String(error)), error instanceof AgentFsKeyValidationError ? 400 : 502);
18667
+ }
17168
18668
  async function handleFs(req, res, pathSegments, queryParams, myAgentId) {
18669
+ if (userAgentFsMeRoute.match(req.method, pathSegments)) {
18670
+ const userId = await resolveAgentFsUserId(req);
18671
+ if (!userId) {
18672
+ jsonError(res, "user identity required", 401);
18673
+ return true;
18674
+ }
18675
+ const denied = await denyFsJoin(userId);
18676
+ if (denied) {
18677
+ jsonError(res, denied, 403);
18678
+ return true;
18679
+ }
18680
+ if (!fsMeRateLimit.take(userId)) {
18681
+ jsonError(res, "Limit of twenty account checks per minute reached", 429);
18682
+ return true;
18683
+ }
18684
+ try {
18685
+ userAgentFsMeRoute.respond(res, 200, await ensureUserAgentFsAccount(userId));
18686
+ } catch (error) {
18687
+ jsonError(res, scrubSecrets(error instanceof Error ? error.message : String(error)), 502);
18688
+ }
18689
+ return true;
18690
+ }
18691
+ if (mintUserAgentFsKeyRoute.match(req.method, pathSegments)) {
18692
+ const userId = await resolveAgentFsUserId(req);
18693
+ if (!userId) {
18694
+ jsonError(res, "user identity required", 401);
18695
+ return true;
18696
+ }
18697
+ const parsed = await mintUserAgentFsKeyRoute.parse(req, res, pathSegments, queryParams);
18698
+ if (!parsed)
18699
+ return true;
18700
+ const denied = await denyFsJoin(userId);
18701
+ if (denied) {
18702
+ jsonError(res, denied, 403);
18703
+ return true;
18704
+ }
18705
+ if (!fsKeyRateLimit.take(userId)) {
18706
+ jsonError(res, "Limit of five keys per minute reached", 429);
18707
+ return true;
18708
+ }
18709
+ try {
18710
+ const result = await mintUserAgentFsKey(userId, parsed.body.label);
18711
+ if (result.status === "minted") {
18712
+ res.setHeader("Cache-Control", "no-store");
18713
+ const { status: _, ...key } = result;
18714
+ mintUserAgentFsKeyRoute.respond(res, 201, key);
18715
+ } else {
18716
+ respondMintFailure(res, result);
18717
+ }
18718
+ } catch (error) {
18719
+ respondMintError(res, error);
18720
+ }
18721
+ return true;
18722
+ }
18723
+ if (continueToAgentFsRoute.match(req.method, pathSegments)) {
18724
+ const userId = await resolveAgentFsUserId(req);
18725
+ if (!userId) {
18726
+ jsonError(res, "user identity required", 401);
18727
+ return true;
18728
+ }
18729
+ const parsed = await continueToAgentFsRoute.parse(req, res, pathSegments, queryParams);
18730
+ if (!parsed)
18731
+ return true;
18732
+ const denied = await denyFsJoin(userId);
18733
+ if (denied) {
18734
+ jsonError(res, denied, 403);
18735
+ return true;
18736
+ }
18737
+ const target = new URL(parsed.body.returnTo);
18738
+ if (target.origin !== allowedReturnOrigin() || !isLiveAppReturnPath(target)) {
18739
+ jsonError(res, "invalid_return_to", 400);
18740
+ return true;
18741
+ }
18742
+ if (!fsContinueRateLimit.take(userId)) {
18743
+ jsonError(res, "Limit of ten continues per minute reached", 429);
18744
+ return true;
18745
+ }
18746
+ const browserApiUrl = getCombConfig().apiUrl;
18747
+ if (!browserApiUrl) {
18748
+ jsonError(res, "agent_fs_not_configured", 503);
18749
+ return true;
18750
+ }
18751
+ try {
18752
+ const linkOrgId = liveAppOrgId(target);
18753
+ if (linkOrgId) {
18754
+ const shared = await resolveAgentFsSharedContext2();
18755
+ if (!shared) {
18756
+ jsonError(res, "agent_fs_not_configured", 503);
18757
+ return true;
18758
+ }
18759
+ if (shared.orgId !== linkOrgId) {
18760
+ jsonError(res, "org_mismatch", 400);
18761
+ return true;
18762
+ }
18763
+ }
18764
+ const date = new Date().toISOString().slice(0, 10);
18765
+ const result = await mintUserAgentFsKey(userId, `${target.host} · ${date}`);
18766
+ if (result.status === "minted") {
18767
+ target.hash = `key=${encodeURIComponent(result.apiKey)}&apiUrl=${encodeURIComponent(browserApiUrl)}`;
18768
+ res.setHeader("Cache-Control", "no-store");
18769
+ continueToAgentFsRoute.respond(res, 200, { redirectUrl: target.toString() });
18770
+ } else {
18771
+ respondMintFailure(res, result);
18772
+ }
18773
+ } catch (error) {
18774
+ respondMintError(res, error);
18775
+ }
18776
+ return true;
18777
+ }
17169
18778
  if (ensureAgentCredentialsRoute.match(req.method, pathSegments)) {
17170
18779
  const parsed = await ensureAgentCredentialsRoute.parse(req, res, pathSegments, queryParams);
17171
18780
  if (!parsed)
@@ -17177,7 +18786,7 @@ async function handleFs(req, res, pathSegments, queryParams, myAgentId) {
17177
18786
  return true;
17178
18787
  }
17179
18788
  try {
17180
- const result = await ensureAgentFsCredentialsForAgent(agentId);
18789
+ const result = await ensureAgentFsCredentialsForAgent2(agentId);
17181
18790
  ensureAgentCredentialsRoute.respond(res, 200, result);
17182
18791
  } catch (error) {
17183
18792
  const message = scrubSecrets(error instanceof Error ? error.message : String(error));
@@ -17195,7 +18804,7 @@ async function handleFs(req, res, pathSegments, queryParams, myAgentId) {
17195
18804
  return true;
17196
18805
  }
17197
18806
  try {
17198
- const result = await inviteEmailToSharedOrg(invite.email, invite.role);
18807
+ const result = await inviteEmailToSharedOrg2(invite.email, invite.role);
17199
18808
  inviteMemberRoute.respond(res, 200, result);
17200
18809
  } catch (error) {
17201
18810
  const message = scrubSecrets(error instanceof Error ? error.message : String(error));
@@ -17380,8 +18989,8 @@ async function sendSignedUrl(res, attachment, expiresIn) {
17380
18989
  return true;
17381
18990
  }
17382
18991
  try {
17383
- const url = await provider.url(scopeFromAttachment(attachment), { expiresIn });
17384
- signedUrlTaskFileRoute.respond(res, 200, { url, expiresIn: Math.min(expiresIn ?? 3600, 3600) });
18992
+ const url2 = await provider.url(scopeFromAttachment(attachment), { expiresIn });
18993
+ signedUrlTaskFileRoute.respond(res, 200, { url: url2, expiresIn: Math.min(expiresIn ?? 3600, 3600) });
17385
18994
  } catch (error) {
17386
18995
  return sendProviderError(res, error);
17387
18996
  }
@@ -17797,7 +19406,7 @@ init_zod();
17797
19406
  init_db4();
17798
19407
  init_rbac_roles();
17799
19408
  init_rbac();
17800
- init_types4();
19409
+ init_types5();
17801
19410
  init_request_auth_context();
17802
19411
  init_route_def();
17803
19412
  init_utils2();
@@ -17943,209 +19552,6 @@ async function handleInboxState(req, res, pathSegments, queryParams) {
17943
19552
  // src/http/integrations.ts
17944
19553
  init_zod();
17945
19554
 
17946
- // src/integrations/chat-sdk/status.ts
17947
- init_zod();
17948
- init_constants3();
17949
- init_env_flag();
17950
- init_secret_scrubber();
17951
- init_adapters();
17952
- init_config();
17953
-
17954
- // src/integrations/chat-sdk/discord-api.ts
17955
- init_secret_scrubber();
17956
- init_adapters();
17957
- init_logger();
17958
- var DISCORD_TIMEOUT_MS = 5000;
17959
- var GUILDS_CACHE_MS = 60000;
17960
- var MAX_GUILD_NAMES = 10;
17961
- var cache;
17962
- async function fetchDiscordGuilds(token, now = Date.now()) {
17963
- if (cache && cache.token === token && now - cache.at < GUILDS_CACHE_MS)
17964
- return cache.guilds;
17965
- let guilds;
17966
- try {
17967
- const response = await fetch(`${resolveAdapterApiUrl("discord")}/users/@me/guilds`, {
17968
- headers: { authorization: `Bot ${token}` },
17969
- signal: AbortSignal.timeout(DISCORD_TIMEOUT_MS)
17970
- });
17971
- if (!response.ok)
17972
- throw new Error(`HTTP ${response.status}`);
17973
- const payload = await response.json();
17974
- if (!Array.isArray(payload))
17975
- throw new Error("unexpected response shape");
17976
- const names = payload.map((guild) => guild !== null && typeof guild === "object" && typeof guild.name === "string" ? guild.name : undefined).filter((name) => name !== undefined);
17977
- guilds = { count: payload.length, names: names.slice(0, MAX_GUILD_NAMES) };
17978
- } catch (error) {
17979
- console.warn(scrubSecrets(`[chat-sdk] discord: could not list the bot's servers: ${errorMessage(error).replaceAll(token, "[REDACTED]")}`));
17980
- }
17981
- cache = { token, at: now, guilds };
17982
- return guilds;
17983
- }
17984
-
17985
- // src/integrations/chat-sdk/status.ts
17986
- init_runtime();
17987
- init_schema();
17988
- init_telegram_api();
17989
- var ChatSdkStatusSchema = object2({
17990
- enabled: boolean(),
17991
- slackClash: boolean(),
17992
- error: string2().optional(),
17993
- adapters: array2(object2({
17994
- name: _enum2(CHAT_SDK_ADAPTER_NAMES),
17995
- configured: boolean(),
17996
- enabled: boolean(),
17997
- health: _enum2(["ok", "error", "disabled", "incomplete"]),
17998
- error: string2().optional(),
17999
- webhookUrl: string2(),
18000
- mode: string2().optional(),
18001
- gateway: object2({
18002
- state: _enum2(["running", "backoff", "stopped"]),
18003
- since: string2(),
18004
- restarts: number2()
18005
- }).optional(),
18006
- guilds: object2({ count: number2(), names: array2(string2()) }).optional()
18007
- }))
18008
- });
18009
- var DEFAULT_MODES = {
18010
- telegram: "webhook",
18011
- slack: "webhook"
18012
- };
18013
- var NOT_RUNNING = "The adapter is starting, or the last configuration save is still applying. Refresh in a few seconds.";
18014
- var SLACK_CLASH_CAUSE = "the Slack adapter conflicts with the built-in Slack integration (set SLACK_DISABLE=true)";
18015
- var MAX_STATUS_ERROR_CHARS = 300;
18016
- function statusError(message) {
18017
- return scrubSecrets(message).slice(0, MAX_STATUS_ERROR_CHARS);
18018
- }
18019
- function readRawAdapters() {
18020
- const raw = process.env.CHAT_SDK_ADAPTERS?.trim();
18021
- if (!raw)
18022
- return {};
18023
- try {
18024
- const parsed = JSON.parse(raw);
18025
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
18026
- return {};
18027
- const out = {};
18028
- for (const name of CHAT_SDK_ADAPTER_NAMES) {
18029
- const value = parsed[name];
18030
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
18031
- out[name] = value;
18032
- }
18033
- }
18034
- return out;
18035
- } catch {
18036
- return {};
18037
- }
18038
- }
18039
- function chatSdkWebhookUrl(name) {
18040
- return `${getPublicMcpBaseUrl()}/api/integrations/chat/${name}/webhook`;
18041
- }
18042
- async function discordGuildsFor(config, health) {
18043
- if (health?.status !== "ok" || health.gateway?.state !== "running")
18044
- return;
18045
- const raw = config.adapters.discord?.botToken;
18046
- const token = typeof raw === "function" ? await raw() : raw;
18047
- if (typeof token !== "string" || token.length === 0)
18048
- return;
18049
- return fetchDiscordGuilds(token);
18050
- }
18051
- async function getChatSdkStatus() {
18052
- const config = await getChatSdkConfig();
18053
- const raw = readRawAdapters();
18054
- const runtimeHealth = getChatSdkHealth();
18055
- const slackClash = raw.slack !== undefined && !isEnvFlagEnabled("SLACK_DISABLE", false);
18056
- const blockedCause = config.error ?? (config.enabled && slackClash ? SLACK_CLASH_CAUSE : undefined);
18057
- const discordGuilds = await discordGuildsFor(config, runtimeHealth.discord);
18058
- const adapters = CHAT_SDK_ADAPTER_NAMES.map((name) => {
18059
- const configured = raw[name] !== undefined;
18060
- const enabled = isAdapterEntryEnabled(raw[name]);
18061
- const current = runtimeHealth[name];
18062
- const incomplete = config.incomplete?.[name];
18063
- const rawMode = raw[name]?.mode;
18064
- const mode = typeof rawMode === "string" ? rawMode : configured ? DEFAULT_MODES[name] : undefined;
18065
- let health = "disabled";
18066
- let error;
18067
- if (current) {
18068
- health = current.status;
18069
- const showWarning = current.status === "error" || current.gateway?.state === "backoff";
18070
- error = current.error ?? (showWarning ? current.lastWarning : undefined);
18071
- } else if (incomplete) {
18072
- health = "incomplete";
18073
- error = incomplete;
18074
- } else if (configured && !enabled) {
18075
- error = "Turned off on the card. The configuration is kept.";
18076
- } else if (config.enabled && configured) {
18077
- error = blockedCause ? `Not started: ${blockedCause}` : NOT_RUNNING;
18078
- }
18079
- return {
18080
- name,
18081
- configured,
18082
- enabled,
18083
- health,
18084
- ...error ? { error: statusError(error) } : {},
18085
- webhookUrl: chatSdkWebhookUrl(name),
18086
- ...mode ? { mode } : {},
18087
- ...current?.gateway ? { gateway: current.gateway } : {},
18088
- ...name === "discord" && discordGuilds ? { guilds: discordGuilds } : {}
18089
- };
18090
- });
18091
- return {
18092
- enabled: config.enabled,
18093
- slackClash,
18094
- ...config.error ? { error: statusError(config.error) } : {},
18095
- adapters
18096
- };
18097
- }
18098
-
18099
- class ChatSdkActionError extends Error {
18100
- status;
18101
- constructor(message, status) {
18102
- super(message);
18103
- this.status = status;
18104
- this.name = "ChatSdkActionError";
18105
- }
18106
- }
18107
- async function callBotApi(baseUrl, token, method, body) {
18108
- try {
18109
- return await callTelegramBotApi(baseUrl, token, method, body);
18110
- } catch (error) {
18111
- if (error instanceof TelegramBotApiError)
18112
- throw new ChatSdkActionError(error.message, 502);
18113
- throw error;
18114
- }
18115
- }
18116
- async function registerTelegramWebhook() {
18117
- const config = await getChatSdkConfig();
18118
- if (!config.enabled) {
18119
- throw new ChatSdkActionError("The Chat SDK channel is disabled (CHAT_SDK_ENABLED is not true). Enable it and restart the API first", 400);
18120
- }
18121
- if (config.error)
18122
- throw new ChatSdkActionError(statusError(config.error), 400);
18123
- const telegram = config.adapters.telegram;
18124
- if (!telegram) {
18125
- throw new ChatSdkActionError("Telegram is not configured in CHAT_SDK_ADAPTERS", 400);
18126
- }
18127
- if (telegram.mode !== "webhook") {
18128
- throw new ChatSdkActionError("Telegram runs in polling mode; a registered webhook would stop polling", 400);
18129
- }
18130
- const secretToken = telegram.secretToken;
18131
- if (typeof secretToken !== "string" || secretToken.length === 0) {
18132
- throw new ChatSdkActionError("Telegram webhook mode needs a secretToken", 400);
18133
- }
18134
- const rawToken = telegram.botToken;
18135
- const token = typeof rawToken === "function" ? await rawToken() : rawToken;
18136
- if (typeof token !== "string" || token.length === 0) {
18137
- throw new ChatSdkActionError("Telegram botToken is empty", 400);
18138
- }
18139
- const baseUrl = resolveAdapterApiUrl("telegram");
18140
- const webhookUrl = chatSdkWebhookUrl("telegram");
18141
- await callBotApi(baseUrl, token, "setWebhook", { url: webhookUrl, secret_token: secretToken });
18142
- const info = await callBotApi(baseUrl, token, "getWebhookInfo", {});
18143
- if (info === null || typeof info !== "object" || typeof info.url !== "string") {
18144
- throw new ChatSdkActionError("Telegram getWebhookInfo returned an unexpected result", 502);
18145
- }
18146
- return { webhookUrl, webhookInfo: info };
18147
- }
18148
-
18149
19555
  // src/slack/app-icon.ts
18150
19556
  init_app3();
18151
19557
  var import_web_api = __toESM(require_dist4(), 1);
@@ -18540,7 +19946,7 @@ init_kv_reserved_namespaces();
18540
19946
  init_kv_view();
18541
19947
  init_rbac();
18542
19948
  init_context_key();
18543
- init_types4();
19949
+ init_types5();
18544
19950
  init_route_def();
18545
19951
  init_utils2();
18546
19952
  var MAX_KV_BODY_BYTES = 2 * 1024 * 1024;
@@ -18780,6 +20186,16 @@ function authorizeWrite(namespace, ctx) {
18780
20186
  }
18781
20187
  return null;
18782
20188
  }
20189
+ if (requiresLeadToWrite(namespace)) {
20190
+ const allowed = ctx.callerAgentId != null && can({
20191
+ principal: { kind: "agent", agentId: ctx.callerAgentId, isLead: ctx.isLead },
20192
+ verb: "kv.write.any",
20193
+ resource: { kind: "kv-namespace", namespace },
20194
+ source: "http"
20195
+ }).allow;
20196
+ if (!allowed)
20197
+ return { status: 403, message: "writes to this namespace require lead" };
20198
+ }
18783
20199
  if (namespace.startsWith("task:agent:")) {
18784
20200
  const allowed = ctx.callerAgentId != null && can({
18785
20201
  principal: { kind: "agent", agentId: ctx.callerAgentId, isLead: ctx.isLead },
@@ -20747,7 +22163,7 @@ init_db4();
20747
22163
  init_mcp_oauth();
20748
22164
  init_ensure_mcp_token();
20749
22165
  init_mcp_wrapper();
20750
- init_types4();
22166
+ init_types5();
20751
22167
  init_constants3();
20752
22168
  init_route_def();
20753
22169
  init_utils2();
@@ -20758,7 +22174,7 @@ function dashboardBase() {
20758
22174
  return getAppUrl();
20759
22175
  }
20760
22176
  function defaultFinalRedirect(mcpServerId) {
20761
- return `${dashboardBase()}/mcp-servers/${mcpServerId}?oauth=success`;
22177
+ return `${dashboardBase()}/integrations/tools/mcp-servers/${mcpServerId}?oauth=success`;
20762
22178
  }
20763
22179
  var DiscoveryResultSchema = object2({
20764
22180
  resourceUrl: string2(),
@@ -21488,6 +22904,18 @@ async function handleMcpOAuth(req, res, pathSegments, queryParams) {
21488
22904
  // src/http/mcp-servers.ts
21489
22905
  init_zod();
21490
22906
  init_db4();
22907
+
22908
+ // src/be/db-queries/mcp-servers.ts
22909
+ init_db4();
22910
+ async function countMcpServerInstalls() {
22911
+ const rows = await getDbClient2().query(`SELECT mcpServerId, COUNT(*) AS installs
22912
+ FROM agent_mcp_servers
22913
+ WHERE isActive = 1
22914
+ GROUP BY mcpServerId`, []);
22915
+ return new Map(rows.map((row) => [row.mcpServerId, row.installs]));
22916
+ }
22917
+
22918
+ // src/http/mcp-servers.ts
21491
22919
  init_mcp_server_checked_update();
21492
22920
  init_mcp_server_stdio_gate();
21493
22921
  init_rbac_audit();
@@ -21495,7 +22923,7 @@ init_rbac_roles();
21495
22923
  init_ensure_mcp_token();
21496
22924
  init_mcp_wrapper();
21497
22925
  init_rbac();
21498
- init_types4();
22926
+ init_types5();
21499
22927
  init_request_auth_context();
21500
22928
  init_request_principal();
21501
22929
  init_route_def();
@@ -21522,7 +22950,12 @@ var listMcpServersRoute = route({
21522
22950
  responses: {
21523
22951
  200: {
21524
22952
  description: "MCP server list",
21525
- schema: object2({ servers: array2(McpServerSchema), total: number2() })
22953
+ schema: object2({
22954
+ servers: array2(McpServerSchema.extend({
22955
+ installCount: number2().optional()
22956
+ })),
22957
+ total: number2()
22958
+ })
21526
22959
  }
21527
22960
  }
21528
22961
  });
@@ -21837,7 +23270,11 @@ async function handleMcpServers(req, res, pathSegments, queryParams) {
21837
23270
  isEnabled: parsed.query.enabled !== undefined ? parsed.query.enabled === "true" : undefined,
21838
23271
  search: parsed.query.search
21839
23272
  });
21840
- listMcpServersRoute.respond(res, 200, { servers, total: servers.length });
23273
+ const installs = await countMcpServerInstalls();
23274
+ listMcpServersRoute.respond(res, 200, {
23275
+ servers: servers.map((server) => ({ ...server, installCount: installs.get(server.id) ?? 0 })),
23276
+ total: servers.length
23277
+ });
21841
23278
  return true;
21842
23279
  }
21843
23280
  if (getMcpServerRoute.match(req.method, pathSegments)) {
@@ -21981,7 +23418,7 @@ init_send_task();
21981
23418
  init_steer_task();
21982
23419
  init_task_tool_ctx();
21983
23420
  init_utils();
21984
- init_types4();
23421
+ init_types5();
21985
23422
  init_steering_enabled();
21986
23423
  var userSendTaskInputSchema = object2({
21987
23424
  task: string2().min(1).describe("The task description to send."),
@@ -22473,7 +23910,7 @@ function truncateUtf8(query, maxBytes) {
22473
23910
 
22474
23911
  // src/http/memory.ts
22475
23912
  init_rbac();
22476
- init_types4();
23913
+ init_types5();
22477
23914
  init_request_auth_context();
22478
23915
  init_secret_scrubber();
22479
23916
  init_request_principal();
@@ -23721,7 +25158,7 @@ function stopMemoryGc() {
23721
25158
  init_zod();
23722
25159
  init_db4();
23723
25160
  init_version2();
23724
- init_types4();
25161
+ init_types5();
23725
25162
  init_db_query();
23726
25163
  init_route_def();
23727
25164
  init_utils2();
@@ -24183,7 +25620,7 @@ init_db4();
24183
25620
  init_model_profiles();
24184
25621
  init_model_validation2();
24185
25622
  init_rbac();
24186
- init_types4();
25623
+ init_types5();
24187
25624
  init_credentials2();
24188
25625
  init_request_principal();
24189
25626
  init_route_def();
@@ -24468,7 +25905,7 @@ init_model_catalog_store();
24468
25905
  init_model_tier_resolution();
24469
25906
  init_pricing_refresh();
24470
25907
  init_rbac();
24471
- init_types4();
25908
+ init_types5();
24472
25909
  init_request_auth_context();
24473
25910
  init_request_principal();
24474
25911
  init_route_def();
@@ -25333,7 +26770,7 @@ init_db4();
25333
26770
  init_memory();
25334
26771
  init_constants2();
25335
26772
  init_mcp_wrapper();
25336
- init_types4();
26773
+ init_types5();
25337
26774
  init_constants3();
25338
26775
  init_credentials2();
25339
26776
  init_egress_guard();
@@ -25369,7 +26806,8 @@ init_registry2();
25369
26806
  init_config4();
25370
26807
  init_connection_state();
25371
26808
  init_telemetry();
25372
- init_types4();
26809
+ init_types5();
26810
+ init_github_host();
25373
26811
  init_runtime_pools_flag();
25374
26812
  init_route_def();
25375
26813
  init_utils2();
@@ -25462,6 +26900,10 @@ var AutomationStatusSchema = object2({
25462
26900
  fixUrl: string2()
25463
26901
  });
25464
26902
  var StatusHealthSchema = _enum2(["ok", "degraded", "broken"]);
26903
+ var StatusGitHubSchema = object2({
26904
+ web_url: string2(),
26905
+ enterprise: boolean()
26906
+ });
25465
26907
  var StatusRuntimePoolsSchema = object2({ enabled: boolean(), supervisor: string2() });
25466
26908
  var StatusResponseSchema = object2({
25467
26909
  runtime_pools: StatusRuntimePoolsSchema,
@@ -25472,7 +26914,8 @@ var StatusResponseSchema = object2({
25472
26914
  automations: array2(AutomationStatusSchema),
25473
26915
  health: StatusHealthSchema,
25474
26916
  telemetry: StatusTelemetrySchema.optional(),
25475
- instance: StatusInstanceSchema.optional()
26917
+ instance: StatusInstanceSchema.optional(),
26918
+ github: StatusGitHubSchema.optional()
25476
26919
  });
25477
26920
  var TestConnectionRequestSchema = object2({
25478
26921
  provider: ProviderNameSchema
@@ -25626,8 +27069,6 @@ function slackMilestone(state) {
25626
27069
  hint = "Slack is explicitly disabled (SLACK_DISABLE=true).";
25627
27070
  } else if (!config.mode) {
25628
27071
  hint = "Invalid SLACK_MODE. Use socket or http.";
25629
- } else if (config.mode === "http" && config.missingCredentials.length === 0) {
25630
- hint = "HTTP credentials are configured, but HTTP ingress is unavailable until the receiver is installed.";
25631
27072
  } else {
25632
27073
  hint = `Set ${config.missingCredentials.join(" + ")} for Slack ${config.mode} mode.`;
25633
27074
  }
@@ -25639,7 +27080,7 @@ function slackMilestone(state) {
25639
27080
  action_url: automationIntegrationFixUrl("slack")
25640
27081
  };
25641
27082
  }
25642
- if (config.mode === "socket" && getSlackConnectionState() === "connected") {
27083
+ if (getSlackConnectionState() === "connected") {
25643
27084
  return {
25644
27085
  id: "slack",
25645
27086
  label: "Slack configured",
@@ -25651,7 +27092,7 @@ function slackMilestone(state) {
25651
27092
  id: "slack",
25652
27093
  label: "Slack configured",
25653
27094
  state: "configured",
25654
- hint: config.mode === "http" ? "HTTP credentials are configured, but HTTP ingress is unavailable until the receiver is installed." : "Socket Mode credentials are configured, but the bot is not connected to Slack.",
27095
+ hint: config.mode === "http" ? "HTTP credentials are configured, but the receiver is not ready (workspace not verified yet)." : "Socket Mode credentials are configured, but the bot is not connected to Slack.",
25655
27096
  action_url: automationIntegrationFixUrl("slack")
25656
27097
  };
25657
27098
  }
@@ -25840,9 +27281,16 @@ async function buildStatusPayload() {
25840
27281
  automations,
25841
27282
  health: computeHealth(setup, readyLeads),
25842
27283
  telemetry: { enabled: isTelemetryEnabled() },
25843
- instance
27284
+ instance,
27285
+ ...githubStatus()
25844
27286
  };
25845
27287
  }
27288
+ function githubStatus() {
27289
+ const host = resolveGitHubHost();
27290
+ if (!host.ok)
27291
+ return {};
27292
+ return { github: { web_url: host.config.webUrl, enterprise: host.config.enterprise } };
27293
+ }
25846
27294
  function getCombStatus(serviceUserId) {
25847
27295
  const comb = getCombConfig();
25848
27296
  return {
@@ -25874,7 +27322,7 @@ var getStatus = route({
25874
27322
  path: "/status",
25875
27323
  pattern: ["status"],
25876
27324
  summary: "Identity + setup readiness + live activity for the swarm dashboard",
25877
- description: "Single source of truth consumed by the UI home page. Identity comes from SWARM_* envs; setup milestones each emit `unverified | configured | verified`; automations report `running | needs_setup` from the same runtime preflight used at dispatch; activity counts agents alive in the last 5 min, leads that can take work (status idle or busy), and tasks created in the last 24h; agent_fs reports whether AGENT_FS_API_URL is set, plus the Comb settings (whether Files is on and, when off, what is missing; the browser-facing agent-fs URL, the shared org and drive ids, and the agent-fs user id of the swarm service account); telemetry reports the effective ANONYMIZED_TELEMETRY opt-out state.",
27325
+ description: "Single source of truth consumed by the UI home page. Identity comes from SWARM_* envs; setup milestones each emit `unverified | configured | verified`; automations report `running | needs_setup` from the same runtime preflight used at dispatch; activity counts agents alive in the last 5 min, leads that can take work (status idle or busy), and tasks created in the last 24h; agent_fs reports whether AGENT_FS_API_URL is set, plus the Comb settings (whether Files is on and, when off, what is missing; the browser-facing agent-fs URL, the shared org and drive ids, and the agent-fs user id of the swarm service account); telemetry reports the effective ANONYMIZED_TELEMETRY opt-out state; github reports the GitHub web base (GITHUB_URL) for PR and repo links.",
25878
27326
  tags: ["Status"],
25879
27327
  responses: {
25880
27328
  200: { description: "Status payload", schema: StatusResponseSchema },
@@ -26024,14 +27472,7 @@ async function buildSignals(state) {
26024
27472
  provider: embeddingsOn ? embeddingsProvider(process.env.EMBEDDING_API_BASE_URL) : null,
26025
27473
  localDefault: localDefault()
26026
27474
  },
26027
- integrations: {
26028
- slack: integrations.slack === "configured",
26029
- github: Boolean(process.env.GITHUB_TOKEN?.trim()) || integrations.github === "verified",
26030
- gitlab: Boolean(process.env.GITLAB_TOKEN?.trim()),
26031
- bitbucket: Boolean(process.env.BITBUCKET_TOKEN?.trim()),
26032
- linear: integrations.linear === "verified",
26033
- jira: integrations.jira === "verified"
26034
- },
27475
+ integrations: setupIntegrationFlags(integrations),
26035
27476
  agents: {
26036
27477
  leadsOnline: agentCounts.leads,
26037
27478
  workersOnline: agentCounts.workers
@@ -26495,7 +27936,7 @@ init_session_templates();
26495
27936
  init_sibling_awareness();
26496
27937
  init_page_fields();
26497
27938
  init_presets();
26498
- init_types4();
27939
+ init_types5();
26499
27940
  init_constants3();
26500
27941
  init_page_session();
26501
27942
  init_request_auth_context();
@@ -26514,6 +27955,7 @@ init_rbac_roles();
26514
27955
  init_session_shares();
26515
27956
  init_steering2();
26516
27957
  init_task_citations2();
27958
+ init_task_ui_spec();
26517
27959
  init_users();
26518
27960
  init_rbac();
26519
27961
  init_context_key();
@@ -26522,7 +27964,8 @@ init_sibling_awareness();
26522
27964
  init_task_skip();
26523
27965
  init_terminal_result_guard();
26524
27966
  init_worker_follow_up();
26525
- init_types4();
27967
+ init_types5();
27968
+ init_actions();
26526
27969
  init_business_use();
26527
27970
  init_request_auth_context();
26528
27971
  init_secret_scrubber();
@@ -26570,7 +28013,7 @@ init_request_principal();
26570
28013
  init_zod();
26571
28014
  init_db4();
26572
28015
  init_identity();
26573
- init_types4();
28016
+ init_types5();
26574
28017
  init_requester_comms();
26575
28018
  var TaskRequestedBySchema = UserSchema.pick({
26576
28019
  id: true,
@@ -26669,6 +28112,7 @@ async function buildTaskThreadParticipants(task) {
26669
28112
  // src/http/tasks.ts
26670
28113
  init_route_def();
26671
28114
  init_session_access();
28115
+ init_task_requester();
26672
28116
  init_utils2();
26673
28117
  var AgentTaskSummarySchema = AgentTaskSchema.pick({
26674
28118
  id: true,
@@ -26734,7 +28178,8 @@ var GetTaskResponseSchema = AgentTaskSchema.extend({
26734
28178
  supportedSteerModes: array2(SteerModeSchema),
26735
28179
  logs: array2(AgentLogSchema),
26736
28180
  attachments: array2(TaskAttachmentSchema),
26737
- citations: array2(TaskCitationSchema)
28181
+ citations: array2(TaskCitationSchema),
28182
+ uiSpec: TaskUiSpecSchema.nullable()
26738
28183
  });
26739
28184
  var FinishTaskSuccessSchema = object2({
26740
28185
  success: literal2(true),
@@ -26849,7 +28294,7 @@ var createTask = route({
26849
28294
  description: "Validation error, an unknown `model` (set `allowCustomModel` to store a custom id), a `vcsRepo` that is not exactly one registered repo, or agentId/offeredTo targets an extension identity"
26850
28295
  },
26851
28296
  403: {
26852
- description: "An agent caller names a parentTaskId it neither owns nor created, or a non-lead agent binds the task to a chat thread"
28297
+ description: "Parent/session access denied, unauthorized chat-thread binding, or routing requirements reject the assignment"
26853
28298
  },
26854
28299
  422: {
26855
28300
  description: "Task creation blocked by an extension",
@@ -27196,13 +28641,36 @@ var resumeTaskRoute = route({
27196
28641
  404: { description: "Task not found" }
27197
28642
  }
27198
28643
  });
28644
+ var runTaskUiActionRoute = route({
28645
+ method: "post",
28646
+ path: "/api/tasks/{id}/ui-actions/{actionId}",
28647
+ pattern: ["api", "tasks", null, "ui-actions", null],
28648
+ session: { taskParam: "id" },
28649
+ rbac: { permission: "task.action.own" },
28650
+ summary: "Run the action a task card Button declares",
28651
+ description: "Runs the task card action once per task and action. Only the task requester may run it: a user token, or the operator key with the requester in `X-Swarm-User-Id`. Agent callers, and operator calls with no picked user, get 403. Needs UI_SPEC_ACTIONS_ENABLED=true.",
28652
+ tags: ["Tasks"],
28653
+ params: object2({ id: string2(), actionId: string2() }),
28654
+ responses: {
28655
+ 200: {
28656
+ description: "The action started, or it already ran",
28657
+ schema: object2({
28658
+ status: _enum2(["started", "already_done"]),
28659
+ taskId: string2().optional()
28660
+ })
28661
+ },
28662
+ 403: { description: "Only the task requester may run the action" },
28663
+ 404: { description: "Task or action not found" },
28664
+ 409: { description: "Card actions are turned off (UI_SPEC_ACTIONS_ENABLED)" }
28665
+ }
28666
+ });
27199
28667
  var supersedeTaskRoute = route({
27200
28668
  method: "post",
27201
28669
  path: "/api/tasks/{id}/supersede",
27202
28670
  pattern: ["api", "tasks", null, "supersede"],
27203
28671
  session: { taskParam: "id" },
27204
28672
  summary: "Supersede an in-progress task (terminate + spawn resume follow-up)",
27205
- 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. 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.',
28673
+ description: "Marks the original task `superseded` (terminal) and creates a fresh `taskType=\"resume\"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine's retry/failure policy applies, and the task moves to `superseded` once the engine queues the step's retry. With `reason: provider_fallback` (and its `errorClass`), the resume runs on the same agent with the next fallback profile that passes the profile check; when none is left, or the task is a workflow step, nothing changes and `kind: noFallback` tells the worker to fail the task itself, led by `failureReason` when set.",
27206
28674
  tags: ["Tasks"],
27207
28675
  params: object2({ id: string2() }),
27208
28676
  body: object2({ reason: ResumeReasonSchema, errorClass: ProviderErrorClassSchema.optional() }).refine((body) => body.reason === "provider_fallback" === (body.errorClass !== undefined), {
@@ -27260,6 +28728,30 @@ var updateTaskTitleRoute = route({
27260
28728
  auth: { apiKey: true },
27261
28729
  rbac: { permission: "task.action.own" }
27262
28730
  });
28731
+ var TaskTagListSchema = array2(string2().regex(/^ui:[a-z0-9][a-z0-9-]{0,60}$/, "Only ui: presentation tags can be changed here")).max(20);
28732
+ var updateTaskTagsRoute = route({
28733
+ method: "patch",
28734
+ path: "/api/tasks/{id}/tags",
28735
+ pattern: ["api", "tasks", null, "tags"],
28736
+ session: { taskParam: "id" },
28737
+ summary: "Add or remove task tags",
28738
+ description: "Adds the `add` tags and removes the `remove` tags. A tag in both lists is removed. Only `ui:` presentation tags are accepted (400 otherwise); tags that drive behaviour are server-owned. The dashboard uses `ui:dismissed` to hide a failed task from Home's Needs you. Does not change `lastUpdatedAt`.",
28739
+ tags: ["Tasks"],
28740
+ params: object2({ id: string2() }),
28741
+ body: object2({
28742
+ add: TaskTagListSchema.optional(),
28743
+ remove: TaskTagListSchema.optional()
28744
+ }).refine((body) => (body.add?.length ?? 0) + (body.remove?.length ?? 0) > 0, {
28745
+ message: "Give at least one tag to add or remove"
28746
+ }),
28747
+ responses: {
28748
+ 200: { description: "Tags updated", schema: object2({ task: AgentTaskSchema }) },
28749
+ 403: { description: "Task belongs to another user" },
28750
+ 404: { description: "Task not found" }
28751
+ },
28752
+ auth: { apiKey: true },
28753
+ rbac: { permission: "task.action.own" }
28754
+ });
27263
28755
  async function canSteerTask(req, myAgentId, task, sessionAccess = "none") {
27264
28756
  const userId = authUserId(getRequestAuth(req));
27265
28757
  const resource = {
@@ -27319,20 +28811,6 @@ async function deniesForeignContext(req, contextKey) {
27319
28811
  }
27320
28812
  return false;
27321
28813
  }
27322
- async function resolveTaskRequester(req, myAgentId, bodyUserId, trustedUserId) {
27323
- const trusted = trustedUserId === undefined ? await resolveHttpAuditUserId(req, myAgentId) : trustedUserId;
27324
- if (trusted)
27325
- return trusted;
27326
- if (process.env.TRUST_BODY_REQUESTED_BY_USER_ID === "false" || !bodyUserId)
27327
- return;
27328
- const mayAssign = can({
27329
- principal: await resolveTaskWritePrincipal(req, myAgentId),
27330
- verb: "task.requester.assign",
27331
- resource: { kind: "none" },
27332
- source: "http"
27333
- }).allow;
27334
- return mayAssign ? (await findUserById(bodyUserId))?.id : undefined;
27335
- }
27336
28814
  async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
27337
28815
  if (pathSegments[0] === "api" && pathSegments[1] === "tasks" && rejectGuest(req, res)) {
27338
28816
  return true;
@@ -27489,6 +28967,7 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
27489
28967
  vcsRepo,
27490
28968
  parentTaskId: parsed.body.parentTaskId || undefined,
27491
28969
  inheritParentOutputSchema: principal.kind === "agent",
28970
+ routingAffinity: parsed.body.parentTaskId && (principal.kind === "user" || principal.kind === "operator") ? { capabilities: [] } : undefined,
27492
28971
  source: parsed.body.source || "api",
27493
28972
  outputSchema: parsed.body.outputSchema || undefined,
27494
28973
  contextKey: parsed.body.contextKey || undefined,
@@ -27518,6 +28997,16 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
27518
28997
  });
27519
28998
  createTask.respond(res, 201, task);
27520
28999
  } catch (error) {
29000
+ if (error instanceof TaskRoutingAuthorizationError) {
29001
+ console.warn("[HTTP] Task assignment rejected:", scrubSecrets(JSON.stringify({
29002
+ parentTaskId: parsed.body.parentTaskId,
29003
+ source: parsed.body.source ?? "api",
29004
+ contextKey: parsed.body.contextKey ?? parentTask?.contextKey,
29005
+ reason: error.message
29006
+ })));
29007
+ jsonError(res, error.message, 403);
29008
+ return true;
29009
+ }
27521
29010
  if (error instanceof TaskCreationBlockedError) {
27522
29011
  createTask.respond(res, 422, { error: error.reason, extension: error.extension });
27523
29012
  return true;
@@ -27893,7 +29382,8 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
27893
29382
  ...await getTaskSteeringFields(task),
27894
29383
  logs,
27895
29384
  attachments,
27896
- citations: await getTaskCitations(task.id)
29385
+ citations: await getTaskCitations(task.id),
29386
+ uiSpec: await getTaskUiSpec(task.id)
27897
29387
  });
27898
29388
  return true;
27899
29389
  }
@@ -28177,6 +29667,68 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
28177
29667
  updateTaskTitleRoute.respond(res, 200, { task });
28178
29668
  return true;
28179
29669
  }
29670
+ if (updateTaskTagsRoute.match(req.method, pathSegments)) {
29671
+ const parsed = await updateTaskTagsRoute.parse(req, res, pathSegments, queryParams);
29672
+ if (!parsed)
29673
+ return true;
29674
+ const existing = await getTaskById2(parsed.params.id);
29675
+ if (!existing) {
29676
+ jsonError(res, "Task not found", 404);
29677
+ return true;
29678
+ }
29679
+ if (await deniesNonOwnerTaskWrite2(req, existing)) {
29680
+ jsonError(res, NOT_YOUR_TASK_DENIED2, 403);
29681
+ return true;
29682
+ }
29683
+ const task = await updateTaskTags2(parsed.params.id, parsed.body);
29684
+ if (!task) {
29685
+ jsonError(res, "Task not found", 404);
29686
+ return true;
29687
+ }
29688
+ updateTaskTagsRoute.respond(res, 200, { task });
29689
+ return true;
29690
+ }
29691
+ if (runTaskUiActionRoute.match(req.method, pathSegments)) {
29692
+ const parsed = await runTaskUiActionRoute.parse(req, res, pathSegments, queryParams);
29693
+ if (!parsed)
29694
+ return true;
29695
+ const task = await getTaskById2(parsed.params.id);
29696
+ if (!task) {
29697
+ jsonError(res, "Task not found", 404);
29698
+ return true;
29699
+ }
29700
+ if (!await canActOnOwnTask(req, myAgentId, task)) {
29701
+ jsonError(res, "Not authorized to act on this task", 403);
29702
+ return true;
29703
+ }
29704
+ const actor = await resolveSessionActor2(req, myAgentId);
29705
+ const tokenUserId = authUserId(getRequestAuth(req));
29706
+ const trustsPickedUser = process.env.TRUST_BODY_REQUESTED_BY_USER_ID !== "false";
29707
+ const actorUserId = actor.kind === "user" && (tokenUserId || trustsPickedUser) ? actor.userId ?? undefined : undefined;
29708
+ const result = await runTaskUiAction({
29709
+ taskId: task.id,
29710
+ actionId: parsed.params.actionId,
29711
+ surface: "web",
29712
+ actorUserId
29713
+ });
29714
+ switch (result.status) {
29715
+ case "forbidden":
29716
+ jsonError(res, "Only the task requester may run this action", 403);
29717
+ return true;
29718
+ case "unknown_action":
29719
+ jsonError(res, "This task declares no such action", 404);
29720
+ return true;
29721
+ case "disabled":
29722
+ jsonError(res, "Card actions are turned off (UI_SPEC_ACTIONS_ENABLED)", 409);
29723
+ return true;
29724
+ case "already_done":
29725
+ runTaskUiActionRoute.respond(res, 200, { status: "already_done" });
29726
+ return true;
29727
+ case "started":
29728
+ runTaskUiActionRoute.respond(res, 200, result);
29729
+ return true;
29730
+ }
29731
+ }
28180
29732
  if (resumeTaskRoute.match(req.method, pathSegments)) {
28181
29733
  const parsed = await resumeTaskRoute.parse(req, res, pathSegments, queryParams);
28182
29734
  if (!parsed)
@@ -31200,7 +32752,7 @@ ${PAGE_DESIGN_CSS}
31200
32752
  }
31201
32753
 
31202
32754
  // src/http/pages-public.ts
31203
- init_types4();
32755
+ init_types5();
31204
32756
  init_constants3();
31205
32757
  init_page_session();
31206
32758
  init_secret_scrubber();
@@ -31732,11 +33284,12 @@ async function fetchAllBotChannels(client) {
31732
33284
  // src/http/poll.ts
31733
33285
  init_model_pin();
31734
33286
  init_telemetry_trigger();
31735
- init_types4();
33287
+ init_types5();
31736
33288
  init_business_use();
31737
33289
  init_multi_runtime2();
31738
33290
  init_request_auth_context();
31739
33291
  init_runtime_pools_flag();
33292
+ init_secret_scrubber();
31740
33293
  init_route_def();
31741
33294
  init_utils2();
31742
33295
  function buildBudgetRefusedTrigger(refusal) {
@@ -31781,6 +33334,12 @@ var PollTaskAssignedTriggerSchema = object2({
31781
33334
  credentialAllowlist: ModelProfileCredentialsSchema.optional()
31782
33335
  }),
31783
33336
  requestedBy: TaskRequestedBySchema.optional(),
33337
+ checklistNudge: object2({
33338
+ itemId: string2(),
33339
+ kind: string2(),
33340
+ label: string2(),
33341
+ href: string2().optional()
33342
+ }).optional(),
31784
33343
  threadParticipants: TaskThreadParticipantsSchema.optional()
31785
33344
  });
31786
33345
  var PollUnreadMentionsTriggerSchema = object2({
@@ -31837,6 +33396,31 @@ async function attachmentsForTrigger(taskId) {
31837
33396
  sizeBytes: a.sizeBytes
31838
33397
  }));
31839
33398
  }
33399
+ async function buildChecklistNudge(task, agent) {
33400
+ const userId = task.requestedByUserId;
33401
+ if (!agent.isLead || !userId || !["ui", "slack", "chat", "comb"].includes(task.source ?? "")) {
33402
+ return;
33403
+ }
33404
+ try {
33405
+ return await getDbClient2().transaction(async () => {
33406
+ const canEditSwarm = await userGrantCanEditSwarm(userId) ?? true;
33407
+ const item = await firstOpenItem(userId, canEditSwarm);
33408
+ if (!item)
33409
+ return;
33410
+ await markNudged(item.id, task.id, userId);
33411
+ const appUrl = await resolveAppUrl();
33412
+ return {
33413
+ itemId: item.id,
33414
+ kind: item.kind,
33415
+ label: item.label,
33416
+ ...appUrl && { href: `${appUrl}${item.href ?? "/"}` }
33417
+ };
33418
+ });
33419
+ } catch (error) {
33420
+ console.warn("[/api/poll] Checklist nudge failed:", scrubSecrets(error instanceof Error ? error.message : String(error)));
33421
+ return;
33422
+ }
33423
+ }
31840
33424
  async function claimModelFields(task, agent, auth) {
31841
33425
  const pin = taskModelPin(task);
31842
33426
  const cleared = {
@@ -32024,6 +33608,7 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
32024
33608
  });
32025
33609
  });
32026
33610
  const assignedRequestedBy = await buildTaskRequestedBy(pendingTask);
33611
+ const nudge = await buildChecklistNudge(pendingTask, agent);
32027
33612
  const assignedThread = await buildTaskThreadParticipants(pendingTask);
32028
33613
  const assignedTriggerSurface = await resolveTriggerSurface(pendingTask.id, pendingTask.source);
32029
33614
  return {
@@ -32038,6 +33623,7 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
32038
33623
  attachments: await attachmentsForTrigger(pendingTask.id)
32039
33624
  },
32040
33625
  ...assignedRequestedBy && { requestedBy: assignedRequestedBy },
33626
+ ...nudge && { checklistNudge: nudge },
32041
33627
  ...assignedThread && { threadParticipants: assignedThread }
32042
33628
  }
32043
33629
  };
@@ -32515,7 +34101,7 @@ async function handlePoolKeys(req, res, pathSegments, queryParams) {
32515
34101
  // src/http/pricing.ts
32516
34102
  init_zod();
32517
34103
  init_db4();
32518
- init_types4();
34104
+ init_types5();
32519
34105
  init_secret_scrubber();
32520
34106
  init_route_def();
32521
34107
  init_utils2();
@@ -32696,7 +34282,7 @@ init_db4();
32696
34282
  init_default_drift();
32697
34283
  init_registry3();
32698
34284
  init_resolver();
32699
- init_types4();
34285
+ init_types5();
32700
34286
  init_template2();
32701
34287
  init_route_def();
32702
34288
  init_utils2();
@@ -33195,7 +34781,7 @@ init_repo_checked_update();
33195
34781
  init_repo_merge_policy();
33196
34782
  init_rbac();
33197
34783
  init_telemetry();
33198
- init_types4();
34784
+ init_types5();
33199
34785
  init_request_principal();
33200
34786
  init_route_def();
33201
34787
  init_utils2();
@@ -33413,7 +34999,7 @@ init_zod();
33413
34999
  init_auth2();
33414
35000
  init_document();
33415
35001
  init_rooms();
33416
- init_types4();
35002
+ init_types5();
33417
35003
  init_request_auth_context();
33418
35004
  init_request_principal();
33419
35005
  init_route_def();
@@ -33689,7 +35275,7 @@ init_multi_runtime();
33689
35275
  init_db2();
33690
35276
  init_tokens();
33691
35277
  init_rbac();
33692
- init_types4();
35278
+ init_types5();
33693
35279
  init_runtime_pools_flag();
33694
35280
  init_secret_scrubber();
33695
35281
  init_request_principal();
@@ -34300,8 +35886,8 @@ async function readWorkflowSavings(opts) {
34300
35886
  const client = getDbClient2();
34301
35887
  const { firstDay, lastDay, ...window } = savingsWindow(opts.days, opts.now);
34302
35888
  const calendarDays = daysBetween(firstDay, lastDay);
34303
- const marker = await client.get("SELECT count(*) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='workflow' AND modelVersion=? AND day>=? AND day<=?", [MODEL_VERSION, firstDay, lastDay]);
34304
- const complete = Number(marker?.n) >= calendarDays.length;
35889
+ const marker = await client.get("SELECT count(CASE WHEN day<? THEN 1 END) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='workflow' AND modelVersion=? AND day>=? AND day<=?", [lastDay, MODEL_VERSION, firstDay, lastDay]);
35890
+ const complete = Number(marker?.n) >= calendarDays.length - 1;
34305
35891
  const markerAt = marker?.at ?? null;
34306
35892
  const scope = {
34307
35893
  days: opts.days,
@@ -34543,10 +36129,10 @@ async function readScriptSavings(opts) {
34543
36129
  const { firstDay, lastDay, ...window } = savingsWindow(opts.days, opts.now);
34544
36130
  const calendarDays = daysBetween(firstDay, lastDay);
34545
36131
  const [marker, scheduledRows] = await Promise.all([
34546
- client.get("SELECT count(*) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='script' AND modelVersion=? AND day>=? AND day<=?", [MODEL_VERSION, firstDay, lastDay]),
36132
+ client.get("SELECT count(CASE WHEN day<? THEN 1 END) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='script' AND modelVersion=? AND day>=? AND day<=?", [lastDay, MODEL_VERSION, firstDay, lastDay]),
34547
36133
  client.query("SELECT DISTINCT scriptName FROM scheduled_tasks WHERE targetType='script' AND scriptName IS NOT NULL ORDER BY scriptName")
34548
36134
  ]);
34549
- const complete = Number(marker?.n) >= calendarDays.length;
36135
+ const complete = Number(marker?.n) >= calendarDays.length - 1;
34550
36136
  const scheduled = scheduledRows.map((r) => r.scriptName);
34551
36137
  const scope = {
34552
36138
  days: opts.days,
@@ -35962,12 +37548,12 @@ init_validate();
35962
37548
  init_db3();
35963
37549
  init_rbac();
35964
37550
  init_scheduler();
35965
- init_types4();
37551
+ init_types5();
35966
37552
  init_favorite_owner();
35967
37553
  init_request_principal();
35968
37554
  init_route_def();
35969
37555
  init_utils2();
35970
- var import_cron_parser = __toESM(require_dist2(), 1);
37556
+ var import_cron_parser = __toESM(require_dist(), 1);
35971
37557
  var scheduleUpdateBodySchema = object2({
35972
37558
  key: AssetKeySchema.optional(),
35973
37559
  name: string2().optional(),
@@ -37003,7 +38589,8 @@ var oauthPresetSchema = object2({
37003
38589
  tokenBodyFormat: _enum2(["form", "json"]).optional(),
37004
38590
  requiresRefreshTokenRotation: boolean().optional(),
37005
38591
  extraParams: record2(string2(), string2()).optional(),
37006
- setupHints: array2(string2())
38592
+ setupHints: array2(string2()),
38593
+ hiddenInCatalog: boolean().optional()
37007
38594
  });
37008
38595
  var sanitizedAuthorizationSchema = object2({
37009
38596
  id: string2(),
@@ -38748,7 +40335,7 @@ function lintWorkflowLabels(source) {
38748
40335
 
38749
40336
  // src/http/script-runs.ts
38750
40337
  init_follow_up_redelegation_guard();
38751
- init_types4();
40338
+ init_types5();
38752
40339
  init_constants3();
38753
40340
  init_secret_scrubber();
38754
40341
  init_raw_llm();
@@ -39440,7 +41027,7 @@ init_rbac();
39440
41027
  init_registry();
39441
41028
  init_extract_signature();
39442
41029
  init_quickjs_compat();
39443
- init_types4();
41030
+ init_types5();
39444
41031
  init_request_auth_context();
39445
41032
  init_secret_scrubber();
39446
41033
  init_route_def();
@@ -40356,8 +41943,11 @@ async function handleScripts(req, res, pathSegments, queryParams, agentId) {
40356
41943
  // src/http/session-data.ts
40357
41944
  init_zod();
40358
41945
  init_db4();
41946
+ init_users();
40359
41947
  init_otel();
40360
- init_types4();
41948
+ init_types5();
41949
+ init_request_auth_context();
41950
+ init_secret_scrubber();
40361
41951
  init_route_def();
40362
41952
  init_session_access();
40363
41953
 
@@ -40519,7 +42109,9 @@ var SessionCostSummaryTotalsSchema = object2({
40519
42109
  attributableCostUsd: number2(),
40520
42110
  excludedCostUsd: number2(),
40521
42111
  excludedTaskCount: number2().int(),
40522
- subscriptionCostUsd: number2()
42112
+ subscriptionCostUsd: number2(),
42113
+ credentialUnattributedCostUsd: number2(),
42114
+ credentialUnattributedSessions: number2().int()
40523
42115
  });
40524
42116
  var SessionCostDailyRowSchema = object2({
40525
42117
  date: string2(),
@@ -40527,7 +42119,9 @@ var SessionCostDailyRowSchema = object2({
40527
42119
  inputTokens: number2().int(),
40528
42120
  outputTokens: number2().int(),
40529
42121
  sessions: number2().int(),
40530
- subscriptionCostUsd: number2()
42122
+ subscriptionCostUsd: number2(),
42123
+ credentialUnattributedCostUsd: number2(),
42124
+ credentialUnattributedSessions: number2().int()
40531
42125
  });
40532
42126
  var SessionCostByAgentRowSchema = object2({
40533
42127
  agentId: string2(),
@@ -40631,12 +42225,15 @@ var createSessionCostRoute = route({
40631
42225
  id: string2().uuid().optional(),
40632
42226
  sessionId: string2().min(1),
40633
42227
  agentId: string2().min(1),
42228
+ credentialKeyType: string2().regex(/^[A-Z][A-Z0-9_]{0,79}$/).nullable().optional(),
42229
+ credentialKeySuffix: string2().min(1).max(10).nullable().optional(),
42230
+ harness: ProviderNameSchema.nullable().optional(),
40634
42231
  totalCostUsd: number2(),
40635
42232
  harnessCostBilled: boolean().optional(),
40636
42233
  taskId: string2().optional(),
40637
42234
  inputTokens: number2().int().nonnegative().optional(),
40638
42235
  outputTokens: number2().int().nonnegative().optional(),
40639
- cacheReadTokens: number2().int().nonnegative().optional(),
42236
+ cacheReadTokens: number2().int().nonnegative().nullable().optional(),
40640
42237
  cacheWriteTokens: number2().int().nonnegative().nullable().optional(),
40641
42238
  cacheWrite5mTokens: number2().int().nonnegative().nullable().optional(),
40642
42239
  cacheWrite1hTokens: number2().int().nonnegative().nullable().optional(),
@@ -40655,7 +42252,9 @@ var createSessionCostRoute = route({
40655
42252
  description: "Cost record stored",
40656
42253
  schema: object2({ success: literal2(true), cost: SessionCostSchema })
40657
42254
  },
40658
- 400: { description: "Validation error" }
42255
+ 400: { description: "Validation error" },
42256
+ 403: { description: "Untrusted session attribution" },
42257
+ 409: { description: "Session identity conflict" }
40659
42258
  }
40660
42259
  });
40661
42260
  var getSessionCostSummaryRoute = route({
@@ -40774,6 +42373,21 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
40774
42373
  const parsed = await createSessionCostRoute.parse(req, res, pathSegments, queryParams);
40775
42374
  if (!parsed)
40776
42375
  return true;
42376
+ const auth = getRequestAuth(req);
42377
+ const trustedWorker = !auth?.page && (auth?.kind === "operator" || auth?.kind === "agent" && (auth.tokenKind === "runtime" || auth.tokenKind === "agent" && !await isScriptRunToken(auth.tokenId)) && auth.agentId === parsed.body.agentId);
42378
+ const hasAttribution = parsed.body.credentialKeyType != null || parsed.body.credentialKeySuffix != null || parsed.body.harness != null;
42379
+ if (hasAttribution && !trustedWorker) {
42380
+ jsonError(res, "Session attribution requires a worker or operator credential.", 403);
42381
+ return true;
42382
+ }
42383
+ if (auth?.kind === "agent" && auth.agentId !== parsed.body.agentId) {
42384
+ jsonError(res, "Session cost agent does not match the authenticated agent.", 403);
42385
+ return true;
42386
+ }
42387
+ if (parsed.body.credentialKeyType != null !== (parsed.body.credentialKeySuffix != null)) {
42388
+ jsonError(res, "Session credential type and suffix must be supplied together.", 400);
42389
+ return true;
42390
+ }
40777
42391
  try {
40778
42392
  const inputTokens = parsed.body.inputTokens ?? 0;
40779
42393
  const cachedInputTokens = parsed.body.cacheReadTokens ?? 0;
@@ -40783,8 +42397,8 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
40783
42397
  const bodyModels = parsed.body.models?.length ? parsed.body.models : null;
40784
42398
  const rowInputTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.inputTokens, 0) : inputTokens;
40785
42399
  const rowOutputTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.outputTokens, 0) : outputTokens;
40786
- const rowCacheReadTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheReadTokens, 0) : cachedInputTokens;
40787
- const rowCacheWriteTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheWriteTokens, 0) : parsed.body.cacheWriteTokens ?? 0;
42400
+ const rowCacheReadTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheReadTokens, 0) : parsed.body.cacheReadTokens ?? null;
42401
+ const rowCacheWriteTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheWriteTokens, 0) : parsed.body.cacheWriteTokens ?? null;
40788
42402
  const harnessCostUsd = parsed.body.totalCostUsd > 0 ? parsed.body.totalCostUsd : null;
40789
42403
  const recomputed = await recomputeSessionCost({
40790
42404
  provider: parsed.body.provider,
@@ -40802,7 +42416,10 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
40802
42416
  atEpochMs: parsed.body.createdAt ?? Date.now()
40803
42417
  }, async (provider, lookupModel, tokenClass, atEpochMs) => (await getActivePricingRow2(provider, lookupModel, tokenClass, atEpochMs))?.pricePerMillionUsd ?? null);
40804
42418
  const { totalCostUsd, costSource } = recomputed;
40805
- const cost = await createSessionCost2({
42419
+ const { cost, created } = await insertSessionCost2({
42420
+ credentialKeyType: parsed.body.credentialKeyType,
42421
+ credentialKeySuffix: parsed.body.credentialKeySuffix,
42422
+ harness: parsed.body.harness,
40806
42423
  id: parsed.body.id,
40807
42424
  sessionId: parsed.body.sessionId,
40808
42425
  taskId: parsed.body.taskId || undefined,
@@ -40824,26 +42441,32 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
40824
42441
  cacheWrite1hTokens: parsed.body.cacheWrite1hTokens,
40825
42442
  modelBreakdown: recomputed.modelBreakdown
40826
42443
  });
40827
- recordSessionCost2({
40828
- totalCostUsd,
40829
- harnessCostUsd: harnessCostUsd ?? undefined,
40830
- harness: parsed.body.provider ?? "unknown",
40831
- model,
40832
- costSource,
40833
- isError: parsed.body.isError ?? false,
40834
- tokens: {
40835
- input: rowInputTokens,
40836
- output: rowOutputTokens,
40837
- cacheRead: rowCacheReadTokens,
40838
- cacheWrite: rowCacheWriteTokens,
40839
- reasoning: parsed.body.reasoningOutputTokens ?? 0,
40840
- thinking: parsed.body.thinkingTokens ?? 0
40841
- }
40842
- });
40843
- incrementServerSessionsProcessed();
42444
+ if (created) {
42445
+ recordSessionCost2({
42446
+ totalCostUsd,
42447
+ harnessCostUsd: harnessCostUsd ?? undefined,
42448
+ harness: parsed.body.provider ?? "unknown",
42449
+ model,
42450
+ costSource,
42451
+ isError: parsed.body.isError ?? false,
42452
+ tokens: {
42453
+ input: rowInputTokens,
42454
+ output: rowOutputTokens,
42455
+ cacheRead: rowCacheReadTokens ?? 0,
42456
+ cacheWrite: rowCacheWriteTokens ?? 0,
42457
+ reasoning: parsed.body.reasoningOutputTokens ?? 0,
42458
+ thinking: parsed.body.thinkingTokens ?? 0
42459
+ }
42460
+ });
42461
+ incrementServerSessionsProcessed();
42462
+ }
40844
42463
  createSessionCostRoute.respond(res, 201, { success: true, cost });
40845
42464
  } catch (error) {
40846
- console.error("[HTTP] Failed to create session cost:", error);
42465
+ if (error instanceof SessionCostConflictError2) {
42466
+ jsonError(res, error.message, 409);
42467
+ return true;
42468
+ }
42469
+ console.error("[HTTP] Failed to create session cost:", scrubSecrets(String(error)));
40847
42470
  jsonError(res, "Failed to store session cost", 500);
40848
42471
  }
40849
42472
  return true;
@@ -40921,6 +42544,7 @@ init_rbac_roles();
40921
42544
  init_session_shares();
40922
42545
  init_steering2();
40923
42546
  init_task_citations2();
42547
+ init_task_ui_spec();
40924
42548
  init_users();
40925
42549
  init_rbac();
40926
42550
  init_auth2();
@@ -40996,9 +42620,10 @@ function warmSlackChannelLabels(groupKeys) {
40996
42620
  }
40997
42621
 
40998
42622
  // src/http/sessions.ts
40999
- init_types4();
42623
+ init_types5();
41000
42624
  init_request_auth_context();
41001
42625
  init_runtime_pools_flag();
42626
+ init_favorite_owner();
41002
42627
  init_request_principal();
41003
42628
  init_route_def();
41004
42629
  init_session_access();
@@ -41089,6 +42714,7 @@ var SessionKeyFilterSchema = string2().transform((value, ctx) => {
41089
42714
  });
41090
42715
  var TaskWithSteeringSchema = AgentTaskSchema.extend({
41091
42716
  citations: array2(TaskCitationSchema),
42717
+ uiSpec: TaskUiSpecSchema.nullable(),
41092
42718
  isLeadTask: boolean(),
41093
42719
  supportedSteerModes: array2(SteerModeSchema)
41094
42720
  });
@@ -41862,6 +43488,11 @@ async function handleSessions(req, res, pathSegments, queryParams, myAgentId) {
41862
43488
  break;
41863
43489
  }
41864
43490
  const moved = await moveSessionChains({ moves, changedBy });
43491
+ if (key !== null && skipped.length === 0 && remaining === 0 && (await listPrefixRoots({ from, limit: 1 })).length === 0) {
43492
+ const scope = moved.length > 0 ? undefined : (await resolveHttpFavoriteOwner(req, myAgentId))?.scope;
43493
+ if (moved.length > 0 || scope)
43494
+ await moveKeyFavorites({ from, to: key, scope });
43495
+ }
41865
43496
  moveSessionPrefix.respond(res, 200, { moved, skipped, remaining });
41866
43497
  });
41867
43498
  return true;
@@ -41892,9 +43523,10 @@ async function handleSessions(req, res, pathSegments, queryParams, myAgentId) {
41892
43523
  } : null;
41893
43524
  const chain = await withDispatchedTasks(await getRootTaskChain2(parsed.params.rootTaskId), sessionRoot.id, actor);
41894
43525
  const tasks = [root, ...chain];
41895
- const [steering, citations, approvals, read, groupKey] = await Promise.all([
43526
+ const [steering, citations, uiSpecs, approvals, read, groupKey] = await Promise.all([
41896
43527
  getTaskSteeringFieldsForTasks(tasks),
41897
43528
  getTaskCitationsForTasks(tasks.map((task) => task.id)),
43529
+ getTaskUiSpecsForTasks(tasks.map((task) => task.id)),
41898
43530
  getPendingApprovalsForTasks2(tasks.map((task) => task.id)),
41899
43531
  actor.kind === "user" && actor.userId ? getSessionReadState(sessionRoot.id, actor.userId, undefined, actor.readAll) : Promise.resolve(null),
41900
43532
  getSessionGroupKey(root)
@@ -41902,7 +43534,8 @@ async function handleSessions(req, res, pathSegments, queryParams, myAgentId) {
41902
43534
  const decorate = (task) => ({
41903
43535
  ...task,
41904
43536
  ...steering.get(task.id),
41905
- citations: citations.get(task.id)
43537
+ citations: citations.get(task.id),
43538
+ uiSpec: uiSpecs.get(task.id) ?? null
41906
43539
  });
41907
43540
  getSession.respond(res, 200, {
41908
43541
  root: decorate(root),
@@ -42258,7 +43891,7 @@ async function getSkillUsageDetail(skillId, window, tzOffsetMinutes = 0, now = D
42258
43891
  }
42259
43892
 
42260
43893
  // src/http/skills.ts
42261
- init_types4();
43894
+ init_types5();
42262
43895
  init_route_def();
42263
43896
  init_utils2();
42264
43897
  var SYSTEM_DEFAULT_SKILL_LOCKED_MESSAGE = "This skill is system-managed and cannot be edited from the UI; it is re-seeded on each start. Fork it under a new name to customize.";
@@ -43164,6 +44797,92 @@ async function handleSkills(req, res, pathSegments, queryParams, myAgentId) {
43164
44797
  return false;
43165
44798
  }
43166
44799
 
44800
+ // src/http/slack-events.ts
44801
+ init_app3();
44802
+ init_config4();
44803
+ init_route_def();
44804
+ init_utils2();
44805
+ var slackEventsRoute = route({
44806
+ method: "post",
44807
+ path: "/api/integrations/slack/events",
44808
+ pattern: ["api", "integrations", "slack", "events"],
44809
+ summary: "Slack HTTP ingress (SLACK_MODE=http): Events API, slash commands and interactivity at one request URL",
44810
+ tags: ["Slack"],
44811
+ auth: { apiKey: false },
44812
+ rbac: {
44813
+ ungated: "Slack-signed request: HMAC v0 verified with SLACK_SIGNING_SECRET, with a 5-minute timestamp window, before any work"
44814
+ },
44815
+ responses: {
44816
+ 200: {
44817
+ description: "Accepted",
44818
+ unstructured: "Slack ack payload: empty, the url_verification challenge, or a command/interactivity response body"
44819
+ },
44820
+ 400: { description: "Malformed body after a valid signature" },
44821
+ 401: { description: "Missing or invalid signature, or timestamp outside the 5-minute window" },
44822
+ 403: { description: "Delivery for a workspace this swarm does not own" },
44823
+ 404: { description: "Slack is disabled or not in HTTP mode" },
44824
+ 413: { description: "Body exceeds 1 MiB" },
44825
+ 503: {
44826
+ description: "Receiver not ready, workspace unverified, or backlog full; Slack retries"
44827
+ }
44828
+ }
44829
+ });
44830
+ var SLACK_EVENTS_MAX_BODY_BYTES = 1024 * 1024;
44831
+ function header2(req, name) {
44832
+ const value = req.headers[name];
44833
+ return Array.isArray(value) ? value[0] : value;
44834
+ }
44835
+ async function handleSlackEvents(req, res, pathSegments) {
44836
+ if (!slackEventsRoute.match(req.method, pathSegments))
44837
+ return false;
44838
+ const config = getSlackConfiguration();
44839
+ if (config.disabled || config.mode !== "http" || config.missingCredentials.length > 0) {
44840
+ jsonError(res, "Slack HTTP mode is not enabled", 404);
44841
+ return true;
44842
+ }
44843
+ const receiver = getSlackHttpReceiver2();
44844
+ if (!receiver) {
44845
+ res.writeHead(503, { "Content-Type": "application/json", "Retry-After": "5" });
44846
+ res.end(JSON.stringify({ error: "Slack receiver is not ready" }));
44847
+ return true;
44848
+ }
44849
+ if (enforceContentLengthCap(req, res, SLACK_EVENTS_MAX_BODY_BYTES) === BODY_TOO_LARGE) {
44850
+ return true;
44851
+ }
44852
+ const chunks = [];
44853
+ let receivedBytes = 0;
44854
+ let tooLarge = false;
44855
+ for await (const chunk of req) {
44856
+ if (tooLarge)
44857
+ continue;
44858
+ receivedBytes += chunk.byteLength;
44859
+ if (receivedBytes > SLACK_EVENTS_MAX_BODY_BYTES) {
44860
+ tooLarge = true;
44861
+ chunks.length = 0;
44862
+ jsonError(res, `Payload too large (max ${SLACK_EVENTS_MAX_BODY_BYTES} bytes)`, 413);
44863
+ continue;
44864
+ }
44865
+ chunks.push(chunk);
44866
+ }
44867
+ if (tooLarge)
44868
+ return true;
44869
+ const result = await receiver.handle({
44870
+ rawBody: Buffer.concat(chunks),
44871
+ signature: header2(req, "x-slack-signature"),
44872
+ timestamp: header2(req, "x-slack-request-timestamp"),
44873
+ contentType: header2(req, "content-type"),
44874
+ retryNum: header2(req, "x-slack-retry-num"),
44875
+ retryReason: header2(req, "x-slack-retry-reason"),
44876
+ signingSecret: process.env.SLACK_SIGNING_SECRET
44877
+ });
44878
+ res.writeHead(result.status, {
44879
+ ...result.contentType ? { "Content-Type": result.contentType } : {},
44880
+ ...result.headers
44881
+ });
44882
+ res.end(result.body);
44883
+ return true;
44884
+ }
44885
+
43167
44886
  // src/http/slack-inbound.ts
43168
44887
  init_zod();
43169
44888
  init_inbound_dispatch();
@@ -43249,7 +44968,7 @@ async function handleSlackInbound(req, res, pathSegments) {
43249
44968
  init_zod();
43250
44969
  init_db4();
43251
44970
  init_steering2();
43252
- init_types4();
44971
+ init_types5();
43253
44972
  init_env_flag();
43254
44973
  init_multi_runtime2();
43255
44974
  init_favorite_owner();
@@ -43492,7 +45211,7 @@ async function handleStats(req, res, pathSegments, queryParams, myAgentId) {
43492
45211
  // src/http/task-templates.ts
43493
45212
  init_zod();
43494
45213
  init_db4();
43495
- init_types4();
45214
+ init_types5();
43496
45215
  init_route_def();
43497
45216
  var listTemplates = route({
43498
45217
  method: "get",
@@ -44443,7 +46162,7 @@ init_db4();
44443
46162
  init_rbac_roles();
44444
46163
  init_users();
44445
46164
  init_rbac();
44446
- init_types4();
46165
+ init_types5();
44447
46166
 
44448
46167
  // src/http/operator-actor.ts
44449
46168
  init_users();
@@ -44624,10 +46343,11 @@ init_db4();
44624
46343
  init_rbac_roles();
44625
46344
  init_users();
44626
46345
  init_rbac();
44627
- init_types4();
46346
+ init_types5();
44628
46347
  init_constants3();
44629
46348
  init_egress_guard();
44630
46349
  init_request_auth_context();
46350
+ init_secret_scrubber();
44631
46351
  init_route_def();
44632
46352
  init_session_access();
44633
46353
  init_utils2();
@@ -45604,6 +47324,13 @@ async function handleUsers(req, res, pathSegments, queryParams) {
45604
47324
  jsonError(res, "code_invalid", 404);
45605
47325
  return true;
45606
47326
  }
47327
+ getDbClient2().afterCommit(async () => {
47328
+ try {
47329
+ await ensureUserAgentFsAccount(result.userId);
47330
+ } catch (error) {
47331
+ console.warn(scrubSecrets(`[agent-fs] invite account ensure failed: ${error instanceof Error ? error.message : String(error)}`));
47332
+ }
47333
+ });
45607
47334
  exchangeInviteCodeRoute.respond(res, 200, result);
45608
47335
  } catch {
45609
47336
  jsonError(res, "Failed to exchange code", 500);
@@ -46085,6 +47812,7 @@ async function routeKapsoInbound(payload) {
46085
47812
  // src/http/webhooks.ts
46086
47813
  init_errors2();
46087
47814
  init_constants3();
47815
+ init_github_host();
46088
47816
  init_secret_scrubber();
46089
47817
  init_azure_devops();
46090
47818
  init_workflows();
@@ -46357,6 +48085,11 @@ async function handleWebhooks(req, res, pathSegments) {
46357
48085
  res.end(JSON.stringify({ error: "Invalid signature" }));
46358
48086
  return true;
46359
48087
  }
48088
+ const enterpriseHost = req.headers["x-github-enterprise-host"];
48089
+ const configuredHost = resolveGitHubHost();
48090
+ if (enterpriseHost && configuredHost.ok && enterpriseHost.toLowerCase() !== configuredHost.config.host) {
48091
+ console.warn(`[GitHub] Webhook from GHES host ${enterpriseHost}, but GITHUB_URL resolves to ${configuredHost.config.host}`);
48092
+ }
46360
48093
  if (eventType === "ping") {
46361
48094
  console.log("[GitHub] Received ping event - webhook configured successfully");
46362
48095
  githubWebhook.respond(res, 200, { message: "pong" });
@@ -47047,7 +48780,7 @@ init_audit_user();
47047
48780
  init_db4();
47048
48781
  init_workflow_idempotency();
47049
48782
  init_workflow_runs();
47050
- init_types4();
48783
+ init_types5();
47051
48784
  init_workflows();
47052
48785
  init_definition2();
47053
48786
  init_engine();
@@ -48344,6 +50077,7 @@ var httpServer = createHttpServer(async (req, res) => {
48344
50077
  () => handleRealtimeTicket(req, res, pathSegments, queryParams),
48345
50078
  () => handleRealtimeAsset(req, res),
48346
50079
  () => handleIntegrations(req, res, pathSegments, queryParams),
50080
+ () => handleSlackEvents(req, res, pathSegments),
48347
50081
  () => handleSlackInbound(req, res, pathSegments),
48348
50082
  () => handlePromptTemplates(req, res, pathSegments, queryParams),
48349
50083
  () => handleDbQuery(req, res, pathSegments, queryParams),
@@ -48373,6 +50107,7 @@ var httpServer = createHttpServer(async (req, res) => {
48373
50107
  () => handleEvents(req, res, pathSegments, queryParams, myAgentId),
48374
50108
  () => handleRuntimePools(req, res, pathSegments, queryParams, myAgentId),
48375
50109
  () => handleExtensions(req, res, pathSegments, queryParams, myAgentId),
50110
+ () => handleChecklist(req, res, pathSegments, queryParams, myAgentId),
48376
50111
  () => handleFavorites(req, res, pathSegments, queryParams, myAgentId),
48377
50112
  () => handleUserRoles(req, res, pathSegments, queryParams),
48378
50113
  () => handleUsers(req, res, pathSegments, queryParams),
@@ -48411,7 +50146,7 @@ var httpServer = createHttpServer(async (req, res) => {
48411
50146
  });
48412
50147
  });
48413
50148
  var detachRealtime = attachRealtimeTransport(httpServer);
48414
- var { attachControllerTransport } = await import("./controllers-connect-63j5rdcm.js");
50149
+ var { attachControllerTransport } = await import("./controllers-connect-ks155r0h.js");
48415
50150
  var detachControllers = attachControllerTransport(httpServer);
48416
50151
  var stopWorkerNudges = startWorkerNudgeListener();
48417
50152
  var taskAutoTitles = startTaskAutoTitleListener();
@@ -48442,7 +50177,7 @@ async function shutdown() {
48442
50177
  sessionsProcessed: getServerSessionsProcessed()
48443
50178
  });
48444
50179
  if (hasCapability("scheduling")) {
48445
- const { stopScheduler } = await import("./index-8w2aznds.js");
50180
+ const { stopScheduler } = await import("./index-cxca2t8y.js");
48446
50181
  stopScheduler();
48447
50182
  }
48448
50183
  stopHeartbeat2();
@@ -48454,7 +50189,7 @@ async function shutdown() {
48454
50189
  await stopSlackApp2();
48455
50190
  await stopChatSdk();
48456
50191
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
48457
- const { stopOAuthKeepalive } = await import("./keepalive-k2a3qe73.js");
50192
+ const { stopOAuthKeepalive } = await import("./keepalive-sh02349h.js");
48458
50193
  await stopOAuthKeepalive();
48459
50194
  }
48460
50195
  stopOAuthPendingGc();
@@ -48539,21 +50274,21 @@ try {
48539
50274
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
48540
50275
  }
48541
50276
  try {
48542
- const { ensurePricingSeeded } = await import("./boot-seeds-n2b3dx4e.js");
50277
+ const { ensurePricingSeeded } = await import("./boot-seeds-ce7rvgq1.js");
48543
50278
  ensurePricingSeeded();
48544
- const { startPricingRefreshLoop } = await import("./pricing-refresh-1nj722h6.js");
50279
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-c6b325mk.js");
48545
50280
  startPricingRefreshLoop();
48546
50281
  } catch (err) {
48547
50282
  console.error("[startup] Failed to seed pricing rows:", err);
48548
50283
  }
48549
50284
  try {
48550
- const { ensureModelProfilesSeeded } = await import("./boot-seeds-n2b3dx4e.js");
50285
+ const { ensureModelProfilesSeeded } = await import("./boot-seeds-ce7rvgq1.js");
48551
50286
  await ensureModelProfilesSeeded();
48552
50287
  } catch (err) {
48553
50288
  console.error("[startup] Failed to seed model profiles:", err);
48554
50289
  }
48555
50290
  try {
48556
- const { ensureRbacSeeded } = await import("./boot-seeds-n2b3dx4e.js");
50291
+ const { ensureRbacSeeded } = await import("./boot-seeds-ce7rvgq1.js");
48557
50292
  ensureRbacSeeded();
48558
50293
  } catch (err) {
48559
50294
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -48561,11 +50296,17 @@ try {
48561
50296
  throw err;
48562
50297
  }
48563
50298
  try {
48564
- const { runAllSeeders } = await import("./index-3yvzbhxd.js");
50299
+ const { runAllSeeders } = await import("./index-9zkchs9t.js");
48565
50300
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
48566
50301
  } catch (err) {
48567
50302
  console.error("[startup] Failed to seed built-in entities:", err);
48568
50303
  }
50304
+ try {
50305
+ const { runImports } = await import("./index-rv89fvzf.js");
50306
+ await runImports();
50307
+ } catch (err) {
50308
+ console.error("[startup] File import failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
50309
+ }
48569
50310
  try {
48570
50311
  await loadEnabledExtensions();
48571
50312
  } catch (err) {
@@ -48612,6 +50353,9 @@ httpServer.listen(port, async () => {
48612
50353
  startChatSdk().catch((err) => {
48613
50354
  console.error("[chat-sdk] Failed to start, continuing without Chat SDK:", scrubSecrets(err instanceof Error ? err.message : String(err)));
48614
50355
  });
50356
+ import("./agent-fs-provision-b5dhdsbd.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
50357
+ console.warn("[agent-fs] Failed to set the org swarm URL:", scrubSecrets(err instanceof Error ? err.message : String(err)));
50358
+ });
48615
50359
  startQueueStallAlarm();
48616
50360
  initGitHub();
48617
50361
  initGitLab();
@@ -48624,25 +50368,25 @@ httpServer.listen(port, async () => {
48624
50368
  await initWorkflows2();
48625
50369
  await startScriptRunSupervisor(getMcpBaseUrl());
48626
50370
  if (hasCapability("scheduling")) {
48627
- const { startScheduler } = await import("./index-8w2aznds.js");
48628
- const { getExecutorRegistry } = await import("./index-qnjvr362.js");
50371
+ const { startScheduler } = await import("./index-cxca2t8y.js");
50372
+ const { getExecutorRegistry } = await import("./index-25pvya7q.js");
48629
50373
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
48630
50374
  startScheduler(getExecutorRegistry(), intervalMs, {
48631
50375
  runId: globalState.__runId
48632
50376
  });
48633
50377
  }
48634
50378
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
48635
- const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-yzxd3sn9.js");
50379
+ const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-2t4859r5.js");
48636
50380
  startHeartbeat(parseHeartbeatIntervalMs(process.env.HEARTBEAT_INTERVAL_MS));
48637
50381
  }
48638
50382
  startPoolRouting();
48639
50383
  startRuntimeSupervisor();
48640
50384
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
48641
- const { startOAuthKeepalive } = await import("./keepalive-k2a3qe73.js");
50385
+ const { startOAuthKeepalive } = await import("./keepalive-sh02349h.js");
48642
50386
  startOAuthKeepalive();
48643
50387
  }
48644
50388
  if (!isEnvFlagEnabled("OAUTH_REFRESH_SWEEP_DISABLE", false)) {
48645
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-y7rm6bkb.js");
50389
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-d9xedk66.js");
48646
50390
  startOAuthRefreshSweep();
48647
50391
  }
48648
50392
  startOAuthPendingGc();
@@ -48652,19 +50396,19 @@ httpServer.listen(port, async () => {
48652
50396
  startSavingsRollup(savingsRollupSql);
48653
50397
  startHumanFreeDrain();
48654
50398
  startTaskSearchBackfill();
48655
- import("./embedding-space-wh8de1t9.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
50399
+ import("./embedding-space-qhw4g68n.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
48656
50400
  setDeploymentEnvReader(getDeploymentEnvValue);
48657
50401
  return runEmbeddingMaintenance({ backfill: true });
48658
50402
  }).catch((err) => {
48659
50403
  console.error("[embedding-space] startup maintenance failed (non-fatal):", err);
48660
50404
  });
48661
- import("./boot-args-schema-4vb0xsat.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
50405
+ import("./boot-args-schema-3gwy0f60.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
48662
50406
  console.error("[boot-args-schema] startup backfill failed (non-fatal):", err);
48663
50407
  });
48664
- import("./boot-scrub-sweep-yrytg42z.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
50408
+ import("./boot-scrub-sweep-7dkdzqxx.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
48665
50409
  console.error("[boot-scrub-sweep] startup scrub failed (non-fatal):", err);
48666
50410
  });
48667
- import("./session-source-backfill-gxxwfh12.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
50411
+ import("./session-source-backfill-v8mt0zwn.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
48668
50412
  console.error("[session-source-backfill] startup run failed (non-fatal):", err);
48669
50413
  });
48670
50414
  }).on("error", (err) => {