@desplega.ai/agent-swarm 2.9.0 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/dist/acp-adapter-g909b5hw.js +16 -0
  2. package/dist/{acp-targets-swxq55dr.js → acp-targets-ny75x1qy.js} +7 -7
  3. package/dist/{actions-pb678g3e.js → actions-b9qgrmeq.js} +81 -21
  4. package/dist/{agent-fs-provision-dmhnc38q.js → agent-fs-provision-b5dhdsbd.js} +4 -4
  5. package/dist/{amp-adapter-3pa66q27.js → amp-adapter-vtax2c9s.js} +2 -2
  6. package/dist/{anthropic-messages-x2cp5fvf.js → anthropic-messages-r5xf5hqw.js} +10 -10
  7. package/dist/{app-17d12ev4.js → app-g2z15hax.js} +6 -3
  8. package/dist/{approval-notifications-h7vd9pmg.js → approval-notifications-yt13wp8r.js} +8 -5
  9. package/dist/{assistant-t7k39ree.js → assistant-2cgfxsgk.js} +23 -21
  10. package/dist/{boot-args-schema-0gqmkfbe.js → boot-args-schema-3gwy0f60.js} +1 -1
  11. package/dist/{boot-reembed-n6anc01d.js → boot-reembed-92g7s5zp.js} +1 -1
  12. package/dist/{boot-reembed-f064w382.js → boot-reembed-mywmyp4s.js} +1 -1
  13. package/dist/{boot-scrub-sweep-ejd5dnrz.js → boot-scrub-sweep-7dkdzqxx.js} +3 -3
  14. package/dist/{boot-seeds-f99fjs5q.js → boot-seeds-ce7rvgq1.js} +4 -4
  15. package/dist/{claude-adapter-gvznwxgc.js → claude-adapter-3m4q7735.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-c217draw.js} +3 -3
  18. package/dist/{claude-sdk-session-0t2teq6n.js → claude-sdk-session-7fbqm51z.js} +7 -7
  19. package/dist/{cli-9a2rtd77.js → cli-1jykg0py.js} +6 -4
  20. package/dist/{cli-5ntc4we6.js → cli-2czxfnvj.js} +235 -2003
  21. package/dist/{cli-dd37e0cm.js → cli-2dq9yv8p.js} +1 -1
  22. package/dist/{cli-c07v0qfa.js → cli-2xs8tsf7.js} +69 -66
  23. package/dist/{cli-7fx9jyfs.js → cli-2yjj3e31.js} +64 -10
  24. package/dist/{cli-4ghh072d.js → cli-32djehja.js} +36 -36
  25. package/dist/{cli-cw7mc1je.js → cli-3j873zxq.js} +3 -3
  26. package/dist/cli-43ms35q9.js +270 -0
  27. package/dist/cli-47hz21se.js +25584 -0
  28. package/dist/{cli-n515ex5z.js → cli-4ymxrwg5.js} +16 -16
  29. package/dist/{cli-5gygrr67.js → cli-67mwzr35.js} +1 -1
  30. package/dist/{cli-5kcmxwxv.js → cli-6945ywhr.js} +1 -1
  31. package/dist/{cli-812paz57.js → cli-6ehs4mta.js} +18 -2
  32. package/dist/{cli-95930z69.js → cli-6ym4jhzp.js} +2 -2
  33. package/dist/{cli-zg3z63x3.js → cli-7mv4h3sn.js} +1 -1
  34. package/dist/{cli-eg437b5p.js → cli-7sf9sb0w.js} +2 -1
  35. package/dist/{cli-nr46j5pw.js → cli-8zh9nrew.js} +1 -1
  36. package/dist/{cli-wr1h0k28.js → cli-9w8712tq.js} +617 -278
  37. package/dist/{cli-ssvdrk4y.js → cli-b6px1k1q.js} +1 -1
  38. package/dist/{cli-7831nhaw.js → cli-b91nz213.js} +3 -3
  39. package/dist/{cli-7cgf614g.js → cli-bg63qmsx.js} +2 -2
  40. package/dist/{cli-me4maa4j.js → cli-bkjdknnp.js} +9 -5
  41. package/dist/{cli-rts1qvb4.js → cli-bnqncekd.js} +2 -2
  42. package/dist/{cli-25nstr34.js → cli-br0924pw.js} +1 -1
  43. package/dist/{cli-ymct0ycy.js → cli-ctx0b85j.js} +5222 -4978
  44. package/dist/{cli-kqh27v2y.js → cli-dgs10ttj.js} +1 -1
  45. package/dist/{cli-kmvcm34h.js → cli-f3jyzq4g.js} +2 -2
  46. package/dist/cli-f8x9drqr.js +84 -0
  47. package/dist/{cli-8axx8vnw.js → cli-f9gz2vyj.js} +5 -5
  48. package/dist/{cli-vvgaz8t6.js → cli-fh97xn30.js} +2 -2
  49. package/dist/{cli-8x8y70av.js → cli-fkef327x.js} +2 -2
  50. package/dist/{cli-js8zrfyg.js → cli-gfy38pvt.js} +2 -2
  51. package/dist/{cli-kaa4bd7x.js → cli-h9yqfzx9.js} +7 -6
  52. package/dist/{cli-svc803vq.js → cli-j7svy295.js} +11 -11
  53. package/dist/{cli-nhq5js1b.js → cli-jaw5v1sy.js} +3 -3
  54. package/dist/{cli-w7dxb2fj.js → cli-jkw6ptfw.js} +6 -6
  55. package/dist/{cli-1tvdx9t5.js → cli-jm0hvmz2.js} +1 -1
  56. package/dist/{cli-e9973bf0.js → cli-jwampxxq.js} +2 -2
  57. package/dist/{cli-dx439zpg.js → cli-kpgcm7xy.js} +13 -1
  58. package/dist/{cli-pz1c00aa.js → cli-kxx4k2jw.js} +2 -2
  59. package/dist/{cli-aa8s22gn.js → cli-m7c2380k.js} +191 -182
  60. package/dist/{cli-2kg31ted.js → cli-m7zvgt57.js} +11 -11
  61. package/dist/{cli-57pvhnyt.js → cli-mhapr559.js} +1 -1
  62. package/dist/{cli-gddgcnav.js → cli-mjw0yf82.js} +1 -1
  63. package/dist/{cli-h474mvp5.js → cli-mkwkwq81.js} +7 -4
  64. package/dist/{cli-jd3kxppb.js → cli-mw620q3n.js} +1 -1
  65. package/dist/{cli-spzkdgtg.js → cli-n3qe7tyr.js} +172 -168
  66. package/dist/{cli-3zxdz9r7.js → cli-nafvvsp8.js} +3 -3
  67. package/dist/{cli-fnh4b12r.js → cli-nbt14he0.js} +6 -6
  68. package/dist/{cli-7akn6ze9.js → cli-nh7x3133.js} +7 -28
  69. package/dist/{cli-faf46gdq.js → cli-p4kckx1z.js} +10 -10
  70. package/dist/{cli-k7pt28ad.js → cli-pb2ay3sh.js} +2 -2
  71. package/dist/{cli-pn1v1pb0.js → cli-psffsanb.js} +3 -2
  72. package/dist/{cli-2tnbc3gw.js → cli-pyjn0qhk.js} +2257 -61
  73. package/dist/{cli-fgphc007.js → cli-rq5rpv6k.js} +1 -1
  74. package/dist/{cli-vw5x18yj.js → cli-sn650d7x.js} +9 -9
  75. package/dist/{cli-mc1fx4xd.js → cli-td9tb872.js} +10 -10
  76. package/dist/{cli-6dp0jkfj.js → cli-tvc4jag9.js} +3 -3
  77. package/dist/{cli-a9hfzg2r.js → cli-ty3gha1p.js} +6 -6
  78. package/dist/{cli-pwsax0vp.js → cli-v57d7fmm.js} +1 -1
  79. package/dist/{cli-nmcpzbty.js → cli-vt89089n.js} +4 -4
  80. package/dist/{cli-sn4pc4qx.js → cli-vyff45ve.js} +2 -2
  81. package/dist/{cli-m1fbz2wj.js → cli-w4n323t3.js} +175 -16
  82. package/dist/{cli-g3zzby8t.js → cli-wn13hhdt.js} +5 -5
  83. package/dist/{cli-q8cfh1t9.js → cli-xag7btpe.js} +1 -1
  84. package/dist/{cli-c5cspahx.js → cli-y2ewxhth.js} +38 -13
  85. package/dist/{cli-k09cxm6m.js → cli-ysvspf5e.js} +2 -2
  86. package/dist/{cli-eepnpee7.js → cli-zh0e5x7p.js} +4 -4
  87. package/dist/{cli-bk9v1xrv.js → cli-zr6qy15y.js} +11 -11
  88. package/dist/cli.js +21 -20
  89. package/dist/{codex-adapter-44yq2fkn.js → codex-adapter-n656pvb8.js} +6 -6
  90. package/dist/{codex-hook-h1zb7cfk.js → codex-hook-59atdwd8.js} +1 -1
  91. package/dist/{codex-login-cdyrr5y1.js → codex-login-a239g1ah.js} +1 -1
  92. package/dist/{codex-session-runner-zbh26gbw.js → codex-session-runner-p0fbv5y9.js} +6 -6
  93. package/dist/{commands-54f02v5b.js → commands-gwea8z5p.js} +3 -3
  94. package/dist/{controller-9gpwcdek.js → controller-t67c3grh.js} +6 -3
  95. package/dist/{controllers-connect-61re6k1n.js → controllers-connect-ks155r0h.js} +22 -20
  96. package/dist/{cursor-adapter-7e4g81vd.js → cursor-adapter-ygwrtmkv.js} +1 -1
  97. package/dist/{db-dg2gc7fd.js → db-kpmx06s9.js} +8 -2
  98. package/dist/{db-wnh0qjy1.js → db-rb2xqdb1.js} +3 -3
  99. package/dist/{dispatcher-jrm24r43.js → dispatcher-31sm0ej2.js} +20 -18
  100. package/dist/{docker-9aq30pp2.js → docker-09tkkg0n.js} +42 -3
  101. package/dist/{dsh-adapter-1yqk267c.js → dsh-adapter-qyxh0w31.js} +1 -1
  102. package/dist/{easter-egg-3d-r4h9cs9m.js → easter-egg-3d-00wjscn6.js} +1 -1
  103. package/dist/{embedding-space-bafjr5f7.js → embedding-space-qhw4g68n.js} +6 -6
  104. package/dist/{embeddings-7xmgqe0e.js → embeddings-zdv9ke6x.js} +1 -1
  105. package/dist/{execute-d6jg5ns0.js → execute-zna8wwr7.js} +1 -1
  106. package/dist/{external-channel-frq1xvq2.js → external-channel-1ac6t56s.js} +2 -2
  107. package/dist/fx-adapter-sk7n0fzc.js +19 -0
  108. package/dist/{google-generative-ai-hh7strj3.js → google-generative-ai-maq6c9bf.js} +1 -1
  109. package/dist/{google-vertex-fy5bw2pm.js → google-vertex-2jgsw2nb.js} +1 -1
  110. package/dist/grok-adapter-sjbcm5ew.js +19 -0
  111. package/dist/handlers-yzy0c87x.js +35 -0
  112. package/dist/{heartbeat-6bpa611t.js → heartbeat-2f6z4kdx.js} +23 -21
  113. package/dist/{hook-w12k146y.js → hook-8y0gvtp1.js} +6 -6
  114. package/dist/{hook-hvm5nf46.js → hook-w1skzaqc.js} +5 -5
  115. package/dist/{http-43tthdvs.js → http-wghxvpef.js} +714 -145
  116. package/dist/{index-1f0vypbg.js → index-0h6qd4p1.js} +34 -24
  117. package/dist/index-25pvya7q.js +40 -0
  118. package/dist/index-2t4859r5.js +35 -0
  119. package/dist/{index-4b1q8kan.js → index-4k7m5dgj.js} +629 -354
  120. package/dist/index-620y7jzq.js +15 -0
  121. package/dist/{index-cret47a5.js → index-8p0j4h4j.js} +506 -43
  122. package/dist/{index-mhq4sh5w.js → index-8zn8nxn5.js} +1 -1
  123. package/dist/{index-m5gx1xd6.js → index-9myfj74s.js} +40 -40
  124. package/dist/{index-ftywhyr0.js → index-9zkchs9t.js} +221 -65
  125. package/dist/{index-bs7gw5fd.js → index-b5wgnm78.js} +44 -44
  126. package/dist/index-cxca2t8y.js +36 -0
  127. package/dist/{index-585gyczt.js → index-pe3d8jfy.js} +3 -3
  128. package/dist/{index-tx9mc2ap.js → index-rv89fvzf.js} +24 -22
  129. package/dist/{index-fn054vsf.js → index-s71ez27v.js} +1 -1
  130. package/dist/{keepalive-rk0j0jvh.js → keepalive-sh02349h.js} +3 -3
  131. package/dist/lead-gk4h5eg7.js +74 -0
  132. package/dist/{maintenance-g6z6kaxw.js → maintenance-yj0dcjja.js} +1 -1
  133. package/dist/{node-jftbyawr.js → node-dqm4xgxw.js} +1 -1
  134. package/dist/{oauth-refresh-sweep-2k3g2q4w.js → oauth-refresh-sweep-d9xedk66.js} +2 -2
  135. package/dist/{onboard-6fdbvh3v.js → onboard-dpgjn03r.js} +2 -2
  136. package/dist/{opencode-adapter-fdbsvts7.js → opencode-adapter-2d31cpjc.js} +6 -6
  137. package/dist/{otel-impl-rvwtc09q.js → otel-impl-1skarpfq.js} +1 -1
  138. package/dist/{pending-sqkrb836.js → pending-bfmxtx0g.js} +21 -19
  139. package/dist/{pi-mono-adapter-asqayqcg.js → pi-mono-adapter-gvppnasy.js} +40 -13
  140. package/dist/{pricing-refresh-f5tkgmw2.js → pricing-refresh-c6b325mk.js} +2 -2
  141. package/dist/{rbac-roles-06s555fa.js → rbac-roles-h80qbdbs.js} +3 -3
  142. package/dist/{rbac-roles-szxsg8t1.js → rbac-roles-zfcx68tx.js} +2 -2
  143. package/dist/{render-v2-103p266q.js → render-v2-nx20t3rb.js} +6 -3
  144. package/dist/{resume-v7kjewt9.js → resume-5ep8agan.js} +10 -7
  145. package/dist/{runtime-f1gmk0b7.js → runtime-r3pj4mce.js} +1 -1
  146. package/dist/{session-access-6shev8ts.js → session-access-n7p3m15b.js} +4 -4
  147. package/dist/{session-source-backfill-bd7spzjd.js → session-source-backfill-v8mt0zwn.js} +3 -3
  148. package/dist/{setup-kmxmztdb.js → setup-z1psaqhe.js} +1 -1
  149. package/dist/thread-buffer-a1re2r9r.js +38 -0
  150. package/dist/{virtual-modules-57eje5wy.js → virtual-modules-rrbjdpxn.js} +3 -3
  151. package/dist/{work-objects-zr47ygmf.js → work-objects-4aghh73z.js} +29 -23
  152. package/dist/worker-3dyyb8ev.js +74 -0
  153. package/dist/{worker-follow-up-grrr3fda.js → worker-follow-up-166zmex1.js} +20 -18
  154. package/openapi.json +1387 -13
  155. package/package.json +7 -6
  156. package/src/apps/catalog.generated.json +43 -3
  157. package/src/apps/page-validator.ts +27 -0
  158. package/src/be/db/model-profiles.ts +4 -1
  159. package/src/be/db/session-costs.ts +219 -0
  160. package/src/be/db/session-log-reasoning.ts +36 -0
  161. package/src/be/db/tasks/read.ts +7 -3
  162. package/src/be/db/tasks/write.ts +33 -1
  163. package/src/be/db.ts +200 -304
  164. package/src/be/key-window-usage.ts +385 -0
  165. package/src/be/migrations/303_task_ui_specs.sql +28 -0
  166. package/src/be/migrations/306_provider_account_telemetry.sql +1 -0
  167. package/src/be/migrations/307_session_cost_credential_attribution.sql +23 -0
  168. package/src/be/migrations/310_session_logs_reasoning.sql +12 -0
  169. package/src/be/runtime-pools/db.ts +3 -0
  170. package/src/be/seed-scripts/catalog/boot-triage.inline.ts +1 -0
  171. package/src/be/seed-scripts/catalog/boot-triage.ts +1 -0
  172. package/src/be/seed-scripts/catalog/wait-for-task.ts +5 -1
  173. package/src/be/seed-skills/index.ts +3 -0
  174. package/src/be/swarm-config-guard.ts +24 -1
  175. package/src/be/task-ui-spec.ts +158 -0
  176. package/src/commands/controller.ts +3 -0
  177. package/src/commands/credential-outcome-report.ts +13 -3
  178. package/src/commands/rate-limit-outcome.ts +6 -0
  179. package/src/commands/runner.ts +34 -53
  180. package/src/extensions/catalog.generated.json +3 -3
  181. package/src/extensions/contract-types.generated.ts +1 -1
  182. package/src/http/api-keys.ts +258 -30
  183. package/src/http/session-data.ts +74 -23
  184. package/src/http/sessions.ts +6 -2
  185. package/src/http/tasks.ts +105 -5
  186. package/src/integrations/chat-sdk/relay.ts +87 -0
  187. package/src/jira/outbound.ts +5 -3
  188. package/src/linear/outbound.ts +5 -1
  189. package/src/prompts/base-prompt.ts +8 -0
  190. package/src/prompts/session-templates.ts +19 -2
  191. package/src/providers/acp-targets.ts +1 -1
  192. package/src/providers/amp-adapter.ts +1 -1
  193. package/src/providers/claude-adapter.ts +27 -4
  194. package/src/providers/claude-flag-settings.ts +39 -1
  195. package/src/providers/codex-adapter.ts +85 -3
  196. package/src/providers/codex-app-server.ts +9 -5
  197. package/src/providers/codex-oauth/auth-json.ts +1 -0
  198. package/src/providers/pi-mono-adapter.ts +35 -2
  199. package/src/providers/pricing-sources.md +32 -0
  200. package/src/providers/types.ts +11 -0
  201. package/src/runtime-providers/docker.ts +65 -1
  202. package/src/scheduler/deferred-task-waits.ts +18 -5
  203. package/src/scripts-runtime/types/swarm-extension.d.ts +8 -8
  204. package/src/slack/actions.ts +56 -0
  205. package/src/slack/app.ts +22 -15
  206. package/src/slack/inbound-files.ts +2 -0
  207. package/src/slack/render-v2.ts +107 -23
  208. package/src/slack/responses.ts +3 -2
  209. package/src/slack/work-objects.ts +4 -1
  210. package/src/tasks/errors.ts +5 -0
  211. package/src/tests/acp-adapter.test.ts +4 -6
  212. package/src/tests/api-key-tracking.test.ts +0 -72
  213. package/src/tests/api-keys-status-model-limits.test.ts +93 -1
  214. package/src/tests/api-keys-validation.test.ts +42 -0
  215. package/src/tests/approval-card-resolution.test.ts +7 -1
  216. package/src/tests/approval-requests-notifications.test.ts +11 -1
  217. package/src/tests/apps-catalog-page-frame.test.ts +49 -0
  218. package/src/tests/apps-session-thread.test.ts +79 -0
  219. package/src/tests/base-prompt.test.ts +111 -5
  220. package/src/tests/chat-sdk-relay.test.ts +149 -1
  221. package/src/tests/claude-adapter-binary.test.ts +67 -6
  222. package/src/tests/claude-flag-settings.test.ts +29 -0
  223. package/src/tests/claude-sdk-lifecycle.test.ts +5 -0
  224. package/src/tests/codex-adapter.test.ts +340 -2
  225. package/src/tests/codex-app-server.test.ts +16 -0
  226. package/src/tests/codex-oauth.test.ts +3 -1
  227. package/src/tests/codex-rate-limits.test.ts +384 -0
  228. package/src/tests/credential-outcome-report.test.ts +20 -0
  229. package/src/tests/db-task-read-contract.test.ts +3 -0
  230. package/src/tests/db-task-write-contract.test.ts +4 -0
  231. package/src/tests/deferred-task-wake.test.ts +63 -1
  232. package/src/tests/docker-isolation-config-guard.test.ts +29 -0
  233. package/src/tests/docs-index-footprint.test.js +11 -3
  234. package/src/tests/e2e-visuals-comment.test.ts +82 -0
  235. package/src/tests/e2e-visuals-verify-pr.test.ts +138 -0
  236. package/src/tests/extensions-example-sql-admin-only.test.ts +7 -4
  237. package/src/tests/fixtures/ui-spec-slack/deploys.json +121 -0
  238. package/src/tests/fixtures/ui-spec-slack/incident.json +183 -0
  239. package/src/tests/fixtures/ui-spec-slack/three-charts-stale.json +196 -0
  240. package/src/tests/fixtures/ui-spec-slack/video-rejected-by-slack.json +183 -0
  241. package/src/tests/fixtures/ui-spec-slack/video.json +446 -0
  242. package/src/tests/gitleaks-download-retry.test.ts +85 -0
  243. package/src/tests/human-thread-routing.test.ts +187 -0
  244. package/src/tests/jira-outbound-sync.test.ts +33 -1
  245. package/src/tests/key-window-usage.test.ts +831 -0
  246. package/src/tests/linear-outbound-sync.test.ts +30 -1
  247. package/src/tests/pi-mono-adapter.test.ts +79 -0
  248. package/src/tests/preload-env.test.ts +2 -0
  249. package/src/tests/preload.ts +3 -1
  250. package/src/tests/prompt-template-session.test.ts +4 -3
  251. package/src/tests/provider-quota-persistence.test.ts +362 -0
  252. package/src/tests/rate-limit-event.test.ts +22 -0
  253. package/src/tests/reasoning-events.test.ts +164 -0
  254. package/src/tests/routing-affinity-inventory.test.ts +22 -0
  255. package/src/tests/runtime-providers-docker.test.ts +91 -0
  256. package/src/tests/script-connections.test.ts +5 -0
  257. package/src/tests/secret-canary-sweep.test.ts +41 -5
  258. package/src/tests/seed-scripts.test.ts +23 -0
  259. package/src/tests/session-cost-attribution.test.ts +748 -0
  260. package/src/tests/session-costs.test.ts +14 -15
  261. package/src/tests/session-logs.test.ts +83 -0
  262. package/src/tests/sessions-detail-batch.test.ts +7 -0
  263. package/src/tests/slack-render-v2.test.ts +357 -0
  264. package/src/tests/slack-start-reload-race.test.ts +67 -0
  265. package/src/tests/subscription-plans.test.ts +20 -1
  266. package/src/tests/task-ui-action-route.test.ts +191 -0
  267. package/src/tests/task-ui-actions.test.ts +195 -0
  268. package/src/tests/task-ui-spec-fallback.test.ts +65 -0
  269. package/src/tests/task-ui-spec.test.ts +368 -0
  270. package/src/tests/workflow-agent-task-retry.test.ts +34 -1
  271. package/src/tools/defer-task.ts +1 -1
  272. package/src/tools/store-progress.ts +69 -3
  273. package/src/types.ts +7 -2
  274. package/src/ui-spec/actions.ts +86 -0
  275. package/src/ui-spec/fallback.ts +19 -0
  276. package/src/ui-spec/slack.ts +17 -0
  277. package/src/ui-spec/validate.ts +169 -0
  278. package/src/utils/codex-rate-limits.ts +159 -0
  279. package/src/utils/credentials.ts +2 -0
  280. package/src/utils/error-tracker.ts +19 -0
  281. package/src/utils/provider-account-telemetry.ts +331 -0
  282. package/src/utils/reasoning-events.ts +107 -0
  283. package/src/utils/subscription-plans.ts +11 -59
  284. package/src/utils/task-ui-spec.ts +67 -0
  285. package/src/workflows/task-step-routing.ts +8 -3
  286. package/templates/extensions/sql-admin-only/README.md +2 -1
  287. package/templates/extensions/sql-admin-only/hooks.ts +7 -3
  288. package/templates/extensions/sql-admin-only/manifest.json +1 -1
  289. package/templates/skills/apps/SKILL.md +32 -5
  290. package/templates/skills/apps/content.md +32 -5
  291. package/templates/skills/ui-spec/config.json +14 -0
  292. package/templates/skills/ui-spec/content.md +127 -0
  293. package/dist/acp-adapter-jqn86aam.js +0 -16
  294. package/dist/cli-srtkr1h2.js +0 -12078
  295. package/dist/fx-adapter-0zrkfbkd.js +0 -19
  296. package/dist/grok-adapter-3db1c538.js +0 -19
  297. package/dist/handlers-k22n8mnn.js +0 -33
  298. package/dist/index-8xcyd3mc.js +0 -33
  299. package/dist/index-9sy2bh6n.js +0 -38
  300. package/dist/index-b24j7t2m.js +0 -12797
  301. package/dist/index-wjd56k1v.js +0 -34
  302. package/dist/lead-atxf3q6e.js +0 -72
  303. package/dist/thread-buffer-4yz236d0.js +0 -36
  304. package/dist/worker-p4hbtcy3.js +0 -72
  305. package/dist/{cli-j49yqpvh.js → cli-7evph51z.js} +3 -3
