@desplega.ai/agent-swarm 2.8.0 → 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 (216) hide show
  1. package/dist/{acp-adapter-t949vbbp.js → acp-adapter-fqzkxyra.js} +3 -3
  2. package/dist/{actions-7e9czc7s.js → actions-kxek041g.js} +18 -18
  3. package/dist/{amp-adapter-gv6cbb7d.js → amp-adapter-ce7jjke4.js} +1 -1
  4. package/dist/{app-b9fbkp9v.js → app-v6zz8yh0.js} +3 -3
  5. package/dist/{assistant-wjb7v4c7.js → assistant-m0sw9xx2.js} +19 -19
  6. package/dist/{boot-args-schema-2t37e0fe.js → boot-args-schema-66bk37wv.js} +1 -1
  7. package/dist/{boot-reembed-gka3zas7.js → boot-reembed-edjpwsc1.js} +1 -1
  8. package/dist/{boot-reembed-a35nkyr1.js → boot-reembed-y27n09tz.js} +1 -1
  9. package/dist/{boot-scrub-sweep-65sdnp6c.js → boot-scrub-sweep-1xc35965.js} +3 -3
  10. package/dist/{boot-seeds-x42tzytw.js → boot-seeds-7hjj91qj.js} +4 -4
  11. package/dist/{boxd-qbkxy6ap.js → boxd-ent8ch04.js} +1 -1
  12. package/dist/{claude-adapter-v221b2fd.js → claude-adapter-stw7jdcf.js} +3 -3
  13. package/dist/{claude-managed-adapter-29eq09wd.js → claude-managed-adapter-jh6c523j.js} +2 -2
  14. package/dist/{claude-managed-setup-9m6450zk.js → claude-managed-setup-y6z2perp.js} +5 -5
  15. package/dist/{claude-sdk-session-0q0ptaba.js → claude-sdk-session-vvya8wqk.js} +3 -3
  16. package/dist/{cli-wk18cm92.js → cli-0cq8y6m7.js} +1 -1
  17. package/dist/{cli-p1w18yhx.js → cli-1pz0330a.js} +1 -1
  18. package/dist/{cli-y97qxcfx.js → cli-1qkz151v.js} +3 -3
  19. package/dist/{cli-qwca7s44.js → cli-26ctbcdp.js} +18 -6
  20. package/dist/{cli-8fknbnhw.js → cli-2kvhc7x8.js} +7 -7
  21. package/dist/{cli-rfywm85n.js → cli-3e875j5p.js} +136 -49
  22. package/dist/{cli-6wxjceza.js → cli-3sy2xags.js} +10 -10
  23. package/dist/{cli-a7wvp2km.js → cli-3vmb0n58.js} +1 -1
  24. package/dist/{cli-p1bq50aa.js → cli-4vzgeta4.js} +13 -13
  25. package/dist/{cli-m28atx8q.js → cli-5y340nzn.js} +4 -4
  26. package/dist/{cli-7p1kvkck.js → cli-6rc5frdm.js} +1 -1
  27. package/dist/{cli-tph5wt3y.js → cli-6wj7p986.js} +1 -1
  28. package/dist/{cli-t73cas91.js → cli-7349va39.js} +8100 -7620
  29. package/dist/{cli-ee0b971j.js → cli-837vfs2x.js} +2 -2
  30. package/dist/{cli-abejgen1.js → cli-959kp5h2.js} +12 -11
  31. package/dist/{cli-8kzasymh.js → cli-97ae65rz.js} +4 -4
  32. package/dist/{cli-m4dqmnbp.js → cli-9mb2q6pb.js} +1 -1
  33. package/dist/{cli-p2gfst4m.js → cli-a0z912j7.js} +123 -35
  34. package/dist/{cli-4txa0ter.js → cli-b98a65ed.js} +3 -3
  35. package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
  36. package/dist/{cli-tk7cjj8h.js → cli-dzpc6en0.js} +1 -1
  37. package/dist/{cli-qa4wdgsy.js → cli-e1p3n5gq.js} +4 -4
  38. package/dist/{cli-gxkx0zzp.js → cli-f4e8r23x.js} +1 -1
  39. package/dist/{cli-qmqk2yc2.js → cli-f4r3g076.js} +1 -1
  40. package/dist/{cli-wcg8x116.js → cli-f6bahpn5.js} +1 -1
  41. package/dist/{cli-qsnnd04k.js → cli-fpjmegdb.js} +1 -1
  42. package/dist/{cli-j790gp2w.js → cli-fwy8kfd6.js} +271 -37
  43. package/dist/{cli-rmmpt0wm.js → cli-g5mtmf6t.js} +6 -6
  44. package/dist/{cli-rzsy6nc6.js → cli-gyt3zydq.js} +3 -3
  45. package/dist/{cli-pasjcnmj.js → cli-j24zbska.js} +3 -3
  46. package/dist/{cli-qfedvmcr.js → cli-jdknh18m.js} +10 -10
  47. package/dist/{cli-7b8sbmag.js → cli-kjtwrhea.js} +1 -1
  48. package/dist/{cli-gpwhbgx0.js → cli-m9s2qff2.js} +57 -25
  49. package/dist/{cli-2wnq8jkz.js → cli-mxn1qvbn.js} +3 -2
  50. package/dist/{cli-s7t6p9my.js → cli-n6vtrcht.js} +1 -1
  51. package/dist/{cli-2zp0et3v.js → cli-pchypa1s.js} +55 -19
  52. package/dist/{cli-yq3zak69.js → cli-pfs8adn4.js} +1 -1
  53. package/dist/{cli-c55z5chy.js → cli-q24n86d2.js} +2 -2
  54. package/dist/{cli-h38x262p.js → cli-rcecc3yq.js} +167 -43
  55. package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
  56. package/dist/{cli-sdtt3men.js → cli-rmzsadkf.js} +1 -1
  57. package/dist/{cli-f3vq58d2.js → cli-t2tma8gb.js} +1 -1
  58. package/dist/{cli-m23zjcy2.js → cli-tekytdq9.js} +2 -2
  59. package/dist/{cli-tqegb8eq.js → cli-vdektqgf.js} +1 -1
  60. package/dist/{cli-ffhtssbp.js → cli-vj75tyaw.js} +1 -1
  61. package/dist/{cli-deefvewm.js → cli-w401b9tq.js} +1 -1
  62. package/dist/{cli-n9ftpys4.js → cli-x6t50dmw.js} +7 -7
  63. package/dist/{cli-6t09sdhy.js → cli-xf3qw745.js} +3 -3
  64. package/dist/{cli-hxpyc9sn.js → cli-z1w943va.js} +2 -2
  65. package/dist/{cli-334z18y3.js → cli-zh9rsbqf.js} +3 -3
  66. package/dist/cli.js +17 -17
  67. package/dist/{codex-adapter-30j9bpzd.js → codex-adapter-zerf5qsp.js} +1 -1
  68. package/dist/{codex-hook-h3vk6xzr.js → codex-hook-30gyhzxe.js} +1 -1
  69. package/dist/{codex-session-runner-8vp57v8w.js → codex-session-runner-89s304py.js} +1 -1
  70. package/dist/{commands-bngnz9g7.js → commands-jeh1b51j.js} +3 -3
  71. package/dist/{controller-hxx8wwy1.js → controller-mctfbrse.js} +3 -3
  72. package/dist/{controllers-connect-e2b4gyxc.js → controllers-connect-nxa1ddwn.js} +19 -19
  73. package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-qj8vehv6.js} +1 -1
  74. package/dist/{db-bgm7vkc0.js → db-2dvay0es.js} +3 -3
  75. package/dist/{db-c6np41ca.js → db-b36qn6k3.js} +2 -2
  76. package/dist/{dispatcher-jnybck15.js → dispatcher-gndbta01.js} +17 -17
  77. package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-f75sz821.js} +1 -1
  78. package/dist/{e2b-jkwfhbcv.js → e2b-3gpc2n3w.js} +1 -1
  79. package/dist/{e2b-s16txnpx.js → e2b-jbm7mj93.js} +1 -1
  80. package/dist/{embedding-space-crsm2zp0.js → embedding-space-4p05vb2x.js} +6 -6
  81. package/dist/{embeddings-e7z3f27f.js → embeddings-m6768mgh.js} +1 -1
  82. package/dist/{external-channel-m77wf5z3.js → external-channel-gjv3jne3.js} +2 -2
  83. package/dist/{fx-adapter-b6w0kf56.js → fx-adapter-rpsgb1tw.js} +4 -4
  84. package/dist/{grok-adapter-4sqtebdk.js → grok-adapter-n2m3zjg1.js} +4 -4
  85. package/dist/handlers-nv8edn19.js +32 -0
  86. package/dist/{heartbeat-xgb036sx.js → heartbeat-a1tv60gt.js} +20 -20
  87. package/dist/{hook-xsk1jbha.js → hook-8h5dzcgq.js} +2 -2
  88. package/dist/{hook-5h02c9ga.js → hook-cyaps9ba.js} +4 -4
  89. package/dist/{http-txe7qhvn.js → http-t15mhbd9.js} +1733 -79
  90. package/dist/{index-0eny15vj.js → index-2skqtd76.js} +2 -2
  91. package/dist/{index-w7em4ktq.js → index-d6wkh8ar.js} +2 -2
  92. package/dist/{index-rvccek1w.js → index-gjwaqaq8.js} +5 -5
  93. package/dist/{index-e5pfbsys.js → index-hjhfk3ra.js} +3 -3
  94. package/dist/{index-1qw6f2dc.js → index-khe3gp0k.js} +4 -4
  95. package/dist/index-ksmyd6kc.js +37 -0
  96. package/dist/{index-vk63emp7.js → index-qav6455f.js} +14 -12
  97. package/dist/index-rjnrje98.js +32 -0
  98. package/dist/index-tv3413wy.js +33 -0
  99. package/dist/{index-ysvbhg5m.js → index-w1zqf680.js} +1 -1
  100. package/dist/{keepalive-4zsrce78.js → keepalive-91s7hzrb.js} +3 -3
  101. package/dist/lead-3hmddvrm.js +70 -0
  102. package/dist/{maintenance-86jvartk.js → maintenance-7pjmy5xy.js} +1 -1
  103. package/dist/{node-je82wjet.js → node-4c5jqxr3.js} +1 -1
  104. package/dist/{oauth-refresh-sweep-j52kg9pr.js → oauth-refresh-sweep-rzqfm94j.js} +2 -2
  105. package/dist/{onboard-c2aj5p8q.js → onboard-74st7pag.js} +3 -3
  106. package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-arn7gm8q.js} +2 -2
  107. package/dist/{otel-impl-yyy203z8.js → otel-impl-rnzey8cb.js} +1 -1
  108. package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-6mkwq64n.js} +3 -2
  109. package/dist/{pricing-refresh-1rgzqyzz.js → pricing-refresh-ha21jhk7.js} +2 -2
  110. package/dist/{rbac-roles-e70xfeyj.js → rbac-roles-59dxachk.js} +2 -2
  111. package/dist/{rbac-roles-q89qe8er.js → rbac-roles-wqhma4dr.js} +3 -3
  112. package/dist/{render-v2-k6tt107q.js → render-v2-14kpzx12.js} +3 -3
  113. package/dist/{resume-cnnrjfxa.js → resume-gsa5fb5f.js} +6 -6
  114. package/dist/{session-access-xkxkjw3n.js → session-access-skm7bnp6.js} +4 -4
  115. package/dist/{session-source-backfill-1d5pdwww.js → session-source-backfill-pbqzbncv.js} +2 -2
  116. package/dist/{setup-se8q7gkc.js → setup-5yermsem.js} +1 -1
  117. package/dist/{work-objects-1kxnbzy5.js → work-objects-xj0ck0w4.js} +20 -20
  118. package/dist/{worker-follow-up-zqm8apt4.js → worker-follow-up-911xc0b8.js} +19 -17
  119. package/dist/worker-qgg0m2gw.js +70 -0
  120. package/openapi.json +1741 -290
  121. package/package.json +3 -3
  122. package/src/apps/catalog.generated.json +120 -1
  123. package/src/apps/definition.ts +38 -11
  124. package/src/apps/page-validator.ts +88 -0
  125. package/src/be/db/model-profiles.ts +110 -11
  126. package/src/be/db/tasks/read.ts +20 -0
  127. package/src/be/db/workflow-run-definitions.ts +19 -8
  128. package/src/be/db-client.ts +43 -5
  129. package/src/be/db.ts +9 -3
  130. package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
  131. package/src/be/model-profile-check.ts +43 -18
  132. package/src/be/runtime-pools/routing.ts +1 -0
  133. package/src/be/savings/calibrate.ts +468 -0
  134. package/src/be/savings/compute.ts +182 -0
  135. package/src/be/savings/model.ts +406 -0
  136. package/src/be/scripts/typecheck.ts +5 -0
  137. package/src/be/seed/agent-fs-provision.ts +48 -11
  138. package/src/be/seed/workflows-seeder.ts +67 -23
  139. package/src/be/skill-parser.ts +19 -7
  140. package/src/commands/onboard/agent-fs-version.ts +1 -1
  141. package/src/commands/provider-error-class.ts +97 -0
  142. package/src/commands/runner.ts +99 -17
  143. package/src/extensions/contract-types.generated.ts +1 -1
  144. package/src/http/all-routes.ts +2 -0
  145. package/src/http/fs.ts +8 -2
  146. package/src/http/index.ts +4 -0
  147. package/src/http/model-profiles.ts +43 -10
  148. package/src/http/poll.ts +1 -0
  149. package/src/http/savings-calibration.ts +277 -0
  150. package/src/http/savings.ts +363 -0
  151. package/src/http/tasks.ts +46 -4
  152. package/src/http/trackers/authorize-gate.ts +41 -0
  153. package/src/http/trackers/jira.ts +26 -4
  154. package/src/http/trackers/linear.ts +26 -4
  155. package/src/integrations/chat-sdk/limits.ts +6 -1
  156. package/src/jira/oauth.ts +7 -1
  157. package/src/linear/README.md +2 -1
  158. package/src/linear/oauth.ts +7 -1
  159. package/src/providers/amp-adapter.ts +1 -1
  160. package/src/providers/codex-adapter.ts +3 -0
  161. package/src/providers/pi-mono-adapter.ts +6 -5
  162. package/src/providers/types.ts +7 -0
  163. package/src/scripts-runtime/eval-harness.ts +14 -1
  164. package/src/scripts-runtime/executors/types.ts +3 -0
  165. package/src/scripts-runtime/sdk-allowlist.ts +11 -1
  166. package/src/scripts-runtime/swarm-sdk.ts +6 -0
  167. package/src/scripts-runtime/types/stdlib.d.ts +9 -0
  168. package/src/scripts-runtime/types/swarm-extension.d.ts +34 -0
  169. package/src/scripts-runtime/types/swarm-sdk.d.ts +9 -0
  170. package/src/tasks/worker-follow-up.ts +142 -3
  171. package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
  172. package/src/tests/apps-chart-shell.test.ts +170 -0
  173. package/src/tests/apps-icon.test.ts +156 -2
  174. package/src/tests/chat-sdk-relay.test.ts +12 -0
  175. package/src/tests/codex-adapter.test.ts +11 -0
  176. package/src/tests/comb-default.test.ts +6 -0
  177. package/src/tests/core-auth.test.ts +7 -6
  178. package/src/tests/db-client-busy-retry.test.ts +58 -6
  179. package/src/tests/deploy-guard.test.ts +154 -0
  180. package/src/tests/docs-index-footprint.test.js +3 -3
  181. package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
  182. package/src/tests/mcp-tools.test.ts +1 -1
  183. package/src/tests/model-profile-fallbacks.test.ts +482 -0
  184. package/src/tests/model-profiles-api.test.ts +1 -0
  185. package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
  186. package/src/tests/provider-error-class.test.ts +174 -0
  187. package/src/tests/runner-provider-fallback.test.ts +197 -0
  188. package/src/tests/savings-calibration-api.test.ts +264 -0
  189. package/src/tests/savings-calibration.test.ts +201 -0
  190. package/src/tests/savings-compute.test.ts +406 -0
  191. package/src/tests/savings-model.test.ts +287 -0
  192. package/src/tests/script-connections.test.ts +2 -0
  193. package/src/tests/script-native-unawaited-drain.test.ts +167 -0
  194. package/src/tests/sdk-allowlist.test.ts +40 -0
  195. package/src/tests/seed-workflows.test.ts +167 -11
  196. package/src/tests/skill-parser.test.ts +45 -0
  197. package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
  198. package/src/tests/workflow-definition-pinning.test.ts +128 -3
  199. package/src/tests/workflow-script-principal.test.ts +94 -4
  200. package/src/tools/app-upsert.ts +1 -1
  201. package/src/tools/model-profiles/list-model-profiles.ts +4 -2
  202. package/src/tools/script-run.ts +1 -1
  203. package/src/tools/update-profile.ts +1 -1
  204. package/src/types.ts +115 -33
  205. package/src/utils/constants.ts +2 -0
  206. package/templates/skills/apps/SKILL.md +62 -3
  207. package/templates/skills/apps/content.md +62 -3
  208. package/templates/skills/swarm-docs/content.md +2 -0
  209. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  210. package/templates/skills/swarm-scripts/content.md +1 -1
  211. package/dist/handlers-kdjcyzdj.js +0 -32
  212. package/dist/index-835xdgnm.js +0 -33
  213. package/dist/index-d469300x.js +0 -37
  214. package/dist/index-rzqwp11g.js +0 -32
  215. package/dist/lead-yqt47dkr.js +0 -70
  216. package/dist/worker-j6xxtq7p.js +0 -70
