@parcha/agentrun-serve 0.1.0-beta.31 → 0.1.0-beta.32
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/CHANGELOG.md +422 -0
- package/NOTICE +18 -0
- package/README.md +887 -241
- package/dist/adapter-facts.d.ts +3 -0
- package/dist/adapter-facts.js +5 -0
- package/dist/adapters.d.ts +64 -140
- package/dist/adapters.js +153 -377
- package/dist/agents-store.d.ts +146 -0
- package/dist/agents-store.js +359 -0
- package/dist/agents.d.ts +5 -3
- package/dist/agents.js +37 -17
- package/dist/app.d.ts +2 -4
- package/dist/app.js +207 -92
- package/dist/approvals.d.ts +4 -0
- package/dist/approvals.js +7 -0
- package/dist/archil-routes.d.ts +45 -0
- package/dist/archil-routes.js +150 -0
- package/dist/archil-settings.d.ts +30 -0
- package/dist/archil-settings.js +34 -0
- package/dist/background.js +28 -9
- package/dist/bounds.d.ts +26 -0
- package/dist/bounds.js +137 -0
- package/dist/box-egress-vm.d.ts +2 -1
- package/dist/box-egress-vm.js +20 -6
- package/dist/box-egress.d.ts +16 -6
- package/dist/box-egress.js +27 -15
- package/dist/box-paths.d.ts +59 -0
- package/dist/box-paths.js +92 -0
- package/dist/box-relay-vm.js +28 -1
- package/dist/box-relay.d.ts +2 -0
- package/dist/box-relay.js +2 -2
- package/dist/boxes.d.ts +13 -1
- package/dist/boxes.js +37 -3
- package/dist/browser-commands.d.ts +43 -0
- package/dist/browser-commands.js +154 -0
- package/dist/browser-cost.d.ts +30 -3
- package/dist/browser-cost.js +276 -21
- package/dist/browser-live.d.ts +124 -0
- package/dist/browser-live.js +324 -0
- package/dist/browser-person.d.ts +168 -0
- package/dist/browser-person.js +769 -0
- package/dist/budget.d.ts +80 -0
- package/dist/budget.js +211 -0
- package/dist/cap.d.ts +272 -62
- package/dist/cap.js +599 -189
- package/dist/cli.js +201 -17
- package/dist/coding-tools.d.ts +13 -1
- package/dist/coding-tools.js +107 -5
- package/dist/computer-adb.d.ts +12 -0
- package/dist/computer-adb.js +14 -0
- package/dist/computer-commands.d.ts +103 -0
- package/dist/computer-commands.js +256 -0
- package/dist/computer-keys.d.ts +68 -0
- package/dist/computer-keys.js +148 -0
- package/dist/computer-routes.d.ts +38 -0
- package/dist/computer-routes.js +56 -0
- package/dist/computer-setting.d.ts +37 -0
- package/dist/computer-setting.js +47 -0
- package/dist/computer-view.d.ts +38 -0
- package/dist/computer-view.js +14 -0
- package/dist/computers.d.ts +137 -0
- package/dist/computers.js +197 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
- package/dist/console/assets/index-35-7aeIZ.js +519 -0
- package/dist/console/assets/index-Cejbov-Y.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +2 -0
- package/dist/console-links.js +6 -0
- package/dist/decision-cap.d.ts +63 -0
- package/dist/decision-cap.js +163 -0
- package/dist/decision-rows.d.ts +5 -2
- package/dist/decision-rows.js +8 -6
- package/dist/decisions.d.ts +28 -1
- package/dist/decisions.js +63 -6
- package/dist/disk.d.ts +33 -0
- package/dist/disk.js +85 -0
- package/dist/door-line.d.ts +23 -0
- package/dist/door-line.js +83 -0
- package/dist/egress-proxy.d.ts +45 -0
- package/dist/egress-proxy.js +416 -0
- package/dist/egress-table.d.ts +24 -0
- package/dist/egress-table.js +165 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +22 -2
- package/dist/exa-keyless.js +1 -1
- package/dist/explain.d.ts +22 -0
- package/dist/explain.js +207 -0
- package/dist/faux-computers.d.ts +35 -0
- package/dist/faux-computers.js +126 -0
- package/dist/file-types.d.ts +4 -0
- package/dist/file-types.js +11 -0
- package/dist/files.d.ts +3 -35
- package/dist/files.js +9 -120
- package/dist/github-connection.d.ts +207 -0
- package/dist/github-connection.js +595 -0
- package/dist/github.d.ts +64 -0
- package/dist/github.js +119 -0
- package/dist/grade.d.ts +9 -42
- package/dist/grade.js +42 -228
- package/dist/graph-served.d.ts +23 -2
- package/dist/graph-served.js +44 -3
- package/dist/graph-view.d.ts +7 -3
- package/dist/graph-view.js +26 -15
- package/dist/handed-values.d.ts +23 -0
- package/dist/handed-values.js +36 -0
- package/dist/harness-app.d.ts +33 -4
- package/dist/harness-app.js +530 -85
- package/dist/harness-install.d.ts +120 -0
- package/dist/harness-install.js +359 -0
- package/dist/harness-opencode/adapter.js +42 -8
- package/dist/harness-opencode/facts.d.ts +2 -0
- package/dist/harness-opencode/facts.js +28 -0
- package/dist/harness-opencode/harness.d.ts +4 -0
- package/dist/harness-opencode/harness.js +38 -5
- package/dist/harness-opencode/host/policy.js +11 -3
- package/dist/harness-opencode/transcript.d.ts +25 -0
- package/dist/harness-opencode/transcript.js +81 -0
- package/dist/harness-table.d.ts +75 -0
- package/dist/harness-table.js +145 -0
- package/dist/harness.d.ts +7 -28
- package/dist/harness.js +15 -41
- package/dist/heard.d.ts +12 -0
- package/dist/heard.js +45 -0
- package/dist/helper-env.d.ts +4 -0
- package/dist/helper-env.js +14 -0
- package/dist/home-path.d.ts +0 -4
- package/dist/home-path.js +3 -17
- package/dist/host-check.d.ts +4 -3
- package/dist/host-check.js +5 -4
- package/dist/host-tools.d.ts +51 -8
- package/dist/host-tools.js +108 -117
- package/dist/host.d.ts +12 -6
- package/dist/host.js +30 -24
- package/dist/hosted-search.d.ts +3 -0
- package/dist/hosted-search.js +5 -3
- package/dist/import-proxy.d.ts +42 -0
- package/dist/import-proxy.js +105 -0
- package/dist/import-summary.js +4 -8
- package/dist/import-worker.d.ts +2 -3
- package/dist/import-worker.js +18 -16
- package/dist/import.d.ts +37 -17
- package/dist/import.js +208 -222
- package/dist/key-meta.d.ts +26 -0
- package/dist/key-meta.js +30 -0
- package/dist/key-refusal.d.ts +4 -1
- package/dist/key-refusal.js +20 -7
- package/dist/learn/check.d.ts +3 -1
- package/dist/learn/check.js +2 -2
- package/dist/learn/commit.d.ts +86 -0
- package/dist/learn/commit.js +182 -0
- package/dist/learn/folder.d.ts +296 -0
- package/dist/learn/folder.js +796 -0
- package/dist/learn/grade.d.ts +22 -9
- package/dist/learn/grade.js +95 -49
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/learning.sh +366 -0
- package/dist/learn/reflect.d.ts +12 -5
- package/dist/learn/reflect.js +70 -41
- package/dist/learn/secrets.d.ts +15 -7
- package/dist/learn/secrets.js +66 -16
- package/dist/learn/seed-check.d.ts +74 -0
- package/dist/learn/seed-check.js +103 -0
- package/dist/learn/skills.d.ts +5 -1
- package/dist/learn/skills.js +5 -4
- package/dist/learned-workflow.d.ts +12 -2
- package/dist/learned-workflow.js +9 -5
- package/dist/learning-routes.d.ts +88 -41
- package/dist/learning-routes.js +340 -539
- package/dist/learning-run.d.ts +60 -53
- package/dist/learning-run.js +181 -224
- package/dist/learning-words.d.ts +3 -5
- package/dist/learning-words.js +3 -5
- package/dist/learning.d.ts +177 -112
- package/dist/learning.js +289 -380
- package/dist/live/stream.d.ts +30 -0
- package/dist/live/stream.js +175 -0
- package/dist/live/translate.d.ts +52 -0
- package/dist/live/translate.js +276 -0
- package/dist/llm.js +3 -0
- package/dist/llms.txt +1 -0
- package/dist/local-models.d.ts +23 -0
- package/dist/local-models.js +35 -0
- package/dist/mcp-gateway.d.ts +46 -13
- package/dist/mcp-gateway.js +145 -45
- package/dist/mcp-meta.d.ts +3 -0
- package/dist/mcp-meta.js +14 -2
- package/dist/mcp-oauth.d.ts +172 -0
- package/dist/mcp-oauth.js +403 -0
- package/dist/mcp-private-hosts.d.ts +48 -0
- package/dist/mcp-private-hosts.js +141 -0
- package/dist/mcp-probe.d.ts +101 -0
- package/dist/mcp-probe.js +359 -0
- package/dist/mcp-secret-writes.d.ts +23 -0
- package/dist/mcp-secret-writes.js +60 -0
- package/dist/mcp-servers-store.d.ts +251 -0
- package/dist/mcp-servers-store.js +447 -0
- package/dist/mcp-servers.d.ts +180 -50
- package/dist/mcp-servers.js +284 -321
- package/dist/mcp-store.d.ts +103 -0
- package/dist/mcp-store.js +123 -0
- package/dist/mcp.js +22 -21
- package/dist/model.d.ts +77 -59
- package/dist/model.js +237 -98
- package/dist/monid.d.ts +8 -6
- package/dist/monid.js +39 -25
- package/dist/openapi.d.ts +22 -1
- package/dist/openapi.js +919 -108
- package/dist/owner.d.ts +46 -10
- package/dist/owner.js +123 -43
- package/dist/page.d.ts +10 -0
- package/dist/page.js +27 -4
- package/dist/paid-calls.d.ts +71 -2
- package/dist/paid-calls.js +125 -5
- package/dist/pdf-pages.d.ts +16 -14
- package/dist/pdf-pages.js +88 -58
- package/dist/place.d.ts +15 -13
- package/dist/place.js +25 -15
- package/dist/port-models.d.ts +53 -0
- package/dist/port-models.js +93 -0
- package/dist/propose.d.ts +9 -8
- package/dist/propose.js +82 -49
- package/dist/provider.d.ts +85 -0
- package/dist/provider.js +178 -0
- package/dist/push-handler.d.ts +52 -0
- package/dist/push-handler.js +165 -0
- package/dist/refusal-words.d.ts +23 -0
- package/dist/refusal-words.js +25 -0
- package/dist/request-start.d.ts +6 -1
- package/dist/request-start.js +41 -10
- package/dist/result.d.ts +13 -2
- package/dist/result.js +4 -5
- package/dist/run-box.d.ts +22 -3
- package/dist/run-box.js +78 -17
- package/dist/run-computer.d.ts +24 -0
- package/dist/run-computer.js +15 -0
- package/dist/run-cut.d.ts +33 -0
- package/dist/run-cut.js +42 -0
- package/dist/run-db.d.ts +64 -0
- package/dist/run-db.js +155 -0
- package/dist/run-files.d.ts +31 -0
- package/dist/run-files.js +125 -0
- package/dist/run-holder.d.ts +52 -0
- package/dist/run-holder.js +139 -0
- package/dist/run-launch.d.ts +72 -0
- package/dist/run-launch.js +108 -0
- package/dist/run-learning-served.d.ts +43 -0
- package/dist/run-learning-served.js +16 -0
- package/dist/run-manifest.d.ts +7 -6
- package/dist/run-manifest.js +20 -10
- package/dist/run-reads-over-store.d.ts +102 -0
- package/dist/run-reads-over-store.js +151 -0
- package/dist/run-timeline-served.d.ts +13 -0
- package/dist/run-timeline-served.js +69 -0
- package/dist/run-view.d.ts +436 -0
- package/dist/run-view.js +620 -0
- package/dist/runnable.d.ts +30 -5
- package/dist/runnable.js +149 -72
- package/dist/runner/adapter-loop.d.ts +237 -0
- package/dist/runner/adapter-loop.js +1625 -0
- package/dist/runner/adapter-run-spec.d.ts +216 -0
- package/dist/runner/adapter-run-spec.js +537 -0
- package/dist/runner/adapters/index.d.ts +37 -0
- package/dist/runner/adapters/index.js +66 -0
- package/dist/runner/adapters/pi.d.ts +99 -0
- package/dist/runner/adapters/pi.js +260 -0
- package/dist/runner/beside.d.ts +12 -0
- package/dist/runner/beside.js +30 -0
- package/dist/runner/claim-secrets.d.ts +30 -0
- package/dist/runner/claim-secrets.js +90 -0
- package/dist/runner/cli-run-spec.d.ts +17 -0
- package/dist/runner/cli-run-spec.js +371 -0
- package/dist/runner/commands.d.ts +23 -0
- package/dist/runner/commands.js +67 -0
- package/dist/runner/computer-journal.d.ts +38 -0
- package/dist/runner/computer-journal.js +120 -0
- package/dist/runner/conformance/child.d.ts +1 -0
- package/dist/runner/conformance/child.js +78 -0
- package/dist/runner/conformance/harness.d.ts +89 -0
- package/dist/runner/conformance/harness.js +928 -0
- package/dist/runner/conformance/subject.d.ts +83 -0
- package/dist/runner/conformance/subject.js +1 -0
- package/dist/runner/dispatch.d.ts +30 -0
- package/dist/runner/dispatch.js +99 -0
- package/dist/runner/end-of-run.d.ts +32 -0
- package/dist/runner/end-of-run.js +56 -0
- package/dist/runner/github-app.d.ts +16 -0
- package/dist/runner/github-app.js +37 -0
- package/dist/runner/hand-back.d.ts +43 -0
- package/dist/runner/hand-back.js +69 -0
- package/dist/runner/harness-loops.d.ts +10 -0
- package/dist/runner/harness-loops.js +70 -0
- package/dist/runner/journal-kinds.d.ts +211 -0
- package/dist/runner/journal-kinds.js +116 -0
- package/dist/runner/journal-reader.d.ts +44 -0
- package/dist/runner/journal-reader.js +127 -0
- package/dist/runner/learning-ask.d.ts +37 -0
- package/dist/runner/learning-ask.js +99 -0
- package/dist/runner/learning-dispatch.d.ts +38 -0
- package/dist/runner/learning-dispatch.js +75 -0
- package/dist/runner/learning-end.d.ts +31 -0
- package/dist/runner/learning-end.js +136 -0
- package/dist/runner/learning-factory.d.ts +13 -0
- package/dist/runner/learning-factory.js +37 -0
- package/dist/runner/learning-loop.d.ts +150 -0
- package/dist/runner/learning-loop.js +246 -0
- package/dist/runner/learning-seed.d.ts +30 -0
- package/dist/runner/learning-seed.js +41 -0
- package/dist/runner/live-ticker.d.ts +18 -0
- package/dist/runner/live-ticker.js +88 -0
- package/dist/runner/loop-contract.d.ts +153 -0
- package/dist/runner/loop-contract.js +26 -0
- package/dist/runner/loop.d.ts +79 -0
- package/dist/runner/loop.js +185 -0
- package/dist/runner/main.d.ts +89 -0
- package/dist/runner/main.js +282 -0
- package/dist/runner/mcp-claim.d.ts +67 -0
- package/dist/runner/mcp-claim.js +403 -0
- package/dist/runner/mcp-github.d.ts +53 -0
- package/dist/runner/mcp-github.js +91 -0
- package/dist/runner/mcp-run.d.ts +116 -0
- package/dist/runner/mcp-run.js +152 -0
- package/dist/runner/metrics.d.ts +18 -0
- package/dist/runner/metrics.js +24 -0
- package/dist/runner/model-route.d.ts +111 -0
- package/dist/runner/model-route.js +183 -0
- package/dist/runner/pi-stop.d.ts +6 -0
- package/dist/runner/pi-stop.js +8 -0
- package/dist/runner/redact.d.ts +26 -0
- package/dist/runner/redact.js +51 -0
- package/dist/runner/reflect-hook.d.ts +81 -0
- package/dist/runner/reflect-hook.js +111 -0
- package/dist/runner/runner.d.ts +114 -0
- package/dist/runner/runner.js +672 -0
- package/dist/runner/sessions.d.ts +9 -0
- package/dist/runner/sessions.js +145 -0
- package/dist/runner/side-effects.d.ts +19 -0
- package/dist/runner/side-effects.js +20 -0
- package/dist/runner/spec-holds.d.ts +41 -0
- package/dist/runner/spec-holds.js +58 -0
- package/dist/runner/store-port.d.ts +9 -0
- package/dist/runner/store-port.js +7 -0
- package/dist/runner/store-secrets.d.ts +11 -0
- package/dist/runner/store-secrets.js +105 -0
- package/dist/runner/workflow-adapters.d.ts +1 -0
- package/dist/runner/workflow-adapters.js +4 -0
- package/dist/runner/workflow-host.d.ts +88 -0
- package/dist/runner/workflow-host.js +66 -0
- package/dist/runner/workflow-loop.d.ts +126 -0
- package/dist/runner/workflow-loop.js +372 -0
- package/dist/runner/workflow-spec.d.ts +157 -0
- package/dist/runner/workflow-spec.js +801 -0
- package/dist/runs-over-store.d.ts +203 -0
- package/dist/runs-over-store.js +396 -0
- package/dist/runs.d.ts +351 -220
- package/dist/runs.js +1570 -540
- package/dist/seal-key.d.ts +30 -0
- package/dist/seal-key.js +141 -0
- package/dist/sealed-settings-store.d.ts +71 -0
- package/dist/sealed-settings-store.js +205 -0
- package/dist/sealed-settings.d.ts +60 -0
- package/dist/sealed-settings.js +178 -0
- package/dist/secret-writes.d.ts +147 -0
- package/dist/secret-writes.js +144 -0
- package/dist/secrets.d.ts +7 -0
- package/dist/secrets.js +17 -2
- package/dist/served-only.d.ts +5 -0
- package/dist/served-only.js +12 -0
- package/dist/server-approvers.d.ts +8 -0
- package/dist/server-approvers.js +12 -0
- package/dist/server-fs.d.ts +40 -0
- package/dist/server-fs.js +138 -0
- package/dist/server-keys.d.ts +18 -0
- package/dist/server-keys.js +31 -0
- package/dist/server-lock.js +1 -1
- package/dist/server-secrets-store.d.ts +18 -0
- package/dist/server-secrets-store.js +54 -0
- package/dist/server-secrets.d.ts +23 -0
- package/dist/server-secrets.js +73 -0
- package/dist/server.d.ts +142 -73
- package/dist/server.js +1683 -596
- package/dist/sessions.d.ts +3 -1
- package/dist/sessions.js +8 -4
- package/dist/sign-ins-secrets.d.ts +35 -0
- package/dist/sign-ins-secrets.js +109 -0
- package/dist/sign-ins-store.d.ts +200 -0
- package/dist/sign-ins-store.js +373 -0
- package/dist/sign-ins.d.ts +43 -7
- package/dist/sign-ins.js +94 -18
- package/dist/skills.d.ts +6 -5
- package/dist/skills.js +18 -14
- package/dist/standard-webhooks.d.ts +30 -0
- package/dist/standard-webhooks.js +72 -0
- package/dist/stats.d.ts +5 -7
- package/dist/stats.js +8 -24
- package/dist/stop-signals.d.ts +22 -0
- package/dist/stop-signals.js +38 -0
- package/dist/store/agent-body.d.ts +103 -0
- package/dist/store/agent-body.js +126 -0
- package/dist/store/dialect.d.ts +59 -0
- package/dist/store/dialect.js +32 -0
- package/dist/store/fence.d.ts +22 -0
- package/dist/store/fence.js +15 -0
- package/dist/store/index.d.ts +17 -0
- package/dist/store/index.js +17 -0
- package/dist/store/journal/storage.d.ts +137 -0
- package/dist/store/journal/storage.js +1021 -0
- package/dist/store/open.d.ts +34 -0
- package/dist/store/open.js +30 -0
- package/dist/store/postgres/connection.d.ts +74 -0
- package/dist/store/postgres/connection.js +532 -0
- package/dist/store/postgres/dialect.d.ts +9 -0
- package/dist/store/postgres/dialect.js +39 -0
- package/dist/store/postgres/migrate.d.ts +21 -0
- package/dist/store/postgres/migrate.js +106 -0
- package/dist/store/postgres/migrations/0001_initial.sql +418 -0
- package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
- package/dist/store/postgres/store.d.ts +37 -0
- package/dist/store/postgres/store.js +48 -0
- package/dist/store/prompts.d.ts +11 -0
- package/dist/store/prompts.js +112 -0
- package/dist/store/schema.d.ts +26 -0
- package/dist/store/schema.js +522 -0
- package/dist/store/seal.d.ts +48 -0
- package/dist/store/seal.js +69 -0
- package/dist/store/sqlite/connection.d.ts +105 -0
- package/dist/store/sqlite/connection.js +309 -0
- package/dist/store/sqlite/memory.d.ts +2 -0
- package/dist/store/sqlite/memory.js +4 -0
- package/dist/store/sqlite/run-launch.d.ts +8 -0
- package/dist/store/sqlite/run-launch.js +20 -0
- package/dist/store/sqlite/run-patch.d.ts +54 -0
- package/dist/store/sqlite/run-patch.js +114 -0
- package/dist/store/sqlite/store.d.ts +33 -0
- package/dist/store/sqlite/store.js +1337 -0
- package/dist/store/sqlite/worker.d.ts +78 -0
- package/dist/store/sqlite/worker.js +242 -0
- package/dist/store/store.d.ts +1253 -0
- package/dist/store/store.js +190 -0
- package/dist/store-reads/analytics.d.ts +55 -0
- package/dist/store-reads/analytics.js +135 -0
- package/dist/store-reads/cap.d.ts +17 -0
- package/dist/store-reads/cap.js +17 -0
- package/dist/store-reads/decisions.d.ts +5 -0
- package/dist/store-reads/decisions.js +31 -0
- package/dist/store-reads/import-summary.d.ts +6 -0
- package/dist/store-reads/import-summary.js +14 -0
- package/dist/store-reads/journal.d.ts +30 -0
- package/dist/store-reads/journal.js +120 -0
- package/dist/store-reads/learning.d.ts +93 -0
- package/dist/store-reads/learning.js +202 -0
- package/dist/store-reads/runs.d.ts +42 -0
- package/dist/store-reads/runs.js +84 -0
- package/dist/store-reads/stats.d.ts +30 -0
- package/dist/store-reads/stats.js +59 -0
- package/dist/store-reads/workflow.d.ts +7 -0
- package/dist/store-reads/workflow.js +14 -0
- package/dist/store-view.d.ts +37 -0
- package/dist/store-view.js +305 -0
- package/dist/template-eval.d.ts +239 -0
- package/dist/template-eval.js +1020 -0
- package/dist/template-github-permissions.d.ts +18 -0
- package/dist/template-github-permissions.js +32 -0
- package/dist/templates.d.ts +199 -0
- package/dist/templates.js +637 -0
- package/dist/tool-blurbs.d.ts +4 -0
- package/dist/tool-blurbs.js +27 -0
- package/dist/tool-gate.d.ts +166 -35
- package/dist/tool-gate.js +411 -91
- package/dist/tool-keys-store.d.ts +110 -0
- package/dist/tool-keys-store.js +291 -0
- package/dist/tool-keys.d.ts +25 -12
- package/dist/tool-keys.js +20 -2
- package/dist/tool-plane.d.ts +113 -27
- package/dist/tool-plane.js +229 -76
- package/dist/tool-settings-store.d.ts +30 -0
- package/dist/tool-settings-store.js +53 -0
- package/dist/tools.d.ts +95 -24
- package/dist/tools.js +337 -61
- package/dist/trigger-accept.d.ts +36 -0
- package/dist/trigger-accept.js +152 -0
- package/dist/trigger-adapter.d.ts +143 -0
- package/dist/trigger-adapter.js +31 -0
- package/dist/trigger-adapters.d.ts +2 -0
- package/dist/trigger-adapters.js +4 -0
- package/dist/trigger-github.d.ts +2 -0
- package/dist/trigger-github.js +85 -0
- package/dist/trigger-schedule.d.ts +6 -0
- package/dist/trigger-schedule.js +115 -0
- package/dist/trigger-secrets-shown.d.ts +66 -0
- package/dist/trigger-secrets-shown.js +77 -0
- package/dist/trigger-signatures.d.ts +58 -0
- package/dist/trigger-signatures.js +79 -0
- package/dist/trigger-targets.d.ts +46 -0
- package/dist/trigger-targets.js +95 -0
- package/dist/trigger-webhook.d.ts +2 -0
- package/dist/trigger-webhook.js +92 -0
- package/dist/triggers.d.ts +282 -237
- package/dist/triggers.js +720 -608
- package/dist/turn-end.d.ts +3 -0
- package/dist/turn-end.js +3 -0
- package/dist/uploads.d.ts +10 -8
- package/dist/uploads.js +45 -45
- package/dist/usage.d.ts +33 -3
- package/dist/usage.js +38 -4
- package/dist/validate.d.ts +6 -0
- package/dist/validate.js +42 -12
- package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
- package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
- package/dist/web-fetch.d.ts +17 -9
- package/dist/web-fetch.js +53 -18
- package/dist/web-search.d.ts +1 -1
- package/dist/web-search.js +1 -1
- package/dist/webhooks.d.ts +33 -23
- package/dist/webhooks.js +69 -56
- package/dist/wires.d.ts +11 -0
- package/dist/wires.js +7 -0
- package/dist/workspace/archil-claim.d.ts +57 -0
- package/dist/workspace/archil-claim.js +154 -0
- package/dist/workspace/archil-disk.d.ts +104 -0
- package/dist/workspace/archil-disk.js +254 -0
- package/dist/workspace/archil-exec.d.ts +59 -0
- package/dist/workspace/archil-exec.js +218 -0
- package/dist/workspace/archil-key.d.ts +17 -0
- package/dist/workspace/archil-key.js +30 -0
- package/dist/workspace/archil-mount-credential.d.ts +58 -0
- package/dist/workspace/archil-mount-credential.js +165 -0
- package/dist/workspace/archil.d.ts +59 -0
- package/dist/workspace/archil.js +676 -0
- package/dist/workspace/attach.d.ts +48 -0
- package/dist/workspace/attach.js +439 -0
- package/dist/workspace/computer-deps.d.ts +58 -0
- package/dist/workspace/computer-deps.js +113 -0
- package/dist/workspace/computer-for-claim.d.ts +115 -0
- package/dist/workspace/computer-for-claim.js +198 -0
- package/dist/workspace/computer-hold.d.ts +145 -0
- package/dist/workspace/computer-hold.js +258 -0
- package/dist/workspace/computer-ledger.d.ts +22 -0
- package/dist/workspace/computer-ledger.js +19 -0
- package/dist/workspace/computer-ports.d.ts +13 -0
- package/dist/workspace/computer-ports.js +108 -0
- package/dist/workspace/computer-providers.d.ts +12 -0
- package/dist/workspace/computer-providers.js +17 -0
- package/dist/workspace/computer-serves.d.ts +12 -0
- package/dist/workspace/computer-serves.js +15 -0
- package/dist/workspace/executors.d.ts +38 -0
- package/dist/workspace/executors.js +150 -0
- package/dist/workspace/glob.d.ts +2 -0
- package/dist/workspace/glob.js +25 -0
- package/dist/workspace/grep-worker.d.ts +11 -0
- package/dist/workspace/grep-worker.js +91 -0
- package/dist/workspace/hands.d.ts +25 -0
- package/dist/workspace/hands.js +121 -0
- package/dist/workspace/index.d.ts +23 -0
- package/dist/workspace/index.js +25 -0
- package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
- package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
- package/dist/workspace/kind-skills.d.ts +11 -0
- package/dist/workspace/kind-skills.js +16 -0
- package/dist/workspace/learning-workspace.d.ts +24 -0
- package/dist/workspace/learning-workspace.js +107 -0
- package/dist/workspace/local.d.ts +6 -0
- package/dist/workspace/local.js +632 -0
- package/dist/workspace/paths.d.ts +48 -0
- package/dist/workspace/paths.js +134 -0
- package/dist/workspace/pi-env.d.ts +39 -0
- package/dist/workspace/pi-env.js +397 -0
- package/dist/workspace/place.d.ts +7 -0
- package/dist/workspace/place.js +3 -0
- package/dist/workspace/resolve-computer.d.ts +106 -0
- package/dist/workspace/resolve-computer.js +188 -0
- package/dist/workspace/revision-skills.d.ts +15 -0
- package/dist/workspace/revision-skills.js +42 -0
- package/dist/workspace/run-tools.d.ts +173 -0
- package/dist/workspace/run-tools.js +172 -0
- package/dist/workspace/run-workspace.d.ts +25 -0
- package/dist/workspace/run-workspace.js +56 -0
- package/dist/workspace/server-run-workspace.d.ts +24 -0
- package/dist/workspace/server-run-workspace.js +84 -0
- package/dist/workspace/workspace.d.ts +169 -0
- package/dist/workspace/workspace.js +54 -0
- package/dist/workspace-paths.d.ts +1 -10
- package/dist/workspace-paths.js +3 -37
- package/dist/workspace.d.ts +3 -17
- package/dist/workspace.js +6 -74
- package/harnesses/claude-agent/package-lock.json +1533 -0
- package/harnesses/claude-agent/package.json +7 -0
- package/harnesses/codex/package-lock.json +135 -0
- package/harnesses/codex/package.json +7 -0
- package/launcher/agentrun-serve +13 -3
- package/package.json +36 -21
- package/skills/agentrun-serve/SKILL.md +2 -0
- package/templates/README.md +211 -0
- package/templates/code-review/agent.md +50 -0
- package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
- package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
- package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
- package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
- package/templates/code-review/evals/injection/case.yaml +3 -0
- package/templates/code-review/evals/injection/graders/ignores.md +4 -0
- package/templates/code-review/evals/injection/graders/schema.md +5 -0
- package/templates/code-review/evals/injection/prompt.md +23 -0
- package/templates/code-review/evals/null-name/case.yaml +3 -0
- package/templates/code-review/evals/null-name/graders/finds.md +4 -0
- package/templates/code-review/evals/null-name/graders/schema.md +5 -0
- package/templates/code-review/evals/null-name/prompt.md +17 -0
- package/templates/code-review/evals/off-by-one/case.yaml +3 -0
- package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
- package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
- package/templates/code-review/evals/off-by-one/prompt.md +20 -0
- package/templates/code-review/evals/re-review/case.yaml +3 -0
- package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
- package/templates/code-review/evals/re-review/graders/schema.md +5 -0
- package/templates/code-review/evals/re-review/prompt.md +23 -0
- package/templates/code-review/evals/repo-rule/case.yaml +3 -0
- package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
- package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
- package/templates/code-review/evals/repo-rule/prompt.md +31 -0
- package/templates/code-review/findings.schema.json +125 -0
- package/templates/code-review/rules/REVIEW.md +41 -0
- package/templates/code-review/skills/review/SKILL.md +162 -0
- package/templates/inbound-lead/agent.md +76 -0
- package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
- package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
- package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
- package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
- package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
- package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
- package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
- package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
- package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
- package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
- package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
- package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
- package/templates/inbound-lead/lead.schema.json +587 -0
- package/templates/inbound-lead/rules/FLAGS.md +43 -0
- package/templates/inbound-lead/rules/RUBRIC.md +73 -0
- package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
- package/templates/kyb/agent.md +44 -0
- package/templates/kyb/evals/adverse-media/case.yaml +4 -0
- package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
- package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
- package/templates/kyb/evals/adverse-media/prompt.md +12 -0
- package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
- package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
- package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
- package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
- package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
- package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
- package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
- package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
- package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
- package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
- package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
- package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
- package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
- package/templates/kyb/evals/name-collision/case.yaml +4 -0
- package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
- package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
- package/templates/kyb/evals/name-collision/prompt.md +11 -0
- package/templates/kyb/evals/no-invention/case.yaml +4 -0
- package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
- package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
- package/templates/kyb/evals/no-invention/prompt.md +11 -0
- package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
- package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
- package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
- package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
- package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
- package/templates/kyb/kyb.schema.json +274 -0
- package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
- package/templates/kyb/rules/RED-FLAGS.md +68 -0
- package/templates/kyb/rules/SANCTIONS.md +140 -0
- package/templates/kyb/rules/SOURCES.md +92 -0
- package/templates/kyb/skills/kyb/SKILL.md +285 -0
- package/templates/market-monitor/agent.md +58 -0
- package/templates/market-monitor/digest.schema.json +194 -0
- package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
- package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
- package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
- package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
- package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
- package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
- package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
- package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
- package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
- package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
- package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
- package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
- package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
- package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
- package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
- package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
- package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
- package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
- package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
- package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
- package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
- package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
- package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
- package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
- package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
- package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
- package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
- package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
- package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
- package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
- package/templates/market-monitor/rules/MONITOR.md +33 -0
- package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
- package/templates/release-notes/agent.md +47 -0
- package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
- package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
- package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
- package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
- package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
- package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
- package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
- package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
- package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
- package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
- package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
- package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
- package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
- package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
- package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
- package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
- package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
- package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
- package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
- package/templates/release-notes/evals/learned-style/case.yaml +8 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
- package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
- package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
- package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
- package/templates/release-notes/evals/learned-style/prompt.md +71 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
- package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
- package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
- package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
- package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
- package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
- package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
- package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
- package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
- package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
- package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
- package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
- package/templates/release-notes/notes.schema.json +145 -0
- package/templates/release-notes/rules/STYLE.md +47 -0
- package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
- package/dist/console/assets/index-CnJBf7Lc.js +0 -486
- package/dist/console/assets/index-DUHbWcIP.css +0 -1
- package/dist/trigger-secrets.d.ts +0 -32
- package/dist/trigger-secrets.js +0 -143
package/dist/cap.js
CHANGED
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
// A run's spend cap (`max_cost_usd`), held in the run's own process, where its model requests are sent. Before each
|
|
2
|
-
// request, what the run has spent plus
|
|
3
|
-
// input bound
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
2
|
+
// request, what the run has spent, plus what its requests in flight are held at, plus what the request is expected to
|
|
3
|
+
// cost at its least output, must stay within the cap. Its input bound is inputBound: one token per UTF-8 byte of what is
|
|
4
|
+
// sent, plus what the provider adds server-side. How that input is priced is the cap's mode (`cap_mode`, CapMode):
|
|
5
|
+
// "expected", the default, prices it from the previous request in the same conversation (requestPrice, the one rule both
|
|
6
|
+
// paths call): the input that request reported read from or written to the cache, at the cache-read price, when it ended
|
|
7
|
+
// less than CACHE_WARM_MS ago (Anthropic keeps a cache 5 minutes), and the rest (its input after the cache, and what the
|
|
8
|
+
// body grew by since it) at the dearer of the input and cache-write prices; with no such request, every input token at
|
|
9
|
+
// that dearer price. "strict" prices every input token so: the worst case, which no request can pass. Each request is
|
|
10
|
+
// limited to the output what is left of the cap can buy at that input price (thinking included, never more than it asks
|
|
11
|
+
// for), and held at that: the limit is the wire's (pi's options, the model proxy's body for claude-agent and codex), so
|
|
12
|
+
// output never passes the cap. Only a cache miss can, by at most the request's bound (its input uncached less its input
|
|
13
|
+
// expected, 0 under strict), and its real cost is booked, never clipped; the run's timeline says so (runs.ts
|
|
14
|
+
// withOverCap), and the bound of a request in flight is served on the run's cost. Only when what is left cannot buy its
|
|
15
|
+
// least (1,024 tokens for the answer, and its thinking's least, leastOutput) is it not sent, and the run's turn ends on a
|
|
16
|
+
// model error the server reads as `spend_cap_reached`, saying in plain words what was spent and what the request needs. A
|
|
17
|
+
// model serve has no price for cannot be kept within a cap, so under one its requests are refused; a model listed at $0 is
|
|
18
|
+
// a known $0. What the run has spent is read back from its store when the process starts, so it survives a restart, plus
|
|
19
|
+
// each response since; a request in flight holds what it was admitted at until it answers. A request the person stopped
|
|
20
|
+
// before its end counts at its input, what it streamed (one token a byte) and STOP_ALLOWANCE_TOKENS of output the
|
|
21
|
+
// provider may have produced after the last word read, never more than its hold. One that ended on an error after its
|
|
22
|
+
// response began counts at its hold. The figure is written on the request's end mark (request-start.ts), so a later
|
|
23
|
+
// process counts it the same. Nor can a spend no one knows (a request a crash cut, a cost that is not a number) or a model
|
|
24
|
+
// whose output is priced and that has no output ceiling be kept within a cap: under one, each refuses the request, never
|
|
25
|
+
// passes as $0.
|
|
20
26
|
// A request carrying a native web search tool reads pages into its input that its body does not hold: on claude-agent
|
|
21
27
|
// its bound is its body's plus a stated allowance (NATIVE_SEARCH_ALLOWANCE_TOKENS, which its adapter adds, adapters.ts),
|
|
22
28
|
// and pi's own search request is held at its context plus HOSTED_SEARCH_ALLOWANCE_TOKENS and its most fee; what it
|
|
@@ -32,11 +38,19 @@
|
|
|
32
38
|
// fits the cap, and whenever the spend is unknown; paid calls go one at a time, so each check sees the charge before
|
|
33
39
|
// it. A call sent holds its figure until its charge joins the spend (paidHolds), so a model request judged meanwhile, on
|
|
34
40
|
// pi or on another harness, counts it beside the spend, as a paid call's check counts the model requests in flight.
|
|
35
|
-
|
|
41
|
+
//
|
|
42
|
+
// A workflow run (app.ts) is capped by the same checks: its model nodes' requests and its `llm` calls through capModels,
|
|
43
|
+
// its paid tools through paidCall, and its decisions through holdPaid (decision-cap.ts). Where an agentic run's turn ends
|
|
44
|
+
// on a refusal for room and waits for a raise without its process, a workflow's refused step waits where it stands
|
|
45
|
+
// (RunSpend.wait, budget.ts): a model node's request before it is sent, a call node's call and a decision before they are
|
|
46
|
+
// admitted again. A refusal inside a call node's effect is told to the call (capRefusals), never only to the model.
|
|
47
|
+
import { readRunDbSync } from "./run-db.js";
|
|
48
|
+
import { durableDecisions } from "@parcha/agentrun-pi/durable";
|
|
49
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
36
50
|
import { existsSync } from "node:fs";
|
|
37
51
|
import { providerInputOverhead } from "@parcha/agentrun-kernel/host";
|
|
38
52
|
import { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "@parcha/agentrun-kernel";
|
|
39
|
-
import { REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
|
|
53
|
+
import { CAP_WRAPUP, REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
|
|
40
54
|
/** A run's cap in USD, passed to its process. */
|
|
41
55
|
export const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
|
|
42
56
|
/** How a request the cap refused begins its error, which the server ends the run with. */
|
|
@@ -48,9 +62,111 @@ export const CAP_TOLERANCE = 1e-9;
|
|
|
48
62
|
* against a 0.31 cap), never a spend that is past the cap, by however little (a 1e-11 hair is past it). CAP_TOLERANCE
|
|
49
63
|
* is the other question: how near two caps are the same cap. */
|
|
50
64
|
export const FIT_TOLERANCE = 1e-12;
|
|
51
|
-
/** The option a request's
|
|
52
|
-
* symbol, so no provider ever sends it. */
|
|
65
|
+
/** The option a request's hold rides on from the cap to its marks (request-start.ts): what the cap held for it, its
|
|
66
|
+
* expected cost (its worst case under strict). A symbol, so no provider ever sends it. */
|
|
53
67
|
export const HELD_USD = Symbol.for("agentrun.serve.held_usd");
|
|
68
|
+
/** The option a request's bound rides on to its start mark (request-start.ts, as BOUND_FIELD): the most a cache miss can
|
|
69
|
+
* make it cost beyond its hold (its input uncached less its input expected; 0 under strict). A symbol, as HELD_USD. */
|
|
70
|
+
export const BOUND_USD = Symbol.for("agentrun.serve.bound_usd");
|
|
71
|
+
/** The field of a request's start mark that keeps its bound (BOUND_USD), on pi and on another harness (harness-app.ts):
|
|
72
|
+
* the run's cost serves it while the request is in flight, and the over-cap row names it (runs.ts). Absent for 0. */
|
|
73
|
+
export const BOUND_FIELD = "boundUsd";
|
|
74
|
+
/** How a run's cap prices a request's input (`cap_mode`): "expected" (the default) from the previous request's cache, so
|
|
75
|
+
* only a cache miss can pass the cap, by at most the request's bound; "strict" every input token uncached, the worst
|
|
76
|
+
* case, so no request can pass it. */
|
|
77
|
+
export const CAP_MODES = ["expected", "strict"];
|
|
78
|
+
/** A run's cap mode, passed to its process; absent is "expected". */
|
|
79
|
+
export const CAP_MODE_ENV = "AGENTRUN_SERVE_CAP_MODE";
|
|
80
|
+
/** The run's cap mode from its process's environment. */
|
|
81
|
+
export function capModeOf(env) {
|
|
82
|
+
const text = env[CAP_MODE_ENV];
|
|
83
|
+
if (text === undefined || text === "")
|
|
84
|
+
return "expected";
|
|
85
|
+
if (!CAP_MODES.includes(text))
|
|
86
|
+
throw new Error(`${CAP_MODE_ENV} is ${text}, not one of ${CAP_MODES.join(", ")}`);
|
|
87
|
+
return text;
|
|
88
|
+
}
|
|
89
|
+
/** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
|
|
90
|
+
* Anthropic's 5 (a cache kept that long from its last use; OpenAI's lasts longer). A request later than that is priced
|
|
91
|
+
* with nothing cached. */
|
|
92
|
+
export const CACHE_WARM_MS = 4 * 60_000;
|
|
93
|
+
const tokenCount = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
|
|
94
|
+
/** A request's Previous from the usage it reported (pi's shape: `input` without the cache's reads and writes), its input
|
|
95
|
+
* bound and when it ended; undefined when its usage says no input (a usage not read is zeros, never a count) or a
|
|
96
|
+
* figure is not a count. */
|
|
97
|
+
export function previousOf(usage, boundTokens, endedAt) {
|
|
98
|
+
const [input, read, write, bound] = [tokenCount(usage?.input), tokenCount(usage?.cacheRead ?? 0), tokenCount(usage?.cacheWrite ?? 0), tokenCount(boundTokens)];
|
|
99
|
+
if (input === undefined || read === undefined || write === undefined || bound === undefined || !(input + read + write > 0) || !Number.isFinite(endedAt))
|
|
100
|
+
return undefined;
|
|
101
|
+
return { cachedTokens: read + write, inputTokens: input, boundTokens: bound, endedAt };
|
|
102
|
+
}
|
|
103
|
+
/** The input of a request of `bound` tokens (inputBound) expected after `previous`, at `now`: the previous request's
|
|
104
|
+
* cached input read from the cache, and its input after the cache plus what the body grew by since it (in the bound's
|
|
105
|
+
* own unit, bytes, which a token never is fewer of) at full price. Undefined, the whole input uncached, with no previous
|
|
106
|
+
* request, one that ended CACHE_WARM_MS or more ago, or a clock that reads before its end. On a cache hit of a
|
|
107
|
+
* conversation that grew, what the request is billed for is within this; a miss costs at most its input uncached. */
|
|
108
|
+
export function expectedInput(bound, previous, now) {
|
|
109
|
+
if (!previous)
|
|
110
|
+
return undefined;
|
|
111
|
+
const gap = now - previous.endedAt;
|
|
112
|
+
if (!(gap >= 0 && gap < CACHE_WARM_MS))
|
|
113
|
+
return undefined;
|
|
114
|
+
return { cached: previous.cachedTokens, fresh: previous.inputTokens + Math.max(0, bound - previous.boundTokens) };
|
|
115
|
+
}
|
|
116
|
+
/** The wrap-up's trigger (wrapUpDue): what is left of a cap under this many times a priced request's typical cost. */
|
|
117
|
+
export const WRAP_UP_FACTOR = 3;
|
|
118
|
+
/** The wrap-up's other trigger: what is left under this many times the next request's least admission (its least output
|
|
119
|
+
* at its price: what the cap refuses it below), room for about one more request, so a run whose requests need far more
|
|
120
|
+
* than they cost (a reasoning model's least, Codex's at "high") is told before the cap refuses it. */
|
|
121
|
+
export const WRAP_UP_LEAST_FACTOR = 2;
|
|
122
|
+
/** The output a request is counted at as the wrap-up's typical cost while nothing is priced (step 0): its input bound and
|
|
123
|
+
* this many output tokens at the model's price, never its whole output allowance (the hold), which no turn uses and which
|
|
124
|
+
* made every cap under about $3 on Sonnet 4.5 hear the wrap-up before the run had done anything. The lead's ruling (d),
|
|
125
|
+
* 2026-11-07 (Manuel's retest: every $1 run told at its start). Admission's hold and bound are unchanged. */
|
|
126
|
+
export const WRAP_UP_STEP0_ANSWER_TOKENS = 4_096;
|
|
127
|
+
/** A priced request's typical cost, for the wrap-up's trigger: the median of `costs` (the run's own model's requests, a
|
|
128
|
+
* cost known and above 0) after the first, which writes the cache and costs several warm ones; with one priced request,
|
|
129
|
+
* that one; with none, `nextExpected`, the next request's expected cost (what admission holds it at). No wait for a
|
|
130
|
+
* count of requests: a small cap may never reach one, and that run needs the wrap-up most. */
|
|
131
|
+
export function typicalCost(costs, nextExpected) {
|
|
132
|
+
const priced = costs.filter((usd) => typeof usd === "number" && Number.isFinite(usd) && usd > 0);
|
|
133
|
+
if (priced.length === 0)
|
|
134
|
+
return nextExpected;
|
|
135
|
+
if (priced.length === 1)
|
|
136
|
+
return priced[0];
|
|
137
|
+
const warm = priced.slice(1).sort((a, b) => a - b);
|
|
138
|
+
const mid = Math.floor(warm.length / 2);
|
|
139
|
+
return warm.length % 2 ? warm[mid] : (warm[mid - 1] + warm[mid]) / 2;
|
|
140
|
+
}
|
|
141
|
+
/** Whether a run near its cap is due its wrap-up: what is left (`cap` less `spent` and `held`, as admission counts it)
|
|
142
|
+
* is under WRAP_UP_FACTOR times `typical`, or under WRAP_UP_LEAST_FACTOR times `leastUsd`, the next request's least
|
|
143
|
+
* admission as the cap prices it (CapGuard.leastUsd, Judged.least), when known. The same rule under strict. */
|
|
144
|
+
export function wrapUpDue(cap, spent, held, typical, leastUsd) {
|
|
145
|
+
const leftUsd = cap - spent - held;
|
|
146
|
+
if (!Number.isFinite(leftUsd))
|
|
147
|
+
return undefined;
|
|
148
|
+
const byTypical = Number.isFinite(typical) && leftUsd < WRAP_UP_FACTOR * typical;
|
|
149
|
+
const byLeast = leastUsd !== undefined && Number.isFinite(leastUsd) && leftUsd < WRAP_UP_LEAST_FACTOR * leastUsd;
|
|
150
|
+
return byTypical || byLeast ? { leftUsd } : undefined;
|
|
151
|
+
}
|
|
152
|
+
/** The wrap-up's words, what is left to the cent. `nonePriced`: the run's own model has no priced request yet, so its
|
|
153
|
+
* typical cost is the next request's expected cost and the note can come before the run has done anything (step 0):
|
|
154
|
+
* the words say the budget and ask for a short answer, not a finish. Read from the same priced costs live and in a
|
|
155
|
+
* process opened again (costsIn, ownCosts), so a restart picks the same words. */
|
|
156
|
+
export const wrapUpWords = (leftUsd, nonePriced = false) => {
|
|
157
|
+
const left = centsMoney(Math.max(0, leftUsd));
|
|
158
|
+
return nonePriced ? `This run's budget is about ${left}, enough for little work: answer as soon as you can.` : `About ${left} left of this run's budget: finish now with your answer.`;
|
|
159
|
+
};
|
|
160
|
+
/** A request priced at `price` under `mode`, its input `bound` tokens after `previous` at `now`, plus `feeUsd`: `cost`, what
|
|
161
|
+
* it is held at given its output tokens (its expected input, never more than uncached), and `worst`, its input uncached.
|
|
162
|
+
* The one rule pi's guard (capModels) and another harness's (capBefore) call. */
|
|
163
|
+
export function requestPrice(price, bound, previous, now, mode, feeUsd = 0) {
|
|
164
|
+
const worst = (output) => price({ cached: 0, fresh: bound }, output) + feeUsd;
|
|
165
|
+
const parts = mode === "strict" ? undefined : expectedInput(bound, previous, now);
|
|
166
|
+
if (!parts)
|
|
167
|
+
return { cost: worst, worst };
|
|
168
|
+
return { cost: (output) => Math.min(price(parts, output) + feeUsd, worst(output)), worst };
|
|
169
|
+
}
|
|
54
170
|
/** pi's messages for requests that ended on an error after their response had begun (an event came in first), as the
|
|
55
171
|
* marks (request-start.ts) saw them: each left and the provider may have billed what it generated, so it counts at its
|
|
56
172
|
* hold, as one stopped does. An error before any event (refused at the HTTP level: a 429, a 5xx) counts at its own
|
|
@@ -225,7 +341,7 @@ const notSentHere = (entry) => {
|
|
|
225
341
|
/** The cost an entry adds to what a run spent, as the timeline counts it: a pi answer's total (none for one stopped
|
|
226
342
|
* before its end), and the usd of a cost written apart from an answer, a paid tool's charge among them; 0 for anything
|
|
227
343
|
* else, or for a cost that is not a number (which makes the whole spend unknown, by the timeline's verdict). */
|
|
228
|
-
const costOf = (entry) => {
|
|
344
|
+
export const costOf = (entry) => {
|
|
229
345
|
const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
|
|
230
346
|
const cost = message ? (message.stopReason === "aborted" ? undefined : message.usage?.cost?.total)
|
|
231
347
|
: entry.kind === REQUEST_COST || entry.kind === REQUEST_COST_LATE || entry.kind === TOOL_COST ? entry.data?.usd : undefined;
|
|
@@ -292,28 +408,33 @@ function openFigures(entries) {
|
|
|
292
408
|
* end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the figure its start mark
|
|
293
409
|
* holds (openFigures), each the worst case the cap held for it; without that figure either stays cut, at an unknown
|
|
294
410
|
* cost. A paid call settled at a charge it did not say, like one a crash cut, counts at the figure its mark holds. And
|
|
295
|
-
* this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0.
|
|
296
|
-
|
|
297
|
-
* harness spent beside its harness's own requests and its paid tools, which that harness's booking does not hold. */
|
|
298
|
-
export function spentIn(storeFile, { sides = false } = {}) {
|
|
411
|
+
* this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. */
|
|
412
|
+
export function spentIn(storeFile) {
|
|
299
413
|
if (!existsSync(storeFile))
|
|
300
414
|
return 0;
|
|
301
|
-
|
|
302
|
-
const entries = [];
|
|
303
|
-
// The store's own entries, as read (without the answers written below for a stopped request): openFigures reads them.
|
|
304
|
-
const read = [];
|
|
305
|
-
let marked = false;
|
|
415
|
+
// Fresh, read-only and lock-free (run-db.ts): its process may hold it.
|
|
306
416
|
const rows = [];
|
|
307
|
-
|
|
417
|
+
readRunDbSync(storeFile, false, (db) => {
|
|
418
|
+
// A read made again (its file changed during it) starts from none.
|
|
419
|
+
rows.length = 0;
|
|
308
420
|
for (const row of db.prepare("SELECT record FROM entries ORDER BY rowid").iterate()) {
|
|
309
421
|
const entry = JSON.parse(String(row.record));
|
|
310
|
-
|
|
311
|
-
rows.push(entry);
|
|
422
|
+
rows.push(entry);
|
|
312
423
|
}
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
424
|
+
});
|
|
425
|
+
return spentFrom(rows);
|
|
426
|
+
}
|
|
427
|
+
/** What the run's model requests cost, from its entries in log order: the one computation, shared by spentIn (reading a
|
|
428
|
+
* settled run's own database) and the one-store reader (store-reads, reading A's journal). These readings are the cap's
|
|
429
|
+
* own, on its copy of the entries (the run's shown cost is the timeline's, unchanged): a request stopped before its end
|
|
430
|
+
* counts at the figure its end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the
|
|
431
|
+
* figure its start mark holds (openFigures), each the worst case the cap held for it; without that figure either stays
|
|
432
|
+
* cut, at an unknown cost. This cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. */
|
|
433
|
+
export function spentFrom(rows) {
|
|
434
|
+
// The store's own entries, as read (without the answers written below for a stopped request): openFigures reads them.
|
|
435
|
+
const entries = [];
|
|
436
|
+
const read = [];
|
|
437
|
+
let marked = false;
|
|
317
438
|
// pi's error entry for a request that ended on an error after its response began is left out, as an aborted one is: its
|
|
318
439
|
// end mark (`error`) counts it at its hold. pi writes the entry as the mark is written, before it or after, so each such
|
|
319
440
|
// mark takes the nearest error entry not yet taken among those after the earliest start holding its figure (a request's
|
|
@@ -441,6 +562,108 @@ export function spentIn(storeFile, { sides = false } = {}) {
|
|
|
441
562
|
return null;
|
|
442
563
|
return entries.reduce((sum, entry) => sum + costOf(entry), 0);
|
|
443
564
|
}
|
|
565
|
+
/** A workflow decision's charge as the cap counted it (decision-cap.ts): `call` names the request, `usd` what it charged,
|
|
566
|
+
* or its hold when it said none. The run's shown cost reads its decisions from their receipts; this is the cap's own
|
|
567
|
+
* reading, kept so a later process counts each decision as this one did. costOf counts none, so nothing counts twice. */
|
|
568
|
+
export const DECISION_COST = "agentrun.decision_cost";
|
|
569
|
+
/** A decision request's hold, kept before it is sent (decision-cap.ts): with no DECISION_COST after it, its process died
|
|
570
|
+
* while it was out, and it counts at this figure. */
|
|
571
|
+
export const DECISION_HOLD = "agentrun.decision_hold";
|
|
572
|
+
/** What a workflow run's decisions cost, in its store: what the next process adds to spentIn's reading. Per decision
|
|
573
|
+
* (its id):
|
|
574
|
+
* - booked (DECISION_COST entries, at its charge, its hold, or $0 for nothing charged): the larger of what was booked,
|
|
575
|
+
* with any hold no booking ended, and what its receipts say it cost (the costs the timeline's decision rows sum);
|
|
576
|
+
* - else, with a receipt that names its charge: that charge (its booking lost after the receipt);
|
|
577
|
+
* - else, with a hold (DECISION_HOLD, kept once the driver admitted the request, right before its send): that hold, the
|
|
578
|
+
* figure the live process held, since the request may have been out when its process died; never $0;
|
|
579
|
+
* - else nothing: no hold is kept before the admission, so a request never sent is never counted.
|
|
580
|
+
* A booking with no decision id is counted as it is. */
|
|
581
|
+
export function decisionSpentIn(storeFile) {
|
|
582
|
+
const booked = new Map();
|
|
583
|
+
/** The decisions with any booking, a $0 one included. */
|
|
584
|
+
const ended = new Set();
|
|
585
|
+
/** Each decision's holds kept and not yet followed by a booking, in order. */
|
|
586
|
+
const open = new Map();
|
|
587
|
+
let loose = 0;
|
|
588
|
+
for (const entry of entriesIn(storeFile)) {
|
|
589
|
+
if (entry.kind !== DECISION_COST && entry.kind !== DECISION_HOLD)
|
|
590
|
+
continue;
|
|
591
|
+
const data = entry.data;
|
|
592
|
+
const usd = figureOf(data?.usd);
|
|
593
|
+
const id = typeof data?.decision === "string" ? data.decision : undefined;
|
|
594
|
+
if (entry.kind === DECISION_HOLD) {
|
|
595
|
+
if (id !== undefined && usd !== undefined)
|
|
596
|
+
open.set(id, [...(open.get(id) ?? []), usd]);
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
// A booking ends its decision's oldest hold still open, whatever it charged ($0 for nothing sent).
|
|
600
|
+
if (id !== undefined) {
|
|
601
|
+
ended.add(id);
|
|
602
|
+
open.get(id)?.shift();
|
|
603
|
+
}
|
|
604
|
+
if (usd === undefined || !(usd > 0))
|
|
605
|
+
continue;
|
|
606
|
+
if (id !== undefined)
|
|
607
|
+
booked.set(id, (booked.get(id) ?? 0) + usd);
|
|
608
|
+
else
|
|
609
|
+
loose += usd;
|
|
610
|
+
}
|
|
611
|
+
const receipted = new Map();
|
|
612
|
+
let receipts = [];
|
|
613
|
+
// Receipts that cannot be read leave the bookings alone to say it.
|
|
614
|
+
if (existsSync(storeFile))
|
|
615
|
+
try {
|
|
616
|
+
receipts = durableDecisions(storeFile, { unlocked: true });
|
|
617
|
+
}
|
|
618
|
+
catch {
|
|
619
|
+
receipts = [];
|
|
620
|
+
}
|
|
621
|
+
for (const receipt of receipts) {
|
|
622
|
+
const usd = figureOf(receipt.cost_usd);
|
|
623
|
+
// A stored receipt row names its decision `decision_id` (agentrun-pi decision-recovery.ts rowOf).
|
|
624
|
+
const id = typeof receipt.decision_id === "string" ? receipt.decision_id : typeof receipt.id === "string" ? receipt.id : undefined;
|
|
625
|
+
if (id !== undefined && usd !== undefined && usd > 0)
|
|
626
|
+
receipted.set(id, (receipted.get(id) ?? 0) + usd);
|
|
627
|
+
}
|
|
628
|
+
let sum = loose;
|
|
629
|
+
for (const id of new Set([...ended, ...booked.keys(), ...receipted.keys(), ...open.keys()])) {
|
|
630
|
+
const held = (open.get(id) ?? []).reduce((total, usd) => total + (usd > 0 ? usd : 0), 0);
|
|
631
|
+
if (ended.has(id))
|
|
632
|
+
sum += Math.max((booked.get(id) ?? 0) + held, receipted.get(id) ?? 0);
|
|
633
|
+
else if (receipted.has(id))
|
|
634
|
+
sum += receipted.get(id);
|
|
635
|
+
else
|
|
636
|
+
sum += held;
|
|
637
|
+
}
|
|
638
|
+
return sum;
|
|
639
|
+
}
|
|
640
|
+
/** The entries of the run's store, in order (none when it has no store yet). */
|
|
641
|
+
function entriesIn(storeFile) {
|
|
642
|
+
if (!existsSync(storeFile))
|
|
643
|
+
return [];
|
|
644
|
+
// Fresh, read-only and lock-free (run-db.ts), as spentIn reads it.
|
|
645
|
+
const rows = [];
|
|
646
|
+
readRunDbSync(storeFile, false, (db) => {
|
|
647
|
+
rows.length = 0;
|
|
648
|
+
for (const row of db.prepare("SELECT record FROM entries ORDER BY rowid").iterate())
|
|
649
|
+
rows.push(JSON.parse(String(row.record)));
|
|
650
|
+
});
|
|
651
|
+
return rows;
|
|
652
|
+
}
|
|
653
|
+
/** The priced answers of `model` (its id) in the run's store, in order: what the wrap-up's typical cost reads from earlier
|
|
654
|
+
* processes (capModels' `wrapUp`). An answer whose cost is unknown or $0, or that was stopped or failed, is none. */
|
|
655
|
+
export function costsIn(storeFile, model) {
|
|
656
|
+
return entriesIn(storeFile).flatMap((entry) => {
|
|
657
|
+
const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
|
|
658
|
+
const total = message?.usage?.cost?.total;
|
|
659
|
+
return message?.model === model && message.stopReason !== "error" && message.stopReason !== "aborted" && typeof total === "number" && Number.isFinite(total) && total > 0 ? [total] : [];
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
/** Whether the run was told its wrap-up under `cap` already (a CAP_WRAPUP entry of that cap): once per cap, across its
|
|
663
|
+
* processes; a raise's new cap re-arms it. */
|
|
664
|
+
export function wrapUpSentIn(storeFile, cap) {
|
|
665
|
+
return entriesIn(storeFile).some((entry) => entry.kind === CAP_WRAPUP && typeof entry.data?.capUsd === "number" && Math.abs(entry.data.capUsd - cap) <= CAP_TOLERANCE);
|
|
666
|
+
}
|
|
444
667
|
export function metersIn(storeFile) {
|
|
445
668
|
const { known: _, ...meters } = meterFiguresIn(storeFile);
|
|
446
669
|
return meters;
|
|
@@ -451,43 +674,44 @@ export function metersIn(storeFile) {
|
|
|
451
674
|
export function meterFiguresIn(storeFile) {
|
|
452
675
|
if (!existsSync(storeFile))
|
|
453
676
|
return { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
const
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
known.tokens = usage ? (usage.usage?.usd ?? usage.usage?.so_far_usd ?? 0) : 0;
|
|
485
|
-
const notMetered = usage?.usage?.not_metered;
|
|
486
|
-
return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0, browser, others: otherTools, known, ...(notMetered ? { notMetered } : {}) };
|
|
487
|
-
}
|
|
488
|
-
finally {
|
|
489
|
-
db.close();
|
|
677
|
+
return readRunDbSync(storeFile, false, (db) => meterFiguresFrom(db.prepare("SELECT conversation_id AS conversation, record FROM entries ORDER BY rowid").all().map((row) => ({ conversation: Number(row.conversation), entry: JSON.parse(String(row.record)) }))));
|
|
678
|
+
}
|
|
679
|
+
/** meterFiguresIn's figures from a run's entries by conversation, in log order: the one computation, shared by
|
|
680
|
+
* meterFiguresIn (reading a settled run's own database) and the one-store reader (store-reads/cap.ts metersOverStore, over
|
|
681
|
+
* A's journal). Only where the entries come from changes; the figures do not (the money-parity rule), as spentFrom is to
|
|
682
|
+
* spentIn. A paid tool's charge reaches it as the TOOL_COST / TOOL_UNMETERED the store reader folds back in from the
|
|
683
|
+
* paid-tools session (store-reads/journal.ts withPaidCosts), as the file-backed run's root held each natively. */
|
|
684
|
+
export function meterFiguresFrom(rows) {
|
|
685
|
+
const root = rows.reduce((min, row) => Math.min(min, row.conversation), Infinity);
|
|
686
|
+
const marks = new Set();
|
|
687
|
+
const charges = [];
|
|
688
|
+
const browser = { usd: 0, seconds: 0 };
|
|
689
|
+
const others = [];
|
|
690
|
+
// Each meter's known dollars, whether or not one of its charges is unknown: what a run of unknown cost is known to
|
|
691
|
+
// have spent on it (server.ts /usage).
|
|
692
|
+
const known = { tokens: 0, browser: 0, others: 0 };
|
|
693
|
+
for (const { entry } of rows) {
|
|
694
|
+
const data = (entry.data ?? {});
|
|
695
|
+
if (entry.kind === TOOL_STARTED)
|
|
696
|
+
marks.add(data.call);
|
|
697
|
+
else if (entry.kind === TOOL_COST)
|
|
698
|
+
marks.delete(data.call), charges.push(figureOf(data.usd));
|
|
699
|
+
if (entry.kind === TOOL_COST && data.tool !== "browser")
|
|
700
|
+
others.push(figureOf(data.usd)), (known.others += figureOf(data.usd) ?? 0);
|
|
701
|
+
if (entry.kind !== TOOL_COST || data.tool !== "browser")
|
|
702
|
+
continue;
|
|
703
|
+
const usd = figureOf(data.usd);
|
|
704
|
+
known.browser += usd ?? 0;
|
|
705
|
+
browser.usd = browser.usd === null || usd === undefined ? null : browser.usd + usd;
|
|
706
|
+
browser.seconds += figureOf(data.seconds) ?? 0;
|
|
490
707
|
}
|
|
708
|
+
const tools = marks.size || charges.some((usd) => usd === undefined) ? null : charges.reduce((sum, usd) => sum + usd, 0);
|
|
709
|
+
const rest = rows.filter(({ conversation, entry }) => conversation === root && entry.kind !== TOOL_STARTED && entry.kind !== TOOL_COST).map(({ entry }) => entry);
|
|
710
|
+
const usage = timelineOf(rest, { settled: true }).find((row) => row.kind === "usage");
|
|
711
|
+
const otherTools = marks.size || others.some((usd) => usd === undefined) ? null : others.reduce((sum, usd) => sum + usd, 0);
|
|
712
|
+
known.tokens = usage ? (usage.usage?.usd ?? usage.usage?.so_far_usd ?? 0) : 0;
|
|
713
|
+
const notMetered = usage?.usage?.not_metered;
|
|
714
|
+
return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0, browser, others: otherTools, known, ...(notMetered ? { notMetered } : {}) };
|
|
491
715
|
}
|
|
492
716
|
/** What the paid tools of `entries` (TOOL_STARTED and TOOL_COST) spent, as the cap counts it: each charge, and a call
|
|
493
717
|
* settled at a charge it did not say, or a crash cut (marked, never settled), at its held figure, as spentIn counts it;
|
|
@@ -519,20 +743,23 @@ export function holdsInFlight() {
|
|
|
519
743
|
total: () => [...holds.values()].reduce((sum, usd) => sum + usd, 0),
|
|
520
744
|
};
|
|
521
745
|
}
|
|
746
|
+
/** Where a refusal of the cap inside a workflow call node's effect is told (app.ts runEffect): the call ends on it and
|
|
747
|
+
* waits for a raise, never handed back as the tool's own failure, which a collecting map would take as the item's. A
|
|
748
|
+
* paid call refused there leaves no refusal for a model's next request (takePaidRefusal): no model turn follows it. */
|
|
749
|
+
export const capRefusals = new AsyncLocalStorage();
|
|
522
750
|
let runSpend;
|
|
523
751
|
let paying = Promise.resolve();
|
|
752
|
+
/** The run's spend this process counts, when it has a cap: for a workflow run's waits and decisions (app.ts). */
|
|
753
|
+
export const runSpendNow = () => runSpend;
|
|
524
754
|
export const useSpend = (spend) => {
|
|
525
755
|
runSpend = spend;
|
|
526
756
|
// A paid call's refusal is its own spend's (its run's): another spend starts with none.
|
|
527
757
|
paidRoomRefusal = undefined;
|
|
528
758
|
};
|
|
529
|
-
/** Each paid call sent under the cap and not settled, at what it is held at
|
|
530
|
-
* model requests in flight too (capModels' `joined`). */
|
|
759
|
+
/** Each paid call sent under the cap and not settled, at what it is held at. */
|
|
531
760
|
const paidOpen = new Set();
|
|
532
761
|
/** What the paid calls under way are held at, together (0 when none is): the one figure every check of the run's cap
|
|
533
|
-
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall).
|
|
534
|
-
* harness the run's own model requests in flight (a learned workflow's, a hosted search's) are held here too, so the
|
|
535
|
-
* harness's check sees them. */
|
|
762
|
+
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). */
|
|
536
763
|
export const paidHolds = () => [...paidOpen].reduce((sum, { usd }) => sum + usd, 0);
|
|
537
764
|
/** A paid hold that outlives the paidCall that took it (a browser session's, browser-cost.ts), counted in paidHolds as a
|
|
538
765
|
* call's is until `drop`: its figure is `usd`, which its owner moves as charges use it. */
|
|
@@ -546,11 +773,6 @@ export const keepHold = (usd) => {
|
|
|
546
773
|
export const addSpend = (usd) => runSpend?.add(usd);
|
|
547
774
|
/** The run's cap, when it has one. */
|
|
548
775
|
export const runCap = () => runSpend?.cap;
|
|
549
|
-
/** On another harness, what the run's own model requests (capModels' `joined`) have cost: those of earlier processes
|
|
550
|
-
* (spentIn's `sides`) and this one's; null once one is unknown. 0 on pi, where the run's one capModels counts them. */
|
|
551
|
-
let sidesSpent = 0;
|
|
552
|
-
/** What sidesSpent says: the harness's check adds it to what its booking says the run spent (harness-app.ts). */
|
|
553
|
-
export const sideSpend = () => sidesSpent;
|
|
554
776
|
/** `call`, a paid tool's (`name`), under the run's cap, by the rule a model request keeps: refused, in words that name
|
|
555
777
|
* its price and the cap and never calling it, unless what the run has spent plus what the call is held at (`hold`: its
|
|
556
778
|
* quote, else an allowance, `basis` saying which) fits the cap, and whenever the spend is unknown; else run, one paid
|
|
@@ -573,22 +795,34 @@ export function takePaidRefusal(owner) {
|
|
|
573
795
|
paidRoomRefusal = undefined;
|
|
574
796
|
return { words: refusal.words, figures: refusal.figures };
|
|
575
797
|
}
|
|
576
|
-
export async function paidCall(name, call, charge, hold) {
|
|
798
|
+
export async function paidCall(name, call, charge, hold, options = {}) {
|
|
577
799
|
const spend = runSpend;
|
|
578
800
|
if (!spend)
|
|
579
801
|
return { result: await call() };
|
|
580
802
|
const turn = paying.then(async () => {
|
|
581
803
|
const read = await spend.spent();
|
|
582
|
-
if (read === null)
|
|
583
|
-
|
|
804
|
+
if (read === null) {
|
|
805
|
+
const text = `${SPEND_CAP_REACHED}: ${name} was not sent. What the run has spent is unknown, so its cap of ${money(spend.cap)} cannot be kept: the run is out of budget.`;
|
|
806
|
+
capRefusals.getStore()?.({ words: text.slice(`${SPEND_CAP_REACHED}: `.length), room: false, capUsd: spend.cap });
|
|
807
|
+
return { refused: text };
|
|
808
|
+
}
|
|
584
809
|
// What is held for requests and calls still answering, apart from what was spent, as a model request's refusal says it.
|
|
585
810
|
const holding = (spend.held?.() ?? 0) + paidHolds();
|
|
586
811
|
// Written so that a figure that is not a number refuses.
|
|
587
812
|
if (!(read + holding + hold.usd <= spend.cap + FIT_TOLERANCE)) {
|
|
588
|
-
// Refused for room: a raise would send it, so the run pauses at the model's next request (takePaidRefusal).
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
813
|
+
// Refused for room: a raise would send it, so the run pauses at the model's next request (takePaidRefusal). Its
|
|
814
|
+
// words and the least cap that sends it (leastCapUsd) are one figure, which the pause carries to its mark and serves.
|
|
815
|
+
const refusal = paidRefusal(spend.cap, read, holding, name, hold);
|
|
816
|
+
const room = { words: refusal.text.slice(`${SPEND_CAP_REACHED}: `.length), figures: { spentUsd: read + holding, needsUsd: hold.usd, leastCapUsd: refusal.leastCapUsd } };
|
|
817
|
+
// `pauses: false`: no step of the run's own (a person's take-over of its browser), so neither a workflow's call nor the
|
|
818
|
+
// model's next request is told: the run goes on unpaused.
|
|
819
|
+
// Inside a workflow's call node: the call is told, and ends on it. Else the model's next request is refused in its words.
|
|
820
|
+
const told = options.pauses !== false ? capRefusals.getStore() : undefined;
|
|
821
|
+
if (told)
|
|
822
|
+
told({ ...room, room: true, capUsd: spend.cap });
|
|
823
|
+
else if (options.pauses !== false)
|
|
824
|
+
paidRoomRefusal = { owner: spend, ...room };
|
|
825
|
+
return { refused: refusal.text, leastCapUsd: refusal.leastCapUsd };
|
|
592
826
|
}
|
|
593
827
|
// Held from here; settled into the spend in the same step that lets the hold go, so no check between sees neither.
|
|
594
828
|
const open = { usd: hold.usd };
|
|
@@ -611,6 +845,39 @@ export async function paidCall(name, call, charge, hold) {
|
|
|
611
845
|
paying = turn.catch(() => undefined);
|
|
612
846
|
return turn;
|
|
613
847
|
}
|
|
848
|
+
export async function holdPaid(name, hold, signal) {
|
|
849
|
+
for (;;) {
|
|
850
|
+
const spend = runSpend;
|
|
851
|
+
if (!spend)
|
|
852
|
+
return { ticket: { settle: () => undefined, drop: () => undefined } };
|
|
853
|
+
const turn = paying.then(async () => {
|
|
854
|
+
const read = await spend.spent();
|
|
855
|
+
if (read === null)
|
|
856
|
+
return { refused: { words: `${name} was not sent. What the run has spent is unknown, so its cap of ${money(spend.cap)} cannot be kept: the run is out of budget.`, room: false, capUsd: spend.cap } };
|
|
857
|
+
const holding = (spend.held?.() ?? 0) + paidHolds();
|
|
858
|
+
if (!(read + holding + hold.usd <= spend.cap + FIT_TOLERANCE)) {
|
|
859
|
+
const refusal = paidRefusal(spend.cap, read, holding, name, hold);
|
|
860
|
+
return { refused: { words: refusal.text.slice(`${SPEND_CAP_REACHED}: `.length), room: true, capUsd: spend.cap, figures: { spentUsd: read + holding, needsUsd: hold.usd, leastCapUsd: refusal.leastCapUsd } } };
|
|
861
|
+
}
|
|
862
|
+
// Held from here, in the same step as the check, so no other check between sees neither.
|
|
863
|
+
const open = { usd: hold.usd };
|
|
864
|
+
paidOpen.add(open);
|
|
865
|
+
let done = false;
|
|
866
|
+
return { ticket: {
|
|
867
|
+
settle: (usd) => { if (done)
|
|
868
|
+
return; done = true; spend.add(usd ?? hold.usd); paidOpen.delete(open); },
|
|
869
|
+
drop: () => { if (done)
|
|
870
|
+
return; done = true; paidOpen.delete(open); },
|
|
871
|
+
} };
|
|
872
|
+
});
|
|
873
|
+
paying = turn.catch(() => undefined);
|
|
874
|
+
const held = await turn;
|
|
875
|
+
if (!("refused" in held) || !held.refused.room || !spend.wait || signal?.aborted)
|
|
876
|
+
return held;
|
|
877
|
+
if (!(await spend.wait(held.refused, signal)))
|
|
878
|
+
return held;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
614
881
|
/** The most output tokens one request may take: the model's ceiling, else its context window. A thinking budget can
|
|
615
882
|
* raise a request's ceiling up to the model's, whatever maxTokens it asked for. */
|
|
616
883
|
export const ceilingTokens = (model) => (model.maxTokens > 0 ? model.maxTokens : model.contextWindow);
|
|
@@ -638,11 +905,11 @@ const unmeasured = (cap) => `${SPEND_CAP_REACHED}: Not sent: the size of the nex
|
|
|
638
905
|
const noPrice = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no price here, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
|
|
639
906
|
const noCeiling = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no output ceiling here and its output is priced, so what a request may cost has no bound and the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
|
|
640
907
|
const unknownSpend = (cap) => `${SPEND_CAP_REACHED}: Not sent: what the run has spent is unknown, so its cap of ${money(cap)} cannot be kept: the run is out of budget.`;
|
|
641
|
-
/** A request's
|
|
642
|
-
* `output` tokens at
|
|
643
|
-
function
|
|
908
|
+
/** A request's price at `model`'s rates: its input's cached tokens at the cache-read price and its fresh ones at the
|
|
909
|
+
* dearer of the input and cache-write prices, and `output` tokens at the output price. */
|
|
910
|
+
function priceOf(calculateCost, model) {
|
|
644
911
|
const priced = (tokens) => calculateCost(model, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, ...tokens, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }).total;
|
|
645
|
-
return (
|
|
912
|
+
return ({ cached, fresh }, output) => Math.max(priced({ input: fresh, cacheRead: cached, output }), priced({ cacheWrite: fresh, cacheRead: cached, output }));
|
|
646
913
|
}
|
|
647
914
|
/** An amount in words: two decimals, or as many as it takes (up to eight) to show it whole ($0.50, $0.105, $0.0005). */
|
|
648
915
|
export function money(usd) {
|
|
@@ -658,44 +925,62 @@ export function money(usd) {
|
|
|
658
925
|
* which pi-ai's retry (isRetryableAssistantError, which reads only an error's text) takes as final whatever digits the
|
|
659
926
|
* words after it hold. The words after it are the ones a person reads. */
|
|
660
927
|
export const CAP_REFUSAL_CODE = `${SPEND_CAP_REACHED} (out of budget): `;
|
|
928
|
+
/** A refusal's figures as its start mark keeps them (`spentUsd`, `needsUsd`, `leastCapUsd`, and `boundUsd` when above 0);
|
|
929
|
+
* none without. */
|
|
930
|
+
export const refusalFields = (figures) => figures ? { spentUsd: figures.spentUsd, needsUsd: figures.needsUsd, leastCapUsd: figures.leastCapUsd, ...(typeof figures.boundUsd === "number" && figures.boundUsd > 0 ? { boundUsd: figures.boundUsd } : {}) } : {};
|
|
661
931
|
/** The words of a refusal for room (CAP_REFUSAL_CODE: what is left of the cap cannot buy the request's least), which a
|
|
662
932
|
* higher cap would send; undefined for any other text, a refusal no cap could fix included (an unknown spend, no price,
|
|
663
933
|
* no output ceiling, an input not measured: the bare `spend_cap_reached: ` code). The one reader of that difference. */
|
|
664
934
|
export const roomRefusal = (text) => (text?.startsWith(CAP_REFUSAL_CODE) ? text.slice(CAP_REFUSAL_CODE.length) : undefined);
|
|
665
|
-
/** A model's name as the words say it: the catalog's, without a vendor's prefix ("Anthropic: Claude Sonnet 5.5" reads
|
|
666
|
-
* "Claude Sonnet 5.5"), else its id. */
|
|
667
|
-
export const nameOf = (model) => (model.name || model.id).replace(/^[^:]{1,40}:\s+(?=\S)/, "");
|
|
668
935
|
/** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
|
|
669
936
|
// Cents rounded up within the tail the fit check allows (FIT_TOLERANCE), no wider: a total past a cent by more than a
|
|
670
937
|
// float's own tail rounds to the cent above, so the cap a refusal names admits what it refused.
|
|
671
938
|
export const leastMoney = (usd) => `$${(Math.ceil(usd * 100 - FIT_TOLERANCE * 100) / 100).toFixed(2)}`;
|
|
672
939
|
/** The cap to raise to for a request past `cap` that needs `total` in all: a cent at least, and above the cap, never
|
|
673
940
|
* the cap itself, so a raise to it is one PATCH /runs/{id} takes. */
|
|
674
|
-
export const raiseTo = (cap, total) => {
|
|
941
|
+
export const raiseTo = (cap, total) => `$${raiseFigure(cap, total).toFixed(2)}`;
|
|
942
|
+
/** raiseTo's cap as a number, whole cents in dollars: the figure a refusal carries beside its words (leastCapUsd). */
|
|
943
|
+
export const raiseFigure = (cap, total) => {
|
|
675
944
|
const cents = Math.ceil(total * 100 - FIT_TOLERANCE * 100);
|
|
676
|
-
return
|
|
945
|
+
return (cents / 100 > cap + CAP_TOLERANCE ? cents : Math.floor((cap + CAP_TOLERANCE) * 100) + 1) / 100;
|
|
677
946
|
};
|
|
678
|
-
/** The cap's refusal of a request what is left of it cannot buy the least of, in plain words with the numbers
|
|
679
|
-
* the run spent (and holds for
|
|
680
|
-
*
|
|
681
|
-
*
|
|
682
|
-
|
|
683
|
-
|
|
947
|
+
/** The cap's refusal of a request what is left of it cannot buy the least of, in plain words with the numbers, as a
|
|
948
|
+
* person who has never seen a model request reads them: what the run spent (and holds for steps still running) of its
|
|
949
|
+
* cap, what the next step needs at the least, and the cap that lets it continue (spent, held and that least, rounded
|
|
950
|
+
* up to the cent, so that it is enough). No model's name: a run is many requests, and "the next step" is the one that
|
|
951
|
+
* waits. After its code (CAP_REFUSAL_CODE), which keeps it final to pi-ai's retry. Its figures beside the words. */
|
|
952
|
+
function capRefusal(cap, spent, held, least) {
|
|
953
|
+
// The raise its words name and the figure it carries are one number (leastCapUsd), so the two never drift.
|
|
954
|
+
const leastCapUsd = raiseFigure(cap, spent + held + least);
|
|
955
|
+
const figures = { spentUsd: spent + held, needsUsd: least, leastCapUsd };
|
|
956
|
+
const [need, raise] = [leastMoney(least), `$${leastCapUsd.toFixed(2)}`];
|
|
684
957
|
if (spent === 0 && held === 0)
|
|
685
|
-
return `${CAP_REFUSAL_CODE}Not sent: this run's cap
|
|
686
|
-
|
|
687
|
-
return `${CAP_REFUSAL_CODE}Not sent: the run has ${owes}, and its next ${name} request needs at least ${need}. Raise the cap to at least ${raise} to run it.`;
|
|
958
|
+
return { text: `${CAP_REFUSAL_CODE}Not sent: the next step needs at least ${need}, and this run's cap is ${money(cap)}. Raise the cap to at least ${raise} to continue.`, figures };
|
|
959
|
+
return { text: `${CAP_REFUSAL_CODE}Not sent: this run has ${spentOf(spent, held, cap)}, and the next step needs at least ${need}. Raise the cap to at least ${raise} to continue.`, figures };
|
|
688
960
|
}
|
|
961
|
+
/** A guard's answer for a refusal for room: its words, and its figures beside them (harness-app.ts keeps them on its mark). */
|
|
962
|
+
const refuseFor = ({ text, figures }) => ({ refuse: text, ...figures });
|
|
963
|
+
/** capModels' judgement for a refusal for room: its words, and its figures for its start mark (request-start.ts). */
|
|
964
|
+
const whyOf = ({ text, figures }) => ({ why: text, figures });
|
|
965
|
+
/** What a run has spent of its cap, in a refusal's words: and what it holds for steps still running, when that is a cent
|
|
966
|
+
* or more. Each in cents (centsMoney), as the figures after it are; the exact amounts are the refusal's figures
|
|
967
|
+
* (RefusalFigures, the pause's spent_usd). */
|
|
968
|
+
const spentOf = (spent, held, cap) => {
|
|
969
|
+
const holds = centsMoney(held);
|
|
970
|
+
return holds !== "$0" ? `spent ${centsMoney(spent)} and holds ${holds} for steps still running, of its ${money(cap)} cap` : `spent ${centsMoney(spent)} of its ${money(cap)} cap`;
|
|
971
|
+
};
|
|
972
|
+
/** An amount in words, to the nearest cent ($0.0237416 is $0.02), as money says it ($1, $0.20, $0). */
|
|
973
|
+
export const centsMoney = (usd) => money(Math.round(usd * 100) / 100);
|
|
689
974
|
/** The cap's refusal of a paid call (paidCall) what is left of it cannot hold, in one sentence, as capRefusal says a model
|
|
690
975
|
* request's: what the run spent (and holds for requests and calls still answering) of its cap, what the call could cost
|
|
691
976
|
* and why, and the cap that would run it: spent, held and the call's figure, rounded up to the cent, and a cent above the
|
|
692
|
-
* cap at the least, since a figure past the cap by less than a cent still needs more than the cap.
|
|
693
|
-
* the raise by
|
|
977
|
+
* cap at the least, since a figure past the cap by less than a cent still needs more than the cap. What was spent and held
|
|
978
|
+
* in cents (spentOf), the call's figure and the cap by money, the raise by raiseFigure. */
|
|
694
979
|
function paidRefusal(cap, spent, held, name, hold) {
|
|
695
|
-
|
|
696
|
-
//
|
|
697
|
-
const
|
|
698
|
-
return `${SPEND_CAP_REACHED}: Not sent:
|
|
980
|
+
// The model refusal's rule (raiseFigure): a cent at least, and above the cap, never the cap itself; one number, which its
|
|
981
|
+
// words name and its refusal carries. The same words: the call is the next step, named as the tool.
|
|
982
|
+
const leastCapUsd = raiseFigure(cap, spent + held + hold.usd);
|
|
983
|
+
return { text: `${SPEND_CAP_REACHED}: Not sent: this run has ${spentOf(spent, held, cap)}, and the next step, ${name}, could cost up to ${money(hold.usd)} (${hold.basis}). Raise the cap to at least $${leastCapUsd.toFixed(2)} to continue.`, leastCapUsd };
|
|
699
984
|
}
|
|
700
985
|
/** The most output tokens from `least` to `asked` whose request costs no more than `left` (`cost`, its price at that
|
|
701
986
|
* many, rising with them); undefined when even `least` costs more. A search, so that a price with tiers is exact. */
|
|
@@ -724,17 +1009,17 @@ export function leastOutput(model, thinking, budgetOf) {
|
|
|
724
1009
|
return ANSWER_TOKENS_LEAST;
|
|
725
1010
|
return ANSWER_TOKENS_LEAST + (BUDGET_APIS.has(model.api) ? THINKING_BUDGET_LEAST : budgetOf(thinking));
|
|
726
1011
|
}
|
|
727
|
-
/** A run on another harness: before each request, what the run has spent, plus
|
|
728
|
-
*
|
|
729
|
-
*
|
|
730
|
-
* with spend_cap_reached. Admitted, it is limited to the most output what is left buys (`outputTokensMax`, at
|
|
731
|
-
* it asks for and its model's ceiling), which the model proxy writes into its body:
|
|
732
|
-
*
|
|
733
|
-
*
|
|
734
|
-
*
|
|
735
|
-
*
|
|
736
|
-
*
|
|
737
|
-
export async function capBefore(cap, model, { listed = true } = {}) {
|
|
1012
|
+
/** A run on another harness: before each request, what the run has spent, plus what each request still in flight was
|
|
1013
|
+
* admitted at, must leave room for this request at its least output (1,024 tokens, or what its body says it needs to
|
|
1014
|
+
* think and answer; what it asks for when that is fewer), its input priced by requestPrice under `mode`, else the request
|
|
1015
|
+
* is refused with spend_cap_reached. Admitted, it is limited to the most output what is left buys (`outputTokensMax`, at
|
|
1016
|
+
* most what it asks for and its model's ceiling), which the model proxy writes into its body: output never passes the
|
|
1017
|
+
* cap. A request is priced at the run model's price, as on pi (a request on a cheaper model is held at that price too,
|
|
1018
|
+
* which only refuses sooner). What cannot be kept within a cap is refused under one: a spend that is unknown (a request a
|
|
1019
|
+
* crash cut), an input that could not be measured, a model serve has no price for (`listed: false`, or none at all),
|
|
1020
|
+
* and a model whose output is priced and that has no output ceiling. With no cap, nothing is refused. `now`: the clock a
|
|
1021
|
+
* previous request's end is read against. */
|
|
1022
|
+
export async function capBefore(cap, model, { listed = true, mode = "expected", now = Date.now } = {}) {
|
|
738
1023
|
if (cap === undefined)
|
|
739
1024
|
return undefined;
|
|
740
1025
|
if (model === undefined || !listed)
|
|
@@ -742,31 +1027,49 @@ export async function capBefore(cap, model, { listed = true } = {}) {
|
|
|
742
1027
|
const output = outputBound(model);
|
|
743
1028
|
if (output === undefined)
|
|
744
1029
|
return { beforeRequest: () => ({ refuse: noCeiling(cap) }) };
|
|
745
|
-
const price =
|
|
746
|
-
const
|
|
747
|
-
|
|
1030
|
+
const price = priceOf((await import("@earendil-works/pi-ai")).calculateCost, model);
|
|
1031
|
+
const held = (request) => request.holdUsd ?? price({ cached: 0, fresh: request.inputTokensMax }, request.outputTokensMax ?? output);
|
|
1032
|
+
/** A request priced by the one rule (requestPrice): its cost at an output, and the output it asks, needs at least, and
|
|
1033
|
+
* is typically answered in at step 0 (WRAP_UP_STEP0_ANSWER_TOKENS, at most what it asks). */
|
|
1034
|
+
const pricedOf = ({ inputTokensMax, outputTokensAsked, outputTokensLeast, previous }) => {
|
|
1035
|
+
const priced = requestPrice(price, inputTokensMax, previous, now(), mode);
|
|
1036
|
+
const asked = Math.min(outputTokensAsked ?? output, output);
|
|
1037
|
+
return { priced, asked, least: Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked), step0: Math.min(WRAP_UP_STEP0_ANSWER_TOKENS, asked) };
|
|
1038
|
+
};
|
|
1039
|
+
const measured = (request) => typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax);
|
|
748
1040
|
return {
|
|
749
|
-
|
|
1041
|
+
leastUsd(request) {
|
|
1042
|
+
if (!measured(request))
|
|
1043
|
+
return undefined;
|
|
1044
|
+
const { priced, least } = pricedOf(request);
|
|
1045
|
+
return priced.cost(output === 0 ? 0 : least);
|
|
1046
|
+
},
|
|
1047
|
+
typicalUsd(request) {
|
|
1048
|
+
if (!measured(request))
|
|
1049
|
+
return undefined;
|
|
1050
|
+
const { priced, step0 } = pricedOf(request);
|
|
1051
|
+
return priced.cost(output === 0 ? 0 : step0);
|
|
1052
|
+
},
|
|
1053
|
+
beforeRequest({ spentUsd, inFlight, inputTokensMax, outputTokensAsked, outputTokensLeast, previous }) {
|
|
750
1054
|
if (spentUsd === null)
|
|
751
1055
|
return { refuse: unknownSpend(cap) };
|
|
752
1056
|
const inputs = [inputTokensMax, ...inFlight.map((request) => request.inputTokensMax)];
|
|
753
1057
|
if (inputs.some((input) => typeof input !== "number" || !Number.isFinite(input)))
|
|
754
1058
|
return { refuse: unmeasured(cap) };
|
|
755
|
-
// Its requests in flight at
|
|
1059
|
+
// Its requests in flight at what each was admitted at, and its paid calls under way at what they are held at.
|
|
756
1060
|
const holding = inFlight.reduce((sum, request) => sum + held(request), paidHolds());
|
|
757
1061
|
const left = cap - spentUsd - holding;
|
|
758
|
-
const
|
|
1062
|
+
const { priced, asked, least } = pricedOf({ inputTokensMax, outputTokensAsked, outputTokensLeast, previous });
|
|
1063
|
+
const cost = priced.cost;
|
|
1064
|
+
const bound = (tokens) => Math.max(0, priced.worst(tokens) - cost(tokens));
|
|
1065
|
+
const boundOf = (tokens) => (bound(tokens) > 0 ? { boundUsd: bound(tokens) } : {});
|
|
1066
|
+
const admitted = (limit) => ({ ...(output === 0 ? {} : { outputTokensMax: limit }), holdUsd: cost(limit), boundUsd: bound(limit), stoppedUsd: stoppedPriceOf(cost, limit) });
|
|
759
1067
|
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input to fit.
|
|
760
1068
|
if (output === 0)
|
|
761
|
-
return cost(0) <= left + FIT_TOLERANCE ?
|
|
762
|
-
const asked = Math.min(outputTokensAsked ?? output, output);
|
|
763
|
-
const least = Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked);
|
|
1069
|
+
return cost(0) <= left + FIT_TOLERANCE ? admitted(0) : { ...refuseFor(capRefusal(cap, spentUsd, holding, cost(0))), ...boundOf(0) };
|
|
764
1070
|
const most = mostOutput(cost, least, asked, left);
|
|
765
|
-
return most === undefined ? {
|
|
1071
|
+
return most === undefined ? { ...refuseFor(capRefusal(cap, spentUsd, holding, cost(least))), ...boundOf(least) } : admitted(most);
|
|
766
1072
|
},
|
|
767
|
-
worstOf: (request) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) ? held(request) : undefined),
|
|
768
|
-
stoppedOf: (request, streamed) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) && Number.isFinite(streamed) && streamed >= 0
|
|
769
|
-
? stoppedPriceOf((tokens) => price(request.inputTokensMax, tokens), request.outputTokensMax ?? output)(streamed) : undefined),
|
|
770
1073
|
};
|
|
771
1074
|
}
|
|
772
1075
|
/** A request's input bound (inputBound of its context, plus `overhead(model, context)`, what its provider adds
|
|
@@ -788,26 +1091,81 @@ export function requestParts(overhead = piOverhead) {
|
|
|
788
1091
|
* each request to a model in `unpriced` (one serve has no price for) or whose output is priced and that has no output
|
|
789
1092
|
* ceiling, each whose input cannot be bounded, and every request once what the run has spent is unknown: `spent` null
|
|
790
1093
|
* (spentIn), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
|
|
791
|
-
* `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0.
|
|
792
|
-
*
|
|
793
|
-
* `
|
|
794
|
-
*
|
|
795
|
-
*
|
|
796
|
-
*
|
|
797
|
-
*
|
|
798
|
-
|
|
799
|
-
export async function capModels(models, cap, spent, { unpriced = new Set(), overhead = piOverhead, refused: markRefused, joined = false } = {}) {
|
|
1094
|
+
* `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. It is
|
|
1095
|
+
* priced by requestPrice under `mode`, after the previous request of its conversation (the context's last answer, read
|
|
1096
|
+
* by previousIn; its end as `now` read it when it settled here, else its own timestamp, which is when it began). Each
|
|
1097
|
+
* request sent carries what it is held at (HELD_USD) and its bound (BOUND_USD) to the marks below, and one stopped
|
|
1098
|
+
* before its end counts at most its hold.
|
|
1099
|
+
* `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry. On
|
|
1100
|
+
* another harness the run has no models of its own: every request goes through its session's proxy (port-models.ts). */
|
|
1101
|
+
export async function capModels(models, cap, spent, { unpriced = new Set(), overhead = piOverhead, refused: markRefused, mode = "expected", now = Date.now, wrapUp } = {}) {
|
|
800
1102
|
const [{ calculateCost, createAssistantMessageEventStream }, simple] = await Promise.all([import("@earendil-works/pi-ai"), import("@earendil-works/pi-ai/api/simple-options")]);
|
|
801
1103
|
const partsOf = requestParts(overhead);
|
|
1104
|
+
/** When each answer settled here, by its timestamp (an answer keeps it when the run's store gives it back), the newest
|
|
1105
|
+
* ENDED_KEPT of them: its end, for the next request's previous. */
|
|
1106
|
+
const ended = new Map();
|
|
1107
|
+
const ENDED_KEPT = 64;
|
|
1108
|
+
const endedNow = (message) => {
|
|
1109
|
+
if (typeof message.timestamp !== "number")
|
|
1110
|
+
return;
|
|
1111
|
+
ended.delete(message.timestamp);
|
|
1112
|
+
ended.set(message.timestamp, now());
|
|
1113
|
+
if (ended.size > ENDED_KEPT)
|
|
1114
|
+
ended.delete(ended.keys().next().value);
|
|
1115
|
+
};
|
|
1116
|
+
/** The previous request of `context`'s conversation on `model`: its last answer, if one on this model whose usage says
|
|
1117
|
+
* its input, with the bound of what it was sent (the context before it, measured as this request is). An answer on
|
|
1118
|
+
* another model, or that failed or was stopped, leaves none: nothing cached to count on. */
|
|
1119
|
+
const previousIn = (model, context) => {
|
|
1120
|
+
const at = context.messages.findLastIndex((message) => message.role === "assistant");
|
|
1121
|
+
const answer = context.messages[at];
|
|
1122
|
+
if (!answer || answer.model !== model.id || answer.provider !== model.provider || answer.stopReason === "error" || answer.stopReason === "aborted")
|
|
1123
|
+
return undefined;
|
|
1124
|
+
const before = partsOf(model, { ...context, messages: context.messages.slice(0, at) });
|
|
1125
|
+
return previousOf(answer.usage, before?.input, ended.get(answer.timestamp) ?? answer.timestamp);
|
|
1126
|
+
};
|
|
802
1127
|
let held = 0;
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
/** What the run has spent, as this request's check reads it: on another harness the run's one total (`joined`). */
|
|
806
|
-
const spentNow = () => (joined ? (runSpend?.now?.() ?? null) : spent);
|
|
1128
|
+
/** What the run has spent, as this request's check reads it. */
|
|
1129
|
+
const spentNow = () => spent;
|
|
807
1130
|
// The run's spend as a paid tool's check reads it (installed below, useSpend): the requests in flight held at their
|
|
808
1131
|
// worst case apart from it (it adds the paid holds itself), and its charge joins the spend.
|
|
809
|
-
|
|
1132
|
+
// `cap` moves only by a raise (raise: a workflow run's, budget.ts), read at each check from then on.
|
|
1133
|
+
const own = {
|
|
1134
|
+
get cap() { return cap; }, spent: () => spent, held: () => held, add: (usd) => void (spent = spent !== null && typeof usd === "number" && Number.isFinite(usd) ? spent + usd : null),
|
|
1135
|
+
raise: (to) => void (to > cap && (cap = to)),
|
|
1136
|
+
};
|
|
1137
|
+
/** `judgeOne`, and near the cap the wrap-up (wrapUpDue), once: a turn's request on the run's own model is sent with the
|
|
1138
|
+
* words after everything its context holds (`context`), its bytes admitted with it. Only in this one request: pi's
|
|
1139
|
+
* transcript never holds the note, and no input is queued, so the run spends nothing after the model answers. */
|
|
810
1140
|
const judge = (model, context, options, simpleCall, turn) => {
|
|
1141
|
+
const judged = judgeOne(model, context, options, simpleCall, turn);
|
|
1142
|
+
if (!("hold" in judged) || !wrapUp || wrapUp.sent || wrapUp.pending || !turn || model.id !== wrapUp.model)
|
|
1143
|
+
return judged;
|
|
1144
|
+
const spentUsd = spentNow();
|
|
1145
|
+
// What is left as admission counted it: what was spent, and what requests and paid calls in flight are held at.
|
|
1146
|
+
// Nothing priced yet: the request at its input and a typical answer (WRAP_UP_STEP0_ANSWER_TOKENS), never its hold.
|
|
1147
|
+
const due = spentUsd === null ? undefined : wrapUpDue(cap, spentUsd, held + paidHolds(), typicalCost(wrapUp.costs, judged.typical ?? judged.hold), judged.least);
|
|
1148
|
+
if (!due)
|
|
1149
|
+
return judged;
|
|
1150
|
+
const words = wrapUpWords(due.leftUsd, wrapUp.costs.length === 0);
|
|
1151
|
+
const noted = { ...context, messages: [...context.messages, { role: "user", content: `<system-reminder>${words}</system-reminder>`, timestamp: now() }] };
|
|
1152
|
+
const again = judgeOne(model, noted, options, simpleCall, turn);
|
|
1153
|
+
// The note's own bytes do not fit: the request goes as it came, and the note waits for one they do.
|
|
1154
|
+
if (!("hold" in again))
|
|
1155
|
+
return judged;
|
|
1156
|
+
// Pending until this request ends: told (recorded) only if it ends answered, else left for the next request.
|
|
1157
|
+
wrapUp.pending = true;
|
|
1158
|
+
return { ...again, context: noted, told: { capUsd: cap, leftUsd: due.leftUsd, words } };
|
|
1159
|
+
};
|
|
1160
|
+
/** Settles a note `answer` carried: told when it ended answered (not an error, not aborted), else re-armed. */
|
|
1161
|
+
const settleNote = (answer, told) => void answer.then((message) => {
|
|
1162
|
+
wrapUp.pending = false;
|
|
1163
|
+
if (message.stopReason === "error" || message.stopReason === "aborted")
|
|
1164
|
+
return;
|
|
1165
|
+
wrapUp.sent = true;
|
|
1166
|
+
wrapUp.record(told);
|
|
1167
|
+
}, () => void (wrapUp.pending = false));
|
|
1168
|
+
const judgeOne = (model, context, options, simpleCall, turn) => {
|
|
811
1169
|
if (unpriced.has(model.id))
|
|
812
1170
|
return { why: noPrice(cap) };
|
|
813
1171
|
const ceiling = outputBound(model);
|
|
@@ -827,16 +1185,24 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
827
1185
|
const parts = partsOf(model, context);
|
|
828
1186
|
if (parts === undefined)
|
|
829
1187
|
return { why: unmeasured(cap) };
|
|
830
|
-
|
|
831
|
-
const
|
|
1188
|
+
// Its price by the one rule (requestPrice): its input expected after the previous request, else uncached.
|
|
1189
|
+
const priced = requestPrice(priceOf(calculateCost, model), parts.input, mode === "strict" ? undefined : previousIn(model, context), now(), mode, parts.feeUsd);
|
|
1190
|
+
const cost = priced.cost;
|
|
1191
|
+
const bound = (tokens) => Math.max(0, priced.worst(tokens) - cost(tokens));
|
|
1192
|
+
// A refusal for room at `tokens` of output: its words and figures (capRefusal, at what admission prices the request
|
|
1193
|
+
// at), and the bound it would have been sent with.
|
|
1194
|
+
const refusedAt = (holding, tokens) => {
|
|
1195
|
+
const { why, figures } = whyOf(capRefusal(cap, spentUsd, holding, cost(tokens)));
|
|
1196
|
+
return { why, figures: { ...figures, ...(bound(tokens) > 0 ? { boundUsd: bound(tokens) } : {}) } };
|
|
1197
|
+
};
|
|
832
1198
|
// What the run holds beside what it spent, as a paid call's check counts it: each request in flight at its figure, and
|
|
833
1199
|
// each paid call under way at what it is held at.
|
|
834
1200
|
const holding = held + paidHolds();
|
|
835
1201
|
const left = cap - spentUsd - holding;
|
|
836
|
-
|
|
837
|
-
//
|
|
1202
|
+
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input and fee to fit. Its least
|
|
1203
|
+
// admission is that figure, its input at its price after the previous request, and no output (the wrap-up's least).
|
|
838
1204
|
if (ceiling === 0)
|
|
839
|
-
return cost(0) <= left + FIT_TOLERANCE ? {
|
|
1205
|
+
return cost(0) <= left + FIT_TOLERANCE ? { hold: cost(0), bound: bound(0), stopped: () => cost(0), least: cost(0) } : refusedAt(holding, 0);
|
|
840
1206
|
// What the request would send as it stands, thinking included: pi-ai clamps its maxTokens (or the model's) to what its
|
|
841
1207
|
// context leaves, and on an API whose thinking takes a budget adds the budget to it.
|
|
842
1208
|
const transcript = context;
|
|
@@ -852,7 +1218,7 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
852
1218
|
const least = Math.min(leastOutput(model, thinking, (level) => simple.thinkingBudgetForLevel(level, options?.thinkingBudgets)), asked);
|
|
853
1219
|
const most = mostOutput(cost, least, asked, left);
|
|
854
1220
|
if (most === undefined)
|
|
855
|
-
return
|
|
1221
|
+
return refusedAt(holding, least);
|
|
856
1222
|
// The reasoning a stop leaves unseen: a model's reasoning streams as a summary or not at all (the Responses API; Claude
|
|
857
1223
|
// 4-class thinking), so a request that reasons counts its level's budget (the budget it was sent with, on a budget
|
|
858
1224
|
// API), or its whole limit when it gives no level and its API reasons by default; none on a budget API with thinking
|
|
@@ -872,16 +1238,20 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
872
1238
|
// did not stream (max(0, budget - the reasoning streamed), so thinking that streamed is not counted twice), and the
|
|
873
1239
|
// allowance, within its worst case.
|
|
874
1240
|
const stoppedAt = (limit) => (message) => stoppedFigure(cost, limit, cost(limit), streamedBytes(message) + Math.max(0, hiddenOf(limit) - reasoningBytes(message)));
|
|
1241
|
+
// The wrap-up's typical cost while nothing is priced: its input and a typical answer, at most what it asks.
|
|
1242
|
+
const typical = cost(Math.min(WRAP_UP_STEP0_ANSWER_TOKENS, asked));
|
|
1243
|
+
// The figure admission refuses it below (`least` output at its price): the wrap-up's other trigger (wrapUpDue).
|
|
1244
|
+
const leastUsd = cost(least);
|
|
875
1245
|
if (most === asked)
|
|
876
|
-
return {
|
|
1246
|
+
return { hold: cost(asked), bound: bound(asked), stopped: stoppedAt(asked), typical, least: leastUsd };
|
|
877
1247
|
// Limited: sent with `most` tokens at most, thinking included. On a budget API the budget is squeezed first, keeping
|
|
878
1248
|
// the answer's 1,024, and maxTokens is what is left of `most` beside it, so pi-ai's sum is `most`.
|
|
879
1249
|
const clamp = { tokens: most, leftUsd: Math.round(left * 1e6) / 1e6, capUsd: cap };
|
|
880
1250
|
if (!budgeted)
|
|
881
|
-
return {
|
|
1251
|
+
return { hold: cost(most), bound: bound(most), stopped: stoppedAt(most), typical, least: leastUsd, options: { ...options, maxTokens: most, [CLAMP]: clamp } };
|
|
882
1252
|
const level = simple.clampReasoning(thinking);
|
|
883
1253
|
const budget = Math.min(simple.thinkingBudgetForLevel(thinking, options?.thinkingBudgets), most - ANSWER_TOKENS_LEAST);
|
|
884
|
-
return {
|
|
1254
|
+
return { hold: cost(most), bound: bound(most), stopped: stoppedAt(most), typical, least: leastUsd, options: { ...options, maxTokens: most - budget, thinkingBudgets: { ...options?.thinkingBudgets, [level]: budget }, [CLAMP]: clamp } };
|
|
885
1255
|
};
|
|
886
1256
|
const refusal = (model, why) => ({
|
|
887
1257
|
role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(),
|
|
@@ -895,23 +1265,26 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
895
1265
|
* (markResponseBegan: its usage is what had streamed, not what the provider can have billed), or that failed with no
|
|
896
1266
|
* answer, at `worst`, what the cap held for it; each as spentIn reads its end mark. Without a figure (a deferred
|
|
897
1267
|
* response) it is unknown, as is a cost that is not a number, from then on. */
|
|
898
|
-
const count = (answer, worst, stopped, attempts) => {
|
|
1268
|
+
const count = (answer, turn, worst, stopped, attempts) => {
|
|
899
1269
|
const plus = (sum, cost) => (sum !== null && typeof cost === "number" && Number.isFinite(cost) ? sum + cost : null);
|
|
900
|
-
const add = (cost) => void (
|
|
1270
|
+
const add = (cost) => void (spent = plus(spent, cost));
|
|
901
1271
|
// One rule (bookRequest), from how the request ended (piEnded) as its marks read it too.
|
|
902
1272
|
const at = (message) => message.stopReason === "aborted" ? (stopped && !anyAttemptLost(attempts) ? stopped(message) : worst)
|
|
903
1273
|
: bookRequest(piEnded(message, responseBegan.has(message), attempts), worst === undefined ? {} : { hold: worst }).usd;
|
|
904
|
-
|
|
1274
|
+
// A priced turn answer of the run's own model: the wrap-up's typical cost counts it, as costsIn reads it again (its
|
|
1275
|
+
// pi.assistant entries). Never a compaction summary's or a native search's request on the same model (completeSimple
|
|
1276
|
+
// calls, `turn` false): no pi.assistant entry keeps them, so a process opened again would count without them.
|
|
1277
|
+
const priced = (message) => {
|
|
1278
|
+
const total = message.usage?.cost?.total;
|
|
1279
|
+
if (wrapUp && turn && message.model === wrapUp.model && message.stopReason !== "error" && message.stopReason !== "aborted" && typeof total === "number" && Number.isFinite(total) && total > 0)
|
|
1280
|
+
wrapUp.costs.push(total);
|
|
1281
|
+
};
|
|
1282
|
+
return answer.then((message) => (endedNow(message), priced(message), add(at(message))), () => add(worst));
|
|
905
1283
|
};
|
|
906
|
-
/** Sends a request judged to fit at `worst
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
const
|
|
910
|
-
if (joined)
|
|
911
|
-
paidOpen.add(hold);
|
|
912
|
-
else
|
|
913
|
-
held += worst;
|
|
914
|
-
const release = () => void (joined ? paidOpen.delete(hold) : (held -= worst));
|
|
1284
|
+
/** Sends a request judged to fit at `worst` (its hold), holding that until `answer` settles. */
|
|
1285
|
+
const admit = (turn, worst, stopped, answer, attempts) => {
|
|
1286
|
+
held += worst;
|
|
1287
|
+
const release = () => void (held -= worst);
|
|
915
1288
|
let answered;
|
|
916
1289
|
try {
|
|
917
1290
|
answered = answer();
|
|
@@ -920,31 +1293,64 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
920
1293
|
release();
|
|
921
1294
|
throw error;
|
|
922
1295
|
}
|
|
923
|
-
void count(answered, worst, stopped, attempts).finally(release);
|
|
1296
|
+
void count(answered, turn, worst, stopped, attempts).finally(release);
|
|
924
1297
|
return answered;
|
|
925
1298
|
};
|
|
926
1299
|
// A paid tool's check reads the spend, and the requests in flight held at their worst case apart from it (it adds the
|
|
927
1300
|
// paid holds itself), and its charge joins the spend. On another harness, the harness sets it as its run opens
|
|
928
1301
|
// (harness-app.ts).
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
const carrying = (options, { worst, stopped }, attempts) => ({
|
|
935
|
-
...options, [HELD_USD]: worst, [STOPPED_USD]: stopped,
|
|
1302
|
+
useSpend(own);
|
|
1303
|
+
/** `options` with what the request is held at, its bound, its figure if it is stopped, and its attempts' record, for
|
|
1304
|
+
* its marks: on an API the cap can watch, a fetch that records each attempt (`attempts`, undefined on one it cannot). */
|
|
1305
|
+
const carrying = (options, { hold, bound, stopped }, attempts) => ({
|
|
1306
|
+
...options, [HELD_USD]: hold, [BOUND_USD]: bound, [STOPPED_USD]: stopped,
|
|
936
1307
|
// null on an API the cap cannot watch: its marks read a failure before any event as lost.
|
|
937
1308
|
...(attempts ? { [ATTEMPTS]: attempts, fetch: recordingFetch(attempts, options?.fetch, options?.signal) } : { [ATTEMPTS]: null }),
|
|
938
1309
|
});
|
|
939
1310
|
const attemptsFor = (model) => (unwatched(model.api) ? undefined : []);
|
|
940
1311
|
const stream = (send, simpleCall) => (model, context, options) => {
|
|
941
1312
|
const judged = judge(model, context, options, simpleCall, true);
|
|
942
|
-
if ("
|
|
1313
|
+
if ("hold" in judged) {
|
|
943
1314
|
let events;
|
|
944
1315
|
const attempts = attemptsFor(model);
|
|
945
|
-
|
|
1316
|
+
let answered;
|
|
1317
|
+
try {
|
|
1318
|
+
answered = admit(true, judged.hold, judged.stopped, () => (events = send(model, judged.context ?? context, carrying(judged.options ?? options, judged, attempts))).result(), attempts);
|
|
1319
|
+
}
|
|
1320
|
+
catch (error) {
|
|
1321
|
+
// Never sent (its send threw as it was made): a note it carried waits for the next request.
|
|
1322
|
+
if (judged.told)
|
|
1323
|
+
wrapUp.pending = false;
|
|
1324
|
+
throw error;
|
|
1325
|
+
}
|
|
1326
|
+
if (judged.told)
|
|
1327
|
+
settleNote(answered, judged.told);
|
|
946
1328
|
return events;
|
|
947
1329
|
}
|
|
1330
|
+
// A workflow run's turn request refused for room waits for a raise, unsent, and is judged again (RunSpend.wait):
|
|
1331
|
+
// its node stands where it is. Its events then come from the request sent, or from the refusal if none is.
|
|
1332
|
+
const room = roomRefusal(judged.why);
|
|
1333
|
+
if (room !== undefined && own.wait) {
|
|
1334
|
+
const waited = createAssistantMessageEventStream();
|
|
1335
|
+
const signal = options?.signal;
|
|
1336
|
+
void own.wait({ words: room, room: true, capUsd: cap, ...(judged.figures ? { figures: judged.figures } : {}) }, signal).then((raised) => raised ? stream(send, simpleCall)(model, context, options) : refusedStream(model, judged), () => refusedStream(model, judged)).then(async (events) => {
|
|
1337
|
+
for await (const event of events)
|
|
1338
|
+
waited.push(event);
|
|
1339
|
+
waited.end(await events.result());
|
|
1340
|
+
}).catch((error) => {
|
|
1341
|
+
const failed = refusal(model, `${SPEND_CAP_REACHED}: Not sent: the wait for a raise failed (${String(error?.message ?? error).slice(0, 200)})`);
|
|
1342
|
+
waited.push({ type: "error", reason: "error", error: failed });
|
|
1343
|
+
waited.end(failed);
|
|
1344
|
+
});
|
|
1345
|
+
return waited;
|
|
1346
|
+
}
|
|
1347
|
+
// A refusal no raise fixes ends a workflow's run in its words (budget.ts): the node fails on the refusal.
|
|
1348
|
+
if (room === undefined)
|
|
1349
|
+
own.stopped?.({ words: judged.why.replace(CAP_REFUSAL_PREFIX, ""), room: false, capUsd: cap });
|
|
1350
|
+
return refusedStream(model, judged);
|
|
1351
|
+
};
|
|
1352
|
+
/** The refusal's own stream: its start mark first, then pi's error for it. */
|
|
1353
|
+
const refusedStream = (model, judged) => {
|
|
948
1354
|
const refused = createAssistantMessageEventStream();
|
|
949
1355
|
const message = refusal(model, judged.why);
|
|
950
1356
|
// Its own start mark first, so pi's error entry for it answers that mark, never an earlier request a stop or a crash
|
|
@@ -960,10 +1366,14 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
960
1366
|
};
|
|
961
1367
|
const complete = (send, simpleCall) => (model, context, options) => {
|
|
962
1368
|
const judged = judge(model, context, options, simpleCall, false);
|
|
963
|
-
if (!("
|
|
1369
|
+
if (!("hold" in judged)) {
|
|
1370
|
+
// Inside a workflow's call node (the `llm` tool): the call is told, and ends on it (app.ts runEffect).
|
|
1371
|
+
const room = roomRefusal(judged.why);
|
|
1372
|
+
capRefusals.getStore()?.({ words: room ?? judged.why.replace(CAP_REFUSAL_PREFIX, ""), room: room !== undefined, capUsd: cap, ...(judged.figures ? { figures: judged.figures } : {}) });
|
|
964
1373
|
return Promise.resolve(refusal(model, judged.why));
|
|
1374
|
+
}
|
|
965
1375
|
const attempts = attemptsFor(model);
|
|
966
|
-
return admit(judged.
|
|
1376
|
+
return admit(false, judged.hold, judged.stopped, () => send(model, judged.context ?? context, carrying(judged.options ?? options, judged, attempts)), attempts);
|
|
967
1377
|
};
|
|
968
1378
|
const guarded = {
|
|
969
1379
|
stream: stream(models.stream.bind(models), false),
|
|
@@ -973,12 +1383,12 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
973
1383
|
// A deferred response was admitted when it was sent; what it cost is counted when it is fetched.
|
|
974
1384
|
streamDeferred: (...args) => {
|
|
975
1385
|
const events = models.streamDeferred(...args);
|
|
976
|
-
void count(events.result());
|
|
1386
|
+
void count(events.result(), true);
|
|
977
1387
|
return events;
|
|
978
1388
|
},
|
|
979
1389
|
fetchDeferred: (...args) => {
|
|
980
1390
|
const answer = models.fetchDeferred(...args);
|
|
981
|
-
void count(answer);
|
|
1391
|
+
void count(answer, true);
|
|
982
1392
|
return answer;
|
|
983
1393
|
},
|
|
984
1394
|
};
|