@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
@@ -56,6 +56,8 @@ import {
56
56
  startEventLoopLagProbe,
57
57
  stopEventLoopLagProbe,
58
58
  init_event_loop_lag,
59
+ DbTransactionDeadlineError,
60
+ init_db_client,
59
61
  getPromptTemplateDefaultDrift,
60
62
  init_default_drift,
61
63
  init_templates2,
@@ -192,6 +194,8 @@ import {
192
194
  modelProfileReferences,
193
195
  modelProfileRefError,
194
196
  deleteModelProfile,
197
+ MAX_MODEL_PROFILE_FALLBACKS,
198
+ modelProfileFallbacksError,
195
199
  taskProfileError,
196
200
  scheduleProfileUpdate,
197
201
  init_model_profiles,
@@ -522,7 +526,7 @@ import {
522
526
  countScriptRunJournalSteps2,
523
527
  countScriptRunJournalAgentTaskSteps2,
524
528
  init_db4
525
- } from "./cli-7w69ne2f.js";
529
+ } from "./cli-rcecc3yq.js";
526
530
  import {
527
531
  PRIMARY_ROLE_NAMES2,
528
532
  OperatorGrantedTargetError2,
@@ -536,17 +540,17 @@ import {
536
540
  assertNotLastAdmin2,
537
541
  setUserRoles2,
538
542
  init_rbac_roles
539
- } from "./cli-1xh9a7hn.js";
540
- import"./cli-k26bkr9t.js";
543
+ } from "./cli-q24n86d2.js";
544
+ import"./cli-b98a65ed.js";
541
545
  import {
542
546
  requestModelCatalogRefresh2,
543
547
  init_pricing_refresh
544
- } from "./cli-a3b239vq.js";
548
+ } from "./cli-t2tma8gb.js";
545
549
  import {
546
550
  workflowEventBus2,
547
551
  init_event_bus
548
552
  } from "./cli-eddnyg3t.js";
549
- import"./cli-b8e9nb04.js";
553
+ import"./cli-fpjmegdb.js";
550
554
  import {
551
555
  require_dist4,
552
556
  getSlackConnectionState,
@@ -577,12 +581,12 @@ import {
577
581
  startSlackApp2,
578
582
  stopSlackApp2,
579
583
  init_app3
580
- } from "./cli-4r05hnqa.js";
584
+ } from "./cli-4vzgeta4.js";
581
585
  import {
582
586
  retryFailedRun2,
583
587
  cancelWorkflowRun2,
584
588
  init_resume
585
- } from "./cli-vbh10fqa.js";
589
+ } from "./cli-j24zbska.js";
586
590
  import {
587
591
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
588
592
  SUPPORTED_PROTOCOL_VERSIONS,
@@ -678,6 +682,7 @@ import {
678
682
  loadEnabledExtensions,
679
683
  stopExtensionRuntime,
680
684
  init_lifecycle,
685
+ nextFallback2,
681
686
  createWorkerTaskFollowUp2,
682
687
  createResumeFollowUp2,
683
688
  init_worker_follow_up,
@@ -836,8 +841,13 @@ import {
836
841
  cancelTaskOutputSchema,
837
842
  cancelTaskHandler,
838
843
  init_cancel_task,
844
+ DbQueryTimeoutError,
845
+ DbQueryConcurrencyCapError,
839
846
  executeReadOnlyQuery,
847
+ getDbQueryHttpBudgetMs,
848
+ init_db_query_shared,
840
849
  assertSelectOnlyQuery,
850
+ executeReadOnlyQueryGated,
841
851
  handleDbQuery,
842
852
  init_db_query,
843
853
  snapshotMetric,
@@ -1000,7 +1010,7 @@ import {
1000
1010
  getEnabledCapabilities,
1001
1011
  createServer,
1002
1012
  init_server
1003
- } from "./cli-93k32c37.js";
1013
+ } from "./cli-3e875j5p.js";
1004
1014
  import {
1005
1015
  FilesError,
1006
1016
  normalizeFilesError,
@@ -1033,7 +1043,7 @@ import {
1033
1043
  resolvePoolDelivery2,
1034
1044
  createPoolAgent2,
1035
1045
  init_db2
1036
- } from "./cli-k93bq1wq.js";
1046
+ } from "./cli-97ae65rz.js";
1037
1047
  import {
1038
1048
  duplicateGuardedQueryKey,
1039
1049
  warnIfCorsAllowsAnyOrigin,
@@ -1090,7 +1100,7 @@ import {
1090
1100
  describeRequestRoute,
1091
1101
  route,
1092
1102
  init_route_def
1093
- } from "./cli-b5rs97a6.js";
1103
+ } from "./cli-5y340nzn.js";
1094
1104
  import {
1095
1105
  startPoolRouting,
1096
1106
  stopPoolRouting,
@@ -1103,13 +1113,13 @@ import {
1103
1113
  checkHeartbeatChecklist2,
1104
1114
  runHeartbeatSweep2,
1105
1115
  stopHeartbeat2
1106
- } from "./cli-b085njxz.js";
1107
- import"./cli-m4dqmnbp.js";
1116
+ } from "./cli-959kp5h2.js";
1117
+ import"./cli-9mb2q6pb.js";
1108
1118
  import {
1109
1119
  runtimeSupervisorStatus,
1110
1120
  startRuntimeSupervisor,
1111
1121
  stopRuntimeSupervisor
1112
- } from "./cli-k0615eh8.js";
1122
+ } from "./cli-3sy2xags.js";
1113
1123
  import {
1114
1124
  TASK_TITLE_TIMEOUT_MS,
1115
1125
  generateTaskTitle
@@ -1134,11 +1144,11 @@ import {
1134
1144
  isUnknownModelError,
1135
1145
  checkProviderPoolKey,
1136
1146
  writeSkillsToFilesystem
1137
- } from "./cli-jcpr5smb.js";
1147
+ } from "./cli-837vfs2x.js";
1138
1148
  import {
1139
1149
  inviteEmailToSharedOrg,
1140
1150
  ensureAgentFsCredentialsForAgent
1141
- } from "./cli-89cqnasv.js";
1151
+ } from "./cli-26ctbcdp.js";
1142
1152
  import {
1143
1153
  Anthropic
1144
1154
  } from "./cli-7349va39.js";
