@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.31
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 +238 -0
- package/README.md +739 -116
- package/dist/adapters.d.ts +35 -6
- package/dist/adapters.js +152 -26
- package/dist/agents.d.ts +18 -7
- package/dist/agents.js +19 -10
- package/dist/app.js +101 -26
- package/dist/background.d.ts +29 -0
- package/dist/background.js +397 -0
- package/dist/box-egress-vm.d.ts +125 -0
- package/dist/box-egress-vm.js +350 -0
- package/dist/box-egress.d.ts +99 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +1 -1
- package/dist/box-image.js +9 -7
- package/dist/box-relay-vm.d.ts +84 -0
- package/dist/box-relay-vm.js +410 -0
- package/dist/box-relay.d.ts +8 -5
- package/dist/box-relay.js +14 -9
- package/dist/boxes.d.ts +28 -5
- package/dist/boxes.js +44 -18
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +130 -21
- package/dist/cap.js +339 -67
- package/dist/cli.js +30 -4
- package/dist/coding-tools.d.ts +7 -3
- package/dist/coding-tools.js +16 -10
- package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
- package/dist/console/assets/index-CnJBf7Lc.js +486 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-rows.d.ts +11 -3
- package/dist/decision-rows.js +18 -11
- package/dist/decisions.d.ts +3 -3
- package/dist/decisions.js +4 -3
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +5 -2
- package/dist/files.d.ts +9 -1
- package/dist/files.js +10 -2
- package/dist/grade.d.ts +11 -11
- package/dist/grade.js +43 -55
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +7 -5
- package/dist/graph-view.js +10 -3
- package/dist/harness-app.d.ts +4 -2
- package/dist/harness-app.js +110 -19
- 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 +4 -1
- package/dist/harness.js +5 -2
- package/dist/host-check.d.ts +12 -0
- package/dist/host-check.js +34 -0
- package/dist/host-tools.d.ts +12 -2
- package/dist/host-tools.js +26 -12
- package/dist/host.js +6 -2
- package/dist/hosted-search.js +5 -1
- package/dist/import.d.ts +2 -2
- package/dist/import.js +4 -3
- package/dist/key-check.d.ts +3 -2
- package/dist/key-check.js +7 -3
- package/dist/key-refusal.js +8 -4
- package/dist/key-words.d.ts +37 -0
- package/dist/key-words.js +40 -0
- package/dist/learn/check.d.ts +10 -1
- package/dist/learn/check.js +19 -1
- package/dist/learn/grade.d.ts +6 -2
- package/dist/learn/grade.js +28 -14
- package/dist/learn/index.d.ts +3 -3
- package/dist/learn/index.js +3 -3
- package/dist/learn/notes.js +2 -1
- package/dist/learn/reflect.d.ts +2 -2
- package/dist/learn/reflect.js +53 -5
- package/dist/learn/secrets.js +28 -8
- package/dist/learn/skills.d.ts +19 -4
- package/dist/learn/skills.js +95 -6
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +30 -1
- package/dist/learning-routes.js +173 -19
- package/dist/learning-run.d.ts +8 -6
- package/dist/learning-run.js +70 -27
- package/dist/learning-words.d.ts +12 -5
- package/dist/learning-words.js +34 -13
- package/dist/learning.d.ts +52 -3
- package/dist/learning.js +204 -4
- package/dist/mcp-gateway.d.ts +96 -0
- package/dist/mcp-gateway.js +408 -0
- package/dist/mcp-meta.d.ts +17 -0
- package/dist/mcp-meta.js +38 -0
- package/dist/mcp-servers.d.ts +33 -9
- package/dist/mcp-servers.js +58 -10
- package/dist/mcp.js +5 -5
- package/dist/model.d.ts +13 -11
- package/dist/model.js +11 -10
- package/dist/openapi/agentrun-v2.openapi.json +1 -0
- package/dist/openapi.js +407 -54
- package/dist/page.d.ts +2 -0
- package/dist/page.js +3 -0
- package/dist/paid-calls.d.ts +5 -1
- package/dist/paid-calls.js +1 -1
- package/dist/pause.d.ts +2 -0
- package/dist/place.d.ts +29 -5
- package/dist/place.js +51 -11
- package/dist/print.d.ts +7 -0
- package/dist/print.js +13 -0
- package/dist/propose.d.ts +2 -0
- package/dist/propose.js +38 -8
- package/dist/request-start.d.ts +12 -4
- package/dist/request-start.js +139 -15
- package/dist/run-box.d.ts +56 -4
- package/dist/run-box.js +183 -23
- package/dist/runnable.d.ts +13 -3
- package/dist/runnable.js +63 -6
- package/dist/runs.d.ts +266 -37
- package/dist/runs.js +884 -90
- package/dist/secrets.d.ts +27 -0
- package/dist/secrets.js +38 -2
- package/dist/server.d.ts +141 -36
- package/dist/server.js +562 -118
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +16 -4
- package/dist/skills.js +35 -7
- package/dist/stats.d.ts +7 -2
- package/dist/stats.js +28 -7
- package/dist/tool-gate.d.ts +281 -0
- package/dist/tool-gate.js +585 -0
- package/dist/tool-keys.d.ts +48 -11
- package/dist/tool-keys.js +46 -8
- package/dist/tool-plane.d.ts +116 -27
- package/dist/tool-plane.js +232 -50
- package/dist/tools.d.ts +69 -14
- package/dist/tools.js +148 -26
- 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 +3 -2
- package/dist/turn-end.js +3 -2
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/validate.d.ts +2 -0
- package/dist/validate.js +11 -2
- package/dist/web-fetch.js +3 -3
- package/dist/webhooks.d.ts +11 -4
- package/dist/webhooks.js +17 -1
- package/launcher/agentrun-serve +1 -1
- package/package.json +16 -14
- package/dist/console/assets/index-BN7oVcO4.js +0 -445
- package/dist/console/assets/index-By-jkqki.css +0 -1
package/dist/cap.js
CHANGED
|
@@ -35,11 +35,19 @@
|
|
|
35
35
|
import { DatabaseSync } from "node:sqlite";
|
|
36
36
|
import { existsSync } from "node:fs";
|
|
37
37
|
import { providerInputOverhead } from "@parcha/agentrun-kernel/host";
|
|
38
|
+
import { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "@parcha/agentrun-kernel";
|
|
38
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";
|
|
39
40
|
/** A run's cap in USD, passed to its process. */
|
|
40
41
|
export const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
|
|
41
42
|
/** How a request the cap refused begins its error, which the server ends the run with. */
|
|
42
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;
|
|
43
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
|
|
44
52
|
* symbol, so no provider ever sends it. */
|
|
45
53
|
export const HELD_USD = Symbol.for("agentrun.serve.held_usd");
|
|
@@ -93,12 +101,97 @@ export function streamedBytes(message) {
|
|
|
93
101
|
}
|
|
94
102
|
return bytes;
|
|
95
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
|
+
}
|
|
96
113
|
/** What a request stopped before its end counts at: its input and `streamed` tokens plus STOP_ALLOWANCE_TOKENS of output,
|
|
97
114
|
* at most the output it was sent with (`limit`), at `cost`'s price; never more than `worst`, what it was held at. */
|
|
98
|
-
export const stoppedFigure = (cost, limit, worst, streamed) =>
|
|
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
|
+
}
|
|
99
185
|
/** How pi's error for a request whose start mark could not be written begins (request-start.ts builds it from this): the
|
|
100
186
|
* request never left, so the entry answers none, and spentIn leaves it out by this. */
|
|
101
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
|
+
};
|
|
102
195
|
/** The input a request carrying claude-agent's native web search may read in beyond its body, added to its input bound
|
|
103
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
|
|
104
197
|
* search's results are billed as input, about 25,000 tokens a search as a working estimate. */
|
|
@@ -199,8 +292,10 @@ function openFigures(entries) {
|
|
|
199
292
|
* end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the figure its start mark
|
|
200
293
|
* holds (openFigures), each the worst case the cap held for it; without that figure either stays cut, at an unknown
|
|
201
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
|
|
202
|
-
* this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0.
|
|
203
|
-
|
|
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 } = {}) {
|
|
204
299
|
if (!existsSync(storeFile))
|
|
205
300
|
return 0;
|
|
206
301
|
const db = new DatabaseSync(storeFile, { readOnly: true });
|
|
@@ -210,8 +305,11 @@ export function spentIn(storeFile) {
|
|
|
210
305
|
let marked = false;
|
|
211
306
|
const rows = [];
|
|
212
307
|
try {
|
|
213
|
-
for (const row of db.prepare("SELECT record FROM entries ORDER BY rowid").iterate())
|
|
214
|
-
|
|
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
|
+
}
|
|
215
313
|
}
|
|
216
314
|
finally {
|
|
217
315
|
db.close();
|
|
@@ -232,29 +330,47 @@ export function spentIn(storeFile) {
|
|
|
232
330
|
// no request's, and no end mark takes one.
|
|
233
331
|
const stopOf = (entry) => entry.model?.[0]?.stopReason;
|
|
234
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 = [];
|
|
235
336
|
let refusals = 0;
|
|
236
337
|
rows.forEach((entry, at) => {
|
|
237
338
|
if (entry.kind === REQUEST_REFUSED)
|
|
238
339
|
refusals += 1;
|
|
239
|
-
else if (entry.kind === "pi.assistant" && stopOf(entry) === "error" && !refusedHere(entry) && !notSentHere(entry)) {
|
|
340
|
+
else if (entry.kind === "pi.assistant" && stopOf(entry) === "error" && !refusedHere(entry) && !notSentHere(entry) && !endUnrecorded(entry)) {
|
|
240
341
|
if (refusals > 0)
|
|
241
342
|
refusals -= 1;
|
|
242
343
|
else
|
|
243
344
|
errorsAt.push(at);
|
|
244
345
|
}
|
|
346
|
+
else if (entry.kind === "pi.assistant" && stopOf(entry) !== "error" && stopOf(entry) !== "aborted")
|
|
347
|
+
answersAt.push(at);
|
|
245
348
|
});
|
|
246
349
|
const taken = new Set();
|
|
247
350
|
const fieldsOf = (entry) => (entry.data ?? {});
|
|
248
351
|
const generationStart = (entry) => entry.kind === REQUEST_STARTED && typeof fieldsOf(entry).request !== "string" && fieldsOf(entry)[CAP_REFUSED_FIELD] !== true;
|
|
249
352
|
// Each such end mark, with the earliest start holding its figure (-1 for none: any error entry then).
|
|
250
|
-
const
|
|
353
|
+
const endsOf = (field) => rows.flatMap((entry, at) => entry.kind === REQUEST_ENDED && fieldsOf(entry)[field] === true
|
|
251
354
|
? [{ at, from: rows.findIndex((start, i) => i < at && generationStart(start) && figureOf(fieldsOf(start)[HELD_FIELD]) === figureOf(fieldsOf(entry)[HELD_FIELD])) }]
|
|
252
355
|
: []);
|
|
253
|
-
|
|
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)) {
|
|
254
370
|
let nearest = -1;
|
|
255
|
-
for (const
|
|
256
|
-
if (
|
|
257
|
-
nearest =
|
|
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;
|
|
258
374
|
if (nearest >= 0)
|
|
259
375
|
taken.add(nearest);
|
|
260
376
|
}
|
|
@@ -280,13 +396,17 @@ export function spentIn(storeFile) {
|
|
|
280
396
|
// marks instead, at the figure its end holds, or cut. Before the first mark (an older run) it stays unknown.
|
|
281
397
|
if (marked && entry.kind === "pi.assistant" && entry.model?.[0]?.stopReason === "aborted")
|
|
282
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;
|
|
283
402
|
if (taken.has(at))
|
|
284
403
|
continue;
|
|
285
404
|
entries.push(bound === undefined ? entry : { ...entry, data: { ...data, usd: bound } });
|
|
286
405
|
read.push(entry);
|
|
287
406
|
const held = data[HELD_FIELD];
|
|
288
407
|
// A summary that ended on an error after its response began (its cost mark says `failed`) counts at its hold.
|
|
289
|
-
|
|
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)
|
|
290
410
|
entries[entries.length - 1] = { ...entry, data: { ...data, usd: held } };
|
|
291
411
|
if (entry.kind !== REQUEST_ENDED || data.unsent === true || typeof held !== "number" || !Number.isFinite(held))
|
|
292
412
|
continue;
|
|
@@ -321,30 +441,49 @@ export function spentIn(storeFile) {
|
|
|
321
441
|
return null;
|
|
322
442
|
return entries.reduce((sum, entry) => sum + costOf(entry), 0);
|
|
323
443
|
}
|
|
324
|
-
/** /usage's meters for a run that ended, from its store: `tools`, each TOOL_COST's `usd`, unknown (null) when one is,
|
|
325
|
-
* or when a call was cut (marked, never settled: what it charged no one knows); and `tokens`, the rest of its root
|
|
326
|
-
* conversation as its settled timeline prices it. A mark is never a charge here (the cap's alone). Never for a live
|
|
327
|
-
* run: its process holds the store exclusively. */
|
|
328
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) {
|
|
329
452
|
if (!existsSync(storeFile))
|
|
330
|
-
return { tools: 0, tokens: null };
|
|
453
|
+
return { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
|
|
331
454
|
const db = new DatabaseSync(storeFile, { readOnly: true, timeout: 2_000 });
|
|
332
455
|
try {
|
|
333
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)) }));
|
|
334
457
|
const root = rows.reduce((min, row) => Math.min(min, row.conversation), Infinity);
|
|
335
458
|
const marks = new Set();
|
|
336
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 };
|
|
337
465
|
for (const { entry } of rows) {
|
|
338
466
|
const data = (entry.data ?? {});
|
|
339
467
|
if (entry.kind === TOOL_STARTED)
|
|
340
468
|
marks.add(data.call);
|
|
341
469
|
else if (entry.kind === TOOL_COST)
|
|
342
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;
|
|
343
479
|
}
|
|
344
480
|
const tools = marks.size || charges.some((usd) => usd === undefined) ? null : charges.reduce((sum, usd) => sum + usd, 0);
|
|
345
481
|
const rest = rows.filter(({ conversation, entry }) => conversation === root && entry.kind !== TOOL_STARTED && entry.kind !== TOOL_COST).map(({ entry }) => entry);
|
|
346
482
|
const usage = timelineOf(rest, { settled: true }).find((row) => row.kind === "usage");
|
|
347
|
-
|
|
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
|
+
const notMetered = usage?.usage?.not_metered;
|
|
486
|
+
return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0, browser, others: otherTools, known, ...(notMetered ? { notMetered } : {}) };
|
|
348
487
|
}
|
|
349
488
|
finally {
|
|
350
489
|
db.close();
|
|
@@ -382,12 +521,36 @@ export function holdsInFlight() {
|
|
|
382
521
|
}
|
|
383
522
|
let runSpend;
|
|
384
523
|
let paying = Promise.resolve();
|
|
385
|
-
export const useSpend = (spend) =>
|
|
386
|
-
|
|
524
|
+
export const useSpend = (spend) => {
|
|
525
|
+
runSpend = spend;
|
|
526
|
+
// A paid call's refusal is its own spend's (its run's): another spend starts with none.
|
|
527
|
+
paidRoomRefusal = undefined;
|
|
528
|
+
};
|
|
529
|
+
/** 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
|
|
530
|
+
* model requests in flight too (capModels' `joined`). */
|
|
387
531
|
const paidOpen = new Set();
|
|
388
532
|
/** What the paid calls under way are held at, together (0 when none is): the one figure every check of the run's cap
|
|
389
|
-
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall).
|
|
533
|
+
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). On another
|
|
534
|
+
* harness the run's own model requests in flight (a learned workflow's, a hosted search's) are held here too, so the
|
|
535
|
+
* harness's check sees them. */
|
|
390
536
|
export const paidHolds = () => [...paidOpen].reduce((sum, { usd }) => sum + usd, 0);
|
|
537
|
+
/** A paid hold that outlives the paidCall that took it (a browser session's, browser-cost.ts), counted in paidHolds as a
|
|
538
|
+
* call's is until `drop`: its figure is `usd`, which its owner moves as charges use it. */
|
|
539
|
+
export const keepHold = (usd) => {
|
|
540
|
+
const open = { usd, drop: () => void paidOpen.delete(open) };
|
|
541
|
+
paidOpen.add(open);
|
|
542
|
+
return open;
|
|
543
|
+
};
|
|
544
|
+
/** A charge booked outside any paidCall (a browser session's, booked in the commit that bills it) joins what the run's
|
|
545
|
+
* process counts as spent, as a paid call's does; with no cap, nothing counts it. */
|
|
546
|
+
export const addSpend = (usd) => runSpend?.add(usd);
|
|
547
|
+
/** The run's cap, when it has one. */
|
|
548
|
+
export const runCap = () => runSpend?.cap;
|
|
549
|
+
/** On another harness, what the run's own model requests (capModels' `joined`) have cost: those of earlier processes
|
|
550
|
+
* (spentIn's `sides`) and this one's; null once one is unknown. 0 on pi, where the run's one capModels counts them. */
|
|
551
|
+
let sidesSpent = 0;
|
|
552
|
+
/** What sidesSpent says: the harness's check adds it to what its booking says the run spent (harness-app.ts). */
|
|
553
|
+
export const sideSpend = () => sidesSpent;
|
|
391
554
|
/** `call`, a paid tool's (`name`), under the run's cap, by the rule a model request keeps: refused, in words that name
|
|
392
555
|
* its price and the cap and never calling it, unless what the run has spent plus what the call is held at (`hold`: its
|
|
393
556
|
* quote, else an allowance, `basis` saying which) fits the cap, and whenever the spend is unknown; else run, one paid
|
|
@@ -395,6 +558,21 @@ export const paidHolds = () => [...paidOpen].reduce((sum, { usd }) => sum + usd,
|
|
|
395
558
|
* reports (`charge` of its result, undefined for none) joins the spend. A charge it does not say (null), or a call that
|
|
396
559
|
* fails, counts at its held figure, as its mark does from the store (spentIn), since it may have charged that much.
|
|
397
560
|
* With no cap it just runs. */
|
|
561
|
+
/** A paid call this run's cap refused for room (paidCall): its words, after the code, and its figures as a model
|
|
562
|
+
* request's refusal keeps them (what was taken, and the call's hold as what it needs). The model's next request is
|
|
563
|
+
* refused in these words and with these figures (takePaidRefusal), so the turn ends on the refusal, as a refused model
|
|
564
|
+
* request's does, and the run waits on a raise (runs.ts pausedAt), its model never given a turn to route around it. */
|
|
565
|
+
let paidRoomRefusal;
|
|
566
|
+
/** The paid call's refusal the next model request of the run whose spend is `owner` is refused with, once: undefined
|
|
567
|
+
* 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
|
|
568
|
+
* others), never a guard a caller builds apart. */
|
|
569
|
+
export function takePaidRefusal(owner) {
|
|
570
|
+
const refusal = paidRoomRefusal;
|
|
571
|
+
if (!refusal || !owner || refusal.owner !== owner)
|
|
572
|
+
return undefined;
|
|
573
|
+
paidRoomRefusal = undefined;
|
|
574
|
+
return { words: refusal.words, figures: refusal.figures };
|
|
575
|
+
}
|
|
398
576
|
export async function paidCall(name, call, charge, hold) {
|
|
399
577
|
const spend = runSpend;
|
|
400
578
|
if (!spend)
|
|
@@ -402,11 +580,16 @@ export async function paidCall(name, call, charge, hold) {
|
|
|
402
580
|
const turn = paying.then(async () => {
|
|
403
581
|
const read = await spend.spent();
|
|
404
582
|
if (read === null)
|
|
405
|
-
return { refused: `${SPEND_CAP_REACHED}: ${name} was not sent. What the run has spent is unknown, so its cap of
|
|
406
|
-
|
|
583
|
+
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.` };
|
|
584
|
+
// What is held for requests and calls still answering, apart from what was spent, as a model request's refusal says it.
|
|
585
|
+
const holding = (spend.held?.() ?? 0) + paidHolds();
|
|
407
586
|
// Written so that a figure that is not a number refuses.
|
|
408
|
-
if (!(
|
|
409
|
-
|
|
587
|
+
if (!(read + holding + hold.usd <= spend.cap + FIT_TOLERANCE)) {
|
|
588
|
+
// Refused for room: a raise would send it, so the run pauses at the model's next request (takePaidRefusal).
|
|
589
|
+
const refused = paidRefusal(spend.cap, read, holding, name, hold);
|
|
590
|
+
paidRoomRefusal = { owner: spend, words: refused.slice(`${SPEND_CAP_REACHED}: `.length), figures: { spentUsd: read + holding, needsUsd: hold.usd } };
|
|
591
|
+
return { refused };
|
|
592
|
+
}
|
|
410
593
|
// Held from here; settled into the spend in the same step that lets the hold go, so no check between sees neither.
|
|
411
594
|
const open = { usd: hold.usd };
|
|
412
595
|
paidOpen.add(open);
|
|
@@ -451,10 +634,10 @@ export function piOverhead(model, context) {
|
|
|
451
634
|
const parts = (context.messages ?? []).flatMap((message) => (Array.isArray(message.content) ? (message.content) : []));
|
|
452
635
|
return providerInputOverhead(model.api, { tools: (context.tools?.length ?? 0) > 0, toolChoice: "any", images: parts.filter((part) => part?.type === "image").length });
|
|
453
636
|
}
|
|
454
|
-
const unmeasured = (cap) => `${SPEND_CAP_REACHED}:
|
|
455
|
-
const noPrice = (cap) => `${SPEND_CAP_REACHED}: the next model request
|
|
456
|
-
const noCeiling = (cap) => `${SPEND_CAP_REACHED}: the next model request
|
|
457
|
-
const unknownSpend = (cap) => `${SPEND_CAP_REACHED}:
|
|
637
|
+
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.`;
|
|
638
|
+
const noPrice = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no price here, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
|
|
639
|
+
const noCeiling = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no output ceiling here and its output is priced, so what a request may cost has no bound and the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
|
|
640
|
+
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.`;
|
|
458
641
|
/** A request's worst case at `model`'s price: `input` tokens at the dearer of its input and cache-write prices, and
|
|
459
642
|
* `output` tokens at its output price. */
|
|
460
643
|
function worstOf(calculateCost, model) {
|
|
@@ -475,34 +658,58 @@ export function money(usd) {
|
|
|
475
658
|
* which pi-ai's retry (isRetryableAssistantError, which reads only an error's text) takes as final whatever digits the
|
|
476
659
|
* words after it hold. The words after it are the ones a person reads. */
|
|
477
660
|
export const CAP_REFUSAL_CODE = `${SPEND_CAP_REACHED} (out of budget): `;
|
|
661
|
+
/** The words of a refusal for room (CAP_REFUSAL_CODE: what is left of the cap cannot buy the request's least), which a
|
|
662
|
+
* higher cap would send; undefined for any other text, a refusal no cap could fix included (an unknown spend, no price,
|
|
663
|
+
* no output ceiling, an input not measured: the bare `spend_cap_reached: ` code). The one reader of that difference. */
|
|
664
|
+
export const roomRefusal = (text) => (text?.startsWith(CAP_REFUSAL_CODE) ? text.slice(CAP_REFUSAL_CODE.length) : undefined);
|
|
478
665
|
/** A model's name as the words say it: the catalog's, without a vendor's prefix ("Anthropic: Claude Sonnet 5.5" reads
|
|
479
666
|
* "Claude Sonnet 5.5"), else its id. */
|
|
480
667
|
export const nameOf = (model) => (model.name || model.id).replace(/^[^:]{1,40}:\s+(?=\S)/, "");
|
|
481
668
|
/** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
|
|
482
|
-
|
|
669
|
+
// Cents rounded up within the tail the fit check allows (FIT_TOLERANCE), no wider: a total past a cent by more than a
|
|
670
|
+
// float's own tail rounds to the cent above, so the cap a refusal names admits what it refused.
|
|
671
|
+
export const leastMoney = (usd) => `$${(Math.ceil(usd * 100 - FIT_TOLERANCE * 100) / 100).toFixed(2)}`;
|
|
672
|
+
/** The cap to raise to for a request past `cap` that needs `total` in all: a cent at least, and above the cap, never
|
|
673
|
+
* the cap itself, so a raise to it is one PATCH /runs/{id} takes. */
|
|
674
|
+
export const raiseTo = (cap, total) => {
|
|
675
|
+
const cents = Math.ceil(total * 100 - FIT_TOLERANCE * 100);
|
|
676
|
+
return `$${((cents / 100 > cap + CAP_TOLERANCE ? cents : Math.floor((cap + CAP_TOLERANCE) * 100) + 1) / 100).toFixed(2)}`;
|
|
677
|
+
};
|
|
483
678
|
/** The cap's refusal of a request what is left of it cannot buy the least of, in plain words with the numbers: what
|
|
484
679
|
* the run spent (and holds for requests still answering) of its cap, what the request needs at the least, and the cap
|
|
485
680
|
* that would run it (spent, held and that least, rounded up to the cent, so that it is enough). After its code
|
|
486
681
|
* (CAP_REFUSAL_CODE), which keeps it final to pi-ai's retry. */
|
|
487
682
|
function capRefusal(cap, spent, held, name, least) {
|
|
488
|
-
const [need, raise] = [leastMoney(least),
|
|
683
|
+
const [need, raise] = [leastMoney(least), raiseTo(cap, spent + held + least)];
|
|
489
684
|
if (spent === 0 && held === 0)
|
|
490
685
|
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.`;
|
|
491
686
|
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`;
|
|
492
687
|
return `${CAP_REFUSAL_CODE}Not sent: the run has ${owes}, and its next ${name} request needs at least ${need}. Raise the cap to at least ${raise} to run it.`;
|
|
493
688
|
}
|
|
689
|
+
/** The cap's refusal of a paid call (paidCall) what is left of it cannot hold, in one sentence, as capRefusal says a model
|
|
690
|
+
* request's: what the run spent (and holds for requests and calls still answering) of its cap, what the call could cost
|
|
691
|
+
* and why, and the cap that would run it: spent, held and the call's figure, rounded up to the cent, and a cent above the
|
|
692
|
+
* cap at the least, since a figure past the cap by less than a cent still needs more than the cap. Every amount by money,
|
|
693
|
+
* the raise by leastMoney. */
|
|
694
|
+
function paidRefusal(cap, spent, held, name, hold) {
|
|
695
|
+
const holds = held > 0 ? ` and holds ${money(held)} for calls still answering` : "";
|
|
696
|
+
// The model refusal's rule (raiseTo): a cent at least, and above the cap, never the cap itself.
|
|
697
|
+
const raise = raiseTo(cap, spent + held + hold.usd);
|
|
698
|
+
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.`;
|
|
699
|
+
}
|
|
494
700
|
/** The most output tokens from `least` to `asked` whose request costs no more than `left` (`cost`, its price at that
|
|
495
701
|
* many, rising with them); undefined when even `least` costs more. A search, so that a price with tiers is exact. */
|
|
496
702
|
function mostOutput(cost, least, asked, left) {
|
|
497
|
-
// Written so that a cost that is not a number refuses.
|
|
498
|
-
|
|
703
|
+
// Written so that a cost that is not a number refuses; within a float's tail of what is left fits (FIT_TOLERANCE).
|
|
704
|
+
const fits = (tokens) => cost(tokens) <= left + FIT_TOLERANCE;
|
|
705
|
+
if (!fits(least))
|
|
499
706
|
return undefined;
|
|
500
|
-
if (
|
|
707
|
+
if (fits(asked))
|
|
501
708
|
return asked;
|
|
502
709
|
let [low, high] = [least, asked];
|
|
503
710
|
while (high - low > 1) {
|
|
504
711
|
const mid = Math.floor((low + high) / 2);
|
|
505
|
-
if (
|
|
712
|
+
if (fits(mid))
|
|
506
713
|
low = mid;
|
|
507
714
|
else
|
|
508
715
|
high = mid;
|
|
@@ -551,15 +758,15 @@ export async function capBefore(cap, model, { listed = true } = {}) {
|
|
|
551
758
|
const cost = (tokens) => price(inputTokensMax, tokens);
|
|
552
759
|
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input to fit.
|
|
553
760
|
if (output === 0)
|
|
554
|
-
return cost(0) <= left ? undefined : { refuse: capRefusal(cap, spentUsd, holding, name, cost(0)) };
|
|
761
|
+
return cost(0) <= left + FIT_TOLERANCE ? undefined : { refuse: capRefusal(cap, spentUsd, holding, name, cost(0)), spentUsd: spentUsd + holding, needsUsd: cost(0) };
|
|
555
762
|
const asked = Math.min(outputTokensAsked ?? output, output);
|
|
556
763
|
const least = Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked);
|
|
557
764
|
const most = mostOutput(cost, least, asked, left);
|
|
558
|
-
return most === undefined ? { refuse: capRefusal(cap, spentUsd, holding, name, cost(least)) } : { outputTokensMax: most };
|
|
765
|
+
return most === undefined ? { refuse: capRefusal(cap, spentUsd, holding, name, cost(least)), spentUsd: spentUsd + holding, needsUsd: cost(least) } : { outputTokensMax: most };
|
|
559
766
|
},
|
|
560
767
|
worstOf: (request) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) ? held(request) : undefined),
|
|
561
768
|
stoppedOf: (request, streamed) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) && Number.isFinite(streamed) && streamed >= 0
|
|
562
|
-
? price(request.inputTokensMax,
|
|
769
|
+
? stoppedPriceOf((tokens) => price(request.inputTokensMax, tokens), request.outputTokensMax ?? output)(streamed) : undefined),
|
|
563
770
|
};
|
|
564
771
|
}
|
|
565
772
|
/** A request's input bound (inputBound of its context, plus `overhead(model, context)`, what its provider adds
|
|
@@ -583,19 +790,40 @@ export function requestParts(overhead = piOverhead) {
|
|
|
583
790
|
* (spentIn), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
|
|
584
791
|
* `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. Each
|
|
585
792
|
* request sent carries its worst case (HELD_USD) to the marks below, and one stopped before its end counts at it.
|
|
586
|
-
* `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry.
|
|
587
|
-
|
|
793
|
+
* `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry.
|
|
794
|
+
* `joined`: the run is on another harness, whose spend is the run's one total, and these are the run's own requests
|
|
795
|
+
* beside the harness's (a learned workflow's, a hosted search's). Each is judged against that total as the harness
|
|
796
|
+
* sets it when its run opens (RunSpend.now: its booked requests, its paid tools' charges and its requests in flight,
|
|
797
|
+
* with sideSpend), unknown until then; held where the harness's check sees it (paidHolds); and its cost added to
|
|
798
|
+
* sideSpend, which starts at `spent` (what these cost in earlier processes: spentIn's `sides`). */
|
|
799
|
+
export async function capModels(models, cap, spent, { unpriced = new Set(), overhead = piOverhead, refused: markRefused, joined = false } = {}) {
|
|
588
800
|
const [{ calculateCost, createAssistantMessageEventStream }, simple] = await Promise.all([import("@earendil-works/pi-ai"), import("@earendil-works/pi-ai/api/simple-options")]);
|
|
589
801
|
const partsOf = requestParts(overhead);
|
|
590
802
|
let held = 0;
|
|
591
|
-
|
|
803
|
+
if (joined)
|
|
804
|
+
sidesSpent = spent;
|
|
805
|
+
/** What the run has spent, as this request's check reads it: on another harness the run's one total (`joined`). */
|
|
806
|
+
const spentNow = () => (joined ? (runSpend?.now?.() ?? null) : spent);
|
|
807
|
+
// The run's spend as a paid tool's check reads it (installed below, useSpend): the requests in flight held at their
|
|
808
|
+
// worst case apart from it (it adds the paid holds itself), and its charge joins the spend.
|
|
809
|
+
const own = { cap, spent: () => spent, held: () => held, add: (usd) => void (spent = spent !== null && typeof usd === "number" && Number.isFinite(usd) ? spent + usd : null) };
|
|
810
|
+
const judge = (model, context, options, simpleCall, turn) => {
|
|
592
811
|
if (unpriced.has(model.id))
|
|
593
812
|
return { why: noPrice(cap) };
|
|
594
813
|
const ceiling = outputBound(model);
|
|
595
814
|
if (ceiling === undefined)
|
|
596
815
|
return { why: noCeiling(cap) };
|
|
597
|
-
|
|
816
|
+
const spentUsd = spentNow();
|
|
817
|
+
if (spentUsd === null)
|
|
598
818
|
return { why: unknownSpend(cap) };
|
|
819
|
+
// A paid call the cap just refused for room: the turn's next request, the one after its result, is refused in its
|
|
820
|
+
// words, and the run pauses there. A request after a message of the person's instead (a stop came first, and the
|
|
821
|
+
// 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
|
|
822
|
+
// own requests (stream, streamSimple) take it: a side request through the run's models (completeSimple: a
|
|
823
|
+
// compaction's summary, native web_search's own, request-start.ts) is judged as any other and leaves it for them.
|
|
824
|
+
const paid = turn ? takePaidRefusal(own) : undefined;
|
|
825
|
+
if (paid && context.messages.at(-1)?.role === "toolResult")
|
|
826
|
+
return { why: `${CAP_REFUSAL_CODE}${paid.words}`, figures: paid.figures };
|
|
599
827
|
const parts = partsOf(model, context);
|
|
600
828
|
if (parts === undefined)
|
|
601
829
|
return { why: unmeasured(cap) };
|
|
@@ -604,24 +832,46 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
604
832
|
// What the run holds beside what it spent, as a paid call's check counts it: each request in flight at its figure, and
|
|
605
833
|
// each paid call under way at what it is held at.
|
|
606
834
|
const holding = held + paidHolds();
|
|
607
|
-
const left = cap -
|
|
835
|
+
const left = cap - spentUsd - holding;
|
|
608
836
|
const name = nameOf(model);
|
|
609
837
|
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input and fee to fit.
|
|
610
838
|
if (ceiling === 0)
|
|
611
|
-
return cost(0) <= left ? { worst: cost(0), stopped: () => cost(0) } : { why: capRefusal(cap,
|
|
839
|
+
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) } };
|
|
612
840
|
// What the request would send as it stands, thinking included: pi-ai clamps its maxTokens (or the model's) to what its
|
|
613
841
|
// context leaves, and on an API whose thinking takes a budget adds the budget to it.
|
|
614
842
|
const transcript = context;
|
|
615
843
|
const thinking = simpleCall && model.reasoning && options?.reasoning ? options.reasoning : undefined;
|
|
616
|
-
|
|
844
|
+
// Adaptive thinking (pi-ai's current Claude models on Anthropic's API) takes no budget: pi-ai sends the request's
|
|
845
|
+
// maxTokens as is, and the model thinks within them as it sees fit: at any level, none included, on a model with
|
|
846
|
+
// mid-conversation effort, else when given a level.
|
|
847
|
+
const compat = model.api === "anthropic-messages" && model.reasoning ? model.compat : undefined;
|
|
848
|
+
const adaptive = compat?.supportsMidConvoEffort === true || (compat?.forceAdaptiveThinking === true && thinking !== undefined);
|
|
849
|
+
const budgeted = thinking !== undefined && BUDGET_APIS.has(model.api) && !adaptive;
|
|
617
850
|
const base = simple.clampMaxTokensToContext(model, transcript, options?.maxTokens ?? ceilingTokens(model));
|
|
618
851
|
const asked = Math.min(ceiling, budgeted ? simple.clampMaxTokensToContext(model, transcript, simple.adjustMaxTokensForThinking(base, ceilingTokens(model), thinking, options?.thinkingBudgets).maxTokens) : base);
|
|
619
852
|
const least = Math.min(leastOutput(model, thinking, (level) => simple.thinkingBudgetForLevel(level, options?.thinkingBudgets)), asked);
|
|
620
853
|
const most = mostOutput(cost, least, asked, left);
|
|
621
854
|
if (most === undefined)
|
|
622
|
-
return { why: capRefusal(cap,
|
|
623
|
-
//
|
|
624
|
-
|
|
855
|
+
return { why: capRefusal(cap, spentUsd, holding, name, cost(least)), figures: { spentUsd: spentUsd + holding, needsUsd: cost(least) } };
|
|
856
|
+
// The reasoning a stop leaves unseen: a model's reasoning streams as a summary or not at all (the Responses API; Claude
|
|
857
|
+
// 4-class thinking), so a request that reasons counts its level's budget (the budget it was sent with, on a budget
|
|
858
|
+
// API), or its whole limit when it gives no level and its API reasons by default; none on a budget API with thinking
|
|
859
|
+
// off, or on a model that does not reason. Adaptive thinking is bounded only by the limit, so it counts the limit
|
|
860
|
+
// less the answer's 1,024 tokens. An estimate, as levels are not limits the provider keeps: within the hold.
|
|
861
|
+
const hiddenOf = (limit) => {
|
|
862
|
+
if (adaptive)
|
|
863
|
+
return Math.max(0, limit - ANSWER_TOKENS_LEAST);
|
|
864
|
+
if (!model.reasoning || thinking === "off")
|
|
865
|
+
return 0;
|
|
866
|
+
if (thinking === undefined)
|
|
867
|
+
return BUDGET_APIS.has(model.api) ? 0 : limit;
|
|
868
|
+
const budget = simple.thinkingBudgetForLevel(thinking, options?.thinkingBudgets);
|
|
869
|
+
return budgeted ? Math.max(0, Math.min(budget, limit - ANSWER_TOKENS_LEAST)) : budget;
|
|
870
|
+
};
|
|
871
|
+
// Stopped before its end, at most the output it was sent with: what it streamed, the part of its reasoning budget that
|
|
872
|
+
// did not stream (max(0, budget - the reasoning streamed), so thinking that streamed is not counted twice), and the
|
|
873
|
+
// allowance, within its worst case.
|
|
874
|
+
const stoppedAt = (limit) => (message) => stoppedFigure(cost, limit, cost(limit), streamedBytes(message) + Math.max(0, hiddenOf(limit) - reasoningBytes(message)));
|
|
625
875
|
if (most === asked)
|
|
626
876
|
return { worst: cost(asked), stopped: stoppedAt(asked) };
|
|
627
877
|
// Limited: sent with `most` tokens at most, thinking included. On a budget API the budget is squeezed first, keeping
|
|
@@ -640,40 +890,59 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
640
890
|
errorMessage: why,
|
|
641
891
|
});
|
|
642
892
|
/** Adds what `answer` cost to what the run has spent once it settles. One stopped before its end counts at `stopped`
|
|
643
|
-
* of what it streamed (stoppedFigure, at most `worst`)
|
|
893
|
+
* of what it streamed (stoppedFigure, at most `worst`), unless an attempt before the stop was lost: then at `worst`, as
|
|
894
|
+
* its lost mark reads in a later process; one that ended on an error after its response began
|
|
644
895
|
* (markResponseBegan: its usage is what had streamed, not what the provider can have billed), or that failed with no
|
|
645
896
|
* answer, at `worst`, what the cap held for it; each as spentIn reads its end mark. Without a figure (a deferred
|
|
646
897
|
* response) it is unknown, as is a cost that is not a number, from then on. */
|
|
647
|
-
const count = (answer, worst, stopped) => {
|
|
648
|
-
const
|
|
649
|
-
const
|
|
650
|
-
|
|
898
|
+
const count = (answer, worst, stopped, attempts) => {
|
|
899
|
+
const plus = (sum, cost) => (sum !== null && typeof cost === "number" && Number.isFinite(cost) ? sum + cost : null);
|
|
900
|
+
const add = (cost) => void (joined ? (sidesSpent = plus(sidesSpent, cost)) : (spent = plus(spent, cost)));
|
|
901
|
+
// One rule (bookRequest), from how the request ended (piEnded) as its marks read it too.
|
|
902
|
+
const at = (message) => message.stopReason === "aborted" ? (stopped && !anyAttemptLost(attempts) ? stopped(message) : worst)
|
|
903
|
+
: bookRequest(piEnded(message, responseBegan.has(message), attempts), worst === undefined ? {} : { hold: worst }).usd;
|
|
651
904
|
return answer.then((message) => add(at(message)), () => add(worst));
|
|
652
905
|
};
|
|
653
|
-
/** Sends a request judged to fit at `worst`, holding that until `answer` settles
|
|
654
|
-
|
|
655
|
-
|
|
906
|
+
/** Sends a request judged to fit at `worst`, holding that until `answer` settles: here, or on another harness where
|
|
907
|
+
* its check sees it (`joined`: paidHolds). */
|
|
908
|
+
const admit = (worst, stopped, answer, attempts) => {
|
|
909
|
+
const hold = { usd: worst };
|
|
910
|
+
if (joined)
|
|
911
|
+
paidOpen.add(hold);
|
|
912
|
+
else
|
|
913
|
+
held += worst;
|
|
914
|
+
const release = () => void (joined ? paidOpen.delete(hold) : (held -= worst));
|
|
656
915
|
let answered;
|
|
657
916
|
try {
|
|
658
917
|
answered = answer();
|
|
659
918
|
}
|
|
660
919
|
catch (error) {
|
|
661
|
-
|
|
920
|
+
release();
|
|
662
921
|
throw error;
|
|
663
922
|
}
|
|
664
|
-
void count(answered, worst, stopped).finally(
|
|
923
|
+
void count(answered, worst, stopped, attempts).finally(release);
|
|
665
924
|
return answered;
|
|
666
925
|
};
|
|
667
|
-
// A paid tool's check reads the spend
|
|
668
|
-
// itself), and its charge joins it
|
|
669
|
-
|
|
926
|
+
// A paid tool's check reads the spend, and the requests in flight held at their worst case apart from it (it adds the
|
|
927
|
+
// paid holds itself), and its charge joins the spend. On another harness, the harness sets it as its run opens
|
|
928
|
+
// (harness-app.ts).
|
|
929
|
+
if (!joined)
|
|
930
|
+
useSpend(own);
|
|
670
931
|
/** `options` with the request's worst case, and its figure if it is stopped, for its marks. */
|
|
671
|
-
|
|
932
|
+
/** `options` with the request's worst case, its figure if it is stopped, and its attempts' record, for its marks: on an
|
|
933
|
+
* API the cap can watch, a fetch that records each attempt (`attempts`, undefined on one it cannot). */
|
|
934
|
+
const carrying = (options, { worst, stopped }, attempts) => ({
|
|
935
|
+
...options, [HELD_USD]: worst, [STOPPED_USD]: stopped,
|
|
936
|
+
// null on an API the cap cannot watch: its marks read a failure before any event as lost.
|
|
937
|
+
...(attempts ? { [ATTEMPTS]: attempts, fetch: recordingFetch(attempts, options?.fetch, options?.signal) } : { [ATTEMPTS]: null }),
|
|
938
|
+
});
|
|
939
|
+
const attemptsFor = (model) => (unwatched(model.api) ? undefined : []);
|
|
672
940
|
const stream = (send, simpleCall) => (model, context, options) => {
|
|
673
|
-
const judged = judge(model, context, options, simpleCall);
|
|
941
|
+
const judged = judge(model, context, options, simpleCall, true);
|
|
674
942
|
if ("worst" in judged) {
|
|
675
943
|
let events;
|
|
676
|
-
|
|
944
|
+
const attempts = attemptsFor(model);
|
|
945
|
+
admit(judged.worst, judged.stopped, () => (events = send(model, context, carrying(judged.options ?? options, judged, attempts))).result(), attempts);
|
|
677
946
|
return events;
|
|
678
947
|
}
|
|
679
948
|
const refused = createAssistantMessageEventStream();
|
|
@@ -681,7 +950,7 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
681
950
|
// Its own start mark first, so pi's error entry for it answers that mark, never an earlier request a stop or a crash
|
|
682
951
|
// cut. A mark that cannot be written still ends the request: spentIn leaves refusals out either way.
|
|
683
952
|
void Promise.resolve()
|
|
684
|
-
.then(() => markRefused?.())
|
|
953
|
+
.then(() => markRefused?.(judged.figures))
|
|
685
954
|
.catch(() => undefined)
|
|
686
955
|
.then(() => {
|
|
687
956
|
refused.push({ type: "error", reason: "error", error: message });
|
|
@@ -690,8 +959,11 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
690
959
|
return refused;
|
|
691
960
|
};
|
|
692
961
|
const complete = (send, simpleCall) => (model, context, options) => {
|
|
693
|
-
const judged = judge(model, context, options, simpleCall);
|
|
694
|
-
|
|
962
|
+
const judged = judge(model, context, options, simpleCall, false);
|
|
963
|
+
if (!("worst" in judged))
|
|
964
|
+
return Promise.resolve(refusal(model, judged.why));
|
|
965
|
+
const attempts = attemptsFor(model);
|
|
966
|
+
return admit(judged.worst, judged.stopped, () => send(model, context, carrying(judged.options ?? options, judged, attempts)), attempts);
|
|
695
967
|
};
|
|
696
968
|
const guarded = {
|
|
697
969
|
stream: stream(models.stream.bind(models), false),
|