@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,468 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Re-derive the automation-savings session curve from this deployment's own
|
|
3
|
+
* `session_costs`, and optionally store it so the savings endpoints use it
|
|
4
|
+
* instead of the constants shipped in `src/be/savings/model.ts`.
|
|
5
|
+
*
|
|
6
|
+
* Served by `POST /api/savings/calibration` (`src/http/savings-calibration.ts`), which
|
|
7
|
+
* also owns the deadline, the one-run-at-a-time lock and the config write. Delete the
|
|
8
|
+
* global `SAVINGS_CURVE_CALIBRATION` row to go back to the shipped curve.
|
|
9
|
+
*
|
|
10
|
+
* Method, rebuilt from the v7 calibration notes (research/cost/2026-11-05); it reproduces
|
|
11
|
+
* the shipped curve to about 1% on session-weighted average, not point for point:
|
|
12
|
+
* - cost(t, tier): 10%-trimmed mean, over this window's opus 5.5 sessions of
|
|
13
|
+
* exactly t turns, of the session's opus tokens repriced at the tier's list
|
|
14
|
+
* prices plus the stored cost of its other models (sub-agents), t = 1..61.
|
|
15
|
+
* The curve is then smoothed with a +-2 turn local linear fit and made
|
|
16
|
+
* non-decreasing.
|
|
17
|
+
* - hrs(t, tier): the same for agent-active hours (durationMs) on opus,
|
|
18
|
+
* times the tier's speed against opus (median ms per turn).
|
|
19
|
+
* - Coverage: a turn count with fewer than MIN_SESSIONS_PER_TURN sessions is unsupported.
|
|
20
|
+
* Gaps between supported turn counts are interpolated. The curve is refused unless the
|
|
21
|
+
* supported counts reach MIN_LOW_TURN at the bottom and MIN_HIGH_TURN at the top. Past the
|
|
22
|
+
* outermost supported count the shipped curve's shape is used, scaled to meet that count.
|
|
23
|
+
*/
|
|
24
|
+
import type { SavingsSql } from "./compute";
|
|
25
|
+
import {
|
|
26
|
+
CALIBRATION_MODEL,
|
|
27
|
+
CURVE,
|
|
28
|
+
type CurveSet,
|
|
29
|
+
SAVINGS_TIERS,
|
|
30
|
+
type SavingsTier,
|
|
31
|
+
TAU_MAX,
|
|
32
|
+
} from "./model";
|
|
33
|
+
|
|
34
|
+
/** The model each tier bills at. */
|
|
35
|
+
export const TIER_MODEL: Record<SavingsTier, string> = {
|
|
36
|
+
smol: "claude-haiku-5-5",
|
|
37
|
+
regular: "claude-sonnet-5-5",
|
|
38
|
+
smart: CALIBRATION_MODEL,
|
|
39
|
+
ultra: "claude-fable-5-1",
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** Hours per turn against opus, used when a tier has too few sessions to measure (v7 values). */
|
|
43
|
+
export const SPEED_FALLBACK: Record<SavingsTier, number> = {
|
|
44
|
+
smol: 1.54,
|
|
45
|
+
regular: 1.29,
|
|
46
|
+
smart: 1,
|
|
47
|
+
ultra: 1,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const TRIM = 0.1;
|
|
51
|
+
const SMOOTH_HALF_WIDTH = 2;
|
|
52
|
+
/** Fewer sessions than this at one turn count: the point is filled from its neighbours. */
|
|
53
|
+
const MIN_SESSIONS_PER_TURN = 5;
|
|
54
|
+
/** Refuse a curve whose lowest supported turn count is above this: short jobs are what the model prices most. */
|
|
55
|
+
export const MIN_LOW_TURN = 3;
|
|
56
|
+
/** Refuse a curve whose highest supported turn count is below this (tau 20 is 65 ops per run). */
|
|
57
|
+
export const MIN_HIGH_TURN = 20;
|
|
58
|
+
/** Refuse a curve built on fewer supported turn counts than this (of 60). */
|
|
59
|
+
export const MIN_SUPPORTED_TURNS = 15;
|
|
60
|
+
/** Fewer opus sessions than this in the window: refuse to calibrate. */
|
|
61
|
+
export const MIN_SESSIONS = 300;
|
|
62
|
+
/** Fewer sessions than this for a tier model: use SPEED_FALLBACK. */
|
|
63
|
+
const MIN_SPEED_SESSIONS = 30;
|
|
64
|
+
/** A curve whose mean cost is further than this factor from the shipped one is never applied. */
|
|
65
|
+
export const SANITY_FACTOR = 3;
|
|
66
|
+
/** Rows read per query; the read pages by keyset so no query is unbounded. */
|
|
67
|
+
const PAGE = 1000;
|
|
68
|
+
/** Refuse a window with more sessions than this: one run must stay inside the API's memory. */
|
|
69
|
+
export const MAX_SESSIONS_READ = 200_000;
|
|
70
|
+
|
|
71
|
+
/** The data cannot support a curve; the message is the reason shown to the caller. */
|
|
72
|
+
export class CalibrationRefusal extends Error {}
|
|
73
|
+
|
|
74
|
+
/** `CurveSet` with plain arrays: what a derivation produces and the API serializes. */
|
|
75
|
+
export type DerivedCurveSet = Record<SavingsTier, { usd: number[]; hrs: number[] }>;
|
|
76
|
+
|
|
77
|
+
export type OpusSession = {
|
|
78
|
+
turns: number;
|
|
79
|
+
durationMs: number;
|
|
80
|
+
inputTokens: number;
|
|
81
|
+
outputTokens: number;
|
|
82
|
+
cacheReadTokens: number;
|
|
83
|
+
cacheWriteTokens: number;
|
|
84
|
+
/** The cost the harness stored for the opus tokens, for the repricing control. */
|
|
85
|
+
costUsd: number;
|
|
86
|
+
/** Stored cost of the session's other models (sub-agents), kept as is at every tier. */
|
|
87
|
+
otherUsd: number;
|
|
88
|
+
};
|
|
89
|
+
export type TierPrices = Record<"input" | "output" | "cached_input" | "cache_write_1h", number>; // USD per million tokens
|
|
90
|
+
export type TurnDuration = { turns: number; durationMs: number };
|
|
91
|
+
|
|
92
|
+
export type DeriveInput = {
|
|
93
|
+
opus: OpusSession[];
|
|
94
|
+
prices: Record<SavingsTier, TierPrices>;
|
|
95
|
+
/** ms-per-turn samples of each non-opus tier model's own sessions. */
|
|
96
|
+
tierTurns: Partial<Record<SavingsTier, TurnDuration[]>>;
|
|
97
|
+
end: Date;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export type DerivedCalibration = {
|
|
101
|
+
calibratedAt: string;
|
|
102
|
+
model: string;
|
|
103
|
+
curve: DerivedCurveSet;
|
|
104
|
+
sessions: number;
|
|
105
|
+
usable: OpusSession[];
|
|
106
|
+
speed: Record<SavingsTier, number>;
|
|
107
|
+
/** Share of sessions whose repriced opus cost is within 1% of the stored cost. */
|
|
108
|
+
repriceMatch: number;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
export function median(values: number[]): number {
|
|
112
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
113
|
+
return sorted[Math.floor(sorted.length / 2)] as number;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function trimmedMean(values: number[], trim = TRIM): number {
|
|
117
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
118
|
+
const cut = Math.floor(sorted.length * trim);
|
|
119
|
+
const kept = sorted.slice(cut, sorted.length - cut);
|
|
120
|
+
return kept.reduce((s, v) => s + v, 0) / kept.length;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Local linear fit over the defined points within `half` turns, evaluated at each point.
|
|
125
|
+
* Unlike a moving average it does not pull the end points toward their inner neighbours.
|
|
126
|
+
* Undefined points stay undefined.
|
|
127
|
+
*/
|
|
128
|
+
function smooth(series: (number | undefined)[], half: number): (number | undefined)[] {
|
|
129
|
+
return series.map((v, i) => {
|
|
130
|
+
if (v === undefined) return undefined;
|
|
131
|
+
const pts: [number, number][] = [];
|
|
132
|
+
for (let j = Math.max(0, i - half); j <= Math.min(series.length - 1, i + half); j++) {
|
|
133
|
+
const y = series[j];
|
|
134
|
+
if (y !== undefined) pts.push([j, y]);
|
|
135
|
+
}
|
|
136
|
+
const n = pts.length;
|
|
137
|
+
const mx = pts.reduce((s, p) => s + p[0], 0) / n;
|
|
138
|
+
const my = pts.reduce((s, p) => s + p[1], 0) / n;
|
|
139
|
+
const sxx = pts.reduce((s, p) => s + (p[0] - mx) ** 2, 0);
|
|
140
|
+
if (sxx === 0) return my;
|
|
141
|
+
const slope = pts.reduce((s, p) => s + (p[0] - mx) * (p[1] - my), 0) / sxx;
|
|
142
|
+
return my + slope * (i - mx);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Fill the gaps, then make the series non-decreasing. Between two known points the fill is
|
|
148
|
+
* linear. Past the first or last known point it follows `reference` (the shipped curve) scaled
|
|
149
|
+
* to meet that point, because a flat extension would price every turn count beyond the data
|
|
150
|
+
* at the edge's level.
|
|
151
|
+
*/
|
|
152
|
+
function fillMonotone(series: (number | undefined)[], reference: readonly number[]): number[] {
|
|
153
|
+
const known = series.flatMap((v, i) => (v === undefined ? [] : [i]));
|
|
154
|
+
const first = known[0] as number;
|
|
155
|
+
const last = known[known.length - 1] as number;
|
|
156
|
+
const scaled = (i: number, anchor: number) =>
|
|
157
|
+
(series[anchor] as number) * ((reference[i] as number) / (reference[anchor] as number));
|
|
158
|
+
let floor = 0;
|
|
159
|
+
return series.map((_, i) => {
|
|
160
|
+
let v: number;
|
|
161
|
+
if (i < first) v = scaled(i, first);
|
|
162
|
+
else if (i > last) v = scaled(i, last);
|
|
163
|
+
else {
|
|
164
|
+
const lo = known.filter((k) => k <= i).at(-1) as number;
|
|
165
|
+
const hi = known.find((k) => k >= i) as number;
|
|
166
|
+
const a = series[lo] as number;
|
|
167
|
+
const b = series[hi] as number;
|
|
168
|
+
v = lo === hi ? a : a + ((b - a) * (i - lo)) / (hi - lo);
|
|
169
|
+
}
|
|
170
|
+
floor = Math.max(floor, v);
|
|
171
|
+
return floor;
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* One value per turn count 1..TAU_MAX: a trimmed mean of `value`, smoothed and non-decreasing.
|
|
177
|
+
* `reference` is the shipped series of the same quantity, used past the supported turn counts.
|
|
178
|
+
*/
|
|
179
|
+
function curveOf(
|
|
180
|
+
sessions: OpusSession[],
|
|
181
|
+
value: (s: OpusSession) => number,
|
|
182
|
+
reference: readonly number[],
|
|
183
|
+
): number[] {
|
|
184
|
+
const byTurns = new Map<number, number[]>();
|
|
185
|
+
for (const s of sessions) {
|
|
186
|
+
if (s.turns < 1 || s.turns > TAU_MAX) continue;
|
|
187
|
+
const at = byTurns.get(s.turns);
|
|
188
|
+
if (at) at.push(value(s));
|
|
189
|
+
else byTurns.set(s.turns, [value(s)]);
|
|
190
|
+
}
|
|
191
|
+
const raw = Array.from({ length: TAU_MAX }, (_, i) => {
|
|
192
|
+
const at = byTurns.get(i + 1);
|
|
193
|
+
return at && at.length >= MIN_SESSIONS_PER_TURN ? trimmedMean(at) : undefined;
|
|
194
|
+
});
|
|
195
|
+
// shortcut: turn 1 is never read (tau >= T0 = 2), so it takes the value of turn 2 instead of a noisy estimate.
|
|
196
|
+
raw[0] = undefined;
|
|
197
|
+
const supported = raw.flatMap((v, i) => (v === undefined ? [] : [i + 1]));
|
|
198
|
+
const lo = supported[0];
|
|
199
|
+
const hi = supported[supported.length - 1];
|
|
200
|
+
if (
|
|
201
|
+
lo === undefined ||
|
|
202
|
+
hi === undefined ||
|
|
203
|
+
lo > MIN_LOW_TURN ||
|
|
204
|
+
hi < MIN_HIGH_TURN ||
|
|
205
|
+
supported.length < MIN_SUPPORTED_TURNS
|
|
206
|
+
) {
|
|
207
|
+
throw new CalibrationRefusal(
|
|
208
|
+
`turn coverage too thin: ${supported.length} of ${TAU_MAX - 1} turn counts have ${MIN_SESSIONS_PER_TURN}+ sessions` +
|
|
209
|
+
`${lo === undefined ? "" : ` (turns ${lo}..${hi})`}; need at least ${MIN_SUPPORTED_TURNS}, reaching turn ${MIN_LOW_TURN} or lower and turn ${MIN_HIGH_TURN} or higher`,
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
const smoothed = smooth(raw.slice(1), SMOOTH_HALF_WIDTH);
|
|
213
|
+
const filled = fillMonotone(smoothed, reference.slice(1));
|
|
214
|
+
return [filled[0] as number, ...filled];
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const round = (x: number, digits: number) => Number(x.toFixed(digits));
|
|
218
|
+
|
|
219
|
+
export function deriveCurves(input: DeriveInput): DerivedCalibration {
|
|
220
|
+
const { opus, prices, tierTurns, end } = input;
|
|
221
|
+
const usable = opus.filter((s) => s.turns >= 1 && s.turns <= TAU_MAX);
|
|
222
|
+
if (usable.length < MIN_SESSIONS) {
|
|
223
|
+
throw new CalibrationRefusal(
|
|
224
|
+
`only ${usable.length} opus sessions of 1..${TAU_MAX} turns in the window; need ${MIN_SESSIONS}`,
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
const opusTokensCost = (p: TierPrices) => (s: OpusSession) =>
|
|
228
|
+
(s.inputTokens * p.input +
|
|
229
|
+
s.outputTokens * p.output +
|
|
230
|
+
s.cacheReadTokens * p.cached_input +
|
|
231
|
+
s.cacheWriteTokens * p.cache_write_1h) /
|
|
232
|
+
1e6;
|
|
233
|
+
const price = (p: TierPrices) => (s: OpusSession) => opusTokensCost(p)(s) + s.otherUsd;
|
|
234
|
+
// The harness bills every cache write at the 1h rate, so repricing at opus prices must give back the stored cost.
|
|
235
|
+
const opusCost = opusTokensCost(prices.smart);
|
|
236
|
+
const repriceMatch =
|
|
237
|
+
usable.filter((s) => Math.abs(opusCost(s) - s.costUsd) <= 0.01 * s.costUsd).length /
|
|
238
|
+
usable.length;
|
|
239
|
+
|
|
240
|
+
const opusHrs = curveOf(usable, (s) => s.durationMs / 3.6e6, CURVE.smart.hrs);
|
|
241
|
+
const perTurn = (rows: TurnDuration[]) =>
|
|
242
|
+
median(
|
|
243
|
+
rows.filter((r) => r.turns >= 3 && r.turns <= TAU_MAX).map((r) => r.durationMs / r.turns),
|
|
244
|
+
);
|
|
245
|
+
const opusPerTurn = perTurn(usable.map((s) => ({ turns: s.turns, durationMs: s.durationMs })));
|
|
246
|
+
const speed = Object.fromEntries(
|
|
247
|
+
SAVINGS_TIERS.map((tier) => {
|
|
248
|
+
const rows = (tierTurns[tier] ?? []).filter((r) => r.turns >= 3 && r.turns <= TAU_MAX);
|
|
249
|
+
if (tier === "smart") return [tier, 1];
|
|
250
|
+
return [
|
|
251
|
+
tier,
|
|
252
|
+
rows.length >= MIN_SPEED_SESSIONS
|
|
253
|
+
? round(perTurn(rows) / opusPerTurn, 3)
|
|
254
|
+
: SPEED_FALLBACK[tier],
|
|
255
|
+
];
|
|
256
|
+
}),
|
|
257
|
+
) as Record<SavingsTier, number>;
|
|
258
|
+
|
|
259
|
+
const curve = Object.fromEntries(
|
|
260
|
+
SAVINGS_TIERS.map((tier) => [
|
|
261
|
+
tier,
|
|
262
|
+
{
|
|
263
|
+
usd: curveOf(usable, price(prices[tier]), CURVE[tier].usd).map((v) => round(v, 4)),
|
|
264
|
+
hrs: opusHrs.map((v) => round(v * speed[tier], 5)),
|
|
265
|
+
},
|
|
266
|
+
]),
|
|
267
|
+
) as DerivedCurveSet;
|
|
268
|
+
return {
|
|
269
|
+
calibratedAt: end.toISOString().slice(0, 10),
|
|
270
|
+
model: CALIBRATION_MODEL,
|
|
271
|
+
curve,
|
|
272
|
+
sessions: usable.length,
|
|
273
|
+
usable,
|
|
274
|
+
speed,
|
|
275
|
+
repriceMatch,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Per-tier deviation of a curve from the shipped one over turns 2..TAU_MAX (turn 1 is never
|
|
281
|
+
* read). `weighted` is the session-weighted mean of derived over shipped: what the model
|
|
282
|
+
* would price on the fleet's own session lengths.
|
|
283
|
+
*/
|
|
284
|
+
export function compareToShipped(curve: CurveSet, sessionsPerTurn: number[]) {
|
|
285
|
+
return SAVINGS_TIERS.flatMap((tier) =>
|
|
286
|
+
(["usd", "hrs"] as const).map((key) => {
|
|
287
|
+
const pairs = curve[tier][key]
|
|
288
|
+
.map((v, i) => ({ ratio: v / (CURVE[tier][key][i] as number), w: sessionsPerTurn[i] ?? 0 }))
|
|
289
|
+
.slice(1);
|
|
290
|
+
const dev = pairs.map((p) => Math.abs(p.ratio - 1)).sort((a, b) => a - b);
|
|
291
|
+
const w = pairs.reduce((s, p) => s + p.w, 0);
|
|
292
|
+
return {
|
|
293
|
+
tier,
|
|
294
|
+
key,
|
|
295
|
+
median: dev[Math.floor(dev.length / 2)] as number,
|
|
296
|
+
max: dev[dev.length - 1] as number,
|
|
297
|
+
over5pct: dev.filter((d) => d > 0.05).length,
|
|
298
|
+
points: dev.length,
|
|
299
|
+
weighted: pairs.reduce((s, p) => s + p.w * p.ratio, 0) / w,
|
|
300
|
+
};
|
|
301
|
+
}),
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ---- Reading the sessions ----------------------------------------------------------------
|
|
306
|
+
|
|
307
|
+
const num = (v: unknown) => Number(v) || 0;
|
|
308
|
+
|
|
309
|
+
/** Keyset-paged read of `sql`, which selects `id` and takes `id > ?` as its last parameter. */
|
|
310
|
+
async function pages<T extends { id: string }>(
|
|
311
|
+
sql: SavingsSql,
|
|
312
|
+
query: string,
|
|
313
|
+
params: (string | number)[],
|
|
314
|
+
): Promise<T[]> {
|
|
315
|
+
const out: T[] = [];
|
|
316
|
+
let after = "";
|
|
317
|
+
for (;;) {
|
|
318
|
+
const rows = await sql<T>(query, [...params, after]);
|
|
319
|
+
out.push(...rows);
|
|
320
|
+
if (out.length > MAX_SESSIONS_READ) {
|
|
321
|
+
throw new CalibrationRefusal(
|
|
322
|
+
`more than ${MAX_SESSIONS_READ} sessions in the window; use a shorter window (days)`,
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
if (rows.length < PAGE) return out;
|
|
326
|
+
after = (rows[rows.length - 1] as T).id;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export async function fetchInput(sql: SavingsSql, start: Date, end: Date): Promise<DeriveInput> {
|
|
331
|
+
const window = [start.toISOString(), end.toISOString()];
|
|
332
|
+
const opusRows = await pages<Record<string, unknown> & { id: string }>(
|
|
333
|
+
sql,
|
|
334
|
+
`SELECT s.id AS id, s.numTurns AS turns, s.durationMs AS durationMs,
|
|
335
|
+
json_extract(j.value,'$.inputTokens') AS inputTokens, json_extract(j.value,'$.outputTokens') AS outputTokens,
|
|
336
|
+
json_extract(j.value,'$.cacheReadTokens') AS cacheReadTokens, json_extract(j.value,'$.cacheWriteTokens') AS cacheWriteTokens,
|
|
337
|
+
json_extract(j.value,'$.costUsd') AS costUsd, s.totalCostUsd AS totalCostUsd
|
|
338
|
+
FROM session_costs s, json_each(CASE WHEN json_valid(s.modelBreakdown) THEN s.modelBreakdown ELSE '[]' END) j
|
|
339
|
+
WHERE s.model = ? AND json_extract(j.value,'$.model') = ? AND s.createdAt >= ? AND s.createdAt < ?
|
|
340
|
+
AND s.numTurns BETWEEN 1 AND ${TAU_MAX} AND s.id > ? ORDER BY s.id LIMIT ${PAGE}`,
|
|
341
|
+
[CALIBRATION_MODEL, CALIBRATION_MODEL, ...window],
|
|
342
|
+
);
|
|
343
|
+
const opus = opusRows.map((r) => ({
|
|
344
|
+
turns: num(r.turns),
|
|
345
|
+
durationMs: num(r.durationMs),
|
|
346
|
+
inputTokens: num(r.inputTokens),
|
|
347
|
+
outputTokens: num(r.outputTokens),
|
|
348
|
+
cacheReadTokens: num(r.cacheReadTokens),
|
|
349
|
+
cacheWriteTokens: num(r.cacheWriteTokens),
|
|
350
|
+
costUsd: num(r.costUsd),
|
|
351
|
+
otherUsd: Math.max(0, num(r.totalCostUsd) - num(r.costUsd)),
|
|
352
|
+
}));
|
|
353
|
+
|
|
354
|
+
const priceRows = await sql<{ model: string; token_class: string; price: number }>(
|
|
355
|
+
`SELECT model, token_class, price_per_million_usd AS price FROM pricing
|
|
356
|
+
WHERE provider = 'claude' AND model IN (${SAVINGS_TIERS.map(() => "?").join(",")}) AND effective_from <= ?
|
|
357
|
+
ORDER BY effective_from`,
|
|
358
|
+
[...SAVINGS_TIERS.map((t) => TIER_MODEL[t]), end.getTime()],
|
|
359
|
+
);
|
|
360
|
+
const latest = new Map<string, number>(); // later effective_from overwrites earlier
|
|
361
|
+
for (const r of priceRows) latest.set(`${r.model}|${r.token_class}`, num(r.price));
|
|
362
|
+
const prices = Object.fromEntries(
|
|
363
|
+
SAVINGS_TIERS.map((tier) => [
|
|
364
|
+
tier,
|
|
365
|
+
Object.fromEntries(
|
|
366
|
+
(["input", "output", "cached_input", "cache_write_1h"] as const).map((cls) => {
|
|
367
|
+
const p = latest.get(`${TIER_MODEL[tier]}|${cls}`);
|
|
368
|
+
if (p === undefined) {
|
|
369
|
+
throw new CalibrationRefusal(`no ${cls} price for ${TIER_MODEL[tier]}`);
|
|
370
|
+
}
|
|
371
|
+
return [cls, p];
|
|
372
|
+
}),
|
|
373
|
+
),
|
|
374
|
+
]),
|
|
375
|
+
) as Record<SavingsTier, TierPrices>;
|
|
376
|
+
|
|
377
|
+
const tierTurns: DeriveInput["tierTurns"] = {};
|
|
378
|
+
for (const tier of SAVINGS_TIERS) {
|
|
379
|
+
if (tier === "smart") continue;
|
|
380
|
+
const rows = await pages<{ id: string; turns: number; durationMs: number }>(
|
|
381
|
+
sql,
|
|
382
|
+
`SELECT id, numTurns AS turns, durationMs FROM session_costs
|
|
383
|
+
WHERE model = ? AND createdAt >= ? AND createdAt < ? AND numTurns BETWEEN 3 AND ${TAU_MAX} AND id > ? ORDER BY id LIMIT ${PAGE}`,
|
|
384
|
+
[TIER_MODEL[tier], ...window],
|
|
385
|
+
);
|
|
386
|
+
tierTurns[tier] = rows.map((r) => ({ turns: num(r.turns), durationMs: num(r.durationMs) }));
|
|
387
|
+
}
|
|
388
|
+
return { opus, prices, tierTurns, end };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// ---- The run -----------------------------------------------------------------------------
|
|
392
|
+
|
|
393
|
+
export type CalibrationGap = ReturnType<typeof compareToShipped>[number];
|
|
394
|
+
|
|
395
|
+
export type CalibrationRun = {
|
|
396
|
+
window: { start: string; end: string; days: number };
|
|
397
|
+
/** Opus sessions of 1..TAU_MAX turns used; 0 when the run was refused before counting. */
|
|
398
|
+
sessions: number;
|
|
399
|
+
/** Why the data cannot support a curve. When set, `calibration` is null. */
|
|
400
|
+
refusal: string | null;
|
|
401
|
+
/** The derived curve in the form the config row stores. */
|
|
402
|
+
calibration: StoredCalibration | null;
|
|
403
|
+
speed: Record<SavingsTier, number> | null;
|
|
404
|
+
repriceMatch: number | null;
|
|
405
|
+
/** Per tier and quantity, the derived curve against the shipped one. */
|
|
406
|
+
gaps: CalibrationGap[];
|
|
407
|
+
/** Derived smart-tier mean cost over the shipped one. */
|
|
408
|
+
meanRatio: number | null;
|
|
409
|
+
/** Why a derived curve must not be applied (mean cost beyond SANITY_FACTOR); null when it may be. */
|
|
410
|
+
applyBlocked: string | null;
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
export type StoredCalibration = {
|
|
414
|
+
calibratedAt: string;
|
|
415
|
+
model: string;
|
|
416
|
+
curve: DerivedCurveSet;
|
|
417
|
+
window: { start: string; end: string; sessions: number };
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
/** Read the window's sessions through `sql` and derive the curve. Never writes. */
|
|
421
|
+
export async function calibrate(
|
|
422
|
+
sql: SavingsSql,
|
|
423
|
+
opts: { days: number; end: Date },
|
|
424
|
+
): Promise<CalibrationRun> {
|
|
425
|
+
const start = new Date(opts.end.getTime() - opts.days * 86_400_000);
|
|
426
|
+
const window = { start: start.toISOString(), end: opts.end.toISOString(), days: opts.days };
|
|
427
|
+
const refused = (refusal: string): CalibrationRun => ({
|
|
428
|
+
window,
|
|
429
|
+
sessions: 0,
|
|
430
|
+
refusal,
|
|
431
|
+
calibration: null,
|
|
432
|
+
speed: null,
|
|
433
|
+
repriceMatch: null,
|
|
434
|
+
gaps: [],
|
|
435
|
+
meanRatio: null,
|
|
436
|
+
applyBlocked: null,
|
|
437
|
+
});
|
|
438
|
+
let derived: DerivedCalibration;
|
|
439
|
+
try {
|
|
440
|
+
derived = deriveCurves(await fetchInput(sql, start, opts.end));
|
|
441
|
+
} catch (err) {
|
|
442
|
+
if (err instanceof CalibrationRefusal) return refused(err.message);
|
|
443
|
+
throw err;
|
|
444
|
+
}
|
|
445
|
+
const perTurn = Array.from({ length: TAU_MAX }, () => 0);
|
|
446
|
+
for (const s of derived.usable) perTurn[s.turns - 1] = (perTurn[s.turns - 1] as number) + 1;
|
|
447
|
+
const mean = (a: readonly number[]) => a.reduce((s, v) => s + v, 0) / a.length;
|
|
448
|
+
const meanRatio = mean(derived.curve.smart.usd) / mean(CURVE.smart.usd);
|
|
449
|
+
return {
|
|
450
|
+
window,
|
|
451
|
+
sessions: derived.sessions,
|
|
452
|
+
refusal: null,
|
|
453
|
+
calibration: {
|
|
454
|
+
calibratedAt: derived.calibratedAt,
|
|
455
|
+
model: derived.model,
|
|
456
|
+
curve: derived.curve,
|
|
457
|
+
window: { start: window.start, end: window.end, sessions: derived.sessions },
|
|
458
|
+
},
|
|
459
|
+
speed: derived.speed,
|
|
460
|
+
repriceMatch: derived.repriceMatch,
|
|
461
|
+
gaps: compareToShipped(derived.curve, perTurn),
|
|
462
|
+
meanRatio,
|
|
463
|
+
applyBlocked:
|
|
464
|
+
meanRatio > SANITY_FACTOR || meanRatio < 1 / SANITY_FACTOR
|
|
465
|
+
? `derived smart curve is ${meanRatio.toFixed(2)}x the shipped one (limit ${SANITY_FACTOR}x)`
|
|
466
|
+
: null,
|
|
467
|
+
};
|
|
468
|
+
}
|