@desplega.ai/agent-swarm 2.8.1 → 2.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-adapter-xq6s2z6t.js +14 -0
- package/dist/{actions-pwjpn0j6.js → actions-ewz7bp4g.js} +20 -19
- package/dist/{amp-adapter-cq9jgj6x.js → amp-adapter-f25tqhnf.js} +3 -3
- package/dist/{app-cnfffgwg.js → app-mkptw0k7.js} +4 -4
- package/dist/{assistant-kpn317y1.js → assistant-c47rfe77.js} +23 -22
- package/dist/{boot-args-schema-pbbnhmc3.js → boot-args-schema-4vb0xsat.js} +1 -1
- package/dist/{boot-reembed-9m0ysxma.js → boot-reembed-1ghy2sab.js} +1 -1
- package/dist/{boot-reembed-majbn53m.js → boot-reembed-htr73hbs.js} +1 -1
- package/dist/{boot-scrub-sweep-app8g8ym.js → boot-scrub-sweep-yrytg42z.js} +4 -4
- package/dist/{boot-seeds-pbtmvcjm.js → boot-seeds-n2b3dx4e.js} +4 -4
- package/dist/{boxd-qbkxy6ap.js → boxd-jmfqgkqa.js} +2 -2
- package/dist/{claude-adapter-wn1g3qp5.js → claude-adapter-r33pqnzx.js} +8 -9
- package/dist/{claude-managed-adapter-jh6c523j.js → claude-managed-adapter-hddmxjyj.js} +4 -4
- package/dist/{claude-managed-setup-pd47nzch.js → claude-managed-setup-hfvry1bd.js} +5 -5
- package/dist/{claude-sdk-session-3a2a6589.js → claude-sdk-session-0hamqzc7.js} +10 -11
- package/dist/{cli-v1dv1r37.js → cli-0bcgyj5b.js} +74 -3
- package/dist/{cli-a3b239vq.js → cli-0vksaxvr.js} +2 -2
- package/dist/{cli-mrt48bx7.js → cli-15204js0.js} +1 -1
- package/dist/{cli-8aes17e4.js → cli-1m96dc36.js} +3 -3
- package/dist/{cli-2r0jcc3k.js → cli-2d0cghfn.js} +1 -1
- package/dist/{cli-wk18cm92.js → cli-4ax9mvvg.js} +4 -4
- package/dist/{cli-9wngrawf.js → cli-4dpkjc2e.js} +6 -6
- package/dist/{cli-x1wa213s.js → cli-4e1hfbpq.js} +5 -5
- package/dist/{cli-7349va39.js → cli-500c09j9.js} +921 -431
- package/dist/{cli-m4dqmnbp.js → cli-54qr8mcd.js} +2 -2
- package/dist/{cli-m88rpzkh.js → cli-5a7szzfh.js} +2 -2
- package/dist/{cli-bst1vp7e.js → cli-5y2fvw4z.js} +13 -5
- package/dist/{cli-vj75tyaw.js → cli-6yygkr0w.js} +7 -7
- package/dist/{cli-7b8sbmag.js → cli-7c5tgqhf.js} +5 -5
- package/dist/{cli-2gxeg5gr.js → cli-8476gtwf.js} +1 -1
- package/dist/{cli-yncmerje.js → cli-922z7gwm.js} +4 -4
- package/dist/{cli-jrzkw01m.js → cli-93t5s4zq.js} +2 -2
- package/dist/{cli-sn7rtnj4.js → cli-9zmb7ptc.js} +9 -9
- package/dist/{cli-tk7cjj8h.js → cli-am1ptset.js} +3 -3
- package/dist/{cli-cyhbbd1z.js → cli-awwptga4.js} +1 -1
- package/dist/{cli-89cqnasv.js → cli-bhsfbmk8.js} +19 -7
- package/dist/{cli-9vhebtjz.js → cli-bj6qhgte.js} +15 -32
- package/dist/{cli-g70vxtjh.js → cli-c0xjnr8z.js} +2 -2
- package/dist/{cli-vqptjbr7.js → cli-c3ng0mb4.js} +14 -14
- package/dist/{cli-re4raaj0.js → cli-c71n3bxq.js} +11 -6
- package/dist/{cli-7p1kvkck.js → cli-crpf163n.js} +25 -18
- package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
- package/dist/{cli-d3p5vwbk.js → cli-dpsfwh7n.js} +13 -21
- package/dist/{cli-xzm9vcfg.js → cli-dtdht77h.js} +2 -2
- package/dist/{cli-bb431xey.js → cli-e2w34h6z.js} +231 -68
- package/dist/{cli-eddnyg3t.js → cli-emekyyhr.js} +1 -1
- package/dist/{cli-d84byzn8.js → cli-f1kwb5fc.js} +109 -33
- package/dist/{cli-0jzra9ad.js → cli-gn9y6fn7.js} +2 -2
- package/dist/{cli-tqegb8eq.js → cli-gpz1d0t2.js} +4 -4
- package/dist/{cli-7w69ne2f.js → cli-h9yy18gy.js} +239 -67
- package/dist/{cli-m5akxq8q.js → cli-j8cjdzan.js} +1 -1
- package/dist/{cli-m9s2qff2.js → cli-jg5txpm6.js} +187 -93
- package/dist/{cli-k26bkr9t.js → cli-k2rw11py.js} +3 -3
- package/dist/{cli-93k32c37.js → cli-k96cecs7.js} +377 -61
- package/dist/{cli-3vjhs18n.js → cli-kd56bmk4.js} +1 -1
- package/dist/{cli-k0615eh8.js → cli-kmemts3w.js} +13 -13
- package/dist/{cli-pcad4cb1.js → cli-knva3nmx.js} +2 -2
- package/dist/{cli-b085njxz.js → cli-kw44j53p.js} +15 -14
- package/dist/{cli-bsywb58a.js → cli-mdpbjnzq.js} +10 -10
- package/dist/{cli-syybb0p1.js → cli-me0r8gzr.js} +35 -76
- package/dist/{cli-4r05hnqa.js → cli-mwwmka77.js} +15 -15
- package/dist/{cli-1xh9a7hn.js → cli-n5t077me.js} +2 -2
- package/dist/{cli-rvhdmjvt.js → cli-nx2n3z6p.js} +1 -1
- package/dist/{cli-28fq781p.js → cli-pe4d96rb.js} +1 -1
- package/dist/{cli-3rkdne1h.js → cli-pxwtcgcp.js} +2 -2
- package/dist/{cli-zcsw143p.js → cli-qmqt520k.js} +2 -2
- package/dist/{cli-2zp0et3v.js → cli-qps8je6j.js} +70 -19
- package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
- package/dist/{cli-k93bq1wq.js → cli-rjvsf9qa.js} +5 -5
- package/dist/{cli-6mma83xa.js → cli-rqfvkx5t.js} +7 -7
- package/dist/{cli-dy32zecz.js → cli-s7zz734a.js} +1 -1
- package/dist/{cli-yn2bbre9.js → cli-s8p8hhty.js} +2 -2
- package/dist/{cli-vbh10fqa.js → cli-sdvcrq5x.js} +5 -5
- package/dist/{cli-b5rs97a6.js → cli-sg27rk2t.js} +5 -5
- package/dist/{cli-d6521kb5.js → cli-skmhsnqh.js} +1 -1
- package/dist/{cli-5mrq3ake.js → cli-t4dv07kr.js} +1 -1
- package/dist/{cli-hxpyc9sn.js → cli-t5ys4ebm.js} +3 -3
- package/dist/{cli-qmqk2yc2.js → cli-tas6ckky.js} +2 -2
- package/dist/{cli-p1w18yhx.js → cli-tf79ryyy.js} +1 -1
- package/dist/{cli-kc7v1nfv.js → cli-tnzebztn.js} +1 -1
- package/dist/{cli-gax7fk3t.js → cli-vx421edw.js} +3 -3
- package/dist/{cli-kchjb7qy.js → cli-x3ex5bqf.js} +1 -1
- package/dist/cli-yss07azk.js +142 -0
- package/dist/{cli-0ntbxyaa.js → cli-z8cvws4c.js} +363 -47
- package/dist/{cli-tacge1w0.js → cli-zdaypkq9.js} +146 -52
- package/dist/{cli-b8e9nb04.js → cli-zeaehgyd.js} +2 -2
- package/dist/{cli-jcpr5smb.js → cli-ztq5z4e1.js} +4 -4
- package/dist/cli.js +21 -21
- package/dist/{codex-adapter-nha71q3n.js → codex-adapter-2brxx5ta.js} +7 -8
- package/dist/{codex-hook-h3vk6xzr.js → codex-hook-c930c3ea.js} +2 -2
- package/dist/{codex-login-bcda78ge.js → codex-login-cbrs1h5w.js} +1 -1
- package/dist/{codex-session-runner-ak9x1k1h.js → codex-session-runner-y9anfj0r.js} +8 -9
- package/dist/{commands-f587qpq8.js → commands-wn9q06qr.js} +3 -3
- package/dist/{controller-hxx8wwy1.js → controller-fw608czd.js} +4 -4
- package/dist/{controllers-connect-k5sg9m9h.js → controllers-connect-63j5rdcm.js} +20 -20
- package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-6mb9jme8.js} +2 -2
- package/dist/{db-nzf8zb5z.js → db-0m6v5tq4.js} +3 -3
- package/dist/{db-amm8w15a.js → db-y4wfrzbm.js} +4 -2
- package/dist/{devin-adapter-xedz98zv.js → devin-adapter-r0yx3gv8.js} +1 -1
- package/dist/{dispatcher-89zrts8f.js → dispatcher-9tq2zzdj.js} +17 -17
- package/dist/{docker-866qpzt9.js → docker-j75atvpt.js} +2 -2
- package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-t09sv4tq.js} +2 -2
- package/dist/{e2b-s16txnpx.js → e2b-7s9dscap.js} +3 -3
- package/dist/{e2b-jkwfhbcv.js → e2b-a7vzs2vj.js} +3 -3
- package/dist/{easter-egg-3d-533knw22.js → easter-egg-3d-fbwvmwhe.js} +1 -1
- package/dist/{embedding-space-ezwenjmj.js → embedding-space-wh8de1t9.js} +6 -6
- package/dist/{embeddings-np74ht6g.js → embeddings-3hpbdtjr.js} +1 -1
- package/dist/{event-bus-e66gh7cc.js → event-bus-tr6h3gv8.js} +1 -1
- package/dist/{execute-b3mrb1mv.js → execute-4bdf8sdy.js} +1 -1
- package/dist/{external-channel-z46yx9d7.js → external-channel-ts2fwqh0.js} +2 -2
- package/dist/fx-adapter-1rnxnf56.js +17 -0
- package/dist/grok-adapter-efhmf1r8.js +17 -0
- package/dist/handlers-anrr3py9.js +32 -0
- package/dist/{heartbeat-dt9qw9c8.js → heartbeat-2ze5fzpc.js} +20 -20
- package/dist/{hook-8k6fbz9b.js → hook-ca54yd4s.js} +5 -5
- package/dist/{hook-jgcgygex.js → hook-gaehe2w5.js} +8 -8
- package/dist/{http-haw4r8ne.js → http-jfg8t2yk.js} +3839 -122
- package/dist/{index-tvfafeyy.js → index-3gv6sc4z.js} +1 -1
- package/dist/{index-tez78qj3.js → index-3yvzbhxd.js} +100 -23
- package/dist/index-8w2aznds.js +33 -0
- package/dist/{index-5gk12my8.js → index-csgrxedz.js} +1 -1
- package/dist/index-qnjvr362.js +37 -0
- package/dist/index-yzxd3sn9.js +32 -0
- package/dist/{keepalive-xn6s7rmg.js → keepalive-k2a3qe73.js} +4 -4
- package/dist/lead-zhxqbfdv.js +69 -0
- package/dist/{maintenance-vdts800b.js → maintenance-gb5sd5nc.js} +1 -1
- package/dist/{node-4c5jqxr3.js → node-7qsx5kvm.js} +1 -1
- package/dist/{oauth-refresh-sweep-094c8wfk.js → oauth-refresh-sweep-y7rm6bkb.js} +3 -3
- package/dist/{onboard-v99eh56m.js → onboard-jmc5qerv.js} +4 -4
- package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-7eade9ev.js} +6 -7
- package/dist/{otel-impl-q7yr9yp0.js → otel-impl-8j1xhxqd.js} +2 -2
- package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-yqmaf32x.js} +14 -13
- package/dist/{pricing-refresh-7dh2yase.js → pricing-refresh-1nj722h6.js} +2 -2
- package/dist/{rbac-roles-mdmc96p4.js → rbac-roles-b1mtr6dr.js} +3 -3
- package/dist/{rbac-roles-npbmdh77.js → rbac-roles-n1f3frk1.js} +2 -2
- package/dist/{render-v2-twhhwmms.js → render-v2-1gfpd8rj.js} +4 -4
- package/dist/{resume-5gsrjd5e.js → resume-w1s1eh5v.js} +7 -7
- package/dist/{runtime-1hv06jsn.js → runtime-84g5egsc.js} +1 -1
- package/dist/{session-access-m191x30x.js → session-access-y6z1txk4.js} +4 -4
- package/dist/{session-source-backfill-nt923ask.js → session-source-backfill-gxxwfh12.js} +3 -3
- package/dist/{setup-wv467afy.js → setup-r91gstyk.js} +1 -1
- package/dist/{virtual-modules-gazyapte.js → virtual-modules-cgnj6kme.js} +3 -3
- package/dist/{work-objects-8zkrpy13.js → work-objects-qcxzg61c.js} +20 -20
- package/dist/worker-7j2907g6.js +69 -0
- package/dist/{worker-follow-up-cecqszem.js → worker-follow-up-y2d2h7km.js} +19 -17
- package/dist/{x-2fyrt5pp.js → x-qhxq2ama.js} +2 -2
- package/openapi.json +2908 -351
- package/package.json +4 -4
- package/src/apps/catalog.generated.json +120 -1
- package/src/apps/definition.ts +38 -11
- package/src/apps/page-validator.ts +88 -0
- package/src/be/db/model-profiles.ts +110 -11
- package/src/be/db/tasks/read.ts +53 -0
- package/src/be/db/workflow-run-definitions.ts +19 -8
- package/src/be/db-client.ts +43 -5
- package/src/be/db.ts +40 -9
- package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
- package/src/be/migrations/289_automation_savings_daily.sql +47 -0
- package/src/be/migrations/291_task_slack_participants.sql +4 -0
- package/src/be/migrations/293_savings_component_links.sql +58 -0
- package/src/be/migrations/296_automation_savings_daily_read_index.sql +6 -0
- package/src/be/model-profile-check.ts +53 -20
- package/src/be/runtime-pools/routing.ts +1 -0
- package/src/be/savings/calibrate.ts +468 -0
- package/src/be/savings/compute.ts +677 -0
- package/src/be/savings/model.ts +674 -0
- package/src/be/savings/read.ts +1500 -0
- package/src/be/savings/rollup.ts +571 -0
- package/src/be/scripts/run-credential.ts +15 -3
- package/src/be/scripts/typecheck.ts +91 -4
- package/src/be/seed/agent-fs-provision.ts +48 -11
- package/src/be/seed/workflows-seeder.ts +67 -23
- package/src/be/seed-scripts/catalog/dreaming-learnings.ts +10 -2
- package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +70 -4
- package/src/be/skill-parser.ts +19 -7
- package/src/be/swarm-config-guard.ts +8 -0
- package/src/be/users.ts +29 -2
- package/src/commands/onboard/agent-fs-version.ts +1 -1
- package/src/commands/provider-error-class.ts +97 -0
- package/src/commands/runner.ts +258 -58
- package/src/extensions/contract-types.generated.ts +1 -1
- package/src/http/all-routes.ts +2 -0
- package/src/http/fs.ts +8 -2
- package/src/http/index.ts +11 -0
- package/src/http/model-profiles.ts +43 -10
- package/src/http/poll.ts +15 -1
- package/src/http/requested-by.ts +97 -1
- package/src/http/savings-calibration.ts +277 -0
- package/src/http/savings.ts +849 -0
- package/src/http/scripts.ts +26 -15
- package/src/http/tasks.ts +89 -9
- package/src/http/trackers/authorize-gate.ts +41 -0
- package/src/http/trackers/jira.ts +26 -4
- package/src/http/trackers/linear.ts +26 -4
- package/src/integrations/chat-sdk/limits.ts +6 -1
- package/src/jira/oauth.ts +7 -1
- package/src/linear/README.md +2 -1
- package/src/linear/oauth.ts +7 -1
- package/src/prompts/session-templates.ts +80 -3
- package/src/providers/acp-targets.ts +1 -1
- package/src/providers/amp-adapter.ts +1 -1
- package/src/providers/claude-adapter.ts +0 -20
- package/src/providers/claude-flag-settings.ts +12 -10
- package/src/providers/codex-adapter.ts +12 -34
- package/src/providers/opencode-adapter.ts +34 -12
- package/src/providers/pi-mono-adapter.ts +6 -5
- package/src/providers/types.ts +7 -0
- package/src/scheduler/scheduler.ts +20 -14
- package/src/scripts-runtime/ctx.ts +1 -1
- package/src/scripts-runtime/executors/quickjs-bundle.ts +1 -0
- package/src/scripts-runtime/executors/quickjs-prelude.ts +162 -2
- package/src/scripts-runtime/executors/quickjs-runner.ts +4 -1
- package/src/scripts-runtime/sdk-allowlist.ts +11 -1
- package/src/scripts-runtime/stdlib/fetch.ts +113 -15
- package/src/scripts-runtime/stdlib/index.ts +3 -1
- package/src/scripts-runtime/stdlib/retry.ts +174 -0
- package/src/scripts-runtime/swarm-sdk.ts +192 -17
- package/src/scripts-runtime/types/stdlib.d.ts +95 -4
- package/src/scripts-runtime/types/swarm-extension.d.ts +60 -0
- package/src/scripts-runtime/types/swarm-sdk.d.ts +69 -2
- package/src/slack/actions.ts +1 -0
- package/src/slack/assistant.ts +2 -0
- package/src/slack/enrich.ts +144 -50
- package/src/slack/handlers.ts +37 -95
- package/src/slack/templates.ts +9 -0
- package/src/slack/thread-buffer.ts +45 -71
- package/src/slack/thread-participants.ts +187 -0
- package/src/tasks/worker-follow-up.ts +142 -3
- package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
- package/src/tests/apps-chart-shell.test.ts +170 -0
- package/src/tests/apps-icon.test.ts +156 -2
- package/src/tests/base-prompt.test.ts +5 -4
- package/src/tests/chat-sdk-relay.test.ts +12 -0
- package/src/tests/claude-adapter-binary.test.ts +7 -1
- package/src/tests/claude-adapter.test.ts +10 -64
- package/src/tests/claude-flag-settings.test.ts +15 -11
- package/src/tests/claude-hook-credentials.test.ts +0 -1
- package/src/tests/claude-sdk-lifecycle.test.ts +5 -1
- package/src/tests/codex-adapter.test.ts +28 -78
- package/src/tests/comb-default.test.ts +6 -0
- package/src/tests/core-auth.test.ts +7 -6
- package/src/tests/create-task-vcs-repo.test.ts +136 -0
- package/src/tests/db-client-busy-retry.test.ts +58 -6
- package/src/tests/db-task-read-contract.test.ts +2 -0
- package/src/tests/db-task-write-contract.test.ts +1 -0
- package/src/tests/deploy-guard.test.ts +154 -0
- package/src/tests/docs-index-footprint.test.js +3 -3
- package/src/tests/dreaming-learnings.test.ts +104 -0
- package/src/tests/extensions-pre-task.test.ts +4 -2
- package/src/tests/fetch-resolved-env.test.ts +47 -1
- package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
- package/src/tests/model-profile-fallbacks.test.ts +482 -0
- package/src/tests/model-profiles-api.test.ts +1 -0
- package/src/tests/opencode-adapter.test.ts +53 -6
- package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
- package/src/tests/prompt-template-session.test.ts +17 -1
- package/src/tests/provider-error-class.test.ts +174 -0
- package/src/tests/runner-provider-fallback.test.ts +197 -0
- package/src/tests/runner-requester-profile.test.ts +139 -1
- package/src/tests/savings-calibration-api.test.ts +264 -0
- package/src/tests/savings-calibration.test.ts +201 -0
- package/src/tests/savings-compound.test.ts +774 -0
- package/src/tests/savings-compute.test.ts +215 -0
- package/src/tests/savings-fleet-latency.test.ts +143 -0
- package/src/tests/savings-fleet-read.test.ts +195 -0
- package/src/tests/savings-fleet-scale.test.ts +222 -0
- package/src/tests/savings-model.test.ts +499 -0
- package/src/tests/savings-read.test.ts +367 -0
- package/src/tests/savings-rollup.test.ts +766 -0
- package/src/tests/savings-scripts.test.ts +611 -0
- package/src/tests/script-connections.test.ts +4 -0
- package/src/tests/script-executor-conformance.test.ts +444 -0
- package/src/tests/scripts-http.test.ts +55 -0
- package/src/tests/scripts-runtime-fetch.test.ts +2 -2
- package/src/tests/sdk-allowlist.test.ts +40 -0
- package/src/tests/secret-rules.test.ts +124 -1
- package/src/tests/secret-scrubber.test.ts +1 -1
- package/src/tests/seed-workflows.test.ts +167 -11
- package/src/tests/skill-parser.test.ts +45 -0
- package/src/tests/slack-dm-implicit-mention.test.ts +20 -1
- package/src/tests/slack-identity-resolution.test.ts +23 -0
- package/src/tests/slack-inbound-files.test.ts +2 -1
- package/src/tests/slack-thread-participants.test.ts +429 -0
- package/src/tests/tool-annotations.test.ts +30 -0
- package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
- package/src/tests/workflow-definition-pinning.test.ts +128 -3
- package/src/tests/workflow-script-principal.test.ts +94 -4
- package/src/tools/app-upsert.ts +1 -1
- package/src/tools/model-profiles/list-model-profiles.ts +4 -2
- package/src/tools/update-profile.ts +1 -1
- package/src/types.ts +146 -33
- package/src/utils/constants.ts +2 -0
- package/src/utils/mcp-server-fetcher.test.ts +89 -0
- package/src/utils/mcp-server-fetcher.ts +13 -5
- package/src/utils/request-auth-context.ts +24 -0
- package/src/utils/secret-rules.generated.ts +1 -1
- package/src/utils/secret-scrubber.ts +154 -29
- package/src/workflows/executors/swarm-script.ts +23 -19
- package/templates/skills/apps/SKILL.md +62 -3
- package/templates/skills/apps/content.md +62 -3
- package/templates/skills/swarm-docs/content.md +2 -0
- package/templates/skills/swarm-scripts/SKILL.md +5 -4
- package/templates/skills/swarm-scripts/content.md +5 -4
- package/templates/skills/work-on-task/SKILL.md +1 -1
- package/templates/skills/work-on-task/content.md +1 -1
- package/templates/workflows/dreaming/content.md +1 -1
- package/dist/acp-adapter-pdy3qsvg.js +0 -15
- package/dist/cli-4bd1rck6.js +0 -4
- package/dist/cli-jywyhqws.js +0 -104
- package/dist/fx-adapter-3q12snn6.js +0 -18
- package/dist/grok-adapter-ahb1w033.js +0 -18
- package/dist/handlers-vbww69re.js +0 -32
- package/dist/index-4xwaf5th.js +0 -32
- package/dist/index-f0hcrs8e.js +0 -33
- package/dist/index-s4ewdma4.js +0 -37
- package/dist/lead-6ygbfhbh.js +0 -70
- package/dist/worker-mz5z7kj0.js +0 -70
- package/src/providers/ctx-mode-env.ts +0 -10
|
@@ -0,0 +1,849 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { getSwarmConfigs, getWorkflow } from "../be/db";
|
|
4
|
+
import type { DbParam } from "../be/db-client";
|
|
5
|
+
import type { SavingsSql } from "../be/savings/compute";
|
|
6
|
+
import {
|
|
7
|
+
type Calibration,
|
|
8
|
+
type CurveSet,
|
|
9
|
+
type PricedWorkflow,
|
|
10
|
+
parseCalibration,
|
|
11
|
+
SAVINGS_CALIBRATION_KEY,
|
|
12
|
+
SAVINGS_TIERS,
|
|
13
|
+
type SavingsBand,
|
|
14
|
+
SHIPPED_CALIBRATION,
|
|
15
|
+
savingsAssumptions,
|
|
16
|
+
} from "../be/savings/model";
|
|
17
|
+
import {
|
|
18
|
+
type FleetKindTotals,
|
|
19
|
+
isKnownScriptName,
|
|
20
|
+
readFleetLlmUsd,
|
|
21
|
+
readFleetSavings,
|
|
22
|
+
readScheduleSavings,
|
|
23
|
+
readScriptSavings,
|
|
24
|
+
readWorkflowComponents,
|
|
25
|
+
readWorkflowSavings,
|
|
26
|
+
type SavingsComponent,
|
|
27
|
+
type SavingsTotals,
|
|
28
|
+
type ScheduleSavingsRow,
|
|
29
|
+
savingsWindow,
|
|
30
|
+
type WorkflowComponentsRead,
|
|
31
|
+
type WorkflowSavingsRead,
|
|
32
|
+
type WorkflowSavingsRow,
|
|
33
|
+
} from "../be/savings/read";
|
|
34
|
+
import { refreshWorkflowToday, utcDay } from "../be/savings/rollup";
|
|
35
|
+
import { executeReadOnlyQueryGated } from "./db-query";
|
|
36
|
+
import {
|
|
37
|
+
DbQueryConcurrencyCapError,
|
|
38
|
+
DbQueryTimeoutError,
|
|
39
|
+
getDbQueryHttpBudgetMs,
|
|
40
|
+
} from "./db-query-shared";
|
|
41
|
+
import { route } from "./route-def";
|
|
42
|
+
import { json } from "./utils";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The scans run through the bounded db-query executor: a child process with a
|
|
46
|
+
* wall-clock budget, sharing the swarm-wide db-query concurrency cap, so they
|
|
47
|
+
* can neither block the API's event loop nor pile up.
|
|
48
|
+
*/
|
|
49
|
+
function budgetedSql(budgetMs: () => number): SavingsSql {
|
|
50
|
+
return async <T>(sql: string, params: DbParam[]) => {
|
|
51
|
+
const result = await executeReadOnlyQueryGated(sql, params, budgetMs(), 10_000);
|
|
52
|
+
return result.rows.map((row) =>
|
|
53
|
+
Object.fromEntries(result.columns.map((column, i) => [column, row[i]])),
|
|
54
|
+
) as T[];
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** One scan at the HTTP db-query budget, without waiting out a full cap (the calibration run). */
|
|
59
|
+
export const boundedSql = budgetedSql(getDbQueryHttpBudgetMs);
|
|
60
|
+
|
|
61
|
+
/** Retries a scan refused by a full concurrency cap, `attempts` times in all, sleeping `stepMs` x attempt (at most 5 s) between them. */
|
|
62
|
+
function waitOutCap(run: SavingsSql, attempts: number, stepMs: number): SavingsSql {
|
|
63
|
+
return async <T>(sql: string, params: DbParam[]) => {
|
|
64
|
+
for (let attempt = 1; ; attempt++) {
|
|
65
|
+
try {
|
|
66
|
+
return await run<T>(sql, params);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
if (!(err instanceof DbQueryConcurrencyCapError) || attempt >= attempts) throw err;
|
|
69
|
+
await Bun.sleep(Math.min(5_000, stepMs * attempt));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Request-path scans (today's bucket of one workflow, the window's first day)
|
|
77
|
+
* use the HTTP db-query budget. A full cap is waited out for about 2 s, so
|
|
78
|
+
* parallel reads queue instead of falling back to an estimate.
|
|
79
|
+
*/
|
|
80
|
+
export const savingsRequestSql = waitOutCap(budgetedSql(getDbQueryHttpBudgetMs), 8, 75);
|
|
81
|
+
|
|
82
|
+
/** The router's step scan for one day takes about 10 s. */
|
|
83
|
+
const ROLLUP_QUERY_BUDGET_MS = 60_000;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Scans of the hourly rollup. They run in the background, so a full
|
|
87
|
+
* concurrency cap is waited out (up to about a minute) instead of failing the day.
|
|
88
|
+
*/
|
|
89
|
+
export const savingsRollupSql = waitOutCap(
|
|
90
|
+
budgetedSql(() => ROLLUP_QUERY_BUDGET_MS),
|
|
91
|
+
20,
|
|
92
|
+
250,
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
const SavingsBandSchema = z.object({ p10: z.number(), p50: z.number(), p90: z.number() });
|
|
96
|
+
|
|
97
|
+
const SavingsJobRowSchema = z.object({
|
|
98
|
+
/**
|
|
99
|
+
* `script-scheduled`: a schedule targets the script, priced as a standalone
|
|
100
|
+
* agent task. `script-agent-invoked`: priced as the extra turns it adds to
|
|
101
|
+
* the calling agent's session.
|
|
102
|
+
*/
|
|
103
|
+
kind: z.enum(["workflow", "script-scheduled", "script-agent-invoked"]),
|
|
104
|
+
/** Set on workflow rows. */
|
|
105
|
+
workflowId: z.string().optional(),
|
|
106
|
+
/** Set on script rows. Scripts are keyed by name across scopes. */
|
|
107
|
+
scriptName: z.string().optional(),
|
|
108
|
+
name: z.string(),
|
|
109
|
+
basis: z.literal("modelled"),
|
|
110
|
+
/** Set on a schedule's row (`scheduleId` or `kind=schedule`): the schedule whose target this row prices. */
|
|
111
|
+
scheduleId: z.string().optional(),
|
|
112
|
+
scheduleName: z.string().optional(),
|
|
113
|
+
scheduleEnabled: z.boolean().optional(),
|
|
114
|
+
/** `target-job` on a schedule's row: runs carry no schedule link, so this is the target's whole row, shared with any other schedule of it. */
|
|
115
|
+
scope: z.literal("target-job").optional(),
|
|
116
|
+
/** True when the enabled-only rule priced only the runs with a downstream effect (an event router). */
|
|
117
|
+
enabledOnlyRule: z.boolean(),
|
|
118
|
+
runs: z.number().int(),
|
|
119
|
+
substitutedRuns: z.number().int(),
|
|
120
|
+
effectRuns: z.number().int(),
|
|
121
|
+
enabledOnlyRuns: z.number().int(),
|
|
122
|
+
capApplied: z.boolean(),
|
|
123
|
+
opsPerRun: z.number(),
|
|
124
|
+
measuredUsd: z
|
|
125
|
+
.number()
|
|
126
|
+
.describe(
|
|
127
|
+
"Measured spend of every run in the window: agent tasks, their reviews, recorded LLM cost.",
|
|
128
|
+
),
|
|
129
|
+
estimatedLlmUsd: z
|
|
130
|
+
.number()
|
|
131
|
+
.describe(
|
|
132
|
+
"LLM spend estimated from tokens and output size, not measured. 0 when the runs recorded their LLM cost.",
|
|
133
|
+
),
|
|
134
|
+
actualUsd: z
|
|
135
|
+
.number()
|
|
136
|
+
.describe(
|
|
137
|
+
"Scaled estimate, not a measurement: `measuredUsd + estimatedLlmUsd` times `substitutedRuns / runs`. The saving subtracts this.",
|
|
138
|
+
),
|
|
139
|
+
agentOnlyUsd: SavingsBandSchema,
|
|
140
|
+
savingUsd: SavingsBandSchema,
|
|
141
|
+
actualHours: z
|
|
142
|
+
.number()
|
|
143
|
+
.describe(
|
|
144
|
+
"Scaled estimate: measured hours times `substitutedRuns / runs`. Always 0 for scripts, which keep no agent active.",
|
|
145
|
+
),
|
|
146
|
+
agentOnlyHours: SavingsBandSchema,
|
|
147
|
+
hoursSaved: SavingsBandSchema,
|
|
148
|
+
agentOnlyUsdPerRun: z.number(),
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
/** What an agent-task schedule's tasks cost. There is no automation to substitute, so no saving. */
|
|
152
|
+
const SavingsMeasuredRowSchema = z.object({
|
|
153
|
+
kind: z.literal("agent-task-schedule"),
|
|
154
|
+
scheduleId: z.string(),
|
|
155
|
+
scheduleName: z.string(),
|
|
156
|
+
scheduleEnabled: z.boolean(),
|
|
157
|
+
name: z.string(),
|
|
158
|
+
basis: z.literal("measured"),
|
|
159
|
+
runs: z.number().int().describe("Agent tasks the schedule created in the window."),
|
|
160
|
+
actualUsd: z
|
|
161
|
+
.number()
|
|
162
|
+
.describe(
|
|
163
|
+
"Recorded cost of those tasks. A floor: review tasks and follow-ups are not linked to the schedule.",
|
|
164
|
+
),
|
|
165
|
+
actualHours: z.number(),
|
|
166
|
+
savingUsd: z.null(),
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const SavingsTotalsSchema = z.object({
|
|
170
|
+
runs: z.number().int(),
|
|
171
|
+
substitutedRuns: z.number().int(),
|
|
172
|
+
enabledOnlyRuns: z.number().int(),
|
|
173
|
+
measuredUsd: z.number(),
|
|
174
|
+
estimatedLlmUsd: z.number(),
|
|
175
|
+
actualUsd: z.number(),
|
|
176
|
+
agentOnlyUsd: SavingsBandSchema,
|
|
177
|
+
savingUsd: SavingsBandSchema,
|
|
178
|
+
actualHours: z.number(),
|
|
179
|
+
hoursSaved: SavingsBandSchema,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
const SavingsComponentSchema = z.object({
|
|
183
|
+
kind: z.enum(["workflow", "script", "task"]),
|
|
184
|
+
workflowId: z.string().optional(),
|
|
185
|
+
scriptName: z.string().optional(),
|
|
186
|
+
name: z.string(),
|
|
187
|
+
/**
|
|
188
|
+
* `sub-workflow`: a sub-workflow node's child run. `step-workflow`,
|
|
189
|
+
* `step-script`, `step-task`: a run, nested script run or task a
|
|
190
|
+
* swarm-script step made. `descendant-task`: a task below an agent-task node's task.
|
|
191
|
+
*/
|
|
192
|
+
linkKind: z.enum([
|
|
193
|
+
"sub-workflow",
|
|
194
|
+
"step-workflow",
|
|
195
|
+
"step-script",
|
|
196
|
+
"step-task",
|
|
197
|
+
"descendant-task",
|
|
198
|
+
]),
|
|
199
|
+
/** 1 for a direct child of the workflow. */
|
|
200
|
+
depth: z.number().int(),
|
|
201
|
+
runs: z
|
|
202
|
+
.number()
|
|
203
|
+
.describe("Runs (tasks for a task component) in this tree. Fractional below the first level."),
|
|
204
|
+
actualUsd: z.number(),
|
|
205
|
+
agentOnlyUsd: SavingsBandSchema,
|
|
206
|
+
savingUsd: SavingsBandSchema,
|
|
207
|
+
hoursSaved: SavingsBandSchema,
|
|
208
|
+
inOwnRow: z
|
|
209
|
+
.boolean()
|
|
210
|
+
.describe(
|
|
211
|
+
"True for unowned tasks: their spend is already in the workflow's own row, on both sides, and adds nothing to `withComponents`.",
|
|
212
|
+
),
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
const savingsMeta = {
|
|
216
|
+
window: z.object({ start: z.string(), end: z.string(), days: z.number().int() }),
|
|
217
|
+
tier: z.enum(SAVINGS_TIERS),
|
|
218
|
+
calibrationModel: z.string(),
|
|
219
|
+
calibratedAt: z.string(),
|
|
220
|
+
/** `shipped`: the constants in the release. `deployment`: derived from this swarm's own sessions. */
|
|
221
|
+
calibrationSource: z.enum(["shipped", "deployment"]),
|
|
222
|
+
/** Newest rollup time of the window's days; null before the first rollup. */
|
|
223
|
+
computedAt: z.string().nullable(),
|
|
224
|
+
/** False when there is nothing to show: the window is not computed yet, or had no runs. Never $0. */
|
|
225
|
+
valid: z.boolean(),
|
|
226
|
+
/** `target-missing`: `GET /api/savings/jobs?scheduleId=` for a schedule whose workflow or script is gone. */
|
|
227
|
+
reason: z.enum(["not-computed", "no-runs", "target-missing"]).nullable(),
|
|
228
|
+
boundaryEstimated: z
|
|
229
|
+
.boolean()
|
|
230
|
+
.describe(
|
|
231
|
+
"The window is rolling, so its first UTC day is partial and its runs are scanned live. True when that scan could not run (too many runs, or a busy database) and the day's bucket was scaled to the part inside the window instead.",
|
|
232
|
+
),
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const SavingsJobsResponseSchema = z.object({
|
|
236
|
+
...savingsMeta,
|
|
237
|
+
rows: z.array(z.union([SavingsJobRowSchema, SavingsMeasuredRowSchema])),
|
|
238
|
+
/** Sum of `rows`; the band is the single-job spread for one row and the fleet spread for more. Null for schedule reads, where schedules of one target would count it twice. */
|
|
239
|
+
total: SavingsTotalsSchema.nullable(),
|
|
240
|
+
/** With `components=true`: what the workflow's runs caused, each priced as on its own row. */
|
|
241
|
+
components: z.array(SavingsComponentSchema).optional(),
|
|
242
|
+
/**
|
|
243
|
+
* With `components=true`: own runs plus every component. Each component is
|
|
244
|
+
* already counted on its own row, so never add this to a list or fleet total.
|
|
245
|
+
*/
|
|
246
|
+
withComponents: SavingsTotalsSchema.nullable().optional(),
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
const SavingsDailyResponseSchema = z.object({
|
|
250
|
+
...savingsMeta,
|
|
251
|
+
/** p50 per UTC day, oldest first. The points add up to the window's p50 saving and actual cost. */
|
|
252
|
+
points: z.array(
|
|
253
|
+
z.object({
|
|
254
|
+
day: z.string(),
|
|
255
|
+
savingUsd: z.number(),
|
|
256
|
+
actualUsd: z
|
|
257
|
+
.number()
|
|
258
|
+
.describe(
|
|
259
|
+
"Scaled estimate: the day's measured and estimated spend times the window's substituted share.",
|
|
260
|
+
),
|
|
261
|
+
measuredUsd: z.number().describe("The day's measured spend, not scaled."),
|
|
262
|
+
/** Estimated; the points sum to the jobs row's `estimatedLlmUsd`. */
|
|
263
|
+
estimatedLlmUsd: z
|
|
264
|
+
.number()
|
|
265
|
+
.describe("The day's LLM spend estimated from tokens and output size, not measured."),
|
|
266
|
+
}),
|
|
267
|
+
),
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
const FleetKindTotalsSchema = z.object({
|
|
271
|
+
jobs: z.number().int(),
|
|
272
|
+
runs: z.number().int(),
|
|
273
|
+
substitutedRuns: z.number().int(),
|
|
274
|
+
savingUsd: z.number().describe("p50"),
|
|
275
|
+
hoursSaved: z.number().describe("p50"),
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
const SavingsSummaryResponseSchema = z.object({
|
|
279
|
+
...savingsMeta,
|
|
280
|
+
/** Every workflow and script; the fleet band unless the fleet is one job. */
|
|
281
|
+
total: SavingsTotalsSchema.nullable(),
|
|
282
|
+
byKind: z
|
|
283
|
+
.object({
|
|
284
|
+
workflows: FleetKindTotalsSchema,
|
|
285
|
+
scheduledScripts: FleetKindTotalsSchema,
|
|
286
|
+
agentInvokedScripts: FleetKindTotalsSchema,
|
|
287
|
+
})
|
|
288
|
+
.nullable(),
|
|
289
|
+
fleetLlmUsd: z
|
|
290
|
+
.number()
|
|
291
|
+
.describe("Measured session spend of the whole swarm in the window, as on the usage page."),
|
|
292
|
+
selfOptimizationRatio: z
|
|
293
|
+
.number()
|
|
294
|
+
.nullable()
|
|
295
|
+
.describe(
|
|
296
|
+
"`(fleetLlmUsd + savingUsd.p50) / fleetLlmUsd`: what the swarm would have spent without its automations, per dollar it spent. Null without spend or without a valid total.",
|
|
297
|
+
),
|
|
298
|
+
excluded: z
|
|
299
|
+
.object({
|
|
300
|
+
enabledOnlyRuns: z
|
|
301
|
+
.number()
|
|
302
|
+
.int()
|
|
303
|
+
.describe(
|
|
304
|
+
"Runs that are not substituted: router events and API runs with no effect, polls above the hourly cap, skipped and cancelled runs.",
|
|
305
|
+
),
|
|
306
|
+
})
|
|
307
|
+
.nullable(),
|
|
308
|
+
assumptions: z.array(z.string()),
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
const windowQuery = {
|
|
312
|
+
days: z.enum(["7", "30", "90"]).default("30").transform(Number),
|
|
313
|
+
tier: z.enum(SAVINGS_TIERS).default("smart"),
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
const savingsJobsRoute = route({
|
|
317
|
+
method: "get",
|
|
318
|
+
path: "/api/savings/jobs",
|
|
319
|
+
pattern: ["api", "savings", "jobs"],
|
|
320
|
+
summary: "Estimated automation savings per workflow or script",
|
|
321
|
+
description:
|
|
322
|
+
"What the workflows' or scripts' runs in the window would have cost as agent tasks, minus what they cost, read from the hourly savings rollup. With `workflowId` and `components=true`, also returns the workflow's components (child workflow runs, nested script runs and tasks its runs caused, recursively) priced as on their own rows, and `withComponents`, own runs plus those; lists and schedule reads reject `components=true`. `measuredUsd` is the measured spend and `estimatedLlmUsd` the LLM spend estimated where none was recorded; `actualUsd` is their sum scaled to the substituted share of runs, the estimate the saving subtracts. Modelled at the chosen tier, with an 80% range (p10 to p90). Pass `workflowId` for one workflow, `scriptName` for one script, or `kind=workflow` / `kind=script` for every workflow or script with runs. Scheduled scripts are priced as standalone agent tasks; other scripts as the extra turns they add to the calling agent's session. Scripts record no LLM spend, so their spend fields are 0. Pass `scheduleId` for one schedule, or `kind=schedule` for every schedule: a workflow or script target returns the target's row (`scope: target-job`, with `scheduleId`), because runs carry no schedule link, so schedules of one target show the same row, and `total` is null for schedule reads; an agent-task target returns a measured row (`basis` measured) with the recorded cost of its tasks and `savingUsd: null`. A disabled schedule is priced from its target's runs and flagged by `scheduleEnabled`. `valid` is false until the rollup has computed every day of the window, and when there were no runs.",
|
|
323
|
+
tags: ["Savings"],
|
|
324
|
+
query: z.object({
|
|
325
|
+
workflowId: z.string().min(1).optional(),
|
|
326
|
+
scriptName: z.string().min(1).optional(),
|
|
327
|
+
scheduleId: z.string().min(1).optional(),
|
|
328
|
+
kind: z.enum(["workflow", "script", "schedule"]).optional(),
|
|
329
|
+
components: z
|
|
330
|
+
.enum(["true", "false"])
|
|
331
|
+
.default("false")
|
|
332
|
+
.transform((v) => v === "true"),
|
|
333
|
+
...windowQuery,
|
|
334
|
+
}),
|
|
335
|
+
responses: {
|
|
336
|
+
200: { description: "Savings rows", schema: SavingsJobsResponseSchema },
|
|
337
|
+
400: {
|
|
338
|
+
description:
|
|
339
|
+
"Not exactly one of workflowId, scriptName, scheduleId and kind, `components=true` without workflowId, or an unknown days or tier value",
|
|
340
|
+
},
|
|
341
|
+
404: { description: "Workflow, script or schedule not found" },
|
|
342
|
+
},
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
const savingsDailyRoute = route({
|
|
346
|
+
method: "get",
|
|
347
|
+
path: "/api/savings/daily",
|
|
348
|
+
pattern: ["api", "savings", "daily"],
|
|
349
|
+
summary: "Daily automation savings of a workflow, a script or the fleet",
|
|
350
|
+
description:
|
|
351
|
+
"The p50 saving, measured spend, estimated LLM spend and scaled actual cost per UTC day of the window, from the hourly savings rollup. With `workflowId` or `scriptName` the points add up to the window figures of `GET /api/savings/jobs` for the same target; with neither they cover every workflow and script and add up to `GET /api/savings/summary`.",
|
|
352
|
+
tags: ["Savings"],
|
|
353
|
+
query: z.object({
|
|
354
|
+
workflowId: z.string().min(1).optional(),
|
|
355
|
+
scriptName: z.string().min(1).optional(),
|
|
356
|
+
...windowQuery,
|
|
357
|
+
}),
|
|
358
|
+
responses: {
|
|
359
|
+
200: { description: "Daily savings points", schema: SavingsDailyResponseSchema },
|
|
360
|
+
400: {
|
|
361
|
+
description: "Both workflowId and scriptName, or an unknown days or tier value",
|
|
362
|
+
},
|
|
363
|
+
404: { description: "Workflow or script not found" },
|
|
364
|
+
},
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
const savingsSummaryRoute = route({
|
|
368
|
+
method: "get",
|
|
369
|
+
path: "/api/savings/summary",
|
|
370
|
+
pattern: ["api", "savings", "summary"],
|
|
371
|
+
summary: "Fleet automation savings",
|
|
372
|
+
description:
|
|
373
|
+
"What every workflow and script run in the window would have cost as agent tasks, minus what they cost, from the hourly savings rollup at the chosen tier, with the fleet's 80% range. Adds the swarm's measured session spend over the same window, the self-optimization ratio, the runs left out and the model's assumptions. `valid` is false until the rollup has computed every day of the window, and when there were no runs.",
|
|
374
|
+
tags: ["Savings"],
|
|
375
|
+
query: z.object(windowQuery),
|
|
376
|
+
responses: {
|
|
377
|
+
200: { description: "Fleet savings", schema: SavingsSummaryResponseSchema },
|
|
378
|
+
400: { description: "An unknown days or tier value" },
|
|
379
|
+
},
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
/** The stored deployment curve is re-read this often, so a new calibration shows within a minute. */
|
|
383
|
+
const CALIBRATION_TTL_MS = 60 * 1000;
|
|
384
|
+
let calibrationCache: { at: number; value: Calibration } | null = null;
|
|
385
|
+
|
|
386
|
+
async function activeCalibration(now: number): Promise<Calibration> {
|
|
387
|
+
if (calibrationCache && now - calibrationCache.at < CALIBRATION_TTL_MS) {
|
|
388
|
+
return calibrationCache.value;
|
|
389
|
+
}
|
|
390
|
+
const [row] = await getSwarmConfigs({ scope: "global", key: SAVINGS_CALIBRATION_KEY });
|
|
391
|
+
// A malformed row falls back to the shipped curve rather than failing every savings request.
|
|
392
|
+
const value = parseCalibration(row?.value) ?? SHIPPED_CALIBRATION;
|
|
393
|
+
calibrationCache = { at: now, value };
|
|
394
|
+
return value;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Forget the cached curve, so the next savings request reads the stored row. */
|
|
398
|
+
export function clearCalibrationCache(): void {
|
|
399
|
+
calibrationCache = null;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const round2 = (x: number) => Math.round(x * 100) / 100;
|
|
403
|
+
const roundBand = (b: SavingsBand): SavingsBand => ({
|
|
404
|
+
p10: round2(b.p10),
|
|
405
|
+
p50: round2(b.p50),
|
|
406
|
+
p90: round2(b.p90),
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Round each value to cents so the rounded values sum to the rounded total
|
|
411
|
+
* (largest remainder), keeping the chart equal to the header amount.
|
|
412
|
+
*/
|
|
413
|
+
export function roundToTotal(values: number[]): number[] {
|
|
414
|
+
const cents = values.map((v) => v * 100);
|
|
415
|
+
const floors = cents.map(Math.floor);
|
|
416
|
+
let left = Math.round(cents.reduce((s, c) => s + c, 0)) - floors.reduce((s, c) => s + c, 0);
|
|
417
|
+
const order = cents
|
|
418
|
+
.map((c, i) => ({ i, r: c - (floors[i] as number) }))
|
|
419
|
+
.sort((a, b) => b.r - a.r);
|
|
420
|
+
for (const { i } of order) {
|
|
421
|
+
if (left <= 0) break;
|
|
422
|
+
floors[i] = (floors[i] as number) + 1;
|
|
423
|
+
left--;
|
|
424
|
+
}
|
|
425
|
+
return floors.map((c) => c / 100);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
type ReadRow = PricedWorkflow & { name: string } & (
|
|
429
|
+
| { workflowId: string; kind?: undefined }
|
|
430
|
+
| { scriptName: string; kind: "script-scheduled" | "script-agent-invoked" }
|
|
431
|
+
);
|
|
432
|
+
|
|
433
|
+
function toRow(row: ReadRow) {
|
|
434
|
+
return {
|
|
435
|
+
...("workflowId" in row
|
|
436
|
+
? { kind: "workflow" as const, workflowId: row.workflowId }
|
|
437
|
+
: { kind: row.kind, scriptName: row.scriptName }),
|
|
438
|
+
name: row.name,
|
|
439
|
+
basis: "modelled" as const,
|
|
440
|
+
enabledOnlyRule: row.enabledOnlyRule,
|
|
441
|
+
runs: row.runs,
|
|
442
|
+
substitutedRuns: row.substitutedRuns,
|
|
443
|
+
effectRuns: row.effectRuns,
|
|
444
|
+
enabledOnlyRuns: row.enabledOnlyRuns,
|
|
445
|
+
capApplied: row.capApplied,
|
|
446
|
+
opsPerRun: round2(row.opsPerRun),
|
|
447
|
+
measuredUsd: round2(row.measuredUsd),
|
|
448
|
+
estimatedLlmUsd: round2(row.estimatedLlmUsd),
|
|
449
|
+
actualUsd: round2(row.actualUsd),
|
|
450
|
+
agentOnlyUsd: roundBand(row.agentOnlyUsd),
|
|
451
|
+
savingUsd: roundBand(row.savingUsd),
|
|
452
|
+
actualHours: round2(row.actualHours),
|
|
453
|
+
agentOnlyHours: roundBand(row.agentOnlyHours),
|
|
454
|
+
hoursSaved: roundBand(row.hoursSaved),
|
|
455
|
+
agentOnlyUsdPerRun: round2(row.agentOnlyUsdPerRun),
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function toComponent(c: SavingsComponent) {
|
|
460
|
+
return {
|
|
461
|
+
...c,
|
|
462
|
+
runs: round2(c.runs),
|
|
463
|
+
actualUsd: round2(c.actualUsd),
|
|
464
|
+
agentOnlyUsd: roundBand(c.agentOnlyUsd),
|
|
465
|
+
savingUsd: roundBand(c.savingUsd),
|
|
466
|
+
hoursSaved: roundBand(c.hoursSaved),
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function toScheduleRow(row: ScheduleSavingsRow) {
|
|
471
|
+
const ref = {
|
|
472
|
+
scheduleId: row.scheduleId,
|
|
473
|
+
scheduleName: row.scheduleName,
|
|
474
|
+
scheduleEnabled: row.scheduleEnabled,
|
|
475
|
+
};
|
|
476
|
+
if (row.basis === "measured") {
|
|
477
|
+
return {
|
|
478
|
+
...ref,
|
|
479
|
+
kind: row.kind,
|
|
480
|
+
name: row.name,
|
|
481
|
+
basis: row.basis,
|
|
482
|
+
runs: row.runs,
|
|
483
|
+
actualUsd: round2(row.actualUsd),
|
|
484
|
+
actualHours: round2(row.actualHours),
|
|
485
|
+
savingUsd: null,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
return { ...toRow(row), ...ref, scope: "target-job" as const };
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function toTotals(t: SavingsTotals) {
|
|
492
|
+
return {
|
|
493
|
+
...t,
|
|
494
|
+
// A component's share of a child's runs is fractional below the first level.
|
|
495
|
+
runs: Math.round(t.runs),
|
|
496
|
+
substitutedRuns: Math.round(t.substitutedRuns),
|
|
497
|
+
enabledOnlyRuns: Math.round(t.enabledOnlyRuns),
|
|
498
|
+
measuredUsd: round2(t.measuredUsd),
|
|
499
|
+
estimatedLlmUsd: round2(t.estimatedLlmUsd),
|
|
500
|
+
actualUsd: round2(t.actualUsd),
|
|
501
|
+
agentOnlyUsd: roundBand(t.agentOnlyUsd),
|
|
502
|
+
savingUsd: roundBand(t.savingUsd),
|
|
503
|
+
actualHours: round2(t.actualHours),
|
|
504
|
+
hoursSaved: roundBand(t.hoursSaved),
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function roundKind(k: FleetKindTotals): FleetKindTotals {
|
|
509
|
+
return { ...k, savingUsd: round2(k.savingUsd), hoursSaved: round2(k.hoursSaved) };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function notFound(
|
|
513
|
+
res: ServerResponse,
|
|
514
|
+
what: "Workflow" | "Script" | "Schedule" = "Workflow",
|
|
515
|
+
): true {
|
|
516
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
517
|
+
res.end(JSON.stringify({ error: `${what} not found` }));
|
|
518
|
+
return true;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* One script. No on-request refresh: the hourly bucket is served.
|
|
523
|
+
* shortcut: scripts skip the workflow page's live refresh of today's bucket
|
|
524
|
+
* (an agent-invoked script can run thousands of times a day and its effect
|
|
525
|
+
* probe is a LIKE scan); add one if a detail page needs minute-fresh numbers.
|
|
526
|
+
*/
|
|
527
|
+
async function readScript(
|
|
528
|
+
scriptName: string,
|
|
529
|
+
days: number,
|
|
530
|
+
tier: (typeof SAVINGS_TIERS)[number],
|
|
531
|
+
curve: CurveSet,
|
|
532
|
+
) {
|
|
533
|
+
if (!(await isKnownScriptName(scriptName))) return null;
|
|
534
|
+
return readScriptSavings({
|
|
535
|
+
days,
|
|
536
|
+
tier,
|
|
537
|
+
now: Date.now(),
|
|
538
|
+
scriptName,
|
|
539
|
+
sql: savingsRequestSql,
|
|
540
|
+
curve,
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function badTarget(res: ServerResponse, message: string): true {
|
|
545
|
+
json(res, { error: message }, 400);
|
|
546
|
+
return true;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** After a refresh scanned the day, later reads within this long reuse it. */
|
|
550
|
+
export const REFRESH_TTL_MS = 60_000;
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* Refresh state per workflow and UTC day. Concurrent reads share the refresh in
|
|
554
|
+
* flight. Once one has scanned the day (computed, refused as too many runs, or
|
|
555
|
+
* stopped by a busy database), reads skip the refresh for REFRESH_TTL_MS, so a
|
|
556
|
+
* burst or a high-volume workflow scans at most once a minute. A refresh that
|
|
557
|
+
* found no newer run did no scan and is not held.
|
|
558
|
+
*/
|
|
559
|
+
const inFlight = new Map<string, Promise<void>>();
|
|
560
|
+
/** When a refresh last scanned the day, per workflow and UTC day. */
|
|
561
|
+
const scannedAt = new Map<string, number>();
|
|
562
|
+
|
|
563
|
+
/** Test hook: forget the refresh state and the held component trees. */
|
|
564
|
+
export function resetSavingsRefreshCache(): void {
|
|
565
|
+
inFlight.clear();
|
|
566
|
+
scannedAt.clear();
|
|
567
|
+
heldTrees.clear();
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Component trees per workflow, window and tier, keyed also by the own row's
|
|
572
|
+
* rollup time, so a refreshed own row gets a fresh tree. Concurrent reads share
|
|
573
|
+
* the read in flight, and a tree is reused for REFRESH_TTL_MS: the tree reads
|
|
574
|
+
* the fleet's rollup rows, so a burst reads them once a minute at most.
|
|
575
|
+
*/
|
|
576
|
+
const heldTrees = new Map<string, { at: number; tree: Promise<WorkflowComponentsRead> }>();
|
|
577
|
+
const MAX_HELD_TREES = 200;
|
|
578
|
+
|
|
579
|
+
function componentsOf(
|
|
580
|
+
own: WorkflowSavingsRow,
|
|
581
|
+
days: number,
|
|
582
|
+
tier: (typeof SAVINGS_TIERS)[number],
|
|
583
|
+
computedAt: string | null,
|
|
584
|
+
calibration: Calibration,
|
|
585
|
+
): Promise<WorkflowComponentsRead> {
|
|
586
|
+
const now = Date.now();
|
|
587
|
+
for (const [k, h] of heldTrees) if (now - h.at >= REFRESH_TTL_MS) heldTrees.delete(k);
|
|
588
|
+
const key = [
|
|
589
|
+
own.workflowId,
|
|
590
|
+
days,
|
|
591
|
+
tier,
|
|
592
|
+
computedAt ?? "",
|
|
593
|
+
calibration.source,
|
|
594
|
+
calibration.calibratedAt,
|
|
595
|
+
calibration.model,
|
|
596
|
+
].join("\u0000");
|
|
597
|
+
const held = heldTrees.get(key);
|
|
598
|
+
if (held) return held.tree;
|
|
599
|
+
const tree = readWorkflowComponents({
|
|
600
|
+
days,
|
|
601
|
+
tier,
|
|
602
|
+
now,
|
|
603
|
+
workflowId: own.workflowId,
|
|
604
|
+
own,
|
|
605
|
+
curve: calibration.curve,
|
|
606
|
+
});
|
|
607
|
+
// A failed read is not held: the next request reads again.
|
|
608
|
+
tree.catch(() => {
|
|
609
|
+
// Only this read's own entry: an expired one may already be replaced.
|
|
610
|
+
if (heldTrees.get(key)?.tree === tree) heldTrees.delete(key);
|
|
611
|
+
});
|
|
612
|
+
if (heldTrees.size >= MAX_HELD_TREES) {
|
|
613
|
+
const oldest = heldTrees.keys().next().value;
|
|
614
|
+
if (oldest !== undefined) heldTrees.delete(oldest);
|
|
615
|
+
}
|
|
616
|
+
heldTrees.set(key, { at: now, tree });
|
|
617
|
+
return tree;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function refreshToday(
|
|
621
|
+
workflow: Parameters<typeof refreshWorkflowToday>[0],
|
|
622
|
+
now: number,
|
|
623
|
+
): Promise<void> {
|
|
624
|
+
const key = `${workflow.id}:${utcDay(now)}`;
|
|
625
|
+
const running = inFlight.get(key);
|
|
626
|
+
if (running) return running;
|
|
627
|
+
const at = scannedAt.get(key);
|
|
628
|
+
if (at !== undefined && now - at < REFRESH_TTL_MS) return Promise.resolve();
|
|
629
|
+
for (const [k, t] of scannedAt) if (now - t >= REFRESH_TTL_MS) scannedAt.delete(k);
|
|
630
|
+
const done = refreshWorkflowToday(workflow, savingsRequestSql, now)
|
|
631
|
+
.then(
|
|
632
|
+
(outcome) => {
|
|
633
|
+
if (outcome !== "skipped") scannedAt.set(key, Date.now());
|
|
634
|
+
},
|
|
635
|
+
(err) => {
|
|
636
|
+
if (!(err instanceof DbQueryConcurrencyCapError || err instanceof DbQueryTimeoutError))
|
|
637
|
+
throw err;
|
|
638
|
+
scannedAt.set(key, Date.now());
|
|
639
|
+
},
|
|
640
|
+
)
|
|
641
|
+
.finally(() => inFlight.delete(key));
|
|
642
|
+
inFlight.set(key, done);
|
|
643
|
+
return done;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* One workflow: bring today's bucket up to date first when it has a run newer
|
|
648
|
+
* than the last rollup. Best effort: on a busy database the hourly bucket is served.
|
|
649
|
+
*/
|
|
650
|
+
async function readOne(
|
|
651
|
+
workflowId: string,
|
|
652
|
+
days: number,
|
|
653
|
+
tier: (typeof SAVINGS_TIERS)[number],
|
|
654
|
+
curve: CurveSet,
|
|
655
|
+
) {
|
|
656
|
+
const workflow = await getWorkflow(workflowId);
|
|
657
|
+
if (!workflow) return null;
|
|
658
|
+
const now = Date.now();
|
|
659
|
+
await refreshToday(workflow, now);
|
|
660
|
+
return readWorkflowSavings({ days, tier, now, workflowId, sql: savingsRequestSql, curve });
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function meta(
|
|
664
|
+
read: {
|
|
665
|
+
window: { start: string; end: string; days: number };
|
|
666
|
+
computedAt: string | null;
|
|
667
|
+
boundaryEstimated: boolean;
|
|
668
|
+
},
|
|
669
|
+
tier: (typeof SAVINGS_TIERS)[number],
|
|
670
|
+
calibration: Calibration,
|
|
671
|
+
valid: { complete: boolean; hasRows: boolean; targetMissing?: boolean },
|
|
672
|
+
) {
|
|
673
|
+
return {
|
|
674
|
+
window: read.window,
|
|
675
|
+
tier,
|
|
676
|
+
calibrationModel: calibration.model,
|
|
677
|
+
calibratedAt: calibration.calibratedAt,
|
|
678
|
+
calibrationSource: calibration.source,
|
|
679
|
+
computedAt: read.computedAt,
|
|
680
|
+
valid: valid.complete && valid.hasRows,
|
|
681
|
+
reason: !valid.complete
|
|
682
|
+
? ("not-computed" as const)
|
|
683
|
+
: valid.hasRows
|
|
684
|
+
? null
|
|
685
|
+
: valid.targetMissing
|
|
686
|
+
? ("target-missing" as const)
|
|
687
|
+
: ("no-runs" as const),
|
|
688
|
+
boundaryEstimated: read.boundaryEstimated,
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
export async function handleSavings(
|
|
693
|
+
req: IncomingMessage,
|
|
694
|
+
res: ServerResponse,
|
|
695
|
+
pathSegments: string[],
|
|
696
|
+
queryParams: URLSearchParams,
|
|
697
|
+
): Promise<boolean> {
|
|
698
|
+
if (savingsDailyRoute.match(req.method, pathSegments)) {
|
|
699
|
+
const parsed = await savingsDailyRoute.parse(req, res, pathSegments, queryParams);
|
|
700
|
+
if (!parsed) return true;
|
|
701
|
+
const { workflowId, scriptName, days, tier } = parsed.query;
|
|
702
|
+
if (workflowId && scriptName) return badTarget(res, "Pass workflowId or scriptName, not both");
|
|
703
|
+
const calibration = await activeCalibration(Date.now());
|
|
704
|
+
const read = workflowId
|
|
705
|
+
? await readOne(workflowId, days, tier, calibration.curve)
|
|
706
|
+
: scriptName
|
|
707
|
+
? await readScript(scriptName, days, tier, calibration.curve)
|
|
708
|
+
: await readFleetSavings({
|
|
709
|
+
days,
|
|
710
|
+
tier,
|
|
711
|
+
now: Date.now(),
|
|
712
|
+
sql: savingsRequestSql,
|
|
713
|
+
curve: calibration.curve,
|
|
714
|
+
});
|
|
715
|
+
if (!read) return notFound(res, workflowId ? "Workflow" : "Script");
|
|
716
|
+
const hasRows = read.total !== null;
|
|
717
|
+
const points = read.complete && hasRows ? read.points : [];
|
|
718
|
+
const saving = roundToTotal(points.map((p) => p.savingUsd));
|
|
719
|
+
const actual = roundToTotal(points.map((p) => p.actualUsd));
|
|
720
|
+
const measured = roundToTotal(points.map((p) => p.measuredUsd));
|
|
721
|
+
const estimated = roundToTotal(points.map((p) => p.estimatedLlmUsd));
|
|
722
|
+
savingsDailyRoute.respond(res, 200, {
|
|
723
|
+
...meta(read, tier, calibration, { complete: read.complete, hasRows }),
|
|
724
|
+
points: points.map((p, i) => ({
|
|
725
|
+
day: p.day,
|
|
726
|
+
savingUsd: saving[i] as number,
|
|
727
|
+
actualUsd: actual[i] as number,
|
|
728
|
+
measuredUsd: measured[i] as number,
|
|
729
|
+
estimatedLlmUsd: estimated[i] as number,
|
|
730
|
+
})),
|
|
731
|
+
});
|
|
732
|
+
return true;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
if (savingsSummaryRoute.match(req.method, pathSegments)) {
|
|
736
|
+
const parsed = await savingsSummaryRoute.parse(req, res, pathSegments, queryParams);
|
|
737
|
+
if (!parsed) return true;
|
|
738
|
+
const { days, tier } = parsed.query;
|
|
739
|
+
const now = Date.now();
|
|
740
|
+
// The spend sum needs only the window: it waits for the connection alongside the fleet read.
|
|
741
|
+
const llm = readFleetLlmUsd(savingsWindow(days, now));
|
|
742
|
+
// Settled here so a fleet read that throws leaves no unhandled rejection behind.
|
|
743
|
+
llm.catch(() => {});
|
|
744
|
+
const calibration = await activeCalibration(now);
|
|
745
|
+
const read = await readFleetSavings({
|
|
746
|
+
days,
|
|
747
|
+
tier,
|
|
748
|
+
now,
|
|
749
|
+
sql: savingsRequestSql,
|
|
750
|
+
curve: calibration.curve,
|
|
751
|
+
});
|
|
752
|
+
const fleetLlmUsd = await llm;
|
|
753
|
+
const total = read.complete ? read.total : null;
|
|
754
|
+
savingsSummaryRoute.respond(res, 200, {
|
|
755
|
+
...meta(read, tier, calibration, { complete: read.complete, hasRows: read.total !== null }),
|
|
756
|
+
total: total ? toTotals(total) : null,
|
|
757
|
+
byKind: total
|
|
758
|
+
? {
|
|
759
|
+
workflows: roundKind(read.byKind.workflows),
|
|
760
|
+
scheduledScripts: roundKind(read.byKind.scheduledScripts),
|
|
761
|
+
agentInvokedScripts: roundKind(read.byKind.agentInvokedScripts),
|
|
762
|
+
}
|
|
763
|
+
: null,
|
|
764
|
+
fleetLlmUsd: round2(fleetLlmUsd),
|
|
765
|
+
selfOptimizationRatio:
|
|
766
|
+
total && fleetLlmUsd > 0 ? (fleetLlmUsd + total.savingUsd.p50) / fleetLlmUsd : null,
|
|
767
|
+
excluded: total ? { enabledOnlyRuns: total.enabledOnlyRuns } : null,
|
|
768
|
+
assumptions: savingsAssumptions(tier),
|
|
769
|
+
});
|
|
770
|
+
return true;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
if (!savingsJobsRoute.match(req.method, pathSegments)) return false;
|
|
774
|
+
const parsed = await savingsJobsRoute.parse(req, res, pathSegments, queryParams);
|
|
775
|
+
if (!parsed) return true;
|
|
776
|
+
const { workflowId, scriptName, scheduleId, kind, days, tier, components } = parsed.query;
|
|
777
|
+
if ([workflowId, scriptName, scheduleId, kind].filter(Boolean).length !== 1) {
|
|
778
|
+
return badTarget(
|
|
779
|
+
res,
|
|
780
|
+
"Pass one of workflowId, scriptName, scheduleId, kind=workflow, kind=script or kind=schedule",
|
|
781
|
+
);
|
|
782
|
+
}
|
|
783
|
+
if (components && !workflowId) {
|
|
784
|
+
return badTarget(res, "components=true needs workflowId; lists count own runs only");
|
|
785
|
+
}
|
|
786
|
+
const calibration = await activeCalibration(Date.now());
|
|
787
|
+
const now = Date.now();
|
|
788
|
+
if (scheduleId || kind === "schedule") {
|
|
789
|
+
const read = await readScheduleSavings({
|
|
790
|
+
days,
|
|
791
|
+
tier,
|
|
792
|
+
now,
|
|
793
|
+
scheduleId,
|
|
794
|
+
sql: savingsRequestSql,
|
|
795
|
+
curve: calibration.curve,
|
|
796
|
+
});
|
|
797
|
+
if (!read) return notFound(res, "Schedule");
|
|
798
|
+
// Measured rows are read live, so they show even while the modelled rollup is incomplete.
|
|
799
|
+
const rows = read.complete ? read.rows : read.rows.filter((r) => r.basis === "measured");
|
|
800
|
+
savingsJobsRoute.respond(res, 200, {
|
|
801
|
+
...meta(read, tier, calibration, {
|
|
802
|
+
complete: read.complete || rows.length > 0,
|
|
803
|
+
hasRows: rows.length > 0,
|
|
804
|
+
targetMissing: read.targetMissing,
|
|
805
|
+
}),
|
|
806
|
+
rows: rows.map(toScheduleRow),
|
|
807
|
+
total: null,
|
|
808
|
+
});
|
|
809
|
+
return true;
|
|
810
|
+
}
|
|
811
|
+
const read: (Omit<WorkflowSavingsRead, "rows"> & { rows: ReadRow[] }) | null = workflowId
|
|
812
|
+
? await readOne(workflowId, days, tier, calibration.curve)
|
|
813
|
+
: scriptName
|
|
814
|
+
? await readScript(scriptName, days, tier, calibration.curve)
|
|
815
|
+
: kind === "script"
|
|
816
|
+
? await readScriptSavings({
|
|
817
|
+
days,
|
|
818
|
+
tier,
|
|
819
|
+
now,
|
|
820
|
+
sql: savingsRequestSql,
|
|
821
|
+
curve: calibration.curve,
|
|
822
|
+
})
|
|
823
|
+
: await readWorkflowSavings({
|
|
824
|
+
days,
|
|
825
|
+
tier,
|
|
826
|
+
now,
|
|
827
|
+
sql: savingsRequestSql,
|
|
828
|
+
curve: calibration.curve,
|
|
829
|
+
});
|
|
830
|
+
if (!read) return notFound(res, scriptName ? "Script" : "Workflow");
|
|
831
|
+
const show = read.complete;
|
|
832
|
+
const own = show && workflowId ? read.rows[0] : undefined;
|
|
833
|
+
const tree =
|
|
834
|
+
components && own && "workflowId" in own
|
|
835
|
+
? await componentsOf(own, days, tier, read.computedAt, calibration)
|
|
836
|
+
: null;
|
|
837
|
+
savingsJobsRoute.respond(res, 200, {
|
|
838
|
+
...meta(read, tier, calibration, { complete: read.complete, hasRows: read.rows.length > 0 }),
|
|
839
|
+
rows: show ? read.rows.map(toRow) : [],
|
|
840
|
+
total: show && read.total ? toTotals(read.total) : null,
|
|
841
|
+
...(components
|
|
842
|
+
? {
|
|
843
|
+
components: tree ? tree.components.map(toComponent) : [],
|
|
844
|
+
withComponents: tree?.withComponents ? toTotals(tree.withComponents) : null,
|
|
845
|
+
}
|
|
846
|
+
: {}),
|
|
847
|
+
});
|
|
848
|
+
return true;
|
|
849
|
+
}
|