@desplega.ai/agent-swarm 2.8.1 → 2.8.3

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 (318) hide show
  1. package/dist/acp-adapter-xq6s2z6t.js +14 -0
  2. package/dist/{actions-pwjpn0j6.js → actions-ewz7bp4g.js} +20 -19
  3. package/dist/{amp-adapter-cq9jgj6x.js → amp-adapter-f25tqhnf.js} +3 -3
  4. package/dist/{app-cnfffgwg.js → app-mkptw0k7.js} +4 -4
  5. package/dist/{assistant-kpn317y1.js → assistant-c47rfe77.js} +23 -22
  6. package/dist/{boot-args-schema-pbbnhmc3.js → boot-args-schema-4vb0xsat.js} +1 -1
  7. package/dist/{boot-reembed-9m0ysxma.js → boot-reembed-1ghy2sab.js} +1 -1
  8. package/dist/{boot-reembed-majbn53m.js → boot-reembed-htr73hbs.js} +1 -1
  9. package/dist/{boot-scrub-sweep-app8g8ym.js → boot-scrub-sweep-yrytg42z.js} +4 -4
  10. package/dist/{boot-seeds-pbtmvcjm.js → boot-seeds-n2b3dx4e.js} +4 -4
  11. package/dist/{boxd-qbkxy6ap.js → boxd-jmfqgkqa.js} +2 -2
  12. package/dist/{claude-adapter-wn1g3qp5.js → claude-adapter-r33pqnzx.js} +8 -9
  13. package/dist/{claude-managed-adapter-jh6c523j.js → claude-managed-adapter-hddmxjyj.js} +4 -4
  14. package/dist/{claude-managed-setup-pd47nzch.js → claude-managed-setup-hfvry1bd.js} +5 -5
  15. package/dist/{claude-sdk-session-3a2a6589.js → claude-sdk-session-0hamqzc7.js} +10 -11
  16. package/dist/{cli-v1dv1r37.js → cli-0bcgyj5b.js} +74 -3
  17. package/dist/{cli-a3b239vq.js → cli-0vksaxvr.js} +2 -2
  18. package/dist/{cli-mrt48bx7.js → cli-15204js0.js} +1 -1
  19. package/dist/{cli-8aes17e4.js → cli-1m96dc36.js} +3 -3
  20. package/dist/{cli-2r0jcc3k.js → cli-2d0cghfn.js} +1 -1
  21. package/dist/{cli-wk18cm92.js → cli-4ax9mvvg.js} +4 -4
  22. package/dist/{cli-9wngrawf.js → cli-4dpkjc2e.js} +6 -6
  23. package/dist/{cli-x1wa213s.js → cli-4e1hfbpq.js} +5 -5
  24. package/dist/{cli-7349va39.js → cli-500c09j9.js} +921 -431
  25. package/dist/{cli-m4dqmnbp.js → cli-54qr8mcd.js} +2 -2
  26. package/dist/{cli-m88rpzkh.js → cli-5a7szzfh.js} +2 -2
  27. package/dist/{cli-bst1vp7e.js → cli-5y2fvw4z.js} +13 -5
  28. package/dist/{cli-vj75tyaw.js → cli-6yygkr0w.js} +7 -7
  29. package/dist/{cli-7b8sbmag.js → cli-7c5tgqhf.js} +5 -5
  30. package/dist/{cli-2gxeg5gr.js → cli-8476gtwf.js} +1 -1
  31. package/dist/{cli-yncmerje.js → cli-922z7gwm.js} +4 -4
  32. package/dist/{cli-jrzkw01m.js → cli-93t5s4zq.js} +2 -2
  33. package/dist/{cli-sn7rtnj4.js → cli-9zmb7ptc.js} +9 -9
  34. package/dist/{cli-tk7cjj8h.js → cli-am1ptset.js} +3 -3
  35. package/dist/{cli-cyhbbd1z.js → cli-awwptga4.js} +1 -1
  36. package/dist/{cli-89cqnasv.js → cli-bhsfbmk8.js} +19 -7
  37. package/dist/{cli-9vhebtjz.js → cli-bj6qhgte.js} +15 -32
  38. package/dist/{cli-g70vxtjh.js → cli-c0xjnr8z.js} +2 -2
  39. package/dist/{cli-vqptjbr7.js → cli-c3ng0mb4.js} +14 -14
  40. package/dist/{cli-re4raaj0.js → cli-c71n3bxq.js} +11 -6
  41. package/dist/{cli-7p1kvkck.js → cli-crpf163n.js} +25 -18
  42. package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
  43. package/dist/{cli-d3p5vwbk.js → cli-dpsfwh7n.js} +13 -21
  44. package/dist/{cli-xzm9vcfg.js → cli-dtdht77h.js} +2 -2
  45. package/dist/{cli-bb431xey.js → cli-e2w34h6z.js} +231 -68
  46. package/dist/{cli-eddnyg3t.js → cli-emekyyhr.js} +1 -1
  47. package/dist/{cli-d84byzn8.js → cli-f1kwb5fc.js} +109 -33
  48. package/dist/{cli-0jzra9ad.js → cli-gn9y6fn7.js} +2 -2
  49. package/dist/{cli-tqegb8eq.js → cli-gpz1d0t2.js} +4 -4
  50. package/dist/{cli-7w69ne2f.js → cli-h9yy18gy.js} +239 -67
  51. package/dist/{cli-m5akxq8q.js → cli-j8cjdzan.js} +1 -1
  52. package/dist/{cli-m9s2qff2.js → cli-jg5txpm6.js} +187 -93
  53. package/dist/{cli-k26bkr9t.js → cli-k2rw11py.js} +3 -3
  54. package/dist/{cli-93k32c37.js → cli-k96cecs7.js} +377 -61
  55. package/dist/{cli-3vjhs18n.js → cli-kd56bmk4.js} +1 -1
  56. package/dist/{cli-k0615eh8.js → cli-kmemts3w.js} +13 -13
  57. package/dist/{cli-pcad4cb1.js → cli-knva3nmx.js} +2 -2
  58. package/dist/{cli-b085njxz.js → cli-kw44j53p.js} +15 -14
  59. package/dist/{cli-bsywb58a.js → cli-mdpbjnzq.js} +10 -10
  60. package/dist/{cli-syybb0p1.js → cli-me0r8gzr.js} +35 -76
  61. package/dist/{cli-4r05hnqa.js → cli-mwwmka77.js} +15 -15
  62. package/dist/{cli-1xh9a7hn.js → cli-n5t077me.js} +2 -2
  63. package/dist/{cli-rvhdmjvt.js → cli-nx2n3z6p.js} +1 -1
  64. package/dist/{cli-28fq781p.js → cli-pe4d96rb.js} +1 -1
  65. package/dist/{cli-3rkdne1h.js → cli-pxwtcgcp.js} +2 -2
  66. package/dist/{cli-zcsw143p.js → cli-qmqt520k.js} +2 -2
  67. package/dist/{cli-2zp0et3v.js → cli-qps8je6j.js} +70 -19
  68. package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
  69. package/dist/{cli-k93bq1wq.js → cli-rjvsf9qa.js} +5 -5
  70. package/dist/{cli-6mma83xa.js → cli-rqfvkx5t.js} +7 -7
  71. package/dist/{cli-dy32zecz.js → cli-s7zz734a.js} +1 -1
  72. package/dist/{cli-yn2bbre9.js → cli-s8p8hhty.js} +2 -2
  73. package/dist/{cli-vbh10fqa.js → cli-sdvcrq5x.js} +5 -5
  74. package/dist/{cli-b5rs97a6.js → cli-sg27rk2t.js} +5 -5
  75. package/dist/{cli-d6521kb5.js → cli-skmhsnqh.js} +1 -1
  76. package/dist/{cli-5mrq3ake.js → cli-t4dv07kr.js} +1 -1
  77. package/dist/{cli-hxpyc9sn.js → cli-t5ys4ebm.js} +3 -3
  78. package/dist/{cli-qmqk2yc2.js → cli-tas6ckky.js} +2 -2
  79. package/dist/{cli-p1w18yhx.js → cli-tf79ryyy.js} +1 -1
  80. package/dist/{cli-kc7v1nfv.js → cli-tnzebztn.js} +1 -1
  81. package/dist/{cli-gax7fk3t.js → cli-vx421edw.js} +3 -3
  82. package/dist/{cli-kchjb7qy.js → cli-x3ex5bqf.js} +1 -1
  83. package/dist/cli-yss07azk.js +142 -0
  84. package/dist/{cli-0ntbxyaa.js → cli-z8cvws4c.js} +363 -47
  85. package/dist/{cli-tacge1w0.js → cli-zdaypkq9.js} +146 -52
  86. package/dist/{cli-b8e9nb04.js → cli-zeaehgyd.js} +2 -2
  87. package/dist/{cli-jcpr5smb.js → cli-ztq5z4e1.js} +4 -4
  88. package/dist/cli.js +21 -21
  89. package/dist/{codex-adapter-nha71q3n.js → codex-adapter-2brxx5ta.js} +7 -8
  90. package/dist/{codex-hook-h3vk6xzr.js → codex-hook-c930c3ea.js} +2 -2
  91. package/dist/{codex-login-bcda78ge.js → codex-login-cbrs1h5w.js} +1 -1
  92. package/dist/{codex-session-runner-ak9x1k1h.js → codex-session-runner-y9anfj0r.js} +8 -9
  93. package/dist/{commands-f587qpq8.js → commands-wn9q06qr.js} +3 -3
  94. package/dist/{controller-hxx8wwy1.js → controller-fw608czd.js} +4 -4
  95. package/dist/{controllers-connect-k5sg9m9h.js → controllers-connect-63j5rdcm.js} +20 -20
  96. package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-6mb9jme8.js} +2 -2
  97. package/dist/{db-nzf8zb5z.js → db-0m6v5tq4.js} +3 -3
  98. package/dist/{db-amm8w15a.js → db-y4wfrzbm.js} +4 -2
  99. package/dist/{devin-adapter-xedz98zv.js → devin-adapter-r0yx3gv8.js} +1 -1
  100. package/dist/{dispatcher-89zrts8f.js → dispatcher-9tq2zzdj.js} +17 -17
  101. package/dist/{docker-866qpzt9.js → docker-j75atvpt.js} +2 -2
  102. package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-t09sv4tq.js} +2 -2
  103. package/dist/{e2b-s16txnpx.js → e2b-7s9dscap.js} +3 -3
  104. package/dist/{e2b-jkwfhbcv.js → e2b-a7vzs2vj.js} +3 -3
  105. package/dist/{easter-egg-3d-533knw22.js → easter-egg-3d-fbwvmwhe.js} +1 -1
  106. package/dist/{embedding-space-ezwenjmj.js → embedding-space-wh8de1t9.js} +6 -6
  107. package/dist/{embeddings-np74ht6g.js → embeddings-3hpbdtjr.js} +1 -1
  108. package/dist/{event-bus-e66gh7cc.js → event-bus-tr6h3gv8.js} +1 -1
  109. package/dist/{execute-b3mrb1mv.js → execute-4bdf8sdy.js} +1 -1
  110. package/dist/{external-channel-z46yx9d7.js → external-channel-ts2fwqh0.js} +2 -2
  111. package/dist/fx-adapter-1rnxnf56.js +17 -0
  112. package/dist/grok-adapter-efhmf1r8.js +17 -0
  113. package/dist/handlers-anrr3py9.js +32 -0
  114. package/dist/{heartbeat-dt9qw9c8.js → heartbeat-2ze5fzpc.js} +20 -20
  115. package/dist/{hook-8k6fbz9b.js → hook-ca54yd4s.js} +5 -5
  116. package/dist/{hook-jgcgygex.js → hook-gaehe2w5.js} +8 -8
  117. package/dist/{http-haw4r8ne.js → http-jfg8t2yk.js} +3839 -122
  118. package/dist/{index-tvfafeyy.js → index-3gv6sc4z.js} +1 -1
  119. package/dist/{index-tez78qj3.js → index-3yvzbhxd.js} +100 -23
  120. package/dist/index-8w2aznds.js +33 -0
  121. package/dist/{index-5gk12my8.js → index-csgrxedz.js} +1 -1
  122. package/dist/index-qnjvr362.js +37 -0
  123. package/dist/index-yzxd3sn9.js +32 -0
  124. package/dist/{keepalive-xn6s7rmg.js → keepalive-k2a3qe73.js} +4 -4
  125. package/dist/lead-zhxqbfdv.js +69 -0
  126. package/dist/{maintenance-vdts800b.js → maintenance-gb5sd5nc.js} +1 -1
  127. package/dist/{node-4c5jqxr3.js → node-7qsx5kvm.js} +1 -1
  128. package/dist/{oauth-refresh-sweep-094c8wfk.js → oauth-refresh-sweep-y7rm6bkb.js} +3 -3
  129. package/dist/{onboard-v99eh56m.js → onboard-jmc5qerv.js} +4 -4
  130. package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-7eade9ev.js} +6 -7
  131. package/dist/{otel-impl-q7yr9yp0.js → otel-impl-8j1xhxqd.js} +2 -2
  132. package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-yqmaf32x.js} +14 -13
  133. package/dist/{pricing-refresh-7dh2yase.js → pricing-refresh-1nj722h6.js} +2 -2
  134. package/dist/{rbac-roles-mdmc96p4.js → rbac-roles-b1mtr6dr.js} +3 -3
  135. package/dist/{rbac-roles-npbmdh77.js → rbac-roles-n1f3frk1.js} +2 -2
  136. package/dist/{render-v2-twhhwmms.js → render-v2-1gfpd8rj.js} +4 -4
  137. package/dist/{resume-5gsrjd5e.js → resume-w1s1eh5v.js} +7 -7
  138. package/dist/{runtime-1hv06jsn.js → runtime-84g5egsc.js} +1 -1
  139. package/dist/{session-access-m191x30x.js → session-access-y6z1txk4.js} +4 -4
  140. package/dist/{session-source-backfill-nt923ask.js → session-source-backfill-gxxwfh12.js} +3 -3
  141. package/dist/{setup-wv467afy.js → setup-r91gstyk.js} +1 -1
  142. package/dist/{virtual-modules-gazyapte.js → virtual-modules-cgnj6kme.js} +3 -3
  143. package/dist/{work-objects-8zkrpy13.js → work-objects-qcxzg61c.js} +20 -20
  144. package/dist/worker-7j2907g6.js +69 -0
  145. package/dist/{worker-follow-up-cecqszem.js → worker-follow-up-y2d2h7km.js} +19 -17
  146. package/dist/{x-2fyrt5pp.js → x-qhxq2ama.js} +2 -2
  147. package/openapi.json +2908 -351
  148. package/package.json +4 -4
  149. package/src/apps/catalog.generated.json +120 -1
  150. package/src/apps/definition.ts +38 -11
  151. package/src/apps/page-validator.ts +88 -0
  152. package/src/be/db/model-profiles.ts +110 -11
  153. package/src/be/db/tasks/read.ts +53 -0
  154. package/src/be/db/workflow-run-definitions.ts +19 -8
  155. package/src/be/db-client.ts +43 -5
  156. package/src/be/db.ts +40 -9
  157. package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
  158. package/src/be/migrations/289_automation_savings_daily.sql +47 -0
  159. package/src/be/migrations/291_task_slack_participants.sql +4 -0
  160. package/src/be/migrations/293_savings_component_links.sql +58 -0
  161. package/src/be/migrations/296_automation_savings_daily_read_index.sql +6 -0
  162. package/src/be/model-profile-check.ts +53 -20
  163. package/src/be/runtime-pools/routing.ts +1 -0
  164. package/src/be/savings/calibrate.ts +468 -0
  165. package/src/be/savings/compute.ts +677 -0
  166. package/src/be/savings/model.ts +674 -0
  167. package/src/be/savings/read.ts +1500 -0
  168. package/src/be/savings/rollup.ts +571 -0
  169. package/src/be/scripts/run-credential.ts +15 -3
  170. package/src/be/scripts/typecheck.ts +91 -4
  171. package/src/be/seed/agent-fs-provision.ts +48 -11
  172. package/src/be/seed/workflows-seeder.ts +67 -23
  173. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +10 -2
  174. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +70 -4
  175. package/src/be/skill-parser.ts +19 -7
  176. package/src/be/swarm-config-guard.ts +8 -0
  177. package/src/be/users.ts +29 -2
  178. package/src/commands/onboard/agent-fs-version.ts +1 -1
  179. package/src/commands/provider-error-class.ts +97 -0
  180. package/src/commands/runner.ts +258 -58
  181. package/src/extensions/contract-types.generated.ts +1 -1
  182. package/src/http/all-routes.ts +2 -0
  183. package/src/http/fs.ts +8 -2
  184. package/src/http/index.ts +11 -0
  185. package/src/http/model-profiles.ts +43 -10
  186. package/src/http/poll.ts +15 -1
  187. package/src/http/requested-by.ts +97 -1
  188. package/src/http/savings-calibration.ts +277 -0
  189. package/src/http/savings.ts +849 -0
  190. package/src/http/scripts.ts +26 -15
  191. package/src/http/tasks.ts +89 -9
  192. package/src/http/trackers/authorize-gate.ts +41 -0
  193. package/src/http/trackers/jira.ts +26 -4
  194. package/src/http/trackers/linear.ts +26 -4
  195. package/src/integrations/chat-sdk/limits.ts +6 -1
  196. package/src/jira/oauth.ts +7 -1
  197. package/src/linear/README.md +2 -1
  198. package/src/linear/oauth.ts +7 -1
  199. package/src/prompts/session-templates.ts +80 -3
  200. package/src/providers/acp-targets.ts +1 -1
  201. package/src/providers/amp-adapter.ts +1 -1
  202. package/src/providers/claude-adapter.ts +0 -20
  203. package/src/providers/claude-flag-settings.ts +12 -10
  204. package/src/providers/codex-adapter.ts +12 -34
  205. package/src/providers/opencode-adapter.ts +34 -12
  206. package/src/providers/pi-mono-adapter.ts +6 -5
  207. package/src/providers/types.ts +7 -0
  208. package/src/scheduler/scheduler.ts +20 -14
  209. package/src/scripts-runtime/ctx.ts +1 -1
  210. package/src/scripts-runtime/executors/quickjs-bundle.ts +1 -0
  211. package/src/scripts-runtime/executors/quickjs-prelude.ts +162 -2
  212. package/src/scripts-runtime/executors/quickjs-runner.ts +4 -1
  213. package/src/scripts-runtime/sdk-allowlist.ts +11 -1
  214. package/src/scripts-runtime/stdlib/fetch.ts +113 -15
  215. package/src/scripts-runtime/stdlib/index.ts +3 -1
  216. package/src/scripts-runtime/stdlib/retry.ts +174 -0
  217. package/src/scripts-runtime/swarm-sdk.ts +192 -17
  218. package/src/scripts-runtime/types/stdlib.d.ts +95 -4
  219. package/src/scripts-runtime/types/swarm-extension.d.ts +60 -0
  220. package/src/scripts-runtime/types/swarm-sdk.d.ts +69 -2
  221. package/src/slack/actions.ts +1 -0
  222. package/src/slack/assistant.ts +2 -0
  223. package/src/slack/enrich.ts +144 -50
  224. package/src/slack/handlers.ts +37 -95
  225. package/src/slack/templates.ts +9 -0
  226. package/src/slack/thread-buffer.ts +45 -71
  227. package/src/slack/thread-participants.ts +187 -0
  228. package/src/tasks/worker-follow-up.ts +142 -3
  229. package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
  230. package/src/tests/apps-chart-shell.test.ts +170 -0
  231. package/src/tests/apps-icon.test.ts +156 -2
  232. package/src/tests/base-prompt.test.ts +5 -4
  233. package/src/tests/chat-sdk-relay.test.ts +12 -0
  234. package/src/tests/claude-adapter-binary.test.ts +7 -1
  235. package/src/tests/claude-adapter.test.ts +10 -64
  236. package/src/tests/claude-flag-settings.test.ts +15 -11
  237. package/src/tests/claude-hook-credentials.test.ts +0 -1
  238. package/src/tests/claude-sdk-lifecycle.test.ts +5 -1
  239. package/src/tests/codex-adapter.test.ts +28 -78
  240. package/src/tests/comb-default.test.ts +6 -0
  241. package/src/tests/core-auth.test.ts +7 -6
  242. package/src/tests/create-task-vcs-repo.test.ts +136 -0
  243. package/src/tests/db-client-busy-retry.test.ts +58 -6
  244. package/src/tests/db-task-read-contract.test.ts +2 -0
  245. package/src/tests/db-task-write-contract.test.ts +1 -0
  246. package/src/tests/deploy-guard.test.ts +154 -0
  247. package/src/tests/docs-index-footprint.test.js +3 -3
  248. package/src/tests/dreaming-learnings.test.ts +104 -0
  249. package/src/tests/extensions-pre-task.test.ts +4 -2
  250. package/src/tests/fetch-resolved-env.test.ts +47 -1
  251. package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
  252. package/src/tests/model-profile-fallbacks.test.ts +482 -0
  253. package/src/tests/model-profiles-api.test.ts +1 -0
  254. package/src/tests/opencode-adapter.test.ts +53 -6
  255. package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
  256. package/src/tests/prompt-template-session.test.ts +17 -1
  257. package/src/tests/provider-error-class.test.ts +174 -0
  258. package/src/tests/runner-provider-fallback.test.ts +197 -0
  259. package/src/tests/runner-requester-profile.test.ts +139 -1
  260. package/src/tests/savings-calibration-api.test.ts +264 -0
  261. package/src/tests/savings-calibration.test.ts +201 -0
  262. package/src/tests/savings-compound.test.ts +774 -0
  263. package/src/tests/savings-compute.test.ts +215 -0
  264. package/src/tests/savings-fleet-latency.test.ts +143 -0
  265. package/src/tests/savings-fleet-read.test.ts +195 -0
  266. package/src/tests/savings-fleet-scale.test.ts +222 -0
  267. package/src/tests/savings-model.test.ts +499 -0
  268. package/src/tests/savings-read.test.ts +367 -0
  269. package/src/tests/savings-rollup.test.ts +766 -0
  270. package/src/tests/savings-scripts.test.ts +611 -0
  271. package/src/tests/script-connections.test.ts +4 -0
  272. package/src/tests/script-executor-conformance.test.ts +444 -0
  273. package/src/tests/scripts-http.test.ts +55 -0
  274. package/src/tests/scripts-runtime-fetch.test.ts +2 -2
  275. package/src/tests/sdk-allowlist.test.ts +40 -0
  276. package/src/tests/secret-rules.test.ts +124 -1
  277. package/src/tests/secret-scrubber.test.ts +1 -1
  278. package/src/tests/seed-workflows.test.ts +167 -11
  279. package/src/tests/skill-parser.test.ts +45 -0
  280. package/src/tests/slack-dm-implicit-mention.test.ts +20 -1
  281. package/src/tests/slack-identity-resolution.test.ts +23 -0
  282. package/src/tests/slack-inbound-files.test.ts +2 -1
  283. package/src/tests/slack-thread-participants.test.ts +429 -0
  284. package/src/tests/tool-annotations.test.ts +30 -0
  285. package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
  286. package/src/tests/workflow-definition-pinning.test.ts +128 -3
  287. package/src/tests/workflow-script-principal.test.ts +94 -4
  288. package/src/tools/app-upsert.ts +1 -1
  289. package/src/tools/model-profiles/list-model-profiles.ts +4 -2
  290. package/src/tools/update-profile.ts +1 -1
  291. package/src/types.ts +146 -33
  292. package/src/utils/constants.ts +2 -0
  293. package/src/utils/mcp-server-fetcher.test.ts +89 -0
  294. package/src/utils/mcp-server-fetcher.ts +13 -5
  295. package/src/utils/request-auth-context.ts +24 -0
  296. package/src/utils/secret-rules.generated.ts +1 -1
  297. package/src/utils/secret-scrubber.ts +154 -29
  298. package/src/workflows/executors/swarm-script.ts +23 -19
  299. package/templates/skills/apps/SKILL.md +62 -3
  300. package/templates/skills/apps/content.md +62 -3
  301. package/templates/skills/swarm-docs/content.md +2 -0
  302. package/templates/skills/swarm-scripts/SKILL.md +5 -4
  303. package/templates/skills/swarm-scripts/content.md +5 -4
  304. package/templates/skills/work-on-task/SKILL.md +1 -1
  305. package/templates/skills/work-on-task/content.md +1 -1
  306. package/templates/workflows/dreaming/content.md +1 -1
  307. package/dist/acp-adapter-pdy3qsvg.js +0 -15
  308. package/dist/cli-4bd1rck6.js +0 -4
  309. package/dist/cli-jywyhqws.js +0 -104
  310. package/dist/fx-adapter-3q12snn6.js +0 -18
  311. package/dist/grok-adapter-ahb1w033.js +0 -18
  312. package/dist/handlers-vbww69re.js +0 -32
  313. package/dist/index-4xwaf5th.js +0 -32
  314. package/dist/index-f0hcrs8e.js +0 -33
  315. package/dist/index-s4ewdma4.js +0 -37
  316. package/dist/lead-6ygbfhbh.js +0 -70
  317. package/dist/worker-mz5z7kj0.js +0 -70
  318. package/src/providers/ctx-mode-env.ts +0 -10
@@ -29,6 +29,7 @@ import {
29
29
  authUser,
30
30
  isOperatorAuth,
31
31
  getCurrentRequestUserId,
32
+ getCurrentRunProvenance,
32
33
  init_request_auth_context,
33
34
  isTelemetryEnabled,
34
35
  _resolveIntegrationType,
@@ -56,6 +57,8 @@ import {
56
57
  startEventLoopLagProbe,
57
58
  stopEventLoopLagProbe,
58
59
  init_event_loop_lag,
60
+ DbTransactionDeadlineError,
61
+ init_db_client,
59
62
  getPromptTemplateDefaultDrift,
60
63
  init_default_drift,
61
64
  init_templates2,
@@ -141,6 +144,9 @@ import {
141
144
  recordApprovalVotes2,
142
145
  getPendingApprovalsForTasks2,
143
146
  computeContentHash2,
147
+ normalizeVcsRepo,
148
+ vcsRepoUrlMatches,
149
+ init_vcs_repo_match,
144
150
  taskModelPin,
145
151
  init_model_pin,
146
152
  normalizeModelKey,
@@ -192,6 +198,8 @@ import {
192
198
  modelProfileReferences,
193
199
  modelProfileRefError,
194
200
  deleteModelProfile,
201
+ MAX_MODEL_PROFILE_FALLBACKS,
202
+ modelProfileFallbacksError,
195
203
  taskProfileError,
196
204
  scheduleProfileUpdate,
197
205
  init_model_profiles,
@@ -522,7 +530,7 @@ import {
522
530
  countScriptRunJournalSteps2,
523
531
  countScriptRunJournalAgentTaskSteps2,
524
532
  init_db4
525
- } from "./cli-7w69ne2f.js";
533
+ } from "./cli-h9yy18gy.js";
526
534
  import {
527
535
  PRIMARY_ROLE_NAMES2,
528
536
  OperatorGrantedTargetError2,
@@ -536,17 +544,17 @@ import {
536
544
  assertNotLastAdmin2,
537
545
  setUserRoles2,
538
546
  init_rbac_roles
539
- } from "./cli-1xh9a7hn.js";
540
- import"./cli-k26bkr9t.js";
547
+ } from "./cli-n5t077me.js";
548
+ import"./cli-k2rw11py.js";
541
549
  import {
542
550
  requestModelCatalogRefresh2,
543
551
  init_pricing_refresh
544
- } from "./cli-a3b239vq.js";
552
+ } from "./cli-0vksaxvr.js";
545
553
  import {
546
554
  workflowEventBus2,
547
555
  init_event_bus
548
- } from "./cli-eddnyg3t.js";
549
- import"./cli-b8e9nb04.js";
556
+ } from "./cli-emekyyhr.js";
557
+ import"./cli-zeaehgyd.js";
550
558
  import {
551
559
  require_dist4,
552
560
  getSlackConnectionState,
@@ -577,12 +585,12 @@ import {
577
585
  startSlackApp2,
578
586
  stopSlackApp2,
579
587
  init_app3
580
- } from "./cli-4r05hnqa.js";
588
+ } from "./cli-mwwmka77.js";
581
589
  import {
582
590
  retryFailedRun2,
583
591
  cancelWorkflowRun2,
584
592
  init_resume
585
- } from "./cli-vbh10fqa.js";
593
+ } from "./cli-sdvcrq5x.js";
586
594
  import {
587
595
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
588
596
  SUPPORTED_PROTOCOL_VERSIONS,
@@ -664,6 +672,8 @@ import {
664
672
  SCRIPT_SDK_RESPONSE_LIMIT_BYTES,
665
673
  readScriptSdkJsonResponse,
666
674
  init_response_limit,
675
+ retry,
676
+ init_retry,
667
677
  ExtensionConfigError,
668
678
  init_loader,
669
679
  ExtensionLifecycleError,
@@ -678,6 +688,7 @@ import {
678
688
  loadEnabledExtensions,
679
689
  stopExtensionRuntime,
680
690
  init_lifecycle,
691
+ nextFallback2,
681
692
  createWorkerTaskFollowUp2,
682
693
  createResumeFollowUp2,
683
694
  init_worker_follow_up,
@@ -836,8 +847,13 @@ import {
836
847
  cancelTaskOutputSchema,
837
848
  cancelTaskHandler,
838
849
  init_cancel_task,
850
+ DbQueryTimeoutError,
851
+ DbQueryConcurrencyCapError,
839
852
  executeReadOnlyQuery,
853
+ getDbQueryHttpBudgetMs,
854
+ init_db_query_shared,
840
855
  assertSelectOnlyQuery,
856
+ executeReadOnlyQueryGated,
841
857
  handleDbQuery,
842
858
  init_db_query,
843
859
  snapshotMetric,
@@ -1000,7 +1016,7 @@ import {
1000
1016
  getEnabledCapabilities,
1001
1017
  createServer,
1002
1018
  init_server
1003
- } from "./cli-93k32c37.js";
1019
+ } from "./cli-k96cecs7.js";
1004
1020
  import {
1005
1021
  FilesError,
1006
1022
  normalizeFilesError,
@@ -1033,7 +1049,7 @@ import {
1033
1049
  resolvePoolDelivery2,
1034
1050
  createPoolAgent2,
1035
1051
  init_db2
1036
- } from "./cli-k93bq1wq.js";
1052
+ } from "./cli-rjvsf9qa.js";
1037
1053
  import {
1038
1054
  duplicateGuardedQueryKey,
1039
1055
  warnIfCorsAllowsAnyOrigin,
@@ -1090,7 +1106,7 @@ import {
1090
1106
  describeRequestRoute,
1091
1107
  route,
1092
1108
  init_route_def
1093
- } from "./cli-b5rs97a6.js";
1109
+ } from "./cli-sg27rk2t.js";
1094
1110
  import {
1095
1111
  startPoolRouting,
1096
1112
  stopPoolRouting,
@@ -1103,28 +1119,28 @@ import {
1103
1119
  checkHeartbeatChecklist2,
1104
1120
  runHeartbeatSweep2,
1105
1121
  stopHeartbeat2
1106
- } from "./cli-b085njxz.js";
1107
- import"./cli-m4dqmnbp.js";
1122
+ } from "./cli-kw44j53p.js";
1123
+ import"./cli-54qr8mcd.js";
1108
1124
  import {
1109
1125
  runtimeSupervisorStatus,
1110
1126
  startRuntimeSupervisor,
1111
1127
  stopRuntimeSupervisor
1112
- } from "./cli-k0615eh8.js";
1128
+ } from "./cli-kmemts3w.js";
1113
1129
  import {
1114
1130
  TASK_TITLE_TIMEOUT_MS,
1115
1131
  generateTaskTitle
1116
- } from "./cli-8aes17e4.js";
1132
+ } from "./cli-1m96dc36.js";
1117
1133
  import"./cli-ns59dc6r.js";
1118
1134
  import {
1119
1135
  ACP_TARGET_IDS
1120
- } from "./cli-d6521kb5.js";
1136
+ } from "./cli-skmhsnqh.js";
1121
1137
  import {
1122
1138
  reasoningCapability,
1123
1139
  supportedReasoningLevels
1124
- } from "./cli-jrzkw01m.js";
1140
+ } from "./cli-93t5s4zq.js";
1125
1141
  import {
1126
1142
  MAX_RATE_LIMIT_RESET_MS
1127
- } from "./cli-kc7v1nfv.js";
1143
+ } from "./cli-tnzebztn.js";
1128
1144
  import {
1129
1145
  isLeadChannelMonitoringEnabled,
1130
1146
  ORG_IDENTITY_KEYS,
@@ -1134,14 +1150,14 @@ import {
1134
1150
  isUnknownModelError,
1135
1151
  checkProviderPoolKey,
1136
1152
  writeSkillsToFilesystem
1137
- } from "./cli-jcpr5smb.js";
1153
+ } from "./cli-ztq5z4e1.js";
1138
1154
  import {
1139
1155
  inviteEmailToSharedOrg,
1140
1156
  ensureAgentFsCredentialsForAgent
1141
- } from "./cli-89cqnasv.js";
1157
+ } from "./cli-bhsfbmk8.js";
1142
1158
  import {
1143
1159
  Anthropic
1144
- } from "./cli-7349va39.js";
1160
+ } from "./cli-500c09j9.js";
1145
1161
  import {
1146
1162
  isCodexOAuthConfigKey
1147
1163
  } from "./cli-j4bwnpkm.js";
