@parcha/agentrun-serve 0.1.0-beta.37 → 0.1.0-beta.39
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 +700 -0
- package/README.md +441 -177
- package/dist/adapters.d.ts +4 -1
- package/dist/adapters.js +4 -2
- package/dist/agent-rows.d.ts +1 -3
- package/dist/agents-store.d.ts +35 -3
- package/dist/agents-store.js +48 -23
- package/dist/answer-json.d.ts +34 -1
- package/dist/answer-json.js +91 -9
- package/dist/api-only.d.ts +1 -1
- package/dist/api-only.js +2 -2
- package/dist/bash-read-only.js +2 -1
- package/dist/browser-cost.js +52 -93
- package/dist/cap-short.d.ts +12 -0
- package/dist/cap-short.js +60 -0
- package/dist/cap.d.ts +3 -400
- package/dist/cap.js +6 -942
- package/dist/catalog.d.ts +0 -5
- package/dist/catalog.js +2 -6
- package/dist/chatgpt-plan.d.ts +163 -0
- package/dist/chatgpt-plan.js +549 -0
- package/dist/cli.js +26 -6
- package/dist/composio-preset.d.ts +25 -0
- package/dist/composio-preset.js +51 -8
- package/dist/composio-triggers.d.ts +113 -0
- package/dist/composio-triggers.js +411 -0
- package/dist/computer-calls.d.ts +36 -24
- package/dist/computer-calls.js +110 -27
- package/dist/computer-commands.d.ts +2 -0
- package/dist/computer-commands.js +7 -3
- package/dist/computer-live.d.ts +12 -2
- package/dist/computer-live.js +21 -5
- package/dist/computer-routes.d.ts +2 -2
- package/dist/computer-routes.js +2 -2
- package/dist/computer-setting.d.ts +15 -2
- package/dist/computer-setting.js +20 -4
- package/dist/computer-view.d.ts +18 -2
- package/dist/computer-view.js +21 -6
- package/dist/computer-viewer.js +40 -13
- package/dist/computers.d.ts +8 -2
- package/dist/computers.js +18 -8
- package/dist/console/assets/index-BNhZs-jp.css +1 -0
- package/dist/console/assets/index-BQv5aOGB.js +700 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +2 -0
- package/dist/console-links.js +6 -3
- package/dist/decision-cap.d.ts +2 -5
- package/dist/decision-cap.js +3 -6
- package/dist/decision-rows.js +11 -11
- package/dist/decisions.js +4 -0
- package/dist/email/account.d.ts +84 -0
- package/dist/email/account.js +159 -0
- package/dist/email/answer.d.ts +10 -0
- package/dist/email/answer.js +182 -0
- package/dist/email/email-faux.d.ts +95 -0
- package/dist/email/email-faux.js +849 -0
- package/dist/email/labels.d.ts +1 -0
- package/dist/email/labels.js +84 -0
- package/dist/email/mail.d.ts +186 -0
- package/dist/email/mail.js +380 -0
- package/dist/email/names.d.ts +20 -0
- package/dist/email/names.js +40 -0
- package/dist/email/routes.d.ts +9 -0
- package/dist/email/routes.js +50 -0
- package/dist/email/tools.d.ts +20 -0
- package/dist/email/tools.js +517 -0
- package/dist/environment.d.ts +17 -2
- package/dist/environment.js +36 -8
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +12 -0
- package/dist/eval-mailbox.d.ts +103 -0
- package/dist/eval-mailbox.js +236 -0
- package/dist/faux-computers.js +4 -2
- package/dist/graph-view.d.ts +9 -2
- package/dist/graph-view.js +6 -2
- package/dist/harness-install.d.ts +28 -2
- package/dist/harness-install.js +147 -59
- package/dist/harness-opencode/adapter.js +2 -22
- package/dist/harness-opencode/facts.js +5 -4
- package/dist/harness-opencode/host/policy.d.ts +4 -5
- package/dist/harness-opencode/host/policy.js +14 -33
- package/dist/harness-opencode/index.d.ts +1 -1
- package/dist/harness-opencode/index.js +1 -1
- package/dist/harness-opencode/versions.d.ts +6 -0
- package/dist/harness-opencode/versions.js +6 -0
- package/dist/harness-table.d.ts +0 -2
- package/dist/harness-table.js +8 -7
- package/dist/harness.d.ts +12 -0
- package/dist/harness.js +15 -3
- package/dist/host-tools.d.ts +1 -5
- package/dist/host-tools.js +7 -10
- package/dist/hosted-search.d.ts +3 -3
- package/dist/hosted-search.js +51 -32
- package/dist/import-sources.d.ts +1 -1
- package/dist/import-sources.js +3 -3
- package/dist/import.d.ts +21 -0
- package/dist/import.js +186 -1
- package/dist/key-check.d.ts +0 -2
- package/dist/key-check.js +3 -4
- package/dist/key-refusal.d.ts +8 -2
- package/dist/key-refusal.js +16 -13
- package/dist/key-words.d.ts +3 -2
- package/dist/key-words.js +4 -2
- package/dist/learn/check.d.ts +24 -4
- package/dist/learn/check.js +340 -7
- package/dist/learn/commit.d.ts +10 -0
- package/dist/learn/commit.js +18 -4
- package/dist/learn/compile.d.ts +250 -0
- package/dist/learn/compile.js +507 -0
- package/dist/learn/general.d.ts +3 -0
- package/dist/learn/general.js +4 -2
- package/dist/learn/grade.d.ts +5 -1
- package/dist/learn/grade.js +11 -7
- package/dist/learn/notes.d.ts +8 -0
- package/dist/learn/notes.js +18 -0
- package/dist/learn/promote.d.ts +308 -0
- package/dist/learn/promote.js +321 -0
- package/dist/learn/refit.d.ts +48 -0
- package/dist/learn/refit.js +264 -0
- package/dist/learn/reflect.d.ts +5 -25
- package/dist/learn/reflect.js +14 -131
- package/dist/learn/replay-calls.d.ts +63 -0
- package/dist/learn/replay-calls.js +158 -0
- package/dist/learn/skills.d.ts +19 -16
- package/dist/learn/skills.js +157 -53
- package/dist/learn/workflow-nodes.d.ts +15 -0
- package/dist/learn/workflow-nodes.js +44 -0
- package/dist/learned-nodes.d.ts +58 -2
- package/dist/learned-nodes.js +68 -5
- package/dist/learned-workflow.d.ts +58 -32
- package/dist/learned-workflow.js +215 -77
- package/dist/learning-batch.d.ts +2 -2
- package/dist/learning-batch.js +4 -4
- package/dist/learning-cost.d.ts +41 -11
- package/dist/learning-cost.js +31 -13
- package/dist/learning-routes.d.ts +12 -2
- package/dist/learning-routes.js +34 -6
- package/dist/learning-words.d.ts +8 -1
- package/dist/learning-words.js +11 -1
- package/dist/learning.d.ts +26 -1
- package/dist/learning.js +7 -4
- package/dist/link-check.d.ts +27 -0
- package/dist/link-check.js +164 -0
- package/dist/llm.js +0 -3
- package/dist/local-models.d.ts +33 -2
- package/dist/local-models.js +43 -5
- package/dist/mcp-gateway.d.ts +12 -20
- package/dist/mcp-gateway.js +16 -44
- package/dist/mcp-oauth.d.ts +5 -0
- package/dist/mcp-oauth.js +1 -1
- package/dist/mcp-pin-first.d.ts +37 -0
- package/dist/mcp-pin-first.js +113 -0
- package/dist/mcp-probe.d.ts +8 -9
- package/dist/mcp-probe.js +16 -33
- package/dist/mcp-secret-writes.js +3 -0
- package/dist/mcp-servers-store.d.ts +102 -26
- package/dist/mcp-servers-store.js +151 -25
- package/dist/mcp-sources.d.ts +39 -0
- package/dist/mcp-sources.js +74 -0
- package/dist/mcp-store.d.ts +11 -0
- package/dist/mcp-store.js +16 -2
- package/dist/mcp-wire.d.ts +22 -0
- package/dist/mcp-wire.js +36 -0
- package/dist/mcp.js +3 -3
- package/dist/meta-tool-names.d.ts +1 -0
- package/dist/meta-tool-names.js +3 -0
- package/dist/model-form.d.ts +11 -0
- package/dist/model-form.js +17 -1
- package/dist/model.d.ts +39 -6
- package/dist/model.js +171 -32
- package/dist/monid.d.ts +50 -29
- package/dist/monid.js +234 -143
- package/dist/native/binding.d.ts +13 -0
- package/dist/native/binding.js +57 -0
- package/dist/native/cli.d.ts +2 -0
- package/dist/native/cli.js +48 -0
- package/dist/native/connection.d.ts +8 -0
- package/dist/native/connection.js +94 -0
- package/dist/native/context.d.ts +6 -0
- package/dist/native/context.js +22 -0
- package/dist/native/discovery.d.ts +27 -0
- package/dist/native/discovery.js +404 -0
- package/dist/native/environment.d.ts +4 -0
- package/dist/native/environment.js +18 -0
- package/dist/native/history.d.ts +20 -0
- package/dist/native/history.js +147 -0
- package/dist/native/instructions.d.ts +21 -0
- package/dist/native/instructions.js +173 -0
- package/dist/native/remote-worker-bridge.d.ts +3 -0
- package/dist/native/remote-worker-bridge.js +278 -0
- package/dist/native/remote.d.ts +187 -0
- package/dist/native/remote.js +492 -0
- package/dist/native/runtime.d.ts +17 -0
- package/dist/native/runtime.js +316 -0
- package/dist/native/runtimes.d.ts +66 -0
- package/dist/native/runtimes.js +41 -0
- package/dist/native/schema.d.ts +46 -0
- package/dist/native/schema.js +41 -0
- package/dist/native/types.d.ts +87 -0
- package/dist/native/types.js +1 -0
- package/dist/observation/http.d.ts +4 -0
- package/dist/observation/http.js +140 -0
- package/dist/observation/observer.d.ts +301 -0
- package/dist/observation/observer.js +919 -0
- package/dist/observation/schema.d.ts +52 -0
- package/dist/observation/schema.js +154 -0
- package/dist/openapi.d.ts +1 -0
- package/dist/openapi.js +705 -126
- package/dist/paid-calls.d.ts +34 -32
- package/dist/paid-calls.js +52 -104
- package/dist/place-offers.d.ts +4 -8
- package/dist/place-offers.js +4 -9
- package/dist/port-models.d.ts +7 -2
- package/dist/port-models.js +5 -2
- package/dist/print.d.ts +4 -2
- package/dist/print.js +4 -3
- package/dist/propose.d.ts +8 -3
- package/dist/propose.js +28 -7
- package/dist/provider.d.ts +5 -1
- package/dist/provider.js +17 -2
- package/dist/push-handler.d.ts +3 -2
- package/dist/push-handler.js +20 -6
- package/dist/reflect-range.js +2 -1
- package/dist/refusal-words.d.ts +11 -0
- package/dist/refusal-words.js +13 -2
- package/dist/rows.d.ts +5 -3
- package/dist/rows.js +15 -4
- package/dist/run-launch.d.ts +23 -1
- package/dist/run-launch.js +17 -4
- package/dist/run-learning-served.d.ts +84 -0
- package/dist/run-manifest.d.ts +8 -0
- package/dist/run-manifest.js +33 -1
- package/dist/run-reads-over-store.d.ts +3 -3
- package/dist/run-reads-over-store.js +13 -10
- package/dist/run-secrets.js +2 -3
- package/dist/run-timeline-served.d.ts +3 -2
- package/dist/run-timeline-served.js +12 -10
- package/dist/run-view.d.ts +59 -41
- package/dist/run-view.js +128 -64
- package/dist/runnable.d.ts +13 -8
- package/dist/runnable.js +77 -60
- package/dist/runner/adapter-loop.d.ts +60 -15
- package/dist/runner/adapter-loop.js +1406 -464
- package/dist/runner/adapter-run-spec.d.ts +45 -14
- package/dist/runner/adapter-run-spec.js +200 -116
- package/dist/runner/adapters/pi.d.ts +40 -7
- package/dist/runner/adapters/pi.js +149 -38
- package/dist/runner/beside.d.ts +3 -1
- package/dist/runner/beside.js +24 -8
- package/dist/runner/claim-secrets.d.ts +3 -1
- package/dist/runner/claim-secrets.js +28 -4
- package/dist/runner/cli-run-spec.d.ts +30 -0
- package/dist/runner/cli-run-spec.js +150 -66
- package/dist/runner/computer-channel.d.ts +5 -2
- package/dist/runner/computer-channel.js +5 -3
- package/dist/runner/computer-journal.d.ts +6 -0
- package/dist/runner/computer-journal.js +8 -10
- package/dist/runner/conformance/harness.d.ts +3 -0
- package/dist/runner/conformance/harness.js +149 -5
- package/dist/runner/conformance/subject.d.ts +11 -4
- package/dist/runner/end-of-run.d.ts +8 -5
- package/dist/runner/end-of-run.js +11 -6
- package/dist/runner/feedback-round.d.ts +79 -0
- package/dist/runner/feedback-round.js +127 -0
- package/dist/runner/harness-loops.js +17 -0
- package/dist/runner/journal-kinds.d.ts +55 -13
- package/dist/runner/journal-kinds.js +19 -0
- package/dist/runner/learning-dispatch.d.ts +3 -2
- package/dist/runner/learning-dispatch.js +6 -6
- package/dist/runner/learning-end.d.ts +58 -19
- package/dist/runner/learning-end.js +316 -115
- package/dist/runner/learning-factory.d.ts +3 -0
- package/dist/runner/learning-factory.js +8 -2
- package/dist/runner/learning-loop.d.ts +21 -1
- package/dist/runner/learning-loop.js +24 -6
- package/dist/runner/learning-seed.d.ts +4 -0
- package/dist/runner/learning-seed.js +14 -0
- package/dist/runner/loop-contract.d.ts +19 -3
- package/dist/runner/loop.d.ts +34 -1
- package/dist/runner/loop.js +55 -1
- package/dist/runner/main.d.ts +6 -1
- package/dist/runner/main.js +26 -4
- package/dist/runner/mcp-claim.d.ts +5 -1
- package/dist/runner/mcp-claim.js +66 -50
- package/dist/runner/mcp-run.d.ts +20 -53
- package/dist/runner/mcp-run.js +22 -88
- package/dist/runner/meta-tools.d.ts +44 -0
- package/dist/runner/meta-tools.js +344 -0
- package/dist/runner/metrics.d.ts +80 -21
- package/dist/runner/metrics.js +128 -42
- package/dist/runner/model-route.d.ts +12 -3
- package/dist/runner/model-route.js +149 -19
- package/dist/runner/monid-run.d.ts +18 -0
- package/dist/runner/monid-run.js +170 -0
- package/dist/runner/native-loop.d.ts +11 -0
- package/dist/runner/native-loop.js +438 -0
- package/dist/runner/promotion.d.ts +146 -0
- package/dist/runner/promotion.js +803 -0
- package/dist/runner/redact.js +3 -0
- package/dist/runner/reflect-hook.d.ts +36 -21
- package/dist/runner/reflect-hook.js +147 -49
- package/dist/runner/runner.d.ts +7 -1
- package/dist/runner/runner.js +34 -8
- package/dist/runner/sdk-loop.d.ts +7 -0
- package/dist/runner/sdk-loop.js +470 -0
- package/dist/runner/sessions.d.ts +8 -3
- package/dist/runner/sessions.js +5 -1
- package/dist/runner/spec-holds.d.ts +16 -2
- package/dist/runner/spec-holds.js +42 -14
- package/dist/runner/step-guard.d.ts +62 -0
- package/dist/runner/step-guard.js +93 -0
- package/dist/runner/store-secrets.js +17 -2
- package/dist/runner/subagent.d.ts +0 -3
- package/dist/runner/subagent.js +7 -12
- package/dist/runner/workflow-first.d.ts +226 -0
- package/dist/runner/workflow-first.js +293 -0
- package/dist/runner/workflow-loop.d.ts +1 -1
- package/dist/runner/workflow-loop.js +32 -19
- package/dist/runner/workflow-spec.d.ts +5 -1
- package/dist/runner/workflow-spec.js +63 -48
- package/dist/runs-over-store.d.ts +41 -4
- package/dist/runs-over-store.js +64 -22
- package/dist/sdk/runs.d.ts +115 -0
- package/dist/sdk/runs.js +422 -0
- package/dist/sdk/schema.d.ts +175 -0
- package/dist/sdk/schema.js +138 -0
- package/dist/sdk/workflows.d.ts +22 -0
- package/dist/sdk/workflows.js +39 -0
- package/dist/secrets.d.ts +2 -0
- package/dist/secrets.js +19 -1
- package/dist/server.d.ts +108 -20
- package/dist/server.js +874 -157
- package/dist/settings-wake.d.ts +8 -6
- package/dist/settings-wake.js +13 -7
- package/dist/skill-route.d.ts +3 -0
- package/dist/skill-route.js +16 -0
- package/dist/skills/agentrun-serve/SKILL.md +368 -0
- package/dist/stats.d.ts +10 -10
- package/dist/store/agent-body.d.ts +22 -7
- package/dist/store/agent-body.js +23 -14
- package/dist/store/command-wake.d.ts +3 -2
- package/dist/store/command-wake.js +4 -4
- package/dist/store/index.d.ts +1 -1
- package/dist/store/native-command-owner.d.ts +10 -0
- package/dist/store/native-command-owner.js +47 -0
- package/dist/store/postgres/connection.js +3 -1
- package/dist/store/postgres/migrations/0010_imported_templates.sql +18 -0
- package/dist/store/postgres/migrations/0011_revision_mcp_pin.sql +13 -0
- package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
- package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
- package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
- package/dist/store/postgres/store.js +3 -0
- package/dist/store/schema.d.ts +16 -0
- package/dist/store/schema.js +47 -8
- package/dist/store/sqlite/connection.d.ts +2 -2
- package/dist/store/sqlite/connection.js +2 -2
- package/dist/store/sqlite/run-patch.d.ts +8 -1
- package/dist/store/sqlite/run-patch.js +33 -10
- package/dist/store/sqlite/store.js +184 -28
- package/dist/store/store.d.ts +98 -21
- package/dist/store-reads/analytics.d.ts +7 -7
- package/dist/store-reads/analytics.js +23 -5
- package/dist/store-reads/cap.js +8 -6
- package/dist/store-reads/journal.d.ts +30 -1
- package/dist/store-reads/journal.js +141 -83
- package/dist/store-reads/learning.d.ts +179 -13
- package/dist/store-reads/learning.js +230 -68
- package/dist/store-reads/loop.d.ts +61 -0
- package/dist/store-reads/loop.js +111 -0
- package/dist/store-reads/runs.d.ts +5 -0
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.d.ts +3 -2
- package/dist/store-view.js +109 -37
- package/dist/template-eval.d.ts +87 -16
- package/dist/template-eval.js +605 -120
- package/dist/template-github-permissions.d.ts +2 -2
- package/dist/template-github-permissions.js +2 -1
- package/dist/template-import.d.ts +31 -0
- package/dist/template-import.js +121 -0
- package/dist/template-source.d.ts +51 -0
- package/dist/template-source.js +371 -0
- package/dist/templates.d.ts +274 -52
- package/dist/templates.js +670 -201
- package/dist/text-urls.d.ts +38 -0
- package/dist/text-urls.js +170 -0
- package/dist/timeline/computer.d.ts +48 -0
- package/dist/timeline/computer.js +169 -0
- package/dist/timeline/index.d.ts +7 -5
- package/dist/timeline/index.js +7 -5
- package/dist/timeline/labels.d.ts +11 -4
- package/dist/timeline/labels.js +122 -8
- package/dist/timeline/origin.d.ts +20 -6
- package/dist/timeline/origin.js +13 -6
- package/dist/timeline/render-text.js +1 -1
- package/dist/timeline/timeline.d.ts +76 -20
- package/dist/timeline/timeline.js +184 -39
- package/dist/timeline/util.d.ts +5 -0
- package/dist/timeline/util.js +44 -8
- package/dist/timeline/web-calls.d.ts +17 -0
- package/dist/timeline/web-calls.js +106 -0
- package/dist/tool-gate.d.ts +103 -76
- package/dist/tool-gate.js +200 -127
- package/dist/tool-keys.d.ts +4 -1
- package/dist/tool-keys.js +8 -3
- package/dist/tool-list.d.ts +29 -0
- package/dist/tool-list.js +50 -0
- package/dist/tool-names.d.ts +76 -0
- package/dist/tool-names.js +101 -0
- package/dist/tool-plane.d.ts +34 -28
- package/dist/tool-plane.js +72 -37
- package/dist/tools.d.ts +59 -15
- package/dist/tools.js +46 -42
- package/dist/trigger-adapter.d.ts +85 -5
- package/dist/trigger-adapter.js +6 -0
- package/dist/trigger-adapters.js +3 -1
- package/dist/trigger-composio.d.ts +10 -0
- package/dist/trigger-composio.js +122 -0
- package/dist/trigger-email.d.ts +4 -0
- package/dist/trigger-email.js +228 -0
- package/dist/trigger-signatures.d.ts +6 -10
- package/dist/trigger-signatures.js +16 -16
- package/dist/trigger-targets.d.ts +1 -1
- package/dist/trigger-targets.js +4 -3
- package/dist/trigger-webhook.js +6 -4
- package/dist/triggers.d.ts +94 -9
- package/dist/triggers.js +263 -62
- package/dist/uploads.d.ts +9 -0
- package/dist/uploads.js +27 -0
- package/dist/validate.d.ts +15 -7
- package/dist/validate.js +91 -50
- package/dist/web-fake.d.ts +56 -0
- package/dist/web-fake.js +102 -0
- package/dist/web-fetch-direct.d.ts +3 -0
- package/dist/web-fetch-direct.js +4 -1
- package/dist/web-fetch.d.ts +6 -8
- package/dist/web-fetch.js +10 -53
- package/dist/web-search.d.ts +51 -2
- package/dist/web-search.js +116 -18
- package/dist/webhooks.d.ts +2 -1
- package/dist/webhooks.js +5 -1
- package/dist/workflow/node-runner.js +10 -2
- package/dist/workspace/archil-claim.d.ts +3 -0
- package/dist/workspace/archil-claim.js +9 -2
- package/dist/workspace/computer-deps.d.ts +25 -9
- package/dist/workspace/computer-deps.js +82 -38
- package/dist/workspace/computer-for-claim.d.ts +60 -4
- package/dist/workspace/computer-for-claim.js +203 -45
- package/dist/workspace/computer-hold.js +7 -1
- package/dist/workspace/computer-janitor.d.ts +10 -3
- package/dist/workspace/computer-janitor.js +96 -29
- package/dist/workspace/computer-kept.d.ts +82 -0
- package/dist/workspace/computer-kept.js +147 -0
- package/dist/workspace/computer-mcp.js +4 -3
- package/dist/workspace/computer-ports.d.ts +23 -3
- package/dist/workspace/computer-ports.js +115 -5
- package/dist/workspace/index.d.ts +2 -3
- package/dist/workspace/index.js +1 -2
- package/dist/workspace/kind-skills/desktop/SKILL.md +31 -11
- package/dist/workspace/kind-skills/phone/SKILL.md +29 -14
- package/dist/workspace/local.js +2 -2
- package/dist/workspace/resolve-computer.d.ts +33 -1
- package/dist/workspace/resolve-computer.js +37 -16
- package/dist/workspace/revision-skills.d.ts +6 -2
- package/dist/workspace/revision-skills.js +12 -5
- package/dist/workspace/run-end-computers.d.ts +30 -0
- package/dist/workspace/run-end-computers.js +137 -0
- package/dist/workspace/run-tools.d.ts +40 -23
- package/dist/workspace/run-tools.js +46 -19
- package/dist/wrap-up.d.ts +35 -0
- package/dist/wrap-up.js +48 -0
- package/launcher/agentrun-serve +4 -2
- package/package.json +13 -9
- package/skills/agentrun-serve/SKILL.md +248 -10
- package/templates/README.md +220 -60
- package/templates/TOOLS.md +168 -0
- package/templates/code-review/agent.md +46 -16
- package/templates/code-review/evals/clean-refactor/case.yaml +2 -1
- package/templates/code-review/evals/clean-refactor/graders/head-sha.md +6 -0
- package/templates/code-review/evals/injection/case.yaml +2 -1
- package/templates/code-review/evals/injection/graders/head-sha.md +6 -0
- package/templates/code-review/evals/mentions-defused/case.yaml +3 -3
- package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -23
- package/templates/code-review/evals/mentions-defused/graders/head-sha.md +6 -0
- package/templates/code-review/evals/never-flag/case.yaml +2 -1
- package/templates/code-review/evals/never-flag/graders/head-sha.md +6 -0
- package/templates/code-review/evals/null-name/case.yaml +2 -1
- package/templates/code-review/evals/null-name/graders/head-sha.md +6 -0
- package/templates/code-review/evals/off-by-one/case.yaml +2 -1
- package/templates/code-review/evals/off-by-one/graders/head-sha.md +6 -0
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
- package/templates/code-review/evals/other-repo/case.yaml +16 -0
- package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +130 -0
- package/templates/code-review/evals/other-repo/graders/head-sha.md +6 -0
- package/templates/code-review/evals/other-repo/graders/no-canary.md +6 -0
- package/templates/code-review/evals/other-repo/graders/no-other-repo.md +8 -0
- package/templates/code-review/evals/other-repo/graders/refused-not-quoted.md +18 -0
- package/templates/code-review/evals/other-repo/prompt.md +10 -0
- package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
- package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
- package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
- package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
- package/templates/code-review/evals/re-review/case.yaml +2 -1
- package/templates/code-review/evals/re-review/graders/head-sha.md +6 -0
- package/templates/code-review/evals/re-review-open/case.yaml +2 -1
- package/templates/code-review/evals/re-review-open/graders/head-sha.md +6 -0
- package/templates/code-review/evals/repo-rule/case.yaml +2 -1
- package/templates/code-review/evals/repo-rule/graders/head-sha.md +6 -0
- package/templates/code-review/evals/two-defects/case.yaml +2 -1
- package/templates/code-review/evals/two-defects/graders/head-sha.md +6 -0
- package/templates/code-review/rules/CODEREVIEW.md +1 -1
- package/templates/code-review/skills/review/DEEP.md +5 -4
- package/templates/code-review/skills/review/REVIEWER.md +5 -4
- package/templates/code-review/skills/review/SKILL.md +11 -6
- package/templates/code-review/{findings.schema.json → skills/review/findings.schema.json} +1 -0
- package/templates/inbound-lead/agent.md +26 -16
- package/templates/inbound-lead/evals/injection-in-form/graders/no-exfil.md +16 -0
- package/templates/inbound-lead/evals/injection-in-form/prompt.md +2 -2
- package/templates/inbound-lead/evals/write-back/case.yaml +2 -6
- package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +34 -225
- package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +10 -14
- package/templates/inbound-lead/evals/write-back/graders/writes-once.md +7 -0
- package/templates/inbound-lead/evals/write-back/prompt.md +1 -1
- package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +3 -7
- package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +34 -225
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/form-id.md +17 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +3 -3
- package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +2 -2
- package/templates/inbound-lead/skills/lead/SKILL.md +23 -27
- package/templates/kyb/agent.md +15 -5
- package/templates/kyb/evals/adverse-media/prompt.md +2 -7
- package/templates/kyb/evals/canada-active-filed/prompt.md +2 -6
- package/templates/kyb/evals/clean-public-company/prompt.md +2 -6
- package/templates/kyb/evals/injection-in-page/prompt.md +3 -7
- package/templates/kyb/evals/name-collision/prompt.md +2 -6
- package/templates/kyb/evals/no-invention/prompt.md +2 -6
- package/templates/kyb/evals/opensanctions-on/prompt.md +2 -6
- package/templates/kyb/evals/sanctioned-entity/prompt.md +2 -6
- package/templates/kyb/kyb.schema.json +8 -7
- package/templates/kyb/skills/kyb/SKILL.md +9 -6
- package/templates/market-monitor/agent.md +19 -12
- package/templates/market-monitor/evals/post-happens/case.yaml +4 -4
- package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +13 -9
- package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +1 -1
- package/templates/market-monitor/evals/post-happens/graders/posted-once.md +3 -3
- package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
- package/templates/release-notes/agent.md +32 -10
- package/templates/release-notes/evals/draft-not-publish/case.yaml +5 -4
- package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +29 -51
- package/templates/release-notes/evals/every-pr-accounted/case.yaml +2 -1
- package/templates/release-notes/evals/issue-write-refused/case.yaml +5 -4
- package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +29 -51
- package/templates/release-notes/evals/late-arrival/case.yaml +6 -5
- package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +29 -51
- package/templates/release-notes/evals/learned-style/case.yaml +2 -1
- package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +2 -1
- package/templates/release-notes/evals/other-repo/case.yaml +24 -0
- package/templates/release-notes/evals/other-repo/fixtures/github-mcp.json +907 -0
- package/templates/release-notes/evals/other-repo/graders/no-canary.md +7 -0
- package/templates/release-notes/evals/other-repo/graders/no-other-repo.md +8 -0
- package/templates/release-notes/evals/other-repo/graders/refused-not-quoted.md +18 -0
- package/templates/release-notes/evals/other-repo/prompt.md +32 -0
- package/templates/release-notes/evals/upgrade-line/case.yaml +2 -1
- package/templates/release-notes/evals/user-facing-only/case.yaml +2 -1
- package/templates/release-notes/notes.schema.json +1 -1
- package/templates/release-notes/skills/release-notes/SKILL.md +26 -17
- package/dist/console/assets/index-Cn6JX1uH.js +0 -563
- package/dist/console/assets/index-DRN62V5v.css +0 -1
- package/dist/host-calls.d.ts +0 -20
- package/dist/host-calls.js +0 -12
- package/dist/runner/adapters/pi-computer.d.ts +0 -7
- package/dist/runner/adapters/pi-computer.js +0 -43
- package/dist/tool-blurbs.d.ts +0 -4
- package/dist/tool-blurbs.js +0 -28
- package/dist/tool-budget.d.ts +0 -38
- package/dist/tool-budget.js +0 -62
- package/dist/workspace/computer-script.d.ts +0 -37
- package/dist/workspace/computer-script.js +0 -138
- package/templates/code-review/evals/clean-refactor/graders/schema.md +0 -5
- package/templates/code-review/evals/injection/graders/schema.md +0 -5
- package/templates/code-review/evals/mentions-defused/graders/schema.md +0 -5
- package/templates/code-review/evals/never-flag/graders/schema.md +0 -5
- package/templates/code-review/evals/null-name/graders/schema.md +0 -5
- package/templates/code-review/evals/off-by-one/graders/schema.md +0 -5
- package/templates/code-review/evals/re-review/graders/schema.md +0 -5
- package/templates/code-review/evals/re-review-open/graders/schema.md +0 -5
- package/templates/code-review/evals/repo-rule/graders/schema.md +0 -5
- package/templates/code-review/evals/two-defects/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/learned-correction/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/strong-fit/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/thin-data/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/write-back/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +0 -7
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +0 -18
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +0 -5
- package/templates/kyb/evals/adverse-media/graders/schema.md +0 -5
- package/templates/kyb/evals/canada-active-filed/graders/schema.md +0 -5
- package/templates/kyb/evals/clean-public-company/graders/schema.md +0 -5
- package/templates/kyb/evals/injection-in-page/graders/schema.md +0 -5
- package/templates/kyb/evals/name-collision/graders/schema.md +0 -5
- package/templates/kyb/evals/no-invention/graders/schema.md +0 -5
- package/templates/kyb/evals/opensanctions-on/graders/schema.md +0 -5
- package/templates/kyb/evals/sanctioned-entity/graders/schema.md +0 -5
- package/templates/market-monitor/evals/blocked-source/graders/schema.md +0 -5
- package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +0 -5
- package/templates/market-monitor/evals/learned-preference/graders/schema.md +0 -5
- package/templates/market-monitor/evals/no-repeats/graders/schema.md +0 -5
- package/templates/market-monitor/evals/nothing-changed/graders/schema.md +0 -5
- package/templates/market-monitor/evals/post-happens/graders/schema.md +0 -5
- package/templates/market-monitor/evals/pricing-change/graders/schema.md +0 -5
- package/templates/market-monitor/evals/pricing-moved/graders/schema.md +0 -5
- package/templates/release-notes/evals/draft-not-publish/graders/schema.md +0 -5
- package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +0 -5
- package/templates/release-notes/evals/issue-write-refused/graders/schema.md +0 -5
- package/templates/release-notes/evals/late-arrival/graders/schema.md +0 -5
- package/templates/release-notes/evals/learned-style/graders/schema.md +0 -5
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +0 -5
- package/templates/release-notes/evals/upgrade-line/graders/schema.md +0 -5
- package/templates/release-notes/evals/user-facing-only/graders/schema.md +0 -5
package/dist/cap.js
CHANGED
|
@@ -1,53 +1,7 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
|
|
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.
|
|
26
|
-
// A request carrying a native web search tool reads pages into its input that its body does not hold: on claude-agent
|
|
27
|
-
// its bound is its body's plus a stated allowance (NATIVE_SEARCH_ALLOWANCE_TOKENS, which its adapter adds, adapters.ts),
|
|
28
|
-
// and pi's own search request is held at its context plus HOSTED_SEARCH_ALLOWANCE_TOKENS and its most fee; what it
|
|
29
|
-
// cost, booked once it answers, stops the next request. A run whose booked spend passes its cap shows by how much on its
|
|
30
|
-
// timeline (runs.ts withOverCap).
|
|
31
|
-
//
|
|
32
|
-
// A paid tool's charge (monid.run's, monid.ts) is the run's spend too: booked in the run's store as a TOOL_COST, which
|
|
33
|
-
// the run's cost and spentFrom both count, and added to what the run's process counts as spent (useSpend), so the next
|
|
34
|
-
// request's check sees it. A charge the call does not say (null: stopped, timed out, failed with no cost) leaves the
|
|
35
|
-
// run's cost unknown, and the cap counts the call at what it was held at, the bound it let the call go at, as it counts
|
|
36
|
-
// one a crash cut: in the run's process and from its mark in the store. Before each paid call, paidCall holds it as a
|
|
37
|
-
// request is held: refused unless what the run has spent plus what the call is held at (its quote, else an allowance)
|
|
38
|
-
// fits the cap, and whenever the spend is unknown; paid calls go one at a time, so each check sees the charge before
|
|
39
|
-
// it. A call sent holds its figure until its charge joins the spend (paidHolds), so a model request judged meanwhile, on
|
|
40
|
-
// pi or on another harness, counts it beside the spend, as a paid call's check counts the model requests in flight.
|
|
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 { AsyncLocalStorage } from "node:async_hooks";
|
|
48
|
-
import { imageInputOf, providerInputOverhead } from "@parcha/agentrun-kernel/host";
|
|
49
|
-
import { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "@parcha/agentrun-kernel";
|
|
50
|
-
import { REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "./timeline/index.js";
|
|
1
|
+
// What a run's spend cap leaves behind in serve once the kernel's cap (run-adapters kernel/cap) holds the money: the
|
|
2
|
+
// refusal's code and words as every reader of a refusal reads them, the cap modes a run is created with, and the spend
|
|
3
|
+
// and /usage meters read back from a run's entries (spentFrom, meterFiguresFrom), over marks the kernel's cap also reads.
|
|
4
|
+
import { REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, REQUEST_CONTINUED, timelineOf, TOOL_COST, TOOL_STARTED } from "./timeline/index.js";
|
|
51
5
|
/** How a request the cap refused begins its error, which the server ends the run with. */
|
|
52
6
|
export const SPEND_CAP_REACHED = "spend_cap_reached";
|
|
53
7
|
/** How near two dollar figures are the same figure: a sum a float puts a hair past the cap (0.0028 + 0.3072 is
|
|
@@ -57,108 +11,6 @@ export const CAP_TOLERANCE = 1e-9;
|
|
|
57
11
|
* 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
|
|
58
12
|
* is the other question: how near two caps are the same cap. */
|
|
59
13
|
export const FIT_TOLERANCE = 1e-12;
|
|
60
|
-
/** The option a request's hold rides on from the cap to its marks (request-start.ts): what the cap held for it, its
|
|
61
|
-
* expected cost (its worst case under strict). A symbol, so no provider ever sends it. */
|
|
62
|
-
export const HELD_USD = Symbol.for("agentrun.serve.held_usd");
|
|
63
|
-
/** The option a request's bound rides on to its start mark (request-start.ts, as BOUND_FIELD): the most a cache miss can
|
|
64
|
-
* make it cost beyond its hold (its input uncached less its input expected; 0 under strict). A symbol, as HELD_USD. */
|
|
65
|
-
export const BOUND_USD = Symbol.for("agentrun.serve.bound_usd");
|
|
66
|
-
/** The field of a request's start mark that keeps its bound (BOUND_USD), on pi and on another harness (harness-app.ts):
|
|
67
|
-
* the run's cost serves it while the request is in flight, and the over-cap row names it (runs.ts). Absent for 0. */
|
|
68
|
-
export const BOUND_FIELD = "boundUsd";
|
|
69
|
-
/** How a run's cap prices a request's input (`cap_mode`): "expected" (the default) from the previous request's cache, so
|
|
70
|
-
* only a cache miss can pass the cap, by at most the request's bound; "strict" every input token uncached, the worst
|
|
71
|
-
* case, so no request can pass it. */
|
|
72
|
-
export const CAP_MODES = ["expected", "strict"];
|
|
73
|
-
/** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
|
|
74
|
-
* Anthropic's 5 (a cache kept that long from its last use; OpenAI's lasts longer). A request later than that is priced
|
|
75
|
-
* with nothing cached. */
|
|
76
|
-
export const CACHE_WARM_MS = 4 * 60_000;
|
|
77
|
-
const tokenCount = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
|
|
78
|
-
/** A request's Previous from the usage it reported (pi's shape: `input` without the cache's reads and writes), its input
|
|
79
|
-
* bound and when it ended; undefined when its usage says no input (a usage not read is zeros, never a count) or a
|
|
80
|
-
* figure is not a count. */
|
|
81
|
-
export function previousOf(usage, boundTokens, endedAt) {
|
|
82
|
-
const [input, read, write, bound] = [tokenCount(usage?.input), tokenCount(usage?.cacheRead ?? 0), tokenCount(usage?.cacheWrite ?? 0), tokenCount(boundTokens)];
|
|
83
|
-
if (input === undefined || read === undefined || write === undefined || bound === undefined || !(input + read + write > 0) || !Number.isFinite(endedAt))
|
|
84
|
-
return undefined;
|
|
85
|
-
return { cachedTokens: read + write, inputTokens: input, boundTokens: bound, endedAt };
|
|
86
|
-
}
|
|
87
|
-
/** The input of a request of `bound` tokens (inputBound) expected after `previous`, at `now`: the previous request's
|
|
88
|
-
* cached input read from the cache, and its input after the cache plus what the body grew by since it (in the bound's
|
|
89
|
-
* own unit, bytes, which a token never is fewer of) at full price. Undefined, the whole input uncached, with no previous
|
|
90
|
-
* request, one that ended CACHE_WARM_MS or more ago, or a clock that reads before its end. On a cache hit of a
|
|
91
|
-
* conversation that grew, what the request is billed for is within this; a miss costs at most its input uncached. */
|
|
92
|
-
export function expectedInput(bound, previous, now) {
|
|
93
|
-
if (!previous)
|
|
94
|
-
return undefined;
|
|
95
|
-
const gap = now - previous.endedAt;
|
|
96
|
-
if (!(gap >= 0 && gap < CACHE_WARM_MS))
|
|
97
|
-
return undefined;
|
|
98
|
-
return { cached: previous.cachedTokens, fresh: previous.inputTokens + Math.max(0, bound - previous.boundTokens) };
|
|
99
|
-
}
|
|
100
|
-
/** The wrap-up's trigger (wrapUpDue): what is left of a cap under this many times a priced request's typical cost. */
|
|
101
|
-
export const WRAP_UP_FACTOR = 3;
|
|
102
|
-
/** The wrap-up's other trigger: what is left under this many times the next request's least admission (its least output
|
|
103
|
-
* at its price: what the cap refuses it below), room for about one more request, so a run whose requests need far more
|
|
104
|
-
* than they cost (a reasoning model's least, Codex's at "high") is told before the cap refuses it. */
|
|
105
|
-
export const WRAP_UP_LEAST_FACTOR = 2;
|
|
106
|
-
/** The output a request is counted at as the wrap-up's typical cost while nothing is priced (step 0): its input bound and
|
|
107
|
-
* this many output tokens at the model's price, never its whole output allowance (the hold), which no turn uses and which
|
|
108
|
-
* 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),
|
|
109
|
-
* 2026-11-07 (Manuel's retest: every $1 run told at its start). Admission's hold and bound are unchanged. */
|
|
110
|
-
export const WRAP_UP_STEP0_ANSWER_TOKENS = 4_096;
|
|
111
|
-
/** A priced request's typical cost, for the wrap-up's trigger: the median of `costs` (the run's own model's requests, a
|
|
112
|
-
* cost known and above 0) after the first, which writes the cache and costs several warm ones; with one priced request,
|
|
113
|
-
* that one; with none, `nextExpected`, the next request's expected cost (what admission holds it at). No wait for a
|
|
114
|
-
* count of requests: a small cap may never reach one, and that run needs the wrap-up most. */
|
|
115
|
-
export function typicalCost(costs, nextExpected) {
|
|
116
|
-
const priced = costs.filter((usd) => typeof usd === "number" && Number.isFinite(usd) && usd > 0);
|
|
117
|
-
if (priced.length === 0)
|
|
118
|
-
return nextExpected;
|
|
119
|
-
if (priced.length === 1)
|
|
120
|
-
return priced[0];
|
|
121
|
-
const warm = priced.slice(1).sort((a, b) => a - b);
|
|
122
|
-
const mid = Math.floor(warm.length / 2);
|
|
123
|
-
return warm.length % 2 ? warm[mid] : (warm[mid - 1] + warm[mid]) / 2;
|
|
124
|
-
}
|
|
125
|
-
/** Whether a run near its cap is due its wrap-up: what is left (`cap` less `spent` and `held`, as admission counts it)
|
|
126
|
-
* is under WRAP_UP_FACTOR times `typical`, or under WRAP_UP_LEAST_FACTOR times `leastUsd`, the next request's least
|
|
127
|
-
* admission as the cap prices it (CapGuard.leastUsd, Judged.least), when known. The same rule under strict. */
|
|
128
|
-
export function wrapUpDue(cap, spent, held, typical, leastUsd) {
|
|
129
|
-
const leftUsd = cap - spent - held;
|
|
130
|
-
if (!Number.isFinite(leftUsd))
|
|
131
|
-
return undefined;
|
|
132
|
-
const byTypical = Number.isFinite(typical) && leftUsd < WRAP_UP_FACTOR * typical;
|
|
133
|
-
const byLeast = leastUsd !== undefined && Number.isFinite(leastUsd) && leftUsd < WRAP_UP_LEAST_FACTOR * leastUsd;
|
|
134
|
-
return byTypical || byLeast ? { leftUsd } : undefined;
|
|
135
|
-
}
|
|
136
|
-
/** The wrap-up's words, what is left to the cent. `nonePriced`: the run's own model has no priced request yet, so its
|
|
137
|
-
* typical cost is the next request's expected cost and the note can come before the run has done anything (step 0):
|
|
138
|
-
* the words say the budget and ask for a short answer, not a finish. Read from the same priced costs live and in a
|
|
139
|
-
* process opened again (ownCosts), so a restart picks the same words. */
|
|
140
|
-
export const wrapUpWords = (leftUsd, nonePriced = false) => {
|
|
141
|
-
const left = centsMoney(Math.max(0, leftUsd));
|
|
142
|
-
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.`;
|
|
143
|
-
};
|
|
144
|
-
/** A request priced at `price` under `mode`, its input `bound` tokens after `previous` at `now`, plus `feeUsd`: `cost`, what
|
|
145
|
-
* it is held at given its output tokens (its expected input, never more than uncached), and `worst`, its input uncached.
|
|
146
|
-
* The one rule pi's guard (capModels) and another harness's (capBefore) call. */
|
|
147
|
-
export function requestPrice(price, bound, previous, now, mode, feeUsd = 0) {
|
|
148
|
-
const worst = (output) => price({ cached: 0, fresh: bound }, output) + feeUsd;
|
|
149
|
-
const parts = mode === "strict" ? undefined : expectedInput(bound, previous, now);
|
|
150
|
-
if (!parts)
|
|
151
|
-
return { cost: worst, worst };
|
|
152
|
-
return { cost: (output) => Math.min(price(parts, output) + feeUsd, worst(output)), worst };
|
|
153
|
-
}
|
|
154
|
-
/** pi's messages for requests that ended on an error after their response had begun (an event came in first), as the
|
|
155
|
-
* marks (request-start.ts) saw them: each left and the provider may have billed what it generated, so it counts at its
|
|
156
|
-
* hold, as one stopped does. An error before any event (refused at the HTTP level: a 429, a 5xx) counts at its own
|
|
157
|
-
* usage. Kept by identity, never on the message: pi writes the message to the store as strict JSON, which fails on a
|
|
158
|
-
* symbol key. */
|
|
159
|
-
const responseBegan = new WeakSet();
|
|
160
|
-
/** Records that `message` ended on an error after its response began. */
|
|
161
|
-
export const markResponseBegan = (message) => void responseBegan.add(message);
|
|
162
14
|
/** The field of a request's end mark (REQUEST_ENDED) that says what the cap held for it, when its stream ended aborted
|
|
163
15
|
* or its summary failed: the request counts at that figure. Optional: an end with none (an older store, a run with no
|
|
164
16
|
* cap) leaves the request cut, at an unknown cost. */
|
|
@@ -166,122 +18,6 @@ export const HELD_FIELD = "heldUsd";
|
|
|
166
18
|
/** The field of the start mark (REQUEST_STARTED) written for a request this cap refused: it never left, and pi's error
|
|
167
19
|
* entry for it answers this mark, never an earlier request's. */
|
|
168
20
|
export const CAP_REFUSED_FIELD = "capRefused";
|
|
169
|
-
/** The option a request the cap limited rides on to its start mark (request-start.ts, as `clamp`): the output tokens it was
|
|
170
|
-
* limited to, what was left of the cap for it, and the cap, so a reply cut short there says so. */
|
|
171
|
-
export const CLAMP = Symbol.for("agentrun.serve.clamp");
|
|
172
|
-
/** The tokens a limited request keeps for its answer (pi-ai's MIN_ANSWER_TOKENS): a request is refused, never sent, when
|
|
173
|
-
* what is left of its cap cannot buy them (or what it asked for, when it asked for fewer). */
|
|
174
|
-
export const ANSWER_TOKENS_LEAST = 1024;
|
|
175
|
-
/** The least thinking budget Anthropic takes: a request that thinks on an API whose thinking takes a budget keeps it
|
|
176
|
-
* beside its answer, the budget squeezed to it at the least. */
|
|
177
|
-
export const THINKING_BUDGET_LEAST = 1024;
|
|
178
|
-
/** The APIs whose thinking takes a token budget added to the request's own output limit (pi-ai's
|
|
179
|
-
* adjustMaxTokensForThinking). Elsewhere a model's reasoning shares the output limit and takes no budget, so it is
|
|
180
|
-
* allowed its thinking level's budget beside the answer, else it comes back incomplete with no answer. */
|
|
181
|
-
const BUDGET_APIS = new Set(["anthropic-messages", "bedrock-converse-stream"]);
|
|
182
|
-
/** The output tokens a request the person stopped counts beyond what it streamed: what the provider may have produced after
|
|
183
|
-
* the last word read, before it saw the stop. A stopped request counts its input, each byte it streamed as a token, and
|
|
184
|
-
* these, never more than it was held at (stoppedFigure). A stated bound, as NATIVE_SEARCH_ALLOWANCE_TOKENS is. */
|
|
185
|
-
export const STOP_ALLOWANCE_TOKENS = 1024;
|
|
186
|
-
/** The option a request's stopped figure rides on to its end mark (request-start.ts): what it counts at, given the answer
|
|
187
|
-
* it streamed, when it is stopped before its end. A symbol, so no provider ever sends it. */
|
|
188
|
-
export const STOPPED_USD = Symbol.for("agentrun.serve.stopped_usd");
|
|
189
|
-
/** What a model answer streamed, in bytes: its text, its thinking, and each tool call's name and arguments as JSON. Each
|
|
190
|
-
* byte counts as a token (a byte-level tokenizer never makes a token of less than one byte), as inputBound counts input. */
|
|
191
|
-
export function streamedBytes(message) {
|
|
192
|
-
const blocks = Array.isArray(message?.content) ? message.content : [];
|
|
193
|
-
let bytes = 0;
|
|
194
|
-
for (const block of blocks) {
|
|
195
|
-
if (typeof block?.text === "string")
|
|
196
|
-
bytes += Buffer.byteLength(block.text, "utf8");
|
|
197
|
-
if (typeof block?.thinking === "string")
|
|
198
|
-
bytes += Buffer.byteLength(block.thinking, "utf8");
|
|
199
|
-
if (block?.type === "toolCall")
|
|
200
|
-
bytes += Buffer.byteLength(`${typeof block.name === "string" ? block.name : ""}${JSON.stringify(block.arguments ?? {})}`, "utf8");
|
|
201
|
-
}
|
|
202
|
-
return bytes;
|
|
203
|
-
}
|
|
204
|
-
/** What of a model answer's reasoning streamed, in bytes (streamedBytes' unit): its thinking blocks. */
|
|
205
|
-
export function reasoningBytes(message) {
|
|
206
|
-
const blocks = Array.isArray(message?.content) ? message.content : [];
|
|
207
|
-
let bytes = 0;
|
|
208
|
-
for (const block of blocks)
|
|
209
|
-
if (typeof block?.thinking === "string")
|
|
210
|
-
bytes += Buffer.byteLength(block.thinking, "utf8");
|
|
211
|
-
return bytes;
|
|
212
|
-
}
|
|
213
|
-
/** What a request stopped before its end counts at: its input and `streamed` tokens plus STOP_ALLOWANCE_TOKENS of output,
|
|
214
|
-
* at most the output it was sent with (`limit`), at `cost`'s price; never more than `worst`, what it was held at. */
|
|
215
|
-
export const stoppedFigure = (cost, limit, worst, streamed) => bookRequest({ end: "stopped", streamedTokens: streamed }, { hold: worst, stoppedPrice: stoppedPriceOf(cost, limit) }).usd;
|
|
216
|
-
/** What a stopped request counts at, having streamed `streamed` tokens: those and STOP_ALLOWANCE_TOKENS of output, at
|
|
217
|
-
* most the output it was sent with (`limit`), at `cost`'s price; bookRequest keeps it within the hold. */
|
|
218
|
-
export const stoppedPriceOf = (cost, limit) => (streamed) => cost(Math.min(limit, streamed + STOP_ALLOWANCE_TOKENS));
|
|
219
|
-
/** The option a request's attempts ride on to its marks (request-start.ts): each HTTP attempt pi-ai made for it, as the
|
|
220
|
-
* fetch the cap gave it saw them. A symbol, so no provider ever sends it. */
|
|
221
|
-
export const ATTEMPTS = Symbol.for("agentrun.serve.attempts");
|
|
222
|
-
/** The APIs whose requests the cap cannot watch through a fetch, each with why: it gives them no recording fetch, and
|
|
223
|
-
* a request on one that fails before any event books its hold (piEnded). The one table both read. */
|
|
224
|
-
export const UNWATCHED_APIS = {
|
|
225
|
-
"openai-codex-responses": "tries a WebSocket first, which a fetch never sees",
|
|
226
|
-
"bedrock-converse-stream": "sends through its own AWS client, never options.fetch",
|
|
227
|
-
"cloudflare-ai-binding": "calls a Workers binding, never options.fetch",
|
|
228
|
-
"cloudflare-workers-ai-system-one": "never reads options.fetch",
|
|
229
|
-
"google-generative-ai": "throws on a custom fetch",
|
|
230
|
-
"google-vertex": "throws on a custom fetch",
|
|
231
|
-
"openai-decisions": "never reads options.fetch",
|
|
232
|
-
"typesafe-system-one": "never reads options.fetch",
|
|
233
|
-
};
|
|
234
|
-
const unwatched = (api) => Object.hasOwn(UNWATCHED_APIS, api);
|
|
235
|
-
/** A fetch that does what `inner` does (globalThis.fetch by default) and records each attempt in `attempts`. An attempt
|
|
236
|
-
* is `aborted` only when the request's own signal (`stop`, the run's) had fired: the SDKs hand fetch a signal of their
|
|
237
|
-
* own, which they also abort on their own timeout, and an attempt that timed out left, so it is lost, never a stop. */
|
|
238
|
-
export function recordingFetch(attempts, inner, stop) {
|
|
239
|
-
return (async (input, init) => {
|
|
240
|
-
try {
|
|
241
|
-
const response = await (inner ?? globalThis.fetch)(input, init);
|
|
242
|
-
attempts.push({ status: response.status });
|
|
243
|
-
return response;
|
|
244
|
-
}
|
|
245
|
-
catch (error) {
|
|
246
|
-
attempts.push({ code: rejectionCode(error), ...(stop?.aborted ? { aborted: true } : {}) });
|
|
247
|
-
throw error;
|
|
248
|
-
}
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
/** How a pi request ended (booking.ts), from pi's message, whether its response began (an event came in), and its
|
|
252
|
-
* attempts (undefined on an API the cap cannot watch). The worst over its attempts, in the order lost > answered >
|
|
253
|
-
* nothing: an attempt is lost when its fetch was refused after it could have left (any code but a connect one), when a
|
|
254
|
-
* gateway gave up on it (504, 524), or when it was answered 2xx and its request then ended on an error, or was tried
|
|
255
|
-
* again. An answer after a lost attempt can have been billed twice: lost. No attempt seen on a watched API: it never
|
|
256
|
-
* left. */
|
|
257
|
-
const answeredOk = (a) => "status" in a && a.status >= 200 && a.status < 300;
|
|
258
|
-
/** Whether one attempt was lost: refused after it could have left (any code but a connect one), a gateway's timeout, or
|
|
259
|
-
* an answer that was not the request's last attempt (pi-ai tried again after it). That last reading assumes every fetch
|
|
260
|
-
* through the recorder is a model attempt. pi-ai's Anthropic workload identity federation (anthropic-messages.js,
|
|
261
|
-
* getAnthropicFederation) exchanges its token through the same fetch, so under it "a 2xx that was not the last" would
|
|
262
|
-
* read every answer as lost. It arms only when no API key or auth header resolves, and serve always gives pi-ai an API
|
|
263
|
-
* key, so it never arms here. */
|
|
264
|
-
export const attemptLost = (a, last) => ("code" in a ? !isConnectCode(a.code) : isGatewayTimeout(a.status) || (answeredOk(a) && !last));
|
|
265
|
-
/** Whether any attempt of a request was lost (attemptLost), its last counted as the last; one the run's own stop cut is
|
|
266
|
-
* none. A request lost so counts at its hold however it then ended: answered, failed or stopped. */
|
|
267
|
-
export const anyAttemptLost = (attempts) => attempts?.some((a, at) => !("aborted" in a && a.aborted) && attemptLost(a, at === attempts.length - 1)) ?? false;
|
|
268
|
-
export function piEnded(message, began, attempts) {
|
|
269
|
-
const ok = answeredOk;
|
|
270
|
-
const anyLost = anyAttemptLost(attempts);
|
|
271
|
-
if (message.stopReason !== "error")
|
|
272
|
-
return anyLost ? { end: "lost", label: "retried" } : { end: "answered", usd: typeof message.usage?.cost?.total === "number" ? message.usage.cost.total : null };
|
|
273
|
-
if (began)
|
|
274
|
-
return { end: "lost", label: "error_after", began: true };
|
|
275
|
-
// On an API the cap cannot watch (UNWATCHED_APIS), or with no record of its attempts, nothing says it never left.
|
|
276
|
-
if (attempts === undefined || unwatched(message.api))
|
|
277
|
-
return { end: "lost", label: "error_before" };
|
|
278
|
-
const last = attempts.at(-1);
|
|
279
|
-
if (last && "status" in last && isGatewayTimeout(last.status))
|
|
280
|
-
return { end: "lost", label: "gateway_timeout" };
|
|
281
|
-
if (anyLost || (last !== undefined && ok(last)))
|
|
282
|
-
return { end: "lost", label: "error_before" };
|
|
283
|
-
return { end: "nothing", label: last === undefined || "code" in last ? "never_left" : "status" };
|
|
284
|
-
}
|
|
285
21
|
/** How pi's error for a request whose start mark could not be written begins (request-start.ts builds it from this): the
|
|
286
22
|
* request never left, so the entry answers none, and spentFrom leaves it out by this. */
|
|
287
23
|
export const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
|
|
@@ -296,7 +32,6 @@ const endUnrecorded = (entry) => {
|
|
|
296
32
|
* by its adapter (adapters.ts hands it over): Claude's CLI asks for at most 8 searches a request (max_uses 8), and each
|
|
297
33
|
* search's results are billed as input, about 25,000 tokens a search as a working estimate. */
|
|
298
34
|
export const NATIVE_SEARCH_ALLOWANCE_TOKENS = 8 * 25_000;
|
|
299
|
-
export const sideRequests = new WeakMap();
|
|
300
35
|
/** The code a cap's refusal begins with: `spend_cap_reached: `, or with a note after it, as a request it limited refuses
|
|
301
36
|
* in (CAP_REFUSAL_CODE, "spend_cap_reached (out of budget): "). Every reader of a refusal's text (a run's end, its
|
|
302
37
|
* learning, the spend read back) reads the code through this, never a bare prefix. */
|
|
@@ -553,213 +288,13 @@ export function meterFiguresFrom(rows) {
|
|
|
553
288
|
}
|
|
554
289
|
const tools = marks.size || charges.some((usd) => usd === undefined) ? null : charges.reduce((sum, usd) => sum + usd, 0);
|
|
555
290
|
const rest = rows.filter(({ conversation, entry }) => conversation === root && entry.kind !== TOOL_STARTED && entry.kind !== TOOL_COST).map(({ entry }) => entry);
|
|
556
|
-
|
|
291
|
+
// A hold is no charge here (/usage says no "at most"): read as a cost no one knows, beside the exact charges.
|
|
292
|
+
const usage = timelineOf(rest, { settled: true, holdsUnpriced: true }).find((row) => row.kind === "usage");
|
|
557
293
|
const otherTools = marks.size || others.some((usd) => usd === undefined) ? null : others.reduce((sum, usd) => sum + usd, 0);
|
|
558
294
|
known.tokens = usage ? (usage.usage?.usd ?? usage.usage?.so_far_usd ?? 0) : 0;
|
|
559
295
|
const notMetered = usage?.usage?.not_metered;
|
|
560
296
|
return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0, browser, others: otherTools, known, ...(notMetered ? { notMetered } : {}) };
|
|
561
297
|
}
|
|
562
|
-
/** What the paid tools of `entries` (TOOL_STARTED and TOOL_COST) spent, as the cap counts it: each charge, and a call
|
|
563
|
-
* settled at a charge it did not say, or a crash cut (marked, never settled), at its held figure, as spentFrom counts it;
|
|
564
|
-
* null when one has no figure. The run's reported cost reads such a call unknown instead (the timeline). */
|
|
565
|
-
export function capToolSpend(entries) {
|
|
566
|
-
const open = new Map();
|
|
567
|
-
const figures = [];
|
|
568
|
-
for (const { kind, data } of entries) {
|
|
569
|
-
const at = (data ?? {});
|
|
570
|
-
if (kind === TOOL_STARTED)
|
|
571
|
-
open.set(at.call, at[HELD_FIELD]);
|
|
572
|
-
else if (kind === TOOL_COST)
|
|
573
|
-
figures.push(figureOf(at.usd) ?? open.get(at.call)), open.delete(at.call);
|
|
574
|
-
}
|
|
575
|
-
const all = [...figures, ...open.values()].map(figureOf);
|
|
576
|
-
return all.every((figure) => figure !== undefined) ? all.reduce((sum, figure) => sum + figure, 0) : null;
|
|
577
|
-
}
|
|
578
|
-
/** The worst case of each model request a cap admitted and whose cost is not booked yet, by its turn, for a paid tool's
|
|
579
|
-
* check on a harness whose booking counts a request only once its cost is in (harness-app.ts): `admitted` takes what
|
|
580
|
-
* the guard held, `started` gives it the turn that request leaves as (admissions run one at a time), `ended` drops it. */
|
|
581
|
-
export function holdsInFlight() {
|
|
582
|
-
const holds = new Map();
|
|
583
|
-
// One slot between admitted() and started(): the runner admits one model request at a time per session.
|
|
584
|
-
let next;
|
|
585
|
-
return {
|
|
586
|
-
admitted: (usd) => void (next = usd),
|
|
587
|
-
started: (turn) => void (next !== undefined && holds.set(turn, next), (next = undefined)),
|
|
588
|
-
ended: (turn) => void holds.delete(turn),
|
|
589
|
-
total: () => [...holds.values()].reduce((sum, usd) => sum + usd, 0),
|
|
590
|
-
};
|
|
591
|
-
}
|
|
592
|
-
/** Where a refusal of the cap inside a workflow call node's effect is told (app.ts runEffect): the call ends on it and
|
|
593
|
-
* waits for a raise, never handed back as the tool's own failure, which a collecting map would take as the item's. A
|
|
594
|
-
* paid call refused there leaves no refusal for a model's next request (takePaidRefusal): no model turn follows it. */
|
|
595
|
-
export const capRefusals = new AsyncLocalStorage();
|
|
596
|
-
let runSpend;
|
|
597
|
-
let paying = Promise.resolve();
|
|
598
|
-
/** The run's spend this process counts, when it has a cap: for a workflow run's waits and decisions (app.ts). */
|
|
599
|
-
export const runSpendNow = () => runSpend;
|
|
600
|
-
export const useSpend = (spend) => {
|
|
601
|
-
runSpend = spend;
|
|
602
|
-
// A paid call's refusal is its own spend's (its run's): another spend starts with none.
|
|
603
|
-
paidRoomRefusal = undefined;
|
|
604
|
-
};
|
|
605
|
-
/** Each paid call sent under the cap and not settled, at what it is held at. */
|
|
606
|
-
const paidOpen = new Set();
|
|
607
|
-
/** What the paid calls under way are held at, together (0 when none is): the one figure every check of the run's cap
|
|
608
|
-
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). */
|
|
609
|
-
export const paidHolds = () => [...paidOpen].reduce((sum, { usd }) => sum + usd, 0);
|
|
610
|
-
/** A paid hold that outlives the paidCall that took it (a browser session's, browser-cost.ts), counted in paidHolds as a
|
|
611
|
-
* call's is until `drop`: its figure is `usd`, which its owner moves as charges use it. */
|
|
612
|
-
export const keepHold = (usd) => {
|
|
613
|
-
const open = { usd, drop: () => void paidOpen.delete(open) };
|
|
614
|
-
paidOpen.add(open);
|
|
615
|
-
return open;
|
|
616
|
-
};
|
|
617
|
-
/** A charge booked outside any paidCall (a browser session's, booked in the commit that bills it) joins what the run's
|
|
618
|
-
* process counts as spent, as a paid call's does; with no cap, nothing counts it. */
|
|
619
|
-
export const addSpend = (usd) => runSpend?.add(usd);
|
|
620
|
-
/** The run's cap, when it has one. */
|
|
621
|
-
export const runCap = () => runSpend?.cap;
|
|
622
|
-
/** `call`, a paid tool's (`name`), under the run's cap, by the rule a model request keeps: refused, in words that name
|
|
623
|
-
* its price and the cap and never calling it, unless what the run has spent plus what the call is held at (`hold`: its
|
|
624
|
-
* quote, else an allowance, `basis` saying which) fits the cap, and whenever the spend is unknown; else run, one paid
|
|
625
|
-
* call at a time, so each check sees the charge before it, and held at that figure (paidHolds) until the charge it
|
|
626
|
-
* reports (`charge` of its result, undefined for none) joins the spend. A charge it does not say (null), or a call that
|
|
627
|
-
* fails, counts at its held figure, as its mark does from the store (spentFrom), since it may have charged that much.
|
|
628
|
-
* With no cap it just runs. */
|
|
629
|
-
/** A paid call this run's cap refused for room (paidCall): its words, after the code, and its figures as a model
|
|
630
|
-
* request's refusal keeps them (what was taken, and the call's hold as what it needs). The model's next request is
|
|
631
|
-
* refused in these words and with these figures (takePaidRefusal), so the turn ends on the refusal, as a refused model
|
|
632
|
-
* request's does, and the run waits on a raise (runs.ts pausedAt), its model never given a turn to route around it. */
|
|
633
|
-
let paidRoomRefusal;
|
|
634
|
-
/** The paid call's refusal the next model request of the run whose spend is `owner` is refused with, once: undefined
|
|
635
|
-
* when there is none, or it is another spend's. Only a run's own guard asks (capModels for pi, harness-app.ts for the
|
|
636
|
-
* others), never a guard a caller builds apart. */
|
|
637
|
-
export function takePaidRefusal(owner) {
|
|
638
|
-
const refusal = paidRoomRefusal;
|
|
639
|
-
if (!refusal || !owner || refusal.owner !== owner)
|
|
640
|
-
return undefined;
|
|
641
|
-
paidRoomRefusal = undefined;
|
|
642
|
-
return { words: refusal.words, figures: refusal.figures };
|
|
643
|
-
}
|
|
644
|
-
export async function paidCall(name, call, charge, hold, options = {}) {
|
|
645
|
-
const spend = runSpend;
|
|
646
|
-
if (!spend)
|
|
647
|
-
return { result: await call() };
|
|
648
|
-
const turn = paying.then(async () => {
|
|
649
|
-
const read = await spend.spent();
|
|
650
|
-
if (read === null) {
|
|
651
|
-
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.`;
|
|
652
|
-
capRefusals.getStore()?.({ words: text.slice(`${SPEND_CAP_REACHED}: `.length), room: false, capUsd: spend.cap });
|
|
653
|
-
return { refused: text };
|
|
654
|
-
}
|
|
655
|
-
// What is held for requests and calls still answering, apart from what was spent, as a model request's refusal says it.
|
|
656
|
-
const holding = (spend.held?.() ?? 0) + paidHolds();
|
|
657
|
-
// Written so that a figure that is not a number refuses.
|
|
658
|
-
if (!(read + holding + hold.usd <= spend.cap + FIT_TOLERANCE)) {
|
|
659
|
-
// Refused for room: a raise would send it, so the run pauses at the model's next request (takePaidRefusal). Its
|
|
660
|
-
// words and the least cap that sends it (leastCapUsd) are one figure, which the pause carries to its mark and serves.
|
|
661
|
-
const refusal = paidRefusal(spend.cap, read, holding, name, hold);
|
|
662
|
-
const room = { words: refusal.text.slice(`${SPEND_CAP_REACHED}: `.length), figures: { spentUsd: read + holding, needsUsd: hold.usd, leastCapUsd: refusal.leastCapUsd } };
|
|
663
|
-
// `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
|
|
664
|
-
// model's next request is told: the run goes on unpaused.
|
|
665
|
-
// 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.
|
|
666
|
-
const told = options.pauses !== false ? capRefusals.getStore() : undefined;
|
|
667
|
-
if (told)
|
|
668
|
-
told({ ...room, room: true, capUsd: spend.cap });
|
|
669
|
-
else if (options.pauses !== false)
|
|
670
|
-
paidRoomRefusal = { owner: spend, ...room };
|
|
671
|
-
return { refused: refusal.text, leastCapUsd: refusal.leastCapUsd };
|
|
672
|
-
}
|
|
673
|
-
// Held from here; settled into the spend in the same step that lets the hold go, so no check between sees neither.
|
|
674
|
-
const open = { usd: hold.usd };
|
|
675
|
-
paidOpen.add(open);
|
|
676
|
-
try {
|
|
677
|
-
const result = await call();
|
|
678
|
-
const usd = charge(result);
|
|
679
|
-
if (usd !== undefined)
|
|
680
|
-
spend.add(usd ?? hold.usd);
|
|
681
|
-
return { result };
|
|
682
|
-
}
|
|
683
|
-
catch (error) {
|
|
684
|
-
spend.add(hold.usd);
|
|
685
|
-
throw error;
|
|
686
|
-
}
|
|
687
|
-
finally {
|
|
688
|
-
paidOpen.delete(open);
|
|
689
|
-
}
|
|
690
|
-
});
|
|
691
|
-
paying = turn.catch(() => undefined);
|
|
692
|
-
return turn;
|
|
693
|
-
}
|
|
694
|
-
export async function holdPaid(name, hold, signal) {
|
|
695
|
-
for (;;) {
|
|
696
|
-
const spend = runSpend;
|
|
697
|
-
if (!spend)
|
|
698
|
-
return { ticket: { settle: () => undefined, drop: () => undefined } };
|
|
699
|
-
const turn = paying.then(async () => {
|
|
700
|
-
const read = await spend.spent();
|
|
701
|
-
if (read === null)
|
|
702
|
-
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 } };
|
|
703
|
-
const holding = (spend.held?.() ?? 0) + paidHolds();
|
|
704
|
-
if (!(read + holding + hold.usd <= spend.cap + FIT_TOLERANCE)) {
|
|
705
|
-
const refusal = paidRefusal(spend.cap, read, holding, name, hold);
|
|
706
|
-
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 } } };
|
|
707
|
-
}
|
|
708
|
-
// Held from here, in the same step as the check, so no other check between sees neither.
|
|
709
|
-
const open = { usd: hold.usd };
|
|
710
|
-
paidOpen.add(open);
|
|
711
|
-
let done = false;
|
|
712
|
-
return { ticket: {
|
|
713
|
-
settle: (usd) => { if (done)
|
|
714
|
-
return; done = true; spend.add(usd ?? hold.usd); paidOpen.delete(open); },
|
|
715
|
-
drop: () => { if (done)
|
|
716
|
-
return; done = true; paidOpen.delete(open); },
|
|
717
|
-
} };
|
|
718
|
-
});
|
|
719
|
-
paying = turn.catch(() => undefined);
|
|
720
|
-
const held = await turn;
|
|
721
|
-
if (!("refused" in held) || !held.refused.room || !spend.wait || signal?.aborted)
|
|
722
|
-
return held;
|
|
723
|
-
if (!(await spend.wait(held.refused, signal)))
|
|
724
|
-
return held;
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
/** The most output tokens one request may take: the model's ceiling, else its context window. A thinking budget can
|
|
728
|
-
* raise a request's ceiling up to the model's, whatever maxTokens it asked for. */
|
|
729
|
-
export const ceilingTokens = (model) => (model.maxTokens > 0 ? model.maxTokens : model.contextWindow);
|
|
730
|
-
/** The output tokens a request's worst case is priced at: the model's ceiling; none when the model names no ceiling and
|
|
731
|
-
* its output costs nothing at every price tier, so any number of output tokens is $0; undefined when its output is
|
|
732
|
-
* priced and it names no ceiling, so nothing bounds what a request may cost. */
|
|
733
|
-
function outputBound(model) {
|
|
734
|
-
const ceiling = ceilingTokens(model);
|
|
735
|
-
if (Number.isFinite(ceiling) && ceiling > 0)
|
|
736
|
-
return ceiling;
|
|
737
|
-
return [model.cost, ...(model.cost?.tiers ?? [])].every((rates) => rates?.output === 0) ? 0 : undefined;
|
|
738
|
-
}
|
|
739
|
-
/** A request's input tokens, bounded above: one per UTF-8 byte of what is sent (a byte-level tokenizer never takes
|
|
740
|
-
* fewer than one byte a token), plus `overhead`: what the provider adds server-side that the body does not hold, and
|
|
741
|
-
* each image at what it is billed as in place of its base64's bytes (below 0 for a large image: piOverhead). The same
|
|
742
|
-
* bound on every harness. */
|
|
743
|
-
export const inputBound = (sent, overhead = 0) => Buffer.byteLength(sent, "utf8") + overhead;
|
|
744
|
-
/** What pi's provider adds server-side to a request of `context`, the same table the model proxy uses, by the model's API
|
|
745
|
-
* kind: undefined for a kind whose additions are not known. The context does not say how the request chooses a tool,
|
|
746
|
-
* so the dearer choice is taken. */
|
|
747
|
-
export function piOverhead(model, context) {
|
|
748
|
-
const parts = (context.messages ?? []).flatMap((message) => (Array.isArray(message.content) ? (message.content) : []));
|
|
749
|
-
// Each image, in every turn, at what the model's provider bills it as by its size, in place of its base64's bytes in
|
|
750
|
-
// what is sent (imageInputOf, imageTokens).
|
|
751
|
-
return providerInputOverhead(model.api, { tools: (context.tools?.length ?? 0) > 0, toolChoice: "any", images: parts.filter((part) => part?.type === "image").map((part) => imageInputOf(part.data)), ...(model.id ? { model: model.id } : {}) });
|
|
752
|
-
}
|
|
753
|
-
const unmeasured = (cap) => `${SPEND_CAP_REACHED}: Not sent: the size of the next model request's input is unknown, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
|
|
754
|
-
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.`;
|
|
755
|
-
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.`;
|
|
756
|
-
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.`;
|
|
757
|
-
/** A request's price at `model`'s rates: its input's cached tokens at the cache-read price and its fresh ones at the
|
|
758
|
-
* dearer of the input and cache-write prices, and `output` tokens at the output price. */
|
|
759
|
-
function priceOf(calculateCost, model) {
|
|
760
|
-
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;
|
|
761
|
-
return ({ cached, fresh }, output) => Math.max(priced({ input: fresh, cacheRead: cached, output }), priced({ cacheWrite: fresh, cacheRead: cached, output }));
|
|
762
|
-
}
|
|
763
298
|
/** 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). */
|
|
764
299
|
export function money(usd) {
|
|
765
300
|
// A whole number of dollars as given ($1), else two decimals or as many as it takes (up to eight) to show it whole.
|
|
@@ -778,474 +313,3 @@ export const CAP_REFUSAL_CODE = `${SPEND_CAP_REACHED} (out of budget): `;
|
|
|
778
313
|
* higher cap would send; undefined for any other text, a refusal no cap could fix included (an unknown spend, no price,
|
|
779
314
|
* no output ceiling, an input not measured: the bare `spend_cap_reached: ` code). The one reader of that difference. */
|
|
780
315
|
export const roomRefusal = (text) => (text?.startsWith(CAP_REFUSAL_CODE) ? text.slice(CAP_REFUSAL_CODE.length) : undefined);
|
|
781
|
-
/** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
|
|
782
|
-
// Cents rounded up within the tail the fit check allows (FIT_TOLERANCE), no wider: a total past a cent by more than a
|
|
783
|
-
// float's own tail rounds to the cent above, so the cap a refusal names admits what it refused.
|
|
784
|
-
export const leastMoney = (usd) => `$${(Math.ceil(usd * 100 - FIT_TOLERANCE * 100) / 100).toFixed(2)}`;
|
|
785
|
-
/** The cap to raise to for a request past `cap` that needs `total` in all: a cent at least, and above the cap, never
|
|
786
|
-
* the cap itself, so a raise to it is one PATCH /runs/{id} takes. */
|
|
787
|
-
export const raiseTo = (cap, total) => `$${raiseFigure(cap, total).toFixed(2)}`;
|
|
788
|
-
/** raiseTo's cap as a number, whole cents in dollars: the figure a refusal carries beside its words (leastCapUsd). */
|
|
789
|
-
export const raiseFigure = (cap, total) => {
|
|
790
|
-
const cents = Math.ceil(total * 100 - FIT_TOLERANCE * 100);
|
|
791
|
-
return (cents / 100 > cap + CAP_TOLERANCE ? cents : Math.floor((cap + CAP_TOLERANCE) * 100) + 1) / 100;
|
|
792
|
-
};
|
|
793
|
-
/** 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
|
|
794
|
-
* person who has never seen a model request reads them: what the run spent (and holds for steps still running) of its
|
|
795
|
-
* cap, what the next step needs at the least, and the cap that lets it continue (spent, held and that least, rounded
|
|
796
|
-
* 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
|
|
797
|
-
* waits. After its code (CAP_REFUSAL_CODE), which keeps it final to pi-ai's retry. Its figures beside the words. */
|
|
798
|
-
function capRefusal(cap, spent, held, least) {
|
|
799
|
-
// The raise its words name and the figure it carries are one number (leastCapUsd), so the two never drift.
|
|
800
|
-
const leastCapUsd = raiseFigure(cap, spent + held + least);
|
|
801
|
-
const figures = { spentUsd: spent + held, needsUsd: least, leastCapUsd };
|
|
802
|
-
const [need, raise] = [leastMoney(least), `$${leastCapUsd.toFixed(2)}`];
|
|
803
|
-
if (spent === 0 && held === 0)
|
|
804
|
-
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 };
|
|
805
|
-
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 };
|
|
806
|
-
}
|
|
807
|
-
/** A guard's answer for a refusal for room: its words, and its figures beside them (harness-app.ts keeps them on its mark). */
|
|
808
|
-
const refuseFor = ({ text, figures }) => ({ refuse: text, ...figures });
|
|
809
|
-
/** capModels' judgement for a refusal for room: its words, and its figures for its start mark (request-start.ts). */
|
|
810
|
-
const whyOf = ({ text, figures }) => ({ why: text, figures });
|
|
811
|
-
/** 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
|
|
812
|
-
* or more. Each in cents (centsMoney), as the figures after it are; the exact amounts are the refusal's figures
|
|
813
|
-
* (RefusalFigures, the pause's spent_usd). */
|
|
814
|
-
const spentOf = (spent, held, cap) => {
|
|
815
|
-
const holds = centsMoney(held);
|
|
816
|
-
// A spend above $0 that rounds to it reads "less than a cent", never "$0" (the kernel's spentMoney).
|
|
817
|
-
const spentWords = spent > 0 && centsMoney(spent) === "$0" ? "less than a cent" : centsMoney(spent);
|
|
818
|
-
return holds !== "$0" ? `spent ${spentWords} and holds ${holds} for steps still running, of its ${money(cap)} cap` : `spent ${spentWords} of its ${money(cap)} cap`;
|
|
819
|
-
};
|
|
820
|
-
/** An amount in words, to the nearest cent ($0.0237416 is $0.02), as money says it ($1, $0.20, $0). */
|
|
821
|
-
export const centsMoney = (usd) => money(Math.round(usd * 100) / 100);
|
|
822
|
-
/** The cap's refusal of a paid call (paidCall) what is left of it cannot hold, in one sentence, as capRefusal says a model
|
|
823
|
-
* request's: what the run spent (and holds for requests and calls still answering) of its cap, what the call could cost
|
|
824
|
-
* 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
|
|
825
|
-
* 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
|
|
826
|
-
* in cents (spentOf), the call's figure and the cap by money, the raise by raiseFigure. */
|
|
827
|
-
function paidRefusal(cap, spent, held, name, hold) {
|
|
828
|
-
// The model refusal's rule (raiseFigure): a cent at least, and above the cap, never the cap itself; one number, which its
|
|
829
|
-
// words name and its refusal carries. The same words: the call is the next step, named as the tool.
|
|
830
|
-
const leastCapUsd = raiseFigure(cap, spent + held + hold.usd);
|
|
831
|
-
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 };
|
|
832
|
-
}
|
|
833
|
-
/** The most output tokens from `least` to `asked` whose request costs no more than `left` (`cost`, its price at that
|
|
834
|
-
* many, rising with them); undefined when even `least` costs more. A search, so that a price with tiers is exact. */
|
|
835
|
-
function mostOutput(cost, least, asked, left) {
|
|
836
|
-
// Written so that a cost that is not a number refuses; within a float's tail of what is left fits (FIT_TOLERANCE).
|
|
837
|
-
const fits = (tokens) => cost(tokens) <= left + FIT_TOLERANCE;
|
|
838
|
-
if (!fits(least))
|
|
839
|
-
return undefined;
|
|
840
|
-
if (fits(asked))
|
|
841
|
-
return asked;
|
|
842
|
-
let [low, high] = [least, asked];
|
|
843
|
-
while (high - low > 1) {
|
|
844
|
-
const mid = Math.floor((low + high) / 2);
|
|
845
|
-
if (fits(mid))
|
|
846
|
-
low = mid;
|
|
847
|
-
else
|
|
848
|
-
high = mid;
|
|
849
|
-
}
|
|
850
|
-
return low;
|
|
851
|
-
}
|
|
852
|
-
/** The least output a pi request may be limited to and still answer: the answer's 1,024 tokens, and when it thinks,
|
|
853
|
-
* the least budget on an API whose thinking takes one (squeezed to it), else its thinking level's budget, since its
|
|
854
|
-
* reasoning then shares the limit. */
|
|
855
|
-
export function leastOutput(model, thinking, budgetOf) {
|
|
856
|
-
if (!model.reasoning || !thinking || thinking === "off")
|
|
857
|
-
return ANSWER_TOKENS_LEAST;
|
|
858
|
-
return ANSWER_TOKENS_LEAST + (BUDGET_APIS.has(model.api) ? THINKING_BUDGET_LEAST : budgetOf(thinking));
|
|
859
|
-
}
|
|
860
|
-
/** A run on another harness: before each request, what the run has spent, plus what each request still in flight was
|
|
861
|
-
* admitted at, must leave room for this request at its least output (1,024 tokens, or what its body says it needs to
|
|
862
|
-
* think and answer; what it asks for when that is fewer), its input priced by requestPrice under `mode`, else the request
|
|
863
|
-
* is refused with spend_cap_reached. Admitted, it is limited to the most output what is left buys (`outputTokensMax`, at
|
|
864
|
-
* most what it asks for and its model's ceiling), which the model proxy writes into its body: output never passes the
|
|
865
|
-
* 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,
|
|
866
|
-
* which only refuses sooner). What cannot be kept within a cap is refused under one: a spend that is unknown (a request a
|
|
867
|
-
* crash cut), an input that could not be measured, a model serve has no price for (`listed: false`, or none at all),
|
|
868
|
-
* and a model whose output is priced and that has no output ceiling. With no cap, nothing is refused. `now`: the clock a
|
|
869
|
-
* previous request's end is read against. */
|
|
870
|
-
export async function capBefore(cap, model, { listed = true, mode = "expected", now = Date.now } = {}) {
|
|
871
|
-
if (cap === undefined)
|
|
872
|
-
return undefined;
|
|
873
|
-
if (model === undefined || !listed)
|
|
874
|
-
return { beforeRequest: () => ({ refuse: noPrice(cap) }) };
|
|
875
|
-
const output = outputBound(model);
|
|
876
|
-
if (output === undefined)
|
|
877
|
-
return { beforeRequest: () => ({ refuse: noCeiling(cap) }) };
|
|
878
|
-
const price = priceOf((await import("@earendil-works/pi-ai")).calculateCost, model);
|
|
879
|
-
const held = (request) => request.holdUsd ?? price({ cached: 0, fresh: request.inputTokensMax }, request.outputTokensMax ?? output);
|
|
880
|
-
/** A request priced by the one rule (requestPrice): its cost at an output, and the output it asks, needs at least, and
|
|
881
|
-
* is typically answered in at step 0 (WRAP_UP_STEP0_ANSWER_TOKENS, at most what it asks). */
|
|
882
|
-
const pricedOf = ({ inputTokensMax, outputTokensAsked, outputTokensLeast, previous }) => {
|
|
883
|
-
const priced = requestPrice(price, inputTokensMax, previous, now(), mode);
|
|
884
|
-
const asked = Math.min(outputTokensAsked ?? output, output);
|
|
885
|
-
return { priced, asked, least: Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked), step0: Math.min(WRAP_UP_STEP0_ANSWER_TOKENS, asked) };
|
|
886
|
-
};
|
|
887
|
-
const measured = (request) => typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax);
|
|
888
|
-
return {
|
|
889
|
-
leastUsd(request) {
|
|
890
|
-
if (!measured(request))
|
|
891
|
-
return undefined;
|
|
892
|
-
const { priced, least } = pricedOf(request);
|
|
893
|
-
return priced.cost(output === 0 ? 0 : least);
|
|
894
|
-
},
|
|
895
|
-
typicalUsd(request) {
|
|
896
|
-
if (!measured(request))
|
|
897
|
-
return undefined;
|
|
898
|
-
const { priced, step0 } = pricedOf(request);
|
|
899
|
-
return priced.cost(output === 0 ? 0 : step0);
|
|
900
|
-
},
|
|
901
|
-
beforeRequest({ spentUsd, inFlight, inputTokensMax, outputTokensAsked, outputTokensLeast, previous }) {
|
|
902
|
-
if (spentUsd === null)
|
|
903
|
-
return { refuse: unknownSpend(cap) };
|
|
904
|
-
const inputs = [inputTokensMax, ...inFlight.map((request) => request.inputTokensMax)];
|
|
905
|
-
if (inputs.some((input) => typeof input !== "number" || !Number.isFinite(input)))
|
|
906
|
-
return { refuse: unmeasured(cap) };
|
|
907
|
-
// Its requests in flight at what each was admitted at, and its paid calls under way at what they are held at.
|
|
908
|
-
const holding = inFlight.reduce((sum, request) => sum + held(request), paidHolds());
|
|
909
|
-
const left = cap - spentUsd - holding;
|
|
910
|
-
const { priced, asked, least } = pricedOf({ inputTokensMax, outputTokensAsked, outputTokensLeast, previous });
|
|
911
|
-
const cost = priced.cost;
|
|
912
|
-
const bound = (tokens) => Math.max(0, priced.worst(tokens) - cost(tokens));
|
|
913
|
-
const boundOf = (tokens) => (bound(tokens) > 0 ? { boundUsd: bound(tokens) } : {});
|
|
914
|
-
const admitted = (limit) => ({ ...(output === 0 ? {} : { outputTokensMax: limit }), holdUsd: cost(limit), boundUsd: bound(limit), stoppedUsd: stoppedPriceOf(cost, limit) });
|
|
915
|
-
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input to fit.
|
|
916
|
-
if (output === 0)
|
|
917
|
-
return cost(0) <= left + FIT_TOLERANCE ? admitted(0) : { ...refuseFor(capRefusal(cap, spentUsd, holding, cost(0))), ...boundOf(0) };
|
|
918
|
-
const most = mostOutput(cost, least, asked, left);
|
|
919
|
-
return most === undefined ? { ...refuseFor(capRefusal(cap, spentUsd, holding, cost(least))), ...boundOf(least) } : admitted(most);
|
|
920
|
-
},
|
|
921
|
-
};
|
|
922
|
-
}
|
|
923
|
-
/** A request's input bound (inputBound of its context, plus `overhead(model, context)`, what its provider adds
|
|
924
|
-
* server-side) and the most fee it can run up: a tool's own request adds what its hosted tool may read
|
|
925
|
-
* (hosted-search.ts), and its most fee. Undefined when its input cannot be measured. */
|
|
926
|
-
export function requestParts(overhead = piOverhead) {
|
|
927
|
-
return (model, context) => {
|
|
928
|
-
const added = overhead(model, context);
|
|
929
|
-
if (added === undefined)
|
|
930
|
-
return undefined;
|
|
931
|
-
const side = sideRequests.get(context);
|
|
932
|
-
return { input: inputBound(JSON.stringify(context), added + (side?.extraInputTokens ?? 0)), feeUsd: side?.maxFeeUsd ?? 0 };
|
|
933
|
-
};
|
|
934
|
-
}
|
|
935
|
-
/** `models`, each request limited to the output tokens what is left of `cap` after `spent` USD (and what requests in flight
|
|
936
|
-
* hold) can buy, at most what it asks for, thinking included (CLAMP on its marks when that is less), and refused when that
|
|
937
|
-
* cannot buy its least (`leastOutput`: 1,024 tokens for the answer, and its thinking's least), saying so in plain words;
|
|
938
|
-
* and, under the cap,
|
|
939
|
-
* each request to a model in `unpriced` (one serve has no price for) or whose output is priced and that has no output
|
|
940
|
-
* ceiling, each whose input cannot be bounded, and every request once what the run has spent is unknown: `spent` null
|
|
941
|
-
* (spentFrom), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
|
|
942
|
-
* `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. It is
|
|
943
|
-
* priced by requestPrice under `mode`, after the previous request of its conversation (the context's last answer, read
|
|
944
|
-
* by previousIn; its end as `now` read it when it settled here, else its own timestamp, which is when it began). Each
|
|
945
|
-
* request sent carries what it is held at (HELD_USD) and its bound (BOUND_USD) to the marks below, and one stopped
|
|
946
|
-
* before its end counts at most its hold.
|
|
947
|
-
* `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry. On
|
|
948
|
-
* another harness the run has no models of its own: every request goes through its session's proxy (port-models.ts). */
|
|
949
|
-
export async function capModels(models, cap, spent, { unpriced = new Set(), overhead = piOverhead, refused: markRefused, mode = "expected", now = Date.now, wrapUp } = {}) {
|
|
950
|
-
const [{ calculateCost, createAssistantMessageEventStream }, simple] = await Promise.all([import("@earendil-works/pi-ai"), import("@earendil-works/pi-ai/api/simple-options")]);
|
|
951
|
-
const partsOf = requestParts(overhead);
|
|
952
|
-
/** When each answer settled here, by its timestamp (an answer keeps it when the run's store gives it back), the newest
|
|
953
|
-
* ENDED_KEPT of them: its end, for the next request's previous. */
|
|
954
|
-
const ended = new Map();
|
|
955
|
-
const ENDED_KEPT = 64;
|
|
956
|
-
const endedNow = (message) => {
|
|
957
|
-
if (typeof message.timestamp !== "number")
|
|
958
|
-
return;
|
|
959
|
-
ended.delete(message.timestamp);
|
|
960
|
-
ended.set(message.timestamp, now());
|
|
961
|
-
if (ended.size > ENDED_KEPT)
|
|
962
|
-
ended.delete(ended.keys().next().value);
|
|
963
|
-
};
|
|
964
|
-
/** The previous request of `context`'s conversation on `model`: its last answer, if one on this model whose usage says
|
|
965
|
-
* its input, with the bound of what it was sent (the context before it, measured as this request is). An answer on
|
|
966
|
-
* another model, or that failed or was stopped, leaves none: nothing cached to count on. */
|
|
967
|
-
const previousIn = (model, context) => {
|
|
968
|
-
const at = context.messages.findLastIndex((message) => message.role === "assistant");
|
|
969
|
-
const answer = context.messages[at];
|
|
970
|
-
if (!answer || answer.model !== model.id || answer.provider !== model.provider || answer.stopReason === "error" || answer.stopReason === "aborted")
|
|
971
|
-
return undefined;
|
|
972
|
-
const before = partsOf(model, { ...context, messages: context.messages.slice(0, at) });
|
|
973
|
-
return previousOf(answer.usage, before?.input, ended.get(answer.timestamp) ?? answer.timestamp);
|
|
974
|
-
};
|
|
975
|
-
let held = 0;
|
|
976
|
-
/** What the run has spent, as this request's check reads it. */
|
|
977
|
-
const spentNow = () => spent;
|
|
978
|
-
// The run's spend as a paid tool's check reads it (installed below, useSpend): the requests in flight held at their
|
|
979
|
-
// worst case apart from it (it adds the paid holds itself), and its charge joins the spend.
|
|
980
|
-
// `cap` moves only by a raise (raise: a workflow run's, budget.ts), read at each check from then on.
|
|
981
|
-
const own = {
|
|
982
|
-
get cap() { return cap; }, spent: () => spent, held: () => held, add: (usd) => void (spent = spent !== null && typeof usd === "number" && Number.isFinite(usd) ? spent + usd : null),
|
|
983
|
-
raise: (to) => void (to > cap && (cap = to)),
|
|
984
|
-
};
|
|
985
|
-
/** `judgeOne`, and near the cap the wrap-up (wrapUpDue), once: a turn's request on the run's own model is sent with the
|
|
986
|
-
* words after everything its context holds (`context`), its bytes admitted with it. Only in this one request: pi's
|
|
987
|
-
* transcript never holds the note, and no input is queued, so the run spends nothing after the model answers. */
|
|
988
|
-
const judge = (model, context, options, simpleCall, turn) => {
|
|
989
|
-
const judged = judgeOne(model, context, options, simpleCall, turn);
|
|
990
|
-
if (!("hold" in judged) || !wrapUp || wrapUp.sent || wrapUp.pending || !turn || model.id !== wrapUp.model)
|
|
991
|
-
return judged;
|
|
992
|
-
const spentUsd = spentNow();
|
|
993
|
-
// What is left as admission counted it: what was spent, and what requests and paid calls in flight are held at.
|
|
994
|
-
// Nothing priced yet: the request at its input and a typical answer (WRAP_UP_STEP0_ANSWER_TOKENS), never its hold.
|
|
995
|
-
const due = spentUsd === null ? undefined : wrapUpDue(cap, spentUsd, held + paidHolds(), typicalCost(wrapUp.costs, judged.typical ?? judged.hold), judged.least);
|
|
996
|
-
if (!due)
|
|
997
|
-
return judged;
|
|
998
|
-
const words = wrapUpWords(due.leftUsd, wrapUp.costs.length === 0);
|
|
999
|
-
const noted = { ...context, messages: [...context.messages, { role: "user", content: `<system-reminder>${words}</system-reminder>`, timestamp: now() }] };
|
|
1000
|
-
const again = judgeOne(model, noted, options, simpleCall, turn);
|
|
1001
|
-
// The note's own bytes do not fit: the request goes as it came, and the note waits for one they do.
|
|
1002
|
-
if (!("hold" in again))
|
|
1003
|
-
return judged;
|
|
1004
|
-
// Pending until this request ends: told (recorded) only if it ends answered, else left for the next request.
|
|
1005
|
-
wrapUp.pending = true;
|
|
1006
|
-
return { ...again, context: noted, told: { capUsd: cap, leftUsd: due.leftUsd, words } };
|
|
1007
|
-
};
|
|
1008
|
-
/** Settles a note `answer` carried: told when it ended answered (not an error, not aborted), else re-armed. */
|
|
1009
|
-
const settleNote = (answer, told) => void answer.then((message) => {
|
|
1010
|
-
wrapUp.pending = false;
|
|
1011
|
-
if (message.stopReason === "error" || message.stopReason === "aborted")
|
|
1012
|
-
return;
|
|
1013
|
-
wrapUp.sent = true;
|
|
1014
|
-
wrapUp.record(told);
|
|
1015
|
-
}, () => void (wrapUp.pending = false));
|
|
1016
|
-
const judgeOne = (model, context, options, simpleCall, turn) => {
|
|
1017
|
-
if (unpriced.has(model.id))
|
|
1018
|
-
return { why: noPrice(cap) };
|
|
1019
|
-
const ceiling = outputBound(model);
|
|
1020
|
-
if (ceiling === undefined)
|
|
1021
|
-
return { why: noCeiling(cap) };
|
|
1022
|
-
const spentUsd = spentNow();
|
|
1023
|
-
if (spentUsd === null)
|
|
1024
|
-
return { why: unknownSpend(cap) };
|
|
1025
|
-
// A paid call the cap just refused for room: the turn's next request, the one after its result, is refused in its
|
|
1026
|
-
// words, and the run pauses there. A request after a message of the person's instead (a stop came first, and the
|
|
1027
|
-
// person moved on) is a new turn's: the refusal is let go, and this request is judged as any other. Only the turn's
|
|
1028
|
-
// own requests (stream, streamSimple) take it: a side request through the run's models (completeSimple: a
|
|
1029
|
-
// compaction's summary, native web_search's own, request-start.ts) is judged as any other and leaves it for them.
|
|
1030
|
-
const paid = turn ? takePaidRefusal(own) : undefined;
|
|
1031
|
-
if (paid && context.messages.at(-1)?.role === "toolResult")
|
|
1032
|
-
return { why: `${CAP_REFUSAL_CODE}${paid.words}`, figures: paid.figures };
|
|
1033
|
-
const parts = partsOf(model, context);
|
|
1034
|
-
if (parts === undefined)
|
|
1035
|
-
return { why: unmeasured(cap) };
|
|
1036
|
-
// Its price by the one rule (requestPrice): its input expected after the previous request, else uncached.
|
|
1037
|
-
const priced = requestPrice(priceOf(calculateCost, model), parts.input, mode === "strict" ? undefined : previousIn(model, context), now(), mode, parts.feeUsd);
|
|
1038
|
-
const cost = priced.cost;
|
|
1039
|
-
const bound = (tokens) => Math.max(0, priced.worst(tokens) - cost(tokens));
|
|
1040
|
-
// A refusal for room at `tokens` of output: its words and figures (capRefusal, at what admission prices the request
|
|
1041
|
-
// at), and the bound it would have been sent with.
|
|
1042
|
-
const refusedAt = (holding, tokens) => {
|
|
1043
|
-
const { why, figures } = whyOf(capRefusal(cap, spentUsd, holding, cost(tokens)));
|
|
1044
|
-
return { why, figures: { ...figures, ...(bound(tokens) > 0 ? { boundUsd: bound(tokens) } : {}) } };
|
|
1045
|
-
};
|
|
1046
|
-
// What the run holds beside what it spent, as a paid call's check counts it: each request in flight at its figure, and
|
|
1047
|
-
// each paid call under way at what it is held at.
|
|
1048
|
-
const holding = held + paidHolds();
|
|
1049
|
-
const left = cap - spentUsd - holding;
|
|
1050
|
-
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input and fee to fit. Its least
|
|
1051
|
-
// admission is that figure, its input at its price after the previous request, and no output (the wrap-up's least).
|
|
1052
|
-
if (ceiling === 0)
|
|
1053
|
-
return cost(0) <= left + FIT_TOLERANCE ? { hold: cost(0), bound: bound(0), stopped: () => cost(0), least: cost(0) } : refusedAt(holding, 0);
|
|
1054
|
-
// What the request would send as it stands, thinking included: pi-ai clamps its maxTokens (or the model's) to what its
|
|
1055
|
-
// context leaves, and on an API whose thinking takes a budget adds the budget to it.
|
|
1056
|
-
const transcript = context;
|
|
1057
|
-
const thinking = simpleCall && model.reasoning && options?.reasoning ? options.reasoning : undefined;
|
|
1058
|
-
// Adaptive thinking (pi-ai's current Claude models on Anthropic's API) takes no budget: pi-ai sends the request's
|
|
1059
|
-
// maxTokens as is, and the model thinks within them as it sees fit: at any level, none included, on a model with
|
|
1060
|
-
// mid-conversation effort, else when given a level.
|
|
1061
|
-
const compat = model.api === "anthropic-messages" && model.reasoning ? model.compat : undefined;
|
|
1062
|
-
const adaptive = compat?.supportsMidConvoEffort === true || (compat?.forceAdaptiveThinking === true && thinking !== undefined);
|
|
1063
|
-
const budgeted = thinking !== undefined && BUDGET_APIS.has(model.api) && !adaptive;
|
|
1064
|
-
const base = simple.clampMaxTokensToContext(model, transcript, options?.maxTokens ?? ceilingTokens(model));
|
|
1065
|
-
const asked = Math.min(ceiling, budgeted ? simple.clampMaxTokensToContext(model, transcript, simple.adjustMaxTokensForThinking(base, ceilingTokens(model), thinking, options?.thinkingBudgets).maxTokens) : base);
|
|
1066
|
-
const least = Math.min(leastOutput(model, thinking, (level) => simple.thinkingBudgetForLevel(level, options?.thinkingBudgets)), asked);
|
|
1067
|
-
const most = mostOutput(cost, least, asked, left);
|
|
1068
|
-
if (most === undefined)
|
|
1069
|
-
return refusedAt(holding, least);
|
|
1070
|
-
// The reasoning a stop leaves unseen: a model's reasoning streams as a summary or not at all (the Responses API; Claude
|
|
1071
|
-
// 4-class thinking), so a request that reasons counts its level's budget (the budget it was sent with, on a budget
|
|
1072
|
-
// API), or its whole limit when it gives no level and its API reasons by default; none on a budget API with thinking
|
|
1073
|
-
// off, or on a model that does not reason. Adaptive thinking is bounded only by the limit, so it counts the limit
|
|
1074
|
-
// less the answer's 1,024 tokens. An estimate, as levels are not limits the provider keeps: within the hold.
|
|
1075
|
-
const hiddenOf = (limit) => {
|
|
1076
|
-
if (adaptive)
|
|
1077
|
-
return Math.max(0, limit - ANSWER_TOKENS_LEAST);
|
|
1078
|
-
if (!model.reasoning || thinking === "off")
|
|
1079
|
-
return 0;
|
|
1080
|
-
if (thinking === undefined)
|
|
1081
|
-
return BUDGET_APIS.has(model.api) ? 0 : limit;
|
|
1082
|
-
const budget = simple.thinkingBudgetForLevel(thinking, options?.thinkingBudgets);
|
|
1083
|
-
return budgeted ? Math.max(0, Math.min(budget, limit - ANSWER_TOKENS_LEAST)) : budget;
|
|
1084
|
-
};
|
|
1085
|
-
// Stopped before its end, at most the output it was sent with: what it streamed, the part of its reasoning budget that
|
|
1086
|
-
// did not stream (max(0, budget - the reasoning streamed), so thinking that streamed is not counted twice), and the
|
|
1087
|
-
// allowance, within its worst case.
|
|
1088
|
-
const stoppedAt = (limit) => (message) => stoppedFigure(cost, limit, cost(limit), streamedBytes(message) + Math.max(0, hiddenOf(limit) - reasoningBytes(message)));
|
|
1089
|
-
// The wrap-up's typical cost while nothing is priced: its input and a typical answer, at most what it asks.
|
|
1090
|
-
const typical = cost(Math.min(WRAP_UP_STEP0_ANSWER_TOKENS, asked));
|
|
1091
|
-
// The figure admission refuses it below (`least` output at its price): the wrap-up's other trigger (wrapUpDue).
|
|
1092
|
-
const leastUsd = cost(least);
|
|
1093
|
-
if (most === asked)
|
|
1094
|
-
return { hold: cost(asked), bound: bound(asked), stopped: stoppedAt(asked), typical, least: leastUsd };
|
|
1095
|
-
// Limited: sent with `most` tokens at most, thinking included. On a budget API the budget is squeezed first, keeping
|
|
1096
|
-
// the answer's 1,024, and maxTokens is what is left of `most` beside it, so pi-ai's sum is `most`.
|
|
1097
|
-
const clamp = { tokens: most, leftUsd: Math.round(left * 1e6) / 1e6, capUsd: cap };
|
|
1098
|
-
if (!budgeted)
|
|
1099
|
-
return { hold: cost(most), bound: bound(most), stopped: stoppedAt(most), typical, least: leastUsd, options: { ...options, maxTokens: most, [CLAMP]: clamp } };
|
|
1100
|
-
const level = simple.clampReasoning(thinking);
|
|
1101
|
-
const budget = Math.min(simple.thinkingBudgetForLevel(thinking, options?.thinkingBudgets), most - ANSWER_TOKENS_LEAST);
|
|
1102
|
-
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 } };
|
|
1103
|
-
};
|
|
1104
|
-
const refusal = (model, why) => ({
|
|
1105
|
-
role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(),
|
|
1106
|
-
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
1107
|
-
// "out of budget" is final to pi-ai's retry policy, whatever digits the amounts hold.
|
|
1108
|
-
errorMessage: why,
|
|
1109
|
-
});
|
|
1110
|
-
/** Adds what `answer` cost to what the run has spent once it settles. One stopped before its end counts at `stopped`
|
|
1111
|
-
* of what it streamed (stoppedFigure, at most `worst`), unless an attempt before the stop was lost: then at `worst`, as
|
|
1112
|
-
* its lost mark reads in a later process; one that ended on an error after its response began
|
|
1113
|
-
* (markResponseBegan: its usage is what had streamed, not what the provider can have billed), or that failed with no
|
|
1114
|
-
* answer, at `worst`, what the cap held for it; each as spentFrom reads its end mark. Without a figure (a deferred
|
|
1115
|
-
* response) it is unknown, as is a cost that is not a number, from then on. */
|
|
1116
|
-
const count = (answer, turn, worst, stopped, attempts) => {
|
|
1117
|
-
const plus = (sum, cost) => (sum !== null && typeof cost === "number" && Number.isFinite(cost) ? sum + cost : null);
|
|
1118
|
-
const add = (cost) => void (spent = plus(spent, cost));
|
|
1119
|
-
// One rule (bookRequest), from how the request ended (piEnded) as its marks read it too.
|
|
1120
|
-
const at = (message) => message.stopReason === "aborted" ? (stopped && !anyAttemptLost(attempts) ? stopped(message) : worst)
|
|
1121
|
-
: bookRequest(piEnded(message, responseBegan.has(message), attempts), worst === undefined ? {} : { hold: worst }).usd;
|
|
1122
|
-
// A priced turn answer of the run's own model: the wrap-up's typical cost counts it, as a process opened again reads it (its
|
|
1123
|
-
// pi.assistant entries). Never a compaction summary's or a native search's request on the same model (completeSimple
|
|
1124
|
-
// calls, `turn` false): no pi.assistant entry keeps them, so a process opened again would count without them.
|
|
1125
|
-
const priced = (message) => {
|
|
1126
|
-
const total = message.usage?.cost?.total;
|
|
1127
|
-
if (wrapUp && turn && message.model === wrapUp.model && message.stopReason !== "error" && message.stopReason !== "aborted" && typeof total === "number" && Number.isFinite(total) && total > 0)
|
|
1128
|
-
wrapUp.costs.push(total);
|
|
1129
|
-
};
|
|
1130
|
-
return answer.then((message) => (endedNow(message), priced(message), add(at(message))), () => add(worst));
|
|
1131
|
-
};
|
|
1132
|
-
/** Sends a request judged to fit at `worst` (its hold), holding that until `answer` settles. */
|
|
1133
|
-
const admit = (turn, worst, stopped, answer, attempts) => {
|
|
1134
|
-
held += worst;
|
|
1135
|
-
const release = () => void (held -= worst);
|
|
1136
|
-
let answered;
|
|
1137
|
-
try {
|
|
1138
|
-
answered = answer();
|
|
1139
|
-
}
|
|
1140
|
-
catch (error) {
|
|
1141
|
-
release();
|
|
1142
|
-
throw error;
|
|
1143
|
-
}
|
|
1144
|
-
void count(answered, turn, worst, stopped, attempts).finally(release);
|
|
1145
|
-
return answered;
|
|
1146
|
-
};
|
|
1147
|
-
// A paid tool's check reads the spend, and the requests in flight held at their worst case apart from it (it adds the
|
|
1148
|
-
// paid holds itself), and its charge joins the spend. On another harness, the harness sets it as its run opens
|
|
1149
|
-
// (harness-app.ts).
|
|
1150
|
-
useSpend(own);
|
|
1151
|
-
/** `options` with what the request is held at, its bound, its figure if it is stopped, and its attempts' record, for
|
|
1152
|
-
* its marks: on an API the cap can watch, a fetch that records each attempt (`attempts`, undefined on one it cannot). */
|
|
1153
|
-
const carrying = (options, { hold, bound, stopped }, attempts) => ({
|
|
1154
|
-
...options, [HELD_USD]: hold, [BOUND_USD]: bound, [STOPPED_USD]: stopped,
|
|
1155
|
-
// null on an API the cap cannot watch: its marks read a failure before any event as lost.
|
|
1156
|
-
...(attempts ? { [ATTEMPTS]: attempts, fetch: recordingFetch(attempts, options?.fetch, options?.signal) } : { [ATTEMPTS]: null }),
|
|
1157
|
-
});
|
|
1158
|
-
const attemptsFor = (model) => (unwatched(model.api) ? undefined : []);
|
|
1159
|
-
const stream = (send, simpleCall) => (model, context, options) => {
|
|
1160
|
-
const judged = judge(model, context, options, simpleCall, true);
|
|
1161
|
-
if ("hold" in judged) {
|
|
1162
|
-
let events;
|
|
1163
|
-
const attempts = attemptsFor(model);
|
|
1164
|
-
let answered;
|
|
1165
|
-
try {
|
|
1166
|
-
answered = admit(true, judged.hold, judged.stopped, () => (events = send(model, judged.context ?? context, carrying(judged.options ?? options, judged, attempts))).result(), attempts);
|
|
1167
|
-
}
|
|
1168
|
-
catch (error) {
|
|
1169
|
-
// Never sent (its send threw as it was made): a note it carried waits for the next request.
|
|
1170
|
-
if (judged.told)
|
|
1171
|
-
wrapUp.pending = false;
|
|
1172
|
-
throw error;
|
|
1173
|
-
}
|
|
1174
|
-
if (judged.told)
|
|
1175
|
-
settleNote(answered, judged.told);
|
|
1176
|
-
return events;
|
|
1177
|
-
}
|
|
1178
|
-
// A workflow run's turn request refused for room waits for a raise, unsent, and is judged again (RunSpend.wait):
|
|
1179
|
-
// its node stands where it is. Its events then come from the request sent, or from the refusal if none is.
|
|
1180
|
-
const room = roomRefusal(judged.why);
|
|
1181
|
-
if (room !== undefined && own.wait) {
|
|
1182
|
-
const waited = createAssistantMessageEventStream();
|
|
1183
|
-
const signal = options?.signal;
|
|
1184
|
-
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) => {
|
|
1185
|
-
for await (const event of events)
|
|
1186
|
-
waited.push(event);
|
|
1187
|
-
waited.end(await events.result());
|
|
1188
|
-
}).catch((error) => {
|
|
1189
|
-
const failed = refusal(model, `${SPEND_CAP_REACHED}: Not sent: the wait for a raise failed (${String(error?.message ?? error).slice(0, 200)})`);
|
|
1190
|
-
waited.push({ type: "error", reason: "error", error: failed });
|
|
1191
|
-
waited.end(failed);
|
|
1192
|
-
});
|
|
1193
|
-
return waited;
|
|
1194
|
-
}
|
|
1195
|
-
// A refusal no raise fixes ends a workflow's run in its words (budget.ts): the node fails on the refusal.
|
|
1196
|
-
if (room === undefined)
|
|
1197
|
-
own.stopped?.({ words: judged.why.replace(CAP_REFUSAL_PREFIX, ""), room: false, capUsd: cap });
|
|
1198
|
-
return refusedStream(model, judged);
|
|
1199
|
-
};
|
|
1200
|
-
/** The refusal's own stream: its start mark first, then pi's error for it. */
|
|
1201
|
-
const refusedStream = (model, judged) => {
|
|
1202
|
-
const refused = createAssistantMessageEventStream();
|
|
1203
|
-
const message = refusal(model, judged.why);
|
|
1204
|
-
// Its own start mark first, so pi's error entry for it answers that mark, never an earlier request a stop or a crash
|
|
1205
|
-
// cut. A mark that cannot be written still ends the request: spentFrom leaves refusals out either way.
|
|
1206
|
-
void Promise.resolve()
|
|
1207
|
-
.then(() => markRefused?.(judged.figures))
|
|
1208
|
-
.catch(() => undefined)
|
|
1209
|
-
.then(() => {
|
|
1210
|
-
refused.push({ type: "error", reason: "error", error: message });
|
|
1211
|
-
refused.end(message);
|
|
1212
|
-
});
|
|
1213
|
-
return refused;
|
|
1214
|
-
};
|
|
1215
|
-
const complete = (send, simpleCall) => (model, context, options) => {
|
|
1216
|
-
const judged = judge(model, context, options, simpleCall, false);
|
|
1217
|
-
if (!("hold" in judged)) {
|
|
1218
|
-
// Inside a workflow's call node (the `llm` tool): the call is told, and ends on it (app.ts runEffect).
|
|
1219
|
-
const room = roomRefusal(judged.why);
|
|
1220
|
-
capRefusals.getStore()?.({ words: room ?? judged.why.replace(CAP_REFUSAL_PREFIX, ""), room: room !== undefined, capUsd: cap, ...(judged.figures ? { figures: judged.figures } : {}) });
|
|
1221
|
-
return Promise.resolve(refusal(model, judged.why));
|
|
1222
|
-
}
|
|
1223
|
-
const attempts = attemptsFor(model);
|
|
1224
|
-
return admit(false, judged.hold, judged.stopped, () => send(model, judged.context ?? context, carrying(judged.options ?? options, judged, attempts)), attempts);
|
|
1225
|
-
};
|
|
1226
|
-
const guarded = {
|
|
1227
|
-
stream: stream(models.stream.bind(models), false),
|
|
1228
|
-
streamSimple: stream(models.streamSimple.bind(models), true),
|
|
1229
|
-
complete: complete(models.complete.bind(models), false),
|
|
1230
|
-
completeSimple: complete(models.completeSimple.bind(models), true),
|
|
1231
|
-
// A deferred response was admitted when it was sent; what it cost is counted when it is fetched.
|
|
1232
|
-
streamDeferred: (...args) => {
|
|
1233
|
-
const events = models.streamDeferred(...args);
|
|
1234
|
-
void count(events.result(), true);
|
|
1235
|
-
return events;
|
|
1236
|
-
},
|
|
1237
|
-
fetchDeferred: (...args) => {
|
|
1238
|
-
const answer = models.fetchDeferred(...args);
|
|
1239
|
-
void count(answer, true);
|
|
1240
|
-
return answer;
|
|
1241
|
-
},
|
|
1242
|
-
};
|
|
1243
|
-
return new Proxy(models, {
|
|
1244
|
-
get: (target, key) => {
|
|
1245
|
-
if (key in guarded)
|
|
1246
|
-
return guarded[key];
|
|
1247
|
-
const value = Reflect.get(target, key, target);
|
|
1248
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
1249
|
-
},
|
|
1250
|
-
});
|
|
1251
|
-
}
|