@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
package/src/be/db.ts CHANGED
@@ -1,5 +1,19 @@
1
+ import {
2
+ CREDENTIAL_SUFFIX_SQL,
3
+ CREDENTIAL_TYPE_SQL,
4
+ type CreateSessionCostInput,
5
+ insertSessionCost,
6
+ rowToSessionCost,
7
+ type SessionCostRow,
8
+ } from "./db/session-costs";
9
+
10
+ export {
11
+ type CreateSessionCostInput,
12
+ insertSessionCost,
13
+ SessionCostConflictError,
14
+ } from "./db/session-costs";
15
+
1
16
  import type { Database } from "bun:sqlite";
2
- import { chatgptSubscriptionModelId } from "@desplega/model-catalog";
3
17
  import pkg from "../../package.json";
4
18
  import { defaultAssetKey, normalizeAssetKey } from "../assets/key";
5
19
  import { sessionSourceKey, sessionThreadGroupKey } from "../assets/source-key";
@@ -10,6 +24,7 @@ import {
10
24
  matchesDefaultIdentityMd,
11
25
  } from "../prompts/defaults";
12
26
  import { realtimeBus } from "../realtime/bus";
27
+ import { TaskRoutingAuthorizationError } from "../tasks/errors";
13
28
  import { slackChannelFromContextKey } from "../tasks/slack-routing";
14
29
  import { _resolveIntegrationType, emitIntegrationConnected, telemetry } from "../telemetry";
15
30
  import { invalidateTelemetryUserRole, scheduleOrgDomainRecompute } from "../telemetry-identity";
