@desplega.ai/agent-swarm 2.8.1 → 2.8.2

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 (194) hide show
  1. package/dist/{acp-adapter-pdy3qsvg.js → acp-adapter-fqzkxyra.js} +3 -3
  2. package/dist/{actions-pwjpn0j6.js → actions-kxek041g.js} +17 -17
  3. package/dist/{amp-adapter-cq9jgj6x.js → amp-adapter-ce7jjke4.js} +1 -1
  4. package/dist/{app-cnfffgwg.js → app-v6zz8yh0.js} +3 -3
  5. package/dist/{assistant-kpn317y1.js → assistant-m0sw9xx2.js} +18 -18
  6. package/dist/{boot-args-schema-pbbnhmc3.js → boot-args-schema-66bk37wv.js} +1 -1
  7. package/dist/{boot-reembed-9m0ysxma.js → boot-reembed-edjpwsc1.js} +1 -1
  8. package/dist/{boot-reembed-majbn53m.js → boot-reembed-y27n09tz.js} +1 -1
  9. package/dist/{boot-scrub-sweep-app8g8ym.js → boot-scrub-sweep-1xc35965.js} +3 -3
  10. package/dist/{boot-seeds-pbtmvcjm.js → boot-seeds-7hjj91qj.js} +4 -4
  11. package/dist/{boxd-qbkxy6ap.js → boxd-ent8ch04.js} +1 -1
  12. package/dist/{claude-adapter-wn1g3qp5.js → claude-adapter-stw7jdcf.js} +3 -3
  13. package/dist/{claude-managed-setup-pd47nzch.js → claude-managed-setup-y6z2perp.js} +1 -1
  14. package/dist/{claude-sdk-session-3a2a6589.js → claude-sdk-session-vvya8wqk.js} +3 -3
  15. package/dist/{cli-wk18cm92.js → cli-0cq8y6m7.js} +1 -1
  16. package/dist/{cli-p1w18yhx.js → cli-1pz0330a.js} +1 -1
  17. package/dist/{cli-d3p5vwbk.js → cli-1qkz151v.js} +3 -3
  18. package/dist/{cli-89cqnasv.js → cli-26ctbcdp.js} +18 -6
  19. package/dist/{cli-syybb0p1.js → cli-2kvhc7x8.js} +7 -7
  20. package/dist/{cli-93k32c37.js → cli-3e875j5p.js} +128 -41
  21. package/dist/{cli-k0615eh8.js → cli-3sy2xags.js} +10 -10
  22. package/dist/{cli-dy32zecz.js → cli-3vmb0n58.js} +1 -1
  23. package/dist/{cli-4r05hnqa.js → cli-4vzgeta4.js} +13 -13
  24. package/dist/{cli-b5rs97a6.js → cli-5y340nzn.js} +4 -4
  25. package/dist/{cli-7p1kvkck.js → cli-6rc5frdm.js} +1 -1
  26. package/dist/{cli-jcpr5smb.js → cli-837vfs2x.js} +2 -2
  27. package/dist/{cli-b085njxz.js → cli-959kp5h2.js} +12 -11
  28. package/dist/{cli-k93bq1wq.js → cli-97ae65rz.js} +4 -4
  29. package/dist/{cli-m4dqmnbp.js → cli-9mb2q6pb.js} +1 -1
  30. package/dist/{cli-bb431xey.js → cli-a0z912j7.js} +121 -33
  31. package/dist/{cli-k26bkr9t.js → cli-b98a65ed.js} +3 -3
  32. package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
  33. package/dist/{cli-tk7cjj8h.js → cli-dzpc6en0.js} +1 -1
  34. package/dist/{cli-6mma83xa.js → cli-e1p3n5gq.js} +4 -4
  35. package/dist/{cli-re4raaj0.js → cli-f4e8r23x.js} +1 -1
  36. package/dist/{cli-qmqk2yc2.js → cli-f4r3g076.js} +1 -1
  37. package/dist/{cli-pcad4cb1.js → cli-f6bahpn5.js} +1 -1
  38. package/dist/{cli-b8e9nb04.js → cli-fpjmegdb.js} +1 -1
  39. package/dist/{cli-0ntbxyaa.js → cli-fwy8kfd6.js} +271 -37
  40. package/dist/{cli-tacge1w0.js → cli-g5mtmf6t.js} +6 -6
  41. package/dist/{cli-sn7rtnj4.js → cli-gyt3zydq.js} +3 -3
  42. package/dist/{cli-vbh10fqa.js → cli-j24zbska.js} +3 -3
  43. package/dist/{cli-vqptjbr7.js → cli-jdknh18m.js} +10 -10
  44. package/dist/{cli-7b8sbmag.js → cli-kjtwrhea.js} +1 -1
  45. package/dist/{cli-9vhebtjz.js → cli-mxn1qvbn.js} +3 -2
  46. package/dist/{cli-zcsw143p.js → cli-n6vtrcht.js} +1 -1
  47. package/dist/{cli-2zp0et3v.js → cli-pchypa1s.js} +55 -19
  48. package/dist/{cli-gax7fk3t.js → cli-pfs8adn4.js} +1 -1
  49. package/dist/{cli-1xh9a7hn.js → cli-q24n86d2.js} +2 -2
  50. package/dist/{cli-7w69ne2f.js → cli-rcecc3yq.js} +167 -43
  51. package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
  52. package/dist/{cli-yn2bbre9.js → cli-rmzsadkf.js} +1 -1
  53. package/dist/{cli-a3b239vq.js → cli-t2tma8gb.js} +1 -1
  54. package/dist/{cli-9wngrawf.js → cli-tekytdq9.js} +2 -2
  55. package/dist/{cli-tqegb8eq.js → cli-vdektqgf.js} +1 -1
  56. package/dist/{cli-cyhbbd1z.js → cli-w401b9tq.js} +1 -1
  57. package/dist/{cli-jywyhqws.js → cli-xf3qw745.js} +3 -3
  58. package/dist/{cli-hxpyc9sn.js → cli-z1w943va.js} +2 -2
  59. package/dist/{cli-yncmerje.js → cli-zh9rsbqf.js} +2 -2
  60. package/dist/cli.js +16 -16
  61. package/dist/{codex-adapter-nha71q3n.js → codex-adapter-zerf5qsp.js} +1 -1
  62. package/dist/{codex-hook-h3vk6xzr.js → codex-hook-30gyhzxe.js} +1 -1
  63. package/dist/{codex-session-runner-ak9x1k1h.js → codex-session-runner-89s304py.js} +1 -1
  64. package/dist/{commands-f587qpq8.js → commands-jeh1b51j.js} +3 -3
  65. package/dist/{controller-hxx8wwy1.js → controller-mctfbrse.js} +3 -3
  66. package/dist/{controllers-connect-k5sg9m9h.js → controllers-connect-nxa1ddwn.js} +18 -18
  67. package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-qj8vehv6.js} +1 -1
  68. package/dist/{db-nzf8zb5z.js → db-2dvay0es.js} +3 -3
  69. package/dist/{db-amm8w15a.js → db-b36qn6k3.js} +2 -2
  70. package/dist/{dispatcher-89zrts8f.js → dispatcher-gndbta01.js} +16 -16
  71. package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-f75sz821.js} +1 -1
  72. package/dist/{e2b-jkwfhbcv.js → e2b-3gpc2n3w.js} +1 -1
  73. package/dist/{e2b-s16txnpx.js → e2b-jbm7mj93.js} +1 -1
  74. package/dist/{embedding-space-ezwenjmj.js → embedding-space-4p05vb2x.js} +6 -6
  75. package/dist/{embeddings-np74ht6g.js → embeddings-m6768mgh.js} +1 -1
  76. package/dist/{external-channel-z46yx9d7.js → external-channel-gjv3jne3.js} +2 -2
  77. package/dist/{fx-adapter-3q12snn6.js → fx-adapter-rpsgb1tw.js} +4 -4
  78. package/dist/{grok-adapter-ahb1w033.js → grok-adapter-n2m3zjg1.js} +4 -4
  79. package/dist/handlers-nv8edn19.js +32 -0
  80. package/dist/{heartbeat-dt9qw9c8.js → heartbeat-a1tv60gt.js} +19 -19
  81. package/dist/{hook-8k6fbz9b.js → hook-8h5dzcgq.js} +2 -2
  82. package/dist/{hook-jgcgygex.js → hook-cyaps9ba.js} +4 -4
  83. package/dist/{http-haw4r8ne.js → http-t15mhbd9.js} +1731 -77
  84. package/dist/{index-s4ewdma4.js → index-ksmyd6kc.js} +16 -16
  85. package/dist/{index-tez78qj3.js → index-qav6455f.js} +13 -11
  86. package/dist/index-rjnrje98.js +32 -0
  87. package/dist/index-tv3413wy.js +33 -0
  88. package/dist/{index-5gk12my8.js → index-w1zqf680.js} +1 -1
  89. package/dist/{keepalive-xn6s7rmg.js → keepalive-91s7hzrb.js} +3 -3
  90. package/dist/{lead-6ygbfhbh.js → lead-3hmddvrm.js} +30 -30
  91. package/dist/{maintenance-vdts800b.js → maintenance-7pjmy5xy.js} +1 -1
  92. package/dist/{oauth-refresh-sweep-094c8wfk.js → oauth-refresh-sweep-rzqfm94j.js} +2 -2
  93. package/dist/{onboard-v99eh56m.js → onboard-74st7pag.js} +3 -3
  94. package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-arn7gm8q.js} +2 -2
  95. package/dist/{otel-impl-q7yr9yp0.js → otel-impl-rnzey8cb.js} +1 -1
  96. package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-6mkwq64n.js} +3 -2
  97. package/dist/{pricing-refresh-7dh2yase.js → pricing-refresh-ha21jhk7.js} +2 -2
  98. package/dist/{rbac-roles-npbmdh77.js → rbac-roles-59dxachk.js} +2 -2
  99. package/dist/{rbac-roles-mdmc96p4.js → rbac-roles-wqhma4dr.js} +3 -3
  100. package/dist/{render-v2-twhhwmms.js → render-v2-14kpzx12.js} +3 -3
  101. package/dist/{resume-5gsrjd5e.js → resume-gsa5fb5f.js} +6 -6
  102. package/dist/{session-access-m191x30x.js → session-access-skm7bnp6.js} +4 -4
  103. package/dist/{session-source-backfill-nt923ask.js → session-source-backfill-pbqzbncv.js} +2 -2
  104. package/dist/{setup-wv467afy.js → setup-5yermsem.js} +1 -1
  105. package/dist/{work-objects-8zkrpy13.js → work-objects-xj0ck0w4.js} +19 -19
  106. package/dist/{worker-follow-up-cecqszem.js → worker-follow-up-911xc0b8.js} +18 -16
  107. package/dist/{worker-mz5z7kj0.js → worker-qgg0m2gw.js} +30 -30
  108. package/openapi.json +1741 -290
  109. package/package.json +2 -2
  110. package/src/apps/catalog.generated.json +120 -1
  111. package/src/apps/definition.ts +38 -11
  112. package/src/apps/page-validator.ts +88 -0
  113. package/src/be/db/model-profiles.ts +110 -11
  114. package/src/be/db/tasks/read.ts +20 -0
  115. package/src/be/db/workflow-run-definitions.ts +19 -8
  116. package/src/be/db-client.ts +43 -5
  117. package/src/be/db.ts +9 -3
  118. package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
  119. package/src/be/model-profile-check.ts +43 -18
  120. package/src/be/runtime-pools/routing.ts +1 -0
  121. package/src/be/savings/calibrate.ts +468 -0
  122. package/src/be/savings/compute.ts +182 -0
  123. package/src/be/savings/model.ts +406 -0
  124. package/src/be/scripts/typecheck.ts +5 -0
  125. package/src/be/seed/agent-fs-provision.ts +48 -11
  126. package/src/be/seed/workflows-seeder.ts +67 -23
  127. package/src/be/skill-parser.ts +19 -7
  128. package/src/commands/onboard/agent-fs-version.ts +1 -1
  129. package/src/commands/provider-error-class.ts +97 -0
  130. package/src/commands/runner.ts +99 -17
  131. package/src/extensions/contract-types.generated.ts +1 -1
  132. package/src/http/all-routes.ts +2 -0
  133. package/src/http/fs.ts +8 -2
  134. package/src/http/index.ts +4 -0
  135. package/src/http/model-profiles.ts +43 -10
  136. package/src/http/poll.ts +1 -0
  137. package/src/http/savings-calibration.ts +277 -0
  138. package/src/http/savings.ts +363 -0
  139. package/src/http/tasks.ts +46 -4
  140. package/src/http/trackers/authorize-gate.ts +41 -0
  141. package/src/http/trackers/jira.ts +26 -4
  142. package/src/http/trackers/linear.ts +26 -4
  143. package/src/integrations/chat-sdk/limits.ts +6 -1
  144. package/src/jira/oauth.ts +7 -1
  145. package/src/linear/README.md +2 -1
  146. package/src/linear/oauth.ts +7 -1
  147. package/src/providers/amp-adapter.ts +1 -1
  148. package/src/providers/codex-adapter.ts +3 -0
  149. package/src/providers/pi-mono-adapter.ts +6 -5
  150. package/src/providers/types.ts +7 -0
  151. package/src/scripts-runtime/sdk-allowlist.ts +11 -1
  152. package/src/scripts-runtime/swarm-sdk.ts +6 -0
  153. package/src/scripts-runtime/types/stdlib.d.ts +9 -0
  154. package/src/scripts-runtime/types/swarm-extension.d.ts +34 -0
  155. package/src/scripts-runtime/types/swarm-sdk.d.ts +9 -0
  156. package/src/tasks/worker-follow-up.ts +142 -3
  157. package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
  158. package/src/tests/apps-chart-shell.test.ts +170 -0
  159. package/src/tests/apps-icon.test.ts +156 -2
  160. package/src/tests/chat-sdk-relay.test.ts +12 -0
  161. package/src/tests/codex-adapter.test.ts +11 -0
  162. package/src/tests/comb-default.test.ts +6 -0
  163. package/src/tests/core-auth.test.ts +7 -6
  164. package/src/tests/db-client-busy-retry.test.ts +58 -6
  165. package/src/tests/deploy-guard.test.ts +154 -0
  166. package/src/tests/docs-index-footprint.test.js +3 -3
  167. package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
  168. package/src/tests/model-profile-fallbacks.test.ts +482 -0
  169. package/src/tests/model-profiles-api.test.ts +1 -0
  170. package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
  171. package/src/tests/provider-error-class.test.ts +174 -0
  172. package/src/tests/runner-provider-fallback.test.ts +197 -0
  173. package/src/tests/savings-calibration-api.test.ts +264 -0
  174. package/src/tests/savings-calibration.test.ts +201 -0
  175. package/src/tests/savings-compute.test.ts +406 -0
  176. package/src/tests/savings-model.test.ts +287 -0
  177. package/src/tests/script-connections.test.ts +2 -0
  178. package/src/tests/sdk-allowlist.test.ts +40 -0
  179. package/src/tests/seed-workflows.test.ts +167 -11
  180. package/src/tests/skill-parser.test.ts +45 -0
  181. package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
  182. package/src/tests/workflow-definition-pinning.test.ts +128 -3
  183. package/src/tests/workflow-script-principal.test.ts +94 -4
  184. package/src/tools/app-upsert.ts +1 -1
  185. package/src/tools/model-profiles/list-model-profiles.ts +4 -2
  186. package/src/tools/update-profile.ts +1 -1
  187. package/src/types.ts +115 -33
  188. package/src/utils/constants.ts +2 -0
  189. package/templates/skills/apps/SKILL.md +62 -3
  190. package/templates/skills/apps/content.md +62 -3
  191. package/templates/skills/swarm-docs/content.md +2 -0
  192. package/dist/handlers-vbww69re.js +0 -32
  193. package/dist/index-4xwaf5th.js +0 -32
  194. package/dist/index-f0hcrs8e.js +0 -33