@@ -1243,7 +1259,7 @@ import {
1243
1259
  init_typecheck,
1244
1260
  parseSkillContent,
1245
1261
  init_skill_parser
1246
- } from "./cli-0ntbxyaa.js";
1262
+ } from "./cli-z8cvws4c.js";
1247
1263
  import {
1248
1264
  signalProcessGroup,
1249
1265
  detachedProcessGroup,
@@ -1260,7 +1276,7 @@ import {
1260
1276
  forceRefreshAuthorizationOrThrow,
1261
1277
  forceRefreshTokenOrThrow,
1262
1278
  init_ensure_token
1263
- } from "./cli-yn2bbre9.js";
1279
+ } from "./cli-s8p8hhty.js";
1264
1280
  import {
1265
1281
  automationIntegrationFixUrl,
1266
1282
  preflightAutomation,
@@ -1304,7 +1320,7 @@ import {
1304
1320
  definitionNodeIds,
1305
1321
  validateDefinition,
1306
1322
  init_definition2
1307
- } from "./cli-vqptjbr7.js";
1323
+ } from "./cli-c3ng0mb4.js";
1308
1324
  import {
1309
1325
  _fetchHolder,
1310
1326
  CLIENT_ID,
@@ -1320,7 +1336,7 @@ import {
1320
1336
  loadAllCodexOAuthSlots,
1321
1337
  getValidCodexOAuth,
1322
1338
  init_storage
1323
- } from "./cli-rvhdmjvt.js";
1339
+ } from "./cli-nx2n3z6p.js";
1324
1340
  import {
1325
1341
  isMultiRuntimeEnabled,
1326
1342
  init_multi_runtime2
@@ -1328,7 +1344,7 @@ import {
1328
1344
  import {
1329
1345
  require_content_type
1330
1346
  } from "./cli-yjdgea32.js";
1331
- import"./cli-dy32zecz.js";
1347
+ import"./cli-s7zz734a.js";
1332
1348
  import {
1333
1349
  isInvalidClientError,
1334
1350
  publicEndpointSsrfOptions,
@@ -1346,11 +1362,11 @@ import {
1346
1362
  revokeMcpToken,
1347
1363
  computeExpiresAt,
1348
1364
  init_mcp_wrapper
1349
- } from "./cli-zcsw143p.js";
1365
+ } from "./cli-qmqt520k.js";
1350
1366
  import {
1351
1367
  createRuntimeProvider,
1352
1368
  init_runtime_providers
1353
- } from "./cli-hxpyc9sn.js";
1369
+ } from "./cli-t5ys4ebm.js";
1354
1370
  import"./cli-v41kn3cd.js";
1355
1371
  import {
1356
1372
  setBedrockProviderModule,
@@ -1387,13 +1403,13 @@ import {
1387
1403
  revokeAgentTokens,
1388
1404
  fingerprintApiKey,
1389
1405
  init_users
1390
- } from "./cli-re4raaj0.js";
1406
+ } from "./cli-c71n3bxq.js";
1391
1407
  import {
1392
1408
  AMP_ESTIMATE_MODELS,
1393
1409
  ampBillsCacheWrites,
1394
1410
  resolveAmpModel,
1395
1411
  init_amp_models
1396
- } from "./cli-p1w18yhx.js";
1412
+ } from "./cli-tf79ryyy.js";
1397
1413
  import {
1398
1414
  ASSET_KEY_MAX_LENGTH,
1399
1415
  normalizeAssetKey,
@@ -1426,6 +1442,7 @@ import {
1426
1442
  ModelProfileNameSchema,
1427
1443
  ModelProfileCredentialsSchema,
1428
1444
  ModelProfileSchema,
1445
+ ProviderErrorClassSchema,
1429
1446
  ProfileCheckResultSchema,
1430
1447
  SessionAccessSchema,
1431
1448
  SessionOwnerSchema,
@@ -1436,6 +1453,7 @@ import {
1436
1453
  SteeringMessageSchema,
1437
1454
  OnUnsupportedSchema,
1438
1455
  SteerResultSchema,
1456
+ SlackParticipantTrustSchema,
1439
1457
  AgentTaskSchema,
1440
1458
  TaskAttachmentSchema,
1441
1459
  UserSchema,
@@ -1555,7 +1573,7 @@ import {
1555
1573
  KvKeySchema,
1556
1574
  KvEntrySchema,
1557
1575
  init_types4
1558
- } from "./cli-2zp0et3v.js";
1576
+ } from "./cli-qps8je6j.js";
1559
1577
  import {
1560
1578
  CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1561
1579
  CODEX_AUTH_WATCH_NAMESPACE,
@@ -1566,7 +1584,7 @@ import {
1566
1584
  IDENTITY_FIELD_BUDGETS,
1567
1585
  IdentityFieldBudgetError,
1568
1586
  init_identity_field_budget
1569
- } from "./cli-tk7cjj8h.js";
1587
+ } from "./cli-am1ptset.js";
1570
1588
  import {
1571
1589
  getSlackConfiguration,
1572
1590
  init_config4
@@ -1595,7 +1613,7 @@ import {
1595
1613
  splitCredentialPool,
1596
1614
  selectCredential,
1597
1615
  init_credentials2
1598
- } from "./cli-5mrq3ake.js";
1616
+ } from "./cli-t4dv07kr.js";
1599
1617
  import {
1600
1618
  interpolate,
1601
1619
  init_template2,
@@ -1605,7 +1623,7 @@ import {
1605
1623
  resolveTemplate,
1606
1624
  init_resolver,
1607
1625
  init_session_templates
1608
- } from "./cli-v1dv1r37.js";
1626
+ } from "./cli-0bcgyj5b.js";
1609
1627
  import {
1610
1628
  init_zod
1611
1629
  } from "./cli-zcfpsfzf.js";
@@ -1632,12 +1650,13 @@ import {
1632
1650
  lazy,
1633
1651
  preprocess,
1634
1652
  ZodIssueCode,
1653
+ exports_iso,
1635
1654
  exports_coerce
1636
1655
  } from "./cli-hg42n3hx.js";
1637
1656
  import {
1638
1657
  init_package,
1639
1658
  package_default
1640
- } from "./cli-yncmerje.js";
1659
+ } from "./cli-922z7gwm.js";
1641
1660
  import {
1642
1661
  realtimeBus,
1643
1662
  init_bus
@@ -1654,7 +1673,7 @@ import {
1654
1673
  isCombEnabled,
1655
1674
  isAgentFsProxyEnabled,
1656
1675
  init_constants3
1657
- } from "./cli-k0wwfqbg.js";
1676
+ } from "./cli-dns0y538.js";
1658
1677
  import {
1659
1678
  parseEnvFlag,
1660
1679
  isEnvFlagEnabled,
@@ -1675,7 +1694,7 @@ import {
1675
1694
  registerVolatileSecret,
1676
1695
  registerEnvSecrets,
1677
1696
  init_secret_scrubber
1678
- } from "./cli-d84byzn8.js";
1697
+ } from "./cli-f1kwb5fc.js";
1679
1698
  import {
1680
1699
  __toESM
1681
1700
  } from "./cli-242037k3.js";
@@ -2442,6 +2461,1549 @@ async function seedRuntimePools(env = process.env) {
2442
2461
  });
2443
2462
  }
2444
2463
 
