@desplega.ai/agent-swarm 2.9.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (453) hide show
  1. package/dist/acp-adapter-bht22g3k.js +16 -0
  2. package/dist/{acp-targets-swxq55dr.js → acp-targets-arrwv4f0.js} +7 -7
  3. package/dist/{actions-pb678g3e.js → actions-y0d2n1c2.js} +102 -21
  4. package/dist/{agent-fs-provision-dmhnc38q.js → agent-fs-provision-tpj7sktd.js} +4 -4
  5. package/dist/{amp-adapter-3pa66q27.js → amp-adapter-vmmnmw8d.js} +2 -2
  6. package/dist/{anthropic-messages-x2cp5fvf.js → anthropic-messages-zdca3gv1.js} +22 -22
  7. package/dist/{app-17d12ev4.js → app-wb7w45dq.js} +6 -3
  8. package/dist/{approval-notifications-h7vd9pmg.js → approval-notifications-7mqr6vbd.js} +8 -5
  9. package/dist/{assistant-t7k39ree.js → assistant-gf60454p.js} +23 -21
  10. package/dist/{boot-args-schema-0gqmkfbe.js → boot-args-schema-qxmd59sr.js} +1 -1
  11. package/dist/{boot-reembed-f064w382.js → boot-reembed-5tmeskj2.js} +1 -1
  12. package/dist/{boot-reembed-n6anc01d.js → boot-reembed-wb44vc3s.js} +1 -1
  13. package/dist/boot-scrub-sweep-25bxhnw4.js +9 -0
  14. package/dist/{boot-seeds-f99fjs5q.js → boot-seeds-nj9za0vk.js} +4 -4
  15. package/dist/{claude-adapter-gvznwxgc.js → claude-adapter-d3krpdyb.js} +7 -7
  16. package/dist/{claude-managed-adapter-pbrbvc64.js → claude-managed-adapter-t8nfgcgz.js} +2 -2
  17. package/dist/{claude-managed-setup-kdxttvc3.js → claude-managed-setup-7y4pwd81.js} +3 -3
  18. package/dist/{claude-sdk-session-0t2teq6n.js → claude-sdk-session-d138zy0e.js} +7 -7
  19. package/dist/{cli-6dp0jkfj.js → cli-01k6wpr9.js} +4 -4
  20. package/dist/{cli-c07v0qfa.js → cli-124ntmf0.js} +83 -74
  21. package/dist/{cli-1tvdx9t5.js → cli-2rnd5j3t.js} +1 -1
  22. package/dist/{cli-4ghh072d.js → cli-2spnz7ye.js} +36 -36
  23. package/dist/{cli-dd37e0cm.js → cli-2v2zdm0a.js} +1 -1
  24. package/dist/{cli-aa8s22gn.js → cli-3aaeb78m.js} +195 -186
  25. package/dist/{cli-8x8y70av.js → cli-3caf7pmg.js} +2 -2
  26. package/dist/{cli-jd3kxppb.js → cli-3et6fmfe.js} +1 -1
  27. package/dist/{cli-kaa4bd7x.js → cli-3f8zbtqa.js} +9 -8
  28. package/dist/{cli-57pvhnyt.js → cli-43evxwj4.js} +1 -1
  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-2tnbc3gw.js → cli-539h29es.js} +2379 -66
  33. package/dist/{cli-rts1qvb4.js → cli-5qhfv9rw.js} +2 -2
  34. package/dist/{cli-faf46gdq.js → cli-6037prsx.js} +10 -10
  35. package/dist/{cli-bk9v1xrv.js → cli-6cwr32fe.js} +25 -25
  36. package/dist/{cli-812paz57.js → cli-6ehs4mta.js} +18 -2
  37. package/dist/{cli-95930z69.js → cli-6ym4jhzp.js} +2 -2
  38. package/dist/{cli-zg3z63x3.js → cli-7mv4h3sn.js} +1 -1
  39. package/dist/{cli-9a2rtd77.js → cli-7r162fxe.js} +24 -15
  40. package/dist/{cli-eg437b5p.js → cli-7sf9sb0w.js} +2 -1
  41. package/dist/{cli-vw5x18yj.js → cli-8st34zhr.js} +20 -10
  42. package/dist/{cli-fgphc007.js → cli-91pkxres.js} +1 -1
  43. package/dist/{cli-2kg31ted.js → cli-9fjr27ez.js} +11 -11
  44. package/dist/{cli-wr1h0k28.js → cli-9w8712tq.js} +617 -278
  45. package/dist/cli-aw83sr40.js +98 -0
  46. package/dist/{cli-ssvdrk4y.js → cli-b6px1k1q.js} +1 -1
  47. package/dist/{cli-w7dxb2fj.js → cli-cc93xzes.js} +6 -6
  48. package/dist/{cli-js8zrfyg.js → cli-fcfbct2j.js} +5 -5
  49. package/dist/{cli-3zxdz9r7.js → cli-fq2rr3jb.js} +6 -6
  50. package/dist/{boot-scrub-sweep-ejd5dnrz.js → cli-had1p04a.js} +8 -9
  51. package/dist/{cli-7cgf614g.js → cli-j6te8keb.js} +5 -5
  52. package/dist/{cli-25nstr34.js → cli-jrbq4djp.js} +1 -1
  53. package/dist/{cli-pz1c00aa.js → cli-k3q2va86.js} +2 -2
  54. package/dist/{cli-nhq5js1b.js → cli-k5yewqgd.js} +3 -3
  55. package/dist/cli-kbtzfrxj.js +404 -0
  56. package/dist/{cli-dx439zpg.js → cli-kpgcm7xy.js} +13 -1
  57. package/dist/{cli-mc1fx4xd.js → cli-m9cvf7vs.js} +10 -10
  58. package/dist/{cli-kmvcm34h.js → cli-md50mj0r.js} +2 -2
  59. package/dist/{cli-q8cfh1t9.js → cli-mk7c5ac4.js} +1 -1
  60. package/dist/cli-mys27d03.js +321 -0
  61. package/dist/{cli-spzkdgtg.js → cli-n3qe7tyr.js} +172 -168
  62. package/dist/{cli-7akn6ze9.js → cli-nh7x3133.js} +7 -28
  63. package/dist/{cli-fnh4b12r.js → cli-nstkanmx.js} +6 -6
  64. package/dist/{cli-g3zzby8t.js → cli-nv4xsvmk.js} +5 -5
  65. package/dist/{cli-sn4pc4qx.js → cli-p0c3vtch.js} +2 -2
  66. package/dist/{cli-5ntc4we6.js → cli-p0n7b5rz.js} +859 -2058
  67. package/dist/{cli-pn1v1pb0.js → cli-psffsanb.js} +3 -2
  68. package/dist/{cli-svc803vq.js → cli-q5srsxq2.js} +15 -15
  69. package/dist/{cli-nmcpzbty.js → cli-qrta34nb.js} +4 -4
  70. package/dist/{cli-k09cxm6m.js → cli-qx4f057j.js} +2 -2
  71. package/dist/{cli-eepnpee7.js → cli-s1khw52h.js} +12 -12
  72. package/dist/{cli-h474mvp5.js → cli-s1zqk1aj.js} +21 -11
  73. package/dist/{cli-8axx8vnw.js → cli-sb4426be.js} +10 -10
  74. package/dist/{cli-kqh27v2y.js → cli-th1dkc2v.js} +1 -1
  75. package/dist/{cli-cw7mc1je.js → cli-tr27kwyg.js} +3 -3
  76. package/dist/{cli-5kcmxwxv.js → cli-tvgqesec.js} +7 -5
  77. package/dist/{cli-a9hfzg2r.js → cli-ty3gha1p.js} +6 -6
  78. package/dist/{cli-fjggej24.js → cli-v46zsvqk.js} +1 -1
  79. package/dist/{cli-5gygrr67.js → cli-v8z0yga9.js} +4 -4
  80. package/dist/{cli-k7pt28ad.js → cli-vfqvrd82.js} +5 -5
  81. package/dist/{cli-vvgaz8t6.js → cli-vq2eg24x.js} +2 -2
  82. package/dist/{cli-pwsax0vp.js → cli-vsw91x06.js} +23 -22
  83. package/dist/{cli-7fx9jyfs.js → cli-w1q68d8x.js} +67 -11
  84. package/dist/{cli-c5cspahx.js → cli-wafmk3fn.js} +45 -20
  85. package/dist/{cli-ymct0ycy.js → cli-wwp1bd3n.js} +5495 -5095
  86. package/dist/{cli-me4maa4j.js → cli-y4ccxtz5.js} +45 -9
  87. package/dist/{cli-m1fbz2wj.js → cli-y8p78ekx.js} +178 -19
  88. package/dist/{cli-nr46j5pw.js → cli-z0m452jr.js} +1 -1
  89. package/dist/{cli-gddgcnav.js → cli-zeh2mhkg.js} +1 -1
  90. package/dist/{cli-e9973bf0.js → cli-zk7v5s89.js} +2 -2
  91. package/dist/cli.js +24 -23
  92. package/dist/{cloudflare-workers-ai-system-one-9y1zx3pt.js → cloudflare-workers-ai-system-one-4aysy6rh.js} +2 -2
  93. package/dist/{codex-adapter-44yq2fkn.js → codex-adapter-exfdbj73.js} +6 -6
  94. package/dist/{codex-hook-h1zb7cfk.js → codex-hook-59atdwd8.js} +1 -1
  95. package/dist/{codex-login-cdyrr5y1.js → codex-login-a239g1ah.js} +1 -1
  96. package/dist/{codex-session-runner-zbh26gbw.js → codex-session-runner-xhznc4g3.js} +6 -6
  97. package/dist/{commands-54f02v5b.js → commands-d8g349v4.js} +3 -3
  98. package/dist/{controller-9gpwcdek.js → controller-mwgdmb8y.js} +6 -3
  99. package/dist/{controllers-connect-61re6k1n.js → controllers-connect-5v7qx04j.js} +22 -20
  100. package/dist/core-sxy4epp2.js +38 -0
  101. package/dist/{cursor-adapter-7e4g81vd.js → cursor-adapter-p2q5h35d.js} +1 -1
  102. package/dist/{db-wnh0qjy1.js → db-qpganbeb.js} +3 -3
  103. package/dist/{db-dg2gc7fd.js → db-wcw0b2j8.js} +8 -2
  104. package/dist/{dispatcher-jrm24r43.js → dispatcher-8d8s49yz.js} +20 -18
  105. package/dist/{docker-9aq30pp2.js → docker-09tkkg0n.js} +42 -3
  106. package/dist/{dsh-adapter-1yqk267c.js → dsh-adapter-me0twn13.js} +1 -1
  107. package/dist/{easter-egg-3d-r4h9cs9m.js → easter-egg-3d-wv7w5ty6.js} +1 -1
  108. package/dist/{embedding-space-bafjr5f7.js → embedding-space-e48xchqa.js} +6 -6
  109. package/dist/{embeddings-7xmgqe0e.js → embeddings-tgq2afbq.js} +1 -1
  110. package/dist/{execute-d6jg5ns0.js → execute-8rhwrk7f.js} +1 -1
  111. package/dist/{external-channel-frq1xvq2.js → external-channel-8bt3j2pm.js} +2 -2
  112. package/dist/fx-adapter-adtdb3jb.js +19 -0
  113. package/dist/{google-generative-ai-hh7strj3.js → google-generative-ai-bh0djqjp.js} +5 -5
  114. package/dist/{google-vertex-fy5bw2pm.js → google-vertex-prjbw8dj.js} +9 -9
  115. package/dist/grok-adapter-accnn9km.js +19 -0
  116. package/dist/handlers-1x77561e.js +35 -0
  117. package/dist/{heartbeat-6bpa611t.js → heartbeat-x0056ra5.js} +23 -21
  118. package/dist/{hook-hvm5nf46.js → hook-a7vmn2st.js} +5 -5
  119. package/dist/{hook-w12k146y.js → hook-mrd2ayxv.js} +6 -6
  120. package/dist/{http-43tthdvs.js → http-ym9c5svp.js} +1335 -363
  121. package/dist/{index-fn054vsf.js → index-01ns1pkw.js} +1 -1
  122. package/dist/{index-1f0vypbg.js → index-0h6qd4p1.js} +34 -24
  123. package/dist/index-48qzcqzj.js +35 -0
  124. package/dist/{index-4b1q8kan.js → index-4k7m5dgj.js} +629 -354
  125. package/dist/index-620y7jzq.js +15 -0
  126. package/dist/{index-cret47a5.js → index-8p0j4h4j.js} +506 -43
  127. package/dist/{index-m5gx1xd6.js → index-9myfj74s.js} +40 -40
  128. package/dist/{index-bs7gw5fd.js → index-b5wgnm78.js} +44 -44
  129. package/dist/{index-ftywhyr0.js → index-ny60jcat.js} +394 -66
  130. package/dist/{index-tx9mc2ap.js → index-p46tvwtx.js} +24 -22
  131. package/dist/{index-585gyczt.js → index-pe3d8jfy.js} +3 -3
  132. package/dist/index-rkvaambe.js +36 -0
  133. package/dist/{index-mhq4sh5w.js → index-x6azjwm8.js} +1 -1
  134. package/dist/index-xj1mq27m.js +40 -0
  135. package/dist/k8s-m56sw868.js +217 -0
  136. package/dist/{keepalive-rk0j0jvh.js → keepalive-7yxg8z4c.js} +3 -3
  137. package/dist/lead-enzn86bz.js +74 -0
  138. package/dist/{maintenance-g6z6kaxw.js → maintenance-6tefxmk1.js} +1 -1
  139. package/dist/{node-jftbyawr.js → node-2wfcey7d.js} +1 -1
  140. package/dist/{oauth-refresh-sweep-2k3g2q4w.js → oauth-refresh-sweep-70cavc3a.js} +2 -2
  141. package/dist/{onboard-6fdbvh3v.js → onboard-fja65z08.js} +5 -5
  142. package/dist/{openai-decisions-q3hh60wr.js → openai-decisions-ytp6w6xh.js} +1 -1
  143. package/dist/{opencode-adapter-fdbsvts7.js → opencode-adapter-hakkm7yh.js} +6 -6
  144. package/dist/{otel-impl-rvwtc09q.js → otel-impl-7zhnt6gj.js} +1 -1
  145. package/dist/{pending-sqkrb836.js → pending-h01yzpx4.js} +21 -19
  146. package/dist/{pi-mono-adapter-asqayqcg.js → pi-mono-adapter-f52hz743.js} +40 -13
  147. package/dist/{pricing-refresh-f5tkgmw2.js → pricing-refresh-fzxvk2zf.js} +2 -2
  148. package/dist/{rbac-roles-06s555fa.js → rbac-roles-9v6vhgbs.js} +3 -3
  149. package/dist/{rbac-roles-szxsg8t1.js → rbac-roles-hfgh8sba.js} +2 -2
  150. package/dist/{render-v2-103p266q.js → render-v2-1rgspxzf.js} +6 -3
  151. package/dist/{resume-v7kjewt9.js → resume-tqy61x24.js} +10 -7
  152. package/dist/{runtime-f1gmk0b7.js → runtime-exkxyx5f.js} +1 -1
  153. package/dist/{session-access-6shev8ts.js → session-access-3act7vt4.js} +4 -4
  154. package/dist/{session-source-backfill-bd7spzjd.js → session-source-backfill-82qe7fqq.js} +3 -3
  155. package/dist/{setup-kmxmztdb.js → setup-ry1vfdef.js} +1 -1
  156. package/dist/thread-buffer-3x93yexa.js +38 -0
  157. package/dist/{typesafe-system-one-f2en2knd.js → typesafe-system-one-vcfj2ak8.js} +2 -2
  158. package/dist/user-merge-jobs-bx6bf7db.js +22 -0
  159. package/dist/{virtual-modules-57eje5wy.js → virtual-modules-s0rjzcqq.js} +3 -3
  160. package/dist/{work-objects-zr47ygmf.js → work-objects-z2e5tv03.js} +29 -23
  161. package/dist/{worker-follow-up-grrr3fda.js → worker-follow-up-y3xeg89w.js} +20 -18
  162. package/dist/worker-zfcv2wbf.js +74 -0
  163. package/openapi.json +2763 -147
  164. package/package.json +9 -8
  165. package/src/apps/catalog.generated.json +43 -3
  166. package/src/apps/page-validator.ts +27 -0
  167. package/src/be/boot-seeds.ts +7 -1
  168. package/src/be/db/model-groups.ts +238 -0
  169. package/src/be/db/model-profiles.ts +28 -7
  170. package/src/be/db/session-costs.ts +225 -0
  171. package/src/be/db/session-log-reasoning.ts +36 -0
  172. package/src/be/db/tasks/read.ts +8 -3
  173. package/src/be/db/tasks/write.ts +34 -1
  174. package/src/be/db/user-references.ts +75 -0
  175. package/src/be/db/users/references.ts +185 -0
  176. package/src/be/db-client.ts +70 -19
  177. package/src/be/db.ts +232 -361
  178. package/src/be/key-window-usage.ts +386 -0
  179. package/src/be/memory/demotion-evidence.ts +34 -0
  180. package/src/be/memory/reranker.ts +34 -12
  181. package/src/be/memory/review-recall-filter.ts +83 -0
  182. package/src/be/memory/search-candidates.ts +19 -6
  183. package/src/be/memory/types.ts +11 -0
  184. package/src/be/migrations/303_task_ui_specs.sql +28 -0
  185. package/src/be/migrations/306_provider_account_telemetry.sql +1 -0
  186. package/src/be/migrations/307_session_cost_credential_attribution.sql +23 -0
  187. package/src/be/migrations/310_session_logs_reasoning.sql +12 -0
  188. package/src/be/migrations/312_task_ui_action_runs_repeatable.sql +6 -0
  189. package/src/be/migrations/314_model_groups.sql +85 -0
  190. package/src/be/migrations/318_superseded_workflow_cut_backfill.sql +22 -0
  191. package/src/be/migrations/319_user_fk_indexes.sql +153 -0
  192. package/src/be/migrations/320_session_costs_kind.sql +4 -0
  193. package/src/be/migrations/321_user_merge_jobs.sql +52 -0
  194. package/src/be/pricing-normalize.ts +2 -0
  195. package/src/be/rbac-roles.ts +6 -4
  196. package/src/be/runtime-pools/db.ts +23 -5
  197. package/src/be/runtime-pools/supervisor.ts +15 -1
  198. package/src/be/scripts/db.ts +11 -0
  199. package/src/be/scripts/typecheck.ts +2 -0
  200. package/src/be/seed-model-groups.ts +86 -0
  201. package/src/be/seed-model-profiles.ts +20 -13
  202. package/src/be/seed-scripts/catalog/boot-triage.inline.ts +1 -0
  203. package/src/be/seed-scripts/catalog/boot-triage.ts +1 -0
  204. package/src/be/seed-scripts/catalog/dreaming-gather.ts +165 -1
  205. package/src/be/seed-scripts/catalog/wait-for-task.ts +5 -1
  206. package/src/be/seed-skills/index.ts +3 -0
  207. package/src/be/swarm-config-guard.ts +58 -1
  208. package/src/be/task-ui-spec.ts +259 -0
  209. package/src/be/user-merge-jobs.ts +564 -0
  210. package/src/be/users.ts +41 -23
  211. package/src/commands/controller.ts +3 -0
  212. package/src/commands/credential-outcome-report.ts +13 -3
  213. package/src/commands/onboard/agent-fs-version.ts +1 -1
  214. package/src/commands/onboard/compose-generator.ts +1 -1
  215. package/src/commands/onboard/env-generator.ts +1 -1
  216. package/src/commands/provider-credentials.ts +1 -1
  217. package/src/commands/rate-limit-outcome.ts +6 -0
  218. package/src/commands/runner.ts +34 -53
  219. package/src/extensions/catalog.generated.json +3 -3
  220. package/src/extensions/contract-types.generated.ts +1 -1
  221. package/src/extensions/contract.ts +15 -0
  222. package/src/extensions/dispatcher.ts +14 -4
  223. package/src/github/handlers.ts +57 -0
  224. package/src/github/types.ts +4 -0
  225. package/src/http/all-routes.ts +2 -0
  226. package/src/http/api-keys.ts +258 -30
  227. package/src/http/approval-requests.ts +5 -1
  228. package/src/http/auth.ts +3 -1
  229. package/src/http/config.ts +34 -1
  230. package/src/http/index.ts +13 -0
  231. package/src/http/memory.ts +19 -6
  232. package/src/http/model-groups.ts +277 -0
  233. package/src/http/model-profiles.ts +30 -13
  234. package/src/http/session-data.ts +74 -23
  235. package/src/http/sessions.ts +6 -2
  236. package/src/http/tasks.ts +140 -5
  237. package/src/http/tool-hooks.ts +140 -0
  238. package/src/http/users.ts +142 -19
  239. package/src/http/workflows.ts +19 -1
  240. package/src/integrations/chat-sdk/inbound.ts +8 -2
  241. package/src/integrations/chat-sdk/limits.ts +8 -3
  242. package/src/integrations/chat-sdk/relay.ts +87 -0
  243. package/src/jira/outbound.ts +5 -3
  244. package/src/linear/outbound.ts +5 -1
  245. package/src/prompts/base-prompt.ts +8 -0
  246. package/src/prompts/session-templates.ts +19 -2
  247. package/src/providers/acp-targets.ts +2 -2
  248. package/src/providers/amp-adapter.ts +1 -1
  249. package/src/providers/claude-adapter.ts +27 -4
  250. package/src/providers/claude-flag-settings.ts +39 -1
  251. package/src/providers/codex-adapter.ts +85 -3
  252. package/src/providers/codex-app-server.ts +9 -5
  253. package/src/providers/codex-oauth/auth-json.ts +1 -0
  254. package/src/providers/pi-mono-adapter.ts +35 -2
  255. package/src/providers/pricing-sources.md +41 -0
  256. package/src/providers/types.ts +11 -0
  257. package/src/rbac/legacy-policy.ts +1 -0
  258. package/src/rbac/permissions.ts +5 -0
  259. package/src/runtime-providers/docker.ts +65 -1
  260. package/src/runtime-providers/index.ts +7 -5
  261. package/src/runtime-providers/k8s.ts +250 -0
  262. package/src/scheduler/deferred-task-waits.ts +18 -5
  263. package/src/scripts-runtime/types/stdlib.d.ts +2 -0
  264. package/src/scripts-runtime/types/swarm-extension.d.ts +24 -9
  265. package/src/scripts-runtime/types/swarm-sdk.d.ts +2 -0
  266. package/src/slack/actions.ts +79 -0
  267. package/src/slack/app.ts +22 -15
  268. package/src/slack/blocks.ts +23 -2
  269. package/src/slack/inbound-files.ts +2 -0
  270. package/src/slack/render-v2.ts +154 -23
  271. package/src/slack/responses.ts +3 -2
  272. package/src/slack/work-objects.ts +4 -1
  273. package/src/tasks/errors.ts +5 -0
  274. package/src/tests/acp-adapter.test.ts +30 -6
  275. package/src/tests/api-key-tracking.test.ts +0 -72
  276. package/src/tests/api-keys-status-model-limits.test.ts +93 -1
  277. package/src/tests/api-keys-validation.test.ts +42 -0
  278. package/src/tests/approval-card-resolution.test.ts +7 -1
  279. package/src/tests/approval-requests-notifications.test.ts +11 -1
  280. package/src/tests/apps-catalog-page-frame.test.ts +49 -0
  281. package/src/tests/apps-session-thread.test.ts +79 -0
  282. package/src/tests/base-prompt.test.ts +111 -5
  283. package/src/tests/chat-sdk-relay.test.ts +170 -2
  284. package/src/tests/check-pr-body.test.ts +43 -0
  285. package/src/tests/claude-adapter-binary.test.ts +67 -6
  286. package/src/tests/claude-flag-settings.test.ts +29 -0
  287. package/src/tests/claude-sdk-lifecycle.test.ts +5 -0
  288. package/src/tests/codex-adapter.test.ts +340 -2
  289. package/src/tests/codex-app-server.test.ts +16 -0
  290. package/src/tests/codex-oauth.test.ts +3 -1
  291. package/src/tests/codex-rate-limits.test.ts +384 -0
  292. package/src/tests/credential-check.test.ts +14 -6
  293. package/src/tests/credential-outcome-report.test.ts +20 -0
  294. package/src/tests/db-client.test.ts +146 -0
  295. package/src/tests/db-task-read-contract.test.ts +3 -0
  296. package/src/tests/db-task-write-contract.test.ts +4 -0
  297. package/src/tests/deferred-task-wake.test.ts +63 -1
  298. package/src/tests/deploy-guard.test.ts +7 -7
  299. package/src/tests/deploy-select.test.ts +83 -0
  300. package/src/tests/docker-isolation-config-guard.test.ts +29 -0
  301. package/src/tests/docs-index-footprint.test.js +11 -3
  302. package/src/tests/dreaming-gather-corrections.test.ts +467 -0
  303. package/src/tests/e2e-visuals-comment.test.ts +82 -0
  304. package/src/tests/e2e-visuals-verify-pr.test.ts +138 -0
  305. package/src/tests/event-loop-lag.test.ts +9 -7
  306. package/src/tests/extensions-example-sql-admin-only.test.ts +7 -4
  307. package/src/tests/fixtures/extensions/native-tool-recorder/hooks.ts +26 -0
  308. package/src/tests/fixtures/extensions/native-tool-recorder/manifest.json +10 -0
  309. package/src/tests/fixtures/onboard/content.compose.yml.txt +1 -1
  310. package/src/tests/fixtures/onboard/content.env.txt +1 -1
  311. package/src/tests/fixtures/onboard/dev.compose.yml.txt +1 -1
  312. package/src/tests/fixtures/onboard/dev.env.txt +1 -1
  313. package/src/tests/fixtures/onboard/full-all.compose.yml.txt +1 -1
  314. package/src/tests/fixtures/onboard/full-all.env.txt +1 -1
  315. package/src/tests/fixtures/onboard/full.compose.yml.txt +1 -1
  316. package/src/tests/fixtures/onboard/full.env.txt +1 -1
  317. package/src/tests/fixtures/onboard/research.compose.yml.txt +1 -1
  318. package/src/tests/fixtures/onboard/research.env.txt +1 -1
  319. package/src/tests/fixtures/onboard/solo.compose.yml.txt +1 -1
  320. package/src/tests/fixtures/onboard/solo.env.txt +1 -1
  321. package/src/tests/fixtures/ui-spec-slack/deploys.json +121 -0
  322. package/src/tests/fixtures/ui-spec-slack/incident.json +183 -0
  323. package/src/tests/fixtures/ui-spec-slack/three-charts-stale.json +196 -0
  324. package/src/tests/fixtures/ui-spec-slack/video-rejected-by-slack.json +183 -0
  325. package/src/tests/fixtures/ui-spec-slack/video.json +446 -0
  326. package/src/tests/github-event-filter.test.ts +8 -0
  327. package/src/tests/github-handlers-inline-comments.test.ts +2 -0
  328. package/src/tests/github-handlers-reactions.test.ts +4 -0
  329. package/src/tests/github-handlers.test.ts +3 -0
  330. package/src/tests/github-sender-trust.test.ts +223 -0
  331. package/src/tests/gitleaks-download-retry.test.ts +85 -0
  332. package/src/tests/http-users.test.ts +142 -41
  333. package/src/tests/human-thread-routing.test.ts +187 -0
  334. package/src/tests/jira-outbound-sync.test.ts +33 -1
  335. package/src/tests/k8s-pool-smoke.test.ts +190 -0
  336. package/src/tests/key-window-usage.test.ts +846 -0
  337. package/src/tests/linear-outbound-sync.test.ts +30 -1
  338. package/src/tests/memory-rater-store.test.ts +35 -1
  339. package/src/tests/memory-reranker.test.ts +39 -4
  340. package/src/tests/memory-review-recall-filter.test.ts +205 -0
  341. package/src/tests/migration-318-superseded-workflow-cut-backfill.test.ts +74 -0
  342. package/src/tests/model-groups-api.test.ts +415 -0
  343. package/src/tests/model-profiles-api.test.ts +1 -0
  344. package/src/tests/operator-granted-credentials.test.ts +7 -2
  345. package/src/tests/operator-granted-role-wire.test.ts +2 -1
  346. package/src/tests/pi-mono-adapter.test.ts +79 -0
  347. package/src/tests/preload-env.test.ts +2 -0
  348. package/src/tests/preload.ts +3 -1
  349. package/src/tests/prompt-template-session.test.ts +4 -3
  350. package/src/tests/provider-quota-persistence.test.ts +362 -0
  351. package/src/tests/rate-limit-event.test.ts +22 -0
  352. package/src/tests/rbac-engine.test.ts +1 -0
  353. package/src/tests/reasoning-events.test.ts +164 -0
  354. package/src/tests/routing-affinity-inventory.test.ts +22 -0
  355. package/src/tests/runtime-k8s-pools.test.ts +142 -0
  356. package/src/tests/runtime-pools-db.test.ts +42 -2
  357. package/src/tests/runtime-pools-http.test.ts +47 -2
  358. package/src/tests/runtime-provider-registration.test.ts +5 -14
  359. package/src/tests/runtime-providers-docker.test.ts +91 -0
  360. package/src/tests/runtime-providers-k8s.test.ts +303 -0
  361. package/src/tests/script-connections.test.ts +18 -1
  362. package/src/tests/secret-canary-sweep.test.ts +41 -5
  363. package/src/tests/seed-scripts.test.ts +23 -0
  364. package/src/tests/session-cost-attribution.test.ts +748 -0
  365. package/src/tests/session-costs.test.ts +14 -15
  366. package/src/tests/session-logs.test.ts +83 -0
  367. package/src/tests/sessions-detail-batch.test.ts +7 -0
  368. package/src/tests/short-id.test.ts +23 -0
  369. package/src/tests/slack-blocks.test.ts +69 -0
  370. package/src/tests/slack-render-v2.test.ts +411 -0
  371. package/src/tests/slack-start-reload-race.test.ts +67 -0
  372. package/src/tests/spec-base-url.test.ts +13 -1
  373. package/src/tests/subscription-plans.test.ts +20 -1
  374. package/src/tests/system-one-decide-session-cost.test.ts +196 -0
  375. package/src/tests/task-ui-action-route.test.ts +249 -0
  376. package/src/tests/task-ui-actions.test.ts +195 -0
  377. package/src/tests/task-ui-script-actions.test.ts +517 -0
  378. package/src/tests/task-ui-spec-fallback.test.ts +65 -0
  379. package/src/tests/task-ui-spec.test.ts +368 -0
  380. package/src/tests/tool-hooks-http.test.ts +187 -0
  381. package/src/tests/ui-spec-script-actions-config.test.ts +196 -0
  382. package/src/tests/user-delete-perf.test.ts +321 -0
  383. package/src/tests/user-merge-jobs.test.ts +680 -0
  384. package/src/tests/vcs-provider.test.ts +25 -5
  385. package/src/tests/vendored-openapi.test.ts +13 -1
  386. package/src/tests/workflow-agent-task-retry.test.ts +96 -1
  387. package/src/tests/workflow-foreach-supersede-retry.test.ts +10 -0
  388. package/src/tests/workflow-http-v2.test.ts +27 -0
  389. package/src/tests/workflow-replay.test.ts +10 -1
  390. package/src/tests/workflow-triggers-v2.test.ts +128 -0
  391. package/src/tests/workflow-wait-event.test.ts +109 -1
  392. package/src/tools/defer-task.ts +1 -1
  393. package/src/tools/memory-search.ts +14 -3
  394. package/src/tools/store-progress.ts +69 -3
  395. package/src/tools/swarm-config/delete-config.ts +12 -1
  396. package/src/tools/swarm-config/set-config.ts +8 -0
  397. package/src/tools/system-one-decide.ts +113 -3
  398. package/src/tools/utils.ts +4 -1
  399. package/src/tools/workflows/create-workflow.ts +2 -0
  400. package/src/tools/workflows/update-workflow.ts +3 -1
  401. package/src/types.ts +93 -4
  402. package/src/ui-spec/actions.ts +112 -0
  403. package/src/ui-spec/fallback.ts +19 -0
  404. package/src/ui-spec/schema.ts +38 -0
  405. package/src/ui-spec/script-actions.ts +340 -0
  406. package/src/ui-spec/script-allowlist.ts +48 -0
  407. package/src/ui-spec/slack.ts +17 -0
  408. package/src/ui-spec/validate.ts +169 -0
  409. package/src/utils/codex-rate-limits.ts +159 -0
  410. package/src/utils/credentials.ts +2 -0
  411. package/src/utils/error-tracker.ts +19 -0
  412. package/src/utils/provider-account-telemetry.ts +331 -0
  413. package/src/utils/reasoning-events.ts +107 -0
  414. package/src/utils/short-id.ts +20 -14
  415. package/src/utils/subscription-plans.ts +11 -59
  416. package/src/utils/task-ui-spec.ts +79 -0
  417. package/src/vcs/index.ts +12 -2
  418. package/src/workflows/executors/system-one-decision.ts +2 -2
  419. package/src/workflows/resume.ts +3 -2
  420. package/src/workflows/task-step-routing.ts +38 -13
  421. package/src/workflows/triggers.ts +35 -3
  422. package/templates/extensions/manifest.schema.json +13 -0
  423. package/templates/extensions/sql-admin-only/README.md +2 -1
  424. package/templates/extensions/sql-admin-only/hooks.ts +7 -3
  425. package/templates/extensions/sql-admin-only/manifest.json +1 -1
  426. package/templates/skills/apps/SKILL.md +32 -5
  427. package/templates/skills/apps/content.md +32 -5
  428. package/templates/skills/swarm-docs/content.md +2 -0
  429. package/templates/skills/ui-spec/config.json +14 -0
  430. package/templates/skills/ui-spec/content.md +133 -0
  431. package/templates/workflows/dreaming/content.md +1 -1
  432. package/dist/acp-adapter-jqn86aam.js +0 -16
  433. package/dist/cli-7831nhaw.js +0 -93
  434. package/dist/cli-srtkr1h2.js +0 -12078
  435. package/dist/fx-adapter-0zrkfbkd.js +0 -19
  436. package/dist/grok-adapter-3db1c538.js +0 -19
  437. package/dist/handlers-k22n8mnn.js +0 -33
  438. package/dist/index-8xcyd3mc.js +0 -33
  439. package/dist/index-9sy2bh6n.js +0 -38
  440. package/dist/index-b24j7t2m.js +0 -12797
  441. package/dist/index-wjd56k1v.js +0 -34
  442. package/dist/lead-atxf3q6e.js +0 -72
  443. package/dist/thread-buffer-4yz236d0.js +0 -36
  444. package/dist/worker-p4hbtcy3.js +0 -72
  445. package/dist/{azure-openai-responses-590s1eea.js → azure-openai-responses-b3y7fz36.js} +8 -8
  446. package/dist/{cli-j49yqpvh.js → cli-7evph51z.js} +3 -3
  447. package/dist/{cli-g0vv9dg4.js → cli-8y43jx2r.js} +8 -8
  448. package/dist/{cli-m0cy2vyf.js → cli-k6nejceb.js} +4 -4
  449. package/dist/{mistral-conversations-0c30em7t.js → mistral-conversations-tm2vd4gc.js} +8 -8
  450. package/dist/{openai-codex-responses-bkcd8pjj.js → openai-codex-responses-sxjv60xx.js} +4 -4
  451. package/dist/{openai-completions-f3n69rep.js → openai-completions-0c7qnhsx.js} +20 -20
  452. package/dist/{openai-responses-gbh0wfqe.js → openai-responses-a7h29chp.js} +15 -15
  453. package/dist/{pi-messages-zebyt7gb.js → pi-messages-2j0fpqwq.js} +5 -5
