@desplega.ai/agent-swarm 2.8.2 → 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 (258) hide show
  1. package/dist/acp-adapter-xq6s2z6t.js +14 -0
  2. package/dist/{actions-kxek041g.js → actions-ewz7bp4g.js} +20 -19
  3. package/dist/{amp-adapter-ce7jjke4.js → amp-adapter-f25tqhnf.js} +3 -3
  4. package/dist/{app-v6zz8yh0.js → app-mkptw0k7.js} +4 -4
  5. package/dist/{assistant-m0sw9xx2.js → assistant-c47rfe77.js} +23 -22
  6. package/dist/{boot-args-schema-66bk37wv.js → boot-args-schema-4vb0xsat.js} +1 -1
  7. package/dist/{boot-reembed-edjpwsc1.js → boot-reembed-1ghy2sab.js} +1 -1
  8. package/dist/{boot-reembed-y27n09tz.js → boot-reembed-htr73hbs.js} +1 -1
  9. package/dist/{boot-scrub-sweep-1xc35965.js → boot-scrub-sweep-yrytg42z.js} +4 -4
  10. package/dist/{boot-seeds-7hjj91qj.js → boot-seeds-n2b3dx4e.js} +4 -4
  11. package/dist/{boxd-ent8ch04.js → boxd-jmfqgkqa.js} +1 -1
  12. package/dist/{claude-adapter-stw7jdcf.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-y6z2perp.js → claude-managed-setup-hfvry1bd.js} +5 -5
  15. package/dist/{claude-sdk-session-vvya8wqk.js → claude-sdk-session-0hamqzc7.js} +10 -11
  16. package/dist/{cli-v1dv1r37.js → cli-0bcgyj5b.js} +74 -3
  17. package/dist/{cli-t2tma8gb.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-0cq8y6m7.js → cli-4ax9mvvg.js} +4 -4
  22. package/dist/{cli-tekytdq9.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-9mb2q6pb.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-kjtwrhea.js → cli-7c5tgqhf.js} +5 -5
  30. package/dist/{cli-2gxeg5gr.js → cli-8476gtwf.js} +1 -1
  31. package/dist/{cli-zh9rsbqf.js → cli-922z7gwm.js} +3 -3
  32. package/dist/{cli-jrzkw01m.js → cli-93t5s4zq.js} +2 -2
  33. package/dist/{cli-gyt3zydq.js → cli-9zmb7ptc.js} +9 -9
  34. package/dist/{cli-dzpc6en0.js → cli-am1ptset.js} +2 -2
  35. package/dist/{cli-w401b9tq.js → cli-awwptga4.js} +1 -1
  36. package/dist/{cli-26ctbcdp.js → cli-bhsfbmk8.js} +3 -3
  37. package/dist/{cli-mxn1qvbn.js → cli-bj6qhgte.js} +14 -32
  38. package/dist/{cli-g70vxtjh.js → cli-c0xjnr8z.js} +2 -2
  39. package/dist/{cli-jdknh18m.js → cli-c3ng0mb4.js} +13 -13
  40. package/dist/{cli-f4e8r23x.js → cli-c71n3bxq.js} +11 -6
  41. package/dist/{cli-6rc5frdm.js → cli-crpf163n.js} +25 -18
  42. package/dist/{cli-1qkz151v.js → cli-dpsfwh7n.js} +13 -21
  43. package/dist/{cli-xzm9vcfg.js → cli-dtdht77h.js} +2 -2
  44. package/dist/{cli-a0z912j7.js → cli-e2w34h6z.js} +137 -62
  45. package/dist/{cli-eddnyg3t.js → cli-emekyyhr.js} +1 -1
  46. package/dist/{cli-d84byzn8.js → cli-f1kwb5fc.js} +109 -33
  47. package/dist/{cli-0jzra9ad.js → cli-gn9y6fn7.js} +2 -2
  48. package/dist/{cli-vdektqgf.js → cli-gpz1d0t2.js} +4 -4
  49. package/dist/{cli-rcecc3yq.js → cli-h9yy18gy.js} +84 -36
  50. package/dist/{cli-m5akxq8q.js → cli-j8cjdzan.js} +1 -1
  51. package/dist/{cli-m9s2qff2.js → cli-jg5txpm6.js} +187 -93
  52. package/dist/{cli-b98a65ed.js → cli-k2rw11py.js} +3 -3
  53. package/dist/{cli-3e875j5p.js → cli-k96cecs7.js} +276 -47
  54. package/dist/{cli-3vjhs18n.js → cli-kd56bmk4.js} +1 -1
  55. package/dist/{cli-3sy2xags.js → cli-kmemts3w.js} +12 -12
  56. package/dist/{cli-f6bahpn5.js → cli-knva3nmx.js} +2 -2
  57. package/dist/{cli-959kp5h2.js → cli-kw44j53p.js} +13 -13
  58. package/dist/{cli-bsywb58a.js → cli-mdpbjnzq.js} +10 -10
  59. package/dist/{cli-2kvhc7x8.js → cli-me0r8gzr.js} +35 -76
  60. package/dist/{cli-4vzgeta4.js → cli-mwwmka77.js} +14 -14
  61. package/dist/{cli-q24n86d2.js → cli-n5t077me.js} +2 -2
  62. package/dist/{cli-rvhdmjvt.js → cli-nx2n3z6p.js} +1 -1
  63. package/dist/{cli-28fq781p.js → cli-pe4d96rb.js} +1 -1
  64. package/dist/{cli-3rkdne1h.js → cli-pxwtcgcp.js} +2 -2
  65. package/dist/{cli-n6vtrcht.js → cli-qmqt520k.js} +2 -2
  66. package/dist/{cli-pchypa1s.js → cli-qps8je6j.js} +17 -2
  67. package/dist/{cli-97ae65rz.js → cli-rjvsf9qa.js} +5 -5
  68. package/dist/{cli-e1p3n5gq.js → cli-rqfvkx5t.js} +6 -6
  69. package/dist/{cli-3vmb0n58.js → cli-s7zz734a.js} +1 -1
  70. package/dist/{cli-rmzsadkf.js → cli-s8p8hhty.js} +2 -2
  71. package/dist/{cli-j24zbska.js → cli-sdvcrq5x.js} +5 -5
  72. package/dist/{cli-5y340nzn.js → cli-sg27rk2t.js} +5 -5
  73. package/dist/{cli-d6521kb5.js → cli-skmhsnqh.js} +1 -1
  74. package/dist/{cli-5mrq3ake.js → cli-t4dv07kr.js} +1 -1
  75. package/dist/{cli-z1w943va.js → cli-t5ys4ebm.js} +3 -3
  76. package/dist/{cli-f4r3g076.js → cli-tas6ckky.js} +2 -2
  77. package/dist/{cli-1pz0330a.js → cli-tf79ryyy.js} +1 -1
  78. package/dist/{cli-kc7v1nfv.js → cli-tnzebztn.js} +1 -1
  79. package/dist/{cli-pfs8adn4.js → cli-vx421edw.js} +3 -3
  80. package/dist/{cli-kchjb7qy.js → cli-x3ex5bqf.js} +1 -1
  81. package/dist/cli-yss07azk.js +142 -0
  82. package/dist/{cli-fwy8kfd6.js → cli-z8cvws4c.js} +98 -16
  83. package/dist/{cli-g5mtmf6t.js → cli-zdaypkq9.js} +146 -52
  84. package/dist/{cli-fpjmegdb.js → cli-zeaehgyd.js} +2 -2
  85. package/dist/{cli-837vfs2x.js → cli-ztq5z4e1.js} +4 -4
  86. package/dist/cli.js +20 -20
  87. package/dist/{codex-adapter-zerf5qsp.js → codex-adapter-2brxx5ta.js} +7 -8
  88. package/dist/{codex-hook-30gyhzxe.js → codex-hook-c930c3ea.js} +1 -1
  89. package/dist/{codex-login-bcda78ge.js → codex-login-cbrs1h5w.js} +1 -1
  90. package/dist/{codex-session-runner-89s304py.js → codex-session-runner-y9anfj0r.js} +8 -9
  91. package/dist/{commands-jeh1b51j.js → commands-wn9q06qr.js} +3 -3
  92. package/dist/{controller-mctfbrse.js → controller-fw608czd.js} +4 -4
  93. package/dist/{controllers-connect-nxa1ddwn.js → controllers-connect-63j5rdcm.js} +20 -20
  94. package/dist/{cursor-adapter-qj8vehv6.js → cursor-adapter-6mb9jme8.js} +2 -2
  95. package/dist/{db-2dvay0es.js → db-0m6v5tq4.js} +3 -3
  96. package/dist/{db-b36qn6k3.js → db-y4wfrzbm.js} +4 -2
  97. package/dist/{devin-adapter-xedz98zv.js → devin-adapter-r0yx3gv8.js} +1 -1
  98. package/dist/{dispatcher-gndbta01.js → dispatcher-9tq2zzdj.js} +17 -17
  99. package/dist/{docker-866qpzt9.js → docker-j75atvpt.js} +2 -2
  100. package/dist/{dsh-adapter-f75sz821.js → dsh-adapter-t09sv4tq.js} +2 -2
  101. package/dist/{e2b-jbm7mj93.js → e2b-7s9dscap.js} +2 -2
  102. package/dist/{e2b-3gpc2n3w.js → e2b-a7vzs2vj.js} +2 -2
  103. package/dist/{easter-egg-3d-533knw22.js → easter-egg-3d-fbwvmwhe.js} +1 -1
  104. package/dist/{embedding-space-4p05vb2x.js → embedding-space-wh8de1t9.js} +6 -6
  105. package/dist/{embeddings-m6768mgh.js → embeddings-3hpbdtjr.js} +1 -1
  106. package/dist/{event-bus-e66gh7cc.js → event-bus-tr6h3gv8.js} +1 -1
  107. package/dist/{execute-b3mrb1mv.js → execute-4bdf8sdy.js} +1 -1
  108. package/dist/{external-channel-gjv3jne3.js → external-channel-ts2fwqh0.js} +2 -2
  109. package/dist/fx-adapter-1rnxnf56.js +17 -0
  110. package/dist/grok-adapter-efhmf1r8.js +17 -0
  111. package/dist/handlers-anrr3py9.js +32 -0
  112. package/dist/{heartbeat-a1tv60gt.js → heartbeat-2ze5fzpc.js} +20 -20
  113. package/dist/{hook-8h5dzcgq.js → hook-ca54yd4s.js} +5 -5
  114. package/dist/{hook-cyaps9ba.js → hook-gaehe2w5.js} +7 -7
  115. package/dist/{http-t15mhbd9.js → http-jfg8t2yk.js} +3861 -1798
  116. package/dist/{index-tvfafeyy.js → index-3gv6sc4z.js} +1 -1
  117. package/dist/{index-qav6455f.js → index-3yvzbhxd.js} +97 -22
  118. package/dist/index-8w2aznds.js +33 -0
  119. package/dist/{index-w1zqf680.js → index-csgrxedz.js} +1 -1
  120. package/dist/index-qnjvr362.js +37 -0
  121. package/dist/index-yzxd3sn9.js +32 -0
  122. package/dist/{keepalive-91s7hzrb.js → keepalive-k2a3qe73.js} +4 -4
  123. package/dist/lead-zhxqbfdv.js +69 -0
  124. package/dist/{maintenance-7pjmy5xy.js → maintenance-gb5sd5nc.js} +1 -1
  125. package/dist/{node-4c5jqxr3.js → node-7qsx5kvm.js} +1 -1
  126. package/dist/{oauth-refresh-sweep-rzqfm94j.js → oauth-refresh-sweep-y7rm6bkb.js} +3 -3
  127. package/dist/{onboard-74st7pag.js → onboard-jmc5qerv.js} +3 -3
  128. package/dist/{opencode-adapter-arn7gm8q.js → opencode-adapter-7eade9ev.js} +6 -7
  129. package/dist/{otel-impl-rnzey8cb.js → otel-impl-8j1xhxqd.js} +2 -2
  130. package/dist/{pi-mono-adapter-6mkwq64n.js → pi-mono-adapter-yqmaf32x.js} +13 -13
  131. package/dist/{pricing-refresh-ha21jhk7.js → pricing-refresh-1nj722h6.js} +2 -2
  132. package/dist/{rbac-roles-wqhma4dr.js → rbac-roles-b1mtr6dr.js} +3 -3
  133. package/dist/{rbac-roles-59dxachk.js → rbac-roles-n1f3frk1.js} +2 -2
  134. package/dist/{render-v2-14kpzx12.js → render-v2-1gfpd8rj.js} +4 -4
  135. package/dist/{resume-gsa5fb5f.js → resume-w1s1eh5v.js} +7 -7
  136. package/dist/{runtime-1hv06jsn.js → runtime-84g5egsc.js} +1 -1
  137. package/dist/{session-access-skm7bnp6.js → session-access-y6z1txk4.js} +4 -4
  138. package/dist/{session-source-backfill-pbqzbncv.js → session-source-backfill-gxxwfh12.js} +3 -3
  139. package/dist/{setup-5yermsem.js → setup-r91gstyk.js} +1 -1
  140. package/dist/{virtual-modules-gazyapte.js → virtual-modules-cgnj6kme.js} +3 -3
  141. package/dist/{work-objects-xj0ck0w4.js → work-objects-qcxzg61c.js} +20 -20
  142. package/dist/worker-7j2907g6.js +69 -0
  143. package/dist/{worker-follow-up-911xc0b8.js → worker-follow-up-y2d2h7km.js} +17 -17
  144. package/dist/{x-2fyrt5pp.js → x-qhxq2ama.js} +2 -2
  145. package/openapi.json +1214 -108
  146. package/package.json +3 -3
  147. package/src/be/db/tasks/read.ts +33 -0
  148. package/src/be/db.ts +32 -7
  149. package/src/be/migrations/289_automation_savings_daily.sql +47 -0
  150. package/src/be/migrations/291_task_slack_participants.sql +4 -0
  151. package/src/be/migrations/293_savings_component_links.sql +58 -0
  152. package/src/be/migrations/296_automation_savings_daily_read_index.sql +6 -0
  153. package/src/be/model-profile-check.ts +10 -2
  154. package/src/be/savings/compute.ts +511 -16
  155. package/src/be/savings/model.ts +282 -14
  156. package/src/be/savings/read.ts +1500 -0
  157. package/src/be/savings/rollup.ts +571 -0
  158. package/src/be/scripts/run-credential.ts +15 -3
  159. package/src/be/scripts/typecheck.ts +86 -4
  160. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +10 -2
  161. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +70 -4
  162. package/src/be/swarm-config-guard.ts +8 -0
  163. package/src/be/users.ts +29 -2
  164. package/src/commands/runner.ts +159 -41
  165. package/src/extensions/contract-types.generated.ts +1 -1
  166. package/src/http/index.ts +8 -1
  167. package/src/http/poll.ts +14 -1
  168. package/src/http/requested-by.ts +97 -1
  169. package/src/http/savings.ts +676 -190
  170. package/src/http/scripts.ts +26 -15
  171. package/src/http/tasks.ts +43 -5
  172. package/src/prompts/session-templates.ts +80 -3
  173. package/src/providers/acp-targets.ts +1 -1
  174. package/src/providers/amp-adapter.ts +1 -1
  175. package/src/providers/claude-adapter.ts +0 -20
  176. package/src/providers/claude-flag-settings.ts +12 -10
  177. package/src/providers/codex-adapter.ts +9 -34
  178. package/src/providers/opencode-adapter.ts +34 -12
  179. package/src/scheduler/scheduler.ts +20 -14
  180. package/src/scripts-runtime/ctx.ts +1 -1
  181. package/src/scripts-runtime/executors/quickjs-bundle.ts +1 -0
  182. package/src/scripts-runtime/executors/quickjs-prelude.ts +162 -2
  183. package/src/scripts-runtime/executors/quickjs-runner.ts +4 -1
  184. package/src/scripts-runtime/stdlib/fetch.ts +113 -15
  185. package/src/scripts-runtime/stdlib/index.ts +3 -1
  186. package/src/scripts-runtime/stdlib/retry.ts +174 -0
  187. package/src/scripts-runtime/swarm-sdk.ts +186 -17
  188. package/src/scripts-runtime/types/stdlib.d.ts +86 -4
  189. package/src/scripts-runtime/types/swarm-extension.d.ts +26 -0
  190. package/src/scripts-runtime/types/swarm-sdk.d.ts +60 -2
  191. package/src/slack/actions.ts +1 -0
  192. package/src/slack/assistant.ts +2 -0
  193. package/src/slack/enrich.ts +144 -50
  194. package/src/slack/handlers.ts +37 -95
  195. package/src/slack/templates.ts +9 -0
  196. package/src/slack/thread-buffer.ts +45 -71
  197. package/src/slack/thread-participants.ts +187 -0
  198. package/src/tests/base-prompt.test.ts +5 -4
  199. package/src/tests/claude-adapter-binary.test.ts +7 -1
  200. package/src/tests/claude-adapter.test.ts +10 -64
  201. package/src/tests/claude-flag-settings.test.ts +15 -11
  202. package/src/tests/claude-hook-credentials.test.ts +0 -1
  203. package/src/tests/claude-sdk-lifecycle.test.ts +5 -1
  204. package/src/tests/codex-adapter.test.ts +17 -78
  205. package/src/tests/create-task-vcs-repo.test.ts +136 -0
  206. package/src/tests/db-task-read-contract.test.ts +2 -0
  207. package/src/tests/db-task-write-contract.test.ts +1 -0
  208. package/src/tests/docs-index-footprint.test.js +3 -3
  209. package/src/tests/dreaming-learnings.test.ts +104 -0
  210. package/src/tests/extensions-pre-task.test.ts +4 -2
  211. package/src/tests/fetch-resolved-env.test.ts +47 -1
  212. package/src/tests/opencode-adapter.test.ts +53 -6
  213. package/src/tests/prompt-template-session.test.ts +17 -1
  214. package/src/tests/runner-requester-profile.test.ts +139 -1
  215. package/src/tests/savings-compound.test.ts +774 -0
  216. package/src/tests/savings-compute.test.ts +7 -198
  217. package/src/tests/savings-fleet-latency.test.ts +143 -0
  218. package/src/tests/savings-fleet-read.test.ts +195 -0
  219. package/src/tests/savings-fleet-scale.test.ts +222 -0
  220. package/src/tests/savings-model.test.ts +212 -0
  221. package/src/tests/savings-read.test.ts +367 -0
  222. package/src/tests/savings-rollup.test.ts +766 -0
  223. package/src/tests/savings-scripts.test.ts +611 -0
  224. package/src/tests/script-connections.test.ts +2 -0
  225. package/src/tests/script-executor-conformance.test.ts +444 -0
  226. package/src/tests/scripts-http.test.ts +55 -0
  227. package/src/tests/scripts-runtime-fetch.test.ts +2 -2
  228. package/src/tests/secret-rules.test.ts +124 -1
  229. package/src/tests/secret-scrubber.test.ts +1 -1
  230. package/src/tests/slack-dm-implicit-mention.test.ts +20 -1
  231. package/src/tests/slack-identity-resolution.test.ts +23 -0
  232. package/src/tests/slack-inbound-files.test.ts +2 -1
  233. package/src/tests/slack-thread-participants.test.ts +429 -0
  234. package/src/tests/tool-annotations.test.ts +30 -0
  235. package/src/types.ts +31 -0
  236. package/src/utils/mcp-server-fetcher.test.ts +89 -0
  237. package/src/utils/mcp-server-fetcher.ts +13 -5
  238. package/src/utils/request-auth-context.ts +24 -0
  239. package/src/utils/secret-rules.generated.ts +1 -1
  240. package/src/utils/secret-scrubber.ts +154 -29
  241. package/src/workflows/executors/swarm-script.ts +23 -19
  242. package/templates/skills/swarm-scripts/SKILL.md +5 -4
  243. package/templates/skills/swarm-scripts/content.md +5 -4
  244. package/templates/skills/work-on-task/SKILL.md +1 -1
  245. package/templates/skills/work-on-task/content.md +1 -1
  246. package/templates/workflows/dreaming/content.md +1 -1
  247. package/dist/acp-adapter-fqzkxyra.js +0 -15
  248. package/dist/cli-4bd1rck6.js +0 -4
  249. package/dist/cli-xf3qw745.js +0 -104
  250. package/dist/fx-adapter-rpsgb1tw.js +0 -18
  251. package/dist/grok-adapter-n2m3zjg1.js +0 -18
  252. package/dist/handlers-nv8edn19.js +0 -32
  253. package/dist/index-ksmyd6kc.js +0 -37
  254. package/dist/index-rjnrje98.js +0 -32
  255. package/dist/index-tv3413wy.js +0 -33
  256. package/dist/lead-3hmddvrm.js +0 -70
  257. package/dist/worker-qgg0m2gw.js +0 -70
  258. package/src/providers/ctx-mode-env.ts +0 -10