@@ -89,8 +104,6 @@ import type {
89
104
  Service,
90
105
  ServiceStatus,
91
106
  SessionCost,
92
- SessionCostModelBreakdown,
93
- SessionCostSource,
94
107
  SessionLog,
95
108
  Skill,
96
109
  SkillFile,
@@ -132,7 +145,6 @@ import {
132
145
  OPEN_TASK_STATUSES,
133
146
  parseModelTier,
134
147
  SERVER_GENERATED_ATTACHMENT_CAPABILITY,
135
- SessionCostModelBreakdownSchema,
136
148
  } from "../types";
137
149
  import {
138
150
  CODEX_AUTH_FAILURE_BENCH_MS,
@@ -159,6 +171,15 @@ import {
159
171
  } from "../utils/identity-field-budget";
160
172
  import { activeModelBlock, type ModelFamily } from "../utils/model-rate-limit-windows";
161
173
  import { isEffectiveOutputSchema } from "../utils/output-schema";
174
+ import {
175
+ applyProviderQuotaReport,
176
+ assertProviderQuotaCapacity,
177
+ type ProviderAccountTelemetry,
178
+ parseProviderAccount,
179
+ type RateLimitReplacement,
180
+ scrubProviderQuotaReport,
181
+ } from "../utils/provider-account-telemetry";
182
+ import { extractReasoning } from "../utils/reasoning-events";
162
183
  import { getCurrentRequestUserId, getCurrentRunProvenance } from "../utils/request-auth-context";
163
184
  import { isRuntimePoolsEnabled } from "../utils/runtime-pools-flag";
164
185
  import {
@@ -167,7 +188,7 @@ import {
167
188
  scrubSecrets,
168
189
  } from "../utils/secret-scrubber";
169
190
  import {
170
- estimateClaudePlan,
191
+ codexPlanFromClaim,
171
192
  planAllowsModelFamily,
172
193
  SUBSCRIPTION_KEY_TYPES,
173
194
  } from "../utils/subscription-plans";
@@ -204,6 +225,7 @@ import { clearAgentModelProfileOnOverrideChange } from "./db/model-profiles";
204
225
  import { pageSearchSql } from "./db/page-search";
205
226
  import { parsePageThemeTokens } from "./db/page-theme-tokens";
206
227
  import { getDb, getDbClient } from "./db/runtime";
228
+ import { classifyClaudeUpdate } from "./db/session-log-reasoning";
207
229
  import {
208
230
  assertAssetKeyMovesAllowed,
209
231
  configureSessionMoveDependencies,
@@ -234,6 +256,14 @@ import {
234
256
  rowToAgentTaskSummary,
235
257
  } from "./db/tasks/read";
236
258
  import { configureTaskWriteDependencies, failTask } from "./db/tasks/write";
259
+ import {
260
+ USER_REFERENCE_COLUMNS_SQL,
261
+ type UserReferenceRow,
262
+ userReferenceRewriteSql,
263
+ WORKFLOW_CONTEXT_REMOVE_REQUESTER_SQL,
264
+ WORKFLOW_CONTEXT_SET_REQUESTER_SQL,
265
+ WORKFLOW_SEALED_CONTEXT_BY_REQUESTER_SQL,
266
+ } from "./db/user-references";
237
267
  import { tombstoneWorkflowIdempotencyKeys } from "./db/workflow-idempotency";
238
268
  import { deleteOrphanedRunDefinitions } from "./db/workflow-run-definitions";
239
269
  import {
@@ -429,6 +459,7 @@ export {
429
459
  getPausedTasksForAgent,
430
460
  getPendingTaskForAgent,
431
461
  getRecentlyCancelledTasksForAgent,
462
+ markWorkflowStepTaskSuperseded,
432
463
  overwriteTerminalTaskResultText,
433
464
  pauseTask,
434
465
  recordTaskProviderIfUnset,
@@ -2729,7 +2760,9 @@ export async function createTaskExtended(
2729
2760
  if (parent.routingAffinityInvalid && options.inheritParentRoutingAffinity !== false) {
2730
2761
  // Never let a corrupt parent affinity create an apparently untagged
2731
2762
  // continuation. This is a fail-closed quarantine, including recovery.
2732
- throw new Error(`Cannot continue task ${parent.id}: routing affinity is invalid.`);
2763
+ throw new TaskRoutingAuthorizationError(
2764
+ `Cannot continue task ${parent.id}: routing affinity is invalid.`,
2765
+ );
2733
2766
  }
2734
2767
  if (parent.routingAffinity && options.inheritParentRoutingAffinity !== false) {
2735
2768
  // Privilege cannot be shed by a continuation. A child can narrow or
@@ -2888,10 +2921,13 @@ export async function createTaskExtended(
2888
2921
  leadOnly: options.routingAffinity.leadOnly === true,
2889
2922
  targetAgentId,
2890
2923
  decision: "reject_ineligible_assignment",
2924
+ parentTaskId: options.parentTaskId,
2925
+ source: options.source,
2926
+ contextKey: options.contextKey,
2891
2927
  },
2892
2928
  });
2893
2929
  } catch {}
2894
- throw new Error(
2930
+ throw new TaskRoutingAuthorizationError(
2895
2931
  options.routingAffinity.leadOnly
2896
2932
  ? `Lead-only task routing affinity does not authorize assignment or offer to agent "${targetAgentId}".`
2897
2933
  : `Task routing affinity does not authorize assignment or offer to agent "${targetAgentId}".`,
@@ -4851,7 +4887,7 @@ export async function createSessionLogs(logs: {
4851
4887
  for (let start = 0; start < logs.lines.length; start += BATCH_SIZE) {
4852
4888
  // Yield to the event loop between batches.
4853
4889
  if (start > 0) await new Promise<void>((r) => setTimeout(r, 5));
4854
- const batch: string[] = [];
4890
+ const batch: Array<{ content: string; reasoning: ReturnType<typeof extractReasoning> }> = [];
4855
4891
  const end = Math.min(start + BATCH_SIZE, logs.lines.length);
4856
4892
  for (let i = start; i < end; i++) {
4857
4893
  const line = logs.lines[i];
@@ -4860,7 +4896,9 @@ export async function createSessionLogs(logs: {
4860
4896
  // content that is already scrubbed at the adapter emit site. We scrub
4861
4897
  // again here so any future write path that bypasses the adapter still
4862
4898
  // lands clean text in the persistent session_logs table.
4863
- batch.push(scrubSecrets(line));
4899
+ const content = scrubSecrets(line);
4900
+ // Parsed here, next to the scrub, so the write lock covers inserts only.
4901
+ batch.push({ content, reasoning: extractReasoning(logs.cli, content) });
4864
4902
  }
4865
4903
  await getDbClient().transaction(async (tx) => {
4866
4904
  // The worker flushes one (sessionId, iteration) in many POSTs, so the
@@ -4875,10 +4913,13 @@ export async function createSessionLogs(logs: {
4875
4913
  [logs.sessionId, logs.iteration],
4876
4914
  );
4877
4915
  let lineNumber = last ? last.lineNumber + 1 : 0;
4878
- for (const content of batch) {
4916
+ // Consecutive Claude thinking lines of one message just before the current line.
4917
+ let run = 0;
4918
+ let runMessageId: string | undefined;
4919
+ for (const [index, { content, reasoning }] of batch.entries()) {
4879
4920
  await tx.run(
4880
- `INSERT INTO session_logs (id, taskId, sessionId, iteration, cli, content, lineNumber, createdAt)
4881
- VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`,
4921
+ `INSERT INTO session_logs (id, taskId, sessionId, iteration, cli, content, lineNumber, createdAt, reasoningChars, reasoningKind)
4922
+ VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), ?, ?)`,
4882
4923
  [
4883
4924
  crypto.randomUUID(),
4884
4925
  logs.taskId ?? null,
@@ -4886,9 +4927,29 @@ export async function createSessionLogs(logs: {
4886
4927
  logs.iteration,
4887
4928
  logs.cli,
4888
4929
  content,
4889
- lineNumber++,
4930
+ lineNumber,
4931
+ reasoning.reasoning?.chars ?? null,
4932
+ reasoning.reasoning ? "reasoning" : null,
4890
4933
  ],
4891
4934
  );
4935
+ const toolMessageId = reasoning.toolUseMessageId;
4936
+ if (toolMessageId) {
4937
+ const before = runMessageId === toolMessageId ? run : 0;
4938
+ // Only a run of 2+ can hold an update. A run that reaches the batch
4939
+ // start may continue in an earlier POST, so the DB decides that case.
4940
+ if (before >= 2 || before === index) {
4941
+ await classifyClaudeUpdate(tx, logs.sessionId, toolMessageId, lineNumber);
4942
+ }
4943
+ }
4944
+ const messageId = reasoning.reasoning?.messageId;
4945
+ if (logs.cli === "claude" && messageId) {
4946
+ run = runMessageId === messageId ? run + 1 : 1;
4947
+ runMessageId = messageId;
4948
+ } else {
4949
+ run = 0;
4950
+ runMessageId = undefined;
4951
+ }
4952
+ lineNumber++;
4892
4953
  }
4893
4954
  });
4894
4955
  }
@@ -4935,160 +4996,8 @@ export async function getSessionLogsBySession(
4935
4996
  // Session Costs (aggregated cost data per session)
4936
4997
  // ============================================================================
4937
4998
 
4938
- type SessionCostRow = {
4939
- id: string;
4940
- sessionId: string;
4941
- taskId: string | null;
4942
- agentId: string;
4943
- totalCostUsd: number;
4944
- inputTokens: number;
4945
- outputTokens: number;
4946
- cacheReadTokens: number;
4947
- cacheWriteTokens: number;
4948
- // Migration 063 additions:
4949
- reasoningOutputTokens: number;
4950
- thinkingTokens: number;
4951
- durationMs: number;
4952
- numTurns: number | null;
4953
- model: string;
4954
- isError: number;
4955
- costSource: string;
4956
- harnessCostUsd: number | null;
4957
- cacheWrite5mTokens: number | null;
4958
- cacheWrite1hTokens: number | null;
4959
- modelBreakdown: string | null;
4960
- createdAt: string;
4961
- };
4962
-
4963
- function rowToSessionCost(row: SessionCostRow): SessionCost {
4964
- let modelBreakdown: SessionCostModelBreakdown[] | null = null;
4965
- if (row.modelBreakdown) {
4966
- try {
4967
- const parsed = SessionCostModelBreakdownSchema.array().safeParse(
4968
- JSON.parse(row.modelBreakdown),
4969
- );
4970
- if (parsed.success) modelBreakdown = parsed.data;
4971
- } catch {
4972
- // Corrupt JSON (manual edits, partial writes) must not fail the listing.
4973
- }
4974
- }
4975
-
4976
- return {
4977
- id: row.id,
4978
- sessionId: row.sessionId,
4979
- taskId: row.taskId ?? undefined,
4980
- agentId: row.agentId,
4981
- totalCostUsd: row.totalCostUsd,
4982
- inputTokens: row.inputTokens,
4983
- outputTokens: row.outputTokens,
4984
- cacheReadTokens: row.cacheReadTokens,
4985
- cacheWriteTokens: row.cacheWriteTokens,
4986
- reasoningOutputTokens: row.reasoningOutputTokens ?? 0,
4987
- thinkingTokens: row.thinkingTokens ?? 0,
4988
- durationMs: row.durationMs,
4989
- numTurns: row.numTurns,
4990
- model: row.model,
4991
- isError: row.isError === 1,
4992
- costSource: (row.costSource as SessionCostSource) ?? "harness",
4993
- harnessCostUsd: row.harnessCostUsd,
4994
- cacheWrite5mTokens: row.cacheWrite5mTokens,
4995
- cacheWrite1hTokens: row.cacheWrite1hTokens,
4996
- modelBreakdown,
4997
- createdAt: row.createdAt,
4998
- };
4999
- }
5000
-
5001
- export interface CreateSessionCostInput {
5002
- id?: string;
5003
- sessionId: string;
5004
- taskId?: string;
5005
- agentId: string;
5006
- totalCostUsd: number;
5007
- inputTokens?: number;
5008
- outputTokens?: number;
5009
- cacheReadTokens?: number;
5010
- cacheWriteTokens?: number;
5011
- // Migration 063 additions — adapters that have these numbers should pass
5012
- // them; defaulting to 0 preserves the old write shape for callers that don't.
5013
- reasoningOutputTokens?: number;
5014
- thinkingTokens?: number;
5015
- durationMs: number;
5016
- // Nullable: some adapters (claude when num_turns is absent) can't honestly
5017
- // report a turn count; we prefer null over a faked 1.
5018
- numTurns: number | null;
5019
- model: string;
5020
- isError?: boolean;
5021
- /**
5022
- * Phase 6 (migration 063 added 'unpriced'): where `totalCostUsd` came from.
5023
- * - 'harness' — value reported by the harness as-is (default).
5024
- * - 'pricing-table' — value recomputed by the API from `pricing` rows.
5025
- * - 'unpriced' — recompute attempted but no matching pricing rows;
5026
- * `totalCostUsd` is whatever the worker submitted.
5027
- * - 'estimated' — fallback token counts priced at an assumed model
5028
- * (amp with a failed thread export).
5029
- */
5030
- costSource?: SessionCostSource;
5031
- harnessCostUsd?: number | null;
5032
- cacheWrite5mTokens?: number | null;
5033
- cacheWrite1hTokens?: number | null;
5034
- modelBreakdown?: SessionCostModelBreakdown[] | null;
5035
- }
5036
-
5037
4999
  export async function createSessionCost(input: CreateSessionCostInput): Promise<SessionCost> {
5038
- const id = input.id ?? crypto.randomUUID();
5039
- const costSource: SessionCostSource = input.costSource ?? "harness";
5040
- const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
5041
- const thinkingTokens = input.thinkingTokens ?? 0;
5042
- await getDbClient().run(
5043
- `INSERT INTO session_costs (
5044
- id, sessionId, taskId, agentId,
5045
- totalCostUsd, inputTokens, outputTokens,
5046
- cacheReadTokens, cacheWriteTokens,
5047
- reasoningOutputTokens, thinkingTokens,
5048
- durationMs, numTurns, model, isError,
5049
- costSource, harnessCostUsd, cacheWrite5mTokens, cacheWrite1hTokens,
5050
- modelBreakdown, createdAt
5051
- )
5052
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
5053
- ON CONFLICT(id) DO NOTHING`,
5054
- [
5055
- id,
5056
- input.sessionId,
5057
- input.taskId ?? null,
5058
- input.agentId,
5059
- input.totalCostUsd,
5060
- input.inputTokens ?? 0,
5061
- input.outputTokens ?? 0,
5062
- input.cacheReadTokens ?? 0,
5063
- input.cacheWriteTokens ?? 0,
5064
- reasoningOutputTokens,
5065
- thinkingTokens,
5066
- input.durationMs,
5067
- input.numTurns,
5068
- // Cost rows group by the underlying model, while task configuration and
5069
- // session logs retain the pi route used to select credentials.
5070
- chatgptSubscriptionModelId(input.model)?.toLowerCase() ?? input.model,
5071
- input.isError ? 1 : 0,
5072
- costSource,
5073
- input.harnessCostUsd ?? null,
5074
- input.cacheWrite5mTokens ?? null,
5075
- input.cacheWrite1hTokens ?? null,
5076
- input.modelBreakdown
5077
- ? JSON.stringify(
5078
- input.modelBreakdown.map((entry) => ({
5079
- ...entry,
5080
- model: chatgptSubscriptionModelId(entry.model)?.toLowerCase() ?? entry.model,
5081
- })),
5082
- )
5083
- : null,
5084
- ],
5085
- );
5086
-
5087
- const row = await getDbClient().get<SessionCostRow>("SELECT * FROM session_costs WHERE id = ?", [
5088
- id,
5089
- ]);
5090
- if (!row) throw new Error("Session cost record is missing after insertion.");
5091
- return rowToSessionCost(row);
5000
+ return (await insertSessionCost(input)).cost;
5092
5001
  }
5093
5002
 
5094
5003
  export async function getSessionCostsByTaskId(taskId: string, limit = 500): Promise<SessionCost[]> {
@@ -5190,6 +5099,9 @@ export interface SessionCostSummaryTotals {
5190
5099
  excludedTaskCount: number;
5191
5100
  /** API-priced cost of sessions whose task ran on a subscription credential (`SUBSCRIPTION_KEY_TYPES`). */
5192
5101
  subscriptionCostUsd: number;
5102
+ /** Cost without an immutable credential identity. Its billing type is unknown. */
5103
+ credentialUnattributedCostUsd: number;
5104
+ credentialUnattributedSessions: number;
5193
5105
  }
5194
5106
 
5195
5107
  export interface SessionCostDailyRow {
@@ -5200,6 +5112,9 @@ export interface SessionCostDailyRow {
5200
5112
  sessions: number;
5201
5113
  /** Part of `costUsd` that ran on a subscription credential. */
5202
5114
  subscriptionCostUsd: number;
5115
+ /** Cost without an immutable credential identity. Its billing type is unknown. */
5116
+ credentialUnattributedCostUsd: number;
5117
+ credentialUnattributedSessions: number;
5203
5118
  }
5204
5119
 
5205
5120
  /**
@@ -5210,7 +5125,7 @@ export type PlanSource = "manual" | "detected" | "estimated";
5210
5125
 
5211
5126
  /** Spend per credential, for the subscription vs API comparison. */
5212
5127
  export interface SessionCostByCredentialRow {
5213
- /** `null` when the task recorded no credential (or the session has no task). */
5128
+ /** Null when the executing session reported no credential. */
5214
5129
  keyType: string | null;
5215
5130
  keySuffix: string | null;
5216
5131
  /** Label set on the API Keys page. */
@@ -5307,7 +5222,7 @@ export async function getSessionCostSummary(opts: {
5307
5222
  }
5308
5223
 
5309
5224
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5310
- const subscriptionSql = `t.credentialKeyType IN (${SUBSCRIPTION_KEY_TYPES.map((k) => `'${k}'`).join(", ")})`;
5225
+ const subscriptionSql = `${CREDENTIAL_TYPE_SQL} IN (${SUBSCRIPTION_KEY_TYPES.map((k) => `'${k}'`).join(", ")})`;
5311
5226
 
5312
5227
  // Totals
5313
5228
  type TotalsRow = {
@@ -5323,6 +5238,8 @@ export async function getSessionCostSummary(opts: {
5323
5238
  excludedCostUsd: number;
5324
5239
  excludedTaskCount: number;
5325
5240
  subscriptionCostUsd: number;
5241
+ credentialUnattributedCostUsd: number;
5242
+ credentialUnattributedSessions: number;
5326
5243
  };
5327
5244
 
5328
5245
  const totalsRow = await getDbClient().get<TotalsRow>(
@@ -5342,7 +5259,10 @@ export async function getSessionCostSummary(opts: {
5342
5259
  THEN sc.totalCostUsd ELSE 0 END), 0) as excludedCostUsd,
5343
5260
  COUNT(DISTINCT CASE WHEN ${HUMAN_FREE_SQL} THEN t.id END) as excludedTaskCount,
5344
5261
  COALESCE(SUM(CASE WHEN ${subscriptionSql}
5345
- THEN sc.totalCostUsd ELSE 0 END), 0) as subscriptionCostUsd
5262
+ THEN sc.totalCostUsd ELSE 0 END), 0) as subscriptionCostUsd,
5263
+ COALESCE(SUM(CASE WHEN ${CREDENTIAL_TYPE_SQL} IS NULL
5264
+ THEN sc.totalCostUsd ELSE 0 END), 0) as credentialUnattributedCostUsd,
5265
+ COUNT(CASE WHEN ${CREDENTIAL_TYPE_SQL} IS NULL THEN 1 END) as credentialUnattributedSessions
5346
5266
  ${from} ${where}`,
5347
5267
  params,
5348
5268
  );
@@ -5367,6 +5287,8 @@ export async function getSessionCostSummary(opts: {
5367
5287
  excludedCostUsd: 0,
5368
5288
  excludedTaskCount: 0,
5369
5289
  subscriptionCostUsd: 0,
5290
+ credentialUnattributedCostUsd: 0,
5291
+ credentialUnattributedSessions: 0,
5370
5292
  };
5371
5293
 
5372
5294
  // Daily breakdown
@@ -5380,6 +5302,8 @@ export async function getSessionCostSummary(opts: {
5380
5302
  outputTokens: number;
5381
5303
  sessions: number;
5382
5304
  subscriptionCostUsd: number;
5305
+ credentialUnattributedCostUsd: number;
5306
+ credentialUnattributedSessions: number;
5383
5307
  }>(
5384
5308
  `SELECT
5385
5309
  DATE(sc.createdAt) as date,
@@ -5388,7 +5312,10 @@ export async function getSessionCostSummary(opts: {
5388
5312
  COALESCE(SUM(sc.outputTokens), 0) as outputTokens,
5389
5313
  COUNT(*) as sessions,
5390
5314
  COALESCE(SUM(CASE WHEN ${subscriptionSql} THEN sc.totalCostUsd ELSE 0 END), 0)
5391
- as subscriptionCostUsd
5315
+ as subscriptionCostUsd,
5316
+ COALESCE(SUM(CASE WHEN ${CREDENTIAL_TYPE_SQL} IS NULL
5317
+ THEN sc.totalCostUsd ELSE 0 END), 0) as credentialUnattributedCostUsd,
5318
+ COUNT(CASE WHEN ${CREDENTIAL_TYPE_SQL} IS NULL THEN 1 END) as credentialUnattributedSessions
5392
5319
  ${from} ${where}
5393
5320
  GROUP BY DATE(sc.createdAt)
5394
5321
  ORDER BY date ASC`,
@@ -5448,8 +5375,8 @@ export async function getSessionCostSummary(opts: {
5448
5375
  >;
5449
5376
  const rows = await getDbClient().query<CredentialRow>(
5450
5377
  `SELECT
5451
- t.credentialKeyType as keyType,
5452
- t.credentialKeySuffix as keySuffix,
5378
+ ${CREDENTIAL_TYPE_SQL} as keyType,
5379
+ ${CREDENTIAL_SUFFIX_SQL} as keySuffix,
5453
5380
  COALESCE(SUM(sc.totalCostUsd), 0) as costUsd,
5454
5381
  COALESCE(SUM(sc.inputTokens), 0) as inputTokens,
5455
5382
  COALESCE(SUM(sc.outputTokens), 0) as outputTokens,
@@ -5457,7 +5384,7 @@ export async function getSessionCostSummary(opts: {
5457
5384
  MIN(sc.createdAt) as firstSessionAt,
5458
5385
  MAX(sc.createdAt) as lastSessionAt
5459
5386
  ${from} ${where}
5460
- GROUP BY t.credentialKeyType, t.credentialKeySuffix
5387
+ GROUP BY ${CREDENTIAL_TYPE_SQL}, ${CREDENTIAL_SUFFIX_SQL}
5461
5388
  ORDER BY costUsd DESC`,
5462
5389
  params,
5463
5390
  );
@@ -5510,7 +5437,11 @@ async function getCredentialLabels(): Promise<
5510
5437
  const key = credentialKey(row.keyType, row.keySuffix);
5511
5438
  const seen = labels.get(key);
5512
5439
  if (!seen) {
5513
- labels.set(key, { name: row.name, plan: row.plan, planSource: row.planSource });
5440
+ labels.set(key, {
5441
+ name: row.name,
5442
+ plan: row.planSource === "estimated" ? null : row.plan,
5443
+ planSource: row.planSource,
5444
+ });
5514
5445
  } else if (!seen.name && row.name) {
5515
5446
  seen.name = row.name;
5516
5447
  }
@@ -11890,9 +11821,11 @@ export interface ApiKeyStatus {
11890
11821
  provider: string;
11891
11822
  /** Latest provider-emitted rate-limit window snapshots, keyed by window type. */
11892
11823
  rateLimitWindows: RateLimitWindowTelemetry;
11824
+ providerAccount: ProviderAccountTelemetry | null;
11893
11825
  /** Subscription plan id (`SUBSCRIPTION_PLANS`), when known. */
11894
11826
  plan: string | null;
11895
11827
  planSource: PlanSource | null;
11828
+ detectedPlanRaw: string | null;
11896
11829
  /** When the CLI last rejected a model with `credits_required` on this key. */
11897
11830
  lastSeatMismatchAt: string | null;
11898
11831
  /** Model family of that rejection (`fable`, `opus`, ...). */
@@ -11906,7 +11839,10 @@ export interface ApiKeyStatus {
11906
11839
  updatedAt: string;
11907
11840
  }
11908
11841
 
11909
- type ApiKeyStatusRow = Omit<ApiKeyStatus, "rateLimitWindows"> & { rateLimitWindows: string | null };
11842
+ type ApiKeyStatusRow = Omit<ApiKeyStatus, "rateLimitWindows" | "providerAccount"> & {
11843
+ rateLimitWindows: string | null;
11844
+ providerAccount: string | null;
11845
+ };
11910
11846
 
11911
11847
  function parseRateLimitWindowsJson(value: string | null | undefined): RateLimitWindowTelemetry {
11912
11848
  if (!value) return {};
@@ -11922,7 +11858,11 @@ function parseRateLimitWindowsJson(value: string | null | undefined): RateLimitW
11922
11858
  }
11923
11859
 
11924
11860
  function rowToApiKeyStatus(row: ApiKeyStatusRow): ApiKeyStatus {
11925
- return { ...row, rateLimitWindows: parseRateLimitWindowsJson(row.rateLimitWindows) };
11861
+ return {
11862
+ ...row,
11863
+ rateLimitWindows: parseRateLimitWindowsJson(row.rateLimitWindows),
11864
+ providerAccount: parseProviderAccount(row.providerAccount),
11865
+ };
11926
11866
  }
11927
11867
 
11928
11868
  export interface AvailableKeyIndicesResult {
@@ -12088,18 +12028,19 @@ export async function recordKeyUsage(
12088
12028
  scopeId: string | null = null,
12089
12029
  /** Plan id the worker detected on the credential (for example from the Codex JWT). */
12090
12030
  plan: string | null = null,
12031
+ planRaw?: string | null,
12091
12032
  ): Promise<{ planChanged: boolean }> {
12092
12033
  const now = new Date().toISOString();
12093
- const client = getDbClient();
12094
- const effectiveScopeId = scopeId ?? "";
12095
-
12096
- // Upsert key status record. Sets `provider` on insert (auto-derived from
12097
- // keyType — see deriveProviderFromKeyType in src/utils/credentials.ts).
12098
- // The `name` column is left null on insert and only set via the
12099
- // setApiKeyName API endpoint when the user manually labels the key.
12100
- const provider = deriveProviderFromKeyType(keyType);
12101
- await client.run(
12102
- `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, lastUsedAt, totalUsageCount, provider, updatedAt)
12034
+ return getDbClient().transaction(async (client) => {
12035
+ const effectiveScopeId = scopeId ?? "";
12036
+
12037
+ // Upsert key status record. Sets `provider` on insert (auto-derived from
12038
+ // keyType, see deriveProviderFromKeyType in src/utils/credentials.ts).
12039
+ // The `name` column is left null on insert and only set via the
12040
+ // setApiKeyName API endpoint when the user manually labels the key.
12041
+ const provider = deriveProviderFromKeyType(keyType);
12042
+ await client.run(
12043
+ `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, lastUsedAt, totalUsageCount, provider, updatedAt)
12103
12044
  VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)
12104
12045
  ON CONFLICT(keyType, keySuffix, scope, scopeId)
12105
12046
  DO UPDATE SET
@@ -12107,29 +12048,53 @@ export async function recordKeyUsage(
12107
12048
  totalUsageCount = totalUsageCount + 1,
12108
12049
  keyIndex = excluded.keyIndex,
12109
12050
  updatedAt = excluded.updatedAt`,
12110
- [keyType, keySuffix, keyIndex, scope, effectiveScopeId, now, provider, now],
12111
- );
12051
+ [keyType, keySuffix, keyIndex, scope, effectiveScopeId, now, provider, now],
12052
+ );
12112
12053
 
12113
- // A detected plan replaces an estimate, never a plan the operator picked.
12114
- let planChanged = false;
12115
- if (plan) {
12116
- const result = await client.run(
12117
- `UPDATE api_key_status SET plan = ?, planSource = 'detected'
12054
+ const ambiguousPro =
12055
+ keyType === "CODEX_OAUTH" &&
12056
+ (plan === "chatgpt_pro" || plan === "chatgpt_pro_5x" || plan === "chatgpt_pro_500");
12057
+ let planChanged = false;
12058
+ const rawIdentity = planRaw
12059
+ ? scrubSecrets(planRaw).slice(0, 80)
12060
+ : keyType === "CODEX_OAUTH" && plan === "chatgpt_pro"
12061
+ ? "pro"
12062
+ : null;
12063
+ // A legacy plan report must not retain a contradictory raw claim.
12064
+ if (rawIdentity || plan) {
12065
+ await client.run(
12066
+ "UPDATE api_key_status SET detectedPlanRaw = ? WHERE keyType = ? AND keySuffix = ?",
12067
+ [rawIdentity, keyType, keySuffix],
12068
+ );
12069
+ }
12070
+ if (ambiguousPro || (keyType === "CODEX_OAUTH" && planRaw && !codexPlanFromClaim(planRaw))) {
12071
+ plan = null;
12072
+ const cleared = await client.run(
12073
+ "UPDATE api_key_status SET plan = NULL, planSource = 'detected' WHERE keyType = ? AND keySuffix = ? AND COALESCE(planSource, '') != 'manual' AND (plan IS NOT NULL OR planSource IS NOT 'detected')",
12074
+ [keyType, keySuffix],
12075
+ );
12076
+ planChanged = cleared.changes > 0;
12077
+ }
12078
+ // A detected plan replaces an estimate, never a plan the operator picked.
12079
+ if (plan) {
12080
+ const result = await client.run(
12081
+ `UPDATE api_key_status SET plan = ?, planSource = 'detected'
12118
12082
  WHERE keyType = ? AND keySuffix = ? AND COALESCE(planSource, '') != 'manual'
12119
12083
  AND (plan IS NOT ? OR planSource IS NOT 'detected')`,
12120
- [plan, keyType, keySuffix, plan],
12121
- );
12122
- planChanged = result.changes > 0;
12123
- }
12084
+ [plan, keyType, keySuffix, plan],
12085
+ );
12086
+ planChanged = result.changes > 0;
12087
+ }
12124
12088
 
12125
- // Record which key was used on the task
12126
- if (taskId) {
12127
- await client.run(
12128
- "UPDATE agent_tasks SET credentialKeySuffix = ?, credentialKeyType = ? WHERE id = ?",
12129
- [keySuffix, keyType, taskId],
12130
- );
12131
- }
12132
- return { planChanged };
12089
+ // Record which key was used on the task
12090
+ if (taskId) {
12091
+ await client.run(
12092
+ "UPDATE agent_tasks SET credentialKeySuffix = ?, credentialKeyType = ? WHERE id = ?",
12093
+ [keySuffix, keyType, taskId],
12094
+ );
12095
+ }
12096
+ return { planChanged };
12097
+ });
12133
12098
  }
12134
12099
 
12135
12100
  /**
@@ -12244,34 +12209,6 @@ export async function recordKeyAuthFailure(
12244
12209
  });
12245
12210
  }
12246
12211
 
12247
- /**
12248
- * Merges reported window snapshots into the stored ones, one window type at a
12249
- * time. A reported entry replaces the stored entry unless the stored entry was
12250
- * observed strictly later (`lastSeenAt`), so an older `allowed` snapshot that
12251
- * arrives after a terminal rejection cannot reopen an exhausted window. An
12252
- * unparseable `lastSeenAt` on either side falls back to "reported wins".
12253
- */
12254
- function mergeRateLimitWindowTelemetry(
12255
- stored: RateLimitWindowTelemetry,
12256
- reported: RateLimitWindowTelemetry,
12257
- ): RateLimitWindowTelemetry {
12258
- const merged: RateLimitWindowTelemetry = { ...stored };
12259
- for (const [type, entry] of Object.entries(reported)) {
12260
- const current = merged[type];
12261
- const currentSeenMs = current ? Date.parse(current.lastSeenAt) : Number.NaN;
12262
- const reportedSeenMs = Date.parse(entry.lastSeenAt);
12263
- if (
12264
- Number.isFinite(currentSeenMs) &&
12265
- Number.isFinite(reportedSeenMs) &&
12266
- currentSeenMs > reportedSeenMs
12267
- ) {
12268
- continue;
12269
- }
12270
- merged[type] = entry;
12271
- }
12272
- return merged;
12273
- }
12274
-
12275
12212
  /**
12276
12213
  * Persists reported window snapshots for a key. Admission
12277
12214
  * (`getAvailableKeyIndices`) reads these windows, so the read-merge-write
@@ -12286,81 +12223,54 @@ export async function recordKeyRateLimitWindows(
12286
12223
  windows: RateLimitWindowTelemetry,
12287
12224
  scope = "global",
12288
12225
  scopeId: string | null = null,
12289
- ): Promise<{ planChanged: boolean }> {
12290
- if (Object.keys(windows).length === 0) return { planChanged: false };
12226
+ account?: ProviderAccountTelemetry,
12227
+ replace: RateLimitReplacement[] = [],
12228
+ ): Promise<void> {
12229
+ if (Object.keys(windows).length === 0 && !account && !replace.length) return;
12291
12230
 
12292
12231
  const now = new Date().toISOString();
12293
12232
  const effectiveScopeId = scopeId ?? "";
12294
12233
  const provider = deriveProviderFromKeyType(keyType);
12295
- const merged = await getDbClient().transaction(async (tx) => {
12296
- const existing = await tx.get<{ rateLimitWindows: string | null }>(
12297
- `SELECT rateLimitWindows FROM api_key_status
12234
+ await getDbClient().transaction(async (tx) => {
12235
+ const existing = await tx.get<{
12236
+ rateLimitWindows: string | null;
12237
+ providerAccount: string | null;
12238
+ }>(
12239
+ `SELECT rateLimitWindows, providerAccount FROM api_key_status
12298
12240
  WHERE keyType = ? AND keySuffix = ? AND scope = ? AND scopeId = ?`,
12299
12241
  [keyType, keySuffix, scope, effectiveScopeId],
12300
12242
  );
12301
- const mergedWindows = mergeRateLimitWindowTelemetry(
12302
- parseRateLimitWindowsJson(existing?.rateLimitWindows),
12303
- windows,
12243
+ const { windows: mergedWindows, account: mergedAccount } = applyProviderQuotaReport(
12244
+ {
12245
+ windows: parseRateLimitWindowsJson(existing?.rateLimitWindows),
12246
+ account: parseProviderAccount(existing?.providerAccount),
12247
+ },
12248
+ scrubProviderQuotaReport({ windows, account, replace }),
12304
12249
  );
12305
- const serialized = JSON.stringify(mergedWindows);
12306
-
12250
+ assertProviderQuotaCapacity({ windows: mergedWindows, account: mergedAccount });
12307
12251
  await tx.run(
12308
- `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, rateLimitWindows, provider, updatedAt)
12309
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
12252
+ `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, rateLimitWindows, providerAccount, provider, updatedAt)
12253
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
12310
12254
  ON CONFLICT(keyType, keySuffix, scope, scopeId)
12311
12255
  DO UPDATE SET
12312
12256
  rateLimitWindows = excluded.rateLimitWindows,
12257
+ providerAccount = excluded.providerAccount,
12313
12258
  keyIndex = excluded.keyIndex,
12314
12259
  provider = excluded.provider,
12315
12260
  updatedAt = excluded.updatedAt`,
12316
- [keyType, keySuffix, keyIndex, scope, effectiveScopeId, serialized, provider, now],
12261
+ [
12262
+ keyType,
12263
+ keySuffix,
12264
+ keyIndex,
12265
+ scope,
12266
+ effectiveScopeId,
12267
+ JSON.stringify(mergedWindows),
12268
+ mergedAccount ? JSON.stringify(mergedAccount) : null,
12269
+ provider,
12270
+ now,
12271
+ ],
12317
12272
  );
12318
- return mergedWindows;
12319
12273
  });
12320
-
12321
- const planChanged =
12322
- keyType === "CLAUDE_CODE_OAUTH_TOKEN" && (await refreshEstimatedClaudePlan(keySuffix, merged));
12323
- return { planChanged };
12324
- }
12325
-
12326
- const WEEK_SECONDS = 7 * 24 * 3600;
12327
-
12328
- /**
12329
- * Estimate the plan of a Claude credential from its 7-day window (see
12330
- * `estimateClaudePlan`), unless a stronger source already set it. Returns
12331
- * true when the stored plan changed.
12332
- */
12333
- async function refreshEstimatedClaudePlan(
12334
- keySuffix: string,
12335
- windows: RateLimitWindowTelemetry,
12336
- ): Promise<boolean> {
12337
- const week = windows.seven_day;
12338
- if (!week?.utilization || !week.resetsAt) return false;
12339
- const client = getDbClient();
12340
- const stronger = await client.get<{ found: number }>(
12341
- `SELECT 1 as found FROM api_key_status
12342
- WHERE keyType = 'CLAUDE_CODE_OAUTH_TOKEN' AND keySuffix = ? AND planSource IN ('manual', 'detected')
12343
- LIMIT 1`,
12344
- [keySuffix],
12345
- );
12346
- if (stronger) return false;
12347
- const windowStart = new Date((week.resetsAt - WEEK_SECONDS) * 1000).toISOString();
12348
- const spend = await client.get<{ spendUsd: number }>(
12349
- `SELECT COALESCE(SUM(sc.totalCostUsd), 0) as spendUsd
12350
- FROM session_costs sc JOIN agent_tasks t ON t.id = sc.taskId
12351
- WHERE t.credentialKeyType = 'CLAUDE_CODE_OAUTH_TOKEN' AND t.credentialKeySuffix = ?
12352
- AND sc.createdAt >= ?`,
12353
- [keySuffix, windowStart],
12354
- );
12355
- const plan = estimateClaudePlan(week.utilization, spend?.spendUsd ?? 0);
12356
- if (!plan) return false;
12357
- const result = await client.run(
12358
- `UPDATE api_key_status SET plan = ?, planSource = 'estimated'
12359
- WHERE keyType = 'CLAUDE_CODE_OAUTH_TOKEN' AND keySuffix = ?
12360
- AND COALESCE(planSource, 'estimated') = 'estimated' AND plan IS NOT ?`,
12361
- [plan, keySuffix, plan],
12362
- );
12363
- return result.changes > 0;
12364
12274
  }
12365
12275
 
12366
12276
  /**
@@ -12479,36 +12389,30 @@ export interface KeyCostSummary {
12479
12389
  }
12480
12390
 
12481
12391
  /**
12482
- * Aggregate cost data per API key by joining session_costs through agent_tasks.
12392
+ * Aggregate cost data using immutable session credentials (legacy rows: the task's).
12483
12393
  */
12484
12394
  export async function getKeyCostSummary(keyType?: string): Promise<KeyCostSummary[]> {
12485
- const conditions = ["t.credentialKeySuffix IS NOT NULL"];
12395
+ const conditions = [`${CREDENTIAL_SUFFIX_SQL} IS NOT NULL`];
12486
12396
  const params: string[] = [];
12487
12397
 
12488
12398
  if (keyType) {
12489
- conditions.push("t.credentialKeyType = ?");
12399
+ conditions.push(`${CREDENTIAL_TYPE_SQL} = ?`);
12490
12400
  params.push(keyType);
12491
12401
  }
12492
12402
 
12493
12403
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
12494
- // Phase 13: INNER JOIN -> LEFT JOIN. The `WHERE t.credentialKeySuffix IS NOT NULL`
12495
- // still filters out rows whose taskId doesn't link to a task with credentials,
12496
- // but switching to LEFT JOIN means a future change that drops the WHERE
12497
- // (or a debugging query that wants orphan rows visible) doesn't silently
12498
- // disappear them. Equivalent for the current `WHERE … IS NOT NULL` filter;
12499
- // makes the query's intent (cost rows owned by a credential) explicit.
12500
12404
  return getDbClient().query<KeyCostSummary>(
12501
12405
  `SELECT
12502
- t.credentialKeyType as keyType,
12503
- t.credentialKeySuffix as keySuffix,
12406
+ ${CREDENTIAL_TYPE_SQL} as keyType,
12407
+ ${CREDENTIAL_SUFFIX_SQL} as keySuffix,
12504
12408
  COALESCE(SUM(sc.totalCostUsd), 0) as totalCost,
12505
12409
  COALESCE(SUM(sc.inputTokens), 0) as totalInputTokens,
12506
12410
  COALESCE(SUM(sc.outputTokens), 0) as totalOutputTokens,
12507
12411
  COUNT(DISTINCT sc.taskId) as taskCount
12508
12412
  FROM session_costs sc
12509
- LEFT JOIN agent_tasks t ON sc.taskId = t.id
12413
+ LEFT JOIN agent_tasks t INDEXED BY idx_agent_tasks_usage_cover ON t.id = sc.taskId
12510
12414
  ${where}
12511
- GROUP BY t.credentialKeyType, t.credentialKeySuffix`,
12415
+ GROUP BY ${CREDENTIAL_TYPE_SQL}, ${CREDENTIAL_SUFFIX_SQL}`,
12512
12416
  params,
12513
12417
  );
12514
12418
  }
@@ -12530,6 +12434,7 @@ type UserRow = {
12530
12434
  metadata: string | null;
12531
12435
  dailyBudgetUsd: number | null;
12532
12436
  status: string;
12437
+ mergedIntoUserId: string | null;
12533
12438
  createdAt: string;
12534
12439
  lastUpdatedAt: string;
12535
12440
  };
@@ -12547,6 +12452,7 @@ function rowToUser(row: UserRow): User {
12547
12452
  metadata: row.metadata ? (JSON.parse(row.metadata) as Record<string, unknown>) : undefined,
12548
12453
  dailyBudgetUsd: row.dailyBudgetUsd ?? null,
12549
12454
  status: (row.status as "invited" | "active" | "suspended") ?? "active",
12455
+ ...(row.mergedIntoUserId ? { mergedIntoUserId: row.mergedIntoUserId } : {}),
12550
12456
  createdAt: row.createdAt,
12551
12457
  lastUpdatedAt: row.lastUpdatedAt,
12552
12458
  };
@@ -12679,15 +12585,14 @@ export async function updateUser(
12679
12585
  return row ? rowToUser(row) : null;
12680
12586
  }
12681
12587
 
12682
- type UserReferenceRow = {
12683
- tableName: string;
12684
- columnName: string;
12685
- };
12686
-
12687
- function quoteSqlIdentifier(identifier: string): string {
12688
- return `"${identifier.replaceAll('"', '""')}"`;
12689
- }
12690
-
12588
+ /**
12589
+ * Delete a user in one transaction, moving every retained reference to
12590
+ * `replacementUserId` (or clearing it). Used by the manage-user tool. The
12591
+ * merge route queues the same rewrite as a background job instead
12592
+ * (src/be/user-merge-jobs.ts, built on the same SQL from
12593
+ * src/be/db/user-references.ts), because on a large database this holds the
12594
+ * event loop for minutes.
12595
+ */
12691
12596
  export async function deleteUser(id: string, replacementUserId?: string): Promise<boolean> {
12692
12597
  if (replacementUserId === id) {
12693
12598
  throw new Error("Replacement user must differ from deleted user");
@@ -12717,28 +12622,7 @@ export async function deleteUser(id: string, replacementUserId?: string): Promis
12717
12622
  // Migration 103 accidentally dropped the scheduled_tasks audit FKs while
12718
12623
  // recreating that table, so discover those two known logical references as
12719
12624
  // well until the table is next rebuilt with its original constraints.
12720
- const references = await tx.query<UserReferenceRow>(
12721
- `SELECT tables.name AS tableName, foreign_keys."from" AS columnName
12722
- FROM sqlite_schema AS tables
12723
- JOIN pragma_foreign_key_list(tables.name) AS foreign_keys
12724
- JOIN pragma_table_info(tables.name) AS columns
12725
- ON columns.name = foreign_keys."from"
12726
- WHERE tables.type = 'table'
12727
- AND foreign_keys."table" = 'users'
12728
- AND foreign_keys.on_delete IN ('NO ACTION', 'RESTRICT')
12729
- AND columns."notnull" = 0
12730
- UNION ALL
12731
- SELECT 'scheduled_tasks' AS tableName, columns.name AS columnName
12732
- FROM pragma_table_info('scheduled_tasks') AS columns
12733
- WHERE columns.name IN ('created_by', 'updated_by')
12734
- AND columns."notnull" = 0
12735
- AND NOT EXISTS (
12736
- SELECT 1
12737
- FROM pragma_foreign_key_list('scheduled_tasks') AS foreign_keys
12738
- WHERE foreign_keys."from" = columns.name
12739
- AND foreign_keys."table" = 'users'
12740
- )`,
12741
- );
12625
+ const references = await tx.query<UserReferenceRow>(USER_REFERENCE_COLUMNS_SQL);
12742
12626
  const replacement = replacementUserId ?? null;
12743
12627
  // The human-free rule only asks whether a task's requester or its workflow
12744
12628
  // run's creator is NULL, so only clearing them (no replacement) can change a
@@ -12755,22 +12639,15 @@ export async function deleteUser(id: string, replacementUserId?: string): Promis
12755
12639
  [id, id],
12756
12640
  )
12757
12641
  ).map((row) => row.id);
12758
- for (const reference of references) {
12759
- const table = quoteSqlIdentifier(reference.tableName);
12760
- const column = quoteSqlIdentifier(reference.columnName);
12761
- await tx.run(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ?`, [replacement, id]);
12762
- }
12763
-
12764
12642
  // Workflow context is persisted JSON rather than a relational column, but
12765
12643
  // it exposes the same requester identity to downstream interpolation. Keep
12766
12644
  // it consistent with workflow_runs.created_by inside this transaction.
12767
- // The sealed replay copy is what a resume reads, so rewrite it first, while
12768
- // the scrubbed column still matches the filter.
12645
+ // Migration 319 indexes the context requester expression, so these passes
12646
+ // touch only this user's runs instead of parsing the JSON of every row
12647
+ // (153 s on 493k prod rows). The sealed replay copy is what a resume
12648
+ // reads, so rewrite it first, while the scrubbed column still matches.
12769
12649
  const sealedContexts = await tx.query<{ id: string; context_replay: string }>(
12770
- `SELECT id, context_replay FROM workflow_runs
12771
- WHERE context_replay IS NOT NULL
12772
- AND json_valid(context)
12773
- AND json_extract(context, '$.swarm.requestedByUserId') = ?`,
12650
+ WORKFLOW_SEALED_CONTEXT_BY_REQUESTER_SQL,
12774
12651
  [id],
12775
12652
  );
12776
12653
  for (const row of sealedContexts) {
@@ -12792,21 +12669,15 @@ export async function deleteUser(id: string, replacementUserId?: string): Promis
12792
12669
  ]);
12793
12670
  }
12794
12671
  if (replacementUserId) {
12795
- await tx.run(
12796
- `UPDATE workflow_runs
12797
- SET context = json_set(context, '$.swarm.requestedByUserId', ?)
12798
- WHERE json_valid(context)
12799
- AND json_extract(context, '$.swarm.requestedByUserId') = ?`,
12800
- [replacementUserId, id],
12801
- );
12672
+ await tx.run(WORKFLOW_CONTEXT_SET_REQUESTER_SQL, [replacementUserId, id]);
12802
12673
  } else {
12803
- await tx.run(
12804
- `UPDATE workflow_runs
12805
- SET context = json_remove(context, '$.swarm.requestedByUserId')
12806
- WHERE json_valid(context)
12807
- AND json_extract(context, '$.swarm.requestedByUserId') = ?`,
12808
- [id],
12809
- );
12674
+ await tx.run(WORKFLOW_CONTEXT_REMOVE_REQUESTER_SQL, [id]);
12675
+ }
12676
+
12677
+ // Migration 319 indexes every discovered column (the user-delete-perf test
12678
+ // pins the plans), so these are index lookups rather than table scans.
12679
+ for (const reference of references) {
12680
+ await tx.run(userReferenceRewriteSql(reference), [replacement, id]);
12810
12681
  }
12811
12682
 
12812
12683
  await reclassifyTaskHumanFree(reclassifySeedIds);