@@ -1,7 +1,35 @@
1
1
  import {
2
2
  bedrockProviderModule
3
- } from "./cli-g0vv9dg4.js";
3
+ } from "./cli-8y43jx2r.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,
@@ -94,6 +99,9 @@ import {
94
99
  isApiOnlyConfigKey,
95
100
  isInternalConfigKey,
96
101
  internalConfigKeyError,
102
+ isHumanOnlyConfigKey,
103
+ humanOnlyConfigKeyError,
104
+ humanOnlyConfigKeyPageError,
97
105
  MAX_DB_RETENTION_DAYS,
98
106
  DB_RETENTION_TUNING_BOUNDS,
99
107
  CODEX_OAUTH_KEEP_WARM_MAX_AGE_HOURS_BOUNDS,
@@ -155,6 +163,9 @@ import {
155
163
  init_key_paths,
156
164
  rerank,
157
165
  init_reranker,
166
+ isReviewTaskId,
167
+ dropReviewTaskCompletions,
168
+ init_review_recall_filter,
158
169
  searchMemoryCandidates,
159
170
  init_search_candidates,
160
171
  getEmbeddingProvider2,
@@ -206,8 +217,6 @@ import {
206
217
  init_vcs_repo_match,
207
218
  taskModelPin,
208
219
  init_model_pin,
209
- normalizeModelKey,
210
- init_pricing_normalize,
211
220
  upsertModelCatalogOverlay,
212
221
  deleteModelCatalogOverlay,
213
222
  loadModelsCatalog,
@@ -254,6 +263,7 @@ import {
254
263
  updateModelProfile,
255
264
  modelProfileReferences,
256
265
  modelProfileRefError,
266
+ isModelNameTakenError,
257
267
  deleteModelProfile,
258
268
  MAX_MODEL_PROFILE_FALLBACKS,
259
269
  modelProfileFallbacksError,
@@ -358,7 +368,6 @@ import {
358
368
  claimMentions2,
359
369
  createSessionLogs2,
360
370
  getSessionLogsByTaskId2,
361
- createSessionCost2,
362
371
  getSessionCostsByTaskId2,
363
372
  getSessionCostsByAgentId2,
364
373
  getAllSessionCosts2,
@@ -481,7 +490,6 @@ import {
481
490
  getAllUsers2,
482
491
  createUser2,
483
492
  updateUser2,
484
- deleteUser2,
485
493
  listInboxState2,
486
494
  upsertInboxState2,
487
495
  listFavorites2,
@@ -534,7 +542,7 @@ import {
534
542
  countScriptRunJournalSteps2,
535
543
  countScriptRunJournalAgentTaskSteps2,
536
544
  init_db4
537
- } from "./cli-ymct0ycy.js";
545
+ } from "./cli-wwp1bd3n.js";
538
546
  import {
539
547
  PRIMARY_ROLE_NAMES2,
540
548
  OperatorGrantedTargetError2,
@@ -548,17 +556,28 @@ import {
548
556
  assertNotLastAdmin2,
549
557
  setUserRoles2,
550
558
  init_rbac_roles
551
- } from "./cli-k7pt28ad.js";
552
- import"./cli-7831nhaw.js";
559
+ } from "./cli-vfqvrd82.js";
560
+ import {
561
+ MAX_MODEL_GROUP_MEMBERS,
562
+ listModelGroups,
563
+ getModelGroupByName,
564
+ createModelGroup,
565
+ updateModelGroup,
566
+ modelGroupReferences,
567
+ deleteModelGroup,
568
+ init_model_groups
569
+ } from "./cli-mys27d03.js";
553
570
  import {
554
571
  requestModelCatalogRefresh2,
555
572
  init_pricing_refresh
556
- } from "./cli-kqh27v2y.js";
573
+ } from "./cli-th1dkc2v.js";
557
574
  import {
558
575
  workflowEventBus2,
559
576
  init_event_bus
560
577
  } from "./cli-q2d3e1k1.js";
561
- import"./cli-q8cfh1t9.js";
578
+ import"./cli-mk7c5ac4.js";
579
+ import"./cli-9w8712tq.js";
580
+ import"./cli-47hz21se.js";
562
581
  import {
563
582
  require_dist4,
564
583
  getSlackConnectionState,
@@ -579,6 +598,10 @@ import {
579
598
  getTaskCitations,
580
599
  getTaskCitationsForTasks,
581
600
  init_task_citations2,
601
+ TaskUiSpecSchema,
602
+ getTaskUiSpec,
603
+ getTaskUiSpecsForTasks,
604
+ init_task_ui_spec,
582
605
  initialize,
583
606
  ensure,
584
607
  init_business_use,
@@ -590,7 +613,7 @@ import {
590
613
  startSlackApp2,
591
614
  stopSlackApp2,
592
615
  init_app3
593
- } from "./cli-2tnbc3gw.js";
616
+ } from "./cli-539h29es.js";
594
617
  import {
595
618
  AGENT_MAX_TASKS_CONFIG_KEY,
596
619
  reconcileAgentMaxTasksPolicy,
@@ -618,12 +641,12 @@ import {
618
641
  dispatchApprovalNotifications2,
619
642
  createApprovalFollowUpTask2,
620
643
  init_approval_notifications
621
- } from "./cli-w7dxb2fj.js";
644
+ } from "./cli-cc93xzes.js";
622
645
  import {
623
646
  retryFailedRun2,
624
647
  cancelWorkflowRun2,
625
648
  init_resume
626
- } from "./cli-9a2rtd77.js";
649
+ } from "./cli-7r162fxe.js";
627
650
  import {
628
651
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
629
652
  SUPPORTED_PROTOCOL_VERSIONS,
@@ -644,8 +667,6 @@ import {
644
667
  init_triggers,
645
668
  snapshotAndUpdateWorkflow,
646
669
  init_version,
647
- TaskCreationBlockedError,
648
- init_errors,
649
670
  RawLlmConfigSchema,
650
671
  RawLlmOutputSchema,
651
672
  executeRawLlm,
@@ -709,6 +730,9 @@ import {
709
730
  loadEnabledExtensions,
710
731
  stopExtensionRuntime,
711
732
  init_lifecycle,
733
+ dispatchPre2,
734
+ dispatchPost2,
735
+ init_dispatcher,
712
736
  resolveIdentity,
713
737
  renderIdentity,
714
738
  init_identity,
@@ -723,13 +747,6 @@ import {
723
747
  init_transcription,
724
748
  isAgentOnDemand,
725
749
  init_reachability,
726
- nextFallback2,
727
- createWorkerTaskFollowUp2,
728
- createResumeFollowUp2,
729
- init_worker_follow_up,
730
- isGitHubEnabled,
731
- initGitHub,
732
- verifyWebhookSignature,
733
750
  isAgentMailEnabled,
734
751
  initAgentMail,
735
752
  verifyAgentMailWebhook,
@@ -777,6 +794,9 @@ import {
777
794
  handlePullRequestCommentCreated,
778
795
  handlePullRequestClosed,
779
796
  init_bitbucket,
797
+ isGitHubEnabled,
798
+ initGitHub,
799
+ verifyWebhookSignature,
780
800
  handlePullRequest,
781
801
  handleIssue,
782
802
  handleComment,
@@ -852,12 +872,16 @@ import {
852
872
  init_page_session,
853
873
  resolveHttpRequestAuth,
854
874
  init_auth,
855
- getDeploymentEnvValue,
856
- loadGlobalConfigsIntoEnv,
857
- reloadGlobalConfigsAndIntegrations,
858
- scheduleIntegrationsReload,
859
- handleCore,
875
+ getDeploymentEnvValue2,
876
+ loadGlobalConfigsIntoEnv2,
877
+ reloadGlobalConfigsAndIntegrations2,
878
+ scheduleIntegrationsReload2,
879
+ handleCore2,
860
880
  init_core,
881
+ nextFallback2,
882
+ createWorkerTaskFollowUp2,
883
+ createResumeFollowUp2,
884
+ init_worker_follow_up,
861
885
  MCP_MAX_TOOL_INPUT_ELEMENTS,
862
886
  MCP_MAX_REQUEST_BODY_BYTES,
863
887
  init_mcp_limits,
@@ -954,6 +978,8 @@ import {
954
978
  init_access,
955
979
  getLinksForMemory,
956
980
  init_links_store,
981
+ attachDemotionEvidence,
982
+ init_demotion_evidence,
957
983
  expandCandidatesWithGraph,
958
984
  init_graph_expansion,
959
985
  isApiDraining,
@@ -1036,6 +1062,8 @@ import {
1036
1062
  discardImprovement,
1037
1063
  improvementLeakHints,
1038
1064
  init_improvements,
1065
+ recomputeSessionCost,
1066
+ init_session_cost_recompute,
1039
1067
  canClaim,
1040
1068
  init_budget_admission,
1041
1069
  emitBudgetRefusalSideEffects,
@@ -1055,7 +1083,7 @@ import {
1055
1083
  getEnabledCapabilities,
1056
1084
  createServer,
1057
1085
  init_server
1058
- } from "./cli-5ntc4we6.js";
1086
+ } from "./cli-p0n7b5rz.js";
1059
1087
  import {
1060
1088
  FilesError,
1061
1089
  normalizeFilesError,
@@ -1066,7 +1094,6 @@ import {
1066
1094
  getFileStorageProvider2,
1067
1095
  init_registry2
1068
1096
  } from "./cli-7cp6aa1q.js";
1069
- import"./cli-wr1h0k28.js";
1070
1097
  import {
1071
1098
  RuntimePoolError2,
1072
1099
  mintControllerToken,
@@ -1088,7 +1115,7 @@ import {
1088
1115
  resolvePoolDelivery2,
1089
1116
  createPoolAgent2,
1090
1117
  init_db2
1091
- } from "./cli-h474mvp5.js";
1118
+ } from "./cli-s1zqk1aj.js";
1092
1119
  import {
1093
1120
  duplicateGuardedQueryKey,
1094
1121
  warnIfCorsAllowsAnyOrigin,
@@ -1145,7 +1172,7 @@ import {
1145
1172
  describeRequestRoute,
1146
1173
  route,
1147
1174
  init_route_def
1148
- } from "./cli-fnh4b12r.js";
1175
+ } from "./cli-nstkanmx.js";
1149
1176
  import {
1150
1177
  startPoolRouting,
1151
1178
  stopPoolRouting,
@@ -1158,17 +1185,17 @@ import {
1158
1185
  checkHeartbeatChecklist2,
1159
1186
  runHeartbeatSweep2,
1160
1187
  stopHeartbeat2
1161
- } from "./cli-2kg31ted.js";
1162
- import"./cli-57pvhnyt.js";
1188
+ } from "./cli-9fjr27ez.js";
1189
+ import"./cli-43evxwj4.js";
1163
1190
  import {
1164
1191
  runtimeSupervisorStatus,
1165
1192
  startRuntimeSupervisor,
1166
1193
  stopRuntimeSupervisor
1167
- } from "./cli-vw5x18yj.js";
1194
+ } from "./cli-8st34zhr.js";
1168
1195
  import {
1169
1196
  TASK_TITLE_TIMEOUT_MS,
1170
1197
  generateTaskTitle
1171
- } from "./cli-js8zrfyg.js";
1198
+ } from "./cli-fcfbct2j.js";
1172
1199
  import"./cli-ns59dc6r.js";
1173
1200
  import {
1174
1201
  ACP_TARGET_IDS
@@ -1179,7 +1206,7 @@ import {
1179
1206
  } from "./cli-5gpqgs8b.js";
1180
1207
  import {
1181
1208
  MAX_RATE_LIMIT_RESET_MS
1182
- } from "./cli-dx439zpg.js";
1209
+ } from "./cli-kpgcm7xy.js";
1183
1210
  import {
1184
1211
  isLeadChannelMonitoringEnabled,
1185
1212
  ORG_IDENTITY_KEYS,
@@ -1189,7 +1216,7 @@ import {
1189
1216
  isUnknownModelError,
1190
1217
  checkProviderPoolKey,
1191
1218
  writeSkillsToFilesystem
1192
- } from "./cli-8axx8vnw.js";
1219
+ } from "./cli-sb4426be.js";
1193
1220
  import {
1194
1221
  AgentFsRequestError2,
1195
1222
  resolveAgentFsSharedContext2,
@@ -1199,10 +1226,20 @@ import {
1199
1226
  roleRank2,
1200
1227
  agentFsRequest2,
1201
1228
  resolveApiUrl2
1202
- } from "./cli-vvgaz8t6.js";
1229
+ } from "./cli-vq2eg24x.js";
1203
1230
  import {
1204
1231
  Anthropic
1205
1232
  } from "./cli-t9ga4qmb.js";
1233
+ import"./cli-had1p04a.js";
1234
+ import {
1235
+ createUserMergeJob2,
1236
+ getUserMergeJob2,
1237
+ listUserMergeJobs2,
1238
+ findActiveUserMergeJob2,
1239
+ findFailedUserMergeJob2,
1240
+ requeueUserMergeJob2,
1241
+ runUserMergeJobs2
1242
+ } from "./cli-kbtzfrxj.js";
1206
1243
  import {
1207
1244
  isCodexOAuthConfigKey
1208
1245
  } from "./cli-j4bwnpkm.js";
@@ -1210,6 +1247,10 @@ import {
1210
1247
  resolveClaudeTransport,
1211
1248
  isClaudeBridgeEffective
1212
1249
  } from "./cli-9fzgd3hg.js";
1250
+ import {
1251
+ runTaskUiAction,
1252
+ init_actions
1253
+ } from "./cli-aw83sr40.js";
1213
1254
  import {
1214
1255
  RATING_MODEL_MAX_LENGTH,
1215
1256
  REFERENCES_SOURCE_MAX_LENGTH,
@@ -1304,7 +1345,7 @@ import {
1304
1345
  init_typecheck,
1305
1346
  parseSkillContent,
1306
1347
  init_skill_parser
1307
- } from "./cli-7fx9jyfs.js";
1348
+ } from "./cli-w1q68d8x.js";
1308
1349
  import {
1309
1350
  signalProcessGroup,
1310
1351
  detachedProcessGroup,
@@ -1321,8 +1362,8 @@ import {
1321
1362
  forceRefreshAuthorizationOrThrow,
1322
1363
  forceRefreshTokenOrThrow,
1323
1364
  init_ensure_token
1324
- } from "./cli-1tvdx9t5.js";
1325
- import"./cli-25nstr34.js";
1365
+ } from "./cli-2rnd5j3t.js";
1366
+ import"./cli-jrbq4djp.js";
1326
1367
  import {
1327
1368
  automationIntegrationFixUrl,
1328
1369
  preflightAutomation,
@@ -1341,7 +1382,7 @@ import {
1341
1382
  definitionNodeIds,
1342
1383
  validateDefinition,
1343
1384
  init_definition2
1344
- } from "./cli-svc803vq.js";
1385
+ } from "./cli-q5srsxq2.js";
1345
1386
  import {
1346
1387
  _fetchHolder,
1347
1388
  CLIENT_ID,
@@ -1357,7 +1398,7 @@ import {
1357
1398
  loadAllCodexOAuthSlots,
1358
1399
  getValidCodexOAuth,
1359
1400
  init_storage
1360
- } from "./cli-eg437b5p.js";
1401
+ } from "./cli-7sf9sb0w.js";
1361
1402
  import {
1362
1403
  isMultiRuntimeEnabled,
1363
1404
  init_multi_runtime2
@@ -1369,10 +1410,11 @@ import {
1369
1410
  import {
1370
1411
  createRuntimeProvider,
1371
1412
  init_runtime_providers
1372
- } from "./cli-5kcmxwxv.js";
1413
+ } from "./cli-tvgqesec.js";
1373
1414
  import {
1374
1415
  require_content_type
1375
1416
  } from "./cli-1jx0srjt.js";
1417
+ import"./cli-n3qe7tyr.js";
1376
1418
  import {
1377
1419
  isInvalidClientError,
1378
1420
  publicEndpointSsrfOptions,
@@ -1390,7 +1432,7 @@ import {
1390
1432
  revokeMcpToken,
1391
1433
  computeExpiresAt,
1392
1434
  init_mcp_wrapper
1393
- } from "./cli-dd37e0cm.js";
1435
+ } from "./cli-2v2zdm0a.js";
1394
1436
  import"./cli-v41kn3cd.js";
1395
1437
  import {
1396
1438
  setBedrockProviderModule,
@@ -1415,6 +1457,7 @@ import {
1415
1457
  unlinkIdentity,
1416
1458
  mintToken,
1417
1459
  revokeToken,
1460
+ revokeAllUserCredentials,
1418
1461
  resolveUserByToken,
1419
1462
  InvalidRuntimeTokenError,
1420
1463
  mintSessionToken,
@@ -1427,13 +1470,20 @@ import {
1427
1470
  revokeAgentTokens,
1428
1471
  fingerprintApiKey,
1429
1472
  init_users
1430
- } from "./cli-pwsax0vp.js";
1473
+ } from "./cli-vsw91x06.js";
1474
+ import {
1475
+ resolveGitHubHost,
1476
+ init_github_host
1477
+ } from "./cli-9ttx00s3.js";
1431
1478
  import {
1432
- AMP_ESTIMATE_MODELS,
1433
- ampBillsCacheWrites,
1434
- resolveAmpModel,
1435
- init_amp_models
1436
- } from "./cli-gddgcnav.js";
1479
+ MAX_PROVIDER_QUOTA_ENTRIES,
1480
+ ProviderQuotaCapacityError,
1481
+ windowFieldObservedAtSchema,
1482
+ codexWindowKey,
1483
+ providerAccountTelemetrySchema,
1484
+ rateLimitReplacementSchema,
1485
+ init_provider_account_telemetry
1486
+ } from "./cli-43ms35q9.js";
1437
1487
  import {
1438
1488
  CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1439
1489
  CODEX_AUTH_WATCH_NAMESPACE,
@@ -1474,6 +1524,7 @@ import {
1474
1524
  ModelProfileNameSchema,
1475
1525
  ModelProfileCredentialsSchema,
1476
1526
  ModelProfileSchema,
1527
+ ModelGroupSchema,
1477
1528
  ProviderErrorClassSchema,
1478
1529
  ProfileCheckResultSchema,
1479
1530
  SessionAccessSchema,
@@ -1489,6 +1540,8 @@ import {
1489
1540
  AgentTaskSchema,
1490
1541
  TaskAttachmentSchema,
1491
1542
  UserSchema,
1543
+ UserMergeJobStatusSchema,
1544
+ UserMergeJobSchema,
1492
1545
  RbacRoleSchema,
1493
1546
  UserRbacRolesSchema,
1494
1547
  UserCommsPrefsSchema,
@@ -1606,36 +1659,31 @@ import {
1606
1659
  KvKeySchema,
1607
1660
  KvEntrySchema,
1608
1661
  init_types5
1609
- } from "./cli-me4maa4j.js";
1610
- import {
1611
- resolveGitHubHost,
1612
- init_github_host
1613
- } from "./cli-9ttx00s3.js";
1662
+ } from "./cli-y4ccxtz5.js";
1614
1663
  import {
1615
1664
  IDENTITY_FIELD_BUDGETS,
1616
1665
  IdentityFieldBudgetError,
1617
1666
  init_identity_field_budget
1618
- } from "./cli-aa8s22gn.js";
1619
- import {
1620
- getSlackConfiguration,
1621
- init_config4
1622
- } from "./cli-eetzmsy5.js";
1667
+ } from "./cli-3aaeb78m.js";
1623
1668
  import {
1624
1669
  isSteeringEnabled2,
1625
1670
  init_steering_enabled
1626
1671
  } from "./cli-4sydckyj.js";
1672
+ import {
1673
+ getSlackConfiguration,
1674
+ init_config4
1675
+ } from "./cli-eetzmsy5.js";
1627
1676
  import {
1628
1677
  SUBSCRIPTION_PLANS_CHECKED_AT,
1629
1678
  SUBSCRIPTION_PLANS,
1630
1679
  isSubscriptionPlanId,
1631
1680
  init_subscription_plans
1632
- } from "./cli-7akn6ze9.js";
1633
- import {
1634
- getOpenRouterAttributionHeaders,
1635
- init_openrouter_base_url
1636
- } from "./cli-dfyv0jdy.js";
1681
+ } from "./cli-nh7x3133.js";
1637
1682
  import {
1638
1683
  MODEL_SCOPED_WINDOWS,
1684
+ KEY_WIDE_WINDOWS,
1685
+ modelFamilyOf,
1686
+ isModelScopedWindow,
1639
1687
  activeModelBlocks,
1640
1688
  init_model_rate_limit_windows,
1641
1689
  CREDENTIAL_POOL_VARS,
@@ -1644,7 +1692,11 @@ import {
1644
1692
  splitCredentialPool,
1645
1693
  selectCredential,
1646
1694
  init_credentials2
1647
- } from "./cli-pn1v1pb0.js";
1695
+ } from "./cli-psffsanb.js";
1696
+ import {
1697
+ getOpenRouterAttributionHeaders,
1698
+ init_openrouter_base_url
1699
+ } from "./cli-dfyv0jdy.js";
1648
1700
  import {
1649
1701
  interpolate,
1650
1702
  init_template2,
@@ -1654,7 +1706,7 @@ import {
1654
1706
  resolveTemplate,
1655
1707
  init_resolver,
1656
1708
  init_session_templates
1657
- } from "./cli-812paz57.js";
1709
+ } from "./cli-6ehs4mta.js";
1658
1710
  import {
1659
1711
  init_zod
1660
1712
  } from "./cli-zcfpsfzf.js";
@@ -1707,7 +1759,7 @@ import {
1707
1759
  import {
1708
1760
  init_package,
1709
1761
  package_default
1710
- } from "./cli-kaa4bd7x.js";
1762
+ } from "./cli-3f8zbtqa.js";
1711
1763
  import {
1712
1764
  realtimeBus,
1713
1765
  init_bus
@@ -7944,7 +7996,290 @@ async function handleAgentsRest(req, res, pathSegments, queryParams, myAgentId)
7944
7996
  // src/http/api-keys.ts
7945
7997
  init_zod();
7946
7998
  init_db4();
7999
+
8000
+ // src/be/key-window-usage.ts
8001
+ init_zod();
8002
+ init_types5();
7947
8003
  init_model_rate_limit_windows();
8004
+ init_provider_account_telemetry();
8005
+ init_db4();
8006
+ var MAX_USAGE_WINDOWS = 256;
8007
+ var MAX_USAGE_WINDOWS_PER_CREDENTIAL = 16;
8008
+ var MAX_USAGE_LOOKBACK_MS = 90 * 86400000;
8009
+ var MAX_USAGE_ROWS = 1e5;
8010
+
8011
+ class KeyWindowUsageLimitError extends Error {
8012
+ status;
8013
+ constructor(message, status = 422) {
8014
+ super(message);
8015
+ this.status = status;
8016
+ }
8017
+ }
8018
+ var counterSchema = object2({
8019
+ value: number2().nullable(),
8020
+ measuredSessions: number2().int(),
8021
+ missingSessions: number2().int()
8022
+ });
8023
+ var tokensSchema = object2({
8024
+ uncachedInput: counterSchema,
8025
+ output: counterSchema,
8026
+ cacheRead: counterSchema,
8027
+ cacheWrite: counterSchema,
8028
+ reasoning: counterSchema,
8029
+ thinking: counterSchema
8030
+ });
8031
+ var keyWindowUsageSchema = object2({
8032
+ statusId: string2(),
8033
+ keyType: string2(),
8034
+ keySuffix: string2(),
8035
+ scope: string2(),
8036
+ scopeId: string2().nullable(),
8037
+ windowKey: string2(),
8038
+ durationMins: number2().nullable(),
8039
+ startsAt: string2().nullable(),
8040
+ endsAt: string2().nullable(),
8041
+ dataThrough: string2(),
8042
+ observedAt: string2(),
8043
+ observationAgeMs: number2(),
8044
+ modelScope: object2({
8045
+ kind: _enum2(["account", "family", "unknown"]),
8046
+ model: string2().nullable()
8047
+ }),
8048
+ unavailableReason: _enum2(["missing_reset", "unknown_duration", "unknown_model_scope", "window_not_started"]).nullable(),
8049
+ usage: object2({
8050
+ sessions: number2().int(),
8051
+ errorSessions: number2().int(),
8052
+ completedTasks: number2().int(),
8053
+ tokens: tokensSchema,
8054
+ modelUnattributedSessions: number2().int(),
8055
+ swarmUnattributedSessions: number2().int()
8056
+ }).nullable()
8057
+ });
8058
+ function currentKeyWindows(statuses, nowMs) {
8059
+ const result = [];
8060
+ for (const key of statuses) {
8061
+ for (const [windowKey, window] of Object.entries(key.rateLimitWindows)) {
8062
+ const resetMs = window.resetsAt === undefined ? null : window.resetsAt * 1000;
8063
+ if (resetMs !== null && (!Number.isFinite(resetMs) || resetMs <= nowMs))
8064
+ continue;
8065
+ if (result.length >= MAX_USAGE_WINDOWS) {
8066
+ throw new KeyWindowUsageLimitError("Too many provider windows. Filter by credential or scope.");
8067
+ }
8068
+ const legacyClaude = window.source ? window.source === "claude" : key.provider === "claude";
8069
+ const family = legacyClaude ? MODEL_SCOPED_WINDOWS[windowKey] : undefined;
8070
+ const durationMins = window.durationMins ?? (legacyClaude ? windowKey === "five_hour" ? 300 : windowKey === "seven_day" || family ? 10080 : null : null);
8071
+ const accountWide = legacyClaude ? KEY_WIDE_WINDOWS.some((name) => name === windowKey) : [codexWindowKey("codex", "primary"), codexWindowKey("codex", "secondary")].includes(windowKey);
8072
+ const modelScope = family ? { kind: "family", model: family } : { kind: accountWide ? "account" : "unknown", model: null };
8073
+ const startMs = resetMs !== null && durationMins ? resetMs - durationMins * 60000 : null;
8074
+ const unavailableReason = resetMs === null ? "missing_reset" : startMs === null ? "unknown_duration" : startMs > nowMs ? "window_not_started" : modelScope.kind === "unknown" ? "unknown_model_scope" : null;
8075
+ result.push({
8076
+ statusId: key.id,
8077
+ keyType: key.keyType,
8078
+ keySuffix: key.keySuffix,
8079
+ scope: key.scope,
8080
+ scopeId: key.scopeId,
8081
+ windowKey,
8082
+ durationMins,
8083
+ startsAt: startMs === null ? null : new Date(startMs).toISOString(),
8084
+ endsAt: resetMs === null ? null : new Date(resetMs).toISOString(),
8085
+ dataThrough: new Date(Math.min(nowMs, resetMs ?? nowMs)).toISOString(),
8086
+ observedAt: window.lastSeenAt,
8087
+ observationAgeMs: Math.max(0, nowMs - Date.parse(window.lastSeenAt)),
8088
+ modelScope,
8089
+ unavailableReason,
8090
+ usage: null
8091
+ });
8092
+ }
8093
+ }
8094
+ return result;
8095
+ }
8096
+ var usageColumns = `sc.taskId, sc.credentialKeyType, sc.credentialKeySuffix, sc.harness,
8097
+ sc.inputTokens, sc.outputTokens, sc.cacheReadTokens, sc.cacheWriteTokens,
8098
+ sc.reasoningOutputTokens, sc.thinkingTokens, sc.model, sc.modelBreakdown,
8099
+ sc.isError, sc.createdAt`;
8100
+ var KEY_WINDOW_USAGE_SQL = `
8101
+ WITH requested_keys AS (
8102
+ SELECT json_extract(value, '$.keyType') AS keyType,
8103
+ json_extract(value, '$.keySuffix') AS keySuffix FROM json_each(?)
8104
+ )
8105
+ SELECT ${usageColumns}, CASE WHEN t.status = 'completed' THEN t.finishedAt END AS finishedAt
8106
+ FROM requested_keys k
8107
+ JOIN session_costs sc INDEXED BY idx_session_costs_credential_createdAt
8108
+ ON sc.credentialKeyType = k.keyType AND sc.credentialKeySuffix = k.keySuffix
8109
+ LEFT JOIN agent_tasks t ON t.id = sc.taskId
8110
+ WHERE sc.createdAt >= ? AND sc.createdAt < ?
8111
+ UNION ALL
8112
+ SELECT ${usageColumns}, t.finishedAt
8113
+ FROM agent_tasks t INDEXED BY idx_agent_tasks_status_finishedAt
8114
+ CROSS JOIN session_costs sc INDEXED BY idx_session_costs_taskId ON sc.taskId = t.id
8115
+ JOIN requested_keys k ON sc.credentialKeyType = k.keyType AND sc.credentialKeySuffix = k.keySuffix
8116
+ WHERE t.status = 'completed' AND t.finishedAt >= ? AND t.finishedAt < ? AND sc.createdAt < ?
8117
+ UNION ALL
8118
+ SELECT NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, 0, 0, '', NULL, 0, sc.createdAt, NULL
8119
+ FROM session_costs sc
8120
+ WHERE (sc.credentialKeyType IS NULL OR sc.credentialKeySuffix IS NULL)
8121
+ AND sc.kind = 'harness'
8122
+ AND sc.createdAt >= ? AND sc.createdAt < ?
8123
+ LIMIT ${MAX_USAGE_ROWS + 1}`;
8124
+ var emptyTokens = () => Object.fromEntries(["uncachedInput", "output", "cacheRead", "cacheWrite", "reasoning", "thinking"].map((name) => [
8125
+ name,
8126
+ { value: null, measuredSessions: 0, missingSessions: 0 }
8127
+ ]));
8128
+ function add(tokens, name, value) {
8129
+ const counter = tokens[name];
8130
+ if (value === null)
8131
+ counter.missingSessions++;
8132
+ else {
8133
+ counter.value = (counter.value ?? 0) + value;
8134
+ counter.measuredSessions++;
8135
+ }
8136
+ }
8137
+ async function aggregateKeyWindowUsage(windows, through) {
8138
+ if (windows.length > MAX_USAGE_WINDOWS) {
8139
+ throw new KeyWindowUsageLimitError("Too many provider windows. Filter by credential or scope.");
8140
+ }
8141
+ const eligible = windows.filter((w) => w.unavailableReason === null && w.startsAt !== null && w.endsAt !== null);
8142
+ const first = eligible[0];
8143
+ if (!first)
8144
+ return [];
8145
+ const start = eligible.reduce((earliest, w) => w.startsAt < earliest ? w.startsAt : earliest, first.startsAt);
8146
+ if (Date.parse(start) < Date.parse(through) - MAX_USAGE_LOOKBACK_MS) {
8147
+ throw new KeyWindowUsageLimitError("Observed usage supports a maximum lookback of 90 days.");
8148
+ }
8149
+ const credentialKey = (key) => JSON.stringify([key.keyType, key.keySuffix]);
8150
+ const windowIdentity = (window) => JSON.stringify([window.startsAt, window.endsAt, window.modelScope]);
8151
+ const windowGroups = new Map;
8152
+ for (const window of eligible) {
8153
+ const key = credentialKey(window);
8154
+ const bounds = windowGroups.get(key) ?? new Set;
8155
+ bounds.add(windowIdentity(window));
8156
+ if (bounds.size > MAX_USAGE_WINDOWS_PER_CREDENTIAL) {
8157
+ throw new KeyWindowUsageLimitError("Too many distinct windows for one credential. Filter by scope.");
8158
+ }
8159
+ windowGroups.set(key, bounds);
8160
+ }
8161
+ const credentials = [
8162
+ ...new Map(eligible.map((w) => [
8163
+ JSON.stringify([w.keyType, w.keySuffix]),
8164
+ { keyType: w.keyType, keySuffix: w.keySuffix }
8165
+ ])).values()
8166
+ ];
8167
+ const rows = await getDbClient2().query(KEY_WINDOW_USAGE_SQL, [
8168
+ JSON.stringify(credentials),
8169
+ start,
8170
+ through,
8171
+ start,
8172
+ through,
8173
+ start,
8174
+ start,
8175
+ through
8176
+ ]);
8177
+ if (rows.length > MAX_USAGE_ROWS) {
8178
+ throw new KeyWindowUsageLimitError("Too many sessions for window usage. Filter by credential or scope.");
8179
+ }
8180
+ const rowsByCredential = new Map;
8181
+ const unattributedTimes = [];
8182
+ for (const row of rows) {
8183
+ if (row.credentialKeyType === null || row.credentialKeySuffix === null) {
8184
+ unattributedTimes.push(row.createdAt);
8185
+ continue;
8186
+ }
8187
+ const key = credentialKey({
8188
+ keyType: row.credentialKeyType,
8189
+ keySuffix: row.credentialKeySuffix
8190
+ });
8191
+ const group = rowsByCredential.get(key) ?? [];
8192
+ group.push(row);
8193
+ rowsByCredential.set(key, group);
8194
+ }
8195
+ unattributedTimes.sort();
8196
+ const unattributedSince = (start) => {
8197
+ let lower = 0;
8198
+ let upper = unattributedTimes.length;
8199
+ while (lower < upper) {
8200
+ const middle = Math.floor((lower + upper) / 2);
8201
+ if (unattributedTimes[middle] < start)
8202
+ lower = middle + 1;
8203
+ else
8204
+ upper = middle;
8205
+ }
8206
+ return unattributedTimes.length - lower;
8207
+ };
8208
+ const computed = new Map;
8209
+ return eligible.map((window) => {
8210
+ const identity = JSON.stringify([credentialKey(window), windowIdentity(window)]);
8211
+ const prior = computed.get(identity);
8212
+ if (prior)
8213
+ return {
8214
+ statusId: window.statusId,
8215
+ windowKey: window.windowKey,
8216
+ dataThrough: through,
8217
+ usage: prior
8218
+ };
8219
+ const usage = {
8220
+ sessions: 0,
8221
+ errorSessions: 0,
8222
+ completedTasks: 0,
8223
+ tokens: emptyTokens(),
8224
+ modelUnattributedSessions: 0,
8225
+ swarmUnattributedSessions: unattributedSince(window.startsAt)
8226
+ };
8227
+ const completed = new Set;
8228
+ for (const row of rowsByCredential.get(credentialKey(window)) ?? []) {
8229
+ const inReceiptWindow = row.createdAt >= window.startsAt && row.createdAt < through;
8230
+ let parts = [
8231
+ {
8232
+ model: row.model,
8233
+ inputTokens: row.inputTokens,
8234
+ outputTokens: row.outputTokens,
8235
+ cacheReadTokens: row.cacheReadTokens,
8236
+ cacheWriteTokens: row.cacheWriteTokens
8237
+ }
8238
+ ];
8239
+ const scoped = window.modelScope.kind !== "account";
8240
+ if (scoped) {
8241
+ parts = [];
8242
+ try {
8243
+ const parsed = SessionCostModelBreakdownSchema.array().safeParse(row.modelBreakdown ? JSON.parse(row.modelBreakdown) : null);
8244
+ parts = parsed.success ? parsed.data : [];
8245
+ } catch {
8246
+ parts = [];
8247
+ }
8248
+ }
8249
+ if (scoped) {
8250
+ const known = parts.length > 0 && parts.every((part) => part.model.length > 0);
8251
+ if (!known && inReceiptWindow)
8252
+ usage.modelUnattributedSessions++;
8253
+ parts = parts.filter((part) => modelFamilyOf(part.model) === window.modelScope.model);
8254
+ if (!parts.length)
8255
+ continue;
8256
+ }
8257
+ if (row.taskId && row.finishedAt && row.finishedAt >= window.startsAt && row.finishedAt < through)
8258
+ completed.add(row.taskId);
8259
+ if (!inReceiptWindow)
8260
+ continue;
8261
+ usage.sessions++;
8262
+ usage.errorSessions += row.isError ? 1 : 0;
8263
+ const sum = (field) => parts.some((part) => part[field] === null) ? null : parts.reduce((total, part) => total + (part[field] ?? 0), 0);
8264
+ const input = sum("inputTokens");
8265
+ const read = sum("cacheReadTokens");
8266
+ const knownInput = ["claude", "claude-managed", "pi", "opencode"].includes(row.harness ?? "");
8267
+ add(usage.tokens, "uncachedInput", row.harness === "codex" ? input !== null && read !== null ? Math.max(0, input - read) : null : knownInput ? input : null);
8268
+ add(usage.tokens, "output", sum("outputTokens"));
8269
+ add(usage.tokens, "cacheRead", read);
8270
+ add(usage.tokens, "cacheWrite", sum("cacheWriteTokens"));
8271
+ add(usage.tokens, "reasoning", !scoped && row.reasoningOutputTokens > 0 ? row.reasoningOutputTokens : null);
8272
+ add(usage.tokens, "thinking", !scoped && row.thinkingTokens > 0 ? row.thinkingTokens : null);
8273
+ }
8274
+ usage.completedTasks = completed.size;
8275
+ computed.set(identity, usage);
8276
+ return { statusId: window.statusId, windowKey: window.windowKey, dataThrough: through, usage };
8277
+ });
8278
+ }
8279
+
8280
+ // src/http/api-keys.ts
8281
+ init_model_rate_limit_windows();
8282
+ init_provider_account_telemetry();
7948
8283
  init_subscription_plans();
7949
8284
  init_route_def();
7950
8285
 
@@ -7998,6 +8333,7 @@ function clearUsageCache() {
7998
8333
 
7999
8334
  // src/http/api-keys.ts
8000
8335
  init_utils2();
8336
+ var windowUsageQueryRateLimit = createIpRateLimiter({ capacity: 8, refillPerMs: 1 / 1000 });
8001
8337
  var successMessageSchema = object2({
8002
8338
  success: literal2(true),
8003
8339
  message: string2()
@@ -8016,7 +8352,8 @@ var reportUsage = route({
8016
8352
  taskId: string2().uuid().optional(),
8017
8353
  scope: string2().optional(),
8018
8354
  scopeId: string2().optional(),
8019
- plan: string2().max(40).optional()
8355
+ plan: string2().max(40).optional(),
8356
+ planRaw: string2().min(1).max(80).optional()
8020
8357
  }),
8021
8358
  responses: {
8022
8359
  200: { description: "Usage recorded", schema: successMessageSchema },
@@ -8107,45 +8444,102 @@ var reportAuthFailure = route({
8107
8444
  }
8108
8445
  });
8109
8446
  var rateLimitWindowSchema = object2({
8110
- status: string2(),
8447
+ status: string2().max(256),
8111
8448
  utilization: number2().optional(),
8112
8449
  resetsAt: number2().finite().optional(),
8450
+ fieldObservedAt: windowFieldObservedAtSchema.optional(),
8451
+ durationMins: number2().int().positive().max(576000).optional(),
8452
+ source: _enum2(["claude", "codex"]).optional(),
8453
+ limitId: string2().min(1).max(128).optional(),
8454
+ label: string2().max(256).optional(),
8455
+ normalModelSlug: string2().max(256).optional(),
8456
+ overageStatus: string2().max(256).optional(),
8457
+ overageDisabledReason: string2().max(256).optional(),
8113
8458
  isUsingOverage: boolean().optional(),
8114
8459
  surpassedThreshold: number2().optional(),
8115
8460
  lastSeenAt: string2().datetime()
8116
8461
  });
8462
+ var MAX_DISPLAY_RESET_MS = 400 * 86400000;
8117
8463
  function sanitizeReportedWindowResets(windows) {
8118
- const nowSec = Math.floor(Date.now() / 1000);
8119
- const maxResetsAtSec = Math.floor((Date.now() + MAX_RATE_LIMIT_RESET_MS) / 1000);
8464
+ const nowMs = Date.now();
8465
+ const nowSec = Math.floor(nowMs / 1000);
8120
8466
  const sanitized = {};
8121
8467
  for (const [key, window] of Object.entries(windows)) {
8122
- sanitized[key] = window.resetsAt === undefined ? window : { ...window, resetsAt: Math.min(Math.max(window.resetsAt, nowSec), maxResetsAtSec) };
8468
+ const duration = window.durationMins ?? (key === "five_hour" ? 300 : key.startsWith("seven_day") ? 10080 : undefined);
8469
+ 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));
8470
+ const maxResetsAtSec = Math.floor((nowMs + horizonMs) / 1000);
8471
+ sanitized[key] = window.resetsAt === undefined ? window : {
8472
+ ...window,
8473
+ resetsAt: Math.min(window.resetsAt < nowSec - MAX_DISPLAY_RESET_MS / 1000 ? nowSec : window.resetsAt, maxResetsAtSec)
8474
+ };
8123
8475
  }
8124
8476
  return sanitized;
8125
8477
  }
8478
+ function sanitizeReportedQuotaObservations(report, nowMs = Date.now()) {
8479
+ const bound = (at) => Date.parse(at) > nowMs + 60000 ? new Date(nowMs).toISOString() : at;
8480
+ const times = (values) => values && Object.fromEntries(Object.entries(values).map(([key, at]) => [key, bound(at)]));
8481
+ return {
8482
+ windows: Object.fromEntries(Object.entries(report.windows).map(([key, window]) => [
8483
+ key,
8484
+ {
8485
+ ...window,
8486
+ lastSeenAt: bound(window.lastSeenAt),
8487
+ ...window.fieldObservedAt ? { fieldObservedAt: times(window.fieldObservedAt) } : {}
8488
+ }
8489
+ ])),
8490
+ account: report.account && {
8491
+ ...report.account,
8492
+ observedAt: bound(report.account.observedAt),
8493
+ ...report.account.fieldObservedAt ? { fieldObservedAt: times(report.account.fieldObservedAt) } : {},
8494
+ ...report.account.limits ? {
8495
+ limits: Object.fromEntries(Object.entries(report.account.limits).map(([id, limit]) => [
8496
+ id,
8497
+ {
8498
+ ...limit,
8499
+ observedAt: bound(limit.observedAt),
8500
+ ...limit.fieldObservedAt ? { fieldObservedAt: times(limit.fieldObservedAt) } : {},
8501
+ ...limit.windowRemovedAt ? { windowRemovedAt: times(limit.windowRemovedAt) } : {}
8502
+ }
8503
+ ]))
8504
+ } : {}
8505
+ },
8506
+ replace: report.replace?.map((replacement) => ({
8507
+ ...replacement,
8508
+ observedAt: bound(replacement.observedAt)
8509
+ }))
8510
+ };
8511
+ }
8126
8512
  var reportRateLimitWindows = route({
8127
8513
  method: "post",
8128
8514
  path: "/api/keys/report-rate-limit-windows",
8129
8515
  pattern: ["api", "keys", "report-rate-limit-windows"],
8130
8516
  summary: "Record provider-emitted rate-limit window telemetry for an API key",
8517
+ description: "Reports accept up to 64 windows and 64 account limits within 256 KiB. Stored records have the same count limits.",
8131
8518
  tags: ["API Keys"],
8519
+ maxBodyBytes: 256 * 1024,
8132
8520
  body: object2({
8133
8521
  keyType: string2(),
8134
8522
  keySuffix: string2().min(1).max(10),
8135
8523
  keyIndex: number2().int().min(0),
8136
- windows: record2(string2(), rateLimitWindowSchema),
8524
+ windows: record2(string2().max(256), rateLimitWindowSchema),
8525
+ account: providerAccountTelemetrySchema.optional(),
8526
+ replace: array2(rateLimitReplacementSchema).max(128).optional(),
8137
8527
  scope: string2().optional(),
8138
8528
  scopeId: string2().optional()
8139
- }),
8529
+ }).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."),
8140
8530
  responses: {
8141
8531
  200: {
8142
8532
  description: "Rate-limit window telemetry recorded",
8143
8533
  schema: successMessageSchema
8144
8534
  },
8145
8535
  400: { description: "Validation error" },
8146
- 401: { description: "Unauthorized" }
8536
+ 401: { description: "Unauthorized" },
8537
+ 413: { description: "Telemetry report exceeds 256 KiB" }
8147
8538
  },
8148
- auth: { apiKey: true }
8539
+ auth: { apiKey: true },
8540
+ rbac: {
8541
+ ungated: "worker credential telemetry, same posture as POST /api/keys/report-rate-limit"
8542
+ }
8149
8543
  });
8150
8544
  var reportSeatMismatch = route({
8151
8545
  method: "post",
@@ -8223,8 +8617,10 @@ var ApiKeyStatusSchema = object2({
8223
8617
  name: string2().nullable(),
8224
8618
  provider: string2(),
8225
8619
  rateLimitWindows: record2(string2(), rateLimitWindowSchema),
8620
+ providerAccount: providerAccountTelemetrySchema.nullable(),
8226
8621
  plan: string2().nullable(),
8227
8622
  planSource: _enum2(["manual", "detected", "estimated"]).nullable(),
8623
+ detectedPlanRaw: string2().nullable(),
8228
8624
  lastSeatMismatchAt: string2().nullable(),
8229
8625
  lastSeatMismatchModel: string2().nullable(),
8230
8626
  consecutiveAuthFailures: number2().int(),
@@ -8287,6 +8683,36 @@ var listStatuses = route({
8287
8683
  },
8288
8684
  auth: { apiKey: true }
8289
8685
  });
8686
+ var getWindowUsage = route({
8687
+ method: "get",
8688
+ path: "/api/keys/window-usage",
8689
+ pattern: ["api", "keys", "window-usage"],
8690
+ summary: "Get Swarm-observed usage within current provider windows",
8691
+ description: "Usage calculations support 256 windows, 16 distinct windows per credential, 90 days, and 100,000 session rows. Oversized requests fail without partial totals.",
8692
+ tags: ["API Keys"],
8693
+ query: object2({
8694
+ keyType: string2().max(128).optional(),
8695
+ keySuffix: string2().min(1).max(10).optional(),
8696
+ scope: string2().max(64).optional(),
8697
+ scopeId: string2().max(128).optional()
8698
+ }),
8699
+ responses: {
8700
+ 200: {
8701
+ description: "Independent windows with receipt-time tokens and explicit measurement coverage",
8702
+ schema: object2({
8703
+ success: literal2(true),
8704
+ asOf: string2(),
8705
+ accounting: literal2("session_cost_receipt_time"),
8706
+ windows: array2(keyWindowUsageSchema)
8707
+ })
8708
+ },
8709
+ 400: { description: "Invalid filters" },
8710
+ 401: { description: "Unauthorized" },
8711
+ 422: { description: "Requested usage exceeds the aggregation bounds" },
8712
+ 429: { description: "Usage query budget exhausted. Retry after one second" }
8713
+ },
8714
+ auth: { apiKey: true }
8715
+ });
8290
8716
  var KeyCostSummarySchema = object2({
8291
8717
  keyType: string2(),
8292
8718
  keySuffix: string2(),
@@ -8426,9 +8852,9 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8426
8852
  const parsed = await reportUsage.parse(req, res, pathSegments, queryParams);
8427
8853
  if (!parsed)
8428
8854
  return true;
8429
- const { keyType, keySuffix, keyIndex, taskId, scope, scopeId, plan } = parsed.body;
8855
+ const { keyType, keySuffix, keyIndex, taskId, scope, scopeId, plan, planRaw } = parsed.body;
8430
8856
  try {
8431
- const { planChanged } = await recordKeyUsage2(keyType, keySuffix, keyIndex, taskId ?? null, scope, scopeId ?? null, plan && isSubscriptionPlanId(plan) ? plan : null);
8857
+ const { planChanged } = await recordKeyUsage2(keyType, keySuffix, keyIndex, taskId ?? null, scope, scopeId ?? null, plan && isSubscriptionPlanId(plan) ? plan : null, planRaw);
8432
8858
  if (planChanged)
8433
8859
  clearUsageCache();
8434
8860
  reportUsage.respond(res, 200, { success: true, message: "Key usage recorded" });
@@ -8485,17 +8911,20 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8485
8911
  const parsed = await reportRateLimitWindows.parse(req, res, pathSegments, queryParams);
8486
8912
  if (!parsed)
8487
8913
  return true;
8488
- const { keyType, keySuffix, keyIndex, windows, scope, scopeId } = parsed.body;
8914
+ const { keyType, keySuffix, keyIndex, scope, scopeId } = parsed.body;
8915
+ const { windows, account, replace } = sanitizeReportedQuotaObservations(parsed.body);
8489
8916
  try {
8490
- const { planChanged } = await recordKeyRateLimitWindows2(keyType, keySuffix, keyIndex, sanitizeReportedWindowResets(windows), scope, scopeId ?? null);
8491
- if (planChanged)
8492
- clearUsageCache();
8917
+ for (const limit of Object.values(account?.limits ?? {})) {
8918
+ if (limit.spend)
8919
+ limit.spend.resetsAt = Math.min(limit.spend.resetsAt, Math.floor(Date.now() / 1000) + 400 * 86400);
8920
+ }
8921
+ await recordKeyRateLimitWindows2(keyType, keySuffix, keyIndex, sanitizeReportedWindowResets(windows), scope, scopeId ?? null, account ?? undefined, replace);
8493
8922
  reportRateLimitWindows.respond(res, 200, {
8494
8923
  success: true,
8495
8924
  message: `Rate-limit windows recorded for ...${keySuffix}`
8496
8925
  });
8497
8926
  } catch (err) {
8498
- jsonError(res, err instanceof Error ? err.message : "Failed to record rate-limit windows", 500);
8927
+ jsonError(res, err instanceof Error ? err.message : "Failed to record rate-limit windows", err instanceof ProviderQuotaCapacityError ? 400 : 500);
8499
8928
  }
8500
8929
  return true;
8501
8930
  }
@@ -8541,6 +8970,52 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8541
8970
  }
8542
8971
  return true;
8543
8972
  }
8973
+ if (getWindowUsage.match(req.method, pathSegments)) {
8974
+ const parsed = await getWindowUsage.parse(req, res, pathSegments, queryParams);
8975
+ if (!parsed)
8976
+ return true;
8977
+ const { keyType, keySuffix, scope, scopeId } = parsed.query;
8978
+ try {
8979
+ const statuses = await getKeyStatuses2(keyType, scope, scope ? scopeId ?? null : undefined);
8980
+ const sampledAt = Date.now();
8981
+ const windows = currentKeyWindows(statuses.filter((key) => keySuffix === undefined || key.keySuffix === keySuffix), sampledAt);
8982
+ const bounds = windows.map((w) => [
8983
+ w.statusId,
8984
+ w.windowKey,
8985
+ w.startsAt,
8986
+ w.endsAt,
8987
+ w.modelScope,
8988
+ w.unavailableReason
8989
+ ]);
8990
+ const cached = await cachedUsageReport(`key-windows:${JSON.stringify([parsed.query, bounds])}`, () => {
8991
+ if (!windowUsageQueryRateLimit.take("window-usage")) {
8992
+ throw new KeyWindowUsageLimitError("Window usage is busy. Retry after one second.", 429);
8993
+ }
8994
+ return aggregateKeyWindowUsage(windows, new Date(sampledAt).toISOString());
8995
+ });
8996
+ const nowMs = Date.now();
8997
+ const byWindow = new Map(cached.map((item) => [JSON.stringify([item.statusId, item.windowKey]), item]));
8998
+ getWindowUsage.respond(res, 200, {
8999
+ success: true,
9000
+ asOf: new Date(nowMs).toISOString(),
9001
+ accounting: "session_cost_receipt_time",
9002
+ windows: windows.filter((w) => w.endsAt === null || Date.parse(w.endsAt) > nowMs).map((window) => {
9003
+ const aggregate = byWindow.get(JSON.stringify([window.statusId, window.windowKey]));
9004
+ return {
9005
+ ...window,
9006
+ observationAgeMs: Math.max(0, nowMs - Date.parse(window.observedAt)),
9007
+ ...aggregate ? { dataThrough: aggregate.dataThrough, usage: aggregate.usage } : {}
9008
+ };
9009
+ })
9010
+ });
9011
+ } catch (err) {
9012
+ const status = err instanceof KeyWindowUsageLimitError ? err.status : 500;
9013
+ if (status === 429)
9014
+ res.setHeader("Retry-After", "1");
9015
+ jsonError(res, err instanceof Error ? err.message : "Failed to get window usage", status);
9016
+ }
9017
+ return true;
9018
+ }
8544
9019
  if (getCosts.match(req.method, pathSegments)) {
8545
9020
  const parsed = await getCosts.parse(req, res, pathSegments, queryParams);
8546
9021
  if (!parsed)
@@ -8852,7 +9327,7 @@ async function handleUsedBy(req, res, pathSegments, queryParams, myAgentId) {
8852
9327
  });
8853
9328
  }
8854
9329
  });
8855
- scheduleIntegrationsReload();
9330
+ scheduleIntegrationsReload2();
8856
9331
  const owner = await resolveHttpFavoriteOwner(req, myAgentId);
8857
9332
  trackRelayed("used_by.consent_changed", {
8858
9333
  granted,
@@ -9099,7 +9574,7 @@ async function handleRanking(req, res, pathSegments, queryParams) {
9099
9574
  return true;
9100
9575
  }
9101
9576
  const { listing } = built;
9102
- scheduleIntegrationsReload();
9577
+ scheduleIntegrationsReload2();
9103
9578
  optIn.respond(res, 200, {
9104
9579
  domain: listing.domain,
9105
9580
  listing,
@@ -9117,7 +9592,7 @@ async function handleRanking(req, res, pathSegments, queryParams) {
9117
9592
  await setEnabled(false);
9118
9593
  if (listing)
9119
9594
  emitOptedOut(listing.domain);
9120
- scheduleIntegrationsReload();
9595
+ scheduleIntegrationsReload2();
9121
9596
  optOut.respond(res, 200, { enabled: false });
9122
9597
  return true;
9123
9598
  }
@@ -9200,13 +9675,27 @@ async function maskConfigRead(req, configs, includeSecrets) {
9200
9675
  async function ensureConfigAdmin(req, res, verb) {
9201
9676
  return ensureHttpPermission(req, res, verb, verb === "config.write.any" ? "Writing swarm config requires the lead agent" : "Deleting swarm config requires the lead agent");
9202
9677
  }
9678
+ async function ensureHumanOnlyConfigWrite(req, res, key) {
9679
+ if (!isHumanOnlyConfigKey(key))
9680
+ return true;
9681
+ const auth = getRequestAuth(req);
9682
+ if (auth?.page) {
9683
+ jsonError(res, humanOnlyConfigKeyPageError(key), 403);
9684
+ return false;
9685
+ }
9686
+ const userId = authUserId(auth);
9687
+ if (userId && (!isRbacEnabled() || (await getUserGrant2(userId)).grantsAll))
9688
+ return true;
9689
+ jsonError(res, humanOnlyConfigKeyError(key), 403);
9690
+ return false;
9691
+ }
9203
9692
  async function runConfigWriteSideEffects(scope, key, value) {
9204
9693
  if (scope !== "global")
9205
9694
  return;
9206
9695
  if (key === "SWARM_ORG_WEBSITE")
9207
9696
  await fillOrgLogoFromWebsite(value);
9208
9697
  await syncRankingAfterConfigChange(key, value);
9209
- scheduleIntegrationsReload();
9698
+ scheduleIntegrationsReload2();
9210
9699
  }
9211
9700
  async function ensureHttpPermission(req, res, verb, forbiddenMessage, callerAgentId) {
9212
9701
  const principal = await requestPrincipal(req, callerAgentId ?? singleHeader(req, "x-agent-id"), {
@@ -9421,7 +9910,7 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9421
9910
  }
9422
9911
  if (reloadConfigRoute.match(req.method, pathSegments)) {
9423
9912
  try {
9424
- const result = await reloadGlobalConfigsAndIntegrations();
9913
+ const result = await reloadGlobalConfigsAndIntegrations2();
9425
9914
  console.log(`[reload-config] Loaded ${result.configsLoaded} config(s), re-initialized: ${result.integrationsReinitialized.join(", ") || "none"}`);
9426
9915
  reloadConfigRoute.respond(res, 200, { success: true, ...result });
9427
9916
  } catch (e) {
@@ -9472,6 +9961,8 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9472
9961
  if (!await ensureConfigAdmin(req, res, "config.write.any"))
9473
9962
  return true;
9474
9963
  const { scope, scopeId, key, value, isSecret, envPath, description, exportToEnv } = parsed.body;
9964
+ if (!await ensureHumanOnlyConfigWrite(req, res, key))
9965
+ return true;
9475
9966
  const validationError = validateConfigEntry({ scope, scopeId, key, value, exportToEnv });
9476
9967
  if (validationError) {
9477
9968
  jsonError(res, validationError, 400);
@@ -9516,6 +10007,8 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9516
10007
  jsonError(res, internalConfigKeyError(existing.key).message, 400);
9517
10008
  return true;
9518
10009
  }
10010
+ if (!await ensureHumanOnlyConfigWrite(req, res, existing.key))
10011
+ return true;
9519
10012
  const deleted = await deleteSwarmConfig2(parsed.params.id);
9520
10013
  if (!deleted) {
9521
10014
  jsonError(res, "Config not found", 404);
@@ -9523,7 +10016,7 @@ async function handleConfig(req, res, pathSegments, queryParams) {
9523
10016
  }
9524
10017
  if (existing.scope === "global") {
9525
10018
  await syncRankingAfterConfigChange(existing.key, null);
9526
- scheduleIntegrationsReload();
10019
+ scheduleIntegrationsReload2();
9527
10020
  }
9528
10021
  if (existing.scope === "agent" && existing.scopeId && existing.key === AGENT_MAX_TASKS_CONFIG_KEY) {
9529
10022
  await resetAgentMaxTasksMirror(existing.scopeId);
@@ -9961,6 +10454,12 @@ async function handleApprovalRequests(req, res, pathSegments, queryParams) {
9961
10454
  if ([...configAnswers.values()].some(({ answer }) => answer.action === "set")) {
9962
10455
  if (!await ensureConfigAdmin(req, res, "config.write.any"))
9963
10456
  return true;
10457
+ for (const { question, answer } of configAnswers.values()) {
10458
+ if (answer.action !== "set")
10459
+ continue;
10460
+ if (!await ensureHumanOnlyConfigWrite(req, res, question.config.key))
10461
+ return true;
10462
+ }
9964
10463
  const userId = authUserId(getRequestAuth(req));
9965
10464
  if (userId && isRbacEnabled()) {
9966
10465
  const grant = await getUserGrant2(userId);
@@ -13037,7 +13536,7 @@ function errorMessage2(error) {
13037
13536
 
13038
13537
  // src/http/comb.ts
13039
13538
  init_rbac();
13040
- init_errors();
13539
+ init_errors2();
13041
13540
  init_secret_scrubber();
13042
13541
  init_request_principal();
13043
13542
  init_route_def();
@@ -13473,16 +13972,16 @@ declare module "swarm-extension" {
13473
13972
  | "schedule"
13474
13973
  | "slack"
13475
13974
  | "agentmail"
13975
+ | "mcp"
13976
+ | "api"
13977
+ | "ui"
13476
13978
  | "github"
13477
13979
  | "gitlab"
13478
13980
  | "azure-devops"
13479
13981
  | "bitbucket"
13982
+ | "system"
13480
13983
  | "linear"
13481
13984
  | "jira"
13482
- | "mcp"
13483
- | "api"
13484
- | "ui"
13485
- | "system"
13486
13985
  | "comb"
13487
13986
  | undefined;
13488
13987
  routingReason?:
@@ -13624,16 +14123,16 @@ declare module "swarm-extension" {
13624
14123
  | "schedule"
13625
14124
  | "slack"
13626
14125
  | "agentmail"
14126
+ | "mcp"
14127
+ | "api"
14128
+ | "ui"
13627
14129
  | "github"
13628
14130
  | "gitlab"
13629
14131
  | "azure-devops"
13630
14132
  | "bitbucket"
14133
+ | "system"
13631
14134
  | "linear"
13632
14135
  | "jira"
13633
- | "mcp"
13634
- | "api"
13635
- | "ui"
13636
- | "system"
13637
14136
  | "comb";
13638
14137
  tags: string[];
13639
14138
  priority: number;
@@ -13815,7 +14314,8 @@ declare module "swarm-extension" {
13815
14314
  runtimeInstanceId: string | undefined;
13816
14315
  sourceTaskId: string | undefined;
13817
14316
  contextKey: string | undefined;
13818
- callOrigin: "mcp" | "extension" | "script-sdk";
14317
+ callOrigin: "mcp" | "native" | "extension" | "script-sdk";
14318
+ harness?: string | undefined;
13819
14319
  };
13820
14320
 
13821
14321
  import type { SwarmSdk } from "swarm-sdk";
@@ -13857,7 +14357,11 @@ declare module "swarm-extension" {
13857
14357
  };
13858
14358
  homepage?: string;
13859
14359
  author?: string;
14360
+ /** Tool-call sources this extension's tool handlers receive. Default \`["mcp"]\`. */
14361
+ toolSources?: readonly ToolSource[];
13860
14362
  }
14363
+ /** \`mcp\`: swarm MCP tools. \`native\`: harness built-ins reported by a worker shim. */
14364
+ export type ToolSource = "mcp" | "native";
13861
14365
  export interface HooksModule {
13862
14366
  default: SwarmExtension;
13863
14367
  config?: z.ZodTypeAny;
@@ -14129,8 +14633,16 @@ declare module "swarm-extension" {
14129
14633
  }
14130
14634
  export interface ToolCallEvent {
14131
14635
  tool: string;
14636
+ /** Secret-scrubbed on native calls: a secret reads as \`[REDACTED:<name>]\`. */
14132
14637
  args: unknown;
14133
14638
  requestInfo: RequestInfo;
14639
+ /** Native calls only: the harness's own tool name, such as \`Bash\`. */
14640
+ nativeTool?: string;
14641
+ /** Native calls only: the harness's own argument shape, secret-scrubbed. */
14642
+ rawArgs?: unknown;
14643
+ /** Native calls only: the harness's call id, and its parent for a nested call. */
14644
+ toolCallId?: string;
14645
+ parentToolCallId?: string;
14134
14646
  }
14135
14647
  export interface ToolCallModify {
14136
14648
  args: unknown;
@@ -14260,6 +14772,8 @@ declare module "swarm-extension" {
14260
14772
  export interface ToolCallCompletedEvent extends ToolCallEvent {
14261
14773
  result: unknown;
14262
14774
  durationMs: number;
14775
+ /** Native calls only: the harness reported the call as failed. */
14776
+ isError?: boolean;
14263
14777
  }
14264
14778
  export interface SwarmEventMap {
14265
14779
  "pre.task.create": {
@@ -16372,7 +16886,7 @@ export default extension;
16372
16886
  $schema: "../manifest.schema.json",
16373
16887
  name: "sql-admin-only",
16374
16888
  description: "Blocks db-query tool calls on tasks created by a non-admin user",
16375
- version: "1.0.0",
16889
+ version: "1.1.0",
16376
16890
  runtime: "api",
16377
16891
  assets: {
16378
16892
  hooks: "hooks.ts"
@@ -16390,7 +16904,7 @@ const SQL_TOOLS = new Set(["db-query"]);
16390
16904
  const manifest = {
16391
16905
  name: "sql-admin-only",
16392
16906
  description: "Blocks db-query tool calls on tasks created by a non-admin user",
16393
- version: "1.0.0",
16907
+ version: "1.1.0",
16394
16908
  runtime: "api",
16395
16909
  assets: { hooks: "hooks.ts" },
16396
16910
  config,
@@ -16445,7 +16959,7 @@ const extension: SwarmExtension<typeof manifest> = (api) => {
16445
16959
  const taskId = event.requestInfo?.sourceTaskId;
16446
16960
  if (!taskId) return;
16447
16961
 
16448
- // Creator lookup. Any failure blocks this SQL call only (fail closed).
16962
+ // Creator lookup. A failed lookup blocks this SQL call only (fail closed).
16449
16963
  let creator: string;
16450
16964
  let role: string;
16451
16965
  try {
@@ -16455,7 +16969,11 @@ const extension: SwarmExtension<typeof manifest> = (api) => {
16455
16969
  )) as Envelope;
16456
16970
  if (q?.success === false) throw new Error("db-query lookup returned success=false");
16457
16971
  const row = (q?.data?.rows ?? q?.rows ?? [])[0];
16458
- if (!row) throw new Error(\`task \${taskId} not found\`);
16972
+ // A successful lookup with no row: the id is not a task. The runner sends a
16973
+ // random correlation id for sessions with no task (pool or channel-message
16974
+ // triggers, src/commands/runner.ts effectiveTaskId). No task means no creator:
16975
+ // allow, the same as a missing header. Errors and timeouts above still block.
16976
+ if (!row) return;
16459
16977
  creator = String(cell(row, 0, "requestedByUserId") ?? "");
16460
16978
  role = String(cell(row, 1, "role") ?? "");
16461
16979
  } catch (err) {
@@ -16477,7 +16995,7 @@ const extension: SwarmExtension<typeof manifest> = (api) => {
16477
16995
  export default extension;
16478
16996
  `
16479
16997
  },
16480
- readme: "# sql-admin-only\n\nBlocks `db-query` tool calls made on a task whose creator (`requestedByUserId`) is not an admin. Every other tool call passes untouched.\n\n| Task creator | `db-query` |\n|---|---|\n| Not set, or the call has no task | Allowed |\n| Set, holds an admin role | Allowed |\n| Set, no admin role | Blocked |\n| Set, but the lookup fails, times out, or the task row is missing | Blocked |\n\nNo config. \"Admin\" means the creator's `users.role` is `admin` (case-insensitive), the role the swarm shows next to a requester's name. Only Lead (`manage-user`) and REST callers with `user.role.manage` can set it. RBAC roles are not used, because every user is created with the RBAC `admin` role. A creator whose user row is gone counts as non-admin.\n\nThe task comes from the call's `X-Source-Task-Id` header. The lookup gets 60% of `EXTENSION_HANDLER_TIMEOUT_MS` (default 5s), because the dispatcher lets a call through when a hook times out.\n\nCoverage limits:\n\n- Only agent MCP tool calls run `pre.tool.call`. Scripts calling `ctx.swarm.db_query`, extensions, and direct `POST /api/db-query` requests skip the hook.\n- A call without an `X-Source-Task-Id` header has no task, so it is allowed.\n"
16998
+ 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"
16481
16999
  },
16482
17000
  "task-digest": {
16483
17001
  manifestFile: "manifest.yaml",
@@ -23197,6 +23715,7 @@ init_event_loop_lag();
23197
23715
  init_memory();
23198
23716
  init_access();
23199
23717
  init_constants2();
23718
+ init_demotion_evidence();
23200
23719
 
23201
23720
  // src/be/memory/edges-store.ts
23202
23721
  init_db4();
@@ -23287,6 +23806,7 @@ async function hasRetrievalForTask(taskId, memoryId) {
23287
23806
  }
23288
23807
 
23289
23808
  // src/http/memory.ts
23809
+ init_review_recall_filter();
23290
23810
  init_search_candidates();
23291
23811
 
23292
23812
  // src/be/memory/usefulness-stats.ts
@@ -24123,6 +24643,9 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
24123
24643
  const provider = getEmbeddingProvider2();
24124
24644
  const store = getMemoryStore2();
24125
24645
  const queryEmbedding = await provider.embed(query, { kind: "query" });
24646
+ const sourceTaskIdHeader = req.headers["x-source-task-id"];
24647
+ const sourceTaskId = Array.isArray(sourceTaskIdHeader) ? sourceTaskIdHeader[0] : sourceTaskIdHeader;
24648
+ const excludeReviewTaskCompletions = await isReviewTaskId(sourceTaskId);
24126
24649
  const candidateLimit = Math.min(limit, 20) * CANDIDATE_SET_MULTIPLIER;
24127
24650
  const candidates = await searchMemoryCandidates(store, queryEmbedding ?? new Float32Array(0), myAgentId, {
24128
24651
  scope,
@@ -24130,18 +24653,18 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
24130
24653
  source,
24131
24654
  isLead: false,
24132
24655
  queryText: query,
24133
- keyPrefix
24656
+ keyPrefix,
24657
+ excludeReviewTaskCompletions
24134
24658
  });
24135
- const expanded = await expandCandidatesWithGraph(candidates, myAgentId, {
24659
+ const graphExpanded = await expandCandidatesWithGraph(candidates, myAgentId, {
24136
24660
  scope,
24137
24661
  source,
24138
24662
  keyPrefix,
24139
24663
  isLead: false
24140
24664
  });
24665
+ const expanded = await attachDemotionEvidence(excludeReviewTaskCompletions ? await dropReviewTaskCompletions(graphExpanded) : graphExpanded);
24141
24666
  const resultLimit = Math.min(limit, 20);
24142
24667
  const ranked = consumptionMode === "prompt" ? rerank(expanded, { limit: expanded.length }).map((r) => ({ r, eligible: memoryRelevance(r) > SIMILARITY_THRESHOLD })).sort((a, b) => Number(b.eligible) - Number(a.eligible)).slice(0, resultLimit).map(({ r }) => r) : rerank(expanded, { limit: resultLimit });
24143
- const sourceTaskIdHeader = req.headers["x-source-task-id"];
24144
- const sourceTaskId = Array.isArray(sourceTaskIdHeader) ? sourceTaskIdHeader[0] : sourceTaskIdHeader;
24145
24668
  const contextKeyHeader = req.headers["x-context-key"];
24146
24669
  const contextKey = Array.isArray(contextKeyHeader) ? contextKeyHeader[0] : contextKeyHeader;
24147
24670
  if (sourceTaskId && intent) {
@@ -24218,7 +24741,9 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
24218
24741
  if (pathNeedle) {
24219
24742
  candidates = candidates.filter((c) => matchesPath(c.sourcePath));
24220
24743
  }
24221
- const ranked = rerank(candidates, { limit: candidates.length });
24744
+ const ranked = rerank(await attachDemotionEvidence(candidates), {
24745
+ limit: candidates.length
24746
+ });
24222
24747
  const page = ranked.slice(offset, offset + pageLimit);
24223
24748
  listMemory.respond(res, 200, {
24224
24749
  results: page.map((r) => ({
@@ -25162,6 +25687,224 @@ async function handleMetrics(req, res, pathSegments, queryParams, myAgentId) {
25162
25687
  return false;
25163
25688
  }
25164
25689
 
25690
+ // src/http/model-groups.ts
25691
+ init_zod();
25692
+ init_audit_user();
25693
+ init_model_groups();
25694
+ init_rbac();
25695
+ init_types5();
25696
+ init_request_principal();
25697
+ init_route_def();
25698
+ init_utils2();
25699
+ var MembersSchema = array2(ModelProfileNameSchema).min(1).max(MAX_MODEL_GROUP_MEMBERS).describe("Profile names in preference order, first preferred. Any harness; no repeats.");
25700
+ var listGroups = route({
25701
+ method: "get",
25702
+ path: "/api/model-groups",
25703
+ pattern: ["api", "model-groups"],
25704
+ summary: "List model groups",
25705
+ description: "Every model group with its member profiles in order, by name.",
25706
+ tags: ["Models"],
25707
+ responses: {
25708
+ 200: { description: "Model groups", schema: object2({ groups: array2(ModelGroupSchema) }) }
25709
+ }
25710
+ });
25711
+ var getGroup = route({
25712
+ method: "get",
25713
+ path: "/api/model-groups/{name}",
25714
+ pattern: ["api", "model-groups", null],
25715
+ summary: "Get one model group",
25716
+ tags: ["Models"],
25717
+ params: object2({ name: string2() }),
25718
+ responses: {
25719
+ 200: { description: "The model group", schema: ModelGroupSchema },
25720
+ 404: { description: "No group with that name" }
25721
+ }
25722
+ });
25723
+ var createGroup = route({
25724
+ method: "post",
25725
+ path: "/api/model-groups",
25726
+ pattern: ["api", "model-groups"],
25727
+ summary: "Create a model group",
25728
+ description: "A group is an ordered list of model profiles that may span harnesses. Every member must be an existing profile, listed once. The name may not be a model profile's (groups and profiles share one name space; 409). Lead, operator or dashboard user.",
25729
+ tags: ["Models"],
25730
+ rbac: { permission: "models.groups.write" },
25731
+ body: object2({
25732
+ name: ModelProfileNameSchema,
25733
+ description: string2().trim().max(500).nullable().optional(),
25734
+ members: MembersSchema
25735
+ }),
25736
+ responses: {
25737
+ 201: { description: "Group created", schema: ModelGroupSchema },
25738
+ 400: { description: "Validation error" },
25739
+ 403: { description: "Forbidden" },
25740
+ 409: { description: "A group or profile with that name exists" }
25741
+ }
25742
+ });
25743
+ var updateGroup = route({
25744
+ method: "patch",
25745
+ path: "/api/model-groups/{name}",
25746
+ pattern: ["api", "model-groups", null],
25747
+ summary: "Update a model group",
25748
+ description: "Changes the description (`null` clears it). The name is fixed; reorder or replace members with `PUT /api/model-groups/{name}/members`. Lead, operator or dashboard user.",
25749
+ tags: ["Models"],
25750
+ rbac: { permission: "models.groups.write" },
25751
+ params: object2({ name: string2() }),
25752
+ body: object2({ description: string2().trim().max(500).nullable() }),
25753
+ responses: {
25754
+ 200: { description: "Group updated", schema: ModelGroupSchema },
25755
+ 400: { description: "Validation error" },
25756
+ 403: { description: "Forbidden" },
25757
+ 404: { description: "No group with that name" }
25758
+ }
25759
+ });
25760
+ var setMembers = route({
25761
+ method: "put",
25762
+ path: "/api/model-groups/{name}/members",
25763
+ pattern: ["api", "model-groups", null, "members"],
25764
+ summary: "Replace a model group's members",
25765
+ description: "Replaces the whole ordered member list in one transaction; send the full list to reorder. Every member must be an existing profile, listed once. Lead, operator or dashboard user.",
25766
+ tags: ["Models"],
25767
+ rbac: { permission: "models.groups.write" },
25768
+ params: object2({ name: string2() }),
25769
+ body: object2({ members: MembersSchema }),
25770
+ responses: {
25771
+ 200: { description: "Members replaced", schema: ModelGroupSchema },
25772
+ 400: { description: "Validation error" },
25773
+ 403: { description: "Forbidden" },
25774
+ 404: { description: "No group with that name" }
25775
+ }
25776
+ });
25777
+ var deleteGroup = route({
25778
+ method: "delete",
25779
+ path: "/api/model-groups/{name}",
25780
+ pattern: ["api", "model-groups", null],
25781
+ summary: "Delete a model group",
25782
+ description: "Refused (409) for a shipped tier group (`smol`, `regular`, `smart`, `ultra`; edit it instead, it would come back at the next boot), and while a schedule names the group or a task holds it (unfinished, or superseded and still owed its resume). Lead, operator or dashboard user.",
25783
+ tags: ["Models"],
25784
+ rbac: { permission: "models.groups.write" },
25785
+ params: object2({ name: string2() }),
25786
+ responses: {
25787
+ 200: { description: "Group deleted", schema: object2({ deleted: literal2(true) }) },
25788
+ 403: { description: "Forbidden" },
25789
+ 404: { description: "No group with that name" },
25790
+ 409: { description: "The group is a seed or still in use" }
25791
+ }
25792
+ });
25793
+ async function canWriteGroups(req, res, myAgentId) {
25794
+ const decision = can({
25795
+ principal: await agentFirstPrincipal(req, myAgentId),
25796
+ verb: "models.groups.write",
25797
+ resource: { kind: "none" },
25798
+ source: "http"
25799
+ });
25800
+ if (!decision.allow) {
25801
+ jsonError(res, "Writing model groups requires the lead, the operator or a dashboard user", 403);
25802
+ return false;
25803
+ }
25804
+ return true;
25805
+ }
25806
+ var WRITE_FAILURE_STATUS = { invalid: 400, exists: 409, "name-taken": 409, missing: 404 };
25807
+ function writeFailed(res, result) {
25808
+ if (result.ok)
25809
+ return false;
25810
+ jsonError(res, result.error, WRITE_FAILURE_STATUS[result.reason]);
25811
+ return true;
25812
+ }
25813
+ async function handleModelGroups(req, res, pathSegments, queryParams, myAgentId) {
25814
+ if (listGroups.match(req.method, pathSegments)) {
25815
+ const parsed = await listGroups.parse(req, res, pathSegments, queryParams);
25816
+ if (!parsed)
25817
+ return true;
25818
+ listGroups.respond(res, 200, { groups: await listModelGroups() });
25819
+ return true;
25820
+ }
25821
+ if (getGroup.match(req.method, pathSegments)) {
25822
+ const parsed = await getGroup.parse(req, res, pathSegments, queryParams);
25823
+ if (!parsed)
25824
+ return true;
25825
+ const group = await getModelGroupByName(parsed.params.name);
25826
+ if (!group) {
25827
+ jsonError(res, "Model group not found", 404);
25828
+ return true;
25829
+ }
25830
+ getGroup.respond(res, 200, group);
25831
+ return true;
25832
+ }
25833
+ if (createGroup.match(req.method, pathSegments)) {
25834
+ const parsed = await createGroup.parse(req, res, pathSegments, queryParams);
25835
+ if (!parsed)
25836
+ return true;
25837
+ if (!await canWriteGroups(req, res, myAgentId))
25838
+ return true;
25839
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
25840
+ const result = await createModelGroup(parsed.body, { userId });
25841
+ if (writeFailed(res, result))
25842
+ return true;
25843
+ createGroup.respond(res, 201, result.group);
25844
+ return true;
25845
+ }
25846
+ if (updateGroup.match(req.method, pathSegments)) {
25847
+ const parsed = await updateGroup.parse(req, res, pathSegments, queryParams);
25848
+ if (!parsed)
25849
+ return true;
25850
+ if (!await canWriteGroups(req, res, myAgentId))
25851
+ return true;
25852
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
25853
+ const result = await updateModelGroup(parsed.params.name, { description: parsed.body.description }, { userId });
25854
+ if (writeFailed(res, result))
25855
+ return true;
25856
+ updateGroup.respond(res, 200, result.group);
25857
+ return true;
25858
+ }
25859
+ if (setMembers.match(req.method, pathSegments)) {
25860
+ const parsed = await setMembers.parse(req, res, pathSegments, queryParams);
25861
+ if (!parsed)
25862
+ return true;
25863
+ if (!await canWriteGroups(req, res, myAgentId))
25864
+ return true;
25865
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
25866
+ const result = await updateModelGroup(parsed.params.name, { members: parsed.body.members }, { userId });
25867
+ if (writeFailed(res, result))
25868
+ return true;
25869
+ setMembers.respond(res, 200, result.group);
25870
+ return true;
25871
+ }
25872
+ if (deleteGroup.match(req.method, pathSegments)) {
25873
+ const parsed = await deleteGroup.parse(req, res, pathSegments, queryParams);
25874
+ if (!parsed)
25875
+ return true;
25876
+ if (!await canWriteGroups(req, res, myAgentId))
25877
+ return true;
25878
+ const current = await getModelGroupByName(parsed.params.name);
25879
+ if (!current) {
25880
+ jsonError(res, "Model group not found", 404);
25881
+ return true;
25882
+ }
25883
+ if (current.seededFrom?.startsWith("tier:")) {
25884
+ jsonError(res, `"${current.name}" is a shipped tier group and comes back at the next boot; edit it instead.`, 409);
25885
+ return true;
25886
+ }
25887
+ const refs = await modelGroupReferences(current.name);
25888
+ if (refs.openTaskCount > 0 || refs.scheduleIds.length > 0) {
25889
+ const schedules = refs.scheduleIds.length > 0 ? ` (${refs.scheduleIds.join(", ")})` : "";
25890
+ jsonError(res, `"${current.name}" is in use: held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}.`, 409);
25891
+ return true;
25892
+ }
25893
+ const outcome = await deleteModelGroup(current.name);
25894
+ if (outcome === "in-use") {
25895
+ jsonError(res, `"${current.name}" is in use by a task or a schedule written just now.`, 409);
25896
+ return true;
25897
+ }
25898
+ if (outcome === "missing") {
25899
+ jsonError(res, "Model group not found", 404);
25900
+ return true;
25901
+ }
25902
+ deleteGroup.respond(res, 200, { deleted: true });
25903
+ return true;
25904
+ }
25905
+ return false;
25906
+ }
25907
+
25165
25908
  // src/http/model-profiles.ts
25166
25909
  init_src2();
25167
25910
  init_zod();
@@ -25207,7 +25950,7 @@ var createProfile = route({
25207
25950
  path: "/api/model-profiles",
25208
25951
  pattern: ["api", "model-profiles"],
25209
25952
  summary: "Create a model profile",
25210
- description: "A profile runs on one harness. `model` must run on that harness and be in the model catalog unless `allowCustomModel` is true (a gateway id, a fresh launch); a `latest:` alias is accepted and resolves at claim. `effort` must be a level the harness and model support. `credentials` pins which pooled keys the profile uses: per credential var of the harness, the last 5 characters of each allowed key (`CODEX_OAUTH` is not supported). `fallbacks` lists profiles on the same harness, in order, that a task on this profile hops to when a provider error (rate limit, seat, overload, auth, empty key pool) ends it; no repeats, no self, no cycle. Operator only (the shared API key).",
25953
+ description: "A profile runs on one harness. `model` must run on that harness and be in the model catalog unless `allowCustomModel` is true (a gateway id, a fresh launch); a `latest:` alias is accepted and resolves at claim. `effort` must be a level the harness and model support. `credentials` pins which pooled keys the profile uses: per credential var of the harness, the last 5 characters of each allowed key (`CODEX_OAUTH` is not supported). `fallbacks` lists profiles on the same harness, in order, that a task on this profile hops to when a provider error (rate limit, seat, overload, auth, empty key pool) ends it; no repeats, no self, no cycle. The name may not be a model group's (one name space; 409). Operator only (the shared API key).",
25211
25954
  tags: ["Models"],
25212
25955
  rbac: { permission: "models.profiles.write" },
25213
25956
  body: object2({
@@ -25224,7 +25967,7 @@ var createProfile = route({
25224
25967
  201: { description: "Profile created", schema: ModelProfileSchema },
25225
25968
  400: { description: "Validation error" },
25226
25969
  403: { description: "Forbidden" },
25227
- 409: { description: "A profile with that name exists" }
25970
+ 409: { description: "A profile or model group with that name exists" }
25228
25971
  }
25229
25972
  });
25230
25973
  var updateProfile = route({
@@ -25256,7 +25999,7 @@ var deleteProfile = route({
25256
25999
  path: "/api/model-profiles/{name}",
25257
26000
  pattern: ["api", "model-profiles", null],
25258
26001
  summary: "Delete a model profile",
25259
- description: "Refused (409) for a shipped `<harness>-<tier>` seed (edit it instead; it would come back at the next boot), and while an agent has the profile as its default, a schedule names it, another profile lists it as a fallback, or a task holds it (unfinished, or superseded and still owed its resume). Operator only (the shared API key).",
26002
+ description: "Refused (409) for a shipped `<harness>-<tier>` seed (edit it instead; it would come back at the next boot), and while an agent has the profile as its default, a schedule names it, another profile lists it as a fallback, a model group lists it as a member, or a task holds it (unfinished, or superseded and still owed its resume). Operator only (the shared API key).",
25260
26003
  tags: ["Models"],
25261
26004
  rbac: { permission: "models.profiles.write" },
25262
26005
  params: object2({ name: string2() }),
@@ -25355,7 +26098,15 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
25355
26098
  if (fallbackError)
25356
26099
  return { error: fallbackError };
25357
26100
  return { created: await createModelProfile(body, { userId }) };
26101
+ }).catch((error) => {
26102
+ if (isModelNameTakenError(error))
26103
+ return { nameTaken: true };
26104
+ throw error;
25358
26105
  });
26106
+ if ("nameTaken" in outcome) {
26107
+ jsonError(res, `"${body.name}" is a model group; profiles and groups share one name space.`, 409);
26108
+ return true;
26109
+ }
25359
26110
  if (typeof outcome.error === "string") {
25360
26111
  jsonError(res, outcome.error, 400);
25361
26112
  return true;
@@ -25426,15 +26177,16 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
25426
26177
  return true;
25427
26178
  }
25428
26179
  const refs = await modelProfileReferences(current.name);
25429
- if (refs.agentIds.length > 0 || refs.openTaskCount > 0 || refs.scheduleIds.length > 0 || refs.fallbackOf.length > 0) {
26180
+ if (refs.agentIds.length > 0 || refs.openTaskCount > 0 || refs.scheduleIds.length > 0 || refs.fallbackOf.length > 0 || refs.groups.length > 0) {
25430
26181
  const schedules = refs.scheduleIds.length > 0 ? ` (${refs.scheduleIds.join(", ")})` : "";
25431
26182
  const fallbackOf = refs.fallbackOf.length > 0 ? ` (${refs.fallbackOf.join(", ")})` : "";
25432
- jsonError(res, `"${current.name}" is in use: default of ${refs.agentIds.length} agent(s), held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}, a fallback of ${refs.fallbackOf.length} profile(s)${fallbackOf}.`, 409);
26183
+ const groups = refs.groups.length > 0 ? ` (${refs.groups.join(", ")})` : "";
26184
+ jsonError(res, `"${current.name}" is in use: default of ${refs.agentIds.length} agent(s), held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}, a fallback of ${refs.fallbackOf.length} profile(s)${fallbackOf}, a member of ${refs.groups.length} model group(s)${groups}.`, 409);
25433
26185
  return true;
25434
26186
  }
25435
26187
  const outcome = await deleteModelProfile(current.name);
25436
26188
  if (outcome === "in-use") {
25437
- jsonError(res, `"${current.name}" is in use by a task, a schedule, an agent default or a fallback list written just now.`, 409);
26189
+ jsonError(res, `"${current.name}" is in use by a task, a schedule, an agent default, a fallback list or a model group written just now.`, 409);
25438
26190
  return true;
25439
26191
  }
25440
26192
  if (outcome === "missing") {
@@ -26980,9 +27732,9 @@ function embeddingsProvider(baseUrl) {
26980
27732
  }
26981
27733
  function deploymentEmbeddings() {
26982
27734
  return {
26983
- baseUrl: getDeploymentEnvValue("EMBEDDING_API_BASE_URL"),
26984
- model: getDeploymentEnvValue("EMBEDDING_MODEL") ?? "text-embedding-3-small",
26985
- apiKey: getDeploymentEnvValue("EMBEDDING_API_KEY") ?? process.env.OPENAI_API_KEY
27735
+ baseUrl: getDeploymentEnvValue2("EMBEDDING_API_BASE_URL"),
27736
+ model: getDeploymentEnvValue2("EMBEDDING_MODEL") ?? "text-embedding-3-small",
27737
+ apiKey: getDeploymentEnvValue2("EMBEDDING_API_KEY") ?? process.env.OPENAI_API_KEY
26986
27738
  };
26987
27739
  }
26988
27740
  function localDefault() {
@@ -27130,14 +27882,14 @@ async function updateMemoryState(preset, result, change) {
27130
27882
  if (!configChanged)
27131
27883
  return;
27132
27884
  if (change?.kind === "restore") {
27133
- await loadGlobalConfigsIntoEnv(true);
27885
+ await loadGlobalConfigsIntoEnv2(true);
27134
27886
  resetEmbeddingProvider2();
27135
27887
  }
27136
- scheduleIntegrationsReload();
27888
+ scheduleIntegrationsReload2();
27137
27889
  }
27138
27890
  function prefixChanges(model) {
27139
- const sameModel = model === getDeploymentEnvValue("EMBEDDING_MODEL");
27140
- return EMBEDDING_PREFIX_KEYS.filter((key) => getDeploymentEnvValue(key)).map((key) => ({
27891
+ const sameModel = model === getDeploymentEnvValue2("EMBEDDING_MODEL");
27892
+ return EMBEDDING_PREFIX_KEYS.filter((key) => getDeploymentEnvValue2(key)).map((key) => ({
27141
27893
  key,
27142
27894
  value: sameModel ? null : ""
27143
27895
  }));
@@ -27149,7 +27901,7 @@ async function handleMemoryProbe(body) {
27149
27901
  const deployment = restore ? deploymentEmbeddings() : null;
27150
27902
  const baseUrl = body.preset === "existing" ? deployment ? deployment.baseUrl : process.env.EMBEDDING_API_BASE_URL : body.baseUrl ?? preset?.baseUrl ?? process.env.EMBEDDING_API_BASE_URL ?? "https://api.openai.com/v1";
27151
27903
  const model = body.preset === "existing" ? deployment?.model ?? process.env.EMBEDDING_MODEL ?? "text-embedding-3-small" : body.model ?? preset?.model ?? process.env.EMBEDDING_MODEL ?? "text-embedding-3-small";
27152
- const configuredEndpoint = body.preset === "existing" && !!baseUrl && baseUrl === getDeploymentEnvValue("EMBEDDING_API_BASE_URL");
27904
+ const configuredEndpoint = body.preset === "existing" && !!baseUrl && baseUrl === getDeploymentEnvValue2("EMBEDDING_API_BASE_URL");
27153
27905
  let endpoint;
27154
27906
  try {
27155
27907
  endpoint = configuredEndpoint ? new URL(baseUrl ?? "") : assertUrlSafe(baseUrl ?? "", publicEndpointSsrfOptions());
@@ -27505,15 +28257,17 @@ init_rbac_roles();
27505
28257
  init_session_shares();
27506
28258
  init_steering2();
27507
28259
  init_task_citations2();
28260
+ init_task_ui_spec();
27508
28261
  init_users();
27509
28262
  init_rbac();
27510
28263
  init_context_key();
27511
- init_errors();
28264
+ init_errors2();
27512
28265
  init_sibling_awareness();
27513
28266
  init_task_skip();
27514
28267
  init_terminal_result_guard();
27515
28268
  init_worker_follow_up();
27516
28269
  init_types5();
28270
+ init_actions();
27517
28271
  init_business_use();
27518
28272
  init_request_auth_context();
27519
28273
  init_secret_scrubber();
@@ -27726,7 +28480,8 @@ var GetTaskResponseSchema = AgentTaskSchema.extend({
27726
28480
  supportedSteerModes: array2(SteerModeSchema),
27727
28481
  logs: array2(AgentLogSchema),
27728
28482
  attachments: array2(TaskAttachmentSchema),
27729
- citations: array2(TaskCitationSchema)
28483
+ citations: array2(TaskCitationSchema),
28484
+ uiSpec: TaskUiSpecSchema.nullable()
27730
28485
  });
27731
28486
  var FinishTaskSuccessSchema = object2({
27732
28487
  success: literal2(true),
@@ -27841,7 +28596,7 @@ var createTask = route({
27841
28596
  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"
27842
28597
  },
27843
28598
  403: {
27844
- description: "An agent caller names a parentTaskId it neither owns nor created, or a non-lead agent binds the task to a chat thread"
28599
+ description: "Parent/session access denied, unauthorized chat-thread binding, or routing requirements reject the assignment"
27845
28600
  },
27846
28601
  422: {
27847
28602
  description: "Task creation blocked by an extension",
@@ -28188,13 +28943,45 @@ var resumeTaskRoute = route({
28188
28943
  404: { description: "Task not found" }
28189
28944
  }
28190
28945
  });
28946
+ var runTaskUiActionRoute = route({
28947
+ method: "post",
28948
+ path: "/api/tasks/{id}/ui-actions/{actionId}",
28949
+ pattern: ["api", "tasks", null, "ui-actions", null],
28950
+ session: { taskParam: "id" },
28951
+ rbac: { permission: "task.action.own" },
28952
+ summary: "Run the action a task card Button declares",
28953
+ description: "Runs a task card action. Only the task requester may run it: a user token, or the operator key with the requester in `X-Swarm-User-Id`. Agent callers, and operator calls with no picked user, get 403. Needs UI_SPEC_ACTIONS_ENABLED=true. A `follow_up` action runs once per task and action. A `script` action re-runs its allowlisted script (UI_SPEC_SCRIPT_ACTIONS) and returns the new card; it can run again after a 30 s cooldown.",
28954
+ tags: ["Tasks"],
28955
+ params: object2({ id: string2(), actionId: string2() }),
28956
+ responses: {
28957
+ 200: {
28958
+ description: "The follow-up started or already ran, or the script action replaced the card (`refreshed`, with the new `uiSpec`)",
28959
+ schema: object2({
28960
+ status: _enum2(["started", "already_done", "refreshed"]),
28961
+ taskId: string2().optional(),
28962
+ uiSpec: TaskUiSpecSchema.optional()
28963
+ })
28964
+ },
28965
+ 403: {
28966
+ description: "Only the task requester may run the action, or the action's script is not allowlisted or changed since it was allowlisted"
28967
+ },
28968
+ 404: { description: "Task or action not found" },
28969
+ 409: {
28970
+ description: "Card actions are turned off (UI_SPEC_ACTIONS_ENABLED), or the script action is already running (with `Retry-After`)"
28971
+ },
28972
+ 422: { description: "The script failed or returned an invalid card; the old card stays" },
28973
+ 429: {
28974
+ description: "The script action ran recently; `Retry-After` says when it can run again"
28975
+ }
28976
+ }
28977
+ });
28191
28978
  var supersedeTaskRoute = route({
28192
28979
  method: "post",
28193
28980
  path: "/api/tasks/{id}/supersede",
28194
28981
  pattern: ["api", "tasks", null, "supersede"],
28195
28982
  session: { taskParam: "id" },
28196
28983
  summary: "Supersede an in-progress task (terminate + spawn resume follow-up)",
28197
- 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.',
28984
+ description: "Marks the original task `superseded` (terminal) and creates a fresh `taskType=\"resume\"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine's retry/failure policy applies, and the task moves to `superseded` once the engine queues the step's retry or the step ends without failing. With `reason: provider_fallback` (and its `errorClass`), the resume runs on the same agent with the next fallback profile that passes the profile check; when none is left, or the task is a workflow step, nothing changes and `kind: noFallback` tells the worker to fail the task itself, led by `failureReason` when set.",
28198
28985
  tags: ["Tasks"],
28199
28986
  params: object2({ id: string2() }),
28200
28987
  body: object2({ reason: ResumeReasonSchema, errorClass: ProviderErrorClassSchema.optional() }).refine((body) => body.reason === "provider_fallback" === (body.errorClass !== undefined), {
@@ -28491,6 +29278,7 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
28491
29278
  vcsRepo,
28492
29279
  parentTaskId: parsed.body.parentTaskId || undefined,
28493
29280
  inheritParentOutputSchema: principal.kind === "agent",
29281
+ routingAffinity: parsed.body.parentTaskId && (principal.kind === "user" || principal.kind === "operator") ? { capabilities: [] } : undefined,
28494
29282
  source: parsed.body.source || "api",
28495
29283
  outputSchema: parsed.body.outputSchema || undefined,
28496
29284
  contextKey: parsed.body.contextKey || undefined,
@@ -28520,6 +29308,16 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
28520
29308
  });
28521
29309
  createTask.respond(res, 201, task);
28522
29310
  } catch (error) {
29311
+ if (error instanceof TaskRoutingAuthorizationError) {
29312
+ console.warn("[HTTP] Task assignment rejected:", scrubSecrets(JSON.stringify({
29313
+ parentTaskId: parsed.body.parentTaskId,
29314
+ source: parsed.body.source ?? "api",
29315
+ contextKey: parsed.body.contextKey ?? parentTask?.contextKey,
29316
+ reason: error.message
29317
+ })));
29318
+ jsonError(res, error.message, 403);
29319
+ return true;
29320
+ }
28523
29321
  if (error instanceof TaskCreationBlockedError) {
28524
29322
  createTask.respond(res, 422, { error: error.reason, extension: error.extension });
28525
29323
  return true;
@@ -28895,7 +29693,8 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
28895
29693
  ...await getTaskSteeringFields(task),
28896
29694
  logs,
28897
29695
  attachments,
28898
- citations: await getTaskCitations(task.id)
29696
+ citations: await getTaskCitations(task.id),
29697
+ uiSpec: await getTaskUiSpec(task.id)
28899
29698
  });
28900
29699
  return true;
28901
29700
  }
@@ -29200,6 +29999,66 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
29200
29999
  updateTaskTagsRoute.respond(res, 200, { task });
29201
30000
  return true;
29202
30001
  }
30002
+ if (runTaskUiActionRoute.match(req.method, pathSegments)) {
30003
+ const parsed = await runTaskUiActionRoute.parse(req, res, pathSegments, queryParams);
30004
+ if (!parsed)
30005
+ return true;
30006
+ const task = await getTaskById2(parsed.params.id);
30007
+ if (!task) {
30008
+ jsonError(res, "Task not found", 404);
30009
+ return true;
30010
+ }
30011
+ if (!await canActOnOwnTask(req, myAgentId, task)) {
30012
+ jsonError(res, "Not authorized to act on this task", 403);
30013
+ return true;
30014
+ }
30015
+ const actor = await resolveSessionActor2(req, myAgentId);
30016
+ const tokenUserId = authUserId(getRequestAuth(req));
30017
+ const trustsPickedUser = process.env.TRUST_BODY_REQUESTED_BY_USER_ID !== "false";
30018
+ const actorUserId = actor.kind === "user" && (tokenUserId || trustsPickedUser) ? actor.userId ?? undefined : undefined;
30019
+ const result = await runTaskUiAction({
30020
+ taskId: task.id,
30021
+ actionId: parsed.params.actionId,
30022
+ surface: "web",
30023
+ actorUserId
30024
+ });
30025
+ switch (result.status) {
30026
+ case "forbidden":
30027
+ jsonError(res, "Only the task requester may run this action", 403);
30028
+ return true;
30029
+ case "unknown_action":
30030
+ jsonError(res, "This task declares no such action", 404);
30031
+ return true;
30032
+ case "disabled":
30033
+ jsonError(res, "Card actions are turned off (UI_SPEC_ACTIONS_ENABLED)", 409);
30034
+ return true;
30035
+ case "already_done":
30036
+ runTaskUiActionRoute.respond(res, 200, { status: "already_done" });
30037
+ return true;
30038
+ case "started":
30039
+ case "refreshed":
30040
+ runTaskUiActionRoute.respond(res, 200, result);
30041
+ return true;
30042
+ case "not_allowlisted":
30043
+ jsonError(res, "This action's script is not allowlisted (UI_SPEC_SCRIPT_ACTIONS)", 403);
30044
+ return true;
30045
+ case "script_changed":
30046
+ jsonError(res, "This action's script changed since it was allowlisted; an admin must re-pin it in UI_SPEC_SCRIPT_ACTIONS", 403);
30047
+ return true;
30048
+ case "running":
30049
+ res.setHeader("Retry-After", String(result.retryAfterSec));
30050
+ jsonError(res, "This action is already running", 409);
30051
+ return true;
30052
+ case "rate_limited":
30053
+ res.setHeader("Retry-After", String(result.retryAfterSec));
30054
+ jsonError(res, `This action ran recently; try again in ${result.retryAfterSec}s`, 429);
30055
+ return true;
30056
+ case "script_failed":
30057
+ case "invalid_output":
30058
+ jsonError(res, `Refresh failed: ${result.error}`, 422);
30059
+ return true;
30060
+ }
30061
+ }
29203
30062
  if (resumeTaskRoute.match(req.method, pathSegments)) {
29204
30063
  const parsed = await resumeTaskRoute.parse(req, res, pathSegments, queryParams);
29205
30064
  if (!parsed)
@@ -33369,7 +34228,7 @@ var deletePoolKey = route({
33369
34228
  var ENV_POOL_ERROR = "These keys come from the deployment env. Change them there.";
33370
34229
  async function readPool(key) {
33371
34230
  const [row] = await getSwarmConfigs2({ scope: "global", key });
33372
- const envValue = getDeploymentEnvValue(key);
34231
+ const envValue = getDeploymentEnvValue2(key);
33373
34232
  const source = row ? "stored" : envValue ? "env" : "none";
33374
34233
  const value = row?.value ?? envValue ?? "";
33375
34234
  registerEnvSecrets({ [key]: value });
@@ -41414,155 +42273,14 @@ async function handleScripts(req, res, pathSegments, queryParams, agentId) {
41414
42273
  // src/http/session-data.ts
41415
42274
  init_zod();
41416
42275
  init_db4();
42276
+ init_users();
41417
42277
  init_otel();
41418
42278
  init_types5();
42279
+ init_request_auth_context();
42280
+ init_secret_scrubber();
41419
42281
  init_route_def();
41420
42282
  init_session_access();
41421
-
41422
- // src/http/session-cost-recompute.ts
41423
- init_pricing_normalize();
41424
- init_amp_models();
41425
- var PER_MILLION = 1e6;
41426
- var INCLUSIVE_INPUT_PROVIDERS = new Set(["codex"]);
41427
- function cacheWriteSplit(input) {
41428
- if (input.cacheWrite5mTokens == null || input.cacheWrite1hTokens == null)
41429
- return null;
41430
- const total = input.cacheWrite5mTokens + input.cacheWrite1hTokens;
41431
- if (total === 0)
41432
- return null;
41433
- return {
41434
- fiveMinuteRatio: input.cacheWrite5mTokens / total,
41435
- oneHourRatio: input.cacheWrite1hTokens / total
41436
- };
41437
- }
41438
- async function priceModel(provider, usage, split, atEpochMs, lookupRate) {
41439
- const lookupModel = normalizeModelKey(provider, usage.model);
41440
- const inputRate = await lookupRate(provider, lookupModel, "input", atEpochMs);
41441
- const outputRate = await lookupRate(provider, lookupModel, "output", atEpochMs);
41442
- if (inputRate == null || outputRate == null)
41443
- return null;
41444
- const cacheReadRate = await lookupRate(provider, lookupModel, "cached_input", atEpochMs) ?? 0;
41445
- const uncachedInputTokens = INCLUSIVE_INPUT_PROVIDERS.has(provider) ? Math.max(0, usage.inputTokens - usage.cacheReadTokens) : usage.inputTokens;
41446
- let cacheWriteCostUnits = 0;
41447
- if (split) {
41448
- const fiveMinuteTokens = usage.cacheWriteTokens * split.fiveMinuteRatio;
41449
- const oneHourTokens = usage.cacheWriteTokens * split.oneHourRatio;
41450
- const fiveMinuteRate = await lookupRate(provider, lookupModel, "cache_write", atEpochMs) ?? 0;
41451
- const oneHourRate = await lookupRate(provider, lookupModel, "cache_write_1h", atEpochMs);
41452
- if (oneHourTokens > 0 && oneHourRate == null)
41453
- return null;
41454
- cacheWriteCostUnits = fiveMinuteTokens * fiveMinuteRate + oneHourTokens * (oneHourRate ?? 0);
41455
- } else {
41456
- const cacheWriteRate = await lookupRate(provider, lookupModel, "cache_write", atEpochMs) ?? 0;
41457
- cacheWriteCostUnits = usage.cacheWriteTokens * cacheWriteRate;
41458
- }
41459
- return (uncachedInputTokens * inputRate + usage.cacheReadTokens * cacheReadRate + cacheWriteCostUnits + usage.outputTokens * outputRate) / PER_MILLION;
41460
- }
41461
- function unpricedResult(input, modelBreakdown) {
41462
- return {
41463
- totalCostUsd: input.harnessCostUsd,
41464
- costSource: "unpriced",
41465
- modelBreakdown
41466
- };
41467
- }
41468
- async function estimateAmpCost(input, lookupRate) {
41469
- let selection;
41470
- try {
41471
- selection = resolveAmpModel(input.model);
41472
- } catch {
41473
- selection = undefined;
41474
- }
41475
- const candidates = [
41476
- ...new Set([
41477
- selection?.pin,
41478
- selection ? AMP_ESTIMATE_MODELS[selection.baseMode] : undefined,
41479
- AMP_ESTIMATE_MODELS.medium
41480
- ])
41481
- ].filter((model) => !!model);
41482
- for (const model of candidates) {
41483
- const writes = ampBillsCacheWrites(model);
41484
- const costUsd = await priceModel("amp", {
41485
- model,
41486
- inputTokens: input.inputTokens + (writes ? 0 : input.cacheWriteTokens),
41487
- outputTokens: input.outputTokens,
41488
- cacheReadTokens: input.cacheReadTokens,
41489
- cacheWriteTokens: writes ? input.cacheWriteTokens : 0
41490
- }, null, input.atEpochMs, lookupRate);
41491
- if (costUsd != null)
41492
- return { totalCostUsd: costUsd, costSource: "estimated", modelBreakdown: undefined };
41493
- }
41494
- return unpricedResult(input, undefined);
41495
- }
41496
- async function recomputeSessionCost(input, lookupRate) {
41497
- const modelUsageEntries = input.models?.length ? input.models : undefined;
41498
- const modelBreakdown = modelUsageEntries?.map((model) => ({ ...model }));
41499
- if (!input.provider) {
41500
- return {
41501
- totalCostUsd: input.harnessCostUsd,
41502
- costSource: "harness",
41503
- modelBreakdown
41504
- };
41505
- }
41506
- if ((input.provider === "amp" || input.provider === "grok" || input.harnessCostBilled) && input.harnessCostUsd > 0) {
41507
- const priced = await recomputeSessionCost({ ...input, harnessCostUsd: 0, harnessCostBilled: false }, lookupRate);
41508
- return {
41509
- totalCostUsd: input.harnessCostUsd,
41510
- costSource: "harness",
41511
- modelBreakdown: priced.modelBreakdown
41512
- };
41513
- }
41514
- if (input.provider === "acp" && input.harnessCostUsd > 0) {
41515
- return { totalCostUsd: input.harnessCostUsd, costSource: "harness", modelBreakdown };
41516
- }
41517
- if (input.provider === "amp" && !modelUsageEntries)
41518
- return estimateAmpCost(input, lookupRate);
41519
- const split = cacheWriteSplit(input);
41520
- const usages = modelUsageEntries ? modelUsageEntries : input.model ? [
41521
- {
41522
- model: input.model,
41523
- inputTokens: input.inputTokens,
41524
- outputTokens: input.outputTokens,
41525
- cacheReadTokens: input.cacheReadTokens,
41526
- cacheWriteTokens: input.cacheWriteTokens
41527
- }
41528
- ] : [];
41529
- if (usages.length === 0) {
41530
- return {
41531
- totalCostUsd: input.harnessCostUsd,
41532
- costSource: "harness",
41533
- modelBreakdown
41534
- };
41535
- }
41536
- const pricedModels = [];
41537
- let pricedCostUsd = 0;
41538
- const hasWebSearchRequests = usages.some((usage) => (usage.webSearchRequests ?? 0) > 0);
41539
- const webSearchRate = hasWebSearchRequests ? await lookupRate(input.provider, "*", "web_search", input.atEpochMs) : null;
41540
- for (const usage of usages) {
41541
- const tokenCostUsd = await priceModel(input.provider, usage, split, input.atEpochMs, lookupRate);
41542
- if (tokenCostUsd == null)
41543
- return unpricedResult(input, modelBreakdown);
41544
- const webSearchCostUsd = (usage.webSearchRequests ?? 0) * (webSearchRate ?? 0) / PER_MILLION;
41545
- const costUsd = tokenCostUsd + webSearchCostUsd;
41546
- pricedCostUsd += costUsd;
41547
- if (modelUsageEntries)
41548
- pricedModels.push({ ...usage, costUsd });
41549
- }
41550
- let sessionFeesUsd = 0;
41551
- const durationMs = input.durationMs ?? 0;
41552
- if (input.provider === "claude-managed" && durationMs > 0) {
41553
- const runtimeRate = await lookupRate(input.provider, "*", "runtime_hour", input.atEpochMs);
41554
- if (runtimeRate == null)
41555
- return unpricedResult(input, modelBreakdown);
41556
- sessionFeesUsd += durationMs / 3600000 * (runtimeRate / PER_MILLION);
41557
- }
41558
- return {
41559
- totalCostUsd: pricedCostUsd + sessionFeesUsd,
41560
- costSource: "pricing-table",
41561
- modelBreakdown: modelUsageEntries ? pricedModels : undefined
41562
- };
41563
- }
41564
-
41565
- // src/http/session-data.ts
42283
+ init_session_cost_recompute();
41566
42284
  init_utils2();
41567
42285
  var SessionCostSummaryTotalsSchema = object2({
41568
42286
  totalCostUsd: number2(),
@@ -41577,7 +42295,9 @@ var SessionCostSummaryTotalsSchema = object2({
41577
42295
  attributableCostUsd: number2(),
41578
42296
  excludedCostUsd: number2(),
41579
42297
  excludedTaskCount: number2().int(),
41580
- subscriptionCostUsd: number2()
42298
+ subscriptionCostUsd: number2(),
42299
+ credentialUnattributedCostUsd: number2(),
42300
+ credentialUnattributedSessions: number2().int()
41581
42301
  });
41582
42302
  var SessionCostDailyRowSchema = object2({
41583
42303
  date: string2(),
@@ -41585,7 +42305,9 @@ var SessionCostDailyRowSchema = object2({
41585
42305
  inputTokens: number2().int(),
41586
42306
  outputTokens: number2().int(),
41587
42307
  sessions: number2().int(),
41588
- subscriptionCostUsd: number2()
42308
+ subscriptionCostUsd: number2(),
42309
+ credentialUnattributedCostUsd: number2(),
42310
+ credentialUnattributedSessions: number2().int()
41589
42311
  });
41590
42312
  var SessionCostByAgentRowSchema = object2({
41591
42313
  agentId: string2(),
@@ -41689,12 +42411,15 @@ var createSessionCostRoute = route({
41689
42411
  id: string2().uuid().optional(),
41690
42412
  sessionId: string2().min(1),
41691
42413
  agentId: string2().min(1),
42414
+ credentialKeyType: string2().regex(/^[A-Z][A-Z0-9_]{0,79}$/).nullable().optional(),
42415
+ credentialKeySuffix: string2().min(1).max(10).nullable().optional(),
42416
+ harness: ProviderNameSchema.nullable().optional(),
41692
42417
  totalCostUsd: number2(),
41693
42418
  harnessCostBilled: boolean().optional(),
41694
42419
  taskId: string2().optional(),
41695
42420
  inputTokens: number2().int().nonnegative().optional(),
41696
42421
  outputTokens: number2().int().nonnegative().optional(),
41697
- cacheReadTokens: number2().int().nonnegative().optional(),
42422
+ cacheReadTokens: number2().int().nonnegative().nullable().optional(),
41698
42423
  cacheWriteTokens: number2().int().nonnegative().nullable().optional(),
41699
42424
  cacheWrite5mTokens: number2().int().nonnegative().nullable().optional(),
41700
42425
  cacheWrite1hTokens: number2().int().nonnegative().nullable().optional(),
@@ -41713,7 +42438,9 @@ var createSessionCostRoute = route({
41713
42438
  description: "Cost record stored",
41714
42439
  schema: object2({ success: literal2(true), cost: SessionCostSchema })
41715
42440
  },
41716
- 400: { description: "Validation error" }
42441
+ 400: { description: "Validation error" },
42442
+ 403: { description: "Untrusted session attribution" },
42443
+ 409: { description: "Session identity conflict" }
41717
42444
  }
41718
42445
  });
41719
42446
  var getSessionCostSummaryRoute = route({
@@ -41832,6 +42559,21 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
41832
42559
  const parsed = await createSessionCostRoute.parse(req, res, pathSegments, queryParams);
41833
42560
  if (!parsed)
41834
42561
  return true;
42562
+ const auth = getRequestAuth(req);
42563
+ 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);
42564
+ const hasAttribution = parsed.body.credentialKeyType != null || parsed.body.credentialKeySuffix != null || parsed.body.harness != null;
42565
+ if (hasAttribution && !trustedWorker) {
42566
+ jsonError(res, "Session attribution requires a worker or operator credential.", 403);
42567
+ return true;
42568
+ }
42569
+ if (auth?.kind === "agent" && auth.agentId !== parsed.body.agentId) {
42570
+ jsonError(res, "Session cost agent does not match the authenticated agent.", 403);
42571
+ return true;
42572
+ }
42573
+ if (parsed.body.credentialKeyType != null !== (parsed.body.credentialKeySuffix != null)) {
42574
+ jsonError(res, "Session credential type and suffix must be supplied together.", 400);
42575
+ return true;
42576
+ }
41835
42577
  try {
41836
42578
  const inputTokens = parsed.body.inputTokens ?? 0;
41837
42579
  const cachedInputTokens = parsed.body.cacheReadTokens ?? 0;
@@ -41841,8 +42583,8 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
41841
42583
  const bodyModels = parsed.body.models?.length ? parsed.body.models : null;
41842
42584
  const rowInputTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.inputTokens, 0) : inputTokens;
41843
42585
  const rowOutputTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.outputTokens, 0) : outputTokens;
41844
- const rowCacheReadTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheReadTokens, 0) : cachedInputTokens;
41845
- const rowCacheWriteTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheWriteTokens, 0) : parsed.body.cacheWriteTokens ?? 0;
42586
+ const rowCacheReadTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheReadTokens, 0) : parsed.body.cacheReadTokens ?? null;
42587
+ const rowCacheWriteTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheWriteTokens, 0) : parsed.body.cacheWriteTokens ?? null;
41846
42588
  const harnessCostUsd = parsed.body.totalCostUsd > 0 ? parsed.body.totalCostUsd : null;
41847
42589
  const recomputed = await recomputeSessionCost({
41848
42590
  provider: parsed.body.provider,
@@ -41860,7 +42602,10 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
41860
42602
  atEpochMs: parsed.body.createdAt ?? Date.now()
41861
42603
  }, async (provider, lookupModel, tokenClass, atEpochMs) => (await getActivePricingRow2(provider, lookupModel, tokenClass, atEpochMs))?.pricePerMillionUsd ?? null);
41862
42604
  const { totalCostUsd, costSource } = recomputed;
41863
- const cost = await createSessionCost2({
42605
+ const { cost, created } = await insertSessionCost2({
42606
+ credentialKeyType: parsed.body.credentialKeyType,
42607
+ credentialKeySuffix: parsed.body.credentialKeySuffix,
42608
+ harness: parsed.body.harness,
41864
42609
  id: parsed.body.id,
41865
42610
  sessionId: parsed.body.sessionId,
41866
42611
  taskId: parsed.body.taskId || undefined,
@@ -41882,26 +42627,32 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
41882
42627
  cacheWrite1hTokens: parsed.body.cacheWrite1hTokens,
41883
42628
  modelBreakdown: recomputed.modelBreakdown
41884
42629
  });
41885
- recordSessionCost2({
41886
- totalCostUsd,
41887
- harnessCostUsd: harnessCostUsd ?? undefined,
41888
- harness: parsed.body.provider ?? "unknown",
41889
- model,
41890
- costSource,
41891
- isError: parsed.body.isError ?? false,
41892
- tokens: {
41893
- input: rowInputTokens,
41894
- output: rowOutputTokens,
41895
- cacheRead: rowCacheReadTokens,
41896
- cacheWrite: rowCacheWriteTokens,
41897
- reasoning: parsed.body.reasoningOutputTokens ?? 0,
41898
- thinking: parsed.body.thinkingTokens ?? 0
41899
- }
41900
- });
41901
- incrementServerSessionsProcessed();
42630
+ if (created) {
42631
+ recordSessionCost2({
42632
+ totalCostUsd,
42633
+ harnessCostUsd: harnessCostUsd ?? undefined,
42634
+ harness: parsed.body.provider ?? "unknown",
42635
+ model,
42636
+ costSource,
42637
+ isError: parsed.body.isError ?? false,
42638
+ tokens: {
42639
+ input: rowInputTokens,
42640
+ output: rowOutputTokens,
42641
+ cacheRead: rowCacheReadTokens ?? 0,
42642
+ cacheWrite: rowCacheWriteTokens ?? 0,
42643
+ reasoning: parsed.body.reasoningOutputTokens ?? 0,
42644
+ thinking: parsed.body.thinkingTokens ?? 0
42645
+ }
42646
+ });
42647
+ incrementServerSessionsProcessed();
42648
+ }
41902
42649
  createSessionCostRoute.respond(res, 201, { success: true, cost });
41903
42650
  } catch (error) {
41904
- console.error("[HTTP] Failed to create session cost:", error);
42651
+ if (error instanceof SessionCostConflictError2) {
42652
+ jsonError(res, error.message, 409);
42653
+ return true;
42654
+ }
42655
+ console.error("[HTTP] Failed to create session cost:", scrubSecrets(String(error)));
41905
42656
  jsonError(res, "Failed to store session cost", 500);
41906
42657
  }
41907
42658
  return true;
@@ -41979,6 +42730,7 @@ init_rbac_roles();
41979
42730
  init_session_shares();
41980
42731
  init_steering2();
41981
42732
  init_task_citations2();
42733
+ init_task_ui_spec();
41982
42734
  init_users();
41983
42735
  init_rbac();
41984
42736
  init_auth2();
@@ -42148,6 +42900,7 @@ var SessionKeyFilterSchema = string2().transform((value, ctx) => {
42148
42900
  });
42149
42901
  var TaskWithSteeringSchema = AgentTaskSchema.extend({
42150
42902
  citations: array2(TaskCitationSchema),
42903
+ uiSpec: TaskUiSpecSchema.nullable(),
42151
42904
  isLeadTask: boolean(),
42152
42905
  supportedSteerModes: array2(SteerModeSchema)
42153
42906
  });
@@ -42956,9 +43709,10 @@ async function handleSessions(req, res, pathSegments, queryParams, myAgentId) {
42956
43709
  } : null;
42957
43710
  const chain = await withDispatchedTasks(await getRootTaskChain2(parsed.params.rootTaskId), sessionRoot.id, actor);
42958
43711
  const tasks = [root, ...chain];
42959
- const [steering, citations, approvals, read, groupKey] = await Promise.all([
43712
+ const [steering, citations, uiSpecs, approvals, read, groupKey] = await Promise.all([
42960
43713
  getTaskSteeringFieldsForTasks(tasks),
42961
43714
  getTaskCitationsForTasks(tasks.map((task) => task.id)),
43715
+ getTaskUiSpecsForTasks(tasks.map((task) => task.id)),
42962
43716
  getPendingApprovalsForTasks2(tasks.map((task) => task.id)),
42963
43717
  actor.kind === "user" && actor.userId ? getSessionReadState(sessionRoot.id, actor.userId, undefined, actor.readAll) : Promise.resolve(null),
42964
43718
  getSessionGroupKey(root)
@@ -42966,7 +43720,8 @@ async function handleSessions(req, res, pathSegments, queryParams, myAgentId) {
42966
43720
  const decorate = (task) => ({
42967
43721
  ...task,
42968
43722
  ...steering.get(task.id),
42969
- citations: citations.get(task.id)
43723
+ citations: citations.get(task.id),
43724
+ uiSpec: uiSpecs.get(task.id) ?? null
42970
43725
  });
42971
43726
  getSession.respond(res, 200, {
42972
43727
  root: decorate(root),
@@ -44816,7 +45571,7 @@ async function handleTelemetryUi(req, res, pathSegments, queryParams, myAgentId)
44816
45571
  await upsertSwarmConfig2({ scope: "global", key: "ANONYMIZED_TELEMETRY", value: "true" });
44817
45572
  process.env.ANONYMIZED_TELEMETRY = "true";
44818
45573
  await syncTelemetryEnabled(parsed.body.via);
44819
- scheduleIntegrationsReload();
45574
+ scheduleIntegrationsReload2();
44820
45575
  enableTelemetry.respond(res, 200, { enabled: isTelemetryEnabled() });
44821
45576
  return true;
44822
45577
  }
@@ -44845,6 +45600,116 @@ async function handleTelemetryUi(req, res, pathSegments, queryParams, myAgentId)
44845
45600
  return true;
44846
45601
  }
44847
45602
 
45603
+ // src/http/tool-hooks.ts
45604
+ init_zod();
45605
+ init_dispatcher();
45606
+ init_secret_scrubber();
45607
+ init_route_def();
45608
+ init_utils2();
45609
+ var REDACTION_MARKER = "[REDACTED:";
45610
+ var toolCallFields = {
45611
+ harness: string2().min(1).max(64).describe("Worker harness, such as `claude` or `pi`."),
45612
+ tool: string2().min(1).max(256).describe("Canonical tool name, such as `bash` or `edit`."),
45613
+ nativeTool: string2().min(1).max(256).optional().describe("The harness's own tool name."),
45614
+ args: unknown().describe("Canonical tool arguments."),
45615
+ rawArgs: unknown().optional().describe("The harness's own argument shape."),
45616
+ toolCallId: string2().max(256).optional(),
45617
+ parentToolCallId: string2().max(256).optional()
45618
+ };
45619
+ var toolHookBody = discriminatedUnion("phase", [
45620
+ object2({ phase: literal2("pre"), ...toolCallFields }),
45621
+ object2({
45622
+ phase: literal2("post"),
45623
+ ...toolCallFields,
45624
+ result: unknown(),
45625
+ isError: boolean().optional(),
45626
+ durationMs: number2().nonnegative()
45627
+ })
45628
+ ]);
45629
+ var toolHookDecision = discriminatedUnion("action", [
45630
+ object2({ action: literal2("continue") }),
45631
+ object2({ action: literal2("modify"), args: unknown() }),
45632
+ object2({ action: literal2("block"), reason: string2() })
45633
+ ]);
45634
+ var toolHookRoute = route({
45635
+ method: "post",
45636
+ path: "/api/tool-hooks",
45637
+ pattern: ["api", "tool-hooks"],
45638
+ summary: "Run extension tool hooks for a harness-native tool call",
45639
+ description: "A worker shim reports a harness built-in tool call (bash, read, write, edit). `phase: pre` " + "runs `pre.tool.call` with `callOrigin: native` and returns the decision. `phase: post` runs " + "`post.tool.call` observe-only and returns 202 at once. Only extensions whose manifest " + '`toolSources` includes `"native"` receive these calls. The server runs the secret scrubber ' + "over the body before any handler sees it, so handlers read `[REDACTED:<name>]` in place of " + "a secret. A `modify` whose args still carry that marker is rejected and the call continues " + "unchanged. Shims must also scrub worker-side before sending.",
45640
+ tags: ["Extensions"],
45641
+ auth: { apiKey: true, agentId: true },
45642
+ body: toolHookBody,
45643
+ maxBodyBytes: 2 * 1024 * 1024,
45644
+ rbac: { ungated: "self-scoped: an agent reports its own harness tool calls" },
45645
+ responses: {
45646
+ 200: { description: "Pre-call decision", schema: toolHookDecision },
45647
+ 202: {
45648
+ description: "Post-call event accepted",
45649
+ schema: object2({ accepted: literal2(true) })
45650
+ },
45651
+ 400: { description: "Invalid body or missing X-Agent-ID header" }
45652
+ }
45653
+ });
45654
+ function header3(req, name) {
45655
+ const raw = req.headers[name];
45656
+ return Array.isArray(raw) ? raw[0] : raw;
45657
+ }
45658
+ async function handleToolHooks(req, res, pathSegments, queryParams, myAgentId) {
45659
+ if (!toolHookRoute.match(req.method, pathSegments))
45660
+ return false;
45661
+ if (!myAgentId) {
45662
+ jsonError(res, "Missing X-Agent-ID header", 400);
45663
+ return true;
45664
+ }
45665
+ const parsed = await toolHookRoute.parse(req, res, pathSegments, queryParams);
45666
+ if (!parsed)
45667
+ return true;
45668
+ const body = scrubObject(parsed.body);
45669
+ const requestInfo = {
45670
+ sessionId: undefined,
45671
+ agentId: myAgentId,
45672
+ runtimeInstanceId: header3(req, "x-runtime-instance-id"),
45673
+ sourceTaskId: header3(req, "x-source-task-id"),
45674
+ contextKey: header3(req, "x-context-key"),
45675
+ callOrigin: "native",
45676
+ harness: body.harness
45677
+ };
45678
+ const event = {
45679
+ tool: body.tool,
45680
+ args: body.args,
45681
+ requestInfo,
45682
+ nativeTool: body.nativeTool,
45683
+ rawArgs: body.rawArgs,
45684
+ toolCallId: body.toolCallId,
45685
+ parentToolCallId: body.parentToolCallId
45686
+ };
45687
+ if (body.phase === "post") {
45688
+ toolHookRoute.respond(res, 202, { accepted: true });
45689
+ dispatchPost2("post.tool.call", {
45690
+ ...event,
45691
+ result: body.result,
45692
+ isError: body.isError,
45693
+ durationMs: body.durationMs
45694
+ });
45695
+ return true;
45696
+ }
45697
+ const result = await dispatchPre2("pre.tool.call", event, {
45698
+ validateModify: (data) => JSON.stringify(data.args ?? null).includes(REDACTION_MARKER) ? {
45699
+ success: false,
45700
+ error: new Error(`Modified arguments for native tool "${body.tool}" contain a redaction marker`)
45701
+ } : { success: true, data }
45702
+ });
45703
+ if (result.action === "block") {
45704
+ toolHookRoute.respond(res, 200, { action: "block", reason: result.reason });
45705
+ } else if (result.action === "modify") {
45706
+ toolHookRoute.respond(res, 200, { action: "modify", args: result.data.args });
45707
+ } else {
45708
+ toolHookRoute.respond(res, 200, { action: "continue" });
45709
+ }
45710
+ return true;
45711
+ }
45712
+
44848
45713
  // src/http/trackers/jira.ts
44849
45714
  init_zod();
44850
45715
  init_oauth();
@@ -46210,14 +47075,15 @@ var mergeUsersRoute = route({
46210
47075
  method: "post",
46211
47076
  path: "/api/users/{id}/merge",
46212
47077
  pattern: ["api", "users", null, "merge"],
46213
- summary: "Merge another user into this one — moves identities + email aliases, deletes source",
47078
+ summary: "Merge another user into this one: moves identities + email aliases, queues the rest",
47079
+ description: "Moves the source's identities and email aliases to the target, revokes the source's credentials and records a manual_merge event, all in one short transaction. The attribution rewrite across every table and the deletion of the source run as a background job; poll GET /api/users/merge-jobs/{jobId} until its status is done or failed. While the job runs, the source cannot authenticate and identity lookups resolve to the target.",
46214
47080
  tags: ["Users"],
46215
47081
  params: object2({ id: string2() }),
46216
47082
  body: object2({ sourceUserId: string2().min(1) }),
46217
47083
  responses: {
46218
- 200: {
46219
- description: "Merged user",
46220
- schema: object2({ user: ComposedUserSchema.nullable() })
47084
+ 202: {
47085
+ description: "The queued merge job",
47086
+ schema: object2({ job: UserMergeJobSchema })
46221
47087
  },
46222
47088
  400: { description: "Validation error (e.g. target == source)" },
46223
47089
  401: { description: "Unauthorized" },
@@ -46225,7 +47091,45 @@ var mergeUsersRoute = route({
46225
47091
  description: "Target holds an operator-granted role (auditor) and the caller is not the operator key"
46226
47092
  },
46227
47093
  404: { description: "Target or source user not found" },
46228
- 409: { description: "Source is the last active admin (last_admin)" }
47094
+ 409: {
47095
+ description: "Source is the last active admin (last_admin), or a merge job for the source or target is still running (merge_in_progress)"
47096
+ }
47097
+ },
47098
+ auth: { apiKey: true }
47099
+ });
47100
+ var listMergeJobsRoute = route({
47101
+ method: "get",
47102
+ path: "/api/users/merge-jobs",
47103
+ pattern: ["api", "users", "merge-jobs"],
47104
+ summary: "List background user merge jobs, newest first",
47105
+ tags: ["Users"],
47106
+ query: object2({
47107
+ status: UserMergeJobStatusSchema.optional(),
47108
+ limit: exports_coerce.number().int().min(1).max(200).optional()
47109
+ }),
47110
+ responses: {
47111
+ 200: {
47112
+ description: "Merge jobs",
47113
+ schema: object2({ jobs: array2(UserMergeJobSchema) })
47114
+ },
47115
+ 401: { description: "Unauthorized" }
47116
+ },
47117
+ auth: { apiKey: true }
47118
+ });
47119
+ var getMergeJobRoute = route({
47120
+ method: "get",
47121
+ path: "/api/users/merge-jobs/{jobId}",
47122
+ pattern: ["api", "users", "merge-jobs", null],
47123
+ summary: "A background user merge job (poll until status is done or failed)",
47124
+ tags: ["Users"],
47125
+ params: object2({ jobId: string2() }),
47126
+ responses: {
47127
+ 200: {
47128
+ description: "The merge job",
47129
+ schema: object2({ job: UserMergeJobSchema })
47130
+ },
47131
+ 401: { description: "Unauthorized" },
47132
+ 404: { description: "Job not found" }
46229
47133
  },
46230
47134
  auth: { apiKey: true }
46231
47135
  });
@@ -46847,6 +47751,29 @@ async function handleUsers(req, res, pathSegments, queryParams) {
46847
47751
  }
46848
47752
  return true;
46849
47753
  }
47754
+ if (listMergeJobsRoute.match(req.method, pathSegments)) {
47755
+ const parsed = await listMergeJobsRoute.parse(req, res, pathSegments, queryParams);
47756
+ if (!parsed)
47757
+ return true;
47758
+ const jobs = await listUserMergeJobs2({
47759
+ status: parsed.query.status,
47760
+ limit: parsed.query.limit
47761
+ });
47762
+ listMergeJobsRoute.respond(res, 200, { jobs });
47763
+ return true;
47764
+ }
47765
+ if (getMergeJobRoute.match(req.method, pathSegments)) {
47766
+ const parsed = await getMergeJobRoute.parse(req, res, pathSegments, queryParams);
47767
+ if (!parsed)
47768
+ return true;
47769
+ const job = await getUserMergeJob2(parsed.params.jobId);
47770
+ if (!job) {
47771
+ jsonError(res, "Merge job not found", 404);
47772
+ return true;
47773
+ }
47774
+ getMergeJobRoute.respond(res, 200, { job });
47775
+ return true;
47776
+ }
46850
47777
  if (mergeUsersRoute.match(req.method, pathSegments)) {
46851
47778
  const parsed = await mergeUsersRoute.parse(req, res, pathSegments, queryParams);
46852
47779
  if (!parsed)
@@ -46870,8 +47797,23 @@ async function handleUsers(req, res, pathSegments, queryParams) {
46870
47797
  jsonError(res, "Source user not found", 404);
46871
47798
  return true;
46872
47799
  }
47800
+ if (targetBefore.mergedIntoUserId || await findActiveUserMergeJob2(sourceId) || await findActiveUserMergeJob2(targetId)) {
47801
+ jsonError(res, "merge_in_progress", 409);
47802
+ return true;
47803
+ }
47804
+ if (sourceBefore.mergedIntoUserId) {
47805
+ const failed = await findFailedUserMergeJob2(sourceId, targetId);
47806
+ if (failed) {
47807
+ const requeued = await requeueUserMergeJob2(failed.id);
47808
+ if (requeued) {
47809
+ runUserMergeJobs2();
47810
+ mergeUsersRoute.respond(res, 202, { job: requeued });
47811
+ return true;
47812
+ }
47813
+ }
47814
+ }
46873
47815
  try {
46874
- const mergedUser = await getDbClient2().transaction(async () => {
47816
+ const job = await getDbClient2().transaction(async () => {
46875
47817
  await assertMayActOnOperatorGrantedTarget2(actor, targetId);
46876
47818
  for (const ident of sourceBefore.identities) {
46877
47819
  await unlinkIdentity(sourceId, ident.kind, ident.externalId, actor);
@@ -46900,7 +47842,8 @@ async function handleUsers(req, res, pathSegments, queryParams) {
46900
47842
  }
46901
47843
  }
46902
47844
  await assertNotLastAdmin2(sourceId);
46903
- await deleteUser2(sourceId, targetId);
47845
+ await revokeAllUserCredentials(sourceId, actor);
47846
+ await getDbClient2().run("UPDATE users SET mergedIntoUserId = ?, lastUpdatedAt = ? WHERE id = ?", [targetId, new Date().toISOString(), sourceId]);
46904
47847
  const targetAfter = await composeUser(targetId);
46905
47848
  await recordIdentityEvent(targetId, "manual_merge", actor, targetBefore, {
46906
47849
  ...targetAfter,
@@ -46910,9 +47853,17 @@ async function handleUsers(req, res, pathSegments, queryParams) {
46910
47853
  email: sourceBefore.email
46911
47854
  }
46912
47855
  });
46913
- return await composeUser(targetId);
47856
+ const queued = await createUserMergeJob2({
47857
+ sourceUserId: sourceId,
47858
+ targetUserId: targetId,
47859
+ createdBy: authUser(getRequestAuth(req))?.id ?? null
47860
+ });
47861
+ getDbClient2().afterCommit(() => {
47862
+ runUserMergeJobs2();
47863
+ });
47864
+ return queued;
46914
47865
  });
46915
- mergeUsersRoute.respond(res, 200, { user: mergedUser });
47866
+ mergeUsersRoute.respond(res, 202, { job });
46916
47867
  } catch (err) {
46917
47868
  if (respondOperatorGrantedRefusal(res, err))
46918
47869
  return true;
@@ -47241,7 +48192,7 @@ async function routeKapsoInbound(payload) {
47241
48192
  }
47242
48193
 
47243
48194
  // src/http/webhooks.ts
47244
- init_errors();
48195
+ init_errors2();
47245
48196
  init_constants3();
47246
48197
  init_github_host();
47247
48198
  init_secret_scrubber();
@@ -48579,6 +49530,14 @@ var webhookTriggerRoute = route({
48579
49530
  params: object2({ workflowId: string2() }),
48580
49531
  auth: { apiKey: false },
48581
49532
  responses: {
49533
+ 200: {
49534
+ description: "Delivery skipped: its event is not in the trigger's `events` allowlist. No run was created.",
49535
+ schema: object2({
49536
+ skipped: literal2(true),
49537
+ reason: literal2("event-not-allowed"),
49538
+ event: string2().nullable()
49539
+ })
49540
+ },
48582
49541
  201: { description: "Webhook processed", schema: object2({ runId: string2() }) },
48583
49542
  401: { description: "Invalid signature" },
48584
49543
  404: { description: "Workflow not found" }
@@ -48650,7 +49609,15 @@ async function handleWorkflows(req, res, pathSegments, queryParams, myAgentId) {
48650
49609
  }
48651
49610
  return true;
48652
49611
  }
48653
- webhookTriggerRoute.respond(res, 201, result);
49612
+ if (result.skipped) {
49613
+ webhookTriggerRoute.respond(res, 200, {
49614
+ skipped: true,
49615
+ reason: result.reason,
49616
+ event: result.event
49617
+ });
49618
+ } else {
49619
+ webhookTriggerRoute.respond(res, 201, { runId: result.runId });
49620
+ }
48654
49621
  return true;
48655
49622
  }
48656
49623
  if (getWorkflowVersionRoute.match(req.method, pathSegments)) {
@@ -49515,6 +50482,7 @@ var httpServer = createHttpServer(async (req, res) => {
49515
50482
  () => handleMetrics(req, res, pathSegments, queryParams, myAgentId),
49516
50483
  () => handleModelsCatalog(req, res, pathSegments, queryParams),
49517
50484
  () => handleModelProfiles(req, res, pathSegments, queryParams, myAgentId),
50485
+ () => handleModelGroups(req, res, pathSegments, queryParams, myAgentId),
49518
50486
  () => handleRepos(req, res, pathSegments, queryParams, myAgentId),
49519
50487
  () => handleSkills(req, res, pathSegments, queryParams, myAgentId),
49520
50488
  () => handleScriptConnections(req, res, pathSegments, queryParams, myAgentId),
@@ -49538,6 +50506,7 @@ var httpServer = createHttpServer(async (req, res) => {
49538
50506
  () => handleEvents(req, res, pathSegments, queryParams, myAgentId),
49539
50507
  () => handleRuntimePools(req, res, pathSegments, queryParams, myAgentId),
49540
50508
  () => handleExtensions(req, res, pathSegments, queryParams, myAgentId),
50509
+ () => handleToolHooks(req, res, pathSegments, queryParams, myAgentId),
49541
50510
  () => handleChecklist(req, res, pathSegments, queryParams, myAgentId),
49542
50511
  () => handleFavorites(req, res, pathSegments, queryParams, myAgentId),
49543
50512
  () => handleUserRoles(req, res, pathSegments, queryParams),
@@ -49556,7 +50525,7 @@ var httpServer = createHttpServer(async (req, res) => {
49556
50525
  () => handleMcpUser(req, res, transportsUser, sessionUsers, transportActivityUser)
49557
50526
  ];
49558
50527
  try {
49559
- if (await handleCore(req, res, myAgentId, apiKey))
50528
+ if (await handleCore2(req, res, myAgentId, apiKey))
49560
50529
  return;
49561
50530
  myAgentId = req.headers["x-agent-id"];
49562
50531
  for (const handler of handlers) {
@@ -49577,7 +50546,7 @@ var httpServer = createHttpServer(async (req, res) => {
49577
50546
  });
49578
50547
  });
49579
50548
  var detachRealtime = attachRealtimeTransport(httpServer);
49580
- var { attachControllerTransport } = await import("./controllers-connect-61re6k1n.js");
50549
+ var { attachControllerTransport } = await import("./controllers-connect-5v7qx04j.js");
49581
50550
  var detachControllers = attachControllerTransport(httpServer);
49582
50551
  var stopWorkerNudges = startWorkerNudgeListener();
49583
50552
  var taskAutoTitles = startTaskAutoTitleListener();
@@ -49608,7 +50577,7 @@ async function shutdown() {
49608
50577
  sessionsProcessed: getServerSessionsProcessed()
49609
50578
  });
49610
50579
  if (hasCapability("scheduling")) {
49611
- const { stopScheduler } = await import("./index-wjd56k1v.js");
50580
+ const { stopScheduler } = await import("./index-rkvaambe.js");
49612
50581
  stopScheduler();
49613
50582
  }
49614
50583
  stopHeartbeat2();
@@ -49620,7 +50589,7 @@ async function shutdown() {
49620
50589
  await stopSlackApp2();
49621
50590
  await stopChatSdk();
49622
50591
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
49623
- const { stopOAuthKeepalive } = await import("./keepalive-rk0j0jvh.js");
50592
+ const { stopOAuthKeepalive } = await import("./keepalive-7yxg8z4c.js");
49624
50593
  await stopOAuthKeepalive();
49625
50594
  }
49626
50595
  stopOAuthPendingGc();
@@ -49681,7 +50650,7 @@ startApiGcInterval();
49681
50650
  startEventLoopLagProbe();
49682
50651
  var startupConfigsInjected = [];
49683
50652
  try {
49684
- startupConfigsInjected = await loadGlobalConfigsIntoEnv(true);
50653
+ startupConfigsInjected = await loadGlobalConfigsIntoEnv2(true);
49685
50654
  } catch (err) {
49686
50655
  console.error("[startup] Failed to load global swarm configs before listen:", err);
49687
50656
  process.exitCode = 1;
@@ -49705,21 +50674,21 @@ try {
49705
50674
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
49706
50675
  }
49707
50676
  try {
49708
- const { ensurePricingSeeded } = await import("./boot-seeds-f99fjs5q.js");
50677
+ const { ensurePricingSeeded } = await import("./boot-seeds-nj9za0vk.js");
49709
50678
  ensurePricingSeeded();
49710
- const { startPricingRefreshLoop } = await import("./pricing-refresh-f5tkgmw2.js");
50679
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-fzxvk2zf.js");
49711
50680
  startPricingRefreshLoop();
49712
50681
  } catch (err) {
49713
50682
  console.error("[startup] Failed to seed pricing rows:", err);
49714
50683
  }
49715
50684
  try {
49716
- const { ensureModelProfilesSeeded } = await import("./boot-seeds-f99fjs5q.js");
50685
+ const { ensureModelProfilesSeeded } = await import("./boot-seeds-nj9za0vk.js");
49717
50686
  await ensureModelProfilesSeeded();
49718
50687
  } catch (err) {
49719
50688
  console.error("[startup] Failed to seed model profiles:", err);
49720
50689
  }
49721
50690
  try {
49722
- const { ensureRbacSeeded } = await import("./boot-seeds-f99fjs5q.js");
50691
+ const { ensureRbacSeeded } = await import("./boot-seeds-nj9za0vk.js");
49723
50692
  ensureRbacSeeded();
49724
50693
  } catch (err) {
49725
50694
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -49727,13 +50696,13 @@ try {
49727
50696
  throw err;
49728
50697
  }
49729
50698
  try {
49730
- const { runAllSeeders } = await import("./index-ftywhyr0.js");
50699
+ const { runAllSeeders } = await import("./index-ny60jcat.js");
49731
50700
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
49732
50701
  } catch (err) {
49733
50702
  console.error("[startup] Failed to seed built-in entities:", err);
49734
50703
  }
49735
50704
  try {
49736
- const { runImports } = await import("./index-tx9mc2ap.js");
50705
+ const { runImports } = await import("./index-p46tvwtx.js");
49737
50706
  await runImports();
49738
50707
  } catch (err) {
49739
50708
  console.error("[startup] File import failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
@@ -49784,7 +50753,7 @@ httpServer.listen(port, async () => {
49784
50753
  startChatSdk().catch((err) => {
49785
50754
  console.error("[chat-sdk] Failed to start, continuing without Chat SDK:", scrubSecrets(err instanceof Error ? err.message : String(err)));
49786
50755
  });
49787
- import("./agent-fs-provision-dmhnc38q.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
50756
+ import("./agent-fs-provision-tpj7sktd.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
49788
50757
  console.warn("[agent-fs] Failed to set the org swarm URL:", scrubSecrets(err instanceof Error ? err.message : String(err)));
49789
50758
  });
49790
50759
  startQueueStallAlarm();
@@ -49799,25 +50768,25 @@ httpServer.listen(port, async () => {
49799
50768
  await initWorkflows2();
49800
50769
  await startScriptRunSupervisor(getMcpBaseUrl());
49801
50770
  if (hasCapability("scheduling")) {
49802
- const { startScheduler } = await import("./index-wjd56k1v.js");
49803
- const { getExecutorRegistry } = await import("./index-9sy2bh6n.js");
50771
+ const { startScheduler } = await import("./index-rkvaambe.js");
50772
+ const { getExecutorRegistry } = await import("./index-xj1mq27m.js");
49804
50773
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
49805
50774
  startScheduler(getExecutorRegistry(), intervalMs, {
49806
50775
  runId: globalState.__runId
49807
50776
  });
49808
50777
  }
49809
50778
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
49810
- const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-8xcyd3mc.js");
50779
+ const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-48qzcqzj.js");
49811
50780
  startHeartbeat(parseHeartbeatIntervalMs(process.env.HEARTBEAT_INTERVAL_MS));
49812
50781
  }
49813
50782
  startPoolRouting();
49814
50783
  startRuntimeSupervisor();
49815
50784
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
49816
- const { startOAuthKeepalive } = await import("./keepalive-rk0j0jvh.js");
50785
+ const { startOAuthKeepalive } = await import("./keepalive-7yxg8z4c.js");
49817
50786
  startOAuthKeepalive();
49818
50787
  }
49819
50788
  if (!isEnvFlagEnabled("OAUTH_REFRESH_SWEEP_DISABLE", false)) {
49820
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-2k3g2q4w.js");
50789
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-70cavc3a.js");
49821
50790
  startOAuthRefreshSweep();
49822
50791
  }
49823
50792
  startOAuthPendingGc();
@@ -49827,19 +50796,22 @@ httpServer.listen(port, async () => {
49827
50796
  startSavingsRollup(savingsRollupSql);
49828
50797
  startHumanFreeDrain();
49829
50798
  startTaskSearchBackfill();
49830
- import("./embedding-space-bafjr5f7.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
49831
- setDeploymentEnvReader(getDeploymentEnvValue);
50799
+ import("./embedding-space-e48xchqa.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
50800
+ setDeploymentEnvReader(getDeploymentEnvValue2);
49832
50801
  return runEmbeddingMaintenance({ backfill: true });
49833
50802
  }).catch((err) => {
49834
50803
  console.error("[embedding-space] startup maintenance failed (non-fatal):", err);
49835
50804
  });
49836
- import("./boot-args-schema-0gqmkfbe.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
50805
+ import("./boot-args-schema-qxmd59sr.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
49837
50806
  console.error("[boot-args-schema] startup backfill failed (non-fatal):", err);
49838
50807
  });
49839
- import("./boot-scrub-sweep-ejd5dnrz.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
50808
+ import("./boot-scrub-sweep-25bxhnw4.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
49840
50809
  console.error("[boot-scrub-sweep] startup scrub failed (non-fatal):", err);
49841
50810
  });
49842
- import("./session-source-backfill-bd7spzjd.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
50811
+ import("./user-merge-jobs-bx6bf7db.js").then(({ resumeUserMergeJobs }) => resumeUserMergeJobs()).catch((err) => {
50812
+ console.error("[user-merge] startup resume failed (non-fatal):", err);
50813
+ });
50814
+ import("./session-source-backfill-82qe7fqq.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
49843
50815
  console.error("[session-source-backfill] startup run failed (non-fatal):", err);
49844
50816
  });
49845
50817
  }).on("error", (err) => {