@@ -0,0 +1,406 @@
1
+ /**
2
+ * Automation savings model: what the work a workflow did would have cost if
3
+ * agent tasks had done it instead.
4
+ *
5
+ * Port of the `automation-savings-estimate` script, version 7, calibrated on
6
+ * 2026-11-05 against opus 5.5 session costs. Change a constant here only
7
+ * together with a new calibration.
8
+ *
9
+ * Per substituted run: agent-only cost = R * curve(tau) * err + F, with
10
+ * tau = T0 + K * ops (capped at TAU_MAX turns), where ops counts the awaited
11
+ * I/O calls of the deterministic steps. Agent-task nodes inside a workflow are
12
+ * kept at their actual cost on both sides; only the deterministic glue is
13
+ * substituted.
14
+ */
15
+
16
+ import { z } from "zod";
17
+
18
+ export const SAVINGS_TIERS = ["smol", "regular", "smart", "ultra"] as const;
19
+ export type SavingsTier = (typeof SAVINGS_TIERS)[number];
20
+ export type SavingsBand = { p10: number; p50: number; p90: number };
21
+ type Quantile = keyof SavingsBand;
22
+
23
+ export const CALIBRATION_MODEL = "claude-opus-5-5";
24
+ export const CALIBRATED_AT = "2026-11-05";
25
+
26
+ /** Agent turns per deterministic op. */
27
+ export const K = 0.2753;
28
+ /** Bootstrap turns of a fresh agent session. */
29
+ export const T0 = 2;
30
+ /** tau cap: the fleet's p95 session length in turns. */
31
+ export const TAU_MAX = 61;
32
+ /** An agent would not poll faster than hourly: schedule runs count at most 24 a day. */
33
+ export const CAP_PER_DAY = 24;
34
+ /** Lead follow-up review per standalone agent task, USD. */
35
+ export const F_FOLLOWUP = 0.107;
36
+ /** USD per million SystemOne input tokens when a run records no cost. */
37
+ export const JEV_PER_M = 0.042;
38
+ /** Failure and retry multiplier, from scheduled agent tasks. */
39
+ export const R: SavingsBand = { p10: 1.011, p50: 1.02, p90: 1.03 };
40
+ /** Leave-one-out backtest spread for a single job. */
41
+ export const ERR_JOB: SavingsBand = { p10: 0.542, p50: 1.0, p90: 1.508 };
42
+ /** Monte Carlo spread for a fleet sum. */
43
+ export const ERR_FLEET: SavingsBand = { p10: 0.746, p50: 1.0, p90: 1.325 };
44
+ /** Ops of a swarm-script node whose script is not in the catalog. */
45
+ export const DEFAULT_OPS = 9;
46
+ /** Upper bound on the ops counted for one script. */
47
+ export const MAX_SCRIPT_OPS = 100;
48
+
49
+ // Session cost (USD) and agent-active hours by session length in turns
50
+ // (index 0 = 1 turn), per tier, from 30 days of session_costs repriced at each
51
+ // tier's model.
52
+ export type CurveSet = Record<SavingsTier, { usd: readonly number[]; hrs: readonly number[] }>;
53
+ export const CURVE: CurveSet = {
54
+ smol: {
55
+ usd: [
56
+ 0.0056, 0.0068, 0.0075, 0.0086, 0.0092, 0.0105, 0.012, 0.0146, 0.0163, 0.0171, 0.0184, 0.02,
57
+ 0.0212, 0.0222, 0.0225, 0.0242, 0.0254, 0.0268, 0.028, 0.0291, 0.0306, 0.0319, 0.0333, 0.0353,
58
+ 0.0359, 0.0374, 0.0389, 0.0413, 0.043, 0.0434, 0.045, 0.047, 0.0489, 0.0505, 0.051, 0.0535,
59
+ 0.0554, 0.057, 0.0586, 0.0595, 0.0612, 0.0633, 0.065, 0.0679, 0.0683, 0.0702, 0.0717, 0.0742,
60
+ 0.0757, 0.0764, 0.078, 0.0805, 0.0824, 0.0842, 0.085, 0.0881, 0.0901, 0.093, 0.0949, 0.0963,
61
+ 0.0979,
62
+ ],
63
+ hrs: [
64
+ 0.00409, 0.00521, 0.00674, 0.00831, 0.00993, 0.0126, 0.01586, 0.01997, 0.02272, 0.02392,
65
+ 0.02615, 0.03049, 0.034, 0.03708, 0.03835, 0.04398, 0.04779, 0.05207, 0.05544, 0.05811,
66
+ 0.06247, 0.06595, 0.07002, 0.07589, 0.0778, 0.08234, 0.08704, 0.09357, 0.09884, 0.10091,
67
+ 0.10694, 0.11393, 0.12002, 0.12476, 0.12736, 0.13666, 0.14271, 0.14854, 0.15322, 0.15738,
68
+ 0.16341, 0.17023, 0.17766, 0.18815, 0.18983, 0.19846, 0.1996, 0.20217, 0.20833, 0.21012,
69
+ 0.21538, 0.2224, 0.23067, 0.23488, 0.23825, 0.24844, 0.25554, 0.26838, 0.27469, 0.27725,
70
+ 0.28259,
71
+ ],
72
+ },
73
+ regular: {
74
+ usd: [
75
+ 0.0878, 0.1074, 0.1211, 0.1383, 0.1497, 0.1699, 0.196, 0.2372, 0.2628, 0.2762, 0.2952, 0.3209,
76
+ 0.3399, 0.3544, 0.3593, 0.3859, 0.4041, 0.425, 0.4435, 0.4586, 0.4817, 0.5001, 0.5215, 0.5501,
77
+ 0.5582, 0.5795, 0.6027, 0.6364, 0.6621, 0.6678, 0.6917, 0.7189, 0.7459, 0.7683, 0.7758,
78
+ 0.8096, 0.8361, 0.8588, 0.8806, 0.893, 0.9152, 0.9422, 0.9654, 1.0056, 1.0108, 1.0351, 1.0545,
79
+ 1.0885, 1.108, 1.1184, 1.1389, 1.1716, 1.1969, 1.2205, 1.2309, 1.2733, 1.3003, 1.3399, 1.3639,
80
+ 1.3838, 1.4053,
81
+ ],
82
+ hrs: [
83
+ 0.00341, 0.00435, 0.00562, 0.00693, 0.00828, 0.0105, 0.01322, 0.01665, 0.01894, 0.01994,
84
+ 0.0218, 0.02541, 0.02834, 0.0309, 0.03197, 0.03665, 0.03983, 0.0434, 0.04621, 0.04844,
85
+ 0.05207, 0.05497, 0.05836, 0.06326, 0.06485, 0.06863, 0.07255, 0.07799, 0.08239, 0.08411,
86
+ 0.08914, 0.09496, 0.10004, 0.10399, 0.10616, 0.11391, 0.11896, 0.12382, 0.12771, 0.13118,
87
+ 0.13621, 0.14189, 0.14808, 0.15683, 0.15823, 0.16542, 0.16638, 0.16852, 0.17365, 0.17514,
88
+ 0.17952, 0.18537, 0.19227, 0.19578, 0.19858, 0.20708, 0.213, 0.22371, 0.22896, 0.23109,
89
+ 0.23555,
90
+ ],
91
+ },
92
+ smart: {
93
+ usd: [
94
+ 0.1746, 0.2138, 0.2413, 0.2756, 0.2983, 0.3385, 0.3907, 0.4729, 0.5243, 0.551, 0.589, 0.6402,
95
+ 0.6783, 0.7075, 0.7173, 0.7705, 0.8068, 0.8487, 0.8857, 0.9158, 0.9621, 0.9989, 1.0416,
96
+ 1.0987, 1.1149, 1.1576, 1.2041, 1.2714, 1.3225, 1.3339, 1.3815, 1.4359, 1.49, 1.5347, 1.5496,
97
+ 1.617, 1.67, 1.7153, 1.7596, 1.7844, 1.8288, 1.8828, 1.9291, 2.0095, 2.0198, 2.0683, 2.1069,
98
+ 2.1748, 2.2137, 2.2345, 2.2752, 2.3413, 2.3918, 2.4388, 2.4595, 2.5444, 2.5985, 2.678, 2.7259,
99
+ 2.7657, 2.8086,
100
+ ],
101
+ hrs: [
102
+ 0.00265, 0.00338, 0.00437, 0.00539, 0.00644, 0.00817, 0.01029, 0.01296, 0.01474, 0.01552,
103
+ 0.01696, 0.01978, 0.02205, 0.02405, 0.02488, 0.02852, 0.031, 0.03377, 0.03596, 0.03769,
104
+ 0.04052, 0.04278, 0.04541, 0.04923, 0.05046, 0.05341, 0.05645, 0.06069, 0.06411, 0.06545,
105
+ 0.06937, 0.0739, 0.07785, 0.08092, 0.08261, 0.08865, 0.09257, 0.09635, 0.09939, 0.10209,
106
+ 0.106, 0.11041, 0.11524, 0.12204, 0.12313, 0.12873, 0.12947, 0.13114, 0.13513, 0.13629,
107
+ 0.1397, 0.14425, 0.14962, 0.15235, 0.15453, 0.16114, 0.16575, 0.17408, 0.17817, 0.17983,
108
+ 0.1833,
109
+ ],
110
+ },
111
+ ultra: {
112
+ usd: [
113
+ 0.4215, 0.5126, 0.5737, 0.6515, 0.702, 0.7922, 0.9108, 1.0969, 1.2137, 1.2729, 1.3559, 1.4659,
114
+ 1.5471, 1.6075, 1.6273, 1.7385, 1.8143, 1.9006, 1.9774, 2.0389, 2.1345, 2.211, 2.2993, 2.4146,
115
+ 2.4463, 2.5326, 2.6278, 2.7635, 2.8673, 2.8901, 2.9876, 3.0983, 3.2073, 3.2964, 3.3254,
116
+ 3.4593, 3.5632, 3.6518, 3.7384, 3.784, 3.8661, 3.9685, 4.0556, 4.2104, 4.229, 4.3174, 4.3912,
117
+ 4.5199, 4.5949, 4.6375, 4.7124, 4.8381, 4.931, 5.017, 5.0554, 5.2133, 5.3132, 5.4655, 5.5501,
118
+ 5.6254, 5.7067,
119
+ ],
120
+ hrs: [
121
+ 0.00265, 0.00338, 0.00437, 0.00539, 0.00644, 0.00817, 0.01029, 0.01296, 0.01474, 0.01552,
122
+ 0.01696, 0.01978, 0.02205, 0.02405, 0.02488, 0.02852, 0.031, 0.03377, 0.03596, 0.03769,
123
+ 0.04052, 0.04278, 0.04541, 0.04923, 0.05046, 0.05341, 0.05645, 0.06069, 0.06411, 0.06545,
124
+ 0.06937, 0.0739, 0.07785, 0.08092, 0.08261, 0.08865, 0.09257, 0.09635, 0.09939, 0.10209,
125
+ 0.106, 0.11041, 0.11524, 0.12204, 0.12313, 0.12873, 0.12947, 0.13114, 0.13513, 0.13629,
126
+ 0.1397, 0.14425, 0.14962, 0.15235, 0.15453, 0.16114, 0.16575, 0.17408, 0.17817, 0.17983,
127
+ 0.1833,
128
+ ],
129
+ },
130
+ };
131
+
132
+ /** Where the curve in use came from: the constants above, or this deployment's own sessions. */
133
+ export type CalibrationSource = "shipped" | "deployment";
134
+ export type Calibration = {
135
+ source: CalibrationSource;
136
+ /** YYYY-MM-DD the curve was derived. */
137
+ calibratedAt: string;
138
+ model: string;
139
+ curve: CurveSet;
140
+ /** The sessions the curve was derived from; absent on a row stored before this was recorded. */
141
+ window?: { start: string; end: string; sessions: number };
142
+ };
143
+
144
+ export const SHIPPED_CALIBRATION: Calibration = {
145
+ source: "shipped",
146
+ calibratedAt: CALIBRATED_AT,
147
+ model: CALIBRATION_MODEL,
148
+ curve: CURVE,
149
+ };
150
+
151
+ /** Global `swarm_config` key holding the JSON written by `POST /api/savings/calibration`. */
152
+ export const SAVINGS_CALIBRATION_KEY = "SAVINGS_CURVE_CALIBRATION";
153
+
154
+ const CurveArraySchema = z.array(z.number().positive()).length(TAU_MAX);
155
+ const TierCurveSchema = z.object({ usd: CurveArraySchema, hrs: CurveArraySchema });
156
+ export const StoredCalibrationSchema = z.object({
157
+ calibratedAt: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
158
+ model: z.string().min(1),
159
+ window: z
160
+ .object({ start: z.string(), end: z.string(), sessions: z.number().int().nonnegative() })
161
+ .optional(),
162
+ curve: z.object({
163
+ smol: TierCurveSchema,
164
+ regular: TierCurveSchema,
165
+ smart: TierCurveSchema,
166
+ ultra: TierCurveSchema,
167
+ }),
168
+ });
169
+
170
+ /** The stored deployment curve, or null when the value is missing or malformed (callers fall back to the shipped one). */
171
+ export function parseCalibration(raw: string | null | undefined): Calibration | null {
172
+ if (!raw) return null;
173
+ try {
174
+ const parsed = StoredCalibrationSchema.safeParse(JSON.parse(raw));
175
+ if (!parsed.success) return null;
176
+ const { calibratedAt, model, curve, window } = parsed.data;
177
+ return { source: "deployment", calibratedAt, model, curve, ...(window ? { window } : {}) };
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+
183
+ /** Linear interpolation on the tier curve; tau is clamped to [1, TAU_MAX]. */
184
+ export function curve(
185
+ tau: number,
186
+ tier: SavingsTier,
187
+ key: "usd" | "hrs",
188
+ set: CurveSet = CURVE,
189
+ ): number {
190
+ const t = Math.max(1, Math.min(TAU_MAX, tau));
191
+ const a = set[tier][key];
192
+ const lo = Math.floor(t);
193
+ const hi = Math.ceil(t);
194
+ const vLo = a[lo - 1] as number;
195
+ const vHi = a[hi - 1] as number;
196
+ return vLo + (vHi - vLo) * (t - lo);
197
+ }
198
+
199
+ /** Retired copies (`<name>-retired-YYYY-MM-DD`) are versions of one job. */
200
+ export function jobKey(name: string): string {
201
+ return name.replace(/-retired-\d{4}-\d{2}-\d{2}$/, "");
202
+ }
203
+
204
+ /** Count of `await` in a script's source, as the ops a swarm-script node performs. */
205
+ export function scriptOpsFromAwaitCount(awaits: number): number {
206
+ return Math.min(MAX_SCRIPT_OPS, Number(awaits) || 0);
207
+ }
208
+
209
+ type DefinitionNode = { id: string; type: string; config?: Record<string, unknown> };
210
+
211
+ /** Deterministic ops per node id. Agent-task, wait and control nodes count 0. */
212
+ export function nodeOpsOf(
213
+ definition: { nodes?: DefinitionNode[] } | null | undefined,
214
+ opsByScript: ReadonlyMap<string, number>,
215
+ ): Map<string, number> {
216
+ const ops = new Map<string, number>();
217
+ for (const node of definition?.nodes ?? []) {
218
+ let o = 0;
219
+ if (node.type === "swarm-script") {
220
+ const name = node.config?.scriptName;
221
+ o = (typeof name === "string" ? opsByScript.get(name) : undefined) ?? DEFAULT_OPS;
222
+ } else if (node.type === "script") {
223
+ o = Math.max(1, (JSON.stringify(node.config ?? {}).match(/\bawait\b/g) ?? []).length);
224
+ } else if (
225
+ ["system-one-decision", "system-one-extraction", "raw-llm", "notify", "code-match"].includes(
226
+ node.type,
227
+ )
228
+ ) {
229
+ o = 1;
230
+ }
231
+ ops.set(node.id, o);
232
+ }
233
+ return ops;
234
+ }
235
+
236
+ /** Tier-independent facts about one workflow over a window. */
237
+ export type WorkflowFacts = {
238
+ /** Every run that started in the window. */
239
+ runs: number;
240
+ /** Runs that were not skipped or cancelled. */
241
+ countedRuns: number;
242
+ /** Counted runs started by a schedule. */
243
+ schedRuns: number;
244
+ /** Of `schedRuns`, the runs that created an agent task or started a child workflow. */
245
+ schedEffectRuns: number;
246
+ /** Deterministic ops summed over every step of every run. */
247
+ opsSum: number;
248
+ agentTasks: number;
249
+ /** Session cost of the agent tasks the runs created. */
250
+ agentUsd: number;
251
+ agentMs: number;
252
+ /** Lead follow-up review cost of those agent tasks. */
253
+ followupUsd: number;
254
+ /** LLM cost a run reported itself (report node). */
255
+ recordedLlmUsd: number;
256
+ /** LLM cost estimated from SystemOne tokens and raw-llm output size. */
257
+ estimatedLlmUsd: number;
258
+ /** Wall time of the deterministic steps. */
259
+ computeSecs: number;
260
+ };
261
+
262
+ export type PricedWorkflow = {
263
+ runs: number;
264
+ substitutedRuns: number;
265
+ /** Schedule runs above the hourly cap that still count because they had an effect. */
266
+ effectRuns: number;
267
+ enabledOnlyRuns: number;
268
+ capApplied: boolean;
269
+ opsPerRun: number;
270
+ /** Measured spend of every run in the window: agent tasks, their reviews, recorded LLM cost. */
271
+ measuredUsd: number;
272
+ /**
273
+ * LLM spend estimated from tokens and output size, not measured. Zero when the
274
+ * runs recorded their LLM cost, which then counts in `measuredUsd` instead.
275
+ */
276
+ estimatedLlmUsd: number;
277
+ /**
278
+ * Scaled estimate, not a measurement:
279
+ * `(measuredUsd + estimatedLlmUsd) * substitutedRuns / runs`.
280
+ * The estimator's actual side; it assumes spend is spread evenly over runs.
281
+ */
282
+ actualUsd: number;
283
+ agentOnlyUsd: SavingsBand;
284
+ savingUsd: SavingsBand;
285
+ /** Scaled estimate like `actualUsd`: measured hours times the substituted share. */
286
+ actualHours: number;
287
+ agentOnlyHours: SavingsBand;
288
+ hoursSaved: SavingsBand;
289
+ /** What one substituted run would cost an agent at p50 (R * curve + review). */
290
+ agentOnlyUsdPerRun: number;
291
+ };
292
+
293
+ /**
294
+ * Split spend into measured and estimated. The window picks the LLM source
295
+ * (`useRecorded`): when any run recorded its LLM cost, no day adds an estimate.
296
+ */
297
+ function spendOf(
298
+ facts: WorkflowFacts,
299
+ useRecorded: boolean,
300
+ ): { measuredUsd: number; estimatedLlmUsd: number } {
301
+ return {
302
+ measuredUsd: facts.agentUsd + facts.followupUsd + (useRecorded ? facts.recordedLlmUsd : 0),
303
+ estimatedLlmUsd: useRecorded ? 0 : facts.estimatedLlmUsd,
304
+ };
305
+ }
306
+
307
+ const bandOf = (fn: (q: Quantile) => number): SavingsBand => ({
308
+ p10: fn("p10"),
309
+ p50: fn("p50"),
310
+ p90: fn("p90"),
311
+ });
312
+
313
+ /**
314
+ * Price one workflow's facts at a tier. `band` picks the error spread: `job`
315
+ * for a single job, `fleet` for a sum over many jobs. `curve` overrides the
316
+ * shipped session-cost curve with a deployment calibration.
317
+ */
318
+ export function priceWorkflow(
319
+ facts: WorkflowFacts,
320
+ opts: { tier: SavingsTier; days: number; band: "job" | "fleet"; curve?: CurveSet },
321
+ ): PricedWorkflow {
322
+ const cap = CAP_PER_DAY * opts.days;
323
+ const runs = facts.runs;
324
+ // Schedule runs: at most the hourly cap, but a run with a downstream effect always counts.
325
+ const vCap = Math.min(facts.schedRuns, cap);
326
+ const vSched = Math.max(vCap, facts.schedEffectRuns);
327
+ const substituted = vSched + (facts.countedRuns - facts.schedRuns);
328
+ const opsPerRun = runs > 0 ? facts.opsSum / runs : 0;
329
+ const tau = Math.min(TAU_MAX, T0 + K * opsPerRun);
330
+ // A pure agent dispatcher (no deterministic ops) substitutes nothing.
331
+ const orchestrates = !(opsPerRun < 1 && facts.agentTasks > 0);
332
+ const unitUsd = orchestrates ? curve(tau, opts.tier, "usd", opts.curve) : 0;
333
+ const unitHrs = orchestrates ? curve(tau, opts.tier, "hrs", opts.curve) : 0;
334
+ const review = unitUsd > 0 ? F_FOLLOWUP : 0;
335
+ const share = runs > 0 ? substituted / runs : 0;
336
+ const { measuredUsd, estimatedLlmUsd } = spendOf(facts, facts.recordedLlmUsd > 0);
337
+ const keptUsd = (facts.agentUsd + facts.followupUsd) * share;
338
+ const keptHours = (facts.agentMs / 3.6e6) * share;
339
+ const actualUsd = (measuredUsd + estimatedLlmUsd) * share;
340
+ const actualHours = (facts.agentMs / 3.6e6 + facts.computeSecs / 3600) * share;
341
+ const err = opts.band === "job" ? ERR_JOB : ERR_FLEET;
342
+ const agentOnlyUsd = bandOf((q) => keptUsd + substituted * (R[q] * unitUsd * err[q] + review));
343
+ const agentOnlyHours = bandOf((q) => keptHours + substituted * R[q] * unitHrs * err[q]);
344
+ return {
345
+ runs,
346
+ substitutedRuns: substituted,
347
+ effectRuns: vSched - vCap,
348
+ enabledOnlyRuns: runs - substituted,
349
+ capApplied: facts.schedRuns > cap,
350
+ opsPerRun,
351
+ measuredUsd,
352
+ estimatedLlmUsd,
353
+ actualUsd,
354
+ agentOnlyUsd,
355
+ savingUsd: bandOf((q) => agentOnlyUsd[q] - actualUsd),
356
+ actualHours,
357
+ agentOnlyHours,
358
+ hoursSaved: bandOf((q) => agentOnlyHours[q] - actualHours),
359
+ agentOnlyUsdPerRun: R.p50 * unitUsd + review,
360
+ };
361
+ }
362
+
363
+ /**
364
+ * Split a window's p50 saving, scaled actual cost, measured spend and
365
+ * estimated LLM spend across the UTC days its runs started on, so the days
366
+ * sum to `priceWorkflow` over the window. The unit
367
+ * cost (tau), the substituted share and the LLM source are the window's.
368
+ * When the hourly cap or the effect rule makes the window's counted schedule
369
+ * runs differ from the raw ones, they are spread pro rata over the days'
370
+ * schedule runs.
371
+ */
372
+ export function splitByDay(
373
+ facts: WorkflowFacts,
374
+ byDay: readonly (WorkflowFacts & { day: string })[],
375
+ opts: { tier: SavingsTier; days: number; curve?: CurveSet },
376
+ ): {
377
+ day: string;
378
+ savingUsd: number;
379
+ actualUsd: number;
380
+ measuredUsd: number;
381
+ estimatedLlmUsd: number;
382
+ }[] {
383
+ const priced = priceWorkflow(facts, { ...opts, band: "job" });
384
+ const runs = facts.runs;
385
+ const share = runs > 0 ? priced.substitutedRuns / runs : 0;
386
+ const nonSched = facts.countedRuns - facts.schedRuns;
387
+ const vSched = priced.substitutedRuns - nonSched;
388
+ // p50 agent-only cost of one substituted run (ERR_JOB.p50 is 1). The sum test pins this.
389
+ const unitUsd = priced.agentOnlyUsdPerRun;
390
+ const useRecorded = facts.recordedLlmUsd > 0;
391
+ return byDay.map((d) => {
392
+ const substituted =
393
+ (facts.schedRuns > 0 ? (vSched * d.schedRuns) / facts.schedRuns : 0) +
394
+ (d.countedRuns - d.schedRuns);
395
+ const { measuredUsd, estimatedLlmUsd } = spendOf(d, useRecorded);
396
+ const keptUsd = (d.agentUsd + d.followupUsd) * share;
397
+ const actualUsd = (measuredUsd + estimatedLlmUsd) * share;
398
+ return {
399
+ day: d.day,
400
+ savingUsd: keptUsd + substituted * unitUsd - actualUsd,
401
+ actualUsd,
402
+ measuredUsd,
403
+ estimatedLlmUsd,
404
+ };
405
+ });
406
+ }
@@ -228,6 +228,11 @@ export interface SwarmSdk {
228
228
  // --- scripts ---
229
229
  script_search(args: { query?: string; scope?: ScriptScope; limit?: number }): Promise<unknown>;
230
230
  script_run(args: { name?: string; source?: string; args?: unknown; intent?: string; scope?: ScriptScope; fsMode?: ScriptFsMode; executor?: ScriptExecutorName | null; idempotencyKey?: string }): Promise<unknown>;
231
+ // --- savings calibration (REST only) ---
232
+ /** The savings curve in use (shipped or derived from this deployment) and the stored row's metadata. */
233
+ savings_calibrationGet(): Promise<unknown>;
234
+ /** Derive the curve from the last \`days\` of sessions. Read-only unless \`apply\` is true (needs config write access). One run at a time; takes up to 120 s, so call it from a script with a long enough timeout. */
235
+ savings_calibrationRun(args?: { days?: number; end?: string; apply?: boolean }): Promise<unknown>;
231
236
  // --- swarm / agent ---
232
237
  swarm_get(args?: { includeFull?: boolean }): Promise<unknown>;
233
238
  agent_info(args?: Record<string, unknown>): Promise<unknown>;
@@ -233,6 +233,7 @@ export type SharedOrgInviteResult = {
233
233
  inviteId?: string;
234
234
  expiresAt?: string;
235
235
  acceptUrl?: string;
236
+ token?: string;
236
237
  };
237
238
 
238
239
  /**
@@ -242,10 +243,12 @@ export type SharedOrgInviteResult = {
242
243
  * Connect-to-Drive flow) never need the bootstrap key itself — it is
243
244
  * API-only and never served over HTTP.
244
245
  *
245
- * agent-fs (>= 0.18.9) adds an email that has an account directly
246
- * (`status: "added"`) and answers an email without one with a pending invite
247
- * (`status: "pending"`, plus `acceptUrl` when its app URL is configured).
248
- * agent-fs sends no email, so the accept link is passed back to the caller.
246
+ * agent-fs (>= 0.18.19) adds an email that is already in the org directly
247
+ * (`status: "added"`) and answers any other email, with or without an account,
248
+ * with a pending invite (`status: "pending"`, the accept `token`, plus
249
+ * `acceptUrl` when its app URL is configured). agent-fs sends no email, so the
250
+ * token and link are passed back to the caller. Only the invited account can
251
+ * accept, with its own key (`POST /invites/{token}/accept`).
249
252
  */
250
253
  export async function inviteEmailToSharedOrg(
251
254
  email: string,
@@ -266,6 +269,7 @@ export async function inviteEmailToSharedOrg(
266
269
  inviteId?: unknown;
267
270
  expiresAt?: unknown;
268
271
  acceptUrl?: unknown;
272
+ token?: unknown;
269
273
  }>(shared.apiUrl, `/orgs/${encodeURIComponent(shared.orgId)}/members/invite`, {
270
274
  method: "POST",
271
275
  headers: shared.authHeaders,
@@ -283,6 +287,7 @@ export async function inviteEmailToSharedOrg(
283
287
  ...(typeof response.inviteId === "string" ? { inviteId: response.inviteId } : {}),
284
288
  ...(typeof response.expiresAt === "string" ? { expiresAt: response.expiresAt } : {}),
285
289
  ...(typeof response.acceptUrl === "string" ? { acceptUrl: response.acceptUrl } : {}),
290
+ ...(typeof response.token === "string" ? { token: response.token } : {}),
286
291
  };
287
292
  }
288
293
 
@@ -347,7 +352,13 @@ export async function ensureAgentFsCredentialsForAgent(agentId: string): Promise
347
352
  const currentRoles = await getCurrentOrgMemberRoles(apiUrl, shared.authHeaders, shared.orgId);
348
353
  const currentRole = currentRoles.get(email.toLowerCase());
349
354
  if (!currentRole || roleRank(currentRole) < roleRank("editor")) {
350
- await inviteToSharedOrg(apiUrl, shared.authHeaders, shared.orgId, { email, role: "editor" });
355
+ await inviteToSharedOrg(
356
+ apiUrl,
357
+ shared.authHeaders,
358
+ shared.orgId,
359
+ { email, role: "editor" },
360
+ { acceptWithApiKey: apiKey },
361
+ );
351
362
  }
352
363
 
353
364
  await upsertSwarmConfig({
@@ -449,14 +460,40 @@ async function inviteToSharedOrg(
449
460
  headers: Record<string, string>,
450
461
  orgId: string,
451
462
  invite: InviteTarget,
463
+ options: { acceptWithApiKey?: string } = {},
452
464
  ): Promise<"invited" | "no-account" | "transient-failure"> {
453
465
  try {
454
- await agentFsRequest(apiUrl, `/orgs/${encodeURIComponent(orgId)}/members/invite`, {
455
- method: "POST",
456
- headers,
457
- body: invite,
458
- allowConflict: true,
459
- });
466
+ const response = await agentFsRequest<{ status?: unknown; token?: unknown }>(
467
+ apiUrl,
468
+ `/orgs/${encodeURIComponent(orgId)}/members/invite`,
469
+ {
470
+ method: "POST",
471
+ headers,
472
+ body: invite,
473
+ allowConflict: true,
474
+ },
475
+ );
476
+ // agent-fs >= 0.18.19 answers an account that is not yet in the org with a
477
+ // pending invite, even when the account exists. An agent account is ours,
478
+ // so accept it with the agent's own key; without that the agent never joins.
479
+ if (
480
+ options.acceptWithApiKey &&
481
+ response?.status === "pending" &&
482
+ typeof response.token === "string"
483
+ ) {
484
+ try {
485
+ await agentFsRequest(apiUrl, `/invites/${encodeURIComponent(response.token)}/accept`, {
486
+ method: "POST",
487
+ headers: { authorization: `Bearer ${options.acceptWithApiKey}` },
488
+ allowConflict: true,
489
+ });
490
+ } catch (error) {
491
+ // The request path carries the invite token: rethrow without it.
492
+ throw new Error(
493
+ `agent-fs invite accept failed${error instanceof AgentFsRequestError ? `: HTTP ${error.status}` : ""}`,
494
+ );
495
+ }
496
+ }
460
497
  return "invited";
461
498
  } catch (error) {
462
499
  console.warn(
@@ -204,10 +204,6 @@ export function loadSeedWorkflows(
204
204
  .sort((left, right) => left.name.localeCompare(right.name));
205
205
  }
206
206
 
207
- function workflowSeedHash(workflow: SeedWorkflow): string {
208
- return computeContentHash(canonicalJson(workflow));
209
- }
210
-
211
207
  async function findWorkflowByName(name: string): Promise<Workflow | null> {
212
208
  return (await listWorkflows()).find((workflow) => workflow.name === name) ?? null;
213
209
  }
@@ -261,27 +257,55 @@ function executableSurface(workflow: SeedWorkflow): string {
261
257
  return canonicalJson(surface);
262
258
  }
263
259
 
260
+ /**
261
+ * The seed hash covers the executable surface only, so an operator setting
262
+ * (an `input` value, on/off, cooldown, description, event triggers) neither
263
+ * reads as a user edit nor blocks a later template update.
264
+ */
265
+ function workflowSeedHash(workflow: SeedWorkflow): string {
266
+ return computeContentHash(executableSurface(workflow));
267
+ }
268
+
269
+ /**
270
+ * The hash older releases recorded in `seed_state`: the whole workflow,
271
+ * operator settings included. Only used to recognise those rows; the next
272
+ * update or in-sync check rewrites them with {@link workflowSeedHash}.
273
+ */
274
+ function legacyWorkflowSeedHash(workflow: SeedWorkflow): string {
275
+ return computeContentHash(canonicalJson(workflow));
276
+ }
277
+
278
+ /**
279
+ * Whether the live workflow still executes what the seeder last wrote, whose
280
+ * hash is `seededHash`. A legacy whole-workflow hash matches the live row
281
+ * itself, or the version snapshot taken before the first edit when that
282
+ * snapshot has the same executable surface as the live row. A legacy edit
283
+ * with no such snapshot counts as edited.
284
+ */
285
+ async function executesSeededSurface(workflow: Workflow, seededHash: string): Promise<boolean> {
286
+ const live = workflowFromRow(workflow);
287
+ if (workflowSeedHash(live) === seededHash) return true;
288
+ if (legacyWorkflowSeedHash(live) === seededHash) return true;
289
+ for (const version of await getWorkflowVersions(workflow.id)) {
290
+ const seeded = workflowFromSnapshot(version.snapshot);
291
+ if (legacyWorkflowSeedHash(seeded) !== seededHash) continue;
292
+ return executableSurface(seeded) === executableSurface(live);
293
+ }
294
+ return false;
295
+ }
296
+
264
297
  /**
265
298
  * Whether a live workflow still runs seed source: `pristine` while what it
266
299
  * executes matches what the seeder last wrote for its name, `edited` once
267
300
  * anyone changed that, `unseeded` for a workflow the seeder never wrote.
268
- * Operator settings (see `executableSurface`) keep it `pristine`. The seeded
269
- * state is the live row itself or, once edited, the version snapshot taken
270
- * before the first edit; an edit with no such snapshot counts as `edited`.
301
+ * Operator settings (see `executableSurface`) keep it `pristine`.
271
302
  */
272
303
  export async function seededWorkflowState(
273
304
  workflow: Workflow,
274
305
  ): Promise<"pristine" | "edited" | "unseeded"> {
275
306
  const state = await getSeedState("workflow", workflow.name);
276
307
  if (!state) return "unseeded";
277
- const live = workflowFromRow(workflow);
278
- if (workflowSeedHash(live) === state.seededHash) return "pristine";
279
- for (const version of await getWorkflowVersions(workflow.id)) {
280
- const seeded = workflowFromSnapshot(version.snapshot);
281
- if (workflowSeedHash(seeded) !== state.seededHash) continue;
282
- return executableSurface(seeded) === executableSurface(live) ? "pristine" : "edited";
283
- }
284
- return "edited";
308
+ return (await executesSeededSurface(workflow, state.seededHash)) ? "pristine" : "edited";
285
309
  }
286
310
 
287
311
  export function createWorkflowsSeeder(
@@ -301,7 +325,17 @@ export function createWorkflowsSeeder(
301
325
 
302
326
  async upstreamHash(item): Promise<string | null> {
303
327
  const existing = await findWorkflowByName(item.key);
304
- return existing ? workflowSeedHash(workflowFromRow(existing)) : null;
328
+ if (!existing) return null;
329
+ const liveHash = workflowSeedHash(workflowFromRow(existing));
330
+ if (liveHash === item.contentHash) return liveHash;
331
+ // The runner calls a workflow pristine when this equals the recorded
332
+ // hash. A legacy row records a whole-workflow hash, so report the
333
+ // recorded hash itself while the workflow still executes that seed.
334
+ const state = await getSeedState("workflow", item.key);
335
+ if (state && (await executesSeededSurface(existing, state.seededHash))) {
336
+ return state.seededHash;
337
+ }
338
+ return liveHash;
305
339
  },
306
340
 
307
341
  async apply(item): Promise<void> {
@@ -311,12 +345,8 @@ export function createWorkflowsSeeder(
311
345
  throw new Error(`Invalid workflow definition: ${validation.errors.join("; ")}`);
312
346
  }
313
347
 
314
- const data = {
315
- description: workflow.description,
348
+ const executable = {
316
349
  definition: workflow.definition,
317
- triggers: workflow.triggers,
318
- cooldown: workflow.cooldown,
319
- input: workflow.input,
320
350
  triggerSchema: workflow.triggerSchema,
321
351
  params: workflow.params,
322
352
  requiredParams: workflow.requiredParams,
@@ -324,12 +354,26 @@ export function createWorkflowsSeeder(
324
354
  };
325
355
  const existing = await findWorkflowByName(workflow.name);
326
356
  if (!existing) {
327
- const created = await createWorkflow({ name: workflow.name, ...data });
357
+ const created = await createWorkflow({
358
+ name: workflow.name,
359
+ ...executable,
360
+ description: workflow.description,
361
+ triggers: workflow.triggers,
362
+ cooldown: workflow.cooldown,
363
+ input: workflow.input,
364
+ });
328
365
  if (!workflow.enabled) await updateWorkflow(created.id, { enabled: false });
329
366
  return;
330
367
  }
331
368
 
332
- await updateWorkflow(existing.id, { ...data, enabled: workflow.enabled });
369
+ // The seed hash leaves operator settings out, so an update must not
370
+ // overwrite them: the live description, on/off, cooldown and event
371
+ // triggers stay as they are, and so do live input values. Input keys the
372
+ // template added are filled from the template, so new nodes that read
373
+ // them still resolve.
374
+ const input =
375
+ workflow.input || existing.input ? { ...workflow.input, ...existing.input } : undefined;
376
+ await updateWorkflow(existing.id, { ...executable, input });
333
377
  },
334
378
  };
335
379
  }