2464
+ // src/be/savings/rollup.ts
2465
+ init_db4();
2466
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
2467
+
2468
+ // src/be/savings/compute.ts
2469
+ init_db4();
2470
+
2471
+ // src/be/savings/model.ts
2472
+ init_zod();
2473
+ var SAVINGS_TIERS = ["smol", "regular", "smart", "ultra"];
2474
+ var CALIBRATION_MODEL = "claude-opus-5-5";
2475
+ var CALIBRATED_AT = "2026-11-05";
2476
+ var MODEL_VERSION = 2;
2477
+ var K = 0.2753;
2478
+ var T0 = 2;
2479
+ var TAU_MAX = 61;
2480
+ var CAP_PER_DAY = 24;
2481
+ var F_FOLLOWUP = 0.107;
2482
+ var JEV_PER_M = 0.042;
2483
+ var R = { p10: 1.011, p50: 1.02, p90: 1.03 };
2484
+ var ERR_JOB = { p10: 0.542, p50: 1, p90: 1.508 };
2485
+ var ERR_FLEET = { p10: 0.746, p50: 1, p90: 1.325 };
2486
+ var DEFAULT_OPS = 9;
2487
+ var INLINE_OPS = 3.9;
2488
+ var INLINE_SCRIPT_NAME = "(inline source)";
2489
+ var MAX_SCRIPT_OPS = 100;
2490
+ var ROUTER_MIN_RUNS_PER_DAY = 240;
2491
+ var ROUTER_MAX_EFFECT_SHARE = 0.1;
2492
+ var ROUTER_MIN_EVENT_SHARE = 0.9;
2493
+ var CURVE = {
2494
+ smol: {
2495
+ usd: [
2496
+ 0.0056,
2497
+ 0.0068,
2498
+ 0.0075,
2499
+ 0.0086,
2500
+ 0.0092,
2501
+ 0.0105,
2502
+ 0.012,
2503
+ 0.0146,
2504
+ 0.0163,
2505
+ 0.0171,
2506
+ 0.0184,
2507
+ 0.02,
2508
+ 0.0212,
2509
+ 0.0222,
2510
+ 0.0225,
2511
+ 0.0242,
2512
+ 0.0254,
2513
+ 0.0268,
2514
+ 0.028,
2515
+ 0.0291,
2516
+ 0.0306,
2517
+ 0.0319,
2518
+ 0.0333,
2519
+ 0.0353,
2520
+ 0.0359,
2521
+ 0.0374,
2522
+ 0.0389,
2523
+ 0.0413,
2524
+ 0.043,
2525
+ 0.0434,
2526
+ 0.045,
2527
+ 0.047,
2528
+ 0.0489,
2529
+ 0.0505,
2530
+ 0.051,
2531
+ 0.0535,
2532
+ 0.0554,
2533
+ 0.057,
2534
+ 0.0586,
2535
+ 0.0595,
2536
+ 0.0612,
2537
+ 0.0633,
2538
+ 0.065,
2539
+ 0.0679,
2540
+ 0.0683,
2541
+ 0.0702,
2542
+ 0.0717,
2543
+ 0.0742,
2544
+ 0.0757,
2545
+ 0.0764,
2546
+ 0.078,
2547
+ 0.0805,
2548
+ 0.0824,
2549
+ 0.0842,
2550
+ 0.085,
2551
+ 0.0881,
2552
+ 0.0901,
2553
+ 0.093,
2554
+ 0.0949,
2555
+ 0.0963,
2556
+ 0.0979
2557
+ ],
2558
+ hrs: [
2559
+ 0.00409,
2560
+ 0.00521,
2561
+ 0.00674,
2562
+ 0.00831,
2563
+ 0.00993,
2564
+ 0.0126,
2565
+ 0.01586,
2566
+ 0.01997,
2567
+ 0.02272,
2568
+ 0.02392,
2569
+ 0.02615,
2570
+ 0.03049,
2571
+ 0.034,
2572
+ 0.03708,
2573
+ 0.03835,
2574
+ 0.04398,
2575
+ 0.04779,
2576
+ 0.05207,
2577
+ 0.05544,
2578
+ 0.05811,
2579
+ 0.06247,
2580
+ 0.06595,
2581
+ 0.07002,
2582
+ 0.07589,
2583
+ 0.0778,
2584
+ 0.08234,
2585
+ 0.08704,
2586
+ 0.09357,
2587
+ 0.09884,
2588
+ 0.10091,
2589
+ 0.10694,
2590
+ 0.11393,
2591
+ 0.12002,
2592
+ 0.12476,
2593
+ 0.12736,
2594
+ 0.13666,
2595
+ 0.14271,
2596
+ 0.14854,
2597
+ 0.15322,
2598
+ 0.15738,
2599
+ 0.16341,
2600
+ 0.17023,
2601
+ 0.17766,
2602
+ 0.18815,
2603
+ 0.18983,
2604
+ 0.19846,
2605
+ 0.1996,
2606
+ 0.20217,
2607
+ 0.20833,
2608
+ 0.21012,
2609
+ 0.21538,
2610
+ 0.2224,
2611
+ 0.23067,
2612
+ 0.23488,
2613
+ 0.23825,
2614
+ 0.24844,
2615
+ 0.25554,
2616
+ 0.26838,
2617
+ 0.27469,
2618
+ 0.27725,
2619
+ 0.28259
2620
+ ]
2621
+ },
2622
+ regular: {
2623
+ usd: [
2624
+ 0.0878,
2625
+ 0.1074,
2626
+ 0.1211,
2627
+ 0.1383,
2628
+ 0.1497,
2629
+ 0.1699,
2630
+ 0.196,
2631
+ 0.2372,
2632
+ 0.2628,
2633
+ 0.2762,
2634
+ 0.2952,
2635
+ 0.3209,
2636
+ 0.3399,
2637
+ 0.3544,
2638
+ 0.3593,
2639
+ 0.3859,
2640
+ 0.4041,
2641
+ 0.425,
2642
+ 0.4435,
2643
+ 0.4586,
2644
+ 0.4817,
2645
+ 0.5001,
2646
+ 0.5215,
2647
+ 0.5501,
2648
+ 0.5582,
2649
+ 0.5795,
2650
+ 0.6027,
2651
+ 0.6364,
2652
+ 0.6621,
2653
+ 0.6678,
2654
+ 0.6917,
2655
+ 0.7189,
2656
+ 0.7459,
2657
+ 0.7683,
2658
+ 0.7758,
2659
+ 0.8096,
2660
+ 0.8361,
2661
+ 0.8588,
2662
+ 0.8806,
2663
+ 0.893,
2664
+ 0.9152,
2665
+ 0.9422,
2666
+ 0.9654,
2667
+ 1.0056,
2668
+ 1.0108,
2669
+ 1.0351,
2670
+ 1.0545,
2671
+ 1.0885,
2672
+ 1.108,
2673
+ 1.1184,
2674
+ 1.1389,
2675
+ 1.1716,
2676
+ 1.1969,
2677
+ 1.2205,
2678
+ 1.2309,
2679
+ 1.2733,
2680
+ 1.3003,
2681
+ 1.3399,
2682
+ 1.3639,
2683
+ 1.3838,
2684
+ 1.4053
2685
+ ],
2686
+ hrs: [
2687
+ 0.00341,
2688
+ 0.00435,
2689
+ 0.00562,
2690
+ 0.00693,
2691
+ 0.00828,
2692
+ 0.0105,
2693
+ 0.01322,
2694
+ 0.01665,
2695
+ 0.01894,
2696
+ 0.01994,
2697
+ 0.0218,
2698
+ 0.02541,
2699
+ 0.02834,
2700
+ 0.0309,
2701
+ 0.03197,
2702
+ 0.03665,
2703
+ 0.03983,
2704
+ 0.0434,
2705
+ 0.04621,
2706
+ 0.04844,
2707
+ 0.05207,
2708
+ 0.05497,
2709
+ 0.05836,
2710
+ 0.06326,
2711
+ 0.06485,
2712
+ 0.06863,
2713
+ 0.07255,
2714
+ 0.07799,
2715
+ 0.08239,
2716
+ 0.08411,
2717
+ 0.08914,
2718
+ 0.09496,
2719
+ 0.10004,
2720
+ 0.10399,
2721
+ 0.10616,
2722
+ 0.11391,
2723
+ 0.11896,
2724
+ 0.12382,
2725
+ 0.12771,
2726
+ 0.13118,
2727
+ 0.13621,
2728
+ 0.14189,
2729
+ 0.14808,
2730
+ 0.15683,
2731
+ 0.15823,
2732
+ 0.16542,
2733
+ 0.16638,
2734
+ 0.16852,
2735
+ 0.17365,
2736
+ 0.17514,
2737
+ 0.17952,
2738
+ 0.18537,
2739
+ 0.19227,
2740
+ 0.19578,
2741
+ 0.19858,
2742
+ 0.20708,
2743
+ 0.213,
2744
+ 0.22371,
2745
+ 0.22896,
2746
+ 0.23109,
2747
+ 0.23555
2748
+ ]
2749
+ },
2750
+ smart: {
2751
+ usd: [
2752
+ 0.1746,
2753
+ 0.2138,
2754
+ 0.2413,
2755
+ 0.2756,
2756
+ 0.2983,
2757
+ 0.3385,
2758
+ 0.3907,
2759
+ 0.4729,
2760
+ 0.5243,
2761
+ 0.551,
2762
+ 0.589,
2763
+ 0.6402,
2764
+ 0.6783,
2765
+ 0.7075,
2766
+ 0.7173,
2767
+ 0.7705,
2768
+ 0.8068,
2769
+ 0.8487,
2770
+ 0.8857,
2771
+ 0.9158,
2772
+ 0.9621,
2773
+ 0.9989,
2774
+ 1.0416,
2775
+ 1.0987,
2776
+ 1.1149,
2777
+ 1.1576,
2778
+ 1.2041,
2779
+ 1.2714,
2780
+ 1.3225,
2781
+ 1.3339,
2782
+ 1.3815,
2783
+ 1.4359,
2784
+ 1.49,
2785
+ 1.5347,
2786
+ 1.5496,
2787
+ 1.617,
2788
+ 1.67,
2789
+ 1.7153,
2790
+ 1.7596,
2791
+ 1.7844,
2792
+ 1.8288,
2793
+ 1.8828,
2794
+ 1.9291,
2795
+ 2.0095,
2796
+ 2.0198,
2797
+ 2.0683,
2798
+ 2.1069,
2799
+ 2.1748,
2800
+ 2.2137,
2801
+ 2.2345,
2802
+ 2.2752,
2803
+ 2.3413,
2804
+ 2.3918,
2805
+ 2.4388,
2806
+ 2.4595,
2807
+ 2.5444,
2808
+ 2.5985,
2809
+ 2.678,
2810
+ 2.7259,
2811
+ 2.7657,
2812
+ 2.8086
2813
+ ],
2814
+ hrs: [
2815
+ 0.00265,
2816
+ 0.00338,
2817
+ 0.00437,
2818
+ 0.00539,
2819
+ 0.00644,
2820
+ 0.00817,
2821
+ 0.01029,
2822
+ 0.01296,
2823
+ 0.01474,
2824
+ 0.01552,
2825
+ 0.01696,
2826
+ 0.01978,
2827
+ 0.02205,
2828
+ 0.02405,
2829
+ 0.02488,
2830
+ 0.02852,
2831
+ 0.031,
2832
+ 0.03377,
2833
+ 0.03596,
2834
+ 0.03769,
2835
+ 0.04052,
2836
+ 0.04278,
2837
+ 0.04541,
2838
+ 0.04923,
2839
+ 0.05046,
2840
+ 0.05341,
2841
+ 0.05645,
2842
+ 0.06069,
2843
+ 0.06411,
2844
+ 0.06545,
2845
+ 0.06937,
2846
+ 0.0739,
2847
+ 0.07785,
2848
+ 0.08092,
2849
+ 0.08261,
2850
+ 0.08865,
2851
+ 0.09257,
2852
+ 0.09635,
2853
+ 0.09939,
2854
+ 0.10209,
2855
+ 0.106,
2856
+ 0.11041,
2857
+ 0.11524,
2858
+ 0.12204,
2859
+ 0.12313,
2860
+ 0.12873,
2861
+ 0.12947,
2862
+ 0.13114,
2863
+ 0.13513,
2864
+ 0.13629,
2865
+ 0.1397,
2866
+ 0.14425,
2867
+ 0.14962,
2868
+ 0.15235,
2869
+ 0.15453,
2870
+ 0.16114,
2871
+ 0.16575,
2872
+ 0.17408,
2873
+ 0.17817,
2874
+ 0.17983,
2875
+ 0.1833
2876
+ ]
2877
+ },
2878
+ ultra: {
2879
+ usd: [
2880
+ 0.4215,
2881
+ 0.5126,
2882
+ 0.5737,
2883
+ 0.6515,
2884
+ 0.702,
2885
+ 0.7922,
2886
+ 0.9108,
2887
+ 1.0969,
2888
+ 1.2137,
2889
+ 1.2729,
2890
+ 1.3559,
2891
+ 1.4659,
2892
+ 1.5471,
2893
+ 1.6075,
2894
+ 1.6273,
2895
+ 1.7385,
2896
+ 1.8143,
2897
+ 1.9006,
2898
+ 1.9774,
2899
+ 2.0389,
2900
+ 2.1345,
2901
+ 2.211,
2902
+ 2.2993,
2903
+ 2.4146,
2904
+ 2.4463,
2905
+ 2.5326,
2906
+ 2.6278,
2907
+ 2.7635,
2908
+ 2.8673,
2909
+ 2.8901,
2910
+ 2.9876,
2911
+ 3.0983,
2912
+ 3.2073,
2913
+ 3.2964,
2914
+ 3.3254,
2915
+ 3.4593,
2916
+ 3.5632,
2917
+ 3.6518,
2918
+ 3.7384,
2919
+ 3.784,
2920
+ 3.8661,
2921
+ 3.9685,
2922
+ 4.0556,
2923
+ 4.2104,
2924
+ 4.229,
2925
+ 4.3174,
2926
+ 4.3912,
2927
+ 4.5199,
2928
+ 4.5949,
2929
+ 4.6375,
2930
+ 4.7124,
2931
+ 4.8381,
2932
+ 4.931,
2933
+ 5.017,
2934
+ 5.0554,
2935
+ 5.2133,
2936
+ 5.3132,
2937
+ 5.4655,
2938
+ 5.5501,
2939
+ 5.6254,
2940
+ 5.7067
2941
+ ],
2942
+ hrs: [
2943
+ 0.00265,
2944
+ 0.00338,
2945
+ 0.00437,
2946
+ 0.00539,
2947
+ 0.00644,
2948
+ 0.00817,
2949
+ 0.01029,
2950
+ 0.01296,
2951
+ 0.01474,
2952
+ 0.01552,
2953
+ 0.01696,
2954
+ 0.01978,
2955
+ 0.02205,
2956
+ 0.02405,
2957
+ 0.02488,
2958
+ 0.02852,
2959
+ 0.031,
2960
+ 0.03377,
2961
+ 0.03596,
2962
+ 0.03769,
2963
+ 0.04052,
2964
+ 0.04278,
2965
+ 0.04541,
2966
+ 0.04923,
2967
+ 0.05046,
2968
+ 0.05341,
2969
+ 0.05645,
2970
+ 0.06069,
2971
+ 0.06411,
2972
+ 0.06545,
2973
+ 0.06937,
2974
+ 0.0739,
2975
+ 0.07785,
2976
+ 0.08092,
2977
+ 0.08261,
2978
+ 0.08865,
2979
+ 0.09257,
2980
+ 0.09635,
2981
+ 0.09939,
2982
+ 0.10209,
2983
+ 0.106,
2984
+ 0.11041,
2985
+ 0.11524,
2986
+ 0.12204,
2987
+ 0.12313,
2988
+ 0.12873,
2989
+ 0.12947,
2990
+ 0.13114,
2991
+ 0.13513,
2992
+ 0.13629,
2993
+ 0.1397,
2994
+ 0.14425,
2995
+ 0.14962,
2996
+ 0.15235,
2997
+ 0.15453,
2998
+ 0.16114,
2999
+ 0.16575,
3000
+ 0.17408,
3001
+ 0.17817,
3002
+ 0.17983,
3003
+ 0.1833
3004
+ ]
3005
+ }
3006
+ };
3007
+ var SHIPPED_CALIBRATION = {
3008
+ source: "shipped",
3009
+ calibratedAt: CALIBRATED_AT,
3010
+ model: CALIBRATION_MODEL,
3011
+ curve: CURVE
3012
+ };
3013
+ var SAVINGS_CALIBRATION_KEY = "SAVINGS_CURVE_CALIBRATION";
3014
+ var CurveArraySchema = array2(number2().positive()).length(TAU_MAX);
3015
+ var TierCurveSchema = object2({ usd: CurveArraySchema, hrs: CurveArraySchema });
3016
+ var StoredCalibrationSchema = object2({
3017
+ calibratedAt: string2().regex(/^\d{4}-\d{2}-\d{2}$/),
3018
+ model: string2().min(1),
3019
+ window: object2({ start: string2(), end: string2(), sessions: number2().int().nonnegative() }).optional(),
3020
+ curve: object2({
3021
+ smol: TierCurveSchema,
3022
+ regular: TierCurveSchema,
3023
+ smart: TierCurveSchema,
3024
+ ultra: TierCurveSchema
3025
+ })
3026
+ });
3027
+ function parseCalibration(raw) {
3028
+ if (!raw)
3029
+ return null;
3030
+ try {
3031
+ const parsed = StoredCalibrationSchema.safeParse(JSON.parse(raw));
3032
+ if (!parsed.success)
3033
+ return null;
3034
+ const { calibratedAt, model, curve, window } = parsed.data;
3035
+ return { source: "deployment", calibratedAt, model, curve, ...window ? { window } : {} };
3036
+ } catch {
3037
+ return null;
3038
+ }
3039
+ }
3040
+ function curve(tau, tier, key, set = CURVE) {
3041
+ const t = Math.max(1, Math.min(TAU_MAX, tau));
3042
+ const a = set[tier][key];
3043
+ const lo = Math.floor(t);
3044
+ const hi = Math.ceil(t);
3045
+ const vLo = a[lo - 1];
3046
+ const vHi = a[hi - 1];
3047
+ return vLo + (vHi - vLo) * (t - lo);
3048
+ }
3049
+ function jobKey(name) {
3050
+ return name.replace(/-retired-\d{4}-\d{2}-\d{2}$/, "");
3051
+ }
3052
+ function scriptOpsFromAwaitCount(awaits) {
3053
+ return Math.min(MAX_SCRIPT_OPS, Number(awaits) || 0);
3054
+ }
3055
+ function nodeOpsOf(definition, opsByScript) {
3056
+ const ops = new Map;
3057
+ for (const node of definition?.nodes ?? []) {
3058
+ let o = 0;
3059
+ if (node.type === "swarm-script") {
3060
+ const name = node.config?.scriptName;
3061
+ o = (typeof name === "string" ? opsByScript.get(name) : undefined) ?? DEFAULT_OPS;
3062
+ } else if (node.type === "script") {
3063
+ o = Math.max(1, (JSON.stringify(node.config ?? {}).match(/\bawait\b/g) ?? []).length);
3064
+ } else if (["system-one-decision", "system-one-extraction", "raw-llm", "notify", "code-match"].includes(node.type)) {
3065
+ o = 1;
3066
+ }
3067
+ ops.set(node.id, o);
3068
+ }
3069
+ return ops;
3070
+ }
3071
+ var keptSpendOf = (f) => f.agentUsd + f.followupUsd + f.childTaskUsd;
3072
+ var keptHoursOf = (f) => (f.agentMs + f.childTaskMs) / 3600000;
3073
+ function spendOf(facts, useRecorded) {
3074
+ return {
3075
+ measuredUsd: keptSpendOf(facts) + (useRecorded ? facts.recordedLlmUsd : 0),
3076
+ estimatedLlmUsd: useRecorded ? 0 : facts.estimatedLlmUsd
3077
+ };
3078
+ }
3079
+ var bandOf = (fn) => ({
3080
+ p10: fn("p10"),
3081
+ p50: fn("p50"),
3082
+ p90: fn("p90")
3083
+ });
3084
+ function allocateSchedule(versions, days) {
3085
+ const cap = CAP_PER_DAY * days;
3086
+ let used = 0;
3087
+ let eff = 0;
3088
+ return versions.map((v) => {
3089
+ const vCap = Math.min(v.schedRuns, Math.max(0, cap - used));
3090
+ const vSched = Math.max(Math.min(used + v.schedRuns, cap), eff + v.schedEffectRuns) - used;
3091
+ used += vSched;
3092
+ eff += v.schedEffectRuns;
3093
+ return { vSched, vCap };
3094
+ });
3095
+ }
3096
+ function isEnabledOnlyRouter(facts, days) {
3097
+ return facts.runs > ROUTER_MIN_RUNS_PER_DAY * days && facts.effectRuns < ROUTER_MAX_EFFECT_SHARE * facts.runs && facts.eventRuns >= ROUTER_MIN_EVENT_SHARE * facts.runs;
3098
+ }
3099
+ function priceRouter(facts, opts) {
3100
+ const v = facts.effectRuns;
3101
+ const opsPerRun = v > 0 ? facts.effectOpsSum / v : 0;
3102
+ const tau = Math.min(TAU_MAX, T0 + K * opsPerRun);
3103
+ const unitUsd = v > 0 ? curve(tau, opts.tier, "usd", opts.curve) : 0;
3104
+ const unitHrs = v > 0 ? curve(tau, opts.tier, "hrs", opts.curve) : 0;
3105
+ const review = unitUsd > 0 ? F_FOLLOWUP : 0;
3106
+ const err = opts.band === "job" ? ERR_JOB : ERR_FLEET;
3107
+ const agentOnlyUsd = bandOf((q) => v * (R[q] * unitUsd * err[q] + review));
3108
+ const agentOnlyHours = bandOf((q) => v * R[q] * unitHrs * err[q]);
3109
+ return {
3110
+ enabledOnlyRule: true,
3111
+ runs: facts.runs,
3112
+ substitutedRuns: v,
3113
+ effectRuns: v,
3114
+ enabledOnlyRuns: facts.runs - v,
3115
+ capApplied: false,
3116
+ opsPerRun,
3117
+ ...spendOf(facts, facts.recordedLlmUsd > 0),
3118
+ actualUsd: 0,
3119
+ agentOnlyUsd,
3120
+ savingUsd: agentOnlyUsd,
3121
+ actualHours: 0,
3122
+ agentOnlyHours,
3123
+ hoursSaved: agentOnlyHours,
3124
+ agentOnlyUsdPerRun: R.p50 * unitUsd + review
3125
+ };
3126
+ }
3127
+ function priceWorkflow(facts, opts, allocation) {
3128
+ if (isEnabledOnlyRouter(facts, opts.days))
3129
+ return priceRouter(facts, opts);
3130
+ const runs = facts.runs;
3131
+ const { vSched, vCap } = allocation ?? allocateSchedule([facts], opts.days)[0];
3132
+ const substituted = vSched + (facts.countedRuns - facts.schedRuns);
3133
+ const opsPerRun = runs > 0 ? facts.opsSum / runs : 0;
3134
+ const tau = Math.min(TAU_MAX, T0 + K * opsPerRun);
3135
+ const orchestrates = !(opsPerRun < 1 && facts.agentTasks > 0);
3136
+ const unitUsd = orchestrates ? curve(tau, opts.tier, "usd", opts.curve) : 0;
3137
+ const unitHrs = orchestrates ? curve(tau, opts.tier, "hrs", opts.curve) : 0;
3138
+ const review = unitUsd > 0 ? F_FOLLOWUP : 0;
3139
+ const share = runs > 0 ? substituted / runs : 0;
3140
+ const { measuredUsd, estimatedLlmUsd } = spendOf(facts, facts.recordedLlmUsd > 0);
3141
+ const keptUsd = keptSpendOf(facts) * share;
3142
+ const keptHours = keptHoursOf(facts) * share;
3143
+ const actualUsd = (measuredUsd + estimatedLlmUsd) * share;
3144
+ const actualHours = (keptHoursOf(facts) + facts.computeSecs / 3600) * share;
3145
+ const err = opts.band === "job" ? ERR_JOB : ERR_FLEET;
3146
+ const agentOnlyUsd = bandOf((q) => keptUsd + substituted * (R[q] * unitUsd * err[q] + review));
3147
+ const agentOnlyHours = bandOf((q) => keptHours + substituted * R[q] * unitHrs * err[q]);
3148
+ return {
3149
+ enabledOnlyRule: false,
3150
+ runs,
3151
+ substitutedRuns: substituted,
3152
+ effectRuns: vSched - vCap,
3153
+ enabledOnlyRuns: runs - substituted,
3154
+ capApplied: vCap < facts.schedRuns,
3155
+ opsPerRun,
3156
+ measuredUsd,
3157
+ estimatedLlmUsd,
3158
+ actualUsd,
3159
+ agentOnlyUsd,
3160
+ savingUsd: bandOf((q) => agentOnlyUsd[q] - actualUsd),
3161
+ actualHours,
3162
+ agentOnlyHours,
3163
+ hoursSaved: bandOf((q) => agentOnlyHours[q] - actualHours),
3164
+ agentOnlyUsdPerRun: R.p50 * unitUsd + review
3165
+ };
3166
+ }
3167
+ function splitByDay(facts, byDay, opts, pricedWindow) {
3168
+ const priced = pricedWindow ?? priceWorkflow(facts, { ...opts, band: "job" });
3169
+ const useRecorded = facts.recordedLlmUsd > 0;
3170
+ if (priced.enabledOnlyRule) {
3171
+ return byDay.map((d) => ({
3172
+ day: d.day,
3173
+ savingUsd: d.effectRuns * priced.agentOnlyUsdPerRun,
3174
+ actualUsd: 0,
3175
+ ...spendOf(d, useRecorded)
3176
+ }));
3177
+ }
3178
+ const runs = facts.runs;
3179
+ const share = runs > 0 ? priced.substitutedRuns / runs : 0;
3180
+ const nonSched = facts.countedRuns - facts.schedRuns;
3181
+ const vSched = priced.substitutedRuns - nonSched;
3182
+ const unitUsd = priced.agentOnlyUsdPerRun;
3183
+ return byDay.map((d) => {
3184
+ const substituted = (facts.schedRuns > 0 ? vSched * d.schedRuns / facts.schedRuns : 0) + (d.countedRuns - d.schedRuns);
3185
+ const { measuredUsd, estimatedLlmUsd } = spendOf(d, useRecorded);
3186
+ const keptUsd = keptSpendOf(d) * share;
3187
+ const actualUsd = (measuredUsd + estimatedLlmUsd) * share;
3188
+ return {
3189
+ day: d.day,
3190
+ savingUsd: keptUsd + substituted * unitUsd - actualUsd,
3191
+ actualUsd,
3192
+ measuredUsd,
3193
+ estimatedLlmUsd
3194
+ };
3195
+ });
3196
+ }
3197
+ function priceScript(facts, opts) {
3198
+ const runs = facts.runs;
3199
+ const nonApi = runs - facts.apiRuns;
3200
+ const vCap = Math.min(nonApi, CAP_PER_DAY * opts.days);
3201
+ const v = Math.max(vCap, Math.min(nonApi, facts.effectRuns));
3202
+ const apiV = facts.apiEffectRuns;
3203
+ const opsPerRun = runs > 0 ? facts.opsSum / runs : 0;
3204
+ const tau = Math.min(TAU_MAX, T0 + K * opsPerRun);
3205
+ const fullUsd = curve(tau, opts.tier, "usd", opts.curve);
3206
+ const fullHrs = curve(tau, opts.tier, "hrs", opts.curve);
3207
+ const scheduled = opts.kind === "script-scheduled";
3208
+ const unitUsd = scheduled ? fullUsd : Math.max(0, fullUsd - curve(T0, opts.tier, "usd", opts.curve));
3209
+ const unitHrs = scheduled ? fullHrs : Math.max(0, fullHrs - curve(T0, opts.tier, "hrs", opts.curve));
3210
+ const review = scheduled ? F_FOLLOWUP : 0;
3211
+ const err = opts.band === "job" ? ERR_JOB : ERR_FLEET;
3212
+ const agentOnlyUsd = bandOf((q) => v * (R[q] * unitUsd * err[q] + review) + apiV * (R[q] * fullUsd * err[q] + F_FOLLOWUP));
3213
+ const agentOnlyHours = bandOf((q) => v * R[q] * unitHrs * err[q] + apiV * R[q] * fullHrs * err[q]);
3214
+ const actualHours = 0;
3215
+ return {
3216
+ enabledOnlyRule: false,
3217
+ runs,
3218
+ substitutedRuns: v + apiV,
3219
+ effectRuns: v - vCap + apiV,
3220
+ enabledOnlyRuns: runs - v - apiV,
3221
+ capApplied: vCap < nonApi,
3222
+ opsPerRun,
3223
+ measuredUsd: 0,
3224
+ estimatedLlmUsd: 0,
3225
+ actualUsd: 0,
3226
+ agentOnlyUsd,
3227
+ savingUsd: agentOnlyUsd,
3228
+ actualHours,
3229
+ agentOnlyHours,
3230
+ hoursSaved: bandOf((q) => agentOnlyHours[q] - actualHours),
3231
+ agentOnlyUsdPerRun: R.p50 * unitUsd + review
3232
+ };
3233
+ }
3234
+ function splitScriptByDay(facts, byDay, priced) {
3235
+ const nonApi = facts.runs - facts.apiRuns;
3236
+ const v = priced.substitutedRuns - facts.apiEffectRuns;
3237
+ const apiUnit = facts.apiEffectRuns > 0 ? (priced.agentOnlyUsd.p50 - v * priced.agentOnlyUsdPerRun) / facts.apiEffectRuns : 0;
3238
+ return byDay.map((d) => ({
3239
+ day: d.day,
3240
+ savingUsd: (nonApi > 0 ? v * (d.runs - d.apiRuns) / nonApi : 0) * priced.agentOnlyUsdPerRun + d.apiEffectRuns * apiUnit,
3241
+ actualUsd: 0,
3242
+ measuredUsd: 0,
3243
+ estimatedLlmUsd: 0
3244
+ }));
3245
+ }
3246
+ var TIER_MODEL = {
3247
+ smol: "haiku-5-5",
3248
+ regular: "sonnet-5-5",
3249
+ smart: "opus-5-5",
3250
+ ultra: "fable-5-1"
3251
+ };
3252
+ function savingsAssumptions(tier) {
3253
+ return [
3254
+ `Tier ${tier} prices sessions at ${TIER_MODEL[tier]} on the fleet's measured session token profile (${CALIBRATION_MODEL}, calibrated ${CALIBRATED_AT}).`,
3255
+ `Agent turns per deterministic op K=${K}, bootstrap T0=${T0} turns, session length capped at ${TAU_MAX} turns (fleet p95).`,
3256
+ `Schedule-triggered runs count at most ${CAP_PER_DAY} a day per job (an agent would not poll faster than hourly) unless they caused a downstream effect; event and manual runs count 1:1; skipped and cancelled runs are excluded.`,
3257
+ `Event routers (over ${ROUTER_MIN_RUNS_PER_DAY} event runs a day, under ${ROUTER_MAX_EFFECT_SHARE * 100}% with an effect) and API-invoked script runs are enabled-only: an effect run counts as one agent decision, never as the job it starts, which is priced on its own row.`,
3258
+ "Effect links: a workflow run created an agent task (agent_tasks.workflowRunId) or started a child workflow run (workflow_runs.parentStepId); a script run wrote the id of an agent task created during the run into its output.",
3259
+ `Failure and retry multiplier R=${R.p50} (p10 ${R.p10}, p90 ${R.p90}) from scheduled agent tasks; lead follow-up review $${F_FOLLOWUP} per standalone agent task.`,
3260
+ "Scripts no schedule targets are priced as the extra turns they add to the calling agent's session (no bootstrap, no review).",
3261
+ "Agent-task nodes inside workflows count at their actual cost on both sides; only the deterministic glue is substituted.",
3262
+ "Scripts record no LLM spend, so their actual cost counts as $0; LLM calls made inside scripts are not counted."
3263
+ ];
3264
+ }
3265
+
3266
+ // src/be/savings/compute.ts
3267
+ var defaultSql = (sql, params) => getDbClient2().query(sql, params);
3268
+ var LIVE_MAX_RUNS = 1e4;
3269
+ var EFFECT_SQL = "(EXISTS(SELECT 1 FROM agent_tasks k WHERE k.workflowRunId=r.id) OR EXISTS(SELECT 1 FROM workflow_run_steps s2 JOIN workflow_runs c ON c.parentStepId=s2.id WHERE s2.runId=r.id))";
3270
+ var AWAITS_SQL = "(length(source)-length(replace(source,'await','')))/5";
3271
+ var num = (v) => Number(v) || 0;
3272
+ var emptyFacts = (runs) => ({
3273
+ runs,
3274
+ countedRuns: 0,
3275
+ schedRuns: 0,
3276
+ schedEffectRuns: 0,
3277
+ eventRuns: 0,
3278
+ effectRuns: 0,
3279
+ effectOpsSum: 0,
3280
+ opsSum: 0,
3281
+ agentTasks: 0,
3282
+ agentUsd: 0,
3283
+ agentMs: 0,
3284
+ followupUsd: 0,
3285
+ childTaskUsd: 0,
3286
+ childTaskMs: 0,
3287
+ recordedLlmUsd: 0,
3288
+ estimatedLlmUsd: 0,
3289
+ computeSecs: 0
3290
+ });
3291
+ async function scriptOps(names, sql) {
3292
+ const ops = new Map;
3293
+ const unique = [...new Set(names.filter(Boolean))];
3294
+ if (unique.length === 0)
3295
+ return ops;
3296
+ for (let i = 0;i < unique.length; i += 500) {
3297
+ const chunk = unique.slice(i, i + 500);
3298
+ const rows = await sql(`SELECT name, ${AWAITS_SQL} aw FROM scripts WHERE isScratch=0 AND name IN (${chunk.map(() => "?").join(",")}) ORDER BY scope='global'`, chunk);
3299
+ for (const row of rows)
3300
+ ops.set(row.name, scriptOpsFromAwaitCount(row.aw));
3301
+ }
3302
+ return ops;
3303
+ }
3304
+ function bucketSql(column, bucket = "day") {
3305
+ return `substr(${column},1,${bucket === "minute" ? 16 : 10})`;
3306
+ }
3307
+ async function computeWorkflowWindow(workflow, window, sql = defaultSql, opts = {}) {
3308
+ const DAY_SQL = bucketSql("r.startedAt", opts.bucket);
3309
+ const span = [workflow.id, window.start, window.end];
3310
+ const maxRuns = opts.maxRuns ?? LIVE_MAX_RUNS;
3311
+ const total = num((await sql("SELECT count(*) n FROM workflow_runs WHERE workflowId=? AND startedAt>=? AND startedAt<?", span))[0]?.n);
3312
+ if (total === 0)
3313
+ return { status: "ok", facts: emptyFacts(0), byDay: [] };
3314
+ if (total > maxRuns)
3315
+ return { status: "too-many-runs", runs: total };
3316
+ const days = new Map;
3317
+ const dayOf = (d) => {
3318
+ const key = String(d);
3319
+ let f = days.get(key);
3320
+ if (!f) {
3321
+ f = { day: key, ...emptyFacts(0) };
3322
+ days.set(key, f);
3323
+ }
3324
+ return f;
3325
+ };
3326
+ const byTrigger = await sql(`SELECT ${DAY_SQL} d, r.triggerType tt, r.status st, count(*) n FROM workflow_runs r INDEXED BY idx_workflow_runs_workflow_started WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1,2,3`, span);
3327
+ let schedRuns = 0;
3328
+ for (const row of byTrigger) {
3329
+ const f = dayOf(row.d);
3330
+ const n = num(row.n);
3331
+ f.runs += n;
3332
+ if (row.tt === "event")
3333
+ f.eventRuns += n;
3334
+ if (row.st === "skipped" || row.st === "cancelled")
3335
+ continue;
3336
+ f.countedRuns += n;
3337
+ if (row.tt === "schedule") {
3338
+ f.schedRuns += n;
3339
+ schedRuns += n;
3340
+ }
3341
+ }
3342
+ if (schedRuns > 0) {
3343
+ const effect = await sql(`SELECT ${DAY_SQL} d, count(*) n FROM workflow_runs r WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? AND r.triggerType='schedule' AND r.status NOT IN ('skipped','cancelled') AND ${EFFECT_SQL} GROUP BY 1`, span);
3344
+ for (const row of effect)
3345
+ dayOf(row.d).schedEffectRuns += num(row.n);
3346
+ }
3347
+ const definition = workflow.definition ?? {};
3348
+ const scriptNames = (definition.nodes ?? []).filter((n) => n.type === "swarm-script").map((n) => n.config?.scriptName).filter((n) => typeof n === "string");
3349
+ const nodeOps = nodeOpsOf(definition, await scriptOps(scriptNames, sql));
3350
+ const steps = await sql(`SELECT ${DAY_SQL} d, s.nodeId nid, count(*) n, sum(CASE WHEN s.nodeType NOT IN ('agent-task','wait','human-in-the-loop','foreach','sub-workflow') THEN (julianday(coalesce(s.finishedAt,s.startedAt))-julianday(s.startedAt))*86400 ELSE 0 END) secs,
3351
+ sum(CASE WHEN s.nodeType LIKE 'system-one%' THEN json_extract(s.output,'$.usage.input_tokens') END) itok,
3352
+ sum(CASE WHEN s.nodeType='raw-llm' THEN length(json_extract(s.output,'$.result')) END) rchars,
3353
+ sum(CASE WHEN s.nodeId='report' THEN json_extract(s.output,'$.result.summary.jevCostUsd') END) jev,
3354
+ sum(CASE WHEN s.nodeId='report' THEN json_extract(s.output,'$.result.cost.clairicUsd') END) clairic
3355
+ FROM workflow_runs r JOIN workflow_run_steps s ON s.runId=r.id WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1,2`, span);
3356
+ for (const x of steps) {
3357
+ const f = dayOf(x.d);
3358
+ f.opsSum += (nodeOps.get(String(x.nid).split("#")[0] ?? "") ?? 0) * num(x.n);
3359
+ f.recordedLlmUsd += num(x.jev) + num(x.clairic);
3360
+ f.estimatedLlmUsd += num(x.itok) / 1e6 * JEV_PER_M + num(x.rchars) * (1.2 / 4 + 0.3) / 1e6;
3361
+ f.computeSecs += num(x.secs);
3362
+ }
3363
+ const agent = await sql(`SELECT ${DAY_SQL} d, count(DISTINCT t.id) tasks, sum(c.u) usd, sum(c.ms) ms
3364
+ FROM workflow_runs r JOIN agent_tasks t ON t.workflowRunId=r.id LEFT JOIN (SELECT taskId, sum(totalCostUsd) u, sum(durationMs) ms FROM session_costs GROUP BY taskId) c ON c.taskId=t.id
3365
+ WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1`, span);
3366
+ for (const row of agent) {
3367
+ const f = dayOf(row.d);
3368
+ f.agentTasks += num(row.tasks);
3369
+ f.agentUsd += num(row.usd);
3370
+ f.agentMs += num(row.ms);
3371
+ }
3372
+ const followups = await sql(`SELECT ${DAY_SQL} d, sum(c2.totalCostUsd) fup FROM workflow_runs r JOIN agent_tasks t2 ON t2.workflowRunId=r.id JOIN agent_tasks k ON k.parentTaskId=t2.id AND (k.task LIKE 'Worker task completed%' OR k.task LIKE 'Worker task failed%') JOIN session_costs c2 ON c2.taskId=k.id WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1`, span);
3373
+ for (const row of followups)
3374
+ dayOf(row.d).followupUsd += num(row.fup);
3375
+ const effect = await sql(`WITH e AS (SELECT s.runId id FROM workflow_runs c INDEXED BY idx_workflow_runs_parentStep_attempt JOIN workflow_run_steps s ON s.id=c.parentStepId JOIN workflow_runs p ON p.id=s.runId
3376
+ WHERE c.parentStepId IS NOT NULL AND p.workflowId=? AND p.startedAt>=? AND p.startedAt<?
3377
+ UNION SELECT k.workflowRunId FROM agent_tasks k INDEXED BY idx_agent_tasks_workflow_run JOIN workflow_runs p ON p.id=k.workflowRunId WHERE k.workflowRunId IS NOT NULL AND p.workflowId=? AND p.startedAt>=? AND p.startedAt<?),
3378
+ ed AS (SELECT e.id, ${DAY_SQL} d FROM e JOIN workflow_runs r ON r.id=e.id)
3379
+ SELECT d, NULL nid, count(*) n FROM ed GROUP BY d
3380
+ UNION ALL SELECT ed.d, s.nodeId, count(*) n FROM ed JOIN workflow_run_steps s ON s.runId=ed.id GROUP BY 1,2`, [...span, ...span]);
3381
+ for (const row of effect) {
3382
+ const f = dayOf(row.d);
3383
+ if (row.nid === null)
3384
+ f.effectRuns += num(row.n);
3385
+ else
3386
+ f.effectOpsSum += (nodeOps.get(String(row.nid).split("#")[0] ?? "") ?? 0) * num(row.n);
3387
+ }
3388
+ const byDay = [...days.values()].sort((a, b) => a.day.localeCompare(b.day));
3389
+ const facts = emptyFacts(0);
3390
+ for (const f of byDay) {
3391
+ for (const k of Object.keys(facts))
3392
+ facts[k] += f[k];
3393
+ }
3394
+ return { status: "ok", facts, byDay };
3395
+ }
3396
+ var DISPATCH_SQL = "(source LIKE '%task_send%' OR source LIKE '%send_task%' OR source LIKE '%sendTask%' OR source LIKE '%workflow_trigger%')";
3397
+ function scriptRunsFilter(window, opts) {
3398
+ const span = [window.start, window.end];
3399
+ return opts.scriptName === undefined ? { where: "", params: span } : {
3400
+ where: "AND coalesce(scriptName, ?)=?",
3401
+ params: [...span, INLINE_SCRIPT_NAME, opts.scriptName]
3402
+ };
3403
+ }
3404
+ async function countScriptRuns(window, sql = defaultSql, opts = {}) {
3405
+ const { where, params } = scriptRunsFilter(window, opts);
3406
+ const rows = await sql(`SELECT count(*) n FROM script_runs WHERE startedAt>=? AND startedAt<? ${where}`, params);
3407
+ return num(rows[0]?.n);
3408
+ }
3409
+ async function computeScriptWindow(window, sql = defaultSql, opts = {}) {
3410
+ const span = [window.start, window.end];
3411
+ const { where, params } = scriptRunsFilter(window, opts);
3412
+ const runs = await sql(`SELECT ${bucketSql("startedAt", opts.bucket)} d, coalesce(scriptName,'${INLINE_SCRIPT_NAME}') nm, count(*) n, sum(apiEndpointId IS NOT NULL) api,
3413
+ sum((julianday(coalesce(finishedAt,startedAt))-julianday(startedAt))*86400) secs
3414
+ FROM script_runs WHERE startedAt>=? AND startedAt<? ${where} GROUP BY 1,2`, params);
3415
+ if (runs.length === 0)
3416
+ return [];
3417
+ const names = [...new Set(runs.map((r) => String(r.nm)))].filter((n) => n !== INLINE_SCRIPT_NAME);
3418
+ const ops = await scriptOps(names, sql);
3419
+ const dispatchers = [];
3420
+ for (let i = 0;i < names.length; i += 500) {
3421
+ const chunk = names.slice(i, i + 500);
3422
+ const rows = await sql(`SELECT DISTINCT name FROM scripts WHERE isScratch=0 AND name IN (${chunk.map(() => "?").join(",")}) AND ${DISPATCH_SQL}`, chunk);
3423
+ dispatchers.push(...rows.map((r) => String(r.name)));
3424
+ }
3425
+ const effects = new Map;
3426
+ const tasksTo = "strftime('%Y-%m-%dT%H:%M:%fZ',?,'+20 minutes')";
3427
+ const probe = dispatchers.length > 0 ? `UNION SELECT ${bucketSql("r.startedAt", opts.bucket)} d, r.scriptName nm, (r.apiEndpointId IS NOT NULL) api, r.id
3428
+ FROM agent_tasks t INDEXED BY idx_agent_tasks_created
3429
+ JOIN script_runs r INDEXED BY idx_script_runs_scriptName_startedAt ON r.scriptName IN (${dispatchers.map(() => "?").join(",")})
3430
+ AND r.startedAt>=strftime('%Y-%m-%dT%H:%M:%fZ',t.createdAt,'-20 minutes') AND r.startedAt<=t.createdAt AND r.output LIKE '%'||t.id||'%'
3431
+ AND r.startedAt>=? AND r.startedAt<?
3432
+ WHERE t.createdAt>=? AND t.createdAt<${tasksTo} AND t.sourceScriptRunId IS NULL` : "";
3433
+ const rows = await sql(`SELECT d, nm, api, count(DISTINCT id) n FROM (
3434
+ SELECT ${bucketSql("r.startedAt", opts.bucket)} d, coalesce(r.scriptName,'${INLINE_SCRIPT_NAME}') nm, (r.apiEndpointId IS NOT NULL) api, r.id
3435
+ FROM agent_tasks t INDEXED BY idx_agent_tasks_sourceScriptRun_created JOIN script_runs r ON r.id=t.sourceScriptRunId
3436
+ WHERE t.sourceScriptRunId IS NOT NULL AND t.createdAt>=? AND t.createdAt<${tasksTo}
3437
+ AND r.startedAt>=? AND r.startedAt<? ${opts.scriptName === undefined ? "" : "AND coalesce(r.scriptName, ?)=?"}
3438
+ ${probe}
3439
+ ) GROUP BY 1,2,3`, [
3440
+ ...span,
3441
+ ...span,
3442
+ ...opts.scriptName === undefined ? [] : [INLINE_SCRIPT_NAME, opts.scriptName],
3443
+ ...dispatchers.length > 0 ? [...dispatchers, ...span, ...span] : []
3444
+ ]);
3445
+ for (const row of rows) {
3446
+ const key = `${row.nm}\x00${row.d}`;
3447
+ const e = effects.get(key) ?? { other: 0, api: 0 };
3448
+ if (num(row.api))
3449
+ e.api += num(row.n);
3450
+ else
3451
+ e.other += num(row.n);
3452
+ effects.set(key, e);
3453
+ }
3454
+ const byName = new Map;
3455
+ const push = (nm, f) => byName.set(nm, [...byName.get(nm) ?? [], f]);
3456
+ for (const r of runs) {
3457
+ const nm = String(r.nm);
3458
+ const n = num(r.n);
3459
+ const perRun = nm === INLINE_SCRIPT_NAME ? INLINE_OPS : ops.get(nm) ?? DEFAULT_OPS;
3460
+ const e = effects.get(`${nm}\x00${r.d}`);
3461
+ push(nm, {
3462
+ day: String(r.d),
3463
+ runs: n,
3464
+ apiRuns: num(r.api),
3465
+ effectRuns: e?.other ?? 0,
3466
+ apiEffectRuns: e?.api ?? 0,
3467
+ opsSum: perRun * n,
3468
+ computeSecs: num(r.secs)
3469
+ });
3470
+ }
3471
+ return [...byName.entries()].map(([scriptName, byDay]) => ({
3472
+ scriptName,
3473
+ byDay: byDay.sort((a, b) => a.day.localeCompare(b.day))
3474
+ })).sort((a, b) => a.scriptName.localeCompare(b.scriptName));
3475
+ }
3476
+ var UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
3477
+ var STEP_GRACE_MS = 5000;
3478
+ var MAX_TASK_DEPTH = 20;
3479
+ async function inChunks(ids, fn) {
3480
+ const out = [];
3481
+ for (let i = 0;i < ids.length; i += 500)
3482
+ out.push(...await fn(ids.slice(i, i + 500)));
3483
+ return out;
3484
+ }
3485
+ var marks = (n) => Array.from({ length: n }, () => "?").join(",");
3486
+ async function computeWorkflowLinksDay(window, workflows, sql = defaultSql) {
3487
+ const span = [window.start, window.end];
3488
+ const links = new Map;
3489
+ const add = (l) => {
3490
+ const key = [l.parentJobId, l.childKind, l.childJobId, l.linkKind].join("\x00");
3491
+ const prev = links.get(key);
3492
+ const usd = l.usd ?? 0;
3493
+ links.set(key, {
3494
+ parentJobId: l.parentJobId,
3495
+ childKind: l.childKind,
3496
+ childJobId: l.childJobId,
3497
+ linkKind: l.linkKind,
3498
+ n: (prev?.n ?? 0) + l.n,
3499
+ actualUsd: (prev?.actualUsd ?? 0) + usd,
3500
+ keptUsd: (prev?.keptUsd ?? 0) + (l.childKind === "task" ? usd : 0)
3501
+ });
3502
+ };
3503
+ const subRuns = await sql(`SELECT p.workflowId pid, c.workflowId cid, count(*) n FROM workflow_runs c INDEXED BY idx_workflow_runs_parentStep_attempt
3504
+ JOIN workflow_run_steps s ON s.id=c.parentStepId JOIN workflow_runs p ON p.id=s.runId
3505
+ WHERE c.parentStepId IS NOT NULL AND c.startedAt>=? AND c.startedAt<? GROUP BY 1,2`, span);
3506
+ for (const r of subRuns) {
3507
+ add({
3508
+ parentJobId: r.pid,
3509
+ childKind: "workflow",
3510
+ childJobId: r.cid,
3511
+ linkKind: "sub-workflow",
3512
+ n: num(r.n)
3513
+ });
3514
+ }
3515
+ const stampedRuns = await sql(`SELECT p.workflowId pid, c.workflowId cid, count(*) n FROM workflow_runs c INDEXED BY idx_workflow_runs_sourceStep_started
3516
+ JOIN workflow_run_steps s ON s.id=c.sourceStepId JOIN workflow_runs p ON p.id=s.runId
3517
+ WHERE c.sourceStepId IS NOT NULL AND c.startedAt>=? AND c.startedAt<? GROUP BY 1,2`, span);
3518
+ for (const r of stampedRuns) {
3519
+ add({
3520
+ parentJobId: r.pid,
3521
+ childKind: "workflow",
3522
+ childJobId: r.cid,
3523
+ linkKind: "step-workflow",
3524
+ n: num(r.n)
3525
+ });
3526
+ }
3527
+ const stampedScripts = await sql(`SELECT p.workflowId pid, coalesce(r.scriptName,'${INLINE_SCRIPT_NAME}') nm, count(*) n FROM script_runs r INDEXED BY idx_script_runs_sourceStep_started
3528
+ JOIN workflow_run_steps s ON s.id=r.sourceStepId JOIN workflow_runs p ON p.id=s.runId
3529
+ WHERE r.sourceStepId IS NOT NULL AND r.startedAt>=? AND r.startedAt<? GROUP BY 1,2`, span);
3530
+ for (const r of stampedScripts) {
3531
+ add({
3532
+ parentJobId: r.pid,
3533
+ childKind: "script",
3534
+ childJobId: String(r.nm),
3535
+ linkKind: "step-script",
3536
+ n: num(r.n)
3537
+ });
3538
+ }
3539
+ const stepTasks = new Map;
3540
+ for (const r of await sql(`SELECT p.workflowId pid, t.id FROM agent_tasks t INDEXED BY idx_agent_tasks_sourceStep_created
3541
+ JOIN workflow_run_steps s ON s.id=t.sourceStepId JOIN workflow_runs p ON p.id=s.runId
3542
+ WHERE t.sourceStepId IS NOT NULL AND t.createdAt>=? AND t.createdAt<?`, span)) {
3543
+ stepTasks.set(String(r.id), String(r.pid));
3544
+ }
3545
+ await linkFromStepOutputs(window, workflows, sql, (pid, kind, id, childWorkflowId) => {
3546
+ if (kind === "task") {
3547
+ if (!stepTasks.has(id))
3548
+ stepTasks.set(id, pid);
3549
+ } else {
3550
+ add({
3551
+ parentJobId: pid,
3552
+ childKind: "workflow",
3553
+ childJobId: childWorkflowId,
3554
+ linkKind: "step-workflow",
3555
+ n: 1
3556
+ });
3557
+ }
3558
+ });
3559
+ const nodeTasks = new Map;
3560
+ for (const r of await sql(`SELECT p.workflowId pid, t.id FROM agent_tasks t INDEXED BY idx_agent_tasks_created JOIN workflow_runs p ON p.id=t.workflowRunId
3561
+ WHERE t.createdAt>=? AND t.createdAt<? AND t.workflowRunId IS NOT NULL`, span)) {
3562
+ nodeTasks.set(String(r.id), String(r.pid));
3563
+ }
3564
+ const childTasks = new Map;
3565
+ const keep = (pid, usd, ms) => {
3566
+ const c = childTasks.get(pid) ?? { usd: 0, ms: 0 };
3567
+ childTasks.set(pid, { usd: c.usd + usd, ms: c.ms + ms });
3568
+ };
3569
+ const roots = [...new Set([...stepTasks.keys(), ...nodeTasks.keys()])];
3570
+ const trees = roots.length === 0 ? [] : await sql(`WITH RECURSIVE r(id) AS (SELECT value FROM json_each(?)),
3571
+ d(root, id, depth) AS (
3572
+ SELECT id, id, 0 FROM r
3573
+ UNION ALL SELECT d.root, k.id, d.depth+1 FROM d JOIN agent_tasks k INDEXED BY idx_agent_tasks_parentTaskId ON k.parentTaskId=d.id
3574
+ WHERE k.workflowRunId IS NULL AND k.sourceStepId IS NULL AND k.id NOT IN (SELECT id FROM r)
3575
+ AND d.depth<${MAX_TASK_DEPTH})
3576
+ SELECT root, depth>0 below, count(*) n,
3577
+ sum((SELECT sum(totalCostUsd) FROM session_costs c WHERE c.taskId=d.id)) usd,
3578
+ sum((SELECT sum(durationMs) FROM session_costs c WHERE c.taskId=d.id)) ms
3579
+ FROM d GROUP BY 1,2`, [JSON.stringify(roots)]);
3580
+ for (const t of trees) {
3581
+ const root = String(t.root);
3582
+ const below = num(t.below) === 1;
3583
+ const fromStep = stepTasks.get(root);
3584
+ const pid = fromStep ?? nodeTasks.get(root);
3585
+ if (!pid)
3586
+ continue;
3587
+ if (!fromStep && !below)
3588
+ continue;
3589
+ const usd = num(t.usd);
3590
+ keep(pid, usd, num(t.ms));
3591
+ if (fromStep) {
3592
+ add({
3593
+ parentJobId: pid,
3594
+ childKind: "task",
3595
+ childJobId: "",
3596
+ linkKind: "step-task",
3597
+ n: below ? 0 : num(t.n),
3598
+ usd
3599
+ });
3600
+ } else {
3601
+ add({
3602
+ parentJobId: pid,
3603
+ childKind: "task",
3604
+ childJobId: "",
3605
+ linkKind: "descendant-task",
3606
+ n: num(t.n),
3607
+ usd
3608
+ });
3609
+ }
3610
+ }
3611
+ return { links: [...links.values()], childTasks };
3612
+ }
3613
+ async function linkFromStepOutputs(window, workflows, sql, onLink) {
3614
+ const nodesByWorkflow = new Map;
3615
+ for (const w of workflows) {
3616
+ const nodes = (w.definition ?? {}).nodes ?? [];
3617
+ const scripted = nodes.filter((n) => n.type === "swarm-script" && typeof n.config?.scriptName === "string").map((n) => ({ nodeId: n.id, scriptName: n.config?.scriptName }));
3618
+ if (scripted.length > 0)
3619
+ nodesByWorkflow.set(w.id, scripted);
3620
+ }
3621
+ const names = [...new Set([...nodesByWorkflow.values()].flat().map((n) => n.scriptName))];
3622
+ if (names.length === 0)
3623
+ return;
3624
+ const dispatchers = new Set((await inChunks(names, (chunk) => sql(`SELECT DISTINCT name FROM scripts WHERE isScratch=0 AND name IN (${marks(chunk.length)}) AND ${DISPATCH_SQL}`, chunk))).map((r) => String(r.name)));
3625
+ for (const [workflowId, nodes] of nodesByWorkflow) {
3626
+ const nodeIds = nodes.filter((n) => dispatchers.has(n.scriptName)).map((n) => n.nodeId);
3627
+ if (nodeIds.length === 0)
3628
+ continue;
3629
+ const steps = await sql(`SELECT s.id, s.startedAt sa, coalesce(s.finishedAt,s.startedAt) fa, s.output FROM workflow_runs p INDEXED BY idx_workflow_runs_workflow_started
3630
+ JOIN workflow_run_steps s ON s.runId=p.id
3631
+ WHERE p.workflowId=? AND p.startedAt>=? AND p.startedAt<? AND s.nodeType='swarm-script' AND s.output IS NOT NULL
3632
+ AND (s.nodeId IN (${marks(nodeIds.length)}) OR ${nodeIds.map(() => "s.nodeId LIKE ?").join(" OR ")})`, [workflowId, window.start, window.end, ...nodeIds, ...nodeIds.map((id) => `${id}#%`)]);
3633
+ const named = new Map;
3634
+ for (const s of steps) {
3635
+ const range = { sa: Date.parse(s.sa), fa: Date.parse(s.fa) + STEP_GRACE_MS };
3636
+ for (const id of new Set(String(s.output).toLowerCase().match(UUID_RE) ?? [])) {
3637
+ if (id === String(s.id))
3638
+ continue;
3639
+ named.set(id, [...named.get(id) ?? [], range]);
3640
+ }
3641
+ }
3642
+ if (named.size === 0)
3643
+ continue;
3644
+ const inStep = (id, at) => (named.get(id) ?? []).some((r) => Date.parse(at) >= r.sa && Date.parse(at) <= r.fa);
3645
+ const ids = [...named.keys()];
3646
+ const runs = await inChunks(ids, (chunk) => sql(`SELECT id, workflowId wid, startedAt at FROM workflow_runs WHERE id IN (${marks(chunk.length)})
3647
+ AND parentStepId IS NULL AND sourceStepId IS NULL AND triggerType IN ('api','manual')`, chunk));
3648
+ for (const r of runs) {
3649
+ if (inStep(String(r.id), String(r.at)))
3650
+ onLink(workflowId, "workflow", String(r.id), String(r.wid));
3651
+ }
3652
+ const tasks = await inChunks(ids, (chunk) => sql(`SELECT id, createdAt at FROM agent_tasks WHERE id IN (${marks(chunk.length)})
3653
+ AND workflowRunId IS NULL AND sourceStepId IS NULL`, chunk));
3654
+ for (const t of tasks) {
3655
+ if (inStep(String(t.id), String(t.at)))
3656
+ onLink(workflowId, "task", String(t.id));
3657
+ }
3658
+ }
3659
+ }
3660
+
3661
+ // src/be/savings/rollup.ts
3662
+ var DAY_MS2 = 86400000;
3663
+ var ROLLUP_DAYS = 91;
3664
+ var ROLLUP_INTERVAL_MS = 60 * 60 * 1000;
3665
+ var RECOMPUTE_AFTER_MS = 30 * 60 * 1000;
3666
+ var WATERMARK_SLACK_MS = 30000;
3667
+ var CATCHUP_INTERVAL_MS = 60 * 1000;
3668
+ var DEFAULT_TICK_BUDGET_MS2 = 5 * 60 * 1000;
3669
+ var utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
3670
+ var dayStartIso = (day) => `${day}T00:00:00.000Z`;
3671
+ var dayStartMs = (day) => Date.parse(dayStartIso(day));
3672
+ var isFinalDay = (day, computedAt) => Date.parse(computedAt) >= dayStartMs(day) + 2 * DAY_MS2;
3673
+ var FACT_COLUMNS = [
3674
+ "runs",
3675
+ "countedRuns",
3676
+ "schedRuns",
3677
+ "schedEffectRuns",
3678
+ "eventRuns",
3679
+ "effectRuns",
3680
+ "effectOpsSum",
3681
+ "opsSum",
3682
+ "agentTasks",
3683
+ "agentUsd",
3684
+ "agentMs",
3685
+ "followupUsd",
3686
+ "childTaskUsd",
3687
+ "childTaskMs",
3688
+ "recordedLlmUsd",
3689
+ "estimatedLlmUsd",
3690
+ "computeSecs"
3691
+ ];
3692
+ var generation = 0;
3693
+ var savingsRollupGeneration = () => generation;
3694
+ var bumpGeneration = () => {
3695
+ generation++;
3696
+ };
3697
+ function parseDefinition(definition) {
3698
+ if (typeof definition !== "string")
3699
+ return definition ?? {};
3700
+ try {
3701
+ return JSON.parse(definition);
3702
+ } catch {
3703
+ return {};
3704
+ }
3705
+ }
3706
+ async function listWorkflows() {
3707
+ const rows = await getDbClient2().query("SELECT id, name, definition FROM workflows ORDER BY name");
3708
+ return rows.map((w) => ({ ...w, definition: parseDefinition(w.definition) }));
3709
+ }
3710
+ async function daysToCompute(kind, now) {
3711
+ const oldest = utcDay(now - (ROLLUP_DAYS - 1) * DAY_MS2);
3712
+ const markers = await getDbClient2().query("SELECT day, modelVersion, computedAt FROM automation_savings_days WHERE jobKind=? AND day>=?", [kind, oldest]);
3713
+ const byDay = new Map(markers.map((m) => [m.day, m]));
3714
+ const days = [];
3715
+ for (let i = 0;i < ROLLUP_DAYS; i++) {
3716
+ const day = utcDay(now - i * DAY_MS2);
3717
+ const m = byDay.get(day);
3718
+ const due = !m || Number(m.modelVersion) !== MODEL_VERSION || !isFinalDay(day, m.computedAt) && now - Date.parse(m.computedAt) >= RECOMPUTE_AFTER_MS;
3719
+ if (due)
3720
+ days.push(day);
3721
+ }
3722
+ return days;
3723
+ }
3724
+ async function computeWorkflowDay(day, sql, signal) {
3725
+ const window = { start: dayStartIso(day), end: dayStartIso(utcDay(dayStartMs(day) + DAY_MS2)) };
3726
+ const buckets = [];
3727
+ const workflows = await listWorkflows();
3728
+ for (const w of workflows) {
3729
+ signal?.throwIfAborted();
3730
+ const out = await computeWorkflowWindow(w, window, sql, {
3731
+ maxRuns: Number.POSITIVE_INFINITY
3732
+ });
3733
+ if (out.status === "ok" && out.facts.runs > 0) {
3734
+ buckets.push({ workflowId: w.id, name: w.name, facts: out.facts });
3735
+ }
3736
+ }
3737
+ signal?.throwIfAborted();
3738
+ const { links, childTasks } = await computeWorkflowLinksDay(window, workflows, sql);
3739
+ for (const b of buckets) {
3740
+ const spend = childTasks.get(b.workflowId);
3741
+ if (!spend)
3742
+ continue;
3743
+ b.facts.childTaskUsd += spend.usd;
3744
+ b.facts.childTaskMs += spend.ms;
3745
+ }
3746
+ return { buckets, links };
3747
+ }
3748
+ var UPSERT_BUCKET = `INSERT INTO automation_savings_daily
3749
+ (day, jobKind, jobId, jobKey, jobName, subKind, ${FACT_COLUMNS.join(", ")}, modelVersion, computedAt)
3750
+ VALUES (?, 'workflow', ?, ?, ?, '', ${FACT_COLUMNS.map(() => "?").join(", ")}, ?, ?)
3751
+ ON CONFLICT(day, jobKind, jobId, subKind) DO UPDATE SET
3752
+ jobKey=excluded.jobKey, jobName=excluded.jobName,
3753
+ ${FACT_COLUMNS.map((c) => `${c}=excluded.${c}`).join(", ")},
3754
+ modelVersion=excluded.modelVersion, computedAt=excluded.computedAt
3755
+ WHERE excluded.computedAt >= automation_savings_daily.computedAt
3756
+ OR automation_savings_daily.modelVersion <> excluded.modelVersion`;
3757
+ var bucketParams = (day, b, computedAt) => [
3758
+ day,
3759
+ b.workflowId,
3760
+ jobKey(b.name),
3761
+ b.name,
3762
+ ...FACT_COLUMNS.map((c) => b.facts[c]),
3763
+ MODEL_VERSION,
3764
+ computedAt
3765
+ ];
3766
+ var INSERT_LINK = `INSERT OR REPLACE INTO automation_savings_links
3767
+ (day, parentJobId, childKind, childJobId, linkKind, n, actualUsd, keptUsd, modelVersion, computedAt)
3768
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
3769
+ async function writeWorkflowDay(day, workflowDay, scannedAt) {
3770
+ await getDbClient2().transaction(async (tx) => {
3771
+ await tx.run("DELETE FROM automation_savings_daily WHERE day=? AND jobKind='workflow' AND (computedAt<=? OR modelVersion<>?)", [day, scannedAt, MODEL_VERSION]);
3772
+ await tx.run("DELETE FROM automation_savings_links WHERE day=?", [day]);
3773
+ for (const b of workflowDay.buckets) {
3774
+ await tx.run(UPSERT_BUCKET, bucketParams(day, b, scannedAt));
3775
+ }
3776
+ for (const l of workflowDay.links) {
3777
+ await tx.run(INSERT_LINK, [
3778
+ day,
3779
+ l.parentJobId,
3780
+ l.childKind,
3781
+ l.childJobId,
3782
+ l.linkKind,
3783
+ l.n,
3784
+ l.actualUsd,
3785
+ l.keptUsd,
3786
+ MODEL_VERSION,
3787
+ scannedAt
3788
+ ]);
3789
+ }
3790
+ await markDay(tx, day, "workflow", scannedAt);
3791
+ });
3792
+ bumpGeneration();
3793
+ }
3794
+ async function markDay(tx, day, kind, computedAt) {
3795
+ await tx.run(`INSERT INTO automation_savings_days (day, jobKind, modelVersion, computedAt) VALUES (?, ?, ?, ?)
3796
+ ON CONFLICT(day, jobKind) DO UPDATE SET modelVersion=excluded.modelVersion, computedAt=excluded.computedAt
3797
+ WHERE excluded.computedAt >= automation_savings_days.computedAt
3798
+ OR automation_savings_days.modelVersion <> excluded.modelVersion`, [day, kind, MODEL_VERSION, computedAt]);
3799
+ }
3800
+ function computeScriptDay(day, sql) {
3801
+ const window = { start: dayStartIso(day), end: dayStartIso(utcDay(dayStartMs(day) + DAY_MS2)) };
3802
+ return computeScriptSlice(window, sql);
3803
+ }
3804
+ async function computeScriptSlice(window, sql, opts = {}) {
3805
+ const out = [];
3806
+ for (const s of await computeScriptWindow(window, sql, opts)) {
3807
+ const facts = {
3808
+ runs: 0,
3809
+ apiRuns: 0,
3810
+ effectRuns: 0,
3811
+ apiEffectRuns: 0,
3812
+ opsSum: 0,
3813
+ computeSecs: 0
3814
+ };
3815
+ for (const d of s.byDay) {
3816
+ for (const k of Object.keys(facts))
3817
+ facts[k] += d[k];
3818
+ }
3819
+ if (facts.runs > 0)
3820
+ out.push({ scriptName: s.scriptName, facts });
3821
+ }
3822
+ return out;
3823
+ }
3824
+ var INSERT_SCRIPT_BUCKET = `INSERT OR REPLACE INTO automation_savings_daily
3825
+ (day, jobKind, jobId, jobKey, jobName, subKind, runs, countedRuns, effectRuns, opsSum, computeSecs, modelVersion, computedAt)
3826
+ VALUES (?, 'script', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
3827
+ async function writeScriptDay(day, buckets, scannedAt) {
3828
+ await getDbClient2().transaction(async (tx) => {
3829
+ await tx.run("DELETE FROM automation_savings_daily WHERE day=? AND jobKind='script'", [day]);
3830
+ for (const { scriptName, facts } of buckets) {
3831
+ const perRun = facts.runs > 0 ? facts.opsSum / facts.runs : 0;
3832
+ const nonApi = facts.runs - facts.apiRuns;
3833
+ const base = [day, scriptName, scriptName, scriptName];
3834
+ await tx.run(INSERT_SCRIPT_BUCKET, [
3835
+ ...base,
3836
+ "",
3837
+ nonApi,
3838
+ nonApi,
3839
+ facts.effectRuns,
3840
+ perRun * nonApi,
3841
+ facts.computeSecs,
3842
+ MODEL_VERSION,
3843
+ scannedAt
3844
+ ]);
3845
+ if (facts.apiRuns > 0) {
3846
+ await tx.run(INSERT_SCRIPT_BUCKET, [
3847
+ ...base,
3848
+ "api",
3849
+ facts.apiRuns,
3850
+ facts.apiRuns,
3851
+ facts.apiEffectRuns,
3852
+ perRun * facts.apiRuns,
3853
+ 0,
3854
+ MODEL_VERSION,
3855
+ scannedAt
3856
+ ]);
3857
+ }
3858
+ }
3859
+ await markDay(tx, day, "script", scannedAt);
3860
+ });
3861
+ bumpGeneration();
3862
+ }
3863
+ async function refreshWorkflowToday(workflow, sql, now) {
3864
+ const day = utcDay(now);
3865
+ const client = getDbClient2();
3866
+ const marker = await client.get("SELECT computedAt FROM automation_savings_days WHERE day=? AND jobKind='workflow' AND modelVersion=?", [day, MODEL_VERSION]);
3867
+ if (!marker)
3868
+ return "skipped";
3869
+ const bucket = await client.get("SELECT computedAt, childTaskUsd, childTaskMs FROM automation_savings_daily WHERE day=? AND jobKind='workflow' AND jobId=? AND subKind=''", [day, workflow.id]);
3870
+ const since = bucket && bucket.computedAt > marker.computedAt ? bucket.computedAt : marker.computedAt;
3871
+ const newer = await client.get("SELECT count(*) n FROM workflow_runs WHERE workflowId=? AND startedAt>=?", [workflow.id, new Date(Date.parse(since) - WATERMARK_SLACK_MS).toISOString()]);
3872
+ if (!Number(newer?.n))
3873
+ return "skipped";
3874
+ const out = await computeWorkflowWindow({ id: workflow.id, definition: parseDefinition(workflow.definition) }, { start: dayStartIso(day), end: dayStartIso(utcDay(dayStartMs(day) + DAY_MS2)) }, sql);
3875
+ if (out.status !== "ok")
3876
+ return "refused";
3877
+ out.facts.childTaskUsd = Number(bucket?.childTaskUsd) || 0;
3878
+ out.facts.childTaskMs = Number(bucket?.childTaskMs) || 0;
3879
+ const computedAt = new Date(now).toISOString();
3880
+ await client.run(UPSERT_BUCKET, bucketParams(day, { workflowId: workflow.id, name: workflow.name, facts: out.facts }, computedAt));
3881
+ bumpGeneration();
3882
+ return "computed";
3883
+ }
3884
+ var rollupSql = null;
3885
+ var rollupTimer = null;
3886
+ var catchupTimer2 = null;
3887
+ var tickPromise = null;
3888
+ var abortController = null;
3889
+ var failedAt = new Map;
3890
+ var stats = {
3891
+ ticks: 0,
3892
+ lastTickAt: null,
3893
+ daysComputed: 0,
3894
+ daysPending: 0,
3895
+ lastError: null
3896
+ };
3897
+ var scheduleContextFree2 = AsyncLocalStorage2.snapshot();
3898
+ function clearCatchup() {
3899
+ if (catchupTimer2) {
3900
+ clearTimeout(catchupTimer2);
3901
+ catchupTimer2 = null;
3902
+ }
3903
+ }
3904
+ function runSavingsRollupTick(sql, options = {}) {
3905
+ if (tickPromise)
3906
+ return tickPromise;
3907
+ const controller = new AbortController;
3908
+ abortController = controller;
3909
+ const promise = Promise.resolve().then(async () => {
3910
+ clearCatchup();
3911
+ const startedAt = Date.now();
3912
+ const now = options.now ?? startedAt;
3913
+ const budget = options.budgetMs ?? DEFAULT_TICK_BUDGET_MS2;
3914
+ stats = { ...stats, ticks: stats.ticks + 1, lastTickAt: new Date(startedAt).toISOString() };
3915
+ let computed = 0;
3916
+ let pending = [];
3917
+ let lastError = null;
3918
+ try {
3919
+ const oldest = utcDay(now - (ROLLUP_DAYS - 1) * DAY_MS2);
3920
+ await getDbClient2().run("DELETE FROM automation_savings_daily WHERE day<?", [oldest]);
3921
+ await getDbClient2().run("DELETE FROM automation_savings_days WHERE day<?", [oldest]);
3922
+ await getDbClient2().run("DELETE FROM automation_savings_links WHERE day<?", [oldest]);
3923
+ bumpGeneration();
3924
+ const wf = await daysToCompute("workflow", now);
3925
+ const sc = await daysToCompute("script", now);
3926
+ pending = [
3927
+ ...wf.map((day) => ({ kind: "workflow", day })),
3928
+ ...sc.map((day) => ({ kind: "script", day }))
3929
+ ].sort((a, b) => b.day.localeCompare(a.day) || (a.kind === "workflow" ? -1 : 1));
3930
+ const recentlyFailed = (p) => now - (failedAt.get(`${p.kind}:${p.day}`) ?? -Infinity) < ROLLUP_INTERVAL_MS;
3931
+ pending = [...pending.filter((p) => !recentlyFailed(p)), ...pending.filter(recentlyFailed)];
3932
+ } catch (err) {
3933
+ lastError = err instanceof Error ? err.message : String(err);
3934
+ }
3935
+ const failed = [];
3936
+ while (pending.length > 0 && !controller.signal.aborted && (computed + failed.length === 0 || Date.now() - startedAt <= budget)) {
3937
+ const { kind, day } = pending.shift();
3938
+ const key = `${kind}:${day}`;
3939
+ try {
3940
+ const scannedAt = new Date(options.now ?? Date.now()).toISOString();
3941
+ if (kind === "workflow") {
3942
+ const workflowDay = await computeWorkflowDay(day, sql, controller.signal);
3943
+ await writeWorkflowDay(day, workflowDay, scannedAt);
3944
+ } else {
3945
+ const buckets = await computeScriptDay(day, sql);
3946
+ await writeScriptDay(day, buckets, scannedAt);
3947
+ }
3948
+ failedAt.delete(key);
3949
+ computed += 1;
3950
+ } catch (err) {
3951
+ if (controller.signal.aborted)
3952
+ break;
3953
+ failed.push(key);
3954
+ failedAt.set(key, now);
3955
+ lastError = `${kind} ${day}: ${err instanceof Error ? err.message : String(err)}`;
3956
+ }
3957
+ }
3958
+ if (lastError)
3959
+ console.warn(`[savings-rollup] ${lastError.slice(0, 300)}`);
3960
+ stats = { ...stats, lastError };
3961
+ stats = {
3962
+ ...stats,
3963
+ daysComputed: stats.daysComputed + computed,
3964
+ daysPending: pending.length + failed.length
3965
+ };
3966
+ if (rollupTimer && pending.length > 0 && computed > 0 && !controller.signal.aborted) {
3967
+ catchupTimer2 = scheduleContextFree2(() => setTimeout(() => {
3968
+ catchupTimer2 = null;
3969
+ if (rollupSql)
3970
+ runSavingsRollupTick(rollupSql);
3971
+ }, CATCHUP_INTERVAL_MS));
3972
+ if (typeof catchupTimer2.unref === "function")
3973
+ catchupTimer2.unref();
3974
+ }
3975
+ return { ...stats };
3976
+ });
3977
+ const tracked = promise.finally(() => {
3978
+ if (tickPromise === tracked)
3979
+ tickPromise = null;
3980
+ if (abortController === controller)
3981
+ abortController = null;
3982
+ });
3983
+ tickPromise = tracked;
3984
+ return tracked;
3985
+ }
3986
+ function startSavingsRollup(sql, intervalMs = ROLLUP_INTERVAL_MS) {
3987
+ if (rollupTimer)
3988
+ return;
3989
+ rollupSql = sql;
3990
+ rollupTimer = scheduleContextFree2(() => setInterval(() => void runSavingsRollupTick(sql), intervalMs));
3991
+ if (typeof rollupTimer.unref === "function")
3992
+ rollupTimer.unref();
3993
+ runSavingsRollupTick(sql);
3994
+ }
3995
+ async function stopSavingsRollup() {
3996
+ if (rollupTimer) {
3997
+ clearInterval(rollupTimer);
3998
+ rollupTimer = null;
3999
+ }
4000
+ clearCatchup();
4001
+ abortController?.abort();
4002
+ await tickPromise?.catch(() => {
4003
+ return;
4004
+ });
4005
+ }
4006
+
2445
4007
  // src/be/scripts/retention.ts
2446
4008
  init_definition();
2447
4009
  init_store2();
@@ -3548,10 +5110,61 @@ init_sdk_allowlist();
3548
5110
  init_redacted();
3549
5111
 
3550
5112
  // src/scripts-runtime/stdlib/fetch.ts
5113
+ init_retry();
5114
+ var IDEMPOTENT_METHODS = new Set([
5115
+ "GET",
5116
+ "HEAD",
5117
+ "OPTIONS",
5118
+ "PUT",
5119
+ "DELETE"
5120
+ ]);
5121
+ var TRANSIENT_5XX = new Set([502, 503, 504]);
5122
+ function shouldRetryFetch(value, repeatSafe) {
5123
+ if (value instanceof Response) {
5124
+ return value.status === 429 || repeatSafe && TRANSIENT_5XX.has(value.status);
5125
+ }
5126
+ return repeatSafe;
5127
+ }
5128
+ function isReplayableBody(body) {
5129
+ return body === undefined || body === null || typeof body === "string" || body instanceof URLSearchParams || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof Blob || body instanceof FormData;
5130
+ }
5131
+ function resolveRetry(option, legacyAttempts) {
5132
+ if (option === false)
5133
+ return { retries: 0 };
5134
+ if (option && typeof option === "object")
5135
+ return option;
5136
+ if (option === undefined && legacyAttempts !== undefined) {
5137
+ return { retries: Math.max(0, legacyAttempts - 1) };
5138
+ }
5139
+ return {};
5140
+ }
3551
5141
  async function runtimeFetch(input, options = {}) {
3552
- const { retries = 3, timeoutMs = 30000, signal, ...init } = options;
3553
- let lastError;
3554
- for (let attempt = 0;attempt < retries; attempt++) {
5142
+ const {
5143
+ retry: retryOption,
5144
+ retries: legacyAttempts,
5145
+ timeoutMs = 30000,
5146
+ signal,
5147
+ ...init
5148
+ } = options;
5149
+ const {
5150
+ idempotencyKey,
5151
+ retryOn: userRetryOn,
5152
+ ...retryOptions
5153
+ } = resolveRetry(retryOption, legacyAttempts);
5154
+ const inputRequest = input instanceof Request ? input : undefined;
5155
+ if (idempotencyKey) {
5156
+ const headers = new Headers(init.headers ?? inputRequest?.headers);
5157
+ if (!headers.has("idempotency-key")) {
5158
+ headers.set("idempotency-key", idempotencyKey === true ? crypto.randomUUID() : String(idempotencyKey));
5159
+ }
5160
+ init.headers = headers;
5161
+ }
5162
+ const method = (init.method ?? inputRequest?.method ?? "GET").toUpperCase();
5163
+ const hasKey = new Headers(init.headers ?? inputRequest?.headers).has("idempotency-key");
5164
+ const repeatSafe = IDEMPOTENT_METHODS.has(method) || hasKey;
5165
+ const replayable = init.body !== undefined ? isReplayableBody(init.body) : !inputRequest || inputRequest.body === null || !inputRequest.bodyUsed;
5166
+ const target = () => inputRequest && inputRequest.body !== null ? inputRequest.clone() : input;
5167
+ const attempt = async () => {
3555
5168
  if (signal?.aborted) {
3556
5169
  throw signal.reason ?? new DOMException("This operation was aborted", "AbortError");
3557
5170
  }
@@ -3562,24 +5175,29 @@ async function runtimeFetch(input, options = {}) {
3562
5175
  if (signal?.aborted)
3563
5176
  controller.abort();
3564
5177
  try {
3565
- const res = await fetch(input, { ...init, signal: controller.signal });
3566
- if (!res.ok && attempt < retries - 1 && res.status >= 500) {
3567
- lastError = new Error(`fetch failed with ${res.status}`);
3568
- continue;
3569
- }
3570
- return res;
5178
+ return await fetch(target(), { ...init, signal: controller.signal });
3571
5179
  } catch (error) {
3572
5180
  if (signal?.aborted)
3573
5181
  throw signal.reason ?? error;
3574
- lastError = error;
3575
- if (attempt === retries - 1)
3576
- break;
5182
+ throw error;
3577
5183
  } finally {
3578
5184
  clearTimeout(timeout);
3579
5185
  signal?.removeEventListener("abort", onAbort);
3580
5186
  }
3581
- }
3582
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
5187
+ };
5188
+ if (!replayable)
5189
+ return attempt();
5190
+ return retry(attempt, {
5191
+ ...retryOptions,
5192
+ signal: signal ?? retryOptions.signal,
5193
+ retryOn: async (value, attemptNumber) => {
5194
+ if (signal?.aborted)
5195
+ return false;
5196
+ if (userRetryOn)
5197
+ return userRetryOn(value, attemptNumber);
5198
+ return shouldRetryFetch(value, repeatSafe);
5199
+ }
5200
+ });
3583
5201
  }
3584
5202
  async function runtimeFetchJson(input, options = {}) {
3585
5203
  const res = await runtimeFetch(input, options);
@@ -3624,6 +5242,9 @@ async function grep(pattern, cwd = process.cwd()) {
3624
5242
  });
3625
5243
  }
3626
5244
 
5245
+ // src/scripts-runtime/stdlib/index.ts
5246
+ init_retry();
5247
+
3627
5248
  // src/scripts-runtime/stdlib/table.ts
3628
5249
  function table(rows) {
3629
5250
  if (rows.length === 0)
@@ -3647,6 +5268,7 @@ var stdlib = {
3647
5268
  grep,
3648
5269
  glob,
3649
5270
  table,
5271
+ retry,
3650
5272
  Redacted
3651
5273
  };
3652
5274
 
@@ -6298,14 +7920,14 @@ var USAGE_CACHE_MAX_STALE_MS = 120000;
6298
7920
  var MAX_ENTRIES = 100;
6299
7921
  var entries = new Map;
6300
7922
  var loading = new Map;
6301
- var generation = 0;
7923
+ var generation2 = 0;
6302
7924
  function load(key, loader) {
6303
7925
  const running = loading.get(key);
6304
7926
  if (running)
6305
7927
  return running;
6306
- const startedIn = generation;
7928
+ const startedIn = generation2;
6307
7929
  const promise = Promise.resolve().then(loader).then((value) => {
6308
- if (startedIn === generation) {
7930
+ if (startedIn === generation2) {
6309
7931
  entries.delete(key);
6310
7932
  if (entries.size >= MAX_ENTRIES)
6311
7933
  entries.delete(entries.keys().next().value);
@@ -6335,7 +7957,7 @@ async function cachedUsageReport(key, loader) {
6335
7957
  return load(key, loader);
6336
7958
  }
6337
7959
  function clearUsageCache() {
6338
- generation++;
7960
+ generation2++;
6339
7961
  entries.clear();
6340
7962
  loading.clear();
6341
7963
  }
@@ -11251,6 +12873,19 @@ declare module "swarm-extension" {
11251
12873
  slackThreadTs?: string | undefined;
11252
12874
  slackTriggerMessageTs?: string | undefined;
11253
12875
  slackUserId?: string | undefined;
12876
+ slackParticipants?:
12877
+ | {
12878
+ people: {
12879
+ slackUserId: string;
12880
+ trust: "external" | "unknown" | "internal";
12881
+ userId?: string | undefined;
12882
+ starter?: boolean | undefined;
12883
+ newest?: boolean | undefined;
12884
+ asked?: boolean | undefined;
12885
+ }[];
12886
+ more: number;
12887
+ }
12888
+ | undefined;
11254
12889
  overrideSlackContext?: boolean | undefined;
11255
12890
  vcsProvider?: "github" | "gitlab" | "azure-devops" | "bitbucket" | undefined;
11256
12891
  vcsRepo?: string | undefined;
@@ -11272,6 +12907,23 @@ declare module "swarm-extension" {
11272
12907
  modelTier?: "smol" | "regular" | "smart" | "ultra" | undefined;
11273
12908
  effort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;
11274
12909
  profile?: string | undefined;
12910
+ fallbackHops?:
12911
+ | {
12912
+ from: string;
12913
+ profile: string;
12914
+ errorClass:
12915
+ | "rate_limit"
12916
+ | "model_window"
12917
+ | "seat"
12918
+ | "credits"
12919
+ | "overloaded"
12920
+ | "server_error"
12921
+ | "auth"
12922
+ | "pool_empty";
12923
+ at: string;
12924
+ skipped?: { profile: string; reason: string }[] | undefined;
12925
+ }[]
12926
+ | undefined;
11275
12927
  scheduleId?: string | undefined;
11276
12928
  workflowRunId?: string | undefined;
11277
12929
  workflowRunStepId?: string | undefined;
@@ -11385,6 +13037,19 @@ declare module "swarm-extension" {
11385
13037
  slackThreadTs?: string | undefined;
11386
13038
  slackTriggerMessageTs?: string | undefined;
11387
13039
  slackUserId?: string | undefined;
13040
+ slackParticipants?:
13041
+ | {
13042
+ people: {
13043
+ slackUserId: string;
13044
+ trust: "external" | "unknown" | "internal";
13045
+ userId?: string | undefined;
13046
+ starter?: boolean | undefined;
13047
+ newest?: boolean | undefined;
13048
+ asked?: boolean | undefined;
13049
+ }[];
13050
+ more: number;
13051
+ }
13052
+ | undefined;
11388
13053
  slackProgressMessageTs?: string | undefined;
11389
13054
  slackTreeRootMessageTs?: string | undefined;
11390
13055
  vcsProvider?: "github" | "gitlab" | "azure-devops" | "bitbucket" | undefined;
@@ -11414,6 +13079,23 @@ declare module "swarm-extension" {
11414
13079
  resolvedEffort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;
11415
13080
  profile?: string | undefined;
11416
13081
  resolvedProfile?: string | undefined;
13082
+ fallbackHops?:
13083
+ | {
13084
+ from: string;
13085
+ profile: string;
13086
+ errorClass:
13087
+ | "rate_limit"
13088
+ | "model_window"
13089
+ | "seat"
13090
+ | "credits"
13091
+ | "overloaded"
13092
+ | "server_error"
13093
+ | "auth"
13094
+ | "pool_empty";
13095
+ at: string;
13096
+ skipped?: { profile: string; reason: string }[] | undefined;
13097
+ }[]
13098
+ | undefined;
11417
13099
  scheduleId?: string | undefined;
11418
13100
  workflowRunId?: string | null | undefined;
11419
13101
  workflowRunStepId?: string | null | undefined;
@@ -15303,10 +16985,11 @@ var agentFsCredentialStateSchema = object2({
15303
16985
  var agentFsInviteStateSchema = object2({
15304
16986
  orgId: string2(),
15305
16987
  invited: boolean().describe("False only when the email already holds the requested role."),
15306
- status: _enum2(["already_member", "added", "pending"]).describe("already_member: no change. added: an existing agent-fs account joined the org. pending: the email has no account, so agent-fs created an invite the person must accept."),
16988
+ status: _enum2(["already_member", "added", "pending"]).describe("already_member: no change. added: the email was already in the org and holds the role now. pending: agent-fs created an invite the person must accept (agent-fs >= 0.18.19 does this for every email not yet in the org, with or without an account)."),
15307
16989
  inviteId: string2().optional().describe("Pending invite id (status pending)."),
15308
16990
  expiresAt: string2().optional().describe("ISO time the accept link expires (status pending)."),
15309
- acceptUrl: string2().optional().describe("Link the invitee opens to accept (status pending). agent-fs sends no email, so hand it to the person. Absent when agent-fs has no app URL configured.")
16991
+ acceptUrl: string2().optional().describe("Link the invitee opens to accept (status pending). agent-fs sends no email, so hand it to the person. Absent when agent-fs has no app URL configured."),
16992
+ token: string2().optional().describe("Accept token (status pending). Only the invited account can redeem it, with its own key: agent-fs POST /invites/{token}/accept.")
15310
16993
  });
15311
16994
  var signedUrlResponseSchema = object2({
15312
16995
  url: string2(),
@@ -15346,7 +17029,7 @@ var inviteMemberRoute = route({
15346
17029
  path: "/api/fs/members/invite",
15347
17030
  pattern: ["api", "fs", "members", "invite"],
15348
17031
  summary: "Invite an external member into the agent-fs shared org",
15349
- description: "The API server performs the invite with its own bootstrap credentials (which are API-only and never served over HTTP), provisioning the shared org/drive first when needed. Intended for the cloud control plane's Connect-to-Drive flow. An email with an agent-fs account is added directly (status added). An email without one gets a pending invite (status pending) with an acceptUrl when agent-fs returns one; agent-fs sends no email, so the caller must hand the link to the invitee. No keys are returned; the invitee obtains their own key via agent-fs registration.",
17032
+ description: "The API server performs the invite with its own bootstrap credentials (which are API-only and never served over HTTP), provisioning the shared org/drive first when needed. Intended for the cloud control plane's Connect-to-Drive flow. An email already in the org gets the grant directly (status added). Any other email gets a pending invite (status pending) with its accept token, and an acceptUrl when agent-fs returns one; agent-fs sends no email, so the caller must hand the link to the invitee, or accept with the invitee's own key. No keys are returned; the invitee obtains their own key via agent-fs registration.",
15350
17033
  tags: ["FS"],
15351
17034
  body: object2({
15352
17035
  email: email(),
@@ -22496,6 +24179,7 @@ async function handleMetrics(req, res, pathSegments, queryParams, myAgentId) {
22496
24179
  init_src2();
22497
24180
  init_zod();
22498
24181
  init_audit_user();
24182
+ init_db4();
22499
24183
  init_model_profiles();
22500
24184
  init_model_validation2();
22501
24185
  init_rbac();
@@ -22536,7 +24220,7 @@ var createProfile = route({
22536
24220
  path: "/api/model-profiles",
22537
24221
  pattern: ["api", "model-profiles"],
22538
24222
  summary: "Create a model profile",
22539
- description: "A profile runs on one harness. `model` must run on that harness and be in the model catalog unless `allowCustomModel` is true (a gateway id, a fresh launch); a `latest:` alias is accepted and resolves at claim. `effort` must be a level the harness and model support. `credentials` pins which pooled keys the profile uses: per credential var of the harness, the last 5 characters of each allowed key (`CODEX_OAUTH` is not supported). Operator only (the shared API key).",
24223
+ description: "A profile runs on one harness. `model` must run on that harness and be in the model catalog unless `allowCustomModel` is true (a gateway id, a fresh launch); a `latest:` alias is accepted and resolves at claim. `effort` must be a level the harness and model support. `credentials` pins which pooled keys the profile uses: per credential var of the harness, the last 5 characters of each allowed key (`CODEX_OAUTH` is not supported). `fallbacks` lists profiles on the same harness, in order, that a task on this profile hops to when a provider error (rate limit, seat, overload, auth, empty key pool) ends it; no repeats, no self, no cycle. Operator only (the shared API key).",
22540
24224
  tags: ["Models"],
22541
24225
  rbac: { permission: "models.profiles.write" },
22542
24226
  body: object2({
@@ -22546,7 +24230,8 @@ var createProfile = route({
22546
24230
  effort: ReasoningEffortSchema.nullable().optional(),
22547
24231
  allowCustomModel: boolean().optional().default(false),
22548
24232
  description: string2().trim().max(500).nullable().optional(),
22549
- credentials: ModelProfileCredentialsSchema.nullable().optional()
24233
+ credentials: ModelProfileCredentialsSchema.nullable().optional(),
24234
+ fallbacks: array2(ModelProfileNameSchema).max(MAX_MODEL_PROFILE_FALLBACKS).optional()
22550
24235
  }),
22551
24236
  responses: {
22552
24237
  201: { description: "Profile created", schema: ModelProfileSchema },
@@ -22560,7 +24245,7 @@ var updateProfile = route({
22560
24245
  path: "/api/model-profiles/{name}",
22561
24246
  pattern: ["api", "model-profiles", null],
22562
24247
  summary: "Update a model profile",
22563
- description: "Changes the model, effort, custom-model flag, description or credential allowlist; the name and harness are fixed. Omit a field to keep it; `effort: null` and `credentials: null` clear it. Applies to tasks claimed after the change. Operator only (the shared API key).",
24248
+ description: "Changes the model, effort, custom-model flag, description, credential allowlist or fallbacks; the name and harness are fixed. Omit a field to keep it; `effort: null` and `credentials: null` clear it, and `fallbacks: []` empties the list. Applies to tasks claimed after the change. Operator only (the shared API key).",
22564
24249
  tags: ["Models"],
22565
24250
  rbac: { permission: "models.profiles.write" },
22566
24251
  params: object2({ name: string2() }),
@@ -22569,7 +24254,8 @@ var updateProfile = route({
22569
24254
  effort: ReasoningEffortSchema.nullable().optional(),
22570
24255
  allowCustomModel: boolean().optional(),
22571
24256
  description: string2().trim().max(500).nullable().optional(),
22572
- credentials: ModelProfileCredentialsSchema.nullable().optional()
24257
+ credentials: ModelProfileCredentialsSchema.nullable().optional(),
24258
+ fallbacks: array2(ModelProfileNameSchema).max(MAX_MODEL_PROFILE_FALLBACKS).optional()
22573
24259
  }),
22574
24260
  responses: {
22575
24261
  200: { description: "Profile updated", schema: ModelProfileSchema },
@@ -22583,7 +24269,7 @@ var deleteProfile = route({
22583
24269
  path: "/api/model-profiles/{name}",
22584
24270
  pattern: ["api", "model-profiles", null],
22585
24271
  summary: "Delete a model profile",
22586
- description: "Refused (409) for a shipped `<harness>-<tier>` seed (edit it instead; it would come back at the next boot), and while an agent has the profile as its default, a schedule names it, or a task holds it (unfinished, or superseded and still owed its resume). Operator only (the shared API key).",
24272
+ description: "Refused (409) for a shipped `<harness>-<tier>` seed (edit it instead; it would come back at the next boot), and while an agent has the profile as its default, a schedule names it, another profile lists it as a fallback, or a task holds it (unfinished, or superseded and still owed its resume). Operator only (the shared API key).",
22587
24273
  tags: ["Models"],
22588
24274
  rbac: { permission: "models.profiles.write" },
22589
24275
  params: object2({ name: string2() }),
@@ -22676,9 +24362,18 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
22676
24362
  jsonError(res, error, 400);
22677
24363
  return true;
22678
24364
  }
22679
- const created = await createModelProfile(body, {
22680
- userId: await resolveHttpAuditUserId(req, myAgentId)
24365
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
24366
+ const outcome = await getDbClient2().transaction(async () => {
24367
+ const fallbackError = body.fallbacks ? await modelProfileFallbacksError(body.name, body.harness, body.fallbacks) : null;
24368
+ if (fallbackError)
24369
+ return { error: fallbackError };
24370
+ return { created: await createModelProfile(body, { userId }) };
22681
24371
  });
24372
+ if (typeof outcome.error === "string") {
24373
+ jsonError(res, outcome.error, 400);
24374
+ return true;
24375
+ }
24376
+ const created = outcome.created;
22682
24377
  if (!created) {
22683
24378
  jsonError(res, `Model profile "${body.name}" already exists`, 409);
22684
24379
  return true;
@@ -22709,9 +24404,18 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
22709
24404
  jsonError(res, error, 400);
22710
24405
  return true;
22711
24406
  }
22712
- const updated = await updateModelProfile(current.name, body, {
22713
- userId: await resolveHttpAuditUserId(req, myAgentId)
24407
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
24408
+ const outcome = await getDbClient2().transaction(async () => {
24409
+ const fallbackError = body.fallbacks ? await modelProfileFallbacksError(current.name, current.harness, body.fallbacks) : null;
24410
+ if (fallbackError)
24411
+ return { error: fallbackError };
24412
+ return { updated: await updateModelProfile(current.name, body, { userId }) };
22714
24413
  });
24414
+ if (typeof outcome.error === "string") {
24415
+ jsonError(res, outcome.error, 400);
24416
+ return true;
24417
+ }
24418
+ const updated = outcome.updated;
22715
24419
  if (!updated) {
22716
24420
  jsonError(res, "Model profile not found", 404);
22717
24421
  return true;
@@ -22735,14 +24439,15 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
22735
24439
  return true;
22736
24440
  }
22737
24441
  const refs = await modelProfileReferences(current.name);
22738
- if (refs.agentIds.length > 0 || refs.openTaskCount > 0 || refs.scheduleIds.length > 0) {
24442
+ if (refs.agentIds.length > 0 || refs.openTaskCount > 0 || refs.scheduleIds.length > 0 || refs.fallbackOf.length > 0) {
22739
24443
  const schedules = refs.scheduleIds.length > 0 ? ` (${refs.scheduleIds.join(", ")})` : "";
22740
- jsonError(res, `"${current.name}" is in use: default of ${refs.agentIds.length} agent(s), held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}.`, 409);
24444
+ const fallbackOf = refs.fallbackOf.length > 0 ? ` (${refs.fallbackOf.join(", ")})` : "";
24445
+ jsonError(res, `"${current.name}" is in use: default of ${refs.agentIds.length} agent(s), held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}, a fallback of ${refs.fallbackOf.length} profile(s)${fallbackOf}.`, 409);
22741
24446
  return true;
22742
24447
  }
22743
24448
  const outcome = await deleteModelProfile(current.name);
22744
24449
  if (outcome === "in-use") {
22745
- jsonError(res, `"${current.name}" is in use by a task, a schedule or an agent default created just now.`, 409);
24450
+ jsonError(res, `"${current.name}" is in use by a task, a schedule, an agent default or a fallback list written just now.`, 409);
22746
24451
  return true;
22747
24452
  }
22748
24453
  if (outcome === "missing") {
@@ -23078,14 +24783,15 @@ async function getJiraOAuthConfig() {
23078
24783
  const app = await getOAuthApp("jira");
23079
24784
  return app ? oauthAppRowToProviderConfig(app) : null;
23080
24785
  }
23081
- async function getJiraAuthorizationUrl(finalRedirect) {
24786
+ async function getJiraAuthorizationUrl(finalRedirect, userId) {
23082
24787
  const config = await getJiraOAuthConfig();
23083
24788
  if (!config)
23084
24789
  return null;
23085
24790
  const result = await buildAuthorizationUrl(config, {
23086
24791
  flow: "tracker",
23087
24792
  label: "default",
23088
- ...finalRedirect ? { finalRedirect } : {}
24793
+ ...finalRedirect ? { finalRedirect } : {},
24794
+ ...userId ? { userId } : {}
23089
24795
  });
23090
24796
  return result.url;
23091
24797
  }
@@ -23122,14 +24828,15 @@ async function getLinearOAuthConfig() {
23122
24828
  const app = await getOAuthApp("linear");
23123
24829
  return app ? oauthAppRowToProviderConfig(app) : null;
23124
24830
  }
23125
- async function getLinearAuthorizationUrl(finalRedirect) {
24831
+ async function getLinearAuthorizationUrl(finalRedirect, userId) {
23126
24832
  const config = await getLinearOAuthConfig();
23127
24833
  if (!config)
23128
24834
  return null;
23129
24835
  const result = await buildAuthorizationUrl(config, {
23130
24836
  flow: "tracker",
23131
24837
  label: "default",
23132
- ...finalRedirect ? { finalRedirect } : {}
24838
+ ...finalRedirect ? { finalRedirect } : {},
24839
+ ...userId ? { userId } : {}
23133
24840
  });
23134
24841
  return result.url;
23135
24842
  }
@@ -24819,6 +26526,7 @@ init_types4();
24819
26526
  init_business_use();
24820
26527
  init_request_auth_context();
24821
26528
  init_secret_scrubber();
26529
+ init_vcs_repo_match();
24822
26530
 
24823
26531
  // src/http/list-total-cache.ts
24824
26532
  var LIST_TOTAL_TTL_MS = 30000;
@@ -24877,9 +26585,14 @@ var TaskRequestedBySchema = UserSchema.pick({
24877
26585
  function getRequesterNotes(notes) {
24878
26586
  return typeof notes === "string" && notes.trim().length > 0 ? notes : undefined;
24879
26587
  }
26588
+ var isUntrusted = (trust) => trust === "external" || trust === "unknown";
24880
26589
  async function buildTaskRequestedBy(task) {
24881
26590
  const user = task.requestedByUserId ? await getUserById2(task.requestedByUserId) : undefined;
24882
26591
  if (user) {
26592
+ const newest = task.slackParticipants?.people.find((person) => person.newest);
26593
+ if (newest && isUntrusted(newest.trust)) {
26594
+ return { id: user.id, name: user.name, email: user.email };
26595
+ }
24883
26596
  return {
24884
26597
  id: user.id,
24885
26598
  name: user.name,
@@ -24894,6 +26607,64 @@ async function buildTaskRequestedBy(task) {
24894
26607
  }
24895
26608
  return;
24896
26609
  }
26610
+ var MAX_NOTE_CHARS = 60;
26611
+ var cut = (value) => value?.trim() ? value.trim().slice(0, MAX_NOTE_CHARS) : undefined;
26612
+ var TaskThreadParticipantsSchema = object2({
26613
+ total: number2().int(),
26614
+ more: number2().int(),
26615
+ people: array2(object2({
26616
+ label: string2(),
26617
+ trust: SlackParticipantTrustSchema,
26618
+ starter: boolean().optional(),
26619
+ newest: boolean().optional(),
26620
+ asked: boolean().optional(),
26621
+ language: string2().optional(),
26622
+ verbosity: string2().optional()
26623
+ })),
26624
+ starterProfile: TaskRequestedBySchema.optional()
26625
+ });
26626
+ async function buildTaskThreadParticipants(task) {
26627
+ const stored = task.slackParticipants;
26628
+ if (!stored || stored.people.length === 0)
26629
+ return;
26630
+ const total = stored.people.length + stored.more;
26631
+ if (total < 2 && !stored.people.some((person) => isUntrusted(person.trust)))
26632
+ return;
26633
+ let starterProfile;
26634
+ const people = await Promise.all(stored.people.map(async (person) => {
26635
+ const user = person.userId ? await getUserById2(person.userId) : undefined;
26636
+ const identity = await resolveIdentity("slack", person.slackUserId);
26637
+ const untrusted = isUntrusted(person.trust);
26638
+ const tags = [
26639
+ identity.status === "resolved" ? undefined : "unknown user",
26640
+ untrusted && identity.status === "resolved" ? person.trust : undefined,
26641
+ !untrusted ? user?.role : undefined,
26642
+ untrusted ? "untrusted" : undefined
26643
+ ].filter(Boolean);
26644
+ const mention = identity.status === "resolved" ? `<@${person.slackUserId}|${identity.name}>` : `<@${person.slackUserId}>`;
26645
+ const comms = user && !untrusted ? getUserCommsPrefs(user) : undefined;
26646
+ if (person.starter && !person.newest && !untrusted && user) {
26647
+ starterProfile = {
26648
+ id: user.id,
26649
+ name: user.name,
26650
+ role: user.role,
26651
+ notes: getRequesterNotes(user.notes),
26652
+ comms
26653
+ };
26654
+ }
26655
+ const primary = person.starter || person.newest;
26656
+ return {
26657
+ label: tags.length > 0 ? `${mention} (${tags.join(", ")})` : mention,
26658
+ trust: person.trust,
26659
+ ...person.starter && { starter: true },
26660
+ ...person.newest && { newest: true },
26661
+ ...person.asked && { asked: true },
26662
+ ...!primary && cut(comms?.language) && { language: cut(comms?.language) },
26663
+ ...!primary && cut(comms?.verbosity) && { verbosity: cut(comms?.verbosity) }
26664
+ };
26665
+ }));
26666
+ return { total, more: stored.more, people, ...starterProfile && { starterProfile } };
26667
+ }
24897
26668
 
24898
26669
  // src/http/tasks.ts
24899
26670
  init_route_def();
@@ -24982,10 +26753,11 @@ var FinishTaskConflictSchema = object2({
24982
26753
  });
24983
26754
  var SupersedeTaskResponseSchema = object2({
24984
26755
  success: literal2(true),
24985
- kind: _enum2(["alreadyFinished", "workflow-failed", "resumed"]),
26756
+ kind: _enum2(["alreadyFinished", "workflow-failed", "resumed", "noFallback"]),
24986
26757
  task: AgentTaskSchema.nullable(),
24987
26758
  resumeTaskId: string2().nullable(),
24988
- resumeTaskStatus: AgentTaskStatusSchema.optional()
26759
+ resumeTaskStatus: AgentTaskStatusSchema.optional(),
26760
+ failureReason: string2().nullable().optional()
24989
26761
  });
24990
26762
  var taskTotals = createListTotalCache(LIST_TOTAL_TTL_MS, 15000);
24991
26763
  var listTasks = route({
@@ -25049,6 +26821,7 @@ var createTask = route({
25049
26821
  dependsOn: array2(string2()).optional(),
25050
26822
  offeredTo: string2().optional(),
25051
26823
  dir: string2().optional(),
26824
+ vcsRepo: string2().trim().min(1).optional().describe("A registered repo (`swarm_repos`), as `owner/repo` or its URL. The worker clones or refreshes it and loads its `CLAUDE.md`. Stored as the registered repo's URL; an unregistered or ambiguous repo is a 400."),
25052
26825
  parentTaskId: string2().optional(),
25053
26826
  key: AssetKeySchema.optional(),
25054
26827
  source: AgentTaskSourceSchema.optional(),
@@ -25073,7 +26846,7 @@ var createTask = route({
25073
26846
  responses: {
25074
26847
  201: { description: "Task created", schema: AgentTaskSchema },
25075
26848
  400: {
25076
- description: "Validation error, an unknown `model` (set `allowCustomModel` to store a custom id), or agentId/offeredTo targets an extension identity"
26849
+ description: "Validation error, an unknown `model` (set `allowCustomModel` to store a custom id), a `vcsRepo` that is not exactly one registered repo, or agentId/offeredTo targets an extension identity"
25077
26850
  },
25078
26851
  403: {
25079
26852
  description: "An agent caller names a parentTaskId it neither owns nor created, or a non-lead agent binds the task to a chat thread"
@@ -25384,6 +27157,7 @@ var listPausedTasks = route({
25384
27157
  tasks: array2(AgentTaskSchema.extend({
25385
27158
  attachments: array2(TaskAttachmentSchema),
25386
27159
  requestedBy: TaskRequestedBySchema.optional(),
27160
+ threadParticipants: TaskThreadParticipantsSchema.optional(),
25387
27161
  credentialAllowlist: ModelProfileCredentialsSchema.optional()
25388
27162
  }))
25389
27163
  })
@@ -25428,10 +27202,13 @@ var supersedeTaskRoute = route({
25428
27202
  pattern: ["api", "tasks", null, "supersede"],
25429
27203
  session: { taskParam: "id" },
25430
27204
  summary: "Supersede an in-progress task (terminate + spawn resume follow-up)",
25431
- description: 'Marks the original task `superseded` (terminal) and creates a fresh `taskType="resume"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine\'s retry/failure policy applies.',
27205
+ description: 'Marks the original task `superseded` (terminal) and creates a fresh `taskType="resume"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine\'s retry/failure policy applies. With `reason: provider_fallback` (and its `errorClass`), the resume runs on the same agent with the next fallback profile that passes the profile check; when none is left, or the task is a workflow step, nothing changes and `kind: noFallback` tells the worker to fail the task itself, led by `failureReason` when set.',
25432
27206
  tags: ["Tasks"],
25433
27207
  params: object2({ id: string2() }),
25434
- body: object2({ reason: ResumeReasonSchema }),
27208
+ body: object2({ reason: ResumeReasonSchema, errorClass: ProviderErrorClassSchema.optional() }).refine((body) => body.reason === "provider_fallback" === (body.errorClass !== undefined), {
27209
+ message: "`errorClass` is required with `reason: provider_fallback` and only allowed with it",
27210
+ path: ["errorClass"]
27211
+ }),
25435
27212
  auth: { apiKey: true, agentId: true },
25436
27213
  responses: {
25437
27214
  200: {
@@ -25646,6 +27423,20 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
25646
27423
  jsonError(res, modelError, 400);
25647
27424
  return true;
25648
27425
  }
27426
+ let vcsRepo;
27427
+ if (parsed.body.vcsRepo) {
27428
+ const requested = parsed.body.vcsRepo;
27429
+ const [repo, ...others] = (await getSwarmRepos2()).filter((r) => vcsRepoUrlMatches(r.url, requested));
27430
+ if (!repo) {
27431
+ jsonError(res, `Unknown repo "${requested}": register it in Repos first.`, 400);
27432
+ return true;
27433
+ }
27434
+ if (others.length > 0) {
27435
+ jsonError(res, `Repo "${requested}" matches several registered repos: pass its URL.`, 400);
27436
+ return true;
27437
+ }
27438
+ vcsRepo = normalizeVcsRepo(repo.url);
27439
+ }
25649
27440
  const parentTask = parsed.body.parentTaskId ? await getTaskById2(parsed.body.parentTaskId) : null;
25650
27441
  const principal = await resolveTaskWritePrincipal(req, myAgentId);
25651
27442
  if (parentTask && await denyParentAttach2(req, res, myAgentId, parentTask, principal)) {
@@ -25663,7 +27454,7 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
25663
27454
  profile: parsed.body.profile,
25664
27455
  ...splitLegacyModelAlias({ model: parsed.body.model, modelTier: parsed.body.modelTier }),
25665
27456
  agentId: defaultAgentId,
25666
- vcsRepo: parentTask?.vcsRepo
27457
+ vcsRepo: vcsRepo ?? parentTask?.vcsRepo
25667
27458
  });
25668
27459
  if (profileError) {
25669
27460
  jsonError(res, profileError, 400);
@@ -25695,6 +27486,7 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
25695
27486
  dependsOn: parsed.body.dependsOn || undefined,
25696
27487
  offeredTo: parsed.body.offeredTo || undefined,
25697
27488
  dir: parsed.body.dir || undefined,
27489
+ vcsRepo,
25698
27490
  parentTaskId: parsed.body.parentTaskId || undefined,
25699
27491
  inheritParentOutputSchema: principal.kind === "agent",
25700
27492
  source: parsed.body.source || "api",
@@ -26278,6 +28070,7 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
26278
28070
  const pausedTasks = await getPausedTasksForAgent2(myAgentId, readableByFor2(await resolveSessionActor2(req, myAgentId)));
26279
28071
  const tasks = await Promise.all(pausedTasks.map(async (task) => {
26280
28072
  const requestedBy = await buildTaskRequestedBy(task);
28073
+ const threadParticipants = await buildTaskThreadParticipants(task);
26281
28074
  const profile = task.resolvedProfile ? await getModelProfileByName(task.resolvedProfile) : null;
26282
28075
  if (profile && hasUnreadableCredentialAllowlist(profile)) {
26283
28076
  console.warn(`[paused-tasks] holding task ${task.id}: profile "${profile.name}" has an unreadable credential allowlist`);
@@ -26287,6 +28080,7 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
26287
28080
  ...task,
26288
28081
  attachments: await getTaskAttachments2(task.id),
26289
28082
  ...requestedBy && { requestedBy },
28083
+ ...threadParticipants && { threadParticipants },
26290
28084
  ...profile?.credentials && { credentialAllowlist: profile.credentials }
26291
28085
  };
26292
28086
  }));
@@ -26452,6 +28246,23 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
26452
28246
  jsonError(res, `Task status is '${task.status}', not 'in_progress'`, 400);
26453
28247
  return true;
26454
28248
  }
28249
+ let fallback;
28250
+ if (parsed.body.reason === "provider_fallback" && parsed.body.errorClass) {
28251
+ const pick = task.workflowRunStepId == null ? await nextFallback2(task, parsed.body.errorClass, {
28252
+ includeRepoSecrets: readsRepoSecrets(getRequestAuth(req), task.agentId ? await getAgentById2(task.agentId) : null)
28253
+ }) : { kind: "none", message: null };
28254
+ if (pick.kind === "none") {
28255
+ supersedeTaskRoute.respond(res, 200, {
28256
+ success: true,
28257
+ kind: "noFallback",
28258
+ task,
28259
+ resumeTaskId: null,
28260
+ failureReason: pick.message
28261
+ });
28262
+ return true;
28263
+ }
28264
+ fallback = { profile: pick.profile, hop: pick.hop };
28265
+ }
26455
28266
  if (task.workflowRunStepId != null) {
26456
28267
  const failed = await failTask2(parsed.params.id, SUPERSEDED_WORKFLOW_TASK_REASON);
26457
28268
  if (task.agentId) {
@@ -26495,7 +28306,8 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
26495
28306
  }
26496
28307
  const followUp = await createResumeFollowUp2({
26497
28308
  parentId: parsed.params.id,
26498
- reason: parsed.body.reason
28309
+ reason: parsed.body.reason,
28310
+ fallback
26499
28311
  });
26500
28312
  if (followUp.kind !== "created") {
26501
28313
  await settleSupersededTaskDependents2(parsed.params.id, null);
@@ -29957,7 +31769,8 @@ var PollTaskOfferedTriggerSchema = object2({
29957
31769
  type: literal2("task_offered"),
29958
31770
  taskId: string2(),
29959
31771
  task: AgentTaskSchema,
29960
- requestedBy: TaskRequestedBySchema.optional()
31772
+ requestedBy: TaskRequestedBySchema.optional(),
31773
+ threadParticipants: TaskThreadParticipantsSchema.optional()
29961
31774
  });
29962
31775
  var PollTaskAssignedTriggerSchema = object2({
29963
31776
  type: literal2("task_assigned"),
@@ -29967,7 +31780,8 @@ var PollTaskAssignedTriggerSchema = object2({
29967
31780
  attachments: array2(PollTriggerAttachmentSchema),
29968
31781
  credentialAllowlist: ModelProfileCredentialsSchema.optional()
29969
31782
  }),
29970
- requestedBy: TaskRequestedBySchema.optional()
31783
+ requestedBy: TaskRequestedBySchema.optional(),
31784
+ threadParticipants: TaskThreadParticipantsSchema.optional()
29971
31785
  });
29972
31786
  var PollUnreadMentionsTriggerSchema = object2({
29973
31787
  type: literal2("unread_mentions"),
@@ -30128,12 +31942,14 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
30128
31942
  if (claimedTask) {
30129
31943
  await recordRuntimeTask(claimedTask.id);
30130
31944
  const offeredRequestedBy = await buildTaskRequestedBy(claimedTask);
31945
+ const offeredThread = await buildTaskThreadParticipants(claimedTask);
30131
31946
  return {
30132
31947
  trigger: {
30133
31948
  type: "task_offered",
30134
31949
  taskId: claimedTask.id,
30135
31950
  task: claimedTask,
30136
- ...offeredRequestedBy && { requestedBy: offeredRequestedBy }
31951
+ ...offeredRequestedBy && { requestedBy: offeredRequestedBy },
31952
+ ...offeredThread && { threadParticipants: offeredThread }
30137
31953
  }
30138
31954
  };
30139
31955
  }
@@ -30208,6 +32024,7 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
30208
32024
  });
30209
32025
  });
30210
32026
  const assignedRequestedBy = await buildTaskRequestedBy(pendingTask);
32027
+ const assignedThread = await buildTaskThreadParticipants(pendingTask);
30211
32028
  const assignedTriggerSurface = await resolveTriggerSurface(pendingTask.id, pendingTask.source);
30212
32029
  return {
30213
32030
  trigger: {
@@ -30220,7 +32037,8 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
30220
32037
  status: "in_progress",
30221
32038
  attachments: await attachmentsForTrigger(pendingTask.id)
30222
32039
  },
30223
- ...assignedRequestedBy && { requestedBy: assignedRequestedBy }
32040
+ ...assignedRequestedBy && { requestedBy: assignedRequestedBy },
32041
+ ...assignedThread && { threadParticipants: assignedThread }
30224
32042
  }
30225
32043
  };
30226
32044
  }
@@ -30247,7 +32065,8 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
30247
32065
  return cached;
30248
32066
  const result = await checkProfileForAgent(myAgentId, profile, {
30249
32067
  vcsRepo,
30250
- includeRepoSecrets
32068
+ includeRepoSecrets,
32069
+ fallbacks: false
30251
32070
  });
30252
32071
  const ok = result?.ok !== false;
30253
32072
  profileOk.set(memoKey, ok);
@@ -30313,6 +32132,7 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
30313
32132
  });
30314
32133
  });
30315
32134
  const claimedRequestedBy = await buildTaskRequestedBy(claimed);
32135
+ const claimedThread = await buildTaskThreadParticipants(claimed);
30316
32136
  const claimedTriggerSurface = await resolveTriggerSurface(claimed.id, claimed.source);
30317
32137
  return {
30318
32138
  trigger: {
@@ -30324,7 +32144,8 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
30324
32144
  ...await claimModelFields(claimed, agent, getRequestAuth(req)),
30325
32145
  attachments: await attachmentsForTrigger(claimed.id)
30326
32146
  },
30327
- ...claimedRequestedBy && { requestedBy: claimedRequestedBy }
32147
+ ...claimedRequestedBy && { requestedBy: claimedRequestedBy },
32148
+ ...claimedThread && { threadParticipants: claimedThread }
30328
32149
  }
30329
32150
  };
30330
32151
  }
@@ -32287,6 +34108,1849 @@ async function handleRuntimePools(req, res, pathSegments, queryParams, agentId)
32287
34108
  return true;
32288
34109
  }
32289
34110
 
34111
+ // src/http/savings.ts
34112
+ init_zod();
34113
+ init_db4();
34114
+
34115
+ // src/be/savings/read.ts
34116
+ init_db4();
34117
+ var DAY_MS3 = 86400000;
34118
+ var MINUTE_MS = 60000;
34119
+ var zeroFacts = () => ({
34120
+ runs: 0,
34121
+ countedRuns: 0,
34122
+ schedRuns: 0,
34123
+ schedEffectRuns: 0,
34124
+ eventRuns: 0,
34125
+ effectRuns: 0,
34126
+ effectOpsSum: 0,
34127
+ opsSum: 0,
34128
+ agentTasks: 0,
34129
+ agentUsd: 0,
34130
+ agentMs: 0,
34131
+ followupUsd: 0,
34132
+ childTaskUsd: 0,
34133
+ childTaskMs: 0,
34134
+ recordedLlmUsd: 0,
34135
+ estimatedLlmUsd: 0,
34136
+ computeSecs: 0
34137
+ });
34138
+ function addFacts(into, row) {
34139
+ for (const c of FACT_COLUMNS)
34140
+ into[c] += Number(row[c]) || 0;
34141
+ }
34142
+ function savingsWindow(days, now) {
34143
+ const startMs = Math.floor(now / MINUTE_MS) * MINUTE_MS - days * DAY_MS3;
34144
+ return {
34145
+ start: new Date(startMs).toISOString(),
34146
+ end: new Date(now).toISOString(),
34147
+ days,
34148
+ firstDay: utcDay(startMs),
34149
+ lastDay: utcDay(now)
34150
+ };
34151
+ }
34152
+ function daysBetween(firstDay, lastDay) {
34153
+ const out = [];
34154
+ for (let t = Date.parse(dayStartIso(firstDay));t <= Date.parse(dayStartIso(lastDay)); t += DAY_MS3) {
34155
+ out.push(utcDay(t));
34156
+ }
34157
+ return out;
34158
+ }
34159
+ var sliceCache = new Map;
34160
+ var SLICE_TTL_MS = 2 * MINUTE_MS;
34161
+ var HOUR_MS = 60 * MINUTE_MS;
34162
+ var FLEET_SLICE_TTL_MS = HOUR_MS + 2 * MINUTE_MS;
34163
+ var FIRST_DAY_SCAN_CONCURRENCY = 2;
34164
+ var scansInFlight = 0;
34165
+ var scanWaiters = [];
34166
+ async function withScanSlot(scan) {
34167
+ if (scansInFlight < FIRST_DAY_SCAN_CONCURRENCY)
34168
+ scansInFlight++;
34169
+ else
34170
+ await new Promise((resolve) => scanWaiters.push(resolve));
34171
+ try {
34172
+ return await scan();
34173
+ } finally {
34174
+ const next = scanWaiters.shift();
34175
+ if (next)
34176
+ next();
34177
+ else
34178
+ scansInFlight--;
34179
+ }
34180
+ }
34181
+ function cachedScan(key, ttl, scan, failed, label) {
34182
+ const hit = sliceCache.get(key);
34183
+ if (hit)
34184
+ return hit.result;
34185
+ const now = Date.now();
34186
+ for (const [k, v] of sliceCache)
34187
+ if (now - v.at > v.ttl)
34188
+ sliceCache.delete(k);
34189
+ const result = withScanSlot(scan).catch((err) => {
34190
+ console.warn(`[savings-read] first-day scan of ${label} failed: ${String(err instanceof Error ? err.message : err).slice(0, 200)}`);
34191
+ if (sliceCache.get(key)?.result === result)
34192
+ sliceCache.delete(key);
34193
+ return failed;
34194
+ });
34195
+ sliceCache.set(key, { at: now, ttl, result });
34196
+ return result;
34197
+ }
34198
+ function scanSlice(workflow, slice, sql, ttl) {
34199
+ return cachedScan(`${workflow.id}|${slice.start}`, ttl, async () => {
34200
+ const out = await computeWorkflowWindow(workflow, slice, sql, { bucket: "minute" });
34201
+ return out.status === "ok" ? { byMinute: out.byDay } : { runs: out.runs };
34202
+ }, { runs: null }, workflow.id);
34203
+ }
34204
+ var COUNT_COLUMNS = new Set([
34205
+ "runs",
34206
+ "countedRuns",
34207
+ "schedRuns",
34208
+ "schedEffectRuns",
34209
+ "eventRuns",
34210
+ "effectRuns",
34211
+ "agentTasks"
34212
+ ]);
34213
+ function scaleBucket(bucket, share) {
34214
+ const out = zeroFacts();
34215
+ for (const c of FACT_COLUMNS) {
34216
+ const v = (Number(bucket[c]) || 0) * share;
34217
+ out[c] = COUNT_COLUMNS.has(c) ? Math.round(v) : v;
34218
+ }
34219
+ return out;
34220
+ }
34221
+ function parseDefinition2(definition) {
34222
+ if (typeof definition !== "string")
34223
+ return definition ?? {};
34224
+ try {
34225
+ return JSON.parse(definition);
34226
+ } catch {
34227
+ return {};
34228
+ }
34229
+ }
34230
+ var byId = (a, b) => a < b ? -1 : a > b ? 1 : 0;
34231
+ var isRetired = (name) => /-retired-\d{4}-\d{2}-\d{2}$/.test(name);
34232
+ var CHUNK_ROWS = 5000;
34233
+ var PRICE_BATCH = 100;
34234
+ var FLEET_CACHE_TTL_MS = 60000;
34235
+ var lastTurn = Promise.resolve();
34236
+ var yieldLoop = () => {
34237
+ lastTurn = lastTurn.then(() => new Promise((resolve) => setImmediate(resolve)));
34238
+ return lastTurn;
34239
+ };
34240
+ async function forEachBucketChunk(columns, where, params, firstDay, lastDay, onRows, oneJob) {
34241
+ const client = getDbClient2();
34242
+ if (oneJob) {
34243
+ await onRows(await client.query(`SELECT ${columns} FROM automation_savings_daily INDEXED BY ${oneJob} WHERE ${where} AND day>=? AND day<=? ORDER BY day`, [...params, firstDay, lastDay]));
34244
+ return;
34245
+ }
34246
+ const counts = await client.query(`SELECT day, count(*) n FROM automation_savings_daily WHERE ${where} AND day>=? AND day<=? GROUP BY day ORDER BY day`, [...params, firstDay, lastDay]);
34247
+ const ends = [];
34248
+ let rows = 0;
34249
+ for (const c of counts) {
34250
+ const n = Number(c.n) || 0;
34251
+ if (ends.length > 0 && rows + n <= CHUNK_ROWS) {
34252
+ ends[ends.length - 1] = c.day;
34253
+ rows += n;
34254
+ } else {
34255
+ ends.push(c.day);
34256
+ rows = n;
34257
+ }
34258
+ }
34259
+ ends[Math.max(0, ends.length - 1)] = lastDay;
34260
+ let from = firstDay;
34261
+ for (const to of ends) {
34262
+ await yieldLoop();
34263
+ await onRows(await client.query(`SELECT ${columns} FROM automation_savings_daily WHERE ${where} AND day>=? AND day<=? ORDER BY day`, [...params, from, to]));
34264
+ from = utcDay(Date.parse(dayStartIso(to)) + DAY_MS3);
34265
+ }
34266
+ }
34267
+ var fleetCache2 = new Map;
34268
+ var fleetLoads = 0;
34269
+ var curveKeys = new WeakMap;
34270
+ function curveKey(curve) {
34271
+ if (!curve)
34272
+ return "shipped";
34273
+ let key = curveKeys.get(curve);
34274
+ if (key === undefined) {
34275
+ key = Bun.hash(JSON.stringify(curve)).toString(36);
34276
+ curveKeys.set(curve, key);
34277
+ }
34278
+ return key;
34279
+ }
34280
+ function cachedFleet(key, fingerprint, load) {
34281
+ const now = Date.now();
34282
+ const hit = fleetCache2.get(key);
34283
+ if (hit && hit.fingerprint === fingerprint && now - hit.at < FLEET_CACHE_TTL_MS) {
34284
+ return hit.value;
34285
+ }
34286
+ for (const [k, e] of fleetCache2)
34287
+ if (now - e.at >= FLEET_CACHE_TTL_MS)
34288
+ fleetCache2.delete(k);
34289
+ fleetLoads++;
34290
+ const value = load();
34291
+ const entry = { fingerprint, at: now, value };
34292
+ fleetCache2.set(key, entry);
34293
+ value.catch(() => {
34294
+ if (fleetCache2.get(key) === entry)
34295
+ fleetCache2.delete(key);
34296
+ });
34297
+ return value;
34298
+ }
34299
+ async function readWorkflowSavings(opts) {
34300
+ const client = getDbClient2();
34301
+ const { firstDay, lastDay, ...window } = savingsWindow(opts.days, opts.now);
34302
+ const calendarDays = daysBetween(firstDay, lastDay);
34303
+ const marker = await client.get("SELECT count(*) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='workflow' AND modelVersion=? AND day>=? AND day<=?", [MODEL_VERSION, firstDay, lastDay]);
34304
+ const complete = Number(marker?.n) >= calendarDays.length;
34305
+ const markerAt = marker?.at ?? null;
34306
+ const scope = {
34307
+ days: opts.days,
34308
+ tier: opts.tier,
34309
+ window,
34310
+ firstDay,
34311
+ lastDay,
34312
+ calendarDays,
34313
+ markerAt,
34314
+ sql: opts.sql,
34315
+ curve: opts.curve
34316
+ };
34317
+ let core;
34318
+ if (opts.workflowId) {
34319
+ const own = await client.get("SELECT jobKey FROM automation_savings_daily WHERE jobKind='workflow' AND jobId=? AND day>=? AND day<=? LIMIT 1", [opts.workflowId, firstDay, lastDay]);
34320
+ if (!own) {
34321
+ return {
34322
+ window,
34323
+ computedAt: markerAt,
34324
+ complete,
34325
+ boundaryEstimated: false,
34326
+ rows: [],
34327
+ total: null,
34328
+ points: []
34329
+ };
34330
+ }
34331
+ core = await priceWorkflowBuckets({
34332
+ ...scope,
34333
+ jobKey: own.jobKey,
34334
+ workflowId: opts.workflowId
34335
+ });
34336
+ } else {
34337
+ core = await cachedFleet(`workflow:${opts.days}:${opts.tier}:${curveKey(opts.curve)}:${window.start}:${lastDay}`, `${savingsRollupGeneration()}:${marker?.n}:${markerAt}`, () => priceWorkflowBuckets(scope));
34338
+ }
34339
+ const band = opts.band ?? (core.rows.length === 1 ? "job" : "fleet");
34340
+ return {
34341
+ window,
34342
+ computedAt: core.computedAt,
34343
+ complete,
34344
+ boundaryEstimated: core.boundaryEstimated,
34345
+ rows: [...core.rows],
34346
+ total: band === "job" ? core.jobTotal : core.fleetTotal,
34347
+ points: [...core.points]
34348
+ };
34349
+ }
34350
+ async function priceWorkflowBuckets(scope) {
34351
+ const keyFilter = scope.jobKey !== undefined ? "AND jobKey=?" : "";
34352
+ let computedAt = scope.markerAt;
34353
+ let boundaryEstimated = false;
34354
+ const jobs = new Map;
34355
+ const fold = async (buckets) => {
34356
+ for (const b of buckets)
34357
+ if (!computedAt || b.computedAt > computedAt)
34358
+ computedAt = b.computedAt;
34359
+ if (buckets.some((b) => b.day === scope.firstDay)) {
34360
+ boundaryEstimated = await clipFirstDay(buckets, scope.window, scope.firstDay, !scope.workflowId, scope.sql);
34361
+ }
34362
+ for (const b of buckets) {
34363
+ if (!(Number(b.runs) > 0))
34364
+ continue;
34365
+ let job = jobs.get(b.jobId);
34366
+ if (!job) {
34367
+ job = {
34368
+ workflowId: b.jobId,
34369
+ jobKey: b.jobKey,
34370
+ name: b.jobName,
34371
+ facts: zeroFacts(),
34372
+ days: []
34373
+ };
34374
+ jobs.set(b.jobId, job);
34375
+ }
34376
+ job.name = b.jobName;
34377
+ addFacts(job.facts, b);
34378
+ job.days.push(b);
34379
+ }
34380
+ };
34381
+ await forEachBucketChunk(`day, jobId, jobKey, jobName, computedAt, ${FACT_COLUMNS.join(", ")}`, `jobKind='workflow' AND subKind='' AND modelVersion=? ${keyFilter}`, [MODEL_VERSION, ...scope.jobKey !== undefined ? [scope.jobKey] : []], scope.firstDay, scope.lastDay, fold, scope.jobKey !== undefined ? "idx_automation_savings_daily_key" : undefined);
34382
+ const allocations = new Map;
34383
+ const byKey = new Map;
34384
+ for (const job of jobs.values()) {
34385
+ if (isEnabledOnlyRouter(job.facts, scope.days))
34386
+ continue;
34387
+ byKey.set(job.jobKey, [...byKey.get(job.jobKey) ?? [], job]);
34388
+ }
34389
+ for (const versions of byKey.values()) {
34390
+ versions.sort((a, b) => Number(isRetired(a.name)) - Number(isRetired(b.name)) || a.name.localeCompare(b.name));
34391
+ const shares = allocateSchedule(versions.map((v) => v.facts), scope.days);
34392
+ versions.forEach((v, i) => {
34393
+ allocations.set(v.workflowId, shares[i]);
34394
+ });
34395
+ }
34396
+ const selected = [...jobs.values()].filter((j) => !scope.workflowId || j.workflowId === scope.workflowId);
34397
+ const rows = [];
34398
+ const jobParts = [];
34399
+ const fleetParts = [];
34400
+ const daily = dayTotals(scope.calendarDays);
34401
+ const pricing = { tier: scope.tier, days: scope.days, curve: scope.curve };
34402
+ for (const [i, job] of selected.entries()) {
34403
+ if (i > 0 && i % PRICE_BATCH === 0)
34404
+ await yieldLoop();
34405
+ const allocation = allocations.get(job.workflowId);
34406
+ const priced = priceWorkflow(job.facts, { ...pricing, band: "job" }, allocation);
34407
+ rows.push({ ...priced, workflowId: job.workflowId, name: job.name });
34408
+ jobParts.push(priced);
34409
+ fleetParts.push(priceWorkflow(job.facts, { ...pricing, band: "fleet" }, allocation));
34410
+ daily.add(splitByDay(job.facts, job.days, pricing, priced));
34411
+ }
34412
+ rows.sort((a, b) => b.savingUsd.p50 - a.savingUsd.p50 || byId(a.workflowId, b.workflowId));
34413
+ return {
34414
+ computedAt,
34415
+ boundaryEstimated,
34416
+ rows,
34417
+ jobTotal: jobParts.length > 0 ? sumTotals(jobParts) : null,
34418
+ fleetTotal: fleetParts.length > 0 ? sumTotals(fleetParts) : null,
34419
+ points: rows.length > 0 ? daily.points : []
34420
+ };
34421
+ }
34422
+ async function clipFirstDay(buckets, window, firstDay, fleet, sql = (q, p) => getDbClient2().query(q, p)) {
34423
+ const startMs = Date.parse(window.start);
34424
+ if (window.start === dayStartIso(firstDay))
34425
+ return false;
34426
+ const sliceStart = fleet ? new Date(Math.floor(startMs / HOUR_MS) * HOUR_MS).toISOString() : window.start;
34427
+ const first = buckets.filter((b) => b.day === firstDay);
34428
+ if (first.length === 0)
34429
+ return false;
34430
+ const ids = [...new Set(first.map((b) => b.jobId))];
34431
+ const defs = await getDbClient2().query(`SELECT id, definition FROM workflows WHERE id IN (${ids.map(() => "?").join(",")})`, ids);
34432
+ const defOf = new Map(defs.map((d) => [d.id, parseDefinition2(d.definition)]));
34433
+ const slice = { start: sliceStart, end: dayStartIso(utcDay(startMs + DAY_MS3)) };
34434
+ const ttl = fleet ? FLEET_SLICE_TTL_MS : SLICE_TTL_MS;
34435
+ const endMs = Date.parse(slice.end);
34436
+ const dayShare = (endMs - startMs) / DAY_MS3;
34437
+ const sliceShare = (endMs - startMs) / (endMs - Date.parse(slice.start));
34438
+ const startMinute = minuteKey(window.start);
34439
+ let estimated = false;
34440
+ const clip = async (b) => {
34441
+ const result = defOf.has(b.jobId) ? await scanSlice({ id: b.jobId, definition: defOf.get(b.jobId) }, slice, sql, ttl) : { runs: null };
34442
+ let facts;
34443
+ if ("byMinute" in result) {
34444
+ facts = zeroFacts();
34445
+ for (const m of result.byMinute)
34446
+ if (m.day >= startMinute)
34447
+ addFacts(facts, m);
34448
+ } else {
34449
+ estimated = true;
34450
+ const share = result.runs !== null && Number(b.runs) > 0 ? Math.min(1, result.runs / Number(b.runs)) * sliceShare : dayShare;
34451
+ facts = scaleBucket(b, share);
34452
+ }
34453
+ for (const c of FACT_COLUMNS)
34454
+ b[c] = facts[c];
34455
+ };
34456
+ const queue = [...first];
34457
+ await Promise.all(Array.from({ length: Math.min(FIRST_DAY_SCAN_CONCURRENCY, queue.length) }, async () => {
34458
+ for (let b = queue.shift();b; b = queue.shift())
34459
+ await clip(b);
34460
+ }));
34461
+ return estimated;
34462
+ }
34463
+ function sumBand(parts) {
34464
+ return {
34465
+ p10: parts.reduce((s, b) => s + b.p10, 0),
34466
+ p50: parts.reduce((s, b) => s + b.p50, 0),
34467
+ p90: parts.reduce((s, b) => s + b.p90, 0)
34468
+ };
34469
+ }
34470
+ function sumTotals(parts) {
34471
+ return {
34472
+ runs: parts.reduce((s, p) => s + p.runs, 0),
34473
+ substitutedRuns: parts.reduce((s, p) => s + p.substitutedRuns, 0),
34474
+ enabledOnlyRuns: parts.reduce((s, p) => s + p.enabledOnlyRuns, 0),
34475
+ measuredUsd: parts.reduce((s, p) => s + p.measuredUsd, 0),
34476
+ estimatedLlmUsd: parts.reduce((s, p) => s + p.estimatedLlmUsd, 0),
34477
+ actualUsd: parts.reduce((s, p) => s + p.actualUsd, 0),
34478
+ agentOnlyUsd: sumBand(parts.map((p) => p.agentOnlyUsd)),
34479
+ savingUsd: sumBand(parts.map((p) => p.savingUsd)),
34480
+ actualHours: parts.reduce((s, p) => s + p.actualHours, 0),
34481
+ hoursSaved: sumBand(parts.map((p) => p.hoursSaved))
34482
+ };
34483
+ }
34484
+ function dayTotals(calendarDays) {
34485
+ const days = calendarDays.map((day) => ({
34486
+ day,
34487
+ savingUsd: 0,
34488
+ actualUsd: 0,
34489
+ measuredUsd: 0,
34490
+ estimatedLlmUsd: 0
34491
+ }));
34492
+ const byDay = new Map(days.map((p) => [p.day, p]));
34493
+ return {
34494
+ points: days,
34495
+ add(points) {
34496
+ for (const p of points) {
34497
+ const d = byDay.get(p.day);
34498
+ if (!d)
34499
+ continue;
34500
+ d.savingUsd += p.savingUsd;
34501
+ d.actualUsd += p.actualUsd;
34502
+ d.measuredUsd += p.measuredUsd;
34503
+ d.estimatedLlmUsd += p.estimatedLlmUsd;
34504
+ }
34505
+ }
34506
+ };
34507
+ }
34508
+ function fillDays(points, calendarDays) {
34509
+ const totals = dayTotals(calendarDays);
34510
+ totals.add(points);
34511
+ return totals.points;
34512
+ }
34513
+ async function isKnownScriptName(name) {
34514
+ if (name === INLINE_SCRIPT_NAME)
34515
+ return true;
34516
+ return !!await getDbClient2().get("SELECT 1 n FROM scripts WHERE name=? LIMIT 1", [
34517
+ name
34518
+ ]);
34519
+ }
34520
+ var zeroScriptFacts = () => ({
34521
+ runs: 0,
34522
+ apiRuns: 0,
34523
+ effectRuns: 0,
34524
+ apiEffectRuns: 0,
34525
+ opsSum: 0,
34526
+ computeSecs: 0
34527
+ });
34528
+ function addScriptBucket(into, b) {
34529
+ const runs = Number(b.runs) || 0;
34530
+ const effect = Number(b.effectRuns) || 0;
34531
+ into.runs += runs;
34532
+ into.opsSum += Number(b.opsSum) || 0;
34533
+ into.computeSecs += Number(b.computeSecs) || 0;
34534
+ if (b.subKind === "api") {
34535
+ into.apiRuns += runs;
34536
+ into.apiEffectRuns += effect;
34537
+ } else {
34538
+ into.effectRuns += effect;
34539
+ }
34540
+ }
34541
+ async function readScriptSavings(opts) {
34542
+ const client = getDbClient2();
34543
+ const { firstDay, lastDay, ...window } = savingsWindow(opts.days, opts.now);
34544
+ const calendarDays = daysBetween(firstDay, lastDay);
34545
+ const [marker, scheduledRows] = await Promise.all([
34546
+ client.get("SELECT count(*) n, max(computedAt) at FROM automation_savings_days WHERE jobKind='script' AND modelVersion=? AND day>=? AND day<=?", [MODEL_VERSION, firstDay, lastDay]),
34547
+ client.query("SELECT DISTINCT scriptName FROM scheduled_tasks WHERE targetType='script' AND scriptName IS NOT NULL ORDER BY scriptName")
34548
+ ]);
34549
+ const complete = Number(marker?.n) >= calendarDays.length;
34550
+ const scheduled = scheduledRows.map((r) => r.scriptName);
34551
+ const scope = {
34552
+ days: opts.days,
34553
+ tier: opts.tier,
34554
+ window,
34555
+ firstDay,
34556
+ lastDay,
34557
+ calendarDays,
34558
+ markerAt: marker?.at ?? null,
34559
+ scheduled: new Set(scheduled),
34560
+ scriptName: opts.scriptName,
34561
+ sql: opts.sql,
34562
+ curve: opts.curve
34563
+ };
34564
+ const core = opts.scriptName !== undefined ? await priceScriptBuckets(scope) : await cachedFleet(`script:${opts.days}:${opts.tier}:${curveKey(opts.curve)}:${window.start}:${lastDay}`, `${savingsRollupGeneration()}:${marker?.n}:${scope.markerAt}:${JSON.stringify(scheduled)}`, () => priceScriptBuckets(scope));
34565
+ const band = opts.band ?? (core.rows.length === 1 ? "job" : "fleet");
34566
+ return {
34567
+ window,
34568
+ computedAt: core.computedAt,
34569
+ complete,
34570
+ boundaryEstimated: core.boundaryEstimated,
34571
+ rows: [...core.rows],
34572
+ total: band === "job" ? core.jobTotal : core.fleetTotal,
34573
+ points: [...core.points]
34574
+ };
34575
+ }
34576
+ async function priceScriptBuckets(scope) {
34577
+ const byName = scope.scriptName !== undefined;
34578
+ let computedAt = scope.markerAt;
34579
+ const jobs = new Map;
34580
+ await forEachBucketChunk("day, jobId, subKind, computedAt, runs, effectRuns, opsSum, computeSecs", `jobKind='script' AND modelVersion=? ${byName ? "AND jobId=?" : ""}`, [MODEL_VERSION, ...byName ? [scope.scriptName] : []], scope.firstDay, scope.lastDay, (buckets) => {
34581
+ for (const b of buckets) {
34582
+ if (!computedAt || b.computedAt > computedAt)
34583
+ computedAt = b.computedAt;
34584
+ let job = jobs.get(b.jobId);
34585
+ if (!job) {
34586
+ job = { facts: zeroScriptFacts(), days: new Map };
34587
+ jobs.set(b.jobId, job);
34588
+ }
34589
+ addScriptBucket(job.facts, b);
34590
+ const day = job.days.get(b.day) ?? zeroScriptFacts();
34591
+ addScriptBucket(day, b);
34592
+ job.days.set(b.day, day);
34593
+ }
34594
+ }, byName ? "idx_automation_savings_daily_job" : undefined);
34595
+ const boundaryEstimated = await clipScriptFirstDay(jobs, scope.window, scope.firstDay, scope);
34596
+ const rows = [];
34597
+ const jobParts = [];
34598
+ const fleetParts = [];
34599
+ const daily = dayTotals(scope.calendarDays);
34600
+ let i = 0;
34601
+ for (const [scriptName, job] of jobs) {
34602
+ if (i > 0 && i % PRICE_BATCH === 0)
34603
+ await yieldLoop();
34604
+ i++;
34605
+ const kind = scope.scheduled.has(scriptName) ? "script-scheduled" : "script-agent-invoked";
34606
+ const pricing = { tier: scope.tier, days: scope.days, kind, curve: scope.curve };
34607
+ const priced = priceScript(job.facts, { ...pricing, band: "job" });
34608
+ rows.push({ ...priced, kind, scriptName, name: scriptName });
34609
+ jobParts.push(priced);
34610
+ fleetParts.push(priceScript(job.facts, { ...pricing, band: "fleet" }));
34611
+ daily.add(splitScriptByDay(job.facts, [...job.days].map(([day, f]) => ({ ...f, day })), priced));
34612
+ }
34613
+ rows.sort((a, b) => b.savingUsd.p50 - a.savingUsd.p50 || byId(a.scriptName, b.scriptName));
34614
+ return {
34615
+ computedAt,
34616
+ boundaryEstimated,
34617
+ rows,
34618
+ jobTotal: jobParts.length > 0 ? sumTotals(jobParts) : null,
34619
+ fleetTotal: fleetParts.length > 0 ? sumTotals(fleetParts) : null,
34620
+ points: rows.length > 0 ? daily.points : []
34621
+ };
34622
+ }
34623
+ var MAX_COMPONENT_DEPTH = 10;
34624
+ var scaleBand = (b, f) => ({
34625
+ p10: b.p10 * f,
34626
+ p50: b.p50 * f,
34627
+ p90: b.p90 * f
34628
+ });
34629
+ function scaleRow(row, f) {
34630
+ return {
34631
+ ...row,
34632
+ runs: row.runs * f,
34633
+ substitutedRuns: row.substitutedRuns * f,
34634
+ enabledOnlyRuns: row.enabledOnlyRuns * f,
34635
+ effectRuns: row.effectRuns * f,
34636
+ measuredUsd: row.measuredUsd * f,
34637
+ estimatedLlmUsd: row.estimatedLlmUsd * f,
34638
+ actualUsd: row.actualUsd * f,
34639
+ agentOnlyUsd: scaleBand(row.agentOnlyUsd, f),
34640
+ savingUsd: scaleBand(row.savingUsd, f),
34641
+ actualHours: row.actualHours * f,
34642
+ agentOnlyHours: scaleBand(row.agentOnlyHours, f),
34643
+ hoursSaved: scaleBand(row.hoursSaved, f)
34644
+ };
34645
+ }
34646
+ var zeroBand = () => ({ p10: 0, p50: 0, p90: 0 });
34647
+ var addBand = (a, b) => ({
34648
+ p10: a.p10 + b.p10,
34649
+ p50: a.p50 + b.p50,
34650
+ p90: a.p90 + b.p90
34651
+ });
34652
+ async function readWorkflowComponents(opts) {
34653
+ const { firstDay, lastDay, start } = savingsWindow(opts.days, opts.now);
34654
+ const firstDayShare = (Date.parse(dayStartIso(utcDay(Date.parse(start) + DAY_MS3))) - Date.parse(start)) / DAY_MS3;
34655
+ const [workflows, scripts, links] = await Promise.all([
34656
+ readWorkflowSavings({ days: opts.days, tier: opts.tier, now: opts.now, curve: opts.curve }),
34657
+ readScriptSavings({ days: opts.days, tier: opts.tier, now: opts.now, curve: opts.curve }),
34658
+ getDbClient2().query(`SELECT parentJobId, childKind, childJobId, linkKind,
34659
+ sum(CASE WHEN day=? THEN n*? ELSE n END) n,
34660
+ sum(CASE WHEN day=? THEN actualUsd*? ELSE actualUsd END) usd
34661
+ FROM automation_savings_links WHERE modelVersion=? AND day>=? AND day<=?
34662
+ GROUP BY 1,2,3,4 ORDER BY 1,2,3,4`, [firstDay, firstDayShare, firstDay, firstDayShare, MODEL_VERSION, firstDay, lastDay])
34663
+ ]);
34664
+ const workflowRows = new Map(workflows.rows.map((r) => [r.workflowId, r]));
34665
+ workflowRows.set(opts.workflowId, opts.own);
34666
+ const scriptRows = new Map(scripts.rows.map((r) => [r.scriptName, r]));
34667
+ const children = new Map;
34668
+ for (const l of links)
34669
+ children.set(l.parentJobId, [...children.get(l.parentJobId) ?? [], l]);
34670
+ const components = new Map;
34671
+ const parts = [];
34672
+ const addComponent = (c, priced, taskUsd = 0) => {
34673
+ const key = `${c.kind}\x00${c.workflowId ?? c.scriptName ?? c.linkKind}`;
34674
+ const prev = components.get(key);
34675
+ components.set(key, {
34676
+ ...c,
34677
+ linkKind: prev && prev.depth <= c.depth ? prev.linkKind : c.linkKind,
34678
+ depth: Math.min(prev?.depth ?? c.depth, c.depth),
34679
+ runs: (prev?.runs ?? 0) + c.runs,
34680
+ actualUsd: (prev?.actualUsd ?? 0) + (priced?.actualUsd ?? taskUsd),
34681
+ agentOnlyUsd: addBand(prev?.agentOnlyUsd ?? zeroBand(), priced?.agentOnlyUsd ?? zeroBand()),
34682
+ savingUsd: addBand(prev?.savingUsd ?? zeroBand(), priced?.savingUsd ?? zeroBand()),
34683
+ hoursSaved: addBand(prev?.hoursSaved ?? zeroBand(), priced?.hoursSaved ?? zeroBand())
34684
+ });
34685
+ if (priced)
34686
+ parts.push(priced);
34687
+ };
34688
+ const walk = (parent, share, depth, path) => {
34689
+ for (const l of children.get(parent) ?? []) {
34690
+ const linked = Number(l.n) * share;
34691
+ if (l.childKind === "task") {
34692
+ if (depth === 1 && linked > 0) {
34693
+ addComponent({
34694
+ kind: "task",
34695
+ name: l.linkKind === "step-task" ? "Tasks its script steps created" : "Tasks below its agent tasks",
34696
+ linkKind: l.linkKind,
34697
+ depth,
34698
+ runs: linked,
34699
+ inOwnRow: true
34700
+ }, null, Number(l.usd) * share);
34701
+ }
34702
+ continue;
34703
+ }
34704
+ if (linked <= 0 || l.childKind === "workflow" && path.has(l.childJobId))
34705
+ continue;
34706
+ const row = l.childKind === "workflow" ? workflowRows.get(l.childJobId) : scriptRows.get(l.childJobId);
34707
+ const f = row && row.runs > 0 ? linked / row.runs : 0;
34708
+ addComponent({
34709
+ kind: l.childKind,
34710
+ ...l.childKind === "workflow" ? { workflowId: l.childJobId } : { scriptName: l.childJobId },
34711
+ name: row?.name ?? l.childJobId,
34712
+ linkKind: l.linkKind,
34713
+ depth,
34714
+ runs: linked,
34715
+ inOwnRow: false
34716
+ }, row ? scaleRow(row, f) : null);
34717
+ if (l.childKind === "workflow" && f > 0 && depth < MAX_COMPONENT_DEPTH) {
34718
+ walk(l.childJobId, Math.min(1, f), depth + 1, new Set([...path, l.childJobId]));
34719
+ }
34720
+ }
34721
+ };
34722
+ walk(opts.workflowId, 1, 1, new Set([opts.workflowId]));
34723
+ const list = [...components.values()].sort((a, b) => Number(a.inOwnRow) - Number(b.inOwnRow) || a.depth - b.depth || b.savingUsd.p50 - a.savingUsd.p50);
34724
+ return { components: list, withComponents: sumTotals([opts.own, ...parts]) };
34725
+ }
34726
+ function kindTotals(rows) {
34727
+ return {
34728
+ jobs: rows.length,
34729
+ runs: rows.reduce((s, r) => s + r.runs, 0),
34730
+ substitutedRuns: rows.reduce((s, r) => s + r.substitutedRuns, 0),
34731
+ savingUsd: rows.reduce((s, r) => s + r.savingUsd.p50, 0),
34732
+ hoursSaved: rows.reduce((s, r) => s + r.hoursSaved.p50, 0)
34733
+ };
34734
+ }
34735
+ function addTotals(a, b) {
34736
+ const band = (x, y) => sumBand([x, y]);
34737
+ return {
34738
+ runs: a.runs + b.runs,
34739
+ substitutedRuns: a.substitutedRuns + b.substitutedRuns,
34740
+ enabledOnlyRuns: a.enabledOnlyRuns + b.enabledOnlyRuns,
34741
+ measuredUsd: a.measuredUsd + b.measuredUsd,
34742
+ estimatedLlmUsd: a.estimatedLlmUsd + b.estimatedLlmUsd,
34743
+ actualUsd: a.actualUsd + b.actualUsd,
34744
+ agentOnlyUsd: band(a.agentOnlyUsd, b.agentOnlyUsd),
34745
+ savingUsd: band(a.savingUsd, b.savingUsd),
34746
+ actualHours: a.actualHours + b.actualHours,
34747
+ hoursSaved: band(a.hoursSaved, b.hoursSaved)
34748
+ };
34749
+ }
34750
+ async function readFleetSavings(opts) {
34751
+ const [wf, sc] = await Promise.all([
34752
+ readWorkflowSavings({ ...opts, band: "fleet" }),
34753
+ readScriptSavings({ ...opts, band: "fleet" })
34754
+ ]);
34755
+ const { firstDay, lastDay } = savingsWindow(opts.days, opts.now);
34756
+ const all = [...wf.rows, ...sc.rows];
34757
+ const total = all.length === 1 ? sumTotals(all) : wf.total && sc.total ? addTotals(wf.total, sc.total) : wf.total ?? sc.total;
34758
+ const points = all.length > 0 ? fillDays([...wf.points, ...sc.points], daysBetween(firstDay, lastDay)) : [];
34759
+ const computedAt = wf.computedAt && sc.computedAt ? wf.computedAt > sc.computedAt ? wf.computedAt : sc.computedAt : wf.computedAt ?? sc.computedAt;
34760
+ return {
34761
+ window: wf.window,
34762
+ computedAt,
34763
+ complete: wf.complete && sc.complete,
34764
+ boundaryEstimated: wf.boundaryEstimated || sc.boundaryEstimated,
34765
+ workflows: wf.rows,
34766
+ scripts: sc.rows,
34767
+ total,
34768
+ points,
34769
+ byKind: {
34770
+ workflows: kindTotals(wf.rows),
34771
+ scheduledScripts: kindTotals(sc.rows.filter((r) => r.kind === "script-scheduled")),
34772
+ agentInvokedScripts: kindTotals(sc.rows.filter((r) => r.kind === "script-agent-invoked"))
34773
+ }
34774
+ };
34775
+ }
34776
+ async function readFleetLlmUsd(window) {
34777
+ const row = await getDbClient2().get("SELECT sum(totalCostUsd) usd FROM session_costs WHERE createdAt>=? AND createdAt<=?", [window.start, window.end]);
34778
+ return Number(row?.usd) || 0;
34779
+ }
34780
+ async function readScheduleSavings(opts) {
34781
+ const client = getDbClient2();
34782
+ const schedules = await client.query(`SELECT id, name, enabled, targetType, workflowId, scriptName FROM scheduled_tasks ${opts.scheduleId ? "WHERE id=?" : ""}`, opts.scheduleId ? [opts.scheduleId] : []);
34783
+ if (opts.scheduleId && schedules.length === 0)
34784
+ return null;
34785
+ const single = opts.scheduleId !== undefined;
34786
+ const of = (targetType) => schedules.filter((s) => s.targetType === targetType);
34787
+ const base = {
34788
+ days: opts.days,
34789
+ tier: opts.tier,
34790
+ now: opts.now,
34791
+ sql: opts.sql,
34792
+ curve: opts.curve
34793
+ };
34794
+ const workflowSchedules = of("workflow");
34795
+ const scriptSchedules = of("script");
34796
+ const workflows = workflowSchedules.some((s) => s.workflowId) ? await readWorkflowSavings({
34797
+ ...base,
34798
+ workflowId: single ? workflowSchedules[0]?.workflowId ?? undefined : undefined
34799
+ }) : null;
34800
+ const scripts = scriptSchedules.some((s) => s.scriptName) ? await readScriptSavings({
34801
+ ...base,
34802
+ scriptName: single ? scriptSchedules[0]?.scriptName ?? undefined : undefined
34803
+ }) : null;
34804
+ const workflowRows = new Map(workflows?.rows.map((r) => [r.workflowId, r]));
34805
+ const scriptRows = new Map(scripts?.rows.map((r) => [r.scriptName, r]));
34806
+ const window = savingsWindow(opts.days, opts.now);
34807
+ const measured = of("agent-task").length > 0 ? await readMeasuredSpend(window.start, opts) : null;
34808
+ const rows = [];
34809
+ let targetMissing = false;
34810
+ for (const s of schedules) {
34811
+ const ref = {
34812
+ scheduleId: s.id,
34813
+ scheduleName: s.name,
34814
+ scheduleEnabled: Boolean(s.enabled)
34815
+ };
34816
+ if (s.targetType === "agent-task") {
34817
+ const spend = measured?.get(s.id);
34818
+ if (spend) {
34819
+ rows.push({
34820
+ ...ref,
34821
+ basis: "measured",
34822
+ kind: "agent-task-schedule",
34823
+ name: s.name,
34824
+ runs: spend.runs,
34825
+ actualUsd: spend.usd,
34826
+ actualHours: spend.ms / 3600000
34827
+ });
34828
+ }
34829
+ continue;
34830
+ }
34831
+ const target = s.targetType === "workflow" ? s.workflowId ? workflowRows.get(s.workflowId) : undefined : s.scriptName ? scriptRows.get(s.scriptName) : undefined;
34832
+ if (target)
34833
+ rows.push({ ...target, ...ref, basis: "modelled" });
34834
+ else if (single)
34835
+ targetMissing = !await targetExists(s);
34836
+ }
34837
+ rows.sort((a, b) => Number(b.basis === "modelled") - Number(a.basis === "modelled") || (a.basis === "modelled" && b.basis === "modelled" ? b.savingUsd.p50 - a.savingUsd.p50 : b.basis === "measured" && a.basis === "measured" ? b.actualUsd - a.actualUsd : 0));
34838
+ const reads = [workflows, scripts].filter((r) => r !== null);
34839
+ const newest = reads.map((r) => r.computedAt).filter((t) => t !== null);
34840
+ return {
34841
+ window: { start: window.start, end: window.end, days: window.days },
34842
+ computedAt: newest.sort().at(-1) ?? (measured ? new Date(opts.now).toISOString() : null),
34843
+ complete: reads.every((r) => r.complete),
34844
+ boundaryEstimated: reads.some((r) => r.boundaryEstimated),
34845
+ rows,
34846
+ targetMissing
34847
+ };
34848
+ }
34849
+ async function targetExists(s) {
34850
+ if (s.targetType === "workflow") {
34851
+ return !s.workflowId || !!await getDbClient2().get("SELECT 1 FROM workflows WHERE id=?", [s.workflowId]);
34852
+ }
34853
+ return !s.scriptName || await isKnownScriptName(s.scriptName);
34854
+ }
34855
+ async function readMeasuredSpend(start, opts) {
34856
+ const rows = await getDbClient2().query(`SELECT t.scheduleId, count(DISTINCT t.id) runs, sum(c.totalCostUsd) usd, sum(c.durationMs) ms
34857
+ FROM agent_tasks t LEFT JOIN session_costs c ON c.taskId=t.id
34858
+ WHERE ${opts.scheduleId ? "t.scheduleId=?" : "t.scheduleId IS NOT NULL"} AND t.createdAt>=? AND t.createdAt<=?
34859
+ GROUP BY t.scheduleId`, [...opts.scheduleId ? [opts.scheduleId] : [], start, new Date(opts.now).toISOString()]);
34860
+ return new Map(rows.map((r) => [
34861
+ r.scheduleId,
34862
+ { runs: Number(r.runs), usd: Number(r.usd) || 0, ms: Number(r.ms) || 0 }
34863
+ ]));
34864
+ }
34865
+ async function clipScriptFirstDay(jobs, window, firstDay, opts) {
34866
+ const fleet = opts.scriptName === undefined;
34867
+ const startMs = Date.parse(window.start);
34868
+ if (window.start === dayStartIso(firstDay))
34869
+ return false;
34870
+ const sliceStart = fleet ? new Date(Math.floor(startMs / HOUR_MS) * HOUR_MS).toISOString() : window.start;
34871
+ if (![...jobs.values()].some((j) => j.days.has(firstDay)))
34872
+ return false;
34873
+ const slice = { start: sliceStart, end: dayStartIso(utcDay(startMs + DAY_MS3)) };
34874
+ const sql = opts.sql ?? ((q, p) => getDbClient2().query(q, p));
34875
+ const scope = { scriptName: opts.scriptName };
34876
+ const live = await cachedScan(`script\x00${MODEL_VERSION}\x00${opts.scriptName ?? "*"}\x00${slice.start}`, fleet ? FLEET_SLICE_TTL_MS : SLICE_TTL_MS, async () => {
34877
+ if (await countScriptRuns(slice, sql, scope) > LIVE_MAX_RUNS)
34878
+ return null;
34879
+ return computeScriptWindow(slice, sql, { ...scope, bucket: "minute" });
34880
+ }, null, opts.scriptName ?? "scripts");
34881
+ const startMinute = minuteKey(window.start);
34882
+ const inWindow = new Map;
34883
+ for (const s of live ?? []) {
34884
+ const facts = zeroScriptFacts();
34885
+ for (const m of s.byDay) {
34886
+ if (m.day < startMinute)
34887
+ continue;
34888
+ for (const k of Object.keys(facts))
34889
+ facts[k] += m[k];
34890
+ }
34891
+ inWindow.set(s.scriptName, facts);
34892
+ }
34893
+ const dayShare = (Date.parse(slice.end) - startMs) / DAY_MS3;
34894
+ for (const [name, job] of jobs) {
34895
+ const old = job.days.get(firstDay);
34896
+ if (!old)
34897
+ continue;
34898
+ const clipped = live ? inWindow.get(name) ?? zeroScriptFacts() : scaleScriptFacts(old, dayShare);
34899
+ for (const k of Object.keys(old)) {
34900
+ job.facts[k] += clipped[k] - old[k];
34901
+ }
34902
+ job.days.set(firstDay, clipped);
34903
+ if (!(job.facts.runs > 0))
34904
+ jobs.delete(name);
34905
+ }
34906
+ return live === null;
34907
+ }
34908
+ function minuteKey(iso) {
34909
+ return iso.slice(0, 16);
34910
+ }
34911
+ function scaleScriptFacts(facts, share) {
34912
+ return {
34913
+ runs: Math.round(facts.runs * share),
34914
+ apiRuns: Math.round(facts.apiRuns * share),
34915
+ effectRuns: Math.round(facts.effectRuns * share),
34916
+ apiEffectRuns: Math.round(facts.apiEffectRuns * share),
34917
+ opsSum: facts.opsSum * share,
34918
+ computeSecs: facts.computeSecs * share
34919
+ };
34920
+ }
34921
+
34922
+ // src/http/savings.ts
34923
+ init_db_query();
34924
+ init_db_query_shared();
34925
+ init_route_def();
34926
+ init_utils2();
34927
+ function budgetedSql(budgetMs) {
34928
+ return async (sql, params) => {
34929
+ const result = await executeReadOnlyQueryGated(sql, params, budgetMs(), 1e4);
34930
+ return result.rows.map((row) => Object.fromEntries(result.columns.map((column, i) => [column, row[i]])));
34931
+ };
34932
+ }
34933
+ var boundedSql = budgetedSql(getDbQueryHttpBudgetMs);
34934
+ function waitOutCap(run, attempts, stepMs) {
34935
+ return async (sql, params) => {
34936
+ for (let attempt = 1;; attempt++) {
34937
+ try {
34938
+ return await run(sql, params);
34939
+ } catch (err) {
34940
+ if (!(err instanceof DbQueryConcurrencyCapError) || attempt >= attempts)
34941
+ throw err;
34942
+ await Bun.sleep(Math.min(5000, stepMs * attempt));
34943
+ }
34944
+ }
34945
+ };
34946
+ }
34947
+ var savingsRequestSql = waitOutCap(budgetedSql(getDbQueryHttpBudgetMs), 8, 75);
34948
+ var ROLLUP_QUERY_BUDGET_MS = 60000;
34949
+ var savingsRollupSql = waitOutCap(budgetedSql(() => ROLLUP_QUERY_BUDGET_MS), 20, 250);
34950
+ var SavingsBandSchema = object2({ p10: number2(), p50: number2(), p90: number2() });
34951
+ var SavingsJobRowSchema = object2({
34952
+ kind: _enum2(["workflow", "script-scheduled", "script-agent-invoked"]),
34953
+ workflowId: string2().optional(),
34954
+ scriptName: string2().optional(),
34955
+ name: string2(),
34956
+ basis: literal2("modelled"),
34957
+ scheduleId: string2().optional(),
34958
+ scheduleName: string2().optional(),
34959
+ scheduleEnabled: boolean().optional(),
34960
+ scope: literal2("target-job").optional(),
34961
+ enabledOnlyRule: boolean(),
34962
+ runs: number2().int(),
34963
+ substitutedRuns: number2().int(),
34964
+ effectRuns: number2().int(),
34965
+ enabledOnlyRuns: number2().int(),
34966
+ capApplied: boolean(),
34967
+ opsPerRun: number2(),
34968
+ measuredUsd: number2().describe("Measured spend of every run in the window: agent tasks, their reviews, recorded LLM cost."),
34969
+ estimatedLlmUsd: number2().describe("LLM spend estimated from tokens and output size, not measured. 0 when the runs recorded their LLM cost."),
34970
+ actualUsd: number2().describe("Scaled estimate, not a measurement: `measuredUsd + estimatedLlmUsd` times `substitutedRuns / runs`. The saving subtracts this."),
34971
+ agentOnlyUsd: SavingsBandSchema,
34972
+ savingUsd: SavingsBandSchema,
34973
+ actualHours: number2().describe("Scaled estimate: measured hours times `substitutedRuns / runs`. Always 0 for scripts, which keep no agent active."),
34974
+ agentOnlyHours: SavingsBandSchema,
34975
+ hoursSaved: SavingsBandSchema,
34976
+ agentOnlyUsdPerRun: number2()
34977
+ });
34978
+ var SavingsMeasuredRowSchema = object2({
34979
+ kind: literal2("agent-task-schedule"),
34980
+ scheduleId: string2(),
34981
+ scheduleName: string2(),
34982
+ scheduleEnabled: boolean(),
34983
+ name: string2(),
34984
+ basis: literal2("measured"),
34985
+ runs: number2().int().describe("Agent tasks the schedule created in the window."),
34986
+ actualUsd: number2().describe("Recorded cost of those tasks. A floor: review tasks and follow-ups are not linked to the schedule."),
34987
+ actualHours: number2(),
34988
+ savingUsd: _null()
34989
+ });
34990
+ var SavingsTotalsSchema = object2({
34991
+ runs: number2().int(),
34992
+ substitutedRuns: number2().int(),
34993
+ enabledOnlyRuns: number2().int(),
34994
+ measuredUsd: number2(),
34995
+ estimatedLlmUsd: number2(),
34996
+ actualUsd: number2(),
34997
+ agentOnlyUsd: SavingsBandSchema,
34998
+ savingUsd: SavingsBandSchema,
34999
+ actualHours: number2(),
35000
+ hoursSaved: SavingsBandSchema
35001
+ });
35002
+ var SavingsComponentSchema = object2({
35003
+ kind: _enum2(["workflow", "script", "task"]),
35004
+ workflowId: string2().optional(),
35005
+ scriptName: string2().optional(),
35006
+ name: string2(),
35007
+ linkKind: _enum2([
35008
+ "sub-workflow",
35009
+ "step-workflow",
35010
+ "step-script",
35011
+ "step-task",
35012
+ "descendant-task"
35013
+ ]),
35014
+ depth: number2().int(),
35015
+ runs: number2().describe("Runs (tasks for a task component) in this tree. Fractional below the first level."),
35016
+ actualUsd: number2(),
35017
+ agentOnlyUsd: SavingsBandSchema,
35018
+ savingUsd: SavingsBandSchema,
35019
+ hoursSaved: SavingsBandSchema,
35020
+ inOwnRow: boolean().describe("True for unowned tasks: their spend is already in the workflow's own row, on both sides, and adds nothing to `withComponents`.")
35021
+ });
35022
+ var savingsMeta = {
35023
+ window: object2({ start: string2(), end: string2(), days: number2().int() }),
35024
+ tier: _enum2(SAVINGS_TIERS),
35025
+ calibrationModel: string2(),
35026
+ calibratedAt: string2(),
35027
+ calibrationSource: _enum2(["shipped", "deployment"]),
35028
+ computedAt: string2().nullable(),
35029
+ valid: boolean(),
35030
+ reason: _enum2(["not-computed", "no-runs", "target-missing"]).nullable(),
35031
+ boundaryEstimated: boolean().describe("The window is rolling, so its first UTC day is partial and its runs are scanned live. True when that scan could not run (too many runs, or a busy database) and the day's bucket was scaled to the part inside the window instead.")
35032
+ };
35033
+ var SavingsJobsResponseSchema = object2({
35034
+ ...savingsMeta,
35035
+ rows: array2(union3([SavingsJobRowSchema, SavingsMeasuredRowSchema])),
35036
+ total: SavingsTotalsSchema.nullable(),
35037
+ components: array2(SavingsComponentSchema).optional(),
35038
+ withComponents: SavingsTotalsSchema.nullable().optional()
35039
+ });
35040
+ var SavingsDailyResponseSchema = object2({
35041
+ ...savingsMeta,
35042
+ points: array2(object2({
35043
+ day: string2(),
35044
+ savingUsd: number2(),
35045
+ actualUsd: number2().describe("Scaled estimate: the day's measured and estimated spend times the window's substituted share."),
35046
+ measuredUsd: number2().describe("The day's measured spend, not scaled."),
35047
+ estimatedLlmUsd: number2().describe("The day's LLM spend estimated from tokens and output size, not measured.")
35048
+ }))
35049
+ });
35050
+ var FleetKindTotalsSchema = object2({
35051
+ jobs: number2().int(),
35052
+ runs: number2().int(),
35053
+ substitutedRuns: number2().int(),
35054
+ savingUsd: number2().describe("p50"),
35055
+ hoursSaved: number2().describe("p50")
35056
+ });
35057
+ var SavingsSummaryResponseSchema = object2({
35058
+ ...savingsMeta,
35059
+ total: SavingsTotalsSchema.nullable(),
35060
+ byKind: object2({
35061
+ workflows: FleetKindTotalsSchema,
35062
+ scheduledScripts: FleetKindTotalsSchema,
35063
+ agentInvokedScripts: FleetKindTotalsSchema
35064
+ }).nullable(),
35065
+ fleetLlmUsd: number2().describe("Measured session spend of the whole swarm in the window, as on the usage page."),
35066
+ selfOptimizationRatio: number2().nullable().describe("`(fleetLlmUsd + savingUsd.p50) / fleetLlmUsd`: what the swarm would have spent without its automations, per dollar it spent. Null without spend or without a valid total."),
35067
+ excluded: object2({
35068
+ enabledOnlyRuns: number2().int().describe("Runs that are not substituted: router events and API runs with no effect, polls above the hourly cap, skipped and cancelled runs.")
35069
+ }).nullable(),
35070
+ assumptions: array2(string2())
35071
+ });
35072
+ var windowQuery = {
35073
+ days: _enum2(["7", "30", "90"]).default("30").transform(Number),
35074
+ tier: _enum2(SAVINGS_TIERS).default("smart")
35075
+ };
35076
+ var savingsJobsRoute = route({
35077
+ method: "get",
35078
+ path: "/api/savings/jobs",
35079
+ pattern: ["api", "savings", "jobs"],
35080
+ summary: "Estimated automation savings per workflow or script",
35081
+ description: "What the workflows' or scripts' runs in the window would have cost as agent tasks, minus what they cost, read from the hourly savings rollup. With `workflowId` and `components=true`, also returns the workflow's components (child workflow runs, nested script runs and tasks its runs caused, recursively) priced as on their own rows, and `withComponents`, own runs plus those; lists and schedule reads reject `components=true`. `measuredUsd` is the measured spend and `estimatedLlmUsd` the LLM spend estimated where none was recorded; `actualUsd` is their sum scaled to the substituted share of runs, the estimate the saving subtracts. Modelled at the chosen tier, with an 80% range (p10 to p90). Pass `workflowId` for one workflow, `scriptName` for one script, or `kind=workflow` / `kind=script` for every workflow or script with runs. Scheduled scripts are priced as standalone agent tasks; other scripts as the extra turns they add to the calling agent's session. Scripts record no LLM spend, so their spend fields are 0. Pass `scheduleId` for one schedule, or `kind=schedule` for every schedule: a workflow or script target returns the target's row (`scope: target-job`, with `scheduleId`), because runs carry no schedule link, so schedules of one target show the same row, and `total` is null for schedule reads; an agent-task target returns a measured row (`basis` measured) with the recorded cost of its tasks and `savingUsd: null`. A disabled schedule is priced from its target's runs and flagged by `scheduleEnabled`. `valid` is false until the rollup has computed every day of the window, and when there were no runs.",
35082
+ tags: ["Savings"],
35083
+ query: object2({
35084
+ workflowId: string2().min(1).optional(),
35085
+ scriptName: string2().min(1).optional(),
35086
+ scheduleId: string2().min(1).optional(),
35087
+ kind: _enum2(["workflow", "script", "schedule"]).optional(),
35088
+ components: _enum2(["true", "false"]).default("false").transform((v) => v === "true"),
35089
+ ...windowQuery
35090
+ }),
35091
+ responses: {
35092
+ 200: { description: "Savings rows", schema: SavingsJobsResponseSchema },
35093
+ 400: {
35094
+ description: "Not exactly one of workflowId, scriptName, scheduleId and kind, `components=true` without workflowId, or an unknown days or tier value"
35095
+ },
35096
+ 404: { description: "Workflow, script or schedule not found" }
35097
+ }
35098
+ });
35099
+ var savingsDailyRoute = route({
35100
+ method: "get",
35101
+ path: "/api/savings/daily",
35102
+ pattern: ["api", "savings", "daily"],
35103
+ summary: "Daily automation savings of a workflow, a script or the fleet",
35104
+ description: "The p50 saving, measured spend, estimated LLM spend and scaled actual cost per UTC day of the window, from the hourly savings rollup. With `workflowId` or `scriptName` the points add up to the window figures of `GET /api/savings/jobs` for the same target; with neither they cover every workflow and script and add up to `GET /api/savings/summary`.",
35105
+ tags: ["Savings"],
35106
+ query: object2({
35107
+ workflowId: string2().min(1).optional(),
35108
+ scriptName: string2().min(1).optional(),
35109
+ ...windowQuery
35110
+ }),
35111
+ responses: {
35112
+ 200: { description: "Daily savings points", schema: SavingsDailyResponseSchema },
35113
+ 400: {
35114
+ description: "Both workflowId and scriptName, or an unknown days or tier value"
35115
+ },
35116
+ 404: { description: "Workflow or script not found" }
35117
+ }
35118
+ });
35119
+ var savingsSummaryRoute = route({
35120
+ method: "get",
35121
+ path: "/api/savings/summary",
35122
+ pattern: ["api", "savings", "summary"],
35123
+ summary: "Fleet automation savings",
35124
+ description: "What every workflow and script run in the window would have cost as agent tasks, minus what they cost, from the hourly savings rollup at the chosen tier, with the fleet's 80% range. Adds the swarm's measured session spend over the same window, the self-optimization ratio, the runs left out and the model's assumptions. `valid` is false until the rollup has computed every day of the window, and when there were no runs.",
35125
+ tags: ["Savings"],
35126
+ query: object2(windowQuery),
35127
+ responses: {
35128
+ 200: { description: "Fleet savings", schema: SavingsSummaryResponseSchema },
35129
+ 400: { description: "An unknown days or tier value" }
35130
+ }
35131
+ });
35132
+ var CALIBRATION_TTL_MS = 60 * 1000;
35133
+ var calibrationCache = null;
35134
+ async function activeCalibration(now) {
35135
+ if (calibrationCache && now - calibrationCache.at < CALIBRATION_TTL_MS) {
35136
+ return calibrationCache.value;
35137
+ }
35138
+ const [row] = await getSwarmConfigs2({ scope: "global", key: SAVINGS_CALIBRATION_KEY });
35139
+ const value = parseCalibration(row?.value) ?? SHIPPED_CALIBRATION;
35140
+ calibrationCache = { at: now, value };
35141
+ return value;
35142
+ }
35143
+ function clearCalibrationCache() {
35144
+ calibrationCache = null;
35145
+ }
35146
+ var round2 = (x) => Math.round(x * 100) / 100;
35147
+ var roundBand = (b) => ({
35148
+ p10: round2(b.p10),
35149
+ p50: round2(b.p50),
35150
+ p90: round2(b.p90)
35151
+ });
35152
+ function roundToTotal(values) {
35153
+ const cents = values.map((v) => v * 100);
35154
+ const floors = cents.map(Math.floor);
35155
+ let left = Math.round(cents.reduce((s, c) => s + c, 0)) - floors.reduce((s, c) => s + c, 0);
35156
+ const order = cents.map((c, i) => ({ i, r: c - floors[i] })).sort((a, b) => b.r - a.r);
35157
+ for (const { i } of order) {
35158
+ if (left <= 0)
35159
+ break;
35160
+ floors[i] = floors[i] + 1;
35161
+ left--;
35162
+ }
35163
+ return floors.map((c) => c / 100);
35164
+ }
35165
+ function toRow(row) {
35166
+ return {
35167
+ ..."workflowId" in row ? { kind: "workflow", workflowId: row.workflowId } : { kind: row.kind, scriptName: row.scriptName },
35168
+ name: row.name,
35169
+ basis: "modelled",
35170
+ enabledOnlyRule: row.enabledOnlyRule,
35171
+ runs: row.runs,
35172
+ substitutedRuns: row.substitutedRuns,
35173
+ effectRuns: row.effectRuns,
35174
+ enabledOnlyRuns: row.enabledOnlyRuns,
35175
+ capApplied: row.capApplied,
35176
+ opsPerRun: round2(row.opsPerRun),
35177
+ measuredUsd: round2(row.measuredUsd),
35178
+ estimatedLlmUsd: round2(row.estimatedLlmUsd),
35179
+ actualUsd: round2(row.actualUsd),
35180
+ agentOnlyUsd: roundBand(row.agentOnlyUsd),
35181
+ savingUsd: roundBand(row.savingUsd),
35182
+ actualHours: round2(row.actualHours),
35183
+ agentOnlyHours: roundBand(row.agentOnlyHours),
35184
+ hoursSaved: roundBand(row.hoursSaved),
35185
+ agentOnlyUsdPerRun: round2(row.agentOnlyUsdPerRun)
35186
+ };
35187
+ }
35188
+ function toComponent(c) {
35189
+ return {
35190
+ ...c,
35191
+ runs: round2(c.runs),
35192
+ actualUsd: round2(c.actualUsd),
35193
+ agentOnlyUsd: roundBand(c.agentOnlyUsd),
35194
+ savingUsd: roundBand(c.savingUsd),
35195
+ hoursSaved: roundBand(c.hoursSaved)
35196
+ };
35197
+ }
35198
+ function toScheduleRow(row) {
35199
+ const ref = {
35200
+ scheduleId: row.scheduleId,
35201
+ scheduleName: row.scheduleName,
35202
+ scheduleEnabled: row.scheduleEnabled
35203
+ };
35204
+ if (row.basis === "measured") {
35205
+ return {
35206
+ ...ref,
35207
+ kind: row.kind,
35208
+ name: row.name,
35209
+ basis: row.basis,
35210
+ runs: row.runs,
35211
+ actualUsd: round2(row.actualUsd),
35212
+ actualHours: round2(row.actualHours),
35213
+ savingUsd: null
35214
+ };
35215
+ }
35216
+ return { ...toRow(row), ...ref, scope: "target-job" };
35217
+ }
35218
+ function toTotals(t) {
35219
+ return {
35220
+ ...t,
35221
+ runs: Math.round(t.runs),
35222
+ substitutedRuns: Math.round(t.substitutedRuns),
35223
+ enabledOnlyRuns: Math.round(t.enabledOnlyRuns),
35224
+ measuredUsd: round2(t.measuredUsd),
35225
+ estimatedLlmUsd: round2(t.estimatedLlmUsd),
35226
+ actualUsd: round2(t.actualUsd),
35227
+ agentOnlyUsd: roundBand(t.agentOnlyUsd),
35228
+ savingUsd: roundBand(t.savingUsd),
35229
+ actualHours: round2(t.actualHours),
35230
+ hoursSaved: roundBand(t.hoursSaved)
35231
+ };
35232
+ }
35233
+ function roundKind(k) {
35234
+ return { ...k, savingUsd: round2(k.savingUsd), hoursSaved: round2(k.hoursSaved) };
35235
+ }
35236
+ function notFound2(res, what = "Workflow") {
35237
+ res.writeHead(404, { "Content-Type": "application/json" });
35238
+ res.end(JSON.stringify({ error: `${what} not found` }));
35239
+ return true;
35240
+ }
35241
+ async function readScript(scriptName, days, tier, curve) {
35242
+ if (!await isKnownScriptName(scriptName))
35243
+ return null;
35244
+ return readScriptSavings({
35245
+ days,
35246
+ tier,
35247
+ now: Date.now(),
35248
+ scriptName,
35249
+ sql: savingsRequestSql,
35250
+ curve
35251
+ });
35252
+ }
35253
+ function badTarget(res, message) {
35254
+ json(res, { error: message }, 400);
35255
+ return true;
35256
+ }
35257
+ var REFRESH_TTL_MS = 60000;
35258
+ var inFlight3 = new Map;
35259
+ var scannedAt = new Map;
35260
+ var heldTrees = new Map;
35261
+ var MAX_HELD_TREES = 200;
35262
+ function componentsOf(own, days, tier, computedAt, calibration) {
35263
+ const now = Date.now();
35264
+ for (const [k, h] of heldTrees)
35265
+ if (now - h.at >= REFRESH_TTL_MS)
35266
+ heldTrees.delete(k);
35267
+ const key = [
35268
+ own.workflowId,
35269
+ days,
35270
+ tier,
35271
+ computedAt ?? "",
35272
+ calibration.source,
35273
+ calibration.calibratedAt,
35274
+ calibration.model
35275
+ ].join("\x00");
35276
+ const held = heldTrees.get(key);
35277
+ if (held)
35278
+ return held.tree;
35279
+ const tree = readWorkflowComponents({
35280
+ days,
35281
+ tier,
35282
+ now,
35283
+ workflowId: own.workflowId,
35284
+ own,
35285
+ curve: calibration.curve
35286
+ });
35287
+ tree.catch(() => {
35288
+ if (heldTrees.get(key)?.tree === tree)
35289
+ heldTrees.delete(key);
35290
+ });
35291
+ if (heldTrees.size >= MAX_HELD_TREES) {
35292
+ const oldest = heldTrees.keys().next().value;
35293
+ if (oldest !== undefined)
35294
+ heldTrees.delete(oldest);
35295
+ }
35296
+ heldTrees.set(key, { at: now, tree });
35297
+ return tree;
35298
+ }
35299
+ function refreshToday(workflow, now) {
35300
+ const key = `${workflow.id}:${utcDay(now)}`;
35301
+ const running = inFlight3.get(key);
35302
+ if (running)
35303
+ return running;
35304
+ const at = scannedAt.get(key);
35305
+ if (at !== undefined && now - at < REFRESH_TTL_MS)
35306
+ return Promise.resolve();
35307
+ for (const [k, t] of scannedAt)
35308
+ if (now - t >= REFRESH_TTL_MS)
35309
+ scannedAt.delete(k);
35310
+ const done = refreshWorkflowToday(workflow, savingsRequestSql, now).then((outcome) => {
35311
+ if (outcome !== "skipped")
35312
+ scannedAt.set(key, Date.now());
35313
+ }, (err) => {
35314
+ if (!(err instanceof DbQueryConcurrencyCapError || err instanceof DbQueryTimeoutError))
35315
+ throw err;
35316
+ scannedAt.set(key, Date.now());
35317
+ }).finally(() => inFlight3.delete(key));
35318
+ inFlight3.set(key, done);
35319
+ return done;
35320
+ }
35321
+ async function readOne(workflowId, days, tier, curve) {
35322
+ const workflow = await getWorkflow2(workflowId);
35323
+ if (!workflow)
35324
+ return null;
35325
+ const now = Date.now();
35326
+ await refreshToday(workflow, now);
35327
+ return readWorkflowSavings({ days, tier, now, workflowId, sql: savingsRequestSql, curve });
35328
+ }
35329
+ function meta(read, tier, calibration, valid) {
35330
+ return {
35331
+ window: read.window,
35332
+ tier,
35333
+ calibrationModel: calibration.model,
35334
+ calibratedAt: calibration.calibratedAt,
35335
+ calibrationSource: calibration.source,
35336
+ computedAt: read.computedAt,
35337
+ valid: valid.complete && valid.hasRows,
35338
+ reason: !valid.complete ? "not-computed" : valid.hasRows ? null : valid.targetMissing ? "target-missing" : "no-runs",
35339
+ boundaryEstimated: read.boundaryEstimated
35340
+ };
35341
+ }
35342
+ async function handleSavings(req, res, pathSegments, queryParams) {
35343
+ if (savingsDailyRoute.match(req.method, pathSegments)) {
35344
+ const parsed = await savingsDailyRoute.parse(req, res, pathSegments, queryParams);
35345
+ if (!parsed)
35346
+ return true;
35347
+ const { workflowId, scriptName, days, tier } = parsed.query;
35348
+ if (workflowId && scriptName)
35349
+ return badTarget(res, "Pass workflowId or scriptName, not both");
35350
+ const calibration = await activeCalibration(Date.now());
35351
+ const read = workflowId ? await readOne(workflowId, days, tier, calibration.curve) : scriptName ? await readScript(scriptName, days, tier, calibration.curve) : await readFleetSavings({
35352
+ days,
35353
+ tier,
35354
+ now: Date.now(),
35355
+ sql: savingsRequestSql,
35356
+ curve: calibration.curve
35357
+ });
35358
+ if (!read)
35359
+ return notFound2(res, workflowId ? "Workflow" : "Script");
35360
+ const hasRows = read.total !== null;
35361
+ const points = read.complete && hasRows ? read.points : [];
35362
+ const saving = roundToTotal(points.map((p) => p.savingUsd));
35363
+ const actual = roundToTotal(points.map((p) => p.actualUsd));
35364
+ const measured = roundToTotal(points.map((p) => p.measuredUsd));
35365
+ const estimated = roundToTotal(points.map((p) => p.estimatedLlmUsd));
35366
+ savingsDailyRoute.respond(res, 200, {
35367
+ ...meta(read, tier, calibration, { complete: read.complete, hasRows }),
35368
+ points: points.map((p, i) => ({
35369
+ day: p.day,
35370
+ savingUsd: saving[i],
35371
+ actualUsd: actual[i],
35372
+ measuredUsd: measured[i],
35373
+ estimatedLlmUsd: estimated[i]
35374
+ }))
35375
+ });
35376
+ return true;
35377
+ }
35378
+ if (savingsSummaryRoute.match(req.method, pathSegments)) {
35379
+ const parsed = await savingsSummaryRoute.parse(req, res, pathSegments, queryParams);
35380
+ if (!parsed)
35381
+ return true;
35382
+ const { days, tier } = parsed.query;
35383
+ const now = Date.now();
35384
+ const llm = readFleetLlmUsd(savingsWindow(days, now));
35385
+ llm.catch(() => {});
35386
+ const calibration = await activeCalibration(now);
35387
+ const read = await readFleetSavings({
35388
+ days,
35389
+ tier,
35390
+ now,
35391
+ sql: savingsRequestSql,
35392
+ curve: calibration.curve
35393
+ });
35394
+ const fleetLlmUsd = await llm;
35395
+ const total = read.complete ? read.total : null;
35396
+ savingsSummaryRoute.respond(res, 200, {
35397
+ ...meta(read, tier, calibration, { complete: read.complete, hasRows: read.total !== null }),
35398
+ total: total ? toTotals(total) : null,
35399
+ byKind: total ? {
35400
+ workflows: roundKind(read.byKind.workflows),
35401
+ scheduledScripts: roundKind(read.byKind.scheduledScripts),
35402
+ agentInvokedScripts: roundKind(read.byKind.agentInvokedScripts)
35403
+ } : null,
35404
+ fleetLlmUsd: round2(fleetLlmUsd),
35405
+ selfOptimizationRatio: total && fleetLlmUsd > 0 ? (fleetLlmUsd + total.savingUsd.p50) / fleetLlmUsd : null,
35406
+ excluded: total ? { enabledOnlyRuns: total.enabledOnlyRuns } : null,
35407
+ assumptions: savingsAssumptions(tier)
35408
+ });
35409
+ return true;
35410
+ }
35411
+ if (!savingsJobsRoute.match(req.method, pathSegments))
35412
+ return false;
35413
+ const parsed = await savingsJobsRoute.parse(req, res, pathSegments, queryParams);
35414
+ if (!parsed)
35415
+ return true;
35416
+ const { workflowId, scriptName, scheduleId, kind, days, tier, components } = parsed.query;
35417
+ if ([workflowId, scriptName, scheduleId, kind].filter(Boolean).length !== 1) {
35418
+ return badTarget(res, "Pass one of workflowId, scriptName, scheduleId, kind=workflow, kind=script or kind=schedule");
35419
+ }
35420
+ if (components && !workflowId) {
35421
+ return badTarget(res, "components=true needs workflowId; lists count own runs only");
35422
+ }
35423
+ const calibration = await activeCalibration(Date.now());
35424
+ const now = Date.now();
35425
+ if (scheduleId || kind === "schedule") {
35426
+ const read = await readScheduleSavings({
35427
+ days,
35428
+ tier,
35429
+ now,
35430
+ scheduleId,
35431
+ sql: savingsRequestSql,
35432
+ curve: calibration.curve
35433
+ });
35434
+ if (!read)
35435
+ return notFound2(res, "Schedule");
35436
+ const rows = read.complete ? read.rows : read.rows.filter((r) => r.basis === "measured");
35437
+ savingsJobsRoute.respond(res, 200, {
35438
+ ...meta(read, tier, calibration, {
35439
+ complete: read.complete || rows.length > 0,
35440
+ hasRows: rows.length > 0,
35441
+ targetMissing: read.targetMissing
35442
+ }),
35443
+ rows: rows.map(toScheduleRow),
35444
+ total: null
35445
+ });
35446
+ return true;
35447
+ }
35448
+ const read = workflowId ? await readOne(workflowId, days, tier, calibration.curve) : scriptName ? await readScript(scriptName, days, tier, calibration.curve) : kind === "script" ? await readScriptSavings({
35449
+ days,
35450
+ tier,
35451
+ now,
35452
+ sql: savingsRequestSql,
35453
+ curve: calibration.curve
35454
+ }) : await readWorkflowSavings({
35455
+ days,
35456
+ tier,
35457
+ now,
35458
+ sql: savingsRequestSql,
35459
+ curve: calibration.curve
35460
+ });
35461
+ if (!read)
35462
+ return notFound2(res, scriptName ? "Script" : "Workflow");
35463
+ const show = read.complete;
35464
+ const own = show && workflowId ? read.rows[0] : undefined;
35465
+ const tree = components && own && "workflowId" in own ? await componentsOf(own, days, tier, read.computedAt, calibration) : null;
35466
+ savingsJobsRoute.respond(res, 200, {
35467
+ ...meta(read, tier, calibration, { complete: read.complete, hasRows: read.rows.length > 0 }),
35468
+ rows: show ? read.rows.map(toRow) : [],
35469
+ total: show && read.total ? toTotals(read.total) : null,
35470
+ ...components ? {
35471
+ components: tree ? tree.components.map(toComponent) : [],
35472
+ withComponents: tree?.withComponents ? toTotals(tree.withComponents) : null
35473
+ } : {}
35474
+ });
35475
+ return true;
35476
+ }
35477
+
35478
+ // src/http/savings-calibration.ts
35479
+ init_zod();
35480
+ init_db4();
35481
+ init_db_client();
35482
+
35483
+ // src/be/savings/calibrate.ts
35484
+ var TIER_MODEL2 = {
35485
+ smol: "claude-haiku-5-5",
35486
+ regular: "claude-sonnet-5-5",
35487
+ smart: CALIBRATION_MODEL,
35488
+ ultra: "claude-fable-5-1"
35489
+ };
35490
+ var SPEED_FALLBACK = {
35491
+ smol: 1.54,
35492
+ regular: 1.29,
35493
+ smart: 1,
35494
+ ultra: 1
35495
+ };
35496
+ var TRIM = 0.1;
35497
+ var SMOOTH_HALF_WIDTH = 2;
35498
+ var MIN_SESSIONS_PER_TURN = 5;
35499
+ var MIN_LOW_TURN = 3;
35500
+ var MIN_HIGH_TURN = 20;
35501
+ var MIN_SUPPORTED_TURNS = 15;
35502
+ var MIN_SESSIONS = 300;
35503
+ var MIN_SPEED_SESSIONS = 30;
35504
+ var SANITY_FACTOR = 3;
35505
+ var PAGE = 1000;
35506
+ var MAX_SESSIONS_READ = 200000;
35507
+
35508
+ class CalibrationRefusal extends Error {
35509
+ }
35510
+ function median(values) {
35511
+ const sorted = [...values].sort((a, b) => a - b);
35512
+ return sorted[Math.floor(sorted.length / 2)];
35513
+ }
35514
+ function trimmedMean(values, trim = TRIM) {
35515
+ const sorted = [...values].sort((a, b) => a - b);
35516
+ const cut = Math.floor(sorted.length * trim);
35517
+ const kept = sorted.slice(cut, sorted.length - cut);
35518
+ return kept.reduce((s, v) => s + v, 0) / kept.length;
35519
+ }
35520
+ function smooth(series, half) {
35521
+ return series.map((v, i) => {
35522
+ if (v === undefined)
35523
+ return;
35524
+ const pts = [];
35525
+ for (let j = Math.max(0, i - half);j <= Math.min(series.length - 1, i + half); j++) {
35526
+ const y = series[j];
35527
+ if (y !== undefined)
35528
+ pts.push([j, y]);
35529
+ }
35530
+ const n = pts.length;
35531
+ const mx = pts.reduce((s, p) => s + p[0], 0) / n;
35532
+ const my = pts.reduce((s, p) => s + p[1], 0) / n;
35533
+ const sxx = pts.reduce((s, p) => s + (p[0] - mx) ** 2, 0);
35534
+ if (sxx === 0)
35535
+ return my;
35536
+ const slope = pts.reduce((s, p) => s + (p[0] - mx) * (p[1] - my), 0) / sxx;
35537
+ return my + slope * (i - mx);
35538
+ });
35539
+ }
35540
+ function fillMonotone(series, reference) {
35541
+ const known = series.flatMap((v, i) => v === undefined ? [] : [i]);
35542
+ const first = known[0];
35543
+ const last = known[known.length - 1];
35544
+ const scaled = (i, anchor) => series[anchor] * (reference[i] / reference[anchor]);
35545
+ let floor = 0;
35546
+ return series.map((_, i) => {
35547
+ let v;
35548
+ if (i < first)
35549
+ v = scaled(i, first);
35550
+ else if (i > last)
35551
+ v = scaled(i, last);
35552
+ else {
35553
+ const lo = known.filter((k) => k <= i).at(-1);
35554
+ const hi = known.find((k) => k >= i);
35555
+ const a = series[lo];
35556
+ const b = series[hi];
35557
+ v = lo === hi ? a : a + (b - a) * (i - lo) / (hi - lo);
35558
+ }
35559
+ floor = Math.max(floor, v);
35560
+ return floor;
35561
+ });
35562
+ }
35563
+ function curveOf(sessions, value, reference) {
35564
+ const byTurns = new Map;
35565
+ for (const s of sessions) {
35566
+ if (s.turns < 1 || s.turns > TAU_MAX)
35567
+ continue;
35568
+ const at = byTurns.get(s.turns);
35569
+ if (at)
35570
+ at.push(value(s));
35571
+ else
35572
+ byTurns.set(s.turns, [value(s)]);
35573
+ }
35574
+ const raw = Array.from({ length: TAU_MAX }, (_, i) => {
35575
+ const at = byTurns.get(i + 1);
35576
+ return at && at.length >= MIN_SESSIONS_PER_TURN ? trimmedMean(at) : undefined;
35577
+ });
35578
+ raw[0] = undefined;
35579
+ const supported = raw.flatMap((v, i) => v === undefined ? [] : [i + 1]);
35580
+ const lo = supported[0];
35581
+ const hi = supported[supported.length - 1];
35582
+ if (lo === undefined || hi === undefined || lo > MIN_LOW_TURN || hi < MIN_HIGH_TURN || supported.length < MIN_SUPPORTED_TURNS) {
35583
+ throw new CalibrationRefusal(`turn coverage too thin: ${supported.length} of ${TAU_MAX - 1} turn counts have ${MIN_SESSIONS_PER_TURN}+ sessions` + `${lo === undefined ? "" : ` (turns ${lo}..${hi})`}; need at least ${MIN_SUPPORTED_TURNS}, reaching turn ${MIN_LOW_TURN} or lower and turn ${MIN_HIGH_TURN} or higher`);
35584
+ }
35585
+ const smoothed = smooth(raw.slice(1), SMOOTH_HALF_WIDTH);
35586
+ const filled = fillMonotone(smoothed, reference.slice(1));
35587
+ return [filled[0], ...filled];
35588
+ }
35589
+ var round3 = (x, digits) => Number(x.toFixed(digits));
35590
+ function deriveCurves(input) {
35591
+ const { opus, prices, tierTurns, end } = input;
35592
+ const usable = opus.filter((s) => s.turns >= 1 && s.turns <= TAU_MAX);
35593
+ if (usable.length < MIN_SESSIONS) {
35594
+ throw new CalibrationRefusal(`only ${usable.length} opus sessions of 1..${TAU_MAX} turns in the window; need ${MIN_SESSIONS}`);
35595
+ }
35596
+ const opusTokensCost = (p) => (s) => (s.inputTokens * p.input + s.outputTokens * p.output + s.cacheReadTokens * p.cached_input + s.cacheWriteTokens * p.cache_write_1h) / 1e6;
35597
+ const price = (p) => (s) => opusTokensCost(p)(s) + s.otherUsd;
35598
+ const opusCost = opusTokensCost(prices.smart);
35599
+ const repriceMatch = usable.filter((s) => Math.abs(opusCost(s) - s.costUsd) <= 0.01 * s.costUsd).length / usable.length;
35600
+ const opusHrs = curveOf(usable, (s) => s.durationMs / 3600000, CURVE.smart.hrs);
35601
+ const perTurn = (rows) => median(rows.filter((r) => r.turns >= 3 && r.turns <= TAU_MAX).map((r) => r.durationMs / r.turns));
35602
+ const opusPerTurn = perTurn(usable.map((s) => ({ turns: s.turns, durationMs: s.durationMs })));
35603
+ const speed = Object.fromEntries(SAVINGS_TIERS.map((tier) => {
35604
+ const rows = (tierTurns[tier] ?? []).filter((r) => r.turns >= 3 && r.turns <= TAU_MAX);
35605
+ if (tier === "smart")
35606
+ return [tier, 1];
35607
+ return [
35608
+ tier,
35609
+ rows.length >= MIN_SPEED_SESSIONS ? round3(perTurn(rows) / opusPerTurn, 3) : SPEED_FALLBACK[tier]
35610
+ ];
35611
+ }));
35612
+ const curve = Object.fromEntries(SAVINGS_TIERS.map((tier) => [
35613
+ tier,
35614
+ {
35615
+ usd: curveOf(usable, price(prices[tier]), CURVE[tier].usd).map((v) => round3(v, 4)),
35616
+ hrs: opusHrs.map((v) => round3(v * speed[tier], 5))
35617
+ }
35618
+ ]));
35619
+ return {
35620
+ calibratedAt: end.toISOString().slice(0, 10),
35621
+ model: CALIBRATION_MODEL,
35622
+ curve,
35623
+ sessions: usable.length,
35624
+ usable,
35625
+ speed,
35626
+ repriceMatch
35627
+ };
35628
+ }
35629
+ function compareToShipped(curve, sessionsPerTurn) {
35630
+ return SAVINGS_TIERS.flatMap((tier) => ["usd", "hrs"].map((key) => {
35631
+ const pairs = curve[tier][key].map((v, i) => ({ ratio: v / CURVE[tier][key][i], w: sessionsPerTurn[i] ?? 0 })).slice(1);
35632
+ const dev = pairs.map((p) => Math.abs(p.ratio - 1)).sort((a, b) => a - b);
35633
+ const w = pairs.reduce((s, p) => s + p.w, 0);
35634
+ return {
35635
+ tier,
35636
+ key,
35637
+ median: dev[Math.floor(dev.length / 2)],
35638
+ max: dev[dev.length - 1],
35639
+ over5pct: dev.filter((d) => d > 0.05).length,
35640
+ points: dev.length,
35641
+ weighted: pairs.reduce((s, p) => s + p.w * p.ratio, 0) / w
35642
+ };
35643
+ }));
35644
+ }
35645
+ var num2 = (v) => Number(v) || 0;
35646
+ async function pages(sql, query, params) {
35647
+ const out = [];
35648
+ let after = "";
35649
+ for (;; ) {
35650
+ const rows = await sql(query, [...params, after]);
35651
+ out.push(...rows);
35652
+ if (out.length > MAX_SESSIONS_READ) {
35653
+ throw new CalibrationRefusal(`more than ${MAX_SESSIONS_READ} sessions in the window; use a shorter window (days)`);
35654
+ }
35655
+ if (rows.length < PAGE)
35656
+ return out;
35657
+ after = rows[rows.length - 1].id;
35658
+ }
35659
+ }
35660
+ async function fetchInput(sql, start, end) {
35661
+ const window = [start.toISOString(), end.toISOString()];
35662
+ const opusRows = await pages(sql, `SELECT s.id AS id, s.numTurns AS turns, s.durationMs AS durationMs,
35663
+ json_extract(j.value,'$.inputTokens') AS inputTokens, json_extract(j.value,'$.outputTokens') AS outputTokens,
35664
+ json_extract(j.value,'$.cacheReadTokens') AS cacheReadTokens, json_extract(j.value,'$.cacheWriteTokens') AS cacheWriteTokens,
35665
+ json_extract(j.value,'$.costUsd') AS costUsd, s.totalCostUsd AS totalCostUsd
35666
+ FROM session_costs s, json_each(CASE WHEN json_valid(s.modelBreakdown) THEN s.modelBreakdown ELSE '[]' END) j
35667
+ WHERE s.model = ? AND json_extract(j.value,'$.model') = ? AND s.createdAt >= ? AND s.createdAt < ?
35668
+ AND s.numTurns BETWEEN 1 AND ${TAU_MAX} AND s.id > ? ORDER BY s.id LIMIT ${PAGE}`, [CALIBRATION_MODEL, CALIBRATION_MODEL, ...window]);
35669
+ const opus = opusRows.map((r) => ({
35670
+ turns: num2(r.turns),
35671
+ durationMs: num2(r.durationMs),
35672
+ inputTokens: num2(r.inputTokens),
35673
+ outputTokens: num2(r.outputTokens),
35674
+ cacheReadTokens: num2(r.cacheReadTokens),
35675
+ cacheWriteTokens: num2(r.cacheWriteTokens),
35676
+ costUsd: num2(r.costUsd),
35677
+ otherUsd: Math.max(0, num2(r.totalCostUsd) - num2(r.costUsd))
35678
+ }));
35679
+ const priceRows = await sql(`SELECT model, token_class, price_per_million_usd AS price FROM pricing
35680
+ WHERE provider = 'claude' AND model IN (${SAVINGS_TIERS.map(() => "?").join(",")}) AND effective_from <= ?
35681
+ ORDER BY effective_from`, [...SAVINGS_TIERS.map((t) => TIER_MODEL2[t]), end.getTime()]);
35682
+ const latest = new Map;
35683
+ for (const r of priceRows)
35684
+ latest.set(`${r.model}|${r.token_class}`, num2(r.price));
35685
+ const prices = Object.fromEntries(SAVINGS_TIERS.map((tier) => [
35686
+ tier,
35687
+ Object.fromEntries(["input", "output", "cached_input", "cache_write_1h"].map((cls) => {
35688
+ const p = latest.get(`${TIER_MODEL2[tier]}|${cls}`);
35689
+ if (p === undefined) {
35690
+ throw new CalibrationRefusal(`no ${cls} price for ${TIER_MODEL2[tier]}`);
35691
+ }
35692
+ return [cls, p];
35693
+ }))
35694
+ ]));
35695
+ const tierTurns = {};
35696
+ for (const tier of SAVINGS_TIERS) {
35697
+ if (tier === "smart")
35698
+ continue;
35699
+ const rows = await pages(sql, `SELECT id, numTurns AS turns, durationMs FROM session_costs
35700
+ WHERE model = ? AND createdAt >= ? AND createdAt < ? AND numTurns BETWEEN 3 AND ${TAU_MAX} AND id > ? ORDER BY id LIMIT ${PAGE}`, [TIER_MODEL2[tier], ...window]);
35701
+ tierTurns[tier] = rows.map((r) => ({ turns: num2(r.turns), durationMs: num2(r.durationMs) }));
35702
+ }
35703
+ return { opus, prices, tierTurns, end };
35704
+ }
35705
+ async function calibrate(sql, opts) {
35706
+ const start = new Date(opts.end.getTime() - opts.days * 86400000);
35707
+ const window = { start: start.toISOString(), end: opts.end.toISOString(), days: opts.days };
35708
+ const refused = (refusal) => ({
35709
+ window,
35710
+ sessions: 0,
35711
+ refusal,
35712
+ calibration: null,
35713
+ speed: null,
35714
+ repriceMatch: null,
35715
+ gaps: [],
35716
+ meanRatio: null,
35717
+ applyBlocked: null
35718
+ });
35719
+ let derived;
35720
+ try {
35721
+ derived = deriveCurves(await fetchInput(sql, start, opts.end));
35722
+ } catch (err) {
35723
+ if (err instanceof CalibrationRefusal)
35724
+ return refused(err.message);
35725
+ throw err;
35726
+ }
35727
+ const perTurn = Array.from({ length: TAU_MAX }, () => 0);
35728
+ for (const s of derived.usable)
35729
+ perTurn[s.turns - 1] = perTurn[s.turns - 1] + 1;
35730
+ const mean = (a) => a.reduce((s, v) => s + v, 0) / a.length;
35731
+ const meanRatio = mean(derived.curve.smart.usd) / mean(CURVE.smart.usd);
35732
+ return {
35733
+ window,
35734
+ sessions: derived.sessions,
35735
+ refusal: null,
35736
+ calibration: {
35737
+ calibratedAt: derived.calibratedAt,
35738
+ model: derived.model,
35739
+ curve: derived.curve,
35740
+ window: { start: window.start, end: window.end, sessions: derived.sessions }
35741
+ },
35742
+ speed: derived.speed,
35743
+ repriceMatch: derived.repriceMatch,
35744
+ gaps: compareToShipped(derived.curve, perTurn),
35745
+ meanRatio,
35746
+ applyBlocked: meanRatio > SANITY_FACTOR || meanRatio < 1 / SANITY_FACTOR ? `derived smart curve is ${meanRatio.toFixed(2)}x the shipped one (limit ${SANITY_FACTOR}x)` : null
35747
+ };
35748
+ }
35749
+
35750
+ // src/http/savings-calibration.ts
35751
+ init_db_query_shared();
35752
+ init_route_def();
35753
+ init_utils2();
35754
+ var DEADLINE_MS = 120000;
35755
+ var deadlineMs = DEADLINE_MS;
35756
+ var running2 = false;
35757
+ class DeadlineError extends Error {
35758
+ }
35759
+ var plain = (c) => Object.fromEntries(SAVINGS_TIERS.map((t) => [t, { usd: [...c[t].usd], hrs: [...c[t].hrs] }]));
35760
+ function deadlineSql(deadlineAt) {
35761
+ return async (sql, params) => {
35762
+ for (let attempt = 0;; attempt++) {
35763
+ const left = deadlineAt - Date.now();
35764
+ if (left <= 0)
35765
+ throw new DeadlineError;
35766
+ let timer;
35767
+ const query = boundedSql(sql, params);
35768
+ query.catch(() => {});
35769
+ try {
35770
+ return await Promise.race([
35771
+ query,
35772
+ new Promise((_, reject) => {
35773
+ timer = setTimeout(() => reject(new DeadlineError), left);
35774
+ })
35775
+ ]);
35776
+ } catch (err) {
35777
+ if (!(err instanceof DbQueryConcurrencyCapError))
35778
+ throw err;
35779
+ const nap = Math.min(250 * 2 ** attempt, 2000, Math.max(0, deadlineAt - Date.now()));
35780
+ await new Promise((r) => setTimeout(r, nap));
35781
+ } finally {
35782
+ clearTimeout(timer);
35783
+ }
35784
+ }
35785
+ };
35786
+ }
35787
+ var TierCurvesSchema = object2({ usd: array2(number2()), hrs: array2(number2()) });
35788
+ var CurveSetSchema = object2(Object.fromEntries(SAVINGS_TIERS.map((t) => [t, TierCurvesSchema])));
35789
+ var WindowSchema = object2({ start: string2(), end: string2(), sessions: number2().int() });
35790
+ var StoredSchema = object2({
35791
+ calibratedAt: string2(),
35792
+ model: string2(),
35793
+ curve: CurveSetSchema,
35794
+ window: WindowSchema.optional()
35795
+ });
35796
+ var GapSchema = object2({
35797
+ tier: _enum2(SAVINGS_TIERS),
35798
+ key: _enum2(["usd", "hrs"]),
35799
+ median: number2().describe("Median absolute deviation from the shipped curve, as a fraction."),
35800
+ max: number2(),
35801
+ over5pct: number2().int().describe("Turn counts more than 5% from the shipped curve."),
35802
+ points: number2().int(),
35803
+ weighted: number2().describe("Session-weighted mean of derived over shipped; 1 means the same price.")
35804
+ });
35805
+ var getRoute2 = route({
35806
+ method: "get",
35807
+ path: "/api/savings/calibration",
35808
+ pattern: ["api", "savings", "calibration"],
35809
+ summary: "The savings curve in use",
35810
+ description: "Which curve prices the savings endpoints: the one shipped with the release, or one derived from this deployment's sessions and stored by `POST /api/savings/calibration`. Reports the stored row's metadata (a malformed row is reported as invalid and ignored by the savings endpoints).",
35811
+ tags: ["Savings"],
35812
+ responses: {
35813
+ 200: {
35814
+ description: "The active calibration",
35815
+ schema: object2({
35816
+ source: _enum2(["shipped", "deployment"]),
35817
+ active: StoredSchema.omit({ window: true }),
35818
+ stored: object2({
35819
+ valid: boolean(),
35820
+ updatedAt: string2(),
35821
+ calibratedAt: string2().optional(),
35822
+ model: string2().optional(),
35823
+ window: WindowSchema.optional()
35824
+ }).nullable()
35825
+ })
35826
+ }
35827
+ }
35828
+ });
35829
+ var postRoute = route({
35830
+ method: "post",
35831
+ path: "/api/savings/calibration",
35832
+ pattern: ["api", "savings", "calibration"],
35833
+ summary: "Derive the savings curve from this deployment's sessions",
35834
+ description: "Reads the window's opus sessions through the bounded query executor, derives the per-tier cost and hours curve, and compares it to the shipped one. Read-only unless `apply` is true, which also requires `config.write.any`: then the curve is stored in the global `SAVINGS_CURVE_CALIBRATION` config row and the savings endpoints use it within seconds. Nothing is stored when the data cannot support a curve or the derived mean cost is more than 3x or less than a third of the shipped one. One run at a time; a run past 120 s is abandoned with 504.",
35835
+ tags: ["Savings"],
35836
+ body: object2({
35837
+ days: number2().int().min(1).max(90).default(30),
35838
+ end: exports_iso.datetime().optional().describe("End of the window (ISO 8601); default now."),
35839
+ apply: boolean().default(false)
35840
+ }),
35841
+ responses: {
35842
+ 200: {
35843
+ description: "The derived curve, or why there is none",
35844
+ schema: object2({
35845
+ window: object2({ start: string2(), end: string2(), days: number2().int() }),
35846
+ sessions: number2().int().describe("Opus sessions of 1 to 61 turns used."),
35847
+ refusals: array2(string2()).describe("Why no curve was derived, or why a derived one was not applied."),
35848
+ calibration: StoredSchema.nullable().describe("The derived curve; null when refused."),
35849
+ speed: record2(string2(), number2()).nullable(),
35850
+ repriceMatch: number2().nullable(),
35851
+ meanRatio: number2().nullable().describe("Derived smart-tier mean cost over the shipped one."),
35852
+ gaps: array2(GapSchema),
35853
+ applied: boolean()
35854
+ })
35855
+ },
35856
+ 400: { description: "Invalid days, end or apply" },
35857
+ 403: { description: "`apply` without permission to write config" },
35858
+ 408: { description: "A session query ran past its time budget" },
35859
+ 409: { description: "Another calibration run is in progress" },
35860
+ 504: { description: "The run passed its 120 s deadline" }
35861
+ },
35862
+ rbac: {
35863
+ ungated: "a dry run only reads sessions; apply:true is gated by config.write.any in the handler"
35864
+ }
35865
+ });
35866
+ async function handleSavingsCalibration(req, res, pathSegments, queryParams) {
35867
+ if (getRoute2.match(req.method, pathSegments)) {
35868
+ const [row] = await getSwarmConfigs2({ scope: "global", key: SAVINGS_CALIBRATION_KEY });
35869
+ let parsed = null;
35870
+ try {
35871
+ const result = StoredCalibrationSchema.safeParse(JSON.parse(row?.value ?? "null"));
35872
+ parsed = result.success ? result.data : null;
35873
+ } catch {}
35874
+ const active = parsed ?? { ...SHIPPED_CALIBRATION, curve: plain(SHIPPED_CALIBRATION.curve) };
35875
+ getRoute2.respond(res, 200, {
35876
+ source: parsed ? "deployment" : "shipped",
35877
+ active: { calibratedAt: active.calibratedAt, model: active.model, curve: active.curve },
35878
+ stored: row ? {
35879
+ valid: parsed !== null,
35880
+ updatedAt: row.lastUpdatedAt,
35881
+ ...parsed ? {
35882
+ calibratedAt: parsed.calibratedAt,
35883
+ model: parsed.model,
35884
+ ...parsed.window ? { window: parsed.window } : {}
35885
+ } : {}
35886
+ } : null
35887
+ });
35888
+ return true;
35889
+ }
35890
+ if (!postRoute.match(req.method, pathSegments))
35891
+ return false;
35892
+ const parsed = await postRoute.parse(req, res, pathSegments, queryParams);
35893
+ if (!parsed)
35894
+ return true;
35895
+ const { days, end, apply } = parsed.body;
35896
+ const deadlineAt = Date.now() + deadlineMs;
35897
+ if (apply && !await ensureConfigAdmin(req, res, "config.write.any"))
35898
+ return true;
35899
+ if (running2) {
35900
+ jsonError(res, "A calibration run is already in progress", 409);
35901
+ return true;
35902
+ }
35903
+ running2 = true;
35904
+ try {
35905
+ const run = await calibrate(deadlineSql(deadlineAt), {
35906
+ days,
35907
+ end: end ? new Date(end) : new Date
35908
+ });
35909
+ if (Date.now() >= deadlineAt)
35910
+ throw new DeadlineError;
35911
+ const refusals = run.refusal ? [run.refusal] : [];
35912
+ let applied = false;
35913
+ if (apply && run.calibration) {
35914
+ if (run.applyBlocked) {
35915
+ refusals.push(`not applied: ${run.applyBlocked}`);
35916
+ } else {
35917
+ StoredCalibrationSchema.parse(run.calibration);
35918
+ await getDbClient2().transaction(() => upsertSwarmConfig2({
35919
+ scope: "global",
35920
+ key: SAVINGS_CALIBRATION_KEY,
35921
+ value: JSON.stringify(run.calibration),
35922
+ exportToEnv: false,
35923
+ description: "Savings session curve derived from this deployment's sessions"
35924
+ }), { deadlineAt });
35925
+ clearCalibrationCache();
35926
+ applied = true;
35927
+ }
35928
+ }
35929
+ postRoute.respond(res, 200, {
35930
+ window: run.window,
35931
+ sessions: run.sessions,
35932
+ refusals,
35933
+ calibration: run.calibration,
35934
+ speed: run.speed,
35935
+ repriceMatch: run.repriceMatch,
35936
+ meanRatio: run.meanRatio,
35937
+ gaps: run.gaps,
35938
+ applied
35939
+ });
35940
+ } catch (err) {
35941
+ if (err instanceof DeadlineError || err instanceof DbTransactionDeadlineError) {
35942
+ jsonError(res, `Calibration passed its ${deadlineMs / 1000} s deadline; use a shorter window`, 504);
35943
+ } else if (err instanceof DbQueryTimeoutError) {
35944
+ json(res, { error: "db_query_timeout", message: err.message }, 408);
35945
+ } else {
35946
+ throw err;
35947
+ }
35948
+ } finally {
35949
+ running2 = false;
35950
+ }
35951
+ return true;
35952
+ }
35953
+
32290
35954
  // src/http/schedules.ts
32291
35955
  init_zod();
32292
35956
  init_asset_key_auth();
@@ -35777,6 +39441,7 @@ init_registry();
35777
39441
  init_extract_signature();
35778
39442
  init_quickjs_compat();
35779
39443
  init_types4();
39444
+ init_request_auth_context();
35780
39445
  init_secret_scrubber();
35781
39446
  init_route_def();
35782
39447
  init_utils2();
@@ -36339,6 +40004,8 @@ async function handleScripts(req, res, pathSegments, queryParams, agentId) {
36339
40004
  const startedAt = new Date().toISOString();
36340
40005
  const runStartTouch = namedScript?.isScratch ? await touchScratchScriptLastUsed(namedScript.id) : null;
36341
40006
  const credentials = await buildScriptCredentialBindingsWithFailures({ agentId: agent.id });
40007
+ const runId = crypto.randomUUID();
40008
+ const callerProvenance = getCurrentRunProvenance();
36342
40009
  const output = await runScriptWithRunCredential({
36343
40010
  source,
36344
40011
  args: parsed.body.args,
@@ -36352,6 +40019,9 @@ async function handleScripts(req, res, pathSegments, queryParams, agentId) {
36352
40019
  agentFs: credentials.agentFs,
36353
40020
  apiConnections: getScriptApiConnectionDescriptors({ agentId: agent.id }),
36354
40021
  mcpConnections: getScriptMcpConnectionDescriptors({ agentId: agent.id })
40022
+ }, {
40023
+ sourceScriptRunId: runId,
40024
+ sourceStepId: callerProvenance?.sourceStepId ?? undefined
36355
40025
  });
36356
40026
  const ok = output.exitCode === 0 && !output.error && !output.runtimeError;
36357
40027
  if (namedScript?.isScratch && ok) {
@@ -36404,7 +40074,7 @@ async function handleScripts(req, res, pathSegments, queryParams, agentId) {
36404
40074
  ].filter(Boolean).join(" — ") || `Script exited with code ${output.exitCode}`);
36405
40075
  try {
36406
40076
  await recordInlineScriptRun2({
36407
- id: crypto.randomUUID(),
40077
+ id: runId,
36408
40078
  agentId: agent.id,
36409
40079
  source,
36410
40080
  args: scrubObject(parsed.body.args ?? null),
@@ -37264,7 +40934,7 @@ var LABEL_TTL_MS = 24 * 60 * 60 * 1000;
37264
40934
  var FAILURE_TTL_MS = 10 * 60 * 1000;
37265
40935
  var FAILURE_CACHE_MAX = 500;
37266
40936
  var LOOKUP_QUEUE_MAX = 50;
37267
- var inFlight3 = new Set;
40937
+ var inFlight4 = new Set;
37268
40938
  var failedUntil = new Map;
37269
40939
  var pending = Promise.resolve();
37270
40940
  async function channelLabel(client, id) {
@@ -37296,21 +40966,21 @@ function warmSlackChannelLabels(groupKeys) {
37296
40966
  const id = CHANNEL_GROUP_KEY.exec(groupKey)?.[1];
37297
40967
  if (!id)
37298
40968
  continue;
37299
- if (inFlight3.has(id) || (failedUntil.get(id) ?? 0) > Date.now())
40969
+ if (inFlight4.has(id) || (failedUntil.get(id) ?? 0) > Date.now())
37300
40970
  continue;
37301
40971
  failedUntil.delete(id);
37302
- if (inFlight3.size >= LOOKUP_QUEUE_MAX)
40972
+ if (inFlight4.size >= LOOKUP_QUEUE_MAX)
37303
40973
  continue;
37304
- if (failedUntil.size + inFlight3.size >= FAILURE_CACHE_MAX) {
40974
+ if (failedUntil.size + inFlight4.size >= FAILURE_CACHE_MAX) {
37305
40975
  const now = Date.now();
37306
40976
  for (const [failedId, until] of failedUntil) {
37307
40977
  if (until <= now)
37308
40978
  failedUntil.delete(failedId);
37309
40979
  }
37310
- if (failedUntil.size + inFlight3.size >= FAILURE_CACHE_MAX)
40980
+ if (failedUntil.size + inFlight4.size >= FAILURE_CACHE_MAX)
37311
40981
  continue;
37312
40982
  }
37313
- inFlight3.add(id);
40983
+ inFlight4.add(id);
37314
40984
  pending = pending.then(async () => {
37315
40985
  try {
37316
40986
  const label = await channelLabel(client, id);
@@ -37319,7 +40989,7 @@ function warmSlackChannelLabels(groupKeys) {
37319
40989
  failedUntil.set(id, Date.now() + FAILURE_TTL_MS);
37320
40990
  console.warn(`[Slack] Could not cache a session channel label: ${slackErrorCode2(error) ?? "unknown error"}`);
37321
40991
  } finally {
37322
- inFlight3.delete(id);
40992
+ inFlight4.delete(id);
37323
40993
  }
37324
40994
  });
37325
40995
  }
@@ -38362,7 +42032,7 @@ async function buildSkillsBundle(readSkills, readFiles) {
38362
42032
  init_db4();
38363
42033
  var SKILL_USAGE_WINDOWS = ["7d", "30d", "all"];
38364
42034
  var WINDOW_DAYS = { "7d": 7, "30d": 30, all: null };
38365
- var DAY_MS2 = 24 * 60 * 60 * 1000;
42035
+ var DAY_MS4 = 24 * 60 * 60 * 1000;
38366
42036
  var RECENT_LIMIT = 25;
38367
42037
  var STARTED_TASK_SQL = `(t.status IN ('in_progress', 'paused', 'completed')
38368
42038
  OR t.claudeSessionId IS NOT NULL
@@ -38376,7 +42046,7 @@ var ALL_WINDOW_CACHE_MS = 5 * 60 * 1000;
38376
42046
  var allWindowCache = new Map;
38377
42047
  function skillUsageWindowStart(window, now = Date.now()) {
38378
42048
  const days = WINDOW_DAYS[window];
38379
- return days === null ? null : new Date(now - days * DAY_MS2).toISOString();
42049
+ return days === null ? null : new Date(now - days * DAY_MS4).toISOString();
38380
42050
  }
38381
42051
  function dayModifier(tzOffsetMinutes) {
38382
42052
  const minutes = Math.max(-14 * 60, Math.min(14 * 60, Math.trunc(tzOffsetMinutes)));
@@ -40035,6 +43705,25 @@ init_webhook_lifecycle();
40035
43705
  init_ensure_token();
40036
43706
  init_route_def();
40037
43707
  init_utils2();
43708
+
43709
+ // src/http/trackers/authorize-gate.ts
43710
+ init_zod();
43711
+ init_audit_user();
43712
+ var TrackerAuthorizeQuerySchema = object2({
43713
+ redirect: string2().optional(),
43714
+ format: _enum2(["redirect", "json"]).optional()
43715
+ });
43716
+ var TrackerAuthorizeUrlSchema = object2({ authorizeUrl: string2() });
43717
+ async function ensureTrackerAuthorizeAdmin(req, res, providerName) {
43718
+ const header = req.headers["x-agent-id"];
43719
+ const agentId = Array.isArray(header) ? header[0] : header;
43720
+ const allowed = await ensureHttpPermission(req, res, "oauth-authorization.manage", `Only the lead can start the ${providerName} OAuth flow.`, agentId);
43721
+ if (!allowed)
43722
+ return null;
43723
+ return { userId: await resolveHttpAuditUserId(req, agentId) };
43724
+ }
43725
+
43726
+ // src/http/trackers/jira.ts
40038
43727
  var MANUAL_WEBHOOK_INSTRUCTIONS = "See docs-site/.../integrations/jira.mdx for manual webhook registration steps.";
40039
43728
  var JiraWebhookIdEntrySchema = object2({
40040
43729
  id: number2().int(),
@@ -40080,12 +43769,17 @@ var jiraAuthorize = route({
40080
43769
  method: "get",
40081
43770
  path: "/api/trackers/jira/authorize",
40082
43771
  pattern: ["api", "trackers", "jira", "authorize"],
40083
- summary: "Redirect to Atlassian OAuth consent screen",
43772
+ summary: "Start the Jira OAuth flow (admin): redirect to the consent screen, or return its URL",
40084
43773
  tags: ["Trackers"],
40085
- auth: { apiKey: false },
40086
- query: object2({ redirect: string2().optional() }),
43774
+ query: TrackerAuthorizeQuerySchema,
43775
+ rbac: { permission: "oauth-authorization.manage" },
40087
43776
  responses: {
43777
+ 200: {
43778
+ description: "Consent URL (format=json), for clients that navigate themselves",
43779
+ schema: TrackerAuthorizeUrlSchema
43780
+ },
40088
43781
  302: { description: "Redirect to Atlassian OAuth" },
43782
+ 403: { description: "Caller lacks oauth-authorization.manage" },
40089
43783
  500: { description: "Failed to generate authorization URL" },
40090
43784
  503: { description: "Jira integration not configured" }
40091
43785
  }
@@ -40232,18 +43926,25 @@ async function handleJiraTracker(req, res, pathSegments) {
40232
43926
  const parsed = await jiraAuthorize.parse(req, res, pathSegments, queryParams);
40233
43927
  if (!parsed)
40234
43928
  return true;
43929
+ const initiator = await ensureTrackerAuthorizeAdmin(req, res, "Jira");
43930
+ if (!initiator)
43931
+ return true;
40235
43932
  if (!isJiraEnabled()) {
40236
43933
  res.writeHead(503, { "Content-Type": "application/json" });
40237
43934
  res.end(JSON.stringify({ error: "Jira integration not configured" }));
40238
43935
  return true;
40239
43936
  }
40240
43937
  try {
40241
- const url = await getJiraAuthorizationUrl(allowedCredentialRedirect(parsed.query.redirect));
43938
+ const url = await getJiraAuthorizationUrl(allowedCredentialRedirect(parsed.query.redirect), initiator.userId);
40242
43939
  if (!url) {
40243
43940
  res.writeHead(500, { "Content-Type": "application/json" });
40244
43941
  res.end(JSON.stringify({ error: "Failed to generate authorization URL" }));
40245
43942
  return true;
40246
43943
  }
43944
+ if (parsed.query.format === "json") {
43945
+ jiraAuthorize.respond(res, 200, { authorizeUrl: url });
43946
+ return true;
43947
+ }
40247
43948
  res.writeHead(302, { Location: url });
40248
43949
  res.end();
40249
43950
  } catch (err) {
@@ -40503,12 +44204,17 @@ var linearAuthorize = route({
40503
44204
  method: "get",
40504
44205
  path: "/api/trackers/linear/authorize",
40505
44206
  pattern: ["api", "trackers", "linear", "authorize"],
40506
- summary: "Redirect to Linear OAuth consent screen",
44207
+ summary: "Start the Linear OAuth flow (admin): redirect to the consent screen, or return its URL",
40507
44208
  tags: ["Trackers"],
40508
- auth: { apiKey: false },
40509
- query: object2({ redirect: string2().optional() }),
44209
+ query: TrackerAuthorizeQuerySchema,
44210
+ rbac: { permission: "oauth-authorization.manage" },
40510
44211
  responses: {
44212
+ 200: {
44213
+ description: "Consent URL (format=json), for clients that navigate themselves",
44214
+ schema: TrackerAuthorizeUrlSchema
44215
+ },
40511
44216
  302: { description: "Redirect to Linear OAuth" },
44217
+ 403: { description: "Caller lacks oauth-authorization.manage" },
40512
44218
  500: { description: "Failed to generate authorization URL" },
40513
44219
  503: { description: "Linear integration not configured" }
40514
44220
  }
@@ -40602,18 +44308,25 @@ async function handleLinearTracker(req, res, pathSegments) {
40602
44308
  const parsed = await linearAuthorize.parse(req, res, pathSegments, queryParams);
40603
44309
  if (!parsed)
40604
44310
  return true;
44311
+ const initiator = await ensureTrackerAuthorizeAdmin(req, res, "Linear");
44312
+ if (!initiator)
44313
+ return true;
40605
44314
  if (!isLinearEnabled()) {
40606
44315
  res.writeHead(503, { "Content-Type": "application/json" });
40607
44316
  res.end(JSON.stringify({ error: "Linear integration not configured" }));
40608
44317
  return true;
40609
44318
  }
40610
44319
  try {
40611
- const url = await getLinearAuthorizationUrl(allowedCredentialRedirect(parsed.query.redirect));
44320
+ const url = await getLinearAuthorizationUrl(allowedCredentialRedirect(parsed.query.redirect), initiator.userId);
40612
44321
  if (!url) {
40613
44322
  res.writeHead(500, { "Content-Type": "application/json" });
40614
44323
  res.end(JSON.stringify({ error: "Failed to generate authorization URL" }));
40615
44324
  return true;
40616
44325
  }
44326
+ if (parsed.query.format === "json") {
44327
+ linearAuthorize.respond(res, 200, { authorizeUrl: url });
44328
+ return true;
44329
+ }
40617
44330
  res.writeHead(302, { Location: url });
40618
44331
  res.end();
40619
44332
  } catch (err) {
@@ -44670,6 +48383,8 @@ var httpServer = createHttpServer(async (req, res) => {
44670
48383
  () => handleImprovements(req, res, pathSegments, queryParams),
44671
48384
  () => handleRanking(req, res, pathSegments, queryParams),
44672
48385
  () => handleFleetBenchmark(req, res, pathSegments, queryParams),
48386
+ () => handleSavings(req, res, pathSegments, queryParams),
48387
+ () => handleSavingsCalibration(req, res, pathSegments, queryParams),
44673
48388
  () => handleTaskTemplates(req, res, pathSegments, queryParams),
44674
48389
  () => handleMcp(req, res, transports, transportActivity, mcpSessionAgents),
44675
48390
  () => handleMcpUser(req, res, transportsUser, sessionUsers, transportActivityUser)
@@ -44696,7 +48411,7 @@ var httpServer = createHttpServer(async (req, res) => {
44696
48411
  });
44697
48412
  });
44698
48413
  var detachRealtime = attachRealtimeTransport(httpServer);
44699
- var { attachControllerTransport } = await import("./controllers-connect-k5sg9m9h.js");
48414
+ var { attachControllerTransport } = await import("./controllers-connect-63j5rdcm.js");
44700
48415
  var detachControllers = attachControllerTransport(httpServer);
44701
48416
  var stopWorkerNudges = startWorkerNudgeListener();
44702
48417
  var taskAutoTitles = startTaskAutoTitleListener();
@@ -44727,7 +48442,7 @@ async function shutdown() {
44727
48442
  sessionsProcessed: getServerSessionsProcessed()
44728
48443
  });
44729
48444
  if (hasCapability("scheduling")) {
44730
- const { stopScheduler } = await import("./index-f0hcrs8e.js");
48445
+ const { stopScheduler } = await import("./index-8w2aznds.js");
44731
48446
  stopScheduler();
44732
48447
  }
44733
48448
  stopHeartbeat2();
@@ -44739,13 +48454,14 @@ async function shutdown() {
44739
48454
  await stopSlackApp2();
44740
48455
  await stopChatSdk();
44741
48456
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
44742
- const { stopOAuthKeepalive } = await import("./keepalive-xn6s7rmg.js");
48457
+ const { stopOAuthKeepalive } = await import("./keepalive-k2a3qe73.js");
44743
48458
  await stopOAuthKeepalive();
44744
48459
  }
44745
48460
  stopOAuthPendingGc();
44746
48461
  stopMcpOverflowSweep();
44747
48462
  stopMemoryGc();
44748
48463
  await stopDbRetention();
48464
+ await stopSavingsRollup();
44749
48465
  stopHumanFreeDrain();
44750
48466
  await stopTaskSearchBackfill();
44751
48467
  stopScratchScriptGc();
@@ -44823,21 +48539,21 @@ try {
44823
48539
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
44824
48540
  }
44825
48541
  try {
44826
- const { ensurePricingSeeded } = await import("./boot-seeds-pbtmvcjm.js");
48542
+ const { ensurePricingSeeded } = await import("./boot-seeds-n2b3dx4e.js");
44827
48543
  ensurePricingSeeded();
44828
- const { startPricingRefreshLoop } = await import("./pricing-refresh-7dh2yase.js");
48544
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-1nj722h6.js");
44829
48545
  startPricingRefreshLoop();
44830
48546
  } catch (err) {
44831
48547
  console.error("[startup] Failed to seed pricing rows:", err);
44832
48548
  }
44833
48549
  try {
44834
- const { ensureModelProfilesSeeded } = await import("./boot-seeds-pbtmvcjm.js");
48550
+ const { ensureModelProfilesSeeded } = await import("./boot-seeds-n2b3dx4e.js");
44835
48551
  await ensureModelProfilesSeeded();
44836
48552
  } catch (err) {
44837
48553
  console.error("[startup] Failed to seed model profiles:", err);
44838
48554
  }
44839
48555
  try {
44840
- const { ensureRbacSeeded } = await import("./boot-seeds-pbtmvcjm.js");
48556
+ const { ensureRbacSeeded } = await import("./boot-seeds-n2b3dx4e.js");
44841
48557
  ensureRbacSeeded();
44842
48558
  } catch (err) {
44843
48559
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -44845,7 +48561,7 @@ try {
44845
48561
  throw err;
44846
48562
  }
44847
48563
  try {
44848
- const { runAllSeeders } = await import("./index-tez78qj3.js");
48564
+ const { runAllSeeders } = await import("./index-3yvzbhxd.js");
44849
48565
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
44850
48566
  } catch (err) {
44851
48567
  console.error("[startup] Failed to seed built-in entities:", err);
@@ -44908,46 +48624,47 @@ httpServer.listen(port, async () => {
44908
48624
  await initWorkflows2();
44909
48625
  await startScriptRunSupervisor(getMcpBaseUrl());
44910
48626
  if (hasCapability("scheduling")) {
44911
- const { startScheduler } = await import("./index-f0hcrs8e.js");
44912
- const { getExecutorRegistry } = await import("./index-s4ewdma4.js");
48627
+ const { startScheduler } = await import("./index-8w2aznds.js");
48628
+ const { getExecutorRegistry } = await import("./index-qnjvr362.js");
44913
48629
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
44914
48630
  startScheduler(getExecutorRegistry(), intervalMs, {
44915
48631
  runId: globalState.__runId
44916
48632
  });
44917
48633
  }
44918
48634
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
44919
- const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-4xwaf5th.js");
48635
+ const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-yzxd3sn9.js");
44920
48636
  startHeartbeat(parseHeartbeatIntervalMs(process.env.HEARTBEAT_INTERVAL_MS));
44921
48637
  }
44922
48638
  startPoolRouting();
44923
48639
  startRuntimeSupervisor();
44924
48640
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
44925
- const { startOAuthKeepalive } = await import("./keepalive-xn6s7rmg.js");
48641
+ const { startOAuthKeepalive } = await import("./keepalive-k2a3qe73.js");
44926
48642
  startOAuthKeepalive();
44927
48643
  }
44928
48644
  if (!isEnvFlagEnabled("OAUTH_REFRESH_SWEEP_DISABLE", false)) {
44929
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-094c8wfk.js");
48645
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-y7rm6bkb.js");
44930
48646
  startOAuthRefreshSweep();
44931
48647
  }
44932
48648
  startOAuthPendingGc();
44933
48649
  startMcpOverflowSweep();
44934
48650
  await startMemoryGc();
44935
48651
  await startDbRetention();
48652
+ startSavingsRollup(savingsRollupSql);
44936
48653
  startHumanFreeDrain();
44937
48654
  startTaskSearchBackfill();
44938
- import("./embedding-space-ezwenjmj.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
48655
+ import("./embedding-space-wh8de1t9.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
44939
48656
  setDeploymentEnvReader(getDeploymentEnvValue);
44940
48657
  return runEmbeddingMaintenance({ backfill: true });
44941
48658
  }).catch((err) => {
44942
48659
  console.error("[embedding-space] startup maintenance failed (non-fatal):", err);
44943
48660
  });
44944
- import("./boot-args-schema-pbbnhmc3.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
48661
+ import("./boot-args-schema-4vb0xsat.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
44945
48662
  console.error("[boot-args-schema] startup backfill failed (non-fatal):", err);
44946
48663
  });
44947
- import("./boot-scrub-sweep-app8g8ym.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
48664
+ import("./boot-scrub-sweep-yrytg42z.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
44948
48665
  console.error("[boot-scrub-sweep] startup scrub failed (non-fatal):", err);
44949
48666
  });
44950
- import("./session-source-backfill-nt923ask.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
48667
+ import("./session-source-backfill-gxxwfh12.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
44951
48668
  console.error("[session-source-backfill] startup run failed (non-fatal):", err);
44952
48669
  });
44953
48670
  }).on("error", (err) => {