@desplega.ai/agent-swarm 2.8.3 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (597) hide show
  1. package/dist/acp-adapter-g909b5hw.js +16 -0
  2. package/dist/acp-targets-ny75x1qy.js +23 -0
  3. package/dist/{actions-ewz7bp4g.js → actions-b9qgrmeq.js} +82 -21
  4. package/dist/agent-fs-provision-b5dhdsbd.js +27 -0
  5. package/dist/{amp-adapter-f25tqhnf.js → amp-adapter-vtax2c9s.js} +3 -3
  6. package/dist/{anthropic-messages-jkva0zps.js → anthropic-messages-r5xf5hqw.js} +37 -37
  7. package/dist/{app-mkptw0k7.js → app-g2z15hax.js} +9 -4
  8. package/dist/approval-notifications-yt13wp8r.js +23 -0
  9. package/dist/{assistant-c47rfe77.js → assistant-2cgfxsgk.js} +56 -33
  10. package/dist/{azure-openai-responses-wgtqkbr3.js → azure-openai-responses-590s1eea.js} +10 -10
  11. package/dist/{boot-args-schema-4vb0xsat.js → boot-args-schema-3gwy0f60.js} +1 -1
  12. package/dist/{boot-reembed-htr73hbs.js → boot-reembed-92g7s5zp.js} +1 -1
  13. package/dist/{boot-reembed-1ghy2sab.js → boot-reembed-mywmyp4s.js} +1 -1
  14. package/dist/{boot-scrub-sweep-yrytg42z.js → boot-scrub-sweep-7dkdzqxx.js} +84 -13
  15. package/dist/{boot-seeds-n2b3dx4e.js → boot-seeds-ce7rvgq1.js} +4 -4
  16. package/dist/{boxd-jmfqgkqa.js → boxd-wn235q80.js} +7 -7
  17. package/dist/claude-adapter-3m4q7735.js +28 -0
  18. package/dist/{claude-managed-adapter-hddmxjyj.js → claude-managed-adapter-t8nfgcgz.js} +4 -4
  19. package/dist/{claude-managed-setup-hfvry1bd.js → claude-managed-setup-c217draw.js} +10 -10
  20. package/dist/{claude-sdk-session-0hamqzc7.js → claude-sdk-session-7fbqm51z.js} +9386 -9196
  21. package/dist/{cli-yjdgea32.js → cli-1jx0srjt.js} +17 -17
  22. package/dist/{cli-sdvcrq5x.js → cli-1jykg0py.js} +18 -14
  23. package/dist/{cli-k96cecs7.js → cli-2czxfnvj.js} +1221 -357
  24. package/dist/{cli-qmqt520k.js → cli-2dq9yv8p.js} +2 -2
  25. package/dist/{cli-e2w34h6z.js → cli-2xs8tsf7.js} +132 -85
  26. package/dist/{cli-z8cvws4c.js → cli-2yjj3e31.js} +907 -56
  27. package/dist/{cli-mdpbjnzq.js → cli-32djehja.js} +42 -42
  28. package/dist/{cli-gpz1d0t2.js → cli-3j873zxq.js} +4 -4
  29. package/dist/cli-43ms35q9.js +270 -0
  30. package/dist/cli-47hz21se.js +25584 -0
  31. package/dist/{cli-n515ex5z.js → cli-4ymxrwg5.js} +16 -16
  32. package/dist/{cli-f1kwb5fc.js → cli-5a6pqy45.js} +333 -21
  33. package/dist/{cli-93t5s4zq.js → cli-5gpqgs8b.js} +2 -2
  34. package/dist/{cli-15204js0.js → cli-6237rnyr.js} +1 -1
  35. package/dist/{cli-4ax9mvvg.js → cli-67mwzr35.js} +9 -9
  36. package/dist/{cli-t5ys4ebm.js → cli-6945ywhr.js} +3 -3
  37. package/dist/{cli-0bcgyj5b.js → cli-6ehs4mta.js} +87 -8
  38. package/dist/{cli-6yygkr0w.js → cli-6ym4jhzp.js} +15 -7
  39. package/dist/{cli-8bpgbr8k.js → cli-7evph51z.js} +5 -5
  40. package/dist/{cli-dtdht77h.js → cli-7mv4h3sn.js} +2 -2
  41. package/dist/{cli-nx2n3z6p.js → cli-7sf9sb0w.js} +3 -2
  42. package/dist/{cli-pe4d96rb.js → cli-7zm3b3f5.js} +1 -1
  43. package/dist/cli-8zh9nrew.js +78 -0
  44. package/dist/cli-9ttx00s3.js +137 -0
  45. package/dist/{cli-x6t50dmw.js → cli-9w8712tq.js} +620 -281
  46. package/dist/{cli-8476gtwf.js → cli-b6px1k1q.js} +1 -1
  47. package/dist/{cli-k2rw11py.js → cli-b91nz213.js} +5 -5
  48. package/dist/{cli-7c5tgqhf.js → cli-bg63qmsx.js} +10 -10
  49. package/dist/{cli-qps8je6j.js → cli-bkjdknnp.js} +54 -10
  50. package/dist/{cli-gn9y6fn7.js → cli-bnqncekd.js} +2 -2
  51. package/dist/{cli-s7zz734a.js → cli-br0924pw.js} +1 -1
  52. package/dist/{cli-h9yy18gy.js → cli-ctx0b85j.js} +5484 -5078
  53. package/dist/{cli-0vksaxvr.js → cli-dgs10ttj.js} +2 -2
  54. package/dist/cli-dqgnbnxs.js +132 -0
  55. package/dist/{cli-q6mfk1ej.js → cli-dzzh58sy.js} +2 -2
  56. package/dist/{cli-2znm3dzj.js → cli-eds5xnsz.js} +2 -2
  57. package/dist/{cli-c0xjnr8z.js → cli-f3jyzq4g.js} +2 -2
  58. package/dist/cli-f8x9drqr.js +84 -0
  59. package/dist/{cli-ztq5z4e1.js → cli-f9gz2vyj.js} +6 -6
  60. package/dist/{cli-bhsfbmk8.js → cli-fh97xn30.js} +93 -44
  61. package/dist/cli-fkef327x.js +103 -0
  62. package/dist/{cli-fsgttth8.js → cli-g0vv9dg4.js} +13 -13
  63. package/dist/{cli-kd56bmk4.js → cli-gabsjg8x.js} +3 -1
  64. package/dist/{cli-1m96dc36.js → cli-gfy38pvt.js} +3 -3
  65. package/dist/{cli-922z7gwm.js → cli-h9yqfzx9.js} +15 -11
  66. package/dist/{cli-5a7szzfh.js → cli-hnamkvnc.js} +2 -2
  67. package/dist/{cli-c3ng0mb4.js → cli-j7svy295.js} +71 -818
  68. package/dist/{cli-yss07azk.js → cli-jaw5v1sy.js} +3 -3
  69. package/dist/cli-jkw6ptfw.js +921 -0
  70. package/dist/{cli-s8p8hhty.js → cli-jm0hvmz2.js} +2 -2
  71. package/dist/{cli-knva3nmx.js → cli-jwampxxq.js} +8 -6
  72. package/dist/cli-kj0hyr43.js +51 -0
  73. package/dist/{cli-tnzebztn.js → cli-kpgcm7xy.js} +13 -1
  74. package/dist/{cli-9zmb7ptc.js → cli-kxx4k2jw.js} +8 -753
  75. package/dist/{cli-am1ptset.js → cli-m7c2380k.js} +208 -194
  76. package/dist/{cli-kw44j53p.js → cli-m7zvgt57.js} +45 -38
  77. package/dist/{cli-504akrp9.js → cli-meydjstb.js} +3 -3
  78. package/dist/{cli-54qr8mcd.js → cli-mhapr559.js} +4 -4
  79. package/dist/{cli-tf79ryyy.js → cli-mjw0yf82.js} +3 -3
  80. package/dist/{cli-rjvsf9qa.js → cli-mkwkwq81.js} +14 -11
  81. package/dist/{cli-n30e0hcp.js → cli-mna6pmfx.js} +2 -2
  82. package/dist/{cli-awwptga4.js → cli-mw620q3n.js} +1 -1
  83. package/dist/{cli-6wj7p986.js → cli-n3qe7tyr.js} +172 -168
  84. package/dist/{cli-4dpkjc2e.js → cli-nafvvsp8.js} +9 -9
  85. package/dist/{cli-sg27rk2t.js → cli-nbt14he0.js} +25 -19
  86. package/dist/{cli-7akn6ze9.js → cli-nh7x3133.js} +7 -28
  87. package/dist/{cli-zdaypkq9.js → cli-p4kckx1z.js} +285 -97
  88. package/dist/{cli-n5t077me.js → cli-pb2ay3sh.js} +10 -3
  89. package/dist/{cli-t4dv07kr.js → cli-psffsanb.js} +4 -3
  90. package/dist/{cli-mwwmka77.js → cli-pyjn0qhk.js} +2712 -268
  91. package/dist/{cli-emekyyhr.js → cli-q2d3e1k1.js} +1 -1
  92. package/dist/{cli-vqva1teb.js → cli-qe909n63.js} +2 -2
  93. package/dist/{cli-2d0cghfn.js → cli-qj39vrc6.js} +1 -1
  94. package/dist/{cli-tas6ckky.js → cli-rq5rpv6k.js} +2 -2
  95. package/dist/{cli-0agcv1v5.js → cli-rqx70rcz.js} +2 -2
  96. package/dist/{cli-kmemts3w.js → cli-sn650d7x.js} +39 -69
  97. package/dist/{cli-98rwmcyc.js → cli-snxhtehz.js} +3 -3
  98. package/dist/{cli-d829z3xc.js → cli-spfz393q.js} +6 -6
  99. package/dist/{cli-500c09j9.js → cli-t9ga4qmb.js} +14 -14
  100. package/dist/{cli-me0r8gzr.js → cli-td9tb872.js} +27 -25
  101. package/dist/cli-tvc4jag9.js +754 -0
  102. package/dist/{cli-6ek0hff4.js → cli-ty3gha1p.js} +4 -4
  103. package/dist/{cli-c71n3bxq.js → cli-v57d7fmm.js} +2 -2
  104. package/dist/{cli-j8cjdzan.js → cli-vs9vdpy0.js} +1 -1
  105. package/dist/cli-vt89089n.js +296 -0
  106. package/dist/{cli-pxwtcgcp.js → cli-vyff45ve.js} +2 -2
  107. package/dist/{cli-x3ex5bqf.js → cli-w16kwbzw.js} +1 -1
  108. package/dist/{cli-bj6qhgte.js → cli-w4n323t3.js} +197 -45
  109. package/dist/{cli-rqfvkx5t.js → cli-wn13hhdt.js} +13 -13
  110. package/dist/{cli-skmhsnqh.js → cli-x40a0w9j.js} +1 -1
  111. package/dist/{cli-zeaehgyd.js → cli-xag7btpe.js} +2 -2
  112. package/dist/{cli-k28wkapa.js → cli-xf1wn5ns.js} +2 -2
  113. package/dist/{cli-rh15cakt.js → cli-xwsm6xkr.js} +1 -1
  114. package/dist/{cli-dpsfwh7n.js → cli-y2ewxhth.js} +56 -31
  115. package/dist/{cli-vx421edw.js → cli-ysvspf5e.js} +9 -7
  116. package/dist/{cli-crpf163n.js → cli-zh0e5x7p.js} +16 -26
  117. package/dist/{cli-4e1hfbpq.js → cli-zr6qy15y.js} +24 -24
  118. package/dist/cli.js +33 -29
  119. package/dist/{codex-adapter-2brxx5ta.js → codex-adapter-n656pvb8.js} +9 -8
  120. package/dist/{codex-hook-c930c3ea.js → codex-hook-59atdwd8.js} +6 -6
  121. package/dist/{codex-login-cbrs1h5w.js → codex-login-a239g1ah.js} +1 -1
  122. package/dist/{codex-session-runner-y9anfj0r.js → codex-session-runner-p0fbv5y9.js} +10 -9
  123. package/dist/{commands-wn9q06qr.js → commands-gwea8z5p.js} +3 -3
  124. package/dist/{controller-fw608czd.js → controller-t67c3grh.js} +9 -6
  125. package/dist/{controllers-connect-63j5rdcm.js → controllers-connect-ks155r0h.js} +28 -25
  126. package/dist/{cursor-adapter-6mb9jme8.js → cursor-adapter-ygwrtmkv.js} +2 -2
  127. package/dist/{db-y4wfrzbm.js → db-kpmx06s9.js} +21 -13
  128. package/dist/{db-0m6v5tq4.js → db-rb2xqdb1.js} +3 -3
  129. package/dist/{devin-adapter-r0yx3gv8.js → devin-adapter-zp4tqq53.js} +1 -1
  130. package/dist/{dispatcher-9tq2zzdj.js → dispatcher-31sm0ej2.js} +21 -18
  131. package/dist/{docker-j75atvpt.js → docker-09tkkg0n.js} +47 -8
  132. package/dist/{dsh-adapter-t09sv4tq.js → dsh-adapter-qyxh0w31.js} +2 -2
  133. package/dist/{e2b-a7vzs2vj.js → e2b-3v1e745x.js} +6 -6
  134. package/dist/{e2b-7s9dscap.js → e2b-sm28k0k3.js} +6 -6
  135. package/dist/{easter-egg-3d-fbwvmwhe.js → easter-egg-3d-00wjscn6.js} +1 -1
  136. package/dist/{embedding-space-wh8de1t9.js → embedding-space-qhw4g68n.js} +6 -6
  137. package/dist/{embeddings-3hpbdtjr.js → embeddings-zdv9ke6x.js} +1 -1
  138. package/dist/{event-bus-tr6h3gv8.js → event-bus-xr83x566.js} +1 -1
  139. package/dist/{execute-4bdf8sdy.js → execute-zna8wwr7.js} +1 -1
  140. package/dist/{external-channel-ts2fwqh0.js → external-channel-1ac6t56s.js} +2 -2
  141. package/dist/fx-adapter-sk7n0fzc.js +19 -0
  142. package/dist/{getMachineId-bsd-nfgrzarv.js → getMachineId-bsd-637a7rbk.js} +3 -3
  143. package/dist/{getMachineId-darwin-wz886dsk.js → getMachineId-darwin-9vytrcnn.js} +3 -3
  144. package/dist/{getMachineId-linux-1nng3p1p.js → getMachineId-linux-mkzsvyyz.js} +3 -3
  145. package/dist/{getMachineId-unsupported-a0428vw9.js → getMachineId-unsupported-4cfs2n11.js} +3 -3
  146. package/dist/{getMachineId-win-h45922nq.js → getMachineId-win-154s3qma.js} +3 -3
  147. package/dist/{google-generative-ai-h7s3e9kk.js → google-generative-ai-maq6c9bf.js} +1 -1
  148. package/dist/{google-vertex-fhxaafzw.js → google-vertex-2jgsw2nb.js} +5 -5
  149. package/dist/grok-adapter-sjbcm5ew.js +19 -0
  150. package/dist/handlers-yzy0c87x.js +35 -0
  151. package/dist/{heartbeat-2ze5fzpc.js → heartbeat-2f6z4kdx.js} +24 -21
  152. package/dist/{hook-gaehe2w5.js → hook-8y0gvtp1.js} +14 -14
  153. package/dist/{hook-ca54yd4s.js → hook-w1skzaqc.js} +5 -5
  154. package/dist/{http-jfg8t2yk.js → http-wghxvpef.js} +2333 -589
  155. package/dist/{index-d6wkh8ar.js → index-0h6qd4p1.js} +34 -24
  156. package/dist/index-25pvya7q.js +40 -0
  157. package/dist/index-2t4859r5.js +35 -0
  158. package/dist/{index-enn321kd.js → index-42jq9yy3.js} +3 -3
  159. package/dist/{index-khe3gp0k.js → index-4k7m5dgj.js} +645 -370
  160. package/dist/index-620y7jzq.js +15 -0
  161. package/dist/{index-gjwaqaq8.js → index-8p0j4h4j.js} +506 -43
  162. package/dist/{index-3gv6sc4z.js → index-8zn8nxn5.js} +1 -1
  163. package/dist/{index-m5gx1xd6.js → index-9myfj74s.js} +40 -40
  164. package/dist/{index-3yvzbhxd.js → index-9zkchs9t.js} +336 -193
  165. package/dist/{index-0rvk3vd4.js → index-b5wgnm78.js} +47 -47
  166. package/dist/index-cxca2t8y.js +36 -0
  167. package/dist/{index-qwj6ntem.js → index-e3krvkh2.js} +4 -4
  168. package/dist/{index-hjhfk3ra.js → index-pe3d8jfy.js} +3 -3
  169. package/dist/index-rv89fvzf.js +572 -0
  170. package/dist/{index-csgrxedz.js → index-s71ez27v.js} +1 -1
  171. package/dist/{keepalive-k2a3qe73.js → keepalive-sh02349h.js} +4 -4
  172. package/dist/lead-gk4h5eg7.js +74 -0
  173. package/dist/{maintenance-gb5sd5nc.js → maintenance-yj0dcjja.js} +1 -1
  174. package/dist/{node-252anz2h.js → node-dqm4xgxw.js} +4 -4
  175. package/dist/{node-ray25snp.js → node-zd6shky9.js} +3 -3
  176. package/dist/{oauth-refresh-sweep-y7rm6bkb.js → oauth-refresh-sweep-d9xedk66.js} +3 -3
  177. package/dist/{onboard-jmc5qerv.js → onboard-dpgjn03r.js} +8 -8
  178. package/dist/{openai-codex-responses-k9gapdze.js → openai-codex-responses-bkcd8pjj.js} +9 -9
  179. package/dist/{openai-responses-4d5dx3c7.js → openai-responses-gbh0wfqe.js} +13 -13
  180. package/dist/{opencode-adapter-7eade9ev.js → opencode-adapter-2d31cpjc.js} +7 -6
  181. package/dist/{otel-impl-8j1xhxqd.js → otel-impl-1skarpfq.js} +110 -110
  182. package/dist/pending-bfmxtx0g.js +82 -0
  183. package/dist/{pi-mono-adapter-yqmaf32x.js → pi-mono-adapter-gvppnasy.js} +43 -16
  184. package/dist/{pricing-refresh-1nj722h6.js → pricing-refresh-c6b325mk.js} +2 -2
  185. package/dist/{rbac-roles-b1mtr6dr.js → rbac-roles-h80qbdbs.js} +3 -3
  186. package/dist/{rbac-roles-n1f3frk1.js → rbac-roles-zfcx68tx.js} +10 -3
  187. package/dist/{render-v2-1gfpd8rj.js → render-v2-nx20t3rb.js} +7 -4
  188. package/dist/{resume-w1s1eh5v.js → resume-5ep8agan.js} +11 -7
  189. package/dist/{runtime-84g5egsc.js → runtime-r3pj4mce.js} +1 -1
  190. package/dist/{session-access-y6z1txk4.js → session-access-n7p3m15b.js} +4 -4
  191. package/dist/{session-source-backfill-gxxwfh12.js → session-source-backfill-v8mt0zwn.js} +4 -4
  192. package/dist/{setup-r91gstyk.js → setup-z1psaqhe.js} +1 -1
  193. package/dist/thread-buffer-a1re2r9r.js +38 -0
  194. package/dist/{virtual-modules-cgnj6kme.js → virtual-modules-rrbjdpxn.js} +5 -5
  195. package/dist/{work-objects-qcxzg61c.js → work-objects-4aghh73z.js} +31 -23
  196. package/dist/worker-3dyyb8ev.js +74 -0
  197. package/dist/{worker-follow-up-y2d2h7km.js → worker-follow-up-166zmex1.js} +21 -18
  198. package/dist/{x-qhxq2ama.js → x-wg164ss9.js} +2 -2
  199. package/openapi.json +2561 -131
  200. package/package.json +15 -11
  201. package/plugin/commands/create-pr.md +1 -1
  202. package/plugin/pi-skills/create-pr/SKILL.md +1 -1
  203. package/src/apps/action-runner.ts +21 -1
  204. package/src/apps/catalog.generated.json +667 -18
  205. package/src/apps/page-validator.ts +341 -8
  206. package/src/assets/key.ts +6 -0
  207. package/src/be/agent-fs-user-keys.ts +186 -0
  208. package/src/be/audit-user.ts +27 -13
  209. package/src/be/automation-preflight.test.ts +14 -14
  210. package/src/be/automation-preflight.ts +24 -16
  211. package/src/be/boot-scrub-sweep.ts +143 -14
  212. package/src/be/caller-session-group.ts +86 -0
  213. package/src/be/checklist.ts +375 -0
  214. package/src/be/db/agents.ts +12 -1
  215. package/src/be/db/approvals.ts +26 -0
  216. package/src/be/db/model-profiles.ts +4 -1
  217. package/src/be/db/session-costs.ts +219 -0
  218. package/src/be/db/session-log-reasoning.ts +36 -0
  219. package/src/be/db/session-moves.ts +23 -0
  220. package/src/be/db/session-tree.ts +78 -19
  221. package/src/be/db/tasks/eligibility-scan.ts +14 -0
  222. package/src/be/db/tasks/read.ts +7 -3
  223. package/src/be/db/tasks/slack-fold.ts +116 -0
  224. package/src/be/db/tasks/write.ts +67 -1
  225. package/src/be/db-queries/mcp-servers.ts +13 -0
  226. package/src/be/db-queries/oauth.ts +6 -0
  227. package/src/be/db-queries/task-artifacts.ts +10 -8
  228. package/src/be/db.ts +242 -319
  229. package/src/be/extensions/assets.ts +17 -13
  230. package/src/be/import/config.ts +54 -0
  231. package/src/be/import/dir-source.ts +372 -0
  232. package/src/be/import/index.ts +149 -0
  233. package/src/be/import/pending.ts +71 -0
  234. package/src/be/import/schema.ts +137 -0
  235. package/src/be/import/seeders.ts +462 -0
  236. package/src/be/key-window-usage.ts +385 -0
  237. package/src/be/migrations/297_import_ownership.sql +34 -0
  238. package/src/be/migrations/301_favorites_key_type.sql +36 -0
  239. package/src/be/migrations/302_checklist_items.sql +23 -0
  240. package/src/be/migrations/303_task_ui_specs.sql +28 -0
  241. package/src/be/migrations/306_provider_account_telemetry.sql +1 -0
  242. package/src/be/migrations/307_session_cost_credential_attribution.sql +23 -0
  243. package/src/be/migrations/310_session_logs_reasoning.sql +12 -0
  244. package/src/be/multi-runtime.ts +8 -1
  245. package/src/be/rbac-roles.ts +8 -1
  246. package/src/be/runtime-pools/db.ts +3 -0
  247. package/src/be/runtime-pools/demand.ts +20 -2
  248. package/src/be/runtime-pools/reachability.ts +31 -0
  249. package/src/be/runtime-pools/routing.ts +8 -1
  250. package/src/be/runtime-pools/supervisor.ts +6 -7
  251. package/src/be/savings/read.ts +8 -6
  252. package/src/be/script-credential-broker.ts +2 -2
  253. package/src/be/scripts/typecheck.ts +4 -4
  254. package/src/be/seed/agent-fs-provision.ts +104 -19
  255. package/src/be/seed/index.ts +1 -1
  256. package/src/be/seed/registry.ts +27 -8
  257. package/src/be/seed/runner.ts +1 -1
  258. package/src/be/seed/schedules-seeder.ts +24 -6
  259. package/src/be/seed/seed-toggle.ts +32 -0
  260. package/src/be/seed/types.ts +6 -0
  261. package/src/be/seed-scripts/catalog/boot-triage.inline.ts +1 -0
  262. package/src/be/seed-scripts/catalog/boot-triage.ts +1 -0
  263. package/src/be/seed-scripts/catalog/dreaming-gather.ts +2 -2
  264. package/src/be/seed-scripts/catalog/wait-for-task.ts +5 -1
  265. package/src/be/seed-skills/index.ts +3 -0
  266. package/src/be/steering.ts +27 -4
  267. package/src/be/swarm-config-guard.ts +54 -1
  268. package/src/be/task-citations.ts +8 -5
  269. package/src/be/task-ui-spec.ts +158 -0
  270. package/src/commands/controller.ts +3 -0
  271. package/src/commands/credential-outcome-report.ts +13 -3
  272. package/src/commands/onboard/agent-fs-version.ts +1 -1
  273. package/src/commands/rate-limit-outcome.ts +6 -0
  274. package/src/commands/runner.ts +95 -55
  275. package/src/e2b/env.ts +2 -0
  276. package/src/extensions/catalog.generated.json +17 -0
  277. package/src/extensions/contract-types.generated.ts +1 -1
  278. package/src/github/app.ts +10 -1
  279. package/src/github/handlers.ts +6 -3
  280. package/src/github/reactions.ts +12 -14
  281. package/src/heartbeat/heartbeat.ts +14 -4
  282. package/src/http/agents.ts +19 -10
  283. package/src/http/all-routes.ts +2 -0
  284. package/src/http/api-keys.ts +258 -30
  285. package/src/http/approval-requests.ts +24 -4
  286. package/src/http/apps.ts +69 -5
  287. package/src/http/checklist.ts +176 -0
  288. package/src/http/db-query-bounded.ts +256 -11
  289. package/src/http/db-query-shared.ts +9 -0
  290. package/src/http/favorites.ts +14 -2
  291. package/src/http/fs.ts +346 -1
  292. package/src/http/index.ts +29 -1
  293. package/src/http/kv.ts +13 -0
  294. package/src/http/mcp-oauth.ts +1 -1
  295. package/src/http/mcp-servers.ts +15 -2
  296. package/src/http/onboarding.ts +2 -9
  297. package/src/http/poll.ts +45 -0
  298. package/src/http/script-connections.ts +1 -0
  299. package/src/http/session-data.ts +74 -23
  300. package/src/http/sessions.ts +23 -2
  301. package/src/http/slack-events.ts +101 -0
  302. package/src/http/status.ts +25 -7
  303. package/src/http/task-requester.ts +46 -0
  304. package/src/http/tasks.ts +169 -42
  305. package/src/http/users.ts +14 -0
  306. package/src/http/webhooks.ts +15 -0
  307. package/src/integrations/cards/index.ts +151 -0
  308. package/src/integrations/chat-sdk/outbound.ts +39 -13
  309. package/src/integrations/chat-sdk/relay.ts +87 -0
  310. package/src/integrations/chat-sdk/runtime.ts +7 -1
  311. package/src/integrations/chat-sdk/status.ts +17 -0
  312. package/src/integrations/chat-sdk/telegram-api.ts +6 -1
  313. package/src/jira/outbound.ts +5 -3
  314. package/src/kv-reserved-namespaces.ts +17 -2
  315. package/src/linear/outbound.ts +5 -1
  316. package/src/oauth/presets.ts +29 -2
  317. package/src/prompts/base-prompt.ts +25 -4
  318. package/src/prompts/session-templates.ts +102 -8
  319. package/src/providers/acp-targets.ts +1 -1
  320. package/src/providers/amp-adapter.ts +1 -1
  321. package/src/providers/claude-adapter.ts +27 -4
  322. package/src/providers/claude-flag-settings.ts +39 -1
  323. package/src/providers/claude-managed-adapter.ts +5 -1
  324. package/src/providers/codex-adapter.ts +86 -4
  325. package/src/providers/codex-app-server.ts +11 -16
  326. package/src/providers/codex-oauth/auth-json.ts +1 -0
  327. package/src/providers/opencode-adapter.ts +7 -19
  328. package/src/providers/pi-mono-adapter.ts +35 -2
  329. package/src/providers/pricing-sources.md +32 -0
  330. package/src/providers/runtime-dependencies.ts +158 -0
  331. package/src/providers/types.ts +11 -0
  332. package/src/rbac/legacy-policy.ts +2 -0
  333. package/src/rbac/permissions.ts +10 -1
  334. package/src/runtime-providers/docker.ts +65 -1
  335. package/src/scheduler/deferred-task-waits.ts +18 -5
  336. package/src/scripts-runtime/credential-broker/default-bindings.ts +19 -11
  337. package/src/scripts-runtime/credential-broker/index.ts +1 -1
  338. package/src/scripts-runtime/egress-secrets.ts +2 -2
  339. package/src/scripts-runtime/swarm-sdk.ts +3 -2
  340. package/src/scripts-runtime/types/stdlib.d.ts +11 -4
  341. package/src/scripts-runtime/types/swarm-extension.d.ts +9 -9
  342. package/src/scripts-runtime/types/swarm-sdk.d.ts +11 -4
  343. package/src/server.ts +4 -4
  344. package/src/slack/actions.ts +56 -0
  345. package/src/slack/app.ts +107 -59
  346. package/src/slack/assistant.ts +33 -7
  347. package/src/slack/handlers.ts +6 -4
  348. package/src/slack/http-receiver.ts +284 -0
  349. package/src/slack/inbound-dispatch.ts +43 -7
  350. package/src/slack/inbound-files.ts +35 -14
  351. package/src/slack/message-text.ts +47 -4
  352. package/src/slack/render-v2.ts +109 -24
  353. package/src/slack/responses.ts +3 -2
  354. package/src/slack/socket-ack.ts +17 -10
  355. package/src/slack/steering.ts +5 -0
  356. package/src/slack/thread-buffer-store.ts +58 -0
  357. package/src/slack/thread-buffer.ts +341 -57
  358. package/src/slack/work-objects.ts +4 -1
  359. package/src/tasks/context-key.ts +24 -0
  360. package/src/tasks/errors.ts +5 -0
  361. package/src/tasks/sibling-awareness.ts +13 -1
  362. package/src/tests/acp-adapter.test.ts +4 -6
  363. package/src/tests/agent-fs-live-url.test.ts +15 -0
  364. package/src/tests/agent-fs-provision-seeder.test.ts +140 -0
  365. package/src/tests/agent-fs-user-keys.test.ts +483 -0
  366. package/src/tests/agentfs-proxy.test.ts +8 -8
  367. package/src/tests/api-key-tracking.test.ts +0 -72
  368. package/src/tests/api-keys-status-model-limits.test.ts +93 -1
  369. package/src/tests/api-keys-validation.test.ts +42 -0
  370. package/src/tests/approval-card-resolution.test.ts +402 -0
  371. package/src/tests/approval-requests-notifications.test.ts +12 -2
  372. package/src/tests/approval-respond-auth.test.ts +28 -0
  373. package/src/tests/apps-action-parent-task.test.ts +140 -0
  374. package/src/tests/apps-catalog-additions.test.ts +315 -0
  375. package/src/tests/apps-catalog-files.test.ts +114 -0
  376. package/src/tests/apps-catalog-hitl.test.ts +117 -0
  377. package/src/tests/apps-catalog-inputs.test.ts +86 -0
  378. package/src/tests/apps-catalog-page-frame.test.ts +49 -0
  379. package/src/tests/apps-catalog-table.test.ts +47 -0
  380. package/src/tests/apps-chart-shell.test.ts +1 -1
  381. package/src/tests/apps-element-assembly.test.ts +52 -3
  382. package/src/tests/apps-session-thread.test.ts +261 -0
  383. package/src/tests/asset-key-invariants.test.ts +14 -0
  384. package/src/tests/base-prompt.test.ts +213 -23
  385. package/src/tests/boot-scrub-sweep.test.ts +172 -0
  386. package/src/tests/caller-session-group.test.ts +199 -0
  387. package/src/tests/cards.test.ts +169 -0
  388. package/src/tests/chat-sdk-relay.test.ts +149 -1
  389. package/src/tests/chat-sdk-status-route.test.ts +16 -3
  390. package/src/tests/chat-sdk-telegram-token.test.ts +76 -0
  391. package/src/tests/chat-sdk-tools.test.ts +147 -0
  392. package/src/tests/checklist-nudge.test.ts +208 -0
  393. package/src/tests/checklist.test.ts +686 -0
  394. package/src/tests/claude-adapter-binary.test.ts +67 -6
  395. package/src/tests/claude-flag-settings.test.ts +29 -0
  396. package/src/tests/claude-sdk-lifecycle.test.ts +5 -0
  397. package/src/tests/codex-adapter.test.ts +340 -2
  398. package/src/tests/codex-app-server.test.ts +32 -0
  399. package/src/tests/codex-oauth.test.ts +3 -1
  400. package/src/tests/codex-rate-limits.test.ts +384 -0
  401. package/src/tests/comb-config-guard.test.ts +21 -0
  402. package/src/tests/comb-default.test.ts +59 -97
  403. package/src/tests/comb-links.test.ts +86 -16
  404. package/src/tests/comb-status.test.ts +24 -27
  405. package/src/tests/create-page-tool.test.ts +101 -1
  406. package/src/tests/create-schedule-key.test.ts +105 -0
  407. package/src/tests/credential-broker.test.ts +2 -2
  408. package/src/tests/credential-outcome-report.test.ts +20 -0
  409. package/src/tests/db-query.test.ts +87 -1
  410. package/src/tests/db-task-read-contract.test.ts +4 -0
  411. package/src/tests/db-task-write-contract.test.ts +6 -1
  412. package/src/tests/deferred-task-wake.test.ts +63 -1
  413. package/src/tests/docker-isolation-config-guard.test.ts +29 -0
  414. package/src/tests/docs-index-footprint.test.js +11 -3
  415. package/src/tests/e2e-visuals-comment.test.ts +82 -0
  416. package/src/tests/e2e-visuals-verify-pr.test.ts +138 -0
  417. package/src/tests/entrypoint-github-enterprise.test.ts +158 -0
  418. package/src/tests/extensions-assets.test.ts +7 -3
  419. package/src/tests/extensions-catalog.test.ts +1 -0
  420. package/src/tests/extensions-example-sql-admin-only.test.ts +201 -0
  421. package/src/tests/extensions-pre-task.test.ts +3 -3
  422. package/src/tests/extensions-steering.test.ts +14 -2
  423. package/src/tests/favorites-agent-fs-path.test.ts +124 -0
  424. package/src/tests/fetch-resolved-env.test.ts +68 -0
  425. package/src/tests/fixtures/import-package.ts +32 -0
  426. package/src/tests/fixtures/runner-missing-dependency.ts +129 -0
  427. package/src/tests/fixtures/ui-spec-slack/deploys.json +121 -0
  428. package/src/tests/fixtures/ui-spec-slack/incident.json +183 -0
  429. package/src/tests/fixtures/ui-spec-slack/three-charts-stale.json +196 -0
  430. package/src/tests/fixtures/ui-spec-slack/video-rejected-by-slack.json +183 -0
  431. package/src/tests/fixtures/ui-spec-slack/video.json +446 -0
  432. package/src/tests/fs-routes.test.ts +505 -2
  433. package/src/tests/github-ghes-mock.test.ts +196 -0
  434. package/src/tests/github-host.test.ts +285 -0
  435. package/src/tests/gitleaks-download-retry.test.ts +85 -0
  436. package/src/tests/heartbeat-supersede-resume.test.ts +73 -0
  437. package/src/tests/heartbeat.test.ts +56 -0
  438. package/src/tests/human-thread-routing.test.ts +187 -0
  439. package/src/tests/import-config.test.ts +209 -0
  440. package/src/tests/import.test.ts +464 -0
  441. package/src/tests/invites-http.test.ts +144 -1
  442. package/src/tests/jira-outbound-sync.test.ts +33 -1
  443. package/src/tests/key-window-usage.test.ts +831 -0
  444. package/src/tests/kv-http.test.ts +11 -0
  445. package/src/tests/linear-outbound-sync.test.ts +30 -1
  446. package/src/tests/literal-matcher.test.ts +58 -0
  447. package/src/tests/mcp-oauth-manual-client.test.ts +1 -1
  448. package/src/tests/oauth-presets.test.ts +12 -0
  449. package/src/tests/pi-mono-adapter.test.ts +79 -0
  450. package/src/tests/pool-affinity.test.ts +50 -0
  451. package/src/tests/preload-env.test.ts +2 -0
  452. package/src/tests/preload.ts +3 -1
  453. package/src/tests/prompt-template-session.test.ts +53 -5
  454. package/src/tests/provider-quota-persistence.test.ts +362 -0
  455. package/src/tests/provider-registration.test.ts +2 -55
  456. package/src/tests/provider-runtime-dependencies.test.ts +212 -0
  457. package/src/tests/rate-limit-event.test.ts +22 -0
  458. package/src/tests/rbac-admission.test.ts +19 -0
  459. package/src/tests/rbac-charact-misc-tools.test.ts +31 -0
  460. package/src/tests/rbac-engine.test.ts +2 -0
  461. package/src/tests/rbac-roles.test.ts +2 -0
  462. package/src/tests/reasoning-events.test.ts +164 -0
  463. package/src/tests/routing-affinity-inventory.test.ts +22 -0
  464. package/src/tests/runner-missing-dependency.test.ts +61 -0
  465. package/src/tests/runtime-pool-reachability.test.ts +135 -1
  466. package/src/tests/runtime-pool-routing.test.ts +52 -0
  467. package/src/tests/runtime-providers-docker.test.ts +91 -0
  468. package/src/tests/runtime-stale-threshold.test.ts +40 -0
  469. package/src/tests/savings-fleet-slices.test.ts +122 -0
  470. package/src/tests/savings-read.test.ts +41 -0
  471. package/src/tests/savings-scripts.test.ts +9 -3
  472. package/src/tests/script-connections.test.ts +7 -0
  473. package/src/tests/script-executor-conformance.test.ts +41 -4
  474. package/src/tests/secret-canary-sweep.test.ts +41 -5
  475. package/src/tests/secret-scrub-gate.test.ts +257 -0
  476. package/src/tests/seed-registry.test.ts +142 -9
  477. package/src/tests/seed-scripts.test.ts +23 -0
  478. package/src/tests/session-cost-attribution.test.ts +748 -0
  479. package/src/tests/session-costs.test.ts +14 -15
  480. package/src/tests/session-logs.test.ts +83 -0
  481. package/src/tests/session-source-keys.test.ts +42 -1
  482. package/src/tests/sessions-detail-batch.test.ts +7 -0
  483. package/src/tests/sessions-move.test.ts +70 -0
  484. package/src/tests/sessions-tree.test.ts +98 -0
  485. package/src/tests/sessions.test.ts +69 -0
  486. package/src/tests/slack-config.test.ts +4 -18
  487. package/src/tests/slack-http-receiver.test.ts +472 -0
  488. package/src/tests/slack-inbound-logging.test.ts +64 -0
  489. package/src/tests/slack-leave-thread.test.ts +1 -1
  490. package/src/tests/slack-message-text.test.ts +104 -0
  491. package/src/tests/slack-mode-lifecycle.test.ts +6 -4
  492. package/src/tests/slack-render-v2.test.ts +405 -0
  493. package/src/tests/slack-skip-reaction.test.ts +2 -2
  494. package/src/tests/slack-start-reload-race.test.ts +67 -0
  495. package/src/tests/slack-steering.test.ts +22 -10
  496. package/src/tests/slack-thread-buffer-context.test.ts +1 -1
  497. package/src/tests/slack-thread-buffer-fold.test.ts +417 -0
  498. package/src/tests/slack-thread-buffer-restore.test.ts +198 -0
  499. package/src/tests/slack-thread-buffer-startup-restore.test.ts +86 -0
  500. package/src/tests/slack-thread-buffer.test.ts +34 -34
  501. package/src/tests/slack-thread-participants.test.ts +23 -5
  502. package/src/tests/slack-tool-blocks.test.ts +167 -0
  503. package/src/tests/status.test.ts +32 -6
  504. package/src/tests/steering-core.test.ts +13 -0
  505. package/src/tests/steering-enabled.test.ts +7 -1
  506. package/src/tests/steering-promotion.test.ts +24 -0
  507. package/src/tests/subscription-plans.test.ts +20 -1
  508. package/src/tests/swarm-config-reserved-keys.test.ts +17 -0
  509. package/src/tests/system-one-hosts-ui-mirror.test.ts +67 -0
  510. package/src/tests/task-artifacts.test.ts +50 -0
  511. package/src/tests/task-session-prompts.test.ts +95 -1
  512. package/src/tests/task-ui-action-route.test.ts +191 -0
  513. package/src/tests/task-ui-actions.test.ts +195 -0
  514. package/src/tests/task-ui-spec-fallback.test.ts +65 -0
  515. package/src/tests/task-ui-spec.test.ts +368 -0
  516. package/src/tests/workflow-agent-task-retry.test.ts +34 -1
  517. package/src/tests/workflow-system-one-extraction.test.ts +149 -1
  518. package/src/tools/chat-post.ts +19 -4
  519. package/src/tools/chat-reply.ts +20 -4
  520. package/src/tools/create-page.ts +21 -4
  521. package/src/tools/defer-task.ts +1 -1
  522. package/src/tools/get-swarm.ts +18 -2
  523. package/src/tools/join-swarm.ts +2 -1
  524. package/src/tools/kv/kv-write-auth.ts +17 -1
  525. package/src/tools/schedules/create-schedule.ts +22 -4
  526. package/src/tools/slack-post.ts +40 -7
  527. package/src/tools/slack-reply.ts +50 -14
  528. package/src/tools/store-progress.ts +69 -3
  529. package/src/types.ts +50 -4
  530. package/src/ui-spec/actions.ts +86 -0
  531. package/src/ui-spec/fallback.ts +19 -0
  532. package/src/ui-spec/slack.ts +17 -0
  533. package/src/ui-spec/validate.ts +169 -0
  534. package/src/utils/codex-rate-limits.ts +159 -0
  535. package/src/utils/constants.ts +60 -138
  536. package/src/utils/credentials.ts +2 -0
  537. package/src/utils/error-tracker.ts +19 -0
  538. package/src/utils/github-host.ts +217 -0
  539. package/src/utils/github-pull-request.ts +8 -5
  540. package/src/utils/literal-matcher.ts +118 -0
  541. package/src/utils/provider-account-telemetry.ts +331 -0
  542. package/src/utils/reasoning-events.ts +107 -0
  543. package/src/utils/secret-scrubber.ts +331 -25
  544. package/src/utils/subscription-plans.ts +11 -59
  545. package/src/utils/task-attachment-links.ts +9 -12
  546. package/src/utils/task-ui-spec.ts +67 -0
  547. package/src/vcs/index.ts +3 -0
  548. package/src/workflows/approval-notifications.ts +188 -12
  549. package/src/workflows/executors/system-one-extraction.ts +14 -7
  550. package/src/workflows/executors/system-one-providers.ts +22 -1
  551. package/src/workflows/task-step-routing.ts +8 -3
  552. package/templates/community/open-prompt-showreel/PLAYBOOK.md +1 -1
  553. package/templates/community/open-prompt-showreel/skills/open-prompt-showreel/SKILL.md +1 -1
  554. package/templates/extensions/README.md +1 -0
  555. package/templates/extensions/sql-admin-only/README.md +20 -0
  556. package/templates/extensions/sql-admin-only/hooks.ts +100 -0
  557. package/templates/extensions/sql-admin-only/manifest.json +8 -0
  558. package/templates/import/manifest.schema.json +136 -0
  559. package/templates/import/sources.schema.json +44 -0
  560. package/templates/skills/agent-browser/SKILL.md +1 -1
  561. package/templates/skills/agent-browser/content.md +1 -1
  562. package/templates/skills/apps/SKILL.md +151 -14
  563. package/templates/skills/apps/content.md +151 -14
  564. package/templates/skills/asset-namespaces/content.md +2 -1
  565. package/templates/skills/chat-sdk/content.md +17 -0
  566. package/templates/skills/db-query-guidance/content.md +2 -1
  567. package/templates/skills/scheduling/content.md +27 -0
  568. package/templates/skills/slack-interaction/content.md +12 -2
  569. package/templates/skills/swarm-docs/content.md +1 -0
  570. package/templates/skills/swarm-extensions/config.json +1 -1
  571. package/templates/skills/swarm-extensions/content.md +33 -23
  572. package/templates/skills/swarm-scripts/SKILL.md +13 -0
  573. package/templates/skills/swarm-scripts/content.md +13 -0
  574. package/templates/skills/ui-spec/config.json +14 -0
  575. package/templates/skills/ui-spec/content.md +127 -0
  576. package/templates/skills/work-on-task/SKILL.md +1 -1
  577. package/templates/skills/work-on-task/content.md +1 -1
  578. package/templates/skills/workflow-iterate/content.md +4 -7
  579. package/templates/workflows/dreaming/content.md +2 -2
  580. package/dist/acp-adapter-xq6s2z6t.js +0 -14
  581. package/dist/claude-adapter-r33pqnzx.js +0 -24
  582. package/dist/cli-dns0y538.js +0 -194
  583. package/dist/cli-m2z8jagn.js +0 -12078
  584. package/dist/fx-adapter-1rnxnf56.js +0 -17
  585. package/dist/grok-adapter-efhmf1r8.js +0 -17
  586. package/dist/handlers-anrr3py9.js +0 -32
  587. package/dist/index-2skqtd76.js +0 -12795
  588. package/dist/index-8w2aznds.js +0 -33
  589. package/dist/index-qnjvr362.js +0 -37
  590. package/dist/index-yzxd3sn9.js +0 -32
  591. package/dist/lead-zhxqbfdv.js +0 -69
  592. package/dist/worker-7j2907g6.js +0 -69
  593. package/src/tests/entrypoint-acp-target-binary.test.ts +0 -439
  594. package/dist/{cli-4caa1x7d.js → cli-tsa40663.js} +4 -4
  595. package/dist/{mistral-conversations-a45tx39a.js → mistral-conversations-0c30em7t.js} +4 -4
  596. package/dist/{openai-completions-xd579js7.js → openai-completions-f3n69rep.js} +18 -18
  597. package/dist/{pi-messages-hjbv8v10.js → pi-messages-zebyt7gb.js} +5 -5
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,
@@ -149,6 +161,7 @@ import {
149
161
  import { MASKED_SECRET_VALUE } from "../utils/config-secrets";
150
162
  import { deriveProviderFromKeyType } from "../utils/credentials";
151
163
  import type { RateLimitWindowTelemetry } from "../utils/error-tracker";
164
+ import { getGitHubHostForSql } from "../utils/github-host";
152
165
  import { extractGitHubPullRequestUrls } from "../utils/github-pull-request";
153
166
  import { validateHeartbeatExpiry } from "../utils/heartbeat-expiry";
154
167
  import {
@@ -158,6 +171,15 @@ import {
158
171
  } from "../utils/identity-field-budget";
159
172
  import { activeModelBlock, type ModelFamily } from "../utils/model-rate-limit-windows";
160
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";
161
183
  import { getCurrentRequestUserId, getCurrentRunProvenance } from "../utils/request-auth-context";
162
184
  import { isRuntimePoolsEnabled } from "../utils/runtime-pools-flag";
163
185
  import {
@@ -166,7 +188,7 @@ import {
166
188
  scrubSecrets,
167
189
  } from "../utils/secret-scrubber";
168
190
  import {
169
- estimateClaudePlan,
191
+ codexPlanFromClaim,
170
192
  planAllowsModelFamily,
171
193
  SUBSCRIPTION_KEY_TYPES,
172
194
  } from "../utils/subscription-plans";
@@ -191,6 +213,7 @@ import {
191
213
  type ApprovalRequestListFilters,
192
214
  type ApprovalVote,
193
215
  approvalRequestListClause,
216
+ scheduleApprovalCardUpdates,
194
217
  scrubApprovalVotesJson,
195
218
  } from "./db/approvals";
196
219
  import {
@@ -202,6 +225,7 @@ import { clearAgentModelProfileOnOverrideChange } from "./db/model-profiles";
202
225
  import { pageSearchSql } from "./db/page-search";
203
226
  import { parsePageThemeTokens } from "./db/page-theme-tokens";
204
227
  import { getDb, getDbClient } from "./db/runtime";
228
+ import { classifyClaudeUpdate } from "./db/session-log-reasoning";
205
229
  import {
206
230
  assertAssetKeyMovesAllowed,
207
231
  configureSessionMoveDependencies,
@@ -218,6 +242,7 @@ import {
218
242
  } from "./db/session-tree";
219
243
  import { searchSkillRowsRanked } from "./db/skill-search";
220
244
  import { SLACK_TREE_NEEDS_RENDER_SQL } from "./db/slack-trees";
245
+ import { getEligibilityScanCap } from "./db/tasks/eligibility-scan";
221
246
  import { classifyTaskHumanFree, reclassifyTaskHumanFree } from "./db/tasks/human-free";
222
247
  import {
223
248
  type AgentTaskRow,
@@ -339,6 +364,9 @@ export {
339
364
  configureAgentDependencies({
340
365
  createLogEntry: (entry) => createLogEntry(entry),
341
366
  installSystemDefaultSkillsForAgent: (agentId) => installSystemDefaultSkillsForAgent(agentId),
367
+ // Lazy: the importer imports this facade.
368
+ resolvePendingImportAssignments: async (agent) =>
369
+ (await import("./import/pending")).resolvePendingImportAssignments(agent),
342
370
  });
343
371
 
344
372
  export {
@@ -423,6 +451,7 @@ export {
423
451
  getPausedTasksForAgent,
424
452
  getPendingTaskForAgent,
425
453
  getRecentlyCancelledTasksForAgent,
454
+ markWorkflowStepTaskSuperseded,
426
455
  overwriteTerminalTaskResultText,
427
456
  pauseTask,
428
457
  recordTaskProviderIfUnset,
@@ -435,6 +464,7 @@ export {
435
464
  supersedeTask,
436
465
  updateTaskClaudeSessionId,
437
466
  updateTaskProgress,
467
+ updateTaskTags,
438
468
  updateTaskTitle,
439
469
  } from "./db/tasks/write";
440
470
 
@@ -2722,7 +2752,9 @@ export async function createTaskExtended(
2722
2752
  if (parent.routingAffinityInvalid && options.inheritParentRoutingAffinity !== false) {
2723
2753
  // Never let a corrupt parent affinity create an apparently untagged
2724
2754
  // continuation. This is a fail-closed quarantine, including recovery.
2725
- throw new Error(`Cannot continue task ${parent.id}: routing affinity is invalid.`);
2755
+ throw new TaskRoutingAuthorizationError(
2756
+ `Cannot continue task ${parent.id}: routing affinity is invalid.`,
2757
+ );
2726
2758
  }
2727
2759
  if (parent.routingAffinity && options.inheritParentRoutingAffinity !== false) {
2728
2760
  // Privilege cannot be shed by a continuation. A child can narrow or
@@ -2881,10 +2913,13 @@ export async function createTaskExtended(
2881
2913
  leadOnly: options.routingAffinity.leadOnly === true,
2882
2914
  targetAgentId,
2883
2915
  decision: "reject_ineligible_assignment",
2916
+ parentTaskId: options.parentTaskId,
2917
+ source: options.source,
2918
+ contextKey: options.contextKey,
2884
2919
  },
2885
2920
  });
2886
2921
  } catch {}
2887
- throw new Error(
2922
+ throw new TaskRoutingAuthorizationError(
2888
2923
  options.routingAffinity.leadOnly
2889
2924
  ? `Lead-only task routing affinity does not authorize assignment or offer to agent "${targetAgentId}".`
2890
2925
  : `Task routing affinity does not authorize assignment or offer to agent "${targetAgentId}".`,
@@ -3605,17 +3640,17 @@ export async function getUnassignedTaskIds(limit = 10): Promise<string[]> {
3605
3640
  }
3606
3641
 
3607
3642
  /**
3608
- * Batch size and hard cap for the paginated eligibility scans in
3643
+ * Batch size for the paginated eligibility scans in
3609
3644
  * `getUnassignedTaskIdsForAgent` (and `autoAssignPoolTasks` in
3610
3645
  * src/heartbeat/heartbeat.ts, which mirrors this pattern). A fixed single
3611
3646
  * window used to mean N ineligible affinity-tagged tasks at the head of the
3612
3647
  * priority order could hide all eligible work behind them forever — see
3613
3648
  * PR #954 review. Scanning continues page-by-page until `limit` eligible
3614
- * candidates are found or the pool is exhausted; the cap bounds worst-case
3615
- * DB load when eligible work is buried deep or genuinely absent.
3649
+ * candidates are found or the pool is exhausted; the scan cap
3650
+ * (`getEligibilityScanCap`) bounds worst-case DB load when eligible work is
3651
+ * buried deep or genuinely absent.
3616
3652
  */
3617
3653
  const ELIGIBILITY_SCAN_BATCH_SIZE = Number(process.env.ELIGIBILITY_SCAN_BATCH_SIZE) || 25;
3618
- const ELIGIBILITY_SCAN_CAP = Number(process.env.ELIGIBILITY_SCAN_CAP) || 500;
3619
3654
 
3620
3655
  /**
3621
3656
  * Same ordering as `getUnassignedTaskIds`, filtered through
@@ -3640,9 +3675,10 @@ export async function getUnassignedTaskIdsForAgent(
3640
3675
 
3641
3676
  const batchSize = Math.max(limit * 5, ELIGIBILITY_SCAN_BATCH_SIZE);
3642
3677
  const eligible: string[] = [];
3678
+ const scanCap = getEligibilityScanCap();
3643
3679
  let offset = 0;
3644
3680
 
3645
- while (eligible.length < limit && offset < ELIGIBILITY_SCAN_CAP) {
3681
+ while (eligible.length < limit && offset < scanCap) {
3646
3682
  const rows = await getDbClient().query<AgentTaskRow>(
3647
3683
  "SELECT * FROM agent_tasks WHERE status = 'unassigned' ORDER BY priority DESC, createdAt ASC, rowid ASC LIMIT ? OFFSET ?",
3648
3684
  [batchSize, offset],
@@ -4843,7 +4879,7 @@ export async function createSessionLogs(logs: {
4843
4879
  for (let start = 0; start < logs.lines.length; start += BATCH_SIZE) {
4844
4880
  // Yield to the event loop between batches.
4845
4881
  if (start > 0) await new Promise<void>((r) => setTimeout(r, 5));
4846
- const batch: string[] = [];
4882
+ const batch: Array<{ content: string; reasoning: ReturnType<typeof extractReasoning> }> = [];
4847
4883
  const end = Math.min(start + BATCH_SIZE, logs.lines.length);
4848
4884
  for (let i = start; i < end; i++) {
4849
4885
  const line = logs.lines[i];
@@ -4852,7 +4888,9 @@ export async function createSessionLogs(logs: {
4852
4888
  // content that is already scrubbed at the adapter emit site. We scrub
4853
4889
  // again here so any future write path that bypasses the adapter still
4854
4890
  // lands clean text in the persistent session_logs table.
4855
- batch.push(scrubSecrets(line));
4891
+ const content = scrubSecrets(line);
4892
+ // Parsed here, next to the scrub, so the write lock covers inserts only.
4893
+ batch.push({ content, reasoning: extractReasoning(logs.cli, content) });
4856
4894
  }
4857
4895
  await getDbClient().transaction(async (tx) => {
4858
4896
  // The worker flushes one (sessionId, iteration) in many POSTs, so the
@@ -4867,10 +4905,13 @@ export async function createSessionLogs(logs: {
4867
4905
  [logs.sessionId, logs.iteration],
4868
4906
  );
4869
4907
  let lineNumber = last ? last.lineNumber + 1 : 0;
4870
- for (const content of batch) {
4908
+ // Consecutive Claude thinking lines of one message just before the current line.
4909
+ let run = 0;
4910
+ let runMessageId: string | undefined;
4911
+ for (const [index, { content, reasoning }] of batch.entries()) {
4871
4912
  await tx.run(
4872
- `INSERT INTO session_logs (id, taskId, sessionId, iteration, cli, content, lineNumber, createdAt)
4873
- VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`,
4913
+ `INSERT INTO session_logs (id, taskId, sessionId, iteration, cli, content, lineNumber, createdAt, reasoningChars, reasoningKind)
4914
+ VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), ?, ?)`,
4874
4915
  [
4875
4916
  crypto.randomUUID(),
4876
4917
  logs.taskId ?? null,
@@ -4878,9 +4919,29 @@ export async function createSessionLogs(logs: {
4878
4919
  logs.iteration,
4879
4920
  logs.cli,
4880
4921
  content,
4881
- lineNumber++,
4922
+ lineNumber,
4923
+ reasoning.reasoning?.chars ?? null,
4924
+ reasoning.reasoning ? "reasoning" : null,
4882
4925
  ],
4883
4926
  );
4927
+ const toolMessageId = reasoning.toolUseMessageId;
4928
+ if (toolMessageId) {
4929
+ const before = runMessageId === toolMessageId ? run : 0;
4930
+ // Only a run of 2+ can hold an update. A run that reaches the batch
4931
+ // start may continue in an earlier POST, so the DB decides that case.
4932
+ if (before >= 2 || before === index) {
4933
+ await classifyClaudeUpdate(tx, logs.sessionId, toolMessageId, lineNumber);
4934
+ }
4935
+ }
4936
+ const messageId = reasoning.reasoning?.messageId;
4937
+ if (logs.cli === "claude" && messageId) {
4938
+ run = runMessageId === messageId ? run + 1 : 1;
4939
+ runMessageId = messageId;
4940
+ } else {
4941
+ run = 0;
4942
+ runMessageId = undefined;
4943
+ }
4944
+ lineNumber++;
4884
4945
  }
4885
4946
  });
4886
4947
  }
@@ -4927,160 +4988,8 @@ export async function getSessionLogsBySession(
4927
4988
  // Session Costs (aggregated cost data per session)
4928
4989
  // ============================================================================
4929
4990
 
4930
- type SessionCostRow = {
4931
- id: string;
4932
- sessionId: string;
4933
- taskId: string | null;
4934
- agentId: string;
4935
- totalCostUsd: number;
4936
- inputTokens: number;
4937
- outputTokens: number;
4938
- cacheReadTokens: number;
4939
- cacheWriteTokens: number;
4940
- // Migration 063 additions:
4941
- reasoningOutputTokens: number;
4942
- thinkingTokens: number;
4943
- durationMs: number;
4944
- numTurns: number | null;
4945
- model: string;
4946
- isError: number;
4947
- costSource: string;
4948
- harnessCostUsd: number | null;
4949
- cacheWrite5mTokens: number | null;
4950
- cacheWrite1hTokens: number | null;
4951
- modelBreakdown: string | null;
4952
- createdAt: string;
4953
- };
4954
-
4955
- function rowToSessionCost(row: SessionCostRow): SessionCost {
4956
- let modelBreakdown: SessionCostModelBreakdown[] | null = null;
4957
- if (row.modelBreakdown) {
4958
- try {
4959
- const parsed = SessionCostModelBreakdownSchema.array().safeParse(
4960
- JSON.parse(row.modelBreakdown),
4961
- );
4962
- if (parsed.success) modelBreakdown = parsed.data;
4963
- } catch {
4964
- // Corrupt JSON (manual edits, partial writes) must not fail the listing.
4965
- }
4966
- }
4967
-
4968
- return {
4969
- id: row.id,
4970
- sessionId: row.sessionId,
4971
- taskId: row.taskId ?? undefined,
4972
- agentId: row.agentId,
4973
- totalCostUsd: row.totalCostUsd,
4974
- inputTokens: row.inputTokens,
4975
- outputTokens: row.outputTokens,
4976
- cacheReadTokens: row.cacheReadTokens,
4977
- cacheWriteTokens: row.cacheWriteTokens,
4978
- reasoningOutputTokens: row.reasoningOutputTokens ?? 0,
4979
- thinkingTokens: row.thinkingTokens ?? 0,
4980
- durationMs: row.durationMs,
4981
- numTurns: row.numTurns,
4982
- model: row.model,
4983
- isError: row.isError === 1,
4984
- costSource: (row.costSource as SessionCostSource) ?? "harness",
4985
- harnessCostUsd: row.harnessCostUsd,
4986
- cacheWrite5mTokens: row.cacheWrite5mTokens,
4987
- cacheWrite1hTokens: row.cacheWrite1hTokens,
4988
- modelBreakdown,
4989
- createdAt: row.createdAt,
4990
- };
4991
- }
4992
-
4993
- export interface CreateSessionCostInput {
4994
- id?: string;
4995
- sessionId: string;
4996
- taskId?: string;
4997
- agentId: string;
4998
- totalCostUsd: number;
4999
- inputTokens?: number;
5000
- outputTokens?: number;
5001
- cacheReadTokens?: number;
5002
- cacheWriteTokens?: number;
5003
- // Migration 063 additions — adapters that have these numbers should pass
5004
- // them; defaulting to 0 preserves the old write shape for callers that don't.
5005
- reasoningOutputTokens?: number;
5006
- thinkingTokens?: number;
5007
- durationMs: number;
5008
- // Nullable: some adapters (claude when num_turns is absent) can't honestly
5009
- // report a turn count; we prefer null over a faked 1.
5010
- numTurns: number | null;
5011
- model: string;
5012
- isError?: boolean;
5013
- /**
5014
- * Phase 6 (migration 063 added 'unpriced'): where `totalCostUsd` came from.
5015
- * - 'harness' — value reported by the harness as-is (default).
5016
- * - 'pricing-table' — value recomputed by the API from `pricing` rows.
5017
- * - 'unpriced' — recompute attempted but no matching pricing rows;
5018
- * `totalCostUsd` is whatever the worker submitted.
5019
- * - 'estimated' — fallback token counts priced at an assumed model
5020
- * (amp with a failed thread export).
5021
- */
5022
- costSource?: SessionCostSource;
5023
- harnessCostUsd?: number | null;
5024
- cacheWrite5mTokens?: number | null;
5025
- cacheWrite1hTokens?: number | null;
5026
- modelBreakdown?: SessionCostModelBreakdown[] | null;
5027
- }
5028
-
5029
4991
  export async function createSessionCost(input: CreateSessionCostInput): Promise<SessionCost> {
5030
- const id = input.id ?? crypto.randomUUID();
5031
- const costSource: SessionCostSource = input.costSource ?? "harness";
5032
- const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
5033
- const thinkingTokens = input.thinkingTokens ?? 0;
5034
- await getDbClient().run(
5035
- `INSERT INTO session_costs (
5036
- id, sessionId, taskId, agentId,
5037
- totalCostUsd, inputTokens, outputTokens,
5038
- cacheReadTokens, cacheWriteTokens,
5039
- reasoningOutputTokens, thinkingTokens,
5040
- durationMs, numTurns, model, isError,
5041
- costSource, harnessCostUsd, cacheWrite5mTokens, cacheWrite1hTokens,
5042
- modelBreakdown, createdAt
5043
- )
5044
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
5045
- ON CONFLICT(id) DO NOTHING`,
5046
- [
5047
- id,
5048
- input.sessionId,
5049
- input.taskId ?? null,
5050
- input.agentId,
5051
- input.totalCostUsd,
5052
- input.inputTokens ?? 0,
5053
- input.outputTokens ?? 0,
5054
- input.cacheReadTokens ?? 0,
5055
- input.cacheWriteTokens ?? 0,
5056
- reasoningOutputTokens,
5057
- thinkingTokens,
5058
- input.durationMs,
5059
- input.numTurns,
5060
- // Cost rows group by the underlying model, while task configuration and
5061
- // session logs retain the pi route used to select credentials.
5062
- chatgptSubscriptionModelId(input.model)?.toLowerCase() ?? input.model,
5063
- input.isError ? 1 : 0,
5064
- costSource,
5065
- input.harnessCostUsd ?? null,
5066
- input.cacheWrite5mTokens ?? null,
5067
- input.cacheWrite1hTokens ?? null,
5068
- input.modelBreakdown
5069
- ? JSON.stringify(
5070
- input.modelBreakdown.map((entry) => ({
5071
- ...entry,
5072
- model: chatgptSubscriptionModelId(entry.model)?.toLowerCase() ?? entry.model,
5073
- })),
5074
- )
5075
- : null,
5076
- ],
5077
- );
5078
-
5079
- const row = await getDbClient().get<SessionCostRow>("SELECT * FROM session_costs WHERE id = ?", [
5080
- id,
5081
- ]);
5082
- if (!row) throw new Error("Session cost record is missing after insertion.");
5083
- return rowToSessionCost(row);
4992
+ return (await insertSessionCost(input)).cost;
5084
4993
  }
5085
4994
 
5086
4995
  export async function getSessionCostsByTaskId(taskId: string, limit = 500): Promise<SessionCost[]> {
@@ -5182,6 +5091,9 @@ export interface SessionCostSummaryTotals {
5182
5091
  excludedTaskCount: number;
5183
5092
  /** API-priced cost of sessions whose task ran on a subscription credential (`SUBSCRIPTION_KEY_TYPES`). */
5184
5093
  subscriptionCostUsd: number;
5094
+ /** Cost without an immutable credential identity. Its billing type is unknown. */
5095
+ credentialUnattributedCostUsd: number;
5096
+ credentialUnattributedSessions: number;
5185
5097
  }
5186
5098
 
5187
5099
  export interface SessionCostDailyRow {
@@ -5192,6 +5104,9 @@ export interface SessionCostDailyRow {
5192
5104
  sessions: number;
5193
5105
  /** Part of `costUsd` that ran on a subscription credential. */
5194
5106
  subscriptionCostUsd: number;
5107
+ /** Cost without an immutable credential identity. Its billing type is unknown. */
5108
+ credentialUnattributedCostUsd: number;
5109
+ credentialUnattributedSessions: number;
5195
5110
  }
5196
5111
 
5197
5112
  /**
@@ -5202,7 +5117,7 @@ export type PlanSource = "manual" | "detected" | "estimated";
5202
5117
 
5203
5118
  /** Spend per credential, for the subscription vs API comparison. */
5204
5119
  export interface SessionCostByCredentialRow {
5205
- /** `null` when the task recorded no credential (or the session has no task). */
5120
+ /** Null when the executing session reported no credential. */
5206
5121
  keyType: string | null;
5207
5122
  keySuffix: string | null;
5208
5123
  /** Label set on the API Keys page. */
@@ -5299,7 +5214,7 @@ export async function getSessionCostSummary(opts: {
5299
5214
  }
5300
5215
 
5301
5216
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5302
- const subscriptionSql = `t.credentialKeyType IN (${SUBSCRIPTION_KEY_TYPES.map((k) => `'${k}'`).join(", ")})`;
5217
+ const subscriptionSql = `${CREDENTIAL_TYPE_SQL} IN (${SUBSCRIPTION_KEY_TYPES.map((k) => `'${k}'`).join(", ")})`;
5303
5218
 
5304
5219
  // Totals
5305
5220
  type TotalsRow = {
@@ -5315,6 +5230,8 @@ export async function getSessionCostSummary(opts: {
5315
5230
  excludedCostUsd: number;
5316
5231
  excludedTaskCount: number;
5317
5232
  subscriptionCostUsd: number;
5233
+ credentialUnattributedCostUsd: number;
5234
+ credentialUnattributedSessions: number;
5318
5235
  };
5319
5236
 
5320
5237
  const totalsRow = await getDbClient().get<TotalsRow>(
@@ -5334,7 +5251,10 @@ export async function getSessionCostSummary(opts: {
5334
5251
  THEN sc.totalCostUsd ELSE 0 END), 0) as excludedCostUsd,
5335
5252
  COUNT(DISTINCT CASE WHEN ${HUMAN_FREE_SQL} THEN t.id END) as excludedTaskCount,
5336
5253
  COALESCE(SUM(CASE WHEN ${subscriptionSql}
5337
- THEN sc.totalCostUsd ELSE 0 END), 0) as subscriptionCostUsd
5254
+ THEN sc.totalCostUsd ELSE 0 END), 0) as subscriptionCostUsd,
5255
+ COALESCE(SUM(CASE WHEN ${CREDENTIAL_TYPE_SQL} IS NULL
5256
+ THEN sc.totalCostUsd ELSE 0 END), 0) as credentialUnattributedCostUsd,
5257
+ COUNT(CASE WHEN ${CREDENTIAL_TYPE_SQL} IS NULL THEN 1 END) as credentialUnattributedSessions
5338
5258
  ${from} ${where}`,
5339
5259
  params,
5340
5260
  );
@@ -5359,6 +5279,8 @@ export async function getSessionCostSummary(opts: {
5359
5279
  excludedCostUsd: 0,
5360
5280
  excludedTaskCount: 0,
5361
5281
  subscriptionCostUsd: 0,
5282
+ credentialUnattributedCostUsd: 0,
5283
+ credentialUnattributedSessions: 0,
5362
5284
  };
5363
5285
 
5364
5286
  // Daily breakdown
@@ -5372,6 +5294,8 @@ export async function getSessionCostSummary(opts: {
5372
5294
  outputTokens: number;
5373
5295
  sessions: number;
5374
5296
  subscriptionCostUsd: number;
5297
+ credentialUnattributedCostUsd: number;
5298
+ credentialUnattributedSessions: number;
5375
5299
  }>(
5376
5300
  `SELECT
5377
5301
  DATE(sc.createdAt) as date,
@@ -5380,7 +5304,10 @@ export async function getSessionCostSummary(opts: {
5380
5304
  COALESCE(SUM(sc.outputTokens), 0) as outputTokens,
5381
5305
  COUNT(*) as sessions,
5382
5306
  COALESCE(SUM(CASE WHEN ${subscriptionSql} THEN sc.totalCostUsd ELSE 0 END), 0)
5383
- as subscriptionCostUsd
5307
+ as subscriptionCostUsd,
5308
+ COALESCE(SUM(CASE WHEN ${CREDENTIAL_TYPE_SQL} IS NULL
5309
+ THEN sc.totalCostUsd ELSE 0 END), 0) as credentialUnattributedCostUsd,
5310
+ COUNT(CASE WHEN ${CREDENTIAL_TYPE_SQL} IS NULL THEN 1 END) as credentialUnattributedSessions
5384
5311
  ${from} ${where}
5385
5312
  GROUP BY DATE(sc.createdAt)
5386
5313
  ORDER BY date ASC`,
@@ -5440,8 +5367,8 @@ export async function getSessionCostSummary(opts: {
5440
5367
  >;
5441
5368
  const rows = await getDbClient().query<CredentialRow>(
5442
5369
  `SELECT
5443
- t.credentialKeyType as keyType,
5444
- t.credentialKeySuffix as keySuffix,
5370
+ ${CREDENTIAL_TYPE_SQL} as keyType,
5371
+ ${CREDENTIAL_SUFFIX_SQL} as keySuffix,
5445
5372
  COALESCE(SUM(sc.totalCostUsd), 0) as costUsd,
5446
5373
  COALESCE(SUM(sc.inputTokens), 0) as inputTokens,
5447
5374
  COALESCE(SUM(sc.outputTokens), 0) as outputTokens,
@@ -5449,7 +5376,7 @@ export async function getSessionCostSummary(opts: {
5449
5376
  MIN(sc.createdAt) as firstSessionAt,
5450
5377
  MAX(sc.createdAt) as lastSessionAt
5451
5378
  ${from} ${where}
5452
- GROUP BY t.credentialKeyType, t.credentialKeySuffix
5379
+ GROUP BY ${CREDENTIAL_TYPE_SQL}, ${CREDENTIAL_SUFFIX_SQL}
5453
5380
  ORDER BY costUsd DESC`,
5454
5381
  params,
5455
5382
  );
@@ -5502,7 +5429,11 @@ async function getCredentialLabels(): Promise<
5502
5429
  const key = credentialKey(row.keyType, row.keySuffix);
5503
5430
  const seen = labels.get(key);
5504
5431
  if (!seen) {
5505
- labels.set(key, { name: row.name, plan: row.plan, planSource: row.planSource });
5432
+ labels.set(key, {
5433
+ name: row.name,
5434
+ plan: row.planSource === "estimated" ? null : row.plan,
5435
+ planSource: row.planSource,
5436
+ });
5506
5437
  } else if (!seen.name && row.name) {
5507
5438
  seen.name = row.name;
5508
5439
  }
@@ -5581,6 +5512,7 @@ export async function getAttributionByPerson(opts: {
5581
5512
  }
5582
5513
  }
5583
5514
  const where = `WHERE ${conditions.join(" AND ")}`;
5515
+ const githubHost = getGitHubHostForSql();
5584
5516
 
5585
5517
  type RootRow = { userId: string; initiated: number; shipped: number };
5586
5518
  const rootRows = await getDbClient().query<RootRow>(
@@ -5621,7 +5553,7 @@ export async function getAttributionByPerson(opts: {
5621
5553
  OR (
5622
5554
  ta.kind = 'url'
5623
5555
  AND (
5624
- ta.url LIKE '%github.com/%/pull/%'
5556
+ ta.url LIKE '%${githubHost}/%/pull/%'
5625
5557
  OR ta.url LIKE '%/-/merge_requests/%'
5626
5558
  )
5627
5559
  )
@@ -5633,7 +5565,7 @@ export async function getAttributionByPerson(opts: {
5633
5565
  -- CROSS JOIN pins the order (tree outer, task by id). Left to itself the
5634
5566
  -- planner scans every task's output and probes the tree instead.
5635
5567
  CROSS JOIN agent_tasks described ON described.id = tree.taskId
5636
- WHERE described.output LIKE '%github.com/%/pull/%'
5568
+ WHERE described.output LIKE '%${githubHost}/%/pull/%'
5637
5569
  OR described.output LIKE '%/-/merge_requests/%'
5638
5570
  )
5639
5571
  SELECT
@@ -10068,7 +10000,10 @@ export async function resolveApprovalRequest(
10068
10000
  id,
10069
10001
  ],
10070
10002
  );
10071
- return row ? rowToApprovalRequest(row) : null;
10003
+ if (!row) return null;
10004
+ const resolved = rowToApprovalRequest(row);
10005
+ scheduleApprovalCardUpdates([resolved]);
10006
+ return resolved;
10072
10007
  }
10073
10008
 
10074
10009
  // Cancels 1 pending request. The `status = 'pending'` guard lets a concurrent
@@ -10085,7 +10020,10 @@ export async function cancelApprovalRequestById(
10085
10020
  RETURNING *`,
10086
10021
  [scrubSecrets(data.reason), data.resolvedBy, now, now, id],
10087
10022
  );
10088
- return row ? rowToApprovalRequest(row) : null;
10023
+ if (!row) return null;
10024
+ const cancelled = rowToApprovalRequest(row);
10025
+ scheduleApprovalCardUpdates([cancelled]);
10026
+ return cancelled;
10089
10027
  }
10090
10028
 
10091
10029
  export async function cancelPendingApprovalRequestsForRun(
@@ -10100,7 +10038,9 @@ export async function cancelPendingApprovalRequestsForRun(
10100
10038
  RETURNING *`,
10101
10039
  [scrubSecrets(reason), now, now, workflowRunId],
10102
10040
  );
10103
- return rows.map(rowToApprovalRequest);
10041
+ const cancelled = rows.map(rowToApprovalRequest);
10042
+ scheduleApprovalCardUpdates(cancelled);
10043
+ return cancelled;
10104
10044
  }
10105
10045
 
10106
10046
  export async function listCancelledApprovalRequestsForRun(
@@ -10125,13 +10065,21 @@ export async function listCancelledApprovalRequestsForStep(
10125
10065
  return rows.map(rowToApprovalRequest);
10126
10066
  }
10127
10067
 
10068
+ /**
10069
+ * Lease one Slack side effect of a settled request. `cancellationNotificationClaims`
10070
+ * holds every such claim: the cancellation thread reply (`<channel>:<ts>`) and the
10071
+ * in-place card edit (`card:<channel>:<ts>`), so a retry never repeats a delivered one.
10072
+ * `anyTerminal` claims on every terminal status, not only `cancelled`.
10073
+ */
10128
10074
  export async function claimApprovalCancellationNotification(
10129
10075
  id: string,
10130
10076
  notificationKey: string,
10077
+ options?: { anyTerminal?: boolean },
10131
10078
  ): Promise<{ approval: ApprovalRequest; leaseToken: string } | null> {
10079
+ const statusClause = options?.anyTerminal ? "status <> 'pending'" : "status = 'cancelled'";
10132
10080
  return getDbClient().transaction(async () => {
10133
10081
  const row = await getDbClient().get<ApprovalRequestRow>(
10134
- "SELECT * FROM approval_requests WHERE id = ? AND status = 'cancelled'",
10082
+ `SELECT * FROM approval_requests WHERE id = ? AND ${statusClause}`,
10135
10083
  [id],
10136
10084
  );
10137
10085
  if (!row) return null;
@@ -10157,7 +10105,7 @@ export async function claimApprovalCancellationNotification(
10157
10105
  await getDbClient().run(
10158
10106
  `UPDATE approval_requests
10159
10107
  SET cancellationNotificationClaims = ?, updatedAt = ?
10160
- WHERE id = ? AND status = 'cancelled'`,
10108
+ WHERE id = ? AND ${statusClause}`,
10161
10109
  [JSON.stringify(claims), now, id],
10162
10110
  );
10163
10111
  return { approval: rowToApprovalRequest(row), leaseToken };
@@ -10206,7 +10154,7 @@ async function updateApprovalCancellationNotificationClaim(
10206
10154
  await getDbClient().run(
10207
10155
  `UPDATE approval_requests
10208
10156
  SET cancellationNotificationClaims = ?, updatedAt = ?
10209
- WHERE id = ? AND status = 'cancelled'`,
10157
+ WHERE id = ? AND status <> 'pending'`,
10210
10158
  [JSON.stringify(claims), new Date().toISOString(), id],
10211
10159
  );
10212
10160
  });
@@ -11865,9 +11813,11 @@ export interface ApiKeyStatus {
11865
11813
  provider: string;
11866
11814
  /** Latest provider-emitted rate-limit window snapshots, keyed by window type. */
11867
11815
  rateLimitWindows: RateLimitWindowTelemetry;
11816
+ providerAccount: ProviderAccountTelemetry | null;
11868
11817
  /** Subscription plan id (`SUBSCRIPTION_PLANS`), when known. */
11869
11818
  plan: string | null;
11870
11819
  planSource: PlanSource | null;
11820
+ detectedPlanRaw: string | null;
11871
11821
  /** When the CLI last rejected a model with `credits_required` on this key. */
11872
11822
  lastSeatMismatchAt: string | null;
11873
11823
  /** Model family of that rejection (`fable`, `opus`, ...). */
@@ -11881,7 +11831,10 @@ export interface ApiKeyStatus {
11881
11831
  updatedAt: string;
11882
11832
  }
11883
11833
 
11884
- type ApiKeyStatusRow = Omit<ApiKeyStatus, "rateLimitWindows"> & { rateLimitWindows: string | null };
11834
+ type ApiKeyStatusRow = Omit<ApiKeyStatus, "rateLimitWindows" | "providerAccount"> & {
11835
+ rateLimitWindows: string | null;
11836
+ providerAccount: string | null;
11837
+ };
11885
11838
 
11886
11839
  function parseRateLimitWindowsJson(value: string | null | undefined): RateLimitWindowTelemetry {
11887
11840
  if (!value) return {};
@@ -11897,7 +11850,11 @@ function parseRateLimitWindowsJson(value: string | null | undefined): RateLimitW
11897
11850
  }
11898
11851
 
11899
11852
  function rowToApiKeyStatus(row: ApiKeyStatusRow): ApiKeyStatus {
11900
- return { ...row, rateLimitWindows: parseRateLimitWindowsJson(row.rateLimitWindows) };
11853
+ return {
11854
+ ...row,
11855
+ rateLimitWindows: parseRateLimitWindowsJson(row.rateLimitWindows),
11856
+ providerAccount: parseProviderAccount(row.providerAccount),
11857
+ };
11901
11858
  }
11902
11859
 
11903
11860
  export interface AvailableKeyIndicesResult {
@@ -12063,18 +12020,19 @@ export async function recordKeyUsage(
12063
12020
  scopeId: string | null = null,
12064
12021
  /** Plan id the worker detected on the credential (for example from the Codex JWT). */
12065
12022
  plan: string | null = null,
12023
+ planRaw?: string | null,
12066
12024
  ): Promise<{ planChanged: boolean }> {
12067
12025
  const now = new Date().toISOString();
12068
- const client = getDbClient();
12069
- const effectiveScopeId = scopeId ?? "";
12070
-
12071
- // Upsert key status record. Sets `provider` on insert (auto-derived from
12072
- // keyType — see deriveProviderFromKeyType in src/utils/credentials.ts).
12073
- // The `name` column is left null on insert and only set via the
12074
- // setApiKeyName API endpoint when the user manually labels the key.
12075
- const provider = deriveProviderFromKeyType(keyType);
12076
- await client.run(
12077
- `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, lastUsedAt, totalUsageCount, provider, updatedAt)
12026
+ return getDbClient().transaction(async (client) => {
12027
+ const effectiveScopeId = scopeId ?? "";
12028
+
12029
+ // Upsert key status record. Sets `provider` on insert (auto-derived from
12030
+ // keyType, see deriveProviderFromKeyType in src/utils/credentials.ts).
12031
+ // The `name` column is left null on insert and only set via the
12032
+ // setApiKeyName API endpoint when the user manually labels the key.
12033
+ const provider = deriveProviderFromKeyType(keyType);
12034
+ await client.run(
12035
+ `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, lastUsedAt, totalUsageCount, provider, updatedAt)
12078
12036
  VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)
12079
12037
  ON CONFLICT(keyType, keySuffix, scope, scopeId)
12080
12038
  DO UPDATE SET
@@ -12082,29 +12040,53 @@ export async function recordKeyUsage(
12082
12040
  totalUsageCount = totalUsageCount + 1,
12083
12041
  keyIndex = excluded.keyIndex,
12084
12042
  updatedAt = excluded.updatedAt`,
12085
- [keyType, keySuffix, keyIndex, scope, effectiveScopeId, now, provider, now],
12086
- );
12043
+ [keyType, keySuffix, keyIndex, scope, effectiveScopeId, now, provider, now],
12044
+ );
12087
12045
 
12088
- // A detected plan replaces an estimate, never a plan the operator picked.
12089
- let planChanged = false;
12090
- if (plan) {
12091
- const result = await client.run(
12092
- `UPDATE api_key_status SET plan = ?, planSource = 'detected'
12046
+ const ambiguousPro =
12047
+ keyType === "CODEX_OAUTH" &&
12048
+ (plan === "chatgpt_pro" || plan === "chatgpt_pro_5x" || plan === "chatgpt_pro_500");
12049
+ let planChanged = false;
12050
+ const rawIdentity = planRaw
12051
+ ? scrubSecrets(planRaw).slice(0, 80)
12052
+ : keyType === "CODEX_OAUTH" && plan === "chatgpt_pro"
12053
+ ? "pro"
12054
+ : null;
12055
+ // A legacy plan report must not retain a contradictory raw claim.
12056
+ if (rawIdentity || plan) {
12057
+ await client.run(
12058
+ "UPDATE api_key_status SET detectedPlanRaw = ? WHERE keyType = ? AND keySuffix = ?",
12059
+ [rawIdentity, keyType, keySuffix],
12060
+ );
12061
+ }
12062
+ if (ambiguousPro || (keyType === "CODEX_OAUTH" && planRaw && !codexPlanFromClaim(planRaw))) {
12063
+ plan = null;
12064
+ const cleared = await client.run(
12065
+ "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')",
12066
+ [keyType, keySuffix],
12067
+ );
12068
+ planChanged = cleared.changes > 0;
12069
+ }
12070
+ // A detected plan replaces an estimate, never a plan the operator picked.
12071
+ if (plan) {
12072
+ const result = await client.run(
12073
+ `UPDATE api_key_status SET plan = ?, planSource = 'detected'
12093
12074
  WHERE keyType = ? AND keySuffix = ? AND COALESCE(planSource, '') != 'manual'
12094
12075
  AND (plan IS NOT ? OR planSource IS NOT 'detected')`,
12095
- [plan, keyType, keySuffix, plan],
12096
- );
12097
- planChanged = result.changes > 0;
12098
- }
12076
+ [plan, keyType, keySuffix, plan],
12077
+ );
12078
+ planChanged = result.changes > 0;
12079
+ }
12099
12080
 
12100
- // Record which key was used on the task
12101
- if (taskId) {
12102
- await client.run(
12103
- "UPDATE agent_tasks SET credentialKeySuffix = ?, credentialKeyType = ? WHERE id = ?",
12104
- [keySuffix, keyType, taskId],
12105
- );
12106
- }
12107
- return { planChanged };
12081
+ // Record which key was used on the task
12082
+ if (taskId) {
12083
+ await client.run(
12084
+ "UPDATE agent_tasks SET credentialKeySuffix = ?, credentialKeyType = ? WHERE id = ?",
12085
+ [keySuffix, keyType, taskId],
12086
+ );
12087
+ }
12088
+ return { planChanged };
12089
+ });
12108
12090
  }
12109
12091
 
12110
12092
  /**
@@ -12219,34 +12201,6 @@ export async function recordKeyAuthFailure(
12219
12201
  });
12220
12202
  }
12221
12203
 
12222
- /**
12223
- * Merges reported window snapshots into the stored ones, one window type at a
12224
- * time. A reported entry replaces the stored entry unless the stored entry was
12225
- * observed strictly later (`lastSeenAt`), so an older `allowed` snapshot that
12226
- * arrives after a terminal rejection cannot reopen an exhausted window. An
12227
- * unparseable `lastSeenAt` on either side falls back to "reported wins".
12228
- */
12229
- function mergeRateLimitWindowTelemetry(
12230
- stored: RateLimitWindowTelemetry,
12231
- reported: RateLimitWindowTelemetry,
12232
- ): RateLimitWindowTelemetry {
12233
- const merged: RateLimitWindowTelemetry = { ...stored };
12234
- for (const [type, entry] of Object.entries(reported)) {
12235
- const current = merged[type];
12236
- const currentSeenMs = current ? Date.parse(current.lastSeenAt) : Number.NaN;
12237
- const reportedSeenMs = Date.parse(entry.lastSeenAt);
12238
- if (
12239
- Number.isFinite(currentSeenMs) &&
12240
- Number.isFinite(reportedSeenMs) &&
12241
- currentSeenMs > reportedSeenMs
12242
- ) {
12243
- continue;
12244
- }
12245
- merged[type] = entry;
12246
- }
12247
- return merged;
12248
- }
12249
-
12250
12204
  /**
12251
12205
  * Persists reported window snapshots for a key. Admission
12252
12206
  * (`getAvailableKeyIndices`) reads these windows, so the read-merge-write
@@ -12261,81 +12215,54 @@ export async function recordKeyRateLimitWindows(
12261
12215
  windows: RateLimitWindowTelemetry,
12262
12216
  scope = "global",
12263
12217
  scopeId: string | null = null,
12264
- ): Promise<{ planChanged: boolean }> {
12265
- if (Object.keys(windows).length === 0) return { planChanged: false };
12218
+ account?: ProviderAccountTelemetry,
12219
+ replace: RateLimitReplacement[] = [],
12220
+ ): Promise<void> {
12221
+ if (Object.keys(windows).length === 0 && !account && !replace.length) return;
12266
12222
 
12267
12223
  const now = new Date().toISOString();
12268
12224
  const effectiveScopeId = scopeId ?? "";
12269
12225
  const provider = deriveProviderFromKeyType(keyType);
12270
- const merged = await getDbClient().transaction(async (tx) => {
12271
- const existing = await tx.get<{ rateLimitWindows: string | null }>(
12272
- `SELECT rateLimitWindows FROM api_key_status
12226
+ await getDbClient().transaction(async (tx) => {
12227
+ const existing = await tx.get<{
12228
+ rateLimitWindows: string | null;
12229
+ providerAccount: string | null;
12230
+ }>(
12231
+ `SELECT rateLimitWindows, providerAccount FROM api_key_status
12273
12232
  WHERE keyType = ? AND keySuffix = ? AND scope = ? AND scopeId = ?`,
12274
12233
  [keyType, keySuffix, scope, effectiveScopeId],
12275
12234
  );
12276
- const mergedWindows = mergeRateLimitWindowTelemetry(
12277
- parseRateLimitWindowsJson(existing?.rateLimitWindows),
12278
- windows,
12235
+ const { windows: mergedWindows, account: mergedAccount } = applyProviderQuotaReport(
12236
+ {
12237
+ windows: parseRateLimitWindowsJson(existing?.rateLimitWindows),
12238
+ account: parseProviderAccount(existing?.providerAccount),
12239
+ },
12240
+ scrubProviderQuotaReport({ windows, account, replace }),
12279
12241
  );
12280
- const serialized = JSON.stringify(mergedWindows);
12281
-
12242
+ assertProviderQuotaCapacity({ windows: mergedWindows, account: mergedAccount });
12282
12243
  await tx.run(
12283
- `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, rateLimitWindows, provider, updatedAt)
12284
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
12244
+ `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, rateLimitWindows, providerAccount, provider, updatedAt)
12245
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
12285
12246
  ON CONFLICT(keyType, keySuffix, scope, scopeId)
12286
12247
  DO UPDATE SET
12287
12248
  rateLimitWindows = excluded.rateLimitWindows,
12249
+ providerAccount = excluded.providerAccount,
12288
12250
  keyIndex = excluded.keyIndex,
12289
12251
  provider = excluded.provider,
12290
12252
  updatedAt = excluded.updatedAt`,
12291
- [keyType, keySuffix, keyIndex, scope, effectiveScopeId, serialized, provider, now],
12253
+ [
12254
+ keyType,
12255
+ keySuffix,
12256
+ keyIndex,
12257
+ scope,
12258
+ effectiveScopeId,
12259
+ JSON.stringify(mergedWindows),
12260
+ mergedAccount ? JSON.stringify(mergedAccount) : null,
12261
+ provider,
12262
+ now,
12263
+ ],
12292
12264
  );
12293
- return mergedWindows;
12294
12265
  });
12295
-
12296
- const planChanged =
12297
- keyType === "CLAUDE_CODE_OAUTH_TOKEN" && (await refreshEstimatedClaudePlan(keySuffix, merged));
12298
- return { planChanged };
12299
- }
12300
-
12301
- const WEEK_SECONDS = 7 * 24 * 3600;
12302
-
12303
- /**
12304
- * Estimate the plan of a Claude credential from its 7-day window (see
12305
- * `estimateClaudePlan`), unless a stronger source already set it. Returns
12306
- * true when the stored plan changed.
12307
- */
12308
- async function refreshEstimatedClaudePlan(
12309
- keySuffix: string,
12310
- windows: RateLimitWindowTelemetry,
12311
- ): Promise<boolean> {
12312
- const week = windows.seven_day;
12313
- if (!week?.utilization || !week.resetsAt) return false;
12314
- const client = getDbClient();
12315
- const stronger = await client.get<{ found: number }>(
12316
- `SELECT 1 as found FROM api_key_status
12317
- WHERE keyType = 'CLAUDE_CODE_OAUTH_TOKEN' AND keySuffix = ? AND planSource IN ('manual', 'detected')
12318
- LIMIT 1`,
12319
- [keySuffix],
12320
- );
12321
- if (stronger) return false;
12322
- const windowStart = new Date((week.resetsAt - WEEK_SECONDS) * 1000).toISOString();
12323
- const spend = await client.get<{ spendUsd: number }>(
12324
- `SELECT COALESCE(SUM(sc.totalCostUsd), 0) as spendUsd
12325
- FROM session_costs sc JOIN agent_tasks t ON t.id = sc.taskId
12326
- WHERE t.credentialKeyType = 'CLAUDE_CODE_OAUTH_TOKEN' AND t.credentialKeySuffix = ?
12327
- AND sc.createdAt >= ?`,
12328
- [keySuffix, windowStart],
12329
- );
12330
- const plan = estimateClaudePlan(week.utilization, spend?.spendUsd ?? 0);
12331
- if (!plan) return false;
12332
- const result = await client.run(
12333
- `UPDATE api_key_status SET plan = ?, planSource = 'estimated'
12334
- WHERE keyType = 'CLAUDE_CODE_OAUTH_TOKEN' AND keySuffix = ?
12335
- AND COALESCE(planSource, 'estimated') = 'estimated' AND plan IS NOT ?`,
12336
- [plan, keySuffix, plan],
12337
- );
12338
- return result.changes > 0;
12339
12266
  }
12340
12267
 
12341
12268
  /**
@@ -12454,36 +12381,30 @@ export interface KeyCostSummary {
12454
12381
  }
12455
12382
 
12456
12383
  /**
12457
- * Aggregate cost data per API key by joining session_costs through agent_tasks.
12384
+ * Aggregate cost data using immutable session credentials (legacy rows: the task's).
12458
12385
  */
12459
12386
  export async function getKeyCostSummary(keyType?: string): Promise<KeyCostSummary[]> {
12460
- const conditions = ["t.credentialKeySuffix IS NOT NULL"];
12387
+ const conditions = [`${CREDENTIAL_SUFFIX_SQL} IS NOT NULL`];
12461
12388
  const params: string[] = [];
12462
12389
 
12463
12390
  if (keyType) {
12464
- conditions.push("t.credentialKeyType = ?");
12391
+ conditions.push(`${CREDENTIAL_TYPE_SQL} = ?`);
12465
12392
  params.push(keyType);
12466
12393
  }
12467
12394
 
12468
12395
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
12469
- // Phase 13: INNER JOIN -> LEFT JOIN. The `WHERE t.credentialKeySuffix IS NOT NULL`
12470
- // still filters out rows whose taskId doesn't link to a task with credentials,
12471
- // but switching to LEFT JOIN means a future change that drops the WHERE
12472
- // (or a debugging query that wants orphan rows visible) doesn't silently
12473
- // disappear them. Equivalent for the current `WHERE … IS NOT NULL` filter;
12474
- // makes the query's intent (cost rows owned by a credential) explicit.
12475
12396
  return getDbClient().query<KeyCostSummary>(
12476
12397
  `SELECT
12477
- t.credentialKeyType as keyType,
12478
- t.credentialKeySuffix as keySuffix,
12398
+ ${CREDENTIAL_TYPE_SQL} as keyType,
12399
+ ${CREDENTIAL_SUFFIX_SQL} as keySuffix,
12479
12400
  COALESCE(SUM(sc.totalCostUsd), 0) as totalCost,
12480
12401
  COALESCE(SUM(sc.inputTokens), 0) as totalInputTokens,
12481
12402
  COALESCE(SUM(sc.outputTokens), 0) as totalOutputTokens,
12482
12403
  COUNT(DISTINCT sc.taskId) as taskCount
12483
12404
  FROM session_costs sc
12484
- LEFT JOIN agent_tasks t ON sc.taskId = t.id
12405
+ LEFT JOIN agent_tasks t INDEXED BY idx_agent_tasks_usage_cover ON t.id = sc.taskId
12485
12406
  ${where}
12486
- GROUP BY t.credentialKeyType, t.credentialKeySuffix`,
12407
+ GROUP BY ${CREDENTIAL_TYPE_SQL}, ${CREDENTIAL_SUFFIX_SQL}`,
12487
12408
  params,
12488
12409
  );
12489
12410
  }
@@ -12991,10 +12912,12 @@ export async function setFavorite(opts: {
12991
12912
  favorite: boolean;
12992
12913
  actorId?: string | null;
12993
12914
  }): Promise<UserFavorite | null> {
12915
+ // A `key` item id arrives normalized: `PUT /api/favorites` normalizes it and answers 400.
12916
+ const itemId = opts.itemId;
12994
12917
  if (!opts.favorite) {
12995
12918
  await getDbClient().run(
12996
12919
  "DELETE FROM user_favorites WHERE favoriteScope = ? AND itemType = ? AND itemId = ?",
12997
- [opts.favoriteScope, opts.itemType, opts.itemId],
12920
+ [opts.favoriteScope, opts.itemType, itemId],
12998
12921
  );
12999
12922
  return null;
13000
12923
  }
@@ -13010,7 +12933,7 @@ export async function setFavorite(opts: {
13010
12933
  lastUpdatedAt = excluded.lastUpdatedAt,
13011
12934
  updated_by = excluded.updated_by
13012
12935
  RETURNING *`,
13013
- [opts.favoriteScope, opts.userId ?? null, opts.itemType, opts.itemId, now, now, actor, actor],
12936
+ [opts.favoriteScope, opts.userId ?? null, opts.itemType, itemId, now, now, actor, actor],
13014
12937
  );
13015
12938
  if (!row) throw new Error("Failed to set favorite");
13016
12939
  return rowToUserFavorite(row);