@@ -5,7 +5,16 @@
5
5
  */
6
6
  import { getDbClient } from "../db";
7
7
  import type { DbParam } from "../db-client";
8
- import { JEV_PER_M, nodeOpsOf, scriptOpsFromAwaitCount, type WorkflowFacts } from "./model";
8
+ import {
9
+ DEFAULT_OPS,
10
+ INLINE_OPS,
11
+ INLINE_SCRIPT_NAME,
12
+ JEV_PER_M,
13
+ nodeOpsOf,
14
+ type ScriptFacts,
15
+ scriptOpsFromAwaitCount,
16
+ type WorkflowFacts,
17
+ } from "./model";
9
18
 
10
19
  /** Runs a read query. The default is the API's own DB client. */
11
20
  export type SavingsSql = <T>(sql: string, params: DbParam[]) => Promise<T[]>;
@@ -13,10 +22,9 @@ export type SavingsSql = <T>(sql: string, params: DbParam[]) => Promise<T[]>;
13
22
  const defaultSql: SavingsSql = (sql, params) => getDbClient().query(sql, params);
14
23
 
15
24
  /**
16
- * Above this many runs in the window the live path refuses: the router
17
- * (~360k runs in 30 days) takes 3 to 7 s for its effect query alone.
18
- * shortcut: a fixed cutoff instead of the plan's router rule; the daily
19
- * rollup (next PR) computes high-volume workflows one day at a time.
25
+ * Above this many runs in the window a live (on-request) computation refuses:
26
+ * the router has 12k to 30k runs a day and its step scan alone takes seconds.
27
+ * The daily rollup has no limit: it runs off the request path, one day at a time.
20
28
  */