@@ -1243,7 +1253,7 @@ import {
1243
1253
  init_typecheck,
1244
1254
  parseSkillContent,
1245
1255
  init_skill_parser
1246
- } from "./cli-0ntbxyaa.js";
1256
+ } from "./cli-fwy8kfd6.js";
1247
1257
  import {
1248
1258
  signalProcessGroup,
1249
1259
  detachedProcessGroup,
@@ -1260,7 +1270,7 @@ import {
1260
1270
  forceRefreshAuthorizationOrThrow,
1261
1271
  forceRefreshTokenOrThrow,
1262
1272
  init_ensure_token
1263
- } from "./cli-yn2bbre9.js";
1273
+ } from "./cli-rmzsadkf.js";
1264
1274
  import {
1265
1275
  automationIntegrationFixUrl,
1266
1276
  preflightAutomation,
@@ -1304,7 +1314,7 @@ import {
1304
1314
  definitionNodeIds,
1305
1315
  validateDefinition,
1306
1316
  init_definition2
1307
- } from "./cli-vqptjbr7.js";
1317
+ } from "./cli-jdknh18m.js";
1308
1318
  import {
1309
1319
  _fetchHolder,
1310
1320
  CLIENT_ID,
@@ -1328,7 +1338,7 @@ import {
1328
1338
  import {
1329
1339
  require_content_type
1330
1340
  } from "./cli-yjdgea32.js";
1331
- import"./cli-dy32zecz.js";
1341
+ import"./cli-3vmb0n58.js";
1332
1342
  import {
1333
1343
  isInvalidClientError,
1334
1344
  publicEndpointSsrfOptions,
@@ -1346,11 +1356,11 @@ import {
1346
1356
  revokeMcpToken,
1347
1357
  computeExpiresAt,
1348
1358
  init_mcp_wrapper
1349
- } from "./cli-zcsw143p.js";
1359
+ } from "./cli-n6vtrcht.js";
1350
1360
  import {
1351
1361
  createRuntimeProvider,
1352
1362
  init_runtime_providers
1353
- } from "./cli-hxpyc9sn.js";
1363
+ } from "./cli-z1w943va.js";
1354
1364
  import"./cli-v41kn3cd.js";
1355
1365
  import {
1356
1366
  setBedrockProviderModule,
@@ -1387,13 +1397,13 @@ import {
1387
1397
  revokeAgentTokens,
1388
1398
  fingerprintApiKey,
1389
1399
  init_users
1390
- } from "./cli-re4raaj0.js";
1400
+ } from "./cli-f4e8r23x.js";
1391
1401
  import {
1392
1402
  AMP_ESTIMATE_MODELS,
1393
1403
  ampBillsCacheWrites,
1394
1404
  resolveAmpModel,
1395
1405
  init_amp_models
1396
- } from "./cli-p1w18yhx.js";
1406
+ } from "./cli-1pz0330a.js";
1397
1407
  import {
1398
1408
  ASSET_KEY_MAX_LENGTH,
1399
1409
  normalizeAssetKey,
@@ -1426,6 +1436,7 @@ import {
1426
1436
  ModelProfileNameSchema,
1427
1437
  ModelProfileCredentialsSchema,
1428
1438
  ModelProfileSchema,
1439
+ ProviderErrorClassSchema,
1429
1440
  ProfileCheckResultSchema,
1430
1441
  SessionAccessSchema,
1431
1442
  SessionOwnerSchema,
@@ -1555,7 +1566,7 @@ import {
1555
1566
  KvKeySchema,
1556
1567
  KvEntrySchema,
1557
1568
  init_types4
1558
- } from "./cli-2zp0et3v.js";
1569
+ } from "./cli-pchypa1s.js";
1559
1570
  import {
1560
1571
  CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
1561
1572
  CODEX_AUTH_WATCH_NAMESPACE,
@@ -1566,7 +1577,7 @@ import {
1566
1577
  IDENTITY_FIELD_BUDGETS,
1567
1578
  IdentityFieldBudgetError,
1568
1579
  init_identity_field_budget
1569
- } from "./cli-tk7cjj8h.js";
1580
+ } from "./cli-dzpc6en0.js";
1570
1581
  import {
1571
1582
  getSlackConfiguration,
1572
1583
  init_config4
@@ -1632,12 +1643,13 @@ import {
1632
1643
  lazy,
1633
1644
  preprocess,
1634
1645
  ZodIssueCode,
1646
+ exports_iso,
1635
1647
  exports_coerce
1636
1648
  } from "./cli-hg42n3hx.js";
1637
1649
  import {
1638
1650
  init_package,
1639
1651
  package_default
1640
- } from "./cli-yncmerje.js";
1652
+ } from "./cli-zh9rsbqf.js";
1641
1653
  import {
1642
1654
  realtimeBus,
1643
1655
  init_bus
@@ -1654,7 +1666,7 @@ import {
1654
1666
  isCombEnabled,
1655
1667
  isAgentFsProxyEnabled,
1656
1668
  init_constants3
1657
- } from "./cli-k0wwfqbg.js";
1669
+ } from "./cli-dns0y538.js";
1658
1670
  import {
1659
1671
  parseEnvFlag,
1660
1672
  isEnvFlagEnabled,
@@ -11272,6 +11284,23 @@ declare module "swarm-extension" {
11272
11284
  modelTier?: "smol" | "regular" | "smart" | "ultra" | undefined;
11273
11285
  effort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;
11274
11286
  profile?: string | undefined;
11287
+ fallbackHops?:
11288
+ | {
11289
+ from: string;
11290
+ profile: string;
11291
+ errorClass:
11292
+ | "rate_limit"
11293
+ | "model_window"
11294
+ | "seat"
11295
+ | "credits"
11296
+ | "overloaded"
11297
+ | "server_error"
11298
+ | "auth"
11299
+ | "pool_empty";
11300
+ at: string;
11301
+ skipped?: { profile: string; reason: string }[] | undefined;
11302
+ }[]
11303
+ | undefined;
11275
11304
  scheduleId?: string | undefined;
11276
11305
  workflowRunId?: string | undefined;
11277
11306
  workflowRunStepId?: string | undefined;
@@ -11414,6 +11443,23 @@ declare module "swarm-extension" {
11414
11443
  resolvedEffort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;
11415
11444
  profile?: string | undefined;
11416
11445
  resolvedProfile?: string | undefined;
11446
+ fallbackHops?:
11447
+ | {
11448
+ from: string;
11449
+ profile: string;
11450
+ errorClass:
11451
+ | "rate_limit"
11452
+ | "model_window"
11453
+ | "seat"
11454
+ | "credits"
11455
+ | "overloaded"
11456
+ | "server_error"
11457
+ | "auth"
11458
+ | "pool_empty";
11459
+ at: string;
11460
+ skipped?: { profile: string; reason: string }[] | undefined;
11461
+ }[]
11462
+ | undefined;
11417
11463
  scheduleId?: string | undefined;
11418
11464
  workflowRunId?: string | null | undefined;
11419
11465
  workflowRunStepId?: string | null | undefined;
@@ -15303,10 +15349,11 @@ var agentFsCredentialStateSchema = object2({
15303
15349
  var agentFsInviteStateSchema = object2({
15304
15350
  orgId: string2(),
15305
15351
  invited: boolean().describe("False only when the email already holds the requested role."),
15306
- status: _enum2(["already_member", "added", "pending"]).describe("already_member: no change. added: an existing agent-fs account joined the org. pending: the email has no account, so agent-fs created an invite the person must accept."),
15352
+ status: _enum2(["already_member", "added", "pending"]).describe("already_member: no change. added: the email was already in the org and holds the role now. pending: agent-fs created an invite the person must accept (agent-fs >= 0.18.19 does this for every email not yet in the org, with or without an account)."),
15307
15353
  inviteId: string2().optional().describe("Pending invite id (status pending)."),
15308
15354
  expiresAt: string2().optional().describe("ISO time the accept link expires (status pending)."),
15309
- acceptUrl: string2().optional().describe("Link the invitee opens to accept (status pending). agent-fs sends no email, so hand it to the person. Absent when agent-fs has no app URL configured.")
15355
+ acceptUrl: string2().optional().describe("Link the invitee opens to accept (status pending). agent-fs sends no email, so hand it to the person. Absent when agent-fs has no app URL configured."),
15356
+ token: string2().optional().describe("Accept token (status pending). Only the invited account can redeem it, with its own key: agent-fs POST /invites/{token}/accept.")
15310
15357
  });
15311
15358
  var signedUrlResponseSchema = object2({
15312
15359
  url: string2(),
@@ -15346,7 +15393,7 @@ var inviteMemberRoute = route({
15346
15393
  path: "/api/fs/members/invite",
15347
15394
  pattern: ["api", "fs", "members", "invite"],
15348
15395
  summary: "Invite an external member into the agent-fs shared org",
15349
- description: "The API server performs the invite with its own bootstrap credentials (which are API-only and never served over HTTP), provisioning the shared org/drive first when needed. Intended for the cloud control plane's Connect-to-Drive flow. An email with an agent-fs account is added directly (status added). An email without one gets a pending invite (status pending) with an acceptUrl when agent-fs returns one; agent-fs sends no email, so the caller must hand the link to the invitee. No keys are returned; the invitee obtains their own key via agent-fs registration.",
15396
+ description: "The API server performs the invite with its own bootstrap credentials (which are API-only and never served over HTTP), provisioning the shared org/drive first when needed. Intended for the cloud control plane's Connect-to-Drive flow. An email already in the org gets the grant directly (status added). Any other email gets a pending invite (status pending) with its accept token, and an acceptUrl when agent-fs returns one; agent-fs sends no email, so the caller must hand the link to the invitee, or accept with the invitee's own key. No keys are returned; the invitee obtains their own key via agent-fs registration.",
15350
15397
  tags: ["FS"],
15351
15398
  body: object2({
15352
15399
  email: email(),
@@ -22496,6 +22543,7 @@ async function handleMetrics(req, res, pathSegments, queryParams, myAgentId) {
22496
22543
  init_src2();
22497
22544
  init_zod();
22498
22545
  init_audit_user();
22546
+ init_db4();
22499
22547
  init_model_profiles();
22500
22548
  init_model_validation2();
22501
22549
  init_rbac();
@@ -22536,7 +22584,7 @@ var createProfile = route({
22536
22584
  path: "/api/model-profiles",
22537
22585
  pattern: ["api", "model-profiles"],
22538
22586
  summary: "Create a model profile",
22539
- description: "A profile runs on one harness. `model` must run on that harness and be in the model catalog unless `allowCustomModel` is true (a gateway id, a fresh launch); a `latest:` alias is accepted and resolves at claim. `effort` must be a level the harness and model support. `credentials` pins which pooled keys the profile uses: per credential var of the harness, the last 5 characters of each allowed key (`CODEX_OAUTH` is not supported). Operator only (the shared API key).",
22587
+ description: "A profile runs on one harness. `model` must run on that harness and be in the model catalog unless `allowCustomModel` is true (a gateway id, a fresh launch); a `latest:` alias is accepted and resolves at claim. `effort` must be a level the harness and model support. `credentials` pins which pooled keys the profile uses: per credential var of the harness, the last 5 characters of each allowed key (`CODEX_OAUTH` is not supported). `fallbacks` lists profiles on the same harness, in order, that a task on this profile hops to when a provider error (rate limit, seat, overload, auth, empty key pool) ends it; no repeats, no self, no cycle. Operator only (the shared API key).",
22540
22588
  tags: ["Models"],
22541
22589
  rbac: { permission: "models.profiles.write" },
22542
22590
  body: object2({
@@ -22546,7 +22594,8 @@ var createProfile = route({
22546
22594
  effort: ReasoningEffortSchema.nullable().optional(),
22547
22595
  allowCustomModel: boolean().optional().default(false),
22548
22596
  description: string2().trim().max(500).nullable().optional(),
22549
- credentials: ModelProfileCredentialsSchema.nullable().optional()
22597
+ credentials: ModelProfileCredentialsSchema.nullable().optional(),
22598
+ fallbacks: array2(ModelProfileNameSchema).max(MAX_MODEL_PROFILE_FALLBACKS).optional()
22550
22599
  }),
22551
22600
  responses: {
22552
22601
  201: { description: "Profile created", schema: ModelProfileSchema },
@@ -22560,7 +22609,7 @@ var updateProfile = route({
22560
22609
  path: "/api/model-profiles/{name}",
22561
22610
  pattern: ["api", "model-profiles", null],
22562
22611
  summary: "Update a model profile",
22563
- description: "Changes the model, effort, custom-model flag, description or credential allowlist; the name and harness are fixed. Omit a field to keep it; `effort: null` and `credentials: null` clear it. Applies to tasks claimed after the change. Operator only (the shared API key).",
22612
+ description: "Changes the model, effort, custom-model flag, description, credential allowlist or fallbacks; the name and harness are fixed. Omit a field to keep it; `effort: null` and `credentials: null` clear it, and `fallbacks: []` empties the list. Applies to tasks claimed after the change. Operator only (the shared API key).",
22564
22613
  tags: ["Models"],
22565
22614
  rbac: { permission: "models.profiles.write" },
22566
22615
  params: object2({ name: string2() }),
@@ -22569,7 +22618,8 @@ var updateProfile = route({
22569
22618
  effort: ReasoningEffortSchema.nullable().optional(),
22570
22619
  allowCustomModel: boolean().optional(),
22571
22620
  description: string2().trim().max(500).nullable().optional(),
22572
- credentials: ModelProfileCredentialsSchema.nullable().optional()
22621
+ credentials: ModelProfileCredentialsSchema.nullable().optional(),
22622
+ fallbacks: array2(ModelProfileNameSchema).max(MAX_MODEL_PROFILE_FALLBACKS).optional()
22573
22623
  }),
22574
22624
  responses: {
22575
22625
  200: { description: "Profile updated", schema: ModelProfileSchema },
@@ -22583,7 +22633,7 @@ var deleteProfile = route({
22583
22633
  path: "/api/model-profiles/{name}",
22584
22634
  pattern: ["api", "model-profiles", null],
22585
22635
  summary: "Delete a model profile",
22586
- description: "Refused (409) for a shipped `<harness>-<tier>` seed (edit it instead; it would come back at the next boot), and while an agent has the profile as its default, a schedule names it, or a task holds it (unfinished, or superseded and still owed its resume). Operator only (the shared API key).",
22636
+ description: "Refused (409) for a shipped `<harness>-<tier>` seed (edit it instead; it would come back at the next boot), and while an agent has the profile as its default, a schedule names it, another profile lists it as a fallback, or a task holds it (unfinished, or superseded and still owed its resume). Operator only (the shared API key).",
22587
22637
  tags: ["Models"],
22588
22638
  rbac: { permission: "models.profiles.write" },
22589
22639
  params: object2({ name: string2() }),
@@ -22676,9 +22726,18 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
22676
22726
  jsonError(res, error, 400);
22677
22727
  return true;
22678
22728
  }
22679
- const created = await createModelProfile(body, {
22680
- userId: await resolveHttpAuditUserId(req, myAgentId)
22729
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
22730
+ const outcome = await getDbClient2().transaction(async () => {
22731
+ const fallbackError = body.fallbacks ? await modelProfileFallbacksError(body.name, body.harness, body.fallbacks) : null;
22732
+ if (fallbackError)
22733
+ return { error: fallbackError };
22734
+ return { created: await createModelProfile(body, { userId }) };
22681
22735
  });
22736
+ if (typeof outcome.error === "string") {
22737
+ jsonError(res, outcome.error, 400);
22738
+ return true;
22739
+ }
22740
+ const created = outcome.created;
22682
22741
  if (!created) {
22683
22742
  jsonError(res, `Model profile "${body.name}" already exists`, 409);
22684
22743
  return true;
@@ -22709,9 +22768,18 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
22709
22768
  jsonError(res, error, 400);
22710
22769
  return true;
22711
22770
  }
22712
- const updated = await updateModelProfile(current.name, body, {
22713
- userId: await resolveHttpAuditUserId(req, myAgentId)
22771
+ const userId = await resolveHttpAuditUserId(req, myAgentId);
22772
+ const outcome = await getDbClient2().transaction(async () => {
22773
+ const fallbackError = body.fallbacks ? await modelProfileFallbacksError(current.name, current.harness, body.fallbacks) : null;
22774
+ if (fallbackError)
22775
+ return { error: fallbackError };
22776
+ return { updated: await updateModelProfile(current.name, body, { userId }) };
22714
22777
  });
22778
+ if (typeof outcome.error === "string") {
22779
+ jsonError(res, outcome.error, 400);
22780
+ return true;
22781
+ }
22782
+ const updated = outcome.updated;
22715
22783
  if (!updated) {
22716
22784
  jsonError(res, "Model profile not found", 404);
22717
22785
  return true;
@@ -22735,14 +22803,15 @@ async function handleModelProfiles(req, res, pathSegments, queryParams, myAgentI
22735
22803
  return true;
22736
22804
  }
22737
22805
  const refs = await modelProfileReferences(current.name);
22738
- if (refs.agentIds.length > 0 || refs.openTaskCount > 0 || refs.scheduleIds.length > 0) {
22806
+ if (refs.agentIds.length > 0 || refs.openTaskCount > 0 || refs.scheduleIds.length > 0 || refs.fallbackOf.length > 0) {
22739
22807
  const schedules = refs.scheduleIds.length > 0 ? ` (${refs.scheduleIds.join(", ")})` : "";
22740
- jsonError(res, `"${current.name}" is in use: default of ${refs.agentIds.length} agent(s), held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}.`, 409);
22808
+ const fallbackOf = refs.fallbackOf.length > 0 ? ` (${refs.fallbackOf.join(", ")})` : "";
22809
+ jsonError(res, `"${current.name}" is in use: default of ${refs.agentIds.length} agent(s), held by ${refs.openTaskCount} unfinished or awaiting-resume task(s), named by ${refs.scheduleIds.length} schedule(s)${schedules}, a fallback of ${refs.fallbackOf.length} profile(s)${fallbackOf}.`, 409);
22741
22810
  return true;
22742
22811
  }
22743
22812
  const outcome = await deleteModelProfile(current.name);
22744
22813
  if (outcome === "in-use") {
22745
- jsonError(res, `"${current.name}" is in use by a task, a schedule or an agent default created just now.`, 409);
22814
+ jsonError(res, `"${current.name}" is in use by a task, a schedule, an agent default or a fallback list written just now.`, 409);
22746
22815
  return true;
22747
22816
  }
22748
22817
  if (outcome === "missing") {
@@ -23078,14 +23147,15 @@ async function getJiraOAuthConfig() {
23078
23147
  const app = await getOAuthApp("jira");
23079
23148
  return app ? oauthAppRowToProviderConfig(app) : null;
23080
23149
  }
23081
- async function getJiraAuthorizationUrl(finalRedirect) {
23150
+ async function getJiraAuthorizationUrl(finalRedirect, userId) {
23082
23151
  const config = await getJiraOAuthConfig();
23083
23152
  if (!config)
23084
23153
  return null;
23085
23154
  const result = await buildAuthorizationUrl(config, {
23086
23155
  flow: "tracker",
23087
23156
  label: "default",
23088
- ...finalRedirect ? { finalRedirect } : {}
23157
+ ...finalRedirect ? { finalRedirect } : {},
23158
+ ...userId ? { userId } : {}
23089
23159
  });
23090
23160
  return result.url;
23091
23161
  }
@@ -23122,14 +23192,15 @@ async function getLinearOAuthConfig() {
23122
23192
  const app = await getOAuthApp("linear");
23123
23193
  return app ? oauthAppRowToProviderConfig(app) : null;
23124
23194
  }
23125
- async function getLinearAuthorizationUrl(finalRedirect) {
23195
+ async function getLinearAuthorizationUrl(finalRedirect, userId) {
23126
23196
  const config = await getLinearOAuthConfig();
23127
23197
  if (!config)
23128
23198
  return null;
23129
23199
  const result = await buildAuthorizationUrl(config, {
23130
23200
  flow: "tracker",
23131
23201
  label: "default",
23132
- ...finalRedirect ? { finalRedirect } : {}
23202
+ ...finalRedirect ? { finalRedirect } : {},
23203
+ ...userId ? { userId } : {}
23133
23204
  });
23134
23205
  return result.url;
23135
23206
  }
@@ -24982,10 +25053,11 @@ var FinishTaskConflictSchema = object2({
24982
25053
  });
24983
25054
  var SupersedeTaskResponseSchema = object2({
24984
25055
  success: literal2(true),
24985
- kind: _enum2(["alreadyFinished", "workflow-failed", "resumed"]),
25056
+ kind: _enum2(["alreadyFinished", "workflow-failed", "resumed", "noFallback"]),
24986
25057
  task: AgentTaskSchema.nullable(),
24987
25058
  resumeTaskId: string2().nullable(),
24988
- resumeTaskStatus: AgentTaskStatusSchema.optional()
25059
+ resumeTaskStatus: AgentTaskStatusSchema.optional(),
25060
+ failureReason: string2().nullable().optional()
24989
25061
  });
24990
25062
  var taskTotals = createListTotalCache(LIST_TOTAL_TTL_MS, 15000);
24991
25063
  var listTasks = route({
@@ -25428,10 +25500,13 @@ var supersedeTaskRoute = route({
25428
25500
  pattern: ["api", "tasks", null, "supersede"],
25429
25501
  session: { taskParam: "id" },
25430
25502
  summary: "Supersede an in-progress task (terminate + spawn resume follow-up)",
25431
- description: 'Marks the original task `superseded` (terminal) and creates a fresh `taskType="resume"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine\'s retry/failure policy applies.',
25503
+ description: 'Marks the original task `superseded` (terminal) and creates a fresh `taskType="resume"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine\'s retry/failure policy applies. With `reason: provider_fallback` (and its `errorClass`), the resume runs on the same agent with the next fallback profile that passes the profile check; when none is left, or the task is a workflow step, nothing changes and `kind: noFallback` tells the worker to fail the task itself, led by `failureReason` when set.',
25432
25504
  tags: ["Tasks"],
25433
25505
  params: object2({ id: string2() }),
25434
- body: object2({ reason: ResumeReasonSchema }),
25506
+ body: object2({ reason: ResumeReasonSchema, errorClass: ProviderErrorClassSchema.optional() }).refine((body) => body.reason === "provider_fallback" === (body.errorClass !== undefined), {
25507
+ message: "`errorClass` is required with `reason: provider_fallback` and only allowed with it",
25508
+ path: ["errorClass"]
25509
+ }),
25435
25510
  auth: { apiKey: true, agentId: true },
25436
25511
  responses: {
25437
25512
  200: {
@@ -26452,6 +26527,23 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
26452
26527
  jsonError(res, `Task status is '${task.status}', not 'in_progress'`, 400);
26453
26528
  return true;
26454
26529
  }
26530
+ let fallback;
26531
+ if (parsed.body.reason === "provider_fallback" && parsed.body.errorClass) {
26532
+ const pick = task.workflowRunStepId == null ? await nextFallback2(task, parsed.body.errorClass, {
26533
+ includeRepoSecrets: readsRepoSecrets(getRequestAuth(req), task.agentId ? await getAgentById2(task.agentId) : null)
26534
+ }) : { kind: "none", message: null };
26535
+ if (pick.kind === "none") {
26536
+ supersedeTaskRoute.respond(res, 200, {
26537
+ success: true,
26538
+ kind: "noFallback",
26539
+ task,
26540
+ resumeTaskId: null,
26541
+ failureReason: pick.message
26542
+ });
26543
+ return true;
26544
+ }
26545
+ fallback = { profile: pick.profile, hop: pick.hop };
26546
+ }
26455
26547
  if (task.workflowRunStepId != null) {
26456
26548
  const failed = await failTask2(parsed.params.id, SUPERSEDED_WORKFLOW_TASK_REASON);
26457
26549
  if (task.agentId) {
@@ -26495,7 +26587,8 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
26495
26587
  }
26496
26588
  const followUp = await createResumeFollowUp2({
26497
26589
  parentId: parsed.params.id,
26498
- reason: parsed.body.reason
26590
+ reason: parsed.body.reason,
26591
+ fallback
26499
26592
  });
26500
26593
  if (followUp.kind !== "created") {
26501
26594
  await settleSupersededTaskDependents2(parsed.params.id, null);
@@ -30247,7 +30340,8 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
30247
30340
  return cached;
30248
30341
  const result = await checkProfileForAgent(myAgentId, profile, {
30249
30342
  vcsRepo,
30250
- includeRepoSecrets
30343
+ includeRepoSecrets,
30344
+ fallbacks: false
30251
30345
  });
30252
30346
  const ok = result?.ok !== false;
30253
30347
  profileOk.set(memoKey, ok);
@@ -32287,6 +32381,1521 @@ async function handleRuntimePools(req, res, pathSegments, queryParams, agentId)
32287
32381
  return true;
32288
32382
  }
32289
32383
 
32384
+ // src/http/savings.ts
32385
+ init_zod();
32386
+ init_db4();
32387
+
32388
+ // src/be/savings/compute.ts
32389
+ init_db4();
32390
+
32391
+ // src/be/savings/model.ts
32392
+ init_zod();
32393
+ var SAVINGS_TIERS = ["smol", "regular", "smart", "ultra"];
32394
+ var CALIBRATION_MODEL = "claude-opus-5-5";
32395
+ var CALIBRATED_AT = "2026-11-05";
32396
+ var K = 0.2753;
32397
+ var T0 = 2;
32398
+ var TAU_MAX = 61;
32399
+ var CAP_PER_DAY = 24;
32400
+ var F_FOLLOWUP = 0.107;
32401
+ var JEV_PER_M = 0.042;
32402
+ var R = { p10: 1.011, p50: 1.02, p90: 1.03 };
32403
+ var ERR_JOB = { p10: 0.542, p50: 1, p90: 1.508 };
32404
+ var ERR_FLEET = { p10: 0.746, p50: 1, p90: 1.325 };
32405
+ var DEFAULT_OPS = 9;
32406
+ var MAX_SCRIPT_OPS = 100;
32407
+ var CURVE = {
32408
+ smol: {
32409
+ usd: [
32410
+ 0.0056,
32411
+ 0.0068,
32412
+ 0.0075,
32413
+ 0.0086,
32414
+ 0.0092,
32415
+ 0.0105,
32416
+ 0.012,
32417
+ 0.0146,
32418
+ 0.0163,
32419
+ 0.0171,
32420
+ 0.0184,
32421
+ 0.02,
32422
+ 0.0212,
32423
+ 0.0222,
32424
+ 0.0225,
32425
+ 0.0242,
32426
+ 0.0254,
32427
+ 0.0268,
32428
+ 0.028,
32429
+ 0.0291,
32430
+ 0.0306,
32431
+ 0.0319,
32432
+ 0.0333,
32433
+ 0.0353,
32434
+ 0.0359,
32435
+ 0.0374,
32436
+ 0.0389,
32437
+ 0.0413,
32438
+ 0.043,
32439
+ 0.0434,
32440
+ 0.045,
32441
+ 0.047,
32442
+ 0.0489,
32443
+ 0.0505,
32444
+ 0.051,
32445
+ 0.0535,
32446
+ 0.0554,
32447
+ 0.057,
32448
+ 0.0586,
32449
+ 0.0595,
32450
+ 0.0612,
32451
+ 0.0633,
32452
+ 0.065,
32453
+ 0.0679,
32454
+ 0.0683,
32455
+ 0.0702,
32456
+ 0.0717,
32457
+ 0.0742,
32458
+ 0.0757,
32459
+ 0.0764,
32460
+ 0.078,
32461
+ 0.0805,
32462
+ 0.0824,
32463
+ 0.0842,
32464
+ 0.085,
32465
+ 0.0881,
32466
+ 0.0901,
32467
+ 0.093,
32468
+ 0.0949,
32469
+ 0.0963,
32470
+ 0.0979
32471
+ ],
32472
+ hrs: [
32473
+ 0.00409,
32474
+ 0.00521,
32475
+ 0.00674,
32476
+ 0.00831,
32477
+ 0.00993,
32478
+ 0.0126,
32479
+ 0.01586,
32480
+ 0.01997,
32481
+ 0.02272,
32482
+ 0.02392,
32483
+ 0.02615,
32484
+ 0.03049,
32485
+ 0.034,
32486
+ 0.03708,
32487
+ 0.03835,
32488
+ 0.04398,
32489
+ 0.04779,
32490
+ 0.05207,
32491
+ 0.05544,
32492
+ 0.05811,
32493
+ 0.06247,
32494
+ 0.06595,
32495
+ 0.07002,
32496
+ 0.07589,
32497
+ 0.0778,
32498
+ 0.08234,
32499
+ 0.08704,
32500
+ 0.09357,
32501
+ 0.09884,
32502
+ 0.10091,
32503
+ 0.10694,
32504
+ 0.11393,
32505
+ 0.12002,
32506
+ 0.12476,
32507
+ 0.12736,
32508
+ 0.13666,
32509
+ 0.14271,
32510
+ 0.14854,
32511
+ 0.15322,
32512
+ 0.15738,
32513
+ 0.16341,
32514
+ 0.17023,
32515
+ 0.17766,
32516
+ 0.18815,
32517
+ 0.18983,
32518
+ 0.19846,
32519
+ 0.1996,
32520
+ 0.20217,
32521
+ 0.20833,
32522
+ 0.21012,
32523
+ 0.21538,
32524
+ 0.2224,
32525
+ 0.23067,
32526
+ 0.23488,
32527
+ 0.23825,
32528
+ 0.24844,
32529
+ 0.25554,
32530
+ 0.26838,
32531
+ 0.27469,
32532
+ 0.27725,
32533
+ 0.28259
32534
+ ]
32535
+ },
32536
+ regular: {
32537
+ usd: [
32538
+ 0.0878,
32539
+ 0.1074,
32540
+ 0.1211,
32541
+ 0.1383,
32542
+ 0.1497,
32543
+ 0.1699,
32544
+ 0.196,
32545
+ 0.2372,
32546
+ 0.2628,
32547
+ 0.2762,
32548
+ 0.2952,
32549
+ 0.3209,
32550
+ 0.3399,
32551
+ 0.3544,
32552
+ 0.3593,
32553
+ 0.3859,
32554
+ 0.4041,
32555
+ 0.425,
32556
+ 0.4435,
32557
+ 0.4586,
32558
+ 0.4817,
32559
+ 0.5001,
32560
+ 0.5215,
32561
+ 0.5501,
32562
+ 0.5582,
32563
+ 0.5795,
32564
+ 0.6027,
32565
+ 0.6364,
32566
+ 0.6621,
32567
+ 0.6678,
32568
+ 0.6917,
32569
+ 0.7189,
32570
+ 0.7459,
32571
+ 0.7683,
32572
+ 0.7758,
32573
+ 0.8096,
32574
+ 0.8361,
32575
+ 0.8588,
32576
+ 0.8806,
32577
+ 0.893,
32578
+ 0.9152,
32579
+ 0.9422,
32580
+ 0.9654,
32581
+ 1.0056,
32582
+ 1.0108,
32583
+ 1.0351,
32584
+ 1.0545,
32585
+ 1.0885,
32586
+ 1.108,
32587
+ 1.1184,
32588
+ 1.1389,
32589
+ 1.1716,
32590
+ 1.1969,
32591
+ 1.2205,
32592
+ 1.2309,
32593
+ 1.2733,
32594
+ 1.3003,
32595
+ 1.3399,
32596
+ 1.3639,
32597
+ 1.3838,
32598
+ 1.4053
32599
+ ],
32600
+ hrs: [
32601
+ 0.00341,
32602
+ 0.00435,
32603
+ 0.00562,
32604
+ 0.00693,
32605
+ 0.00828,
32606
+ 0.0105,
32607
+ 0.01322,
32608
+ 0.01665,
32609
+ 0.01894,
32610
+ 0.01994,
32611
+ 0.0218,
32612
+ 0.02541,
32613
+ 0.02834,
32614
+ 0.0309,
32615
+ 0.03197,
32616
+ 0.03665,
32617
+ 0.03983,
32618
+ 0.0434,
32619
+ 0.04621,
32620
+ 0.04844,
32621
+ 0.05207,
32622
+ 0.05497,
32623
+ 0.05836,
32624
+ 0.06326,
32625
+ 0.06485,
32626
+ 0.06863,
32627
+ 0.07255,
32628
+ 0.07799,
32629
+ 0.08239,
32630
+ 0.08411,
32631
+ 0.08914,
32632
+ 0.09496,
32633
+ 0.10004,
32634
+ 0.10399,
32635
+ 0.10616,
32636
+ 0.11391,
32637
+ 0.11896,
32638
+ 0.12382,
32639
+ 0.12771,
32640
+ 0.13118,
32641
+ 0.13621,
32642
+ 0.14189,
32643
+ 0.14808,
32644
+ 0.15683,
32645
+ 0.15823,
32646
+ 0.16542,
32647
+ 0.16638,
32648
+ 0.16852,
32649
+ 0.17365,
32650
+ 0.17514,
32651
+ 0.17952,
32652
+ 0.18537,
32653
+ 0.19227,
32654
+ 0.19578,
32655
+ 0.19858,
32656
+ 0.20708,
32657
+ 0.213,
32658
+ 0.22371,
32659
+ 0.22896,
32660
+ 0.23109,
32661
+ 0.23555
32662
+ ]
32663
+ },
32664
+ smart: {
32665
+ usd: [
32666
+ 0.1746,
32667
+ 0.2138,
32668
+ 0.2413,
32669
+ 0.2756,
32670
+ 0.2983,
32671
+ 0.3385,
32672
+ 0.3907,
32673
+ 0.4729,
32674
+ 0.5243,
32675
+ 0.551,
32676
+ 0.589,
32677
+ 0.6402,
32678
+ 0.6783,
32679
+ 0.7075,
32680
+ 0.7173,
32681
+ 0.7705,
32682
+ 0.8068,
32683
+ 0.8487,
32684
+ 0.8857,
32685
+ 0.9158,
32686
+ 0.9621,
32687
+ 0.9989,
32688
+ 1.0416,
32689
+ 1.0987,
32690
+ 1.1149,
32691
+ 1.1576,
32692
+ 1.2041,
32693
+ 1.2714,
32694
+ 1.3225,
32695
+ 1.3339,
32696
+ 1.3815,
32697
+ 1.4359,
32698
+ 1.49,
32699
+ 1.5347,
32700
+ 1.5496,
32701
+ 1.617,
32702
+ 1.67,
32703
+ 1.7153,
32704
+ 1.7596,
32705
+ 1.7844,
32706
+ 1.8288,
32707
+ 1.8828,
32708
+ 1.9291,
32709
+ 2.0095,
32710
+ 2.0198,
32711
+ 2.0683,
32712
+ 2.1069,
32713
+ 2.1748,
32714
+ 2.2137,
32715
+ 2.2345,
32716
+ 2.2752,
32717
+ 2.3413,
32718
+ 2.3918,
32719
+ 2.4388,
32720
+ 2.4595,
32721
+ 2.5444,
32722
+ 2.5985,
32723
+ 2.678,
32724
+ 2.7259,
32725
+ 2.7657,
32726
+ 2.8086
32727
+ ],
32728
+ hrs: [
32729
+ 0.00265,
32730
+ 0.00338,
32731
+ 0.00437,
32732
+ 0.00539,
32733
+ 0.00644,
32734
+ 0.00817,
32735
+ 0.01029,
32736
+ 0.01296,
32737
+ 0.01474,
32738
+ 0.01552,
32739
+ 0.01696,
32740
+ 0.01978,
32741
+ 0.02205,
32742
+ 0.02405,
32743
+ 0.02488,
32744
+ 0.02852,
32745
+ 0.031,
32746
+ 0.03377,
32747
+ 0.03596,
32748
+ 0.03769,
32749
+ 0.04052,
32750
+ 0.04278,
32751
+ 0.04541,
32752
+ 0.04923,
32753
+ 0.05046,
32754
+ 0.05341,
32755
+ 0.05645,
32756
+ 0.06069,
32757
+ 0.06411,
32758
+ 0.06545,
32759
+ 0.06937,
32760
+ 0.0739,
32761
+ 0.07785,
32762
+ 0.08092,
32763
+ 0.08261,
32764
+ 0.08865,
32765
+ 0.09257,
32766
+ 0.09635,
32767
+ 0.09939,
32768
+ 0.10209,
32769
+ 0.106,
32770
+ 0.11041,
32771
+ 0.11524,
32772
+ 0.12204,
32773
+ 0.12313,
32774
+ 0.12873,
32775
+ 0.12947,
32776
+ 0.13114,
32777
+ 0.13513,
32778
+ 0.13629,
32779
+ 0.1397,
32780
+ 0.14425,
32781
+ 0.14962,
32782
+ 0.15235,
32783
+ 0.15453,
32784
+ 0.16114,
32785
+ 0.16575,
32786
+ 0.17408,
32787
+ 0.17817,
32788
+ 0.17983,
32789
+ 0.1833
32790
+ ]
32791
+ },
32792
+ ultra: {
32793
+ usd: [
32794
+ 0.4215,
32795
+ 0.5126,
32796
+ 0.5737,
32797
+ 0.6515,
32798
+ 0.702,
32799
+ 0.7922,
32800
+ 0.9108,
32801
+ 1.0969,
32802
+ 1.2137,
32803
+ 1.2729,
32804
+ 1.3559,
32805
+ 1.4659,
32806
+ 1.5471,
32807
+ 1.6075,
32808
+ 1.6273,
32809
+ 1.7385,
32810
+ 1.8143,
32811
+ 1.9006,
32812
+ 1.9774,
32813
+ 2.0389,
32814
+ 2.1345,
32815
+ 2.211,
32816
+ 2.2993,
32817
+ 2.4146,
32818
+ 2.4463,
32819
+ 2.5326,
32820
+ 2.6278,
32821
+ 2.7635,
32822
+ 2.8673,
32823
+ 2.8901,
32824
+ 2.9876,
32825
+ 3.0983,
32826
+ 3.2073,
32827
+ 3.2964,
32828
+ 3.3254,
32829
+ 3.4593,
32830
+ 3.5632,
32831
+ 3.6518,
32832
+ 3.7384,
32833
+ 3.784,
32834
+ 3.8661,
32835
+ 3.9685,
32836
+ 4.0556,
32837
+ 4.2104,
32838
+ 4.229,
32839
+ 4.3174,
32840
+ 4.3912,
32841
+ 4.5199,
32842
+ 4.5949,
32843
+ 4.6375,
32844
+ 4.7124,
32845
+ 4.8381,
32846
+ 4.931,
32847
+ 5.017,
32848
+ 5.0554,
32849
+ 5.2133,
32850
+ 5.3132,
32851
+ 5.4655,
32852
+ 5.5501,
32853
+ 5.6254,
32854
+ 5.7067
32855
+ ],
32856
+ hrs: [
32857
+ 0.00265,
32858
+ 0.00338,
32859
+ 0.00437,
32860
+ 0.00539,
32861
+ 0.00644,
32862
+ 0.00817,
32863
+ 0.01029,
32864
+ 0.01296,
32865
+ 0.01474,
32866
+ 0.01552,
32867
+ 0.01696,
32868
+ 0.01978,
32869
+ 0.02205,
32870
+ 0.02405,
32871
+ 0.02488,
32872
+ 0.02852,
32873
+ 0.031,
32874
+ 0.03377,
32875
+ 0.03596,
32876
+ 0.03769,
32877
+ 0.04052,
32878
+ 0.04278,
32879
+ 0.04541,
32880
+ 0.04923,
32881
+ 0.05046,
32882
+ 0.05341,
32883
+ 0.05645,
32884
+ 0.06069,
32885
+ 0.06411,
32886
+ 0.06545,
32887
+ 0.06937,
32888
+ 0.0739,
32889
+ 0.07785,
32890
+ 0.08092,
32891
+ 0.08261,
32892
+ 0.08865,
32893
+ 0.09257,
32894
+ 0.09635,
32895
+ 0.09939,
32896
+ 0.10209,
32897
+ 0.106,
32898
+ 0.11041,
32899
+ 0.11524,
32900
+ 0.12204,
32901
+ 0.12313,
32902
+ 0.12873,
32903
+ 0.12947,
32904
+ 0.13114,
32905
+ 0.13513,
32906
+ 0.13629,
32907
+ 0.1397,
32908
+ 0.14425,
32909
+ 0.14962,
32910
+ 0.15235,
32911
+ 0.15453,
32912
+ 0.16114,
32913
+ 0.16575,
32914
+ 0.17408,
32915
+ 0.17817,
32916
+ 0.17983,
32917
+ 0.1833
32918
+ ]
32919
+ }
32920
+ };
32921
+ var SHIPPED_CALIBRATION = {
32922
+ source: "shipped",
32923
+ calibratedAt: CALIBRATED_AT,
32924
+ model: CALIBRATION_MODEL,
32925
+ curve: CURVE
32926
+ };
32927
+ var SAVINGS_CALIBRATION_KEY = "SAVINGS_CURVE_CALIBRATION";
32928
+ var CurveArraySchema = array2(number2().positive()).length(TAU_MAX);
32929
+ var TierCurveSchema = object2({ usd: CurveArraySchema, hrs: CurveArraySchema });
32930
+ var StoredCalibrationSchema = object2({
32931
+ calibratedAt: string2().regex(/^\d{4}-\d{2}-\d{2}$/),
32932
+ model: string2().min(1),
32933
+ window: object2({ start: string2(), end: string2(), sessions: number2().int().nonnegative() }).optional(),
32934
+ curve: object2({
32935
+ smol: TierCurveSchema,
32936
+ regular: TierCurveSchema,
32937
+ smart: TierCurveSchema,
32938
+ ultra: TierCurveSchema
32939
+ })
32940
+ });
32941
+ function parseCalibration(raw) {
32942
+ if (!raw)
32943
+ return null;
32944
+ try {
32945
+ const parsed = StoredCalibrationSchema.safeParse(JSON.parse(raw));
32946
+ if (!parsed.success)
32947
+ return null;
32948
+ const { calibratedAt, model, curve, window } = parsed.data;
32949
+ return { source: "deployment", calibratedAt, model, curve, ...window ? { window } : {} };
32950
+ } catch {
32951
+ return null;
32952
+ }
32953
+ }
32954
+ function curve(tau, tier, key, set = CURVE) {
32955
+ const t = Math.max(1, Math.min(TAU_MAX, tau));
32956
+ const a = set[tier][key];
32957
+ const lo = Math.floor(t);
32958
+ const hi = Math.ceil(t);
32959
+ const vLo = a[lo - 1];
32960
+ const vHi = a[hi - 1];
32961
+ return vLo + (vHi - vLo) * (t - lo);
32962
+ }
32963
+ function scriptOpsFromAwaitCount(awaits) {
32964
+ return Math.min(MAX_SCRIPT_OPS, Number(awaits) || 0);
32965
+ }
32966
+ function nodeOpsOf(definition, opsByScript) {
32967
+ const ops = new Map;
32968
+ for (const node of definition?.nodes ?? []) {
32969
+ let o = 0;
32970
+ if (node.type === "swarm-script") {
32971
+ const name = node.config?.scriptName;
32972
+ o = (typeof name === "string" ? opsByScript.get(name) : undefined) ?? DEFAULT_OPS;
32973
+ } else if (node.type === "script") {
32974
+ o = Math.max(1, (JSON.stringify(node.config ?? {}).match(/\bawait\b/g) ?? []).length);
32975
+ } else if (["system-one-decision", "system-one-extraction", "raw-llm", "notify", "code-match"].includes(node.type)) {
32976
+ o = 1;
32977
+ }
32978
+ ops.set(node.id, o);
32979
+ }
32980
+ return ops;
32981
+ }
32982
+ function spendOf(facts, useRecorded) {
32983
+ return {
32984
+ measuredUsd: facts.agentUsd + facts.followupUsd + (useRecorded ? facts.recordedLlmUsd : 0),
32985
+ estimatedLlmUsd: useRecorded ? 0 : facts.estimatedLlmUsd
32986
+ };
32987
+ }
32988
+ var bandOf = (fn) => ({
32989
+ p10: fn("p10"),
32990
+ p50: fn("p50"),
32991
+ p90: fn("p90")
32992
+ });
32993
+ function priceWorkflow(facts, opts) {
32994
+ const cap = CAP_PER_DAY * opts.days;
32995
+ const runs = facts.runs;
32996
+ const vCap = Math.min(facts.schedRuns, cap);
32997
+ const vSched = Math.max(vCap, facts.schedEffectRuns);
32998
+ const substituted = vSched + (facts.countedRuns - facts.schedRuns);
32999
+ const opsPerRun = runs > 0 ? facts.opsSum / runs : 0;
33000
+ const tau = Math.min(TAU_MAX, T0 + K * opsPerRun);
33001
+ const orchestrates = !(opsPerRun < 1 && facts.agentTasks > 0);
33002
+ const unitUsd = orchestrates ? curve(tau, opts.tier, "usd", opts.curve) : 0;
33003
+ const unitHrs = orchestrates ? curve(tau, opts.tier, "hrs", opts.curve) : 0;
33004
+ const review = unitUsd > 0 ? F_FOLLOWUP : 0;
33005
+ const share = runs > 0 ? substituted / runs : 0;
33006
+ const { measuredUsd, estimatedLlmUsd } = spendOf(facts, facts.recordedLlmUsd > 0);
33007
+ const keptUsd = (facts.agentUsd + facts.followupUsd) * share;
33008
+ const keptHours = facts.agentMs / 3600000 * share;
33009
+ const actualUsd = (measuredUsd + estimatedLlmUsd) * share;
33010
+ const actualHours = (facts.agentMs / 3600000 + facts.computeSecs / 3600) * share;
33011
+ const err = opts.band === "job" ? ERR_JOB : ERR_FLEET;
33012
+ const agentOnlyUsd = bandOf((q) => keptUsd + substituted * (R[q] * unitUsd * err[q] + review));
33013
+ const agentOnlyHours = bandOf((q) => keptHours + substituted * R[q] * unitHrs * err[q]);
33014
+ return {
33015
+ runs,
33016
+ substitutedRuns: substituted,
33017
+ effectRuns: vSched - vCap,
33018
+ enabledOnlyRuns: runs - substituted,
33019
+ capApplied: facts.schedRuns > cap,
33020
+ opsPerRun,
33021
+ measuredUsd,
33022
+ estimatedLlmUsd,
33023
+ actualUsd,
33024
+ agentOnlyUsd,
33025
+ savingUsd: bandOf((q) => agentOnlyUsd[q] - actualUsd),
33026
+ actualHours,
33027
+ agentOnlyHours,
33028
+ hoursSaved: bandOf((q) => agentOnlyHours[q] - actualHours),
33029
+ agentOnlyUsdPerRun: R.p50 * unitUsd + review
33030
+ };
33031
+ }
33032
+ function splitByDay(facts, byDay, opts) {
33033
+ const priced = priceWorkflow(facts, { ...opts, band: "job" });
33034
+ const runs = facts.runs;
33035
+ const share = runs > 0 ? priced.substitutedRuns / runs : 0;
33036
+ const nonSched = facts.countedRuns - facts.schedRuns;
33037
+ const vSched = priced.substitutedRuns - nonSched;
33038
+ const unitUsd = priced.agentOnlyUsdPerRun;
33039
+ const useRecorded = facts.recordedLlmUsd > 0;
33040
+ return byDay.map((d) => {
33041
+ const substituted = (facts.schedRuns > 0 ? vSched * d.schedRuns / facts.schedRuns : 0) + (d.countedRuns - d.schedRuns);
33042
+ const { measuredUsd, estimatedLlmUsd } = spendOf(d, useRecorded);
33043
+ const keptUsd = (d.agentUsd + d.followupUsd) * share;
33044
+ const actualUsd = (measuredUsd + estimatedLlmUsd) * share;
33045
+ return {
33046
+ day: d.day,
33047
+ savingUsd: keptUsd + substituted * unitUsd - actualUsd,
33048
+ actualUsd,
33049
+ measuredUsd,
33050
+ estimatedLlmUsd
33051
+ };
33052
+ });
33053
+ }
33054
+
33055
+ // src/be/savings/compute.ts
33056
+ var defaultSql = (sql, params) => getDbClient2().query(sql, params);
33057
+ var LIVE_MAX_RUNS = 1e4;
33058
+ var EFFECT_SQL = "(EXISTS(SELECT 1 FROM agent_tasks k WHERE k.workflowRunId=r.id) OR EXISTS(SELECT 1 FROM workflow_run_steps s2 JOIN workflow_runs c ON c.parentStepId=s2.id WHERE s2.runId=r.id))";
33059
+ var AWAITS_SQL = "(length(source)-length(replace(source,'await','')))/5";
33060
+ var num = (v) => Number(v) || 0;
33061
+ var emptyFacts = (runs) => ({
33062
+ runs,
33063
+ countedRuns: 0,
33064
+ schedRuns: 0,
33065
+ schedEffectRuns: 0,
33066
+ opsSum: 0,
33067
+ agentTasks: 0,
33068
+ agentUsd: 0,
33069
+ agentMs: 0,
33070
+ followupUsd: 0,
33071
+ recordedLlmUsd: 0,
33072
+ estimatedLlmUsd: 0,
33073
+ computeSecs: 0
33074
+ });
33075
+ async function scriptOps(names, sql) {
33076
+ const ops = new Map;
33077
+ const unique = [...new Set(names.filter(Boolean))];
33078
+ if (unique.length === 0)
33079
+ return ops;
33080
+ const rows = await sql(`SELECT name, ${AWAITS_SQL} aw FROM scripts WHERE isScratch=0 AND name IN (${unique.map(() => "?").join(",")}) ORDER BY scope='global'`, unique);
33081
+ for (const row of rows)
33082
+ ops.set(row.name, scriptOpsFromAwaitCount(row.aw));
33083
+ return ops;
33084
+ }
33085
+ var DAY_SQL = "substr(r.startedAt,1,10)";
33086
+ async function computeWorkflowWindow(workflow, window, sql = defaultSql) {
33087
+ const span = [workflow.id, window.start, window.end];
33088
+ const total = num((await sql("SELECT count(*) n FROM workflow_runs WHERE workflowId=? AND startedAt>=? AND startedAt<?", span))[0]?.n);
33089
+ if (total === 0)
33090
+ return { status: "ok", facts: emptyFacts(0), byDay: [] };
33091
+ if (total > LIVE_MAX_RUNS)
33092
+ return { status: "too-many-runs", runs: total };
33093
+ const days = new Map;
33094
+ const dayOf = (d) => {
33095
+ const key = String(d);
33096
+ let f = days.get(key);
33097
+ if (!f) {
33098
+ f = { day: key, ...emptyFacts(0) };
33099
+ days.set(key, f);
33100
+ }
33101
+ return f;
33102
+ };
33103
+ const byTrigger = await sql(`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`, span);
33104
+ let schedRuns = 0;
33105
+ for (const row of byTrigger) {
33106
+ const f = dayOf(row.d);
33107
+ const n = num(row.n);
33108
+ f.runs += n;
33109
+ if (row.st === "skipped" || row.st === "cancelled")
33110
+ continue;
33111
+ f.countedRuns += n;
33112
+ if (row.tt === "schedule") {
33113
+ f.schedRuns += n;
33114
+ schedRuns += n;
33115
+ }
33116
+ }
33117
+ if (schedRuns > 0) {
33118
+ const effect = await sql(`SELECT ${DAY_SQL} d, count(*) n FROM workflow_runs r WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? AND r.triggerType='schedule' AND r.status NOT IN ('skipped','cancelled') AND ${EFFECT_SQL} GROUP BY 1`, span);
33119
+ for (const row of effect)
33120
+ dayOf(row.d).schedEffectRuns += num(row.n);
33121
+ }
33122
+ const definition = workflow.definition ?? {};
33123
+ const scriptNames = (definition.nodes ?? []).filter((n) => n.type === "swarm-script").map((n) => n.config?.scriptName).filter((n) => typeof n === "string");
33124
+ const nodeOps = nodeOpsOf(definition, await scriptOps(scriptNames, sql));
33125
+ const steps = await sql(`SELECT ${DAY_SQL} d, s.nodeId nid, count(*) n, sum(CASE WHEN s.nodeType NOT IN ('agent-task','wait','human-in-the-loop','foreach','sub-workflow') THEN (julianday(coalesce(s.finishedAt,s.startedAt))-julianday(s.startedAt))*86400 ELSE 0 END) secs,
33126
+ sum(CASE WHEN s.nodeType LIKE 'system-one%' THEN json_extract(s.output,'$.usage.input_tokens') END) itok,
33127
+ sum(CASE WHEN s.nodeType='raw-llm' THEN length(json_extract(s.output,'$.result')) END) rchars,
33128
+ sum(CASE WHEN s.nodeId='report' THEN json_extract(s.output,'$.result.summary.jevCostUsd') END) jev,
33129
+ sum(CASE WHEN s.nodeId='report' THEN json_extract(s.output,'$.result.cost.clairicUsd') END) clairic
33130
+ FROM workflow_runs r JOIN workflow_run_steps s ON s.runId=r.id WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1,2`, span);
33131
+ for (const x of steps) {
33132
+ const f = dayOf(x.d);
33133
+ f.opsSum += (nodeOps.get(String(x.nid).split("#")[0] ?? "") ?? 0) * num(x.n);
33134
+ f.recordedLlmUsd += num(x.jev) + num(x.clairic);
33135
+ f.estimatedLlmUsd += num(x.itok) / 1e6 * JEV_PER_M + num(x.rchars) * (1.2 / 4 + 0.3) / 1e6;
33136
+ f.computeSecs += num(x.secs);
33137
+ }
33138
+ const agent = await sql(`SELECT ${DAY_SQL} d, count(DISTINCT t.id) tasks, sum(c.u) usd, sum(c.ms) ms
33139
+ 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
33140
+ WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1`, span);
33141
+ for (const row of agent) {
33142
+ const f = dayOf(row.d);
33143
+ f.agentTasks += num(row.tasks);
33144
+ f.agentUsd += num(row.usd);
33145
+ f.agentMs += num(row.ms);
33146
+ }
33147
+ const followups = await sql(`SELECT ${DAY_SQL} d, sum(c2.totalCostUsd) fup FROM workflow_runs r JOIN agent_tasks t2 ON t2.workflowRunId=r.id JOIN agent_tasks k ON k.parentTaskId=t2.id AND (k.task LIKE 'Worker task completed%' OR k.task LIKE 'Worker task failed%') JOIN session_costs c2 ON c2.taskId=k.id WHERE r.workflowId=? AND r.startedAt>=? AND r.startedAt<? GROUP BY 1`, span);
33148
+ for (const row of followups)
33149
+ dayOf(row.d).followupUsd += num(row.fup);
33150
+ const byDay = [...days.values()].sort((a, b) => a.day.localeCompare(b.day));
33151
+ const facts = emptyFacts(0);
33152
+ for (const f of byDay) {
33153
+ for (const k of Object.keys(facts))
33154
+ facts[k] += f[k];
33155
+ }
33156
+ return { status: "ok", facts, byDay };
33157
+ }
33158
+
33159
+ // src/http/savings.ts
33160
+ init_db_query();
33161
+ init_db_query_shared();
33162
+ init_route_def();
33163
+ init_utils2();
33164
+ var FACTS_TTL_MS = 10 * 60 * 1000;
33165
+ var boundedSql = async (sql, params) => {
33166
+ const result = await executeReadOnlyQueryGated(sql, params, getDbQueryHttpBudgetMs(), 1e4);
33167
+ return result.rows.map((row) => Object.fromEntries(result.columns.map((column, i) => [column, row[i]])));
33168
+ };
33169
+ var SavingsBandSchema = object2({ p10: number2(), p50: number2(), p90: number2() });
33170
+ var SavingsJobRowSchema = object2({
33171
+ kind: literal2("workflow"),
33172
+ workflowId: string2(),
33173
+ name: string2(),
33174
+ basis: literal2("modelled"),
33175
+ runs: number2().int(),
33176
+ substitutedRuns: number2().int(),
33177
+ effectRuns: number2().int(),
33178
+ enabledOnlyRuns: number2().int(),
33179
+ capApplied: boolean(),
33180
+ opsPerRun: number2(),
33181
+ measuredUsd: number2().describe("Measured spend of every run in the window: agent tasks, their reviews, recorded LLM cost."),
33182
+ estimatedLlmUsd: number2().describe("LLM spend estimated from tokens and output size, not measured. 0 when the runs recorded their LLM cost."),
33183
+ actualUsd: number2().describe("Scaled estimate, not a measurement: `measuredUsd + estimatedLlmUsd` times `substitutedRuns / runs`. The saving subtracts this."),
33184
+ agentOnlyUsd: SavingsBandSchema,
33185
+ savingUsd: SavingsBandSchema,
33186
+ actualHours: number2().describe("Scaled estimate: measured hours times `substitutedRuns / runs`."),
33187
+ agentOnlyHours: SavingsBandSchema,
33188
+ hoursSaved: SavingsBandSchema,
33189
+ agentOnlyUsdPerRun: number2()
33190
+ });
33191
+ var SavingsJobsResponseSchema = object2({
33192
+ window: object2({ start: string2(), end: string2(), days: number2().int() }),
33193
+ tier: _enum2(SAVINGS_TIERS),
33194
+ calibrationModel: string2(),
33195
+ calibratedAt: string2(),
33196
+ calibrationSource: _enum2(["shipped", "deployment"]),
33197
+ computedAt: string2(),
33198
+ valid: boolean(),
33199
+ reason: _enum2(["no-runs", "too-many-runs"]).nullable(),
33200
+ rows: array2(SavingsJobRowSchema)
33201
+ });
33202
+ var savingsJobsRoute = route({
33203
+ method: "get",
33204
+ path: "/api/savings/jobs",
33205
+ pattern: ["api", "savings", "jobs"],
33206
+ summary: "Estimated automation savings for a workflow",
33207
+ description: "What the workflow's runs in the window would have cost as agent tasks, minus what they cost. `measuredUsd` is the measured spend and `estimatedLlmUsd` the LLM spend estimated where none was recorded; `actualUsd` is their sum scaled to the substituted share of runs, the estimate the saving subtracts. Modelled at the chosen tier, with an 80% range (p10 to p90). `valid` is false when the workflow had no runs, or more runs than the live computation handles.",
33208
+ tags: ["Savings"],
33209
+ query: object2({
33210
+ workflowId: string2().min(1),
33211
+ days: _enum2(["7", "30", "90"]).default("30").transform(Number),
33212
+ tier: _enum2(SAVINGS_TIERS).default("smart")
33213
+ }),
33214
+ responses: {
33215
+ 200: { description: "Savings rows for the workflow", schema: SavingsJobsResponseSchema },
33216
+ 400: { description: "Missing workflowId, or an unknown days or tier value" },
33217
+ 404: { description: "Workflow not found" },
33218
+ 408: { description: "A savings query ran past its time budget" },
33219
+ 429: { description: "Too many concurrent database queries; retry shortly" }
33220
+ }
33221
+ });
33222
+ var SavingsDailyResponseSchema = object2({
33223
+ window: object2({ start: string2(), end: string2(), days: number2().int() }),
33224
+ tier: _enum2(SAVINGS_TIERS),
33225
+ calibrationModel: string2(),
33226
+ calibratedAt: string2(),
33227
+ calibrationSource: _enum2(["shipped", "deployment"]),
33228
+ computedAt: string2(),
33229
+ valid: boolean(),
33230
+ reason: _enum2(["no-runs", "too-many-runs"]).nullable(),
33231
+ points: array2(object2({
33232
+ day: string2(),
33233
+ savingUsd: number2(),
33234
+ actualUsd: number2().describe("Scaled estimate: the day's measured and estimated spend times the window's substituted share."),
33235
+ measuredUsd: number2().describe("The day's measured spend, not scaled."),
33236
+ estimatedLlmUsd: number2().describe("The day's LLM spend estimated from tokens and output size, not measured.")
33237
+ }))
33238
+ });
33239
+ var savingsDailyRoute = route({
33240
+ method: "get",
33241
+ path: "/api/savings/daily",
33242
+ pattern: ["api", "savings", "daily"],
33243
+ summary: "Daily automation savings for a workflow",
33244
+ description: "The workflow's p50 saving, measured spend and scaled actual cost per UTC day of the window, from the same computation as `/api/savings/jobs`, so the points sum to its p50 saving, `measuredUsd`, `estimatedLlmUsd` and `actualUsd`. When the hourly cap applies, the counted schedule runs are spread pro rata over the days. `valid` is false when the workflow had no runs, or more runs than the live computation handles.",
33245
+ tags: ["Savings"],
33246
+ query: object2({
33247
+ workflowId: string2().min(1),
33248
+ days: _enum2(["7", "30", "90"]).default("30").transform(Number),
33249
+ tier: _enum2(SAVINGS_TIERS).default("smart")
33250
+ }),
33251
+ responses: {
33252
+ 200: {
33253
+ description: "Daily savings points for the workflow",
33254
+ schema: SavingsDailyResponseSchema
33255
+ },
33256
+ 400: { description: "Missing workflowId, or an unknown days or tier value" },
33257
+ 404: { description: "Workflow not found" },
33258
+ 408: { description: "A savings query ran past its time budget" },
33259
+ 429: { description: "Too many concurrent database queries; retry shortly" }
33260
+ }
33261
+ });
33262
+ var factsCache = new Map;
33263
+ var CALIBRATION_TTL_MS = 60 * 1000;
33264
+ var calibrationCache = null;
33265
+ async function activeCalibration(now) {
33266
+ if (calibrationCache && now - calibrationCache.at < CALIBRATION_TTL_MS) {
33267
+ return calibrationCache.value;
33268
+ }
33269
+ const [row] = await getSwarmConfigs2({ scope: "global", key: SAVINGS_CALIBRATION_KEY });
33270
+ const value = parseCalibration(row?.value) ?? SHIPPED_CALIBRATION;
33271
+ calibrationCache = { at: now, value };
33272
+ return value;
33273
+ }
33274
+ function clearCalibrationCache() {
33275
+ calibrationCache = null;
33276
+ }
33277
+ function cachedWindow(workflow, days, now) {
33278
+ const key = `${workflow.id}:${days}`;
33279
+ const hit = factsCache.get(key);
33280
+ if (hit && now - hit.at < FACTS_TTL_MS)
33281
+ return hit;
33282
+ const end = new Date(now).toISOString();
33283
+ const start = new Date(now - days * 86400000).toISOString();
33284
+ const entry = {
33285
+ at: now,
33286
+ start,
33287
+ end,
33288
+ result: computeWorkflowWindow(workflow, { start, end }, boundedSql)
33289
+ };
33290
+ entry.result.catch(() => factsCache.delete(key));
33291
+ factsCache.set(key, entry);
33292
+ return entry;
33293
+ }
33294
+ var round2 = (x) => Math.round(x * 100) / 100;
33295
+ var roundBand = (b) => ({
33296
+ p10: round2(b.p10),
33297
+ p50: round2(b.p50),
33298
+ p90: round2(b.p90)
33299
+ });
33300
+ function roundToTotal(values) {
33301
+ const cents = values.map((v) => v * 100);
33302
+ const floors = cents.map(Math.floor);
33303
+ let left = Math.round(cents.reduce((s, c) => s + c, 0)) - floors.reduce((s, c) => s + c, 0);
33304
+ const order = cents.map((c, i) => ({ i, r: c - floors[i] })).sort((a, b) => b.r - a.r);
33305
+ for (const { i } of order) {
33306
+ if (left <= 0)
33307
+ break;
33308
+ floors[i] = floors[i] + 1;
33309
+ left--;
33310
+ }
33311
+ return floors.map((c) => c / 100);
33312
+ }
33313
+ function utcDays(start, end) {
33314
+ const out = [];
33315
+ for (let t = Date.parse(start.slice(0, 10));t <= Date.parse(end); t += 86400000) {
33316
+ out.push(new Date(t).toISOString().slice(0, 10));
33317
+ }
33318
+ return out;
33319
+ }
33320
+ async function handleSavings(req, res, pathSegments, queryParams) {
33321
+ const isJobs = savingsJobsRoute.match(req.method, pathSegments);
33322
+ if (!isJobs && !savingsDailyRoute.match(req.method, pathSegments))
33323
+ return false;
33324
+ const parsed = isJobs ? await savingsJobsRoute.parse(req, res, pathSegments, queryParams) : await savingsDailyRoute.parse(req, res, pathSegments, queryParams);
33325
+ if (!parsed)
33326
+ return true;
33327
+ const { workflowId, days, tier } = parsed.query;
33328
+ const workflow = await getWorkflow2(workflowId);
33329
+ if (!workflow) {
33330
+ res.writeHead(404, { "Content-Type": "application/json" });
33331
+ res.end(JSON.stringify({ error: "Workflow not found" }));
33332
+ return true;
33333
+ }
33334
+ const entry = cachedWindow(workflow, days, Date.now());
33335
+ let result;
33336
+ try {
33337
+ result = await entry.result;
33338
+ } catch (err) {
33339
+ if (err instanceof DbQueryConcurrencyCapError) {
33340
+ res.setHeader("Retry-After", "1");
33341
+ json(res, { error: "db_query_concurrency_cap", message: err.message }, 429);
33342
+ return true;
33343
+ }
33344
+ if (err instanceof DbQueryTimeoutError) {
33345
+ json(res, { error: "db_query_timeout", message: err.message }, 408);
33346
+ return true;
33347
+ }
33348
+ throw err;
33349
+ }
33350
+ const calibration = await activeCalibration(Date.now());
33351
+ const base = {
33352
+ window: { start: entry.start, end: entry.end, days },
33353
+ tier,
33354
+ calibrationModel: calibration.model,
33355
+ calibratedAt: calibration.calibratedAt,
33356
+ calibrationSource: calibration.source,
33357
+ computedAt: new Date(entry.at).toISOString()
33358
+ };
33359
+ if (result.status === "too-many-runs" || result.facts.runs === 0) {
33360
+ const reason = result.status === "too-many-runs" ? "too-many-runs" : "no-runs";
33361
+ if (isJobs)
33362
+ savingsJobsRoute.respond(res, 200, { ...base, valid: false, reason, rows: [] });
33363
+ else
33364
+ savingsDailyRoute.respond(res, 200, { ...base, valid: false, reason, points: [] });
33365
+ return true;
33366
+ }
33367
+ if (!isJobs) {
33368
+ const split = new Map(splitByDay(result.facts, result.byDay, { tier, days, curve: calibration.curve }).map((p) => [
33369
+ p.day,
33370
+ p
33371
+ ]));
33372
+ const dayList = utcDays(entry.start, entry.end);
33373
+ const saving = roundToTotal(dayList.map((d) => split.get(d)?.savingUsd ?? 0));
33374
+ const actual = roundToTotal(dayList.map((d) => split.get(d)?.actualUsd ?? 0));
33375
+ const measured = roundToTotal(dayList.map((d) => split.get(d)?.measuredUsd ?? 0));
33376
+ const estimated = roundToTotal(dayList.map((d) => split.get(d)?.estimatedLlmUsd ?? 0));
33377
+ savingsDailyRoute.respond(res, 200, {
33378
+ ...base,
33379
+ valid: true,
33380
+ reason: null,
33381
+ points: dayList.map((day, i) => ({
33382
+ day,
33383
+ savingUsd: saving[i],
33384
+ actualUsd: actual[i],
33385
+ measuredUsd: measured[i],
33386
+ estimatedLlmUsd: estimated[i]
33387
+ }))
33388
+ });
33389
+ return true;
33390
+ }
33391
+ const priced = priceWorkflow(result.facts, { tier, days, band: "job", curve: calibration.curve });
33392
+ savingsJobsRoute.respond(res, 200, {
33393
+ ...base,
33394
+ valid: true,
33395
+ reason: null,
33396
+ rows: [
33397
+ {
33398
+ kind: "workflow",
33399
+ workflowId: workflow.id,
33400
+ name: workflow.name,
33401
+ basis: "modelled",
33402
+ runs: priced.runs,
33403
+ substitutedRuns: priced.substitutedRuns,
33404
+ effectRuns: priced.effectRuns,
33405
+ enabledOnlyRuns: priced.enabledOnlyRuns,
33406
+ capApplied: priced.capApplied,
33407
+ opsPerRun: round2(priced.opsPerRun),
33408
+ measuredUsd: round2(priced.measuredUsd),
33409
+ estimatedLlmUsd: round2(priced.estimatedLlmUsd),
33410
+ actualUsd: round2(priced.actualUsd),
33411
+ agentOnlyUsd: roundBand(priced.agentOnlyUsd),
33412
+ savingUsd: roundBand(priced.savingUsd),
33413
+ actualHours: round2(priced.actualHours),
33414
+ agentOnlyHours: roundBand(priced.agentOnlyHours),
33415
+ hoursSaved: roundBand(priced.hoursSaved),
33416
+ agentOnlyUsdPerRun: round2(priced.agentOnlyUsdPerRun)
33417
+ }
33418
+ ]
33419
+ });
33420
+ return true;
33421
+ }
33422
+
33423
+ // src/http/savings-calibration.ts
33424
+ init_zod();
33425
+ init_db4();
33426
+ init_db_client();
33427
+
33428
+ // src/be/savings/calibrate.ts
33429
+ var TIER_MODEL = {
33430
+ smol: "claude-haiku-5-5",
33431
+ regular: "claude-sonnet-5-5",
33432
+ smart: CALIBRATION_MODEL,
33433
+ ultra: "claude-fable-5-1"
33434
+ };
33435
+ var SPEED_FALLBACK = {
33436
+ smol: 1.54,
33437
+ regular: 1.29,
33438
+ smart: 1,
33439
+ ultra: 1
33440
+ };
33441
+ var TRIM = 0.1;
33442
+ var SMOOTH_HALF_WIDTH = 2;
33443
+ var MIN_SESSIONS_PER_TURN = 5;
33444
+ var MIN_LOW_TURN = 3;
33445
+ var MIN_HIGH_TURN = 20;
33446
+ var MIN_SUPPORTED_TURNS = 15;
33447
+ var MIN_SESSIONS = 300;
33448
+ var MIN_SPEED_SESSIONS = 30;
33449
+ var SANITY_FACTOR = 3;
33450
+ var PAGE = 1000;
33451
+ var MAX_SESSIONS_READ = 200000;
33452
+
33453
+ class CalibrationRefusal extends Error {
33454
+ }
33455
+ function median(values) {
33456
+ const sorted = [...values].sort((a, b) => a - b);
33457
+ return sorted[Math.floor(sorted.length / 2)];
33458
+ }
33459
+ function trimmedMean(values, trim = TRIM) {
33460
+ const sorted = [...values].sort((a, b) => a - b);
33461
+ const cut = Math.floor(sorted.length * trim);
33462
+ const kept = sorted.slice(cut, sorted.length - cut);
33463
+ return kept.reduce((s, v) => s + v, 0) / kept.length;
33464
+ }
33465
+ function smooth(series, half) {
33466
+ return series.map((v, i) => {
33467
+ if (v === undefined)
33468
+ return;
33469
+ const pts = [];
33470
+ for (let j = Math.max(0, i - half);j <= Math.min(series.length - 1, i + half); j++) {
33471
+ const y = series[j];
33472
+ if (y !== undefined)
33473
+ pts.push([j, y]);
33474
+ }
33475
+ const n = pts.length;
33476
+ const mx = pts.reduce((s, p) => s + p[0], 0) / n;
33477
+ const my = pts.reduce((s, p) => s + p[1], 0) / n;
33478
+ const sxx = pts.reduce((s, p) => s + (p[0] - mx) ** 2, 0);
33479
+ if (sxx === 0)
33480
+ return my;
33481
+ const slope = pts.reduce((s, p) => s + (p[0] - mx) * (p[1] - my), 0) / sxx;
33482
+ return my + slope * (i - mx);
33483
+ });
33484
+ }
33485
+ function fillMonotone(series, reference) {
33486
+ const known = series.flatMap((v, i) => v === undefined ? [] : [i]);
33487
+ const first = known[0];
33488
+ const last = known[known.length - 1];
33489
+ const scaled = (i, anchor) => series[anchor] * (reference[i] / reference[anchor]);
33490
+ let floor = 0;
33491
+ return series.map((_, i) => {
33492
+ let v;
33493
+ if (i < first)
33494
+ v = scaled(i, first);
33495
+ else if (i > last)
33496
+ v = scaled(i, last);
33497
+ else {
33498
+ const lo = known.filter((k) => k <= i).at(-1);
33499
+ const hi = known.find((k) => k >= i);
33500
+ const a = series[lo];
33501
+ const b = series[hi];
33502
+ v = lo === hi ? a : a + (b - a) * (i - lo) / (hi - lo);
33503
+ }
33504
+ floor = Math.max(floor, v);
33505
+ return floor;
33506
+ });
33507
+ }
33508
+ function curveOf(sessions, value, reference) {
33509
+ const byTurns = new Map;
33510
+ for (const s of sessions) {
33511
+ if (s.turns < 1 || s.turns > TAU_MAX)
33512
+ continue;
33513
+ const at = byTurns.get(s.turns);
33514
+ if (at)
33515
+ at.push(value(s));
33516
+ else
33517
+ byTurns.set(s.turns, [value(s)]);
33518
+ }
33519
+ const raw = Array.from({ length: TAU_MAX }, (_, i) => {
33520
+ const at = byTurns.get(i + 1);
33521
+ return at && at.length >= MIN_SESSIONS_PER_TURN ? trimmedMean(at) : undefined;
33522
+ });
33523
+ raw[0] = undefined;
33524
+ const supported = raw.flatMap((v, i) => v === undefined ? [] : [i + 1]);
33525
+ const lo = supported[0];
33526
+ const hi = supported[supported.length - 1];
33527
+ if (lo === undefined || hi === undefined || lo > MIN_LOW_TURN || hi < MIN_HIGH_TURN || supported.length < MIN_SUPPORTED_TURNS) {
33528
+ throw new CalibrationRefusal(`turn coverage too thin: ${supported.length} of ${TAU_MAX - 1} turn counts have ${MIN_SESSIONS_PER_TURN}+ sessions` + `${lo === undefined ? "" : ` (turns ${lo}..${hi})`}; need at least ${MIN_SUPPORTED_TURNS}, reaching turn ${MIN_LOW_TURN} or lower and turn ${MIN_HIGH_TURN} or higher`);
33529
+ }
33530
+ const smoothed = smooth(raw.slice(1), SMOOTH_HALF_WIDTH);
33531
+ const filled = fillMonotone(smoothed, reference.slice(1));
33532
+ return [filled[0], ...filled];
33533
+ }
33534
+ var round3 = (x, digits) => Number(x.toFixed(digits));
33535
+ function deriveCurves(input) {
33536
+ const { opus, prices, tierTurns, end } = input;
33537
+ const usable = opus.filter((s) => s.turns >= 1 && s.turns <= TAU_MAX);
33538
+ if (usable.length < MIN_SESSIONS) {
33539
+ throw new CalibrationRefusal(`only ${usable.length} opus sessions of 1..${TAU_MAX} turns in the window; need ${MIN_SESSIONS}`);
33540
+ }
33541
+ const opusTokensCost = (p) => (s) => (s.inputTokens * p.input + s.outputTokens * p.output + s.cacheReadTokens * p.cached_input + s.cacheWriteTokens * p.cache_write_1h) / 1e6;
33542
+ const price = (p) => (s) => opusTokensCost(p)(s) + s.otherUsd;
33543
+ const opusCost = opusTokensCost(prices.smart);
33544
+ const repriceMatch = usable.filter((s) => Math.abs(opusCost(s) - s.costUsd) <= 0.01 * s.costUsd).length / usable.length;
33545
+ const opusHrs = curveOf(usable, (s) => s.durationMs / 3600000, CURVE.smart.hrs);
33546
+ const perTurn = (rows) => median(rows.filter((r) => r.turns >= 3 && r.turns <= TAU_MAX).map((r) => r.durationMs / r.turns));
33547
+ const opusPerTurn = perTurn(usable.map((s) => ({ turns: s.turns, durationMs: s.durationMs })));
33548
+ const speed = Object.fromEntries(SAVINGS_TIERS.map((tier) => {
33549
+ const rows = (tierTurns[tier] ?? []).filter((r) => r.turns >= 3 && r.turns <= TAU_MAX);
33550
+ if (tier === "smart")
33551
+ return [tier, 1];
33552
+ return [
33553
+ tier,
33554
+ rows.length >= MIN_SPEED_SESSIONS ? round3(perTurn(rows) / opusPerTurn, 3) : SPEED_FALLBACK[tier]
33555
+ ];
33556
+ }));
33557
+ const curve = Object.fromEntries(SAVINGS_TIERS.map((tier) => [
33558
+ tier,
33559
+ {
33560
+ usd: curveOf(usable, price(prices[tier]), CURVE[tier].usd).map((v) => round3(v, 4)),
33561
+ hrs: opusHrs.map((v) => round3(v * speed[tier], 5))
33562
+ }
33563
+ ]));
33564
+ return {
33565
+ calibratedAt: end.toISOString().slice(0, 10),
33566
+ model: CALIBRATION_MODEL,
33567
+ curve,
33568
+ sessions: usable.length,
33569
+ usable,
33570
+ speed,
33571
+ repriceMatch
33572
+ };
33573
+ }
33574
+ function compareToShipped(curve, sessionsPerTurn) {
33575
+ return SAVINGS_TIERS.flatMap((tier) => ["usd", "hrs"].map((key) => {
33576
+ const pairs = curve[tier][key].map((v, i) => ({ ratio: v / CURVE[tier][key][i], w: sessionsPerTurn[i] ?? 0 })).slice(1);
33577
+ const dev = pairs.map((p) => Math.abs(p.ratio - 1)).sort((a, b) => a - b);
33578
+ const w = pairs.reduce((s, p) => s + p.w, 0);
33579
+ return {
33580
+ tier,
33581
+ key,
33582
+ median: dev[Math.floor(dev.length / 2)],
33583
+ max: dev[dev.length - 1],
33584
+ over5pct: dev.filter((d) => d > 0.05).length,
33585
+ points: dev.length,
33586
+ weighted: pairs.reduce((s, p) => s + p.w * p.ratio, 0) / w
33587
+ };
33588
+ }));
33589
+ }
33590
+ var num2 = (v) => Number(v) || 0;
33591
+ async function pages(sql, query, params) {
33592
+ const out = [];
33593
+ let after = "";
33594
+ for (;; ) {
33595
+ const rows = await sql(query, [...params, after]);
33596
+ out.push(...rows);
33597
+ if (out.length > MAX_SESSIONS_READ) {
33598
+ throw new CalibrationRefusal(`more than ${MAX_SESSIONS_READ} sessions in the window; use a shorter window (days)`);
33599
+ }
33600
+ if (rows.length < PAGE)
33601
+ return out;
33602
+ after = rows[rows.length - 1].id;
33603
+ }
33604
+ }
33605
+ async function fetchInput(sql, start, end) {
33606
+ const window = [start.toISOString(), end.toISOString()];
33607
+ const opusRows = await pages(sql, `SELECT s.id AS id, s.numTurns AS turns, s.durationMs AS durationMs,
33608
+ json_extract(j.value,'$.inputTokens') AS inputTokens, json_extract(j.value,'$.outputTokens') AS outputTokens,
33609
+ json_extract(j.value,'$.cacheReadTokens') AS cacheReadTokens, json_extract(j.value,'$.cacheWriteTokens') AS cacheWriteTokens,
33610
+ json_extract(j.value,'$.costUsd') AS costUsd, s.totalCostUsd AS totalCostUsd
33611
+ FROM session_costs s, json_each(CASE WHEN json_valid(s.modelBreakdown) THEN s.modelBreakdown ELSE '[]' END) j
33612
+ WHERE s.model = ? AND json_extract(j.value,'$.model') = ? AND s.createdAt >= ? AND s.createdAt < ?
33613
+ AND s.numTurns BETWEEN 1 AND ${TAU_MAX} AND s.id > ? ORDER BY s.id LIMIT ${PAGE}`, [CALIBRATION_MODEL, CALIBRATION_MODEL, ...window]);
33614
+ const opus = opusRows.map((r) => ({
33615
+ turns: num2(r.turns),
33616
+ durationMs: num2(r.durationMs),
33617
+ inputTokens: num2(r.inputTokens),
33618
+ outputTokens: num2(r.outputTokens),
33619
+ cacheReadTokens: num2(r.cacheReadTokens),
33620
+ cacheWriteTokens: num2(r.cacheWriteTokens),
33621
+ costUsd: num2(r.costUsd),
33622
+ otherUsd: Math.max(0, num2(r.totalCostUsd) - num2(r.costUsd))
33623
+ }));
33624
+ const priceRows = await sql(`SELECT model, token_class, price_per_million_usd AS price FROM pricing
33625
+ WHERE provider = 'claude' AND model IN (${SAVINGS_TIERS.map(() => "?").join(",")}) AND effective_from <= ?
33626
+ ORDER BY effective_from`, [...SAVINGS_TIERS.map((t) => TIER_MODEL[t]), end.getTime()]);
33627
+ const latest = new Map;
33628
+ for (const r of priceRows)
33629
+ latest.set(`${r.model}|${r.token_class}`, num2(r.price));
33630
+ const prices = Object.fromEntries(SAVINGS_TIERS.map((tier) => [
33631
+ tier,
33632
+ Object.fromEntries(["input", "output", "cached_input", "cache_write_1h"].map((cls) => {
33633
+ const p = latest.get(`${TIER_MODEL[tier]}|${cls}`);
33634
+ if (p === undefined) {
33635
+ throw new CalibrationRefusal(`no ${cls} price for ${TIER_MODEL[tier]}`);
33636
+ }
33637
+ return [cls, p];
33638
+ }))
33639
+ ]));
33640
+ const tierTurns = {};
33641
+ for (const tier of SAVINGS_TIERS) {
33642
+ if (tier === "smart")
33643
+ continue;
33644
+ const rows = await pages(sql, `SELECT id, numTurns AS turns, durationMs FROM session_costs
33645
+ WHERE model = ? AND createdAt >= ? AND createdAt < ? AND numTurns BETWEEN 3 AND ${TAU_MAX} AND id > ? ORDER BY id LIMIT ${PAGE}`, [TIER_MODEL[tier], ...window]);
33646
+ tierTurns[tier] = rows.map((r) => ({ turns: num2(r.turns), durationMs: num2(r.durationMs) }));
33647
+ }
33648
+ return { opus, prices, tierTurns, end };
33649
+ }
33650
+ async function calibrate(sql, opts) {
33651
+ const start = new Date(opts.end.getTime() - opts.days * 86400000);
33652
+ const window = { start: start.toISOString(), end: opts.end.toISOString(), days: opts.days };
33653
+ const refused = (refusal) => ({
33654
+ window,
33655
+ sessions: 0,
33656
+ refusal,
33657
+ calibration: null,
33658
+ speed: null,
33659
+ repriceMatch: null,
33660
+ gaps: [],
33661
+ meanRatio: null,
33662
+ applyBlocked: null
33663
+ });
33664
+ let derived;
33665
+ try {
33666
+ derived = deriveCurves(await fetchInput(sql, start, opts.end));
33667
+ } catch (err) {
33668
+ if (err instanceof CalibrationRefusal)
33669
+ return refused(err.message);
33670
+ throw err;
33671
+ }
33672
+ const perTurn = Array.from({ length: TAU_MAX }, () => 0);
33673
+ for (const s of derived.usable)
33674
+ perTurn[s.turns - 1] = perTurn[s.turns - 1] + 1;
33675
+ const mean = (a) => a.reduce((s, v) => s + v, 0) / a.length;
33676
+ const meanRatio = mean(derived.curve.smart.usd) / mean(CURVE.smart.usd);
33677
+ return {
33678
+ window,
33679
+ sessions: derived.sessions,
33680
+ refusal: null,
33681
+ calibration: {
33682
+ calibratedAt: derived.calibratedAt,
33683
+ model: derived.model,
33684
+ curve: derived.curve,
33685
+ window: { start: window.start, end: window.end, sessions: derived.sessions }
33686
+ },
33687
+ speed: derived.speed,
33688
+ repriceMatch: derived.repriceMatch,
33689
+ gaps: compareToShipped(derived.curve, perTurn),
33690
+ meanRatio,
33691
+ applyBlocked: meanRatio > SANITY_FACTOR || meanRatio < 1 / SANITY_FACTOR ? `derived smart curve is ${meanRatio.toFixed(2)}x the shipped one (limit ${SANITY_FACTOR}x)` : null
33692
+ };
33693
+ }
33694
+
33695
+ // src/http/savings-calibration.ts
33696
+ init_db_query_shared();
33697
+ init_route_def();
33698
+ init_utils2();
33699
+ var DEADLINE_MS = 120000;
33700
+ var deadlineMs = DEADLINE_MS;
33701
+ var running2 = false;
33702
+ class DeadlineError extends Error {
33703
+ }
33704
+ var plain = (c) => Object.fromEntries(SAVINGS_TIERS.map((t) => [t, { usd: [...c[t].usd], hrs: [...c[t].hrs] }]));
33705
+ function deadlineSql(deadlineAt) {
33706
+ return async (sql, params) => {
33707
+ for (let attempt = 0;; attempt++) {
33708
+ const left = deadlineAt - Date.now();
33709
+ if (left <= 0)
33710
+ throw new DeadlineError;
33711
+ let timer;
33712
+ const query = boundedSql(sql, params);
33713
+ query.catch(() => {});
33714
+ try {
33715
+ return await Promise.race([
33716
+ query,
33717
+ new Promise((_, reject) => {
33718
+ timer = setTimeout(() => reject(new DeadlineError), left);
33719
+ })
33720
+ ]);
33721
+ } catch (err) {
33722
+ if (!(err instanceof DbQueryConcurrencyCapError))
33723
+ throw err;
33724
+ const nap = Math.min(250 * 2 ** attempt, 2000, Math.max(0, deadlineAt - Date.now()));
33725
+ await new Promise((r) => setTimeout(r, nap));
33726
+ } finally {
33727
+ clearTimeout(timer);
33728
+ }
33729
+ }
33730
+ };
33731
+ }
33732
+ var TierCurvesSchema = object2({ usd: array2(number2()), hrs: array2(number2()) });
33733
+ var CurveSetSchema = object2(Object.fromEntries(SAVINGS_TIERS.map((t) => [t, TierCurvesSchema])));
33734
+ var WindowSchema = object2({ start: string2(), end: string2(), sessions: number2().int() });
33735
+ var StoredSchema = object2({
33736
+ calibratedAt: string2(),
33737
+ model: string2(),
33738
+ curve: CurveSetSchema,
33739
+ window: WindowSchema.optional()
33740
+ });
33741
+ var GapSchema = object2({
33742
+ tier: _enum2(SAVINGS_TIERS),
33743
+ key: _enum2(["usd", "hrs"]),
33744
+ median: number2().describe("Median absolute deviation from the shipped curve, as a fraction."),
33745
+ max: number2(),
33746
+ over5pct: number2().int().describe("Turn counts more than 5% from the shipped curve."),
33747
+ points: number2().int(),
33748
+ weighted: number2().describe("Session-weighted mean of derived over shipped; 1 means the same price.")
33749
+ });
33750
+ var getRoute2 = route({
33751
+ method: "get",
33752
+ path: "/api/savings/calibration",
33753
+ pattern: ["api", "savings", "calibration"],
33754
+ summary: "The savings curve in use",
33755
+ description: "Which curve prices the savings endpoints: the one shipped with the release, or one derived from this deployment's sessions and stored by `POST /api/savings/calibration`. Reports the stored row's metadata (a malformed row is reported as invalid and ignored by the savings endpoints).",
33756
+ tags: ["Savings"],
33757
+ responses: {
33758
+ 200: {
33759
+ description: "The active calibration",
33760
+ schema: object2({
33761
+ source: _enum2(["shipped", "deployment"]),
33762
+ active: StoredSchema.omit({ window: true }),
33763
+ stored: object2({
33764
+ valid: boolean(),
33765
+ updatedAt: string2(),
33766
+ calibratedAt: string2().optional(),
33767
+ model: string2().optional(),
33768
+ window: WindowSchema.optional()
33769
+ }).nullable()
33770
+ })
33771
+ }
33772
+ }
33773
+ });
33774
+ var postRoute = route({
33775
+ method: "post",
33776
+ path: "/api/savings/calibration",
33777
+ pattern: ["api", "savings", "calibration"],
33778
+ summary: "Derive the savings curve from this deployment's sessions",
33779
+ description: "Reads the window's opus sessions through the bounded query executor, derives the per-tier cost and hours curve, and compares it to the shipped one. Read-only unless `apply` is true, which also requires `config.write.any`: then the curve is stored in the global `SAVINGS_CURVE_CALIBRATION` config row and the savings endpoints use it within seconds. Nothing is stored when the data cannot support a curve or the derived mean cost is more than 3x or less than a third of the shipped one. One run at a time; a run past 120 s is abandoned with 504.",
33780
+ tags: ["Savings"],
33781
+ body: object2({
33782
+ days: number2().int().min(1).max(90).default(30),
33783
+ end: exports_iso.datetime().optional().describe("End of the window (ISO 8601); default now."),
33784
+ apply: boolean().default(false)
33785
+ }),
33786
+ responses: {
33787
+ 200: {
33788
+ description: "The derived curve, or why there is none",
33789
+ schema: object2({
33790
+ window: object2({ start: string2(), end: string2(), days: number2().int() }),
33791
+ sessions: number2().int().describe("Opus sessions of 1 to 61 turns used."),
33792
+ refusals: array2(string2()).describe("Why no curve was derived, or why a derived one was not applied."),
33793
+ calibration: StoredSchema.nullable().describe("The derived curve; null when refused."),
33794
+ speed: record2(string2(), number2()).nullable(),
33795
+ repriceMatch: number2().nullable(),
33796
+ meanRatio: number2().nullable().describe("Derived smart-tier mean cost over the shipped one."),
33797
+ gaps: array2(GapSchema),
33798
+ applied: boolean()
33799
+ })
33800
+ },
33801
+ 400: { description: "Invalid days, end or apply" },
33802
+ 403: { description: "`apply` without permission to write config" },
33803
+ 408: { description: "A session query ran past its time budget" },
33804
+ 409: { description: "Another calibration run is in progress" },
33805
+ 504: { description: "The run passed its 120 s deadline" }
33806
+ },
33807
+ rbac: {
33808
+ ungated: "a dry run only reads sessions; apply:true is gated by config.write.any in the handler"
33809
+ }
33810
+ });
33811
+ async function handleSavingsCalibration(req, res, pathSegments, queryParams) {
33812
+ if (getRoute2.match(req.method, pathSegments)) {
33813
+ const [row] = await getSwarmConfigs2({ scope: "global", key: SAVINGS_CALIBRATION_KEY });
33814
+ let parsed = null;
33815
+ try {
33816
+ const result = StoredCalibrationSchema.safeParse(JSON.parse(row?.value ?? "null"));
33817
+ parsed = result.success ? result.data : null;
33818
+ } catch {}
33819
+ const active = parsed ?? { ...SHIPPED_CALIBRATION, curve: plain(SHIPPED_CALIBRATION.curve) };
33820
+ getRoute2.respond(res, 200, {
33821
+ source: parsed ? "deployment" : "shipped",
33822
+ active: { calibratedAt: active.calibratedAt, model: active.model, curve: active.curve },
33823
+ stored: row ? {
33824
+ valid: parsed !== null,
33825
+ updatedAt: row.lastUpdatedAt,
33826
+ ...parsed ? {
33827
+ calibratedAt: parsed.calibratedAt,
33828
+ model: parsed.model,
33829
+ ...parsed.window ? { window: parsed.window } : {}
33830
+ } : {}
33831
+ } : null
33832
+ });
33833
+ return true;
33834
+ }
33835
+ if (!postRoute.match(req.method, pathSegments))
33836
+ return false;
33837
+ const parsed = await postRoute.parse(req, res, pathSegments, queryParams);
33838
+ if (!parsed)
33839
+ return true;
33840
+ const { days, end, apply } = parsed.body;
33841
+ const deadlineAt = Date.now() + deadlineMs;
33842
+ if (apply && !await ensureConfigAdmin(req, res, "config.write.any"))
33843
+ return true;
33844
+ if (running2) {
33845
+ jsonError(res, "A calibration run is already in progress", 409);
33846
+ return true;
33847
+ }
33848
+ running2 = true;
33849
+ try {
33850
+ const run = await calibrate(deadlineSql(deadlineAt), {
33851
+ days,
33852
+ end: end ? new Date(end) : new Date
33853
+ });
33854
+ if (Date.now() >= deadlineAt)
33855
+ throw new DeadlineError;
33856
+ const refusals = run.refusal ? [run.refusal] : [];
33857
+ let applied = false;
33858
+ if (apply && run.calibration) {
33859
+ if (run.applyBlocked) {
33860
+ refusals.push(`not applied: ${run.applyBlocked}`);
33861
+ } else {
33862
+ StoredCalibrationSchema.parse(run.calibration);
33863
+ await getDbClient2().transaction(() => upsertSwarmConfig2({
33864
+ scope: "global",
33865
+ key: SAVINGS_CALIBRATION_KEY,
33866
+ value: JSON.stringify(run.calibration),
33867
+ exportToEnv: false,
33868
+ description: "Savings session curve derived from this deployment's sessions"
33869
+ }), { deadlineAt });
33870
+ clearCalibrationCache();
33871
+ applied = true;
33872
+ }
33873
+ }
33874
+ postRoute.respond(res, 200, {
33875
+ window: run.window,
33876
+ sessions: run.sessions,
33877
+ refusals,
33878
+ calibration: run.calibration,
33879
+ speed: run.speed,
33880
+ repriceMatch: run.repriceMatch,
33881
+ meanRatio: run.meanRatio,
33882
+ gaps: run.gaps,
33883
+ applied
33884
+ });
33885
+ } catch (err) {
33886
+ if (err instanceof DeadlineError || err instanceof DbTransactionDeadlineError) {
33887
+ jsonError(res, `Calibration passed its ${deadlineMs / 1000} s deadline; use a shorter window`, 504);
33888
+ } else if (err instanceof DbQueryTimeoutError) {
33889
+ json(res, { error: "db_query_timeout", message: err.message }, 408);
33890
+ } else {
33891
+ throw err;
33892
+ }
33893
+ } finally {
33894
+ running2 = false;
33895
+ }
33896
+ return true;
33897
+ }
33898
+
32290
33899
  // src/http/schedules.ts
32291
33900
  init_zod();
32292
33901
  init_asset_key_auth();
@@ -40035,6 +41644,25 @@ init_webhook_lifecycle();
40035
41644
  init_ensure_token();
40036
41645
  init_route_def();
40037
41646
  init_utils2();
41647
+
41648
+ // src/http/trackers/authorize-gate.ts
41649
+ init_zod();
41650
+ init_audit_user();
41651
+ var TrackerAuthorizeQuerySchema = object2({
41652
+ redirect: string2().optional(),
41653
+ format: _enum2(["redirect", "json"]).optional()
41654
+ });
41655
+ var TrackerAuthorizeUrlSchema = object2({ authorizeUrl: string2() });
41656
+ async function ensureTrackerAuthorizeAdmin(req, res, providerName) {
41657
+ const header = req.headers["x-agent-id"];
41658
+ const agentId = Array.isArray(header) ? header[0] : header;
41659
+ const allowed = await ensureHttpPermission(req, res, "oauth-authorization.manage", `Only the lead can start the ${providerName} OAuth flow.`, agentId);
41660
+ if (!allowed)
41661
+ return null;
41662
+ return { userId: await resolveHttpAuditUserId(req, agentId) };
41663
+ }
41664
+
41665
+ // src/http/trackers/jira.ts
40038
41666
  var MANUAL_WEBHOOK_INSTRUCTIONS = "See docs-site/.../integrations/jira.mdx for manual webhook registration steps.";
40039
41667
  var JiraWebhookIdEntrySchema = object2({
40040
41668
  id: number2().int(),
@@ -40080,12 +41708,17 @@ var jiraAuthorize = route({
40080
41708
  method: "get",
40081
41709
  path: "/api/trackers/jira/authorize",
40082
41710
  pattern: ["api", "trackers", "jira", "authorize"],
40083
- summary: "Redirect to Atlassian OAuth consent screen",
41711
+ summary: "Start the Jira OAuth flow (admin): redirect to the consent screen, or return its URL",
40084
41712
  tags: ["Trackers"],
40085
- auth: { apiKey: false },
40086
- query: object2({ redirect: string2().optional() }),
41713
+ query: TrackerAuthorizeQuerySchema,
41714
+ rbac: { permission: "oauth-authorization.manage" },
40087
41715
  responses: {
41716
+ 200: {
41717
+ description: "Consent URL (format=json), for clients that navigate themselves",
41718
+ schema: TrackerAuthorizeUrlSchema
41719
+ },
40088
41720
  302: { description: "Redirect to Atlassian OAuth" },
41721
+ 403: { description: "Caller lacks oauth-authorization.manage" },
40089
41722
  500: { description: "Failed to generate authorization URL" },
40090
41723
  503: { description: "Jira integration not configured" }
40091
41724
  }
@@ -40232,18 +41865,25 @@ async function handleJiraTracker(req, res, pathSegments) {
40232
41865
  const parsed = await jiraAuthorize.parse(req, res, pathSegments, queryParams);
40233
41866
  if (!parsed)
40234
41867
  return true;
41868
+ const initiator = await ensureTrackerAuthorizeAdmin(req, res, "Jira");
41869
+ if (!initiator)
41870
+ return true;
40235
41871
  if (!isJiraEnabled()) {
40236
41872
  res.writeHead(503, { "Content-Type": "application/json" });
40237
41873
  res.end(JSON.stringify({ error: "Jira integration not configured" }));
40238
41874
  return true;
40239
41875
  }
40240
41876
  try {
40241
- const url = await getJiraAuthorizationUrl(allowedCredentialRedirect(parsed.query.redirect));
41877
+ const url = await getJiraAuthorizationUrl(allowedCredentialRedirect(parsed.query.redirect), initiator.userId);
40242
41878
  if (!url) {
40243
41879
  res.writeHead(500, { "Content-Type": "application/json" });
40244
41880
  res.end(JSON.stringify({ error: "Failed to generate authorization URL" }));
40245
41881
  return true;
40246
41882
  }
41883
+ if (parsed.query.format === "json") {
41884
+ jiraAuthorize.respond(res, 200, { authorizeUrl: url });
41885
+ return true;
41886
+ }
40247
41887
  res.writeHead(302, { Location: url });
40248
41888
  res.end();
40249
41889
  } catch (err) {
@@ -40503,12 +42143,17 @@ var linearAuthorize = route({
40503
42143
  method: "get",
40504
42144
  path: "/api/trackers/linear/authorize",
40505
42145
  pattern: ["api", "trackers", "linear", "authorize"],
40506
- summary: "Redirect to Linear OAuth consent screen",
42146
+ summary: "Start the Linear OAuth flow (admin): redirect to the consent screen, or return its URL",
40507
42147
  tags: ["Trackers"],
40508
- auth: { apiKey: false },
40509
- query: object2({ redirect: string2().optional() }),
42148
+ query: TrackerAuthorizeQuerySchema,
42149
+ rbac: { permission: "oauth-authorization.manage" },
40510
42150
  responses: {
42151
+ 200: {
42152
+ description: "Consent URL (format=json), for clients that navigate themselves",
42153
+ schema: TrackerAuthorizeUrlSchema
42154
+ },
40511
42155
  302: { description: "Redirect to Linear OAuth" },
42156
+ 403: { description: "Caller lacks oauth-authorization.manage" },
40512
42157
  500: { description: "Failed to generate authorization URL" },
40513
42158
  503: { description: "Linear integration not configured" }
40514
42159
  }
@@ -40602,18 +42247,25 @@ async function handleLinearTracker(req, res, pathSegments) {
40602
42247
  const parsed = await linearAuthorize.parse(req, res, pathSegments, queryParams);
40603
42248
  if (!parsed)
40604
42249
  return true;
42250
+ const initiator = await ensureTrackerAuthorizeAdmin(req, res, "Linear");
42251
+ if (!initiator)
42252
+ return true;
40605
42253
  if (!isLinearEnabled()) {
40606
42254
  res.writeHead(503, { "Content-Type": "application/json" });
40607
42255
  res.end(JSON.stringify({ error: "Linear integration not configured" }));
40608
42256
  return true;
40609
42257
  }
40610
42258
  try {
40611
- const url = await getLinearAuthorizationUrl(allowedCredentialRedirect(parsed.query.redirect));
42259
+ const url = await getLinearAuthorizationUrl(allowedCredentialRedirect(parsed.query.redirect), initiator.userId);
40612
42260
  if (!url) {
40613
42261
  res.writeHead(500, { "Content-Type": "application/json" });
40614
42262
  res.end(JSON.stringify({ error: "Failed to generate authorization URL" }));
40615
42263
  return true;
40616
42264
  }
42265
+ if (parsed.query.format === "json") {
42266
+ linearAuthorize.respond(res, 200, { authorizeUrl: url });
42267
+ return true;
42268
+ }
40617
42269
  res.writeHead(302, { Location: url });
40618
42270
  res.end();
40619
42271
  } catch (err) {
@@ -44670,6 +46322,8 @@ var httpServer = createHttpServer(async (req, res) => {
44670
46322
  () => handleImprovements(req, res, pathSegments, queryParams),
44671
46323
  () => handleRanking(req, res, pathSegments, queryParams),
44672
46324
  () => handleFleetBenchmark(req, res, pathSegments, queryParams),
46325
+ () => handleSavings(req, res, pathSegments, queryParams),
46326
+ () => handleSavingsCalibration(req, res, pathSegments, queryParams),
44673
46327
  () => handleTaskTemplates(req, res, pathSegments, queryParams),
44674
46328
  () => handleMcp(req, res, transports, transportActivity, mcpSessionAgents),
44675
46329
  () => handleMcpUser(req, res, transportsUser, sessionUsers, transportActivityUser)
@@ -44696,7 +46350,7 @@ var httpServer = createHttpServer(async (req, res) => {
44696
46350
  });
44697
46351
  });
44698
46352
  var detachRealtime = attachRealtimeTransport(httpServer);
44699
- var { attachControllerTransport } = await import("./controllers-connect-k5sg9m9h.js");
46353
+ var { attachControllerTransport } = await import("./controllers-connect-nxa1ddwn.js");
44700
46354
  var detachControllers = attachControllerTransport(httpServer);
44701
46355
  var stopWorkerNudges = startWorkerNudgeListener();
44702
46356
  var taskAutoTitles = startTaskAutoTitleListener();
@@ -44727,7 +46381,7 @@ async function shutdown() {
44727
46381
  sessionsProcessed: getServerSessionsProcessed()
44728
46382
  });
44729
46383
  if (hasCapability("scheduling")) {
44730
- const { stopScheduler } = await import("./index-f0hcrs8e.js");
46384
+ const { stopScheduler } = await import("./index-tv3413wy.js");
44731
46385
  stopScheduler();
44732
46386
  }
44733
46387
  stopHeartbeat2();
@@ -44739,7 +46393,7 @@ async function shutdown() {
44739
46393
  await stopSlackApp2();
44740
46394
  await stopChatSdk();
44741
46395
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
44742
- const { stopOAuthKeepalive } = await import("./keepalive-xn6s7rmg.js");
46396
+ const { stopOAuthKeepalive } = await import("./keepalive-91s7hzrb.js");
44743
46397
  await stopOAuthKeepalive();
44744
46398
  }
44745
46399
  stopOAuthPendingGc();
@@ -44823,21 +46477,21 @@ try {
44823
46477
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
44824
46478
  }
44825
46479
  try {
44826
- const { ensurePricingSeeded } = await import("./boot-seeds-pbtmvcjm.js");
46480
+ const { ensurePricingSeeded } = await import("./boot-seeds-7hjj91qj.js");
44827
46481
  ensurePricingSeeded();
44828
- const { startPricingRefreshLoop } = await import("./pricing-refresh-7dh2yase.js");
46482
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-ha21jhk7.js");
44829
46483
  startPricingRefreshLoop();
44830
46484
  } catch (err) {
44831
46485
  console.error("[startup] Failed to seed pricing rows:", err);
44832
46486
  }
44833
46487
  try {
44834
- const { ensureModelProfilesSeeded } = await import("./boot-seeds-pbtmvcjm.js");
46488
+ const { ensureModelProfilesSeeded } = await import("./boot-seeds-7hjj91qj.js");
44835
46489
  await ensureModelProfilesSeeded();
44836
46490
  } catch (err) {
44837
46491
  console.error("[startup] Failed to seed model profiles:", err);
44838
46492
  }
44839
46493
  try {
44840
- const { ensureRbacSeeded } = await import("./boot-seeds-pbtmvcjm.js");
46494
+ const { ensureRbacSeeded } = await import("./boot-seeds-7hjj91qj.js");
44841
46495
  ensureRbacSeeded();
44842
46496
  } catch (err) {
44843
46497
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -44845,7 +46499,7 @@ try {
44845
46499
  throw err;
44846
46500
  }
44847
46501
  try {
44848
- const { runAllSeeders } = await import("./index-tez78qj3.js");
46502
+ const { runAllSeeders } = await import("./index-qav6455f.js");
44849
46503
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
44850
46504
  } catch (err) {
44851
46505
  console.error("[startup] Failed to seed built-in entities:", err);
@@ -44908,25 +46562,25 @@ httpServer.listen(port, async () => {
44908
46562
  await initWorkflows2();
44909
46563
  await startScriptRunSupervisor(getMcpBaseUrl());
44910
46564
  if (hasCapability("scheduling")) {
44911
- const { startScheduler } = await import("./index-f0hcrs8e.js");
44912
- const { getExecutorRegistry } = await import("./index-s4ewdma4.js");
46565
+ const { startScheduler } = await import("./index-tv3413wy.js");
46566
+ const { getExecutorRegistry } = await import("./index-ksmyd6kc.js");
44913
46567
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
44914
46568
  startScheduler(getExecutorRegistry(), intervalMs, {
44915
46569
  runId: globalState.__runId
44916
46570
  });
44917
46571
  }
44918
46572
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
44919
- const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-4xwaf5th.js");
46573
+ const { parseHeartbeatIntervalMs, startHeartbeat } = await import("./index-rjnrje98.js");
44920
46574
  startHeartbeat(parseHeartbeatIntervalMs(process.env.HEARTBEAT_INTERVAL_MS));
44921
46575
  }
44922
46576
  startPoolRouting();
44923
46577
  startRuntimeSupervisor();
44924
46578
  if (!isEnvFlagEnabled("OAUTH_KEEPALIVE_DISABLE", false)) {
44925
- const { startOAuthKeepalive } = await import("./keepalive-xn6s7rmg.js");
46579
+ const { startOAuthKeepalive } = await import("./keepalive-91s7hzrb.js");
44926
46580
  startOAuthKeepalive();
44927
46581
  }
44928
46582
  if (!isEnvFlagEnabled("OAUTH_REFRESH_SWEEP_DISABLE", false)) {
44929
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-094c8wfk.js");
46583
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-rzqfm94j.js");
44930
46584
  startOAuthRefreshSweep();
44931
46585
  }
44932
46586
  startOAuthPendingGc();
@@ -44935,19 +46589,19 @@ httpServer.listen(port, async () => {
44935
46589
  await startDbRetention();
44936
46590
  startHumanFreeDrain();
44937
46591
  startTaskSearchBackfill();
44938
- import("./embedding-space-ezwenjmj.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
46592
+ import("./embedding-space-4p05vb2x.js").then(({ runEmbeddingMaintenance, setDeploymentEnvReader }) => {
44939
46593
  setDeploymentEnvReader(getDeploymentEnvValue);
44940
46594
  return runEmbeddingMaintenance({ backfill: true });
44941
46595
  }).catch((err) => {
44942
46596
  console.error("[embedding-space] startup maintenance failed (non-fatal):", err);
44943
46597
  });
44944
- import("./boot-args-schema-pbbnhmc3.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
46598
+ import("./boot-args-schema-66bk37wv.js").then(({ runBootArgsSchemaBackfill }) => runBootArgsSchemaBackfill()).catch((err) => {
44945
46599
  console.error("[boot-args-schema] startup backfill failed (non-fatal):", err);
44946
46600
  });
44947
- import("./boot-scrub-sweep-app8g8ym.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
46601
+ import("./boot-scrub-sweep-1xc35965.js").then(({ runBootScrubSweep }) => runBootScrubSweep()).catch((err) => {
44948
46602
  console.error("[boot-scrub-sweep] startup scrub failed (non-fatal):", err);
44949
46603
  });
44950
- import("./session-source-backfill-nt923ask.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
46604
+ import("./session-source-backfill-pbqzbncv.js").then(({ runSessionSourceBackfill }) => runSessionSourceBackfill()).catch((err) => {
44951
46605
  console.error("[session-source-backfill] startup run failed (non-fatal):", err);
44952
46606
  });
44953
46607
  }).on("error", (err) => {