@parcha/agentrun-serve 0.1.0-beta.29 → 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 +188 -0
- package/README.md +564 -97
- package/dist/adapters.d.ts +35 -6
- package/dist/adapters.js +152 -26
- package/dist/agents.d.ts +11 -5
- package/dist/agents.js +16 -10
- package/dist/app.js +80 -20
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/box-egress.d.ts +98 -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 +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +8 -5
- package/dist/box-relay.js +14 -9
- package/dist/boxes.d.ts +21 -3
- package/dist/boxes.js +14 -7
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +129 -21
- package/dist/cap.js +338 -67
- 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-34jfpIbQ.js +481 -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/errors.d.ts +2 -0
- package/dist/errors.js +5 -2
- package/dist/files.d.ts +6 -1
- package/dist/files.js +7 -2
- package/dist/grade.d.ts +7 -10
- package/dist/grade.js +31 -51
- 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 +101 -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-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/learn/check.d.ts +10 -1
- package/dist/learn/check.js +19 -1
- package/dist/learn/grade.d.ts +3 -2
- package/dist/learn/grade.js +25 -13
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/notes.js +2 -1
- package/dist/learn/reflect.d.ts +2 -2
- package/dist/learn/reflect.js +51 -5
- package/dist/learn/secrets.js +28 -8
- package/dist/learn/skills.d.ts +17 -4
- package/dist/learn/skills.js +79 -6
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-run.d.ts +7 -5
- package/dist/learning-run.js +45 -23
- package/dist/learning-words.d.ts +6 -3
- package/dist/learning-words.js +8 -5
- package/dist/learning.d.ts +44 -3
- package/dist/learning.js +148 -3
- package/dist/mcp-servers.d.ts +7 -4
- package/dist/mcp-servers.js +5 -0
- 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 +358 -48
- 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 +27 -4
- package/dist/place.js +42 -10
- 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 +173 -23
- package/dist/runnable.d.ts +5 -2
- package/dist/runnable.js +12 -4
- package/dist/runs.d.ts +258 -36
- package/dist/runs.js +830 -89
- package/dist/secrets.d.ts +12 -0
- package/dist/secrets.js +18 -0
- package/dist/server.d.ts +131 -35
- package/dist/server.js +467 -105
- 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 +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +46 -10
- package/dist/tool-keys.js +44 -2
- package/dist/tool-plane.d.ts +112 -27
- package/dist/tool-plane.js +205 -47
- package/dist/tools.d.ts +69 -14
- package/dist/tools.js +143 -24
- 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/webhooks.d.ts +11 -4
- package/dist/webhooks.js +17 -1
- package/launcher/agentrun-serve +1 -1
- package/package.json +19 -13
- 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,48 @@ 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
|
+
return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0, browser, others: otherTools, known };
|
|
348
486
|
}
|
|
349
487
|
finally {
|
|
350
488
|
db.close();
|
|
@@ -382,12 +520,36 @@ export function holdsInFlight() {
|
|
|
382
520
|
}
|
|
383
521
|
let runSpend;
|
|
384
522
|
let paying = Promise.resolve();
|
|
385
|
-
export const useSpend = (spend) =>
|
|
386
|
-
|
|
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`). */
|
|
387
530
|
const paidOpen = new Set();
|
|
388
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
|
|
389
|
-
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall).
|
|
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. */
|
|
390
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;
|
|
391
553
|
/** `call`, a paid tool's (`name`), under the run's cap, by the rule a model request keeps: refused, in words that name
|
|
392
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
|
|
393
555
|
* quote, else an allowance, `basis` saying which) fits the cap, and whenever the spend is unknown; else run, one paid
|
|
@@ -395,6 +557,21 @@ export const paidHolds = () => [...paidOpen].reduce((sum, { usd }) => sum + usd,
|
|
|
395
557
|
* reports (`charge` of its result, undefined for none) joins the spend. A charge it does not say (null), or a call that
|
|
396
558
|
* fails, counts at its held figure, as its mark does from the store (spentIn), since it may have charged that much.
|
|
397
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
|
+
}
|
|
398
575
|
export async function paidCall(name, call, charge, hold) {
|
|
399
576
|
const spend = runSpend;
|
|
400
577
|
if (!spend)
|
|
@@ -402,11 +579,16 @@ export async function paidCall(name, call, charge, hold) {
|
|
|
402
579
|
const turn = paying.then(async () => {
|
|
403
580
|
const read = await spend.spent();
|
|
404
581
|
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
|
-
|
|
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();
|
|
407
585
|
// Written so that a figure that is not a number refuses.
|
|
408
|
-
if (!(
|
|
409
|
-
|
|
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
|
+
}
|
|
410
592
|
// Held from here; settled into the spend in the same step that lets the hold go, so no check between sees neither.
|
|
411
593
|
const open = { usd: hold.usd };
|
|
412
594
|
paidOpen.add(open);
|
|
@@ -451,10 +633,10 @@ export function piOverhead(model, context) {
|
|
|
451
633
|
const parts = (context.messages ?? []).flatMap((message) => (Array.isArray(message.content) ? (message.content) : []));
|
|
452
634
|
return providerInputOverhead(model.api, { tools: (context.tools?.length ?? 0) > 0, toolChoice: "any", images: parts.filter((part) => part?.type === "image").length });
|
|
453
635
|
}
|
|
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}:
|
|
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.`;
|
|
458
640
|
/** A request's worst case at `model`'s price: `input` tokens at the dearer of its input and cache-write prices, and
|
|
459
641
|
* `output` tokens at its output price. */
|
|
460
642
|
function worstOf(calculateCost, model) {
|
|
@@ -475,34 +657,58 @@ export function money(usd) {
|
|
|
475
657
|
* which pi-ai's retry (isRetryableAssistantError, which reads only an error's text) takes as final whatever digits the
|
|
476
658
|
* words after it hold. The words after it are the ones a person reads. */
|
|
477
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);
|
|
478
664
|
/** A model's name as the words say it: the catalog's, without a vendor's prefix ("Anthropic: Claude Sonnet 5.5" reads
|
|
479
665
|
* "Claude Sonnet 5.5"), else its id. */
|
|
480
666
|
export const nameOf = (model) => (model.name || model.id).replace(/^[^:]{1,40}:\s+(?=\S)/, "");
|
|
481
667
|
/** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
|
|
482
|
-
|
|
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
|
+
};
|
|
483
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
|
|
484
678
|
* the run spent (and holds for requests still answering) of its cap, what the request needs at the least, and the cap
|
|
485
679
|
* that would run it (spent, held and that least, rounded up to the cent, so that it is enough). After its code
|
|
486
680
|
* (CAP_REFUSAL_CODE), which keeps it final to pi-ai's retry. */
|
|
487
681
|
function capRefusal(cap, spent, held, name, least) {
|
|
488
|
-
const [need, raise] = [leastMoney(least),
|
|
682
|
+
const [need, raise] = [leastMoney(least), raiseTo(cap, spent + held + least)];
|
|
489
683
|
if (spent === 0 && held === 0)
|
|
490
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.`;
|
|
491
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`;
|
|
492
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.`;
|
|
493
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
|
+
}
|
|
494
699
|
/** The most output tokens from `least` to `asked` whose request costs no more than `left` (`cost`, its price at that
|
|
495
700
|
* many, rising with them); undefined when even `least` costs more. A search, so that a price with tiers is exact. */
|
|
496
701
|
function mostOutput(cost, least, asked, left) {
|
|
497
|
-
// Written so that a cost that is not a number refuses.
|
|
498
|
-
|
|
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))
|
|
499
705
|
return undefined;
|
|
500
|
-
if (
|
|
706
|
+
if (fits(asked))
|
|
501
707
|
return asked;
|
|
502
708
|
let [low, high] = [least, asked];
|
|
503
709
|
while (high - low > 1) {
|
|
504
710
|
const mid = Math.floor((low + high) / 2);
|
|
505
|
-
if (
|
|
711
|
+
if (fits(mid))
|
|
506
712
|
low = mid;
|
|
507
713
|
else
|
|
508
714
|
high = mid;
|
|
@@ -551,15 +757,15 @@ export async function capBefore(cap, model, { listed = true } = {}) {
|
|
|
551
757
|
const cost = (tokens) => price(inputTokensMax, tokens);
|
|
552
758
|
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input to fit.
|
|
553
759
|
if (output === 0)
|
|
554
|
-
return cost(0) <= left ? undefined : { refuse: capRefusal(cap, spentUsd, holding, name, cost(0)) };
|
|
760
|
+
return cost(0) <= left + FIT_TOLERANCE ? undefined : { refuse: capRefusal(cap, spentUsd, holding, name, cost(0)), spentUsd: spentUsd + holding, needsUsd: cost(0) };
|
|
555
761
|
const asked = Math.min(outputTokensAsked ?? output, output);
|
|
556
762
|
const least = Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked);
|
|
557
763
|
const most = mostOutput(cost, least, asked, left);
|
|
558
|
-
return most === undefined ? { refuse: capRefusal(cap, spentUsd, holding, name, cost(least)) } : { outputTokensMax: most };
|
|
764
|
+
return most === undefined ? { refuse: capRefusal(cap, spentUsd, holding, name, cost(least)), spentUsd: spentUsd + holding, needsUsd: cost(least) } : { outputTokensMax: most };
|
|
559
765
|
},
|
|
560
766
|
worstOf: (request) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) ? held(request) : undefined),
|
|
561
767
|
stoppedOf: (request, streamed) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) && Number.isFinite(streamed) && streamed >= 0
|
|
562
|
-
? price(request.inputTokensMax,
|
|
768
|
+
? stoppedPriceOf((tokens) => price(request.inputTokensMax, tokens), request.outputTokensMax ?? output)(streamed) : undefined),
|
|
563
769
|
};
|
|
564
770
|
}
|
|
565
771
|
/** A request's input bound (inputBound of its context, plus `overhead(model, context)`, what its provider adds
|
|
@@ -583,19 +789,40 @@ export function requestParts(overhead = piOverhead) {
|
|
|
583
789
|
* (spentIn), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
|
|
584
790
|
* `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. Each
|
|
585
791
|
* 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
|
-
|
|
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 } = {}) {
|
|
588
799
|
const [{ calculateCost, createAssistantMessageEventStream }, simple] = await Promise.all([import("@earendil-works/pi-ai"), import("@earendil-works/pi-ai/api/simple-options")]);
|
|
589
800
|
const partsOf = requestParts(overhead);
|
|
590
801
|
let held = 0;
|
|
591
|
-
|
|
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) => {
|
|
592
810
|
if (unpriced.has(model.id))
|
|
593
811
|
return { why: noPrice(cap) };
|
|
594
812
|
const ceiling = outputBound(model);
|
|
595
813
|
if (ceiling === undefined)
|
|
596
814
|
return { why: noCeiling(cap) };
|
|
597
|
-
|
|
815
|
+
const spentUsd = spentNow();
|
|
816
|
+
if (spentUsd === null)
|
|
598
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 };
|
|
599
826
|
const parts = partsOf(model, context);
|
|
600
827
|
if (parts === undefined)
|
|
601
828
|
return { why: unmeasured(cap) };
|
|
@@ -604,24 +831,46 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
604
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
|
|
605
832
|
// each paid call under way at what it is held at.
|
|
606
833
|
const holding = held + paidHolds();
|
|
607
|
-
const left = cap -
|
|
834
|
+
const left = cap - spentUsd - holding;
|
|
608
835
|
const name = nameOf(model);
|
|
609
836
|
// A model whose output costs nothing and names no ceiling: nothing to limit, only its input and fee to fit.
|
|
610
837
|
if (ceiling === 0)
|
|
611
|
-
return cost(0) <= left ? { worst: cost(0), stopped: () => cost(0) } : { why: capRefusal(cap,
|
|
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) } };
|
|
612
839
|
// What the request would send as it stands, thinking included: pi-ai clamps its maxTokens (or the model's) to what its
|
|
613
840
|
// context leaves, and on an API whose thinking takes a budget adds the budget to it.
|
|
614
841
|
const transcript = context;
|
|
615
842
|
const thinking = simpleCall && model.reasoning && options?.reasoning ? options.reasoning : undefined;
|
|
616
|
-
|
|
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;
|
|
617
849
|
const base = simple.clampMaxTokensToContext(model, transcript, options?.maxTokens ?? ceilingTokens(model));
|
|
618
850
|
const asked = Math.min(ceiling, budgeted ? simple.clampMaxTokensToContext(model, transcript, simple.adjustMaxTokensForThinking(base, ceilingTokens(model), thinking, options?.thinkingBudgets).maxTokens) : base);
|
|
619
851
|
const least = Math.min(leastOutput(model, thinking, (level) => simple.thinkingBudgetForLevel(level, options?.thinkingBudgets)), asked);
|
|
620
852
|
const most = mostOutput(cost, least, asked, left);
|
|
621
853
|
if (most === undefined)
|
|
622
|
-
return { why: capRefusal(cap,
|
|
623
|
-
//
|
|
624
|
-
|
|
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)));
|
|
625
874
|
if (most === asked)
|
|
626
875
|
return { worst: cost(asked), stopped: stoppedAt(asked) };
|
|
627
876
|
// Limited: sent with `most` tokens at most, thinking included. On a budget API the budget is squeezed first, keeping
|
|
@@ -640,40 +889,59 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
640
889
|
errorMessage: why,
|
|
641
890
|
});
|
|
642
891
|
/** 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`)
|
|
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
|
|
644
894
|
* (markResponseBegan: its usage is what had streamed, not what the provider can have billed), or that failed with no
|
|
645
895
|
* answer, at `worst`, what the cap held for it; each as spentIn reads its end mark. Without a figure (a deferred
|
|
646
896
|
* 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
|
-
|
|
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;
|
|
651
903
|
return answer.then((message) => add(at(message)), () => add(worst));
|
|
652
904
|
};
|
|
653
|
-
/** Sends a request judged to fit at `worst`, holding that until `answer` settles
|
|
654
|
-
|
|
655
|
-
|
|
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));
|
|
656
914
|
let answered;
|
|
657
915
|
try {
|
|
658
916
|
answered = answer();
|
|
659
917
|
}
|
|
660
918
|
catch (error) {
|
|
661
|
-
|
|
919
|
+
release();
|
|
662
920
|
throw error;
|
|
663
921
|
}
|
|
664
|
-
void count(answered, worst, stopped).finally(
|
|
922
|
+
void count(answered, worst, stopped, attempts).finally(release);
|
|
665
923
|
return answered;
|
|
666
924
|
};
|
|
667
|
-
// A paid tool's check reads the spend
|
|
668
|
-
// itself), and its charge joins it
|
|
669
|
-
|
|
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);
|
|
670
930
|
/** `options` with the request's worst case, and its figure if it is stopped, for its marks. */
|
|
671
|
-
|
|
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 : []);
|
|
672
939
|
const stream = (send, simpleCall) => (model, context, options) => {
|
|
673
|
-
const judged = judge(model, context, options, simpleCall);
|
|
940
|
+
const judged = judge(model, context, options, simpleCall, true);
|
|
674
941
|
if ("worst" in judged) {
|
|
675
942
|
let events;
|
|
676
|
-
|
|
943
|
+
const attempts = attemptsFor(model);
|
|
944
|
+
admit(judged.worst, judged.stopped, () => (events = send(model, context, carrying(judged.options ?? options, judged, attempts))).result(), attempts);
|
|
677
945
|
return events;
|
|
678
946
|
}
|
|
679
947
|
const refused = createAssistantMessageEventStream();
|
|
@@ -681,7 +949,7 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
681
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
|
|
682
950
|
// cut. A mark that cannot be written still ends the request: spentIn leaves refusals out either way.
|
|
683
951
|
void Promise.resolve()
|
|
684
|
-
.then(() => markRefused?.())
|
|
952
|
+
.then(() => markRefused?.(judged.figures))
|
|
685
953
|
.catch(() => undefined)
|
|
686
954
|
.then(() => {
|
|
687
955
|
refused.push({ type: "error", reason: "error", error: message });
|
|
@@ -690,8 +958,11 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
|
|
|
690
958
|
return refused;
|
|
691
959
|
};
|
|
692
960
|
const complete = (send, simpleCall) => (model, context, options) => {
|
|
693
|
-
const judged = judge(model, context, options, simpleCall);
|
|
694
|
-
|
|
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);
|
|
695
966
|
};
|
|
696
967
|
const guarded = {
|
|
697
968
|
stream: stream(models.stream.bind(models), false),
|