21
29
  export const LIVE_MAX_RUNS = 10_000;
22
30
 
@@ -34,16 +42,21 @@ const AWAITS_SQL = "(length(source)-length(replace(source,'await','')))/5";
34
42
 
35
43
  const num = (v: unknown): number => Number(v) || 0;
36
44
 
37
- const emptyFacts = (runs: number): WorkflowFacts => ({
45
+ export const emptyFacts = (runs: number): WorkflowFacts => ({
38
46
  runs,
39
47
  countedRuns: 0,
40
48
  schedRuns: 0,
41
49
  schedEffectRuns: 0,
50
+ eventRuns: 0,
51
+ effectRuns: 0,
52
+ effectOpsSum: 0,
42
53
  opsSum: 0,
43
54
  agentTasks: 0,
44
55
  agentUsd: 0,
45
56
  agentMs: 0,
46
57
  followupUsd: 0,
58
+ childTaskUsd: 0,
59
+ childTaskMs: 0,
47
60
  recordedLlmUsd: 0,
48
61
  estimatedLlmUsd: 0,
49
62
  computeSecs: 0,
@@ -54,24 +67,40 @@ async function scriptOps(names: string[], sql: SavingsSql): Promise<Map<string,
54
67
  const ops = new Map<string, number>();
55
68
  const unique = [...new Set(names.filter(Boolean))];
56
69
  if (unique.length === 0) return ops;
57
- const rows = await sql<{ name: string; aw: number }>(
58
- `SELECT name, ${AWAITS_SQL} aw FROM scripts WHERE isScratch=0 AND name IN (${unique.map(() => "?").join(",")}) ORDER BY scope='global'`,
59
- unique,
60
- );
61
- for (const row of rows) ops.set(row.name, scriptOpsFromAwaitCount(row.aw));
70
+ // Chunked: a day can have over a thousand script names.
71
+ for (let i = 0; i < unique.length; i += 500) {
72
+ const chunk = unique.slice(i, i + 500);
73
+ const rows = await sql<{ name: string; aw: number }>(
74
+ `SELECT name, ${AWAITS_SQL} aw FROM scripts WHERE isScratch=0 AND name IN (${chunk.map(() => "?").join(",")}) ORDER BY scope='global'`,
75
+ chunk,
76
+ );
77
+ for (const row of rows) ops.set(row.name, scriptOpsFromAwaitCount(row.aw));
78
+ }
62
79
  return ops;
63
80
  }
64
81
 
65
- /** UTC day (`YYYY-MM-DD`) of an ISO `startedAt`. */
66
- const DAY_SQL = "substr(r.startedAt,1,10)";
82
+ /**
83
+ * How runs are grouped: by UTC day (`YYYY-MM-DD`), or by UTC minute
84
+ * (`YYYY-MM-DDTHH:MM`) so a reader can drop the runs before a window start
85
+ * that falls inside the scanned slice.
86
+ */
87
+ export type SavingsBucket = "day" | "minute";
67
88
 
68
- /** Every run's facts, grouped by the UTC day it started; the window facts are their sum. */
89
+ /** The SQL key of an ISO `startedAt` column for `bucket`. */
90
+ function bucketSql(column: string, bucket: SavingsBucket = "day"): string {
91
+ return `substr(${column},1,${bucket === "minute" ? 16 : 10})`;
92
+ }
93
+
94
+ /** Every run's facts, grouped by the UTC day (or minute) it started; the window facts are their sum. */
69
95
  export async function computeWorkflowWindow(
70
96
  workflow: { id: string; definition: unknown },
71
97
  window: { start: string; end: string },
72
98
  sql: SavingsSql = defaultSql,
99
+ opts: { maxRuns?: number; bucket?: SavingsBucket } = {},
73
100
  ): Promise<WorkflowWindow> {
101
+ const DAY_SQL = bucketSql("r.startedAt", opts.bucket);
74
102
  const span = [workflow.id, window.start, window.end];
103
+ const maxRuns = opts.maxRuns ?? LIVE_MAX_RUNS;
75
104
  // Index-only count first, so a high-volume workflow never reaches the step scans.
76
105
  const total = num(
77
106
  (
@@ -82,7 +111,7 @@ export async function computeWorkflowWindow(
82
111
  )[0]?.n,
83
112
  );
84
113
  if (total === 0) return { status: "ok", facts: emptyFacts(0), byDay: [] };
85
- if (total > LIVE_MAX_RUNS) return { status: "too-many-runs", runs: total };
114
+ if (total > maxRuns) return { status: "too-many-runs", runs: total };
86
115
 
87
116
  const days = new Map<string, DayFacts>();
88
117
  const dayOf = (d: unknown): DayFacts => {
@@ -96,7 +125,8 @@ export async function computeWorkflowWindow(
96
125
  };
97
126
 
98
127
  const byTrigger = await sql<{ d: string; tt: string; st: string; n: number }>(
99
- `SELECT ${DAY_SQL} d, r.triggerType tt, r.status st, count(*) n FROM workflow_runs r WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1,2,3`,
128
+ // Without the hint the planner picks the triggerType index and scans every run.
129
+ `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`,
100
130
  span,
101
131
  );
102
132
  let schedRuns = 0;
@@ -104,6 +134,7 @@ export async function computeWorkflowWindow(
104
134
  const f = dayOf(row.d);
105
135
  const n = num(row.n);
106
136
  f.runs += n;
137
+ if (row.tt === "event") f.eventRuns += n;
107
138
  if (row.st === "skipped" || row.st === "cancelled") continue;
108
139
  f.countedRuns += n;
109
140
  if (row.tt === "schedule") {
@@ -173,6 +204,25 @@ export async function computeWorkflowWindow(
173
204
  );
174
205
  for (const row of followups) dayOf(row.d).followupUsd += num(row.fup);
175
206
 
207
+ // Effect runs of any trigger, found from the child side (child runs via
208
+ // parentStepId, tasks via workflowRunId), with the steps of those runs:
209
+ // the enabled-only rule prices only these.
210
+ const effect = await sql<{ d: string; nid: string | null; n: number }>(
211
+ `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
212
+ WHERE c.parentStepId IS NOT NULL AND p.workflowId=? AND p.startedAt>=? AND p.startedAt<?
213
+ 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<?),
214
+ ed AS (SELECT e.id, ${DAY_SQL} d FROM e JOIN workflow_runs r ON r.id=e.id)
215
+ SELECT d, NULL nid, count(*) n FROM ed GROUP BY d
216
+ 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`,
217
+ [...span, ...span],
218
+ );
219
+ for (const row of effect) {
220
+ const f = dayOf(row.d);
221
+ // The row with no node id carries the day's effect-run count.
222
+ if (row.nid === null) f.effectRuns += num(row.n);
223
+ else f.effectOpsSum += (nodeOps.get(String(row.nid).split("#")[0] ?? "") ?? 0) * num(row.n);
224
+ }
225
+
176
226
  const byDay = [...days.values()].sort((a, b) => a.day.localeCompare(b.day));
177
227
  const facts = emptyFacts(0);
178
228
  for (const f of byDay) {
@@ -180,3 +230,448 @@ export async function computeWorkflowWindow(
180
230
  }
181
231
  return { status: "ok", facts, byDay };
182
232
  }
233
+
234
+ /** One script's facts per UTC day. */
235
+ export type ScriptDayFacts = ScriptFacts & { day: string };
236
+ export type ScriptWindowFacts = { scriptName: string; byDay: ScriptDayFacts[] };
237
+
238
+ /** Source that can create an agent task or start a workflow; only these scripts are probed for effects. */
239
+ const DISPATCH_SQL =
240
+ "(source LIKE '%task_send%' OR source LIKE '%send_task%' OR source LIKE '%sendTask%' OR source LIKE '%workflow_trigger%')";
241
+
242
+ /** The script_runs filter of a window, narrowed to one script name (runs without one by INLINE_SCRIPT_NAME). */
243
+ function scriptRunsFilter(
244
+ window: { start: string; end: string },
245
+ opts: { scriptName?: string },
246
+ ): { where: string; params: string[] } {
247
+ const span = [window.start, window.end];
248
+ return opts.scriptName === undefined
249
+ ? { where: "", params: span }
250
+ : {
251
+ where: "AND coalesce(scriptName, ?)=?",
252
+ params: [...span, INLINE_SCRIPT_NAME, opts.scriptName],
253
+ };
254
+ }
255
+
256
+ /** Runs of every script (or of one script) in the window. */
257
+ export async function countScriptRuns(
258
+ window: { start: string; end: string },
259
+ sql: SavingsSql = defaultSql,
260
+ opts: { scriptName?: string } = {},
261
+ ): Promise<number> {
262
+ const { where, params } = scriptRunsFilter(window, opts);
263
+ const rows = await sql<{ n: number }>(
264
+ `SELECT count(*) n FROM script_runs WHERE startedAt>=? AND startedAt<? ${where}`,
265
+ params,
266
+ );
267
+ return num(rows[0]?.n);
268
+ }
269
+
270
+ /**
271
+ * Facts of every script with runs in the window (or of one script), grouped by
272
+ * the UTC day (or minute) the runs started. Ported from v7 `scriptJobs`: runs are keyed by
273
+ * `scriptName` (runs without one by INLINE_SCRIPT_NAME), ops are the `await`
274
+ * count of the catalog source (the global row wins), and a run had an effect
275
+ * when its output names an agent task created while it ran (up to 20 minutes
276
+ * after it started), counted on the day the run started. v7 folds names beyond its first 900 into a tail row; here
277
+ * every name keeps its own row and ops.
278
+ */
279
+ export async function computeScriptWindow(
280
+ window: { start: string; end: string },
281
+ sql: SavingsSql = defaultSql,
282
+ opts: { scriptName?: string; bucket?: SavingsBucket } = {},
283
+ ): Promise<ScriptWindowFacts[]> {
284
+ const span = [window.start, window.end];
285
+ const { where, params } = scriptRunsFilter(window, opts);
286
+ const runs = await sql<{ d: string; nm: string; n: number; api: number; secs: number | null }>(
287
+ `SELECT ${bucketSql("startedAt", opts.bucket)} d, coalesce(scriptName,'${INLINE_SCRIPT_NAME}') nm, count(*) n, sum(apiEndpointId IS NOT NULL) api,
288
+ sum((julianday(coalesce(finishedAt,startedAt))-julianday(startedAt))*86400) secs
289
+ FROM script_runs WHERE startedAt>=? AND startedAt<? ${where} GROUP BY 1,2`,
290
+ params,
291
+ );
292
+ if (runs.length === 0) return [];
293
+ const names = [...new Set(runs.map((r) => String(r.nm)))].filter((n) => n !== INLINE_SCRIPT_NAME);
294
+ const ops = await scriptOps(names, sql);
295
+
296
+ const dispatchers: string[] = [];
297
+ for (let i = 0; i < names.length; i += 500) {
298
+ const chunk = names.slice(i, i + 500);
299
+ const rows = await sql<{ name: string }>(
300
+ `SELECT DISTINCT name FROM scripts WHERE isScratch=0 AND name IN (${chunk.map(() => "?").join(",")}) AND ${DISPATCH_SQL}`,
301
+ chunk,
302
+ );
303
+ dispatchers.push(...rows.map((r) => String(r.name)));
304
+ }
305
+ // Effect runs per day the run started, like their runs: a run at 23:59 whose
306
+ // task lands after midnight still credits its own day, so tasks are read up
307
+ // to 20 minutes past the window end.
308
+ const effects = new Map<string, { other: number; api: number }>();
309
+ // A task stamped with the run that created it (its run token) links
310
+ // exactly; the output probe covers unstamped tasks of dispatching scripts.
311
+ const tasksTo = "strftime('%Y-%m-%dT%H:%M:%fZ',?,'+20 minutes')";
312
+ const probe =
313
+ dispatchers.length > 0
314
+ ? `UNION SELECT ${bucketSql("r.startedAt", opts.bucket)} d, r.scriptName nm, (r.apiEndpointId IS NOT NULL) api, r.id
315
+ FROM agent_tasks t INDEXED BY idx_agent_tasks_created
316
+ JOIN script_runs r INDEXED BY idx_script_runs_scriptName_startedAt ON r.scriptName IN (${dispatchers.map(() => "?").join(",")})
317
+ 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||'%'
318
+ AND r.startedAt>=? AND r.startedAt<?
319
+ WHERE t.createdAt>=? AND t.createdAt<${tasksTo} AND t.sourceScriptRunId IS NULL`
320
+ : "";
321
+ const rows = await sql<{ d: string; nm: string; api: number; n: number }>(
322
+ `SELECT d, nm, api, count(DISTINCT id) n FROM (
323
+ SELECT ${bucketSql("r.startedAt", opts.bucket)} d, coalesce(r.scriptName,'${INLINE_SCRIPT_NAME}') nm, (r.apiEndpointId IS NOT NULL) api, r.id
324
+ FROM agent_tasks t INDEXED BY idx_agent_tasks_sourceScriptRun_created JOIN script_runs r ON r.id=t.sourceScriptRunId
325
+ WHERE t.sourceScriptRunId IS NOT NULL AND t.createdAt>=? AND t.createdAt<${tasksTo}
326
+ AND r.startedAt>=? AND r.startedAt<? ${opts.scriptName === undefined ? "" : "AND coalesce(r.scriptName, ?)=?"}
327
+ ${probe}
328
+ ) GROUP BY 1,2,3`,
329
+ [
330
+ ...span,
331
+ ...span,
332
+ ...(opts.scriptName === undefined ? [] : [INLINE_SCRIPT_NAME, opts.scriptName]),
333
+ ...(dispatchers.length > 0 ? [...dispatchers, ...span, ...span] : []),
334
+ ],
335
+ );
336
+ for (const row of rows) {
337
+ const key = `${row.nm}\u0000${row.d}`;
338
+ const e = effects.get(key) ?? { other: 0, api: 0 };
339
+ if (num(row.api)) e.api += num(row.n);
340
+ else e.other += num(row.n);
341
+ effects.set(key, e);
342
+ }
343
+
344
+ const byName = new Map<string, ScriptDayFacts[]>();
345
+ const push = (nm: string, f: ScriptDayFacts) => byName.set(nm, [...(byName.get(nm) ?? []), f]);
346
+ for (const r of runs) {
347
+ const nm = String(r.nm);
348
+ const n = num(r.n);
349
+ const perRun = nm === INLINE_SCRIPT_NAME ? INLINE_OPS : (ops.get(nm) ?? DEFAULT_OPS);
350
+ const e = effects.get(`${nm}\u0000${r.d}`);
351
+ push(nm, {
352
+ day: String(r.d),
353
+ runs: n,
354
+ apiRuns: num(r.api),
355
+ effectRuns: e?.other ?? 0,
356
+ apiEffectRuns: e?.api ?? 0,
357
+ opsSum: perRun * n,
358
+ computeSecs: num(r.secs),
359
+ });
360
+ }
361
+ return [...byName.entries()]
362
+ .map(([scriptName, byDay]) => ({
363
+ scriptName,
364
+ byDay: byDay.sort((a, b) => a.day.localeCompare(b.day)),
365
+ }))
366
+ .sort((a, b) => a.scriptName.localeCompare(b.scriptName));
367
+ }
368
+
369
+ /** A workflow's link to something its runs caused, for one UTC day. */
370
+ export type SavingsLink = {
371
+ parentJobId: string;
372
+ childKind: "workflow" | "script" | "task";
373
+ /** Workflow id, script name, or "" for tasks. */
374
+ childJobId: string;
375
+ /**
376
+ * `sub-workflow`: child run of a sub-workflow node (parentStepId).
377
+ * `step-workflow`, `step-script`, `step-task`: a run, nested script run or
378
+ * task a swarm-script step made. `descendant-task`: a task below the
379
+ * agent-task nodes' tasks (parentTaskId).
380
+ */
381
+ linkKind: "sub-workflow" | "step-workflow" | "step-script" | "step-task" | "descendant-task";
382
+ n: number;
383
+ /** Session cost of linked tasks (with their descendants for `step-task`); 0 for runs. */
384
+ actualUsd: number;
385
+ /** The part of `actualUsd` the parent's own row keeps on both sides. */
386
+ keptUsd: number;
387
+ };
388
+
389
+ export type WorkflowLinksDay = {
390
+ links: SavingsLink[];
391
+ /** Per parent workflow: spend of the tasks it caused without owning them (`WorkflowFacts.childTaskUsd`). */
392
+ childTasks: Map<string, { usd: number; ms: number }>;
393
+ };
394
+
395
+ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
396
+ /** A run or task a step made starts while the step runs, or within 5 s of its end. */
397
+ const STEP_GRACE_MS = 5_000;
398
+ /** Deepest task chain followed below a root task (the deepest seen is 17). */
399
+ const MAX_TASK_DEPTH = 20;
400
+
401
+ async function inChunks<T>(ids: string[], fn: (chunk: string[]) => Promise<T[]>): Promise<T[]> {
402
+ const out: T[] = [];
403
+ for (let i = 0; i < ids.length; i += 500) out.push(...(await fn(ids.slice(i, i + 500))));
404
+ return out;
405
+ }
406
+
407
+ const marks = (n: number) => Array.from({ length: n }, () => "?").join(",");
408
+
409
+ /**
410
+ * What every workflow's runs caused on one UTC day (by the child's start),
411
+ * for the "with components" view and the kept spend of unowned tasks.
412
+ *
413
+ * - Sub-workflow children: `parentStepId`, exact.
414
+ * - Runs, tasks and nested script runs a swarm-script step made: the step id
415
+ * its run token stamped (`sourceStepId`). Unstamped runs and tasks (made
416
+ * before the stamp existed, or by a run with no token) fall back to an id in
417
+ * the step's output plus a start inside the step; stamped rows never take
418
+ * that path. Nested script runs are linked only when stamped: matching them
419
+ * by time is too noisy (agents call the same scripts by hand).
420
+ * - Task spend: the tasks the steps made, and the descendants (`parentTaskId`,
421
+ * stopping at a task with its own workflow run) of those and of the
422
+ * agent-task nodes' tasks.
423
+ */
424
+ export async function computeWorkflowLinksDay(
425
+ window: { start: string; end: string },
426
+ workflows: { id: string; definition: unknown }[],
427
+ sql: SavingsSql = defaultSql,
428
+ ): Promise<WorkflowLinksDay> {
429
+ const span = [window.start, window.end];
430
+ const links = new Map<string, SavingsLink>();
431
+ const add = (l: Omit<SavingsLink, "actualUsd" | "keptUsd"> & { usd?: number }) => {
432
+ const key = [l.parentJobId, l.childKind, l.childJobId, l.linkKind].join("\u0000");
433
+ const prev = links.get(key);
434
+ const usd = l.usd ?? 0;
435
+ links.set(key, {
436
+ parentJobId: l.parentJobId,
437
+ childKind: l.childKind,
438
+ childJobId: l.childJobId,
439
+ linkKind: l.linkKind,
440
+ n: (prev?.n ?? 0) + l.n,
441
+ actualUsd: (prev?.actualUsd ?? 0) + usd,
442
+ keptUsd: (prev?.keptUsd ?? 0) + (l.childKind === "task" ? usd : 0),
443
+ });
444
+ };
445
+
446
+ const subRuns = await sql<{ pid: string; cid: string; n: number }>(
447
+ `SELECT p.workflowId pid, c.workflowId cid, count(*) n FROM workflow_runs c INDEXED BY idx_workflow_runs_parentStep_attempt
448
+ JOIN workflow_run_steps s ON s.id=c.parentStepId JOIN workflow_runs p ON p.id=s.runId
449
+ WHERE c.parentStepId IS NOT NULL AND c.startedAt>=? AND c.startedAt<? GROUP BY 1,2`,
450
+ span,
451
+ );
452
+ for (const r of subRuns) {
453
+ add({
454
+ parentJobId: r.pid,
455
+ childKind: "workflow",
456
+ childJobId: r.cid,
457
+ linkKind: "sub-workflow",
458
+ n: num(r.n),
459
+ });
460
+ }
461
+ const stampedRuns = await sql<{ pid: string; cid: string; n: number }>(
462
+ `SELECT p.workflowId pid, c.workflowId cid, count(*) n FROM workflow_runs c INDEXED BY idx_workflow_runs_sourceStep_started
463
+ JOIN workflow_run_steps s ON s.id=c.sourceStepId JOIN workflow_runs p ON p.id=s.runId
464
+ WHERE c.sourceStepId IS NOT NULL AND c.startedAt>=? AND c.startedAt<? GROUP BY 1,2`,
465
+ span,
466
+ );
467
+ for (const r of stampedRuns) {
468
+ add({
469
+ parentJobId: r.pid,
470
+ childKind: "workflow",
471
+ childJobId: r.cid,
472
+ linkKind: "step-workflow",
473
+ n: num(r.n),
474
+ });
475
+ }
476
+ const stampedScripts = await sql<{ pid: string; nm: string; n: number }>(
477
+ `SELECT p.workflowId pid, coalesce(r.scriptName,'${INLINE_SCRIPT_NAME}') nm, count(*) n FROM script_runs r INDEXED BY idx_script_runs_sourceStep_started
478
+ JOIN workflow_run_steps s ON s.id=r.sourceStepId JOIN workflow_runs p ON p.id=s.runId
479
+ WHERE r.sourceStepId IS NOT NULL AND r.startedAt>=? AND r.startedAt<? GROUP BY 1,2`,
480
+ span,
481
+ );
482
+ for (const r of stampedScripts) {
483
+ add({
484
+ parentJobId: r.pid,
485
+ childKind: "script",
486
+ childJobId: String(r.nm),
487
+ linkKind: "step-script",
488
+ n: num(r.n),
489
+ });
490
+ }
491
+
492
+ // Tasks the steps made, per parent workflow.
493
+ const stepTasks = new Map<string, string>();
494
+ for (const r of await sql<{ pid: string; id: string }>(
495
+ `SELECT p.workflowId pid, t.id FROM agent_tasks t INDEXED BY idx_agent_tasks_sourceStep_created
496
+ JOIN workflow_run_steps s ON s.id=t.sourceStepId JOIN workflow_runs p ON p.id=s.runId
497
+ WHERE t.sourceStepId IS NOT NULL AND t.createdAt>=? AND t.createdAt<?`,
498
+ span,
499
+ )) {
500
+ stepTasks.set(String(r.id), String(r.pid));
501
+ }
502
+
503
+ await linkFromStepOutputs(window, workflows, sql, (pid, kind, id, childWorkflowId) => {
504
+ if (kind === "task") {
505
+ if (!stepTasks.has(id)) stepTasks.set(id, pid);
506
+ } else {
507
+ add({
508
+ parentJobId: pid,
509
+ childKind: "workflow",
510
+ childJobId: childWorkflowId as string,
511
+ linkKind: "step-workflow",
512
+ n: 1,
513
+ });
514
+ }
515
+ });
516
+
517
+ // Agent-task nodes' tasks: their own cost is in the row already; only their descendants add.
518
+ const nodeTasks = new Map<string, string>();
519
+ for (const r of await sql<{ pid: string; id: string }>(
520
+ `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
521
+ WHERE t.createdAt>=? AND t.createdAt<? AND t.workflowRunId IS NOT NULL`,
522
+ span,
523
+ )) {
524
+ nodeTasks.set(String(r.id), String(r.pid));
525
+ }
526
+
527
+ const childTasks = new Map<string, { usd: number; ms: number }>();
528
+ const keep = (pid: string, usd: number, ms: number) => {
529
+ const c = childTasks.get(pid) ?? { usd: 0, ms: 0 };
530
+ childTasks.set(pid, { usd: c.usd + usd, ms: c.ms + ms });
531
+ };
532
+ // Each task counts under exactly one root: the walk stops at any other root
533
+ // of the day and at any task a step or a node owns (on any day), so all
534
+ // roots go in as one set.
535
+ const roots = [...new Set([...stepTasks.keys(), ...nodeTasks.keys()])];
536
+ const trees =
537
+ roots.length === 0
538
+ ? []
539
+ : await sql<{
540
+ root: string;
541
+ below: number;
542
+ n: number;
543
+ usd: number | null;
544
+ ms: number | null;
545
+ }>(
546
+ `WITH RECURSIVE r(id) AS (SELECT value FROM json_each(?)),
547
+ d(root, id, depth) AS (
548
+ SELECT id, id, 0 FROM r
549
+ 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
550
+ WHERE k.workflowRunId IS NULL AND k.sourceStepId IS NULL AND k.id NOT IN (SELECT id FROM r)
551
+ AND d.depth<${MAX_TASK_DEPTH})
552
+ SELECT root, depth>0 below, count(*) n,
553
+ sum((SELECT sum(totalCostUsd) FROM session_costs c WHERE c.taskId=d.id)) usd,
554
+ sum((SELECT sum(durationMs) FROM session_costs c WHERE c.taskId=d.id)) ms
555
+ FROM d GROUP BY 1,2`,
556
+ [JSON.stringify(roots)],
557
+ );
558
+ for (const t of trees) {
559
+ const root = String(t.root);
560
+ const below = num(t.below) === 1;
561
+ const fromStep = stepTasks.get(root);
562
+ const pid = fromStep ?? nodeTasks.get(root);
563
+ if (!pid) continue;
564
+ // A node task's own cost is the row's agentUsd; a step task counts whole.
565
+ if (!fromStep && !below) continue;
566
+ const usd = num(t.usd);
567
+ keep(pid, usd, num(t.ms));
568
+ if (fromStep) {
569
+ // n counts the tasks the step made; their descendants add only spend.
570
+ add({
571
+ parentJobId: pid,
572
+ childKind: "task",
573
+ childJobId: "",
574
+ linkKind: "step-task",
575
+ n: below ? 0 : num(t.n),
576
+ usd,
577
+ });
578
+ } else {
579
+ add({
580
+ parentJobId: pid,
581
+ childKind: "task",
582
+ childJobId: "",
583
+ linkKind: "descendant-task",
584
+ n: num(t.n),
585
+ usd,
586
+ });
587
+ }
588
+ }
589
+ return { links: [...links.values()], childTasks };
590
+ }
591
+
592
+ /**
593
+ * The unstamped fallback: runs and tasks whose id a dispatching step's output
594
+ * names and that started while the step ran. Only steps of nodes whose script
595
+ * can dispatch (`DISPATCH_SQL`) are read.
596
+ */
597
+ async function linkFromStepOutputs(
598
+ window: { start: string; end: string },
599
+ workflows: { id: string; definition: unknown }[],
600
+ sql: SavingsSql,
601
+ onLink: (
602
+ parentWorkflowId: string,
603
+ kind: "workflow" | "task",
604
+ id: string,
605
+ childWorkflowId?: string,
606
+ ) => void,
607
+ ): Promise<void> {
608
+ const nodesByWorkflow = new Map<string, { nodeId: string; scriptName: string }[]>();
609
+ for (const w of workflows) {
610
+ const nodes =
611
+ (
612
+ (w.definition ?? {}) as {
613
+ nodes?: { id: string; type: string; config?: Record<string, unknown> }[];
614
+ }
615
+ ).nodes ?? [];
616
+ const scripted = nodes
617
+ .filter((n) => n.type === "swarm-script" && typeof n.config?.scriptName === "string")
618
+ .map((n) => ({ nodeId: n.id, scriptName: n.config?.scriptName as string }));
619
+ if (scripted.length > 0) nodesByWorkflow.set(w.id, scripted);
620
+ }
621
+ const names = [...new Set([...nodesByWorkflow.values()].flat().map((n) => n.scriptName))];
622
+ if (names.length === 0) return;
623
+ const dispatchers = new Set(
624
+ (
625
+ await inChunks(names, (chunk) =>
626
+ sql<{ name: string }>(
627
+ `SELECT DISTINCT name FROM scripts WHERE isScratch=0 AND name IN (${marks(chunk.length)}) AND ${DISPATCH_SQL}`,
628
+ chunk,
629
+ ),
630
+ )
631
+ ).map((r) => String(r.name)),
632
+ );
633
+ for (const [workflowId, nodes] of nodesByWorkflow) {
634
+ const nodeIds = nodes.filter((n) => dispatchers.has(n.scriptName)).map((n) => n.nodeId);
635
+ if (nodeIds.length === 0) continue;
636
+ const steps = await sql<{ id: string; sa: string; fa: string; output: string | null }>(
637
+ `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
638
+ JOIN workflow_run_steps s ON s.runId=p.id
639
+ WHERE p.workflowId=? AND p.startedAt>=? AND p.startedAt<? AND s.nodeType='swarm-script' AND s.output IS NOT NULL
640
+ AND (s.nodeId IN (${marks(nodeIds.length)}) OR ${nodeIds.map(() => "s.nodeId LIKE ?").join(" OR ")})`,
641
+ [workflowId, window.start, window.end, ...nodeIds, ...nodeIds.map((id) => `${id}#%`)],
642
+ );
643
+ const named = new Map<string, { sa: number; fa: number }[]>();
644
+ for (const s of steps) {
645
+ const range = { sa: Date.parse(s.sa), fa: Date.parse(s.fa) + STEP_GRACE_MS };
646
+ for (const id of new Set(String(s.output).toLowerCase().match(UUID_RE) ?? [])) {
647
+ if (id === String(s.id)) continue;
648
+ named.set(id, [...(named.get(id) ?? []), range]);
649
+ }
650
+ }
651
+ if (named.size === 0) continue;
652
+ const inStep = (id: string, at: string) =>
653
+ (named.get(id) ?? []).some((r) => Date.parse(at) >= r.sa && Date.parse(at) <= r.fa);
654
+ const ids = [...named.keys()];
655
+ const runs = await inChunks(ids, (chunk) =>
656
+ sql<{ id: string; wid: string; at: string }>(
657
+ `SELECT id, workflowId wid, startedAt at FROM workflow_runs WHERE id IN (${marks(chunk.length)})
658
+ AND parentStepId IS NULL AND sourceStepId IS NULL AND triggerType IN ('api','manual')`,
659
+ chunk,
660
+ ),
661
+ );
662
+ for (const r of runs) {
663
+ if (inStep(String(r.id), String(r.at)))
664
+ onLink(workflowId, "workflow", String(r.id), String(r.wid));
665
+ }
666
+ const tasks = await inChunks(ids, (chunk) =>
667
+ sql<{ id: string; at: string }>(
668
+ `SELECT id, createdAt at FROM agent_tasks WHERE id IN (${marks(chunk.length)})
669
+ AND workflowRunId IS NULL AND sourceStepId IS NULL`,
670
+ chunk,
671
+ ),
672
+ );
673
+ for (const t of tasks) {
674
+ if (inStep(String(t.id), String(t.at))) onLink(workflowId, "task", String(t.id));
675
+ }
676
+ }
677
+ }