@@ -0,0 +1,468 @@
1
+ /**
2
+ * Re-derive the automation-savings session curve from this deployment's own
3
+ * `session_costs`, and optionally store it so the savings endpoints use it
4
+ * instead of the constants shipped in `src/be/savings/model.ts`.
5
+ *
6
+ * Served by `POST /api/savings/calibration` (`src/http/savings-calibration.ts`), which
7
+ * also owns the deadline, the one-run-at-a-time lock and the config write. Delete the
8
+ * global `SAVINGS_CURVE_CALIBRATION` row to go back to the shipped curve.
9
+ *
10
+ * Method, rebuilt from the v7 calibration notes (research/cost/2026-11-05); it reproduces
11
+ * the shipped curve to about 1% on session-weighted average, not point for point:
12
+ * - cost(t, tier): 10%-trimmed mean, over this window's opus 5.5 sessions of
13
+ * exactly t turns, of the session's opus tokens repriced at the tier's list
14
+ * prices plus the stored cost of its other models (sub-agents), t = 1..61.
15
+ * The curve is then smoothed with a +-2 turn local linear fit and made
16
+ * non-decreasing.
17
+ * - hrs(t, tier): the same for agent-active hours (durationMs) on opus,
18
+ * times the tier's speed against opus (median ms per turn).
19
+ * - Coverage: a turn count with fewer than MIN_SESSIONS_PER_TURN sessions is unsupported.
20
+ * Gaps between supported turn counts are interpolated. The curve is refused unless the
21
+ * supported counts reach MIN_LOW_TURN at the bottom and MIN_HIGH_TURN at the top. Past the
22
+ * outermost supported count the shipped curve's shape is used, scaled to meet that count.
23
+ */
24
+ import type { SavingsSql } from "./compute";
25
+ import {
26
+ CALIBRATION_MODEL,
27
+ CURVE,
28
+ type CurveSet,
29
+ SAVINGS_TIERS,
30
+ type SavingsTier,
31
+ TAU_MAX,
32
+ } from "./model";
33
+
34
+ /** The model each tier bills at. */
35
+ export const TIER_MODEL: Record<SavingsTier, string> = {
36
+ smol: "claude-haiku-5-5",
37
+ regular: "claude-sonnet-5-5",
38
+ smart: CALIBRATION_MODEL,
39
+ ultra: "claude-fable-5-1",
40
+ };
41
+
42
+ /** Hours per turn against opus, used when a tier has too few sessions to measure (v7 values). */
43
+ export const SPEED_FALLBACK: Record<SavingsTier, number> = {
44
+ smol: 1.54,
45
+ regular: 1.29,
46
+ smart: 1,
47
+ ultra: 1,
48
+ };
49
+
50
+ const TRIM = 0.1;
51
+ const SMOOTH_HALF_WIDTH = 2;
52
+ /** Fewer sessions than this at one turn count: the point is filled from its neighbours. */
53
+ const MIN_SESSIONS_PER_TURN = 5;
54
+ /** Refuse a curve whose lowest supported turn count is above this: short jobs are what the model prices most. */
55
+ export const MIN_LOW_TURN = 3;
56
+ /** Refuse a curve whose highest supported turn count is below this (tau 20 is 65 ops per run). */
57
+ export const MIN_HIGH_TURN = 20;
58
+ /** Refuse a curve built on fewer supported turn counts than this (of 60). */
59
+ export const MIN_SUPPORTED_TURNS = 15;
60
+ /** Fewer opus sessions than this in the window: refuse to calibrate. */
61
+ export const MIN_SESSIONS = 300;
62
+ /** Fewer sessions than this for a tier model: use SPEED_FALLBACK. */
63
+ const MIN_SPEED_SESSIONS = 30;
64
+ /** A curve whose mean cost is further than this factor from the shipped one is never applied. */
65
+ export const SANITY_FACTOR = 3;
66
+ /** Rows read per query; the read pages by keyset so no query is unbounded. */
67
+ const PAGE = 1000;
68
+ /** Refuse a window with more sessions than this: one run must stay inside the API's memory. */
69
+ export const MAX_SESSIONS_READ = 200_000;
70
+
71
+ /** The data cannot support a curve; the message is the reason shown to the caller. */
72
+ export class CalibrationRefusal extends Error {}
73
+
74
+ /** `CurveSet` with plain arrays: what a derivation produces and the API serializes. */
75
+ export type DerivedCurveSet = Record<SavingsTier, { usd: number[]; hrs: number[] }>;
76
+
77
+ export type OpusSession = {
78
+ turns: number;
79
+ durationMs: number;
80
+ inputTokens: number;
81
+ outputTokens: number;
82
+ cacheReadTokens: number;
83
+ cacheWriteTokens: number;
84
+ /** The cost the harness stored for the opus tokens, for the repricing control. */
85
+ costUsd: number;
86
+ /** Stored cost of the session's other models (sub-agents), kept as is at every tier. */
87
+ otherUsd: number;
88
+ };
89
+ export type TierPrices = Record<"input" | "output" | "cached_input" | "cache_write_1h", number>; // USD per million tokens
90
+ export type TurnDuration = { turns: number; durationMs: number };
91
+
92
+ export type DeriveInput = {
93
+ opus: OpusSession[];
94
+ prices: Record<SavingsTier, TierPrices>;
95
+ /** ms-per-turn samples of each non-opus tier model's own sessions. */
96
+ tierTurns: Partial<Record<SavingsTier, TurnDuration[]>>;
97
+ end: Date;
98
+ };
99
+
100
+ export type DerivedCalibration = {
101
+ calibratedAt: string;
102
+ model: string;
103
+ curve: DerivedCurveSet;
104
+ sessions: number;
105
+ usable: OpusSession[];
106
+ speed: Record<SavingsTier, number>;
107
+ /** Share of sessions whose repriced opus cost is within 1% of the stored cost. */
108
+ repriceMatch: number;
109
+ };
110
+
111
+ export function median(values: number[]): number {
112
+ const sorted = [...values].sort((a, b) => a - b);
113
+ return sorted[Math.floor(sorted.length / 2)] as number;
114
+ }
115
+
116
+ export function trimmedMean(values: number[], trim = TRIM): number {
117
+ const sorted = [...values].sort((a, b) => a - b);
118
+ const cut = Math.floor(sorted.length * trim);
119
+ const kept = sorted.slice(cut, sorted.length - cut);
120
+ return kept.reduce((s, v) => s + v, 0) / kept.length;
121
+ }
122
+
123
+ /**
124
+ * Local linear fit over the defined points within `half` turns, evaluated at each point.
125
+ * Unlike a moving average it does not pull the end points toward their inner neighbours.
126
+ * Undefined points stay undefined.
127
+ */
128
+ function smooth(series: (number | undefined)[], half: number): (number | undefined)[] {
129
+ return series.map((v, i) => {
130
+ if (v === undefined) return undefined;
131
+ const pts: [number, number][] = [];
132
+ for (let j = Math.max(0, i - half); j <= Math.min(series.length - 1, i + half); j++) {
133
+ const y = series[j];
134
+ if (y !== undefined) pts.push([j, y]);
135
+ }
136
+ const n = pts.length;
137
+ const mx = pts.reduce((s, p) => s + p[0], 0) / n;
138
+ const my = pts.reduce((s, p) => s + p[1], 0) / n;
139
+ const sxx = pts.reduce((s, p) => s + (p[0] - mx) ** 2, 0);
140
+ if (sxx === 0) return my;
141
+ const slope = pts.reduce((s, p) => s + (p[0] - mx) * (p[1] - my), 0) / sxx;
142
+ return my + slope * (i - mx);
143
+ });
144
+ }
145
+
146
+ /**
147
+ * Fill the gaps, then make the series non-decreasing. Between two known points the fill is
148
+ * linear. Past the first or last known point it follows `reference` (the shipped curve) scaled
149
+ * to meet that point, because a flat extension would price every turn count beyond the data
150
+ * at the edge's level.
151
+ */
152
+ function fillMonotone(series: (number | undefined)[], reference: readonly number[]): number[] {
153
+ const known = series.flatMap((v, i) => (v === undefined ? [] : [i]));
154
+ const first = known[0] as number;
155
+ const last = known[known.length - 1] as number;
156
+ const scaled = (i: number, anchor: number) =>
157
+ (series[anchor] as number) * ((reference[i] as number) / (reference[anchor] as number));
158
+ let floor = 0;
159
+ return series.map((_, i) => {
160
+ let v: number;
161
+ if (i < first) v = scaled(i, first);
162
+ else if (i > last) v = scaled(i, last);
163
+ else {
164
+ const lo = known.filter((k) => k <= i).at(-1) as number;
165
+ const hi = known.find((k) => k >= i) as number;
166
+ const a = series[lo] as number;
167
+ const b = series[hi] as number;
168
+ v = lo === hi ? a : a + ((b - a) * (i - lo)) / (hi - lo);
169
+ }
170
+ floor = Math.max(floor, v);
171
+ return floor;
172
+ });
173
+ }
174
+
175
+ /**
176
+ * One value per turn count 1..TAU_MAX: a trimmed mean of `value`, smoothed and non-decreasing.
177
+ * `reference` is the shipped series of the same quantity, used past the supported turn counts.
178
+ */
179
+ function curveOf(
180
+ sessions: OpusSession[],
181
+ value: (s: OpusSession) => number,
182
+ reference: readonly number[],
183
+ ): number[] {
184
+ const byTurns = new Map<number, number[]>();
185
+ for (const s of sessions) {
186
+ if (s.turns < 1 || s.turns > TAU_MAX) continue;
187
+ const at = byTurns.get(s.turns);
188
+ if (at) at.push(value(s));
189
+ else byTurns.set(s.turns, [value(s)]);
190
+ }
191
+ const raw = Array.from({ length: TAU_MAX }, (_, i) => {
192
+ const at = byTurns.get(i + 1);
193
+ return at && at.length >= MIN_SESSIONS_PER_TURN ? trimmedMean(at) : undefined;
194
+ });
195
+ // shortcut: turn 1 is never read (tau >= T0 = 2), so it takes the value of turn 2 instead of a noisy estimate.
196
+ raw[0] = undefined;
197
+ const supported = raw.flatMap((v, i) => (v === undefined ? [] : [i + 1]));
198
+ const lo = supported[0];
199
+ const hi = supported[supported.length - 1];
200
+ if (
201
+ lo === undefined ||
202
+ hi === undefined ||
203
+ lo > MIN_LOW_TURN ||
204
+ hi < MIN_HIGH_TURN ||
205
+ supported.length < MIN_SUPPORTED_TURNS
206
+ ) {
207
+ throw new CalibrationRefusal(
208
+ `turn coverage too thin: ${supported.length} of ${TAU_MAX - 1} turn counts have ${MIN_SESSIONS_PER_TURN}+ sessions` +
209
+ `${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`,
210
+ );
211
+ }
212
+ const smoothed = smooth(raw.slice(1), SMOOTH_HALF_WIDTH);
213
+ const filled = fillMonotone(smoothed, reference.slice(1));
214
+ return [filled[0] as number, ...filled];
215
+ }
216
+
217
+ const round = (x: number, digits: number) => Number(x.toFixed(digits));
218
+
219
+ export function deriveCurves(input: DeriveInput): DerivedCalibration {
220
+ const { opus, prices, tierTurns, end } = input;
221
+ const usable = opus.filter((s) => s.turns >= 1 && s.turns <= TAU_MAX);
222
+ if (usable.length < MIN_SESSIONS) {
223
+ throw new CalibrationRefusal(
224
+ `only ${usable.length} opus sessions of 1..${TAU_MAX} turns in the window; need ${MIN_SESSIONS}`,
225
+ );
226
+ }
227
+ const opusTokensCost = (p: TierPrices) => (s: OpusSession) =>
228
+ (s.inputTokens * p.input +
229
+ s.outputTokens * p.output +
230
+ s.cacheReadTokens * p.cached_input +
231
+ s.cacheWriteTokens * p.cache_write_1h) /
232
+ 1e6;
233
+ const price = (p: TierPrices) => (s: OpusSession) => opusTokensCost(p)(s) + s.otherUsd;
234
+ // The harness bills every cache write at the 1h rate, so repricing at opus prices must give back the stored cost.
235
+ const opusCost = opusTokensCost(prices.smart);
236
+ const repriceMatch =
237
+ usable.filter((s) => Math.abs(opusCost(s) - s.costUsd) <= 0.01 * s.costUsd).length /
238
+ usable.length;
239
+
240
+ const opusHrs = curveOf(usable, (s) => s.durationMs / 3.6e6, CURVE.smart.hrs);
241
+ const perTurn = (rows: TurnDuration[]) =>
242
+ median(
243
+ rows.filter((r) => r.turns >= 3 && r.turns <= TAU_MAX).map((r) => r.durationMs / r.turns),
244
+ );
245
+ const opusPerTurn = perTurn(usable.map((s) => ({ turns: s.turns, durationMs: s.durationMs })));
246
+ const speed = Object.fromEntries(
247
+ SAVINGS_TIERS.map((tier) => {
248
+ const rows = (tierTurns[tier] ?? []).filter((r) => r.turns >= 3 && r.turns <= TAU_MAX);
249
+ if (tier === "smart") return [tier, 1];
250
+ return [
251
+ tier,
252
+ rows.length >= MIN_SPEED_SESSIONS
253
+ ? round(perTurn(rows) / opusPerTurn, 3)
254
+ : SPEED_FALLBACK[tier],
255
+ ];
256
+ }),
257
+ ) as Record<SavingsTier, number>;
258
+
259
+ const curve = Object.fromEntries(
260
+ SAVINGS_TIERS.map((tier) => [
261
+ tier,
262
+ {
263
+ usd: curveOf(usable, price(prices[tier]), CURVE[tier].usd).map((v) => round(v, 4)),
264
+ hrs: opusHrs.map((v) => round(v * speed[tier], 5)),
265
+ },
266
+ ]),
267
+ ) as DerivedCurveSet;
268
+ return {
269
+ calibratedAt: end.toISOString().slice(0, 10),
270
+ model: CALIBRATION_MODEL,
271
+ curve,
272
+ sessions: usable.length,
273
+ usable,
274
+ speed,
275
+ repriceMatch,
276
+ };
277
+ }
278
+
279
+ /**
280
+ * Per-tier deviation of a curve from the shipped one over turns 2..TAU_MAX (turn 1 is never
281
+ * read). `weighted` is the session-weighted mean of derived over shipped: what the model
282
+ * would price on the fleet's own session lengths.
283
+ */
284
+ export function compareToShipped(curve: CurveSet, sessionsPerTurn: number[]) {
285
+ return SAVINGS_TIERS.flatMap((tier) =>
286
+ (["usd", "hrs"] as const).map((key) => {
287
+ const pairs = curve[tier][key]
288
+ .map((v, i) => ({ ratio: v / (CURVE[tier][key][i] as number), w: sessionsPerTurn[i] ?? 0 }))
289
+ .slice(1);
290
+ const dev = pairs.map((p) => Math.abs(p.ratio - 1)).sort((a, b) => a - b);
291
+ const w = pairs.reduce((s, p) => s + p.w, 0);
292
+ return {
293
+ tier,
294
+ key,
295
+ median: dev[Math.floor(dev.length / 2)] as number,
296
+ max: dev[dev.length - 1] as number,
297
+ over5pct: dev.filter((d) => d > 0.05).length,
298
+ points: dev.length,
299
+ weighted: pairs.reduce((s, p) => s + p.w * p.ratio, 0) / w,
300
+ };
301
+ }),
302
+ );
303
+ }
304
+
305
+ // ---- Reading the sessions ----------------------------------------------------------------
306
+
307
+ const num = (v: unknown) => Number(v) || 0;
308
+
309
+ /** Keyset-paged read of `sql`, which selects `id` and takes `id > ?` as its last parameter. */
310
+ async function pages<T extends { id: string }>(
311
+ sql: SavingsSql,
312
+ query: string,
313
+ params: (string | number)[],
314
+ ): Promise<T[]> {
315
+ const out: T[] = [];
316
+ let after = "";
317
+ for (;;) {
318
+ const rows = await sql<T>(query, [...params, after]);
319
+ out.push(...rows);
320
+ if (out.length > MAX_SESSIONS_READ) {
321
+ throw new CalibrationRefusal(
322
+ `more than ${MAX_SESSIONS_READ} sessions in the window; use a shorter window (days)`,
323
+ );
324
+ }
325
+ if (rows.length < PAGE) return out;
326
+ after = (rows[rows.length - 1] as T).id;
327
+ }
328
+ }
329
+
330
+ export async function fetchInput(sql: SavingsSql, start: Date, end: Date): Promise<DeriveInput> {
331
+ const window = [start.toISOString(), end.toISOString()];
332
+ const opusRows = await pages<Record<string, unknown> & { id: string }>(
333
+ sql,
334
+ `SELECT s.id AS id, s.numTurns AS turns, s.durationMs AS durationMs,
335
+ json_extract(j.value,'$.inputTokens') AS inputTokens, json_extract(j.value,'$.outputTokens') AS outputTokens,
336
+ json_extract(j.value,'$.cacheReadTokens') AS cacheReadTokens, json_extract(j.value,'$.cacheWriteTokens') AS cacheWriteTokens,
337
+ json_extract(j.value,'$.costUsd') AS costUsd, s.totalCostUsd AS totalCostUsd
338
+ FROM session_costs s, json_each(CASE WHEN json_valid(s.modelBreakdown) THEN s.modelBreakdown ELSE '[]' END) j
339
+ WHERE s.model = ? AND json_extract(j.value,'$.model') = ? AND s.createdAt >= ? AND s.createdAt < ?
340
+ AND s.numTurns BETWEEN 1 AND ${TAU_MAX} AND s.id > ? ORDER BY s.id LIMIT ${PAGE}`,
341
+ [CALIBRATION_MODEL, CALIBRATION_MODEL, ...window],
342
+ );
343
+ const opus = opusRows.map((r) => ({
344
+ turns: num(r.turns),
345
+ durationMs: num(r.durationMs),
346
+ inputTokens: num(r.inputTokens),
347
+ outputTokens: num(r.outputTokens),
348
+ cacheReadTokens: num(r.cacheReadTokens),
349
+ cacheWriteTokens: num(r.cacheWriteTokens),
350
+ costUsd: num(r.costUsd),
351
+ otherUsd: Math.max(0, num(r.totalCostUsd) - num(r.costUsd)),
352
+ }));
353
+
354
+ const priceRows = await sql<{ model: string; token_class: string; price: number }>(
355
+ `SELECT model, token_class, price_per_million_usd AS price FROM pricing
356
+ WHERE provider = 'claude' AND model IN (${SAVINGS_TIERS.map(() => "?").join(",")}) AND effective_from <= ?
357
+ ORDER BY effective_from`,
358
+ [...SAVINGS_TIERS.map((t) => TIER_MODEL[t]), end.getTime()],
359
+ );
360
+ const latest = new Map<string, number>(); // later effective_from overwrites earlier
361
+ for (const r of priceRows) latest.set(`${r.model}|${r.token_class}`, num(r.price));
362
+ const prices = Object.fromEntries(
363
+ SAVINGS_TIERS.map((tier) => [
364
+ tier,
365
+ Object.fromEntries(
366
+ (["input", "output", "cached_input", "cache_write_1h"] as const).map((cls) => {
367
+ const p = latest.get(`${TIER_MODEL[tier]}|${cls}`);
368
+ if (p === undefined) {
369
+ throw new CalibrationRefusal(`no ${cls} price for ${TIER_MODEL[tier]}`);
370
+ }
371
+ return [cls, p];
372
+ }),
373
+ ),
374
+ ]),
375
+ ) as Record<SavingsTier, TierPrices>;
376
+
377
+ const tierTurns: DeriveInput["tierTurns"] = {};
378
+ for (const tier of SAVINGS_TIERS) {
379
+ if (tier === "smart") continue;
380
+ const rows = await pages<{ id: string; turns: number; durationMs: number }>(
381
+ sql,
382
+ `SELECT id, numTurns AS turns, durationMs FROM session_costs
383
+ WHERE model = ? AND createdAt >= ? AND createdAt < ? AND numTurns BETWEEN 3 AND ${TAU_MAX} AND id > ? ORDER BY id LIMIT ${PAGE}`,
384
+ [TIER_MODEL[tier], ...window],
385
+ );
386
+ tierTurns[tier] = rows.map((r) => ({ turns: num(r.turns), durationMs: num(r.durationMs) }));
387
+ }
388
+ return { opus, prices, tierTurns, end };
389
+ }
390
+
391
+ // ---- The run -----------------------------------------------------------------------------
392
+
393
+ export type CalibrationGap = ReturnType<typeof compareToShipped>[number];
394
+
395
+ export type CalibrationRun = {
396
+ window: { start: string; end: string; days: number };
397
+ /** Opus sessions of 1..TAU_MAX turns used; 0 when the run was refused before counting. */
398
+ sessions: number;
399
+ /** Why the data cannot support a curve. When set, `calibration` is null. */
400
+ refusal: string | null;
401
+ /** The derived curve in the form the config row stores. */
402
+ calibration: StoredCalibration | null;
403
+ speed: Record<SavingsTier, number> | null;
404
+ repriceMatch: number | null;
405
+ /** Per tier and quantity, the derived curve against the shipped one. */
406
+ gaps: CalibrationGap[];
407
+ /** Derived smart-tier mean cost over the shipped one. */
408
+ meanRatio: number | null;
409
+ /** Why a derived curve must not be applied (mean cost beyond SANITY_FACTOR); null when it may be. */
410
+ applyBlocked: string | null;
411
+ };
412
+
413
+ export type StoredCalibration = {
414
+ calibratedAt: string;
415
+ model: string;
416
+ curve: DerivedCurveSet;
417
+ window: { start: string; end: string; sessions: number };
418
+ };
419
+
420
+ /** Read the window's sessions through `sql` and derive the curve. Never writes. */
421
+ export async function calibrate(
422
+ sql: SavingsSql,
423
+ opts: { days: number; end: Date },
424
+ ): Promise<CalibrationRun> {
425
+ const start = new Date(opts.end.getTime() - opts.days * 86_400_000);
426
+ const window = { start: start.toISOString(), end: opts.end.toISOString(), days: opts.days };
427
+ const refused = (refusal: string): CalibrationRun => ({
428
+ window,
429
+ sessions: 0,
430
+ refusal,
431
+ calibration: null,
432
+ speed: null,
433
+ repriceMatch: null,
434
+ gaps: [],
435
+ meanRatio: null,
436
+ applyBlocked: null,
437
+ });
438
+ let derived: DerivedCalibration;
439
+ try {
440
+ derived = deriveCurves(await fetchInput(sql, start, opts.end));
441
+ } catch (err) {
442
+ if (err instanceof CalibrationRefusal) return refused(err.message);
443
+ throw err;
444
+ }
445
+ const perTurn = Array.from({ length: TAU_MAX }, () => 0);
446
+ for (const s of derived.usable) perTurn[s.turns - 1] = (perTurn[s.turns - 1] as number) + 1;
447
+ const mean = (a: readonly number[]) => a.reduce((s, v) => s + v, 0) / a.length;
448
+ const meanRatio = mean(derived.curve.smart.usd) / mean(CURVE.smart.usd);
449
+ return {
450
+ window,
451
+ sessions: derived.sessions,
452
+ refusal: null,
453
+ calibration: {
454
+ calibratedAt: derived.calibratedAt,
455
+ model: derived.model,
456
+ curve: derived.curve,
457
+ window: { start: window.start, end: window.end, sessions: derived.sessions },
458
+ },
459
+ speed: derived.speed,
460
+ repriceMatch: derived.repriceMatch,
461
+ gaps: compareToShipped(derived.curve, perTurn),
462
+ meanRatio,
463
+ applyBlocked:
464
+ meanRatio > SANITY_FACTOR || meanRatio < 1 / SANITY_FACTOR
465
+ ? `derived smart curve is ${meanRatio.toFixed(2)}x the shipped one (limit ${SANITY_FACTOR}x)`
466
+ : null,
467
+ };
468
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Live facts for one workflow over a window, read from workflow_runs, steps,
3
+ * agent tasks and session costs. The SQL is ported from the
4
+ * `automation-savings-estimate` script (v7); pricing lives in `model.ts`.
5
+ */
6
+ import { getDbClient } from "../db";
7
+ import type { DbParam } from "../db-client";
8
+ import { JEV_PER_M, nodeOpsOf, scriptOpsFromAwaitCount, type WorkflowFacts } from "./model";
9
+
10
+ /** Runs a read query. The default is the API's own DB client. */
11
+ export type SavingsSql = <T>(sql: string, params: DbParam[]) => Promise<T[]>;
12
+
13
+ const defaultSql: SavingsSql = (sql, params) => getDbClient().query(sql, params);
14
+
15
+ /**
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.
20
+ */
21
+ export const LIVE_MAX_RUNS = 10_000;
22
+
23
+ export type WorkflowWindow =
24
+ | { status: "ok"; facts: WorkflowFacts; byDay: DayFacts[] }
25
+ | { status: "too-many-runs"; runs: number };
26
+
27
+ /** One UTC day's facts. The window's facts are the sum over its days. */
28
+ export type DayFacts = WorkflowFacts & { day: string };
29
+
30
+ // A run "caused a downstream effect" when it created an agent task or started a child workflow run.
31
+ const EFFECT_SQL =
32
+ "(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))";
33
+ const AWAITS_SQL = "(length(source)-length(replace(source,'await','')))/5";
34
+
35
+ const num = (v: unknown): number => Number(v) || 0;
36
+
37
+ const emptyFacts = (runs: number): WorkflowFacts => ({
38
+ runs,
39
+ countedRuns: 0,
40
+ schedRuns: 0,
41
+ schedEffectRuns: 0,
42
+ opsSum: 0,
43
+ agentTasks: 0,
44
+ agentUsd: 0,
45
+ agentMs: 0,
46
+ followupUsd: 0,
47
+ recordedLlmUsd: 0,
48
+ estimatedLlmUsd: 0,
49
+ computeSecs: 0,
50
+ });
51
+
52
+ /** Ops per script name; a global script wins over an agent-scoped one of the same name. */
53
+ async function scriptOps(names: string[], sql: SavingsSql): Promise<Map<string, number>> {
54
+ const ops = new Map<string, number>();
55
+ const unique = [...new Set(names.filter(Boolean))];
56
+ 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));
62
+ return ops;
63
+ }
64
+
65
+ /** UTC day (`YYYY-MM-DD`) of an ISO `startedAt`. */
66
+ const DAY_SQL = "substr(r.startedAt,1,10)";
67
+
68
+ /** Every run's facts, grouped by the UTC day it started; the window facts are their sum. */
69
+ export async function computeWorkflowWindow(
70
+ workflow: { id: string; definition: unknown },
71
+ window: { start: string; end: string },
72
+ sql: SavingsSql = defaultSql,
73
+ ): Promise<WorkflowWindow> {
74
+ const span = [workflow.id, window.start, window.end];
75
+ // Index-only count first, so a high-volume workflow never reaches the step scans.
76
+ const total = num(
77
+ (
78
+ await sql<{ n: number }>(
79
+ "SELECT count(*) n FROM workflow_runs WHERE workflowId=? AND startedAt>=? AND startedAt<?",
80
+ span,
81
+ )
82
+ )[0]?.n,
83
+ );
84
+ if (total === 0) return { status: "ok", facts: emptyFacts(0), byDay: [] };
85
+ if (total > LIVE_MAX_RUNS) return { status: "too-many-runs", runs: total };
86
+
87
+ const days = new Map<string, DayFacts>();
88
+ const dayOf = (d: unknown): DayFacts => {
89
+ const key = String(d);
90
+ let f = days.get(key);
91
+ if (!f) {
92
+ f = { day: key, ...emptyFacts(0) };
93
+ days.set(key, f);
94
+ }
95
+ return f;
96
+ };
97
+
98
+ 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`,
100
+ span,
101
+ );
102
+ let schedRuns = 0;
103
+ for (const row of byTrigger) {
104
+ const f = dayOf(row.d);
105
+ const n = num(row.n);
106
+ f.runs += n;
107
+ if (row.st === "skipped" || row.st === "cancelled") continue;
108
+ f.countedRuns += n;
109
+ if (row.tt === "schedule") {
110
+ f.schedRuns += n;
111
+ schedRuns += n;
112
+ }
113
+ }
114
+ if (schedRuns > 0) {
115
+ const effect = await sql<{ d: string; n: number }>(
116
+ `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`,
117
+ span,
118
+ );
119
+ for (const row of effect) dayOf(row.d).schedEffectRuns += num(row.n);
120
+ }
121
+
122
+ const definition = (workflow.definition ?? {}) as {
123
+ nodes?: { id: string; type: string; config?: Record<string, unknown> }[];
124
+ };
125
+ const scriptNames = (definition.nodes ?? [])
126
+ .filter((n) => n.type === "swarm-script")
127
+ .map((n) => n.config?.scriptName)
128
+ .filter((n): n is string => typeof n === "string");
129
+ const nodeOps = nodeOpsOf(definition, await scriptOps(scriptNames, sql));
130
+
131
+ const steps = await sql<{
132
+ d: string;
133
+ nid: string;
134
+ n: number;
135
+ secs: number | null;
136
+ itok: number | null;
137
+ rchars: number | null;
138
+ jev: number | null;
139
+ clairic: number | null;
140
+ }>(
141
+ `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,
142
+ sum(CASE WHEN s.nodeType LIKE 'system-one%' THEN json_extract(s.output,'$.usage.input_tokens') END) itok,
143
+ sum(CASE WHEN s.nodeType='raw-llm' THEN length(json_extract(s.output,'$.result')) END) rchars,
144
+ sum(CASE WHEN s.nodeId='report' THEN json_extract(s.output,'$.result.summary.jevCostUsd') END) jev,
145
+ sum(CASE WHEN s.nodeId='report' THEN json_extract(s.output,'$.result.cost.clairicUsd') END) clairic
146
+ 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`,
147
+ span,
148
+ );
149
+ for (const x of steps) {
150
+ const f = dayOf(x.d);
151
+ // foreach iterations store `<nodeId>#<i>`.
152
+ f.opsSum += (nodeOps.get(String(x.nid).split("#")[0] ?? "") ?? 0) * num(x.n);
153
+ f.recordedLlmUsd += num(x.jev) + num(x.clairic);
154
+ f.estimatedLlmUsd += (num(x.itok) / 1e6) * JEV_PER_M + (num(x.rchars) * (1.2 / 4 + 0.3)) / 1e6;
155
+ f.computeSecs += num(x.secs);
156
+ }
157
+
158
+ const agent = await sql<{ d: string; tasks: number; usd: number | null; ms: number | null }>(
159
+ `SELECT ${DAY_SQL} d, count(DISTINCT t.id) tasks, sum(c.u) usd, sum(c.ms) ms
160
+ 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
161
+ WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1`,
162
+ span,
163
+ );
164
+ for (const row of agent) {
165
+ const f = dayOf(row.d);
166
+ f.agentTasks += num(row.tasks);
167
+ f.agentUsd += num(row.usd);
168
+ f.agentMs += num(row.ms);
169
+ }
170
+ const followups = await sql<{ d: string; fup: number | null }>(
171
+ `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`,
172
+ span,
173
+ );
174
+ for (const row of followups) dayOf(row.d).followupUsd += num(row.fup);
175
+
176
+ const byDay = [...days.values()].sort((a, b) => a.day.localeCompare(b.day));
177
+ const facts = emptyFacts(0);
178
+ for (const f of byDay) {
179
+ for (const k of Object.keys(facts) as (keyof WorkflowFacts)[]) facts[k] += f[k];
180
+ }
181
+ return { status: "ok", facts, byDay };
182
+ }