@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30
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 +748 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +2190 -2
- package/dist/adapters.d.ts +234 -0
- package/dist/adapters.js +585 -0
- package/dist/agents.d.ts +130 -0
- package/dist/agents.js +308 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +384 -0
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +285 -0
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +45 -0
- package/dist/box-relay.js +227 -0
- package/dist/boxes.d.ts +72 -0
- package/dist/boxes.js +189 -0
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +332 -0
- package/dist/cap.js +992 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +35 -0
- package/dist/coding-tools.js +87 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +19 -0
- package/dist/decision-rows.js +123 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +74 -0
- package/dist/errors.js +69 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +65 -0
- package/dist/files.js +158 -0
- package/dist/grade.d.ts +93 -0
- package/dist/grade.js +328 -0
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +102 -0
- package/dist/graph-view.js +219 -0
- package/dist/harness-app.d.ts +40 -0
- package/dist/harness-app.js +708 -0
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +56 -0
- package/dist/harness.js +77 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +30 -0
- package/dist/host-tools.js +154 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +85 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +133 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1222 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +37 -0
- package/dist/key-check.js +112 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +191 -0
- package/dist/learn/check.d.ts +108 -0
- package/dist/learn/check.js +277 -0
- package/dist/learn/grade.d.ts +80 -0
- package/dist/learn/grade.js +445 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +147 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +213 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +131 -0
- package/dist/learn/skills.d.ts +97 -0
- package/dist/learn/skills.js +271 -0
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +306 -0
- package/dist/learning-run.js +819 -0
- package/dist/learning-words.d.ts +76 -0
- package/dist/learning-words.js +174 -0
- package/dist/learning.d.ts +418 -0
- package/dist/learning.js +946 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +118 -0
- package/dist/mcp-servers.js +450 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +186 -0
- package/dist/model.js +485 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4806 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1727 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +50 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +70 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +69 -0
- package/dist/place.js +137 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +40 -0
- package/dist/propose.js +112 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +22 -0
- package/dist/request-start.js +350 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +186 -0
- package/dist/run-box.js +590 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +83 -0
- package/dist/runnable.js +170 -0
- package/dist/runs.d.ts +1062 -0
- package/dist/runs.js +3020 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +62 -0
- package/dist/secrets.js +158 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +722 -0
- package/dist/server.js +2118 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +43 -0
- package/dist/skills.js +96 -0
- package/dist/stats.d.ts +106 -0
- package/dist/stats.js +103 -0
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +187 -0
- package/dist/tool-keys.js +315 -0
- package/dist/tool-plane.d.ts +228 -0
- package/dist/tool-plane.js +400 -0
- package/dist/tools.d.ts +202 -0
- package/dist/tools.js +372 -0
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +24 -0
- package/dist/turn-end.js +15 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +57 -0
- package/dist/validate.js +184 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +189 -0
- package/dist/webhooks.js +503 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +100 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/cap.js
ADDED
|
@@ -0,0 +1,992 @@
|
|
|
1
|
+
// A run's spend cap (`max_cost_usd`), held in the run's own process, where its model requests are sent. Before each
|
|
2
|
+
// request, what the run has spent plus the request's worst case must stay within the cap. The worst case is the request's
|
|
3
|
+
// input bound (inputBound: one token per UTF-8 byte of what is sent, plus what the provider adds server-side) at the
|
|
4
|
+
// higher of the model's input and cache-write prices, plus the output it is sent with at the output price, plus any fee
|
|
5
|
+
// its tokens do not show (pi's own search request's). Each request is limited to the output what is left of the cap can
|
|
6
|
+
// buy (thinking included, never more than it asks for), and held at that: the limit is the wire's (pi's options, the
|
|
7
|
+
// model proxy's body for claude-agent and codex), so the cap stays exact. Only when what is left cannot buy its least (1,024
|
|
8
|
+
// tokens for the answer, and its thinking's least, leastOutput) is it not sent, and the run's turn ends on a model error
|
|
9
|
+
// the server reads as `spend_cap_reached`, saying in plain words what was spent and what the request needs. A model serve has
|
|
10
|
+
// no price for cannot be kept within a cap, so under one its requests are refused; a model listed at $0 is a known $0. What the run has
|
|
11
|
+
// spent is read back from its store when the process starts, so it survives a restart, plus each response since; a
|
|
12
|
+
// request in flight holds its worst case until it answers. A request the person stopped before its end counts at its input,
|
|
13
|
+
// what it streamed (one token a byte) and STOP_ALLOWANCE_TOKENS of output the provider may have produced after the last
|
|
14
|
+
// word read, never more than its worst case: a cut stream's own usage is not what it charged, and its worst case, once
|
|
15
|
+
// the request is limited to what is left, is the rest of the cap. One that ended on an error after its response began
|
|
16
|
+
// counts at its worst case. The figure is written on the request's end mark (request-start.ts), so a later process
|
|
17
|
+
// counts it the same. Nor can a spend no one
|
|
18
|
+
// knows (a request a crash cut, a cost that is not a number) or a model whose output is priced and that has no output
|
|
19
|
+
// ceiling be kept within a cap: under one, each refuses the request, never passes as $0.
|
|
20
|
+
// A request carrying a native web search tool reads pages into its input that its body does not hold: on claude-agent
|
|
21
|
+
// its bound is its body's plus a stated allowance (NATIVE_SEARCH_ALLOWANCE_TOKENS, which its adapter adds, adapters.ts),
|
|
22
|
+
// and pi's own search request is held at its context plus HOSTED_SEARCH_ALLOWANCE_TOKENS and its most fee; what it
|
|
23
|
+
// cost, booked once it answers, stops the next request. A run whose booked spend passes its cap shows by how much on its
|
|
24
|
+
// timeline (runs.ts withOverCap).
|
|
25
|
+
//
|
|
26
|
+
// 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
|
|
27
|
+
// the run's cost and spentIn both count, and added to what the run's process counts as spent (useSpend), so the next
|
|
28
|
+
// request's check sees it. A charge the call does not say (null: stopped, timed out, failed with no cost) leaves the
|
|
29
|
+
// 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
|
|
30
|
+
// 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
|
|
31
|
+
// request is held: refused unless what the run has spent plus what the call is held at (its quote, else an allowance)
|
|
32
|
+
// fits the cap, and whenever the spend is unknown; paid calls go one at a time, so each check sees the charge before
|
|
33
|
+
// it. A call sent holds its figure until its charge joins the spend (paidHolds), so a model request judged meanwhile, on
|
|
34
|
+
// pi or on another harness, counts it beside the spend, as a paid call's check counts the model requests in flight.
|
|
35
|
+
import { DatabaseSync } from "node:sqlite";
|
|
36
|
+
import { existsSync } from "node:fs";
|
|
37
|
+
import { providerInputOverhead } from "@parcha/agentrun-kernel/host";
|
|
38
|
+
import { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "@parcha/agentrun-kernel";
|
|
39
|
+
import { REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
|
|
40
|
+
/** A run's cap in USD, passed to its process. */
|
|
41
|
+
export const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
|
|
42
|
+
/** How a request the cap refused begins its error, which the server ends the run with. */
|
|
43
|
+
export const SPEND_CAP_REACHED = "spend_cap_reached";
|
|
44
|
+
/** How near two dollar figures are the same figure: a sum a float puts a hair past the cap (0.0028 + 0.3072 is
|
|
45
|
+
* 0.31000000000000005) is the cap, and fits it. A raise must be above a run's cap by more (runs.ts). */
|
|
46
|
+
export const CAP_TOLERANCE = 1e-9;
|
|
47
|
+
/** How far past what is left a sum may read and still fit it: a float's own tail (0.0028 + 0.3072 is 0.31000000000000005
|
|
48
|
+
* against a 0.31 cap), never a spend that is past the cap, by however little (a 1e-11 hair is past it). CAP_TOLERANCE
|
|
49
|
+
* is the other question: how near two caps are the same cap. */
|
|
50
|
+
export const FIT_TOLERANCE = 1e-12;
|
|
51
|
+
/** The option a request's worst case rides on from the cap to its marks (request-start.ts): what the cap held for it. A
|
|
52
|
+
* symbol, so no provider ever sends it. */
|
|
53
|
+
export const HELD_USD = Symbol.for("agentrun.serve.held_usd");
|
|
54
|
+
/** pi's messages for requests that ended on an error after their response had begun (an event came in first), as the
|
|
55
|
+
* marks (request-start.ts) saw them: each left and the provider may have billed what it generated, so it counts at its
|
|
56
|
+
* hold, as one stopped does. An error before any event (refused at the HTTP level: a 429, a 5xx) counts at its own
|
|
57
|
+
* usage. Kept by identity, never on the message: pi writes the message to the store as strict JSON, which fails on a
|
|
58
|
+
* symbol key. */
|
|
59
|
+
const responseBegan = new WeakSet();
|
|
60
|
+
/** Records that `message` ended on an error after its response began. */
|
|
61
|
+
export const markResponseBegan = (message) => void responseBegan.add(message);
|
|
62
|
+
/** The field of a request's end mark (REQUEST_ENDED) that says what the cap held for it, when its stream ended aborted
|
|
63
|
+
* or its summary failed: the request counts at that figure. Optional: an end with none (an older store, a run with no
|
|
64
|
+
* cap) leaves the request cut, at an unknown cost. */
|
|
65
|
+
export const HELD_FIELD = "heldUsd";
|
|
66
|
+
/** The field of the start mark (REQUEST_STARTED) written for a request this cap refused: it never left, and pi's error
|
|
67
|
+
* entry for it answers this mark, never an earlier request's. */
|
|
68
|
+
export const CAP_REFUSED_FIELD = "capRefused";
|
|
69
|
+
/** The option a request the cap limited rides on to its start mark (request-start.ts, as `clamp`): the output tokens it was
|
|
70
|
+
* limited to, what was left of the cap for it, and the cap, so a reply cut short there says so. */
|
|
71
|
+
export const CLAMP = Symbol.for("agentrun.serve.clamp");
|
|
72
|
+
/** The tokens a limited request keeps for its answer (pi-ai's MIN_ANSWER_TOKENS): a request is refused, never sent, when
|
|
73
|
+
* what is left of its cap cannot buy them (or what it asked for, when it asked for fewer). */
|
|
74
|
+
export const ANSWER_TOKENS_LEAST = 1024;
|
|
75
|
+
/** The least thinking budget Anthropic takes: a request that thinks on an API whose thinking takes a budget keeps it
|
|
76
|
+
* beside its answer, the budget squeezed to it at the least. */
|
|
77
|
+
export const THINKING_BUDGET_LEAST = 1024;
|
|
78
|
+
/** The APIs whose thinking takes a token budget added to the request's own output limit (pi-ai's
|
|
79
|
+
* adjustMaxTokensForThinking). Elsewhere a model's reasoning shares the output limit and takes no budget, so it is
|
|
80
|
+
* allowed its thinking level's budget beside the answer, else it comes back incomplete with no answer. */
|
|
81
|
+
const BUDGET_APIS = new Set(["anthropic-messages", "bedrock-converse-stream"]);
|
|
82
|
+
/** The output tokens a request the person stopped counts beyond what it streamed: what the provider may have produced after
|
|
83
|
+
* the last word read, before it saw the stop. A stopped request counts its input, each byte it streamed as a token, and
|
|
84
|
+
* these, never more than it was held at (stoppedFigure). A stated bound, as NATIVE_SEARCH_ALLOWANCE_TOKENS is. */
|
|
85
|
+
export const STOP_ALLOWANCE_TOKENS = 1024;
|
|
86
|
+
/** The option a request's stopped figure rides on to its end mark (request-start.ts): what it counts at, given the answer
|
|
87
|
+
* it streamed, when it is stopped before its end. A symbol, so no provider ever sends it. */
|
|
88
|
+
export const STOPPED_USD = Symbol.for("agentrun.serve.stopped_usd");
|
|
89
|
+
/** What a model answer streamed, in bytes: its text, its thinking, and each tool call's name and arguments as JSON. Each
|
|
90
|
+
* byte counts as a token (a byte-level tokenizer never makes a token of less than one byte), as inputBound counts input. */
|
|
91
|
+
export function streamedBytes(message) {
|
|
92
|
+
const blocks = Array.isArray(message?.content) ? message.content : [];
|
|
93
|
+
let bytes = 0;
|
|
94
|
+
for (const block of blocks) {
|
|
95
|
+
if (typeof block?.text === "string")
|
|
96
|
+
bytes += Buffer.byteLength(block.text, "utf8");
|
|
97
|
+
if (typeof block?.thinking === "string")
|
|
98
|
+
bytes += Buffer.byteLength(block.thinking, "utf8");
|
|
99
|
+
if (block?.type === "toolCall")
|
|
100
|
+
bytes += Buffer.byteLength(`${typeof block.name === "string" ? block.name : ""}${JSON.stringify(block.arguments ?? {})}`, "utf8");
|
|
101
|
+
}
|
|
102
|
+
return bytes;
|
|
103
|
+
}
|
|
104
|
+
/** What of a model answer's reasoning streamed, in bytes (streamedBytes' unit): its thinking blocks. */
|
|
105
|
+
export function reasoningBytes(message) {
|
|
106
|
+
const blocks = Array.isArray(message?.content) ? message.content : [];
|
|
107
|
+
let bytes = 0;
|
|
108
|
+
for (const block of blocks)
|
|
109
|
+
if (typeof block?.thinking === "string")
|
|
110
|
+
bytes += Buffer.byteLength(block.thinking, "utf8");
|
|
111
|
+
return bytes;
|
|
112
|
+
}
|
|
113
|
+
/** What a request stopped before its end counts at: its input and `streamed` tokens plus STOP_ALLOWANCE_TOKENS of output,
|
|
114
|
+
* at most the output it was sent with (`limit`), at `cost`'s price; never more than `worst`, what it was held at. */
|
|
115
|
+
export const stoppedFigure = (cost, limit, worst, streamed) => bookRequest({ end: "stopped", streamedTokens: streamed }, { hold: worst, stoppedPrice: stoppedPriceOf(cost, limit) }).usd;
|
|
116
|
+
/** What a stopped request counts at, having streamed `streamed` tokens: those and STOP_ALLOWANCE_TOKENS of output, at
|
|
117
|
+
* most the output it was sent with (`limit`), at `cost`'s price; bookRequest keeps it within the hold. */
|
|
118
|
+
export const stoppedPriceOf = (cost, limit) => (streamed) => cost(Math.min(limit, streamed + STOP_ALLOWANCE_TOKENS));
|
|
119
|
+
/** The option a request's attempts ride on to its marks (request-start.ts): each HTTP attempt pi-ai made for it, as the
|
|
120
|
+
* fetch the cap gave it saw them. A symbol, so no provider ever sends it. */
|
|
121
|
+
export const ATTEMPTS = Symbol.for("agentrun.serve.attempts");
|
|
122
|
+
/** The APIs whose requests the cap cannot watch through a fetch, each with why: it gives them no recording fetch, and
|
|
123
|
+
* a request on one that fails before any event books its hold (piEnded). The one table both read. */
|
|
124
|
+
export const UNWATCHED_APIS = {
|
|
125
|
+
"openai-codex-responses": "tries a WebSocket first, which a fetch never sees",
|
|
126
|
+
"bedrock-converse-stream": "sends through its own AWS client, never options.fetch",
|
|
127
|
+
"cloudflare-ai-binding": "calls a Workers binding, never options.fetch",
|
|
128
|
+
"cloudflare-workers-ai-system-one": "never reads options.fetch",
|
|
129
|
+
"google-generative-ai": "throws on a custom fetch",
|
|
130
|
+
"google-vertex": "throws on a custom fetch",
|
|
131
|
+
"openai-decisions": "never reads options.fetch",
|
|
132
|
+
"typesafe-system-one": "never reads options.fetch",
|
|
133
|
+
};
|
|
134
|
+
const unwatched = (api) => Object.hasOwn(UNWATCHED_APIS, api);
|
|
135
|
+
/** A fetch that does what `inner` does (globalThis.fetch by default) and records each attempt in `attempts`. An attempt
|
|
136
|
+
* is `aborted` only when the request's own signal (`stop`, the run's) had fired: the SDKs hand fetch a signal of their
|
|
137
|
+
* own, which they also abort on their own timeout, and an attempt that timed out left, so it is lost, never a stop. */
|
|
138
|
+
export function recordingFetch(attempts, inner, stop) {
|
|
139
|
+
return (async (input, init) => {
|
|
140
|
+
try {
|
|
141
|
+
const response = await (inner ?? globalThis.fetch)(input, init);
|
|
142
|
+
attempts.push({ status: response.status });
|
|
143
|
+
return response;
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
attempts.push({ code: rejectionCode(error), ...(stop?.aborted ? { aborted: true } : {}) });
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/** How a pi request ended (booking.ts), from pi's message, whether its response began (an event came in), and its
|
|
152
|
+
* attempts (undefined on an API the cap cannot watch). The worst over its attempts, in the order lost > answered >
|
|
153
|
+
* nothing: an attempt is lost when its fetch was refused after it could have left (any code but a connect one), when a
|
|
154
|
+
* gateway gave up on it (504, 524), or when it was answered 2xx and its request then ended on an error, or was tried
|
|
155
|
+
* again. An answer after a lost attempt can have been billed twice: lost. No attempt seen on a watched API: it never
|
|
156
|
+
* left. */
|
|
157
|
+
const answeredOk = (a) => "status" in a && a.status >= 200 && a.status < 300;
|
|
158
|
+
/** Whether one attempt was lost: refused after it could have left (any code but a connect one), a gateway's timeout, or
|
|
159
|
+
* an answer that was not the request's last attempt (pi-ai tried again after it). That last reading assumes every fetch
|
|
160
|
+
* through the recorder is a model attempt. pi-ai's Anthropic workload identity federation (anthropic-messages.js,
|
|
161
|
+
* getAnthropicFederation) exchanges its token through the same fetch, so under it "a 2xx that was not the last" would
|
|
162
|
+
* read every answer as lost. It arms only when no API key or auth header resolves, and serve always gives pi-ai an API
|
|
163
|
+
* key, so it never arms here. */
|
|
164
|
+
export const attemptLost = (a, last) => ("code" in a ? !isConnectCode(a.code) : isGatewayTimeout(a.status) || (answeredOk(a) && !last));
|
|
165
|
+
/** Whether any attempt of a request was lost (attemptLost), its last counted as the last; one the run's own stop cut is
|
|
166
|
+
* none. A request lost so counts at its hold however it then ended: answered, failed or stopped. */
|
|
167
|
+
export const anyAttemptLost = (attempts) => attempts?.some((a, at) => !("aborted" in a && a.aborted) && attemptLost(a, at === attempts.length - 1)) ?? false;
|
|
168
|
+
export function piEnded(message, began, attempts) {
|
|
169
|
+
const ok = answeredOk;
|
|
170
|
+
const anyLost = anyAttemptLost(attempts);
|
|
171
|
+
if (message.stopReason !== "error")
|
|
172
|
+
return anyLost ? { end: "lost", label: "retried" } : { end: "answered", usd: typeof message.usage?.cost?.total === "number" ? message.usage.cost.total : null };
|
|
173
|
+
if (began)
|
|
174
|
+
return { end: "lost", label: "error_after", began: true };
|
|
175
|
+
// On an API the cap cannot watch (UNWATCHED_APIS), or with no record of its attempts, nothing says it never left.
|
|
176
|
+
if (attempts === undefined || unwatched(message.api))
|
|
177
|
+
return { end: "lost", label: "error_before" };
|
|
178
|
+
const last = attempts.at(-1);
|
|
179
|
+
if (last && "status" in last && isGatewayTimeout(last.status))
|
|
180
|
+
return { end: "lost", label: "gateway_timeout" };
|
|
181
|
+
if (anyLost || (last !== undefined && ok(last)))
|
|
182
|
+
return { end: "lost", label: "error_before" };
|
|
183
|
+
return { end: "nothing", label: last === undefined || "code" in last ? "never_left" : "status" };
|
|
184
|
+
}
|
|
185
|
+
/** How pi's error for a request whose start mark could not be written begins (request-start.ts builds it from this): the
|
|
186
|
+
* request never left, so the entry answers none, and spentIn leaves it out by this. */
|
|
187
|
+
export const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
|
|
188
|
+
/** pi's error for a request that left and whose end mark the store refused (request-start.ts): its cost is not recorded
|
|
189
|
+
* as booked, so it stays open, read at its start mark's hold, never closed by this entry at its own usage. */
|
|
190
|
+
export const END_NOT_WRITTEN = "the model request's end could not be recorded";
|
|
191
|
+
const endUnrecorded = (entry) => {
|
|
192
|
+
const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
|
|
193
|
+
return message?.stopReason === "error" && typeof message.errorMessage === "string" && message.errorMessage.startsWith(END_NOT_WRITTEN);
|
|
194
|
+
};
|
|
195
|
+
/** The input a request carrying claude-agent's native web search may read in beyond its body, added to its input bound
|
|
196
|
+
* by its adapter (adapters.ts hands it over): Claude's CLI asks for at most 8 searches a request (max_uses 8), and each
|
|
197
|
+
* search's results are billed as input, about 25,000 tokens a search as a working estimate. */
|
|
198
|
+
export const NATIVE_SEARCH_ALLOWANCE_TOKENS = 8 * 25_000;
|
|
199
|
+
export const sideRequests = new WeakMap();
|
|
200
|
+
/** The run's cap from its process's environment; absent for a run without one. */
|
|
201
|
+
export function capOf(env) {
|
|
202
|
+
const text = env[CAP_ENV];
|
|
203
|
+
if (text === undefined || text === "")
|
|
204
|
+
return undefined;
|
|
205
|
+
const cap = Number(text);
|
|
206
|
+
if (!(Number.isFinite(cap) && cap > 0))
|
|
207
|
+
throw new Error(`${CAP_ENV} is ${text}, not a number above 0`);
|
|
208
|
+
return cap;
|
|
209
|
+
}
|
|
210
|
+
/** The code a cap's refusal begins with: `spend_cap_reached: `, or with a note after it, as a request it limited refuses
|
|
211
|
+
* in (CAP_REFUSAL_CODE, "spend_cap_reached (out of budget): "). Every reader of a refusal's text (a run's end, its
|
|
212
|
+
* learning, the spend read back) reads the code through this, never a bare prefix. */
|
|
213
|
+
export const CAP_REFUSAL_PREFIX = /^spend_cap_reached(?: \([^)]*\))?: /;
|
|
214
|
+
/** Whether `entry` is pi's answer to a request this cap refused (capModels): an error that begins spend_cap_reached. */
|
|
215
|
+
const refusedHere = (entry) => {
|
|
216
|
+
const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
|
|
217
|
+
return message?.stopReason === "error" && typeof message.errorMessage === "string" && CAP_REFUSAL_PREFIX.test(message.errorMessage);
|
|
218
|
+
};
|
|
219
|
+
/** Whether `entry` is pi's error for a request whose start mark could not be written (request-start.ts, MARK_NOT_WRITTEN):
|
|
220
|
+
* it never left and has no mark of its own, so it answers no request, and read as an answer it would close another's. */
|
|
221
|
+
const notSentHere = (entry) => {
|
|
222
|
+
const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
|
|
223
|
+
return message?.stopReason === "error" && typeof message.errorMessage === "string" && message.errorMessage.startsWith(MARK_NOT_WRITTEN);
|
|
224
|
+
};
|
|
225
|
+
/** The cost an entry adds to what a run spent, as the timeline counts it: a pi answer's total (none for one stopped
|
|
226
|
+
* before its end), and the usd of a cost written apart from an answer, a paid tool's charge among them; 0 for anything
|
|
227
|
+
* else, or for a cost that is not a number (which makes the whole spend unknown, by the timeline's verdict). */
|
|
228
|
+
const costOf = (entry) => {
|
|
229
|
+
const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
|
|
230
|
+
const cost = message ? (message.stopReason === "aborted" ? undefined : message.usage?.cost?.total)
|
|
231
|
+
: entry.kind === REQUEST_COST || entry.kind === REQUEST_COST_LATE || entry.kind === TOOL_COST ? entry.data?.usd : undefined;
|
|
232
|
+
return typeof cost === "number" && Number.isFinite(cost) ? cost : 0;
|
|
233
|
+
};
|
|
234
|
+
/** A held figure as a mark carries it: a finite number, else none. */
|
|
235
|
+
const figureOf = (value) => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
|
|
236
|
+
/** Takes one figure out of `open`: `figure` itself when it is there, else the smallest, a figure that is not there reading
|
|
237
|
+
* as the largest (a start with none stays while any other could go). */
|
|
238
|
+
const close = (open, figure) => {
|
|
239
|
+
if (!open.length)
|
|
240
|
+
return;
|
|
241
|
+
let at = figure === undefined ? -1 : open.indexOf(figure);
|
|
242
|
+
if (at < 0)
|
|
243
|
+
at = open.reduce((low, f, i) => (f !== undefined && (open[low] === undefined || f < open[low]) ? i : low), 0);
|
|
244
|
+
open.splice(at, 1);
|
|
245
|
+
};
|
|
246
|
+
/** The figures of the requests of each kind that `entries` leave open, marked as sent with no answer, cost or end, read in
|
|
247
|
+
* order, as the run's timeline counts them (pi-durable-agent's meter), so the two agree on how many were cut. A start adds
|
|
248
|
+
* its figure. An end mark closes its own start: a stopped request's at the figure it names, a withdrawn one's (`unsent`,
|
|
249
|
+
* which names none) the smallest. An end that names none for a request that left (an older store) closes nothing, so
|
|
250
|
+
* that request stays cut. An answer, or a summary's cost, closes the smallest figure still open, since when requests
|
|
251
|
+
* overlap the marks do not say which one it answered. What stays open is then never less than the requests truly open,
|
|
252
|
+
* figure for figure: taking the smallest, or the very figure an end names, never leaves a smaller figure open than any
|
|
253
|
+
* other way of reading the same marks. It is exactly them when requests do not overlap. pi's answer to a request that
|
|
254
|
+
* never left (REQUEST_REFUSED's error entry) and a harness answer's continuation close nothing. */
|
|
255
|
+
function openFigures(entries) {
|
|
256
|
+
const open = { generation: [], compaction: [] };
|
|
257
|
+
let [refused, continued] = [0, 0];
|
|
258
|
+
for (const entry of entries) {
|
|
259
|
+
const message = entry.model?.[0];
|
|
260
|
+
const data = (entry.data ?? {});
|
|
261
|
+
// A side request (a compaction's summary, a tool's own request): marked with a label, as the timeline reads it.
|
|
262
|
+
const kind = typeof data.request === "string" ? "compaction" : "generation";
|
|
263
|
+
if (entry.kind === REQUEST_REFUSED)
|
|
264
|
+
refused += 1;
|
|
265
|
+
else if (entry.kind === "pi.assistant" && refused > 0 && message?.stopReason === "error")
|
|
266
|
+
refused -= 1;
|
|
267
|
+
else if (entry.kind === REQUEST_CONTINUED)
|
|
268
|
+
continued += 1;
|
|
269
|
+
else if (entry.kind === "pi.assistant" && continued > 0 && message)
|
|
270
|
+
continued -= 1;
|
|
271
|
+
else if (entry.kind === REQUEST_STARTED)
|
|
272
|
+
open[kind].push(figureOf(data[HELD_FIELD]));
|
|
273
|
+
else if (entry.kind === REQUEST_ENDED) {
|
|
274
|
+
if (data.unsent === true)
|
|
275
|
+
close(open[kind]);
|
|
276
|
+
else if (figureOf(data[HELD_FIELD]) !== undefined)
|
|
277
|
+
close(open[kind], figureOf(data[HELD_FIELD]));
|
|
278
|
+
}
|
|
279
|
+
else if (entry.kind === REQUEST_COST)
|
|
280
|
+
close(open.compaction);
|
|
281
|
+
else if (entry.kind === "pi.assistant" && message)
|
|
282
|
+
close(open.generation);
|
|
283
|
+
}
|
|
284
|
+
return open;
|
|
285
|
+
}
|
|
286
|
+
/** What the run's store says its model requests cost, across every conversation in it: known or not as the run's own
|
|
287
|
+
* timeline says (pi-durable-agent's timelineOf), read as a settled run, since the process that wrote it is gone, and
|
|
288
|
+
* then the full amount, never the timeline's total rounded for display. Every response, and each cost written apart
|
|
289
|
+
* from one (a compaction summary's; a harness request's that came in after its answer). A cost that is not a number, or
|
|
290
|
+
* one still pending, leaves it unknown, as the timeline says. These readings are the cap's own, on its copy of the
|
|
291
|
+
* entries (the run's shown cost is the timeline's, unchanged): a request stopped before its end counts at the figure its
|
|
292
|
+
* end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the figure its start mark
|
|
293
|
+
* holds (openFigures), each the worst case the cap held for it; without that figure either stays cut, at an unknown
|
|
294
|
+
* cost. A paid call settled at a charge it did not say, like one a crash cut, counts at the figure its mark holds. And
|
|
295
|
+
* this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. `sides`: only the
|
|
296
|
+
* run's side requests (each marked with a label: a learned workflow's, a hosted search's), what a run on another
|
|
297
|
+
* harness spent beside its harness's own requests and its paid tools, which that harness's booking does not hold. */
|
|
298
|
+
export function spentIn(storeFile, { sides = false } = {}) {
|
|
299
|
+
if (!existsSync(storeFile))
|
|
300
|
+
return 0;
|
|
301
|
+
const db = new DatabaseSync(storeFile, { readOnly: true });
|
|
302
|
+
const entries = [];
|
|
303
|
+
// The store's own entries, as read (without the answers written below for a stopped request): openFigures reads them.
|
|
304
|
+
const read = [];
|
|
305
|
+
let marked = false;
|
|
306
|
+
const rows = [];
|
|
307
|
+
try {
|
|
308
|
+
for (const row of db.prepare("SELECT record FROM entries ORDER BY rowid").iterate()) {
|
|
309
|
+
const entry = JSON.parse(String(row.record));
|
|
310
|
+
if (!sides || ([REQUEST_STARTED, REQUEST_ENDED, REQUEST_COST, REQUEST_COST_LATE].includes(entry.kind) && typeof entry.data?.request === "string"))
|
|
311
|
+
rows.push(entry);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
finally {
|
|
315
|
+
db.close();
|
|
316
|
+
}
|
|
317
|
+
// pi's error entry for a request that ended on an error after its response began is left out, as an aborted one is: its
|
|
318
|
+
// end mark (`error`) counts it at its hold. pi writes the entry as the mark is written, before it or after, so each such
|
|
319
|
+
// mark takes the nearest error entry not yet taken among those after the earliest start holding its figure (a request's
|
|
320
|
+
// start and end marks hold the same, request-start.ts). Its own entry comes after its own start, so it is always among
|
|
321
|
+
// them. An error before every such start answered an earlier request (a 429, before any event): taken when a crash came
|
|
322
|
+
// between the mark and pi's entry, it would leave that request open at its hold. The marks with the fewest entries to
|
|
323
|
+
// choose from take first, so as many are taken as the marks' own entries in the store and no more errors are read as
|
|
324
|
+
// answers than are, one of which could close a start a crash cut; which one a mark takes, when errors overlap, moves no
|
|
325
|
+
// figure below what can have been spent, as an answer's choice of start does not (openFigures). An earlier start holding
|
|
326
|
+
// the very same figure (a 429's retry, with the same context) leaves its 429 takeable, so the spend then reads high,
|
|
327
|
+
// never low: telling the two apart needs to know which request each entry answers, and the marks do not say. An error
|
|
328
|
+
// with no such mark (before any event: a 429, a 5xx) is its request's answer.
|
|
329
|
+
// A cancel's refusal (REQUEST_REFUSED) answers the next error entry, as openFigures and the timeline read them: those are
|
|
330
|
+
// no request's, and no end mark takes one.
|
|
331
|
+
const stopOf = (entry) => entry.model?.[0]?.stopReason;
|
|
332
|
+
const errorsAt = [];
|
|
333
|
+
// pi's answers: a `lost` end mark (written before a retry, request-start.ts) takes pi's entry for its own request, an
|
|
334
|
+
// answer or an error, the first after the mark: it is counted at the mark's hold, never at its usage too.
|
|
335
|
+
const answersAt = [];
|
|
336
|
+
let refusals = 0;
|
|
337
|
+
rows.forEach((entry, at) => {
|
|
338
|
+
if (entry.kind === REQUEST_REFUSED)
|
|
339
|
+
refusals += 1;
|
|
340
|
+
else if (entry.kind === "pi.assistant" && stopOf(entry) === "error" && !refusedHere(entry) && !notSentHere(entry) && !endUnrecorded(entry)) {
|
|
341
|
+
if (refusals > 0)
|
|
342
|
+
refusals -= 1;
|
|
343
|
+
else
|
|
344
|
+
errorsAt.push(at);
|
|
345
|
+
}
|
|
346
|
+
else if (entry.kind === "pi.assistant" && stopOf(entry) !== "error" && stopOf(entry) !== "aborted")
|
|
347
|
+
answersAt.push(at);
|
|
348
|
+
});
|
|
349
|
+
const taken = new Set();
|
|
350
|
+
const fieldsOf = (entry) => (entry.data ?? {});
|
|
351
|
+
const generationStart = (entry) => entry.kind === REQUEST_STARTED && typeof fieldsOf(entry).request !== "string" && fieldsOf(entry)[CAP_REFUSED_FIELD] !== true;
|
|
352
|
+
// Each such end mark, with the earliest start holding its figure (-1 for none: any error entry then).
|
|
353
|
+
const endsOf = (field) => rows.flatMap((entry, at) => entry.kind === REQUEST_ENDED && fieldsOf(entry)[field] === true
|
|
354
|
+
? [{ at, from: rows.findIndex((start, i) => i < at && generationStart(start) && figureOf(fieldsOf(start)[HELD_FIELD]) === figureOf(fieldsOf(entry)[HELD_FIELD])) }]
|
|
355
|
+
: []);
|
|
356
|
+
// A `lost` mark is written before its request's retry is sent (request-start.ts watchingLost) and is in the store before
|
|
357
|
+
// pi has the request's result, so its request's entry is the first after it, before the next generation request's start
|
|
358
|
+
// (one sent after it): never an earlier request's answer, however near. None there (its entry was the loud failure of a
|
|
359
|
+
// mark the store took late, END_NOT_WRITTEN, or a crash came first) and it takes none. These go first, so an error mark
|
|
360
|
+
// never takes a lost request's own entry.
|
|
361
|
+
const afterMark = [...errorsAt, ...answersAt].sort((a, b) => a - b);
|
|
362
|
+
// An `unpriced` mark (an answer whose cost cannot be read, at its hold) is written the same way, before pi has the answer.
|
|
363
|
+
for (const { at } of [...endsOf("lost"), ...endsOf("unpriced")]) {
|
|
364
|
+
const next = rows.findIndex((entry, i) => i > at && generationStart(entry));
|
|
365
|
+
const own = afterMark.find((entry) => entry > at && (next < 0 || entry < next) && !taken.has(entry));
|
|
366
|
+
if (own !== undefined)
|
|
367
|
+
taken.add(own);
|
|
368
|
+
}
|
|
369
|
+
for (const { at, from } of endsOf("error").sort((a, b) => b.from - a.from)) {
|
|
370
|
+
let nearest = -1;
|
|
371
|
+
for (const entry of errorsAt)
|
|
372
|
+
if (entry > from && !taken.has(entry) && (nearest < 0 || Math.abs(entry - at) < Math.abs(nearest - at)))
|
|
373
|
+
nearest = entry;
|
|
374
|
+
if (nearest >= 0)
|
|
375
|
+
taken.add(nearest);
|
|
376
|
+
}
|
|
377
|
+
// Each paid tool call marked and not settled, by call: what it was held at.
|
|
378
|
+
const calls = new Map();
|
|
379
|
+
for (const [at, entry] of rows.entries()) {
|
|
380
|
+
const data = (entry.data ?? {});
|
|
381
|
+
// A request this cap refused never left, and costs nothing: its mark and pi's error entry for it (an older store
|
|
382
|
+
// has the entry alone, which the timeline would count as answering an earlier request a crash cut). Nor did one
|
|
383
|
+
// whose start mark could not be written, whose error entry has no mark at all. A cancel's refusal is its mark
|
|
384
|
+
// (REQUEST_REFUSED) and pi's error for it, which close nothing together (openFigures, and the timeline).
|
|
385
|
+
if (refusedHere(entry) || notSentHere(entry) || (entry.kind === REQUEST_STARTED && data[CAP_REFUSED_FIELD] === true))
|
|
386
|
+
continue;
|
|
387
|
+
// A paid call settled at a charge it did not say: at the figure its mark holds, the cap's bound for it.
|
|
388
|
+
const bound = entry.kind === TOOL_COST && figureOf(data.usd) === undefined ? figureOf(calls.get(data.call)) : undefined;
|
|
389
|
+
if (entry.kind === TOOL_STARTED)
|
|
390
|
+
calls.set(data.call, data[HELD_FIELD]);
|
|
391
|
+
if (entry.kind === TOOL_COST)
|
|
392
|
+
calls.delete(data.call);
|
|
393
|
+
if (entry.kind === REQUEST_STARTED)
|
|
394
|
+
marked = true;
|
|
395
|
+
// pi's entry for a marked request stopped before its end (what had streamed of it): the request is counted by its
|
|
396
|
+
// marks instead, at the figure its end holds, or cut. Before the first mark (an older run) it stays unknown.
|
|
397
|
+
if (marked && entry.kind === "pi.assistant" && entry.model?.[0]?.stopReason === "aborted")
|
|
398
|
+
continue;
|
|
399
|
+
// pi's entry for a request whose end mark the store refused: the request stays open, at its start's hold.
|
|
400
|
+
if (marked && endUnrecorded(entry))
|
|
401
|
+
continue;
|
|
402
|
+
if (taken.has(at))
|
|
403
|
+
continue;
|
|
404
|
+
entries.push(bound === undefined ? entry : { ...entry, data: { ...data, usd: bound } });
|
|
405
|
+
read.push(entry);
|
|
406
|
+
const held = data[HELD_FIELD];
|
|
407
|
+
// A summary that ended on an error after its response began (its cost mark says `failed`) counts at its hold.
|
|
408
|
+
// So does one whose cost could not be read (`unpriced`): the booking rule's figure for an answer with no cost.
|
|
409
|
+
if (entry.kind === REQUEST_COST && (data.failed === true || data.unpriced === true) && figureOf(held) !== undefined)
|
|
410
|
+
entries[entries.length - 1] = { ...entry, data: { ...data, usd: held } };
|
|
411
|
+
if (entry.kind !== REQUEST_ENDED || data.unsent === true || typeof held !== "number" || !Number.isFinite(held))
|
|
412
|
+
continue;
|
|
413
|
+
// The stopped request closed at what the cap held for it: a summary by its cost, a generation by an answer.
|
|
414
|
+
entries.push(typeof data.request === "string"
|
|
415
|
+
? { kind: REQUEST_COST, data: { request: data.request, usd: held } }
|
|
416
|
+
: { kind: "pi.assistant", ...(entry.conversationId !== undefined ? { conversationId: entry.conversationId } : {}), model: [{ role: "assistant", content: [], stopReason: "stop", usage: { cost: { total: held } }, timestamp: 0 }] });
|
|
417
|
+
}
|
|
418
|
+
// A paid tool call a crash cut (marked, never settled) counts at its held figure, settled by it here, as a cut request.
|
|
419
|
+
for (const [call, figure] of calls)
|
|
420
|
+
entries.push({ kind: TOOL_COST, data: { call, usd: figureOf(figure) ?? null } });
|
|
421
|
+
// A request still open is one a crash cut, with no answer and no end: it counts at what the cap held for it, as its start
|
|
422
|
+
// mark says: its own figure when requests do not overlap, else one never less (openFigures). One still open with no
|
|
423
|
+
// figure (an older store) leaves them all cut, unknown.
|
|
424
|
+
const open = openFigures(read);
|
|
425
|
+
for (const kind of ["generation", "compaction"]) {
|
|
426
|
+
const figures = open[kind];
|
|
427
|
+
if (figures.some((figure) => figure === undefined))
|
|
428
|
+
continue;
|
|
429
|
+
for (const figure of figures) {
|
|
430
|
+
entries.push(kind === "compaction"
|
|
431
|
+
? { kind: REQUEST_COST, data: { request: "compaction", usd: figure } }
|
|
432
|
+
: { kind: "pi.assistant", model: [{ role: "assistant", content: [], stopReason: "stop", usage: { cost: { total: figure } }, timestamp: 0 }] });
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
// The timeline says whether the spend is known; the amount is summed here, as it is, since the timeline rounds its total
|
|
436
|
+
// for display (to the millionth of a dollar), and a cap must not lose what that drops.
|
|
437
|
+
const usage = timelineOf(entries, { settled: true }).find((row) => row.kind === "usage")?.usage;
|
|
438
|
+
if (usage === undefined)
|
|
439
|
+
return 0;
|
|
440
|
+
if (typeof usage.usd !== "number" || !Number.isFinite(usage.usd))
|
|
441
|
+
return null;
|
|
442
|
+
return entries.reduce((sum, entry) => sum + costOf(entry), 0);
|
|
443
|
+
}
|
|
444
|
+
export function metersIn(storeFile) {
|
|
445
|
+
const { known: _, ...meters } = meterFiguresIn(storeFile);
|
|
446
|
+
return meters;
|
|
447
|
+
}
|
|
448
|
+
/** metersIn's meters, and beside them each meter's known dollars: its settled charges' figures, whether or not another of
|
|
449
|
+
* its charges is unknown (a hold, a call cut or never settled, is no charge here: it adds nothing). What a run of
|
|
450
|
+
* unknown cost is known to have spent on each (server.ts /usage). */
|
|
451
|
+
export function meterFiguresIn(storeFile) {
|
|
452
|
+
if (!existsSync(storeFile))
|
|
453
|
+
return { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
|
|
454
|
+
const db = new DatabaseSync(storeFile, { readOnly: true, timeout: 2_000 });
|
|
455
|
+
try {
|
|
456
|
+
const rows = db.prepare("SELECT conversation_id AS conversation, record FROM entries ORDER BY rowid").all().map((row) => ({ conversation: Number(row.conversation), entry: JSON.parse(String(row.record)) }));
|
|
457
|
+
const root = rows.reduce((min, row) => Math.min(min, row.conversation), Infinity);
|
|
458
|
+
const marks = new Set();
|
|
459
|
+
const charges = [];
|
|
460
|
+
const browser = { usd: 0, seconds: 0 };
|
|
461
|
+
const others = [];
|
|
462
|
+
// Each meter's known dollars, whether or not one of its charges is unknown: what a run of unknown cost is known to
|
|
463
|
+
// have spent on it (server.ts /usage).
|
|
464
|
+
const known = { tokens: 0, browser: 0, others: 0 };
|
|
465
|
+
for (const { entry } of rows) {
|
|
466
|
+
const data = (entry.data ?? {});
|
|
467
|
+
if (entry.kind === TOOL_STARTED)
|
|
468
|
+
marks.add(data.call);
|
|
469
|
+
else if (entry.kind === TOOL_COST)
|
|
470
|
+
marks.delete(data.call), charges.push(figureOf(data.usd));
|
|
471
|
+
if (entry.kind === TOOL_COST && data.tool !== "browser")
|
|
472
|
+
others.push(figureOf(data.usd)), (known.others += figureOf(data.usd) ?? 0);
|
|
473
|
+
if (entry.kind !== TOOL_COST || data.tool !== "browser")
|
|
474
|
+
continue;
|
|
475
|
+
const usd = figureOf(data.usd);
|
|
476
|
+
known.browser += usd ?? 0;
|
|
477
|
+
browser.usd = browser.usd === null || usd === undefined ? null : browser.usd + usd;
|
|
478
|
+
browser.seconds += figureOf(data.seconds) ?? 0;
|
|
479
|
+
}
|
|
480
|
+
const tools = marks.size || charges.some((usd) => usd === undefined) ? null : charges.reduce((sum, usd) => sum + usd, 0);
|
|
481
|
+
const rest = rows.filter(({ conversation, entry }) => conversation === root && entry.kind !== TOOL_STARTED && entry.kind !== TOOL_COST).map(({ entry }) => entry);
|
|
482
|
+
const usage = timelineOf(rest, { settled: true }).find((row) => row.kind === "usage");
|
|
483
|
+
const otherTools = marks.size || others.some((usd) => usd === undefined) ? null : others.reduce((sum, usd) => sum + usd, 0);
|
|
484
|
+
known.tokens = usage ? (usage.usage?.usd ?? usage.usage?.so_far_usd ?? 0) : 0;
|
|
485
|
+
return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0, browser, others: otherTools, known };
|
|
486
|
+
}
|
|
487
|
+
finally {
|
|
488
|
+
db.close();
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
/** What the paid tools of `entries` (TOOL_STARTED and TOOL_COST) spent, as the cap counts it: each charge, and a call
|
|
492
|
+
* settled at a charge it did not say, or a crash cut (marked, never settled), at its held figure, as spentIn counts it;
|
|
493
|
+
* null when one has no figure. The run's reported cost reads such a call unknown instead (the timeline). */
|
|
494
|
+
export function capToolSpend(entries) {
|
|
495
|
+
const open = new Map();
|
|
496
|
+
const figures = [];
|
|
497
|
+
for (const { kind, data } of entries) {
|
|
498
|
+
const at = (data ?? {});
|
|
499
|
+
if (kind === TOOL_STARTED)
|
|
500
|
+
open.set(at.call, at[HELD_FIELD]);
|
|
501
|
+
else if (kind === TOOL_COST)
|
|
502
|
+
figures.push(figureOf(at.usd) ?? open.get(at.call)), open.delete(at.call);
|
|
503
|
+
}
|
|
504
|
+
const all = [...figures, ...open.values()].map(figureOf);
|
|
505
|
+
return all.every((figure) => figure !== undefined) ? all.reduce((sum, figure) => sum + figure, 0) : null;
|
|
506
|
+
}
|
|
507
|
+
/** 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
|
|
508
|
+
* check on a harness whose booking counts a request only once its cost is in (harness-app.ts): `admitted` takes what
|
|
509
|
+
* the guard held, `started` gives it the turn that request leaves as (admissions run one at a time), `ended` drops it. */
|
|
510
|
+
export function holdsInFlight() {
|
|
511
|
+
const holds = new Map();
|
|
512
|
+
// One slot between admitted() and started(): the runner admits one model request at a time per session.
|
|
513
|
+
let next;
|
|
514
|
+
return {
|
|
515
|
+
admitted: (usd) => void (next = usd),
|
|
516
|
+
started: (turn) => void (next !== undefined && holds.set(turn, next), (next = undefined)),
|
|
517
|
+
ended: (turn) => void holds.delete(turn),
|
|
518
|
+
total: () => [...holds.values()].reduce((sum, usd) => sum + usd, 0),
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
let runSpend;
|
|
522
|
+
let paying = Promise.resolve();
|
|
523
|
+
export const useSpend = (spend) => {
|
|
524
|
+
runSpend = spend;
|
|
525
|
+
// A paid call's refusal is its own spend's (its run's): another spend starts with none.
|
|
526
|
+
paidRoomRefusal = undefined;
|
|
527
|
+
};
|
|
528
|
+
/** Each paid call sent under the cap and not settled, at what it is held at; on another harness, each of the run's own
|
|
529
|
+
* model requests in flight too (capModels' `joined`). */
|
|
530
|
+
const paidOpen = new Set();
|
|
531
|
+
/** What the paid calls under way are held at, together (0 when none is): the one figure every check of the run's cap
|
|
532
|
+
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). On another
|
|
533
|
+
* harness the run's own model requests in flight (a learned workflow's, a hosted search's) are held here too, so the
|
|
534
|
+
* harness's check sees them. */
|
|
535
|
+
export const paidHolds = () => [...paidOpen].reduce((sum, { usd }) => sum + usd, 0);
|
|
536
|
+
/** A paid hold that outlives the paidCall that took it (a browser session's, browser-cost.ts), counted in paidHolds as a
|
|
537
|
+
* call's is until `drop`: its figure is `usd`, which its owner moves as charges use it. */
|
|
538
|
+
export const keepHold = (usd) => {
|
|
539
|
+
const open = { usd, drop: () => void paidOpen.delete(open) };
|
|
540
|
+
paidOpen.add(open);
|
|
541
|
+
return open;
|
|
542
|
+
};
|
|
543
|
+
/** A charge booked outside any paidCall (a browser session's, booked in the commit that bills it) joins what the run's
|
|
544
|
+
* process counts as spent, as a paid call's does; with no cap, nothing counts it. */
|
|
545
|
+
export const addSpend = (usd) => runSpend?.add(usd);
|
|
546
|
+
/** The run's cap, when it has one. */
|
|
547
|
+
export const runCap = () => runSpend?.cap;
|
|
548
|
+
/** On another harness, what the run's own model requests (capModels' `joined`) have cost: those of earlier processes
|
|
549
|
+
* (spentIn's `sides`) and this one's; null once one is unknown. 0 on pi, where the run's one capModels counts them. */
|
|
550
|
+
let sidesSpent = 0;
|
|
551
|
+
/** What sidesSpent says: the harness's check adds it to what its booking says the run spent (harness-app.ts). */
|
|
552
|
+
export const sideSpend = () => sidesSpent;
|
|
553
|
+
/** `call`, a paid tool's (`name`), under the run's cap, by the rule a model request keeps: refused, in words that name
|
|
554
|
+
* its price and the cap and never calling it, unless what the run has spent plus what the call is held at (`hold`: its
|
|
555
|
+
* quote, else an allowance, `basis` saying which) fits the cap, and whenever the spend is unknown; else run, one paid
|
|
556
|
+
* call at a time, so each check sees the charge before it, and held at that figure (paidHolds) until the charge it
|
|
557
|
+
* reports (`charge` of its result, undefined for none) joins the spend. A charge it does not say (null), or a call that
|
|
558
|
+
* fails, counts at its held figure, as its mark does from the store (spentIn), since it may have charged that much.
|
|
559
|
+
* With no cap it just runs. */
|
|
560
|
+
/** A paid call this run's cap refused for room (paidCall): its words, after the code, and its figures as a model
|
|
561
|
+
* request's refusal keeps them (what was taken, and the call's hold as what it needs). The model's next request is
|
|
562
|
+
* refused in these words and with these figures (takePaidRefusal), so the turn ends on the refusal, as a refused model
|
|
563
|
+
* request's does, and the run waits on a raise (runs.ts pausedAt), its model never given a turn to route around it. */
|
|
564
|
+
let paidRoomRefusal;
|
|
565
|
+
/** The paid call's refusal the next model request of the run whose spend is `owner` is refused with, once: undefined
|
|
566
|
+
* 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
|
|
567
|
+
* others), never a guard a caller builds apart. */
|
|
568
|
+
export function takePaidRefusal(owner) {
|
|
569
|
+
const refusal = paidRoomRefusal;
|
|
570
|
+
if (!refusal || !owner || refusal.owner !== owner)
|
|
571
|
+
return undefined;
|
|
572
|
+
paidRoomRefusal = undefined;
|
|
573
|
+
return { words: refusal.words, figures: refusal.figures };
|
|
574
|
+
}
|
|
575
|
+
export async function paidCall(name, call, charge, hold) {
|
|
576
|
+
const spend = runSpend;
|
|
577
|
+
if (!spend)
|
|
578
|
+
return { result: await call() };
|
|
579
|
+
const turn = paying.then(async () => {
|
|
580
|
+
const read = await spend.spent();
|
|
581
|
+
if (read === null)
|
|
582
|
+
return { refused: `${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.` };
|
|
583
|
+
// What is held for requests and calls still answering, apart from what was spent, as a model request's refusal says it.
|
|
584
|
+
const holding = (spend.held?.() ?? 0) + paidHolds();
|
|
585
|
+
// Written so that a figure that is not a number refuses.
|
|
586
|
+
if (!(read + holding + hold.usd <= spend.cap + FIT_TOLERANCE)) {
|
|
587
|
+
// Refused for room: a raise would send it, so the run pauses at the model's next request (takePaidRefusal).
|
|
588
|
+
const refused = paidRefusal(spend.cap, read, holding, name, hold);
|
|
589
|
+
paidRoomRefusal = { owner: spend, words: refused.slice(`${SPEND_CAP_REACHED}: `.length), figures: { spentUsd: read + holding, needsUsd: hold.usd } };
|
|
590
|
+
return { refused };
|
|
591
|
+
}
|
|
592
|
+
// Held from here; settled into the spend in the same step that lets the hold go, so no check between sees neither.
|
|
593
|
+
const open = { usd: hold.usd };
|
|
594
|
+
paidOpen.add(open);
|
|
595
|
+
try {
|
|
596
|
+
const result = await call();
|
|
597
|
+
const usd = charge(result);
|
|
598
|
+
if (usd !== undefined)
|
|
599
|
+
spend.add(usd ?? hold.usd);
|
|
600
|
+
return { result };
|
|
601
|
+
}
|
|
602
|
+
catch (error) {
|
|
603
|
+
spend.add(hold.usd);
|
|
604
|
+
throw error;
|
|
605
|
+
}
|
|
606
|
+
finally {
|
|
607
|
+
paidOpen.delete(open);
|
|
608
|
+
}
|
|
609
|
+
});
|
|
610
|
+
paying = turn.catch(() => undefined);
|
|
611
|
+
return turn;
|
|
612
|
+
}
|
|
613
|
+
/** The most output tokens one request may take: the model's ceiling, else its context window. A thinking budget can
|
|
614
|
+
* raise a request's ceiling up to the model's, whatever maxTokens it asked for. */
|
|
615
|
+
export const ceilingTokens = (model) => (model.maxTokens > 0 ? model.maxTokens : model.contextWindow);
|
|
616
|
+
/** The output tokens a request's worst case is priced at: the model's ceiling; none when the model names no ceiling and
|
|
617
|
+
* its output costs nothing at every price tier, so any number of output tokens is $0; undefined when its output is
|
|
618
|
+
* priced and it names no ceiling, so nothing bounds what a request may cost. */
|
|
619
|
+
function outputBound(model) {
|
|
620
|
+
const ceiling = ceilingTokens(model);
|
|
621
|
+
if (Number.isFinite(ceiling) && ceiling > 0)
|
|
622
|
+
return ceiling;
|
|
623
|
+
return [model.cost, ...(model.cost?.tiers ?? [])].every((rates) => rates?.output === 0) ? 0 : undefined;
|
|
624
|
+
}
|
|
625
|
+
/** A request's input tokens, bounded above: one per UTF-8 byte of what is sent (a byte-level tokenizer never takes
|
|
626
|
+
* fewer than one byte a token, and an image's base64 is far more bytes than its tokens), plus `overhead`, what the
|
|
627
|
+
* provider adds server-side that the body does not hold. The same bound on every harness. */
|
|
628
|
+
export const inputBound = (sent, overhead = 0) => Buffer.byteLength(sent, "utf8") + overhead;
|
|
629
|
+
/** What pi's provider adds server-side to a request of `context`, the same table the model proxy uses, by the model's API
|
|
630
|
+
* kind: undefined for a kind whose additions are not known. The context does not say how the request chooses a tool,
|
|
631
|
+
* so the dearer choice is taken. */
|
|
632
|
+
export function piOverhead(model, context) {
|
|
633
|
+
const parts = (context.messages ?? []).flatMap((message) => (Array.isArray(message.content) ? (message.content) : []));
|
|
634
|
+
return providerInputOverhead(model.api, { tools: (context.tools?.length ?? 0) > 0, toolChoice: "any", images: parts.filter((part) => part?.type === "image").length });
|
|
635
|
+
}
|
|
636
|
+
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.`;
|
|
637
|
+
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.`;
|
|
638
|
+
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.`;
|
|
639
|
+
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.`;
|
|
640
|
+
/** A request's worst case at `model`'s price: `input` tokens at the dearer of its input and cache-write prices, and
|
|
641
|
+
* `output` tokens at its output price. */
|
|
642
|
+
function worstOf(calculateCost, model) {
|
|
643
|
+
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;
|
|
644
|
+
return (input, output) => Math.max(priced({ input, output }), priced({ cacheWrite: input, output }));
|
|
645
|
+
}
|
|
646
|
+
/** 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). */
|
|
647
|
+
export function money(usd) {
|
|
648
|
+
// A whole number of dollars as given ($1), else two decimals or as many as it takes (up to eight) to show it whole.
|
|
649
|
+
if (Number.isInteger(usd))
|
|
650
|
+
return `$${usd}`;
|
|
651
|
+
for (let digits = 2; digits < 8; digits++)
|
|
652
|
+
if (Number(usd.toFixed(digits)) === Number(usd.toFixed(8)))
|
|
653
|
+
return `$${usd.toFixed(digits)}`;
|
|
654
|
+
return `$${usd.toFixed(8)}`;
|
|
655
|
+
}
|
|
656
|
+
/** The code a cap's refusal begins with: `spend_cap_reached`, which the server ends the run with, and "out of budget",
|
|
657
|
+
* which pi-ai's retry (isRetryableAssistantError, which reads only an error's text) takes as final whatever digits the
|
|
658
|
+
* words after it hold. The words after it are the ones a person reads. */
|
|
659
|
+
export const CAP_REFUSAL_CODE = `${SPEND_CAP_REACHED} (out of budget): `;
|
|
660
|
+
/** The words of a refusal for room (CAP_REFUSAL_CODE: what is left of the cap cannot buy the request's least), which a
|
|
661
|
+
* higher cap would send; undefined for any other text, a refusal no cap could fix included (an unknown spend, no price,
|
|
662
|
+
* no output ceiling, an input not measured: the bare `spend_cap_reached: ` code). The one reader of that difference. */
|
|
663
|
+
export const roomRefusal = (text) => (text?.startsWith(CAP_REFUSAL_CODE) ? text.slice(CAP_REFUSAL_CODE.length) : undefined);
|
|
664
|
+
/** A model's name as the words say it: the catalog's, without a vendor's prefix ("Anthropic: Claude Sonnet 5.5" reads
|
|
665
|
+
* "Claude Sonnet 5.5"), else its id. */
|
|
666
|
+
export const nameOf = (model) => (model.name || model.id).replace(/^[^:]{1,40}:\s+(?=\S)/, "");
|
|
667
|
+
/** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
|
|
668
|
+
// Cents rounded up within the tail the fit check allows (FIT_TOLERANCE), no wider: a total past a cent by more than a
|
|
669
|
+
// float's own tail rounds to the cent above, so the cap a refusal names admits what it refused.
|
|
670
|
+
export const leastMoney = (usd) => `$${(Math.ceil(usd * 100 - FIT_TOLERANCE * 100) / 100).toFixed(2)}`;
|
|
671
|
+
/** The cap to raise to for a request past `cap` that needs `total` in all: a cent at least, and above the cap, never
|
|
672
|
+
* the cap itself, so a raise to it is one PATCH /runs/{id} takes. */
|
|
673
|
+
export const raiseTo = (cap, total) => {
|
|
674
|
+
const cents = Math.ceil(total * 100 - FIT_TOLERANCE * 100);
|
|
675
|
+
return `$${((cents / 100 > cap + CAP_TOLERANCE ? cents : Math.floor((cap + CAP_TOLERANCE) * 100) + 1) / 100).toFixed(2)}`;
|
|
676
|
+
};
|
|
677
|
+
/** The cap's refusal of a request what is left of it cannot buy the least of, in plain words with the numbers: what
|
|
678
|
+
* the run spent (and holds for requests still answering) of its cap, what the request needs at the least, and the cap
|
|
679
|
+
* that would run it (spent, held and that least, rounded up to the cent, so that it is enough). After its code
|
|
680
|
+
* (CAP_REFUSAL_CODE), which keeps it final to pi-ai's retry. */
|
|
681
|
+
function capRefusal(cap, spent, held, name, least) {
|
|
682
|
+
const [need, raise] = [leastMoney(least), raiseTo(cap, spent + held + least)];
|
|
683
|
+
if (spent === 0 && held === 0)
|
|
684
|
+
return `${CAP_REFUSAL_CODE}Not sent: this run's cap of ${money(cap)} can't cover one ${name} request (at least ${need}). Raise the cap to at least ${raise} to run it.`;
|
|
685
|
+
const owes = held > 0 ? `spent ${money(spent)} and holds ${money(held)} for requests still answering, of its ${money(cap)} cap` : `spent ${money(spent)} of its ${money(cap)} cap`;
|
|
686
|
+
return `${CAP_REFUSAL_CODE}Not sent: the run has ${owes}, and its next ${name} request needs at least ${need}. Raise the cap to at least ${raise} to run it.`;
|
|
687
|
+
}
|
|
688
|
+
/** The cap's refusal of a paid call (paidCall) what is left of it cannot hold, in one sentence, as capRefusal says a model
|
|
689
|
+
* request's: what the run spent (and holds for requests and calls still answering) of its cap, what the call could cost
|
|
690
|
+
* 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
|
|
691
|
+
* cap at the least, since a figure past the cap by less than a cent still needs more than the cap. Every amount by money,
|
|
692
|
+
* the raise by leastMoney. */
|
|
693
|
+
function paidRefusal(cap, spent, held, name, hold) {
|
|
694
|
+
const holds = held > 0 ? ` and holds ${money(held)} for calls still answering` : "";
|
|
695
|
+
// The model refusal's rule (raiseTo): a cent at least, and above the cap, never the cap itself.
|
|
696
|
+
const raise = raiseTo(cap, spent + held + hold.usd);
|
|
697
|
+
return `${SPEND_CAP_REACHED}: Not sent: the run has spent ${money(spent)}${holds} of its ${money(cap)} cap, and ${name} could cost up to ${money(hold.usd)} (${hold.basis}). Raise the cap to at least ${raise} to run it.`;
|
|
698
|
+
}
|
|
699
|
+
/** The most output tokens from `least` to `asked` whose request costs no more than `left` (`cost`, its price at that
|
|
700
|
+
* many, rising with them); undefined when even `least` costs more. A search, so that a price with tiers is exact. */
|
|
701
|
+
function mostOutput(cost, least, asked, left) {
|
|
702
|
+
// Written so that a cost that is not a number refuses; within a float's tail of what is left fits (FIT_TOLERANCE).
|
|
703
|
+
const fits = (tokens) => cost(tokens) <= left + FIT_TOLERANCE;
|
|
704
|
+
if (!fits(least))
|
|
705
|
+
return undefined;
|
|
706
|
+
if (fits(asked))
|
|
707
|
+
return asked;
|
|
708
|
+
let [low, high] = [least, asked];
|
|
709
|
+
while (high - low > 1) {
|
|
710
|
+
const mid = Math.floor((low + high) / 2);
|
|
711
|
+
if (fits(mid))
|
|
712
|
+
low = mid;
|
|
713
|
+
else
|
|
714
|
+
high = mid;
|
|
715
|
+
}
|
|
716
|
+
return low;
|
|
717
|
+
}
|
|
718
|
+
/** The least output a pi request may be limited to and still answer: the answer's 1,024 tokens, and when it thinks,
|
|
719
|
+
* the least budget on an API whose thinking takes one (squeezed to it), else its thinking level's budget, since its
|
|
720
|
+
* reasoning then shares the limit. */
|
|
721
|
+
export function leastOutput(model, thinking, budgetOf) {
|
|
722
|
+
if (!model.reasoning || !thinking || thinking === "off")
|
|
723
|
+
return ANSWER_TOKENS_LEAST;
|
|
724
|
+
return ANSWER_TOKENS_LEAST + (BUDGET_APIS.has(model.api) ? THINKING_BUDGET_LEAST : budgetOf(thinking));
|
|
725
|
+
}
|
|
726
|
+
/** A run on another harness: before each request, what the run has spent, plus the worst case of each request still in
|
|
727
|
+
* flight (at the output limit it was admitted with), must leave room for this request at its least output (1,024 tokens,
|
|
728
|
+
* or what its body says it needs to think and answer; what it asks for when that is fewer), else the request is refused
|
|
729
|
+
* with spend_cap_reached. Admitted, it is limited to the most output what is left buys (`outputTokensMax`, at most what
|
|
730
|
+
* it asks for and its model's ceiling), which the model proxy writes into its body: what it is held at is then what the
|
|
731
|
+
* provider can bill for it. A request's worst case is at the run model's
|
|
732
|
+
* price, as on pi (a request on a cheaper model is held at that price too, which only refuses sooner). What cannot be
|
|
733
|
+
* kept within a cap is refused under one: a spend that is unknown (a request a crash cut), an input that could not be
|
|
734
|
+
* measured, a model serve has no price for (`listed: false`, or none at all), and a model whose output is priced and
|
|
735
|
+
* that has no output ceiling. With no cap, nothing is refused. */
|
|
736
|
+
export async function capBefore(cap, model, { listed = true } = {}) {
|
|
737
|
+
if (cap === undefined)
|
|
738
|
+
return undefined;
|
|
739
|
+
if (model === undefined || !listed)
|
|
740
|
+
return { beforeRequest: () => ({ refuse: noPrice(cap) }) };
|
|
741
|
+
const output = outputBound(model);
|
|
742
|
+
if (output === undefined)
|
|
743
|
+
return { beforeRequest: () => ({ refuse: noCeiling(cap) }) };
|
|
744
|
+
const price = worstOf((await import("@earendil-works/pi-ai")).calculateCost, model);
|
|
745
|
+
const name = nameOf(model);
|
|
746
|
+
const held = (request) => price(request.inputTokensMax, request.outputTokensMax ?? output);
|
|
747
|
+
return {
|
|
748
|
+
beforeRequest({ spentUsd, inFlight, inputTokensMax, outputTokensAsked, outputTokensLeast }) {
|
|
749
|
+
if (spentUsd === null)
|
|
750
|
+
return { refuse: unknownSpend(cap) };
|
|
751
|
+
const inputs = [inputTokensMax, ...inFlight.map((request) => request.inputTokensMax)];
|
|
752
|
+
if (inputs.some((input) => typeof input !== "number" || !Number.isFinite(input)))
|
|
753
|
+
return { refuse: unmeasured(cap) };
|
|
754
|
+
// Its requests in flight at the limit each was admitted with, and its paid calls under way at what they are held at.
|
|
755
|
+
const holding = inFlight.reduce((sum, request) => sum + held(request), paidHolds());
|
|
756
|
+
const left = cap - spentUsd - holding;
|
|
757
|
+
const cost = (tokens) => price(inputTokensMax, tokens);
|
|
758
|
+
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input to fit.
|
|
759
|
+
if (output === 0)
|
|
760
|
+
return cost(0) <= left + FIT_TOLERANCE ? undefined : { refuse: capRefusal(cap, spentUsd, holding, name, cost(0)), spentUsd: spentUsd + holding, needsUsd: cost(0) };
|
|
761
|
+
const asked = Math.min(outputTokensAsked ?? output, output);
|
|
762
|
+
const least = Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked);
|
|
763
|
+
const most = mostOutput(cost, least, asked, left);
|
|
764
|
+
return most === undefined ? { refuse: capRefusal(cap, spentUsd, holding, name, cost(least)), spentUsd: spentUsd + holding, needsUsd: cost(least) } : { outputTokensMax: most };
|
|
765
|
+
},
|
|
766
|
+
worstOf: (request) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) ? held(request) : undefined),
|
|
767
|
+
stoppedOf: (request, streamed) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) && Number.isFinite(streamed) && streamed >= 0
|
|
768
|
+
? stoppedPriceOf((tokens) => price(request.inputTokensMax, tokens), request.outputTokensMax ?? output)(streamed) : undefined),
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
/** A request's input bound (inputBound of its context, plus `overhead(model, context)`, what its provider adds
|
|
772
|
+
* server-side) and the most fee it can run up: a tool's own request adds what its hosted tool may read
|
|
773
|
+
* (hosted-search.ts), and its most fee. Undefined when its input cannot be measured. */
|
|
774
|
+
export function requestParts(overhead = piOverhead) {
|
|
775
|
+
return (model, context) => {
|
|
776
|
+
const added = overhead(model, context);
|
|
777
|
+
if (added === undefined)
|
|
778
|
+
return undefined;
|
|
779
|
+
const side = sideRequests.get(context);
|
|
780
|
+
return { input: inputBound(JSON.stringify(context), added + (side?.extraInputTokens ?? 0)), feeUsd: side?.maxFeeUsd ?? 0 };
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
/** `models`, each request limited to the output tokens what is left of `cap` after `spent` USD (and what requests in flight
|
|
784
|
+
* hold) can buy, at most what it asks for, thinking included (CLAMP on its marks when that is less), and refused when that
|
|
785
|
+
* cannot buy its least (`leastOutput`: 1,024 tokens for the answer, and its thinking's least), saying so in plain words;
|
|
786
|
+
* and, under the cap,
|
|
787
|
+
* each request to a model in `unpriced` (one serve has no price for) or whose output is priced and that has no output
|
|
788
|
+
* ceiling, each whose input cannot be bounded, and every request once what the run has spent is unknown: `spent` null
|
|
789
|
+
* (spentIn), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
|
|
790
|
+
* `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. Each
|
|
791
|
+
* request sent carries its worst case (HELD_USD) to the marks below, and one stopped before its end counts at it.
|
|
792
|
+
* `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry.
|
|
793
|
+
* `joined`: the run is on another harness, whose spend is the run's one total, and these are the run's own requests
|
|
794
|
+
* beside the harness's (a learned workflow's, a hosted search's). Each is judged against that total as the harness
|
|
795
|
+
* sets it when its run opens (RunSpend.now: its booked requests, its paid tools' charges and its requests in flight,
|
|
796
|
+
* with sideSpend), unknown until then; held where the harness's check sees it (paidHolds); and its cost added to
|
|
797
|
+
* sideSpend, which starts at `spent` (what these cost in earlier processes: spentIn's `sides`). */
|
|
798
|
+
export async function capModels(models, cap, spent, { unpriced = new Set(), overhead = piOverhead, refused: markRefused, joined = false } = {}) {
|
|
799
|
+
const [{ calculateCost, createAssistantMessageEventStream }, simple] = await Promise.all([import("@earendil-works/pi-ai"), import("@earendil-works/pi-ai/api/simple-options")]);
|
|
800
|
+
const partsOf = requestParts(overhead);
|
|
801
|
+
let held = 0;
|
|
802
|
+
if (joined)
|
|
803
|
+
sidesSpent = spent;
|
|
804
|
+
/** What the run has spent, as this request's check reads it: on another harness the run's one total (`joined`). */
|
|
805
|
+
const spentNow = () => (joined ? (runSpend?.now?.() ?? null) : spent);
|
|
806
|
+
// The run's spend as a paid tool's check reads it (installed below, useSpend): the requests in flight held at their
|
|
807
|
+
// worst case apart from it (it adds the paid holds itself), and its charge joins the spend.
|
|
808
|
+
const own = { cap, spent: () => spent, held: () => held, add: (usd) => void (spent = spent !== null && typeof usd === "number" && Number.isFinite(usd) ? spent + usd : null) };
|
|
809
|
+
const judge = (model, context, options, simpleCall, turn) => {
|
|
810
|
+
if (unpriced.has(model.id))
|
|
811
|
+
return { why: noPrice(cap) };
|
|
812
|
+
const ceiling = outputBound(model);
|
|
813
|
+
if (ceiling === undefined)
|
|
814
|
+
return { why: noCeiling(cap) };
|
|
815
|
+
const spentUsd = spentNow();
|
|
816
|
+
if (spentUsd === null)
|
|
817
|
+
return { why: unknownSpend(cap) };
|
|
818
|
+
// A paid call the cap just refused for room: the turn's next request, the one after its result, is refused in its
|
|
819
|
+
// words, and the run pauses there. A request after a message of the person's instead (a stop came first, and the
|
|
820
|
+
// 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
|
|
821
|
+
// own requests (stream, streamSimple) take it: a side request through the run's models (completeSimple: a
|
|
822
|
+
// compaction's summary, native web_search's own, request-start.ts) is judged as any other and leaves it for them.
|
|
823
|
+
const paid = turn ? takePaidRefusal(own) : undefined;
|
|
824
|
+
if (paid && context.messages.at(-1)?.role === "toolResult")
|
|
825
|
+
return { why: `${CAP_REFUSAL_CODE}${paid.words}`, figures: paid.figures };
|
|
826
|
+
const parts = partsOf(model, context);
|
|
827
|
+
if (parts === undefined)
|
|
828
|
+
return { why: unmeasured(cap) };
|
|
829
|
+
const price = worstOf(calculateCost, model);
|
|
830
|
+
const cost = (tokens) => price(parts.input, tokens) + parts.feeUsd;
|
|
831
|
+
// What the run holds beside what it spent, as a paid call's check counts it: each request in flight at its figure, and
|
|
832
|
+
// each paid call under way at what it is held at.
|
|
833
|
+
const holding = held + paidHolds();
|
|
834
|
+
const left = cap - spentUsd - holding;
|
|
835
|
+
const name = nameOf(model);
|
|
836
|
+
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input and fee to fit.
|
|
837
|
+
if (ceiling === 0)
|
|
838
|
+
return cost(0) <= left + FIT_TOLERANCE ? { worst: cost(0), stopped: () => cost(0) } : { why: capRefusal(cap, spentUsd, holding, name, cost(0)), figures: { spentUsd: spentUsd + holding, needsUsd: cost(0) } };
|
|
839
|
+
// What the request would send as it stands, thinking included: pi-ai clamps its maxTokens (or the model's) to what its
|
|
840
|
+
// context leaves, and on an API whose thinking takes a budget adds the budget to it.
|
|
841
|
+
const transcript = context;
|
|
842
|
+
const thinking = simpleCall && model.reasoning && options?.reasoning ? options.reasoning : undefined;
|
|
843
|
+
// Adaptive thinking (pi-ai's current Claude models on Anthropic's API) takes no budget: pi-ai sends the request's
|
|
844
|
+
// maxTokens as is, and the model thinks within them as it sees fit: at any level, none included, on a model with
|
|
845
|
+
// mid-conversation effort, else when given a level.
|
|
846
|
+
const compat = model.api === "anthropic-messages" && model.reasoning ? model.compat : undefined;
|
|
847
|
+
const adaptive = compat?.supportsMidConvoEffort === true || (compat?.forceAdaptiveThinking === true && thinking !== undefined);
|
|
848
|
+
const budgeted = thinking !== undefined && BUDGET_APIS.has(model.api) && !adaptive;
|
|
849
|
+
const base = simple.clampMaxTokensToContext(model, transcript, options?.maxTokens ?? ceilingTokens(model));
|
|
850
|
+
const asked = Math.min(ceiling, budgeted ? simple.clampMaxTokensToContext(model, transcript, simple.adjustMaxTokensForThinking(base, ceilingTokens(model), thinking, options?.thinkingBudgets).maxTokens) : base);
|
|
851
|
+
const least = Math.min(leastOutput(model, thinking, (level) => simple.thinkingBudgetForLevel(level, options?.thinkingBudgets)), asked);
|
|
852
|
+
const most = mostOutput(cost, least, asked, left);
|
|
853
|
+
if (most === undefined)
|
|
854
|
+
return { why: capRefusal(cap, spentUsd, holding, name, cost(least)), figures: { spentUsd: spentUsd + holding, needsUsd: cost(least) } };
|
|
855
|
+
// The reasoning a stop leaves unseen: a model's reasoning streams as a summary or not at all (the Responses API; Claude
|
|
856
|
+
// 4-class thinking), so a request that reasons counts its level's budget (the budget it was sent with, on a budget
|
|
857
|
+
// API), or its whole limit when it gives no level and its API reasons by default; none on a budget API with thinking
|
|
858
|
+
// off, or on a model that does not reason. Adaptive thinking is bounded only by the limit, so it counts the limit
|
|
859
|
+
// less the answer's 1,024 tokens. An estimate, as levels are not limits the provider keeps: within the hold.
|
|
860
|
+
const hiddenOf = (limit) => {
|
|
861
|
+
if (adaptive)
|
|
862
|
+
return Math.max(0, limit - ANSWER_TOKENS_LEAST);
|
|
863
|
+
if (!model.reasoning || thinking === "off")
|
|
864
|
+
return 0;
|
|
865
|
+
if (thinking === undefined)
|
|
866
|
+
return BUDGET_APIS.has(model.api) ? 0 : limit;
|
|
867
|
+
const budget = simple.thinkingBudgetForLevel(thinking, options?.thinkingBudgets);
|
|
868
|
+
return budgeted ? Math.max(0, Math.min(budget, limit - ANSWER_TOKENS_LEAST)) : budget;
|
|
869
|
+
};
|
|
870
|
+
// Stopped before its end, at most the output it was sent with: what it streamed, the part of its reasoning budget that
|
|
871
|
+
// did not stream (max(0, budget - the reasoning streamed), so thinking that streamed is not counted twice), and the
|
|
872
|
+
// allowance, within its worst case.
|
|
873
|
+
const stoppedAt = (limit) => (message) => stoppedFigure(cost, limit, cost(limit), streamedBytes(message) + Math.max(0, hiddenOf(limit) - reasoningBytes(message)));
|
|
874
|
+
if (most === asked)
|
|
875
|
+
return { worst: cost(asked), stopped: stoppedAt(asked) };
|
|
876
|
+
// Limited: sent with `most` tokens at most, thinking included. On a budget API the budget is squeezed first, keeping
|
|
877
|
+
// the answer's 1,024, and maxTokens is what is left of `most` beside it, so pi-ai's sum is `most`.
|
|
878
|
+
const clamp = { tokens: most, leftUsd: Math.round(left * 1e6) / 1e6, capUsd: cap };
|
|
879
|
+
if (!budgeted)
|
|
880
|
+
return { worst: cost(most), stopped: stoppedAt(most), options: { ...options, maxTokens: most, [CLAMP]: clamp } };
|
|
881
|
+
const level = simple.clampReasoning(thinking);
|
|
882
|
+
const budget = Math.min(simple.thinkingBudgetForLevel(thinking, options?.thinkingBudgets), most - ANSWER_TOKENS_LEAST);
|
|
883
|
+
return { worst: cost(most), stopped: stoppedAt(most), options: { ...options, maxTokens: most - budget, thinkingBudgets: { ...options?.thinkingBudgets, [level]: budget }, [CLAMP]: clamp } };
|
|
884
|
+
};
|
|
885
|
+
const refusal = (model, why) => ({
|
|
886
|
+
role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(),
|
|
887
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
888
|
+
// "out of budget" is final to pi-ai's retry policy, whatever digits the amounts hold.
|
|
889
|
+
errorMessage: why,
|
|
890
|
+
});
|
|
891
|
+
/** Adds what `answer` cost to what the run has spent once it settles. One stopped before its end counts at `stopped`
|
|
892
|
+
* of what it streamed (stoppedFigure, at most `worst`), unless an attempt before the stop was lost: then at `worst`, as
|
|
893
|
+
* its lost mark reads in a later process; one that ended on an error after its response began
|
|
894
|
+
* (markResponseBegan: its usage is what had streamed, not what the provider can have billed), or that failed with no
|
|
895
|
+
* answer, at `worst`, what the cap held for it; each as spentIn reads its end mark. Without a figure (a deferred
|
|
896
|
+
* response) it is unknown, as is a cost that is not a number, from then on. */
|
|
897
|
+
const count = (answer, worst, stopped, attempts) => {
|
|
898
|
+
const plus = (sum, cost) => (sum !== null && typeof cost === "number" && Number.isFinite(cost) ? sum + cost : null);
|
|
899
|
+
const add = (cost) => void (joined ? (sidesSpent = plus(sidesSpent, cost)) : (spent = plus(spent, cost)));
|
|
900
|
+
// One rule (bookRequest), from how the request ended (piEnded) as its marks read it too.
|
|
901
|
+
const at = (message) => message.stopReason === "aborted" ? (stopped && !anyAttemptLost(attempts) ? stopped(message) : worst)
|
|
902
|
+
: bookRequest(piEnded(message, responseBegan.has(message), attempts), worst === undefined ? {} : { hold: worst }).usd;
|
|
903
|
+
return answer.then((message) => add(at(message)), () => add(worst));
|
|
904
|
+
};
|
|
905
|
+
/** Sends a request judged to fit at `worst`, holding that until `answer` settles: here, or on another harness where
|
|
906
|
+
* its check sees it (`joined`: paidHolds). */
|
|
907
|
+
const admit = (worst, stopped, answer, attempts) => {
|
|
908
|
+
const hold = { usd: worst };
|
|
909
|
+
if (joined)
|
|
910
|
+
paidOpen.add(hold);
|
|
911
|
+
else
|
|
912
|
+
held += worst;
|
|
913
|
+
const release = () => void (joined ? paidOpen.delete(hold) : (held -= worst));
|
|
914
|
+
let answered;
|
|
915
|
+
try {
|
|
916
|
+
answered = answer();
|
|
917
|
+
}
|
|
918
|
+
catch (error) {
|
|
919
|
+
release();
|
|
920
|
+
throw error;
|
|
921
|
+
}
|
|
922
|
+
void count(answered, worst, stopped, attempts).finally(release);
|
|
923
|
+
return answered;
|
|
924
|
+
};
|
|
925
|
+
// A paid tool's check reads the spend, and the requests in flight held at their worst case apart from it (it adds the
|
|
926
|
+
// paid holds itself), and its charge joins the spend. On another harness, the harness sets it as its run opens
|
|
927
|
+
// (harness-app.ts).
|
|
928
|
+
if (!joined)
|
|
929
|
+
useSpend(own);
|
|
930
|
+
/** `options` with the request's worst case, and its figure if it is stopped, for its marks. */
|
|
931
|
+
/** `options` with the request's worst case, its figure if it is stopped, and its attempts' record, for its marks: on an
|
|
932
|
+
* API the cap can watch, a fetch that records each attempt (`attempts`, undefined on one it cannot). */
|
|
933
|
+
const carrying = (options, { worst, stopped }, attempts) => ({
|
|
934
|
+
...options, [HELD_USD]: worst, [STOPPED_USD]: stopped,
|
|
935
|
+
// null on an API the cap cannot watch: its marks read a failure before any event as lost.
|
|
936
|
+
...(attempts ? { [ATTEMPTS]: attempts, fetch: recordingFetch(attempts, options?.fetch, options?.signal) } : { [ATTEMPTS]: null }),
|
|
937
|
+
});
|
|
938
|
+
const attemptsFor = (model) => (unwatched(model.api) ? undefined : []);
|
|
939
|
+
const stream = (send, simpleCall) => (model, context, options) => {
|
|
940
|
+
const judged = judge(model, context, options, simpleCall, true);
|
|
941
|
+
if ("worst" in judged) {
|
|
942
|
+
let events;
|
|
943
|
+
const attempts = attemptsFor(model);
|
|
944
|
+
admit(judged.worst, judged.stopped, () => (events = send(model, context, carrying(judged.options ?? options, judged, attempts))).result(), attempts);
|
|
945
|
+
return events;
|
|
946
|
+
}
|
|
947
|
+
const refused = createAssistantMessageEventStream();
|
|
948
|
+
const message = refusal(model, judged.why);
|
|
949
|
+
// Its own start mark first, so pi's error entry for it answers that mark, never an earlier request a stop or a crash
|
|
950
|
+
// cut. A mark that cannot be written still ends the request: spentIn leaves refusals out either way.
|
|
951
|
+
void Promise.resolve()
|
|
952
|
+
.then(() => markRefused?.(judged.figures))
|
|
953
|
+
.catch(() => undefined)
|
|
954
|
+
.then(() => {
|
|
955
|
+
refused.push({ type: "error", reason: "error", error: message });
|
|
956
|
+
refused.end(message);
|
|
957
|
+
});
|
|
958
|
+
return refused;
|
|
959
|
+
};
|
|
960
|
+
const complete = (send, simpleCall) => (model, context, options) => {
|
|
961
|
+
const judged = judge(model, context, options, simpleCall, false);
|
|
962
|
+
if (!("worst" in judged))
|
|
963
|
+
return Promise.resolve(refusal(model, judged.why));
|
|
964
|
+
const attempts = attemptsFor(model);
|
|
965
|
+
return admit(judged.worst, judged.stopped, () => send(model, context, carrying(judged.options ?? options, judged, attempts)), attempts);
|
|
966
|
+
};
|
|
967
|
+
const guarded = {
|
|
968
|
+
stream: stream(models.stream.bind(models), false),
|
|
969
|
+
streamSimple: stream(models.streamSimple.bind(models), true),
|
|
970
|
+
complete: complete(models.complete.bind(models), false),
|
|
971
|
+
completeSimple: complete(models.completeSimple.bind(models), true),
|
|
972
|
+
// A deferred response was admitted when it was sent; what it cost is counted when it is fetched.
|
|
973
|
+
streamDeferred: (...args) => {
|
|
974
|
+
const events = models.streamDeferred(...args);
|
|
975
|
+
void count(events.result());
|
|
976
|
+
return events;
|
|
977
|
+
},
|
|
978
|
+
fetchDeferred: (...args) => {
|
|
979
|
+
const answer = models.fetchDeferred(...args);
|
|
980
|
+
void count(answer);
|
|
981
|
+
return answer;
|
|
982
|
+
},
|
|
983
|
+
};
|
|
984
|
+
return new Proxy(models, {
|
|
985
|
+
get: (target, key) => {
|
|
986
|
+
if (key in guarded)
|
|
987
|
+
return guarded[key];
|
|
988
|
+
const value = Reflect.get(target, key, target);
|
|
989
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
990
|
+
},
|
|
991
|
+
});
|
|
992
|
+
}
|