@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
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Context } from "@earendil-works/chord";
|
|
2
|
+
import { type Conversation, type Session, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
|
|
3
|
+
import type { SessionCharge } from "@parcha/pi-browser";
|
|
4
|
+
/** List prices by pi-browser provider name (`provider.name`): Browserbase's (pi-browser's LIST_PRICES), $0.12 an hour with
|
|
5
|
+
* a one-minute minimum; Kernel's headless browser, about $0.06 an hour billed by the second; a local Chrome (`cdp`), free. */
|
|
6
|
+
export declare const BROWSER_PRICES: Readonly<Record<string, {
|
|
7
|
+
usdPerHour: number;
|
|
8
|
+
minimumS: number;
|
|
9
|
+
}>>;
|
|
10
|
+
/** An operator's price for a provider, in USD an hour: this prefix and the provider's name in capitals
|
|
11
|
+
* (AGENTRUN_BROWSER_USD_PER_HOUR_BROWSERBASE, _KERNEL, _CDP). */
|
|
12
|
+
export declare const BROWSER_PRICE_ENV = "AGENTRUN_BROWSER_USD_PER_HOUR_";
|
|
13
|
+
/** What a release may take to be confirmed at the provider once it is asked (pi-browser's confirm polls back off 0.5 to 4 s). */
|
|
14
|
+
export declare const RELEASE_ALLOWANCE_S = 30;
|
|
15
|
+
/** How long pi-browser leaves a create whose answer was lost before it releases it by its tag (its create deadline; serve
|
|
16
|
+
* keeps the default). */
|
|
17
|
+
export declare const CREATE_DEADLINE_S = 60;
|
|
18
|
+
export declare const priceEnvOf: (provider: string) => string;
|
|
19
|
+
/** `provider`'s session price: the operator's (a non-negative decimal), else the list's; `usdPerHour` null when neither
|
|
20
|
+
* names one or the operator's cannot be read, which is no price, never $0. */
|
|
21
|
+
export declare function browserPrice(provider: string, env: NodeJS.ProcessEnv): {
|
|
22
|
+
usdPerHour: number | null;
|
|
23
|
+
minimumS: number;
|
|
24
|
+
};
|
|
25
|
+
/** One run's browser bookings, for its one provider at `price` with pi-browser's idle window `idleS`. `release` lets go of
|
|
26
|
+
* a conversation's session (pi-browser's release, "close"). */
|
|
27
|
+
export declare function browserSpend(provider: string, price: {
|
|
28
|
+
usdPerHour: number | null;
|
|
29
|
+
minimumS: number;
|
|
30
|
+
}, idleS: number, release: (conversation: Pick<Conversation, "id" | "commit">, context: Context) => Promise<void>): {
|
|
31
|
+
onCharge: (charge: SessionCharge, tx: Tx, call?: {
|
|
32
|
+
callId: string;
|
|
33
|
+
}) => Promise<void>;
|
|
34
|
+
watch: (harness: Pick<Session, "subscribeCommits">, inventory?: string) => void;
|
|
35
|
+
reopened: (harness: Pick<Session, "snapshot">, docs: {
|
|
36
|
+
Inventory: unknown;
|
|
37
|
+
Sessions: unknown;
|
|
38
|
+
}, context: Context) => Promise<void>;
|
|
39
|
+
capped: (tool: ToolRegistration) => ToolRegistration;
|
|
40
|
+
stretch: number;
|
|
41
|
+
};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
2
|
+
import { TOOL_COST } from "@parcha/pi-durable-agent/timeline";
|
|
3
|
+
import { addSpend, keepHold, paidCall, runCap, SPEND_CAP_REACHED } from "./cap.js";
|
|
4
|
+
import { forModel } from "./result.js";
|
|
5
|
+
/** List prices by pi-browser provider name (`provider.name`): Browserbase's (pi-browser's LIST_PRICES), $0.12 an hour with
|
|
6
|
+
* a one-minute minimum; Kernel's headless browser, about $0.06 an hour billed by the second; a local Chrome (`cdp`), free. */
|
|
7
|
+
export const BROWSER_PRICES = Object.freeze({
|
|
8
|
+
browserbase: { usdPerHour: 0.12, minimumS: 60 },
|
|
9
|
+
kernel: { usdPerHour: 0.06, minimumS: 0 },
|
|
10
|
+
cdp: { usdPerHour: 0, minimumS: 0 },
|
|
11
|
+
});
|
|
12
|
+
/** An operator's price for a provider, in USD an hour: this prefix and the provider's name in capitals
|
|
13
|
+
* (AGENTRUN_BROWSER_USD_PER_HOUR_BROWSERBASE, _KERNEL, _CDP). */
|
|
14
|
+
export const BROWSER_PRICE_ENV = "AGENTRUN_BROWSER_USD_PER_HOUR_";
|
|
15
|
+
/** What a release may take to be confirmed at the provider once it is asked (pi-browser's confirm polls back off 0.5 to 4 s). */
|
|
16
|
+
export const RELEASE_ALLOWANCE_S = 30;
|
|
17
|
+
/** How long pi-browser leaves a create whose answer was lost before it releases it by its tag (its create deadline; serve
|
|
18
|
+
* keeps the default). */
|
|
19
|
+
export const CREATE_DEADLINE_S = 60;
|
|
20
|
+
export const priceEnvOf = (provider) => `${BROWSER_PRICE_ENV}${provider.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
|
|
21
|
+
/** `provider`'s session price: the operator's (a non-negative decimal), else the list's; `usdPerHour` null when neither
|
|
22
|
+
* names one or the operator's cannot be read, which is no price, never $0. */
|
|
23
|
+
export function browserPrice(provider, env) {
|
|
24
|
+
const listed = Object.hasOwn(BROWSER_PRICES, provider) ? BROWSER_PRICES[provider] : undefined;
|
|
25
|
+
const text = env[priceEnvOf(provider)]?.trim();
|
|
26
|
+
const given = text ? (/^(\d+(\.\d*)?|\.\d+)$/.test(text) ? Number(text) : NaN) : undefined;
|
|
27
|
+
return { usdPerHour: given === undefined ? (listed?.usdPerHour ?? null) : Number.isFinite(given) ? given : null, minimumS: listed?.minimumS ?? 0 };
|
|
28
|
+
}
|
|
29
|
+
/** One run's browser bookings, for its one provider at `price` with pi-browser's idle window `idleS`. `release` lets go of
|
|
30
|
+
* a conversation's session (pi-browser's release, "close"). */
|
|
31
|
+
export function browserSpend(provider, price, idleS, release) {
|
|
32
|
+
const rate = price.usdPerHour;
|
|
33
|
+
const usdOf = (seconds) => ((rate ?? 0) * seconds) / 3600;
|
|
34
|
+
const stretchS = price.minimumS + idleS + RELEASE_ALLOWANCE_S;
|
|
35
|
+
const stretch = usdOf(stretchS);
|
|
36
|
+
const sessions = new Map();
|
|
37
|
+
/** Each call under way, by its id: its conversation and its hold. */
|
|
38
|
+
const calls = new Map();
|
|
39
|
+
const take = (hold, usd) => void (hold && (hold.usd = Math.max(0, hold.usd - usd)));
|
|
40
|
+
/** Booked in the commit that bills it: a TOOL_COST under the call that ran it (a release's, under its session's last
|
|
41
|
+
* call), what it cost or null when its time has no price, and the seconds it was for, with what `booked` needs. A free
|
|
42
|
+
* provider's time books nothing and holds nothing. */
|
|
43
|
+
async function onCharge(charge, tx, call) {
|
|
44
|
+
if (rate === 0)
|
|
45
|
+
return;
|
|
46
|
+
const usd = charge.state === "priced" ? charge.usd : null;
|
|
47
|
+
const data = { tool: "browser", charged_by: charge.provider, call: call?.callId ?? sessions.get(charge.tag)?.call ?? null, usd, seconds: charge.seconds, tag: charge.tag, conversation: charge.conversationId, at: charge.at, final: charge.final };
|
|
48
|
+
await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: TOOL_COST, data });
|
|
49
|
+
}
|
|
50
|
+
/** A charge whose commit is in (watch): it joins what the run's process counts as spent, and moves the holds. Never
|
|
51
|
+
* inside the commit, so one that fails changes neither. */
|
|
52
|
+
function booked(data) {
|
|
53
|
+
const usd = data.usd ?? 0;
|
|
54
|
+
const session = sessions.get(data.tag);
|
|
55
|
+
addSpend(data.usd);
|
|
56
|
+
if (data.final) {
|
|
57
|
+
// A session the provider ended before its first charge has no reserve: its release comes out of its call's hold.
|
|
58
|
+
take(session?.reserve ?? [...calls.values()].find((c) => c.cid === data.conversation)?.hold, usd);
|
|
59
|
+
session?.reserve.drop();
|
|
60
|
+
sessions.delete(data.tag);
|
|
61
|
+
}
|
|
62
|
+
else if (session) {
|
|
63
|
+
take(data.call === null ? undefined : calls.get(data.call)?.hold, usd);
|
|
64
|
+
// Its reserve is one stretch again: a kept session's held what it ran before this charge, which booked it.
|
|
65
|
+
session.reserve.usd = stretch;
|
|
66
|
+
Object.assign(session, { at: Date.parse(data.at), call: data.call ?? session.call });
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
take(data.call === null ? undefined : calls.get(data.call)?.hold, usd + stretch);
|
|
70
|
+
sessions.set(data.tag, { cid: data.conversation, reserve: keepHold(stretch), at: Date.parse(data.at), call: data.call });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** At a reopen, after pi-browser's reconcile: every session its custody still tracks (each row of its inventory: kept,
|
|
74
|
+
* unreached, still releasing, lost) is held from here as if opened in this process, at a stretch beside what it ran
|
|
75
|
+
* since its last charge, the time the process was down included; that is already spent at the provider, so it is
|
|
76
|
+
* held, never refused. Its final charge, or its leaving the inventory, lets it go. One billed in full is not held. */
|
|
77
|
+
async function reopened(harness, docs, context) {
|
|
78
|
+
if (rate === 0)
|
|
79
|
+
return;
|
|
80
|
+
const rows = Object.values((await harness.snapshot(docs.Inventory, context))?.rows ?? {});
|
|
81
|
+
for (const row of rows.filter((r) => !sessions.has(r.tag))) {
|
|
82
|
+
const record = (await harness.snapshot(docs.Sessions, row.conversationId, context))?.sessions?.find((s) => s.tag === row.tag);
|
|
83
|
+
const at = Date.parse(record?.spent.chargedThrough ?? "");
|
|
84
|
+
// Billed in full already (its release's charge landed since reconcile): nothing is left to hold, nor to drop it.
|
|
85
|
+
if (!Number.isFinite(at) || record?.spent.final)
|
|
86
|
+
continue;
|
|
87
|
+
// Its reserve carries the down time, so its calls count what it runs from here (`at` now), not the down time again.
|
|
88
|
+
const now = Date.now();
|
|
89
|
+
sessions.set(row.tag, { cid: row.conversationId, reserve: keepHold(stretch + usdOf(Math.max(0, now - at) / 1000)), at: now, call: null });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** The open-session inventory as committed: a session it no longer holds lets go of its reserve (released, billed or
|
|
93
|
+
* not); one whose create's answer was lost, left to a release after the create deadline (releasing, no id), is held
|
|
94
|
+
* for that deadline and a stretch, out of its call's hold (two stretches, never less), until its release is billed or
|
|
95
|
+
* ends it. */
|
|
96
|
+
function tracked(rows) {
|
|
97
|
+
for (const [tag, open] of sessions)
|
|
98
|
+
if (!Object.hasOwn(rows, tag))
|
|
99
|
+
(open.reserve.drop(), sessions.delete(tag));
|
|
100
|
+
for (const row of Object.values(rows)) {
|
|
101
|
+
if (rate === 0 || row.state !== "releasing" || row.resourceId !== null || sessions.has(row.tag))
|
|
102
|
+
continue;
|
|
103
|
+
const usd = usdOf(CREATE_DEADLINE_S + stretchS);
|
|
104
|
+
take([...calls.values()].find((c) => c.cid === row.conversationId)?.hold, usd);
|
|
105
|
+
sessions.set(row.tag, { cid: row.conversationId, reserve: keepHold(usd), at: Date.now(), call: null });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Applies each browser charge `harness` commits, and each change of pi-browser's inventory (the document of kind
|
|
109
|
+
* `inventory`), once the commit is in: the charges first, so a release billed and ended in one commit is billed from
|
|
110
|
+
* its reserve before it goes. */
|
|
111
|
+
function watch(harness, inventory = "browser.inventory") {
|
|
112
|
+
harness.subscribeCommits((publication) => {
|
|
113
|
+
for (const change of publication.changes) {
|
|
114
|
+
const data = change.type === "entry" && change.value.kind === TOOL_COST ? change.value.data : undefined;
|
|
115
|
+
if (data?.tool === "browser" && typeof data.tag === "string")
|
|
116
|
+
booked(data);
|
|
117
|
+
}
|
|
118
|
+
for (const change of publication.changes) {
|
|
119
|
+
if (change.type === "document" && change.record.kind === inventory && change.value)
|
|
120
|
+
tracked((change.value.rows) ?? {});
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
/** `tool` held under the run's cap before each call. */
|
|
125
|
+
function capped(tool) {
|
|
126
|
+
return {
|
|
127
|
+
...tool,
|
|
128
|
+
execute: async (args, api, context) => {
|
|
129
|
+
const cap = runCap();
|
|
130
|
+
if (cap !== undefined && rate === null)
|
|
131
|
+
return refuse(`${SPEND_CAP_REACHED}: This browser call was not sent. ${provider}'s session time has no price here (${priceEnvOf(provider)} gives one), so the run's cap of $${cap} cannot be kept: the run is out of budget.`, api, context);
|
|
132
|
+
const now = Date.now();
|
|
133
|
+
const ranS = [...sessions.values()].filter((s) => s.cid === api.conversationId).reduce((sum, s) => sum + Math.max(0, now - s.at) / 1000, 0);
|
|
134
|
+
// Up to the millionth of a dollar, so the cap's words name a figure never below the hold.
|
|
135
|
+
const usd = Math.ceil(Math.round((usdOf(ranS) + 2 * stretch) * 1e12) / 1e6) / 1e6;
|
|
136
|
+
const basis = `${provider}'s session time at $${rate} an hour: the ${Math.round(ranS)} s its session ran since its last charge, and twice the next stretch of ${stretchS} s (its ${price.minimumS} s minimum, the ${idleS} s idle window and ${RELEASE_ALLOWANCE_S} s for its release)`;
|
|
137
|
+
const paid = await paidCall("this browser call", async () => keepHold(usd), () => undefined, { usd, basis });
|
|
138
|
+
if ("refused" in paid)
|
|
139
|
+
return refuse(paid.refused, api, context);
|
|
140
|
+
const hold = paid.result;
|
|
141
|
+
calls.set(api.callId, { cid: api.conversationId, hold });
|
|
142
|
+
try {
|
|
143
|
+
return await tool.execute(args, api, context);
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
calls.delete(api.callId);
|
|
147
|
+
hold.drop();
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** The cap's refusal as the call's error, and the conversation's session let go, so it runs no longer. */
|
|
153
|
+
async function refuse(why, api, context) {
|
|
154
|
+
await release({ id: api.conversationId, commit: api.commit.bind(api) }, context).catch(() => undefined);
|
|
155
|
+
return forModel(JSON.stringify({ error: why }), { isError: true });
|
|
156
|
+
}
|
|
157
|
+
return { onCharge, watch, reopened, capped, stretch };
|
|
158
|
+
}
|
package/dist/cap.d.ts
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
|
+
import { type Ended } from "@parcha/agentrun-kernel";
|
|
1
2
|
import { type EntryLike } from "@parcha/pi-durable-agent/timeline";
|
|
2
3
|
import type { Api, AssistantMessage, Context, Model, Models } from "@earendil-works/pi-ai";
|
|
3
4
|
/** A run's cap in USD, passed to its process. */
|
|
4
5
|
export declare const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
|
|
5
6
|
/** How a request the cap refused begins its error, which the server ends the run with. */
|
|
6
7
|
export declare const SPEND_CAP_REACHED = "spend_cap_reached";
|
|
8
|
+
/** How near two dollar figures are the same figure: a sum a float puts a hair past the cap (0.0028 + 0.3072 is
|
|
9
|
+
* 0.31000000000000005) is the cap, and fits it. A raise must be above a run's cap by more (runs.ts). */
|
|
10
|
+
export declare const CAP_TOLERANCE = 1e-9;
|
|
11
|
+
/** 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
|
|
12
|
+
* 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
|
|
13
|
+
* is the other question: how near two caps are the same cap. */
|
|
14
|
+
export declare const FIT_TOLERANCE = 1e-12;
|
|
7
15
|
/** 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
|
|
8
16
|
* symbol, so no provider ever sends it. */
|
|
9
17
|
export declare const HELD_USD: unique symbol;
|
|
@@ -37,6 +45,10 @@ export declare const STOPPED_USD: unique symbol;
|
|
|
37
45
|
export declare function streamedBytes(message: {
|
|
38
46
|
content?: unknown;
|
|
39
47
|
} | undefined): number;
|
|
48
|
+
/** What of a model answer's reasoning streamed, in bytes (streamedBytes' unit): its thinking blocks. */
|
|
49
|
+
export declare function reasoningBytes(message: {
|
|
50
|
+
content?: unknown;
|
|
51
|
+
} | undefined): number;
|
|
40
52
|
/** A request's figure if it is stopped before its end, given the answer it had streamed. */
|
|
41
53
|
export type Stopped = (message: {
|
|
42
54
|
content?: unknown;
|
|
@@ -44,9 +56,44 @@ export type Stopped = (message: {
|
|
|
44
56
|
/** What a request stopped before its end counts at: its input and `streamed` tokens plus STOP_ALLOWANCE_TOKENS of output,
|
|
45
57
|
* at most the output it was sent with (`limit`), at `cost`'s price; never more than `worst`, what it was held at. */
|
|
46
58
|
export declare const stoppedFigure: (cost: (output: number) => number, limit: number, worst: number, streamed: number) => number;
|
|
59
|
+
/** What a stopped request counts at, having streamed `streamed` tokens: those and STOP_ALLOWANCE_TOKENS of output, at
|
|
60
|
+
* most the output it was sent with (`limit`), at `cost`'s price; bookRequest keeps it within the hold. */
|
|
61
|
+
export declare const stoppedPriceOf: (cost: (output: number) => number, limit: number) => (streamed: number) => number;
|
|
62
|
+
/** The option a request's attempts ride on to its marks (request-start.ts): each HTTP attempt pi-ai made for it, as the
|
|
63
|
+
* fetch the cap gave it saw them. A symbol, so no provider ever sends it. */
|
|
64
|
+
export declare const ATTEMPTS: unique symbol;
|
|
65
|
+
/** One attempt of a request: the status it was answered with, or the code its fetch was refused with, `aborted` when the
|
|
66
|
+
* request's own signal had fired by then (the run stopped it: no attempt lost to the provider). */
|
|
67
|
+
export type Attempt = {
|
|
68
|
+
status: number;
|
|
69
|
+
} | {
|
|
70
|
+
code: string | undefined;
|
|
71
|
+
aborted?: true;
|
|
72
|
+
};
|
|
73
|
+
/** The APIs whose requests the cap cannot watch through a fetch, each with why: it gives them no recording fetch, and
|
|
74
|
+
* a request on one that fails before any event books its hold (piEnded). The one table both read. */
|
|
75
|
+
export declare const UNWATCHED_APIS: Readonly<Record<string, string>>;
|
|
76
|
+
/** A fetch that does what `inner` does (globalThis.fetch by default) and records each attempt in `attempts`. An attempt
|
|
77
|
+
* is `aborted` only when the request's own signal (`stop`, the run's) had fired: the SDKs hand fetch a signal of their
|
|
78
|
+
* own, which they also abort on their own timeout, and an attempt that timed out left, so it is lost, never a stop. */
|
|
79
|
+
export declare function recordingFetch(attempts: Attempt[], inner?: typeof fetch, stop?: AbortSignal): typeof fetch;
|
|
80
|
+
/** Whether one attempt was lost: refused after it could have left (any code but a connect one), a gateway's timeout, or
|
|
81
|
+
* an answer that was not the request's last attempt (pi-ai tried again after it). That last reading assumes every fetch
|
|
82
|
+
* through the recorder is a model attempt. pi-ai's Anthropic workload identity federation (anthropic-messages.js,
|
|
83
|
+
* getAnthropicFederation) exchanges its token through the same fetch, so under it "a 2xx that was not the last" would
|
|
84
|
+
* read every answer as lost. It arms only when no API key or auth header resolves, and serve always gives pi-ai an API
|
|
85
|
+
* key, so it never arms here. */
|
|
86
|
+
export declare const attemptLost: (a: Attempt, last: boolean) => boolean;
|
|
87
|
+
/** Whether any attempt of a request was lost (attemptLost), its last counted as the last; one the run's own stop cut is
|
|
88
|
+
* none. A request lost so counts at its hold however it then ended: answered, failed or stopped. */
|
|
89
|
+
export declare const anyAttemptLost: (attempts: readonly Attempt[] | undefined) => boolean;
|
|
90
|
+
export declare function piEnded(message: Pick<AssistantMessage, "stopReason" | "usage" | "api">, began: boolean, attempts: readonly Attempt[] | undefined): Ended;
|
|
47
91
|
/** How pi's error for a request whose start mark could not be written begins (request-start.ts builds it from this): the
|
|
48
92
|
* request never left, so the entry answers none, and spentIn leaves it out by this. */
|
|
49
93
|
export declare const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
|
|
94
|
+
/** pi's error for a request that left and whose end mark the store refused (request-start.ts): its cost is not recorded
|
|
95
|
+
* as booked, so it stays open, read at its start mark's hold, never closed by this entry at its own usage. */
|
|
96
|
+
export declare const END_NOT_WRITTEN = "the model request's end could not be recorded";
|
|
50
97
|
/** The input a request carrying claude-agent's native web search may read in beyond its body, added to its input bound
|
|
51
98
|
* by its adapter (adapters.ts hands it over): Claude's CLI asks for at most 8 searches a request (max_uses 8), and each
|
|
52
99
|
* search's results are billed as input, about 25,000 tokens a search as a working estimate. */
|
|
@@ -76,15 +123,36 @@ export declare const CAP_REFUSAL_PREFIX: RegExp;
|
|
|
76
123
|
* end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the figure its start mark
|
|
77
124
|
* holds (openFigures), each the worst case the cap held for it; without that figure either stays cut, at an unknown
|
|
78
125
|
* 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
|
|
79
|
-
* this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0.
|
|
80
|
-
|
|
126
|
+
* this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. `sides`: only the
|
|
127
|
+
* run's side requests (each marked with a label: a learned workflow's, a hosted search's), what a run on another
|
|
128
|
+
* harness spent beside its harness's own requests and its paid tools, which that harness's booking does not hold. */
|
|
129
|
+
export declare function spentIn(storeFile: string, { sides }?: {
|
|
130
|
+
sides?: boolean;
|
|
131
|
+
}): number | null;
|
|
81
132
|
/** /usage's meters for a run that ended, from its store: `tools`, each TOOL_COST's `usd`, unknown (null) when one is,
|
|
82
133
|
* or when a call was cut (marked, never settled: what it charged no one knows); and `tokens`, the rest of its root
|
|
83
|
-
* conversation as its settled timeline prices it
|
|
84
|
-
*
|
|
85
|
-
|
|
134
|
+
* conversation as its settled timeline prices it; `browser`, the part of `tools` that is browser session time
|
|
135
|
+
* (browser-cost.ts), with its seconds; and `others`, the rest of `tools`, each unknown (null) apart. A mark is never a charge here (the cap's alone). Never for a live run: its process
|
|
136
|
+
* holds the store exclusively. */
|
|
137
|
+
export type Meters = {
|
|
86
138
|
tools: number | null;
|
|
87
139
|
tokens: number | null;
|
|
140
|
+
browser: {
|
|
141
|
+
usd: number | null;
|
|
142
|
+
seconds: number;
|
|
143
|
+
};
|
|
144
|
+
others: number | null;
|
|
145
|
+
};
|
|
146
|
+
export declare function metersIn(storeFile: string): Meters;
|
|
147
|
+
/** metersIn's meters, and beside them each meter's known dollars: its settled charges' figures, whether or not another of
|
|
148
|
+
* its charges is unknown (a hold, a call cut or never settled, is no charge here: it adds nothing). What a run of
|
|
149
|
+
* unknown cost is known to have spent on each (server.ts /usage). */
|
|
150
|
+
export declare function meterFiguresIn(storeFile: string): Meters & {
|
|
151
|
+
known: {
|
|
152
|
+
tokens: number;
|
|
153
|
+
browser: number;
|
|
154
|
+
others: number;
|
|
155
|
+
};
|
|
88
156
|
};
|
|
89
157
|
/** What the paid tools of `entries` (TOOL_STARTED and TOOL_COST) spent, as the cap counts it: each charge, and a call
|
|
90
158
|
* settled at a charge it did not say, or a crash cut (marked, never settled), at its held figure, as spentIn counts it;
|
|
@@ -99,25 +167,45 @@ export declare function holdsInFlight(): {
|
|
|
99
167
|
ended: (turn: number) => undefined;
|
|
100
168
|
total: () => number;
|
|
101
169
|
};
|
|
102
|
-
/** The run's spend as its process counts it, for a paid tool: what it has spent (`spent
|
|
103
|
-
*
|
|
104
|
-
* and
|
|
170
|
+
/** The run's spend as its process counts it, for a paid tool: what it has spent (`spent`; null when unknown), what its
|
|
171
|
+
* model requests in flight are held at, at their worst case (`held`, read once `spent` is in; absent: none apart from
|
|
172
|
+
* `spent`), and the charge a call adds (`add`). Set by the run's cap, on pi (capModels) and on another harness
|
|
173
|
+
* (harness-app.ts); none without a cap. A run is one process, so one is set per process. `now`: the whole figure read at
|
|
174
|
+
* once, held requests included, with no wait for a cost still coming in; another harness sets it, for the run's own
|
|
175
|
+
* model requests beside the harness's (capModels' `joined`). */
|
|
105
176
|
export type RunSpend = {
|
|
106
177
|
cap: number;
|
|
107
178
|
spent(): number | null | Promise<number | null>;
|
|
179
|
+
held?(): number;
|
|
108
180
|
add(usd: number | null): void;
|
|
181
|
+
now?(): number | null;
|
|
109
182
|
};
|
|
110
183
|
export declare const useSpend: (spend: RunSpend | undefined) => void;
|
|
111
184
|
/** What the paid calls under way are held at, together (0 when none is): the one figure every check of the run's cap
|
|
112
|
-
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall).
|
|
185
|
+
* adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). On another
|
|
186
|
+
* harness the run's own model requests in flight (a learned workflow's, a hosted search's) are held here too, so the
|
|
187
|
+
* harness's check sees them. */
|
|
113
188
|
export declare const paidHolds: () => number;
|
|
114
|
-
/**
|
|
115
|
-
*
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
189
|
+
/** A paid hold that outlives the paidCall that took it (a browser session's, browser-cost.ts), counted in paidHolds as a
|
|
190
|
+
* call's is until `drop`: its figure is `usd`, which its owner moves as charges use it. */
|
|
191
|
+
export declare const keepHold: (usd: number) => {
|
|
192
|
+
usd: number;
|
|
193
|
+
drop(): void;
|
|
194
|
+
};
|
|
195
|
+
/** A charge booked outside any paidCall (a browser session's, booked in the commit that bills it) joins what the run's
|
|
196
|
+
* process counts as spent, as a paid call's does; with no cap, nothing counts it. */
|
|
197
|
+
export declare const addSpend: (usd: number | null) => void;
|
|
198
|
+
/** The run's cap, when it has one. */
|
|
199
|
+
export declare const runCap: () => number | undefined;
|
|
200
|
+
/** What sidesSpent says: the harness's check adds it to what its booking says the run spent (harness-app.ts). */
|
|
201
|
+
export declare const sideSpend: () => number | null;
|
|
202
|
+
/** The paid call's refusal the next model request of the run whose spend is `owner` is refused with, once: undefined
|
|
203
|
+
* 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
|
|
204
|
+
* others), never a guard a caller builds apart. */
|
|
205
|
+
export declare function takePaidRefusal(owner: RunSpend | undefined): {
|
|
206
|
+
words: string;
|
|
207
|
+
figures: RefusalFigures;
|
|
208
|
+
} | undefined;
|
|
121
209
|
export declare function paidCall<T>(name: string, call: () => Promise<T>, charge: (result: T) => number | null | undefined, hold: {
|
|
122
210
|
usd: number;
|
|
123
211
|
basis: string;
|
|
@@ -143,11 +231,25 @@ export declare function money(usd: number): string;
|
|
|
143
231
|
* which pi-ai's retry (isRetryableAssistantError, which reads only an error's text) takes as final whatever digits the
|
|
144
232
|
* words after it hold. The words after it are the ones a person reads. */
|
|
145
233
|
export declare const CAP_REFUSAL_CODE = "spend_cap_reached (out of budget): ";
|
|
234
|
+
/** A refusal for room's figures, beside its words: what the cap counted as taken (spent, and held for requests still
|
|
235
|
+
* answering) and the least the refused request needs. Kept on the refusal's own start mark (`spentUsd`, `needsUsd`), so a
|
|
236
|
+
* run paused at its cap says them (runs.ts pending), and its cap's raise is checked against them. */
|
|
237
|
+
export type RefusalFigures = {
|
|
238
|
+
spentUsd: number;
|
|
239
|
+
needsUsd: number;
|
|
240
|
+
};
|
|
241
|
+
/** The words of a refusal for room (CAP_REFUSAL_CODE: what is left of the cap cannot buy the request's least), which a
|
|
242
|
+
* higher cap would send; undefined for any other text, a refusal no cap could fix included (an unknown spend, no price,
|
|
243
|
+
* no output ceiling, an input not measured: the bare `spend_cap_reached: ` code). The one reader of that difference. */
|
|
244
|
+
export declare const roomRefusal: (text: string | undefined) => string | undefined;
|
|
146
245
|
/** A model's name as the words say it: the catalog's, without a vendor's prefix ("Anthropic: Claude Sonnet 5.5" reads
|
|
147
246
|
* "Claude Sonnet 5.5"), else its id. */
|
|
148
247
|
export declare const nameOf: (model: Pick<Model<Api>, "name" | "id">) => string;
|
|
149
248
|
/** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
|
|
150
249
|
export declare const leastMoney: (usd: number) => string;
|
|
250
|
+
/** The cap to raise to for a request past `cap` that needs `total` in all: a cent at least, and above the cap, never
|
|
251
|
+
* the cap itself, so a raise to it is one PATCH /runs/{id} takes. */
|
|
252
|
+
export declare const raiseTo: (cap: number, total: number) => string;
|
|
151
253
|
/** The least output a pi request may be limited to and still answer: the answer's 1,024 tokens, and when it thinks,
|
|
152
254
|
* the least budget on an API whose thinking takes one (squeezed to it), else its thinking level's budget, since its
|
|
153
255
|
* reasoning then shares the limit. */
|
|
@@ -157,9 +259,9 @@ export declare function leastOutput(model: Pick<Model<Api>, "api" | "reasoning">
|
|
|
157
259
|
* admitted with, and the model proxy each request's input bound (`inputTokensMax`, inputBound of its body; undefined
|
|
158
260
|
* when the body could not be measured), the output it asks for, and the least it may be limited to. */
|
|
159
261
|
export interface CapGuard {
|
|
160
|
-
beforeRequest(request: GuardRequest): undefined | {
|
|
262
|
+
beforeRequest(request: GuardRequest): undefined | ({
|
|
161
263
|
refuse: string;
|
|
162
|
-
} | {
|
|
264
|
+
} & Partial<RefusalFigures>) | {
|
|
163
265
|
outputTokensMax: number;
|
|
164
266
|
};
|
|
165
267
|
/** The worst case a request this guard admitted is held at (its input bound, and the output limit it was admitted with
|
|
@@ -216,9 +318,15 @@ export declare function requestParts(overhead?: (model: Model<Api>, context: Con
|
|
|
216
318
|
* (spentIn), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
|
|
217
319
|
* `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. Each
|
|
218
320
|
* request sent carries its worst case (HELD_USD) to the marks below, and one stopped before its end counts at it.
|
|
219
|
-
* `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry.
|
|
220
|
-
|
|
321
|
+
* `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry.
|
|
322
|
+
* `joined`: the run is on another harness, whose spend is the run's one total, and these are the run's own requests
|
|
323
|
+
* beside the harness's (a learned workflow's, a hosted search's). Each is judged against that total as the harness
|
|
324
|
+
* sets it when its run opens (RunSpend.now: its booked requests, its paid tools' charges and its requests in flight,
|
|
325
|
+
* with sideSpend), unknown until then; held where the harness's check sees it (paidHolds); and its cost added to
|
|
326
|
+
* sideSpend, which starts at `spent` (what these cost in earlier processes: spentIn's `sides`). */
|
|
327
|
+
export declare function capModels<M extends Models>(models: M, cap: number, spent: number | null, { unpriced, overhead, refused: markRefused, joined }?: {
|
|
221
328
|
unpriced?: ReadonlySet<string>;
|
|
222
329
|
overhead?: (model: Model<Api>, context: Context) => number | undefined;
|
|
223
|
-
refused?: () => Promise<void>;
|
|
330
|
+
refused?: (figures?: RefusalFigures) => Promise<void>;
|
|
331
|
+
joined?: boolean;
|
|
224
332
|
}): Promise<M>;
|