@@ -2,6 +2,34 @@ import {
2
2
  bedrockProviderModule
3
3
  } from "./cli-g0vv9dg4.js";
4
4
  import {
5
+ auditAssetKeys,
6
+ init_asset_key_audit,
7
+ CredentialBindingSchema,
8
+ placeholderForConfigKey,
9
+ isPrivateAddress,
10
+ assertUrlSafe,
11
+ init_egress_guard,
12
+ init_credential_broker,
13
+ encryptSecret,
14
+ decryptSecret,
15
+ getEncryptionKey,
16
+ init_crypto,
17
+ withLoopPath,
18
+ startEventLoopLagProbe,
19
+ stopEventLoopLagProbe,
20
+ init_event_loop_lag,
21
+ DbTransactionDeadlineError,
22
+ init_db_client,
23
+ getPromptTemplateDefaultDrift,
24
+ init_default_drift,
25
+ init_templates2,
26
+ init_templates3,
27
+ getDb2,
28
+ closeDb2,
29
+ getDbClient2,
30
+ init_runtime2,
31
+ SessionCostConflictError2,
32
+ insertSessionCost2,
5
33
  chatThreadOfContextKey,
6
34
  agentContextKey,
7
35
  pageContextKey,
@@ -10,6 +38,9 @@ import {
10
38
  SOURCE_GROUPS_READ_ONLY,
11
39
  sourceMoveError,
12
40
  init_source_key,
41
+ TaskCreationBlockedError,
42
+ TaskRoutingAuthorizationError,
43
+ init_errors2,
13
44
  init_catalog,
14
45
  catalog_default,
15
46
  COMPANY_TEAM_SIZES,
@@ -41,32 +72,6 @@ import {
41
72
  telemetry,
42
73
  emitIntegrationConnected,
43
74
  init_telemetry,
44
- auditAssetKeys,
45
- init_asset_key_audit,
46
- CredentialBindingSchema,
47
- placeholderForConfigKey,
48
- isPrivateAddress,
49
- assertUrlSafe,
50
- init_egress_guard,
51
- init_credential_broker,
52
- encryptSecret,
53
- decryptSecret,
54
- getEncryptionKey,
55
- init_crypto,
56
- withLoopPath,
57
- startEventLoopLagProbe,
58
- stopEventLoopLagProbe,
59
- init_event_loop_lag,
60
- DbTransactionDeadlineError,
61
- init_db_client,
62
- getPromptTemplateDefaultDrift,
63
- init_default_drift,
64
- init_templates2,
65
- init_templates3,
66
- getDb2,
67
- closeDb2,
68
- getDbClient2,
69
- init_runtime2,
70
75
  isRbacEnabled,
71
76
  decideToolAdmission,
72
77
  LEGACY_RULES,
@@ -358,7 +363,6 @@ import {
358
363
  claimMentions2,
359
364
  createSessionLogs2,
360
365
  getSessionLogsByTaskId2,
361
- createSessionCost2,
362
366
  getSessionCostsByTaskId2,
363
367
  getSessionCostsByAgentId2,
364
368
  getAllSessionCosts2,
@@ -534,7 +538,7 @@ import {
534
538
  countScriptRunJournalSteps2,
535
539
  countScriptRunJournalAgentTaskSteps2,
536
540
  init_db4
537
- } from "./cli-ymct0ycy.js";
541
+ } from "./cli-ctx0b85j.js";
538
542
  import {
539
543
  PRIMARY_ROLE_NAMES2,
540
544
  OperatorGrantedTargetError2,
@@ -548,17 +552,19 @@ import {
548
552
  assertNotLastAdmin2,
549
553
  setUserRoles2,
550
554
  init_rbac_roles
551
- } from "./cli-k7pt28ad.js";
552
- import"./cli-7831nhaw.js";
555
+ } from "./cli-pb2ay3sh.js";
556
+ import"./cli-b91nz213.js";
553
557
  import {
554
558
  requestModelCatalogRefresh2,
555
559
  init_pricing_refresh
556
- } from "./cli-kqh27v2y.js";
560
+ } from "./cli-dgs10ttj.js";
557
561
  import {
558
562
  workflowEventBus2,
559
563
  init_event_bus
560
564
  } from "./cli-q2d3e1k1.js";
561
- import"./cli-q8cfh1t9.js";
565
+ import"./cli-xag7btpe.js";
566
+ import"./cli-9w8712tq.js";
567
+ import"./cli-47hz21se.js";
562
568
  import {
563
569
  require_dist4,
564
570
  getSlackConnectionState,
@@ -579,6 +585,10 @@ import {
579
585
  getTaskCitations,
580
586
  getTaskCitationsForTasks,
581
587
  init_task_citations2,
588
+ TaskUiSpecSchema,
589
+ getTaskUiSpec,
590
+ getTaskUiSpecsForTasks,
591
+ init_task_ui_spec,
582
592
  initialize,
583
593
  ensure,
584
594
  init_business_use,
@@ -590,7 +600,7 @@ import {
590
600
  startSlackApp2,
591
601
  stopSlackApp2,
592
602
  init_app3
593
- } from "./cli-2tnbc3gw.js";
603
+ } from "./cli-pyjn0qhk.js";
594
604
  import {
595
605
  AGENT_MAX_TASKS_CONFIG_KEY,
596
606
  reconcileAgentMaxTasksPolicy,
@@ -618,12 +628,12 @@ import {
618
628
  dispatchApprovalNotifications2,
619
629
  createApprovalFollowUpTask2,
620
630
  init_approval_notifications
621
- } from "./cli-w7dxb2fj.js";
631
+ } from "./cli-jkw6ptfw.js";
622
632
  import {
623
633
  retryFailedRun2,
624
634
  cancelWorkflowRun2,
625
635
  init_resume
626
- } from "./cli-9a2rtd77.js";
636
+ } from "./cli-1jykg0py.js";
627
637
  import {
628
638
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
629
639
  SUPPORTED_PROTOCOL_VERSIONS,
@@ -644,8 +654,6 @@ import {
644
654
  init_triggers,
645
655
  snapshotAndUpdateWorkflow,
646
656
  init_version,
647
- TaskCreationBlockedError,
648
- init_errors,
649
657
  RawLlmConfigSchema,
650
658
  RawLlmOutputSchema,
651
659
  executeRawLlm,
@@ -1055,7 +1063,7 @@ import {
1055
1063
  getEnabledCapabilities,
1056
1064
  createServer,
1057
1065
  init_server
1058
- } from "./cli-5ntc4we6.js";
1066
+ } from "./cli-2czxfnvj.js";
1059
1067
  import {
1060
1068
  FilesError,
1061
1069
  normalizeFilesError,
@@ -1066,7 +1074,6 @@ import {
1066
1074
  getFileStorageProvider2,
1067
1075
  init_registry2
1068
1076
  } from "./cli-7cp6aa1q.js";
1069
- import"./cli-wr1h0k28.js";
1070
1077
  import {
1071
1078
  RuntimePoolError2,
1072
1079
  mintControllerToken,
@@ -1088,7 +1095,7 @@ import {
1088
1095
  resolvePoolDelivery2,
1089
1096
  createPoolAgent2,
1090
1097
  init_db2
1091
- } from "./cli-h474mvp5.js";
1098
+ } from "./cli-mkwkwq81.js";
1092
1099
  import {
1093
1100
  duplicateGuardedQueryKey,
1094
1101
  warnIfCorsAllowsAnyOrigin,
@@ -1145,7 +1152,7 @@ import {
1145
1152
  describeRequestRoute,
1146
1153
  route,
1147
1154
  init_route_def
1148
- } from "./cli-fnh4b12r.js";
1155
+ } from "./cli-nbt14he0.js";
1149
1156
  import {
1150
1157
  startPoolRouting,
1151
1158
  stopPoolRouting,
@@ -1158,17 +1165,17 @@ import {
1158
1165
  checkHeartbeatChecklist2,
1159
1166
  runHeartbeatSweep2,
1160
1167
  stopHeartbeat2
1161
- } from "./cli-2kg31ted.js";
1162
- import"./cli-57pvhnyt.js";
1168
+ } from "./cli-m7zvgt57.js";
1169
+ import"./cli-mhapr559.js";
1163
1170
  import {
1164
1171
  runtimeSupervisorStatus,
1165
1172
  startRuntimeSupervisor,
1166
1173
  stopRuntimeSupervisor
1167
- } from "./cli-vw5x18yj.js";
1174
+ } from "./cli-sn650d7x.js";
1168
1175
  import {
1169
1176
  TASK_TITLE_TIMEOUT_MS,
1170
1177
  generateTaskTitle
1171
- } from "./cli-js8zrfyg.js";
1178
+ } from "./cli-gfy38pvt.js";
1172
1179
  import"./cli-ns59dc6r.js";
1173
1180
  import {
1174
1181
  ACP_TARGET_IDS
@@ -1179,7 +1186,7 @@ import {
1179
1186
  } from "./cli-5gpqgs8b.js";
1180
1187
  import {
1181
1188
  MAX_RATE_LIMIT_RESET_MS
1182
- } from "./cli-dx439zpg.js";
1189
+ } from "./cli-kpgcm7xy.js";
1183
1190
  import {
1184
1191
  isLeadChannelMonitoringEnabled,
1185
1192
  ORG_IDENTITY_KEYS,
@@ -1189,7 +1196,7 @@ import {
1189
1196
  isUnknownModelError,
1190
1197
  checkProviderPoolKey,
1191
1198
  writeSkillsToFilesystem
1192
- } from "./cli-8axx8vnw.js";
1199
+ } from "./cli-f9gz2vyj.js";
1193
1200
  import {
1194
1201
  AgentFsRequestError2,
1195
1202
  resolveAgentFsSharedContext2,
@@ -1199,7 +1206,7 @@ import {
1199
1206
  roleRank2,
1200
1207
  agentFsRequest2,
1201
1208
  resolveApiUrl2
1202
- } from "./cli-vvgaz8t6.js";
1209
+ } from "./cli-fh97xn30.js";
1203
1210
  import {
1204
1211
  Anthropic
1205
1212
  } from "./cli-t9ga4qmb.js";
@@ -1210,6 +1217,10 @@ import {
1210
1217
  resolveClaudeTransport,
1211
1218
  isClaudeBridgeEffective
1212
1219
  } from "./cli-9fzgd3hg.js";
1220
+ import {
1221
+ runTaskUiAction,
1222
+ init_actions
1223
+ } from "./cli-f8x9drqr.js";
1213
1224
  import {
1214
1225
  RATING_MODEL_MAX_LENGTH,
1215
1226
  REFERENCES_SOURCE_MAX_LENGTH,
@@ -1304,7 +1315,7 @@ import {
1304
1315
  init_typecheck,
1305
1316
  parseSkillContent,
1306
1317
  init_skill_parser
1307
- } from "./cli-7fx9jyfs.js";
1318
+ } from "./cli-2yjj3e31.js";
1308
1319
  import {
1309
1320
  signalProcessGroup,
1310
1321
  detachedProcessGroup,
@@ -1321,8 +1332,8 @@ import {
1321
1332
  forceRefreshAuthorizationOrThrow,
1322
1333
  forceRefreshTokenOrThrow,
1323
1334
  init_ensure_token
1324
- } from "./cli-1tvdx9t5.js";
1325
- import"./cli-25nstr34.js";
1335
+ } from "./cli-jm0hvmz2.js";
1336
+ import"./cli-br0924pw.js";
1326
1337
  import {
1327
1338
  automationIntegrationFixUrl,
1328
1339
  preflightAutomation,
@@ -1341,7 +1352,7 @@ import {
1341
1352
  definitionNodeIds,
1342
1353
  validateDefinition,
1343
1354
  init_definition2
1344
- } from "./cli-svc803vq.js";
1355
+ } from "./cli-j7svy295.js";
1345
1356
  import {
1346
1357
  _fetchHolder,
1347
1358
  CLIENT_ID,
@@ -1357,7 +1368,7 @@ import {
1357
1368
  loadAllCodexOAuthSlots,
1358
1369
  getValidCodexOAuth,
1359
1370
  init_storage
1360
- } from "./cli-eg437b5p.js";
1371
+ } from "./cli-7sf9sb0w.js";
1361
1372
  import {
1362
1373
  isMultiRuntimeEnabled,
1363
1374
  init_multi_runtime2
@@ -1369,10 +1380,11 @@ import {
1369
1380
  import {
1370
1381
  createRuntimeProvider,
1371
1382
  init_runtime_providers
1372
- } from "./cli-5kcmxwxv.js";
1383
+ } from "./cli-6945ywhr.js";
1373
1384
  import {
1374
1385
  require_content_type
1375
1386
  } from "./cli-1jx0srjt.js";
1387
+ import"./cli-n3qe7tyr.js";
1376
1388
  import {
1377
1389
  isInvalidClientError,
1378
1390
  publicEndpointSsrfOptions,
@@ -1390,7 +1402,7 @@ import {
1390
1402
  revokeMcpToken,
1391
1403
  computeExpiresAt,
1392
1404
  init_mcp_wrapper
1393
- } from "./cli-dd37e0cm.js";
1405
+ } from "./cli-2dq9yv8p.js";
1394
1406
  import"./cli-v41kn3cd.js";
1395
1407
  import {
1396
1408
  setBedrockProviderModule,
@@ -1427,13 +1439,22 @@ import {
1427
1439
  revokeAgentTokens,
1428
1440
  fingerprintApiKey,
1429
1441
  init_users
1430
- } from "./cli-pwsax0vp.js";
1442
+ } from "./cli-v57d7fmm.js";
1431
1443
  import {
1432
1444
  AMP_ESTIMATE_MODELS,
1433
1445
  ampBillsCacheWrites,
1434
1446
  resolveAmpModel,
1435
1447
  init_amp_models
1436
- } from "./cli-gddgcnav.js";
1448
+ } from "./cli-mjw0yf82.js";
1449
+ import {
1450
+ MAX_PROVIDER_QUOTA_ENTRIES,
1451
+ ProviderQuotaCapacityError,
1452
+ windowFieldObservedAtSchema,
1453
+ codexWindowKey,
1454
+ providerAccountTelemetrySchema,
1455
+ rateLimitReplacementSchema,
1456
+ init_provider_account_telemetry
1457
+ } from "./cli-43ms35q9.js";
1437
1458
  import {
1438
1459
  CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1439
1460
  CODEX_AUTH_WATCH_NAMESPACE,
@@ -1606,7 +1627,7 @@ import {
1606
1627
  KvKeySchema,
1607
1628
  KvEntrySchema,
1608
1629
  init_types5
1609
- } from "./cli-me4maa4j.js";
1630
+ } from "./cli-bkjdknnp.js";
1610
1631
  import {
1611
1632
  resolveGitHubHost,
1612
1633
  init_github_host
@@ -1615,7 +1636,7 @@ import {
1615
1636
  IDENTITY_FIELD_BUDGETS,
1616
1637
  IdentityFieldBudgetError,
1617
1638
  init_identity_field_budget
1618
- } from "./cli-aa8s22gn.js";
1639
+ } from "./cli-m7c2380k.js";
1619
1640
  import {
1620
1641
  getSlackConfiguration,
1621
1642
  init_config4
@@ -1629,13 +1650,16 @@ import {
1629
1650
  SUBSCRIPTION_PLANS,
1630
1651
  isSubscriptionPlanId,
1631
1652
  init_subscription_plans
1632
- } from "./cli-7akn6ze9.js";
1653
+ } from "./cli-nh7x3133.js";
1633
1654
  import {
1634
1655
  getOpenRouterAttributionHeaders,
1635
1656
  init_openrouter_base_url
1636
1657
  } from "./cli-dfyv0jdy.js";
1637
1658
  import {
1638
1659
  MODEL_SCOPED_WINDOWS,
1660
+ KEY_WIDE_WINDOWS,
1661
+ modelFamilyOf,
1662
+ isModelScopedWindow,
1639
1663
  activeModelBlocks,
1640
1664
  init_model_rate_limit_windows,
1641
1665
  CREDENTIAL_POOL_VARS,
@@ -1644,7 +1668,7 @@ import {
1644
1668
  splitCredentialPool,
1645
1669
  selectCredential,
1646
1670
  init_credentials2
1647
- } from "./cli-pn1v1pb0.js";
1671
+ } from "./cli-psffsanb.js";
1648
1672
  import {
1649
1673
  interpolate,
1650
1674
  init_template2,
@@ -1654,7 +1678,7 @@ import {
1654
1678
  resolveTemplate,
1655
1679
  init_resolver,
1656
1680
  init_session_templates
1657
- } from "./cli-812paz57.js";
1681
+ } from "./cli-6ehs4mta.js";
1658
1682
  import {
1659
1683
  init_zod
1660
1684
  } from "./cli-zcfpsfzf.js";
@@ -1707,7 +1731,7 @@ import {
1707
1731
  import {
1708
1732
  init_package,
1709
1733
  package_default
1710
- } from "./cli-kaa4bd7x.js";
1734
+ } from "./cli-h9yqfzx9.js";
1711
1735
  import {
1712
1736
  realtimeBus,
1713
1737
  init_bus
@@ -7944,7 +7968,289 @@ async function handleAgentsRest(req, res, pathSegments, queryParams, myAgentId)
7944
7968
  // src/http/api-keys.ts
7945
7969
  init_zod();
7946
7970
  init_db4();
7971
+
7972
+ // src/be/key-window-usage.ts
7973
+ init_zod();
7974
+ init_types5();
7975
+ init_model_rate_limit_windows();
7976
+ init_provider_account_telemetry();
7977
+ init_db4();
7978
+ var MAX_USAGE_WINDOWS = 256;
7979
+ var MAX_USAGE_WINDOWS_PER_CREDENTIAL = 16;
7980
+ var MAX_USAGE_LOOKBACK_MS = 90 * 86400000;
7981
+ var MAX_USAGE_ROWS = 1e5;
7982
+
7983
+ class KeyWindowUsageLimitError extends Error {
7984
+ status;
7985
+ constructor(message, status = 422) {
7986
+ super(message);
7987
+ this.status = status;
7988
+ }
7989
+ }
7990
+ var counterSchema = object2({
7991
+ value: number2().nullable(),
7992
+ measuredSessions: number2().int(),
7993
+ missingSessions: number2().int()
7994
+ });
7995
+ var tokensSchema = object2({
7996
+ uncachedInput: counterSchema,
7997
+ output: counterSchema,
7998
+ cacheRead: counterSchema,
7999
+ cacheWrite: counterSchema,
8000
+ reasoning: counterSchema,
8001
+ thinking: counterSchema
8002
+ });
8003
+ var keyWindowUsageSchema = object2({
8004
+ statusId: string2(),
8005
+ keyType: string2(),
8006
+ keySuffix: string2(),
8007
+ scope: string2(),
8008
+ scopeId: string2().nullable(),
8009
+ windowKey: string2(),
8010
+ durationMins: number2().nullable(),
8011
+ startsAt: string2().nullable(),
8012
+ endsAt: string2().nullable(),
8013
+ dataThrough: string2(),
8014
+ observedAt: string2(),
8015
+ observationAgeMs: number2(),
8016
+ modelScope: object2({
8017
+ kind: _enum2(["account", "family", "unknown"]),
8018
+ model: string2().nullable()
8019
+ }),
8020
+ unavailableReason: _enum2(["missing_reset", "unknown_duration", "unknown_model_scope", "window_not_started"]).nullable(),
8021
+ usage: object2({
8022
+ sessions: number2().int(),
8023
+ errorSessions: number2().int(),
8024
+ completedTasks: number2().int(),
8025
+ tokens: tokensSchema,
8026
+ modelUnattributedSessions: number2().int(),
8027
+ swarmUnattributedSessions: number2().int()
8028
+ }).nullable()
8029
+ });
8030
+ function currentKeyWindows(statuses, nowMs) {
8031
+ const result = [];
8032
+ for (const key of statuses) {
8033
+ for (const [windowKey, window] of Object.entries(key.rateLimitWindows)) {
8034
+ const resetMs = window.resetsAt === undefined ? null : window.resetsAt * 1000;
8035
+ if (resetMs !== null && (!Number.isFinite(resetMs) || resetMs <= nowMs))
8036
+ continue;
8037
+ if (result.length >= MAX_USAGE_WINDOWS) {
8038
+ throw new KeyWindowUsageLimitError("Too many provider windows. Filter by credential or scope.");
8039
+ }
8040
+ const legacyClaude = window.source ? window.source === "claude" : key.provider === "claude";
8041
+ const family = legacyClaude ? MODEL_SCOPED_WINDOWS[windowKey] : undefined;
8042
+ const durationMins = window.durationMins ?? (legacyClaude ? windowKey === "five_hour" ? 300 : windowKey === "seven_day" || family ? 10080 : null : null);
8043
+ const accountWide = legacyClaude ? KEY_WIDE_WINDOWS.some((name) => name === windowKey) : [codexWindowKey("codex", "primary"), codexWindowKey("codex", "secondary")].includes(windowKey);
8044
+ const modelScope = family ? { kind: "family", model: family } : { kind: accountWide ? "account" : "unknown", model: null };
8045
+ const startMs = resetMs !== null && durationMins ? resetMs - durationMins * 60000 : null;
8046
+ const unavailableReason = resetMs === null ? "missing_reset" : startMs === null ? "unknown_duration" : startMs > nowMs ? "window_not_started" : modelScope.kind === "unknown" ? "unknown_model_scope" : null;
8047
+ result.push({
8048
+ statusId: key.id,
8049
+ keyType: key.keyType,
8050
+ keySuffix: key.keySuffix,
8051
+ scope: key.scope,
8052
+ scopeId: key.scopeId,
8053
+ windowKey,
8054
+ durationMins,
8055
+ startsAt: startMs === null ? null : new Date(startMs).toISOString(),
8056
+ endsAt: resetMs === null ? null : new Date(resetMs).toISOString(),
8057
+ dataThrough: new Date(Math.min(nowMs, resetMs ?? nowMs)).toISOString(),
8058
+ observedAt: window.lastSeenAt,
8059
+ observationAgeMs: Math.max(0, nowMs - Date.parse(window.lastSeenAt)),
8060
+ modelScope,
8061
+ unavailableReason,
8062
+ usage: null
8063
+ });
8064
+ }
8065
+ }
8066
+ return result;
8067
+ }
8068
+ var usageColumns = `sc.taskId, sc.credentialKeyType, sc.credentialKeySuffix, sc.harness,
8069
+ sc.inputTokens, sc.outputTokens, sc.cacheReadTokens, sc.cacheWriteTokens,
8070
+ sc.reasoningOutputTokens, sc.thinkingTokens, sc.model, sc.modelBreakdown,
8071
+ sc.isError, sc.createdAt`;
8072
+ var KEY_WINDOW_USAGE_SQL = `
8073
+ WITH requested_keys AS (
8074
+ SELECT json_extract(value, '$.keyType') AS keyType,
8075
+ json_extract(value, '$.keySuffix') AS keySuffix FROM json_each(?)
8076
+ )
8077
+ SELECT ${usageColumns}, CASE WHEN t.status = 'completed' THEN t.finishedAt END AS finishedAt
8078
+ FROM requested_keys k
8079
+ JOIN session_costs sc INDEXED BY idx_session_costs_credential_createdAt
8080
+ ON sc.credentialKeyType = k.keyType AND sc.credentialKeySuffix = k.keySuffix
8081
+ LEFT JOIN agent_tasks t ON t.id = sc.taskId
8082
+ WHERE sc.createdAt >= ? AND sc.createdAt < ?
8083
+ UNION ALL
8084
+ SELECT ${usageColumns}, t.finishedAt
8085
+ FROM agent_tasks t INDEXED BY idx_agent_tasks_status_finishedAt
8086
+ CROSS JOIN session_costs sc INDEXED BY idx_session_costs_taskId ON sc.taskId = t.id
8087
+ JOIN requested_keys k ON sc.credentialKeyType = k.keyType AND sc.credentialKeySuffix = k.keySuffix
8088
+ WHERE t.status = 'completed' AND t.finishedAt >= ? AND t.finishedAt < ? AND sc.createdAt < ?
8089
+ UNION ALL
8090
+ SELECT NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, 0, 0, '', NULL, 0, sc.createdAt, NULL
8091
+ FROM session_costs sc
8092
+ WHERE (sc.credentialKeyType IS NULL OR sc.credentialKeySuffix IS NULL)
8093
+ AND sc.createdAt >= ? AND sc.createdAt < ?
8094
+ LIMIT ${MAX_USAGE_ROWS + 1}`;
8095
+ var emptyTokens = () => Object.fromEntries(["uncachedInput", "output", "cacheRead", "cacheWrite", "reasoning", "thinking"].map((name) => [
8096
+ name,
8097
+ { value: null, measuredSessions: 0, missingSessions: 0 }
8098
+ ]));
8099
+ function add(tokens, name, value) {
8100
+ const counter = tokens[name];
8101
+ if (value === null)
8102
+ counter.missingSessions++;
8103
+ else {
8104
+ counter.value = (counter.value ?? 0) + value;
8105
+ counter.measuredSessions++;
8106
+ }
8107
+ }
8108
+ async function aggregateKeyWindowUsage(windows, through) {
8109
+ if (windows.length > MAX_USAGE_WINDOWS) {
8110
+ throw new KeyWindowUsageLimitError("Too many provider windows. Filter by credential or scope.");
8111
+ }
8112
+ const eligible = windows.filter((w) => w.unavailableReason === null && w.startsAt !== null && w.endsAt !== null);
8113
+ const first = eligible[0];
8114
+ if (!first)
8115
+ return [];
8116
+ const start = eligible.reduce((earliest, w) => w.startsAt < earliest ? w.startsAt : earliest, first.startsAt);
8117
+ if (Date.parse(start) < Date.parse(through) - MAX_USAGE_LOOKBACK_MS) {
8118
+ throw new KeyWindowUsageLimitError("Observed usage supports a maximum lookback of 90 days.");
8119
+ }
8120
+ const credentialKey = (key) => JSON.stringify([key.keyType, key.keySuffix]);
8121
+ const windowIdentity = (window) => JSON.stringify([window.startsAt, window.endsAt, window.modelScope]);
8122
+ const windowGroups = new Map;
8123
+ for (const window of eligible) {
8124
+ const key = credentialKey(window);
8125
+ const bounds = windowGroups.get(key) ?? new Set;
8126
+ bounds.add(windowIdentity(window));
8127
+ if (bounds.size > MAX_USAGE_WINDOWS_PER_CREDENTIAL) {
8128
+ throw new KeyWindowUsageLimitError("Too many distinct windows for one credential. Filter by scope.");
8129
+ }
8130
+ windowGroups.set(key, bounds);
8131
+ }
8132
+ const credentials = [
8133
+ ...new Map(eligible.map((w) => [
8134
+ JSON.stringify([w.keyType, w.keySuffix]),
8135
+ { keyType: w.keyType, keySuffix: w.keySuffix }
8136
+ ])).values()
8137
+ ];
8138
+ const rows = await getDbClient2().query(KEY_WINDOW_USAGE_SQL, [
8139
+ JSON.stringify(credentials),
8140
+ start,
8141
+ through,
8142
+ start,
8143
+ through,
8144
+ start,
8145
+ start,
8146
+ through
8147
+ ]);
8148
+ if (rows.length > MAX_USAGE_ROWS) {
8149
+ throw new KeyWindowUsageLimitError("Too many sessions for window usage. Filter by credential or scope.");
8150
+ }
8151
+ const rowsByCredential = new Map;
8152
+ const unattributedTimes = [];
8153
+ for (const row of rows) {
8154
+ if (row.credentialKeyType === null || row.credentialKeySuffix === null) {
8155
+ unattributedTimes.push(row.createdAt);
8156
+ continue;
8157
+ }
8158
+ const key = credentialKey({
8159
+ keyType: row.credentialKeyType,
8160
+ keySuffix: row.credentialKeySuffix
8161
+ });
8162
+ const group = rowsByCredential.get(key) ?? [];
8163
+ group.push(row);
8164
+ rowsByCredential.set(key, group);
8165
+ }
8166
+ unattributedTimes.sort();
8167
+ const unattributedSince = (start) => {
8168
+ let lower = 0;
8169
+ let upper = unattributedTimes.length;
8170
+ while (lower < upper) {
8171
+ const middle = Math.floor((lower + upper) / 2);
8172
+ if (unattributedTimes[middle] < start)
8173
+ lower = middle + 1;
8174
+ else
8175
+ upper = middle;
8176
+ }
8177
+ return unattributedTimes.length - lower;
8178
+ };
8179
+ const computed = new Map;
8180
+ return eligible.map((window) => {
8181
+ const identity = JSON.stringify([credentialKey(window), windowIdentity(window)]);
8182
+ const prior = computed.get(identity);
8183
+ if (prior)
8184
+ return {
8185
+ statusId: window.statusId,
8186
+ windowKey: window.windowKey,
8187
+ dataThrough: through,
8188
+ usage: prior
8189
+ };
8190
+ const usage = {
8191
+ sessions: 0,
8192
+ errorSessions: 0,
8193
+ completedTasks: 0,
8194
+ tokens: emptyTokens(),
8195
+ modelUnattributedSessions: 0,
8196
+ swarmUnattributedSessions: unattributedSince(window.startsAt)
8197
+ };
8198
+ const completed = new Set;
8199
+ for (const row of rowsByCredential.get(credentialKey(window)) ?? []) {
8200
+ const inReceiptWindow = row.createdAt >= window.startsAt && row.createdAt < through;
8201
+ let parts = [
8202
+ {
8203
+ model: row.model,
8204
+ inputTokens: row.inputTokens,
8205
+ outputTokens: row.outputTokens,
8206
+ cacheReadTokens: row.cacheReadTokens,
8207
+ cacheWriteTokens: row.cacheWriteTokens
8208
+ }
8209
+ ];
8210
+ const scoped = window.modelScope.kind !== "account";
8211
+ if (scoped) {
8212
+ parts = [];
8213
+ try {
8214
+ const parsed = SessionCostModelBreakdownSchema.array().safeParse(row.modelBreakdown ? JSON.parse(row.modelBreakdown) : null);
8215
+ parts = parsed.success ? parsed.data : [];
8216
+ } catch {
8217
+ parts = [];
8218
+ }
8219
+ }
8220
+ if (scoped) {
8221
+ const known = parts.length > 0 && parts.every((part) => part.model.length > 0);
8222
+ if (!known && inReceiptWindow)
8223
+ usage.modelUnattributedSessions++;
8224
+ parts = parts.filter((part) => modelFamilyOf(part.model) === window.modelScope.model);
8225
+ if (!parts.length)
8226
+ continue;
8227
+ }
8228
+ if (row.taskId && row.finishedAt && row.finishedAt >= window.startsAt && row.finishedAt < through)
8229
+ completed.add(row.taskId);
8230
+ if (!inReceiptWindow)
8231
+ continue;
8232
+ usage.sessions++;
8233
+ usage.errorSessions += row.isError ? 1 : 0;
8234
+ const sum = (field) => parts.some((part) => part[field] === null) ? null : parts.reduce((total, part) => total + (part[field] ?? 0), 0);
8235
+ const input = sum("inputTokens");
8236
+ const read = sum("cacheReadTokens");
8237
+ const knownInput = ["claude", "claude-managed", "pi", "opencode"].includes(row.harness ?? "");
8238
+ add(usage.tokens, "uncachedInput", row.harness === "codex" ? input !== null && read !== null ? Math.max(0, input - read) : null : knownInput ? input : null);
8239
+ add(usage.tokens, "output", sum("outputTokens"));
8240
+ add(usage.tokens, "cacheRead", read);
8241
+ add(usage.tokens, "cacheWrite", sum("cacheWriteTokens"));
8242
+ add(usage.tokens, "reasoning", !scoped && row.reasoningOutputTokens > 0 ? row.reasoningOutputTokens : null);
8243
+ add(usage.tokens, "thinking", !scoped && row.thinkingTokens > 0 ? row.thinkingTokens : null);
8244
+ }
8245
+ usage.completedTasks = completed.size;
8246
+ computed.set(identity, usage);
8247
+ return { statusId: window.statusId, windowKey: window.windowKey, dataThrough: through, usage };
8248
+ });
8249
+ }
8250
+
8251
+ // src/http/api-keys.ts
7947
8252
  init_model_rate_limit_windows();
8253
+ init_provider_account_telemetry();
7948
8254
  init_subscription_plans();
7949
8255
  init_route_def();
7950
8256
 
@@ -7998,6 +8304,7 @@ function clearUsageCache() {
7998
8304
 
7999
8305
  // src/http/api-keys.ts
8000
8306
  init_utils2();
8307
+ var windowUsageQueryRateLimit = createIpRateLimiter({ capacity: 8, refillPerMs: 1 / 1000 });
8001
8308
  var successMessageSchema = object2({
8002
8309
  success: literal2(true),
8003
8310
  message: string2()
@@ -8016,7 +8323,8 @@ var reportUsage = route({
8016
8323
  taskId: string2().uuid().optional(),
8017
8324
  scope: string2().optional(),
8018
8325
  scopeId: string2().optional(),
8019
- plan: string2().max(40).optional()
8326
+ plan: string2().max(40).optional(),
8327
+ planRaw: string2().min(1).max(80).optional()
8020
8328
  }),
8021
8329
  responses: {
8022
8330
  200: { description: "Usage recorded", schema: successMessageSchema },
@@ -8107,45 +8415,102 @@ var reportAuthFailure = route({
8107
8415
  }
8108
8416
  });
8109
8417
  var rateLimitWindowSchema = object2({
8110
- status: string2(),
8418
+ status: string2().max(256),
8111
8419
  utilization: number2().optional(),
8112
8420
  resetsAt: number2().finite().optional(),
8421
+ fieldObservedAt: windowFieldObservedAtSchema.optional(),
8422
+ durationMins: number2().int().positive().max(576000).optional(),
8423
+ source: _enum2(["claude", "codex"]).optional(),
8424
+ limitId: string2().min(1).max(128).optional(),
8425
+ label: string2().max(256).optional(),
8426
+ normalModelSlug: string2().max(256).optional(),
8427
+ overageStatus: string2().max(256).optional(),
8428
+ overageDisabledReason: string2().max(256).optional(),
8113
8429
  isUsingOverage: boolean().optional(),
8114
8430
  surpassedThreshold: number2().optional(),
8115
8431
  lastSeenAt: string2().datetime()
8116
8432
  });
8433
+ var MAX_DISPLAY_RESET_MS = 400 * 86400000;
8117
8434
  function sanitizeReportedWindowResets(windows) {
8118
- const nowSec = Math.floor(Date.now() / 1000);
8119
- const maxResetsAtSec = Math.floor((Date.now() + MAX_RATE_LIMIT_RESET_MS) / 1000);
8435
+ const nowMs = Date.now();
8436
+ const nowSec = Math.floor(nowMs / 1000);
8120
8437
  const sanitized = {};
8121
8438
  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) };
8439
+ const duration = window.durationMins ?? (key === "five_hour" ? 300 : key.startsWith("seven_day") ? 10080 : undefined);
8440
+ const horizonMs = isModelScopedWindow(key) ? MAX_RATE_LIMIT_RESET_MS : duration === undefined ? MAX_DISPLAY_RESET_MS : Math.min(MAX_DISPLAY_RESET_MS, Math.max(MAX_RATE_LIMIT_RESET_MS, duration * 60000 + 86400000));
8441
+ const maxResetsAtSec = Math.floor((nowMs + horizonMs) / 1000);
8442
+ sanitized[key] = window.resetsAt === undefined ? window : {
8443
+ ...window,
8444
+ resetsAt: Math.min(window.resetsAt < nowSec - MAX_DISPLAY_RESET_MS / 1000 ? nowSec : window.resetsAt, maxResetsAtSec)
8445
+ };
8123
8446
  }
8124
8447
  return sanitized;
8125
8448
  }
8449
+ function sanitizeReportedQuotaObservations(report, nowMs = Date.now()) {
8450
+ const bound = (at) => Date.parse(at) > nowMs + 60000 ? new Date(nowMs).toISOString() : at;
8451
+ const times = (values) => values && Object.fromEntries(Object.entries(values).map(([key, at]) => [key, bound(at)]));
8452
+ return {
8453
+ windows: Object.fromEntries(Object.entries(report.windows).map(([key, window]) => [
8454
+ key,
8455
+ {
8456
+ ...window,
8457
+ lastSeenAt: bound(window.lastSeenAt),
8458
+ ...window.fieldObservedAt ? { fieldObservedAt: times(window.fieldObservedAt) } : {}
8459
+ }
8460
+ ])),
8461
+ account: report.account && {
8462
+ ...report.account,
8463
+ observedAt: bound(report.account.observedAt),
8464
+ ...report.account.fieldObservedAt ? { fieldObservedAt: times(report.account.fieldObservedAt) } : {},
8465
+ ...report.account.limits ? {
8466
+ limits: Object.fromEntries(Object.entries(report.account.limits).map(([id, limit]) => [
8467
+ id,
8468
+ {
8469
+ ...limit,
8470
+ observedAt: bound(limit.observedAt),
8471
+ ...limit.fieldObservedAt ? { fieldObservedAt: times(limit.fieldObservedAt) } : {},
8472
+ ...limit.windowRemovedAt ? { windowRemovedAt: times(limit.windowRemovedAt) } : {}
8473
+ }
8474
+ ]))
8475
+ } : {}
8476
+ },
8477
+ replace: report.replace?.map((replacement) => ({
8478
+ ...replacement,
8479
+ observedAt: bound(replacement.observedAt)
8480
+ }))
8481
+ };
8482
+ }
8126
8483
  var reportRateLimitWindows = route({
8127
8484
  method: "post",
8128
8485
  path: "/api/keys/report-rate-limit-windows",
8129
8486
  pattern: ["api", "keys", "report-rate-limit-windows"],
8130
8487
  summary: "Record provider-emitted rate-limit window telemetry for an API key",
8488
+ description: "Reports accept up to 64 windows and 64 account limits within 256 KiB. Stored records have the same count limits.",
8131
8489
  tags: ["API Keys"],
8490
+ maxBodyBytes: 256 * 1024,
8132
8491
  body: object2({
8133
8492
  keyType: string2(),
8134
8493
  keySuffix: string2().min(1).max(10),
8135
8494
  keyIndex: number2().int().min(0),
8136
- windows: record2(string2(), rateLimitWindowSchema),
8495
+ windows: record2(string2().max(256), rateLimitWindowSchema),
8496
+ account: providerAccountTelemetrySchema.optional(),
8497
+ replace: array2(rateLimitReplacementSchema).max(128).optional(),
8137
8498
  scope: string2().optional(),
8138
8499
  scopeId: string2().optional()
8139
- }),
8500
+ }).refine((report) => Object.keys(report.windows).length <= MAX_PROVIDER_QUOTA_ENTRIES && Object.keys(report.account?.limits ?? {}).length <= MAX_PROVIDER_QUOTA_ENTRIES, "Reports support at most 64 windows and 64 account limits."),
8140
8501
  responses: {
8141
8502
  200: {
8142
8503
  description: "Rate-limit window telemetry recorded",
8143
8504
  schema: successMessageSchema
8144
8505
  },
8145
8506
  400: { description: "Validation error" },
8146
- 401: { description: "Unauthorized" }
8507
+ 401: { description: "Unauthorized" },
8508
+ 413: { description: "Telemetry report exceeds 256 KiB" }
8147
8509
  },
8148
- auth: { apiKey: true }
8510
+ auth: { apiKey: true },
8511
+ rbac: {
8512
+ ungated: "worker credential telemetry, same posture as POST /api/keys/report-rate-limit"
8513
+ }
8149
8514
  });
8150
8515
  var reportSeatMismatch = route({
8151
8516
  method: "post",
@@ -8223,8 +8588,10 @@ var ApiKeyStatusSchema = object2({
8223
8588
  name: string2().nullable(),
8224
8589
  provider: string2(),
8225
8590
  rateLimitWindows: record2(string2(), rateLimitWindowSchema),
8591
+ providerAccount: providerAccountTelemetrySchema.nullable(),
8226
8592
  plan: string2().nullable(),
8227
8593
  planSource: _enum2(["manual", "detected", "estimated"]).nullable(),
8594
+ detectedPlanRaw: string2().nullable(),
8228
8595
  lastSeatMismatchAt: string2().nullable(),
8229
8596
  lastSeatMismatchModel: string2().nullable(),
8230
8597
  consecutiveAuthFailures: number2().int(),
@@ -8287,6 +8654,36 @@ var listStatuses = route({
8287
8654
  },
8288
8655
  auth: { apiKey: true }
8289
8656
  });
8657
+ var getWindowUsage = route({
8658
+ method: "get",
8659
+ path: "/api/keys/window-usage",
8660
+ pattern: ["api", "keys", "window-usage"],
8661
+ summary: "Get Swarm-observed usage within current provider windows",
8662
+ description: "Usage calculations support 256 windows, 16 distinct windows per credential, 90 days, and 100,000 session rows. Oversized requests fail without partial totals.",
8663
+ tags: ["API Keys"],
8664
+ query: object2({
8665
+ keyType: string2().max(128).optional(),
8666
+ keySuffix: string2().min(1).max(10).optional(),
8667
+ scope: string2().max(64).optional(),
8668
+ scopeId: string2().max(128).optional()
8669
+ }),
8670
+ responses: {
8671
+ 200: {
8672
+ description: "Independent windows with receipt-time tokens and explicit measurement coverage",
8673
+ schema: object2({
8674
+ success: literal2(true),
8675
+ asOf: string2(),
8676
+ accounting: literal2("session_cost_receipt_time"),
8677
+ windows: array2(keyWindowUsageSchema)
8678
+ })
8679
+ },
8680
+ 400: { description: "Invalid filters" },
8681
+ 401: { description: "Unauthorized" },
8682
+ 422: { description: "Requested usage exceeds the aggregation bounds" },
8683
+ 429: { description: "Usage query budget exhausted. Retry after one second" }
8684
+ },
8685
+ auth: { apiKey: true }
8686
+ });
8290
8687
  var KeyCostSummarySchema = object2({
8291
8688
  keyType: string2(),
8292
8689
  keySuffix: string2(),
@@ -8426,9 +8823,9 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8426
8823
  const parsed = await reportUsage.parse(req, res, pathSegments, queryParams);
8427
8824
  if (!parsed)
8428
8825
  return true;
8429
- const { keyType, keySuffix, keyIndex, taskId, scope, scopeId, plan } = parsed.body;
8826
+ const { keyType, keySuffix, keyIndex, taskId, scope, scopeId, plan, planRaw } = parsed.body;
8430
8827
  try {
8431
- const { planChanged } = await recordKeyUsage2(keyType, keySuffix, keyIndex, taskId ?? null, scope, scopeId ?? null, plan && isSubscriptionPlanId(plan) ? plan : null);
8828
+ const { planChanged } = await recordKeyUsage2(keyType, keySuffix, keyIndex, taskId ?? null, scope, scopeId ?? null, plan && isSubscriptionPlanId(plan) ? plan : null, planRaw);
8432
8829
  if (planChanged)
8433
8830
  clearUsageCache();
8434
8831
  reportUsage.respond(res, 200, { success: true, message: "Key usage recorded" });
@@ -8485,17 +8882,20 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8485
8882
  const parsed = await reportRateLimitWindows.parse(req, res, pathSegments, queryParams);
8486
8883
  if (!parsed)
8487
8884
  return true;
8488
- const { keyType, keySuffix, keyIndex, windows, scope, scopeId } = parsed.body;
8885
+ const { keyType, keySuffix, keyIndex, scope, scopeId } = parsed.body;
8886
+ const { windows, account, replace } = sanitizeReportedQuotaObservations(parsed.body);
8489
8887
  try {
8490
- const { planChanged } = await recordKeyRateLimitWindows2(keyType, keySuffix, keyIndex, sanitizeReportedWindowResets(windows), scope, scopeId ?? null);
8491
- if (planChanged)
8492
- clearUsageCache();
8888
+ for (const limit of Object.values(account?.limits ?? {})) {
8889
+ if (limit.spend)
8890
+ limit.spend.resetsAt = Math.min(limit.spend.resetsAt, Math.floor(Date.now() / 1000) + 400 * 86400);
8891
+ }
8892
+ await recordKeyRateLimitWindows2(keyType, keySuffix, keyIndex, sanitizeReportedWindowResets(windows), scope, scopeId ?? null, account ?? undefined, replace);
8493
8893
  reportRateLimitWindows.respond(res, 200, {
8494
8894
  success: true,
8495
8895
  message: `Rate-limit windows recorded for ...${keySuffix}`
8496
8896
  });
8497
8897
  } catch (err) {
8498
- jsonError(res, err instanceof Error ? err.message : "Failed to record rate-limit windows", 500);
8898
+ jsonError(res, err instanceof Error ? err.message : "Failed to record rate-limit windows", err instanceof ProviderQuotaCapacityError ? 400 : 500);
8499
8899
  }
8500
8900
  return true;
8501
8901
  }
@@ -8541,6 +8941,52 @@ async function handleApiKeys(req, res, pathSegments, queryParams) {
8541
8941
  }
8542
8942
  return true;
8543
8943
  }
8944
+ if (getWindowUsage.match(req.method, pathSegments)) {
8945
+ const parsed = await getWindowUsage.parse(req, res, pathSegments, queryParams);
8946
+ if (!parsed)
8947
+ return true;
8948
+ const { keyType, keySuffix, scope, scopeId } = parsed.query;
8949
+ try {
8950
+ const statuses = await getKeyStatuses2(keyType, scope, scope ? scopeId ?? null : undefined);
8951
+ const sampledAt = Date.now();
8952
+ const windows = currentKeyWindows(statuses.filter((key) => keySuffix === undefined || key.keySuffix === keySuffix), sampledAt);
8953
+ const bounds = windows.map((w) => [
8954
+ w.statusId,
8955
+ w.windowKey,
8956
+ w.startsAt,
8957
+ w.endsAt,
8958
+ w.modelScope,
8959
+ w.unavailableReason
8960
+ ]);
8961
+ const cached = await cachedUsageReport(`key-windows:${JSON.stringify([parsed.query, bounds])}`, () => {
8962
+ if (!windowUsageQueryRateLimit.take("window-usage")) {
8963
+ throw new KeyWindowUsageLimitError("Window usage is busy. Retry after one second.", 429);
8964
+ }
8965
+ return aggregateKeyWindowUsage(windows, new Date(sampledAt).toISOString());
8966
+ });
8967
+ const nowMs = Date.now();
8968
+ const byWindow = new Map(cached.map((item) => [JSON.stringify([item.statusId, item.windowKey]), item]));
8969
+ getWindowUsage.respond(res, 200, {
8970
+ success: true,
8971
+ asOf: new Date(nowMs).toISOString(),
8972
+ accounting: "session_cost_receipt_time",
8973
+ windows: windows.filter((w) => w.endsAt === null || Date.parse(w.endsAt) > nowMs).map((window) => {
8974
+ const aggregate = byWindow.get(JSON.stringify([window.statusId, window.windowKey]));
8975
+ return {
8976
+ ...window,
8977
+ observationAgeMs: Math.max(0, nowMs - Date.parse(window.observedAt)),
8978
+ ...aggregate ? { dataThrough: aggregate.dataThrough, usage: aggregate.usage } : {}
8979
+ };
8980
+ })
8981
+ });
8982
+ } catch (err) {
8983
+ const status = err instanceof KeyWindowUsageLimitError ? err.status : 500;
8984
+ if (status === 429)
8985
+ res.setHeader("Retry-After", "1");
8986
+ jsonError(res, err instanceof Error ? err.message : "Failed to get window usage", status);
8987
+ }
8988
+ return true;
8989
+ }
8544
8990
  if (getCosts.match(req.method, pathSegments)) {
8545
8991
  const parsed = await getCosts.parse(req, res, pathSegments, queryParams);
8546
8992
  if (!parsed)
@@ -13037,7 +13483,7 @@ function errorMessage2(error) {
13037
13483
 
13038
13484
  // src/http/comb.ts
13039
13485
  init_rbac();
13040
- init_errors();
13486
+ init_errors2();
13041
13487
  init_secret_scrubber();
13042
13488
  init_request_principal();
13043
13489
  init_route_def();
@@ -13473,16 +13919,16 @@ declare module "swarm-extension" {
13473
13919
  | "schedule"
13474
13920
  | "slack"
13475
13921
  | "agentmail"
13922
+ | "mcp"
13923
+ | "api"
13924
+ | "ui"
13476
13925
  | "github"
13477
13926
  | "gitlab"
13478
13927
  | "azure-devops"
13479
13928
  | "bitbucket"
13929
+ | "system"
13480
13930
  | "linear"
13481
13931
  | "jira"
13482
- | "mcp"
13483
- | "api"
13484
- | "ui"
13485
- | "system"
13486
13932
  | "comb"
13487
13933
  | undefined;
13488
13934
  routingReason?:
@@ -13624,16 +14070,16 @@ declare module "swarm-extension" {
13624
14070
  | "schedule"
13625
14071
  | "slack"
13626
14072
  | "agentmail"
14073
+ | "mcp"
14074
+ | "api"
14075
+ | "ui"
13627
14076
  | "github"
13628
14077
  | "gitlab"
13629
14078
  | "azure-devops"
13630
14079
  | "bitbucket"
14080
+ | "system"
13631
14081
  | "linear"
13632
14082
  | "jira"
13633
- | "mcp"
13634
- | "api"
13635
- | "ui"
13636
- | "system"
13637
14083
  | "comb";
13638
14084
  tags: string[];
13639
14085
  priority: number;
@@ -16372,7 +16818,7 @@ export default extension;
16372
16818
  $schema: "../manifest.schema.json",
16373
16819
  name: "sql-admin-only",
16374
16820
  description: "Blocks db-query tool calls on tasks created by a non-admin user",
16375
- version: "1.0.0",
16821
+ version: "1.1.0",
16376
16822
  runtime: "api",
16377
16823
  assets: {
16378
16824
  hooks: "hooks.ts"
@@ -16390,7 +16836,7 @@ const SQL_TOOLS = new Set(["db-query"]);
16390
16836
  const manifest = {
16391
16837
  name: "sql-admin-only",
16392
16838
  description: "Blocks db-query tool calls on tasks created by a non-admin user",
16393
- version: "1.0.0",
16839
+ version: "1.1.0",
16394
16840
  runtime: "api",
16395
16841
  assets: { hooks: "hooks.ts" },
16396
16842
  config,
@@ -16445,7 +16891,7 @@ const extension: SwarmExtension<typeof manifest> = (api) => {
16445
16891
  const taskId = event.requestInfo?.sourceTaskId;
16446
16892
  if (!taskId) return;
16447
16893
 
16448
- // Creator lookup. Any failure blocks this SQL call only (fail closed).
16894
+ // Creator lookup. A failed lookup blocks this SQL call only (fail closed).
16449
16895
  let creator: string;
16450
16896
  let role: string;
16451
16897
  try {
@@ -16455,7 +16901,11 @@ const extension: SwarmExtension<typeof manifest> = (api) => {
16455
16901
  )) as Envelope;
16456
16902
  if (q?.success === false) throw new Error("db-query lookup returned success=false");
16457
16903
  const row = (q?.data?.rows ?? q?.rows ?? [])[0];
16458
- if (!row) throw new Error(\`task \${taskId} not found\`);
16904
+ // A successful lookup with no row: the id is not a task. The runner sends a
16905
+ // random correlation id for sessions with no task (pool or channel-message
16906
+ // triggers, src/commands/runner.ts effectiveTaskId). No task means no creator:
16907
+ // allow, the same as a missing header. Errors and timeouts above still block.
16908
+ if (!row) return;
16459
16909
  creator = String(cell(row, 0, "requestedByUserId") ?? "");
16460
16910
  role = String(cell(row, 1, "role") ?? "");
16461
16911
  } catch (err) {
@@ -16477,7 +16927,7 @@ const extension: SwarmExtension<typeof manifest> = (api) => {
16477
16927
  export default extension;
16478
16928
  `
16479
16929
  },
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"
16930
+ readme: "# sql-admin-only\n\nBlocks `db-query` tool calls made on a task whose creator (`requestedByUserId`) is not an admin. Every other tool call passes untouched.\n\n| Task creator | `db-query` |\n|---|---|\n| Not set, or the call has no task | Allowed |\n| The header's id has no task row (a session with no task) | Allowed |\n| Set, holds an admin role | Allowed |\n| Set, no admin role | Blocked |\n| Set, but the lookup fails or times out | Blocked |\n\nNo config. \"Admin\" means the creator's `users.role` is `admin` (case-insensitive), the role the swarm shows next to a requester's name. Only Lead (`manage-user`) and REST callers with `user.role.manage` can set it. RBAC roles are not used, because every user is created with the RBAC `admin` role. A creator whose user row is gone counts as non-admin.\n\nThe task comes from the call's `X-Source-Task-Id` header. The lookup gets 60% of `EXTENSION_HANDLER_TIMEOUT_MS` (default 5s), because the dispatcher lets a call through when a hook times out.\n\nCoverage limits:\n\n- Only agent MCP tool calls run `pre.tool.call`. Scripts calling `ctx.swarm.db_query`, extensions, and direct `POST /api/db-query` requests skip the hook.\n- A call without an `X-Source-Task-Id` header has no task, so it is allowed.\n"
16481
16931
  },
16482
16932
  "task-digest": {
16483
16933
  manifestFile: "manifest.yaml",
@@ -27505,15 +27955,17 @@ init_rbac_roles();
27505
27955
  init_session_shares();
27506
27956
  init_steering2();
27507
27957
  init_task_citations2();
27958
+ init_task_ui_spec();
27508
27959
  init_users();
27509
27960
  init_rbac();
27510
27961
  init_context_key();
27511
- init_errors();
27962
+ init_errors2();
27512
27963
  init_sibling_awareness();
27513
27964
  init_task_skip();
27514
27965
  init_terminal_result_guard();
27515
27966
  init_worker_follow_up();
27516
27967
  init_types5();
27968
+ init_actions();
27517
27969
  init_business_use();
27518
27970
  init_request_auth_context();
27519
27971
  init_secret_scrubber();
@@ -27726,7 +28178,8 @@ var GetTaskResponseSchema = AgentTaskSchema.extend({
27726
28178
  supportedSteerModes: array2(SteerModeSchema),
27727
28179
  logs: array2(AgentLogSchema),
27728
28180
  attachments: array2(TaskAttachmentSchema),
27729
- citations: array2(TaskCitationSchema)
28181
+ citations: array2(TaskCitationSchema),
28182
+ uiSpec: TaskUiSpecSchema.nullable()
27730
28183
  });
27731
28184
  var FinishTaskSuccessSchema = object2({
27732
28185
  success: literal2(true),
@@ -27841,7 +28294,7 @@ var createTask = route({
27841
28294
  description: "Validation error, an unknown `model` (set `allowCustomModel` to store a custom id), a `vcsRepo` that is not exactly one registered repo, or agentId/offeredTo targets an extension identity"
27842
28295
  },
27843
28296
  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"
28297
+ description: "Parent/session access denied, unauthorized chat-thread binding, or routing requirements reject the assignment"
27845
28298
  },
27846
28299
  422: {
27847
28300
  description: "Task creation blocked by an extension",
@@ -28188,13 +28641,36 @@ var resumeTaskRoute = route({
28188
28641
  404: { description: "Task not found" }
28189
28642
  }
28190
28643
  });
28644
+ var runTaskUiActionRoute = route({
28645
+ method: "post",
28646
+ path: "/api/tasks/{id}/ui-actions/{actionId}",
28647
+ pattern: ["api", "tasks", null, "ui-actions", null],
28648
+ session: { taskParam: "id" },
28649
+ rbac: { permission: "task.action.own" },
28650
+ summary: "Run the action a task card Button declares",
28651
+ description: "Runs the task card action once per task and action. Only the task requester may run it: a user token, or the operator key with the requester in `X-Swarm-User-Id`. Agent callers, and operator calls with no picked user, get 403. Needs UI_SPEC_ACTIONS_ENABLED=true.",
28652
+ tags: ["Tasks"],
28653
+ params: object2({ id: string2(), actionId: string2() }),
28654
+ responses: {
28655
+ 200: {
28656
+ description: "The action started, or it already ran",
28657
+ schema: object2({
28658
+ status: _enum2(["started", "already_done"]),
28659
+ taskId: string2().optional()
28660
+ })
28661
+ },
28662
+ 403: { description: "Only the task requester may run the action" },
28663
+ 404: { description: "Task or action not found" },
28664
+ 409: { description: "Card actions are turned off (UI_SPEC_ACTIONS_ENABLED)" }
28665
+ }
28666
+ });
28191
28667
  var supersedeTaskRoute = route({
28192
28668
  method: "post",
28193
28669
  path: "/api/tasks/{id}/supersede",
28194
28670
  pattern: ["api", "tasks", null, "supersede"],
28195
28671
  session: { taskParam: "id" },
28196
28672
  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.',
28673
+ description: "Marks the original task `superseded` (terminal) and creates a fresh `taskType=\"resume\"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine's retry/failure policy applies, and the task moves to `superseded` once the engine queues the step's retry. With `reason: provider_fallback` (and its `errorClass`), the resume runs on the same agent with the next fallback profile that passes the profile check; when none is left, or the task is a workflow step, nothing changes and `kind: noFallback` tells the worker to fail the task itself, led by `failureReason` when set.",
28198
28674
  tags: ["Tasks"],
28199
28675
  params: object2({ id: string2() }),
28200
28676
  body: object2({ reason: ResumeReasonSchema, errorClass: ProviderErrorClassSchema.optional() }).refine((body) => body.reason === "provider_fallback" === (body.errorClass !== undefined), {
@@ -28491,6 +28967,7 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
28491
28967
  vcsRepo,
28492
28968
  parentTaskId: parsed.body.parentTaskId || undefined,
28493
28969
  inheritParentOutputSchema: principal.kind === "agent",
28970
+ routingAffinity: parsed.body.parentTaskId && (principal.kind === "user" || principal.kind === "operator") ? { capabilities: [] } : undefined,
28494
28971
  source: parsed.body.source || "api",
28495
28972
  outputSchema: parsed.body.outputSchema || undefined,
28496
28973
  contextKey: parsed.body.contextKey || undefined,
@@ -28520,6 +28997,16 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
28520
28997
  });
28521
28998
  createTask.respond(res, 201, task);
28522
28999
  } catch (error) {
29000
+ if (error instanceof TaskRoutingAuthorizationError) {
29001
+ console.warn("[HTTP] Task assignment rejected:", scrubSecrets(JSON.stringify({
29002
+ parentTaskId: parsed.body.parentTaskId,
29003
+ source: parsed.body.source ?? "api",
29004
+ contextKey: parsed.body.contextKey ?? parentTask?.contextKey,
29005
+ reason: error.message
29006
+ })));
29007
+ jsonError(res, error.message, 403);
29008
+ return true;
29009
+ }
28523
29010
  if (error instanceof TaskCreationBlockedError) {
28524
29011
  createTask.respond(res, 422, { error: error.reason, extension: error.extension });
28525
29012
  return true;
@@ -28895,7 +29382,8 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
28895
29382
  ...await getTaskSteeringFields(task),
28896
29383
  logs,
28897
29384
  attachments,
28898
- citations: await getTaskCitations(task.id)
29385
+ citations: await getTaskCitations(task.id),
29386
+ uiSpec: await getTaskUiSpec(task.id)
28899
29387
  });
28900
29388
  return true;
28901
29389
  }
@@ -29200,6 +29688,47 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
29200
29688
  updateTaskTagsRoute.respond(res, 200, { task });
29201
29689
  return true;
29202
29690
  }
29691
+ if (runTaskUiActionRoute.match(req.method, pathSegments)) {
29692
+ const parsed = await runTaskUiActionRoute.parse(req, res, pathSegments, queryParams);
29693
+ if (!parsed)
29694
+ return true;
29695
+ const task = await getTaskById2(parsed.params.id);
29696
+ if (!task) {
29697
+ jsonError(res, "Task not found", 404);
29698
+ return true;
29699
+ }
29700
+ if (!await canActOnOwnTask(req, myAgentId, task)) {
29701
+ jsonError(res, "Not authorized to act on this task", 403);
29702
+ return true;
29703
+ }
29704
+ const actor = await resolveSessionActor2(req, myAgentId);
29705
+ const tokenUserId = authUserId(getRequestAuth(req));
29706
+ const trustsPickedUser = process.env.TRUST_BODY_REQUESTED_BY_USER_ID !== "false";
29707
+ const actorUserId = actor.kind === "user" && (tokenUserId || trustsPickedUser) ? actor.userId ?? undefined : undefined;
29708
+ const result = await runTaskUiAction({
29709
+ taskId: task.id,
29710
+ actionId: parsed.params.actionId,
29711
+ surface: "web",
29712
+ actorUserId
29713
+ });
29714
+ switch (result.status) {
29715
+ case "forbidden":
29716
+ jsonError(res, "Only the task requester may run this action", 403);
29717
+ return true;
29718
+ case "unknown_action":
29719
+ jsonError(res, "This task declares no such action", 404);
29720
+ return true;
29721
+ case "disabled":
29722
+ jsonError(res, "Card actions are turned off (UI_SPEC_ACTIONS_ENABLED)", 409);
29723
+ return true;
29724
+ case "already_done":
29725
+ runTaskUiActionRoute.respond(res, 200, { status: "already_done" });
29726
+ return true;
29727
+ case "started":
29728
+ runTaskUiActionRoute.respond(res, 200, result);
29729
+ return true;
29730
+ }
29731
+ }
29203
29732
  if (resumeTaskRoute.match(req.method, pathSegments)) {
29204
29733
  const parsed = await resumeTaskRoute.parse(req, res, pathSegments, queryParams);
29205
29734
  if (!parsed)
@@ -41414,8 +41943,11 @@ async function handleScripts(req, res, pathSegments, queryParams, agentId) {
41414
41943
  // src/http/session-data.ts
41415
41944
  init_zod();
41416
41945
  init_db4();
41946
+ init_users();
41417
41947
  init_otel();
41418
41948
  init_types5();
41949
+ init_request_auth_context();
41950
+ init_secret_scrubber();
41419
41951
  init_route_def();
41420
41952
  init_session_access();
41421
41953
 
@@ -41577,7 +42109,9 @@ var SessionCostSummaryTotalsSchema = object2({
41577
42109
  attributableCostUsd: number2(),
41578
42110
  excludedCostUsd: number2(),
41579
42111
  excludedTaskCount: number2().int(),
41580
- subscriptionCostUsd: number2()
42112
+ subscriptionCostUsd: number2(),
42113
+ credentialUnattributedCostUsd: number2(),
42114
+ credentialUnattributedSessions: number2().int()
41581
42115
  });
41582
42116
  var SessionCostDailyRowSchema = object2({
41583
42117
  date: string2(),
@@ -41585,7 +42119,9 @@ var SessionCostDailyRowSchema = object2({
41585
42119
  inputTokens: number2().int(),
41586
42120
  outputTokens: number2().int(),
41587
42121
  sessions: number2().int(),
41588
- subscriptionCostUsd: number2()
42122
+ subscriptionCostUsd: number2(),
42123
+ credentialUnattributedCostUsd: number2(),
42124
+ credentialUnattributedSessions: number2().int()
41589
42125
  });
41590
42126
  var SessionCostByAgentRowSchema = object2({
41591
42127
  agentId: string2(),
@@ -41689,12 +42225,15 @@ var createSessionCostRoute = route({
41689
42225
  id: string2().uuid().optional(),
41690
42226
  sessionId: string2().min(1),
41691
42227
  agentId: string2().min(1),
42228
+ credentialKeyType: string2().regex(/^[A-Z][A-Z0-9_]{0,79}$/).nullable().optional(),
42229
+ credentialKeySuffix: string2().min(1).max(10).nullable().optional(),
42230
+ harness: ProviderNameSchema.nullable().optional(),
41692
42231
  totalCostUsd: number2(),
41693
42232
  harnessCostBilled: boolean().optional(),
41694
42233
  taskId: string2().optional(),
41695
42234
  inputTokens: number2().int().nonnegative().optional(),
41696
42235
  outputTokens: number2().int().nonnegative().optional(),
41697
- cacheReadTokens: number2().int().nonnegative().optional(),
42236
+ cacheReadTokens: number2().int().nonnegative().nullable().optional(),
41698
42237
  cacheWriteTokens: number2().int().nonnegative().nullable().optional(),
41699
42238
  cacheWrite5mTokens: number2().int().nonnegative().nullable().optional(),
41700
42239
  cacheWrite1hTokens: number2().int().nonnegative().nullable().optional(),
@@ -41713,7 +42252,9 @@ var createSessionCostRoute = route({
41713
42252
  description: "Cost record stored",
41714
42253
  schema: object2({ success: literal2(true), cost: SessionCostSchema })
41715
42254
  },
41716
- 400: { description: "Validation error" }
42255
+ 400: { description: "Validation error" },
42256
+ 403: { description: "Untrusted session attribution" },
42257
+ 409: { description: "Session identity conflict" }
41717
42258
  }
41718
42259
  });
41719
42260
  var getSessionCostSummaryRoute = route({
@@ -41832,6 +42373,21 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
41832
42373
  const parsed = await createSessionCostRoute.parse(req, res, pathSegments, queryParams);
41833
42374
  if (!parsed)
41834
42375
  return true;
42376
+ const auth = getRequestAuth(req);
42377
+ const trustedWorker = !auth?.page && (auth?.kind === "operator" || auth?.kind === "agent" && (auth.tokenKind === "runtime" || auth.tokenKind === "agent" && !await isScriptRunToken(auth.tokenId)) && auth.agentId === parsed.body.agentId);
42378
+ const hasAttribution = parsed.body.credentialKeyType != null || parsed.body.credentialKeySuffix != null || parsed.body.harness != null;
42379
+ if (hasAttribution && !trustedWorker) {
42380
+ jsonError(res, "Session attribution requires a worker or operator credential.", 403);
42381
+ return true;
42382
+ }
42383
+ if (auth?.kind === "agent" && auth.agentId !== parsed.body.agentId) {
42384
+ jsonError(res, "Session cost agent does not match the authenticated agent.", 403);
42385
+ return true;
42386
+ }
42387
+ if (parsed.body.credentialKeyType != null !== (parsed.body.credentialKeySuffix != null)) {
42388
+ jsonError(res, "Session credential type and suffix must be supplied together.", 400);
42389
+ return true;
42390
+ }
41835
42391
  try {
41836
42392
  const inputTokens = parsed.body.inputTokens ?? 0;
41837
42393
  const cachedInputTokens = parsed.body.cacheReadTokens ?? 0;
@@ -41841,8 +42397,8 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
41841
42397
  const bodyModels = parsed.body.models?.length ? parsed.body.models : null;
41842
42398
  const rowInputTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.inputTokens, 0) : inputTokens;
41843
42399
  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;
42400
+ const rowCacheReadTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheReadTokens, 0) : parsed.body.cacheReadTokens ?? null;
42401
+ const rowCacheWriteTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheWriteTokens, 0) : parsed.body.cacheWriteTokens ?? null;
41846
42402
  const harnessCostUsd = parsed.body.totalCostUsd > 0 ? parsed.body.totalCostUsd : null;
41847
42403
  const recomputed = await recomputeSessionCost({
41848
42404
  provider: parsed.body.provider,
@@ -41860,7 +42416,10 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
41860
42416
  atEpochMs: parsed.body.createdAt ?? Date.now()
41861
42417
  }, async (provider, lookupModel, tokenClass, atEpochMs) => (await getActivePricingRow2(provider, lookupModel, tokenClass, atEpochMs))?.pricePerMillionUsd ?? null);
41862
42418
  const { totalCostUsd, costSource } = recomputed;
41863
- const cost = await createSessionCost2({
42419
+ const { cost, created } = await insertSessionCost2({
42420
+ credentialKeyType: parsed.body.credentialKeyType,
42421
+ credentialKeySuffix: parsed.body.credentialKeySuffix,
42422
+ harness: parsed.body.harness,
41864
42423
  id: parsed.body.id,
41865
42424
  sessionId: parsed.body.sessionId,
41866
42425
  taskId: parsed.body.taskId || undefined,
@@ -41882,26 +42441,32 @@ async function handleSessionData(req, res, pathSegments, queryParams, myAgentId)
41882
42441
  cacheWrite1hTokens: parsed.body.cacheWrite1hTokens,
41883
42442
  modelBreakdown: recomputed.modelBreakdown
41884
42443
  });
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();
42444
+ if (created) {
42445
+ recordSessionCost2({
42446
+ totalCostUsd,
42447
+ harnessCostUsd: harnessCostUsd ?? undefined,
42448
+ harness: parsed.body.provider ?? "unknown",
42449
+ model,
42450
+ costSource,
42451
+ isError: parsed.body.isError ?? false,
42452
+ tokens: {
42453
+ input: rowInputTokens,
42454
+ output: rowOutputTokens,
42455
+ cacheRead: rowCacheReadTokens ?? 0,
42456
+ cacheWrite: rowCacheWriteTokens ?? 0,
42457
+ reasoning: parsed.body.reasoningOutputTokens ?? 0,
42458
+ thinking: parsed.body.thinkingTokens ?? 0
42459
+ }
42460
+ });
42461
+ incrementServerSessionsProcessed();
42462
+ }
41902
42463
  createSessionCostRoute.respond(res, 201, { success: true, cost });
41903
42464
  } catch (error) {
41904
- console.error("[HTTP] Failed to create session cost:", error);
42465
+ if (error instanceof SessionCostConflictError2) {
42466
+ jsonError(res, error.message, 409);
42467
+ return true;
42468
+ }
42469
+ console.error("[HTTP] Failed to create session cost:", scrubSecrets(String(error)));
41905
42470
  jsonError(res, "Failed to store session cost", 500);
41906
42471
  }
41907
42472
  return true;
@@ -41979,6 +42544,7 @@ init_rbac_roles();
41979
42544
  init_session_shares();
41980
42545
  init_steering2();
41981
42546
  init_task_citations2();
42547
+ init_task_ui_spec();
41982
42548
  init_users();
41983
42549
  init_rbac();
41984
42550
  init_auth2();
@@ -42148,6 +42714,7 @@ var SessionKeyFilterSchema = string2().transform((value, ctx) => {
42148
42714
  });
42149
42715
  var TaskWithSteeringSchema = AgentTaskSchema.extend({
42150
42716
  citations: array2(TaskCitationSchema),
42717
+ uiSpec: TaskUiSpecSchema.nullable(),
42151
42718
  isLeadTask: boolean(),
42152
42719
  supportedSteerModes: array2(SteerModeSchema)
42153
42720
  });
@@ -42956,9 +43523,10 @@ async function handleSessions(req, res, pathSegments, queryParams, myAgentId) {
42956
43523
  } : null;
42957
43524
  const chain = await withDispatchedTasks(await getRootTaskChain2(parsed.params.rootTaskId), sessionRoot.id, actor);
42958
43525
  const tasks = [root, ...chain];
42959
- const [steering, citations, approvals, read, groupKey] = await Promise.all([
43526
+ const [steering, citations, uiSpecs, approvals, read, groupKey] = await Promise.all([
42960
43527
  getTaskSteeringFieldsForTasks(tasks),
42961
43528
  getTaskCitationsForTasks(tasks.map((task) => task.id)),
43529
+ getTaskUiSpecsForTasks(tasks.map((task) => task.id)),
42962
43530
  getPendingApprovalsForTasks2(tasks.map((task) => task.id)),
42963
43531
  actor.kind === "user" && actor.userId ? getSessionReadState(sessionRoot.id, actor.userId, undefined, actor.readAll) : Promise.resolve(null),
42964
43532
  getSessionGroupKey(root)
@@ -42966,7 +43534,8 @@ async function handleSessions(req, res, pathSegments, queryParams, myAgentId) {
42966
43534
  const decorate = (task) => ({
42967
43535
  ...task,
42968
43536
  ...steering.get(task.id),
42969
- citations: citations.get(task.id)
43537
+ citations: citations.get(task.id),
43538
+ uiSpec: uiSpecs.get(task.id) ?? null
42970
43539
  });
42971
43540
  getSession.respond(res, 200, {
42972
43541
  root: decorate(root),
@@ -47241,7 +47810,7 @@ async function routeKapsoInbound(payload) {
47241
47810
  }
47242
47811
 
47243
47812
  // src/http/webhooks.ts
47244
- init_errors();
47813
+ init_errors2();
47245
47814
  init_constants3();
47246
47815
  init_github_host();
47247
47816
  init_secret_scrubber();
@@ -49577,7 +50146,7 @@ var httpServer = createHttpServer(async (req, res) => {
49577
50146
  });
49578
50147
  });
49579
50148
  var detachRealtime = attachRealtimeTransport(httpServer);
49580
- var { attachControllerTransport } = await import("./controllers-connect-61re6k1n.js");
50149
+ var { attachControllerTransport } = await import("./controllers-connect-ks155r0h.js");
49581
50150
  var detachControllers = attachControllerTransport(httpServer);
49582
50151
  var stopWorkerNudges = startWorkerNudgeListener();
49583
50152
  var taskAutoTitles = startTaskAutoTitleListener();
@@ -49608,7 +50177,7 @@ async function shutdown() {
49608
50177
  sessionsProcessed: getServerSessionsProcessed()
49609
50178
  });
49610
50179
  if (hasCapability("scheduling")) {
49611
- const { stopScheduler } = await import("./index-wjd56k1v.js");
50180
+ const { stopScheduler } = await import("./index-cxca2t8y.js");
49612
50181
  stopScheduler();
49613
50182
  }
49614
50183
  stopHeartbeat2();
@@ -49620,7 +50189,7 @@ async function shutdown() {
49620
50189
  await stopSlackApp2();
49621
50190
  await stopChatSdk();
49622
50191
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
49623
- const { stopOAuthKeepalive } = await import("./keepalive-rk0j0jvh.js");
50192
+ const { stopOAuthKeepalive } = await import("./keepalive-sh02349h.js");
49624
50193
  await stopOAuthKeepalive();
49625
50194
  }
49626
50195
  stopOAuthPendingGc();
@@ -49705,21 +50274,21 @@ try {
49705
50274
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
49706
50275
  }
49707
50276
  try {
49708
- const { ensurePricingSeeded } = await import("./boot-seeds-f99fjs5q.js");
50277
+ const { ensurePricingSeeded } = await import("./boot-seeds-ce7rvgq1.js");
49709
50278
  ensurePricingSeeded();
49710
- const { startPricingRefreshLoop } = await import("./pricing-refresh-f5tkgmw2.js");
50279
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-c6b325mk.js");
49711
50280
  startPricingRefreshLoop();
49712
50281
  } catch (err) {
49713
50282
  console.error("[startup] Failed to seed pricing rows:", err);
49714
50283
  }
49715
50284
  try {
49716
- const { ensureModelProfilesSeeded } = await import("./boot-seeds-f99fjs5q.js");
50285
+ const { ensureModelProfilesSeeded } = await import("./boot-seeds-ce7rvgq1.js");
49717
50286
  await ensureModelProfilesSeeded();
49718
50287
  } catch (err) {
49719
50288
  console.error("[startup] Failed to seed model profiles:", err);
49720
50289
  }
49721
50290
  try {
49722
- const { ensureRbacSeeded } = await import("./boot-seeds-f99fjs5q.js");
50291
+ const { ensureRbacSeeded } = await import("./boot-seeds-ce7rvgq1.js");
49723
50292
  ensureRbacSeeded();
49724
50293
  } catch (err) {
49725
50294
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -49727,13 +50296,13 @@ try {
49727
50296
  throw err;
49728
50297
  }
49729
50298
  try {
49730
- const { runAllSeeders } = await import("./index-ftywhyr0.js");
50299
+ const { runAllSeeders } = await import("./index-9zkchs9t.js");
49731
50300
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
49732
50301
  } catch (err) {
49733
50302
  console.error("[startup] Failed to seed built-in entities:", err);
49734
50303
  }
49735
50304
  try {
49736
- const { runImports } = await import("./index-tx9mc2ap.js");
50305
+ const { runImports } = await import("./index-rv89fvzf.js");
49737
50306
  await runImports();
49738
50307
  } catch (err) {
49739
50308
  console.error("[startup] File import failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
@@ -49784,7 +50353,7 @@ httpServer.listen(port, async () => {
49784
50353
  startChatSdk().catch((err) => {
49785
50354
  console.error("[chat-sdk] Failed to start, continuing without Chat SDK:", scrubSecrets(err instanceof Error ? err.message : String(err)));
49786
50355
  });
49787
- import("./agent-fs-provision-dmhnc38q.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
50356
+ import("./agent-fs-provision-b5dhdsbd.js").then(({ syncAgentFsOrgSwarmUrl }) => syncAgentFsOrgSwarmUrl(getConfiguredAppUrls()[0])).catch((err) => {
49788
50357
  console.warn("[agent-fs] Failed to set the org swarm URL:", scrubSecrets(err instanceof Error ? err.message : String(err)));
49789
50358
  });
49790
50359
  startQueueStallAlarm();
@@ -49799,25 +50368,25 @@ httpServer.listen(port, async () => {
49799
50368
  await initWorkflows2();
49800
50369
  await startScriptRunSupervisor(getMcpBaseUrl());
49801
50370
  if (hasCapability("scheduling")) {
49802
- const { startScheduler } = await import("./index-wjd56k1v.js");
49803
- const { getExecutorRegistry } = await import("./index-9sy2bh6n.js");
50371
+ const { startScheduler } = await import("./index-cxca2t8y.js");
50372
+ const { getExecutorRegistry } = await import("./index-25pvya7q.js");
49804
50373
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
49805
50374
  startScheduler(getExecutorRegistry(), intervalMs, {
49806
50375
  runId: globalState.__runId
49807
50376
  });
49808
50377
  }
49809
50378
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
49810
- const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-8xcyd3mc.js");
50379
+ const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-2t4859r5.js");
49811
50380
  startHeartbeat(parseHeartbeatIntervalMs(process.env.HEARTBEAT_INTERVAL_MS));
49812
50381
  }
49813
50382
  startPoolRouting();
49814
50383
  startRuntimeSupervisor();
49815
50384
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
49816
- const { startOAuthKeepalive } = await import("./keepalive-rk0j0jvh.js");
50385
+ const { startOAuthKeepalive } = await import("./keepalive-sh02349h.js");
49817
50386
  startOAuthKeepalive();
49818
50387
  }
49819
50388
  if (!isEnvFlagEnabled("OAUTH_REFRESH_SWEEP_DISABLE", false)) {
49820
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-2k3g2q4w.js");
50389
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-d9xedk66.js");
49821
50390
  startOAuthRefreshSweep();
49822
50391
  }
49823
50392
  startOAuthPendingGc();
@@ -49827,19 +50396,19 @@ httpServer.listen(port, async () => {
49827
50396
  startSavingsRollup(savingsRollupSql);
49828
50397
  startHumanFreeDrain();
49829
50398
  startTaskSearchBackfill();
49830
- import("./embedding-space-bafjr5f7.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
50399
+ import("./embedding-space-qhw4g68n.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
49831
50400
  setDeploymentEnvReader(getDeploymentEnvValue);
49832
50401
  return runEmbeddingMaintenance({ backfill: true });
49833
50402
  }).catch((err) => {
49834
50403
  console.error("[embedding-space] startup maintenance failed (non-fatal):", err);
49835
50404
  });
49836
- import("./boot-args-schema-0gqmkfbe.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
50405
+ import("./boot-args-schema-3gwy0f60.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
49837
50406
  console.error("[boot-args-schema] startup backfill failed (non-fatal):", err);
49838
50407
  });
49839
- import("./boot-scrub-sweep-ejd5dnrz.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
50408
+ import("./boot-scrub-sweep-7dkdzqxx.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
49840
50409
  console.error("[boot-scrub-sweep] startup scrub failed (non-fatal):", err);
49841
50410
  });
49842
- import("./session-source-backfill-bd7spzjd.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
50411
+ import("./session-source-backfill-v8mt0zwn.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
49843
50412
  console.error("[session-source-backfill] startup run failed (non-fatal):", err);
49844
50413
  });
49845
50414
  }).on("error", (err) => {